import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { FAKE_KEY, startFakeAnthropic, toolTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs"; import { makeSyntheticPokerStream, pokerTruthAt, SPOKEN_CUES } from "yt-dlp-transcript-common/testing/frames/syntheticPoker.mjs"; import { enqueueFrameScan, frameScanCap, frameScanModel, parseFrameScanBody } from "yt-dlp-transcript-common/controller/frameScan"; import { frameScanSidecar, loadFrameScan } from "yt-dlp-transcript-common/lib/frameScan-server"; import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { appendGenerationUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/_frameScan.test.ts" // // The `frame-scan` job (release 30, lane P) end to end in this process: the // controller the route adapts, a synthetic poker stream (ffmpeg) saved in a // temp saved-video store, its spoken cues on disk, the fake Anthropic server, // a temp jobs dir and usage ledger. const SLUG = "synth-poker"; const ID = "synthstream1"; let tmp: string; let api: FakeAnthropic; let paths: Paths; let gen: GenerationSettings; let videoDir: string; const timesOf = (body: any): number[] => [...JSON.stringify(body.messages[0].content).matchAll(/frame \d+ at (\d+):(\d+)/g)].map((m) => Number(m[1]) * 60 + Number(m[2])); const truthTurn = (body: any) => toolTurn("answer", { frames: timesOf(body).map((t, i) => ({ frame: i + 1, ...pokerTruthAt(t) })) }); before(async () => { tmp = await mkdtemp(path.join(os.tmpdir(), "frame-scan-job-")); api = await startFakeAnthropic(); const keyFile = path.join(tmp, "anthropic.env"); await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`); await chmod(keyFile, 0o600); const channel = path.join(tmp, "channels", SLUG); videoDir = path.join(channel, "data", ID); await mkdir(videoDir, { recursive: true }); await writeFile(path.join(channel, "config.json"), JSON.stringify({ url: "https://rumble.com/c/synth" })); await writeFile(path.join(videoDir, "transcript.cues.json"), JSON.stringify({ cues: SPOKEN_CUES })); const store = path.join(tmp, "saved-videos", SLUG, ID); await mkdir(store, { recursive: true }); const { file } = await makeSyntheticPokerStream(store); await rename(file, path.join(store, "source-media.mp4")); await writeFile(path.join(videoDir, "saved-video.json"), JSON.stringify({ storedAt: "2026-10-15T00:00:00Z", dir: store, file: "source-media.mp4", bytes: 1 })); paths = { jobsDir: path.join(tmp, ".jobs"), channelsDir: path.join(tmp, "channels"), generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), ollamaUrl: "http://127.0.0.1:9", } as Paths; gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20, max: 10 } }); }); // A job's end still writes after its status reads done (its log and sidecar, // and the report regeneration it arms in the channel dir): waited for before // the corpus is removed (testing/jobs/quiesce.ts). const { quiesceJobs } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); after(async () => { await quiesceJobs(); await api.close(); await rm(tmp, { recursive: true, force: true }); }); const deps = (g: Partial = {}) => ({ paths, settings: () => ({ generation: { ...gen, ...g } }) }); test("the body: a video and a profile; numbers as numbers within their ranges", () => { assert.throws(() => parseFrameScanBody({}), /"slug"/); assert.throws(() => parseFrameScanBody({ slug: "a", id: "../x" }), /"id"/); assert.throws(() => parseFrameScanBody({ slug: "a", id: "b", profile: "chess" }), /"profile" is one of poker/); assert.throws(() => parseFrameScanBody({ slug: "a", id: "b", everySeconds: 0 }), /everySeconds/); assert.throws(() => parseFrameScanBody({ slug: "a", id: "b", from: 50, to: 10 }), /"to" must be after "from"/); assert.throws(() => parseFrameScanBody({ slug: "a", id: "b", framesPerAsk: 12 }), /framesPerAsk/); assert.deepEqual(parseFrameScanBody({ slug: "a", id: "b", hero: " Synth ", maxUsd: 2 }), { slug: "a", id: "b", profile: "poker", hero: "Synth", maxUsd: 2 }); }); test("the model is the route's; code needs a named one; the cap is within caps.max", () => { assert.equal(frameScanModel(gen), "claude-haiku-4-5"); assert.equal(frameScanModel({ ...gen, routes: { ...gen.routes, frames: "local" } }), "qwen2.5vl:7b"); assert.throws(() => frameScanModel({ ...gen, routes: { ...gen.routes, frames: "code" } }), /name a "model"/); assert.equal(frameScanModel({ ...gen, routes: { ...gen.routes, frames: "code" } }, "claude-haiku-5-5"), "claude-haiku-5-5"); assert.equal(frameScanCap(gen), 5); assert.equal(frameScanCap({ ...gen, frames: { ...gen.frames, maxUsd: 50 } }), 10); assert.throws(() => frameScanCap(gen, 11), /over the settings' max/); }); test("a video that is not saved is refused, naming the persist-videos body", async () => { await mkdir(path.join(paths.channelsDir, SLUG, "data", "notsaved1"), { recursive: true }); const out = await enqueueFrameScan({ slug: SLUG, id: "notsaved1" }, deps()); assert.ok("result" in out && !out.result.ok); assert.match((out.result as { error: string }).error, /no saved video .* pnpm ops persist-videos --json '\{"items":\[\{"slug":"synth-poker","id":"notsaved1"\}\],"format":"original"\}'/); }); test("an API scan: a frame-scan job on `frames`, the sidecar beside the video, the cache in data//frames, the spend in the ledger", async () => { for (let i = 0; i < 10; i++) api.push(truthTurn); const out = await enqueueFrameScan({ slug: SLUG, id: ID, hero: "SynthHero" }, deps()); assert.ok("model" in out && out.result.ok, JSON.stringify(out)); assert.equal(out.queueKey, "frames"); const job = getRegistry().get(out.result.jobId)!; assert.equal(job.kind, "frame-scan"); assert.equal(job.channelSlug, SLUG); void out.result.stream.cancel(); const done = await out.result.done; const log = await readFile(job.logPath, "utf8"); assert.equal(done.status, "done", log); assert.match(log, /@@frame-scan \{"slug":"synth-poker","id":"synthstream1","profile":"poker","file":"frame-scan.poker.json","frames":21,/); assert.ok(!log.includes(FAKE_KEY)); const rec = (await loadFrameScan(videoDir, "poker"))!; assert.ok(rec.derived.events.some((e) => e.kind === "double-up" && e.t === 90)); assert.deepEqual(rec.derived.flags.map((f) => f.t), [125]); // A classic channel (no media/): the cache is in data//frames/poker. const cache = path.join(videoDir, "frames", "poker"); assert.ok((await readdir(cache)).some((f) => f.endsWith(".jpg"))); const rows = await readGenerationUsage(paths.generationUsageFile); assert.deepEqual(rows.map((r) => [r.task, r.model, r.jobId]), [["frame-scan", "claude-haiku-4-5", out.result.jobId]]); assert.ok(rows[0]!.usd > 0); // Evict: the cache goes, the sidecar stays; a re-run decodes again and asks nothing. const ev = await enqueueFrameScan({ slug: SLUG, id: ID, evict: true }, deps()); assert.ok("evicted" in ev && ev.evicted.removed && ev.evicted.bytes > 0); await assert.rejects(stat(cache)); const asked = api.requests.length; const again = await enqueueFrameScan({ slug: SLUG, id: ID }, deps()); assert.ok("model" in again && again.result.ok); void again.result.stream.cancel(); assert.equal((await again.result.done).status, "done"); assert.equal(api.requests.length, asked); assert.equal((await loadFrameScan(videoDir, "poker"))!.runs.length, 2); }); test("a tiered channel (media/ beside data/): the cache is on the media side", async () => { await mkdir(path.join(paths.channelsDir, SLUG, "media"), { recursive: true }); try { for (let i = 0; i < 4; i++) api.push(truthTurn); const out = await enqueueFrameScan({ slug: SLUG, id: ID, everySeconds: 60 }, deps()); assert.ok("model" in out && out.result.ok, JSON.stringify(out)); void out.result.stream.cancel(); assert.equal((await out.result.done).status, "done"); assert.ok((await readdir(path.join(paths.channelsDir, SLUG, "media", ID, "frames", "poker"))).some((f) => f.endsWith(".jpg"))); } finally { await rm(path.join(paths.channelsDir, SLUG, "media"), { recursive: true, force: true }); } }); test("past the day's cap an API scan is refused; a local route goes on draft:local", async () => { await appendGenerationUsage(paths.generationUsageFile, [ { at: new Date().toISOString(), day: utcDay(), jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 }, ]); const refused = await enqueueFrameScan({ slug: SLUG, id: ID }, deps()); assert.ok("result" in refused && !refused.result.ok); assert.match((refused.result as { error: string }).error, /daily cap/); // The local route: queued on draft:local (its ollama is not there: the job fails, the queue is the point). const local = await enqueueFrameScan({ slug: SLUG, id: ID, model: "qwen2.5vl:7b", everySeconds: 600 }, deps()); assert.ok("model" in local && local.result.ok); assert.equal(local.queueKey, "draft:local"); void local.result.stream.cancel(); await local.result.done; }); test("rederive: the derived timeline worked out again from the stored readings, no job and no model; refused with no sidecar", async () => { const sidecar = frameScanSidecar("poker"); const rec = (await loadFrameScan(videoDir, "poker"))!; // An old derivation (any shape the rules once made), and the API asked nothing new. await sidecar.write(videoDir, { ...rec, derived: { tournaments: [], events: [], segments: [], flags: [], misreads: [] } }); const asked = api.requests.length; const out = await enqueueFrameScan({ slug: SLUG, id: ID, rederive: true }, deps()); assert.ok("rederived" in out, JSON.stringify(out)); assert.equal(out.rederived.before.tournaments, 0); assert.equal(out.rederived.after.tournaments, 1); assert.ok((out.rederived.eventsByKind.bust ?? 0) >= 1, JSON.stringify(out.rederived.eventsByKind)); assert.equal(api.requests.length, asked); const again = (await loadFrameScan(videoDir, "poker"))!; assert.equal(again.readings.length, rec.readings.length); assert.equal(again.costUsd, rec.costUsd); assert.ok(again.rederivedAt); const none = await enqueueFrameScan({ slug: SLUG, id: "notsaved1", rederive: true }, deps()); assert.ok("result" in none && !none.result.ok); assert.match((none.result as { error: string }).error, /no frame-scan\.poker\.json to re-derive/); assert.throws(() => parseFrameScanBody({ slug: "a", id: "b", rederive: true, evict: true }), /one at a time/); });