import { test, expect } from "@playwright/test";
import { copyFileSync, existsSync, readFileSync, readdirSync, rmSync } from "node:fs";
import { createHash } from "node:crypto";
import path from "node:path";
import { fileURLToPath } from "node:url";
import * as urls from "./urls";
import { TUNING_LINE } from "./fixtures/tuning-fixture.mjs";
// ---------------------------------------------------------------------------
// A CHARACTER's ORPHEUS TUNING, in its preset on the Voices page (lane character-tuning, S2 of
// plans/orpheus-retune.md; components/projects/CharacterTuning.tsx, /api/report/voices, lib/report/castCli.mjs
// `cast set|try|stale`). Fixture: e2e/fixtures/tuning-fixture.mjs -- this video's own "teller" (orpheus · tara) and
// three reads of it (made with the defaults; with its line's own tuning; recorded). Every step a press:
//
// Lively fills the numbers; a number edited is "custom"
// the line it reads in this project, prefilled; Read it (pressed twice: one job) -> a job (the stub editor's tts)
// -> a try, reading 0; Another reading -> reading 1, then 2 -- counted from the line as it is said, not as typed
// another job running: said in place, the buttons open again when it ends; a job umtool no longer knows: failed
// Keep these settings (takes 3 typed) -> umtool cast project
set: the preset says the tuning kept, the note
// beside it, the takes field as stored; an unsaved edit above it stays
// the route refuses a flag as a character and a tuning value that is not a number
// the read made with the defaults is now one made with other settings (listed, never re-made)
// and nothing the cut shows changed: the manifest, every drawn card, no take
// ---------------------------------------------------------------------------
const HERE = path.dirname(fileURLToPath(import.meta.url));
const FIXTURE = path.join(HERE, "..", ".e2e-song");
const P = "reports/tuning-fixture";
const DIR = path.join(FIXTURE, "reports", "tuning-fixture");
const MANIFEST = path.join(DIR, "video.manifest.json");
const CHARACTERS = path.join(DIR, "narration", "characters.json");
const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
type Tts = { route: string; text?: string; engine?: string; voice?: string; tuning?: Record; reading?: number };
const ttsAsks = () => (existsSync(STUB_LOG) ? (JSON.parse(readFileSync(STUB_LOG, "utf8")) as Tts[]) : []).filter((r) => r.route === "tts" && r.voice === "tara");
const sha = (s: string) => createHash("sha1").update(s).digest("hex");
const takeFiles = () => readdirSync(path.join(DIR, "narration", "posts"), { recursive: true }).map(String).sort();
/** Every post item's card as drawn (the card page, plain and following) and its plan: what the cut shows. */
const drawn = async () => {
const { postCardHtml, postItemPlan } = (await import("../report-to-video/post-item.mjs")) as unknown as {
postCardHtml: (e: unknown, o: Record) => string; postItemPlan: (e: unknown, r?: unknown) => unknown;
};
const m = JSON.parse(readFileSync(MANIFEST, "utf8")) as { render?: unknown; timeline: unknown[] };
return m.timeline.map((e) => sha(JSON.stringify([postCardHtml(e, { width: 1080, height: 1350 }), postCardHtml(e, { width: 1080, height: 1350, follow: true }), postItemPlan(e, m.render)])));
};
test.beforeAll(() => {
for (const f of [MANIFEST, CHARACTERS]) if (!existsSync(`${f}.pristine`)) copyFileSync(f, `${f}.pristine`);
});
const reset = () => {
for (const f of [MANIFEST, CHARACTERS]) copyFileSync(`${f}.pristine`, f);
rmSync(CHARACTERS.replace(/\.json$/, ".undo.json"), { force: true });
rmSync(path.join(DIR, "narration", "auditions"), { recursive: true, force: true });
// The takes a test made (the fixture's own are each post's take-1), and a read's marker.
for (const id of ["1", "2", "3"]) {
const dir = path.join(DIR, "narration", "posts", id);
if (!existsSync(dir)) continue;
for (const f of readdirSync(dir)) if (!f.startsWith("take-1.")) rmSync(path.join(dir, f), { recursive: true, force: true });
}
};
test.beforeEach(() => {
test.setTimeout(240_000);
reset();
});
test.afterAll(reset);
test("a character's tuning: Lively, Read it, Another reading, Keep -- its stale read listed, nothing shown changed", async ({ page }) => {
const manifestBefore = readFileSync(MANIFEST, "utf8");
const cardsBefore = await drawn();
const takesBefore = takeFiles();
const asksBefore = ttsAsks().length;
await page.goto(urls.voicesHref(P));
const row = page.locator('[data-voices-character="teller"]');
await expect(row).toBeVisible({ timeout: 30_000 });
await row.locator('[data-voices-preset-open="teller"]').click();
const ed = page.locator('[data-preset-editor="teller"]');
const tune = ed.locator('[data-tuning="teller"]');
await expect(tune).toHaveAttribute("data-tuning-name", "default");
await expect(tune.locator("[data-tuning-stale]")).toHaveAttribute("data-tuning-stale", "0");
// The line it reads in this project, prefilled.
await expect(tune.locator("[data-tuning-text]")).toHaveValue(TUNING_LINE);
// Lively: the numbers shown under the name; one edited is custom; Lively again.
await tune.getByRole("radio", { name: /Orpheus tuning: Lively/ }).click();
await expect(tune).toHaveAttribute("data-tuning-name", "lively");
await expect(tune.locator('[data-tuning-field="temperature"]')).toHaveValue("0.75");
await expect(tune.locator('[data-tuning-field="top_p"]')).toHaveValue("0.92");
await expect(tune.locator('[data-tuning-field="repeat_penalty"]')).toHaveValue("1.25");
await tune.locator('[data-tuning-field="temperature"]').fill("0.8");
await expect(tune.locator("[data-tuning-custom]")).toBeVisible();
await tune.locator('[data-tuning-pick="lively"]').click();
await expect(tune.locator("[data-tuning-custom]")).toHaveCount(0);
// The line typed with doubled spaces: what is SAID collapses them (Another reading counts from that, review 1 #3).
const typed = TUNING_LINE.replace(/ /g, " ");
await tune.locator("[data-tuning-text]").fill(typed);
// Read it, pressed twice at once (review 1 #5): one job, one ask, nothing "already running".
await tune.getByRole("button", { name: "Read the line with these settings" }).dblclick();
await expect(tune.locator('[data-tuning-try="0"]')).toBeVisible({ timeout: 60_000 });
let asks = ttsAsks().slice(asksBefore);
expect(asks).toHaveLength(1);
expect(asks[0].tuning).toEqual({ temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 });
expect(asks[0].reading).toBeUndefined();
expect(asks[0].text).toBe(TUNING_LINE);
await expect(tune.locator("[data-tuning-blocked]")).toHaveCount(0);
await expect(tune.locator('[data-tuning-try="0"] [data-tuning-try-numbers]')).toContainText("Lively · temperature 0.75 · top_p 0.92 · repeat penalty 1.25");
await expect(tune.locator('[data-tuning-try="0"] [data-tuning-try-audio]')).toHaveAttribute("src", /narration%2Fauditions%2F[0-9a-f]{20}\.wav/);
// Another reading: the same line and numbers, reading 1; and again, reading 2.
const another = tune.getByRole("button", { name: "Read the same line again, the next reading" });
await another.click();
await expect(tune.locator('[data-tuning-try="1"]')).toBeVisible({ timeout: 60_000 });
await expect(another).toBeEnabled({ timeout: 60_000 });
await another.click();
await expect(tune.locator('[data-tuning-try="2"]')).toBeVisible({ timeout: 60_000 });
asks = ttsAsks().slice(asksBefore);
expect(asks).toHaveLength(3);
expect(asks.map((a) => a.reading)).toEqual([undefined, 1, 2]);
expect(asks[1].tuning).toEqual(asks[0].tuning);
await expect(tune.locator("[data-tuning-tries]")).toHaveAttribute("data-tuning-tries", "3");
await expect(tune.locator("[data-tuning-status]")).toContainText("reading 2 made");
// Another job running: said in place, Read it closed until it ends (umtool runs one job at a time).
let busy = true;
const tryPost = (u: URL) => u.pathname === "/api/report/voices" && !u.search;
const busyJob = (u: URL) => u.pathname === "/api/report/voices" && u.searchParams.get("job") === "busy-1";
await page.route(tryPost, async (route) => {
const body = route.request().postDataJSON() as { op?: string } | null;
if (route.request().method() === "POST" && body?.op === "try") {
return route.fulfill({ status: 409, contentType: "application/json", body: JSON.stringify({ error: "another job is running", busy: true, running: { id: "busy-1", kind: "cast-audition reports/tuning-fixture", state: "running", error: null } }) });
}
return route.continue();
});
await page.route(busyJob, (route) => route.fulfill({ contentType: "application/json", body: JSON.stringify({ id: "busy-1", state: busy ? "running" : "done", error: null }) }));
await tune.locator("[data-tuning-read]").click();
await expect(tune.locator("[data-tuning-blocked]")).toContainText("Another job is running (cast-audition reports/tuning-fixture): Read it is open again when it ends.");
await expect(tune.locator("[data-tuning-read]")).toBeDisabled();
busy = false;
await expect(tune.locator("[data-tuning-blocked]")).toHaveCount(0, { timeout: 10_000 });
await expect(tune.locator("[data-tuning-read]")).toBeEnabled();
await page.unroute(tryPost);
await page.unroute(busyJob);
expect(ttsAsks().slice(asksBefore), "the refused press asked nothing").toHaveLength(3);
// A job umtool no longer knows (restarted: 404 on its poll) is a failed read -- never "made", nothing played (review 1 #4).
const goneJob = (u: URL) => u.pathname === "/api/report/voices" && u.searchParams.get("job") === "gone-1";
await page.route(tryPost, async (route) => {
const body = route.request().postDataJSON() as { op?: string } | null;
if (route.request().method() === "POST" && body?.op === "try") return route.fulfill({ contentType: "application/json", body: JSON.stringify({ ok: true, job: { id: "gone-1", state: "running", error: null } }) });
return route.continue();
});
await page.route(goneJob, (route) => route.fulfill({ status: 404, contentType: "application/json", body: JSON.stringify({ error: "no such job" }) }));
await tune.locator("[data-tuning-read]").click();
await expect(tune.locator("[data-tuning-error]")).toContainText("the read failed: no such job");
await expect(tune.locator("[data-tuning-status]")).toHaveCount(0);
await expect(tune.locator("[data-tuning-read]")).toBeEnabled();
await page.unroute(tryPost);
await page.unroute(goneJob);
// The route: a flag is never a character; a tuning value is a number (review 1 #16).
const refused = await page.evaluate(async (project) => {
const ask = async (body: Record) => {
const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) });
return [r.status, ((await r.json()) as { error?: string }).error ?? ""];
};
return [
await ask({ op: "try", who: "--project", text: "x", tuning: { temperature: 0.7 }, reading: 0 }),
await ask({ op: "character-set", scope: "project", id: "teller", tuning: { temperature: [0.7] } }),
];
}, P);
expect(refused[0]).toEqual([400, "a try is of a character: its id, or @handle"]);
expect(refused[1]).toEqual([400, "tuning.temperature is a number (got [0.7])"]);
// An edit above the tuning, not saved yet: Keep must not throw it away (review 1 #6).
await ed.locator("[data-preset-direction]").fill("slower, warmer");
// Takes 3 typed: not what is stored (none), so Keep is open (review 1 #17); the CLI's note is said beside it, and the
// field shows what is stored -- none, the setting's (review 1 #7). The note is the CLI's when the setting is not 3;
// here it is laid on the route's answer, as the CLI words it.
await tune.locator('[data-tuning-field="takes"]').fill("3");
const keepSet = (u: URL) => u.pathname === "/api/report/voices" && !u.search;
await page.route(keepSet, async (route) => {
const body = route.request().postDataJSON() as { op?: string } | null;
if (route.request().method() !== "POST" || body?.op !== "character-set") return route.continue();
const res = await route.fetch();
const j = (await res.json()) as Record;
return route.fulfill({ response: res, json: { ...j, notes: ["takes 3 is Orpheus's default and is not kept: its reads take the editor's setting (4)"] } });
});
// Keep these settings: the CLI's own command; the preset says it is kept; the read made with the defaults is stale.
await tune.getByRole("button", { name: /Keep these settings for The Teller \(this video\)/ }).click();
await expect(page.locator("[data-voices-status]")).toContainText("The Teller: Orpheus tuning kept (Lively) for this video only");
const kept = (JSON.parse(readFileSync(CHARACTERS, "utf8")) as { characters: { id: string; synthetic?: { tuning?: Record } }[] }).characters.find((c) => c.id === "teller");
expect(kept?.synthetic?.tuning).toEqual({ temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 });
const tune2 = page.locator('[data-preset-editor="teller"] [data-tuning="teller"]');
await expect(tune2.locator("[data-tuning-note]")).toContainText("note: takes 3 is Orpheus's default and is not kept");
await expect(tune2.locator('[data-tuning-field="takes"]')).toHaveValue("");
await expect(ed.locator("[data-preset-direction]")).toHaveValue("slower, warmer");
await page.unroute(keepSet);
await expect(tune2).toHaveAttribute("data-tuning-kept", "yes");
await expect(tune2.locator("[data-tuning-effective]")).toContainText("kept: Lively · temperature 0.75 · top_p 0.92 · repeat penalty 1.25");
await expect(tune2.locator("[data-tuning-stale]")).toHaveAttribute("data-tuning-stale", "1");
await expect(tune2.locator("[data-tuning-stale]")).toContainText("1 read by this character was made with other settings: p-1");
await expect(tune2.locator("[data-tuning-stale-item]")).toHaveCount(1);
await expect(row.locator("[data-voice-stale]")).toHaveAttribute("data-voice-stale", "1");
// The tries are still there after the keep (scratch, the project's).
await expect(tune2.locator("[data-tuning-tries]")).toHaveAttribute("data-tuning-tries", "3");
// Nothing the cut shows changed: the manifest byte for byte, every card as drawn, no take made, no script written.
expect(readFileSync(MANIFEST, "utf8")).toBe(manifestBefore);
expect(await drawn()).toEqual(cardsBefore);
expect(takeFiles()).toEqual(takesBefore);
});
// THE BENCH (after S3, lane line-rerun): the character's tuning reaches its post's Read again; the Tune's numbers beat
// it; "Keep this tuning for " keeps them as the character's (cast project set) and says what that leaves
// stale -- and the card draws what it drew.
type BenchTake = { file: string; tuning?: Record; tuningAsked?: true | "preset"; reading?: number };
const takesOf = (id: string) => ((JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: { id: string; narration?: { takes?: BenchTake[] } }[] }).timeline.find((e) => e.id === id)!.narration?.takes ?? []);
const benchAsks = () => (existsSync(STUB_LOG) ? (JSON.parse(readFileSync(STUB_LOG, "utf8")) as (Tts & { out?: string })[]) : []).filter((r) => r.route === "tts" && String(r.out ?? "").includes("/tuning-fixture/narration/posts/1/"));
const drawnCard = async (page: import("@playwright/test").Page) => {
const frame = page.frameLocator('[data-post-card-frame="read"]');
await expect(frame.locator("[data-post-words]")).toContainText("bridge", { timeout: 15_000 });
return frame.locator("body").evaluate((b) => ({
words: b.querySelector("[data-post-words]")?.textContent ?? null,
blocks: [...b.querySelectorAll("[data-post-block]")].map((x) => [x.getAttribute("data-post-block"), x.textContent]),
tiles: [...b.querySelectorAll("[data-thread-tile]")].map((x) => [x.getAttribute("data-thread-tile"), x.getAttribute("data-thread-mode")]),
follow: b.getAttribute("data-post-follow"),
}));
};
test("the post bench: Read again asks the character's Lively (\"preset\"); the Tune's numbers beat it (true); Keep for the character -- the card unchanged", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1400 });
await page.goto(urls.voicesHref(P));
// The character's tuning, kept through its command (the Voices page's Keep is the first test's).
const kept0 = await page.evaluate(async (project) => {
const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "character-set", scope: "project", id: "teller", tuning: { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 } }) });
return r.status;
}, P);
expect(kept0).toBe(200);
await page.goto(urls.postBenchHref(P, "p-1"));
const panel = page.locator('[data-post-narration="p-1"]');
await expect(panel.locator("[data-post-take]")).toHaveCount(1, { timeout: 30_000 });
const before = await drawnCard(page);
const asked0 = benchAsks().length;
// Read again: the character's tuning asked, recorded as its ("preset").
await panel.locator('[aria-label="Read again"]').click();
await expect(panel.locator("[data-post-take]")).toHaveCount(2, { timeout: 30_000 });
expect(benchAsks().length).toBe(asked0 + 1);
// (The Read again carries the character's sampler, and only the takes the LINE owned -- none here: they are the
// character's or the editor's setting, resolved now, never copied from the last read; lane reads-find.)
expect(benchAsks().at(-1)!.tuning).toMatchObject({ temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 });
expect(takesOf("p-1")[1]).toMatchObject({ tuningAsked: "preset", tuning: { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 } });
// The Tune's numbers, this line only: they beat the character's, and say so (true).
await panel.locator("[data-read-tune] summary").click();
await panel.locator('[aria-label="temperature, this line only"]').fill("0.9");
await panel.locator('[aria-label="Read again with this tuning"]').click();
await expect(panel.locator("[data-post-take]")).toHaveCount(3, { timeout: 30_000 });
expect(benchAsks().at(-1)!.tuning?.temperature).toBe(0.9);
expect(takesOf("p-1")[2]).toMatchObject({ tuningAsked: true });
expect(takesOf("p-1")[2].tuning?.temperature).toBe(0.9);
// Keep this tuning for the character: its command; what it kept, and that this read (the picked one, made with the
// defaults) was made with other settings.
await panel.getByRole("button", { name: "Keep this tuning for The Teller" }).click();
await expect(panel.locator("[data-read-tune-kept]")).toContainText("kept for The Teller (this video only)", { timeout: 15_000 });
await expect(panel.locator("[data-read-tune-kept]")).toContainText("this read was made with other settings");
const teller = (JSON.parse(readFileSync(CHARACTERS, "utf8")) as { characters: { id: string; synthetic?: { tuning?: Record } }[] }).characters.find((c) => c.id === "teller");
expect(teller?.synthetic?.tuning?.temperature).toBe(0.9);
// The card draws what it drew: no take was picked, no words changed.
await page.reload();
expect(await drawnCard(page)).toEqual(before);
});
// REVIEW 2, THE MUST: a plain Read again under a tuned character asks the CHARACTER's tuning as it is now -- never the
// last read's numbers as the line's own. Twice under Lively ("preset" both), the character made Steady: the playing
// read is stale, and a third plain Read again asks Steady, "preset".
const setTeller = (page: import("@playwright/test").Page, tuning: Record) =>
page.evaluate(async ([project, t]) => {
const r = await fetch("/api/report/voices", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "character-set", scope: "project", id: "teller", tuning: t }) });
return r.status;
}, [P, tuning] as const);
const staleOfTeller = (page: import("@playwright/test").Page) =>
page.evaluate(async (project) => ((await (await fetch(`/api/report/voices?project=${encodeURIComponent(project)}&stale=teller`)).json()) as { items?: string[] }).items ?? [], P);
test("review 2: a plain Read again asks the character's tuning as it is now (\"preset\"), never the last read's as its own", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1400 });
await page.goto(urls.voicesHref(P));
expect(await setTeller(page, { temperature: 0.75, top_p: 0.92, repeat_penalty: 1.25 })).toBe(200);
await page.goto(urls.postBenchHref(P, "p-1"));
const panel = page.locator('[data-post-narration="p-1"]');
await expect(panel.locator("[data-post-take]")).toHaveCount(1, { timeout: 30_000 });
const before = await drawnCard(page);
const again = panel.locator('[aria-label="Read again"]');
// Twice under Lively: the second press starts from the first's (Lively, the character's) -- still the character's.
await again.click();
await expect(panel.locator("[data-post-take]")).toHaveCount(2, { timeout: 30_000 });
await expect(again).toBeEnabled({ timeout: 30_000 });
await again.click();
await expect(panel.locator("[data-post-take]")).toHaveCount(3, { timeout: 30_000 });
expect(takesOf("p-1")[1].tuningAsked).toBe("preset");
expect(takesOf("p-1")[2].tuningAsked).toBe("preset");
// The Tune says where its numbers start: the character's.
await panel.locator("[data-read-tune] summary").click();
await expect(panel.locator("[data-read-tune-baseline]")).toContainText("The Teller: Lively");
// Play the latest, then the character becomes Steady: that read is stale.
await panel.locator('[aria-label="Pick take 3"]').click();
await expect(panel.locator('[data-post-take="3"]')).toHaveAttribute("data-post-take-picked", "1");
expect(await setTeller(page, { temperature: 0.4, top_p: 0.8 })).toBe(200);
expect(await staleOfTeller(page)).toContain("p-1");
// A third plain press asks Steady, the character's now, and says so.
await page.reload();
await expect(panel.locator("[data-post-take]")).toHaveCount(3, { timeout: 30_000 });
const asked0 = benchAsks().length;
await panel.locator('[aria-label="Read again"]').click();
await expect(panel.locator("[data-post-take]")).toHaveCount(4, { timeout: 30_000 });
expect(benchAsks().length).toBe(asked0 + 1);
const sent = benchAsks().at(-1)!.tuning ?? {};
expect([sent.temperature, sent.top_p, sent.repeat_penalty ?? 1.2]).toEqual([0.4, 0.8, 1.2]);
expect(takesOf("p-1")[3].tuningAsked).toBe("preset");
// Defaults, this line only (review 2 #3): the three defaults asked as the line's own.
await panel.locator("[data-read-tune] summary").click();
await panel.locator('[aria-label="Tuning back to the defaults"]').click();
await panel.locator('[aria-label="Read again with this tuning"]').click();
await expect(panel.locator("[data-post-take]")).toHaveCount(5, { timeout: 30_000 });
const dflt = benchAsks().at(-1)!.tuning ?? {};
expect([dflt.temperature, dflt.top_p]).toEqual([0.55, 0.85]);
expect(takesOf("p-1")[4].tuningAsked).toBe(true);
// Back to the character (review 3 #3): the line's own last read, its Tune's "Use The Teller's" -- the next press
// asks nothing of its own, Steady is read, recorded "preset".
await expect(panel.locator("[data-read-tune-baseline]")).toContainText("this line's own", { timeout: 15_000 });
await panel.locator('[aria-label="Use The Teller\'s tuning for this line"]').click();
await expect(panel.locator("[data-read-tune-baseline]")).toContainText("The Teller: Steady");
await panel.locator('[aria-label="Read again with this tuning"]').click();
await expect(panel.locator("[data-post-take]")).toHaveCount(6, { timeout: 30_000 });
const back = benchAsks().at(-1)!.tuning ?? {};
expect([back.temperature, back.top_p]).toEqual([0.4, 0.8]);
expect(takesOf("p-1")[5].tuningAsked).toBe("preset");
// The card draws what it drew (take 3 plays: words as drafted).
await page.reload();
expect(await drawnCard(page)).toEqual(before);
});