@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
@@ -33,6 +33,7 @@ assert.match(surfaceSource, /safely excluded[\s\S]*Copy recommended fix[\s\S]*Re
33
33
  assert.match(surfaceSource, /started safely without optional companions[\s\S]*Recheck/, "degraded startup should remain core-safe and recheckable");
34
34
  assert.match(surfaceSource, /Migrating optional features[\s\S]*Retry failed[\s\S]*Copy commands[\s\S]*Restart tab/, "progress and recovery should expose the required sequential/retry/copy/deferred-restart actions");
35
35
  assert.match(surfaceSource, /if \(optionalFeatureRestartNotice\.restartDeferred\)[\s\S]*Restart tab[\s\S]*else[\s\S]*Dismiss/, "a deferred restart action must remain persistent until restart succeeds");
36
+ assert.match(surfaceSource, /optionalFeatureMigrationCompletionIsDismissed\(snapshot\)[\s\S]*surface\.hidden = true[\s\S]*phase === "complete"[\s\S]*dismissOptionalFeatureMigrationCompletion/, "dismissing a completed migration should hide the complete surface, not only its restart notice");
36
37
  assert.match(surfaceSource, /setAttribute\("role", "alert"\)/, "only conflict/partial terminal feedback should add alert semantics");
37
38
  assert.match(surfaceSource, /optional-feature-migration-completion-summary[\s\S]*card\.focus/, "completion summary should receive focus once");
38
39
  assert.doesNotMatch(surfaceSource, /percent|% complete/i, "package-manager progress must not fabricate percentages");
@@ -56,13 +57,16 @@ assert.match(eventSource, /webui_optional_feature_migration[\s\S]*applyOptionalF
56
57
  assert.match(eventSource, /webui_optional_feature_restart_completed[\s\S]*webui_optional_feature_restart_deferred/, "SSE restart events should be consumed");
57
58
  const progressRecoverySource = sourceBetween("function applyOptionalFeatureProgressStates", "function refreshOptionalFeatureMigrationElapsedText");
58
59
  assert.match(progressRecoverySource, /progress\.restartDeferred === true[\s\S]*optionalFeatureRestartNotice/, "cached progress must rehydrate the deferred Restart action after a full browser reload");
59
- assert.match(progressRecoverySource, /progress\.autoRestarted === true[\s\S]*optionalFeatureRestartNotice/, "cached progress should rehydrate the completed restart notice");
60
+ assert.match(progressRecoverySource, /progress\.autoRestarted === true && !optionalFeatureMigrationCompletionIsDismissed\(snapshot\)[\s\S]*optionalFeatureRestartNotice/, "cached progress should rehydrate an undismissed completed restart notice");
61
+ assert.match(progressRecoverySource, /optionalFeatureMigrationCompletionIsDismissed\(snapshot\)[\s\S]*optionalFeatureRestartNotice = null/, "cached progress must not resurrect a dismissed completion notice");
62
+ assert.match(app, /OPTIONAL_FEATURE_MIGRATION_DISMISS_STORAGE_KEY[\s\S]*storedDismissedOptionalFeatureMigrationKey[\s\S]*localStorage\.setItem\(OPTIONAL_FEATURE_MIGRATION_DISMISS_STORAGE_KEY, key\)/, "completion dismissal should survive reloads in browser storage");
60
63
  assert.match(app, /source\.onopen[\s\S]*refreshOptionalFeaturePackageStatuses\(\)/, "event-stream reconnect should recover the current cached server snapshot");
61
- const timerSource = sourceBetween("function refreshOptionalFeatureMigrationElapsedText", "function optionalFeatureMigrationAction");
62
- assert.doesNotMatch(timerSource, /renderOptionalFeatureMigrationSurface\(\)/, "elapsed ticks must not replace and re-announce the entire live region");
63
- assert.match(timerSource, /querySelector\("\.optional-feature-migration-detail"\)/, "elapsed ticks should update only the detail node");
64
+ const elapsedTimerSource = sourceBetween("function refreshOptionalFeatureMigrationElapsedText", "function clearOptionalFeatureReadyDismissTimer");
65
+ const dismissalTimerSource = sourceBetween("function clearOptionalFeatureReadyDismissTimer", "function optionalFeatureMigrationAction");
66
+ assert.doesNotMatch(elapsedTimerSource, /renderOptionalFeatureMigrationSurface\(\)/, "elapsed ticks must not replace and re-announce the entire live region");
67
+ assert.match(elapsedTimerSource, /querySelector\("\.optional-feature-migration-detail"\)/, "elapsed ticks should update only the detail node");
64
68
  assert.match(app, /const OPTIONAL_FEATURE_READY_AUTO_DISMISS_MS = 5_000;/, "a successful startup audit should remain readable briefly before dismissal");
65
- assert.match(timerSource, /scheduleOptionalFeatureReadyDismiss[\s\S]*setTimeout[\s\S]*optionalFeatureReadyDismissKey\(\) !== key \|\| optionalFeatureRestartNotice[\s\S]*surface\.hidden = true/, "ready feedback should auto-dismiss only while the same ready snapshot remains non-actionable");
69
+ assert.match(dismissalTimerSource, /scheduleOptionalFeatureReadyDismiss[\s\S]*setTimeout[\s\S]*optionalFeatureReadyDismissKey\(\) !== key \|\| optionalFeatureRestartNotice[\s\S]*surface\.hidden = true/, "ready feedback should auto-dismiss only while the same ready snapshot remains non-actionable");
66
70
  assert.match(surfaceSource, /readyCanAutoDismiss[\s\S]*scheduleOptionalFeatureReadyDismiss\(readyCanAutoDismiss \? readyDismissKey : ""\)/, "rendering should schedule dismissal only for non-actionable ready feedback");
67
71
 
68
72
  assert.match(css, /\.optional-feature-migration-surface[\s\S]*\.optional-feature-migration-dialog[\s\S]*@media \(max-width: 34rem\)/, "migration surfaces should have desktop and responsive styling");
@@ -22,6 +22,11 @@ assert.match(
22
22
  /const UI_LAYOUT_FIELDS = \["sidePanel", "composerActions", "footerScopedModelOrder", "terminalTabs", "fileViewerWidth"\];/,
23
23
  "every approved arrangement surface should be a durable layout field",
24
24
  );
25
+ assert.match(
26
+ app,
27
+ /const UI_LAYOUT_SIDE_PANEL_FIELDS = \["sectionOrder", "collapsedSectionIds", "hiddenSectionIds", "collapsed"\];/,
28
+ "Control Deck durable layout should contain only order, visibility, and collapse state",
29
+ );
25
30
  for (const [constant, value] of [
26
31
  ["UI_LAYOUT_ID_MAX_LENGTH", "256"],
27
32
  ["UI_LAYOUT_TITLE_MAX_LENGTH", "160"],
@@ -193,6 +198,11 @@ assert.match(
193
198
  /function restoreSidePanelState\(\)[\s\S]*setSidePanelCollapsed\(stored \?\? false, \{ persist: false \}\)/,
194
199
  "passive Control Deck restoration must not echo stale cache back to the server",
195
200
  );
201
+ assert.doesNotMatch(
202
+ app,
203
+ /initializeSidePanelSectionResizing|persistSidePanelSectionHeight|beginSidePanelSectionResize|sidePanelSectionResizeState|data-side-panel-section-resize/,
204
+ "Control Deck section-height adjustment and persistence should be absent",
205
+ );
196
206
 
197
207
  // --- Composer order and grid stay one atomic logical update ----------------
198
208
 
@@ -261,7 +271,8 @@ assert.match(
261
271
 
262
272
  // --- Coherent browser asset revisions --------------------------------------
263
273
 
264
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v74"/, "changed browser assets should advance the PWA cache identity");
265
- assert.match(html, /data-app-src="\/app\.js\?v=113"/, "the boot loader should request the updated app module revision");
274
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "changed browser assets should advance the PWA cache identity");
275
+ assert.match(html, /styles\.css\?v=104/, "the page should request the updated layout stylesheet revision");
276
+ assert.match(html, /data-app-src="\/app\.js\?v=120"/, "the boot loader should request the updated app module revision");
266
277
 
267
278
  console.log("persistent-ui-layout-static.test.mjs passed");
@@ -504,8 +504,8 @@ assert.match(css, /@media \(max-width: 720px\), \(max-device-width: 720px\), \(p
504
504
  assert.match(css, /\.questionnaire-options button\s*\{\s*min-height:\s*3\.35rem/, "mobile questionnaire targets must exceed the 44px floor");
505
505
  assert.match(css, /@media \(prefers-reduced-motion: reduce\)\s*\{[\s\S]*?\*, \*::before, \*::after[\s\S]*?transition-duration:\s*1ms !important/, "global reduced-motion rules must cover questionnaire transitions");
506
506
 
507
- assert.match(html, /styles\.css\?v=98/, "questionnaire CSS needs the current stylesheet revision");
508
- assert.match(html, /app\.js\?v=113/, "questionnaire behavior needs the current app revision");
509
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v74"/, "questionnaire public assets need a coherent PWA cache revision");
507
+ assert.match(html, /styles\.css\?v=104/, "questionnaire CSS needs the current stylesheet revision");
508
+ assert.match(html, /app\.js\?v=120/, "questionnaire behavior needs the current app revision");
509
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "questionnaire public assets need a coherent PWA cache revision");
510
510
 
511
511
  console.log("questionnaire-dialog.test.mjs passed");
@@ -68,7 +68,13 @@ try {
68
68
  assert.equal(initialSafetyGuardSetup.status, 200);
69
69
  assert.equal(initialSafetyGuardSetup.body?.data?.config?.enabled, true, "safety guard should default to enabled");
70
70
  assert.deepEqual(initialSafetyGuardSetup.body?.data?.config?.contextLines, { before: 3, after: 3 });
71
+ assert.deepEqual(initialSafetyGuardSetup.body?.data?.config?.autoReview, {
72
+ enabled: false,
73
+ model: { provider: "", modelId: "", thinkingLevel: "off" },
74
+ }, "auto-review should default off with no implicit model selection");
71
75
  assert.ok(initialSafetyGuardSetup.body?.data?.categories?.includes("database"));
76
+ assert.equal(initialSafetyGuardSetup.body?.data?.models?.[0]?.id, "fake-model", "GET should return authenticated models from the active Pi tab");
77
+ assert.deepEqual(initialSafetyGuardSetup.body?.data?.modelThinkingLevels?.["fake/fake-model"], ["off"], "GET should return supported thinking levels per model");
72
78
 
73
79
  const invalidSafetyGuardSetup = await request("/api/safety-guard/config", {
74
80
  method: "POST",
@@ -76,6 +82,28 @@ try {
76
82
  });
77
83
  assert.equal(invalidSafetyGuardSetup.status, 400, "setup should reject context limits outside the canonical range");
78
84
 
85
+ const unavailableAutoReviewModel = await request("/api/safety-guard/config", {
86
+ method: "POST",
87
+ body: { config: { autoReview: { enabled: true, model: { provider: "fake", modelId: "missing-model", thinkingLevel: "off" } } } },
88
+ });
89
+ assert.equal(unavailableAutoReviewModel.status, 400, "enabled auto-review should reject unavailable models");
90
+
91
+ const unsupportedAutoReviewThinking = await request("/api/safety-guard/config", {
92
+ method: "POST",
93
+ body: { config: { autoReview: { enabled: true, model: { provider: "fake", modelId: "fake-model", thinkingLevel: "low" } } } },
94
+ });
95
+ assert.equal(unsupportedAutoReviewThinking.status, 400, "enabled auto-review should reject unsupported thinking levels");
96
+
97
+ const enabledAutoReviewSetup = await request("/api/safety-guard/config", {
98
+ method: "POST",
99
+ body: { config: { autoReview: { enabled: true, model: { provider: "fake", modelId: "fake-model", thinkingLevel: "off" } } } },
100
+ });
101
+ assert.equal(enabledAutoReviewSetup.status, 200);
102
+ assert.deepEqual(enabledAutoReviewSetup.body?.data?.config?.autoReview, {
103
+ enabled: true,
104
+ model: { provider: "fake", modelId: "fake-model", thinkingLevel: "off" },
105
+ });
106
+
79
107
  const savedSafetyGuardSetup = await request("/api/safety-guard/config", {
80
108
  method: "POST",
81
109
  body: {
@@ -84,6 +112,7 @@ try {
84
112
  categories: { docker: false },
85
113
  protectedPaths: { edit: false },
86
114
  contextLines: { before: 2, after: 4 },
115
+ autoReview: { enabled: false },
87
116
  },
88
117
  },
89
118
  });
@@ -91,8 +120,13 @@ try {
91
120
  assert.equal(savedSafetyGuardSetup.body?.data?.config?.enabled, false);
92
121
  assert.equal(savedSafetyGuardSetup.body?.data?.config?.categories?.docker, false);
93
122
  assert.deepEqual(savedSafetyGuardSetup.body?.data?.config?.contextLines, { before: 2, after: 4 });
123
+ assert.deepEqual(savedSafetyGuardSetup.body?.data?.config?.autoReview, {
124
+ enabled: false,
125
+ model: { provider: "fake", modelId: "fake-model", thinkingLevel: "off" },
126
+ }, "disabling auto-review should retain the explicitly selected model");
94
127
  const persistedSafetyGuardSetup = JSON.parse(await readFile(safetyGuardSettingsFile, "utf8"));
95
128
  assert.equal(persistedSafetyGuardSetup.protectedPaths?.edit, false);
129
+ assert.equal(persistedSafetyGuardSetup.autoReview?.enabled, false);
96
130
 
97
131
  const initialGitSetup = await request("/api/git-workflow/preferences");
98
132
  assert.equal(initialGitSetup.status, 200);
@@ -61,6 +61,15 @@ const rawPiScript = String.raw`
61
61
  });
62
62
  `;
63
63
 
64
+ let testSocketSerial = 0;
65
+
66
+ function testSocketPath(label) {
67
+ testSocketSerial += 1;
68
+ return process.platform === "win32"
69
+ ? `\\\\.\\pipe\\pi-webui-rpc-host-${process.pid}-${testSocketSerial}-${label}`
70
+ : path.join(work, `${label}.sock`);
71
+ }
72
+
64
73
  async function listen(server, socketPath) {
65
74
  const connections = new Set();
66
75
  server.__testConnections = connections;
@@ -374,7 +383,7 @@ try {
374
383
  await removeSupervisorState(resetPaths, { removeSocket: true, instanceId: "reset-instance" });
375
384
 
376
385
  // Untagged pre-attach errors and silent peers must fail a client deterministically.
377
- const attachErrorPath = path.join(work, "attach-error.sock");
386
+ const attachErrorPath = testSocketPath("attach-error");
378
387
  const attachErrorServer = createServer((socket) => socket.once("data", () => socket.write(`${JSON.stringify({ type: "result", ok: false, code: "RPC_SUPERVISOR_AUTH", error: "denied" })}\n`)));
379
388
  await listen(attachErrorServer, attachErrorPath);
380
389
  const attachErrorClient = new RpcSupervisorClient({
@@ -387,7 +396,7 @@ try {
387
396
  await delay(20);
388
397
  await closeServer(attachErrorServer);
389
398
 
390
- const attachTimeoutPath = path.join(work, "attach-timeout.sock");
399
+ const attachTimeoutPath = testSocketPath("attach-timeout");
391
400
  const attachTimeoutServer = createServer(() => {});
392
401
  await listen(attachTimeoutServer, attachTimeoutPath);
393
402
  const attachTimeoutClient = new RpcSupervisorClient({
@@ -0,0 +1,117 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { chmod, mkdtemp, readFile, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path, { dirname, join } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
10
+ const serverScript = join(root, "bin", "pi-webui.mjs");
11
+ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
12
+ const port = 30000 + Math.floor(Math.random() * 20000);
13
+ const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-safety-guard-auto-review-"));
14
+ const safetyGuardSettingsFile = path.join(cwd, "safety-guard.json");
15
+
16
+ async function request(pathname, { method = "GET", body, timeoutMs = 5_000 } = {}) {
17
+ const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
18
+ method,
19
+ headers: body === undefined ? undefined : { "Content-Type": "application/json" },
20
+ body: body === undefined ? undefined : JSON.stringify(body),
21
+ signal: AbortSignal.timeout(timeoutMs),
22
+ });
23
+ return { status: response.status, body: await response.json().catch(() => undefined) };
24
+ }
25
+
26
+ async function removeWithRetry(target) {
27
+ let lastError;
28
+ for (let attempt = 0; attempt < 20; attempt += 1) {
29
+ try {
30
+ await rm(target, { recursive: true, force: true });
31
+ return;
32
+ } catch (error) {
33
+ lastError = error;
34
+ if (!["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) throw error;
35
+ await delay(100 + attempt * 50);
36
+ }
37
+ }
38
+ throw lastError;
39
+ }
40
+
41
+ await chmod(fakePi, 0o755);
42
+ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
43
+ stdio: ["ignore", "pipe", "pipe"],
44
+ env: { ...process.env, PI_SAFETY_GUARD_CONFIG_FILE: safetyGuardSettingsFile, PI_WEBUI_RPC_SUPERVISOR: "0" },
45
+ });
46
+ let serverOutput = "";
47
+ child.stdout.on("data", (chunk) => { serverOutput += String(chunk); });
48
+ child.stderr.on("data", (chunk) => { serverOutput += String(chunk); });
49
+
50
+ try {
51
+ let health;
52
+ for (let attempt = 0; attempt < 100; attempt += 1) {
53
+ if (child.exitCode !== null) break;
54
+ try {
55
+ health = await request("/api/health", { timeoutMs: 1_000 });
56
+ if (health.status === 200) break;
57
+ } catch {
58
+ // Server not listening yet.
59
+ }
60
+ await delay(200);
61
+ }
62
+ assert.equal(health?.status, 200, `server should become healthy, output:\n${serverOutput}`);
63
+
64
+ const initial = await request("/api/safety-guard/config");
65
+ assert.equal(initial.status, 200);
66
+ assert.deepEqual(initial.body?.data?.config?.autoReview, {
67
+ enabled: false,
68
+ model: { provider: "", modelId: "", thinkingLevel: "off" },
69
+ });
70
+ assert.equal(initial.body?.data?.models?.[0]?.provider, "fake");
71
+ assert.equal(initial.body?.data?.models?.[0]?.id, "fake-model");
72
+ assert.deepEqual(initial.body?.data?.modelThinkingLevels, { "fake/fake-model": ["off"] });
73
+
74
+ const unavailable = await request("/api/safety-guard/config", {
75
+ method: "POST",
76
+ body: { config: { autoReview: { enabled: true, model: { provider: "fake", modelId: "missing-model", thinkingLevel: "off" } } } },
77
+ });
78
+ assert.equal(unavailable.status, 400);
79
+ assert.match(unavailable.body?.error || "", /not currently available/);
80
+
81
+ const unsupported = await request("/api/safety-guard/config", {
82
+ method: "POST",
83
+ body: { config: { autoReview: { enabled: true, model: { provider: "fake", modelId: "fake-model", thinkingLevel: "low" } } } },
84
+ });
85
+ assert.equal(unsupported.status, 400);
86
+ assert.match(unsupported.body?.error || "", /does not support thinking level low/);
87
+
88
+ const enabled = await request("/api/safety-guard/config", {
89
+ method: "POST",
90
+ body: { config: { autoReview: { enabled: true, model: { provider: "fake", modelId: "fake-model", thinkingLevel: "off" } } } },
91
+ });
92
+ assert.equal(enabled.status, 200);
93
+ assert.equal(enabled.body?.data?.config?.autoReview?.enabled, true);
94
+
95
+ const disabledWithRetainedSelection = await request("/api/safety-guard/config", {
96
+ method: "POST",
97
+ body: { config: { autoReview: { enabled: false, model: { provider: "fake", modelId: "missing-model", thinkingLevel: "low" } } } },
98
+ });
99
+ assert.equal(disabledWithRetainedSelection.status, 200, "disabled auto-review should tolerate retained selections without runtime validation");
100
+ assert.deepEqual(disabledWithRetainedSelection.body?.data?.config?.autoReview, {
101
+ enabled: false,
102
+ model: { provider: "fake", modelId: "missing-model", thinkingLevel: "low" },
103
+ });
104
+
105
+ const persisted = JSON.parse(await readFile(safetyGuardSettingsFile, "utf8"));
106
+ assert.deepEqual(persisted.autoReview, disabledWithRetainedSelection.body.data.config.autoReview);
107
+ console.log("safety-guard-auto-review-harness.test.mjs passed");
108
+ } finally {
109
+ const exited = new Promise((resolve) => child.once("exit", resolve));
110
+ child.kill("SIGTERM");
111
+ await Promise.race([exited, delay(2_000)]);
112
+ if (child.exitCode === null) {
113
+ child.kill("SIGKILL");
114
+ await Promise.race([exited, delay(2_000)]);
115
+ }
116
+ await removeWithRetry(cwd);
117
+ }
@@ -0,0 +1,34 @@
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, server] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
10
+ ]);
11
+
12
+ const dialog = app.match(/async function openNativeSafetyGuardSetupDialog\(\) \{[\s\S]*?\n\}\n\nfunction gitWorkflowSetupModelKey/)?.[0] || "";
13
+ assert.ok(dialog, "Safety Guard Setup dialog should remain extractable");
14
+ assert.match(dialog, /nativeSettingToggle\("Automatic model review"[\s\S]*config\.autoReview\?\.enabled === true/, "dialog should apply the canonical disabled-by-default auto-review toggle");
15
+ assert.match(dialog, /nativeSettingSelect\("Review model"[\s\S]*nativeSettingSelect\("Review thinking"/, "dialog should expose model and thinking selectors");
16
+ assert.match(dialog, /data\.modelThinkingLevels\?\.\[selectedModelKey\]/, "thinking options should come from the server's per-model support map");
17
+ assert.match(dialog, /controls\.autoReviewModel\.select\.disabled = !models\.length[\s\S]*controls\.autoReviewThinking\.select\.disabled = !selectedAvailable/, "model and thinking selectors should remain configurable before auto-review is enabled");
18
+ assert.match(dialog, /model and thinking can still be preselected before enabling auto-review/, "disabled auto-review state should explain that model setup remains available");
19
+ assert.match(dialog, /Unavailable: no authenticated Pi models are available[\s\S]*Unavailable: select one of the authenticated models from this active tab/, "dialog should explain model-unavailable states");
20
+ assert.match(dialog, /const collectConfig = \(\) =>[\s\S]*autoReview: \{[\s\S]*enabled: controls\.autoReview\.input\.checked[\s\S]*provider:[\s\S]*modelId:[\s\S]*thinkingLevel:/, "collection should persist the canonical nested autoReview shape");
21
+ assert.match(dialog, /const applyConfig = \(value\) =>[\s\S]*controls\.autoReview\.input\.checked = value\?\.autoReview\?\.enabled === true[\s\S]*syncAutoReviewControls/, "application and reset should restore auto-review controls and availability state");
22
+ assert.match(dialog, /addNativeCommandAction\("Reset defaults"[\s\S]*applyConfig\(defaults\)/, "reset should apply canonical defaults");
23
+ assert.match(dialog, /submitted\.autoReview\.enabled && !models\.some[\s\S]*submitted\.autoReview\.enabled && !supportedLevels\.includes[\s\S]*body: \{ config: submitted \}/, "save should reject unavailable browser selections before posting the nested config");
24
+
25
+ const api = server.match(/function safetyGuardModelKey\(model\)[\s\S]*?\n\}\n\nfunction requireSubagentLaunchSlotScope/)?.[0] || "";
26
+ assert.ok(api, "Safety Guard config API helpers should remain extractable");
27
+ assert.match(api, /availableGitWorkflowModels\(tab\)/, "GET payload should discover authenticated models through the active tab convention");
28
+ assert.match(api, /modelThinkingLevels: Object\.fromEntries[\s\S]*supportedGitWorkflowThinkingLevels\(model\)/, "GET payload should reuse the existing supported-thinking convention");
29
+ assert.match(api, /mergeSafetyGuardConfig\(settingsModule\.readSafetyGuardConfig\(\), submitted\)/, "POST validation should inspect the merged canonical config");
30
+ assert.match(api, /if \(next\.autoReview\.enabled\)[\s\S]*Selected auto-review model is not currently available[\s\S]*does not support thinking level/, "POST should validate availability and thinking support only when auto-review is enabled");
31
+ assert.match(server, /url\.pathname === "\/api\/safety-guard\/config" && req\.method === "GET"[\s\S]*const tab = getRequestedTab\(req, url\)[\s\S]*safetyGuardConfigData\(tab\)/, "GET route should pass the requested active tab into model discovery");
32
+ assert.match(server, /url\.pathname === "\/api\/safety-guard\/config" && req\.method === "POST"[\s\S]*saveSafetyGuardConfigData\(tab, body\)/, "POST route should validate against the requested active tab");
33
+
34
+ console.log("safety-guard-auto-review-static.test.mjs passed");