import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/liveRecordings.test.ts // // The live recordings listing (controller/liveRecordings.ts) over a temp // corpus: rows written through lib/liveRecordings-server.ts, records and // staging files made by hand, the job registry a stub. const ROOT = await mkdtemp(path.join(tmpdir(), "live-recordings-")); 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 { listLiveRecordings, acknowledgeLiveRecording, countLiveRecordingsNeedingAttention } = await import("./liveRecordings"); const { upsertLiveRecordingRow, loadLiveRecordingRows } = await import("../lib/liveRecordings-server"); const { liveRecordingSidecar } = await import("../lib/mediaImport-server"); const paths = getPaths(); test.after(() => rm(ROOT, { recursive: true, force: true })); const SLUG = "synth-live"; await mkdir(path.join(CORPUS, "channels", SLUG, "data"), { recursive: true }); await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: "Synth" })); const store = path.join(paths.savedVideosDir, SLUG); await mkdir(store, { recursive: true }); const NOW = new Date("2026-11-20T12:00:00.000Z"); const minutesAgo = (m: number) => new Date(NOW.getTime() - m * 60_000); async function recording(id: string, stem: string, opts: { jobId?: string; startedAt?: Date } = {}) { const startedAt = (opts.startedAt ?? minutesAgo(60)).toISOString(); const rec = { status: "recording" as const, url: `https://www.youtube.com/watch?v=${id}`, platform: "youtube", fromStart: true, startedAt, parts: [{ method: "ytdlp" as const, url: "u", fromStart: true, startedAt, stem }], attempts: 1, mustKeep: true, streamStartedAt: minutesAgo(120).toISOString(), ...(opts.jobId ? { jobId: opts.jobId } : {}), }; const dir = path.join(CORPUS, "channels", SLUG, "data", id); await mkdir(dir, { recursive: true }); await liveRecordingSidecar.write(dir, rec); await upsertLiveRecordingRow(paths, SLUG, { ...rec, id, mustKeep: true, attempts: 1 }); return rec; } test("a recording whose job runs and whose files grow: bytes summed, not stalled, elapsed from the stream's start", async () => { const stem = ".exmplgrow01.live-2026-11-20T11-00-00-000Z.ytdlp"; await recording("exmplgrow01", stem, { jobId: "job-grow" }); await writeFile(path.join(store, `${stem}.f247.webm`), Buffer.alloc(3000)); await writeFile(path.join(store, `${stem}.f140.m4a`), Buffer.alloc(1000)); for (const f of [`${stem}.f247.webm`, `${stem}.f140.m4a`]) await utimes(path.join(store, f), minutesAgo(1), minutesAgo(1)); const { rows } = await listLiveRecordings(paths, { slug: SLUG, id: "exmplgrow01", now: NOW, jobs: () => [{ id: "job-grow", kind: "record-live", status: "running", channelSlug: SLUG, videoId: "exmplgrow01" }], }); const r = rows[0]!; assert.equal(r.status, "recording"); assert.equal(r.bytes, 4000); assert.equal(r.stalled, false); assert.equal(r.lastGrowthAt, minutesAgo(1).toISOString()); assert.equal(r.streamElapsedSeconds, 7200); assert.equal(r.needsAttention, false); assert.equal(r.job?.status, "running"); assert.equal(r.check, "pnpm ops get live-recordings synth-live/exmplgrow01"); }); test("stalled: recording, and nothing has grown for stallMinutes", async () => { const stem = ".exmplstal01.live-2026-11-20T11-00-00-000Z.ytdlp"; await recording("exmplstal01", stem, { jobId: "job-stall" }); await writeFile(path.join(store, `${stem}.ts`), Buffer.alloc(500)); await utimes(path.join(store, `${stem}.ts`), minutesAgo(25), minutesAgo(25)); const jobs = () => [{ id: "job-stall", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: "exmplstal01" }]; const r = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplstal01", now: NOW, stallMinutes: 10, jobs })).rows[0]!; assert.equal(r.stalled, true); assert.match(r.reason, /NOT growing/); const later = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplstal01", now: NOW, stallMinutes: 30, jobs })).rows[0]!; assert.equal(later.stalled, false); }); test("interrupted: the record says recording and no record-live job runs it — it needs a person until acknowledged", async () => { await recording("exmplintr01", ".exmplintr01.live-2026-11-20T11-00-00-000Z.ytdlp", { jobId: "job-gone" }); const r = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplintr01", now: NOW, jobs: () => [] })).rows[0]!; assert.equal(r.status, "interrupted"); assert.equal(r.needsAttention, true); assert.equal(r.stalled, false, "stalled is for a recording that runs"); assert.ok((await countLiveRecordingsNeedingAttention(paths)) >= 1); const ack = await acknowledgeLiveRecording(paths, { slug: SLUG, id: "exmplintr01", by: "test" }); assert.deepEqual(ack, { ok: true, acknowledged: 1 }); const after = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplintr01", now: NOW, jobs: () => [] })).rows[0]!; assert.equal(after.needsAttention, false); assert.equal((await acknowledgeLiveRecording(paths, { slug: SLUG, id: "exmplintr01" })).ok, false, "nothing left to acknowledge"); }); test("the default listing: recording, needing a person, or of the last week; --all is everything", async () => { const old = { status: "landed" as const, url: "u", platform: "youtube", fromStart: true, startedAt: "2026-10-01T00:00:00.000Z", endedAt: "2026-10-01T03:00:00.000Z", parts: [] }; await upsertLiveRecordingRow(paths, SLUG, { ...old, id: "exmplold001", attempts: 1, mustKeep: false }); await upsertLiveRecordingRow(paths, SLUG, { ...old, status: "failed", id: "exmplold002", attempts: 6, mustKeep: true, error: "nothing was recorded" }); const ids = (await listLiveRecordings(paths, { slug: SLUG, now: NOW, jobs: () => [] })).rows.map((r) => r.id); assert.ok(!ids.includes("exmplold001"), "an old landed recording is not in the default view"); assert.ok(ids.includes("exmplold002"), "an old failure that nobody acknowledged is"); const all = (await listLiveRecordings(paths, { slug: SLUG, now: NOW, all: true, jobs: () => [] })).rows.map((r) => r.id); assert.ok(all.includes("exmplold001")); assert.equal((await loadLiveRecordingRows(paths, SLUG)).length, all.length); }); test("record-live's reply names the command that answers for the recording", async () => { const { recordLiveCheckCommand } = await import("./recordLive"); assert.equal(recordLiveCheckCommand("demo-yt", { url: "https://www.youtube.com/watch?v=exampleid01" }), "pnpm ops get live-recordings demo-yt/exampleid01"); assert.equal(recordLiveCheckCommand("demo-yt", { id: "exampleid02" }), "pnpm ops get live-recordings demo-yt/exampleid02"); assert.equal(recordLiveCheckCommand("demo-kick", { url: "https://kick.com/somechannel" }), "pnpm ops get live-recordings demo-kick", "a Kick channel's VOD is found in the job"); }); test("1.8: an unparseable live-recordings.json is never overwritten — set aside under a timestamped name, a new file started, and the kept file needs a person", async () => { const slug = "synth-corrupt"; const dir = path.join(CORPUS, "channels", slug); await mkdir(path.join(dir, "data"), { recursive: true }); await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: "Corrupt" })); const garbage = '{"rows": [{"id": "exmplcorr01", "status": "failed", "startedAt": "2026-11-19T00:00:00.000Z"'; // truncated await writeFile(path.join(dir, "live-recordings.json"), garbage); // Read side: said, not moved. const before = await listLiveRecordings(paths, { slug, now: NOW, jobs: () => [] }); assert.equal(before.files.length, 1); assert.equal(before.files[0]!.state, "unreadable"); assert.equal(before.files[0]!.reason, "unparseable"); assert.ok(before.needsAttention >= 1); // A write: the file is renamed aside, byte for byte, and a new one begins. await upsertLiveRecordingRow(paths, slug, { id: "exmplcorr02", url: "u", platform: "youtube", startedAt: NOW.toISOString(), status: "failed", fromStart: true, attempts: 1, mustKeep: true, parts: [], }); const names = (await readdir(dir)).filter((n) => n.startsWith("live-recordings.json")); const aside = names.find((n) => /^live-recordings\.json\.corrupt-\d{4}-\d\d-\d\dT[\d-]+Z$/.test(n)); assert.ok(aside, names.join(", ")); assert.equal(await readFile(path.join(dir, aside!), "utf8"), garbage, "kept as it was"); const after = await listLiveRecordings(paths, { slug, now: NOW, jobs: () => [] }); assert.deepEqual(after.rows.map((r) => r.id), ["exmplcorr02"]); assert.equal(after.files.length, 1); assert.equal(after.files[0]!.state, "set-aside"); assert.equal(after.files[0]!.file, aside); assert.match(after.files[0]!.message, new RegExp(aside!.replace(/[.]/g, "\\."))); assert.equal(after.needsAttention, 2, "the new failure and the kept file"); // A second write does not set the new (good) file aside. await upsertLiveRecordingRow(paths, slug, { id: "exmplcorr03", url: "u", platform: "youtube", startedAt: NOW.toISOString(), status: "landed", fromStart: true, attempts: 1, mustKeep: false, parts: [] }); assert.equal((await readdir(dir)).filter((n) => n.includes(".corrupt-")).length, 1); // Acknowledged: no longer counted; the file stays. assert.deepEqual(await acknowledgeLiveRecording(paths, { slug, file: aside!, by: "test" }), { ok: true, acknowledged: 1 }); const acked = await listLiveRecordings(paths, { slug, now: NOW, jobs: () => [] }); assert.equal(acked.files.length, 0); assert.equal(acked.needsAttention, 1); assert.ok((await readdir(dir)).includes(aside!)); }); test("2.2: a stalled recording is counted beside needsAttention, and each part says its own bytes while it records", async () => { const stem = ".exmplstal02.live-2026-11-20T11-00-00-000Z.ytdlp"; await recording("exmplstal02", stem, { jobId: "job-stall2" }); await writeFile(path.join(store, `${stem}.f247.webm`), Buffer.alloc(700)); await utimes(path.join(store, `${stem}.f247.webm`), minutesAgo(40), minutesAgo(40)); const jobs = () => [{ id: "job-stall2", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: "exmplstal02" }]; const l = await listLiveRecordings(paths, { slug: SLUG, id: "exmplstal02", now: NOW, stallMinutes: 10, jobs }); assert.equal(l.stalled, 1); assert.equal(l.rows[0]!.needsAttention, false, "stalled is said on its own, not acknowledged"); assert.equal(l.rows[0]!.parts[0]!.bytes, 700); assert.equal(l.rows[0]!.parts[0]!.lastGrowthAt, minutesAgo(40).toISOString()); }); test("2.5: a row that names its job is recording only while THAT job runs (a newer run of the id is another row)", async () => { await recording("exmplstale1", ".exmplstale1.live-2026-11-20T10-00-00-000Z.ytdlp", { jobId: "job-old" }); const jobs = () => [{ id: "job-new", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: "exmplstale1" }]; const r = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplstale1", now: NOW, jobs })).rows[0]!; assert.equal(r.status, "interrupted"); }); test("needsAttention: interrupted always, a cancel only when must-keep, kept parts even when superseded", async () => { const { rowNeedsAttention } = await import("../lib/liveRecordings-server"); const base = { fallback: undefined, acknowledgedAt: undefined, supersededBy: undefined } as const; assert.equal(rowNeedsAttention({ ...base, status: "interrupted", mustKeep: false }), true); assert.equal(rowNeedsAttention({ ...base, status: "cancelled", mustKeep: true }), true); assert.equal(rowNeedsAttention({ ...base, status: "cancelled", mustKeep: false }), false); const kept = [{ stem: "s", files: [{ name: "s.mp4", bytes: 9 }], bytes: 9, seconds: 1, fromStart: false, run: "this" as const, why: "w" }]; assert.equal(rowNeedsAttention({ ...base, status: "landed", supersededBy: "job-x", keptParts: kept }), true); assert.equal(rowNeedsAttention({ ...base, status: "landed", acknowledgedAt: "t", keptParts: kept }), false); assert.equal(rowNeedsAttention({ ...base, status: "landed", missingStream: "video" }), true); }); test("REVIEW 1.3 (live-guard-2): an interruption 'restarted' by the boot pass needs a person until the NEW run's part grows; a new run that failed or never began leaves it loud", async () => { const id = "exmplrest01"; const t0 = minutesAgo(90).toISOString(); await upsertLiveRecordingRow(paths, SLUG, { id, url: `https://www.youtube.com/watch?v=${id}`, platform: "youtube", startedAt: t0, endedAt: minutesAgo(31).toISOString(), status: "interrupted", stoppedBy: "shutdown", fromStart: true, attempts: 1, mustKeep: true, parts: [], restart: { at: minutesAgo(30).toISOString(), by: "boot", state: "restarted", jobId: "job-new" }, }); const old = async (jobs: () => { id: string; kind: string; status: "running"; channelSlug: string; videoId: string }[] = () => []) => (await listLiveRecordings(paths, { slug: SLUG, id, now: NOW, all: true, jobs })).rows.find((r) => r.startedAt === t0)!; // No new run at all. let r = await old(); assert.equal(r.needsAttention, true, "the restart has not recorded a byte"); assert.match(r.reason, /no new run|not recorded/i); // The new run records, and its part grows. const stem = `.${id}.live-2026-11-20T11-30-00-000Z.ytdlp`; const started = minutesAgo(29).toISOString(); await upsertLiveRecordingRow(paths, SLUG, { id, url: `https://www.youtube.com/watch?v=${id}`, platform: "youtube", startedAt: started, status: "recording", jobId: "job-new", fromStart: true, attempts: 1, mustKeep: true, resumeOf: t0, parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt: started, stem }], }); await writeFile(path.join(store, `${stem}.ts`), Buffer.alloc(2000)); await utimes(path.join(store, `${stem}.ts`), minutesAgo(1), minutesAgo(1)); const running = () => [{ id: "job-new", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: id }]; r = await old(running); assert.equal(r.needsAttention, false, "the new run records and grows"); // The new run failed: loud again, and says so. await upsertLiveRecordingRow(paths, SLUG, { id, url: `https://www.youtube.com/watch?v=${id}`, platform: "youtube", startedAt: started, endedAt: minutesAgo(5).toISOString(), status: "failed", error: "nothing was recorded", jobId: "job-new", fromStart: true, attempts: 6, mustKeep: true, resumeOf: t0, parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt: started, stem }], }); r = await old(); assert.equal(r.needsAttention, true); assert.match(r.reason, /failed/); });