@firstpick/pi-package-webui 0.8.6 → 0.8.7

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 (89) hide show
  1. package/README.md +18 -606
  2. package/bin/pi-webui-launcher.mjs +22 -0
  3. package/bin/pi-webui-update-supervisor.mjs +86 -0
  4. package/bin/pi-webui.mjs +558 -524
  5. package/index.ts +8 -5
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +17 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-preferences.mjs +16 -1
  11. package/lib/subagent-launch-slots.mjs +14 -2
  12. package/lib/trust-boundaries.mjs +3 -0
  13. package/lib/update/executor.mjs +99 -0
  14. package/lib/update/journal.mjs +175 -0
  15. package/lib/update/owners.mjs +70 -0
  16. package/lib/update/plan.mjs +134 -0
  17. package/lib/update/resolver.mjs +168 -0
  18. package/lib/update/supervisor.mjs +238 -0
  19. package/lib/update/verify.mjs +52 -0
  20. package/lib/update-commands.mjs +25 -13
  21. package/lib/webui-workspaces.mjs +17 -1
  22. package/package.json +4 -4
  23. package/public/app.js +1290 -82
  24. package/public/index.html +124 -48
  25. package/public/middle-button-drag-scroll.mjs +154 -0
  26. package/public/sampling-parameter-controls.mjs +361 -0
  27. package/public/service-worker.js +3 -1
  28. package/public/styles.css +417 -1
  29. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  30. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  31. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  32. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  33. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  34. package/tests/browser/update-reconnect.spec.mjs +92 -0
  35. package/tests/codex-fast-mode-static.test.mjs +2 -2
  36. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  37. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  38. package/tests/component-update-api-static.test.mjs +22 -61
  39. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  40. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  41. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  42. package/tests/fast-mode-client-static.test.mjs +1 -1
  43. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  44. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  45. package/tests/fixtures/fake-pi.mjs +66 -0
  46. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  47. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  48. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  49. package/tests/http-endpoints-harness.test.mjs +68 -18
  50. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  51. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  52. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  53. package/tests/mobile-foundation-static.test.mjs +4 -4
  54. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  55. package/tests/mobile-static.test.mjs +23 -21
  56. package/tests/open-issue-wizard-static.test.mjs +1 -1
  57. package/tests/optional-feature-migration-frontend.test.mjs +9 -5
  58. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  59. package/tests/questionnaire-dialog.test.mjs +3 -3
  60. package/tests/remote-auth-settings-harness.test.mjs +34 -0
  61. package/tests/rpc-supervisor-host.test.mjs +11 -2
  62. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  63. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  64. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  65. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  66. package/tests/sampling-parameter-controls.test.mjs +241 -0
  67. package/tests/session-sampling-helper.test.mjs +228 -0
  68. package/tests/session-sampling-http.test.mjs +168 -0
  69. package/tests/session-sampling-ui-static.test.mjs +370 -0
  70. package/tests/session-summary-core.test.mjs +24 -11
  71. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  72. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  73. package/tests/staged-content-hash-contract.test.mjs +52 -11
  74. package/tests/subagent-launch-slots.test.mjs +18 -1
  75. package/tests/theme-customizer-static.test.mjs +1 -1
  76. package/tests/ui-layout-settings.test.mjs +18 -1
  77. package/tests/update-api-harness.test.mjs +111 -0
  78. package/tests/update-commands.test.mjs +15 -45
  79. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  80. package/tests/update-journal-harness.test.mjs +59 -0
  81. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  82. package/tests/update-owners.test.mjs +27 -0
  83. package/tests/update-plan.test.mjs +58 -0
  84. package/tests/update-resolver.test.mjs +56 -0
  85. package/tests/update-supervisor-harness.test.mjs +57 -0
  86. package/tests/update-tab-restore-harness.test.mjs +24 -0
  87. package/tests/update-verify.test.mjs +31 -0
  88. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  89. package/webui-rpc-helper.mjs +119 -0
@@ -88,14 +88,14 @@ async function waitForSseEvent(tabId, predicate, trigger) {
88
88
 
89
89
  async function rmWithRetry(target) {
90
90
  let lastError;
91
- for (let attempt = 0; attempt < 8; attempt++) {
91
+ for (let attempt = 0; attempt < 20; attempt++) {
92
92
  try {
93
93
  await rm(target, { recursive: true, force: true });
94
94
  return;
95
95
  } catch (error) {
96
96
  lastError = error;
97
97
  if (error?.code !== "EBUSY" && error?.code !== "EPERM" && error?.code !== "ENOTEMPTY") throw error;
98
- await delay(150 * (attempt + 1));
98
+ await delay(Math.min(500, 150 * (attempt + 1)));
99
99
  }
100
100
  }
101
101
  throw lastError;
@@ -170,7 +170,9 @@ const args = process.argv.slice(2);
170
170
  const log = async (entry) => appendFile(process.env.FAKE_PI_CLI_LOG, JSON.stringify({ at: Date.now(), ...entry }) + "\\n", "utf8");
171
171
  process.on("SIGTERM", () => process.exit(143));
172
172
  process.on("SIGINT", () => process.exit(130));
173
- if (args[0] === "install") {
173
+ if (args[0] === "--version") {
174
+ console.log("0.84.0");
175
+ } else if (args[0] === "install") {
174
176
  const source = String(args[1] || "");
175
177
  await log({ event: "start", args });
176
178
  if (source === "npm:@firstpick/pi-extension-stats") {
@@ -201,6 +203,7 @@ if (args[0] === "install") {
201
203
  `, "utf8");
202
204
  await chmod(fakePiCli, 0o755);
203
205
 
206
+ const latestPiVersion = "999.0.0";
204
207
  const voiceProviderRequests = [];
205
208
  const voiceProvider = createServer(async (req, res) => {
206
209
  const chunks = [];
@@ -217,6 +220,11 @@ const voiceProvider = createServer(async (req, res) => {
217
220
  res.end(Buffer.from("fake mp3 bytes"));
218
221
  return;
219
222
  }
223
+ if (req.url === "/pi-latest") {
224
+ res.writeHead(200, { "content-type": "application/json" });
225
+ res.end(JSON.stringify({ version: latestPiVersion, packageName: "@earendil-works/pi-coding-agent" }));
226
+ return;
227
+ }
220
228
  if (req.url?.startsWith("/pi-releases/")) {
221
229
  const tagName = decodeURIComponent(req.url.slice("/pi-releases/".length));
222
230
  res.writeHead(200, { "content-type": "application/json" });
@@ -259,6 +267,7 @@ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.
259
267
  PI_WEBUI_RECOVERY_TOKEN: recoveryEndpointToken,
260
268
  PI_VOICE_STT_URL: `http://127.0.0.1:${voiceProviderPort}/stt`,
261
269
  PI_VOICE_TTS_URL: `http://127.0.0.1:${voiceProviderPort}/tts`,
270
+ PI_WEBUI_PI_LATEST_VERSION_URL: `http://127.0.0.1:${voiceProviderPort}/pi-latest`,
262
271
  PI_WEBUI_PI_RELEASES_API_BASE_URL: `http://127.0.0.1:${voiceProviderPort}/pi-releases`,
263
272
  },
264
273
  });
@@ -316,7 +325,7 @@ async function runOptionalFeatureFocus() {
316
325
 
317
326
  const initial = await request("127.0.0.1", "/api/optional-features");
318
327
  assert.equal(initial.status, 200);
319
- assert.equal(initial.body?.data?.features?.length, 19);
328
+ assert.equal(initial.body?.data?.features?.length, 20);
320
329
  const aurBefore = initial.body?.data?.features?.find(({ featureId }) => featureId === "aurReview");
321
330
  assert.deepEqual({ installed: aurBefore?.installed, configured: aurBefore?.configured, ready: aurBefore?.ready }, { installed: true, configured: false, ready: false });
322
331
  assert.equal(aurBefore?.expectedSpec, "^0.1.1");
@@ -477,7 +486,7 @@ try {
477
486
  assert.equal(Object.hasOwn(createdGlobalTheme.body?.data || {}, "path"), false, "theme save responses must not disclose host paths");
478
487
  const globalThemeFile = path.join(workflowPolicyAgentDir, "themes", "global-fixture.json");
479
488
  assert.equal(await readFile(globalThemeFile, "utf8"), serializeTheme(globalTheme), "global themes must use canonical Pi JSON bytes");
480
- assert.equal((await stat(globalThemeFile)).mode & 0o777, 0o600, "saved themes must have private permissions");
489
+ if (process.platform !== "win32") assert.equal((await stat(globalThemeFile)).mode & 0o777, 0o600, "saved themes must have private permissions");
481
490
 
482
491
  const projectTheme = themeFixture("project-fixture", "#335577");
483
492
  const createdProjectTheme = await request("127.0.0.1", customThemePath, {
@@ -644,6 +653,32 @@ try {
644
653
  const summaryTabs = await request("127.0.0.1", "/api/tabs");
645
654
  const summaryTabId = summaryTabs.body?.data?.tabs?.[0]?.id;
646
655
  assert.ok(summaryTabId, "session-summary endpoint checks require the startup tab");
656
+
657
+ const samplingPath = `/api/tabs/${encodeURIComponent(summaryTabId)}/sampling-parameters`;
658
+ const initialSampling = await request("127.0.0.1", samplingPath);
659
+ assert.equal(initialSampling.status, 200, initialSampling.body?.error);
660
+ assert.equal(initialSampling.headers.get("cache-control"), "private, no-store");
661
+ assert.equal(initialSampling.body?.data?.support?.supported, true);
662
+ assert.equal(initialSampling.body?.data?.support?.api, "openai-completions");
663
+ assert.deepEqual(initialSampling.body?.data?.support?.model, { provider: "fake", id: "fake-model", name: "Fake Model" });
664
+ assert.equal(initialSampling.body?.data?.support?.parameters?.temperature?.supported, true);
665
+ assert.equal(initialSampling.body?.data?.support?.parameters?.top_k?.supported, false);
666
+ assert.equal(initialSampling.body?.data?.support?.parameters?.min_p?.source, "unsupported");
667
+ assert.ok(Array.isArray(initialSampling.body?.data?.support?.compatibleApis), "legacy support diagnostics must remain available");
668
+
669
+ const savedSampling = await request("127.0.0.1", samplingPath, {
670
+ method: "PUT",
671
+ body: { temperature: 0.3, top_k: 32, vendor_mode: "strict" },
672
+ });
673
+ assert.equal(savedSampling.status, 200, savedSampling.body?.error);
674
+ assert.deepEqual(savedSampling.body?.data?.session, { temperature: 0.3, top_k: 32, vendor_mode: "strict" });
675
+ assert.deepEqual(savedSampling.body?.data?.effective, { temperature: 0.3 }, "unsupported stored sampling values must remain inert");
676
+ assert.equal(savedSampling.body?.data?.support?.parameters?.top_k?.supported, false);
677
+ const resetSampling = await request("127.0.0.1", samplingPath, { method: "PUT", body: {} });
678
+ assert.equal(resetSampling.status, 200, resetSampling.body?.error);
679
+ assert.deepEqual(resetSampling.body?.data?.session, {});
680
+ assert.deepEqual(resetSampling.body?.data?.effective, { temperature: 0.7 });
681
+
647
682
  const summaryPath = `/api/session-summary/preferences?tab=${encodeURIComponent(summaryTabId)}`;
648
683
  const initialSummaryPreferences = await request("127.0.0.1", summaryPath);
649
684
  assert.equal(initialSummaryPreferences.status, 200, initialSummaryPreferences.body?.error);
@@ -709,7 +744,7 @@ try {
709
744
  assert.equal(persistedSummaryPreferences.configured, true);
710
745
  assert.equal(persistedSummaryPreferences.model.modelId, "fake-model");
711
746
  assert.equal(Object.hasOwn(persistedSummaryPreferences, "credentials"), false, "summary preferences must not persist credentials");
712
- assert.equal((await stat(sessionSummaryConfigFile)).mode & 0o777, 0o600, "summary preferences must be private");
747
+ if (process.platform !== "win32") assert.equal((await stat(sessionSummaryConfigFile)).mode & 0o777, 0o600, "summary preferences must be private");
713
748
  persistedSummaryPreferences.credentials = "fixture-secret-must-not-cross-http";
714
749
  persistedSummaryPreferences.model.providerToken = "fixture-provider-token";
715
750
  await writeFile(sessionSummaryConfigFile, `${JSON.stringify(persistedSummaryPreferences, null, 2)}\n`, { mode: 0o600 });
@@ -877,7 +912,7 @@ try {
877
912
  assert.deepEqual(persistedWorkflowPolicy, savedWorkflowPolicy.body?.data?.policy, "workflow policy file should contain exactly the canonical saved policy");
878
913
  assert.equal(Object.hasOwn(savedWorkflowPolicy.body?.data?.policy || {}, "suggestions"), false, "saved v1 response policy must not persist advisory suggestions");
879
914
  assert.equal(Object.hasOwn(persistedWorkflowPolicy, "suggestions"), false, "saved v1 file must not persist advisory suggestions");
880
- assert.equal((await stat(workflowPolicyFile)).mode & 0o777, 0o600, "workflow policy file must be private");
915
+ if (process.platform !== "win32") assert.equal((await stat(workflowPolicyFile)).mode & 0o777, 0o600, "workflow policy file must be private");
881
916
 
882
917
  const readWorkflowPolicy = await request("127.0.0.1", "/api/workflow-policy");
883
918
  assert.equal(readWorkflowPolicy.status, 200, `saved workflow policy should reload: ${readWorkflowPolicy.body?.error || ""}`);
@@ -927,15 +962,16 @@ try {
927
962
 
928
963
  const releaseNotes = await request("127.0.0.1", "/api/pi-release-notes");
929
964
  assert.equal(releaseNotes.status, 200, `Pi release notes should load through the server: ${releaseNotes.body?.error || ""}`);
930
- assert.equal(releaseNotes.body?.data?.version, health.body.piVersion);
931
- assert.equal(releaseNotes.body?.data?.tagName, `v${health.body.piVersion}`);
932
- assert.equal(releaseNotes.body?.data?.title, `Pi v${health.body.piVersion} test release`);
965
+ assert.equal(releaseNotes.body?.data?.version, latestPiVersion, "an available update should select the latest Pi release");
966
+ assert.equal(releaseNotes.body?.data?.tagName, `v${latestPiVersion}`);
967
+ assert.equal(releaseNotes.body?.data?.title, `Pi v${latestPiVersion} test release`);
933
968
  assert.match(releaseNotes.body?.data?.body || "", /Release notes from the test GitHub endpoint/);
934
- assert.equal(releaseNotes.body?.data?.url, `https://github.com/earendil-works/pi/releases/tag/v${health.body.piVersion}`);
969
+ assert.equal(releaseNotes.body?.data?.url, `https://github.com/earendil-works/pi/releases/tag/v${latestPiVersion}`);
935
970
  assert.equal(releaseNotes.headers.get("cache-control"), "private, no-store", "browser caches should not retain notes across Pi upgrades");
936
971
  const cachedReleaseNotes = await request("127.0.0.1", "/api/pi-release-notes");
937
- assert.equal(cachedReleaseNotes.body?.data?.tagName, `v${health.body.piVersion}`);
938
- assert.equal(voiceProviderRequests.filter((item) => item.url === `/pi-releases/v${health.body.piVersion}`).length, 1, "the server should fetch each installed Pi release only once");
972
+ assert.equal(cachedReleaseNotes.body?.data?.tagName, `v${latestPiVersion}`);
973
+ assert.equal(voiceProviderRequests.filter((item) => item.url === `/pi-releases/v${latestPiVersion}`).length, 1, "the server should fetch the available Pi release only once");
974
+ assert.equal(voiceProviderRequests.filter((item) => item.url === `/pi-releases/v${health.body.piVersion}`).length, 0, "the installed Pi release should not be fetched while a newer release is available");
939
975
 
940
976
  // Static assets: brotli/gzip compression plus ETag revalidation (P0-2).
941
977
  const brotliResponse = await fetch(`http://127.0.0.1:${port}/app.js`, {
@@ -1221,7 +1257,7 @@ try {
1221
1257
 
1222
1258
  const optionalFeatures = await request("127.0.0.1", "/api/optional-features");
1223
1259
  assert.equal(optionalFeatures.status, 200, "optional feature status should load");
1224
- assert.equal(optionalFeatures.body?.data?.features?.length, 19, "the explicit server catalog should expose every allowlisted feature");
1260
+ assert.equal(optionalFeatures.body?.data?.features?.length, 20, "the explicit server catalog should expose every allowlisted feature");
1225
1261
  const aurReviewFeature = optionalFeatures.body?.data?.features?.find((feature) => feature.featureId === "aurReview");
1226
1262
  assert.equal(aurReviewFeature?.expectedSpec, "^0.1.1", "status should expose the catalog-owned compatibility spec");
1227
1263
  assert.equal(aurReviewFeature?.installed, true, "workspace discovery should find the local pi-extension-aur-review sibling without an npm dependency");
@@ -1278,7 +1314,7 @@ try {
1278
1314
  assert.equal(unknownBatch.status, 400, "batch installs must reject unknown IDs before starting any command");
1279
1315
  const oversizedBatch = await request("127.0.0.1", "/api/optional-feature-install-batch", {
1280
1316
  method: "POST",
1281
- body: { tab: tabId, revision: currentBatchRevision, featureIds: Array.from({ length: 20 }, () => "aurReview") },
1317
+ body: { tab: tabId, revision: currentBatchRevision, featureIds: Array.from({ length: 21 }, () => "aurReview") },
1282
1318
  });
1283
1319
  assert.equal(oversizedBatch.status, 400, "batch installs must cap raw input to the catalog size");
1284
1320
  const staleBatch = await request("127.0.0.1", "/api/optional-feature-install-batch", {
@@ -2537,9 +2573,11 @@ try {
2537
2573
  assert.equal(operationSnapshot.body?.data?.conflicts?.[0]?.preview?.hasMarkers, true, "conflict preview should detect conflict markers");
2538
2574
 
2539
2575
  const conflictAgent = await request("127.0.0.1", "/api/git-operation/resolve-with-agent", { method: "POST", body: { tab: mergeTab }, timeoutMs: 20_000 });
2576
+ const conflictAgentTabId = conflictAgent.body?.data?.tab?.id;
2540
2577
  assert.equal(conflictAgent.status, 200);
2541
2578
  assert.equal(conflictAgent.body?.ok, true, `conflict handoff should open an agent tab: ${conflictAgent.body?.error || ""}`);
2542
- assert.notEqual(conflictAgent.body?.data?.tab?.id, mergeTab, "conflict handoff should create a separate tab");
2579
+ assert.ok(conflictAgentTabId, "conflict handoff should create a separate tab");
2580
+ assert.notEqual(conflictAgentTabId, mergeTab, "conflict handoff should create a separate tab");
2543
2581
  assert.equal(conflictAgent.body?.data?.tab?.cwd, mergeRepo, "conflict agent should use the conflicted repository root");
2544
2582
  assert.equal(conflictAgent.body?.data?.tab?.title, "Resolve merge conflicts");
2545
2583
  assert.deepEqual(conflictAgent.body?.data?.operation?.conflicts, [{ path: "file.txt", status: "UU" }]);
@@ -2745,7 +2783,7 @@ try {
2745
2783
  const pruneConfirmed = await request("127.0.0.1", "/api/git-worktrees/prune", { method: "POST", body: { tab: undoTab, confirmed: true }, timeoutMs: 20_000 });
2746
2784
  assert.equal(pruneConfirmed.body?.ok, true, `confirmed prune should succeed: ${pruneConfirmed.body?.error || ""}`);
2747
2785
 
2748
- const closeGitActionTabs = await request("127.0.0.1", "/api/tabs/close", { method: "POST", body: { ids: [gitignoreTab, lfTab, noFinalNewlineTab, crlfTab, literalTab, unsafeTab, fileDiffTab, stagingTab, truncationTab, mergeTab, abortTab, rebaseTab, bisectTab, stashTab, undoTab] }, timeoutMs: 10_000 });
2786
+ const closeGitActionTabs = await request("127.0.0.1", "/api/tabs/close", { method: "POST", body: { ids: [gitignoreTab, lfTab, noFinalNewlineTab, crlfTab, literalTab, unsafeTab, fileDiffTab, stagingTab, truncationTab, mergeTab, conflictAgentTabId, abortTab, rebaseTab, bisectTab, stashTab, undoTab] }, timeoutMs: 10_000 });
2749
2787
  assert.equal(closeGitActionTabs.status, 200, "git action fixture tabs should close");
2750
2788
  await rmWithRetry(gitFixturesRoot);
2751
2789
 
@@ -3033,7 +3071,10 @@ try {
3033
3071
  nestedSearchState = await request("127.0.0.1", `/api/app-runners?tab=${encodeURIComponent(nestedSearchTabId)}`, { timeoutMs: 5_000 });
3034
3072
  }
3035
3073
  assert.equal(nestedSearchState.body?.data?.activeRun?.status, "done", "configured shell runner should complete");
3036
- assert.match((nestedSearchState.body?.data?.activeRun?.lines || []).join("\n"), new RegExp(`configured alpha cwd=${cwd.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`), "configured shell runners should execute at the project root");
3074
+ const expectedShellCwd = process.platform === "win32"
3075
+ ? cwd.replace(/\\/g, "/").replace(/^([A-Za-z]):/, (_match, drive) => `/${drive.toLowerCase()}`)
3076
+ : cwd;
3077
+ assert.match((nestedSearchState.body?.data?.activeRun?.lines || []).join("\n"), new RegExp(`configured alpha cwd=${expectedShellCwd.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`), "configured shell runners should execute at the project root");
3037
3078
  } finally {
3038
3079
  if (nestedSearchTabId) await request("127.0.0.1", "/api/tabs/close", { method: "POST", body: { ids: [nestedSearchTabId] }, timeoutMs: 10_000 });
3039
3080
  }
@@ -3655,6 +3696,15 @@ try {
3655
3696
  const remoteWorkflowPolicyRead = await request(lan, "/api/workflow-policy");
3656
3697
  assert.equal(remoteWorkflowPolicyRead.status, 403, "workflow policy reads must be localhost-only");
3657
3698
 
3699
+ const remoteUpdatePlan = await request(lan, "/api/update/plan", { method: "POST", body: { targets: ["pi"] } });
3700
+ assert.equal(remoteUpdatePlan.status, 403, "update plans must be localhost-only before target resolution");
3701
+ const remoteUpdateApply = await request(lan, "/api/update/apply", { method: "POST", body: { transactionId: "remote", planDigest: "a".repeat(64) } });
3702
+ assert.equal(remoteUpdateApply.status, 403, "update apply must be localhost-only before journal lookup");
3703
+ const remoteUpdateTransaction = await request(lan, "/api/update/transactions/remote");
3704
+ assert.equal(remoteUpdateTransaction.status, 403, "update transaction receipts must be localhost-only");
3705
+ const remoteUpdateRollback = await request(lan, "/api/update/rollback", { method: "POST", body: { transactionId: "remote", planDigest: "a".repeat(64) } });
3706
+ assert.equal(remoteUpdateRollback.status, 403, "update rollback must be localhost-only before pointer mutation");
3707
+
3658
3708
  const remoteWorkflowPolicySave = await request(lan, "/api/workflow-policy", {
3659
3709
  method: "POST",
3660
3710
  body: { policy: workflowPolicyToSave, expectedRevision: savedWorkflowPolicy.body?.data?.revision },
@@ -0,0 +1,24 @@
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 [app, css, html, serviceWorker, packageJson] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "public", "styles.css"), "utf8"),
10
+ readFile(join(root, "public", "index.html"), "utf8"),
11
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
12
+ readFile(join(root, "package.json"), "utf8"),
13
+ ]);
14
+
15
+ assert.match(app, /import \{ installMiddleButtonDragScroll \} from "\.\/middle-button-drag-scroll\.mjs";/, "the app should load the delegated drag-scroll controller");
16
+ assert.match(app, /installMiddleButtonDragScroll\(\{[\s\S]*onDirection: \(\{ target, offsetY \}\)[\s\S]*noteChatUserScrollIntent\(\{ type: "middle-drag", deltaY: offsetY \}\)/, "chat auto-scroll direction should feed the existing follow/pause intent state");
17
+ assert.match(app, /event\?\.type === "middle-drag"\) return event\.deltaY > 0;/, "moving below the press point should be recognized as intent to read later chat output");
18
+ assert.match(css, /body\.middle-button-auto-scrolling,[\s\S]*cursor: all-scroll !important;[\s\S]*user-select: none !important;/, "active automatic scrolling should expose a directional-scroll affordance and suppress accidental selection");
19
+ assert.match(html, /styles\.css\?v=104/, "changed drag-scroll styles should advance the stylesheet revision");
20
+ assert.match(html, /app\.js\?v=120/, "changed drag-scroll wiring should advance the app revision");
21
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81";[\s\S]*"\/middle-button-drag-scroll\.mjs"/, "offline PWA installs should refresh and cache the new controller module");
22
+ assert.match(JSON.parse(packageJson).scripts.check, /node --check public\/middle-button-drag-scroll\.mjs/, "the package check should parse the startup-critical controller module");
23
+
24
+ console.log("middle-button-drag-scroll-static.test.mjs passed");
@@ -0,0 +1,170 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ findMiddleButtonDragScrollTarget,
4
+ installMiddleButtonDragScroll,
5
+ middleButtonAutoScrollVelocity,
6
+ } from "../public/middle-button-drag-scroll.mjs";
7
+
8
+ class FakeEventTarget {
9
+ listeners = new Map();
10
+
11
+ addEventListener(type, listener) {
12
+ const listeners = this.listeners.get(type) || new Set();
13
+ listeners.add(listener);
14
+ this.listeners.set(type, listeners);
15
+ }
16
+
17
+ removeEventListener(type, listener) {
18
+ this.listeners.get(type)?.delete(listener);
19
+ }
20
+
21
+ emit(type, event = {}) {
22
+ for (const listener of [...(this.listeners.get(type) || [])]) listener(event);
23
+ }
24
+ }
25
+
26
+ function frameHarness() {
27
+ let nextId = 1;
28
+ const callbacks = new Map();
29
+ return {
30
+ requestFrame(callback) {
31
+ const id = nextId++;
32
+ callbacks.set(id, callback);
33
+ return id;
34
+ },
35
+ cancelFrame(id) { callbacks.delete(id); },
36
+ run(timestamp) {
37
+ const entry = callbacks.entries().next().value;
38
+ assert.ok(entry, "an animation frame should be pending");
39
+ const [id, callback] = entry;
40
+ callbacks.delete(id);
41
+ callback(timestamp);
42
+ },
43
+ get pending() { return callbacks.size; },
44
+ };
45
+ }
46
+
47
+ function fakeElement({ parentElement = null, scrollHeight = 0, clientHeight = 0, scrollTop = 0, overflowY = "visible", interactive = false } = {}) {
48
+ const style = {
49
+ scrollBehavior: "",
50
+ removeProperty(name) {
51
+ if (name === "scroll-behavior") this.scrollBehavior = "";
52
+ },
53
+ };
54
+ return {
55
+ nodeType: 1,
56
+ parentElement,
57
+ scrollHeight,
58
+ clientHeight,
59
+ scrollTop,
60
+ overflowY,
61
+ interactive,
62
+ style,
63
+ closest() { return this.interactive ? this : null; },
64
+ };
65
+ }
66
+
67
+ function pointerEvent(overrides = {}) {
68
+ return {
69
+ button: 1,
70
+ pointerId: 7,
71
+ pointerType: "mouse",
72
+ clientY: 200,
73
+ defaultPrevented: false,
74
+ preventDefault() { this.defaultPrevented = true; },
75
+ ...overrides,
76
+ };
77
+ }
78
+
79
+ const getStyle = (node) => ({ overflowY: node.overflowY });
80
+
81
+ assert.equal(middleButtonAutoScrollVelocity(10), 0, "the center dead zone should suppress accidental scrolling");
82
+ assert.equal(middleButtonAutoScrollVelocity(20), 120, "downward displacement should produce downward velocity");
83
+ assert.equal(middleButtonAutoScrollVelocity(-20), -120, "upward displacement should produce upward velocity");
84
+ assert.equal(middleButtonAutoScrollVelocity(1000), 1200, "automatic scrolling should have a bounded maximum speed");
85
+
86
+ {
87
+ const outer = fakeElement({ scrollHeight: 1200, clientHeight: 300, overflowY: "auto" });
88
+ const inner = fakeElement({ parentElement: outer, scrollHeight: 800, clientHeight: 200, overflowY: "scroll" });
89
+ const child = fakeElement({ parentElement: inner });
90
+ assert.equal(findMiddleButtonDragScrollTarget(child, { getStyle }), inner, "the nearest vertical scroll surface should win");
91
+ inner.scrollHeight = inner.clientHeight;
92
+ assert.equal(findMiddleButtonDragScrollTarget(child, { getStyle }), outer, "a non-overflowing child should fall back to its scrollable parent");
93
+ }
94
+
95
+ {
96
+ const root = new FakeEventTarget();
97
+ const eventTarget = new FakeEventTarget();
98
+ const frames = frameHarness();
99
+ const activeClasses = new Set();
100
+ const classTarget = { classList: { add: (name) => activeClasses.add(name), remove: (name) => activeClasses.delete(name) } };
101
+ const surface = fakeElement({ scrollHeight: 1200, clientHeight: 300, scrollTop: 500, overflowY: "auto" });
102
+ surface.style.scrollBehavior = "smooth";
103
+ const child = fakeElement({ parentElement: surface });
104
+ const directions = [];
105
+ const controller = installMiddleButtonDragScroll({
106
+ root,
107
+ eventTarget,
108
+ classTarget,
109
+ getStyle,
110
+ requestFrame: (callback) => frames.requestFrame(callback),
111
+ cancelFrame: (frame) => frames.cancelFrame(frame),
112
+ onDirection: (direction) => directions.push(direction),
113
+ });
114
+
115
+ const down = pointerEvent({ target: child });
116
+ root.emit("pointerdown", down);
117
+ assert.equal(down.defaultPrevented, true, "an accepted middle press should suppress native browser autoscroll");
118
+ assert.equal(surface.style.scrollBehavior, "auto", "smooth scrolling should be disabled during automatic movement");
119
+ assert.equal(activeClasses.has("middle-button-auto-scrolling"), true);
120
+ assert.equal(frames.pending, 1);
121
+
122
+ const mouseDown = pointerEvent({ target: child });
123
+ root.emit("mousedown", mouseDown);
124
+ assert.equal(mouseDown.defaultPrevented, true, "the compatibility mouse event should also suppress native browser autoscroll");
125
+
126
+ const moveDown = pointerEvent({ target: child, clientY: 260 });
127
+ eventTarget.emit("pointermove", moveDown);
128
+ assert.equal(moveDown.defaultPrevented, true);
129
+ assert.equal(surface.scrollTop, 500, "pointer movement should select direction without directly grabbing content");
130
+ assert.deepEqual({ target: directions[0].target, offsetY: directions[0].offsetY }, { target: surface, offsetY: 60 });
131
+
132
+ frames.run(0);
133
+ assert.equal(surface.scrollTop, 510, "a displaced pointer should scroll down on the next animation frame");
134
+ frames.run(100);
135
+ assert.equal(surface.scrollTop, 540, "scrolling should continue while the pointer remains displaced and stationary");
136
+
137
+ const moveUp = pointerEvent({ target: child, clientY: 140 });
138
+ eventTarget.emit("pointermove", moveUp);
139
+ assert.equal(directions.at(-1).offsetY, -60);
140
+ frames.run(150);
141
+ assert.equal(surface.scrollTop, 510, "moving above the press point should reverse automatic scrolling upward");
142
+
143
+ eventTarget.emit("pointerup", pointerEvent({ target: child, clientY: 140 }));
144
+ assert.equal(frames.pending, 0, "releasing the middle button should cancel automatic scrolling immediately");
145
+ assert.equal(surface.style.scrollBehavior, "smooth", "the previous inline scroll behavior should be restored");
146
+ assert.equal(activeClasses.has("middle-button-auto-scrolling"), false);
147
+
148
+ controller.destroy();
149
+ assert.equal(root.listeners.get("pointerdown")?.size, 0, "destroy should remove the delegated pointer listener");
150
+ }
151
+
152
+ {
153
+ const root = new FakeEventTarget();
154
+ const eventTarget = new FakeEventTarget();
155
+ const surface = fakeElement({ scrollHeight: 1000, clientHeight: 200, scrollTop: 300, overflowY: "auto" });
156
+ const interactiveChild = fakeElement({ parentElement: surface, interactive: true });
157
+ installMiddleButtonDragScroll({ root, eventTarget, classTarget: null, getStyle });
158
+
159
+ const leftClick = pointerEvent({ target: surface, button: 0 });
160
+ root.emit("pointerdown", leftClick);
161
+ assert.equal(leftClick.defaultPrevented, false, "left-button interactions must remain untouched");
162
+
163
+ const middleClick = pointerEvent({ target: interactiveChild });
164
+ root.emit("pointerdown", middleClick);
165
+ assert.equal(middleClick.defaultPrevented, false, "interactive targets should retain native middle-click behavior");
166
+ eventTarget.emit("pointermove", pointerEvent({ target: interactiveChild, clientY: 260 }));
167
+ assert.equal(surface.scrollTop, 300);
168
+ }
169
+
170
+ console.log("middle-button-drag-scroll.test.mjs passed");
@@ -47,9 +47,9 @@ assert.match(css, /html\[data-tablet-shell="v2"\] \.mobile-shell-nav[\s\S]*?widt
47
47
  assert.match(css, /html\[data-tablet-shell="v2"\] \.mobile-shell-surface[\s\S]*?width: min\(30rem, 72vw\)/, "tablet inspector must be a bounded right-side sheet");
48
48
  assert.match(css, /html\[data-tablet-shell="v2"\] \.file-viewer-pane[\s\S]*?position: fixed[\s\S]*?inset: 0/, "tablet files must default to full-screen replacement");
49
49
  assert.match(css, /and \(pointer: coarse\)[\s\S]*?min-height: 44px/, "coarse tablet pointers must retain the 44px target floor");
50
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v74"/, "continuity/tablet assets need a coherent cache identity");
51
- assert.match(html, /styles\.css\?v=98/, "tablet CSS must have a coherent HTML revision");
52
- assert.match(html, /app\.js\?v=113/, "continuity app logic must have a coherent HTML revision");
50
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "continuity/tablet assets need a coherent cache identity");
51
+ assert.match(html, /styles\.css\?v=104/, "tablet CSS must have a coherent HTML revision");
52
+ assert.match(html, /app\.js\?v=120/, "continuity app logic must have a coherent HTML revision");
53
53
  assert.match(readme, /tabletShell=v2/, "tablet preview and rollback must be documented");
54
54
 
55
55
  console.log("mobile-continuity-tablet-static.test.mjs passed");
@@ -37,9 +37,9 @@ assert.match(pkg.scripts.check, /node --check public\/transcript-renderer\.mjs/,
37
37
  assert.match(server, /STATIC_PUBLIC_FILE_EXTENSIONS[\s\S]*"\.mjs"/, "the server must serve typed startup modules from the public asset boundary");
38
38
  assert.match(serviceWorker, /"\/mobile-shell-state\.mjs"/, "the PWA shell must cache the new startup module");
39
39
  assert.match(serviceWorker, /"\/transcript-renderer\.mjs"/, "the PWA shell must cache the transcript startup module");
40
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v74"/, "the cache identity must change with the startup graph");
41
- assert.match(html, /styles\.css\?v=98/, "the stylesheet revision must change with mobile/tablet CSS fixes");
42
- assert.match(html, /app\.js\?v=113/, "the app revision must change with continuity/tablet wiring");
40
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "the cache identity must change with the startup graph");
41
+ assert.match(html, /styles\.css\?v=104/, "the stylesheet revision must change with mobile/tablet CSS fixes");
42
+ assert.match(html, /app\.js\?v=120/, "the app revision must change with continuity/tablet wiring");
43
43
  assert.match(serviceWorker, /const APP_SHELL_NETWORK_TIMEOUT_MS = 8_000;[\s\S]*?event\.waitUntil\([\s\S]*?cache\.put\(request, response\.clone\(\)\)[\s\S]*?return networkResponse;/, "runtime cache writes must extend the event lifetime without blocking bounded network responses");
44
44
  assert.match(serviceWorker, /MOBILE_NAVIGATION_MESSAGE_TYPE = "pi-webui:navigate:v1"/, "the service worker must use a versioned active-client navigation message");
45
45
  assert.match(serviceWorker, /client\.postMessage\(\{ type: MOBILE_NAVIGATION_MESSAGE_TYPE, target \}\)/, "existing clients must receive only a validated target message");
@@ -57,7 +57,7 @@ assert.match(server, /requestId was already used for a different prompt/, "reque
57
57
  assert.match(server, /runId: null/, "tab activity must expose an opaque parent-run field");
58
58
  assert.match(server, /activity\.runId = randomUUID\(\)/, "parent-run IDs must be server-issued opaque values");
59
59
  assert.match(server, /function markTabFailed\([\s\S]*?activity\.status = "failed"[\s\S]*?activity\.completionSerial/, "failed parent turns must be represented distinctly from successful completion");
60
- assert.match(server, /SSE_BACKPRESSURE_MAX_PENDING_BYTES = 512 \* 1024/, "SSE backpressure buffering must remain explicitly bounded");
60
+ assert.match(server, /SSE_BACKPRESSURE_MAX_PENDING_BYTES = 4 \* 1024 \* 1024/, "SSE backpressure buffering must remain explicitly bounded above the healthy fixture burst");
61
61
  assert.match(server, /res\.once\("drain", \(\) => flushSseClient\(client\)\)/, "healthy SSE clients must resume after transient write backpressure");
62
62
  assert.match(server, /client\.tab\?\.sseClients\?\.delete\(client\)/, "eviction must remove only the slow client");
63
63
  assert.match(server, /client\.res\?\.end\(\)/, "slow-client eviction must finish chunked SSE responses gracefully");
@@ -60,6 +60,6 @@ assert.match(css, /data-mobile-presentation="essential"/, "Essential presentatio
60
60
  assert.match(css, /html\[data-mobile-shell="v2"\] body\.mobile-keyboard-open \.widget-area,[\s\S]*?\.composer-actions-button \{ display: block !important; \}/, "v2 keyboard mode must keep run widgets and the actions entry available");
61
61
  assert.match(css, /@media \(prefers-reduced-motion: reduce\)/, "reduced-motion behavior is required");
62
62
  assert.match(css, /@media \(forced-colors: active\)/, "forced-color affordances are required");
63
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v74"/, "browser asset changes need a coherent cache tuple");
63
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "browser asset changes need a coherent cache tuple");
64
64
 
65
65
  console.log("mobile-phone-experience-static.test.mjs passed");
@@ -10,7 +10,7 @@ const [pkgRaw, html, css, app, server, extension, readme, startScript, manifestR
10
10
  readFile(join(root, "public", "index.html"), "utf8"),
11
11
  readFile(join(root, "public", "styles.css"), "utf8"),
12
12
  readFile(join(root, "public", "app.js"), "utf8"),
13
- readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
13
+ readFile(join(root, "bin", "pi-webui.mjs"), "utf8").then((value) => value.replace(/\r\n/g, "\n")),
14
14
  readFile(join(root, "index.ts"), "utf8"),
15
15
  readFile(join(root, "README.md"), "utf8"),
16
16
  readFile(join(root, "dev", "scripts", "start-webui.sh"), "utf8"),
@@ -268,6 +268,10 @@ assert.match(css, /@media\s*\([^)]*max-width[^)]*\)\s*\{[\s\S]*?\.subagent-termi
268
268
  assert.match(readme, /exactly six telemetry cards: PI, measured token speed, context, model, effort, and input\/output tokens from a bounded recent session scan; unavailable or legacy evidence remains `—` or `unknown` rather than an estimate/, "README should document each subagent telemetry card, bounded scan scope, and honest unknown behavior");
269
269
  assert.doesNotMatch(html, /id="subagentOverlayDialog"/, "subagent output should not use a blocking modal dialog");
270
270
  assert.match(html, /data-side-panel-section="session"[\s\S]*data-side-panel-section="subagents"[\s\S]*data-side-panel-section="queue"/, "Subagents should appear between Session and Queue in the side panel");
271
+ assert.match(html, /data-side-panel-section="sampling"[\s\S]*class="side-panel-section-label">Sampling parameters<\/span>[\s\S]*id="samplingParametersSupport"[\s\S]*id="samplingParametersControls"[\s\S]*id="samplingParametersPreserved"[\s\S]*id="applySamplingParametersButton"[\s\S]*id="resetSamplingParametersButton"[\s\S]*id="samplingParametersStatus"/, "Sampling parameters should be a labelled side-panel section with native controls, hidden-key preservation status, apply/reset actions, and live status");
272
+ assert.match(app, /sampling: \["Sampling parameters", \["sidePanelSectionSampling"\]\]/, "mobile More settings should reuse the canonical native sampling controls");
273
+ assert.doesNotMatch(html, /id="samplingParametersInput"|Session override \(JSON object\)/, "mobile reuse should not expose the removed raw JSON editor");
274
+ assert.match(css, /\.sampling-parameters \{[\s\S]*container: sampling-parameters \/ inline-size;[\s\S]*@container sampling-parameters \(max-width: 22rem\)[\s\S]*\.sampling-parameter-editor,[\s\S]*grid-template-columns: minmax\(0, 1fr\)/, "native sampling controls should collapse to one column in narrow side-panel/mobile hosts");
271
275
  assert.match(html, /data-side-panel-section="queue"[\s\S]*id="createPromptListButton"[\s\S]*>Create prompt list<\/button>/, "Queue section should expose prompt-list creation");
272
276
  assert.match(html, /id="loadPromptListButton"[\s\S]*>Load List<\/button>[\s\S]*id="runLoadedPromptListButton"[^>]*disabled[^>]*>Run<\/button>/, "Queue section should expose load and run controls for saved prompt lists");
273
277
  assert.match(html, /id="promptListDialog"[\s\S]*id="promptListAddPromptButton"[\s\S]*\+ Add follow-up prompt/, "prompt-list dialog should add follow-up prompt rows");
@@ -352,7 +356,7 @@ assert.ok(
352
356
  Math.min(optionsReloadIndex, optionsNameIndex) < optionsRemoteIndex && optionsRemoteIndex < Math.max(optionsReloadIndex, optionsNameIndex),
353
357
  "Open Remote should render between Reload Pi and Name Session",
354
358
  );
355
- assert.match(html, /id="optionsConversationModeButton"[^>]*data-command="\/talk"[^>]*hidden[\s\S]*?<span>Start Conversation<\/span>/, "Options menu should include the feature-gated Natural Conversation toggle");
359
+ assert.match(html, /id="optionsConversationModeButton"[^>]*data-command="\/talk"[^>]*hidden[\s\S]*?<span>Start Natural Conversation<\/span>/, "Options menu should include the feature-gated Natural Conversation toggle");
356
360
  assert.match(html, /id="conversationModeChip" class="composer-conversation-mode-chip"[\s\S]*hidden>Voice: off<\/button>/, "composer should expose a hidden-until-active conversation status chip");
357
361
  const workflowModeButtonHtml = html.match(/<button\s+id="workflowModeButton"[\s\S]*?<\/button>/)?.[0] || "";
358
362
  const workflowOverlayOpenButtonHtml = html.match(/<button\s+id="workflowOverlayOpenButton"[\s\S]*?<\/button>/)?.[0] || "";
@@ -838,7 +842,7 @@ assert.match(app, /const PI_WEBUI_NPM_URL = "https:\/\/www\.npmjs\.com\/package\
838
842
  assert.match(app, /async function confirmOpenWebuiNpmPage\(\)[\s\S]*appConfirm\([\s\S]*confirmLabel: "Open npm"[\s\S]*openWebuiNpmPageInNewTab\(\)/, "Web UI version button should ask before opening npm in a new tab");
839
843
  assert.match(app, /function refreshWebuiVersion\(\)[\s\S]*api\("\/api\/health", \{ scoped: false \}\)[\s\S]*setWebuiVersion\(health\.webuiVersion\)[\s\S]*setPiVersion\(health\.piVersion\)[\s\S]*setWebuiDevServer\(isWebuiDevMetadata\(health\)\)/, "frontend should load Pi version, Web UI version, and dev mode from health metadata");
840
844
  assert.match(app, /case "webui_connected":[\s\S]*setWebuiVersion\(event\.version\)[\s\S]*setPiVersion\(event\.piVersion\)[\s\S]*setWebuiDevServer\(isWebuiDevMetadata\(event\)\)/, "frontend should refresh Pi version, Web UI version, and dev mode from reconnect events");
841
- assert.match(server, /url\.pathname === "\/api\/pi-release-notes"[\s\S]*installedPiReleaseNotes\(\)/, "server should expose the installed Pi release notes endpoint");
845
+ assert.match(server, /url\.pathname === "\/api\/pi-release-notes"[\s\S]*piReleaseNotes\(\)/, "server should expose release notes for the available Pi update or the installed fallback");
842
846
  assert.match(server, /PI_RELEASES_PAGE_BASE_URL = "https:\/\/github\.com\/earendil-works\/pi\/releases\/tag"/, "release-note links should target the official Pi GitHub release page");
843
847
  assert.match(server, /const webuiDevServer = isTruthyEnv\(process\.env\.PI_WEBUI_DEV\) \|\| isSourceCheckout\(packageRoot\)/, "server should derive dev mode from PI_WEBUI_DEV or a source checkout");
844
848
  assert.match(server, /webuiDev: webuiDevServer,[\s\S]*webuiMode: webuiDevServer \? "dev" : "production"/, "server status should expose Web UI dev mode");
@@ -849,8 +853,8 @@ assert.match(server, /options\.cwd = await validateStartupCwd\(options\.cwd\)/,
849
853
  assert.match(server, /cwdExplicit: false/, "server should track whether startup cwd was explicitly requested");
850
854
  assert.match(server, /return options\.cwdExplicit \? \[await createTab\(\)\] : \[\]/, "server should wait for UI cwd selection when no --cwd is supplied");
851
855
  assert.match(server, /async function resolvedPiCliScript\(\)[\s\S]*require\.resolve\.paths\(PI_CODING_AGENT_PACKAGE\)[\s\S]*nodeModulesRoot[\s\S]*dist[\s\S]*cli\.js/, "server should resolve the bundled Pi CLI through Node resolution roots so hoisted global installs can spawn RPC tabs");
852
- assert.match(server, /const bundledCli = await resolvedPiCliScript\(\)/, "standalone server should prefer the resolved Pi CLI script before falling back to PATH pi");
853
- assert.match(server, /if \(options\.piBinExplicit\) \{\n\s+resolveCommand = \(args\) => resolvePiCommand\(args\)/, "explicit --pi JavaScript launchers should also work for capability checks and update commands");
856
+ assert.match(server, /canonicalPiRuntimeIdentity[\s\S]*bundledCli: await resolvedPiCliScript\(\)/, "standalone server should use the canonical resolver with the bundled Pi CLI before PATH pi");
857
+ assert.match(server, /resolveCanonicalPiRuntime\([\s\S]*explicitCommand: options\.piBinExplicit \? options\.piBin : ""[\s\S]*bundledCli/, "updates should resolve the same canonical explicit or bundled Pi identity used by tabs");
854
858
  assert.match(app, /serverActionSelect\.addEventListener\("change", updateServerActionButton\)/, "Server action dropdown should control the guarded run button");
855
859
  assert.match(app, /runServerActionButton\.addEventListener\("click"[\s\S]*runSelectedServerAction/, "Server action run button should execute the selected action");
856
860
  assert.match(app, /api\("\/api\/restart", \{ method: "POST", scoped: false \}\)/, "Restart Server action should call the unscoped restart endpoint");
@@ -858,18 +862,16 @@ assert.match(app, /setServerActionStatus\(message, "warn"\);\n\s+setServerRestar
858
862
  assert.match(app, /const showOfflinePanel = backendOffline && !serverRestartInProgress/, "intentional restart should suppress the generic offline shell while reconnecting");
859
863
  assert.match(app, /api\("\/api\/shutdown", \{ method: "POST", scoped: false \}\)/, "Stop Server action should call the unscoped shutdown endpoint");
860
864
  assert.match(server, /url\.pathname === "\/api\/restart" && req\.method === "POST"/, "server should expose restart endpoint");
861
- assert.match(server, /PI_WEBUI_RESTORE_TABS: JSON\.stringify\(restorableTabs \|\| \[\]\)/, "server restart should preserve restorable tab metadata");
865
+ assert.match(server, /PI_WEBUI_RESTORE_FILE: restore\.file/, "server restart should pass tab metadata through a private read-once restore file");
862
866
  assert.match(server, /if \(webuiDevServer\) env\.PI_WEBUI_DEV = "1";/, "server restart should explicitly preserve dev mode");
863
- assert.match(server, /async function piUpdateCommandSupportsAll\(command\)[\s\S]*runCommand\(command\.command, command\.args \|\| \[\][\s\S]*piUpdateHelpSupportsAll/, "server should check the selected Pi executable's update help");
864
- assert.match(server, /const supportsAll = all && await piUpdateCommandSupportsAll\(await resolveCommand\(\["update", "--help"\]\)\)[\s\S]*piUpdateCommandSteps\(\{ all, supportsAll \}\)/, "server should prefer --all only when the capability check succeeds");
865
- assert.match(server, /async function resolveUpdateTasks\(\{ all = false \} = \{\}\)[\s\S]*const piTasks = await resolvePiUpdateCommands\(\{ all \}\)[\s\S]*if \(!all\) return uniqueUpdateTasks\(piTasks\)[\s\S]*currentWebuiPackageUpdateTask\(npmRuntime\)[\s\S]*agentPackageRootUpdateTask\(npmRuntime\)[\s\S]*projectPackageRootUpdateTasks\(npmRuntime\)[\s\S]*npmGlobalPackageRootUpdateTask\(npmRuntime\)[\s\S]*bunGlobalPackageRootUpdateTask\(\)/, "server all-update should run the selected Pi plan plus detected local/global Pi package root tasks with install-aware npm resolution");
866
- assert.match(server, /const OPTIONAL_FEATURE_PACKAGE_NAMES = new Set\(OPTIONAL_FEATURE_PACKAGES\.values\(\)\)[\s\S]*const UPDATE_PACKAGE_NAMES = \[\.\.\.CORE_UPDATE_PACKAGE_NAMES\]\.sort\(\)/, "direct package-root updates should target core packages while retaining the Optional Feature exclusion set");
867
- assert.match(server, /function isWebuiOrPiPackageName\(packageName\)[\s\S]*OPTIONAL_FEATURE_PACKAGE_NAMES\.has\(name\)\) return false/, "direct npm and Bun update discovery should leave Optional Features under Pi management");
868
- assert.match(app, /const commandText = all \? '"pi update --all" when supported, otherwise "pi update --self" followed by "pi update --extensions"' : '"pi update --self"'/, "frontend update confirmation should describe capability selection and fallback");
869
- assert.match(app, /configured packages including Optional Features, and detected core Pi\/Web UI package roots/, "frontend all-update confirmation should distinguish Pi-managed Optional Features from direct core-root updates");
870
- assert.match(app, /api\(all \? "\/api\/update\?all=1" : "\/api\/update"/, "frontend all update should call the explicit all-mode endpoint");
871
- assert.match(html, /<option value="update-all">Update Pi \+ Packages &amp; Restart<\/option>/, "side panel should expose package-inclusive updates as a separate server action");
872
- assert.match(readme, /first checks the selected Pi executable's `pi update --help`[\s\S]*uses `pi update --all` when advertised[\s\S]*otherwise falls back/, "README should document the checked preferred and fallback update modes");
867
+ assert.match(server, /url\.pathname === "\/api\/update\/plan"[\s\S]*createServerOwnedUpdatePlan/, "server should expose exact server-owned update planning");
868
+ assert.match(server, /url\.pathname === "\/api\/update\/apply"[\s\S]*validateUpdateApplyRequest[\s\S]*applyServerOwnedUpdate/, "server should apply only a transaction id and plan digest");
869
+ assert.match(server, /Legacy update mutation is disabled/, "divergent legacy update mutation routes should fail closed");
870
+ assert.doesNotMatch(server, /function resolveUpdateTasks|function projectPackageRootUpdateTasks|function npmGlobalPackageRootUpdateTask|function bunGlobalPackageRootUpdateTask/, "broad heuristic package-root mutation should be removed");
871
+ assert.match(app, /Exact immutable plan digest:[\s\S]*persisted exact-target plan[\s\S]*will not re-resolve latest or scan package roots/, "frontend confirmation should bind users to the exact plan digest and fail-closed scope");
872
+ assert.match(app, /api\("\/api\/update\/apply", \{ method: "POST", body: \{ transactionId: plan\.transactionId, planDigest: plan\.digest \}/, "frontend should apply only the confirmed transaction and digest");
873
+ assert.match(html, /<option value="update-all">/, "side panel should retain a combined update action while routing through exact plans");
874
+ assert.match(readme, /exact-target plan|plan digest/i, "README should document exact update plans");
873
875
  assert.match(server, /async function closeNetworkAccess\(\)/, "server should expose a local-only rebind helper for closing network access");
874
876
  assert.match(server, /url\.pathname === "\/api\/network\/close" && req\.method === "POST"/, "server should route network close requests");
875
877
  assert.match(server, /server\.closeAllConnections\?\.\(\)/, "network rebind should force-close long-lived clients so close-to-localhost can complete");
@@ -884,7 +886,7 @@ assert.match(app, /function setOptionsMenuOpen\(open\)[\s\S]*scheduleMobileDropd
884
886
  assert.match(app, /function focusPromptInput\(\{ defer = false \} = \{\}\)/, "frontend should focus the prompt composer programmatically after tab/app startup");
885
887
  assert.match(app, /async function switchTab\(tabId\)[\s\S]*?restoreActiveDraft\(\);\n\s+focusPromptInput\(\{ defer: true \}\);/, "switching to a newly opened tab should focus the prompt input immediately");
886
888
  assert.match(app, /async function initializeTabs\(\)[\s\S]*?restoreActiveDraft\(\);[\s\S]*if \(!loadedTabs\.length\)[\s\S]*focusPromptInput\(\{ defer: true \}\);/, "starting the Web UI should prompt for cwd when needed and focus active tabs");
887
- assert.match(app, /resizePromptInput\(\);\nrestoreDurableUiLayoutPendingJournal\(\);\nrestoreSidePanelWidthPreference\(\);\nrestoreFileViewerWidthPreference\(\);\nfocusPromptInput\(\{ defer: true \}\);\nrestoreStoredSkillUsage\(\);\nrestoreBusyPromptBehaviorSetting\(\);\nupdateComposerModeButtons\(\);/, "startup should restore resizable panel preferences, request prompt focus, and restore skill tags before waiting for tab state refreshes");
889
+ assert.match(app, /resizePromptInput\(\);\nclearRemovedSidePanelSectionHeightState\(\);\nrestoreDurableUiLayoutPendingJournal\(\);\nrestoreSidePanelWidthPreference\(\);\nrestoreFileViewerWidthPreference\(\);\nfocusPromptInput\(\{ defer: true \}\);\nrestoreStoredSkillUsage\(\);\nrestoreBusyPromptBehaviorSetting\(\);\nupdateComposerModeButtons\(\);/, "startup should clear retired section-height state, restore resizable panel preferences, request prompt focus, and restore skill tags before waiting for tab state refreshes");
888
890
  assert.match(app, /elements\.promptInput\.addEventListener\("focus", \(\) => \{\n\s+syncMobileChatToBottomForInput\(\);/, "focusing mobile input should scroll output to bottom");
889
891
  assert.match(app, /navigator\.serviceWorker\.register\("\/service-worker\.js"\)/, "PWA service worker should be registered by the app");
890
892
  assert.match(app, /function serverStartCommandText\(\)[\s\S]*return `pi-webui\$\{currentPortArg\(\)\}`/, "PWA/offline shell should build a pathless pi-webui recovery command");
@@ -1363,7 +1365,7 @@ assert.match(app, /if \(response\.data\?\.level\) requestGitFooterWebuiPayload\(
1363
1365
  assert.match(app, /Loading git footer status…/, "missing git footer payload should show a loading state before declaring the extension unavailable");
1364
1366
  assert.match(app, /GIT_FOOTER_WEBUI_PAYLOAD_CACHE_KEY/, "git footer payloads should be cached across Web UI reloads");
1365
1367
  assert.match(app, /function setOptionalFeatureDisabled\(featureId, disabled\)[\s\S]*clearGitFooterWebuiPayloadCache\(\)/, "changing the git footer feature toggle should invalidate the cached footer payload");
1366
- const workspaceInfoSource = server.match(/async function getWorkspaceInfo[\s\S]*?\n}\n\nlet activeGitWorkflowProcess/)?.[0] || "";
1368
+ const workspaceInfoSource = server.match(/async function getWorkspaceInfo[\s\S]*?\r?\n}\r?\n\r?\nlet activeGitWorkflowProcess/)?.[0] || "";
1367
1369
  assert.ok(workspaceInfoSource, "server workspace info source should be inspectable");
1368
1370
  assert.doesNotMatch(workspaceInfoSource, /runCommand\("git"|branchStatus|isRepo/, "Web UI workspace endpoint should not duplicate git footer status collection");
1369
1371
  assert.match(app, /function renderOptionalFeatureDependentDisplays\(\)[\s\S]*renderOptionalFeatureControls\(\);[\s\S]*renderThemeSelect\(\);[\s\S]*renderWidgets\(\);[\s\S]*renderStatus\(\);[\s\S]*renderCommands\(\);[\s\S]*renderAllMessages\(\{ preserveScroll: true, forceRebuild: true \}\);[\s\S]*if \(streamRawText\) renderStreamingAssistantText\(\);/, "optional feature toggles should immediately refresh visible controls, commands, transcript, and live stream displays");
@@ -2081,8 +2083,8 @@ assert.match(server, /type: "webui_extension_ui_resolved"[\s\S]*?pendingExtensio
2081
2083
  assert.match(server, /command\.type === "abort"[\s\S]*?cancelPendingExtensionUiRequests\(tab\)/, "abort should cancel hidden pending extension UI requests");
2082
2084
  assert.match(server, /type: "webui_extension_ui_cancelled"/, "server should notify browsers when pending extension UI requests are cancelled");
2083
2085
  assert.match(server, /async function handleNativeSlashCommand\(tab, body, req\)/, "server should intercept supported native slash commands with request context for security guards");
2084
- assert.match(server, /const restoreTabs = readRestoreTabsFromEnv\(\)/, "server should accept restart tab restore descriptors from the launcher environment");
2085
- assert.match(server, /delete process\.env\.PI_WEBUI_RESTORE_TABS/, "server should avoid leaking restore descriptors into spawned Pi RPC processes");
2086
+ assert.match(server, /const restoreTabs = await readRestoreTabsFromEnv\(\)/, "server should accept private restart tab restore descriptors from the launcher environment");
2087
+ assert.match(server, /delete process\.env\.PI_WEBUI_RESTORE_FILE[\s\S]*delete process\.env\.PI_WEBUI_RESTORE_TABS/, "server should avoid leaking private or obsolete restore descriptors into spawned Pi RPC processes");
2086
2088
  assert.match(server, /if \(sessionFile && !options\.noSession\) piArgs\.push\("--session", sessionFile\)/, "restored tabs should resume previous session files");
2087
2089
  assert.doesNotMatch(server, /args\.push\("--name"/, "Web UI tab titles should not be forwarded as Pi CLI --name flags because older bundled Pi CLIs reject them");
2088
2090
  assert.match(server, /const closedRestorableTabs = \[\]/, "server should track recently closed tabs separately from restart restore descriptors");
@@ -2104,7 +2106,7 @@ assert.match(extension, /const openTabSources: unknown\[\] = \[\]/, "launcher sh
2104
2106
  assert.match(extension, /const detailedTabs = statusData\?\.tabs;\n\s+if \(Array\.isArray\(detailedTabs\)\) openTabSources\.push\(detailedTabs\)/, "launcher should prefer detailed open tabs over restorableTabs that may include closed tabs");
2105
2107
  assert.match(extension, /if \(openTabSources\.length > 0\) return mergeRestorableTabsFromStatusSources\(openTabSources, options\)/, "launcher should restore only open tabs when open tab lists are available");
2106
2108
  assert.match(extension, /return mergeRestorableTabsFromStatusSources\(\[statusData\?\.restorableTabs, existing\.restorableTabs\], options\)/, "launcher should use restorableTabs only as a legacy fallback");
2107
- assert.match(extension, /env\.PI_WEBUI_RESTORE_TABS = JSON\.stringify\(restoreTabs\)/, "launcher should pass restorable tabs to the new detached server");
2109
+ assert.match(extension, /env\.PI_WEBUI_RESTORE_FILE = \(await createRestoreFile\(agentDir, restoreTabs\)\)\.file/, "launcher should pass restorable tabs through a private read-once file");
2108
2110
  assert.match(extension, /pi\.registerCommand\("webui-start"/, "extension should expose the canonical /webui-start command");
2109
2111
  assert.match(extension, /pi\.registerCommand\("webui-tree-navigate"/, "extension should expose the internal Web UI tree navigation command");
2110
2112
  assert.match(extension, /ctx\.navigateTree\(payload\.entryId/, "internal Web UI tree command should call the native session tree navigation API");
@@ -68,7 +68,7 @@ assert.match(server, /STATIC_PUBLIC_FILE_EXTENSIONS[\s\S]*"\.mjs"/, "the server
68
68
  assert.match(serviceWorker, /"\/issue-wizard-state\.mjs"/, "the PWA shell must keep caching the pure wizard module");
69
69
  assert.match(serviceWorker, /"\/issue-bot-client\.mjs"/, "the PWA shell must cache the browser client module");
70
70
  // Intent preserved: changing the public startup graph advances the PWA cache identity.
71
- assert.match(serviceWorker, /pi-webui-pwa-v74/, "the PWA cache name must change with browser wiring updates");
71
+ assert.match(serviceWorker, /pi-webui-pwa-v81/, "the PWA cache name must change with browser wiring updates");
72
72
  assert.match(packageJson, /node --check public\/issue-wizard-state\.mjs/, "the package check must keep syntax-checking the pure wizard module");
73
73
  assert.match(packageJson, /node --check public\/issue-bot-client\.mjs/, "the package check must syntax-check the browser client module");
74
74