import { test, expect, type APIRequestContext, type Locator, type Page } from "@playwright/test";
import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs";
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import * as urls from "./urls";
import { WARM_TIMEOUT, warm } from "./warm";
/** A schedule write's click and its answer (POST /api/schedules): each runs the editor stub's real report-schedule
* action in a tsx child (editor-stub.mjs, spawnSync -- about 3.4 s on an idle machine, measured), longer than an
* expect's 5 s under load. The page is read once the answer is in. */
const clickAnswered = async (page: Page, button: Locator) => {
const answered = page.waitForResponse((r) => new URL(r.url()).pathname.startsWith("/api/schedules") && r.request().method() !== "GET", { timeout: 60_000 });
await button.click();
await answered;
};
// ---------------------------------------------------------------------------
// RECURRING REPORTS (plans/umtool-redesign.md, R5) over the editor stub, which
// runs the REAL report-schedule action and store over the fixture's article
// store with a tick's steps stubbed (common/testing/schedule/opsStub.ts): a
// tick makes a done edition, a second tick the same day is quiet, "held" in
// the terms is a daily-cap refusal, "fail" a failure.
//
// Create → "A recurring report": planned, then started (a series; a living
// report) · the series page: Tick now, a real and a quiet edition, the tick
// log, pause/resume, edit cadence, delete (plan, then confirm) · Work: one
// row per series, the recurring facet · the Inbox: a finished edition is
// Review, a held or failed tick is Your call · a living report's article:
// the cadence chip in its head.
//
// WRITES articles/.series/r5-*, articles/r5-* (through the stub; removed after)
//
// R5_SHOTS=
also saves the screenshots (1366×768 and 1440×900, both themes).
// ---------------------------------------------------------------------------
const HERE = path.dirname(fileURLToPath(import.meta.url));
const FIXTURE = path.join(HERE, "..", ".e2e-song");
const ARTICLES = path.join(FIXTURE, "articles");
const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
const SHOTS = process.env.R5_SHOTS ?? "";
const stubAsked = (route: string) =>
(JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; [k: string]: unknown }[]).filter((r) => r.route === route);
const series = (id: string) => JSON.parse(readFileSync(path.join(ARTICLES, ".series", id, "series.json"), "utf8"));
function clean() {
rmSync(path.join(ARTICLES, ".series"), { recursive: true, force: true });
for (const a of readdirSync(ARTICLES).filter((n) => n.startsWith("r5-"))) rmSync(path.join(ARTICLES, a), { recursive: true, force: true });
}
async function shoot(page: Page, name: string) {
if (!SHOTS) return;
mkdirSync(SHOTS, { recursive: true });
// No reload (a form keeps what was typed): the theme is the attribute the
// server stamps from the cookie, set here in place.
const was = await page.evaluate(() => document.documentElement.getAttribute("data-theme"));
for (const theme of ["dark", "light"] as const) {
await page.evaluate((t) => document.documentElement.setAttribute("data-theme", t), theme);
for (const [w, h] of [
[1366, 768],
[1440, 900],
] as const) {
await page.setViewportSize({ width: w, height: h });
await page.waitForTimeout(150);
await page.screenshot({ path: path.join(SHOTS, `${name}-${w}x${h}-${theme}.png`) });
}
}
await page.evaluate((t) => (t ? document.documentElement.setAttribute("data-theme", t) : document.documentElement.removeAttribute("data-theme")), was);
await page.setViewportSize({ width: 1280, height: 720 });
}
// The stub's clock for the recurring reports: the instant the next asks run at.
const STUB = `http://127.0.0.1:${portFor("EDITOR_STUB_PORT")}`;
async function clock(request: APIRequestContext, body: { now?: string; quiet?: boolean }) {
const r = await request.post(`${STUB}/__stub/schedule-clock`, { data: body });
expect(r.ok()).toBe(true);
}
async function api(page: Page, body: Record) {
const r = await page.request.post("/api/schedules", { data: body });
const b = (await r.json()) as Record;
expect(r.ok(), JSON.stringify(b)).toBe(true);
return b;
}
test.describe.configure({ mode: "serial" });
test.beforeAll(async ({ playwright }) => {
test.setTimeout(WARM_TIMEOUT);
clean();
await warm(playwright, [urls.createHref({ make: "recurring" }), "/api/articles/channels", "/api/schedules", urls.seriesHref("r5-none"), urls.workHref({ recurring: "1" })]);
});
test.afterAll(async ({ request }) => {
await clock(request, {}).catch(() => {});
clean();
});
test("Create → A recurring report: a series, planned (first tick, model, cap), then started; its page opens", async ({ page }) => {
test.setTimeout(90_000);
await page.goto(urls.createHref({ make: "recurring" }));
const form = page.getByRole("form", { name: "a recurring report" });
await expect(form.getByRole("textbox", { name: "topic" })).toBeFocused();
await expect(form.getByRole("radio", { name: "Series" })).toBeChecked();
await form.getByRole("textbox", { name: "topic" }).fill("R5 cohost");
await form.getByRole("textbox", { name: "question" }).fill("What did the co-hosts say this week?");
await form.getByRole("textbox", { name: "find a channel" }).fill("site");
await form.getByRole("button", { name: /Site Channel/ }).click();
await expect(form.getByRole("combobox", { name: "cadence" })).toHaveValue("weekly");
await expect(form.getByRole("combobox", { name: "day of the week" })).toHaveValue("1");
await shoot(page, "create-recurring");
await clickAnswered(page, form.getByRole("button", { name: "Plan the schedule" }));
const plan = form.getByRole("region", { name: "plan recurring report" });
await expect(plan).toContainText("Series r5-cohost · weekly · Mon 06:00 · first tick Mon 06:00");
await expect(plan.locator("[data-plan-first-tick]")).toHaveAttribute("data-plan-first-tick", /T\d\d:00:00\.000Z$/);
await expect(plan).toContainText(/up to \$\d+\.\d\d a tick · daily cap \$\d+\.\d\d/);
await expect(plan).toContainText(/first edition: R5 cohost · week of (\d{4}-\d{2}-\d{2}) \(\1 … \d{4}-\d{2}-\d{2}, 7 whole days\)/);
// Nothing written by the plan.
expect(existsSync(path.join(ARTICLES, ".series", "r5-cohost"))).toBe(false);
expect(stubAsked("report-schedule").at(-1)).toMatchObject({ action: "create", dryRun: true, shape: "series", topic: "R5 cohost", channels: ["sitechan"], cadence: { kind: "weekly", dow: 1, at: "06:00" } });
await shoot(page, "create-recurring-plan");
// The confirm has the focus: Enter starts it.
await expect(form.getByRole("button", { name: "Start the schedule" })).toBeFocused();
await page.keyboard.press("Enter");
await page.waitForURL(/\/series\/r5-cohost$/, { timeout: 20_000 });
await expect(page.locator("[data-schedule-chip]")).toHaveText(/weekly · next Mon 06:00/);
await expect(page.locator("[data-series-empty]")).toContainText("No edition yet");
expect(series("r5-cohost")).toMatchObject({ shape: "series", topic: "R5 cohost", scope: { channels: ["sitechan"] }, paused: false, editions: [] });
});
test("the series page: Tick now makes an edition over whole days; again at once, nothing to cover; a week on, a quiet one; the tick log", async ({ page, request }) => {
test.setTimeout(90_000);
// Monday 2026-10-19, noon UTC (the same date on the stub's clock, whatever its zone).
await clock(request, { now: "2026-10-19T12:00:00.000Z" });
await page.goto(urls.seriesHref("r5-cohost"));
await clickAnswered(page, page.getByRole("button", { name: "Tick now" }));
await expect(page.locator("[data-schedule-said]")).toContainText(/Tick queued — job stub-tick-\d+/);
const done = page.locator("[data-edition='1']");
await expect(done).toHaveAttribute("data-edition-status", "done");
// The Mon … Sun before the tick, seven whole days, named for its start.
expect(series("r5-cohost").editions[0]).toMatchObject({ article: "r5-cohost-2026-10-19", window: { from: "2026-10-12", to: "2026-10-18" } });
await expect(done.locator("[data-edition-link='r5-cohost-2026-10-19']")).toHaveText("R5 cohost · week of 2026-10-12");
await expect(done.locator("[data-edition-window]")).toHaveAttribute("data-edition-window", "2026-10-12/2026-10-18");
// The scheduled tick (the real clock's next Monday) starts where this edition ended: on 2026-10-19
// it has nothing to cover yet; after it, it covers 2026-10-19 … the day before it.
await expect(page.locator("[data-series-next]")).toHaveText(/^(Nothing to cover yet — the next edition starts 2026-10-19|next, Mon 06:00: 2026-10-19 … \d{4}-\d{2}-\d{2})$/);
// At once again: no day is read twice -- no edition, $0, said plainly, no card.
await clickAnswered(page, page.getByRole("button", { name: "Tick now" }));
const ticks = page.getByRole("table", { name: "ticks" });
await expect(ticks.locator("tbody tr")).toHaveCount(2);
await expect(ticks.locator("tbody tr").first()).toContainText("Nothing to cover yet — the next edition starts 2026-10-19");
await expect(page.locator("[data-edition]")).toHaveCount(1);
// A week on, nothing in the window matches: a quiet edition, dimmed, no link.
await clock(request, { now: "2026-10-26T12:00:00.000Z", quiet: true });
await clickAnswered(page, page.getByRole("button", { name: "Tick now" }));
const quiet = page.locator("[data-edition='2']");
await expect(quiet).toHaveAttribute("data-edition-status", "quiet");
await expect(quiet).toHaveClass(/opacity-55/);
await expect(quiet.locator("[data-edition-link]")).toHaveCount(0);
await expect(quiet.locator("[data-edition-window]")).toHaveAttribute("data-edition-window", "2026-10-19/2026-10-25");
await clock(request, {});
// Newest first.
await expect(page.locator("[data-edition]")).toHaveCount(2);
await expect(page.locator("[data-edition]").first()).toHaveAttribute("data-edition", "2");
await expect(ticks.locator("tbody tr")).toHaveCount(3);
await expect(ticks.locator("tbody tr").first()).toHaveAttribute("data-tick-status", "quiet");
await expect(ticks.locator("tbody tr").nth(2)).toContainText("$0.37");
await expect(page.locator("[data-series-spent]")).toHaveAttribute("data-series-spent", "0.37");
await shoot(page, "series-page");
await clickAnswered(page, page.getByRole("button", { name: "Pause schedule" }));
await expect(page.locator("[data-schedule-chip]")).toHaveText(/weekly · paused/);
await clickAnswered(page, page.getByRole("button", { name: "Resume schedule" }));
await expect(page.locator("[data-schedule-chip]")).toHaveText(/weekly · next Mon 06:00/);
await page.getByRole("button", { name: "Edit cadence" }).click();
const edit = page.getByRole("form", { name: "edit cadence" });
await edit.getByRole("combobox", { name: "cadence" }).selectOption("daily");
await edit.locator('input[aria-label="at"]').fill("07:30");
await clickAnswered(page, edit.getByRole("button", { name: "Save cadence" }));
await expect(page.locator("[data-schedule-chip]")).toHaveText(/daily · next \w{3} 07:30/);
expect(series("r5-cohost").cadence).toEqual({ kind: "daily", at: "07:30" });
expect(stubAsked("report-schedule").map((r) => r.action)).toEqual(expect.arrayContaining(["tick-now", "pause", "resume", "update"]));
});
test("keys: the head's controls in Tab order; Edit cadence opens on its first field, Escape returns to it; the delete plan opens on its confirm", async ({ page }) => {
await page.goto(urls.seriesHref("r5-cohost"));
const pause = page.getByRole("button", { name: "Pause schedule" });
await expect(pause).toBeEnabled();
await pause.focus();
for (const name of ["Tick now", "Edit cadence", "Delete schedule"]) {
await page.keyboard.press("Tab");
await expect(page.getByRole("button", { name })).toBeFocused();
}
await page.keyboard.press("Shift+Tab");
await page.keyboard.press("Enter");
const edit = page.getByRole("form", { name: "edit cadence" });
await expect(edit.getByRole("combobox", { name: "cadence" })).toBeFocused();
await page.keyboard.press("Escape");
await expect(edit).toHaveCount(0);
await expect(page.getByRole("button", { name: "Edit cadence" })).toBeFocused();
await page.keyboard.press("Tab");
// Enter on Delete schedule asks for the plan (a schedule write's round-trip, clickAnswered's): read once answered.
const planned = page.waitForResponse((r) => new URL(r.url()).pathname.startsWith("/api/schedules") && r.request().method() !== "GET", { timeout: 60_000 });
await page.keyboard.press("Enter");
await planned;
const plan = page.getByRole("region", { name: "delete schedule r5-cohost" });
await expect(plan.getByRole("button", { name: "Confirm delete" })).toBeFocused();
await page.keyboard.press("Escape");
await expect(page.getByRole("button", { name: "Delete schedule" })).toBeFocused();
});
test("Work: one row per series, with its chip, under the recurring facet; its editions are not rows", async ({ page }) => {
await page.goto(urls.workHref({ recurring: "1" }));
const row = page.locator("[data-lit-line][data-piece='s:r5-cohost']");
await expect(row).toBeVisible();
await expect(row).toHaveAttribute("data-recurring", "");
await expect(row.locator("[data-work-chip]")).toHaveText(/daily · next/);
await expect(page.locator("[data-lit-line][data-piece^='a:articles/r5-cohost-']")).toHaveCount(0);
// Every row the facet keeps is recurring.
const rows = page.locator("[data-lit-line][data-piece]");
expect(await rows.count()).toBe(await page.locator("[data-lit-line][data-recurring]").count());
await page.goto(urls.workHref({ kind: "series" }));
await expect(page.locator("[data-lit-line][data-piece='s:r5-cohost']")).toBeVisible();
await page.goto(urls.workHref());
await expect(page.locator("[data-lit-line][data-piece^='a:articles/r5-cohost-']")).toHaveCount(0);
});
test("the Inbox: a finished edition is Review on its series; a held tick (Raise cap) and a failed one (Tick now) are Your call", async ({ page }) => {
test.setTimeout(90_000);
await page.goto("/");
for (const [topic, terms] of [
["R5 held", "held"],
["R5 fail", "fail"],
]) {
const made = (await api(page, { action: "create", shape: "series", topic, channels: ["sitechan"], cadence: "weekly mon 06:00", terms })) as { schedule: { id: string } };
await api(page, { action: "tick-now", id: made.schedule.id });
}
await page.goto("/");
const review = page.locator("[data-group=review] [data-lit-line][data-piece='s:r5-cohost'][data-card='edition-ready']");
await expect(review).toBeVisible();
await expect(review.locator("[data-action-link]")).toHaveText("Review edition");
const held = page.locator("[data-group=your-call] [data-lit-line][data-piece='s:r5-held'][data-card='tick-held']");
await expect(held).toBeVisible();
await expect(held).toContainText(/held by a cap: .*daily cap/);
await expect(held.locator("[data-action-link]")).toHaveText("Raise cap");
await expect(held.locator("[data-action-link]")).toHaveAttribute("href", urls.generationPolicyHref());
const failed = page.locator("[data-group=your-call] [data-lit-line][data-piece='s:r5-fail'][data-card='tick-failed']");
await expect(failed).toBeVisible();
await expect(failed.locator("[data-action-link]")).toHaveText("Tick now");
await expect(failed.locator("[data-action-link]")).toHaveAttribute("href", urls.seriesHref("r5-fail"));
// The edition's article raises no iteration card of its own.
await expect(page.locator("[data-lit-line][data-piece^='a:articles/r5-cohost-']")).toHaveCount(0);
await shoot(page, "inbox-recurring");
// A held series has no edition: the next tick covers its window.
expect(series("r5-held").editions).toEqual([]);
});
test("a living report: Create makes it; its article carries the cadence chip with Pause and Tick now; delete is plan, then confirm", async ({ page }) => {
test.setTimeout(120_000);
await page.goto(urls.createHref({ make: "recurring" }));
const form = page.getByRole("form", { name: "a recurring report" });
await form.getByRole("radio", { name: "Living report" }).check();
await form.getByRole("textbox", { name: "topic" }).fill("R5 living");
await form.getByRole("textbox", { name: "find a channel" }).fill("site");
await form.getByRole("button", { name: /Site Channel/ }).click();
await clickAnswered(page, form.getByRole("button", { name: "Plan the schedule" }));
await expect(form.getByRole("region", { name: "plan recurring report" })).toContainText("a new article, r5-living: its first tick is its first sweep");
await clickAnswered(page, form.getByRole("button", { name: "Start the schedule" }));
await page.waitForURL(/\/articles\/r5-living$/, { timeout: 20_000 });
const head = page.locator("[data-piece-schedule='r5-living']");
await expect(head.locator("[data-schedule-chip]")).toHaveText(/weekly · next Mon 06:00/);
await clickAnswered(page, head.getByRole("button", { name: "Tick now" }));
await expect(head.locator("[data-schedule-said]")).toContainText(/Tick queued/);
// The first tick is the article's first sweep: an iteration, ready for review.
await expect(page.locator("[data-testid='piece-tab-iterations']")).toContainText("1");
await shoot(page, "living-chip");
await page.goto(urls.workHref({ recurring: "1" }));
await expect(page.locator("[data-lit-line][data-piece='a:articles/r5-living'] [data-work-chip]")).toHaveText(/weekly · next/);
await page.goto("/articles/r5-living");
await page.getByRole("button", { name: "More" }).click();
await clickAnswered(page, page.getByRole("button", { name: "Delete schedule" }));
const plan = page.getByRole("region", { name: "delete schedule r5-living" });
await expect(plan).toContainText("the schedule of r5-living");
await expect(plan.getByRole("list", { name: "what is kept" })).toContainText("the article r5-living and its iterations");
await expect(plan.getByRole("button", { name: "Confirm delete" })).toBeFocused();
await clickAnswered(page, plan.getByRole("button", { name: "Confirm delete" }));
await expect(page.locator("[data-piece-schedule]")).toHaveCount(0);
expect(existsSync(path.join(ARTICLES, "r5-living", "schedule.json"))).toBe(false);
expect(existsSync(path.join(ARTICLES, "r5-living", "iterations", "1", "iteration.json"))).toBe(true);
});
test("delete a series: the plan says the editions stay as articles; Keep it writes nothing; Confirm delete goes to the recurring list", async ({ page }) => {
await page.goto(urls.seriesHref("r5-cohost"));
await clickAnswered(page, page.getByRole("button", { name: "Delete schedule" }));
const plan = page.getByRole("region", { name: "delete schedule r5-cohost" });
await expect(plan).toContainText("the series r5-cohost");
await expect(plan.getByRole("list", { name: "what is kept" })).toContainText("1 edition article, as articles: r5-cohost-");
await page.keyboard.press("Escape");
await expect(plan).toHaveCount(0);
await expect(page.getByRole("button", { name: "Delete schedule" })).toBeFocused();
expect(existsSync(path.join(ARTICLES, ".series", "r5-cohost", "series.json"))).toBe(true);
await clickAnswered(page, page.getByRole("button", { name: "Delete schedule" }));
await clickAnswered(page, page.getByRole("region", { name: "delete schedule r5-cohost" }).getByRole("button", { name: "Confirm delete" }));
await page.waitForURL(/\/work\?recurring=1$/, { timeout: 20_000 });
expect(existsSync(path.join(ARTICLES, ".series", "r5-cohost"))).toBe(false);
// The edition is an article in its own right now.
const edition = readdirSync(ARTICLES).find((n) => n.startsWith("r5-cohost-"));
expect(edition).toBeTruthy();
});