feat(web): port the pi2-web-ui-design v0.1.1 UI

Sync the React console with the v0.1.1 prototype (20 CHGs): Quiet Workbench
shell, Chat IA v3, tool-family rendering, and the mobile page pill.

Shell / tokens (CHG-01/04/15/20):
- tokens.css rewritten from the prototype (three-layer light/dark/system),
  `--tabbar-h` removed, new faint/border-subtle/surface-1-2/fs-*/dur-*/reading-max
- 56px icon-only nav rail/sidebar (44x44 hit targets, CSS tooltips, active is a
  solid primary fill, no left bar), 52px topbar, merged preferences menu,
  ⌘K/Cmd-K palette
- `<600` gets a topbar page pill + page sheet; the bottom tabbar is gone

Pages (CHG-01): workspaces becomes a card grid with whole-card links and a
320px recent-activity column; status gets four metric tiles + a zero-primary
layout; connect gets a two-column hero, one primary per state and a collapsed
manual form.

Chat IA v3 (CHG-02/10-14/16-19): two columns, single-workspace tree with a
workspace switch, single-line rows with attention, body-level row popover,
session tray (todo/tasks) replacing the right panel, context ring moved into a
composer telemetry line, right-aligned user messages, queued messages as one
stream entity plus a composer status bar, and an in-place subagent child view.

Tool rendering (CHG-05/06/09): new `features/chat/tools` module — one row per
call, DTO adapter for the daemon's block shape, 11 kind families, state
semantics ("one state, one meaning"), 44px touch targets and the diff row
contrast fix.

i18n: 729 keys per language (zh/en parity checked), 0 unresolved keys.

Verification: web typecheck + 297 vitest + vite build green, root typecheck
green, `scripts/smoke.sh` green, and a new visual harness
(`scripts/ui-mock-server.mjs` + `scripts/ui-shots.mjs`, docs/ui-parity.md)
shoots 4 pages x 3 viewports x 2 themes = 24 screenshots clean with
overflow/console/primary/tabbar assertions. `scripts/e2e/ui-e2e.mjs` selectors
are updated to the new DOM; that suite still needs a real pi + nvim to run.
This commit is contained in:
yuez committed 2026-10-26 20:28:47 +08:00
1 parent a8425a51b6
commit 88e73c7737
98 files changed
+17676 -2871

No files matched your search

+375 -141
View File
@@ -564,7 +564,24 @@ class Ctx {
/* DOM helpers */
/* ------------------------------------------------------------------ */
const navItems = (page) => page.locator(".sidebar .nav-item, .rail .nav-item, .tabbar .nav-item");
/**
* Nav rows (v0.1.1): the sidebar (≥840) and the rail (600–839) render the same
* icon-only rows, so the label lives in `aria-label`/`data-tip`, never in the
* text. Below 600 there is no persistent strip at all — the topbar `.page-pill`
* owns navigation and the mobile strip is gone for good.
*/
const NAV_ITEM = ".sidebar .nav-item, .rail .nav-item";
const navItems = (page) => page.locator(NAV_ITEM);
/** Labels of the nav rows that CSS actually shows (0 items below 600px). */
async function navItemLabels(page) {
return page.locator(NAV_ITEM).evaluateAll((nodes) =>
nodes
.filter((node) => node.getClientRects().length > 0)
.map((node) => (node.getAttribute("aria-label") ?? node.textContent ?? "").trim()),
);
}
const pageName = (page) => page.evaluate(() => document.body.dataset.page ?? "");
const streamText = (page) => page.locator('[role="log"][aria-label="Message stream"]');
@@ -722,6 +739,43 @@ async function openChat(page, sessionId, workspaceId) {
return waitEnabled(page, COMPOSER_INPUT, 30000);
}
/**
* The session row `…` popover (v0.1.1): a `[role="menu"]` portalled to `body`,
* every entry carries a locale-independent `data-menu-action`
* (`active-only|show-all|dispatch|rename|close`).
*/
async function openSessionRowMenu(page, sessionId) {
await page.locator(`.tree-pane .tree-row[data-session-id="${sessionId}"] .t-more`).click();
const menu = page.locator('[data-testid="session-row-menu"]');
await menu.waitFor({ state: "visible", timeout: 10000 });
return menu;
}
/** Session tree row name (the per-row `aria-label` moved onto `.t-name`). */
async function treeRowNames(page) {
return page
.locator(".tree-pane .tree-row[data-session-id] .t-name")
.evaluateAll((nodes) => nodes.map((node) => (node.textContent ?? "").trim()));
}
/** The session tray: the anchored `role="dialog"` that replaced the right panel. */
const sessionTray = (page) => page.locator('[data-testid="session-tray"]');
/**
* Open the tray from its stream-head chip (`head-chip-plan` → todo,
* `head-chip-tasks` → tasks). The chip is a *toggle*, so only click when the
* matching tab is not already open.
*/
async function openTray(page, tab = "todo") {
const chip = page.locator(`[data-testid="head-chip-${tab === "todo" ? "plan" : "tasks"}"]`);
await chip.waitFor({ state: "visible", timeout: 20000 });
const tray = sessionTray(page);
const already = (await chip.getAttribute("aria-expanded")) === "true" && (await tray.getAttribute("data-tab")) === tab;
if (!already) await chip.click();
await tray.waitFor({ state: "visible", timeout: 10000 });
return tray;
}
function entryIdsFromFrames(frames, sessionId) {
const snapshots = [];
const appended = [];
@@ -1002,9 +1056,9 @@ scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair
// 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);
const summary = await waitFor(async () => ((await page.locator("section.cn-state").count()) > 0 ? true : null), 15000);
ctx.softCheck("paired /connect shows the summary instead of the manual form", Boolean(summary), {
expected: ".cn-summary visible",
expected: "section.cn-state visible",
observed: { summary: Boolean(summary), forms: await page.locator("form.cn-form").count(), url: page.url() },
});
await ctx.shot(page, "b2-paired-summary");
@@ -1182,8 +1236,9 @@ scenario("B4", "Workspaces: seeded rows/order/counts, path validation, UI add +
observed: rowIds,
});
// v0.1.1: the whole card is the link (no separate enter button).
const enterHrefs = await page
.locator('[data-testid="workspace-enter"]')
.locator('[data-testid="workspace-row"]')
.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href")));
ctx.check(
"each row links to /chat?workspace=<id>",
@@ -1195,20 +1250,46 @@ scenario("B4", "Workspaces: seeded rows/order/counts, path validation, UI add +
});
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), {
// The status line summarises *every* served workspace; the session/running
// counters are not filtered by the visibility policy.
const servedWorkspaces = await listWorkspaces();
const expectedSessionCount = `${servedWorkspaces.reduce(
(total, item) => total + Math.max(item.liveCount || 0, item.sessionCount || 0),
0,
)} sessions`;
const statusLine = page.locator('[data-testid="workspaces-status-line"]');
ctx.check("status line is present", (await statusLine.count()) === 1, { observed: await statusLine.count() });
const barText = (await statusLine.innerText()).replace(/\s+/g, " ");
ctx.check("status line workspace count", barText.includes(expectedWorkspaceCount), {
expected: expectedWorkspaceCount,
observed: barText,
});
ctx.check("context bar session count", barText.includes(expectedSessionCount), {
ctx.check("status line session count", barText.includes(expectedSessionCount), {
expected: expectedSessionCount,
observed: barText,
});
ctx.check("status line links to /status", (await statusLine.locator('a[href="/status"]').count()) === 1, {
observed: await statusLine.locator("a").evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href"))),
});
// --- recent-activity column (new in v0.1.1) ---------------------------
const activity = page.locator('[data-testid="workspaces-activity"]');
ctx.check("recent-activity column is present", (await activity.count()) === 1, { observed: await activity.count() });
const activityRows = activity.locator('[data-testid="workspace-activity-row"]');
const activityIds = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id")));
const activityHrefs = await activityRows.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("href")));
const expectedActivity = rowIds
.map((id) => apiList.find((item) => item.workspaceId === id))
.filter((item) => item && typeof item.lastActiveAt === "number" && Number.isFinite(item.lastActiveAt))
.sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0))
.slice(0, 5)
.map((item) => item.workspaceId);
ctx.checkValue("recent activity lists the newest 5 workspaces", activityIds, expectedActivity);
ctx.check(
"activity rows link into /chat?workspace=<id>",
activityHrefs.every((href, index) => href === `/chat?workspace=${activityIds[index]}`),
{ observed: activityHrefs },
);
// --- empty path validation (no POST must happen) ----------------------
const requestsBefore = ctx.cmdRequests.length;
@@ -1293,22 +1374,34 @@ scenario("B4", "Workspaces: seeded rows/order/counts, path validation, UI add +
/* B5 — chat session tree */
/* ------------------------------------------------------------------ */
scenario("B5", "Chat tree: workspace selector, New session → /chat/<sid>, rename persists, close confirms, switch workspaces", async (ctx) => {
scenario("B5", "Chat tree: workspace picker, New session → /chat/<sid>, rename via the row menu, 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), {
// v0.1.1: the workspace picker is a button + `menuitemradio` menu (no <select>).
const wsSwitch = page.locator('[data-testid="ws-switch"]');
const wsMenu = page.locator('[data-testid="ws-menu"]');
ctx.check("workspace switch is present", (await wsSwitch.count()) === 1, { observed: await wsSwitch.count() });
await wsSwitch.click();
await wsMenu.waitFor({ state: "visible", timeout: 10000 });
const options = await wsMenu
.locator("[data-workspace-id]")
.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id")));
const checkedWorkspaces = await wsMenu
.locator('[data-workspace-id][aria-checked="true"]')
.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-workspace-id")));
ctx.checkValue("the workspace menu marks W1 as current", checkedWorkspaces, [state.ws1]);
ctx.check("workspace menu lists every workspace", options.length >= 2 && options.includes(state.ws2), {
expected: [state.ws1, state.ws2],
observed: options,
});
await wsSwitch.click();
const menuClosed = await waitFor(async () => ((await wsMenu.isVisible()) ? null : true), 6000);
ctx.check("the workspace menu closes on a second click", Boolean(menuClosed), { observed: await wsMenu.isVisible() });
const before = await listSessions(state.ws1);
const newSessionButton = page.locator(".tree-pane .pane-head button", { hasText: "New session" }).first();
const newSessionButton = page.locator('.tree-pane [data-testid="tree-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.
@@ -1328,24 +1421,27 @@ scenario("B5", "Chat tree: workspace selector, New session → /chat/<sid>, rena
});
ctx.log(`sessions in W1: ${before.length} → ${after.length}`);
const selectedRow = page.locator('.tree-pane .tree-row[aria-current="true"]');
const selectedRow = page.locator(".tree-pane .tree-row[data-session-id].selected");
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"]`,
expected: `.tree-row[data-session-id="${sessionId}"].selected`,
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, {
const selectedLabel = ((await selectedRow.first().locator(".t-name").innerText()) ?? "").trim();
ctx.check("tree row name 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();
// v0.1.1: row actions live in the `…` popover (`data-menu-action`), not in
// per-row buttons.
const rowMenu = await openSessionRowMenu(page, sessionId);
await rowMenu.locator('[data-menu-action="rename"]').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");
@@ -1354,19 +1450,21 @@ scenario("B5", "Chat tree: workspace selector, New session → /chat/<sid>, rena
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 labels = () => treeRowNames(page);
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",
expected: "tree row name=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 targetRow = page.locator(".tree-pane .tree-row[data-session-id]").filter({ hasText: "e2e-renamed" });
ctx.check("the renamed row is reachable in the tree", (await targetRow.count()) >= 1, { observed: await labels() });
const closeMenu = await openSessionRowMenu(page, sessionId);
await closeMenu.locator('[data-menu-action="close"]').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, " ");
@@ -1393,7 +1491,9 @@ scenario("B5", "Chat tree: workspace selector, New session → /chat/<sid>, rena
}
// --- workspace switch does not leak rows -----------------------------
await workspaceSelect.selectOption(state.ws2);
await wsSwitch.click();
await wsMenu.waitFor({ state: "visible", timeout: 10000 });
await wsMenu.locator(`[data-workspace-id="${state.ws2}"]`).click();
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 () => {
@@ -1420,6 +1520,25 @@ scenario("B6", "Prompt + streaming: PONG turn, one user entry, no .streaming aft
observed: { composer: await composerState(page) },
});
// --- composer queue bar (v0.1.1) --------------------------------------
// The queued prompts are rendered in the stream (`[data-testid=stream-queued]`,
// `.msg--queued`); the composer only carries a `role=status` bar with a clear
// action that stays disabled while nothing is pending.
const queueBar = page.locator('[data-testid="composer-queue"]');
const queueClear = page.locator('[data-testid="composer-queue-clear"]');
ctx.check(
"the composer queue bar is a status line",
(await queueBar.count()) === 1 && (await queueBar.getAttribute("role")) === "status",
{
expected: '[data-testid="composer-queue"][role=status]',
observed: { count: await queueBar.count(), role: await queueBar.getAttribute("role") },
},
);
ctx.check("the queue clear action is disabled with nothing pending", await queueClear.isDisabled(), {
expected: "disabled",
observed: { disabled: await queueClear.isDisabled(), text: (await queueClear.innerText()).trim() },
});
// --- Shift+Enter inserts a newline, it must not send -----------------
const textarea = page.locator(COMPOSER_INPUT);
await textarea.click();
@@ -1711,10 +1830,12 @@ scenario("B8", "Model/thinking selects: commands sent, no error toast, values su
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), {
// v0.1.1 moved the row subtitle into the row button's title
// (`name · model · thinking`); there is no `.t-sub` span any more.
const treeRow = page.locator(`.tree-pane .tree-row[data-session-id="${sessionId}"] .tree-row__main`).first();
if ((await treeRow.count()) > 0) {
const subText = ((await treeRow.getAttribute("title")) ?? "").trim();
ctx.softCheck("the tree row title shows the new model", subText.includes(modelId), {
expected: modelId,
observed: subText,
});
@@ -1747,80 +1868,92 @@ scenario("B8", "Model/thinking selects: commands sent, no error toast, values su
});
/* ------------------------------------------------------------------ */
/* B9 — panels (Subagents / Todo / Tasks) */
/* B9 — session tray (todo / tasks) + subagent child view */
/* ------------------------------------------------------------------ */
const MOCK_COPY = [/prototype demo only/i, /Demo only: local mock/i, /nothing is uploaded/i, /mock/i, /demo/i];
scenario("B9", "Panels: tab switching, empty/real states, real subagent dispatch + preview, no mock copy", async (ctx) => {
scenario("B9", "Session tray: two tabs, empty/real states, dispatch from the row menu, subagent child view, no mock copy", async (ctx) => {
const { page } = await ctx.openPage("paired");
const sessionId = await createSession(state.ws1);
state.panelSession = { sessionId, workspaceId: state.ws1 };
state.traySession = { sessionId, workspaceId: state.ws1 };
ctx.check("chat page becomes usable", await openChat(page, sessionId, state.ws1), { expected: "composer enabled" });
const tablist = page.locator('[role="tablist"][aria-label="Panel"]');
await tablist.waitFor({ state: "visible", timeout: 20000 });
// v0.1.1 removed the right panel: `/chat` is two columns and the Todo/Tasks
// surfaces are the anchored session tray.
await page.locator('[data-testid="head-chips"]').waitFor({ state: "visible", timeout: 20000 });
ctx.checkValue("no right panel column on /chat", await page.locator(".panel-pane").count(), 0);
// --- open the tray from the Plan chip ---------------------------------
const tray = await openTray(page, "todo");
ctx.checkValue("the Plan chip opens the tray on the todo tab", await tray.getAttribute("data-tab"), "todo");
ctx.check("the tray is a non-modal dialog", (await tray.getAttribute("role")) === "dialog" && (await tray.getAttribute("aria-modal")) === "false", {
expected: 'role=dialog aria-modal=false',
observed: { role: await tray.getAttribute("role"), modal: await tray.getAttribute("aria-modal") },
});
const tablist = tray.locator('[role="tablist"]');
const tabNames = (await tablist.locator('[role="tab"]').allInnerTexts()).map((text) => text.replace(/\s+/g, " ").trim());
ctx.check("three panel tabs exist", tabNames.length === 3, { expected: 3, observed: tabNames });
ctx.check("the tray has exactly two tabs (Todo, Tasks)", tabNames.length === 2, { expected: 2, observed: tabNames });
const tabIds = await tablist
.locator('[role="tab"]')
.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-testid")));
ctx.checkValue("panel tabs carry the documented test ids", tabIds, ["panel-tab-subagents", "panel-tab-todo", "panel-tab-tasks"]);
ctx.checkValue("tray tabs carry the documented test ids", tabIds, ["tray-tab-todo", "tray-tab-tasks"]);
ctx.checkValue("subagents are not a tray tab any more", tabIds.includes("tray-tab-subagents"), false);
const tab = (id) => page.locator(`[data-testid="panel-tab-${id}"]`);
const tab = (id) => tray.locator(`[data-testid="tray-tab-${id}"]`);
const selectedTab = () =>
tablist
.locator('[role="tab"][aria-selected="true"]')
.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-testid")));
const panelText = async () => (await page.locator(".panel-pane .panel-scroll").innerText()).replace(/\s+/g, " ");
const trayText = async () => (await tray.locator(".tray-body").innerText()).replace(/\s+/g, " ");
// Todo
// Todo (selected on open)
await tab("todo").click();
await sleep(400);
const todoText = await panelText();
const todoRows = await page.locator(".panel-pane .todo__row").count();
const todoText = await trayText();
const todoRows = await tray.locator(".todo__row").count();
ctx.check("Todo tab renders real rows or its explicit empty state", todoRows > 0 || /no todos yet/i.test(todoText), {
expected: ".todo__row or 'No todos yet'",
observed: short(todoText, 200),
});
ctx.checkValue("clicking the Todo tab selects it", await selectedTab(), ["panel-tab-todo"]);
ctx.checkValue("clicking the Todo tab selects it", await selectedTab(), ["tray-tab-todo"]);
ctx.log(`todo tab: rows=${todoRows} text=${short(todoText, 120)}`);
// Tasks
await tab("tasks").click();
await sleep(400);
const tasksText = await panelText();
const taskRows = await page.locator(".panel-pane .task-item[data-task-id]").count();
const tasksText = await trayText();
const taskRows = await tray.locator(".task-row[data-task-id]").count();
ctx.check("Tasks tab renders real rows or its explicit empty state", taskRows > 0 || /no background tasks/i.test(tasksText), {
expected: ".task-item[data-task-id] or 'No background tasks'",
expected: ".task-row[data-task-id] or 'No background tasks'",
observed: short(tasksText, 200),
});
ctx.checkValue("clicking the Tasks tab selects it", await selectedTab(), ["panel-tab-tasks"]);
ctx.checkValue("clicking the Tasks tab selects it", await selectedTab(), ["tray-tab-tasks"]);
ctx.check("Tasks tab shows no fake pid", !/\bpid\b\s*[:=]?\s*\d+/i.test(tasksText), {
expected: "no fabricated pid",
observed: short(tasksText, 200),
});
// Subagents
await tab("subagents").click();
await sleep(300);
const subagentsText = await panelText();
ctx.check("Subagents tab renders its empty state before any dispatch", /no subagents yet/i.test(subagentsText), {
expected: "No subagents yet",
observed: short(subagentsText, 200),
});
ctx.checkValue("clicking the Subagents tab selects it", await selectedTab(), ["panel-tab-subagents"]);
const allPanelCopy = `${todoText} ${tasksText} ${subagentsText}`;
const mockHits = MOCK_COPY.filter((re) => re.test(allPanelCopy)).map(String);
ctx.check("no mock/prototype copy in the panel", mockHits.length === 0, {
const allTrayCopy = `${todoText} ${tasksText}`;
const mockHits = MOCK_COPY.filter((re) => re.test(allTrayCopy)).map(String);
ctx.check("no mock/prototype copy in the tray", mockHits.length === 0, {
expected: "no mock copy",
observed: mockHits,
});
await ctx.shot(page, "b9-tray");
// --- dispatch a real subagent ----------------------------------------
await page.locator(".panel-pane button", { hasText: "Dispatch" }).first().click();
// Esc closes the tray (single-layer close chain).
await page.keyboard.press("Escape");
const trayClosed = await waitFor(async () => ((await sessionTray(page).isVisible()) ? null : true), 6000);
ctx.check("Escape closes the tray", Boolean(trayClosed), { observed: await sessionTray(page).isVisible() });
// --- dispatch a real subagent from the session row `…` menu ----------
const rowMenu = await openSessionRowMenu(page, sessionId);
ctx.checkValue("the row menu offers `Dispatch subagent`", await rowMenu.locator('[data-menu-action="dispatch"]').count(), 1);
await rowMenu.locator('[data-menu-action="dispatch"]').click();
const dialog = await dialogFor(page, "Dispatch subagent", 8000);
ctx.check("dispatch modal opens", Boolean(dialog), { observed: page.url() });
ctx.check("dispatch modal opens from the row menu", Boolean(dialog), { observed: page.url() });
await page.locator("#dispatch-task").fill("Reply with exactly SUB and nothing else.");
await page.locator("#dispatch-name").fill("e2e-ui-sub");
await dialog.getByRole("button", { name: /^Dispatch$/ }).click();
@@ -1829,9 +1962,9 @@ scenario("B9", "Panels: tab switching, empty/real states, real subagent dispatch
ctx.check("dispatch posts subagent.dispatch", Boolean(dispatchCmd), { observed: ctx.cmdRequests.map((r) => r.method) });
ctx.log(`subagent.dispatch body params: ${short(dispatchCmd?.params, 300)}`);
const subagentRows = page.locator(".tree-pane .tree-row[data-subagent-id]");
const rowOrFailure = await waitFor(async () => {
const rows = page.locator(".panel-pane .sub-item");
if ((await rows.count()) > 0) return { kind: "row" };
if ((await subagentRows.count()) > 0) return { kind: "row" };
const errors = await toastTexts(page);
const failed = errors.find((text) => /failed/i.test(text));
if (failed) return { kind: "error", text: failed };
@@ -1839,54 +1972,70 @@ scenario("B9", "Panels: tab switching, empty/real states, real subagent dispatch
}, 120000, 250);
if (rowOrFailure?.kind === "error") {
const response = ctx.cmdResponses.filter((item) => item.url.includes("/api/v1/cmd")).pop();
ctx.softCheck("dispatch creates a real subagent row", false, {
expected: ".sub-item row (or a batch) after ≤120 s",
ctx.softCheck("dispatch creates a real subagent tree row", false, {
expected: ".tree-row[data-subagent-id] (or a batch) after ≤120 s",
observed: { toast: rowOrFailure.text, lastCmdResponse: response ?? null },
});
} else {
ctx.softCheck("dispatch creates a real subagent row", rowOrFailure?.kind === "row", {
expected: ".panel-pane .sub-item",
ctx.softCheck("dispatch creates a real subagent tree row", rowOrFailure?.kind === "row", {
expected: ".tree-pane .tree-row[data-subagent-id]",
observed: rowOrFailure ?? "no row after 120 s",
});
}
if (rowOrFailure?.kind === "row") {
const subRow = page.locator(".panel-pane .sub-item").filter({ hasText: "e2e-ui-sub" }).first();
const subRow = subagentRows.filter({ hasText: "e2e-ui-sub" }).first();
const rowVisible = await waitFor(async () => ((await subRow.count()) > 0 ? true : null), 10000);
ctx.softCheck("the dispatched subagent is named e2e-ui-sub", Boolean(rowVisible), {
expected: "sub-item with e2e-ui-sub",
observed: await page.locator(".panel-pane .sub-item").allInnerTexts(),
expected: "subagent row named e2e-ui-sub",
observed: await subagentRows.allInnerTexts(),
});
if (rowVisible) {
await subRow.click();
const preview = await dialogFor(page, "Subagent", 10000);
ctx.softCheck("subagent preview modal opens", Boolean(preview), { observed: page.url() });
if (preview) {
const feed = preview.locator('[aria-label="Read-only preview"]');
const feedCount = await feed.count();
const previewText = (await preview.innerText()).replace(/\s+/g, " ");
ctx.softCheck("preview shows a real tail or an explicit empty state", feedCount > 0 || /no output|empty|running/i.test(previewText), {
expected: 'feed [aria-label="Read-only preview"]',
observed: short(previewText, 300),
// Subagents open in-place (`?sub=<id>`), not in a modal.
await subRow.locator("button.tree-row__main").click();
const child = page.locator('[data-testid="subagent-view"]');
const childOpen = await waitFor(async () => ((await child.count()) > 0 ? true : null), 15000);
ctx.softCheck("the subagent child view replaces the stream", Boolean(childOpen), {
expected: '[data-testid="subagent-view"]',
observed: page.url(),
});
if (childOpen) {
ctx.check("the child view is a `?sub=` deep link", Boolean(new URL(page.url()).searchParams.get("sub")), {
observed: page.url(),
});
const timeline = child.locator('[data-testid="sub-timeline"]');
const timelineCount = await timeline.count();
const entries = timelineCount ? await timeline.locator("[data-entry-id]").count() : 0;
const emptyState = await child.locator(".sub-empty").count();
const childText = (await child.innerText()).replace(/\s+/g, " ");
ctx.softCheck(
"the child view shows a real timeline or an explicit empty state",
timelineCount === 1 && (entries > 0 || emptyState > 0),
{
expected: '[data-testid="sub-timeline"] with entries or .sub-empty',
observed: { timeline: timelineCount, entries, emptyState },
},
);
const childMock = MOCK_COPY.filter((re) => re.test(childText)).map(String);
ctx.softCheck("the child view has no mock copy", childMock.length === 0, { observed: childMock });
await ctx.shot(page, "b9-subagent-child-view");
const back = child.locator(".sub-back");
ctx.checkValue("the child view has a `Parent` back button", await back.count(), 1);
await back.click();
const leftChild = await waitFor(
async () => ((await page.locator('[data-testid="subagent-view"]').count()) === 0 ? true : null),
10000,
);
ctx.softCheck("`Parent` returns to the session stream", Boolean(leftChild), {
expected: "no [data-testid=subagent-view]",
observed: page.url(),
});
const previewMock = MOCK_COPY.filter((re) => re.test(previewText)).map(String);
ctx.softCheck("preview has no mock copy", previewMock.length === 0, { observed: previewMock });
await ctx.shot(page, "b9-subagent-preview");
const back = preview.getByRole("button", { name: /back to parent/i });
if ((await back.count()) > 0) {
await back.click();
const closed = await waitFor(async () => ((await page.getByRole("dialog").count()) === 0 ? true : null), 8000);
ctx.softCheck("'Back to parent' closes the preview", Boolean(closed), {
observed: await page.getByRole("dialog").count(),
});
} else {
ctx.softCheck("'Back to parent' button exists", false, { observed: short(previewText, 200) });
}
}
}
}
await dismissDialogs(page);
await ctx.shot(page, "b9-panel");
await ctx.shot(page, "b9-child-view");
});
/* ------------------------------------------------------------------ */
@@ -1985,6 +2134,39 @@ scenario("B10", "Attention: the e2e_request tool surfaces the blocking dialog; A
observed: written ?? "file missing",
});
// --- v0.1.1 tool rows ------------------------------------------------
// One tool call = one row: `.tool[data-kind] > .tool__row > .tool__head`
// (`__verb` + `__target`); expanding mounts the lazy `.tool__body`.
const toolRow = page.locator('.stream-body .tool[data-kind]').first();
const toolVisible = await waitFor(async () => ((await toolRow.count()) > 0 ? true : null), 20000);
ctx.softCheck("the tool call renders as a v0.1.1 tool row", Boolean(toolVisible), {
expected: ".tool[data-kind] inside the message stream",
observed: await page.locator(".stream-body .tool").count(),
});
if (toolVisible) {
const anatomy = await toolRow.evaluate((node) => ({
kind: node.getAttribute("data-kind"),
state: node.getAttribute("data-state"),
head: Boolean(node.querySelector(".tool__head")),
verb: (node.querySelector(".tool__verb")?.textContent ?? "").trim(),
target: (node.querySelector(".tool__target")?.textContent ?? "").trim(),
body: Boolean(node.querySelector(".tool__body")),
}));
ctx.log(`tool row anatomy: ${short(anatomy, 200)}`);
ctx.softCheck("the tool row is head + verb + target", anatomy.head && anatomy.verb.length > 0 && Boolean(anatomy.kind), {
expected: ".tool__head + .tool__verb (+ .tool__target)",
observed: anatomy,
});
if (!anatomy.body) {
await toolRow.locator(".tool__head").first().click();
const opened = await waitFor(async () => ((await toolRow.locator(".tool__body").count()) > 0 ? true : null), 8000);
ctx.softCheck("expanding the tool row mounts .tool__body", Boolean(opened), {
expected: ".tool__body after clicking .tool__head",
observed: { open: Boolean(opened), anatomy },
});
}
}
if (requestId) {
const second = await cmd("attention.respond", { requestId, response: { value: "Accepted" } }, { sessionId });
ctx.softCheck("a second client cannot answer the resolved request", second.status >= 400, {
@@ -2000,12 +2182,14 @@ scenario("B10", "Attention: the e2e_request tool surfaces the blocking dialog; A
/* B11 — status page */
/* ------------------------------------------------------------------ */
const STATUS_CARDS = ["Server info", "Health checks", "Resources", "Models & providers", "Background tasks", "Paired devices", "Connection"];
// v0.1.1: the "Resources" card became the `MetricsBlock` strip (`.section-label`
// + `[data-res]` tiles), so the page carries six `.card__title` cards.
const STATUS_CARDS = ["Server info", "Health checks", "Models & providers", "Background tasks", "Paired devices", "Connection"];
scenario("B11", "Status: seven API-backed cards, devices list/revoke, disconnect clears the connection", async (ctx) => {
scenario("B11", "Status: six API-backed cards + metrics strip, devices list/revoke, disconnect clears the connection", async (ctx) => {
const { page } = await ctx.openPage("paired");
await page.goto(`${BASE}/status`, { waitUntil: "domcontentloaded" });
const titlesReady = await waitFor(async () => ((await page.locator(".card__title").count()) >= 7 ? true : null), 30000);
const titlesReady = await waitFor(async () => ((await page.locator(".card__title").count()) >= STATUS_CARDS.length ? true : null), 30000);
ctx.check("status cards render", Boolean(titlesReady), { observed: await page.locator(".card__title").count() });
const titles = (await page.locator(".card__title").allInnerTexts()).map((text) => text.replace(/\s+/g, " ").trim());
for (const expected of STATUS_CARDS) {
@@ -2046,10 +2230,12 @@ scenario("B11", "Status: seven API-backed cards, devices list/revoke, disconnect
expected: "8-character pairing code",
observed: { pairingCode, cardText: short((await connectionCard.innerText()).replace(/\s+/g, " "), 200) },
});
const pairingUrl = (await page.locator('[data-testid="pairing-url"]').innerText().catch(() => "")).trim();
ctx.softCheck("the connection card shows the pairing URL", pairingUrl.includes("/pair/"), {
expected: "<endpoint>/pair/<code> or /#pair=<code>",
observed: pairingUrl,
// v0.1.1 renders the pairing URL as a QR code (the `<canvas>` is seeded with
// `url || code`) instead of a copyable text line.
const pairingQr = await page.locator(".qr-wrap canvas").count();
ctx.softCheck("the connection card renders the pairing QR", pairingQr >= 1, {
expected: ".qr-wrap canvas",
observed: { canvases: pairingQr, cardText: short((await connectionCard.innerText()).replace(/\s+/g, " "), 200) },
});
// Devices card: lists exactly the API devices the UI does not consider revoked.
@@ -2144,8 +2330,15 @@ scenario("B12", "Reconnect: offline → online restores the composer + connectio
await context.setOffline(true);
await sleep(1500);
const offlineState = await page.evaluate(() => document.querySelector(".shell")?.getAttribute("data-ws-state") ?? null);
const offline = await waitFor(async () => (/offline/i.test(await page.locator(".chat-conn").innerText()) ? true : null), 6000);
ctx.log(`offline indicator shown: ${Boolean(offline)} (observed "${await page.locator(".chat-conn").innerText()}", shell data-ws-state=${offlineState})`);
// v0.1.1 removed the `.chat-conn` stream-head indicator: the offline state is
// carried by the composer hint (`[role=status]`, woken by `!connected`) plus
// the shell reconnect banner.
const hintText = async () => (await page.locator(".composer__hint").innerText().catch(() => "")).replace(/\s+/g, " ").trim();
const offline = await waitFor(async () => (/reconnect|lost|offline/i.test(await hintText()) ? true : null), 15000);
ctx.log(
`offline hint shown: ${Boolean(offline)} (observed "${await hintText()}", shell data-ws-state=${offlineState}, ` +
`reconnect banner=${await page.locator('[data-testid="reconnect-banner"]').count()})`,
);
await context.setOffline(false);
ctx.offlineWindow = false;
@@ -2165,10 +2358,10 @@ scenario("B12", "Reconnect: offline → online restores the composer + connectio
expected: "textarea enabled",
observed: { composer: await composerState(page) },
});
const online = await waitFor(async () => (/online/i.test(await page.locator(".chat-conn").innerText()) ? true : null), 30000);
ctx.check("the connection indicator returns to open/Online", Boolean(online), {
expected: "Online",
observed: await page.locator(".chat-conn").innerText(),
const online = await waitFor(async () => ((await page.locator(".composer__hint").count()) === 0 ? true : null), 30000);
ctx.check("the offline hint disappears once the socket is back", Boolean(online), {
expected: "no .composer__hint",
observed: await hintText(),
});
const { snapshots, appended } = entryIdsFromFrames(ctx.wsFrames, pong.sessionId);
@@ -2347,43 +2540,48 @@ scenario("B14", "i18n + theme: language menu switches html[lang]/copy, theme seg
ctx.checkValue("English heading", (await h1.innerText()).trim(), "Workspaces");
ctx.checkValue("html lang starts as en-US", await page.evaluate(() => document.documentElement.lang), "en-US");
const langButton = page.locator('button[aria-label^="Language"]');
await langButton.click();
await page.getByRole("menuitemradio", { name: /chinese/i }).click();
// v0.1.1: the topbar preference menu (appearance + language) replaces the
// old standalone language/theme triggers. Locate it by class/data hooks so
// the check never depends on a copy string.
const prefTrigger = page.locator(".pref-trigger");
ctx.check("one preference trigger in the topbar", (await prefTrigger.count()) === 1, { observed: await prefTrigger.count() });
await prefTrigger.click();
await page.locator('[data-lang-seg] [data-lang="zh"]').click();
const zhApplied = await waitFor(async () => ((await page.evaluate(() => document.documentElement.lang)) === "zh-CN" ? true : null), 10000);
ctx.check("switching to zh updates html[lang]", Boolean(zhApplied), {
expected: "zh-CN",
observed: await page.evaluate(() => document.documentElement.lang),
});
ctx.checkValue("visible copy switches to Chinese", (await h1.innerText()).trim(), "工作空间");
const zhNav = (await page.locator(".sidebar .nav-item").allInnerTexts()).map((text) => text.replace(/\s+/g, " ").trim());
const zhNav = await navItemLabels(page);
ctx.checkValue("visible nav labels switch to Chinese", zhNav, ["工作空间", "对话", "状态"]);
const zhNavLabel = (await page.locator(".sidebar .nav-label").innerText()).trim();
ctx.checkValue("the nav container label switches to Chinese", zhNavLabel, "控制台");
const zhNavLabel = (await page.locator(".sidebar").getAttribute("aria-label")) ?? "";
ctx.checkValue("the nav container label switches to Chinese", zhNavLabel.trim(), "控制台");
const zhBody = await bodyText(page);
ctx.check("no raw i18n keys leak after the switch", !/\b(chat|nav|status|workspaces|connect)\.[a-zA-Z][a-zA-Z0-9]*/.test(zhBody), {
observed: short(zhBody.replace(/\s+/g, " "), 200),
});
ctx.checkValue("language is persisted to pi2-lang", await page.evaluate(() => localStorage.getItem("pi2-lang")), "zh");
await page.locator('button[aria-label^="语言"]').click();
await page.getByRole("menuitemradio", { name: /英文|english/i }).click();
await prefTrigger.click();
await page.locator('[data-lang-seg] [data-lang="en"]').click();
const enApplied = await waitFor(async () => ((await page.evaluate(() => document.documentElement.lang)) === "en-US" ? true : null), 10000);
ctx.check("switching back restores English", Boolean(enApplied), {
expected: "en-US",
observed: await page.evaluate(() => document.documentElement.lang),
});
ctx.checkValue("English copy is restored", (await h1.innerText()).trim(), "Workspaces");
const enNav = (await page.locator(".sidebar .nav-item").allInnerTexts()).map((text) => text.replace(/\s+/g, " ").trim());
const enNav = await navItemLabels(page);
ctx.checkValue("nav labels are restored to English", enNav, ["Workspaces", "Chat", "Status"]);
// --- theme ------------------------------------------------------------
const themeGroup = page.locator('[role="group"][aria-label="Theme"]');
await prefTrigger.click();
const themeGroup = page.locator("[data-theme-seg]");
ctx.check("theme segment exists", (await themeGroup.count()) === 1, { observed: await themeGroup.count() });
const themeAttr = () => page.evaluate(() => document.documentElement.getAttribute("data-theme"));
const storedTheme = () => page.evaluate(() => localStorage.getItem("pi2-theme"));
await themeGroup.getByRole("button", { name: /^dark$/i }).click();
await themeGroup.locator('[data-v="dark"]').click();
ctx.check("dark theme sets html[data-theme=dark]", (await waitFor(async () => ((await themeAttr()) === "dark" ? true : null), 5000)) ?? false, {
expected: "dark",
observed: await themeAttr(),
@@ -2393,12 +2591,13 @@ scenario("B14", "i18n + theme: language menu switches html[lang]/copy, theme seg
await h1.waitFor({ state: "visible", timeout: 20000 });
ctx.checkValue("dark theme survives a reload", await themeAttr(), "dark");
await themeGroup.getByRole("button", { name: /^light$/i }).click();
await prefTrigger.click();
await page.locator('[data-theme-seg] [data-v="light"]').click();
ctx.check("light theme sets html[data-theme=light]", (await waitFor(async () => ((await themeAttr()) === "light" ? true : null), 5000)) ?? false, {
expected: "light",
observed: await themeAttr(),
});
await themeGroup.getByRole("button", { name: /^auto$|^system$/i }).click();
await page.locator('[data-theme-seg] [data-v="system"]').click();
const systemStored = await waitFor(async () => ((await storedTheme()) === "system" ? true : null), 5000);
ctx.check("system theme is persisted as 'system'", Boolean(systemStored), { expected: "system", observed: await storedTheme() });
ctx.check("system theme resolves to light|dark", ["light", "dark"].includes(await themeAttr()), { observed: await themeAttr() });
@@ -2450,7 +2649,7 @@ scenario("C1", "Responsive: 1440×900 / 768×1024 / 380×780 on all four pages h
kind: "paired",
anchor: ".stream-head, .stream-body",
},
{ name: "status", path: "/status", kind: "paired", anchor: ".status-grid" },
{ name: "status", path: "/status", kind: "paired", anchor: ".status-page" },
{ name: "connect", path: "/connect", kind: "unpaired", anchor: ".cn" },
];
@@ -2487,40 +2686,75 @@ async function navState(page) {
return style.display !== "none" && style.visibility !== "hidden" && rect.width > 0 && rect.height > 0;
};
const result = {};
for (const [key, selector] of [["sidebar", ".sidebar"], ["rail", ".rail"], ["tabbar", ".tabbar"]]) {
// v0.1.1: only the icon strip (sidebar ≥840 / rail 600–839) exists;
// below 600 the topbar `.page-pill` owns navigation; no mobile strip.
for (const [key, selector] of [["sidebar", ".sidebar"], ["rail", ".rail"]]) {
const element = document.querySelector(selector);
result[key] = element && visible(element) ? element.querySelectorAll(".nav-item").length : null;
}
result.totalNavItems = document.querySelectorAll(".sidebar .nav-item, .rail .nav-item, .tabbar .nav-item").length;
result.tabbar = document.querySelectorAll(".tabbar").length;
result.totalNavItems = document.querySelectorAll(".sidebar .nav-item, .rail .nav-item").length;
const pill = document.querySelector(".page-pill");
result.pagePill = pill && visible(pill) ? (pill.getAttribute("aria-expanded") === "true" ? "open" : "closed") : null;
result.pageSheets = document.querySelectorAll('[role="dialog"] .sheet-row').length;
return result;
});
}
scenario("C2", "Nav: 3 items in the visible container at each breakpoint on nav pages, 0 on /connect", async (ctx) => {
scenario("C2", "Nav: 3 icon rows in the one visible container (sidebar/rail), <600 page pill + sheet, 0 on /connect", async (ctx) => {
for (const viewport of VIEWPORTS) {
const { page } = await ctx.openPage("paired", { viewport: { width: viewport.width, height: viewport.height } });
await page.goto(`${BASE}/workspaces`, { waitUntil: "domcontentloaded" });
await page.locator("[data-workspace-id], .empty").first().waitFor({ state: "visible", timeout: 30000 }).catch(() => undefined);
const state_ = await navState(page);
const active = ["sidebar", "rail", "tabbar"].filter((key) => state_[key] !== null);
const expectedContainer = viewport.width >= 840 ? "sidebar" : viewport.width >= 600 ? "rail" : "tabbar";
ctx.check(`${viewport.name}: exactly one nav container is visible`, active.length === 1, { observed: state_ });
ctx.check(`${viewport.name}: the expected container (${expectedContainer}) is the visible one`, active[0] === expectedContainer, {
expected: expectedContainer,
observed: active,
});
ctx.check(`${viewport.name}: 3 nav items`, state_[expectedContainer] === 3, {
expected: 3,
observed: state_[expectedContainer],
});
const expectedContainer = viewport.width >= 840 ? "sidebar" : viewport.width >= 600 ? "rail" : null;
ctx.checkValue(`${viewport.name}: no mobile tabbar is rendered`, state_.tabbar, 0);
if (expectedContainer) {
const active = ["sidebar", "rail"].filter((key) => state_[key] !== null);
ctx.check(`${viewport.name}: exactly one nav container is visible`, active.length === 1, { observed: state_ });
ctx.check(`${viewport.name}: the expected container (${expectedContainer}) is the visible one`, active[0] === expectedContainer, {
expected: expectedContainer,
observed: active,
});
ctx.check(`${viewport.name}: 3 nav items`, state_[expectedContainer] === 3, {
expected: 3,
observed: state_[expectedContainer],
});
ctx.checkValue(`${viewport.name}: the page pill is hidden above 600`, state_.pagePill, null);
const labels = await navItemLabels(page);
ctx.checkValue(`${viewport.name}: nav rows are labelled by aria-label`, labels, ["Workspaces", "Chat", "Status"]);
} else {
const active = ["sidebar", "rail"].filter((key) => state_[key] !== null);
ctx.check(`${viewport.name}: no persistent nav strip below 600`, active.length === 0, { observed: state_ });
ctx.checkValue(`${viewport.name}: the page pill carries navigation`, state_.pagePill, "closed");
await page.locator(".page-pill").click();
const sheetOpen = await waitFor(async () => ((await navState(page)).pageSheets > 0 ? true : null), 8000);
ctx.check(`${viewport.name}: the page pill opens a sheet`, Boolean(sheetOpen), {
expected: 'a [role="dialog"] with .sheet-row entries',
observed: (await navState(page)).pageSheets,
});
const sheet = page.getByRole("dialog").first();
const current = await page.locator('[role="dialog"] .sheet-row[aria-current="page"]').allInnerTexts();
ctx.check(`${viewport.name}: the sheet marks the current page`, current.length === 1, {
expected: "1 row with aria-current=page",
observed: current.map((text) => text.replace(/\s+/g, " ").trim()),
});
// The page rows are plain router links, so the target is locale-free.
await sheet.locator('a.sheet-row[href="/chat"]').first().click();
const navigated = await waitFor(async () => (new URL(page.url()).pathname.startsWith("/chat") ? true : null), 15000);
ctx.check(`${viewport.name}: the sheet navigates to the picked page`, Boolean(navigated), {
expected: "/chat",
observed: page.url(),
});
}
await page.context().close();
const { page: connectPage } = await ctx.openPage("unpaired", { viewport: { width: viewport.width, height: viewport.height } });
await connectPage.goto(`${BASE}/connect`, { waitUntil: "domcontentloaded" });
await connectPage.locator(".cn h1").waitFor({ state: "visible", timeout: 20000 }).catch(() => undefined);
const connectState = await navState(connectPage);
ctx.check(`${viewport.name}: /connect has no nav rail/tabbar`, connectState.totalNavItems === 0, {
expected: 0,
ctx.check(`${viewport.name}: /connect has no nav strip, tabbar or page pill`, connectState.totalNavItems === 0 && connectState.tabbar === 0 && connectState.pagePill === null, {
expected: { totalNavItems: 0, tabbar: 0, pagePill: null },
observed: connectState,
});
await connectPage.context().close();
+913
View File
@@ -0,0 +1,913 @@
/**
* Fixture data for the web-console visual harness (`scripts/ui-mock-server.mjs`
* + `scripts/ui-shots.mjs`).
*
* Shapes are taken from `web/src/lib/api.ts` and `src/protocol/types.ts` — the
* wire contract, not a UI model. Two families deliberately coexist:
*
* - REST history entries are **raw pi entries** (`message` / `toolResult` /
* `custom`), which `web/src/lib/entry-projection.ts` projects. That is the
* real `GET /api/v1/sessions/:sid/entries` payload.
* - `state.entries` (only used by the legacy session) carries **Block-shaped**
* entries, including the pre-0.2 tool DTO (`input` / `result` / `text` /
* `diff`) that `tools/adapt.ts` has to keep working.
*
* Nothing here talks to a daemon, a plugin or the network.
*/
/** Local CLI token the mock accepts for `POST /api/v1/console/session`. */
export const MOCK_CLI_TOKEN = "mock-cli-token-0000000000000000000000";
/** Device token the mock mints for the local browser (base64url-ish, ≥20 chars). */
export const MOCK_DEVICE_TOKEN = "mock-device-token-0000000000000000000000";
/** Second device token (a phone that paired earlier). */
export const MOCK_PHONE_TOKEN = "mock-phone-token-11111111111111111111111";
export const MOCK_DAEMON_ID = "d-mock-0f3a9c";
const MINUTE = 60_000;
/** Fixed "now" for the running instance; callers may override. */
export function buildFixtures(now = Date.now()) {
const iso = (ts) => new Date(ts).toISOString();
const t0 = now - 42 * MINUTE;
/* ---------------------------------------------------------------- */
/* raw pi entries: helpers */
/* ---------------------------------------------------------------- */
const userEntry = (id, ts, text) => ({
type: "message",
id,
timestamp: iso(ts),
message: { role: "user", timestamp: ts, content: [{ type: "text", text }] },
});
const assistantEntry = (id, ts, content, extra = {}) => ({
type: "message",
id,
timestamp: iso(ts),
message: { role: "assistant", timestamp: ts, content, ...extra },
});
const toolCall = (id, name, args) => ({ type: "toolCall", id, name, arguments: args });
const toolResult = (id, ts, { toolCallId, toolName, text, isError = false, details }) => ({
type: "message",
id,
timestamp: iso(ts),
message: {
role: "toolResult",
toolCallId,
toolName,
timestamp: ts,
content: [{ type: "text", text }],
isError,
...(details !== undefined ? { details } : {}),
},
});
const todoCheckpoint = (id, ts, todos) => ({
type: "custom",
id,
timestamp: iso(ts),
customType: "pi2-todo",
data: {
todos,
completed: todos.filter((todo) => todo.status === "completed").length,
total: todos.length,
},
});
/* ---------------------------------------------------------------- */
/* todo / task / batch / subagent state */
/* ---------------------------------------------------------------- */
const MAIN_TODOS = [
{ content: "Port v0.1.1 tokens (light/dark)", status: "completed", activeForm: "Porting tokens" },
{ content: "Replace .tabbar with the 56px nav rail", status: "in_progress", activeForm: "Replacing .tabbar" },
{ content: "Tool family renderer for 22 tools", status: "in_progress", activeForm: "Rendering tool families" },
{ content: "Visual harness: mock API + screenshots", status: "pending", activeForm: "Building the visual harness" },
];
const MAIN_TASKS = [
{
id: "task-1",
command: "pnpm --dir web build",
status: "running",
startTime: now - 38_000,
durationMs: 38_000,
exitCode: null,
outputFile: "/tmp/pi2-mock/tasks/task-1.log",
},
{
id: "task-2",
command: "bash scripts/smoke.sh",
status: "completed",
startTime: now - 9 * MINUTE,
durationMs: 41_200,
exitCode: 0,
outputFile: "/tmp/pi2-mock/tasks/task-2.log",
},
{
id: "task-3",
command: "pnpm --dir web exec vitest run tests/tools.kind.test.tsx",
status: "failed",
startTime: now - 21 * MINUTE,
durationMs: 7_640,
exitCode: 1,
},
];
const MAIN_BATCHES = [
{
batchId: "batch-1",
status: "running",
items: [
{ ref: "sa-shell", name: "WS-A shell", status: "running" },
{ ref: "sa-workspaces", name: "WS-B pages", status: "ok" },
{ ref: "sa-tools", name: "WS-C tools", status: "failed", error: "typecheck: 2 errors" },
{ ref: "sa-stream", name: "WS-E stream", status: "queued" },
],
summary: { total: 4, done: 2, ok: 1, failed: 1, cancelled: 0, running: 1 },
},
{
batchId: "batch-0",
status: "partial",
items: [
{ ref: "sa-audit", name: "contract audit", status: "ok" },
{ ref: "sa-digest", name: "digest pass", status: "cancelled" },
],
summary: { total: 2, done: 2, ok: 1, failed: 0, cancelled: 1, running: 0 },
},
];
const MAIN_SUBAGENTS = [
{
id: "sa-shell",
name: "WS-A shell",
status: "active",
model: "claude-sonnet-4.5",
thinking: "high",
task: "Rewrite tokens + nav rail, drop .tabbar",
createdAt: t0 + 2 * MINUTE,
lastActiveAt: now - 12_000,
live: true,
visible: true,
parentId: "s-main",
children: [
{
id: "sa-tokens",
name: "tokens.css",
status: "completed",
model: "claude-sonnet-4.5",
task: "Swap the three-stage token set",
createdAt: t0 + 3 * MINUTE,
lastActiveAt: now - 14 * MINUTE,
visible: true,
},
{
id: "sa-palette",
name: "⌘K palette",
status: "failed",
model: "claude-sonnet-4.5",
task: "Esc must restore focus to the trigger",
createdAt: t0 + 5 * MINUTE,
lastActiveAt: now - 8 * MINUTE,
visible: true,
},
],
},
{
id: "sa-tools",
name: "WS-C tools",
status: "dormant",
model: "gpt-5.1-codex",
thinking: "medium",
task: "22 tool names → 4 display states",
createdAt: t0 + 9 * MINUTE,
lastActiveAt: now - 6 * MINUTE,
live: false,
visible: false,
parentId: "s-main",
},
{
id: "sa-stream",
name: "WS-E stream",
status: "interrupted",
task: "queued messages render once",
createdAt: t0 + 12 * MINUTE,
lastActiveAt: now - 3 * MINUTE,
visible: true,
},
];
/**
* Pending `confirm` attention. It hangs off `s-attention` (never the session
* the screenshot matrix opens) because the console's attention modal is
* blocking by design: putting it on `s-main` would hide the chat page behind
* a dialog that only an answer or a timeout can close.
*/
const MAIN_ATTENTION = [
{
requestId: "att-1",
method: "confirm",
title: "Allow `write` to docs/ui-parity.md?",
message: "The agent wants to create the harness documentation inside the repo.",
options: [
{ id: "allow_once", label: "Allow once" },
{ id: "allow_session", label: "Allow for this session" },
{ id: "deny", label: "Deny" },
],
createdAt: now - 40_000,
receivedAt: now - 39_500,
timeoutSec: 120,
},
];
const MAIN_QUEUE = [
{ id: "q-1", text: "Also assert the /connect page has no server chip.", steer: false },
{ id: "q-2", text: "Re-run the matrix once WS-A lands.", steer: true },
];
/* ---------------------------------------------------------------- */
/* history: the main session */
/* ---------------------------------------------------------------- */
const mainEntries = [
userEntry("e-01", t0, "Port the v0.1.1 shell. Do not touch the wire protocol, and keep the old DTO working."),
assistantEntry("e-02", t0 + 20_000, [
{
type: "thinking",
thinking:
"Three invariants decide this: the protocol stays put, tools degrade on old fields, and the nav rail replaces .tabbar below 600px.",
},
{
type: "text",
text: "Plan: tokens first, then the shell, then the tool families. I re-read `docs/protocol.md` §3.3 before touching anything.",
},
toolCall("call-bash-1", "bash", {
command: "pnpm --dir web typecheck",
description: "baseline typecheck",
timeout: 120_000,
}),
]),
toolResult("e-03", t0 + 26_000, {
toolCallId: "call-bash-1",
toolName: "bash",
text: "> tsc --noEmit\n\n(no output)\nexit 0",
details: { exitCode: 0, durationMs: 5_420 },
}),
assistantEntry("e-04", t0 + 30_000, [
{
type: "text",
text: "Baseline is green. Now the token swap — the shorthand names stay, only the values move.",
},
toolCall("call-edit-1", "edit", {
path: "web/src/styles/tokens.css",
oldText: " --tabbar-h: 3.75rem;\n --topbar-h: 3.25rem;",
newText: " --topbar-h: 3.25rem;\n --rail-w: 3.5rem;",
}),
]),
toolResult("e-05", t0 + 31_500, {
toolCallId: "call-edit-1",
toolName: "edit",
text: "Applied 1 edit to web/src/styles/tokens.css",
details: { path: "web/src/styles/tokens.css", additions: 1, deletions: 1 },
}),
assistantEntry("e-06", t0 + 40_000, [
{
type: "text",
text: "Removing the tabbar variable breaks three rules; let me find every consumer.",
},
toolCall("call-grep-1", "grep", {
pattern: "tabbar",
path: "web/src",
ignoreCase: true,
}),
]),
toolResult("e-07", t0 + 41_000, {
toolCallId: "call-grep-1",
toolName: "grep",
text: [
"web/src/styles/app.css:106 /* tabbar <600 */",
"web/src/styles/app.css:107 .tabbar {",
"web/src/styles/app.css:131 .main { padding-bottom: calc(var(--tabbar-h) + var(--space-6)); }",
"web/src/styles/pages/chat.css:1079 height: calc(100dvh - var(--topbar-h) - var(--tabbar-h));",
"web/src/components/app-shell.tsx:251 <nav className=\"tabbar\">",
].join("\n"),
details: { matches: 5, files: 3 },
}),
assistantEntry("e-08", t0 + 50_000, [
{
type: "text",
text: "Checking whether the prototype published a nav-rail spec before I invent one.",
},
toolCall("call-search-1", "web_search", {
query: "pi2 web console nav rail 56px icon-only design tokens",
numResults: 5,
}),
]),
toolResult("e-09", t0 + 58_000, {
toolCallId: "call-search-1",
toolName: "web_search",
text: [
"1. pi2-web-ui-design v0.1.1 — CHG-04 nav rail",
" https://example.invalid/pi2-web-ui-design#chg-04",
"2. Design tokens: three-stage light/dark",
" https://example.invalid/tokens",
].join("\n"),
details: { results: 2, provider: "mock-search" },
}),
assistantEntry("e-10", t0 + 60_000, [
toolCall("call-todo-1", "todo_write", {
todos: MAIN_TODOS.map(({ content, status, activeForm }) => ({ content, status, activeForm })),
}),
]),
toolResult("e-11", t0 + 60_400, {
toolCallId: "call-todo-1",
toolName: "todo_write",
text: "Todos updated: 1 completed, 2 in progress, 1 pending",
}),
todoCheckpoint("e-12", t0 + 60_500, MAIN_TODOS),
assistantEntry("e-12b", t0 + 62_000, [
{
type: "text",
text: "The shell and the tool families are independent, so I fan them out. Each child owns an exclusive file set.",
},
toolCall("call-dispatch-1", "dispatch_subagents", {
tasks: [
{ name: "WS-A shell", prompt: "tokens.css + app.css + app-shell.tsx", files: ["web/src/styles/**"] },
{ name: "WS-C tools", prompt: "22 tool names → 4 display states", files: ["web/src/features/chat/tools/**"] },
],
parallel: true,
}),
]),
toolResult("e-13", t0 + 63_000, {
toolCallId: "call-dispatch-1",
toolName: "dispatch_subagents",
text: "dispatched 2 subagents (batch-1)",
details: { batchId: "batch-1", refs: ["sa-shell", "sa-tools"] },
}),
assistantEntry("e-14", t0 + 70_000, [
{
type: "text",
text: "The repo has an MCP bridge, so let me open the tracking issue from here.",
},
toolCall("call-mcp-1", "mcp__github__create_issue", {
owner: "zgs225",
repo: "pi2d",
title: "visual harness: assert .tabbar is gone",
body: "Seeded by scripts/ui-mock-server.mjs — an unknown tool the web client must render generically.",
}),
]),
toolResult("e-15", t0 + 73_000, {
toolCallId: "call-mcp-1",
toolName: "mcp__github__create_issue",
text: '{"number":42,"state":"open","html_url":"https://example.invalid/zgs225/pi2d/issues/42"}',
details: { server: "github", tool: "create_issue" },
}),
assistantEntry("e-16", t0 + 80_000, [
{ type: "text", text: "One command deliberately fails so the error styling is covered:" },
toolCall("call-bash-2", "bash", {
command: "pnpm --dir web exec vitest run tests/status-page.test.tsx",
description: "run the failing status page test",
}),
]),
toolResult("e-17", t0 + 88_000, {
toolCallId: "call-bash-2",
toolName: "bash",
text: [
" FAIL tests/status-page.test.tsx > StatusPage > renders the tasks card",
"AssertionError: expected 0 to be greater than 0",
" at tests/status-page.test.tsx:64:31",
"Tests 1 failed | 172 passed (173)",
].join("\n"),
isError: true,
details: { exitCode: 1, durationMs: 8_120 },
}),
assistantEntry("e-18", t0 + 90_000, [
{
type: "text",
text: "Known baseline failure (documented in PLAN §3.1). Meanwhile the docs update is being written:",
},
toolCall("call-write-1", "write", {
path: "docs/ui-parity.md",
content: "# UI parity harness\n\n…",
}),
]),
// No toolResult for `call-write-1`: the block stays `pending` (spinner).
assistantEntry("e-19", now - 8_000, [
{
type: "text",
text: "Writing the docs now. Queue is open — send steer notes if the matrix needs another breakpoint.",
},
]),
];
/* ---------------------------------------------------------------- */
/* history: child session, legacy DTO session, plain session */
/* ---------------------------------------------------------------- */
const childEntries = [
userEntry("c-01", t0 + 64_000, "Only touch web/src/features/chat/tools/**. Never web/src/pages/**."),
assistantEntry("c-02", t0 + 66_000, [
{ type: "thinking", thinking: "The mapping table is the contract: 22 names, 9 states, 4 displays." },
{
type: "text",
text: "Reading the digest for the tool-kind table first — the tests pin the exact mapping.",
},
toolCall("call-bash-c1", "bash", { command: "sed -n '1,120p' /tmp/pi2d-port/digests/03-tools.md" }),
]),
toolResult("c-03", t0 + 67_500, {
toolCallId: "call-bash-c1",
toolName: "bash",
text: "## 03 — tool families\n\nbash/exec → shell; edit/write/apply_patch → edit; …",
}),
assistantEntry("c-04", now - 15_000, [
{ type: "text", text: "Mapping extracted; writing `tools/kind.ts` next." },
]),
];
const legacyEntries = [
userEntry("l-01", t0 + 100_000, "Replay an old daemon's entry stream: the tool DTO still has input/result/text/diff."),
{
type: "message",
id: "l-02",
timestamp: iso(t0 + 101_000),
message: {
role: "assistant",
timestamp: t0 + 101_000,
content: [{ type: "text", text: "Legacy shapes below — the adapter must normalise them, not crash." }],
},
},
];
/** Block-shaped `state.entries` for the legacy session (old tool DTO + notice). */
const legacyStateEntries = [
{
id: "l-blocks-1",
role: "assistant",
ts: t0 + 102_000,
done: true,
blocks: [
{
type: "tool",
toolCallId: "legacy-call-1",
name: "bash",
// Pre-0.2 DTO: `input` instead of `args`.
input: { command: "ls -la web/dist/assets | head -3" },
// …`result` instead of `output`, `text` instead of `output.text`.
result: { text: "index-D95FiwHJ.css\nindex-CltlYEg7.js", exitCode: 0 },
text: "index-D95FiwHJ.css\nindex-CltlYEg7.js",
state: "done",
},
{
type: "tool",
toolCallId: "legacy-call-2",
name: "edit",
input: { path: "web/src/styles/app.css", old_string: ".tabbar { display: flex; }", new_string: "" },
result: { text: "Applied 1 edit" },
// Pre-0.2 DTO carried a prerendered unified diff.
diff: "--- a/web/src/styles/app.css\n+++ b/web/src/styles/app.css\n@@ -151,1 +151,0 @@\n-@media (max-width: 599px) { .tabbar { display: flex; } }\n",
state: "done",
},
],
},
{
id: "l-notice-1",
role: "notice",
ts: t0 + 104_000,
done: true,
blocks: [{ type: "text", text: "Sub-agent WS-C finished: 22 tools mapped, 1 legacy path kept." }],
},
];
const plainEntries = [
userEntry("p-01", now - 5 * 3_600_000, "Old session, nothing running: the empty-idle state must still render."),
assistantEntry("p-02", now - 5 * 3_600_000 + 30_000, [
{ type: "text", text: "Done. This session is idle with no queue, no attention and no tasks." },
]),
];
/* ---------------------------------------------------------------- */
/* sessions */
/* ---------------------------------------------------------------- */
const baseSession = (overrides) => ({
sessionId: "",
workspaceId: "ws-main",
cwd: "/home/pi2/Workspace/Neovim/pi2d",
name: null,
status: "idle",
flags: { attention: false, done: true, error: false },
model: { provider: "anthropic", id: "claude-sonnet-4.5" },
thinking: "high",
usage: { input: 184_320, output: 26_880, cacheRead: 92_400, cacheWrite: 8_192, cost: 1.8421 },
contextUsage: { tokens: 148_512, window: 200_000, percent: 74 },
queue: [],
todos: [],
tasks: [],
batches: [],
subagents: [],
attention: [],
entries: [],
...overrides,
});
const sessions = [
baseSession({
sessionId: "s-main",
name: "Port v0.1.1 shell + tool families",
status: "busy",
// No pending attention here: this is the session the screenshot matrix
// opens, and the attention modal is blocking (it cannot be dismissed),
// so a pending request would hide the page under a dialog. Attention
// lives on `s-attention` below, where the tree still shows the dot.
flags: { attention: false, done: false, error: false },
queue: MAIN_QUEUE,
todos: MAIN_TODOS,
tasks: MAIN_TASKS,
batches: MAIN_BATCHES,
subagents: MAIN_SUBAGENTS,
lastActiveAt: now - 8_000,
}),
baseSession({
sessionId: "s-child",
name: "WS-C tool families",
status: "idle",
parentId: "s-main",
visible: true,
task: "22 tool names → kind mapping + 4 display states",
todos: [
{ content: "kind.ts mapping table", status: "completed" },
{ content: "state.ts: 9 → 4", status: "in_progress", activeForm: "Collapsing tool states" },
],
contextUsage: { tokens: 41_200, window: 200_000, percent: 21 },
usage: { input: 52_100, output: 9_640, cacheRead: 12_000, cacheWrite: 2_048, cost: 0.421 },
lastActiveAt: now - 15_000,
}),
baseSession({
sessionId: "s-attention",
name: "Diff review: web/src/styles/tokens.css",
status: "idle",
flags: { attention: true, done: false, error: false },
attention: [
...MAIN_ATTENTION,
{
requestId: "att-diff-1",
method: "diff",
title: "Review the token rewrite",
message: "3 files changed by sub-agent WS-A.",
payload: {
files: [
{
path: "web/src/styles/tokens.css",
before: ":root {\n --tabbar-h: 3.75rem;\n --topbar-h: 3.25rem;\n}\n",
after: ":root {\n --topbar-h: 3.25rem;\n --rail-w: 3.5rem;\n}\n",
},
{
path: "web/src/styles/app.css",
before: "@media (max-width: 599px) { .tabbar { display: flex; } }\n",
after: "@media (max-width: 599px) { .rail { display: none; } }\n",
},
],
},
createdAt: now - 3 * MINUTE,
receivedAt: now - 3 * MINUTE + 250,
},
],
usage: { input: 8_400, output: 1_200, cacheRead: 0, cacheWrite: 0, cost: 0.052 },
contextUsage: { tokens: 9_600, window: 200_000, percent: 5 },
lastActiveAt: now - 3 * MINUTE,
}),
baseSession({
sessionId: "s-hidden",
name: "scratch: token experiment",
status: "exited",
visible: false,
flags: { attention: false, done: true, error: true },
model: { provider: "openai", id: "gpt-5.1-codex" },
thinking: "medium",
usage: { input: 3_200, output: 800, cacheRead: 0, cacheWrite: 0, cost: 0.021 },
contextUsage: { tokens: 4_000, window: 128_000, percent: 3 },
lastActiveAt: now - 34 * MINUTE,
}),
baseSession({
sessionId: "s-legacy",
name: "legacy DTO replay",
status: "idle",
visible: true,
entries: legacyStateEntries,
usage: { input: 2_040, output: 640, cacheRead: 0, cacheWrite: 0, cost: 0.011 },
contextUsage: { tokens: 2_680, window: 128_000, percent: 2 },
lastActiveAt: now - 52 * MINUTE,
}),
baseSession({
sessionId: "s-idle",
name: "nightly smoke run",
status: "idle",
usage: { input: 1_100, output: 300, cacheRead: 0, cacheWrite: 0, cost: 0.006 },
contextUsage: { tokens: 1_400, window: 128_000, percent: 1 },
lastActiveAt: now - 5 * 3_600_000,
}),
];
const entryPages = {
"s-main": mainEntries,
"s-child": childEntries,
"s-attention": legacyEntries,
"s-hidden": [],
"s-legacy": legacyEntries,
"s-idle": plainEntries,
};
/* ---------------------------------------------------------------- */
/* workspaces */
/* ---------------------------------------------------------------- */
const readyInstance = (workspaceId, overrides = {}) => ({
workspaceId,
instanceId: `inst-${workspaceId}`,
status: "ready",
nvimPid: 41_022,
pluginVersion: "1.8.0",
hasUI: true,
attachedClients: 2,
listenAddr: "/run/user/1000/pi2/i/ab12.sock",
startedAt: now - 47 * MINUTE,
...overrides,
});
const workspaces = [
{
workspaceId: "ws-main",
cwd: "/home/pi2/Workspace/Neovim/pi2d",
name: "pi2d",
alias: "web console",
pinned: true,
hidden: false,
trusted: true,
exists: true,
sessionCount: 6,
liveCount: 4,
lastActiveAt: now - 8_000,
instance: readyInstance("ws-main"),
visibility: "default",
},
{
workspaceId: "ws-nvim",
cwd: "/home/pi2/Workspace/Neovim/pi2.nvim",
name: "pi2.nvim",
pinned: false,
hidden: false,
trusted: true,
exists: true,
sessionCount: 3,
liveCount: 1,
lastActiveAt: now - 26 * MINUTE,
instance: readyInstance("ws-nvim", {
instanceId: "inst-ws-nvim",
nvimPid: 41_310,
hasUI: false,
attachedClients: 1,
startedAt: now - 2 * 3_600_000,
}),
visibility: "default",
},
{
workspaceId: "ws-docs",
cwd: "/home/pi2/Workspace/Misc/pi2-web-ui-design",
name: "pi2-web-ui-design",
alias: null,
pinned: false,
hidden: false,
trusted: false,
exists: true,
sessionCount: 1,
liveCount: 0,
lastActiveAt: now - 3 * 3_600_000,
instance: null,
visibility: "default",
},
{
workspaceId: "ws-hidden",
cwd: "/home/pi2/Workspace/Scratch/token-experiment",
name: "token-experiment",
alias: null,
pinned: false,
hidden: true,
trusted: true,
exists: true,
sessionCount: 2,
liveCount: 0,
lastActiveAt: now - 34 * MINUTE,
instance: null,
visibility: "secondary",
visibilityReason: "hidden",
},
{
workspaceId: "ws-tmp",
cwd: "/tmp/pi2-visual-ws.MDdJQT",
name: "pi2-visual-ws.MDdJQT",
alias: null,
pinned: false,
hidden: false,
trusted: true,
exists: true,
sessionCount: 1,
liveCount: 1,
lastActiveAt: now - 12 * MINUTE,
instance: readyInstance("ws-tmp", {
instanceId: "inst-ws-tmp",
nvimPid: 41_877,
hasUI: false,
attachedClients: 0,
status: "degraded",
reason: "plugin handshake timed out",
}),
visibility: "secondary",
visibilityReason: "temp",
},
{
workspaceId: "ws-ghost",
cwd: "/home/pi2/Workspace/Moved/away",
name: "away",
alias: null,
pinned: false,
hidden: false,
trusted: true,
exists: false,
sessionCount: 4,
liveCount: 0,
lastActiveAt: now - 22 * 3_600_000,
instance: null,
visibility: "secondary",
visibilityReason: "ghost",
},
];
/* ---------------------------------------------------------------- */
/* daemon surfaces */
/* ---------------------------------------------------------------- */
const info = {
v: 1,
daemonId: MOCK_DAEMON_ID,
machineId: MOCK_DAEMON_ID,
platform: "linux",
name: "pi2-mock",
hostname: "k3sagent01",
os: "Linux 6.1.0-27-amd64",
version: "0.2.0-mock",
pluginVersion: "1.8.0",
host: "127.0.0.1",
port: 0,
uptimeMs: 3 * 3_600_000 + 17 * MINUTE,
status: "online",
capabilities: ["ws", "sse", "devices", "attention"],
limits: { maxFrameBytes: 8_388_608, maxBodyBytes: 1_048_576, maxSessions: 256 },
};
const health = {
ok: false,
checkedAt: now,
items: [
{ name: "instances", ok: true, detail: "3 connected" },
{ name: "workspaces", ok: false, detail: "5 of 6 present (1 missing)" },
{ name: "auth", ok: true, detail: "3 devices + local token" },
{ name: "static", ok: true, detail: "web/dist" },
],
};
const devices = [
{
id: "dev-local",
deviceId: "dev-local",
name: "local browser",
kind: "laptop",
scopes: ["read", "steer", "apply"],
lastSeenAt: now - 15_000,
lastActiveAt: now - 15_000,
createdAt: now - 26 * 3_600_000,
revokedAt: null,
},
{
id: "dev-phone",
deviceId: "dev-phone",
name: "Pixel 8 · pi2",
kind: "phone",
scopes: ["read", "steer"],
lastSeenAt: now - 47 * MINUTE,
lastActiveAt: now - 47 * MINUTE,
createdAt: now - 9 * 86_400_000,
revokedAt: null,
},
{
id: "dev-tablet",
deviceId: "dev-tablet",
name: "iPad Air",
kind: "tablet",
scopes: ["read"],
lastSeenAt: now - 6 * 86_400_000,
lastActiveAt: now - 6 * 86_400_000,
createdAt: now - 40 * 86_400_000,
revokedAt: now - 5 * 86_400_000,
},
];
const modelProviders = [
{
provider: "anthropic",
models: [
{ id: "claude-sonnet-4.5", contextWindow: 200_000, reasoning: true },
{ id: "claude-opus-4.1", contextWindow: 200_000, reasoning: true },
{ id: "claude-haiku-4.5", contextWindow: 200_000, reasoning: false },
],
},
{
provider: "openai",
models: [
{ id: "gpt-5.1-codex", contextWindow: 128_000, reasoning: true },
{ id: "gpt-5-mini", contextWindow: 128_000, reasoning: false },
],
},
{
provider: "cliproxyapi",
models: [{ id: "gemini-3-pro", contextWindow: 1_000_000, reasoning: true }],
},
];
const resources = {
instances: [
{
workspaceId: "ws-main",
instanceId: "inst-ws-main",
nvimPid: 41_022,
rssBytes: 268_435_456,
sessions: 4,
hasUI: true,
},
{
workspaceId: "ws-nvim",
instanceId: "inst-ws-nvim",
nvimPid: 41_310,
rssBytes: 96_468_992,
sessions: 1,
hasUI: false,
},
{
workspaceId: "ws-tmp",
instanceId: "inst-ws-tmp",
nvimPid: 41_877,
rssBytes: 54_525_952,
sessions: 1,
hasUI: false,
},
],
totalRssBytes: 419_430_400,
physicalMemoryBytes: 34_359_738_368,
warn: false,
reason: "",
};
const diagnostics = {
v: 1,
daemonId: MOCK_DAEMON_ID,
uptimeMs: info.uptimeMs,
connections: [{ clientId: "c-mock", kind: "web", workspaceId: "ws-main" }],
eventsSent: 12_842,
eventRate: 3.4,
slowQueries: 0,
devices: devices.length,
workspaces: workspaces.length,
instances: resources.instances,
};
const sessionById = new Map(sessions.map((session) => [session.sessionId, session]));
return {
info: { ...info, port: undefined },
health,
workspaces,
sessions,
sessionById,
entriesBySession: entryPages,
devices,
modelProviders,
resources,
diagnostics,
/** `GET /api/v1/pair` mint response (no code in the body). */
pairCode: {
accepted: true,
code: "QK7M-2XPD",
url: "http://127.0.0.1:4321/pair/QK7M-2XPD",
expiresAt: now + 10 * MINUTE,
nonce: "n-9f2c1a",
},
/** `attention` flattened per workspace for `GET /api/v1/attention`. */
attentionByWorkspace: (workspaceId) =>
sessions
.filter((session) => session.workspaceId === workspaceId)
.flatMap((session) => session.attention ?? []),
};
}
+736
View File
@@ -0,0 +1,736 @@
#!/usr/bin/env node
/**
* Zero-dependency mock of the pi2 daemon's browser surface, for the visual
* harness (`scripts/ui-shots.mjs`).
*
* It answers **exactly** the REST + WS contract the web client speaks
* (`web/src/lib/api.ts`, the feature `queries.ts` files under web/src/features,
* `web/src/lib/ws.ts`) with the fixtures from `scripts/ui-fixtures.mjs`, and
* optionally serves the built console (`web/dist`) so a screenshot run needs
* nothing else.
*
* node scripts/ui-mock-server.mjs # API only, port 0
* node scripts/ui-mock-server.mjs --static web/dist # + the built UI
* node scripts/ui-mock-server.mjs --pair-only # every auth → 401
*
* It prints `READY <port>` on stdout once listening (the harness waits for
* that line) and logs nothing else unless `--log` is given.
*
* What it deliberately does **not** do: no `pi` spawn, no plugin relay, no
* session state machine. Mutations are acked and dropped — this is a fixture
* server, not a daemon (`AGENTS.md` hard rule 2).
*
* `--pair-only` is the unpaired branch: every authenticated endpoint answers
* `401 E_UNAUTHORIZED`, which is what `/workspaces` needs to redirect itself to
* `/connect`. `POST /api/v1/console/session` is refused too, so the harness can
* prove that no local sign-in sneaks past the guard.
*/
import crypto from "node:crypto";
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
MOCK_CLI_TOKEN,
MOCK_DAEMON_ID,
MOCK_DEVICE_TOKEN,
MOCK_PHONE_TOKEN,
buildFixtures,
} from "./ui-fixtures.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(HERE, "..");
/* ------------------------------------------------------------------ */
/* argv */
/* ------------------------------------------------------------------ */
function parseArgs(argv) {
const options = {
port: 0,
host: "127.0.0.1",
staticDir: null,
pairOnly: false,
log: false,
now: null,
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
const next = () => {
const value = argv[index + 1];
if (value === undefined) throw new Error(`${arg} needs a value`);
index += 1;
return value;
};
switch (arg) {
case "--port":
options.port = Number(next());
break;
case "--host":
options.host = next();
break;
case "--static":
// `--static auto` (or a bare `--static` at the end) means `web/dist`.
if (argv[index + 1] === undefined || argv[index + 1].startsWith("--")) {
options.staticDir = path.join(REPO_ROOT, "web", "dist");
} else {
const value = next();
options.staticDir = value === "auto" ? path.join(REPO_ROOT, "web", "dist") : path.resolve(value);
}
break;
case "--pair-only":
options.pairOnly = true;
break;
case "--log":
options.log = true;
break;
case "--now":
options.now = Number(next());
break;
case "--help":
case "-h":
process.stdout.write(
"usage: ui-mock-server.mjs [--port 0] [--host 127.0.0.1] [--static <web/dist>] [--pair-only] [--log]\n",
);
process.exit(0);
break;
default:
process.stderr.write(`ui-mock-server: unknown argument ${arg}\n`);
process.exit(2);
}
}
if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535) {
process.stderr.write("ui-mock-server: --port must be 0..65535\n");
process.exit(2);
}
return options;
}
const OPTIONS = parseArgs(process.argv.slice(2));
const NOW = Number.isFinite(OPTIONS.now) && OPTIONS.now > 0 ? OPTIONS.now : Date.now();
const FIXTURES = buildFixtures(NOW);
/** Tokens this mock accepts as a device bearer (the CLI token only for login). */
const DEVICE_TOKENS = new Set([MOCK_DEVICE_TOKEN, MOCK_PHONE_TOKEN]);
const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
function log(line) {
if (OPTIONS.log) process.stderr.write(`ui-mock-server: ${line}\n`);
}
/* ------------------------------------------------------------------ */
/* small helpers */
/* ------------------------------------------------------------------ */
function sendJson(res, status, body, extraHeaders = {}) {
const payload = body === undefined ? "" : JSON.stringify(body);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(payload),
"Cache-Control": "no-store",
...extraHeaders,
});
res.end(payload);
}
function sendEmpty(res, status = 204) {
res.writeHead(status, { "Content-Length": 0, "Cache-Control": "no-store" });
res.end();
}
/** `{code, message, retryable}` — the shape `web/src/lib/api.ts` parses. */
function sendError(res, status, code, message, details) {
sendJson(res, status, { code, message, retryable: status >= 500, ...(details ? { details } : {}) });
}
function unauthorized(res, message = "missing or invalid device token") {
sendError(res, 401, "E_UNAUTHORIZED", message);
}
function notFound(res, message = "not found") {
sendError(res, 404, "E_NOT_FOUND", message);
}
function bearer(req) {
const header = req.headers.authorization;
if (typeof header !== "string") return undefined;
const match = /^Bearer\s+(.+)$/i.exec(header.trim());
return match?.[1]?.trim();
}
function isLoopback(req) {
const address = req.socket.remoteAddress ?? "";
return LOOPBACK.has(address);
}
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on("data", (chunk) => {
size += chunk.length;
if (size > 1_048_576) {
reject(new Error("body too large"));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on("end", () => {
const raw = Buffer.concat(chunks).toString("utf8");
if (!raw) return resolve({});
try {
const parsed = JSON.parse(raw);
resolve(parsed && typeof parsed === "object" ? parsed : {});
} catch {
reject(new Error("malformed JSON"));
}
});
req.on("error", reject);
});
}
const DEVICE_PUBLIC = {
id: "dev-local",
name: "local browser",
kind: "laptop",
scopes: ["read", "steer", "apply"],
};
/* ------------------------------------------------------------------ */
/* REST */
/* ------------------------------------------------------------------ */
const MIME = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".map": "application/json; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".svg": "image/svg+xml",
".webp": "image/webp",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".txt": "text/plain; charset=utf-8",
};
function serveStatic(req, res, pathname) {
if (!OPTIONS.staticDir) return notFound(res, `no such API route ${pathname}`);
const distDir = OPTIONS.staticDir;
const indexPath = path.join(distDir, "index.html");
if (!fs.existsSync(indexPath)) {
return sendError(
res,
503,
"E_INTERNAL",
`web/dist is missing — run \`pnpm --dir web build\` (looked in ${distDir})`,
);
}
let decoded;
try {
decoded = decodeURIComponent(pathname);
} catch {
return notFound(res, "malformed path");
}
if (decoded.includes("\0")) return notFound(res, "malformed path");
const relative = decoded.replace(/^\/+/, "");
const candidate = path.resolve(distDir, relative);
// No traversal out of the build directory.
if (candidate !== distDir && !candidate.startsWith(`${distDir}${path.sep}`)) return notFound(res, "not found");
if (relative !== "" && fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
const body = fs.readFileSync(candidate);
res.writeHead(200, {
"Content-Type": MIME[path.extname(candidate).toLowerCase()] ?? "application/octet-stream",
"Content-Length": body.length,
// Hashed assets are immutable; index.html is not.
"Cache-Control": relative.startsWith("assets/") ? "public, max-age=31536000, immutable" : "no-store",
});
res.end(req.method === "HEAD" ? undefined : body);
return undefined;
}
// History-mode routes (`/chat/s-main`, `/status`, …) resolve to the SPA.
const html = fs.readFileSync(indexPath);
res.writeHead(200, { "Content-Type": MIME[".html"], "Content-Length": html.length, "Cache-Control": "no-store" });
res.end(req.method === "HEAD" ? undefined : html);
return undefined;
}
/** Sessions of one workspace, in the shape `/workspaces/:id/sessions` acks. */
function sessionsOf(workspaceId) {
const rows = FIXTURES.sessions.filter((session) => session.workspaceId === workspaceId);
return { v: 1, sessions: rows, cursor: { hasMore: false } };
}
function entriesPage(sessionId, url) {
const limitRaw = Number(url.searchParams.get("limit"));
const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(500, Math.floor(limitRaw)) : 50;
const all = FIXTURES.entriesBySession[sessionId] ?? [];
const beforeId = url.searchParams.get("before");
const end = beforeId ? Math.max(0, all.findIndex((entry) => entry.id === beforeId)) : all.length;
const start = Math.max(0, end - limit);
const page = all.slice(start, end);
return {
v: 1,
entries: page,
cursor: { before: page[0]?.id ?? null, hasMore: start > 0 },
};
}
function modelGroups() {
return { v: 1, providers: FIXTURES.modelProviders };
}
async function handleApi(req, res, url) {
const method = req.method ?? "GET";
const pathname = url.pathname;
/* Public surface (docs/protocol.md §3.1): info/health are loopback-public. */
if (pathname === "/api/v1/info" && method === "GET") {
return sendJson(res, 200, { ...FIXTURES.info, port: SERVER_PORT });
}
if ((pathname === "/api/v1/health" || pathname === "/health") && method === "GET") {
return sendJson(res, 200, FIXTURES.health);
}
if (pathname === "/api/v1/console/session" && method === "POST") {
// Loopback + the local CLI token only; `--pair-only` proves no auto sign-in.
if (!isLoopback(req)) return sendError(res, 403, "E_FORBIDDEN", "console login is loopback-only");
const caller = bearer(req);
if (OPTIONS.pairOnly || caller !== MOCK_CLI_TOKEN) {
return unauthorized(res, "console login requires the local CLI token");
}
await readBody(req).catch(() => undefined);
return sendJson(res, 200, {
token: MOCK_DEVICE_TOKEN,
device: DEVICE_PUBLIC,
url: `http://127.0.0.1:${SERVER_PORT}/#t=${encodeURIComponent(MOCK_DEVICE_TOKEN)}`,
});
}
if (pathname === "/api/v1/pair" && method === "POST") {
const body = await readBody(req).catch(() => ({}));
if (typeof body.code === "string") {
// Public redeem: the fixture code pairs the browser as a laptop.
if (body.code.replace(/[\s-]/g, "").toUpperCase() !== FIXTURES.pairCode.code.replace(/-/g, "")) {
return unauthorized(res, "pairing code is invalid or expired");
}
return sendJson(res, 200, { token: MOCK_DEVICE_TOKEN, device: DEVICE_PUBLIC });
}
if (OPTIONS.pairOnly) return unauthorized(res);
return sendJson(res, 200, { accepted: true, ...FIXTURES.pairCode });
}
/* Everything below needs a device token (and is refused in --pair-only). */
if (OPTIONS.pairOnly) return unauthorized(res);
const token = bearer(req);
if (!token || !DEVICE_TOKENS.has(token)) return unauthorized(res);
if (pathname === "/api/v1/workspaces" && method === "GET") {
return sendJson(res, 200, FIXTURES.workspaces);
}
let match = /^\/api\/v1\/workspaces\/([^/]+)\/sessions$/.exec(pathname);
if (match && method === "GET") {
const workspaceId = decodeURIComponent(match[1]);
if (!FIXTURES.workspaces.some((workspace) => workspace.workspaceId === workspaceId)) {
return notFound(res, `unknown workspace ${workspaceId}`);
}
return sendJson(res, 200, sessionsOf(workspaceId));
}
match = /^\/api\/v1\/sessions\/([^/]+)\/entries$/.exec(pathname);
if (match && method === "GET") {
const sessionId = decodeURIComponent(match[1]);
if (!FIXTURES.sessionById.has(sessionId)) return notFound(res, `unknown session ${sessionId}`);
return sendJson(res, 200, entriesPage(sessionId, url));
}
// Harness extras: the daemon relays `queue`/`tasks` inside `/sessions` and
// the WS snapshot, never as their own REST routes. These two exist only so
// an audit can read the fixtures directly; no web code calls them.
match = /^\/api\/v1\/sessions\/([^/]+)\/(queue|tasks)$/.exec(pathname);
if (match && method === "GET") {
const session = FIXTURES.sessionById.get(decodeURIComponent(match[1]));
if (!session) return notFound(res, "unknown session");
const key = match[2];
return sendJson(res, 200, { v: 1, [key]: session[key] ?? [] });
}
if (pathname === "/api/v1/attention" && method === "GET") {
const workspaceId = url.searchParams.get("workspaceId") ?? "";
if (!FIXTURES.workspaces.some((workspace) => workspace.workspaceId === workspaceId)) {
return notFound(res, `unknown workspace ${workspaceId}`);
}
return sendJson(res, 200, { v: 1, attention: FIXTURES.attentionByWorkspace(workspaceId) });
}
if (pathname === "/api/v1/models" && method === "GET") {
const workspaceId = url.searchParams.get("workspaceId") ?? "";
if (!workspaceId) return sendError(res, 400, "E_BAD_REQUEST", "workspaceId is required");
if (!FIXTURES.workspaces.some((workspace) => workspace.workspaceId === workspaceId)) {
return notFound(res, `unknown workspace ${workspaceId}`);
}
return sendJson(res, 200, modelGroups());
}
if (pathname === "/api/v1/devices" && method === "GET") {
// Bare array (`auth.listDevices()`), not `{devices:[…]}`.
return sendJson(res, 200, FIXTURES.devices);
}
match = /^\/api\/v1\/devices\/([^/]+)$/.exec(pathname);
if (match && method === "DELETE") {
const deviceId = decodeURIComponent(match[1]);
if (!FIXTURES.devices.some((device) => device.deviceId === deviceId)) {
return notFound(res, `unknown device ${deviceId}`);
}
return sendEmpty(res, 204);
}
if (pathname === "/api/v1/resources" && method === "GET") {
return sendJson(res, 200, FIXTURES.resources);
}
if (pathname === "/api/v1/diagnostics" && method === "GET") {
return sendJson(res, 200, FIXTURES.diagnostics);
}
if (pathname === "/api/v1/cmd" && method === "POST") {
const body = await readBody(req).catch(() => ({}));
log(`cmd ${String(body.method ?? "?")}`);
// Commands are acked and dropped: the mock owns no runtime.
return sendJson(res, 200, { accepted: true, disposition: "mock", method: body.method ?? null });
}
return notFound(res, `no such API route ${pathname}`);
}
function handleRequest(req, res) {
const origin = req.headers.origin;
if (origin) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Vary", "Origin");
}
if (req.method === "OPTIONS") {
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "authorization, content-type");
res.setHeader("Access-Control-Max-Age", "600");
return sendEmpty(res, 204);
}
let url;
try {
url = new URL(req.url ?? "/", "http://127.0.0.1");
} catch {
return sendError(res, 400, "E_BAD_REQUEST", "malformed URL");
}
log(`${req.method} ${url.pathname}${url.search}`);
const isApi = url.pathname === "/api" || url.pathname.startsWith("/api/");
if (isApi) {
Promise.resolve(handleApi(req, res, url)).catch((error) => {
sendError(res, 500, "E_INTERNAL", error instanceof Error ? error.message : String(error));
});
return undefined;
}
if (url.pathname === "/ws" || url.pathname.startsWith("/ws/")) return notFound(res, "upgrade required");
return serveStatic(req, res, url.pathname);
}
/* ------------------------------------------------------------------ */
/* WebSocket (RFC 6455 server side, hand-rolled: no dependencies) */
/* ------------------------------------------------------------------ */
const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
const MAX_FRAME_BYTES = 8 * 1024 * 1024;
function encodeFrame(opcode, payload) {
const length = payload.length;
let header;
if (length < 126) {
header = Buffer.alloc(2);
header[1] = length;
} else if (length < 65_536) {
header = Buffer.alloc(4);
header[1] = 126;
header.writeUInt16BE(length, 2);
} else {
header = Buffer.alloc(10);
header[1] = 127;
header.writeBigUInt64BE(BigInt(length), 2);
}
header[0] = 0x80 | opcode;
return Buffer.concat([header, payload]);
}
class WsPeer {
constructor(socket) {
this.socket = socket;
this.buffer = Buffer.alloc(0);
this.fragments = [];
this.fragmentOpcode = 0;
this.authenticated = false;
this.closed = false;
this.device = null;
}
sendJson(record) {
if (this.closed) return;
const payload = Buffer.from(JSON.stringify(record), "utf8");
try {
this.socket.write(encodeFrame(0x1, payload));
} catch {
this.closed = true;
}
}
sendFrame(opcode, payload) {
if (this.closed) return;
try {
this.socket.write(encodeFrame(opcode, payload));
} catch {
this.closed = true;
}
}
close(code = 1000, reason = "") {
if (this.closed) return;
this.closed = true;
const reasonBytes = Buffer.from(reason, "utf8");
const payload = Buffer.alloc(2 + reasonBytes.length);
payload.writeUInt16BE(code, 0);
reasonBytes.copy(payload, 2);
try {
this.socket.write(encodeFrame(0x8, payload));
this.socket.end();
} catch {
this.socket.destroy();
}
}
error(code, message) {
this.sendJson({ v: 1, type: "error", payload: { code, message, retryable: false } });
}
push(chunk) {
this.buffer = Buffer.concat([this.buffer, chunk]);
for (;;) {
const buffer = this.buffer;
if (buffer.length < 2) return;
const fin = (buffer[0] & 0x80) !== 0;
const opcode = buffer[0] & 0x0f;
const masked = (buffer[1] & 0x80) !== 0;
let length = buffer[1] & 0x7f;
let offset = 2;
if (length === 126) {
if (buffer.length < 4) return;
length = buffer.readUInt16BE(2);
offset = 4;
} else if (length === 127) {
if (buffer.length < 10) return;
const big = buffer.readBigUInt64BE(2);
if (big > BigInt(MAX_FRAME_BYTES)) {
this.close(1009, "frame too large");
return;
}
length = Number(big);
offset = 10;
}
let maskKey = null;
if (masked) {
if (buffer.length < offset + 4) return;
maskKey = buffer.subarray(offset, offset + 4);
offset += 4;
}
if (length > MAX_FRAME_BYTES) {
this.close(1009, "frame too large");
return;
}
if (buffer.length < offset + length) return;
let payload = Buffer.from(buffer.subarray(offset, offset + length));
if (maskKey) {
for (let index = 0; index < payload.length; index += 1) payload[index] ^= maskKey[index % 4];
}
this.buffer = buffer.subarray(offset + length);
if (opcode === 0x8) {
this.close(1000, "bye");
return;
}
if (opcode === 0x9) {
this.sendFrame(0xa, payload);
continue;
}
if (opcode === 0xa) continue;
if (opcode === 0x1 || opcode === 0x2) {
this.fragmentOpcode = opcode;
this.fragments = [payload];
} else if (opcode === 0x0) {
this.fragments.push(payload);
} else {
this.close(1002, "unsupported opcode");
return;
}
if (!fin) continue;
const message = Buffer.concat(this.fragments);
this.fragments = [];
if (this.fragmentOpcode === 0x2) continue; // binary frames are ignored
this.onText(message.toString("utf8"));
}
}
onText(raw) {
let frame;
try {
frame = JSON.parse(raw);
} catch {
this.error("E_BAD_REQUEST", "malformed JSON");
this.close(4400, "malformed JSON");
return;
}
if (!frame || typeof frame !== "object" || typeof frame.type !== "string") {
this.error("E_BAD_REQUEST", "missing frame type");
return;
}
if (!this.authenticated) {
const payload = frame.payload && typeof frame.payload === "object" ? frame.payload : {};
const token = typeof frame.token === "string" ? frame.token : typeof payload.token === "string" ? payload.token : "";
if (frame.type !== "auth" || !DEVICE_TOKENS.has(token)) {
this.error("E_UNAUTHORIZED", "invalid device token");
this.close(4401, "unauthorized");
return;
}
this.authenticated = true;
this.device = DEVICE_PUBLIC;
this.sendJson({
v: 1,
type: "hello_ack",
daemonId: MOCK_DAEMON_ID,
limits: { maxFrameBytes: MAX_FRAME_BYTES },
device: DEVICE_PUBLIC,
});
return;
}
switch (frame.type) {
case "ping":
this.sendJson({ v: 1, type: "pong", ts: Date.now() });
return;
case "subscribe":
this.onSubscribe(frame.payload && typeof frame.payload === "object" ? frame.payload : {});
return;
case "unsubscribe":
return;
case "auth":
return;
default:
this.error("E_BAD_REQUEST", `unknown message type "${frame.type}"`);
}
}
onSubscribe(payload) {
const workspaceId = typeof payload.workspaceId === "string" ? payload.workspaceId : undefined;
const ids = new Set(
(Array.isArray(payload.sessionIds) ? payload.sessionIds : []).filter((id) => typeof id === "string"),
);
if (typeof payload.sessionId === "string") ids.add(payload.sessionId);
if (!ids.size && workspaceId) {
for (const session of FIXTURES.sessions) {
if (session.workspaceId === workspaceId) ids.add(session.sessionId);
}
}
if (!ids.size) {
this.error("E_BAD_REQUEST", "subscribe requires workspaceId or sessionIds");
return;
}
for (const sessionId of ids) {
const session = FIXTURES.sessionById.get(sessionId);
if (!session) {
this.error("E_SESSION_NOT_FOUND", `unknown session ${sessionId}`);
continue;
}
// `payload: {state, entries[]}` — docs/protocol.md §2. The state's own
// `entries` are Block-shaped (legacy DTO fixtures); the live tail is
// the raw pi entry stream, so keep them apart.
this.sendJson({
v: 1,
type: "snapshot",
sessionId,
epoch: session.instanceId ?? `inst-${session.workspaceId}`,
seq: 1,
ts: Date.now(),
payload: {
state: { ...session, entries: [] },
entries: FIXTURES.entriesBySession[sessionId] ?? [],
},
});
}
}
}
function handleUpgrade(req, socket, head) {
let pathname;
try {
pathname = new URL(req.url ?? "/", "http://127.0.0.1").pathname;
} catch {
socket.destroy();
return;
}
if (pathname !== "/ws" && pathname !== "/ws/") {
socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
return;
}
if (OPTIONS.pairOnly) {
// No socket in the unpaired branch: the client must stay on /connect.
socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
return;
}
const key = req.headers["sec-websocket-key"];
if (typeof key !== "string" || req.headers.upgrade?.toLowerCase() !== "websocket") {
socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
return;
}
const accept = crypto.createHash("sha1").update(`${key}${WS_GUID}`).digest("base64");
socket.write(
"HTTP/1.1 101 Switching Protocols\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
`Sec-WebSocket-Accept: ${accept}\r\n\r\n`,
);
const peer = new WsPeer(socket);
socket.setNoDelay(true);
if (head && head.length) peer.push(head);
socket.on("data", (chunk) => peer.push(chunk));
socket.on("error", () => {
peer.closed = true;
});
socket.on("close", () => {
peer.closed = true;
});
log(`ws open (${peer.authenticated ? "authed" : "pending"})`);
}
/* ------------------------------------------------------------------ */
/* boot */
/* ------------------------------------------------------------------ */
let SERVER_PORT = 0;
const server = http.createServer(handleRequest);
server.on("upgrade", handleUpgrade);
server.on("clientError", (_error, socket) => {
socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
});
server.listen(OPTIONS.port, OPTIONS.host, () => {
const address = server.address();
SERVER_PORT = typeof address === "object" && address ? address.port : OPTIONS.port;
if (OPTIONS.staticDir && !fs.existsSync(path.join(OPTIONS.staticDir, "index.html"))) {
process.stderr.write(
`ui-mock-server: warning — ${OPTIONS.staticDir}/index.html is missing (run \`pnpm --dir web build\`)\n`,
);
}
process.stdout.write(`READY ${SERVER_PORT}\n`);
});
function shutdown(code = 0) {
server.close(() => process.exit(code));
// Sockets (WS upgrades) keep the server open; do not hang the harness.
setTimeout(() => process.exit(code), 250).unref();
}
process.on("SIGTERM", () => shutdown(0));
process.on("SIGINT", () => shutdown(0));
+691
View File
@@ -0,0 +1,691 @@
#!/usr/bin/env node
/**
* Visual acceptance harness for the pi2 web console (WS-F in
* `/tmp/pi2d-port/PLAN.md` §3.3).
*
* Shoots the built console (`web/dist`) through the zero-dependency fixture
* server (`scripts/ui-mock-server.mjs`), across 4 pages × 3 viewports × 2
* themes, and asserts the parity invariants that a screenshot alone cannot
* prove: no console error, no horizontal overflow, no `.tabbar`, no navigation
* on `/connect`, and the per-page primary-button budget (workspaces = 1,
* status = 0, connect = 1).
*
* Usage:
* pnpm --dir web build # prerequisite
* node scripts/ui-shots.mjs --serve-static --round r1 --out /tmp/pi2d-port/shots/r1
* node scripts/ui-shots.mjs --base http://127.0.0.1:7676 # against a real daemon
* node scripts/ui-shots.mjs --serve-static --matrix=quick # 1440×900 × light/dark
*
* Options:
* --serve-static spawn the mock daemon and serve `web/dist` from it
* --base <url> shoot an already running daemon instead (implies no spawn)
* --out <dir> output dir (default: /tmp/pi2d-port/shots/<round>)
* --round <label> label recorded in the report (default: "adhoc")
* --matrix full|quick full = 24 shots, quick = 1440×900 × light/dark = 8
* --static-dir <dir> build output to serve (default: web/dist)
* --timeout <ms> per-shot settle budget (default: 12000)
*
* Artifacts: `<out>/<page>-<w>x<h>-<theme>.png` (24 files in `full`) and
* `<out>/report.json`. Exit code: 0 all assertions pass, 1 otherwise, 2 when
* the harness itself cannot start (no build, no browser, no server).
*
* Design rules: Playwright is *resolved*, never added as a dependency (same
* loader as `scripts/e2e/ui-e2e.mjs`); nothing here patches product code, so a
* failing assertion means a real visual regression and must not be "fixed" by
* editing the UI from this script.
*/
import { spawn } from "node:child_process";
import fs from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(HERE, "..");
const require_ = createRequire(import.meta.url);
const ENV = process.env;
/* ------------------------------------------------------------------ */
/* argv */
/* ------------------------------------------------------------------ */
const VIEWPORTS = [
{ id: "mobile", width: 380, height: 780 },
{ id: "tablet", width: 1024, height: 768 },
{ id: "desktop", width: 1440, height: 900 },
];
const THEMES = ["light", "dark"];
/** Pages, their routes, and the primary-button budget (`null` = not asserted). */
const PAGES = [
{ id: "workspaces", route: "/workspaces", primary: [1, 1], nav: true },
{ id: "chat", route: "/chat/s-main?workspace=ws-main", primary: null, nav: true },
{ id: "status", route: "/status", primary: [0, 0], nav: true },
{ id: "connect", route: "/connect", primary: [1, 1], nav: false },
];
function usage() {
process.stdout.write(
[
"usage: node scripts/ui-shots.mjs [--serve-static] [--base <url>] [--out <dir>]",
" [--round <label>] [--matrix=full|quick]",
" [--static-dir <dir>] [--timeout <ms>]",
"",
].join("\n"),
);
}
function parseArgs(argv) {
const options = {
serveStatic: false,
base: null,
out: null,
round: "adhoc",
matrix: "full",
staticDir: path.join(REPO_ROOT, "web", "dist"),
timeoutMs: 12_000,
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
const value = () => {
const next = argv[index + 1];
if (next === undefined) throw new Error(`${arg} needs a value`);
index += 1;
return next;
};
if (arg === "--help" || arg === "-h") {
usage();
process.exit(0);
} else if (arg === "--serve-static") {
options.serveStatic = true;
} else if (arg.startsWith("--base=")) {
options.base = arg.slice("--base=".length);
} else if (arg === "--base") {
options.base = value();
} else if (arg.startsWith("--out=")) {
options.out = arg.slice("--out=".length);
} else if (arg === "--out") {
options.out = value();
} else if (arg.startsWith("--round=")) {
options.round = arg.slice("--round=".length);
} else if (arg === "--round") {
options.round = value();
} else if (arg.startsWith("--matrix=")) {
options.matrix = arg.slice("--matrix=".length);
} else if (arg === "--matrix") {
options.matrix = value();
} else if (arg.startsWith("--static-dir=")) {
options.staticDir = path.resolve(arg.slice("--static-dir=".length));
} else if (arg === "--static-dir") {
options.staticDir = path.resolve(value());
} else if (arg.startsWith("--timeout=")) {
options.timeoutMs = Number(arg.slice("--timeout=".length));
} else if (arg === "--timeout") {
options.timeoutMs = Number(value());
} else {
process.stderr.write(`ui-shots: unknown argument ${arg}\n`);
usage();
process.exit(2);
}
}
if (!["full", "quick"].includes(options.matrix)) {
process.stderr.write(`ui-shots: --matrix must be full or quick (got ${options.matrix})\n`);
process.exit(2);
}
if (!options.serveStatic && !options.base) {
process.stderr.write("ui-shots: pass --serve-static or --base <url>\n");
usage();
process.exit(2);
}
if (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) {
process.stderr.write("ui-shots: --timeout must be a positive number of milliseconds\n");
process.exit(2);
}
options.out = path.resolve(options.out ?? path.join("/tmp/pi2d-port/shots", options.round));
return options;
}
const OPTIONS = parseArgs(process.argv.slice(2));
const VIEWPORT_MATRIX = OPTIONS.matrix === "quick" ? VIEWPORTS.filter((item) => item.id === "desktop") : VIEWPORTS;
/* ------------------------------------------------------------------ */
/* playwright (resolved, not a dependency) */
/* ------------------------------------------------------------------ */
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;
};
for (const spec of [ENV.PI2_SHOTS_PLAYWRIGHT_MODULE, ENV.PI2_E2E_PLAYWRIGHT_MODULE].filter(Boolean)) {
const fromEnv = attempt(spec);
if (fromEnv) return { pw: fromEnv, spec };
}
const fromRequire = attempt("playwright");
if (fromRequire) return { pw: fromRequire, spec: "playwright" };
// mise installs npm-global tools under <mise>/installs/npm-playwright/*/v11/*/node_modules
const roots = [
"/home/yuez/.local/share/mise/installs/npm-playwright",
path.join(ENV.HOME || "/root", ".local/share/mise/installs/npm-playwright"),
];
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) {
const candidate = path.join(v11, hash, "node_modules", "playwright");
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(", ")})`);
}
function chromePath() {
const candidates = [
ENV.PI2_SHOTS_CHROME,
ENV.PI2_E2E_CHROME,
"/usr/bin/google-chrome-stable",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
].filter(Boolean);
return candidates.find((candidate) => fs.existsSync(candidate));
}
/* ------------------------------------------------------------------ */
/* fixture servers */
/* ------------------------------------------------------------------ */
const children = [];
function startMockServer({ pairOnly = false } = {}) {
const args = [
path.join(HERE, "ui-mock-server.mjs"),
"--port",
"0",
"--static",
OPTIONS.staticDir,
...(pairOnly ? ["--pair-only"] : []),
];
const child = spawn(process.execPath, args, { cwd: REPO_ROOT, stdio: ["ignore", "pipe", "pipe"] });
children.push(child);
let stderr = "";
child.stderr.on("data", (chunk) => {
stderr += chunk.toString();
});
return new Promise((resolve, reject) => {
let stdout = "";
const timer = setTimeout(() => {
child.kill("SIGKILL");
reject(new Error(`ui-mock-server did not print READY within 10s${stderr ? `: ${stderr}` : ""}`));
}, 10_000);
child.stdout.on("data", (chunk) => {
stdout += chunk.toString();
const match = /READY (\d+)/.exec(stdout);
if (!match) return;
clearTimeout(timer);
resolve({ port: Number(match[1]), child });
});
child.on("exit", (code) => {
clearTimeout(timer);
reject(new Error(`ui-mock-server exited early (code ${code})${stderr ? `: ${stderr}` : ""}`));
});
});
}
/* ------------------------------------------------------------------ */
/* helpers */
/* ------------------------------------------------------------------ */
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function storageState(origin, { paired, theme }) {
if (!paired) {
return {
cookies: [],
origins: [{ origin, localStorage: [{ name: "pi2-theme", value: theme }] }],
};
}
const local = [
{ name: "pi2-connection", value: "paired" },
{ name: "pi2-endpoint", value: origin },
{ name: "pi2-device-token", value: "mock-device-token-0000000000000000000000" },
{ name: "pi2-device-scopes", value: JSON.stringify(["read", "steer", "apply"]) },
{ name: "pi2-device", value: "visual harness" },
{ name: "pi2-connected-at", value: String(Date.now()) },
{ name: "pi2-theme", value: theme },
];
return { cookies: [], origins: [{ origin, localStorage: local }] };
}
function assert(name, ok, expected, observed) {
return { name, ok: Boolean(ok), expected, observed };
}
/** Wait until no same-origin request has been in flight for `quietMs`. */
async function waitForQuiet(page, timeoutMs, quietMs = 350) {
const started = Date.now();
let last = Date.now();
let pending = 0;
page.on("request", () => {
pending += 1;
last = Date.now();
});
const done = () => {
pending = Math.max(0, pending - 1);
last = Date.now();
};
page.on("requestfinished", done);
page.on("requestfailed", done);
while (Date.now() - started < timeoutMs) {
if (pending === 0 && Date.now() - last > quietMs) return true;
await sleep(100);
}
return false;
}
async function collect(page) {
return page.evaluate(() => {
const root = document.getElementById("root");
const text = (root?.innerText ?? "").replace(/\s+/g, " ").trim();
const count = (selector) => document.querySelectorAll(selector).length;
const de = document.documentElement;
const shell = document.querySelector(".shell");
return {
path: location.pathname,
search: location.search,
title: document.title,
theme: de.dataset.theme ?? "",
paired: shell?.getAttribute("data-paired") ?? null,
wsState: shell?.getAttribute("data-ws-state") ?? null,
textLen: text.length,
textHead: text.slice(0, 220),
scrollWidth: de.scrollWidth,
clientWidth: de.clientWidth,
bodyScrollWidth: document.body.scrollWidth,
tabbar: count(".tabbar"),
primary: count(".btn--primary"),
pagePill: count(".page-pill"),
navItem: count(".nav-item"),
dots: count(".dot"),
modals: count(".modal-backdrop"),
hasRoot: root !== null,
};
});
}
/** Elements that overflow the viewport to the right (only run when it does). */
async function overflowOffenders(page) {
return page.evaluate(() => {
const width = document.documentElement.clientWidth;
const offenders = [];
for (const element of document.querySelectorAll("body *")) {
const rect = element.getBoundingClientRect();
if (rect.width === 0 && rect.height === 0) continue;
if (rect.right > width + 1 || rect.left < -1) {
const id = element.id ? `#${element.id}` : "";
const cls = typeof element.className === "string" ? element.className.trim().split(/\s+/).slice(0, 3).join(".") : "";
offenders.push(`${element.tagName.toLowerCase()}${id}${cls ? `.${cls}` : ""} [${Math.round(rect.left)}→${Math.round(rect.right)}]`);
if (offenders.length >= 6) break;
}
}
return offenders;
});
}
/* ------------------------------------------------------------------ */
/* main */
/* ------------------------------------------------------------------ */
const failures = [];
const notes = [];
function record(shotId, checks) {
for (const check of checks) {
if (check.ok) continue;
failures.push({
shot: shotId,
check: check.name,
expected: check.expected,
observed: check.observed,
});
}
}
async function shootPage(browser, { base, origin, page: spec, viewport, theme, index, total }) {
const file = `${spec.id}-${viewport.width}x${viewport.height}-${theme}.png`;
const shotPath = path.join(OPTIONS.out, file);
const context = await browser.newContext({
viewport: { width: viewport.width, height: viewport.height },
deviceScaleFactor: 1,
colorScheme: theme,
locale: "en-US",
storageState: storageState(origin, { paired: true, theme }),
baseURL: base,
});
const consoleErrors = [];
const pageErrors = [];
const apiErrors = [];
try {
await context.addInitScript((lang) => {
try {
localStorage.setItem("pi2-lang", lang);
} catch {
/* private mode */
}
}, "en");
const page = await context.newPage();
page.on("console", (message) => {
if (message.type() === "error") consoleErrors.push(message.text());
});
page.on("pageerror", (error) => pageErrors.push(error.message));
page.on("response", (response) => {
const url = response.url();
if (!/\/api\/v1\//.test(url)) return;
if (response.status() >= 400) apiErrors.push(`${response.status()} ${new URL(url).pathname}`);
});
let navError = null;
try {
await page.goto(`${base}${spec.route}`, { waitUntil: "load", timeout: OPTIONS.timeoutMs });
} catch (error) {
navError = error instanceof Error ? error.message : String(error);
}
await waitForQuiet(page, OPTIONS.timeoutMs);
await page
.evaluate(() => (document.fonts && document.fonts.ready ? document.fonts.ready.then(() => true) : true))
.catch(() => undefined);
await sleep(450);
// The fixtures keep pending attention off the session this matrix opens
// (the console's attention modal is blocking and Escape-proof), so any
// overlay here is a finding: assert it away instead of clicking through.
const metrics = await collect(page);
const checks = [];
checks.push(
assert("page-loaded", !navError && metrics.hasRoot && metrics.textLen > 60, ">60 chars of app text", {
navError,
textLen: metrics.textLen,
}),
);
checks.push(
assert("route", metrics.path === spec.route.split("?")[0], spec.route.split("?")[0], `${metrics.path}${metrics.search}`),
);
checks.push(assert("paired", metrics.paired === "true", "data-paired=true", metrics.paired));
checks.push(assert("theme", metrics.theme === theme, theme, metrics.theme || "(none)"));
const errorSummary = (list) => (list.length ? { count: list.length, samples: list.slice(0, 4) } : 0);
checks.push(assert("console-errors", consoleErrors.length === 0, 0, errorSummary(consoleErrors)));
checks.push(assert("page-errors", pageErrors.length === 0, 0, errorSummary(pageErrors)));
checks.push(assert("api-errors", apiErrors.length === 0, 0, errorSummary(apiErrors)));
const overflow = metrics.scrollWidth > metrics.clientWidth + 1;
const offenders = overflow ? await overflowOffenders(page) : [];
checks.push(
assert("no-horizontal-overflow", !overflow, `${metrics.clientWidth}px`, {
scrollWidth: metrics.scrollWidth,
offenders,
}),
);
checks.push(assert("no-tabbar", metrics.tabbar === 0, 0, metrics.tabbar));
// A stray overlay hides the page under a modal: the screenshots must show
// the page, not a dialog nobody asked for.
checks.push(assert("no-unexpected-modal", metrics.modals === 0, 0, metrics.modals));
if (!spec.nav) {
checks.push(assert("connect-no-page-pill", metrics.pagePill === 0, 0, metrics.pagePill));
checks.push(assert("connect-no-nav-item", metrics.navItem === 0, 0, metrics.navItem));
}
if (spec.primary) {
const [min, max] = spec.primary;
checks.push(
assert("primary-count", metrics.primary >= min && metrics.primary <= max, `${min}..${max}`, metrics.primary),
);
}
if (metrics.dots < 3 && (spec.id === "chat" || spec.id === "status")) {
notes.push(`${file}: only ${metrics.dots} status dot(s) (PLAN §3.3 asks for ≥3)`);
}
await page.screenshot({ path: shotPath, fullPage: false, timeout: OPTIONS.timeoutMs });
record(file, checks);
process.stdout.write(
`${checks.every((check) => check.ok) ? "ok " : "FAIL"} [${index + 1}/${total}] ${file}` +
` ${metrics.title || "(no title)"} primary=${metrics.primary} dots=${metrics.dots} ws=${metrics.wsState}\n`,
);
return {
file,
page: spec.id,
viewport: { width: viewport.width, height: viewport.height },
theme,
bytes: fs.existsSync(shotPath) ? fs.statSync(shotPath).size : 0,
metrics,
checks,
};
} finally {
await context.close();
}
}
/**
* Unpaired branch (`--pair-only`): the guard must bounce `/workspaces` to
* `/connect`, and the connect page must have no navigation chrome at all.
*/
async function checkUnpaired(browser, { pairBase, pairOrigin }) {
const context = await browser.newContext({
viewport: { width: 1440, height: 900 },
colorScheme: "dark",
locale: "en-US",
storageState: storageState(pairOrigin, { paired: false, theme: "dark" }),
baseURL: pairBase,
});
try {
await context.addInitScript(() => {
try {
localStorage.setItem("pi2-lang", "en");
} catch {
/* private mode */
}
});
const page = await context.newPage();
const consoleErrors = [];
page.on("console", (message) => {
if (message.type() === "error") consoleErrors.push(message.text());
});
await page.goto(`${pairBase}/workspaces`, { waitUntil: "load", timeout: OPTIONS.timeoutMs });
await sleep(700);
const metrics = await collect(page);
const checks = [
assert("unpaired-redirects-to-connect", metrics.path === "/connect", "/connect", metrics.path),
assert("unpaired-no-page-pill", metrics.pagePill === 0, 0, metrics.pagePill),
assert("unpaired-no-nav-item", metrics.navItem === 0, 0, metrics.navItem),
assert("unpaired-no-tabbar", metrics.tabbar === 0, 0, metrics.tabbar),
assert("unpaired-connect-primary", metrics.primary === 1, 1, metrics.primary),
assert("unpaired-not-paired", metrics.paired === "false", "data-paired=false", metrics.paired),
assert("unpaired-renders", metrics.textLen > 60, ">60 chars", metrics.textLen),
// A refused `/api/v1/*` is expected here, but a console error is not.
assert("unpaired-console-errors", consoleErrors.length === 0, 0, consoleErrors.slice(0, 4)), ];
record("(unpaired)", checks);
process.stdout.write(
`${checks.every((check) => check.ok) ? "ok " : "FAIL"} [unpaired] /workspaces → ${metrics.path} primary=${
metrics.primary
}\n`,
);
return { name: "unpaired-redirect", base: pairBase, metrics, checks };
} finally {
await context.close();
}
}
function buildFingerprint() {
const indexPath = path.join(OPTIONS.staticDir, "index.html");
if (!fs.existsSync(indexPath)) return null;
const stat = fs.statSync(indexPath);
const html = fs.readFileSync(indexPath, "utf8");
const assets = [...html.matchAll(/\/(assets\/[^"']+)/g)].map((match) => match[1]);
return { indexMtime: new Date(stat.mtimeMs).toISOString(), assets };
}
async function main() {
const startedAt = Date.now();
if (OPTIONS.serveStatic && !fs.existsSync(path.join(OPTIONS.staticDir, "index.html"))) {
process.stderr.write(
`ui-shots: ${OPTIONS.staticDir}/index.html is missing — run \`pnpm --dir web build\` first\n`,
);
process.exit(2);
}
fs.mkdirSync(OPTIONS.out, { recursive: true });
// Which bundle was shot? A rebuild during the run (another workstream, or a
// `vite build` in parallel) changes the asset hash and can 503 a shot.
const buildBefore = buildFingerprint();
let base = OPTIONS.base ? OPTIONS.base.replace(/\/+$/, "") : null;
let pairBase = null;
if (OPTIONS.serveStatic) {
const server = await startMockServer();
base = base ?? `http://127.0.0.1:${server.port}`;
try {
const pairServer = await startMockServer({ pairOnly: true });
pairBase = `http://127.0.0.1:${pairServer.port}`;
} catch (error) {
process.stderr.write(`ui-shots: unpaired check skipped (${error.message})\n`);
}
}
const origin = new URL(base).origin;
let playwright;
try {
playwright = loadPlaywright();
} catch (error) {
process.stderr.write(`ui-shots: ${error.message}\n`);
process.exit(2);
}
const executablePath = chromePath();
const browser = await playwright.pw.chromium.launch({
headless: true,
...(executablePath ? { executablePath } : {}),
args: ["--no-sandbox"],
});
const shots = [];
const checks = [];
const matrix = [];
for (const viewport of VIEWPORT_MATRIX) {
for (const theme of THEMES) {
for (const spec of PAGES) matrix.push({ spec, viewport, theme });
}
}
try {
for (let index = 0; index < matrix.length; index += 1) {
const { spec, viewport, theme } = matrix[index];
shots.push(await shootPage(browser, { base, origin, page: spec, viewport, theme, index, total: matrix.length }));
}
if (pairBase) {
const pairOrigin = new URL(pairBase).origin;
checks.push(await checkUnpaired(browser, { pairBase, pairOrigin, origin: pairOrigin }));
} else {
notes.push("unpaired redirect check skipped (needs --serve-static)");
}
} finally {
await browser.close();
for (const child of children) {
if (child.exitCode === null) child.kill("SIGTERM");
}
}
const passed = shots.filter((shot) => shot.checks.every((check) => check.ok)).length;
const buildAfter = buildFingerprint();
if (buildBefore && buildAfter && buildBefore.indexMtime !== buildAfter.indexMtime) {
notes.push(
`web/dist changed during the run (${buildBefore.assets.join(",")} → ${buildAfter.assets.join(",")}); a parallel rebuild can 503 a shot`,
);
}
const report = {
round: OPTIONS.round,
generatedAt: new Date().toISOString(),
durationMs: Date.now() - startedAt,
base,
pairBase,
out: OPTIONS.out,
matrix: OPTIONS.matrix,
viewports: VIEWPORT_MATRIX,
themes: THEMES,
pages: PAGES.map((page) => ({ id: page.id, route: page.route, primary: page.primary })),
playwright: playwright.spec,
browser: executablePath ?? "(playwright bundled chromium)",
summary: {
shots: shots.length,
passed,
failed: shots.length - passed,
failures: failures.length,
consoleErrors: shots.reduce((total, shot) => {
const observed = shot.checks.find((check) => check.name === "console-errors")?.observed;
return total + (observed && typeof observed === "object" ? observed.count : 0);
}, 0),
horizontalOverflow: shots.filter(
(shot) => !shot.checks.find((check) => check.name === "no-horizontal-overflow")?.ok,
).length,
},
failures,
notes,
staticDir: OPTIONS.staticDir,
build: buildAfter ?? buildBefore,
shots,
checks,
};
fs.writeFileSync(path.join(OPTIONS.out, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
const lines = [];
lines.push("");
lines.push(`ui-shots: ${report.summary.passed}/${report.summary.shots} shots clean → ${OPTIONS.out}`);
if (failures.length) {
lines.push("");
lines.push("FAILURES");
for (const failure of failures) {
lines.push(
` ${failure.shot} · ${failure.check}\n expected: ${JSON.stringify(failure.expected)}\n observed: ${JSON.stringify(failure.observed)}`,
);
}
}
if (notes.length) {
lines.push("");
lines.push("NOTES");
for (const note of notes) lines.push(` ${note}`);
}
lines.push(`report: ${path.join(OPTIONS.out, "report.json")}`);
process.stdout.write(`${lines.join("\n")}\n`);
process.exit(failures.length ? 1 : 0);
}
main().catch((error) => {
for (const child of children) {
if (child.exitCode === null) child.kill("SIGKILL");
}
process.stderr.write(`ui-shots: ${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
process.exit(2);
});