@bismawy/pi-arnative 0.8.2 → 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,21 +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
45
  import { markPatched, originalOf } from "../lib/patch.ts";
46
46
 
47
47
  type Theme = { fg(color: string, text: string): string; bg?(color: string, text: string): string };
48
48
  type TResult = { content: Array<{ type: string; text?: string }>; isError?: boolean; details?: any };
49
- 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 };
50
50
  type Res = (r: TResult, th: Theme, soft: (s: string) => string, isErr: boolean, expanded: boolean) => string;
51
51
 
52
52
  const cwd = process.cwd();
53
53
  const MAX_TIMINGS = 200;
54
54
  const TIMINGS = new Map<string, number>();
55
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
+
56
61
  export function recordTiming(toolCallId: string, durationMs: number): void {
57
62
  if (TIMINGS.size >= MAX_TIMINGS) {
58
63
  const oldest = TIMINGS.keys().next().value;
@@ -146,9 +151,12 @@ export function titleRow(
146
151
  inner: number,
147
152
  dur: string,
148
153
  expanded: boolean,
154
+ hint = "",
149
155
  ): string[] {
150
156
  const head = `${icon} ${name} ${argPart}`.trim();
151
- 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) : "";
152
160
  if (!durStr) {
153
161
  return expanded ? wrapTextWithAnsi(head, inner) : [truncateToWidth(head, inner, "…")];
154
162
  }
@@ -191,10 +199,11 @@ export function toolSummary(name: string, text: string, args?: any): string {
191
199
  return title ? `${head}. ${title}` : head;
192
200
  }
193
201
 
194
- // Expand hint `[ctrl+o to expand]` (key text follows the active keybinding).
195
- export function expandHint(th: Theme): string {
196
- return th.fg("dim", `[${expandKeyName()} to expand]`);
197
- }
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]";
198
207
 
199
208
  // Expanded detail: themed markdown (same layout as a normal pi message — code
200
209
  // blocks, lists, colors) instead of a plain dim dump.
@@ -247,6 +256,17 @@ export function stripEdgesKeepingImages(lines: string[]): string[] {
247
256
  return [...head, ...lines.slice(firstImage)];
248
257
  }
249
258
 
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
+
250
270
  // The patches below reinstall on every module load (pi's /reload re-evaluates the
251
271
  // extension in the same process), so a UI fix applies without restarting pi; see
252
272
  // lib/patch.ts for the originals/mark bookkeeping that makes that safe.
@@ -255,9 +275,42 @@ if (ToolExecutionComponent?.prototype?.render) {
255
275
  const origRender = originalOf<(this: any, width: number) => string[]>(proto, "render");
256
276
  proto.render = markPatched(function (this: any, width: number): string[] {
257
277
  const lines = origRender.call(this, width);
258
- return OWN_BOX.has(this.toolName) || boxTheirRenderers(this) || !hasOwnRendererDef(this)
259
- ? stripEdgesKeepingImages(lines)
260
- : lines;
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);
261
314
  });
262
315
  }
263
316
 
@@ -267,21 +320,19 @@ if (ToolExecutionComponent?.prototype?.render) {
267
320
  // for tools that define no renderCall/renderResult of their own; third-party
268
321
  // renderers are handled by the generic predicate below.
269
322
  //
270
- // 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);
271
324
  // boxing itself is generic (see boxTheirRenderers). The pi-web-access tools get a
272
325
  // friendlier title ("search "/"fetch "/"get_content ") and their renderer content is
273
- // reused inside our box. `todo` (@juicesharp/rpiv-todo) gets a check-square icon
274
- // (\uf14a) and the toolPendingBg/toolSuccessBg backgrounds.
326
+ // reused inside our box.
275
327
  //
276
328
  // MCP tools (pi-mcp-adapter) declare `renderShell: "default"`, so the generic
277
329
  // predicate boxes them, but their result renderer prints the WHOLE output on error
278
330
  // (unbounded) and their call args can run to dozens of lines: a 1-line summary +
279
- // [ctrl+o to expand] is tighter while the invoked tool stays visible.
331
+ // [show] is tighter while the invoked tool stays visible.
280
332
  const BOXED_TOOLS = new Map([
281
333
  ["web_search", "search"],
282
334
  ["fetch_content", "fetch"],
283
335
  ["get_search_content", "get_content"],
284
- ["todo", "todo"],
285
336
  ]);
286
337
 
287
338
  // @narumitw/pi-chrome-devtools ships bare-text renderers ("Chrome DevTools: navigate",
@@ -334,10 +385,10 @@ const mcpInfo = (name: string, args: any, th: Theme): string => {
334
385
  return tool ? th.fg("dim", `${tool}${server ? ` @ ${server}` : ""}`) : "";
335
386
  };
336
387
 
337
- // 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].
338
389
  const CALL_ROWS = 2;
339
390
  const capped = (th: Theme, rows: string[], expanded: boolean): string[] =>
340
- 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)];
341
392
 
342
393
  // Third-party renderers run unguarded here (at render time, unlike pi's own
343
394
  // updateDisplay which wraps them in try/catch + fallback): a throw becomes an
@@ -417,12 +468,18 @@ if (ToolExecutionComponent?.prototype?.render) {
417
468
  own && !CDP_NAME.has(name) && !MCP_TOOL(name)
418
469
  ? componentLines(safeCall(() => own.call(this, args, th, ctx)), width - 6)
419
470
  : [];
420
- if (name === "todo" && theirs.length)
421
- return box(th, width, formatTodoRows(theirs, th), "toolPendingBg");
422
471
  if (mine && theirs.length)
423
472
  return box(th, width, boxedRows(icon, capped(th, theirs, Boolean(this.expanded))));
424
473
  const inner = Math.max(8, width - 4);
425
- const rows = titleRow(th, icon, th.fg("accent", displayName(name)), mcpInfo(name, args, th), inner, "", false);
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
+ );
426
483
  return box(th, width, rows, boxBgOf(name));
427
484
  });
428
485
  });
@@ -461,27 +518,22 @@ if (ToolExecutionComponent?.prototype?.render) {
461
518
  const callLines = componentLines(safeCall(() => origCall.call(this)?.call(this, ctx.args, th, ctx)), width - 6);
462
519
  return box(th, width, boxedRows(icon, [callLines[0]?.trim() || displayName(name), ...boxed2]));
463
520
  }
464
- if (name === "todo" && boxed2.length) {
465
- // todo call result (status completed / in_progress)
466
- const callLines = componentLines(safeCall(() => origCall.call(this)?.call(this, ctx.args, th, ctx)), width - 6);
467
- const combined = [...callLines, ...boxed2];
468
- const bgType = isErr ? "toolErrorBg" : "toolSuccessBg";
469
- return box(th, width, formatTodoRows(combined, th), bgType);
470
- }
471
521
  if (boxed2.length && !cdp) return box(th, width, boxedRows(icon, boxed2));
522
+ const more = countLines(text) > 1;
472
523
  const rows = titleRow(
473
524
  th,
474
525
  icon,
475
526
  th.fg("accent", displayName(name)),
476
- 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),
477
530
  inner,
478
- "",
531
+ durationOf(ctx),
479
532
  opts.expanded,
533
+ more ? (opts.expanded ? HINT_COLLAPSE : HINT_EXPAND) : "",
480
534
  );
481
535
  const summary = toolSummary(name, text, ctx.args);
482
- const more = countLines(text) > 1;
483
- const hint = more && !opts.expanded ? ` ${expandHint(th)}` : "";
484
- rows.push(`${resHead(th)}${summary ? ` ${paintLinks(summary, soft)}` : ""}${hint}`);
536
+ rows.push(`${resHead(th)}${summary ? ` ${paintLinks(summary, soft)}` : ""}`);
485
537
  if (opts.expanded && more) {
486
538
  // MCP args are gone once the call box is replaced by the result.
487
539
  if (MCP_TOOL(name)) rows.push(th.fg("dim", `args ${JSON.stringify(ctx.args ?? {})}`));
@@ -493,22 +545,13 @@ if (ToolExecutionComponent?.prototype?.render) {
493
545
  });
494
546
  }
495
547
 
496
- // todo line format: \uf14a icon (success color) in the title, resHead prefix on the status line.
497
- const formatTodoRows = (lines: string[], th: Theme): string[] => {
498
- const icon = th.fg("success", "\uf14a");
499
- const head = resHead(th);
500
- const out: string[] = [];
501
- for (let i = 0; i < lines.length; i++) {
502
- let l = lines[i];
503
- if (i === 0) {
504
- l = l.replace(/^(\x1b\[[0-9;]*m)*todo\b/, `${icon} todo`);
505
- } else {
506
- l = `${head} ${l}`;
507
- }
508
- out.push(l);
509
- }
510
- return out;
511
- };
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
+ }
512
555
 
513
556
  // codemode: the script is highlighted, the calls and output come from pi's own details.
514
557
  function codeLines(code: string): string[] {
@@ -566,20 +609,25 @@ function codemodeBoxRows(
566
609
  expanded: boolean,
567
610
  isErr: boolean,
568
611
  icon: string,
612
+ inner: number,
613
+ dur = "",
569
614
  ): string[] {
570
- const rows = [`${icon} ${th.fg("accent", "codemode")}`];
571
- const script = codemodeScript(typeof args?.code === "string" ? args.code : "", expanded);
572
- 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);
573
617
  const calls = (result?.details?.calls as any[] | undefined) ?? [];
574
618
  const output = codemodeOutput(result?.content);
575
619
  const outLines = output ? output.split("\n") : [];
576
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}`));
577
627
  if (shown) {
578
628
  if (calls.length || outLines.length) rows.push("");
579
629
  rows.push(...calls.map((c) => formatCodemodeCall(c, th)), ...outLines.map((l) => th.fg("toolOutput", ` ${l}`)));
580
630
  }
581
- const hidden = script.hidden + (shown ? 0 : calls.length + outLines.length);
582
- if (!expanded && hidden > 0) rows[rows.length - 1] += ` ${expandHint(th)}`;
583
631
  return rows;
584
632
  }
585
633
 
@@ -642,11 +690,15 @@ function minimal(
642
690
  // `ctx.isError`/`result.isError` are the only honest sources: output text starting with
643
691
  // "Error" is normal content (a file whose first line says "Error handling...").
644
692
  const isErr = Boolean(context.isError || result.isError);
645
- const dur = fmtMs(context.toolCallId ? TIMINGS.get(context.toolCallId) : undefined);
693
+ const dur = durationOf(context as TCtx);
646
694
  const icon = isErr ? theme.fg("error", "x") : theme.fg("success", "✓");
647
695
  return new Lines((width) => {
648
696
  const soft = softSecondaryOf(theme);
649
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) : "";
650
702
  const rows = titleRow(
651
703
  theme,
652
704
  icon,
@@ -655,16 +707,11 @@ function minimal(
655
707
  inner,
656
708
  dur,
657
709
  expanded,
710
+ label,
658
711
  );
659
- // Anything the collapsed summary hides gets the standard hint; without it a
660
- // two-line box (edit: `+1 / -1`) looks complete while the diff sits behind it.
661
- const hasDetail = countLines(text) > 1 || Boolean((result.details as { diff?: string } | undefined)?.diff);
662
712
  const resLine = res(result, theme, soft, isErr, expanded);
663
713
  if (expanded) rows.push(...full(result, theme));
664
- else if (resLine) {
665
- const hint = hasDetail ? ` ${expandHint(theme)}` : "";
666
- rows.push(hint ? `${truncateToWidth(resLine, Math.max(8, inner - visibleWidth(hint)), "…")}${hint}` : resLine);
667
- }
714
+ else if (resLine) rows.push(resLine);
668
715
  return box(theme, width, rows);
669
716
  });
670
717
  },
@@ -820,7 +867,7 @@ const codemodeRenderers = {
820
867
  // Same spinner as every other box while the tool runs; the codemode glyph
821
868
  // only appears once the result is in (renderResult).
822
869
  const icon = th.fg("warning", spinIcon());
823
- 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);
824
871
  });
825
872
  },
826
873
  renderResult(result: TResult & { details?: any }, opts: { expanded: boolean; isPartial?: boolean }, th: Theme, ctx: TCtx) {
@@ -828,8 +875,9 @@ const codemodeRenderers = {
828
875
  ((ctx.state ??= {}) as Record<string, unknown>).hasResult = true;
829
876
  const isErr = Boolean(ctx.isError || result.isError);
830
877
  const icon = isErr ? th.fg("error", "x") : th.fg("success", "\uf489");
878
+ const dur = durationOf(ctx);
831
879
  return new Lines((width) =>
832
- 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"),
833
881
  );
834
882
  },
835
883
  };
@@ -936,9 +984,32 @@ if (isMain(import.meta.url)) {
936
984
  assert(noDefOut[0].startsWith("\u256d") && noDefOut[noDefOut.length - 1].startsWith("\u2570"), "tool without a definition: result wrapped in a box");
937
985
  assert(
938
986
  noDefOut.some((l: string) => l.includes("\u2713 glob")) &&
939
- noDefOut.some((l: string) => l.includes('[ctrl+o to expand]')),
987
+ noDefOut.some((l: string) => l.includes('[show]')),
940
988
  "tool without a definition: title + summary + expand hint",
941
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
+ );
942
1013
  // Generic predicate: any tool that ships its own renderers and no `renderShell: "self"`
943
1014
  // is boxed — no name list to maintain for new extensions.
944
1015
  const withRenderer = { toolName: "bash", toolDefinition: { renderResult: () => undefined } };
@@ -1121,7 +1192,7 @@ if (isMain(import.meta.url)) {
1121
1192
  }
1122
1193
 
1123
1194
  // pi-mcp-adapter: result does NOT use their renderer (unbounded error dump)
1124
- // -> 1-line summary + [ctrl+o to expand]; the invoked tool stays visible.
1195
+ // -> 1-line summary + [show]; the invoked tool stays visible.
1125
1196
  const mcpTheirs = () => "renderer-mcp";
1126
1197
  const mcpTool = { toolName: "mcp", toolDefinition: { renderCall: mcpTheirs, renderResult: mcpTheirs } };
1127
1198
  assert(
@@ -1148,7 +1219,28 @@ if (isMain(import.meta.url)) {
1148
1219
  mcpOut.some((l: string) => l.includes("fetch_content @ tinyfish")),
1149
1220
  "mcp: title names the invoked MCP tool",
1150
1221
  );
1151
- 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");
1152
1244
  const mcpFull = (ToolExecutionComponent.prototype.getResultRenderer.call(mcpTool) as any)(
1153
1245
  mcpPayload,
1154
1246
  { expanded: true, isPartial: false },
@@ -1258,7 +1350,7 @@ if (isMain(import.meta.url)) {
1258
1350
  out.some((l: string) => l.includes("Appended to MEMORY.md. ## Heading")),
1259
1351
  "box carries the summary + heading",
1260
1352
  );
1261
- 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");
1262
1354
  assert(
1263
1355
  resRenderer(
1264
1356
  { content: [{ type: "text", text: "Appended to MEMORY.md\n\nExisting preview" }] },
@@ -1283,28 +1375,6 @@ if (isMain(import.meta.url)) {
1283
1375
  syncTicker();
1284
1376
  assert(TICK === null, "ticker stops when idle (no timer leak)");
1285
1377
 
1286
- // todo render: \uf14a + 2 lines (title & status) + background box
1287
- const todoCall = () => ({ render: () => ["todo → Test subject"] });
1288
- const todoResult = () => ({ render: () => ["● completed"] });
1289
- const todoTool = { toolName: "todo", toolDefinition: { renderCall: todoCall, renderResult: todoResult } };
1290
- const thBgTodo: Theme = {
1291
- fg: (_c, s) => s,
1292
- bg: (c, s) => `[bg:${c}]${s}[/bg]`,
1293
- };
1294
- const todoCallOut = (ToolExecutionComponent.prototype.getCallRenderer.call(todoTool) as any)({}, thBgTodo, { state: {} }).render(60);
1295
- assert(todoCallOut[0].includes("[bg:toolPendingBg]"), "todo call: background pending");
1296
- assert(todoCallOut.some((l: string) => l.includes("\uf14a todo → Test subject")), "todo call: \uf14a icon in the title");
1297
-
1298
- const todoResultOut = (ToolExecutionComponent.prototype.getResultRenderer.call(todoTool) as any)(
1299
- { content: [] },
1300
- { expanded: false, isPartial: false },
1301
- thBgTodo,
1302
- { state: {}, args: {} },
1303
- ).render(60);
1304
- assert(todoResultOut[0].includes("[bg:toolSuccessBg]"), "todo result: background success");
1305
- assert(todoResultOut.some((l: string) => l.includes("\uf14a todo → Test subject")), "todo result: \uf14a icon on line 1");
1306
- assert(todoResultOut.some((l: string) => l.includes("● completed")), "todo result: status with the resHead prefix on line 2");
1307
-
1308
1378
  // Expanded detail: themed markdown, error text intact and no longer plain dim.
1309
1379
  const errDetail = fullText(
1310
1380
  { content: [{ type: "text", text: '{\n "pattern": "**/*.ts"\n}\nTool glob not found' }], isError: true },
@@ -1339,19 +1409,23 @@ if (isMain(import.meta.url)) {
1339
1409
  // pi prefixes the box with a spacer blank line; drop blanks so the rows are predictable.
1340
1410
  return (c.render(100) as string[]).map(stripAnsi).filter((l) => l !== "");
1341
1411
  };
1412
+ recordTiming("1", 10);
1342
1413
  const cmCollapsed = cmRender(cmArgs, cmRes);
1343
1414
  assert(cmCollapsed.length === 4 && cmCollapsed[0]!.startsWith("╭") && cmCollapsed[3]!.startsWith("╰"), "codemode: collapsed box is title + one script line inside the border");
1344
- 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");
1345
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");
1346
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");
1347
- // 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.
1348
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 };
1349
1422
  const cmErr = cmRender({ code: "boom()" }, longErr);
1350
- 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");
1351
1425
  // Running: the shared spinner, not the codemode glyph, and no hint while nothing is hidden.
1352
1426
  const cmRunning = cmRender({ code: "console.log(1);" }, undefined);
1353
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");
1354
- 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");
1355
1429
  assert([...cmCollapsed, ...cmExpanded, ...cmErr].every((l) => visibleWidth(l) === 100), "codemode: box fills the given width");
1356
1430
  assert(fmtMs(2) === "2ms" && fmtMs(1400) === "1.4s" && fmtMs(undefined) === "", "duration wording: ms under a second, s above");
1357
1431
  assert(codemodeOutput(cmRes.content) === "alpha: ok", "codemode: Script completed header dropped (own block)");
@@ -1368,11 +1442,47 @@ if (isMain(import.meta.url)) {
1368
1442
  return (c.render(74) as string[]).map(stripAnsi).filter((l) => l !== "");
1369
1443
  };
1370
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");
1371
1470
  const ed = minRender("edit", { path: "README.md" }, diffRes);
1372
- assert(ed.some((l) => l.includes("+1 / -1") && l.includes("to expand")), "minimal(): collapsed edit summary carries the expand hint");
1373
- 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");
1374
1480
  assert(
1375
- minRender("bash", { command: "true" }, { content: [{ type: "text", text: "done" }], details: {} }).every((l) => !l.includes("to expand")),
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
+ );
1484
+ assert(
1485
+ minRender("bash", { command: "true" }, { content: [{ type: "text", text: "done" }], details: {} }).every((l) => !l.includes("[show]")),
1376
1486
  "minimal(): a single-line output has nothing hidden, so no hint",
1377
1487
  );
1378
1488
  // Output that merely STARTS with "Error" is content, not a failure: the box keeps its ✓.
@@ -1424,8 +1534,106 @@ if (isMain(import.meta.url)) {
1424
1534
  assert(stripAnsi(cdpCallOut[1]!).includes(CDP_ICON), "chrome-devtools: call box uses the Chrome glyph, not the spinner");
1425
1535
  const cdpExpanded = cdpComp(cdpResult, true);
1426
1536
  assert(cdpExpanded.some((l) => l.includes('"pageId": "p1"')), "chrome-devtools: expanded shows the full tool output");
1427
- 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");
1428
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
+
1429
1637
  // Capped timings map self-check
1430
1638
  for (let i = 0; i < 250; i++) recordTiming(`call_${i}`, i);
1431
1639
  assert(TIMINGS.size === MAX_TIMINGS, `TIMINGS size is bounded to ${MAX_TIMINGS}`);