@firstpick/pi-package-webui 0.10.5 → 0.10.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 (47) hide show
  1. package/DEVELOPMENT.md +9 -1
  2. package/README.md +2 -0
  3. package/TECHNICAL.md +3 -1
  4. package/bin/pi-webui.mjs +1 -1
  5. package/lib/thinking-stream-recovery.mjs +29 -142
  6. package/package.json +2 -2
  7. package/public/app.js +44 -79
  8. package/public/fast-output-live.mjs +8 -6
  9. package/public/index.html +2 -2
  10. package/public/service-worker.js +1 -1
  11. package/public/stream-output-controller.mjs +59 -12
  12. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  13. package/tests/codex-fast-mode-static.test.mjs +2 -2
  14. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  15. package/tests/control-visibility-static.test.mjs +3 -3
  16. package/tests/controls-layout-static.test.mjs +3 -3
  17. package/tests/events-tree-context-menu-static.test.mjs +3 -3
  18. package/tests/fast-mode-client-static.test.mjs +2 -2
  19. package/tests/fast-output-live.test.mjs +9 -0
  20. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  21. package/tests/file-viewer-image-static.test.mjs +3 -3
  22. package/tests/fixtures/fake-pi.mjs +2 -2
  23. package/tests/guided-git-activation-static.test.mjs +3 -3
  24. package/tests/guided-git-fallback-ui-static.test.mjs +2 -2
  25. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  26. package/tests/intercom-main-transcript-suppression-static.test.mjs +5 -6
  27. package/tests/main-output-loading-static.test.mjs +3 -3
  28. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  29. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  30. package/tests/mobile-foundation-static.test.mjs +3 -3
  31. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  32. package/tests/mobile-static.test.mjs +3 -3
  33. package/tests/open-issue-wizard-static.test.mjs +1 -1
  34. package/tests/optional-feature-prompt-impact-static.test.mjs +3 -3
  35. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  36. package/tests/prompt-input-vertical-scroll-static.test.mjs +3 -3
  37. package/tests/questionnaire-dialog.test.mjs +3 -3
  38. package/tests/session-sampling-ui-static.test.mjs +3 -3
  39. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  40. package/tests/stream-output-controller.test.mjs +4 -2
  41. package/tests/streaming-ui-coupling.test.mjs +2 -2
  42. package/tests/subagent-observability-static.test.mjs +2 -2
  43. package/tests/syntax-highlighting-static.test.mjs +3 -3
  44. package/tests/theme-customizer-static.test.mjs +1 -1
  45. package/tests/thinking-stream-recovery.test.mjs +58 -75
  46. package/tests/tool-call-stream.test.mjs +152 -0
  47. package/tests/windows-drive-cwd-picker-static.test.mjs +3 -3
package/DEVELOPMENT.md CHANGED
@@ -112,6 +112,14 @@ node tests/syntax-highlighting-static.test.mjs
112
112
 
113
113
  `tests/syntax-highlight.test.mjs` covers all 23 profiles and 58 aliases with exact round-trip assertions, representative token classes, prototype-pollution-style alias names, malicious-looking markup source, non-string input, and exact/over-limit character and line boundaries. `tests/syntax-highlighting-static.test.mjs` covers renderer wiring, the absence of HTML sinks, theme-token mapping against `THEME_TOKEN_GROUPS`, CSS fallbacks, app-shell closure, asset/cache revision coherence, and documentation coverage. When changing browser assets, advance `styles.css?v=`, `app.js?v=`, and `CACHE_NAME` together; several static tests assert those exact values.
114
114
 
115
+ ## RPC delta and final-message contracts
116
+
117
+ `createToolCallStreamTracker` in `public/stream-output-controller.mjs` tracks tool identities and argument previews by message-local `contentIndex`. It accepts current `toolcall_start` IDs/names and legacy indexed partial snapshots, and retains identity across bare argument deltas. Unidentified calls stay hidden until metadata arrives, normally in `toolcall_end` on Pi 0.84. Intercom calls remain hidden and their argument text is not retained. Each message holds at most 128 calls with at most 262,144 UTF-16 code units per argument preview; excess live data waits for the completed transcript. Message boundaries and browser stream resets clear this state independently of transient card removal.
118
+
119
+ `lib/thinking-stream-recovery.mjs` only fills missing `thinking_end` content from active deltas. Explicit block snapshots, including empty and shortened text, replace the draft. `message_end.message` passes through unchanged, and fetched history bypasses streaming recovery. The server retains no completed-thinking cache. Normal and compact browser renderers clear an existing thinking surface on an explicit empty block correction.
120
+
121
+ Focused checks are `node --test tests/tool-call-stream.test.mjs tests/thinking-stream-recovery.test.mjs tests/fast-output-live.test.mjs` and the Chromium Intercom conversation-viewer test. The latter emits metadata only on the tool start, then bare argument deltas, and checks that no Intercom content flashes in the main transcript.
122
+
115
123
  ## Streaming performance diagnostics and workloads
116
124
 
117
125
  The bounded frame queue in `public/stream-output-controller.mjs` emits timing fields only when an `onDiagnostic` hook is installed. Receipt timestamps survive adjacent-delta merges, and each `batch` record includes the oldest source event's `maxAgeMs` plus synchronous sink/follow work as `drainMs`. The controller accepts injectable frame, pressure-task, and clock hooks for deterministic tests; when diagnostics are disabled, it performs no clock reads. Supported message-update envelopes are measured by a JSON-equivalent UTF-16 walker, and adjacent delta merges add only escaped payload bytes while adopting the latest envelope. Unknown structured values retain a conservative one-time serialization fallback.
@@ -162,7 +170,7 @@ The separate `WS3 paced cadence and slow-renderer queue pressure remain bounded`
162
170
 
163
171
  `GET /api/intercom/conversations?tab=<tab-id>` projects bounded summaries from `SessionManager.getBranch()` for the selected server-owned session. Adding `conversation=<opaque-id>` returns one sanitized detail. Browser values never select a session path. The pure projector in `lib/intercom-conversations.mjs` accepts only structured generic Intercom records and matched native supervisor request/reply records, deduplicates protocol identities, excludes synthetic relays and attachments, and applies conversation/message/text/response bounds before serialization.
164
172
 
165
- `lib/intercom-transcript-filter.mjs` is the separate normal-transcript boundary. After thinking recovery and before HTTP delta slicing, it removes structured `intercom_message` records, generic `intercom` tool-call parts, and results paired by explicit call ID or tool name. It copies only changed mixed assistant records and preserves unrelated meaningful content without mutating the RPC response. Live stream and execution guards in `public/app.js` prevent an Intercom card or event-log line from flashing before the filtered authoritative refresh; unrelated supervisor and tool activity keeps the existing path. The conversation endpoint still reads raw active-branch records independently.
173
+ `lib/intercom-transcript-filter.mjs` is the separate normal-transcript boundary. Before HTTP delta slicing, it removes structured `intercom_message` records, generic `intercom` tool-call parts, and results paired by explicit call ID or tool name. It copies only changed mixed assistant records and preserves unrelated meaningful content without mutating the RPC response. Live stream and execution guards in `public/app.js` prevent an Intercom card or event-log line from flashing before the filtered authoritative refresh; unrelated supervisor and tool activity keeps the existing path. The conversation endpoint still reads raw active-branch records independently.
166
174
 
167
175
  `public/app.js` keeps only in-memory per-tab summaries. `refreshIntercomConversationSummaries` uses tab-generation and request-serial guards; `refreshIntercomConversationDetail` adds a separate serial plus a five-second open-dialog refresh. Switching tabs or closing the native dialog invalidates pending detail responses and cancels its timer. The renderer rebuilds message bubbles only from normalized `direction`, participant name/ID, text, and timestamp fields, assigning text with safe DOM APIs. It never renders server records wholesale. The footer tag group uses a reversed inline strip capped at 50 percent of the desktop prompt row, so the newest conversation starts at the right edge and older tags extend toward the middle. Direct tags are capped at 13rem. A `ResizeObserver` measures complete tag widths and reserves space for `+X`; tags that do not fit move into a bounded popup above the composer. Narrow layouts give the strip the full row and keep 44-pixel targets in the popup. Escape, outside clicks, and focus changes close the popup. Each reused direct or popup button stores a compact label/count signature, so unchanged tags retain their children instead of retriggering the polite live region.
168
176
 
package/README.md CHANGED
@@ -65,6 +65,8 @@ Check the server at any time with:
65
65
  5. Open the Control Deck for sessions, Git, app runners, themes, updates, and optional features. Under **Controls → Interface**, choose **Top bar** or **Sidebar** for terminal tabs, then choose **Right**, **Left**, or **Both** for the Control Deck. In **Sidebar**, **Both** is unavailable; choosing **Right** or **Left** swaps the Control Deck and terminal/tabs rails across the chat.
66
66
  6. On desktop, drag the workspace-facing edge of any visible Control Deck—or the terminal/tabs rail in **Sidebar**—to choose a comfortable width. In **Both**, resize the left and right Control Decks independently; widths return on your next visit.
67
67
 
68
+ The completed response replaces the live draft, including thinking the provider corrects or removes. On older Pi releases, tool arguments may appear only after the tool is identified, so Intercom content stays out of the main transcript.
69
+
68
70
  When session history is loading, a small status overlay floats directly above the Git footer without resizing the transcript. It names the current step, such as **Checking for new messages…**, **Loading conversation history…**, or **Preparing your conversation…**. Existing transcript content and controls remain available; no popup interrupts your work.
69
71
 
70
72
  Open **Events** to see bounded tool activity details such as status, duration, a safe target when available, and a shortened call ID. Use **Show** to isolate errors and failures, warnings, tool activity, or rows with **Tree…** available; **All events** restores the full browser-held history. Select a row to jump to its chat card. Right-click any row, or use its keyboard context-menu shortcut, to switch between **Detailed** and **Compact** display. Compact keeps the timestamp and summary while hiding secondary metadata; tool rows retain a colored lifecycle accent. Eligible tool rows also offer **Tree…** to confirm navigation to that exact point in the session; use `/tree` to navigate back. Repeated successful subagent Auto-Clear activity stays in one row whose finished-run count increases.
package/TECHNICAL.md CHANGED
@@ -141,6 +141,8 @@ Re-running the same `pi install npm:<package>` command is the supported update p
141
141
 
142
142
  Normal output shows the full live tool and response stream. Compact output keeps the current tool status and final answer while omitting most intermediate details from the live display.
143
143
 
144
+ Completed responses replace streamed drafts, including shortened or removed thinking. Refreshing history does not restore text removed by the provider. On older Pi releases, tool arguments stay hidden until Pi identifies the tool, which may happen only when argument generation completes. This keeps Intercom transport content out of the main transcript.
145
+
144
146
  Choose the mode under **Controls → Output processing** or **Settings → Browser workflow**, then select **Compact**. The stable setting and command-line identifier is `compact-v1`. The setting affects display only; it does not change Pi prompts, tools, models, saved transcript meaning, or inference.
145
147
 
146
148
  ## Code block syntax highlighting
@@ -345,7 +347,7 @@ The launcher refuses immediately while the originating tab is running, compactin
345
347
 
346
348
  Open **Common Pi Options → Guided Git Setup** or run `/git-workflow-setup` before using generated commit messages, branch names, or pull-request text. Choose the required primary model and its reasoning effort. You may also choose a different fallback model and a separate supported effort, or leave **No fallback** selected. The effort lists follow the capabilities reported for each selected model. Before enabling fallback, account for its privacy and cost impact: large commit diffs use multiple model requests, and a fallback attempt sends the complete staged evidence again to the configured fallback provider.
347
349
 
348
- A configured fallback is a strict one-retry policy: Guided Git lets the primary model finish its own retry lifecycle, then makes at most one fallback attempt after a final primary model-generation failure. The workflow output identifies the primary and configured fallback at startup and reports when generation continues with the fallback. For a commit diff at the extension’s 16 MiB ceiling, one attempt can use up to 35 requests; chunk-summary formatting does not trigger retries. Fallback can repeat the full attempt, for up to 70 requests across both providers. Fallback status is restored when you return to the tab or its live event connection reconnects. Generated commit, branch, or PR text is treated as ready only after the correlated attempt finishes successfully. Primary and fallback requests run independently of the parent Pi session, whose active model and reasoning effort remain unchanged throughout.
350
+ A configured fallback is a strict one-retry policy: Guided Git lets the primary model finish its own retry lifecycle, then makes at most one fallback attempt after a final primary model-generation failure. The workflow output identifies the primary and configured fallback at startup and reports when generation continues with the fallback. For a commit diff at the extension’s 16 MiB ceiling, one attempt can use up to 35 requests; chunk-summary formatting does not trigger retries. Fallback can repeat the full attempt, for up to 70 requests across both providers. If safe commit text lacks a summary and typed change list, the native extension can use its final-request allowance for one presentation rewrite with the same model. A failed optional rewrite keeps the original safe text for editing and does not trigger provider fallback. Fallback status is restored when you return to the tab or its live event connection reconnects. Generated commit, branch, or PR text is treated as ready only after the correlated attempt finishes successfully. Primary and fallback requests run independently of the parent Pi session, whose active model and reasoning effort remain unchanged throughout.
349
351
 
350
352
  Fallback applies only to model generation. Request validation failures, staged-content checks, busy-state rejection, user cancellation, Git command failures, and a stopped or failed Pi process do not trigger it. A dead Pi process cannot run the fallback; restart or reload the tab and start a new generation request after addressing the failure.
351
353
 
package/bin/pi-webui.mjs CHANGED
@@ -13201,7 +13201,7 @@ async function safeRpcResponse(tab, command, timeoutMs = REQUEST_TIMEOUT_MS) {
13201
13201
  if (command?.type === "get_messages" && Array.isArray(response?.data?.messages)) {
13202
13202
  response.data = {
13203
13203
  ...response.data,
13204
- messages: filterSessionSummaryTranscriptMessages(filterIntercomTranscriptMessages(tab.thinkingStreamRecovery.applyToMessages(response.data.messages))),
13204
+ messages: filterSessionSummaryTranscriptMessages(filterIntercomTranscriptMessages(response.data.messages)),
13205
13205
  };
13206
13206
  }
13207
13207
  return response;
@@ -1,156 +1,43 @@
1
- const COMPLETED_RECOVERY_LIMIT = 128;
1
+ import { reconcileTranscriptThinkingSnapshot as reconcileThinkingSnapshot } from "../public/stream-output-controller.mjs";
2
2
 
3
- function text(value) {
4
- return typeof value === "string" ? value : "";
5
- }
6
-
7
- function thinkingContentIndex(event = {}, update = event.assistantMessageEvent || {}) {
8
- const value = update.contentIndex ?? event.contentIndex;
9
- return Number.isInteger(value) && value >= 0 ? value : 0;
10
- }
11
-
12
- function thinkingPart(part) {
13
- return !!(part && typeof part === "object" && (part.type === "thinking" || typeof part.thinking === "string"));
14
- }
15
-
16
- function thinkingPartText(part) {
17
- if (!thinkingPart(part)) return "";
18
- return text(part.thinking) || text(part.content) || text(part.text);
19
- }
20
-
21
- function messageThinkingAt(message, contentIndex) {
22
- if (!Array.isArray(message?.content)) return "";
23
- return thinkingPartText(message.content[contentIndex]);
24
- }
25
-
26
- function messageThinkingTemplateAt(message, contentIndex) {
27
- if (!Array.isArray(message?.content)) return null;
28
- const part = message.content[contentIndex];
29
- return thinkingPart(part) ? part : null;
30
- }
31
-
32
- /**
33
- * Prefer the longer value only when the two snapshots are prefix-compatible.
34
- * Divergent authoritative content wins so provider corrections/redactions are
35
- * never silently overwritten by an earlier stream accumulator.
36
- */
37
- export function reconcileThinkingSnapshot(accumulated, snapshot) {
38
- const previous = text(accumulated);
39
- const next = text(snapshot);
40
- if (!previous) return next;
41
- if (!next) return previous;
42
- if (next.startsWith(previous)) return next;
43
- if (previous.startsWith(next)) return previous;
44
- return next;
45
- }
46
-
47
- function replaceThinkingAt(message, contentIndex, recovered, template = null) {
48
- if (!message || message.role !== "assistant" || !Array.isArray(message.content) || !recovered) return message;
49
- const current = message.content[contentIndex];
50
- let replacement = null;
51
- if (thinkingPart(current)) {
52
- replacement = { ...current, type: current.type || "thinking", thinking: recovered };
53
- } else if (thinkingPart(template) && contentIndex <= message.content.length) {
54
- replacement = { ...template, type: template.type || "thinking", thinking: recovered };
55
- }
56
- if (!replacement) return message;
57
- const content = [...message.content];
58
- if (contentIndex < content.length) content[contentIndex] = replacement;
59
- else content.push(replacement);
60
- return { ...message, content };
61
- }
3
+ export { reconcileThinkingSnapshot };
62
4
 
63
- function recoveryKey(timestamp, contentIndex) {
64
- if (timestamp === undefined || timestamp === null || timestamp === "") return "";
65
- return `${String(timestamp)}|${contentIndex}`;
5
+ function thinkingText(message, contentIndex) {
6
+ const part = message?.content?.[contentIndex];
7
+ if (part?.type !== "thinking") return undefined;
8
+ if (typeof part.thinking === "string") return part.thinking;
9
+ if (typeof part.content === "string") return part.content;
10
+ return typeof part.text === "string" ? part.text : undefined;
66
11
  }
67
12
 
13
+ /** Fill missing thinking-end text during streaming, never rewrite finalized messages. */
68
14
  export class ThinkingStreamRecovery {
69
15
  #active = new Map();
70
- #completed = new Map();
71
16
 
72
- ingest(rawEvent) {
73
- if (!rawEvent || typeof rawEvent !== "object") return rawEvent;
74
- const event = rawEvent;
75
- if (event.type === "message_start" && event.message?.role === "assistant") {
17
+ ingest(event) {
18
+ if (!event || typeof event !== "object") return event;
19
+ if ((event.type === "message_start" || event.type === "message_end") && event.message?.role === "assistant") {
76
20
  this.#active.clear();
77
21
  return event;
78
22
  }
79
- if (event.type === "message_update") return this.#ingestUpdate(event);
80
- if (event.type === "message_end" && event.message?.role === "assistant") return this.#ingestEnd(event);
81
- return event;
82
- }
83
-
84
- applyToMessages(messages) {
85
- if (!Array.isArray(messages) || this.#completed.size === 0) return messages;
86
- let changed = false;
87
- const recoveredMessages = messages.map((message) => {
88
- if (message?.role !== "assistant") return message;
89
- let recoveredMessage = message;
90
- for (const record of this.#completed.values()) {
91
- if (record.timestamp !== String(message.timestamp ?? "")) continue;
92
- const authoritative = messageThinkingAt(recoveredMessage, record.contentIndex);
93
- const recovered = reconcileThinkingSnapshot(record.text, authoritative);
94
- if (recovered !== authoritative) {
95
- recoveredMessage = replaceThinkingAt(recoveredMessage, record.contentIndex, recovered, record.template);
96
- }
97
- }
98
- if (recoveredMessage !== message) changed = true;
99
- return recoveredMessage;
100
- });
101
- return changed ? recoveredMessages : messages;
102
- }
103
-
104
- #ingestUpdate(event) {
23
+ if (event.type !== "message_update") return event;
105
24
  const update = event.assistantMessageEvent;
106
- if (!update || typeof update !== "object" || !["thinking_start", "thinking_delta", "thinking_end"].includes(update.type)) return event;
107
- const contentIndex = thinkingContentIndex(event, update);
108
- const existing = this.#active.get(contentIndex) || { text: "", template: null };
109
- const partialText = messageThinkingAt(update.partial, contentIndex);
110
- const direct = text(update.content) || text(update.thinking);
111
- const delta = text(update.delta);
112
- const template = messageThinkingTemplateAt(update.partial, contentIndex) || existing.template;
113
- let recovered = existing.text;
114
-
115
- if (update.type === "thinking_delta") {
116
- const appended = recovered + delta;
117
- recovered = partialText ? reconcileThinkingSnapshot(appended, partialText) : appended;
118
- } else {
119
- recovered = reconcileThinkingSnapshot(recovered, direct || partialText || delta);
120
- }
121
- this.#active.set(contentIndex, { text: recovered, template });
122
-
123
- if (update.type !== "thinking_end" || !recovered) return event;
124
- const authoritative = direct || partialText || delta;
125
- if (recovered === authoritative && (!delta || delta === recovered)) return event;
126
- const patchedUpdate = { ...update, content: recovered };
127
- if (Object.prototype.hasOwnProperty.call(patchedUpdate, "delta")) patchedUpdate.delta = recovered;
128
- if (update.partial) patchedUpdate.partial = replaceThinkingAt(update.partial, contentIndex, recovered, template);
129
- return { ...event, assistantMessageEvent: patchedUpdate };
130
- }
131
-
132
- #ingestEnd(event) {
133
- let message = event.message;
134
- for (const [contentIndex, record] of this.#active) {
135
- if (!record.text) continue;
136
- const authoritative = messageThinkingAt(message, contentIndex);
137
- const recovered = reconcileThinkingSnapshot(record.text, authoritative);
138
- if (recovered !== authoritative) message = replaceThinkingAt(message, contentIndex, recovered, record.template);
139
- const key = recoveryKey(message.timestamp, contentIndex);
140
- if (key) this.#rememberCompleted(key, {
141
- timestamp: String(message.timestamp),
142
- contentIndex,
143
- text: recovered,
144
- template: record.template,
145
- });
25
+ if (!["thinking_start", "thinking_delta", "thinking_end"].includes(update?.type)) return event;
26
+ const contentIndex = update.contentIndex ?? event.contentIndex ?? 0;
27
+ if (!Number.isSafeInteger(contentIndex) || contentIndex < 0) return event;
28
+ const previous = update.type === "thinking_start" ? "" : this.#active.get(contentIndex) || "";
29
+ const partial = thinkingText(update.partial, contentIndex);
30
+ const direct = typeof update.content === "string" ? update.content
31
+ : typeof update.thinking === "string" ? update.thinking : undefined;
32
+ const delta = typeof update.delta === "string" ? update.delta : "";
33
+ const accumulated = update.type === "thinking_delta" ? previous + delta : previous;
34
+ const next = reconcileThinkingSnapshot(accumulated, direct ?? partial);
35
+ if (update.type !== "thinking_end") {
36
+ this.#active.set(contentIndex, next);
37
+ return event;
146
38
  }
147
- this.#active.clear();
148
- return message === event.message ? event : { ...event, message };
149
- }
150
-
151
- #rememberCompleted(key, record) {
152
- this.#completed.delete(key);
153
- this.#completed.set(key, record);
154
- while (this.#completed.size > COMPLETED_RECOVERY_LIMIT) this.#completed.delete(this.#completed.keys().next().value);
39
+ this.#active.delete(contentIndex);
40
+ if (direct !== undefined) return event;
41
+ return { ...event, assistantMessageEvent: { ...update, content: next } };
155
42
  }
156
43
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstpick/pi-package-webui",
3
- "version": "0.10.5",
3
+ "version": "0.10.7",
4
4
  "description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/Firstp1ck/pi-coding-agent-forge/tree/main/pi-package-webui#readme",
@@ -36,7 +36,7 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@earendil-works/pi-ai": "^0.83.0",
39
- "@earendil-works/pi-coding-agent": "^0.85.0",
39
+ "@earendil-works/pi-coding-agent": "^0.87.0",
40
40
  "@earendil-works/pi-tui": "^0.83.0",
41
41
  "@firstpick/pi-utils": "^0.2.5",
42
42
  "mermaid": "^11.15.0",
package/public/app.js CHANGED
@@ -12,7 +12,7 @@ import { createTranscriptRenderer, groupConsecutiveThinkingItems, groupConsecuti
12
12
  import { createStreamDerivedOutputState } from "./stream-derived-output.mjs";
13
13
  import { advanceStreamingMarkdownTail } from "./stream-markdown-tail.mjs";
14
14
  import { createLatestWinsRenderScheduler } from "./stream-render-scheduler.mjs";
15
- import { classifyTranscriptStreamEvent, createStreamOutputController, reconcileTranscriptThinkingSnapshot } from "./stream-output-controller.mjs";
15
+ import { classifyTranscriptStreamEvent, createStreamOutputController, createToolCallStreamTracker, reconcileTranscriptThinkingSnapshot } from "./stream-output-controller.mjs";
16
16
  import { installMiddleButtonDragScroll } from "./middle-button-drag-scroll.mjs";
17
17
  import { tokenizeCode } from "./syntax-highlight.mjs";
18
18
  import { PI_THEME_EXPORT_FIELDS, THEME_TOKEN_GROUPS, canonicalizeTheme, serializeTheme, themeColorToRgb, validateTheme } from "./theme-contract.mjs";
@@ -697,6 +697,7 @@ let streamToolCallRawArguments = "";
697
697
  let streamToolCallName = "";
698
698
  let streamToolCallId = "";
699
699
  let streamToolCallContentIndex = null;
700
+ const streamToolCalls = createToolCallStreamTracker({ isHiddenTool: isIntercomTransportToolName });
700
701
  let streamToolCallComplete = false;
701
702
  let streamThinkingBubble = null;
702
703
  let streamThinking = null;
@@ -942,7 +943,7 @@ const assistantStreamRenderScheduler = createLatestWinsRenderScheduler({
942
943
  });
943
944
  const thinkingStreamRenderScheduler = createLatestWinsRenderScheduler({
944
945
  render: (options = {}) => {
945
- if (streamThinkingRawText) setStreamingThinkingText(streamThinkingRawText, options);
946
+ setStreamingThinkingText(streamThinkingRawText, options);
946
947
  if (options.complete) streamThinkingBubble?.classList.add("complete");
947
948
  completeNormalStreamScheduledRender();
948
949
  },
@@ -984,13 +985,18 @@ const streamOutputController = createStreamOutputController({
984
985
  applyTextUpdate: (event) => handleMessageUpdate(event),
985
986
  applyThinkingUpdate: (event) => handleMessageUpdate(event),
986
987
  applyToolCallUpdate: (event) => {
987
- if (isIntercomToolCallUpdate(event)) {
988
- streamToolCallSeen = true;
989
- suppressStreamingAssistantTextBeforeToolCall();
988
+ const call = streamToolCalls.ingest(event);
989
+ streamToolCallSeen = true;
990
+ suppressStreamingAssistantTextBeforeToolCall();
991
+ if (!call?.visible) {
990
992
  resetStreamingToolCallState({ remove: true });
991
993
  return;
992
994
  }
993
- handleMessageUpdate(event);
995
+ if (compactOutputActive()) {
996
+ handleCompactMessageUpdate(event);
997
+ return;
998
+ }
999
+ updateStreamingToolCallFromState(call);
994
1000
  },
995
1001
  applyToolExecutionUpdate: (event) => {
996
1002
  if (!compactOutputActive() && !isIntercomTransportToolName(event?.toolName)) applyTranscriptToolExecutionUpdate(event);
@@ -37305,13 +37311,6 @@ function isIntercomTransportToolName(value) {
37305
37311
  return String(value || "").trim().toLowerCase() === "intercom";
37306
37312
  }
37307
37313
 
37308
- function isIntercomToolCallUpdate(event) {
37309
- const update = event?.assistantMessageEvent || {};
37310
- const part = assistantToolCallPartFromUpdate(event, update);
37311
- const rawName = update.name || update.toolName || update.toolCall?.name || (part ? assistantToolCallName(part) : "");
37312
- return isIntercomTransportToolName(rawName);
37313
- }
37314
-
37315
37314
  function assistantToolCallArguments(part) {
37316
37315
  return part?.arguments || part?.args || part?.input || part?.toolCall?.arguments || {};
37317
37316
  }
@@ -45537,9 +45536,17 @@ function flushCompactLiveOutput() {
45537
45536
  });
45538
45537
  restoreChatTextSelection(selectionSnapshot);
45539
45538
  }
45539
+ } else {
45540
+ removeCompactLiveBubble(compactTextBubble);
45541
+ compactTextBubble = null;
45542
+ compactTextNode = null;
45540
45543
  }
45541
45544
  if (compactLiveState.thinking && ensureCompactThinkingBubble()) {
45542
45545
  if (compactThinkingNode?._rawThinkingText !== compactLiveState.thinking) renderThinkingMarkdown(compactThinkingNode, compactLiveState.thinking);
45546
+ } else if (!compactLiveState.thinking) {
45547
+ removeCompactLiveBubble(compactThinkingBubble);
45548
+ compactThinkingBubble = null;
45549
+ compactThinkingNode = null;
45543
45550
  }
45544
45551
  scheduleChatFollowScroll();
45545
45552
  }
@@ -45915,6 +45922,7 @@ function resetStreamBubble({ preserveCompact = false } = {}) {
45915
45922
  resetStreamDerivedOutputState("reset");
45916
45923
  streamBubbleVisibleSince = 0;
45917
45924
  streamToolCallSeen = false;
45925
+ streamToolCalls.reset();
45918
45926
  resetStreamingToolCallState({ remove: true });
45919
45927
  streamThinkingBubble = null;
45920
45928
  streamThinking = null;
@@ -45992,54 +46000,18 @@ function assistantStreamingMessage(event) {
45992
46000
  return partial?.role === "assistant" ? partial : null;
45993
46001
  }
45994
46002
 
45995
- function assistantToolCallPartFromUpdate(event, update = event?.assistantMessageEvent || {}) {
45996
- if (isAssistantToolCallPart(update.toolCall)) return update.toolCall;
45997
- const message = assistantStreamingMessage(event);
45998
- const content = message?.content;
45999
- if (!Array.isArray(content)) return null;
46000
- const contentIndex = Number(update.contentIndex);
46001
- if (Number.isInteger(contentIndex) && isAssistantToolCallPart(content[contentIndex])) return content[contentIndex];
46002
- for (let index = content.length - 1; index >= 0; index -= 1) {
46003
- if (isAssistantToolCallPart(content[index])) return content[index];
46004
- }
46005
- return null;
46006
- }
46007
-
46008
- function streamToolCallNameFromUpdate(update, part) {
46009
- const rawName = update.name || update.toolName || update.toolCall?.name || assistantToolCallName(part);
46010
- const name = runIndicatorToolName(rawName);
46011
- return name === "unknown" ? "tool" : name;
46012
- }
46013
-
46014
- function streamingToolCallContentIndexFromUpdate(update) {
46015
- const contentIndex = Number(update.contentIndex);
46016
- return Number.isInteger(contentIndex) ? contentIndex : null;
46017
- }
46018
-
46019
- function updateStreamingToolCallFromEvent(event, { reset = false, appendDelta = false, complete = false, scroll = false } = {}) {
46020
- const update = event.assistantMessageEvent || {};
46021
- const part = assistantToolCallPartFromUpdate(event, update);
46022
- const contentIndex = streamingToolCallContentIndexFromUpdate(update);
46023
- if (reset || (contentIndex !== null && streamToolCallContentIndex !== null && contentIndex !== streamToolCallContentIndex)) {
46003
+ function updateStreamingToolCallFromState(call) {
46004
+ if (!call?.visible) return;
46005
+ if (call.contentIndex !== streamToolCallContentIndex || call.id !== streamToolCallId) {
46024
46006
  resetStreamingToolCallState({ remove: true });
46025
46007
  }
46026
- streamToolCallContentIndex = contentIndex ?? streamToolCallContentIndex;
46027
- streamToolCallName = streamToolCallNameFromUpdate(update, part) || streamToolCallName || "tool";
46028
- streamToolCallId = assistantToolCallId(update.toolCall || part) || streamToolCallId;
46029
- streamToolCallComplete = !!complete;
46030
-
46031
- const partArgumentText = toolCallArgumentsText(assistantToolCallArguments(update.toolCall || part), { includeEmptyObject: false });
46032
- if (reset) streamToolCallRawArguments = partArgumentText || "";
46033
- if (appendDelta && update.delta !== undefined && update.delta !== null) streamToolCallRawArguments += typeof update.delta === "string" ? update.delta : String(update.delta);
46034
- if (!streamToolCallRawArguments && partArgumentText) streamToolCallRawArguments = partArgumentText;
46035
- if (complete) {
46036
- const finalArgumentText = toolCallArgumentsText(assistantToolCallArguments(update.toolCall || part), { includeEmptyObject: true });
46037
- if (finalArgumentText && (finalArgumentText !== "{}" || !streamToolCallRawArguments)) streamToolCallRawArguments = finalArgumentText;
46038
- if (!streamToolCallRawArguments) streamToolCallRawArguments = "{}";
46039
- }
46040
-
46041
- renderStreamingToolCallCard({ scroll });
46042
- return streamToolCallName || "tool";
46008
+ streamToolCallContentIndex = call.contentIndex;
46009
+ streamToolCallName = call.name;
46010
+ streamToolCallId = call.id;
46011
+ streamToolCallComplete = call.complete;
46012
+ streamToolCallRawArguments = call.rawArguments;
46013
+ if (call.truncated) streamToolCallRawArguments += "\n[Live arguments truncated; see the completed tool card.]";
46014
+ renderStreamingToolCallCard();
46043
46015
  }
46044
46016
 
46045
46017
  function assistantTextFromMessage(message, { streaming = false } = {}) {
@@ -46080,7 +46052,13 @@ function assistantThinkingTextFromMessage(message, { streaming = false } = {}) {
46080
46052
 
46081
46053
  function setStreamingThinkingText(text, { complete = false } = {}) {
46082
46054
  const thinking = visibleThinkingText(text);
46083
- if (!thinkingOutputVisible || !thinking) return false;
46055
+ if (!thinkingOutputVisible) return false;
46056
+ if (!thinking) {
46057
+ removeLiveTranscriptBubble(streamThinkingBubble, "thinking-correction");
46058
+ streamThinkingBubble = null;
46059
+ streamThinking = null;
46060
+ return true;
46061
+ }
46084
46062
  showStreamingThinking("");
46085
46063
  if (streamThinking) renderThinkingMarkdown(streamThinking, thinking, { complete });
46086
46064
  return true;
@@ -46120,12 +46098,10 @@ function syncStreamingThinkingFromUpdate(event, update, { placeholder = "", rend
46120
46098
  return render ? setStreamingThinkingText(streamThinkingRawText || placeholder) : true;
46121
46099
  }
46122
46100
  if (update.type === "thinking_end") {
46123
- if (delta) setStreamThinkingRawText(delta, { reconcile: true });
46124
- else {
46125
- const fallback = streamingThinkingTextFallback(event);
46126
- if (fallback !== null) setStreamThinkingRawText(fallback, { reconcile: true });
46127
- }
46128
- return render ? setStreamingThinkingText(streamThinkingRawText || placeholder, { complete: true }) : true;
46101
+ const snapshot = typeof update.content === "string" ? update.content
46102
+ : typeof update.thinking === "string" ? update.thinking : streamingThinkingTextFallback(event);
46103
+ if (snapshot !== null) setStreamThinkingRawText(snapshot, { reconcile: true });
46104
+ return render ? setStreamingThinkingText(streamThinkingRawText, { complete: true }) : true;
46129
46105
  }
46130
46106
  const fallback = streamingThinkingTextFallback(event);
46131
46107
  if (fallback === null) return false;
@@ -46152,7 +46128,7 @@ function handleMessageUpdate(event) {
46152
46128
  if (thinkingOutputVisible && streamThinkingRawText) thinkingStreamRenderScheduler.request({ complete: false });
46153
46129
  } else if (update.type === "thinking_end") {
46154
46130
  syncStreamingThinkingFromUpdate(event, update, { render: false });
46155
- if (thinkingOutputVisible && streamThinkingRawText) {
46131
+ if (thinkingOutputVisible) {
46156
46132
  thinkingStreamRenderScheduler.request({ complete: true });
46157
46133
  thinkingStreamRenderScheduler.flushNow("thinking_end");
46158
46134
  }
@@ -46161,18 +46137,6 @@ function handleMessageUpdate(event) {
46161
46137
  if (update.type === "text_end") fallbackStreamDerivedOutput("settlement:text_end");
46162
46138
  assistantStreamRenderScheduler.request({ complete: update.type === "text_end" });
46163
46139
  if (update.type === "text_end") assistantStreamRenderScheduler.flushNow("text_end");
46164
- } else if (update.type === "toolcall_start") {
46165
- streamToolCallSeen = true;
46166
- suppressStreamingAssistantTextBeforeToolCall();
46167
- updateStreamingToolCallFromEvent(event, { reset: true });
46168
- } else if (update.type === "toolcall_delta") {
46169
- streamToolCallSeen = true;
46170
- suppressStreamingAssistantTextBeforeToolCall();
46171
- updateStreamingToolCallFromEvent(event, { appendDelta: true });
46172
- } else if (update.type === "toolcall_end") {
46173
- streamToolCallSeen = true;
46174
- suppressStreamingAssistantTextBeforeToolCall();
46175
- updateStreamingToolCallFromEvent(event, { complete: true });
46176
46140
  } else if (update.type === "error") {
46177
46141
  streamProviderErrorText = assistantStreamErrorMessage(event, update);
46178
46142
  appendMessage({ role: "error", title: "assistant error", timestamp: Date.now(), content: streamProviderErrorText, level: "error" }, { streaming: true });
@@ -49271,6 +49235,7 @@ function handleEvent(event) {
49271
49235
  }
49272
49236
  break;
49273
49237
  case "message_end": {
49238
+ if (event.message?.role === "assistant") streamToolCalls.reset();
49274
49239
  if (compactOutputActive()) finishCompactLiveOutput(tabContext);
49275
49240
  streamMessageActive = false;
49276
49241
  if (event.message?.role === "assistant" && event.message.stopReason === "error") {
@@ -93,14 +93,16 @@ export function reduceFastOutputLiveEvent(state = createFastOutputLiveState(), e
93
93
  changed = true;
94
94
  kind = "toolcall";
95
95
  } else if (update.type === "text_end") {
96
- const finalText = text(update.content) || text(update.text) || delta;
97
- if (finalText) current.text = finalText;
98
- changed = Boolean(finalText);
96
+ const finalText = typeof update.content === "string" ? update.content
97
+ : typeof update.text === "string" ? update.text : typeof update.delta === "string" ? delta : current.text;
98
+ changed = current.text !== finalText;
99
+ current.text = finalText;
99
100
  kind = "text-end";
100
101
  } else if (update.type === "thinking_end") {
101
- const finalThinking = text(update.content) || text(update.thinking) || delta;
102
- if (finalThinking) current.thinking = finalThinking;
103
- changed = Boolean(finalThinking);
102
+ const finalThinking = typeof update.content === "string" ? update.content
103
+ : typeof update.thinking === "string" ? update.thinking : typeof update.delta === "string" ? delta : current.thinking;
104
+ changed = current.thinking !== finalThinking;
105
+ current.thinking = finalThinking;
104
106
  kind = "thinking-end";
105
107
  } else if (update.type === "toolcall_end" || update.type === "tool_call_end") {
106
108
  const argumentsText = toolCallArguments(update) || delta || current.toolCall.arguments;
package/public/index.html CHANGED
@@ -12,7 +12,7 @@
12
12
  <link rel="manifest" href="/manifest.webmanifest" />
13
13
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
14
14
  <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
15
- <link rel="stylesheet" href="/styles.css?v=153" />
15
+ <link rel="stylesheet" href="/styles.css?v=154" />
16
16
  <script>
17
17
  // Public-only issue-bot runtime configuration. Keep disabled unless the gateway,
18
18
  // Turnstile site key, exact CORS origin, and private-report destination are approved.
@@ -1895,7 +1895,7 @@
1895
1895
  </form>
1896
1896
  </dialog>
1897
1897
 
1898
- <script id="webuiBootLoader" data-app-src="/app.js?v=183">
1898
+ <script id="webuiBootLoader" data-app-src="/app.js?v=184">
1899
1899
  (() => {
1900
1900
  "use strict";
1901
1901
 
@@ -1,4 +1,4 @@
1
- const CACHE_NAME = "pi-webui-pwa-v154";
1
+ const CACHE_NAME = "pi-webui-pwa-v155";
2
2
  const APP_SHELL = [
3
3
  "/",
4
4
  "/index.html",
@@ -19,19 +19,66 @@ export const DEFAULT_STREAM_PENDING_BYTE_LIMIT = 256 * 1024;
19
19
 
20
20
  export const TRANSCRIPT_STREAM_MESSAGE_UPDATE_TYPES = Object.freeze(Object.keys(MESSAGE_UPDATE_KINDS));
21
21
 
22
- /**
23
- * Keep the longer value when a final snapshot is only a prefix of the text
24
- * already streamed. Divergent snapshots still win so provider corrections or
25
- * redactions remain authoritative.
26
- */
22
+ /** An explicit snapshot wins, including empty or shortened provider corrections. */
27
23
  export function reconcileTranscriptThinkingSnapshot(accumulated, snapshot) {
28
- const previous = typeof accumulated === "string" ? accumulated : "";
29
- const next = typeof snapshot === "string" ? snapshot : "";
30
- if (!previous) return next;
31
- if (!next) return previous;
32
- if (next.startsWith(previous)) return next;
33
- if (previous.startsWith(next)) return previous;
34
- return next;
24
+ return typeof snapshot === "string" ? snapshot : typeof accumulated === "string" ? accumulated : "";
25
+ }
26
+
27
+ /** Reconstruct message-scoped tool calls without depending on cumulative RPC snapshots. */
28
+ export function createToolCallStreamTracker({ isHiddenTool = () => false, maxCalls = 128, maxArgumentChars = 256 * 1024 } = {}) {
29
+ if (!Number.isSafeInteger(maxCalls) || maxCalls < 1 || !Number.isSafeInteger(maxArgumentChars) || maxArgumentChars < 1) {
30
+ throw new TypeError("Tool stream limits must be positive safe integers");
31
+ }
32
+ const calls = new Map();
33
+ const nonempty = (value) => typeof value === "string" ? value.trim() : "";
34
+ const argumentText = (value) => {
35
+ if (typeof value === "string") return value;
36
+ if (value === undefined) return undefined;
37
+ try { return JSON.stringify(value, null, 2); } catch { return undefined; }
38
+ };
39
+ return {
40
+ reset() { calls.clear(); },
41
+ ingest(event) {
42
+ const update = event?.assistantMessageEvent;
43
+ if (event?.type !== "message_update" || !["toolcall_start", "toolcall_delta", "toolcall_end"].includes(update?.type)) return null;
44
+ const contentIndex = update.contentIndex ?? event.contentIndex ?? 0;
45
+ if (!Number.isSafeInteger(contentIndex) || contentIndex < 0) return null;
46
+ const message = event.message?.role === "assistant" ? event.message : update.partial;
47
+ const candidate = update.toolCall ?? message?.content?.[contentIndex];
48
+ const part = candidate?.type === "toolCall" || candidate?.name ? candidate : null;
49
+ const name = nonempty(part?.name) || nonempty(update.toolName) || nonempty(update.name);
50
+ const id = nonempty(part?.id) || nonempty(update.id) || nonempty(update.toolCallId);
51
+ let call = calls.get(contentIndex);
52
+ if (!call || update.type === "toolcall_start" || (id && call.id && id !== call.id)) {
53
+ if (!call && calls.size >= maxCalls) return null;
54
+ call = { contentIndex, id: "", name: "", rawArguments: "", complete: false, truncated: false };
55
+ calls.set(contentIndex, call);
56
+ }
57
+ if (name) call.name = name;
58
+ if (id) call.id = id;
59
+ call.complete = update.type === "toolcall_end";
60
+ const visible = Boolean(call.name) && !isHiddenTool(call.name);
61
+ if (!visible) {
62
+ // Older RPC starts have no identity. Wait for a named snapshot or completed call.
63
+ call.rawArguments = "";
64
+ call.truncated = false;
65
+ } else {
66
+ const snapshot = argumentText(part?.arguments ?? update.arguments ?? update.args);
67
+ if (call.complete && snapshot !== undefined) {
68
+ call.rawArguments = snapshot.slice(0, maxArgumentChars);
69
+ call.truncated = snapshot.length > maxArgumentChars;
70
+ } else if (update.type === "toolcall_delta" && typeof update.delta === "string") {
71
+ const remaining = maxArgumentChars - call.rawArguments.length;
72
+ call.rawArguments += update.delta.slice(0, remaining);
73
+ call.truncated ||= update.delta.length > remaining;
74
+ } else if (snapshot !== undefined && snapshot !== "{}") {
75
+ call.rawArguments = snapshot.slice(0, maxArgumentChars);
76
+ call.truncated = snapshot.length > maxArgumentChars;
77
+ }
78
+ }
79
+ return { ...call, visible };
80
+ },
81
+ };
35
82
  }
36
83
 
37
84
  export function classifyTranscriptStreamEvent(event) {