@bismawy/pi-arnative 0.16.0 → 0.18.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.
Files changed (47) hide show
  1. package/README.md +25 -16
  2. package/extensions/index.ts +41 -0
  3. package/lib/active-clock.ts +91 -0
  4. package/lib/ansi.ts +40 -78
  5. package/lib/box.ts +49 -68
  6. package/lib/chatbox.ts +371 -0
  7. package/lib/color.ts +3 -31
  8. package/lib/compat.ts +0 -60
  9. package/lib/edit-diff.ts +199 -0
  10. package/{extensions → lib/features}/arnative.ts +96 -423
  11. package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -325
  12. package/{extensions → lib/features}/budget.ts +17 -242
  13. package/lib/features/footer.ts +2232 -0
  14. package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
  15. package/{extensions → lib/features}/model-heal.ts +5 -28
  16. package/lib/features/progress-group.ts +1557 -0
  17. package/{extensions → lib/features}/render-cache.ts +130 -158
  18. package/{extensions → lib/features}/timestamps.ts +132 -131
  19. package/{extensions → lib/features}/todos.ts +44 -158
  20. package/lib/features/tools.ts +1202 -0
  21. package/lib/features/ui-render-tweaks.ts +606 -0
  22. package/lib/features/usage.ts +786 -0
  23. package/lib/format.ts +22 -4
  24. package/lib/git-status.ts +164 -0
  25. package/lib/list-picker.ts +1 -127
  26. package/lib/model-heal.ts +70 -162
  27. package/lib/patch.ts +0 -63
  28. package/lib/preset-store.ts +17 -133
  29. package/lib/provider-store.ts +573 -0
  30. package/lib/provider.ts +52 -851
  31. package/lib/runtime.ts +209 -0
  32. package/lib/shortcuts.ts +8 -58
  33. package/lib/spinner.ts +88 -162
  34. package/lib/status-widget.ts +4 -30
  35. package/lib/todos.ts +20 -143
  36. package/lib/usage-pricing.ts +143 -0
  37. package/lib/usage-store.ts +44 -378
  38. package/package.json +5 -6
  39. package/CHANGELOG.md +0 -678
  40. package/extensions/animations.ts +0 -242
  41. package/extensions/footer.ts +0 -2580
  42. package/extensions/tools.ts +0 -2231
  43. package/extensions/ui-render-tweaks.ts +0 -1005
  44. package/extensions/usage-export.ts +0 -283
  45. package/extensions/usage.ts +0 -1406
  46. package/lib/check.ts +0 -21
  47. package/themes/gen-themes.mjs +0 -715
@@ -0,0 +1,606 @@
1
+ /**
2
+ * Six small patches to pi's fullscreen renderer (render layer only, session data
3
+ * untouched):
4
+ * 1. Hide pi's built-in "Reloading keybindings, extensions, skills..." box
5
+ * (hardcoded in handleReloadCommand, no auto-hide).
6
+ * 2. Drag selection: pi wraps it in reverse video (\x1b[7m), unreadable in some
7
+ * terminals/themes -> explicit colors (bg selectedBg + fg text).
8
+ * 3. Compaction message: pi's 3 lines (label, blank, text) squeezed into one:
9
+ * `[compaction] Compacted from N tokens (ctrl+o to expand)`.
10
+ * 4. Custom `pi-jev-eye-review` message: pi adds a label + blank line inside a purple
11
+ * box; our renderer shows the content as-is.
12
+ * 5. `↓ Jump to latest message` pill (fullscreen): bg selectedBg (grey) -> accent,
13
+ * text darkened (theme canvas) so contrast stays high (9.6:1).
14
+ * 6. `ctx.ui.select` rows: pi paints the whole selected row accent -> keep accent on
15
+ * the `❯` marker and `·` separators, selected text in soft.
16
+ */
17
+ import { AssistantMessageComponent, CompactionSummaryMessageComponent, ExtensionSelectorComponent, getMarkdownTheme, InteractiveMode, UserMessageComponent, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
18
+ import { Container, Markdown, MouseRegion, Spacer, Text, TuiAltScreen, type Component, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
19
+ import { renderBoxLines } from "../box.ts";
20
+ import { statusRows } from "../status-widget.ts";
21
+ import { ansiBgOpen, getActiveTheme, setActiveTheme, stripAnsi, themeOf, softOf } from "../ansi.ts";
22
+ import { contrast } from "../color.ts";
23
+ import { expandKeyName } from "../format.ts";
24
+ import { patchOnce } from "../patch.ts";
25
+ import { getRuntime, type ThinkingLabelState } from "../runtime.ts";
26
+
27
+ type ActiveTheme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; italic?(text: string): string } | null;
28
+ const activeTheme = () => getActiveTheme<Exclude<ActiveTheme, null>>();
29
+
30
+ // Hide pi's built-in "Reloading keybindings, extensions, skills..." box
31
+ // (hardcoded in handleReloadCommand, no auto-hide). Patches Container.render
32
+ // through the prototype chain (Container is not exported) and drops the whole box on match.
33
+ const RELOAD_TEXT = "Reloading keybindings, extensions, skills, prompts, themes, and context files...";
34
+ /** The reload box is a fixed 5-child container (2 borders, 2 spacers, one 78-char line), so it
35
+ * renders at most ~9 rows even wrapped. Anything larger cannot be the box, and this predicate
36
+ * runs per frame on every plain Container — including a transcript of tens of thousands of
37
+ * lines, where the substring scan is the single most expensive arnative render patch. */
38
+ const RELOAD_BOX_MAX_LINES = 64;
39
+ /**
40
+ * True only for the box itself: border rows, blank spacers and (possibly wrapped) copy of the
41
+ * message. The patch sits on every plain Container, so a bare substring test would blank a
42
+ * whole chat the moment a transcript line mentioned the phrase. Containers larger than
43
+ * {@link RELOAD_BOX_MAX_LINES} are refused before any scanning starts.
44
+ */
45
+ export function shouldHideReloadBox(lines: readonly string[]): boolean {
46
+ if (lines.length > RELOAD_BOX_MAX_LINES) return false;
47
+ if (!lines.some((l) => l.includes("Reloading keybindings"))) return false;
48
+ const rows = lines.map((l) => stripAnsi(l).trim());
49
+ return rows.every((r) => r === "" || /^[─-]+$/.test(r) || RELOAD_TEXT.includes(r));
50
+ }
51
+ // Every patch below reinstalls on each load (lib/patch.ts): `/reload` re-evaluates the
52
+ // module in the same process, so a `globalThis` guard would freeze the first load.
53
+ if (UserMessageComponent?.prototype) {
54
+ const containerProto = Object.getPrototypeOf(UserMessageComponent.prototype) as { render?: (width: number) => string[] };
55
+ if (typeof containerProto?.render === "function") {
56
+ patchOnce(containerProto, "render", (orig) => function (this: any, width: number): string[] {
57
+ const lines = orig.call(this, width);
58
+ return shouldHideReloadBox(lines) ? [] : lines;
59
+ });
60
+ }
61
+ }
62
+
63
+ // bg open code (no closing reset) -> lib/ansi.ts (single definition).
64
+
65
+ // Drag selection in pi fullscreen: pi only wraps the selection in reverse video
66
+ // (\x1b[7m), unreadable in some terminals/themes. Replaced with explicit colors
67
+ // (bg selectedBg + fg text) so text always stays visible.
68
+
69
+ export function recolorSelection(highlighted: string, fgOpen: string, bgOpen: string): string {
70
+ return highlighted.split("\x1b[7m").join(fgOpen + bgOpen).split("\x1b[27m").join("\x1b[39m\x1b[49m");
71
+ }
72
+
73
+ export function ansiFgOpen(th: { fg?(c: string, t: string): string } | null, color = "text"): string {
74
+ if (!th?.fg) return "";
75
+ try {
76
+ const probe = th.fg(color, "");
77
+ const reset = "\x1b[39m";
78
+ return probe.endsWith(reset) ? probe.slice(0, -reset.length) : probe;
79
+ } catch {
80
+ return "";
81
+ }
82
+ }
83
+
84
+ // `↓ Jump to latest message` pill (fullscreen): pi colors it with bg `selectedBg`
85
+ // (grey) -> accent bg + darkened canvas text (contrast 9.6:1, WCAG AA). pi has no bg
86
+ // token for `accent` (7 exist, see PILL_INK), so the SGR escapes are swapped;
87
+ // `bg("accent")` would throw "Unknown theme background color" and stay unchanged.
88
+ const PILL_MARK = "↓ Jump to latest message";
89
+ const PILL_INK = "toolPendingBg";
90
+
91
+ const asBg = (seq: string) => seq.replace(/\x1b\[38;/g, "\x1b[48;");
92
+ const asFg = (seq: string) => seq.replace(/\x1b\[48;/g, "\x1b[38;");
93
+
94
+ export function accentPill(
95
+ text: string,
96
+ th: { fg?(c: string, t: string): string; bg?(c: string, t: string): string } | null,
97
+ ): string {
98
+ if (!text.includes(PILL_MARK) || !th?.fg || !th?.bg) return text;
99
+ const accentBg = asBg(ansiFgOpen(th, "accent"));
100
+ const inkFg = asFg(ansiBgOpen(th, PILL_INK));
101
+ if (!accentBg || !inkFg) return text; // token missing from the theme -> leave pi's default
102
+ return `${accentBg}${inkFg}${stripAnsi(text)}\x1b[39m\x1b[49m`;
103
+ }
104
+
105
+ // TuiAltScreen builds the pill via the per-instance `scrollToEndIndicator` callback
106
+ // (an instance field, so the prototype cannot be patched). Swap in our callback
107
+ // only while the composite runs, then restore the original.
108
+ export function withAccentPill<T>(
109
+ host: { scrollToEndIndicator?: (() => string) | undefined },
110
+ fn: () => T,
111
+ th: { fg?(c: string, t: string): string; bg?(c: string, t: string): string } | null,
112
+ ): T {
113
+ const orig = host.scrollToEndIndicator;
114
+ if (typeof orig !== "function") return fn();
115
+ host.scrollToEndIndicator = () => accentPill(orig(), th);
116
+ try {
117
+ return fn();
118
+ } finally {
119
+ host.scrollToEndIndicator = orig;
120
+ }
121
+ }
122
+
123
+ if (TuiAltScreen?.prototype) {
124
+ const proto = TuiAltScreen.prototype as any;
125
+ if (typeof proto.applySelectionHighlight === "function") {
126
+ patchOnce(proto, "applySelectionHighlight", (orig) => function (this: any, text: string): string {
127
+ const highlighted = orig.call(this, text);
128
+ const fgOpen = ansiFgOpen(activeTheme());
129
+ const bgOpen = ansiBgOpen(activeTheme(), "selectedBg");
130
+ return fgOpen && bgOpen ? recolorSelection(highlighted, fgOpen, bgOpen) : highlighted;
131
+ });
132
+ }
133
+ }
134
+
135
+ if (TuiAltScreen?.prototype) {
136
+ const proto = TuiAltScreen.prototype as unknown as {
137
+ compositeScrollToEndIndicator?: (screen: string[], layout: unknown, width: number) => string[];
138
+ };
139
+ if (typeof proto.compositeScrollToEndIndicator === "function") {
140
+ patchOnce(proto, "compositeScrollToEndIndicator", (origComposite) => function (
141
+ this: { scrollToEndIndicator?: (() => string) | undefined },
142
+ screen: string[],
143
+ layout: unknown,
144
+ width: number,
145
+ ) {
146
+ return withAccentPill(this, () => origComposite.call(this, screen, layout, width), activeTheme());
147
+ });
148
+ }
149
+ }
150
+
151
+ // 6. Select menus (ctx.ui.select -> ExtensionSelectorComponent.updateList): pi colors the
152
+ // whole selected row accent. Arnative keeps accent on the `❯` marker and `·` separators
153
+ // and moves the selected text to soft (accent on themes without the token).
154
+
155
+ /** Selected row body: `·` separators accent, the text around them soft. */
156
+ export function selectRowText(row: string, th: { fg(c: string, t: string): string }): string {
157
+ const soft = softOf(th);
158
+ return row
159
+ .split("·")
160
+ .map((part) => soft(part))
161
+ .join(th.fg("accent", "·"));
162
+ }
163
+
164
+ if (ExtensionSelectorComponent?.prototype) {
165
+ const proto = ExtensionSelectorComponent.prototype as unknown as {
166
+ options: string[];
167
+ selectedIndex: number;
168
+ listContainer: { clear(): void; addChild(c: unknown): void };
169
+ updateList(): void;
170
+ };
171
+ patchOnce(proto, "updateList", (origUpdateList) => function (this: typeof proto) {
172
+ const th = activeTheme();
173
+ if (!th) return origUpdateList.call(this); // no theme yet -> pi's default
174
+ this.listContainer.clear();
175
+ for (let i = 0; i < this.options.length; i++) {
176
+ const text =
177
+ i === this.selectedIndex
178
+ ? th.fg("accent", "❯ ") + selectRowText(this.options[i]!, th)
179
+ : ` ${th.fg("text", this.options[i]!)}`;
180
+ this.listContainer.addChild(new Text(text, 1, 0));
181
+ }
182
+ });
183
+ }
184
+
185
+ export default function uiRenderTweaks(pi: ExtensionAPI) {
186
+ // The active theme is re-read per session (ctx.ui.theme); render reads it lazily.
187
+ pi.on("session_start", async (_event, ctx) => {
188
+ const th = themeOf<Exclude<ActiveTheme, null>>(ctx);
189
+ if (th) setActiveTheme(th);
190
+ clearThinkingTicker();
191
+ });
192
+
193
+ pi.on("agent_end", async () => {
194
+ clearThinkingTicker();
195
+ });
196
+
197
+ pi.on("session_shutdown", async () => {
198
+ clearThinkingTicker();
199
+ });
200
+
201
+ // 4. `pi-jev-eye-review` contract message: use our own border box.
202
+ // Collapsed by default: [pi-jev-eye] Reviewed turn contract. [click to expand]
203
+ // On click: the full contract content appears inside the box.
204
+ pi.registerMessageRenderer("pi-jev-eye-review", (message, { expanded }, th) => {
205
+ const raw = customMessageText(message.content);
206
+ return new JevReviewBoxComponent(raw, Boolean(expanded), th);
207
+ });
208
+ }
209
+
210
+ // "Package Updates Available" notification: pi wraps the text in a DynamicBorder
211
+ // (full lines, not a box). Replaced with an arnative box (╭─╮ │ ╰─╯) through an
212
+ // InteractiveMode prototype patch; the yellow (warning) title and border stay, the
213
+ // body text is unchanged.
214
+ export class PackageUpdateBoxComponent implements Component {
215
+ private packages: string[];
216
+ private th: { fg(c: string, t: string): string } | null;
217
+
218
+ constructor(packages: string[], th: { fg(c: string, t: string): string } | null) {
219
+ this.packages = packages;
220
+ this.th = th;
221
+ }
222
+
223
+ invalidate(): void {}
224
+
225
+ render(width: number): string[] {
226
+ const th = this.th;
227
+ const fg = (color: string, text: string) => (th ? th.fg(color, text) : text);
228
+ const rows = [
229
+ fg("warning", "\x1b[1m\uf449 Package Updates Available\x1b[22m"),
230
+ `${fg("muted", "Package updates are available. Run ")}${fg("accent", "pi update --extensions")}`,
231
+ fg("muted", "Packages:"),
232
+ ...this.packages.map((pkg) => `- ${pkg}`),
233
+ ];
234
+ return renderBoxLines(th, width, rows, undefined, "warning");
235
+ }
236
+ }
237
+
238
+ if (InteractiveMode?.prototype) {
239
+ const proto = InteractiveMode.prototype as unknown as {
240
+ showPackageUpdateNotification(packages: string[]): void;
241
+ };
242
+ patchOnce(proto, "showPackageUpdateNotification", () => function (this: typeof proto, packages: string[]) {
243
+ const self = this as unknown as {
244
+ chatContainer: { addChild(c: unknown): void };
245
+ ui: { requestRender(): void };
246
+ };
247
+ self.chatContainer.addChild(new Spacer(1));
248
+ self.chatContainer.addChild(new PackageUpdateBoxComponent(packages, activeTheme()));
249
+ self.ui.requestRender();
250
+ });
251
+ }
252
+
253
+ // arnative box border helper -> lib/box.ts (one definition for every box)
254
+
255
+ // 7. Status rows above the chat column (pi's `aboveEditor` widget slot). pi turns a string
256
+ // array into unstyled `Text`, so an extension's status line ignores the theme and lands in
257
+ // the default foreground. Every such array is handed to a component factory instead, which
258
+ // receives the live theme: the arnative mark leads the block and every row is `dim`.
259
+ if (InteractiveMode?.prototype) {
260
+ const proto = InteractiveMode.prototype as unknown as {
261
+ setExtensionWidget(key: string, content: unknown, options?: { placement?: string }): void;
262
+ renderWidgets?(): void;
263
+ };
264
+ patchOnce(proto, "setExtensionWidget", (origSetWidget) => function (
265
+ this: typeof proto,
266
+ key: string,
267
+ content: unknown,
268
+ options?: { placement?: string },
269
+ ) {
270
+ const ui = (this as unknown as { ui?: { requestRender(): void } }).ui;
271
+ if (ui) thinkingState.ui = ui;
272
+ if (Array.isArray(content) && content.every((line) => typeof line === "string")) {
273
+ const rows = content as string[];
274
+ content = (_tui: unknown, th: Parameters<typeof statusRows>[0]) => ({
275
+ dispose() {
276
+ /* no listeners, no timers */
277
+ },
278
+ invalidate() {
279
+ /* the rows are fixed at set time */
280
+ },
281
+ render(width: number): string[] {
282
+ return statusRows(th ?? activeTheme(), rows, width);
283
+ },
284
+ });
285
+ }
286
+ return origSetWidget.call(this, key, content, options);
287
+ });
288
+ if (typeof proto.renderWidgets === "function") {
289
+ patchOnce(proto, "renderWidgets", (origRenderWidgets) => function (this: typeof proto) {
290
+ const ui = (this as unknown as { ui?: { requestRender(): void } }).ui;
291
+ if (ui) thinkingState.ui = ui;
292
+ return origRenderWidgets.call(this);
293
+ });
294
+ }
295
+ }
296
+
297
+ class JevReviewBoxComponent implements Component {
298
+ private text: string;
299
+ private th: { fg(c: string, t: string): string; bg?(c: string, t: string): string };
300
+ public isExpanded: boolean;
301
+
302
+ constructor(text: string, isExpanded: boolean, th: { fg(c: string, t: string): string; bg?(c: string, t: string): string }) {
303
+ this.text = text;
304
+ this.isExpanded = isExpanded;
305
+ this.th = th;
306
+ }
307
+
308
+ render(width: number): string[] {
309
+ const tag = this.th.fg("customMessageLabel", "\x1b[1m[pi-jev-eye]\x1b[22m");
310
+ if (!this.isExpanded) {
311
+ const title = this.th.fg("customMessageText", "Reviewed turn contract.");
312
+ const hint = this.th.fg("dim", "[click to expand]");
313
+ return renderBoxLines(this.th, width, [`${tag} ${title} ${hint}`]);
314
+ }
315
+ // Expanded: show every content line
316
+ const lines = this.text.split("\n");
317
+ const formattedRows = lines.map((line, idx) => {
318
+ if (idx === 0 && line.startsWith("[pi-jev-eye]")) {
319
+ const rest = line.slice("[pi-jev-eye]".length).trim();
320
+ return `${tag} ${this.th.fg("customMessageText", rest)}`;
321
+ }
322
+ return this.th.fg("customMessageText", line);
323
+ });
324
+ return renderBoxLines(this.th, width, formattedRows);
325
+ }
326
+
327
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
328
+ if (event.type === "click" && event.button === "left") {
329
+ this.isExpanded = !this.isExpanded;
330
+ return { handled: true };
331
+ }
332
+ return undefined;
333
+ }
334
+
335
+ invalidate(): void {}
336
+ }
337
+
338
+ // 3. Compaction message: one line instead of three (label, spacer, text).
339
+ // The theme is used so colors match pi's own box; before the session starts (no
340
+ // proxy yet) the built-in renderer keeps working.
341
+ export function compactionLine(th: { fg(c: string, t: string): string }, tokenStr: string): string {
342
+ const label = th.fg("customMessageLabel", "\x1b[1m[compaction]\x1b[22m");
343
+ return `${label} ${th.fg("customMessageText", `Compacted from ${tokenStr} tokens (`)}${th.fg("dim", expandKeyName())}${th.fg(
344
+ "customMessageText",
345
+ " to expand)",
346
+ )}`;
347
+ }
348
+
349
+ // Custom message content: a plain string, or concatenated text blocks (image blocks dropped).
350
+ export function customMessageText(content: unknown): string {
351
+ if (typeof content === "string") return content;
352
+ if (Array.isArray(content))
353
+ return content
354
+ .filter((c) => (c as { type?: string })?.type === "text")
355
+ .map((c) => (c as { text?: string }).text ?? "")
356
+ .join("\n");
357
+ return "";
358
+ }
359
+
360
+ if (CompactionSummaryMessageComponent?.prototype) {
361
+ const proto = CompactionSummaryMessageComponent.prototype as any;
362
+ patchOnce(proto, "updateDisplay", (origUpdateDisplay) => function (this: any): void {
363
+ const th = activeTheme();
364
+ if (!th) return origUpdateDisplay.call(this);
365
+ const message = this.message as { tokensBefore?: number; summary?: string } | undefined;
366
+ const tokenStr = Number(message?.tokensBefore ?? 0).toLocaleString();
367
+ this.clear();
368
+ const content = new Container();
369
+ if (this.expanded) {
370
+ content.addChild(new Text(th.fg("customMessageLabel", "\x1b[1m[compaction]\x1b[22m"), 0, 0));
371
+ content.addChild(new Spacer(1));
372
+ content.addChild(
373
+ new Markdown(
374
+ `**Compacted from ${tokenStr} tokens**\n\n${message?.summary ?? ""}`,
375
+ 0,
376
+ 0,
377
+ this.markdownTheme ?? getMarkdownTheme(),
378
+ { color: (t: string) => th.fg("customMessageText", t) },
379
+ ),
380
+ );
381
+ } else {
382
+ content.addChild(new Text(compactionLine(th, tokenStr), 0, 0));
383
+ }
384
+ this.addChild(
385
+ new MouseRegion(content, (event: any) => {
386
+ if (event.type !== "click" || event.button !== "left") return undefined;
387
+ this.setExpanded(!this.expanded);
388
+ return { handled: true };
389
+ }),
390
+ );
391
+ });
392
+ }
393
+
394
+ // 8. Hidden thinking label (`AssistantMessageComponent`): pi renders plain `Thinking...`
395
+ // in `thinkingText`. Arnative replaces pi's default `"Thinking..."` label with `\uec21`
396
+ // in `accent`, `Thinking...` in `dim`, and animates `.` -> `..` -> `...` while that
397
+ // thinking run is actively streaming. Finished or non-default labels stay static.
398
+ const THINKING_ICON = "\uec21";
399
+ const THINKING_DOTS = [".", "..", "..."] as const;
400
+ const THINKING_DOT_MS = 400;
401
+
402
+ const thinkingState: ThinkingLabelState = (getRuntime().thinkingLabelState ??= {
403
+ ui: null,
404
+ active: new Set<object>(),
405
+ starts: new WeakMap<object, number[]>(),
406
+ finished: new WeakMap<object, Array<string | undefined>>(),
407
+ timer: null,
408
+ });
409
+
410
+ function stopThinkingTicker(): void {
411
+ if (thinkingState.timer) {
412
+ clearInterval(thinkingState.timer);
413
+ thinkingState.timer = null;
414
+ }
415
+ }
416
+
417
+ export function clearThinkingTicker(): void {
418
+ thinkingState.active.clear();
419
+ thinkingState.starts = new WeakMap<object, number[]>();
420
+ thinkingState.finished = new WeakMap<object, Array<string | undefined>>();
421
+ stopThinkingTicker();
422
+ }
423
+
424
+ // Clear any leftover timer on module reload so old closures never keep ticking.
425
+ clearThinkingTicker();
426
+
427
+ function syncThinkingTicker(): void {
428
+ if (thinkingState.active.size === 0) {
429
+ stopThinkingTicker();
430
+ return;
431
+ }
432
+ if (thinkingState.timer) return;
433
+ thinkingState.timer = setInterval(() => {
434
+ if (thinkingState.active.size === 0) {
435
+ stopThinkingTicker();
436
+ return;
437
+ }
438
+ thinkingState.ui?.requestRender?.();
439
+ }, THINKING_DOT_MS);
440
+ thinkingState.timer.unref?.();
441
+ }
442
+
443
+ export function thinkingDotsAt(now: number, startMs: number): string {
444
+ const elapsed = Math.max(0, now - startMs);
445
+ const step = Math.floor(elapsed / THINKING_DOT_MS) % THINKING_DOTS.length;
446
+ return THINKING_DOTS[step]!;
447
+ }
448
+
449
+ // A finished run states what it did and how long it took, so the collapsed block stops
450
+ // claiming to be thinking once the answer has started. Seconds below a minute, then
451
+ // `Xm Ys`; a run always lasts at least one second, never `0s`.
452
+ export function formatThinkingElapsed(ms: number): string {
453
+ const total = Math.max(1, Math.round(ms / 1000));
454
+ if (total < 60) return `${total}s`;
455
+ const minutes = Math.floor(total / 60);
456
+ const seconds = total % 60;
457
+ return seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`;
458
+ }
459
+
460
+ export function formatThinkingLabel(
461
+ th: { fg(color: string, text: string): string; italic?(text: string): string } | null,
462
+ dots = "...",
463
+ finished?: string,
464
+ ): string {
465
+ const icon = th ? th.fg("dim", THINKING_ICON) : THINKING_ICON;
466
+ const label = finished ?? `Thinking${dots}`;
467
+ const styledLabel = th ? (th.italic ? th.italic(th.fg("dim", label)) : th.fg("dim", label)) : label;
468
+ return `${icon} ${styledLabel}`;
469
+ }
470
+
471
+ export function activeThinkingRunIndex(
472
+ message: { content?: Array<{ type?: string; text?: string; thinking?: string }> } | undefined,
473
+ isStreaming: boolean,
474
+ ): number | null {
475
+ if (!isStreaming || !Array.isArray(message?.content)) return null;
476
+ let runIdx = -1;
477
+ let lastVisibleKind: "thinking" | "other" | null = null;
478
+ for (let i = 0; i < message.content.length; i++) {
479
+ const block = message.content[i];
480
+ if (!block) continue;
481
+ if (block.type === "thinking") {
482
+ let hasText = false;
483
+ for (; i < message.content.length; i++) {
484
+ const b = message.content[i];
485
+ if (b?.type !== "thinking") break;
486
+ if (typeof b.thinking === "string" && b.thinking.trim()) hasText = true;
487
+ }
488
+ i--;
489
+ if (hasText) {
490
+ runIdx++;
491
+ lastVisibleKind = "thinking";
492
+ }
493
+ } else if ((block.type === "text" && typeof block.text === "string" && block.text.trim()) || block.type === "toolCall") {
494
+ lastVisibleKind = "other";
495
+ }
496
+ }
497
+ return lastVisibleKind === "thinking" && runIdx >= 0 ? runIdx : null;
498
+ }
499
+
500
+ class ThinkingLabelComponent implements Component {
501
+ private inner: Text;
502
+ private isActive: boolean;
503
+ private startMs: number | undefined;
504
+ private finished: string | undefined;
505
+ private getTheme: () => ActiveTheme;
506
+
507
+ constructor(
508
+ padX: number,
509
+ isActive: boolean,
510
+ startMs: number | undefined,
511
+ getTheme: () => ActiveTheme,
512
+ finished?: string,
513
+ ) {
514
+ this.isActive = isActive;
515
+ this.startMs = startMs;
516
+ this.finished = finished;
517
+ this.getTheme = getTheme;
518
+ this.inner = new Text(this.labelText(), padX, 0);
519
+ }
520
+
521
+ private labelText(): string {
522
+ const dots = this.isActive ? thinkingDotsAt(Date.now(), this.startMs ?? Date.now()) : "...";
523
+ return formatThinkingLabel(this.getTheme(), dots, this.isActive ? undefined : this.finished);
524
+ }
525
+
526
+ invalidate(): void {
527
+ this.inner.invalidate();
528
+ }
529
+
530
+ render(width: number): string[] {
531
+ this.inner.setText(this.labelText());
532
+ return this.inner.render(width);
533
+ }
534
+ }
535
+
536
+ function isPlainTextComponent(c: unknown): boolean {
537
+ if (!c || typeof c !== "object") return false;
538
+ const ctorName = (c as { constructor?: { name?: string } }).constructor?.name;
539
+ if (ctorName === "Text") return true;
540
+ return "text" in c && typeof (c as { text?: unknown }).text === "string" && !("theme" in c);
541
+ }
542
+
543
+ function patchThinkingInAssistantMessage(comp: {
544
+ contentContainer?: { children?: unknown[] };
545
+ lastMessage?: { content?: Array<{ type?: string; text?: string; thinking?: string }> };
546
+ isStreaming?: boolean;
547
+ hiddenThinkingLabel?: string;
548
+ outputPad?: number;
549
+ }): boolean {
550
+ const th = activeTheme();
551
+ if (!th || (comp.hiddenThinkingLabel ?? "Thinking...") !== "Thinking...") {
552
+ thinkingState.active.delete(comp);
553
+ syncThinkingTicker();
554
+ return false;
555
+ }
556
+ const activeRunIdx = activeThinkingRunIndex(comp.lastMessage, Boolean(comp.isStreaming));
557
+ const children = comp.contentContainer?.children ?? [];
558
+ const starts = thinkingState.starts.get(comp) ?? [];
559
+ const finished = thinkingState.finished.get(comp) ?? [];
560
+ let runIdx = 0;
561
+ let anyActive = false;
562
+ let anyReplaced = false;
563
+ for (const child of children) {
564
+ if (!child || typeof child !== "object" || !("child" in child) || !("onMouse" in child)) continue;
565
+ const region = child as { child: unknown };
566
+ if (isPlainTextComponent(region.child)) {
567
+ const isActive = activeRunIdx === runIdx;
568
+ if (isActive) {
569
+ anyActive = true;
570
+ starts[runIdx] ??= Date.now();
571
+ } else if (starts[runIdx] !== undefined && finished[runIdx] === undefined) {
572
+ // The run just ended: keep how long it took, so the settled label reads
573
+ // `Thought for 3s` instead of claiming to still think.
574
+ finished[runIdx] = `Thought for ${formatThinkingElapsed(Date.now() - starts[runIdx]!)}`;
575
+ }
576
+ region.child = new ThinkingLabelComponent(
577
+ comp.outputPad ?? 1,
578
+ isActive,
579
+ starts[runIdx],
580
+ activeTheme,
581
+ finished[runIdx],
582
+ );
583
+ anyReplaced = true;
584
+ }
585
+ runIdx++;
586
+ }
587
+ thinkingState.starts.set(comp, starts);
588
+ thinkingState.finished.set(comp, finished);
589
+ if (anyActive) thinkingState.active.add(comp);
590
+ else thinkingState.active.delete(comp);
591
+ syncThinkingTicker();
592
+ return anyReplaced;
593
+ }
594
+
595
+ if (AssistantMessageComponent?.prototype?.updateContent) {
596
+ const proto = AssistantMessageComponent.prototype as any;
597
+ patchOnce(proto, "updateContent", (origUpdateContent) => function (this: any, message: unknown, isStreaming?: boolean) {
598
+ const res = origUpdateContent.call(this, message, isStreaming);
599
+ patchThinkingInAssistantMessage(this);
600
+ return res;
601
+ });
602
+ }
603
+
604
+ export const __test = {
605
+ RELOAD_BOX_MAX_LINES,
606
+ };