@aoshizuku/pi-bettertui 0.1.1 → 0.1.2
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 +327 -327
- package/package.json +1 -1
- package/src/format.ts +165 -165
- package/src/gutter.ts +236 -236
- package/src/index.ts +660 -660
- package/src/segment.ts +311 -311
- package/src/shell-description.ts +75 -75
- package/src/thinking.ts +524 -524
- package/src/timeline.ts +881 -881
- package/src/tool-lines.ts +173 -173
- package/src/tool-row.ts +387 -387
- package/src/tool-summary.ts +237 -237
- package/src/types.ts +13 -13
package/src/thinking.ts
CHANGED
|
@@ -1,524 +1,524 @@
|
|
|
1
|
-
import {
|
|
2
|
-
AssistantMessageComponent,
|
|
3
|
-
getMarkdownTheme,
|
|
4
|
-
type Theme,
|
|
5
|
-
} from "@earendil-works/pi-coding-agent";
|
|
6
|
-
import {
|
|
7
|
-
type Component,
|
|
8
|
-
Markdown,
|
|
9
|
-
MouseRegion,
|
|
10
|
-
type TUI,
|
|
11
|
-
type TuiMouseEvent,
|
|
12
|
-
type TuiMouseEventResult,
|
|
13
|
-
truncateToWidth,
|
|
14
|
-
} from "@earendil-works/pi-tui";
|
|
15
|
-
|
|
16
|
-
import type { BetterTuiConfig } from "./config.js";
|
|
17
|
-
import { clickSegment, paintSegment } from "./fold-view.js";
|
|
18
|
-
import { formatDuration, tailThinkingRows, thoughtLabel } from "./format.js";
|
|
19
|
-
import { applyAssistantGutter, GUTTER } from "./gutter.js";
|
|
20
|
-
import { type InterruptNoteHooks, replaceInterruptNote } from "./interrupt.js";
|
|
21
|
-
import { thinkingAnchor, thinkingRuns, type ThinkingRun } from "./segment.js";
|
|
22
|
-
import type { ActivityTimeline } from "./timeline.js";
|
|
23
|
-
|
|
24
|
-
const PATCH_KEY = Symbol.for("pi-bettertui.thinking");
|
|
25
|
-
/** The header starts in the gutter's content column (DESIGN.md §2.1). */
|
|
26
|
-
const HEADER_INDENT = GUTTER;
|
|
27
|
-
const HEADER_PAD = " ".repeat(HEADER_INDENT);
|
|
28
|
-
/** The streaming tail and the expanded thought sit two columns further in, under the header. */
|
|
29
|
-
const BODY_INDENT = GUTTER + 2;
|
|
30
|
-
const BODY_PAD = " ".repeat(BODY_INDENT);
|
|
31
|
-
const expandedState = new WeakMap<object, boolean>();
|
|
32
|
-
/** Identifies patches made by this module instance; each /reload loads a new one. */
|
|
33
|
-
const MODULE_OWNER = {};
|
|
34
|
-
/** Undo functions of every prototype patched by this module instance. */
|
|
35
|
-
const cleanups = new Set<() => void>();
|
|
36
|
-
|
|
37
|
-
export interface ThinkingPatchHooks {
|
|
38
|
-
/** The plugin as a whole: the gutter applies even when thinking is left to pi. */
|
|
39
|
-
isEnabled: () => boolean;
|
|
40
|
-
/** Thinking window height; 0 keeps pi's native thinking block. */
|
|
41
|
-
getLines: () => number;
|
|
42
|
-
getTheme: () => Theme;
|
|
43
|
-
getActiveTui: () => TUI | undefined;
|
|
44
|
-
/** Fold segments (fold-more.md §5.6); absent or with fold off, thinking renders as before. */
|
|
45
|
-
fold?: FoldHooks;
|
|
46
|
-
/** pi's abort note under an aborted message (DESIGN.md §9); absent, pi's note stays. */
|
|
47
|
-
interrupt?: InterruptNoteHooks;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export interface FoldHooks {
|
|
51
|
-
timeline: ActivityTimeline;
|
|
52
|
-
getConfig: () => BetterTuiConfig;
|
|
53
|
-
getCwd: () => string;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
interface PatchRecord {
|
|
57
|
-
/** Missing on patches from builds before the owner check. */
|
|
58
|
-
owner?: object;
|
|
59
|
-
hooks: ThinkingPatchHooks;
|
|
60
|
-
originalUpdateContent: (...args: any[]) => any;
|
|
61
|
-
originalSetHideThinkingBlock: (...args: any[]) => any;
|
|
62
|
-
patchedUpdateContent: (...args: any[]) => any;
|
|
63
|
-
patchedSetHideThinkingBlock: (...args: any[]) => any;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
interface ThinkingViewOptions {
|
|
67
|
-
text: string;
|
|
68
|
-
streaming: boolean;
|
|
69
|
-
expanded: boolean;
|
|
70
|
-
startedAt: number;
|
|
71
|
-
durationMs: number;
|
|
72
|
-
pad: number;
|
|
73
|
-
getTheme: () => Theme;
|
|
74
|
-
lineCount: number;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export class ThinkingView implements Component {
|
|
78
|
-
private text: string;
|
|
79
|
-
private streaming: boolean;
|
|
80
|
-
private expanded: boolean;
|
|
81
|
-
private startedAt: number;
|
|
82
|
-
private durationMs: number;
|
|
83
|
-
private pad: number;
|
|
84
|
-
private getTheme: () => Theme;
|
|
85
|
-
private lineCount: number;
|
|
86
|
-
private markdown?: Markdown;
|
|
87
|
-
private markdownText = "";
|
|
88
|
-
private markdownTheme?: ReturnType<typeof getMarkdownTheme>;
|
|
89
|
-
private markdownPalette = "";
|
|
90
|
-
|
|
91
|
-
constructor(options: ThinkingViewOptions) {
|
|
92
|
-
this.text = options.text;
|
|
93
|
-
this.streaming = options.streaming;
|
|
94
|
-
this.expanded = options.expanded;
|
|
95
|
-
this.startedAt = options.startedAt;
|
|
96
|
-
this.durationMs = options.durationMs;
|
|
97
|
-
this.pad = options.pad;
|
|
98
|
-
this.getTheme = options.getTheme;
|
|
99
|
-
this.lineCount = options.lineCount;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
render(width: number): string[] {
|
|
103
|
-
if (width <= 0) return [];
|
|
104
|
-
const theme = this.getTheme();
|
|
105
|
-
const pad = " ".repeat(Math.max(0, this.pad));
|
|
106
|
-
const duration = this.streaming
|
|
107
|
-
? Math.max(0, Date.now() - this.startedAt)
|
|
108
|
-
: this.durationMs;
|
|
109
|
-
const header = truncateToWidth(this.renderHeader(theme, duration), width, "…");
|
|
110
|
-
if (this.expanded) {
|
|
111
|
-
return [header, ...this.renderExpanded(width, pad, theme)];
|
|
112
|
-
}
|
|
113
|
-
if (this.streaming) {
|
|
114
|
-
return [header, ...this.renderTail(width, pad, theme)];
|
|
115
|
-
}
|
|
116
|
-
return [header];
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
invalidate(): void {
|
|
120
|
-
this.markdown = undefined;
|
|
121
|
-
this.markdownText = "";
|
|
122
|
-
this.markdownPalette = "";
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* A process line, not an event (DESIGN.md §2.1): no marker, the gutter's column 0 stays blank
|
|
127
|
-
* and the whole line is dim from the content column on.
|
|
128
|
-
*/
|
|
129
|
-
private renderHeader(theme: Theme, duration: number): string {
|
|
130
|
-
const label = this.streaming ? "Thinking…" : thoughtLabel(duration);
|
|
131
|
-
const elapsed = this.streaming && duration >= 1_000 ? ` ${formatDuration(duration)}` : "";
|
|
132
|
-
return `${" ".repeat(Math.max(0, this.pad) + HEADER_INDENT)}${theme.fg("dim", label + elapsed)}`;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
private renderTail(width: number, pad: string, theme: Theme): string[] {
|
|
136
|
-
// Wrapped rows, not clipped lines (DESIGN.md §2.1). The "… " for hidden rows hangs in the two
|
|
137
|
-
// columns between the header and the body, so the wrap width is the same whether or not it shows.
|
|
138
|
-
const contentWidth = Math.max(1, width - this.pad - BODY_INDENT);
|
|
139
|
-
const { rows, hidden } = tailThinkingRows(this.text, Math.max(1, this.lineCount), contentWidth);
|
|
140
|
-
const output: string[] = [];
|
|
141
|
-
for (let index = 0; index < this.lineCount; index++) {
|
|
142
|
-
const row = rows[index];
|
|
143
|
-
if (row === undefined) {
|
|
144
|
-
output.push("");
|
|
145
|
-
continue;
|
|
146
|
-
}
|
|
147
|
-
const lead = hidden && index === 0 ? "… " : " ";
|
|
148
|
-
output.push(`${pad}${HEADER_PAD}${theme.italic(theme.fg("thinkingText", lead + row))}`);
|
|
149
|
-
}
|
|
150
|
-
return output;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
private renderExpanded(width: number, pad: string, theme: Theme): string[] {
|
|
154
|
-
const markdownTheme = getMarkdownTheme();
|
|
155
|
-
const palette = [theme.fg("thinkingText", "x"), theme.bold("x"), theme.italic("x")].join("|");
|
|
156
|
-
if (
|
|
157
|
-
!this.markdown ||
|
|
158
|
-
this.markdownText !== this.text ||
|
|
159
|
-
this.markdownTheme !== markdownTheme ||
|
|
160
|
-
this.markdownPalette !== palette
|
|
161
|
-
) {
|
|
162
|
-
this.markdown = new Markdown(this.text, 0, 0, markdownTheme, {
|
|
163
|
-
color: (line: string) => theme.fg("thinkingText", line),
|
|
164
|
-
italic: true,
|
|
165
|
-
});
|
|
166
|
-
this.markdownText = this.text;
|
|
167
|
-
this.markdownTheme = markdownTheme;
|
|
168
|
-
this.markdownPalette = palette;
|
|
169
|
-
}
|
|
170
|
-
const contentWidth = Math.max(1, width - this.pad - BODY_INDENT);
|
|
171
|
-
const lines = this.markdown.render(contentWidth);
|
|
172
|
-
return lines.map((line) => truncateToWidth(`${pad}${BODY_PAD}${line}`, width, "…"));
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export function installThinkingPatch(hooks: ThinkingPatchHooks): () => void {
|
|
177
|
-
return patchPrototype(AssistantMessageComponent.prototype as any, hooks);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Pi loads extensions through its own module instance. Importing
|
|
182
|
-
* `AssistantMessageComponent` here can therefore give us a different class
|
|
183
|
-
* object than the one pi renders. Find the live instances in the TUI tree and
|
|
184
|
-
* patch their actual prototype, then rebuild what is already on screen.
|
|
185
|
-
*/
|
|
186
|
-
export function installLiveThinkingPatch(tui: unknown, hooks: ThinkingPatchHooks): boolean {
|
|
187
|
-
const components = collectAssistantComponents(tui);
|
|
188
|
-
if (components.length === 0) return false;
|
|
189
|
-
const prototypes = new Set<object>();
|
|
190
|
-
for (const component of components) {
|
|
191
|
-
const proto = Object.getPrototypeOf(component);
|
|
192
|
-
if (proto && typeof proto === "object") prototypes.add(proto);
|
|
193
|
-
}
|
|
194
|
-
for (const proto of prototypes) patchPrototype(proto as any, hooks);
|
|
195
|
-
for (const component of components) {
|
|
196
|
-
const lastMessage = (component as any).lastMessage;
|
|
197
|
-
if (lastMessage) (component as any).updateContent(lastMessage, Boolean((component as any).isStreaming));
|
|
198
|
-
}
|
|
199
|
-
return true;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/** Restore pi's own methods on every prototype this module instance patched (shutdown or reload). */
|
|
203
|
-
export function uninstallThinkingPatches(): void {
|
|
204
|
-
for (const cleanup of [...cleanups]) cleanup();
|
|
205
|
-
cleanups.clear();
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
/** Remove a patch left behind by an earlier load of this extension, if pi still runs it. */
|
|
209
|
-
function unwrapStale(proto: any, record: PatchRecord): void {
|
|
210
|
-
if (proto.updateContent === record.patchedUpdateContent) proto.updateContent = record.originalUpdateContent;
|
|
211
|
-
if (proto.setHideThinkingBlock === record.patchedSetHideThinkingBlock) {
|
|
212
|
-
proto.setHideThinkingBlock = record.originalSetHideThinkingBlock;
|
|
213
|
-
}
|
|
214
|
-
proto[PATCH_KEY] = undefined;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
function patchPrototype(proto: any, hooks: ThinkingPatchHooks): () => void {
|
|
218
|
-
const existing = proto[PATCH_KEY] as PatchRecord | undefined;
|
|
219
|
-
if (existing?.owner === MODULE_OWNER) {
|
|
220
|
-
existing.hooks = hooks;
|
|
221
|
-
return () => {};
|
|
222
|
-
}
|
|
223
|
-
// The patch lives on pi's prototype and outlives a /reload; the earlier module's code would
|
|
224
|
-
// keep rendering with the old layout, so take it off before installing this module's.
|
|
225
|
-
if (existing) unwrapStale(proto, existing);
|
|
226
|
-
|
|
227
|
-
const originalUpdateContent = proto.updateContent;
|
|
228
|
-
const originalSetHideThinkingBlock = proto.setHideThinkingBlock;
|
|
229
|
-
if (typeof originalUpdateContent !== "function" || typeof originalSetHideThinkingBlock !== "function") {
|
|
230
|
-
return () => {};
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// Read hooks through the record: a later install in this module instance replaces them.
|
|
234
|
-
const patchedUpdateContent = function (this: any, message: any, isStreaming = this.isStreaming): any {
|
|
235
|
-
if (!expandedState.has(this)) expandedState.set(this, false);
|
|
236
|
-
const result = originalUpdateContent.call(this, message, isStreaming);
|
|
237
|
-
const current = record.hooks;
|
|
238
|
-
const enabled = current.isEnabled();
|
|
239
|
-
// Order matters (fold-more.md §5.6): place the blocks first, so the slots below find their
|
|
240
|
-
// segment; the gutter runs last and must not see a slot as padded text.
|
|
241
|
-
const fold = enabled && current.fold?.timeline.foldEnabled ? current.fold : undefined;
|
|
242
|
-
fold?.timeline.ingestAssistant(message, Boolean(isStreaming));
|
|
243
|
-
if (enabled && current.getLines() > 0) decorateThinking(this, message, Boolean(isStreaming), current, fold);
|
|
244
|
-
applyAssistantGutter(this, enabled, current.getTheme);
|
|
245
|
-
if (enabled && current.interrupt) replaceInterruptNote(this, message, current.interrupt);
|
|
246
|
-
return result;
|
|
247
|
-
};
|
|
248
|
-
|
|
249
|
-
const patchedSetHideThinkingBlock = function (this: any, hide: boolean): any {
|
|
250
|
-
// Pi's Ctrl+T toggles this flag. Reuse it as "show details": the first
|
|
251
|
-
// press (hide=true) expands the thought this plugin collapsed by default.
|
|
252
|
-
expandedState.set(this, hide);
|
|
253
|
-
const fold = record.hooks.fold;
|
|
254
|
-
if (fold) fold.timeline.thinkingDetails = hide;
|
|
255
|
-
return originalSetHideThinkingBlock.call(this, hide);
|
|
256
|
-
};
|
|
257
|
-
|
|
258
|
-
const record: PatchRecord = {
|
|
259
|
-
owner: MODULE_OWNER,
|
|
260
|
-
hooks,
|
|
261
|
-
originalUpdateContent,
|
|
262
|
-
originalSetHideThinkingBlock,
|
|
263
|
-
patchedUpdateContent,
|
|
264
|
-
patchedSetHideThinkingBlock,
|
|
265
|
-
};
|
|
266
|
-
proto[PATCH_KEY] = record;
|
|
267
|
-
proto.updateContent = patchedUpdateContent;
|
|
268
|
-
proto.setHideThinkingBlock = patchedSetHideThinkingBlock;
|
|
269
|
-
|
|
270
|
-
const cleanup = (): void => {
|
|
271
|
-
cleanups.delete(cleanup);
|
|
272
|
-
if (proto[PATCH_KEY] !== record) return;
|
|
273
|
-
unwrapStale(proto, record);
|
|
274
|
-
};
|
|
275
|
-
cleanups.add(cleanup);
|
|
276
|
-
return cleanup;
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
function collectAssistantComponents(root: unknown): any[] {
|
|
280
|
-
const out: any[] = [];
|
|
281
|
-
const stack: unknown[] = [root];
|
|
282
|
-
const seen = new Set<object>();
|
|
283
|
-
while (stack.length > 0) {
|
|
284
|
-
const value = stack.pop();
|
|
285
|
-
if (!value || typeof value !== "object" || seen.has(value)) continue;
|
|
286
|
-
seen.add(value);
|
|
287
|
-
const candidate = value as any;
|
|
288
|
-
if (
|
|
289
|
-
candidate.contentContainer &&
|
|
290
|
-
typeof candidate.updateContent === "function" &&
|
|
291
|
-
typeof candidate.setHideThinkingBlock === "function" &&
|
|
292
|
-
candidate.lastMessage?.role === "assistant"
|
|
293
|
-
) {
|
|
294
|
-
out.push(candidate);
|
|
295
|
-
}
|
|
296
|
-
if (Array.isArray(candidate.children)) {
|
|
297
|
-
for (const child of candidate.children) stack.push(child);
|
|
298
|
-
}
|
|
299
|
-
if (candidate.child) stack.push(candidate.child);
|
|
300
|
-
}
|
|
301
|
-
return out;
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
function decorateThinking(
|
|
305
|
-
component: any,
|
|
306
|
-
message: any,
|
|
307
|
-
streaming: boolean,
|
|
308
|
-
hooks: ThinkingPatchHooks,
|
|
309
|
-
fold?: FoldHooks,
|
|
310
|
-
): void {
|
|
311
|
-
const container = component.contentContainer;
|
|
312
|
-
if (!container || !Array.isArray(container.children)) return;
|
|
313
|
-
const runs = regionRuns(component, message);
|
|
314
|
-
if (runs.length === 0) return;
|
|
315
|
-
|
|
316
|
-
const regions = container.children.filter(isThinkingRegion);
|
|
317
|
-
if (regions.length === 0) return;
|
|
318
|
-
const timestamp = typeof message?.timestamp === "number" ? message.timestamp : undefined;
|
|
319
|
-
|
|
320
|
-
const expanded = expandedState.get(component) ?? false;
|
|
321
|
-
const phaseStreaming = streaming && !hasAnswer(message);
|
|
322
|
-
const startedAt = typeof message?.timestamp === "number" ? message.timestamp : Date.now();
|
|
323
|
-
const durationMs = typeof message?.durationMs === "number"
|
|
324
|
-
? message.durationMs
|
|
325
|
-
: streaming
|
|
326
|
-
? Math.max(0, Date.now() - startedAt)
|
|
327
|
-
: 0;
|
|
328
|
-
for (let index = 0; index < regions.length; index++) {
|
|
329
|
-
const region = regions[index]!;
|
|
330
|
-
// pi draws one region per run with text, minus hidden runs when the hidden label is empty.
|
|
331
|
-
const run = runs[index];
|
|
332
|
-
if (!run) continue;
|
|
333
|
-
const text = run.text;
|
|
334
|
-
const view = new ThinkingView({
|
|
335
|
-
text,
|
|
336
|
-
streaming: phaseStreaming,
|
|
337
|
-
expanded,
|
|
338
|
-
startedAt,
|
|
339
|
-
durationMs,
|
|
340
|
-
// Laid out on the shared gutter (DESIGN.md §2), whatever pi's outputPad is.
|
|
341
|
-
pad: 0,
|
|
342
|
-
getTheme: hooks.getTheme,
|
|
343
|
-
lineCount: hooks.getLines(),
|
|
344
|
-
});
|
|
345
|
-
const wrapped = new MouseRegion(view, (event) => {
|
|
346
|
-
if (event.type !== "click" || event.button !== "left") return undefined;
|
|
347
|
-
expandedState.set(component, !(expandedState.get(component) ?? false));
|
|
348
|
-
const lastMessage = component.lastMessage;
|
|
349
|
-
if (lastMessage) component.updateContent(lastMessage, Boolean(component.isStreaming));
|
|
350
|
-
hooks.getActiveTui()?.requestRender();
|
|
351
|
-
return { handled: true };
|
|
352
|
-
});
|
|
353
|
-
// With fold on, the slot decides on every render whether it draws this view, its whole
|
|
354
|
-
// segment, or nothing (fold-more.md §5.6).
|
|
355
|
-
const slot = fold && timestamp !== undefined
|
|
356
|
-
? new ThinkingSlot(thinkingAnchor(timestamp, run.runIndex), wrapped, fold, hooks)
|
|
357
|
-
: wrapped;
|
|
358
|
-
const childIndex = container.children.indexOf(region);
|
|
359
|
-
if (childIndex >= 0) container.children[childIndex] = slot;
|
|
360
|
-
}
|
|
361
|
-
// pi's blank lines stay where pi puts them, including the one between a thought and the text
|
|
362
|
-
// after it; under fold they only drop next to slots that draw nothing.
|
|
363
|
-
if (fold) replaceSpacersWithGaps(container);
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
/**
|
|
367
|
-
* The runs pi draws a region for, in order (fold-more.md §2.3): every run with text gets a run
|
|
368
|
-
* index, but a hidden run gets no region when the hidden label is empty.
|
|
369
|
-
*/
|
|
370
|
-
export function regionRuns(component: any, message: unknown): ThinkingRun[] {
|
|
371
|
-
const runs = thinkingRuns((message as { content?: unknown } | undefined)?.content);
|
|
372
|
-
const hideAll = component?.hideThinkingBlock === true;
|
|
373
|
-
const label = typeof component?.hiddenThinkingLabel === "string" ? component.hiddenThinkingLabel : "Thinking...";
|
|
374
|
-
if (label.trim()) return runs;
|
|
375
|
-
const overrides = component?.thinkingVisibilityOverrides;
|
|
376
|
-
const override = (run: number): boolean | undefined =>
|
|
377
|
-
overrides && typeof overrides.get === "function" ? overrides.get(run) : undefined;
|
|
378
|
-
return runs.filter((run) => !(override(run.runIndex) ?? hideAll));
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
/** A thinking region under fold: its own view, its segment's host output, or nothing. */
|
|
382
|
-
export class ThinkingSlot implements Component {
|
|
383
|
-
private targets: string[] = [];
|
|
384
|
-
|
|
385
|
-
constructor(
|
|
386
|
-
readonly anchor: string,
|
|
387
|
-
private readonly view: Component,
|
|
388
|
-
private readonly fold: FoldHooks,
|
|
389
|
-
private readonly hooks: ThinkingPatchHooks,
|
|
390
|
-
) {}
|
|
391
|
-
|
|
392
|
-
/** Whether this slot draws anything; spacers before it only show when something does. */
|
|
393
|
-
visible(): boolean {
|
|
394
|
-
return this.fold.timeline.foldRole(this.anchor).kind !== "hidden";
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
render(width: number): string[] {
|
|
398
|
-
const role = this.fold.timeline.foldRole(this.anchor);
|
|
399
|
-
if (role.kind === "hidden") return [];
|
|
400
|
-
if (role.kind === "single") return [...this.view.render(width)];
|
|
401
|
-
const paint = paintSegment(role.segment, width, {
|
|
402
|
-
timeline: this.fold.timeline,
|
|
403
|
-
config: this.fold.getConfig(),
|
|
404
|
-
theme: this.hooks.getTheme(),
|
|
405
|
-
cwd: this.fold.getCwd(),
|
|
406
|
-
expanded: this.fold.timeline.globalExpanded,
|
|
407
|
-
});
|
|
408
|
-
this.targets = paint.targets;
|
|
409
|
-
return paint.lines;
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
413
|
-
const role = this.fold.timeline.foldRole(this.anchor);
|
|
414
|
-
if (role.kind === "hidden") return undefined;
|
|
415
|
-
if (role.kind === "single") return this.view.handleMouse?.(event) as TuiMouseEventResult | undefined;
|
|
416
|
-
if (event.type !== "click" || event.button !== "left") return undefined;
|
|
417
|
-
const timeline = this.fold.timeline;
|
|
418
|
-
if (!clickSegment(timeline, role.segment, this.targets, event.y)) return undefined;
|
|
419
|
-
this.hooks.getActiveTui()?.requestRender();
|
|
420
|
-
return { handled: true };
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
invalidate(): void {
|
|
424
|
-
this.view.invalidate();
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
/**
|
|
429
|
-
* pi's blank line before a visible block, drawn only when something visible follows it in the
|
|
430
|
-
* same message before the next gap (fold-more.md §5.6). A message whose slots are all hidden
|
|
431
|
-
* then takes no lines at all, and a hidden slot between two gaps does not leave two blank lines.
|
|
432
|
-
*/
|
|
433
|
-
export class GapSlot implements Component {
|
|
434
|
-
constructor(private readonly siblings: { children: unknown[] }) {}
|
|
435
|
-
|
|
436
|
-
render(_width: number): string[] {
|
|
437
|
-
const children = this.siblings.children;
|
|
438
|
-
const index = children.indexOf(this);
|
|
439
|
-
if (index < 0) return [""];
|
|
440
|
-
for (let next = index + 1; next < children.length; next++) {
|
|
441
|
-
const child = children[next];
|
|
442
|
-
if (child instanceof GapSlot) return [];
|
|
443
|
-
if (child instanceof ThinkingSlot && !child.visible()) continue;
|
|
444
|
-
return [""];
|
|
445
|
-
}
|
|
446
|
-
return [];
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
invalidate(): void {}
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
function replaceSpacersWithGaps(container: { children: unknown[] }): void {
|
|
453
|
-
const children = container.children;
|
|
454
|
-
for (let index = 0; index < children.length; index++) {
|
|
455
|
-
const child = children[index] as { lines?: unknown };
|
|
456
|
-
if (isSpacer(child) && child.lines === 1) children[index] = new GapSlot(container);
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
/**
|
|
461
|
-
* pi-tui's Spacer: a line count, `setLines`, and a render that yields only empty lines. pi may
|
|
462
|
-
* load pi-tui through another module instance, so match the shape rather than the class.
|
|
463
|
-
*/
|
|
464
|
-
export function isSpacer(value: unknown): boolean {
|
|
465
|
-
if (!value || typeof value !== "object") return false;
|
|
466
|
-
const candidate = value as { lines?: unknown; setLines?: unknown; render?: unknown };
|
|
467
|
-
if (typeof candidate.lines !== "number" || candidate.lines < 1) return false;
|
|
468
|
-
if (typeof candidate.setLines !== "function" || typeof candidate.render !== "function") return false;
|
|
469
|
-
// Containers and padded text also render blank lines; a spacer has neither children nor content.
|
|
470
|
-
if ("children" in candidate || "child" in candidate || "text" in candidate) return false;
|
|
471
|
-
let lines: unknown;
|
|
472
|
-
try {
|
|
473
|
-
lines = (candidate.render as (width: number) => unknown).call(candidate, 1);
|
|
474
|
-
} catch {
|
|
475
|
-
return false;
|
|
476
|
-
}
|
|
477
|
-
return Array.isArray(lines) && lines.length === candidate.lines && lines.every((line) => line === "");
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
function isThinkingRegion(value: unknown): boolean {
|
|
481
|
-
if (!value || typeof value !== "object") return false;
|
|
482
|
-
const region = value as { child?: unknown; onMouse?: unknown };
|
|
483
|
-
return Boolean(region.child && typeof region.onMouse === "function");
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
export function collectThinkingRuns(message: unknown): string[] {
|
|
487
|
-
if (!message || typeof message !== "object") return [];
|
|
488
|
-
const content = (message as { content?: unknown }).content;
|
|
489
|
-
if (!Array.isArray(content)) return [];
|
|
490
|
-
const runs: string[] = [];
|
|
491
|
-
let current: string[] = [];
|
|
492
|
-
const flush = () => {
|
|
493
|
-
const text = current.join("\n\n").trim();
|
|
494
|
-
if (text) runs.push(text);
|
|
495
|
-
current = [];
|
|
496
|
-
};
|
|
497
|
-
for (const item of content) {
|
|
498
|
-
if (!item || typeof item !== "object") {
|
|
499
|
-
flush();
|
|
500
|
-
continue;
|
|
501
|
-
}
|
|
502
|
-
const block = item as { type?: unknown; thinking?: unknown; text?: unknown };
|
|
503
|
-
if (block.type === "thinking") {
|
|
504
|
-
const text = typeof block.thinking === "string" ? block.thinking : typeof block.text === "string" ? block.text : "";
|
|
505
|
-
if (text.trim()) current.push(text);
|
|
506
|
-
} else {
|
|
507
|
-
flush();
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
flush();
|
|
511
|
-
return runs;
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
export function hasAnswer(message: unknown): boolean {
|
|
515
|
-
if (!message || typeof message !== "object") return false;
|
|
516
|
-
const content = (message as { content?: unknown }).content;
|
|
517
|
-
if (!Array.isArray(content)) return false;
|
|
518
|
-
return content.some((item) => {
|
|
519
|
-
if (!item || typeof item !== "object") return false;
|
|
520
|
-
const block = item as { type?: unknown; text?: unknown };
|
|
521
|
-
if (block.type === "toolCall") return true;
|
|
522
|
-
return block.type === "text" && typeof block.text === "string" && block.text.trim().length > 0;
|
|
523
|
-
});
|
|
524
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
AssistantMessageComponent,
|
|
3
|
+
getMarkdownTheme,
|
|
4
|
+
type Theme,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import {
|
|
7
|
+
type Component,
|
|
8
|
+
Markdown,
|
|
9
|
+
MouseRegion,
|
|
10
|
+
type TUI,
|
|
11
|
+
type TuiMouseEvent,
|
|
12
|
+
type TuiMouseEventResult,
|
|
13
|
+
truncateToWidth,
|
|
14
|
+
} from "@earendil-works/pi-tui";
|
|
15
|
+
|
|
16
|
+
import type { BetterTuiConfig } from "./config.js";
|
|
17
|
+
import { clickSegment, paintSegment } from "./fold-view.js";
|
|
18
|
+
import { formatDuration, tailThinkingRows, thoughtLabel } from "./format.js";
|
|
19
|
+
import { applyAssistantGutter, GUTTER } from "./gutter.js";
|
|
20
|
+
import { type InterruptNoteHooks, replaceInterruptNote } from "./interrupt.js";
|
|
21
|
+
import { thinkingAnchor, thinkingRuns, type ThinkingRun } from "./segment.js";
|
|
22
|
+
import type { ActivityTimeline } from "./timeline.js";
|
|
23
|
+
|
|
24
|
+
const PATCH_KEY = Symbol.for("pi-bettertui.thinking");
|
|
25
|
+
/** The header starts in the gutter's content column (DESIGN.md §2.1). */
|
|
26
|
+
const HEADER_INDENT = GUTTER;
|
|
27
|
+
const HEADER_PAD = " ".repeat(HEADER_INDENT);
|
|
28
|
+
/** The streaming tail and the expanded thought sit two columns further in, under the header. */
|
|
29
|
+
const BODY_INDENT = GUTTER + 2;
|
|
30
|
+
const BODY_PAD = " ".repeat(BODY_INDENT);
|
|
31
|
+
const expandedState = new WeakMap<object, boolean>();
|
|
32
|
+
/** Identifies patches made by this module instance; each /reload loads a new one. */
|
|
33
|
+
const MODULE_OWNER = {};
|
|
34
|
+
/** Undo functions of every prototype patched by this module instance. */
|
|
35
|
+
const cleanups = new Set<() => void>();
|
|
36
|
+
|
|
37
|
+
export interface ThinkingPatchHooks {
|
|
38
|
+
/** The plugin as a whole: the gutter applies even when thinking is left to pi. */
|
|
39
|
+
isEnabled: () => boolean;
|
|
40
|
+
/** Thinking window height; 0 keeps pi's native thinking block. */
|
|
41
|
+
getLines: () => number;
|
|
42
|
+
getTheme: () => Theme;
|
|
43
|
+
getActiveTui: () => TUI | undefined;
|
|
44
|
+
/** Fold segments (fold-more.md §5.6); absent or with fold off, thinking renders as before. */
|
|
45
|
+
fold?: FoldHooks;
|
|
46
|
+
/** pi's abort note under an aborted message (DESIGN.md §9); absent, pi's note stays. */
|
|
47
|
+
interrupt?: InterruptNoteHooks;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface FoldHooks {
|
|
51
|
+
timeline: ActivityTimeline;
|
|
52
|
+
getConfig: () => BetterTuiConfig;
|
|
53
|
+
getCwd: () => string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface PatchRecord {
|
|
57
|
+
/** Missing on patches from builds before the owner check. */
|
|
58
|
+
owner?: object;
|
|
59
|
+
hooks: ThinkingPatchHooks;
|
|
60
|
+
originalUpdateContent: (...args: any[]) => any;
|
|
61
|
+
originalSetHideThinkingBlock: (...args: any[]) => any;
|
|
62
|
+
patchedUpdateContent: (...args: any[]) => any;
|
|
63
|
+
patchedSetHideThinkingBlock: (...args: any[]) => any;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface ThinkingViewOptions {
|
|
67
|
+
text: string;
|
|
68
|
+
streaming: boolean;
|
|
69
|
+
expanded: boolean;
|
|
70
|
+
startedAt: number;
|
|
71
|
+
durationMs: number;
|
|
72
|
+
pad: number;
|
|
73
|
+
getTheme: () => Theme;
|
|
74
|
+
lineCount: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export class ThinkingView implements Component {
|
|
78
|
+
private text: string;
|
|
79
|
+
private streaming: boolean;
|
|
80
|
+
private expanded: boolean;
|
|
81
|
+
private startedAt: number;
|
|
82
|
+
private durationMs: number;
|
|
83
|
+
private pad: number;
|
|
84
|
+
private getTheme: () => Theme;
|
|
85
|
+
private lineCount: number;
|
|
86
|
+
private markdown?: Markdown;
|
|
87
|
+
private markdownText = "";
|
|
88
|
+
private markdownTheme?: ReturnType<typeof getMarkdownTheme>;
|
|
89
|
+
private markdownPalette = "";
|
|
90
|
+
|
|
91
|
+
constructor(options: ThinkingViewOptions) {
|
|
92
|
+
this.text = options.text;
|
|
93
|
+
this.streaming = options.streaming;
|
|
94
|
+
this.expanded = options.expanded;
|
|
95
|
+
this.startedAt = options.startedAt;
|
|
96
|
+
this.durationMs = options.durationMs;
|
|
97
|
+
this.pad = options.pad;
|
|
98
|
+
this.getTheme = options.getTheme;
|
|
99
|
+
this.lineCount = options.lineCount;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
render(width: number): string[] {
|
|
103
|
+
if (width <= 0) return [];
|
|
104
|
+
const theme = this.getTheme();
|
|
105
|
+
const pad = " ".repeat(Math.max(0, this.pad));
|
|
106
|
+
const duration = this.streaming
|
|
107
|
+
? Math.max(0, Date.now() - this.startedAt)
|
|
108
|
+
: this.durationMs;
|
|
109
|
+
const header = truncateToWidth(this.renderHeader(theme, duration), width, "…");
|
|
110
|
+
if (this.expanded) {
|
|
111
|
+
return [header, ...this.renderExpanded(width, pad, theme)];
|
|
112
|
+
}
|
|
113
|
+
if (this.streaming) {
|
|
114
|
+
return [header, ...this.renderTail(width, pad, theme)];
|
|
115
|
+
}
|
|
116
|
+
return [header];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
invalidate(): void {
|
|
120
|
+
this.markdown = undefined;
|
|
121
|
+
this.markdownText = "";
|
|
122
|
+
this.markdownPalette = "";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A process line, not an event (DESIGN.md §2.1): no marker, the gutter's column 0 stays blank
|
|
127
|
+
* and the whole line is dim from the content column on.
|
|
128
|
+
*/
|
|
129
|
+
private renderHeader(theme: Theme, duration: number): string {
|
|
130
|
+
const label = this.streaming ? "Thinking…" : thoughtLabel(duration);
|
|
131
|
+
const elapsed = this.streaming && duration >= 1_000 ? ` ${formatDuration(duration)}` : "";
|
|
132
|
+
return `${" ".repeat(Math.max(0, this.pad) + HEADER_INDENT)}${theme.fg("dim", label + elapsed)}`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private renderTail(width: number, pad: string, theme: Theme): string[] {
|
|
136
|
+
// Wrapped rows, not clipped lines (DESIGN.md §2.1). The "… " for hidden rows hangs in the two
|
|
137
|
+
// columns between the header and the body, so the wrap width is the same whether or not it shows.
|
|
138
|
+
const contentWidth = Math.max(1, width - this.pad - BODY_INDENT);
|
|
139
|
+
const { rows, hidden } = tailThinkingRows(this.text, Math.max(1, this.lineCount), contentWidth);
|
|
140
|
+
const output: string[] = [];
|
|
141
|
+
for (let index = 0; index < this.lineCount; index++) {
|
|
142
|
+
const row = rows[index];
|
|
143
|
+
if (row === undefined) {
|
|
144
|
+
output.push("");
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
const lead = hidden && index === 0 ? "… " : " ";
|
|
148
|
+
output.push(`${pad}${HEADER_PAD}${theme.italic(theme.fg("thinkingText", lead + row))}`);
|
|
149
|
+
}
|
|
150
|
+
return output;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
private renderExpanded(width: number, pad: string, theme: Theme): string[] {
|
|
154
|
+
const markdownTheme = getMarkdownTheme();
|
|
155
|
+
const palette = [theme.fg("thinkingText", "x"), theme.bold("x"), theme.italic("x")].join("|");
|
|
156
|
+
if (
|
|
157
|
+
!this.markdown ||
|
|
158
|
+
this.markdownText !== this.text ||
|
|
159
|
+
this.markdownTheme !== markdownTheme ||
|
|
160
|
+
this.markdownPalette !== palette
|
|
161
|
+
) {
|
|
162
|
+
this.markdown = new Markdown(this.text, 0, 0, markdownTheme, {
|
|
163
|
+
color: (line: string) => theme.fg("thinkingText", line),
|
|
164
|
+
italic: true,
|
|
165
|
+
});
|
|
166
|
+
this.markdownText = this.text;
|
|
167
|
+
this.markdownTheme = markdownTheme;
|
|
168
|
+
this.markdownPalette = palette;
|
|
169
|
+
}
|
|
170
|
+
const contentWidth = Math.max(1, width - this.pad - BODY_INDENT);
|
|
171
|
+
const lines = this.markdown.render(contentWidth);
|
|
172
|
+
return lines.map((line) => truncateToWidth(`${pad}${BODY_PAD}${line}`, width, "…"));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function installThinkingPatch(hooks: ThinkingPatchHooks): () => void {
|
|
177
|
+
return patchPrototype(AssistantMessageComponent.prototype as any, hooks);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Pi loads extensions through its own module instance. Importing
|
|
182
|
+
* `AssistantMessageComponent` here can therefore give us a different class
|
|
183
|
+
* object than the one pi renders. Find the live instances in the TUI tree and
|
|
184
|
+
* patch their actual prototype, then rebuild what is already on screen.
|
|
185
|
+
*/
|
|
186
|
+
export function installLiveThinkingPatch(tui: unknown, hooks: ThinkingPatchHooks): boolean {
|
|
187
|
+
const components = collectAssistantComponents(tui);
|
|
188
|
+
if (components.length === 0) return false;
|
|
189
|
+
const prototypes = new Set<object>();
|
|
190
|
+
for (const component of components) {
|
|
191
|
+
const proto = Object.getPrototypeOf(component);
|
|
192
|
+
if (proto && typeof proto === "object") prototypes.add(proto);
|
|
193
|
+
}
|
|
194
|
+
for (const proto of prototypes) patchPrototype(proto as any, hooks);
|
|
195
|
+
for (const component of components) {
|
|
196
|
+
const lastMessage = (component as any).lastMessage;
|
|
197
|
+
if (lastMessage) (component as any).updateContent(lastMessage, Boolean((component as any).isStreaming));
|
|
198
|
+
}
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Restore pi's own methods on every prototype this module instance patched (shutdown or reload). */
|
|
203
|
+
export function uninstallThinkingPatches(): void {
|
|
204
|
+
for (const cleanup of [...cleanups]) cleanup();
|
|
205
|
+
cleanups.clear();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Remove a patch left behind by an earlier load of this extension, if pi still runs it. */
|
|
209
|
+
function unwrapStale(proto: any, record: PatchRecord): void {
|
|
210
|
+
if (proto.updateContent === record.patchedUpdateContent) proto.updateContent = record.originalUpdateContent;
|
|
211
|
+
if (proto.setHideThinkingBlock === record.patchedSetHideThinkingBlock) {
|
|
212
|
+
proto.setHideThinkingBlock = record.originalSetHideThinkingBlock;
|
|
213
|
+
}
|
|
214
|
+
proto[PATCH_KEY] = undefined;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function patchPrototype(proto: any, hooks: ThinkingPatchHooks): () => void {
|
|
218
|
+
const existing = proto[PATCH_KEY] as PatchRecord | undefined;
|
|
219
|
+
if (existing?.owner === MODULE_OWNER) {
|
|
220
|
+
existing.hooks = hooks;
|
|
221
|
+
return () => {};
|
|
222
|
+
}
|
|
223
|
+
// The patch lives on pi's prototype and outlives a /reload; the earlier module's code would
|
|
224
|
+
// keep rendering with the old layout, so take it off before installing this module's.
|
|
225
|
+
if (existing) unwrapStale(proto, existing);
|
|
226
|
+
|
|
227
|
+
const originalUpdateContent = proto.updateContent;
|
|
228
|
+
const originalSetHideThinkingBlock = proto.setHideThinkingBlock;
|
|
229
|
+
if (typeof originalUpdateContent !== "function" || typeof originalSetHideThinkingBlock !== "function") {
|
|
230
|
+
return () => {};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Read hooks through the record: a later install in this module instance replaces them.
|
|
234
|
+
const patchedUpdateContent = function (this: any, message: any, isStreaming = this.isStreaming): any {
|
|
235
|
+
if (!expandedState.has(this)) expandedState.set(this, false);
|
|
236
|
+
const result = originalUpdateContent.call(this, message, isStreaming);
|
|
237
|
+
const current = record.hooks;
|
|
238
|
+
const enabled = current.isEnabled();
|
|
239
|
+
// Order matters (fold-more.md §5.6): place the blocks first, so the slots below find their
|
|
240
|
+
// segment; the gutter runs last and must not see a slot as padded text.
|
|
241
|
+
const fold = enabled && current.fold?.timeline.foldEnabled ? current.fold : undefined;
|
|
242
|
+
fold?.timeline.ingestAssistant(message, Boolean(isStreaming));
|
|
243
|
+
if (enabled && current.getLines() > 0) decorateThinking(this, message, Boolean(isStreaming), current, fold);
|
|
244
|
+
applyAssistantGutter(this, enabled, current.getTheme);
|
|
245
|
+
if (enabled && current.interrupt) replaceInterruptNote(this, message, current.interrupt);
|
|
246
|
+
return result;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const patchedSetHideThinkingBlock = function (this: any, hide: boolean): any {
|
|
250
|
+
// Pi's Ctrl+T toggles this flag. Reuse it as "show details": the first
|
|
251
|
+
// press (hide=true) expands the thought this plugin collapsed by default.
|
|
252
|
+
expandedState.set(this, hide);
|
|
253
|
+
const fold = record.hooks.fold;
|
|
254
|
+
if (fold) fold.timeline.thinkingDetails = hide;
|
|
255
|
+
return originalSetHideThinkingBlock.call(this, hide);
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
const record: PatchRecord = {
|
|
259
|
+
owner: MODULE_OWNER,
|
|
260
|
+
hooks,
|
|
261
|
+
originalUpdateContent,
|
|
262
|
+
originalSetHideThinkingBlock,
|
|
263
|
+
patchedUpdateContent,
|
|
264
|
+
patchedSetHideThinkingBlock,
|
|
265
|
+
};
|
|
266
|
+
proto[PATCH_KEY] = record;
|
|
267
|
+
proto.updateContent = patchedUpdateContent;
|
|
268
|
+
proto.setHideThinkingBlock = patchedSetHideThinkingBlock;
|
|
269
|
+
|
|
270
|
+
const cleanup = (): void => {
|
|
271
|
+
cleanups.delete(cleanup);
|
|
272
|
+
if (proto[PATCH_KEY] !== record) return;
|
|
273
|
+
unwrapStale(proto, record);
|
|
274
|
+
};
|
|
275
|
+
cleanups.add(cleanup);
|
|
276
|
+
return cleanup;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function collectAssistantComponents(root: unknown): any[] {
|
|
280
|
+
const out: any[] = [];
|
|
281
|
+
const stack: unknown[] = [root];
|
|
282
|
+
const seen = new Set<object>();
|
|
283
|
+
while (stack.length > 0) {
|
|
284
|
+
const value = stack.pop();
|
|
285
|
+
if (!value || typeof value !== "object" || seen.has(value)) continue;
|
|
286
|
+
seen.add(value);
|
|
287
|
+
const candidate = value as any;
|
|
288
|
+
if (
|
|
289
|
+
candidate.contentContainer &&
|
|
290
|
+
typeof candidate.updateContent === "function" &&
|
|
291
|
+
typeof candidate.setHideThinkingBlock === "function" &&
|
|
292
|
+
candidate.lastMessage?.role === "assistant"
|
|
293
|
+
) {
|
|
294
|
+
out.push(candidate);
|
|
295
|
+
}
|
|
296
|
+
if (Array.isArray(candidate.children)) {
|
|
297
|
+
for (const child of candidate.children) stack.push(child);
|
|
298
|
+
}
|
|
299
|
+
if (candidate.child) stack.push(candidate.child);
|
|
300
|
+
}
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function decorateThinking(
|
|
305
|
+
component: any,
|
|
306
|
+
message: any,
|
|
307
|
+
streaming: boolean,
|
|
308
|
+
hooks: ThinkingPatchHooks,
|
|
309
|
+
fold?: FoldHooks,
|
|
310
|
+
): void {
|
|
311
|
+
const container = component.contentContainer;
|
|
312
|
+
if (!container || !Array.isArray(container.children)) return;
|
|
313
|
+
const runs = regionRuns(component, message);
|
|
314
|
+
if (runs.length === 0) return;
|
|
315
|
+
|
|
316
|
+
const regions = container.children.filter(isThinkingRegion);
|
|
317
|
+
if (regions.length === 0) return;
|
|
318
|
+
const timestamp = typeof message?.timestamp === "number" ? message.timestamp : undefined;
|
|
319
|
+
|
|
320
|
+
const expanded = expandedState.get(component) ?? false;
|
|
321
|
+
const phaseStreaming = streaming && !hasAnswer(message);
|
|
322
|
+
const startedAt = typeof message?.timestamp === "number" ? message.timestamp : Date.now();
|
|
323
|
+
const durationMs = typeof message?.durationMs === "number"
|
|
324
|
+
? message.durationMs
|
|
325
|
+
: streaming
|
|
326
|
+
? Math.max(0, Date.now() - startedAt)
|
|
327
|
+
: 0;
|
|
328
|
+
for (let index = 0; index < regions.length; index++) {
|
|
329
|
+
const region = regions[index]!;
|
|
330
|
+
// pi draws one region per run with text, minus hidden runs when the hidden label is empty.
|
|
331
|
+
const run = runs[index];
|
|
332
|
+
if (!run) continue;
|
|
333
|
+
const text = run.text;
|
|
334
|
+
const view = new ThinkingView({
|
|
335
|
+
text,
|
|
336
|
+
streaming: phaseStreaming,
|
|
337
|
+
expanded,
|
|
338
|
+
startedAt,
|
|
339
|
+
durationMs,
|
|
340
|
+
// Laid out on the shared gutter (DESIGN.md §2), whatever pi's outputPad is.
|
|
341
|
+
pad: 0,
|
|
342
|
+
getTheme: hooks.getTheme,
|
|
343
|
+
lineCount: hooks.getLines(),
|
|
344
|
+
});
|
|
345
|
+
const wrapped = new MouseRegion(view, (event) => {
|
|
346
|
+
if (event.type !== "click" || event.button !== "left") return undefined;
|
|
347
|
+
expandedState.set(component, !(expandedState.get(component) ?? false));
|
|
348
|
+
const lastMessage = component.lastMessage;
|
|
349
|
+
if (lastMessage) component.updateContent(lastMessage, Boolean(component.isStreaming));
|
|
350
|
+
hooks.getActiveTui()?.requestRender();
|
|
351
|
+
return { handled: true };
|
|
352
|
+
});
|
|
353
|
+
// With fold on, the slot decides on every render whether it draws this view, its whole
|
|
354
|
+
// segment, or nothing (fold-more.md §5.6).
|
|
355
|
+
const slot = fold && timestamp !== undefined
|
|
356
|
+
? new ThinkingSlot(thinkingAnchor(timestamp, run.runIndex), wrapped, fold, hooks)
|
|
357
|
+
: wrapped;
|
|
358
|
+
const childIndex = container.children.indexOf(region);
|
|
359
|
+
if (childIndex >= 0) container.children[childIndex] = slot;
|
|
360
|
+
}
|
|
361
|
+
// pi's blank lines stay where pi puts them, including the one between a thought and the text
|
|
362
|
+
// after it; under fold they only drop next to slots that draw nothing.
|
|
363
|
+
if (fold) replaceSpacersWithGaps(container);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* The runs pi draws a region for, in order (fold-more.md §2.3): every run with text gets a run
|
|
368
|
+
* index, but a hidden run gets no region when the hidden label is empty.
|
|
369
|
+
*/
|
|
370
|
+
export function regionRuns(component: any, message: unknown): ThinkingRun[] {
|
|
371
|
+
const runs = thinkingRuns((message as { content?: unknown } | undefined)?.content);
|
|
372
|
+
const hideAll = component?.hideThinkingBlock === true;
|
|
373
|
+
const label = typeof component?.hiddenThinkingLabel === "string" ? component.hiddenThinkingLabel : "Thinking...";
|
|
374
|
+
if (label.trim()) return runs;
|
|
375
|
+
const overrides = component?.thinkingVisibilityOverrides;
|
|
376
|
+
const override = (run: number): boolean | undefined =>
|
|
377
|
+
overrides && typeof overrides.get === "function" ? overrides.get(run) : undefined;
|
|
378
|
+
return runs.filter((run) => !(override(run.runIndex) ?? hideAll));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** A thinking region under fold: its own view, its segment's host output, or nothing. */
|
|
382
|
+
export class ThinkingSlot implements Component {
|
|
383
|
+
private targets: string[] = [];
|
|
384
|
+
|
|
385
|
+
constructor(
|
|
386
|
+
readonly anchor: string,
|
|
387
|
+
private readonly view: Component,
|
|
388
|
+
private readonly fold: FoldHooks,
|
|
389
|
+
private readonly hooks: ThinkingPatchHooks,
|
|
390
|
+
) {}
|
|
391
|
+
|
|
392
|
+
/** Whether this slot draws anything; spacers before it only show when something does. */
|
|
393
|
+
visible(): boolean {
|
|
394
|
+
return this.fold.timeline.foldRole(this.anchor).kind !== "hidden";
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
render(width: number): string[] {
|
|
398
|
+
const role = this.fold.timeline.foldRole(this.anchor);
|
|
399
|
+
if (role.kind === "hidden") return [];
|
|
400
|
+
if (role.kind === "single") return [...this.view.render(width)];
|
|
401
|
+
const paint = paintSegment(role.segment, width, {
|
|
402
|
+
timeline: this.fold.timeline,
|
|
403
|
+
config: this.fold.getConfig(),
|
|
404
|
+
theme: this.hooks.getTheme(),
|
|
405
|
+
cwd: this.fold.getCwd(),
|
|
406
|
+
expanded: this.fold.timeline.globalExpanded,
|
|
407
|
+
});
|
|
408
|
+
this.targets = paint.targets;
|
|
409
|
+
return paint.lines;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
413
|
+
const role = this.fold.timeline.foldRole(this.anchor);
|
|
414
|
+
if (role.kind === "hidden") return undefined;
|
|
415
|
+
if (role.kind === "single") return this.view.handleMouse?.(event) as TuiMouseEventResult | undefined;
|
|
416
|
+
if (event.type !== "click" || event.button !== "left") return undefined;
|
|
417
|
+
const timeline = this.fold.timeline;
|
|
418
|
+
if (!clickSegment(timeline, role.segment, this.targets, event.y)) return undefined;
|
|
419
|
+
this.hooks.getActiveTui()?.requestRender();
|
|
420
|
+
return { handled: true };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
invalidate(): void {
|
|
424
|
+
this.view.invalidate();
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* pi's blank line before a visible block, drawn only when something visible follows it in the
|
|
430
|
+
* same message before the next gap (fold-more.md §5.6). A message whose slots are all hidden
|
|
431
|
+
* then takes no lines at all, and a hidden slot between two gaps does not leave two blank lines.
|
|
432
|
+
*/
|
|
433
|
+
export class GapSlot implements Component {
|
|
434
|
+
constructor(private readonly siblings: { children: unknown[] }) {}
|
|
435
|
+
|
|
436
|
+
render(_width: number): string[] {
|
|
437
|
+
const children = this.siblings.children;
|
|
438
|
+
const index = children.indexOf(this);
|
|
439
|
+
if (index < 0) return [""];
|
|
440
|
+
for (let next = index + 1; next < children.length; next++) {
|
|
441
|
+
const child = children[next];
|
|
442
|
+
if (child instanceof GapSlot) return [];
|
|
443
|
+
if (child instanceof ThinkingSlot && !child.visible()) continue;
|
|
444
|
+
return [""];
|
|
445
|
+
}
|
|
446
|
+
return [];
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
invalidate(): void {}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function replaceSpacersWithGaps(container: { children: unknown[] }): void {
|
|
453
|
+
const children = container.children;
|
|
454
|
+
for (let index = 0; index < children.length; index++) {
|
|
455
|
+
const child = children[index] as { lines?: unknown };
|
|
456
|
+
if (isSpacer(child) && child.lines === 1) children[index] = new GapSlot(container);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* pi-tui's Spacer: a line count, `setLines`, and a render that yields only empty lines. pi may
|
|
462
|
+
* load pi-tui through another module instance, so match the shape rather than the class.
|
|
463
|
+
*/
|
|
464
|
+
export function isSpacer(value: unknown): boolean {
|
|
465
|
+
if (!value || typeof value !== "object") return false;
|
|
466
|
+
const candidate = value as { lines?: unknown; setLines?: unknown; render?: unknown };
|
|
467
|
+
if (typeof candidate.lines !== "number" || candidate.lines < 1) return false;
|
|
468
|
+
if (typeof candidate.setLines !== "function" || typeof candidate.render !== "function") return false;
|
|
469
|
+
// Containers and padded text also render blank lines; a spacer has neither children nor content.
|
|
470
|
+
if ("children" in candidate || "child" in candidate || "text" in candidate) return false;
|
|
471
|
+
let lines: unknown;
|
|
472
|
+
try {
|
|
473
|
+
lines = (candidate.render as (width: number) => unknown).call(candidate, 1);
|
|
474
|
+
} catch {
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
return Array.isArray(lines) && lines.length === candidate.lines && lines.every((line) => line === "");
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function isThinkingRegion(value: unknown): boolean {
|
|
481
|
+
if (!value || typeof value !== "object") return false;
|
|
482
|
+
const region = value as { child?: unknown; onMouse?: unknown };
|
|
483
|
+
return Boolean(region.child && typeof region.onMouse === "function");
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
export function collectThinkingRuns(message: unknown): string[] {
|
|
487
|
+
if (!message || typeof message !== "object") return [];
|
|
488
|
+
const content = (message as { content?: unknown }).content;
|
|
489
|
+
if (!Array.isArray(content)) return [];
|
|
490
|
+
const runs: string[] = [];
|
|
491
|
+
let current: string[] = [];
|
|
492
|
+
const flush = () => {
|
|
493
|
+
const text = current.join("\n\n").trim();
|
|
494
|
+
if (text) runs.push(text);
|
|
495
|
+
current = [];
|
|
496
|
+
};
|
|
497
|
+
for (const item of content) {
|
|
498
|
+
if (!item || typeof item !== "object") {
|
|
499
|
+
flush();
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
const block = item as { type?: unknown; thinking?: unknown; text?: unknown };
|
|
503
|
+
if (block.type === "thinking") {
|
|
504
|
+
const text = typeof block.thinking === "string" ? block.thinking : typeof block.text === "string" ? block.text : "";
|
|
505
|
+
if (text.trim()) current.push(text);
|
|
506
|
+
} else {
|
|
507
|
+
flush();
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
flush();
|
|
511
|
+
return runs;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
export function hasAnswer(message: unknown): boolean {
|
|
515
|
+
if (!message || typeof message !== "object") return false;
|
|
516
|
+
const content = (message as { content?: unknown }).content;
|
|
517
|
+
if (!Array.isArray(content)) return false;
|
|
518
|
+
return content.some((item) => {
|
|
519
|
+
if (!item || typeof item !== "object") return false;
|
|
520
|
+
const block = item as { type?: unknown; text?: unknown };
|
|
521
|
+
if (block.type === "toolCall") return true;
|
|
522
|
+
return block.type === "text" && typeof block.text === "string" && block.text.trim().length > 0;
|
|
523
|
+
});
|
|
524
|
+
}
|