@firstpick/pi-package-webui 0.8.5 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +18 -584
  2. package/bin/pi-webui-launcher.mjs +22 -0
  3. package/bin/pi-webui-update-supervisor.mjs +86 -0
  4. package/bin/pi-webui.mjs +933 -554
  5. package/index.ts +16 -6
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +20 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-core.mjs +4 -3
  11. package/lib/session-summary-preferences.mjs +16 -1
  12. package/lib/subagent-launch-slots.mjs +14 -2
  13. package/lib/trust-boundaries.mjs +16 -0
  14. package/lib/update/executor.mjs +99 -0
  15. package/lib/update/journal.mjs +175 -0
  16. package/lib/update/owners.mjs +70 -0
  17. package/lib/update/plan.mjs +134 -0
  18. package/lib/update/resolver.mjs +168 -0
  19. package/lib/update/supervisor.mjs +238 -0
  20. package/lib/update/verify.mjs +52 -0
  21. package/lib/update-commands.mjs +25 -13
  22. package/lib/webui-workspaces.mjs +17 -1
  23. package/lib/workspace-session-summaries.mjs +400 -0
  24. package/package.json +4 -4
  25. package/public/app.js +2487 -349
  26. package/public/index.html +200 -51
  27. package/public/middle-button-drag-scroll.mjs +154 -0
  28. package/public/sampling-parameter-controls.mjs +361 -0
  29. package/public/service-worker.js +5 -1
  30. package/public/stream-output-controller.mjs +327 -0
  31. package/public/styles.css +666 -71
  32. package/public/theme-contract.mjs +244 -0
  33. package/session-summary.ts +164 -4
  34. package/tests/aur-review-widget-static.test.mjs +2 -1
  35. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  36. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  37. package/tests/browser/interaction-continuity.spec.mjs +2 -2
  38. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  39. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  40. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  41. package/tests/browser/session-summary.spec.mjs +131 -3
  42. package/tests/browser/stream-output-isolation.spec.mjs +510 -0
  43. package/tests/browser/update-reconnect.spec.mjs +92 -0
  44. package/tests/codex-fast-mode-static.test.mjs +2 -2
  45. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  46. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  47. package/tests/component-update-api-static.test.mjs +22 -61
  48. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  49. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  50. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  51. package/tests/fast-mode-client-static.test.mjs +3 -2
  52. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  53. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  54. package/tests/fixtures/fake-pi.mjs +269 -2
  55. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  56. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  57. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  58. package/tests/git-workflow-preferences.test.mjs +7 -1
  59. package/tests/guided-git-aur-review.test.mjs +4 -3
  60. package/tests/http-endpoints-harness.test.mjs +274 -23
  61. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  62. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  63. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  64. package/tests/mobile-foundation-static.test.mjs +5 -6
  65. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  66. package/tests/mobile-static.test.mjs +85 -50
  67. package/tests/native-parity.test.mjs +1 -1
  68. package/tests/open-issue-wizard-static.test.mjs +2 -3
  69. package/tests/optional-feature-migration-frontend.test.mjs +9 -5
  70. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  71. package/tests/questionnaire-dialog.test.mjs +3 -3
  72. package/tests/remote-auth-settings-harness.test.mjs +43 -0
  73. package/tests/rpc-supervisor-host.test.mjs +11 -2
  74. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  75. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  76. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  77. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  78. package/tests/sampling-parameter-controls.test.mjs +241 -0
  79. package/tests/session-sampling-helper.test.mjs +228 -0
  80. package/tests/session-sampling-http.test.mjs +168 -0
  81. package/tests/session-sampling-ui-static.test.mjs +370 -0
  82. package/tests/session-summary-core.test.mjs +205 -10
  83. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  84. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  85. package/tests/staged-content-hash-contract.test.mjs +52 -11
  86. package/tests/stream-lifecycle-core.test.mjs +134 -0
  87. package/tests/stream-output-controller.test.mjs +252 -0
  88. package/tests/stream-output-isolation-static.test.mjs +89 -0
  89. package/tests/streaming-ui-coupling.test.mjs +50 -0
  90. package/tests/subagent-gate-visibility.test.mjs +1 -1
  91. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  92. package/tests/subagent-launch-slots.test.mjs +18 -1
  93. package/tests/theme-contract.test.mjs +104 -0
  94. package/tests/theme-customizer-static.test.mjs +82 -0
  95. package/tests/theme-scheme-mode.test.mjs +15 -0
  96. package/tests/ui-layout-settings.test.mjs +18 -1
  97. package/tests/update-api-harness.test.mjs +111 -0
  98. package/tests/update-commands.test.mjs +15 -45
  99. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  100. package/tests/update-journal-harness.test.mjs +59 -0
  101. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  102. package/tests/update-owners.test.mjs +27 -0
  103. package/tests/update-plan.test.mjs +58 -0
  104. package/tests/update-resolver.test.mjs +56 -0
  105. package/tests/update-supervisor-harness.test.mjs +57 -0
  106. package/tests/update-tab-restore-harness.test.mjs +24 -0
  107. package/tests/update-verify.test.mjs +31 -0
  108. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  109. package/tests/workspace-session-summaries.test.mjs +288 -0
  110. package/webui-rpc-helper.mjs +119 -0
@@ -1,7 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
- import { mkdtemp, rm } from "node:fs/promises";
2
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
5
6
  import { writeSessionSummaryPreferences } from "../lib/session-summary-preferences.mjs";
6
7
  import {
7
8
  SESSION_SUMMARY_DISPLAY_TYPE,
@@ -26,6 +27,15 @@ import {
26
27
  shouldApplySummaryTitle,
27
28
  } from "../lib/session-summary-core.mjs";
28
29
 
30
+ async function waitFor(label, predicate, timeoutMs = 5_000) {
31
+ const deadline = Date.now() + timeoutMs;
32
+ while (Date.now() < deadline) {
33
+ if (predicate()) return;
34
+ await delay(10);
35
+ }
36
+ throw new Error(`${label} did not happen within ${timeoutMs}ms`);
37
+ }
38
+
29
39
  const entries = [
30
40
  { type: "message", id: "u1", message: { role: "user", content: [{ type: "text", text: "Please fix auth" }, { type: "image", data: "SECRET_IMAGE" }] } },
31
41
  { type: "message", id: "a1", message: { role: "assistant", content: [
@@ -98,6 +108,8 @@ assert.equal(latestSummaryState([{
98
108
  data: { ...baseState, result: { ...baseState.result, summaryMarkdown: escapedPersistedSummary } },
99
109
  }]).result.summaryMarkdown, escapedPersistedSummary, "persisted state validation uses the decoded Markdown bound");
100
110
  assert.equal(latestSummaryState([{ type: "custom", customType: SESSION_SUMMARY_STATE_TYPE, data: { version: 99 } }]), undefined);
111
+ const titlelessState = { ...baseState, result: { summaryMarkdown: "# Valid titleless summary" }, titleAppliedAtOrdinal: undefined };
112
+ assert.equal(latestSummaryState([{ type: "custom", customType: SESSION_SUMMARY_STATE_TYPE, data: titlelessState }]).result.summaryMarkdown, "# Valid titleless summary", "valid titleless generated states remain discoverable");
101
113
  assert.deepEqual(latestSummaryNameProvenance([
102
114
  { type: "custom", customType: SESSION_SUMMARY_NAME_PROVENANCE_TYPE, data: { version: 1, explicit: true } },
103
115
  { type: "custom", customType: SESSION_SUMMARY_NAME_PROVENANCE_TYPE, data: { version: 99, explicit: false } },
@@ -254,6 +266,7 @@ try {
254
266
  const api = {
255
267
  on(name, handler) { handlers.set(name, handler); },
256
268
  registerCommand(name, options) { commands.set(name, options); },
269
+ registerTool() {},
257
270
  registerEntryRenderer(name, renderer) { renderers.set(name, renderer); },
258
271
  sendMessage(message) {
259
272
  const id = `e${activeBranch.length + 1}`;
@@ -312,7 +325,7 @@ try {
312
325
  const settledReturn = handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
313
326
  assert.equal(settledReturn, undefined, "settled handler returns synchronously");
314
327
  assert.equal(completionCalls.length, 0, "provider work does not delay outward settlement");
315
- for (let i = 0; i < 20 && completionCalls.length === 0; i += 1) await new Promise((resolve) => setImmediate(resolve));
328
+ await waitFor("automatic session-summary completion start", () => completionCalls.length === 1);
316
329
  assert.equal(completionCalls.length, 1);
317
330
  const [, completionContext, completionOptions] = completionCalls[0];
318
331
  assert.equal(completionContext.tools, undefined);
@@ -327,7 +340,7 @@ try {
327
340
  assert.equal(typeof completionOptions.sessionId, "string");
328
341
  assert.notEqual(completionOptions.sessionId, "fake-session", "completion uses a fresh routing ID");
329
342
  releaseComplete();
330
- for (let i = 0; i < 20 && !branchEntries.some((entry) => entry.customType === SESSION_SUMMARY_STATE_TYPE); i += 1) await new Promise((resolve) => setImmediate(resolve));
343
+ await waitFor("persisted automatic session-summary state", () => branchEntries.some((entry) => entry.customType === SESSION_SUMMARY_STATE_TYPE));
331
344
  const persistedState = latestSummaryState(branchEntries);
332
345
  assert.equal(persistedState.result.summaryMarkdown, "# Summary\n\nCore is ready.");
333
346
  assert.equal(sessionName, "Summary core", "first generated title applies immediately");
@@ -345,7 +358,7 @@ try {
345
358
  nextCompletionError = new Error("overlap failed");
346
359
  const overlapCallIndex = completionCalls.length;
347
360
  handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
348
- for (let i = 0; i < 20 && completionCalls.length === overlapCallIndex; i += 1) await new Promise((resolve) => setImmediate(resolve));
361
+ await waitFor("overlapping automatic session-summary start", () => completionCalls.length === overlapCallIndex + 1);
349
362
  assert.equal(completionCalls.length, overlapCallIndex + 1);
350
363
  const overlapRefresh = commands.get("summary").handler("refresh", ctx);
351
364
  releaseComplete();
@@ -361,20 +374,21 @@ try {
361
374
  const coalescedFailureCountBefore = branchEntries.filter((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed").length;
362
375
  const coalescedCallIndex = completionCalls.length;
363
376
  handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
364
- for (let i = 0; i < 20 && completionCalls.length === coalescedCallIndex; i += 1) await new Promise((resolve) => setImmediate(resolve));
377
+ await waitFor("coalesced automatic session-summary start", () => completionCalls.length === coalescedCallIndex + 1);
365
378
  assert.equal(completionCalls.length, coalescedCallIndex + 1);
366
379
  handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
367
380
  nextCompletionError = new Error("pending automatic failed");
368
381
  completeGate = Promise.resolve();
369
382
  releaseComplete();
370
- for (let i = 0; i < 40 && !branchEntries.some((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed"); i += 1) {
371
- await new Promise((resolve) => setImmediate(resolve));
372
- }
383
+ await waitFor(
384
+ "pending automatic session-summary failure",
385
+ () => branchEntries.some((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed"),
386
+ );
373
387
  assert.equal(completionCalls.length, coalescedCallIndex + 2, "pending automatic refresh launches after the first succeeds");
374
388
  const coalescedFailures = branchEntries.filter((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed");
375
389
  assert.equal(coalescedFailures.length - coalescedFailureCountBefore, 1, "an internally launched pending failure emits exactly one terminal RPC event");
376
390
 
377
- for (let i = 0; i < 20 && !branchEntries.some((entry) => entry.details?.kind === "success"); i += 1) await new Promise((resolve) => setImmediate(resolve));
391
+ await waitFor("automatic session-summary success", () => branchEntries.some((entry) => entry.details?.kind === "success"));
378
392
  assert.equal(latestSummaryNameProvenance(branchEntries), undefined, "self-generated rename does not record explicit provenance");
379
393
 
380
394
  api.setSessionName("Summary core");
@@ -421,7 +435,7 @@ try {
421
435
  fakeOutput = { version: 1, title: "Stale title", summaryMarkdown: "# Stale result" };
422
436
  const staleCallIndex = completionCalls.length;
423
437
  const staleRefresh = commands.get("summary").handler("refresh", ctx);
424
- for (let i = 0; i < 20 && completionCalls.length === staleCallIndex; i += 1) await new Promise((resolve) => setImmediate(resolve));
438
+ await waitFor("stale-source session-summary start", () => completionCalls.length === staleCallIndex + 1);
425
439
  assert.equal(completionCalls.length, staleCallIndex + 1);
426
440
  activeBranch = branchB;
427
441
  leafId = branchB.at(-1).id;
@@ -482,6 +496,187 @@ try {
482
496
  routingIds.add(calledOptions.sessionId);
483
497
  }
484
498
  assert.equal(routingIds.size, representativeCases.length, "each representative provider call gets a fresh routing ID");
499
+
500
+ // W2 integration: use pi-intercom's documented extension-channel contract.
501
+ class FakeChannel {
502
+ connected = true;
503
+ supported = true;
504
+ published = [];
505
+ peers = new Map();
506
+ snapshot() { return { connected: this.connected, supported: this.supported }; }
507
+ publish(payload, options) { this.published.push({ payload, options }); }
508
+ async listSessions() {
509
+ return [...this.peers.entries()].map(([id, value]) => ({ id, cwd: value.cwd, pid: value.pid }));
510
+ }
511
+ }
512
+
513
+ const testCwd = join(extensionTemp, "test-workspace-a");
514
+ const crossCwd = join(extensionTemp, "test-workspace-b");
515
+ await mkdir(testCwd, { recursive: true });
516
+ await mkdir(crossCwd, { recursive: true });
517
+ const fakeChannel = new FakeChannel();
518
+ fakeChannel.peers.set("self-sender-1", { cwd: testCwd, pid: process.pid });
519
+ const w2Tools = new Map();
520
+ const w2Commands = new Map();
521
+ const w2Branch = [
522
+ { type: "message", id: "m1", message: { role: "user", content: "Work on feature" } },
523
+ { type: "custom", customType: SESSION_SUMMARY_STATE_TYPE, data: {
524
+ version: 1,
525
+ source: { sessionId: "s-self", leafId: "m1", fingerprint: "fp-self", entryCount: 1 },
526
+ result: { title: "Self Title", summaryMarkdown: "# Self Summary\n\nWorking on feature" },
527
+ generation: { provider: "fake", modelId: "fake", thinkingLevel: "low", promptRevision: "v1" },
528
+ generatedAt: "2026-08-05T00:00:00.000Z",
529
+ settledTurnOrdinal: 1,
530
+ } },
531
+ ];
532
+ let intercomRegistration;
533
+ const w2Api = {
534
+ events: {
535
+ emit(event, registration) {
536
+ if (event !== "intercom:extension-register") return;
537
+ intercomRegistration = registration;
538
+ registration.onReady(fakeChannel);
539
+ },
540
+ },
541
+ on(name, handler) { handlers.set(name, handler); },
542
+ registerCommand(name, options) { w2Commands.set(name, options); },
543
+ registerTool(tool) { w2Tools.set(tool.name, tool); },
544
+ registerEntryRenderer() {},
545
+ sendMessage() {},
546
+ appendEntry(customType, data) { w2Branch.push({ type: "custom", customType, data }); },
547
+ getSessionName() { return "Self Title"; },
548
+ };
549
+
550
+ createSessionSummaryExtension({ completeFn: fakeComplete })(w2Api);
551
+ assert.equal(w2Tools.has("workspace_session_summaries"), true, "workspace_session_summaries tool registered");
552
+ const workspaceTool = w2Tools.get("workspace_session_summaries");
553
+ assert.match(workspaceTool.promptSnippet, /same-CWD session summaries/);
554
+ assert.equal(Array.isArray(workspaceTool.promptGuidelines), true, "tool guidelines use the Pi array contract");
555
+ assert.match(workspaceTool.promptGuidelines.join("\n"), /intercom/);
556
+
557
+ const w2Ctx = {
558
+ cwd: testCwd,
559
+ sessionManager: {
560
+ getBranch: () => w2Branch.slice(),
561
+ getSessionId: () => "s-self",
562
+ getSessionFile: () => join(extensionTemp, "s-self.jsonl"),
563
+ },
564
+ };
565
+ await handlers.get("session_start")({ type: "session_start", reason: "startup" }, w2Ctx);
566
+ assert.equal(intercomRegistration.namespace, "firstpick/session-summary/v1");
567
+ assert.equal(intercomRegistration.ownerEligible, false);
568
+ assert.equal(typeof intercomRegistration.onEvent, "function");
569
+ assert.equal(fakeChannel.published.at(-1)?.options?.audience, "capable");
570
+ const initialPublicationCount = fakeChannel.published.length;
571
+ intercomRegistration.onEvent({ type: "session_joined", session: { id: "new-peer", cwd: testCwd } });
572
+ assert.equal(fakeChannel.published.length, initialPublicationCount + 1, "a joining capable peer triggers summary republication");
573
+ fakeChannel.connected = false;
574
+ intercomRegistration.onEvent({ type: "connection", connected: false, supported: false });
575
+ fakeChannel.connected = true;
576
+ intercomRegistration.onEvent({ type: "connection", connected: true, supported: true });
577
+ assert.equal(fakeChannel.published.length, initialPublicationCount + 2, "a supported reconnect republishes the current summary");
578
+
579
+ fakeChannel.peers.set("peer-same", { cwd: testCwd, pid: process.pid + 1 });
580
+ fakeChannel.peers.set("peer-cross", { cwd: crossCwd, pid: process.pid + 2 });
581
+ intercomRegistration.onEvent({ type: "message", fromSessionId: "peer-same", payload: {
582
+ version: 1,
583
+ sessionId: "s-peer-same",
584
+ cwd: testCwd,
585
+ title: "Peer Same Title",
586
+ summaryMarkdown: "Working on same CWD with secret sk-proj-123456789012345 and path /.pi/agent/sessions/secret.jsonl",
587
+ generatedAt: "2026-08-05T01:00:00.000Z",
588
+ } });
589
+ intercomRegistration.onEvent({ type: "message", fromSessionId: "peer-cross", payload: {
590
+ version: 1,
591
+ sessionId: "s-peer-cross",
592
+ cwd: crossCwd,
593
+ title: "Peer Cross Title",
594
+ summaryMarkdown: "Working on cross CWD",
595
+ generatedAt: "2026-08-05T01:00:00.000Z",
596
+ } });
597
+ intercomRegistration.onEvent({ type: "message", fromSessionId: "self-sender-1", payload: {
598
+ version: 1,
599
+ sessionId: "s-self",
600
+ cwd: testCwd,
601
+ title: "Self Payload",
602
+ summaryMarkdown: "Self payload should be excluded",
603
+ generatedAt: "2026-08-05T01:00:00.000Z",
604
+ } });
605
+
606
+ let toolResult = await workspaceTool.execute("call-1", {}, undefined, undefined, w2Ctx);
607
+ let toolText = toolResult.content[0].text;
608
+ assert.match(toolText, /Peer Same Title/);
609
+ assert.equal(toolText.includes("Peer Cross Title"), false, "cross-CWD live peer excluded");
610
+ assert.equal(toolText.includes("Self Payload"), false, "self live payload excluded");
611
+ assert.equal(toolText.includes("sk-proj-123456789012345"), false, "raw API secret redacted from tool output");
612
+ assert.match(toolText, /\[redacted secret\]/);
613
+ assert.equal(toolText.includes("/.pi/agent/sessions/secret.jsonl"), false, "private session path redacted from tool output");
614
+ assert.match(toolText, /\[private session path\]/);
615
+ intercomRegistration.onEvent({ type: "session_joined", session: { id: "peer-same", cwd: testCwd } });
616
+ toolResult = await workspaceTool.execute("call-replaced", {}, undefined, undefined, w2Ctx);
617
+ assert.equal(toolResult.content[0].text.includes("Peer Same Title"), false, "a stable sender-ID replacement invalidates the prior live summary until the replacement publishes");
618
+ intercomRegistration.onEvent({ type: "message", fromSessionId: "peer-same", payload: {
619
+ version: 1,
620
+ sessionId: "s-peer-same",
621
+ cwd: testCwd,
622
+ title: "Peer Same Title",
623
+ summaryMarkdown: "Replacement summary",
624
+ generatedAt: "2026-08-05T01:10:00.000Z",
625
+ } });
626
+
627
+ fakeChannel.peers.set("peer-malformed", { cwd: testCwd, pid: process.pid + 3 });
628
+ intercomRegistration.onEvent({ type: "message", fromSessionId: "peer-malformed", payload: { version: 99, sessionId: "s-bad" } });
629
+ toolResult = await workspaceTool.execute("call-2", {}, undefined, undefined, w2Ctx);
630
+ assert.equal(toolResult.content[0].text.includes("s-bad"), false, "malformed payload ignored");
631
+
632
+ fakeChannel.peers.delete("peer-same");
633
+ intercomRegistration.onEvent({ type: "session_left", sessionId: "peer-same" });
634
+ toolResult = await workspaceTool.execute("call-3", {}, undefined, undefined, w2Ctx);
635
+ assert.equal(toolResult.content[0].text.includes("Peer Same Title"), false, "disconnected peer removed");
636
+
637
+ const summaryCmd = w2Commands.get("summary");
638
+ await summaryCmd.handler("workspace", w2Ctx);
639
+ const workspaceDisplayEntry = w2Branch.findLast((entry) => entry.type === "custom" && entry.customType === SESSION_SUMMARY_DISPLAY_TYPE);
640
+ assert.equal(workspaceDisplayEntry.data.title, "Workspace session summaries");
641
+ assert.match(workspaceDisplayEntry.data.summaryMarkdown, /Workspace session summaries/);
642
+
643
+ fakeChannel.connected = false;
644
+ intercomRegistration.onEvent({ type: "connection", connected: false, supported: false });
645
+ toolResult = await workspaceTool.execute("call-4", {}, undefined, undefined, w2Ctx);
646
+ assert.match(toolResult.content[0].text, /Live peer status is unavailable/);
647
+
648
+ let fallbackRegisteredTool;
649
+ const noEventsApi = {
650
+ on() {},
651
+ registerCommand() {},
652
+ registerTool(tool) { fallbackRegisteredTool = tool; },
653
+ registerEntryRenderer() {},
654
+ getSessionName() { return "Self Title"; },
655
+ };
656
+ createSessionSummaryExtension({ completeFn: fakeComplete })(noEventsApi);
657
+ const customSessionDir = join(extensionTemp, "configured-session-dir");
658
+ await mkdir(customSessionDir);
659
+ const persistedPeerState = {
660
+ ...baseState,
661
+ source: { ...baseState.source, sessionId: "configured-peer" },
662
+ result: { title: "Configured session dir peer", summaryMarkdown: "# Persisted peer" },
663
+ };
664
+ await writeFile(join(customSessionDir, "configured-peer.jsonl"), [
665
+ JSON.stringify({ type: "session", version: 3, id: "configured-peer", timestamp: "2026-08-05T00:00:00.000Z", cwd: testCwd }),
666
+ JSON.stringify({ type: "custom", id: "peer0001", parentId: null, timestamp: "2026-08-05T00:01:00.000Z", customType: SESSION_SUMMARY_STATE_TYPE, data: persistedPeerState }),
667
+ ].join("\n") + "\n");
668
+ const fallbackCtx = {
669
+ ...w2Ctx,
670
+ sessionManager: {
671
+ ...w2Ctx.sessionManager,
672
+ getSessionFile: () => join(extensionTemp, "external", "s-self.jsonl"),
673
+ getSessionDir: () => customSessionDir,
674
+ },
675
+ };
676
+ const fallbackResult = await fallbackRegisteredTool.execute("call-5", {}, undefined, undefined, fallbackCtx);
677
+ assert.match(fallbackResult.content[0].text, /Live peer status is unavailable/);
678
+ assert.match(fallbackResult.content[0].text, /Configured session dir peer/, "configured session directory is preferred over the current session file parent");
679
+
485
680
  } finally {
486
681
  if (previousConfigFile === undefined) delete process.env.PI_SESSION_SUMMARY_CONFIG_FILE;
487
682
  else process.env.PI_SESSION_SUMMARY_CONFIG_FILE = previousConfigFile;
@@ -0,0 +1,34 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [app, css, layout, html, serviceWorker] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "public", "styles.css"), "utf8"),
10
+ readFile(join(root, "lib", "ui-layout-settings.mjs"), "utf8"),
11
+ readFile(join(root, "public", "index.html"), "utf8"),
12
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
13
+ ]);
14
+
15
+ for (const removedToken of [
16
+ "data-side-panel-section-resize",
17
+ "initializeSidePanelSectionResizing",
18
+ "persistSidePanelSectionHeight",
19
+ "beginSidePanelSectionResize",
20
+ "side-panel-section-resize-handle",
21
+ "side-panel-section-resizing",
22
+ ]) {
23
+ assert.doesNotMatch(app, new RegExp(removedToken), `${removedToken} should be absent from the browser controller`);
24
+ assert.doesNotMatch(css, new RegExp(removedToken), `${removedToken} should be absent from side-panel styles`);
25
+ }
26
+ assert.doesNotMatch(layout, /sectionHeightMin|sectionHeightMax|validateSectionHeights|sectionHeights/, "the durable layout schema should not expose section heights");
27
+ assert.match(app, /const UI_LAYOUT_SIDE_PANEL_FIELDS = \["sectionOrder", "collapsedSectionIds", "hiddenSectionIds", "collapsed"\];/, "the browser durable layout field list should omit section heights");
28
+ assert.match(app, /function clearRemovedSidePanelSectionHeightState\(\)[\s\S]*localStorage\.removeItem\(REMOVED_SIDE_PANEL_SECTION_HEIGHT_STORAGE_KEY\)[\s\S]*record\.field === "sidePanel" && record\.subfield === "sectionHeights"/, "startup should remove the retired cache and pending mutations");
29
+ assert.match(app, /clearRemovedSidePanelSectionHeightState\(\);\s*restoreDurableUiLayoutPendingJournal\(\);/, "retired height state should be cleared before pending layout restoration");
30
+ assert.match(html, /styles\.css\?v=104/, "removing section resize styles should advance the stylesheet revision");
31
+ assert.match(html, /app\.js\?v=120/, "removing section resize behavior should advance the app revision");
32
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "removing browser assets should advance the PWA cache identity");
33
+
34
+ console.log("side-panel-section-height-removal-static.test.mjs passed");
@@ -61,8 +61,8 @@ assert.match(
61
61
  /\.side-panel-section-toggle\[data-side-panel-section-toggle\][\s\S]*cursor: grab[\s\S]*touch-action: none[\s\S]*\.side-panel-section\.dragging[\s\S]*cursor: grabbing[\s\S]*\.drag-over-before[\s\S]*\.drag-over-after/,
62
62
  "section headers should expose model-picker-style grab, dragging, and insertion-marker affordances",
63
63
  );
64
- assert.match(html, /styles\.css\?v=98/, "changed side-panel styles should advance the stylesheet revision");
65
- assert.match(html, /app\.js\?v=113/, "changed side-panel behavior should advance the app revision");
66
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v72"/, "changed browser assets should advance the PWA cache identity");
64
+ assert.match(html, /styles\.css\?v=104/, "changed side-panel styles should advance the stylesheet revision");
65
+ assert.match(html, /app\.js\?v=120/, "changed side-panel behavior should advance the app revision");
66
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "changed browser assets should advance the PWA cache identity");
67
67
 
68
68
  console.log("side-panel-section-reorder-static.test.mjs passed");
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
5
5
  import path from "node:path";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { setTimeout as delay } from "node:timers/promises";
8
9
 
9
10
  const root = join(dirname(fileURLToPath(import.meta.url)), "..");
10
11
  const workspaceRoot = join(root, "..");
@@ -13,6 +14,29 @@ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
13
14
  const reviewModuleUrl = pathToFileURL(join(workspaceRoot, "pi-extension-aur-review", "src", "git.ts")).href;
14
15
  const port = 41000 + Math.floor(Math.random() * 10000);
15
16
 
17
+ async function waitForChildClose(child, timeoutMs = 2_000) {
18
+ if (child.exitCode !== null) return true;
19
+ return Promise.race([
20
+ new Promise((resolve) => child.once("close", () => resolve(true))),
21
+ delay(timeoutMs, false),
22
+ ]);
23
+ }
24
+
25
+ async function rmWithRetry(target) {
26
+ let lastError;
27
+ for (let attempt = 0; attempt < 20; attempt += 1) {
28
+ try {
29
+ await rm(target, { recursive: true, force: true });
30
+ return;
31
+ } catch (error) {
32
+ lastError = error;
33
+ if (!["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) throw error;
34
+ await delay(Math.min(500, 150 * (attempt + 1)));
35
+ }
36
+ }
37
+ throw lastError;
38
+ }
39
+
16
40
  function git(cwd, ...args) {
17
41
  const result = spawnSync("git", args, { cwd, encoding: "utf8" });
18
42
  assert.equal(result.status, 0, `git ${args.join(" ")} failed:\n${result.stderr || result.stdout}`);
@@ -56,6 +80,7 @@ const child = spawn(process.execPath, [serverScript, "--cwd", repo, "--host", "1
56
80
  ...process.env,
57
81
  PI_CODING_AGENT_DIR: agentDir,
58
82
  PI_WEBUI_SETTINGS_FILE: path.join(agentDir, "settings.json"),
83
+ PI_WEBUI_RPC_SUPERVISOR: "0",
59
84
  },
60
85
  });
61
86
  let serverOutput = "";
@@ -130,10 +155,19 @@ try {
130
155
  await assertMatchesExtension("mode");
131
156
  reset();
132
157
 
133
- await symlink("normal.txt", path.join(repo, "normal-link"));
134
- git(repo, "add", "normal-link");
135
- await assertMatchesExtension("symlink");
136
- reset();
158
+ let symlinkSupported = true;
159
+ try {
160
+ await symlink("normal.txt", path.join(repo, "normal-link"));
161
+ } catch (error) {
162
+ if (!["EACCES", "EPERM"].includes(error?.code)) throw error;
163
+ symlinkSupported = false;
164
+ console.log(`staged-content-hash-contract: symlink unavailable (${error.code}); skipping symlink hash case`);
165
+ }
166
+ if (symlinkSupported) {
167
+ git(repo, "add", "normal-link");
168
+ await assertMatchesExtension("symlink");
169
+ reset();
170
+ }
137
171
 
138
172
  await writeFile(path.join(repo, "added.txt"), "added\n");
139
173
  git(repo, "rm", "-q", "deleted.txt");
@@ -164,11 +198,18 @@ try {
164
198
 
165
199
  console.log("staged content hash contract tests passed");
166
200
  } finally {
167
- child.kill("SIGTERM");
168
- await Promise.race([
169
- new Promise((resolve) => child.once("close", resolve)),
170
- new Promise((resolve) => setTimeout(resolve, 2_000)),
171
- ]);
172
- if (child.exitCode === null) child.kill("SIGKILL");
173
- await Promise.all([rm(repo, { recursive: true, force: true }), rm(agentDir, { recursive: true, force: true })]);
201
+ if (child.exitCode === null) {
202
+ try {
203
+ await request("/api/shutdown", { method: "POST" });
204
+ } catch {
205
+ // Fall back to direct termination below when the server is already unavailable.
206
+ }
207
+ }
208
+ if (child.exitCode === null) child.kill("SIGTERM");
209
+ if (!(await waitForChildClose(child))) {
210
+ child.kill("SIGKILL");
211
+ await waitForChildClose(child);
212
+ }
213
+ await delay(500);
214
+ await Promise.all([rmWithRetry(repo), rmWithRetry(agentDir)]);
174
215
  }
@@ -0,0 +1,134 @@
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
+ const packageJson = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
9
+
10
+ function functionDeclaration(source, name) {
11
+ const match = new RegExp(`function\\s+${name}\\s*\\(`).exec(source);
12
+ assert.ok(match, `${name} should be defined`);
13
+ let parens = 0;
14
+ let open = -1;
15
+ for (let index = match.index + match[0].length - 1; index < source.length; index += 1) {
16
+ if (source[index] === "(") parens += 1;
17
+ else if (source[index] === ")") parens -= 1;
18
+ else if (source[index] === "{" && parens === 0) {
19
+ open = index;
20
+ break;
21
+ }
22
+ }
23
+ assert.notEqual(open, -1, `${name} should open`);
24
+ let depth = 0;
25
+ for (let index = open; index < source.length; index += 1) {
26
+ if (source[index] === "{") depth += 1;
27
+ else if (source[index] === "}" && --depth === 0) return source.slice(match.index, index + 1);
28
+ }
29
+ assert.fail(`${name} should close`);
30
+ }
31
+
32
+ const handleEventSource = functionDeclaration(app, "handleEvent");
33
+ const inactiveTabGuardIndex = handleEventSource.indexOf("if (!eventTargetsActiveTab(event))");
34
+ const runEpochAdvanceIndex = handleEventSource.indexOf('if (event?.type === "agent_start") beginToolBoundaryRun(event);');
35
+ assert.ok(runEpochAdvanceIndex >= 0 && runEpochAdvanceIndex < inactiveTabGuardIndex, "agent_start must advance tool-run identity before inactive-tab routing");
36
+ assert.equal((handleEventSource.match(/beginToolBoundaryRun\(event\)/g) || []).length, 1, "agent_start must advance the tool-run epoch exactly once");
37
+
38
+ // Execute the production partitioning helpers directly. An immediate switch to
39
+ // tab B must not merge or drop tab A's settlement/workflow flags.
40
+ {
41
+ const declarations = [
42
+ "semanticReconcileContextKey",
43
+ "mergeSemanticReconcileRequest",
44
+ "takeSemanticReconcileRequests",
45
+ ].map((name) => functionDeclaration(app, name)).join("\n");
46
+ const createHarness = new Function("SEMANTIC_RECONCILE_FLAGS", `${declarations}\nreturn { mergeSemanticReconcileRequest, takeSemanticReconcileRequests };`);
47
+ const harness = createHarness(["messages", "state", "footer", "footerData", "feedback", "usage", "workflow"]);
48
+ const pending = new Map();
49
+ const tabA = { tabId: "tab-a", generation: 11 };
50
+ const tabB = { tabId: "tab-b", generation: 12 };
51
+
52
+ harness.mergeSemanticReconcileRequest(pending, { state: true, workflow: true }, tabA);
53
+ harness.mergeSemanticReconcileRequest(pending, { footer: true }, tabB);
54
+ harness.mergeSemanticReconcileRequest(pending, { messages: true }, tabA);
55
+ const requests = harness.takeSemanticReconcileRequests(pending);
56
+ assert.equal(pending.size, 0);
57
+ assert.equal(requests.length, 2, "tab generations must retain independent reconciliation requests");
58
+ const requestA = requests.find((request) => request.tabContext.tabId === "tab-a");
59
+ const requestB = requests.find((request) => request.tabContext.tabId === "tab-b");
60
+ assert.deepEqual(requestA, { tabContext: tabA, dirty: { state: true, workflow: true, messages: true } });
61
+ assert.deepEqual(requestB, { tabContext: tabB, dirty: { footer: true } });
62
+
63
+ const current = tabB;
64
+ const workflowTabs = requests.filter(({ dirty }) => dirty.workflow).map(({ tabContext }) => tabContext.tabId);
65
+ const activeDomRequests = requests.filter(({ tabContext }) => tabContext.tabId === current.tabId && tabContext.generation === current.generation);
66
+ assert.deepEqual(workflowTabs, ["tab-a"], "originating-tab workflow settlement must survive the immediate switch");
67
+ assert.deepEqual(activeDomRequests.map(({ dirty }) => dirty), [{ footer: true }], "stale tab A DOM work must not be reassigned to tab B");
68
+ }
69
+
70
+ // Execute the production run-key/dedupe path with a deterministic skill sink.
71
+ // Replays dedupe, a new run may reuse an ID, and unusable start args leave the
72
+ // completion fallback available.
73
+ {
74
+ const declarations = [
75
+ "beginToolBoundaryRun",
76
+ "toolBoundaryRunIdentity",
77
+ "toolBoundaryRecordKey",
78
+ "rememberToolBoundaryRecordKey",
79
+ "claimToolBoundaryRecord",
80
+ "trackSkillsFromEvent",
81
+ ].map((name) => functionDeclaration(app, name)).join("\n");
82
+ const createHarness = new Function(`
83
+ let activeTabId = "tab-a";
84
+ const TOOL_BOUNDARY_RECORD_LIMIT = 400;
85
+ const toolBoundaryRunEpochByTab = new Map();
86
+ const recordedToolBoundaryKeys = new Set();
87
+ const tracked = [];
88
+ function trackSkillsFromToolInvocation(tabId, toolName, args, options) {
89
+ const usable = String(toolName || "").toLowerCase() === "read" && typeof args?.path === "string" && args.path.endsWith("SKILL.md");
90
+ if (usable) tracked.push({ tabId, path: args.path, source: options.sourcePrefix });
91
+ return usable;
92
+ }
93
+ function clearSkillUsageForTab() {}
94
+ ${declarations}
95
+ return { beginToolBoundaryRun, claimToolBoundaryRecord, trackSkillsFromEvent, tracked, recordedToolBoundaryKeys, toolBoundaryRunEpochByTab };
96
+ `);
97
+ const harness = createHarness();
98
+ const skillPath = "/tmp/example/SKILL.md";
99
+
100
+ harness.beginToolBoundaryRun({ type: "agent_start", tabId: "tab-a" });
101
+ const first = { type: "tool_execution_start", tabId: "tab-a", toolCallId: "same-id", toolName: "read", args: { path: skillPath } };
102
+ harness.trackSkillsFromEvent(first);
103
+ harness.trackSkillsFromEvent({ ...first, replayed: true });
104
+ assert.equal(harness.tracked.length, 1, "replayed boundaries in one run must dedupe");
105
+
106
+ harness.beginToolBoundaryRun({ type: "agent_start", tabId: "tab-a", replayed: true });
107
+ harness.trackSkillsFromEvent(first);
108
+ assert.equal(harness.tracked.length, 1, "a replayed agent_start must not create a new run epoch");
109
+
110
+ harness.beginToolBoundaryRun({ type: "agent_start", tabId: "tab-a" });
111
+ harness.trackSkillsFromEvent(first);
112
+ assert.equal(harness.tracked.length, 2, "the same tool ID must be recordable in a new agent run");
113
+
114
+ harness.beginToolBoundaryRun({ type: "agent_start", tabId: "tab-a" });
115
+ const missingStart = { type: "tool_execution_start", tabId: "tab-a", toolCallId: "fallback-id", toolName: "read", args: {} };
116
+ harness.trackSkillsFromEvent(missingStart);
117
+ assert.equal(harness.tracked.length, 2, "unusable start args must not create a false skill record");
118
+ const usableEnd = { ...missingStart, type: "tool_execution_end", args: { path: skillPath } };
119
+ harness.trackSkillsFromEvent(usableEnd);
120
+ harness.trackSkillsFromEvent({ ...usableEnd, replayed: true });
121
+ assert.equal(harness.tracked.length, 3, "completion should fill missing start data once and still dedupe replay");
122
+
123
+ const inactiveTool = { type: "tool_execution_start", tabId: "tab-b", toolCallId: "inactive-same-id", toolName: "read", args: { path: skillPath } };
124
+ harness.beginToolBoundaryRun({ type: "agent_start", tabId: "tab-b" });
125
+ harness.trackSkillsFromEvent(inactiveTool);
126
+ harness.beginToolBoundaryRun({ type: "agent_start", tabId: "tab-b" });
127
+ harness.trackSkillsFromEvent(inactiveTool);
128
+ assert.equal(harness.tracked.length, 5, "an inactive tab must record a reused tool ID once in each new run");
129
+ assert.equal(harness.toolBoundaryRunEpochByTab.get("tab-b"), 2, "inactive agent starts must advance their tab-local run epoch");
130
+ }
131
+
132
+ assert.match(packageJson.scripts.check, /node --check public\/stream-output-controller\.mjs/, "canonical npm check must syntax-check the startup stream controller");
133
+
134
+ console.log("stream-lifecycle-core.test.mjs passed");