@ftrdotdev/pi-tui 0.2.1 → 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.
package/src/ui/preview.ts CHANGED
@@ -2,16 +2,19 @@
2
2
  * preview — display a file in the chat for the human only.
3
3
  *
4
4
  * Two entry points:
5
- * - `preview` tool: the model calls it. The TUI renders the full file (with
6
- * syntax highlighting) while the model only receives a one-line
7
- * confirmation. Use when the user needs to review a file that the model
8
- * does not need in its context.
5
+ * - `preview` tool: the model calls it. The TUI renders the full file — text
6
+ * with syntax highlighting, images inline via the terminal's graphics
7
+ * protocol — while the model only receives a one-line confirmation (image
8
+ * bytes live only in the TUI `details`, never in model context). Use when
9
+ * the user needs to review a file that the model does not need in its
10
+ * context.
9
11
  * - `/preview <path>` command: the human invokes it. The content is stored as
10
12
  * a custom entry that never participates in LLM context.
11
13
  *
12
14
  * The module has no direct Node dependencies: file reads go through the
13
15
  * platform `FileSystem` service, path operations through the `Path` service,
14
- * and byte slicing uses the standard `Uint8Array`/`TextEncoder` Web APIs. The
16
+ * and byte slicing/base64 encoding uses the standard `Uint8Array`/`TextEncoder`
17
+ * /`btoa` Web APIs. The
15
18
  * only platform primitive without an Effect service — the home directory used
16
19
  * for `~` expansion — is injected into {@link PreviewService.make} and bound
17
20
  * at the entry point (src/index.ts). The registrations run the pipeline
@@ -26,7 +29,15 @@ import {
26
29
  getMarkdownTheme,
27
30
  highlightCode,
28
31
  } from "@earendil-works/pi-coding-agent";
29
- import { Container, Markdown, Text } from "@earendil-works/pi-tui";
32
+ import {
33
+ Container,
34
+ getImageDimensions,
35
+ Image,
36
+ Markdown,
37
+ Spacer,
38
+ Text,
39
+ type ImageDimensions,
40
+ } from "@earendil-works/pi-tui";
30
41
  import { makeBorderedBox } from "../components/bordered-box.ts";
31
42
  import { Type } from "typebox";
32
43
 
@@ -34,6 +45,127 @@ export const MAX_BYTES = 50 * 1024; // 50KB, matching the built-in read limits
34
45
  export const MAX_LINES = 2000;
35
46
  export const COLLAPSED_LINES = 40;
36
47
 
48
+ /** MIME types pi-tui's Image component can size and render (PNG/JPEG/GIF/WebP
49
+ * plus AVIF, whose size this module parses itself). */
50
+ const IMAGE_MIME_BY_EXT: Readonly<Record<string, string>> = {
51
+ ".png": "image/png",
52
+ ".jpg": "image/jpeg",
53
+ ".jpeg": "image/jpeg",
54
+ ".gif": "image/gif",
55
+ ".webp": "image/webp",
56
+ ".avif": "image/avif",
57
+ };
58
+
59
+ /**
60
+ * Map a path's extension to a renderable image MIME type, or undefined when
61
+ * the file is not one pi-tui's Image component can display. Comparison is
62
+ * case-insensitive.
63
+ */
64
+ export function mimeFromPath(path: string): string | undefined {
65
+ const lower = path.toLowerCase();
66
+ for (const ext of Object.keys(IMAGE_MIME_BY_EXT)) {
67
+ if (lower.endsWith(ext)) return IMAGE_MIME_BY_EXT[ext]!;
68
+ }
69
+ return undefined;
70
+ }
71
+
72
+ /**
73
+ * Encode raw bytes as base64 using Web APIs only. Chunked so large files do
74
+ * not exceed the engine's spread-argument limit on `String.fromCharCode`.
75
+ */
76
+ export function bytesToBase64(bytes: Uint8Array): string {
77
+ let binary = "";
78
+ const chunk = 0x8000;
79
+ for (let i = 0; i < bytes.length; i += chunk) {
80
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
81
+ }
82
+ return btoa(binary);
83
+ }
84
+
85
+ /** Read a big-endian u32 from a byte array (no DataView needed on a subarray). */
86
+ function readU32BE(bytes: Uint8Array, offset: number): number {
87
+ return (
88
+ (((bytes[offset] ?? 0) << 24) |
89
+ ((bytes[offset + 1] ?? 0) << 16) |
90
+ ((bytes[offset + 2] ?? 0) << 8) |
91
+ (bytes[offset + 3] ?? 0)) >>>
92
+ 0
93
+ );
94
+ }
95
+
96
+ /** The 4-char ASCII box type at an ISO-BMFF box header. */
97
+ function boxType(bytes: Uint8Array, offset: number): string {
98
+ return String.fromCharCode(
99
+ bytes[offset + 4] ?? 0,
100
+ bytes[offset + 5] ?? 0,
101
+ bytes[offset + 6] ?? 0,
102
+ bytes[offset + 7] ?? 0,
103
+ );
104
+ }
105
+
106
+ /** ISO-BMFF boxes that are FullBoxes (payload begins with a 4-byte version/flags header). */
107
+ const FULLBOX_CONTAINERS = new Set(["meta", "iprp", "ipma", "iinf", "iref", "iloc", "pitm"]);
108
+
109
+ /** ISO-BMFF container boxes to descend into when hunting `ispe` (skips `mdat`/image payloads). */
110
+ const CONTAINER_BOXES = new Set(["meta", "iprp", "ipco", "ipma", "iinf", "iref", "iloc", "pitm"]);
111
+
112
+ /**
113
+ * Recursively locate the first `ispe` box in an ISO-BMFF file (AVIF/HEIC),
114
+ * returning its payload offset and length, or null when absent. `ispe` holds
115
+ * the image's spatial extents. Only known container boxes are descended, so
116
+ * `mdat` image payloads are never scanned.
117
+ */
118
+ function findIspe(
119
+ bytes: Uint8Array,
120
+ start: number,
121
+ end: number,
122
+ ): { offset: number; length: number } | null {
123
+ let offset = start;
124
+ while (offset + 8 <= end) {
125
+ const type = boxType(bytes, offset);
126
+ let sizeField = readU32BE(bytes, offset);
127
+ let headerLen = 8;
128
+ if (sizeField === 1) {
129
+ // 64-bit largesize follows the 8-byte type.
130
+ headerLen = 16;
131
+ sizeField = readU32BE(bytes, offset + 12); // low 32 bits (high is effectively 0 for images)
132
+ if (offset + 16 > end) break;
133
+ } else if (sizeField === 0) {
134
+ sizeField = end - offset; // box extends to the end of the file
135
+ }
136
+ if (sizeField < headerLen) break; // malformed box
137
+ const payloadStart = offset + headerLen;
138
+ const payloadEnd = offset + sizeField;
139
+
140
+ if (type === "ispe") return { offset: payloadStart, length: sizeField - headerLen };
141
+
142
+ if (CONTAINER_BOXES.has(type)) {
143
+ // FullBox children skip their 4-byte version/flags header.
144
+ const childStart = FULLBOX_CONTAINERS.has(type) ? payloadStart + 4 : payloadStart;
145
+ const found = findIspe(bytes, childStart, payloadEnd);
146
+ if (found) return found;
147
+ }
148
+ if (payloadEnd <= offset) break;
149
+ offset = payloadEnd;
150
+ }
151
+ return null;
152
+ }
153
+
154
+ /**
155
+ * Parse the pixel dimensions of an AVIF file from its ISO-BMFF `ispe` box, or
156
+ * null when the size cannot be found. pi-tui's `getImageDimensions` has no AVIF
157
+ * support, so this module computes the size itself and hands it to the `Image`.
158
+ */
159
+ export function getAvifDimensions(bytes: Uint8Array): ImageDimensions | null {
160
+ const ispe = findIspe(bytes, 0, bytes.length);
161
+ if (!ispe || ispe.length < 12) return null;
162
+ // ispe payload: version/flags (4) + width (4) + height (4).
163
+ const width = readU32BE(bytes, ispe.offset + 4);
164
+ const height = readU32BE(bytes, ispe.offset + 8);
165
+ if (width === 0 || height === 0) return null;
166
+ return { widthPx: width, heightPx: height };
167
+ }
168
+
37
169
  /** Slice a byte array without splitting a multi-byte UTF-8 character. */
38
170
  export function sliceUtf8(buf: Uint8Array, maxBytes: number): Uint8Array {
39
171
  if (buf.length <= maxBytes) return buf;
@@ -64,16 +196,30 @@ export function capContent(
64
196
  // Preview service
65
197
  // ---------------------------------------------------------------------------
66
198
 
67
- /** The display record the preview tool, command, and entry renderer consume. */
68
- export interface PreviewData {
69
- path: string;
70
- content: string;
71
- lang?: string;
72
- truncated: boolean;
199
+ /** A text record: read as a string, rendered as Markdown or highlighted code. */
200
+ export interface TextPreview {
201
+ readonly kind: "text";
202
+ readonly path: string;
203
+ readonly content: string;
204
+ readonly lang?: string;
205
+ readonly truncated: boolean;
73
206
  }
74
207
 
75
- /** The failure-details variant: the record plus the user-facing error message. */
76
- export type PreviewDataError = PreviewData & { readonly error: string };
208
+ /** An image record: raw bytes base64-encoded, rendered via pi-tui's Image. */
209
+ export interface ImagePreview {
210
+ readonly kind: "image";
211
+ readonly path: string;
212
+ readonly mimeType: string;
213
+ readonly base64: string;
214
+ readonly dimensions?: ImageDimensions;
215
+ readonly truncated: boolean;
216
+ }
217
+
218
+ /** The display record the preview tool, command, and entry renderer consume. */
219
+ export type PreviewData = TextPreview | ImagePreview;
220
+
221
+ /** The failure-details variant: a text record plus the user-facing error message. */
222
+ export type PreviewDataError = TextPreview & { readonly error: string };
77
223
 
78
224
  /** A file read failed; carries the path and the underlying platform message. */
79
225
  export class PreviewReadError extends Schema.TaggedError<PreviewReadError>()("PreviewReadError", {
@@ -136,7 +282,7 @@ export class PreviewService extends Context.Service<
136
282
  }
137
283
  if (ref === "~") return homedir();
138
284
  if (ref.startsWith("~/")) return path.join(homedir(), ref.slice(2));
139
- if (/^file:\/\//.test(ref)) {
285
+ if (ref.startsWith("file://")) {
140
286
  const url = yield* Effect.try({
141
287
  try: () => new URL(ref),
142
288
  catch: () =>
@@ -154,6 +300,36 @@ export class PreviewService extends Context.Service<
154
300
  const read = Effect.fn("PreviewService.read")(function* (
155
301
  absPath: string,
156
302
  ): Effect.fn.Return<PreviewData, PreviewReadError> {
303
+ const mime = mimeFromPath(absPath);
304
+ if (mime) {
305
+ // Image: read raw bytes (no string decoding, no byte/line capping), then
306
+ // base64-encode and dimension-detect for pi-tui's Image component. The
307
+ // base64 only lives in `details` for TUI rendering — it never reaches the
308
+ // model, which sees the same one-line confirmation stub.
309
+ const bytes = yield* fs
310
+ .readFile(absPath)
311
+ .pipe(
312
+ Effect.catch(
313
+ (err: PlatformError.PlatformError) =>
314
+ new PreviewReadError({ path: absPath, message: err.message }),
315
+ ),
316
+ );
317
+ const base64 = bytesToBase64(bytes);
318
+ // AVIF/HEIC sizes come from the ISO-BMFF `ispe` box (pi-tui has no
319
+ // AVIF parser); every other supported format is sized from base64.
320
+ const dimensions =
321
+ mime === "image/avif"
322
+ ? (getAvifDimensions(bytes) ?? undefined)
323
+ : (getImageDimensions(base64, mime) ?? undefined);
324
+ return {
325
+ kind: "image",
326
+ path: absPath,
327
+ mimeType: mime,
328
+ base64,
329
+ dimensions,
330
+ truncated: false,
331
+ };
332
+ }
157
333
  const raw = yield* fs
158
334
  .readFileString(absPath)
159
335
  .pipe(
@@ -163,7 +339,13 @@ export class PreviewService extends Context.Service<
163
339
  ),
164
340
  );
165
341
  const { content, truncated } = capContent(raw, maxBytes, maxLines);
166
- return { path: absPath, content, lang: getLanguageFromPath(absPath), truncated };
342
+ return {
343
+ kind: "text",
344
+ path: absPath,
345
+ content,
346
+ lang: getLanguageFromPath(absPath),
347
+ truncated,
348
+ };
167
349
  });
168
350
 
169
351
  return PreviewService.of({ resolveFileRef, read });
@@ -198,6 +380,19 @@ export function renderBodyComponent(
198
380
  theme: Theme,
199
381
  collapsedLines: number = COLLAPSED_LINES,
200
382
  ): Component {
383
+ if (data.kind === "image") {
384
+ // The Image component detects terminal support itself: real pixels on
385
+ // kitty/ghostty/wezterm/iTerm2, a `[Image: path [mime] WxH]` text fallback
386
+ // (OSC-8 hyperlinked when available) elsewhere. `expanded`/collapse do not
387
+ // apply — there is no text to truncate.
388
+ return new Image(
389
+ data.base64,
390
+ data.mimeType,
391
+ { fallbackColor: (s) => theme.fg("muted", s) },
392
+ { filename: data.path },
393
+ data.dimensions,
394
+ );
395
+ }
201
396
  const isMarkdown = data.lang === "markdown";
202
397
  if (isMarkdown) {
203
398
  const content = expanded
@@ -222,6 +417,30 @@ export function renderBodyComponent(
222
417
  return new Text(`\n${out.join("\n")}`, 0, 0);
223
418
  }
224
419
 
420
+ /**
421
+ * Wrap a preview body in the house frame. Text records use the bordered box.
422
+ * Image records must NOT draw their own pixels: ad-hoc kitty transmissions from
423
+ * a custom renderer are not part of pi's managed image pipeline and corrupt the
424
+ * screen. Instead the tool delivers images as native `type: "image"` content
425
+ * blocks (see execute) which pi's ToolExecution renders below our caption `——`
426
+ * so here we only draw the path/dimensions caption.
427
+ */
428
+ function makePreviewComponent(data: PreviewData, expanded: boolean, theme: Theme): Component {
429
+ if (data.kind === "image") {
430
+ const caption = data.dimensions
431
+ ? `${data.path} (${data.dimensions.widthPx}x${data.dimensions.heightPx})`
432
+ : data.path;
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),
436
+ });
437
+ }
438
+ return makeBorderedBox(renderBodyComponent(data, expanded, theme), theme, {
439
+ label: theme.fg("accent", theme.bold("preview")),
440
+ bg: (s) => theme.bg("customMessageBg", s),
441
+ });
442
+ }
443
+
225
444
  /** Extract the user-facing message exactly like the legacy catch blocks. */
226
445
  function errorMessage(err: unknown): string {
227
446
  return err instanceof Error ? err.message : String(err);
@@ -265,7 +484,11 @@ export function registerPreview(
265
484
  }),
266
485
  }),
267
486
 
268
- // What the MODEL sees — a stub, not the file.
487
+ // What the MODEL sees — a stub plus, for images, a pi-native `type: "image"`
488
+ // content block. The block is what makes the TUI render the picture through
489
+ // pi's own managed image pipeline (the same path the built-in `read` tool
490
+ // uses); pi auto-resizes it for provider requests, so the model receives a
491
+ // compressed thumbnail rather than raw bytes. Text previews stay stub-only.
269
492
  async execute(_toolCallId, { path }, _signal, _onUpdate, ctx) {
270
493
  return Effect.runPromiseWith(effectContext)(
271
494
  Effect.gen(function* () {
@@ -275,7 +498,12 @@ export function registerPreview(
275
498
  }).pipe(
276
499
  Effect.match({
277
500
  onSuccess: (data) => ({
278
- content: [{ type: "text", text: `[Preview shown to user: ${path}]` }],
501
+ content: [
502
+ { type: "text" as const, text: `[Preview shown to user: ${path}]` },
503
+ ...(data.kind === "image"
504
+ ? [{ type: "image" as const, data: data.base64, mimeType: data.mimeType }]
505
+ : []),
506
+ ],
279
507
  details: data,
280
508
  }),
281
509
  onFailure: (err: unknown) => {
@@ -283,6 +511,7 @@ export function registerPreview(
283
511
  return {
284
512
  content: [{ type: "text", text: `preview failed: ${message}` }],
285
513
  details: {
514
+ kind: "text",
286
515
  path,
287
516
  content: "",
288
517
  lang: undefined,
@@ -314,10 +543,7 @@ export function registerPreview(
314
543
  bg: (s) => theme.bg("customMessageBg", s),
315
544
  });
316
545
  }
317
- return makeBorderedBox(renderBodyComponent(data, options.expanded, theme), theme, {
318
- label: theme.fg("accent", theme.bold("preview")),
319
- bg: (s) => theme.bg("customMessageBg", s),
320
- });
546
+ return makePreviewComponent(data, options.expanded, theme);
321
547
  },
322
548
  });
323
549
 
@@ -326,15 +552,36 @@ export function registerPreview(
326
552
  // =========================================================================
327
553
  pi.registerEntryRenderer("preview", (entry, { expanded }, theme) => {
328
554
  const data = entry.data as PreviewData | undefined;
329
- const body = new Container();
330
555
  if (!data) {
331
- body.addChild(new Text(theme.fg("warning", "[preview] no data"), 0, 0));
332
- return makeBorderedBox(body, theme, {
556
+ const noData = new Container();
557
+ noData.addChild(new Text(theme.fg("warning", "[preview] no data"), 0, 0));
558
+ return makeBorderedBox(noData, theme, {
333
559
  label: theme.fg("warning", theme.bold("preview")),
334
560
  color: "warning",
335
561
  bg: (s) => theme.bg("customMessageBg", s),
336
562
  });
337
563
  }
564
+ // Image entries mirror pi's native tool-image layout exactly: the bordered
565
+ // caption box, one blank spacer row, then the bare Image. pi's own images
566
+ // always emit a spacer row before the kitty transmission; our earlier boxed
567
+ // attempts lacked it, which is what broke Ghostty decoding. Entries have no
568
+ // content-block pipeline, so the Image is drawn by this renderer.
569
+ if (data.kind === "image") {
570
+ const c = new Container();
571
+ c.addChild(makePreviewComponent(data, expanded, theme));
572
+ c.addChild(new Spacer(1));
573
+ c.addChild(
574
+ new Image(
575
+ data.base64,
576
+ data.mimeType,
577
+ { fallbackColor: (s) => theme.fg("toolOutput", s) },
578
+ { filename: data.path, maxWidthCells: 60 },
579
+ data.dimensions,
580
+ ),
581
+ );
582
+ return c;
583
+ }
584
+ const body = new Container();
338
585
  body.addChild(new Text(theme.fg("accent", data.path), 0, 0));
339
586
  body.addChild(renderBodyComponent(data, expanded, theme));
340
587
  return makeBorderedBox(body, theme, {
@@ -175,18 +175,67 @@ export function renderRuntimeSegment(
175
175
  }
176
176
 
177
177
  /**
178
- * The working/done timer footer segment, or `""` when neither timer
179
- * field is set. The working read calls `Date.now()` only while a timer
180
- * is active.
178
+ * The timer segment's two packable parts: the atomic total (priority 2 in
179
+ * the footer packing) and the inference/tool split (priority 1, so it
180
+ * yields before the total on narrow widths). `split` is `""` while
181
+ * waiting or when both buckets are zero.
181
182
  */
182
- export function renderTimerSegment(theme: Theme, state: FooterState, glyphs: IconGlyphs): string {
183
- if (state.workingSince !== undefined) {
184
- return `${theme.fg("accent", glyphs.working)} ${theme.fg("dim", "working")} ${theme.fg("accent", formatDuration(Date.now() - state.workingSince))}`;
183
+ export interface TimerSegmentParts {
184
+ total: string;
185
+ split: string;
186
+ }
187
+
188
+ /** `~ 2s > 1s`-style split from the two non-zero buckets, or `""`. */
189
+ function renderSplit(theme: Theme, glyphs: IconGlyphs, inference: number, tool: number): string {
190
+ const buckets: string[] = [];
191
+ if (inference > 0) {
192
+ buckets.push(`${theme.fg("dim", glyphs.inference)} ${theme.fg("accent", formatDuration(inference))}`);
193
+ }
194
+ if (tool > 0) {
195
+ buckets.push(`${theme.fg("dim", glyphs.tool)} ${theme.fg("accent", formatDuration(tool))}`);
196
+ }
197
+ return buckets.join(" ");
198
+ }
199
+
200
+ /**
201
+ * The working/done timer footer segment, or `undefined` when neither
202
+ * timer state is set. The working read calls `Date.now()` only while a
203
+ * timer is active; pass `now` to freeze the clock in deterministic tests.
204
+ *
205
+ * The segment reads the ActivityTracker, which charges every instant of
206
+ * the open run to one of four exclusive buckets. While a blocking
207
+ * `ctx.ui` prompt is open it reports `waiting` (no split) instead of
208
+ * counting toward `working`. A finished run's `lastDoneIn` is the active
209
+ * work time (total minus waits) and its frozen inference/tool split is
210
+ * rendered next to it until the next run starts.
211
+ */
212
+ export function renderTimerSegment(
213
+ theme: Theme,
214
+ state: FooterState,
215
+ glyphs: IconGlyphs,
216
+ now: number = Date.now(),
217
+ ): TimerSegmentParts | undefined {
218
+ if (state.tracker.isRunOpen()) {
219
+ if (state.tracker.isWaiting()) {
220
+ return {
221
+ total: `${theme.fg("warning", glyphs.working)} ${theme.fg("warning", "waiting")} ${theme.fg("warning", formatDuration(state.tracker.waitingMs(now)))}`,
222
+ split: "",
223
+ };
224
+ }
225
+ const active = state.tracker.breakdown(now);
226
+ return {
227
+ total: `${theme.fg("accent", glyphs.working)} ${theme.fg("dim", "working")} ${theme.fg("accent", formatDuration(active.total - active.wait))}`,
228
+ split: renderSplit(theme, glyphs, active.inference, active.tool),
229
+ };
185
230
  }
186
231
  if (state.lastDoneIn !== undefined) {
187
- return `${theme.fg("success", glyphs.done)} ${theme.fg("success", "done")} ${theme.fg("text", formatDuration(state.lastDoneIn))}`;
232
+ const done = state.tracker.breakdown(now);
233
+ return {
234
+ total: `${theme.fg("success", glyphs.done)} ${theme.fg("success", "done")} ${theme.fg("text", formatDuration(state.lastDoneIn))}`,
235
+ split: renderSplit(theme, glyphs, done.inference, done.tool),
236
+ };
188
237
  }
189
- return "";
238
+ return undefined;
190
239
  }
191
240
 
192
241
  /**