@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.
@@ -6,12 +6,15 @@ import { networkInterfaces, tmpdir } from "node:os";
6
6
  import path from "node:path";
7
7
  import { setTimeout as delay } from "node:timers/promises";
8
8
  import { dirname, join } from "node:path";
9
- import { fileURLToPath } from "node:url";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import { terminateProcessTree } from "../lib/process-tree.mjs";
11
+ import { readSupervisorState, supervisorPaths, supervisorPidIsAlive } from "../lib/rpc-supervisor-state.mjs";
10
12
 
11
13
  const root = join(dirname(fileURLToPath(import.meta.url)), "..");
12
14
  const serverScript = join(root, "bin", "pi-webui.mjs");
13
15
  const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
14
16
  const port = 30000 + Math.floor(Math.random() * 20000);
17
+ const optionalFeatureFocus = process.env.PI_WEBUI_OPTIONAL_FEATURES_FOCUS === "1";
15
18
 
16
19
  function lanAddress() {
17
20
  for (const entries of Object.values(networkInterfaces())) {
@@ -119,6 +122,7 @@ const harnessSideEffectsRoot = await mkdtemp(path.join(tmpdir(), "pi-webui-http-
119
122
  const settingsFile = path.join(harnessSideEffectsRoot, "webui-settings.json");
120
123
  const workflowPolicyAgentDir = path.join(harnessSideEffectsRoot, "agent");
121
124
  const workflowPolicyFile = path.join(workflowPolicyAgentDir, "workflow-policy.json");
125
+ const sessionSummaryConfigFile = path.join(workflowPolicyAgentDir, "session-summary.json");
122
126
  const canonicalWorkflowPolicySuggestions = {
123
127
  shellAllowlist: ["git", "node", "npm"],
124
128
  networkAllowlist: ["api.github.com", "registry.npmjs.org"],
@@ -126,6 +130,8 @@ const canonicalWorkflowPolicySuggestions = {
126
130
  };
127
131
  const openCommandLog = path.join(harnessSideEffectsRoot, "open-default.log");
128
132
  const fakePiCommandLog = path.join(harnessSideEffectsRoot, "fake-pi-commands.jsonl");
133
+ const fakePiCliLog = path.join(harnessSideEffectsRoot, "fake-pi-cli.jsonl");
134
+ const fakePiCli = path.join(harnessSideEffectsRoot, "fake-pi-cli.mjs");
129
135
  const recoveryEndpointToken = "test-recovery-token-6e1cc61d22d44c8dbf3c";
130
136
  const openCommandScript = path.join(harnessSideEffectsRoot, "fake-open-default.mjs");
131
137
  const fakeOpenBinDir = path.join(harnessSideEffectsRoot, "bin");
@@ -142,6 +148,43 @@ await writeFile(path.join(fakeOpenBinDir, "xdg-open"), `#!/usr/bin/env node\nimp
142
148
  await writeFile(path.join(fakeOpenBinDir, "gio"), `#!/usr/bin/env node\nimport { appendFile } from "node:fs/promises";\nawait appendFile(process.env.PI_WEBUI_OPEN_LOG, "gio\\t" + process.argv.slice(2).join("\\t") + "\\n", "utf8");\n`, "utf8");
143
149
  await writeFile(path.join(fakeOpenBinDir, "xdg-mime"), `#!/usr/bin/env node\nconst [,, verb, mode, value = ""] = process.argv;\nif (verb === "query" && mode === "filetype") {\n if (value.endsWith(".piunknown")) console.log("application/x-pi-unknown");\n else if (value.endsWith(".md")) console.log("text/markdown");\n else console.log("text/plain");\n process.exit(0);\n}\nif (verb === "query" && mode === "default") {\n if (value === "text/plain") console.log("fake-text-editor.desktop");\n process.exit(0);\n}\nprocess.exit(1);\n`, "utf8");
144
150
  await Promise.all(["xdg-open", "gio", "xdg-mime"].map((name) => chmod(path.join(fakeOpenBinDir, name), 0o755)));
151
+ await writeFile(fakePiCli, `#!/usr/bin/env node
152
+ import { appendFile, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
153
+ import path from "node:path";
154
+ const args = process.argv.slice(2);
155
+ const log = async (entry) => appendFile(process.env.FAKE_PI_CLI_LOG, JSON.stringify({ at: Date.now(), ...entry }) + "\\n", "utf8");
156
+ process.on("SIGTERM", () => process.exit(143));
157
+ process.on("SIGINT", () => process.exit(130));
158
+ if (args[0] === "install") {
159
+ const source = String(args[1] || "");
160
+ await log({ event: "start", args });
161
+ if (source === "npm:@firstpick/pi-extension-stats") {
162
+ console.error("fixture Pi install failure for stats");
163
+ await log({ event: "finish", args, exitCode: 17 });
164
+ process.exitCode = 17;
165
+ } else {
166
+ const packageName = source.startsWith("npm:") ? source.slice(4) : "";
167
+ const sourceRoot = path.join(${JSON.stringify(path.dirname(root))}, packageName.split("/").at(-1));
168
+ const installRoot = path.join(process.env.PI_CODING_AGENT_DIR, "npm", "node_modules", ...packageName.split("/"));
169
+ await mkdir(path.dirname(installRoot), { recursive: true });
170
+ await rm(installRoot, { recursive: true, force: true });
171
+ await cp(sourceRoot, installRoot, { recursive: true });
172
+ const settingsPath = path.join(process.env.PI_CODING_AGENT_DIR, "settings.json");
173
+ const settings = JSON.parse(await readFile(settingsPath, "utf8").catch(() => "{}"));
174
+ const packages = Array.isArray(settings.packages) ? settings.packages : [];
175
+ if (!packages.some((entry) => (typeof entry === "string" ? entry : entry?.source) === source)) packages.push(source);
176
+ settings.packages = packages;
177
+ await mkdir(path.dirname(settingsPath), { recursive: true });
178
+ await writeFile(settingsPath, JSON.stringify(settings, null, 2) + "\\n", "utf8");
179
+ console.log("installed " + source);
180
+ await log({ event: "finish", args, exitCode: 0 });
181
+ }
182
+ } else {
183
+ await log({ event: "rpc", args });
184
+ await import(${JSON.stringify(pathToFileURL(fakePi).href)});
185
+ }
186
+ `, "utf8");
187
+ await chmod(fakePiCli, 0o755);
145
188
 
146
189
  const voiceProviderRequests = [];
147
190
  const voiceProvider = createServer(async (req, res) => {
@@ -176,7 +219,7 @@ const voiceProvider = createServer(async (req, res) => {
176
219
  await new Promise((resolve) => voiceProvider.listen(0, "127.0.0.1", resolve));
177
220
  const voiceProviderPort = voiceProvider.address().port;
178
221
 
179
- const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.0.0.0", "--port", String(port), "--pi", fakePi], {
222
+ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.0.0.0", "--port", String(port), "--pi", fakePiCli], {
180
223
  stdio: ["ignore", "pipe", "pipe"],
181
224
  env: {
182
225
  ...process.env,
@@ -187,6 +230,7 @@ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.
187
230
  PATH: `${fakeOpenBinDir}${path.delimiter}${process.env.PATH || ""}`,
188
231
  PI_CODING_AGENT_DIR: workflowPolicyAgentDir,
189
232
  PI_WEBUI_SETTINGS_FILE: settingsFile,
233
+ PI_SESSION_SUMMARY_CONFIG_FILE: sessionSummaryConfigFile,
190
234
  PI_WEBUI_RPC_SUPERVISOR: "1",
191
235
  ...(process.platform === "linux" ? {} : { PI_WEBUI_OPEN_COMMAND: openCommandScript }),
192
236
  PI_WEBUI_OPEN_LOG: openCommandLog,
@@ -194,6 +238,7 @@ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.
194
238
  FAKE_PI_ARTIFACT_MANIFEST: artifactManifest,
195
239
  FAKE_PI_ARTIFACT_DOWNLOAD: artifactDownload,
196
240
  FAKE_PI_LOG_FILE: fakePiCommandLog,
241
+ FAKE_PI_CLI_LOG: fakePiCliLog,
197
242
  FAKE_PI_VOICE_SCRIPTS: "1",
198
243
  FAKE_PI_LARGE_PAYLOADS: "1",
199
244
  PI_WEBUI_RECOVERY_TOKEN: recoveryEndpointToken,
@@ -210,6 +255,164 @@ child.stderr.on("data", (chunk) => {
210
255
  serverOutput += String(chunk);
211
256
  });
212
257
 
258
+ async function verifyTopLevelOptionalFeatureProtection(tabId) {
259
+ const extensionsDir = path.join(workflowPolicyAgentDir, "extensions");
260
+ const aliasPath = path.join(extensionsDir, "aur-review-local");
261
+ await mkdir(extensionsDir, { recursive: true });
262
+ await rm(aliasPath, { recursive: true, force: true });
263
+ await symlink(path.join(path.dirname(root), "pi-extension-aur-review"), aliasPath, process.platform === "win32" ? "junction" : "dir");
264
+ try {
265
+ const recheckResponse = await request("127.0.0.1", "/api/optional-feature-migration/recheck", { method: "POST", body: {} });
266
+ assert.equal(recheckResponse.status, 200, recheckResponse.body?.error);
267
+ const statusResponse = await request("127.0.0.1", "/api/optional-features");
268
+ const status = statusResponse.body?.data?.features?.find(({ featureId }) => featureId === "aurReview");
269
+ assert.equal(statusResponse.status, 200);
270
+ assert.equal(status?.configured, false, "a top-level resource should remain distinct from package registration");
271
+ assert.equal(status?.locallyConfigured, true, "an enabled top-level resource should be recognized as locally configured");
272
+ assert.equal(status?.ready, true, "an installed top-level resource should be ready without duplicate package registration");
273
+ assert.equal(status?.resourceConflict, false);
274
+ assert.equal(Object.hasOwn(status || {}, "installedRoot"), false, "browser audit payloads must not expose install paths");
275
+ assert.equal(Object.hasOwn(status || {}, "topLevelResources"), false, "browser audit payloads must not expose resource paths");
276
+ assert.equal(status?.state, "local-resource");
277
+
278
+ const logOffset = (await readJsonLines(fakePiCliLog)).length;
279
+ const installResponse = await request("127.0.0.1", "/api/optional-feature-install", {
280
+ method: "POST",
281
+ body: { tab: tabId, featureId: "aurReview" },
282
+ });
283
+ assert.equal(installResponse.status, 409, "npm registration should be blocked before it can duplicate an enabled top-level resource");
284
+ assert.equal(installResponse.body?.optionalFeatureInstall?.kind, "local-resource-conflict");
285
+ assert.equal((await readJsonLines(fakePiCliLog)).length, logOffset, "a blocked duplicate registration must not launch Pi install");
286
+ } finally {
287
+ await rm(aliasPath, { recursive: true, force: true });
288
+ await request("127.0.0.1", "/api/optional-feature-migration/recheck", { method: "POST", body: {} });
289
+ }
290
+ }
291
+
292
+ async function runOptionalFeatureFocus() {
293
+ const tabs = await request("127.0.0.1", "/api/tabs");
294
+ const tabId = tabs.body?.data?.tabs?.[0]?.id;
295
+ assert.ok(tabId, "focused optional-feature checks require the startup tab");
296
+
297
+ const manifest = JSON.parse(await readFile(path.join(root, "package.json"), "utf8"));
298
+ assert.deepEqual(manifest.optionalDependencies, { "node-pty": "^1.1.0" });
299
+ assert.equal(manifest.dependencies?.["@firstpick/pi-utils"], "^0.2.5");
300
+ assert.equal(JSON.stringify(manifest.pi).includes("node_modules/@firstpick"), false);
301
+
302
+ const initial = await request("127.0.0.1", "/api/optional-features");
303
+ assert.equal(initial.status, 200);
304
+ assert.equal(initial.body?.data?.features?.length, 19);
305
+ const aurBefore = initial.body?.data?.features?.find(({ featureId }) => featureId === "aurReview");
306
+ assert.deepEqual({ installed: aurBefore?.installed, configured: aurBefore?.configured, ready: aurBefore?.ready }, { installed: true, configured: false, ready: false });
307
+ assert.equal(aurBefore?.expectedSpec, "^0.1.1");
308
+ await verifyTopLevelOptionalFeatureProtection(tabId);
309
+
310
+ const single = await request("127.0.0.1", "/api/optional-feature-install", {
311
+ method: "POST",
312
+ body: { tab: tabId, featureId: "aurReview" },
313
+ timeoutMs: 10_000,
314
+ });
315
+ assert.equal(single.status, 200, single.body?.error);
316
+ assert.match(single.body?.data?.command || "", /install npm:@firstpick\/pi-extension-aur-review$/);
317
+ assert.deepEqual({
318
+ installed: single.body?.data?.status?.installed,
319
+ configured: single.body?.data?.status?.configured,
320
+ ready: single.body?.data?.status?.ready,
321
+ }, { installed: true, configured: true, ready: true });
322
+
323
+ const conflictExtensionsDir = path.join(workflowPolicyAgentDir, "extensions");
324
+ const conflictAliasPath = path.join(conflictExtensionsDir, "aur-review-conflict");
325
+ await mkdir(conflictExtensionsDir, { recursive: true });
326
+ await symlink(path.join(path.dirname(root), "pi-extension-aur-review"), conflictAliasPath, process.platform === "win32" ? "junction" : "dir");
327
+ try {
328
+ const conflictAudit = await request("127.0.0.1", "/api/optional-feature-migration/recheck", { method: "POST", body: {} });
329
+ const conflictFeature = conflictAudit.body?.data?.features?.find(({ featureId }) => featureId === "aurReview");
330
+ assert.equal(conflictFeature?.state, "conflict");
331
+ assert.equal(conflictFeature?.resourceConflict, true);
332
+ const conflictTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd, title: "conflict-safe optional package" } });
333
+ assert.equal(conflictTab.status, 201, conflictTab.body?.error);
334
+ const conflictRpcArgs = (await readJsonLines(fakePiCliLog)).filter(({ event }) => event === "rpc").at(-1)?.args || [];
335
+ const normalizedConflictArgs = conflictRpcArgs.map((arg) => String(arg).replace(/\\/g, "/"));
336
+ assert.equal(normalizedConflictArgs.some((arg) => arg.includes("/extensions/aur-review-conflict/")), false, "conflicting top-level alias must be excluded from RPC args");
337
+ assert.equal(normalizedConflictArgs.filter((arg) => arg.endsWith("/pi-extension-aur-review/index.ts")).length, 1, "registered package remains canonical during a conflict");
338
+ await request("127.0.0.1", "/api/tabs/close", { method: "POST", body: { ids: [conflictTab.body?.data?.tab?.id] } });
339
+ } finally {
340
+ await rm(conflictAliasPath, { recursive: true, force: true });
341
+ await request("127.0.0.1", "/api/optional-feature-migration/recheck", { method: "POST", body: {} });
342
+ }
343
+
344
+ const resourceTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd, title: "configured optional package" } });
345
+ assert.equal(resourceTab.status, 201, resourceTab.body?.error);
346
+ const rpcArgs = (await readJsonLines(fakePiCliLog)).filter(({ event }) => event === "rpc").at(-1)?.args || [];
347
+ const normalizedArgs = rpcArgs.map((arg) => String(arg).replace(/\\/g, "/"));
348
+ assert.equal(normalizedArgs.filter((arg) => arg.endsWith("/pi-extension-aur-review/index.ts")).length, 1);
349
+ assert.equal(normalizedArgs.filter((arg) => arg.endsWith("/pi-package-webui/index.ts")).length, 1);
350
+ await request("127.0.0.1", "/api/tabs/close", { method: "POST", body: { ids: [resourceTab.body?.data?.tab?.id] } });
351
+
352
+ const batchPlan = await request("127.0.0.1", "/api/optional-features");
353
+ const batchRevision = batchPlan.body?.data?.revision;
354
+ assert.match(batchRevision || "", /^sha256:[a-f0-9]{64}$/);
355
+ assert.equal((await request("127.0.0.1", "/api/optional-feature-install-batch", { method: "POST", body: { tab: tabId, revision: batchRevision, featureIds: "aurReview" } })).status, 400);
356
+ assert.equal((await request("127.0.0.1", "/api/optional-feature-install-batch", { method: "POST", body: { tab: tabId, revision: batchRevision, featureIds: ["not-allowlisted"] } })).status, 400);
357
+ assert.equal((await request("127.0.0.1", "/api/optional-feature-install-batch", { method: "POST", body: { tab: tabId, revision: batchRevision, featureIds: Array(20).fill("aurReview") } })).status, 400);
358
+ assert.equal((await request("127.0.0.1", "/api/optional-feature-install-batch", { method: "POST", body: { tab: tabId, revision: "sha256:stale", featureIds: ["aurReview"] } })).status, 409);
359
+
360
+ const logOffset = (await readJsonLines(fakePiCliLog)).length;
361
+ const batch = await request("127.0.0.1", "/api/optional-feature-install-batch", {
362
+ method: "POST",
363
+ body: { tab: tabId, revision: batchRevision, featureIds: ["bangCommandAutocomplete", "statsCommand", "bangCommandAutocomplete", "gitFooterStatus"] },
364
+ timeoutMs: 20_000,
365
+ });
366
+ assert.equal(batch.status, 200, batch.body?.error);
367
+ assert.deepEqual(batch.body?.data?.featureIds, ["bangCommandAutocomplete", "statsCommand", "gitFooterStatus"]);
368
+ assert.deepEqual(batch.body?.data?.results?.map(({ featureId, ok }) => [featureId, ok]), [
369
+ ["bangCommandAutocomplete", true], ["statsCommand", false], ["gitFooterStatus", true],
370
+ ]);
371
+ assert.deepEqual([batch.body?.data?.total, batch.body?.data?.succeeded, batch.body?.data?.failed], [3, 2, 1]);
372
+ assert.equal(batch.body?.data?.results?.[1]?.optionalFeatureInstall?.exitCode, 17);
373
+ assert.match(batch.body?.data?.results?.[1]?.optionalFeatureInstall?.outputTail || "", /fixture Pi install failure/);
374
+ const sequence = (await readJsonLines(fakePiCliLog)).slice(logOffset).filter(({ event }) => event === "start" || event === "finish");
375
+ assert.deepEqual(sequence.map(({ event, args, exitCode }) => [event, args?.[1], exitCode]), [
376
+ ["start", "npm:@firstpick/pi-extension-bang-command-autocomplete", undefined],
377
+ ["finish", "npm:@firstpick/pi-extension-bang-command-autocomplete", 0],
378
+ ["start", "npm:@firstpick/pi-extension-stats", undefined],
379
+ ["finish", "npm:@firstpick/pi-extension-stats", 17],
380
+ ["start", "npm:@firstpick/pi-extension-git-footer-status", undefined],
381
+ ["finish", "npm:@firstpick/pi-extension-git-footer-status", 0],
382
+ ]);
383
+
384
+ const progressSnapshot = (await request("127.0.0.1", "/api/optional-features")).body?.data;
385
+ assert.equal(progressSnapshot?.phase, "partial");
386
+ assert.deepEqual([progressSnapshot?.progress?.succeeded, progressSnapshot?.progress?.failed], [2, 1]);
387
+ assert.equal(progressSnapshot?.progress?.results?.length, 3);
388
+
389
+ const rpcLaunchCountBeforeSuccess = (await readJsonLines(fakePiCliLog)).filter(({ event }) => event === "rpc").length;
390
+ const successfulBatch = await request("127.0.0.1", "/api/optional-feature-install-batch", {
391
+ method: "POST",
392
+ body: { tab: tabId, revision: progressSnapshot.revision, featureIds: ["releaseAur"] },
393
+ timeoutMs: 20_000,
394
+ });
395
+ assert.equal(successfulBatch.status, 200, successfulBatch.body?.error);
396
+ assert.deepEqual(successfulBatch.body?.data?.restart, { autoRestarted: true, restartDeferred: false });
397
+ let rpcLaunchCountAfterSuccess = rpcLaunchCountBeforeSuccess;
398
+ for (let attempt = 0; attempt < 20 && rpcLaunchCountAfterSuccess === rpcLaunchCountBeforeSuccess; attempt++) {
399
+ await delay(50);
400
+ rpcLaunchCountAfterSuccess = (await readJsonLines(fakePiCliLog)).filter(({ event }) => event === "rpc").length;
401
+ }
402
+ assert.equal(rpcLaunchCountAfterSuccess, rpcLaunchCountBeforeSuccess + 1, "an idle tab should restart automatically after a fully successful batch");
403
+ const completedSnapshot = (await request("127.0.0.1", "/api/optional-features")).body?.data;
404
+ assert.equal(completedSnapshot?.phase, "complete");
405
+ assert.equal(completedSnapshot?.progress?.autoRestarted, true);
406
+
407
+ const lanHost = lanAddress();
408
+ if (lanHost) assert.equal((await request(lanHost, "/api/optional-feature-install-batch", { method: "POST", body: { tab: tabId, revision: batchRevision, featureIds: ["aurReview"] } })).status, 403);
409
+
410
+ const shutdownResponse = await request("127.0.0.1", "/api/shutdown", { method: "POST", body: {} });
411
+ assert.equal(shutdownResponse.status, 200);
412
+ for (let attempt = 0; attempt < 50 && child.exitCode === null; attempt++) await delay(100);
413
+ assert.notEqual(child.exitCode, null);
414
+ }
415
+
213
416
  try {
214
417
  // Wait for the HTTP server to accept requests.
215
418
  let health;
@@ -228,6 +431,101 @@ try {
228
431
  assert.equal(health.body.piRunning, true, "fake pi RPC process should be attached and running");
229
432
  assert.match(health.body.piVersion, /^\d+\.\d+\.\d+/, "health metadata should expose the installed Pi version");
230
433
 
434
+ if (optionalFeatureFocus) {
435
+ await runOptionalFeatureFocus();
436
+ } else {
437
+ const summaryTabs = await request("127.0.0.1", "/api/tabs");
438
+ const summaryTabId = summaryTabs.body?.data?.tabs?.[0]?.id;
439
+ assert.ok(summaryTabId, "session-summary endpoint checks require the startup tab");
440
+ const summaryPath = `/api/session-summary/preferences?tab=${encodeURIComponent(summaryTabId)}`;
441
+ const initialSummaryPreferences = await request("127.0.0.1", summaryPath);
442
+ assert.equal(initialSummaryPreferences.status, 200, initialSummaryPreferences.body?.error);
443
+ assert.equal(initialSummaryPreferences.headers.get("cache-control"), "private, no-store", "summary preferences must not be cached by shared or browser caches");
444
+ assert.equal(initialSummaryPreferences.body?.data?.version, 1);
445
+ assert.equal(initialSummaryPreferences.body?.data?.preferences?.configured, false, "first read should not silently save setup defaults");
446
+ assert.deepEqual(initialSummaryPreferences.body?.data?.models?.map(({ provider, id }) => [provider, id]), [["fake", "fake-model"]]);
447
+ assert.deepEqual(initialSummaryPreferences.body?.data?.modelThinkingLevels?.["fake/fake-model"], ["off"]);
448
+ assert.match(initialSummaryPreferences.body?.data?.disclosure?.scope || "", /user text, final assistant text, and tool names only/i);
449
+ assert.equal(await pathExists(sessionSummaryConfigFile), false, "reading unconfigured summary setup must not create a preference file");
450
+
451
+ const unconfiguredSummaryGenerate = await request("127.0.0.1", `/api/session-summary/generate?tab=${encodeURIComponent(summaryTabId)}`, { method: "POST", body: { refresh: true } });
452
+ assert.equal(unconfiguredSummaryGenerate.status, 409, "direct generation must not bypass explicit setup confirmation");
453
+ assert.match(unconfiguredSummaryGenerate.body?.error || "", /setup must be confirmed/i);
454
+
455
+ const nonJsonSummarySave = await fetch(`http://127.0.0.1:${port}${summaryPath}`, {
456
+ method: "PUT",
457
+ headers: { "content-type": "text/plain" },
458
+ body: "{}",
459
+ });
460
+ assert.equal(nonJsonSummarySave.status, 415, "summary setup must reject cross-origin-simple content types");
461
+ const crossSiteSummarySave = await fetch(`http://127.0.0.1:${port}${summaryPath}`, {
462
+ method: "PUT",
463
+ headers: { "content-type": "application/json", "sec-fetch-site": "cross-site" },
464
+ body: JSON.stringify({ confirmed: true, preferences: {} }),
465
+ });
466
+ assert.equal(crossSiteSummarySave.status, 403, "summary setup must reject explicit cross-site mutations");
467
+ const unconfirmedSummarySave = await request("127.0.0.1", summaryPath, { method: "PUT", body: { confirmed: false, preferences: {} } });
468
+ assert.equal(unconfirmedSummarySave.status, 409, "summary setup must require explicit privacy and cost confirmation");
469
+ assert.equal(await pathExists(sessionSummaryConfigFile), false, "rejected summary setup must not persist defaults");
470
+
471
+ const validSummaryPreferences = {
472
+ enabled: true,
473
+ model: { provider: "fake", modelId: "fake-model", thinkingLevel: "off" },
474
+ prompts: { title: "Fixture title prompt", summary: "Fixture Markdown summary prompt" },
475
+ input: { scope: "text-and-tool-names" },
476
+ context: { injectLatest: false },
477
+ title: { enabled: true, minSettledTurns: 3 },
478
+ };
479
+ const invalidSummaryShape = await request("127.0.0.1", summaryPath, {
480
+ method: "PUT",
481
+ body: { confirmed: true, preferences: { ...validSummaryPreferences, credentials: "forbidden" } },
482
+ });
483
+ assert.equal(invalidSummaryShape.status, 400, "summary setup must reject unknown fields rather than retaining secrets or future client authority");
484
+ const invalidSummaryModel = await request("127.0.0.1", summaryPath, {
485
+ method: "PUT",
486
+ body: { confirmed: true, preferences: { ...validSummaryPreferences, model: { provider: "fake", modelId: "missing", thinkingLevel: "off" } } },
487
+ });
488
+ assert.equal(invalidSummaryModel.status, 400, "summary setup must validate against the active tab's authenticated model registry");
489
+ const savedSummaryPreferences = await request("127.0.0.1", summaryPath, {
490
+ method: "PUT",
491
+ body: { confirmed: true, preferences: validSummaryPreferences },
492
+ });
493
+ assert.equal(savedSummaryPreferences.status, 200, savedSummaryPreferences.body?.error);
494
+ assert.equal(savedSummaryPreferences.headers.get("cache-control"), "private, no-store");
495
+ assert.equal(savedSummaryPreferences.body?.data?.preferences?.configured, true);
496
+ assert.equal(savedSummaryPreferences.body?.data?.summary?.configured, true);
497
+ const summaryReplay = await waitForSseEvent(summaryTabId, (event) => event.type === "webui_session_summary" && event.kind === "replay");
498
+ assert.equal(summaryReplay.event.tabId, summaryTabId, "summary replay must remain scoped to the requested tab");
499
+ assert.equal(summaryReplay.event.summary?.configured, true);
500
+ assert.equal(Object.hasOwn(summaryReplay.event, "preferences"), false, "summary SSE replay must not expose setup prompts or model preferences");
501
+ const persistedSummaryPreferences = JSON.parse(await readFile(sessionSummaryConfigFile, "utf8"));
502
+ assert.equal(persistedSummaryPreferences.configured, true);
503
+ assert.equal(persistedSummaryPreferences.model.modelId, "fake-model");
504
+ assert.equal(Object.hasOwn(persistedSummaryPreferences, "credentials"), false, "summary preferences must not persist credentials");
505
+ assert.equal((await stat(sessionSummaryConfigFile)).mode & 0o777, 0o600, "summary preferences must be private");
506
+ persistedSummaryPreferences.credentials = "fixture-secret-must-not-cross-http";
507
+ persistedSummaryPreferences.model.providerToken = "fixture-provider-token";
508
+ await writeFile(sessionSummaryConfigFile, `${JSON.stringify(persistedSummaryPreferences, null, 2)}\n`, { mode: 0o600 });
509
+ const sanitizedSummaryPreferences = await request("127.0.0.1", summaryPath);
510
+ assert.equal(sanitizedSummaryPreferences.status, 200);
511
+ assert.equal(Object.hasOwn(sanitizedSummaryPreferences.body?.data?.preferences || {}, "credentials"), false, "unknown persisted keys must not cross the browser API boundary");
512
+ assert.equal(Object.hasOwn(sanitizedSummaryPreferences.body?.data?.preferences?.model || {}, "providerToken"), false, "unknown nested model keys must not cross the browser API boundary");
513
+ assert.equal(JSON.parse(await readFile(sessionSummaryConfigFile, "utf8")).credentials, "fixture-secret-must-not-cross-http", "sanitized reads must not destroy unknown future persisted keys");
514
+
515
+ const summaryPromptCountBefore = (await readJsonLines(fakePiCommandLog)).filter(({ direction, type, message }) => direction === "command" && type === "prompt" && String(message || "").startsWith("/summary")).length;
516
+ const unavailableSummaryGenerate = await request("127.0.0.1", `/api/session-summary/generate?tab=${encodeURIComponent(summaryTabId)}`, { method: "POST", body: { refresh: true } });
517
+ assert.equal(unavailableSummaryGenerate.status, 409, "generation should fail closed when /summary is absent from the active tab command catalog");
518
+ const summaryPromptCountAfter = (await readJsonLines(fakePiCommandLog)).filter(({ direction, type, message }) => direction === "command" && type === "prompt" && String(message || "").startsWith("/summary")).length;
519
+ assert.equal(summaryPromptCountAfter, summaryPromptCountBefore, "an unavailable summary command must not start a model-facing agent prompt");
520
+ const malformedSummaryGenerate = await request("127.0.0.1", `/api/session-summary/generate?tab=${encodeURIComponent(summaryTabId)}`, { method: "POST", body: { refresh: "yes" } });
521
+ assert.equal(malformedSummaryGenerate.status, 400, "summary refresh must be a strict boolean");
522
+ const oversizedSummarySave = await fetch(`http://127.0.0.1:${port}${summaryPath}`, {
523
+ method: "PUT",
524
+ headers: { "content-type": "application/json" },
525
+ body: JSON.stringify({ confirmed: true, padding: "x".repeat(33 * 1024) }),
526
+ });
527
+ assert.equal(oversizedSummarySave.status, 413, "summary mutations over 32 KiB must be rejected before validation");
528
+
231
529
  const initialInterfacePreferences = await request("127.0.0.1", "/api/interface-preferences");
232
530
  assert.equal(initialInterfacePreferences.status, 200);
233
531
  assert.equal(initialInterfacePreferences.body?.data?.preferences?.sidePanelWidth, null, "a user without a saved width should receive the default preference");
@@ -705,11 +1003,114 @@ try {
705
1003
  const validImageCommand = imageCommands.find((entry) => entry.direction === "command" && entry.message === "canonical inline image fixture");
706
1004
  assert.deepEqual(validImageCommand?.images, [{ type: "image", data: canonicalPng, mimeType: "image/png" }], "canonical image bytes and MIME type should be forwarded unchanged");
707
1005
 
1006
+ const webuiManifest = JSON.parse(await readFile(path.join(root, "package.json"), "utf8"));
1007
+ assert.deepEqual(webuiManifest.optionalDependencies, { "node-pty": "^1.1.0" }, "node-pty should be the only optional dependency");
1008
+ assert.equal(webuiManifest.dependencies?.["@firstpick/pi-utils"], "^0.2.5", "the required pi-utils runtime dependency must remain regular");
1009
+ assert.equal(JSON.stringify(webuiManifest.pi).includes("node_modules/@firstpick"), false, "the WebUI manifest must not claim optional companion resources");
1010
+
708
1011
  const optionalFeatures = await request("127.0.0.1", "/api/optional-features");
709
1012
  assert.equal(optionalFeatures.status, 200, "optional feature status should load");
1013
+ assert.equal(optionalFeatures.body?.data?.features?.length, 19, "the explicit server catalog should expose every allowlisted feature");
710
1014
  const aurReviewFeature = optionalFeatures.body?.data?.features?.find((feature) => feature.featureId === "aurReview");
1015
+ assert.equal(aurReviewFeature?.expectedSpec, "^0.1.1", "status should expose the catalog-owned compatibility spec");
711
1016
  assert.equal(aurReviewFeature?.installed, true, "workspace discovery should find the local pi-extension-aur-review sibling without an npm dependency");
712
- assert.equal(path.basename(aurReviewFeature?.installedRoot || ""), "pi-extension-aur-review", "aur-review discovery must validate the exact sibling manifest/name");
1017
+ assert.equal(aurReviewFeature?.configured, false, "physical discovery alone must not imply Pi registration");
1018
+ assert.equal(aurReviewFeature?.ready, false, "a physical but unregistered companion must not be ready after reload");
1019
+ assert.equal(aurReviewFeature?.state, "unknown", "physical discovery without canonical ownership must remain unknown");
1020
+ assert.equal(Object.hasOwn(aurReviewFeature || {}, "installedRoot"), false, "browser status must not expose the validated host package path");
1021
+ await verifyTopLevelOptionalFeatureProtection(tabId);
1022
+
1023
+ const invalidSingleFeature = await request("127.0.0.1", "/api/optional-feature-install", {
1024
+ method: "POST",
1025
+ body: { tab: tabId, featureId: "not-allowlisted" },
1026
+ });
1027
+ assert.equal(invalidSingleFeature.status, 400, "single installs must reject feature IDs outside the server catalog");
1028
+
1029
+ const installedAurReview = await request("127.0.0.1", "/api/optional-feature-install", {
1030
+ method: "POST",
1031
+ body: { tab: tabId, featureId: "aurReview" },
1032
+ timeoutMs: 10_000,
1033
+ });
1034
+ assert.equal(installedAurReview.status, 200, installedAurReview.body?.error);
1035
+ assert.match(installedAurReview.body?.data?.command || "", /install npm:@firstpick\/pi-extension-aur-review$/, "the selected Pi CLI should receive the exact unpinned npm source");
1036
+ assert.equal(installedAurReview.body?.data?.status?.installed, true);
1037
+ assert.equal(installedAurReview.body?.data?.status?.configured, true);
1038
+ assert.equal(installedAurReview.body?.data?.status?.ready, true, "successful Pi installation must verify physical presence and registration");
1039
+ const aurInstallCommands = (await readJsonLines(fakePiCliLog)).filter((entry) => entry.event === "start" && entry.args?.[1] === "npm:@firstpick/pi-extension-aur-review");
1040
+ assert.deepEqual(aurInstallCommands.map((entry) => entry.args), [["install", "npm:@firstpick/pi-extension-aur-review"]], "the feature path must invoke Pi install exactly once without npm CLI flags");
1041
+
1042
+ const registeredOptionalFeatures = await request("127.0.0.1", "/api/optional-features");
1043
+ const registeredAurReview = registeredOptionalFeatures.body?.data?.features?.find((feature) => feature.featureId === "aurReview");
1044
+ assert.equal(registeredAurReview?.ready, true, "Pi registration should survive a fresh status-manager read");
1045
+
1046
+ const resourceTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd, title: "configured optional package" } });
1047
+ assert.equal(resourceTab.status, 201, resourceTab.body?.error);
1048
+ const resourceTabId = resourceTab.body?.data?.tab?.id;
1049
+ const rpcLaunches = (await readJsonLines(fakePiCliLog)).filter((entry) => entry.event === "rpc");
1050
+ const configuredLaunchArgs = rpcLaunches.at(-1)?.args || [];
1051
+ const normalizedLaunchArgs = configuredLaunchArgs.map((arg) => String(arg).replace(/\\/g, "/"));
1052
+ assert.equal(normalizedLaunchArgs.filter((arg) => arg.endsWith("/pi-extension-aur-review/index.ts")).length, 1, "a separately configured optional extension should load once in a WebUI RPC tab");
1053
+ assert.equal(normalizedLaunchArgs.filter((arg) => arg.endsWith("/pi-package-webui/index.ts")).length, 1, "the WebUI package itself should remain loaded exactly once");
1054
+ assert.equal((await request("127.0.0.1", "/api/tabs/close", { method: "POST", body: { ids: [resourceTabId] } })).status, 200);
1055
+
1056
+ const currentBatchPlan = await request("127.0.0.1", "/api/optional-features");
1057
+ const currentBatchRevision = currentBatchPlan.body?.data?.revision;
1058
+ const malformedBatch = await request("127.0.0.1", "/api/optional-feature-install-batch", {
1059
+ method: "POST",
1060
+ body: { tab: tabId, revision: currentBatchRevision, featureIds: "aurReview" },
1061
+ });
1062
+ assert.equal(malformedBatch.status, 400, "batch installs must require an array");
1063
+ const unknownBatch = await request("127.0.0.1", "/api/optional-feature-install-batch", {
1064
+ method: "POST",
1065
+ body: { tab: tabId, revision: currentBatchRevision, featureIds: ["aurReview", "not-allowlisted"] },
1066
+ });
1067
+ assert.equal(unknownBatch.status, 400, "batch installs must reject unknown IDs before starting any command");
1068
+ const oversizedBatch = await request("127.0.0.1", "/api/optional-feature-install-batch", {
1069
+ method: "POST",
1070
+ body: { tab: tabId, revision: currentBatchRevision, featureIds: Array.from({ length: 20 }, () => "aurReview") },
1071
+ });
1072
+ assert.equal(oversizedBatch.status, 400, "batch installs must cap raw input to the catalog size");
1073
+ const staleBatch = await request("127.0.0.1", "/api/optional-feature-install-batch", {
1074
+ method: "POST",
1075
+ body: { tab: tabId, revision: "sha256:stale", featureIds: ["aurReview"] },
1076
+ });
1077
+ assert.equal(staleBatch.status, 409, "batch installs must reject stale audit revisions");
1078
+
1079
+ const batchLogStart = (await readJsonLines(fakePiCliLog)).length;
1080
+ const partialBatch = await request("127.0.0.1", "/api/optional-feature-install-batch", {
1081
+ method: "POST",
1082
+ body: { tab: tabId, revision: currentBatchRevision, featureIds: ["bangCommandAutocomplete", "statsCommand", "bangCommandAutocomplete", "gitFooterStatus"] },
1083
+ timeoutMs: 20_000,
1084
+ });
1085
+ assert.equal(partialBatch.status, 200, partialBatch.body?.error);
1086
+ assert.deepEqual(partialBatch.body?.data?.featureIds, ["bangCommandAutocomplete", "statsCommand", "gitFooterStatus"], "batch input should be deduplicated without reordering");
1087
+ assert.deepEqual(partialBatch.body?.data?.results?.map(({ featureId, ok }) => [featureId, ok]), [
1088
+ ["bangCommandAutocomplete", true],
1089
+ ["statsCommand", false],
1090
+ ["gitFooterStatus", true],
1091
+ ], "a failed Pi install must not stop later allowlisted installs");
1092
+ assert.deepEqual({ total: partialBatch.body?.data?.total, succeeded: partialBatch.body?.data?.succeeded, failed: partialBatch.body?.data?.failed }, { total: 3, succeeded: 2, failed: 1 });
1093
+ assert.equal(partialBatch.body?.data?.results?.[1]?.optionalFeatureInstall?.exitCode, 17, "batch failures should retain exit diagnostics");
1094
+ assert.match(partialBatch.body?.data?.results?.[1]?.optionalFeatureInstall?.command || "", /install npm:@firstpick\/pi-extension-stats$/, "batch failures should retain a copyable Pi command");
1095
+ assert.match(partialBatch.body?.data?.results?.[1]?.optionalFeatureInstall?.outputTail || "", /fixture Pi install failure/, "batch failures should retain bounded output diagnostics");
1096
+ const batchLog = (await readJsonLines(fakePiCliLog)).slice(batchLogStart).filter((entry) => entry.event === "start" || entry.event === "finish");
1097
+ assert.deepEqual(batchLog.map((entry) => [entry.event, entry.args?.[1], entry.exitCode]), [
1098
+ ["start", "npm:@firstpick/pi-extension-bang-command-autocomplete", undefined],
1099
+ ["finish", "npm:@firstpick/pi-extension-bang-command-autocomplete", 0],
1100
+ ["start", "npm:@firstpick/pi-extension-stats", undefined],
1101
+ ["finish", "npm:@firstpick/pi-extension-stats", 17],
1102
+ ["start", "npm:@firstpick/pi-extension-git-footer-status", undefined],
1103
+ ["finish", "npm:@firstpick/pi-extension-git-footer-status", 0],
1104
+ ], "batch commands should execute sequentially in request order");
1105
+
1106
+ const lanHost = lanAddress();
1107
+ if (lanHost) {
1108
+ const remoteBatch = await request(lanHost, "/api/optional-feature-install-batch", {
1109
+ method: "POST",
1110
+ body: { tab: tabId, revision: currentBatchRevision, featureIds: ["aurReview"] },
1111
+ });
1112
+ assert.equal(remoteBatch.status, 403, "batch installs must remain localhost-only");
1113
+ }
713
1114
 
714
1115
  const sessionToolsBefore = await request("127.0.0.1", `/api/tools?tab=${encodeURIComponent(tabId)}&scope=session`);
715
1116
  assert.equal(sessionToolsBefore.status, 200);
@@ -3241,12 +3642,27 @@ try {
3241
3642
  await delay(100);
3242
3643
  }
3243
3644
  assert.notEqual(child.exitCode, null, "server should exit after /api/shutdown");
3645
+ }
3244
3646
  } finally {
3245
3647
  if (child.exitCode === null) {
3246
3648
  child.kill("SIGKILL");
3247
3649
  await new Promise((resolve) => child.once("exit", resolve));
3248
3650
  }
3249
3651
  await new Promise((resolve) => voiceProvider.close(() => resolve()));
3652
+ const testSupervisorPaths = await supervisorPaths({ agentDir: workflowPolicyAgentDir, port });
3653
+ const testSupervisorState = await readSupervisorState(testSupervisorPaths);
3654
+ if (testSupervisorState && supervisorPidIsAlive(testSupervisorState.pid)) {
3655
+ terminateProcessTree({
3656
+ pid: testSupervisorState.pid,
3657
+ exitCode: null,
3658
+ signalCode: null,
3659
+ kill: (signal) => {
3660
+ process.kill(testSupervisorState.pid, signal);
3661
+ return true;
3662
+ },
3663
+ }, "SIGKILL");
3664
+ for (let attempt = 0; attempt < 50 && supervisorPidIsAlive(testSupervisorState.pid); attempt++) await delay(100);
3665
+ }
3250
3666
  await rmWithRetry(cwd);
3251
3667
  await rmWithRetry(harnessSideEffectsRoot);
3252
3668
  }