// Run with: // pnpm -C editor exec tsx --test "app/api/ops/_lookouts.test.ts" // // `pnpm ops get lookouts` and `pnpm ops lookout-run` (the dry run, and the // run's refusals — the run itself is common/controller/lookoutRun.test.ts's, // on a stub model), against the route handlers over a temp corpus. Every // channel and lookout here is invented. Never the live editor's settings. import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, readdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { callGet, callPost, setupOpsCorpus } from "./_testCorpus"; const corpus = await setupOpsCorpus(null); const { GET } = await import("./lookouts/route"); const { POST, GET: GET_RUN } = await import("./lookout-run/route"); const { writeLookoutRun } = await import("yt-dlp-transcript-common/lib/lookoutStore"); test.after(() => corpus.cleanup()); const LOOKOUTS = { enabled: false, afterSync: false, items: [{ id: "example-week", label: "Example week", channels: ["example-news", "no-such-channel"], days: 3, timeZone: "America/New_York" }], }; async function video(slug: string, dir: string, title: string, uploadDate: string, timestamp: number, seconds: number) { const d = path.join(corpus.transcripts, "channels", slug, "data", dir); await mkdir(d, { recursive: true }); await writeFile(path.join(d, "metadata.info.json"), JSON.stringify({ id: dir, title, duration: seconds, upload_date: uploadDate, timestamp })); const cues = Array.from({ length: 40 }, (_, i) => ({ start: i * (seconds / 40), end: (i + 1) * (seconds / 40), text: `${title} line ${i} of ${dir}` })); await writeFile( path.join(d, "transcript.cues.json"), JSON.stringify({ version: 2, id: dir, title, uploadDate, duration: seconds, platform: "youtube", webpageUrl: `https://example.invalid/${dir}`, cues }), ); } test("get lookouts: the saved lookouts and what the store holds for each; nothing configured is an empty list", async () => { const empty = await callGet(GET!, "http://localhost/api/ops/lookouts"); assert.equal(empty.status, 200, JSON.stringify(empty.body)); assert.deepEqual(empty.body.lookouts, []); assert.equal(empty.body.enabled, false); await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); const r = await callGet(GET!, "http://localhost/api/ops/lookouts"); assert.equal(r.status, 200, JSON.stringify(r.body)); const [one] = r.body.lookouts as Record[]; assert.equal(one!.id, "example-week"); assert.equal(one!.maxVideos, 40, "the defaults the settings filled"); assert.equal(one!.lastRun, null); assert.equal(one!.runs, 0); assert.equal(one!.unruled, 0); assert.equal((await callGet(GET!, "http://localhost/api/ops/lookouts?id=nope")).status, 404); assert.equal((await callGet(GET!, "http://localhost/api/ops/lookouts?lookout=x")).status, 400); }); test("lookout-run: the dry run lists what would be read, on air dates, and writes nothing", async () => { await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); await corpus.writeChannelConfig("example-news", {}); // 2026-11-04T01:20:53Z is the evening of 3 Nov in New York. await video("example-news", "Evening0001", "Evening Show", "20261104", 1793755253, 1200); await video("example-news", "Short000001", "A Short", "20261104", 1793790000, 45); const before = await readdir(corpus.transcripts); const r = await callPost(POST!, { id: "example-week", dryRun: true, until: "2026-11-05" }); assert.equal(r.status, 200, JSON.stringify(r.body)); const plan = r.body.plan as { window: { from: string; to: string }; read: { video: string; airDate: string }[]; skipped: { video: string; reason: string }[]; refused: { channel: string }[]; }; assert.deepEqual(plan.window, { from: "2026-11-03", to: "2026-11-05", days: 3, timeZone: "America/New_York" }); assert.deepEqual(plan.read.map((v) => [v.video, v.airDate]), [["Evening0001", "2026-11-03"]]); assert.deepEqual(plan.skipped.map((v) => [v.video, v.reason]), [["Short000001", "under-min-seconds"]]); assert.deepEqual(plan.refused.map((x) => x.channel), ["no-such-channel"]); assert.deepEqual(await readdir(corpus.transcripts), before, "no store, no job, nothing written"); assert.deepEqual(await corpus.listJobIds(), []); }); test("lookout-run refuses before reading anything: lookouts off, an unknown lookout or key, bad overrides", async () => { await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); // The run (no dryRun) with lookouts off: refused, no job. const run = await callPost(POST!, { id: "example-week" }); assert.equal(run.status, 400); assert.match(String(run.body.error), /lookouts are off/); assert.equal((await callPost(POST!, { id: "example-week", dryRun: false })).status, 400); assert.deepEqual(await corpus.listJobIds(), []); // On with a route this build does not read on: refused, no job. await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: { ...LOOKOUTS, enabled: true }, generation: { routes: { lookout: "code" } } }); const code = await callPost(POST!, { id: "example-week" }); assert.equal(code.status, 400); assert.match(String(code.body.error), /routed to Claude Code/); assert.equal((await callPost(POST!, { id: "example-week", model: "claude-haiku-4-5" })).status, 400); assert.equal((await callPost(POST!, { id: "example-week", maxCalls: 99999 })).status, 400); assert.deepEqual(await corpus.listJobIds(), []); await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); assert.equal((await callPost(POST!, { id: "nope", dryRun: true })).status, 404); assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, model: "x" })).status, 400); assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, days: 99 })).status, 400); assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, maxVideos: 0 })).status, 400); assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, until: "11/05/2026" })).status, 400); await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: { items: [{ id: "empty", channels: [] }] } }); const none = await callPost(POST!, { id: "empty", dryRun: true }); assert.equal(none.status, 400); assert.match(String(none.body.error), /names no channels/); }); test("get lookout-run: the latest run whole, or the one named; cancel answers the jobs it cancelled", async () => { await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); const none = await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week"); assert.equal(none.status, 200, JSON.stringify(none.body)); assert.equal(none.body.run, null); assert.deepEqual(none.body.running, []); const run = (runId: string, title: string) => ({ version: 1, lookoutId: "example-week", runId, startedAt: "2026-11-11T12:00:00.000Z", endedAt: "2026-11-11T12:10:00.000Z", status: "done" as const, window: { from: "2026-11-09", to: "2026-11-11", days: 3, timeZone: "UTC" }, model: "stub-local:1b", calls: 3, seconds: 9, selection: null, ideas: [], note: title, }); await writeLookoutRun({ transcriptsDir: corpus.transcripts }, run("20261110T120000Z-aaaa", "older")); await writeLookoutRun({ transcriptsDir: corpus.transcripts }, run("20261111T120000Z-bbbb", "newer")); const latest = await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week"); assert.equal((latest.body.run as { note: string }).note, "newer"); const named = await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week&run=20261110T120000Z-aaaa"); assert.equal((named.body.run as { note: string }).note, "older"); assert.equal((await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week&run=20261109T120000Z-cccc")).status, 404); assert.equal((await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week&run=../x")).status, 400); assert.equal((await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=nope")).status, 404); assert.equal((await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run")).status, 400); assert.equal((await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week&x=1")).status, 400); const cancel = await callPost(POST!, { id: "example-week", cancel: true }); assert.equal(cancel.status, 200, JSON.stringify(cancel.body)); assert.deepEqual(cancel.body.cancelled, [], "nothing running: nothing cancelled"); assert.equal((await callPost(POST!, { id: "example-week", cancel: true, days: 2 })).status, 400); assert.equal((await callPost(POST!, { id: "nope", cancel: true })).status, 404); assert.deepEqual(await corpus.listJobIds(), []); }); test("get lookout-run counts ideas as get lookouts does: a damaged idea is left out and counted", async () => { await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); const { ideaKey } = await import("yt-dlp-transcript-common/lib/lookoutStore"); const moments = [ { channel: "example-news", video: "v1", date: "2026-11-10", start: 10, end: 14, quote: "q" }, { channel: "example-news", video: "v2", date: "2026-11-11", start: 20, end: 24, quote: "q" }, ]; const key = ideaKey(moments)!; const idea = { id: "idea-1", key, workingTitle: "t", angle: "", whyNow: "", kind: "claim", estimatedLengthSec: 8, confidence: "high", confidenceWhy: "", moments, caveats: [], sensitive: false }; await writeLookoutRun({ transcriptsDir: corpus.transcripts }, { version: 1, lookoutId: "example-week", runId: "20261112T120000Z-dddd", startedAt: "2026-11-12T12:00:00.000Z", endedAt: "2026-11-12T12:10:00.000Z", status: "done", window: { from: "2026-11-10", to: "2026-11-12", days: 3, timeZone: "UTC" }, model: "stub-local:1b", calls: 3, seconds: 9, selection: null, ideas: [idea as never, { ...idea, id: "idea-2", moments: [null] } as never, { ...idea, id: "idea-3", moments: [null, ...moments] } as never], }); const r = await callGet(GET_RUN!, "http://localhost/api/ops/lookout-run?id=example-week"); assert.equal(r.status, 200, JSON.stringify(r.body)); const ideas = (r.body.run as { ideas: { id: string; moments: unknown[] }[] }).ideas; assert.deepEqual(ideas.map((i) => i.id), ["idea-1", "idea-3"]); assert.ok(ideas.every((i) => i.moments.length === 2)); assert.equal(r.body.ideasNotSurfaced, 1); const all = await callGet(GET!, "http://localhost/api/ops/lookouts?id=example-week"); assert.equal(all.status, 200, JSON.stringify(all.body)); assert.equal((all.body.lookouts as { lastRun: { ideas: number } }[])[0]!.lastRun.ideas, 2, "the same count"); }); test("cancel is by the job's lookout id: a run of a lookout since removed from settings is still cancelled", async () => { await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); await corpus.writeChannelConfig("example-news", {}); const { enqueueLookoutRun } = await import("yt-dlp-transcript-common/controller/lookoutRun"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); const { sanitizeLookouts } = await import("yt-dlp-transcript-common/lib/lookoutSettings"); const { sanitizeGeneration } = await import("yt-dlp-transcript-common/lib/generationSettings"); let release!: () => void; const gate = new Promise((r) => (release = r)); // A run that never reaches a model: it waits at render mode until released. const out = await enqueueLookoutRun( { id: "example-week", until: "2026-11-05" }, { paths: getPaths(), settings: () => ({ lookouts: sanitizeLookouts({ ...LOOKOUTS, enabled: true }), generation: sanitizeGeneration({ routes: { lookout: "local" }, models: { local: "stub-local:1b" } }) }) as never, ask: () => async () => { await gate; throw new Error("stub: no model in this test"); }, memAvailableMb: async () => 8000, renderHeld: () => null, unload: async () => {}, }, ); assert.ok(out.result.ok, JSON.stringify(out.result)); if (!out.result.ok) return; void out.result.stream.cancel(); // The lookout is removed from settings while its run is live. await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: { enabled: false, items: [] } }); const c = await callPost(POST!, { id: "example-week", cancel: true }); assert.equal(c.status, 200, JSON.stringify(c.body)); assert.deepEqual(c.body.cancelled, [out.result.jobId]); release(); assert.equal((await out.result.done).status, "cancelled"); // Nothing live and not in settings: a 404. assert.equal((await callPost(POST!, { id: "example-week", cancel: true })).status, 404); });