SPB Git

Repository Public

next-p-ra-ui.spec.ts 14.9 KB 173 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/e2e/next-p-ra-ui.spec.ts9 * Description      : P-RA UI fixes — load failures are error states with Retry10 *                    (tasks, trash, archive, search index / duplicates), task11 *                    quick-add does not invent due dates, delete is reachable12 *                    on touch and undoable, trash and search lists page with13 *                    "Show more". Desktop Chromium, scratch database only;14 *                    everything seeded carries the prefix `E2E-pra` and is15 *                    removed in afterAll.16 * Module           : tests17 * Repository       : https://git.spboucher.ai/note-spboucher-ai18 * Project Website  : https://note.spboucher.ai19 * Created          : 2026-11-1920 * Last Modified    : 2026-11-1921 *22 * Author           : Simon-Pierre Boucher23 * Position         : Professor of Finance24 * Institution      : Université du Québec en Outaouais (UQO)25 * Organization     : SP Boucher26 * Website          : https://spboucher.ai27 * Git              : https://git.spboucher.ai28 *29 * Preferred Contact: contact@spboucher.ai30 * Development      : dev@spboucher.ai31 * Support          : support@spboucher.ai32 * Security/Admin   : admin@spboucher.ai33 *34 * Copyright (c) 202635 * Simon-Pierre Boucher36 * All rights reserved where applicable. This file is governed by the37 * applicable project license, copyright notices and relevant law.38 * Existing third-party rights and notices remain unaffected.39 *40 * License          : None specified (no license file in this repository)41 *42 * Do not embed credentials, private keys, access tokens,43 * certificates or confidential personal information.44 *45 * =============================================================================46 * END OF SP BOUCHER SOURCE HEADER47 * =============================================================================48 */4950import { test, expect, type Page, type Route } from "@playwright/test";51import { apiCall, sql, STATE } from "./helpers";5253const PFX = "E2E-pra"; const stamp = Date.now().toString(36);54const pages: string[] = [];55test.afterAll(async () => {56  await sql`delete from tasks where title like ${PFX + " %"}`;57  if (pages.length) await sql`delete from pages where id = any(${pages}::uuid[])`;58  await sql`delete from pages where title like ${PFX + " %"}`;59});6061const fail = (route: Route) => route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: "E2E forced failure" }) });62/** The alert of an error state: title, the server message and a Retry button. */63async function expectError(page: Page, testId: string, title: RegExp) {64  const alert = page.getByTestId(testId); await expect(alert).toBeVisible({ timeout: 15_000 }); await expect(alert).toHaveAttribute("role", "alert");65  await expect(alert).toContainText(title); await expect(alert).toContainText("E2E forced failure"); await expect(alert.getByRole("button", { name: "Retry" })).toBeVisible();66  return alert;67}68const taskByTitle = async (page: Page, title: string) => ((await apiCall(page, "GET", "/api/tasks?done=1")).body as any[]).find((t) => t.title === title);6970test("U9 tasks: a failed load is an error state with Retry, not 'Inbox zero'; Retry recovers", async ({ page }) => {71  await page.goto("/"); const title = `${PFX} ${stamp} visible after retry`; expect((await apiCall(page, "POST", "/api/tasks", { title })).status).toBe(201);72  const api = /\/api\/tasks(\?.*)?$/; await page.route(api, (r) => (r.request().method() === "GET" ? fail(r) : r.continue()));73  await page.goto("/tasks"); const alert = await expectError(page, "tasks-error", /Could not load your tasks/);74  await expect(page.getByText("Inbox zero")).toHaveCount(0); await expect(page.getByText("Not loaded")).toBeVisible();75  await page.unroute(api); await alert.getByRole("button", { name: "Retry" }).click();76  await expect(page.getByTestId("tasks-error")).toHaveCount(0); await expect(page.getByTestId("task-row").filter({ hasText: title })).toBeVisible();77});7879test("U9 trash and archive: a failed load is an error state with Retry, not an empty list", async ({ page }) => {80  await page.goto("/"); const created = await apiCall(page, "POST", "/api/pages", { title: `${PFX} ${stamp} trashed` }); expect(created.status).toBe(201); pages.push(created.body.id);81  expect((await apiCall(page, "DELETE", `/api/pages/${created.body.id}`)).status).toBe(200);82  const trash = /\/api\/pages\?view=trash/; await page.route(trash, fail);83  await page.goto("/trash"); const alert = await expectError(page, "trash-error", /Could not load the trash/); await expect(page.getByText("Trash is empty")).toHaveCount(0);84  await page.unroute(trash); await alert.getByRole("button", { name: "Retry" }).click();85  await expect(page.getByTestId("trash-error")).toHaveCount(0); await expect(page.getByTestId("trash-row").filter({ hasText: `${PFX} ${stamp} trashed` })).toBeVisible();86  const archive = /\/api\/pages\?view=archived/; await page.route(archive, fail);87  await page.goto("/archive"); const a2 = await expectError(page, "archive-error", /Could not load the archive/); await expect(page.getByText("Nothing archived")).toHaveCount(0);88  await page.unroute(archive); await a2.getByRole("button", { name: "Retry" }).click(); await expect(page.getByTestId("archive-error")).toHaveCount(0);89});9091test("U9 search: the Index and Duplicates tabs show an error state with Retry and recover", async ({ page }) => {92  const idx = /\/api\/search\/index-state/, dups = /\/api\/search\/duplicates/;93  await page.route(idx, (r) => (r.request().method() === "GET" ? fail(r) : r.continue())); await page.route(dups, fail);94  await page.goto("/search");95  await page.getByRole("tab", { name: /^Index/ }).click(); const a = await expectError(page, "index-error", /Could not load the index status/);96  await page.unroute(idx); await a.getByRole("button", { name: "Retry" }).click();97  await expect(page.getByTestId("index-error")).toHaveCount(0); await expect(page.getByRole("button", { name: /Rebuild everything/ })).toBeVisible();98  await page.getByRole("tab", { name: "Duplicates" }).click(); const b = await expectError(page, "duplicates-error", /Could not load the duplicates/); await expect(page.getByText("No near-duplicate pages")).toHaveCount(0);99  await page.unroute(dups); await b.getByRole("button", { name: "Retry" }).click();100  await expect(page.getByTestId("duplicates-error")).toHaveCount(0); await expect(page.getByText(/No near-duplicate pages|% similar/).first()).toBeVisible();101});102103test("U12 quick-add: 'Buy sun cream' and 'Plan 3 days in Paris' keep their title and get no due date; 'tomorrow' still works", async ({ page }) => {104  await page.goto("/tasks"); const input = page.getByLabel("Add a task");105  const add = async (text: string) => { await input.fill(text); await page.keyboard.press("Enter"); await expect(input).toHaveValue(""); };106  const sun = `${PFX} ${stamp} Buy sun cream`, paris = `${PFX} ${stamp} Plan 3 days in Paris`, marc = `${PFX} ${stamp} Call Marc`;107  await add(sun); await add(paris); await add(`${marc} tomorrow`);108  await expect(page.getByTestId("task-row").filter({ hasText: sun })).toBeVisible(); await expect(page.getByTestId("task-row").filter({ hasText: sun }).getByTestId("task-due")).toHaveCount(0);109  const a = await taskByTitle(page, sun), b = await taskByTitle(page, paris), c = await taskByTitle(page, marc);110  expect(a).toBeTruthy(); expect(a.dueAt).toBeNull(); expect(b).toBeTruthy(); expect(b.dueAt).toBeNull(); expect(c).toBeTruthy(); expect(c.dueAt).not.toBeNull();111  await expect(page.getByTestId("task-row").filter({ hasText: marc }).getByTestId("task-due")).toBeVisible();112});113114test("U13 delete then Undo restores the same task; the restore route is idempotent", async ({ page }) => {115  await page.goto("/"); const title = `${PFX} ${stamp} undo me`; const made = await apiCall(page, "POST", "/api/tasks", { title, dueAt: "2031-01-15", priority: "high", project: "e2e" }); expect(made.status).toBe(201); const id = made.body.id;116  await page.goto("/tasks"); const row = page.getByTestId("task-row").filter({ hasText: title }); await expect(row).toBeVisible();117  await row.hover(); await row.getByRole("button", { name: `Delete task: ${title}` }).click();118  await expect(row).toHaveCount(0); await expect(page.getByText("Task deleted")).toBeVisible(); expect((await apiCall(page, "GET", `/api/tasks/${id}`)).body.deletedAt).toBeTruthy();119  await page.getByRole("button", { name: "Undo" }).click();120  await expect(row).toBeVisible(); await expect(page.getByText("Task restored")).toBeVisible();121  const back = (await apiCall(page, "GET", `/api/tasks/${id}`)).body; expect(back.deletedAt ?? null).toBeNull(); expect(back.title).toBe(title); expect(back.priority).toBe("high"); expect(back.project).toBe("e2e"); expect(String(back.dueAt)).toContain("2031-01-15");122  // route contract: restoring a live task changes nothing; unknown action and unknown id are refused123  expect((await apiCall(page, "POST", `/api/tasks/${id}?action=restore`)).status).toBe(200);124  expect((await apiCall(page, "POST", `/api/tasks/${id}?action=explode`)).status).toBe(400);125  expect((await apiCall(page, "POST", "/api/tasks/00000000-0000-4000-8000-000000000000?action=restore")).status).toBe(404);126});127128test("U13 touch: the delete button is visible with a 44 px target and the due date shows on a 360 px screen", async ({ page, browser }) => {129  await page.goto("/"); const title = `${PFX} ${stamp} touch row`; expect((await apiCall(page, "POST", "/api/tasks", { title, dueAt: "2031-02-20" })).status).toBe(201);130  const ctx = await browser.newContext({ viewport: { width: 360, height: 740 }, isMobile: true, hasTouch: true, storageState: STATE }); const phone = await ctx.newPage();131  try {132    await phone.goto("/tasks"); const fine = await phone.evaluate(() => window.matchMedia("(hover: hover) and (pointer: fine)").matches);133    test.skip(fine, "this browser does not emulate a coarse pointer");134    const row = phone.getByTestId("task-row").filter({ hasText: title }); await expect(row).toBeVisible(); await expect(row.getByTestId("task-due")).toBeVisible();135    const del = row.getByRole("button", { name: `Delete task: ${title}` }); await expect(del).toBeVisible(); expect(await del.evaluate((el) => getComputedStyle(el).opacity)).toBe("1");136    const box = (await del.boundingBox())!; expect(box.width).toBeGreaterThanOrEqual(44); expect(box.height).toBeGreaterThanOrEqual(44);137    expect(await phone.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth + 1)).toBe(true);138  } finally { await ctx.close(); }139});140141test("U10 trash: more than 100 trashed pages are reached with 'Show more'; ?offset= is validated", async ({ page }) => {142  test.setTimeout(120_000); await page.goto("/"); const N = 103; const ids: string[] = [];143  for (let i = 0; i < N; i += 10) { const batch = await Promise.all(Array.from({ length: Math.min(10, N - i) }, (_v, k) => apiCall(page, "POST", "/api/pages", { title: `${PFX} ${stamp} bulk ${String(i + k).padStart(3, "0")}` }))); for (const r of batch) { expect(r.status).toBe(201); ids.push(r.body.id); pages.push(r.body.id); } }144  // trashed long ago: they close the list (most recently deleted first), whatever the scratch trash already holds145  await sql`update pages set deleted_at = timestamptz '2001-01-01' + (random() * interval '1 day') where id = any(${ids}::uuid[])`;146  const first = await apiCall(page, "GET", "/api/pages?view=trash&limit=100"); expect(first.status).toBe(200); expect(first.body.length).toBe(100); expect(first.headers["x-next-offset"]).toBe("100");147  const second = await apiCall(page, "GET", "/api/pages?view=trash&limit=100&offset=100"); expect(second.status).toBe(200); expect(second.body.length).toBeGreaterThanOrEqual(3);148  const overlap = new Set(first.body.map((p: any) => p.id)); expect(second.body.some((p: any) => overlap.has(p.id))).toBe(false);149  for (const bad of ["-1", "abc", "1.5", "9999999"]) { const r = await apiCall(page, "GET", `/api/pages?view=trash&offset=${bad}`); expect(r.status, bad).toBe(400); expect(r.body.code).toBe("bad_offset"); }150  const plain = await apiCall(page, "GET", "/api/pages?view=recent&limit=1"); expect(plain.status).toBe(200); expect(Array.isArray(plain.body)).toBe(true);151  await page.goto("/trash"); const rows = page.getByTestId("trash-row"); await expect(rows).toHaveCount(100); const more = page.getByTestId("trash-more");152  await expect(more).toContainText("Showing the first 100."); const bulk = rows.filter({ hasText: `${PFX} ${stamp} bulk` });153  for (let i = 0; i < 30 && (await more.getByRole("button", { name: "Show more" }).count()); i++) { const n = await rows.count(); await more.getByRole("button", { name: "Show more" }).click(); await expect.poll(() => rows.count()).toBeGreaterThan(n); }154  await expect(page.getByTestId("trash-more")).toHaveCount(0); await expect(bulk).toHaveCount(N);155});156157test("U10 search: results load 40 at a time up to 120, then the list says it is truncated", async ({ page }) => {158  const limits: number[] = [];159  await page.route(/\/api\/search\?/, (r) => { const u = new URL(r.request().url()); if (u.searchParams.get("mode") !== "hybrid") return r.continue(); const limit = Number(u.searchParams.get("limit")); limits.push(limit);160    const hits = Array.from({ length: Math.min(limit, 500) }, (_v, i) => ({ chunkId: `c${i}`, pageId: null, sourceType: "page", sourceId: `s${i}`, title: `${PFX} hit ${i + 1}`, icon: null, heading: null, blockId: null, content: `passage ${i + 1}`, semantic: 0, keyword: 1, kind: "page" }));161    return r.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(hits) }); });162  await page.goto(`/search?q=${encodeURIComponent(`${PFX} many`)}`);163  const items = page.getByTestId("search-results").locator("> li"); const more = page.getByTestId("search-more"); const btn = more.getByRole("button", { name: "Show more" });164  await expect(items).toHaveCount(40); await expect(more).toContainText("Showing the first 40."); await expect(page.getByRole("tab", { name: "Results · 40+" })).toBeVisible();165  await btn.click(); await expect(items).toHaveCount(80); await btn.click(); await expect(items).toHaveCount(120);166  await expect(more).toContainText("Showing the first 120 results"); await expect(btn).toHaveCount(0); expect(limits).toEqual(expect.arrayContaining([40, 80, 120])); expect(Math.max(...limits)).toBe(120);167  // a new query starts again at the first 40168  await page.getByLabel("Search everything").fill(`${PFX} other`); await expect(items).toHaveCount(40); expect(limits[limits.length - 1]).toBe(40);169  await page.unrouteAll({ behavior: "ignoreErrors" });170  // the route itself accepts the higher limit (it capped at 60 before) and still answers a plain array171  const r = await apiCall(page, "GET", "/api/search?mode=quick&q=&limit=120"); expect(r.status).toBe(200); expect(Array.isArray(r.body)).toBe(true);172});173
Files main
Menu

Theme