@ftrdotdev/pi-tui 0.3.0 → 0.4.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.
@@ -6,20 +6,31 @@ import type {
6
6
  ToolDefinition,
7
7
  } from "@earendil-works/pi-coding-agent";
8
8
  import { initTheme } from "@earendil-works/pi-coding-agent";
9
- import { Markdown, Text } from "@earendil-works/pi-tui";
9
+ import {
10
+ Image,
11
+ Markdown,
12
+ resetCapabilitiesCache,
13
+ setCapabilities,
14
+ Text,
15
+ } from "@earendil-works/pi-tui";
10
16
  import { Context, Effect, PlatformError } from "effect";
11
17
  import * as FileSystem from "effect/FileSystem";
12
18
  import type { Component } from "@earendil-works/pi-tui";
13
19
  import {
20
+ bytesToBase64,
14
21
  capContent,
15
22
  COLLAPSED_LINES,
16
23
  MAX_BYTES,
17
24
  MAX_LINES,
25
+ mimeFromPath,
26
+ getAvifDimensions,
18
27
  PreviewReadError,
19
28
  PreviewService,
20
29
  renderBodyComponent,
21
30
  registerPreview,
22
31
  sliceUtf8,
32
+ type PreviewData,
33
+ type TextPreview,
23
34
  } from "./preview.ts";
24
35
 
25
36
  // The Markdown component reads pi's global theme at render time.
@@ -29,6 +40,51 @@ const HOMEDIR = "/home/test";
29
40
  const testHomedir = () => HOMEDIR;
30
41
  const encode = (raw: string) => new TextEncoder().encode(raw);
31
42
 
43
+ /**
44
+ * A minimal PNG header (signature + IHDR) carrying a 512x256 size. pi-tui's
45
+ * `getPngDimensions` only inspects the signature and the width/height words at
46
+ * offsets 16..23, so this suffices to exercise the dimension detection path.
47
+ */
48
+ const PNG_BYTES = new Uint8Array([
49
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, // PNG signature
50
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, // IHDR chunk header
51
+ 0x00, 0x00, 0x02, 0x00, // width = 512 (big-endian uint32)
52
+ 0x00, 0x00, 0x01, 0x00, // height = 256
53
+ ]);
54
+ const PNG_BASE64 = bytesToBase64(PNG_BYTES);
55
+
56
+ /**
57
+ * Build an AVIF-shaped ISO-BMFF file carrying the given width/height in an
58
+ * `ispe` box nested under meta → iprp → ipco (the standard AVIF layout).
59
+ */
60
+ function buildAvif(width: number, height: number): Uint8Array {
61
+ const box = (type: string, payload: number[]): number[] => {
62
+ const size = 8 + payload.length;
63
+ return [
64
+ (size >>> 24) & 0xff,
65
+ (size >>> 16) & 0xff,
66
+ (size >>> 8) & 0xff,
67
+ size & 0xff,
68
+ ...Array.from(type, (c) => c.charCodeAt(0)),
69
+ ...payload,
70
+ ];
71
+ };
72
+ const fullbox = (): number[] => [0, 0, 0, 0];
73
+ const u32 = (n: number): number[] => [
74
+ (n >>> 24) & 0xff,
75
+ (n >>> 16) & 0xff,
76
+ (n >>> 8) & 0xff,
77
+ n & 0xff,
78
+ ];
79
+ const ispe = box("ispe", [...fullbox(), ...u32(width), ...u32(height)]);
80
+ const ipco = box("ipco", ispe);
81
+ const iprp = box("iprp", [...fullbox(), ...ipco]);
82
+ const meta = box("meta", [...fullbox(), ...iprp]);
83
+ const ftyp = box("ftyp", [...Array.from("avif", (c) => c.charCodeAt(0)), 0, 0, 0, 0]);
84
+ return new Uint8Array([...ftyp, ...meta]);
85
+ }
86
+ const AVIF_BYTES = buildAvif(512, 256);
87
+
32
88
  /** Minimal shape guard: a renderable TUI component (replaces the former class check). */
33
89
  const isComponent = (c: unknown): c is Component => typeof (c as Component)?.render === "function";
34
90
  const decode = (buf: Uint8Array) => new TextDecoder().decode(buf);
@@ -159,24 +215,40 @@ it.effect("resolveFileRef trims surrounding whitespace", () =>
159
215
 
160
216
  interface MemFs {
161
217
  readonly fs: Partial<FileSystem.FileSystem>;
162
- readonly files: Map<string, string>;
218
+ readonly files: Map<string, Uint8Array>;
163
219
  }
164
220
 
165
- function makeMemFs(init: Record<string, string> = {}): MemFs {
166
- const files = new Map<string, string>(Object.entries(init));
221
+ /**
222
+ * In-memory FileSystem for tests. Text entries are keyed by path in the first
223
+ * argument, binary entries (images) in the second. Both `readFileString` and
224
+ * `readFile` are provided so PreviewService can read text and image files.
225
+ */
226
+ function makeMemFs(
227
+ init: Record<string, string> = {},
228
+ binary: Record<string, Uint8Array> = {},
229
+ ): MemFs {
230
+ const files = new Map<string, Uint8Array>();
231
+ for (const [p, raw] of Object.entries(init)) files.set(p, new TextEncoder().encode(raw));
232
+ for (const [p, bytes] of Object.entries(binary)) files.set(p, bytes);
233
+ const notFound = (method: string) => (path: string) =>
234
+ Effect.fail(
235
+ PlatformError.systemError({
236
+ _tag: "NotFound",
237
+ module: "FileSystem",
238
+ method,
239
+ pathOrDescriptor: path,
240
+ description: "No such file",
241
+ }),
242
+ );
167
243
  const fs: Partial<FileSystem.FileSystem> = {
168
- readFileString: (path) =>
244
+ readFile: (path) =>
169
245
  files.has(path)
170
246
  ? Effect.succeed(files.get(path)!)
171
- : Effect.fail(
172
- PlatformError.systemError({
173
- _tag: "NotFound",
174
- module: "FileSystem",
175
- method: "readFileString",
176
- pathOrDescriptor: path,
177
- description: "No such file",
178
- }),
179
- ),
247
+ : notFound("readFile")(path),
248
+ readFileString: (path) =>
249
+ files.has(path)
250
+ ? Effect.succeed(new TextDecoder().decode(files.get(path)!))
251
+ : notFound("readFileString")(path),
180
252
  };
181
253
  return { fs, files };
182
254
  }
@@ -187,11 +259,18 @@ const runRead = (mem: MemFs, absPath: string, maxBytes?: number, maxLines?: numb
187
259
  return yield* svc.read(absPath);
188
260
  }).pipe(Effect.provide(PreviewService.layerTest(mem.fs, testHomedir, maxBytes, maxLines)));
189
261
 
262
+ /** Narrow a read result to a text record, failing loudly if it came back as an image. */
263
+ const asText = (d: PreviewData): TextPreview => {
264
+ if (d.kind !== "text") throw new Error(`expected text preview, got "${d.kind}"`);
265
+ return d;
266
+ };
267
+
190
268
  it.effect("read returns the display record for a readable file", () =>
191
269
  Effect.gen(function* () {
192
270
  const mem = makeMemFs({ "/abs/file.md": "# Hello" });
193
271
  const data = yield* runRead(mem, "/abs/file.md");
194
272
  assert.deepStrictEqual(data, {
273
+ kind: "text",
195
274
  path: "/abs/file.md",
196
275
  content: "# Hello",
197
276
  lang: "markdown",
@@ -203,7 +282,7 @@ it.effect("read returns the display record for a readable file", () =>
203
282
  it.effect("read computes a code language hint from the path", () =>
204
283
  Effect.gen(function* () {
205
284
  const mem = makeMemFs({ "/abs/main.ts": "const x = 1;\n" });
206
- const data = yield* runRead(mem, "/abs/main.ts");
285
+ const data = asText(yield* runRead(mem, "/abs/main.ts"));
207
286
  assert.strictEqual(data.lang, "typescript");
208
287
  assert.strictEqual(data.truncated, false);
209
288
  }),
@@ -212,7 +291,7 @@ it.effect("read computes a code language hint from the path", () =>
212
291
  it.effect("read truncates content at the injected byte cap and reports truncated", () =>
213
292
  Effect.gen(function* () {
214
293
  const mem = makeMemFs({ "/abs/big.txt": "abcdef" });
215
- const data = yield* runRead(mem, "/abs/big.txt", 5);
294
+ const data = asText(yield* runRead(mem, "/abs/big.txt", 5));
216
295
  assert.strictEqual(data.content, "abcde");
217
296
  assert.strictEqual(data.truncated, true);
218
297
  }),
@@ -221,7 +300,7 @@ it.effect("read truncates content at the injected byte cap and reports truncated
221
300
  it.effect("read does not split a multi-byte character at the injected byte cap", () =>
222
301
  Effect.gen(function* () {
223
302
  const mem = makeMemFs({ "/abs/uni.txt": "€€€" });
224
- const data = yield* runRead(mem, "/abs/uni.txt", 4);
303
+ const data = asText(yield* runRead(mem, "/abs/uni.txt", 4));
225
304
  assert.strictEqual(data.content, "€");
226
305
  assert.strictEqual(data.truncated, true);
227
306
  }),
@@ -230,7 +309,7 @@ it.effect("read does not split a multi-byte character at the injected byte cap",
230
309
  it.effect("read truncates content at the injected line cap and reports truncated", () =>
231
310
  Effect.gen(function* () {
232
311
  const mem = makeMemFs({ "/abs/lines.txt": "a\nb\nc\nd" });
233
- const data = yield* runRead(mem, "/abs/lines.txt", 100, 3);
312
+ const data = asText(yield* runRead(mem, "/abs/lines.txt", 100, 3));
234
313
  assert.strictEqual(data.content, "a\nb\nc");
235
314
  assert.strictEqual(data.truncated, true);
236
315
  }),
@@ -239,12 +318,114 @@ it.effect("read truncates content at the injected line cap and reports truncated
239
318
  it.effect("read leaves content untruncated at the exact byte and line caps", () =>
240
319
  Effect.gen(function* () {
241
320
  const mem = makeMemFs({ "/abs/at.txt": "abcde" });
242
- const data = yield* runRead(mem, "/abs/at.txt", 5, 2000);
321
+ const data = asText(yield* runRead(mem, "/abs/at.txt", 5, 2000));
243
322
  assert.strictEqual(data.content, "abcde");
244
323
  assert.strictEqual(data.truncated, false);
245
324
  }),
246
325
  );
247
326
 
327
+ // ---------------------------------------------------------------------------
328
+ // Image preview — mime detection and image read behavior
329
+ // ---------------------------------------------------------------------------
330
+
331
+ it("mimeFromPath maps supported image extensions to their MIME type", () => {
332
+ assert.strictEqual(mimeFromPath("/a/pic.png"), "image/png");
333
+ assert.strictEqual(mimeFromPath("/a/pic.jpg"), "image/jpeg");
334
+ assert.strictEqual(mimeFromPath("/a/pic.jpeg"), "image/jpeg");
335
+ assert.strictEqual(mimeFromPath("/a/pic.gif"), "image/gif");
336
+ assert.strictEqual(mimeFromPath("/a/pic.webp"), "image/webp");
337
+ assert.strictEqual(mimeFromPath("/a/pic.avif"), "image/avif");
338
+ assert.strictEqual(mimeFromPath("/a/PIC.PNG"), "image/png"); // case-insensitive
339
+ assert.strictEqual(mimeFromPath("/a/notes.txt"), undefined);
340
+ assert.strictEqual(mimeFromPath("/a/noext"), undefined);
341
+ assert.strictEqual(mimeFromPath("/a/pic.svg"), undefined); // unsupported by pi-tui Image
342
+ });
343
+
344
+ it("bytesToBase64 round-trips through atob for ASCII and binary bytes", () => {
345
+ assert.strictEqual(bytesToBase64(encode("abc")), "YWJj");
346
+ const round = new Uint8Array(atob(bytesToBase64(PNG_BYTES)).split("").map((c) => c.charCodeAt(0)));
347
+ assert.deepStrictEqual(round, PNG_BYTES);
348
+ assert.strictEqual(bytesToBase64(PNG_BYTES), PNG_BASE64);
349
+ });
350
+
351
+ it.effect("read returns an image record with mime, base64, and detected dimensions", () =>
352
+ Effect.gen(function* () {
353
+ const mem = makeMemFs({}, { "/abs/pic.png": PNG_BYTES });
354
+ const data = yield* runRead(mem, "/abs/pic.png");
355
+ assert.strictEqual(data.kind, "image");
356
+ if (data.kind !== "image") return;
357
+ assert.strictEqual(data.path, "/abs/pic.png");
358
+ assert.strictEqual(data.mimeType, "image/png");
359
+ assert.strictEqual(data.base64, PNG_BASE64);
360
+ assert.deepStrictEqual(data.dimensions, { widthPx: 512, heightPx: 256 });
361
+ assert.strictEqual(data.truncated, false);
362
+ }),
363
+ );
364
+
365
+ it("getAvifDimensions parses the ispe box from an AVIF file", () => {
366
+ assert.deepStrictEqual(getAvifDimensions(AVIF_BYTES), { widthPx: 512, heightPx: 256 });
367
+ const tall = buildAvif(64, 128);
368
+ assert.deepStrictEqual(getAvifDimensions(tall), { widthPx: 64, heightPx: 128 });
369
+ assert.strictEqual(getAvifDimensions(new Uint8Array([1, 2, 3])), null); // no boxes
370
+ assert.strictEqual(getAvifDimensions(new Uint8Array()), null);
371
+ // A zero-sized ispe (width/height of 0) parses to null.
372
+ const ftypOnly = buildAvif(0, 0);
373
+ assert.strictEqual(getAvifDimensions(ftypOnly), null);
374
+ });
375
+
376
+ it.effect("read returns an AVIF image record with parsed dimensions", () =>
377
+ Effect.gen(function* () {
378
+ const mem = makeMemFs({}, { "/abs/pic.avif": AVIF_BYTES });
379
+ const data = yield* runRead(mem, "/abs/pic.avif");
380
+ assert.strictEqual(data.kind, "image");
381
+ if (data.kind !== "image") return;
382
+ assert.strictEqual(data.mimeType, "image/avif");
383
+ assert.deepStrictEqual(data.dimensions, { widthPx: 512, heightPx: 256 });
384
+ assert.strictEqual(data.truncated, false);
385
+ }),
386
+ );
387
+
388
+
389
+ it.effect("read routes jpeg/gif/webp extensions to image records", () =>
390
+ Effect.gen(function* () {
391
+ const mem = makeMemFs({}, { "/a/x.jpg": PNG_BYTES, "/a/y.gif": PNG_BYTES, "/a/z.webp": PNG_BYTES });
392
+ const jpeg = yield* runRead(mem, "/a/x.jpg");
393
+ const gif = yield* runRead(mem, "/a/y.gif");
394
+ const webp = yield* runRead(mem, "/a/z.webp");
395
+ assert.strictEqual(jpeg.kind, "image");
396
+ assert.strictEqual(gif.kind, "image");
397
+ assert.strictEqual(webp.kind, "image");
398
+ if (jpeg.kind === "image") assert.strictEqual(jpeg.mimeType, "image/jpeg");
399
+ if (gif.kind === "image") assert.strictEqual(gif.mimeType, "image/gif");
400
+ if (webp.kind === "image") assert.strictEqual(webp.mimeType, "image/webp");
401
+ }),
402
+ );
403
+
404
+ it.effect("read does not apply byte/line caps to image files", () =>
405
+ Effect.gen(function* () {
406
+ const mem = makeMemFs({}, { "/a/big.png": PNG_BYTES });
407
+ const data = yield* runRead(mem, "/a/big.png", 4);
408
+ assert.strictEqual(data.kind, "image");
409
+ if (data.kind !== "image") return;
410
+ assert.strictEqual(data.base64, PNG_BASE64);
411
+ assert.strictEqual(data.truncated, false);
412
+ }),
413
+ );
414
+
415
+ it.effect("read fails with PreviewReadError when an image file is missing", () =>
416
+ Effect.gen(function* () {
417
+ const mem = makeMemFs();
418
+ const err = yield* runRead(mem, "/missing.png").pipe(
419
+ Effect.match({
420
+ onFailure: (e) => e,
421
+ onSuccess: () => undefined,
422
+ }),
423
+ );
424
+ assert.ok(err instanceof PreviewReadError);
425
+ assert.strictEqual(err.path, "/missing.png");
426
+ }),
427
+ );
428
+
248
429
  it.effect("read fails with PreviewReadError when the file is missing", () =>
249
430
  Effect.gen(function* () {
250
431
  const mem = makeMemFs();
@@ -323,6 +504,7 @@ class FakePi {
323
504
  renderer: (entry: any, options: any, theme: any) => any;
324
505
  }> = [];
325
506
  readonly entries: Array<{ type: string; data?: unknown }> = [];
507
+ readonly toolResultHandlers: Array<(event: any) => any> = [];
326
508
  registerTool(tool: ToolDefinition<any, any, any>): void {
327
509
  this.tools.push(tool);
328
510
  }
@@ -335,6 +517,9 @@ class FakePi {
335
517
  appendEntry<T = unknown>(type: string, data?: T): void {
336
518
  this.entries.push({ type, data });
337
519
  }
520
+ on(event: string, handler: any): void {
521
+ if (event === "tool_result") this.toolResultHandlers.push(handler);
522
+ }
338
523
  }
339
524
 
340
525
  /** Build a Context.Context containing a PreviewService over the injected mem fs. */
@@ -370,6 +555,7 @@ it("tool execute returns the exact confirmation stub and the display record for
370
555
  "[Preview shown to user: src/file.md]",
371
556
  );
372
557
  assert.deepStrictEqual(result.details, {
558
+ kind: "text",
373
559
  path: "/cwd/src/file.md",
374
560
  content: "# Title",
375
561
  lang: "markdown",
@@ -377,6 +563,35 @@ it("tool execute returns the exact confirmation stub and the display record for
377
563
  });
378
564
  });
379
565
 
566
+ it("tool execute keeps the model stub for images and returns an image detail record", async () => {
567
+ const tool = registerTool(makeMemFs({}, { "/cwd/pic.png": PNG_BYTES }));
568
+ const ctx = { cwd: "/cwd" } as ExtensionContext;
569
+ const result = await tool.execute("call-1", { path: "pic.png" }, undefined, undefined, ctx);
570
+ assert.strictEqual(
571
+ (result.content[0] as { type: "text"; text: string }).text,
572
+ "[Preview shown to user: pic.png]",
573
+ );
574
+ // pi-native image block so the TUI renders the picture through its own pipeline.
575
+ // The block is what the model sees too (pi auto-resizes it for provider requests).
576
+ assert.deepStrictEqual(result.content[1], {
577
+ type: "image",
578
+ data: PNG_BASE64,
579
+ mimeType: "image/png",
580
+ });
581
+ const details = result.details as { kind: string; base64?: string; mimeType?: string };
582
+ assert.strictEqual(details.kind, "image");
583
+ assert.strictEqual(details.mimeType, "image/png");
584
+ assert.strictEqual(details.base64, PNG_BASE64);
585
+ });
586
+
587
+ it("tool execute returns only the text stub for text files (no image block)", async () => {
588
+ const tool = registerTool(makeMemFs({ "/cwd/file.md": "# Title" }));
589
+ const ctx = { cwd: "/cwd" } as ExtensionContext;
590
+ const result = await tool.execute("call-1", { path: "file.md" }, undefined, undefined, ctx);
591
+ assert.strictEqual(result.content.length, 1);
592
+ assert.strictEqual((result.content[0] as { type: string }).type, "text");
593
+ });
594
+
380
595
  it("tool execute resolves relative paths against the tool context cwd", async () => {
381
596
  const tool = registerTool(makeMemFs({ "/cwd/src/file.md": "# Title" }));
382
597
  const ctx = { cwd: "/cwd" } as ExtensionContext;
@@ -401,6 +616,7 @@ it("tool execute returns the exact failure stub and error details when the read
401
616
  );
402
617
  assert.deepStrictEqual(result.details, {
403
618
  path: "missing.md",
619
+ kind: "text",
404
620
  content: "",
405
621
  lang: undefined,
406
622
  truncated: false,
@@ -429,20 +645,20 @@ it("tool execute reports the failure stub when the reference is unresolvable", a
429
645
  });
430
646
 
431
647
  it("renderBodyComponent renders markdown content with the Markdown component when the language hint is markdown", () => {
432
- const data = { path: "/a.md", content: "# Hi", lang: "markdown", truncated: false };
648
+ const data = { kind: "text" as const, path: "/a.md", content: "# Hi", lang: "markdown", truncated: false };
433
649
  const out = renderBodyComponent(data, true, theme);
434
650
  assert.instanceOf(out, Markdown);
435
651
  });
436
652
 
437
653
  it("renderBodyComponent renders code content with the Text component when the language hint is not markdown", () => {
438
- const data = { path: "/a.ts", content: "const x = 1;", lang: "typescript", truncated: false };
654
+ const data = { kind: "text" as const, path: "/a.ts", content: "const x = 1;", lang: "typescript", truncated: false };
439
655
  const out = renderBodyComponent(data, true, theme);
440
656
  assert.instanceOf(out, Text);
441
657
  });
442
658
 
443
659
  it("renderBodyComponent collapses code content to the collapsed line count when not expanded", () => {
444
660
  const content = Array.from({ length: 45 }, (_, i) => `line ${i + 1}`).join("\n");
445
- const data = { path: "/a.ts", content, lang: "typescript", truncated: false };
661
+ const data = { kind: "text" as const, path: "/a.ts", content, lang: "typescript", truncated: false };
446
662
  const out = renderBodyComponent(data, false, theme);
447
663
  assert.instanceOf(out, Text);
448
664
  assert.strictEqual(
@@ -452,7 +668,7 @@ it("renderBodyComponent collapses code content to the collapsed line count when
452
668
  });
453
669
 
454
670
  it("renderBodyComponent appends the truncated note for a truncated expanded record", () => {
455
- const data = { path: "/a.md", content: "# Hi", lang: "markdown", truncated: true };
671
+ const data = { kind: "text" as const, path: "/a.md", content: "# Hi", lang: "markdown", truncated: true };
456
672
  const out = renderBodyComponent(data, true, theme);
457
673
  assert.instanceOf(out, Markdown);
458
674
  assert.strictEqual(out.render(200).join("\n").includes("... (truncated preview)"), true);
@@ -460,7 +676,7 @@ it("renderBodyComponent appends the truncated note for a truncated expanded reco
460
676
 
461
677
  it("renderBodyComponent appends the more-lines note for a collapsed markdown record", () => {
462
678
  const content = Array.from({ length: 41 }, (_, i) => `line ${i + 1}`).join("\n");
463
- const data = { path: "/a.md", content, lang: "markdown", truncated: false };
679
+ const data = { kind: "text" as const, path: "/a.md", content, lang: "markdown", truncated: false };
464
680
  const out = renderBodyComponent(data, false, theme);
465
681
  assert.instanceOf(out, Markdown);
466
682
  assert.strictEqual(
@@ -469,6 +685,62 @@ it("renderBodyComponent appends the more-lines note for a collapsed markdown rec
469
685
  );
470
686
  });
471
687
 
688
+ it("renderBodyComponent renders image data with the Image component", () => {
689
+ const data = {
690
+ kind: "image" as const,
691
+ path: "/a/pic.png",
692
+ mimeType: "image/png",
693
+ base64: PNG_BASE64,
694
+ dimensions: { widthPx: 512, heightPx: 256 },
695
+ truncated: false,
696
+ };
697
+ const out = renderBodyComponent(data, true, theme);
698
+ assert.instanceOf(out, Image);
699
+ });
700
+
701
+ it("renderBodyComponent image falls back to a text notice when the terminal lacks image support", () => {
702
+ setCapabilities({ images: null, trueColor: false, hyperlinks: false });
703
+ try {
704
+ const data = {
705
+ kind: "image" as const,
706
+ path: "/a/pic.png",
707
+ mimeType: "image/png",
708
+ base64: PNG_BASE64,
709
+ dimensions: { widthPx: 512, heightPx: 256 },
710
+ truncated: false,
711
+ };
712
+ const out = renderBodyComponent(data, true, theme);
713
+ assert.instanceOf(out, Image);
714
+ const lines = out.render(200).join("\n");
715
+ assert.strictEqual(lines.includes("/a/pic.png"), true);
716
+ assert.strictEqual(lines.includes("image/png"), true);
717
+ assert.strictEqual(lines.includes("512x256"), true);
718
+ } finally {
719
+ resetCapabilitiesCache();
720
+ }
721
+ });
722
+
723
+ it("renderBodyComponent image emits a kitty sequence when the terminal supports images", () => {
724
+ setCapabilities({ images: "kitty", trueColor: true, hyperlinks: true });
725
+ try {
726
+ const data = {
727
+ kind: "image" as const,
728
+ path: "/a/pic.png",
729
+ mimeType: "image/png",
730
+ base64: PNG_BASE64,
731
+ dimensions: { widthPx: 512, heightPx: 256 },
732
+ truncated: false,
733
+ };
734
+ const out = renderBodyComponent(data, true, theme);
735
+ assert.instanceOf(out, Image);
736
+ const lines = out.render(200);
737
+ assert.strictEqual(lines[0]?.startsWith("\x1b_G"), true);
738
+ assert.ok(lines.length >= 1);
739
+ } finally {
740
+ resetCapabilitiesCache();
741
+ }
742
+ });
743
+
472
744
  it("the preview tool renders its own shell instead of pi's standard tool box", () => {
473
745
  const tool = registerTool();
474
746
  assert.strictEqual(tool.renderShell, "self");
@@ -505,7 +777,7 @@ it("renderResult renders the warning box for an error result", () => {
505
777
  const tool = registerTool();
506
778
  const result = {
507
779
  content: [],
508
- details: { path: "/x", content: "", lang: undefined, truncated: false, error: "boom" },
780
+ details: { kind: "text", path: "/x", content: "", lang: undefined, truncated: false, error: "boom" },
509
781
  } as any;
510
782
  const out = tool.renderResult!(result, { expanded: true, isPartial: false }, theme, {} as any);
511
783
  assert.ok(isComponent(out));
@@ -515,7 +787,7 @@ it("renderResult renders the warning box for an error result", () => {
515
787
 
516
788
  it("renderResult renders the body in a bordered box for a success result", () => {
517
789
  const tool = registerTool();
518
- const record = { path: "/a.md", content: "# Hi", lang: "markdown", truncated: false };
790
+ const record = { kind: "text", path: "/a.md", content: "# Hi", lang: "markdown", truncated: false };
519
791
  const out = tool.renderResult!(
520
792
  { content: [], details: record } as any,
521
793
  { expanded: true, isPartial: false },
@@ -527,6 +799,39 @@ it("renderResult renders the body in a bordered box for a success result", () =>
527
799
  assert.strictEqual(out.render(200).join("\n").includes("Hi"), true);
528
800
  });
529
801
 
802
+ it("renderResult draws an image caption and leaves pixel drawing to pi's native content blocks", () => {
803
+ const tool = registerTool();
804
+ const record = {
805
+ kind: "image" as const,
806
+ path: "/a/pic.png",
807
+ mimeType: "image/png",
808
+ base64: PNG_BASE64,
809
+ dimensions: { widthPx: 512, heightPx: 256 },
810
+ truncated: false,
811
+ };
812
+ const out = tool.renderResult!(
813
+ { content: [], details: record } as any,
814
+ { expanded: true, isPartial: false },
815
+ theme,
816
+ {} as any,
817
+ );
818
+ assert.ok(isComponent(out));
819
+ const rendered = out.render(200).join("\n");
820
+ assert.strictEqual(rendered.startsWith("╭"), true); // caption box
821
+ assert.strictEqual(rendered.includes("/a/pic.png"), true);
822
+ assert.strictEqual(rendered.includes("512x256"), true);
823
+ // No raw kitty transmission from the renderer — pi renders the image natively.
824
+ assert.strictEqual(rendered.includes("\x1b_G"), false);
825
+ });
826
+
827
+ it("the model stub and image block both reach the model (image stays in content)", async () => {
828
+ // The image block is intentional: it is what makes the TUI render the picture
829
+ // through pi's native pipeline, and pi auto-resizes it for provider requests.
830
+ const pi = new FakePi();
831
+ registerPreview(pi as unknown as ExtensionAPI, makePreviewContext(makeMemFs()));
832
+ assert.strictEqual(pi.toolResultHandlers.length, 0, "no tool_result hook registered");
833
+ });
834
+
530
835
  // ---------------------------------------------------------------------------
531
836
  // Slice 5 — preview command and entry renderer behavior
532
837
  // ---------------------------------------------------------------------------
@@ -572,7 +877,7 @@ it("the preview command appends the display record as a custom entry on success"
572
877
  assert.deepStrictEqual(pi.entries, [
573
878
  {
574
879
  type: "preview",
575
- data: { path: "/cwd/file.md", content: "# Hi", lang: "markdown", truncated: false },
880
+ data: { kind: "text", path: "/cwd/file.md", content: "# Hi", lang: "markdown", truncated: false },
576
881
  },
577
882
  ]);
578
883
  assert.strictEqual(calls.length, 0);
@@ -627,7 +932,7 @@ it("the entry renderer renders the path header and the body inside a bordered bo
627
932
  registerPreview(pi as unknown as ExtensionAPI, makePreviewContext(makeMemFs()));
628
933
  const renderer = pi.renderers.find((r) => r.type === "preview")!.renderer;
629
934
  const out = renderer(
630
- { data: { path: "/abs/a.md", content: "# Hi", lang: "markdown", truncated: false } },
935
+ { data: { kind: "text", path: "/abs/a.md", content: "# Hi", lang: "markdown", truncated: false } },
631
936
  { expanded: true },
632
937
  theme,
633
938
  );
@@ -637,3 +942,43 @@ it("the entry renderer renders the path header and the body inside a bordered bo
637
942
  assert.strictEqual(rendered.includes("/abs/a.md"), true);
638
943
  assert.strictEqual(rendered.includes("Hi"), true);
639
944
  });
945
+
946
+ it("the entry renderer draws image entries as caption box + spacer + bare kitty transmission", () => {
947
+ setCapabilities({ images: "kitty", trueColor: true, hyperlinks: true });
948
+ try {
949
+ const pi = new FakePi();
950
+ registerPreview(pi as unknown as ExtensionAPI, makePreviewContext(makeMemFs()));
951
+ const renderer = pi.renderers.find((r) => r.type === "preview")!.renderer;
952
+ const out = renderer(
953
+ {
954
+ data: {
955
+ kind: "image",
956
+ path: "/abs/pic.png",
957
+ mimeType: "image/png",
958
+ base64: PNG_BASE64,
959
+ dimensions: { widthPx: 512, heightPx: 256 },
960
+ truncated: false,
961
+ },
962
+ },
963
+ { expanded: true },
964
+ theme,
965
+ );
966
+ assert.ok(isComponent(out));
967
+ const lines = out.render(200);
968
+ const rendered = lines.join("\n");
969
+ // Caption box on top…
970
+ assert.strictEqual(rendered.startsWith("╭"), true);
971
+ assert.strictEqual(rendered.includes("/abs/pic.png"), true);
972
+ // …then a blank spacer row…
973
+ const boxRows = rendered.split("\n");
974
+ assert.strictEqual(boxRows.includes(""), true);
975
+ // …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
+ assert.strictEqual(
978
+ lines.some((l: string) => l.includes("│ \x1b_G") || l.includes("╭ \x1b_G") || /[╭─╰╯]\x1b_G/.test(l)),
979
+ false,
980
+ );
981
+ } finally {
982
+ resetCapabilitiesCache();
983
+ }
984
+ });