@xynogen/pix-pretty 1.27.0 → 1.29.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/lang.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { basename, extname } from "node:path";
2
2
 
3
- import type { BundledLanguage } from "./types.js";
3
+ import type { BundledLanguage } from "./types.ts";
4
4
 
5
5
  export const EXT_LANG: Record<string, BundledLanguage> = {
6
6
  ts: "typescript",
package/src/progress.ts CHANGED
@@ -19,8 +19,8 @@ import {
19
19
  modalOverlayOptions,
20
20
  modalWidth,
21
21
  terminalModalHeight,
22
- } from "./modal-frame.js";
23
- import { SPINNER } from "./widget-format.js";
22
+ } from "./modal-frame.ts";
23
+ import { SPINNER } from "./widget-format.ts";
24
24
 
25
25
  interface ProgressTheme {
26
26
  fg(color: string, text: string): string;
@@ -14,6 +14,8 @@ import {
14
14
  Key,
15
15
  type KeybindingsManager,
16
16
  matchesKey,
17
+ truncateToWidth,
18
+ visibleWidth,
17
19
  } from "@earendil-works/pi-tui";
18
20
  import {
19
21
  frameModal,
@@ -22,7 +24,8 @@ import {
22
24
  modalOverlayOptions,
23
25
  modalWidth,
24
26
  terminalModalHeight,
25
- } from "./modal-frame.js";
27
+ } from "./modal-frame.ts";
28
+ import { getErrorMessage } from "./utils.ts";
26
29
 
27
30
  export interface ProviderPickerRow {
28
31
  id: string;
@@ -212,10 +215,12 @@ export function renderSettingsRows(
212
215
  rowLines[index] = lines.length;
213
216
  const label = `${active ? theme.fg("accent", "→") : " "} ${theme.fg(active ? "accent" : "text", row.label.padEnd(labelWidth))} `;
214
217
  const editing = active ? field : undefined;
218
+ const valueWidth = Math.max(10, width - labelWidth - 4);
215
219
  lines.push(
216
220
  editing
217
- ? `${label}${editing.render(Math.max(10, width - labelWidth - 4))[0] ?? ""}`
218
- : `${label}${theme.fg(row.tone ?? "success", row.value)}`,
221
+ ? `${label}${editing.render(valueWidth)[0] ?? ""}`
222
+ : // One line per row. A long value (a device name) wraps and breaks the cursor math.
223
+ `${label}${theme.fg(row.tone ?? "success", truncateToWidth(row.value, valueWidth, "…"))}`,
219
224
  );
220
225
  if (!active || !list) return;
221
226
  // ponytail: a window of `max` items around the cursor. Add a scrollbar if lists grow past ~50.
@@ -229,10 +234,16 @@ export function renderSettingsRows(
229
234
  list.choices.slice(start, start + max).forEach((choice, offset) => {
230
235
  const on = start + offset === list.cursor;
231
236
  if (on) listLine = lines.length;
237
+ // One line per choice, like the row value. A long device name must not wrap.
238
+ // Cut plain text before the color, so the cut never splits a style.
239
+ const room = Math.max(10, width - pad.length - 2);
240
+ const name = truncateToWidth(choice.label ?? choice.value, room, "…");
241
+ const left = room - visibleWidth(name);
242
+ const hint = choice.hint && left > 3 ? truncateToWidth(` ${choice.hint}`, left, "…") : "";
232
243
  const text =
233
244
  choice.value === CUSTOM_CHOICE
234
245
  ? theme.fg(on ? "accent" : "dim", "type a value…")
235
- : `${theme.fg(on ? "accent" : "text", choice.label ?? choice.value)}${choice.hint ? theme.fg("muted", ` ${choice.hint}`) : ""}`;
246
+ : `${theme.fg(on ? "accent" : "text", name)}${hint ? theme.fg("muted", hint) : ""}`;
236
247
  lines.push(`${pad}${on ? theme.fg("accent", "▸") : " "} ${text}`);
237
248
  });
238
249
  if (list.choices.length === 0) lines.push(`${pad} ${theme.fg("muted", "no match")}`);
@@ -286,7 +297,7 @@ export async function showSettingsPicker(
286
297
  try {
287
298
  if ((await opts.onAction(action)) === "close") return close(action);
288
299
  } catch (cause) {
289
- error = cause instanceof Error ? cause.message : String(cause);
300
+ error = getErrorMessage(cause);
290
301
  }
291
302
  busy = false;
292
303
  rows = opts.rows();
package/src/renderers.ts CHANGED
@@ -2,13 +2,13 @@ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works
2
2
  import { config } from "@xynogen/pix-runtime/config";
3
3
  import { prettySection } from "@xynogen/pix-runtime/sections";
4
4
 
5
- import { FG_DIM, FG_LNUM, FG_RULE, RST } from "./ansi.js";
6
- import { MAX_PREVIEW_LINES } from "./config.js";
7
- import { hlBlock } from "./highlight.js";
8
- import { dirIcon, fileColor, fileIcon } from "./icons.js";
9
- import { lang } from "./lang.js";
10
- import type { FgTheme } from "./types.js";
11
- import { lnum, normalizeLineEndings, pluralize, rule, termW } from "./utils.js";
5
+ import { FG_DIM, FG_LNUM, FG_RULE, RST } from "./ansi.ts";
6
+ import { MAX_PREVIEW_LINES } from "./config.ts";
7
+ import { hlBlock } from "./highlight.ts";
8
+ import { dirIcon, fileColor, fileIcon } from "./icons.ts";
9
+ import { lang } from "./lang.ts";
10
+ import type { FgTheme } from "./types.ts";
11
+ import { lnum, normalizeLineEndings, pluralize, rule, termW } from "./utils.ts";
12
12
 
13
13
  /** Layout controls for {@link renderFileContent}. */
14
14
  export interface RenderFileContentOptions {
@@ -0,0 +1,268 @@
1
+ /**
2
+ * shell-tool — shared registrar + renderer for command-shell tools.
3
+ *
4
+ * pix-bash (`bash`) and pix-powershell (`powershell`) wrap Pi's built-in
5
+ * shell tool definitions (both built on Pi's `createShellToolDefinition`) and
6
+ * render them identically: a compact call line, a status-colored framed body,
7
+ * a live five-line tail while streaming, and an auto-collapsed one-line row.
8
+ * Only the tool name and the command summarizer differ per shell.
9
+ */
10
+
11
+ import type { AgentToolUpdateCallback, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
+ import { truncateToWidth } from "@earendil-works/pi-tui";
13
+ import { type CollapseState, tickCollapse } from "@xynogen/pix-runtime/collapse";
14
+ import { BG_BASE, FG_DIM, RST, resolveBaseBackground } from "./ansi.ts";
15
+ import { MAX_PREVIEW_LINES } from "./config.ts";
16
+ import { renderBashOutput } from "./renderers.ts";
17
+ import type { ToolContext } from "./tools/context.ts";
18
+ import type {
19
+ BashParams,
20
+ PiPrettyApi,
21
+ RenderContextLike,
22
+ ThemeLike,
23
+ ToolFactory,
24
+ ToolResultLike,
25
+ } from "./types.ts";
26
+ import {
27
+ dotJoin,
28
+ fillToolBackground,
29
+ frameToolResult,
30
+ getErrorMessage,
31
+ getTextContent,
32
+ hideCollapsedToolCall,
33
+ isTextContent,
34
+ renderCollapsedToolRow,
35
+ renderToolError,
36
+ ruleFrame,
37
+ sectionRule,
38
+ setResultDetails,
39
+ termW,
40
+ unframeToolResult,
41
+ } from "./utils.ts";
42
+ import { formatDuration } from "./widget-format.ts";
43
+
44
+ export interface ShellToolOptions {
45
+ /** Tool name to register (and collapse-config key), e.g. `"bash"`, `"powershell"`. */
46
+ name: string;
47
+ /** One-line command summary used by the auto-collapsed row. */
48
+ summarize: (command: string) => string;
49
+ /** Output that implies failure when no explicit exit code is reported. */
50
+ failurePattern?: RegExp;
51
+ }
52
+
53
+ const EXIT_CODE_RE = /(?:exit code|exited with(?: code)?|exit status)[:\s]*(\d+)/i;
54
+
55
+ /** Drop cursor/erase CSI + OSC sequences (keep SGR colors) so progress-bar
56
+ * control codes don't leak into the TUI as literal escape junk. */
57
+ function stripNonSgrCsi(text: string): string {
58
+ return text
59
+ .replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, "") // OSC …BEL/ST
60
+ .replace(/\x1b\[[?][0-9;]*[A-Za-z]/g, "") // private-mode CSI (?25l etc.)
61
+ .replace(/\x1b\[[0-9;]*[A-HJKSTfhl]/g, ""); // cursor move / erase CSI
62
+ }
63
+
64
+ /**
65
+ * Progress bars rewrite one line with CR (and often ESC[K). Treat each CR as
66
+ * "overwrite this line", not a newline — otherwise every tick dumps a new row
67
+ * and the card scrolls with dozens of near-identical frames.
68
+ *
69
+ * Split on LF first: `.` does not match CR, so a single `/^.*$/gm` pass would
70
+ * miss CR-only progress streams entirely.
71
+ */
72
+ export function collapseProgressFrames(text: string): string {
73
+ return text
74
+ .replace(/\r\n/g, "\n")
75
+ .split("\n")
76
+ .map((line) => {
77
+ const cr = line.lastIndexOf("\r");
78
+ return stripNonSgrCsi(cr >= 0 ? line.slice(cr + 1) : line);
79
+ })
80
+ .join("\n");
81
+ }
82
+
83
+ /** Canonical shell output normalization: collapse CR progress frames, then
84
+ * squeeze blank runs and trim. */
85
+ export function normalizeShellText(text: string): string {
86
+ return collapseProgressFrames(text)
87
+ .replace(/\n{3,}/g, "\n\n")
88
+ .replace(/^\n+|\n+$/g, "");
89
+ }
90
+
91
+ /** Register `options.name` as a pretty-rendered wrapper around a Pi shell tool. */
92
+ export function registerShellTool(
93
+ pi: PiPrettyApi,
94
+ createTool: ToolFactory<BashParams>,
95
+ ctx: ToolContext,
96
+ options: ShellToolOptions,
97
+ ): void {
98
+ const { cwd, TextComponent, terminalWidth } = ctx;
99
+ const { name, summarize, failurePattern } = options;
100
+ const origTool = createTool(cwd);
101
+
102
+ pi.registerTool({
103
+ ...origTool,
104
+ name,
105
+ // Full-width framing (rules + bg fill) baked at termW(); the default
106
+ // Box shell pads x by 1 and re-wraps at width-2, splitting every line.
107
+ renderShell: "self",
108
+
109
+ async execute(
110
+ tid: string,
111
+ params: BashParams,
112
+ sig: AbortSignal | undefined,
113
+ upd: AgentToolUpdateCallback<unknown> | undefined,
114
+ toolCtx: ExtensionContext,
115
+ ) {
116
+ const startedAt = Date.now();
117
+ const details = (text: string) => {
118
+ const exitMatch = text.match(EXIT_CODE_RE);
119
+ const exitCode = exitMatch ? Number(exitMatch[1]) : failurePattern?.test(text) ? 1 : 0;
120
+ return {
121
+ _type: "bashResult" as const,
122
+ text,
123
+ exitCode,
124
+ command: params.command ?? "",
125
+ durationMs: Date.now() - startedAt,
126
+ };
127
+ };
128
+
129
+ try {
130
+ const result = (await origTool.execute(tid, params, sig, upd, toolCtx)) as ToolResultLike;
131
+ setResultDetails(result, details(getTextContent(result)));
132
+ return result;
133
+ } catch (error) {
134
+ const text = getErrorMessage(error);
135
+ if (!EXIT_CODE_RE.test(text)) throw error;
136
+ return {
137
+ content: [{ type: "text" as const, text }],
138
+ details: details(text),
139
+ isError: true,
140
+ };
141
+ }
142
+ },
143
+
144
+ renderCall(args: BashParams, theme: ThemeLike, renderCtx: RenderContextLike) {
145
+ resolveBaseBackground(theme);
146
+ const displayCmdRaw = (args.command ?? "").trim();
147
+ const text = renderCtx.lastComponent ?? new TextComponent("", 0, 0);
148
+ const label = theme.fg("toolTitle", theme.bold(name));
149
+ const collapseState = renderCtx.state as CollapseState;
150
+ if (hideCollapsedToolCall(collapseState, renderCtx.expanded, (value) => text.setText(value)))
151
+ return text;
152
+ const timeout = args.timeout ? ` ${theme.fg("muted", `(${args.timeout}s timeout)`)}` : "";
153
+ const cmdLines = displayCmdRaw.split("\n");
154
+ const firstLine = cmdLines[0] ?? "";
155
+ const compactCmd =
156
+ cmdLines.length > 1
157
+ ? `${firstLine} ${theme.fg("muted", `… (+${cmdLines.length - 1} lines)`)}`
158
+ : firstLine;
159
+ const baseCmd = renderCtx.expanded ? displayCmdRaw : compactCmd;
160
+ const availableWidth = Math.max(1, (terminalWidth?.() ?? termW()) - 1);
161
+ const prefix = `${label} `;
162
+ const reserve = Math.max(0, availableWidth - timeout.length);
163
+ const displayCmd = truncateToWidth(
164
+ theme.fg("dim", baseCmd),
165
+ Math.max(1, reserve - prefix.length),
166
+ "…",
167
+ );
168
+ text.setText(
169
+ fillToolBackground(`${prefix}${displayCmd}${timeout}`, BG_BASE, terminalWidth?.()),
170
+ );
171
+ return text;
172
+ },
173
+
174
+ renderResult(
175
+ result: ToolResultLike,
176
+ _opt: unknown,
177
+ theme: ThemeLike,
178
+ renderCtx: RenderContextLike,
179
+ ) {
180
+ resolveBaseBackground(theme);
181
+ const text = unframeToolResult(renderCtx.lastComponent ?? new TextComponent("", 0, 0));
182
+ const d = result.details as Record<string, unknown> | undefined;
183
+ const isPartial = (_opt as { isPartial?: boolean } | undefined)?.isPartial === true;
184
+ const completed = () => frameToolResult(text, theme, renderCtx.isError);
185
+ const structuredError = renderCtx.isError && d?._type === "bashResult";
186
+
187
+ if (renderCtx.isError && (!structuredError || isPartial)) {
188
+ text.setText(renderToolError(getTextContent(result) || "Error", theme));
189
+ return isPartial ? text : completed();
190
+ }
191
+
192
+ // Auto-collapse: show summary line after delay
193
+ const cs = renderCtx.state as CollapseState;
194
+ if (!isPartial && tickCollapse(name, cs, renderCtx.invalidate, renderCtx.expanded)) {
195
+ if (d?._type === "bashResult") {
196
+ const normalizedText = normalizeShellText(d.text as string);
197
+ const lc = normalizedText ? normalizedText.split("\n").length : 0;
198
+ const durationMs = Number(d.durationMs ?? 0);
199
+ const exitCode = d.exitCode as number | null;
200
+ const status = exitCode === null ? "warning" : exitCode === 0 ? "success" : "error";
201
+ const meta = dotJoin([
202
+ exitCode !== null && exitCode !== 0 && `exit ${exitCode}`,
203
+ lc > 0 && `${lc} ${lc === 1 ? "line" : "lines"}`,
204
+ durationMs > 0 && formatDuration(durationMs, "bash"),
205
+ ]);
206
+ text.setText(
207
+ renderCollapsedToolRow(
208
+ theme,
209
+ name,
210
+ summarize(String(d.command ?? "")),
211
+ meta,
212
+ status,
213
+ terminalWidth?.(),
214
+ ),
215
+ );
216
+ } else {
217
+ text.setText(fillToolBackground(` ${theme.fg("muted", "done")}`));
218
+ }
219
+ return text;
220
+ }
221
+
222
+ if (renderCtx.isError) {
223
+ text.setText(renderToolError(getTextContent(result) || "Error", theme));
224
+ return completed();
225
+ }
226
+
227
+ if (d?._type === "bashResult") {
228
+ const normalizedText = normalizeShellText(d.text as string);
229
+ const { summary } = renderBashOutput(normalizedText, d.exitCode as number | null, theme);
230
+ const lines = normalizedText ? normalizedText.split("\n") : [];
231
+ const lineCount = lines.length;
232
+
233
+ if (!normalizedText) {
234
+ text.setText(fillToolBackground(summary));
235
+ return isPartial ? text : completed();
236
+ }
237
+
238
+ const maxShow = renderCtx.expanded ? lineCount : MAX_PREVIEW_LINES;
239
+ const show = lines.slice(0, maxShow);
240
+ const footer =
241
+ lineCount > maxShow ? [`${FG_DIM} … ${lineCount - maxShow} more lines${RST}`] : [];
242
+ // Every result (including single-line) is framed; the rules follow exit
243
+ // status: green ok, red failure. The `✓ exit N` header is dropped — the
244
+ // collapsed row already carries status.
245
+ const exitCode = d.exitCode as number | null;
246
+ const statusKey = exitCode === null || exitCode === 0 ? "success" : "error";
247
+ const paint = (s: string) => theme.fg(statusKey, s);
248
+ const sw = Math.max(8, termW() - 4); // section-rule width inside the 2-space indent
249
+ const body = show.map((line) => ` ${sectionRule(line, theme, sw) ?? line}`);
250
+ const out = isPartial ? [...body, ...footer] : ruleFrame(body, footer, termW(), paint);
251
+ text.setText(fillToolBackground(out.join("\n")));
252
+ return text;
253
+ }
254
+
255
+ const fallback = result.content?.[0];
256
+ const fallbackText = fallback && isTextContent(fallback) ? fallback.text : "done";
257
+ if (isPartial) {
258
+ const liveLines = normalizeShellText(String(fallbackText)).split("\n").slice(-5);
259
+ text.setText(
260
+ fillToolBackground(liveLines.map((line) => ` ${theme.fg("dim", line)}`).join("\n")),
261
+ );
262
+ return text;
263
+ }
264
+ text.setText(fillToolBackground(` ${theme.fg("dim", String(fallbackText).slice(0, 120))}`));
265
+ return completed();
266
+ },
267
+ });
268
+ }
package/src/test-utils.ts CHANGED
@@ -2,9 +2,9 @@
2
2
  // rebuilt these same mocks (MockTextComponent, capture-pi, theme, render ctx)
3
3
  // by hand; this collapses them to one import. Pure and Pi-host-agnostic.
4
4
 
5
- import type { CursorStore, FffState } from "./fff.js";
6
- import type { ToolContext } from "./tools/context.js";
7
- import type { PiPrettyApi, RenderContextLike, TextComponentCtor, ThemeLike } from "./types.js";
5
+ import type { CursorStore, FffState } from "./fff.ts";
6
+ import type { ToolContext } from "./tools/context.ts";
7
+ import type { PiPrettyApi, RenderContextLike, TextComponentCtor, ThemeLike } from "./types.ts";
8
8
 
9
9
  /** In-memory TextComponent: stores text, splits on render. */
10
10
  export class MockTextComponent {
@@ -0,0 +1,85 @@
1
+ /**
2
+ * tool-status.ts — one wording + surface for pix-runtime binary downloads.
3
+ *
4
+ * `ensureTool()` (pix-runtime/binaries) reports progress through `onStatus`;
5
+ * runtime cannot import UI. Consumers pass this adapter so every package shows
6
+ * downloads the same way: a footer status while downloading (live activity),
7
+ * then one transient line when installed or failed (AGENTS.md UI surfaces).
8
+ */
9
+
10
+ import { icon } from "./icon-catalog.ts";
11
+ import { showTransientMessage, type TransientErrorUI } from "./transient-error.ts";
12
+
13
+ /** Structural mirror of pix-runtime's ToolStatus (kept local: pretty depends on runtime, not its types). */
14
+ export type ToolStatusEvent =
15
+ | { kind: "downloading"; name: string; version: string; url: string; size?: string }
16
+ | { kind: "installed"; name: string; path: string; version: string; verified: boolean }
17
+ | { kind: "failed"; name: string; error: string; hint: string };
18
+
19
+ export type ToolStatusUI = TransientErrorUI & {
20
+ setStatus?(key: string, text: string | undefined): void;
21
+ };
22
+
23
+ const STATUS_KEY = "pix-binaries";
24
+
25
+ /** Human wording for one status event. */
26
+ export function formatToolStatus(s: ToolStatusEvent): string {
27
+ if (s.kind === "downloading") {
28
+ const size = s.size ? ` (${s.size})` : "";
29
+ return `downloading ${s.name} ${s.version}${size} from ${s.url}`;
30
+ }
31
+ if (s.kind === "installed") {
32
+ return `installed ${s.name} ${s.version} → ${s.path}${s.verified ? " (sha256 verified)" : ""}`;
33
+ }
34
+ return `${s.name} unavailable: ${s.error}${s.hint ? ` — install: ${s.hint}` : ""}`;
35
+ }
36
+
37
+ /** Structural mirror of pix-runtime's BinaryMissingError (no runtime import needed). */
38
+ export interface BinaryMissingLike {
39
+ name: "BinaryMissingError";
40
+ tool: string;
41
+ message: string;
42
+ }
43
+
44
+ export function isBinaryMissing(err: unknown): err is BinaryMissingLike {
45
+ return (
46
+ err instanceof Error &&
47
+ err.name === "BinaryMissingError" &&
48
+ typeof (err as { tool?: unknown }).tool === "string"
49
+ );
50
+ }
51
+
52
+ const warned = new Set<string>();
53
+
54
+ /**
55
+ * Background features (footer branch, welcome, recency) call this when a
56
+ * binary is missing: one transient warning per tool per process, pointing at
57
+ * the /pix Binaries tab, instead of failing silently or spamming. Returns true
58
+ * when `err` was a missing-binary error (handled), false otherwise.
59
+ */
60
+ export function warnBinaryMissing(ui: TransientErrorUI | undefined, err: unknown): boolean {
61
+ if (!isBinaryMissing(err)) return false;
62
+ if (!ui || warned.has(err.tool)) return true;
63
+ warned.add(err.tool);
64
+ showTransientMessage(ui, `${err.message} · set a path in /pix → Binaries`, "warning");
65
+ return true;
66
+ }
67
+
68
+ /** Test seam: forget which tools already warned. */
69
+ export function resetBinaryWarnings(): void {
70
+ warned.clear();
71
+ }
72
+
73
+ /** Build an `onStatus` callback that routes events to the standard surfaces. */
74
+ export function reportToolStatus(ui: ToolStatusUI | undefined): (s: ToolStatusEvent) => void {
75
+ return (s) => {
76
+ if (!ui) return;
77
+ if (s.kind === "downloading") {
78
+ ui.setStatus?.(STATUS_KEY, `${icon("status.running")} ${s.name} ${s.version}`);
79
+ showTransientMessage(ui, formatToolStatus(s), "info");
80
+ return;
81
+ }
82
+ ui.setStatus?.(STATUS_KEY, undefined);
83
+ showTransientMessage(ui, formatToolStatus(s), s.kind === "installed" ? "info" : "warning");
84
+ };
85
+ }
@@ -1,5 +1,5 @@
1
- import type { CursorStore, FffState } from "../fff.js";
2
- import type { TextComponentCtor } from "../types.js";
1
+ import type { CursorStore, FffState } from "../fff.ts";
2
+ import type { TextComponentCtor } from "../types.ts";
3
3
 
4
4
  // ── Shared context passed to each tool registrar ───────────────────────
5
5
 
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,8 @@ 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
16
  import type {
17
17
  FgTheme,
18
18
  TextComponentCtor,
@@ -21,7 +21,7 @@ import type {
21
21
  ToolImageContent,
22
22
  ToolResultLike,
23
23
  ToolTextContent,
24
- } from "./types.js";
24
+ } from "./types.ts";
25
25
 
26
26
  export function renderToolError(error: string, theme: FgTheme): string {
27
27
  return fillToolBackground(theme.fg("error", error), BG_ERROR);
@@ -91,35 +91,37 @@ type FramedResultComponent = ResultComponent & {
91
91
  };
92
92
  };
93
93
 
94
+ // ponytail: 4 widths cover drag/split/fullscreen toggles. The ceiling is memory
95
+ // (4 × card size). Raise MAX_WIDTHS if the profile `resize` column shows misses.
96
+ const MAX_WIDTHS = 4;
97
+
98
+ type ViewportEntry = {
99
+ /** Raw line → line fitted to this width. */
100
+ lines: Map<string, string>;
101
+ /** Inner render output for the current text at this width. */
102
+ rendered: string[] | undefined;
103
+ };
104
+
94
105
  class ViewportText implements TextComponentLike, ViewportComponent {
95
106
  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;
107
+ // Pi re-renders every frame (spinner, streaming, resize). One entry per recent
108
+ // width holds that width's line cache and the inner render output.
109
+ // - Idle frame (same text + width): return the cached lines. No pi-tui call.
110
+ // - Streaming (text grows, same width): the line cache fits only new or changed lines.
111
+ // - Resize back to a recent width: return that width's cached lines.
112
+ // The returned array is shared by reference. pi-tui treats render output as read-only.
113
+ private widths = new Map<number, ViewportEntry>();
114
+ // The inner component holds one text. Track it, so a fit that gives the same
115
+ // text does not force pi-tui to wrap again.
116
+ private innerText: string | undefined;
115
117
 
116
118
  constructor(private readonly component: TextComponentLike) {}
117
119
 
118
120
  setText(value: string): void {
119
121
  if (value === this.text) return;
120
122
  this.text = value;
121
- this.fittedWidth = -1; // invalidate blob memo (line cache stays valid)
122
- this.renderedWidth = -1; // invalidate render-output memo
123
+ // Render output is stale. Line caches stay valid, because they key on the raw line.
124
+ for (const entry of this.widths.values()) entry.rendered = undefined;
123
125
  }
124
126
 
125
127
  getText(): string {
@@ -127,46 +129,48 @@ class ViewportText implements TextComponentLike, ViewportComponent {
127
129
  }
128
130
 
129
131
  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;
132
+ let entry = this.widths.get(width);
133
+ if (entry) {
134
+ // Refresh recency: Map keeps insertion order, so re-insert moves it to the end.
135
+ this.widths.delete(width);
136
+ this.widths.set(width, entry);
137
+ } else {
138
+ entry = { lines: new Map(), rendered: undefined };
139
+ this.widths.set(width, entry);
140
+ if (this.widths.size > MAX_WIDTHS) {
141
+ const oldest = this.widths.keys().next().value;
142
+ if (oldest !== undefined) this.widths.delete(oldest);
134
143
  }
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
144
  }
156
- if (width !== this.renderedWidth) {
157
- this.rendered = this.component.render?.(width) ?? this.fittedText.split("\n");
158
- this.renderedWidth = width;
145
+ if (entry.rendered) return entry.rendered;
146
+
147
+ const cache = entry.lines;
148
+ const lines = this.text.split("\n");
149
+ // Bound the cache so a long streaming log cannot grow it without limit.
150
+ if (cache.size > 4 * lines.length + 256) cache.clear();
151
+ const fittedText = lines
152
+ .map((line) => {
153
+ let fitted = cache.get(line);
154
+ if (fitted === undefined) {
155
+ fitted = truncateToWidth(line, width, "");
156
+ cache.set(line, fitted);
157
+ }
158
+ return fitted;
159
+ })
160
+ .join("\n");
161
+ if (fittedText !== this.innerText) {
162
+ this.component.setText(fittedText);
163
+ this.innerText = fittedText;
159
164
  }
160
- return this.rendered;
165
+ entry.rendered = this.component.render?.(width) ?? fittedText.split("\n");
166
+ return entry.rendered;
161
167
  }
162
168
 
163
169
  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;
170
+ // invalidate = output stale for reasons other than (text, width): a theme or
171
+ // style change. Fitting is pure on (text, width), so line caches stay valid.
172
+ // The render output (colors) may differ, so drop every width's render memo.
173
+ for (const entry of this.widths.values()) entry.rendered = undefined;
170
174
  this.component.invalidate?.();
171
175
  }
172
176
  }
@@ -512,8 +516,10 @@ function _readTtyColumns(): number | undefined {
512
516
  export function shortPath(cwd: string, home: string, p: string): string {
513
517
  if (!p) return "";
514
518
  const r = relative(cwd, p);
515
- if (!r.startsWith("..") && !r.startsWith("/")) return r;
516
- return p.replace(home, "~");
519
+ // isAbsolute: on Windows, relative() across drives returns the absolute target.
520
+ if (!r.startsWith("..") && !isAbsolute(r)) return r;
521
+ // Empty home (unset HOME) must not match: "".replace would prefix every path with "~".
522
+ return home && p.startsWith(home) ? `~${p.slice(home.length)}` : p;
517
523
  }
518
524
 
519
525
  /** Paints a rule line. Callers pass `(s) => theme.fg(status, s)` so the frame