// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. import { createRequire } from "node:module"; import assert from "node:assert/strict"; const require = createRequire(import.meta.url); const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); page.setDefaultTimeout(10000); const errors = []; page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); }); page.on("pageerror", error => errors.push(error.message)); await page.addInitScript(() => { window.isTauri = true; const root = "C:\\smoke-workspace"; const files = new Map([ ["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"], ["notes/second.md", "# Second note\n"], ["src/hello.py", "print('hello')\n"], ]); const callbacks = new Map(); const listeners = new Map(); let sequence = 0; const calls = []; const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); }; window.__TAURI_INTERNALS__ = { metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, unregisterCallback: id => callbacks.delete(id), invoke: async (command, args = {}) => { calls.push({ command, args }); if (command === "plugin:event|listen") { const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler; } if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; } if (command === "workspace_write_bytes") { if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; }); if (window.__TEST__.failWrite) throw new Error("Image write failed"); files.set(args.rel, args.base64); return; } if (command === "workspace_read_data_url") { if (!files.has(args.rel)) throw new Error("missing image"); return "data:image/svg+xml;base64," + files.get(args.rel); } if (command === "workspace_last_path") return root; if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" }; if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); } if (command === "workspace_write") { if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk"); files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return; } if (command === "workspace_list") { const prefix = args.rel ? args.rel + "/" : ""; const entries = new Map(); for (const path of files.keys()) { if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue; const tail = path.slice(prefix.length); const name = tail.split("/")[0]; entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" }); } return [...entries.values()]; } if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; } if (command === "workspace_search") return []; if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }]; if (command === "pty_open") { const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")]; emit("pty-data", { id: args.id, data: data.slice(0, 8) }); emit("pty-data", { id: args.id, data: data.slice(8) }); await new Promise(resolve => setTimeout(resolve, 50)); return; } if (command.startsWith("pty_")) return; if (command === "plugin:dialog|message") return "Cancel"; throw new Error(`Unhandled IPC: ${command}`); }, }; window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; window.__TEST__ = { files, calls, emit, root }; }); async function openNote(name = "welcome.md") { await page.keyboard.press("Control+p"); await page.getByRole("textbox", { name: "Find a file" }).fill(name); await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click(); await page.locator(".cm-content").waitFor(); } async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); } async function save() { await page.keyboard.press("Control+s"); await page.waitForTimeout(100); return page.evaluate(() => window.__TEST__.files.get("notes/welcome.md")); } async function drop(count = 1, selector = ".cm-content") { await page.locator(selector).evaluate((element, count) => { const data = new DataTransfer(); const svg = 'Image drop test'; for (let i = 0; i < count; i++) data.items.add(new File([svg], "picture.svg", { type: "" })); const rect = element.getBoundingClientRect(); element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 })); }, count); } try { await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); await page.getByText("smoke-workspace", { exact: true }).waitFor(); await openNote(); await page.evaluate(async () => { const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js"); window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content")); window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "First paragraph.\n\nLast paragraph.\n" } }); }); const original = await source(); const acceptsDrag = await page.locator(".cm-content").evaluate(element => { const data = new DataTransfer(); data.items.add(new File(["x"], "test.svg")); const event = new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer: data }); element.dispatchEvent(event); return event.defaultPrevented; }); assert.ok(acceptsDrag); await drop(2); await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 2); await page.locator(".md-image-frame img").first().waitFor(); assert.equal(await page.locator(".md-image-frame img").count(), 2); const inserted = await source(); assert.ok(inserted.indexOf("![]") < inserted.indexOf("First paragraph."), "drop inserts at pointer, not stale cursor"); const paths = [...inserted.matchAll(/!\[\]\(([^)]+)\)/g)].map(match => match[1]); assert.notEqual(paths[0], paths[1]); assert.ok(paths.every(path => path.startsWith("../attachments/"))); assert.equal(await save(), inserted); // Selecting and editing Markdown leaves the image visible and updates its alt text. await page.locator(".md-image-frame").first().hover(); await page.getByRole("button", { name: "Edit image source", exact: true }).first().click(); assert.equal(await page.locator(".md-image-frame img").count(), 2); assert.ok((await page.locator(".cm-line").allTextContents()).some(line => line.includes(paths[0]))); await page.evaluate(() => { const view = window.__CM__, from = view.state.doc.toString().indexOf("![]") + 2; view.dispatch({ changes: { from, insert: "Edited alt" }, selection: { anchor: from + 10 } }); }); await page.locator('img[alt="Edited alt"]').waitFor(); await page.screenshot({ path: ".audit/images-editing.png" }); await page.locator(".md-image-frame").first().hover(); await page.getByRole("button", { name: "Zoom in", exact: true }).first().click(); const zoom = page.getByRole("dialog", { name: "Image zoom" }); await zoom.waitFor(); await zoom.getByRole("button", { name: "Zoom in", exact: true }).click(); assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "100%"); await zoom.getByRole("button", { name: "Zoom in", exact: true }).click(); assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "200%"); await page.screenshot({ path: ".audit/images-zoom.png" }); await zoom.getByRole("button", { name: "Fit image", exact: true }).click(); await page.keyboard.press("Escape"); assert.equal(await page.getByRole("dialog").count(), 0); assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Zoom in"); // Undo the alt edit and the complete drop as separate operations. await page.locator(".cm-line").filter({ hasText: "![Edited alt]" }).click(); await page.keyboard.press("Control+z"); await page.keyboard.press("Control+z"); assert.equal(await source(), original); await page.keyboard.press("Control+y"); assert.equal(await source(), inserted); // Type and move the cursor during a slow import; the drop follows its original position. await page.evaluate(() => { window.__TEST__.delay = true; }); await drop(); await page.waitForFunction(() => !!window.__TEST__.resume); await page.evaluate(() => { const view = window.__CM__; view.dispatch({ changes: { from: 0, insert: "Typed while saving.\n\n" }, selection: { anchor: view.state.doc.length } }); window.__TEST__.delay = false; window.__TEST__.resume(); window.__TEST__.resume = null; }); await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 3); assert.ok((await source()).startsWith("Typed while saving.\n\n![]")); // Typed local image paths load without changing views, including wiki syntax. await page.evaluate(path => { window.__TEST__.files.set("attachments/typed.svg", [...window.__TEST__.files].find(([key]) => key.startsWith("attachments/"))[1]); const view = window.__CM__; view.dispatch({ changes: { from: view.state.doc.length, insert: `\n![[${path}|Wiki image]]\n` }, selection: { anchor: view.state.doc.length } }); }, "../attachments/typed.svg"); await page.locator('img[alt="Wiki image"]').waitFor(); await save(); await page.getByRole("button", { name: "Read", exact: true }).click(); await page.locator(".md-page .md-image-frame").first().hover(); await page.locator(".md-page").getByRole("button", { name: "Zoom in", exact: true }).first().click(); await page.getByRole("dialog", { name: "Image zoom" }).waitFor(); await page.keyboard.press("Escape"); // Source mode uses the same drop flow; the batch is one undo step. await page.getByRole("button", { name: "Edit", exact: true }).click(); await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click(); await page.locator(".monaco-editor textarea").waitFor(); await page.evaluate(async () => { const { monaco } = await import("/src/lib/editor/monacoEnv.ts"); window.__MONACO__ = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected); }); const sourceBefore = await page.evaluate(() => window.__MONACO__.getValue()); await drop(2, ".monaco-editor .view-lines"); await page.waitForFunction(() => (window.__MONACO__.getValue().match(/!\[\]/g) || []).length === 5); await page.keyboard.press("Control+z"); assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), sourceBefore); await page.keyboard.press("Control+y"); assert.equal((await save()).match(/!\[\]/g).length, 5); // A failed write leaves source unchanged and surfaces an error. const beforeFailure = await page.evaluate(() => window.__MONACO__.getValue()); await page.evaluate(() => { window.__TEST__.failWrite = true; }); await drop(1, ".monaco-editor .view-lines"); await page.getByText("Image write failed", { exact: true }).waitFor(); assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), beforeFailure); await page.evaluate(() => { window.__TEST__.failWrite = false; }); // File drops over a rendered widget are handled by the editor's capture listener. await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click(); await page.locator(".cm-content").waitFor(); await page.evaluate(async () => { const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js"); window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content")); }); await drop(1, ".md-image-frame img >> nth=0"); await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 6); // Switching tabs while a write is pending cannot insert into the new document. await page.evaluate(() => { window.__TEST__.delay = true; }); await drop(); await page.waitForFunction(() => !!window.__TEST__.resume); await openNote("second.md"); await page.evaluate(() => { window.__TEST__.delay = false; window.__TEST__.resume(); }); await page.waitForTimeout(100); assert.ok(!(await page.locator(".cm-content").textContent()).includes("attachments/")); // Clipboard images are inserted and remain a single undo operation too. await page.locator(".cm-content").evaluate(element => { const data = new DataTransfer(); data.items.add(new File([''], "pasted.svg", { type: "image/svg+xml" })); element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data })); }); await page.waitForFunction(() => document.querySelector(".md-image-frame img")); await page.keyboard.press("Control+s"); await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg")); assert.deepEqual(errors, []); console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode and undo passed."); } catch (error) { await page.screenshot({ path: ".audit/images-failure.png" }); console.error(errors); throw error; } finally { await browser.close(); }