import { test, expect, type Page } from "@playwright/test"; import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { PIPELINE_CASE, PIPELINE_DEFINITION, PLANTED, SUBJECT_CHANNEL, TALK_CHANNEL } from "./fixtures/case-fixture.mjs"; import { researchCaseHref, researchCasePipelineApi, researchCasePipelineHref } from "../lib/research/hrefs"; import { WARM_TIMEOUT, warm } from "./warm"; // --------------------------------------------------------------------------- // THE CASE PIPELINE (plans/release-38/research-cases-and-assist.md, lane A) on its fixture // (e2e/fixtures/case-fixture.mjs): from the board to the pipeline; the definition saved; a private name typed, // stored only as a hash; coverage per channel × year with the key years and a gap's button asking the editor // (stubbed) after its plan; candidates and their counts; batches whose every line is at most 200 characters; // finding rows by hand, one refused by the gate; the gate blocking the export of a row written before the name was // added, by row id and never the name; the export once the row is withheld; the hand-off to the board; the date // checks' sentence. E2E_SHOTS_DIR, when set, collects a screenshot of each stage. // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); const FIXTURE = path.join(HERE, "..", ".e2e-song"); const CASE_DIR = path.join(FIXTURE, ".umtool", "research", PIPELINE_CASE); // The stub writes its log on its first request; before that there is none. const stubLog = (): { route?: string; slug?: string }[] => { try { return JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")); } catch { return []; } }; // A background stage ends in well under a second; the first poll of a route can wait on its compile. const STAGE = { timeout: 30_000 }; const SHOTS = process.env.E2E_SHOTS_DIR; /** The case's files whose text names the planted private name, relative to the case dir. */ function filesNaming(term: string, dir = CASE_DIR, base = CASE_DIR): string[] { return readdirSync(dir).flatMap((name) => { const p = path.join(dir, name); if (statSync(p).isDirectory()) return filesNaming(term, p, base); return readFileSync(p, "utf8").toLowerCase().includes(term.toLowerCase()) ? [path.relative(base, p)] : []; }); } async function shot(page: Page, name: string, stage?: string) { if (!SHOTS) return; if (stage) await page.locator(`#stage-${stage}`).scrollIntoViewIfNeeded(); await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false }); } const status = (page: Page) => page.locator("[data-pipeline-status]"); const stageState = (page: Page, stage: string) => page.locator(`#stage-${stage} [data-stage-state]`); test.describe.configure({ mode: "serial" }); test.beforeAll(async ({ playwright }) => { test.setTimeout(WARM_TIMEOUT); await warm(playwright, [researchCasePipelineHref(PIPELINE_CASE), researchCasePipelineApi(PIPELINE_CASE), researchCaseHref(PIPELINE_CASE)]); }); test("a case through its pipeline: define, coverage, candidates, batches, findings, the privacy gate, export, hand-off, date checks", async ({ page }) => { test.setTimeout(180_000); await page.setViewportSize({ width: 1366, height: 900 }); // From the board. await page.goto(researchCaseHref(PIPELINE_CASE)); await page.locator("[data-case-pipeline]").click(); await expect(page).toHaveURL(new RegExp(`/research/${PIPELINE_CASE}/pipeline`)); await expect(page.locator("[data-pipeline-meta]")).toHaveText("not defined yet"); // Define: a private name in the definition is refused; the definition itself saves. const defBox = page.getByRole("textbox", { name: "Definition" }); await defBox.fill(JSON.stringify({ ...PIPELINE_DEFINITION, privateNames: { note: "x", sha256: ["a".repeat(64)] } })); await page.getByRole("button", { name: "Save the definition" }).click(); await expect(page.locator("#stage-define [role=alert]")).toContainText("never saved with the definition"); await defBox.fill(JSON.stringify(PIPELINE_DEFINITION, null, 2)); await page.getByRole("button", { name: "Save the definition" }).click(); await expect(page.locator("[data-pipeline-meta]")).toContainText("1 subject · 2 eras · 2 reader groups · 2 channels"); await shot(page, "01-define", "define"); // Coverage: per channel × year; the key years marked; a gap's button plans, then asks the editor. await page.getByRole("button", { name: "Count coverage" }).click(); await expect(stageState(page, "coverage")).toHaveAttribute("data-stage-state", "done", STAGE); const cov = page.getByRole("table", { name: "Coverage" }); const own2015 = cov.locator("tr", { hasText: SUBJECT_CHANNEL }).filter({ hasText: "2015" }); await expect(own2015).toHaveAttribute("data-key-year", ""); await expect(own2015.locator("td")).toHaveText([SUBJECT_CHANNEL, /2015\s*key/, "2", "2", "1", "1"]); await expect(cov.locator("tr", { hasText: "undated" })).toHaveCount(1); await shot(page, "02-coverage", "coverage"); const gap = page.locator(`[data-gap="${SUBJECT_CHANNEL}"]`); await gap.getByRole("button", { name: /Download missing \(2\)/ }).click(); const dialog = page.getByRole("dialog"); await expect(dialog).toContainText(`download every listed video ${SUBJECT_CHANNEL} does not hold`); await expect(dialog).toContainText('"/api/ops/download-missing"'); expect(stubLog().some((r) => r.route === "download-missing")).toBe(false); await dialog.getByRole("button", { name: "Confirm" }).click(); await expect(status(page)).toHaveText(`asked the editor: download-missing ${SUBJECT_CHANNEL}`); await expect.poll(() => stubLog().filter((r) => r.route === "download-missing").map((r) => r.slug)).toEqual([SUBJECT_CHANNEL]); await gap.getByRole("button", { name: /Persist the key period/ }).click(); await expect(dialog).toContainText('"toFetch"'); await dialog.getByRole("button", { name: "Cancel" }).click(); // Candidates: counted before any read; the talk show's line that names no subject is noise. await page.getByRole("button", { name: "Find candidates" }).click(); await expect(stageState(page, "candidates")).toHaveAttribute("data-stage-state", "done", STAGE); const counts = page.locator("[data-candidate-counts]"); await expect(counts).toContainText("3 windows in 3 recordings"); await expect(counts).toContainText("noSubject 1"); await expect(counts).toContainText("notStrict 1"); await shot(page, "03-candidates", "candidates"); // Batches: per group, wrapped -- no line over 200 characters, on the page and on disk. await page.getByRole("button", { name: "Make batches" }).click(); await expect(page.locator("[data-batch]")).toHaveCount(2); await expect(page.locator('[data-batch="own-1-001"]')).toContainText("pending"); await page.locator('[data-batch="talk-1-001"]').getByRole("button", { name: "Read the text" }).click(); const text = (await page.locator("[data-batch-text]").textContent()) ?? ""; expect(text).toContain("Naming rule"); expect(text).toContain("Wren Halloway stopped by the lantern shop"); expect(Math.max(...text.split("\n").map((l) => l.length))).toBeLessThanOrEqual(200); for (const b of ["own-1-001", "talk-1-001"]) { const onDisk = readFileSync(path.join(CASE_DIR, "batches", `${b}.txt`), "utf8"); expect(Math.max(...onDisk.split("\n").map((l) => l.length))).toBeLessThanOrEqual(200); } await shot(page, "04-batches"); await page.keyboard.press("Escape"); // Findings by hand, before any private name: the talk-show row names a private person. const row = (o: Record) => JSON.stringify({ batch: "own-1-001", slug: SUBJECT_CHANNEL, id: "lw-2015a", date: "20150310", title: "Opening the lantern shop", t: 120, url: "https://www.youtube.com/watch?v=lw-2015a", category: "shop", relevance: 3, quote: "welcome to the lantern shop", summary: "She opens the shop", speaker: "Wren Halloway", confidence: "high", round: 1, by: "hand", ...o }); const rows = [ row({}), row({ t: 126, relevance: 2, quote: "I built every lantern here myself", summary: "She built the lanterns" }), row({ batch: "talk-1-001", slug: TALK_CHANNEL, id: "ht-2015a", date: "20150320", title: "Harbor Talk 12", t: 186, url: "https://www.youtube.com/watch?v=ht-2015a", quote: `she was with ${PLANTED} that day`, summary: "The host says who she was with", speaker: "host" }), row({ id: "lw-2021a", date: "20210305", title: "Closing the shop", t: 240, quote: "the lantern shop is closing for good", summary: "She closes the shop" }), ]; await page.getByRole("textbox", { name: "Finding rows" }).fill(rows.join("\n")); await page.getByRole("button", { name: "Add rows" }).click(); await expect(status(page)).toHaveText("4 rows added: f1, f2, f3, f4"); // The private name, typed: hashed in the browser, posted as a hash, shown as a count. const posted: string[] = []; page.on("request", (r) => { if (r.url().includes("/pipeline/private-names")) posted.push(r.postData() ?? ""); }); await page.getByLabel("A private name", { exact: true }).fill(PLANTED); await page.getByRole("button", { name: "Add", exact: true }).click(); await expect(page.locator("[data-private-count]")).toHaveText("1 hashed"); expect(posted.join("")).not.toMatch(/Ottoline|Brackenridge/i); expect(posted.join("")).toMatch(/"add":\["[0-9a-f]{64}"\]/); expect(readFileSync(path.join(CASE_DIR, "pipeline.json"), "utf8")).not.toMatch(/Ottoline|Brackenridge/i); // The candidates and batches written before it are withheld now; only the row a person wrote still names it. await expect(status(page)).toContainText("added: 1 private name (hashed); withheld in"); expect(filesNaming(PLANTED)).toEqual(["findings.jsonl"]); // The gate: row f3 is blocked, by id; a new row naming the name is refused at the write. const gate = page.locator("[data-gate]"); await expect(gate).toHaveAttribute("data-gate", "blocked"); await expect(gate).toContainText("in 1 row (f3 ×"); await page.getByRole("textbox", { name: "Finding rows" }).fill(row({ t: 300, summary: `Again with ${PLANTED}` })); await page.getByRole("button", { name: "Add rows" }).click(); await expect(status(page)).toContainText("the privacy gate blocked these findings"); await expect(status(page)).toContainText("(f5)"); await expect(status(page)).not.toContainText("Ottoline"); await shot(page, "05-privacy-gate", "privacy"); // The export is blocked, naming the row, never the name; nothing is written. await page.getByRole("button", { name: "Export the report" }).click(); await expect(status(page)).toContainText("the privacy gate blocked the export"); await expect(status(page)).toContainText("in 1 item (f3)"); await expect(stageState(page, "export")).toHaveAttribute("data-stage-state", "failed", STAGE); await expect(page.locator("#stage-export [data-stage-log]")).not.toContainText("Ottoline"); expect(readFileSync(path.join(CASE_DIR, "stages.json"), "utf8")).not.toMatch(/Ottoline|Brackenridge/i); await shot(page, "06-export-blocked", "export"); // A person withholds the name in the row (lane C's correction; here, the file), and the export goes through. const f = path.join(CASE_DIR, "findings.jsonl"); writeFileSync(f, readFileSync(f, "utf8").replace(PLANTED, "[name withheld]")); await page.getByRole("textbox", { name: "Summary" }).fill("What Wren said about the shop, from opening to closing."); await page.getByRole("button", { name: "Save the summary" }).click(); await expect(status(page)).toHaveText("summary saved as yours"); await expect(gate).toHaveAttribute("data-gate", "clear"); await expect(page.locator("[data-merge]")).toContainText("Her own words 2"); await expect(page.locator("[data-merge]")).toContainText("What others said 1"); await expect(page.locator("[data-merge]")).toContainText("f2 → f1"); await page.getByRole("button", { name: "Export the report" }).click(); await expect(stageState(page, "export")).toHaveAttribute("data-stage-state", "done", STAGE); const md = readFileSync(path.join(CASE_DIR, "REPORT.md"), "utf8"); expect(md).toMatch(/^# Wren and the lantern shop\n\nWhat Wren said about the shop/); expect(md).toContain('## Her own words\n\n- She opens the shop: "welcome to the lantern shop" — [Opening the lantern shop @ 2:00](https://www.youtube.com/watch?v=lw-2015a&t=120s)'); expect(md).toContain('"she was with [name withheld] that day"'); expect(md).not.toMatch(/Ottoline|Brackenridge/i); expect(filesNaming(PLANTED)).toEqual([]); const html = await (await page.request.get(`${researchCasePipelineApi(PIPELINE_CASE, "report")}?format=html`)).text(); expect(html).toContain("

Her own words

"); await shot(page, "07-export", "export"); // Hand off to the board: plan, confirm, the board holds the findings in sections. await page.getByRole("button", { name: "Hand off to the board" }).click(); await expect(dialog).toContainText("Pin 3 findings to the board"); await dialog.getByRole("button", { name: "Confirm" }).click(); await expect(status(page)).toHaveText("pinned 3 to the board"); const board = JSON.parse(readFileSync(path.join(CASE_DIR, "case.json"), "utf8")) as { sections: { title: string }[]; quotes: { text: string; claim: string }[] }; expect(board.sections.map((s) => s.title)).toEqual(["Her own words", "What others said"]); expect(board.quotes.map((q) => q.claim)).toContain("She closes the shop"); // Date checks: the subject's uploads around the key date, and the sentence. await page.getByRole("button", { name: "Check the dates" }).click(); await expect(stageState(page, "date-checks")).toHaveAttribute("data-stage-state", "done", STAGE); await expect(page.locator('[data-date-check="2021-03-01"] [data-date-sentence]')).toHaveText("response found: 1 finding in uploads from 2021-03-05 to 2021-03-05 (rows f4)"); await shot(page, "08-date-checks", "date-checks"); }); test("the API refuses a private name sent as text, and the board's own exits are gated by the case's names", async ({ request }) => { const r = await request.post(researchCasePipelineApi(PIPELINE_CASE, "private-names"), { data: { add: [PLANTED] } }); expect(r.status()).toBe(400); expect((await r.json()).error).toContain("sha256 hex digests only"); // The board exports what was pinned: clear now (the row was withheld before the hand-off). const ok = await request.get(`/api/research/cases/${PIPELINE_CASE}/export.md`); expect(ok.status()).toBe(200); // A pinned note naming the private person blocks the board's export, by quote id. const doc = JSON.parse(readFileSync(path.join(CASE_DIR, "case.json"), "utf8")); doc.quotes[0].note = `ask ${PLANTED}`; writeFileSync(path.join(CASE_DIR, "case.json"), JSON.stringify(doc, null, 2)); const blocked = await request.get(`/api/research/cases/${PIPELINE_CASE}/export.md`); expect(blocked.status()).toBe(409); const err = (await blocked.json()).error as string; expect(err).toContain(`(${doc.quotes[0].id})`); expect(err).not.toMatch(/Ottoline|Brackenridge/i); });