@firstpick/pi-package-webui 0.9.2 → 0.9.4

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 (78) hide show
  1. package/README.md +14 -8
  2. package/bin/pi-webui.mjs +256 -39
  3. package/index.ts +266 -1
  4. package/lib/git-workflow-preferences.mjs +8 -25
  5. package/lib/intercom-conversations.mjs +491 -0
  6. package/lib/intercom-transcript-filter.mjs +99 -0
  7. package/lib/resource-selection.mjs +140 -0
  8. package/package.json +2 -2
  9. package/public/app.js +1061 -119
  10. package/public/index.html +31 -6
  11. package/public/service-worker.js +2 -1
  12. package/public/stream-output-controller.mjs +15 -0
  13. package/public/styles.css +426 -1
  14. package/public/syntax-highlight.mjs +622 -0
  15. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  16. package/tests/browser/interaction-continuity.spec.mjs +34 -0
  17. package/tests/browser/intercom-conversation-viewer.spec.mjs +357 -0
  18. package/tests/browser/persistent-ui-layout.spec.mjs +61 -0
  19. package/tests/browser/resource-profiles.spec.mjs +200 -0
  20. package/tests/browser/subagent-observability.spec.mjs +29 -0
  21. package/tests/codex-fast-mode-static.test.mjs +7 -6
  22. package/tests/common-options-submenus-interaction-static.test.mjs +2 -0
  23. package/tests/common-options-submenus-markup-static.test.mjs +1 -0
  24. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  25. package/tests/composer-skill-tag-layout.test.mjs +32 -2
  26. package/tests/control-deck-component-updates-static.test.mjs +4 -0
  27. package/tests/controls-layout-static.test.mjs +3 -3
  28. package/tests/fast-mode-client-static.test.mjs +2 -2
  29. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  30. package/tests/feature-system-prompt-optional-feature-static.test.mjs +5 -5
  31. package/tests/file-viewer-image-static.test.mjs +69 -0
  32. package/tests/fixtures/fake-pi.mjs +105 -6
  33. package/tests/foreground-transcript-catch-up-static.test.mjs +1 -1
  34. package/tests/git-panel-file-preview-static.test.mjs +5 -5
  35. package/tests/git-panel-live-updates-static.test.mjs +3 -3
  36. package/tests/git-workflow-preferences.test.mjs +4 -4
  37. package/tests/http-endpoints-harness.test.mjs +124 -2
  38. package/tests/intercom-conversation-viewer-static.test.mjs +106 -0
  39. package/tests/intercom-conversations-http.test.mjs +252 -0
  40. package/tests/intercom-conversations.test.mjs +374 -0
  41. package/tests/intercom-main-transcript-suppression-static.test.mjs +52 -0
  42. package/tests/intercom-tag-layout-static.test.mjs +46 -0
  43. package/tests/intercom-transcript-filter.test.mjs +98 -0
  44. package/tests/main-output-loading-static.test.mjs +59 -0
  45. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  46. package/tests/mobile-compact-layout.test.mjs +2 -3
  47. package/tests/mobile-continuity-tablet-static.test.mjs +6 -6
  48. package/tests/mobile-foundation-static.test.mjs +3 -3
  49. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  50. package/tests/mobile-static.test.mjs +66 -42
  51. package/tests/native-parity.test.mjs +8 -7
  52. package/tests/open-issue-wizard-static.test.mjs +1 -1
  53. package/tests/optional-feature-migration-frontend.test.mjs +5 -5
  54. package/tests/optional-feature-resource-setup-static.test.mjs +29 -0
  55. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  56. package/tests/questionnaire-dialog.test.mjs +3 -3
  57. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  58. package/tests/resource-defaults-helper.test.mjs +60 -6
  59. package/tests/resource-selection.test.mjs +114 -0
  60. package/tests/resource-tui-extension.test.mjs +23 -0
  61. package/tests/session-sampling-ui-static.test.mjs +3 -3
  62. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  63. package/tests/stream-output-controller.test.mjs +8 -0
  64. package/tests/stream-output-isolation-static.test.mjs +2 -2
  65. package/tests/streaming-ui-coupling.test.mjs +5 -0
  66. package/tests/subagent-gate-visibility.test.mjs +1 -1
  67. package/tests/subagent-launch-slots.test.mjs +1 -1
  68. package/tests/subagent-observability-static.test.mjs +5 -3
  69. package/tests/subagent-reliability-integration.test.mjs +23 -1
  70. package/tests/subagent-workflow-section-static.test.mjs +67 -0
  71. package/tests/subagents-helper.test.mjs +313 -1
  72. package/tests/syntax-highlight.test.mjs +235 -0
  73. package/tests/syntax-highlighting-static.test.mjs +84 -0
  74. package/tests/terminal-cwd-grouping-static.test.mjs +22 -0
  75. package/tests/theme-customizer-static.test.mjs +5 -5
  76. package/tests/thinking-format-parser.test.mjs +64 -0
  77. package/tests/webui-settings-locking.test.mjs +1 -1
  78. package/webui-rpc-helper.mjs +417 -74
@@ -121,6 +121,21 @@ await writeFile(asyncStatusFile, JSON.stringify({
121
121
  { agent: "reviewer", status: "running", model: "openai-codex/gpt-5.6-sol", thinking: "high" },
122
122
  ],
123
123
  }));
124
+ const gateAsyncRunDir = await mkdtemp(path.join(asyncRunDir, "gate-"));
125
+ const gateSessionFile = path.join(gateAsyncRunDir, "scout-session.jsonl");
126
+ await writeFile(gateSessionFile, `${JSON.stringify({
127
+ type: "message",
128
+ timestamp: "2026-07-19T12:00:10.000Z",
129
+ message: { role: "assistant", content: [{ type: "text", text: "Gate child output is live." }] },
130
+ })}\n`);
131
+ await writeFile(path.join(gateAsyncRunDir, "status.json"), JSON.stringify({
132
+ runId: "recovered-gate-run",
133
+ mode: "single",
134
+ state: "running",
135
+ startedAt: Date.now() - 500,
136
+ lastUpdate: Date.now(),
137
+ steps: [{ agent: "scout", status: "running", sessionFile: gateSessionFile, currentTool: "read", model: "openai-codex/gpt-5.6-terra:xhigh", thinking: "xhigh" }],
138
+ }));
124
139
 
125
140
  const statusText = `Active async runs: 2
126
141
 
@@ -139,7 +154,9 @@ const unsubscribeRpc = bus.on("subagents:rpc:v1:request", (request) => {
139
154
  subagentStatusRequestCount += 1;
140
155
  const text = request.params?.id === "run-a"
141
156
  ? `Run: run-a\nState: running\nMode: parallel\nDir: ${asyncRunDir}`
142
- : statusText;
157
+ : request.params?.id === "recovered-gate-run"
158
+ ? `Run: recovered-gate-run\nState: running\nMode: single\nDir: ${gateAsyncRunDir}`
159
+ : statusText;
143
160
  if (subagentRpcReplyHook?.(request) === true) return;
144
161
  bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
145
162
  version: 1,
@@ -261,6 +278,13 @@ assert.deepEqual(recoveredFleetRun && {
261
278
  controllable: false,
262
279
  agents: [["Recovery scout", "openai-codex/gpt-5.6-terra:xhigh", "xhigh"]],
263
280
  }, "unmatched authoritative fleet children should publish a bounded non-controllable provisional row");
281
+ const recoveredCanonical = latestCanonicalPayload().instances.find((instance) => instance.runId === "fleet:fleet-recovered");
282
+ assert.deepEqual(recoveredCanonical && {
283
+ open: recoveredCanonical.capabilities.open,
284
+ refresh: recoveredCanonical.capabilities.refresh,
285
+ cancel: recoveredCanonical.capabilities.cancel,
286
+ outputKind: recoveredCanonical.outputRef.kind,
287
+ }, { open: true, refresh: true, cancel: false, outputKind: "helper" }, "recovered pi-subagents rows should expose a read-only helper-owned output view without lifecycle controls");
264
288
  assert.deepEqual(payload.fleet, { version: 1, totalActive: 5, omitted: 0 }, "fleet recovery should publish only bounded aggregate recovery metadata");
265
289
 
266
290
  subagentRpcReplyHook = (request) => {
@@ -382,6 +406,251 @@ assert.ok(payload.runs.some((run) => run.id === workflowRunId), "pi-subagents po
382
406
 
383
407
  const helperCommand = registeredCommands.get("webui-helper");
384
408
  assert.ok(helperCommand?.handler, "Web UI helper command should be registered");
409
+
410
+ const warmingWorkflowRunId = "workflow-warming-up";
411
+ const warmingWorkflowDir = await mkdtemp(path.join(asyncRunDir, "workflow-warmup-"));
412
+ const warmingWorkflowSessionFile = path.join(warmingWorkflowDir, "worker-session.jsonl");
413
+ const warmingWorkflowStartedAt = Date.now() - 500;
414
+ await writeFile(path.join(warmingWorkflowDir, "status.json"), JSON.stringify({
415
+ runId: warmingWorkflowRunId,
416
+ mode: "workflow",
417
+ state: "running",
418
+ startedAt: warmingWorkflowStartedAt,
419
+ lastUpdate: Date.now(),
420
+ steps: [],
421
+ }));
422
+ bus.emit("subagent:async-started", {
423
+ id: warmingWorkflowRunId,
424
+ mode: "workflow",
425
+ asyncDir: warmingWorkflowDir,
426
+ workflowGraph: { nodes: [] },
427
+ });
428
+ const warmingWorkflowFleet = {
429
+ version: 1,
430
+ entries: [
431
+ { key: "fleet-reviewer-1", agent: "reviewer", startedAt: fleetStartedAt, tokens: { input: 0, output: 0, total: 0 } },
432
+ { key: "fleet-reviewer-2", agent: "reviewer", startedAt: fleetStartedAt + 1, tokens: { input: 0, output: 0, total: 0 } },
433
+ { key: "fleet-worker", agent: "worker", startedAt: fleetStartedAt + 2, tokens: { input: 0, output: 0, total: 0 } },
434
+ { key: "fleet-nested", agent: "nested-oracle", startedAt: fleetStartedAt + 3, tokens: { input: 0, output: 0, total: 0 } },
435
+ { key: "fleet-recovered", agent: "scout", role: "Recovery scout", model: "openai-codex/gpt-5.6-terra:xhigh", effort: "xhigh", startedAt: fleetStartedAt + 4, tokens: { input: 0, output: 0, total: 0 } },
436
+ { key: "fleet-warming-workflow", agent: "workflow", startedAt: warmingWorkflowStartedAt, tokens: { input: 0, output: 0, total: 0 } },
437
+ { key: "fleet-warming-worker", agent: "worker", model: "openai-codex/gpt-5.6-sol", effort: "high", startedAt: warmingWorkflowStartedAt + 1, tokens: { input: 0, output: 0, total: 0 } },
438
+ ],
439
+ totalActive: 7,
440
+ omitted: 0,
441
+ };
442
+ const pollWarmingWorkflow = async (text, asyncSnapshot) => {
443
+ subagentRpcReplyHook = (request) => {
444
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
445
+ subagentRpcReplyHook = null;
446
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
447
+ version: 1,
448
+ requestId: request.requestId,
449
+ method: request.method,
450
+ success: true,
451
+ data: { text, details: { mode: "single", results: [] }, fleet: warmingWorkflowFleet, ...(asyncSnapshot ? { asyncSnapshot } : {}) },
452
+ });
453
+ return true;
454
+ };
455
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
456
+ await new Promise((resolve) => setTimeout(resolve, 0));
457
+ };
458
+ const warmingHeaderOnlyStatus = `Active async runs: 1
459
+
460
+ - ${warmingWorkflowRunId} | running | active | workflow | steps 0 | ~/repo`;
461
+ await pollWarmingWorkflow(warmingHeaderOnlyStatus);
462
+ await pollWarmingWorkflow(warmingHeaderOnlyStatus);
463
+ payload = latestPayload();
464
+ assert.equal(payload.runs.some((run) => run.id === "fleet:fleet-warming-workflow"), false, "a known workflow controller must not become an empty recovered Workflow row while its first child locator is pending");
465
+ await writeFile(warmingWorkflowSessionFile, `${JSON.stringify({
466
+ type: "message",
467
+ timestamp: "2026-07-26T12:00:10.000Z",
468
+ message: { role: "assistant", content: [{ type: "text", text: "Workflow worker output is live." }] },
469
+ })}\n`);
470
+ await writeFile(path.join(warmingWorkflowDir, "status.json"), JSON.stringify({
471
+ runId: warmingWorkflowRunId,
472
+ mode: "workflow",
473
+ state: "running",
474
+ startedAt: warmingWorkflowStartedAt,
475
+ lastUpdate: Date.now(),
476
+ steps: [{ agent: "worker", status: "running", sessionFile: warmingWorkflowSessionFile, model: "openai-codex/gpt-5.6-sol", thinking: "high" }],
477
+ }));
478
+ await pollWarmingWorkflow("No active async runs.", {
479
+ kind: "pi-subagents.async-status-snapshot",
480
+ version: 1,
481
+ generatedAt: Date.now(),
482
+ runs: [{
483
+ id: warmingWorkflowRunId,
484
+ kind: "workflow",
485
+ label: "workflow",
486
+ state: "running",
487
+ startedAt: warmingWorkflowStartedAt,
488
+ updatedAt: Date.now(),
489
+ children: [{ id: "ws1-input-backend", kind: "step", label: "ws1-input-backend", state: "running" }],
490
+ }],
491
+ });
492
+ payload = latestPayload();
493
+ const warmingWorkflowRun = payload.runs.find((run) => run.id === warmingWorkflowRunId);
494
+ assert.deepEqual(warmingWorkflowRun && {
495
+ source: warmingWorkflowRun.source,
496
+ status: warmingWorkflowRun.status,
497
+ agents: warmingWorkflowRun.agents.map((agent) => [agent.name, agent.model, agent.thinking]),
498
+ }, {
499
+ source: "async",
500
+ status: "running",
501
+ agents: [["worker", "openai-codex/gpt-5.6-sol", "high"]],
502
+ }, "an active workflow header must keep the run alive until its first worker locator appears");
503
+ assert.equal(payload.runs.some((run) => run.id === "fleet:fleet-warming-worker"), false, "the real workflow worker must replace its temporary fleet placeholder");
504
+ const warmingWorkflowCanonical = latestCanonicalPayload().instances.find((instance) => instance.runId === warmingWorkflowRunId && instance.name === "worker");
505
+ assert.ok(warmingWorkflowCanonical, "the resolved workflow worker should publish a canonical output handle");
506
+ await helperCommand.handler(JSON.stringify({
507
+ requestId: "warming-workflow-live-output-test",
508
+ action: "subagent-output",
509
+ payload: { outputId: warmingWorkflowCanonical.outputRef.id },
510
+ }), ctx);
511
+ const warmingWorkflowOutput = helperResponse("warming-workflow-live-output-test");
512
+ assert.equal(warmingWorkflowOutput.ok, true);
513
+ assert.equal(warmingWorkflowOutput.data.source, "async");
514
+ assert.equal(warmingWorkflowOutput.data.agent.unavailable, undefined);
515
+ assert.deepEqual(warmingWorkflowOutput.data.agent.recentOutput, ["Workflow worker output is live."], "a newly resolved workflow worker should expose its live transcript instead of the recovered placeholder");
516
+ bus.emit("subagent:async-complete", { id: warmingWorkflowRunId });
517
+
518
+ await helperCommand.handler(JSON.stringify({
519
+ requestId: "recovered-subagent-output-test",
520
+ action: "subagent-output",
521
+ payload: { outputId: recoveredCanonical.outputRef.id },
522
+ }), ctx);
523
+ const recoveredOutputResponse = helperResponse("recovered-subagent-output-test");
524
+ assert.equal(recoveredOutputResponse.ok, true, "a recovered fleet row should open through its opaque helper handle");
525
+ assert.equal(recoveredOutputResponse.data.source, "recovered");
526
+ assert.equal(recoveredOutputResponse.data.agent.unavailable, true);
527
+ assert.match(recoveredOutputResponse.data.agent.unavailableReason, /recovered from aggregate fleet metadata/, "the read-only recovered view should explain why detailed output is not yet available");
528
+
529
+ for (const handler of extensionHandlers.get("tool_execution_update") || []) {
530
+ handler({
531
+ type: "tool_execution_update",
532
+ toolCallId: "recovered-foreground-call",
533
+ toolName: "subagent",
534
+ partialResult: {
535
+ details: {
536
+ runId: "recovered-foreground-run",
537
+ mode: "single",
538
+ progress: [{
539
+ index: 0,
540
+ agent: "scout",
541
+ status: "running",
542
+ currentTool: "read",
543
+ recentOutput: ["Recovered child output is live again"],
544
+ }],
545
+ },
546
+ },
547
+ }, ctx);
548
+ }
549
+ payload = latestPayload();
550
+ assert.equal(payload.runs.some((run) => run.id === "fleet:fleet-recovered"), false, "a recovered fleet placeholder should be replaced when its live tool update arrives");
551
+ const recoveredForegroundRun = payload.runs.find((run) => run.id === "recovered-foreground-run");
552
+ assert.deepEqual(recoveredForegroundRun && {
553
+ source: recoveredForegroundRun.source,
554
+ controllable: recoveredForegroundRun.controllable,
555
+ agents: recoveredForegroundRun.agents.map((agent) => [agent.name, agent.model, agent.thinking]),
556
+ }, {
557
+ source: "foreground",
558
+ controllable: undefined,
559
+ agents: [["scout", "openai-codex/gpt-5.6-terra:xhigh", "xhigh"]],
560
+ }, "a live update without a preceding start event should promote recovered metadata into a normal foreground run even when the fleet display role differs from the agent identity");
561
+ const recoveredForegroundCanonical = latestCanonicalPayload().instances.find((instance) => instance.runId === "recovered-foreground-run");
562
+ await helperCommand.handler(JSON.stringify({
563
+ requestId: "recovered-foreground-live-output-test",
564
+ action: "subagent-output",
565
+ payload: { outputId: recoveredForegroundCanonical.outputRef.id },
566
+ }), ctx);
567
+ const recoveredForegroundOutput = helperResponse("recovered-foreground-live-output-test");
568
+ assert.equal(recoveredForegroundOutput.ok, true);
569
+ assert.equal(recoveredForegroundOutput.data.source, "foreground");
570
+ assert.equal(recoveredForegroundOutput.data.agent.unavailable, undefined);
571
+ assert.deepEqual(recoveredForegroundOutput.data.agent.recentOutput, ["Recovered child output is live again"], "promoted recovered runs should expose subsequent live output");
572
+ for (const handler of extensionHandlers.get("tool_execution_end") || []) {
573
+ handler({ type: "tool_execution_end", toolCallId: "recovered-foreground-call", toolName: "subagent" }, ctx);
574
+ }
575
+ await helperCommand.handler(JSON.stringify({
576
+ requestId: "dismiss-recovered-foreground-run",
577
+ action: "subagent-dismiss",
578
+ payload: { runId: "recovered-foreground-run" },
579
+ }), ctx);
580
+ assert.equal(helperResponse("dismiss-recovered-foreground-run").ok, true, "a promoted recovered run should follow the normal foreground completion lifecycle");
581
+
582
+ const gateRecoveredStartedAt = Date.now() - 500;
583
+ subagentRpcReplyHook = (request) => {
584
+ if (request.method !== "status" || Object.keys(request.params || {}).length) return false;
585
+ subagentRpcReplyHook = null;
586
+ bus.emit(`subagents:rpc:v1:reply:${request.requestId}`, {
587
+ version: 1,
588
+ requestId: request.requestId,
589
+ method: request.method,
590
+ success: true,
591
+ data: {
592
+ text: statusText,
593
+ details: { mode: "single", results: [] },
594
+ fleet: {
595
+ version: 1,
596
+ entries: [{
597
+ key: "fleet-gate-recovered",
598
+ agent: "scout",
599
+ role: "Gate recovery scout",
600
+ model: "openai-codex/gpt-5.6-terra:xhigh",
601
+ effort: "xhigh",
602
+ startedAt: gateRecoveredStartedAt,
603
+ tokens: { input: 0, output: 0, total: 0 },
604
+ }],
605
+ totalActive: 1,
606
+ omitted: 0,
607
+ },
608
+ },
609
+ });
610
+ return true;
611
+ };
612
+ bus.emit("subagents:rpc:v1:ready", { version: 1 });
613
+ await new Promise((resolve) => setTimeout(resolve, 0));
614
+ assert.ok(latestPayload().runs.some((run) => run.id === "fleet:fleet-gate-recovered"), "an unmatched gate child should begin as an aggregate fleet placeholder");
615
+ bus.emit("webui:subagent-gate:v1:update", {
616
+ version: 1,
617
+ id: "gate-live-output",
618
+ status: "running",
619
+ requiredSuccesses: 1,
620
+ qualifyingSuccesses: 0,
621
+ requireDistinctProviders: false,
622
+ startedAt: gateRecoveredStartedAt,
623
+ updatedAt: Date.now(),
624
+ attempts: [{
625
+ id: "gate-live-output:0:1",
626
+ taskIndex: 0,
627
+ attempt: 1,
628
+ maxAttempts: 1,
629
+ agent: "scout",
630
+ label: "Gate recovery scout",
631
+ retrySafety: "read-only",
632
+ runId: "recovered-gate-run",
633
+ model: "openai-codex/gpt-5.6-terra:xhigh",
634
+ provider: "openai-codex",
635
+ status: "running",
636
+ startedAt: gateRecoveredStartedAt,
637
+ }],
638
+ });
639
+ assert.equal(latestPayload().runs.some((run) => run.id === "fleet:fleet-gate-recovered"), false, "a running gate attempt with a real run id should replace its aggregate fleet placeholder");
640
+ const gateTrackedRun = latestPayload().runs.find((run) => run.id === "recovered-gate-run");
641
+ assert.equal(gateTrackedRun?.source, "async", "gate-owned children should become normal output-capable async runs");
642
+ const gateTrackedCanonical = latestCanonicalPayload().instances.find((instance) => instance.runId === "recovered-gate-run");
643
+ await helperCommand.handler(JSON.stringify({
644
+ requestId: "recovered-gate-live-output-test",
645
+ action: "subagent-output",
646
+ payload: { outputId: gateTrackedCanonical.outputRef.id },
647
+ }), ctx);
648
+ const recoveredGateOutput = helperResponse("recovered-gate-live-output-test");
649
+ assert.equal(recoveredGateOutput.ok, true);
650
+ assert.equal(recoveredGateOutput.data.source, "async");
651
+ assert.equal(recoveredGateOutput.data.agent.unavailable, undefined, "a gate child with a run locator must not retain the aggregate-fleet warning");
652
+ assert.deepEqual(recoveredGateOutput.data.agent.recentOutput, ["Gate child output is live."], "a recovered gate child should resolve its session transcript through the real run locator");
653
+
385
654
  const requestsBeforeWorkflowOutput = subagentStatusRequestCount;
386
655
  await helperCommand.handler(JSON.stringify({
387
656
  requestId: "workflow-subagent-output-test",
@@ -1138,6 +1407,49 @@ assert.ok(Number.isSafeInteger(retainedCanonical.endedAt), "terminal instances c
1138
1407
  assert.equal(retainedCanonical.capabilities.cancel, false, "a finished run stops advertising cancel");
1139
1408
  assert.equal(retainedCanonical.capabilities.open, true, "retained rows stay openable");
1140
1409
 
1410
+ bus.emit("firstpick:webui-agent-runs:v1", {
1411
+ version: 1,
1412
+ producerId: "custom-duplicate",
1413
+ complete: true,
1414
+ instances: [providerInstance({
1415
+ instanceId: canonicalAgent.instanceId,
1416
+ runId: canonicalAgent.runId,
1417
+ launcher: "custom",
1418
+ provider: "custom-duplicate",
1419
+ status: "done",
1420
+ updatedAt: retainedCanonical.endedAt,
1421
+ endedAt: retainedCanonical.endedAt,
1422
+ capabilities: { open: true, refresh: true, cancel: false, steer: false },
1423
+ })],
1424
+ });
1425
+ await helperCommand.handler(JSON.stringify({
1426
+ requestId: "dismiss-terminal-duplicate-projection",
1427
+ action: "subagent-dismiss",
1428
+ payload: { runId: "canon-run" },
1429
+ }), ctx);
1430
+ assert.equal(helperResponse("dismiss-terminal-duplicate-projection").ok, true, "the terminal owning run should accept dismissal");
1431
+ canonical = latestCanonicalPayload();
1432
+ assert.equal(canonical.instances.some((instance) => instance.instanceId === canonicalAgent.instanceId), false, "dismissal should suppress a terminal run still present in a duplicate provider snapshot");
1433
+
1434
+ bus.emit("firstpick:webui-agent-runs:v1", {
1435
+ version: 1,
1436
+ producerId: "custom-duplicate",
1437
+ complete: true,
1438
+ instances: [providerInstance({
1439
+ instanceId: canonicalAgent.instanceId,
1440
+ runId: canonicalAgent.runId,
1441
+ launcher: "custom",
1442
+ provider: "custom-duplicate",
1443
+ status: "running",
1444
+ startedAt: retainedCanonical.endedAt + 1,
1445
+ updatedAt: retainedCanonical.endedAt + 1,
1446
+ endedAt: null,
1447
+ })],
1448
+ });
1449
+ canonical = latestCanonicalPayload();
1450
+ assert.equal(canonical.instances.find((instance) => instance.instanceId === canonicalAgent.instanceId)?.status, "running", "a newer provider lifecycle should release the local dismissal tombstone");
1451
+ bus.emit("firstpick:webui-agent-runs:v1", { version: 1, producerId: "custom-duplicate", complete: true, instances: [] });
1452
+
1141
1453
  for (const handler of extensionHandlers.get("session_shutdown") || []) await handler({ reason: "quit" }, ctx);
1142
1454
  unsubscribeRpc();
1143
1455
  delete process.env.PI_WEBUI_SETTINGS_FILE;
@@ -0,0 +1,235 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ MAX_SYNTAX_HIGHLIGHT_CHARACTERS,
4
+ MAX_SYNTAX_HIGHLIGHT_LINES,
5
+ SUPPORTED_SYNTAX_LANGUAGES,
6
+ SYNTAX_LANGUAGE_ALIASES,
7
+ normalizeSyntaxLanguage,
8
+ tokenizeCode,
9
+ } from "../public/syntax-highlight.mjs";
10
+
11
+ const TOKEN_TYPES = new Set([
12
+ "plain",
13
+ "comment",
14
+ "keyword",
15
+ "function",
16
+ "variable",
17
+ "string",
18
+ "number",
19
+ "type",
20
+ "operator",
21
+ "punctuation",
22
+ ]);
23
+
24
+ function assertRoundTrip(language, source, message = language) {
25
+ const tokens = tokenizeCode(source, language);
26
+ assert.equal(tokens.map(({ text }) => text).join(""), source, `${message} should preserve source exactly`);
27
+ for (const token of tokens) {
28
+ assert.ok(TOKEN_TYPES.has(token.type), `${message} emitted unsupported token type ${token.type}`);
29
+ assert.equal(typeof token.text, "string", `${message} token text should be a string`);
30
+ assert.notEqual(token.text, "", `${message} should not emit empty tokens`);
31
+ assert.deepEqual(Object.keys(token).sort(), ["text", "type"], `${message} tokens should keep the small public shape`);
32
+ }
33
+ return tokens;
34
+ }
35
+
36
+ function tokenText(tokens, type) {
37
+ return tokens.filter((token) => token.type === type).map((token) => token.text).join("");
38
+ }
39
+
40
+ const expectedAliases = {
41
+ python: ["python", "py"],
42
+ javascript: ["javascript", "js", "jsx", "mjs", "cjs", "node"],
43
+ typescript: ["typescript", "ts", "tsx"],
44
+ bash: ["bash", "sh", "shell", "zsh"],
45
+ powershell: ["powershell", "pwsh", "ps1"],
46
+ cmd: ["cmd", "bat", "batch", "dos"],
47
+ json: ["json"],
48
+ jsonc: ["jsonc"],
49
+ ini: ["ini", "cfg", "conf", "properties"],
50
+ toml: ["toml"],
51
+ yaml: ["yaml", "yml"],
52
+ diff: ["diff", "patch"],
53
+ sql: ["sql"],
54
+ css: ["css"],
55
+ html: ["html", "htm"],
56
+ xml: ["xml", "svg"],
57
+ dockerfile: ["dockerfile", "docker"],
58
+ c: ["c", "h"],
59
+ cpp: ["cpp", "c++", "cc", "cxx", "hpp", "hxx"],
60
+ java: ["java"],
61
+ go: ["go", "golang"],
62
+ rust: ["rust", "rs"],
63
+ csharp: ["csharp", "cs", "c#", "dotnet"],
64
+ };
65
+
66
+ assert.deepEqual(new Set(SUPPORTED_SYNTAX_LANGUAGES), new Set(Object.keys(expectedAliases)), "supported languages should expose every canonical profile exactly once");
67
+ for (const [canonical, aliases] of Object.entries(expectedAliases)) {
68
+ for (const alias of aliases) {
69
+ assert.equal(normalizeSyntaxLanguage(alias), canonical, `${alias} should normalize to ${canonical}`);
70
+ assert.equal(SYNTAX_LANGUAGE_ALIASES[alias], canonical, `${alias} should be present in the exported alias catalog`);
71
+ }
72
+ }
73
+ assert.equal(normalizeSyntaxLanguage(" TSX "), "typescript", "language normalization should trim and ignore case");
74
+ assert.equal(normalizeSyntaxLanguage("unknown-language"), "", "unknown languages should not be guessed");
75
+ for (const inheritedName of ["constructor", "toString", "__proto__"]) {
76
+ assert.equal(normalizeSyntaxLanguage(inheritedName), "", `inherited object key ${inheritedName} must not resolve as a language alias`);
77
+ }
78
+
79
+ const fixtures = [
80
+ {
81
+ language: "python",
82
+ source: "def greet(name: str):\n # keep this\n return f\"Hello, {name}\" + str(42)",
83
+ types: ["keyword", "function", "type", "comment", "string", "number", "punctuation"],
84
+ },
85
+ {
86
+ language: "javascript",
87
+ source: "// browser code\nconst answer = format(`value ${42}`) + 42;",
88
+ types: ["comment", "keyword", "function", "string", "number", "operator", "punctuation"],
89
+ },
90
+ {
91
+ language: "typescript",
92
+ source: "interface User { name: string }\nconst load = async (id: number) => fetch(`/u/${id}`);",
93
+ types: ["keyword", "type", "function", "string", "operator", "punctuation"],
94
+ },
95
+ {
96
+ language: "bash",
97
+ source: "#!/usr/bin/env bash\nif [[ -n $HOME ]]; then echo \"ready\"; fi",
98
+ types: ["comment", "keyword", "variable", "string", "operator", "punctuation"],
99
+ },
100
+ {
101
+ language: "powershell",
102
+ source: "# profile\nparam([string]$Name)\nWrite-Output -InputObject \"Hi $Name\"",
103
+ types: ["comment", "keyword", "type", "variable", "string", "punctuation"],
104
+ },
105
+ {
106
+ language: "cmd",
107
+ source: "REM startup\r\nIF DEFINED USERPROFILE ECHO %USERPROFILE% & ECHO \"ready\"",
108
+ types: ["comment", "keyword", "variable", "string"],
109
+ },
110
+ {
111
+ language: "json",
112
+ source: "{\"enabled\": true, \"retries\": 3, \"value\": null}",
113
+ types: ["variable", "keyword", "number", "punctuation"],
114
+ },
115
+ {
116
+ language: "jsonc",
117
+ source: "{\n // safe comment\n \"path\": \"C:\\\\tmp\",\n \"ok\": false\n}",
118
+ types: ["comment", "variable", "string", "keyword", "punctuation"],
119
+ },
120
+ {
121
+ language: "ini",
122
+ source: "[server]\nhost-name = localhost\n; local only",
123
+ types: ["type", "variable", "operator", "comment", "punctuation"],
124
+ },
125
+ {
126
+ language: "toml",
127
+ source: "[[servers.alpha]]\nenabled = true\nport = 8080 # local",
128
+ types: ["type", "variable", "keyword", "number", "comment", "operator", "punctuation"],
129
+ },
130
+ {
131
+ language: "yaml",
132
+ source: "service-name: api\nenabled: true\nports:\n - 8080 # local",
133
+ types: ["variable", "keyword", "number", "comment", "operator", "punctuation"],
134
+ },
135
+ {
136
+ language: "diff",
137
+ source: "diff --git a/a.js b/a.js\n--- a/a.js\n+++ b/a.js\n@@ -1 +1 @@\n-old\n+new\n",
138
+ types: ["keyword", "type", "comment", "string"],
139
+ },
140
+ {
141
+ language: "sql",
142
+ source: "SELECT COUNT(id) FROM users WHERE created_at > DATE('2025-01-01'); -- bounded",
143
+ types: ["keyword", "function", "type", "string", "comment", "operator", "punctuation"],
144
+ },
145
+ {
146
+ language: "css",
147
+ source: ".card { color: #fff; margin-top: 12px; /* compact */ }",
148
+ types: ["variable", "number", "comment", "punctuation"],
149
+ },
150
+ {
151
+ language: "html",
152
+ source: "<!-- safe -->\n<section class=\"card\" data-id='7'><span>Text</span></section>",
153
+ types: ["comment", "type", "variable", "string", "operator", "punctuation"],
154
+ },
155
+ {
156
+ language: "xml",
157
+ source: "<?xml version=\"1.0\"?><root id=\"a\"><child /></root>",
158
+ types: ["type", "variable", "string", "operator", "punctuation"],
159
+ },
160
+ {
161
+ language: "dockerfile",
162
+ source: "FROM node:22\nARG APP_HOME=/app\nRUN echo $APP_HOME && echo \"ready\" # build path",
163
+ types: ["keyword", "variable", "string", "comment", "operator", "punctuation"],
164
+ },
165
+ {
166
+ language: "c",
167
+ source: "// C\nstatic int add(int a, int b) { return a + b; }",
168
+ types: ["comment", "keyword", "type", "function", "operator", "punctuation"],
169
+ },
170
+ {
171
+ language: "cpp",
172
+ source: "class Box { public: size_t size() const { return 1; } };",
173
+ types: ["keyword", "type", "function", "number", "punctuation"],
174
+ },
175
+ {
176
+ language: "java",
177
+ source: "public class Main { static String greet(String name) { return \"Hi \" + name; } }",
178
+ types: ["keyword", "type", "function", "string", "operator", "punctuation"],
179
+ },
180
+ {
181
+ language: "go",
182
+ source: "package main\nfunc add(a int, b int) int { return a + b }",
183
+ types: ["keyword", "type", "function", "operator", "punctuation"],
184
+ },
185
+ {
186
+ language: "rust",
187
+ source: "pub fn add(a: i32, b: i32) -> i32 { a + b }",
188
+ types: ["keyword", "type", "function", "operator", "punctuation"],
189
+ },
190
+ {
191
+ language: "csharp",
192
+ source: "public static string Greet(string name) => $\"Hi {name}\";",
193
+ types: ["keyword", "type", "string", "operator", "punctuation"],
194
+ },
195
+ ];
196
+
197
+ for (const fixture of fixtures) {
198
+ const tokens = assertRoundTrip(fixture.language, fixture.source);
199
+ for (const type of fixture.types) {
200
+ assert.notEqual(tokenText(tokens, type), "", `${fixture.language} should emit a representative ${type} token`);
201
+ }
202
+ }
203
+
204
+ const malicious = "const payload = \"</code><img src=x onerror=alert(1)>\"; // <script>alert(2)</script>";
205
+ const maliciousTokens = assertRoundTrip("js", malicious, "malicious-looking JavaScript");
206
+ assert.ok(tokenText(maliciousTokens, "string").includes("<img"), "HTML-looking source should remain inert token text for DOM-safe integration");
207
+ assert.ok(tokenText(maliciousTokens, "comment").includes("<script>"), "comment source should remain exact text rather than markup");
208
+
209
+ const unknown = "<b>plain & exact</b>\nconst x = 1;";
210
+ assert.deepEqual(tokenizeCode(unknown, "not-a-language"), [{ type: "plain", text: unknown }], "unknown languages should use one exact plain token");
211
+ assert.deepEqual(tokenizeCode(unknown, ""), [{ type: "plain", text: unknown }], "missing language metadata should use one exact plain token");
212
+ assert.deepEqual(tokenizeCode("", "python"), [], "empty source should not emit empty token objects");
213
+ assert.deepEqual(tokenizeCode(null, "python"), [], "null source should normalize to empty source");
214
+ assert.deepEqual(tokenizeCode(12345, "python"), [{ type: "number", text: "12345" }], "non-string source should normalize to its exact string form");
215
+
216
+ const characterLimit = "if ".repeat(Math.ceil(MAX_SYNTAX_HIGHLIGHT_CHARACTERS / 3)).slice(0, MAX_SYNTAX_HIGHLIGHT_CHARACTERS);
217
+ assert.notDeepEqual(tokenizeCode(characterLimit, "python"), [{ type: "plain", text: characterLimit }], "the exact character limit should remain eligible for highlighting");
218
+ const oversizedCharacters = `${characterLimit}x`;
219
+ assert.deepEqual(tokenizeCode(oversizedCharacters, "python"), [{ type: "plain", text: oversizedCharacters }], "source above the character cap should skip tokenization exactly");
220
+
221
+ const lineLimit = `${"if True:\n".repeat(MAX_SYNTAX_HIGHLIGHT_LINES - 1)}pass`;
222
+ assert.notDeepEqual(tokenizeCode(lineLimit, "python"), [{ type: "plain", text: lineLimit }], "the exact line limit should remain eligible for highlighting");
223
+ const oversizedLines = `${lineLimit}\npass`;
224
+ assert.deepEqual(tokenizeCode(oversizedLines, "python"), [{ type: "plain", text: oversizedLines }], "source above the line cap should skip tokenization exactly");
225
+
226
+ const cmdComment = "REM bounded";
227
+ const nearCapCmdLine = `${" ".repeat(MAX_SYNTAX_HIGHLIGHT_CHARACTERS - cmdComment.length)}${cmdComment}`;
228
+ const nearCapCmdTokens = assertRoundTrip("cmd", nearCapCmdLine, "near-cap indented cmd comment");
229
+ assert.equal(tokenText(nearCapCmdTokens, "comment"), cmdComment, "near-cap cmd input should scan indentation once and recognize the line-leading comment");
230
+
231
+ for (const alias of Object.keys(SYNTAX_LANGUAGE_ALIASES)) {
232
+ assertRoundTrip(alias, "keyword = \"value\" # exact\nnext(42)", `alias ${alias}`);
233
+ }
234
+
235
+ console.log(`syntax-highlight.test.mjs passed (${fixtures.length} language fixtures, ${Object.keys(SYNTAX_LANGUAGE_ALIASES).length} aliases)`);