@firstpick/pi-package-webui 0.9.6 → 0.9.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 (52) hide show
  1. package/README.md +7 -3
  2. package/bin/pi-webui.mjs +367 -72
  3. package/lib/git-workflow-preferences.mjs +21 -1
  4. package/lib/session-tree-event-targets.mjs +70 -0
  5. package/lib/subagent-launch-policy.mjs +375 -0
  6. package/lib/subagent-launch-slots.mjs +2 -1
  7. package/package.json +1 -1
  8. package/public/app.js +721 -35
  9. package/public/index.html +38 -2
  10. package/public/service-worker.js +1 -1
  11. package/public/styles.css +254 -3
  12. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  13. package/tests/browser/control-visibility.spec.mjs +141 -2
  14. package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
  15. package/tests/browser/guided-git-fallback.spec.mjs +153 -0
  16. package/tests/codex-fast-mode-static.test.mjs +2 -2
  17. package/tests/compact-sections-static.test.mjs +4 -0
  18. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  19. package/tests/control-visibility-static.test.mjs +66 -3
  20. package/tests/controls-layout-static.test.mjs +3 -3
  21. package/tests/events-tree-context-menu-static.test.mjs +131 -0
  22. package/tests/fast-mode-client-static.test.mjs +5 -2
  23. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  24. package/tests/file-viewer-image-static.test.mjs +3 -3
  25. package/tests/git-workflow-preferences.test.mjs +30 -1
  26. package/tests/guided-git-fallback-runtime.test.mjs +418 -0
  27. package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
  28. package/tests/guided-git-message-reliability-static.test.mjs +8 -7
  29. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  30. package/tests/main-output-loading-static.test.mjs +3 -3
  31. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  32. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  33. package/tests/mobile-foundation-static.test.mjs +3 -3
  34. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  35. package/tests/mobile-static.test.mjs +7 -5
  36. package/tests/open-issue-wizard-static.test.mjs +1 -1
  37. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  38. package/tests/prompt-input-vertical-scroll-static.test.mjs +3 -3
  39. package/tests/questionnaire-dialog.test.mjs +3 -3
  40. package/tests/remote-auth-settings-harness.test.mjs +23 -0
  41. package/tests/resource-defaults-helper.test.mjs +12 -0
  42. package/tests/session-sampling-helper.test.mjs +1 -0
  43. package/tests/session-sampling-ui-static.test.mjs +3 -3
  44. package/tests/session-tree-event-targets.test.mjs +106 -0
  45. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  46. package/tests/subagent-launch-policy.test.mjs +532 -0
  47. package/tests/subagent-observability-static.test.mjs +2 -2
  48. package/tests/subagents-helper.test.mjs +211 -1
  49. package/tests/syntax-highlighting-static.test.mjs +3 -3
  50. package/tests/tab-close-continuity-static.test.mjs +23 -0
  51. package/tests/theme-customizer-static.test.mjs +1 -1
  52. package/webui-rpc-helper.mjs +220 -3
@@ -28,6 +28,7 @@ class EventBus {
28
28
  const bus = new EventBus();
29
29
  const extensionHandlers = new Map();
30
30
  const registeredCommands = new Map();
31
+ const registeredTools = new Map();
31
32
  const statuses = [];
32
33
  const notifications = [];
33
34
  const sentMessages = [];
@@ -37,6 +38,8 @@ let idle = true;
37
38
  let subagentStatusRequestCount = 0;
38
39
  let subagentRpcReplyHook = null;
39
40
  let setStatusFailures = 0;
41
+ let confirmationResponse = true;
42
+ const confirmations = [];
40
43
  const pi = {
41
44
  events: bus,
42
45
  on(name, handler) {
@@ -45,6 +48,7 @@ const pi = {
45
48
  extensionHandlers.set(name, handlers);
46
49
  },
47
50
  registerCommand(name, command) { registeredCommands.set(name, command); },
51
+ registerTool(tool) { registeredTools.set(tool.name, tool); },
48
52
  getAllTools() { return []; },
49
53
  getActiveTools() { return []; },
50
54
  setActiveTools() {},
@@ -77,6 +81,10 @@ const ctx = {
77
81
  };
78
82
  },
79
83
  ui: {
84
+ async confirm(title, message) {
85
+ confirmations.push({ title, message });
86
+ return confirmationResponse;
87
+ },
80
88
  setStatus(key, text) {
81
89
  if (setStatusFailures > 0) {
82
90
  setStatusFailures -= 1;
@@ -93,7 +101,9 @@ const ctx = {
93
101
  const asyncRunDir = await mkdtemp(path.join(tmpdir(), "pi-webui-subagent-output-test-"));
94
102
  const settingsFile = path.join(asyncRunDir, "webui-settings.json");
95
103
  const initialLaunchRoles = defaultSubagentLaunchSlotRoles();
104
+ initialLaunchRoles.delegate[0] = { id: "delegate:base", model: "fake/delegate", thinking: "low" };
96
105
  initialLaunchRoles.reviewer[0] = { id: "reviewer:base", model: "fake/reviewer", thinking: "high" };
106
+ initialLaunchRoles.reviewer.push({ id: "reviewer:second", model: "fake/reviewer-second", thinking: "medium" });
97
107
  await writeFile(settingsFile, `${JSON.stringify({
98
108
  version: 5,
99
109
  resourceDefaults: { tools: { enabledTools: null }, skills: { enabledSkills: ["repo-explorer"] } },
@@ -184,7 +194,161 @@ const promptWithSkills = [
184
194
  ].join("\n");
185
195
  const initialGuidance = await beforeAgentStart({ systemPrompt: promptWithSkills, systemPromptOptions: ctx.getSystemPromptOptions() });
186
196
  assert.match(initialGuidance?.systemPrompt || "", /reviewer slot 1: agent=reviewer model=fake\/reviewer:high/, "session_start should cache effective launch-slot guidance");
197
+ assert.match(initialGuidance?.systemPrompt || "", /runtime fills omitted model fields for structured subagent and subagent_gate launches, including runs\.run and runs\.all workflow children/, "guidance should explain which calls receive runtime defaults");
198
+ assert.match(initialGuidance?.systemPrompt || "", /Explicit reviewer model or thinking mismatches are blocked before launch/, "guidance should explain reviewer mismatch enforcement");
199
+ assert.match(initialGuidance?.systemPrompt || "", /approve_subagent_model_deviation tool is valid only after the user explicitly authorizes/, "guidance should require explicit user authorization for deviations");
187
200
  assert.doesNotMatch(initialGuidance?.systemPrompt || "", /code-security/, "launch-slot guidance must compose with disabled-skill filtering");
201
+
202
+ const deviationTool = registeredTools.get("approve_subagent_model_deviation");
203
+ assert.ok(deviationTool, "helper should register the WebUI-owned reviewer deviation approval tool");
204
+ assert.equal(deviationTool.parameters.additionalProperties, false, "deviation approval parameters should reject unknown fields");
205
+ assert.deepEqual(deviationTool.parameters.required, ["role", "occurrence", "requestedModel", "reason"]);
206
+ assert.equal(deviationTool.parameters.properties.role.const, "reviewer");
207
+ assert.deepEqual(
208
+ [deviationTool.parameters.properties.occurrence.minimum, deviationTool.parameters.properties.occurrence.maximum],
209
+ [1, 8],
210
+ "deviation approvals should use one-based reviewer occurrences bounded to the eight slots",
211
+ );
212
+ assert.equal(deviationTool.parameters.properties.requestedModel.maxLength, 280);
213
+ assert.equal(deviationTool.parameters.properties.reason.maxLength, 500);
214
+ assert.match(`${deviationTool.description} ${deviationTool.promptGuidelines.join(" ")}`, /only after the user explicitly authorizes/i);
215
+
216
+ const applyLaunchSlotDefaults = (extensionHandlers.get("tool_call") || [])[0];
217
+ assert.ok(applyLaunchSlotDefaults, "helper should register launch-slot defaults before subagent execution");
218
+ const singleLaunchInput = { agent: "delegate", task: "Delegate this work" };
219
+ assert.equal(await applyLaunchSlotDefaults({ toolName: "subagent", input: singleLaunchInput }, ctx), undefined);
220
+ assert.equal(singleLaunchInput.model, "fake/delegate:low", "structured single launches should receive the configured role model and thinking level");
221
+ const omittedReviewerInput = { agent: "reviewer", task: "Use the configured reviewer" };
222
+ assert.equal(await applyLaunchSlotDefaults({ toolName: "subagent", input: omittedReviewerInput }, ctx), undefined);
223
+ assert.equal(omittedReviewerInput.model, "fake/reviewer:high", "an omitted reviewer model should receive the immutable snapshot default");
224
+ const exactReviewerInput = { agent: "reviewer", task: "Use the exact configured reviewer", model: "fake/reviewer:high" };
225
+ assert.equal(await applyLaunchSlotDefaults({ toolName: "subagent", input: exactReviewerInput }, ctx), undefined, "an exact reviewer model should be admitted");
226
+ const explicitLaunchInput = { agent: "reviewer", task: "Review with the requested model", model: "fake/explicit:high" };
227
+ const explicitBlock = await applyLaunchSlotDefaults({ toolName: "subagent", input: explicitLaunchInput }, ctx);
228
+ assert.equal(explicitBlock?.block, true, "an explicit reviewer model mismatch should block before tool execution");
229
+ assert.match(explicitBlock?.reason || "", /occurrence 1.*expected fake\/reviewer:high, requested fake\/explicit:high.*Retry with fake\/reviewer:high/i, "the block should identify occurrence, expected, requested, and correction details");
230
+ assert.equal(explicitLaunchInput.model, "fake/explicit:high", "a blocked explicit mismatch must never be silently overwritten");
231
+ const nonReviewerInput = { agent: "delegate", task: "Keep this explicit model", model: "fake/explicit-delegate:low" };
232
+ assert.equal(await applyLaunchSlotDefaults({ toolName: "subagent", input: nonReviewerInput }, ctx), undefined);
233
+ assert.equal(nonReviewerInput.model, "fake/explicit-delegate:low", "explicit non-reviewer models should retain their prior behavior");
234
+
235
+ ctx.hasUI = false;
236
+ await assert.rejects(
237
+ deviationTool.execute("permit-no-ui", {
238
+ role: "reviewer",
239
+ occurrence: 1,
240
+ requestedModel: "fake/no-ui:high",
241
+ reason: "The user asked for this reviewer model.",
242
+ }),
243
+ /requires an interactive WebUI confirmation/,
244
+ "deviation approval must fail closed when interactive UI is unavailable",
245
+ );
246
+ ctx.hasUI = true;
247
+ confirmationResponse = false;
248
+ await assert.rejects(
249
+ deviationTool.execute("permit-rejected", {
250
+ role: "reviewer",
251
+ occurrence: 2,
252
+ requestedModel: "fake/rejected:medium",
253
+ reason: "The user may reject this exact request.",
254
+ }),
255
+ /not confirmed by the user/,
256
+ "deviation approval must fail closed when the user rejects the confirmation",
257
+ );
258
+ assert.deepEqual(confirmations.at(-1), {
259
+ title: "Authorize reviewer model deviation?",
260
+ message: "Allow reviewer occurrence 2 to use fake/rejected:medium once within 2 minutes?\n\nReason: The user may reject this exact request.",
261
+ }, "the interactive confirmation should identify the exact occurrence, model, duration, and reason");
262
+ confirmationResponse = true;
263
+
264
+ const mixedPermit = await deviationTool.execute("permit-mixed", {
265
+ role: "reviewer",
266
+ occurrence: 1,
267
+ requestedModel: " fake/permitted:high ",
268
+ reason: " The user explicitly requested a different first reviewer. ",
269
+ });
270
+ assert.equal(mixedPermit.details.requestedModel, "fake/permitted:high", "permit model and reason input should be normalized before local storage");
271
+ const mixedGateInput = { tasks: [
272
+ { agent: "reviewer", task: "Permitted first mismatch", model: "fake/permitted:high" },
273
+ { agent: "reviewer", task: "Unpermitted second mismatch", model: "fake/unpermitted:medium" },
274
+ ] };
275
+ assert.equal((await applyLaunchSlotDefaults({ toolName: "subagent_gate", input: mixedGateInput }, ctx))?.block, true, "one unpermitted mismatch should block the whole structured request");
276
+ const retainedPermitInput = { agent: "reviewer", task: "Retry the retained permit", model: "fake/permitted:high" };
277
+ assert.equal(await applyLaunchSlotDefaults({ toolName: "subagent", input: retainedPermitInput }, ctx), undefined, "a permit matched in a blocked request should remain available until the whole request is admitted");
278
+ assert.equal((await applyLaunchSlotDefaults({ toolName: "subagent", input: { ...retainedPermitInput } }, ctx))?.block, true, "an admitted direct launch should consume its matching permit exactly once");
279
+
280
+ const expiringPermit = await deviationTool.execute("permit-expiry", {
281
+ role: "reviewer",
282
+ occurrence: 1,
283
+ requestedModel: "fake/expired:high",
284
+ reason: "The user explicitly authorized this temporary reviewer model.",
285
+ });
286
+ const realDateNowForPermit = Date.now;
287
+ Date.now = () => expiringPermit.details.expiresAt + 1;
288
+ try {
289
+ const expiredInput = { agent: "reviewer", task: "Expired reviewer", model: "fake/expired:high" };
290
+ assert.equal((await applyLaunchSlotDefaults({ toolName: "subagent", input: expiredInput }, ctx))?.block, true, "an expired permit should be pruned and rejected");
291
+ } finally {
292
+ Date.now = realDateNowForPermit;
293
+ }
294
+
295
+ const workflowPermit = await deviationTool.execute("permit-workflow", {
296
+ role: "reviewer",
297
+ occurrence: 1,
298
+ requestedModel: "fake/workflow-reviewer:high",
299
+ reason: "The user explicitly authorized this reviewer inside one workflow.",
300
+ });
301
+ const workflowInput = {
302
+ workflowScript: "return runs.run('review', { agent: 'reviewer', task: 'Review it', model: 'fake/workflow-reviewer:high' })",
303
+ };
304
+ assert.equal(await applyLaunchSlotDefaults({ toolName: "subagent", input: workflowInput }, ctx), undefined, "a matching permit should be leased into one workflow wrapper");
305
+ assert.match(workflowInput.workflowScript, /PI_WEBUI_SUBAGENT_LAUNCH_SLOTS_V1/);
306
+ assert.match(workflowInput.workflowScript, new RegExp(workflowPermit.details.permitId), "the wrapped workflow should contain the leased permit descriptor");
307
+ assert.match(workflowInput.workflowScript, new RegExp(`\\"expiresAt\\":${workflowPermit.details.expiresAt}`), "the workflow descriptor should retain its bounded expiry");
308
+ const workflowPermitReuse = { agent: "reviewer", task: "Do not reuse the workflow permit", model: "fake/workflow-reviewer:high" };
309
+ assert.equal((await applyLaunchSlotDefaults({ toolName: "subagent", input: workflowPermitReuse }, ctx))?.block, true, "leasing a permit into a workflow should remove it from helper memory immediately");
310
+ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
311
+ const immediateWorkflowCalls = [];
312
+ await new AsyncFunction("runs", workflowInput.workflowScript)({
313
+ run(key, params) { immediateWorkflowCalls.push({ key, ...params }); return Promise.resolve({ key }); },
314
+ all() { throw new Error("unexpected runs.all"); },
315
+ status() { return {}; },
316
+ ref() { return ""; },
317
+ refs() { return ""; },
318
+ });
319
+ assert.equal(immediateWorkflowCalls.length, 1, "an unexpired leased workflow permit should admit its exact reviewer child");
320
+
321
+ const delayedWorkflowPermit = await deviationTool.execute("permit-delayed-workflow", {
322
+ role: "reviewer",
323
+ occurrence: 1,
324
+ requestedModel: "fake/delayed-workflow-reviewer:high",
325
+ reason: "The user explicitly authorized this reviewer inside one delayed workflow.",
326
+ });
327
+ const delayedWorkflowInput = {
328
+ workflowScript: "return runs.run('review', { agent: 'reviewer', task: 'Review later', model: 'fake/delayed-workflow-reviewer:high' })",
329
+ };
330
+ await applyLaunchSlotDefaults({ toolName: "subagent", input: delayedWorkflowInput }, ctx);
331
+ const realDateNowForDelayedWorkflow = Date.now;
332
+ Date.now = () => delayedWorkflowPermit.details.expiresAt + 1;
333
+ try {
334
+ await assert.rejects(
335
+ new AsyncFunction("runs", delayedWorkflowInput.workflowScript)({
336
+ run() { throw new Error("expired workflow permit reached original runs"); },
337
+ all() { throw new Error("unexpected runs.all"); },
338
+ status() { return {}; },
339
+ ref() { return ""; },
340
+ refs() { return ""; },
341
+ }),
342
+ (error) => error.code === "reviewer-model-policy-blocked",
343
+ "a leased workflow permit must be rechecked at delayed use time",
344
+ );
345
+ } finally {
346
+ Date.now = realDateNowForDelayedWorkflow;
347
+ }
348
+
349
+ const gateLaunchInput = { tasks: [{ agent: "reviewer", task: "Review correctness" }, { agent: "delegate", task: "Check scope" }, { agent: "reviewer", task: "Review tests" }] };
350
+ assert.equal(await applyLaunchSlotDefaults({ toolName: "subagent_gate", input: gateLaunchInput }, ctx), undefined);
351
+ assert.deepEqual(gateLaunchInput.tasks.map((task) => task.model), ["fake/reviewer:high", "fake/delegate:low", "fake/reviewer-second:medium"], "gate tasks should consume each role's slots independently in task order");
188
352
  const changedLaunchRoles = defaultSubagentLaunchSlotRoles();
189
353
  changedLaunchRoles.reviewer[0] = { id: "reviewer:base", model: "fake/changed", thinking: "high" };
190
354
  await writeFile(settingsFile, `${JSON.stringify({
@@ -195,7 +359,40 @@ await writeFile(settingsFile, `${JSON.stringify({
195
359
  const cachedGuidance = await beforeAgentStart({ systemPrompt: "Base system prompt.", systemPromptOptions: ctx.getSystemPromptOptions() });
196
360
  assert.match(cachedGuidance?.systemPrompt || "", /fake\/reviewer:high/, "a settings save must not mutate the active helper snapshot");
197
361
  assert.doesNotMatch(cachedGuidance?.systemPrompt || "", /fake\/changed:high/);
198
- for (let attempt = 0; attempt < 20 && !statuses.some((entry) => entry.text?.startsWith("PI_WEBUI_SUBAGENTS_V1 ") && entry.text.includes("run-a")); attempt++) {
362
+ const cachedLaunchInput = { agent: "reviewer", task: "Review after settings save" };
363
+ await applyLaunchSlotDefaults({ toolName: "subagent", input: cachedLaunchInput }, ctx);
364
+ assert.equal(cachedLaunchInput.model, "fake/reviewer:high", "runtime launch defaults should use the same immutable active-tab snapshot as prompt guidance");
365
+ const staleGenerationPermit = await deviationTool.execute("permit-old-generation", {
366
+ role: "reviewer",
367
+ occurrence: 1,
368
+ requestedModel: "fake/old-generation:high",
369
+ reason: "The user explicitly authorized this model in the current snapshot.",
370
+ });
371
+ for (let index = 1; index < 8; index += 1) {
372
+ await deviationTool.execute(`permit-bound-${index}`, {
373
+ role: "reviewer",
374
+ occurrence: index + 1,
375
+ requestedModel: `fake/bounded-${index}:high`,
376
+ reason: "The user explicitly authorized this bounded local permit.",
377
+ });
378
+ }
379
+ await assert.rejects(
380
+ deviationTool.execute("permit-over-limit", {
381
+ role: "reviewer",
382
+ occurrence: 1,
383
+ requestedModel: "fake/over-limit:high",
384
+ reason: "This should exceed the local permit bound.",
385
+ }),
386
+ /already has 8 unused reviewer model deviation permits/,
387
+ "the helper should retain at most eight local permits",
388
+ );
389
+ for (const handler of extensionHandlers.get("session_start") || []) await handler({ reason: "reload-launch-slot-snapshot" }, ctx);
390
+ const staleGenerationInput = { agent: "reviewer", task: "Do not reuse stale authorization", model: staleGenerationPermit.details.requestedModel };
391
+ assert.equal((await applyLaunchSlotDefaults({ toolName: "subagent", input: staleGenerationInput }, ctx))?.block, true, "snapshot reload should invalidate permits from the prior revision and helper generation");
392
+ const reloadedLaunchInput = { agent: "reviewer", task: "Use the reloaded reviewer slot" };
393
+ assert.equal(await applyLaunchSlotDefaults({ toolName: "subagent", input: reloadedLaunchInput }, ctx), undefined);
394
+ assert.equal(reloadedLaunchInput.model, "fake/changed:high", "a snapshot reload should atomically adopt the newly saved reviewer slot");
395
+ for (let attempt = 0; attempt < 20 && !statuses.filter((entry) => entry.key === "webui-subagents").at(-1)?.text?.includes("run-a"); attempt++) {
199
396
  await new Promise((resolve) => setTimeout(resolve, 10));
200
397
  }
201
398
 
@@ -1034,6 +1231,19 @@ assert.deepEqual(helperResponse("dismiss-finished-foreground"), {
1034
1231
  payload = latestPayload();
1035
1232
  assert.equal(payload.runs.some((run) => run.id === "foreground-call"), false, "a dismissed finished run should disappear from the published snapshot");
1036
1233
 
1234
+ await helperCommand.handler(JSON.stringify({
1235
+ requestId: "dismiss-already-missing-foreground",
1236
+ action: "subagent-dismiss",
1237
+ payload: { runId: "foreground-call" },
1238
+ }), ctx);
1239
+ assert.deepEqual(helperResponse("dismiss-already-missing-foreground"), {
1240
+ requestId: "dismiss-already-missing-foreground",
1241
+ ok: true,
1242
+ data: { runId: "foreground-call", dismissed: true, alreadyMissing: true },
1243
+ }, "dismiss should be idempotent when the terminal run disappeared before the request arrived");
1244
+ payload = latestPayload();
1245
+ assert.equal(payload.runs.some((run) => run.id === "foreground-call"), false, "idempotent dismissal should republish the cleared snapshot");
1246
+
1037
1247
  await helperCommand.handler(JSON.stringify({
1038
1248
  requestId: "dismiss-running-async",
1039
1249
  action: "subagent-dismiss",
@@ -60,9 +60,9 @@ assert.match(css, /\.markdown-code \.syntax-comment \{[^}]*font-style: italic;/,
60
60
 
61
61
  // --- Offline/PWA startup closure and coherent revisions ---
62
62
  assert.match(serviceWorker, /"\/syntax-highlight\.mjs",/, "the eagerly imported tokenizer must be part of the offline app shell");
63
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v123"/, "adding a startup module should advance the PWA cache identity");
64
- assert.match(html, /styles\.css\?v=132/, "new token styles should advance the stylesheet revision");
65
- assert.match(html, /data-app-src="\/app\.js\?v=157"/, "new renderer wiring should advance the app module revision");
63
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v132"/, "adding a startup module should advance the PWA cache identity");
64
+ assert.match(html, /styles\.css\?v=137/, "new token styles should advance the stylesheet revision");
65
+ assert.match(html, /data-app-src="\/app\.js\?v=166"/, "new renderer wiring should advance the app module revision");
66
66
  assert.match(pkg, /node --check public\/syntax-highlight\.mjs/, "the package check should syntax-check the startup-critical tokenizer");
67
67
 
68
68
  const appShell = serviceWorker.slice(serviceWorker.indexOf("const APP_SHELL"), serviceWorker.indexOf("];", serviceWorker.indexOf("const APP_SHELL")));
@@ -0,0 +1,23 @@
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 = await readFile(join(root, "public", "app.js"), "utf8");
8
+
9
+ const scheduleStart = app.indexOf("function scheduleSupervisorContinuityRefresh(");
10
+ const scheduleEnd = app.indexOf("\nfunction handleInactiveTabEvent(", scheduleStart);
11
+ const schedule = app.slice(scheduleStart, scheduleEnd);
12
+ const closeStart = app.indexOf("async function closeTerminalTabs(");
13
+ const closeEnd = app.indexOf("\nasync function closeTerminalTab(", closeStart);
14
+ const closeTabs = app.slice(closeStart, closeEnd);
15
+
16
+ assert.ok(scheduleStart >= 0 && scheduleEnd > scheduleStart, "the continuity refresh scheduler should remain inspectable");
17
+ assert.ok(closeStart >= 0 && closeEnd > closeStart, "the terminal close lifecycle should remain inspectable");
18
+ assert.match(app, /const closingTerminalTabIds = new Set\(\)/, "the frontend should track tabs whose intentional shutdown is in progress");
19
+ assert.match(schedule, /closingTerminalTabIds\.has\(tabContext\.tabId\)/, "continuity refreshes should skip tabs that are intentionally closing");
20
+ assert.match(schedule, /if \(!isCurrentTabContext\(tabContext\) \|\| closingTerminalTabIds\.has\(tabContext\.tabId\)\) return;[\s\S]*continuity refresh failed/, "an in-flight refresh rejected by intentional shutdown should not produce a false error");
21
+ assert.match(closeTabs, /for \(const id of targetIds\) closingTerminalTabIds\.add\(id\);[\s\S]*finally \{\s*for \(const id of targetIds\) closingTerminalTabIds\.delete\(id\);/, "the close lifecycle should mark every target before the request and always clear the marker afterward");
22
+
23
+ console.log("tab-close-continuity-static.test.mjs passed");
@@ -34,7 +34,7 @@ assert.match(html, /role="alert" hidden>[\s\S]*Replace this exact target\?/, "ov
34
34
 
35
35
  assert.match(app, /from "\.\/theme-contract\.mjs"/, "frontend should consume the shared browser-safe theme contract");
36
36
  assert.match(serviceWorker, /"\/theme-contract\.mjs"/, "the PWA app shell should cache the startup-critical theme contract");
37
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v123"/, "adding the theme contract to the startup graph should advance the PWA cache identity");
37
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v132"/, "adding the theme contract to the startup graph should advance the PWA cache identity");
38
38
  assert.match(pkg, /node --check public\/theme-contract\.mjs/, "the package check should syntax-check the startup-critical theme contract");
39
39
  assert.match(app, /function themeDraftFromCatalog\(theme, name = theme\?\.name\)[\s\S]*colors: cloneThemeDraft\(theme\?\.colors \|\| \{\}\)/, "catalog metadata should be projected into a schema-only editable draft");
40
40
  assert.match(app, /for \(const \{ name, label \} of group\.tokens\)/, "visual controls should render from the exact shared token inventory");
@@ -1,7 +1,8 @@
1
- import { createHash } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { AgentSession, formatSkillsForPrompt } from "@earendil-works/pi-coding-agent";
5
+ import { Type } from "typebox";
5
6
  import {
6
7
  AGENT_RUN_PROVIDER_EVENT,
7
8
  AgentRunIndex,
@@ -14,9 +15,11 @@ import {
14
15
  resolveResourceSelection,
15
16
  } from "./lib/resource-selection.mjs";
16
17
  import { mutatePiRuntimeFollowUpQueue } from "./lib/queue-mutation.mjs";
18
+ import { applySubagentLaunchSlotDefaults } from "./lib/subagent-launch-policy.mjs";
17
19
  import {
18
20
  formatSubagentLaunchSlotGuidance,
19
21
  resolveSubagentLaunchSlotProjectKey,
22
+ subagentLaunchSlotRevision,
20
23
  subagentLaunchSlotScopeEntry,
21
24
  } from "./lib/subagent-launch-slots.mjs";
22
25
  import { SUBAGENT_GATE_UPDATE_EVENT } from "./lib/subagent-gate.mjs";
@@ -88,6 +91,17 @@ const SUBAGENT_TELEMETRY_CONTEXT_WINDOW_LIMIT = 16_000_000;
88
91
  const SUBAGENT_TELEMETRY_RESPONSE_DURATION_MS = 15 * 60 * 1000;
89
92
  const SUBAGENT_TELEMETRY_SPEED_LIMIT = 1_000_000;
90
93
  const STATS_INITIAL_PROMPT_ESTIMATE_TYPE = "stats_initial_prompt_estimate";
94
+ const SUBAGENT_DEVIATION_PERMIT_LIMIT = 8;
95
+ const SUBAGENT_DEVIATION_PERMIT_TTL_MS = 2 * 60 * 1000;
96
+ const SUBAGENT_DEVIATION_REQUESTED_MODEL_LIMIT = 280;
97
+ const SUBAGENT_DEVIATION_REASON_LIMIT = 500;
98
+
99
+ const SubagentModelDeviationParams = Type.Object({
100
+ role: Type.Literal("reviewer"),
101
+ occurrence: Type.Integer({ minimum: 1, maximum: SUBAGENT_DEVIATION_PERMIT_LIMIT }),
102
+ requestedModel: Type.String({ minLength: 1, maxLength: SUBAGENT_DEVIATION_REQUESTED_MODEL_LIMIT }),
103
+ reason: Type.String({ minLength: 1, maxLength: SUBAGENT_DEVIATION_REASON_LIMIT }),
104
+ }, { additionalProperties: false });
91
105
 
92
106
  const ACTIVE_COMMAND_SESSION_KEY = Symbol.for("pi.webui.helper.activeCommandSession");
93
107
 
@@ -942,6 +956,11 @@ export default function webuiRpcHelper(pi) {
942
956
  let resourceRpcActive = false;
943
957
  let sessionSamplingParams = {};
944
958
  let subagentLaunchSlotGuidance = "";
959
+ let subagentLaunchSlotRoles = null;
960
+ let subagentLaunchSlotSnapshotLoadFailed = false;
961
+ let activeSubagentLaunchSlotRevision = null;
962
+ let subagentLaunchSlotGeneration = 0;
963
+ let subagentModelDeviationPermits = [];
945
964
  let subagentContext = null;
946
965
  let subagentBridgeAvailable = false;
947
966
  let subagentPollTimer = null;
@@ -2133,14 +2152,153 @@ export default function webuiRpcHelper(pi) {
2133
2152
  return (await readWebuiSettings()).resourceDefaults;
2134
2153
  }
2135
2154
 
2155
+ function clearSubagentModelDeviationPermits() {
2156
+ subagentModelDeviationPermits = [];
2157
+ }
2158
+
2159
+ function pruneSubagentModelDeviationPermits(now = Date.now()) {
2160
+ subagentModelDeviationPermits = subagentModelDeviationPermits.filter((permit) => permit.expiresAt > now
2161
+ && permit.slotRevision === activeSubagentLaunchSlotRevision
2162
+ && permit.helperGeneration === subagentLaunchSlotGeneration);
2163
+ return subagentModelDeviationPermits;
2164
+ }
2165
+
2166
+ function subagentModelDeviationDescriptors() {
2167
+ return pruneSubagentModelDeviationPermits().map((permit) => ({
2168
+ id: permit.id,
2169
+ role: permit.role,
2170
+ occurrence: permit.occurrence,
2171
+ requestedModel: permit.requestedModel,
2172
+ expiresAt: permit.expiresAt,
2173
+ }));
2174
+ }
2175
+
2176
+ function removeSubagentModelDeviationPermits(ids) {
2177
+ const consumed = new Set(ids);
2178
+ if (!consumed.size) return;
2179
+ subagentModelDeviationPermits = subagentModelDeviationPermits.filter((permit) => !consumed.has(permit.id));
2180
+ }
2181
+
2182
+ async function approveSubagentModelDeviation(params = {}) {
2183
+ pruneSubagentModelDeviationPermits();
2184
+ if (!subagentLaunchSlotRoles || !activeSubagentLaunchSlotRevision) {
2185
+ throw new Error("Reviewer model deviation approval is unavailable until the active WebUI launch-slot snapshot loads.");
2186
+ }
2187
+ if (params.role !== "reviewer" || !Number.isInteger(params.occurrence)
2188
+ || params.occurrence < 1 || params.occurrence > SUBAGENT_DEVIATION_PERMIT_LIMIT) {
2189
+ throw new Error("Reviewer model deviation approval requires reviewer occurrence 1 through 8.");
2190
+ }
2191
+ if (typeof params.requestedModel !== "string" || params.requestedModel.length > SUBAGENT_DEVIATION_REQUESTED_MODEL_LIMIT) {
2192
+ throw new Error(`Requested model must be at most ${SUBAGENT_DEVIATION_REQUESTED_MODEL_LIMIT} characters.`);
2193
+ }
2194
+ const requestedModel = params.requestedModel.trim();
2195
+ if (!requestedModel) throw new Error("Requested model must not be blank.");
2196
+ if (typeof params.reason !== "string" || params.reason.length > SUBAGENT_DEVIATION_REASON_LIMIT) {
2197
+ throw new Error(`Deviation reason must be at most ${SUBAGENT_DEVIATION_REASON_LIMIT} characters.`);
2198
+ }
2199
+ const reason = params.reason.trim();
2200
+ if (!reason) throw new Error("Deviation reason must not be blank.");
2201
+ if (subagentModelDeviationPermits.length >= SUBAGENT_DEVIATION_PERMIT_LIMIT) {
2202
+ throw new Error("The active WebUI tab already has 8 unused reviewer model deviation permits.");
2203
+ }
2204
+
2205
+ const approvalSlotRevision = activeSubagentLaunchSlotRevision;
2206
+ const approvalGeneration = subagentLaunchSlotGeneration;
2207
+ const context = subagentContext;
2208
+ if (context?.hasUI !== true || typeof context.ui?.confirm !== "function") {
2209
+ throw new Error("Reviewer model deviation approval requires an interactive WebUI confirmation.");
2210
+ }
2211
+ const confirmed = await context.ui.confirm(
2212
+ "Authorize reviewer model deviation?",
2213
+ `Allow reviewer occurrence ${params.occurrence} to use ${requestedModel} once within 2 minutes?\n\nReason: ${reason}`,
2214
+ );
2215
+ if (confirmed !== true) throw new Error("Reviewer model deviation approval was not confirmed by the user.");
2216
+
2217
+ pruneSubagentModelDeviationPermits();
2218
+ if (!subagentLaunchSlotRoles || !activeSubagentLaunchSlotRevision) {
2219
+ throw new Error("Reviewer model deviation approval is unavailable until the active WebUI launch-slot snapshot loads.");
2220
+ }
2221
+ if (activeSubagentLaunchSlotRevision !== approvalSlotRevision || subagentLaunchSlotGeneration !== approvalGeneration) {
2222
+ throw new Error("Reviewer model deviation approval expired because the active WebUI launch-slot snapshot changed during confirmation.");
2223
+ }
2224
+ if (subagentModelDeviationPermits.length >= SUBAGENT_DEVIATION_PERMIT_LIMIT) {
2225
+ throw new Error("The active WebUI tab already has 8 unused reviewer model deviation permits.");
2226
+ }
2227
+ const createdAt = Date.now();
2228
+ const permit = {
2229
+ id: randomUUID(),
2230
+ role: "reviewer",
2231
+ occurrence: params.occurrence,
2232
+ requestedModel,
2233
+ reason,
2234
+ slotRevision: activeSubagentLaunchSlotRevision,
2235
+ helperGeneration: subagentLaunchSlotGeneration,
2236
+ createdAt,
2237
+ expiresAt: createdAt + SUBAGENT_DEVIATION_PERMIT_TTL_MS,
2238
+ };
2239
+ subagentModelDeviationPermits.push(permit);
2240
+ return {
2241
+ content: [{
2242
+ type: "text",
2243
+ text: `Approved one reviewer occurrence ${permit.occurrence} launch with ${permit.requestedModel}. The local permit expires in 2 minutes and is consumed by one admitted launch or leased workflow.`,
2244
+ }],
2245
+ details: {
2246
+ permitId: permit.id,
2247
+ role: permit.role,
2248
+ occurrence: permit.occurrence,
2249
+ requestedModel: permit.requestedModel,
2250
+ createdAt: permit.createdAt,
2251
+ expiresAt: permit.expiresAt,
2252
+ },
2253
+ };
2254
+ }
2255
+
2256
+ function reviewerModelPolicyBlockReason(decisions) {
2257
+ const decision = decisions[0];
2258
+ const more = decisions.length > 1 ? ` (${decisions.length - 1} more mismatch${decisions.length === 2 ? "" : "es"} also blocked.)` : "";
2259
+ return `Reviewer occurrence ${decision.occurrence} model mismatch: expected ${decision.expectedModel}, requested ${decision.requestedModel}. Retry with ${decision.correctionModel} or omit model to use the configured slot; use approve_subagent_model_deviation only after explicit user authorization.${more}`;
2260
+ }
2261
+
2262
+ function inputRequestsReviewer(input) {
2263
+ const role = (value) => typeof value === "string" ? value.trim() : "";
2264
+ if (!isPlainObject(input)) return false;
2265
+ if (role(input.agent) === "reviewer") return true;
2266
+ if (Array.isArray(input.tasks) && input.tasks.some((task) => role(task?.agent) === "reviewer")) return true;
2267
+ return Array.isArray(input.chain) && input.chain.some((step) => role(step?.agent) === "reviewer"
2268
+ || (Array.isArray(step?.parallel) && step.parallel.some((task) => role(task?.agent) === "reviewer"))
2269
+ || role(step?.parallel?.agent) === "reviewer");
2270
+ }
2271
+
2272
+ function launchNeedsLoadedSlotSnapshot(toolName, input) {
2273
+ if (!isPlainObject(input) || input.action !== undefined || input.resume !== undefined) return false;
2274
+ if (toolName === "subagent" && typeof input.workflowScript === "string" && input.workflowScript.trim()) return true;
2275
+ return inputRequestsReviewer(input);
2276
+ }
2277
+
2136
2278
  async function loadSubagentLaunchSlotGuidance(ctx) {
2279
+ const generation = ++subagentLaunchSlotGeneration;
2280
+ clearSubagentModelDeviationPermits();
2281
+ activeSubagentLaunchSlotRevision = null;
2137
2282
  try {
2138
2283
  const settings = await readWebuiSettings();
2139
2284
  const projectKey = await resolveSubagentLaunchSlotProjectKey(ctx?.cwd);
2140
2285
  const effective = subagentLaunchSlotScopeEntry(settings.subagentLaunchSlots, "project", projectKey);
2141
- subagentLaunchSlotGuidance = formatSubagentLaunchSlotGuidance(effective.entry.roles);
2286
+ const revision = subagentLaunchSlotRevision(settings.subagentLaunchSlots, "project", projectKey);
2287
+ if (generation !== subagentLaunchSlotGeneration) return;
2288
+ subagentLaunchSlotRoles = effective.entry.roles;
2289
+ subagentLaunchSlotSnapshotLoadFailed = false;
2290
+ activeSubagentLaunchSlotRevision = revision;
2291
+ const assignments = formatSubagentLaunchSlotGuidance(subagentLaunchSlotRoles);
2292
+ subagentLaunchSlotGuidance = assignments
2293
+ ? `${assignments}\nExplicit reviewer model or thinking mismatches are blocked before launch. The approve_subagent_model_deviation tool is valid only after the user explicitly authorizes that exact reviewer occurrence and requested model, and it always requires interactive confirmation.`
2294
+ : "";
2142
2295
  } catch (error) {
2296
+ if (generation !== subagentLaunchSlotGeneration) return;
2297
+ subagentLaunchSlotRoles = null;
2298
+ subagentLaunchSlotSnapshotLoadFailed = true;
2143
2299
  subagentLaunchSlotGuidance = "";
2300
+ activeSubagentLaunchSlotRevision = null;
2301
+ clearSubagentModelDeviationPermits();
2144
2302
  console.warn(`Web UI subagent launch slots could not be read: ${error instanceof Error ? error.message : String(error)}`);
2145
2303
  }
2146
2304
  }
@@ -2325,7 +2483,22 @@ export default function webuiRpcHelper(pi) {
2325
2483
  function dismissSubagentRun(payload = {}) {
2326
2484
  const runId = subagentText(payload.runId, 160);
2327
2485
  if (!runId) throw new Error("Subagent dismiss requires runId");
2328
- const entry = findTrackedSubagentRun(runId);
2486
+ const entry = ordinarySubagentRunEntries().find((candidate) => candidate.run?.id === runId);
2487
+ if (!entry) {
2488
+ const canonicalRunId = canonicalAgentRunId(runId, "run");
2489
+ const staleProviderInstances = [...agentRunProviderSnapshots.values()]
2490
+ .flatMap((rows) => [...rows.values()])
2491
+ .filter((instance) => instance.runId === canonicalRunId && ["done", "failed", "cancelled"].includes(instance.status));
2492
+ rememberDismissedHelperAgentRunProjections(staleProviderInstances);
2493
+ // Dismiss is idempotent. Force a fresh empty projection so a server that
2494
+ // still has the previous terminal snapshot can clear it immediately.
2495
+ lastPublishedSubagentSignature = "";
2496
+ lastPublishedSubagentAt = 0;
2497
+ lastPublishedAgentRunSignature = "";
2498
+ lastPublishedAgentRunAt = 0;
2499
+ publishSubagentStatus();
2500
+ return { runId, dismissed: true, alreadyMissing: true };
2501
+ }
2329
2502
  if (entry.run.status === "running") throw new Error(`Cannot dismiss running subagent run: ${runId}`);
2330
2503
  rememberDismissedHelperAgentRunProjections(canonicalInstancesFromPublicRun(entry.run, new Set()));
2331
2504
  entry.runs.delete(entry.key);
@@ -2408,6 +2581,21 @@ export default function webuiRpcHelper(pi) {
2408
2581
  }
2409
2582
  }
2410
2583
 
2584
+ pi.registerTool({
2585
+ name: "approve_subagent_model_deviation",
2586
+ label: "Approve reviewer model deviation",
2587
+ description: "Request interactive user confirmation for one short-lived, one-use local permit covering an explicit reviewer model mismatch. The confirmation identifies the exact reviewer occurrence and requested model.",
2588
+ promptSnippet: "Request confirmation for one reviewer model deviation",
2589
+ promptGuidelines: [
2590
+ "Call approve_subagent_model_deviation only after the user explicitly authorizes that exact reviewer occurrence and requested model; never infer authorization from task text or use it merely to bypass a mismatch block. The tool still displays an interactive confirmation and fails closed without UI or on rejection.",
2591
+ "The permit is local, expires after 2 minutes, and is consumed by one admitted structured launch or leased into one workflow wrapper.",
2592
+ ],
2593
+ parameters: SubagentModelDeviationParams,
2594
+ async execute(_toolCallId, params) {
2595
+ return approveSubagentModelDeviation(params);
2596
+ },
2597
+ });
2598
+
2411
2599
  pi.registerCommand(HELPER_COMMAND, {
2412
2600
  description: "Internal Web UI helper for browser-native tools and skills configuration",
2413
2601
  handler: async (args, ctx) => {
@@ -2451,6 +2639,7 @@ export default function webuiRpcHelper(pi) {
2451
2639
  resourceRpcActive = ctx.mode === "rpc";
2452
2640
  if (resourceRpcActive) await recomputeResourceState(ctx);
2453
2641
  restoreSamplingParamsFromBranch(ctx);
2642
+ await loadSubagentLaunchSlotGuidance(ctx);
2454
2643
  subagentContext = ctx;
2455
2644
  subagentPollGeneration += 1;
2456
2645
  foregroundSubagentRuns.clear();
@@ -2473,6 +2662,29 @@ export default function webuiRpcHelper(pi) {
2473
2662
  await recomputeResourceState(ctx, event.model);
2474
2663
  });
2475
2664
 
2665
+ pi.on("tool_call", (event) => {
2666
+ if (!["subagent", "subagent_gate"].includes(event.toolName)) return;
2667
+ const deviations = subagentModelDeviationDescriptors();
2668
+ if (!subagentLaunchSlotRoles) {
2669
+ if (subagentLaunchSlotSnapshotLoadFailed && launchNeedsLoadedSlotSnapshot(event.toolName, event.input)) {
2670
+ return {
2671
+ block: true,
2672
+ reason: "Reviewer launch policy is unavailable because the WebUI launch-slot snapshot could not be loaded. Reload the active tab after fixing settings before launching reviewers or workflows.",
2673
+ };
2674
+ }
2675
+ return;
2676
+ }
2677
+ const report = applySubagentLaunchSlotDefaults(event.toolName, event.input, subagentLaunchSlotRoles, { deviations });
2678
+ if (report.blocked.length) {
2679
+ return { block: true, reason: reviewerModelPolicyBlockReason(report.blocked) };
2680
+ }
2681
+ const workflowWrapped = report.applied.some((item) => item.location === "workflowScript" && item.reason === "runtime-role-defaults");
2682
+ removeSubagentModelDeviationPermits(workflowWrapped
2683
+ ? deviations.map((deviation) => deviation.id)
2684
+ : report.consumedDeviationIds);
2685
+ return undefined;
2686
+ });
2687
+
2476
2688
  pi.on("tool_execution_start", (event, ctx) => {
2477
2689
  if (event.toolName !== "subagent" || event.args?.action) return;
2478
2690
  const id = subagentText(event.toolCallId, 160);
@@ -2578,6 +2790,11 @@ export default function webuiRpcHelper(pi) {
2578
2790
  resourceGeneration += 1;
2579
2791
  subagentContext = null;
2580
2792
  subagentLaunchSlotGuidance = "";
2793
+ subagentLaunchSlotRoles = null;
2794
+ subagentLaunchSlotSnapshotLoadFailed = false;
2795
+ activeSubagentLaunchSlotRevision = null;
2796
+ subagentLaunchSlotGeneration += 1;
2797
+ clearSubagentModelDeviationPermits();
2581
2798
  subagentPollGeneration += 1;
2582
2799
  clearTimeout(subagentPollTimer);
2583
2800
  subagentPollTimer = null;