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";
// ---------------------------------------------------------------------------
// RECORD -> FILTER -> PREVIEW on the record page (components/projects/RecordSession.tsx, RecordFilter.tsx;
// /api/report/post-narration/record; lib/report/recordPreview.mjs). Fixture: e2e/fixtures/record-filter-fixture.mjs
// -- p-1 and p-2 by @savvy (the spec gives her a character of this video's own: seed-vc, contour +2, a direction),
// p-3 by @stranger (nobody's). The editor is the suite's stub: voice-enhance is not installed, voice-convert copies
// after one poll at the heavy slot ("waiting for memory").
//
// Filter -> the preview (no take), the wait at the heavy slot a state, raw and filtered side by side -> another
// pitch asks for the convert again -> Save to character -> Keep: the takes from the preview's files, the next post
// Again; nobody's post: nothing to convert, Keep in this video only, the recording kept alone
// the microphone off (a page opened over http from the LAN): said, and a sound file filtered and kept all the same
//
// RECORD_FILTER_SHOTS=
screenshots there
// ---------------------------------------------------------------------------
const HERE = path.dirname(fileURLToPath(import.meta.url));
const FIXTURE = path.join(HERE, "..", ".e2e-song");
const P = "reports/record-filter-fixture";
const DIR = path.join(FIXTURE, "reports", "record-filter-fixture");
const MANIFEST = path.join(DIR, "video.manifest.json");
const NARRATION = path.join(DIR, "narration");
const CHARACTERS = path.join(NARRATION, "characters.json");
const SCRATCH = (post: string) => path.join(NARRATION, ".record-preview", `${post}.operator`);
const REQUESTS = path.join(FIXTURE, "editor-stub.requests.json");
const SHOTS = process.env.RECORD_FILTER_SHOTS ?? null;
/** A voice for the fake microphone (and the file chosen where there is none): a 1 kHz tone, two seconds. */
const MIC_WAV = path.join(FIXTURE, "record-filter-mic.wav");
type Take = { file: string; engine?: string; voice?: string; note?: string; seconds: number; source?: { kind: string; from?: string }; steps?: { op: string; engine?: string; voice?: string; pitch?: string; semitones?: number }[] };
type Entry = { id: string; narration?: { script?: string; takes?: Take[]; pick?: number; approved?: boolean } };
const narr = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline.find((e) => e.id === id)!.narration!;
const converts = () => (JSON.parse(readFileSync(REQUESTS, "utf8")) as { route?: string; engine?: string; voice?: string; pitch?: string; semitones?: number; file?: string; out?: string }[]).filter((r) => r.route === "voice-convert");
const characters = () => (JSON.parse(readFileSync(CHARACTERS, "utf8")) as { characters: { id: string; handles?: string[]; recorded?: { convert?: { engine?: string; voice?: string; pitch?: string; semitones?: number } } }[] }).characters;
const shot = async (page: Page, name: string) => {
if (!SHOTS) return;
mkdirSync(SHOTS, { recursive: true });
await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: true });
};
if (!existsSync(MIC_WAV)) {
mkdirSync(FIXTURE, { recursive: true });
execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=1000:sample_rate=48000:duration=2", "-ac", "1", MIC_WAV]);
}
// A fake microphone and audio that may start without a gesture, for the whole file.
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"] } });
test.beforeAll(() => {
if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
});
const reset = () => {
copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
rmSync(NARRATION, { recursive: true, force: true });
rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
};
/** @savvy's character of this video's own: converted by seed-vc to a stock voice, contour +2, a direction to read by. */
const giveSavvy = () => {
mkdirSync(NARRATION, { recursive: true });
writeFileSync(CHARACTERS, `${JSON.stringify({
format: "umtool-project-characters", version: 1,
characters: [{ id: "madam-savvy", name: "Madam Savvy", handles: ["savvy"], synthetic: { voice: "kokoro:af_bella" }, recorded: { convert: { engine: "seed-vc", pitch: "contour", semitones: 2 }, direction: "higher, brisk, amused" } }],
}, null, 2)}\n`);
};
test.beforeEach(async ({ page }) => {
test.setTimeout(180_000);
reset();
// "Filter before keeping" as the page decides it (on for a post whose character converts), whatever a test before left.
await page.addInitScript(() => {
try {
window.localStorage.removeItem("umtool.record.filter-first");
window.localStorage.setItem("umtool.record.count-in", "0");
} catch {
// no storage here
}
});
});
test.afterAll(reset);
const s = (page: Page) => page.locator("[data-record-session]");
/** Space, a second of the fake microphone, Space: the part is on disk. */
const recordPart = async (page: Page) => {
await page.keyboard.press("Space");
await expect(s(page)).toHaveAttribute("data-record-phase", "recording", { timeout: 15_000 });
await page.waitForTimeout(1200);
await page.keyboard.press("Space");
await expect(s(page)).toHaveAttribute("data-record-phase", "idle", { timeout: 15_000 });
};
const filterDone = async (page: Page) => {
await expect(page.locator("[data-record-filter-job]")).toHaveAttribute("data-record-filter-job", "done", { timeout: 90_000 });
};
test("Filter runs the character's recorded preset as one job into a preview (no take); raw and filtered side by side; another pitch; Save to character; Keep makes the takes and opens the next post", async ({ page }) => {
giveSavvy();
await page.setViewportSize({ width: 1366, height: 1100 });
await page.goto(urls.narrationRecordHref(P, { post: "p-1" }));
await expect(s(page)).toHaveAttribute("data-record-session", "p-1");
// Who it is read as, above the record button: the character, its direction, its stock voice to hear.
const who = page.locator("[data-record-character]");
await expect(who).toHaveAttribute("data-record-character", "madam-savvy");
await expect(who).toHaveAttribute("data-record-character-layer", "project");
await expect(page.locator("[data-record-character-name]")).toHaveText("Madam Savvy");
await expect(page.locator("[data-record-direction]")).toContainText("higher, brisk, amused");
await expect(page.locator("[data-record-stock]")).toContainText("kokoro:af_bella reads it");
// Her character converts: the post waits to be filtered. The microphone is here (localhost): no note.
await expect(page.locator("[data-record-review]")).toBeChecked();
await expect(page.locator("[data-record-no-mic]")).toHaveCount(0);
await expect(page.locator("[data-record-review-panel]")).toHaveCount(0);
// Record it: NO take is made -- the waveform with its two cut marks, the pitch from the preset.
await recordPart(page);
const panel = page.locator("[data-record-review-panel]");
await expect(panel).toBeVisible();
await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
expect(narr("p-1").takes ?? []).toHaveLength(0);
await expect(page.locator("[data-record-pitch]")).toHaveValue("contour");
await expect(page.locator("[data-record-semitones]")).toHaveValue("2");
await expect(page.locator("[data-record-keep]")).toHaveAttribute("data-record-keep-what", "recording");
// A cut mark moved (a keyboard click at the start): four presses of the arrow, 0.2 s in.
const from = page.locator('[data-record-mark="from"]');
const markAt = async () => Number(await from.getAttribute("data-record-mark-at"));
const auto = await markAt();
await from.focus();
for (let i = 0; i < 4; i += 1) await page.keyboard.press("ArrowRight");
await expect.poll(markAt).toBeCloseTo(auto + 0.2, 2);
await expect(page.locator("[data-record-span-auto]")).toBeVisible();
await shot(page, "record-filter-marks");
// FILTER (f): one job -- the clean skipped (the stub has no enhance engine), cut, converted; its wait at the heavy
// slot was a state on the way, and nothing failed.
await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
await page.keyboard.press("f");
await expect(page.locator("[data-record-filter-job]")).toBeVisible({ timeout: 15_000 });
await filterDone(page);
const job = page.locator("[data-record-filter-job]");
await expect(job).toHaveAttribute("data-record-filter-waited", /memory/);
await expect(job.locator('[data-record-filter-step="clean"]')).toHaveAttribute("data-record-filter-step-state", "skipped");
await expect(job.locator('[data-record-filter-step="trim"]')).toHaveAttribute("data-record-filter-step-state", "done");
await expect(job.locator('[data-record-filter-step="convert"]')).toHaveAttribute("data-record-filter-step-state", "done");
await expect(page.locator("[data-record-filter-error]")).toHaveCount(0);
// The preview, in the scratch dir; still no take.
expect(existsSync(path.join(SCRATCH("1"), "raw.wav"))).toBe(true);
expect(existsSync(path.join(SCRATCH("1"), "filtered.wav"))).toBe(true);
expect(narr("p-1").takes ?? []).toHaveLength(0);
const asked = converts().at(-1)!;
expect(asked).toMatchObject({ engine: "seed-vc", voice: "kokoro:af_bella", pitch: "contour", semitones: 2 });
expect(asked.file).toMatch(/narration\/\.record-preview\/1\.operator\/raw\.wav$/);
await expect(panel).toHaveAttribute("data-record-preview-current", "1");
await expect(page.locator("[data-record-preview-note]").first()).toContainText("not cleaned");
// Raw and filtered, side by side.
await expect(page.locator("[data-record-compare-what]")).toContainText("converted to kokoro:af_bella by seed-vc · pitch contour +2 st · both at one loudness");
const player = page.locator("[data-record-player]");
await page.locator("[data-record-play-raw]").click();
await expect(player).toHaveAttribute("src", /preview&file=raw/);
await page.locator("[data-record-play-filtered]").click();
await expect(player).toHaveAttribute("src", /preview&file=filtered/);
await shot(page, "record-filter-preview");
// Another pitch: the preview is not of it any more; Filter again asks for the convert, at that pitch.
const before = converts().length;
await page.locator("[data-record-pitch]").selectOption("source");
await expect(panel).toHaveAttribute("data-record-preview-current", "0");
await expect(page.locator("[data-record-preview-stale]")).toBeVisible();
await page.locator("[data-record-filter]").click();
await expect(panel).toHaveAttribute("data-record-preview-current", "1", { timeout: 90_000 });
expect(converts()).toHaveLength(before + 1);
expect(converts().at(-1)).toMatchObject({ pitch: "source", semitones: 2, voice: "kokoro:af_bella" });
await expect(page.locator('[data-record-filter-step="trim"]')).toHaveAttribute("data-record-filter-step-state", "cached");
// Save to character: this video's own character keeps the pitch.
await page.locator("[data-record-save-character]").click();
await expect(page.locator("[data-record-saved]")).toContainText("saved to Madam Savvy (this video's own)");
expect(characters().find((c) => c.id === "madam-savvy")!.recorded!.convert).toMatchObject({ engine: "seed-vc", pitch: "source", semitones: 2 });
await expect(page.locator("[data-record-save-character]")).toBeDisabled();
// KEEP (Enter): the takes from the preview's files -- nothing converted again -- the last picked, awaiting approval;
// the scratch dir and the session are gone; the next post not recorded is open.
const convertsBefore = converts().length;
await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
await page.keyboard.press("Enter");
await expect(s(page)).toHaveAttribute("data-record-session", "p-2", { timeout: 30_000 });
await expect(page.locator("[data-record-last-kept]")).toContainText("kept post 1: recorded (take-1.recorded-operator.wav), converted to kokoro:af_bella (pitch: source +2 st) (take-2.convert-seed-vc.wav)");
const n = narr("p-1");
expect(n.takes).toHaveLength(2);
expect(n.pick).toBe(1);
expect(n.approved).not.toBe(true);
expect(n.takes![0]).toMatchObject({ file: "narration/posts/1/take-1.recorded-operator.wav", engine: "recorded", voice: "operator", note: "recorded for Madam Savvy" });
expect(n.takes![1]).toMatchObject({ file: "narration/posts/1/take-2.convert-seed-vc.wav", engine: "derived", voice: "af_bella", source: { kind: "take", from: "take-1.recorded-operator" } });
expect(n.takes![1].steps![0]).toMatchObject({ op: "convert", engine: "seed-vc", voice: "kokoro:af_bella", pitch: "source", semitones: 2 });
for (const t of n.takes!) expect(existsSync(path.join(DIR, t.file))).toBe(true);
expect(converts()).toHaveLength(convertsBefore);
expect(existsSync(SCRATCH("1"))).toBe(false);
expect(existsSync(path.join(NARRATION, "posts", "1", ".recording-operator"))).toBe(false);
await expect(page.locator('[data-record-jump="p-1"]')).toHaveAttribute("data-record-state", "recorded");
await expect(page.locator("[data-record-progress]")).toHaveAttribute("data-record-progress", "1");
// The next post reads as her too, at the pitch just saved.
await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
await shot(page, "record-filter-kept");
});
test("Again drops the preview and records the part again; nobody's post has nothing to convert: Keep in this video only, and the recording kept alone", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 1100 });
await page.goto(urls.narrationRecordHref(P, { post: "p-3" }));
await expect(s(page)).toHaveAttribute("data-record-session", "p-3");
await expect(page.locator("[data-record-no-character]")).toContainText("no character reads @stranger");
// Nobody converts it: the last part would make the take at once -- until a person asks to filter first.
await expect(page.locator("[data-record-review]")).not.toBeChecked();
await page.locator("[data-record-review]").check();
await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
await recordPart(page);
const panel = page.locator("[data-record-review-panel]");
await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
await expect(page.locator("[data-record-pitch-row]")).toHaveCount(0);
expect(existsSync(path.join(SCRATCH("3"), "p01.raw.wav"))).toBe(true);
// Filter: no clean engine, no character -- it says so, and nothing failed.
await page.locator("[data-record-filter]").click();
await filterDone(page);
await expect(page.locator('[data-record-filter-step="convert"]')).toHaveAttribute("data-record-filter-step-state", "skipped");
await expect(page.locator("[data-record-nothing-filtered]")).toBeVisible();
await expect(page.locator("[data-record-filter-error]")).toHaveCount(0);
const first = readFileSync(path.join(NARRATION, "posts", "3", ".recording-operator", "session.json"), "utf8");
// AGAIN (Backspace): the preview dropped, the part recorded again -- still no take.
await page.keyboard.press("Backspace");
await expect(s(page)).toHaveAttribute("data-record-phase", "recording", { timeout: 15_000 });
expect(existsSync(SCRATCH("3"))).toBe(false);
await page.waitForTimeout(1200);
await page.keyboard.press("Space");
await expect(s(page)).toHaveAttribute("data-record-phase", "idle", { timeout: 15_000 });
await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
await expect(page.locator("[data-record-filter-job]")).toHaveCount(0);
expect(readFileSync(path.join(NARRATION, "posts", "3", ".recording-operator", "session.json"), "utf8")).not.toBe(first);
expect(narr("p-3").takes ?? []).toHaveLength(0);
// Keep in this video only: @stranger gets a character of this video's own.
await page.locator("[data-record-keep-in-video]").click();
await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character-layer", "project", { timeout: 20_000 });
const made = characters().find((c) => (c.handles ?? []).includes("stranger"));
expect(made).toBeTruthy();
await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", made!.id);
await expect(page.locator("[data-record-keep-in-video]")).toHaveCount(0);
// Not filtered: Keep keeps the recording alone -- one recorded take, picked -- and moves on.
await expect(panel).toHaveAttribute("data-record-preview-current", "0");
await expect(page.locator("[data-record-keep]")).toHaveAttribute("data-record-keep-what", "recording");
await page.locator("[data-record-keep]").click();
await expect(s(page)).toHaveAttribute("data-record-session", "p-1", { timeout: 30_000 });
const n = narr("p-3");
expect(n.takes).toHaveLength(1);
expect(n.takes![0]).toMatchObject({ file: "narration/posts/3/take-1.recorded-operator.wav", engine: "recorded" });
expect(n.pick).toBe(0);
expect(existsSync(SCRATCH("3"))).toBe(false);
expect(existsSync(path.join(NARRATION, "posts", "3", ".recording-operator"))).toBe(false);
});
test("opened over http from the LAN the microphone is off, and the page says so; a sound file is filtered and kept all the same; with the filter off the last part makes the take at once", async ({ page }) => {
giveSavvy();
// What a browser gives a page opened over plain http from another machine: no secure context, no microphone.
await page.addInitScript(() => Object.defineProperty(window, "isSecureContext", { get: () => false }));
await page.setViewportSize({ width: 1366, height: 1100 });
await page.goto(urls.narrationRecordHref(P, { post: "p-1" }));
await expect(page.locator("[data-record-no-mic]")).toContainText("The microphone is off on this page");
await expect(page.locator("[data-record-no-mic]")).toContainText("localhost");
await expect(page.locator("[data-record-toggle]")).toBeDisabled();
// Space does not try the microphone.
await page.keyboard.press("Space");
await expect(s(page)).toHaveAttribute("data-record-phase", "idle");
await expect(page.locator("[data-record-error]")).toHaveCount(0);
// A sound file for the part: filtered, previewed and kept as a recording made here would be.
await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
await page.locator("[data-record-file]").setInputFiles(MIC_WAV);
await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
await page.locator("[data-record-filter]").click();
await filterDone(page);
await expect(page.locator("[data-record-review-panel]")).toHaveAttribute("data-record-preview-current", "1");
await page.locator("[data-record-play-filtered]").click();
await expect(page.locator("[data-record-player]")).toHaveAttribute("src", /preview&file=filtered/);
await page.locator("[data-record-keep]").click();
await expect(s(page)).toHaveAttribute("data-record-session", "p-2", { timeout: 30_000 });
expect(narr("p-1").takes!.map((t) => t.engine)).toEqual(["recorded", "derived"]);
await shot(page, "record-filter-lan");
// "Filter before keeping" off: the last part makes the recorded take at once, as before.
await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
await expect(page.locator("[data-record-review]")).toBeChecked();
await page.locator("[data-record-review]").uncheck();
await page.locator("[data-record-file]").setInputFiles(MIC_WAV);
await expect(page.locator("[data-record-status]")).toContainText("take-1.recorded-operator.wav", { timeout: 30_000 });
await expect(page.locator("[data-record-review-panel]")).toHaveCount(0);
expect(narr("p-2").takes).toHaveLength(1);
expect(existsSync(path.join(NARRATION, ".record-preview", "2.operator"))).toBe(false);
});
test("a part recorded again with Space (no Again) and Enter at once: the filtered read of the EARLIER recording is never kept", async ({ page }) => {
giveSavvy();
await page.setViewportSize({ width: 1366, height: 1100 });
await page.goto(urls.narrationRecordHref(P, { post: "p-1" }));
await expect(page.locator("[data-record-character]")).toHaveAttribute("data-record-character", "madam-savvy");
await recordPart(page);
await expect(page.locator('[data-record-wave="1"]')).toBeVisible({ timeout: 20_000 });
await page.locator("[data-record-filter]").click();
await filterDone(page);
await expect(page.locator("[data-record-review-panel]")).toHaveAttribute("data-record-preview-current", "1");
const before = converts().length;
// Space records over the part; Enter the moment it has landed.
await page.locator("[data-record-teleprompter]").click({ position: { x: 2, y: 2 } });
await page.keyboard.press("Space");
await expect(s(page)).toHaveAttribute("data-record-phase", "recording", { timeout: 15_000 });
await page.waitForTimeout(1200);
await page.keyboard.press("Space");
await page.keyboard.press("Enter");
await expect(s(page)).toHaveAttribute("data-record-phase", "idle", { timeout: 15_000 });
// The earlier preview is gone, on the page and on disk; whatever Enter did, no converted take was made.
await expect(page.locator("[data-record-compare]")).toHaveCount(0);
expect(existsSync(path.join(SCRATCH("1"), "filtered.wav"))).toBe(false);
expect((narr("p-1").takes ?? []).filter((t) => t.engine === "derived")).toHaveLength(0);
expect(converts()).toHaveLength(before);
// The server holds the line too: a filtered Keep with no preview of this recording is refused.
const r = await page.request.post("/api/report/post-narration/record", { data: { project: P, id: "p-1", op: "keep", filtered: true } });
if ((narr("p-1").takes ?? []).length === 0) expect(r.status()).toBe(409);
});