@firstpick/pi-package-webui 0.8.3 → 0.8.4

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.
@@ -0,0 +1,271 @@
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-session-summary-"));
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
+ PI_SESSION_SUMMARY_CONFIG_FILE: join(tempRoot, "session-summary.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 isolated real server and fake RPC fixture.
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
+ if (child?.exitCode === null) child.kill("SIGTERM");
58
+ if (child && child.exitCode === null) await new Promise((resolve) => child.once("exit", resolve));
59
+ await rm(tempRoot, { recursive: true, force: true });
60
+ });
61
+
62
+ function preferencesData({ configured = false, summary = null } = {}) {
63
+ return {
64
+ version: 1,
65
+ preferences: {
66
+ version: 1,
67
+ configured,
68
+ enabled: false,
69
+ model: { provider: "fake", modelId: "fake-model", thinkingLevel: "off" },
70
+ prompts: { title: "Create a bounded title", summary: "Create a bounded Markdown summary" },
71
+ input: { scope: "text-and-tool-names" },
72
+ context: { injectLatest: false },
73
+ title: { enabled: true, minSettledTurns: 3 },
74
+ },
75
+ models: [{ provider: "fake", id: "fake-model", name: "Fake Model", reasoning: false }],
76
+ modelThinkingLevels: { "fake/fake-model": ["off"] },
77
+ disclosure: {
78
+ scope: "Active-branch user text, final assistant text, and tool names only.",
79
+ cost: "One configured-model request with no fallback.",
80
+ persistence: "Preferences and validated output are stored locally.",
81
+ },
82
+ summary: summary || (configured ? { version: 1, status: "idle", configured: true, enabled: false, durable: false, updatedAt: new Date().toISOString() } : null),
83
+ };
84
+ }
85
+
86
+ function generatedSummaryResponse() {
87
+ return {
88
+ status: 200,
89
+ payload: {
90
+ ok: true,
91
+ data: {
92
+ requested: true,
93
+ summary: {
94
+ version: 1,
95
+ status: "success",
96
+ configured: true,
97
+ enabled: false,
98
+ durable: false,
99
+ title: "Validated fixture title",
100
+ summaryMarkdown: "## Goal\n\nKeep **validated Markdown** visible.\n\n<script>globalThis.summaryPwned = true</script>",
101
+ updatedAt: new Date().toISOString(),
102
+ },
103
+ },
104
+ },
105
+ };
106
+ }
107
+
108
+ async function installSummaryRoutes(page, requests, { configured = false, summary = null, generate = generatedSummaryResponse } = {}) {
109
+ await page.route("**/api/commands?*", async (route) => {
110
+ await route.fulfill({
111
+ status: 200,
112
+ contentType: "application/json",
113
+ body: JSON.stringify({ ok: true, data: { commands: [
114
+ { name: "summary", source: "extension", description: "Open the latest session summary" },
115
+ { name: "summary-setup", source: "extension", description: "Configure session summaries" },
116
+ ] } }),
117
+ });
118
+ });
119
+ await page.route("**/api/session-summary/preferences?*", async (route) => {
120
+ const method = route.request().method();
121
+ if (method === "GET") {
122
+ requests.get += 1;
123
+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ ok: true, data: preferencesData({ configured, summary }) }) });
124
+ return;
125
+ }
126
+ requests.put.push(JSON.parse(route.request().postData() || "{}"));
127
+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ ok: true, data: preferencesData({ configured: true }) }) });
128
+ });
129
+ await page.route("**/api/session-summary/generate?*", async (route) => {
130
+ const request = JSON.parse(route.request().postData() || "{}");
131
+ requests.generate.push(request);
132
+ const response = await generate(request, requests.generate.length);
133
+ await route.fulfill({
134
+ status: response.status,
135
+ contentType: "application/json",
136
+ body: JSON.stringify(response.payload),
137
+ });
138
+ });
139
+ }
140
+
141
+ test("first click opens confirmed setup, cancel has no side effect, and save opens a non-blocking sanitized overlay", async ({ page }) => {
142
+ const requests = { get: 0, put: [], generate: [] };
143
+ await installSummaryRoutes(page, requests);
144
+ await page.goto(baseURL);
145
+
146
+ const summaryButton = page.locator("#summaryHeaderButton");
147
+ await expect(summaryButton).toBeVisible();
148
+ await summaryButton.evaluate((button) => button.click());
149
+ await expect(page.locator("#nativeCommandDialog")).toBeVisible();
150
+ await expect(page.locator("#nativeCommandTitle")).toHaveText("/summary-setup");
151
+ await expect(page.locator("#nativeCommandBody")).toContainText("Privacy scope");
152
+ expect(requests.put).toHaveLength(0);
153
+ expect(requests.generate).toHaveLength(0);
154
+
155
+ await page.locator("#nativeCommandActions").getByRole("button", { name: "Cancel" }).click();
156
+ await expect(page.locator("#nativeCommandDialog")).not.toBeVisible();
157
+ expect(requests.put).toHaveLength(0);
158
+ expect(requests.generate).toHaveLength(0);
159
+
160
+ await summaryButton.evaluate((button) => button.click());
161
+ await expect(page.locator("#nativeCommandDialog")).toBeVisible();
162
+ await page.locator("#nativeCommandActions").getByRole("button", { name: "Save and generate" }).click();
163
+ await expect(page.locator("#confirmationDialog")).toBeVisible();
164
+ await expect(page.locator("#confirmationSummary")).toContainText("Active-branch user text");
165
+ expect(requests.put).toHaveLength(0);
166
+ expect(requests.generate).toHaveLength(0);
167
+ await page.locator("#confirmationConfirmButton").click();
168
+
169
+ await expect(page.locator("#sessionSummaryOverlay")).toBeVisible();
170
+ await expect(page.locator("#sessionSummaryOverlay")).toHaveAttribute("aria-modal", "false");
171
+ await expect(page.locator("#sessionSummaryOverlayTitle")).toHaveText("Validated fixture title");
172
+ await expect(page.locator("#sessionSummaryOverlayBody h2")).toHaveText("Goal");
173
+ await expect(page.locator("#sessionSummaryOverlayBody strong")).toHaveText("validated Markdown");
174
+ await expect(page.locator("#sessionSummaryOverlayBody script")).toHaveCount(0);
175
+ await expect(page.locator("#sessionSummaryOverlayBody")).toContainText("<script>globalThis.summaryPwned = true</script>");
176
+ expect(await page.evaluate(() => globalThis.summaryPwned)).toBeUndefined();
177
+ expect(requests.put).toHaveLength(1);
178
+ expect(requests.put[0]).toMatchObject({ confirmed: true, preferences: { input: { scope: "text-and-tool-names" } } });
179
+ expect(requests.generate).toEqual([{ refresh: true }]);
180
+
181
+ await page.setViewportSize({ width: 390, height: 844 });
182
+ const dimensions = await page.locator("#sessionSummaryOverlay").evaluate((element) => ({
183
+ clientWidth: element.clientWidth,
184
+ scrollWidth: element.scrollWidth,
185
+ right: element.getBoundingClientRect().right,
186
+ }));
187
+ expect(dimensions.scrollWidth).toBeLessThanOrEqual(dimensions.clientWidth + 1);
188
+ expect(dimensions.right).toBeLessThanOrEqual(391);
189
+ });
190
+
191
+ test("typed summary commands stay native, preserve failures, reset sessions, restore focus, and close on tab switch", async ({ page }) => {
192
+ const requests = { get: 0, put: [], generate: [], prompt: [] };
193
+ const initialSummary = {
194
+ version: 1,
195
+ status: "success",
196
+ configured: true,
197
+ enabled: false,
198
+ durable: true,
199
+ sessionId: "session-a",
200
+ title: "Session A",
201
+ summaryMarkdown: "## Previous success\n\nKeep this Markdown on refresh failure.",
202
+ updatedAt: new Date().toISOString(),
203
+ };
204
+ let generationMode = "failure";
205
+ await installSummaryRoutes(page, requests, {
206
+ configured: true,
207
+ summary: initialSummary,
208
+ generate: async () => generationMode === "failure"
209
+ ? { status: 503, payload: { ok: false, error: "Fixture provider unavailable" } }
210
+ : {
211
+ status: 200,
212
+ payload: {
213
+ ok: true,
214
+ data: {
215
+ requested: true,
216
+ summary: {
217
+ version: 1,
218
+ status: "idle",
219
+ configured: true,
220
+ enabled: false,
221
+ durable: true,
222
+ sessionId: "session-b",
223
+ updatedAt: new Date().toISOString(),
224
+ },
225
+ },
226
+ },
227
+ },
228
+ });
229
+ await page.route("**/api/prompt?*", async (route) => {
230
+ requests.prompt.push(JSON.parse(route.request().postData() || "{}"));
231
+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ ok: true, data: {} }) });
232
+ });
233
+ await page.goto(baseURL);
234
+ await expect(page.locator("#summaryHeaderButton")).toBeVisible();
235
+
236
+ const prompt = page.locator("#promptInput");
237
+ await prompt.fill("/summary");
238
+ await prompt.press("Enter");
239
+ await expect(page.locator("#sessionSummaryOverlay")).toBeVisible();
240
+ await expect(page.locator("#sessionSummaryOverlayTitle")).toHaveText("Session A");
241
+ await expect(page.locator("#sessionSummaryOverlayBody")).toContainText("Previous success");
242
+ await expect(prompt).toHaveValue("");
243
+ await expect(prompt).toBeFocused();
244
+ expect(requests.generate).toHaveLength(0);
245
+ expect(requests.prompt).toHaveLength(0);
246
+ expect(await page.locator(".message.user").allTextContents()).not.toContainEqual(expect.stringContaining("/summary"));
247
+
248
+ await page.keyboard.press("Escape");
249
+ await expect(page.locator("#sessionSummaryOverlay")).toBeHidden();
250
+ await expect(prompt).toBeFocused();
251
+
252
+ await prompt.fill("/summary refresh");
253
+ await prompt.press("Enter");
254
+ await expect.poll(() => requests.generate.length).toBe(1);
255
+ expect(requests.generate[0]).toEqual({ refresh: true });
256
+ await expect(page.locator("#sessionSummaryOverlayStatus")).toContainText("Fixture provider unavailable");
257
+ await expect(page.locator("#sessionSummaryOverlayBody")).toContainText("Keep this Markdown on refresh failure");
258
+ expect(requests.prompt).toHaveLength(0);
259
+
260
+ generationMode = "session-reset";
261
+ await prompt.fill("/summary refresh");
262
+ await prompt.press("Enter");
263
+ await expect.poll(() => requests.generate.length).toBe(2);
264
+ await expect(page.locator("#sessionSummaryOverlayBody")).not.toContainText("Previous success");
265
+ await expect(page.locator("#sessionSummaryOverlayBody")).toContainText("Generate a summary to populate this view.");
266
+
267
+ await page.locator("#newTabButton").evaluate((button) => button.click());
268
+ await page.locator("#newTabCurrentDirectoryButton").evaluate((button) => button.click());
269
+ await expect(page.locator("#tabBar [role=\"tab\"]")).toHaveCount(2);
270
+ await expect(page.locator("#sessionSummaryOverlay")).toBeHidden();
271
+ });
@@ -4,7 +4,7 @@ import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
6
6
  const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
- const [server, app, html, styles, serviceWorker, readme, packageRaw, lockRaw] = await Promise.all([
7
+ const [server, app, html, styles, serviceWorker, readme, packageRaw, lockRaw, optionalFeatureCatalog] = await Promise.all([
8
8
  readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
9
9
  readFile(join(root, "public", "app.js"), "utf8"),
10
10
  readFile(join(root, "public", "index.html"), "utf8"),
@@ -13,18 +13,19 @@ const [server, app, html, styles, serviceWorker, readme, packageRaw, lockRaw] =
13
13
  readFile(join(root, "README.md"), "utf8"),
14
14
  readFile(join(root, "package.json"), "utf8"),
15
15
  readFile(join(root, "package-lock.json"), "utf8"),
16
+ readFile(join(root, "lib", "optional-feature-catalog.mjs"), "utf8"),
16
17
  ]);
17
18
  const pkg = JSON.parse(packageRaw);
18
19
  const lock = JSON.parse(lockRaw);
19
20
  const packageName = "@firstpick/pi-extension-codex-fast-mode";
20
21
 
21
- assert.equal(pkg.optionalDependencies?.[packageName], "^0.1.0", "WebUI should declare the Fast-mode companion as optional");
22
- assert.ok(pkg.pi?.extensions?.includes(`node_modules/${packageName}/index.ts`), "WebUI should load the optional Fast-mode extension when installed");
23
- assert.equal(lock.packages?.[""]?.optionalDependencies?.[packageName], "^0.1.0", "lock root should mirror the unpublished optional requirement without inventing a resolved artifact");
24
- assert.equal(lock.packages?.[`node_modules/${packageName}`]?.version, "0.1.0", "lockfile should resolve the published Fast-mode companion");
25
- assert.equal(lock.packages?.[`node_modules/${packageName}`]?.optional, true, "resolved Fast-mode companion should remain optional");
22
+ assert.equal(pkg.optionalDependencies?.[packageName], undefined, "WebUI should keep the Fast-mode companion as a separate Pi package");
23
+ assert.equal(pkg.pi?.extensions?.includes(`node_modules/${packageName}/index.ts`), false, "WebUI should not claim the separately configured Fast-mode extension");
24
+ assert.equal(lock.packages?.[""]?.optionalDependencies?.[packageName], undefined, "lock root should not install the Fast-mode companion with WebUI core");
25
+ assert.equal(lock.packages?.[`node_modules/${packageName}`], undefined, "lockfile should not resolve the separately installed Fast-mode companion");
26
+ assert.match(optionalFeatureCatalog, /\["codexFastMode", "@firstpick\/pi-extension-codex-fast-mode", "\^0\.1\.0"\]/, "Optional Features should retain the Pi-installable Fast-mode package mapping");
26
27
 
27
- assert.match(server, /\["codexFastMode", "@firstpick\/pi-extension-codex-fast-mode"\]/, "server should register the package in Optional Features");
28
+ assert.match(server, /const OPTIONAL_FEATURE_PACKAGES = new Map\(OPTIONAL_FEATURE_CATALOG/, "server should derive Fast-mode installation from the shared Optional Features catalog");
28
29
  assert.match(server, /CODEX_FAST_MODE_STATUS_KEY = "codex-fast-mode"[\s\S]*?CODEX_FAST_MODE_COMMAND_NAME = "fast-mode"/, "server should use the extension-owned status and command contracts");
29
30
  assert.match(server, /function codexFastModeStatusState\(statusText\)[\s\S]*?text !== "on" && text !== "off"[\s\S]*?known: true, enabled: text === "on"/, "server should accept only exact published on/off states");
30
31
  assert.match(server, /function codexFastModeSnapshot\(tab, patch = \{\}\)[\s\S]*?extensionStatusMap\(tab\)\.get\(CODEX_FAST_MODE_STATUS_KEY\)/, "server snapshots should come from remembered extension status");