import { test, expect } from "@playwright/test"; import { execFileSync, spawnSync } from "node:child_process"; import { existsSync, readFileSync, readdirSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; // --------------------------------------------------------------------------- // A narrated card (release 25, T2), built through the driver. // // The voice is asked of the EDITOR, never synthesized here: the chain's // narration step posts the card's words to `/api/ops/tts`, follows the job to // its `@@tts-result` line, and keeps the sound in out/narration/; the build // puts it under the card. The editor is the suite's stub // (e2e/fixtures/editor-stub.mjs), whose "voice" is an ffmpeg tone -- what this // proves is that the words, the engine and the voice crossed the wire and the // sound landed under the right card, and that the plain card beside it stayed // silent. // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); const FIXTURE = path.join(HERE, "..", ".e2e-song"); const PROJECT = "reports/narration-fixture"; const OUT = path.join(FIXTURE, "reports", "narration-fixture", "out"); const SEGS = path.join(OUT, "sourced", "segments"); const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); const DISCLOSURE = "Narration: synthetic voice (Kokoro-82M ยท af_heart)"; type Job = { id: string; state: string; error: string | null; events?: { ev: string; id?: string; cached?: boolean }[] }; async function waitFor(request: import("@playwright/test").APIRequestContext, id: string, ms = 180_000): Promise { const until = Date.now() + ms; while (Date.now() < until) { const j = (await (await request.get(`/api/report/build?job=${id}`)).json()) as Job; if (j.state !== "running") return j; await new Promise((r) => setTimeout(r, 400)); } throw new Error("the job never finished"); } /** The loudest sample of a file's sound, in dB; -91 is digital silence. */ function maxVolume(file: string): number { const r = spawnSync("ffmpeg", ["-nostdin", "-hide_banner", "-i", file, "-af", "volumedetect", "-f", "null", "-"], { encoding: "utf8" }); const m = /max_volume:\s*(-?[\d.]+) dB/.exec(r.stderr); return m ? Number(m[1]) : NaN; } const ttsAsks = (): { route?: string; text?: string; engine?: string; voice?: string; speed?: number; authorization?: string }[] => { try { return (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string }[]).filter((r) => r.route === "tts"); } catch { return []; } }; test("the chain asks the editor for the narration before the build", async ({ request }) => { // The stub's log is the suite's: count from here (another spec may have asked before). const before = ttsAsks().length; const r = await request.post("/api/report/build?dry=1", { data: { project: PROJECT, preset: "fast" } }); const j = (await r.json()) as { steps: { label: string; argv: string[] }[] }; const scripts = j.steps.map((s) => path.basename(s.argv[1] ?? "")); const at = scripts.indexOf("narrate-via-editor.mjs"); expect(at).toBeGreaterThan(0); expect(scripts[at + 1]).toBe("build-video.mjs"); // Nothing was asked by a dry run. expect(ttsAsks()).toHaveLength(before); }); test("a narrated card speaks, its length is the narration's, the plain card is silent, and the exports disclose the voice", async ({ request }) => { const before = ttsAsks().length; const start = await request.post("/api/report/build", { data: { project: PROJECT, preset: "fast" } }); expect(start.ok()).toBeTruthy(); const { job } = (await start.json()) as { job: Job }; const done = await waitFor(request, job.id); expect(done.state, done.error ?? "").toBe("done"); // One ask, the words verbatim, the engine and voice named, the token sent. const asks = ttsAsks().slice(before); expect(asks).toHaveLength(1); expect(asks[0]).toMatchObject({ text: "Six months later, the county said yes.", engine: "kokoro", voice: "af_heart", speed: 1, authorization: "Bearer umtool-e2e-token", }); expect((done.events ?? []).some((e) => e.ev === "narrate" && e.id === "k01" && e.cached === false)).toBe(true); // Kept beside the build, with its disclosure. const records = readdirSync(path.join(OUT, "narration")).filter((n) => n.endsWith(".json")); expect(records).toHaveLength(1); const rec = JSON.parse(readFileSync(path.join(OUT, "narration", records[0]), "utf8")) as { disclosure: string; seconds: number }; expect(rec.disclosure).toBe(DISCLOSURE); // "auto": 7 words at the stub's 0.3 s = 2.1 s, plus the lead and the tail (0.8 + 0.8) -> 3.7 s. const seg = JSON.parse(readFileSync(path.join(SEGS, "k01.narration.json"), "utf8")) as { seconds: number }; expect(seg.seconds).toBe(3.7); const dur = Number(execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", path.join(SEGS, "k01.mp4")]).toString()); expect(Math.abs(dur - 3.7)).toBeLessThan(0.15); expect(maxVolume(path.join(SEGS, "k01.mp4"))).toBeGreaterThan(-30); expect(maxVolume(path.join(SEGS, "k02.mp4"))).toBe(-91); for (const format of ["description", "chapters"]) { const text = await (await request.get(`/api/report/export?project=${encodeURIComponent(PROJECT)}&format=${format}`)).text(); expect(text, format).toContain(DISCLOSURE); } expect(existsSync(path.join(OUT, "narration-fixture.mp4"))).toBe(true); }); // --------------------------------------------------------------------------- // The podcast (release 25, T3): the export row's "podcast" renders the built // cut as sound only -- the narrated card's voice and the clip, the plain card // left out -- and offers the files. Runs on the build above. // --------------------------------------------------------------------------- test("the export row renders the cut as a podcast and offers the files", async ({ page, request }) => { await page.goto(urls.section("reports/narration-fixture", "exports")); const row = page.locator('[data-export-variant="sourced"]'); const podcast = row.locator('[data-podcast="sourced"]'); await expect(podcast.getByRole("button", { name: "podcast" })).toBeVisible(); await expect(podcast.locator("[data-podcast-file]")).toHaveCount(0); await podcast.getByRole("button", { name: "podcast" }).click(); await expect(podcast.locator('[data-podcast-file="m4a"]')).toBeVisible({ timeout: 120_000 }); await expect(podcast.locator('[data-podcast-file="mp3"]')).toBeVisible(); await expect(podcast.locator('[data-podcast-file="notes"]')).toBeVisible(); await expect(podcast.getByRole("button", { name: "re-render podcast" })).toBeVisible(); // The m4a: the narrated card and the clip, the silent card left out, with chapters. const m4a = path.join(OUT, "sourced", "podcast.m4a"); const info = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_chapters", "-show_entries", "format=duration:format_tags=comment", "-of", "json", m4a]).toString()) as { chapters: { tags: { title: string } }[]; format: { duration: string; tags?: Record }; }; expect(info.chapters).toHaveLength(2); expect(info.format.tags?.comment).toBe(DISCLOSURE); const rec = JSON.parse(readFileSync(path.join(OUT, "sourced", "podcast.json"), "utf8")) as { left: string[] }; expect(rec.left).toEqual(["k02"]); // Served by name, never by path. const got = await request.get(`/api/report/podcast?project=${encodeURIComponent(PROJECT)}&variant=sourced&file=m4a`); expect(got.status()).toBe(200); expect(got.headers()["content-type"]).toBe("audio/mp4"); const notes = await (await request.get(`/api/report/podcast?project=${encodeURIComponent(PROJECT)}&variant=sourced&file=notes`)).text(); expect(notes).toContain("## Chapters"); expect(notes).toContain("https://archive.example/?v=testchan%2Fvid1&t=9"); expect(notes).toContain(DISCLOSURE); expect((await request.get(`/api/report/podcast?project=${encodeURIComponent(PROJECT)}&variant=sourced&file=../../x`)).status()).toBe(400); });