// `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; downloadedOf?: (slug: string) => Promise; isActive?: (slug: string) => boolean; start?: (slug: string, config: ChannelConfig, downloadedAtRun: number | undefined) => Promise; }; // 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(); constructor(private readonly deps: Required) {} 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; holding: boolean }; onLog?: (line: string) => void; }, ): Promise { 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; } }