import { test, expect, type Page } from "@playwright/test";
import { execFileSync } from "node:child_process";
import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import * as urls from "./urls";
// ---------------------------------------------------------------------------
// THE THREAD WALK (report-to-video/post-conversation.mjs; knobs.md, "Thread
// reads"; operator, 4 Nov: "weird thread progression", "wrong order", "a full
// read thread progression"): one conversation played back to back is ONE
// scene. Fixture: e2e/fixtures/post-narration-fixture.mjs's three items made
// a tree here -- p-11 his reply under his root post (771), p-12 his answer to
// a stranger who answered p-11, p-13 his answer to a second stranger who
// answered the root (the sibling branch) -- and p-14 a post whose read reads
// the post it quotes first (its links among it).
//
// THREAD_WALK_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.THREAD_WALK_SHOTS ?? null;
const ROOT = { id: "771", author: "Narr Subject", handle: "narrsubject", date: "2026-10-30T06:00:00.000Z", text: "Many have questioned my methods in dealing with the whole mess, and I will say it once more for everyone." };
const A = "I can't help but feel like I've failed everyone, they all got exactly what they wanted out of it.";
const FOX = { id: "834", author: "Fox One", handle: "fox_one", date: "2026-10-30T07:00:00.000Z", text: "Far as people should be concerned you are no better than the people you criticised all week." };
const C = "As far as people are concerned you are nobody at all, and that is the end of it.";
const DRAC = { id: "775", author: "Drac Two", handle: "drac_two", date: "2026-10-30T06:10:00.000Z", text: "Oh please, you were never going to change anything here by drawing all that attention to it." };
const B = "I have fought them before, so who are you to tell me what fighting them is like.";
const QUOTED = { author: "Quoted Person", handle: "quoted_person", date: "2026-10-30T05:00:00.000Z", text: "Read the receipts before you say another word about it.\n\nhttps://\nweb.archive.org/web/2021032015\n1733/https://twitter.com/someone/status/1373102987070017537\n…" };
const Q_REPLY = "I read them, and they say the opposite of what you think they say.";
/** A take as the batch assembles one: its pieces in order (para = piece * 100), a part each, 3 words a second. */
function takeOf(pieces: string[]) {
let at = 0;
const parts = pieces.map((text, pi) => {
const seconds = Math.round((text.split(/\s+/).length / 3) * 100) / 100;
if (pi) at += 0.6;
const p = { n: pi + 1, para: pi * 100, text, start: Math.round(at * 100) / 100, seconds };
at += seconds;
return p;
});
return { file: "narration/posts/11/take-1.orpheus-zac.wav", engine: "orpheus", voice: "leo+zac", seconds: Math.round(at * 100) / 100, script: pieces.join("\n\n"), parts };
}
const STARTS = (pieces: string[]) => takeOf(pieces).parts.map((p) => 0.4 + p.start);
test.beforeAll(() => {
if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
});
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 });
const m = JSON.parse(readFileSync(MANIFEST, "utf8"));
const byId = (id: string) => m.timeline.find((x: { id: string }) => x.id === id);
const narr = (e: Record, text: string, pieces: string[]) => Object.assign(e, { text, narration: { script: text, takes: [takeOf(pieces)], pick: 0 } });
const a = narr(byId("p-11"), A, [A]);
a.parents = [ROOT];
const c = narr(byId("p-12"), C, [FOX.text, C]);
delete c.media;
c.date = "2026-10-30T07:10:00.000Z";
c.parents = [FOX, { id: "11", author: "Narr Subject", handle: "narrsubject", date: "2026-10-30T10:00:00.000Z", text: A }];
const b = narr(byId("p-13"), B, [DRAC.text, B]);
b.date = "2026-10-30T11:00:00.000Z";
b.parents = [DRAC, ROOT];
const q = narr({ ...structuredClone(b), id: "p-14", post: "narrchan-x/14", parents: undefined, date: "2026-10-30T12:00:00.000Z" }, Q_REPLY, [
"Read the receipts before you say another word about it.",
"https://. web.archive.org slash web slash 2021032015. 1733/. …",
Q_REPLY,
]);
delete q.parents;
q.quoted = QUOTED;
m.timeline = [a, c, b, q];
writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
});
/** Play opened paused `at` seconds into `id`; its frame once the card is threaded. */
async function playAt(page: Page, id: string, at: number) {
await page.goto(urls.playHref(PROJECT, { bare: true, clip: id, at }));
const player = page.locator(`[data-post-play="${id}"]`);
await expect(player).toHaveAttribute("data-post-thread", /\d/, { timeout: 15_000 });
const frame = page.frameLocator('[data-post-card-frame="read"]');
await expect(frame.locator("body")).toHaveAttribute("data-post-thread", /\d/, { timeout: 15_000 });
await expect.poll(async () => Math.abs(Number(await player.getAttribute("data-post-s")) - at)).toBeLessThan(0.3);
return { player, frame };
}
const tilesOf = async (player: ReturnType) =>
Object.fromEntries(((await player.getAttribute("data-post-thread-tiles")) ?? "").split(" ").filter(Boolean).map((x) => {
const [sc, v] = x.split("=");
return [sc, v.split("/").map(Number)];
}));
const slotTop = (frame: ReturnType, scope: string) =>
frame.locator(`[data-thread-slot="${scope}"]`).evaluate((el) => el.getBoundingClientRect().top - document.querySelector("[data-post-words]")!.getBoundingClientRect().top);
test("ONE SCENE: his answer to the stranger opens on his reply above it (carried, in full), the root kept on top as context; the stranger's post comes in lit while it is read", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 1000 });
// At its first frame: the post p-11 ended on, in full; the root small and dim above it.
{
const { player, frame } = await playAt(page, "p-12", 0.05);
await expect(frame.locator('[data-thread-slot="conv:771"]')).toHaveAttribute("data-thread-scene", "keep");
const t = await tilesOf(player);
// In full as the item opens (the change to it begins with the read, 0.4 s in less the pan's lead: at once).
expect(t["parent:1"][0]).toBeGreaterThan(0.9);
expect(t["parent:1"][1]).toBeGreaterThan(0.9);
expect(t["conv:771"][0]).toBeLessThan(1);
// The stranger's post not yet in (it fades in as the read begins).
expect(t["parent:0"][1]).toBeLessThan(0.2);
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-open.png") });
}
// The stranger's post read: in full and lit, the root still on top of the column.
{
const [fox] = STARTS([FOX.text, C]);
const { player, frame } = await playAt(page, "p-12", fox + 1.4);
const t = await tilesOf(player);
expect(t["parent:0"]).toEqual([1, 1]);
expect(t["conv:771"]).toEqual([0.62, 0.5]);
expect(t["parent:1"]).toEqual([0.62, 0.5]);
await expect.poll(async () => frame.locator('[data-thread-slot="parent:0"]').getAttribute("data-thread-state")).toBe("focus");
expect(await slotTop(frame, "conv:771")).toBeLessThan(await slotTop(frame, "parent:1"));
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-fox.png") });
}
});
test("THE SIBLING SWAP: the next branch's item opens on the post the last one ended on; that branch collapses away (scale 0) as the second stranger comes in, lit -- the root stays on top", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 1000 });
{
const { player, frame } = await playAt(page, "p-13", 0.05);
for (const sc of ["conv:11", "conv:834", "conv:12"]) await expect(frame.locator(`[data-thread-slot="${sc}"]`)).toHaveAttribute("data-thread-scene", "collapse");
const t = await tilesOf(player);
// The post p-12 ended on, in full as the item opens (it collapses as the read begins: at once).
expect(t["conv:12"][0]).toBeGreaterThan(0.9);
expect(t["conv:12"][1]).toBeGreaterThan(0.9);
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-swap-open.png") });
}
{
const [drac] = STARTS([DRAC.text, B]);
const { player, frame } = await playAt(page, "p-13", drac + 1.4);
const t = await tilesOf(player);
for (const sc of ["conv:11", "conv:834", "conv:12"]) expect(t[sc].slice(0, 2)).toEqual([0, 0]);
expect(t["parent:0"]).toEqual([1, 1]);
expect(t["parent:1"]).toEqual([0.62, 0.5]);
await expect.poll(async () => frame.locator('[data-thread-slot="conv:12"]').getAttribute("data-thread-state")).toBe("hidden");
await expect.poll(async () => frame.locator('[data-thread-slot="parent:0"]').getAttribute("data-thread-state")).toBe("focus");
// The root on top, the new branch under it; the collapsed slots closed up.
expect(await slotTop(frame, "parent:1")).toBeLessThan(await slotTop(frame, "parent:0"));
await expect.poll(async () => frame.locator('[data-thread-slot="conv:12"]').evaluate((el) => el.getBoundingClientRect().height)).toBeLessThan(1);
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-swap-drac.png") });
}
});
test("A QUOTE READ FIRST is its own tile above his post, in full and lit while read -- his post not yet shown; the read's link is warned with its fix", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 1000 });
const { player, frame } = await playAt(page, "p-14", 1.5);
const t = await tilesOf(player);
expect(t.quoted).toEqual([1, 1]);
expect(t.post[1]).toBe(0);
await expect(frame.locator('[data-thread-slot="quoted"]')).toHaveAttribute("data-thread-above", "");
expect(await slotTop(frame, "quoted")).toBeLessThan(await slotTop(frame, "post"));
await expect.poll(async () => frame.locator('[data-thread-slot="quoted"]').getAttribute("data-thread-state")).toBe("focus");
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-quote.png") });
// posts roles: the part that says a link, and the fix.
const roles = execFileSync(process.execPath, [path.join(HERE, "..", "bin", "umtool.mjs"), "posts", "roles", PROJECT, "p-14"], { env: { ...process.env, REPORTS_DIR: path.dirname(REPORTS) }, encoding: "utf8" });
expect(roles).toMatch(/WARNING: timeline p-14: part 2 of its take says a link aloud .*umtool posts reread p-14 --drop-urls/);
});
test("the bench: one scene with the item before (what stays on top, what collapses); a context piece the take reads offers \"Read without it\"", async ({ page }) => {
await page.setViewportSize({ width: 1500, height: 1100 });
await page.goto(urls.postBenchHref(PROJECT, "p-13"));
const panel = page.locator("[data-post-thread-panel]");
await expect(panel).toHaveAttribute("data-threaded", "1");
await expect(panel.locator("[data-post-thread-scene]")).toHaveAttribute("data-post-thread-scene", "3");
await expect(panel.locator('[data-post-thread-scene-tile="12"]')).toHaveAttribute("data-action", "collapse");
await expect(panel.locator('[data-post-thread-reread="parent:0"]')).toHaveText("Read without it");
await expect(panel.locator('[data-post-thread-piece="post"] [data-post-thread-reread]')).toHaveCount(0);
if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-bench.png") });
});