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"; import type { ChannelConfig } from "../lib/channelConfig"; import type { AttemptOutcome } from "../ytdlp/runOneYtdlp"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchLiveChat.test.ts // // One video's chat replay (release 36, lane A). The yt-dlp runner is a stub // that records its argv and writes the JSON-lines replay where the // `subtitle:` template says — no yt-dlp, no network. Every case is a temp // corpus; the job cases run through the real registry over it. const ROOT = await mkdtemp(path.join(tmpdir(), "fetch-chat-")); 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 { CHAT_PLATFORMS, fetchLiveChat, liveChatPlan, noChatFetcherSentence, runFetchChatJob, } = await import("./fetchLiveChat"); const { liveChatOnlyArgs } = await import("../ytdlp/downloadOneManaged"); const paths = getPaths(); test.after(() => rm(ROOT, { recursive: true, force: true })); const SLUG = "synth-stream"; const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig; const NO_COOKIES = { cookies: undefined, mode: "when-required" } as const; function chatLine(sec: number, author: string, text: string): string { return JSON.stringify({ replayChatItemAction: { actions: [ { addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text }] }, authorName: { simpleText: author } }, }, }, }, ], videoOffsetTimeMsec: String(sec * 1000), }, }); } const REPLAY = [chatLine(12, "viewer1", "lol"), chatLine(14, "viewer2", "LMAO"), chatLine(30, "viewer3", "W")].join("\n") + "\n"; async function video(id: string, meta: 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: "Synth stream", ...meta })); return dir; } // The stub: records the argv, writes the replay under the subtitle template. function stubRunner(o: { writes?: string | null; exitCode?: number; stderr?: string } = {}) { const calls: { cwd: string; args: string[] }[] = []; const run = async (cwd: string, args: string[]): Promise => { calls.push({ cwd, args }); const i = args.findIndex((a) => a.startsWith("subtitle:")); if (o.writes !== null && (o.exitCode ?? 0) === 0) { const base = args[i + 0].slice("subtitle:".length); await writeFile(path.join(cwd, `${base}.live_chat.json`), o.writes ?? REPLAY); } return { exitCode: o.exitCode ?? 0, stderrTail: o.stderr ?? "", archiveLine: null, formatLine: null }; }; return { run, calls }; } const log = () => { const lines: string[] = []; return { lines, onLog: (s: string) => lines.push(s) }; }; test("the chat pass is the managed download's chat-only command line, paced", () => { const url = "https://www.youtube.com/watch?v=abc"; const args = liveChatOnlyArgs(CONFIG, undefined, url, 7); assert.deepEqual(args.slice(0, 2), ["--ignore-config", "--restrict-filenames"]); assert.ok(args.includes("--skip-download")); assert.deepEqual(args.slice(args.indexOf("--sub-langs"), args.indexOf("--sub-langs") + 2), ["--sub-langs", "live_chat"]); assert.ok(args.includes("--no-write-info-json"), "the metadata on disk is never rewritten"); assert.equal(args[args.indexOf("--sleep-requests") + 1], "7", "the platform's pace"); assert.deepEqual(args.slice(-2), ["--", url]); assert.ok(CHAT_PLATFORMS.has("youtube")); }); test("plan: YouTube fetches; another platform has no fetcher; a never-live video has no replay", async () => { await video("yt1", { webpage_url: "https://www.youtube.com/watch?v=yt1", was_live: true }); assert.deepEqual(await liveChatPlan(paths, SLUG, "yt1", CONFIG), { kind: "fetch", url: "https://www.youtube.com/watch?v=yt1", platform: "youtube", }); await video("tw1", { webpage_url: "https://www.twitch.tv/videos/123" }); const tw = await liveChatPlan(paths, SLUG, "tw1", CONFIG); assert.deepEqual(tw, { kind: "no-fetcher", platform: "twitch" }); assert.equal(noChatFetcherSentence("twitch"), "no chat fetcher for twitch: only YouTube's chat replay is fetched"); await video("nl1", { webpage_url: "https://www.youtube.com/watch?v=nl1", live_status: "not_live" }); assert.equal((await liveChatPlan(paths, SLUG, "nl1", CONFIG)).kind, "not-live"); assert.equal((await liveChatPlan(paths, SLUG, "nope", CONFIG)).kind, "refused"); assert.equal((await liveChatPlan(paths, SLUG, "../x", CONFIG)).kind, "refused"); }); test("a fetch writes the replay and its cues; a second plan says fresh", async () => { const dir = await video("yt2", { webpage_url: "https://www.youtube.com/watch?v=yt2", was_live: true }); const { run, calls } = stubRunner(); const l = log(); const r = await fetchLiveChat({ paths, slug: SLUG, videoId: "yt2", videoUrl: "https://www.youtube.com/watch?v=yt2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run, paceSeconds: 3, }); assert.equal(r.status, "fetched"); assert.equal(r.status === "fetched" && r.messages, 3); assert.equal(calls.length, 1); assert.equal(calls[0].cwd, path.join(CORPUS, "channels", SLUG)); const cues = JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")); assert.equal(cues.source, "live_chat"); assert.equal(cues.cues.length, 3); assert.equal(cues.cues[0].start, 12); assert.match(l.lines.join(""), /3 message\(s\) in live_chat\.cues\.json/); assert.equal((await liveChatPlan(paths, SLUG, "yt2", CONFIG)).kind, "fresh"); }); test("a pass that writes nothing is an answer, not a failure", async () => { const dir = await video("yt3", { webpage_url: "https://www.youtube.com/watch?v=yt3" }); const { run } = stubRunner({ writes: null }); const l = log(); const r = await fetchLiveChat({ paths, slug: SLUG, videoId: "yt3", videoUrl: "https://www.youtube.com/watch?v=yt3", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run, }); assert.deepEqual(r, { status: "none" }); assert.match(l.lines.join(""), /No chat replay for yt3/); assert.deepEqual((await readdir(dir)).sort(), ["metadata.info.json"]); }); test("a rate-limited pass records the cooldown and fails; an auth gate retries once with cookies", async () => { await video("yt4", { webpage_url: "https://www.youtube.com/watch?v=yt4" }); let backoffs = 0; const limited = stubRunner({ exitCode: 1, stderr: "ERROR: [youtube] yt4: HTTP Error 429: Too Many Requests" }); await assert.rejects( fetchLiveChat({ paths, slug: SLUG, videoId: "yt4", videoUrl: "https://www.youtube.com/watch?v=yt4", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: new AbortController().signal, run: limited.run, onPlatformBackoff: () => void backoffs++, }), /rate-limited the chat fetch/, ); assert.equal(backoffs, 1); const calls: string[][] = []; const authThenOk = async (cwd: string, args: string[]): Promise => { calls.push(args); if (calls.length === 1) { return { exitCode: 1, stderrTail: "ERROR: [youtube] yt4: Sign in to confirm your age", archiveLine: null, formatLine: null }; } const base = args[args.findIndex((a) => a.startsWith("subtitle:"))].slice("subtitle:".length); await writeFile(path.join(cwd, `${base}.live_chat.json`), REPLAY); return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; }; const r = await fetchLiveChat({ paths, slug: SLUG, videoId: "yt4", videoUrl: "https://www.youtube.com/watch?v=yt4", channelConfig: CONFIG, cookiePolicy: { cookies: "firefox", mode: "when-required" }, onLog: () => {}, signal: new AbortController().signal, run: authThenOk, }); assert.equal(r.status, "fetched"); assert.equal(calls.length, 2); assert.ok(!calls[0].includes("--cookies-from-browser")); assert.ok(calls[1].includes("--cookies-from-browser")); }); test("a members-only refusal is recorded as the video's availability, and the job still fails", async () => { const dir = await video("ym1", { webpage_url: "https://www.youtube.com/watch?v=ym1", was_live: true }); // What the backfill wrote while the stream was live and public. await writeFile( path.join(dir, "availability.json"), JSON.stringify({ checkedAt: "2026-01-02T03:00:00.000Z", checkedBy: "backfill", availability: "public", history: [{ availability: "public", observedAt: "2026-01-02T03:00:00.000Z", source: "backfill" }], }), ); const stderr = "ERROR: [youtube] ym1: Join this channel to get access to members-only content like this video, and other exclusive perks."; const { run } = stubRunner({ exitCode: 1, stderr, writes: null }); const l = log(); await assert.rejects( fetchLiveChat({ paths, slug: SLUG, videoId: "ym1", videoUrl: "https://www.youtube.com/watch?v=ym1", channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "defer" }, onLog: l.onLog, signal: new AbortController().signal, run, paceSeconds: 0, }), /could not fetch the chat of ym1/, ); const rec = JSON.parse(await readFile(path.join(dir, "availability.json"), "utf8")); assert.equal(rec.availability, "members_only"); assert.equal(rec.checkedBy, "fetch"); assert.deepEqual(rec.history.map((h: { availability: string; source: string }) => [h.availability, h.source]), [ ["public", "backfill"], ["members_only", "fetch"], ]); // The same refusal again rewrites nothing. const before = await readFile(path.join(dir, "availability.json"), "utf8"); await assert.rejects( fetchLiveChat({ paths, slug: SLUG, videoId: "ym1", videoUrl: "https://www.youtube.com/watch?v=ym1", channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "defer" }, onLog: l.onLog, signal: new AbortController().signal, run, paceSeconds: 0, }), ); assert.equal(await readFile(path.join(dir, "availability.json"), "utf8"), before); }); test("a members-only refusal is recorded even when the cookie retry then fetches the chat", async () => { const dir = await video("ym2", { webpage_url: "https://www.youtube.com/watch?v=ym2", was_live: true }); await writeFile( path.join(dir, "availability.json"), JSON.stringify({ checkedAt: "2026-01-02T03:00:00.000Z", checkedBy: "backfill", availability: "public", history: [{ availability: "public", observedAt: "2026-01-02T03:00:00.000Z", source: "backfill" }], }), ); const calls: string[][] = []; const refusedThenOk = async (cwd: string, args: string[]): Promise => { calls.push(args); if (calls.length === 1) { return { exitCode: 1, stderrTail: "ERROR: [youtube] ym2: Join this channel to get access to members-only content like this video, and other exclusive perks.", archiveLine: null, formatLine: null, }; } const base = args[args.findIndex((a) => a.startsWith("subtitle:"))].slice("subtitle:".length); await writeFile(path.join(cwd, `${base}.live_chat.json`), REPLAY); return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; }; const r = await fetchLiveChat({ paths, slug: SLUG, videoId: "ym2", videoUrl: "https://www.youtube.com/watch?v=ym2", channelConfig: CONFIG, cookiePolicy: { cookies: "firefox", mode: "when-required" }, onLog: () => {}, signal: new AbortController().signal, run: refusedThenOk, paceSeconds: 0, }); assert.equal(r.status, "fetched"); assert.equal(calls.length, 2); assert.ok(calls[1].includes("--cookies-from-browser"), "the retry carried the members' cookies"); const rec = JSON.parse(await readFile(path.join(dir, "availability.json"), "utf8")); assert.equal(rec.availability, "members_only"); assert.equal(rec.checkedBy, "fetch"); }); test("a removal is never recorded from a chat refusal: only the availability check establishes one", async () => { const dir = await video("yd1", { webpage_url: "https://www.youtube.com/watch?v=yd1", was_live: true }); const before = JSON.stringify({ checkedAt: "2026-01-02T03:00:00.000Z", checkedBy: "backfill", availability: "public", history: [{ availability: "public", observedAt: "2026-01-02T03:00:00.000Z", source: "backfill" }], }); await writeFile(path.join(dir, "availability.json"), before); const { run } = stubRunner({ exitCode: 1, stderr: "ERROR: [youtube] yd1: Video unavailable. This video has been removed by the uploader", writes: null, }); await assert.rejects( fetchLiveChat({ paths, slug: SLUG, videoId: "yd1", videoUrl: "https://www.youtube.com/watch?v=yd1", channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "defer" }, onLog: () => {}, signal: new AbortController().signal, run, paceSeconds: 0, }), ); assert.equal(await readFile(path.join(dir, "availability.json"), "utf8"), before); }); test("a rate-limited or soft-blocked chat pass records no availability", async () => { const dir = await video("yr1", { webpage_url: "https://www.youtube.com/watch?v=yr1", was_live: true }); for (const stderr of [ "ERROR: [youtube] yr1: HTTP Error 429: Too Many Requests", "ERROR: [youtube] yr1: This content isn't available, try again later.", "ERROR: [youtube] yr1: Sign in to confirm you're not a bot", ]) { const { run } = stubRunner({ exitCode: 1, stderr, writes: null }); await assert.rejects( fetchLiveChat({ paths, slug: SLUG, videoId: "yr1", videoUrl: "https://www.youtube.com/watch?v=yr1", channelConfig: CONFIG, cookiePolicy: { cookies: undefined, mode: "defer" }, onLog: () => {}, signal: new AbortController().signal, run, paceSeconds: 0, onPlatformBackoff: () => {}, }), ); } await assert.rejects(readFile(path.join(dir, "availability.json"), "utf8")); }); test("the job: refusals before any job (info for a skip), a fetch job, a normalize-only job", async () => { await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG)); const tw = await runFetchChatJob({ paths, slug: SLUG, videoId: "tw1", channelConfig: CONFIG, cookiePolicy: NO_COOKIES }); assert.deepEqual(tw, { ok: false, info: true, error: "no chat fetcher for twitch: only YouTube's chat replay is fetched" }); const fresh = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES }); assert.ok(!fresh.ok && fresh.info && /already here/.test(fresh.error)); const missing = await runFetchChatJob({ paths, slug: SLUG, videoId: "nope", channelConfig: CONFIG, cookiePolicy: NO_COOKIES }); assert.ok(!missing.ok && !missing.info); const dir = await video("yt5", { webpage_url: "https://www.youtube.com/watch?v=yt5", was_live: true }); const { run, calls } = stubRunner(); const job = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt5", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run }); assert.ok(job.ok, JSON.stringify(job)); void job.stream.cancel(); const done = await job.done; assert.equal(done.status, "done"); assert.equal(calls.length, 1); assert.ok((await readdir(dir)).includes("live_chat.cues.json")); // The raw replay on disk with stale cues: normalized, no spawn. const dir6 = await video("yt6", { webpage_url: "https://www.youtube.com/watch?v=yt6", was_live: true }); await writeFile(path.join(dir6, "transcript.live_chat.json"), REPLAY); await writeFile(path.join(dir6, "live_chat.cues.json"), "{}"); const old = new Date(Date.now() - 60_000); await utimes(path.join(dir6, "live_chat.cues.json"), old, old); const spawn = stubRunner(); const norm = await runFetchChatJob({ paths, slug: SLUG, videoId: "yt6", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run }); assert.ok(norm.ok); void norm.stream.cancel(); assert.equal((await norm.done).status, "done"); assert.equal(spawn.calls.length, 0, "no network for a replay already here"); assert.equal(JSON.parse(await readFile(path.join(dir6, "live_chat.cues.json"), "utf8")).cues.length, 3); }); // RE-NORMALIZE ONLY (lane chat-clock): the raw on disk parsed again, fresh or // not, never a fetch. test("renormalize: refused with no raw chat on disk (it never fetches), and no job", async () => { await video("rn1", { webpage_url: "https://www.youtube.com/watch?v=rn1", was_live: true }); const spawn = stubRunner(); const out = await runFetchChatJob({ paths, slug: SLUG, videoId: "rn1", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run, renormalize: true, }); assert.ok(!out.ok && !out.info && /no raw chat on disk/.test(out.error) && /never fetches/.test(out.error), JSON.stringify(out)); assert.equal(spawn.calls.length, 0); const none = await runFetchChatJob({ paths, slug: SLUG, videoId: "nope", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, renormalize: true, }); assert.ok(!none.ok); }); test("renormalize: a FRESH chat captured live is parsed again onto the broadcast's clock, with no spawn", async () => { const t0 = Date.UTC(2026, 0, 2, 3, 0, 0); const dir = await video("rn2", { webpage_url: "https://www.youtube.com/watch?v=rn2", was_live: true, release_timestamp: t0 / 1000, }); const live = JSON.stringify({ replayChatItemAction: { actions: [{ addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text: "hello" }] }, authorName: { simpleText: "viewer1" }, id: "m1", timestampUsec: String((t0 + 2_335_000) * 1000), }, }, }, }], }, videoOffsetTimeMsec: "100000", isLive: true, }); await writeFile(path.join(dir, "transcript.live_chat.json"), live + "\n"); // A v1 file written before the fix: fresh by its mtime. await writeFile( path.join(dir, "live_chat.cues.json"), '{"version":1,"source":"live_chat","cues":[{"start":100,"end":105,"text":"viewer1: hello"}]}', ); const plain = await runFetchChatJob({ paths, slug: SLUG, videoId: "rn2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES }); assert.ok(!plain.ok && plain.info && /already here/.test(plain.error), "without the flag: fresh, no job"); const spawn = stubRunner(); const job = await runFetchChatJob({ paths, slug: SLUG, videoId: "rn2", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run, renormalize: true, }); assert.ok(job.ok, JSON.stringify(job)); void job.stream.cancel(); assert.equal((await job.done).status, "done"); assert.equal(spawn.calls.length, 0, "no network"); const doc = JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")); assert.equal(doc.version, 2); assert.equal(doc.cues[0].start, 2335); assert.equal(doc.clock.basis, "broadcast-start"); assert.equal(doc.clock.shiftSeconds, 2235); }); test("renormalize: held by the media guard while the channel's media is moving", async () => { const dir = await video("rn3", { webpage_url: "https://www.youtube.com/watch?v=rn3", was_live: true }); await writeFile(path.join(dir, "transcript.live_chat.json"), REPLAY); const marker = path.join(CORPUS, "channels", SLUG, ".relocating.json"); await writeFile(marker, JSON.stringify({ target: "/nowhere", direction: "out", startedAt: new Date().toISOString(), phase: "copying", scope: "media" })); try { const out = await runFetchChatJob({ paths, slug: SLUG, videoId: "rn3", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, renormalize: true, }); assert.ok(!out.ok && /moving|transition|held/i.test(out.error), JSON.stringify(out)); } finally { await rm(marker, { force: true }); } }); // A DELIBERATE RE-FETCH OVER A STORED CAPTURE (lane text-compress, REVIEW-2 // R1): fetch-chat `replace`. NOTHING EVER REMOVES A CAPTURE BECAUSE A // DIFFERENT ONE ARRIVED — a platform's replay is often shorter than the live // capture, and the capture cannot be fetched again. The stored capture is kept // as `chat-capture-kept..json.zst` (no reader sees it), both are // measured in the log and the result, and only then does the new replay // become the chat. An empty replay, no replay, a failed pass or a `.part`: the // stored capture stays THE chat. Over a plain chat, `replace` is refused. test("replace: a SHORTER replay over a longer stored capture — both survive, the longer one byte-identical", async () => { const { storeFixture } = await import("../testing/storedTextFixture"); const { readStoredText, decodeStoredBytes, readdirLogical } = await import("../lib/storedText-server"); const { isKeptChatCapture } = await import("../lib/mediaTier"); const { readSubTracks } = await import("../lib/videoStatus"); const CHAT = "transcript.live_chat.json"; const LONG = [chatLine(1, "a", "live 1"), chatLine(2, "b", "live 2"), chatLine(3, "c", "live 3"), chatLine(900, "d", "live 4")].join("\n") + "\n"; const SHORT = chatLine(1, "a", "replay 1") + "\n"; for (const tiered of [false, true]) { const id = tiered ? "rpt1" : "rp1"; const d = await video(id, { webpage_url: `https://www.youtube.com/watch?v=${id}`, was_live: true }); if (tiered) { const media = path.join(CORPUS, "channels", SLUG, "media", id); await mkdir(media, { recursive: true }); await writeFile(path.join(media, CHAT), LONG); const { symlink } = await import("node:fs/promises"); await symlink(path.join("..", "..", "media", id, CHAT), path.join(d, CHAT)); } else { await writeFile(path.join(d, CHAT), LONG); } await storeFixture(d, CHAT); const ok = stubRunner({ writes: SHORT }); const l = log(); const r = await fetchLiveChat({ paths, slug: SLUG, videoId: id, videoUrl: `https://www.youtube.com/watch?v=${id}`, channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run: ok.run, replace: true, paceSeconds: 0, }); assert.equal(r.status, "fetched", JSON.stringify(r)); // The new replay is the chat… assert.equal(await readStoredText(d, CHAT, "utf8"), SHORT, `${id}: the chat`); // …and the earlier, longer capture is kept, byte-identical after decode. const kept = (await readdir(d)).filter(isKeptChatCapture); assert.equal(kept.length, 1, `${id}: ${(await readdir(d)).join(", ")}`); assert.equal((await decodeStoredBytes(await readFile(path.join(d, kept[0])))).toString("utf8"), LONG, `${id}: kept whole`); // No reader sees the kept capture as the chat. assert.ok(!(await readdirLogical(d)).some((e) => e.startsWith("transcript.live_chat") && e !== CHAT), id); const tracks = (await readSubTracks(d)).map((t) => JSON.stringify(t)); assert.equal(tracks.filter((t) => t.includes("live_chat")).length, 1, `${id}: one chat track (${tracks.join(" ")})`); assert.ok(!tracks.some((t) => t.includes("chat-capture-kept")), `${id}: the kept capture is no track`); // Both captures measured, in the result and the log. assert.deepEqual(r.replace?.earlier, { bytes: LONG.length, messages: 4, firstSec: 1, lastSec: 900, keptAs: kept[0] }); assert.deepEqual(r.replace?.fetched, { bytes: SHORT.length, messages: 1, firstSec: 1, lastSec: 1, keptAs: null }); assert.match(l.lines.join(""), /Earlier capture \(chat-capture-kept\..*\): 4 message\(s\).*Replay fetched now: 1 message\(s\)/); assert.match(l.lines.join(""), /3 fewer message/); } }); test("replace: an EMPTY replay, no replay, a failed pass or a .part — the stored capture stays the chat", async () => { const { storeFixture } = await import("../testing/storedTextFixture"); const { readStoredText, decodeStoredBytes } = await import("../lib/storedText-server"); const { isKeptChatCapture } = await import("../lib/mediaTier"); const CHAT = "transcript.live_chat.json"; const OLD = [chatLine(1, "a", "old whole capture"), chatLine(2, "b", "more")].join("\n") + "\n"; const forms = async (d: string) => (await readdir(d)).filter((e) => (e.startsWith("transcript.live_chat") && !e.endsWith(".part")) || isKeptChatCapture(e)).sort(); const seeded = async (id: string) => { const d = await video(id, { webpage_url: `https://www.youtube.com/watch?v=${id}`, was_live: true }); await writeFile(path.join(d, CHAT), OLD); await storeFixture(d, CHAT); return d; }; const l = log(); const go = (id: string, run: Parameters[0]["run"]) => fetchLiveChat({ paths, slug: SLUG, videoId: id, videoUrl: `https://www.youtube.com/watch?v=${id}`, channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: l.onLog, signal: new AbortController().signal, run, replace: true, paceSeconds: 0, }); // An empty replay (a file with no message in it): the stored capture is the // chat, the job says the replay was empty, and the empty replay is kept too. const e = await seeded("rpe"); const out = await go("rpe", stubRunner({ writes: '{"replayChatItemAction":{"actions":[]}}\n' }).run); assert.equal(out.status, "none"); assert.equal(await readStoredText(e, CHAT, "utf8"), OLD, "THE chat is the stored capture"); assert.match(l.lines.join(""), /The replay came back EMPTY \(0 messages\)/); assert.equal(out.replace?.earlier.messages, 2); assert.equal(out.replace?.fetched?.messages, 0); const keptEmpty = (await forms(e)).filter(isKeptChatCapture); assert.equal(keptEmpty.length, 1, (await forms(e)).join(", ")); assert.deepEqual((await forms(e)).filter((n) => !isKeptChatCapture(n)), [`${CHAT}.zst`]); assert.equal((await decodeStoredBytes(await readFile(path.join(e, keptEmpty[0])))).toString("utf8"), '{"replayChatItemAction":{"actions":[]}}\n'); // Nothing landed; a failed pass; a .part. for (const [id, run] of [ ["rp2", stubRunner({ writes: null }).run], ["rp3", stubRunner({ exitCode: 1, stderr: "ERROR: [youtube] rp3: Video unavailable" }).run], ["rp4", async (cwd: string) => { await writeFile(path.join(cwd, "data", "rp4", `${CHAT}.part`), "half"); return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; }], ] as const) { const d = await seeded(id); const r = await go(id, run).catch((err: Error) => ({ status: "failed", error: err.message })); assert.notEqual(r.status, "fetched", id); assert.deepEqual((await forms(d)), [`${CHAT}.zst`], `${id}: the stored chat is the chat, nothing kept aside`); assert.equal(await readStoredText(d, CHAT, "utf8"), OLD, id); } // Over a plain chat: refused before any job, nothing spawned. const d5 = await video("rp5", { webpage_url: "https://www.youtube.com/watch?v=rp5", was_live: true }); await writeFile(path.join(d5, CHAT), OLD); const spawn = stubRunner(); const refused = await runFetchChatJob({ paths, slug: SLUG, videoId: "rp5", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run, replace: true }); assert.ok(!refused.ok && /re-fetches over a chat stored compressed only/.test(refused.error), JSON.stringify(refused)); assert.equal(spawn.calls.length, 0); const both = await runFetchChatJob({ paths, slug: SLUG, videoId: "rp5", channelConfig: CONFIG, cookiePolicy: NO_COOKIES, run: spawn.run, replace: true, renormalize: true }); assert.ok(!both.ok && /ask one/.test(both.error)); });