@firstpick/pi-package-webui 0.7.3 → 0.7.5

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 (34) hide show
  1. package/README.md +34 -20
  2. package/bin/pi-webui.mjs +332 -39
  3. package/index.ts +10 -1
  4. package/lib/git-workflow-preferences.mjs +91 -22
  5. package/lib/subagent-launch-slots.mjs +304 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/webui-output-mode.mjs +97 -0
  8. package/package.json +22 -22
  9. package/public/app.js +1629 -69
  10. package/public/fast-output-live.mjs +179 -0
  11. package/public/index.html +86 -12
  12. package/public/service-worker.js +3 -1
  13. package/public/styles.css +769 -37
  14. package/public/subagent-launch-slot-state.mjs +64 -0
  15. package/tests/chat-scroll-intent-static.test.mjs +59 -0
  16. package/tests/custom-message-markdown-static.test.mjs +15 -0
  17. package/tests/fast-mode-client-static.test.mjs +169 -0
  18. package/tests/fast-mode-output-work.test.mjs +69 -0
  19. package/tests/fast-mode-sse-harness.test.mjs +204 -0
  20. package/tests/fast-output-live.test.mjs +106 -0
  21. package/tests/fixtures/fake-pi.mjs +58 -0
  22. package/tests/fixtures/fast-mode-output-events.mjs +50 -0
  23. package/tests/footer-middle-truncation.test.mjs +2 -2
  24. package/tests/git-workflow-preferences.test.mjs +8 -2
  25. package/tests/http-endpoints-harness.test.mjs +74 -0
  26. package/tests/mobile-static.test.mjs +86 -15
  27. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  28. package/tests/side-panel-resize-static.test.mjs +43 -0
  29. package/tests/subagent-launch-slot-state.test.mjs +36 -0
  30. package/tests/subagent-launch-slots-static.test.mjs +34 -0
  31. package/tests/subagent-launch-slots.test.mjs +143 -0
  32. package/tests/subagents-helper.test.mjs +46 -0
  33. package/tests/webui-output-mode.test.mjs +73 -0
  34. package/webui-rpc-helper.mjs +37 -9
@@ -0,0 +1,64 @@
1
+ function cloneSlot(slot = {}) {
2
+ return {
3
+ id: String(slot.id || ""),
4
+ model: typeof slot.model === "string" ? slot.model : null,
5
+ thinking: typeof slot.thinking === "string" ? slot.thinking : null,
6
+ };
7
+ }
8
+
9
+ export function cloneLaunchSlotRoles(roles = {}) {
10
+ return Object.fromEntries(Object.entries(roles || {}).map(([roleId, slots]) => [
11
+ roleId,
12
+ Array.isArray(slots) ? slots.map(cloneSlot) : [],
13
+ ]));
14
+ }
15
+
16
+ export function launchSlotRolesEqual(left, right) {
17
+ const leftRoles = Object.keys(left || {}).sort();
18
+ const rightRoles = Object.keys(right || {}).sort();
19
+ if (leftRoles.length !== rightRoles.length || leftRoles.some((roleId, index) => roleId !== rightRoles[index])) return false;
20
+ return leftRoles.every((roleId) => {
21
+ const leftSlots = Array.isArray(left?.[roleId]) ? left[roleId] : [];
22
+ const rightSlots = Array.isArray(right?.[roleId]) ? right[roleId] : [];
23
+ return leftSlots.length === rightSlots.length && leftSlots.every((slot, index) => (
24
+ slot?.id === rightSlots[index]?.id
25
+ && (slot?.model || null) === (rightSlots[index]?.model || null)
26
+ && (slot?.thinking || null) === (rightSlots[index]?.thinking || null)
27
+ ));
28
+ });
29
+ }
30
+
31
+ export function updateLaunchSlot(roles, roleId, slotId, patch = {}) {
32
+ const next = cloneLaunchSlotRoles(roles);
33
+ const slots = next[roleId];
34
+ const index = Array.isArray(slots) ? slots.findIndex((slot) => slot.id === slotId) : -1;
35
+ if (index < 0) return next;
36
+ const model = Object.hasOwn(patch, "model") ? (patch.model || null) : slots[index].model;
37
+ const thinking = model && Object.hasOwn(patch, "thinking") ? (patch.thinking || null) : model ? slots[index].thinking : null;
38
+ slots[index] = { ...slots[index], model, thinking };
39
+ return next;
40
+ }
41
+
42
+ export function addLaunchSlot(roles, roleId, sourceSlotId, { slotsPerRole = 8, totalSlots = 32, createId } = {}) {
43
+ const next = cloneLaunchSlotRoles(roles);
44
+ const slots = next[roleId];
45
+ if (!Array.isArray(slots) || slots.length >= slotsPerRole) return null;
46
+ const total = Object.values(next).reduce((count, value) => count + (Array.isArray(value) ? value.length : 0), 0);
47
+ if (total >= totalSlots) return null;
48
+ const source = slots.find((slot) => slot.id === sourceSlotId) || slots[slots.length - 1];
49
+ const id = typeof createId === "function" ? String(createId(roleId, slots) || "") : "";
50
+ if (!id || slots.some((slot) => slot.id === id)) return null;
51
+ const slot = { id, model: source?.model || null, thinking: source?.model ? source.thinking || null : null };
52
+ slots.push(slot);
53
+ return { roles: next, slot };
54
+ }
55
+
56
+ export function removeLaunchSlot(roles, roleId, slotId, baseSlotId = `${roleId}:base`) {
57
+ if (slotId === baseSlotId) return null;
58
+ const next = cloneLaunchSlotRoles(roles);
59
+ const slots = next[roleId];
60
+ const index = Array.isArray(slots) ? slots.findIndex((slot) => slot.id === slotId) : -1;
61
+ if (index < 0) return null;
62
+ const [removed] = slots.splice(index, 1);
63
+ return { roles: next, removed, focusSlotId: slots[Math.max(0, index - 1)]?.id || null };
64
+ }
@@ -0,0 +1,59 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
8
+
9
+ function findFunctionBody(source, name) {
10
+ const signature = new RegExp(`function\\s+${name}\\s*\\(`, "m");
11
+ const match = signature.exec(source);
12
+ assert.ok(match, `${name} should be defined`);
13
+ let parenDepth = 0;
14
+ let openBrace = -1;
15
+ for (let index = match.index + match[0].length - 1; index < source.length; index += 1) {
16
+ const char = source[index];
17
+ if (char === "(") parenDepth += 1;
18
+ else if (char === ")") parenDepth -= 1;
19
+ else if (char === "{" && parenDepth === 0) {
20
+ openBrace = index;
21
+ break;
22
+ }
23
+ }
24
+ assert.notEqual(openBrace, -1, `${name} body should open`);
25
+ let depth = 0;
26
+ for (let index = openBrace; index < source.length; index += 1) {
27
+ const char = source[index];
28
+ if (char === "{") depth += 1;
29
+ else if (char === "}") {
30
+ depth -= 1;
31
+ if (depth === 0) return source.slice(openBrace + 1, index);
32
+ }
33
+ }
34
+ assert.fail(`${name} body should close`);
35
+ }
36
+
37
+ const touchStart = findFunctionBody(app, "noteChatTouchStart");
38
+ const awayIntent = findFunctionBody(app, "isChatScrollAwayIntent");
39
+ const noteIntent = findFunctionBody(app, "noteChatUserScrollIntent");
40
+ const syncAutoFollow = findFunctionBody(app, "syncAutoFollowFromChatScroll");
41
+ const updateLatest = findFunctionBody(app, "updateJumpToLatestButton");
42
+ const applyFollow = findFunctionBody(app, "applyChatFollowScroll");
43
+ const resumeFollow = findFunctionBody(app, "resumeChatAutoFollow");
44
+ const forceFollow = findFunctionBody(app, "scrollChatToBottom");
45
+
46
+ assert.match(awayIntent, /event\?\.type === "wheel"[\s\S]*event\.deltaY < 0/, "wheel-up should be recognized as intent to read earlier output");
47
+ assert.match(touchStart, /touches\?\.\[0\]\?\.clientY[\s\S]*chatLastTouchClientY/, "touch scrolling should capture its starting direction");
48
+ assert.match(awayIntent, /event\?\.type === "touchmove"[\s\S]*clientY > chatLastTouchClientY[\s\S]*return scrollAway/, "downward finger movement should pause follow while upward movement can resume at Latest");
49
+ assert.match(awayIntent, /"ArrowUp"[\s\S]*"Home"[\s\S]*"PageUp"/, "upward keyboard navigation should pause streaming follow");
50
+ assert.match(noteIntent, /autoFollowChat = false;[\s\S]*updateJumpToLatestButton\(\)/, "upward intent should pause follow and reveal Latest before the scroll event fires");
51
+ assert.match(syncAutoFollow, /^\s*const nearBottom[\s\S]*if \(isChatUserScrollAwayIntentActive\(\)\) \{\s*autoFollowChat = false;/, "the near-bottom threshold must not re-enable follow during active upward input");
52
+ assert.match(updateLatest, /hidden = autoFollowChat/, "Latest visibility should reflect paused follow even while still inside the near-bottom threshold");
53
+ assert.doesNotMatch(updateLatest, /isChatNearBottom/, "Latest must not remain hidden solely because the first upward movement is near the bottom");
54
+ assert.match(applyFollow, /if \(!autoFollowChat\)[\s\S]*return;/, "already queued streaming frames must honor the immediate follow pause");
55
+ assert.match(resumeFollow, /chatUserScrollAwayIntentUntil = 0;[\s\S]*autoFollowChat = true;/, "explicit resume should clear stale upward intent before following again");
56
+ assert.match(forceFollow, /if \(force\) resumeChatAutoFollow\(\)/, "Latest and other forced-bottom actions should use the explicit resume path");
57
+ assert.match(app, /addEventListener\("touchstart", noteChatTouchStart[\s\S]*addEventListener\("touchend", clearChatTouchIntent[\s\S]*addEventListener\("touchcancel", clearChatTouchIntent/, "touch direction tracking should be initialized and cleared for each gesture");
58
+
59
+ console.log("chat-scroll-intent-static.test.mjs passed");
@@ -0,0 +1,15 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
8
+
9
+ assert.match(
10
+ app,
11
+ /renderContent\(body, message\.content, \{ markdown: message\.role === "assistant" \|\| message\.role === "custom" \}\)/,
12
+ "assistant and custom message output should render as Markdown",
13
+ );
14
+
15
+ console.log("custom message Markdown static check passed");
@@ -0,0 +1,169 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { createFastModeOutputEvents } from "./fixtures/fast-mode-output-events.mjs";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const [app, helper, html, worker, styles, packageRaw] = await Promise.all([
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ readFile(join(root, "public", "fast-output-live.mjs"), "utf8"),
11
+ readFile(join(root, "public", "index.html"), "utf8"),
12
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
13
+ readFile(join(root, "public", "styles.css"), "utf8"),
14
+ readFile(join(root, "package.json"), "utf8"),
15
+ ]);
16
+
17
+ function functionBody(source, name) {
18
+ const marker = `function ${name}(`;
19
+ const start = source.indexOf(marker);
20
+ assert.notEqual(start, -1, `${name} should be defined`);
21
+ let parenDepth = 0;
22
+ let open = -1;
23
+ for (let index = start + marker.length - 1; index < source.length; index += 1) {
24
+ if (source[index] === "(") parenDepth += 1;
25
+ else if (source[index] === ")") parenDepth -= 1;
26
+ else if (source[index] === "{" && parenDepth === 0) {
27
+ open = index;
28
+ break;
29
+ }
30
+ }
31
+ assert.notEqual(open, -1, `${name} should open`);
32
+ let depth = 0;
33
+ for (let index = open; index < source.length; index += 1) {
34
+ if (source[index] === "{") depth += 1;
35
+ if (source[index] === "}") {
36
+ depth -= 1;
37
+ if (depth === 0) return source.slice(open + 1, index);
38
+ }
39
+ }
40
+ assert.fail(`${name} should close`);
41
+ }
42
+
43
+ const connectEvents = functionBody(app, "connectEvents");
44
+ const compactUpdate = functionBody(app, "handleCompactMessageUpdate");
45
+ const compactFlush = functionBody(app, "flushCompactLiveOutput");
46
+ const compactThinkingBubble = functionBody(app, "ensureCompactThinkingBubble");
47
+ const compactToolShell = functionBody(app, "renderCompactToolShell");
48
+ const clearCompactToolShells = functionBody(app, "clearCompactToolShells");
49
+ const compactTranscript = functionBody(app, "renderCompactTranscriptBody");
50
+ const compactThinkingDisclosureExpanded = functionBody(app, "compactThinkingDisclosureExpanded");
51
+ const setCompactThinkingDisclosureExpanded = functionBody(app, "setCompactThinkingDisclosureExpanded");
52
+ const clearCompactThinkingDisclosureState = functionBody(app, "clearCompactThinkingDisclosureState");
53
+ const createMessageBubble = functionBody(app, "createMessageBubble");
54
+ const appendTranscriptMessage = functionBody(app, "appendTranscriptMessage");
55
+ const compactThinkingSegments = functionBody(app, "compactThinkingSegments");
56
+ const compactStoredTranscriptItems = functionBody(app, "compactStoredTranscriptItems");
57
+ const orderedTranscriptItems = functionBody(app, "orderedTranscriptItems");
58
+ const transcriptRenderEpoch = functionBody(app, "transcriptRenderEpoch");
59
+ const compactLiveStreamActive = functionBody(app, "compactLiveStreamRenderActive");
60
+ const restoreCompactStream = functionBody(app, "restoreCompactLiveOutputAfterChatRebuild");
61
+ const refreshMessages = functionBody(app, "refreshMessages");
62
+ const resetCompactLiveOutput = functionBody(app, "resetCompactLiveOutput");
63
+ const resetStream = functionBody(app, "resetStreamBubble");
64
+ const normalToCompact = functionBody(app, "transitionNormalLiveOutputToCompact");
65
+ const compactToNormal = functionBody(app, "transitionCompactLiveOutputToNormal");
66
+ const nativeSettingsDialog = functionBody(app, "openNativeSettingsDialog");
67
+ const nativeSettingsPayload = functionBody(app, "collectNativeSettingsPayload");
68
+ const outputModeMetadataText = functionBody(app, "webuiOutputModeMetadataText");
69
+ const sidebarOutputModeRefresh = functionBody(app, "refreshSidebarOutputMode");
70
+ const sidebarOutputModeApply = functionBody(app, "applySidebarOutputMode");
71
+
72
+ assert.match(app, /from "\.\/fast-output-live\.mjs"/, "browser should import the pure compact live helper");
73
+ assert.match(connectEvents, /outputMode:\s*eventSourceOutputModeRequest/, "all new EventSource connections should negotiate an explicit output mode");
74
+ assert.match(connectEvents, /outputModeProtocol:\s*"1"/, "all new EventSource connections should negotiate protocol 1");
75
+ assert.match(app, /function outputModeAcknowledgement[\s\S]*?outputMode\?\.protocolVersion !== 1[\s\S]*?function acceptOutputModeAcknowledgement[\s\S]*?outputModeAcknowledgement\(event\)[\s\S]*?connectEvents\(activeTabContext\(\), \{ requestedMode: "normal", fallbackAttempted: true \}\)/, "unacknowledged or old servers should receive one normal-mode fallback");
76
+ assert.match(app, /function compactOutputActive\(\) \{\s+return outputModeAcknowledged && activeOutputMode === "compact-v1";/, "compact rendering must remain acknowledgement-gated");
77
+ assert.match(app, /case "webui_output_mode":[\s\S]*?applyOutputModeControl\(event, tabContext\)/, "mode-control events should be handled before subsequent compact representation events");
78
+ assert.match(app, /function applyOutputModeControl[\s\S]*?finishCompactLiveOutput\(tabContext\)[\s\S]*?resetCompactLiveOutput\(\)/, "mode changes should synchronously flush then reset compact state at semantic boundaries");
79
+ assert.match(normalToCompact, /seedFastOutputLiveState\(\{ text: streamRawText, thinking: streamThinkingRawText \}\)/, "normal-to-compact controls should seed pre-switch text and thinking into the compact state");
80
+ assert.match(normalToCompact, /setStreamRawText\(""\)[\s\S]*?setStreamThinkingRawText\(""\)[\s\S]*?removeStreamBubble\(\)[\s\S]*?removeStreamingThinkingBubble\(\)[\s\S]*?flushCompactLiveOutput\(\)/, "normal-to-compact controls should remove stale normal bubbles and synchronously show the seeded compact state");
81
+ assert.match(compactToNormal, /fastOutputLiveTextAndThinking\(compactLiveState\)[\s\S]*?resetCompactLiveOutput\(\)[\s\S]*?setStreamRawText\(live\.text\)[\s\S]*?setStreamThinkingRawText\(live\.thinking\)[\s\S]*?renderStreamingAssistantText\(\)/, "compact-to-normal controls should transfer pre-switch live text/thinking before normal rendering resumes");
82
+
83
+ assert.doesNotMatch(compactUpdate, /event\.message|assistantMessageEvent\.partial|renderStreamingMarkdown|renderMarkdown|syncLiveTodoProgressWidgetFromText/, "compact deltas should consume direct fields without accumulated scans, markdown, or todo extraction");
84
+ assert.match(compactUpdate, /reduceFastOutputLiveEvent\(compactLiveState, event\)/, "compact deltas should use the pure reducer");
85
+ assert.match(compactUpdate, /shouldConsumeFastOutputLiveEvent\(reduced\)/, "recognized compact empty end variants should be consumed instead of reaching normal handlers with stripped snapshots");
86
+ assert.match(helper, /function shouldConsumeFastOutputLiveEvent\(reduction = \{\}\)[\s\S]*?"text-end"[\s\S]*?"thinking-end"[\s\S]*?"toolcall-end"/, "the reducer policy should consume only recognized compact end variants when no DOM state changes");
87
+ assert.match(compactFlush, /\.textContent = compactLiveState\.text/, "compact assistant text must render through a stable plain-text node while streaming");
88
+ assert.match(compactThinkingBubble, /title: "thinking \(live\)"[\s\S]*?compactThinkingAggregate: true[\s\S]*?compactThinkingKey: "live"[\s\S]*?compactThinkingDefaultExpanded: true[\s\S]*?make\("div", "markdown-body thinking-text compact-live-thinking"\)/, "compact live thinking should use one expanded-by-default aggregate disclosure with a stable key and established Markdown styles");
89
+ assert.match(resetCompactLiveOutput, /clearCompactThinkingDisclosureState\("live"\)/, "a new compact stream should clear any explicit live override and restore its expanded default");
90
+ assert.match(compactFlush, /compactThinkingNode\?\._rawThinkingText !== compactLiveState\.thinking[\s\S]*?renderThinkingMarkdown\(compactThinkingNode, compactLiveState\.thinking\)/, "compact live thinking should preserve Markdown formatting");
91
+ assert.doesNotMatch(compactFlush, /compactThinkingNode\.textContent|renderStreamingMarkdown|renderToolExecution|normalizeToolExecution/, "compact thinking must not fall back to plain text or invoke rich tool renderers");
92
+ assert.doesNotMatch(compactToolShell, /normalizeToolExecution|toolExecutionRenderSignature|renderToolExecution|handleToolExecutionUpdate|JSON\.stringify/, "compact tool shells must defer rich bodies and raw serialization");
93
+ assert.match(app, /case "tool_execution_update":\s+if \(!compactOutputActive\(\)\) handleToolExecutionUpdate\(event\);/, "compact mode should not build intermediate rich tool updates");
94
+ assert.match(app, /case "tool_execution_end":[\s\S]*?compactLiveScheduler\.flushNow\(\)[\s\S]*?renderCompactToolShell\(event, \{ complete: true \}\)[\s\S]*?finishCompactLiveOutput\(tabContext\)/, "compact tool completion should remain lightweight and request final reconciliation");
95
+ assert.match(resetStream, /resetCompactLiveOutput\(\)/, "reset and tab changes should cancel compact pending work");
96
+ assert.match(app, /case "message_end": \{\s+if \(compactOutputActive\(\)\) finishCompactLiveOutput\(tabContext\);/, "message ends should synchronously flush compact output before reconciliation");
97
+ assert.match(app, /case "agent_end":\s+if \(compactOutputActive\(\)\) finishCompactLiveOutput\(tabContext\);/, "agent ends should synchronously flush compact output before reconciliation");
98
+ assert.match(compactTranscript, /message\.role !== "assistant"[\s\S]*?appendMarkdown\(body, output \|\| "_\[non-text output omitted in fast mode\]_"\)[\s\S]*?classList\.add\("compact-transcript-text"\)/, "reconciled fast-mode assistant output should preserve Markdown and explain omitted non-text output");
99
+ assert.doesNotMatch(compactTranscript, /appendText|renderToolExecution|normalizeToolExecution|JSON\.stringify|appendToolOutput|appendToolDiff|appendToolImages/, "fast-mode final output must not fall back to plain text or render tool details");
100
+ assert.match(createMessageBubble, /compactOutputActive\(\) && !streaming[\s\S]*?renderCompactTranscriptBody\(body, message\)/, "final transcript rendering should select the compact Markdown path only for acknowledged fast mode");
101
+ assert.match(appendTranscriptMessage, /compactTranscript && transcriptMessage\.role !== "assistant"/, "fast-mode assistant reconciliation should defer all thinking to the aggregate transcript item and retain only final output");
102
+ assert.match(compactThinkingSegments, /!thinkingOutputVisible\) return \[\][\s\S]*?message\?\.role === "thinking"[\s\S]*?assistantDisplayMessages\(message\)[\s\S]*?displayMessage\.role === "thinking"/, "fast mode should collect direct and embedded assistant thinking segments only when thinking output is enabled");
103
+ assert.match(compactStoredTranscriptItems, /pendingThinking\.segments\.join\("\\n\\n"\)[\s\S]*?compactThinkingAggregate: true[\s\S]*?pendingThinking\.segments\.push\(\.\.\.thinkingSegments\)/, "thinking separated by tool calls should reconcile into one aggregate Markdown payload");
104
+ assert.match(compactStoredTranscriptItems, /message\?\.role === "user"\) flushThinking\(\)[\s\S]*?message\?\.role === "assistant"\) flushThinking\(\)/, "aggregate thinking should stay bounded to one user turn and end before its final assistant output");
105
+ assert.match(createMessageBubble, /compactThinkingAggregate = compactOutputActive\(\)[\s\S]*?message\.compactThinkingAggregate === true[\s\S]*?isCollapsibleOutput = compactThinkingAggregate[\s\S]*?defaultExpanded = message\.compactThinkingDefaultExpanded === true[\s\S]*?details\.open = compactThinkingDisclosureExpanded\(message\.compactThinkingKey, defaultExpanded\)[\s\S]*?setCompactThinkingDisclosureExpanded\(message\.compactThinkingKey, details\.open, defaultExpanded\)[\s\S]*?else if \(shouldOpenMessageCollapseByDefault/, "aggregate thinking should use a native disclosure with role-specific defaults and preserve explicit toggles across reconciliation");
106
+ assert.match(compactThinkingDisclosureExpanded, /compactThinkingDisclosureStateByTab\.get\(activeTabId \|\| "default"\)[\s\S]*?disclosureState\?\.has\(key\)[\s\S]*?!!defaultExpanded/, "aggregate disclosure state should be isolated per terminal tab and fall back to the role-specific default");
107
+ assert.match(setCompactThinkingDisclosureExpanded, /expanded === defaultExpanded[\s\S]*?disclosureState\?\.delete\(key\)[\s\S]*?disclosureState = new Map\(\)[\s\S]*?disclosureState\.set\(key, !!expanded\)/, "aggregate disclosure state should store only explicit overrides from the role-specific default");
108
+ assert.match(clearCompactThinkingDisclosureState, /disclosureState\?\.delete\(key\)[\s\S]*?compactThinkingDisclosureStateByTab\.delete\(tabId\)/, "stream resets should remove a live disclosure override without changing its expanded default");
109
+ assert.match(compactStoredTranscriptItems, /compactThinkingKey: `turn:\$\{pendingThinking\.firstIndex\}`[\s\S]*?transcriptKey: `compact-thinking:\$\{pendingThinking\.firstIndex\}`/, "aggregate thinking should use a turn-stable disclosure and transcript key while later segments arrive");
110
+ assert.match(app, /workflowOverlayMinimizedByTab\.delete\(tabId\)[\s\S]*?compactThinkingDisclosureStateByTab\.delete\(tabId\)/, "closing a terminal tab should discard its aggregate thinking disclosure state");
111
+ assert.match(styles, /\.message\.compact-thinking-aggregate \{[\s\S]*?\.compact-thinking-disclosure[\s\S]*?border-top-color/, "aggregate thinking should render as one compact mauve disclosure box");
112
+ assert.match(orderedTranscriptItems, /compactOutputActive\(\) \? compactStoredTranscriptItems\(\) : \[\]/, "stored fast-mode transcript rows should come from the aggregate thinking projection");
113
+ assert.match(orderedTranscriptItems, /if \(!compactOutputActive\(\)\) latestMessages\.forEach/, "normal mode should retain the unchanged stored-message projection");
114
+ assert.match(orderedTranscriptItems, /if \(!compactOutputActive\(\)\) \{[\s\S]*?liveToolRuns\.entries\(\)/, "live tool-run reconciliation should not retain additional fast-mode tool rows");
115
+ assert.match(transcriptRenderEpoch, /compactOutputActive\(\) \? "compact" : "normal"/, "mode changes should invalidate the keyed transcript renderer");
116
+ assert.match(clearCompactToolShells, /removeCompactLiveBubble\(shell\?\.bubble\)[\s\S]*?compactToolShells\.clear\(\)/, "fast mode should remove previous transient tool shells from the DOM and registry");
117
+ assert.match(compactToolShell, /if \(!shell\) \{\s+clearCompactToolShells\(\)/, "a newly-started tool should replace the previous transient tool shell");
118
+ assert.match(compactToolShell, /shell\.status\.textContent = complete[\s\S]*?event\?\.isError \? "failed" : "done"[\s\S]*?: "running"/, "the current transient tool shell should expose only a non-duplicated status");
119
+ assert.match(styles, /\.message\.compact-tool-shell\s*\{[\s\S]*?display: grid[\s\S]*?grid-template-columns:[\s\S]*?padding: 0\.46rem 0\.62rem[\s\S]*?box-shadow: none/, "fast-mode tool activity should render as a compact horizontal row");
120
+ assert.match(styles, /\.compact-tool-shell \.compact-tool-status\s*\{[\s\S]*?display: inline-flex[\s\S]*?border-radius: 999px[\s\S]*?font-size: 0\.7rem[\s\S]*?text-transform: uppercase/, "the minimal tool status should remain visually distinct as a small pill");
121
+ assert.match(styles, /\.compact-tool-shell\.tool-running \.compact-tool-status[\s\S]*?\.compact-tool-shell\.tool-success \.compact-tool-status[\s\S]*?\.compact-tool-shell\.tool-error \.compact-tool-status/, "running, success, and failure tool states should have distinct visual tones");
122
+ assert.match(compactUpdate, /compactLiveState = reduced\.state;\s+clearCompactToolShells\(\)/, "new assistant or tool-call deltas should clear the preceding transient tool shell");
123
+ assert.match(compactLiveStreamActive, /messageOutputActive = streamMessageActive && Boolean\([\s\S]*?compactLiveState\.text[\s\S]*?compactLiveState\.thinking[\s\S]*?compactOutputActive\(\) && currentState\?\.isStreaming === true && Boolean\(compactToolShells\.size \|\| messageOutputActive\)/, "mid-stream reconciliation should preserve active compact message output or a current tool shell, but not completed final text");
124
+ assert.match(restoreCompactStream, /compactTextBubble = null[\s\S]*?compactThinkingBubble = null[\s\S]*?if \(streamMessageActive\) flushCompactLiveOutput\(\)[\s\S]*?compactToolShells\.values\(\)[\s\S]*?appendChatMessageBubble\(shell\.bubble\)/, "compact message state should be restored only while its message is active, while the current shell can survive between messages");
125
+ assert.match(refreshMessages, /preserveCompactStream = compactLiveStreamRenderActive\(\)[\s\S]*?!preserveCompactStream && !preserveNormalStream[\s\S]*?renderMessages\(latestMessages\)[\s\S]*?preserveCompactStream\) restoreCompactLiveOutputAfterChatRebuild\(\)/, "message refreshes must not reset active compact output before rebuilding the transcript");
126
+
127
+ assert.match(app, /const SETTINGS_OUTPUT_MODE_OPTIONS = \[[\s\S]*?value: "normal"[\s\S]*?value: "compact-v1"/, "settings should offer normal and compact-v1 server defaults");
128
+ assert.match(nativeSettingsDialog, /api\("\/api\/webui-output-mode", \{ scoped: false \}\)/, "opening settings should load output-mode metadata from the separate server API");
129
+ assert.match(nativeSettingsDialog, /outputMode: nativeSettingSelect\("Output processing", outputModeMetadata\.persistedDefault, SETTINGS_OUTPUT_MODE_OPTIONS,[\s\S]*?\{ label: "server", tone: "startup" \}\)/, "Browser workflow should expose a server-badged output-processing selector");
130
+ assert.match(nativeSettingsDialog, /Fast mode preserves Markdown final output, keeps live thinking expanded, groups stored thinking in one collapsed disclosure per turn, shows only the current tool status transiently, and does not change model inference or token generation\. Changes use server barriers without restarting Pi\./, "settings copy should distinguish expanded live thinking from collapsed stored thinking without changing inference semantics");
131
+ assert.match(nativeSettingsDialog, /nativeSettingsSection\("Browser workflow"[\s\S]*?controls\.outputMode/, "the output-mode selector should be placed in Browser workflow");
132
+ assert.match(outputModeMetadataText, /Persisted default:[\s\S]*?Effective mode:[\s\S]*?Source:/, "settings should display persisted default plus effective mode and source");
133
+ assert.match(outputModeMetadataText, /metadata\.overridden[\s\S]*?overrides the persisted setting/, "settings should display CLI/environment override state when it wins");
134
+ assert.match(nativeSettingsDialog, /Output-mode API unavailable:[\s\S]*?Showing the normal default; other settings can still be applied\./, "unavailable output-mode API should leave a visible nonfatal normal-default diagnostic");
135
+ assert.match(nativeSettingsDialog, /controls\.outputMode\.select\.disabled = !!outputModeApiDiagnostic/, "unavailable output-mode API should safely prevent an unpersistable mode change");
136
+ assert.match(nativeSettingsDialog, /method: "PUT",[\s\S]*?body: \{ outputModeDefault: controls\.outputMode\.select\.value \},[\s\S]*?scoped: false,[\s\S]*?const refreshedOutputMode = await api\("\/api\/webui-output-mode", \{ scoped: false \}\)/, "changed output defaults should PUT the server payload and then refresh metadata");
137
+ assert.doesNotMatch(nativeSettingsPayload, /outputMode(?:Default|Metadata|ApiDiagnostic|Changed)?/, "server-scoped output mode must stay out of the native SettingsManager payload");
138
+ assert.match(nativeSettingsDialog, /const response = await nativeCommandApi\("\/api\/settings", \{ method: "POST", body: \{ settings: payload, reload \} \}\);[\s\S]*?nativeSettingsChangedMessage\(response, reload\)/, "existing native settings apply behavior should remain intact");
139
+
140
+ assert.match(html, /data-side-panel-section="controls"[\s\S]*?id="outputProcessingControlsTitle">Output processing<[\s\S]*?<span class="control-scope-badge">Server<\/span>[\s\S]*?id="fastOutputModeSelect"[\s\S]*?<option value="normal">Normal<\/option>[\s\S]*?<option value="compact-v1">Fast<\/option>[\s\S]*?id="setFastOutputModeButton"[\s\S]*?id="fastOutputModeStatus"/, "Controls should expose a server-scoped normal/fast selector with apply button and live status");
141
+ assert.match(app, /fastOutputModeSelect: \$\("#fastOutputModeSelect"\)[\s\S]*?setFastOutputModeButton: \$\("#setFastOutputModeButton"\)[\s\S]*?fastOutputModeStatus: \$\("#fastOutputModeStatus"\)/, "sidebar fast-mode elements should be wired");
142
+ assert.match(sidebarOutputModeRefresh, /api\("\/api\/webui-output-mode", \{ scoped: false \}\)[\s\S]*?normalizeWebuiOutputModeMetadata\(response\.data\)/, "sidebar selector should load current server output-mode metadata");
143
+ assert.match(sidebarOutputModeApply, /method: "PUT"[\s\S]*?body: \{ outputModeDefault \}[\s\S]*?scoped: false[\s\S]*?await refreshSidebarOutputMode\(\)/, "sidebar selector should persist the selected mode and refresh effective metadata");
144
+ assert.match(sidebarOutputModeApply, /outputModeDefault === "compact-v1"[\s\S]*?Fast output mode enabled[\s\S]*?Normal output processing restored/, "sidebar apply feedback should distinguish enabling fast mode from restoring normal mode");
145
+ assert.match(sidebarOutputModeApply, /sidebarOutputModeDiagnostic = ""[\s\S]*?sidebarOutputModeNotice = `Failed to update fast mode:[\s\S]*?You can retry\.`[\s\S]*?sidebarOutputModeLoaded = true/, "a transient apply failure should remain visible without permanently disabling retry");
146
+ assert.match(app, /function renderSidebarOutputModeControl[\s\S]*?sidebarOutputModeNotice[\s\S]*?webuiOutputModeMetadataText\(sidebarOutputModeMetadata\)[\s\S]*?updateSidebarOutputModeApplyState\(\)/, "sidebar status should expose retry notices or persisted/effective/source metadata and apply state");
147
+ assert.match(styles, /\.toggle-control-hint\.warning\s*\{[\s\S]*?color: var\(--ctp-yellow\)/, "sidebar output-mode failures should use the warning palette");
148
+ assert.match(app, /fastOutputModeSelect\?\.addEventListener\("change", \(\) => \{[\s\S]*?sidebarOutputModeNotice = ""[\s\S]*?renderSidebarOutputModeControl\(\{ syncSelection: false \}\)[\s\S]*?setFastOutputModeButton\?\.addEventListener\("click", \(\) => applySidebarOutputMode\(\)/, "sidebar selection should clear transient failures and keep Apply retryable");
149
+ assert.match(app, /refreshSidebarOutputMode\(\)\.catch[\s\S]*?initializeTabs\(\)/, "sidebar output mode should initialize with the WebUI");
150
+
151
+ assert.match(helper, /FAST_OUTPUT_FLUSH_INTERVAL_MS = 100/, "the live scheduler should retain the exact 100 ms sustained-output bound");
152
+ assert.match(worker, /pi-webui-pwa-v44[\s\S]*?"\/fast-output-live\.mjs"/, "PWA cache identity and app shell should include the compact helper");
153
+ assert.match(html, /<label for="fastOutputModeSelect">Fast mode \(Experimental\)<\/label>/, "the sidebar should mark fast mode as experimental");
154
+ assert.match(html, /Markdown final output; live thinking expanded; stored thinking grouped and collapsed/, "the sidebar should distinguish live and stored thinking defaults");
155
+ assert.match(html, /<script type="module" src="\/app\.js\?v=91"><\/script>/, "the PWA entry point should cache-bust browser wiring");
156
+ assert.match(JSON.parse(packageRaw).scripts.check, /node --check public\/fast-output-live\.mjs/, "package checks should parse the compact helper");
157
+
158
+ const events = createFastModeOutputEvents();
159
+ const deltas = events.filter((event) => event?.type === "message_update" && event.assistantMessageEvent?.type === "text_delta");
160
+ const normalScanChars = deltas.reduce((total, event) => total + JSON.stringify(event.message).length + JSON.stringify(event.assistantMessageEvent.partial).length, 0);
161
+ const compactScanChars = deltas.reduce((total, event) => total + event.assistantMessageEvent.delta.length, 0);
162
+ const scanRatio = normalScanChars / compactScanChars;
163
+ const normalFlushes = deltas.length;
164
+ const compactFlushes = Math.ceil(deltas.length / 5); // fixed 20 ms model: first + max one 100 ms flush
165
+ const ledger = { normalScanChars, compactScanChars, scanRatio: Number(scanRatio.toFixed(3)), normalFlushes, compactFlushes, normalDomWrites: normalFlushes, compactDomWrites: compactFlushes };
166
+ assert.ok(scanRatio >= 1.5, `compact browser scan ledger must improve by >= 1.5x: ${JSON.stringify(ledger)}`);
167
+ assert.ok(compactFlushes <= normalFlushes && ledger.compactDomWrites <= ledger.normalDomWrites, `compact modeled flush/DOM work must not increase: ${JSON.stringify(ledger)}`);
168
+ console.log(`fast-mode client ledger ${JSON.stringify(ledger)}`);
169
+ console.log("fast-mode-client-static.test.mjs passed");
@@ -0,0 +1,69 @@
1
+ import assert from "node:assert/strict";
2
+ import { createHash } from "node:crypto";
3
+ import { browserOutputEvent, encodeBrowserSseEvent } from "../lib/webui-output-mode.mjs";
4
+ import { createFastModeOutputEvents, fixedFastModeTraceMetadata } from "./fixtures/fast-mode-output-events.mjs";
5
+
6
+ function utf8Bytes(value) {
7
+ return Buffer.byteLength(value, "utf8");
8
+ }
9
+
10
+ function semanticPayload(encodedEvents) {
11
+ const semantics = { lifecycle: [], text: "", indices: [], finalMessage: null, toolEvents: [], errors: [] };
12
+ for (const encoded of encodedEvents) {
13
+ const event = JSON.parse(encoded);
14
+ if (event.type === "message_update") {
15
+ const update = event.assistantMessageEvent;
16
+ if (update?.type === "text_delta") {
17
+ semantics.text += update.delta;
18
+ semantics.indices.push(update.contentIndex ?? event.contentIndex ?? null);
19
+ }
20
+ continue;
21
+ }
22
+ if (["agent_start", "message_start", "message_end", "agent_end"].includes(event.type)) semantics.lifecycle.push(event.type);
23
+ if (event.type === "message_end") semantics.finalMessage = event.message;
24
+ if (["tool_execution_start", "tool_execution_end"].includes(event.type)) {
25
+ semantics.toolEvents.push({ type: event.type, toolCallId: event.toolCallId, toolName: event.toolName, isError: event.isError, result: event.result });
26
+ }
27
+ if (event.error !== undefined) semantics.errors.push({ type: event.type, error: event.error });
28
+ }
29
+ return semantics;
30
+ }
31
+
32
+ function runProductionSeam(outputMode) {
33
+ const events = createFastModeOutputEvents();
34
+ const original = structuredClone(events);
35
+ const R = events.reduce((total, event) => total + utf8Bytes(JSON.stringify(event)), 0);
36
+ const encoded = events.map((event) => encodeBrowserSseEvent(event, { outputMode })).filter((event) => event !== undefined);
37
+ const S = encoded.reduce((total, payload) => total + utf8Bytes(payload), 0);
38
+ assert.deepEqual(events, original, `${outputMode} production transformation must not mutate parsed/scoped events`);
39
+ return { R, S, encoded, semantic: semanticPayload(encoded) };
40
+ }
41
+
42
+ const normal = runProductionSeam("normal");
43
+ const compact = runProductionSeam("compact-v1");
44
+ const Wnormal = normal.R + 2 * normal.S;
45
+ const Wfast = compact.R + 2 * compact.S;
46
+ const ratio = Wnormal / Wfast;
47
+ const normalSemanticJson = JSON.stringify(normal.semantic);
48
+ const compactSemanticJson = JSON.stringify(compact.semantic);
49
+ const normalHash = createHash("sha256").update(normalSemanticJson).digest("hex");
50
+ const compactHash = createHash("sha256").update(compactSemanticJson).digest("hex");
51
+
52
+ assert.deepEqual(compact.semantic, normal.semantic, "normal and compact production outputs must retain ordered final semantics");
53
+ assert.equal(compactHash, normalHash, "canonical semantic payload hashes must match");
54
+ assert.ok(ratio >= 1.5, `expected Wnormal / Wfast >= 1.5, got ${ratio}`);
55
+ assert.equal(normal.semantic.text.length, fixedFastModeTraceMetadata().finalBytes, "the fixed trace should contain 512 × 32 bytes of assistant text");
56
+ assert.equal(normal.semantic.indices.length, fixedFastModeTraceMetadata().deltaCount);
57
+ assert.equal(browserOutputEvent(createFastModeOutputEvents()[2], { outputMode: "compact-v1" }).message, undefined, "the byte-work gate must call the production compact seam");
58
+
59
+ console.log(JSON.stringify({
60
+ fixture: fixedFastModeTraceMetadata(),
61
+ R: normal.R,
62
+ Snormal: normal.S,
63
+ Sfast: compact.S,
64
+ Wnormal,
65
+ Wfast,
66
+ ratio: Number(ratio.toFixed(6)),
67
+ semanticHash: normalHash,
68
+ }));
69
+ console.log("fast-mode-output-work.test.mjs passed");
@@ -0,0 +1,204 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
11
+ const serverScript = join(root, "bin", "pi-webui.mjs");
12
+ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
13
+
14
+ function nextPort() {
15
+ return 32000 + Math.floor(Math.random() * 20000);
16
+ }
17
+
18
+ async function request(port, pathname, { method = "GET", body, timeoutMs = 10_000 } = {}) {
19
+ const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
20
+ method,
21
+ headers: body === undefined ? undefined : { "content-type": "application/json" },
22
+ body: body === undefined ? undefined : JSON.stringify(body),
23
+ signal: AbortSignal.timeout(timeoutMs),
24
+ });
25
+ let payload;
26
+ try {
27
+ payload = await response.json();
28
+ } catch {
29
+ payload = undefined;
30
+ }
31
+ return { status: response.status, body: payload };
32
+ }
33
+
34
+ async function waitForHealth(port, child, output) {
35
+ for (let attempt = 0; attempt < 100; attempt += 1) {
36
+ if (child.exitCode !== null) break;
37
+ try {
38
+ const health = await request(port, "/api/health", { timeoutMs: 1_000 });
39
+ if (health.status === 200) return health;
40
+ } catch {
41
+ // Server startup is asynchronous.
42
+ }
43
+ await delay(50);
44
+ }
45
+ assert.fail(`server did not become healthy:\n${output()}`);
46
+ }
47
+
48
+ async function openSse(port, tabId, query = "") {
49
+ const controller = new AbortController();
50
+ const response = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}${query}`, { signal: controller.signal });
51
+ assert.equal(response.status, 200, "SSE connection should open");
52
+ const client = { controller, events: [], waiters: new Set(), readerError: null };
53
+ const reader = response.body.getReader();
54
+ const decoder = new TextDecoder();
55
+ void (async () => {
56
+ let buffer = "";
57
+ try {
58
+ while (true) {
59
+ const { done, value } = await reader.read();
60
+ if (done) break;
61
+ buffer += decoder.decode(value, { stream: true });
62
+ let boundary;
63
+ while ((boundary = buffer.indexOf("\n\n")) >= 0) {
64
+ const block = buffer.slice(0, boundary);
65
+ buffer = buffer.slice(boundary + 2);
66
+ const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
67
+ if (!data) continue;
68
+ const event = JSON.parse(data);
69
+ client.events.push(event);
70
+ for (const wake of client.waiters) wake();
71
+ client.waiters.clear();
72
+ }
73
+ }
74
+ } catch (error) {
75
+ if (!controller.signal.aborted) client.readerError = error;
76
+ for (const wake of client.waiters) wake();
77
+ client.waiters.clear();
78
+ }
79
+ })();
80
+ return client;
81
+ }
82
+
83
+ async function waitForEvent(client, predicate, { from = 0, timeoutMs = 8_000 } = {}) {
84
+ let index = from;
85
+ const deadline = Date.now() + timeoutMs;
86
+ while (Date.now() < deadline) {
87
+ while (index < client.events.length) {
88
+ const event = client.events[index++];
89
+ if (predicate(event)) return event;
90
+ }
91
+ if (client.readerError) throw client.readerError;
92
+ await new Promise((resolve, reject) => {
93
+ const timer = setTimeout(() => {
94
+ client.waiters.delete(wake);
95
+ reject(new Error("timed out waiting for SSE event"));
96
+ }, Math.max(1, deadline - Date.now()));
97
+ const wake = () => {
98
+ clearTimeout(timer);
99
+ client.waiters.delete(wake);
100
+ resolve();
101
+ };
102
+ client.waiters.add(wake);
103
+ });
104
+ }
105
+ throw new Error("timed out waiting for SSE event");
106
+ }
107
+
108
+ async function stopServer(server) {
109
+ for (const client of server.clients) client.controller.abort();
110
+ if (server.child?.exitCode === null && server.child?.signalCode === null) {
111
+ const exited = new Promise((resolve) => server.child.once("exit", resolve));
112
+ server.child.kill("SIGKILL");
113
+ await exited;
114
+ }
115
+ await rm(server.cwd, { recursive: true, force: true });
116
+ }
117
+
118
+ const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-fast-mode-harness-"));
119
+ const settingsFile = path.join(cwd, "settings.json");
120
+ const port = nextPort();
121
+ let child;
122
+ const server = { child: null, cwd, clients: [] };
123
+ let output = "";
124
+ try {
125
+ await writeFile(settingsFile, `${JSON.stringify({ outputModeDefault: "normal" })}\n`);
126
+ await chmod(fakePi, 0o755);
127
+ child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
128
+ stdio: ["ignore", "pipe", "pipe"],
129
+ env: { ...process.env, PI_CODING_AGENT_DIR: path.join(cwd, "agent"), PI_WEBUI_SETTINGS_FILE: settingsFile },
130
+ });
131
+ server.child = child;
132
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
133
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
134
+ const health = await waitForHealth(port, child, () => output);
135
+ assert.deepEqual(health.body.outputMode, { persistedDefault: "normal", effectiveDefault: "normal", source: "persisted", overridden: false });
136
+ const tabId = (await request(port, "/api/tabs")).body?.data?.tabs?.[0]?.id;
137
+ assert.ok(tabId, "server should create an RPC tab");
138
+
139
+ const auto = await openSse(port, tabId, "&outputMode=auto&outputModeProtocol=1");
140
+ const compact = await openSse(port, tabId, "&outputMode=compact-v1&outputModeProtocol=1");
141
+ const legacy = await openSse(port, tabId, "&outputMode=auto");
142
+ server.clients.push(auto, compact, legacy);
143
+ assert.deepEqual((await waitForEvent(auto, (event) => event.type === "webui_connected")).outputMode, {
144
+ protocolVersion: 1, requestedMode: "auto", activeMode: "normal", serverDefault: "normal", serverDefaultSource: "persisted",
145
+ });
146
+ assert.equal((await waitForEvent(compact, (event) => event.type === "webui_connected")).outputMode.activeMode, "compact-v1");
147
+ assert.deepEqual((await waitForEvent(legacy, (event) => event.type === "webui_connected")).outputMode, {
148
+ protocolVersion: 0, requestedMode: "normal", activeMode: "normal", serverDefault: "normal", serverDefaultSource: "persisted",
149
+ });
150
+
151
+ const autoStart = auto.events.length;
152
+ const compactStart = compact.events.length;
153
+ const prompt = await request(port, "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture fast mode flow" } });
154
+ assert.equal(prompt.status, 200, `fixture prompt should run: ${prompt.body?.error || ""}`);
155
+ const normalDelta = await waitForEvent(auto, (event) => event.type === "message_update", { from: autoStart });
156
+ const compactDelta = await waitForEvent(compact, (event) => event.type === "message_update", { from: compactStart });
157
+ assert.ok(normalDelta.message && normalDelta.assistantMessageEvent.partial, "normal clients retain accumulated message snapshots");
158
+ assert.equal(compactDelta.message, undefined, "compact clients omit duplicate accumulated message snapshots");
159
+ assert.equal(compactDelta.assistantMessageEvent.partial, undefined, "compact clients omit duplicate partial snapshots");
160
+ await waitForEvent(auto, (event) => event.type === "tool_execution_update", { from: autoStart });
161
+ await waitForEvent(compact, (event) => event.type === "tool_execution_end", { from: compactStart });
162
+ await waitForEvent(compact, (event) => event.type === "agent_end", { from: compactStart });
163
+ assert.equal(compact.events.slice(compactStart).some((event) => event.type === "tool_execution_update"), false, "only compact intermediate tool updates are omitted");
164
+ assert.ok(compact.events.slice(compactStart).some((event) => event.type === "pi_stderr"), "diagnostics must pass through compact routing");
165
+ assert.ok(compact.events.slice(compactStart).some((event) => event.type === "extension_ui_request" && event.method === "confirm"), "extension dialogs must pass through compact routing");
166
+
167
+ const switchToCompactAt = auto.events.length;
168
+ const outputPut = await request(port, "/api/webui-output-mode", { method: "PUT", body: { outputModeDefault: "compact-v1" } });
169
+ assert.equal(outputPut.status, 200);
170
+ assert.deepEqual(outputPut.body.data, { persistedDefault: "compact-v1", effectiveDefault: "compact-v1", source: "persisted", overridden: false });
171
+ assert.equal((await waitForEvent(auto, (event) => event.type === "webui_output_mode", { from: switchToCompactAt })).activeMode, "compact-v1", "idle auto clients should switch immediately");
172
+ assert.equal(compact.events.slice(compactStart).some((event) => event.type === "webui_output_mode"), false, "explicit client choices never follow the server default");
173
+
174
+ const switchToNormalAt = auto.events.length;
175
+ await request(port, "/api/webui-output-mode", { method: "PUT", body: { outputModeDefault: "normal" } });
176
+ await waitForEvent(auto, (event) => event.type === "webui_output_mode" && event.activeMode === "normal", { from: switchToNormalAt });
177
+ const barrierStart = auto.events.length;
178
+ assert.equal((await request(port, "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture fast mode barrier" } })).status, 200);
179
+ await waitForEvent(auto, (event) => event.type === "message_update", { from: barrierStart });
180
+ assert.equal((await request(port, "/api/webui-output-mode", { method: "PUT", body: { outputModeDefault: "compact-v1" } })).status, 200);
181
+ const messageEnd = await waitForEvent(auto, (event) => event.type === "message_end", { from: barrierStart });
182
+ assert.ok(messageEnd.message, "the current semantic unit must retain its old normal representation");
183
+ const control = await waitForEvent(auto, (event) => event.type === "webui_output_mode" && event.activeMode === "compact-v1", { from: barrierStart });
184
+ assert.ok(auto.events.indexOf(messageEnd) < auto.events.indexOf(control), "control must follow the semantic barrier");
185
+ const afterBarrier = auto.events.length;
186
+ assert.equal((await request(port, "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture fast mode flow" } })).status, 200);
187
+ assert.equal((await waitForEvent(auto, (event) => event.type === "message_update", { from: afterBarrier })).message, undefined, "events after the control use compact representation");
188
+
189
+ const historyStart = auto.events.length;
190
+ assert.equal((await request(port, "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture fast mode history" } })).status, 200);
191
+ await waitForEvent(auto, (event) => event.type === "agent_end", { from: historyStart });
192
+ const detailed = await request(port, "/api/webui-status?detailed=1&events=200");
193
+ const summary = detailed.body?.data?.events?.findLast((event) => event.type === "message_update" && event.deltaCount === 512);
194
+ assert.deepEqual({ deltaCount: summary?.deltaCount, deltaChars: summary?.deltaChars, deltaUtf8Bytes: summary?.deltaUtf8Bytes }, { deltaCount: 512, deltaChars: 2048, deltaUtf8Bytes: 2048 }, "debug history should coalesce all canonical deltas without retaining content");
195
+ assert.equal(Object.hasOwn(summary || {}, "message"), false);
196
+ assert.equal(Object.hasOwn(summary || {}, "partial"), false);
197
+
198
+ const invalid = await request(port, "/api/webui-output-mode", { method: "PUT", body: { outputModeDefault: "fast" } });
199
+ assert.equal(invalid.status, 400, "configuration API should reject invalid persisted mode values");
200
+ } finally {
201
+ await stopServer(server);
202
+ }
203
+
204
+ console.log("fast-mode-sse-harness.test.mjs passed");