@ftrdotdev/pi-tui 0.2.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 (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -0
  3. package/package.json +80 -0
  4. package/src/autocomplete-contract.test.ts +126 -0
  5. package/src/autocomplete-contract.ts +91 -0
  6. package/src/commands/git-execution.test.ts +69 -0
  7. package/src/commands/git-execution.ts +198 -0
  8. package/src/commands/git-status.test.ts +379 -0
  9. package/src/commands/git-status.ts +320 -0
  10. package/src/components/bordered-box.test.ts +136 -0
  11. package/src/components/bordered-box.ts +106 -0
  12. package/src/components/define-component.ts +33 -0
  13. package/src/components/index.ts +35 -0
  14. package/src/config.test.ts +469 -0
  15. package/src/config.ts +307 -0
  16. package/src/frame/box-frame.test.ts +44 -0
  17. package/src/frame/box-frame.ts +160 -0
  18. package/src/icons.ts +203 -0
  19. package/src/index.ts +359 -0
  20. package/src/runtime.ts +256 -0
  21. package/src/session-lifecycle.ts +41 -0
  22. package/src/state.test.ts +7 -0
  23. package/src/state.ts +90 -0
  24. package/src/telemetry.ts +301 -0
  25. package/src/ui/editor-tint.test.ts +70 -0
  26. package/src/ui/editor-tint.ts +78 -0
  27. package/src/ui/editor.ts +403 -0
  28. package/src/ui/footer.test.ts +350 -0
  29. package/src/ui/footer.ts +225 -0
  30. package/src/ui/header.test.ts +260 -0
  31. package/src/ui/header.ts +165 -0
  32. package/src/ui/preview.test.ts +639 -0
  33. package/src/ui/preview.ts +374 -0
  34. package/src/ui/render-helpers.ts +275 -0
  35. package/src/ui/settings-command.test.ts +218 -0
  36. package/src/ui/settings-command.ts +390 -0
  37. package/src/utils.ts +448 -0
  38. package/src/vim/editor-close-autocomplete.ts +26 -0
  39. package/src/vim/editor-host.test.ts +340 -0
  40. package/src/vim/editor-state.test.ts +385 -0
  41. package/src/vim/editor-state.ts +314 -0
  42. package/src/vim/mode-indicator.test.ts +27 -0
  43. package/src/vim/mode-indicator.ts +44 -0
  44. package/src/vim/selection-render.test.ts +77 -0
  45. package/src/vim/selection-render.ts +85 -0
  46. package/src/vim/text-model.test.ts +85 -0
  47. package/src/vim/text-model.ts +75 -0
  48. package/src/vim/vim-router.test.ts +50 -0
  49. package/src/vim/vim-router.ts +55 -0
  50. package/src/vim/word-motion.ts +96 -0
@@ -0,0 +1,639 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ Theme,
6
+ ToolDefinition,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import { initTheme } from "@earendil-works/pi-coding-agent";
9
+ import { Markdown, Text } from "@earendil-works/pi-tui";
10
+ import { Context, Effect, PlatformError } from "effect";
11
+ import * as FileSystem from "effect/FileSystem";
12
+ import type { Component } from "@earendil-works/pi-tui";
13
+ import {
14
+ capContent,
15
+ COLLAPSED_LINES,
16
+ MAX_BYTES,
17
+ MAX_LINES,
18
+ PreviewReadError,
19
+ PreviewService,
20
+ renderBodyComponent,
21
+ registerPreview,
22
+ sliceUtf8,
23
+ } from "./preview.ts";
24
+
25
+ // The Markdown component reads pi's global theme at render time.
26
+ initTheme();
27
+
28
+ const HOMEDIR = "/home/test";
29
+ const testHomedir = () => HOMEDIR;
30
+ const encode = (raw: string) => new TextEncoder().encode(raw);
31
+
32
+ /** Minimal shape guard: a renderable TUI component (replaces the former class check). */
33
+ const isComponent = (c: unknown): c is Component => typeof (c as Component)?.render === "function";
34
+ const decode = (buf: Uint8Array) => new TextDecoder().decode(buf);
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // Slice 1 — byte-safe truncation and capping behavior
38
+ // ---------------------------------------------------------------------------
39
+
40
+ it("sliceUtf8 returns the buffer unchanged when its length is at or below the byte cap", () => {
41
+ const buf = encode("abc");
42
+ assert.strictEqual(decode(sliceUtf8(buf, 3)), "abc");
43
+ assert.strictEqual(decode(sliceUtf8(buf, 5)), "abc");
44
+ });
45
+
46
+ it("sliceUtf8 cuts the buffer at the byte cap when the content exceeds it", () => {
47
+ const buf = encode("abcdef");
48
+ assert.strictEqual(decode(sliceUtf8(buf, 4)), "abcd");
49
+ });
50
+
51
+ it("sliceUtf8 does not split a multi-byte character at the byte boundary", () => {
52
+ const buf = encode("a€b");
53
+ assert.strictEqual(decode(sliceUtf8(buf, 4)), "a€");
54
+ assert.strictEqual(decode(sliceUtf8(buf, 3)), "a");
55
+ });
56
+
57
+ it("sliceUtf8 returns an empty buffer when the cap lands inside the leading multi-byte character", () => {
58
+ const buf = encode("€ab");
59
+ assert.strictEqual(sliceUtf8(buf, 2).length, 0);
60
+ });
61
+
62
+ it("capContent returns the content unchanged with truncated false when both caps hold", () => {
63
+ assert.deepStrictEqual(capContent("abcde", 5, 3), { content: "abcde", truncated: false });
64
+ });
65
+
66
+ it("capContent truncates at the byte cap and reports truncated when the content exceeds the byte cap", () => {
67
+ assert.deepStrictEqual(capContent("abcdef", 5, 10), { content: "abcde", truncated: true });
68
+ });
69
+
70
+ it("capContent truncates at the line cap and reports truncated when the content exceeds the line cap", () => {
71
+ assert.deepStrictEqual(capContent("a\nb\nc\nd", 100, 3), { content: "a\nb\nc", truncated: true });
72
+ });
73
+
74
+ it("capContent applies the byte cap before the line cap and reports truncated when both fire", () => {
75
+ assert.deepStrictEqual(capContent("ab\ncd\nefgh", 6, 2), { content: "ab\ncd", truncated: true });
76
+ });
77
+
78
+ it("capContent does not split a multi-byte character at the byte cap", () => {
79
+ assert.deepStrictEqual(capContent("€€€", 4, 10), { content: "€", truncated: true });
80
+ });
81
+
82
+ it("the truncation constants keep today's production values", () => {
83
+ assert.strictEqual(MAX_BYTES, 50 * 1024);
84
+ assert.strictEqual(MAX_LINES, 2000);
85
+ assert.strictEqual(COLLAPSED_LINES, 40);
86
+ });
87
+
88
+ // ---------------------------------------------------------------------------
89
+ // Slice 2 — reference resolution behavior
90
+ // ---------------------------------------------------------------------------
91
+
92
+ const runResolve = (raw: string, cwd: string, mem: MemFs = makeMemFs()) =>
93
+ Effect.gen(function* () {
94
+ const svc = yield* PreviewService;
95
+ return yield* svc.resolveFileRef(raw, cwd);
96
+ }).pipe(Effect.provide(PreviewService.layerTest(mem.fs, testHomedir)));
97
+
98
+ it.effect("resolveFileRef strips the @ autocomplete prefix", () =>
99
+ Effect.gen(function* () {
100
+ const out = yield* runResolve("@src/main.ts", "/proj");
101
+ assert.strictEqual(out, "/proj/src/main.ts");
102
+ }),
103
+ );
104
+
105
+ it.effect("resolveFileRef strips surrounding double and single quotes", () =>
106
+ Effect.gen(function* () {
107
+ const double = yield* runResolve('"src/my file.ts"', "/proj");
108
+ assert.strictEqual(double, "/proj/src/my file.ts");
109
+ const single = yield* runResolve("'src/a.ts'", "/proj");
110
+ assert.strictEqual(single, "/proj/src/a.ts");
111
+ }),
112
+ );
113
+
114
+ it.effect("resolveFileRef expands a bare tilde to the home directory", () =>
115
+ Effect.gen(function* () {
116
+ const out = yield* runResolve("~", "/proj");
117
+ assert.strictEqual(out, HOMEDIR);
118
+ }),
119
+ );
120
+
121
+ it.effect("resolveFileRef expands a tilde-prefixed path against the home directory", () =>
122
+ Effect.gen(function* () {
123
+ const out = yield* runResolve("~/notes/a.md", "/proj");
124
+ assert.strictEqual(out, "/home/test/notes/a.md");
125
+ }),
126
+ );
127
+
128
+ it.effect("resolveFileRef converts a file URL to a path", () =>
129
+ Effect.gen(function* () {
130
+ const out = yield* runResolve("file:///tmp/a.md", "/proj");
131
+ assert.strictEqual(out, "/tmp/a.md");
132
+ }),
133
+ );
134
+
135
+ it.effect("resolveFileRef passes absolute paths through unchanged", () =>
136
+ Effect.gen(function* () {
137
+ const out = yield* runResolve("/abs/dir/a.ts", "/proj");
138
+ assert.strictEqual(out, "/abs/dir/a.ts");
139
+ }),
140
+ );
141
+
142
+ it.effect("resolveFileRef resolves relative paths against the working directory", () =>
143
+ Effect.gen(function* () {
144
+ const out = yield* runResolve("sub/b.md", "/proj");
145
+ assert.strictEqual(out, "/proj/sub/b.md");
146
+ }),
147
+ );
148
+
149
+ it.effect("resolveFileRef trims surrounding whitespace", () =>
150
+ Effect.gen(function* () {
151
+ const out = yield* runResolve(" src/a.ts ", "/proj");
152
+ assert.strictEqual(out, "/proj/src/a.ts");
153
+ }),
154
+ );
155
+
156
+ // ---------------------------------------------------------------------------
157
+ // Slice 3 — preview read service behavior
158
+ // ---------------------------------------------------------------------------
159
+
160
+ interface MemFs {
161
+ readonly fs: Partial<FileSystem.FileSystem>;
162
+ readonly files: Map<string, string>;
163
+ }
164
+
165
+ function makeMemFs(init: Record<string, string> = {}): MemFs {
166
+ const files = new Map<string, string>(Object.entries(init));
167
+ const fs: Partial<FileSystem.FileSystem> = {
168
+ readFileString: (path) =>
169
+ files.has(path)
170
+ ? 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
+ ),
180
+ };
181
+ return { fs, files };
182
+ }
183
+
184
+ const runRead = (mem: MemFs, absPath: string, maxBytes?: number, maxLines?: number) =>
185
+ Effect.gen(function* () {
186
+ const svc = yield* PreviewService;
187
+ return yield* svc.read(absPath);
188
+ }).pipe(Effect.provide(PreviewService.layerTest(mem.fs, testHomedir, maxBytes, maxLines)));
189
+
190
+ it.effect("read returns the display record for a readable file", () =>
191
+ Effect.gen(function* () {
192
+ const mem = makeMemFs({ "/abs/file.md": "# Hello" });
193
+ const data = yield* runRead(mem, "/abs/file.md");
194
+ assert.deepStrictEqual(data, {
195
+ path: "/abs/file.md",
196
+ content: "# Hello",
197
+ lang: "markdown",
198
+ truncated: false,
199
+ });
200
+ }),
201
+ );
202
+
203
+ it.effect("read computes a code language hint from the path", () =>
204
+ Effect.gen(function* () {
205
+ const mem = makeMemFs({ "/abs/main.ts": "const x = 1;\n" });
206
+ const data = yield* runRead(mem, "/abs/main.ts");
207
+ assert.strictEqual(data.lang, "typescript");
208
+ assert.strictEqual(data.truncated, false);
209
+ }),
210
+ );
211
+
212
+ it.effect("read truncates content at the injected byte cap and reports truncated", () =>
213
+ Effect.gen(function* () {
214
+ const mem = makeMemFs({ "/abs/big.txt": "abcdef" });
215
+ const data = yield* runRead(mem, "/abs/big.txt", 5);
216
+ assert.strictEqual(data.content, "abcde");
217
+ assert.strictEqual(data.truncated, true);
218
+ }),
219
+ );
220
+
221
+ it.effect("read does not split a multi-byte character at the injected byte cap", () =>
222
+ Effect.gen(function* () {
223
+ const mem = makeMemFs({ "/abs/uni.txt": "€€€" });
224
+ const data = yield* runRead(mem, "/abs/uni.txt", 4);
225
+ assert.strictEqual(data.content, "€");
226
+ assert.strictEqual(data.truncated, true);
227
+ }),
228
+ );
229
+
230
+ it.effect("read truncates content at the injected line cap and reports truncated", () =>
231
+ Effect.gen(function* () {
232
+ const mem = makeMemFs({ "/abs/lines.txt": "a\nb\nc\nd" });
233
+ const data = yield* runRead(mem, "/abs/lines.txt", 100, 3);
234
+ assert.strictEqual(data.content, "a\nb\nc");
235
+ assert.strictEqual(data.truncated, true);
236
+ }),
237
+ );
238
+
239
+ it.effect("read leaves content untruncated at the exact byte and line caps", () =>
240
+ Effect.gen(function* () {
241
+ const mem = makeMemFs({ "/abs/at.txt": "abcde" });
242
+ const data = yield* runRead(mem, "/abs/at.txt", 5, 2000);
243
+ assert.strictEqual(data.content, "abcde");
244
+ assert.strictEqual(data.truncated, false);
245
+ }),
246
+ );
247
+
248
+ it.effect("read fails with PreviewReadError when the file is missing", () =>
249
+ Effect.gen(function* () {
250
+ const mem = makeMemFs();
251
+ const tag = yield* runRead(mem, "/missing.md").pipe(
252
+ Effect.match({
253
+ onFailure: (err) => err._tag,
254
+ onSuccess: () => "unexpected-success",
255
+ }),
256
+ );
257
+ assert.strictEqual(tag, "PreviewReadError");
258
+
259
+ const err = yield* runRead(mem, "/missing.md").pipe(
260
+ Effect.match({
261
+ onFailure: (e) => e,
262
+ onSuccess: () => undefined,
263
+ }),
264
+ );
265
+ assert.ok(err instanceof PreviewReadError);
266
+ assert.strictEqual(err.path, "/missing.md");
267
+ assert.strictEqual(typeof err.message === "string" && err.message.length > 0, true);
268
+ }),
269
+ );
270
+
271
+ it.effect("read fails with PreviewReadError on a permission error", () =>
272
+ Effect.gen(function* () {
273
+ const deniedFs: Partial<FileSystem.FileSystem> = {
274
+ readFileString: () =>
275
+ Effect.fail(
276
+ PlatformError.systemError({
277
+ _tag: "PermissionDenied",
278
+ module: "FileSystem",
279
+ method: "readFileString",
280
+ pathOrDescriptor: "/denied.md",
281
+ description: "cannot read",
282
+ }),
283
+ ),
284
+ };
285
+ const mem: MemFs = { fs: deniedFs, files: new Map() };
286
+ const err = yield* runRead(mem, "/denied.md").pipe(
287
+ Effect.match({
288
+ onFailure: (e) => e,
289
+ onSuccess: () => undefined,
290
+ }),
291
+ );
292
+ assert.ok(err instanceof PreviewReadError);
293
+ assert.strictEqual(err.path, "/denied.md");
294
+ }),
295
+ );
296
+
297
+ it("PreviewReadError carries the expected tag and fields", () => {
298
+ const err = new PreviewReadError({ path: "/x", message: "boom" });
299
+ assert.strictEqual(err._tag, "PreviewReadError");
300
+ assert.instanceOf(err, PreviewReadError);
301
+ assert.strictEqual(err.path, "/x");
302
+ assert.strictEqual(err.message, "boom");
303
+ });
304
+
305
+ // ---------------------------------------------------------------------------
306
+ // Slice 4 — preview tool registration behavior
307
+ // ---------------------------------------------------------------------------
308
+
309
+ const theme = {
310
+ fg: (_color: string, text: string) => text,
311
+ bg: (_color: string, text: string) => text,
312
+ bold: (text: string) => text,
313
+ } as unknown as Theme;
314
+
315
+ class FakePi {
316
+ readonly tools: Array<ToolDefinition<any, any, any>> = [];
317
+ readonly commands: Array<{
318
+ name: string;
319
+ handler: (args: string, ctx: any) => Promise<void>;
320
+ }> = [];
321
+ readonly renderers: Array<{
322
+ type: string;
323
+ renderer: (entry: any, options: any, theme: any) => any;
324
+ }> = [];
325
+ readonly entries: Array<{ type: string; data?: unknown }> = [];
326
+ registerTool(tool: ToolDefinition<any, any, any>): void {
327
+ this.tools.push(tool);
328
+ }
329
+ registerCommand(name: string, options: any): void {
330
+ this.commands.push({ name, ...options });
331
+ }
332
+ registerEntryRenderer(type: string, renderer: any): void {
333
+ this.renderers.push({ type, renderer });
334
+ }
335
+ appendEntry<T = unknown>(type: string, data?: T): void {
336
+ this.entries.push({ type, data });
337
+ }
338
+ }
339
+
340
+ /** Build a Context.Context containing a PreviewService over the injected mem fs. */
341
+ const makePreviewContext = (
342
+ mem: MemFs,
343
+ maxBytes?: number,
344
+ maxLines?: number,
345
+ ): Context.Context<PreviewService> =>
346
+ Effect.runSync(
347
+ Effect.context<PreviewService>().pipe(
348
+ Effect.provide(PreviewService.layerTest(mem.fs, testHomedir, maxBytes, maxLines)),
349
+ ),
350
+ );
351
+
352
+ const registerTool = (mem: MemFs = makeMemFs()) => {
353
+ const pi = new FakePi();
354
+ registerPreview(pi as unknown as ExtensionAPI, makePreviewContext(mem));
355
+ return pi.tools[0]!;
356
+ };
357
+
358
+ it("the preview tool registers with the preview name and a path parameter", () => {
359
+ const tool = registerTool();
360
+ assert.strictEqual(tool.name, "preview");
361
+ assert.strictEqual(tool.parameters.properties.path.type, "string");
362
+ });
363
+
364
+ it("tool execute returns the exact confirmation stub and the display record for a readable file", async () => {
365
+ const tool = registerTool(makeMemFs({ "/cwd/src/file.md": "# Title" }));
366
+ const ctx = { cwd: "/cwd" } as ExtensionContext;
367
+ const result = await tool.execute("call-1", { path: "src/file.md" }, undefined, undefined, ctx);
368
+ assert.strictEqual(
369
+ (result.content[0] as { type: "text"; text: string }).text,
370
+ "[Preview shown to user: src/file.md]",
371
+ );
372
+ assert.deepStrictEqual(result.details, {
373
+ path: "/cwd/src/file.md",
374
+ content: "# Title",
375
+ lang: "markdown",
376
+ truncated: false,
377
+ });
378
+ });
379
+
380
+ it("tool execute resolves relative paths against the tool context cwd", async () => {
381
+ const tool = registerTool(makeMemFs({ "/cwd/src/file.md": "# Title" }));
382
+ const ctx = { cwd: "/cwd" } as ExtensionContext;
383
+ const result = await tool.execute("call-1", { path: "src/file.md" }, undefined, undefined, ctx);
384
+ assert.strictEqual(result.details.path, "/cwd/src/file.md");
385
+ });
386
+
387
+ it("tool execute returns the exact failure stub and error details when the read fails", async () => {
388
+ const tool = registerTool();
389
+ const ctx = { cwd: "/cwd" } as ExtensionContext;
390
+ const result = await tool.execute("call-1", { path: "missing.md" }, undefined, undefined, ctx);
391
+ const expectedMessage = PlatformError.systemError({
392
+ _tag: "NotFound",
393
+ module: "FileSystem",
394
+ method: "readFileString",
395
+ pathOrDescriptor: "/cwd/missing.md",
396
+ description: "No such file",
397
+ }).message;
398
+ assert.strictEqual(
399
+ (result.content[0] as { type: "text"; text: string }).text,
400
+ `preview failed: ${expectedMessage}`,
401
+ );
402
+ assert.deepStrictEqual(result.details, {
403
+ path: "missing.md",
404
+ content: "",
405
+ lang: undefined,
406
+ truncated: false,
407
+ error: expectedMessage,
408
+ });
409
+ });
410
+
411
+ it("tool execute reports the failure stub when the reference is unresolvable", async () => {
412
+ const tool = registerTool();
413
+ const ctx = { cwd: "/cwd" } as ExtensionContext;
414
+ const result = await tool.execute(
415
+ "call-1",
416
+ { path: "file://host/path" },
417
+ undefined,
418
+ undefined,
419
+ ctx,
420
+ );
421
+ assert.strictEqual(
422
+ (result.content[0] as { type: "text"; text: string }).text.startsWith("preview failed: "),
423
+ true,
424
+ );
425
+ assert.strictEqual(
426
+ typeof result.details.error === "string" && result.details.error.length > 0,
427
+ true,
428
+ );
429
+ });
430
+
431
+ 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 };
433
+ const out = renderBodyComponent(data, true, theme);
434
+ assert.instanceOf(out, Markdown);
435
+ });
436
+
437
+ 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 };
439
+ const out = renderBodyComponent(data, true, theme);
440
+ assert.instanceOf(out, Text);
441
+ });
442
+
443
+ it("renderBodyComponent collapses code content to the collapsed line count when not expanded", () => {
444
+ const content = Array.from({ length: 45 }, (_, i) => `line ${i + 1}`).join("\n");
445
+ const data = { path: "/a.ts", content, lang: "typescript", truncated: false };
446
+ const out = renderBodyComponent(data, false, theme);
447
+ assert.instanceOf(out, Text);
448
+ assert.strictEqual(
449
+ out.render(200).join("\n").includes("... (5 lines shown, expand to view all)"),
450
+ true,
451
+ );
452
+ });
453
+
454
+ it("renderBodyComponent appends the truncated note for a truncated expanded record", () => {
455
+ const data = { path: "/a.md", content: "# Hi", lang: "markdown", truncated: true };
456
+ const out = renderBodyComponent(data, true, theme);
457
+ assert.instanceOf(out, Markdown);
458
+ assert.strictEqual(out.render(200).join("\n").includes("... (truncated preview)"), true);
459
+ });
460
+
461
+ it("renderBodyComponent appends the more-lines note for a collapsed markdown record", () => {
462
+ const content = Array.from({ length: 41 }, (_, i) => `line ${i + 1}`).join("\n");
463
+ const data = { path: "/a.md", content, lang: "markdown", truncated: false };
464
+ const out = renderBodyComponent(data, false, theme);
465
+ assert.instanceOf(out, Markdown);
466
+ assert.strictEqual(
467
+ out.render(200).join("\n").includes("... (1 more lines, expand to view all)"),
468
+ true,
469
+ );
470
+ });
471
+
472
+ it("the preview tool renders its own shell instead of pi's standard tool box", () => {
473
+ const tool = registerTool();
474
+ assert.strictEqual(tool.renderShell, "self");
475
+ });
476
+
477
+ it("renderCall renders the preview tool title and the path argument", () => {
478
+ const tool = registerTool();
479
+ const out = tool.renderCall!({ path: "/abs/x.ts" }, theme, {} as any);
480
+ assert.ok(isComponent(out));
481
+ const rendered = out.render(200).join("\n");
482
+ assert.strictEqual(rendered.startsWith("╭"), true); // borders, not raw text
483
+ assert.strictEqual(rendered.includes("preview"), true);
484
+ assert.strictEqual(rendered.includes("/abs/x.ts"), true);
485
+ });
486
+
487
+ it("renderResult falls back to the last component when the details are missing", () => {
488
+ const tool = registerTool();
489
+ const result = { content: [], details: undefined } as any;
490
+ const last = new Text("last", 0, 0);
491
+ const out = tool.renderResult!(result, { expanded: true, isPartial: false }, theme, {
492
+ lastComponent: last,
493
+ } as any);
494
+ assert.strictEqual(out, last);
495
+ const fallback = tool.renderResult!(
496
+ result,
497
+ { expanded: true, isPartial: false },
498
+ theme,
499
+ {} as any,
500
+ );
501
+ assert.instanceOf(fallback, Text);
502
+ });
503
+
504
+ it("renderResult renders the warning box for an error result", () => {
505
+ const tool = registerTool();
506
+ const result = {
507
+ content: [],
508
+ details: { path: "/x", content: "", lang: undefined, truncated: false, error: "boom" },
509
+ } as any;
510
+ const out = tool.renderResult!(result, { expanded: true, isPartial: false }, theme, {} as any);
511
+ assert.ok(isComponent(out));
512
+ assert.strictEqual(out.render(200).join("\n").startsWith("╭"), true); // bordered warning box
513
+ assert.strictEqual(out.render(200).join("\n").includes("preview failed: boom"), true);
514
+ });
515
+
516
+ it("renderResult renders the body in a bordered box for a success result", () => {
517
+ const tool = registerTool();
518
+ const record = { path: "/a.md", content: "# Hi", lang: "markdown", truncated: false };
519
+ const out = tool.renderResult!(
520
+ { content: [], details: record } as any,
521
+ { expanded: true, isPartial: false },
522
+ theme,
523
+ {} as any,
524
+ );
525
+ assert.ok(isComponent(out));
526
+ assert.strictEqual(out.render(200).join("\n").startsWith("╭"), true); // bordered body
527
+ assert.strictEqual(out.render(200).join("\n").includes("Hi"), true);
528
+ });
529
+
530
+ // ---------------------------------------------------------------------------
531
+ // Slice 5 — preview command and entry renderer behavior
532
+ // ---------------------------------------------------------------------------
533
+
534
+ interface NotifySpy {
535
+ readonly calls: Array<[string, string]>;
536
+ readonly ctx: any;
537
+ }
538
+
539
+ const makeCommandCtx = (): NotifySpy => {
540
+ const calls: Array<[string, string]> = [];
541
+ const ctx = {
542
+ cwd: "/cwd",
543
+ ui: {
544
+ notify: (msg: string, level: string) => {
545
+ calls.push([msg, level]);
546
+ },
547
+ },
548
+ };
549
+ return { calls, ctx };
550
+ };
551
+
552
+ const registerCommand = (mem: MemFs = makeMemFs()) => {
553
+ const pi = new FakePi();
554
+ registerPreview(pi as unknown as ExtensionAPI, makePreviewContext(mem));
555
+ return { pi, handler: pi.commands.find((c) => c.name === "preview")!.handler };
556
+ };
557
+
558
+ it("the preview command notifies the usage warning when the argument is empty", async () => {
559
+ const { pi, handler } = registerCommand();
560
+ const { calls, ctx } = makeCommandCtx();
561
+ await handler(" ", ctx);
562
+ assert.strictEqual(calls.length, 1);
563
+ assert.deepStrictEqual(calls[0], ["usage: /preview <path>", "warning"]);
564
+ assert.strictEqual(pi.entries.length, 0);
565
+ });
566
+
567
+ it("the preview command appends the display record as a custom entry on success", async () => {
568
+ const mem = makeMemFs({ "/cwd/file.md": "# Hi" });
569
+ const { pi, handler } = registerCommand(mem);
570
+ const { calls, ctx } = makeCommandCtx();
571
+ await handler("/cwd/file.md", ctx);
572
+ assert.deepStrictEqual(pi.entries, [
573
+ {
574
+ type: "preview",
575
+ data: { path: "/cwd/file.md", content: "# Hi", lang: "markdown", truncated: false },
576
+ },
577
+ ]);
578
+ assert.strictEqual(calls.length, 0);
579
+ });
580
+
581
+ it("the preview command resolves relative paths before reading", async () => {
582
+ const mem = makeMemFs({ "/cwd/file.md": "# Hi" });
583
+ const { pi, handler } = registerCommand(mem);
584
+ const { ctx } = makeCommandCtx();
585
+ await handler("file.md", ctx);
586
+ assert.strictEqual((pi.entries[0]!.data as { path: string }).path, "/cwd/file.md");
587
+ });
588
+
589
+ it("the preview command notifies the error message when the read fails", async () => {
590
+ const { pi, handler } = registerCommand();
591
+ const { calls, ctx } = makeCommandCtx();
592
+ await handler("missing.md", ctx);
593
+ const expectedMessage = PlatformError.systemError({
594
+ _tag: "NotFound",
595
+ module: "FileSystem",
596
+ method: "readFileString",
597
+ pathOrDescriptor: "/cwd/missing.md",
598
+ description: "No such file",
599
+ }).message;
600
+ assert.strictEqual(calls.length, 1);
601
+ assert.deepStrictEqual(calls[0], [`preview failed: ${expectedMessage}`, "error"]);
602
+ assert.strictEqual(pi.entries.length, 0);
603
+ });
604
+
605
+ it("the preview command notifies the error message when the reference is unresolvable", async () => {
606
+ const { pi, handler } = registerCommand();
607
+ const { calls, ctx } = makeCommandCtx();
608
+ await handler("file://host/path", ctx);
609
+ assert.strictEqual(calls.length, 1);
610
+ assert.strictEqual(calls[0]![0].startsWith("preview failed: "), true);
611
+ assert.strictEqual(calls[0]![1], "error");
612
+ assert.strictEqual(pi.entries.length, 0);
613
+ });
614
+
615
+ it("the entry renderer renders a warning bordered box when the entry has no data", () => {
616
+ const pi = new FakePi();
617
+ registerPreview(pi as unknown as ExtensionAPI, makePreviewContext(makeMemFs()));
618
+ const renderer = pi.renderers.find((r) => r.type === "preview")!.renderer;
619
+ const out = renderer({ data: undefined }, { expanded: true }, theme);
620
+ assert.ok(isComponent(out));
621
+ assert.strictEqual(out.render(200).join("\n").startsWith("╭"), true); // bordered warning box
622
+ assert.strictEqual(out.render(200).join("\n").includes("[preview] no data"), true);
623
+ });
624
+
625
+ it("the entry renderer renders the path header and the body inside a bordered box when the entry has data", () => {
626
+ const pi = new FakePi();
627
+ registerPreview(pi as unknown as ExtensionAPI, makePreviewContext(makeMemFs()));
628
+ const renderer = pi.renderers.find((r) => r.type === "preview")!.renderer;
629
+ const out = renderer(
630
+ { data: { path: "/abs/a.md", content: "# Hi", lang: "markdown", truncated: false } },
631
+ { expanded: true },
632
+ theme,
633
+ );
634
+ assert.ok(isComponent(out));
635
+ const rendered = out.render(200).join("\n");
636
+ assert.strictEqual(rendered.startsWith("╭"), true); // bordered body
637
+ assert.strictEqual(rendered.includes("/abs/a.md"), true);
638
+ assert.strictEqual(rendered.includes("Hi"), true);
639
+ });