pi-pretty-tui 0.1.3 → 0.1.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.
@@ -1,5 +1,9 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
1
  import {
2
+ AssistantMessageComponent,
3
+ CustomEditor,
4
+ InteractiveMode,
5
+ ToolExecutionComponent,
6
+ UserMessageComponent,
3
7
  createBashTool,
4
8
  createEditTool,
5
9
  createFindTool,
@@ -7,6 +11,8 @@ import {
7
11
  createLsTool,
8
12
  createReadTool,
9
13
  createWriteTool,
14
+ getAgentDir,
15
+ type ExtensionAPI,
10
16
  } from "@earendil-works/pi-coding-agent";
11
17
  import {
12
18
  type Component,
@@ -14,10 +20,389 @@ import {
14
20
  visibleWidth,
15
21
  wrapTextWithAnsi,
16
22
  } from "@earendil-works/pi-tui";
23
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
24
+ import { join } from "node:path";
17
25
 
18
- /** Polished tool calls and list rendering for Pi's TUI. */
26
+ type PrettyTuiMode = "full" | "compact" | "clean";
27
+ const CLEAN_TOOL_ACTIVITY_MIN_MS = 1000;
28
+ type PrettyTuiConfig = {
29
+ mode?: PrettyTuiMode;
30
+ /** Legacy location used by the first mode implementation. */
31
+ bash?: {
32
+ mode?: "full" | "compact";
33
+ };
34
+ };
35
+
36
+ const loadConfig = (path: string): PrettyTuiConfig => {
37
+ try {
38
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
39
+ return parsed && typeof parsed === "object" ? parsed : {};
40
+ } catch {
41
+ return {};
42
+ }
43
+ };
44
+
45
+ /** Polished user messages, tool calls, and list rendering for Pi's TUI. */
19
46
  export default function prettyTui(pi: ExtensionAPI) {
20
47
  const cwd = process.cwd();
48
+ const configPath = join(getAgentDir(), "pretty-tui.json");
49
+ let config = loadConfig(configPath);
50
+ const configuredMode = config.mode ?? config.bash?.mode;
51
+ let renderMode: PrettyTuiMode = configuredMode === "full" || configuredMode === "compact" || configuredMode === "clean"
52
+ ? configuredMode
53
+ : "clean";
54
+ let cleanToolsExpanded = false;
55
+ let changingAllToolsExpansion = false;
56
+ const cleanCompactToolCallIds = new Set<string>();
57
+ const cleanGroupToolCallIds = new Map<string, string[]>();
58
+ const cleanToolCallGroupOwners = new Map<string, string>();
59
+ const cleanToolComponents = new Map<string, any>();
60
+ const cleanToolThemes = new Map<string, any>();
61
+ const cleanToolNames = new Map<string, string>();
62
+ let renderCleanGroupSummary = (_lastToolCallId: string, _width: number): string[] => [];
63
+
64
+ const setCleanGroupMembers = (lastToolCallId: string, toolCallIds: string[]) => {
65
+ cleanGroupToolCallIds.set(lastToolCallId, toolCallIds);
66
+ for (const toolCallId of toolCallIds) cleanToolCallGroupOwners.set(toolCallId, lastToolCallId);
67
+ };
68
+
69
+ const isCleanGroupRevealed = (toolCallId: string): boolean => {
70
+ if (cleanCompactToolCallIds.has(toolCallId)) return true;
71
+ const groupOwner = cleanToolCallGroupOwners.get(toolCallId);
72
+ const groupToolCallIds = groupOwner ? cleanGroupToolCallIds.get(groupOwner) : undefined;
73
+ return groupToolCallIds?.some((id) => cleanCompactToolCallIds.has(id)) ?? false;
74
+ };
75
+
76
+ const cleanThemeForToolCall = (toolCallId: string): any => {
77
+ const directTheme = cleanToolThemes.get(toolCallId);
78
+ if (directTheme) return directTheme;
79
+ const groupOwner = cleanToolCallGroupOwners.get(toolCallId);
80
+ const groupToolCallIds = groupOwner ? cleanGroupToolCallIds.get(groupOwner) : undefined;
81
+ return groupToolCallIds
82
+ ?.map((id) => cleanToolThemes.get(id))
83
+ .find(Boolean);
84
+ };
85
+
86
+ const saveRenderMode = (mode: PrettyTuiMode) => {
87
+ config = { ...config, mode };
88
+ mkdirSync(getAgentDir(), { recursive: true });
89
+ writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
90
+ };
91
+
92
+ pi.registerCommand("pretty-tui", {
93
+ description: "Configure pi-pretty-tui rendering mode",
94
+ getArgumentCompletions: (prefix: string) => {
95
+ const items = [
96
+ { value: "full", label: "full", description: "Full tool details and output" },
97
+ { value: "compact", label: "compact", description: "Concise summaries for all built-in tools" },
98
+ { value: "clean", label: "clean", description: "Group supported tools into Running/Done status" },
99
+ { value: "status", label: "status", description: "Show the current mode" },
100
+ ];
101
+ const filtered = items.filter((item) => item.value.startsWith(prefix.trim().toLowerCase()));
102
+ return filtered.length > 0 ? filtered : null;
103
+ },
104
+ handler: async (args, ctx) => {
105
+ let requested = args.trim().toLowerCase();
106
+
107
+ if (!requested) {
108
+ if (!ctx.hasUI) {
109
+ ctx.ui.notify(`pi-pretty-tui mode: ${renderMode}`, "info");
110
+ return;
111
+ }
112
+ const full = `Full — full tool details and output${renderMode === "full" ? " (current)" : ""}`;
113
+ const compact = `Compact — concise summaries for all built-in tools${renderMode === "compact" ? " (current)" : ""}`;
114
+ const clean = `Clean — group supported tools into Running/Done status${renderMode === "clean" ? " (current)" : ""}`;
115
+ const selected = await ctx.ui.select("pi-pretty-tui rendering mode", [full, compact, clean]);
116
+ if (!selected) return;
117
+ requested = selected === full ? "full" : selected === compact ? "compact" : "clean";
118
+ }
119
+
120
+ if (requested === "status") {
121
+ ctx.ui.notify(`pi-pretty-tui mode: ${renderMode}`, "info");
122
+ return;
123
+ }
124
+ if (requested !== "full" && requested !== "compact" && requested !== "clean") {
125
+ ctx.ui.notify("Usage: /pretty-tui [full|compact|clean|status]", "error");
126
+ return;
127
+ }
128
+
129
+ cleanCompactToolCallIds.clear();
130
+ renderMode = requested;
131
+ for (const component of cleanToolComponents.values()) component.updateDisplay?.();
132
+ try {
133
+ saveRenderMode(renderMode);
134
+ ctx.ui.notify(`pi-pretty-tui mode set to: ${renderMode}`, "info");
135
+ } catch (error) {
136
+ const message = error instanceof Error ? error.message : String(error);
137
+ ctx.ui.notify(`Mode changed for this session, but could not save settings: ${message}`, "warning");
138
+ }
139
+ },
140
+ });
141
+
142
+ // Give Pi's main prompt editor a complete rounded frame. Render the native
143
+ // editor at a two-column narrower width so cursor layout, wrapping, IME, and
144
+ // autocomplete remain native, then add one themed border column per side.
145
+ const customEditorPrototype = CustomEditor.prototype as any;
146
+ const editorFramePatchKey = Symbol.for("pretty-tui.rounded-editor-frame");
147
+ if (!customEditorPrototype[editorFramePatchKey]) {
148
+ const hadOwnRender = Object.prototype.hasOwnProperty.call(customEditorPrototype, "render");
149
+ const hadOwnHandleMouse = Object.prototype.hasOwnProperty.call(customEditorPrototype, "handleMouse");
150
+ const originalEditorRender = customEditorPrototype.render;
151
+ const originalEditorHandleMouse = customEditorPrototype.handleMouse;
152
+ const patchedEditorRender = function (this: any, width: number): string[] {
153
+ if (width < 3) return originalEditorRender.call(this, width);
154
+
155
+ const innerWidth = width - 2;
156
+ const lines = originalEditorRender.call(this, innerWidth) as string[];
157
+ const visibleLineCount = Math.max(0, Number(this.renderedVisibleLineCount) || 0);
158
+ const bottomBorderIndex = visibleLineCount + 1;
159
+ const fitInnerWidth = (line: string) =>
160
+ line + " ".repeat(Math.max(0, innerWidth - visibleWidth(line)));
161
+
162
+ return lines.map((line, index) => {
163
+ const fitted = fitInnerWidth(line);
164
+ if (index === 0) return this.borderColor("╭") + fitted + this.borderColor("╮");
165
+ if (index === bottomBorderIndex) return this.borderColor("╰") + fitted + this.borderColor("╯");
166
+ if (index < bottomBorderIndex) return this.borderColor("│") + fitted + this.borderColor("│");
167
+ // Autocomplete remains outside the input frame, aligned to its content.
168
+ return " " + fitted + " ";
169
+ });
170
+ };
171
+ const patchedEditorHandleMouse = function (this: any, event: any) {
172
+ if (event.width < 3) return originalEditorHandleMouse.call(this, event);
173
+ const innerWidth = event.width - 2;
174
+ return originalEditorHandleMouse.call(this, {
175
+ ...event,
176
+ x: Math.max(0, Math.min(innerWidth - 1, event.x - 1)),
177
+ width: innerWidth,
178
+ });
179
+ };
180
+
181
+ customEditorPrototype[editorFramePatchKey] = {
182
+ hadOwnRender,
183
+ hadOwnHandleMouse,
184
+ originalRender: originalEditorRender,
185
+ originalHandleMouse: originalEditorHandleMouse,
186
+ patchedRender: patchedEditorRender,
187
+ patchedHandleMouse: patchedEditorHandleMouse,
188
+ };
189
+ customEditorPrototype.render = patchedEditorRender;
190
+ customEditorPrototype.handleMouse = patchedEditorHandleMouse;
191
+
192
+ pi.on("session_shutdown", () => {
193
+ const patch = customEditorPrototype[editorFramePatchKey];
194
+ if (!patch) return;
195
+ if (patch.patchedRender === customEditorPrototype.render) {
196
+ if (patch.hadOwnRender) customEditorPrototype.render = patch.originalRender;
197
+ else delete customEditorPrototype.render;
198
+ }
199
+ if (patch.patchedHandleMouse === customEditorPrototype.handleMouse) {
200
+ if (patch.hadOwnHandleMouse) customEditorPrototype.handleMouse = patch.originalHandleMouse;
201
+ else delete customEditorPrototype.handleMouse;
202
+ }
203
+ if (
204
+ customEditorPrototype.render === patch.originalRender &&
205
+ customEditorPrototype.handleMouse === patch.originalHandleMouse
206
+ ) {
207
+ delete customEditorPrototype[editorFramePatchKey];
208
+ }
209
+ });
210
+ }
211
+
212
+ // Render user prompts as a titled, rounded frame while preserving Pi's
213
+ // original Markdown component, wrapping, output padding, and OSC 133 zones.
214
+ const userMessagePrototype = UserMessageComponent.prototype as any;
215
+ const userMessagePatchKey = Symbol.for("pretty-tui.user-message-frame");
216
+ if (!userMessagePrototype[userMessagePatchKey]) {
217
+ const originalUserMessageRebuild = userMessagePrototype.rebuild;
218
+ const patchedUserMessageRebuild = function (this: any) {
219
+ originalUserMessageRebuild.call(this);
220
+ const content = this.children?.[0] as any;
221
+ if (!content) return;
222
+
223
+ // Reuse Pi's theme-aware user background across the complete frame.
224
+ const userMessageBg = content.bgFn as ((text: string) => string) | undefined;
225
+ content.paddingX = 0;
226
+ content.paddingY = 0;
227
+ content.setBgFn?.(undefined);
228
+ content.invalidate?.();
229
+
230
+ const outputPad = Math.max(0, Number(this.outputPad) || 0);
231
+ const markdownTheme = this.markdownTheme;
232
+ const border = (text: string) => markdownTheme.quoteBorder(text);
233
+ const frame: Component = {
234
+ render(width: number): string[] {
235
+ const sidePad = Math.min(outputPad, Math.max(0, Math.floor((width - 1) / 2)));
236
+ const outer = " ".repeat(sidePad);
237
+ const frameWidth = Math.max(1, width - sidePad * 2);
238
+ const paintBackground = (line: string) => {
239
+ const padding = " ".repeat(Math.max(0, frameWidth - visibleWidth(line)));
240
+ return userMessageBg ? userMessageBg(line + padding) : line + padding;
241
+ };
242
+ if (frameWidth < 4) {
243
+ return content.render(frameWidth).map((line: string) => outer + paintBackground(line));
244
+ }
245
+
246
+ const title = " User ";
247
+ const topStart = "╭─";
248
+ const topTail = "─".repeat(Math.max(0, frameWidth - visibleWidth(topStart) - visibleWidth(title) - 1));
249
+ const top = border(topStart + markdownTheme.bold(title) + topTail + "╮");
250
+ const bottom = border("╰" + "─".repeat(Math.max(0, frameWidth - 2)) + "╯");
251
+ const contentWidth = Math.max(1, frameWidth - 4);
252
+ const body = content.render(contentWidth).map((line: string) => {
253
+ const padding = " ".repeat(Math.max(0, contentWidth - visibleWidth(line)));
254
+ return border("│ ") + line + padding + border(" │");
255
+ });
256
+ return [top, ...body, bottom].map((line: string) => outer + paintBackground(line));
257
+ },
258
+ invalidate() {
259
+ content.invalidate?.();
260
+ },
261
+ };
262
+
263
+ this.clear();
264
+ this.addChild(frame);
265
+ };
266
+
267
+ userMessagePrototype[userMessagePatchKey] = {
268
+ originalRebuild: originalUserMessageRebuild,
269
+ patchedRebuild: patchedUserMessageRebuild,
270
+ };
271
+ userMessagePrototype.rebuild = patchedUserMessageRebuild;
272
+
273
+ pi.on("session_shutdown", () => {
274
+ const patch = userMessagePrototype[userMessagePatchKey];
275
+ if (!patch) return;
276
+ if (patch.patchedRebuild === userMessagePrototype.rebuild) {
277
+ userMessagePrototype.rebuild = patch.originalRebuild;
278
+ }
279
+ if (userMessagePrototype.rebuild === patch.originalRebuild) {
280
+ delete userMessagePrototype[userMessagePatchKey];
281
+ }
282
+ });
283
+ }
284
+
285
+ // Pi's built-in assistant component turns hidden thinking into a static
286
+ // "Thinking..." label. In collapsed clean mode, omit that label entirely;
287
+ // the clean-mode Running(...) row owns activity, while Ctrl+O still reveals
288
+ // the thinking content. The component is exported by Pi specifically for
289
+ // extension-level rendering customizations, so patch its public methods
290
+ // rather than Pi's source.
291
+ const assistantPrototype = AssistantMessageComponent.prototype as any;
292
+ const thinkingPatchKey = Symbol.for("pretty-tui.clean-thinking");
293
+ if (!assistantPrototype[thinkingPatchKey]) {
294
+ const originalUpdateContent = assistantPrototype.updateContent;
295
+ const originalRender = assistantPrototype.render;
296
+ const originalMessageKey = Symbol("pretty-tui.original-assistant-message");
297
+ const renderedModeKey = Symbol("pretty-tui.rendered-assistant-mode");
298
+ const renderedExpansionKey = Symbol("pretty-tui.rendered-thinking-expansion");
299
+
300
+ const patchedUpdateContent = function (this: any, message: any, isStreaming = this.isStreaming) {
301
+ if (renderMode !== "clean") {
302
+ originalUpdateContent.call(this, message, isStreaming);
303
+ this[originalMessageKey] = message;
304
+ this[renderedModeKey] = renderMode;
305
+ this[renderedExpansionKey] = undefined;
306
+ return;
307
+ }
308
+
309
+ const showThinking = cleanToolsExpanded;
310
+ const content = Array.isArray(message?.content) ? message.content : [];
311
+ // In collapsed clean mode, omit Pi's built-in Thinking... placeholder
312
+ // entirely. The clean-mode Running(...) row owns the activity label;
313
+ // expanded mode still reveals the actual thinking content.
314
+ const displayMessage = showThinking
315
+ ? message
316
+ : { ...message, content: content.filter((item: any) => item.type !== "thinking") };
317
+ const previousHideThinkingBlock = this.hideThinkingBlock;
318
+ this.hideThinkingBlock = false;
319
+ try {
320
+ originalUpdateContent.call(this, displayMessage, isStreaming);
321
+ } finally {
322
+ this.hideThinkingBlock = previousHideThinkingBlock;
323
+ }
324
+
325
+ // Pi's invalidate()/setHideThinkingBlock() call updateContent with
326
+ // lastMessage, so retain the unfiltered message for later mode changes.
327
+ this[originalMessageKey] = message;
328
+ this[renderedModeKey] = renderMode;
329
+ this[renderedExpansionKey] = showThinking;
330
+ this.lastMessage = message;
331
+ };
332
+
333
+ const patchedRender = function (this: any, width: number): string[] {
334
+ const needsRefresh = this[originalMessageKey] && (
335
+ this[renderedModeKey] !== renderMode ||
336
+ (renderMode === "clean" && this[renderedExpansionKey] !== cleanToolsExpanded)
337
+ );
338
+ if (needsRefresh) {
339
+ patchedUpdateContent.call(this, this[originalMessageKey], this.isStreaming);
340
+ }
341
+ return originalRender.call(this, width);
342
+ };
343
+
344
+ assistantPrototype[thinkingPatchKey] = {
345
+ originalUpdateContent,
346
+ patchedUpdateContent,
347
+ originalRender,
348
+ patchedRender,
349
+ };
350
+ assistantPrototype.updateContent = patchedUpdateContent;
351
+ assistantPrototype.render = patchedRender;
352
+
353
+ pi.on("session_shutdown", () => {
354
+ const patch = assistantPrototype[thinkingPatchKey];
355
+ if (!patch) return;
356
+ if (patch.patchedUpdateContent === assistantPrototype.updateContent) {
357
+ assistantPrototype.updateContent = patch.originalUpdateContent;
358
+ }
359
+ if (patch.patchedRender === assistantPrototype.render) {
360
+ assistantPrototype.render = patch.originalRender;
361
+ }
362
+ if (
363
+ assistantPrototype.updateContent === patch.originalUpdateContent &&
364
+ assistantPrototype.render === patch.originalRender
365
+ ) {
366
+ delete assistantPrototype[thinkingPatchKey];
367
+ }
368
+ });
369
+ }
370
+
371
+ // Extension shortcuts cannot replace Pi's built-in Ctrl+O binding. Wrap
372
+ // the exported state transition instead, so both Ctrl+O and UI callers keep
373
+ // their normal behavior while clean thinking follows the same state.
374
+ const interactiveModePrototype = InteractiveMode.prototype as any;
375
+ const toolsExpansionPatchKey = Symbol.for("pretty-tui.clean-tool-expansion");
376
+ if (!interactiveModePrototype[toolsExpansionPatchKey]) {
377
+ const originalSetToolsExpanded = interactiveModePrototype.setToolsExpanded;
378
+ const patchedSetToolsExpanded = function (this: any, expanded: boolean) {
379
+ cleanToolsExpanded = expanded;
380
+ changingAllToolsExpansion = true;
381
+ if (!expanded) cleanCompactToolCallIds.clear();
382
+ try {
383
+ return originalSetToolsExpanded.call(this, expanded);
384
+ } finally {
385
+ changingAllToolsExpansion = false;
386
+ }
387
+ };
388
+
389
+ interactiveModePrototype[toolsExpansionPatchKey] = {
390
+ originalSetToolsExpanded,
391
+ patchedSetToolsExpanded,
392
+ };
393
+ interactiveModePrototype.setToolsExpanded = patchedSetToolsExpanded;
394
+
395
+ pi.on("session_shutdown", () => {
396
+ const patch = interactiveModePrototype[toolsExpansionPatchKey];
397
+ if (!patch) return;
398
+ if (patch.patchedSetToolsExpanded === interactiveModePrototype.setToolsExpanded) {
399
+ interactiveModePrototype.setToolsExpanded = patch.originalSetToolsExpanded;
400
+ }
401
+ if (interactiveModePrototype.setToolsExpanded === patch.originalSetToolsExpanded) {
402
+ delete interactiveModePrototype[toolsExpansionPatchKey];
403
+ }
404
+ });
405
+ }
21
406
 
22
407
  // Pi normalizes unordered-list markers to "-". Replace only that marker;
23
408
  // leave code-block rendering entirely to Pi's built-in Markdown renderer.
@@ -266,19 +651,843 @@ export default function prettyTui(pi: ExtensionAPI) {
266
651
  return failed;
267
652
  };
268
653
 
654
+ type ToolSummaryGroup = {
655
+ count: number;
656
+ failed: number;
657
+ lastToolCallId: string;
658
+ toolCallIds?: string[];
659
+ activity?: string;
660
+ };
661
+ type ToolSummaryData = {
662
+ count?: number;
663
+ failed?: number;
664
+ /** Identifies the last tool component for older single-group entries. */
665
+ lastToolCallId?: string;
666
+ /** All groups from a run, used to restore summaries after reload. */
667
+ groups?: ToolSummaryGroup[];
668
+ };
669
+ const supportedTools = new Set(["read", "bash", "edit", "write", "grep", "find", "ls"]);
670
+ type ToolActivityHold = {
671
+ toolCallId: string;
672
+ name: string;
673
+ until: number;
674
+ after: string;
675
+ started: boolean;
676
+ timer?: ReturnType<typeof setTimeout>;
677
+ };
678
+ const settledSummaries = new Map<string, { count: number; failed: number; activity: DisplayValue }>();
679
+ const toolActivityHolds = new Map<string, ToolActivityHold>();
680
+ const legacySummaryLastToolCallIds = new Map<string, string>();
681
+ const knownToolCallIds = new Set<string>();
682
+ type CleanRunState = {
683
+ activeToolCallId?: string;
684
+ lastCompletedToolCallId?: string;
685
+ activeToolName?: string;
686
+ activity?: string;
687
+ requestRender?: () => void;
688
+ count: number;
689
+ failed: number;
690
+ currentToolCallIds: string[];
691
+ activeToolCallIds: Set<string>;
692
+ groups: ToolSummaryGroup[];
693
+ active: boolean;
694
+ settled: boolean;
695
+ };
696
+ const cleanRun: CleanRunState = {
697
+ count: 0,
698
+ failed: 0,
699
+ currentToolCallIds: [],
700
+ activeToolCallIds: new Set(),
701
+ groups: [],
702
+ active: false,
703
+ settled: false,
704
+ };
705
+
706
+ const toolDisplayName = (name: string): string =>
707
+ name === "ls" ? "List" : name.charAt(0).toUpperCase() + name.slice(1);
708
+
709
+ const clearToolActivityHolds = () => {
710
+ for (const hold of toolActivityHolds.values()) {
711
+ if (hold.timer) clearTimeout(hold.timer);
712
+ }
713
+ toolActivityHolds.clear();
714
+ };
715
+
716
+ const heldActivity = (hold: ToolActivityHold): string =>
717
+ Date.now() < hold.until ? hold.name : hold.after;
718
+
719
+ const scheduleToolActivityRelease = (hold: ToolActivityHold) => {
720
+ if (hold.timer) clearTimeout(hold.timer);
721
+ const delay = Math.max(0, hold.until - Date.now());
722
+ hold.timer = setTimeout(() => {
723
+ hold.timer = undefined;
724
+ if (Date.now() < hold.until) {
725
+ scheduleToolActivityRelease(hold);
726
+ return;
727
+ }
728
+ if (toolActivityHolds.get(hold.toolCallId) === hold) {
729
+ toolActivityHolds.delete(hold.toolCallId);
730
+ }
731
+ if (cleanRun.lastCompletedToolCallId === hold.toolCallId && !cleanRun.activeToolCallId) {
732
+ cleanRun.activeToolName = undefined;
733
+ cleanRun.activity = hold.after;
734
+ }
735
+ cleanRun.requestRender?.();
736
+ }, delay);
737
+ };
738
+
739
+ const beginToolActivity = (toolCallId: string, name: string, started = false) => {
740
+ const previous = toolActivityHolds.get(toolCallId);
741
+ if (previous) {
742
+ if (previous.timer) clearTimeout(previous.timer);
743
+ previous.name = name;
744
+ previous.started ||= started;
745
+ cleanRun.activeToolName = name;
746
+ cleanRun.activity = name;
747
+ return;
748
+ }
749
+ const startedAt = Date.now();
750
+ toolActivityHolds.set(toolCallId, {
751
+ toolCallId,
752
+ name,
753
+ until: startedAt + CLEAN_TOOL_ACTIVITY_MIN_MS,
754
+ after: "thinking...",
755
+ started,
756
+ });
757
+ cleanRun.activeToolName = name;
758
+ cleanRun.activity = name;
759
+ };
760
+
761
+ const holdToolActivity = (toolCallId: string, name: string) => {
762
+ let hold = toolActivityHolds.get(toolCallId);
763
+ if (!hold) {
764
+ const now = Date.now();
765
+ hold = {
766
+ toolCallId,
767
+ name,
768
+ until: now + CLEAN_TOOL_ACTIVITY_MIN_MS,
769
+ after: "thinking...",
770
+ started: true,
771
+ };
772
+ toolActivityHolds.set(toolCallId, hold);
773
+ }
774
+ hold.name = name;
775
+ hold.started = true;
776
+ hold.after = "thinking...";
777
+ scheduleToolActivityRelease(hold);
778
+ };
779
+
780
+ const activityValueForHold = (toolCallId: string, after: string): DisplayValue => {
781
+ const hold = toolActivityHolds.get(toolCallId);
782
+ if (!hold) return after;
783
+ hold.after = after;
784
+ return () => heldActivity(hold);
785
+ };
786
+
787
+ const liveCleanToolCount = (): number =>
788
+ Math.max(cleanRun.count, cleanRun.currentToolCallIds.length);
789
+
790
+ const currentCleanActivity = (): string => {
791
+ if (cleanRun.activeToolCallId) {
792
+ return cleanRun.activeToolName ?? cleanRun.activity ?? "thinking...";
793
+ }
794
+ if (cleanRun.lastCompletedToolCallId) {
795
+ const hold = toolActivityHolds.get(cleanRun.lastCompletedToolCallId);
796
+ if (hold) return heldActivity(hold);
797
+ }
798
+ return cleanRun.activeToolName ?? cleanRun.activity ?? (cleanRun.active ? "thinking..." : "done");
799
+ };
800
+
801
+ pi.on("session_shutdown", clearToolActivityHolds);
802
+
803
+ // A tool component can be created from the streamed assistant message
804
+ // before Pi dispatches tool_execution_start. Mark its activity at the
805
+ // component's own execution boundary too, so the first clean render names it.
806
+ const toolExecutionPrototype = ToolExecutionComponent.prototype as any;
807
+ const toolExecutionPatchKey = Symbol.for("pretty-tui.clean-tool-execution");
808
+ if (!toolExecutionPrototype[toolExecutionPatchKey]) {
809
+ const originalMarkExecutionStarted = toolExecutionPrototype.markExecutionStarted;
810
+ const originalSetExpanded = toolExecutionPrototype.setExpanded;
811
+ const originalToolRender = toolExecutionPrototype.render;
812
+ const originalToolHandleMouse = toolExecutionPrototype.handleMouse;
813
+ const renderedModeKey = Symbol("pretty-tui.tool-rendered-mode");
814
+ const revealCleanGroup = (groupToolCallIds: string[], ui?: any) => {
815
+ for (const toolCallId of groupToolCallIds) cleanCompactToolCallIds.add(toolCallId);
816
+ for (const toolCallId of groupToolCallIds) cleanToolComponents.get(toolCallId)?.updateDisplay();
817
+ ui?.requestRender?.();
818
+ };
819
+ const patchedMarkExecutionStarted = function (this: any) {
820
+ if (supportedTools.has(this.toolName)) {
821
+ if (!cleanRun.currentToolCallIds.includes(this.toolCallId)) {
822
+ cleanRun.currentToolCallIds.push(this.toolCallId);
823
+ }
824
+ cleanRun.activeToolCallIds.add(this.toolCallId);
825
+ cleanToolNames.set(this.toolCallId, toolDisplayName(this.toolName));
826
+ setCleanGroupMembers(this.toolCallId, cleanRun.currentToolCallIds.slice());
827
+ if (typeof this.ui?.requestRender === "function") {
828
+ cleanRun.requestRender = () => this.ui.requestRender();
829
+ }
830
+ cleanRun.active = true;
831
+ cleanRun.activeToolCallId = this.toolCallId;
832
+ beginToolActivity(this.toolCallId, toolDisplayName(this.toolName), true);
833
+ }
834
+ return originalMarkExecutionStarted.call(this);
835
+ };
836
+ const patchedSetExpanded = function (this: any, expanded: boolean) {
837
+ const groupToolCallIds = cleanGroupToolCallIds.get(this.toolCallId);
838
+ if (
839
+ renderMode === "clean" &&
840
+ !changingAllToolsExpansion &&
841
+ expanded &&
842
+ !this.expanded &&
843
+ !isCleanGroupRevealed(this.toolCallId) &&
844
+ groupToolCallIds?.length
845
+ ) {
846
+ revealCleanGroup(groupToolCallIds, this.ui);
847
+ return;
848
+ }
849
+ return originalSetExpanded.call(this, expanded);
850
+ };
851
+ const patchedToolRender = function (this: any, width: number): string[] {
852
+ if (supportedTools.has(this.toolName)) {
853
+ cleanToolComponents.set(this.toolCallId, this);
854
+ knownToolCallIds.add(this.toolCallId);
855
+ }
856
+ if (this[renderedModeKey] !== renderMode) {
857
+ this[renderedModeKey] = renderMode;
858
+ this.updateDisplay();
859
+ }
860
+
861
+ const groupOwner = cleanToolCallGroupOwners.get(this.toolCallId);
862
+ const groupToolCallIds = groupOwner ? cleanGroupToolCallIds.get(groupOwner) : undefined;
863
+ const childIndex = groupToolCallIds?.indexOf(this.toolCallId) ?? -1;
864
+ const showAsChild = renderMode === "clean" && childIndex >= 0 && isCleanGroupRevealed(this.toolCallId);
865
+ if (!showAsChild || !groupOwner || !groupToolCallIds) {
866
+ return originalToolRender.call(this, width);
867
+ }
868
+
869
+ const rawChildPrefix = childIndex === groupToolCallIds.length - 1 ? " └─ " : " ├─ ";
870
+ const rawContinuation = childIndex === groupToolCallIds.length - 1 ? " " : " │ ";
871
+ const childTheme = cleanThemeForToolCall(this.toolCallId);
872
+ const childPrefix = childTheme ? childTheme.fg("dim", rawChildPrefix) : rawChildPrefix;
873
+ const continuation = childTheme ? childTheme.fg("dim", rawContinuation) : rawContinuation;
874
+ const childWidth = Math.max(1, width - visibleWidth(rawChildPrefix));
875
+ const lines = originalToolRender.call(this, childWidth);
876
+ if (lines.length === 0) return lines;
877
+
878
+ const decoratedContent = lines.slice(1).map((line: string, index: number) =>
879
+ (index === 0 ? childPrefix : continuation) + line
880
+ );
881
+ if (childIndex !== 0) return decoratedContent;
882
+ return [lines[0], ...renderCleanGroupSummary(groupOwner, width), ...decoratedContent];
883
+ };
884
+ const patchedToolHandleMouse = function (this: any, event: any) {
885
+ const groupOwner = cleanToolCallGroupOwners.get(this.toolCallId);
886
+ const groupToolCallIds = groupOwner ? cleanGroupToolCallIds.get(groupOwner) : undefined;
887
+ const childIndex = groupToolCallIds?.indexOf(this.toolCallId) ?? -1;
888
+ const showAsChild = renderMode === "clean" && childIndex >= 0 && isCleanGroupRevealed(this.toolCallId);
889
+ const isLeftClick = event.type === "click" && event.button === "left";
890
+
891
+ // Pi normally ignores tool clicks until a result exists. Clean mode can
892
+ // still reveal the active call safely because this changes presentation
893
+ // only; it does not affect or delay execution.
894
+ if (
895
+ renderMode === "clean" &&
896
+ !showAsChild &&
897
+ isLeftClick &&
898
+ this.toolCallId === groupOwner &&
899
+ groupToolCallIds?.length
900
+ ) {
901
+ revealCleanGroup(groupToolCallIds, this.ui);
902
+ return { handled: true };
903
+ }
904
+ if (!showAsChild || !groupToolCallIds) return originalToolHandleMouse.call(this, event);
905
+
906
+ const summaryHeight = childIndex === 0 ? renderCleanGroupSummary(groupOwner!, event.width).length : 0;
907
+ if (
908
+ childIndex === 0 &&
909
+ event.y > 0 &&
910
+ event.y <= summaryHeight &&
911
+ isLeftClick
912
+ ) {
913
+ changingAllToolsExpansion = true;
914
+ try {
915
+ for (const toolCallId of groupToolCallIds) {
916
+ const component = cleanToolComponents.get(toolCallId);
917
+ if (component?.expanded) originalSetExpanded.call(component, false);
918
+ cleanCompactToolCallIds.delete(toolCallId);
919
+ }
920
+ for (const toolCallId of groupToolCallIds) cleanToolComponents.get(toolCallId)?.updateDisplay();
921
+ } finally {
922
+ changingAllToolsExpansion = false;
923
+ }
924
+ this.ui?.requestRender?.();
925
+ return { handled: true };
926
+ }
927
+
928
+ if (!this.result && isLeftClick) {
929
+ originalSetExpanded.call(this, !this.expanded);
930
+ this.ui?.requestRender?.();
931
+ return { handled: true };
932
+ }
933
+
934
+ const childPrefixWidth = visibleWidth(" ├─ ");
935
+ return originalToolHandleMouse.call(this, {
936
+ ...event,
937
+ x: Math.max(0, event.x - childPrefixWidth),
938
+ y: event.y - summaryHeight + (childIndex === 0 ? 0 : 1),
939
+ width: Math.max(1, event.width - childPrefixWidth),
940
+ });
941
+ };
942
+
943
+ toolExecutionPrototype[toolExecutionPatchKey] = {
944
+ originalMarkExecutionStarted,
945
+ patchedMarkExecutionStarted,
946
+ originalSetExpanded,
947
+ patchedSetExpanded,
948
+ originalRender: originalToolRender,
949
+ patchedRender: patchedToolRender,
950
+ originalHandleMouse: originalToolHandleMouse,
951
+ patchedHandleMouse: patchedToolHandleMouse,
952
+ };
953
+ toolExecutionPrototype.markExecutionStarted = patchedMarkExecutionStarted;
954
+ toolExecutionPrototype.setExpanded = patchedSetExpanded;
955
+ toolExecutionPrototype.render = patchedToolRender;
956
+ toolExecutionPrototype.handleMouse = patchedToolHandleMouse;
957
+
958
+ pi.on("session_shutdown", () => {
959
+ const patch = toolExecutionPrototype[toolExecutionPatchKey];
960
+ if (!patch) return;
961
+ if (patch.patchedMarkExecutionStarted === toolExecutionPrototype.markExecutionStarted) {
962
+ toolExecutionPrototype.markExecutionStarted = patch.originalMarkExecutionStarted;
963
+ }
964
+ if (patch.patchedSetExpanded === toolExecutionPrototype.setExpanded) {
965
+ toolExecutionPrototype.setExpanded = patch.originalSetExpanded;
966
+ }
967
+ if (patch.patchedRender === toolExecutionPrototype.render) {
968
+ toolExecutionPrototype.render = patch.originalRender;
969
+ }
970
+ if (patch.patchedHandleMouse === toolExecutionPrototype.handleMouse) {
971
+ toolExecutionPrototype.handleMouse = patch.originalHandleMouse;
972
+ }
973
+ if (
974
+ toolExecutionPrototype.markExecutionStarted === patch.originalMarkExecutionStarted &&
975
+ toolExecutionPrototype.setExpanded === patch.originalSetExpanded &&
976
+ toolExecutionPrototype.render === patch.originalRender &&
977
+ toolExecutionPrototype.handleMouse === patch.originalHandleMouse
978
+ ) {
979
+ delete toolExecutionPrototype[toolExecutionPatchKey];
980
+ }
981
+ });
982
+ }
983
+
984
+ const finishCleanGroup = (activity = cleanRun.activity ?? "done") => {
985
+ if (cleanRun.lastCompletedToolCallId && cleanRun.count > 0) {
986
+ const group: ToolSummaryGroup = {
987
+ count: cleanRun.count,
988
+ failed: cleanRun.failed,
989
+ lastToolCallId: cleanRun.lastCompletedToolCallId,
990
+ toolCallIds: cleanRun.currentToolCallIds.slice(),
991
+ activity,
992
+ };
993
+ cleanRun.groups.push(group);
994
+ settledSummaries.set(group.lastToolCallId, {
995
+ count: group.count,
996
+ failed: group.failed,
997
+ activity: activityValueForHold(group.lastToolCallId, activity),
998
+ });
999
+ setCleanGroupMembers(group.lastToolCallId, group.toolCallIds ?? []);
1000
+ }
1001
+ cleanRun.count = 0;
1002
+ cleanRun.failed = 0;
1003
+ cleanRun.currentToolCallIds = [];
1004
+ cleanRun.activeToolCallIds.clear();
1005
+ cleanRun.lastCompletedToolCallId = undefined;
1006
+ cleanRun.activeToolCallId = undefined;
1007
+ cleanRun.activeToolName = undefined;
1008
+ };
1009
+
1010
+ const settleLastCleanGroup = () => {
1011
+ const group = cleanRun.groups[cleanRun.groups.length - 1];
1012
+ if (!group) return;
1013
+ group.activity = "done";
1014
+ settledSummaries.set(group.lastToolCallId, {
1015
+ count: group.count,
1016
+ failed: group.failed,
1017
+ activity: activityValueForHold(group.lastToolCallId, "done"),
1018
+ });
1019
+ };
1020
+
1021
+ const summaryText = (count: number, _failed: number, activity = "done"): string => {
1022
+ const activityText = typeof activity === "string" ? activity : "done";
1023
+ const countLabel = `${count} tool ${count === 1 ? "call" : "calls"}`;
1024
+ const activityLabel = activityText !== "done" && activityText.trim()
1025
+ ? ` · ${activityText}`
1026
+ : "";
1027
+ return `${countLabel}${activityLabel}`;
1028
+ };
1029
+
1030
+ const summaryRow = (
1031
+ theme: any,
1032
+ count: number,
1033
+ failed: number,
1034
+ activity: DisplayValue = "done",
1035
+ ): DisplayRow => ({
1036
+ prefix: () => {
1037
+ const currentActivity = typeof activity === "function" ? activity() : activity;
1038
+ const color = currentActivity === "done" ? "success" : "accent";
1039
+ return theme.fg(color, "● ");
1040
+ },
1041
+ continuation: " ",
1042
+ content: () => {
1043
+ const currentActivity = typeof activity === "function" ? activity() : activity;
1044
+ const label = currentActivity === "done" ? "Done" : "Running";
1045
+ const color = label === "Done" ? "success" : "accent";
1046
+ return theme.fg(color, theme.bold(label)) +
1047
+ theme.fg("dim", "(") +
1048
+ theme.fg("text", summaryText(count, failed, currentActivity)) + theme.fg("dim", ")");
1049
+ },
1050
+ });
1051
+
1052
+ renderCleanGroupSummary = (lastToolCallId: string, width: number): string[] => {
1053
+ const summaryTheme = cleanThemeForToolCall(lastToolCallId);
1054
+ if (!summaryTheme) return [];
1055
+ const settled = settledSummaries.get(lastToolCallId);
1056
+ if (settled) {
1057
+ return block([summaryRow(summaryTheme, settled.count, settled.failed, settled.activity)]).render(width);
1058
+ }
1059
+ if (cleanRun.activeToolCallId === lastToolCallId) {
1060
+ return block([summaryRow(
1061
+ summaryTheme,
1062
+ liveCleanToolCount(),
1063
+ cleanRun.failed,
1064
+ () => cleanRun.activeToolName ?? currentCleanActivity(),
1065
+ )]).render(width);
1066
+ }
1067
+ if (cleanRun.lastCompletedToolCallId === lastToolCallId && cleanRun.count > 0) {
1068
+ return block([summaryRow(summaryTheme, cleanRun.count, cleanRun.failed, currentCleanActivity)]).render(width);
1069
+ }
1070
+ return [];
1071
+ };
1072
+
1073
+ /**
1074
+ * Clean mode keeps Running/Done rows in the existing tool components. This
1075
+ * avoids waiting for agent_end (which can be followed by retry/compaction),
1076
+ * leaves a visible count between calls, and keeps each row in transcript order.
1077
+ */
1078
+ const cleanToolCall = (theme: any, name: string, toolCallId: string): Component => {
1079
+ knownToolCallIds.add(toolCallId);
1080
+ cleanToolThemes.set(toolCallId, theme);
1081
+ return {
1082
+ render(width: number): string[] {
1083
+ if (renderMode !== "clean") return [];
1084
+
1085
+ const settledSummary = settledSummaries.get(toolCallId);
1086
+ if (settledSummary) {
1087
+ return block([summaryRow(theme, settledSummary.count, settledSummary.failed, settledSummary.activity)]).render(width);
1088
+ }
1089
+ if (cleanRun.settled) return [];
1090
+
1091
+ if (cleanRun.activeToolCallId === toolCallId) {
1092
+ return block([summaryRow(
1093
+ theme,
1094
+ liveCleanToolCount(),
1095
+ cleanRun.failed,
1096
+ () => cleanRun.activeToolName ?? name,
1097
+ )]).render(width);
1098
+ }
1099
+
1100
+ // The active tool owns the live Running row. Keep the latest completed
1101
+ // portion hidden while that tool's minimum display time is running.
1102
+ if (
1103
+ cleanRun.lastCompletedToolCallId === toolCallId &&
1104
+ cleanRun.count > 0 &&
1105
+ !cleanRun.activeToolCallId
1106
+ ) {
1107
+ return block([summaryRow(theme, cleanRun.count, cleanRun.failed, currentCleanActivity)]).render(width);
1108
+ }
1109
+
1110
+ // Do not fall back to the per-component pending state here: Pi may
1111
+ // create several tool-call components before execution starts, and
1112
+ // showing that fallback would briefly expose all of them. The active
1113
+ // component is selected to render the current Running row at execution start.
1114
+ return [];
1115
+ },
1116
+ invalidate() {},
1117
+ };
1118
+ };
1119
+
1120
+ const hiddenToolResult = (context: any, options: any, output: string): Component => {
1121
+ if (options.isPartial) setStatus(context, "running");
1122
+ else completeStatus(context, output);
1123
+ return block([]);
1124
+ };
1125
+
1126
+ // In collapsed clean mode, every supported tool call is represented by its
1127
+ // Running row. Ctrl+O bypasses this and restores the normal full renderer.
1128
+ const hideCleanTool = (
1129
+ toolCallId: string,
1130
+ expanded: boolean,
1131
+ _executionStarted = false,
1132
+ ): boolean => renderMode === "clean" && !expanded && !isCleanGroupRevealed(toolCallId);
1133
+
1134
+ const useCompactToolView = (toolCallId: string, expanded: boolean): boolean =>
1135
+ !expanded && (
1136
+ renderMode === "compact" ||
1137
+ (renderMode === "clean" && isCleanGroupRevealed(toolCallId))
1138
+ );
1139
+
1140
+ pi.registerEntryRenderer<ToolSummaryData>("pretty-tui-tool-summary", (entry, { expanded }, theme) => ({
1141
+ render(width: number): string[] {
1142
+ if (renderMode !== "clean" || expanded) return [];
1143
+ const data = entry.data;
1144
+ const groups = data?.groups?.length
1145
+ ? data.groups
1146
+ : data?.lastToolCallId
1147
+ ? [{
1148
+ count: data.count ?? 0,
1149
+ failed: data.failed ?? 0,
1150
+ lastToolCallId: data.lastToolCallId,
1151
+ }]
1152
+ : (() => {
1153
+ const summaryCallId = legacySummaryLastToolCallIds.get(entry.id);
1154
+ return summaryCallId
1155
+ ? [{
1156
+ count: data?.count ?? 0,
1157
+ failed: data?.failed ?? 0,
1158
+ lastToolCallId: summaryCallId,
1159
+ }]
1160
+ : [];
1161
+ })();
1162
+ // The live tool components own the visual positions. Keep this durable
1163
+ // entry as a fallback only for groups whose tool components are absent
1164
+ // from the current branch (for example, after compaction).
1165
+ const missingGroups = groups.filter((group) => !knownToolCallIds.has(group.lastToolCallId));
1166
+ if (missingGroups.length === 0) return [];
1167
+ // Persisted entries represent settled groups. Older versions could
1168
+ // accidentally store the transient responding... activity, so always
1169
+ // normalize their display to Done.
1170
+ return block(missingGroups.map((group) =>
1171
+ summaryRow(theme, group.count, group.failed, "done")
1172
+ )).render(width);
1173
+ },
1174
+ invalidate() {},
1175
+ }));
1176
+
1177
+ const restoreCleanSession = (ctx: any) => {
1178
+ cleanToolsExpanded = ctx.ui.getToolsExpanded();
1179
+ settledSummaries.clear();
1180
+ legacySummaryLastToolCallIds.clear();
1181
+ knownToolCallIds.clear();
1182
+ cleanCompactToolCallIds.clear();
1183
+ cleanGroupToolCallIds.clear();
1184
+ cleanToolCallGroupOwners.clear();
1185
+ cleanToolComponents.clear();
1186
+ cleanToolThemes.clear();
1187
+ cleanToolNames.clear();
1188
+ clearToolActivityHolds();
1189
+ cleanRun.requestRender = undefined;
1190
+ cleanRun.count = 0;
1191
+ cleanRun.failed = 0;
1192
+ cleanRun.currentToolCallIds = [];
1193
+ cleanRun.activeToolCallIds.clear();
1194
+ cleanRun.groups = [];
1195
+ cleanRun.activeToolCallId = undefined;
1196
+ cleanRun.activeToolName = undefined;
1197
+ cleanRun.lastCompletedToolCallId = undefined;
1198
+ cleanRun.activity = undefined;
1199
+ cleanRun.active = false;
1200
+ cleanRun.settled = false;
1201
+
1202
+ let count = 0;
1203
+ let failed = 0;
1204
+ let lastToolCallId: string | undefined;
1205
+ let lastFinishedGroup: ToolSummaryGroup | undefined;
1206
+ const toolCalls = new Set<string>();
1207
+ const explicitSummaryIds = new Set<string>();
1208
+
1209
+ const rememberGroup = (group: ToolSummaryGroup, entryId?: string) => {
1210
+ settledSummaries.set(group.lastToolCallId, {
1211
+ count: group.count,
1212
+ failed: group.failed,
1213
+ activity: "done",
1214
+ });
1215
+ if (group.toolCallIds?.length) {
1216
+ setCleanGroupMembers(group.lastToolCallId, group.toolCallIds.slice());
1217
+ }
1218
+ if (entryId) legacySummaryLastToolCallIds.set(entryId, group.lastToolCallId);
1219
+ explicitSummaryIds.add(group.lastToolCallId);
1220
+ };
1221
+
1222
+ const finishGroup = () => {
1223
+ if (lastToolCallId && count > 0) {
1224
+ lastFinishedGroup = { count, failed, lastToolCallId, toolCallIds: [...toolCalls] };
1225
+ setCleanGroupMembers(lastToolCallId, [...toolCalls]);
1226
+ if (!explicitSummaryIds.has(lastToolCallId)) {
1227
+ settledSummaries.set(lastToolCallId, { count, failed, activity: "done" });
1228
+ }
1229
+ }
1230
+ count = 0;
1231
+ failed = 0;
1232
+ lastToolCallId = undefined;
1233
+ toolCalls.clear();
1234
+ };
1235
+
1236
+ // Use the same compaction-aware branch that Pi renders in the transcript;
1237
+ // getEntries() can also contain entries from other branches.
1238
+ for (const entry of ctx.sessionManager.buildContextEntries()) {
1239
+ if (entry.type === "custom" && entry.customType === "pretty-tui-tool-summary") {
1240
+ const data = entry.data as ToolSummaryData | undefined;
1241
+ if (data?.groups?.length) {
1242
+ for (const group of data.groups) {
1243
+ if (group?.lastToolCallId && group.count > 0) rememberGroup(group);
1244
+ }
1245
+ } else if (data?.lastToolCallId) {
1246
+ rememberGroup({
1247
+ count: data.count ?? 0,
1248
+ failed: data.failed ?? 0,
1249
+ lastToolCallId: data.lastToolCallId,
1250
+ });
1251
+ } else if (lastFinishedGroup) {
1252
+ // Migrate summaries written by the earlier clean-mode versions,
1253
+ // which did not persist the final tool call id. The text message
1254
+ // preceding this entry has already closed the group.
1255
+ rememberGroup({
1256
+ count: data?.count ?? lastFinishedGroup.count,
1257
+ failed: data?.failed ?? lastFinishedGroup.failed,
1258
+ lastToolCallId: lastFinishedGroup.lastToolCallId,
1259
+ }, entry.id);
1260
+ } else if (lastToolCallId && count > 0) {
1261
+ // Also handle a legacy entry inserted before the boundary text.
1262
+ rememberGroup({
1263
+ count: data?.count ?? count,
1264
+ failed: data?.failed ?? failed,
1265
+ lastToolCallId,
1266
+ }, entry.id);
1267
+ }
1268
+ continue;
1269
+ }
1270
+
1271
+ if (entry.type !== "message") continue;
1272
+ const message = entry.message as any;
1273
+
1274
+ if (message.role === "user") {
1275
+ finishGroup();
1276
+ lastFinishedGroup = undefined;
1277
+ continue;
1278
+ }
1279
+
1280
+ if (message.role === "assistant") {
1281
+ const hasVisibleText = (message.content ?? []).some(
1282
+ (item: any) => item.type === "text" && typeof item.text === "string" && item.text.trim().length > 0,
1283
+ );
1284
+ if (hasVisibleText) finishGroup();
1285
+ for (const item of message.content ?? []) {
1286
+ if (item.type !== "toolCall" || !supportedTools.has(item.name)) continue;
1287
+ count++;
1288
+ lastToolCallId = item.id;
1289
+ toolCalls.add(item.id);
1290
+ }
1291
+ continue;
1292
+ }
1293
+
1294
+ if (message.role === "toolResult" && toolCalls.has(message.toolCallId) && message.isError) {
1295
+ failed++;
1296
+ }
1297
+ }
1298
+
1299
+ finishGroup();
1300
+ };
1301
+
1302
+ pi.on("session_start", (_event, ctx) => restoreCleanSession(ctx));
1303
+ pi.on("session_tree", (_event, ctx) => restoreCleanSession(ctx));
1304
+ pi.on("session_compact", () => {
1305
+ // Tool components removed by compaction must no longer suppress the
1306
+ // durable summary fallback. Remaining components register again as Pi
1307
+ // renders the rebuilt transcript.
1308
+ knownToolCallIds.clear();
1309
+ });
1310
+
1311
+ const hasVisibleAssistantText = (message: any): boolean =>
1312
+ message?.role === "assistant" && (message.content ?? []).some(
1313
+ (item: any) => item.type === "text" && typeof item.text === "string" && item.text.trim().length > 0,
1314
+ );
1315
+
1316
+ const pendingToolCalls = (message: any): any[] =>
1317
+ (message?.content ?? []).filter(
1318
+ (item: any) => item.type === "toolCall" && supportedTools.has(item.name) && item.id,
1319
+ );
1320
+
1321
+ const trackPendingToolActivity = (message: any): boolean => {
1322
+ const toolCalls = pendingToolCalls(message);
1323
+ if (toolCalls.length === 0) return false;
1324
+ for (const toolCall of toolCalls) {
1325
+ if (!cleanRun.currentToolCallIds.includes(toolCall.id)) {
1326
+ cleanRun.currentToolCallIds.push(toolCall.id);
1327
+ }
1328
+ cleanToolNames.set(toolCall.id, toolDisplayName(toolCall.name));
1329
+ }
1330
+ const toolCall = toolCalls[toolCalls.length - 1];
1331
+ if (cleanRun.lastCompletedToolCallId === toolCall.id) return false;
1332
+ setCleanGroupMembers(toolCall.id, cleanRun.currentToolCallIds.slice());
1333
+ cleanRun.active = true;
1334
+ cleanRun.activeToolCallId = toolCall.id;
1335
+ beginToolActivity(toolCall.id, toolDisplayName(toolCall.name));
1336
+ return true;
1337
+ };
1338
+
1339
+ const clearPendingToolActivities = () => {
1340
+ for (const [toolCallId, hold] of toolActivityHolds) {
1341
+ if (hold.started) continue;
1342
+ if (hold.timer) clearTimeout(hold.timer);
1343
+ toolActivityHolds.delete(toolCallId);
1344
+ if (cleanRun.activeToolCallId === toolCallId) {
1345
+ cleanRun.activeToolCallId = undefined;
1346
+ cleanRun.activeToolName = undefined;
1347
+ }
1348
+ }
1349
+ };
1350
+
1351
+ // A visible assistant response is the boundary between tool groups. Do
1352
+ // this during streaming so a following tool call cannot inherit the prior
1353
+ // summary, while message_end keeps the rule correct for non-streaming paths.
1354
+ pi.on("message_update", (event) => {
1355
+ if (hasVisibleAssistantText(event.message)) {
1356
+ cleanRun.activity = "responding...";
1357
+ finishCleanGroup("responding...");
1358
+ return;
1359
+ }
1360
+ trackPendingToolActivity(event.message);
1361
+ });
1362
+ pi.on("message_end", (event) => {
1363
+ if (hasVisibleAssistantText(event.message)) {
1364
+ cleanRun.activity = "done";
1365
+ finishCleanGroup("done");
1366
+ settleLastCleanGroup();
1367
+ return;
1368
+ }
1369
+ trackPendingToolActivity(event.message);
1370
+ });
1371
+
1372
+ pi.on("agent_start", () => {
1373
+ // A retry can start another low-level agent loop. Keep the accumulated
1374
+ // count until the whole run reaches agent_settled.
1375
+ if (!cleanRun.active) {
1376
+ clearToolActivityHolds();
1377
+ cleanRun.count = 0;
1378
+ cleanRun.failed = 0;
1379
+ cleanRun.currentToolCallIds = [];
1380
+ cleanRun.activeToolCallIds.clear();
1381
+ cleanRun.groups = [];
1382
+ cleanRun.lastCompletedToolCallId = undefined;
1383
+ cleanRun.settled = false;
1384
+ }
1385
+ cleanRun.active = true;
1386
+ cleanRun.activeToolCallIds.clear();
1387
+ cleanRun.activeToolCallId = undefined;
1388
+ cleanRun.activeToolName = undefined;
1389
+ cleanRun.activity = "thinking...";
1390
+ });
1391
+ pi.on("tool_execution_start", (event) => {
1392
+ if (!supportedTools.has(event.toolName)) return;
1393
+ if (!cleanRun.currentToolCallIds.includes(event.toolCallId)) {
1394
+ cleanRun.currentToolCallIds.push(event.toolCallId);
1395
+ }
1396
+ cleanRun.activeToolCallIds.add(event.toolCallId);
1397
+ cleanToolNames.set(event.toolCallId, toolDisplayName(event.toolName));
1398
+ setCleanGroupMembers(event.toolCallId, cleanRun.currentToolCallIds.slice());
1399
+ cleanRun.active = true;
1400
+ cleanRun.activeToolCallId = event.toolCallId;
1401
+ beginToolActivity(event.toolCallId, toolDisplayName(event.toolName), true);
1402
+ });
1403
+ pi.on("tool_execution_end", (event) => {
1404
+ if (!supportedTools.has(event.toolName)) return;
1405
+ const activityName = cleanRun.activeToolCallId === event.toolCallId
1406
+ ? cleanRun.activeToolName ?? toolDisplayName(event.toolName)
1407
+ : toolDisplayName(event.toolName);
1408
+ // Keep the tool activity visible until at least one second after start;
1409
+ // this only delays the status transition, never the tool result itself.
1410
+ holdToolActivity(event.toolCallId, activityName);
1411
+ cleanRun.count++;
1412
+ if (event.isError) cleanRun.failed++;
1413
+ cleanRun.lastCompletedToolCallId = event.toolCallId;
1414
+ cleanRun.activeToolCallIds.delete(event.toolCallId);
1415
+ if (cleanRun.activeToolCallId === event.toolCallId) {
1416
+ cleanRun.activeToolCallId = [...cleanRun.currentToolCallIds]
1417
+ .reverse()
1418
+ .find((toolCallId) => cleanRun.activeToolCallIds.has(toolCallId));
1419
+ cleanRun.activeToolName = cleanRun.activeToolCallId
1420
+ ? cleanToolNames.get(cleanRun.activeToolCallId)
1421
+ : undefined;
1422
+ cleanRun.activity = cleanRun.activeToolName ?? "thinking...";
1423
+ }
1424
+ const visibleSummaryToolCallId = cleanRun.activeToolCallId ?? cleanRun.lastCompletedToolCallId;
1425
+ setCleanGroupMembers(visibleSummaryToolCallId, cleanRun.currentToolCallIds.slice());
1426
+ });
1427
+ pi.on("agent_end", () => {
1428
+ // No summary is appended here: this event may be followed by an automatic
1429
+ // retry or compaction. The live row remains available until settled.
1430
+ clearPendingToolActivities();
1431
+ cleanRun.activeToolCallIds.clear();
1432
+ cleanRun.activeToolCallId = undefined;
1433
+ cleanRun.activeToolName = undefined;
1434
+ cleanRun.activity = "thinking...";
1435
+ });
1436
+ pi.on("agent_settled", () => {
1437
+ if (cleanRun.settled) return;
1438
+
1439
+ clearPendingToolActivities();
1440
+ // Finalize the last group after retries/compaction have definitely ended.
1441
+ finishCleanGroup("done");
1442
+ for (const group of cleanRun.groups) {
1443
+ group.activity = "done";
1444
+ settledSummaries.set(group.lastToolCallId, {
1445
+ count: group.count,
1446
+ failed: group.failed,
1447
+ activity: activityValueForHold(group.lastToolCallId, "done"),
1448
+ });
1449
+ }
1450
+ cleanRun.active = false;
1451
+ cleanRun.activeToolCallIds.clear();
1452
+ cleanRun.activeToolCallId = undefined;
1453
+ cleanRun.activeToolName = undefined;
1454
+ cleanRun.activity = "done";
1455
+ cleanRun.settled = true;
1456
+
1457
+ const groups = cleanRun.groups.slice();
1458
+ if (renderMode !== "clean" || groups.length === 0) return;
1459
+
1460
+ const count = groups.reduce((total, group) => total + group.count, 0);
1461
+ const failed = groups.reduce((total, group) => total + group.failed, 0);
1462
+ const lastToolCallId = groups[groups.length - 1]?.lastToolCallId;
1463
+ pi.appendEntry<ToolSummaryData>("pretty-tui-tool-summary", {
1464
+ count,
1465
+ failed,
1466
+ lastToolCallId,
1467
+ groups: groups.map(({ count, failed, lastToolCallId, toolCallIds }) => ({
1468
+ count,
1469
+ failed,
1470
+ lastToolCallId,
1471
+ toolCallIds,
1472
+ })),
1473
+ });
1474
+ });
1475
+
269
1476
  const read = createReadTool(cwd);
270
1477
  pi.registerTool({
271
1478
  ...read,
272
1479
  renderShell: "self",
273
1480
  renderCall(args: any, theme: any, context: any) {
1481
+ if (hideCleanTool(context.toolCallId, context.expanded, context.executionStarted)) return cleanToolCall(theme, "Read", context.toolCallId);
274
1482
  const range = args.offset || args.limit
275
1483
  ? ` · lines ${args.offset ?? 1}${args.limit ? `–${(args.offset ?? 1) + args.limit - 1}` : "+"}`
276
1484
  : "";
277
1485
  return call(theme, "Read", `${args.path}${range}`, context.state);
278
1486
  },
279
1487
  renderResult(toolResult: any, options: any, theme: any, context: any) {
280
- if (options.isPartial) return partialResult(context, theme, "Reading…");
281
1488
  const output = textContent(toolResult);
1489
+ if (hideCleanTool(context.toolCallId, options.expanded, context.executionStarted)) return hiddenToolResult(context, options, output);
1490
+ if (options.isPartial) return partialResult(context, theme, "Reading…");
282
1491
  const image = toolResult.content?.find((item: any) => item.type === "image");
283
1492
  const failed = completeStatus(context, output);
284
1493
  if (image) return result(theme, "Read image", "", false, failed);
@@ -299,11 +1508,28 @@ export default function prettyTui(pi: ExtensionAPI) {
299
1508
  ...bash,
300
1509
  renderShell: "self",
301
1510
  renderCall(args: any, theme: any, context: any) {
1511
+ if (hideCleanTool(context.toolCallId, context.expanded, context.executionStarted)) return cleanToolCall(theme, "Bash", context.toolCallId);
302
1512
  const command = typeof args.command === "string" ? args.command : "";
1513
+ if (useCompactToolView(context.toolCallId, context.expanded)) {
1514
+ const commandLines = command.split(/\r\n|\r|\n/);
1515
+ const firstLine = commandLines[0] ?? "";
1516
+ const omitted = commandLines.length - 1;
1517
+ const detail = omitted > 0
1518
+ ? `${firstLine} … (${omitted} more ${omitted === 1 ? "line" : "lines"})`
1519
+ : firstLine;
1520
+ return call(theme, "Bash", detail, context.state);
1521
+ }
303
1522
  return call(theme, "Bash", command, context.state);
304
1523
  },
305
1524
  renderResult(toolResult: any, options: any, theme: any, context: any) {
306
1525
  const output = textContent(toolResult);
1526
+ if (hideCleanTool(context.toolCallId, options.expanded, context.executionStarted)) return hiddenToolResult(context, options, output);
1527
+ if (useCompactToolView(context.toolCallId, options.expanded)) {
1528
+ if (options.isPartial) return partialResult(context, theme, "Running…");
1529
+ const failed = completeStatus(context, output);
1530
+ return result(theme, failed ? "Command failed" : "Done", "", false, failed);
1531
+ }
1532
+
307
1533
  if (options.isPartial) {
308
1534
  return bashResult(context, theme, "Running…", output, options.expanded, "running");
309
1535
  }
@@ -332,12 +1558,14 @@ export default function prettyTui(pi: ExtensionAPI) {
332
1558
  ...edit,
333
1559
  renderShell: "self",
334
1560
  renderCall(args: any, theme: any, context: any) {
1561
+ if (hideCleanTool(context.toolCallId, context.expanded, context.executionStarted)) return cleanToolCall(theme, "Edit", context.toolCallId);
335
1562
  const count = Array.isArray(args.edits) ? ` · ${args.edits.length} changes` : "";
336
1563
  return call(theme, "Edit", `${args.path}${count}`, context.state);
337
1564
  },
338
1565
  renderResult(toolResult: any, options: any, theme: any, context: any) {
339
- if (options.isPartial) return partialResult(context, theme, "Editing…");
340
1566
  const output = textContent(toolResult);
1567
+ if (hideCleanTool(context.toolCallId, options.expanded, context.executionStarted)) return hiddenToolResult(context, options, output);
1568
+ if (options.isPartial) return partialResult(context, theme, "Editing…");
341
1569
  const failed = completeStatus(context, output);
342
1570
  const diff = toolResult.details?.diff ?? "";
343
1571
  const additions = diff.split("\n").filter((line: string) => line.startsWith("+") && !line.startsWith("+++")).length;
@@ -371,12 +1599,21 @@ export default function prettyTui(pi: ExtensionAPI) {
371
1599
  ...write,
372
1600
  renderShell: "self",
373
1601
  renderCall(args: any, theme: any, context: any) {
1602
+ if (hideCleanTool(context.toolCallId, context.expanded, context.executionStarted)) return cleanToolCall(theme, "Write", context.toolCallId);
374
1603
  const content = typeof args.content === "string" ? args.content : "";
375
- return writeCall(theme, String(args.path ?? ""), content, context.expanded, context.state);
1604
+ const path = String(args.path ?? "");
1605
+ if (useCompactToolView(context.toolCallId, context.expanded)) {
1606
+ const lines = content.replace(/\t/g, " ").split("\n");
1607
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
1608
+ const total = lines.length;
1609
+ return call(theme, "Write", `${path} · ${total} ${total === 1 ? "line" : "lines"}`, context.state);
1610
+ }
1611
+ return writeCall(theme, path, content, context.expanded, context.state);
376
1612
  },
377
1613
  renderResult(toolResult: any, options: any, theme: any, context: any) {
378
- if (options.isPartial) return partialResult(context, theme, "Writing…");
379
1614
  const output = textContent(toolResult);
1615
+ if (hideCleanTool(context.toolCallId, options.expanded, context.executionStarted)) return hiddenToolResult(context, options, output);
1616
+ if (options.isPartial) return partialResult(context, theme, "Writing…");
380
1617
  const failed = completeStatus(context, output);
381
1618
  return result(
382
1619
  theme,
@@ -393,13 +1630,15 @@ export default function prettyTui(pi: ExtensionAPI) {
393
1630
  ...grep,
394
1631
  renderShell: "self",
395
1632
  renderCall(args: any, theme: any, context: any) {
1633
+ if (hideCleanTool(context.toolCallId, context.expanded, context.executionStarted)) return cleanToolCall(theme, "Grep", context.toolCallId);
396
1634
  const where = args.path ? ` · ${args.path}` : "";
397
1635
  const glob = args.glob ? ` · ${args.glob}` : "";
398
1636
  return call(theme, "Grep", `${args.pattern}${where}${glob}`, context.state);
399
1637
  },
400
1638
  renderResult(toolResult: any, options: any, theme: any, context: any) {
401
- if (options.isPartial) return partialResult(context, theme, "Searching…");
402
1639
  const output = textContent(toolResult);
1640
+ if (hideCleanTool(context.toolCallId, options.expanded, context.executionStarted)) return hiddenToolResult(context, options, output);
1641
+ if (options.isPartial) return partialResult(context, theme, "Searching…");
403
1642
  const failed = completeStatus(context, output);
404
1643
  const matches = nonEmptyLines(output);
405
1644
  return result(theme, failed ? output.split("\n")[0] : `Found ${matches} matches`, output, options.expanded, failed);
@@ -411,11 +1650,13 @@ export default function prettyTui(pi: ExtensionAPI) {
411
1650
  ...find,
412
1651
  renderShell: "self",
413
1652
  renderCall(args: any, theme: any, context: any) {
1653
+ if (hideCleanTool(context.toolCallId, context.expanded, context.executionStarted)) return cleanToolCall(theme, "Find", context.toolCallId);
414
1654
  return call(theme, "Find", `${args.pattern}${args.path ? ` · ${args.path}` : ""}`, context.state);
415
1655
  },
416
1656
  renderResult(toolResult: any, options: any, theme: any, context: any) {
417
- if (options.isPartial) return partialResult(context, theme, "Searching…");
418
1657
  const output = textContent(toolResult);
1658
+ if (hideCleanTool(context.toolCallId, options.expanded, context.executionStarted)) return hiddenToolResult(context, options, output);
1659
+ if (options.isPartial) return partialResult(context, theme, "Searching…");
419
1660
  const failed = completeStatus(context, output);
420
1661
  const matches = nonEmptyLines(output);
421
1662
  return result(theme, failed ? output.split("\n")[0] : `Found ${matches} paths`, output, options.expanded, failed);
@@ -427,11 +1668,13 @@ export default function prettyTui(pi: ExtensionAPI) {
427
1668
  ...ls,
428
1669
  renderShell: "self",
429
1670
  renderCall(args: any, theme: any, context: any) {
1671
+ if (hideCleanTool(context.toolCallId, context.expanded, context.executionStarted)) return cleanToolCall(theme, "List", context.toolCallId);
430
1672
  return call(theme, "List", args.path ?? ".", context.state);
431
1673
  },
432
1674
  renderResult(toolResult: any, options: any, theme: any, context: any) {
433
- if (options.isPartial) return partialResult(context, theme, "Listing…");
434
1675
  const output = textContent(toolResult);
1676
+ if (hideCleanTool(context.toolCallId, options.expanded, context.executionStarted)) return hiddenToolResult(context, options, output);
1677
+ if (options.isPartial) return partialResult(context, theme, "Listing…");
435
1678
  const failed = completeStatus(context, output);
436
1679
  const entries = nonEmptyLines(output);
437
1680
  return result(theme, failed ? output.split("\n")[0] : `Listed ${entries} entries`, output, options.expanded, failed);