@xynogen/pix-pretty 1.26.0 → 1.27.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/README.md CHANGED
@@ -49,6 +49,10 @@ problem on terminals without a Nerd Font, becomes a one-file edit here.
49
49
  `{ action: "approved" | "denied" | "timeout", password? }`. Padded with
50
50
  `Box` `paddingX=2`, `paddingY=1`. The simpler `./confirm` export is the
51
51
  plain boolean Yes/No dialog.
52
+ - **Provider picker** (`./provider-picker`) — the color-coded settings UI
53
+ shared by `/web` and `/voice`: a sectioned settings overview, and a provider
54
+ tree with a default dot, connection status, and expandable shell variables
55
+ with set state and an export example.
52
56
 
53
57
  UI features that used to live here have moved to [`pix-display`](packages/pix-display):
54
58
  paste chip rendering and reasoning-tag (`<think>`/`<thinking>`) → native
@@ -125,6 +129,7 @@ The package exposes its sub-modules via `exports`:
125
129
  @xynogen/pix-pretty/context
126
130
  @xynogen/pix-pretty/gate-overlay
127
131
  @xynogen/pix-pretty/modal-frame
132
+ @xynogen/pix-pretty/provider-picker
128
133
  ```
129
134
 
130
135
  ## Full distro
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xynogen/pix-pretty",
3
- "version": "1.26.0",
3
+ "version": "1.27.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",
@@ -27,6 +27,7 @@
27
27
  "./context": "./src/tools/context.ts",
28
28
  "./gate-overlay": "./src/gate-overlay.ts",
29
29
  "./modal-frame": "./src/modal-frame.ts",
30
+ "./provider-picker": "./src/provider-picker.ts",
30
31
  "./test-utils": "./src/test-utils.ts",
31
32
  "./transient-error": "./src/transient-error.ts"
32
33
  },
@@ -0,0 +1,523 @@
1
+ /**
2
+ * pix-pretty/provider-picker — color-coded provider settings used by /web and /voice.
3
+ *
4
+ * `showSettingsPicker` shows the sectioned overview. `showProviderPicker` shows the tree:
5
+ *
6
+ * One row per provider: default dot, status (connected / no API key needed / N variables
7
+ * not set), and an expandable list of shell variables with set state and an export
8
+ * example. A provider row with a `model` also shows a model row when expanded.
9
+ */
10
+
11
+ import {
12
+ decodeKittyPrintable,
13
+ Input,
14
+ Key,
15
+ type KeybindingsManager,
16
+ matchesKey,
17
+ } from "@earendil-works/pi-tui";
18
+ import {
19
+ frameModal,
20
+ MIN_MODAL_HEIGHT,
21
+ ModalPager,
22
+ modalOverlayOptions,
23
+ modalWidth,
24
+ terminalModalHeight,
25
+ } from "./modal-frame.js";
26
+
27
+ export interface ProviderPickerRow {
28
+ id: string;
29
+ configured: boolean;
30
+ env: string[];
31
+ /** Show "no API key needed" in place of "connected". */
32
+ noKey?: boolean;
33
+ /** Current model. When set, the expanded row shows an editable model line. */
34
+ model?: string;
35
+ }
36
+
37
+ export interface ProviderPickerOptions {
38
+ title: string;
39
+ subtitle: string;
40
+ /** Rows in display order. An `auto` row renders as a choice, not a provider. */
41
+ rows: ProviderPickerRow[];
42
+ current: string;
43
+ /** Canonical name → legacy alias. Either one counts as set. */
44
+ envAliases?: Record<string, string>;
45
+ envExample?: (name: string) => string;
46
+ }
47
+
48
+ export type ProviderPickerAction =
49
+ | { kind: "select"; id: string }
50
+ | { kind: "model"; id: string; value: string };
51
+
52
+ interface PickerTheme {
53
+ fg(color: string, text: string): string;
54
+ bg(color: string, text: string): string;
55
+ bold(text: string): string;
56
+ }
57
+
58
+ export interface ProviderPickerUI {
59
+ custom<T>(
60
+ cb: (
61
+ tui: { requestRender(): void; terminal?: { rows?: number } },
62
+ theme: PickerTheme,
63
+ keybindings: KeybindingsManager,
64
+ done: (value: T) => void,
65
+ ) => {
66
+ render(width: number): string[];
67
+ invalidate(): void;
68
+ handleInput(data: string): void;
69
+ dispose?(): void;
70
+ },
71
+ opts?: { overlay?: boolean; overlayOptions?: ReturnType<typeof modalOverlayOptions> },
72
+ ): Promise<T | undefined>;
73
+ }
74
+
75
+ type Node =
76
+ | { kind: "provider"; row: ProviderPickerRow }
77
+ | { kind: "env"; name: string }
78
+ | { kind: "model"; row: ProviderPickerRow };
79
+
80
+ function defaultExample(name: string): string {
81
+ return name.endsWith("_URL")
82
+ ? `export ${name}="https://example.com"`
83
+ : `export ${name}="your-api-key"`;
84
+ }
85
+
86
+ /** Render the tree body. Exported for tests. */
87
+ export function renderProviderRows(
88
+ opts: ProviderPickerOptions,
89
+ theme: Pick<PickerTheme, "fg">,
90
+ state: { cursor: number; expanded: Set<string>; field?: { render(width: number): string[] } },
91
+ width: number,
92
+ ): { lines: string[]; nodes: Node[]; selected: { start: number; end: number } } {
93
+ const aliases = opts.envAliases ?? {};
94
+ const envIsSet = (name: string) => {
95
+ const alias = aliases[name];
96
+ return Boolean(process.env[name] || (alias && process.env[alias]));
97
+ };
98
+ const expandable = (row: ProviderPickerRow) =>
99
+ row.model !== undefined || row.env.some((name) => !envIsSet(name));
100
+ const nodes: Node[] = [];
101
+ for (const row of opts.rows) {
102
+ nodes.push({ kind: "provider", row });
103
+ if (!state.expanded.has(row.id)) continue;
104
+ for (const name of row.env) nodes.push({ kind: "env", name });
105
+ if (row.model !== undefined) nodes.push({ kind: "model", row });
106
+ }
107
+ const mute = (value: string) => theme.fg("muted", value);
108
+ const lines: string[] = [];
109
+ let selected = { start: 0, end: 1 };
110
+ nodes.forEach((node, index) => {
111
+ const marker = index === state.cursor ? theme.fg("accent", "\u25B6") : " ";
112
+ const start = lines.length;
113
+ if (node.kind === "model") {
114
+ const label = `${marker} ${theme.fg("accent", "model")}:`;
115
+ const field = index === state.cursor ? state.field : undefined;
116
+ lines.push(
117
+ field
118
+ ? `${label} ${field.render(Math.max(10, width - 15))[0] ?? ""}`
119
+ : `${label} ${mute(node.row.model ?? "")}`,
120
+ );
121
+ } else if (node.kind === "env") {
122
+ // ponytail: show only presence. Pix never reads or stores the secret value.
123
+ const names = aliases[node.name] ? `${node.name} / ${aliases[node.name]}` : node.name;
124
+ if (envIsSet(node.name)) {
125
+ lines.push(
126
+ `${marker} ${theme.fg("accent", names)} ${theme.fg("success", "\u25CF set")}`,
127
+ );
128
+ } else {
129
+ lines.push(
130
+ `${marker} ${theme.fg("accent", names)} ${mute("\u25CB not set")}`,
131
+ ` ${theme.fg("warning", (opts.envExample ?? defaultExample)(node.name))}`,
132
+ );
133
+ }
134
+ } else {
135
+ const { id, configured, env, noKey } = node.row;
136
+ const unset = env.filter((name) => !envIsSet(name)).length;
137
+ const arrow = expandable(node.row) ? mute(state.expanded.has(id) ? "\u25BE" : "\u25B8") : " ";
138
+ const isDefault = opts.current === id;
139
+ const dot = isDefault ? theme.fg("accent", "\u25CF") : mute("\u25CB");
140
+ const status =
141
+ id === "auto"
142
+ ? mute("choice")
143
+ : configured
144
+ ? theme.fg("success", noKey ? "no API key needed" : "connected")
145
+ : theme.fg("warning", `${unset} variable${unset === 1 ? "" : "s"} not set`);
146
+ const tail = isDefault ? mute(" \u00b7 default") : "";
147
+ lines.push(`${marker} ${arrow} ${dot} ${theme.fg("accent", id)} ${status}${tail}`);
148
+ }
149
+ if (index === state.cursor) selected = { start, end: lines.length };
150
+ });
151
+ return { lines, nodes, selected };
152
+ }
153
+
154
+ export interface SettingsRow {
155
+ key: string;
156
+ section: string;
157
+ label: string;
158
+ value: string;
159
+ /** Theme role for the value. Default `success`. */
160
+ tone?: "success" | "warning" | "muted";
161
+ /** Enter edits `value` in a text field inside the row, not in a new dialog. */
162
+ editable?: boolean;
163
+ /**
164
+ * Enter opens a list under the row, inside the same modal. Typing filters it. With
165
+ * `editable`, the list also has a "type a value…" item that opens the text field.
166
+ */
167
+ choices?: SettingsChoice[];
168
+ }
169
+
170
+ export interface SettingsChoice {
171
+ value: string;
172
+ /** Readable text shown in place of `value`, for example a device name. */
173
+ label?: string;
174
+ /** Muted text after the label, for example the language name. */
175
+ hint?: string;
176
+ }
177
+
178
+ const CUSTOM_CHOICE = "\u0000custom";
179
+
180
+ /** Choices that match `query` by value or hint, case-insensitive. Exported for tests. */
181
+ export function filterChoices(choices: SettingsChoice[], query: string): SettingsChoice[] {
182
+ const q = query.trim().toLowerCase();
183
+ if (!q) return choices;
184
+ return choices.filter((choice) =>
185
+ [choice.value, choice.label, choice.hint].some((text) => text?.toLowerCase().includes(q)),
186
+ );
187
+ }
188
+
189
+ export type SettingsAction = { key: string; value?: string };
190
+
191
+ /** Render the sectioned settings overview body. Exported for tests. */
192
+ export function renderSettingsRows(
193
+ rows: SettingsRow[],
194
+ theme: Pick<PickerTheme, "fg">,
195
+ selected: number,
196
+ field?: { render(width: number): string[] },
197
+ width = 80,
198
+ list?: { choices: SettingsChoice[]; cursor: number; query: string; max?: number },
199
+ ): { lines: string[]; rowLines: number[]; listLine?: number } {
200
+ const labelWidth = Math.max(...rows.map((row) => row.label.length));
201
+ const lines: string[] = [];
202
+ const rowLines: number[] = [];
203
+ let listLine: number | undefined;
204
+ let section = "";
205
+ rows.forEach((row, index) => {
206
+ if (row.section !== section) {
207
+ if (section) lines.push("");
208
+ lines.push(theme.fg("dim", ` ${row.section}`));
209
+ section = row.section;
210
+ }
211
+ const active = index === selected;
212
+ rowLines[index] = lines.length;
213
+ const label = `${active ? theme.fg("accent", "→") : " "} ${theme.fg(active ? "accent" : "text", row.label.padEnd(labelWidth))} `;
214
+ const editing = active ? field : undefined;
215
+ lines.push(
216
+ editing
217
+ ? `${label}${editing.render(Math.max(10, width - labelWidth - 4))[0] ?? ""}`
218
+ : `${label}${theme.fg(row.tone ?? "success", row.value)}`,
219
+ );
220
+ if (!active || !list) return;
221
+ // ponytail: a window of `max` items around the cursor. Add a scrollbar if lists grow past ~50.
222
+ const max = list.max ?? 8;
223
+ const start = Math.max(
224
+ 0,
225
+ Math.min(list.cursor - Math.floor(max / 2), list.choices.length - max),
226
+ );
227
+ const pad = " ".repeat(labelWidth + 4);
228
+ lines.push(`${pad}${theme.fg("muted", "filter:")} ${list.query}${theme.fg("accent", "█")}`);
229
+ list.choices.slice(start, start + max).forEach((choice, offset) => {
230
+ const on = start + offset === list.cursor;
231
+ if (on) listLine = lines.length;
232
+ const text =
233
+ choice.value === CUSTOM_CHOICE
234
+ ? 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}`) : ""}`;
236
+ lines.push(`${pad}${on ? theme.fg("accent", "▸") : " "} ${text}`);
237
+ });
238
+ if (list.choices.length === 0) lines.push(`${pad} ${theme.fg("muted", "no match")}`);
239
+ });
240
+ return { lines, rowLines, listLine };
241
+ }
242
+
243
+ export interface SettingsPickerOptions {
244
+ title: string;
245
+ /** Rows are read again after each action, so a changed value shows at once. */
246
+ rows: () => SettingsRow[];
247
+ /**
248
+ * Run a row action while the modal stays open. Return `"close"` to close it and
249
+ * resolve with the action, for example to open another view.
250
+ */
251
+ onAction: (action: SettingsAction) => Promise<"close" | undefined> | "close" | undefined;
252
+ /** Extra lines under the rows, for example a live level meter. Read on each render. */
253
+ status?: () => string[];
254
+ /** Called with a redraw function while the modal is open, for live status lines. */
255
+ onMount?: (redraw: () => void) => () => void;
256
+ /** Start row. */
257
+ selected?: number;
258
+ }
259
+
260
+ /**
261
+ * Show the sectioned settings overview. It stays open until esc, or until
262
+ * `onAction` returns `"close"`. For an `editable` row, enter opens a text field in
263
+ * the row. Resolves with the closing action, or null on escape.
264
+ */
265
+ export async function showSettingsPicker(
266
+ ui: ProviderPickerUI,
267
+ opts: SettingsPickerOptions,
268
+ ): Promise<SettingsAction | null> {
269
+ const result = await ui.custom<SettingsAction | null>(
270
+ (tui, theme, keybindings, done) => {
271
+ let rows = opts.rows();
272
+ let selected = Math.min(opts.selected ?? 0, Math.max(0, rows.length - 1));
273
+ let field: Input | undefined;
274
+ let list: { row: SettingsRow; query: string; cursor: number } | undefined;
275
+ let busy = false;
276
+ let error = "";
277
+ const redraw = () => tui.requestRender();
278
+ const unmount = opts.onMount?.(redraw);
279
+ const close = (value: SettingsAction | null) => {
280
+ unmount?.();
281
+ done(value);
282
+ };
283
+ const run = async (action: SettingsAction) => {
284
+ busy = true;
285
+ error = "";
286
+ try {
287
+ if ((await opts.onAction(action)) === "close") return close(action);
288
+ } catch (cause) {
289
+ error = cause instanceof Error ? cause.message : String(cause);
290
+ }
291
+ busy = false;
292
+ rows = opts.rows();
293
+ redraw();
294
+ };
295
+ const edit = (row: SettingsRow) => {
296
+ const input = new Input({ prompt: "" });
297
+ input.setValue(row.value);
298
+ input.focused = true;
299
+ input.onEscape = () => {
300
+ field = undefined;
301
+ };
302
+ input.onSubmit = (raw) => {
303
+ const value = raw.trim();
304
+ field = undefined;
305
+ if (value && value !== row.value) void run({ key: row.key, value });
306
+ };
307
+ field = input;
308
+ };
309
+ const listChoices = () => {
310
+ if (!list) return [];
311
+ const shown = filterChoices(list.row.choices ?? [], list.query);
312
+ return list.row.editable ? [...shown, { value: CUSTOM_CHOICE }] : shown;
313
+ };
314
+ const openList = (row: SettingsRow) => {
315
+ const index = (row.choices ?? []).findIndex((choice) => choice.value === row.value);
316
+ list = { row, query: "", cursor: Math.max(0, index) };
317
+ };
318
+ const listInput = (data: string) => {
319
+ if (!list) return;
320
+ const choices = listChoices();
321
+ if (keybindings.matches(data, "tui.select.cancel")) list = undefined;
322
+ else if (keybindings.matches(data, "tui.select.up"))
323
+ list.cursor = (list.cursor - 1 + choices.length) % Math.max(1, choices.length);
324
+ else if (keybindings.matches(data, "tui.select.down"))
325
+ list.cursor = (list.cursor + 1) % Math.max(1, choices.length);
326
+ else if (matchesKey(data, Key.enter)) {
327
+ const choice = choices[list.cursor];
328
+ const { row, query } = list;
329
+ list = undefined;
330
+ if (!choice) return;
331
+ if (choice.value === CUSTOM_CHOICE) {
332
+ edit(row);
333
+ if (query) field?.setValue(query);
334
+ } else if (choice.value !== row.value) void run({ key: row.key, value: choice.value });
335
+ } else if (matchesKey(data, Key.backspace)) {
336
+ list.query = list.query.slice(0, -1);
337
+ list.cursor = 0;
338
+ } else {
339
+ const char = decodeKittyPrintable(data) ?? data;
340
+ if (char.length !== 1 || char < " ") return;
341
+ list.query += char;
342
+ list.cursor = 0;
343
+ }
344
+ redraw();
345
+ };
346
+ return {
347
+ render(width: number) {
348
+ const mw = modalWidth(width);
349
+ const body = renderSettingsRows(
350
+ rows,
351
+ theme,
352
+ selected,
353
+ field,
354
+ mw - 4,
355
+ list && { choices: listChoices(), cursor: list.cursor, query: list.query },
356
+ );
357
+ const status = opts.status?.() ?? [];
358
+ if (error) status.push(theme.fg("error", error));
359
+ if (status.length) body.lines.push("", ...status);
360
+ return frameModal({
361
+ width: mw,
362
+ maxHeight: terminalModalHeight(tui.terminal?.rows),
363
+ minHeight: MIN_MODAL_HEIGHT,
364
+ title: opts.title,
365
+ titleColor: (text) => theme.fg("accent", theme.bold(text)),
366
+ header: [""],
367
+ body: body.lines,
368
+ footer: [
369
+ "",
370
+ theme.fg(
371
+ "muted",
372
+ field
373
+ ? "enter save · esc cancel"
374
+ : list
375
+ ? "type to filter · ↑↓ move · enter pick · esc cancel"
376
+ : "↑↓ move · enter change · esc close",
377
+ ),
378
+ ],
379
+ selectedBodyLine: body.listLine ?? body.rowLines[selected],
380
+ color: (text) => theme.fg("accent", text),
381
+ bg: (text) => theme.bg("customMessageBg", text),
382
+ }).lines;
383
+ },
384
+ invalidate() {},
385
+ dispose: unmount,
386
+ handleInput(data: string) {
387
+ if (field) {
388
+ field.handleInput(data);
389
+ return redraw();
390
+ }
391
+ if (list) return listInput(data);
392
+ if (keybindings.matches(data, "tui.select.cancel")) return close(null);
393
+ if (busy) return;
394
+ const row = rows[selected];
395
+ if (matchesKey(data, Key.enter)) {
396
+ if (!row) return;
397
+ if (row.choices?.length) openList(row);
398
+ else if (row.editable) edit(row);
399
+ else void run({ key: row.key });
400
+ return redraw();
401
+ }
402
+ if (keybindings.matches(data, "tui.select.up"))
403
+ selected = (selected - 1 + rows.length) % rows.length;
404
+ else if (keybindings.matches(data, "tui.select.down"))
405
+ selected = (selected + 1) % rows.length;
406
+ else return;
407
+ redraw();
408
+ },
409
+ };
410
+ },
411
+ { overlay: true, overlayOptions: modalOverlayOptions() },
412
+ );
413
+ return result ?? null;
414
+ }
415
+
416
+ /** Show the provider tree. Resolves the chosen action, or null on escape. */
417
+ export async function showProviderPicker(
418
+ ui: ProviderPickerUI,
419
+ opts: ProviderPickerOptions,
420
+ ): Promise<ProviderPickerAction | null> {
421
+ const result = await ui.custom<ProviderPickerAction | null>(
422
+ (tui, theme, keybindings, done) => {
423
+ const guide = (key: string, action: string) =>
424
+ theme.fg("text", key) + theme.fg("muted", ` ${action}`);
425
+ const sep = theme.fg("muted", " \u00b7 ");
426
+ const expanded = new Set<string>();
427
+ const pager = new ModalPager();
428
+ let field: Input | undefined;
429
+ let nodes = renderProviderRows(opts, theme, { cursor: -1, expanded }, 80).nodes;
430
+ let cursor = Math.max(
431
+ 0,
432
+ nodes.findIndex((node) => node.kind === "provider" && node.row.id === opts.current),
433
+ );
434
+
435
+ const openField = (row: ProviderPickerRow) => {
436
+ const input = new Input({ prompt: "" });
437
+ input.setValue(row.model ?? "");
438
+ input.focused = true;
439
+ input.onEscape = () => {
440
+ field = undefined;
441
+ };
442
+ input.onSubmit = (raw) => {
443
+ const value = raw.trim();
444
+ field = undefined;
445
+ if (value) done({ kind: "model", id: row.id, value });
446
+ };
447
+ field = input;
448
+ };
449
+
450
+ const select = () => {
451
+ const node = nodes[cursor];
452
+ if (node?.kind === "provider") return done({ kind: "select", id: node.row.id });
453
+ if (node?.kind !== "model") return;
454
+ openField(node.row);
455
+ };
456
+
457
+ const toggle = () => {
458
+ const node = nodes[cursor];
459
+ if (node?.kind !== "provider") return;
460
+ if (expanded.has(node.row.id)) expanded.delete(node.row.id);
461
+ else expanded.add(node.row.id);
462
+ nodes = renderProviderRows(opts, theme, { cursor, expanded }, 80).nodes;
463
+ };
464
+
465
+ return {
466
+ render(width: number) {
467
+ const mw = modalWidth(width);
468
+ const body = renderProviderRows(opts, theme, { cursor, expanded, field }, mw - 4);
469
+ nodes = body.nodes;
470
+ const frame = frameModal({
471
+ width: mw,
472
+ maxHeight: terminalModalHeight(tui.terminal?.rows),
473
+ minHeight: MIN_MODAL_HEIGHT,
474
+ header: [
475
+ theme.fg("accent", theme.bold(opts.title)),
476
+ theme.fg("dim", opts.subtitle),
477
+ "",
478
+ ],
479
+ body: body.lines,
480
+ selectedBodyRange: pager.selectedRange(body.selected),
481
+ footer: [
482
+ "",
483
+ field
484
+ ? guide("enter", "submit") + sep + guide("esc", "cancel")
485
+ : guide("\u2191\u2193", "navigate") +
486
+ sep +
487
+ guide("enter", "set default") +
488
+ sep +
489
+ guide("space", "open") +
490
+ sep +
491
+ guide("esc", "close"),
492
+ ],
493
+ bodyOffset: pager.bodyOffset,
494
+ color: (value) => theme.fg("accent", value),
495
+ bg: (value) => theme.bg("customMessageBg", value),
496
+ fg: (value) => theme.fg("text", value),
497
+ });
498
+ pager.sync(frame);
499
+ return frame.lines;
500
+ },
501
+ invalidate() {},
502
+ handleInput(data: string) {
503
+ if (field) field.handleInput(data);
504
+ else if (pager.handleInput(data, keybindings, true)) {
505
+ // paged
506
+ } else if (matchesKey(data, Key.escape)) return done(null);
507
+ else if (matchesKey(data, Key.enter)) return select();
508
+ else if (matchesKey(data, Key.space)) toggle();
509
+ else if (matchesKey(data, Key.up) || keybindings.matches(data, "tui.select.up")) {
510
+ cursor = Math.max(0, cursor - 1);
511
+ pager.followSelection();
512
+ } else if (matchesKey(data, Key.down) || keybindings.matches(data, "tui.select.down")) {
513
+ cursor = Math.min(nodes.length - 1, cursor + 1);
514
+ pager.followSelection();
515
+ }
516
+ tui.requestRender();
517
+ },
518
+ };
519
+ },
520
+ { overlay: true, overlayOptions: modalOverlayOptions() },
521
+ );
522
+ return result ?? null;
523
+ }