@firstpick/pi-package-webui 0.8.4 → 0.8.6

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 (50) hide show
  1. package/README.md +24 -2
  2. package/bin/pi-webui.mjs +383 -31
  3. package/index.ts +8 -1
  4. package/lib/git-workflow-preferences.mjs +3 -0
  5. package/lib/session-summary-core.mjs +4 -3
  6. package/lib/trust-boundaries.mjs +13 -0
  7. package/lib/workspace-session-summaries.mjs +400 -0
  8. package/package.json +2 -2
  9. package/public/app.js +1242 -267
  10. package/public/index.html +77 -4
  11. package/public/service-worker.js +3 -1
  12. package/public/stream-output-controller.mjs +327 -0
  13. package/public/styles.css +249 -70
  14. package/public/theme-contract.mjs +244 -0
  15. package/session-summary.ts +164 -4
  16. package/tests/aur-review-widget-static.test.mjs +2 -1
  17. package/tests/boot-failure-diagnostics.test.mjs +2 -2
  18. package/tests/browser/interaction-continuity.spec.mjs +2 -2
  19. package/tests/browser/session-summary.spec.mjs +131 -3
  20. package/tests/browser/stream-output-isolation.spec.mjs +510 -0
  21. package/tests/codex-fast-mode-static.test.mjs +2 -2
  22. package/tests/composer-action-grid-reorder-static.test.mjs +2 -2
  23. package/tests/fast-mode-client-static.test.mjs +3 -2
  24. package/tests/feature-decision-output-popup-static.test.mjs +1 -1
  25. package/tests/fixtures/fake-pi.mjs +203 -2
  26. package/tests/git-workflow-preferences.test.mjs +7 -1
  27. package/tests/guided-git-aur-review.test.mjs +4 -3
  28. package/tests/http-endpoints-harness.test.mjs +224 -13
  29. package/tests/mobile-continuity-tablet-static.test.mjs +2 -2
  30. package/tests/mobile-foundation-static.test.mjs +3 -4
  31. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  32. package/tests/mobile-static.test.mjs +63 -29
  33. package/tests/native-parity.test.mjs +1 -1
  34. package/tests/open-issue-wizard-static.test.mjs +2 -3
  35. package/tests/optional-feature-migration-frontend.test.mjs +3 -0
  36. package/tests/persistent-ui-layout-static.test.mjs +2 -2
  37. package/tests/questionnaire-dialog.test.mjs +2 -2
  38. package/tests/remote-auth-settings-harness.test.mjs +9 -0
  39. package/tests/session-summary-core.test.mjs +183 -1
  40. package/tests/side-panel-section-reorder-static.test.mjs +2 -2
  41. package/tests/stream-lifecycle-core.test.mjs +134 -0
  42. package/tests/stream-output-controller.test.mjs +252 -0
  43. package/tests/stream-output-isolation-static.test.mjs +89 -0
  44. package/tests/streaming-ui-coupling.test.mjs +50 -0
  45. package/tests/subagent-gate-visibility.test.mjs +1 -1
  46. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  47. package/tests/theme-contract.test.mjs +104 -0
  48. package/tests/theme-customizer-static.test.mjs +82 -0
  49. package/tests/theme-scheme-mode.test.mjs +15 -0
  50. package/tests/workspace-session-summaries.test.mjs +288 -0
@@ -1,5 +1,5 @@
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
5
  import { writeSessionSummaryPreferences } from "../lib/session-summary-preferences.mjs";
@@ -98,6 +98,8 @@ assert.equal(latestSummaryState([{
98
98
  data: { ...baseState, result: { ...baseState.result, summaryMarkdown: escapedPersistedSummary } },
99
99
  }]).result.summaryMarkdown, escapedPersistedSummary, "persisted state validation uses the decoded Markdown bound");
100
100
  assert.equal(latestSummaryState([{ type: "custom", customType: SESSION_SUMMARY_STATE_TYPE, data: { version: 99 } }]), undefined);
101
+ const titlelessState = { ...baseState, result: { summaryMarkdown: "# Valid titleless summary" }, titleAppliedAtOrdinal: undefined };
102
+ assert.equal(latestSummaryState([{ type: "custom", customType: SESSION_SUMMARY_STATE_TYPE, data: titlelessState }]).result.summaryMarkdown, "# Valid titleless summary", "valid titleless generated states remain discoverable");
101
103
  assert.deepEqual(latestSummaryNameProvenance([
102
104
  { type: "custom", customType: SESSION_SUMMARY_NAME_PROVENANCE_TYPE, data: { version: 1, explicit: true } },
103
105
  { type: "custom", customType: SESSION_SUMMARY_NAME_PROVENANCE_TYPE, data: { version: 99, explicit: false } },
@@ -254,6 +256,7 @@ try {
254
256
  const api = {
255
257
  on(name, handler) { handlers.set(name, handler); },
256
258
  registerCommand(name, options) { commands.set(name, options); },
259
+ registerTool() {},
257
260
  registerEntryRenderer(name, renderer) { renderers.set(name, renderer); },
258
261
  sendMessage(message) {
259
262
  const id = `e${activeBranch.length + 1}`;
@@ -482,6 +485,185 @@ try {
482
485
  routingIds.add(calledOptions.sessionId);
483
486
  }
484
487
  assert.equal(routingIds.size, representativeCases.length, "each representative provider call gets a fresh routing ID");
488
+
489
+ // W2 integration: use pi-intercom's documented extension-channel contract.
490
+ class FakeChannel {
491
+ connected = true;
492
+ supported = true;
493
+ published = [];
494
+ peers = new Map();
495
+ snapshot() { return { connected: this.connected, supported: this.supported }; }
496
+ publish(payload, options) { this.published.push({ payload, options }); }
497
+ async listSessions() {
498
+ return [...this.peers.entries()].map(([id, value]) => ({ id, cwd: value.cwd, pid: value.pid }));
499
+ }
500
+ }
501
+
502
+ const testCwd = "/tmp/test-workspace-a";
503
+ const crossCwd = "/tmp/test-workspace-b";
504
+ const fakeChannel = new FakeChannel();
505
+ fakeChannel.peers.set("self-sender-1", { cwd: testCwd, pid: process.pid });
506
+ const w2Tools = new Map();
507
+ const w2Commands = new Map();
508
+ const w2Branch = [
509
+ { type: "message", id: "m1", message: { role: "user", content: "Work on feature" } },
510
+ { type: "custom", customType: SESSION_SUMMARY_STATE_TYPE, data: {
511
+ version: 1,
512
+ source: { sessionId: "s-self", leafId: "m1", fingerprint: "fp-self", entryCount: 1 },
513
+ result: { title: "Self Title", summaryMarkdown: "# Self Summary\n\nWorking on feature" },
514
+ generation: { provider: "fake", modelId: "fake", thinkingLevel: "low", promptRevision: "v1" },
515
+ generatedAt: "2026-08-05T00:00:00.000Z",
516
+ settledTurnOrdinal: 1,
517
+ } },
518
+ ];
519
+ let intercomRegistration;
520
+ const w2Api = {
521
+ events: {
522
+ emit(event, registration) {
523
+ if (event !== "intercom:extension-register") return;
524
+ intercomRegistration = registration;
525
+ registration.onReady(fakeChannel);
526
+ },
527
+ },
528
+ on(name, handler) { handlers.set(name, handler); },
529
+ registerCommand(name, options) { w2Commands.set(name, options); },
530
+ registerTool(tool) { w2Tools.set(tool.name, tool); },
531
+ registerEntryRenderer() {},
532
+ sendMessage() {},
533
+ appendEntry(customType, data) { w2Branch.push({ type: "custom", customType, data }); },
534
+ getSessionName() { return "Self Title"; },
535
+ };
536
+
537
+ createSessionSummaryExtension({ completeFn: fakeComplete })(w2Api);
538
+ assert.equal(w2Tools.has("workspace_session_summaries"), true, "workspace_session_summaries tool registered");
539
+ const workspaceTool = w2Tools.get("workspace_session_summaries");
540
+ assert.match(workspaceTool.promptSnippet, /same-CWD session summaries/);
541
+ assert.equal(Array.isArray(workspaceTool.promptGuidelines), true, "tool guidelines use the Pi array contract");
542
+ assert.match(workspaceTool.promptGuidelines.join("\n"), /intercom/);
543
+
544
+ const w2Ctx = {
545
+ cwd: testCwd,
546
+ sessionManager: {
547
+ getBranch: () => w2Branch.slice(),
548
+ getSessionId: () => "s-self",
549
+ getSessionFile: () => join(extensionTemp, "s-self.jsonl"),
550
+ },
551
+ };
552
+ await handlers.get("session_start")({ type: "session_start", reason: "startup" }, w2Ctx);
553
+ assert.equal(intercomRegistration.namespace, "firstpick/session-summary/v1");
554
+ assert.equal(intercomRegistration.ownerEligible, false);
555
+ assert.equal(typeof intercomRegistration.onEvent, "function");
556
+ assert.equal(fakeChannel.published.at(-1)?.options?.audience, "capable");
557
+ const initialPublicationCount = fakeChannel.published.length;
558
+ intercomRegistration.onEvent({ type: "session_joined", session: { id: "new-peer", cwd: testCwd } });
559
+ assert.equal(fakeChannel.published.length, initialPublicationCount + 1, "a joining capable peer triggers summary republication");
560
+ fakeChannel.connected = false;
561
+ intercomRegistration.onEvent({ type: "connection", connected: false, supported: false });
562
+ fakeChannel.connected = true;
563
+ intercomRegistration.onEvent({ type: "connection", connected: true, supported: true });
564
+ assert.equal(fakeChannel.published.length, initialPublicationCount + 2, "a supported reconnect republishes the current summary");
565
+
566
+ fakeChannel.peers.set("peer-same", { cwd: testCwd, pid: process.pid + 1 });
567
+ fakeChannel.peers.set("peer-cross", { cwd: crossCwd, pid: process.pid + 2 });
568
+ intercomRegistration.onEvent({ type: "message", fromSessionId: "peer-same", payload: {
569
+ version: 1,
570
+ sessionId: "s-peer-same",
571
+ cwd: testCwd,
572
+ title: "Peer Same Title",
573
+ summaryMarkdown: "Working on same CWD with secret sk-proj-123456789012345 and path /.pi/agent/sessions/secret.jsonl",
574
+ generatedAt: "2026-08-05T01:00:00.000Z",
575
+ } });
576
+ intercomRegistration.onEvent({ type: "message", fromSessionId: "peer-cross", payload: {
577
+ version: 1,
578
+ sessionId: "s-peer-cross",
579
+ cwd: crossCwd,
580
+ title: "Peer Cross Title",
581
+ summaryMarkdown: "Working on cross CWD",
582
+ generatedAt: "2026-08-05T01:00:00.000Z",
583
+ } });
584
+ intercomRegistration.onEvent({ type: "message", fromSessionId: "self-sender-1", payload: {
585
+ version: 1,
586
+ sessionId: "s-self",
587
+ cwd: testCwd,
588
+ title: "Self Payload",
589
+ summaryMarkdown: "Self payload should be excluded",
590
+ generatedAt: "2026-08-05T01:00:00.000Z",
591
+ } });
592
+
593
+ let toolResult = await workspaceTool.execute("call-1", {}, undefined, undefined, w2Ctx);
594
+ let toolText = toolResult.content[0].text;
595
+ assert.match(toolText, /Peer Same Title/);
596
+ assert.equal(toolText.includes("Peer Cross Title"), false, "cross-CWD live peer excluded");
597
+ assert.equal(toolText.includes("Self Payload"), false, "self live payload excluded");
598
+ assert.equal(toolText.includes("sk-proj-123456789012345"), false, "raw API secret redacted from tool output");
599
+ assert.match(toolText, /\[redacted secret\]/);
600
+ assert.equal(toolText.includes("/.pi/agent/sessions/secret.jsonl"), false, "private session path redacted from tool output");
601
+ assert.match(toolText, /\[private session path\]/);
602
+ intercomRegistration.onEvent({ type: "session_joined", session: { id: "peer-same", cwd: testCwd } });
603
+ toolResult = await workspaceTool.execute("call-replaced", {}, undefined, undefined, w2Ctx);
604
+ 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");
605
+ intercomRegistration.onEvent({ type: "message", fromSessionId: "peer-same", payload: {
606
+ version: 1,
607
+ sessionId: "s-peer-same",
608
+ cwd: testCwd,
609
+ title: "Peer Same Title",
610
+ summaryMarkdown: "Replacement summary",
611
+ generatedAt: "2026-08-05T01:10:00.000Z",
612
+ } });
613
+
614
+ fakeChannel.peers.set("peer-malformed", { cwd: testCwd, pid: process.pid + 3 });
615
+ intercomRegistration.onEvent({ type: "message", fromSessionId: "peer-malformed", payload: { version: 99, sessionId: "s-bad" } });
616
+ toolResult = await workspaceTool.execute("call-2", {}, undefined, undefined, w2Ctx);
617
+ assert.equal(toolResult.content[0].text.includes("s-bad"), false, "malformed payload ignored");
618
+
619
+ fakeChannel.peers.delete("peer-same");
620
+ intercomRegistration.onEvent({ type: "session_left", sessionId: "peer-same" });
621
+ toolResult = await workspaceTool.execute("call-3", {}, undefined, undefined, w2Ctx);
622
+ assert.equal(toolResult.content[0].text.includes("Peer Same Title"), false, "disconnected peer removed");
623
+
624
+ const summaryCmd = w2Commands.get("summary");
625
+ await summaryCmd.handler("workspace", w2Ctx);
626
+ const workspaceDisplayEntry = w2Branch.findLast((entry) => entry.type === "custom" && entry.customType === SESSION_SUMMARY_DISPLAY_TYPE);
627
+ assert.equal(workspaceDisplayEntry.data.title, "Workspace session summaries");
628
+ assert.match(workspaceDisplayEntry.data.summaryMarkdown, /Workspace session summaries/);
629
+
630
+ fakeChannel.connected = false;
631
+ intercomRegistration.onEvent({ type: "connection", connected: false, supported: false });
632
+ toolResult = await workspaceTool.execute("call-4", {}, undefined, undefined, w2Ctx);
633
+ assert.match(toolResult.content[0].text, /Live peer status is unavailable/);
634
+
635
+ let fallbackRegisteredTool;
636
+ const noEventsApi = {
637
+ on() {},
638
+ registerCommand() {},
639
+ registerTool(tool) { fallbackRegisteredTool = tool; },
640
+ registerEntryRenderer() {},
641
+ getSessionName() { return "Self Title"; },
642
+ };
643
+ createSessionSummaryExtension({ completeFn: fakeComplete })(noEventsApi);
644
+ const customSessionDir = join(extensionTemp, "configured-session-dir");
645
+ await mkdir(customSessionDir);
646
+ const persistedPeerState = {
647
+ ...baseState,
648
+ source: { ...baseState.source, sessionId: "configured-peer" },
649
+ result: { title: "Configured session dir peer", summaryMarkdown: "# Persisted peer" },
650
+ };
651
+ await writeFile(join(customSessionDir, "configured-peer.jsonl"), [
652
+ JSON.stringify({ type: "session", version: 3, id: "configured-peer", timestamp: "2026-08-05T00:00:00.000Z", cwd: testCwd }),
653
+ JSON.stringify({ type: "custom", id: "peer0001", parentId: null, timestamp: "2026-08-05T00:01:00.000Z", customType: SESSION_SUMMARY_STATE_TYPE, data: persistedPeerState }),
654
+ ].join("\n") + "\n");
655
+ const fallbackCtx = {
656
+ ...w2Ctx,
657
+ sessionManager: {
658
+ ...w2Ctx.sessionManager,
659
+ getSessionFile: () => join(extensionTemp, "external", "s-self.jsonl"),
660
+ getSessionDir: () => customSessionDir,
661
+ },
662
+ };
663
+ const fallbackResult = await fallbackRegisteredTool.execute("call-5", {}, undefined, undefined, fallbackCtx);
664
+ assert.match(fallbackResult.content[0].text, /Live peer status is unavailable/);
665
+ assert.match(fallbackResult.content[0].text, /Configured session dir peer/, "configured session directory is preferred over the current session file parent");
666
+
485
667
  } finally {
486
668
  if (previousConfigFile === undefined) delete process.env.PI_SESSION_SUMMARY_CONFIG_FILE;
487
669
  else process.env.PI_SESSION_SUMMARY_CONFIG_FILE = previousConfigFile;
@@ -62,7 +62,7 @@ assert.match(
62
62
  "section headers should expose model-picker-style grab, dragging, and insertion-marker affordances",
63
63
  );
64
64
  assert.match(html, /styles\.css\?v=98/, "changed side-panel styles should advance the stylesheet revision");
65
- assert.match(html, /app\.js\?v=112/, "changed side-panel behavior should advance the app revision");
66
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v71"/, "changed browser assets should advance the PWA cache identity");
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-v74"/, "changed browser assets should advance the PWA cache identity");
67
67
 
68
68
  console.log("side-panel-section-reorder-static.test.mjs passed");
@@ -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");
@@ -0,0 +1,252 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ DEFAULT_STREAM_PENDING_BYTE_LIMIT,
4
+ DEFAULT_STREAM_PENDING_ENTRY_LIMIT,
5
+ TRANSCRIPT_STREAM_MESSAGE_UPDATE_TYPES,
6
+ classifyTranscriptStreamEvent,
7
+ createStreamOutputController,
8
+ } from "../public/stream-output-controller.mjs";
9
+
10
+ function messageUpdate(type, delta = "", extra = {}) {
11
+ return { type: "message_update", assistantMessageEvent: { type, delta, ...extra } };
12
+ }
13
+
14
+ class FakeFrames {
15
+ next = 1;
16
+ callbacks = new Map();
17
+ cancelled = [];
18
+
19
+ schedule = (callback) => {
20
+ const handle = this.next++;
21
+ this.callbacks.set(handle, callback);
22
+ return handle;
23
+ };
24
+
25
+ cancel = (handle) => {
26
+ this.cancelled.push(handle);
27
+ this.callbacks.delete(handle);
28
+ };
29
+
30
+ run(handle = this.callbacks.keys().next().value) {
31
+ const callback = this.callbacks.get(handle);
32
+ assert.equal(typeof callback, "function", `frame ${handle} should be pending`);
33
+ this.callbacks.delete(handle);
34
+ callback();
35
+ }
36
+ }
37
+
38
+ assert.deepEqual(TRANSCRIPT_STREAM_MESSAGE_UPDATE_TYPES, [
39
+ "thinking_start", "thinking_delta", "thinking_end",
40
+ "text_start", "text_delta", "text_end",
41
+ "toolcall_start", "toolcall_delta", "toolcall_end",
42
+ "error",
43
+ ]);
44
+ assert.deepEqual(classifyTranscriptStreamEvent(messageUpdate("text_delta")), {
45
+ kind: "text", subtype: "text_delta", recognized: true, barrier: false,
46
+ });
47
+ assert.equal(classifyTranscriptStreamEvent(messageUpdate("thinking_end")).barrier, true);
48
+ assert.equal(classifyTranscriptStreamEvent(messageUpdate("toolcall_end")).kind, "tool-call");
49
+ assert.equal(classifyTranscriptStreamEvent({ type: "tool_execution_update" }).kind, "tool-execution");
50
+ assert.deepEqual(classifyTranscriptStreamEvent(messageUpdate("future_delta")), {
51
+ kind: "unknown-message-update", subtype: "future_delta", recognized: false, barrier: false,
52
+ });
53
+ assert.equal(classifyTranscriptStreamEvent({ type: "agent_start" }), null);
54
+ assert.equal(DEFAULT_STREAM_PENDING_ENTRY_LIMIT, 128);
55
+ assert.equal(DEFAULT_STREAM_PENDING_BYTE_LIMIT, 256 * 1024);
56
+
57
+ // Adjacent compatible deltas coalesce, while kind changes retain exact order.
58
+ {
59
+ const frames = new FakeFrames();
60
+ const calls = [];
61
+ const controller = createStreamOutputController({
62
+ scheduleFrame: frames.schedule,
63
+ cancelFrame: frames.cancel,
64
+ applyTextUpdate: (event) => calls.push(`text:${event.assistantMessageEvent.delta}`),
65
+ applyThinkingUpdate: (event) => calls.push(`thinking:${event.assistantMessageEvent.delta}`),
66
+ applyToolCallUpdate: (event) => calls.push(`tool-call:${event.assistantMessageEvent.delta}`),
67
+ applyToolExecutionUpdate: (event) => calls.push(`tool-execution:${event.partialResult?.content || ""}`),
68
+ applyFollowScroll: () => calls.push("follow"),
69
+ });
70
+ controller.dispatch(messageUpdate("text_delta", "A"));
71
+ controller.dispatch(messageUpdate("text_delta", "B"));
72
+ controller.dispatch(messageUpdate("thinking_delta", "C"));
73
+ controller.dispatch(messageUpdate("thinking_delta", "D"));
74
+ controller.dispatch(messageUpdate("toolcall_delta", "E", { contentIndex: 2, toolCall: { id: "tool-1" } }));
75
+ controller.dispatch(messageUpdate("toolcall_delta", "F", { contentIndex: 2, toolCall: { id: "tool-1" } }));
76
+ controller.dispatch({ type: "tool_execution_update", toolCallId: "tool-1", partialResult: { content: "partial" } });
77
+ controller.dispatch({ type: "tool_execution_update", toolCallId: "tool-1", partialResult: { content: "complete" } });
78
+ assert.equal(frames.callbacks.size, 1, "all raw updates should share one frame");
79
+ assert.equal(controller.pendingCount(), 4, "four adjacent semantic groups should remain");
80
+ frames.run();
81
+ assert.deepEqual(calls, ["text:AB", "thinking:CD", "tool-call:EF", "tool-execution:complete", "follow"]);
82
+ }
83
+
84
+ // A realistic 1,000-delta burst is lossless and bounded to one sink call.
85
+ {
86
+ const frames = new FakeFrames();
87
+ const chunks = Array.from({ length: 1_000 }, (_, index) => `[${index}]`);
88
+ const applied = [];
89
+ const controller = createStreamOutputController({
90
+ scheduleFrame: frames.schedule,
91
+ cancelFrame: frames.cancel,
92
+ applyTextUpdate: (event) => applied.push(event.assistantMessageEvent.delta),
93
+ });
94
+ for (let index = 0; index < chunks.length; index += 1) {
95
+ controller.dispatch({ ...messageUpdate("text_delta", chunks[index]), isolationDeltaIndex: index });
96
+ }
97
+ assert.equal(controller.pendingCount(), 1, "adjacent non-empty text deltas should coalesce to one pending entry");
98
+ assert.ok(controller.pendingBytes() <= controller.limits().maxPendingBytes);
99
+ frames.run();
100
+ assert.deepEqual(applied, [chunks.join("")], "coalescing must preserve exact output bytes and order");
101
+ }
102
+
103
+ // Alternating kinds cannot coalesce, so count overflow drains synchronously
104
+ // instead of dropping or retaining an unbounded queue.
105
+ {
106
+ const frames = new FakeFrames();
107
+ const calls = [];
108
+ const overflows = [];
109
+ const controller = createStreamOutputController({
110
+ scheduleFrame: frames.schedule,
111
+ cancelFrame: frames.cancel,
112
+ maxPendingEntries: 4,
113
+ maxPendingBytes: 10_000,
114
+ applyTextUpdate: (event) => calls.push(`t${event.assistantMessageEvent.delta}`),
115
+ applyThinkingUpdate: (event) => calls.push(`h${event.assistantMessageEvent.delta}`),
116
+ onOverflow: (overflow) => overflows.push(overflow.reason),
117
+ });
118
+ const expected = [];
119
+ for (let index = 0; index < 21; index += 1) {
120
+ const text = index % 2 === 0;
121
+ expected.push(`${text ? "t" : "h"}${index}`);
122
+ controller.dispatch(messageUpdate(text ? "text_delta" : "thinking_delta", String(index)));
123
+ assert.ok(controller.pendingCount() <= 4, "pending count must never exceed its configured bound");
124
+ assert.ok(controller.pendingBytes() <= 10_000, "pending bytes must never exceed their configured bound");
125
+ }
126
+ controller.barrier("test-overflow-tail");
127
+ assert.deepEqual(calls, expected);
128
+ assert.ok(overflows.includes("entry-limit"));
129
+ assert.equal(frames.callbacks.size, 0);
130
+ }
131
+
132
+ // A single oversize event is applied directly after the prior batch. It is not
133
+ // retained beyond the byte bound and no content is lost.
134
+ {
135
+ const calls = [];
136
+ const overflows = [];
137
+ const controller = createStreamOutputController({
138
+ maxPendingBytes: 80,
139
+ applyTextUpdate: (event) => calls.push(event.assistantMessageEvent.delta),
140
+ onOverflow: (overflow) => overflows.push(overflow.reason),
141
+ });
142
+ controller.dispatch(messageUpdate("text_delta", "x".repeat(200)));
143
+ assert.equal(controller.pendingCount(), 0);
144
+ assert.equal(controller.pendingBytes(), 0);
145
+ assert.deepEqual(calls, ["x".repeat(200)]);
146
+ assert.ok(overflows.includes("oversize-event"));
147
+ }
148
+
149
+ // Raw and semantic barriers preserve text/thinking/tool/error chronology and
150
+ // cancel the retained frame before the transition can mutate chrome.
151
+ {
152
+ const frames = new FakeFrames();
153
+ const calls = [];
154
+ const controller = createStreamOutputController({
155
+ scheduleFrame: frames.schedule,
156
+ cancelFrame: frames.cancel,
157
+ applyTextUpdate: (event) => calls.push(`text:${event.assistantMessageEvent.delta}`),
158
+ applyThinkingUpdate: (event) => calls.push(`thinking:${event.assistantMessageEvent.delta}`),
159
+ applyToolExecutionUpdate: (event) => calls.push(`tool:${event.partialResult.content}`),
160
+ applyStreamError: () => calls.push("error"),
161
+ applyFollowScroll: () => calls.push("follow"),
162
+ });
163
+ controller.dispatch(messageUpdate("text_delta", "tail"));
164
+ controller.dispatch(messageUpdate("thinking_delta", "thought"));
165
+ controller.dispatch({ type: "tool_execution_update", toolCallId: "t", partialResult: { content: "tool tail" } });
166
+ const queuedHandle = frames.callbacks.keys().next().value;
167
+ assert.equal(controller.barrier("auto_retry_start"), 3);
168
+ assert.deepEqual(calls, ["text:tail", "thinking:thought", "tool:tool tail", "follow"]);
169
+ assert.ok(frames.cancelled.includes(queuedHandle));
170
+ controller.dispatch(messageUpdate("thinking_delta", "before-end"));
171
+ controller.dispatch(messageUpdate("thinking_end"));
172
+ assert.deepEqual(calls.slice(-3), ["thinking:before-end", "thinking:", "follow"]);
173
+ controller.dispatch(messageUpdate("error"));
174
+ assert.deepEqual(calls.slice(-2), ["error", "follow"], "stream errors must never be dropped by batching");
175
+ controller.dispatch(messageUpdate("text_delta", "abort-tail"));
176
+ const abortHandle = frames.callbacks.keys().next().value;
177
+ assert.equal(controller.barrier("user-abort"), 1);
178
+ assert.deepEqual(calls.slice(-2), ["text:abort-tail", "follow"], "user abort must synchronously preserve a pending text tail");
179
+ assert.ok(frames.cancelled.includes(abortHandle));
180
+ }
181
+
182
+ // Hidden-frame delay preserves the tail; a stale owner is rejected both at
183
+ // dispatch and if ownership changes before the delayed frame runs.
184
+ {
185
+ const frames = new FakeFrames();
186
+ const calls = [];
187
+ let currentOwner = "tab-a:1";
188
+ const controller = createStreamOutputController({
189
+ scheduleFrame: frames.schedule,
190
+ cancelFrame: frames.cancel,
191
+ isOwnerCurrent: (owner) => owner === currentOwner,
192
+ applyTextUpdate: (event) => calls.push(event.assistantMessageEvent.delta),
193
+ onStaleOwner: (_event, owner) => calls.push(`stale:${owner}`),
194
+ });
195
+ controller.dispatch(messageUpdate("text_delta", "hidden-tail"), { owner: currentOwner });
196
+ assert.deepEqual(calls, [], "a throttled/hidden frame may remain pending without losing output");
197
+ controller.barrier("visibility-barrier");
198
+ assert.deepEqual(calls, ["hidden-tail"]);
199
+ controller.dispatch(messageUpdate("text_delta", "stale-later"), { owner: currentOwner });
200
+ currentOwner = "tab-a:2";
201
+ frames.run();
202
+ assert.deepEqual(calls, ["hidden-tail", "stale:tab-a:1"]);
203
+ assert.equal(controller.dispatch(messageUpdate("text_delta", "stale-now"), { owner: "tab-b:1" }), true);
204
+ assert.deepEqual(calls, ["hidden-tail", "stale:tab-a:1", "stale:tab-b:1"]);
205
+ }
206
+
207
+ // Unknown transcript-shaped events remain isolated but reach the fallback with
208
+ // bounded diagnostic metadata; indexed coalesced input reports receipt/apply.
209
+ {
210
+ const frames = new FakeFrames();
211
+ const unknown = [];
212
+ const diagnostics = [];
213
+ const controller = createStreamOutputController({
214
+ scheduleFrame: frames.schedule,
215
+ cancelFrame: frames.cancel,
216
+ applyTextUpdate: () => {},
217
+ onUnknownStreamEvent: (event, classification, owner) => unknown.push({ event, classification, owner }),
218
+ onDiagnostic: (record) => diagnostics.push(record),
219
+ });
220
+ controller.dispatch({ ...messageUpdate("text_delta", "A"), isolationDeltaIndex: 0 }, { owner: "tab:1" });
221
+ controller.dispatch({ ...messageUpdate("text_delta", "B"), isolationDeltaIndex: 1 }, { owner: "tab:1" });
222
+ controller.dispatch(messageUpdate("future_delta", "preserve me"), { owner: "tab:1" });
223
+ frames.run();
224
+ assert.equal(unknown.length, 1);
225
+ assert.equal(unknown[0].event.assistantMessageEvent.delta, "preserve me");
226
+ assert.equal(unknown[0].classification.subtype, "future_delta");
227
+ const receipts = diagnostics.filter((record) => record.type === "receipt");
228
+ assert.deepEqual(receipts.slice(0, 2).map((record) => record.index), [0, 1]);
229
+ const textApply = diagnostics.find((record) => record.type === "apply" && record.kind === "text");
230
+ assert.equal(textApply.sourceCount, 2);
231
+ assert.deepEqual(textApply.sourceIndexes, [0, 1]);
232
+ }
233
+
234
+ for (const mode of ["normal", "compact-v1"]) {
235
+ const frames = new FakeFrames();
236
+ const seen = [];
237
+ const controller = createStreamOutputController({
238
+ scheduleFrame: frames.schedule,
239
+ cancelFrame: frames.cancel,
240
+ applyTextUpdate: (event) => seen.push(`${mode}:${event.assistantMessageEvent.delta}`),
241
+ applyFollowScroll: () => seen.push(`${mode}:follow`),
242
+ });
243
+ controller.dispatch(messageUpdate("text_delta", "same"));
244
+ controller.dispatch(messageUpdate("text_delta", " output"));
245
+ frames.run();
246
+ assert.deepEqual(seen, [`${mode}:same output`, `${mode}:follow`], `${mode} should use the same coalescing and ordering contract`);
247
+ }
248
+
249
+ assert.throws(() => createStreamOutputController({ maxPendingEntries: 0 }), /positive safe integer/);
250
+ assert.throws(() => createStreamOutputController({ maxPendingBytes: -1 }), /positive safe integer/);
251
+
252
+ console.log("stream-output-controller.test.mjs passed");