Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit e76ce789a01653a792d83b8d340762772a3e21a4
parent cbf5620cf16e0e58d526d4abe71d2c07587aebd9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 26 Oct 2026 07:46:15 -0400

Channels: chat: with-download | later | never — a later channel's downloads leave the live chat out and the download lane queues one paced, resumable fetch-chat-backlog job once it has nothing left to download; subLangs and chat are Configure fields and channel-config patch keys

- effectiveSubLangs strips live_chat from --sub-langs unless the chat comes
  with the download (youtube handling and the missing-subs pass).
- controller/chatBacklog.ts: every held stream (metadata live_status) whose
  chat is not here, one at a time through fetchLiveChat with the batch gap;
  chat-backlog.json remembers streams with none and the last run.
- controller/laneChatBacklog.ts: the download lane's trigger (idle channel,
  15-min recheck, focus-aware, background job, 25 chats a run).
- pnpm ops fetch-chat-backlog {slug, dryRun?, limit?, queueKey?}; the Download
  stage's Fetch chat backlog; CHANNEL.md regenerated.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCHANNEL.md | 3++-
MOPERATING.md | 21+++++++++++++++++++++
Mcommon/controller/autoRunner.ts | 34++++++++++++++++++++++++++++++++++
Acommon/controller/chatBacklog.test.ts | 212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/chatBacklog.ts | 438+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/laneChatBacklog.ts | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.test.ts | 27+++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 29+++++++++++++++++++++++++++++
Mcommon/lib/channelConfig.ts | 54+++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/channelConfigSchema.test.ts | 2+-
Mcommon/lib/channelConfigSchema.ts | 1+
Mcommon/ytdlp/downloadOneManaged.ts | 5++++-
Mcommon/ytdlp/runYtdlp.ts | 5++++-
Meditor/CHANGELOG.md | 1+
Aeditor/app/api/ops/fetch-chat-backlog/route.test.ts | 42++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/fetch-chat-backlog/route.ts | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/chatBacklogActions.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/stages/DownloadStage.tsx | 15++++++++++++++-
Meditor/app/channels/components/ChannelForm.tsx | 41+++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/channelConfigToForm.ts | 5+++++
Meditor/app/channels/components/parseChannelForm.test.ts | 25+++++++++++++++++++++++++
Meditor/app/channels/components/parseChannelForm.ts | 17++++++++++++++++-
Meditor/app/jobs/jobReplayRegistry.ts | 10++++++++++
Mscripts/archilyzer-ops.mjs | 7+++++++
24 files changed, 1225 insertions(+), 7 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -32,7 +32,8 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `dataDir` | config | RETIRED (release 17). The whole-directory layout's record: the absolute path `channels/<slug>/data` was a symlink to. Still parsed for one release so a write never erases it: a channel that carries it — or whose `data/` is a link — is `legacy`, and every media job, lane and build holds it until `archilyzer storage migrate-tier <slug>` moves its text back and its media into `mediaDir`. Written only by the re-point of a storage location (which keeps it `<root>/<slug>/data` on the new root); removed by that migration. | | `mediaDir` | config | Where this channel's big files live when relocated: `channels/<slug>/media` is a symlink to it, `<root>/<slug>/media`. Absent = in place. Written only by relocate / re-point / the tier migration — a record of what is on disk, never free text, because a value that disagrees with the link is an "inconsistent" channel every media guard refuses. The text (`data/`) never moves. | | `ytdlpExtraArgs` | config | Extra yt-dlp arguments, appended verbatim. Must be an array of strings or it is dropped. | -| `subLangs` | config | yt-dlp `--sub-langs` value for caption downloads. | +| `subLangs` | config | yt-dlp `--sub-langs` value for caption downloads (comma-separated; a leading `-` excludes). Absent = `en.*,live_chat`. The `live_chat` entry is dropped unless `chat` is `"with-download"`. A Configure field. | +| `chat` | config | When a stream's live chat replay is fetched: `"with-download"` (default — with the captions, as a `live_chat` subtitle track), `"later"` (the downloads leave it out — each YouTube download of a streaming channel is 2–4× faster — and when the channel has nothing left to download, the download lane queues one paced, resumable `fetch-chat-backlog` job for its `was_live` streams' chats; `pnpm ops fetch-chat-backlog` runs it by hand) or `"never"` (left out; `pnpm ops fetch-chat` still fetches one). A Configure field. | | `lastSyncedAt` | sync state | SYNC STATE. When the channel last synced (ISO time). Stamped by every sync, and by a social fetch; read by the scheduler's cadence gate. | | `lastFullDownloadAt` | sync state | SYNC STATE. When a full download pass last completed (ISO time). | | `lastFullSweepAt` | sync state | SYNC STATE. When this channel last paid for a sync FULL SWEEP — the deep pass that re-enumerates the whole listing to refresh `playlist` and flag videos that have left it. Stamped by the sweep; read by the cadence gate to decide whether the next sync sweeps or stays on the cheap newest-first paged walk. | diff --git a/OPERATING.md b/OPERATING.md @@ -73,6 +73,27 @@ pnpm ops persist-videos --json '{"items":[{"slug":"example","id":"<videoId>"}] (`"operation"` pins one operation's tier). - Bucket names and sizes: `pnpm ops get channel example`. - Keep videos out of cleanup by title or description: `pnpm ops keep-videos --json '{"slug":"example","match":"interview","dryRun":true}'`. +- A new caption download writes its `transcript.cues.json` as it lands (a umtool build reads it); `build-cues` + mends an older one. + +### A streaming channel: its chats after its downloads + +```sh +pnpm ops channel-config --json '{"slug":"example","patch":{"chat":"later"}}' +pnpm ops fetch-chat-backlog --json '{"slug":"example","dryRun":true}' +pnpm ops fetch-chat-backlog --json '{"slug":"example"}' --wait +``` + +- A stream's live chat replay (7–42 MB) rides its caption download by default and makes each YouTube download of a + streaming channel 2–4× slower. `chat` (Configure → Live chat replay): `"with-download"` (default), `"later"` or + `"never"` — the downloads leave the chat out for the last two. +- `"later"`: once the channel has nothing left to download, the download lane queues one `fetch-chat-backlog` job + for it — every held video whose metadata says it was a stream (`live_status` was_live) and whose chat is not here, + one at a time at the platform's pace, on its download queue, at most 25 a run. A re-run skips the chats here and the + streams known to have none (`chat-backlog.json`); a restart resumes it. The channel page's Download stage has + **Fetch chat backlog**; `dryRun` counts from the disk and starts nothing. +- The caption languages are a Configure field too (`subLangs`, yt-dlp's `--sub-langs`; blank = `en.*,live_chat`), + and a `channel-config` patch key. ### Cookies gone stale: the dashboard's banner diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts @@ -104,6 +104,7 @@ import { WaybackAutoPicker, type WaybackAutoPick, } from "./laneWaybackAuto"; +import { ChatBacklogLane } from "./laneChatBacklog"; import { isGateHeld } from "../lib/pauseGates"; import { inspectChannelMedia, @@ -1363,6 +1364,9 @@ async function runLoop( // `wayback.auto` channels' new scan rows (release 37 S2): read once a minute // per channel, each row offered once in this runner's life. const waybackAuto = WaybackAutoPicker.forPaths(paths); + // `chat: "later"` channels' chat backlogs (2026-10-26): one job per channel + // once it has nothing left to download, considered at most every 15 min. + const chatBacklogLane = ChatBacklogLane.forPaths(paths); // Platforms this tick may not touch — busy or cooling down. Hoisted out of the // download branch because the metadata-scan pre-pick honours it too: a // platform in a 429 cooldown must not be asked for 1,800 titles either. @@ -1741,6 +1745,36 @@ async function runLoop( ? focusSummary(ctx.model, ctx.focusSlugs, pending) : null; reportFocusHold(focus); + // ── A CHANNEL WITH NOTHING LEFT TO DOWNLOAD GETS ITS CHATS (2026-10-26) ── + // + // A `chat: "later"` channel's downloads leave the live chat out; once no + // video of it is pending here (before the platform gates: a cooling + // platform is not "done"), none is in flight and no metadata scan is owed, + // the lane queues one `fetch-chat-backlog` job for it on the platform's + // download queue, in the background (controller/laneChatBacklog.ts). + // Voided: the consideration reads two small files and never holds the tick. + if (kind === "download") { + const busy = new Set<string>(); + for (const ids of Object.values(pending)) { + for (const id of ids) { + const s = owner.get(id); + if (s) busy.add(s); + } + } + for (const unit of live.inFlight.values()) busy.add(unit.channelSlug); + const listed = new Set<string>(); + for (const c of channels) { + listed.add(c.slug); + if (c.filtered && (c.scanUnscanned ?? 0) > 0) busy.add(c.slug); + } + void chatBacklogLane + .consider(metaCache, { + idle: (slug) => listed.has(slug) && !busy.has(slug), + ...(focus ? { focus: { slugs: new Set(ctx.focusSlugs), holding: focus.holding } } : {}), + onLog, + }) + .catch(() => {}); + } // THE RUNNER JOB'S OWN BAR, on the metrics the per-channel jobs already // use — so a lane's runner row reads like the manual verb's row rather than // like an opaque long-lived loop. `target` moves as the corpus does (this diff --git a/common/controller/chatBacklog.test.ts b/common/controller/chatBacklog.test.ts @@ -0,0 +1,212 @@ +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<string, unknown>, files: Record<string, string> = {}): Promise<void> { + 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<string>) { + const asked: string[] = []; + const run = async (cwd: string, args: string[]): Promise<AttemptOutcome> => { + 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<string>(), 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"]); +}); diff --git a/common/controller/chatBacklog.ts b/common/controller/chatBacklog.ts @@ -0,0 +1,438 @@ +// A CHANNEL'S STREAM CHATS, FETCHED AFTER ITS DOWNLOADS (2026-10-26) — the +// `fetch-chat-backlog` job: `pnpm ops fetch-chat-backlog {slug}`, and the +// download lane's own for a channel whose `chat` is "later" once it has nothing +// left to download (controller/laneChatBacklog.ts). +// +// WHY. A stream's live chat replay is 7–42 MB and came down with its captions, +// which made each YouTube download of a streaming channel 2–4× slower while +// the Ethanalyzer backlog was archived (2026-10-23…26). The fix then was a hand +// edit of `subLangs` and a hand-written watcher that waited for the downloads +// and ran `pnpm ops fetch-chat` per streamed episode — and died on reboot. A +// `chat: "later"` channel's downloads leave the chat out (effectiveSubLangs), +// and this job fetches the chats afterwards. +// +// WHICH VIDEOS. Every held video whose metadata says it was a stream +// (`live_status` was_live / post_live, or `was_live: true`) and whose chat is +// not here — selected by the METADATA, because a download without `live_chat` +// in its sub-langs records no chat track to look for. A raw replay already on +// disk is only normalized. Newest first. +// +// PACED AND RESUMABLE. One chat at a time through fetchLiveChat (the one +// chat-only pass: the channel's cookies, the platform's live pace), on the +// platform's download queue, with the batch downloads' gap between two +// (downloadGapMs). It stops on a rate limit (the platform's cooldown recorded), +// a held platform, three failures in a row, a drain or `limit` chats; a re-run +// skips every chat already here and every stream already known to have none — +// `chat-backlog.json` beside the channel's config remembers those, and what the +// last run did. Replayable, and resumed after a restart (jobs/jobKinds.ts). + +import path from "node:path"; +import { readdir, readFile } from "node:fs/promises"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import type { ResolvedCookiePolicy } from "../lib/cookiePolicy"; +import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; +import type { Paths } from "../lib/paths"; +import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys"; +import { getSettings } from "../lib/settings"; +import { META_FILENAME } from "../lib/videoStatus"; +import { + heldPlatformRefusal, + platformCooldownRemainingMs, + recordDownloadBackoff, + recordPlatformClean, +} from "../jobs/downloadBackoff"; +import { downloadGapMs } from "../jobs/platformBackoff"; +import { getRegistry } from "../jobs/registry"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { + channelPaceSeconds, + channelPlatform, + platformMinGapSeconds, + staticSleepRequestsSeconds, +} from "../ytdlp/channelArgs"; +import { fetchLiveChat, liveChatPlan, noChatFetcherSentence, type ChatRunner } from "./fetchLiveChat"; +import { normalizeLiveChat } from "./normalizeLiveChat"; +import { readChannelSnapshotShared } from "./channels"; + +export const FETCH_CHAT_BACKLOG_KIND = "fetch-chat-backlog"; +export const CHAT_BACKLOG_FILENAME = "chat-backlog.json"; +// Three failures in a row (not a rate limit) stop a run: the source is saying +// something a fourth request will not change. +export const CHAT_BACKLOG_MAX_FAILURES_IN_A_ROW = 3; + +const STREAM_STATUSES = new Set(["was_live", "post_live"]); + +export type ChatBacklogState = { + version: 1; + // Streams whose chat the source does not have (replay off, or never live + // after all), and those with no chat fetcher: never asked again. + settled: Record<string, { at: string; why: "no-chat" | "not-live" | "no-fetcher" }>; + lastRun?: { + jobId?: string; + startedAt: string; + endedAt: string; + // Every stream's chat is here or settled. + complete: boolean; + fetched: number; + normalized: number; + none: number; + failed: number; + remaining: number; + stopped?: string; + // The channel report's downloaded count the run started from: the lane + // queues the next run when it moves. + downloadedAtRun?: number; + }; +}; + +function statePath(paths: Paths, slug: string): string { + return path.join(paths.channelsDir, slug, CHAT_BACKLOG_FILENAME); +} + +export async function readChatBacklogState(paths: Paths, slug: string): Promise<ChatBacklogState> { + const read = await readJsonFile(statePath(paths, slug)); + const v = read.ok ? (read.value as Partial<ChatBacklogState>) : null; + return { + version: 1, + settled: v && v.settled && typeof v.settled === "object" ? v.settled : {}, + ...(v?.lastRun && typeof v.lastRun === "object" ? { lastRun: v.lastRun } : {}), + }; +} + +async function writeChatBacklogState(paths: Paths, slug: string, state: ChatBacklogState): Promise<void> { + await writeJsonAtomic(statePath(paths, slug), state); +} + +async function streamInfo(videoDir: string): Promise<{ live: string | null; date: string }> { + try { + const meta = JSON.parse(await readFile(path.join(videoDir, META_FILENAME), "utf8")) as { + live_status?: unknown; + was_live?: unknown; + upload_date?: unknown; + release_date?: unknown; + }; + const live = meta.was_live === true ? "was_live" : typeof meta.live_status === "string" ? meta.live_status : null; + const date = typeof meta.upload_date === "string" ? meta.upload_date : typeof meta.release_date === "string" ? meta.release_date : ""; + return { live, date }; + } catch { + return { live: null, date: "" }; + } +} + +export type ChatBacklogCandidate = { id: string; date: string; action: "fetch" | "normalize"; url?: string; platform?: string }; + +export type ChatBacklogPlan = { + candidates: ChatBacklogCandidate[]; + // Streams whose chat is already here (fresh live_chat.cues.json). + have: number; + // Streams known to have none (chat-backlog.json `settled`). + settled: number; + // Held videos that were not streams. + notStreams: number; +}; + +// What the job would do, from the disk alone (no request): every held stream +// whose chat is neither here nor settled, newest first. +export async function planChatBacklog( + paths: Paths, + slug: string, + config: ChannelConfig, + state?: ChatBacklogState, +): Promise<ChatBacklogPlan> { + const known = state ?? (await readChatBacklogState(paths, slug)); + const dataDir = path.join(paths.channelsDir, slug, "data"); + let ids: string[]; + try { + ids = (await readdir(dataDir, { withFileTypes: true })) + .filter((e) => e.isDirectory() || e.isSymbolicLink()) + .map((e) => e.name); + } catch { + ids = []; + } + const plan: ChatBacklogPlan = { candidates: [], have: 0, settled: 0, notStreams: 0 }; + for (const id of ids) { + if (known.settled[id]) { + plan.settled++; + continue; + } + const { live, date } = await streamInfo(path.join(dataDir, id)); + if (!live || !STREAM_STATUSES.has(live)) { + plan.notStreams++; + continue; + } + const p = await liveChatPlan(paths, slug, id, config); + if (p.kind === "fresh") plan.have++; + else if (p.kind === "normalize") plan.candidates.push({ id, date, action: "normalize" }); + else if (p.kind === "fetch") plan.candidates.push({ id, date, action: "fetch", url: p.url, platform: p.platform }); + else if (p.kind === "no-fetcher" || p.kind === "not-live") plan.settled++; + } + plan.candidates.sort((a, b) => b.date.localeCompare(a.date) || a.id.localeCompare(b.id)); + return plan; +} + +export type ChatBacklogResult = NonNullable<ChatBacklogState["lastRun"]>; + +export type RunChatBacklogOpts = { + paths: Paths; + slug: string; + config: ChannelConfig; + cookiePolicy?: ResolvedCookiePolicy; + onLog: (line: string) => void; + signal: AbortSignal; + drainSignal?: AbortSignal; + limit?: number; + jobId?: string; + downloadedAtRun?: number; + // A chat landed (fetched or normalized): the job's itemLanded. + onChat?: (id: string) => void; + // Test seams. + run?: ChatRunner; + sleep?: (ms: number, signal: AbortSignal) => Promise<void>; + gapMs?: () => number; + now?: () => Date; +}; + +function sleepFor(ms: number, signal: AbortSignal): Promise<void> { + return new Promise((resolve) => { + if (signal.aborted || ms <= 0) return resolve(); + const t = setTimeout(resolve, ms); + signal.addEventListener("abort", () => { + clearTimeout(t); + resolve(); + }, { once: true }); + }); +} + +export async function runChatBacklog(opts: RunChatBacklogOpts): Promise<ChatBacklogResult> { + const now = opts.now ?? (() => new Date()); + const sleep = opts.sleep ?? sleepFor; + const startedAt = now().toISOString(); + const state = await readChatBacklogState(opts.paths, opts.slug); + const plan = await planChatBacklog(opts.paths, opts.slug, opts.config, state); + opts.onLog( + `Chat backlog of ${opts.slug}: ${plan.candidates.length} stream chat(s) to get` + + ` (${plan.candidates.filter((c) => c.action === "normalize").length} already on disk, only normalized);` + + ` ${plan.have} here, ${plan.settled} known to have none, ${plan.notStreams} video(s) not streams.` + + (opts.limit ? ` At most ${opts.limit} this run.` : ""), + ); + const result: ChatBacklogResult = { + ...(opts.jobId ? { jobId: opts.jobId } : {}), + startedAt, + endedAt: startedAt, + complete: false, + fetched: 0, + normalized: 0, + none: 0, + failed: 0, + remaining: plan.candidates.length, + ...(opts.downloadedAtRun !== undefined ? { downloadedAtRun: opts.downloadedAtRun } : {}), + }; + const save = async () => { + result.endedAt = now().toISOString(); + state.lastRun = { ...result }; + await writeChatBacklogState(opts.paths, opts.slug, state); + }; + // The batch downloads' gap between two videos (runYtdlp's subtitle pass + // takes the same): the pause, plus the platform's pace above its base. + const sleepSeconds = opts.config.sleepBetweenDownloadsSeconds ?? getSettings().sleepBetweenDownloadsSeconds; + const platformOfChannel = channelPlatform(opts.config); + const gapMs = + opts.gapMs ?? + (() => + downloadGapMs( + sleepSeconds, + channelPaceSeconds(opts.config), + staticSleepRequestsSeconds(platformOfChannel), + { minSeconds: platformMinGapSeconds(platformOfChannel) }, + )); + let fetchedOnce = false; + let failuresInARow = 0; + let attempted = 0; + for (const c of plan.candidates) { + if (opts.signal.aborted) { + result.stopped = "cancelled"; + break; + } + if (opts.drainSignal?.aborted) { + result.stopped = "drained"; + break; + } + if (opts.limit && attempted >= opts.limit) { + result.stopped = `the run's limit (${opts.limit})`; + break; + } + attempted++; + const videoDir = path.join(opts.paths.channelsDir, opts.slug, "data", c.id); + try { + if (c.action === "normalize") { + const out = await normalizeLiveChat({ + videoDir, + channelSlug: opts.slug, + ...(opts.config.name ? { configName: opts.config.name } : {}), + force: true, + log: (m) => opts.onLog(`${m}\n`), + }); + if (out.status !== "skipped") { + result.normalized++; + opts.onChat?.(c.id); + } + result.remaining--; + continue; + } + const platform = c.platform ?? "youtube"; + const held = await heldPlatformRefusal(platform, "The chat backlog", opts.paths); + if (held) { + result.stopped = held; + break; + } + const cooling = await platformCooldownRemainingMs(platform, opts.paths); + if (cooling > 0) { + result.stopped = `${platform} is in a rate-limit cooldown (${Math.ceil(cooling / 1000)}s remaining)`; + break; + } + if (fetchedOnce) { + const ms = gapMs(); + if (ms > 0) { + opts.onLog(`Sleeping ${Math.round(ms / 1000)}s before the next chat...`); + await sleep(ms, AbortSignal.any([opts.signal, ...(opts.drainSignal ? [opts.drainSignal] : [])])); + if (opts.signal.aborted || opts.drainSignal?.aborted) { + result.stopped = opts.signal.aborted ? "cancelled" : "drained"; + break; + } + } + } + fetchedOnce = true; + const out = await fetchLiveChat({ + paths: opts.paths, + slug: opts.slug, + videoId: c.id, + videoUrl: c.url!, + channelConfig: opts.config, + ...(opts.cookiePolicy ? { cookiePolicy: opts.cookiePolicy } : {}), + onLog: opts.onLog, + signal: opts.signal, + onPlatformBackoff: () => recordDownloadBackoff(platform, opts.paths), + onPlatformClean: () => recordPlatformClean(platform, opts.paths), + ...(opts.run ? { run: opts.run } : {}), + }); + failuresInARow = 0; + result.remaining--; + if (out.status === "fetched") { + result.fetched++; + opts.onChat?.(c.id); + } else { + result.none++; + state.settled[c.id] = { at: now().toISOString(), why: "no-chat" }; + } + } catch (err) { + const message = (err as Error).message; + if (opts.signal.aborted) { + result.stopped = "cancelled"; + break; + } + result.failed++; + failuresInARow++; + opts.onLog(`${c.id}: ${message}`); + if (/rate-limited/i.test(message)) { + result.stopped = "a rate limit (the platform's cooldown is recorded)"; + break; + } + if (failuresInARow >= CHAT_BACKLOG_MAX_FAILURES_IN_A_ROW) { + result.stopped = `${CHAT_BACKLOG_MAX_FAILURES_IN_A_ROW} failures in a row`; + break; + } + } + } + result.complete = result.remaining === 0; + await save(); + opts.onLog( + `Chat backlog of ${opts.slug}: ${result.fetched} fetched, ${result.normalized} normalized, ${result.none} with no chat, ` + + `${result.failed} failed; ${result.remaining} left${result.stopped ? ` — stopped: ${result.stopped}` : ""}.`, + ); + return result; +} + +// Is a backlog job of this channel queued or running? +export function activeChatBacklogJob(slug: string): string | null { + const live = getRegistry() + .list() + .find((j) => j.kind === FETCH_CHAT_BACKLOG_KIND && j.channelSlug === slug && (j.status === "queued" || j.status === "running")); + return live?.id ?? null; +} + +export type StartChatBacklogOpts = { + paths: Paths; + slug: string; + config: ChannelConfig; + cookiePolicy: ResolvedCookiePolicy; + limit?: number; + queueKey?: string; + // The download lane's: behind any foreground job on the queue. + background?: boolean; + downloadedAtRun?: number; + run?: ChatRunner; +}; + +// THE JOB. Every refusal before any job, in the sentences the rest of the +// app uses: a channel whose text cannot be read, one already running a +// backlog, a held platform or one cooling down (`info`: the source is resting). +export async function startChatBacklogJob(opts: StartChatBacklogOpts): Promise<StreamActionResult> { + const { paths, slug, config } = opts; + try { + await assertChannelTextReadable(paths, slug, config); + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + const active = activeChatBacklogJob(slug); + if (active) return { ok: false, info: true, error: `a chat backlog of ${slug} is already queued or running (job ${active})` }; + const platform = channelPlatform(config) ?? "unknown"; + if (platform !== "youtube") return { ok: false, info: true, error: noChatFetcherSentence(platform) }; + const held = await heldPlatformRefusal(platform, "The chat backlog", paths); + if (held) return { ok: false, info: true, error: held }; + const remainingMs = await platformCooldownRemainingMs(platform, paths); + if (remainingMs > 0) { + return { + ok: false, + info: true, + error: `${platform} is in a rate-limit cooldown (${Math.ceil(remainingMs / 1000)}s remaining). The chat backlog can run once it lapses.`, + }; + } + return runManagedFunction({ + kind: FETCH_CHAT_BACKLOG_KIND, + queueKey: resolveQueueKey(downloadQueueKey(config), opts.queueKey), + paths, + channelSlug: slug, + ...(opts.background ? { background: true } : {}), + spec: { + kind: FETCH_CHAT_BACKLOG_KIND, + slug, + params: { + ...(opts.limit ? { limit: opts.limit } : {}), + ...(opts.queueKey ? { queueKey: opts.queueKey } : {}), + }, + }, + fn: async (onLog, signal, _progress, ctx) => { + const result = await runChatBacklog({ + paths, + slug, + config, + cookiePolicy: opts.cookiePolicy, + onLog, + signal, + drainSignal: ctx.drainSignal, + jobId: ctx.jobId, + ...(opts.limit ? { limit: opts.limit } : {}), + // The report's downloaded count this run starts from (the lane's + // "has anything been downloaded since?"). + downloadedAtRun: + opts.downloadedAtRun ?? (await readChannelSnapshotShared(paths, slug))?.totals?.downloaded, + onChat: () => ctx.itemLanded(), + ...(opts.run ? { run: opts.run } : {}), + }); + if (result.failed > 0 && result.fetched + result.normalized + result.none === 0 && !result.stopped?.startsWith("the run's limit")) { + throw new Error(`${result.failed} chat fetch(es) failed and none landed${result.stopped ? ` — stopped: ${result.stopped}` : ""}`); + } + }, + }); +} diff --git a/common/controller/laneChatBacklog.ts b/common/controller/laneChatBacklog.ts @@ -0,0 +1,119 @@ +// `chat: "later"` IN THE DOWNLOAD LANE (2026-10-26): once a channel that +// fetches its chats later has nothing left to download, the lane queues ONE +// `fetch-chat-backlog` job for it (controller/chatBacklog.ts) — paced, +// resumable, on the platform's download queue as a BACKGROUND job, so a click +// jumps ahead of it, and capped at CHAT_BACKLOG_LANE_LIMIT chats a run so the +// platform's queue is handed back to the downloads between runs. It replaces +// the hand-written watcher that waited for a channel's downloads to finish and +// then ran `pnpm ops fetch-chat` per streamed episode (and died on reboot). +// +// WHEN. A channel is considered at most once per CHAT_BACKLOG_RECHECK_MS, and +// queued only when no backlog of it is queued or running and its last run's +// record (`chat-backlog.json`) says there may be work: no run yet, a run that +// stopped before the end (a limit, a rate limit, a drain) and ended more than +// the recheck ago, or a channel report whose downloaded count has moved since +// the last run began. Never for a channel outside a holding focus (the lane's +// own rule), and never for a paused one (the lane's channel list leaves those +// out). A refusal (a held platform, a cooldown) is the action's own sentence +// in the lane's log, once per consideration. + +import type { ChannelConfig } from "../lib/channelConfig"; +import { resolveCookiePolicy } from "../lib/cookiePolicy"; +import type { Paths } from "../lib/paths"; +import { getSettings } from "../lib/settings"; +import type { StreamActionResult } from "../jobs/streamCommand"; +import { activeChatBacklogJob, readChatBacklogState, startChatBacklogJob, type ChatBacklogState } from "./chatBacklog"; +import { readChannelSnapshotShared } from "./channels"; + +export const CHAT_BACKLOG_RECHECK_MS = 15 * 60 * 1000; +export const CHAT_BACKLOG_LANE_LIMIT = 25; + +export type ChatBacklogLaneDeps = { + now?: () => number; + readState?: (slug: string) => Promise<ChatBacklogState>; + downloadedOf?: (slug: string) => Promise<number | undefined>; + isActive?: (slug: string) => boolean; + start?: (slug: string, config: ChannelConfig, downloadedAtRun: number | undefined) => Promise<StreamActionResult>; +}; + +// Should a backlog run start now, by the channel's last run and its report? +export function chatBacklogDue( + state: ChatBacklogState, + downloaded: number | undefined, + now: number, + recheckMs = CHAT_BACKLOG_RECHECK_MS, +): boolean { + const last = state.lastRun; + if (!last) return true; + if (downloaded !== undefined && last.downloadedAtRun !== downloaded) return true; + if (!last.complete) return now - Date.parse(last.endedAt) >= recheckMs; + return false; +} + +export class ChatBacklogLane { + private readonly considered = new Map<string, number>(); + constructor(private readonly deps: Required<ChatBacklogLaneDeps>) {} + + static forPaths(paths: Paths, deps: ChatBacklogLaneDeps = {}): ChatBacklogLane { + return new ChatBacklogLane({ + now: deps.now ?? Date.now, + readState: deps.readState ?? ((slug) => readChatBacklogState(paths, slug)), + downloadedOf: + deps.downloadedOf ?? + (async (slug) => (await readChannelSnapshotShared(paths, slug))?.totals?.downloaded), + isActive: deps.isActive ?? ((slug) => activeChatBacklogJob(slug) !== null), + start: + deps.start ?? + ((slug, config, downloadedAtRun) => + startChatBacklogJob({ + paths, + slug, + config, + cookiePolicy: resolveCookiePolicy(getSettings(), config), + limit: CHAT_BACKLOG_LANE_LIMIT, + background: true, + ...(downloadedAtRun !== undefined ? { downloadedAtRun } : {}), + })), + }); + } + + // The channels with nothing left to download this tick (`idle`), in the + // lane's order. Starts at most one job per channel; answers the ones it + // started. + async consider( + channels: ReadonlyArray<{ slug: string; config: ChannelConfig }>, + opts: { + idle: (slug: string) => boolean; + focus?: { slugs: ReadonlySet<string>; holding: boolean }; + onLog?: (line: string) => void; + }, + ): Promise<string[]> { + const started: string[] = []; + const now = this.deps.now(); + for (const c of channels) { + if (c.config.chat !== "later") continue; + if (opts.focus?.holding && !opts.focus.slugs.has(c.slug)) continue; + if (!opts.idle(c.slug)) continue; + const at = this.considered.get(c.slug); + if (at !== undefined && now - at < CHAT_BACKLOG_RECHECK_MS) continue; + this.considered.set(c.slug, now); + if (this.deps.isActive(c.slug)) continue; + const downloaded = await this.deps.downloadedOf(c.slug).catch(() => undefined); + const state = await this.deps.readState(c.slug).catch(() => null); + if (!state || !chatBacklogDue(state, downloaded, now)) continue; + const res = await this.deps.start(c.slug, c.config, downloaded).catch( + (err) => ({ ok: false, error: (err as Error).message }) as StreamActionResult, + ); + if (res.ok) { + void res.stream.cancel(); + started.push(c.slug); + opts.onLog?.( + `Auto-download: ${c.slug} has nothing left to download; queued its chat backlog (job ${res.jobId}, at most ${CHAT_BACKLOG_LANE_LIMIT} chats).`, + ); + } else { + opts.onLog?.(`Auto-download: ${c.slug}'s chat backlog not queued: ${res.error}`); + } + } + return started; + } +} diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -2,6 +2,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { isDrainableKind, + resumeOnBootKindIds, jobKindLabel, getJobKind, kindNeedsMedia, @@ -365,6 +366,7 @@ test("pacing guard: the kinds that make platform requests are network kinds", () "record-live", "persist-videos", "fetch-chat", + "fetch-chat-backlog", "auto-download-unit", "check-availability", "import-page", @@ -383,3 +385,28 @@ test("pacing guard: the kinds that make platform requests are network kinds", () assert.equal(kindIsNetwork("auto-download"), false); for (const k of jobKindIds()) assert.equal(typeof kindIsNetwork(k), "boolean"); }); + +// 2026-10-26: what a restart interrupted is resumed only for a kind that is +// replayable AND continues on a re-run (jobs/resumeInterrupted.ts). +test("resumeOnBoot: exactly the kinds that continue on a re-run, every one replayable", () => { + assert.deepEqual(resumeOnBootKindIds().sort(), [ + "capture-posts", + "download-missing", + "fetch-chat-backlog", + "fetch-posts", + "fetch-windows", + "import-archive-org", + "import-one", + "normalize-transcripts", + "persist-videos", + "refresh-report", + "whisper-all", + "whisper-bucket-auto-subs", + "whisper-bucket-downloaded-no-transcript", + ]); + for (const k of resumeOnBootKindIds()) assert.equal(getJobKind(k)?.replayable, true, `${k} is replayable`); + // Never a move, a delete or a one-shot. + for (const k of ["relocate-channel-media", "repoint-storage-location", "purge-superseded-auto-subs", "evict-clips", "sync", "fetch-chat", "record-live"]) { + assert.equal(getJobKind(k)?.resumeOnBoot, undefined, `${k} does not resume`); + } +}); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -851,6 +851,26 @@ const JOB_KINDS: Record<string, JobKindMeta> = { network: true, needsMedia: true, }, + // A CHANNEL'S STREAM CHATS AFTER ITS DOWNLOADS (2026-10-26, + // controller/chatBacklog.ts — `pnpm ops fetch-chat-backlog`, and the + // download lane's own for a `chat: "later"` channel with nothing left to + // download): the chat of every held stream that lacks one, one at a time + // through fetch-chat's pass. On the platform download queue, paced (the + // batch downloads' gap between two), `needsMedia` (it writes raw replays, a + // tierable big file). Drainable — it stops between chats — and, since a + // re-run skips every chat here and every stream known to have none, + // replayable and resumed after a restart. An ingest kind: the index reads + // the cues. + "fetch-chat-backlog": { + kind: "fetch-chat-backlog", + label: "Fetch chat backlog", + drainable: true, + replayable: true, + queueKeyStrategy: "platform", + network: true, + needsMedia: true, + resumeOnBoot: true, + }, // A FILE MADE A NORMAL TRANSCRIBED ITEM (controller/importMedia.ts — `pnpm // ops import-media`, "Import a file" on the channel and video pages): the // record (one metadata-only pass for a source page, or by hand), then the @@ -1496,6 +1516,8 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([ // One video's live chat replay, normalized into the cues the index reads // (release 36 lane A). "fetch-chat", + // Its backlog: every held stream's chat, after the downloads (2026-10-26). + "fetch-chat-backlog", // A file landed as a video's source, its audio beside it; a live recording // landed the same way (plans/live-capture.md). "import-media", @@ -1534,6 +1556,13 @@ export function kindIsNetwork(kind: string): boolean { return JOB_KINDS[kind]?.network ?? false; } +// The kinds a restart's interruption is resumed for (JobKindMeta.resumeOnBoot). +export function resumeOnBootKindIds(): string[] { + return Object.values(JOB_KINDS) + .filter((k) => k.resumeOnBoot === true) + .map((k) => k.kind); +} + // Every kind on a platform queue, for the test that holds each to a decision. export function platformKindIds(): string[] { return Object.values(JOB_KINDS) diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -107,6 +107,53 @@ export function isRejectedLivestreamMode( return v === "skip" || v === "chat-only"; } +// WHEN A STREAM'S LIVE CHAT REPLAY IS FETCHED (2026-10-26). The replay rides +// the caption download as a `live_chat` subtitle track (yt-dlp `--sub-langs`) +// and is 7–42 MB per stream, which made each YouTube download of a streaming +// channel 2–4× slower while the backlog was being archived (Ethanalyzer, +// 2026-10-23…26). Absent = "with-download" (every channel before the field): +// with-download the chat comes down with the captions, as it always has; +// later the downloads leave it out, and once the channel has +// nothing left to download the download lane queues ONE +// paced, resumable `fetch-chat-backlog` job for its streams' +// chats (controller/chatBacklog.ts); +// never the downloads leave it out and nothing fetches it +// (`pnpm ops fetch-chat` still does, one video at a time). +export type ChatMode = "with-download" | "later" | "never"; +export const CHAT_MODES: readonly ChatMode[] = ["with-download", "later", "never"]; + +export function isChatMode(v: unknown): v is ChatMode { + return v === "with-download" || v === "later" || v === "never"; +} + +// yt-dlp's `--sub-langs` when the channel names none. +export const DEFAULT_SUB_LANGS = "en.*,live_chat"; + +// The `--sub-langs` a caption download passes: the channel's (or the +// default), WITHOUT the live chat unless `chat` fetches it with the download. +// An entry that is `live_chat` itself is dropped; one that would still match +// it (`all`, `.*`) gets `-live_chat` after it, yt-dlp's own exclusion. Nothing +// left (a channel whose only track was the chat) falls back to `en.*`. +export function effectiveSubLangs(config: Pick<ChannelConfig, "subLangs" | "chat">): string { + const langs = config.subLangs?.trim() || DEFAULT_SUB_LANGS; + if ((config.chat ?? "with-download") === "with-download") return langs; + const kept = langs + .split(",") + .map((x) => x.trim()) + .filter((x) => x && x !== "live_chat" && x !== "-live_chat"); + const catchesChat = kept.some((x) => { + if (x.startsWith("-")) return false; + if (x === "all") return true; + try { + return new RegExp(`^(?:${x})$`).test("live_chat"); + } catch { + return false; + } + }); + if (kept.length === 0) return "en.*"; + return catchesChat ? [...kept, "-live_chat"].join(",") : kept.join(","); +} + // A channel's `config.json`. Each field is documented in // CHANNEL_CONFIG_FIELD_DOCS below (rendered into CHANNEL.md); the keys that are // SYNC STATE rather than configuration are CHANNEL_SYNC_STATE_KEYS. @@ -138,6 +185,7 @@ export type ChannelConfig = { mediaDir?: string; ytdlpExtraArgs?: string[]; subLangs?: string; + chat?: ChatMode; lastSyncedAt?: string; lastFullDownloadAt?: string; lastFullSweepAt?: string; @@ -197,7 +245,10 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { mediaDir: "Where this channel's big files live when relocated: `channels/<slug>/media` is a symlink to it, `<root>/<slug>/media`. Absent = in place. Written only by relocate / re-point / the tier migration — a record of what is on disk, never free text, because a value that disagrees with the link is an \"inconsistent\" channel every media guard refuses. The text (`data/`) never moves.", ytdlpExtraArgs: "Extra yt-dlp arguments, appended verbatim. Must be an array of strings or it is dropped.", - subLangs: "yt-dlp `--sub-langs` value for caption downloads.", + subLangs: + "yt-dlp `--sub-langs` value for caption downloads (comma-separated; a leading `-` excludes). Absent = `en.*,live_chat`. The `live_chat` entry is dropped unless `chat` is `\"with-download\"`. A Configure field.", + chat: + 'When a stream\'s live chat replay is fetched: `"with-download"` (default — with the captions, as a `live_chat` subtitle track), `"later"` (the downloads leave it out — each YouTube download of a streaming channel is 2–4× faster — and when the channel has nothing left to download, the download lane queues one paced, resumable `fetch-chat-backlog` job for its `was_live` streams\' chats; `pnpm ops fetch-chat-backlog` runs it by hand) or `"never"` (left out; `pnpm ops fetch-chat` still fetches one). A Configure field.', lastSyncedAt: "SYNC STATE. When the channel last synced (ISO time). Stamped by every sync, and by a social fetch; read by the scheduler's cadence gate.", lastFullDownloadAt: "SYNC STATE. When a full download pass last completed (ISO time).", @@ -417,6 +468,7 @@ export const CHANNEL_CONFIG_COERCIONS: { ? (v as string[]) : undefined, subLangs: str, + chat: (v) => (isChatMode(v) ? v : undefined), lastSyncedAt: str, lastFullDownloadAt: str, lastFullSweepAt: str, diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 38); // release 38: `xSearch` + assert.equal(CHANNEL_CONFIG_KEYS.length, 39); // 2026-10-26: `chat` assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -62,6 +62,7 @@ export const channelConfigObjectSchema = z.object({ mediaDir: field("mediaDir"), ytdlpExtraArgs: field("ytdlpExtraArgs"), subLangs: field("subLangs"), + chat: field("chat"), lastSyncedAt: field("lastSyncedAt"), lastFullDownloadAt: field("lastFullDownloadAt"), lastFullSweepAt: field("lastFullSweepAt"), diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -20,6 +20,7 @@ import { import { type AudioFormat, type ChannelConfig, + effectiveSubLangs, } from "../lib/channelConfig"; import { resolvePersistenceDecision, @@ -293,7 +294,9 @@ function youtubeHandlingArgs( "--write-auto-subs", "--write-subs", "--sub-langs", - config.subLangs ?? "en.*,live_chat", + // Without the live chat unless the channel fetches it with the download + // (ChannelConfig.chat). + effectiveSubLangs(config), ]; if (!reuseInfoJson) args.push("--write-info-json"); args.push( diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -9,6 +9,7 @@ import { type AudioFormat, type ChannelConfig, type ChannelHandling, + effectiveSubLangs, } from "../lib/channelConfig"; import { getSettings } from "../lib/settings"; import { patchChannelConfig } from "../controller/channels"; @@ -1501,7 +1502,9 @@ async function downloadMissingSubs(opts: RunYtdlpOpts): Promise<void> { .map((s) => s.trim()) .filter(Boolean); - const subLangs = opts.channelConfig.subLangs ?? "en.*,live_chat"; + // Without the live chat unless the channel fetches it with the download + // (ChannelConfig.chat): a `later` channel's chats are the backlog job's. + const subLangs = effectiveSubLangs(opts.channelConfig); const matchesSubLang = compileSubLangMatcher(subLangs); const tofetch: string[] = []; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A streaming channel can fetch its live chats after its downloads, by itself.** A stream's chat replay (7–42 MB) came down with its captions and made each YouTube download 2–4× slower while the Ethanalyzer backlog was archived; the fix was a hand edit of `subLangs` and a hand-written watcher that ran `pnpm ops fetch-chat` per streamed episode once the downloads were done — and died on reboot. Configure → **Live chat replay** (`chat`: with the download, Later or Never): with Later the downloads leave the chat out and, once the channel has nothing left to download, the download lane queues one paced **Fetch chat backlog** job for every stream (by its metadata) whose chat is not here, 25 at a time, skipping what landed and the streams known to have none, and resumed after a restart. The Download stage has the button; `pnpm ops fetch-chat-backlog {slug, dryRun?, limit?}` runs it by hand. **Caption languages** (`subLangs`) is a Configure field and a `channel-config` patch key now. Needs a restart of the editor. - **What an import adds is work for the lanes at once, not when the import ends.** On 2026-10-26 an archive.org import added 64 recordings over several hours while the channel's report still listed the 32 it had at 01:10; the transcription lane reads its work from that report, so the 64 waited untranscribed and the GPU went to another site's backlog, and `pnpm ops transcribe-bucket` answered "64 of ids not in the downloadedNoTranscript bucket". An archive.org import, an attach of local media and a persist now regenerate the channel's report as items land (the first at once, then at least every 10 items or 2 minutes), and `transcribe-bucket` regenerates a report that is behind the disk before it answers. Needs a restart of the editor. - **A restart no longer kills the long jobs it interrupts: they resume.** On 2026-10-25/26 one restart stopped an archive.org import (89 files), a feed download-missing (28 episodes) and a forum catch-up, each closed "interrupted" and re-queued by hand. At boot the editor now re-queues every job the previous process left running whose kind continues on a re-run — an archive.org import, an import, a download-missing, a posts fetch, a persist, a clip-window fetch, a transcription batch, a post capture, a cues pass, a report — and its log opens with the job it resumes. A job interrupted twice in a row, a dry run and a full posts re-walk are not resumed, and the old job says why. `pnpm ops job resume-interrupted [--dry-run]` does the same by hand; `jobs.resumeInterruptedOnBoot: false` turns the boot's resume off, and an idle boot never resumes. A job that waited in its queue and then died mid-run is now closed as interrupted too, instead of being re-queued as if it had never started. An archive.org import, a single import and a cues pass gained Retry. Needs a restart of the editor. - **A new caption download is ready for a umtool build the moment it lands.** A YouTube video whose captions were downloaded (the-quartering, 2026-10-23/24) had its `transcript.en-orig.vtt` but no `transcript.cues.json` — only a transcription wrote one, and every older video got its file from the normalize pass — so umtool refused it ("clip-no-cues") until `pnpm ops build-cues` was run by hand. Every successful download, and the Download missing subs pass, now writes the cues file the normalize pass would. Needs a restart of the editor. diff --git a/editor/app/api/ops/fetch-chat-backlog/route.test.ts b/editor/app/api/ops/fetch-chat-backlog/route.test.ts @@ -0,0 +1,42 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/fetch-chat-backlog/route.test.ts" +// +// A channel's stream chats after its downloads (2026-10-26): the dry run counts +// them from the disk with no job; the body is checked before anything. + +const corpus = await setupOpsCorpus(null); +await corpus.writeSettings(); +await corpus.writeChannelConfig("demo-streams", { handling: "youtube", url: "https://www.youtube.com/@demo", chat: "later" }); +const DATA = path.join(corpus.transcripts, "channels", "demo-streams", "data"); +for (const [id, live] of [["stream00001", "was_live"], ["stream00002", "was_live"], ["upload00001", "not_live"]]) { + await mkdir(path.join(DATA, id), { recursive: true }); + await writeFile( + path.join(DATA, id, "metadata.info.json"), + JSON.stringify({ id, title: id, live_status: live, upload_date: "20251001", webpage_url: `https://www.youtube.com/watch?v=${id}` }), + ); +} + +const { POST } = await import("./route"); +test.after(() => corpus.cleanup()); + +test("a dry run counts the streams whose chat is not here, and starts no job", async () => { + const before = await corpus.listJobIds(); + const res = await callPost(POST, { slug: "demo-streams", dryRun: true }); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.chats, 2); + assert.equal(res.body.notStreams, 1); + assert.deepEqual([...(res.body.ids as string[])].sort(), ["stream00001", "stream00002"]); + assert.deepEqual(await corpus.listJobIds(), before); +}); + +test("the body is checked first: a bad limit, a limit on a dry run, an unknown key", async () => { + assert.match(String((await callPost(POST, { slug: "demo-streams", limit: 0 })).body.error), /"limit" must be a whole number above 0/); + assert.match(String((await callPost(POST, { slug: "demo-streams", dryRun: true, limit: 5 })).body.error), /a dry run starts no job/); + assert.equal((await callPost(POST, { slug: "demo-streams", ids: ["x"] })).status, 400); +}); diff --git a/editor/app/api/ops/fetch-chat-backlog/route.ts b/editor/app/api/ops/fetch-chat-backlog/route.ts @@ -0,0 +1,52 @@ +import { NextResponse } from "next/server"; +import { + fetchChatBacklogAction, + previewChatBacklogAction, +} from "../../../channels/[slug]/chatBacklogActions"; +import { jobResponse, OpsInputError, ops, opsFail, optBool, optString, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, dryRun?, limit?, queueKey? } -> { ok: true, jobId } +// | { ok: true, dryRun: true, chats, … } +// +// A channel's stream chats, after its downloads (2026-10-26; +// controller/chatBacklog.ts): every held video whose metadata says it was a +// stream (`live_status` was_live / post_live) and whose chat is not here, one +// at a time through fetch-chat's pass — the channel's cookies, the platform's +// live pace and the batch downloads' gap between two — on the platform's +// download queue. A re-run skips every chat here and every stream known to +// have none (`chat-backlog.json`). `limit` caps the chats this run asks for. +// The download lane queues the same job by itself for a channel whose `chat` +// is "later" once it has nothing left to download. +// +// `dryRun` answers from the disk alone, no job: `chats` (to get, newest +// first; `ids` the first 50), `normalizeOnly` (raw replays already here), +// `have`, `settled` (known to have none), `notStreams`. +// +// Answered without a job, `info: true`: a channel on a platform with no chat +// fetcher, a backlog already queued or running, a held platform or one in a +// rate-limit cooldown. +export async function POST(request: Request) { + return ops(request, ["slug", "dryRun", "limit", "queueKey"], async (body) => { + const slug = reqSlug(body, "slug"); + const limit = body.limit; + if (limit !== undefined && !(typeof limit === "number" && Number.isInteger(limit) && limit > 0)) { + throw new OpsInputError('"limit" must be a whole number above 0'); + } + if (optBool(body, "dryRun")) { + if (limit !== undefined || body.queueKey !== undefined) { + throw new OpsInputError('a dry run starts no job: "limit" and "queueKey" go with a real run'); + } + const preview = await previewChatBacklogAction(slug); + if (!preview.ok) return opsFail(preview.error); + return NextResponse.json({ ...preview, dryRun: true }); + } + return jobResponse( + await fetchChatBacklogAction(slug, { + ...(typeof limit === "number" ? { limit } : {}), + ...(optString(body, "queueKey") ? { queueKey: optString(body, "queueKey") } : {}), + }), + ); + }); +} diff --git a/editor/app/channels/[slug]/chatBacklogActions.ts b/editor/app/channels/[slug]/chatBacklogActions.ts @@ -0,0 +1,67 @@ +"use server"; + +// A CHANNEL'S STREAM CHATS AFTER ITS DOWNLOADS (2026-10-26): the Download +// stage's "Fetch chat backlog" and `pnpm ops fetch-chat-backlog`, over the one +// job controller/chatBacklog.ts makes (the download lane makes the same one +// for a `chat: "later"` channel with nothing left to download). +// +// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file). + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { resolveCookiePolicy } from "yt-dlp-transcript-common/lib/cookiePolicy"; +import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { planChatBacklog, startChatBacklogJob } from "yt-dlp-transcript-common/controller/chatBacklog"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; + +export async function fetchChatBacklogAction( + slug: string, + opts: { limit?: number; queueKey?: string } = {}, +): Promise<StreamActionResult> { + if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` }; + if (opts.limit !== undefined && !(Number.isInteger(opts.limit) && opts.limit > 0)) { + return { ok: false, error: '"limit" must be a whole number above 0' }; + } + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `Channel "${slug}" not found` }; + return startChatBacklogJob({ + paths, + slug, + config, + cookiePolicy: resolveCookiePolicy(getSettings(), config), + ...(opts.limit ? { limit: opts.limit } : {}), + ...(opts.queueKey ? { queueKey: opts.queueKey } : {}), + }); +} + +export type ChatBacklogPreview = + | { + ok: true; + chats: number; + normalizeOnly: number; + have: number; + settled: number; + notStreams: number; + // The first 50, newest first. + ids: string[]; + } + | { ok: false; error: string }; + +// What a run would do, from the disk alone: no request, no job. +export async function previewChatBacklogAction(slug: string): Promise<ChatBacklogPreview> { + if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` }; + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `Channel "${slug}" not found` }; + const plan = await planChatBacklog(paths, slug, config); + return { + ok: true, + chats: plan.candidates.length, + normalizeOnly: plan.candidates.filter((c) => c.action === "normalize").length, + have: plan.have, + settled: plan.settled, + notStreams: plan.notStreams, + ids: plan.candidates.slice(0, 50).map((c) => c.id), + }; +} diff --git a/editor/app/channels/[slug]/components/stages/DownloadStage.tsx b/editor/app/channels/[slug]/components/stages/DownloadStage.tsx @@ -20,6 +20,7 @@ import { downloadMissingSubsAction, } from "../../pipelineActions"; import { RetryBucketControl } from "../RetryBucketControl"; +import { fetchChatBacklogAction } from "../../chatBacklogActions"; import { VideoIdList } from "../VideoIdList"; type Props = { @@ -196,7 +197,7 @@ export function DownloadStage({ // the word, on a page where the other two were a lane and a // per-channel action. Nothing about this shares a queue, a pause or a // counter with the speaker lane. - desc="Fetch missing subtitle tracks (live_chat, alt-language captions) for already-downloaded videos. Reads each video's metadata.info.json for advertised tracks, then re-invokes yt-dlp with --skip-download for any whose expected sub file is missing on disk. Uses the channel's subLangs config (defaults to en.*,live_chat)." + desc="Fetch missing subtitle tracks (live_chat, alt-language captions) for already-downloaded videos. Reads each video's metadata.info.json for advertised tracks, then re-invokes yt-dlp with --skip-download for any whose expected sub file is missing on disk. Uses the channel's caption languages (defaults to en.*,live_chat) — without live_chat when its Live chat replay is Later or Never." /> <label className="flex items-center gap-2 text-sm"> <input @@ -228,6 +229,18 @@ export function DownloadStage({ } /> </div> + <div className="flex flex-col gap-2"> + <Heading + title="Fetch chat backlog" + desc="Fetch the live chat replay of every downloaded stream (metadata live_status was_live) that has none yet, one at a time at the platform's pace, on its download queue. Skips chats already here and streams known to have none; stops on a rate limit and picks up where it stopped when run again. A channel whose Live chat replay is Later gets this from the download lane by itself once it has nothing left to download." + /> + <StreamActionLog + trigger={() => fetchChatBacklogAction(slug)} + cancelAction={cancelJobAction} + buttonLabel="Fetch chat backlog" + runningLabel="Fetching chats…" + /> + </div> <NoTranscriptList slug={slug} ids={noTranscriptIds} diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -819,6 +819,47 @@ export function ChannelForm({ </span> </span> </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium"> + Caption languages{" "} + <span className="text-muted-foreground font-normal"> + (yt-dlp --sub-langs) + </span> + </span> + <SeededInput + state={state} + name="subLangs" + initial={c?.subLangs ?? ""} + placeholder="en.*,live_chat" + aria-label="caption languages" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono" + /> + <span className="text-xs text-muted-foreground"> + Comma-separated; a leading <code>-</code> excludes. Blank ={" "} + <code>en.*,live_chat</code>. + </span> + </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Live chat replay</span> + <SeededSelect + state={state} + name="chat" + initial={c?.chat ?? ""} + aria-label="live chat replay" + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="">With the download — a live_chat caption track</option> + <option value="later"> + Later — downloads skip it; one chat backlog job once downloads are done + </option> + <option value="never">Never — downloads skip it</option> + </SeededSelect> + <span className="text-xs text-muted-foreground"> + A stream&apos;s chat is 7–42 MB and makes its download 2–4× slower. + Later fetches every streamed video&apos;s chat, paced, when the + channel has nothing left to download. + </span> + </label> </Section> <Section title="Retention & persistence"> <label className="flex flex-col gap-1 text-sm"> diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -53,6 +53,9 @@ export const CHANNEL_FORM_VALUES = [ "cookiesFromBrowser", "cookieMode", "storedUrlDownloads", + // Caption languages and when the live chat is fetched (2026-10-26). + "subLangs", + "chat", "downloadFilterInclude", "downloadFilterExclude", "downloadFilterRejectedLivestreams", @@ -122,6 +125,8 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { put(fd, "cookieMode", config.cookieMode); put(fd, "storedUrlDownloads", config.storedUrlDownloads); if (config.browserLookup) fd.set("browserLookup", "on"); + put(fd, "subLangs", config.subLangs); + put(fd, "chat", config.chat); put(fd, "downloadFilterInclude", config.downloadFilter?.include); put(fd, "downloadFilterExclude", config.downloadFilter?.exclude); if (config.downloadFilter?.includeLivestreams) { diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -307,3 +307,28 @@ test("the ops patch round-trips a search channel, its hidden authors kept", () = assert.deepEqual(next.xSearch, { query: "zephyr OR breeze", lang: "en", exclude: ["alice", "bob"] }); assert.equal(next.url, "https://x.com/search?q=zephyr%20OR%20breeze&f=live"); }); + +// 2026-10-26: caption languages and when the live chat comes down are +// Configure fields and `channel-config` patch keys (subLangs could only be set +// offline before). +test("subLangs and chat: parsed, refused when unknown, round-tripped through the ops patch, cleared by empty", () => { + const { config } = parseChannelForm(form({ subLangs: " en.*,es ", chat: "later" })); + assert.equal(config.subLangs, "en.*,es"); + assert.equal(config.chat, "later"); + // The default chat mode is not stored: choosing it clears a stored one. + assert.equal("chat" in parseChannelForm(form({ chat: "with-download" })).config, false); + assert.throws(() => parseChannelForm(form({ chat: "sometimes" })), /Live chat must be one of: with-download, later, never/); + for (const k of ["subLangs", "chat"]) assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes(k), k); + + const fd = channelConfigToFormData({ handling: "youtube", name: "Example VODs", subLangs: "en.*,live_chat" }); + validateChannelFormPatch({ chat: "never" }); + applyChannelFormPatch(fd, { chat: "never" }); + const patched = parseChannelForm(fd).config; + assert.equal(patched.chat, "never"); + assert.equal(patched.subLangs, "en.*,live_chat", "a patch that does not name subLangs keeps it"); + const back = channelConfigToFormData(patched); + applyChannelFormPatch(back, { subLangs: "", chat: "" }); + const cleared = parseChannelForm(back).config; + assert.equal("subLangs" in cleared, false); + assert.equal("chat" in cleared, false); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -46,7 +46,7 @@ import { import { downloadFilterPatternProblem } from "yt-dlp-transcript-common/lib/downloadFilters"; import { recordedDatePatternProblem } from "yt-dlp-transcript-common/lib/recordedDate"; import { mirrorSlugs } from "yt-dlp-transcript-common/lib/mirrors/config"; -import { isRejectedLivestreamMode } from "yt-dlp-transcript-common/lib/channelConfig"; +import { CHAT_MODES, isChatMode, isRejectedLivestreamMode } from "yt-dlp-transcript-common/lib/channelConfig"; import { AUDIO_CHECK_PLATFORMS } from "yt-dlp-transcript-common/lib/audioCheckPolicy"; export type ParsedChannelForm = { @@ -81,6 +81,10 @@ export const CHANNEL_FORM_FIELDS = [ "audioCheck", "storedUrlDownloads", "browserLookup", + // 2026-10-26: Configure fields since then (subLangs could only be set + // offline before, with patchChannelConfig). + "subLangs", + "chat", "downloadFilter", "recordedDate", "mirror", @@ -274,6 +278,15 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { isStoredUrlMode(storedUrlRaw) && storedUrlRaw !== "never" ? storedUrlRaw : undefined; // The browser lookup (release 32 R9): a checkbox; unchecked = omitted. const browserLookup = formData.get("browserLookup") != null; + // Caption languages and the live chat (2026-10-26). Blank = the default + // (`en.*,live_chat`), omitted; "with-download" is the default chat mode, + // omitted too, so choosing it clears a stored mode. + const subLangs = stringOrUndef(formData, "subLangs"); + const chatRaw = String(formData.get("chat") ?? "").trim(); + if (chatRaw && !isChatMode(chatRaw)) { + throw new Error(`Live chat must be one of: ${CHAT_MODES.join(", ")}`); + } + const chat = isChatMode(chatRaw) && chatRaw !== "with-download" ? chatRaw : undefined; // Download filter. Both patterns are regex SOURCES compiled with "i" at // download time, so the form is the place that refuses an unparseable one: @@ -456,6 +469,8 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { if (audioCheck) config.audioCheck = audioCheck; if (storedUrlDownloads) config.storedUrlDownloads = storedUrlDownloads; if (browserLookup) config.browserLookup = true; + if (subLangs) config.subLangs = subLangs; + if (chat) config.chat = chat; if (downloadFilter) config.downloadFilter = downloadFilter; if (recordedDateTitlePattern) { config.recordedDate = { titlePattern: recordedDateTitlePattern }; diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -65,6 +65,7 @@ import { import { fetchWindowsJobAction } from "../channels/[slug]/videos/fetchWindowsAction"; import { browserLookupAction } from "../channels/[slug]/browserLookupActions"; import { normalizeChannelAction } from "../channels/[slug]/normalizeActions"; +import { fetchChatBacklogAction } from "../channels/[slug]/chatBacklogActions"; import { startRefreshReport } from "yt-dlp-transcript-common/jobs/snapshotScheduler"; import type { FetchWindowsItem } from "yt-dlp-transcript-common/controller/fetchWindows"; import { reportsPrepareAction } from "../sites/lib/reportsPrepareAction"; @@ -546,6 +547,15 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { ...(bool(p.force) ? { force: true } : {}), }); }, + // A channel's stream chats: the same cap; a re-run skips every chat here + // and every stream known to have none (2026-10-26). + "fetch-chat-backlog": (spec) => { + const { p, queueKey } = params(spec); + return fetchChatBacklogAction(spec.slug, { + ...(num(p.limit) !== undefined ? { limit: num(p.limit) } : {}), + ...(queueKey ? { queueKey } : {}), + }); + }, // One channel's report, regenerated on the refresh-report queue. "refresh-report": async (spec) => startRefreshReport(getPaths(), spec.slug), "persist-kept": (spec) => { diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -43,6 +43,8 @@ // pnpm ops metadata-scan --json '{"slug":"the-quartering"}' // pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait // pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait +// pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}' +// pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}' // pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait // pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait // pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait @@ -597,6 +599,11 @@ const ACTIONS = [ // result JSON (the project, its URL, the segments) is what stdout carries. "fetch-chat", "find-clips", + // A channel's stream chats after its downloads ({slug, dryRun?, limit?, + // queueKey?}): every held stream whose chat is not here, paced, one at a + // time, as one fetch-chat-backlog job on the platform's download queue; a + // re-run skips what landed. `dryRun` counts them from the disk, no job. + "fetch-chat-backlog", ]; // The log line a transcribe job ends with: this marker, then the result as