@ftrdotdev/pi-tui 0.8.0 → 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.
Files changed (76) hide show
  1. package/CHANGELOG.md +225 -0
  2. package/README.md +5 -0
  3. package/package.json +18 -15
  4. package/src/activity-service.test.ts +97 -0
  5. package/src/activity.test.ts +1 -1
  6. package/src/activity.ts +38 -0
  7. package/src/chrome/budget.test.ts +345 -0
  8. package/src/chrome/budget.ts +220 -0
  9. package/src/chrome/declarations.ts +303 -0
  10. package/src/chrome/facts.test.ts +165 -0
  11. package/src/chrome/facts.ts +267 -0
  12. package/src/chrome/frame.ts +45 -0
  13. package/src/chrome/laws.test.ts +231 -0
  14. package/src/chrome/port.test.ts +164 -0
  15. package/src/chrome/port.ts +67 -0
  16. package/src/chrome/service-provider.test.ts +383 -0
  17. package/src/chrome/service-provider.ts +55 -0
  18. package/src/commands/git-execution.test.ts +5 -2
  19. package/src/commands/git-execution.ts +27 -15
  20. package/src/commands/git-status.test.ts +47 -15
  21. package/src/commands/git-status.ts +83 -31
  22. package/src/components/bordered-box.test.ts +12 -15
  23. package/src/components/bordered-box.ts +11 -7
  24. package/src/components/define-component.ts +1 -1
  25. package/src/components/index.ts +7 -0
  26. package/src/components/row-list.test.ts +310 -0
  27. package/src/components/row-list.ts +272 -0
  28. package/src/config.test.ts +118 -3
  29. package/src/config.ts +46 -40
  30. package/src/frame/box-frame.test.ts +53 -7
  31. package/src/harness-policy.test.ts +47 -0
  32. package/src/icons.test.ts +19 -0
  33. package/src/icons.ts +50 -31
  34. package/src/index.test.ts +135 -0
  35. package/src/index.ts +118 -119
  36. package/src/layers.test.ts +94 -0
  37. package/src/layers.ts +92 -0
  38. package/src/runtime-service.test.ts +218 -0
  39. package/src/runtime-service.ts +103 -0
  40. package/src/runtime.test.ts +165 -66
  41. package/src/runtime.ts +127 -93
  42. package/src/session-lifecycle-service.test.ts +95 -0
  43. package/src/session-lifecycle.test.ts +77 -0
  44. package/src/session-lifecycle.ts +21 -0
  45. package/src/state.test.ts +132 -3
  46. package/src/state.ts +43 -13
  47. package/src/telemetry-service.test.ts +250 -0
  48. package/src/telemetry.test.ts +322 -0
  49. package/src/telemetry.ts +130 -23
  50. package/src/ui/editor-tint.test.ts +58 -45
  51. package/src/ui/editor-tint.ts +1 -1
  52. package/src/ui/editor.ts +117 -53
  53. package/src/ui/footer.test.ts +349 -120
  54. package/src/ui/footer.ts +147 -124
  55. package/src/ui/header.test.ts +203 -223
  56. package/src/ui/header.ts +32 -96
  57. package/src/ui/preview.test.ts +73 -70
  58. package/src/ui/preview.ts +48 -33
  59. package/src/ui/render-helpers.test.ts +82 -13
  60. package/src/ui/render-helpers.ts +110 -122
  61. package/src/ui/settings-command.test.ts +70 -11
  62. package/src/ui/settings-command.ts +30 -45
  63. package/src/ui/theme-color.test.ts +4 -3
  64. package/src/usage-totals-service.test.ts +230 -0
  65. package/src/usage-totals-service.ts +59 -0
  66. package/src/utils.test.ts +46 -50
  67. package/src/utils.ts +41 -239
  68. package/src/vim/editor-host.test.ts +201 -75
  69. package/src/vim/editor-state.ts +2 -2
  70. package/src/vim/mode-indicator.test.ts +6 -5
  71. package/src/vim/mode-indicator.ts +13 -9
  72. package/src/vim/selection-render.ts +8 -4
  73. package/src/vim/text-model.test.ts +52 -14
  74. package/src/vim/text-model.ts +1 -1
  75. package/src/vim/vim-router.test.ts +3 -0
  76. package/src/vim/vim-router.ts +1 -1
package/src/ui/preview.ts CHANGED
@@ -39,12 +39,22 @@ import {
39
39
  type ImageDimensions,
40
40
  } from "@earendil-works/pi-tui";
41
41
  import { makeBorderedBox } from "../components/bordered-box.ts";
42
- import { Type } from "typebox";
42
+ import { isNonEmptyString } from "../utils.ts";
43
+ import { obj, str, type Static } from "@earendil-works/pi-schema";
43
44
 
44
45
  export const MAX_BYTES = 50 * 1024; // 50KB, matching the built-in read limits
45
46
  export const MAX_LINES = 2000;
46
47
  export const COLLAPSED_LINES = 40;
47
48
 
49
+ const PreviewParams = obj({
50
+ path: str({
51
+ description:
52
+ "File path to display. Accepts @-references (@src/main.ts), ~ expansion, relative or absolute paths.",
53
+ }),
54
+ });
55
+
56
+ type PreviewParams = Static<typeof PreviewParams>;
57
+
48
58
  /** MIME types pi-tui's Image component can size and render (PNG/JPEG/GIF/WebP
49
59
  * plus AVIF, whose size this module parses itself). */
50
60
  const IMAGE_MIME_BY_EXT: Readonly<Record<string, string>> = {
@@ -143,7 +153,7 @@ function findIspe(
143
153
  // FullBox children skip their 4-byte version/flags header.
144
154
  const childStart = FULLBOX_CONTAINERS.has(type) ? payloadStart + 4 : payloadStart;
145
155
  const found = findIspe(bytes, childStart, payloadEnd);
146
- if (found) return found;
156
+ if (found !== null) return found;
147
157
  }
148
158
  if (payloadEnd <= offset) break;
149
159
  offset = payloadEnd;
@@ -158,7 +168,7 @@ function findIspe(
158
168
  */
159
169
  export function getAvifDimensions(bytes: Uint8Array): ImageDimensions | null {
160
170
  const ispe = findIspe(bytes, 0, bytes.length);
161
- if (!ispe || ispe.length < 12) return null;
171
+ if (ispe === null || ispe.length < 12) return null;
162
172
  // ispe payload: version/flags (4) + width (4) + height (4).
163
173
  const width = readU32BE(bytes, ispe.offset + 4);
164
174
  const height = readU32BE(bytes, ispe.offset + 8);
@@ -222,7 +232,10 @@ export type PreviewData = TextPreview | ImagePreview;
222
232
  export type PreviewDataError = TextPreview & { readonly error: string };
223
233
 
224
234
  /** A file read failed; carries the path and the underlying platform message. */
225
- export class PreviewReadError extends Schema.TaggedError<PreviewReadError>()("PreviewReadError", {
235
+ export class PreviewReadError extends Schema.TaggedError<
236
+ PreviewReadError,
237
+ { readonly brand: unique symbol }
238
+ >()("PreviewReadError", {
226
239
  path: Schema.String,
227
240
  message: Schema.String,
228
241
  }) {}
@@ -242,7 +255,7 @@ export class PreviewService extends Context.Service<
242
255
  ) => Effect.Effect<string, PlatformError.BadArgument>;
243
256
  readonly read: (absPath: string) => Effect.Effect<PreviewData, PreviewReadError>;
244
257
  }
245
- >()("tui/preview/PreviewService") {
258
+ >()("@ftrdotdev/pi-tui/ui/preview/PreviewService") {
246
259
  /**
247
260
  * @param homedir - provider for the user's home directory (`~` expansion).
248
261
  * Effect has no home-directory service, so the platform implementation is
@@ -301,7 +314,7 @@ export class PreviewService extends Context.Service<
301
314
  absPath: string,
302
315
  ): Effect.fn.Return<PreviewData, PreviewReadError> {
303
316
  const mime = mimeFromPath(absPath);
304
- if (mime) {
317
+ if (isNonEmptyString(mime)) {
305
318
  // Image: read raw bytes (no string decoding, no byte/line capping), then
306
319
  // base64-encode and dimension-detect for pi-tui's Image component. The
307
320
  // base64 only lives in `details` for TUI rendering — it never reaches the
@@ -309,9 +322,8 @@ export class PreviewService extends Context.Service<
309
322
  const bytes = yield* fs
310
323
  .readFile(absPath)
311
324
  .pipe(
312
- Effect.catch(
313
- (err: PlatformError.PlatformError) =>
314
- new PreviewReadError({ path: absPath, message: err.message }),
325
+ Effect.catch((err: PlatformError.PlatformError) =>
326
+ PreviewReadError.make({ path: absPath, message: err.message }),
315
327
  ),
316
328
  );
317
329
  const base64 = bytesToBase64(bytes);
@@ -326,24 +338,24 @@ export class PreviewService extends Context.Service<
326
338
  path: absPath,
327
339
  mimeType: mime,
328
340
  base64,
329
- dimensions,
341
+ ...(dimensions === undefined ? {} : { dimensions }),
330
342
  truncated: false,
331
343
  };
332
344
  }
333
345
  const raw = yield* fs
334
346
  .readFileString(absPath)
335
347
  .pipe(
336
- Effect.catch(
337
- (err: PlatformError.PlatformError) =>
338
- new PreviewReadError({ path: absPath, message: err.message }),
348
+ Effect.catch((err: PlatformError.PlatformError) =>
349
+ PreviewReadError.make({ path: absPath, message: err.message }),
339
350
  ),
340
351
  );
341
352
  const { content, truncated } = capContent(raw, maxBytes, maxLines);
353
+ const lang = getLanguageFromPath(absPath);
342
354
  return {
343
355
  kind: "text",
344
356
  path: absPath,
345
357
  content,
346
- lang: getLanguageFromPath(absPath),
358
+ ...(lang === undefined ? {} : { lang }),
347
359
  truncated,
348
360
  };
349
361
  });
@@ -408,7 +420,9 @@ export function renderBodyComponent(
408
420
  return new Markdown(content + note, 0, 0, getMarkdownTheme());
409
421
  }
410
422
 
411
- const lines = data.lang ? highlightCode(data.content, data.lang) : data.content.split("\n");
423
+ const lines = isNonEmptyString(data.lang)
424
+ ? highlightCode(data.content, data.lang)
425
+ : data.content.split("\n");
412
426
  const max = expanded ? lines.length : Math.min(collapsedLines, lines.length);
413
427
  const out = lines.slice(0, max);
414
428
  if (max < lines.length || data.truncated) {
@@ -427,9 +441,10 @@ export function renderBodyComponent(
427
441
  */
428
442
  function makePreviewComponent(data: PreviewData, expanded: boolean, theme: Theme): Component {
429
443
  if (data.kind === "image") {
430
- const caption = data.dimensions
431
- ? `${data.path} (${data.dimensions.widthPx}x${data.dimensions.heightPx})`
432
- : data.path;
444
+ const caption =
445
+ data.dimensions !== undefined
446
+ ? `${data.path} (${data.dimensions.widthPx}x${data.dimensions.heightPx})`
447
+ : data.path;
433
448
  return makeBorderedBox(new Text(theme.fg("accent", caption), 0, 0), theme, {
434
449
  label: theme.style("preview", { fg: "accent", bold: true }),
435
450
  bg: "customMessageBg",
@@ -477,19 +492,14 @@ export function registerPreview(
477
492
  // The custom renderers draw their own framed box; skip pi's standard
478
493
  // tool shell so the element is not double-framed.
479
494
  renderShell: "self",
480
- parameters: Type.Object({
481
- path: Type.String({
482
- description:
483
- "File path to display. Accepts @-references (@src/main.ts), ~ expansion, relative or absolute paths.",
484
- }),
485
- }),
495
+ parameters: PreviewParams,
486
496
 
487
497
  // What the MODEL sees — a stub plus, for images, a pi-native `type: "image"`
488
498
  // content block. The block is what makes the TUI render the picture through
489
499
  // pi's own managed image pipeline (the same path the built-in `read` tool
490
500
  // uses); pi auto-resizes it for provider requests, so the model receives a
491
501
  // compressed thumbnail rather than raw bytes. Text previews stay stub-only.
492
- async execute(_toolCallId, { path }, _signal, _onUpdate, ctx) {
502
+ async execute(_toolCallId, { path }: PreviewParams, _signal, _onUpdate, ctx) {
493
503
  return Effect.runPromiseWith(effectContext)(
494
504
  Effect.gen(function* () {
495
505
  const svc = yield* PreviewService;
@@ -514,7 +524,6 @@ export function registerPreview(
514
524
  kind: "text",
515
525
  path,
516
526
  content: "",
517
- lang: undefined,
518
527
  truncated: false,
519
528
  error: message,
520
529
  } satisfies PreviewDataError,
@@ -526,7 +535,8 @@ export function registerPreview(
526
535
  },
527
536
 
528
537
  renderCall(args, theme) {
529
- return makeBorderedBox(new Text(args.path, 0, 0), theme, {
538
+ const { path } = args as PreviewParams;
539
+ return makeBorderedBox(new Text(path, 0, 0), theme, {
530
540
  label: theme.style("preview", { fg: "toolTitle", bold: true }),
531
541
  bg: "customMessageBg",
532
542
  });
@@ -535,8 +545,8 @@ export function registerPreview(
535
545
  // What the TUI renders — the full highlighted file.
536
546
  renderResult(result, options, theme, context) {
537
547
  const data = result.details as (PreviewData & { error?: string }) | undefined;
538
- if (!data) return context.lastComponent ?? new Text("", 0, 0);
539
- if (data.error) {
548
+ if (data === undefined) return context.lastComponent ?? new Text("", 0, 0);
549
+ if (isNonEmptyString(data.error)) {
540
550
  return makeBorderedBox(new Text(`preview failed: ${data.error}`, 0, 0), theme, {
541
551
  label: theme.style("preview", { fg: "warning", bold: true }),
542
552
  color: "warning",
@@ -552,7 +562,7 @@ export function registerPreview(
552
562
  // =========================================================================
553
563
  pi.registerEntryRenderer("preview", (entry, { expanded }, theme) => {
554
564
  const data = entry.data as PreviewData | undefined;
555
- if (!data) {
565
+ if (data === undefined) {
556
566
  const noData = new Container();
557
567
  noData.addChild(new Text(theme.fg("warning", "[preview] no data"), 0, 0));
558
568
  return makeBorderedBox(noData, theme, {
@@ -597,11 +607,16 @@ export function registerPreview(
597
607
  // shows only the text call-row. Mirror the `/preview` command and append the
598
608
  // display record as a custom entry so the entry renderer above draws it.
599
609
  pi.on("tool_execution_end", (event, ctx) => {
600
- if (!event.parentToolCallId || event.toolName !== "preview") return;
610
+ if (
611
+ event.parentToolCallId === undefined ||
612
+ event.parentToolCallId === "" ||
613
+ event.toolName !== "preview"
614
+ )
615
+ return;
601
616
  if (ctx.mode !== "tui") return;
602
617
  const data = (event.result as { details?: PreviewData | PreviewDataError } | undefined)
603
618
  ?.details;
604
- if (!data || "error" in data) return;
619
+ if (data === undefined || "error" in data) return;
605
620
  pi.appendEntry("preview", data);
606
621
  });
607
622
 
@@ -610,7 +625,7 @@ export function registerPreview(
610
625
  "Display a file in the chat for the user to read (TUI only, not sent to the model).",
611
626
  handler: async (args, ctx) => {
612
627
  const path = args.trim();
613
- if (!path) {
628
+ if (path === "") {
614
629
  ctx.ui.notify("usage: /preview <path>", "warning");
615
630
  return;
616
631
  }
@@ -1,19 +1,18 @@
1
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";
2
+ import { PROPERTY_RUNS, themeDouble } from "@ftrdotdev/pi-test-kit";
3
+ import { barArbitrary, barPairArbitrary } from "../../test-support/generators.ts";
4
+ import type { IconMode } from "../config.ts";
5
+ import { resolveGlyphs } from "../icons.ts";
6
+ import { renderBar, renderContextBar, renderRuntimeSegment } from "./render-helpers.ts";
4
7
 
5
8
  // 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), "[####]");
9
+ const theme = themeDouble();
10
+
11
+ it("renderBar fills by rounded percentage in ascii and nerd", () => {
12
+ assert.strictEqual(renderBar(theme, 50, 10, "ascii"), "[▮▮▮▮▮▯▯▯▯▯]");
13
+ assert.strictEqual(renderBar(theme, 0, 4, "nerd"), "[░░░░]");
14
+ assert.strictEqual(renderBar(theme, 100, 4, "ascii"), "[▮▮▮▮]");
15
+ assert.strictEqual(renderBar(theme, 150, 4, "ascii"), "[▮▮▮▮]");
17
16
  });
18
17
 
19
18
  it("renderRuntimeSegment joins every runtime with a dim separator", () => {
@@ -23,3 +22,73 @@ it("renderRuntimeSegment joins every runtime with a dim separator", () => {
23
22
  "node 1.2.3 · rs",
24
23
  );
25
24
  });
25
+
26
+ it("renders context occupancy as tokens over window", () => {
27
+ const usage = { tokens: 100_000, contextWindow: 200_000, percent: 50 } as never;
28
+ assert.strictEqual(renderContextBar(theme, usage, resolveGlyphs("ascii")), "◧ 100k/200k");
29
+ assert.strictEqual(
30
+ renderContextBar(
31
+ theme,
32
+ { tokens: 0, contextWindow: 200_000, percent: 0 } as never,
33
+ resolveGlyphs("ascii"),
34
+ ),
35
+ "◧ 0/200k",
36
+ );
37
+ // Unknown tokens after compaction must read as unknown, not as zero.
38
+ assert.strictEqual(
39
+ renderContextBar(
40
+ theme,
41
+ { tokens: null, contextWindow: 200_000, percent: null } as never,
42
+ resolveGlyphs("ascii"),
43
+ ),
44
+ "◧ —/200k",
45
+ );
46
+ assert.strictEqual(
47
+ renderContextBar(
48
+ theme,
49
+ { tokens: 0, contextWindow: 0, percent: 0 } as never,
50
+ resolveGlyphs("ascii"),
51
+ ),
52
+ "",
53
+ );
54
+ });
55
+
56
+ /** The cells between the dim brackets; the identity theme leaves them plain. */
57
+ const barBody = (rendered: string): string => rendered.slice(1, -1);
58
+
59
+ /** Cells of `rendered` that equal the glyph the bar fills with at 100 %. */
60
+ const filledCells = (rendered: string, barWidth: number, mode: IconMode): number => {
61
+ const filledGlyph = Array.from(barBody(renderBar(theme, 100, barWidth, mode)))[0];
62
+ return Array.from(barBody(rendered)).filter((cell) => cell === filledGlyph).length;
63
+ };
64
+
65
+ it.prop(
66
+ "the bar body is exactly bar width columns wide",
67
+ { bar: barArbitrary },
68
+ ({ bar }) => {
69
+ const body = barBody(renderBar(theme, bar.pct, bar.barWidth, bar.mode));
70
+ assert.strictEqual(Array.from(body).length, bar.barWidth);
71
+ const filledGlyph = Array.from(barBody(renderBar(theme, 100, bar.barWidth, bar.mode)))[0];
72
+ const emptyGlyph = Array.from(barBody(renderBar(theme, 0, bar.barWidth, bar.mode)))[0];
73
+ const filled = Array.from(body).filter((cell) => cell === filledGlyph).length;
74
+ assert.strictEqual(
75
+ body,
76
+ filledGlyph!.repeat(filled) + emptyGlyph!.repeat(bar.barWidth - filled),
77
+ );
78
+ },
79
+ { arbitrary: { runs: PROPERTY_RUNS } },
80
+ );
81
+
82
+ it.prop(
83
+ "the filled cell count is exact at both endpoints and never decreases as the percentage grows",
84
+ { pair: barPairArbitrary },
85
+ ({ pair }) => {
86
+ const filledAt = (pct: number): number =>
87
+ filledCells(renderBar(theme, pct, pair.barWidth, pair.mode), pair.barWidth, pair.mode);
88
+ assert.strictEqual(filledAt(0), 0);
89
+ assert.strictEqual(filledAt(100), pair.barWidth);
90
+ assert.strictEqual(filledAt(150), pair.barWidth);
91
+ assert.isAtMost(filledAt(pair.left), filledAt(pair.right));
92
+ },
93
+ { arbitrary: { runs: PROPERTY_RUNS } },
94
+ );