From 9b5f7776a684f1b68e9637b90571ea6d224264c0 Mon Sep 17 00:00:00 2001 From: Tyler Hallada Date: Sun, 15 Nov 2026 14:30:50 -0500 Subject: [PATCH] Browser tests Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab --- e2e/helpers.ts | 103 ++++++++++ e2e/keyboard.spec.ts | 291 ++++++++++++++++++++++++++ e2e/links.spec.ts | 477 +++++++++++++++++++++++++++++++++++++++++++ e2e/menu.spec.ts | 350 +++++++++++++++++++++++++++++++ e2e/more.spec.ts | 177 ++++++++++++++++ e2e/panes.spec.ts | 314 ++++++++++++++++++++++++++++ e2e/research.spec.ts | 102 +++++++++ e2e/review.spec.ts | 282 +++++++++++++++++++++++++ e2e/scale.spec.ts | 121 +++++++++++ 9 files changed, 2217 insertions(+) create mode 100644 e2e/helpers.ts create mode 100644 e2e/keyboard.spec.ts create mode 100644 e2e/links.spec.ts create mode 100644 e2e/menu.spec.ts create mode 100644 e2e/more.spec.ts create mode 100644 e2e/panes.spec.ts create mode 100644 e2e/research.spec.ts create mode 100644 e2e/review.spec.ts create mode 100644 e2e/scale.spec.ts diff --git a/e2e/helpers.ts b/e2e/helpers.ts new file mode 100644 index 0000000..7653ccd --- /dev/null +++ b/e2e/helpers.ts @@ -0,0 +1,103 @@ +/** + * What the browser tests share: driving the page from the keyboard, reading the store the page + * exposes as globalThis.__ie, waiting for it to settle, and the links written into the shared + * library over the op API, as an outside agent would (every kind of target, a note that also links, + * a cross-document node link, two documents mentioning one article; the articles are the mock + * Wikipedia's fixtures in server/wikiMock.ts). + */ +import { writeFileSync } from "node:fs"; +import type { APIRequestContext, Page } from "@playwright/test"; + +/** A keypress → paint timing, as the page records it. */ +export interface Sample { + what: string; + ms: number; +} + +/** Run a function on the page's store and return what it returns. */ +export const state = (page: Page, fn: (s: any) => T): Promise => page.evaluate(`(${fn})(globalThis.__ie)`) as Promise; + +/** Press space-separated keys, in order. */ +export const keys = async (page: Page, seq: string) => { + for (const k of seq.split(" ")) await page.keyboard.press(k); +}; + +/** / then a title then Enter: jump to a section. */ +export const jump = async (page: Page, title: string) => { + await page.keyboard.press("/"); + await page.keyboard.type(title); + await page.keyboard.press("Enter"); +}; + +/** : then text then Enter. */ +export const command = async (page: Page, text: string) => { + await page.keyboard.press(":"); + await page.keyboard.type(text); + await page.keyboard.press("Enter"); +}; + +/** Wait until no generation, reconciliation or link scan is running. */ +export const idle = (page: Page) => + page.waitForFunction(() => { + const s = (globalThis as any).__ie; + return s.busy === 0 && s.pending.size === 0 && s.links.busy === 0; + }); + +/** Wait until the server has every edit the page made. */ +export const synced = (page: Page) => page.waitForFunction(() => (globalThis as any).__ie.synced()); + +/** The tests share one server-side library: let each test's work reach it before the page closes. */ +export async function settle(page: Page) { + if (!(await page.evaluate(() => !!(globalThis as any).__ie?.ready).catch(() => false))) return; + await idle(page); + await synced(page); +} + +export const focusedTitle = (page: Page) => state(page, (s) => s.snap.nodes[s.focus.node].title); +/** The selected words. */ +export const selected = (page: Page) => state(page, (s) => (s.focus.range ? s.snap.nodes[s.focus.node].body.slice(s.focus.range[0], s.focus.range[1]) : "") as string); + +/** Write a latency report to test-results/latency-.json. */ +export const writeReport = (name: string, report: unknown) => writeFileSync(`test-results/latency-${name}.json`, JSON.stringify(report, null, 2)); + +// ---- links written into the shared library ---- + +interface Snap { + root: string; + nodes: Record; +} + +const W = (title: string) => ({ kind: "wiki", title, lang: "en" }); + +/** Find a section by its document's slug and title path. */ +function find(s: Snap, slug: string, ...path: string[]): string { + let at = s.nodes[s.root].children.find((c) => s.nodes[c].slug === slug)!; + for (const t of path) at = s.nodes[at].children.find((c) => s.nodes[c].kind === "section" && s.nodes[c].title === t)!; + if (!at) throw new Error(`no ${slug}/${path.join("/")}`); + return at; +} +const noteOn = (s: Snap, parent: string, quote: string) => s.nodes[parent].children.find((c) => s.nodes[c].kind === "note" && s.nodes[c].anchors[0]?.text === quote)!; + +export async function seedLinks(request: APIRequestContext) { + const s: Snap = await (await request.get("/api/tree")).json(); + const recursion = find(s, "fixed-points", "Recursion without names"); + if (s.nodes[recursion].children.some((c) => s.nodes[c].ref)) return; // already seeded by an earlier test + const howY = find(s, "fixed-points", "Recursion without names", "How Y works"); + const triple = find(s, "origin-of-the-elements", "Fusion in ordinary stars", "The triple-alpha process"); + const separate = find(s, "octopus-minds", "A separate experiment"); + const programs = find(s, "what-a-proof-is", "Proof assistants", "Proofs as programs"); + const ops = [ + { op: "create", parent: recursion, kind: "note", quote: "fixed-point combinator", ref: W("Fixed-point combinator") }, + { op: "update", id: noteOn(s, recursion, "lambda calculus"), ref: W("Lambda calculus") }, + { op: "create", parent: recursion, kind: "note", quote: "Y combinator", ref: { kind: "node", id: howY, doc: "fixed-points", path: ["Recursion without names", "How Y works"] } }, + { op: "create", parent: recursion, kind: "note", quote: "self-reference", ref: { kind: "url", url: "https://plato.stanford.edu/entries/self-reference/", title: "Self-Reference (Stanford Encyclopedia of Philosophy)" } }, + { op: "update", id: noteOn(s, triple, "an excited state at almost exactly the energy"), ref: W("Hoyle state") }, + { op: "create", parent: triple, kind: "note", quote: "Fred Hoyle", ref: W("Fred Hoyle") }, + { op: "create", parent: separate, kind: "note", quote: "octopus", ref: W("Octopus") }, + { op: "update", id: noteOn(s, separate, "cephalopod"), ref: W("Cephalopod") }, + { op: "create", parent: programs, kind: "note", quote: "a function turning proofs", ref: W("Lambda calculus") }, + { op: "create", parent: programs, kind: "note", quote: "Several of the leading systems", ref: { kind: "node", id: recursion, doc: "fixed-points", path: ["Recursion without names"] } }, + ]; + const res = await request.post("/api/ops", { data: { author: "linker", message: "Seed links for the link tests", ops } }); + if (!res.ok()) throw new Error(`seeding links failed: ${res.status()} ${await res.text()}`); +} diff --git a/e2e/keyboard.spec.ts b/e2e/keyboard.spec.ts new file mode 100644 index 0000000..e7ccfef --- /dev/null +++ b/e2e/keyboard.spec.ts @@ -0,0 +1,291 @@ +/** + * A scripted run of the app using only the keyboard, against the production build and the + * deterministic mock model. Assertions read state from the page; every action is a keystroke. + * Latencies are measured in the page (keydown timestamp → the frame after the render). + */ +import { expect, test, type Page } from "@playwright/test"; +import { command, focusedTitle, idle, jump, keys, settle, state, writeReport, type Sample } from "./helpers"; + +const titlesUnder = (page: Page, title: string) => + page.evaluate((t) => { + const s = (globalThis as any).__ie; + const n = Object.values(s.snap.nodes).find((x: any) => x.title === t) as any; + return n.children.map((c: string) => s.snap.nodes[c]).filter((c: any) => c.kind === "section").map((c: any) => c.title) as string[]; + }, title); + +/** The first document, opened in the column (hoisted, with the library one step out). */ +async function open(page: Page) { + await page.goto("/doc/infinite-expand"); + await page.waitForSelector("article"); + await page.evaluate(() => document.fonts.ready); +} + +test.describe.configure({ mode: "serial" }); + +// The tests share one server-side library. Let each test's work reach it before the page closes. +test.afterEach(({ page }) => settle(page)); + +test("opens on an outline of ten titles with the prompt folded above it", async ({ page }) => { + await open(page); + await expect(page.locator("article > .outline > .node")).toHaveCount(10); + await expect(page.locator(".node.open")).toHaveCount(0); + await expect(page.locator(".abstract.seed.folded")).toBeVisible(); + await expect(page.locator("h1")).toHaveText("Infinispand"); + await page.keyboard.press("Enter"); + await expect(page.locator(".abstract.seed.folded")).toHaveCount(0); + await expect(page.locator(".abstract.seed")).toContainText("I think maybe we want something like CDRTs under the hood"); +}); + +test("pre-generated expansions paint within the 50 ms budget", async ({ page }) => { + await open(page); + // One keystroke per frame (about 60 a second, well past any typist). Sent faster than that, + // keys queue behind each other and the measurement becomes the length of the queue. + const keys = async (p: Page, seq: string) => { + for (const k of seq.split(" ")) { + await p.keyboard.press(k); + await p.evaluate(() => new Promise((r) => requestAnimationFrame(() => r(null)))); + } + }; + // Walk the whole pre-generated outline: open every section, top to bottom, then every note in a few. + for (let i = 0; i < 70; i++) await keys(page, "j l"); + const opened = await page.locator(".node.open").count(); + expect(opened).toBeGreaterThan(40); + // Close and reopen subtrees, and step through grains. + await keys(page, "O j l h l i j j i l l Escape Escape"); + // Open notes in every form from the keyboard. + await jump(page, "Levels of a node"); + await keys(page, "Tab Enter Tab Enter Tab Enter Escape Escape"); + await jump(page, "Expansion by depth"); + await keys(page, "Tab Enter Tab Enter"); + await expect(page.locator(".gloss").first()).toBeVisible(); + await expect(page.locator(".inset").first()).toBeVisible(); + await expect(page.locator(".sidenote").first()).toBeVisible(); + + const samples: Sample[] = await state(page, (s) => s.samples); + const ms = samples.filter((x) => x.what !== "first-token").map((x) => x.ms).sort((a, b) => a - b); + const pct = (p: number) => ms[Math.min(ms.length - 1, Math.floor(ms.length * p))]; + const report = { keystrokes: ms.length, median: pct(0.5), p95: pct(0.95), max: ms[ms.length - 1] }; + const slow = samples.filter((x) => x.what !== "first-token" && x.ms > 30).map((x) => `${x.what}:${Math.round(x.ms)}`); + console.log("keypress → paint (ms):", JSON.stringify(report), "over 30ms:", slow.join(" ")); + writeReport("paint", report); + expect(ms.length).toBeGreaterThan(150); + expect(report.p95).toBeLessThan(50); +}); + +test("a margin note sits beside its line and does not overlap its neighbours", async ({ page }) => { + await open(page); + await jump(page, "Expansion by depth"); + await keys(page, "l Tab Enter"); + const note = page.locator(".sidenote").first(); + const anchor = page.locator(".anchor.on").first(); + const [n, a, col] = await Promise.all([note.boundingBox(), anchor.boundingBox(), page.locator("article").boundingBox()]); + expect(n!.x).toBeGreaterThan(col!.x + col!.width); // in the margin, not the column + expect(Math.abs(n!.y - a!.y)).toBeLessThan(40); // level with the words it is about +}); + +test("past the pre-generated text, a selection is expanded by the model, in a form that follows its size", async ({ page }) => { + await open(page); + await jump(page, "Gloss"); + // Sentence grain → a margin note, streamed. + await keys(page, "l i j e"); + await expect(page.locator(".sidenote.pending")).toBeVisible(); + await idle(page); + await expect(page.locator(".sidenote")).toContainText("Mock note on"); + // Word grain → an inline gloss. + await keys(page, "i l l d"); + await idle(page); + await expect(page.locator(".gloss").last()).toContainText("mock gloss of"); + // Several sentences → an inset passage, with the reader's own question as the lens. + await jump(page, "Levels of a node"); + await keys(page, "l i J J"); + await command(page, "how does this fail?"); + await idle(page); + await expect(page.locator(".inset").last()).toContainText("through the how does this fail? lens"); + + const notes = await state(page, (s) => + Object.values(s.snap.nodes).filter((c: any) => c.kind === "note" && /^[Mm]ock/.test(c.body)).map((c: any) => c.form).sort(), + ); + expect(notes).toEqual(["gloss", "note", "passage"]); + + const samples: Sample[] = await state(page, (s) => s.samples); + const first = samples.filter((x) => x.what === "first-token").map((x) => x.ms); + console.log("request → first token painted (ms, mock model):", JSON.stringify(first.map(Math.round))); + writeReport("first-token", { mock: true, samples: first }); + expect(first.length).toBe(3); + expect(Math.max(...first)).toBeLessThan(1000); +}); + +test("a note is a node: it can be entered and expanded again", async ({ page }) => { + await open(page); + await jump(page, "Gloss"); + await keys(page, "l Tab Enter Enter"); // open the pre-generated gloss, then step into it + expect(await state(page, (s) => s.snap.nodes[s.focus.node].kind)).toBe("note"); + await keys(page, "i i e"); // a word inside the note + await idle(page); + const depth = await state(page, (s) => Object.values(s.snap.nodes).filter((n: any) => n.kind === "note" && s.snap.nodes[n.parent].kind === "note" && /mock/.test(n.body)).length); + expect(depth).toBe(1); +}); + +test("a leaf with no children gets subsections on request", async ({ page }) => { + await open(page); + await jump(page, "Sidenote"); + expect(await titlesUnder(page, "Sidenote")).toEqual([]); + await keys(page, "e e"); // open, then go deeper + await idle(page); + expect(await titlesUnder(page, "Sidenote")).toEqual(["First part of Sidenote", "Second part of Sidenote"]); + await expect(page.locator(".node.open", { hasText: "First part of Sidenote" }).first()).toBeVisible(); +}); + +test("editing a node pins it, and the model reconciles its parent and its open children", async ({ page }) => { + await open(page); + await jump(page, "Passage"); + await keys(page, "l c"); + await page.keyboard.press("Control+a"); + await page.keyboard.type("A human rewrote this section entirely."); + await page.keyboard.press("Escape"); + await idle(page); + const after = await state(page, (s) => { + const by = (t: string): any => Object.values(s.snap.nodes).find((x: any) => x.title === t); + return { passage: by("Passage"), parent: by("Display forms").body, log: s.log.map((l: any) => l.text) }; + }); + expect(after.passage).toMatchObject({ body: "A human rewrote this section entirely.", pinned: true, by: "human" }); + // The mock resolver says one level up needs rewriting; the level above that is kept. + expect(after.parent).toMatch(/^Re-summarised from: Gloss; Sidenote; Passage/); + expect(after.log.some((l: string) => /1 level up/.test(l))).toBe(true); + await expect(page.locator(".flags.attn")).toHaveCount(0); +}); + +test("add, rename, move, delete and undo, without leaving the keyboard", async ({ page }) => { + await open(page); + await jump(page, "Keyboard and focus"); + const before = await titlesUnder(page, "Keyboard and focus"); + await keys(page, "l a"); + await page.keyboard.type("Chords"); + await page.keyboard.press("Enter"); + await idle(page); + expect(await titlesUnder(page, "Keyboard and focus")).toEqual([...before, "Chords"]); + expect(await focusedTitle(page)).toBe("Chords"); + await keys(page, "K K"); + await idle(page); + expect((await titlesUnder(page, "Keyboard and focus")).indexOf("Chords")).toBe(before.length - 2); + await keys(page, "r"); + await page.keyboard.press("Control+a"); + await page.keyboard.type("Key chords"); + await page.keyboard.press("Enter"); + await idle(page); + expect(await titlesUnder(page, "Keyboard and focus")).toContain("Key chords"); + await keys(page, "D"); + await idle(page); + expect(await titlesUnder(page, "Keyboard and focus")).not.toContain("Key chords"); + // Every one of those steps, and every reconciliation they triggered, is a named, hashed commit. + const log = await state(page, (s) => s.commits().slice(0, 12).map((c: any) => [c.message, !!c.hash])); + expect(log.filter(([m]: [string]) => m === "(undo/redo)")).toEqual([]); + expect(log.every(([, hashed]: [string, boolean]) => hashed)).toBe(true); + expect(log.map(([m]: [string]) => m)).toContain("Delete “Key chords”"); + await keys(page, "u"); + expect(await titlesUnder(page, "Keyboard and focus")).toContain("Key chords"); +}); + +test("the editor agent edits through the same ops and its work is merged back", async ({ page }) => { + await open(page); + await jump(page, "The tree underneath"); + await command(page, 'add "Garbage collection"'); + await idle(page); + expect(await titlesUnder(page, "The tree underneath")).toContain("Garbage collection"); + const commit = await state(page, (s) => s.commits().find((c: any) => c.message.startsWith("Agent: add"))); + expect(commit).toMatchObject({ by: "agent", actor: "llm" }); + // u takes the agent's work back. + await keys(page, "u"); + expect(await titlesUnder(page, "The tree underneath")).not.toContain("Garbage collection"); +}); + +test("history: every commit verifies, any commit can be viewed, and a revert is a new commit", async ({ page }) => { + await open(page); + await keys(page, "g v"); + await expect(page.locator(".verdict")).toContainText(/Verified: all \d+ hashed commits reproduce byte-for-byte/); + const total = await state(page, (s) => s.commits().length); + expect(total).toBeGreaterThan(11); + // Walk down to the oldest commits (the library's creation, then the first document's) and look + // at the document as it was when only three sections had been written. + for (let i = 0; i < total + 5; i++) await page.keyboard.press("j"); + await keys(page, "k k k k Enter"); + await expect(page.locator(".banner")).toContainText("Read-only"); + await expect(page.locator("article > .outline > .node")).toHaveCount(3); + // Writing is refused while viewing the past. + await keys(page, "a"); + await expect(page.locator(".status .message")).toContainText("read-only"); + await expect(page.locator(".title-editor")).toHaveCount(0); + // Revert to it: the document goes back, the rest of the library stays, and the revert is itself + // a commit that can be undone. + const others = await state(page, (s) => s.doc.snap().nodes[s.doc.snap().root].children.filter((c: string) => c !== s.currentDoc).map((c: string) => s.doc.shape(undefined, c)).join()); + expect(others).not.toBe(""); + await keys(page, "r"); + await expect(page.locator(".banner")).toHaveCount(0); + await expect(page.locator("article > .outline > .node")).toHaveCount(3); + expect(await state(page, (s) => s.commits()[0].tag)).toBe("revert"); + expect(await state(page, (s) => s.doc.snap().nodes[s.doc.snap().root].children.filter((c: string) => c !== s.currentDoc).map((c: string) => s.doc.shape(undefined, c)).join())).toBe(others); + await keys(page, "v"); + await expect(page.locator(".verdict")).toContainText("Verified"); + await keys(page, "Escape u"); + await expect(page.locator("article > .outline > .node")).toHaveCount(10); +}); + +test("branches merge; a conflict in meaning is found, resolved by the model, and can be overruled", async ({ page }) => { + await open(page); + const edit = async (text: string) => { + await jump(page, "Deeper, not longer"); + await keys(page, "l c"); + await page.keyboard.press("Control+a"); + await page.keyboard.type(text); + await page.keyboard.press("Escape"); + await idle(page); + }; + await command(page, "/auto off"); // keep the cascade out of this test + await command(page, "/branch alt"); + await edit("On alt: deeper text is always shorter."); + await command(page, "/switch main"); + await edit("On main: deeper text is never shorter."); + await command(page, "/auto on"); + await command(page, "/merge alt"); + await idle(page); + const conflicts = await state(page, (s) => s.doc.conflicts()); + expect(conflicts).toHaveLength(1); + expect(conflicts[0]).toMatchObject({ type: "edit-edit", status: "resolved", resolvedBy: "resolver" }); + expect([conflicts[0].a, conflicts[0].b].sort()).toEqual(["On alt: deeper text is always shorter.", "On main: deeper text is never shorter."]); + // Review it in the panel and overrule the model: take side B instead. + await keys(page, "g"); + for (let i = 0; i < 40; i++) await page.keyboard.press("k"); + await expect(page.locator(".conflict.selected")).toContainText("resolved by resolver"); + await keys(page, "x"); + expect((await state(page, (s) => s.doc.conflicts()))[0].status).toBe("open"); + await keys(page, "2"); + const settled = (await state(page, (s) => s.doc.conflicts()))[0]; + expect(settled).toMatchObject({ status: "resolved", resolvedBy: "tester", resolved: settled.b }); + await keys(page, "v"); + await expect(page.locator(".verdict")).toContainText("Verified"); +}); + +test("two people editing at once converge, and the document survives a reload", async ({ browser }) => { + const a = await (await browser.newContext()).newPage(); + const b = await (await browser.newContext()).newPage(); + await open(a); + await open(b); + await jump(a, "A shared working memory"); + await keys(a, "l a"); + await a.keyboard.type("Written by A"); + await a.keyboard.press("Enter"); + await jump(b, "How we know it works"); + await keys(b, "l a"); + await b.keyboard.type("Written by B"); + await b.keyboard.press("Enter"); + await expect.poll(() => titlesUnder(a, "How we know it works")).toContain("Written by B"); + await expect.poll(() => titlesUnder(b, "A shared working memory")).toContain("Written by A"); + await idle(a); + await idle(b); + await expect.poll(async () => (await state(a, (s) => s.doc.stateHash())) === (await state(b, (s) => s.doc.stateHash()))).toBe(true); + await a.reload(); + await a.waitForSelector("article"); + expect(await titlesUnder(a, "How we know it works")).toContain("Written by B"); + // The view is remembered too: the section A opened is still open. + await expect(a.locator(".node.open", { hasText: "A shared working memory" }).first()).toBeVisible(); +}); diff --git a/e2e/links.spec.ts b/e2e/links.spec.ts new file mode 100644 index 0000000..576d0e7 --- /dev/null +++ b/e2e/links.spec.ts @@ -0,0 +1,477 @@ +/** + * Links and Wikipedia, keyboard only, against the mock Wikipedia (IE_WIKI=mock, server/wikiMock.ts) + * and the shared library with links written into it over the op API (e2e/helpers.ts). Nothing here + * touches the network: requests to wikipedia.org are refused, so a test that opens one only sees + * the address it would have gone to. + */ +import { expect, test, type Page } from "@playwright/test"; +import { command, focusedTitle, jump, keys, seedLinks, selected, settle, state, writeReport, type Sample } from "./helpers"; + +/** The panes' titles, left to right: a node's title, or W:article for a Wikipedia pane. */ +const trail = (page: Page) => + state(page, (s) => s.trail.map((p: any) => (p.kind === "node" ? s.snap.nodes[p.id].title || s.snap.nodes[p.id].anchors[0]?.text : `W:${p.title}${p.sec ? `#${p.sec}` : ""}`))); +const panes = (page: Page) => page.locator(".strip > .pane"); + +/** Tab through the focused section's marked spans until the selection is these words. */ +async function tabTo(page: Page, words: string) { + for (let i = 0; i < 12; i++) { + await page.keyboard.press("Tab"); + if ((await selected(page)) === words) return; + } + throw new Error(`Tab never reached “${words}”`); +} + +async function column(page: Page, path = "/doc/fixed-points") { + await page.setViewportSize({ width: 1440, height: 900 }); + await page.goto(path); + await page.waitForFunction(() => (globalThis as any).__ie?.ready); + await page.evaluate(() => document.fonts.ready); +} +async function wide(page: Page, path = "/doc/fixed-points") { + await page.setViewportSize({ width: 1920, height: 1080 }); + await page.goto(path); + await page.waitForSelector(".strip > .pane"); + await page.evaluate(() => document.fonts.ready); +} +/** Open a section in panes and select the first marked span in its text. */ +async function inPane(page: Page, title: string, words: string) { + await jump(page, title); + await tabTo(page, words); +} + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ request }) => { + await seedLinks(request); +}); + +test.beforeEach(async ({ context }) => { + // The mock answers /api/wiki; wikipedia.org itself is never reached from a test. + await context.route(/wikipedia\.org|wikimedia\.org|evil\.example|stanford\.edu|example\.org/, (r) => r.abort()); +}); + +test.afterEach(({ page }) => settle(page)); + +test("each kind of link has its mark; a note that also links keeps its dotted underline", async ({ page }) => { + await column(page); + await jump(page, "Recursion without names"); + await keys(page, "Enter"); + const sec = page.locator(".node.open", { hasText: "Recursion without names" }).first(); + // Wikipedia: solid underline and a W after the words. + const wiki = sec.locator(".lnk.l-wiki", { hasText: "fixed-point combinator" }); + await expect(wiki).toBeVisible(); + expect(await wiki.evaluate((el) => getComputedStyle(el).textDecorationLine)).toContain("underline"); + await expect(sec.locator(".lmark.l-wiki").first()).toHaveText("W"); + // Another note in the library: §, with the document in its tooltip. + await expect(sec.locator(".lnk.l-node", { hasText: "Y combinator" })).toBeVisible(); + const nodeMark = sec.locator(".lmark.l-node").first(); + await expect(nodeMark).toHaveText("§"); + expect(await nodeMark.getAttribute("title")).toContain("in Fixed points"); + // The web: ↗. + await expect(sec.locator(".lnk.l-url", { hasText: "self-reference" })).toBeVisible(); + await expect(sec.locator(".lmark.l-url")).toHaveText("↗"); + // Both: "lambda calculus" is a gloss (dotted) that also links to an article (W). + const both = sec.locator(".anchor", { hasText: "lambda calculus" }); + await expect(both).toBeVisible(); + expect(await both.evaluate((el) => getComputedStyle(el).backgroundImage)).toContain("gradient"); + expect(await both.evaluate((el) => el.nextElementSibling?.className)).toContain("lmark l-wiki"); + // The marks are not text: the body offsets are unchanged and the mark cannot be selected. + expect(await sec.locator(".lmark").first().evaluate((el) => getComputedStyle(el).userSelect)).toBe("none"); +}); + +test("hovering a link shows its preview and leaving or a key takes it away; focusing it by keyboard shows it too", async ({ page }) => { + await column(page); + await jump(page, "Recursion without names"); + await keys(page, "Enter"); + const link = page.locator(".lnk.l-wiki", { hasText: "fixed-point combinator" }); + await link.hover(); + const popup = page.locator(".popup:not(.focus-popup)"); + await expect(popup).toContainText("Higher-order function Y for which Y f = f (Y f)"); + await expect(popup.locator(".wattr")).toContainText("CC BY-SA 4.0"); + await page.mouse.move(5, 5); + await expect(popup).toHaveCount(0); + // It does not come back on its own, and a key press ends a pending one. + await link.hover(); + await expect(popup).toHaveCount(1); + await page.keyboard.press("Shift"); + await expect(popup).toHaveCount(0); + await page.mouse.move(5, 5); + await page.waitForTimeout(700); + await expect(page.locator(".popup")).toHaveCount(0); + // The node link's preview names its document and shows its first lines. + await page.locator(".lnk.l-node", { hasText: "Y combinator" }).hover(); + await expect(popup).toContainText("Fixed points"); + await expect(popup).toContainText("How Y works"); + await page.mouse.move(5, 5); + await expect(popup).toHaveCount(0); + // By keyboard: while the selection is a link's words, its card shows beside them, and goes with the focus. + await keys(page, "i"); + await tabTo(page, "fixed-point combinator"); + const fp = page.locator(".focus-popup"); + await expect(fp).toBeVisible(); + await expect(fp).toContainText("Fixed-point combinator"); + await tabTo(page, "self-reference"); + await expect(fp).toContainText("plato.stanford.edu"); + await keys(page, "Escape"); + await expect(fp).toHaveCount(0); +}); + +test("panes: Tab and Enter open an article in the next pane; its sections open as rows; a link in it opens a further pane; moving left keeps the trail", async ({ page }) => { + await wide(page); + await inPane(page, "Recursion without names", "fixed-point combinator"); + await keys(page, "Enter"); + const art = page.locator(".wiki-pane").last(); + await expect(art.locator(".wiki-head h2")).toHaveText("Fixed-point combinator"); + await expect(art.locator(".wiki-brand")).toContainText("Wikipedia"); + await expect(art.locator(".wattr")).toContainText("CC BY-SA 4.0"); + await expect(art.locator(".wattr")).toContainText("Adapted"); + // Its sections are rows, numbered; the lead is its text, with the sanitiser's leftovers gone. + await expect(art.locator(".wrow > .row .title")).toHaveText(["Introduction", "Y combinator", "Other fixed-point combinators", "Typed fixed-point combinators"]); + expect(await art.locator(".wiki-text sup, .wiki-text table.infobox, .wiki-text script").count()).toBe(0); + expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names", "W:Fixed-point combinator"]); + // j j l: the second section opens as the next pane; l again steps into it. + await expect(art.locator(".wrow").first()).toBeVisible(); + await keys(page, "j j l"); + await expect(panes(page)).toHaveCount(5); + const sec = panes(page).last(); + await expect(sec.locator(".wiki-head h2")).toContainText("Y combinator"); + await expect(sec.locator(".wrow .title")).toHaveText(["Verification"]); + await expect(sec.locator(".wattr")).toBeVisible(); + await keys(page, "l"); + expect(await state(page, (s) => s.aux)).toMatchObject({ kind: "wiki", host: "p4", row: { t: "head" } }); + // Tab reaches the section's link to Lambda calculus; Enter opens it as a further pane. + await keys(page, "Tab"); + await expect(sec.locator("a.wfocus")).toHaveText("lambda calculus"); + await keys(page, "Enter"); + await expect(panes(page)).toHaveCount(6); + await expect(panes(page).last().locator(".wiki-head h2")).toHaveText("Lambda calculus"); + // Back left, step by step, to the words the trail started from; nothing to the right closes. + await keys(page, "h"); + expect(await state(page, (s) => s.paneAt)).toBe(4); + // From the link it was opened from: off the link, up to the section's row, the article's head, the words. + await keys(page, "h h h h"); + expect(await selected(page)).toBe("fixed-point combinator"); + expect(await trail(page)).toEqual(["Library", "Fixed points", "Recursion without names", "W:Fixed-point combinator", "W:Fixed-point combinator#2", "W:Lambda calculus"]); + await expect(panes(page)).toHaveCount(6); + // Opening something else from an earlier pane replaces what is to its right. + await tabTo(page, "lambda calculus"); + await keys(page, "Enter"); + expect((await trail(page)).slice(3)).toEqual(["lambda calculus"]); + // W opens the focused article on wikipedia.org in a new tab (refused here, so only its address is seen). + await keys(page, "h"); + await tabTo(page, "fixed-point combinator"); + await keys(page, "Enter"); + const [req] = await Promise.all([page.context().waitForEvent("request", (r) => r.url().includes("wikipedia.org")), page.keyboard.press("W")]); + expect(req.url()).toBe("https://en.wikipedia.org/wiki/Fixed-point_combinator"); + for (const p of page.context().pages()) if (p !== page) await p.close(); + // Spines of covered article panes carry the W and the tint. + await keys(page, "j j l l Tab Enter"); + await expect(panes(page).last().locator(".wiki-head h2")).toHaveText("Lambda calculus"); + await keys(page, "Tab Enter"); + await expect(panes(page).last().locator(".wiki-head h2")).toHaveText("Alonzo Church"); + const spine = page.locator(".wiki-pane[data-covered] .spine").first(); + await expect(spine.locator(".wmark")).toHaveText("W"); + expect(await spine.evaluate((el) => getComputedStyle(el).backgroundColor)).not.toBe(await page.locator(".pane.root .spine").evaluate((el) => getComputedStyle(el).backgroundColor)); +}); + +test("a note that also links opens as one pane: its text above, the article beneath, folded to its summary until l", async ({ page }) => { + await wide(page, "/doc/origin-of-the-elements"); + await inPane(page, "The triple-alpha process", "an excited state at almost exactly the energy"); + await keys(page, "Enter"); + const pane = panes(page).last(); + await expect(pane).toHaveClass(/note-pane/); + await expect(pane.locator(".body").first()).toContainText("It is called the Hoyle state"); + const block = pane.locator(".wiki.embedded"); + await expect(block).toHaveClass(/folded/); + await expect(block.locator(".wiki-head h2")).toHaveText("Hoyle state"); + await expect(block.locator(".wattr")).toBeVisible(); + // j reaches the article under the note; l unfolds it in place; its sections are rows. + await keys(page, "j"); + expect(await state(page, (s) => s.aux?.host?.startsWith("n"))).toBe(true); + await keys(page, "l"); + await expect(block).not.toHaveClass(/folded/); + await expect(block.locator(".wrow .title")).toHaveText(["Prediction", "Structure"]); + expect(await block.locator(".wiki-text a[data-wiki]").evaluateAll((as) => as.map((a) => a.getAttribute("data-wiki")))).toEqual(["Carbon-12", "Fred Hoyle", "Triple-alpha process"]); + await keys(page, "j l"); + await expect(panes(page).last().locator(".wiki-head h2")).toContainText("Prediction"); + await keys(page, "h h"); + expect(await state(page, (s) => s.aux)).toBeNull(); +}); + +test("a link to a node in another document opens it, and Back returns; in panes it opens next and h returns", async ({ page }) => { + await column(page, "/doc/what-a-proof-is"); + await jump(page, "Proofs as programs"); + await keys(page, "Enter i"); + await tabTo(page, "Several of the leading systems"); + await keys(page, "Enter"); + const preview = page.locator(".lpreview.l-node"); + await expect(preview).toContainText("Fixed points"); + await expect(preview).toContainText("Recursion without names"); + await keys(page, "Enter"); + await expect.poll(() => focusedTitle(page)).toBe("Recursion without names"); + await expect(page).toHaveURL(/\/doc\/fixed-points\//); + await page.goBack(); + await expect.poll(() => focusedTitle(page)).toBe("Proofs as programs"); + // Panes: the node opens in the next pane, marked with its document; h comes back to the words. + await wide(page, "/doc/what-a-proof-is"); + await inPane(page, "Proofs as programs", "Several of the leading systems"); + await keys(page, "Enter"); + const last = panes(page).last(); + await expect(last).toHaveClass(/jumped/); + await expect(last.locator(".pane-from")).toHaveText("Fixed points"); + await expect(last.locator(".pane-head h2")).toHaveText("Recursion without names"); + await keys(page, "h"); + expect(await selected(page)).toBe("Several of the leading systems"); + await expect(panes(page)).toHaveCount(4); +}); + +test("Linked from and Mentioned in list what links here, reachable by j and Enter", async ({ page }) => { + await wide(page); + await jump(page, "Recursion without names"); + await keys(page, "l"); + const pane = panes(page).last(); + const back = pane.locator(".backlinks"); + await expect(back.locator("h3")).toHaveText("Linked from"); + await expect(back.locator("li .bl-title")).toHaveText(["Proofs as programs"]); + await expect(back.locator("li .bl-doc")).toHaveText(["What a proof is"]); + // A section nothing links to has no list at all. + await expect(page.locator(`.pane[data-pane="${await state(page, (s) => s.focus.node)}"] .backlinks`)).toHaveCount(1); + await keys(page, "l j j"); + await expect(back.locator("li.focused")).toHaveCount(1); + await keys(page, "Enter"); + expect(await selected(page)).toBe("Several of the leading systems"); + // Lambda calculus is linked from two documents: its pane lists both, and either leads back. + await inPane(page, "Recursion without names", "lambda calculus"); + await keys(page, "Enter j l"); + const art = page.locator(".wiki-pane").last(); + await keys(page, "L"); + const lc = page.locator(".wiki-pane").last(); + await expect(lc.locator(".backlinks h3")).toHaveText("Mentioned in"); + await expect(lc.locator(".backlinks .bl-doc")).toHaveText(["Fixed points", "What a proof is"]); + for (let i = 0; i < 8 && !(await lc.locator(".backlinks li.focused").count()); i++) await keys(page, "j"); + await keys(page, "j"); + await expect(lc.locator(".backlinks li.focused .bl-doc")).toHaveText("What a proof is"); + await keys(page, "Enter"); + expect(await selected(page)).toBe("a function turning proofs"); + void art; +}); + +test("linking by hand: the picker links to the library, to Wikipedia and to an address; it retargets; /unlink and D remove", async ({ page }) => { + await column(page, "/doc/tides"); + await jump(page, "The tides"); + const doc = await state(page, (s) => s.focus.node); + const linkCount = () => page.evaluate((d) => { + const s = (globalThis as any).__ie.snap; + return s.nodes[d].children.map((c: string) => s.nodes[c]).filter((n: any) => n.ref).map((n: any) => `${n.anchors[0].text}|${n.ref.kind}|${n.ref.title ?? n.ref.url ?? n.ref.path?.join("/")}`); + }, doc); + // A word in the document's text: i i selects it; w opens the picker filled with it. + await keys(page, "i i"); + const word = await selected(page); + await keys(page, "w"); + const picker = page.locator(".picker"); + await expect(picker.locator("input")).toHaveValue(word); + // Library: a document by title. + await page.keyboard.press("Control+a"); + await page.keyboard.type("Octopus minds"); + await expect(picker.locator(".choice.selected .t")).toHaveText("Octopus minds"); + await keys(page, "Enter"); + await expect(picker).toHaveCount(0); + expect(await linkCount()).toEqual([`${word}|node|`]); + await expect(page.locator(".lnk.l-node", { hasText: word })).toBeVisible(); + // The same picker on that link retargets it, here to Wikipedia: suggestions arrive under their own head. + await keys(page, "w"); + await expect(picker.locator(".picker-head")).toContainText("Retarget"); + await page.keyboard.press("Control+a"); + await page.keyboard.type("octo"); + await expect(picker.locator(".group", { hasText: "Wikipedia" })).toBeVisible(); + const octopus = picker.locator(".choice", { hasText: "Octopus" }).filter({ hasText: "molluscs" }); + await expect(octopus).toBeVisible(); + while (!(await octopus.evaluate((el) => el.classList.contains("selected")))) await keys(page, "ArrowDown"); + await keys(page, "Enter"); + expect(await linkCount()).toEqual([`${word}|wiki|Octopus`]); + await expect(page.locator(".lnk.l-wiki", { hasText: word })).toBeVisible(); + // An address: pasted, it is offered as an external link. + await keys(page, "l"); + const second = await selected(page); + await keys(page, "w"); + await page.keyboard.press("Control+a"); + await page.keyboard.type("https://example.org/tides"); + await expect(picker.locator(".choice.selected")).toContainText("example.org"); + await keys(page, "Enter"); + expect(await linkCount()).toEqual([`${word}|wiki|Octopus`, `${second}|url|https://example.org/tides`]); + // /link with a target in the text form, on the node itself: the document is about something. + await keys(page, "Escape Escape"); + await command(page, "/link w:Tide"); + expect(await state(page, (s) => s.snap.nodes[s.focus.node].ref)).toEqual({ kind: "wiki", title: "Tide", lang: "en" }); + await command(page, "/unlink"); + expect(await state(page, (s) => s.snap.nodes[s.focus.node].ref)).toBeUndefined(); + // /unlink on a link's words removes the link; D on a link removes it too. + await keys(page, "i"); + await tabTo(page, second); + await command(page, "/unlink"); + expect(await linkCount()).toEqual([`${word}|wiki|Octopus`]); + await tabTo(page, word); + await keys(page, "D"); + expect(await linkCount()).toEqual([]); + await keys(page, "u"); + expect(await linkCount()).toEqual([`${word}|wiki|Octopus`]); + await keys(page, "Escape"); +}); + +test("a disambiguation page lists its senses as rows; a missing article, an unreachable Wikipedia and a slow one say so plainly", async ({ page }) => { + await wide(page, "/doc/tides"); + await jump(page, "The tides"); + await keys(page, "i i"); + await command(page, "/link w:Mercury"); + await keys(page, "Enter"); + const art = page.locator(".wiki-pane").last(); + await expect(art.locator(".senses h3")).toContainText("may refer to"); + await expect(art.locator(".sense .title")).toHaveText(["Mercury (planet)", "Mercury (element)", "Mercury (mythology)", "Freddie Mercury"]); + await keys(page, "j l"); + await expect(page.locator(".wiki-pane").last().locator(".wiki-head h2")).toHaveText("Mercury (planet)"); + await expect(page.locator(".wiki-pane").last().locator(".wattr")).toBeVisible(); + for (const [title, says] of [["No such article zzz", "No article"], ["Offline example", "could not be reached"]]) { + await keys(page, "h h h"); + await command(page, `/link w:${title}`); + await keys(page, "Enter"); + await expect(page.locator(".wiki-pane").last().locator(".wiki-problem")).toContainText(says); + } + // Refused or slow, Wikipedia gets a plain message, and the reader is told once (only once) how to make it fast. + await keys(page, "h h h"); + await command(page, "/link w:Rate limited example"); + await keys(page, "Enter"); + await expect(page.locator(".wiki-pane").last().locator(".wiki-problem")).toContainText("fewer requests"); + await expect(page.locator(".status .message")).toContainText("IE_WIKI_CONTACT"); + expect(await page.evaluate(() => localStorage.getItem("ie:wiki-hint"))).toBe("true"); + await keys(page, "h h h"); + await command(page, "/link w:Slow article"); + await keys(page, "Enter"); + await expect(page.locator(".wiki-pane").last().locator(".wiki-wait")).toContainText("Loading"); + await expect(page.locator(".wiki-pane").last().locator(".wiki-head h2")).toHaveText("Slow article", { timeout: 10_000 }); + await expect(page.locator(".status .message")).not.toContainText("IE_WIKI_CONTACT"); + await keys(page, "h h h"); + await command(page, "/unlink"); +}); + +test("column: Enter on a link shows a preview, Enter again opens the article as a page; its sections open in place; h and Back return", async ({ page }) => { + await column(page); + await jump(page, "Recursion without names"); + await keys(page, "Enter i"); + await tabTo(page, "fixed-point combinator"); + await keys(page, "Enter"); + const preview = page.locator(".lpreview.l-wiki"); + await expect(preview).toContainText("Higher-order function Y"); + await expect(preview.locator(".wattr")).toBeVisible(); + await keys(page, "Enter"); + const pageEl = page.locator(".wiki-page"); + await expect(pageEl.locator(".wiki-head h2")).toHaveText("Fixed-point combinator"); + await expect(pageEl.locator(".wattr").last()).toContainText("CC BY-SA 4.0"); + await expect(page).toHaveURL(/\/w\/en\/Fixed-point_combinator$/); + await expect(pageEl.locator(".wrow").first()).toBeVisible(); + await keys(page, "j j l"); + await expect(pageEl.locator(".wrow.open > .row .title")).toHaveText("Y combinator"); + await expect(pageEl.locator(".wrow.open .wiki-text")).toContainText("defined in the"); + await keys(page, "l"); + await expect(pageEl.locator(".wrow.focused > .row .title")).toHaveText("Verification"); + // A link in the open section opens a further article on the page; h goes back one. + await keys(page, "h Tab Enter"); + await expect(pageEl.locator(".wiki-head h2")).toHaveText("Lambda calculus"); + await keys(page, "h"); + await expect(pageEl.locator(".wiki-head h2")).toHaveText("Fixed-point combinator"); + await keys(page, "h h h"); + await expect(page.locator(".wiki-page")).toHaveCount(0); + expect(await selected(page)).toBe("fixed-point combinator"); + // Back works too. + await keys(page, "Enter"); + await expect(page.locator(".wiki-page")).toHaveCount(1); + await page.goBack(); + await expect(page.locator(".wiki-page")).toHaveCount(0); + await expect.poll(() => focusedTitle(page)).toBe("Recursion without names"); + // A section's own target is a row under its text: j reaches it, Enter follows it. + await command(page, "/link w:Recursion (computer science)"); + await keys(page, "Escape"); + for (let i = 0; i < 6 && !(await page.locator(".target-row.focused").count()); i++) await keys(page, "j"); + await expect(page.locator(".target-row.focused")).toContainText("Recursion (computer science)"); + await keys(page, "Enter"); + await expect(page.locator(".wiki-page .wiki-head h2")).toHaveText("Recursion (computer science)"); + await keys(page, "h"); + await command(page, "/unlink"); +}); + +test("a hostile article cannot run script or load anything from elsewhere, in a pane or on the column's page", async ({ page }) => { + const outside: string[] = []; + page.on("request", (r) => { + const u = new URL(r.url()); + if (u.hostname !== "localhost" && u.protocol !== "data:" && u.protocol !== "blob:") outside.push(r.url()); + }); + let dialogs = 0; + page.on("dialog", (d) => (dialogs++, d.dismiss())); + for (const view of [wide, column]) { + await view(page, "/doc/tides"); + await jump(page, "The tides"); + await keys(page, "i i"); + await command(page, "/link w:Hostile article"); + await keys(page, "Enter"); + if (view === column) await keys(page, "Enter"); + const art = page.locator(view === column ? ".wiki-page" : ".wiki-pane").last(); + await expect(art.locator(".wiki-head h2")).toHaveText("Hostile article"); + // Open its section too (once the article, not just its title, is there). + await expect(art.locator(".wrow").first()).toBeVisible(); + await keys(page, "j l"); + await page.waitForTimeout(300); + const text = page.locator(".wiki-text"); + expect(await text.locator("script, iframe, object, embed, img, svg, style, link, form, video, base, meta").count()).toBe(0); + expect(await text.evaluateAll((els) => els.flatMap((e) => [...e.querySelectorAll("*")]).flatMap((e) => [...e.attributes].map((a) => a.name)).filter((n) => /^on|^style$|^src|^srcset$|^background$/.test(n)))).toEqual([]); + expect(await text.evaluateAll((els) => els.flatMap((e) => [...e.querySelectorAll("a[href]")]).map((a) => a.getAttribute("href")!).filter((h) => !/^https:\/\//.test(h)))).toEqual([]); + for (const a of await text.locator("a[target]").all()) expect(await a.getAttribute("rel")).toContain("noopener"); + // The heading with markup in it is shown as text. + if (view === wide) await expect(page.locator(".wiki-pane").last().locator(".wiki-head")).toContainText(" (window as any).__pwned)).toBeUndefined(); + await keys(page, "h h h h"); + if (view === column) await keys(page, "Escape"); + await command(page, "/unlink"); + } + expect(await page.evaluate(() => (window as any).__pwned)).toBeUndefined(); + expect(dialogs).toBe(0); + expect(outside).toEqual([]); +}); + +test("keypress → paint stays within one frame budget through links and articles, in panes and in the column", async ({ page }) => { + const paced = async (seq: string) => { + for (const k of seq.split(" ")) { + await page.keyboard.press(k); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => r(null)))); + } + }; + const report: Record = {}; + for (const view of ["panes", "column"] as const) { + if (view === "panes") await wide(page); + else await column(page); + const seq = view === "panes" ? "l i Tab Tab Enter j j l l Tab h h h h Tab Enter j h h Escape Escape" : "Enter i Tab Tab Enter Enter j j l l h h h h Escape Escape"; + const measure = async (passes: number) => { + await page.evaluate(() => ((globalThis as any).__ie.samples.length = 0)); + for (let pass = 0; pass < passes; pass++) { + await paced(seq); + await page.waitForTimeout(50); + } + const samples: Sample[] = await state(page, (s) => s.samples); + const ms = samples.filter((x) => x.what !== "first-token").map((x) => x.ms).sort((a, b) => a - b); + const pct = (p: number) => ms[Math.min(ms.length - 1, Math.floor(ms.length * p))]; + return { keystrokes: ms.length, median: pct(0.5), p95: pct(0.95), max: ms[ms.length - 1], over20: samples.filter((x) => x.what !== "first-token" && x.ms > 20).map((x) => `${x.what}:${Math.round(x.ms)}`) }; + }; + await jump(page, "Recursion without names"); + // The first time through, each article is fetched, cleaned and laid out for the first time; + // after that, what is timed is moving through what is already there. + const cold = await measure(1); + const warm = await measure(3); + report[view] = { cold, warm }; + // One frame for nearly every key; a rare second frame (a preview appearing, the column's + // article page giving way to the document) is allowed, as the other latency tests allow it. + expect(warm.keystrokes).toBeGreaterThan(30); + expect(warm.median).toBeLessThan(17.5); + expect(warm.p95).toBeLessThan(34); + expect(cold.max).toBeLessThan(100); + } + console.log("links keypress → paint (ms):", JSON.stringify(report)); + writeReport("links", report); +}); diff --git a/e2e/menu.spec.ts b/e2e/menu.spec.ts new file mode 100644 index 0000000..4bd0222 --- /dev/null +++ b/e2e/menu.spec.ts @@ -0,0 +1,350 @@ +/** + * Documents in the library, from the keyboard: the menu (filter and open, create, rename, + * duplicate, delete, export and import), addresses that survive a reload and Back, a jump that + * crosses documents, and moving between documents without closing anything. These tests make + * their own documents and leave the first one alone: the other specs share it. + */ +import { expect, test, type Page } from "@playwright/test"; +import { command, idle, jump, keys, settle, state, synced } from "./helpers"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { parseDoc } from "../src/core/format"; + +const FIXTURE = fileURLToPath(new URL("../tests/fixtures/menu-fixture.md", import.meta.url)); + +/** The titles in the document on screen. */ +const titles = (page: Page) => + state(page, (s) => { + const d = s.currentDoc; + const out: string[] = []; + const visit = (id: string) => (out.push(s.snap.nodes[id].title), s.snap.nodes[id].children.forEach(visit)); + if (d) visit(d); + return out; + }); +/** m, type to filter, Enter. */ +const openByMenu = async (page: Page, filter: string) => { + await page.keyboard.press("m"); + await expect(page.locator(".panel.docs .filter")).toBeFocused(); + await page.keyboard.type(filter); + await page.keyboard.press("Enter"); +}; +/** m, then Esc to the list, where single keys act. */ +const menuList = async (page: Page) => { + await page.keyboard.press("m"); + await expect(page.locator(".panel.docs .filter")).toBeFocused(); + await page.keyboard.press("Escape"); + await expect(page.locator(".panel.docs .filter")).not.toBeFocused(); + await expect.poll(() => state(page, (s) => `${s.mode}/${s.menu.focus}`)).toBe("docs/list"); +}; +async function open(page: Page, path = "/doc/infinite-expand") { + await page.goto(path); + await page.waitForSelector("article"); +} + +test.describe.configure({ mode: "serial" }); + +// Playwright turns on file-chooser interception only when something listens for it, and does so +// asynchronously: a waitForEvent("filechooser") made just before the key that opens the picker can +// lose that race, and then the picker opens unintercepted and no event ever comes (seen under load: +// the app had appended and clicked its file input). Listening from the start keeps it on throughout. +test.beforeEach(async ({ page }) => { + page.on("filechooser", () => {}); +}); + +test.afterEach(({ page }) => settle(page)); + +test("the library is the first page: its documents are its sections, and opening one needs no closing step", async ({ page }) => { + await open(page, "/"); + await expect(page.locator(".top h1")).toHaveText("Library"); + const docs = await state(page, (s) => s.snap.nodes[s.snap.root].children.length); + await expect(page.locator("article > .outline > .node")).toHaveCount(docs); + await expect(page.locator("article > .outline > .node.open")).toHaveCount(0); + await keys(page, "j Enter"); // the first document's row: it opens in place of the list + await expect(page.locator(".top h1")).toHaveText("Infinispand"); + await expect(page.locator(".crumbs")).toHaveText(/Library/); + await expect(page).toHaveURL(/\/doc\/infinite-expand$/); + await expect(page.locator(".docbar .doc-title .name")).toHaveText("Infinispand"); + await keys(page, "h"); // stepping out of the document returns to the library, on its row + await expect(page.locator(".top h1")).toHaveText("Library"); + expect(await state(page, (s) => s.snap.nodes[s.focus.node].title)).toBe("Infinispand"); + await keys(page, "j l"); // the next one + await expect(page.locator(".top h1")).toHaveText("A mind made of text"); + // The library's own text is never stale and the library is not rewritten by anything. + expect(await state(page, (s) => s.snap.nodes[s.snap.root].seenUp)).toBe(""); +}); + +test("m opens the menu, in library order, and the title in the top bar opens it too", async ({ page }) => { + await open(page); + await keys(page, "m"); + const panel = page.locator(".panel.docs"); + await expect(panel).toBeVisible(); + await expect(panel.locator(".doc.current")).toContainText("Infinispand"); + await expect(panel.locator(".doc.current")).toContainText(/open · (saved|saving…)/); + const listed = await panel.locator(".doc .title").allTextContents(); + expect(listed).toEqual(await state(page, (s) => s.snap.nodes[s.snap.root].children.map((c: string) => s.snap.nodes[c].title))); + await keys(page, "Escape Escape"); + await expect(panel).toHaveCount(0); + await page.locator(".docbar .doc-title").click(); + await expect(panel).toBeVisible(); + await expect(page.locator(".docbar .save-state")).toHaveText("saved"); +}); + +test("import a .md file, then export it and get the same document back", async ({ page }) => { + await open(page); + await menuList(page); + const chooser = page.waitForEvent("filechooser"); + await keys(page, "i"); + await (await chooser).setFiles(FIXTURE); + await expect(page.locator(".top h1")).toHaveText("Menu fixture"); + await expect(page).toHaveURL(/\/doc\/menu-fixture$/); + const shape = () => state(page, (s) => s.doc.shape(undefined, s.currentDoc)); + const imported = await shape(); + + await menuList(page); + const download = page.waitForEvent("download"); + await keys(page, "x"); + const file = await (await download).path(); + const text = readFileSync(file, "utf8"); + expect(await (await download).suggestedFilename()).toBe("menu-fixture.md"); + expect(parseDoc(text)).toEqual(parseDoc(readFileSync(FIXTURE, "utf8"))); + + // Importing the exported file gives a second document with the same shape. + await keys(page, "Escape"); + const again = page.waitForEvent("filechooser"); + await command(page, "/import"); + await (await again).setFiles({ name: "menu-fixture.md", mimeType: "text/markdown", buffer: Buffer.from(text) }); + await expect(page).toHaveURL(/\/doc\/menu-fixture-2$/); + expect(await shape()).toBe(imported); + expect(await state(page, (s) => [s.currentDoc, ...s.snap.nodes[s.currentDoc].children].filter((id: string) => s.snap.nodes[id].by !== "llm").length)).toBe(0); + // Both are on the server, as sections of the library. + await synced(page); + expect((await (await page.request.get("/api/docs")).json()).map((d: any) => d.slug)).toEqual(expect.arrayContaining(["menu-fixture", "menu-fixture-2"])); +}); + +test("a file with a quote that is not in its text is refused, naming the section and the quote", async ({ page }) => { + await open(page); + const bad = readFileSync(FIXTURE, "utf8").replace('"a phrase worth a note"', '"words that are not there"'); + await menuList(page); + const chooser = page.waitForEvent("filechooser"); + await keys(page, "i"); + await (await chooser).setFiles({ name: "broken.md", mimeType: "text/markdown", buffer: Buffer.from(bad) }); + await expect(page.locator(".panel.docs .problems")).toContainText('broken.md:5: in “Menu fixture”: quote not found: "words that are not there"'); + await expect(page.locator(".top h1")).toHaveText("Infinispand"); +}); + +test("filter and open; the address names the document and the node, and survives a reload, Back and Forward", async ({ page }) => { + await open(page, "/"); + await keys(page, "m"); + await page.keyboard.type("menu fix"); + await expect(page.locator(".panel.docs .doc")).toHaveCount(2); + await keys(page, "Escape j k Enter"); + await expect(page.locator(".top h1")).toHaveText("Menu fixture"); + await expect(page.locator(".panel.docs")).toHaveCount(0); + await expect(page).toHaveTitle("Menu fixture"); + await expect(page).toHaveURL(/\/doc\/menu-fixture$/); + // Into a section: the address follows the focus to the node. + await keys(page, "j"); + const section = await state(page, (s) => s.focus.node); + await expect(page).toHaveURL(new RegExp(`/doc/menu-fixture/${encodeURIComponent(section)}$`)); + await page.reload(); + await page.waitForSelector("article"); + await expect(page.locator(".top h1")).toHaveText("Menu fixture"); + expect(await state(page, (s) => s.focus.node)).toBe(section); + // A link to a document opens it; Back returns to the node; Back again to the library. + await open(page, "/doc/infinite-expand"); + await expect(page.locator(".top h1")).toHaveText("Infinispand"); + await page.goBack(); + await expect(page.locator(".top h1")).toHaveText("Menu fixture"); + await expect.poll(() => state(page, (s) => s.focus.node)).toBe(section); + await page.goForward(); + await expect(page.locator(".top h1")).toHaveText("Infinispand"); + // An address that names nothing says so and shows the library. + await open(page, "/doc/no-such-document"); + await expect(page.locator(".top h1")).toHaveText("Library"); + await expect(page.locator(".status .message")).toContainText("no-such-document"); +}); + +test("the jump box searches every document, says which one each match is in, and goes there", async ({ page }) => { + await open(page); + await page.keyboard.press("/"); + await page.keyboard.type("amphidromes"); + const hit = page.locator(".jump li").first(); + await expect(hit.locator(".t")).toHaveText("Amphidromes"); + await expect(hit.locator(".in")).toHaveText("The tides"); + await page.keyboard.press("Enter"); + await expect(page.locator(".top h1")).toHaveText("The tides"); + expect(await state(page, (s) => s.snap.nodes[s.focus.node].title)).toBe("Amphidromes"); + await expect(page).toHaveURL(/\/doc\/tides\/\d+%40\d+$/); + // Back to where the jump started. + await page.goBack(); + await expect(page.locator(".top h1")).toHaveText("Infinispand"); + // A document's own title opens it. + await jump(page, "Fixed points"); + await expect(page.locator(".top h1")).toHaveText("Fixed points"); +}); + +test("the library opens from this browser without the network, and catches up when it returns", async ({ page }) => { + await open(page, "/doc/menu-fixture"); + await synced(page); + await page.route("**/api/**", (route) => route.abort()); + await page.reload(); + await page.waitForSelector("article"); + await expect(page.locator(".top h1")).toHaveText("Menu fixture"); + await command(page, "/open tides"); + await expect(page.locator(".top h1")).toHaveText("The tides"); + await keys(page, "j r"); + await page.keyboard.press("Control+a"); + await page.keyboard.type("Renamed offline"); + await page.keyboard.press("Enter"); + await expect(page.locator(".docbar .save-state")).toHaveText(/offline|saving/); + await page.waitForTimeout(300); // the replica reaches IndexedDB a moment after the edit + await page.unroute("**/api/**"); + await page.reload(); + await page.waitForSelector("article"); + await expect(page.locator(".docbar .save-state")).toHaveText("saved", { timeout: 15_000 }); + expect(JSON.stringify(await (await page.request.get("/api/docs/tides/tree")).json())).toContain("Renamed offline"); +}); + +test("create, rename and duplicate from the menu", async ({ page }) => { + await open(page); + await menuList(page); + await keys(page, "n"); + await page.keyboard.type("Scratch pad"); + await page.keyboard.press("Enter"); + await expect(page.locator(".top h1")).toHaveText("Scratch pad"); + await expect(page).toHaveURL(/\/doc\/scratch-pad$/); + + await menuList(page); + await keys(page, "r"); + await page.keyboard.press("Control+a"); + await page.keyboard.type("Scratch pad, renamed"); + await page.keyboard.press("Enter"); + await expect(page.locator(".top h1")).toHaveText("Scratch pad, renamed"); + await expect(page.locator(".panel.docs .doc.current .title")).toHaveText("Scratch pad, renamed"); + await expect(page).toHaveURL(/\/doc\/scratch-pad$/); // the slug, and so links, stay + await synced(page); + const listed = await (await page.request.get("/api/docs/scratch-pad")).json(); + expect(listed.title).toBe("Scratch pad, renamed"); + + await keys(page, "s"); + await page.keyboard.press("Control+a"); + await page.keyboard.type("Scratch copy"); + await page.keyboard.press("Enter"); + await expect(page.locator(".top h1")).toHaveText("Scratch copy"); + await expect(page).toHaveURL(/\/doc\/scratch-copy$/); + // The copy sits after the original in the library, and is one commit in its history. + expect(await state(page, (s) => s.commits()[0].message)).toBe("Duplicate “Scratch pad, renamed” as “Scratch copy”"); + const order = await state(page, (s) => s.snap.nodes[s.snap.root].children.map((c: string) => s.snap.nodes[c].slug)); + expect(order.indexOf("scratch-copy")).toBe(order.indexOf("scratch-pad") + 1); +}); + +test("delete asks first, and is an ordinary delete that u undoes", async ({ page }) => { + await open(page, "/doc/scratch-copy"); + await keys(page, "m"); + await page.keyboard.type("scratch copy"); + await keys(page, "Escape D"); + await expect(page.locator(".panel.docs .confirm")).toContainText("u brings it back"); + await keys(page, "n"); + await expect(page.locator(".panel.docs .confirm")).toHaveCount(0); + await keys(page, "D y"); + await expect(page.locator(".status .message")).toContainText("Deleted “Scratch copy”"); + await expect(page.locator(".top h1")).toHaveText("Library"); + await synced(page); + expect((await page.request.get("/api/docs/scratch-copy")).status()).toBe(404); + await keys(page, "Escape u"); + await expect.poll(() => state(page, (s) => s.snap.nodes[s.snap.root].children.map((c: string) => s.snap.nodes[c].slug))).toContain("scratch-copy"); + await synced(page); + expect((await page.request.get("/api/docs/scratch-copy")).status()).toBe(200); +}); + +test("a node moves from one document to another, and undo works wherever the last edit was", async ({ page }) => { + await open(page, "/doc/scratch-pad"); + await keys(page, "a"); + await page.keyboard.type("Only in the scratch pad"); + await page.keyboard.press("Enter"); + // Move straight on: the edit is the library's, and goes to the server from wherever the reader is. + await openByMenu(page, "menu fixture"); + await expect(page.locator(".top h1")).toHaveText("Menu fixture"); + expect(await titles(page)).not.toContain("Only in the scratch pad"); + await expect + .poll(async () => JSON.stringify(await (await page.request.get("/api/docs/scratch-pad/tree")).json())) + .toContain("Only in the scratch pad"); + expect(JSON.stringify(await (await page.request.get("/api/docs/menu-fixture/tree")).json())).not.toContain("Only in the scratch pad"); + // Undo is the library's too: u here takes back the edit made in the scratch pad. + await keys(page, "u"); + await openByMenu(page, "scratch pad"); + expect(await titles(page)).not.toContain("Only in the scratch pad"); + await keys(page, "U"); + expect(await titles(page)).toContain("Only in the scratch pad"); + // An outside agent moves the section into another document with one ordinary move. + await synced(page); + const tree = await (await page.request.get("/api/tree")).json(); + const node = Object.values(tree.nodes).find((n) => n.title === "Only in the scratch pad"); + const target = Object.values(tree.nodes).find((n) => n.slug === "menu-fixture"); + const res = await page.request.post("/api/ops", { data: { author: "mover", message: "Move it across", ops: [{ op: "move", id: node.id, parent: target.id }] } }); + expect(res.ok()).toBe(true); + await expect.poll(() => titles(page)).not.toContain("Only in the scratch pad"); + await openByMenu(page, "menu fixture"); + expect(await titles(page)).toContain("Only in the scratch pad"); + // Its address still finds it, under its new document. + await page.reload(); + await page.waitForSelector("article"); + await jump(page, "Only in the scratch pad"); + await expect(page).toHaveURL(new RegExp(`/doc/menu-fixture/${encodeURIComponent(node.id)}$`)); +}); + +test("a note being written in one document lands there after the reader has moved to another", async ({ page }) => { + await open(page, "/doc/menu-fixture"); + await keys(page, "i j e"); // select the document's second sentence and expand it + await expect.poll(() => state(page, (s) => s.pending.size)).toBe(1); + const where = await state(page, (s) => s.focus.node); + await openByMenu(page, "scratch pad"); + await expect(page.locator(".top h1")).toHaveText("Scratch pad, renamed"); + await idle(page); + await expect(page.locator(".pending, .writing")).toHaveCount(0); + const notes = await state(page, (s) => s.snap.nodes[s.snap.nodes[s.snap.root].children.find((c: string) => s.snap.nodes[c].slug === "menu-fixture")].children.filter((c: string) => /mock/i.test(s.snap.nodes[c].body)).length); + expect(notes).toBe(1); + expect(await state(page, (s) => s.snap.nodes[s.focus.node].title)).not.toBe(where); +}); + +test("the : commands do the same", async ({ page }) => { + await open(page); + await command(page, "/new Made by command"); + await expect(page.locator(".top h1")).toHaveText("Made by command"); + await command(page, "/rename Renamed by command"); + await expect(page.locator(".top h1")).toHaveText("Renamed by command"); + await command(page, "/open menu-fixture"); + await expect(page.locator(".top h1")).toHaveText("Menu fixture"); + const download = page.waitForEvent("download"); + await command(page, "/export"); + expect(await (await download).suggestedFilename()).toBe("menu-fixture.md"); + await command(page, "/open made-by-command"); + await expect(page.locator(".top h1")).toHaveText("Renamed by command"); +}); + +test("the menu works in panes and at phone width", async ({ page }) => { + await page.setViewportSize({ width: 1920, height: 1080 }); + await open(page, "/doc/infinite-expand"); + await expect(page.locator(".strip > .pane")).toHaveCount(2); // the library, and the document + await openByMenu(page, "menu fixture"); + await expect(page.locator(".strip .pane.root h1")).toHaveText("Library"); + await expect(page.locator(".strip .pane.doc h1")).toHaveText("Menu fixture"); + await keys(page, "l l"); + await expect(page.locator(".strip > .pane")).toHaveCount(3); + await openByMenu(page, "infinispand"); + await expect(page.locator(".strip > .pane")).toHaveCount(2); // the pane path is the other document's own + await expect(page.locator(".strip .pane.doc h1")).toHaveText("Infinispand"); + + await page.setViewportSize({ width: 390, height: 800 }); + await keys(page, "m"); + await expect(page.locator(".panel.docs .filter")).toBeFocused(); + const box = (await page.locator(".panel.docs").boundingBox())!; + expect(box.x).toBeGreaterThanOrEqual(0); + expect(box.x + box.width).toBeLessThanOrEqual(390); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); + await page.keyboard.type("scratch pad"); + await page.keyboard.press("Enter"); + await expect(page.locator(".top h1")).toHaveText("Scratch pad, renamed"); + const bar = (await page.locator(".docbar").boundingBox())!; + expect(bar.x + bar.width).toBeLessThanOrEqual(390); +}); diff --git a/e2e/more.spec.ts b/e2e/more.spec.ts new file mode 100644 index 0000000..a3c9920 --- /dev/null +++ b/e2e/more.spec.ts @@ -0,0 +1,177 @@ +/** The mouse, narrow screens, hover previews, hoisting, speculation, orphans, and an outside agent over HTTP. */ +import { expect, test, type Page } from "@playwright/test"; +import { idle, jump, keys, settle, state } from "./helpers"; + +async function open(page: Page) { + await page.goto("/doc/infinite-expand"); + await page.waitForSelector("article"); +} + +test.afterEach(({ page }) => settle(page)); + +test("everything is reachable with the mouse: titles, marked spans, and a dragged selection", async ({ page }) => { + await open(page); + await page.locator(".row", { hasText: "Borrowed from Gwern" }).click(); + await expect(page.locator(".node.open > .row", { hasText: "Borrowed from Gwern" })).toBeVisible(); + await page.locator(".row", { hasText: "Semantic zoom" }).click(); + // A marked span opens its pre-generated note. + const anchor = page.locator(".node.open .anchor", { hasText: "StretchText" }); + await anchor.click(); + await expect(page.locator(".anchor.on")).toHaveCount(1); + await anchor.click(); + await expect(page.locator(".anchor.on")).toHaveCount(0); + // Dragging across text makes that range the focus; e then expands it like any other. + await page.locator(".row", { hasText: "Typography" }).click(); + const para = page.locator(".node.open", { hasText: "Typography" }).last().locator(".para").first(); + const box = (await para.boundingBox())!; + await page.mouse.move(box.x + 6, box.y + 12); + await page.mouse.down(); + await page.mouse.move(box.x + 150, box.y + 12, { steps: 6 }); + await page.mouse.up(); + const focus = await state(page, (s) => ({ grain: s.focus.grain, text: s.snap.nodes[s.focus.node].body.slice(s.focus.range[0], s.focus.range[1]) })); + expect(focus.grain).toBe("word"); + expect(focus.text.length).toBeGreaterThan(3); + await page.keyboard.press("e"); + await idle(page); + const made = await state(page, (s) => Object.values(s.snap.nodes).filter((n: any) => n.kind === "note" && /^[Mm]ock/.test(n.body)).map((n: any) => n.anchors[0].text)); + expect(made).toContain(focus.text); +}); + +test("hovering a marked span previews its note without opening it", async ({ page }) => { + await open(page); + await jump(page, "Semantic zoom"); + await page.keyboard.press("l"); + await page.locator(".node.open .anchor", { hasText: "StretchText" }).hover(); + await expect(page.locator(".popup")).toBeVisible(); + await expect(page.locator(".anchor.on")).toHaveCount(0); + await page.mouse.move(5, 5); + await expect(page.locator(".popup")).toHaveCount(0); +}); + +test("on a narrow screen a margin note falls into the column", async ({ page }) => { + await page.setViewportSize({ width: 820, height: 900 }); + await open(page); + await jump(page, "Expansion by depth"); + await keys(page, "l Tab Enter"); + const [note, col] = await Promise.all([page.locator(".sidenote").first().boundingBox(), page.locator("article").boundingBox()]); + expect(note!.x).toBeGreaterThanOrEqual(col!.x); + expect(note!.x + note!.width).toBeLessThanOrEqual(col!.x + col!.width + 1); + // And nothing scrolls sideways. + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); +}); + +test("hoisting makes one node the whole page; Esc steps out to its document, and from its top to the library", async ({ page }) => { + await open(page); + await jump(page, "Semantic conflicts"); + await page.keyboard.press("z"); + await expect(page.locator("h1")).toHaveText("Semantic conflicts"); + await expect(page.locator(".crumbs")).toContainText("Versioning and merge"); + await expect(page.locator("article > .outline > .node")).toHaveCount(3); + await page.keyboard.press("Escape"); + await expect(page.locator("h1")).toHaveText("Infinispand"); + // The focus stays on the section it stepped out of, now a row; from the document's own top, out again. + expect(await state(page, (s) => s.snap.nodes[s.focus.node].title)).toBe("Semantic conflicts"); + await page.keyboard.press("O"); // collapse everything: the focus goes to the top + await page.keyboard.press("Escape"); + await expect(page.locator("h1")).toHaveText("Library"); + await expect(page).toHaveURL(/\/$/); +}); + +test("with speculation on, the focused sentence is already being written when it is asked for", async ({ page }) => { + await open(page); + await page.keyboard.press(":"); + await page.keyboard.type("/speculate on"); + await page.keyboard.press("Enter"); + await jump(page, "Typography"); + await keys(page, "l i"); + await page.waitForTimeout(1200); // focus rests; the expansion is written in the background + expect(await state(page, (s) => s.pending.size)).toBe(0); // nothing is shown until asked + await page.keyboard.press("e"); + // The whole text is there on the first frame: no stream to wait for. + await expect(page.locator(".sidenote, .inset").filter({ hasText: "Mock" }).first()).toBeVisible({ timeout: 500 }); + await idle(page); + await page.keyboard.press(":"); + await page.keyboard.type("/speculate off"); + await page.keyboard.press("Enter"); +}); + +test("deleting the words a note is about orphans the note, visibly", async ({ page }) => { + await open(page); + await page.keyboard.press(":"); + await page.keyboard.type("/auto off"); + await page.keyboard.press("Enter"); + await jump(page, "Focus and grain"); + await keys(page, "l Tab Enter"); // open its pre-generated note + await expect(page.locator(".sidenote", { hasText: "A cursor that only addressed nodes" })).toHaveCount(1); + await keys(page, "Escape Escape c"); + await page.keyboard.press("Control+a"); + await page.keyboard.type("Rewritten so that the anchored words are gone."); + await page.keyboard.press("Escape"); + const orphan = page.locator(".inset.orphan", { hasText: "orphaned: its text “a node and a grain” was deleted" }); + await expect(orphan).toHaveCount(1); + await keys(page, "u"); // and undo brings the words, and the anchor, back + await expect(orphan).toHaveCount(0); + await expect(page.locator(".sidenote", { hasText: "A cursor that only addressed nodes" })).toHaveCount(1); + await page.keyboard.press(":"); + await page.keyboard.type("/auto on"); + await page.keyboard.press("Enter"); +}); + +test("an outside agent edits over HTTP with the same ops, and the open page follows", async ({ page, request }) => { + await open(page); + const tree = await (await request.get("/api/tree/main")).json(); + // The tree is the whole library; its documents are the root's sections. + expect(Object.values(tree.nodes).filter((n) => n.parent === tree.root).map((n) => n.slug)).toContain("infinite-expand"); + const target = Object.values(tree.nodes).find((n) => n.title === "The first document"); + expect(target).toBeTruthy(); + const res = await request.post("/api/ops/main", { + data: { author: "outside-agent", message: "Add a remark", ops: [{ op: "create", parent: target.id, title: "Written over HTTP", body: "By an agent that is not the browser." }] }, + }); + expect(res.ok()).toBe(true); + await expect.poll(() => state(page, (s) => Object.values(s.snap.nodes).some((n: any) => n.title === "Written over HTTP"))).toBe(true); + const commit = await state(page, (s) => s.commits().find((c: any) => c.message === "Add a remark")); + expect(commit).toMatchObject({ by: "outside-agent", tag: "api" }); + // A refused op is reported, not applied. + const bad = await request.post("/api/ops/main", { data: { ops: [{ op: "delete", id: tree.root }] } }); + expect(bad.status()).toBe(422); + expect((await bad.json()).error).toMatch(/root/); +}); + +test("the footer counts this session's model calls, and /api/usage says what it knows", async ({ page, request }) => { + await open(page); + const session = page.locator(".status .usage-session"); + await expect(session).toHaveText(/^[\d,]+ calls? · \S+ in · \S+ out$/); + const before = Number(await session.getAttribute("data-calls")); + // Ask why about a sentence no other test has touched: always a new model call. + await jump(page, "Semantic conflicts"); + await keys(page, "l i y"); + await idle(page); + await expect.poll(async () => Number(await session.getAttribute("data-calls"))).toBeGreaterThan(before); + // The mock has no plan window, so there is no plan figure. + await expect(page.locator(".status .usage-plan")).toHaveCount(0); + // The footer still fits on one line, inside the window. + const bar = (await page.locator(".status").boundingBox())!; + const right = (await page.locator(".status .right").boundingBox())!; + expect(right.x + right.width).toBeLessThanOrEqual(bar.x + bar.width); + expect(right.height).toBeLessThan(bar.height); + + const u = await (await request.get("/api/usage")).json(); + expect(u).toMatchObject({ + provider: "mock", + model: "mock", + plan: null, + session: { + calls: expect.any(Number), + failed: expect.any(Number), + unreported: expect.any(Number), + input: { fresh: expect.any(Number), cacheRead: 0, cacheWrite: 0, total: expect.any(Number) }, + output: expect.any(Number), + lastCall: { at: expect.any(String), input: expect.any(Number), output: expect.any(Number) }, + costUsd: null, + }, + }); + expect(u.session.calls).toBeGreaterThan(before); + expect(u.session.input.total).toBe(u.session.input.fresh); + expect(u.session.input.total).toBeGreaterThan(0); + expect(Date.parse(u.session.startedAt)).toBeLessThanOrEqual(Date.parse(u.now)); +}); diff --git a/e2e/panes.spec.ts b/e2e/panes.spec.ts new file mode 100644 index 0000000..505e000 --- /dev/null +++ b/e2e/panes.spec.ts @@ -0,0 +1,314 @@ +/** + * The panes view, on a wide window: the path to the focus as a strip of panes side by side. + * Same production build, mock model and shared library as the other specs. The first pane is the + * library; most tests here are about the panes themselves, so they hoist to the first document + * (z) and start from it, as the first pane. + */ +import { expect, test, type Page } from "@playwright/test"; +import { command, focusedTitle, idle, jump, keys, settle, state, writeReport, type Sample } from "./helpers"; + +/** Each pane's title and box, left to right. */ +const panes = (page: Page) => + page.evaluate(() => + [...document.querySelectorAll(".strip > .pane")].map((p) => { + const r = p.getBoundingClientRect(); + return { title: p.querySelector(".pane-head h2, .top h1")?.textContent ?? "", left: r.left, right: r.right, width: r.width, covered: p.hasAttribute("data-covered") }; + }), + ); +const paneTitles = async (page: Page) => (await panes(page)).map((p) => p.title); +const nodeId = (page: Page, title: string) => page.evaluate((t) => (Object.values((globalThis as any).__ie.snap.nodes) as any[]).find((n) => n.title === t).id as string, title); + +async function open(page: Page) { + await page.goto("/doc/infinite-expand"); + await page.waitForSelector(".strip > .pane"); + await page.evaluate(() => document.fonts.ready); + // The library pane and the document's; hoisting makes the document the first. + await expect(page.locator(".strip > .pane")).toHaveCount(2); + await page.keyboard.press("z"); + await expect(page.locator(".strip > .pane")).toHaveCount(1); +} + +test.use({ viewport: { width: 1920, height: 1080 } }); +test.describe.configure({ mode: "serial" }); + +test.afterEach(({ page }) => settle(page)); + +test("the library is the first pane, and a document opens in the next; reload and Back keep the place", async ({ page }) => { + await page.goto("/"); + await page.waitForSelector(".strip > .pane"); + expect(await paneTitles(page)).toEqual(["Library"]); + await expect(page.locator(".pane.root .rows > .node")).toHaveCount(await state(page, (s) => s.snap.nodes[s.snap.root].children.length)); + await keys(page, "j l"); // the first document's row, then open it + expect(await paneTitles(page)).toEqual(["Library", "Infinispand"]); + await expect(page.locator(".pane.doc .abstract.seed.folded")).toBeVisible(); + await keys(page, "j l"); // the next document: its pane replaces the first one's + expect(await paneTitles(page)).toEqual(["Library", "A mind made of text"]); + await keys(page, "l l"); // into its first section, and open that + const third = await paneTitles(page); + expect(third).toHaveLength(3); + await expect(page).toHaveURL(/\/doc\/a-mind-made-of-text\/\d+%40\d+$/); + await page.reload(); + await page.waitForSelector(".strip > .pane"); + expect(await paneTitles(page)).toEqual(third); + // Opening a document from the menu is a new page in the address bar's history; Back returns. + await page.keyboard.press("m"); + await page.keyboard.type("tides"); + await page.keyboard.press("Enter"); + expect(await paneTitles(page)).toEqual(["Library", "The tides"]); + await expect(page).toHaveURL(/\/doc\/tides$/); + await page.goBack(); + await expect.poll(() => paneTitles(page)).toEqual(third); + await page.goForward(); + await expect.poll(() => paneTitles(page)).toEqual(["Library", "The tides"]); +}); + +test("auto shows panes at 1920 px and one column at 1440; v and /view switch", async ({ page }) => { + await open(page); + await expect(page.locator(".app.view-panes .strip > .pane")).toHaveCount(1); + await expect(page.locator(".strip .pane.root h1")).toHaveText("Infinispand"); + await page.setViewportSize({ width: 1440, height: 900 }); + await expect(page.locator(".strip")).toHaveCount(0); + await expect(page.locator("article > .outline > .node").first()).toBeVisible(); + await page.setViewportSize({ width: 1920, height: 1080 }); + await expect(page.locator(".strip > .pane")).toHaveCount(1); + await keys(page, "v"); + await expect(page.locator(".strip")).toHaveCount(0); + await expect(page.locator(".status .message")).toContainText("one column"); + await keys(page, "v"); + await expect(page.locator(".strip > .pane")).toHaveCount(1); + await expect(page.locator(".status .message")).toContainText("panes"); + await command(page, "/view column"); + await expect(page.locator(".strip")).toHaveCount(0); + expect(await state(page, (s) => s.settings.view)).toBe("column"); + await command(page, "/view auto"); + await expect(page.locator(".strip > .pane")).toHaveCount(1); + // The setting is remembered. + await page.reload(); + await page.waitForSelector(".strip > .pane"); + expect(await page.evaluate(() => JSON.parse(localStorage.getItem("ie:settings")!).view)).toBe("auto"); +}); + +test("opening three levels deep gives four panes left to right; h moves back left keeping them; q closes", async ({ page }) => { + await open(page); + // l: first child · l: open it · l: its first child · j j · l open · l first child · l open + await keys(page, "l l l j j l l l"); + await expect(page.locator(".strip > .pane")).toHaveCount(4); + const ps = await panes(page); + expect(ps.map((p) => p.title)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand", "Deepening a leaf"]); + for (let i = 1; i < ps.length; i++) expect(ps[i].left).toBeGreaterThan(ps[i - 1].left); + // In each parent's list, the child whose pane is showing is marked. + await expect(page.locator(".pane .node.showing > .row")).toHaveText(["Expansion by depth", "Generation on demand", "Deepening a leaf"].map((t) => new RegExp(t))); + // Moving back left closes nothing: the trail stays as it was. + await keys(page, "h"); + await expect(page.locator(".strip > .pane")).toHaveCount(4); + expect(await focusedTitle(page)).toBe("Generation on demand"); + await keys(page, "h"); + expect(await focusedTitle(page)).toBe("Expansion by depth"); + expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand", "Deepening a leaf"]); + // And forward again along the same trail. + await keys(page, "l"); + expect(await focusedTitle(page)).toBe("Levels of a node"); + await expect(page.locator(".strip > .pane")).toHaveCount(4); + // q closes the panes right of the one being read; again, that one. + await keys(page, "h q"); + expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth"]); + await keys(page, "q"); + expect(await paneTitles(page)).toEqual(["Infinispand"]); + expect(await focusedTitle(page)).toBe("Expansion by depth"); +}); + +test("j and k move among siblings, and the strip follows", async ({ page }) => { + await open(page); + await keys(page, "j"); // from the top: its first child + expect(await focusedTitle(page)).toBe("Expansion by depth"); + await jump(page, "Levels of a node"); + await expect(page.locator(".strip > .pane")).toHaveCount(2); + await keys(page, "j"); + expect(await focusedTitle(page)).toBe("Pre-generated depth"); + await keys(page, "l"); // open it: its pane appears + expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth"]); + await keys(page, "j"); // a closed sibling: the open one's pane stays until something else is opened + expect(await focusedTitle(page)).toBe("Generation on demand"); + expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth"]); + await keys(page, "k"); + expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth"]); + await keys(page, "k k k k"); // stops at the first sibling, never wanders into other panes + expect(await focusedTitle(page)).toBe("Levels of a node"); + await keys(page, "j j j j j j"); + expect(await focusedTitle(page)).toBe("Deeper, not longer"); + // A click on a row does what l does: focus it and show its pane. + await page.locator(".pane .row", { hasText: "Generation on demand" }).click(); + expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand"]); + expect(await focusedTitle(page)).toBe("Generation on demand"); +}); + +test("a pre-generated note opened in a pane is set inside the pane", async ({ page }) => { + await open(page); + await jump(page, "Expansion by depth"); + await keys(page, "l Tab Enter"); + const pane = page.locator(".strip > .pane").nth(1); + const note = pane.locator(".sidenote").first(); + await expect(note).toBeVisible(); + const [n, p, body] = await Promise.all([note.boundingBox(), pane.boundingBox(), pane.locator(".pane-head").boundingBox()]); + expect(n!.x).toBeGreaterThanOrEqual(body!.x); // in the pane's column, not a margin + expect(n!.x + n!.width).toBeLessThanOrEqual(body!.x + body!.width + 1); + expect(n!.x + n!.width).toBeLessThanOrEqual(p!.x + p!.width); + expect(await pane.locator(".pane-scroll").evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true); + // And by mouse: a click on the marked span closes it again. + await pane.locator(".anchor.on").first().click(); + await expect(pane.locator(".sidenote")).toHaveCount(0); +}); + +test("in panes everything is reachable with the mouse: rows, headings, marked spans, a dragged selection", async ({ page }) => { + await open(page); + await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click(); + expect(await paneTitles(page)).toEqual(["Infinispand", "Borrowed from Gwern"]); + await page.locator(".pane .row", { hasText: "Semantic zoom" }).click(); + expect(await paneTitles(page)).toEqual(["Infinispand", "Borrowed from Gwern", "Semantic zoom"]); + // A marked span opens its note, and closes it again. + const anchor = page.locator(".pane .anchor", { hasText: "StretchText" }); + await anchor.click(); + await expect(page.locator(".pane .anchor.on")).toHaveCount(1); + await anchor.click(); + await expect(page.locator(".pane .anchor.on")).toHaveCount(0); + // A pane's heading focuses its node, leaving the trail as it is; a click on the focused row whose pane is showing closes that pane. + await page.locator(".pane-head", { hasText: "Borrowed from Gwern" }).click(); + expect(await focusedTitle(page)).toBe("Borrowed from Gwern"); + expect(await paneTitles(page)).toEqual(["Infinispand", "Borrowed from Gwern", "Semantic zoom"]); + await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click(); + expect(await paneTitles(page)).toEqual(["Infinispand"]); + await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click(); + await page.locator(".pane .row", { hasText: "Typography" }).click(); + // Dragging across a pane's text makes that range the focus. + const para = page.locator(".strip > .pane").last().locator(".para").first(); + const box = (await para.boundingBox())!; + await page.mouse.move(box.x + 6, box.y + 12); + await page.mouse.down(); + await page.mouse.move(box.x + 150, box.y + 12, { steps: 6 }); + await page.mouse.up(); + const focus = await state(page, (s) => ({ title: s.snap.nodes[s.focus.node].title, grain: s.focus.grain, text: s.snap.nodes[s.focus.node].body.slice(s.focus.range[0], s.focus.range[1]) })); + expect(focus.title).toBe("Typography"); + expect(focus.grain).toBe("word"); + expect(focus.text.length).toBeGreaterThan(3); + await page.keyboard.press("Escape"); +}); + +test("past the viewport, earlier panes become spines; a click on one brings it back", async ({ page }) => { + await open(page); + await keys(page, "l l l j j l l l"); + await expect(page.locator(".strip > .pane")).toHaveCount(4); + // The focused pane, and its parent with the marked row, end up fully in view. + await expect.poll(async () => { + const ps = await panes(page); + return ps[3].left >= 0 && ps[3].right <= 1920 + 1 && ps[2].left >= 0 && ps[2].right <= ps[3].left + 1; + }).toBe(true); + const strip = page.locator(".strip"); + expect(await strip.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true); + // The root has slid under the rest and shows as a spine, its title set vertically. + const spine = page.locator('.pane[data-covered] .spine').first(); + await expect(spine).toHaveText("Infinispand"); + await expect.poll(() => spine.evaluate((el) => getComputedStyle(el).opacity)).toBe("1"); + expect(await spine.locator("span").evaluate((el) => getComputedStyle(el).writingMode)).toBe("vertical-rl"); + const box = (await spine.boundingBox())!; + expect(box.x).toBeGreaterThanOrEqual(0); + expect(box.width).toBeLessThan(60); + await spine.click(); + expect(await focusedTitle(page)).toBe("Infinispand"); + // The trail stays; the strip slides back to show the first pane whole. + await expect(page.locator(".strip > .pane")).toHaveCount(4); + await expect.poll(async () => (await panes(page))[0].left).toBe(0); + await expect(page.locator(".pane[data-covered]")).toHaveCount(0); +}); + +test("generation in a pane: a note on a sentence streams in; a leaf gets sections as rows", async ({ page }) => { + await open(page); + await jump(page, "Why it ends"); + await keys(page, "l i j e"); + const last = page.locator(".strip > .pane").last(); + await expect(last.locator(".pane-head h2")).toHaveText("Why it ends"); + await expect(last.locator(".sidenote.pending")).toBeVisible(); + await idle(page); + await expect(last.locator(".sidenote")).toContainText("Mock note on"); + await keys(page, "Escape Escape"); + await jump(page, "Downward: rendered children"); + await keys(page, "e e"); + await idle(page); + const pane = page.locator(`.pane[data-pane="${await nodeId(page, "Downward: rendered children")}"]`); + await expect(pane.locator(".rows .row")).toHaveText([/First part of Downward: rendered children/, /Second part of Downward: rendered children/]); + await keys(page, "l l"); // into the new section, and open it: a fifth pane + await expect(page.locator(".strip > .pane")).toHaveCount(5); + expect((await paneTitles(page)).at(-1)).toBe("First part of Downward: rendered children"); +}); + +test("editing in a pane: c, type, Esc", async ({ page }) => { + await open(page); + await jump(page, "Pinned nodes"); + await keys(page, "c"); + const editor = page.locator(".pane .editor"); + await expect(editor).toBeFocused(); + await page.keyboard.press("Control+a"); + await page.keyboard.type("Rewritten in a pane."); + await page.keyboard.press("Escape"); + await expect(page.locator(".strip > .pane").last().locator(".body").first()).toHaveText("Rewritten in a pane."); + expect(await state(page, (s) => s.snap.nodes[s.focus.node].body)).toBe("Rewritten in a pane."); + // r renames at the head of the pane. + await keys(page, "r"); + await expect(page.locator(".pane-head .title-editor")).toBeFocused(); + await page.keyboard.press("Escape"); + await idle(page); +}); + +test("keypress → paint stays within the 50 ms budget in panes", async ({ page }) => { + await open(page); + // One keystroke per frame, as in the column test. + const paced = async (seq: string) => { + for (const k of seq.split(" ")) { + await page.keyboard.press(k); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => r(null)))); + } + }; + // Walk down and across: open each top-level section, then three of its children in turn, + // read a sentence of the last, close back up and move to the next section. + for (let pass = 0; pass < 2; pass++) { + await paced("O"); + for (let i = 0; i < 10; i++) await paced(`${i === 0 ? "l" : "j"} l l l j l j l i j Escape h h`); + } + // Open notes in a pane from the keyboard. + await jump(page, "Levels of a node"); + await paced("Tab Enter Tab Enter Tab Enter Escape Escape"); + await jump(page, "Expansion by depth"); + await paced("l Tab Enter Tab Enter Escape Escape"); + const samples: Sample[] = await state(page, (s) => s.samples); + const ms = samples.filter((x) => x.what !== "first-token").map((x) => x.ms).sort((a, b) => a - b); + const pct = (p: number) => ms[Math.min(ms.length - 1, Math.floor(ms.length * p))]; + const report = { view: "panes", keystrokes: ms.length, median: pct(0.5), p95: pct(0.95), max: ms[ms.length - 1] }; + const slow = samples.filter((x) => x.what !== "first-token" && x.ms > 30).map((x) => `${x.what}:${Math.round(x.ms)}`); + console.log("panes keypress → paint (ms):", JSON.stringify(report), "over 30ms:", slow.join(" ")); + writeReport("paint-panes", report); + expect(ms.length).toBeGreaterThan(150); + expect(report.p95).toBeLessThan(50); +}); + +test("only the strip scrolls sideways, and nothing hides behind the status line", async ({ page }) => { + await open(page); + await keys(page, "l l l j j l l l"); + await expect(page.locator(".strip > .pane")).toHaveCount(4); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth && document.body.scrollWidth <= window.innerWidth)).toBe(true); + expect(await page.evaluate(() => (window.scrollX, document.scrollingElement!.scrollLeft))).toBe(0); + expect(await page.locator(".strip").evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true); + const status = (await page.locator(".status").boundingBox())!; + const strip = (await page.locator(".strip").boundingBox())!; + expect(strip.y + strip.height).toBeLessThanOrEqual(status.y + 0.5); + // The longest pane (the root's list) scrolls its last row clear of the status line. + await keys(page, "O k"); + const root = page.locator(".pane.root .pane-scroll"); + await root.evaluate((el) => (el.scrollTop = el.scrollHeight)); + const lastRow = (await page.locator(".pane.root .rows > .node").last().boundingBox())!; + expect(lastRow.y + lastRow.height).toBeLessThanOrEqual(status.y); + // The history panel takes its width from the strip rather than covering it. + await keys(page, "g"); + const panel = (await page.locator(".panel").boundingBox())!; + const narrowed = (await page.locator(".strip").boundingBox())!; + expect(narrowed.x + narrowed.width).toBeLessThanOrEqual(panel.x + 1); + await keys(page, "Escape"); +}); diff --git a/e2e/research.spec.ts b/e2e/research.spec.ts new file mode 100644 index 0000000..8286ad1 --- /dev/null +++ b/e2e/research.spec.ts @@ -0,0 +1,102 @@ +/** + * /research with the mock model: its fake web search and fetch (no network) are shown step by step + * above the status line, the section it writes carries links to the pages it read, those open in a + * new tab, and Esc stops a run without keeping anything it did. + */ +import { expect, test, type Page } from "@playwright/test"; +import { command, idle, jump, keys, settle, state } from "./helpers"; + + +async function open(page: Page) { + // Record what would open in a new tab instead of opening it. + await page.addInitScript(() => { + (globalThis as any).__opened = []; + window.open = ((url: string) => ((globalThis as any).__opened.push(String(url)), null)) as typeof window.open; + }); + await page.goto("/doc/infinite-expand"); + await page.waitForSelector("article"); +} + +test.describe.configure({ mode: "serial" }); + +test.afterEach(({ page }) => settle(page)); + +test("/research shows its searches and pages, writes a section, and links its claim to a page it read", async ({ page }) => { + await open(page); + expect(await state(page, (s) => s.web)).toEqual({ on: true, searches: 5, fetches: 5 }); + await jump(page, "The tree underneath"); + await command(page, "/research how tides work"); + + const panel = page.locator(".agent-panel"); + await expect(panel).toBeVisible(); + await expect(panel).toHaveAttribute("data-agent", "running"); + await expect(panel.locator(".agent-head")).toContainText("Esc stops"); + await expect(panel.locator(".agent-steps")).toContainText("searched “how tides work”: 3 results"); + await expect(panel.locator(".agent-steps")).toContainText("read “How tides work” · example.org"); + await expect(panel).toHaveAttribute("data-agent", "done"); + // The edits are steps too, after the research. + const steps = await panel.locator(".agent-steps li").allTextContents(); + const searched = steps.findIndex((s) => s.startsWith("searched")); + const edited = steps.findIndex((s) => s.startsWith("added “On how tides work”")); + expect(searched).toBeGreaterThanOrEqual(0); + expect(edited).toBeGreaterThan(searched); + expect(steps).toContain("linked “pulled by the Moon” to How tides work (example.org)"); + // The summary lists the sources it linked. + await expect(panel.locator(".agent-summary")).toContainText("mock agent"); + await expect(panel.locator(".agent-sources a")).toHaveText("How tides work"); + await expect(panel.locator(".agent-sources a")).toHaveAttribute("href", "https://example.org/research/tides"); + await expect(page.locator(".status .message")).toContainText("sources: How tides work (example.org)"); + await idle(page); + + // The section is in the document, with the phrase linked to the page: a web link, marked ↗. + const link = await state(page, (s) => { + const snap = s.snap; + const sec = Object.values(snap.nodes).find((n: any) => n.title === "On how tides work") as any; + const note = sec && sec.children.map((c: string) => snap.nodes[c]).find((c: any) => c.kind === "note" && c.ref); + return note ? { ref: note.ref, words: note.anchors[0].text, body: note.body, by: snap.nodes[sec.id].by } : null; + }); + expect(link).toEqual({ ref: { kind: "url", url: "https://example.org/research/tides", title: "How tides work" }, words: "pulled by the Moon", body: "", by: "llm" }); + + // Esc puts the finished panel away. + await keys(page, "Escape"); + await expect(panel).toHaveCount(0); + + // The link opens: go to the section, Tab to the linked words, Enter (twice in the column: a + // preview first) opens the page in a new tab. + await jump(page, "On how tides work"); + await keys(page, "l"); + const sec = page.locator(".node.open", { hasText: "pulled by the Moon" }).last(); + await expect(sec.locator(".lmark.l-url")).toHaveText("↗"); + await keys(page, "Tab"); + expect(await state(page, (s) => s.snap.nodes[s.focus.node].body.slice(s.focus.range?.[0], s.focus.range?.[1]))).toBe("pulled by the Moon"); + for (let i = 0; i < 2 && !(await page.evaluate(() => (globalThis as any).__opened.length)); i++) await keys(page, "Enter"); + expect(await page.evaluate(() => (globalThis as any).__opened)).toEqual(["https://example.org/research/tides"]); +}); + +test("an ordinary request that asks to look something up uses the web too", async ({ page }) => { + await open(page); + await jump(page, "The tree underneath"); + await command(page, "look up neap tides"); + await expect(page.locator(".agent-panel .agent-steps")).toContainText("searched “look up neap tides”"); + await expect(page.locator(".agent-panel")).toHaveAttribute("data-agent", "done"); + await idle(page); + await keys(page, "Escape"); +}); + +test("Esc stops a research run, and nothing it did is kept", async ({ page }) => { + await open(page); + await jump(page, "The tree underneath"); + const before = await state(page, (s) => Object.keys(s.snap.nodes).length); + await command(page, "/research stop me"); + const panel = page.locator(".agent-panel"); + await expect(panel.locator(".agent-steps")).toContainText("searched “stop me”"); + await keys(page, "Escape"); + await expect(page.locator(".status .message")).toContainText("stopped; nothing it did was kept"); + await expect(panel).toHaveAttribute("data-agent", "done"); + await expect(panel.locator(".agent-summary")).toHaveText("Stopped. Nothing it did was kept."); + await idle(page); + expect(await state(page, (s) => Object.keys(s.snap.nodes).length)).toBe(before); + expect(await state(page, (s) => Object.values(s.snap.nodes).some((n: any) => n.title === "On stop me"))).toBe(false); + await keys(page, "Escape"); + await expect(panel).toHaveCount(0); +}); diff --git a/e2e/review.spec.ts b/e2e/review.spec.ts new file mode 100644 index 0000000..ce71284 --- /dev/null +++ b/e2e/review.spec.ts @@ -0,0 +1,282 @@ +/** + * Link discovery, keyboard only: links made automatically after an edit (and undone with u), + * suggestions shown in the text and taken or declined with y and n, review mode, the [[ completer, + * bare [[marks]] resolved on save, model-written text with its marks taken out and checked, the + * Related list, /linkdoc with progress and a cancel, the /autolink modes, and latency. Against the + * mock model, the mock Wikipedia (Octopus, Cephalopod, Fred Hoyle, Hoyle state, Carbon-12, Lambda + * calculus, …) and the hashed-words embedder (IE_EMBED=fake). + */ +import { expect, test, type Page } from "@playwright/test"; +import { command, idle, jump, keys, selected, settle, state, writeReport } from "./helpers"; + +const body = (page: Page) => state(page, (s) => s.snap.nodes[s.focus.node].body as string); +/** The links on the focused node: quote → target title (or node id). */ +const linksHere = (page: Page) => + state(page, (s) => { + const snap = s.snap; + const out: Record = {}; + for (const c of snap.nodes[s.focus.node].children) { + const n = snap.nodes[c]; + if (n.kind === "note" && n.ref) out[n.anchors[0].text] = n.ref.kind === "wiki" ? n.ref.title : n.ref.kind === "node" ? `node:${snap.nodes[n.ref.id]?.title}` : n.ref.url; + } + return out; + }); +const suggestions = (page: Page) => state(page, (s) => s.links.forNode(s.focus.node, s.snap).map((x: any) => x.quote) as string[]); + +async function column(page: Page, path = "/") { + await page.setViewportSize({ width: 1440, height: 900 }); + await page.goto(path); + await page.waitForFunction(() => (globalThis as any).__ie?.ready); + await page.evaluate(() => document.fonts.ready); +} + +/** A new document with this text, typed from the keyboard; the focus is on it afterwards. */ +async function newDoc(page: Page, title: string, text: string) { + await command(page, `/new ${title}`); + // In panes the library's pane has a heading too. + await expect(page.locator("h1", { hasText: title })).toBeVisible(); + await keys(page, "c"); + await page.keyboard.type(text); + await page.keyboard.press("Escape"); +} + +test.describe.configure({ mode: "serial" }); + +test.beforeEach(async ({ context }) => { + await context.route(/wikipedia\.org|wikimedia\.org/, (r) => r.abort()); +}); + +test.afterEach(async ({ page }) => { + if (await state(page, (s) => !!s?.ready).catch(() => false)) await command(page, "/autolink suggest"); + await settle(page); +}); + +test("with /autolink on, the sure links are made at once after an edit, as their own commit, and u removes them", async ({ page }) => { + await column(page); + expect(await state(page, (s) => s.settings.autolink)).toBe("suggest"); + await command(page, "/autolink on"); + await newDoc(page, "Autolink one", "The cephalopod met Fred Hoyle, who taught it the lambda calculus."); + await idle(page); + await expect(page.locator("article .lnk")).toHaveCount(3); + expect(await linksHere(page)).toEqual({ cephalopod: "Cephalopod", "Fred Hoyle": "Fred Hoyle", "lambda calculus": "Lambda calculus" }); + await expect(page.locator(".status .message")).toContainText("Linked"); + const top = await state(page, (s) => s.commits()[0]); + expect(top).toMatchObject({ by: "linker", tag: "autolink" }); + await keys(page, "u"); + await expect(page.locator("article .lnk")).toHaveCount(0); + // Only the links went: the text typed is still there. + expect(await body(page)).toContain("Fred Hoyle"); +}); + +test("suggestions are drawn in the text; Tab reaches them, y links one, n declines one for good; S reviews the rest", async ({ page }) => { + await column(page); + await command(page, "/autolink suggest"); + await newDoc(page, "Suggested links", "The cephalopod met Fred Hoyle.\n\nHe spoke of the Hoyle state of carbon-12 and of the lambda calculus."); + await idle(page); + await expect(page.locator("article .sugg")).toHaveCount(5); + await expect(page.locator("article .lnk")).toHaveCount(0); + // Tab lands on the first; its card shows the proposed article with its summary. + await keys(page, "Tab"); + expect(await selected(page)).toBe("cephalopod"); + await expect(page.locator(".suggestion")).toContainText("Cephalopod"); + await expect(page.locator(".suggestion")).toContainText("Class of mollusks"); + await keys(page, "y"); + expect(await linksHere(page)).toEqual({ cephalopod: "Cephalopod" }); + await keys(page, "Escape Escape Tab Tab"); + expect(await selected(page)).toBe("Fred Hoyle"); + await keys(page, "n"); + expect(await state(page, (s) => s.snap.nodes[s.focus.node].nolink)).toEqual(["fred hoyle"]); + await expect(page.locator("article .sugg")).toHaveCount(3); + // An edit elsewhere in the node does not bring the declined one back. + await keys(page, "Escape Escape c End"); + await page.keyboard.type(" Indeed."); + await keys(page, "Escape"); + await idle(page); + expect(await suggestions(page)).not.toContain("Fred Hoyle"); + // Review: step through what is left; s skips, n declines, Y links all that remain. + await keys(page, "S"); + await expect(page.locator(".status .message")).toContainText("review 1/3"); + expect(await selected(page)).toBe("Hoyle state"); + await keys(page, "s"); + expect(await selected(page)).toBe("carbon-12"); + await keys(page, "n"); + expect(await selected(page)).toBe("lambda calculus"); + await keys(page, "Y"); + expect(await state(page, (s) => s.mode)).toBe("normal"); + expect(await linksHere(page)).toEqual({ cephalopod: "Cephalopod", "lambda calculus": "Lambda calculus" }); + expect(await suggestions(page)).toEqual(["Hoyle state"]); +}); + +test("typing [[ in the editor completes from library titles first, then Wikipedia; the choice is linked on save", async ({ page }) => { + await column(page); + await newDoc(page, "Completer", "A start."); + await idle(page); + await keys(page, "c End"); + await page.keyboard.type(" See [[Recursion with"); + const completer = page.locator("[data-completer]"); + await expect(completer.locator(".choice").first()).toContainText("Recursion without names"); + await expect(completer.locator(".group").first()).toHaveText("Library"); + await keys(page, "Enter"); + await page.keyboard.type(" and the [[octo"); + await expect(completer.locator(".group", { hasText: "Wikipedia" })).toBeVisible(); + const choices = await completer.locator(".choice .t").allTextContents(); + const at = choices.indexOf("Octopus"); + expect(at).toBeGreaterThanOrEqual(0); + for (let i = 0; i < at; i++) await keys(page, "ArrowDown"); + await keys(page, "Enter"); + await expect(completer).toHaveCount(0); + await keys(page, "Escape"); + expect(await body(page)).toBe("A start. See Recursion without names and the octopus"); + expect(await linksHere(page)).toEqual({ "Recursion without names": "node:Recursion without names", octopus: "Octopus" }); +}); + +test("a bare [[term]] is looked up when the edit is saved: found, it is linked; not found, the writer is told", async ({ page }) => { + await column(page); + await newDoc(page, "Bare marks", "The [[Hoyle state]] and [[a thing nobody wrote about]]."); + await idle(page); + expect(await body(page)).toBe("The Hoyle state and a thing nobody wrote about."); + expect(await linksHere(page)).toEqual({ "Hoyle state": "Hoyle state" }); + await expect(page.locator(".status .message")).toContainText("Found nothing to link for “a thing nobody wrote about”"); +}); + +test("text a model writes arrives without its marks, and the ones that check out are links", async ({ page }) => { + await column(page); + await command(page, "/autolink on"); + await newDoc(page, "Model marks", "A leaf about sea creatures and recursion."); + await idle(page); + // e on a node with text and no sections asks the model for sections; the mock marks a few phrases. + await keys(page, "e"); + await idle(page); + const kids = await state(page, (s) => s.snap.nodes[s.focus.node].children.filter((c: string) => s.snap.nodes[c].kind === "section").map((c: string) => s.snap.nodes[c])); + expect(kids).toHaveLength(2); + for (const k of kids) expect(k.body).not.toContain("[["); + expect(kids[0].body).toBe("Mock body one. It elaborates the first half, as a cephalopod would."); + expect(kids[1].body).toContain("with no such article anywhere."); + const links = await state(page, (s) => + s.snap.nodes[s.focus.node].children.flatMap((c: string) => s.snap.nodes[c].children.map((x: string) => s.snap.nodes[x]).filter((x: any) => x.ref).map((x: any) => `${x.anchors[0].text}→${x.ref.kind === "wiki" ? x.ref.title : "node"}`)), + ); + expect(links).toContain("cephalopod→Cephalopod"); + // The phrase with no article is simply left as text. + expect(links.some((l: string) => l.startsWith("no such article"))).toBe(false); + // The second section's mark named a library node from the nearby list, by its handle. + expect(links.some((l: string) => l.endsWith("→node"))).toBe(true); + // Nothing on the page ever showed a bracket. + await expect(page.locator("article")).not.toContainText("[["); +}); + +test("the Related list sits under a node; a number links the selected words to that row's section", async ({ page }) => { + await column(page); + await newDoc(page, "Related here", "Fixed points of functions: a function maps a point to itself, and iterating finds the fixed point."); + await idle(page); + await expect(page.locator(".related-list li").first()).toBeVisible(); + const first = await page.locator(".related-list li .bl-title").first().textContent(); + // Select a word and press 1: it links to the first related section. + await keys(page, "i i"); + const word = await selected(page); + await keys(page, "1"); + expect(await linksHere(page)).toMatchObject({ [word]: `node:${first}` }); + await expect(page.locator("article .lnk.l-node")).toHaveCount(1); + // On the node itself, a number goes to that section. + await keys(page, "Escape Escape 2"); + expect(await state(page, (s) => s.snap.nodes[s.focus.node].title)).not.toBe("Related here"); +}); + +test("/linkdoc and /linkall look for links in the background, with progress in the status line and a cancel", async ({ page }) => { + await column(page, "/doc/fixed-points"); + await command(page, "/autolink suggest"); + await command(page, "/linkall"); + await page.waitForFunction(() => (globalThis as any).__ie.links.job?.state === "running" && (globalThis as any).__ie.links.job.done > 0); + await expect(page.locator(".status .job")).toContainText("links "); + // Navigation does not stop it. + await jump(page, "Recursion without names"); + await command(page, "/linkcancel"); + await page.waitForFunction(() => (globalThis as any).__ie.links.job?.state === "cancelled"); + const job = await state(page, (s) => s.links.job); + expect(job.done).toBeLessThan(job.total); + await expect(page.locator(".status .job")).toHaveCount(0); + // A document job runs to the end, and what it found is waiting in the text. + await command(page, "/linkdoc"); + await page.waitForFunction(() => (globalThis as any).__ie.links.job?.state === "done", undefined, { timeout: 30_000 }); + await expect(page.locator(".status .message")).toContainText("Looked for links in Fixed points"); + await page.waitForFunction(() => { + const s = (globalThis as any).__ie; + return s.links.under(Object.keys(s.snap.nodes), s.snap).length > 0; + }); + await keys(page, "S"); + await expect(page.locator(".status .message")).toContainText("review 1/"); + await keys(page, "Escape"); +}); + +test("/autolink off looks for nothing, suggest only suggests, on links", async ({ page }) => { + await column(page); + await command(page, "/autolink off"); + await newDoc(page, "Modes", "The cephalopod."); + await idle(page); + await expect(page.locator("article .sugg")).toHaveCount(0); + await expect(page.locator("article .lnk")).toHaveCount(0); + await command(page, "/autolink suggest"); + await keys(page, "c End"); + await page.keyboard.type(" And Fred Hoyle."); + await keys(page, "Escape"); + await idle(page); + await expect(page.locator("article .sugg")).toHaveCount(2); + await expect(page.locator("article .lnk")).toHaveCount(0); + await command(page, "/autolink on"); + await keys(page, "c End"); + await page.keyboard.type(" Again."); + await keys(page, "Escape"); + await idle(page); + await expect(page.locator("article .lnk")).toHaveCount(2); + expect(await state(page, (s) => s.settings.autolink)).toBe("on"); +}); + +test("Tab then Enter on an article that is still loading go to its first link once it arrives", async ({ page }) => { + await page.setViewportSize({ width: 1920, height: 1080 }); + await page.goto("/"); + await page.waitForFunction(() => (globalThis as any).__ie?.ready); + await newDoc(page, "Slow article link", "About the [[Hoyle state]]."); + await idle(page); + expect(await linksHere(page)).toEqual({ "Hoyle state": "Hoyle state" }); + // The article takes a while to come (a slow network); the reader does not wait for it. + await page.route(/\/api\/wiki\/article\?title=Hoyle/, async (r) => { + await new Promise((done) => setTimeout(done, 1500)); + await r.continue(); + }); + await keys(page, "Tab"); + expect(await selected(page)).toBe("Hoyle state"); + await keys(page, "Enter"); + await expect(page.locator(".strip > .pane").last().locator(".wiki-wait")).toBeVisible(); + await keys(page, "Tab Enter"); + await expect(page.locator(".status .message")).toContainText("still loading"); + // When it arrives, the Tab goes to its first link and the Enter opens that. + await expect(page.locator(".strip > .pane").last().locator(".wiki-head h2")).toHaveText("Carbon-12", { timeout: 10_000 }); +}); + +test("keypress → paint stays within a frame while suggestions are on screen and scans run after edits", async ({ page }) => { + await column(page); + await command(page, "/autolink suggest"); + await newDoc(page, "Latency", "The cephalopod met Fred Hoyle.\n\nHe spoke of the Hoyle state of carbon-12 and of the lambda calculus."); + await idle(page); + await page.evaluate(() => ((globalThis as any).__ie.samples.length = 0)); + const paced = async (seq: string) => { + for (const k of seq.split(" ")) { + await page.keyboard.press(k); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => r(null)))); + } + }; + for (let round = 0; round < 4; round++) { + await paced("Tab Tab Tab Tab Escape Escape i j j Escape"); + // An edit, saved: the scan it starts runs after the save, off the keystroke. + await paced("c"); + await page.keyboard.type(` More ${round}.`); + await paced("Escape"); + } + await idle(page); + const ms: number[] = (await state(page, (s) => s.samples)).filter((x: any) => x.what !== "first-token").map((x: any) => x.ms).sort((a: number, b: number) => a - b); + const p95 = ms[Math.floor(ms.length * 0.95)]; + const report = { keystrokes: ms.length, median: ms[ms.length >> 1], p95, max: ms[ms.length - 1] }; + console.log("keypress → paint with suggestions (ms):", JSON.stringify(report)); + writeReport("linking", report); + expect(ms.length).toBeGreaterThan(40); + expect(p95).toBeLessThan(50); +}); diff --git a/e2e/scale.spec.ts b/e2e/scale.spec.ts new file mode 100644 index 0000000..6ccfc78 --- /dev/null +++ b/e2e/scale.spec.ts @@ -0,0 +1,121 @@ +/** + * A large library in the browser: 100 more documents of 50 nodes each (over 5,000 nodes in all), + * written over the op API. Keypress → paint is measured as in the other specs, while moving + * through the library page, inside documents and across them, in the column and in panes; a body + * edit is timed from the store call to the painted frame. Runs last: it fills the shared library. + */ +import { expect, test, type Page } from "@playwright/test"; +import { state, synced, writeReport, type Sample } from "./helpers"; + +const ready = (page: Page) => page.waitForFunction(() => (globalThis as any).__ie?.ready === true, undefined, { timeout: 30_000 }); +/** One keystroke per frame, as in the other latency tests. */ +const paced = async (page: Page, seq: string) => { + for (const k of seq.split(" ")) { + await page.keyboard.press(k); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => r(null)))); + } +}; +const SENTENCE = "This sentence is about something that matters here. Another follows it, with a few more words. "; + +/** Edit a leaf's body through the store, and time it to the painted frame. */ +const editTimes = (page: Page, rounds: number) => + page.evaluate(async (rounds) => { + const s = (globalThis as any).__ie; + const paint = () => new Promise((r) => requestAnimationFrame(() => { + const ch = new MessageChannel(); + ch.port1.onmessage = () => r(); + ch.port2.postMessage(0); + })); + const out: number[] = []; + for (let i = 0; i < rounds; i++) { + const t = performance.now(); + s.startEdit("body"); + s.commitEdit(`Edited in the large library, round ${i}. ` + s.snap.nodes[s.focus.node].body); + await paint(); + out.push(performance.now() - t); + await new Promise((r) => setTimeout(r, 30)); + } + return out; + }, rounds); + +const stats = (ms: number[]) => { + const sorted = [...ms].sort((a, b) => a - b); + const pct = (p: number) => sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))]; + return { n: sorted.length, median: +pct(0.5).toFixed(1), p95: +pct(0.95).toFixed(1), max: +sorted[sorted.length - 1].toFixed(1) }; +}; +const keySamples = async (page: Page) => (await state(page, (s) => s.samples as Sample[])).filter((x) => x.what !== "first-token").map((x) => x.ms); + +test.describe.configure({ mode: "serial" }); +test.setTimeout(300_000); + +test("a library of over 5,000 nodes in 100 more documents: keypress → paint and a body edit, in the column and in panes", async ({ page, request }) => { + // Write the documents, one commit each, as an outside agent would. + const tree = await (await request.get("/api/tree")).json(); + let t = Date.now(); + for (let d = 0; d < 100; d++) { + const ops: any[] = [{ op: "create", parent: tree.root, title: `Scale document ${d}`, body: SENTENCE.repeat(3) }]; + let n = 1; + for (let s = 0; s < 7; s++) { + const sec = n++; + ops.push({ op: "create", parent: "$0", title: `Part ${d}.${s}`, body: SENTENCE.repeat(2) }); + for (let k = 0; k < 6; k++, n++) ops.push({ op: "create", parent: `$${sec}`, title: `Leaf ${d}.${s}.${k}`, body: SENTENCE.repeat(2) }); + } + ops.push({ op: "create", parent: "$0", kind: "note", quote: "something that matters", body: "A note." }); + for (let i = 0; i < n; i++) ops.push({ op: "bless", id: `$${i}` }); + const res = await request.post("/api/ops", { data: { author: "scale", message: `Scale document ${d}`, ops } }); + expect(res.ok()).toBe(true); + } + const written = Date.now() - t; + + // Boot: a fresh page fetches the whole library and reads it. + t = Date.now(); + await page.goto("/"); + await ready(page); + const bootFresh = Date.now() - t; + const nodes = await state(page, (s) => Object.keys(s.snap.nodes).length); + expect(nodes).toBeGreaterThan(5000); + await synced(page); + // And again, from the replica this browser now keeps. + t = Date.now(); + await page.reload(); + await ready(page); + const bootStored = Date.now() - t; + await page.evaluate(() => document.fonts.ready); + + // ---- the column ---- + await page.evaluate(() => ((globalThis as any).__ie.samples.length = 0)); + // Down the library page's 113 rows, into documents and out, across to the next. + for (let i = 0; i < 40; i++) await paced(page, "j"); + for (let i = 0; i < 6; i++) await paced(page, "l j l j l i j Escape h h h j"); + await paced(page, "O"); + const column = stats(await keySamples(page)); + // A body edit inside a document deep in the library. + await page.goto("/doc/scale-document-97"); + await ready(page); + await paced(page, "j l j"); + const columnEdit = stats(await editTimes(page, 15)); + + // ---- panes ---- + await page.setViewportSize({ width: 1920, height: 1080 }); + await page.goto("/"); + await ready(page); + await expect(page.locator(".strip > .pane")).toHaveCount(1); + await page.evaluate(() => ((globalThis as any).__ie.samples.length = 0)); + for (let i = 0; i < 40; i++) await paced(page, "j"); + for (let i = 0; i < 6; i++) await paced(page, "l l l j l i j Escape h h h j"); + const panes = stats(await keySamples(page)); + await page.goto("/doc/scale-document-98"); + await ready(page); + await paced(page, "l l j"); + const panesEdit = stats(await editTimes(page, 15)); + + const report = { nodes, documents: await state(page, (s) => s.snap.nodes[s.snap.root].children.length), writtenMs: written, bootFreshMs: bootFresh, bootStoredMs: bootStored, column, columnEdit, panes, panesEdit }; + console.log("large library:", JSON.stringify(report)); + writeReport("scale", report); + for (const r of [column, panes]) { + expect(r.n).toBeGreaterThan(80); + expect(r.p95).toBeLessThan(50); + } + for (const r of [columnEdit, panesEdit]) expect(r.median).toBeLessThan(50); + expect(bootStored).toBeLessThan(10_000); +});