import { test, expect, type Page } from "@playwright/test"; import { mkdir } from "node:fs/promises"; import { join } from "node:path"; import { resetData, writeSettings } from "./helpers"; import { testPaths } from "./testPaths"; // THE PAGES THAT STREAM. The dashboard, /jobs, /settings, /storage and // /channels send their shell — the sidebar, the heading, the controls — at // once, and each slow section when its read is done, behind a // boundary whose fallback is a skeleton the size of what is coming. // // Against this fixture every read is over in milliseconds, so the test server // honours a cookie (app/lib/streamDelay.ts, inert outside a test server) that // holds every streamed section back. With it a spec can see the three things // worth pinning: // // 1. THE SHELL COMES FIRST: the heading and every skeleton are in the // document before any section is. This is an assertion about ORDER in // the response, not about a clock. // 2. NOTHING MOVES WHEN A SECTION ARRIVES: each skeleton's box is the box of // the section that replaces it, to a few px. // 3. A REFRESH NEVER BRINGS A SKELETON BACK: router.refresh() (the global // AutoRefresh) is a transition, so a section already on screen stays // until its new render is ready. // // 4. A SECTION THAT FAILS FAILS ALONE: its place says so and the rest of // the page stands (StreamErrorBoundary) — on /settings, the form. // // The skeletons are sized by counts (live jobs, jobs listed, storage // locations), so the box test also runs with one of each SEEDED, through the // test routes and the settings file: the per-row constants are held to a // filled box, not only the empty ones. // // And the one thing streaming must not cost: a page that calls notFound() // still answers 404. Only these static routes carry a boundary; none of them // can be "not found". (navigation.spec.ts explains what a loading.tsx did to // that, and why there is none.) const DELAY_MS = 1500; const TOLERANCE_PX = 4; // The first-run checklist, as the document carries it (FirstRunPanel). const FIRST_RUN_MARK = 'aria-label="First steps"'; type Streamed = { path: string; heading: string; // data-stream-skeleton / data-stream-filled names, in document order. sections: string[]; }; const PAGES: Streamed[] = [ { path: "/", heading: "Dashboard", sections: ["dashboard-pipeline", "dashboard-needs-work", "dashboard-channels"], }, { path: "/jobs", heading: "Jobs", sections: ["jobs-list"] }, { path: "/settings", heading: "Settings", sections: ["settings-x", "settings-archives"] }, { path: "/storage", heading: "Storage", sections: ["storage-locations"] }, { path: "/channels", heading: "Channels", sections: ["channels-freshness", "channels-rack"] }, ]; async function holdSections(page: Page, baseURL: string) { await page.context().addCookies([ { name: "e2e-stream-delay", value: String(DELAY_MS), url: baseURL }, ]); } // What a browser console must not say on a streamed page: a hydration // mismatch, a suspended-outside-a-boundary error, an uncaught exception. function watchConsole(page: Page): string[] { const problems: string[] = []; page.on("console", (m) => { if (m.type() === "error") problems.push(m.text()); }); page.on("pageerror", (e) => problems.push(String(e))); return problems; } // Open `path` with every section held back, measure each skeleton, let the // sections arrive, and hold each one's box to its skeleton's. async function expectSkeletonsHoldTheirBoxes( page: Page, baseURL: string, { path, heading, sections }: Streamed, ) { const problems = watchConsole(page); await holdSections(page, baseURL); await page.goto(path, { waitUntil: "commit" }); await expect( page.getByRole("heading", { name: heading, level: 1 }), ).toBeAttached(); const before: Record = {}; for (const name of sections) { const skeleton = page.locator(`[data-stream-skeleton="${name}"]`); await expect(skeleton, name).toBeVisible(); before[name] = (await skeleton.boundingBox())!; } for (const name of sections) { const filled = page.locator(`[data-stream-filled="${name}"]`); await expect(filled, name).toBeVisible({ timeout: 15_000 }); } await expect(page.locator("[data-stream-skeleton]")).toHaveCount(0); for (const name of sections) { const after = (await page.locator(`[data-stream-filled="${name}"]`).boundingBox())!; const b = before[name]; const say = `${name}: skeleton ${JSON.stringify(b)} filled ${JSON.stringify(after)}`; expect.soft(Math.abs(after.y - b.y), say).toBeLessThanOrEqual(TOLERANCE_PX); expect.soft(Math.abs(after.height - b.height), say).toBeLessThanOrEqual(TOLERANCE_PX); expect.soft(Math.abs(after.x - b.x), say).toBeLessThanOrEqual(TOLERANCE_PX); expect.soft(Math.abs(after.width - b.width), say).toBeLessThanOrEqual(TOLERANCE_PX); } expect(problems, problems.join("\n")).toEqual([]); } test.describe("streamed pages", () => { test.beforeEach(async () => { await resetData("channel-with-counts"); }); for (const p of PAGES) { test(`${p.path}: the shell is sent before its sections`, async ({ baseURL }) => { const res = await fetch(baseURL + p.path, { headers: { "Accept-Encoding": "identity", Cookie: `e2e-stream-delay=${DELAY_MS}`, }, }); expect(res.status).toBe(200); const html = await res.text(); // THE SHELL is everything the server sent before the first section: the // document is written in the order it was produced, so what precedes // the first filled block was on its way before any section was ready. // (Its first mention in ANY form: its markup, or the component payload // that describes it, whichever the server wrote first.) const firstFilled = html.indexOf("data-stream-filled"); expect(firstFilled, "no section ever streamed in").toBeGreaterThan(0); const shell = html.slice(0, firstFilled); expect(shell, "the heading is not in the shell").toContain(""); for (const name of p.sections) { // Every skeleton is in the shell… expect(shell, name).toContain(`data-stream-skeleton="${name}"`); // …and each section streamed in after it. expect(html.slice(firstFilled), name).toContain(`data-stream-filled="${name}"`); } }); test(`${p.path}: each skeleton holds the box of the section that replaces it`, async ({ page, baseURL, }) => { await expectSkeletonsHoldTheirBoxes(page, baseURL!, p); }); test(`${p.path}: a refresh never brings a skeleton back`, async ({ page, baseURL }) => { await writeSettings({ autoRefreshIntervalSeconds: 1, adminTitle: "Before Title" }); const problems = watchConsole(page); await holdSections(page, baseURL!); await page.goto(p.path); for (const name of p.sections) { await expect(page.locator(`[data-stream-filled="${name}"]`), name).toBeVisible({ timeout: 15_000, }); } await expect(page.locator("[data-stream-skeleton]")).toHaveCount(0); // Count every skeleton that enters the document from here on. await page.evaluate(() => { const w = window as unknown as { __skeletons: number }; w.__skeletons = 0; new MutationObserver(() => { w.__skeletons += document.querySelectorAll("[data-stream-skeleton]").length; }).observe(document.body, { childList: true, subtree: true }); }); // A change the passive refresher brings in: the sidebar's title is the // root layout's, so seeing the new one means a whole refresh landed — // with every section held back DELAY_MS on the way. await writeSettings({ autoRefreshIntervalSeconds: 1, adminTitle: "After Title" }); await expect(page.locator("aside").getByText("After Title")).toBeVisible({ timeout: 20_000, }); for (const name of p.sections) { await expect(page.locator(`[data-stream-filled="${name}"]`), name).toBeVisible(); } expect( await page.evaluate(() => (window as unknown as { __skeletons: number }).__skeletons), ).toBe(0); expect(problems, problems.join("\n")).toEqual([]); }); } // THE ROW CONSTANTS, HELD TO A FILLED BOX. A fake job from the stuck-job // test route (a running job that has gone quiet: the row the list draws for // it carries its last log line) and, for /jobs, one more that is finished. const fakeJob = async (baseURL: string, queue: string): Promise => ((await (await fetch(`${baseURL}/api/test/stuck-job?queue=${queue}`)).json()) as { id: string }).id; const release = (baseURL: string, id: string) => fetch(`${baseURL}/api/test/stuck-job?release=${id}`); test("/: the pipeline band's skeleton holds its box with a live job in it", async ({ page, baseURL, }) => { const id = await fakeJob(baseURL!, "streaming-live"); try { await expectSkeletonsHoldTheirBoxes(page, baseURL!, { path: "/", heading: "Dashboard", sections: ["dashboard-pipeline", "dashboard-needs-work", "dashboard-channels"], }); await expect( page.locator('[data-stream-filled="dashboard-pipeline"] tbody tr'), ).toHaveCount(1); } finally { await release(baseURL!, id); } }); test("/jobs: the list's skeleton holds its box with a live and a finished job in it", async ({ page, baseURL, request, }) => { const live = await fakeJob(baseURL!, "streaming-live"); const done = await fakeJob(baseURL!, "streaming-done"); try { await release(baseURL!, done); // The finished one has to BE finished before the page is asked for. await expect .poll(async () => { const payload = (await (await request.get("/api/jobs/active")).json()) as { jobs: { id: string }[]; }; return payload.jobs.map((j) => j.id); }) .toEqual([live]); await expectSkeletonsHoldTheirBoxes(page, baseURL!, { path: "/jobs", heading: "Jobs", sections: ["jobs-list"], }); await expect(page.locator('[data-stream-filled="jobs-list"] tbody tr')).toHaveCount(2); } finally { await release(baseURL!, live); } }); test("/storage: the skeleton holds its box with a location configured", async ({ page, baseURL, }) => { const root = join(testPaths().transcriptsDir, ".streaming-location"); await mkdir(root, { recursive: true }); await writeSettings({ storage: { locations: [{ id: "cold", label: "Cold", root, autoRepoint: false }], defaultLocationId: "cold", }, }); await expectSkeletonsHoldTheirBoxes(page, baseURL!, { path: "/storage", heading: "Storage", sections: ["storage-locations"], }); await expect(page.getByLabel("storage location: cold")).toBeVisible(); }); // A SECTION THAT FAILS FAILS ALONE. The test server makes one section throw // (the `e2e-stream-fail` cookie, app/lib/streamDelay.ts). test("/settings: a session section that throws leaves the form and the other section standing", async ({ page, baseURL, }) => { await page.context().addCookies([ { name: "e2e-stream-fail", value: "settings-x", url: baseURL! }, ]); await page.goto("/settings"); const failed = page.locator('[data-stream-error="settings-x"]'); await expect(failed).toBeVisible(); await expect(failed).toContainText("The X session section could not be loaded."); // The form is there and saves. await expect(page.getByRole("heading", { name: "Settings", level: 1 })).toBeVisible(); await page.getByLabel(/auto-refresh interval/i).fill("0"); await page.getByRole("button", { name: /save settings/i }).click(); await expect(page.getByRole("status").filter({ hasText: "Saved" })).toBeVisible(); // The other streamed section arrived; nothing is left waiting. await expect(page.locator('[data-stream-filled="settings-archives"]')).toBeVisible(); await expect(page.locator("[data-stream-skeleton]")).toHaveCount(0); await expect(page.locator('[data-stream-error="settings-archives"]')).toHaveCount(0); }); test("the other pages: a section that throws says so in its place, under the heading", async ({ page, baseURL, }) => { const cases = [ { path: "/", heading: "Dashboard", name: "dashboard-pipeline", text: "The pipeline and Needs work could not be loaded." }, { path: "/jobs", heading: "Jobs", name: "jobs-list", text: "The job list could not be loaded." }, { path: "/storage", heading: "Storage", name: "storage-locations", text: "The storage locations could not be loaded." }, { path: "/channels", heading: "Channels", name: "channels-rack", text: "The channels could not be loaded." }, ]; for (const c of cases) { await page.context().clearCookies(); await page.context().addCookies([{ name: "e2e-stream-fail", value: c.name, url: baseURL! }]); await page.goto(c.path); await expect(page.getByRole("heading", { name: c.heading, level: 1 }), c.path).toBeAttached(); await expect(page.locator(`[data-stream-error="${c.name}"]`), c.path).toContainText(c.text); // The sidebar still works: the page is not the route's error page. await expect(page.locator("aside").getByRole("link", { name: "Jobs", exact: true }).first()).toBeVisible(); } }); // THE FIRST-RUN CHECKLIST IS PART OF THE SHELL: with no channel at all it is // sent with the heading, so it cannot push the page down when the live half // arrives. test("/: with no channel, the first-run checklist is in the shell", async ({ baseURL }) => { await resetData("empty"); const res = await fetch(baseURL + "/", { headers: { "Accept-Encoding": "identity", Cookie: `e2e-stream-delay=${DELAY_MS}` }, }); const html = await res.text(); const shell = html.slice(0, html.indexOf("data-stream-filled")); expect(shell).toContain(FIRST_RUN_MARK); // Once, not again with the live half. expect(html.split(FIRST_RUN_MARK).length - 1).toBe(1); }); // The regression guard beside navigation.spec.ts's: a boundary on the static // routes must not turn another route's notFound() into a 200. test("a channel that does not exist still answers 404", async ({ request }) => { const res = await request.get("/channels/this-channel-does-not-exist"); expect(res.status()).toBe(404); }); });