import assert from "node:assert/strict"; import { spawn, execFileSync, type ChildProcess } from "node:child_process"; import { existsSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import net from "node:net"; import test from "node:test"; /** * Behaviour check for the chat bar's "More" menu (issue #1862): the button * must open its popover on screen, the tooltip must keep its accessible name, * and the menu items must run. Rendered behavior needs a real browser, so this * drives the dev server in headless Chrome over CDP and mocks only the HTTP * API inside the page. It skips when no Chrome binary is installed. */ const uiDir = fileURLToPath(new URL("..", import.meta.url)); // The page refuses to paint the chat dock until /api/auth/status answers with // a signed-in user, and the composer palette reads the session list, so the // mock answers just those and lets everything else fall through to empty JSON. const PAGE_MOCK = `(() => { const realFetch = window.fetch.bind(window); window.__archieSent = []; window.fetch = (input, init) => { const url = typeof input === "string" ? input : input.url; const json = (body, type = "application/json") => Promise.resolve(new Response(typeof body === "string" ? body : JSON.stringify(body), { status: 200, headers: { "Content-Type": type } })); if (url.includes("/api/chat/")) window.__archieSent.push((init?.method || "GET") + " " + url.replace(location.origin, "") + (init?.body ? " " + init.body : "")); if (url.includes("/api/auth/status")) return json({ setup_required: false, user: { id: "u1", display_name: "Operator", kind: "operator" }, oidc: false, public_url: location.origin + "/", instance: "archie" }); if (url.includes("/api/chat/sessions")) return json({ active_model: "test-model", sessions: [{ session_id: "s1", title: "Test session", created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z" }] }); if (url.includes("/turns")) return json([]); if (url.includes("/health")) return json({ status: "ok" }); if (url.includes("/api/")) return json({}); return realFetch(input, init); }; window.EventSource = class { close() {} addEventListener() {} removeEventListener() {} }; })();`; function freePort(): Promise { return new Promise((resolve, reject) => { const server = net.createServer(); server.unref(); server.on("error", reject); server.listen(0, "127.0.0.1", () => { const { port } = server.address() as net.AddressInfo; server.close(() => resolve(port)); }); }); } function findChrome(): string | null { const candidates = [ process.env.CHROME_BIN, "google-chrome", "google-chrome-stable", "chromium", "chromium-browser", ].filter((c): c is string => !!c); for (const candidate of candidates) { if (candidate.includes("/")) { if (existsSync(candidate)) return candidate; continue; } try { const found = execFileSync("which", [candidate], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim(); if (found) return found; } catch { // not on PATH } } return null; } interface Cdp { send(method: string, params?: Record): Promise; evaluate(expression: string): Promise; close(): void; } async function connectChrome(debugPort: number): Promise { let target: any; for (let attempt = 0; attempt < 60 && !target; attempt++) { try { const list = await (await fetch(`http://127.0.0.1:${debugPort}/json/list`)).json(); target = (list as any[]).find((t) => t.type === "page"); } catch { // devtools not up yet } if (!target) await new Promise((r) => setTimeout(r, 250)); } if (!target) throw new Error("chrome devtools endpoint never came up"); const ws = new WebSocket(target.webSocketDebuggerUrl); await new Promise((resolve, reject) => { ws.onopen = () => resolve(); ws.onerror = () => reject(new Error("chrome websocket failed")); }); let nextId = 0; const pending = new Map void; reject: (e: Error) => void }>(); ws.onmessage = (event) => { const message = JSON.parse(String(event.data)); if (message.id && pending.has(message.id)) { const { resolve, reject } = pending.get(message.id)!; pending.delete(message.id); if (message.error) reject(new Error(JSON.stringify(message.error))); else resolve(message.result); } }; const send = (method: string, params: Record = {}) => new Promise((resolve, reject) => { const id = ++nextId; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params })); }); return { send, evaluate: async (expression) => { const result = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }); if (result.exceptionDetails) throw new Error("page error: " + JSON.stringify(result.exceptionDetails).slice(0, 500)); return result.result.value; }, close: () => ws.close(), }; } async function startVite(): Promise<{ port: number; child: ChildProcess }> { const viteBin = join(uiDir, "node_modules", "vite", "bin", "vite.js"); if (!existsSync(viteBin)) throw new Error("ui dependencies are not installed (run pnpm install)"); let lastError = ""; for (let attempt = 0; attempt < 5; attempt++) { const port = await freePort(); const child = spawn(process.execPath, [viteBin, "--port", String(port), "--strictPort", "--host", "127.0.0.1"], { cwd: uiDir, stdio: ["ignore", "pipe", "pipe"], }); child.stderr?.on("data", (chunk) => { lastError += chunk; }); for (let poll = 0; poll < 60; poll++) { if (child.exitCode !== null) break; try { const response = await fetch(`http://127.0.0.1:${port}/`); if (response.ok) return { port, child }; } catch { // not listening yet } await new Promise((r) => setTimeout(r, 250)); } child.kill("SIGKILL"); } throw new Error("vite dev server did not start: " + lastError.slice(0, 400)); } test("chat More menu opens on screen and its items run", { timeout: 90000 }, async (t) => { const chrome = findChrome(); if (!chrome) { t.skip("no Chrome/Chromium binary available for the browser check"); return; } const { port: vitePort, child: vite } = await startVite(); const debugPort = await freePort(); const profile = join(tmpdir(), `archie-more-menu-test-${process.pid}-${Date.now()}`); const chromeChild = spawn(chrome, [ "--headless=new", `--remote-debugging-port=${debugPort}`, "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage", `--user-data-dir=${profile}`, "--window-size=1280,900", "about:blank", ], { stdio: "ignore" }); try { const cdp = await connectChrome(debugPort); try { await cdp.send("Page.enable"); await cdp.send("Runtime.enable"); await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: PAGE_MOCK }); await cdp.send("Emulation.setDeviceMetricsOverride", { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false }); await cdp.send("Page.navigate", { url: `http://127.0.0.1:${vitePort}/` }); // Wait for the app shell and the collapsed dock, then expand it. await cdp.evaluate(`(async () => { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); for (let i = 0; i < 60; i++) { if (document.querySelector('button[aria-label="Show conversation"]')) { document.querySelector('button[aria-label="Show conversation"]').click(); for (let j = 0; j < 40 && !document.querySelector('button[aria-label="More"]'); j++) await sleep(250); return !!document.querySelector('button[aria-label="More"]'); } await sleep(250); } return false; })()`).then((expanded: unknown) => assert.equal(expanded, true, "the chat dock expanded and rendered the More button")); // Pick the open conversation first, so the menu's actions have a // session to act on. await cdp.evaluate(`(() => { document.querySelector('button[aria-label="Conversations"]').click(); })()`); await new Promise((r) => setTimeout(r, 800)); await cdp.evaluate(`(() => { const item = [...document.querySelectorAll('nav[aria-label="Conversations"] button')].find((el) => el.innerText.includes("Test session")); if (item) item.click(); })()`); await cdp.evaluate(`(async () => { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const read = () => window.__archieSent.includes("GET /api/chat/sessions/s1/turns"); for (let i = 0; i < 40 && !read(); i++) await sleep(250); return read(); })()`).then((selected: unknown) => assert.equal(selected, true, "selecting the conversation read its turns")); // Hover the More button: the tooltip keeps its accessible name. const moreBox = await cdp.evaluate(`(() => { const r = document.querySelector('button[aria-label="More"]').getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; })()`); await cdp.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: moreBox.x, y: moreBox.y }); await new Promise((r) => setTimeout(r, 1200)); const tooltip = await cdp.evaluate(`(() => { const tip = document.querySelector('[data-slot="tooltip-content"]'); return tip && (tip.offsetWidth || tip.offsetHeight) ? tip.innerText.trim() : null; })()`); assert.ok(tooltip && tooltip.includes("More"), `hovering the More button shows the More tooltip, got ${JSON.stringify(tooltip)}`); // Click it: the popover must open inside the viewport. await cdp.send("Input.dispatchMouseEvent", { type: "mousePressed", x: moreBox.x, y: moreBox.y, button: "left", clickCount: 1 }); await cdp.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: moreBox.x, y: moreBox.y, button: "left", clickCount: 1 }); const opened = await cdp.evaluate(`(async () => { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); for (let i = 0; i < 40 && !document.querySelector('[data-slot="popover-content"]'); i++) await sleep(250); const pop = document.querySelector('[data-slot="popover-content"]'); if (!pop) return { exists: false }; const r = pop.getBoundingClientRect(); return { exists: true, inViewport: r.x >= 0 && r.y >= 0 && r.right <= innerWidth && r.bottom <= innerHeight, rect: { x: r.x, y: r.y, right: r.right, bottom: r.bottom }, text: pop.innerText.replace(/\\s+/g, " ").trim(), ariaExpanded: document.querySelector('button[aria-label="More"]').getAttribute("aria-expanded"), }; })()`); assert.equal(opened.exists, true, "clicking More opens the popover"); assert.equal(opened.ariaExpanded, "true"); assert.equal(opened.inViewport, true, `the menu must render on screen, got ${JSON.stringify(opened.rect)}`); for (const item of ["Rename", "Copy as Markdown", "Delete"]) { assert.ok(opened.text.includes(item), `the menu lists ${item}`); } // A server that lists no slash commands gets none of their buttons. for (const item of ["Retry", "Undo", "Branch", "Preview compression"]) { assert.ok(!opened.text.includes(item), `the menu hides ${item}`); } // Run Copy as Markdown from the menu: the menu closes. await cdp.evaluate(`(() => { const copy = [...document.querySelectorAll('[data-slot="popover-content"] button')].find((el) => el.innerText.includes("Copy as Markdown")); if (copy) copy.click(); })()`); const afterCopy = await cdp.evaluate(`(async () => { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); for (let i = 0; i < 40; i++) { const pop = document.querySelector('[data-slot="popover-content"]'); if (!pop || pop.getAttribute("data-state") === "closed") break; await sleep(250); } return { popoverClosed: !document.querySelector('[data-slot="popover-content"]') || document.querySelector('[data-slot="popover-content"]').getAttribute("data-state") === "closed", ariaExpanded: document.querySelector('button[aria-label="More"]').getAttribute("aria-expanded"), dockStillThere: !!document.querySelector('button[aria-label="More"]'), }; })()`); assert.equal(afterCopy.popoverClosed, true, "running an action closes the menu"); assert.equal(afterCopy.ariaExpanded, "false"); assert.equal(afterCopy.dockStillThere, true); // Reopen and use Rename: the labelled dialog opens from the menu. await cdp.evaluate(`(() => { document.querySelector('button[aria-label="More"]').click(); })()`); await new Promise((r) => setTimeout(r, 1000)); await cdp.evaluate(`(() => { const rename = [...document.querySelectorAll('[data-slot="popover-content"] button')].find((el) => el.innerText.includes("Rename")); if (rename) rename.click(); })()`); await new Promise((r) => setTimeout(r, 1000)); const dialog = await cdp.evaluate(`(() => { const d = [...document.querySelectorAll('[role="dialog"]')].find((el) => !el.hasAttribute("data-slot") || el.getAttribute("data-slot") !== "popover-content"); return d ? d.innerText.replace(/\\s+/g, " ").trim() : null; })()`); assert.ok(dialog && dialog.includes("Session title"), `Rename opens the session-title dialog, got ${JSON.stringify(dialog)}`); // Submit a title: it is saved through the chat API. await cdp.evaluate(`(() => { const input = document.querySelector('[role="dialog"] input'); input.value = "Renamed"; input.dispatchEvent(new Event("input", { bubbles: true })); })()`); await new Promise((r) => setTimeout(r, 300)); await cdp.evaluate(`(() => { const ok = [...document.querySelectorAll('[role="dialog"] button')].find((el) => el.innerText.trim() === "OK"); if (ok) ok.click(); })()`); await cdp.evaluate(`(async () => { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const sent = () => window.__archieSent.includes('PATCH /api/chat/sessions/s1 {"title":"Renamed"}'); for (let i = 0; i < 40 && !sent(); i++) await sleep(250); return sent(); })()`).then((sent: unknown) => assert.equal(sent, true, "Rename saves the title through the chat API")); // Reopen the menu, then Escape: it dismisses the menu but leaves the // conversation open. await new Promise((r) => setTimeout(r, 800)); await cdp.evaluate(`(() => { document.querySelector('button[aria-label="More"]').click(); })()`); await new Promise((r) => setTimeout(r, 1000)); await cdp.send("Input.dispatchKeyEvent", { type: "rawKeyDown", key: "Escape", windowsVirtualKeyCode: 27 }); await cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key: "Escape", windowsVirtualKeyCode: 27 }); await new Promise((r) => setTimeout(r, 800)); const afterEscape = await cdp.evaluate(`(async () => { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); for (let i = 0; i < 40; i++) { const pop = document.querySelector('[data-slot="popover-content"]'); if (!pop || pop.getAttribute("data-state") === "closed") break; await sleep(250); } return { popoverClosed: !document.querySelector('[data-slot="popover-content"]') || document.querySelector('[data-slot="popover-content"]').getAttribute("data-state") === "closed", dockStillThere: !!document.querySelector('button[aria-label="More"]'), ariaExpanded: document.querySelector('button[aria-label="More"]').getAttribute("aria-expanded"), }; })()`); assert.equal(afterEscape.popoverClosed, true, "Escape closes the menu"); assert.equal(afterEscape.ariaExpanded, "false"); assert.equal(afterEscape.dockStillThere, true, "Escape leaves the conversation open"); } finally { cdp.close(); } } finally { chromeChild.kill("SIGKILL"); vite.kill("SIGKILL"); } });