import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { ChannelConfig } from "../lib/channelConfig"; import type { AttemptOutcome } from "../ytdlp/runOneYtdlp"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/chatBacklog.test.ts // // A CHANNEL'S STREAM CHATS AFTER ITS DOWNLOADS (2026-10-26): the backlog job // picks every held stream (by its metadata) whose chat is not here, fetches // them one at a time through a stub runner (no yt-dlp, no network), remembers // the streams that have none, and a second run asks for nothing it already // knows. The lane's trigger is pure. Temp corpus only. const ROOT = await mkdtemp(path.join(tmpdir(), "chat-backlog-")); 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 { effectiveSubLangs } = await import("../lib/channelConfig"); const { planChatBacklog, readChatBacklogState, runChatBacklog, CHAT_BACKLOG_FILENAME } = await import("./chatBacklog"); const { ChatBacklogLane, chatBacklogDue, CHAT_BACKLOG_RECHECK_MS } = await import("./laneChatBacklog"); const paths = getPaths(); test.after(() => rm(ROOT, { recursive: true, force: true })); const SLUG = "synth-pod"; const CONFIG = { handling: "youtube", url: "https://www.youtube.com/@synth", name: "Synth", chat: "later" } as ChannelConfig; function chatLine(sec: number, text: string): string { return JSON.stringify({ replayChatItemAction: { actions: [ { addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text }] }, authorName: { simpleText: "v" } } } } }, ], videoOffsetTimeMsec: String(sec * 1000), }, }); } const REPLAY = [chatLine(5, "first"), chatLine(9, "second")].join("\n") + "\n"; async function video(id: string, meta: Record, files: Record = {}): Promise { const dir = path.join(CORPUS, "channels", SLUG, "data", id); await mkdir(dir, { recursive: true }); await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG)); await writeFile( path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: `Episode ${id}`, webpage_url: `https://www.youtube.com/watch?v=${id}`, extractor_key: "Youtube", ...meta }), ); for (const [name, body] of Object.entries(files)) await writeFile(path.join(dir, name), body); } // The stub yt-dlp: a replay for the ids in `withChat`, nothing for the rest. function stub(withChat: Set) { const asked: string[] = []; const run = async (cwd: string, args: string[]): Promise => { const url = args[args.length - 1]; const id = new URL(url).searchParams.get("v") ?? url; asked.push(id); const i = args.findIndex((a) => a.startsWith("subtitle:")); if (withChat.has(id)) await writeFile(path.join(cwd, `${args[i].slice("subtitle:".length)}.live_chat.json`), REPLAY); return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; }; return { run, asked }; } await video("strm0000001", { live_status: "was_live", upload_date: "20251001" }); await video("strm0000002", { live_status: "was_live", upload_date: "20251020" }); await video("strm0000003", { was_live: true, upload_date: "20251010" }); await video("upld0000001", { live_status: "not_live", upload_date: "20251015" }); await video("strm0000004", { live_status: "post_live", upload_date: "20251005" }, { "transcript.live_chat.json": REPLAY }); test("effectiveSubLangs: the chat rides the download only when `chat` says so", () => { assert.equal(effectiveSubLangs({}), "en.*,live_chat"); assert.equal(effectiveSubLangs({ chat: "with-download", subLangs: "en,de,live_chat" }), "en,de,live_chat"); assert.equal(effectiveSubLangs({ chat: "later" }), "en.*"); assert.equal(effectiveSubLangs({ chat: "never", subLangs: "en.*, live_chat ,es" }), "en.*,es"); assert.equal(effectiveSubLangs({ chat: "later", subLangs: "all" }), "all,-live_chat"); assert.equal(effectiveSubLangs({ chat: "later", subLangs: "live_chat" }), "en.*"); }); test("the plan: held streams whose chat is not here, newest first; a raw replay is only normalized", async () => { const plan = await planChatBacklog(paths, SLUG, CONFIG); assert.deepEqual( plan.candidates.map((c) => [c.id, c.action]), [ ["strm0000002", "fetch"], ["strm0000003", "fetch"], ["strm0000004", "normalize"], ["strm0000001", "fetch"], ], ); assert.equal(plan.notStreams, 1); }); test("a run: one chat at a time, the gap between two, none remembered; a second run asks for nothing", async () => { const { run, asked } = stub(new Set(["strm0000002", "strm0000001"])); const slept: number[] = []; const landed: string[] = []; const lines: string[] = []; const result = await runChatBacklog({ paths, slug: SLUG, config: CONFIG, onLog: (l) => lines.push(l), signal: new AbortController().signal, run, gapMs: () => 7000, sleep: async (ms) => { slept.push(ms); }, onChat: (id) => landed.push(id), downloadedAtRun: 5, }); assert.deepEqual(asked, ["strm0000002", "strm0000003", "strm0000001"]); assert.deepEqual(slept, [7000, 7000], "a gap between two requests, none before the first"); assert.deepEqual(landed.sort(), ["strm0000001", "strm0000002", "strm0000004"]); assert.equal(result.fetched, 2); assert.equal(result.normalized, 1); assert.equal(result.none, 1); assert.equal(result.complete, true); const state = await readChatBacklogState(paths, SLUG); assert.equal(state.settled.strm0000003?.why, "no-chat"); assert.equal(state.lastRun?.downloadedAtRun, 5); assert.match(await readFile(path.join(CORPUS, "channels", SLUG, CHAT_BACKLOG_FILENAME), "utf8"), /"no-chat"/); const again = stub(new Set()); const second = await runChatBacklog({ paths, slug: SLUG, config: CONFIG, onLog: () => {}, signal: new AbortController().signal, run: again.run, gapMs: () => 0 }); assert.deepEqual(again.asked, []); assert.equal(second.remaining, 0); assert.equal(second.complete, true); }); test("a run stops at its limit and a drain, and says what is left", async () => { await video("strm0000010", { live_status: "was_live", upload_date: "20251101" }); await video("strm0000011", { live_status: "was_live", upload_date: "20251102" }); const { run, asked } = stub(new Set(["strm0000010", "strm0000011"])); const limited = await runChatBacklog({ paths, slug: SLUG, config: CONFIG, onLog: () => {}, signal: new AbortController().signal, run, gapMs: () => 0, limit: 1 }); assert.deepEqual(asked, ["strm0000011"]); assert.equal(limited.complete, false); assert.equal(limited.remaining, 1); assert.match(limited.stopped ?? "", /limit \(1\)/); const drain = new AbortController(); drain.abort(); const drained = await runChatBacklog({ paths, slug: SLUG, config: CONFIG, onLog: () => {}, signal: new AbortController().signal, drainSignal: drain.signal, run, gapMs: () => 0 }); assert.equal(drained.stopped, "drained"); assert.equal(drained.remaining, 1); }); test("the lane's trigger: due with no run, after new downloads, or after an unfinished run has rested", () => { const now = Date.parse("2026-10-26T12:00:00Z"); const run = (o: Partial<{ complete: boolean; endedAt: string; downloadedAtRun: number }>) => ({ version: 1 as const, settled: {}, lastRun: { startedAt: "2026-10-26T11:00:00Z", endedAt: o.endedAt ?? "2026-10-26T11:55:00Z", complete: o.complete ?? true, fetched: 0, normalized: 0, none: 0, failed: 0, remaining: 0, ...(o.downloadedAtRun !== undefined ? { downloadedAtRun: o.downloadedAtRun } : {}), }, }); assert.equal(chatBacklogDue({ version: 1, settled: {} }, 10, now), true); assert.equal(chatBacklogDue(run({ downloadedAtRun: 10 }), 10, now), false); assert.equal(chatBacklogDue(run({ downloadedAtRun: 10 }), 12, now), true); assert.equal(chatBacklogDue(run({ complete: false, downloadedAtRun: 10 }), 10, now), false, "rested 5 min of 15"); assert.equal( chatBacklogDue(run({ complete: false, downloadedAtRun: 10, endedAt: new Date(now - CHAT_BACKLOG_RECHECK_MS).toISOString() }), 10, now), true, ); }); test("the lane queues one backlog per idle `later` channel, at most once per recheck", async () => { let now = 1_000_000; const started: string[] = []; const lane = new ChatBacklogLane({ now: () => now, readState: async () => ({ version: 1, settled: {} }), downloadedOf: async () => 3, isActive: () => false, start: async (slug) => { started.push(slug); return { ok: true, jobId: `J-${slug}`, stream: new ReadableStream(), done: new Promise(() => {}) }; }, }); const later = { ...CONFIG, chat: "later" } as ChannelConfig; const channels = [ { slug: "a", config: later }, { slug: "b", config: later }, { slug: "c", config: { ...CONFIG, chat: undefined } as ChannelConfig }, { slug: "d", config: later }, ]; const lines: string[] = []; await lane.consider(channels, { idle: (s) => s !== "b", focus: { slugs: new Set(["a", "b", "c"]), holding: true }, onLog: (l) => lines.push(l) }); assert.deepEqual(started, ["a"], "b has downloads left, c fetches chat with its downloads, d is outside the focus"); assert.match(lines[0], /a has nothing left to download; queued its chat backlog \(job J-a/); await lane.consider(channels, { idle: () => true }); assert.deepEqual(started, ["a", "b", "d"], "a was considered moments ago"); now += CHAT_BACKLOG_RECHECK_MS; await lane.consider(channels, { idle: () => true }); assert.deepEqual(started, ["a", "b", "d", "a", "b", "d"]); });