@xynogen/pix-pretty 1.21.0 → 1.26.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/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@xynogen/pix-pretty",
3
- "version": "1.21.0",
3
+ "version": "1.26.0",
4
4
  "description": "Enhanced tool output rendering with syntax highlighting, file icons, tree views, diff rendering, and FFF search",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
7
7
  "exports": {
8
8
  ".": "./src/index.ts",
9
9
  "./ansi": "./src/ansi.ts",
10
+ "./batch": "./src/batch.ts",
10
11
  "./confirm": "./src/confirm.ts",
11
12
  "./progress": "./src/progress.ts",
12
13
  "./config": "./src/config.ts",
@@ -26,7 +27,8 @@
26
27
  "./context": "./src/tools/context.ts",
27
28
  "./gate-overlay": "./src/gate-overlay.ts",
28
29
  "./modal-frame": "./src/modal-frame.ts",
29
- "./test-utils": "./src/test-utils.ts"
30
+ "./test-utils": "./src/test-utils.ts",
31
+ "./transient-error": "./src/transient-error.ts"
30
32
  },
31
33
  "scripts": {
32
34
  "test": "bun test"
@@ -61,7 +63,7 @@
61
63
  "access": "public"
62
64
  },
63
65
  "dependencies": {
64
- "@xynogen/pix-runtime": "^0.8.4",
66
+ "@xynogen/pix-runtime": "^0.10.0",
65
67
  "chalk": "^4.1.2",
66
68
  "cli-highlight": "^2.1.11",
67
69
  "@ff-labs/fff-node": "^0.10.6",
package/src/batch.ts ADDED
@@ -0,0 +1,168 @@
1
+ /** Shared batching for read/grep/find/ls — N known targets, one tool result. */
2
+
3
+ export const BATCH_MAX_TARGETS = 20;
4
+ export const BATCH_MAX_BYTES = 50 * 1024;
5
+
6
+ const encoder = new TextEncoder();
7
+ const decoder = new TextDecoder();
8
+
9
+ /** Merge a singular target with an optional array, trimming and de-duping. */
10
+ export function resolveBatchStrings(single: string | undefined, many: unknown): string[] {
11
+ const out: string[] = [];
12
+ const seen = new Set<string>();
13
+ const add = (value: unknown) => {
14
+ if (typeof value !== "string") return;
15
+ const trimmed = value.trim();
16
+ if (!trimmed || seen.has(trimmed)) return;
17
+ seen.add(trimmed);
18
+ out.push(trimmed);
19
+ };
20
+ add(single);
21
+ if (Array.isArray(many)) {
22
+ for (const value of many) add(value);
23
+ }
24
+ return out;
25
+ }
26
+
27
+ /** Cap the target list at BATCH_MAX_TARGETS, reporting how many were dropped. */
28
+ export function sliceBatchTargets(targets: string[]): { targets: string[]; omitted: number } {
29
+ if (targets.length <= BATCH_MAX_TARGETS) return { targets, omitted: 0 };
30
+ return {
31
+ targets: targets.slice(0, BATCH_MAX_TARGETS),
32
+ omitted: targets.length - BATCH_MAX_TARGETS,
33
+ };
34
+ }
35
+
36
+ /** Minimal JSON-schema object shape we touch when adding a batch field. */
37
+ export interface SchemaObject {
38
+ properties: Record<string, unknown>;
39
+ required?: string[];
40
+ [key: string]: unknown;
41
+ }
42
+
43
+ /** Add an optional string[] field and drop listed keys from `required`. Does not mutate `schema`. */
44
+ export function withOptionalStringArray(
45
+ schema: unknown,
46
+ field: string,
47
+ description: string,
48
+ unrequire: string[] = [],
49
+ ): SchemaObject {
50
+ const src = schema && typeof schema === "object" ? (schema as Record<string, unknown>) : {};
51
+ const properties = {
52
+ ...((src.properties as Record<string, unknown> | undefined) ?? {}),
53
+ [field]: {
54
+ type: "array",
55
+ items: { type: "string" },
56
+ description,
57
+ },
58
+ };
59
+ const required = Array.isArray(src.required)
60
+ ? (src.required as string[]).filter((key) => !unrequire.includes(key))
61
+ : [];
62
+ const next: SchemaObject = { ...src, properties };
63
+ if (required.length > 0) next.required = required;
64
+ else delete next.required;
65
+ return next;
66
+ }
67
+
68
+ export type BatchSection = {
69
+ id: string;
70
+ body: string;
71
+ units: number;
72
+ nouns: readonly [string, string];
73
+ error?: string;
74
+ truncated?: boolean;
75
+ hint?: string;
76
+ };
77
+
78
+ function unitLabel(units: number, nouns: readonly [string, string]): string {
79
+ return `${units} ${units === 1 ? nouns[0] : nouns[1]}`;
80
+ }
81
+
82
+ /** One-line summary of every section (always covers all, even truncated/errored). */
83
+ export function formatBatchIndex(sections: BatchSection[], omitted = 0): string {
84
+ const parts = sections.map((section) => {
85
+ if (section.error) return `${section.id} error`;
86
+ if (section.truncated) {
87
+ return section.hint ? `${section.id} truncated, ${section.hint}` : `${section.id} truncated`;
88
+ }
89
+ return `${section.id} ${unitLabel(section.units, section.nouns)}`;
90
+ });
91
+ if (omitted > 0) parts.push(`+${omitted} omitted`);
92
+ return parts.join(" · ");
93
+ }
94
+
95
+ function byteLength(text: string): number {
96
+ return encoder.encode(text).length;
97
+ }
98
+
99
+ function cutToBytes(text: string, maxBytes: number): string {
100
+ const bytes = encoder.encode(text);
101
+ if (bytes.length <= maxBytes) return text;
102
+ let cut = decoder.decode(bytes.slice(0, maxBytes));
103
+ if (cut.endsWith("\uFFFD")) cut = cut.slice(0, -1);
104
+ const lastNl = cut.lastIndexOf("\n");
105
+ return lastNl > 0 ? cut.slice(0, lastNl) : cut;
106
+ }
107
+
108
+ /** Cap section bodies across the whole batch. Index always covers every section. */
109
+ export function capSections(
110
+ sections: BatchSection[],
111
+ maxBytes: number,
112
+ maxUnits?: number,
113
+ omitted = 0,
114
+ ): { index: string; text: string; sections: BatchSection[] } {
115
+ let remainingUnits = maxUnits;
116
+ let remainingBytes = maxBytes;
117
+ const capped: BatchSection[] = [];
118
+
119
+ for (const section of sections) {
120
+ if (section.error) {
121
+ capped.push(section);
122
+ continue;
123
+ }
124
+ if ((remainingUnits != null && remainingUnits <= 0) || remainingBytes <= 0) {
125
+ capped.push({ ...section, body: "", units: 0, truncated: true });
126
+ continue;
127
+ }
128
+
129
+ const lines = section.body.length > 0 ? section.body.split("\n") : [];
130
+ let keep = lines;
131
+ let truncated = Boolean(section.truncated);
132
+ if (remainingUnits != null && keep.length > remainingUnits) {
133
+ keep = keep.slice(0, remainingUnits);
134
+ truncated = true;
135
+ }
136
+ let body = keep.join("\n");
137
+ if (byteLength(body) > remainingBytes) {
138
+ body = cutToBytes(body, remainingBytes);
139
+ keep = body.length > 0 ? body.split("\n") : [];
140
+ truncated = true;
141
+ }
142
+ const units = body ? keep.length : 0;
143
+ if (remainingUnits != null) remainingUnits -= units;
144
+ remainingBytes -= byteLength(body);
145
+ capped.push({ ...section, body, units, truncated });
146
+ }
147
+
148
+ const index = formatBatchIndex(capped, omitted);
149
+ const blocks = capped
150
+ .filter((section) => section.error || section.body)
151
+ .map((section) => `===== ${section.id} =====\n${section.error ?? section.body}`);
152
+ const text = [index, ...blocks].filter(Boolean).join("\n\n");
153
+ return { index, text, sections: capped };
154
+ }
155
+
156
+ /** Join full section bodies with `===== id =====` headers (no capping). */
157
+ export function joinSectionBodies(sections: BatchSection[]): string {
158
+ return sections
159
+ .map((section) => `===== ${section.id} =====\n${section.error ?? section.body}`)
160
+ .join("\n\n");
161
+ }
162
+
163
+ /** Compact target label for a call row: list up to `max`, else `N noun`. */
164
+ export function formatCallTargets(ids: string[], max = 3, noun = "files"): string {
165
+ if (ids.length === 0) return "";
166
+ if (ids.length <= max) return ids.join(", ");
167
+ return `${ids.length} ${noun}`;
168
+ }
@@ -218,7 +218,10 @@ function buildSections(opts: {
218
218
  } else {
219
219
  const label = config.mode === "sudo" ? (config.passwordLabel ?? "Sudo password:") : "Password:";
220
220
  footer.push(theme.fg("dim", label));
221
- if (passwordStatus) footer.push(theme.fg("error", passwordStatus));
221
+ if (passwordStatus)
222
+ footer.push(
223
+ theme.fg(passwordStatus === "Checking password…" ? "dim" : "error", passwordStatus),
224
+ );
222
225
  footer.push(...maskedInput.render(inner));
223
226
  footer.push("");
224
227
  footer.push(theme.fg("muted", "←→/PgUp/PgDn inspect • enter confirm • esc cancel"));
@@ -29,13 +29,8 @@ export function loadIconMode(): IconMode | undefined {
29
29
  }
30
30
 
31
31
  /** Persist the icon mode to pix.json (`pretty.icons`). */
32
- export function saveIconMode(mode: IconMode): Promise<void> {
33
- return updateConfig(prettySection, { icons: mode }).then(
34
- () => undefined,
35
- (err) => {
36
- console.error("pix-pretty: persist icon mode failed:", err);
37
- },
38
- );
32
+ export async function saveIconMode(mode: IconMode): Promise<void> {
33
+ await updateConfig(prettySection, { icons: mode });
39
34
  }
40
35
 
41
36
  /**
package/src/renderers.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
1
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
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_RULE, RST } from "./ansi.js";
5
+ import { FG_DIM, FG_LNUM, FG_RULE, RST } from "./ansi.js";
6
6
  import { MAX_PREVIEW_LINES } from "./config.js";
7
7
  import { hlBlock } from "./highlight.js";
8
8
  import { dirIcon, fileColor, fileIcon } from "./icons.js";
@@ -10,6 +10,18 @@ import { lang } from "./lang.js";
10
10
  import type { FgTheme } from "./types.js";
11
11
  import { lnum, normalizeLineEndings, pluralize, rule, termW } from "./utils.js";
12
12
 
13
+ /** Layout controls for {@link renderFileContent}. */
14
+ export interface RenderFileContentOptions {
15
+ /** Total render width. Defaults to the live terminal width (`termW()`). */
16
+ width?: number;
17
+ /**
18
+ * Wrap over-wide code lines onto continuation rows instead of clipping the
19
+ * tail with `›`. Off by default (compact preview stays one row per line);
20
+ * expanded views pass `true` so no source text is hidden.
21
+ */
22
+ wrapLongLines?: boolean;
23
+ }
24
+
13
25
  /** Render syntax-highlighted file content with line numbers. */
14
26
  export async function renderFileContent(
15
27
  content: string,
@@ -17,6 +29,7 @@ export async function renderFileContent(
17
29
  offset = 1,
18
30
  maxLines = MAX_PREVIEW_LINES,
19
31
  theme?: FgTheme,
32
+ options: RenderFileContentOptions = {},
20
33
  ): Promise<string> {
21
34
  const normalizedContent = normalizeLineEndings(content);
22
35
  const lines = normalizedContent.split("\n");
@@ -25,7 +38,7 @@ export async function renderFileContent(
25
38
  const lg = lang(filePath);
26
39
  const hl = await hlBlock(show.join("\n"), lg, theme);
27
40
 
28
- const tw = termW();
41
+ const tw = options.width ?? termW();
29
42
  const startLine = offset;
30
43
  const endLine = startLine + show.length - 1;
31
44
  const nw = Math.max(3, String(endLine).length);
@@ -38,6 +51,17 @@ export async function renderFileContent(
38
51
  for (let i = 0; i < hl.length; i++) {
39
52
  const ln = startLine + i;
40
53
  const code = hl[i] ?? show[i] ?? "";
54
+ if (options.wrapLongLines && visibleWidth(code) > cw) {
55
+ // Expanded view: no tail is hidden. First row carries the line number,
56
+ // continuation rows indent under the gutter so the code column aligns.
57
+ const rows = wrapTextWithAnsi(code, cw);
58
+ const pad = " ".repeat(nw);
59
+ rows.forEach((rowText, r) => {
60
+ const gutter = r === 0 ? lnum(ln, nw) : `${FG_LNUM}${pad}${RST}`;
61
+ out.push(`${gutter} ${FG_RULE}│${RST} ${rowText}${RST}`);
62
+ });
63
+ continue;
64
+ }
41
65
  const display = truncateToWidth(code, cw, `${FG_DIM}›`);
42
66
  out.push(`${lnum(ln, nw)} ${FG_RULE}│${RST} ${display}${RST}`);
43
67
  }
@@ -0,0 +1,68 @@
1
+ import { Text, truncateToWidth } from "@earendil-works/pi-tui";
2
+ import { rule } from "./utils.ts";
3
+
4
+ export const TRANSIENT_ERROR_TTL_MS = 30_000;
5
+ const WIDGET_KEY = "pix-transient-error";
6
+ const timers = new WeakMap<object, ReturnType<typeof setTimeout>>();
7
+
8
+ type TransientMessageTheme = {
9
+ fg(color: "error" | "warning" | "accent" | "muted" | "borderMuted", text: string): string;
10
+ };
11
+
12
+ export type TransientMessageLevel = "error" | "warning" | "info";
13
+
14
+ type WidgetFactory = (
15
+ tui: unknown,
16
+ theme: TransientMessageTheme,
17
+ ) => { render(width: number): string[]; invalidate(): void };
18
+
19
+ export type TransientErrorUI = {
20
+ setWidget(
21
+ key: string,
22
+ content: WidgetFactory | undefined,
23
+ options?: { placement?: "aboveEditor" | "belowEditor" },
24
+ ): void;
25
+ };
26
+
27
+ /** Show newest runtime message above the editor (on top of the prompt bar), then remove it after 30 seconds. */
28
+ export function showTransientMessage(
29
+ ui: TransientErrorUI,
30
+ message: string,
31
+ level: TransientMessageLevel = "error",
32
+ ): void {
33
+ const previous = timers.get(ui);
34
+ if (previous) clearTimeout(previous);
35
+
36
+ ui.setWidget(
37
+ WIDGET_KEY,
38
+ (_tui, theme) => {
39
+ const text = new Text("", 0, 0);
40
+ return {
41
+ render(width: number) {
42
+ const color = level === "info" ? "accent" : level;
43
+ const prefix = theme.fg(color, `${level} `);
44
+ text.setText(prefix + theme.fg("muted", message.replace(/\s+/g, " ").trim()));
45
+ return [
46
+ rule(width, (glyphs) => theme.fg("borderMuted", glyphs)),
47
+ truncateToWidth(text.render(width)[0] ?? "", width),
48
+ ];
49
+ },
50
+ invalidate: () => text.invalidate(),
51
+ };
52
+ },
53
+ { placement: "aboveEditor" },
54
+ );
55
+
56
+ const timer = setTimeout(() => {
57
+ if (timers.get(ui) !== timer) return;
58
+ timers.delete(ui);
59
+ ui.setWidget(WIDGET_KEY, undefined);
60
+ }, TRANSIENT_ERROR_TTL_MS);
61
+ timer.unref?.();
62
+ timers.set(ui, timer);
63
+ }
64
+
65
+ /** Error-level convenience wrapper. */
66
+ export function showTransientError(ui: TransientErrorUI, message: string): void {
67
+ showTransientMessage(ui, message, "error");
68
+ }
package/src/types.ts CHANGED
@@ -24,7 +24,12 @@ export type BundledTheme = string;
24
24
  // Config
25
25
  // ---------------------------------------------------------------------------
26
26
 
27
- export type BgTheme = { getBgAnsi?: (key: string) => string };
27
+ export type BgTheme = {
28
+ getBgAnsi?: (key: string) => string;
29
+ // Semantic background wrapper exposed by Pi's theme (e.g. modal fills). Optional
30
+ // so mock/partial themes remain assignable; real runtime themes provide it.
31
+ bg?: (key: string, text: string) => string;
32
+ };
28
33
 
29
34
  export type FgTheme = {
30
35
  fg: (key: string, text: string) => string;
@@ -186,6 +191,8 @@ export type FindResultDetails = {
186
191
  _type: "findResult";
187
192
  text: string;
188
193
  pattern: string;
194
+ /** Present when the call batched several glob patterns in one search. */
195
+ patterns?: string[];
189
196
  path?: string;
190
197
  matchCount: number;
191
198
  };
@@ -194,6 +201,8 @@ export type GrepResultDetails = {
194
201
  _type: "grepResult";
195
202
  text: string;
196
203
  pattern: string;
204
+ /** Present when the call batched several patterns in one search. */
205
+ patterns?: string[];
197
206
  path?: string;
198
207
  matchCount: number;
199
208
  /** Search flags, so the renderer can rebuild the matcher to highlight hits:
@@ -217,7 +226,7 @@ export type RenderDetails =
217
226
  exitCode: number | null;
218
227
  command: string;
219
228
  }
220
- | { _type: "lsResult"; text: string; path: string; entryCount: number }
229
+ | { _type: "lsResult"; text: string; path: string; entryCount: number; paths?: string[] }
221
230
  | FindResultDetails
222
231
  | GrepResultDetails
223
232
  | EditInfoDetails
package/src/utils.ts CHANGED
@@ -87,7 +87,7 @@ const RESULT_FRAME = Symbol("pix.resultFrame");
87
87
  type FramedResultComponent = ResultComponent & {
88
88
  [RESULT_FRAME]: {
89
89
  component: FramableComponent;
90
- update(theme: ResultFrameTheme, isError: boolean): void;
90
+ update(theme: ResultFrameTheme, isError: boolean, section: boolean): void;
91
91
  };
92
92
  };
93
93
 
@@ -519,9 +519,11 @@ export function shortPath(cwd: string, home: string, p: string): string {
519
519
  /** Paints a rule line. Callers pass `(s) => theme.fg(status, s)` so the frame
520
520
  * tint follows the active theme (success/error/warning). Default = neutral FG_RULE. */
521
521
  export type RulePaint = (glyphs: string) => string;
522
+ export type RuleStyle = "solid" | "dashed";
522
523
 
523
- export function rule(w: number, paint?: RulePaint): string {
524
- const glyphs = "─".repeat(w);
524
+ /** Render a full-width solid rule or a spaced ASCII dashed separator. */
525
+ export function rule(w: number, paint?: RulePaint, style: RuleStyle = "solid"): string {
526
+ const glyphs = style === "dashed" ? "- ".repeat(Math.ceil(w / 2)).slice(0, w) : "─".repeat(w);
525
527
  return paint ? paint(glyphs) : `${FG_RULE}${glyphs}${RST}`;
526
528
  }
527
529
 
@@ -549,7 +551,7 @@ export function sectionRule(line: string, theme: FgTheme, width: number): string
549
551
  return theme.fg("muted", `${"─".repeat(lead)}${label}${"─".repeat(tail)}`);
550
552
  }
551
553
 
552
- /** Decorate any tool result component with status-colored top/bottom rules. */
554
+ /** Decorate completed tool output with status-colored default chrome. */
553
555
  export function frameToolResult<T extends FramableComponent & { setText(value: string): void }>(
554
556
  component: T,
555
557
  theme: ResultFrameTheme,
@@ -565,25 +567,46 @@ export function frameToolResult(
565
567
  theme: ResultFrameTheme,
566
568
  isError: boolean,
567
569
  ): ResultComponent {
570
+ return decorateToolResult(component, theme, isError, false);
571
+ }
572
+
573
+ /** Decorate explicit expanded/detail sections with solid top and bottom rules. */
574
+ export function frameToolSection(
575
+ component: FramableComponent,
576
+ theme: ResultFrameTheme,
577
+ isError: boolean,
578
+ ): ResultComponent {
579
+ return decorateToolResult(component, theme, isError, true);
580
+ }
581
+
582
+ function decorateToolResult(
583
+ component: FramableComponent,
584
+ theme: ResultFrameTheme,
585
+ isError: boolean,
586
+ section: boolean,
587
+ ): ResultComponent & Partial<TextComponentLike> {
568
588
  const existing = component as Partial<FramedResultComponent>;
569
589
  if (existing[RESULT_FRAME]) {
570
- existing[RESULT_FRAME].update(theme, isError);
590
+ existing[RESULT_FRAME].update(theme, isError, section);
571
591
  return component as ResultComponent;
572
592
  }
573
593
  let frameTheme = theme;
574
594
  let failed = isError;
595
+ let solid = section;
575
596
  const framed: FramedResultComponent & Partial<TextComponentLike> = {
576
597
  [RESULT_FRAME]: {
577
598
  component,
578
- update(nextTheme, nextError) {
599
+ update(nextTheme, nextError, nextSection) {
579
600
  frameTheme = nextTheme;
580
601
  failed = nextError;
602
+ solid = nextSection;
581
603
  },
582
604
  },
583
605
  wantsKeyRelease: component.wantsKeyRelease,
584
606
  render(width) {
585
607
  const paint = (line: string) => frameTheme.fg(failed ? "error" : "success", line);
586
- return ruleFrame(component.render?.(width) ?? [], [], width, paint);
608
+ const lines = component.render?.(width) ?? [];
609
+ return solid ? sectionFrame(lines, [], width, paint) : ruleFrame(lines, [], width, paint);
587
610
  },
588
611
  invalidate() {
589
612
  component.invalidate?.();
@@ -602,16 +625,24 @@ export function unframeToolResult<T extends FramableComponent>(component: T): T
602
625
  }
603
626
 
604
627
  /**
605
- * Frame tool output the way bash/read/sudo do: a top rule, the body lines, a
606
- * bottom rule, then any footer lines (e.g. `… +N more`) below the close. The
607
- * single source of the "rule top, rule bottom" invariant so every tool's result
608
- * block is framed identically — MCP and the shell tools share this.
628
+ * Default completed-tool chrome: unchanged body, full-width dashed close, then
629
+ * footer lines. Existing callers inherit this distro-wide presentation.
609
630
  */
610
631
  export function ruleFrame(
611
632
  bodyLines: string[],
612
633
  footerLines: string[] = [],
613
634
  width?: number,
614
635
  paint?: RulePaint,
636
+ ): string[] {
637
+ return [...bodyLines, rule(width ?? termW(), paint, "dashed"), ...footerLines];
638
+ }
639
+
640
+ /** Explicit solid top/bottom frame for sections that need stronger separation. */
641
+ export function sectionFrame(
642
+ bodyLines: string[],
643
+ footerLines: string[] = [],
644
+ width?: number,
645
+ paint?: RulePaint,
615
646
  ): string[] {
616
647
  const r = rule(width ?? termW(), paint);
617
648
  return [r, ...bodyLines, r, ...footerLines];