@firstpick/pi-package-webui 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +12 -0
  2. package/bin/pi-webui.mjs +190 -20
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/trust-boundaries.mjs +1 -0
  5. package/package.json +1 -1
  6. package/public/app.js +1454 -101
  7. package/public/index.html +155 -27
  8. package/public/service-worker.js +1 -1
  9. package/public/styles.css +731 -2
  10. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  11. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  12. package/tests/browser/interaction-continuity.spec.mjs +158 -0
  13. package/tests/browser/mobile-foundation.spec.mjs +11 -0
  14. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  15. package/tests/browser/stats-overlay.spec.mjs +265 -0
  16. package/tests/codex-fast-mode-static.test.mjs +2 -2
  17. package/tests/component-update-api-static.test.mjs +67 -0
  18. package/tests/component-update-state.test.mjs +80 -0
  19. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  20. package/tests/fast-mode-client-static.test.mjs +1 -1
  21. package/tests/fixtures/fake-pi.mjs +129 -5
  22. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  23. package/tests/interaction-state-stability-static.test.mjs +21 -4
  24. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  25. package/tests/mobile-foundation-static.test.mjs +6 -4
  26. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  27. package/tests/mobile-static.test.mjs +2 -1
  28. package/tests/native-parity-harness.test.mjs +2 -0
  29. package/tests/open-issue-wizard-static.test.mjs +1 -1
  30. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  31. package/tests/sse-backpressure-harness.test.mjs +51 -12
  32. package/tests/stats-dashboard-static.test.mjs +266 -0
@@ -48,7 +48,15 @@ class FakeResponse {
48
48
  async json() { return this._json; }
49
49
  }
50
50
 
51
- function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus = 200, workflowModuleStatus = 404 } = {}) {
51
+ function makeEnvironment({
52
+ importApp,
53
+ stylesheetLoaded = true,
54
+ stylesheetStatus = 200,
55
+ workflowModuleStatus = 404,
56
+ manifestStatus = 200,
57
+ manifestText = '{"name":"Pi Web UI"}',
58
+ hangingHealth = false,
59
+ } = {}) {
52
60
  const elements = {
53
61
  panel: new FakeElement({ hidden: true }),
54
62
  reason: new FakeElement(),
@@ -57,7 +65,7 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
57
65
  reload: new FakeElement(),
58
66
  copyStatus: new FakeElement(),
59
67
  };
60
- const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=92", sheet: stylesheetLoaded ? {} : null });
68
+ const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=93", sheet: stylesheetLoaded ? {} : null });
61
69
  const listeners = new Map();
62
70
  const timers = new Map();
63
71
  let timerId = 0;
@@ -76,7 +84,7 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
76
84
  removeEventListener(name) { listeners.delete(name); },
77
85
  };
78
86
  const document = {
79
- currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=103" } }),
87
+ currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=104" } }),
80
88
  readyState: "complete",
81
89
  querySelector(selector) {
82
90
  return {
@@ -94,10 +102,14 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
94
102
 
95
103
  async function fetch(input) {
96
104
  const url = String(input);
97
- if (url.includes("/api/health")) return new FakeResponse(url, 200, { type: "application/json", json: { ok: true, webuiVersion: "0.7.6", remoteAuthPin: "1234" } });
105
+ if (url.includes("/api/health")) {
106
+ if (hangingHealth) return new Promise(() => {});
107
+ return new FakeResponse(url, 200, { type: "application/json", json: { ok: true, webuiVersion: "0.7.6", remoteAuthPin: "1234" } });
108
+ }
98
109
  if (url.includes("/app.js")) return new FakeResponse(url, 200, { type: "text/javascript", text: 'import "./workflow-status-stack.mjs";\nimport "./fast-output-live.mjs";' });
99
110
  if (url.includes("workflow-status-stack.mjs")) return new FakeResponse(url, workflowModuleStatus, { type: workflowModuleStatus === 200 ? "text/javascript" : "application/json" });
100
111
  if (url.includes("fast-output-live.mjs")) return new FakeResponse(url, 200, { type: "text/javascript" });
112
+ if (url.includes("manifest.webmanifest")) return new FakeResponse(url, manifestStatus, { type: manifestStatus === 200 ? "application/manifest+json" : "text/html", text: manifestText });
101
113
  if (url.includes("styles.css")) return new FakeResponse(url, stylesheetStatus, { type: "text/css" });
102
114
  return new FakeResponse(url, 404);
103
115
  }
@@ -124,6 +136,12 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
124
136
  elements,
125
137
  listeners,
126
138
  timers,
139
+ fireTimers() {
140
+ for (const [id, callback] of [...timers]) {
141
+ timers.delete(id);
142
+ callback();
143
+ }
144
+ },
127
145
  copied: () => copied,
128
146
  reloaded: () => reloaded,
129
147
  };
@@ -168,13 +186,53 @@ await settleAsyncWork();
168
186
  assert.equal(stylesheetFailure.elements.panel.hidden, false, "a missing critical stylesheet should expose the boot-failure panel");
169
187
  assert.match(stylesheetFailure.elements.report.value, /Critical stylesheet returned HTTP 404/);
170
188
 
189
+ const syntaxFailureWithManifestNoise = makeEnvironment({
190
+ importApp: async () => {
191
+ const error = new Error("Unexpected token '}'");
192
+ error.name = "SyntaxError";
193
+ throw error;
194
+ },
195
+ workflowModuleStatus: 200,
196
+ manifestText: "<!doctype html><title>wrong response</title>",
197
+ });
198
+ vm.runInNewContext(loaderSource, syntaxFailureWithManifestNoise.context, { filename: "webui-boot-loader.js" });
199
+ await settleAsyncWork();
200
+ assert.match(syntaxFailureWithManifestNoise.elements.reason.textContent, /JavaScript failed during startup: SyntaxError: Unexpected token/);
201
+ assert.match(syntaxFailureWithManifestNoise.elements.report.value, /entry module: HTTP 200 text\/javascript/);
202
+ assert.match(syntaxFailureWithManifestNoise.elements.report.value, /optional web manifest: HTTP 200 application\/manifest\+json.*invalid JSON/);
203
+ assert.match(syntaxFailureWithManifestNoise.elements.report.value, /web manifest has a separate problem.*does not execute or block app\.js startup/i, "manifest parse noise should be identified as non-blocking");
204
+
205
+ const stalledBoot = makeEnvironment({
206
+ importApp: async () => new Promise(() => {}),
207
+ workflowModuleStatus: 200,
208
+ });
209
+ vm.runInNewContext(loaderSource, stalledBoot.context, { filename: "webui-boot-loader.js" });
210
+ stalledBoot.fireTimers();
211
+ await settleAsyncWork();
212
+ assert.match(stalledBoot.elements.reason.textContent, /WebUI startup stalled even though the current HTTP checks succeeded/);
213
+ assert.match(stalledBoot.elements.report.value, /Error: Error: Startup watchdog timed out/);
214
+
215
+ const hangingDiagnostic = makeEnvironment({
216
+ importApp: async () => { throw new Error("Startup module failed before diagnostics"); },
217
+ workflowModuleStatus: 200,
218
+ hangingHealth: true,
219
+ });
220
+ vm.runInNewContext(loaderSource, hangingDiagnostic.context, { filename: "webui-boot-loader.js" });
221
+ await settleAsyncWork();
222
+ hangingDiagnostic.fireTimers();
223
+ await settleAsyncWork();
224
+ assert.equal(hangingDiagnostic.elements.panel.hidden, false, "the failure panel should remain usable while a diagnostic request hangs");
225
+ assert.doesNotMatch(hangingDiagnostic.elements.report.value, /Collecting diagnostics/, "bounded probes must always replace the collecting placeholder");
226
+ assert.match(hangingDiagnostic.elements.reason.textContent, /diagnostic check timed out while probing \/api\/health/i);
227
+ assert.match(hangingDiagnostic.elements.report.value, /backend health: diagnostic timed out after 3 seconds/);
228
+
171
229
  const startupModuleNames = [...new Set([...app.matchAll(/(?:\bfrom\s+|\bimport\s*(?:\(\s*)?)["']\.\/([^"'?]+)(?:\?[^"']*)?["']/g)].map((match) => match[1]))];
172
230
  assert.ok(startupModuleNames.length >= 1, "the startup-module invariant should discover app.js imports");
173
231
  for (const moduleName of startupModuleNames) {
174
232
  assert.ok(serviceWorker.includes(`"/${moduleName}"`), `the PWA app shell should include every app.js startup module: ${moduleName}`);
175
233
  }
176
234
  assert.match(serviceWorker, /pi-webui-pwa-v\d+/, "the app-shell cache should retain a versioned identity");
177
- assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=103"), "the inline loader should own app module startup");
235
+ assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=104"), "the inline loader should own app module startup");
178
236
  assert.doesNotMatch(html, /<script type="module" src="\/app\.js/, "the app module should not bypass the guarded loader");
179
237
 
180
238
  console.log("boot-failure-diagnostics.test.mjs passed");
@@ -0,0 +1,180 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { createServer } from "node:net";
4
+ import { mkdtemp, rm } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { dirname, join } from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { fileURLToPath } from "node:url";
9
+ import { expect, test } from "@playwright/test";
10
+
11
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
12
+ const serverScript = join(root, "bin", "pi-webui.mjs");
13
+ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
14
+
15
+ async function freePort() {
16
+ const server = createServer();
17
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
18
+ const { port } = server.address();
19
+ await new Promise((resolve) => server.close(resolve));
20
+ return port;
21
+ }
22
+
23
+ let child;
24
+ let baseURL;
25
+ let tempRoot;
26
+ let output = "";
27
+
28
+ test.beforeAll(async () => {
29
+ const port = await freePort();
30
+ tempRoot = await mkdtemp(join(tmpdir(), "pi-webui-component-updates-"));
31
+ baseURL = `http://127.0.0.1:${port}`;
32
+ child = spawn(process.execPath, [serverScript, "--cwd", tempRoot, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
33
+ stdio: ["ignore", "pipe", "pipe"],
34
+ env: {
35
+ ...process.env,
36
+ PI_WEBUI_RPC_SUPERVISOR: "0",
37
+ PI_CODING_AGENT_DIR: join(tempRoot, "agent"),
38
+ PI_WEBUI_SETTINGS_FILE: join(tempRoot, "settings.json"),
39
+ },
40
+ });
41
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
42
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
43
+ for (let attempt = 0; attempt < 80; attempt += 1) {
44
+ if (child.exitCode !== null) break;
45
+ try {
46
+ const response = await fetch(`${baseURL}/api/health`, { signal: AbortSignal.timeout(500) });
47
+ if (response.ok) return;
48
+ } catch {
49
+ // Wait for the package server and fake Pi fixture to start.
50
+ }
51
+ await delay(100);
52
+ }
53
+ throw new Error(`Pi Web UI did not start:\n${output}`);
54
+ });
55
+
56
+ test.afterAll(async () => {
57
+ child?.kill("SIGTERM");
58
+ if (child) await new Promise((resolve) => child.once("exit", resolve));
59
+ await rm(tempRoot, { recursive: true, force: true });
60
+ });
61
+
62
+ test("component tags and dialogs expose safe background update lifecycle", async ({ page }) => {
63
+ const requests = [];
64
+ let statusPollsAfterStart = 0;
65
+ const status = {
66
+ updateAvailable: true,
67
+ updateInProgress: false,
68
+ canRunUpdate: true,
69
+ pi: { checked: true, currentVersion: "0.83.0", latestVersion: "0.84.0", updateAvailable: true },
70
+ webui: { checked: true, currentVersion: "0.8.1", latestVersion: "0.8.2", updateAvailable: true },
71
+ componentUpdates: {
72
+ pi: { target: "pi", state: "idle", message: "", error: "", canStart: true, unavailableReason: "", restartRequired: false },
73
+ webui: {
74
+ target: "webui",
75
+ state: "idle",
76
+ message: "",
77
+ error: "",
78
+ canStart: false,
79
+ unavailableReason: "Automatic Web UI update is unavailable from a source or development checkout.",
80
+ restartRequired: true,
81
+ },
82
+ },
83
+ };
84
+
85
+ await page.route("**/api/pi-release-notes", async (route) => {
86
+ await route.fulfill({
87
+ status: 200,
88
+ contentType: "application/json",
89
+ body: JSON.stringify({ ok: true, data: { version: "0.83.0", body: "Fixture release notes", url: "https://example.test/pi" } }),
90
+ });
91
+ });
92
+ await page.route("**/api/component-update", async (route) => {
93
+ const body = route.request().postDataJSON();
94
+ requests.push({ method: route.request().method(), body });
95
+ const target = body?.target;
96
+ status.updateInProgress = true;
97
+ status.componentUpdates[target] = {
98
+ ...status.componentUpdates[target],
99
+ state: "running",
100
+ canStart: false,
101
+ message: `Updating ${target === "pi" ? "Pi" : "Web UI"}…`,
102
+ error: "",
103
+ };
104
+ await route.fulfill({
105
+ status: 202,
106
+ contentType: "application/json",
107
+ body: JSON.stringify({ ok: true, data: status.componentUpdates[target] }),
108
+ });
109
+ });
110
+ await page.route("**/api/update-status*", async (route) => {
111
+ if (status.componentUpdates.pi.state === "running") {
112
+ statusPollsAfterStart += 1;
113
+ status.componentUpdates.pi = {
114
+ ...status.componentUpdates.pi,
115
+ state: "succeeded",
116
+ canStart: true,
117
+ message: "Pi update completed.",
118
+ };
119
+ status.updateInProgress = false;
120
+ }
121
+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ ok: true, data: status }) });
122
+ });
123
+
124
+ await page.goto(baseURL);
125
+ const piTag = page.locator("#piVersionButton");
126
+ const webuiTag = page.locator("#webuiVersionButton");
127
+ await expect(piTag).toHaveAttribute("data-update-state", "available", { timeout: 8_000 });
128
+ await expect(piTag).toHaveAccessibleName(/Pi .*update available/);
129
+ await expect(webuiTag).toHaveAttribute("data-update-state", "available");
130
+ await expect(webuiTag).toHaveAccessibleName(/Web UI .*update available/);
131
+ await page.locator("#updateNotificationDismissButton").click();
132
+ await expect(page.locator("#updateNotification")).toBeHidden();
133
+
134
+ await webuiTag.click();
135
+ const webuiDialog = page.locator("#webuiPackageDialog");
136
+ await expect(webuiDialog).toBeVisible();
137
+ await expect(page.locator("#webuiPackageCurrentVersion")).toHaveText("v0.8.1");
138
+ await expect(page.locator("#webuiPackageLatestVersion")).toHaveText("v0.8.2");
139
+ await expect(page.locator("#webuiPackageNpmButton")).toHaveText("View on npm");
140
+ await expect(page.locator("#webuiComponentUpdateStatus")).toContainText("source or development checkout");
141
+ await expect(page.locator("#webuiComponentUpdateButton")).toBeDisabled();
142
+ await page.locator("#webuiPackageCloseButton").click();
143
+
144
+ await piTag.click();
145
+ const piDialog = page.locator("#piReleaseNotesDialog");
146
+ await expect(piDialog).toBeVisible();
147
+ await expect(page.locator("#piComponentUpdateStatus")).toContainText("Pi v0.83.0 → v0.84.0 is available");
148
+ await page.locator("#piComponentUpdateButton").click();
149
+ await expect(page.locator("#confirmationDialog")).toBeVisible();
150
+ await expect(page.locator("#confirmationSummary")).toContainText("Web UI server and running Pi tabs are not restarted");
151
+ await page.locator("#confirmationConfirmButton").click();
152
+
153
+ await expect(piTag).toHaveAttribute("data-update-state", "running");
154
+ await expect(piTag).toHaveAccessibleName(/update running/);
155
+ await expect(page.locator("#piComponentUpdateButton")).toBeDisabled();
156
+ assert.deepEqual(requests, [{ method: "POST", body: { target: "pi" } }], "the dialog must submit exactly one Pi-only POST");
157
+
158
+ await expect(piTag).toHaveAttribute("data-update-state", "succeeded", { timeout: 5_000 });
159
+ await expect(page.locator("#piComponentUpdateStatus")).toContainText("New or reloaded Pi sessions use the update");
160
+ await expect(page.locator("#piComponentUpdateStatus")).toContainText("already-running tabs keep their current runtime");
161
+ assert.ok(statusPollsAfterStart >= 1, "the browser should poll while the accepted job is running");
162
+ const pollsAtSuccess = statusPollsAfterStart;
163
+ await page.waitForTimeout(1_300);
164
+ assert.equal(statusPollsAfterStart, pollsAtSuccess, "short polling should stop after terminal success");
165
+ await page.locator("#piReleaseNotesCloseButton").click();
166
+ await expect(piDialog).toBeHidden();
167
+
168
+ status.componentUpdates.webui = {
169
+ ...status.componentUpdates.webui,
170
+ state: "failed",
171
+ canStart: true,
172
+ message: "Web UI update failed.",
173
+ error: "bounded fixture failure",
174
+ };
175
+ await webuiTag.click();
176
+ await expect(page.locator("#webuiComponentUpdateStatus")).toContainText("bounded fixture failure");
177
+ await expect(page.locator("#webuiComponentUpdateStatus")).toContainText("retry the update");
178
+ await expect(page.locator("#webuiComponentUpdateButton")).toBeEnabled();
179
+ await expect(page.locator("#webuiComponentUpdateButton")).toHaveText("Retry Web UI update");
180
+ });
@@ -305,6 +305,9 @@ test("main output text selection survives streaming-tail and settlement rerender
305
305
  await expect.poll(() => originalSurface.evaluate((node) => node.isConnected), { timeout: 8_000 }).toBe(true);
306
306
  await expect.poll(() => originalBubble.evaluate((node) => ({ connected: node.isConnected, streaming: node.classList.contains("streaming"), itemKey: node.dataset.itemKey, messageKey: node.dataset.transcriptMessageKey })), { timeout: 8_000 }).toEqual({ connected: true, streaming: false, itemKey: "m:4", messageKey: "m:4" });
307
307
  await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || ""), { timeout: 8_000 }).toBe(selectedText);
308
+ await waitForFixtureSettlement(page, tabId);
309
+ await delay(4_000);
310
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
308
311
  });
309
312
 
310
313
  test("backward normal-output selection keeps its direction through streaming and exact settlement", async ({ page }) => {
@@ -458,6 +461,7 @@ test("selectable live tool output restores an unchanged range across body reconc
458
461
  const toolBody = page.locator(".message.toolExecution .message-body").last();
459
462
  const selectedText = "tool selection literal";
460
463
  await expect(toolBody).toContainText("unselected revision one");
464
+ await toolBody.locator(".tool-output-details").evaluate((node) => { node.open = true; });
461
465
  assert.equal((await selectRenderedText(toolBody, selectedText)).text, selectedText);
462
466
  const bodyHandle = await toolBody.elementHandle();
463
467
  assert.ok(bodyHandle, "tool selection continuity needs an inspectable semantic surface");
@@ -467,6 +471,32 @@ test("selectable live tool output restores an unchanged range across body reconc
467
471
  await waitForFixtureSettlement(page);
468
472
  });
469
473
 
474
+ test("expanded live tool output preserves reader scroll and summary focus across updates", async ({ page }) => {
475
+ await page.setViewportSize({ width: 1280, height: 800 });
476
+ await page.goto(baseURL);
477
+ await triggerTranscriptContinuity(page, "tool");
478
+
479
+ const toolBody = page.locator(".message.toolExecution .message-body").last();
480
+ const details = toolBody.locator(".tool-output-details");
481
+ const output = details.locator(".tool-output-code");
482
+ const summary = details.locator("summary");
483
+ await expect(toolBody).toContainText("unselected revision one");
484
+ await summary.click();
485
+ const scrollState = await output.evaluate((node) => {
486
+ node.scrollTop = Math.min(180, node.scrollHeight - node.clientHeight);
487
+ return { top: node.scrollTop };
488
+ });
489
+ assert.ok(scrollState.top > 0, "the tool fixture must create vertical reader scroll");
490
+ await summary.focus();
491
+ await expect(summary).toBeFocused();
492
+
493
+ await expect(toolBody).toContainText("unselected revision two");
494
+ await expect.poll(() => details.evaluate((node) => node.open)).toBe(true);
495
+ await expect.poll(() => output.evaluate((node) => node.scrollTop)).toBe(scrollState.top);
496
+ await expect(summary).toBeFocused();
497
+ await waitForFixtureSettlement(page);
498
+ });
499
+
470
500
  test("authoritative divergence clears a stale live-output selection", async ({ page }) => {
471
501
  await page.setViewportSize({ width: 1280, height: 800 });
472
502
  await page.goto(baseURL);
@@ -570,6 +600,134 @@ test("Mermaid async rendering leaves selected source nodes connected", async ({
570
600
  await waitForFixtureSettlement(page);
571
601
  });
572
602
 
603
+ test("cross-message selection survives a whole transcript rebuild", async ({ page }) => {
604
+ await page.setViewportSize({ width: 1280, height: 800 });
605
+ await page.goto(baseURL);
606
+ await triggerTranscriptContinuity(page, "duplicate");
607
+ await waitForFixtureSettlement(page);
608
+ const surfaces = page.locator(".message.assistant:not(.streaming) .markdown-body");
609
+ await expect.poll(() => surfaces.count()).toBeGreaterThanOrEqual(2);
610
+ const selectedLength = await page.locator("#chat").evaluate((chat) => {
611
+ const outputs = [...chat.querySelectorAll(".message.assistant:not(.streaming) .markdown-body")];
612
+ const textNodes = (root) => {
613
+ const nodes = [];
614
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
615
+ while (walker.nextNode()) {
616
+ if ((walker.currentNode.data || "").trim()) nodes.push(walker.currentNode);
617
+ }
618
+ return nodes;
619
+ };
620
+ const startNodes = textNodes(outputs[0]);
621
+ const endNodes = textNodes(outputs.at(-1));
622
+ const startNode = startNodes.at(-1);
623
+ const endNode = endNodes[0];
624
+ const range = document.createRange();
625
+ range.setStart(startNode, Math.max(0, startNode.data.length - 8));
626
+ range.setEnd(endNode, Math.min(18, endNode.data.length));
627
+ const selection = window.getSelection();
628
+ selection.removeAllRanges();
629
+ selection.addRange(range);
630
+ const textOffset = (surface, node, offset) => {
631
+ const prefix = document.createRange();
632
+ prefix.selectNodeContents(surface);
633
+ prefix.setEnd(node, offset);
634
+ return prefix.toString().length;
635
+ };
636
+ const endpoint = (surface, node, offset) => ({
637
+ itemKey: surface.closest(".message")?.dataset.transcriptMessageKey || surface.closest(".message")?.dataset.itemKey || "",
638
+ surfaceKey: surface.dataset.transcriptSurfaceKey || "",
639
+ offset: textOffset(surface, node, offset),
640
+ });
641
+ window.__crossMessageSelectionText = selection.toString();
642
+ window.__crossMessageSelectionBoundary = {
643
+ start: window.__crossMessageSelectionText.slice(0, 8),
644
+ end: window.__crossMessageSelectionText.slice(-18),
645
+ };
646
+ window.__crossMessageSelectionEndpoints = {
647
+ anchor: endpoint(outputs[0], selection.anchorNode, selection.anchorOffset),
648
+ focus: endpoint(outputs.at(-1), selection.focusNode, selection.focusOffset),
649
+ };
650
+ return window.__crossMessageSelectionText.length;
651
+ });
652
+ assert.ok(selectedLength > 20, "the fixture must create a real cross-message browser Range");
653
+
654
+ await page.evaluate(() => {
655
+ const key = "pi-webui-optional-features-disabled";
656
+ const current = JSON.parse(localStorage.getItem(key) || "[]");
657
+ const next = current.includes("bangCommandAutocomplete")
658
+ ? current.filter((id) => id !== "bangCommandAutocomplete")
659
+ : [...current, "bangCommandAutocomplete"];
660
+ localStorage.setItem(key, JSON.stringify(next));
661
+ window.dispatchEvent(new StorageEvent("storage", { key }));
662
+ });
663
+
664
+ await expect.poll(() => page.evaluate(() => {
665
+ const selection = window.getSelection();
666
+ const current = selection?.toString() || "";
667
+ const anchorSurface = selection?.anchorNode?.parentElement?.closest?.("[data-transcript-surface-key]");
668
+ const focusSurface = selection?.focusNode?.parentElement?.closest?.("[data-transcript-surface-key]");
669
+ const anchorBubble = anchorSurface?.closest(".message");
670
+ const focusBubble = focusSurface?.closest(".message");
671
+ const anchorItemKey = anchorBubble?.dataset.transcriptMessageKey || anchorBubble?.dataset.itemKey || "";
672
+ const focusItemKey = focusBubble?.dataset.transcriptMessageKey || focusBubble?.dataset.itemKey || "";
673
+ return current.length > 20
674
+ && current.startsWith(window.__crossMessageSelectionBoundary.start)
675
+ && current.endsWith(window.__crossMessageSelectionBoundary.end)
676
+ && anchorItemKey === window.__crossMessageSelectionEndpoints.anchor.itemKey
677
+ && focusItemKey === window.__crossMessageSelectionEndpoints.focus.itemKey;
678
+ })).toBe(true);
679
+ });
680
+
681
+ test("individually expanded tool details stay open through transcript rerenders", async ({ page }) => {
682
+ await page.setViewportSize({ width: 1280, height: 800 });
683
+ await page.goto(baseURL);
684
+ await triggerTranscriptContinuity(page, "tool");
685
+ const details = page.locator(".message.toolExecution .tool-raw-details").last();
686
+ await expect(details).toBeAttached();
687
+ await expect.poll(() => details.evaluate((node) => node.open)).toBe(false);
688
+ const summary = details.locator("summary");
689
+ await summary.click();
690
+ await expect.poll(() => details.evaluate((node) => node.open)).toBe(true);
691
+ await waitForFixtureSettlement(page);
692
+ const rawOutput = details.locator(".tool-raw-code");
693
+ const scrollTop = await rawOutput.evaluate((node) => {
694
+ node.scrollTop = Math.min(140, node.scrollHeight - node.clientHeight);
695
+ return node.scrollTop;
696
+ });
697
+ assert.ok(scrollTop > 0, "the settled raw-tool fixture must create reader scroll");
698
+ await summary.focus();
699
+ await expect(summary).toBeFocused();
700
+
701
+ await page.evaluate(() => {
702
+ const key = "pi-webui-optional-features-disabled";
703
+ const current = JSON.parse(localStorage.getItem(key) || "[]");
704
+ const next = current.includes("bangCommandAutocomplete")
705
+ ? current.filter((id) => id !== "bangCommandAutocomplete")
706
+ : [...current, "bangCommandAutocomplete"];
707
+ localStorage.setItem(key, JSON.stringify(next));
708
+ window.dispatchEvent(new StorageEvent("storage", { key }));
709
+ });
710
+
711
+ await delay(4_000);
712
+ await expect.poll(() => details.evaluate((node) => node.open)).toBe(true);
713
+ await expect.poll(() => rawOutput.evaluate((node) => node.scrollTop)).toBe(scrollTop);
714
+ await expect(summary).toBeFocused();
715
+ });
716
+
717
+ test("same-mode output control preserves settled output selection", async ({ page }) => {
718
+ await page.setViewportSize({ width: 1280, height: 800 });
719
+ await page.goto(baseURL);
720
+ const output = page.locator(".message.assistant .markdown-body").first();
721
+ const selectedText = "fake answer";
722
+ await expect(output).toContainText(selectedText);
723
+ await waitForFixtureSettlement(page);
724
+ assert.equal((await selectRenderedText(output, selectedText)).text, selectedText);
725
+
726
+ await api(page, "/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: "normal" } });
727
+
728
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
729
+ });
730
+
573
731
  test("tab navigation clears transcript selection and never restores it into another context", async ({ page }) => {
574
732
  await page.setViewportSize({ width: 1280, height: 800 });
575
733
  await page.goto(baseURL);
@@ -238,6 +238,17 @@ test("mobile continuity preserves drafts, restores metadata honestly, and retrie
238
238
  await context.close();
239
239
  });
240
240
 
241
+ test("an extension response clears stale local running state after canonical idle", async ({ page }) => {
242
+ await page.goto(baseURL);
243
+ await page.locator("#promptInput").fill("fixture mobile blocker");
244
+ await page.locator("#sendButton").click();
245
+ await expect(page.locator("#dialogTitle")).toHaveText("Fixture blocker");
246
+ await expect(page.locator("#chat .runIndicator")).toContainText("Waiting for your confirm response…");
247
+ await page.locator("#dialogActions").getByRole("button", { name: "Yes", exact: true }).click();
248
+ await expect(page.locator("#dialog")).not.toBeVisible();
249
+ await expect(page.locator("#chat .runIndicator")).toBeHidden({ timeout: 5_000 });
250
+ });
251
+
241
252
  test("a blocker notification switches to its background tab before exact-target validation", async ({ browser }) => {
242
253
  const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
243
254
  const page = await context.newPage();
@@ -0,0 +1,101 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createServer } from "node:net";
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import { expect, test } from "@playwright/test";
9
+
10
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
11
+ const serverScript = join(root, "bin", "pi-webui.mjs");
12
+ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
13
+
14
+ async function freePort() {
15
+ const server = createServer();
16
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
17
+ const { port } = server.address();
18
+ await new Promise((resolve) => server.close(resolve));
19
+ return port;
20
+ }
21
+
22
+ let child;
23
+ let baseURL;
24
+ let tempRoot;
25
+ let output = "";
26
+
27
+ test.beforeAll(async () => {
28
+ const port = await freePort();
29
+ tempRoot = await mkdtemp(join(tmpdir(), "pi-webui-side-panel-order-"));
30
+ baseURL = `http://127.0.0.1:${port}`;
31
+ child = spawn(process.execPath, [serverScript, "--cwd", tempRoot, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
32
+ stdio: ["ignore", "pipe", "pipe"],
33
+ env: {
34
+ ...process.env,
35
+ PI_WEBUI_RPC_SUPERVISOR: "0",
36
+ PI_CODING_AGENT_DIR: join(tempRoot, "agent"),
37
+ PI_WEBUI_SETTINGS_FILE: join(tempRoot, "settings.json"),
38
+ },
39
+ });
40
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
41
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
42
+ for (let attempt = 0; attempt < 80; attempt += 1) {
43
+ if (child.exitCode !== null) break;
44
+ try {
45
+ const response = await fetch(`${baseURL}/api/health`, { signal: AbortSignal.timeout(500) });
46
+ if (response.ok) return;
47
+ } catch {
48
+ // Wait for the real server and fake Pi fixture to start.
49
+ }
50
+ await delay(100);
51
+ }
52
+ throw new Error(`Pi Web UI did not start:\n${output}`);
53
+ });
54
+
55
+ test.afterAll(async () => {
56
+ child?.kill("SIGTERM");
57
+ if (child) await new Promise((resolve) => child.once("exit", resolve));
58
+ await rm(tempRoot, { recursive: true, force: true });
59
+ });
60
+
61
+ async function sectionOrder(page) {
62
+ return page.locator("#sidePanel .side-panel-body > [data-side-panel-section]").evaluateAll((sections) => (
63
+ sections.map((section) => section.dataset.sidePanelSection)
64
+ ));
65
+ }
66
+
67
+ test("Control Deck sections persist pointer and keyboard reordering", async ({ page }) => {
68
+ await page.setViewportSize({ width: 1440, height: 900 });
69
+ await page.goto(baseURL);
70
+ await expect(page.locator("#sidePanel")).toBeVisible();
71
+
72
+ const initialOrder = await sectionOrder(page);
73
+ expect(initialOrder.slice(0, 3)).toEqual(["controls", "files", "git"]);
74
+
75
+ const controls = page.locator('[data-side-panel-section-toggle="controls"]');
76
+ const git = page.locator('[data-side-panel-section-toggle="git"]');
77
+ const controlsBox = await controls.boundingBox();
78
+ const gitBox = await git.boundingBox();
79
+ expect(controlsBox).toBeTruthy();
80
+ expect(gitBox).toBeTruthy();
81
+ await page.mouse.move(controlsBox.x + controlsBox.width / 2, controlsBox.y + controlsBox.height / 2);
82
+ await page.mouse.down();
83
+ await page.mouse.move(controlsBox.x + controlsBox.width / 2, controlsBox.y + controlsBox.height / 2 + 12, { steps: 2 });
84
+ await page.mouse.move(gitBox.x + gitBox.width / 2, gitBox.y + gitBox.height - 4, { steps: 6 });
85
+ await page.mouse.up();
86
+
87
+ await expect.poll(async () => (await sectionOrder(page)).slice(0, 3)).toEqual(["files", "git", "controls"]);
88
+ await expect.poll(async () => page.evaluate(() => JSON.parse(localStorage.getItem("pi-webui-side-panel-section-order-v1") || "[]").slice(0, 3))).toEqual(["files", "git", "controls"]);
89
+
90
+ await page.reload();
91
+ await expect.poll(async () => (await sectionOrder(page)).slice(0, 3)).toEqual(["files", "git", "controls"]);
92
+
93
+ const movedControls = page.locator('[data-side-panel-section-toggle="controls"]');
94
+ await movedControls.focus();
95
+ await movedControls.press("Alt+ArrowUp");
96
+ await expect.poll(async () => (await sectionOrder(page)).slice(0, 3)).toEqual(["files", "controls", "git"]);
97
+ await expect(movedControls).toBeFocused();
98
+
99
+ await page.reload();
100
+ await expect.poll(async () => (await sectionOrder(page)).slice(0, 3)).toEqual(["files", "controls", "git"]);
101
+ });