@firstpick/pi-package-webui 0.9.5 → 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 (82) hide show
  1. package/README.md +11 -5
  2. package/bin/pi-webui.mjs +457 -77
  3. package/lib/git-workflow-preferences.mjs +21 -1
  4. package/lib/optional-feature-catalog.mjs +1 -1
  5. package/lib/session-actions.mjs +20 -2
  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 +2539 -292
  11. package/public/index.html +87 -31
  12. package/public/service-worker.js +4 -1
  13. package/public/stream-derived-output.mjs +799 -0
  14. package/public/stream-markdown-tail.mjs +204 -0
  15. package/public/stream-output-controller.mjs +193 -51
  16. package/public/stream-render-scheduler.mjs +85 -0
  17. package/public/styles.css +501 -19
  18. package/public/transcript-renderer.mjs +73 -24
  19. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  20. package/tests/browser/composer-action-grid-reorder.spec.mjs +114 -31
  21. package/tests/browser/control-visibility.spec.mjs +141 -2
  22. package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
  23. package/tests/browser/guided-git-fallback.spec.mjs +153 -0
  24. package/tests/browser/mobile-foundation.spec.mjs +28 -0
  25. package/tests/browser/stream-output-isolation.spec.mjs +308 -3
  26. package/tests/browser/user-noticeable-fixes.spec.mjs +204 -0
  27. package/tests/codex-fast-mode-static.test.mjs +2 -2
  28. package/tests/compact-sections-static.test.mjs +4 -0
  29. package/tests/composer-action-grid-reorder-static.test.mjs +8 -7
  30. package/tests/control-visibility-static.test.mjs +66 -3
  31. package/tests/controls-layout-static.test.mjs +3 -3
  32. package/tests/cwd-footer-reliability-static.test.mjs +1 -1
  33. package/tests/events-tree-context-menu-static.test.mjs +131 -0
  34. package/tests/fast-mode-client-static.test.mjs +5 -2
  35. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  36. package/tests/file-viewer-image-static.test.mjs +3 -3
  37. package/tests/fixtures/fake-pi.mjs +57 -10
  38. package/tests/fixtures/streaming-workloads.mjs +36 -0
  39. package/tests/footer-provider-usage-visual-static.test.mjs +15 -0
  40. package/tests/foreground-transcript-catch-up-static.test.mjs +7 -1
  41. package/tests/git-workflow-preferences.test.mjs +30 -1
  42. package/tests/guided-git-fallback-runtime.test.mjs +418 -0
  43. package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
  44. package/tests/guided-git-message-reliability-static.test.mjs +8 -7
  45. package/tests/interaction-state-stability-static.test.mjs +3 -1
  46. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  47. package/tests/intercom-conversations-http.test.mjs +16 -0
  48. package/tests/main-output-loading-static.test.mjs +3 -3
  49. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  50. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  51. package/tests/mobile-foundation-static.test.mjs +3 -3
  52. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  53. package/tests/mobile-static.test.mjs +80 -67
  54. package/tests/open-issue-wizard-static.test.mjs +1 -1
  55. package/tests/persistent-ui-layout-static.test.mjs +4 -4
  56. package/tests/prompt-input-vertical-scroll-static.test.mjs +26 -0
  57. package/tests/questionnaire-dialog.test.mjs +3 -3
  58. package/tests/remote-auth-settings-harness.test.mjs +23 -0
  59. package/tests/resource-defaults-helper.test.mjs +12 -0
  60. package/tests/runtime-error-visibility.test.mjs +3 -3
  61. package/tests/session-auth-harness.test.mjs +26 -1
  62. package/tests/session-sampling-helper.test.mjs +1 -0
  63. package/tests/session-sampling-ui-static.test.mjs +3 -3
  64. package/tests/session-tree-event-targets.test.mjs +106 -0
  65. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  66. package/tests/stream-derived-output.test.mjs +121 -0
  67. package/tests/stream-markdown-tail.test.mjs +218 -0
  68. package/tests/stream-output-controller.test.mjs +119 -4
  69. package/tests/stream-output-isolation-static.test.mjs +27 -6
  70. package/tests/stream-output-workloads.test.mjs +40 -3
  71. package/tests/stream-render-scheduler.test.mjs +115 -0
  72. package/tests/streaming-ui-coupling.test.mjs +1 -1
  73. package/tests/subagent-launch-policy.test.mjs +532 -0
  74. package/tests/subagent-observability-static.test.mjs +2 -2
  75. package/tests/subagents-helper.test.mjs +211 -1
  76. package/tests/syntax-highlighting-static.test.mjs +3 -3
  77. package/tests/tab-close-continuity-static.test.mjs +23 -0
  78. package/tests/theme-customizer-static.test.mjs +1 -1
  79. package/tests/thinking-format-parser.test.mjs +15 -0
  80. package/tests/todo-filter-static.test.mjs +148 -0
  81. package/tests/transcript-markdown-tail.test.mjs +137 -0
  82. 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-v115"/, "adding a startup module should advance the PWA cache identity");
64
- assert.match(html, /styles\.css\?v=129/, "new token styles should advance the stylesheet revision");
65
- assert.match(html, /data-app-src="\/app\.js\?v=150"/, "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-v115"/, "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");
@@ -3,6 +3,7 @@ import { readFile } from "node:fs/promises";
3
3
  import vm from "node:vm";
4
4
  import { dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { splitThinkingFormatTextAuthoritative } from "../public/stream-derived-output.mjs";
6
7
 
7
8
  const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
9
  const app = await readFile(join(root, "public", "app.js"), "utf8");
@@ -61,4 +62,18 @@ assert.deepEqual(parse("<|analysis>channel reasoning<analysis|>\nanswer"), {
61
62
  complete: true,
62
63
  }, "channel-style thinking delimiters should remain unchanged");
63
64
 
65
+ for (const [text, options] of [
66
+ ["<th", { streaming: true }],
67
+ ["<think>reasoning</thi", { streaming: true }],
68
+ ["<think>first</think><th", { streaming: true }],
69
+ ["<think>first</think><think>second</think>\r\nanswer", { streaming: true }],
70
+ ["<|Analysis>Unicode 😀<ANALYSIS|>\nanswer", { streaming: true }],
71
+ ]) {
72
+ assert.deepEqual(
73
+ parse(text, options),
74
+ JSON.parse(JSON.stringify(splitThinkingFormatTextAuthoritative(text, options))),
75
+ `stream-derived authoritative parsing should stay aligned for ${JSON.stringify(text)}`,
76
+ );
77
+ }
78
+
64
79
  console.log("thinking-format-parser.test.mjs passed");
@@ -0,0 +1,148 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import vm from "node:vm";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { stripTodoProgressLinesAuthoritative } from "../public/stream-derived-output.mjs";
7
+
8
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
9
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
10
+
11
+ // Extract the contiguous region containing textLines and stripTodoProgressLines.
12
+ // textLines is a shared helper; stripTodoProgressLines references it and the
13
+ // todo-progress regex constants. The region ends at the next function boundary.
14
+ const textLinesStart = app.indexOf("\nfunction textLines(");
15
+ assert.ok(textLinesStart >= 0, "textLines helper should exist in app.js");
16
+ const nextFnAfterStrip = app.indexOf("\nfunction parseTodoProgressItemLine(", textLinesStart);
17
+ assert.ok(nextFnAfterStrip > textLinesStart, "parseTodoProgressItemLine should follow stripTodoProgressLines");
18
+ const todoFilterRegion = app.slice(textLinesStart, nextFnAfterStrip);
19
+
20
+ // Also need the regex constants from the module-level scope.
21
+ assert.ok(app.includes("const TODO_PROGRESS_LINE_REGEX = "), "TODO_PROGRESS_LINE_REGEX should be defined");
22
+ assert.ok(app.includes("const TODO_PROGRESS_PARTIAL_LINE_REGEX = "), "TODO_PROGRESS_PARTIAL_LINE_REGEX should be defined");
23
+
24
+ // VM context: provide the regex constants and stub isOptionalFeatureDetected.
25
+ const context = {
26
+ TODO_PROGRESS_LINE_REGEX: /^\s*(?:(?:[-*]|\d+[.)])\s*)?\[(?: |x|X|-)\]\s+.+$/,
27
+ TODO_PROGRESS_PARTIAL_LINE_REGEX: /^\s*(?:(?:[-*]|\d+[.)])\s*)?\[(?: |x|X|-)?\]?\s*.*$/,
28
+ isOptionalFeatureDetected: () => true,
29
+ };
30
+ vm.runInNewContext(
31
+ `${todoFilterRegion}\nthis.stripTodoProgressLines = stripTodoProgressLines;`,
32
+ context,
33
+ { filename: "todo-filter-helpers.js" },
34
+ );
35
+
36
+ function appStrip(text, options) {
37
+ return context.stripTodoProgressLines(text, options);
38
+ }
39
+
40
+ /**
41
+ * Representative cases for todo-progress line filtering equivalence:
42
+ * - todo lines with all markers: [ ], [x], [X], [-]
43
+ * - ordered/unordered/numeric prefixes: * [ ], - [ ], 1. [ ]
44
+ * - partial todo tails with and without trailing newline
45
+ * - fenced code containing todo-like lines
46
+ * - CRLF normalization
47
+ * - blank-line collapsing
48
+ * - Unicode
49
+ * - feature-disabled passthrough
50
+ */
51
+ const representativeCases = [
52
+ // Simple todo lines with all markers
53
+ { text: "- [ ] pending\n- [x] done\n- [-] partial\n- [X] done caps\nfinal", opts: { streaming: true } },
54
+ // Ordered/numeric prefixes
55
+ { text: "Goal: steps\n* [ ] task one\n- [x] task two\n1. [ ] task three\n4) [ ] task four\nfinal", opts: { streaming: true } },
56
+ // Partial todo tails without trailing newline (streaming)
57
+ { text: "Goal: ship\n- [", opts: { streaming: true } },
58
+ // Partial todo tails with trailing newline
59
+ { text: "Goal: ship\n- [\nvisible", opts: { streaming: true } },
60
+ // Partial todo tails with incomplete markers
61
+ { text: "Goal: ship\n- [x", opts: { streaming: true } },
62
+ { text: "Some text\n- [ ] partial item", opts: { streaming: true } },
63
+ { text: "Some text\n- [ ] partial item\n", opts: { streaming: true } },
64
+ // Fenced code containing todo-like lines
65
+ { text: "```md\n- [ ] literal checklist\n```\n- [ ] transport\nAnswer", opts: { streaming: true } },
66
+ // Nested fences and edge cases
67
+ { text: "```\n- [ ] inside\n```` still code\n```\nafter\n- [ ] filtered", opts: { streaming: true } },
68
+ // CRLF
69
+ { text: "Goal: ship\r\n- [ ] first\r\n- [x] second\r\n- [-] third\r\nAnswer", opts: { streaming: true } },
70
+ { text: "Goal: ship\r\n- [ ] first\r\nAnswer\r\n- [x] leftover", opts: { streaming: true } },
71
+ // Blank-line collapsing
72
+ { text: "- [ ] filtered\n\n\n\nvisible\n\n\n- [x] filtered\n\nkeep", opts: { streaming: true } },
73
+ // Unicode
74
+ { text: "😀 live\n- [ ] 隐藏\n- [x] 完成\n🚀 final", opts: { streaming: true } },
75
+ // Unicode with code fence
76
+ { text: "```émoji\n- [ ] literal\n```\n- [ ] transport\nfinal 🌟", opts: { streaming: true } },
77
+ // No todo lines at all (passthrough)
78
+ { text: "Plain assistant output with no derived markers.", opts: { streaming: true } },
79
+ // Empty string
80
+ { text: "", opts: { streaming: true } },
81
+ // Only todo lines
82
+ { text: "- [ ] only todos\n- [x] all filtered", opts: { streaming: true } },
83
+ // Streaming=false (complete output)
84
+ { text: "- [ ] line\nvisible", opts: { streaming: false } },
85
+ // Feature-disabled passthrough (isOptionalFeatureDetected returns false)
86
+ { text: "- [ ] visible when todo feature is absent\n- [x] also visible", opts: { streaming: true, _featureDisabled: true } },
87
+ // Partial incomplete fence
88
+ { text: "```\n- [ ] hidden inside incomplete fence\n", opts: { streaming: true } },
89
+ // Whitespace-prefixed todo lines
90
+ { text: "spaced:\n - [ ] indented\n\t- [x] tabbed\nvisible", opts: { streaming: true } },
91
+ // Consecutive blank-line handling
92
+ { text: "- [ ] filtered\n\nkeep\n\n\n- [x] filtered\nend", opts: { streaming: true } },
93
+ // Single line partial
94
+ { text: "- [ ]", opts: { streaming: true } },
95
+ { text: "- [ ]\n", opts: { streaming: true } },
96
+ ];
97
+
98
+ for (const { text, opts } of representativeCases) {
99
+ const { streaming = false, _featureDisabled = false } = opts || {};
100
+ const appResult = _featureDisabled
101
+ ? (() => {
102
+ // Simulate feature-disabled passthrough without modifying the vm context
103
+ const raw = String(text || "");
104
+ // When isOptionalFeatureDetected returns false, stripTodoProgressLines returns text as-is.
105
+ // Re-create that logic manually since we can't re-run the vm context with a different stub.
106
+ return raw;
107
+ })()
108
+ : appStrip(text, { streaming });
109
+ const authResult = stripTodoProgressLinesAuthoritative(text, { streaming, todoProgressDetected: !_featureDisabled });
110
+
111
+ const label = _featureDisabled
112
+ ? `feature-disabled ${JSON.stringify(text)}`
113
+ : `${JSON.stringify(text)} streaming=${streaming}`;
114
+ assert.deepEqual(appResult, authResult, `app stripTodoProgressLines must match authoritative at ${label}`);
115
+ }
116
+
117
+ // Additional deep-equal checks via vm extraction of a known instance
118
+ // to ensure function bodies produce the exact same string output line by line.
119
+ const targetedCases = [
120
+ ["Goal: ship\r\n- [ ] first\r\n- [x] second\r\nAnswer", { streaming: true }],
121
+ ["Goal: ship\r\n- [ ] first\r\n- [x] second\r\nAnswer", { streaming: false }],
122
+ ["```md\n- [ ] literal\n```\n- [ ] transport\nAnswer", { streaming: true }],
123
+ ["```\n- [ ] one\n```\n- [x] two\nfinal", { streaming: true }],
124
+ ["Alpha\n\n\n- [ ] filtered\n\n\nBeta", { streaming: true }],
125
+ ["😀unicode🌍\n- [ ] hidden\nkeep", { streaming: true }],
126
+ ["", { streaming: true }],
127
+ ["", { streaming: false }],
128
+ ["- [ ]", { streaming: true }],
129
+ ["- [ ] done", { streaming: false }],
130
+ ["- [ ] done\n- [x] all\n- [-] three\nvisible", { streaming: true }],
131
+ // Partial tails without newline
132
+ ["text\n- [", { streaming: true }],
133
+ ["text\n- [x", { streaming: true }],
134
+ ["text\n1. [", { streaming: true }],
135
+ ];
136
+
137
+ for (const [text, opts] of targetedCases) {
138
+ const { streaming = false } = opts || {};
139
+ const appResult = appStrip(text, { streaming });
140
+ const authResult = stripTodoProgressLinesAuthoritative(text, { streaming });
141
+ assert.deepEqual(
142
+ appResult,
143
+ authResult,
144
+ `targeted case should match: ${JSON.stringify(text)} streaming=${streaming}`,
145
+ );
146
+ }
147
+
148
+ console.log("todo-filter-static.test.mjs passed");
@@ -0,0 +1,137 @@
1
+ import assert from "node:assert/strict";
2
+ import { advanceStreamingMarkdownTail } from "../public/stream-markdown-tail.mjs";
3
+ import { createTranscriptRenderer } from "../public/transcript-renderer.mjs";
4
+
5
+ class FakeNode {
6
+ static ELEMENT_NODE = 1;
7
+ static TEXT_NODE = 3;
8
+ constructor(nodeType) {
9
+ this.nodeType = nodeType;
10
+ this.childNodes = [];
11
+ this.parentNode = null;
12
+ this.isConnected = false;
13
+ }
14
+ get firstChild() { return this.childNodes[0] || null; }
15
+ append(...nodes) {
16
+ for (const node of nodes) {
17
+ if (node.nodeType === 11) {
18
+ this.append(...[...node.childNodes]);
19
+ node.childNodes = [];
20
+ continue;
21
+ }
22
+ node.parentNode = this;
23
+ node.isConnected = this.isConnected;
24
+ this.childNodes.push(node);
25
+ }
26
+ }
27
+ remove() {
28
+ if (this.parentNode) this.parentNode.childNodes = this.parentNode.childNodes.filter((node) => node !== this);
29
+ this.parentNode = null;
30
+ this.setConnected(false);
31
+ }
32
+ setConnected(value) {
33
+ this.isConnected = value;
34
+ for (const child of this.childNodes) child.setConnected(value);
35
+ }
36
+ }
37
+
38
+ class FakeText extends FakeNode {
39
+ constructor(data = "") { super(FakeNode.TEXT_NODE); this.data = data; }
40
+ appendData(value) { this.data += value; }
41
+ }
42
+
43
+ class FakeElement extends FakeNode {
44
+ constructor() { super(FakeNode.ELEMENT_NODE); this.dataset = {}; }
45
+ addEventListener() {}
46
+ closest() { return null; }
47
+ matches() { return false; }
48
+ querySelectorAll() { return []; }
49
+ contains(candidate) {
50
+ if (candidate === this) return true;
51
+ return this.childNodes.some((child) => child === candidate || (child.contains?.(candidate) ?? false));
52
+ }
53
+ }
54
+
55
+ class FakeFragment extends FakeNode {
56
+ constructor() { super(11); }
57
+ }
58
+
59
+ globalThis.Node = FakeNode;
60
+ globalThis.document = {
61
+ addEventListener() {},
62
+ createDocumentFragment: () => new FakeFragment(),
63
+ createTextNode: (value) => new FakeText(value),
64
+ createElement: () => new FakeElement(),
65
+ };
66
+ globalThis.window = {
67
+ addEventListener() {},
68
+ getSelection: () => ({ rangeCount: 0, isCollapsed: true }),
69
+ };
70
+
71
+ const chat = new FakeElement();
72
+ chat.setConnected(true);
73
+ const surface = new FakeElement();
74
+ chat.append(surface);
75
+ const renderer = createTranscriptRenderer({ chat });
76
+ let liveCreates = 0;
77
+ let liveAppends = 0;
78
+ let authoritativeRenders = 0;
79
+
80
+ const options = {
81
+ surface,
82
+ messageKey: "live:test",
83
+ kind: "assistant-final",
84
+ stableBoundary: (text, state, advanceOptions) => advanceStreamingMarkdownTail(state, text, advanceOptions),
85
+ renderInto(parent, text) {
86
+ authoritativeRenders += 1;
87
+ const block = new FakeElement();
88
+ block.append(new FakeText(text));
89
+ parent.append(block);
90
+ },
91
+ renderLiveTail(parent, tail) {
92
+ liveCreates += 1;
93
+ const block = new FakeElement();
94
+ block.append(new FakeText(tail));
95
+ parent.append(block);
96
+ },
97
+ appendLiveTail(nodes, previousTail, tail) {
98
+ liveAppends += 1;
99
+ nodes[0].firstChild.appendData(tail.slice(previousTail.length));
100
+ },
101
+ };
102
+
103
+ const first = renderer.reconcileMarkdownSurface({ ...options, text: "```js\none" });
104
+ const mountedTail = surface.firstChild;
105
+ assert.equal(first.liveMode, "open-fence");
106
+ assert.equal(liveCreates, 1);
107
+ assert.equal(authoritativeRenders, 0, "an incomplete fence must not run authoritative Markdown/tokenization");
108
+
109
+ const second = renderer.reconcileMarkdownSurface({ ...options, text: "```js\nonetwo" });
110
+ assert.equal(second.reusedTail, true);
111
+ assert.equal(surface.firstChild, mountedTail, "live open-fence appends must retain the mounted tail node identity");
112
+ assert.equal(liveCreates, 1);
113
+ assert.equal(liveAppends, 1);
114
+ assert.equal(authoritativeRenders, 0);
115
+
116
+ const closedText = "```js\nonetwo\n```";
117
+ renderer.reconcileMarkdownSurface({ ...options, text: closedText });
118
+ assert.equal(authoritativeRenders, 1, "closing the fence must perform one authoritative highlighted render");
119
+ assert.notEqual(surface.firstChild, mountedTail);
120
+ const highlightedTail = surface.firstChild;
121
+
122
+ renderer.reconcileMarkdownSurface({ ...options, text: closedText, complete: true });
123
+ assert.equal(authoritativeRenders, 1, "explicit completion must promote an already authoritative close without highlighting twice");
124
+ assert.equal(surface.firstChild, highlightedTail, "authoritative completion must preserve the completed block identity");
125
+
126
+ const longPlain = "x".repeat(16 * 1024 + 1);
127
+ renderer.reconcileMarkdownSurface({ ...options, text: longPlain });
128
+ assert.equal(surface.firstChild.firstChild.data, longPlain);
129
+ renderer.reconcileMarkdownSurface({ ...options, text: longPlain, complete: true });
130
+ assert.equal(authoritativeRenders, 2, "completion must replace the cheap long-tail representation with authoritative Markdown");
131
+
132
+ const incompleteFence = "```js\nunfinished";
133
+ renderer.reconcileMarkdownSurface({ ...options, text: incompleteFence });
134
+ renderer.reconcileMarkdownSurface({ ...options, text: incompleteFence, complete: true });
135
+ assert.equal(authoritativeRenders, 3, "completion must authoritatively tokenize even an unclosed fence exactly once");
136
+
137
+ console.log("transcript-markdown-tail.test.mjs passed");