@ftrdotdev/pi-tui 0.5.2 → 0.6.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/runtime.ts CHANGED
@@ -158,7 +158,7 @@ const RUNTIMES: readonly RuntimeDef[] = [
158
158
 
159
159
  interface CacheEntry {
160
160
  fingerprint: string;
161
- runtime: RuntimeInfo | null;
161
+ runtime: RuntimeInfo;
162
162
  }
163
163
 
164
164
  const cache = new Map<string, CacheEntry>();
@@ -221,36 +221,33 @@ async function fetchVersion(def: RuntimeDef, cwd: string): Promise<string | unde
221
221
  }
222
222
  }
223
223
 
224
- export async function readRuntimeInfo(cwd: string): Promise<RuntimeInfo | null> {
224
+ /**
225
+ * Every runtime that matches `cwd`, in table order. Each match carries its
226
+ * version when the runtime's version command answers. Results are cached per
227
+ * `(cwd, runtime)` and invalidated by a fingerprint of the marker files.
228
+ */
229
+ export async function readRuntimeInfo(cwd: string): Promise<RuntimeInfo[]> {
230
+ const matches: RuntimeInfo[] = [];
225
231
  for (const def of RUNTIMES) {
226
232
  if (!matchesDef(cwd, def)) continue;
227
- const fp = fingerprint(cwd, def);
228
- const cacheKey = `${cwd}\0${def.name}`;
229
- const cached = cache.get(cacheKey);
230
- if (cached && cached.fingerprint === fp) {
231
- return cached.runtime;
232
- }
233
-
234
- for (const key of cache.keys()) {
235
- if (key === cacheKey || key.startsWith(`${cwd}\0`)) cache.delete(key);
236
- }
237
-
238
- const version = await fetchVersion(def, cwd);
239
- const info: RuntimeInfo = {
240
- name: def.name,
241
- version,
242
- };
243
- cache.set(cacheKey, { fingerprint: fp, runtime: info });
244
- while (cache.size > CACHE_MAX) {
245
- const oldest = cache.keys().next().value;
246
- if (oldest === undefined) break;
247
- cache.delete(oldest);
248
- }
249
- return info;
233
+ matches.push(await resolveRuntime(cwd, def));
250
234
  }
251
- return null;
235
+ return matches;
252
236
  }
253
237
 
254
- export function clearRuntimeCache(): void {
255
- cache.clear();
238
+ async function resolveRuntime(cwd: string, def: RuntimeDef): Promise<RuntimeInfo> {
239
+ const fp = fingerprint(cwd, def);
240
+ const cacheKey = `${cwd}\0${def.name}`;
241
+ const cached = cache.get(cacheKey);
242
+ if (cached && cached.fingerprint === fp) return cached.runtime;
243
+
244
+ const version = await fetchVersion(def, cwd);
245
+ const info: RuntimeInfo = { name: def.name, version };
246
+ cache.set(cacheKey, { fingerprint: fp, runtime: info });
247
+ while (cache.size > CACHE_MAX) {
248
+ const oldest = cache.keys().next().value;
249
+ if (oldest === undefined) break;
250
+ cache.delete(oldest);
251
+ }
252
+ return info;
256
253
  }
@@ -1,17 +1,14 @@
1
1
  export class SessionLifecycle {
2
2
  private current = 0;
3
- private deferred: Array<() => void> = [];
4
3
  private shutDown = false;
5
4
 
6
5
  start(): void {
7
6
  this.current++;
8
7
  this.shutDown = false;
9
- this.flushDeferred();
10
8
  }
11
9
 
12
10
  shutdown(): void {
13
11
  this.shutDown = true;
14
- this.deferred = [];
15
12
  }
16
13
 
17
14
  isCurrent(generation?: number): boolean {
@@ -23,19 +20,4 @@ export class SessionLifecycle {
23
20
  currentGeneration(): number {
24
21
  return this.current;
25
22
  }
26
-
27
- defer(fn: () => void): void {
28
- if (this.shutDown) return;
29
- this.deferred.push(fn);
30
- }
31
-
32
- private flushDeferred(): void {
33
- const pending = this.deferred;
34
- this.deferred = [];
35
- for (const fn of pending) {
36
- try {
37
- fn();
38
- } catch {}
39
- }
40
- }
41
23
  }
package/src/state.test.ts CHANGED
@@ -13,4 +13,4 @@ it("createInitialState starts with a fresh tracker and no done figure", () => {
13
13
  assert.strictEqual(s.tracker.isRunOpen(), false);
14
14
  assert.strictEqual(s.tracker.isWaiting(), false);
15
15
  assert.deepStrictEqual(s.tracker.breakdown(0), { inference: 0, tool: 0, wait: 0, total: 0 });
16
- });
16
+ });
package/src/state.ts CHANGED
@@ -7,7 +7,7 @@ import { formatProviderLabel } from "./utils.ts";
7
7
 
8
8
  export interface FooterState {
9
9
  git: GitStatus;
10
- runtime: RuntimeInfo | null;
10
+ runtime: RuntimeInfo[];
11
11
  sessionStartEpoch: number;
12
12
  /** Frozen active-work total from the last finished run, as today. */
13
13
  lastDoneIn: number | undefined;
@@ -71,7 +71,7 @@ export function invalidateUsageCache(): void {
71
71
  export function createInitialState(): FooterState {
72
72
  return {
73
73
  git: GitStatus.empty(),
74
- runtime: null,
74
+ runtime: [],
75
75
  sessionStartEpoch: Date.now(),
76
76
  lastDoneIn: undefined,
77
77
  tracker: new ActivityTracker(),
@@ -1,4 +1,4 @@
1
- import { afterEach, assert, it } from "@effect/vitest";
1
+ import { assert, it } from "@effect/vitest";
2
2
  import { Effect } from "effect";
3
3
  import type { ThemeColor } from "@earendil-works/pi-coding-agent";
4
4
  import {
@@ -1,5 +1,6 @@
1
1
  import { Context, Layer } from "effect";
2
2
  import type { ThemeColor } from "@earendil-works/pi-coding-agent";
3
+ import type { Color } from "@earendil-works/pi-tui";
3
4
 
4
5
  /**
5
6
  * A border-tint contribution. `id` stamps the contributor so a later
@@ -10,7 +11,7 @@ import type { ThemeColor } from "@earendil-works/pi-coding-agent";
10
11
  */
11
12
  export interface BorderTintProvider {
12
13
  readonly id: string;
13
- readonly getTint: () => ThemeColor | undefined;
14
+ readonly getTint: () => ThemeColor | Color | undefined;
14
15
  }
15
16
 
16
17
  /**
@@ -33,7 +34,7 @@ export class EditorTintService extends Context.Service<
33
34
  readonly configure: (
34
35
  update: (current: readonly BorderTintProvider[]) => readonly BorderTintProvider[],
35
36
  ) => void;
36
- readonly getTint: () => ThemeColor | undefined;
37
+ readonly getTint: () => ThemeColor | Color | undefined;
37
38
  }
38
39
  >()("tui/editor/EditorTintService") {
39
40
  static readonly layer = Layer.sync(EditorTintService, () => {
package/src/ui/editor.ts CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  type Theme,
7
7
  type ThemeColor,
8
8
  } from "@earendil-works/pi-coding-agent";
9
- import type { EditorTheme, TUI } from "@earendil-works/pi-tui";
9
+ import type { Color, EditorTheme, TUI } from "@earendil-works/pi-tui";
10
10
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
11
11
  import {
12
12
  inspectAutocompleteInternals,
@@ -23,6 +23,20 @@ import { renderSelection } from "../vim/selection-render.ts";
23
23
  import { type Cursor, type Range, type VimTextModelShape } from "../vim/text-model.ts";
24
24
  import { wordBackward, wordEnd, wordForward } from "../vim/word-motion.ts";
25
25
 
26
+ /** A status indicator embedded in the editor's top border, at two sizes. */
27
+ interface BorderStatus {
28
+ /** Spinner plus message, as pi renders it inside a border. */
29
+ readonly full: string;
30
+ /** Spinner only, for widths where the message does not fit. */
31
+ readonly spinner: string;
32
+ }
33
+
34
+ /** Join defined, non-empty label parts with the house separator. */
35
+ function joinLabel(...parts: Array<string | undefined>): string | undefined {
36
+ const kept = parts.filter((part): part is string => part !== undefined && part.length > 0);
37
+ return kept.length === 0 ? undefined : kept.join(" · ");
38
+ }
39
+
26
40
  /**
27
41
  * Top or bottom border of the editor frame, composed from the shared
28
42
  * {@link buildBoxFrame} model and {@link composeBorderLine} so every box in
@@ -38,17 +52,26 @@ function roundedBorder(
38
52
  paint: (s: string) => string,
39
53
  sourceLine?: string,
40
54
  modeGlyph?: string,
55
+ status?: BorderStatus,
41
56
  ): string {
42
57
  const scrollLabel =
43
58
  sourceLine === undefined ? undefined : stripAnsi(sourceLine).match(/([↑↓]\s+\d+\s+more)/)?.[1];
44
- // The mode glyph and the scroll hint share the border's single label slot;
45
- // join them with the house separator so a narrow editor drops both together.
46
- const label =
47
- modeGlyph === undefined
48
- ? scrollLabel
49
- : scrollLabel === undefined
50
- ? modeGlyph
51
- : `${modeGlyph} · ${scrollLabel}`;
59
+ // An embedded status takes the top border's left segment, like pi's own
60
+ // editor: `╭─ <status> ─────╮`. The status outranks the mode glyph and the
61
+ // scroll hint, and the spinner alone is the last resort before the plain
62
+ // border. Narrow widths therefore keep the status instead of dropping it.
63
+ if (kind === "top" && status !== undefined) {
64
+ const inner = Math.max(0, width - 2);
65
+ const glyph = modeGlyph === undefined || modeGlyph.length === 0 ? "" : `${modeGlyph} · `;
66
+ for (const text of [`${glyph}${status.full}`, `${glyph}${status.spinner}`, status.spinner]) {
67
+ const textWidth = visibleWidth(text);
68
+ const dashes = inner - 2 - textWidth - 1;
69
+ if (textWidth > 0 && dashes >= 0) {
70
+ return paint("╭─ ") + text + paint(` ${"─".repeat(dashes)}`) + paint("╮");
71
+ }
72
+ }
73
+ }
74
+ const label = joinLabel(modeGlyph, scrollLabel);
52
75
  const frame = buildBoxFrame(width, {
53
76
  label,
54
77
  labelWidth: label === undefined ? undefined : visibleWidth(label),
@@ -74,9 +97,9 @@ export interface TuiEditorOptions {
74
97
  * undefined to keep pi's own border color. Generic — the editor has no
75
98
  * notion of what supplied the color.
76
99
  */
77
- readonly getBorderTint?: () => ThemeColor | undefined;
78
- /** Paints a given theme color onto text (e.g. `theme.fg(color, s)`). */
79
- readonly tintPaint?: (color: ThemeColor, s: string) => string;
100
+ readonly getBorderTint?: () => ThemeColor | Color | undefined;
101
+ /** Paints a given theme color onto text (e.g. `theme.style(s, { fg: color })`). */
102
+ readonly tintPaint?: (color: ThemeColor | Color, s: string) => string;
80
103
  /**
81
104
  * Live mode indicator for the top border (e.g. vim's N/I/V letter), or
82
105
  * undefined for none. A thunk so the glyph follows mode changes on every
@@ -95,9 +118,15 @@ export class TuiEditor extends CustomEditor {
95
118
  private readonly boxTheme: Theme;
96
119
  private readonly onAutocompleteMismatch?: (detail: string) => void;
97
120
  private readonly paintSelection: (s: string) => string;
98
- private readonly getBorderTint?: () => ThemeColor | undefined;
99
- private readonly tintPaint?: (color: ThemeColor, s: string) => string;
121
+ private readonly getBorderTint?: () => ThemeColor | Color | undefined;
122
+ private readonly tintPaint?: (color: ThemeColor | Color, s: string) => string;
100
123
  private readonly getModeIndicator?: () => string | undefined;
124
+ /**
125
+ * The status indicator pi embeds in the top border. pi only calls
126
+ * `setWorkingStatusIndicator()` when `embedWorkingStatus` is true, so we
127
+ * capture it to render the house border ourselves.
128
+ */
129
+ private statusIndicator?: Parameters<CustomEditor["setWorkingStatusIndicator"]>[0];
101
130
  /** The modal state machine backing vim; read by the package's tint wiring. */
102
131
  readonly vimState: VimEditorState;
103
132
  private autocompleteDiagnosed = false;
@@ -108,9 +137,10 @@ export class TuiEditor extends CustomEditor {
108
137
  keybindings: KeybindingsManager,
109
138
  options: TuiEditorOptions = {},
110
139
  ) {
111
- super(tui, editorTheme, keybindings, { paddingX: 0 });
140
+ super(tui, editorTheme, keybindings, { paddingX: 0, embedWorkingStatus: true });
112
141
  this.boxTheme = {
113
142
  fg: (_color: ThemeColor, s: string) => this.borderPaint(s),
143
+ style: (s: string) => this.borderPaint(s),
114
144
  } as unknown as Theme;
115
145
  this.onAutocompleteMismatch = options.onAutocompleteMismatch;
116
146
  this.paintSelection = options.paintSelection ?? ((s: string) => s);
@@ -132,6 +162,13 @@ export class TuiEditor extends CustomEditor {
132
162
  super.setPaddingX(0);
133
163
  }
134
164
 
165
+ override setWorkingStatusIndicator(
166
+ indicator: Parameters<CustomEditor["setWorkingStatusIndicator"]>[0],
167
+ ): void {
168
+ this.statusIndicator = indicator;
169
+ super.setWorkingStatusIndicator(indicator);
170
+ }
171
+
135
172
  /**
136
173
  * Validated view of pi's autocomplete internals. When the contract no
137
174
  * longer matches (pi internals changed shape), report once and return
@@ -315,7 +352,16 @@ export class TuiEditor extends CustomEditor {
315
352
  : undefined;
316
353
 
317
354
  const result: string[] = [];
318
- result.push(roundedBorder(width, "top", borderPaint, baseLines[0], this.getModeIndicator?.()));
355
+ const indicator = this.statusIndicator;
356
+ const status: BorderStatus | undefined = indicator
357
+ ? {
358
+ full: indicator.renderInBorder(Math.max(1, width - 5)),
359
+ spinner: indicator.renderSpinnerInBorder(width),
360
+ }
361
+ : undefined;
362
+ result.push(
363
+ roundedBorder(width, "top", borderPaint, baseLines[0], this.getModeIndicator?.(), status),
364
+ );
319
365
 
320
366
  for (let i = 1; i < bottomIdx; i++) {
321
367
  const line = contentLines ? (contentLines[i - 1] ?? "") : (baseLines[i] ?? "");
@@ -362,8 +408,8 @@ export function installEditor(
362
408
  ctx.ui.setEditorComponent((tui, editorTheme, keybindings) => {
363
409
  const editor = new TuiEditor(tui, editorTheme, keybindings, {
364
410
  getVimEnabled: options.getVimEnabled,
365
- // Paints the resolved border tint through the theme's color fg().
366
- tintPaint: (color, s) => ctx.ui.theme.fg(color, s),
411
+ // Paints the resolved border tint through the theme's color style().
412
+ tintPaint: (color, s) => ctx.ui.theme.style(s, { fg: color }),
367
413
  // The editor stays generic: it asks the shared service for a tint and
368
414
  // knows nothing about vim. vim is just one provider registered here.
369
415
  getBorderTint: () => options.tint.getTint(),
@@ -43,7 +43,7 @@ const state: FooterState = {
43
43
  deleted: 0,
44
44
  commit: null,
45
45
  }),
46
- runtime: null,
46
+ runtime: [],
47
47
  sessionStartEpoch: 1_700_000_000_000,
48
48
  lastDoneIn: undefined,
49
49
  tracker: new ActivityTracker(),
@@ -76,6 +76,13 @@ const config: TuiConfig = {
76
76
  stalls: true,
77
77
  cost: true,
78
78
  },
79
+ smartCompaction: {
80
+ enabled: true,
81
+ classifier: null,
82
+ keepContextThreshold: 0.5,
83
+ keepContextMinConfidence: 0.5,
84
+ maxCandidates: 8,
85
+ },
79
86
  };
80
87
  const getConfig = () => config;
81
88
 
@@ -1,7 +1,8 @@
1
1
  import { assert, it } from "@effect/vitest";
2
+ import { vi } from "vitest";
2
3
  import { Effect, Random } from "effect";
3
4
  import { VERSION, type Theme } from "@earendil-works/pi-coding-agent";
4
- import { HeaderRenderService, installHeader } from "./header.ts";
5
+ import { HeaderRenderService, installHeader, resetScreenClearMemory } from "./header.ts";
5
6
 
6
7
  // Pixel parity: the header must render byte-identically through makeBorderedBox
7
8
  // as it did with its hand-rolled box (captured before the refactor). The tips
@@ -12,6 +13,7 @@ const plainTheme = {
12
13
  fg: (_color: string, text: string) => text,
13
14
  bg: (_color: string, text: string) => text,
14
15
  bold: (text: string) => `*${text}*`,
16
+ style: (text: string) => text,
15
17
  } as unknown as Theme;
16
18
 
17
19
  const pi = {
@@ -243,13 +245,13 @@ it("installHeader registers a closure component at mount and unregisters on clea
243
245
  const cleanup = installHeader(pi, mountCtx);
244
246
 
245
247
  assert.strictEqual(typeof captured, "function");
246
- const componentA = captured!(undefined, plainTheme) as {
248
+ const componentA = captured!({ mode: "fullscreen" }, plainTheme) as {
247
249
  render: (width: number) => string[];
248
250
  };
249
251
  const linesA = componentA.render(80);
250
252
 
251
253
  // Re-mount swaps the slot to a fresh component; both render the header.
252
- const componentB = captured!(undefined, plainTheme) as {
254
+ const componentB = captured!({ mode: "fullscreen" }, plainTheme) as {
253
255
  render: (width: number) => string[];
254
256
  };
255
257
  assert.notStrictEqual(componentA, componentB);
@@ -274,3 +276,48 @@ it("installHeader registers a closure component at mount and unregisters on clea
274
276
  assert.strictEqual(unregistered, true);
275
277
  assert.strictEqual(captured, undefined);
276
278
  });
279
+
280
+ /** Mount context that captures the header factory pi would invoke. */
281
+ const captureMountCtx = (
282
+ onFactory: (factory: ((tui: unknown, theme: unknown) => unknown) | undefined) => void,
283
+ ) =>
284
+ ({
285
+ model: { provider: "anthropic", id: "claude-sonnet-4" },
286
+ cwd: "/projects/pi-mono/packages/tui",
287
+ ui: {
288
+ theme: plainTheme,
289
+ setHeader(factory: ((tui: unknown, theme: unknown) => unknown) | undefined) {
290
+ onFactory(factory);
291
+ },
292
+ },
293
+ }) as never;
294
+
295
+ it("clears the screen once per process, and only in regular mode", () => {
296
+ const originalIsTTY = process.stdout.isTTY;
297
+ Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true });
298
+ const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
299
+ try {
300
+ resetScreenClearMemory();
301
+ let captured: ((tui: unknown, theme: unknown) => unknown) | undefined;
302
+ const mountCtx = captureMountCtx((factory) => {
303
+ captured = factory;
304
+ });
305
+
306
+ installHeader(pi, mountCtx);
307
+ captured!({ mode: "fullscreen" }, plainTheme);
308
+ assert.strictEqual(write.mock.calls.length, 0, "fullscreen must not clear");
309
+
310
+ captured!({ mode: "regular" }, plainTheme);
311
+ assert.deepStrictEqual(write.mock.calls[0]?.[0], "\x1b[2J\x1b[H");
312
+
313
+ // A reload re-mounts in regular mode while pi-tui still holds the
314
+ // previous lines. The once guard must keep it from writing escape codes
315
+ // behind the renderer's back (the blank-widget regression).
316
+ captured!({ mode: "regular" }, plainTheme);
317
+ assert.strictEqual(write.mock.calls.length, 1, "re-mount must not clear again");
318
+ } finally {
319
+ write.mockRestore();
320
+ Object.defineProperty(process.stdout, "isTTY", { value: originalIsTTY, configurable: true });
321
+ resetScreenClearMemory();
322
+ }
323
+ });
package/src/ui/header.ts CHANGED
@@ -19,6 +19,38 @@ import {
19
19
  pickSlashCommandTips,
20
20
  } from "../utils.ts";
21
21
 
22
+ /**
23
+ * Process-wide flag: the raw screen clear runs at most once per launch.
24
+ * `Symbol.for` keeps the same key across extension module reloads, so a
25
+ * `/reload` re-import does not reset it.
26
+ */
27
+ const SCREEN_CLEARED_KEY = Symbol.for("@ftrdotdev/pi-tui/screen-cleared");
28
+
29
+ type ScreenClearedGlobal = typeof globalThis & { [SCREEN_CLEARED_KEY]?: boolean };
30
+
31
+ /** Test seam: forget that the screen was cleared, so a test can assert it. */
32
+ export function resetScreenClearMemory(): void {
33
+ delete (globalThis as ScreenClearedGlobal)[SCREEN_CLEARED_KEY];
34
+ }
35
+
36
+ /**
37
+ * Clear the visible screen and home the cursor, at most once per process.
38
+ *
39
+ * The write bypasses pi-tui, so it is only safe before the TUI has painted:
40
+ * on the first regular-mode mount, when the screen still holds the shell
41
+ * prompt. Every later mount (reload, new, fork, resume, settings toggle)
42
+ * happens while pi-tui holds the previous lines and its cursor row; clearing
43
+ * then desyncs the differential renderer and leaves regions such as an
44
+ * extension widget blank until the next full repaint.
45
+ */
46
+ function clearVisibleScreenOnce(): void {
47
+ if (!process.stdout.isTTY) return;
48
+ const globals = globalThis as ScreenClearedGlobal;
49
+ if (globals[SCREEN_CLEARED_KEY]) return;
50
+ globals[SCREEN_CLEARED_KEY] = true;
51
+ process.stdout.write("\x1b[2J\x1b[H");
52
+ }
53
+
22
54
  /**
23
55
  * Pi header widget (`setHeader`), framed in the house rounded box.
24
56
  *
@@ -138,7 +170,12 @@ export class HeaderRenderService extends Context.Service<
138
170
  */
139
171
  export function installHeader(pi: ExtensionAPI, ctx: ExtensionContext): () => void {
140
172
  let header: DisposableComponent | undefined;
141
- ctx.ui.setHeader(() => {
173
+ ctx.ui.setHeader((tui) => {
174
+ // Regular mode keeps the terminal's scrollback, so the first mount clears
175
+ // the previous screen. Fullscreen owns the alternate screen, which is
176
+ // already fresh; clearing there only flickers. The once guard keeps a
177
+ // re-mount from desyncing pi-tui's differential renderer.
178
+ if (tui.mode === "regular") clearVisibleScreenOnce();
142
179
  // Re-mount: dispose the previous instance before building the new one.
143
180
  if (header?.dispose) header.dispose();
144
181
  // Build the service layer and run construction synchronously at mount.
@@ -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 {
@@ -645,20 +651,38 @@ it("tool execute reports the failure stub when the reference is unresolvable", a
645
651
  });
646
652
 
647
653
  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 };
654
+ const data = {
655
+ kind: "text" as const,
656
+ path: "/a.md",
657
+ content: "# Hi",
658
+ lang: "markdown",
659
+ truncated: false,
660
+ };
649
661
  const out = renderBodyComponent(data, true, theme);
650
662
  assert.instanceOf(out, Markdown);
651
663
  });
652
664
 
653
665
  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 };
666
+ const data = {
667
+ kind: "text" as const,
668
+ path: "/a.ts",
669
+ content: "const x = 1;",
670
+ lang: "typescript",
671
+ truncated: false,
672
+ };
655
673
  const out = renderBodyComponent(data, true, theme);
656
674
  assert.instanceOf(out, Text);
657
675
  });
658
676
 
659
677
  it("renderBodyComponent collapses code content to the collapsed line count when not expanded", () => {
660
678
  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 };
679
+ const data = {
680
+ kind: "text" as const,
681
+ path: "/a.ts",
682
+ content,
683
+ lang: "typescript",
684
+ truncated: false,
685
+ };
662
686
  const out = renderBodyComponent(data, false, theme);
663
687
  assert.instanceOf(out, Text);
664
688
  assert.strictEqual(
@@ -668,7 +692,13 @@ it("renderBodyComponent collapses code content to the collapsed line count when
668
692
  });
669
693
 
670
694
  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 };
695
+ const data = {
696
+ kind: "text" as const,
697
+ path: "/a.md",
698
+ content: "# Hi",
699
+ lang: "markdown",
700
+ truncated: true,
701
+ };
672
702
  const out = renderBodyComponent(data, true, theme);
673
703
  assert.instanceOf(out, Markdown);
674
704
  assert.strictEqual(out.render(200).join("\n").includes("... (truncated preview)"), true);
@@ -676,7 +706,13 @@ it("renderBodyComponent appends the truncated note for a truncated expanded reco
676
706
 
677
707
  it("renderBodyComponent appends the more-lines note for a collapsed markdown record", () => {
678
708
  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 };
709
+ const data = {
710
+ kind: "text" as const,
711
+ path: "/a.md",
712
+ content,
713
+ lang: "markdown",
714
+ truncated: false,
715
+ };
680
716
  const out = renderBodyComponent(data, false, theme);
681
717
  assert.instanceOf(out, Markdown);
682
718
  assert.strictEqual(
@@ -777,7 +813,14 @@ it("renderResult renders the warning box for an error result", () => {
777
813
  const tool = registerTool();
778
814
  const result = {
779
815
  content: [],
780
- details: { kind: "text", path: "/x", content: "", lang: undefined, truncated: false, error: "boom" },
816
+ details: {
817
+ kind: "text",
818
+ path: "/x",
819
+ content: "",
820
+ lang: undefined,
821
+ truncated: false,
822
+ error: "boom",
823
+ },
781
824
  } as any;
782
825
  const out = tool.renderResult!(result, { expanded: true, isPartial: false }, theme, {} as any);
783
826
  assert.ok(isComponent(out));
@@ -787,7 +830,13 @@ it("renderResult renders the warning box for an error result", () => {
787
830
 
788
831
  it("renderResult renders the body in a bordered box for a success result", () => {
789
832
  const tool = registerTool();
790
- const record = { kind: "text", path: "/a.md", content: "# Hi", lang: "markdown", truncated: false };
833
+ const record = {
834
+ kind: "text",
835
+ path: "/a.md",
836
+ content: "# Hi",
837
+ lang: "markdown",
838
+ truncated: false,
839
+ };
791
840
  const out = tool.renderResult!(
792
841
  { content: [], details: record } as any,
793
842
  { expanded: true, isPartial: false },
@@ -877,7 +926,13 @@ it("the preview command appends the display record as a custom entry on success"
877
926
  assert.deepStrictEqual(pi.entries, [
878
927
  {
879
928
  type: "preview",
880
- data: { kind: "text", path: "/cwd/file.md", content: "# Hi", lang: "markdown", truncated: false },
929
+ data: {
930
+ kind: "text",
931
+ path: "/cwd/file.md",
932
+ content: "# Hi",
933
+ lang: "markdown",
934
+ truncated: false,
935
+ },
881
936
  },
882
937
  ]);
883
938
  assert.strictEqual(calls.length, 0);
@@ -932,7 +987,15 @@ it("the entry renderer renders the path header and the body inside a bordered bo
932
987
  registerPreview(pi as unknown as ExtensionAPI, makePreviewContext(makeMemFs()));
933
988
  const renderer = pi.renderers.find((r) => r.type === "preview")!.renderer;
934
989
  const out = renderer(
935
- { data: { kind: "text", path: "/abs/a.md", content: "# Hi", lang: "markdown", truncated: false } },
990
+ {
991
+ data: {
992
+ kind: "text",
993
+ path: "/abs/a.md",
994
+ content: "# Hi",
995
+ lang: "markdown",
996
+ truncated: false,
997
+ },
998
+ },
936
999
  { expanded: true },
937
1000
  theme,
938
1001
  );
@@ -973,9 +1036,14 @@ it("the entry renderer draws image entries as caption box + spacer + bare kitty
973
1036
  const boxRows = rendered.split("\n");
974
1037
  assert.strictEqual(boxRows.includes(""), true);
975
1038
  // …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
1039
  assert.strictEqual(
978
- lines.some((l: string) => l.includes("│ \x1b_G") || l.includes("╭ \x1b_G") || /[╭─╰╯]\x1b_G/.test(l)),
1040
+ lines.some((l: string) => l.startsWith("\x1b_G")),
1041
+ true,
1042
+ );
1043
+ assert.strictEqual(
1044
+ lines.some(
1045
+ (l: string) => l.includes("│ \x1b_G") || l.includes("╭ \x1b_G") || /[╭─╰╯]\x1b_G/.test(l),
1046
+ ),
979
1047
  false,
980
1048
  );
981
1049
  } finally {