// The frame scan end to end over a synthetic stream (ffmpeg-made, in a temp // dir) and the fake model servers: sampling, duplicates, the reads with real // JPEGs as image blocks, the cap, resume, the derivation. No real model. import { test, before, after } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readdir, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { errorTurn, imagesOf, startFakeAnthropic, toolTurn, type FakeAnthropic } from "../../testing/llm/fakeAnthropic.mjs"; import { imagesOf as ollamaImagesOf, jsonReply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs"; import { makeSyntheticPokerStream, pokerTruthAt, SPOKEN_CUES } from "../../testing/frames/syntheticPoker.mjs"; import { duplicatesOf } from "./dhash"; import { batchArgs, batchesOf, gridOf, readFrameIndex, sampleFrames } from "./sample-server"; import { claudeImageTokens, jpegSize, runFrameScan } from "./scan"; import type { FrameScanRecord } from "../frameScan-server"; let dir = ""; let video = ""; before(async () => { dir = await mkdtemp(path.join(os.tmpdir(), "frame-scan-")); video = (await makeSyntheticPokerStream(dir)).file; }); after(async () => { await rm(dir, { recursive: true, force: true }); }); // The fake model: each ask's frame times from its text, each frame read as the // synthetic client shows it at that time. const timesOf = (body: { messages: { content: unknown }[] }): number[] => { const c = body.messages[0].content; const text = typeof c === "string" ? c : (c as { type: string; text?: string }[]).filter((b) => b.type === "text").map((b) => b.text).join(""); return [...text.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) })) }); function memoryStore() { let rec: FrameScanRecord | null = null; let writes = 0; return { load: async () => rec, write: async (r: FrameScanRecord) => { rec = JSON.parse(JSON.stringify(r)); writes++; }, get: () => rec, writes: () => writes, }; } test("gridOf and batchesOf: grid times in source seconds, batches on the grid", () => { assert.deepEqual(gridOf(5, 40, 10), [5, 15, 25, 35]); assert.deepEqual(gridOf(0, 0, 10), []); assert.deepEqual(batchesOf([0, 10, 20, 30, 40], 10, 20), [[0, 10], [20, 30], [40]]); const args = batchArgs({ source: "in.mp4", start: 30, seconds: 60, every: 10, width: 1280, outPattern: "o/%06d.jpg", keyframesOnly: true }); assert.ok(args.includes("nokey")); assert.ok(args.join(" ").includes("fps=1/10")); assert.equal(args.indexOf("-ss") < args.indexOf("-i"), true); }); test("claudeImageTokens and jpegSize", () => { assert.equal(claudeImageTokens(1280, 720), 1229); assert.ok(claudeImageTokens(3840, 2160) <= 1534); assert.equal(jpegSize(Buffer.from("not a jpeg")), null); }); test("sampleFrames: one ffmpeg a batch, JPEGs at the profile's width, a hash each; a re-run decodes nothing", async () => { const cache = path.join(dir, "cache-sample"); const idx = await sampleFrames({ source: video, dir: cache, from: 0, to: 210, every: 10, width: 640, batchSeconds: 100 }); assert.equal(idx.frames.length, 21); assert.deepEqual(idx.frames.slice(0, 3).map((f) => f.t), [0, 10, 20]); const files = (await readdir(cache)).filter((f) => f.endsWith(".jpg")); assert.equal(files.length, 21); // Static stretches hash alike; a change of picture does not. const dup = duplicatesOf(idx.frames.map((f) => f.hash), { maxBits: 2, rereadEvery: 6 }); assert.equal(dup[1], 0); // lobby 10 s = lobby 0 s assert.equal(dup[3], null); // the table at 30 s assert.equal(dup[4], 3); assert.equal(dup[9], null); // the double-up at 90 s const kept = dup.filter((d) => d === null).length; assert.ok(kept >= 7 && kept <= 10, `kept ${kept}`); // The index is reused: a re-run with an ffmpeg that cannot run still answers. const again = await sampleFrames({ source: video, dir: cache, from: 0, to: 210, every: 10, width: 640, batchSeconds: 100, ffmpeg: "/nonexistent/ffmpeg" }); assert.deepEqual(again.frames, idx.frames); assert.equal((await readFrameIndex(cache))?.frames.length, 21); }); test("a scan on the API: images as JPEG blocks, readings, the derived timeline, the spend; a re-run asks nothing", async () => { const api: FakeAnthropic = await startFakeAnthropic({ turns: Array.from({ length: 20 }, () => truthTurn) }); const store = memoryStore(); const cache = path.join(dir, "cache-api"); const logs: string[] = []; try { const opts = { profile: "poker", source: video, cacheDir: cache, everySeconds: 10, model: "claude-haiku-4-5", llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, maxUsd: 1, cues: SPOKEN_CUES, hints: { hero: "SynthHero" }, onLog: (l: string) => logs.push(l), now: () => new Date("2026-10-15T12:00:00Z"), }; const out = await runFrameScan(opts, store); const r = out.record; // Every ask carried real 1280-px JPEGs, at most four, with the frame times in its text. assert.ok(api.requests.length >= 2); for (const body of api.requests) { const imgs = imagesOf(body); assert.ok(imgs.length >= 1 && imgs.length <= 4); for (const im of imgs) { assert.equal(im.mediaType, "image/jpeg"); assert.equal(im.width, 1280); } assert.equal(imgs.length, timesOf(body).length); assert.match(JSON.stringify(body.system), /SynthHero/); } assert.equal(r.sampling.frames, 21); assert.equal(r.readings.length, r.sampling.kept); assert.equal(r.sampling.skippedDuplicates, 21 - r.sampling.kept); assert.equal(r.duplicates.length, r.sampling.skippedDuplicates); assert.equal(out.run.read, r.sampling.kept); assert.equal(out.run.failed, 0); assert.ok(out.run.costUsd > 0 && r.costUsd === out.run.costUsd); assert.equal(r.model.model, "claude-haiku-4-5"); assert.equal(r.source.savedVideo, path.basename(video)); const d = r.derived; const events = d.events.map((e) => [e.t, e.kind]); assert.deepEqual(events.filter(([, k]) => k !== "buy-in"), [ // Release 31: the lobby's 120 left, then the table header's 85 — under 100. [30, "players-left"], [90, "double-up"], [120, "big-loss"], // No final table at 120: the frames' 9 left is flagged against the spoken // "four players left", and a flagged reading makes no event. [180, "bust"], [180, "eliminated"], ]); assert.ok(events.some(([t, k]) => k === "buy-in" && t === 35)); assert.equal(d.tournaments.length, 1); assert.equal(d.tournaments[0].name, "Synthetic Cup"); assert.deepEqual(d.tournaments[0].series.stack, [[30, 20000], [90, 41000], [120, 9000], [180, 0]]); assert.deepEqual(d.segments.map((s) => s.phase), ["lobby", "table", "break", "table", "lobby"]); // The spoken "four players left" against the frames' 9: flagged, not trusted. assert.deepEqual(d.flags.map((f) => [f.t, f.field, f.spoken, f.frame]), [[125, "playersLeft", 4, 9]]); // Again: every kept frame is read, so nothing is asked. const asked = api.requests.length; const again = await runFrameScan(opts, store); assert.equal(api.requests.length, asked); assert.equal(again.run.read, 0); assert.equal(again.record.runs.length, 2); assert.equal(again.record.costUsd, out.run.costUsd); } finally { await api.close(); } }); test("the cap stops a scan before an ask that would pass it; the next run reads the rest", async () => { const api = await startFakeAnthropic({ turns: Array.from({ length: 20 }, () => truthTurn) }); const store = memoryStore(); try { const base = { profile: "poker", source: video, cacheDir: path.join(dir, "cache-cap"), everySeconds: 10, model: "claude-haiku-4-5", llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, framesPerAsk: 1, }; // About one ask's worth (~$0.0035 estimated a frame on Haiku 4.5). const first = await runFrameScan({ ...base, maxUsd: 0.005 }, store); assert.equal(first.run.stopped, "cap"); assert.ok(first.run.read >= 1 && first.run.read < first.record.sampling.kept, `read ${first.run.read}`); assert.ok(first.run.costUsd <= 0.005); const second = await runFrameScan({ ...base, maxUsd: 1 }, store); assert.equal(second.run.stopped, undefined); assert.equal(first.run.read + second.run.read, second.record.sampling.kept); } finally { await api.close(); } }); test("three failed asks in a row stop a scan, and nothing is recorded as read", async () => { const api = await startFakeAnthropic({ turns: [errorTurn(400, "invalid_request_error", "this model does not take images"), errorTurn(400, "invalid_request_error", "no"), errorTurn(400, "invalid_request_error", "no")] }); const store = memoryStore(); try { const out = await runFrameScan( { profile: "poker", source: video, cacheDir: path.join(dir, "cache-err"), everySeconds: 30, model: "claude-haiku-4-5", llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, maxRetries: 0 } }, maxUsd: 1, framesPerAsk: 1, }, store, ); assert.equal(out.run.stopped, "errors"); assert.equal(out.run.failed, 3); assert.equal(out.record.readings.length, 0); } finally { await api.close(); } }); test("a scan on a local vision model: one frame an ask, as `images`, under the prompt cap", async () => { const ol = await startFakeOllama({ models: ["qwen2.5vl:7b"], turns: Array.from({ length: 30 }, () => (body: any) => { const t = [...String(body.messages[1].content).matchAll(/frame \d+ at (\d+):(\d+)/g)].map((m) => Number(m[1]) * 60 + Number(m[2])); return jsonReply({ frames: t.map((x, i) => ({ frame: i + 1, ...pokerTruthAt(x) })) }); }), }); const store = memoryStore(); try { const out = await runFrameScan( { profile: "poker", source: video, cacheDir: path.join(dir, "cache-local"), everySeconds: 20, model: "qwen2.5vl:7b", llm: { ollama: { baseUrl: ol.url } }, maxUsd: Number.POSITIVE_INFINITY, }, store, ); assert.equal(out.run.failed, 0); assert.equal(out.run.costUsd, 0); assert.equal(ol.requests.length, out.run.read); for (const body of ol.requests) { const imgs = ollamaImagesOf(body); assert.equal(imgs.length, 1); assert.equal(imgs[0].width, 1280); } assert.ok(out.record.derived.events.some((e) => e.kind === "bust")); } finally { await ol.close(); } }); test("maxFrames bounds a scan's range and says so", async () => { const api = await startFakeAnthropic({ turns: Array.from({ length: 5 }, () => truthTurn) }); try { const out = await runFrameScan( { profile: "poker", source: video, cacheDir: path.join(dir, "cache-max"), everySeconds: 10, maxFrames: 5, model: "claude-haiku-4-5", llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, maxUsd: 1, }, memoryStore(), ); assert.equal(out.run.stopped, "maxFrames"); assert.equal(out.record.sampling.frames, 5); assert.equal(out.record.sampling.to, 50); } finally { await api.close(); } }); test("fresh: every frame read again (another model), the runs and the spend kept; a crop is hashed and read", async () => { const api = await startFakeAnthropic({ turns: Array.from({ length: 30 }, () => truthTurn) }); const store = memoryStore(); try { const base = { profile: "poker", source: video, cacheDir: path.join(dir, "cache-fresh"), everySeconds: 30, model: "claude-haiku-4-5", llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, maxUsd: 1, crop: [0, 0.25, 1, 0.5] as [number, number, number, number], }; const first = await runFrameScan(base, store); const asked = api.requests.length; assert.ok(first.run.read > 0); for (const body of api.requests) for (const im of imagesOf(body)) assert.deepEqual([im.width, im.height], [1280, 360]); assert.deepEqual(first.record.sampling.crop, [0, 0.25, 1, 0.5]); const again = await runFrameScan({ ...base, model: "claude-haiku-5-5", fresh: true }, store); assert.equal(again.run.read, first.run.read); assert.ok(api.requests.length > asked); assert.equal(again.record.runs.length, 2); assert.ok(again.record.costUsd > first.record.costUsd); assert.equal(again.record.model.model, "claude-haiku-5-5"); } finally { await api.close(); } });