import { test, expect, type Page } from "@playwright/test";
import { execFileSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import * as urls from "./urls";
// ---------------------------------------------------------------------------
// A POST's SCREENS ON THE POST BENCH (report-to-video/post-screens.mjs; knobs.md, "Screens: a post's text screenshots";
// operator, 12 Nov: "The 'read text screenshots as posts' ability in different variations should be first class"):
// - the bench's screens section adds a screen in the post's video, takes pasted lines, a line not read, an excerpt,
// the transcription checked -- saved by the bench's Save through the item's one writer, no model anywhere;
// - a narrated item whose read reads the screen draws it on the card after its words: typeset, its line being read
// lit, "· transcribed" in its header and on the card's badge while it is up;
// - a read line RECORDED in the operator's voice (lane/screens-2; the fake microphone's tone, never a real voice):
// Record / Stop / play back / Keep (one job: recorded, then converted by the stub editor to the speaker's
// character's stock voice -- none picked), the take CHOSEN for the line in its select and saved, then "Make the
// read" (one job): the read plays the chosen take in the line's place. Recording is off while the draft is unsaved.
// Fixture: e2e/fixtures/post-narration-fixture.mjs's p-11 (a 4 s video, a 2 s take), rewritten here.
//
// POST_SCREENS_SHOTS=
screenshots there
// ---------------------------------------------------------------------------
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPORTS = path.join(HERE, "..", ".e2e-song", "reports");
const DIR = path.join(REPORTS, "post-narration-fixture");
const MANIFEST = path.join(DIR, "video.manifest.json");
const PROJECT = "reports/post-narration-fixture";
const SHOTS = process.env.POST_SCREENS_SHOTS ?? null;
/** The fake microphone's voice: a 1 kHz tone, two seconds (never a real recording). */
const MIC_WAV = path.join(HERE, "..", ".e2e-song", "post-screens-mic.wav");
const CHARACTERS = path.join(DIR, "narration", "characters.json");
if (!existsSync(MIC_WAV)) {
mkdirSync(path.dirname(MIC_WAV), { recursive: true });
execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=48000:duration=2", "-ac", "1", MIC_WAV]);
}
test.use({ launchOptions: { args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", `--use-file-for-fake-audio-capture=${MIC_WAV}`, "--autoplay-policy=no-user-gesture-required"] } });
type Line = { who?: string; side?: string; text: string; time?: string; redact?: boolean };
type Screen = { id: string; media: number; at?: number[]; kind: string; lines: Line[]; read: unknown; checked?: { by: string } };
const item = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; screens?: Screen[] }> }).timeline.find((e) => e.id === id);
test.beforeAll(() => {
if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
if (existsSync(CHARACTERS) && !existsSync(`${CHARACTERS}.pristine`)) copyFileSync(CHARACTERS, `${CHARACTERS}.pristine`);
});
const restoreCharacters = () => {
if (existsSync(`${CHARACTERS}.pristine`)) copyFileSync(`${CHARACTERS}.pristine`, CHARACTERS);
else rmSync(CHARACTERS, { force: true });
};
test.beforeEach(() => {
test.setTimeout(120_000);
copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
rmSync(path.join(DIR, "notes.json"), { force: true });
restoreCharacters();
});
test.afterAll(() => {
if (existsSync(`${MANIFEST}.pristine`)) copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
restoreCharacters();
});
const panel = (page: Page) => page.locator("[data-post-screens-panel]");
test("the bench's screens: add one in the video, paste its lines, leave one unread, trim an excerpt, mark it checked -- Save writes it", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 1100 });
await page.goto(urls.postBenchHref(PROJECT, "p-11"));
await expect(panel(page)).toBeVisible({ timeout: 15_000 });
await expect(panel(page)).toHaveAttribute("data-screens", "0");
await panel(page).locator("[data-post-screens-add]").click();
const sc = page.locator('[data-post-screen="s1"]');
await expect(sc).toBeVisible();
await expect(sc.locator("[data-post-screen-kind]")).toHaveValue("dm");
// In the video: the seconds it is visible.
await sc.locator("[data-post-screen-at-from]").fill("0.5");
await sc.locator("[data-post-screen-at-to]").fill("3.5");
await expect(sc.locator("[data-post-screen-scrub] video")).toHaveCount(1);
// Pasted lines: who: words | time, her side by hand, a line with a shape the card masks.
await sc.locator("[data-post-screen-paste]").fill(
["TheQuartering: what's your email so I can refund your order | 11:32 AM", "[right] narrsubject: where is my scale video | 11:53 AM", "TheQuartering: you HONESTLY believe that I have lied about weight loss?", "- reply to support@coffee.example"].join("\n"),
);
await sc.locator("[data-post-screen-paste-add]").click();
await expect(sc.locator("[data-post-screen-line]")).toHaveCount(4);
await expect(sc.locator('[data-post-screen-masked="3"]')).toContainText("email");
// Line 3 not read; line 2 read as an excerpt.
await sc.locator('[data-post-screen-read="3"]').uncheck();
await sc.locator('[data-post-screen-excerpt="2"]').fill("I have lied about weight loss");
await sc.locator("[data-post-screen-checked]").check();
await expect(panel(page).locator("[data-post-screens-errors]")).toHaveCount(0);
await expect(panel(page).locator("[data-post-screens-read-cmd]")).toContainText("umtool posts screen reports/post-narration-fixture p-11 read");
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-screens-bench.png"), fullPage: true });
await page.locator("[data-post-bench-save]").click();
await expect.poll(() => item("p-11")?.screens?.length ?? 0).toBe(1);
const saved = item("p-11")!.screens![0];
expect(saved.at).toEqual([0.5, 3.5]);
expect(saved.lines.map((l) => `${l.who ?? "-"}|${l.side ?? "auto"}|${l.time ?? ""}`)).toEqual(["TheQuartering|auto|11:32 AM", "narrsubject|right|11:53 AM", "TheQuartering|auto|", "-|auto|"]);
expect(saved.read).toEqual([{ line: 0 }, { line: 1 }, { line: 2, text: "I have lied about weight loss" }]);
expect(saved.checked?.by).toBe("operator");
// The lint's word: its read does not read it yet.
await expect(panel(page).locator("[data-post-screens-warnings]")).toContainText("does not read screen s1");
// An excerpt that is not the line's own words is refused on the page before Save.
await page.locator('[data-post-screen="s1"] [data-post-screen-excerpt="2"]').fill("I lied about weight");
await expect(panel(page).locator("[data-post-screens-errors]")).toContainText("is not a run of line 2's words");
});
test("a read that reads the screen draws it on the card after its words: typeset, the line read lit, transcribed in its header and on the badge", async ({ page }) => {
// Its 2 s take, its parts' roles stored: his words, then the screen's two lines.
const m = JSON.parse(readFileSync(MANIFEST, "utf8"));
const e = m.timeline.find((x: { id: string }) => x.id === "p-11");
e.screens = [{ id: "s1", media: 0, at: [0.5, 3.5], kind: "dm", read: "all", lines: [{ who: "TheQuartering", text: "hop on the scale fatso", time: "12:18 PM" }, { who: "narrsubject", text: "you first" }] }];
e.narration.script = "The video speaks for itself.";
e.narration.takes[0].parts = [
{ n: 1, para: 0, text: "The video speaks for itself.", start: 0, seconds: 0.6, role: "post" },
{ n: 2, para: 100, text: "hop on the scale fatso", start: 0.8, seconds: 0.5, role: "screen:s1:0" },
{ n: 3, para: 200, text: "you first", start: 1.5, seconds: 0.5, role: "screen:s1:1" },
];
e.redact = false;
writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
await page.setViewportSize({ width: 1366, height: 1100 });
await page.goto(urls.postBenchHref(PROJECT, "p-11"));
const frame = page.frameLocator('[data-post-card-frame="read"]');
await expect(frame.locator("body")).toHaveAttribute("data-post-ready", "1", { timeout: 15_000 });
await expect(frame.locator('[data-post-screen="s1"]')).toHaveCount(1);
await expect(frame.locator('[data-post-screen="s1"] [data-screen-transcribed]')).toContainText("transcribed");
await expect(frame.locator('[data-post-screen="s1"] .stitle')).toContainText("DMs shown in Narr Subject's video");
// Its second line being read (the item's 0.4 s lead + 1.5 s): lit, the badge up.
await page.locator("[data-post-bench-scrub]").fill("2.1");
await expect(async () => {
const op = await frame.locator('[data-screen-badge="s1"]').evaluate((el) => Number(getComputedStyle(el).opacity));
expect(op).toBeGreaterThan(0.9);
}).toPass({ timeout: 10_000 });
await expect(frame.locator('[data-screen-badge="s1"]')).toContainText("DMs · transcribed");
const opOf = (n: number) => frame.locator(`[data-screen-line="${n}"] .sbub`).evaluate((el) => Number(getComputedStyle(el).opacity || "1"));
await expect(async () => {
expect(await opOf(1)).toBeGreaterThan(0.95);
expect(await opOf(0)).toBeLessThan(0.9);
}).toPass({ timeout: 10_000 });
// Shown by name: the item says redact: false.
await expect(frame.locator('[data-screen-line="0"] .sname')).toHaveText("TheQuartering");
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-screens-card.png") });
});
type Take = { file: string; engine?: string; voice?: string; script?: string; steps?: Array<{ op: string; voice?: string }>; screenLine?: { screen: string; n: number; said: string; speaker: string }; parts?: Array<{ role?: string; take?: string }> };
type Narr = { pick?: number; script?: string; takes: Take[] };
const narrOf = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<{ id: string; narration: Narr; screens?: Array }> }> }).timeline.find((e) => e.id === id)!;
const idOf = (t: Take) => t.file.split("/").pop()!.replace(/\.wav$/, "");
test("a read line in your own voice: Record / Stop / Keep (one job, none picked), the take chosen for the line and saved, Make the read plays it in the line's place", async ({ page }) => {
test.setTimeout(180_000);
const m = JSON.parse(readFileSync(MANIFEST, "utf8"));
const e = m.timeline.find((x: { id: string }) => x.id === "p-11");
e.screens = [{ id: "s1", media: 0, at: [0.5, 3.5], kind: "dm", read: "all", lines: [{ who: "TheQuartering", text: "hop on the scale fatso call 555 201 4477" }, { who: "narrsubject", text: "you first" }] }];
writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
// TheQuartering's character in this video: a stock voice to convert to.
mkdirSync(path.dirname(CHARACTERS), { recursive: true });
writeFileSync(CHARACTERS, JSON.stringify({ format: "umtool-project-characters", version: 1, characters: [{ id: "tq", name: "Jeremy", handles: ["thequartering"], synthetic: { voice: "kokoro:am_michael" }, recorded: { convert: { engine: "openvoice", voice: "kokoro:am_michael" } } }] }));
const before = narrOf("p-11").narration;
await page.setViewportSize({ width: 1366, height: 1100 });
await page.goto(urls.postBenchHref(PROJECT, "p-11"));
const sc = page.locator('[data-post-screen="s1"]');
await expect(sc).toBeVisible({ timeout: 15_000 });
// What you read: the line as the read says it -- the number masked out.
await expect(sc.locator('[data-post-screen-prompt="0"]')).toContainText("hop on the scale fatso call");
await expect(sc.locator('[data-post-screen-prompt="0"]')).not.toContainText("555");
// Unsaved: recording is off (a line is recorded as it is saved).
await sc.locator('[data-post-screen-time="1"]').fill("12:19 PM");
await expect(sc.locator('[data-post-screen-record="0"]')).toBeDisabled();
await expect(sc.locator('[data-post-screen-record-save-first="0"]')).toBeVisible();
await sc.locator('[data-post-screen-time="1"]').fill("");
await expect(sc.locator('[data-post-screen-record="0"]')).toBeEnabled();
// Record, Stop, play back, Keep.
await sc.locator('[data-post-screen-record="0"]').click();
await expect(sc.locator('[data-post-screen-recording="0"]')).toBeVisible();
await page.waitForTimeout(1200);
await sc.locator('[data-post-screen-record-stop="0"]').click();
await expect(sc.locator('[data-post-screen-record-playback="0"]')).toHaveCount(1);
await sc.locator('[data-post-screen-record-keep="0"]').click();
await expect(panel(page).locator('[data-post-screens-job="line"]')).toHaveAttribute("data-post-screens-job-state", "done", { timeout: 90_000 });
const n1 = narrOf("p-11").narration;
const made = n1.takes.slice(before.takes.length);
expect(made.length).toBeGreaterThanOrEqual(2);
expect(made.every((t) => t.screenLine?.screen === "s1" && t.screenLine?.n === 0 && t.screenLine?.speaker === "TheQuartering")).toBe(true);
expect(made.every((t) => !/555|4477/.test(String(t.script)))).toBe(true);
expect(made.at(-1)!.steps?.[0]?.op).toBe("convert");
expect(n1.pick ?? 0).toBe(before.pick ?? 0);
await expect(panel(page).locator("[data-post-screens-voice-status]")).toContainText("none picked");
// Not chosen: the lint says so; choose the converted take, Save.
await expect(panel(page).locator("[data-post-screens-warnings]")).toContainText("has a recording no read uses");
const converted = idOf(made.at(-1)!);
await sc.locator('[data-post-screen-line-take="0"]').selectOption(converted);
await page.locator("[data-post-bench-save]").click();
await expect.poll(() => narrOf("p-11").screens?.[0]?.lineTakes?.["0"] ?? null).toBe(converted);
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-screens-voice.png"), fullPage: true });
// Make the read: the chosen take in the line's place, the rest synthesized (the stub editor's tts).
await panel(page).locator("[data-post-screens-make-read]").click();
await expect(panel(page).locator('[data-post-screens-job="read"]')).toHaveAttribute("data-post-screens-job-state", "done", { timeout: 120_000 });
const n2 = narrOf("p-11").narration;
const playing = n2.takes[n2.pick ?? 0];
expect(playing.parts?.find((p) => p.role === "screen:s1:0")?.take).toBe(converted);
expect(playing.parts?.some((p) => p.role === "screen:s1:1" && !p.take)).toBe(true);
});
test("a read older than its screen is not played on the bench: the item plays silent and says why (review round 1, M1)", async ({ page }) => {
// Its read reads the screen's two lines; then line 0's words are edited under it (the writer takes it).
const m = JSON.parse(readFileSync(MANIFEST, "utf8"));
const e = m.timeline.find((x: { id: string }) => x.id === "p-11");
e.screens = [{ id: "s1", media: 0, at: [0.5, 3.5], kind: "dm", read: "all", lines: [{ who: "TheQuartering", text: "call me at 555 201 4477 fatso" }, { who: "narrsubject", text: "you first" }] }];
e.narration.script = "The video speaks for itself.";
e.narration.takes[0].parts = [
{ n: 1, para: 0, text: "The video speaks for itself.", start: 0, seconds: 0.6, role: "post" },
{ n: 2, para: 100, text: "hop on the scale fatso", start: 0.8, seconds: 0.5, role: "screen:s1:0", line: "hop on the scale fatso", speaker: "TheQuartering" },
{ n: 3, para: 200, text: "you first", start: 1.5, seconds: 0.5, role: "screen:s1:1", line: "you first", speaker: "narrsubject" },
];
writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
await page.setViewportSize({ width: 1366, height: 1100 });
await page.goto(urls.postBenchHref(PROJECT, "p-11"));
const player = page.locator('[data-post-play="p-11"]').first();
await expect(player).toHaveAttribute("data-post-read-refused", "1", { timeout: 15_000 });
await expect(player.locator("[data-post-read-refused-reason]")).toContainText("make the read again");
await expect(player).not.toHaveAttribute("data-post-narrated", "1");
await expect(player.locator("[data-post-narration-audio]")).toHaveCount(0);
// The card page draws no screen (no read reads it) and never the old lit lines.
const frame = page.frameLocator('[data-post-card-frame="read"]');
await expect(frame.locator("body")).toHaveAttribute("data-post-ready", "1", { timeout: 15_000 });
await expect(frame.locator('[data-post-screen="s1"]')).toHaveCount(0);
});