import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdtemp, readFile, rm, 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 { jsonReply, startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs"; import { ASSIST_NOTE, writeAssistProject } from "yt-dlp-transcript-common/testing/clips/assistProject.mjs"; import { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft"; import { planVideoAssistJob, type AssistNoteReply, type VideoAssistJobDeps } from "yt-dlp-transcript-common/controller/videoAssist"; import { readAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs"; import { GENERATION_PRESETS, sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { isLocalUsage, readGenerationUsage } 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/_videoAssist.test.ts" // // The `report-draft` task `video-assist` (release 38 lane E) end to end in // this process: the controller the ops route adapts, a synthetic video // project in a temp dir (common/testing/clips/assistProject.mjs), the fake // Anthropic and ollama servers, a temp jobs dir and usage ledger. let tmp: string; let api: FakeAnthropic; let ol: FakeOllama; let paths: Paths; let gen: GenerationSettings; before(async () => { tmp = await mkdtemp(path.join(os.tmpdir(), "video-assist-")); api = await startFakeAnthropic(); ol = await startFakeOllama(); const keyFile = path.join(tmp, "anthropic.env"); await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`); await chmod(keyFile, 0o600); paths = { jobsDir: path.join(tmp, ".jobs"), transcriptsDir: path.join(tmp, "transcripts"), channelsDir: path.join(tmp, "transcripts", "channels"), generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), ollamaUrl: ol.url, } as Paths; gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20, max: 10 }, routes: { ...GENERATION_PRESETS.balanced } }); }); after(async () => { await api.close(); await ol.close(); await rm(tmp, { recursive: true, force: true }); }); const deps = (g: Partial = {}, more: Partial = {}) => ({ paths, corpusTools: async () => { throw new Error("no corpus tools here"); }, settings: () => ({ generation: { ...gen, ...g } }), ...more }) as ReportDraftDeps & VideoAssistJobDeps; const out = (o: Awaited>) => o.result as { ok: boolean; error: string }; async function finished(o: Awaited>) { assert.ok(o.result.ok, (o.result as { error?: string }).error); const job = getRegistry().get(o.result.jobId)!; void o.result.stream.cancel(); const done = await o.result.done; return { job, done, log: await readFile(job.logPath, "utf8") }; } test("the body: a project and a request (or a note), a scope; never an article", () => { assert.throws(() => parseReportDraftBody({ task: "video-assist", request: "x" }), /"project" is the video project's absolute directory/); assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p" }), /needs its "request"/); assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", note: "n_abcd1234" }), /not both/); assert.throws(() => parseReportDraftBody({ task: "video-assist", article: "a", project: "/p", request: "x" }), /not an article/); assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", scope: "everything" }), /"scope" is look, clips, fx or all/); assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", proposals: ["p1"] }), /a clips-suggest job's/); assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", request: "x" }), /"request" is a video-assist job's/); assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", iteration: 2 }), /takes no iteration/); assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", answers: { ops: [] }, model: "m" }), /no "model"/); assert.deepEqual(parseReportDraftBody({ task: "video-assist", project: "/p", request: " quicker joins ", scope: "look", dryRun: true }), { task: "video-assist", article: "", project: "/p", request: "quicker joins", scope: "look", dryRun: true, }); }); test("on the local model (the default route): draft:local through the arbiter, one schema-bound ask, proposals written, ollama unloaded, no ledger row", async () => { const dir = path.join(tmp, "local"); writeAssistProject(dir); assert.equal(gen.routes["video-assist"], "local"); ol.push(jsonReply({ ops: [{ op: "look", id: "", key: "transition", value: 0.15 }, { op: "slide", id: "", key: "blur", value: 0.3 }], reply: "Quicker, less smear." })); const { job, done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, request: "make the joins 0.15 s with less smear" }, deps())); assert.equal(done.status, "done", log); assert.equal(job.queueKey, "draft:local"); assert.match(log, /through the GPU arbiter: it waits for a transcription/); assert.match(log, /proposed: join 0\.22 s → 0\.15 s/); assert.match(log, /unloaded qwen3:8b from ollama/); assert.match(log, /@@report-draft \{"article":"","iteration":0,"task":"video-assist","project":"[^"]+local","status":"done","summary":"2 edits proposed \(join 0\.22 s → 0\.15 s; smear 0\.5 → 0\.3\) on qwen3:8b"/); const { doc } = await readAssistProposals(dir); assert.deepEqual(doc!.diff, ["join 0.22 s → 0.15 s", "smear 0.5 → 0.3"]); assert.ok(ol.unloads.includes("qwen3:8b")); // No spend; the local call is in the ledger at no cost (demo epic D3). const mine = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); assert.equal(mine.filter((r) => !isLocalUsage(r)).length, 0); assert.deepEqual(mine.map((r) => [r.task, r.model, r.route, r.usd, r.calls]), [["video-assist", "qwen3:8b", "local", 0, 1]]); const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); assert.equal(m.render.transition, 0.22, "nothing applied"); }); test("on the API: draft:api, the narration cap, a ledger row as task video-assist", async () => { const dir = path.join(tmp, "api"); writeAssistProject(dir); api.push(toolTurn("answer", { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "QR off." })); const { job, done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, request: "no QR" }, deps({ routes: { ...gen.routes, "video-assist": "api" } }))); assert.equal(done.status, "done", log); assert.equal(job.queueKey, "draft:api"); assert.match(log, /the Claude API, cap \$1\)/); const rows = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); assert.deepEqual(rows.map((r) => [r.task, r.model, r.article, r.iteration]), [["video-assist", "claude-sonnet-5-5", "", 0]]); assert.deepEqual((await readAssistProposals(dir)).doc!.diff, ["QR code on → off"]); }); test("the code route: refused with no answer; the plan is the request; a session's answer runs on no model", async () => { const dir = path.join(tmp, "code"); writeAssistProject(dir); const code = { routes: { ...gen.routes, "video-assist": "code" as const } }; const refused = await enqueueReportDraft({ task: "video-assist", project: dir, request: "no QR" }, deps(code)); assert.ok(!out(refused).ok && /routed to Claude Code/.test(out(refused).error)); const plan = await planVideoAssistJob(parseReportDraftBody({ task: "video-assist", project: dir, request: "no QR", dryRun: true }), deps(code)); assert.equal(plan.provider, "code"); assert.match(plan.request.user, /THE REQUEST:\nno QR/); assert.match(plan.request.user, /- qr = true/); const asked = api.requests.length + ol.requests.length; const { done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, request: "no QR", answers: { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "" } }, deps(code))); assert.equal(done.status, "done", log); assert.equal(api.requests.length + ol.requests.length, asked); assert.equal((await readAssistProposals(dir)).doc!.model, "claude-code"); }); test("Ask on a note on the whole project: its text is the request; the reply posted as the agent's with an assist proposal; nothing applied", async () => { const dir = path.join(tmp, "note"); writeAssistProject(dir, { note: "quicker joins please" }); const nowhere = await enqueueReportDraft({ task: "video-assist", project: dir, note: ASSIST_NOTE }, deps({}, { umtoolUrl: null, workerToken: "t" })); assert.ok(!out(nowhere).ok && /UMTOOL_URL is not set/.test(out(nowhere).error)); const missing = await enqueueReportDraft({ task: "video-assist", project: dir, note: "n_absent00" }, deps({}, { umtoolUrl: "http://x", workerToken: "t" })); assert.ok(!out(missing).ok && /no note n_absent00/.test(out(missing).error)); let prompt = ""; ol.push((body: { messages: { role: string; content: string }[] }) => { prompt = body.messages.find((m) => m.role === "user")!.content; return jsonReply({ ops: [{ op: "look", id: "", key: "transition", value: 0.12 }], reply: "Joins at 0.12 s." }); }); const posted: AssistNoteReply[] = []; const { done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, note: ASSIST_NOTE }, deps({}, { postReply: async (r) => void posted.push(r) }))); assert.equal(done.status, "done", log); assert.match(prompt, /THE REQUEST:\nquicker joins please/); const { doc } = await readAssistProposals(dir); assert.equal(doc!.note, ASSIST_NOTE); assert.deepEqual(posted, [ { project: dir, note: ASSIST_NOTE, text: "Joins at 0.12 s.\nProposed 1 edit — Apply below or in the Build tab's Look panel:\n• join 0.22 s → 0.12 s", proposal: { kind: "assist", at: doc!.at, ops: 1 } }, ]); const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); assert.equal(m.render.transition, 0.22); });