@xynogen/pix-pretty 1.27.0 → 1.30.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/utils.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { relative } from "node:path";
1
+ import { isAbsolute, relative } from "node:path";
2
2
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
3
 
4
4
  import {
@@ -11,8 +11,9 @@ import {
11
11
  FG_RULE,
12
12
  hasAnsi,
13
13
  RST,
14
- } from "./ansi.js";
15
- import { MAX_PREVIEW_LINES } from "./config.js";
14
+ } from "./ansi.ts";
15
+ import { MAX_PREVIEW_LINES } from "./config.ts";
16
+ import { icon } from "./icon-catalog.ts";
16
17
  import type {
17
18
  FgTheme,
18
19
  TextComponentCtor,
@@ -21,7 +22,7 @@ import type {
21
22
  ToolImageContent,
22
23
  ToolResultLike,
23
24
  ToolTextContent,
24
- } from "./types.js";
25
+ } from "./types.ts";
25
26
 
26
27
  export function renderToolError(error: string, theme: FgTheme): string {
27
28
  return fillToolBackground(theme.fg("error", error), BG_ERROR);
@@ -91,35 +92,37 @@ type FramedResultComponent = ResultComponent & {
91
92
  };
92
93
  };
93
94
 
95
+ // ponytail: 4 widths cover drag/split/fullscreen toggles. The ceiling is memory
96
+ // (4 × card size). Raise MAX_WIDTHS if the profile `resize` column shows misses.
97
+ const MAX_WIDTHS = 4;
98
+
99
+ type ViewportEntry = {
100
+ /** Raw line → line fitted to this width. */
101
+ lines: Map<string, string>;
102
+ /** Inner render output for the current text at this width. */
103
+ rendered: string[] | undefined;
104
+ };
105
+
94
106
  class ViewportText implements TextComponentLike, ViewportComponent {
95
107
  private text = "";
96
- // Pi re-renders every frame (spinner/streaming). Two-level cache:
97
- // 1. per-line: `truncateToWidth` result keyed by raw line + width. Streaming
98
- // only appends to the tail, so already-fitted lines hit the cache and
99
- // only the new/changed lines pay the pi-tui width cost (was O(total
100
- // lines) per chunk, now O(new lines)).
101
- // 2. per-blob: skip re-joining + re-setText'ing the inner component when
102
- // neither text nor width changed (idle frames, spinner ticks).
103
- private fittedWidth = -1;
104
- private fittedText = "";
105
- private lineCache = new Map<string, string>();
106
- private lineCacheWidth = -1;
107
- // Render-output memo. The inner component's render is a pure function of
108
- // (fittedText, width), so on an unchanged frame (spinner tick, idle) we skip
109
- // calling into pi-tui AND skip the fallback split — otherwise both fired
110
- // every single frame even when nothing changed. The returned array is shared
111
- // by reference; pi-tui's render contract is read-only (the host joins/prints
112
- // the lines, never mutates), so we don't defensively copy per frame.
113
- private rendered: string[] = [];
114
- private renderedWidth = -1;
108
+ // Pi re-renders every frame (spinner, streaming, resize). One entry per recent
109
+ // width holds that width's line cache and the inner render output.
110
+ // - Idle frame (same text + width): return the cached lines. No pi-tui call.
111
+ // - Streaming (text grows, same width): the line cache fits only new or changed lines.
112
+ // - Resize back to a recent width: return that width's cached lines.
113
+ // The returned array is shared by reference. pi-tui treats render output as read-only.
114
+ private widths = new Map<number, ViewportEntry>();
115
+ // The inner component holds one text. Track it, so a fit that gives the same
116
+ // text does not force pi-tui to wrap again.
117
+ private innerText: string | undefined;
115
118
 
116
119
  constructor(private readonly component: TextComponentLike) {}
117
120
 
118
121
  setText(value: string): void {
119
122
  if (value === this.text) return;
120
123
  this.text = value;
121
- this.fittedWidth = -1; // invalidate blob memo (line cache stays valid)
122
- this.renderedWidth = -1; // invalidate render-output memo
124
+ // Render output is stale. Line caches stay valid, because they key on the raw line.
125
+ for (const entry of this.widths.values()) entry.rendered = undefined;
123
126
  }
124
127
 
125
128
  getText(): string {
@@ -127,46 +130,48 @@ class ViewportText implements TextComponentLike, ViewportComponent {
127
130
  }
128
131
 
129
132
  render(width: number): string[] {
130
- if (width !== this.fittedWidth) {
131
- if (width !== this.lineCacheWidth) {
132
- this.lineCache.clear(); // width changed → every line must re-fit
133
- this.lineCacheWidth = width;
133
+ let entry = this.widths.get(width);
134
+ if (entry) {
135
+ // Refresh recency: Map keeps insertion order, so re-insert moves it to the end.
136
+ this.widths.delete(width);
137
+ this.widths.set(width, entry);
138
+ } else {
139
+ entry = { lines: new Map(), rendered: undefined };
140
+ this.widths.set(width, entry);
141
+ if (this.widths.size > MAX_WIDTHS) {
142
+ const oldest = this.widths.keys().next().value;
143
+ if (oldest !== undefined) this.widths.delete(oldest);
134
144
  }
135
- const cache = this.lineCache;
136
- const lines = this.text.split("\n");
137
- // Bound the cache so a long streaming log can't grow it without limit.
138
- // The working set is the visible line count; a generous multiple keeps
139
- // steady-state hits while capping worst-case memory. Reset when exceeded
140
- // rather than LRU-evicting — simpler, and a width-stable frame refills it.
141
- if (cache.size > 4 * lines.length + 256) cache.clear();
142
- this.fittedText = lines
143
- .map((line) => {
144
- let fitted = cache.get(line);
145
- if (fitted === undefined) {
146
- fitted = truncateToWidth(line, width, "");
147
- cache.set(line, fitted);
148
- }
149
- return fitted;
150
- })
151
- .join("\n");
152
- this.fittedWidth = width;
153
- this.renderedWidth = -1; // fitted text rebuilt → render output is stale
154
- this.component.setText(this.fittedText);
155
145
  }
156
- if (width !== this.renderedWidth) {
157
- this.rendered = this.component.render?.(width) ?? this.fittedText.split("\n");
158
- this.renderedWidth = width;
146
+ if (entry.rendered) return entry.rendered;
147
+
148
+ const cache = entry.lines;
149
+ const lines = this.text.split("\n");
150
+ // Bound the cache so a long streaming log cannot grow it without limit.
151
+ if (cache.size > 4 * lines.length + 256) cache.clear();
152
+ const fittedText = lines
153
+ .map((line) => {
154
+ let fitted = cache.get(line);
155
+ if (fitted === undefined) {
156
+ fitted = truncateToWidth(line, width, "");
157
+ cache.set(line, fitted);
158
+ }
159
+ return fitted;
160
+ })
161
+ .join("\n");
162
+ if (fittedText !== this.innerText) {
163
+ this.component.setText(fittedText);
164
+ this.innerText = fittedText;
159
165
  }
160
- return this.rendered;
166
+ entry.rendered = this.component.render?.(width) ?? fittedText.split("\n");
167
+ return entry.rendered;
161
168
  }
162
169
 
163
170
  invalidate(): void {
164
- // invalidate = "output stale for reasons other than (text,width)" — theme /
165
- // style change. Fitting is pure on (text,width) so fittedText/lineCache stay
166
- // valid, but the RENDER output (colors) may differ, so drop the render memo;
167
- // otherwise a same-width frame after invalidate would serve pre-invalidate
168
- // output forever.
169
- this.renderedWidth = -1;
171
+ // invalidate = output stale for reasons other than (text, width): a theme or
172
+ // style change. Fitting is pure on (text, width), so line caches stay valid.
173
+ // The render output (colors) may differ, so drop every width's render memo.
174
+ for (const entry of this.widths.values()) entry.rendered = undefined;
170
175
  this.component.invalidate?.();
171
176
  }
172
177
  }
@@ -300,6 +305,33 @@ type CollapsedToolTheme = {
300
305
  bold: (text: string) => string;
301
306
  };
302
307
 
308
+ /** Use the host lifecycle fields so every call has the same status marker. */
309
+ export function formatToolCallTitle(
310
+ theme: {
311
+ fg: (role: "muted" | "warning" | "error" | "success" | "toolTitle", text: string) => string;
312
+ bold?: (text: string) => string;
313
+ },
314
+ tool: string,
315
+ context: { executionStarted?: boolean; isPartial?: boolean; isError?: boolean } = {},
316
+ ): string {
317
+ const complete = context.isPartial === false;
318
+ const role = complete
319
+ ? context.isError
320
+ ? "error"
321
+ : "success"
322
+ : context.executionStarted
323
+ ? "warning"
324
+ : "muted";
325
+ const marker = complete
326
+ ? context.isError
327
+ ? "status.error"
328
+ : "status.ok"
329
+ : context.executionStarted
330
+ ? "status.running"
331
+ : "status.pending";
332
+ return `${theme.fg(role, padIcon(icon(marker)))} ${theme.fg("toolTitle", theme.bold?.(tool) ?? tool)}`;
333
+ }
334
+
303
335
  /** Format the shared one-row content without assuming a render shell. */
304
336
  export function formatCollapsedToolRow(
305
337
  theme: CollapsedToolTheme,
@@ -308,9 +340,11 @@ export function formatCollapsedToolRow(
308
340
  meta = "",
309
341
  status: CollapsedToolStatus = "success",
310
342
  ): string {
311
- const icon = padIcon(COLLAPSED_TOOL_GLYPH[status]);
343
+ const marker = padIcon(
344
+ icon(status === "success" ? "status.ok" : status === "error" ? "status.error" : "status.warn"),
345
+ );
312
346
  const parts = [
313
- `${theme.fg(status, icon)} ${theme.fg("toolTitle", theme.bold(tool))}`,
347
+ `${theme.fg(status, marker)} ${theme.fg("toolTitle", theme.bold(tool))}`,
314
348
  target ? theme.fg("dim", target) : "",
315
349
  meta ? `${theme.fg("muted", "·")} ${theme.fg("muted", meta)}` : "",
316
350
  ].filter(Boolean);
@@ -420,17 +454,11 @@ export function renderDimPreview(
420
454
  const highlight = opts.highlight;
421
455
  const output = normalizeLineEndings(text).trim() || "done";
422
456
  const lines = output.split("\n");
423
- const sw = Math.max(8, termW() - 4); // section-rule width inside the 2-space indent
424
457
  const body = lines
425
458
  .slice(0, maxLines)
426
- .map(
427
- (line) => ` ${sectionRule(line, theme, sw) ?? dimLineWithHighlight(line, theme, highlight)}`,
428
- );
429
- const header = opts.header ? ` ${theme.fg("dim", opts.header)}` : undefined;
430
- const overflow =
431
- lines.length > maxLines
432
- ? ` ${theme.fg("muted", `… ${pluralize(lines.length - maxLines, "more line")}`)}`
433
- : undefined;
459
+ .map((line) => bodyLine(line, theme, (l) => dimLineWithHighlight(l, theme, highlight)));
460
+ const header = opts.header ? `${BODY_PAD}${theme.fg("dim", opts.header)}` : undefined;
461
+ const overflow = lines.length > maxLines ? moreLines(lines.length - maxLines, theme) : undefined;
434
462
 
435
463
  if (opts.frame) {
436
464
  // One shape regardless of line count: a single framed box, no floating
@@ -512,8 +540,10 @@ function _readTtyColumns(): number | undefined {
512
540
  export function shortPath(cwd: string, home: string, p: string): string {
513
541
  if (!p) return "";
514
542
  const r = relative(cwd, p);
515
- if (!r.startsWith("..") && !r.startsWith("/")) return r;
516
- return p.replace(home, "~");
543
+ // isAbsolute: on Windows, relative() across drives returns the absolute target.
544
+ if (!r.startsWith("..") && !isAbsolute(r)) return r;
545
+ // Empty home (unset HOME) must not match: "".replace would prefix every path with "~".
546
+ return home && p.startsWith(home) ? `~${p.slice(home.length)}` : p;
517
547
  }
518
548
 
519
549
  /** Paints a rule line. Callers pass `(s) => theme.fg(status, s)` so the frame
@@ -527,6 +557,9 @@ export function rule(w: number, paint?: RulePaint, style: RuleStyle = "solid"):
527
557
  return paint ? paint(glyphs) : `${FG_RULE}${glyphs}${RST}`;
528
558
  }
529
559
 
560
+ /** Narrow theme for helpers that paint only `muted`. Pi's Theme and FgTheme both fit. */
561
+ type MutedTheme = { fg: (key: "muted", text: string) => string };
562
+
530
563
  /** Matches an `=== label ===` separator line (a common shell/echo idiom). */
531
564
  const SECTION_RE = /^\s*={2,}\s*(.+?)\s*={2,}\s*$/;
532
565
 
@@ -540,7 +573,7 @@ const SECTION_RULE_LEAD = 4;
540
573
  * so the divider aligns with the surrounding tool frame. Label and rule both
541
574
  * use the muted role — theme-driven, ANSI-safe.
542
575
  */
543
- export function sectionRule(line: string, theme: FgTheme, width: number): string | null {
576
+ export function sectionRule(line: string, theme: MutedTheme, width: number): string | null {
544
577
  const m = SECTION_RE.exec(line);
545
578
  if (!m || hasAnsi(line)) return null;
546
579
  const label = ` ${m[1]} `;
@@ -551,6 +584,30 @@ export function sectionRule(line: string, theme: FgTheme, width: number): string
551
584
  return theme.fg("muted", `${"─".repeat(lead)}${label}${"─".repeat(tail)}`);
552
585
  }
553
586
 
587
+ /**
588
+ * One tool-result body line, aligned under the tool title. An `=== label ===` line
589
+ * becomes a full-width section rule. Other lines go through `paint`.
590
+ */
591
+ /**
592
+ * Body indent: one tab. pi-tui renders `\t` as 3 cells, the title column after
593
+ * the 2-cell status icon + space.
594
+ */
595
+ export const BODY_PAD = "\t";
596
+
597
+ export function bodyLine(
598
+ line: string,
599
+ theme: MutedTheme,
600
+ paint: (line: string) => string = (s) => s,
601
+ ): string {
602
+ // ponytail: 3 = pi-tui tab width. Use visibleWidth if BODY_PAD stops being one tab.
603
+ return `${BODY_PAD}${sectionRule(line, theme, termW() - 3) ?? paint(line)}`;
604
+ }
605
+
606
+ /** Muted `… N more lines` footer for a truncated tool-result body. */
607
+ export function moreLines(count: number, theme: MutedTheme): string {
608
+ return `${BODY_PAD}${theme.fg("muted", `… ${pluralize(count, "more line")}`)}`;
609
+ }
610
+
554
611
  /** Decorate completed tool output with status-colored default chrome. */
555
612
  export function frameToolResult<T extends FramableComponent & { setText(value: string): void }>(
556
613
  component: T,