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 { TranscribeFileRequest, TranscribeFileResult } from "./transcribeFile"; import type { FindClipsDeps } from "./findClips"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/findClips.test.ts // // THE CHAIN END TO END WITH STUBS (release 36, lane A): the editor's ops // actions (a door that writes what each job would leave), the job registry // (every job done), the word timings (a fake engine result), diarization (a // started job that writes diarization.json) and umtool (a fetch that answers // the clips route's contract). No yt-dlp, no engine, no network. Every case // is its own video in one temp corpus. const ROOT = await mkdtemp(path.join(tmpdir(), "find-clips-")); 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 { getSettings } = await import("../lib/settings"); const { FIND_CLIPS_RESULT_MARKER, enqueueFindClips, parseFindClipsBody, planFindClipsSteps, inspectFindClips, projectSlugFor, runFindClips, } = await import("./findClips"); const { loadFindClipsRecord } = await import("../lib/findClipsRecord-server"); const paths = getPaths(); test.after(() => rm(ROOT, { recursive: true, force: true })); const SLUG = "synth-react"; const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig; await mkdir(path.join(CORPUS, "channels", SLUG), { recursive: true }); await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG)); const SETTINGS_ON = () => { const s = getSettings(); return { ...s, diarization: { ...s.diarization, enabled: true, segModel: "/m/seg.onnx", embModel: "/m/emb.onnx" }, autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, held: false } }, }; }; const SEGMENTS = [ { id: "s1", from: 290, to: 6300, subject: 4, host: 1, why: "subject 4 holds 81% of long-turn time" }, { id: "s2", from: 6500, to: 9278, subject: 16, host: 1, why: "subject 16 holds 77% of long-turn time" }, ]; async function video(id: string, platformUrl = `https://www.youtube.com/watch?v=${id}`): Promise { const dir = path.join(CORPUS, "channels", SLUG, "data", id); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: "Synth stream", webpage_url: platformUrl, was_live: true })); return dir; } // Everything a finished chain leaves on disk, so every step is skipped. async function complete(dir: string) { await writeFile(path.join(dir, "source-media.mp4"), "container"); await writeFile(path.join(dir, "audio.mp3"), "audio"); await writeFile(path.join(dir, "transcript.json"), JSON.stringify({ transcription: [] })); await writeFile(path.join(dir, "words.json"), JSON.stringify({ version: 1, words: [{ w: "hello", start: 1, end: 1.4 }] })); await writeFile(path.join(dir, "transcript.live_chat.json"), "\n"); await writeFile(path.join(dir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [] })); await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] })); } type Harness = { deps: FindClipsDeps; actions: { action: string; args: Record }[]; umtoolCalls: { method: string; url: string; body?: unknown; auth?: string | null }[]; words: TranscribeFileRequest[]; diarized: number; log: string[]; }; function harness(dir: string, o: { umtool?: "ok" | "down" | "refuses" | "fails" | "busy" | "exists"; paused?: boolean; pauseHeld?: string[]; chatFails?: boolean } = {}): Harness { const h: Harness = { actions: [], umtoolCalls: [], words: [], diarized: 0, log: [], deps: null as unknown as FindClipsDeps }; let n = 0; const editor = { async run(action: string, args: Record) { h.actions.push({ action, args }); if (action === "persist-videos") await writeFile(path.join(dir, "source-media.mp4"), "container"); if (action === "transcribe-one") await writeFile(path.join(dir, "transcript.json"), JSON.stringify({ transcription: [] })); if (action === "fetch-chat") { if (o.chatFails) throw new Error("youtube is in a rate-limit cooldown (300s remaining)"); await writeFile(path.join(dir, "transcript.live_chat.json"), "\n"); await writeFile(path.join(dir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [] })); } return { ok: true, jobId: `j${++n}` }; }, }; let polls = 0; const fetchStub = (async (input: string | URL | Request, init?: RequestInit) => { const url = String(input); const method = init?.method ?? "GET"; const auth = new Headers(init?.headers).get("authorization"); h.umtoolCalls.push({ method, url, ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}), auth }); if (o.umtool === "down") throw new TypeError("fetch failed (ECONNREFUSED)"); if (method === "POST") { if (o.umtool === "refuses") return Response.json({ error: "no diarization.json for synth-react/v" }, { status: 400 }); if (o.umtool === "exists") return Response.json({ error: "project v-clips already exists" }, { status: 409 }); if (o.umtool === "busy" && h.umtoolCalls.filter((c) => c.method === "POST").length < 3) { return Response.json({ error: "a job is already running (clips-analyze)", running: { id: "u0" } }, { status: 409 }); } return Response.json({ ok: true, jobId: "u1", job: { id: "u1" }, project: "v-clips", created: true, segments: SEGMENTS, segment: "s1", scope: [290, 6300], href: "/projects/v-clips/clips", notes: ["words.json copied in"], }); } polls++; if (polls === 1) return Response.json({ state: "running", log: ["analyze: laughs 12"], next: 1 }); if (o.umtool === "fails") return Response.json({ state: "failed", error: "CED-mini exited 1", log: [], next: 1 }); return Response.json({ state: "done", log: ["propose: 18 clips, 612 s"], next: 2 }); }) as typeof fetch; h.deps = { paths, editor, jobOf: async () => ({ status: "done" }), umtoolUrl: "http://127.0.0.1:9", workerToken: "tok", fetch: fetchStub, settings: SETTINGS_ON, pool: { isPaused: () => o.paused === true, enabledIds: () => (o.paused ? [] : ["gpu"]), pauseHeldIds: () => o.pauseHeld ?? (o.paused ? ["gpu"] : []), }, transcribeWords: async (req) => { h.words.push(req); return { version: 1, path: req.path, window: null, worker: { id: "gpu", name: "GPU", appId: "parakeet", model: "m.gguf", device: null }, transcriptFormat: "chough-json", transcribedAt: "2026-10-19T00:00:00.000Z", durationMs: 10, waitedMs: 0, cues: [{ start: 1, end: 2, text: "hello world" }], text: "hello world", words: [ { w: "hello", start: 1, end: 1.4 }, { w: "world", start: 1.5, end: 2 }, ], } satisfies TranscribeFileResult; }, diarize: async () => { h.diarized++; await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] })); return { ok: true, jobId: "d1", stream: new ReadableStream(), done: Promise.resolve({ status: "done" as const, jobId: "d1" }) }; }, pollMs: 1, sleep: async () => {}, }; return h; } const run = (h: Harness, id: string, extra: Record = {}) => runFindClips({ slug: SLUG, id, ...extra }, h.deps, { config: CONFIG, onLog: (l) => h.log.push(l), signal: new AbortController().signal, }); test("the body: slug and id required; target, segment, project and the flags checked", () => { assert.match((parseFindClipsBody({}) as { error: string }).error, /"slug" is required/); assert.match((parseFindClipsBody({ slug: SLUG }) as { error: string }).error, /"id" is required/); assert.match((parseFindClipsBody({ slug: SLUG, id: "v", target: 3 }) as { error: string }).error, /"target"/); assert.match((parseFindClipsBody({ slug: SLUG, id: "v", segment: "s 2" }) as { error: string }).error, /"segment"/); assert.match((parseFindClipsBody({ slug: SLUG, id: "v", project: "Bad_Slug" }) as { error: string }).error, /"project"/); assert.match((parseFindClipsBody({ slug: SLUG, id: "v", whilePaused: "yes" }) as { error: string }).error, /"whilePaused"/); assert.deepEqual(parseFindClipsBody({ slug: SLUG, id: "v", target: 600.4, segment: "s2", whilePaused: true, dryRun: false }), { ok: true, value: { slug: SLUG, id: "v", target: 600, segment: "s2", whilePaused: true }, }); assert.equal(projectSlugFor("fGSRhEWc9M4"), "fgsrhewc9m4-clips"); assert.equal(projectSlugFor("fGSRhEWc9M4", "s2"), "fgsrhewc9m4-clips-s2"); }); test("every step run: each in order, named in the log, outputs written, umtool followed", async () => { const id = "runAll00001"; const dir = await video(id); const h = harness(dir); const r = await run(h, id, { target: 600, whilePaused: true }); assert.deepEqual( h.actions.map((a) => a.action), ["persist-videos", "transcribe-one", "fetch-chat"], ); assert.deepEqual(h.actions[0].args, { items: [{ slug: SLUG, id }] }); assert.deepEqual(h.actions[1].args, { slug: SLUG, id, whilePaused: true }); assert.equal(h.words.length, 1); assert.equal(h.words[0].words, true); assert.equal(h.words[0].whilePaused, true); assert.equal(h.words[0].path, path.join(dir, "source-media.mp4"), "the container when no audio file is here"); assert.equal(h.diarized, 1); // words.json: the result without cues and text. const words = JSON.parse(await readFile(path.join(dir, "words.json"), "utf8")); assert.equal(words.words.length, 2); assert.ok(!("cues" in words) && !("text" in words)); // umtool: the contract's body, the worker token, then the job followed. const post = h.umtoolCalls[0]; assert.equal(post.method, "POST"); assert.equal(post.url, "http://127.0.0.1:9/api/report/clips"); assert.equal(post.auth, "Bearer tok"); assert.deepEqual(post.body, { mode: "new", slug: "runall00001-clips", from: `${SLUG}/${id}`, target: 600, scope: "auto", wordsPath: path.join(dir, "words.json"), }); assert.match(h.umtoolCalls[1].url, /\?job=u1&since=0$/); assert.match(h.umtoolCalls[2].url, /\?job=u1&since=1$/); const text = h.log.join("\n"); for (const line of [ /running: saved video — no saved video/, /running: corpus transcript — no corpus transcript/, /running: word timings — transcribing source-media\.mp4 with word timings/, /running: chat replay — fetching the chat replay/, /running: diarization — no diarization\.json/, /running: umtool — finding the segments and the clips/, /umtool: analyze: laughs 12/, /umtool: propose: 18 clips, 612 s/, ]) { assert.match(text, line); } assert.equal(r.project, "v-clips"); assert.equal(r.url, "http://127.0.0.1:9/projects/v-clips/clips"); assert.equal(r.created, true); assert.equal(r.segment, "s1", "the segment auto-scope chose"); assert.match(text, /umtool: made project v-clips \(segment s1\) \(job u1\)/); assert.match(text, /umtool: note: words\.json copied in/); assert.deepEqual(r.segments.map((s) => s.id), ["s1", "s2"]); assert.deepEqual(r.steps.map((s) => s.action), ["ran", "ran", "ran", "ran", "ran", "ran"]); }); test("every step skipped: nothing asked of the editor or an engine; umtool still asked", async () => { const id = "skipAll0001"; const dir = await video(id); await complete(dir); const h = harness(dir); const r = await run(h, id, { segment: "s2" }); assert.deepEqual(h.actions, []); assert.equal(h.words.length, 0); assert.equal(h.diarized, 0); const text = h.log.join("\n"); for (const line of [ /skipped: saved video — saved video present/, /skipped: corpus transcript — transcript\.json present/, /skipped: word timings — words\.json present \(1 words\)/, /skipped: chat replay — live_chat\.cues\.json present/, /skipped: diarization — diarization\.json present/, /running: umtool — finding clips in segment s2/, ]) { assert.match(text, line); } assert.deepEqual(h.umtoolCalls[0].body, { mode: "new", slug: "skipall0001-clips-s2", from: `${SLUG}/${id}`, segment: "s2", wordsPath: path.join(dir, "words.json"), }); assert.equal(r.segment, "s2"); assert.deepEqual(r.steps.map((s) => s.action), ["skipped", "skipped", "skipped", "skipped", "skipped", "ran"]); }); test("umtool down, refusing, or failing: a clear failure naming the step", async () => { for (const [mode, re] of [ ["down", /^step umtool: umtool at http:\/\/127\.0\.0\.1:9 did not answer \(fetch failed \(ECONNREFUSED\)\) — is it running\?$/], ["refuses", /^step umtool: umtool refused the clips request \(HTTP 400\): no diarization\.json/], ["fails", /^step umtool: umtool job u1 failed: CED-mini exited 1$/], ["exists", /^step umtool: umtool refused the clips request \(HTTP 409\): project v-clips already exists$/], ] as const) { const id = `um${mode}`.padEnd(11, "0"); const dir = await video(id); await complete(dir); await assert.rejects(run(harness(dir, { umtool: mode }), id), { message: re }); } }); test("a busy umtool (409 naming its running job) is waited for, then asked again", async () => { const id = "umbusy00001"; const dir = await video(id); await complete(dir); const h = harness(dir, { umtool: "busy" }); const r = await run(h, id); assert.equal(r.project, "v-clips"); assert.equal(h.umtoolCalls.filter((c) => c.method === "POST").length, 3); assert.equal(h.log.filter((l) => /umtool is busy \(a job is already running \(clips-analyze\)\); waiting for it/.test(l)).length, 1); }); test("a twitch video skips the chat with the sentence; a refused chat fetch is logged and the chain goes on", async () => { const tw = await video("twitch00001", "https://www.twitch.tv/videos/123"); await complete(tw); await rm(path.join(tw, "live_chat.cues.json")); await rm(path.join(tw, "transcript.live_chat.json")); const h = harness(tw); await run(h, "twitch00001"); assert.match(h.log.join("\n"), /skipped: chat replay — no chat fetcher for twitch: only YouTube's chat replay is fetched/); assert.deepEqual(h.actions, []); const yt = await video("chatfail001"); await complete(yt); await rm(path.join(yt, "live_chat.cues.json")); await rm(path.join(yt, "transcript.live_chat.json")); const h2 = harness(yt, { chatFails: true }); const r = await run(h2, "chatfail001"); assert.match(h2.log.join("\n"), /the chat was not fetched \(step chat replay: fetch-chat refused: youtube is in a rate-limit cooldown/); assert.equal(r.project, "v-clips", "the chain finished without the chat"); }); test("a paused pool fails the transcription step at once unless the run is whilePaused", async () => { const id = "paused00001"; const dir = await video(id); await writeFile(path.join(dir, "source-media.mp4"), "container"); await assert.rejects(run(harness(dir, { paused: true }), id), { message: /^step corpus transcript: the transcription workers are paused — run it with "while paused"/ }); // Paused, flagged, but no worker the pause alone switched off. await assert.rejects( run(harness(dir, { paused: true, pauseHeld: [] }), id, { whilePaused: true }), { message: /^step corpus transcript: the workers are paused and none was switched off by the pause alone/ }, ); const h = harness(dir, { paused: true }); await run(h, id, { whilePaused: true }); assert.equal(h.actions.find((a) => a.action === "transcribe-one")?.args.whilePaused, true); assert.equal(h.words[0].whilePaused, true); }); test("diarization off or the backfill lane held fails the step with where to fix it", async () => { const id = "diar0000001"; const dir = await video(id); await complete(dir); await rm(path.join(dir, "diarization.json")); const off = harness(dir); off.deps.settings = () => getSettings(); await assert.rejects(run(off, id), { message: /^step diarization: diarization is switched off, or its models are not set — set it up on \/operations\/diarization$/ }); const held = harness(dir); held.deps.settings = () => { const s = SETTINGS_ON(); return { ...s, autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, held: true } } }; }; await assert.rejects(run(held, id), { message: /^step diarization: the backfill lane is held, and it holds a diarization run too — run Find clips "while paused"/ }); // whilePaused: the one-video diarization in this job, the lane left held. let inline = 0; held.deps.diarizeInline = async () => { inline++; await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] })); return "diarized"; }; await run(held, id, { whilePaused: true }); assert.equal(inline, 1); assert.equal(held.diarized, 0, "the lane job was not asked"); assert.match(held.log.join("\n"), /running: diarization — no diarization\.json: diarizing this one video in this job \(the backfill lane stays held\)/); // An engine that fails names its outcome. await rm(path.join(dir, "diarization.json")); held.deps.diarizeInline = async () => "failed"; await assert.rejects(run(held, id, { whilePaused: true }), { message: /^step diarization: the one-video diarization ended "failed"$/ }); }); test("the dry run plans every step from the disk; the job writes find-clips.json and ends with the marker", async () => { const id = "dryrun00001"; const dir = await video(id); await writeFile(path.join(dir, "transcript.json"), "{}"); const state = await inspectFindClips(paths, SLUG, id, CONFIG); assert.deepEqual( planFindClipsSteps(state, {}).map((s) => [s.id, s.run]), [["persist", true], ["transcript", false], ["words", true], ["chat", true], ["diarization", true], ["umtool", true]], ); const h = harness(dir); const dry = await enqueueFindClips({ slug: SLUG, id, dryRun: true }, h.deps); assert.ok(dry.dryRun); assert.equal(dry.plan.steps.length, 6); assert.deepEqual(h.actions, [], "a dry run asks nothing"); // Refusals before a job. const noUmtool = await enqueueFindClips({ slug: SLUG, id }, { ...h.deps, umtoolUrl: null }); assert.ok(!noUmtool.dryRun && !noUmtool.result.ok && /UMTOOL_URL is not set/.test(noUmtool.result.error)); const noVideo = await enqueueFindClips({ slug: SLUG, id: "nope" }, h.deps); assert.ok(!noVideo.dryRun && !noVideo.result.ok && /not a video of synth-react/.test(noVideo.result.error)); const noChannel = await enqueueFindClips({ slug: "no-such-channel", id }, h.deps); assert.ok(!noChannel.dryRun && !noChannel.result.ok && /not found/.test(noChannel.result.error)); const out = await enqueueFindClips({ slug: SLUG, id }, h.deps); assert.ok(!out.dryRun && out.result.ok, JSON.stringify(out)); void out.result.stream.cancel(); const done = await out.result.done; assert.equal(done.status, "done"); const record = await loadFindClipsRecord(dir); assert.ok(record); assert.equal(record.project, "v-clips"); assert.equal(record.url, "http://127.0.0.1:9/projects/v-clips/clips"); assert.equal(record.jobId, out.result.jobId); assert.deepEqual(record.segments.map((s) => s.id), ["s1", "s2"]); const log = await readFile(path.join(paths.jobsDir, `${out.result.jobId}.log`), "utf8"); const line = log.split("\n").find((l) => l.startsWith(FIND_CLIPS_RESULT_MARKER)); assert.ok(line, log); assert.equal(JSON.parse(line.slice(FIND_CLIPS_RESULT_MARKER.length)).umtoolJob, "u1"); });