@ftrdotdev/pi-tui 0.5.2 → 0.7.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.
@@ -45,6 +45,7 @@ const encode = (raw: string) => new TextEncoder().encode(raw);
45
45
  * `getPngDimensions` only inspects the signature and the width/height words at
46
46
  * offsets 16..23, so this suffices to exercise the dimension detection path.
47
47
  */
48
+ // prettier-ignore
48
49
  const PNG_BYTES = new Uint8Array([
49
50
  0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, // PNG signature
50
51
  0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, // IHDR chunk header
@@ -242,9 +243,7 @@ function makeMemFs(
242
243
  );
243
244
  const fs: Partial<FileSystem.FileSystem> = {
244
245
  readFile: (path) =>
245
- files.has(path)
246
- ? Effect.succeed(files.get(path)!)
247
- : notFound("readFile")(path),
246
+ files.has(path) ? Effect.succeed(files.get(path)!) : notFound("readFile")(path),
248
247
  readFileString: (path) =>
249
248
  files.has(path)
250
249
  ? Effect.succeed(new TextDecoder().decode(files.get(path)!))
@@ -343,7 +342,11 @@ it("mimeFromPath maps supported image extensions to their MIME type", () => {
343
342
 
344
343
  it("bytesToBase64 round-trips through atob for ASCII and binary bytes", () => {
345
344
  assert.strictEqual(bytesToBase64(encode("abc")), "YWJj");
346
- const round = new Uint8Array(atob(bytesToBase64(PNG_BYTES)).split("").map((c) => c.charCodeAt(0)));
345
+ const round = new Uint8Array(
346
+ atob(bytesToBase64(PNG_BYTES))
347
+ .split("")
348
+ .map((c) => c.charCodeAt(0)),
349
+ );
347
350
  assert.deepStrictEqual(round, PNG_BYTES);
348
351
  assert.strictEqual(bytesToBase64(PNG_BYTES), PNG_BASE64);
349
352
  });
@@ -385,10 +388,12 @@ it.effect("read returns an AVIF image record with parsed dimensions", () =>
385
388
  }),
386
389
  );
387
390
 
388
-
389
391
  it.effect("read routes jpeg/gif/webp extensions to image records", () =>
390
392
  Effect.gen(function* () {
391
- const mem = makeMemFs({}, { "/a/x.jpg": PNG_BYTES, "/a/y.gif": PNG_BYTES, "/a/z.webp": PNG_BYTES });
393
+ const mem = makeMemFs(
394
+ {},
395
+ { "/a/x.jpg": PNG_BYTES, "/a/y.gif": PNG_BYTES, "/a/z.webp": PNG_BYTES },
396
+ );
392
397
  const jpeg = yield* runRead(mem, "/a/x.jpg");
393
398
  const gif = yield* runRead(mem, "/a/y.gif");
394
399
  const webp = yield* runRead(mem, "/a/z.webp");
@@ -491,6 +496,7 @@ const theme = {
491
496
  fg: (_color: string, text: string) => text,
492
497
  bg: (_color: string, text: string) => text,
493
498
  bold: (text: string) => text,
499
+ style: (text: string) => text,
494
500
  } as unknown as Theme;
495
501
 
496
502
  class FakePi {
@@ -505,6 +511,7 @@ class FakePi {
505
511
  }> = [];
506
512
  readonly entries: Array<{ type: string; data?: unknown }> = [];
507
513
  readonly toolResultHandlers: Array<(event: any) => any> = [];
514
+ readonly toolExecutionEndHandlers: Array<(event: any, ctx?: any) => any> = [];
508
515
  registerTool(tool: ToolDefinition<any, any, any>): void {
509
516
  this.tools.push(tool);
510
517
  }
@@ -519,6 +526,7 @@ class FakePi {
519
526
  }
520
527
  on(event: string, handler: any): void {
521
528
  if (event === "tool_result") this.toolResultHandlers.push(handler);
529
+ if (event === "tool_execution_end") this.toolExecutionEndHandlers.push(handler);
522
530
  }
523
531
  }
524
532
 
@@ -645,20 +653,38 @@ it("tool execute reports the failure stub when the reference is unresolvable", a
645
653
  });
646
654
 
647
655
  it("renderBodyComponent renders markdown content with the Markdown component when the language hint is markdown", () => {
648
- const data = { kind: "text" as const, path: "/a.md", content: "# Hi", lang: "markdown", truncated: false };
656
+ const data = {
657
+ kind: "text" as const,
658
+ path: "/a.md",
659
+ content: "# Hi",
660
+ lang: "markdown",
661
+ truncated: false,
662
+ };
649
663
  const out = renderBodyComponent(data, true, theme);
650
664
  assert.instanceOf(out, Markdown);
651
665
  });
652
666
 
653
667
  it("renderBodyComponent renders code content with the Text component when the language hint is not markdown", () => {
654
- const data = { kind: "text" as const, path: "/a.ts", content: "const x = 1;", lang: "typescript", truncated: false };
668
+ const data = {
669
+ kind: "text" as const,
670
+ path: "/a.ts",
671
+ content: "const x = 1;",
672
+ lang: "typescript",
673
+ truncated: false,
674
+ };
655
675
  const out = renderBodyComponent(data, true, theme);
656
676
  assert.instanceOf(out, Text);
657
677
  });
658
678
 
659
679
  it("renderBodyComponent collapses code content to the collapsed line count when not expanded", () => {
660
680
  const content = Array.from({ length: 45 }, (_, i) => `line ${i + 1}`).join("\n");
661
- const data = { kind: "text" as const, path: "/a.ts", content, lang: "typescript", truncated: false };
681
+ const data = {
682
+ kind: "text" as const,
683
+ path: "/a.ts",
684
+ content,
685
+ lang: "typescript",
686
+ truncated: false,
687
+ };
662
688
  const out = renderBodyComponent(data, false, theme);
663
689
  assert.instanceOf(out, Text);
664
690
  assert.strictEqual(
@@ -668,7 +694,13 @@ it("renderBodyComponent collapses code content to the collapsed line count when
668
694
  });
669
695
 
670
696
  it("renderBodyComponent appends the truncated note for a truncated expanded record", () => {
671
- const data = { kind: "text" as const, path: "/a.md", content: "# Hi", lang: "markdown", truncated: true };
697
+ const data = {
698
+ kind: "text" as const,
699
+ path: "/a.md",
700
+ content: "# Hi",
701
+ lang: "markdown",
702
+ truncated: true,
703
+ };
672
704
  const out = renderBodyComponent(data, true, theme);
673
705
  assert.instanceOf(out, Markdown);
674
706
  assert.strictEqual(out.render(200).join("\n").includes("... (truncated preview)"), true);
@@ -676,7 +708,13 @@ it("renderBodyComponent appends the truncated note for a truncated expanded reco
676
708
 
677
709
  it("renderBodyComponent appends the more-lines note for a collapsed markdown record", () => {
678
710
  const content = Array.from({ length: 41 }, (_, i) => `line ${i + 1}`).join("\n");
679
- const data = { kind: "text" as const, path: "/a.md", content, lang: "markdown", truncated: false };
711
+ const data = {
712
+ kind: "text" as const,
713
+ path: "/a.md",
714
+ content,
715
+ lang: "markdown",
716
+ truncated: false,
717
+ };
680
718
  const out = renderBodyComponent(data, false, theme);
681
719
  assert.instanceOf(out, Markdown);
682
720
  assert.strictEqual(
@@ -777,7 +815,14 @@ it("renderResult renders the warning box for an error result", () => {
777
815
  const tool = registerTool();
778
816
  const result = {
779
817
  content: [],
780
- details: { kind: "text", path: "/x", content: "", lang: undefined, truncated: false, error: "boom" },
818
+ details: {
819
+ kind: "text",
820
+ path: "/x",
821
+ content: "",
822
+ lang: undefined,
823
+ truncated: false,
824
+ error: "boom",
825
+ },
781
826
  } as any;
782
827
  const out = tool.renderResult!(result, { expanded: true, isPartial: false }, theme, {} as any);
783
828
  assert.ok(isComponent(out));
@@ -787,7 +832,13 @@ it("renderResult renders the warning box for an error result", () => {
787
832
 
788
833
  it("renderResult renders the body in a bordered box for a success result", () => {
789
834
  const tool = registerTool();
790
- const record = { kind: "text", path: "/a.md", content: "# Hi", lang: "markdown", truncated: false };
835
+ const record = {
836
+ kind: "text",
837
+ path: "/a.md",
838
+ content: "# Hi",
839
+ lang: "markdown",
840
+ truncated: false,
841
+ };
791
842
  const out = tool.renderResult!(
792
843
  { content: [], details: record } as any,
793
844
  { expanded: true, isPartial: false },
@@ -877,7 +928,13 @@ it("the preview command appends the display record as a custom entry on success"
877
928
  assert.deepStrictEqual(pi.entries, [
878
929
  {
879
930
  type: "preview",
880
- data: { kind: "text", path: "/cwd/file.md", content: "# Hi", lang: "markdown", truncated: false },
931
+ data: {
932
+ kind: "text",
933
+ path: "/cwd/file.md",
934
+ content: "# Hi",
935
+ lang: "markdown",
936
+ truncated: false,
937
+ },
881
938
  },
882
939
  ]);
883
940
  assert.strictEqual(calls.length, 0);
@@ -932,7 +989,15 @@ it("the entry renderer renders the path header and the body inside a bordered bo
932
989
  registerPreview(pi as unknown as ExtensionAPI, makePreviewContext(makeMemFs()));
933
990
  const renderer = pi.renderers.find((r) => r.type === "preview")!.renderer;
934
991
  const out = renderer(
935
- { data: { kind: "text", path: "/abs/a.md", content: "# Hi", lang: "markdown", truncated: false } },
992
+ {
993
+ data: {
994
+ kind: "text",
995
+ path: "/abs/a.md",
996
+ content: "# Hi",
997
+ lang: "markdown",
998
+ truncated: false,
999
+ },
1000
+ },
936
1001
  { expanded: true },
937
1002
  theme,
938
1003
  );
@@ -973,12 +1038,81 @@ it("the entry renderer draws image entries as caption box + spacer + bare kitty
973
1038
  const boxRows = rendered.split("\n");
974
1039
  assert.strictEqual(boxRows.includes(""), true);
975
1040
  // …then the kitty transmission on its own line (no rail prefix, no box glyph before \x1b_G).
976
- assert.strictEqual(lines.some((l: string) => l.startsWith("\x1b_G")), true);
977
1041
  assert.strictEqual(
978
- lines.some((l: string) => l.includes("│ \x1b_G") || l.includes("╭ \x1b_G") || /[╭─╰╯]\x1b_G/.test(l)),
1042
+ lines.some((l: string) => l.startsWith("\x1b_G")),
1043
+ true,
1044
+ );
1045
+ assert.strictEqual(
1046
+ lines.some(
1047
+ (l: string) => l.includes("│ \x1b_G") || l.includes("╭ \x1b_G") || /[╭─╰╯]\x1b_G/.test(l),
1048
+ ),
979
1049
  false,
980
1050
  );
981
1051
  } finally {
982
1052
  resetCapabilitiesCache();
983
1053
  }
984
1054
  });
1055
+
1056
+ // ---------------------------------------------------------------------------
1057
+ // Slice 6 — nested (codemode) previews append a renderable entry
1058
+ // ---------------------------------------------------------------------------
1059
+
1060
+ const TEXT_RECORD: TextPreview = {
1061
+ kind: "text",
1062
+ path: "/cwd/file.md",
1063
+ content: "# Hi",
1064
+ lang: "markdown",
1065
+ truncated: false,
1066
+ };
1067
+
1068
+ const nestedEndEvent = (overrides: Record<string, unknown> = {}) => ({
1069
+ type: "tool_execution_end",
1070
+ toolCallId: "call-1/1",
1071
+ toolName: "preview",
1072
+ result: { content: [], details: TEXT_RECORD },
1073
+ isError: false,
1074
+ parentToolCallId: "call-1",
1075
+ ...overrides,
1076
+ });
1077
+
1078
+ const registerEndHook = () => {
1079
+ const pi = new FakePi();
1080
+ registerPreview(pi as unknown as ExtensionAPI, makePreviewContext(makeMemFs()));
1081
+ return { pi, handler: pi.toolExecutionEndHandlers[0]! };
1082
+ };
1083
+
1084
+ it("the nested-preview hook appends the display record so the entry renderer can draw it", () => {
1085
+ const { pi, handler } = registerEndHook();
1086
+ assert.strictEqual(pi.toolExecutionEndHandlers.length, 1);
1087
+ handler(nestedEndEvent(), { mode: "tui" });
1088
+ assert.deepStrictEqual(pi.entries, [{ type: "preview", data: TEXT_RECORD }]);
1089
+ });
1090
+
1091
+ it("the nested-preview hook ignores model-issued (top-level) preview ends", () => {
1092
+ const { pi, handler } = registerEndHook();
1093
+ handler(nestedEndEvent({ parentToolCallId: undefined }), { mode: "tui" });
1094
+ assert.strictEqual(pi.entries.length, 0);
1095
+ });
1096
+
1097
+ it("the nested-preview hook ignores nested ends for other tools", () => {
1098
+ const { pi, handler } = registerEndHook();
1099
+ handler(nestedEndEvent({ toolName: "read" }), { mode: "tui" });
1100
+ assert.strictEqual(pi.entries.length, 0);
1101
+ });
1102
+
1103
+ it("the nested-preview hook ignores non-tui modes", () => {
1104
+ const { pi, handler } = registerEndHook();
1105
+ handler(nestedEndEvent(), { mode: "rpc" });
1106
+ assert.strictEqual(pi.entries.length, 0);
1107
+ });
1108
+
1109
+ it("the nested-preview hook ignores failed previews", () => {
1110
+ const { pi, handler } = registerEndHook();
1111
+ handler(
1112
+ nestedEndEvent({
1113
+ result: { content: [], details: { ...TEXT_RECORD, content: "", error: "boom" } },
1114
+ }),
1115
+ { mode: "tui" },
1116
+ );
1117
+ assert.strictEqual(pi.entries.length, 0);
1118
+ });
package/src/ui/preview.ts CHANGED
@@ -431,13 +431,13 @@ function makePreviewComponent(data: PreviewData, expanded: boolean, theme: Theme
431
431
  ? `${data.path} (${data.dimensions.widthPx}x${data.dimensions.heightPx})`
432
432
  : data.path;
433
433
  return makeBorderedBox(new Text(theme.fg("accent", caption), 0, 0), theme, {
434
- label: theme.fg("accent", theme.bold("preview")),
435
- bg: (s) => theme.bg("customMessageBg", s),
434
+ label: theme.style("preview", { fg: "accent", bold: true }),
435
+ bg: "customMessageBg",
436
436
  });
437
437
  }
438
438
  return makeBorderedBox(renderBodyComponent(data, expanded, theme), theme, {
439
- label: theme.fg("accent", theme.bold("preview")),
440
- bg: (s) => theme.bg("customMessageBg", s),
439
+ label: theme.style("preview", { fg: "accent", bold: true }),
440
+ bg: "customMessageBg",
441
441
  });
442
442
  }
443
443
 
@@ -527,8 +527,8 @@ export function registerPreview(
527
527
 
528
528
  renderCall(args, theme) {
529
529
  return makeBorderedBox(new Text(args.path, 0, 0), theme, {
530
- label: theme.fg("toolTitle", theme.bold("preview")),
531
- bg: (s) => theme.bg("customMessageBg", s),
530
+ label: theme.style("preview", { fg: "toolTitle", bold: true }),
531
+ bg: "customMessageBg",
532
532
  });
533
533
  },
534
534
 
@@ -538,9 +538,9 @@ export function registerPreview(
538
538
  if (!data) return context.lastComponent ?? new Text("", 0, 0);
539
539
  if (data.error) {
540
540
  return makeBorderedBox(new Text(`preview failed: ${data.error}`, 0, 0), theme, {
541
- label: theme.fg("warning", theme.bold("preview")),
541
+ label: theme.style("preview", { fg: "warning", bold: true }),
542
542
  color: "warning",
543
- bg: (s) => theme.bg("customMessageBg", s),
543
+ bg: "customMessageBg",
544
544
  });
545
545
  }
546
546
  return makePreviewComponent(data, options.expanded, theme);
@@ -556,9 +556,9 @@ export function registerPreview(
556
556
  const noData = new Container();
557
557
  noData.addChild(new Text(theme.fg("warning", "[preview] no data"), 0, 0));
558
558
  return makeBorderedBox(noData, theme, {
559
- label: theme.fg("warning", theme.bold("preview")),
559
+ label: theme.style("preview", { fg: "warning", bold: true }),
560
560
  color: "warning",
561
- bg: (s) => theme.bg("customMessageBg", s),
561
+ bg: "customMessageBg",
562
562
  });
563
563
  }
564
564
  // Image entries mirror pi's native tool-image layout exactly: the bordered
@@ -585,11 +585,26 @@ export function registerPreview(
585
585
  body.addChild(new Text(theme.fg("accent", data.path), 0, 0));
586
586
  body.addChild(renderBodyComponent(data, expanded, theme));
587
587
  return makeBorderedBox(body, theme, {
588
- label: theme.fg("accent", theme.bold("preview")),
589
- bg: (s) => theme.bg("customMessageBg", s),
588
+ label: theme.style("preview", { fg: "accent", bold: true }),
589
+ bg: "customMessageBg",
590
590
  });
591
591
  });
592
592
 
593
+ // A preview called from inside a codemode script never gets its own tool row:
594
+ // pi's interactive mode ignores nested `tool_execution_*` events, and nested
595
+ // results never become transcript entries. The widget that `renderResult`
596
+ // draws for model-issued calls is therefore dropped, and codemode's renderer
597
+ // shows only the text call-row. Mirror the `/preview` command and append the
598
+ // display record as a custom entry so the entry renderer above draws it.
599
+ pi.on("tool_execution_end", (event, ctx) => {
600
+ if (!event.parentToolCallId || event.toolName !== "preview") return;
601
+ if (ctx.mode !== "tui") return;
602
+ const data = (event.result as { details?: PreviewData | PreviewDataError } | undefined)
603
+ ?.details;
604
+ if (!data || "error" in data) return;
605
+ pi.appendEntry("preview", data);
606
+ });
607
+
593
608
  pi.registerCommand("preview", {
594
609
  description:
595
610
  "Display a file in the chat for the user to read (TUI only, not sent to the model).",
@@ -0,0 +1,25 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import type { Theme } from "@earendil-works/pi-coding-agent";
3
+ import { renderBar, renderRuntimeSegment } from "./render-helpers.ts";
4
+
5
+ // Identity theme: styling is a no-op so assertions read the plain text.
6
+ const theme = {
7
+ fg: (_color: string, text: string) => text,
8
+ bg: (_color: string, text: string) => text,
9
+ bold: (text: string) => text,
10
+ } as unknown as Theme;
11
+
12
+ it("renderBar fills by rounded percentage in ascii and unicode", () => {
13
+ assert.strictEqual(renderBar(theme, 50, 10, true), "[#####-----]");
14
+ assert.strictEqual(renderBar(theme, 0, 4, false), "[░░░░]");
15
+ assert.strictEqual(renderBar(theme, 100, 4, true), "[####]");
16
+ assert.strictEqual(renderBar(theme, 150, 4, true), "[####]");
17
+ });
18
+
19
+ it("renderRuntimeSegment joins every runtime with a dim separator", () => {
20
+ assert.strictEqual(renderRuntimeSegment(theme, [], "ascii"), "");
21
+ assert.strictEqual(
22
+ renderRuntimeSegment(theme, [{ name: "nodejs", version: "1.2.3" }, { name: "rust" }], "ascii"),
23
+ "node 1.2.3 · rs",
24
+ );
25
+ });
@@ -159,19 +159,22 @@ export function renderGitSegment(
159
159
  }
160
160
 
161
161
  /**
162
- * The runtime footer segment: a runtime symbol (ascii or nerd per the
163
- * icon mode) plus its version when known. Returns `""` for no runtime.
162
+ * The runtime footer segment: one symbol (ascii or nerd per the icon mode)
163
+ * per matching runtime, each with its version when known. Multiple runtimes
164
+ * are joined with a dim separator. Returns `""` for no runtime.
164
165
  */
165
166
  export function renderRuntimeSegment(
166
167
  theme: Theme,
167
- runtime: RuntimeInfo | null,
168
+ runtimes: readonly RuntimeInfo[],
168
169
  iconMode: TuiConfig["icons"]["mode"],
169
170
  ): string {
170
- if (!runtime) return "";
171
- const symbol = theme.fg("success", runtimeSymbol(runtime.name, iconMode));
172
- const version = runtime.version ? theme.fg("muted", runtime.version) : "";
173
- const label = [symbol, version].filter(Boolean).join(" ");
174
- return label;
171
+ return runtimes
172
+ .map((runtime) => {
173
+ const symbol = theme.fg("success", runtimeSymbol(runtime.name, iconMode));
174
+ const version = runtime.version ? theme.fg("muted", runtime.version) : "";
175
+ return [symbol, version].filter(Boolean).join(" ");
176
+ })
177
+ .join(theme.fg("dim", " · "));
175
178
  }
176
179
 
177
180
  /**
@@ -189,7 +192,9 @@ export interface TimerSegmentParts {
189
192
  function renderSplit(theme: Theme, glyphs: IconGlyphs, inference: number, tool: number): string {
190
193
  const buckets: string[] = [];
191
194
  if (inference > 0) {
192
- buckets.push(`${theme.fg("dim", glyphs.inference)} ${theme.fg("accent", formatDuration(inference))}`);
195
+ buckets.push(
196
+ `${theme.fg("dim", glyphs.inference)} ${theme.fg("accent", formatDuration(inference))}`,
197
+ );
193
198
  }
194
199
  if (tool > 0) {
195
200
  buckets.push(`${theme.fg("dim", glyphs.tool)} ${theme.fg("accent", formatDuration(tool))}`);