@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/src/index.ts CHANGED
@@ -1,660 +1,660 @@
1
- import { type ExtensionAPI, type ExtensionContext, keyText, type Theme } from "@earendil-works/pi-coding-agent";
2
- import { Text, type TUI } from "@earendil-works/pi-tui";
3
-
4
- import { DEFAULT_CONFIG, getConfigPath, loadConfig, saveConfig, type BetterTuiConfig } from "./config.js";
5
- import { formatDuration } from "./format.js";
6
- import { installUserMessagePatch, refreshLiveUserMessages, uninstallUserMessagePatches } from "./gutter.js";
7
- import { installHeader } from "./header.js";
8
- import { summarizedInterrupts } from "./interrupt.js";
9
- import { installLiveThinkingPatch, uninstallThinkingPatches } from "./thinking.js";
10
- import type { FoldPolicy } from "./segment.js";
11
- import { ActivityTimeline } from "./timeline.js";
12
- import { applySetting, settingsItems } from "./settings.js";
13
- import { createDescribedShellTool, SHELL_TOOL_NAMES } from "./shell-description.js";
14
- import { exposeSettings } from "./shizuku-settings.js";
15
- import { installSkillPatch, refreshLiveSkills, uninstallSkillPatches } from "./skill.js";
16
- import { RUNNING_BLOCK_DELAY_MS } from "./tool-lines.js";
17
- import { createToolRenderers } from "./tool-row.js";
18
- import { isManagedTool, isShellTool } from "./tool-summary.js";
19
- import { installUserShellPatch, refreshLiveUserShells, uninstallUserShellPatches } from "./user-shell.js";
20
-
21
- const TURN_SUMMARY_ENTRY = "better-tui-turn";
22
-
23
- interface TurnSummaryData {
24
- durationMs: number;
25
- tools: number;
26
- aborted?: boolean;
27
- }
28
-
29
- /**
30
- * `✻ Worked for 2m 5s · 7 tools`, or `✻ Interrupted after 12s · 3 tools` with the one word in
31
- * warning (DESIGN.md §5, §9). ✻ takes the gutter's column 0 like every other transcript marker.
32
- */
33
- export function turnSummaryLine(data: TurnSummaryData, theme: Theme): string {
34
- const tools = data.tools > 0 ? ` · ${data.tools} tool${data.tools === 1 ? "" : "s"}` : "";
35
- const rest = `${formatDuration(data.durationMs)}${tools}`;
36
- if (data.aborted) return `${theme.fg("dim", "✻ ")}${theme.fg("warning", "Interrupted")}${theme.fg("dim", ` after ${rest}`)}`;
37
- return theme.fg("dim", `✻ Worked for ${rest}`);
38
- }
39
-
40
- export default function betterTui(pi: ExtensionAPI): void {
41
- let config: BetterTuiConfig = loadConfig();
42
- let activeCtx: ExtensionContext | undefined;
43
- let activeTui: TUI | undefined;
44
- let fallbackTheme: Theme | undefined;
45
- let headerCleanup: (() => void) | undefined;
46
- let builtinCache = new Map<string, boolean>();
47
- let runStartedAt: number | undefined;
48
- let runTools = 0;
49
- let liveThinkingPatched = false;
50
- let liveThinkingTimers: ReturnType<typeof setTimeout>[] = [];
51
- let seedTimers: ReturnType<typeof setTimeout>[] = [];
52
- let skillTimers: ReturnType<typeof setTimeout>[] = [];
53
- let userShellTimers: ReturnType<typeof setTimeout>[] = [];
54
-
55
- const plainTheme = {
56
- fg: (_token: string, text: string) => text,
57
- bg: (_token: string, text: string) => text,
58
- bold: (text: string) => text,
59
- italic: (text: string) => text,
60
- dim: (text: string) => text,
61
- underline: (text: string) => text,
62
- strikethrough: (text: string) => text,
63
- style: (text: string) => text,
64
- colors: {},
65
- } as unknown as Theme;
66
- const getTheme = (): Theme => {
67
- try {
68
- return activeCtx?.ui.theme ?? fallbackTheme ?? plainTheme;
69
- } catch {
70
- return fallbackTheme ?? plainTheme;
71
- }
72
- };
73
-
74
- // Parameter schemas of the shell overrides registered below. A later extension that
75
- // overrides bash again brings its own schema, so identity tells the two apart.
76
- const ownShellSchemas = new WeakSet<object>();
77
- // The schema change needs a reload, so this reflects the config at load time.
78
- const shellDescriptionLoaded = config.enabled && config.tools.compact && config.tools.shellDescription;
79
- if (shellDescriptionLoaded) {
80
- for (const name of SHELL_TOOL_NAMES) {
81
- const tool = createDescribedShellTool(name, () => pi.getSettings());
82
- ownShellSchemas.add(tool.parameters);
83
- pi.registerTool(tool);
84
- }
85
- }
86
-
87
- const refreshBuiltins = (): void => {
88
- const next = new Map<string, boolean>();
89
- for (const tool of pi.getAllTools()) {
90
- const source = (tool as { sourceInfo?: { source?: string } }).sourceInfo?.source;
91
- const own = typeof tool.parameters === "object" && tool.parameters !== null && ownShellSchemas.has(tool.parameters);
92
- next.set(tool.name, source === "builtin" || source === undefined || own);
93
- }
94
- builtinCache = next;
95
- };
96
-
97
- const isBuiltin = (name: string): boolean => builtinCache.get(name) ?? true;
98
-
99
- const isManaged = (name: string): boolean =>
100
- config.enabled && config.tools.compact && isManagedTool(name) && isBuiltin(name);
101
-
102
- const timeline = new ActivityTimeline();
103
-
104
- /** Fold needs the compact rows it hides; `thinking 0` leaves thinking to pi as a text boundary. */
105
- const foldPolicy = (): FoldPolicy => ({
106
- enabled: config.enabled && config.tools.compact && config.fold.enabled,
107
- minItems: config.fold.minItems,
108
- thinking: config.thinking.lines > 0,
109
- manage: isManaged,
110
- });
111
- // Resume can build tool rows before session_start seeds; they must already see fold's policy,
112
- // or they would form read-only groups whose hidden members keep an empty component.
113
- timeline.setFoldPolicy(foldPolicy());
114
- // A segment hosted by a thinking run has no tool row to invalidate; a frame is enough.
115
- timeline.onFoldChange = () => requestRender();
116
-
117
- const applyHeader = (ctx: ExtensionContext, newSession = false): void => {
118
- headerCleanup?.();
119
- headerCleanup = undefined;
120
- if (!ctx.hasUI || ctx.mode !== "tui") {
121
- activeTui = undefined;
122
- return;
123
- }
124
- activeCtx = ctx;
125
- fallbackTheme = ctx.ui.theme;
126
- if (!config.enabled) {
127
- ctx.ui.setHeader(undefined);
128
- activeTui = undefined;
129
- return;
130
- }
131
- // `/new` and `/clear` open with a divider instead of a confirmation line (DESIGN.md §10).
132
- headerCleanup = installHeader(ctx, config, getTheme, (tui) => {
133
- activeTui = tui;
134
- }, newSession);
135
- };
136
-
137
- /** Aborted assistant messages whose `✻ Interrupted` summary stands in for pi's abort note (DESIGN.md §9). */
138
- let summarized = new Set<number>();
139
- /** Aborted assistant messages of the run in progress, until its summary is written. */
140
- let runAborted: number[] = [];
141
-
142
- /** Whether the run in progress ends with a `✻` summary line. */
143
- const writesSummary = (): boolean =>
144
- config.enabled && config.turnSummary && runStartedAt !== undefined && activeCtx?.hasUI === true && activeCtx.mode === "tui";
145
-
146
- const seed = (ctx: ExtensionContext): void => {
147
- refreshBuiltins();
148
- timeline.setFoldPolicy(foldPolicy());
149
- const branch = ctx.sessionManager.getBranch();
150
- timeline.seed(branch, config.tools.groupReadOnly, isManaged);
151
- summarized = summarizedInterrupts(branch, TURN_SUMMARY_ENTRY);
152
- };
153
-
154
- /** A fold-related config change rebuilt the model; set while a run is going on. */
155
- let reseedPending = false;
156
-
157
- /**
158
- * Rebuild rows and segments under the current config and make pi rebuild every tool row's
159
- * component: a row that was a hidden group member holds an empty component until pi calls
160
- * its renderer again. A run in progress is left alone and rebuilt once it settles.
161
- */
162
- const refreshFold = (ctx: ExtensionContext): void => {
163
- if (runStartedAt !== undefined) {
164
- reseedPending = true;
165
- return;
166
- }
167
- reseedPending = false;
168
- const invalidators = timeline.rowInvalidators();
169
- seed(ctx);
170
- for (const invalidate of invalidators) invalidate();
171
- };
172
-
173
- const cancelSeedTimers = (): void => {
174
- for (const timer of seedTimers) clearTimeout(timer);
175
- seedTimers = [];
176
- };
177
-
178
- /** Resume can build the transcript before session_start; reseed once storage is ready. */
179
- const scheduleSeed = (ctx: ExtensionContext): void => {
180
- cancelSeedTimers();
181
- for (const delay of [0, 50, 200, 500, 1_000]) {
182
- seedTimers.push(setTimeout(() => {
183
- if (activeCtx !== ctx || runStartedAt !== undefined) return;
184
- seed(ctx);
185
- requestRender();
186
- }, delay));
187
- }
188
- };
189
-
190
- const requestRender = (): void => {
191
- activeTui?.requestRender();
192
- };
193
-
194
- const runningBlockTimers = new Map<string, ReturnType<typeof setTimeout>>();
195
-
196
- const cancelRunningBlockTimers = (): void => {
197
- for (const timer of runningBlockTimers.values()) clearTimeout(timer);
198
- runningBlockTimers.clear();
199
- };
200
-
201
- /**
202
- * A command's preview block opens once it has run for RUNNING_BLOCK_DELAY_MS. Rows derive that
203
- * from the clock on every render, and pi's working indicator usually redraws often enough;
204
- * one redraw right after the delay makes sure the block does not wait for the next output.
205
- */
206
- const scheduleRunningBlock = (id: string): void => {
207
- if (runningBlockTimers.has(id)) return;
208
- runningBlockTimers.set(id, setTimeout(() => {
209
- runningBlockTimers.delete(id);
210
- const row = timeline.row(id);
211
- if (!row || row.endedAt !== undefined) return;
212
- timeline.refresh(id);
213
- requestRender();
214
- }, RUNNING_BLOCK_DELAY_MS + 16));
215
- };
216
-
217
- const thinkingHooks = {
218
- isEnabled: () => config.enabled,
219
- getLines: () => config.thinking.lines,
220
- getTheme,
221
- getActiveTui: () => activeTui,
222
- fold: {
223
- timeline,
224
- getConfig: () => config,
225
- getCwd: () => activeCtx?.cwd ?? process.cwd(),
226
- },
227
- interrupt: {
228
- // While the run settles its summary is still to come; the note must not flash up first.
229
- summaryFollows: (timestamp: number) =>
230
- summarized.has(timestamp) || (runAborted.includes(timestamp) && writesSummary()),
231
- getTheme,
232
- },
233
- };
234
-
235
- const ensureLiveThinking = (): void => {
236
- // The same patch carries the assistant gutter, so it is needed even with native thinking.
237
- if (liveThinkingPatched || !config.enabled || !activeTui) return;
238
- liveThinkingPatched = installLiveThinkingPatch(activeTui, thinkingHooks);
239
- };
240
-
241
- const scheduleLiveThinking = (): void => {
242
- for (const timer of liveThinkingTimers) clearTimeout(timer);
243
- liveThinkingTimers = [];
244
- liveThinkingPatched = false;
245
- for (const delay of [0, 50, 200, 500, 1_000]) {
246
- liveThinkingTimers.push(setTimeout(() => {
247
- ensureLiveThinking();
248
- }, delay));
249
- }
250
- };
251
-
252
- const skillHooks = {
253
- isEnabled: () => config.enabled,
254
- getTheme,
255
- };
256
- installSkillPatch(skillHooks);
257
- // User messages get the ❯ marker in the gutter; same switch and theme as the skill rows.
258
- installUserMessagePatch(skillHooks);
259
-
260
- // `!` / `!!` blocks drawn as a rounded box (DESIGN.md §7); the box is derived on every render.
261
- const userShellHooks = {
262
- isEnabled: () => config.enabled,
263
- getTheme,
264
- expandKey: () => keyText("app.tools.expand"),
265
- // Three rows once a user message sits below (§7.4); the tree finds a block pi moved.
266
- foldAnswered: () => config.userShell.foldAnswered,
267
- getRoot: () => activeTui,
268
- };
269
- installUserShellPatch(userShellHooks);
270
-
271
- /** Rebuild skill and user messages already on screen; `tui` covers a disable, which drops activeTui. */
272
- const refreshSkills = (tui: TUI | undefined = activeTui): void => {
273
- if (!tui) return;
274
- const rebuilt =
275
- refreshLiveSkills(tui, skillHooks) +
276
- refreshLiveUserMessages(tui, skillHooks) +
277
- refreshLiveUserShells(tui, userShellHooks);
278
- if (rebuilt > 0) tui.requestRender();
279
- };
280
-
281
- const cancelUserShellTimers = (): void => {
282
- for (const timer of userShellTimers) clearTimeout(timer);
283
- userShellTimers = [];
284
- };
285
-
286
- /** pi builds the shell block right after `user_bash`; find its prototype once it is on screen. */
287
- const scheduleUserShellRefresh = (): void => {
288
- cancelUserShellTimers();
289
- for (const delay of [0, 50, 200]) {
290
- userShellTimers.push(setTimeout(() => {
291
- if (activeTui && refreshLiveUserShells(activeTui, userShellHooks) > 0) activeTui.requestRender();
292
- }, delay));
293
- }
294
- };
295
-
296
- const cancelSkillTimers = (): void => {
297
- for (const timer of skillTimers) clearTimeout(timer);
298
- skillTimers = [];
299
- };
300
-
301
- /** The transcript and a new skill message are built after the events that announce them. */
302
- const scheduleSkillRefresh = (delays: readonly number[] = [0, 50, 200, 500, 1_000]): void => {
303
- cancelSkillTimers();
304
- for (const delay of delays) {
305
- skillTimers.push(setTimeout(() => refreshSkills(), delay));
306
- }
307
- };
308
-
309
- const applyConfigChange = (ctx: ExtensionContext): void => {
310
- const previousTui = activeTui;
311
- // Segments depend on these switches; any other change keeps the model (and expanded rows).
312
- const before = timeline.foldPolicy;
313
- const after = foldPolicy();
314
- if (
315
- (before.enabled || after.enabled) &&
316
- (before.enabled !== after.enabled || before.minItems !== after.minItems || before.thinking !== after.thinking)
317
- ) {
318
- refreshFold(ctx);
319
- }
320
- applyHeader(ctx);
321
- refreshSkills(activeTui ?? previousTui);
322
- // Enabling hands over the TUI only once pi rebuilds the header.
323
- scheduleSkillRefresh();
324
- timeline.bumpEpoch();
325
- if (ctx.hasUI && ctx.mode === "tui") {
326
- // Rebuild assistant thinking blocks with the new presentation.
327
- ctx.ui.setHiddenThinkingLabel();
328
- }
329
- scheduleLiveThinking();
330
- requestRender();
331
- };
332
-
333
- const status = (): string => {
334
- const thinking = config.thinking.lines === 0 ? "native" : String(config.thinking.lines);
335
- return [
336
- `enabled=${config.enabled ? "on" : "off"}`,
337
- `header=${config.header}`,
338
- `thinking=${thinking}`,
339
- `tools=${config.tools.compact ? "compact" : "native"}`,
340
- `group=${config.tools.groupReadOnly ? "read-only" : "off"}`,
341
- `describe=${config.tools.shellDescription ? "on" : "off"}${describePending() ? " (after /reload)" : ""}`,
342
- `shellfold=${config.userShell.foldAnswered ? "on" : "off"}`,
343
- `summary=${config.turnSummary ? "on" : "off"}`,
344
- `fold=${config.fold.enabled ? `on (≥${config.fold.minItems})` : "off"}`,
345
- ].join(" · ");
346
- };
347
-
348
- /** Whether the shell override at load time no longer matches the config. */
349
- const describePending = (): boolean =>
350
- shellDescriptionLoaded !== (config.enabled && config.tools.compact && config.tools.shellDescription);
351
-
352
- pi.registerToolRenderer((toolName, next) => {
353
- const native = next();
354
- if (!isManaged(toolName)) return native;
355
- return createToolRenderers(toolName, native, {
356
- timeline,
357
- getConfig: () => config,
358
- getTheme,
359
- });
360
- });
361
-
362
- pi.registerEntryRenderer(TURN_SUMMARY_ENTRY, (entry, _options, theme) => {
363
- const data = entry.data as TurnSummaryData | undefined;
364
- if (!data || typeof data.durationMs !== "number") return undefined;
365
- return new Text(turnSummaryLine(data, theme), 0, 0);
366
- });
367
-
368
- pi.on("session_start", (event, ctx) => {
369
- config = loadConfig();
370
- activeCtx = ctx;
371
- fallbackTheme = ctx.hasUI ? ctx.ui.theme : fallbackTheme;
372
- runStartedAt = undefined;
373
- runTools = 0;
374
- seed(ctx);
375
- scheduleSeed(ctx);
376
- applyHeader(ctx, event.reason === "new");
377
- installSkillPatch(skillHooks);
378
- installUserMessagePatch(skillHooks);
379
- installUserShellPatch(userShellHooks);
380
- scheduleLiveThinking();
381
- scheduleSkillRefresh();
382
- requestRender();
383
- });
384
-
385
- pi.on("user_bash", () => {
386
- // Display only: returning nothing leaves execution to pi (or to another extension).
387
- scheduleUserShellRefresh();
388
- return undefined;
389
- });
390
-
391
- pi.on("agent_start", () => {
392
- cancelSeedTimers();
393
- runStartedAt ??= Date.now();
394
- });
395
-
396
- pi.on("tool_execution_start", (event) => {
397
- if (event.parentToolCallId) return;
398
- runTools++;
399
- if (!isManaged(event.toolName)) {
400
- timeline.closeCurrent();
401
- requestRender();
402
- return;
403
- }
404
- timeline.begin(event.toolCallId, event.toolName, event.args, Date.now(), config.tools.groupReadOnly);
405
- // Under fold the row exists since its arguments streamed; a running command's elapsed time
406
- // and its preview delay start when it runs (fold-more.md §5.8).
407
- timeline.startExecution(event.toolCallId, Date.now());
408
- if (timeline.foldEnabled && isShellTool(event.toolName)) scheduleRunningBlock(event.toolCallId);
409
- requestRender();
410
- });
411
-
412
- pi.on("tool_execution_end", (event) => {
413
- if (event.parentToolCallId) return;
414
- // The event carries the error flag beside the result; the timeline reads it from the result.
415
- const result = { ...(event.result ?? {}), isError: event.isError === true };
416
- if (timeline.row(event.toolCallId)) {
417
- timeline.end(event.toolCallId, result, Date.now());
418
- } else if (isManaged(event.toolName)) {
419
- timeline.begin(event.toolCallId, event.toolName, {}, Date.now(), config.tools.groupReadOnly);
420
- timeline.end(event.toolCallId, result, Date.now());
421
- }
422
- requestRender();
423
- });
424
-
425
- pi.on("tool_execution_update", (event) => {
426
- if (event.parentToolCallId) return;
427
- timeline.update(event.toolCallId, event.partialResult);
428
- });
429
-
430
- // Extensions hear message events before pi's interactive mode does, so blocks are placed in
431
- // segments before pi builds their tool rows, even while the assistant patch is not installed.
432
- pi.on("message_start", (event) => {
433
- if (event.message.role !== "assistant") return;
434
- timeline.ingestAssistant(event.message, true);
435
- if (!liveThinkingPatched) setTimeout(ensureLiveThinking, 0);
436
- });
437
-
438
- pi.on("message_update", (event) => {
439
- if (event.message.role !== "assistant") return;
440
- timeline.ingestAssistant(event.message, true);
441
- if (!liveThinkingPatched) ensureLiveThinking();
442
- });
443
-
444
- pi.on("message_end", (event) => {
445
- const ended = event.message as { role?: unknown; stopReason?: unknown; timestamp?: unknown };
446
- if (ended.role === "assistant" && ended.stopReason === "aborted" && typeof ended.timestamp === "number") {
447
- runAborted.push(ended.timestamp);
448
- }
449
- timeline.ingestAssistant(event.message, false);
450
- timeline.onMessage(event.message);
451
- if (event.message.role === "user") scheduleSkillRefresh([0, 50]);
452
- if (event.message.role === "assistant" && !liveThinkingPatched) ensureLiveThinking();
453
- requestRender();
454
- });
455
-
456
- pi.on("turn_end", () => {
457
- // A turn can end between two reads; keep the group open until text, a
458
- // mutation, a user message, or the whole run settles.
459
- requestRender();
460
- });
461
-
462
- pi.on("agent_settled", (event) => {
463
- timeline.closeCurrent();
464
- // The run is over: every segment it drew as a list collapses into its summary line, at the
465
- // same moment `✻ Worked for` appears (fold-more.md §4.10). A seed does the same at its end.
466
- timeline.settle();
467
- cancelRunningBlockTimers();
468
- const durationMs = runStartedAt === undefined ? 0 : Date.now() - runStartedAt;
469
- if (writesSummary()) {
470
- pi.appendEntry(TURN_SUMMARY_ENTRY, {
471
- durationMs,
472
- tools: runTools,
473
- aborted: event.aborted,
474
- } satisfies TurnSummaryData);
475
- // From now on the summary says it; the abort notes above give way on the next frame.
476
- if (event.aborted) for (const timestamp of runAborted) summarized.add(timestamp);
477
- }
478
- runAborted = [];
479
- runStartedAt = undefined;
480
- runTools = 0;
481
- if (reseedPending && activeCtx) refreshFold(activeCtx);
482
- requestRender();
483
- });
484
-
485
- pi.on("session_compact", () => {
486
- timeline.closeCurrent();
487
- timeline.closeSegment();
488
- requestRender();
489
- });
490
-
491
- pi.on("session_tree", (_event, ctx) => {
492
- runStartedAt = undefined;
493
- runTools = 0;
494
- seed(ctx);
495
- scheduleSeed(ctx);
496
- scheduleLiveThinking();
497
- scheduleSkillRefresh();
498
- requestRender();
499
- });
500
-
501
- pi.on("session_shutdown", () => {
502
- for (const timer of liveThinkingTimers) clearTimeout(timer);
503
- liveThinkingTimers = [];
504
- cancelSeedTimers();
505
- cancelSkillTimers();
506
- cancelUserShellTimers();
507
- cancelRunningBlockTimers();
508
- uninstallSkillPatches();
509
- uninstallUserMessagePatches();
510
- uninstallUserShellPatches();
511
- // The prototype patch outlives this module; leave pi's own method for the next load.
512
- uninstallThinkingPatches();
513
- liveThinkingPatched = false;
514
- headerCleanup?.();
515
- headerCleanup = undefined;
516
- activeTui = undefined;
517
- activeCtx = undefined;
518
- runStartedAt = undefined;
519
- runTools = 0;
520
- runAborted = [];
521
- timeline.reset();
522
- });
523
-
524
- // The /shizuku panel (pi-shizuku-settings) edits the same file /bettertui writes.
525
- exposeSettings(pi, {
526
- id: "pi-bettertui",
527
- title: "pi-bettertui",
528
- description: "Compact transcript: tool rows, activity folding, thinking window",
529
- file: getConfigPath(),
530
- items: () => settingsItems(config),
531
- set: (id, value) => {
532
- const result = applySetting(config, id, value);
533
- if ("error" in result) return { ok: false, error: result.error };
534
- try {
535
- saveConfig(result.config);
536
- } catch (error) {
537
- return { ok: false, error: `could not save config: ${String(error)}` };
538
- }
539
- config = result.config;
540
- if (activeCtx) applyConfigChange(activeCtx);
541
- return { ok: true };
542
- },
543
- });
544
-
545
- pi.registerCommand("bettertui", {
546
- description: "Configure pi-bettertui (status | on | off | header off|compact | thinking 0-5 | group on|off | tools on|off | describe on|off | shellfold on|off | summary on|off | fold on|off | reset)",
547
- handler: async (args, ctx) => {
548
- const parts = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
549
- const command = parts[0] ?? "status";
550
- const value = parts[1];
551
- let changed = false;
552
- switch (command) {
553
- case "on":
554
- config.enabled = true;
555
- changed = true;
556
- break;
557
- case "off":
558
- config.enabled = false;
559
- changed = true;
560
- break;
561
- case "header":
562
- if (value === "off" || value === "compact") {
563
- config.header = value;
564
- changed = true;
565
- } else {
566
- ctx.ui.notify("usage: /bettertui header off|compact", "warning");
567
- return;
568
- }
569
- break;
570
- case "thinking": {
571
- const lines = Number(value);
572
- if (Number.isInteger(lines) && lines >= 0 && lines <= 5) {
573
- config.thinking.lines = lines;
574
- changed = true;
575
- } else {
576
- ctx.ui.notify("usage: /bettertui thinking 0-5 (0 = native)", "warning");
577
- return;
578
- }
579
- break;
580
- }
581
- case "group":
582
- if (value === "on" || value === "off") {
583
- config.tools.groupReadOnly = value === "on";
584
- changed = true;
585
- } else {
586
- ctx.ui.notify("usage: /bettertui group on|off", "warning");
587
- return;
588
- }
589
- break;
590
- case "tools":
591
- if (value === "on" || value === "off") {
592
- config.tools.compact = value === "on";
593
- changed = true;
594
- } else {
595
- ctx.ui.notify("usage: /bettertui tools on|off", "warning");
596
- return;
597
- }
598
- break;
599
- case "summary":
600
- if (value === "on" || value === "off") {
601
- config.turnSummary = value === "on";
602
- changed = true;
603
- } else {
604
- ctx.ui.notify("usage: /bettertui summary on|off", "warning");
605
- return;
606
- }
607
- break;
608
- case "fold":
609
- if (value === "on" || value === "off") {
610
- config.fold.enabled = value === "on";
611
- changed = true;
612
- } else {
613
- ctx.ui.notify("usage: /bettertui fold on|off", "warning");
614
- return;
615
- }
616
- break;
617
- case "describe":
618
- if (value === "on" || value === "off") {
619
- config.tools.shellDescription = value === "on";
620
- changed = true;
621
- } else {
622
- ctx.ui.notify("usage: /bettertui describe on|off (applies after /reload)", "warning");
623
- return;
624
- }
625
- break;
626
- case "shellfold":
627
- if (value === "on" || value === "off") {
628
- config.userShell.foldAnswered = value === "on";
629
- changed = true;
630
- } else {
631
- ctx.ui.notify("usage: /bettertui shellfold on|off", "warning");
632
- return;
633
- }
634
- break;
635
- case "reset":
636
- config = structuredClone(DEFAULT_CONFIG);
637
- changed = true;
638
- break;
639
- case "status":
640
- break;
641
- default:
642
- ctx.ui.notify(
643
- "usage: /bettertui [status|on|off|header off|compact|thinking 0-5|group on|off|tools on|off|describe on|off|shellfold on|off|summary on|off|fold on|off|reset]",
644
- "warning",
645
- );
646
- return;
647
- }
648
-
649
- if (changed) {
650
- try {
651
- saveConfig(config);
652
- } catch (error) {
653
- ctx.ui.notify(`pi-bettertui: could not save config: ${String(error)}`, "warning");
654
- }
655
- applyConfigChange(ctx);
656
- }
657
- ctx.ui.notify(`pi-bettertui: ${status()}`, "info");
658
- },
659
- });
660
- }
1
+ import { type ExtensionAPI, type ExtensionContext, keyText, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import { Text, type TUI } from "@earendil-works/pi-tui";
3
+
4
+ import { DEFAULT_CONFIG, getConfigPath, loadConfig, saveConfig, type BetterTuiConfig } from "./config.js";
5
+ import { formatDuration } from "./format.js";
6
+ import { installUserMessagePatch, refreshLiveUserMessages, uninstallUserMessagePatches } from "./gutter.js";
7
+ import { installHeader } from "./header.js";
8
+ import { summarizedInterrupts } from "./interrupt.js";
9
+ import { installLiveThinkingPatch, uninstallThinkingPatches } from "./thinking.js";
10
+ import type { FoldPolicy } from "./segment.js";
11
+ import { ActivityTimeline } from "./timeline.js";
12
+ import { applySetting, settingsItems } from "./settings.js";
13
+ import { createDescribedShellTool, SHELL_TOOL_NAMES } from "./shell-description.js";
14
+ import { exposeSettings } from "./shizuku-settings.js";
15
+ import { installSkillPatch, refreshLiveSkills, uninstallSkillPatches } from "./skill.js";
16
+ import { RUNNING_BLOCK_DELAY_MS } from "./tool-lines.js";
17
+ import { createToolRenderers } from "./tool-row.js";
18
+ import { isManagedTool, isShellTool } from "./tool-summary.js";
19
+ import { installUserShellPatch, refreshLiveUserShells, uninstallUserShellPatches } from "./user-shell.js";
20
+
21
+ const TURN_SUMMARY_ENTRY = "better-tui-turn";
22
+
23
+ interface TurnSummaryData {
24
+ durationMs: number;
25
+ tools: number;
26
+ aborted?: boolean;
27
+ }
28
+
29
+ /**
30
+ * `✻ Worked for 2m 5s · 7 tools`, or `✻ Interrupted after 12s · 3 tools` with the one word in
31
+ * warning (DESIGN.md §5, §9). ✻ takes the gutter's column 0 like every other transcript marker.
32
+ */
33
+ export function turnSummaryLine(data: TurnSummaryData, theme: Theme): string {
34
+ const tools = data.tools > 0 ? ` · ${data.tools} tool${data.tools === 1 ? "" : "s"}` : "";
35
+ const rest = `${formatDuration(data.durationMs)}${tools}`;
36
+ if (data.aborted) return `${theme.fg("dim", "✻ ")}${theme.fg("warning", "Interrupted")}${theme.fg("dim", ` after ${rest}`)}`;
37
+ return theme.fg("dim", `✻ Worked for ${rest}`);
38
+ }
39
+
40
+ export default function betterTui(pi: ExtensionAPI): void {
41
+ let config: BetterTuiConfig = loadConfig();
42
+ let activeCtx: ExtensionContext | undefined;
43
+ let activeTui: TUI | undefined;
44
+ let fallbackTheme: Theme | undefined;
45
+ let headerCleanup: (() => void) | undefined;
46
+ let builtinCache = new Map<string, boolean>();
47
+ let runStartedAt: number | undefined;
48
+ let runTools = 0;
49
+ let liveThinkingPatched = false;
50
+ let liveThinkingTimers: ReturnType<typeof setTimeout>[] = [];
51
+ let seedTimers: ReturnType<typeof setTimeout>[] = [];
52
+ let skillTimers: ReturnType<typeof setTimeout>[] = [];
53
+ let userShellTimers: ReturnType<typeof setTimeout>[] = [];
54
+
55
+ const plainTheme = {
56
+ fg: (_token: string, text: string) => text,
57
+ bg: (_token: string, text: string) => text,
58
+ bold: (text: string) => text,
59
+ italic: (text: string) => text,
60
+ dim: (text: string) => text,
61
+ underline: (text: string) => text,
62
+ strikethrough: (text: string) => text,
63
+ style: (text: string) => text,
64
+ colors: {},
65
+ } as unknown as Theme;
66
+ const getTheme = (): Theme => {
67
+ try {
68
+ return activeCtx?.ui.theme ?? fallbackTheme ?? plainTheme;
69
+ } catch {
70
+ return fallbackTheme ?? plainTheme;
71
+ }
72
+ };
73
+
74
+ // Parameter schemas of the shell overrides registered below. A later extension that
75
+ // overrides bash again brings its own schema, so identity tells the two apart.
76
+ const ownShellSchemas = new WeakSet<object>();
77
+ // The schema change needs a reload, so this reflects the config at load time.
78
+ const shellDescriptionLoaded = config.enabled && config.tools.compact && config.tools.shellDescription;
79
+ if (shellDescriptionLoaded) {
80
+ for (const name of SHELL_TOOL_NAMES) {
81
+ const tool = createDescribedShellTool(name, () => pi.getSettings());
82
+ ownShellSchemas.add(tool.parameters);
83
+ pi.registerTool(tool);
84
+ }
85
+ }
86
+
87
+ const refreshBuiltins = (): void => {
88
+ const next = new Map<string, boolean>();
89
+ for (const tool of pi.getAllTools()) {
90
+ const source = (tool as { sourceInfo?: { source?: string } }).sourceInfo?.source;
91
+ const own = typeof tool.parameters === "object" && tool.parameters !== null && ownShellSchemas.has(tool.parameters);
92
+ next.set(tool.name, source === "builtin" || source === undefined || own);
93
+ }
94
+ builtinCache = next;
95
+ };
96
+
97
+ const isBuiltin = (name: string): boolean => builtinCache.get(name) ?? true;
98
+
99
+ const isManaged = (name: string): boolean =>
100
+ config.enabled && config.tools.compact && isManagedTool(name) && isBuiltin(name);
101
+
102
+ const timeline = new ActivityTimeline();
103
+
104
+ /** Fold needs the compact rows it hides; `thinking 0` leaves thinking to pi as a text boundary. */
105
+ const foldPolicy = (): FoldPolicy => ({
106
+ enabled: config.enabled && config.tools.compact && config.fold.enabled,
107
+ minItems: config.fold.minItems,
108
+ thinking: config.thinking.lines > 0,
109
+ manage: isManaged,
110
+ });
111
+ // Resume can build tool rows before session_start seeds; they must already see fold's policy,
112
+ // or they would form read-only groups whose hidden members keep an empty component.
113
+ timeline.setFoldPolicy(foldPolicy());
114
+ // A segment hosted by a thinking run has no tool row to invalidate; a frame is enough.
115
+ timeline.onFoldChange = () => requestRender();
116
+
117
+ const applyHeader = (ctx: ExtensionContext, newSession = false): void => {
118
+ headerCleanup?.();
119
+ headerCleanup = undefined;
120
+ if (!ctx.hasUI || ctx.mode !== "tui") {
121
+ activeTui = undefined;
122
+ return;
123
+ }
124
+ activeCtx = ctx;
125
+ fallbackTheme = ctx.ui.theme;
126
+ if (!config.enabled) {
127
+ ctx.ui.setHeader(undefined);
128
+ activeTui = undefined;
129
+ return;
130
+ }
131
+ // `/new` and `/clear` open with a divider instead of a confirmation line (DESIGN.md §10).
132
+ headerCleanup = installHeader(ctx, config, getTheme, (tui) => {
133
+ activeTui = tui;
134
+ }, newSession);
135
+ };
136
+
137
+ /** Aborted assistant messages whose `✻ Interrupted` summary stands in for pi's abort note (DESIGN.md §9). */
138
+ let summarized = new Set<number>();
139
+ /** Aborted assistant messages of the run in progress, until its summary is written. */
140
+ let runAborted: number[] = [];
141
+
142
+ /** Whether the run in progress ends with a `✻` summary line. */
143
+ const writesSummary = (): boolean =>
144
+ config.enabled && config.turnSummary && runStartedAt !== undefined && activeCtx?.hasUI === true && activeCtx.mode === "tui";
145
+
146
+ const seed = (ctx: ExtensionContext): void => {
147
+ refreshBuiltins();
148
+ timeline.setFoldPolicy(foldPolicy());
149
+ const branch = ctx.sessionManager.getBranch();
150
+ timeline.seed(branch, config.tools.groupReadOnly, isManaged);
151
+ summarized = summarizedInterrupts(branch, TURN_SUMMARY_ENTRY);
152
+ };
153
+
154
+ /** A fold-related config change rebuilt the model; set while a run is going on. */
155
+ let reseedPending = false;
156
+
157
+ /**
158
+ * Rebuild rows and segments under the current config and make pi rebuild every tool row's
159
+ * component: a row that was a hidden group member holds an empty component until pi calls
160
+ * its renderer again. A run in progress is left alone and rebuilt once it settles.
161
+ */
162
+ const refreshFold = (ctx: ExtensionContext): void => {
163
+ if (runStartedAt !== undefined) {
164
+ reseedPending = true;
165
+ return;
166
+ }
167
+ reseedPending = false;
168
+ const invalidators = timeline.rowInvalidators();
169
+ seed(ctx);
170
+ for (const invalidate of invalidators) invalidate();
171
+ };
172
+
173
+ const cancelSeedTimers = (): void => {
174
+ for (const timer of seedTimers) clearTimeout(timer);
175
+ seedTimers = [];
176
+ };
177
+
178
+ /** Resume can build the transcript before session_start; reseed once storage is ready. */
179
+ const scheduleSeed = (ctx: ExtensionContext): void => {
180
+ cancelSeedTimers();
181
+ for (const delay of [0, 50, 200, 500, 1_000]) {
182
+ seedTimers.push(setTimeout(() => {
183
+ if (activeCtx !== ctx || runStartedAt !== undefined) return;
184
+ seed(ctx);
185
+ requestRender();
186
+ }, delay));
187
+ }
188
+ };
189
+
190
+ const requestRender = (): void => {
191
+ activeTui?.requestRender();
192
+ };
193
+
194
+ const runningBlockTimers = new Map<string, ReturnType<typeof setTimeout>>();
195
+
196
+ const cancelRunningBlockTimers = (): void => {
197
+ for (const timer of runningBlockTimers.values()) clearTimeout(timer);
198
+ runningBlockTimers.clear();
199
+ };
200
+
201
+ /**
202
+ * A command's preview block opens once it has run for RUNNING_BLOCK_DELAY_MS. Rows derive that
203
+ * from the clock on every render, and pi's working indicator usually redraws often enough;
204
+ * one redraw right after the delay makes sure the block does not wait for the next output.
205
+ */
206
+ const scheduleRunningBlock = (id: string): void => {
207
+ if (runningBlockTimers.has(id)) return;
208
+ runningBlockTimers.set(id, setTimeout(() => {
209
+ runningBlockTimers.delete(id);
210
+ const row = timeline.row(id);
211
+ if (!row || row.endedAt !== undefined) return;
212
+ timeline.refresh(id);
213
+ requestRender();
214
+ }, RUNNING_BLOCK_DELAY_MS + 16));
215
+ };
216
+
217
+ const thinkingHooks = {
218
+ isEnabled: () => config.enabled,
219
+ getLines: () => config.thinking.lines,
220
+ getTheme,
221
+ getActiveTui: () => activeTui,
222
+ fold: {
223
+ timeline,
224
+ getConfig: () => config,
225
+ getCwd: () => activeCtx?.cwd ?? process.cwd(),
226
+ },
227
+ interrupt: {
228
+ // While the run settles its summary is still to come; the note must not flash up first.
229
+ summaryFollows: (timestamp: number) =>
230
+ summarized.has(timestamp) || (runAborted.includes(timestamp) && writesSummary()),
231
+ getTheme,
232
+ },
233
+ };
234
+
235
+ const ensureLiveThinking = (): void => {
236
+ // The same patch carries the assistant gutter, so it is needed even with native thinking.
237
+ if (liveThinkingPatched || !config.enabled || !activeTui) return;
238
+ liveThinkingPatched = installLiveThinkingPatch(activeTui, thinkingHooks);
239
+ };
240
+
241
+ const scheduleLiveThinking = (): void => {
242
+ for (const timer of liveThinkingTimers) clearTimeout(timer);
243
+ liveThinkingTimers = [];
244
+ liveThinkingPatched = false;
245
+ for (const delay of [0, 50, 200, 500, 1_000]) {
246
+ liveThinkingTimers.push(setTimeout(() => {
247
+ ensureLiveThinking();
248
+ }, delay));
249
+ }
250
+ };
251
+
252
+ const skillHooks = {
253
+ isEnabled: () => config.enabled,
254
+ getTheme,
255
+ };
256
+ installSkillPatch(skillHooks);
257
+ // User messages get the ❯ marker in the gutter; same switch and theme as the skill rows.
258
+ installUserMessagePatch(skillHooks);
259
+
260
+ // `!` / `!!` blocks drawn as a rounded box (DESIGN.md §7); the box is derived on every render.
261
+ const userShellHooks = {
262
+ isEnabled: () => config.enabled,
263
+ getTheme,
264
+ expandKey: () => keyText("app.tools.expand"),
265
+ // Three rows once a user message sits below (§7.4); the tree finds a block pi moved.
266
+ foldAnswered: () => config.userShell.foldAnswered,
267
+ getRoot: () => activeTui,
268
+ };
269
+ installUserShellPatch(userShellHooks);
270
+
271
+ /** Rebuild skill and user messages already on screen; `tui` covers a disable, which drops activeTui. */
272
+ const refreshSkills = (tui: TUI | undefined = activeTui): void => {
273
+ if (!tui) return;
274
+ const rebuilt =
275
+ refreshLiveSkills(tui, skillHooks) +
276
+ refreshLiveUserMessages(tui, skillHooks) +
277
+ refreshLiveUserShells(tui, userShellHooks);
278
+ if (rebuilt > 0) tui.requestRender();
279
+ };
280
+
281
+ const cancelUserShellTimers = (): void => {
282
+ for (const timer of userShellTimers) clearTimeout(timer);
283
+ userShellTimers = [];
284
+ };
285
+
286
+ /** pi builds the shell block right after `user_bash`; find its prototype once it is on screen. */
287
+ const scheduleUserShellRefresh = (): void => {
288
+ cancelUserShellTimers();
289
+ for (const delay of [0, 50, 200]) {
290
+ userShellTimers.push(setTimeout(() => {
291
+ if (activeTui && refreshLiveUserShells(activeTui, userShellHooks) > 0) activeTui.requestRender();
292
+ }, delay));
293
+ }
294
+ };
295
+
296
+ const cancelSkillTimers = (): void => {
297
+ for (const timer of skillTimers) clearTimeout(timer);
298
+ skillTimers = [];
299
+ };
300
+
301
+ /** The transcript and a new skill message are built after the events that announce them. */
302
+ const scheduleSkillRefresh = (delays: readonly number[] = [0, 50, 200, 500, 1_000]): void => {
303
+ cancelSkillTimers();
304
+ for (const delay of delays) {
305
+ skillTimers.push(setTimeout(() => refreshSkills(), delay));
306
+ }
307
+ };
308
+
309
+ const applyConfigChange = (ctx: ExtensionContext): void => {
310
+ const previousTui = activeTui;
311
+ // Segments depend on these switches; any other change keeps the model (and expanded rows).
312
+ const before = timeline.foldPolicy;
313
+ const after = foldPolicy();
314
+ if (
315
+ (before.enabled || after.enabled) &&
316
+ (before.enabled !== after.enabled || before.minItems !== after.minItems || before.thinking !== after.thinking)
317
+ ) {
318
+ refreshFold(ctx);
319
+ }
320
+ applyHeader(ctx);
321
+ refreshSkills(activeTui ?? previousTui);
322
+ // Enabling hands over the TUI only once pi rebuilds the header.
323
+ scheduleSkillRefresh();
324
+ timeline.bumpEpoch();
325
+ if (ctx.hasUI && ctx.mode === "tui") {
326
+ // Rebuild assistant thinking blocks with the new presentation.
327
+ ctx.ui.setHiddenThinkingLabel();
328
+ }
329
+ scheduleLiveThinking();
330
+ requestRender();
331
+ };
332
+
333
+ const status = (): string => {
334
+ const thinking = config.thinking.lines === 0 ? "native" : String(config.thinking.lines);
335
+ return [
336
+ `enabled=${config.enabled ? "on" : "off"}`,
337
+ `header=${config.header}`,
338
+ `thinking=${thinking}`,
339
+ `tools=${config.tools.compact ? "compact" : "native"}`,
340
+ `group=${config.tools.groupReadOnly ? "read-only" : "off"}`,
341
+ `describe=${config.tools.shellDescription ? "on" : "off"}${describePending() ? " (after /reload)" : ""}`,
342
+ `shellfold=${config.userShell.foldAnswered ? "on" : "off"}`,
343
+ `summary=${config.turnSummary ? "on" : "off"}`,
344
+ `fold=${config.fold.enabled ? `on (≥${config.fold.minItems})` : "off"}`,
345
+ ].join(" · ");
346
+ };
347
+
348
+ /** Whether the shell override at load time no longer matches the config. */
349
+ const describePending = (): boolean =>
350
+ shellDescriptionLoaded !== (config.enabled && config.tools.compact && config.tools.shellDescription);
351
+
352
+ pi.registerToolRenderer((toolName, next) => {
353
+ const native = next();
354
+ if (!isManaged(toolName)) return native;
355
+ return createToolRenderers(toolName, native, {
356
+ timeline,
357
+ getConfig: () => config,
358
+ getTheme,
359
+ });
360
+ });
361
+
362
+ pi.registerEntryRenderer(TURN_SUMMARY_ENTRY, (entry, _options, theme) => {
363
+ const data = entry.data as TurnSummaryData | undefined;
364
+ if (!data || typeof data.durationMs !== "number") return undefined;
365
+ return new Text(turnSummaryLine(data, theme), 0, 0);
366
+ });
367
+
368
+ pi.on("session_start", (event, ctx) => {
369
+ config = loadConfig();
370
+ activeCtx = ctx;
371
+ fallbackTheme = ctx.hasUI ? ctx.ui.theme : fallbackTheme;
372
+ runStartedAt = undefined;
373
+ runTools = 0;
374
+ seed(ctx);
375
+ scheduleSeed(ctx);
376
+ applyHeader(ctx, event.reason === "new");
377
+ installSkillPatch(skillHooks);
378
+ installUserMessagePatch(skillHooks);
379
+ installUserShellPatch(userShellHooks);
380
+ scheduleLiveThinking();
381
+ scheduleSkillRefresh();
382
+ requestRender();
383
+ });
384
+
385
+ pi.on("user_bash", () => {
386
+ // Display only: returning nothing leaves execution to pi (or to another extension).
387
+ scheduleUserShellRefresh();
388
+ return undefined;
389
+ });
390
+
391
+ pi.on("agent_start", () => {
392
+ cancelSeedTimers();
393
+ runStartedAt ??= Date.now();
394
+ });
395
+
396
+ pi.on("tool_execution_start", (event) => {
397
+ if (event.parentToolCallId) return;
398
+ runTools++;
399
+ if (!isManaged(event.toolName)) {
400
+ timeline.closeCurrent();
401
+ requestRender();
402
+ return;
403
+ }
404
+ timeline.begin(event.toolCallId, event.toolName, event.args, Date.now(), config.tools.groupReadOnly);
405
+ // Under fold the row exists since its arguments streamed; a running command's elapsed time
406
+ // and its preview delay start when it runs (fold-more.md §5.8).
407
+ timeline.startExecution(event.toolCallId, Date.now());
408
+ if (timeline.foldEnabled && isShellTool(event.toolName)) scheduleRunningBlock(event.toolCallId);
409
+ requestRender();
410
+ });
411
+
412
+ pi.on("tool_execution_end", (event) => {
413
+ if (event.parentToolCallId) return;
414
+ // The event carries the error flag beside the result; the timeline reads it from the result.
415
+ const result = { ...(event.result ?? {}), isError: event.isError === true };
416
+ if (timeline.row(event.toolCallId)) {
417
+ timeline.end(event.toolCallId, result, Date.now());
418
+ } else if (isManaged(event.toolName)) {
419
+ timeline.begin(event.toolCallId, event.toolName, {}, Date.now(), config.tools.groupReadOnly);
420
+ timeline.end(event.toolCallId, result, Date.now());
421
+ }
422
+ requestRender();
423
+ });
424
+
425
+ pi.on("tool_execution_update", (event) => {
426
+ if (event.parentToolCallId) return;
427
+ timeline.update(event.toolCallId, event.partialResult);
428
+ });
429
+
430
+ // Extensions hear message events before pi's interactive mode does, so blocks are placed in
431
+ // segments before pi builds their tool rows, even while the assistant patch is not installed.
432
+ pi.on("message_start", (event) => {
433
+ if (event.message.role !== "assistant") return;
434
+ timeline.ingestAssistant(event.message, true);
435
+ if (!liveThinkingPatched) setTimeout(ensureLiveThinking, 0);
436
+ });
437
+
438
+ pi.on("message_update", (event) => {
439
+ if (event.message.role !== "assistant") return;
440
+ timeline.ingestAssistant(event.message, true);
441
+ if (!liveThinkingPatched) ensureLiveThinking();
442
+ });
443
+
444
+ pi.on("message_end", (event) => {
445
+ const ended = event.message as { role?: unknown; stopReason?: unknown; timestamp?: unknown };
446
+ if (ended.role === "assistant" && ended.stopReason === "aborted" && typeof ended.timestamp === "number") {
447
+ runAborted.push(ended.timestamp);
448
+ }
449
+ timeline.ingestAssistant(event.message, false);
450
+ timeline.onMessage(event.message);
451
+ if (event.message.role === "user") scheduleSkillRefresh([0, 50]);
452
+ if (event.message.role === "assistant" && !liveThinkingPatched) ensureLiveThinking();
453
+ requestRender();
454
+ });
455
+
456
+ pi.on("turn_end", () => {
457
+ // A turn can end between two reads; keep the group open until text, a
458
+ // mutation, a user message, or the whole run settles.
459
+ requestRender();
460
+ });
461
+
462
+ pi.on("agent_settled", (event) => {
463
+ timeline.closeCurrent();
464
+ // The run is over: every segment it drew as a list collapses into its summary line, at the
465
+ // same moment `✻ Worked for` appears (fold-more.md §4.10). A seed does the same at its end.
466
+ timeline.settle();
467
+ cancelRunningBlockTimers();
468
+ const durationMs = runStartedAt === undefined ? 0 : Date.now() - runStartedAt;
469
+ if (writesSummary()) {
470
+ pi.appendEntry(TURN_SUMMARY_ENTRY, {
471
+ durationMs,
472
+ tools: runTools,
473
+ aborted: event.aborted,
474
+ } satisfies TurnSummaryData);
475
+ // From now on the summary says it; the abort notes above give way on the next frame.
476
+ if (event.aborted) for (const timestamp of runAborted) summarized.add(timestamp);
477
+ }
478
+ runAborted = [];
479
+ runStartedAt = undefined;
480
+ runTools = 0;
481
+ if (reseedPending && activeCtx) refreshFold(activeCtx);
482
+ requestRender();
483
+ });
484
+
485
+ pi.on("session_compact", () => {
486
+ timeline.closeCurrent();
487
+ timeline.closeSegment();
488
+ requestRender();
489
+ });
490
+
491
+ pi.on("session_tree", (_event, ctx) => {
492
+ runStartedAt = undefined;
493
+ runTools = 0;
494
+ seed(ctx);
495
+ scheduleSeed(ctx);
496
+ scheduleLiveThinking();
497
+ scheduleSkillRefresh();
498
+ requestRender();
499
+ });
500
+
501
+ pi.on("session_shutdown", () => {
502
+ for (const timer of liveThinkingTimers) clearTimeout(timer);
503
+ liveThinkingTimers = [];
504
+ cancelSeedTimers();
505
+ cancelSkillTimers();
506
+ cancelUserShellTimers();
507
+ cancelRunningBlockTimers();
508
+ uninstallSkillPatches();
509
+ uninstallUserMessagePatches();
510
+ uninstallUserShellPatches();
511
+ // The prototype patch outlives this module; leave pi's own method for the next load.
512
+ uninstallThinkingPatches();
513
+ liveThinkingPatched = false;
514
+ headerCleanup?.();
515
+ headerCleanup = undefined;
516
+ activeTui = undefined;
517
+ activeCtx = undefined;
518
+ runStartedAt = undefined;
519
+ runTools = 0;
520
+ runAborted = [];
521
+ timeline.reset();
522
+ });
523
+
524
+ // The /shizuku panel (pi-shizuku-settings) edits the same file /bettertui writes.
525
+ exposeSettings(pi, {
526
+ id: "pi-bettertui",
527
+ title: "pi-bettertui",
528
+ description: "Compact transcript: tool rows, activity folding, thinking window",
529
+ file: getConfigPath(),
530
+ items: () => settingsItems(config),
531
+ set: (id, value) => {
532
+ const result = applySetting(config, id, value);
533
+ if ("error" in result) return { ok: false, error: result.error };
534
+ try {
535
+ saveConfig(result.config);
536
+ } catch (error) {
537
+ return { ok: false, error: `could not save config: ${String(error)}` };
538
+ }
539
+ config = result.config;
540
+ if (activeCtx) applyConfigChange(activeCtx);
541
+ return { ok: true };
542
+ },
543
+ });
544
+
545
+ pi.registerCommand("bettertui", {
546
+ description: "Configure pi-bettertui (status | on | off | header off|compact | thinking 0-5 | group on|off | tools on|off | describe on|off | shellfold on|off | summary on|off | fold on|off | reset)",
547
+ handler: async (args, ctx) => {
548
+ const parts = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
549
+ const command = parts[0] ?? "status";
550
+ const value = parts[1];
551
+ let changed = false;
552
+ switch (command) {
553
+ case "on":
554
+ config.enabled = true;
555
+ changed = true;
556
+ break;
557
+ case "off":
558
+ config.enabled = false;
559
+ changed = true;
560
+ break;
561
+ case "header":
562
+ if (value === "off" || value === "compact") {
563
+ config.header = value;
564
+ changed = true;
565
+ } else {
566
+ ctx.ui.notify("usage: /bettertui header off|compact", "warning");
567
+ return;
568
+ }
569
+ break;
570
+ case "thinking": {
571
+ const lines = Number(value);
572
+ if (Number.isInteger(lines) && lines >= 0 && lines <= 5) {
573
+ config.thinking.lines = lines;
574
+ changed = true;
575
+ } else {
576
+ ctx.ui.notify("usage: /bettertui thinking 0-5 (0 = native)", "warning");
577
+ return;
578
+ }
579
+ break;
580
+ }
581
+ case "group":
582
+ if (value === "on" || value === "off") {
583
+ config.tools.groupReadOnly = value === "on";
584
+ changed = true;
585
+ } else {
586
+ ctx.ui.notify("usage: /bettertui group on|off", "warning");
587
+ return;
588
+ }
589
+ break;
590
+ case "tools":
591
+ if (value === "on" || value === "off") {
592
+ config.tools.compact = value === "on";
593
+ changed = true;
594
+ } else {
595
+ ctx.ui.notify("usage: /bettertui tools on|off", "warning");
596
+ return;
597
+ }
598
+ break;
599
+ case "summary":
600
+ if (value === "on" || value === "off") {
601
+ config.turnSummary = value === "on";
602
+ changed = true;
603
+ } else {
604
+ ctx.ui.notify("usage: /bettertui summary on|off", "warning");
605
+ return;
606
+ }
607
+ break;
608
+ case "fold":
609
+ if (value === "on" || value === "off") {
610
+ config.fold.enabled = value === "on";
611
+ changed = true;
612
+ } else {
613
+ ctx.ui.notify("usage: /bettertui fold on|off", "warning");
614
+ return;
615
+ }
616
+ break;
617
+ case "describe":
618
+ if (value === "on" || value === "off") {
619
+ config.tools.shellDescription = value === "on";
620
+ changed = true;
621
+ } else {
622
+ ctx.ui.notify("usage: /bettertui describe on|off (applies after /reload)", "warning");
623
+ return;
624
+ }
625
+ break;
626
+ case "shellfold":
627
+ if (value === "on" || value === "off") {
628
+ config.userShell.foldAnswered = value === "on";
629
+ changed = true;
630
+ } else {
631
+ ctx.ui.notify("usage: /bettertui shellfold on|off", "warning");
632
+ return;
633
+ }
634
+ break;
635
+ case "reset":
636
+ config = structuredClone(DEFAULT_CONFIG);
637
+ changed = true;
638
+ break;
639
+ case "status":
640
+ break;
641
+ default:
642
+ ctx.ui.notify(
643
+ "usage: /bettertui [status|on|off|header off|compact|thinking 0-5|group on|off|tools on|off|describe on|off|shellfold on|off|summary on|off|fold on|off|reset]",
644
+ "warning",
645
+ );
646
+ return;
647
+ }
648
+
649
+ if (changed) {
650
+ try {
651
+ saveConfig(config);
652
+ } catch (error) {
653
+ ctx.ui.notify(`pi-bettertui: could not save config: ${String(error)}`, "warning");
654
+ }
655
+ applyConfigChange(ctx);
656
+ }
657
+ ctx.ui.notify(`pi-bettertui: ${status()}`, "info");
658
+ },
659
+ });
660
+ }