@firstpick/pi-package-webui 0.9.6 → 0.9.8

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 (70) hide show
  1. package/README.md +13 -5
  2. package/bin/pi-webui.mjs +480 -96
  3. package/index.ts +2 -1
  4. package/lib/git-workflow-preferences.mjs +21 -1
  5. package/lib/optional-feature-catalog.mjs +1 -1
  6. package/lib/session-tree-event-targets.mjs +70 -0
  7. package/lib/subagent-launch-policy.mjs +375 -0
  8. package/lib/subagent-launch-slots.mjs +2 -1
  9. package/package.json +1 -1
  10. package/public/app.js +1348 -131
  11. package/public/guided-git-command-state.mjs +175 -1
  12. package/public/index.html +48 -9
  13. package/public/service-worker.js +1 -1
  14. package/public/styles.css +387 -34
  15. package/public/transcript-renderer.mjs +62 -0
  16. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  17. package/tests/browser/control-visibility.spec.mjs +141 -2
  18. package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
  19. package/tests/browser/footer-model-advanced-layout.spec.mjs +512 -0
  20. package/tests/browser/guided-git-extension-command.spec.mjs +180 -0
  21. package/tests/browser/guided-git-fallback.spec.mjs +218 -0
  22. package/tests/browser/interaction-continuity.spec.mjs +33 -0
  23. package/tests/codex-fast-mode-static.test.mjs +2 -2
  24. package/tests/compact-sections-static.test.mjs +4 -0
  25. package/tests/compaction-static.test.mjs +1 -1
  26. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  27. package/tests/control-visibility-static.test.mjs +66 -3
  28. package/tests/controls-layout-static.test.mjs +3 -3
  29. package/tests/events-tree-context-menu-static.test.mjs +131 -0
  30. package/tests/fast-mode-client-static.test.mjs +5 -2
  31. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  32. package/tests/file-viewer-image-static.test.mjs +3 -3
  33. package/tests/fixtures/fake-pi.mjs +34 -3
  34. package/tests/git-footer-context-menu-static.test.mjs +103 -1
  35. package/tests/git-workflow-preferences.test.mjs +30 -1
  36. package/tests/guided-git-activation-http.test.mjs +194 -0
  37. package/tests/guided-git-activation-static.test.mjs +80 -0
  38. package/tests/guided-git-activation.test.mjs +244 -0
  39. package/tests/guided-git-fallback-runtime.test.mjs +419 -0
  40. package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
  41. package/tests/guided-git-message-reliability-static.test.mjs +9 -7
  42. package/tests/guided-git-optional-feature.test.mjs +31 -0
  43. package/tests/http-endpoints-harness.test.mjs +3 -0
  44. package/tests/interaction-state-stability-static.test.mjs +1 -1
  45. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  46. package/tests/main-output-loading-static.test.mjs +11 -9
  47. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  48. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  49. package/tests/mobile-foundation-static.test.mjs +3 -3
  50. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  51. package/tests/mobile-static.test.mjs +92 -9
  52. package/tests/open-issue-wizard-static.test.mjs +1 -1
  53. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  54. package/tests/prompt-input-vertical-scroll-static.test.mjs +6 -6
  55. package/tests/prompt-routing-input-clear-static.test.mjs +1 -1
  56. package/tests/questionnaire-dialog.test.mjs +3 -3
  57. package/tests/remote-auth-settings-harness.test.mjs +23 -0
  58. package/tests/resource-defaults-helper.test.mjs +12 -0
  59. package/tests/session-sampling-helper.test.mjs +1 -0
  60. package/tests/session-sampling-ui-static.test.mjs +3 -3
  61. package/tests/session-tree-event-targets.test.mjs +106 -0
  62. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  63. package/tests/subagent-launch-policy.test.mjs +532 -0
  64. package/tests/subagent-observability-static.test.mjs +2 -2
  65. package/tests/subagents-helper.test.mjs +211 -1
  66. package/tests/syntax-highlighting-static.test.mjs +3 -3
  67. package/tests/tab-close-continuity-static.test.mjs +25 -0
  68. package/tests/theme-customizer-static.test.mjs +1 -1
  69. package/tests/thinking-block-grouping.test.mjs +79 -0
  70. 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-v139"/, "adding a startup module should advance the PWA cache identity");
64
+ assert.match(html, /styles\.css\?v=142/, "new token styles should advance the stylesheet revision");
65
+ assert.match(html, /data-app-src="\/app\.js\?v=172"/, "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,25 @@
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
+ assert.match(closeTabs, /addEvent\(`closed \$\{closedIds\.length \|\| targetTabs\.length\} terminal \$\{closedIds\.length === 1 \? "tab" : "tabs"\}`, "info"\)/, "successful terminal tab closure should be recorded as information rather than a warning");
23
+ assert.doesNotMatch(closeTabs, /addEvent\(`closed [^`]+`, "warn"\)/, "successful terminal tab closure should never be classified as a warning");
24
+
25
+ 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-v139"/, "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");
@@ -0,0 +1,79 @@
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
+ import { groupConsecutiveThinkingItems, groupConsecutiveThinkingMessages } from "../public/transcript-renderer.mjs";
6
+
7
+ function thinking(content, timestamp) {
8
+ return { role: "thinking", title: "thinking", content, thinking: content, timestamp };
9
+ }
10
+
11
+ const first = thinking("inspect the renderer", "2026-08-23T13:00:00Z");
12
+ assert.equal(groupConsecutiveThinkingMessages([first])[0], first, "a single thinking message should retain its identity");
13
+
14
+ const grouped = groupConsecutiveThinkingMessages([
15
+ first,
16
+ thinking("confirm the display order", "2026-08-23T13:00:01Z"),
17
+ thinking("verify the final state", "2026-08-23T13:00:02Z"),
18
+ ]);
19
+ assert.equal(grouped.length, 1, "adjacent thinking messages should render as one transcript message");
20
+ assert.equal(grouped[0].thinking, "inspect the renderer\n\nconfirm the display order\n\nverify the final state", "grouped thinking should remain chronological and readable");
21
+ assert.equal(grouped[0].content, grouped[0].thinking, "copy and rendering paths should receive the same grouped text");
22
+ assert.equal(grouped[0].timestamp, first.timestamp, "the grouped message should keep the first block's stable metadata");
23
+ assert.equal(grouped[0].thinkingSegmentCount, 3, "the aggregate should retain its source segment count");
24
+
25
+ const toolCall = { role: "toolCall", toolName: "read", content: {} };
26
+ const separated = groupConsecutiveThinkingMessages([
27
+ thinking("before the tool"),
28
+ toolCall,
29
+ thinking("after the tool"),
30
+ thinking("still after the tool"),
31
+ ]);
32
+ assert.deepEqual(separated.map((message) => message.role), ["thinking", "toolCall", "thinking"], "non-thinking transcript messages should remain hard grouping boundaries");
33
+ assert.equal(separated[0].thinking, "before the tool");
34
+ assert.equal(separated[2].thinking, "after the tool\n\nstill after the tool");
35
+
36
+ const nonTextThinking = { role: "thinking", content: { provider: "opaque" } };
37
+ assert.deepEqual(
38
+ groupConsecutiveThinkingMessages([thinking("before"), nonTextThinking, thinking("after")]),
39
+ [thinking("before"), nonTextThinking, thinking("after")],
40
+ "non-text thinking payloads should not be stringified or merged",
41
+ );
42
+
43
+ function assistantItem(index, content) {
44
+ return {
45
+ message: { role: "assistant", timestamp: `2026-08-23T13:00:0${index}Z`, content: [{ type: "thinking", thinking: content }] },
46
+ messageIndex: index,
47
+ order: index,
48
+ };
49
+ }
50
+
51
+ const separateAssistantMessages = [
52
+ assistantItem(1, "first assistant message"),
53
+ assistantItem(2, "second assistant message"),
54
+ assistantItem(3, "third assistant message"),
55
+ ];
56
+ const groupedItems = groupConsecutiveThinkingItems(separateAssistantMessages, (item) => {
57
+ const part = item.message.content[0];
58
+ return thinking(part.thinking, item.message.timestamp);
59
+ });
60
+ assert.equal(groupedItems.length, 1, "thinking-only assistant messages should collapse after transcript ordering");
61
+ assert.equal(groupedItems[0].message.thinking, "first assistant message\n\nsecond assistant message\n\nthird assistant message");
62
+ assert.equal(groupedItems[0].thinkingGroupSourceCount, 3, "the transcript aggregate should retain its source item count");
63
+
64
+ const finalOutputItem = { message: { role: "assistant", content: [{ type: "text", text: "answer" }] }, messageIndex: 4, order: 4 };
65
+ const itemBoundary = groupConsecutiveThinkingItems(
66
+ [assistantItem(1, "before"), finalOutputItem, assistantItem(2, "after")],
67
+ (item) => item.message.content[0]?.type === "thinking" ? thinking(item.message.content[0].thinking) : null,
68
+ );
69
+ assert.deepEqual(itemBoundary.map((item) => item.message.role), ["assistant", "assistant", "assistant"], "a rendered final-output item should keep separate thinking runs apart");
70
+
71
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
72
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
73
+ assert.match(app, /import \{ createTranscriptRenderer, groupConsecutiveThinkingItems, groupConsecutiveThinkingMessages \} from "\.\/transcript-renderer\.mjs";/, "the browser should import both grouping helpers from the transcript renderer");
74
+ assert.match(app, /function assistantDisplayMessages\(message\)[\s\S]*?const displayMessages = assistantDisplayMessagesWithoutFailure[\s\S]*?return groupConsecutiveThinkingMessages\(failure \? \[\.\.\.displayMessages, failure\] : displayMessages\);/, "assistant display projection should group adjacent thinking inside one assistant message");
75
+ assert.match(app, /function transcriptItemThinkingMessage\(item\)[\s\S]*?assistantDisplayMessages\(message\)[\s\S]*?displayMessages\.length !== 1[\s\S]*?role !== "thinking"/, "only transcript items that render as one thinking card should be eligible for cross-message grouping");
76
+ assert.match(app, /function groupConsecutiveThinkingTranscriptItems\(items\)[\s\S]*?groupConsecutiveThinkingItems\(items, transcriptItemThinkingMessage\)[\s\S]*?transcriptKey: `thinking-group:\$\{sourceKey\}`/, "cross-message groups should receive one stable transcript identity");
77
+ assert.match(app, /const groupedThinking = compactOutputActive\(\) \? ordered : groupConsecutiveThinkingTranscriptItems\(ordered\);[\s\S]*?groupWorkflowStatusTranscriptItems\(groupedThinking, toolResults\)/, "normal transcripts should group thinking after complete chronological ordering");
78
+
79
+ console.log("thinking-block-grouping.test.mjs passed");