@bismawy/pi-arnative 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@
7
7
  * │ ✓ $ cmd smart… 0.1s │ final, collapsed; duration right-aligned
8
8
  * │ 󱞩 first output line │
9
9
  * ╰────────────────────────────╯
10
- * Click / the `app.tools.expand` key (ctrl+o by default) = full title + detail
10
+ * Click `[show]` / `[hide]` or press the `app.tools.expand` key (ctrl+o by default) = full title + detail
11
11
  * (output dim; edit = toolDiff*).
12
12
  * Collapsed summary: bash/write `󱞩 first line`; grep/find/read numeric
13
13
  * (→ N matches / → N files / N lines); edit `󱞩 +N / -M`. Expanded plain output
@@ -17,7 +17,7 @@
17
17
  * "has a result" lives in context.state, read at render() -> restore/reload safe,
18
18
  * no stale 󰔟 box. Third-party tools with no renderer of their own (memory_write,
19
19
  * scratchpad, MCP…) get the same box: shell "self", one-line summary,
20
- * `[ctrl+o to expand]` for the full detail.
20
+ * `[show]` for the full detail.
21
21
  */
22
22
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
23
23
  import {
@@ -38,20 +38,26 @@ import {
38
38
  } from "@earendil-works/pi-coding-agent";
39
39
  import { Markdown, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
40
40
  import { homedir } from "node:os";
41
- import { renderBoxLines as box } from "../lib/box.ts";
41
+ import { inSpans, renderBoxLines as box, type TextSpan, textSpans } from "../lib/box.ts";
42
42
  import { stripAnsi, softSecondaryOf } from "../lib/ansi.ts";
43
+ import { actionWord } from "../lib/todos.ts";
43
44
  import { assert, isMain } from "../lib/check.ts";
44
- import { expandKeyName } from "../lib/format.ts";
45
+ import { markPatched, originalOf } from "../lib/patch.ts";
45
46
 
46
47
  type Theme = { fg(color: string, text: string): string; bg?(color: string, text: string): string };
47
48
  type TResult = { content: Array<{ type: string; text?: string }>; isError?: boolean; details?: any };
48
- type TCtx = { isError?: boolean; toolCallId?: string; args?: any; state?: Record<string, unknown> };
49
+ type TCtx = { isError?: boolean; toolCallId?: string; args?: any; state?: Record<string, unknown>; durationMs?: number };
49
50
  type Res = (r: TResult, th: Theme, soft: (s: string) => string, isErr: boolean, expanded: boolean) => string;
50
51
 
51
52
  const cwd = process.cwd();
52
53
  const MAX_TIMINGS = 200;
53
54
  const TIMINGS = new Map<string, number>();
54
55
 
56
+ /** Runtime of one call: pi's own figure first (it survives a restore and covers tools this
57
+ * module does not wrap), then the wall time recorded by the execute wrapper. */
58
+ const durationOf = (ctx: TCtx): string =>
59
+ fmtMs(ctx.durationMs ?? (ctx.toolCallId ? TIMINGS.get(ctx.toolCallId) : undefined));
60
+
55
61
  export function recordTiming(toolCallId: string, durationMs: number): void {
56
62
  if (TIMINGS.size >= MAX_TIMINGS) {
57
63
  const oldest = TIMINGS.keys().next().value;
@@ -145,9 +151,12 @@ export function titleRow(
145
151
  inner: number,
146
152
  dur: string,
147
153
  expanded: boolean,
154
+ hint = "",
148
155
  ): string[] {
149
156
  const head = `${icon} ${name} ${argPart}`.trim();
150
- const durStr = dur ? theme.fg("dim", dur) : "";
157
+ // Runtime first, label last: the figure is what you read, the label is the button.
158
+ const right = [dur, hint].filter(Boolean).join(" · ");
159
+ const durStr = right ? theme.fg("dim", right) : "";
151
160
  if (!durStr) {
152
161
  return expanded ? wrapTextWithAnsi(head, inner) : [truncateToWidth(head, inner, "…")];
153
162
  }
@@ -190,10 +199,11 @@ export function toolSummary(name: string, text: string, args?: any): string {
190
199
  return title ? `${head}. ${title}` : head;
191
200
  }
192
201
 
193
- // Expand hint `[ctrl+o to expand]` (key text follows the active keybinding).
194
- export function expandHint(th: Theme): string {
195
- return th.fg("dim", `[${expandKeyName()} to expand]`);
196
- }
202
+ // The box says whether it is open with a word: [show] folded, [hide] open. The label is
203
+ // also the click target (see HINT_SPANS) and sits on the title row, so the affordance a
204
+ // click just used stays visible instead of vanishing with the summary line.
205
+ export const HINT_EXPAND = "[show]";
206
+ export const HINT_COLLAPSE = "[hide]";
197
207
 
198
208
  // Expanded detail: themed markdown (same layout as a normal pi message — code
199
209
  // blocks, lists, colors) instead of a plain dim dump.
@@ -246,16 +256,62 @@ export function stripEdgesKeepingImages(lines: string[]): string[] {
246
256
  return [...head, ...lines.slice(firstImage)];
247
257
  }
248
258
 
249
- const GAP_KEY = Symbol.for("pi-arnative.toolGapStripped");
250
- if (ToolExecutionComponent?.prototype?.render && !(globalThis as Record<symbol, boolean>)[GAP_KEY]) {
251
- (globalThis as Record<symbol, boolean>)[GAP_KEY] = true;
252
- const origRender = ToolExecutionComponent.prototype.render;
253
- ToolExecutionComponent.prototype.render = function (width: number): string[] {
259
+ // Per box: did this module strip the blank rows above it? Those rows shift every mouse
260
+ // row index, so a press on the border and the title row is found at 0 and 1 only for a
261
+ // stripped box. `Symbol.for` keeps the state across the re-import a `/reload` performs.
262
+ // Cells of the expand hint in this box's own drawn lines. The hint is the whole click
263
+ // target: every other cell of the box keeps pi's text selection, so the output stays
264
+ // copyable. Recomputed on every render, because the label moves with the width and the key.
265
+ const HINT_SPANS = Symbol.for("pi-arnative.toolBoxHintSpans");
266
+ // A press already toggled this box; the release and the synthesized click that follow it
267
+ // must not toggle it a second time.
268
+ const PRESS_TOGGLED = Symbol.for("pi-arnative.toolBoxPressToggled");
269
+
270
+ // The patches below reinstall on every module load (pi's /reload re-evaluates the
271
+ // extension in the same process), so a UI fix applies without restarting pi; see
272
+ // lib/patch.ts for the originals/mark bookkeeping that makes that safe.
273
+ if (ToolExecutionComponent?.prototype?.render) {
274
+ const proto = ToolExecutionComponent.prototype as any;
275
+ const origRender = originalOf<(this: any, width: number) => string[]>(proto, "render");
276
+ proto.render = markPatched(function (this: any, width: number): string[] {
254
277
  const lines = origRender.call(this, width);
255
- return OWN_BOX.has(this.toolName) || boxTheirRenderers(this) || !hasOwnRendererDef(this)
256
- ? stripEdgesKeepingImages(lines)
257
- : lines;
258
- };
278
+ const stripped = OWN_BOX.has(this.toolName) || boxTheirRenderers(this) || !hasOwnRendererDef(this);
279
+ const drawn = stripped ? stripEdgesKeepingImages(lines) : lines;
280
+ // Only a box this module laid out is measured here; a renderer pi owns keeps pi's
281
+ // own mouse path, since its row offsets come from a layout it did not show us.
282
+ // Title rows only (frame + title): a [show] inside the output must not become a button.
283
+ this[HINT_SPANS] = stripped
284
+ ? [...textSpans(drawn, HINT_EXPAND), ...textSpans(drawn, HINT_COLLAPSE)].filter((span) => span.row <= 1)
285
+ : [];
286
+ return drawn;
287
+ });
288
+
289
+ // Click to expand, on the hint text alone. pi toggles on the "click" it synthesizes from
290
+ // a press and a release at the same cell, so a one-cell drift made the hint look inert,
291
+ // and the stripped row above the box left its top border dead. A left press on the hint
292
+ // toggles at once and the release plus the click that follow are swallowed; the click
293
+ // clears the flag, not the release, or that click would toggle the box back. Any other
294
+ // cell is left to pi: a press there starts a selection, so the output can be copied.
295
+ const origMouse = originalOf<(this: any, event: any) => any>(proto, "handleMouse");
296
+ proto.handleMouse = markPatched(function (this: any, event: any): any {
297
+ const onHint = (this[HINT_SPANS] as TextSpan[] | undefined)?.length
298
+ ? inSpans(this[HINT_SPANS] as TextSpan[], event.y, event.x)
299
+ : false;
300
+ if (onHint && event.type === "press" && event.button === "left") {
301
+ // A child of the box (an image preview) keeps its own press.
302
+ const childHit = origMouse.call(this, event);
303
+ if (childHit) return childHit;
304
+ if (!this.result) return undefined;
305
+ this.setExpanded(!this.expanded);
306
+ this[PRESS_TOGGLED] = true;
307
+ return { handled: true, render: true };
308
+ }
309
+ if (this[PRESS_TOGGLED] && (event.type === "release" || event.type === "click")) {
310
+ if (event.type === "click") this[PRESS_TOGGLED] = false;
311
+ return { handled: true, render: false };
312
+ }
313
+ return origMouse.call(this, event);
314
+ });
259
315
  }
260
316
 
261
317
  // --- Tools without their own renderer: same box, one-line summary ---
@@ -264,21 +320,19 @@ if (ToolExecutionComponent?.prototype?.render && !(globalThis as Record<symbol,
264
320
  // for tools that define no renderCall/renderResult of their own; third-party
265
321
  // renderers are handled by the generic predicate below.
266
322
  //
267
- // BOXED_TOOLS is now a display-name map (plus the todo/cdp special render paths);
323
+ // BOXED_TOOLS is now a display-name map (plus the cdp special render path);
268
324
  // boxing itself is generic (see boxTheirRenderers). The pi-web-access tools get a
269
325
  // friendlier title ("search "/"fetch "/"get_content ") and their renderer content is
270
- // reused inside our box. `todo` (@juicesharp/rpiv-todo) gets a check-square icon
271
- // (\uf14a) and the toolPendingBg/toolSuccessBg backgrounds.
326
+ // reused inside our box.
272
327
  //
273
328
  // MCP tools (pi-mcp-adapter) declare `renderShell: "default"`, so the generic
274
329
  // predicate boxes them, but their result renderer prints the WHOLE output on error
275
330
  // (unbounded) and their call args can run to dozens of lines: a 1-line summary +
276
- // [ctrl+o to expand] is tighter while the invoked tool stays visible.
331
+ // [show] is tighter while the invoked tool stays visible.
277
332
  const BOXED_TOOLS = new Map([
278
333
  ["web_search", "search"],
279
334
  ["fetch_content", "fetch"],
280
335
  ["get_search_content", "get_content"],
281
- ["todo", "todo"],
282
336
  ]);
283
337
 
284
338
  // @narumitw/pi-chrome-devtools ships bare-text renderers ("Chrome DevTools: navigate",
@@ -311,12 +365,16 @@ const MCP_TOOL = (name: string): boolean => name === "mcp" || name === "mcpScrip
311
365
  // `powershell`/`ls` (their definitions spread `renderCall`/`renderResult` onto the
312
366
  // tool object) and pi-mcp-adapter (`renderShell: "default"`) all fall in by shape.
313
367
  //
368
+ // MCP is boxed even when pi-mcp-adapter declares `renderShell: "self"`: since 2.3x
369
+ // its default `toolResultRendering: "compact"` paints flat text (`mcp call x @ y`,
370
+ // no border), so a `self` shell there means "no box", not "my own box".
371
+ //
314
372
  // `source_check` is the single exception: its partial phase (curator URLs + approval
315
373
  // state) would disappear because our partial path returns nothing.
316
374
  const NOT_BOXED = new Set(["source_check"]);
317
375
  const boxTheirRenderers = (self: any): boolean =>
318
376
  Boolean(self.toolDefinition) &&
319
- self.toolDefinition.renderShell !== "self" &&
377
+ (self.toolDefinition.renderShell !== "self" || MCP_TOOL(self.toolName)) &&
320
378
  !NOT_BOXED.has(self.toolName);
321
379
 
322
380
  // The MCP box title names the invoked tool (full args when expanded).
@@ -327,10 +385,10 @@ const mcpInfo = (name: string, args: any, th: Theme): string => {
327
385
  return tool ? th.fg("dim", `${tool}${server ? ` @ ${server}` : ""}`) : "";
328
386
  };
329
387
 
330
- // Cap third-party lines in the call box; the rest goes behind [ctrl+o to expand].
388
+ // Cap third-party lines in the call box; the rest goes behind [show].
331
389
  const CALL_ROWS = 2;
332
390
  const capped = (th: Theme, rows: string[], expanded: boolean): string[] =>
333
- expanded || rows.length <= CALL_ROWS ? rows : [...rows.slice(0, CALL_ROWS), th.fg("dim", expandHint(th))];
391
+ expanded || rows.length <= CALL_ROWS ? rows : [...rows.slice(0, CALL_ROWS), th.fg("dim", HINT_EXPAND)];
334
392
 
335
393
  // Third-party renderers run unguarded here (at render time, unlike pi's own
336
394
  // updateDisplay which wraps them in try/catch + fallback): a throw becomes an
@@ -368,13 +426,11 @@ const boxedRows = (icon: string, lines: string[]): string[] => {
368
426
  */
369
427
  export const boxBgOf = (name: string): string | undefined => (name === "memory_write" ? "customMessageBg" : undefined);
370
428
 
371
- const DEFAULT_TOOL_KEY = Symbol.for("pi-arnative.defaultToolBox");
372
- if (ToolExecutionComponent?.prototype?.render && !(globalThis as Record<symbol, boolean>)[DEFAULT_TOOL_KEY]) {
373
- (globalThis as Record<symbol, boolean>)[DEFAULT_TOOL_KEY] = true;
429
+ if (ToolExecutionComponent?.prototype?.render) {
374
430
  const proto = ToolExecutionComponent.prototype as any;
375
- const origCall = proto.getCallRenderer;
376
- const origResult = proto.getResultRenderer;
377
- const origShell = proto.getRenderShell;
431
+ const origCall = originalOf<(this: any) => any>(proto, "getCallRenderer");
432
+ const origResult = originalOf<(this: any) => any>(proto, "getResultRenderer");
433
+ const origShell = originalOf<(this: any) => string>(proto, "getRenderShell");
378
434
  const hasOwnRenderer = (self: any): boolean =>
379
435
  !boxTheirRenderers(self) && Boolean(origCall.call(self) || origResult.call(self));
380
436
  // pi-fff splits title (renderCall) and result (renderResult) — both merge into one box.
@@ -387,37 +443,48 @@ if (ToolExecutionComponent?.prototype?.render && !(globalThis as Record<symbol,
387
443
  // getCallRenderer/getResultRenderer — our patch is bypassed and the call renders
388
444
  // as bare name + pretty-printed args. Claim those calls as defined so they take
389
445
  // the same box path as any other renderer-less tool.
390
- const origHasRendererDefinition = proto.hasRendererDefinition;
391
- proto.hasRendererDefinition = function (): boolean {
446
+ const origHasRendererDefinition = originalOf<(this: any) => boolean>(proto, "hasRendererDefinition");
447
+ proto.hasRendererDefinition = markPatched(function (this: any): boolean {
392
448
  return origHasRendererDefinition.call(this) || this.toolDefinition === undefined;
393
- };
449
+ });
394
450
 
395
- proto.getRenderShell = function (): string {
451
+ proto.getRenderShell = markPatched(function (this: any): string {
396
452
  if (boxTheirRenderers(this)) return "self";
397
453
  return hasOwnRenderer(this) ? origShell.call(this) : "self";
398
- };
454
+ });
399
455
 
400
- proto.getCallRenderer = function () {
401
- const name: string = this.toolName;
402
- const mine = boxTheirRenderers(this);
403
- const own = origCall.call(this);
404
- // Chrome DevTools' own renderCall is a bare line; ours replaces it (icon + name).
456
+ proto.getCallRenderer = markPatched(function (this: any) {
457
+ const name: string = this.toolName;
458
+ const mine = boxTheirRenderers(this);
459
+ const own = origCall.call(this);
460
+ // Chrome DevTools' own renderCall is a bare line and pi-mcp-adapter's compact one
461
+ // is the same flat text; ours replaces both (icon + name + invoked MCP tool).
405
462
  if (own && !mine && !CDP_NAME.has(name)) return own;
406
463
  return (args: any, th: Theme, ctx: TCtx) =>
407
464
  new Lines((width) => {
408
465
  if ((ctx.state as Record<string, unknown> | undefined)?.hasResult) return [];
409
466
  const icon = CDP_NAME.has(name) ? th.fg("accent", CDP_ICON) : th.fg("warning", spinIcon());
410
- const theirs = own ? componentLines(safeCall(() => own.call(this, args, th, ctx)), width - 6) : [];
411
- if (name === "todo" && theirs.length)
412
- return box(th, width, formatTodoRows(theirs, th), "toolPendingBg");
467
+ const theirs =
468
+ own && !CDP_NAME.has(name) && !MCP_TOOL(name)
469
+ ? componentLines(safeCall(() => own.call(this, args, th, ctx)), width - 6)
470
+ : [];
413
471
  if (mine && theirs.length)
414
472
  return box(th, width, boxedRows(icon, capped(th, theirs, Boolean(this.expanded))));
415
473
  const inner = Math.max(8, width - 4);
416
- return box(th, width, titleRow(th, icon, th.fg("accent", displayName(name)), "", inner, "", false), boxBgOf(name));
474
+ const rows = titleRow(
475
+ th,
476
+ icon,
477
+ th.fg("accent", displayName(name)),
478
+ name === "todo" ? todoTitleDetail(th, softSecondaryOf(th), actionWord(args?.action, args?.status)) : mcpInfo(name, args, th),
479
+ inner,
480
+ "",
481
+ false,
482
+ );
483
+ return box(th, width, rows, boxBgOf(name));
417
484
  });
418
- };
485
+ });
419
486
 
420
- proto.getResultRenderer = function () {
487
+ proto.getResultRenderer = markPatched(function (this: any) {
421
488
  const name: string = this.toolName;
422
489
  const own = origResult.call(this);
423
490
  // pi-fff splits title (renderCall) and result (renderResult); both go in one box.
@@ -451,27 +518,22 @@ if (ToolExecutionComponent?.prototype?.render && !(globalThis as Record<symbol,
451
518
  const callLines = componentLines(safeCall(() => origCall.call(this)?.call(this, ctx.args, th, ctx)), width - 6);
452
519
  return box(th, width, boxedRows(icon, [callLines[0]?.trim() || displayName(name), ...boxed2]));
453
520
  }
454
- if (name === "todo" && boxed2.length) {
455
- // todo call result (status completed / in_progress)
456
- const callLines = componentLines(safeCall(() => origCall.call(this)?.call(this, ctx.args, th, ctx)), width - 6);
457
- const combined = [...callLines, ...boxed2];
458
- const bgType = isErr ? "toolErrorBg" : "toolSuccessBg";
459
- return box(th, width, formatTodoRows(combined, th), bgType);
460
- }
461
521
  if (boxed2.length && !cdp) return box(th, width, boxedRows(icon, boxed2));
522
+ const more = countLines(text) > 1;
462
523
  const rows = titleRow(
463
524
  th,
464
525
  icon,
465
526
  th.fg("accent", displayName(name)),
466
- mcpInfo(name, ctx.args, th),
527
+ name === "todo"
528
+ ? todoTitleDetail(th, soft, (result.details as { detail?: unknown } | undefined)?.detail)
529
+ : mcpInfo(name, ctx.args, th),
467
530
  inner,
468
- "",
531
+ durationOf(ctx),
469
532
  opts.expanded,
533
+ more ? (opts.expanded ? HINT_COLLAPSE : HINT_EXPAND) : "",
470
534
  );
471
535
  const summary = toolSummary(name, text, ctx.args);
472
- const more = countLines(text) > 1;
473
- const hint = more && !opts.expanded ? ` ${expandHint(th)}` : "";
474
- rows.push(`${resHead(th)}${summary ? ` ${paintLinks(summary, soft)}` : ""}${hint}`);
536
+ rows.push(`${resHead(th)}${summary ? ` ${paintLinks(summary, soft)}` : ""}`);
475
537
  if (opts.expanded && more) {
476
538
  // MCP args are gone once the call box is replaced by the result.
477
539
  if (MCP_TOOL(name)) rows.push(th.fg("dim", `args ${JSON.stringify(ctx.args ?? {})}`));
@@ -480,25 +542,16 @@ if (ToolExecutionComponent?.prototype?.render && !(globalThis as Record<symbol,
480
542
  return box(th, width, rows, boxBgOf(name));
481
543
  });
482
544
  };
483
- };
545
+ });
484
546
  }
485
547
 
486
- // todo line format: \uf14a icon (success color) in the title, resHead prefix on the status line.
487
- const formatTodoRows = (lines: string[], th: Theme): string[] => {
488
- const icon = th.fg("success", "\uf14a");
489
- const head = resHead(th);
490
- const out: string[] = [];
491
- for (let i = 0; i < lines.length; i++) {
492
- let l = lines[i];
493
- if (i === 0) {
494
- l = l.replace(/^(\x1b\[[0-9;]*m)*todo\b/, `${icon} todo`);
495
- } else {
496
- l = `${head} ${l}`;
497
- }
498
- out.push(l);
499
- }
500
- return out;
501
- };
548
+ /** `todo · completed`: the status the call left behind (or its action word), so the title says
549
+ * what happened and not just which tool ran. The word takes the soft accent tier, the dot stays
550
+ * dim. */
551
+ function todoTitleDetail(th: Theme, soft: (s: string) => string, word: unknown): string {
552
+ const text = typeof word === "string" ? word.trim() : "";
553
+ return text ? `${th.fg("dim", "·")} ${soft(text)}` : "";
554
+ }
502
555
 
503
556
  // codemode: the script is highlighted, the calls and output come from pi's own details.
504
557
  function codeLines(code: string): string[] {
@@ -556,20 +609,25 @@ function codemodeBoxRows(
556
609
  expanded: boolean,
557
610
  isErr: boolean,
558
611
  icon: string,
612
+ inner: number,
613
+ dur = "",
559
614
  ): string[] {
560
- const rows = [`${icon} ${th.fg("accent", "codemode")}`];
561
- const script = codemodeScript(typeof args?.code === "string" ? args.code : "", expanded);
562
- script.lines.forEach((line, i) => rows.push(i === 0 ? `${resHead(th)} ${line}` : ` ${line}`));
615
+ const code = typeof args?.code === "string" ? args.code : "";
616
+ const script = codemodeScript(code, expanded);
563
617
  const calls = (result?.details?.calls as any[] | undefined) ?? [];
564
618
  const output = codemodeOutput(result?.content);
565
619
  const outLines = output ? output.split("\n") : [];
566
620
  const shown = expanded || isErr;
621
+ // A failing run shows its calls and output even when collapsed, so only a multi-line
622
+ // script gives it anything to fold; a passing run folds multi-line scripts, calls and output.
623
+ const foldable = countLines(code) > 1 || (!isErr && (calls.length > 0 || outLines.length > 0));
624
+ const label = foldable ? (expanded ? HINT_COLLAPSE : HINT_EXPAND) : "";
625
+ const rows = titleRow(th, icon, th.fg("accent", "codemode"), "", inner, dur, expanded, label);
626
+ script.lines.forEach((line, i) => rows.push(i === 0 ? `${resHead(th)} ${line}` : ` ${line}`));
567
627
  if (shown) {
568
628
  if (calls.length || outLines.length) rows.push("");
569
629
  rows.push(...calls.map((c) => formatCodemodeCall(c, th)), ...outLines.map((l) => th.fg("toolOutput", ` ${l}`)));
570
630
  }
571
- const hidden = script.hidden + (shown ? 0 : calls.length + outLines.length);
572
- if (!expanded && hidden > 0) rows[rows.length - 1] += ` ${expandHint(th)}`;
573
631
  return rows;
574
632
  }
575
633
 
@@ -632,11 +690,15 @@ function minimal(
632
690
  // `ctx.isError`/`result.isError` are the only honest sources: output text starting with
633
691
  // "Error" is normal content (a file whose first line says "Error handling...").
634
692
  const isErr = Boolean(context.isError || result.isError);
635
- const dur = fmtMs(context.toolCallId ? TIMINGS.get(context.toolCallId) : undefined);
693
+ const dur = durationOf(context as TCtx);
636
694
  const icon = isErr ? theme.fg("error", "x") : theme.fg("success", "✓");
637
695
  return new Lines((width) => {
638
696
  const soft = softSecondaryOf(theme);
639
697
  const inner = Math.max(8, width - 4);
698
+ // Anything the collapsed summary hides gets the standard hint; without it a
699
+ // two-line box (edit: `+1 / -1`) looks complete while the diff sits behind it.
700
+ const hasDetail = countLines(text) > 1 || Boolean((result.details as { diff?: string } | undefined)?.diff);
701
+ const label = hasDetail ? (expanded ? HINT_COLLAPSE : HINT_EXPAND) : "";
640
702
  const rows = titleRow(
641
703
  theme,
642
704
  icon,
@@ -645,16 +707,11 @@ function minimal(
645
707
  inner,
646
708
  dur,
647
709
  expanded,
710
+ label,
648
711
  );
649
- // Anything the collapsed summary hides gets the standard hint; without it a
650
- // two-line box (edit: `+1 / -1`) looks complete while the diff sits behind it.
651
- const hasDetail = countLines(text) > 1 || Boolean((result.details as { diff?: string } | undefined)?.diff);
652
712
  const resLine = res(result, theme, soft, isErr, expanded);
653
713
  if (expanded) rows.push(...full(result, theme));
654
- else if (resLine) {
655
- const hint = hasDetail ? ` ${expandHint(theme)}` : "";
656
- rows.push(hint ? `${truncateToWidth(resLine, Math.max(8, inner - visibleWidth(hint)), "…")}${hint}` : resLine);
657
- }
714
+ else if (resLine) rows.push(resLine);
658
715
  return box(theme, width, rows);
659
716
  });
660
717
  },
@@ -810,7 +867,7 @@ const codemodeRenderers = {
810
867
  // Same spinner as every other box while the tool runs; the codemode glyph
811
868
  // only appears once the result is in (renderResult).
812
869
  const icon = th.fg("warning", spinIcon());
813
- return box(th, width, codemodeBoxRows(args, undefined, th, Boolean(ctx.expanded), isErr, icon), bg);
870
+ return box(th, width, codemodeBoxRows(args, undefined, th, Boolean(ctx.expanded), isErr, icon, Math.max(8, width - 4)), bg);
814
871
  });
815
872
  },
816
873
  renderResult(result: TResult & { details?: any }, opts: { expanded: boolean; isPartial?: boolean }, th: Theme, ctx: TCtx) {
@@ -818,8 +875,9 @@ const codemodeRenderers = {
818
875
  ((ctx.state ??= {}) as Record<string, unknown>).hasResult = true;
819
876
  const isErr = Boolean(ctx.isError || result.isError);
820
877
  const icon = isErr ? th.fg("error", "x") : th.fg("success", "\uf489");
878
+ const dur = durationOf(ctx);
821
879
  return new Lines((width) =>
822
- box(th, width, codemodeBoxRows(ctx.args, result, th, Boolean(opts.expanded), isErr, icon), isErr ? "toolErrorBg" : "toolSuccessBg"),
880
+ box(th, width, codemodeBoxRows(ctx.args, result, th, Boolean(opts.expanded), isErr, icon, Math.max(8, width - 4), dur), isErr ? "toolErrorBg" : "toolSuccessBg"),
823
881
  );
824
882
  },
825
883
  };
@@ -926,9 +984,32 @@ if (isMain(import.meta.url)) {
926
984
  assert(noDefOut[0].startsWith("\u256d") && noDefOut[noDefOut.length - 1].startsWith("\u2570"), "tool without a definition: result wrapped in a box");
927
985
  assert(
928
986
  noDefOut.some((l: string) => l.includes("\u2713 glob")) &&
929
- noDefOut.some((l: string) => l.includes('[ctrl+o to expand]')),
987
+ noDefOut.some((l: string) => l.includes('[show]')),
930
988
  "tool without a definition: title + summary + expand hint",
931
989
  );
990
+ // todo (this package's own tool, no renderers): the title says what the call left behind.
991
+ const todoNoRenderer = { toolName: "todo", toolDefinition: {} };
992
+ const todoBox = (ToolExecutionComponent.prototype.getResultRenderer.call(todoNoRenderer) as any)(
993
+ { content: [{ type: "text", text: "Updated #1" }], details: { detail: "completed" } },
994
+ { expanded: false, isPartial: false },
995
+ th,
996
+ { args: { action: "update", id: 1, status: "completed" }, state: {} },
997
+ ).render(60);
998
+ assert(
999
+ todoBox.some((l: string) => l.includes("todo · completed")),
1000
+ `todo result: the title names the status, got ${todoBox.find((l: string) => l.includes("todo"))}`,
1001
+ );
1002
+ assert(todoBox.some((l: string) => l.includes("Updated #1")), "todo result: the status line keeps the result text");
1003
+ const todoPending = (ToolExecutionComponent.prototype.getCallRenderer.call(todoNoRenderer) as any)(
1004
+ { action: "create", subject: "Tulis widget" },
1005
+ th,
1006
+ { state: {}, args: {} },
1007
+ ).render(60);
1008
+ assert(todoPending.some((l: string) => l.includes("todo · created")), "todo call: the title names the action");
1009
+ assert(
1010
+ !todoBox.some((l: string) => l.includes("·") && l.includes("Tulis widget")),
1011
+ "todo: the task name stays on the status line, not in the title",
1012
+ );
932
1013
  // Generic predicate: any tool that ships its own renderers and no `renderShell: "self"`
933
1014
  // is boxed — no name list to maintain for new extensions.
934
1015
  const withRenderer = { toolName: "bash", toolDefinition: { renderResult: () => undefined } };
@@ -1111,7 +1192,7 @@ if (isMain(import.meta.url)) {
1111
1192
  }
1112
1193
 
1113
1194
  // pi-mcp-adapter: result does NOT use their renderer (unbounded error dump)
1114
- // -> 1-line summary + [ctrl+o to expand]; the invoked tool stays visible.
1195
+ // -> 1-line summary + [show]; the invoked tool stays visible.
1115
1196
  const mcpTheirs = () => "renderer-mcp";
1116
1197
  const mcpTool = { toolName: "mcp", toolDefinition: { renderCall: mcpTheirs, renderResult: mcpTheirs } };
1117
1198
  assert(
@@ -1138,7 +1219,28 @@ if (isMain(import.meta.url)) {
1138
1219
  mcpOut.some((l: string) => l.includes("fetch_content @ tinyfish")),
1139
1220
  "mcp: title names the invoked MCP tool",
1140
1221
  );
1141
- assert(mcpOut.some((l: string) => l.includes("[ctrl+o to expand]")), "mcp: expand hint present");
1222
+ assert(mcpOut.some((l: string) => l.includes("[show]")), "mcp: expand hint present");
1223
+ // Nothing hidden (a single output line), so the label goes away in both states.
1224
+ const mcpTiny = { content: [{ type: "text", text: "ok" }], details: {} };
1225
+ for (const expanded of [false, true]) {
1226
+ const rows = (ToolExecutionComponent.prototype.getResultRenderer.call(mcpTool) as any)(
1227
+ mcpTiny,
1228
+ { expanded, isPartial: false },
1229
+ th,
1230
+ { args: { tool: "fetch_content", server: "tinyfish" }, state: {} },
1231
+ ).render(96);
1232
+ assert(rows.every((l: string) => !l.includes("[show]") && !l.includes("[hide]")), `mcp: nothing hidden, so no label (expanded=${expanded})`);
1233
+ }
1234
+ // A box whose content comes from a third-party renderer still shows its runtime, the
1235
+ // way pi's own box did before this module replaced it.
1236
+ recordTiming("mcp-dur", 2400);
1237
+ const mcpTimed = (ToolExecutionComponent.prototype.getResultRenderer.call(mcpTool) as any)(
1238
+ mcpPayload,
1239
+ { expanded: false, isPartial: false },
1240
+ th,
1241
+ { args: { tool: "fetch_content", server: "tinyfish" }, state: {}, toolCallId: "mcp-dur" },
1242
+ ).render(96);
1243
+ assert(mcpTimed[1]!.includes("2.4s"), "mcp: the title row carries the runtime");
1142
1244
  const mcpFull = (ToolExecutionComponent.prototype.getResultRenderer.call(mcpTool) as any)(
1143
1245
  mcpPayload,
1144
1246
  { expanded: true, isPartial: false },
@@ -1147,6 +1249,40 @@ if (isMain(import.meta.url)) {
1147
1249
  ).render(96);
1148
1250
  assert(mcpFull.length > mcpOut.length, "mcp: expand shows the full dump + args");
1149
1251
 
1252
+ // pi-mcp-adapter >= 2.3x defaults to `toolResultRendering: "compact"`, which sets
1253
+ // `renderShell: "self"` and paints flat text (`mcp call x @ y`, no border). That
1254
+ // `self` means "no box", not "my own box", so the MCP names must still be boxed.
1255
+ const mcpCompact = { toolName: "mcp", toolDefinition: { renderShell: "self", renderCall: mcpTheirs, renderResult: mcpTheirs } };
1256
+ assert(
1257
+ ToolExecutionComponent.prototype.getRenderShell.call(mcpCompact) === "self" &&
1258
+ (ToolExecutionComponent.prototype.getResultRenderer.call(mcpCompact) as any) !== mcpTheirs,
1259
+ "mcp compact (renderShell self): still boxed, their flat renderer skipped",
1260
+ );
1261
+ const mcpCompactOut = (ToolExecutionComponent.prototype.getResultRenderer.call(mcpCompact) as any)(
1262
+ { content: [{ type: "text", text: "ok" }], details: {} },
1263
+ { expanded: false, isPartial: false },
1264
+ th,
1265
+ { args: { tool: "cloudflare_execute", server: "cloudflare" }, state: {} },
1266
+ ).render(96);
1267
+ assert(
1268
+ mcpCompactOut[0].startsWith("\u256d") && mcpCompactOut.some((l: string) => l.includes("cloudflare_execute @ cloudflare")),
1269
+ "mcp compact: bordered box naming the invoked tool",
1270
+ );
1271
+ const mcpCompactCall = (ToolExecutionComponent.prototype.getCallRenderer.call(mcpCompact) as any)(
1272
+ { tool: "cloudflare_execute", server: "cloudflare" },
1273
+ th,
1274
+ { args: {}, state: {} },
1275
+ ).render(96);
1276
+ assert(
1277
+ mcpCompactCall[0].startsWith("\u256d") && mcpCompactCall.some((l: string) => l.includes("cloudflare_execute @ cloudflare")),
1278
+ "mcp compact: the running box is ours too (no flat `mcp call ...` line)",
1279
+ );
1280
+ // A non-MCP fourth-party `renderShell: "self"` still draws its own box: untouched.
1281
+ assert(
1282
+ ToolExecutionComponent.prototype.getResultRenderer.call({ toolName: "other_ext", toolDefinition: { renderShell: "self", renderResult: mcpTheirs } })() === "renderer-mcp",
1283
+ "renderShell self outside MCP keeps its own renderer",
1284
+ );
1285
+
1150
1286
  // Gap is only stripped for our own box lines.
1151
1287
  // The default export registers the tools (filling OWN_BOX); a pi stub suffices.
1152
1288
  arnativeTools({
@@ -1214,7 +1350,7 @@ if (isMain(import.meta.url)) {
1214
1350
  out.some((l: string) => l.includes("Appended to MEMORY.md. ## Heading")),
1215
1351
  "box carries the summary + heading",
1216
1352
  );
1217
- assert(out.some((l: string) => l.includes("[ctrl+o to expand]")), "collapsed: expand hint present");
1353
+ assert(out.some((l: string) => l.includes("[show]")), "collapsed: expand hint present");
1218
1354
  assert(
1219
1355
  resRenderer(
1220
1356
  { content: [{ type: "text", text: "Appended to MEMORY.md\n\nExisting preview" }] },
@@ -1239,28 +1375,6 @@ if (isMain(import.meta.url)) {
1239
1375
  syncTicker();
1240
1376
  assert(TICK === null, "ticker stops when idle (no timer leak)");
1241
1377
 
1242
- // todo render: \uf14a + 2 lines (title & status) + background box
1243
- const todoCall = () => ({ render: () => ["todo → Test subject"] });
1244
- const todoResult = () => ({ render: () => ["● completed"] });
1245
- const todoTool = { toolName: "todo", toolDefinition: { renderCall: todoCall, renderResult: todoResult } };
1246
- const thBgTodo: Theme = {
1247
- fg: (_c, s) => s,
1248
- bg: (c, s) => `[bg:${c}]${s}[/bg]`,
1249
- };
1250
- const todoCallOut = (ToolExecutionComponent.prototype.getCallRenderer.call(todoTool) as any)({}, thBgTodo, { state: {} }).render(60);
1251
- assert(todoCallOut[0].includes("[bg:toolPendingBg]"), "todo call: background pending");
1252
- assert(todoCallOut.some((l: string) => l.includes("\uf14a todo → Test subject")), "todo call: \uf14a icon in the title");
1253
-
1254
- const todoResultOut = (ToolExecutionComponent.prototype.getResultRenderer.call(todoTool) as any)(
1255
- { content: [] },
1256
- { expanded: false, isPartial: false },
1257
- thBgTodo,
1258
- { state: {}, args: {} },
1259
- ).render(60);
1260
- assert(todoResultOut[0].includes("[bg:toolSuccessBg]"), "todo result: background success");
1261
- assert(todoResultOut.some((l: string) => l.includes("\uf14a todo → Test subject")), "todo result: \uf14a icon on line 1");
1262
- assert(todoResultOut.some((l: string) => l.includes("● completed")), "todo result: status with the resHead prefix on line 2");
1263
-
1264
1378
  // Expanded detail: themed markdown, error text intact and no longer plain dim.
1265
1379
  const errDetail = fullText(
1266
1380
  { content: [{ type: "text", text: '{\n "pattern": "**/*.ts"\n}\nTool glob not found' }], isError: true },
@@ -1295,19 +1409,23 @@ if (isMain(import.meta.url)) {
1295
1409
  // pi prefixes the box with a spacer blank line; drop blanks so the rows are predictable.
1296
1410
  return (c.render(100) as string[]).map(stripAnsi).filter((l) => l !== "");
1297
1411
  };
1412
+ recordTiming("1", 10);
1298
1413
  const cmCollapsed = cmRender(cmArgs, cmRes);
1299
1414
  assert(cmCollapsed.length === 4 && cmCollapsed[0]!.startsWith("╭") && cmCollapsed[3]!.startsWith("╰"), "codemode: collapsed box is title + one script line inside the border");
1300
- assert(cmCollapsed[2]!.includes("const l = await tools.todo") && cmCollapsed[2]!.includes("[ctrl+o to expand]"), "codemode: collapsed shows the first script line + hint");
1415
+ assert(cmCollapsed[1]!.endsWith("10ms · [show] │"), "codemode: the title row right-aligns the runtime and expand hint");
1416
+ assert(cmCollapsed[2]!.includes("const l = await tools.todo"), "codemode: collapsed shows the first script line");
1301
1417
  const cmExpanded = cmRender(cmArgs, cmRes, true);
1418
+ assert(cmExpanded[1]!.endsWith("10ms · [hide] │"), "codemode: the expanded title row right-aligns the runtime and fold hint");
1302
1419
  assert(cmExpanded.some((l) => l.includes("✓ todo") && l.includes("2ms")) && cmExpanded.some((l) => l.includes("alpha: ok")), "codemode: expanded shows the nested calls and the output");
1303
- // A failing run is never truncated: the whole output is shown without a hint.
1420
+ // A failing run is never truncated: the whole output is shown without a hint in either state.
1304
1421
  const longErr = { content: [{ type: "text", text: "Script failed\nWall time 0.1 seconds\nOutput:\n" + Array.from({ length: 12 }, (_, i) => `line ${i + 1}`).join("\n") }], isError: true };
1305
1422
  const cmErr = cmRender({ code: "boom()" }, longErr);
1306
- assert(cmErr.some((l) => l.includes("line 12")) && !cmErr.some((l) => l.includes("to expand")), "codemode: a failed run shows all its output, no hint");
1423
+ assert(cmErr.some((l) => l.includes("line 12")) && !cmErr.some((l) => l.includes("[show]")), "codemode: a failed run shows all its output, no hint");
1424
+ assert(!cmRender({ code: "boom()" }, longErr, true).some((l) => l.includes("[hide]")), "codemode: a failed single-line run has nothing to fold when expanded");
1307
1425
  // Running: the shared spinner, not the codemode glyph, and no hint while nothing is hidden.
1308
1426
  const cmRunning = cmRender({ code: "console.log(1);" }, undefined);
1309
1427
  assert(FRAMES.some((f) => cmRunning.join("\n").includes(f)) && !cmRunning.join("\n").includes("\uf489"), "codemode: running box uses the shared spinner, not the codemode glyph");
1310
- assert(!cmRunning.some((l) => l.includes("to expand")), "codemode: nothing hidden on a single-line script");
1428
+ assert(!cmRunning.some((l) => l.includes("[show]")), "codemode: nothing hidden on a single-line script");
1311
1429
  assert([...cmCollapsed, ...cmExpanded, ...cmErr].every((l) => visibleWidth(l) === 100), "codemode: box fills the given width");
1312
1430
  assert(fmtMs(2) === "2ms" && fmtMs(1400) === "1.4s" && fmtMs(undefined) === "", "duration wording: ms under a second, s above");
1313
1431
  assert(codemodeOutput(cmRes.content) === "alpha: ok", "codemode: Script completed header dropped (own block)");
@@ -1324,11 +1442,47 @@ if (isMain(import.meta.url)) {
1324
1442
  return (c.render(74) as string[]).map(stripAnsi).filter((l) => l !== "");
1325
1443
  };
1326
1444
  const diffRes = { content: [{ type: "text", text: "ok" }], details: { diff: "@@\n-old\n+new" } };
1445
+ // The runtime comes from pi's own duration first (a restored session, a tool this
1446
+ // module does not wrap), then from the wall clock this module records. The pinned
1447
+ // devDependency predates `durationMs`, so only the fallback is reachable here; the
1448
+ // pi-supplied path is checked against the installed 1.4.0 in the release audit.
1449
+ const withDur = (id: string, expanded: boolean) => {
1450
+ const c: any = new ToolExecutionComponent("bash", id, { command: "true" }, {}, reg2.bash, { requestRender() {} }, cwd);
1451
+ c.updateResult(diffRes, false);
1452
+ c.setExpanded(expanded);
1453
+ return (c.render(74) as string[]).map(stripAnsi).filter((l) => l !== "");
1454
+ };
1455
+ recordTiming("dur-collapsed", 1400);
1456
+ const durRow = withDur("dur-collapsed", false)[1]!;
1457
+ assert(durRow.includes("1.4s"), "duration: the collapsed title row keeps the runtime");
1458
+ assert(
1459
+ durRow.indexOf("1.4s") < durRow.indexOf("[show]") && durRow.includes("1.4s · [show]"),
1460
+ "duration: the runtime comes first, the label keeps the right edge",
1461
+ );
1462
+ recordTiming("dur-open", 400);
1463
+ const durOpen = withDur("dur-open", true);
1464
+ assert(
1465
+ durOpen[1]!.includes("400ms · [hide]"),
1466
+ "duration: the expanded title row carries the runtime before the fold label",
1467
+ );
1468
+ const bare = withDur("dur-none", false)[1]!;
1469
+ assert(!/dms|d.ds/.test(bare), "duration: a call with no figure leaves the row clean");
1327
1470
  const ed = minRender("edit", { path: "README.md" }, diffRes);
1328
- assert(ed.some((l) => l.includes("+1 / -1") && l.includes("to expand")), "minimal(): collapsed edit summary carries the expand hint");
1329
- assert(!minRender("edit", { path: "README.md" }, diffRes, true).some((l) => l.includes("to expand")), "minimal(): expanded edit drops the hint");
1471
+ assert(ed[1]!.includes("[show]"), "minimal(): the title row carries the expand hint");
1472
+ assert(ed.some((l) => l.includes("+1 / -1")), "minimal(): the summary stays on its own row");
1473
+ assert(!ed.some((l) => l.includes("+1 / -1") && l.includes("[show]")), "minimal(): the summary no longer shares its row with the hint");
1474
+ assert(!minRender("edit", { path: "README.md" }, diffRes, true).some((l) => l.includes("[show]")), "minimal(): expanded edit drops the hint");
1475
+ // Expanded, the affordance stays: the same key folds the box back, on the title row.
1476
+ const opened = minRender("edit", { path: "README.md" }, diffRes, true);
1477
+ assert(opened[1]!.includes("[hide]"), "minimal(): the expanded title row offers the fold hint");
1478
+ assert(!opened.some((l) => l.includes("[show]")), "minimal(): the folded box offers no expand hint");
1479
+ assert(opened.every((l) => visibleWidth(l) === 74), "minimal(): the fold hint keeps every row the box width");
1480
+ assert(
1481
+ minRender("edit", { path: "README.md" }, { content: [{ type: "text", text: "done" }], details: {} }, true).every((l) => !l.includes("[hide]")),
1482
+ "minimal(): nothing hidden, so an expanded box offers no fold hint",
1483
+ );
1330
1484
  assert(
1331
- minRender("bash", { command: "true" }, { content: [{ type: "text", text: "done" }], details: {} }).every((l) => !l.includes("to expand")),
1485
+ minRender("bash", { command: "true" }, { content: [{ type: "text", text: "done" }], details: {} }).every((l) => !l.includes("[show]")),
1332
1486
  "minimal(): a single-line output has nothing hidden, so no hint",
1333
1487
  );
1334
1488
  // Output that merely STARTS with "Error" is content, not a failure: the box keeps its ✓.
@@ -1380,13 +1534,151 @@ if (isMain(import.meta.url)) {
1380
1534
  assert(stripAnsi(cdpCallOut[1]!).includes(CDP_ICON), "chrome-devtools: call box uses the Chrome glyph, not the spinner");
1381
1535
  const cdpExpanded = cdpComp(cdpResult, true);
1382
1536
  assert(cdpExpanded.some((l) => l.includes('"pageId": "p1"')), "chrome-devtools: expanded shows the full tool output");
1383
- assert(cdpCollapsed.some((l) => l.includes("navigated") && l.includes("to expand")), "chrome-devtools: collapsed shows the first line + hint");
1537
+ assert(cdpCollapsed.some((l) => l.includes("navigated")), "chrome-devtools: collapsed shows the first line");
1538
+ assert(cdpCollapsed[1]!.includes("[show]"), "chrome-devtools: the title row carries the expand hint");
1384
1539
  assert([...cdpCollapsed, ...cdpExpanded].every((l) => visibleWidth(l) === 74), "chrome-devtools: box fills the given width");
1540
+ // Mouse on a tool box: the strip patch removes the blank rows above the box AFTER
1541
+ // pi laid out its mouse regions, so a click used to land one row high and the top
1542
+ // border was dead. pi also drops the click when the pointer drifts one cell.
1543
+ const mouseBox = () => {
1544
+ const c: any = new ToolExecutionComponent("mouse_probe", "1", {}, {}, {}, { requestRender: () => undefined }, cwd);
1545
+ c.updateResult({ content: [{ type: "text", text: "one\ntwo\nthree" }] }, false);
1546
+ // Render before any event: pi only hit-tests a click against a box it has measured.
1547
+ c.render(60);
1548
+ return c;
1549
+ };
1550
+ // Height comes from the box as drawn, the same number pi puts in the event.
1551
+ const mouse = (c: any, type: string, y: number, x = 5): any =>
1552
+ c.handleMouse({
1553
+ type,
1554
+ button: "left",
1555
+ x,
1556
+ y,
1557
+ screenX: x,
1558
+ screenY: y,
1559
+ width: 60,
1560
+ height: (c.render(60) as string[]).length,
1561
+ shift: false,
1562
+ alt: false,
1563
+ ctrl: false,
1564
+ });
1565
+ const click = (c: any, y: number, x = 5) => {
1566
+ mouse(c, "press", y, x);
1567
+ mouse(c, "release", y, x);
1568
+ mouse(c, "click", y, x);
1569
+ };
1570
+ const spans = (c: any) => textSpans(c.render(60) as string[], "[show]");
1571
+ const probeLines = mouseBox().render(60) as string[];
1572
+ assert(
1573
+ probeLines.length === 4 && stripAnsi(probeLines[0]!).startsWith("╭"),
1574
+ "mouse probe: 4 rows, blank edges stripped",
1575
+ );
1576
+ {
1577
+ const box = mouseBox();
1578
+ const [hint] = spans(box);
1579
+ assert(hint !== undefined, "mouse: the drawn box carries the hint span");
1580
+ const x = hint!.start;
1581
+ click(box, hint!.row, x);
1582
+ assert(box.expanded === true, "mouse: a click on the hint expands");
1583
+ click(box, hint!.row, x);
1584
+ assert(box.expanded === false, "mouse: the next click on the hint collapses");
1585
+ }
1586
+ {
1587
+ // A one-cell drift used to swallow the click: the press toggles, so it cannot.
1588
+ const box = mouseBox();
1589
+ const [hint] = spans(box);
1590
+ const x = hint!.start;
1591
+ mouse(box, "press", hint!.row, x);
1592
+ mouse(box, "move", hint!.row, x + 1);
1593
+ mouse(box, "release", hint!.row, x + 1);
1594
+ assert(box.expanded === true, "mouse: a one-cell drift on the hint still expands");
1595
+ mouse(box, "click", hint!.row, x + 1);
1596
+ assert(box.expanded === true, "mouse: the swallowed click does not toggle twice");
1597
+ }
1598
+ {
1599
+ // A label inside the output is content, not a button: only the title rows are matched.
1600
+ const outLabel: any = new ToolExecutionComponent("bash", "8", { command: "printf" }, {}, {}, { requestRender() {} }, cwd);
1601
+ outLabel.updateResult({ content: [{ type: "text", text: "line\n[show] in the output\nmore" }], details: {} }, false);
1602
+ outLabel.setExpanded(true);
1603
+ const outLines = (outLabel.render(60) as string[]).map(stripAnsi);
1604
+ const labelRow = outLines.findIndex((l) => l.includes("in the output"));
1605
+ assert(labelRow > 1, "mouse: the output label sits below the title rows");
1606
+ const labelX = outLines[labelRow]!.indexOf("[show]");
1607
+ const labelTaken = outLabel.handleMouse({ type: "press", button: "left", x: labelX, y: labelRow, screenX: labelX, screenY: labelRow, width: 60, height: outLines.length, shift: false, alt: false, ctrl: false });
1608
+ assert(labelTaken === undefined && outLabel.expanded === true, "mouse: a [show] inside the output is not a button");
1609
+ }
1610
+ {
1611
+ // Expanded, the fold hint is a click target too: the same cells, the other label.
1612
+ const box = mouseBox();
1613
+ const [open] = textSpans(box.render(60) as string[], "[show]");
1614
+ click(box, open!.row, open!.start);
1615
+ assert(box.expanded === true, "mouse: the expand hint opens the box");
1616
+ const [fold] = textSpans(box.render(60) as string[], "[hide]");
1617
+ assert(fold !== undefined, "mouse: the expanded box draws the fold hint");
1618
+ // One cell of drift: pi would drop the click, so only the hint cells can fold it.
1619
+ const fx = fold!.start;
1620
+ mouse(box, "press", fold!.row, fx);
1621
+ mouse(box, "move", fold!.row, fx + 1);
1622
+ mouse(box, "release", fold!.row, fx + 1);
1623
+ assert(box.expanded === false, "mouse: a drifting press on the fold hint closes the box");
1624
+ mouse(box, "click", fold!.row, fx + 1);
1625
+ assert(box.expanded === false, "mouse: the swallowed click does not reopen it");
1626
+ }
1627
+ {
1628
+ // Every cell off the hint stays with pi, which is what keeps the output copyable.
1629
+ const box = mouseBox();
1630
+ const taken = mouse(box, "press", 2, 6);
1631
+ assert(taken === undefined && box.expanded === false, "mouse: a press off the hint is left to pi (text selection)");
1632
+ mouse(box, "move", 2, 14);
1633
+ mouse(box, "release", 2, 14);
1634
+ assert(box.expanded === false, "mouse: a drag over the output does not expand the box");
1635
+ }
1636
+
1385
1637
  // Capped timings map self-check
1386
1638
  for (let i = 0; i < 250; i++) recordTiming(`call_${i}`, i);
1387
1639
  assert(TIMINGS.size === MAX_TIMINGS, `TIMINGS size is bounded to ${MAX_TIMINGS}`);
1388
1640
  assert(!TIMINGS.has("call_0") && TIMINGS.has("call_249"), "TIMINGS evicts oldest entries");
1389
1641
  TIMINGS.clear();
1390
1642
 
1643
+ // /reload re-evaluates this module inside the same pi process. The prototype patches
1644
+ // must reinstall with the new closures; a globalThis guard bailed out on the second
1645
+ // load and kept the old ones, so a UI fix never appeared until pi restarted.
1646
+ {
1647
+ const before = ToolExecutionComponent.prototype.getResultRenderer;
1648
+ await import(`${import.meta.url}?reload=1`);
1649
+ const after = ToolExecutionComponent.prototype.getResultRenderer;
1650
+ assert(after !== before, "/reload: the prototype patch reinstalls on re-evaluation");
1651
+ // The stored original must stay pi's own method: capturing our previous patch
1652
+ // wrapped every box in a second one (double border + double ✓).
1653
+ const stored = (ToolExecutionComponent.prototype as any)[Symbol.for("pi-arnative.protoOriginals")];
1654
+ const patchedMark = Symbol.for("pi-arnative.patchedMethod");
1655
+ assert(
1656
+ !stored.render[patchedMark] && !stored.getResultRenderer[patchedMark],
1657
+ "/reload: originals stay pi's own methods, never a previous patch",
1658
+ );
1659
+ const plainAfter = (ToolExecutionComponent.prototype.getResultRenderer.call(noRenderer) as any)(
1660
+ { content: [{ type: "text", text: "Appended to MEMORY.md" }] },
1661
+ { expanded: false, isPartial: false },
1662
+ th,
1663
+ { args: {}, state: {} },
1664
+ ).render(60);
1665
+ assert(
1666
+ plainAfter.filter((l: string) => l.startsWith("\u256d")).length === 1,
1667
+ "/reload: a plain tool draws one box, not a box inside a box",
1668
+ );
1669
+ const mcpAfter = (after as any).call(mcpCompact);
1670
+ assert(mcpAfter !== mcpTheirs, "/reload: MCP stays boxed after re-evaluation");
1671
+ const out2 = mcpAfter(
1672
+ { content: [{ type: "text", text: "ok" }], details: {} },
1673
+ { expanded: false, isPartial: false },
1674
+ th,
1675
+ { args: { tool: "cloudflare_execute", server: "cloudflare" }, state: {} },
1676
+ ).render(96);
1677
+ assert(
1678
+ out2[0].startsWith("\u256d") && out2.some((l: string) => l.includes("cloudflare_execute @ cloudflare")),
1679
+ "/reload: the box still renders (no double-patch loop, originals kept once)",
1680
+ );
1681
+ }
1682
+
1391
1683
  console.log("OK");
1392
1684
  }