@arhen/pi-senja 1.2.7 → 1.4.0

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.
package/README.md CHANGED
@@ -9,8 +9,13 @@ Forked from [pi-haiku](https://github.com/nnocte/pi-haiku) **0.2.0** by **nocte*
9
9
  - **Gruvbox Material dark/medium/material** — exact colors captured from Neovim, matching the Ghostty Senja theme. Background `#282828`, foreground `#d4be98`, orange accent `#e78a4e`. All 56 Pi roles and HTML export backgrounds use palette variables.
10
10
  - **A header** with shortcuts grouped by control, models, view, and input.
11
11
  - **A footer** with location, Git branch, session name, provider, model, thinking effort (including `max`), context bar, token usage, latest cache-hit rate, cost, OAuth subscription marker, and extension statuses.
12
- - **State-tinted tool panels** — running tools use amber `#4f422e`, successful tools the warm grey `#32302f`, failed tools maroon `#4c3432`. Your own messages sit one step brighter at `#45403d`, so a user turn, a finished tool block and the `#282828` page all read apart.
13
- - **Quiet tool text** — tool titles and output both use the foreground beige (`fg0`) rather than loud accents, keeping panels calm against their tint.
12
+ - **Flat tool output** — image captions, command results, and errors sit on the terminal background. Only source and diff lines get a quiet editor surface (Senja warm grey `#32302f`). Status dots and failure labels carry the state; user messages retain their own background.
13
+ - **Grouped tool calls** — a single call stays on one line, e.g. `• Write example.ts ▸`. Codemode summaries can use the full pane width; all other tool summaries use at most 60% of the pane. Long titles truncate on one line, leaving room for the status and arrow. For runs longer than ten, the heading counts every call and failure, but only the latest ten calls are listed. Click **Show all** to reveal earlier calls above those ten, or **Show less** to fold history again. The control briefly brightens without scrolling through intermediate layouts (`REDUCE_MOTION=1` disables the feedback). Image reads keep Pi’s native inline image or text fallback, without a code gutter. Two or more consecutive calls to the same tool share a fixed heading, e.g. `• Ran codemode ×4 · 1 failed`. Each call occupies one tree line: `├─ script ▸` or `└─ script · failed ▸`. Click the line to open its indented native panel. The muted trailing icon changes to `▾`. Calls start collapsed by default. While running, the label has a subtle moving highlight without changing the row height (`REDUCE_MOTION=1` or `NO_COLOR=1` disables it). Click a call to open or close it at any time; partial output, success, and failure update its status without changing your choice. Expanded panels omit repeated titles and number script or file source lines (read offsets and native diff numbering are preserved). A text read opens to five wrapped lines; click its “more lines” hint to see the full read result. Image reads are not clipped. Opening a codemode row shows Pi’s native preview: at most five wrapped output lines. Click the result to see it in full; click it again to return to the preview. The row arrow closes the panel. Numbered source has a shaded row of padding above and below. Nested calls, output, and timing align with the script text, without an inner border. Pi’s tool expansion shortcut (default `Ctrl+O`) toggles all calls. Collapsed thinking is marked with a single-cell outline bulb (Nerd Font) beside `Thinking…` while streaming and `Thought` afterward. Inside a tool group, the bulb sits after the tree guide. Click the label to replace it with Pi’s thinking text without an icon, or the text to fold it back. A thinking-only turn between matching tools stays above the next call’s tree branch; elsewhere it stays in transcript order. Final replies have no marker. Parallel calls share the row once. Thinking follows its call through **Show all / Show less** and does not count toward the ten calls. A different tool or assistant prose starts a new group.
14
+ - **Shared transcript renderer** — compatible subagent views use the same renderer as the leader when Senja is enabled. Other Pi extensions can synchronously discover it via `pi.events.emit("pi:transcript-renderer", provider => { … })`. Mount with `provider.mount(chatContainer, tui, theme, starts?, cancelled?)`, render and send clicks to its `root`, and call `dispose()` when the view closes. The optional maps use tool call IDs and monotonic milliseconds (starts or frozen durations). With no provider, render the native container. This is opt-in for custom views; non-transcript panels are unchanged.
15
+ - **Tool activity** — An unnamed call shows `preparing…`. As soon as Pi names it, the row shows `running`, even while the model writes the script. The timer starts at the first named call update and keeps counting through execution (`running 1m 30s`). Confirmed interruptions freeze that total (`cancelled · 8s`) without counting as failures.
16
+ - **Codemode intent titles** — Senja asks the agent to put a short plan in a leading `// @title: Find the goal notice renderer` comment (after an optional `// @options:` line). The row displays that plan; expand it for the actual script and results. Untitled calls keep their script preview.
17
+ - **Goal notices** — a `goal-ui` status starts as one clickable row. Open it for the original notice, including its objective, usage and commands.
18
+ - **Quiet tool text** — action labels such as `Ran` use muted teal (`#7daea3`) to distinguish tools from assistant prose. Tool names following a verb and tool output use the foreground beige (`fg0`) rather than loud accents, keeping panels calm against their tint.
14
19
  - **Editor-style code colors** — pink keywords, olive strings, aqua function names, amber types, warm beige identifiers and punctuation, readable muted comments. Applies to code in tool calls/results and Markdown code blocks through Pi's syntax roles.
15
20
  - **A live timer** while Pi works, plus elapsed-time completion message and notification. Preserves the active mode label and colour from `@arhen/pi-add-mode` (`review is working... 8s`).
16
21
  - **Fast / Ultrafast mode** — `/fast on|off` and `/ultrafast on|off` set a paid speed preference per OpenAI provider and model. With `openai-codex` and ChatGPT sign-in, Senja checks the account catalog and retries a saved tier after a temporary lookup failure on the next turn or model selection. With the public `openai` Responses provider, Senja checks known model support and OpenAI handles account eligibility. The footer shows the selected preference as `fast` or `ultrafast`. Preferences persist under `<agent-dir>/fast-mode/`. An explicit `samplingParams.service_tier` takes precedence.
@@ -28,7 +33,7 @@ Disable/remove `pi-haiku` or other header/footer replacements to avoid competing
28
33
 
29
34
  ## Toggle
30
35
 
31
- Type `/senja` to turn the header and footer on or off. The theme stays selected. Terminal session startup selects `senja`; selecting another theme afterward still works.
36
+ Type `/senja` to turn the header, footer, and tool grouping on or off. The theme stays selected. Terminal session startup selects `senja`; selecting another theme afterward still works.
32
37
 
33
38
  ## Development
34
39
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arhen/pi-senja",
3
- "version": "1.2.7",
3
+ "version": "1.4.0",
4
4
  "description": "Senja Gruvbox Material theme with Haiku's structured header, footer, and live timer for Pi.",
5
5
  "license": "MIT",
6
6
  "author": "arhen",
package/src/index.ts CHANGED
@@ -21,6 +21,8 @@ import type { ExtensionAPI, ExtensionContext, Theme, ThemeColor } from "@earendi
21
21
  import { VERSION } from "@earendil-works/pi-coding-agent";
22
22
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
23
23
 
24
+ import { createTranscriptView, formatDuration, installToolGroups } from "./tool-groups.ts";
25
+
24
26
  // ── Visual primitives ────────────────────────────────────────────────────────
25
27
 
26
28
  const GLYPH = {
@@ -129,20 +131,6 @@ function fmtTokens(n: number): string {
129
131
  return `${Math.round(n / 1_000_000)}M`;
130
132
  }
131
133
 
132
- /** Format milliseconds as a human-readable duration. */
133
- function formatDuration(ms: number): string {
134
- const totalSeconds = Math.max(0, Math.floor(ms / 1000));
135
- if (totalSeconds < 60) return `${totalSeconds}s`;
136
-
137
- const s = totalSeconds % 60;
138
- const totalMinutes = Math.floor(totalSeconds / 60);
139
- if (totalMinutes < 60) return `${totalMinutes}m ${s}s`;
140
-
141
- const m = totalMinutes % 60;
142
- const h = Math.floor(totalMinutes / 60);
143
- return `${h}h ${m}m ${s}s`;
144
- }
145
-
146
134
  /** Right-align two text blocks, truncating left if they don't both fit. */
147
135
  function alignRight(left: string, right: string, width: number, theme: Theme): string {
148
136
  const rightW = visibleWidth(right);
@@ -332,13 +320,44 @@ function renderHeader(theme: Theme, width: number): string[] {
332
320
  return lines.map((line) => truncateToWidth(line, width, ellipsis));
333
321
  }
334
322
 
335
- function applyHeader(ctx: ExtensionContext): void {
336
- ctx.ui.setHeader((_tui, theme) => ({
337
- render(width: number): string[] {
338
- return renderHeader(theme, width);
339
- },
340
- invalidate() {},
341
- }));
323
+ function readUsage(ctx: ExtensionContext) {
324
+ let totalInput = 0;
325
+ let totalOutput = 0;
326
+ let totalCost = 0;
327
+ let latestCacheHitRate: number | undefined;
328
+
329
+ for (const entry of ctx.sessionManager.getEntries()) {
330
+ if (entry.type === "message" && entry.message.role === "assistant") {
331
+ const m = entry.message;
332
+ totalInput += m.usage.input;
333
+ totalOutput += m.usage.output;
334
+ totalCost += m.usage.cost.total;
335
+
336
+ const promptTokens = m.usage.input + m.usage.cacheRead + m.usage.cacheWrite;
337
+ latestCacheHitRate = promptTokens > 0 ? (m.usage.cacheRead / promptTokens) * 100 : undefined;
338
+ }
339
+ }
340
+ return { totalInput, totalOutput, totalCost, latestCacheHitRate, contextUsage: ctx.getContextUsage() };
341
+ }
342
+
343
+ function applyHeader(
344
+ ctx: ExtensionContext,
345
+ starts: ReadonlyMap<string, number>,
346
+ cancelled: ReadonlyMap<string, number | undefined>,
347
+ ): void {
348
+ ctx.ui.setHeader((tui, theme) => {
349
+ let cached: { width: number; lines: string[] } | undefined;
350
+ return {
351
+ ...installToolGroups(tui, theme, starts, cancelled),
352
+ render(width: number) {
353
+ if (cached?.width !== width) cached = { width, lines: renderHeader(theme, width) };
354
+ return cached.lines;
355
+ },
356
+ invalidate() {
357
+ cached = undefined;
358
+ },
359
+ };
360
+ });
342
361
  }
343
362
 
344
363
  function restoreHeader(ctx: ExtensionContext): void {
@@ -363,6 +382,37 @@ export default function (pi: ExtensionAPI) {
363
382
  let renderHandle: RenderHandle | undefined;
364
383
  let disposeFooter: (() => void) | undefined;
365
384
  let enabled = true;
385
+ const starts = new Map<string, number>();
386
+ const cancelled = new Map<string, number | undefined>();
387
+ function startCall(id: string) {
388
+ if (!starts.has(id)) starts.set(id, performance.now());
389
+ }
390
+ function cancelCall(id: string) {
391
+ if (cancelled.has(id)) return;
392
+ const start = starts.get(id);
393
+ cancelled.set(id, start === undefined ? undefined : performance.now() - start);
394
+ starts.delete(id);
395
+ }
396
+ pi.on("message_update", ({ assistantMessageEvent: update }, ctx) => {
397
+ if (ctx.mode !== "tui" || !("contentIndex" in update)) return;
398
+ const block = update.partial.content[update.contentIndex];
399
+ if (block?.type === "toolCall" && block.name && block.id) startCall(block.id);
400
+ });
401
+ pi.on("message_end", ({ message }, ctx) => {
402
+ if (ctx.mode !== "tui" || message.role !== "assistant" || message.stopReason !== "aborted") return;
403
+ for (const block of message.content) {
404
+ if (block.type === "toolCall") cancelCall(block.id);
405
+ }
406
+ });
407
+ pi.on("tool_execution_start", (event, ctx) => {
408
+ if (ctx.mode === "tui" && !event.parentToolCallId) startCall(event.toolCallId);
409
+ });
410
+ pi.on("tool_execution_end", (event, ctx) => {
411
+ if (!event.parentToolCallId && event.isError && ctx.signal?.aborted && starts.has(event.toolCallId)) {
412
+ cancelCall(event.toolCallId);
413
+ }
414
+ starts.delete(event.toolCallId);
415
+ });
366
416
  let workingSince: number | undefined;
367
417
  let workingTimer: ReturnType<typeof setInterval> | undefined;
368
418
  let lastDoneIn: number | undefined;
@@ -370,6 +420,17 @@ export default function (pi: ExtensionAPI) {
370
420
  const speedTiers = new Map<string, SpeedTier | null>();
371
421
  const unverifiedTiers = new Set<string>();
372
422
 
423
+ const guide =
424
+ "Start each codemode script with a // @title: comment describing its planned action in a short verb phrase (e.g. // @title: Find the goal notice renderer). If using // @options:, put the title on the next line.";
425
+ const unsubscribeTranscript = pi.events.on("pi:transcript-renderer", (accept) => {
426
+ if (enabled && typeof accept === "function") accept({ mount: createTranscriptView, codemodeGuide: guide });
427
+ });
428
+ pi.on("before_agent_start", (event, ctx) => {
429
+ if (!enabled || ctx.mode !== "tui" || !event.systemPromptOptions?.selectedTools.includes("codemode")) return;
430
+ const { promptGuidelines } = event.systemPromptOptions;
431
+ if (!promptGuidelines.includes(guide)) promptGuidelines.push(guide);
432
+ });
433
+
373
434
  const unsubscribeMode = pi.events.on("pi-mode:working-message", (message) => {
374
435
  if (message === undefined || typeof message === "string") modeWorkingMessage = message || undefined;
375
436
  });
@@ -473,11 +534,15 @@ export default function (pi: ExtensionAPI) {
473
534
 
474
535
  if (ctx.mode !== "tui") return;
475
536
 
537
+ let lastMessage: string | undefined;
476
538
  const tick = () => {
477
539
  if (workingSince === undefined) return;
478
540
  const elapsed = formatDuration(Date.now() - workingSince);
541
+ const message = `${modeWorkingMessage ?? "Working…"} ${elapsed}`;
542
+ if (message === lastMessage) return;
479
543
  try {
480
- ctx.ui.setWorkingMessage(`${modeWorkingMessage ?? "Working…"} ${elapsed}`);
544
+ ctx.ui.setWorkingMessage(message);
545
+ lastMessage = message;
481
546
  } catch {
482
547
  // Ignore if the UI is already torn down.
483
548
  }
@@ -497,6 +562,7 @@ export default function (pi: ExtensionAPI) {
497
562
 
498
563
  // Report final duration and clean up timers.
499
564
  pi.on("agent_end", (_event, ctx) => {
565
+ starts.clear();
500
566
  clearWorkingTimers();
501
567
 
502
568
  if (workingSince !== undefined) {
@@ -537,34 +603,25 @@ export default function (pi: ExtensionAPI) {
537
603
  }
538
604
  };
539
605
  disposeFooter = dispose;
606
+ let cached: { key: string; model: ExtensionContext["model"]; usage: ReturnType<typeof readUsage> } | undefined;
540
607
 
541
608
  return {
542
609
  dispose,
543
610
  invalidate() {
544
- // Stateless render; nothing to cache.
611
+ cached = undefined;
545
612
  },
546
613
  render(width: number): string[] {
547
614
  if (width <= 0) return [];
548
- // ── Aggregate usage across every assistant message ───────────────
549
- let totalInput = 0;
550
- let totalOutput = 0;
551
- let totalCost = 0;
552
- let latestCacheHitRate: number | undefined;
553
-
554
- for (const entry of ctx.sessionManager.getEntries()) {
555
- if (entry.type === "message" && entry.message.role === "assistant") {
556
- const m = entry.message as AssistantMessage;
557
- totalInput += m.usage.input;
558
- totalOutput += m.usage.output;
559
- totalCost += m.usage.cost.total;
560
-
561
- const promptTokens = m.usage.input + m.usage.cacheRead + m.usage.cacheWrite;
562
- latestCacheHitRate = promptTokens > 0 ? (m.usage.cacheRead / promptTokens) * 100 : undefined;
563
- }
615
+ const manager = ctx.sessionManager;
616
+ // Pi's session is append-only; older hosts without the cheap entry count use the uncached path.
617
+ const key =
618
+ "getEntryCount" in manager && typeof manager.getEntryCount === "function"
619
+ ? `${manager.getSessionId()}:${manager.getLeafId()}:${manager.getEntryCount()}`
620
+ : "";
621
+ if (!cached || !key || cached.key !== key || cached.model !== ctx.model) {
622
+ cached = { key, model: ctx.model, usage: readUsage(ctx) };
564
623
  }
565
-
566
- // ── Context usage for the active model ───────────────────────────
567
- const contextUsage = ctx.getContextUsage();
624
+ const { totalInput, totalOutput, totalCost, latestCacheHitRate, contextUsage } = cached.usage;
568
625
  const contextWindow = contextUsage?.contextWindow ?? ctx.model?.contextWindow ?? 0;
569
626
  const contextTokens = contextUsage?.tokens ?? null;
570
627
  const contextPercent = contextUsage?.percent ?? null;
@@ -590,13 +647,13 @@ export default function (pi: ExtensionAPI) {
590
647
  locationBlock += ` ${theme.fg("dim", "session")} ${theme.fg("text", sessionName)}`;
591
648
  }
592
649
 
593
- let modelBlock = `${theme.fg(providerColor(provider), String(provider))} ${theme.fg("dim", GLYPH.square)} ${theme.fg("text", modelId)}`;
650
+ let modelBlock = `${theme.fg(providerColor(provider), provider)} ${theme.fg("dim", GLYPH.square)} ${theme.fg("text", modelId)}`;
594
651
  if (reasoning) {
595
652
  const level = pi.getThinkingLevel();
596
653
  modelBlock += ` ${theme.fg("dim", GLYPH.square)} ${theme.fg(effortColor(level), level)}`;
597
654
  }
598
- const key = speedKey(ctx.model);
599
- const tier = key && speedTiers.get(key);
655
+ const modelKey = speedKey(ctx.model);
656
+ const tier = modelKey && speedTiers.get(modelKey);
600
657
  if (tier) {
601
658
  modelBlock += ` ${theme.fg("dim", GLYPH.square)} ${theme.fg("warning", tier)}`;
602
659
  }
@@ -693,7 +750,7 @@ export default function (pi: ExtensionAPI) {
693
750
 
694
751
  // Toggle command.
695
752
  pi.registerCommand("senja", {
696
- description: "Toggle the Senja header and footer",
753
+ description: "Toggle the Senja header, footer, and tool groups",
697
754
  handler: async (_args, ctx) => {
698
755
  if (ctx.mode !== "tui") {
699
756
  if (ctx.hasUI) ctx.ui.notify("Senja requires terminal UI mode", "info");
@@ -702,7 +759,7 @@ export default function (pi: ExtensionAPI) {
702
759
  enabled = !enabled;
703
760
  if (enabled) {
704
761
  applyFooter(ctx);
705
- applyHeader(ctx);
762
+ applyHeader(ctx, starts, cancelled);
706
763
  ctx.ui.notify("Senja enabled", "info");
707
764
  } else {
708
765
  restoreFooter(ctx);
@@ -787,7 +844,7 @@ export default function (pi: ExtensionAPI) {
787
844
 
788
845
  if (enabled) {
789
846
  applyFooter(ctx);
790
- applyHeader(ctx);
847
+ applyHeader(ctx, starts, cancelled);
791
848
  } else {
792
849
  restoreFooter(ctx);
793
850
  restoreHeader(ctx);
@@ -795,6 +852,9 @@ export default function (pi: ExtensionAPI) {
795
852
  });
796
853
 
797
854
  pi.on("session_shutdown", () => {
855
+ starts.clear();
856
+ cancelled.clear();
857
+ unsubscribeTranscript();
798
858
  unsubscribeMode();
799
859
  modeWorkingMessage = undefined;
800
860
  clearWorkingTimers();
@@ -0,0 +1,710 @@
1
+ import {
2
+ AssistantMessageComponent,
3
+ CustomMessageComponent,
4
+ type Theme,
5
+ ToolExecutionComponent,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import {
8
+ type Component,
9
+ Container,
10
+ foregroundAnsi,
11
+ indexedColor,
12
+ Markdown,
13
+ MouseRegion,
14
+ mixColors,
15
+ rgbColor,
16
+ Spacer,
17
+ sliceByColumn,
18
+ stripTerminalSequences,
19
+ Text,
20
+ type TUI,
21
+ truncateToWidth,
22
+ visibleWidth,
23
+ wrapTextWithAnsi,
24
+ } from "@earendil-works/pi-tui";
25
+
26
+ type ToolRow = Component & {
27
+ toolName: string;
28
+ toolCallId: string;
29
+ args?: Record<string, unknown>;
30
+ isPartial: boolean;
31
+ expanded: boolean;
32
+ outputPad?: number;
33
+ result?: {
34
+ isError: boolean;
35
+ durationMs?: number;
36
+ details?: { diff?: string };
37
+ content?: { type: string; text?: string }[];
38
+ };
39
+ setExpanded(value: boolean): void;
40
+ };
41
+
42
+ function summary(value: unknown): string {
43
+ if (typeof value !== "string") return "";
44
+ return stripTerminalSequences(value.slice(0, 2048))
45
+ .replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]+/gu, " ")
46
+ .replace(/\s+/gu, " ")
47
+ .trim();
48
+ }
49
+
50
+ const graphemes = new Intl.Segmenter();
51
+ const colorSpan = /(\x1b\[38;(?:2;\d+;\d+;\d+|5;\d+)m)([^\x1b]+)/g;
52
+
53
+ function createShimmer(theme: Theme) {
54
+ const ramps = new Map<string, string[]>();
55
+ const target = theme.appearance === "light" ? rgbColor(0, 0, 0) : rgbColor(255, 255, 255);
56
+ return (line: string, frame: number) => {
57
+ const width = visibleWidth(line);
58
+ if (width < 2) return line;
59
+ const center = (frame * 2) % width;
60
+ const radius = Math.min(9, width / 2);
61
+ let column = 0;
62
+ let cursor = 0;
63
+ // Only tint foreground spans. Leave bold, resets, tree guides and unstyled text intact.
64
+ return line.replace(colorSpan, (span, ansi: string, text: string, offset) => {
65
+ column += visibleWidth(line.slice(cursor, offset));
66
+ cursor = offset + span.length;
67
+ let ramp = ramps.get(ansi);
68
+ if (!ramp) {
69
+ const [mode, r, g, b] = ansi.slice(5, -1).split(";").map(Number);
70
+ const base = mode === 5 ? indexedColor(r!) : rgbColor(r!, g!, b!);
71
+ ramp = Array.from({ length: 9 }, (_, i) =>
72
+ i ? foregroundAnsi(mixColors(base, target, i / 24, "srgb"), mode === 5 ? "256color" : "truecolor") : ansi,
73
+ );
74
+ ramps.set(ansi, ramp);
75
+ }
76
+ let result = ansi;
77
+ let previous = 0;
78
+ for (const { segment } of graphemes.segment(text)) {
79
+ const dx = Math.abs(column - center);
80
+ const distance = Math.min(dx, width - dx);
81
+ const level = distance >= radius ? 0 : Math.round(4 * (1 + Math.cos((Math.PI * distance) / radius)));
82
+ if (level !== previous) result += ramp[level];
83
+ result += segment;
84
+ previous = level;
85
+ column += visibleWidth(segment);
86
+ }
87
+ return previous ? result + ansi : result;
88
+ });
89
+ };
90
+ }
91
+
92
+ function describe(tool: ToolRow): [string, string] {
93
+ const a = tool.args ?? {};
94
+ switch (tool.toolName) {
95
+ case "read": {
96
+ const path = summary(a.file_path ?? a.path) || ".";
97
+ if (typeof a.offset !== "number" && typeof a.limit !== "number") return ["Explored", path];
98
+ const start = typeof a.offset === "number" ? a.offset : 1;
99
+ return ["Explored", `${path}:${start}${typeof a.limit === "number" ? `-${start + a.limit - 1}` : ""}`];
100
+ }
101
+ case "ls":
102
+ return ["Explored", summary(a.path) || "."];
103
+ case "find":
104
+ case "grep":
105
+ return ["Searched", summary(a.pattern)];
106
+ case "web_search":
107
+ return ["Searched the web", summary(a.query)];
108
+ case "edit":
109
+ case "write":
110
+ return ["", summary(a.path ?? a.file_path)];
111
+ case "bash":
112
+ return ["Ran", summary(a.command)];
113
+ case "codemode": {
114
+ const code = a.code ?? a.input ?? a.source ?? a.script;
115
+ const title =
116
+ typeof code === "string"
117
+ ? /^(?:\/\/ @options:[^\n]*\n)?\/\/ @title:[ \t]*([^\r\n]+)/.exec(code.slice(0, 2048))
118
+ : undefined;
119
+ return ["Ran", summary(title?.[1]) || summary(code)];
120
+ }
121
+ default:
122
+ return ["Called", summary(a.path ?? a.query)];
123
+ }
124
+ }
125
+
126
+ function sourceText(tool: ToolRow) {
127
+ const args = tool.args ?? {};
128
+ let raw: unknown;
129
+ let first = 1;
130
+ if (tool.toolName === "codemode") raw = args.code;
131
+ else if (tool.toolName === "write") raw = args.content;
132
+ else if (tool.toolName === "read" && !tool.result?.isError) {
133
+ raw = tool.result?.content?.find((block) => block.type === "text")?.text;
134
+ if (typeof args.offset === "number" && Number.isSafeInteger(args.offset)) first = Math.max(1, args.offset);
135
+ }
136
+ if (typeof raw !== "string" || !raw) return;
137
+ return { raw, first };
138
+ }
139
+
140
+ function indentedDetails(
141
+ tool: ToolRow,
142
+ theme: Theme,
143
+ previews: WeakSet<Component>,
144
+ tui: TUI,
145
+ ): Component & { guide: string; revision: number } {
146
+ let inset = 0;
147
+ let top = 0;
148
+ let padTop = 0;
149
+ let editorRows = 0;
150
+ let padBottom = 0;
151
+ let hiddenReadRows = 0;
152
+ let height = 0;
153
+ let contentWidth = 0;
154
+ let gutter = 0;
155
+ let outputGutter = 0;
156
+ let codeEnd = 0;
157
+ let previousSource: string | undefined;
158
+ let logicalLines: string[] = [];
159
+ let cached:
160
+ | { lines: readonly string[]; width: number; guide: string; revision: number; first?: number; body: string[] }
161
+ | undefined;
162
+ const blank = /^(?:\s|\x1b\[[\d;:]*m)*$/;
163
+ return {
164
+ guide: "",
165
+ revision: 0,
166
+ invalidate: () => tool.invalidate(),
167
+ render(width) {
168
+ const image = tool.result?.content?.some((block) => block.type === "image");
169
+ const source = image ? undefined : sourceText(tool);
170
+ if (source?.raw !== previousSource) {
171
+ previousSource = source?.raw;
172
+ logicalLines = previousSource?.replace(/\r/g, "").replace(/\t/g, " ").trimEnd().split("\n") ?? [];
173
+ cached = undefined;
174
+ }
175
+ const digits = source ? Math.max(2, String(source.first + logicalLines.length - 1).length) : 0;
176
+ gutter = digits && width >= 16 ? digits + 2 : 0;
177
+ const innerPad = image ? 0 : gutter ? 2 : (tool.outputPad ?? 1);
178
+ inset = Math.max(0, visibleWidth(this.guide) - innerPad);
179
+ const guide = sliceByColumn(this.guide, 0, inset);
180
+ contentWidth = Math.max(1, width - inset - gutter - (width >= 16 ? 2 : 0));
181
+ const lines = tool.render(contentWidth);
182
+ if (
183
+ cached?.width === width &&
184
+ cached.guide === this.guide &&
185
+ cached.revision === this.revision &&
186
+ cached.first === source?.first &&
187
+ cached.lines.length === lines.length &&
188
+ lines.every((line, i) => line === cached!.lines[i])
189
+ ) {
190
+ return cached.body;
191
+ }
192
+ height = lines.length;
193
+ top = 0;
194
+ while (top < height && blank.test(lines[top]!)) top++;
195
+ const plain = (line: string) => stripTerminalSequences(line).trim();
196
+ const innerWidth = Math.max(1, contentWidth - 2 * (tool.outputPad ?? 1));
197
+ const [, subject] = describe(tool);
198
+ const titles = [`${tool.toolName} ${subject}`, tool.toolName];
199
+ if (process.env.HOME && subject.startsWith(`${process.env.HOME}/`)) {
200
+ titles.unshift(`${tool.toolName} ~${subject.slice(process.env.HOME.length)}`);
201
+ }
202
+ const headerStart = top;
203
+ if (tool.toolName === "bash" && visibleWidth(subject) <= innerWidth - 2) titles.unshift(`$ ${subject}`);
204
+ for (const title of titles) {
205
+ const parts = wrapTextWithAnsi(title, innerWidth);
206
+ if (!parts.every((part, i) => top + i < height && plain(lines[top + i]!) === part.trim())) continue;
207
+ top += parts.length;
208
+ while (!image && top < height && blank.test(lines[top]!)) top++;
209
+ break;
210
+ }
211
+ let end = height;
212
+ while (!image && end > top && blank.test(lines[end - 1]!)) end--;
213
+ hiddenReadRows = tool.toolName === "read" && source ? Math.max(0, end - top - 5) : 0;
214
+ if (end === top) return [];
215
+ const clipped = previews.has(tool) ? hiddenReadRows : 0;
216
+ const displayEnd = end - clipped;
217
+ // Keep non-redundant renderer metadata (ranges, limits, invalid arguments).
218
+ const firstLine = stripTerminalSequences(lines[top]!);
219
+ const redundant = top === headerStart && firstLine.trimStart().startsWith(`${tool.toolName} `);
220
+ const labelEnd = redundant
221
+ ? firstLine.length - firstLine.trimStart().length + visibleWidth(tool.toolName) + 1
222
+ : 0;
223
+ const numbers = new Map<number, string>();
224
+ codeEnd = top;
225
+ if (source) {
226
+ let row = top;
227
+ let started = false;
228
+ for (const [i, logical] of logicalLines.entries()) {
229
+ if (row >= displayEnd) break;
230
+ if (!started && !logical.trim()) continue;
231
+ const parts = wrapTextWithAnsi(logical, innerWidth);
232
+ if (!parts.every((part, j) => row + j < end && plain(lines[row + j]!) === part.trim())) break;
233
+ numbers.set(row, String(source.first + i));
234
+ row += parts.length;
235
+ codeEnd = Math.min(row, displayEnd);
236
+ started = true;
237
+ }
238
+ }
239
+ outputGutter =
240
+ tool.toolName === "codemode" && codeEnd > top ? gutter : Math.max(0, innerPad - (tool.outputPad ?? 1));
241
+ const resultIndent = " ".repeat(outputGutter);
242
+ const fills = (["toolPendingBg", "toolSuccessBg", "toolErrorBg"] as const).map((role) => theme.getBgAnsi(role));
243
+ const diff =
244
+ tool.toolName === "edit" &&
245
+ !tool.result?.isError &&
246
+ !!(tool.result?.details?.diff || Reflect.get(tool, "rendererState")?.callComponent?.preview?.diff);
247
+ const surface = (text: string) => theme.bg("toolSuccessBg", text.replace(/\x1b\[(?:0?|49)m/g, "$&" + fills[1]));
248
+ const body = lines.slice(top, displayEnd).map((line, i) => {
249
+ // Graphics sequences and their reserved rows belong to Pi's image renderer.
250
+ if (image && (!line.trim() || line.includes("\x1b_G") || line.includes("\x1b]1337;File="))) return guide + line;
251
+ let content = i === 0 && labelEnd ? sliceByColumn(line, labelEnd, contentWidth) : line;
252
+ for (const fill of fills) if (fill) content = content.replaceAll(fill, "");
253
+ const code = top + i < codeEnd;
254
+ if (!code && !diff) return guide + resultIndent + content;
255
+ const number = numbers.get(top + i);
256
+ const cell = number && gutter ? ` ${theme.fg("dim", number.padStart(digits))} ` : " ".repeat(gutter);
257
+ return guide + surface(cell + content);
258
+ });
259
+ editorRows = diff ? body.length : codeEnd - top;
260
+ padTop = !image && (editorRows || body.length > 1) ? 1 : 0;
261
+ padBottom = !image && body.length > 1 && editorRows !== body.length ? 1 : 0;
262
+ if (padBottom) body.push(guide);
263
+ if (editorRows) {
264
+ const pad = guide + theme.bg("toolSuccessBg", " ".repeat(gutter + contentWidth));
265
+ body.splice(editorRows, 0, pad);
266
+ body.unshift(pad);
267
+ } else if (padTop) body.unshift(guide);
268
+ if (clipped) {
269
+ body.push(truncateToWidth(this.guide + theme.fg("muted", `… ${clipped} more lines · click to expand`), width));
270
+ }
271
+ cached = { lines, width, guide: this.guide, revision: this.revision, first: source?.first, body };
272
+ return body;
273
+ },
274
+ handleMouse(event) {
275
+ if (hiddenReadRows && event.type === "click" && event.button === "left") {
276
+ if (previews.has(tool)) previews.delete(tool);
277
+ else previews.add(tool);
278
+ cached = undefined;
279
+ tui.requestRender();
280
+ return { handled: true };
281
+ }
282
+ const row = event.y - padTop;
283
+ if (row < 0 || (editorRows && row === editorRows) || event.y >= event.height - padBottom) return;
284
+ const y = row + top - (editorRows && row > editorRows ? 1 : 0);
285
+ const x = event.x - inset - (y < codeEnd ? gutter : outputGutter);
286
+ if (x < 0 || x >= contentWidth) return;
287
+ const full = tool.expanded;
288
+ const result = tool.handleMouse?.({ ...event, x, y, width: contentWidth, height });
289
+ if (tool.toolName === "codemode" && full && !tool.expanded) previews.add(tool);
290
+ return result;
291
+ },
292
+ };
293
+ }
294
+
295
+ function isToolRow(row: Component): row is ToolRow {
296
+ return row instanceof ToolExecutionComponent && typeof Reflect.get(row, "toolName") === "string";
297
+ }
298
+
299
+ function thinkingRow(region: MouseRegion, theme: Theme, tui: TUI): Component & { guide?: string; live: boolean } {
300
+ const child = Reflect.get(region, "child");
301
+ const open = child instanceof Markdown;
302
+ const padding = open ? (Reflect.get(child, "paddingX") ?? 0) : 0;
303
+ const margin = " ".repeat(padding);
304
+ const bulb = theme.fg("dim", "\uEA61 ");
305
+ const indent = " ".repeat(visibleWidth(bulb));
306
+ return {
307
+ live: false,
308
+ render(width) {
309
+ const label = theme.italic(theme.fg("thinkingText", this.live ? "Thinking…" : "Thought"));
310
+ const guide = this.guide ?? " ";
311
+ if (!open) return [truncateToWidth(guide + bulb + label, width)];
312
+ const prefix = guide + indent;
313
+ const inner = Math.max(1, width - visibleWidth(prefix));
314
+ const lines = region.render(inner + padding).map((line) => {
315
+ const text = line.startsWith(margin) ? line.slice(padding) : line;
316
+ return truncateToWidth(prefix + text, width, "");
317
+ });
318
+ return [this.guide ?? "", ...lines, this.guide ?? ""];
319
+ },
320
+ handleMouse(event) {
321
+ if (event.type !== "click" || event.button !== "left") return;
322
+ if (open && (event.y === 0 || event.y === event.height - 1)) return;
323
+ const inset = visibleWidth(this.guide ?? " ") + indent.length;
324
+ const result = region.handleMouse({
325
+ ...event,
326
+ x: Math.max(0, event.x - inset) + padding,
327
+ y: event.y - (open ? 1 : 0),
328
+ width: Math.max(1, event.width - inset) + padding,
329
+ height: event.height - (open ? 2 : 0),
330
+ });
331
+ if (result?.handled) tui.requestRender();
332
+ return result;
333
+ },
334
+ invalidate: () => region.invalidate(),
335
+ };
336
+ }
337
+
338
+ /** Format milliseconds as a human-readable duration. */
339
+ export function formatDuration(ms: number): string {
340
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
341
+ if (totalSeconds < 60) return `${totalSeconds}s`;
342
+
343
+ const s = totalSeconds % 60;
344
+ const totalMinutes = Math.floor(totalSeconds / 60);
345
+ if (totalMinutes < 60) return `${totalMinutes}m ${s}s`;
346
+
347
+ const m = totalMinutes % 60;
348
+ const h = Math.floor(totalMinutes / 60);
349
+ return `${h}h ${m}m ${s}s`;
350
+ }
351
+
352
+ export function installToolGroups(
353
+ tui: TUI,
354
+ theme: Theme,
355
+ starts?: ReadonlyMap<string, number>,
356
+ cancelled?: ReadonlyMap<string, number | undefined>,
357
+ ) {
358
+ // ponytail: Pi 1.x exposes per-tool renderers, not transcript grouping; leave unknown layouts alone until Pi ships a group hook.
359
+ const document = tui.children?.[0];
360
+ if (!(document instanceof Container) || document.children.length !== 3) return;
361
+ const [header, resources, chat] = document.children;
362
+ if (!(header instanceof Container && resources instanceof Container && chat instanceof Container)) return;
363
+
364
+ const mounted = createTranscriptView(chat, tui, theme, starts, cancelled, () => {
365
+ const viewport =
366
+ "getPrimaryScrollView" in tui && typeof tui.getPrimaryScrollView === "function"
367
+ ? tui.getPrimaryScrollView()
368
+ : undefined;
369
+ viewport?.scrollTo(viewport.scrollTop, { disableFollow: true });
370
+ });
371
+ document.children[2] = mounted.root;
372
+ return {
373
+ dispose() {
374
+ mounted.dispose();
375
+ if (document.children[2] === mounted.root) document.children[2] = chat;
376
+ },
377
+ };
378
+ }
379
+
380
+ export function createTranscriptView(
381
+ chat: Container,
382
+ tui: TUI,
383
+ theme: Theme,
384
+ starts?: ReadonlyMap<string, number>,
385
+ cancelled?: ReadonlyMap<string, number | undefined>,
386
+ holdScroll?: () => void,
387
+ ) {
388
+ const blockGap = new Spacer(1);
389
+ const branchGap: Component = {
390
+ render: (width) => [width >= 8 ? theme.fg("dim", " │") : ""],
391
+ invalidate() {},
392
+ };
393
+ const goalRows = new WeakMap<CustomMessageComponent, MouseRegion>();
394
+ function goalRow(card: CustomMessageComponent) {
395
+ const message = Reflect.get(card, "message");
396
+ if (
397
+ message?.customType !== "goal-ui" ||
398
+ typeof message.content !== "string" ||
399
+ Reflect.get(card, "customRenderer")
400
+ ) {
401
+ return;
402
+ }
403
+ let row = goalRows.get(card);
404
+ if (!row) {
405
+ const title = summary(message.content.split("\n", 1)[0]) || "Goal";
406
+ row = new MouseRegion(
407
+ {
408
+ render(width) {
409
+ const limit = Math.max(1, Math.floor(width / 2));
410
+ const icon = theme.fg("muted", Reflect.get(card, "_expanded") ? "▾" : "▸");
411
+ const label = ` ${theme.fg("dim", "•")} ${theme.fg("customMessageLabel", title)}`;
412
+ return [limit <= 2 ? icon : `${truncateToWidth(label, limit - 2, "…")} ${icon}`];
413
+ },
414
+ invalidate() {},
415
+ },
416
+ (event) => {
417
+ if (event.type !== "click" || event.button !== "left") return;
418
+ card.setExpanded(!Reflect.get(card, "_expanded"));
419
+ tui.requestRender();
420
+ return { handled: true };
421
+ },
422
+ );
423
+ goalRows.set(card, row);
424
+ }
425
+ return row;
426
+ }
427
+
428
+ const titles = new WeakMap<Component, Text>();
429
+ const controls = new WeakMap<Component, MouseRegion>();
430
+ const showAll = new WeakSet<Component>();
431
+ const previews = new WeakSet<Component>();
432
+ type Thought = ReturnType<typeof thinkingRow>;
433
+ const originals = new WeakMap<Component, MouseRegion>();
434
+ function styleThoughts(message: AssistantMessageComponent): Thought[] | undefined {
435
+ const [content] = message.children;
436
+ if (message.children.length !== 1 || !(content instanceof Container)) return;
437
+ const thoughts: Thought[] = [];
438
+ let onlyThoughts = true;
439
+ for (const [i, part] of content.children.entries()) {
440
+ if (part instanceof Spacer) continue;
441
+ const region = originals.get(part) ?? part;
442
+ const child = region instanceof MouseRegion ? Reflect.get(region, "child") : undefined;
443
+ if (!(region instanceof MouseRegion) || !(child instanceof Text || child instanceof Markdown)) {
444
+ onlyThoughts = false;
445
+ continue;
446
+ }
447
+ if (child instanceof Text && Reflect.get(message, "hiddenThinkingLabel") === "") continue;
448
+ const row = region === part ? thinkingRow(region, theme, tui) : (part as Thought);
449
+ if (region === part) {
450
+ originals.set(row, region);
451
+ content.children[i] = row;
452
+ }
453
+ row.guide = undefined;
454
+ row.live =
455
+ i === content.children.length - 1 &&
456
+ Reflect.get(message, "isStreaming") === true &&
457
+ Reflect.get(message, "lastMessage")?.content.at(-1)?.type === "thinking";
458
+ thoughts.push(row);
459
+ }
460
+ return onlyThoughts ? thoughts : undefined;
461
+ }
462
+ const motion = !process.env.REDUCE_MOTION && !process.env.NO_COLOR;
463
+ const shimmer = createShimmer(theme);
464
+ let frame = 0;
465
+ let animation: ReturnType<typeof setInterval> | undefined;
466
+ let pressed: Component | undefined;
467
+ let settle: ReturnType<typeof setTimeout> | undefined;
468
+ const calls = new WeakMap<
469
+ Component,
470
+ {
471
+ label: Text;
472
+ row: MouseRegion;
473
+ details?: ReturnType<typeof indentedDetails>;
474
+ labelKey?: string;
475
+ }
476
+ >();
477
+ function historyControl(first: ToolRow, title: Text) {
478
+ return new MouseRegion(title, (event) => {
479
+ if (event.type !== "click" || event.button !== "left") return;
480
+ if (showAll.has(first)) showAll.delete(first);
481
+ else {
482
+ showAll.add(first);
483
+ holdScroll?.();
484
+ }
485
+ if (motion) {
486
+ clearTimeout(settle);
487
+ pressed = first;
488
+ settle = setTimeout(() => {
489
+ pressed = undefined;
490
+ tui.requestRender();
491
+ }, 150);
492
+ }
493
+ tui.requestRender();
494
+ return { handled: true };
495
+ });
496
+ }
497
+
498
+ function createCall(tool: ToolRow) {
499
+ const label = new Text("", 0, 0);
500
+ const row = new MouseRegion(label, (event) => {
501
+ if (event.type !== "click" || event.button !== "left") return;
502
+ if (tool.toolName === "read") {
503
+ if (tool.expanded) previews.delete(tool);
504
+ else previews.add(tool);
505
+ tool.setExpanded(!tool.expanded);
506
+ } else if (tool.toolName !== "codemode") tool.setExpanded(!tool.expanded);
507
+ else if (tool.expanded || previews.has(tool)) {
508
+ previews.delete(tool);
509
+ if (tool.expanded) tool.setExpanded(false);
510
+ } else previews.add(tool);
511
+ tui.requestRender();
512
+ return { handled: true };
513
+ });
514
+ return { label, row };
515
+ }
516
+
517
+ const view = new Container();
518
+ const render = view.render.bind(view);
519
+ let revision = 0;
520
+ view.invalidate = () => {
521
+ revision++;
522
+ chat.invalidate();
523
+ };
524
+ view.render = (width) => {
525
+ let animating = false;
526
+ const rows: Component[] = [];
527
+ let run: ToolRow[] = [];
528
+ let name = "";
529
+ const before = new Map<ToolRow, Thought[]>();
530
+ let pending: { message: AssistantMessageComponent; regions: Thought[] }[] = [];
531
+ const flush = () => {
532
+ const first = run[0];
533
+ if (!first) return;
534
+ const grouped = run.length > 1;
535
+ let failed = 0;
536
+ let interrupted = 0;
537
+ for (const tool of run) {
538
+ if (!tool.result?.isError) continue;
539
+ if (cancelled?.has(tool.toolCallId)) interrupted++;
540
+ else failed++;
541
+ }
542
+ const heading = () => {
543
+ const [verb] = describe(first);
544
+ const settled = interrupted ? "muted" : "success";
545
+ const role = failed ? "error" : run.some((tool) => tool.isPartial) ? "warning" : settled;
546
+ const dot = theme.fg(role, "•");
547
+ const action = theme.bold(theme.fg("customMessageLabel", verb || (name === "edit" ? "Edit" : "Write")));
548
+ return ` ${dot} ${action}${verb ? ` ${theme.fg("toolTitle", summary(name))}` : ""}`;
549
+ };
550
+ rows.push(blockGap);
551
+ if (grouped) {
552
+ let title = titles.get(first);
553
+ if (!title) {
554
+ title = new Text("", 0, 0);
555
+ titles.set(first, title);
556
+ }
557
+ const status = failed ? theme.fg("error", ` · ${failed} failed`) : "";
558
+ const caption = `${heading()} ×${run.length}${status}`;
559
+ if (run.length <= 10) {
560
+ title.setText(truncateToWidth(caption, width));
561
+ rows.push(title);
562
+ } else {
563
+ let control = controls.get(first);
564
+ if (!control) {
565
+ control = historyControl(first, title);
566
+ controls.set(first, control);
567
+ }
568
+ const action = theme.fg(
569
+ pressed === first ? "toolTitle" : "muted",
570
+ showAll.has(first) ? "Show less" : "Show all",
571
+ );
572
+ const titleLine = truncateToWidth(caption, width);
573
+ title.setText(
574
+ visibleWidth(titleLine) + 3 + visibleWidth(action) <= width
575
+ ? `${titleLine} · ${action}`
576
+ : `${titleLine}\n${truncateToWidth(action, width)}`,
577
+ );
578
+ rows.push(control);
579
+ }
580
+ }
581
+
582
+ for (let i = showAll.has(first) ? 0 : Math.max(0, run.length - 10); i < run.length; i++) {
583
+ const tool = run[i]!;
584
+ let call = calls.get(tool);
585
+ if (!call) {
586
+ call = createCall(tool);
587
+ calls.set(tool, call);
588
+ }
589
+ if (tool.toolName === "read" ? !tool.expanded : tool.expanded) previews.delete(tool);
590
+ const open = tool.expanded || previews.has(tool);
591
+ const last = i === run.length - 1;
592
+ const [, subject] = describe(tool);
593
+ const start = tool.isPartial ? starts?.get(tool.toolCallId) : undefined;
594
+ const error = tool.result?.isError && (cancelled?.has(tool.toolCallId) ? "cancelled" : "failed");
595
+ const state = error || (!tool.isPartial ? "" : name ? "running" : "preparing…");
596
+ const duration =
597
+ state === "cancelled" ? (cancelled?.get(tool.toolCallId) ?? tool.result?.durationMs) : undefined;
598
+ const elapsed = start === undefined ? "" : formatDuration(performance.now() - start);
599
+ const regions = before.get(tool);
600
+ const rowWidth = name === "codemode" ? width : Math.max(1, Math.floor(width * 0.6));
601
+ const branch = grouped && rowWidth >= 9 ? (last ? " └─ " : " ├─ ") : "";
602
+ const guide = width < 8 ? "" : !grouped ? " " : last ? " " : " │ ";
603
+ if (regions) {
604
+ for (const row of regions) {
605
+ row.live = false;
606
+ row.guide = width >= 8 ? theme.fg("dim", " │ ") : "";
607
+ rows.push(row);
608
+ }
609
+ }
610
+ const active = motion && tool.isPartial && !error && width > 1;
611
+ animating ||= active || !!elapsed;
612
+ const labelKey = `${revision}:${width}:${grouped}:${last}:${open}:${state}:${elapsed}:${duration ?? ""}:${active ? frame : 0}:${subject}`;
613
+ if (labelKey !== call.labelKey) {
614
+ call.labelKey = labelKey;
615
+ const available = rowWidth - branch.length - 2;
616
+ let suffix = state ? ` · ${state}` : "";
617
+ if (duration !== undefined) {
618
+ const timed = `${suffix} · ${formatDuration(duration)}`;
619
+ if (timed.length < available) suffix = timed;
620
+ } else if (elapsed) {
621
+ const full = `${suffix} ${elapsed}`;
622
+ suffix = full.length < available ? full : ` · ${elapsed}`;
623
+ }
624
+ const icon = theme.fg("muted", open ? "▾" : "▸");
625
+ const status = suffix.length < available ? theme.fg(state === "failed" ? "error" : "muted", suffix) : "";
626
+ const label = theme.fg("dim", subject || summary(name));
627
+ const caption = grouped ? label : !name ? " •" : subject ? `${heading()} ${label}` : heading();
628
+ const script = truncateToWidth(caption, Math.max(0, available - visibleWidth(status)), "…");
629
+ const line = `${script}${status} ${icon}`;
630
+ call.label.setText(rowWidth <= 1 ? icon : theme.fg("dim", branch) + (active ? shimmer(line, frame) : line));
631
+ }
632
+ rows.push(call.row);
633
+ if (open) {
634
+ call.details ??= indentedDetails(tool, theme, previews, tui);
635
+ const details = call.details;
636
+ details.revision = revision;
637
+ details.guide = guide.includes("│") ? theme.fg("dim", guide) : guide;
638
+ rows.push(details);
639
+ if (!last) rows.push(branchGap);
640
+ } else call.details = undefined;
641
+ }
642
+ run = [];
643
+ for (const { message } of pending) rows.push(message);
644
+ pending = [];
645
+ };
646
+
647
+ for (const child of chat.children) {
648
+ if (isToolRow(child)) {
649
+ if (child.toolName !== name) flush();
650
+ else if (pending.length) {
651
+ before.set(
652
+ child,
653
+ pending.flatMap(({ regions }) => regions),
654
+ );
655
+ pending = [];
656
+ }
657
+ name = child.toolName;
658
+ run.push(child);
659
+ } else {
660
+ if (child instanceof AssistantMessageComponent) {
661
+ const regions = styleThoughts(child);
662
+ if (run.length && regions) {
663
+ if (regions.length) pending.push({ message: child, regions });
664
+ continue;
665
+ }
666
+ }
667
+ flush();
668
+ const notice = child instanceof CustomMessageComponent && goalRow(child);
669
+ if (notice) {
670
+ rows.push(blockGap, notice);
671
+ if (Reflect.get(child, "_expanded")) rows.push(child);
672
+ } else rows.push(child);
673
+ }
674
+ }
675
+ flush();
676
+ if (animating && !animation) {
677
+ animation = setInterval(
678
+ () => {
679
+ frame++;
680
+ tui.requestRender();
681
+ },
682
+ motion ? 25 : 1000,
683
+ );
684
+ animation.unref();
685
+ } else if (!animating && animation) {
686
+ clearInterval(animation);
687
+ animation = undefined;
688
+ frame = 0;
689
+ }
690
+ view.children = rows;
691
+ return render(width);
692
+ };
693
+ return {
694
+ root: view,
695
+ dispose() {
696
+ clearInterval(animation);
697
+ clearTimeout(settle);
698
+ for (const message of chat.children) {
699
+ if (!(message instanceof AssistantMessageComponent)) continue;
700
+ const [content] = message.children;
701
+ if (content instanceof Container) {
702
+ for (const [i, part] of content.children.entries()) {
703
+ const original = originals.get(part);
704
+ if (original) content.children[i] = original;
705
+ }
706
+ }
707
+ }
708
+ },
709
+ };
710
+ }