// Page tests for the Notebook: the top bar icon on every screen, the tabs (made // by naming them, renamed, reordered, deleted after two confirms), the live // Markdown editor, autosave per tab and what survives a reload or a restart, // one notepad per folder, the page's content-security policy with the editor // open, hostile Markdown, typing speed on a long note, both themes, and the // pictures: adding, deleting, the preview and the cap. // Run with: // node --test scripts/test-web-console-page-notepad.mjs // // Each test drives the real console in a real Chrome or Edge through // scripts/page-test-helpers.mjs: one browser for the file, a fresh console // session per test. Notes land in the file's throwaway NOTEPADS_DIR. // // The editor lives in the open shadow root of `.notepad-cm-host`: Playwright's // CSS locators pierce it, `page.evaluate` code reaches in through `shadowRoot`, // and the text is read from the editor's own state (`docText`), since lines // the cursor is not on draw without their Markdown marks. import fs from "node:fs"; import path from "node:path"; import test from "node:test"; import assert from "node:assert/strict"; import { pageSuite, openSession, drawn, styleOf } from "./page-test-helpers.mjs"; import { JPEG, backdate, cli, until } from "./web-console-test-helpers.mjs"; import { LEGACY_TAB_ID, NOTEPAD_MAX_IMAGES, NOTE_MAX_BYTES, addImage as addImageTo, createTab, defaultTabId, deleteTab, listTabs, markTabSent, notepadFolder, notepadKey, readNotepad, removeImage as removeImageFrom, saveNote as saveNoteTo, } from "../src/web-console/notepads.mjs"; import { NOT_LOADED, SAVE_DEBOUNCE_MS, errorSentence } from "../src/web-console/public/notepad.js"; const suite = pageSuite(test); // The store calls here name the tab they use: the last one, with Notes made // first when the notepad has none. const openTab = (folder) => defaultTabId(folder) ?? createTab(folder, "Notes").id; const saveNote = (folder, text) => saveNoteTo(folder, openTab(folder), text); const addImage = (folder, buf) => addImageTo(folder, openTab(folder), buf); const removeImage = (folder, id) => removeImageFrom(folder, openTab(folder), id); // A plan session on the person's turn. const PLAN_QUESTION = { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }], agent: { status: "waiting" }, }; // The editor's editable surface (the locator pierces the shadow root). const input = (s) => s.page.locator("#notepad-editor .cm-content"); // The editor's whole text. const docText = (s) => s.page.evaluate(async () => { const { EditorView } = await import("/vendor/codemirror.esm.js"); const content = document.querySelector(".notepad-cm-host").shadowRoot.querySelector(".cm-content"); return EditorView.findFromDOM(content).state.doc.toString(); }); // Replaces the text the way typing does: through the editor, so autosave runs. const setDoc = (s, text) => s.page.evaluate(async (t) => { const { EditorView } = await import("/vendor/codemirror.esm.js"); const content = document.querySelector(".notepad-cm-host").shadowRoot.querySelector(".cm-content"); const view = EditorView.findFromDOM(content); view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: t }, selection: { anchor: t.length } }); }, text); // Opens the notepad and, unless told the note cannot load, waits until it has: // the editor is read-only until then. A notepad with no tab gets Notes first, // unless `tabs: false`, since an empty one shows the empty state instead. async function openNotepad(s, { loads = true, tabs = true } = {}) { if (tabs && !listTabs(s.project).tabs.length) createTab(s.project, "Notes"); await s.page.click("#btn-notepad"); await s.page.locator("#notepad-modal[open]").waitFor(); if (tabs) await input(s).waitFor(); if (loads && tabs) { await s.page.waitForFunction(() => { const c = document.querySelector(".notepad-cm-host")?.shadowRoot?.querySelector(".cm-content"); return Boolean(c) && c.getAttribute("aria-readonly") !== "true"; }); } } async function closeNotepad(s) { await s.page.click("#notepad-close"); await s.page.waitForFunction(() => !document.getElementById("notepad-modal").open); } // The editor's text once the page has read the note in: opening reads it from // the server, so the first value can still be the empty editor. async function shows(s, text) { await until(async () => (await docText(s)) === text, 5000); return docText(s); } // Types as a person does, into the end of the text. async function typeInto(s, text) { await input(s).click(); await s.page.keyboard.press("Control+End"); await s.page.keyboard.type(text); } // The note on disk for the session's folder (its last tab), as the store reads it. const onDisk = (s) => readNotepad(s.project).text; // Records content-security violations from now on; the getter lists them. async function watchViolations(s) { await s.context.addInitScript(() => { window.__violations = []; document.addEventListener("securitypolicyviolation", (e) => window.__violations.push(`${e.violatedDirective} ${e.blockedURI} ${e.sourceFile}:${e.lineNumber} ${e.sample}`), ); }); await s.page.reload({ waitUntil: "domcontentloaded" }); await drawn(s.page); return () => s.page.evaluate(() => window.__violations); } async function iconUsable(s, where) { const btn = s.page.locator("#btn-notepad"); assert.ok(await btn.isVisible(), `the icon shows on ${where}`); assert.ok(await btn.isEnabled(), `the icon is usable on ${where}`); assert.equal(await btn.getAttribute("aria-label"), "Notebook"); assert.equal(await btn.getAttribute("title"), "Notebook"); } test("the notepad icon shows on the dashboard, a skill session and a finished screen", async (t) => { const dash = await openSession(await suite.browser(), { t, workflow: "dashboard" }); await iconUsable(dash, "the dashboard"); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); await iconUsable(s, "a skill session"); // Right of Stop session and Subagents, in the same row. const order = await s.page.evaluate(() => [...document.querySelectorAll(".topbar-row.second .row-left > button")].map((b) => b.id), ); assert.ok(order.indexOf("btn-notepad") > order.indexOf("btn-stop"), order.join(", ")); assert.equal(order.indexOf("btn-notepad"), order.indexOf("btn-subagents") + 1, order.join(", ")); s.post({ settle: true, finish: { headline: "The plan is done", body: "All written down." } }); await s.page.locator(".handoff, .end-pane, #main").first().waitFor(); await s.page.waitForFunction(() => document.getElementById("btn-stop").hidden); await iconUsable(s, "the finished screen"); await openNotepad(s); }); test("typing Markdown styles it in place, saves within two seconds, and survives close, reload and a restart", async (t) => { const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); await openNotepad(s); assert.equal(await input(s).getAttribute("aria-label"), "Notebook text"); await typeInto(s, "# Shopping list\n\nSome **bold** text"); const typedAt = Date.now(); // Styled in place: the heading line is drawn large, the bold run bold. await s.page.locator("#notepad-editor .cm-h1").waitFor(); assert.match(await s.page.locator("#notepad-editor .cm-h1").innerText(), /Shopping list/); const sizes = await s.page.evaluate(() => { const root = document.querySelector(".notepad-cm-host").shadowRoot; const px = (el) => parseFloat(getComputedStyle(el).fontSize); return { heading: px(root.querySelector(".cm-h1")), body: px(root.querySelector(".cm-content")) }; }); assert.ok(sizes.heading > sizes.body * 1.4, `the heading is larger than the text (${sizes.heading}px against ${sizes.body}px)`); assert.equal(await s.page.locator("#notepad-editor .cm-strong").count(), 1); await until(() => onDisk(s) === "# Shopping list\n\nSome **bold** text", 4000); assert.ok(Date.now() - typedAt < 2000, `saved ${Date.now() - typedAt} ms after the last key`); await s.page.waitForFunction(() => document.getElementById("notepad-status").textContent === "Saved"); // Close flushes at once, without waiting out the debounce. await s.page.keyboard.type("\nmore"); await s.page.click("#notepad-close"); const closedAt = Date.now(); await until(() => onDisk(s).endsWith("\nmore"), 4000); assert.ok(Date.now() - closedAt < SAVE_DEBOUNCE_MS, `flushed ${Date.now() - closedAt} ms after close`); assert.equal(await s.page.evaluate(() => document.activeElement && document.activeElement.id), "btn-notepad"); const expected = "# Shopping list\n\nSome **bold** text\nmore"; await s.page.reload({ waitUntil: "domcontentloaded" }); await drawn(s.page); await openNotepad(s); assert.equal(await shows(s, expected), expected, "a reload shows the saved note"); // A server restart (the agent's open --resume) keeps it too. cli(["stop", "--session", s.sid, "--force"], { cwd: s.project }); await until(async () => !(await s.answers()), 5000); const resumed = cli(["open", "--resume", s.sid, "--no-open", "--workflow", "plan"], { cwd: s.project }).json; s.url = resumed.url; await s.page.goto(s.url, { waitUntil: "domcontentloaded" }); await drawn(s.page); await openNotepad(s); assert.equal(await shows(s, expected), expected, "a restarted server shows the saved note"); }); test("two sessions in two folders keep two separate notepads", async (t) => { const a = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); const b = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); await openNotepad(a); await setDoc(a, "Folder A's note"); await until(() => onDisk(a) === "Folder A's note", 4000); await openNotepad(b); assert.equal(await docText(b), "", "the second folder starts empty"); await setDoc(b, "Folder B's note"); await until(() => onDisk(b) === "Folder B's note", 4000); assert.equal(onDisk(a), "Folder A's note"); // Reopening each shows its own. await closeNotepad(a); await openNotepad(a); assert.equal(await shows(a, "Folder A's note"), "Folder A's note"); }); test("the editor breaks no content-security rule, and hostile Markdown runs nothing", async (t) => { const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); const consoleErrors = []; s.page.on("console", (m) => { if (m.type() === "error") consoleErrors.push(m.text()); }); const violations = await watchViolations(s); await openNotepad(s); await typeInto( s, "# Title\n\n- a list with `code` and [a link](https://example.com)\n> quoted\n\n" + '\n\n' + 'click\n', ); await until(() => onDisk(s).includes("__pwned3"), 4000); await s.page.waitForTimeout(300); const result = await s.page.evaluate(() => { const root = document.querySelector(".notepad-cm-host").shadowRoot; return { pwned: [window.__pwned, window.__pwned2, window.__pwned3], // CodeMirror's own empty spacer images (aria-hidden) beside widgets are not typed HTML. imgs: root.querySelectorAll("img:not(.cm-widgetBuffer)").length, scripts: root.querySelectorAll("script").length, styleTags: root.querySelectorAll("style").length + document.querySelectorAll("style").length, }; }); assert.deepEqual(await violations(), [], "no content-security violations with the notepad open"); assert.deepEqual(result.pwned, [undefined, undefined, undefined], "nothing typed ran"); assert.equal(result.imgs, 0, "typed HTML stays text"); assert.equal(result.scripts, 0); assert.equal(result.styleTags, 0, "the editor added no