@firstpick/pi-package-webui 0.8.1 → 0.8.3

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 (51) hide show
  1. package/README.md +21 -3
  2. package/bin/pi-webui.mjs +287 -32
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/git-workflow-preferences.mjs +246 -19
  5. package/lib/thinking-stream-recovery.mjs +156 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/ui-layout-settings.mjs +254 -0
  8. package/package.json +5 -3
  9. package/public/app.js +3072 -142
  10. package/public/index.html +188 -39
  11. package/public/service-worker.js +1 -1
  12. package/public/styles.css +1091 -39
  13. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  14. package/tests/browser/composer-action-grid-reorder.spec.mjs +303 -0
  15. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  16. package/tests/browser/feature-decision-output-popup.spec.mjs +156 -0
  17. package/tests/browser/interaction-continuity.spec.mjs +187 -0
  18. package/tests/browser/mobile-foundation.spec.mjs +11 -0
  19. package/tests/browser/persistent-ui-layout.spec.mjs +744 -0
  20. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  21. package/tests/browser/stats-overlay.spec.mjs +265 -0
  22. package/tests/codex-fast-mode-static.test.mjs +2 -2
  23. package/tests/component-update-api-static.test.mjs +67 -0
  24. package/tests/component-update-state.test.mjs +80 -0
  25. package/tests/composer-action-grid-reorder-static.test.mjs +63 -0
  26. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  27. package/tests/fast-mode-client-static.test.mjs +2 -2
  28. package/tests/feature-decision-output-popup-static.test.mjs +172 -0
  29. package/tests/fixtures/fake-pi.mjs +180 -6
  30. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  31. package/tests/git-workflow-preferences.test.mjs +4 -2
  32. package/tests/http-endpoints-harness.test.mjs +88 -1
  33. package/tests/interaction-state-stability-static.test.mjs +24 -4
  34. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  35. package/tests/mobile-foundation-static.test.mjs +6 -4
  36. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  37. package/tests/mobile-static.test.mjs +34 -16
  38. package/tests/native-parity-harness.test.mjs +2 -0
  39. package/tests/open-issue-wizard-static.test.mjs +1 -1
  40. package/tests/persistent-ui-layout-static.test.mjs +267 -0
  41. package/tests/questionnaire-dialog.test.mjs +511 -0
  42. package/tests/queue-edit-reorder-static.test.mjs +1 -0
  43. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  44. package/tests/side-panel-resize-static.test.mjs +1 -0
  45. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  46. package/tests/sse-backpressure-harness.test.mjs +51 -12
  47. package/tests/stats-dashboard-static.test.mjs +266 -0
  48. package/tests/subagent-launch-slots.test.mjs +1 -1
  49. package/tests/thinking-stream-recovery.test.mjs +88 -0
  50. package/tests/ui-layout-settings.test.mjs +92 -0
  51. package/tests/webui-settings-locking.test.mjs +159 -0
@@ -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
+ });
@@ -0,0 +1,265 @@
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-stats-dashboard-"));
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
+ FAKE_PI_STATS_PROMPT_CONTEXT: "1",
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 real 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
+ async function openStatsOverlay(page) {
63
+ await page.goto(baseURL);
64
+ // Poll the activation so it also waits for the app boot to attach listeners.
65
+ await expect
66
+ .poll(async () => page.evaluate(() => {
67
+ const dialog = document.querySelector("#statsOverlayDialog");
68
+ if (dialog?.open) return true;
69
+ document.querySelector("#optionsStatsButton")?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
70
+ return !!dialog?.open;
71
+ }))
72
+ .toBe(true);
73
+ await expect(page.locator("#statsOverlayTabs [role='tab']").first()).toBeVisible();
74
+ }
75
+
76
+ async function emitStatsPromptFixture(page, message) {
77
+ const tabsResponse = await page.request.get(`${baseURL}/api/tabs`);
78
+ expect(tabsResponse.ok()).toBe(true);
79
+ const tabsPayload = await tabsResponse.json();
80
+ const tabId = tabsPayload.data?.activeTabId || tabsPayload.data?.tabs?.[0]?.id;
81
+ expect(tabId).toBeTruthy();
82
+ const response = await page.request.post(`${baseURL}/api/prompt?tab=${encodeURIComponent(tabId)}`, {
83
+ data: { message, requestId: `stats-prompt-${Date.now()}-${Math.random().toString(36).slice(2)}` },
84
+ });
85
+ expect(response.ok()).toBe(true);
86
+ }
87
+
88
+ async function openPromptContextTab(page) {
89
+ await openStatsOverlay(page);
90
+ await emitStatsPromptFixture(page, "/stats-webui 14");
91
+ await page.locator("#statsOverlayTab-prompt").click();
92
+ await expect(page.locator("#statsOverlayBody .stats-prompt-initial")).toBeVisible();
93
+ }
94
+
95
+ async function emitMalformedSnapshot(page) {
96
+ await emitStatsPromptFixture(page, "fixture stats prompt malformed");
97
+ }
98
+
99
+ async function expectNoPromptHorizontalOverflow(page) {
100
+ const overflow = await page.evaluate(() => {
101
+ const selectors = ["html", "body", "#statsOverlayDialog", "#statsOverlayDialog form", "#statsOverlayBody", ".stats-prompt-pane"];
102
+ return selectors.map((selector) => {
103
+ const element = document.querySelector(selector);
104
+ return { selector, clientWidth: element?.clientWidth ?? -1, scrollWidth: element?.scrollWidth ?? -1 };
105
+ });
106
+ });
107
+ for (const measurement of overflow) {
108
+ expect(measurement.clientWidth, `${measurement.selector} should exist`).toBeGreaterThanOrEqual(0);
109
+ expect(measurement.scrollWidth, `${measurement.selector} should not overflow horizontally`).toBeLessThanOrEqual(measurement.clientWidth + 1);
110
+ }
111
+ }
112
+
113
+ test("stats overlay exposes stable tab/tabpanel semantics", async ({ page }) => {
114
+ await page.setViewportSize({ width: 1440, height: 900 });
115
+ await openStatsOverlay(page);
116
+
117
+ const tabs = page.locator("#statsOverlayTabs [role='tab']");
118
+ await expect(tabs).toHaveCount(7);
119
+
120
+ const first = tabs.first();
121
+ await expect(first).toHaveAttribute("id", "statsOverlayTab-overview");
122
+ await expect(first).toHaveAttribute("aria-selected", "true");
123
+ await expect(first).toHaveAttribute("aria-controls", "statsOverlayBody");
124
+ await expect(first).toHaveAttribute("tabindex", "0");
125
+
126
+ const second = tabs.nth(1);
127
+ await expect(second).toHaveAttribute("aria-selected", "false");
128
+ await expect(second).toHaveAttribute("tabindex", "-1");
129
+
130
+ const panel = page.locator("#statsOverlayBody");
131
+ await expect(panel).toHaveAttribute("role", "tabpanel");
132
+ await expect(panel).toHaveAttribute("aria-labelledby", "statsOverlayTab-overview");
133
+
134
+ await tabs.nth(3).click();
135
+ await expect(tabs.nth(3)).toHaveAttribute("aria-selected", "true");
136
+ await expect(tabs.nth(3)).toHaveAttribute("tabindex", "0");
137
+ await expect(first).toHaveAttribute("aria-selected", "false");
138
+ await expect(first).toHaveAttribute("tabindex", "-1");
139
+ await expect(panel).toHaveAttribute("aria-labelledby", "statsOverlayTab-sessions");
140
+ });
141
+
142
+ test("stats overlay tablist supports arrow, Home, and End keyboard navigation", async ({ page }) => {
143
+ await page.setViewportSize({ width: 1440, height: 900 });
144
+ await openStatsOverlay(page);
145
+
146
+ const tabs = page.locator("#statsOverlayTabs [role='tab']");
147
+ const panel = page.locator("#statsOverlayBody");
148
+
149
+ await tabs.first().focus();
150
+ await page.keyboard.press("ArrowRight");
151
+ await expect(tabs.nth(1)).toHaveAttribute("aria-selected", "true");
152
+ await expect(tabs.nth(1)).toBeFocused();
153
+ await expect(panel).toHaveAttribute("aria-labelledby", "statsOverlayTab-daily");
154
+
155
+ await page.keyboard.press("Enter");
156
+ await expect(tabs.nth(1)).toBeFocused();
157
+
158
+ await page.keyboard.press("ArrowLeft");
159
+ await expect(tabs.first()).toHaveAttribute("aria-selected", "true");
160
+ await expect(tabs.first()).toBeFocused();
161
+
162
+ await page.keyboard.press("End");
163
+ await expect(tabs.nth(6)).toHaveAttribute("aria-selected", "true");
164
+ await expect(tabs.nth(6)).toBeFocused();
165
+ await expect(panel).toHaveAttribute("aria-labelledby", "statsOverlayTab-raw");
166
+
167
+ await page.keyboard.press("ArrowRight");
168
+ await expect(tabs.first()).toHaveAttribute("aria-selected", "true", "ArrowRight should wrap to the first tab");
169
+
170
+ await page.keyboard.press("ArrowLeft");
171
+ await expect(tabs.nth(6)).toHaveAttribute("aria-selected", "true", "ArrowLeft should wrap to the last tab");
172
+
173
+ await page.keyboard.press("Home");
174
+ await expect(tabs.first()).toHaveAttribute("aria-selected", "true");
175
+ await expect(tabs.first()).toBeFocused();
176
+ });
177
+
178
+ test("Prompt/context renders structured native sections and preserves raw command output", async ({ page }) => {
179
+ await page.setViewportSize({ width: 1440, height: 900 });
180
+ await openPromptContextTab(page);
181
+
182
+ const pane = page.locator("#statsOverlayBody .stats-prompt-pane");
183
+ await expect(pane.locator(".stats-prompt-initial")).toHaveCount(1);
184
+ await expect(pane.locator(".stats-prompt-snapshot")).toHaveCount(1);
185
+ await expect(pane.locator(".stats-prompt-current")).toHaveCount(1);
186
+ await expect(pane.locator(".stats-prompt-legacy-fallback")).toHaveCount(0);
187
+ await expect(pane.locator(".stats-overlay-lines")).toHaveCount(0);
188
+ await expect(pane.locator(".stats-prompt-inventory-details")).toHaveCount(5);
189
+ await expectNoPromptHorizontalOverflow(page);
190
+
191
+ await expect(pane).toContainText("System <img src=x onerror=\"globalThis.fixturePwned=true\"> & \"quoted\"");
192
+ await expect(pane.locator("img, script")).toHaveCount(0);
193
+ expect(await page.evaluate(() => globalThis.fixturePwned)).toBeUndefined();
194
+ await expect(pane.getByText("Zero-token framing", { exact: true })).toBeVisible();
195
+ await expect(pane.locator(".stats-prompt-snapshot .stats-prompt-badge")).toHaveText("0 chars");
196
+
197
+ const progress = pane.locator("progress.stats-prompt-progress");
198
+ await expect(progress).toHaveAttribute("aria-label", "Actual current context utilization");
199
+ await expect(progress).toHaveAttribute("aria-valuetext", "0 tok used / n/a window · 0.0%");
200
+ await expect(progress).toHaveAttribute("value", "0");
201
+ await expect(pane).toContainText("Source composition below is a character-derived heuristic");
202
+ await expect(pane).toContainText("Actual − estimate");
203
+ await expect(pane).toContainText("-200 tok");
204
+
205
+ const details = pane.locator("details.stats-prompt-inventory-details");
206
+ const metadataSummary = details.first().locator("summary");
207
+ await metadataSummary.focus();
208
+ await page.keyboard.press("Enter");
209
+ await expect(details.first()).toHaveAttribute("open", "");
210
+ await expect(details.first()).toContainText("Current date");
211
+ await expect(details.first()).toContainText("n/a");
212
+
213
+ await details.nth(1).locator("summary").click();
214
+ await expect(details.nth(1)).toContainText("1 omitted");
215
+ await expect(details.nth(1)).toContainText("<script>fixture-tool</script>");
216
+ await expect(details.nth(1).locator("script")).toHaveCount(0);
217
+
218
+ await page.locator("#statsOverlayTab-raw").click();
219
+ const raw = page.locator("#statsOverlayBody .stats-overlay-lines");
220
+ await expect(raw.filter({ hasText: "RAW_PROMPT_INJECTION <keep>& exact" })).toHaveCount(1);
221
+ await expect(raw.filter({ hasText: "RAW_PROMPT_DETAILED </pre> exact" })).toHaveCount(1);
222
+ await expect(raw.filter({ hasText: "RAW_CONTEXT_BREAKDOWN <raw> exact" })).toHaveCount(1);
223
+ await expect(page.locator("#statsOverlayBody")).toContainText("RAW_PROMPT_INJECTION <keep>& exact\n\nRAW_PROMPT_DETAILED </pre> exact");
224
+ });
225
+
226
+ test("Prompt/context isolates a malformed subsection behind its matching legacy fallback", async ({ page }) => {
227
+ await page.setViewportSize({ width: 1440, height: 900 });
228
+ await openPromptContextTab(page);
229
+ await emitMalformedSnapshot(page);
230
+
231
+ const pane = page.locator("#statsOverlayBody .stats-prompt-pane");
232
+ await expect(pane.locator(".stats-prompt-legacy-fallback")).toHaveCount(1);
233
+ await expect(pane.locator(".stats-prompt-initial")).toHaveCount(1);
234
+ await expect(pane.locator(".stats-prompt-snapshot")).toHaveCount(0);
235
+ await expect(pane.locator(".stats-prompt-current")).toHaveCount(1);
236
+ await expect(pane.locator(".stats-overlay-lines")).toHaveCount(1);
237
+ await expect(pane.locator(".stats-prompt-legacy-fallback")).toContainText("Structured data unavailable");
238
+ await expect(pane.locator(".stats-overlay-lines")).toHaveText("RAW_PROMPT_DETAILED </pre> exact");
239
+ await expect(pane).not.toContainText("RAW_PROMPT_INJECTION <keep>& exact");
240
+ await expect(pane).not.toContainText("RAW_CONTEXT_BREAKDOWN <raw> exact");
241
+ });
242
+
243
+ test("Prompt/context causes no horizontal overflow at 390 and 320 pixels", async ({ page }) => {
244
+ await page.setViewportSize({ width: 390, height: 844 });
245
+ await openPromptContextTab(page);
246
+ for (const summary of await page.locator(".stats-prompt-inventory-details summary").all()) await summary.click();
247
+ await expectNoPromptHorizontalOverflow(page);
248
+
249
+ await page.setViewportSize({ width: 320, height: 568 });
250
+ await expectNoPromptHorizontalOverflow(page);
251
+
252
+ const nestedVerticalScrollers = await page.evaluate(() => [...document.querySelectorAll(".stats-prompt-pane *")]
253
+ .filter((element) => {
254
+ const overflowY = getComputedStyle(element).overflowY;
255
+ return ["auto", "scroll"].includes(overflowY) && element.scrollHeight > element.clientHeight + 1;
256
+ })
257
+ .map((element) => element.className || element.tagName));
258
+ expect(nestedVerticalScrollers).toEqual([]);
259
+
260
+ const tabs = page.locator("#statsOverlayTabs [role='tab']");
261
+ await tabs.nth(5).focus();
262
+ await page.keyboard.press("ArrowRight");
263
+ await expect(tabs.nth(6)).toHaveAttribute("aria-selected", "true", "keyboard navigation should keep working on narrow screens");
264
+ await expect(tabs.nth(6)).toBeFocused();
265
+ });
@@ -53,7 +53,7 @@ assert.match(app, /statusKey === CODEX_FAST_MODE_STATUS_KEY[\s\S]*?applyCodexFas
53
53
  assert.match(readme, /### Compact live output mode[\s\S]*?select \*\*Compact\*\*[\s\S]*?`compact-v1`/, "README should document Compact mode with the stable wire identifier");
54
54
  assert.match(readme, /### Codex subscription Fast mode[\s\S]*?service_tier: "priority"[\s\S]*?1\.5× faster[\s\S]*?2× Standard credits[\s\S]*?2\.5×/, "README should separately document subscription Fast mode and its cost semantics");
55
55
  // Intent preserved: browser-asset changes must advance the coherent cache tuple.
56
- assert.match(serviceWorker, /pi-webui-pwa-v61/, "PWA cache identity should be bumped for changed browser assets");
57
- assert.match(html, /data-app-src="\/app\.js\?v=103"/, "browser module URL should be cache-busted for Fast-mode wiring");
56
+ assert.match(serviceWorker, /pi-webui-pwa-v71/, "PWA cache identity should be bumped for changed browser assets");
57
+ assert.match(html, /data-app-src="\/app\.js\?v=112"/, "browser module URL should be cache-busted for Fast-mode wiring");
58
58
 
59
59
  console.log("codex-fast-mode-static.test.mjs passed");
@@ -0,0 +1,67 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const packageRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const server = await readFile(join(packageRoot, "bin", "pi-webui.mjs"), "utf8");
8
+
9
+ assert.match(
10
+ server,
11
+ /function updateStatusForRequest\(status, req\)[\s\S]*updateInProgress: privilegedUpdateInProgress\(\)[\s\S]*componentUpdates: componentUpdatesForRequest\(req\)/,
12
+ "update status should preserve top-level single-flight state and add per-component public state",
13
+ );
14
+ assert.match(
15
+ server,
16
+ /url\.pathname === "\/api\/component-update" && req\.method === "POST"[\s\S]*requireLocalhostRoute\(req, url\.pathname\)[\s\S]*readJsonBody\(req\)[\s\S]*validateComponentUpdateRequest\(body\)[\s\S]*startComponentUpdate\(validation\.target\)[\s\S]*sendJson\(res, 202/,
17
+ "component update starts should be localhost-only, validated, asynchronous 202 responses",
18
+ );
19
+ assert.match(
20
+ server,
21
+ /function startComponentUpdate\(target\)[\s\S]*piUpdateInProgress \|\| componentUpdateState\.hasRunning\(\)[\s\S]*componentUpdateState\.begin\(target\)[\s\S]*setImmediate\(\(\) => \{ void runComponentUpdate\(target\); \}\)/,
22
+ "component starts should reserve shared single-flight state before scheduling background execution",
23
+ );
24
+ assert.match(
25
+ server,
26
+ /async function runPiUpdateAndPrepareRestart[\s\S]*if \(componentUpdateState\.hasRunning\(\)\) throw makeHttpError\(409/,
27
+ "legacy updates should conflict with running component jobs",
28
+ );
29
+ assert.match(
30
+ server,
31
+ /async function resolveComponentUpdateTasks\(target\)[\s\S]*target === "pi"[\s\S]*resolvePiUpdateCommands\(\{ all: false \}\)[\s\S]*target === "webui"[\s\S]*currentWebuiComponentUpdateTask/,
32
+ "component resolution should keep Pi-only and WebUI-only paths separate",
33
+ );
34
+ assert.match(
35
+ server,
36
+ /async function currentWebuiComponentUpdateTask\(npmRuntime = \{\}\)[\s\S]*webuiComponentUpdateUnavailableReason\(\)[\s\S]*global Bun Web UI package[\s\S]*`\$\{WEBUI_PACKAGE\}@latest`[\s\S]*npmPrefixUpdateTask\("current Web UI package", installRoot, \[WEBUI_PACKAGE\], npmRuntime\)/,
37
+ "Web UI updates should refuse source mode and update only the Web UI package in supported Bun/npm topologies",
38
+ );
39
+ assert.match(
40
+ server,
41
+ /function webuiComponentUpdateUnavailableReason\(\)[\s\S]*webuiDevServer \|\| !String\(packageRoot\).*includes\("node_modules"\)[\s\S]*source or development checkout/,
42
+ "source and development checkouts should fail closed",
43
+ );
44
+ assert.match(
45
+ server,
46
+ /target === "webui"[\s\S]*let npmRuntime = \{\}[\s\S]*resolvePiUpdateCommands\(\{ all: false \}\)[\s\S]*preferredDirectories:[\s\S]*piInstallDirectory[\s\S]*catch[\s\S]*webui_component_update_npm_resolution_fallback[\s\S]*currentWebuiComponentUpdateTask\(npmRuntime\)/,
47
+ "the Web UI updater should prefer npm from the selected Pi installation and fall back when Pi resolution is unavailable",
48
+ );
49
+ assert.match(
50
+ server,
51
+ /url\.pathname === "\/api\/update" && req\.method === "POST"[\s\S]*runPiUpdateAndPrepareRestart\(\{ all: queryAll \|\| bodyAll \}\)[\s\S]*sendJson\(res, 200[\s\S]*shutdown\("api update", \{ preserveSessions: true \}\)/,
52
+ "the legacy update route should retain update-all selection, 200 completion, restart, and session preservation",
53
+ );
54
+ const targetedWebuiUpdater = server.match(/async function currentWebuiComponentUpdateTask\([^)]*\)[\s\S]*?\n}\n\nasync function resolveComponentUpdateTasks/)?.[0];
55
+ assert.ok(targetedWebuiUpdater, "the targeted Web UI updater source should be inspectable");
56
+ assert.doesNotMatch(
57
+ targetedWebuiUpdater,
58
+ /UPDATE_PACKAGE_NAMES|packagesPresentInInstallPrefix|optionalFeature|projectPackageRoot/,
59
+ "the targeted Web UI updater must not broaden into package-root or optional package updates",
60
+ );
61
+ assert.match(
62
+ server,
63
+ /catch \(error\) \{\n\s*updateStatusCache = null;\n\s*updateStatusCacheAt = 0;\n\s*componentUpdateState\.fail/,
64
+ "failed component updates should invalidate cached package status before publishing terminal state",
65
+ );
66
+
67
+ console.log("component update API static tests passed");
@@ -0,0 +1,80 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ ComponentUpdateState,
4
+ sanitizeComponentUpdateError,
5
+ validateComponentUpdateRequest,
6
+ } from "../lib/component-update-state.mjs";
7
+
8
+ const times = [
9
+ new Date("2030-01-01T00:00:00.000Z"),
10
+ new Date("2030-01-01T00:00:01.000Z"),
11
+ new Date("2030-01-01T00:00:02.000Z"),
12
+ new Date("2030-01-01T00:00:03.000Z"),
13
+ ];
14
+ const updates = new ComponentUpdateState({ now: () => times.shift() });
15
+
16
+ assert.deepEqual(updates.get("pi"), {
17
+ target: "pi",
18
+ state: "idle",
19
+ startedAt: null,
20
+ finishedAt: null,
21
+ message: "",
22
+ error: "",
23
+ restartRequired: false,
24
+ });
25
+ assert.equal(updates.get("webui").restartRequired, true);
26
+
27
+ const runningPi = updates.begin("pi");
28
+ assert.equal(runningPi.state, "running");
29
+ assert.equal(runningPi.startedAt, "2030-01-01T00:00:00.000Z");
30
+ assert.equal(updates.hasRunning(), true);
31
+ assert.throws(() => updates.begin("webui"), /already running/, "component jobs must be single-flight");
32
+
33
+ const busyStates = updates.publicStates({ localRequest: true, updateInProgress: true });
34
+ assert.equal(busyStates.pi.canStart, false);
35
+ assert.equal(busyStates.webui.canStart, false);
36
+ assert.match(busyStates.webui.unavailableReason, /privileged update/i);
37
+
38
+ const succeededPi = updates.succeed("pi", "Pi update completed.");
39
+ assert.equal(succeededPi.state, "succeeded");
40
+ assert.equal(succeededPi.finishedAt, "2030-01-01T00:00:01.000Z");
41
+ assert.equal(succeededPi.error, "");
42
+ assert.equal(updates.hasRunning(), false);
43
+
44
+ updates.begin("webui");
45
+ const secretFailure = new Error(`Authorization: Bearer top-secret-token\npassword=hunter2\nhttps://alice:private@example.test/path\n${"x".repeat(2000)}`);
46
+ const failedWebui = updates.fail("webui", secretFailure);
47
+ assert.equal(failedWebui.state, "failed");
48
+ assert.equal(failedWebui.finishedAt, "2030-01-01T00:00:03.000Z");
49
+ assert.ok(failedWebui.error.length <= 1200, "terminal error text must be bounded");
50
+ assert.doesNotMatch(failedWebui.error, /top-secret-token|hunter2|alice:private/);
51
+ assert.match(failedWebui.error, /\[redacted\]/);
52
+
53
+ const sourceStates = updates.publicStates({
54
+ localRequest: true,
55
+ updateInProgress: false,
56
+ webuiAvailable: false,
57
+ webuiUnavailableReason: "Source checkout updates are unavailable.",
58
+ });
59
+ assert.equal(sourceStates.pi.canStart, true);
60
+ assert.equal(sourceStates.webui.canStart, false);
61
+ assert.equal(sourceStates.webui.unavailableReason, "Source checkout updates are unavailable.");
62
+
63
+ const remoteStates = updates.publicStates({ localRequest: false, updateInProgress: false });
64
+ assert.equal(remoteStates.pi.canStart, false);
65
+ assert.equal(remoteStates.webui.canStart, false);
66
+ assert.match(remoteStates.pi.unavailableReason, /localhost/i);
67
+
68
+ for (const body of [null, [], {}, { target: "all" }, { target: "pi", extra: true }, { extra: "pi" }]) {
69
+ assert.equal(validateComponentUpdateRequest(body).ok, false, `invalid request must be rejected: ${JSON.stringify(body)}`);
70
+ }
71
+ assert.deepEqual(validateComponentUpdateRequest({ target: "pi" }), { ok: true, target: "pi" });
72
+ assert.deepEqual(validateComponentUpdateRequest({ target: "webui" }), { ok: true, target: "webui" });
73
+
74
+ const ansiAndToken = sanitizeComponentUpdateError("\u001b[31mtoken=npm_abcdefghijklmnopqrstuvwxyz123456\u001b[0m");
75
+ assert.doesNotMatch(ansiAndToken, /\u001b|npm_abcdefghijklmnopqrstuvwxyz123456/);
76
+ const npmAuthToken = sanitizeComponentUpdateError("//registry.npmjs.org/:_authToken=opaque-registry-secret");
77
+ assert.doesNotMatch(npmAuthToken, /opaque-registry-secret/);
78
+ assert.match(npmAuthToken, /\[redacted\]/);
79
+
80
+ console.log("component update state tests passed");
@@ -0,0 +1,63 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [html, app, css, serviceWorker] = await Promise.all([
8
+ readFile(join(root, "public", "index.html"), "utf8"),
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ readFile(join(root, "public", "styles.css"), "utf8"),
11
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
12
+ ]);
13
+
14
+ assert.match(html, /id="newSessionButton"[^>]*data-composer-action-id="new"[^>]*data-composer-action-span="1"/, "New should occupy one composer grid cell");
15
+ for (const [id, label] of [
16
+ ["compact", "Compact"],
17
+ ["app-runner", "App runner"],
18
+ ["steer", "Steer"],
19
+ ["follow-up", "Follow-up"],
20
+ ["abort", "Abort"],
21
+ ["send", "Send"],
22
+ ]) {
23
+ assert.match(html, new RegExp(`data-composer-action-id="${id}"[^>]*data-composer-action-span="2"`), `${label} should occupy two composer grid cells`);
24
+ }
25
+ for (const id of ["git", "publish", "native-command", "options", "btw"]) {
26
+ assert.match(html, new RegExp(`data-composer-action-id="${id}"[^>]*data-composer-action-span="1"`), `${id} should occupy one composer grid cell`);
27
+ }
28
+ assert.match(html, /id="composerActionGridGuide"[^>]*class="composer-action-grid-guide"[^>]*aria-hidden="true"[^>]*hidden/, "the composer should provide a decorative drag-only grid guide");
29
+ assert.match(html, /id="composerActionOrderStatus"[^>]*role="status"[^>]*aria-live="polite"/, "reordering should have a polite live-region announcement");
30
+
31
+ assert.match(
32
+ css,
33
+ /body\.composer-action-grid-enabled \.composer-row\s*\{[\s\S]*--composer-action-cell-min-width:\s*3\.2rem[\s\S]*display:\s*grid[\s\S]*grid-template-columns:\s*repeat\(auto-fill, minmax\(var\(--composer-action-cell-min-width\), 1fr\)\)[\s\S]*grid-auto-flow:\s*dense/,
34
+ "the desktop composer should use wider dense responsive grid cells",
35
+ );
36
+ assert.match(css, /grid-column:\s*var\(--composer-action-grid-column, auto\) \/ span var\(--composer-action-grid-span\)/, "actions should support explicit sparse grid columns");
37
+ assert.match(css, /\[data-composer-action-span="2"\]\s*\{\s*--composer-action-grid-span:\s*2;/, "wide actions should span exactly two cells");
38
+ assert.match(css, /body\.composer-action-grid-enabled \.composer-row \[data-composer-action-id\]\.composer-publish-menu:hover,[\s\S]*\.composer-publish-menu:focus-within,[\s\S]*\.composer-publish-menu\.open \{\s*z-index:\s*100;/, "open composer dropdowns should stack above prompt tags and neighboring grid controls");
39
+ assert.match(css, /#newSessionButton\s*\{[\s\S]*display:\s*grid[\s\S]*place-items:\s*center[\s\S]*padding-inline:\s*0\.4rem[\s\S]*text-align:\s*center/, "New should center its label inside the one-cell button");
40
+ assert.match(css, /composer-action-drag-active[\s\S]*composer-action-grid-guide:not\(\[hidden\]\)[\s\S]*position:\s*absolute[\s\S]*inset:\s*0[\s\S]*grid-template-columns:\s*repeat\(auto-fill, minmax\(var\(--composer-action-cell-min-width\), 1fr\)\)[\s\S]*gap:\s*0\.5rem/, "the drag-only guide should cover the complete composer row with the same responsive tracks");
41
+ assert.match(css, /\.composer-action-grid-cell\s*\{[\s\S]*min-width:\s*0[\s\S]*border:[\s\S]*background:/, "empty guide cells should render as full grid cells");
42
+ assert.match(css, /composer-action-dragging[\s\S]*cursor:\s*grabbing[\s\S]*composer-action-drag-before[\s\S]*composer-action-drag-after/, "dragging and occupied drop targets should have visible affordances");
43
+ assert.match(css, /composer-action-grid-cell-target[\s\S]*border-color:\s*var\(--ctp-teal\)/, "empty-cell drop targets should have a visible affordance");
44
+
45
+ assert.match(app, /const COMPOSER_ACTION_ORDER_STORAGE_KEY = "pi-webui-composer-action-order-v1";[\s\S]*const COMPOSER_ACTION_LAYOUT_STORAGE_KEY = "pi-webui-composer-action-layout-v2";[\s\S]*const COMPOSER_ACTION_POINTER_DRAG_THRESHOLD_PX = 6;/, "composer order and sparse layout should use versioned storage with a bounded drag threshold");
46
+ assert.match(app, /function readStoredComposerActionOrder\(\)[\s\S]*localStorage\.getItem\(COMPOSER_ACTION_ORDER_STORAGE_KEY\)[\s\S]*new Set[\s\S]*function persistComposerActionOrder\(\)[\s\S]*localStorage\.setItem\(COMPOSER_ACTION_ORDER_STORAGE_KEY/, "stored order should be validated, deduplicated, and persisted");
47
+ assert.match(app, /function applyComposerActionOrder\(orderIds\)[\s\S]*knownIds[\s\S]*completeOrder[\s\S]*--composer-action-order/, "new actions should append safely when restoring an older order");
48
+ assert.match(app, /function showComposerActionGridGuide\(\)[\s\S]*composerActionGridColumnCount\(\)[\s\S]*top - groups\.at\(-1\) > 4[\s\S]*columnCount \* rowCount[\s\S]*composer-action-drag-active[\s\S]*function hideComposerActionGridGuide/, "dragging should materialize every full-row guide cell without splitting near-equal action tops into false rows");
49
+ assert.match(app, /function composerActionGridColumnCount\(\)[\s\S]*--composer-action-cell-min-width[\s\S]*row\.clientWidth[\s\S]*Math\.floor\(\(availableWidth \+ gap\) \/ \(minWidth \+ gap\)\)/, "column counts should derive from the visible row width instead of overflow-created implicit tracks");
50
+ assert.match(app, /function readStoredComposerActionLayout\(\)[\s\S]*COMPOSER_ACTION_LAYOUT_STORAGE_KEY[\s\S]*function composerActionSlotCanFit[\s\S]*function persistComposerActionSlotLayout[\s\S]*positions:\s*Object\.fromEntries/, "sparse cell positions should be validated and persisted independently from order");
51
+ assert.match(app, /function remapComposerActionSlot\(record, slot, sourceColumns, targetColumns\)[\s\S]*relativeColumn[\s\S]*function nearestAvailableComposerActionSlot[\s\S]*function restoreComposerActionSlotLayout\(\)[\s\S]*stored\.columns === columns[\s\S]*remapComposerActionSlot/, "saved sparse positions should project into changed responsive grid widths instead of being cleared");
52
+ assert.doesNotMatch(app, /if \(!stored \|\| stored\.columns !== columns\)/, "column-count changes should not discard saved sparse positions");
53
+ assert.match(app, /function captureComposerActionSlotLayout\(\)[\s\S]*composerActionGridGuide[\s\S]*function moveComposerActionToGridCell\(actionId, cell\)[\s\S]*composerActionSlotCanFit[\s\S]*composer-action-grid-cell-target/, "empty grid cells should capture and retain exact action slots");
54
+ assert.match(app, /function composerActionRootFromPoint\(clientX, clientY\)[\s\S]*elementFromPoint[\s\S]*function updateComposerActionPointerDrag\(event\)[\s\S]*Math\.hypot[\s\S]*COMPOSER_ACTION_POINTER_DRAG_THRESHOLD_PX[\s\S]*showComposerActionGridGuide\(\)[\s\S]*captureComposerActionSlotLayout\(\)[\s\S]*composerActionGridCellFromPoint[\s\S]*moveComposerActionToGridCell/, "pointer dragging should activate after the threshold and distinguish occupied from empty grid cells");
55
+ assert.match(app, /function initializeComposerActionOrdering\(\)[\s\S]*MutationObserver[\s\S]*ResizeObserver[\s\S]*observedRowWidth[\s\S]*scheduleComposerActionSlotLayoutRestore[\s\S]*aria-keyshortcuts[\s\S]*ArrowLeft[\s\S]*ArrowRight[\s\S]*moveComposerActionByOffset[\s\S]*pointerdown/, "keyboard and pointer reordering should stay synchronized with dynamic action visibility and composer width");
56
+ assert.match(app, /event\.key === COMPOSER_ACTION_ORDER_STORAGE_KEY\) restoreComposerActionOrder\(\)[\s\S]*event\.key === COMPOSER_ACTION_LAYOUT_STORAGE_KEY\) restoreComposerActionSlotLayout\(\)/, "other tabs should apply persisted composer order and sparse-layout changes");
57
+ assert.match(app, /initializeComposerActionOrdering\(\);[\s\S]*restoreSidePanelSectionOrder\(\);/, "composer ordering should initialize during guarded app startup");
58
+
59
+ assert.match(html, /styles\.css\?v=98/, "changed composer styles should advance the stylesheet revision");
60
+ assert.match(html, /app\.js\?v=112/, "changed composer behavior should advance the app revision");
61
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v71"/, "changed browser assets should advance the PWA cache identity");
62
+
63
+ console.log("composer-action-grid-reorder-static.test.mjs passed");