#!/usr/bin/env node /** * pi2 web console — browser (Playwright) end-to-end driver. * * Implements the browser layer of `docs/e2e.md`: * B1–B14 functional scenarios against the daemon-served production bundle * C1–C4 responsive / visual / i18n / console-error scenarios * * Design rules (see docs/e2e.md §2–§6): * - Every scenario is isolated: a fresh browser context, its own storage state, * its own try/catch, a screenshot on failure, exit-code tracking. * - The browser is driven exactly like a user: no product code is patched, no * `window` test hooks, no mocked API responses except the one negative-path * case in B4 (workspaces API error + retry), which is a deliberate fault * injection requested by the plan. * - Product bugs are reported as FAILURES with the observed DOM/network * evidence, never worked around. Only the cases the plan explicitly allows to * skip (camera-only pairing, missing attention dialog) become SKIP. * * Usage: started by `scripts/e2e/run-ui.sh` (which owns the daemon, the CLI * token, the pairing code and the temp root). Standalone: * * E2E_BASE=... E2E_CLI_TOKEN=... E2E_DEVICE_TOKEN=... E2E_PORT=... \ * E2E_ROOT=... node scripts/e2e/ui-e2e.mjs * * Artifacts: $E2E_ROOT/screens/*.png and $E2E_ROOT/report/ui-e2e.{json,md} * (plus a copy of the markdown at /tmp/pi2-e2e-recon/e2e-ui-run.md). * * Exit code: 0 when no scenario FAILs (SKIP is tolerated), 1 otherwise. */ import { createRequire } from "node:module"; import fs from "node:fs"; import path from "node:path"; /* ------------------------------------------------------------------ */ /* environment */ /* ------------------------------------------------------------------ */ const ENV = process.env; const BASE = (ENV.E2E_BASE || "").replace(/\/+$/, ""); const CLI_TOKEN = ENV.E2E_CLI_TOKEN || ""; const DEVICE_TOKEN = ENV.E2E_DEVICE_TOKEN || ""; const PAIR_CODE = ENV.E2E_PAIR_CODE || ""; const ROOT = ENV.E2E_ROOT || "/tmp/pi2-e2e-ui-manual"; const SCREENS = path.join(ROOT, "screens"); const REPORT_DIR = path.join(ROOT, "report"); const WS_ROOTS = ENV.PI2_WORKSPACE_ROOTS || path.join(ROOT, "workspaces"); const EXTRA_REPORT = ENV.E2E_REPORT_COPY || "/tmp/pi2-e2e-recon/e2e-ui-run2.md"; const CHROME = ENV.PI2_E2E_CHROME || "/usr/bin/google-chrome-stable"; if (!BASE || !CLI_TOKEN) { console.error("ui-e2e: E2E_BASE and E2E_CLI_TOKEN are required (run through scripts/e2e/run-ui.sh)"); process.exit(2); } const PORT = String(ENV.E2E_PORT || new URL(BASE).port || ""); const ORIGIN = new URL(BASE).origin; const BASE_HOST = new URL(BASE).hostname; fs.mkdirSync(SCREENS, { recursive: true }); fs.mkdirSync(REPORT_DIR, { recursive: true }); /* ------------------------------------------------------------------ */ /* playwright resolution (not a daemon dependency) */ /* ------------------------------------------------------------------ */ const require_ = createRequire(import.meta.url); function loadPlaywright() { const tried = []; const attempt = (spec) => { tried.push(spec); try { const mod = require_(spec); if (mod && typeof mod.chromium?.launch === "function") return mod; } catch { /* keep trying */ } return null; }; if (ENV.PI2_E2E_PLAYWRIGHT_MODULE) { const fromEnv = attempt(ENV.PI2_E2E_PLAYWRIGHT_MODULE); if (fromEnv) return { pw: fromEnv, spec: ENV.PI2_E2E_PLAYWRIGHT_MODULE }; } const fromRequire = attempt("playwright"); if (fromRequire) return { pw: fromRequire, spec: "playwright" }; // mise installs npm-global tools under /installs/npm-playwright/*/v11/*/node_modules const roots = [ "/home/yuez/.local/share/mise/installs/npm-playwright", path.join(process.env.HOME || "/root", ".local/share/mise/installs/npm-playwright"), ]; const globs = []; for (const root of roots) { let versions = []; try { versions = fs.readdirSync(root); } catch { continue; } for (const version of versions) { const v11 = path.join(root, version, "v11"); let hashes = []; try { hashes = fs.readdirSync(v11); } catch { continue; } for (const hash of hashes) globs.push(path.join(v11, hash, "node_modules", "playwright")); } } for (const candidate of globs) { if (!fs.existsSync(candidate)) continue; const mod = attempt(candidate); if (mod) return { pw: mod, spec: candidate }; } throw new Error(`cannot load playwright (tried: ${tried.join(", ")})`); } const { pw, spec: playwrightSpec } = loadPlaywright(); const CHROME_PATH = fs.existsSync(CHROME) ? CHROME : undefined; /* ------------------------------------------------------------------ */ /* small utilities */ /* ------------------------------------------------------------------ */ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); function escRe(text) { return String(text).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function short(value, limit = 400) { const text = typeof value === "string" ? value : JSON.stringify(value); if (!text) return ""; return text.length > limit ? `${text.slice(0, limit)}…` : text; } /** Poll a predicate until it returns something truthy (or time out → null). */ async function waitFor(fn, timeoutMs, intervalMs = 100) { const deadline = Date.now() + timeoutMs; for (;;) { const value = await fn().catch(() => null); if (value) return value; if (Date.now() > deadline) return null; await sleep(intervalMs); } } class Failure extends Error { constructor(check) { super(`${check.name}${check.detail ? ` — ${short(check.detail.observed ?? check.detail, 200)}` : ""}`); this.name = "Failure"; this.check = check; } } class SkipSignal extends Error { constructor(reason) { super(reason); this.name = "SkipSignal"; } } /* ------------------------------------------------------------------ */ /* daemon API (harness-side seeding, CLI token) */ /* ------------------------------------------------------------------ */ async function apiRaw(method, apiPath, { token = CLI_TOKEN, body } = {}) { const headers = { Accept: "application/json" }; if (token) headers.Authorization = `Bearer ${String(token).replace(/^Bearer\s+/i, "")}`; if (body !== undefined) headers["Content-Type"] = "application/json"; const response = await fetch(`${BASE}${apiPath}`, { method, headers, ...(body !== undefined ? { body: typeof body === "string" ? body : JSON.stringify(body) } : {}), }); const text = await response.text(); let json; try { json = text ? JSON.parse(text) : null; } catch { json = null; } return { status: response.status, ok: response.ok, json, text }; } async function api(method, apiPath, options) { const result = await apiRaw(method, apiPath, options); if (!result.ok) throw new Error(`API ${method} ${apiPath} → ${result.status} ${short(result.text, 200)}`); return result.json; } async function cmd(method, params, extra = {}) { const result = await apiRaw("POST", "/api/v1/cmd", { body: { method, params: params ?? {}, ...extra } }); return result; } function deepFindSessionId(value) { if (!value || typeof value !== "object") return undefined; if (typeof value.sessionId === "string" && value.sessionId) return value.sessionId; for (const key of Object.keys(value)) { const found = deepFindSessionId(value[key]); if (found) return found; } return undefined; } async function addWorkspace(cwd, alias) { const body = { cwd, trust: true, ...(alias ? { alias } : {}) }; const result = await api("POST", "/api/v1/cmd", { body: { method: "workspace.add", params: body } }); const workspaceId = result?.workspace?.workspaceId ?? deepFindWorkspaceId(result) ?? undefined; if (!workspaceId) throw new Error(`workspace.add returned no id: ${short(result)}`); return workspaceId; } function deepFindWorkspaceId(value) { if (!value || typeof value !== "object") return undefined; if (typeof value.workspaceId === "string" && value.workspaceId) return value.workspaceId; for (const key of Object.keys(value)) { const found = deepFindWorkspaceId(value[key]); if (found) return found; } return undefined; } async function ensureInstance(workspaceId, timeoutMs = 20000) { await cmd("instance.ensure", { workspaceId }); const ready = await waitFor(async () => { const list = await api("GET", "/api/v1/workspaces"); const row = (Array.isArray(list) ? list : list.workspaces).find((item) => item.workspaceId === workspaceId); if (!row) return null; return row.instance?.status === "ready" ? row : null; }, timeoutMs, 150); if (!ready) throw new Error(`instance for ${workspaceId} never became ready`); return ready; } async function listWorkspaces() { const list = await api("GET", "/api/v1/workspaces"); return Array.isArray(list) ? list : (list.workspaces ?? []); } async function createSession(workspaceId) { const result = await cmd("session.create", { workspaceId }); if (result.status !== 202 && result.status !== 200) { throw new Error(`session.create failed: ${result.status} ${short(result.text, 200)}`); } const sessionId = deepFindSessionId(result.json); if (!sessionId) throw new Error(`session.create returned no sessionId: ${short(result.text, 200)}`); return sessionId; } async function listSessions(workspaceId) { const body = await api("GET", `/api/v1/workspaces/${encodeURIComponent(workspaceId)}/sessions`); const rows = body?.sessions ?? body?.result?.sessions ?? (Array.isArray(body) ? body : []); return Array.isArray(rows) ? rows : []; } async function listDevices() { const body = await api("GET", "/api/v1/devices"); if (Array.isArray(body)) return body; return body?.devices ?? []; } /* ------------------------------------------------------------------ */ /* console-error allowlist */ /* ------------------------------------------------------------------ */ /** Known-benign browser messages (network/WS noise, devtools chatter). */ const CONSOLE_ALLOWLIST = [ { id: "http-error-log", re: /^Failed to load resource/i }, { id: "net-disconnected", re: /net::ERR_(INTERNET_DISCONNECTED|CONNECTION_REFUSED|CONNECTION_RESET|NETWORK_CHANGED|NAME_NOT_RESOLVED|CONNECTION_CLOSED|EMPTY_RESPONSE)/i }, { id: "websocket", re: /WebSocket (connection|is closed|closed)/i }, { id: "ws-error-event", re: /^(Error: )?WebSocket/i }, { id: "react-devtools", re: /Download the React DevTools/i }, { id: "favicon", re: /favicon\.ico/i }, ]; function classifyConsole(text) { for (const entry of CONSOLE_ALLOWLIST) { if (entry.re.test(text)) return entry.id; } return null; } /** Every console error / pageerror seen by any scenario (for C4). */ const GLOBAL_ERRORS = []; /* ------------------------------------------------------------------ */ /* scenario context */ /* ------------------------------------------------------------------ */ class Ctx { constructor(def) { this.id = def.id; this.title = def.title; this.checks = []; this.failures = []; this.notes = []; this.logs = []; this.consoleErrors = []; this.consoleWarnings = []; this.pageErrors = []; this.httpErrors = []; this.cmdRequests = []; this.cmdResponses = []; /** Every `/api/v1/**` response: `{method, path, status}`. */ this.apiCalls = []; /** Client-side navigations (pathname + search) in order. */ this.navigations = []; this.wsFrames = []; this.screenshots = []; this.contexts = []; this.offlineWindow = false; this.skipped = null; this.durationMs = 0; this.status = "PASS"; } log(message) { this.logs.push(message); if (ENV.E2E_VERBOSE === "1") console.error(` ${message}`); } note(message) { this.notes.push(message); this.log(message); } /** Hard assertion: records and throws on failure (rest of the scenario is skipped). */ check(name, ok, detail) { const record = { name, ok: Boolean(ok), detail: detail ?? null }; this.checks.push(record); if (!record.ok) { this.failures.push(record); throw new Failure(record); } return record; } /** Soft assertion: records a failure but lets the scenario continue. */ softCheck(name, ok, detail) { const record = { name, ok: Boolean(ok), detail: detail ?? null }; this.checks.push(record); if (!record.ok) this.failures.push(record); return record; } checkValue(name, actual, expected) { return this.check(name, JSON.stringify(actual) === JSON.stringify(expected), { expected, observed: actual }); } skip(reason) { this.skipped = reason; this.log(`SKIP: ${reason}`); throw new SkipSignal(reason); } async shot(page, name, options = {}) { if (!page || page.isClosed()) return null; const file = path.join(SCREENS, `${name}.png`); try { await page.screenshot({ path: file, fullPage: options.fullPage === true, timeout: 15000 }); this.screenshots.push(file); const size = fs.statSync(file).size; return { file, size }; } catch (error) { this.log(`screenshot failed (${name}): ${error.message}`); return null; } } storageState(kind, localExtra = {}) { if (kind === "unpaired") { const local = Object.entries(localExtra).map(([name, value]) => ({ name, value: String(value) })); return { cookies: [], origins: local.length ? [{ origin: ORIGIN, localStorage: local }] : [] }; } const local = [ { name: "pi2-connection", value: "paired" }, { name: "pi2-endpoint", value: BASE }, // Raw token (web/src/lib/api.ts strips an optional `Bearer ` prefix). { name: "pi2-device-token", value: DEVICE_TOKEN }, { name: "pi2-device-scopes", value: JSON.stringify(["read", "steer", "apply"]) }, { name: "pi2-device", value: "Playwright" }, { name: "pi2-connected-at", value: String(Date.now()) }, ...Object.entries(localExtra).map(([name, value]) => ({ name, value: String(value) })), ]; return { cookies: [], origins: [{ origin: ORIGIN, localStorage: local }] }; } /** * Fresh context + page. `kind` selects the seeded storage ("paired" | * "unpaired"); `language` is pinned before boot (mandatory: the default * follows navigator.language). */ async openPage(kind, options = {}) { const context = await browser.newContext({ viewport: options.viewport ?? { width: 1440, height: 900 }, storageState: this.storageState(kind, options.storageLocal ?? {}), locale: options.locale ?? "en-US", colorScheme: options.colorScheme ?? "light", baseURL: BASE, ignoreHTTPSErrors: true, }); this.contexts.push(context); await context.addInitScript((lang) => { try { localStorage.setItem("pi2-lang", lang); } catch { /* private mode */ } // Harness instrumentation: remember every `pi2-*` storage write so a // scenario can prove what the app persisted (and in which order) even // when a later step clears it again. try { const writes = []; window.__pi2Writes = writes; const setItem = Storage.prototype.setItem; const removeItem = Storage.prototype.removeItem; Storage.prototype.setItem = function (key, value) { if (String(key).startsWith("pi2-")) { writes.push({ op: "set", key: String(key), value: String(value), at: Date.now(), href: location.pathname }); } return setItem.call(this, key, value); }; Storage.prototype.removeItem = function (key) { if (String(key).startsWith("pi2-")) { writes.push({ op: "remove", key: String(key), at: Date.now(), href: location.pathname }); } return removeItem.call(this, key); }; } catch { /* ignore */ } }, options.language ?? "en"); const page = await context.newPage(); page.setDefaultTimeout(options.timeout ?? 15000); page.setDefaultNavigationTimeout(30000); this.instrument(page); return { context, page }; } instrument(page) { const ctx = this; page.on("console", (message) => { const type = message.type(); if (type !== "error" && type !== "warning") return; const record = { scenario: ctx.id, type, text: message.text(), location: message.location?.() ?? null, page: (() => { try { return page.url(); } catch { return ""; } })(), allowlist: classifyConsole(message.text()), offline: ctx.offlineWindow, }; if (type === "error") { ctx.consoleErrors.push(record); GLOBAL_ERRORS.push(record); } else { ctx.consoleWarnings.push(record); } }); page.on("pageerror", (error) => { const record = { scenario: ctx.id, message: error.message, stack: short(error.stack, 700) }; ctx.pageErrors.push(record); GLOBAL_ERRORS.push({ ...record, type: "pageerror", allowlist: null, offline: ctx.offlineWindow }); }); page.on("framenavigated", (frame) => { try { if (frame !== page.mainFrame()) return; const url = new URL(frame.url()); ctx.navigations.push(`${url.pathname}${url.search}`); } catch { /* ignore */ } }); page.on("request", (request) => { try { const url = request.url(); if (url.includes("/api/v1/cmd") && request.method() === "POST") { let body = null; try { body = JSON.parse(request.postData() || "null"); } catch { body = request.postData(); } ctx.cmdRequests.push({ url, method: body?.method ?? null, sessionId: body?.sessionId ?? null, params: body?.params ?? null, at: Date.now() }); } } catch { /* ignore */ } }); page.on("response", (response) => { const url = response.url(); const status = response.status(); if (!url.includes("/api/v1/")) return; ctx.apiCalls.push({ method: response.request().method(), path: url.replace(BASE, "").split("?")[0], status, at: Date.now(), }); const record = { url: url.replace(BASE, ""), status, at: Date.now() }; if (status >= 400) ctx.httpErrors.push(record); if (url.includes("/api/v1/cmd")) { response .json() .then((body) => { ctx.cmdResponses.push({ ...record, body }); }) .catch(() => { ctx.cmdResponses.push({ ...record, body: null }); }); } }); page.on("websocket", (socket) => { socket.on("framereceived", (frame) => { try { const raw = typeof frame.payload === "string" ? frame.payload : frame.payload?.toString?.("utf8"); if (!raw) return; const parsed = JSON.parse(raw); ctx.wsFrames.push(parsed); } catch { /* binary/other frame */ } }); }); } async closeAll() { for (const context of this.contexts) { try { await context.close(); } catch { /* already closed */ } } this.contexts = []; } /** `GET` the daemon through the page so the browser's device token is used. */ async pageFetch(page, apiPath) { return page.evaluate(async (target) => { const token = (localStorage.getItem("pi2-device-token") || "").replace(/^Bearer\s+/i, ""); const response = await fetch(target, { headers: token ? { Authorization: `Bearer ${token}` } : {} }); const text = await response.text(); return { status: response.status, text }; }, apiPath); } } /* ------------------------------------------------------------------ */ /* DOM helpers */ /* ------------------------------------------------------------------ */ const navItems = (page) => page.locator(".sidebar .nav-item, .rail .nav-item, .tabbar .nav-item"); const pageName = (page) => page.evaluate(() => document.body.dataset.page ?? ""); const streamText = (page) => page.locator('[role="log"][aria-label="Message stream"]'); async function dialogFor(page, title, timeout = 8000) { const byRole = page.getByRole("dialog", { name: new RegExp(escRe(title), "i") }); if (await waitFor(async () => (await byRole.count()) > 0, timeout, 100)) return byRole.first(); // Radix names the dialog after the whole title element (which also contains // the Close button), so fall back to a text match inside the modal shell. const byText = page.locator(".modal-content").filter({ hasText: title }); if (await waitFor(async () => (await byText.count()) > 0, 2000, 100)) return byText.first(); return null; } async function anyDialog(page) { const dialogs = page.getByRole("dialog"); const count = await dialogs.count(); return count > 0 ? dialogs.first() : null; } async function dismissDialogs(page) { for (let attempt = 0; attempt < 3; attempt += 1) { if ((await page.getByRole("dialog").count()) === 0) return; await page.keyboard.press("Escape"); await sleep(150); } } async function errorToasts(page) { return page.locator('[data-sonner-toast][data-type="error"]'); } /** Number of error toasts currently rendered (`Locator.count()` is async). */ async function errorToastCount(page) { return (await errorToasts(page)).count(); } async function toastTexts(page) { return page.evaluate(() => Array.from(document.querySelectorAll("[data-sonner-toast]")).map((node) => node.textContent?.trim() ?? ""), ); } async function waitToast(page, pattern, timeout = 6000) { return waitFor(async () => { const texts = await toastTexts(page); return texts.find((text) => pattern.test(text)) ?? null; }, timeout, 80); } async function bodyText(page) { return page.evaluate(() => document.body.innerText); } async function setText(page, selector, value) { const locator = page.locator(selector).first(); await locator.waitFor({ state: "visible", timeout: 15000 }); await locator.fill(value); return locator; } async function waitEnabled(page, selector, timeout = 30000) { const ok = await waitFor( async () => page.evaluate((target) => { const el = document.querySelector(target); if (!el) return false; return !el.disabled && el.getAttribute("aria-disabled") !== "true"; }, selector), timeout, 120, ); return Boolean(ok); } const COMPOSER_INPUT = '[data-testid="composer-input"]'; /** `article.msg[data-entry-id]` projections (id/role come from the product test ids). */ async function streamArticles(page) { return page.evaluate(() => Array.from(document.querySelectorAll("article.msg[data-entry-id]")).map((node) => ({ id: node.getAttribute("data-entry-id") ?? "", role: node.getAttribute("data-role") ?? "", text: Array.from(node.querySelectorAll(".msg__text")) .map((text) => (text.textContent ?? "").trim()) .filter(Boolean) .join("\n") .trim(), streaming: Boolean(node.querySelector(".msg__text.streaming")), })), ); } async function streamName(page) { const locator = page.locator(".stream-head .stream-name").first(); if ((await locator.count()) === 0) return ""; return (await locator.innerText()).trim(); } async function sessionStatusBadge(page) { const locator = page.locator(".stream-head .stream-status").first(); if ((await locator.count()) === 0) return ""; return (await locator.innerText()).trim(); } /** Composer facts from the product test ids (`composer-input|send|abort`). */ async function composerState(page) { return page.evaluate(() => { const input = document.querySelector('[data-testid="composer-input"]'); const send = document.querySelector('[data-testid="composer-send"]'); const abort = document.querySelector('[data-testid="composer-abort"]'); return { input: Boolean(input), enabled: Boolean(input && !input.disabled), send: send ? (send.textContent ?? "").trim() : null, sendEnabled: send ? !send.hasAttribute("disabled") : null, abort: Boolean(abort), }; }); } /** Abort wins while the run is busy (the send button stays visible next to it). */ async function composerSendLabel(page) { const state_ = await composerState(page); if (state_.abort) return "Abort"; return state_.send ?? ""; } /** `/chat/?workspace=`; ids may briefly be the `tmp-N` placeholder. */ function chatUrl(sessionId, workspaceId) { return `${BASE}/chat/${encodeURIComponent(sessionId)}?workspace=${encodeURIComponent(workspaceId)}`; } /** Wait until the address bar carries a real (non `tmp-`) session id. */ async function waitRealSessionId(page, timeout = 10000) { return waitFor(async () => { const url = new URL(page.url()); const match = /^\/chat\/([^/]+)$/.exec(url.pathname); if (!match) return null; const id = decodeURIComponent(match[1]); if (id.startsWith("tmp-")) return null; return { sessionId: id, workspace: url.searchParams.get("workspace"), href: url.href }; }, timeout, 150); } /** Session ids currently rendered in the tree (`data-session-id`). */ async function treeSessionIds(page) { return page .locator(".tree-pane .tree-row[data-session-id]") .evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-session-id"))); } async function openChat(page, sessionId, workspaceId) { await page.goto(chatUrl(sessionId, workspaceId), { waitUntil: "domcontentloaded" }); await streamText(page).waitFor({ state: "visible", timeout: 30000 }); return waitEnabled(page, COMPOSER_INPUT, 30000); } function entryIdsFromFrames(frames, sessionId) { const snapshots = []; const appended = []; for (const frame of frames) { const type = frame?.type; const payload = frame?.payload; if (type === "snapshot") { const state = payload?.state ?? payload; if (payload?.sessionId !== sessionId && frame?.sessionId !== sessionId) continue; const entries = Array.isArray(state?.entries) ? state.entries : []; snapshots.push(entries.map((entry) => entry.id)); } else if (type === "event") { const event = payload?.event ?? payload; if (!event || typeof event.type !== "string") continue; if (frame?.sessionId && frame.sessionId !== sessionId) continue; if (event.type === "entry_appended" && event.entry?.id) appended.push(event.entry.id); if (event.type === "entry_updated" && event.entry?.id) appended.push(event.entry.id); } } return { snapshots, appended }; } /** Entries of the last snapshot frame for `sessionId` (`{id, role, text}`). */ function snapshotEntries(frames, sessionId) { let latest = null; for (const frame of frames) { const payload = frame?.payload; if (frame?.type !== "snapshot") continue; const state = payload?.state ?? payload; const id = payload?.sessionId ?? frame?.sessionId ?? state?.sessionId; if (sessionId && id && id !== sessionId) continue; const entries = Array.isArray(state?.entries) ? state.entries : []; latest = entries.map((entry) => ({ id: entry.id, role: entry.role, text: (entry.blocks ?? []) .filter((block) => block.type === "text") .map((block) => String(block.text ?? "")) .join("\n") .trim(), })); } return latest; } /** `{type:"error"}` frames the socket received (auth failures show up here). */ function socketErrors(frames) { return frames .filter((frame) => frame?.type === "error") .map((frame) => ({ code: frame?.payload?.code ?? null, message: frame?.payload?.message ?? null })); } function duplicates(list) { const seen = new Set(); const dupes = new Set(); for (const item of list) { if (seen.has(item)) dupes.add(item); seen.add(item); } return [...dupes]; } /* ------------------------------------------------------------------ */ /* scenario registry */ /* ------------------------------------------------------------------ */ const scenarios = []; const state = {}; // cross-scenario fixtures (seeded workspaces, reusable sessions) function scenario(id, title, fn, options = {}) { scenarios.push({ id, title, fn, budgetMs: options.budgetMs ?? 300000 }); } /* ------------------------------------------------------------------ */ /* B1 — unpaired guard */ /* ------------------------------------------------------------------ */ scenario("B1", "Unpaired guard: /workspaces, /status, /chat redirect to /connect; safeNext rejects external next", async (ctx) => { const { page } = await ctx.openPage("unpaired"); const guardCase = async (target, expectedNext) => { await page.goto(`${BASE}${target}`, { waitUntil: "domcontentloaded" }); const landed = await waitFor(async () => { const url = new URL(page.url()); return url.pathname === "/connect" ? url : null; }, 10000); ctx.check(`${target} redirects to /connect`, Boolean(landed), { expected: `${BASE}/connect?next=${encodeURIComponent(expectedNext)}`, observed: page.url(), }); ctx.check(`${target}: next=${expectedNext}`, landed?.searchParams.get("next") === expectedNext, { expected: expectedNext, observed: landed?.searchParams.get("next") ?? null, }); ctx.check(`${target}: page is the connect shell`, (await pageName(page)) === "connect", { expected: "connect", observed: await pageName(page), }); ctx.check(`${target}: no nav items`, (await navItems(page).count()) === 0, { observed: await navItems(page).count(), }); ctx.check(`${target}: no .server-chip`, (await page.locator(".server-chip").count()) === 0, { observed: await page.locator(".server-chip").count(), }); }; await guardCase("/workspaces", "/workspaces"); ctx.checkValue("raw /workspaces redirect search", new URL(page.url()).search, "?next=%2Fworkspaces"); await guardCase("/status", "/status"); await guardCase("/chat", "/chat"); // An external `next` must be replaced by the allow-listed fallback and never // cause an off-site navigation. const requested = []; page.on("request", (request) => requested.push(request.url())); for (const evil of ["https://evil.example/pwn", "//evil.example/pwn", "javascript:alert(1)"]) { await page.goto(`${BASE}/connect?next=${encodeURIComponent(evil)}`, { waitUntil: "domcontentloaded" }); await sleep(400); const url = new URL(page.url()); const next = url.searchParams.get("next"); ctx.check(`external next rejected: ${evil}`, next !== evil && url.hostname === BASE_HOST && !page.url().includes("evil.example"), { expected: "next normalized to /workspaces, same origin", observed: { url: page.url(), next }, }); ctx.log(`safeNext(${evil}) → ${next}`); } ctx.check("no request left the origin", requested.every((url) => new URL(url).hostname === BASE_HOST || url.startsWith("data:")), { observed: requested.filter((url) => { try { return new URL(url).hostname !== BASE_HOST; } catch { return false; } }), }); await ctx.shot(page, "b1-connect-guard"); }); /* ------------------------------------------------------------------ */ /* B2 — manual pairing */ /* ------------------------------------------------------------------ */ const CONNECT_TESTIDS = [ "connect-host", "connect-port", "connect-pair-code", "connect-device", "connect-submit", "connect-scan", "connect-manual", ]; /** Mint a single-use pairing code through the CLI token (`pair.create`). */ async function mintPairCode() { const created = await cmd("pair.create", { ttlSec: 600 }); const code = created.json?.code; if (typeof code !== "string" || !code) { throw new Error(`pair.create returned no code: ${created.status} ${short(created.text, 200)}`); } return code; } /** Fill the manual form by test id (never by input order). */ async function fillManualForm(page, code, device = "Playwright") { await page.locator('[data-testid="connect-host"]').fill(BASE_HOST); await page.locator('[data-testid="connect-port"]').fill(PORT); await page.locator('[data-testid="connect-pair-code"]').fill(code); await page.locator('[data-testid="connect-device"]').fill(device); await page.locator('[data-testid="connect-submit"]').click(); } scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair + redirect (wrong code → inline error)", async (ctx) => { const { page } = await ctx.openPage("unpaired"); await page.goto(`${BASE}/connect?next=%2Fworkspaces`, { waitUntil: "domcontentloaded" }); await page.locator('[data-testid="connect-pair-code"]').waitFor({ state: "visible", timeout: 15000 }); const missing = []; for (const id of CONNECT_TESTIDS) { if ((await page.locator(`[data-testid="${id}"]`).count()) === 0) missing.push(id); } ctx.check("connect page exposes the documented test ids", missing.length === 0, { expected: CONNECT_TESTIDS, observed: { missing }, }); // --- happy path ------------------------------------------------------- const code = await mintPairCode(); await fillManualForm(page, code); const outcome = await waitFor(async () => { const inline = page.locator("form.cn-form .cn-error[role=alert]"); if ((await inline.count()) > 0 && (await inline.first().isVisible())) { return { kind: "error", text: (await inline.first().innerText()).trim() }; } const url = new URL(page.url()); if (url.pathname === "/workspaces") return { kind: "redirect", url: url.href }; return null; }, 25000); const pairCalls = ctx.apiCalls.filter((call) => call.method === "POST" && call.path === "/api/v1/pair"); ctx.log(`redeem calls: ${JSON.stringify(pairCalls)}`); ctx.check("the redeem posts the public POST /api/v1/pair", pairCalls.length >= 1, { expected: "POST /api/v1/pair {code,deviceName,kind}", observed: { pairCalls, cmdMethods: ctx.cmdRequests.map((request) => request.method) }, }); ctx.check("POST /api/v1/pair answered 200", pairCalls.some((call) => call.status === 200), { expected: 200, observed: pairCalls, }); ctx.check("no redeem goes through the bearer-gated /api/v1/cmd", !ctx.cmdRequests.some((r) => r.method === "pair.redeem"), { expected: "no pair.redeem cmd", observed: ctx.cmdRequests.map((request) => request.method), }); // The app may bounce back to /connect within ~100 ms, so the navigation log // (not just the final URL) is the evidence that `next` was followed. const reachedNext = ctx.navigations.some((entry) => entry.startsWith("/workspaces")); ctx.softCheck("manual pairing navigates to next (/workspaces)", reachedNext || outcome?.kind === "redirect", { expected: "a navigation to /workspaces", observed: { navigations: ctx.navigations, outcome }, }); const storage = await page.evaluate(() => ({ connection: localStorage.getItem("pi2-connection"), token: localStorage.getItem("pi2-device-token"), scopes: localStorage.getItem("pi2-device-scopes"), endpoint: localStorage.getItem("pi2-endpoint"), })); const connWrites = await page.evaluate(() => (window.__pi2Writes ?? []).filter((write) => ["pi2-connection", "pi2-device-token", "pi2-device-scopes"].includes(write.key)), ); ctx.note(`pi2-* storage writes: ${short(connWrites, 700)}`); ctx.note(`navigations: ${short(ctx.navigations, 400)}`); // The freshly minted token, as the app stored it (the storage is cleared // again by the disconnect that follows, so read it from the write log). const mintedRaw = (connWrites.find((write) => write.key === "pi2-device-token" && write.op === "set")?.value ?? "").replace( /^Bearer\s+/i, "", ); const mintedScopes = (connWrites.find((write) => write.key === "pi2-device-scopes" && write.op === "set")?.value ?? "").trim(); const wsErrors = socketErrors(ctx.wsFrames); const wsAuthErrors = wsErrors.filter((entry) => entry.code === "E_UNAUTHORIZED"); ctx.softCheck("the socket authenticates with the freshly paired token", wsAuthErrors.length === 0, { expected: "no E_UNAUTHORIZED socket error after pairing", observed: { socketErrors: wsErrors.slice(0, 5), navigations: ctx.navigations }, cause: "web/src/lib/api.ts:setDeviceToken() persists 'Bearer ' and web/src/lib/ws.ts sends getDeviceToken() verbatim in the auth frame, " + "while src/daemon/auth.ts:187 verifyToken() hashes the raw string → E_UNAUTHORIZED → app-shell.tsx disconnects and bounces to /connect", }); const mintedDevices = mintedRaw ? await apiRaw("GET", "/api/v1/devices", { token: mintedRaw }) : { status: 0, text: "no token written" }; ctx.softCheck("the minted device token is accepted over HTTP", mintedDevices.status === 200, { expected: 200, observed: { status: mintedDevices.status, body: short(mintedDevices.text, 200) }, }); ctx.softCheck("localStorage pi2-connection stays paired", storage.connection === "paired", { expected: "paired", observed: { connection: storage.connection, setToken: Boolean(mintedRaw), writes: connWrites, navigations: ctx.navigations }, cause: "the flow writes pi2-connection=paired (see the write log), then ~100 ms later the app removes the token + scopes and writes 'unpaired' " + "because the socket auth of that same token fails with E_UNAUTHORIZED", }); ctx.softCheck("localStorage pi2-device-token is still set", Boolean(storage.token), { expected: "", observed: storage.token ? "set" : { removedAfterMs: connWrites.at(-1)?.at, writes: connWrites }, }); let scopes = null; try { scopes = JSON.parse(storage.scopes ?? mintedScopes ?? "null"); } catch { scopes = null; } ctx.softCheck("the paired scopes are a non-empty array", Array.isArray(scopes) && scopes.length > 0, { expected: '["read", …]', observed: storage.scopes ?? mintedScopes, }); // A paired browser shows the summary instead of the form. await page.goto(`${BASE}/connect`, { waitUntil: "domcontentloaded" }); const summary = await waitFor(async () => ((await page.locator(".cn-summary").count()) > 0 ? true : null), 15000); ctx.softCheck("paired /connect shows the summary instead of the manual form", Boolean(summary), { expected: ".cn-summary visible", observed: { summary: Boolean(summary), forms: await page.locator("form.cn-form").count(), url: page.url() }, }); await ctx.shot(page, "b2-paired-summary"); // --- wrong code (fresh unpaired context) ------------------------------ const { page: wrong } = await ctx.openPage("unpaired"); await wrong.goto(`${BASE}/connect?next=%2Fworkspaces`, { waitUntil: "domcontentloaded" }); await wrong.locator('[data-testid="connect-pair-code"]').waitFor({ state: "visible", timeout: 15000 }); await fillManualForm(wrong, "ZZZZZZZZ"); const inlineError = await waitFor(async () => { const alert = wrong.locator('form.cn-form [role="alert"]'); if ((await alert.count()) === 0) return null; const first = alert.first(); if (!(await first.isVisible())) return null; const text = (await first.innerText()).trim(); return text || null; }, 25000); ctx.check("wrong code shows an inline role=alert error", Boolean(inlineError), { expected: "visible [role=alert] inside form.cn-form", observed: inlineError ?? "none", }); ctx.log(`wrong-code inline error: ${short(inlineError, 160)}`); const afterFailure = await wrong.evaluate(() => localStorage.getItem("pi2-connection")); ctx.check("wrong code leaves the browser unpaired", afterFailure !== "paired", { expected: "unpaired / null", observed: afterFailure, }); ctx.check("wrong code keeps the form usable", await wrong.locator('[data-testid="connect-submit"]').isEnabled(), { expected: "submit enabled", }); await ctx.shot(wrong, "b2-pairing-error"); }); /* ------------------------------------------------------------------ */ /* B3 — QR / paste-link pairing */ /* ------------------------------------------------------------------ */ scenario("B3", "Paste-link pairing: pi2:// and /pair/ links reach the confirm modal; confirming pairs", async (ctx) => { const parseCode = await mintPairCode(); const openScan = async (page) => { await page.locator('[data-testid="connect-scan"]').waitFor({ state: "visible", timeout: 15000 }); await page.locator('[data-testid="connect-scan"]').click(); const dialog = await dialogFor(page, "Scan pairing code", 8000); ctx.check("scan dialog opens", Boolean(dialog), { expected: "dialog 'Scan pairing code'", observed: page.url(), }); const input = page.locator('[aria-label="Pairing link"]'); if (!(await waitFor(async () => ((await input.isVisible()) ? true : null), 6000))) { // Camera unavailable/denied → the paste fallback folds open on its own; // open the `details` fold when it did not. await page .locator("summary", { hasText: /can'?t scan|paste the pairing link/i }) .first() .click() .catch(() => undefined); } const ready = await waitFor(async () => ((await input.isVisible()) ? true : null), 15000); ctx.check("paste-link fallback is reachable", Boolean(ready), { expected: 'visible input[aria-label="Pairing link"]', observed: await page.locator(".cn-scan__state").innerText().catch(() => ""), }); return input; }; const identify = async (page, input, link) => { await input.fill(link); await page.getByRole("button", { name: /^Identify$/ }).click(); const confirm = await dialogFor(page, "Confirm connection", 8000); return { confirm, state: await page.locator(".cn-scan__state").innerText().catch(() => "") }; }; // --- 1) pi2:// link parses into the confirm modal --------------------- const { page } = await ctx.openPage("unpaired"); await page.goto(`${BASE}/connect`, { waitUntil: "domcontentloaded" }); const pi2Link = `pi2://pair?host=${BASE_HOST}&port=${PORT}&code=${parseCode}`; const parsed = await identify(page, await openScan(page), pi2Link); ctx.check(`pi2:// link is parsed (${pi2Link})`, Boolean(parsed.confirm), { expected: "dialog 'Confirm connection'", observed: parsed.state, }); const confirmText = (await parsed.confirm.innerText()).replace(/\s+/g, " "); ctx.check("confirm modal masks the pairing code", confirmText.includes("…"), { expected: "masked code containing …", observed: short(confirmText, 200), }); await parsed.confirm.locator('[data-testid="connect-confirm-cancel"]').click(); const cancelled = await waitFor(async () => ((await page.getByRole("dialog").count()) === 0 ? true : null), 8000); ctx.check("cancel closes the confirm modal", Boolean(cancelled), { observed: await page.getByRole("dialog").count(), }); ctx.check("cancel keeps the browser unpaired", (await page.evaluate(() => localStorage.getItem("pi2-connection"))) !== "paired", { observed: await page.evaluate(() => localStorage.getItem("pi2-connection")), }); await ctx.shot(page, "b3-paste-link"); // --- 2) confirming the link pairs the browser ------------------------ const redeemCode = await mintPairCode(); const parsed2 = await identify(page, await openScan(page), `pi2://pair?host=${BASE_HOST}&port=${PORT}&code=${redeemCode}`); ctx.check("the second pi2:// link still parses", Boolean(parsed2.confirm), { observed: parsed2.state }); await parsed2.confirm.locator('[data-testid="connect-confirm-connect"]').click(); const paired = await waitFor(async () => { const alert = page.locator('.modal-content [role="alert"]'); if ((await alert.count()) > 0 && (await alert.first().isVisible())) { return { kind: "error", text: (await alert.first().innerText()).trim() }; } if (ctx.navigations.some((entry) => entry.startsWith("/workspaces"))) { return { kind: "redirect", url: page.url() }; } return null; }, 25000); ctx.softCheck("confirming the pasted link pairs and navigates to /workspaces", paired?.kind === "redirect", { expected: "navigation to /workspaces with a device token", observed: paired ?? { url: page.url(), navigations: ctx.navigations }, }); const linkStorage = await page.evaluate(() => ({ connection: localStorage.getItem("pi2-connection"), token: localStorage.getItem("pi2-device-token"), scopes: localStorage.getItem("pi2-device-scopes"), })); const linkWrites = await page.evaluate(() => (window.__pi2Writes ?? []).filter((write) => ["pi2-connection", "pi2-device-token", "pi2-device-scopes"].includes(write.key)), ); ctx.note(`link-flow pi2-* storage writes: ${short(linkWrites, 700)}`); const linkWsErrors = socketErrors(ctx.wsFrames); ctx.softCheck( "the socket authenticates after the link-flow pairing", linkWsErrors.filter((entry) => entry.code === "E_UNAUTHORIZED").length === 0, { expected: "no E_UNAUTHORIZED socket error", observed: { socketErrors: linkWsErrors.slice(0, 5), navigations: ctx.navigations }, cause: "same stored 'Bearer ' passed verbatim to the WS auth frame (web/src/lib/api.ts + web/src/lib/ws.ts:219)", }, ); ctx.softCheck("the link flow keeps paired + token + scopes", linkStorage.connection === "paired" && Boolean(linkStorage.token), { expected: { connection: "paired", token: "set" }, observed: { ...linkStorage, token: linkStorage.token ? "set" : null, writes: linkWrites }, cause: "the same write-then-clear sequence as B2 (socket auth of the fresh token is rejected → app-shell disconnects)", }); // --- 3) the daemon's own /pair/ URL parses --------------------- const { page: page3 } = await ctx.openPage("unpaired"); await page3.goto(`${BASE}/connect`, { waitUntil: "domcontentloaded" }); const daemonLink = `${BASE}/pair/${parseCode}`; const parsed3 = await identify(page3, await openScan(page3), daemonLink); ctx.check(`daemon pairing URL is accepted by the parser (${daemonLink})`, Boolean(parsed3.confirm), { expected: "dialog 'Confirm connection'", observed: { scanState: parsed3.state, confirmDialog: Boolean(parsed3.confirm) }, }); await ctx.shot(page3, "b3-daemon-url"); await dismissDialogs(page3); }); /* ------------------------------------------------------------------ */ /* B4 — workspaces */ /* ------------------------------------------------------------------ */ scenario("B4", "Workspaces: seeded rows/order/counts, path validation, UI add + navigate", async (ctx) => { const { page } = await ctx.openPage("paired"); await page.goto(`${BASE}/workspaces`, { waitUntil: "domcontentloaded" }); await page.locator("[data-workspace-id]").first().waitFor({ state: "visible", timeout: 20000 }); const apiList = (await listWorkspaces()).filter((item) => !item.hidden); const expectedOrder = [...apiList].sort( (a, b) => Number(Boolean(b.pinned)) - Number(Boolean(a.pinned)) || (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0), ); const rows = page.locator('[data-workspace-id][data-testid="workspace-row"]'); const rowIds = await rows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id"))); ctx.checkValue("workspace row count equals the API", rowIds.length, apiList.length); ctx.checkValue("workspace rows are the API workspaces", [...rowIds].sort(), apiList.map((item) => item.workspaceId).sort()); ctx.checkValue("workspace row order (pinned → lastActiveAt desc)", rowIds, expectedOrder.map((item) => item.workspaceId)); ctx.check("W1/W2 are both rendered", [state.ws1, state.ws2].every((id) => rowIds.includes(id)), { expected: [state.ws1, state.ws2], observed: rowIds, }); const enterHrefs = await page .locator('[data-testid="workspace-enter"]') .evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href"))); ctx.check( "each row links to /chat?workspace=", enterHrefs.length === rowIds.length && rowIds.every((id, index) => enterHrefs[index] === `/chat?workspace=${id}`), { observed: enterHrefs }, ); ctx.check("no server/workspace selector on /workspaces", (await page.locator("select").count()) === 0, { observed: await page.locator("select").count(), }); const expectedWorkspaceCount = `${apiList.length} workspaces`; const expectedSessionCount = `${ apiList.reduce((total, item) => total + Math.max(item.liveCount || 0, item.sessionCount || 0), 0) } sessions`; const contextBar = page.locator('section.ws-context[aria-label="Current server"]'); ctx.check("context bar is present", (await contextBar.count()) === 1, { observed: await contextBar.count() }); const barText = (await contextBar.innerText()).replace(/\s+/g, " "); ctx.check("context bar workspace count", barText.includes(expectedWorkspaceCount), { expected: expectedWorkspaceCount, observed: barText, }); ctx.check("context bar session count", barText.includes(expectedSessionCount), { expected: expectedSessionCount, observed: barText, }); // --- empty path validation (no POST must happen) ---------------------- const requestsBefore = ctx.cmdRequests.length; await page.getByRole("button", { name: /open new workspace/i }).first().click(); const dialog = await dialogFor(page, "Open new workspace", 8000); ctx.check("new-workspace dialog opens", Boolean(dialog), { observed: page.url() }); await dialog.getByRole("button", { name: /^Open$/ }).click(); const pathError = await waitFor(async () => { const alert = page.locator('form#new-workspace-form [role="alert"]'); if ((await alert.count()) === 0) return null; const text = (await alert.first().innerText()).trim(); return text || null; }, 6000); ctx.check("empty path shows an inline validation error", pathError === "Enter a working directory path", { expected: "Enter a working directory path", observed: pathError, }); ctx.check("empty path issues no workspace.add", ctx.cmdRequests.slice(requestsBefore).every((r) => r.method !== "workspace.add"), { observed: ctx.cmdRequests.slice(requestsBefore).map((r) => r.method), }); // --- real add through the UI ------------------------------------------ const newPath = path.join(WS_ROOTS, "ui-added"); fs.mkdirSync(newPath, { recursive: true }); await page.locator("#new-workspace-path").fill(newPath); await page.locator("#new-workspace-name").fill("UI Added"); await dialog.getByRole("button", { name: /^Open$/ }).click(); const navigated = await waitFor(async () => { const url = new URL(page.url()); if (!url.pathname.startsWith("/chat")) return null; return url.searchParams.get("workspace"); }, 30000); ctx.check("adding a workspace navigates into /chat?workspace=", Boolean(navigated), { expected: "/chat?workspace=", observed: page.url(), }); const apiWorkspaces = await listWorkspaces(); const created = apiWorkspaces.find((item) => item.cwd === newPath); ctx.check("the added workspace is listed by the API", Boolean(created), { expected: `workspace with cwd=${newPath}`, observed: apiWorkspaces.map((item) => item.cwd), }); ctx.check("navigation uses the created workspace id", navigated === created?.workspaceId, { expected: created?.workspaceId, observed: navigated, }); const toast = await waitToast(page, /opened workspace/i, 4000); ctx.log(`add-workspace toast: ${toast ?? "(already gone)"}`); // --- API error + retry must not white-screen -------------------------- const { page: errorPage } = await ctx.openPage("paired"); await errorPage.route("**/api/v1/workspaces", (route) => route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: { code: "E_INTERNAL", message: "injected by ui-e2e (B4)", retryable: true } }), }), ); await errorPage.goto(`${BASE}/workspaces`, { waitUntil: "domcontentloaded" }); const errorEmpty = await waitFor(async () => { const text = await bodyText(errorPage); return /could not load workspaces/i.test(text) ? text : null; }, 20000); ctx.check("workspaces API error renders an error state", Boolean(errorEmpty), { expected: "Could not load workspaces", observed: short((await bodyText(errorPage)).replace(/\s+/g, " "), 200), }); await ctx.shot(errorPage, "b4-workspaces-api-error"); await errorPage.unroute("**/api/v1/workspaces"); await errorPage.getByRole("button", { name: /retry/i }).first().click(); const recovered = await waitFor(async () => (await errorPage.locator("[data-workspace-id]").count()) > 0, 20000); ctx.check("retry recovers the workspaces list", Boolean(recovered), { expected: "workspace rows after Retry", observed: await errorPage.locator("[data-workspace-id]").count(), }); state.uiAddedWorkspace = created?.workspaceId; }); /* ------------------------------------------------------------------ */ /* B5 — chat session tree */ /* ------------------------------------------------------------------ */ scenario("B5", "Chat tree: workspace selector, New session → /chat/, rename persists, close confirms, switch workspaces", async (ctx) => { const { page } = await ctx.openPage("paired"); await page.goto(`${BASE}/chat?workspace=${encodeURIComponent(state.ws1)}`, { waitUntil: "domcontentloaded" }); await page.locator(".tree-pane .pane-head").waitFor({ state: "visible", timeout: 20000 }); const workspaceSelect = page.locator('select[aria-label="Workspace"]'); ctx.check("workspace selector is present", (await workspaceSelect.count()) === 1, { observed: await workspaceSelect.count() }); ctx.checkValue("workspace selector value is W1", await workspaceSelect.inputValue(), state.ws1); const options = await workspaceSelect.locator("option").evaluateAll((nodes) => nodes.map((node) => node.value)); ctx.check("workspace selector lists every workspace", options.length >= 2 && options.includes(state.ws2), { expected: [state.ws1, state.ws2], observed: options, }); const before = await listSessions(state.ws1); const newSessionButton = page.locator(".tree-pane .pane-head button", { hasText: "New session" }).first(); await newSessionButton.click(); // The URL may briefly carry the `tmp-N` placeholder; the web replaces it with // the real id once the plugin announces the migration. const createdUrl = await waitRealSessionId(page, 15000); ctx.check("New session routes to /chat/", Boolean(createdUrl), { expected: "/chat/", observed: page.url() }); ctx.check("New session keeps ?workspace=W1", createdUrl?.workspace === state.ws1, { expected: state.ws1, observed: createdUrl?.workspace, }); const sessionId = createdUrl.sessionId; state.treeSession = { sessionId, workspaceId: state.ws1 }; const after = await listSessions(state.ws1); ctx.check("the created session is listed by the API", after.some((row) => row.sessionId === sessionId), { expected: sessionId, observed: after.map((row) => row.sessionId), }); ctx.log(`sessions in W1: ${before.length} → ${after.length}`); const selectedRow = page.locator('.tree-pane .tree-row[aria-current="true"]'); const rowFound = await waitFor(async () => { const ids = await treeSessionIds(page); return ids.includes(sessionId) ? true : null; }, 20000); ctx.check("the new session row is in the tree and selected", Boolean(rowFound) && (await selectedRow.count()) === 1, { expected: `.tree-row[data-session-id="${sessionId}"][aria-current="true"]`, observed: await treeSessionIds(page), }); const streamedName = await streamName(page); const selectedLabel = (await selectedRow.first().getAttribute("aria-label")) ?? ""; ctx.check("tree row label matches the stream title", selectedLabel === streamedName && streamedName.length > 0, { expected: streamedName, observed: selectedLabel, }); // --- rename (must persist through the plugin + a reload) ------------- await selectedRow.first().locator('button[aria-label="Rename session"]').click(); const renameDialog = await dialogFor(page, "Rename session", 8000); ctx.check("rename dialog opens from the tree row", Boolean(renameDialog), { observed: page.url() }); await page.locator("#rename-input").fill("e2e-renamed"); await renameDialog.getByRole("button", { name: /^Save$/ }).click(); const renameToast = await waitToast(page, /renamed/i, 8000); ctx.check("rename surfaces a toast", Boolean(renameToast), { expected: "Renamed: e2e-renamed", observed: (await toastTexts(page)).join(" | ") }); await page.reload({ waitUntil: "domcontentloaded" }); await page.locator(".tree-pane .pane-head").waitFor({ state: "visible", timeout: 20000 }); const labels = () => page.locator(".tree-pane .tree-row").evaluateAll((nodes) => nodes.map((node) => node.getAttribute("aria-label"))); const persisted = await waitFor(async () => { const current = await labels(); return current.includes("e2e-renamed") ? current : null; }, 25000); ctx.check("renamed session persists across a reload", Boolean(persisted), { expected: "tree row aria-label=e2e-renamed", observed: persisted ?? (await labels()), }); // --- close asks for confirmation and removes the row ----------------- const targetRow = page.locator('.tree-pane .tree-row[aria-label="e2e-renamed"]'); await targetRow.first().locator('button[aria-label="Close process"]').click(); const closeDialog = await dialogFor(page, "Close process", 8000); ctx.check("close asks for confirmation", Boolean(closeDialog), { observed: page.url() }); const closeText = (await closeDialog.innerText()).replace(/\s+/g, " "); ctx.check("close confirmation names the session", closeText.includes("e2e-renamed"), { expected: "…e2e-renamed…", observed: closeText }); await closeDialog.getByRole("button", { name: /^Close process$/ }).click(); const closedToast = await waitToast(page, /closed process/i, 8000); ctx.log(`close toast: ${closedToast ?? "(none)"}`); const rowGone = await waitFor(async () => { const current = await labels(); return current.includes("e2e-renamed") ? null : current; }, 25000); if (!rowGone) { const apiAfterClose = await listSessions(state.ws1); ctx.softCheck("closed session disappears from the tree", false, { expected: "row removed after close", observed: { treeRows: await labels(), apiSessions: apiAfterClose.filter((row) => row.sessionId === sessionId), }, cause: "session.close closes the pi process but GET /api/v1/workspaces//sessions keeps the row, so the tree re-adds it on the next poll", }); } else { ctx.check("closed session disappears from the tree", true, { observed: "removed" }); } // --- workspace switch does not leak rows ----------------------------- await workspaceSelect.selectOption(state.ws2); const switched = await waitFor(async () => (new URL(page.url()).searchParams.get("workspace") === state.ws2 ? true : null), 20000); ctx.check("switching the workspace updates ?workspace", Boolean(switched), { expected: state.ws2, observed: page.url() }); const ws2Rows = await waitFor(async () => { const current = await labels(); return current.includes("e2e-renamed") ? null : current; }, 20000); ctx.check("switching to W2 does not leak W1 rows", Boolean(ws2Rows), { expected: "no W1 rows in the W2 tree", observed: ws2Rows ?? (await labels()), }); ctx.log(`W2 tree rows: ${JSON.stringify(ws2Rows)}`); await ctx.shot(page, "b5-tree"); }); /* ------------------------------------------------------------------ */ /* B6 — prompt + streaming */ /* ------------------------------------------------------------------ */ scenario("B6", "Prompt + streaming: PONG turn, one user entry, no .streaming after settle, Shift+Enter does not send", async (ctx) => { const { page } = await ctx.openPage("paired"); const sessionId = await createSession(state.ws1); state.pongSession = { sessionId, workspaceId: state.ws1 }; ctx.check("chat page becomes usable (WS open + composer enabled)", await openChat(page, sessionId, state.ws1), { expected: "textarea[aria-label='Message input'] enabled", observed: { composer: await composerState(page) }, }); // --- Shift+Enter inserts a newline, it must not send ----------------- const textarea = page.locator(COMPOSER_INPUT); await textarea.click(); await textarea.type("line one"); await page.keyboard.press("Shift+Enter"); await textarea.type("line two"); const value = await textarea.inputValue(); ctx.check("Shift+Enter inserts a newline", value.includes("\n"), { expected: "two lines", observed: value }); ctx.check("Shift+Enter does not send", (await page.locator('article.msg[data-role="user"]').count()) === 0, { observed: await page.locator('article.msg[data-role="user"]').count(), }); await textarea.fill(""); // --- Enter sends, the assistant streams and settles ------------------ const prompt = "Reply with exactly the word PONG and nothing else."; await textarea.fill(prompt); await page.keyboard.press("Enter"); const sent = await waitFor(async () => ctx.cmdRequests.find((request) => request.method === "prompt.send") ?? null, 15000); ctx.check("Enter posts prompt.send", Boolean(sent) && sent.params?.text === prompt, { expected: { method: "prompt.send", text: prompt }, observed: sent ?? null, }); const userEntries = await waitFor(async () => { const articles = await streamArticles(page); const users = articles.filter((article) => article.role === "user"); return users.length === 1 ? users : null; }, 20000); ctx.check("exactly one user entry appears", Boolean(userEntries), { expected: 1, observed: (await streamArticles(page)).filter((a) => a.role === "user"), }); ctx.checkValue("the user entry text is the prompt", userEntries[0].text, prompt); const settled = await waitFor(async () => { const articles = await streamArticles(page); const assistant = articles.filter((article) => article.role === "assistant"); if (assistant.length !== 1) return null; const text = assistant[0].text.trim(); return text.length > 0 && !assistant[0].streaming ? assistant[0] : null; }, 120000, 250); const finalArticles = await streamArticles(page); const assistants = finalArticles.filter((article) => article.role === "assistant"); const snapEntries = snapshotEntries(ctx.wsFrames, sessionId) ?? []; ctx.note(`snapshot entries: ${short(snapEntries, 600)}`); ctx.note(`DOM articles: ${short(finalArticles, 600)}`); ctx.softCheck( "the plugin snapshot holds exactly one assistant entry", snapEntries.filter((entry) => entry.role === "assistant").length <= 1, { expected: "<=1 assistant entry in the snapshot", observed: snapEntries.filter((entry) => entry.role === "assistant") }, ); ctx.check("the assistant turn settles", Boolean(settled), { expected: "one settled assistant article", observed: { count: assistants.length, text: short(assistants.map((a) => a.text).join(" | "), 200) }, }); ctx.checkValue("assistant text is exactly PONG", settled.text.trim().toLowerCase(), "pong"); ctx.check("exactly one assistant entry for the turn", assistants.length === 1, { expected: 1, observed: assistants.length, }); ctx.check( "no .msg__text.streaming remains", finalArticles.every((article) => !article.streaming), { observed: finalArticles.filter((a) => a.streaming) }, ); const backToSend = await waitFor(async () => { const state_ = await composerState(page); return state_.send === "Send" && !state_.abort ? true : null; }, 15000); ctx.check("the Abort button disappears and Send is available", Boolean(backToSend), { expected: { abort: false, send: "Send" }, observed: await composerState(page), }); // `flags.done` is sticky once a turn completed, so the badge reads `Done` // (the design's `state.done`); docs/e2e.md B6 describes it as idle. Both mean // "settled": the composer is back to Send and nothing streams any more. const SETTLED_BADGES = ["Idle", "Done"]; const badge = await waitFor(async () => { const label = await sessionStatusBadge(page); return SETTLED_BADGES.includes(label) ? label : null; }, 15000); ctx.check("status badge returns to a settled state (Idle/Done)", Boolean(badge), { expected: "Idle|Done", observed: await sessionStatusBadge(page), }); ctx.note(`settled status badge: ${await sessionStatusBadge(page)}`); ctx.check("no error toast during the turn", (await errorToastCount(page)) === 0, { observed: await toastTexts(page), }); const frameTypes = ctx.wsFrames .map((frame) => (frame?.type === "event" ? (frame.payload?.event ?? frame.payload)?.type : frame?.type)) .filter(Boolean); const counts = frameTypes.reduce((acc, type) => ({ ...acc, [type]: (acc[type] ?? 0) + 1 }), {}); ctx.note(`WS frames: ${short(counts, 300)}`); ctx.check("streaming produced assistant deltas over the WS", (counts.message_update ?? 0) >= 1, { expected: ">=1 message_update", observed: counts, }); await ctx.shot(page, "b6-pong"); }); /* ------------------------------------------------------------------ */ /* B7 — abort */ /* ------------------------------------------------------------------ */ scenario("B7", "Abort: slow prompt → Abort button → Idle within 10 s, partial text stays, nothing more arrives", async (ctx) => { const { page } = await ctx.openPage("paired"); const sessionId = await createSession(state.ws1); ctx.check("chat page becomes usable", await openChat(page, sessionId, state.ws1), { expected: "composer enabled" }); const textarea = page.locator(COMPOSER_INPUT); await textarea.fill("Count from 1 to 200, one number per line."); await page.keyboard.press("Enter"); const abortVisible = await waitFor(async () => ((await page.locator('[data-testid="composer-abort"]').count()) > 0 ? true : null), 30000); ctx.check("an Abort button appears while busy", Boolean(abortVisible), { expected: '[data-testid="composer-abort"]', observed: await composerState(page), }); await waitFor(async () => { const articles = await streamArticles(page); return articles.some((article) => article.role === "assistant" && article.text.length > 0) ? true : null; }, 30000); await page.locator('[data-testid="composer-abort"]').click(); const abortSent = await waitFor(async () => ctx.cmdRequests.find((request) => request.method === "prompt.abort") ?? null, 10000); ctx.check("Abort posts prompt.abort", Boolean(abortSent), { observed: ctx.cmdRequests.map((r) => r.method) }); // After an aborted turn the protocol (§4.1 `agent_settled{aborted}`) leaves // `status=idle` and sets `flags.error`, so the badge reads `Error` — the // session is settled, it just carries the abort flag. Accept either label; // the hard requirements are that the composer returns to Send (no stuck // busy state) and that no further assistant text arrives (asserted below). const ABORT_SETTLED_STATUS = ["Idle", "Error"]; const settled = await waitFor(async () => { const label = await sessionStatusBadge(page); return (await composerSendLabel(page)) === "Send" && ABORT_SETTLED_STATUS.includes(label) ? label : null; }, 10000); const abortStatusLabel = await sessionStatusBadge(page); ctx.check("status returns to Idle within 10 s of the abort", Boolean(settled), { expected: { button: "Send", status: "Idle|Error" }, observed: { button: await composerSendLabel(page), status: abortStatusLabel }, }); ctx.note(`abort status label: ${abortStatusLabel || "(none)"}`); const partial = (await streamArticles(page)).filter((article) => article.role === "assistant"); ctx.check("partial assistant text remains", partial.some((article) => article.text.length > 0), { expected: ">=1 assistant article with text", observed: partial.map((article) => short(article.text, 80)), }); const lengthBefore = partial.map((article) => article.text.length).join(","); await sleep(4000); const lengthAfter = (await streamArticles(page)) .filter((article) => article.role === "assistant") .map((article) => article.text.length) .join(","); ctx.check("no further text arrives after the abort", lengthBefore === lengthAfter, { expected: lengthBefore, observed: lengthAfter, }); await ctx.shot(page, "b7-abort"); }); /* ------------------------------------------------------------------ */ /* B8 — model / thinking */ /* ------------------------------------------------------------------ */ /** Thinking levels the composer ` is empty or shows a value outside off|minimal|low|medium|high|xhigh|max after the reload", }); if (!wsSnapshot) { ctx.note("no WS snapshot frame for the session arrived within 15 s of the reload — the level was read from the select alone"); } if (shownLevel !== "low") { ctx.note( `thinking clamped by the model to ${shownLevel}: session.setThinking{level:"low"} was accepted, but the active ` + "model does not support `low` — the same clamp API scenario A6 records as an accepted deviation", ); } // --- model ---------------------------------------------------------- const model = page.locator('[data-testid="composer-model"]'); const modelOptions = await model.locator("option").evaluateAll((nodes) => nodes.filter((node) => node.value).map((node) => node.value), ); if (!modelOptions.length) { ctx.note("model select has no real options (workspace.query kind=models returned nothing) — model switch not exercised"); ctx.skip("model select has no options to switch to (no providers reported by the workspace)"); } const target = modelOptions[0]; await model.selectOption(target); const modelCmd = await waitFor(async () => ctx.cmdRequests.find((request) => request.method === "session.setModel") ?? null, 10000); ctx.check("model change posts session.setModel", Boolean(modelCmd), { expected: `session.setModel for ${target}`, observed: modelCmd ?? null, }); const modelResponse = ctx.cmdResponses.filter((response) => response.url.includes("/api/v1/cmd")).pop(); await sleep(2000); ctx.softCheck("model change shows no error toast", (await errorToastCount(page)) === 0, { expected: "no [data-sonner-toast][data-type=error]", observed: { toasts: await toastTexts(page), lastCmdResponse: modelResponse ?? null }, }); const modelId = target.slice(target.indexOf("/") + 1); const treeSub = page.locator(`.tree-pane .tree-row[data-session-id="${sessionId}"] .t-sub`).first(); if ((await treeSub.count()) > 0) { const subText = (await treeSub.innerText()).trim(); ctx.softCheck("the tree row subtitle shows the new model", subText.includes(modelId), { expected: modelId, observed: subText, }); } await page.reload({ waitUntil: "domcontentloaded" }); ctx.check("chat page becomes usable after the model reload", await openChat(page, sessionId, state.ws1), { expected: "composer enabled" }); // The backend may clamp or default the model (a provider that rejects the // requested id falls back), so a reload only has to show *a listed* model — // the requested one whenever the provider honours it. const modelValue = async () => page.locator('[data-testid="composer-model"]').inputValue().catch(() => ""); const modelAfter = await waitFor( async () => { const value = await modelValue(); return modelOptions.includes(value) ? value : null; }, 20000, ); ctx.check("the reloaded model select shows a listed model", Boolean(modelAfter), { expected: modelOptions, observed: { select: await modelValue(), requested: target }, cause: "the model