ceulen 0.1.0 → 0.5.1

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 (56) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +103 -14
  3. package/extensions/index.ts +113 -0
  4. package/extensions/lib/env.ts +75 -0
  5. package/extensions/lib/panel.ts +1720 -0
  6. package/extensions/lib/registry.ts +182 -0
  7. package/extensions/modules/composer/index.ts +128 -0
  8. package/extensions/modules/composer/lib/settings.ts +55 -0
  9. package/extensions/modules/composer/lib/shapes.ts +436 -0
  10. package/extensions/modules/composer/test/editor.test.ts +138 -0
  11. package/extensions/modules/composer/test/module.test.ts +218 -0
  12. package/extensions/modules/composer/test/screen.test.ts +195 -0
  13. package/extensions/modules/composer/test/shapes.test.ts +175 -0
  14. package/extensions/modules/config/index.ts +298 -0
  15. package/extensions/modules/config/piSettings.ts +467 -0
  16. package/extensions/modules/config/plugins.ts +290 -0
  17. package/extensions/modules/config/test/kernel.test.ts +523 -0
  18. package/extensions/modules/config/test/kernelV4.test.ts +196 -0
  19. package/extensions/modules/config/test/menu.test.ts +226 -0
  20. package/extensions/modules/config/test/panel.test.ts +395 -0
  21. package/extensions/modules/config/test/piSettings.test.ts +185 -0
  22. package/extensions/modules/config/test/plugins.test.ts +181 -0
  23. package/extensions/modules/config/test/preview-block.test.ts +88 -0
  24. package/extensions/modules/ponytail/UPSTREAM +26 -0
  25. package/extensions/modules/ponytail/index.ts +336 -0
  26. package/extensions/modules/ponytail/lib/config.ts +149 -0
  27. package/extensions/modules/ponytail/lib/instructions.ts +98 -0
  28. package/extensions/modules/ponytail/lib/subagent.ts +31 -0
  29. package/extensions/modules/ponytail/test/extension.test.ts +422 -0
  30. package/extensions/modules/ponytail/test/helpers.test.ts +163 -0
  31. package/extensions/modules/ponytail/test/subagent.test.ts +33 -0
  32. package/extensions/modules/router/commands/commands.ts +99 -0
  33. package/extensions/modules/router/configPanel.ts +89 -0
  34. package/extensions/modules/router/index.ts +75 -0
  35. package/extensions/modules/router/lib/client.ts +390 -0
  36. package/extensions/modules/router/lib/config.ts +142 -0
  37. package/extensions/modules/router/lib/migrate.ts +92 -0
  38. package/extensions/modules/router/lib/provider.ts +138 -0
  39. package/extensions/modules/router/lib/refresh.ts +19 -0
  40. package/extensions/modules/router/test/guard.test.ts +77 -0
  41. package/extensions/modules/router/test/unit.test.ts +1126 -0
  42. package/extensions/modules/usage/index.ts +1975 -0
  43. package/extensions/modules/usage/test/context.test.ts +387 -0
  44. package/extensions/modules/usage/test/env-gating.test.ts +113 -0
  45. package/extensions/modules/usage/test/opencode-go-usage.test.ts +139 -0
  46. package/extensions/modules/usage/test/parsers.test.ts +244 -0
  47. package/extensions/modules/usage/test/stale-ctx-regression.test.ts +294 -0
  48. package/extensions/modules/usage/test/zai-anthropic-adapter.test.ts +40 -0
  49. package/package.json +15 -3
  50. package/skills/ponytail/SKILL.md +124 -0
  51. package/skills/ponytail-audit/SKILL.md +41 -0
  52. package/skills/ponytail-debt/SKILL.md +44 -0
  53. package/skills/ponytail-gain/SKILL.md +51 -0
  54. package/skills/ponytail-help/SKILL.md +73 -0
  55. package/skills/ponytail-review/SKILL.md +57 -0
  56. package/extensions/index.js +0 -42
@@ -0,0 +1,1720 @@
1
+ /**
2
+ * // ponytail: forked from @bacnh85/pi-config-panel 0.1.10; evolved in-repo
3
+ * (split layout, row descriptions/warnings, enum rows, defaults, type-to-search).
4
+ * Upstream sync = manual port.
5
+ *
6
+ * Shared interactive config-panel kernel — an arrow-key toggle/edit form
7
+ * opened via ctx.ui.custom, mirroring Pi's built-in /settings UX.
8
+ *
9
+ * Extracted from pi-a2a's /a2a-config panel (0.3.0 design, unchanged kernel):
10
+ * a generic row model (kind: toggle | string | number | action) with a pure
11
+ * build-rows function per extension so all logic is unit-testable without a
12
+ * TUI. The interactive shell (ctx.ui.custom) is a thin adapter over the model.
13
+ *
14
+ * IMPORTANT (learned the hard way in pi-a2a): the panel must NOT call
15
+ * ctx.ui.input() / ctx.ui.confirm() while it is displayed — those open
16
+ * editor-container dialogs that render UNDER the overlay and fight the
17
+ * overlay focus. Instead the panel embeds its own pi-tui Input component for
18
+ * value editing and saves directly on Esc (no confirmation dialog). This
19
+ * matches the proven llama extension pattern (single custom component,
20
+ * self-contained input handling).
21
+ *
22
+ * Layout (v4, fullscreen boxed frame): the panel renders as a fixed-chrome
23
+ * frame sized to the terminal, launched as a full-viewport overlay. Rounded
24
+ * corners + tee dividers + `│ … │` rows make it a closed rectangle (OMP's
25
+ * overlay-box): boxed top with the title inset → boxed tab row → divider →
26
+ * boxed body → boxed description area → divider → boxed pinned key-hint
27
+ * footer → boxed bottom border. The body is OMP's split — a section sidebar
28
+ * on the left (width PINNED across every tab so the rail never jumps), the
29
+ * rows on the right with in-pane underlined section headings and
30
+ * non-active-section rows dim-washed. Below a 60-column rows pane the
31
+ * sidebar hides and only the headings remain; a fixed-height description
32
+ * area keeps navigation from shifting.
33
+ *
34
+ * Keys: ↑/↓ navigate, Enter toggles booleans / cycles enums / edits strings+
35
+ * numbers (inline input), → ←/Tab jump groups, printable text filters rows,
36
+ * Esc closes (saves when dirty).
37
+ */
38
+
39
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
40
+ import { Input, fuzzyFilter, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
41
+ import type { Component, KeybindingsManager } from "@earendil-works/pi-tui";
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // Row model
45
+ // ---------------------------------------------------------------------------
46
+
47
+ export type PanelRowKind = "toggle" | "string" | "number" | "action" | "info";
48
+
49
+ /** Suggestion option for rows with inline completion support. */
50
+ export interface PanelCompletionItem {
51
+ value: string;
52
+ label?: string;
53
+ description?: string;
54
+ }
55
+
56
+ /** One option of a row's selection submenu (Enter on a multi-choice row). */
57
+ export interface PanelMenuOption {
58
+ value: string;
59
+ label?: string;
60
+ description?: string;
61
+ }
62
+
63
+ export interface PanelRow {
64
+ key: string;
65
+ label: string;
66
+ kind: PanelRowKind;
67
+ value: unknown;
68
+ /** Mask the value in render + inline-edit hint (for secrets/tokens). */
69
+ mask?: boolean;
70
+ /** One-line help for the row, rendered in the fixed description area while
71
+ * selected (env precedence, next-session timing, …). */
72
+ description?: string;
73
+ /** Risk/caveat note rendered above the description in warning styling, with
74
+ * a glyph on the row (e.g. "takes effect after /reload"). */
75
+ warning?: string;
76
+ /** Closed value set: Enter opens the selection submenu (OMP's select
77
+ * submenu), where ↑/↓ browse, Enter commits and Esc backs out. Rows with
78
+ * `values` never open the inline editor. */
79
+ values?: readonly string[];
80
+ /** Dynamic option set for the selection submenu (overrides `values` for the
81
+ * menu; computed at open time — themes, models, …). */
82
+ menu?: () => PanelMenuOption[];
83
+ /** Live preview fired with each highlighted option while the submenu is
84
+ * open (OMP's onThemePreview). Never fired on commit. */
85
+ preview?: (value: string) => void;
86
+ /** Fired once when the submenu is cancelled (Esc) so the row can undo its
87
+ * live preview (OMP's onPreviewCancel). The row owns the restore — passing
88
+ * the original value back through `preview` can't restore values that
89
+ * aren't valid options (e.g. the "auto" theme setting). */
90
+ previewCancel?: () => void;
91
+ /** Read-only preview render (OMP's settings-screen preview window): the
92
+ * block rendered under the rows pane / open submenu for this row — while
93
+ * browsing a submenu, `value` is the HIGHLIGHTED option's value so the
94
+ * preview follows the cursor. Pure: fired per render, never mutates
95
+ * anything. `width` is the body's inner width; lines are truncated to it. */
96
+ previewLines?: (value: string, width: number) => string[];
97
+ /** Declared default; a current value that differs renders warning-styled so
98
+ * the user sees at a glance what this session changed. */
99
+ defaultValue?: unknown;
100
+ /** When set, inline editing shows a suggestion list (↑/↓ + Tab to pick,
101
+ * Enter always submits the typed text). Options are re-filtered against
102
+ * the text after the last `,` so comma-separated values can be composed. */
103
+ completions?: () => PanelCompletionItem[];
104
+ set(v: unknown): void;
105
+ }
106
+
107
+ export interface PanelGroup {
108
+ key: string;
109
+ label: string;
110
+ /** Optional tab this group belongs to. ADJACENT groups with the same `tab`
111
+ * render as one tab (the tab chip shows the tab name + first icon) with
112
+ * each group's `label` as a left-sidebar SECTION, the rows on the right —
113
+ * OMP's tab → section → rows hierarchy. Without `tab`, the group is its
114
+ * own tab and `label` doubles as the tab name. */
115
+ tab?: string;
116
+ /** Short glyph shown on the tab chip (emoji or symbol; width-aware). */
117
+ icon?: string;
118
+ rows: PanelRow[];
119
+ }
120
+
121
+ /** Options accepted by `row()` beyond the required set. */
122
+ export interface PanelRowOpts {
123
+ mask?: boolean;
124
+ description?: string;
125
+ warning?: string;
126
+ values?: readonly string[];
127
+ menu?: () => PanelMenuOption[];
128
+ preview?: (value: string) => void;
129
+ previewCancel?: () => void;
130
+ previewLines?: (value: string, width: number) => string[];
131
+ defaultValue?: unknown;
132
+ completions?: () => PanelCompletionItem[];
133
+ }
134
+
135
+ /** Action descriptor (the "add peer" / "remove peer" rows). */
136
+ export interface PanelAction {
137
+ label: string;
138
+ /** Runs when the row is activated. `prompt` opens an inline input dialog
139
+ * (Enter confirms, Esc cancels → undefined) — actions must NOT call
140
+ * ctx.ui.input()/select()/confirm() while the panel overlay is showing. */
141
+ run: (prompt: (label: string, onDone: (value: string | undefined) => void) => void) => Promise<void> | void;
142
+ }
143
+
144
+ /** Build the row model from a working config. The extension owns this —
145
+ * row setters mutate the passed config in place so the caller keeps a
146
+ * working copy and marks dirty. */
147
+ export type BuildRows<T> = (cfg: T, actions: Record<string, PanelAction>) => PanelGroup[];
148
+
149
+ // ---------------------------------------------------------------------------
150
+ // Pure row helpers — shared by every extension's buildRows
151
+ // ---------------------------------------------------------------------------
152
+
153
+ /** Construct a row whose setter updates BOTH the backing config and row.value
154
+ * so the render reflects the change immediately (a stale value made toggles
155
+ * appear dead — regression-tested in pi-a2a). */
156
+ export function row(
157
+ key: string,
158
+ label: string,
159
+ kind: PanelRowKind,
160
+ value: unknown,
161
+ set: (v: unknown) => void,
162
+ opts: PanelRowOpts = {},
163
+ ): PanelRow {
164
+ const r: PanelRow = {
165
+ key,
166
+ label,
167
+ kind,
168
+ value,
169
+ mask: opts.mask,
170
+ description: opts.description,
171
+ warning: opts.warning,
172
+ values: opts.values,
173
+ menu: opts.menu,
174
+ preview: opts.preview,
175
+ previewCancel: opts.previewCancel,
176
+ previewLines: opts.previewLines,
177
+ defaultValue: opts.defaultValue,
178
+ ...(opts.completions && { completions: opts.completions }),
179
+ set(v: unknown) {
180
+ set(v);
181
+ r.value = kind === "number" ? toInt(v, Number(r.value)) : v;
182
+ },
183
+ };
184
+ return r;
185
+ }
186
+
187
+ /** Coerce to int, keeping the fallback on garbage input. */
188
+ export function toInt(v: unknown, fallback: number): number {
189
+ const n = typeof v === "string" ? parseInt(v, 10) : v;
190
+ return Number.isFinite(n) ? (n as number) : fallback;
191
+ }
192
+
193
+ /** Apply every row's setter to a fresh config (for tests / "apply" flows). */
194
+ export function applyRows<T>(cfg: T, groups: PanelGroup[]): T {
195
+ for (const g of groups) {
196
+ for (const r of g.rows) {
197
+ if (r.kind !== "action") r.set(r.value);
198
+ }
199
+ }
200
+ return cfg;
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------
204
+ // Interactive shell (thin adapter over the model)
205
+ // ---------------------------------------------------------------------------
206
+
207
+ export interface ConfigPanelOpts<T> {
208
+ ctx: ExtensionContext;
209
+ cfg: T;
210
+ /** Row builder for the panel's config (the extension-specific part). */
211
+ build: BuildRows<T>;
212
+ actions?: Record<string, PanelAction>;
213
+ /** Panel title (first render line). */
214
+ title?: string;
215
+ /** Called when the panel saves (Esc with dirty). Second arg: row keys the
216
+ * user actually edited (for secret-persistence decisions). */
217
+ onSave?: (saved: boolean, editedKeys?: Set<string>) => void;
218
+ }
219
+
220
+ /** Build the action-row handler for an open panel. Shared with tests so the
221
+ * rebuild-after-action behavior (added/removed rows re-render) is guarded by
222
+ * the same code path production uses. `onError` reports action failures
223
+ * (openConfigPanel routes to ctx.ui.notify). */
224
+ export function makeOnAction<T>(
225
+ model: ConfigPanelModel,
226
+ cfg: T,
227
+ build: BuildRows<T>,
228
+ actions: Record<string, PanelAction>,
229
+ onError: (msg: string) => void,
230
+ ): (row: PanelRow) => Promise<void> {
231
+ return async (row) => {
232
+ // Cancel detection: run() is typically sync — it returns BEFORE the inline
233
+ // prompt resolves — so dirty/rebuild is decided at prompt resolution, not
234
+ // after row.set resolves. Esc resolves onDone(undefined) → cancelled → no
235
+ // dirty, no rebuild, so Esc-close won't fire onSave(true). Promptless
236
+ // actions (no prompt() call) keep the old apply-on-return behavior.
237
+ let prompted = false;
238
+ const apply = () => {
239
+ model.dirty = true;
240
+ model.setGroups(build(cfg, actions));
241
+ model.requestRender();
242
+ };
243
+ try {
244
+ await row.set((label: string, onDone: (v: string | undefined) => void) => {
245
+ prompted = true;
246
+ model.prompt(label, (v) => {
247
+ // Run the action's own callback first so the rebuild below sees the
248
+ // mutated config; "" (empty submit) is an applied change, only
249
+ // undefined is a cancel.
250
+ onDone(v);
251
+ if (v !== undefined) apply();
252
+ });
253
+ });
254
+ if (!prompted) apply();
255
+ } catch (e: any) {
256
+ onError(`Action failed: ${e?.message || e}`);
257
+ }
258
+ };
259
+ }
260
+
261
+ /**
262
+ * Open the interactive config panel via ctx.ui.custom.
263
+ * Resolves when the panel closes (Esc — saves when dirty).
264
+ *
265
+ * Full-viewport (OMP's /settings shape): launched as a 100%×100% top-left
266
+ * overlay so the frame covers the terminal and the chat stays untouched
267
+ * underneath; on close pi hides the overlay and focus returns to the editor
268
+ * (interactive-mode.js custom→showExtensionCustom overlay branch).
269
+ */
270
+ export function openConfigPanel<T>(opts: ConfigPanelOpts<T>): Promise<void> {
271
+ const { ctx, cfg, build, actions = {}, title, onSave } = opts;
272
+ if (ctx.mode !== "tui" || !ctx.hasUI) {
273
+ ctx.ui.notify("Config panel requires interactive TUI mode.", "warning");
274
+ onSave?.(false);
275
+ return Promise.resolve();
276
+ }
277
+ return ctx.ui.custom((tui, theme, keybindings, done) => {
278
+ const model = new ConfigPanelModel(build(cfg, actions), theme, title);
279
+ model.keybindings = keybindings;
280
+ model.onRequestRender = () => tui.requestRender();
281
+ model.onSave = async () => {
282
+ try {
283
+ await onSave?.(true, model.editedKeys);
284
+ } catch (e: any) {
285
+ // Async rejections land here too (await unwraps the promise) — the
286
+ // panel stays open so the user can retry or Esc without saving.
287
+ ctx.ui.notify(`Save failed: ${e?.message || e}`, "error");
288
+ return;
289
+ }
290
+ done();
291
+ };
292
+ // Action rows run with an inline prompt (Enter confirms, Esc cancels →
293
+ // undefined). Actions must NOT use ctx.ui.input/select/confirm here —
294
+ // those render under the overlay and break the panel. onAction is an
295
+ // error-reporting hook (activate() drives the action itself).
296
+ model.onAction = makeOnAction(model, cfg, build, actions, (msg) => ctx.ui.notify(msg, "error"));
297
+ model.onClose = () => {
298
+ // Save when dirty (no confirm dialog — Esc = save-and-close; Esc within
299
+ // an inline input cancels the edit instead). Matches the llama
300
+ // extension's no-nested-dialog pattern.
301
+ if (model.dirty) {
302
+ model.onSave?.();
303
+ } else {
304
+ done();
305
+ }
306
+ };
307
+ return model;
308
+ }, {
309
+ overlay: true,
310
+ overlayOptions: () => ({ anchor: "top-left", width: "100%", maxHeight: "100%", margin: 0 }),
311
+ });
312
+ }
313
+
314
+ /** Coerce a raw input string to the row kind's value. */
315
+ export function kindValue(kind: PanelRowKind, raw: string): unknown {
316
+ if (kind === "number") {
317
+ const n = parseInt(raw, 10);
318
+ return Number.isFinite(n) ? n : raw;
319
+ }
320
+ if (kind === "toggle") return /^(1|true|yes|on)$/i.test(raw.trim());
321
+ return raw;
322
+ }
323
+
324
+ // ---------------------------------------------------------------------------
325
+ // Inline completion helpers (pure — unit-tested without a TUI)
326
+ // ---------------------------------------------------------------------------
327
+
328
+ /** Split the value at the cursor into the committed head (text before the
329
+ * segment containing the cursor) and the live segment the cursor sits in.
330
+ * Cursor-aware: the picker edits whichever entry the cursor is inside, not
331
+ * just the last one. Without a cursor (undefined), falls back to the legacy
332
+ * last-segment split. */
333
+ function splitSegments(raw: string, cursor?: number): { head: string; suffix: string } {
334
+ if (cursor === undefined || cursor >= raw.length) {
335
+ const idx = raw.lastIndexOf(",");
336
+ if (idx === -1) return { head: "", suffix: raw };
337
+ return { head: raw.slice(0, idx).trim(), suffix: raw.slice(idx + 1).replace(/^ /, '') };
338
+ }
339
+ // Segment boundaries: commas before and after the cursor. A cursor sitting
340
+ // ON a comma belongs to the segment before it (editing that entry's tail).
341
+ const start = (raw.lastIndexOf(",", cursor - 1) + 1) || 0;
342
+ let end = raw.indexOf(",", cursor);
343
+ if (end === -1) end = raw.length;
344
+ const head = raw.slice(0, start).trim().replace(/,$/, "").trim();
345
+ const suffix = raw.slice(start, end).replace(/^ /, "");
346
+ return { head, suffix };
347
+ }
348
+
349
+ /** Filter completion options against the segment the cursor sits in (or the
350
+ * last segment when no cursor is given). Empty → every option (full list).
351
+ * Case-insensitive substring. `emptyQuery` overrides the segment text with
352
+ * an empty query (full list) — used after cursor navigation so entering an
353
+ * existing entry offers all options, not just itself. */
354
+ export function filterSuggestions(options: PanelCompletionItem[], raw: string, cursor?: number, emptyQuery = false): PanelCompletionItem[] {
355
+ const { suffix } = splitSegments(raw, cursor);
356
+ const q = emptyQuery ? "" : suffix.trim().toLowerCase();
357
+ if (!q) return options;
358
+ return options.filter((o) => o.value.toLowerCase().includes(q) || (o.label ?? o.value).toLowerCase().includes(q));
359
+ }
360
+
361
+ /** Searchable text for a row: label, key, rendered value, description,
362
+ * warning, and enum values (OMP's getSettingItemFilterText). */
363
+ export function filterText(r: PanelRow): string {
364
+ const value = r.mask && String(r.value ?? "") !== "" ? "" : String(r.value ?? "");
365
+ return [r.label, r.key, value, r.description ?? "", r.warning ?? "", ...(r.values ?? [])].join(" ");
366
+ }
367
+
368
+ /** Value produced by accepting `item.value` while editing `raw`: replaces the
369
+ * segment at the cursor (last segment when no cursor given) — `head + ", " +
370
+ * value` + untouched tail segments. No trailing comma is added after the
371
+ * replaced segment; typing `,` after a pick starts the next segment. */
372
+ export function joinCompletion(raw: string, itemValue: string, cursor?: number): string {
373
+ const { head } = splitSegments(raw, cursor);
374
+ // Preserve any segments after the cursor's segment (a first-segment pick
375
+ // has an empty head but still a tail — early-return would drop it).
376
+ const after = cursor === undefined || cursor >= raw.length
377
+ ? ""
378
+ : (() => {
379
+ let end = raw.indexOf(",", cursor);
380
+ if (end === -1) end = raw.length;
381
+ return raw.slice(end); // ", seg2, seg3" or ""
382
+ })();
383
+ if (!head) return `${itemValue}${after}`;
384
+ return `${head}, ${itemValue}${after}`;
385
+ }
386
+
387
+ /** Extract the printable text of a keypress (single printable grapheme), or
388
+ * undefined for control sequences. Used by type-to-search. */
389
+ export function printableText(data: string): string | undefined {
390
+ if (data.length === 0) return undefined;
391
+ // Control chars, escape sequences, and bare/paired control codes → no text.
392
+ if (data.length === 1 && data.charCodeAt(0) < 0x20) return undefined;
393
+ if (data.charCodeAt(0) === 0x7f) return undefined;
394
+ if (data.startsWith("\u001b")) return undefined;
395
+ return data;
396
+ }
397
+
398
+ // ---------------------------------------------------------------------------
399
+
400
+ interface PanelTheme {
401
+ fg(color: string, text: string): string;
402
+ bg?(color: string, text: string): string;
403
+ bold?(text: string): string;
404
+ underline?(text: string): string;
405
+ }
406
+
407
+ /** Fixed description-area height (blank + this many text rows), so moving
408
+ * between rows with/without descriptions never shifts the layout (OMP). */
409
+ const DESC_ROWS = 3;
410
+
411
+ /** Frame chrome rows (fixed): top border, tab row, divider, blank + DESC_ROWS
412
+ * description area, divider, footer hint, bottom border — 7 + DESC_ROWS. The
413
+ * body (heading + rows window) gets whatever height remains — OMP's
414
+ * fullscreen shape. */
415
+ const FRAME_ROWS = 7 + DESC_ROWS;
416
+
417
+ /** Max label column width before the value column starts (OMP's metric). */
418
+ const MAX_LABEL_WIDTH = 30;
419
+
420
+ /** Max inline suggestions shown while editing a completion row. */
421
+ const MAX_SUGGESTIONS = 8;
422
+
423
+ export class ConfigPanelModel implements Component {
424
+ onRequestRender: (() => void) | null = null;
425
+ onChanged: (() => void) | null = null;
426
+ onSave: (() => void) | null = null;
427
+ onAction: ((row: PanelRow) => Promise<void>) | null = null;
428
+ onClose: (() => void) | null = null;
429
+ keybindings: KeybindingsManager | null = null;
430
+ /** Terminal height source for the full-viewport frame; tests inject a
431
+ * constant (default: the real terminal, 40 when unknown). */
432
+ getHeight: () => number = () => process.stdout.rows || 40;
433
+
434
+ dirty = false;
435
+ /** Keys of rows the user actually edited (for secret-persistence decisions). */
436
+ editedKeys = new Set<string>();
437
+ /** Current groups (exposed for tests/rebuild inspection). */
438
+ get groups(): PanelGroup[] {
439
+ return this._groups;
440
+ }
441
+ private _groups: PanelGroup[];
442
+ /** pi's theme object is a Proxy over a globalThis slot (theme.js) — every
443
+ * property access reads the CURRENT theme, so a live preview restyles the
444
+ * panel chrome too without any refresh hook. */
445
+ private theme: PanelTheme | null;
446
+ private title: string;
447
+ private flat: PanelRow[] = [];
448
+ private selected = 0;
449
+ private editing: PanelRow | null = null;
450
+ private input: Input | null = null;
451
+ /** Live suggestion list while editing a row that has completions. */
452
+ private suggestions: PanelCompletionItem[] = [];
453
+ private lastFilteredValue: string | null = null;
454
+ private suggestionIdx = 0;
455
+ private pendingPrompt: { label: string; onDone: (value: string | undefined) => void } | null = null;
456
+ /** Selection submenu (Enter on a `values`/`menu` row): OMP's select
457
+ * submenu — browse options with live preview, Enter commits, Esc backs
458
+ * out. `view` is the query-filtered slice the cursor navigates. */
459
+ private menuItem: {
460
+ row: PanelRow;
461
+ options: PanelMenuOption[];
462
+ view: PanelMenuOption[];
463
+ idx: number;
464
+ query: string;
465
+ } | null = null;
466
+ /** Type-to-filter query. Filtering swaps the rows pane to a flat match list
467
+ * (no sidebar) while the selection moves over matches only. */
468
+ filter = "";
469
+ /** Visible row indices (all rows, or filtered matches) — the selection
470
+ * navigates THIS list, so filtering can't select a hidden row. */
471
+ private visible: number[] = [];
472
+ /** Active tab index (tab = group; only the active group's rows render).
473
+ * Selection is remembered per tab so switching back lands where you left. */
474
+ private tab = 0;
475
+ private tabSelection: number[] = [];
476
+ private _focused = false;
477
+
478
+ /** Active tab index (tests). */
479
+ get activeTab(): number {
480
+ return this.tab;
481
+ }
482
+
483
+ /** Tab index containing the selected row (tests — the invariant the sidebar
484
+ * and tab bar highlight both derive from). */
485
+ get tabOfSelection(): number {
486
+ return this.tabOf(this.selected);
487
+ }
488
+
489
+ /** Absolute row indices currently visible/navigable (tests). */
490
+ get visibleRows(): number[] {
491
+ return [...this.visible];
492
+ }
493
+
494
+ constructor(groups: PanelGroup[], theme: PanelTheme | null, title = "Configuration") {
495
+ this._groups = groups;
496
+ this.theme = theme;
497
+ this.title = title;
498
+ this.rebuildFlat();
499
+ }
500
+
501
+ // Focusable interface (TUI checks `"focused" in component`).
502
+ get focused(): boolean {
503
+ return this._focused;
504
+ }
505
+
506
+ /** Selected row's absolute index (tests + save routing inspection). */
507
+ get selectedIndex(): number {
508
+ return this.selected;
509
+ }
510
+
511
+ set focused(v: boolean) {
512
+ this._focused = v;
513
+ if (this.input) this.input.focused = v;
514
+ }
515
+
516
+ private rebuildFlat(): void {
517
+ this.flat = this.groups.flatMap((g) => g.rows);
518
+ this.recomputeVisible();
519
+ }
520
+
521
+ /** Tab model: adjacent groups sharing a `tab` key form one tab. Each tab is
522
+ * `{ tabKey, label, icon, groups: [group indices] }`; a group without
523
+ * `tab` is its own tab (`tabKey` = its group key, so a coinccidental label
524
+ * match can never merge unrelated groups). Computed per call — group lists
525
+ * are tiny. */
526
+ private tabs(): { tabKey: string; label: string; icon?: string; groups: number[] }[] {
527
+ const out: { tabKey: string; label: string; icon?: string; groups: number[] }[] = [];
528
+ for (let i = 0; i < this.groups.length; i++) {
529
+ const g = this.groups[i]!;
530
+ const key = g.tab ?? `$${i}`; // $-prefixed: group keys can never collide with it
531
+ if (g.tab !== undefined && out.length > 0 && out[out.length - 1]!.tabKey === key) {
532
+ out[out.length - 1]!.groups.push(i);
533
+ if (!out[out.length - 1]!.icon && g.icon) out[out.length - 1]!.icon = g.icon;
534
+ continue;
535
+ }
536
+ out.push({ tabKey: key, label: g.tab ?? g.label, ...(g.icon ? { icon: g.icon } : {}), groups: [i] });
537
+ }
538
+ return out;
539
+ }
540
+
541
+ /** Rows of a tab: every row of every group belonging to it. */
542
+ private tabRows(t: number): number[] {
543
+ const tabs = this.tabs();
544
+ const tab = tabs[t];
545
+ if (!tab) return [];
546
+ const out: number[] = [];
547
+ for (const gi of tab.groups) {
548
+ const start = this.groupStart(gi);
549
+ const count = this.groups[gi]?.rows.length ?? 0;
550
+ for (let j = 0; j < count; j++) out.push(start + j);
551
+ }
552
+ return out;
553
+ }
554
+
555
+ /** First row index of a tab (0 when the tab has no rows). */
556
+ private tabStart(t: number): number {
557
+ const tabs = this.tabs();
558
+ return tabs[t]?.groups.length ? this.groupStart(tabs[t]!.groups[0]!) : 0;
559
+ }
560
+
561
+ /** Absolute row index of a group's first row (0 when missing). */
562
+ private groupStart(g: number): number {
563
+ let acc = 0;
564
+ for (let i = 0; i < g && i < this.groups.length; i++) acc += this.groups[i]!.rows.length;
565
+ return acc;
566
+ }
567
+
568
+ /** Tab index containing a flat row index (0 when none). */
569
+ private tabOf(index: number): number {
570
+ const tabs = this.tabs();
571
+ for (let t = 0; t < tabs.length; t++) {
572
+ const rows = this.tabRows(t);
573
+ if (rows.length > 0 && index >= rows[0]! && index <= rows[rows.length - 1]!) return t;
574
+ }
575
+ return 0;
576
+ }
577
+
578
+ /** Group index whose rows contain a flat row index (-1 when none). */
579
+ private sectionOf(index: number): number {
580
+ for (let gi = 0; gi < this.groups.length; gi++) {
581
+ const start = this.groupStart(gi);
582
+ const count = this.groups[gi]?.rows.length ?? 0;
583
+ if (count > 0 && index >= start && index < start + count) return gi;
584
+ }
585
+ return -1;
586
+ }
587
+
588
+ /** Switch to tab `t`, remembering the selection of the tab being left and
589
+ * restoring the target tab's own via recomputeVisible (which honors
590
+ * `tabSelection` in unfiltered mode). Wraps like OMP's TabBar. */
591
+ private setTab(t: number): void {
592
+ const tabs = this.tabs();
593
+ if (tabs.length === 0) return;
594
+ const next = ((t % tabs.length) + tabs.length) % tabs.length;
595
+ if (next === this.tab) return;
596
+ // Remember where we were in the tab we're leaving.
597
+ this.tabSelection[this.tab] = this.selected;
598
+ this.tab = next;
599
+ this.recomputeVisible();
600
+ this.requestRender();
601
+ }
602
+
603
+ /** Tab-step key: switches tabs (wrapping); during a search (matches span
604
+ * every category) it jumps the selection to the next/previous category
605
+ * that HAS a match — OMP's "tabs act as jump targets" behavior. */
606
+ private stepTab(delta: number): void {
607
+ const tabs = this.tabs();
608
+ if (tabs.length === 0) return;
609
+ if (this.filter) {
610
+ const tabsInView = [...new Set(this.visible.map((i) => this.tabOf(i)))].sort((a, b) => a - b);
611
+ if (tabsInView.length === 0) return;
612
+ const cur = this.tabOf(this.selected);
613
+ const at = tabsInView.indexOf(cur);
614
+ const target = at === -1
615
+ ? (delta > 0 ? tabsInView[0]! : tabsInView[tabsInView.length - 1]!)
616
+ : tabsInView[((at + delta) % tabsInView.length + tabsInView.length) % tabsInView.length]!;
617
+ const landed = this.visible.find((i) => this.tabOf(i) === target);
618
+ if (landed !== undefined) this.selected = landed;
619
+ this.requestRender();
620
+ return;
621
+ }
622
+ this.setTab(this.tab + delta);
623
+ }
624
+
625
+ /** Jump to the next/previous SECTION (group) inside the active tab — OMP's
626
+ * section jump: selection lands on the section's first visible row. Tabs
627
+ * with one section fall back to paging through rows. */
628
+ private jumpSection(delta: number): void {
629
+ const tabs = this.tabs();
630
+ const tab = tabs[this.tab];
631
+ if (!tab) return;
632
+ if (tab.groups.length < 2) {
633
+ // No sections: page through the tab's rows (OMP's fallback).
634
+ const rows = this.tabRows(this.tab);
635
+ const pos = rows.indexOf(this.selected);
636
+ const at = pos === -1 ? 0 : Math.max(0, Math.min(rows.length - 1, pos + delta * this.bodyRows()));
637
+ if (rows.length > 0) this.selected = rows[at]!;
638
+ this.requestRender();
639
+ return;
640
+ }
641
+ // Which section holds the selection?
642
+ let cur = 0;
643
+ for (let s = 0; s < tab.groups.length; s++) {
644
+ const gi = tab.groups[s]!;
645
+ if (this.selected >= this.groupStart(gi)) cur = s;
646
+ }
647
+ const nextSection = ((cur + delta) % tab.groups.length + tab.groups.length) % tab.groups.length;
648
+ const start = this.groupStart(tab.groups[nextSection]!);
649
+ const count = this.groups[tab.groups[nextSection]!]?.rows.length ?? 0;
650
+ if (count > 0) this.selected = start;
651
+ this.requestRender();
652
+ }
653
+
654
+ /** Recompute the navigable row list. Without a filter the list is the
655
+ * ACTIVE TAB's rows (tabs separate categories — ↑/↓ must not wander into a
656
+ * hidden tab); with one, rows from every tab fuzzy-match on
657
+ * label/value/description and the previously selected row is kept when it
658
+ * survives, else the first match wins. */
659
+ private recomputeVisible(): void {
660
+ const q = this.filter.trim();
661
+ if (!q) {
662
+ const rows = this.tabRows(this.tab);
663
+ this.visible = rows;
664
+ if (rows.length > 0 && !rows.includes(this.selected)) {
665
+ // Prefer this tab's remembered row (tab switch); fall back to its first.
666
+ const remembered = this.tabSelection[this.tab];
667
+ this.selected = remembered !== undefined && rows.includes(remembered)
668
+ ? remembered
669
+ : rows[0]!;
670
+ }
671
+ return;
672
+ }
673
+ const prevRow = this.flat[this.selected];
674
+ this.visible = this.flat
675
+ .map((r, i) => ({ r, i }))
676
+ .filter(({ r }) => fuzzyFilter([r], q, filterText).length > 0)
677
+ .map(({ i }) => i);
678
+ if (this.visible.length === 0) {
679
+ this.selected = 0;
680
+ return;
681
+ }
682
+ const at = prevRow ? this.visible.indexOf(this.flat.indexOf(prevRow)) : -1;
683
+ this.selected = at >= 0 ? this.flat.indexOf(prevRow) : this.visible[0]!;
684
+ // While filtering, the active tab FOLLOWS the selection (OMP's "tabs act
685
+ // as jump targets"): the tab the matched row lives on is the one you are
686
+ // configuring, even before Esc clears the search.
687
+ this.tab = this.tabOf(this.selected);
688
+ }
689
+
690
+ /** Selected row's position within `visible`. */
691
+ private visiblePos(): number {
692
+ const at = this.visible.indexOf(this.selected);
693
+ return at >= 0 ? at : 0;
694
+ }
695
+
696
+ /** Set the type-to-search filter: swap the rows pane to a flat match list
697
+ * and pull the selection onto a surviving match. Clearing the filter snaps
698
+ * the tab to the row the user was on, so the panel resumes on that
699
+ * category instead of the one they started from. */
700
+ setFilter(q: string): void {
701
+ const cleared = this.filter !== "" && q === "";
702
+ // Capture the matched row + its tab BEFORE the filter clears: the
703
+ // unfiltered recompute below re-clamps `selected` back onto the OLD tab's
704
+ // rows, which would make any after-the-fact snap resolve to the old tab
705
+ // and silently no-op.
706
+ const matchRow = cleared && this.visible.length > 0 ? this.selected : undefined;
707
+ this.filter = q;
708
+ if (matchRow !== undefined) {
709
+ this.tab = this.tabOf(matchRow);
710
+ this.selected = matchRow;
711
+ this.tabSelection[this.tab] = matchRow;
712
+ }
713
+ this.recomputeVisible();
714
+ this.requestRender();
715
+ }
716
+
717
+ requestRender(): void {
718
+ this.onRequestRender?.();
719
+ }
720
+
721
+ /** SDK Component contract — external invalidation replays the flat model. */
722
+ invalidate(): void {
723
+ this.rebuildFlat();
724
+ this.onRequestRender?.();
725
+ }
726
+
727
+ /** Replace the row model (after an action mutated the config, e.g. added an
728
+ * entry) and rebuild the flat list, preserving the selected ROW by identity
729
+ * (indices shift when a group grows/shrinks). */
730
+ setGroups(groups: PanelGroup[]): void {
731
+ const prevRow = this.flat[this.selected];
732
+ this._groups = groups;
733
+ this.flat = this.groups.flatMap((g) => g.rows);
734
+ // The tab list is derived from groups — an action may have removed tabs,
735
+ // so re-clamp BEFORE any tab-indexed lookup (tabBarLine derefs it raw).
736
+ this.tab = Math.max(0, Math.min(this.tab, this.tabs().length - 1));
737
+ const at = prevRow ? this.flat.indexOf(prevRow) : -1;
738
+ this.selected = at >= 0 ? at : Math.max(0, Math.min(this.selected, this.flat.length - 1));
739
+ this.recomputeVisible();
740
+ }
741
+
742
+ private color(token: string, text: string): string {
743
+ return this.theme?.fg ? this.theme.fg(token, text) : text;
744
+ }
745
+
746
+ /** Footer key hints with colored key glyphs (OMP style): `[["←→","tab"],
747
+ * ["↑↓","navigate"]]` → `←→ tab · ↑↓ navigate ...` — keys in `accent`,
748
+ * their meaning in `dim`. */
749
+ private keyHint(pairs: [string, string][]): string {
750
+ const sep = this.color("dim", " · ");
751
+ return pairs
752
+ .map(([key, meaning]) => this.color("accent", key) + " " + this.color("dim", meaning))
753
+ .join(sep);
754
+ }
755
+
756
+ render(width: number): string[] {
757
+ const w = Math.max(20, width);
758
+ const flat = this.flat;
759
+ const contentRows = this.bodyRows();
760
+ // Fixed-chrome frame (OMP's fullscreen settings shape): boxed title
761
+ // border → tab row → divider → body → description → divider → pinned
762
+ // key-hint footer → boxed bottom border. Every row is wrapped in box
763
+ // sides (OMP's row()) so the frame is a closed rectangle. Exactly
764
+ // max(14, getHeight()) lines.
765
+ const lines: string[] = [this.boxTop(w)];
766
+
767
+ // Tab row — always exactly one line: the search banner while filtering
768
+ // (search spans every tab), else the tab bar; single-tab panels leave it
769
+ // blank so the geometry never shifts.
770
+ if (this.filter) {
771
+ const q = this.color("accent", "▸ ") + this.filter + this.color("accent", "█");
772
+ const count = this.visible.length === 1 ? "1 match" : `${this.visible.length} matches`;
773
+ const right = this.color(this.visible.length > 0 ? "dim" : "warning", count);
774
+ const gap = Math.max(1, w - 4 - visibleWidth(q) - visibleWidth(right) - 1);
775
+ lines.push(this.boxRow(q + " ".repeat(gap) + right, w));
776
+ } else {
777
+ lines.push(this.boxRow(this.tabBarLine(w - 4) ?? "", w));
778
+ }
779
+ lines.push(this.boxDivider(w));
780
+
781
+ // Body — rows pane (+ sidebar), empty-state note, or the inline action
782
+ // prompt — padded/truncated to contentRows below so the body absorbs the
783
+ // terminal height instead of the frame floating after the content.
784
+ // Inner width: box sides + their single-column insets (OMP's row()).
785
+ const iw = Math.max(1, w - 4);
786
+ const body: string[] = [];
787
+ if (this.pendingPrompt) {
788
+ const inputLines = this.input ? this.input.render(iw - 2) : ["…"];
789
+ body.push(this.color("text", `${this.pendingPrompt.label}: ${inputLines[0] ?? ""}`));
790
+ }
791
+
792
+ // Description area shows the selected row ONLY when that row belongs to
793
+ // the active tab (an empty/shrunk tab must not describe a hidden
794
+ // neighbor's row). During a filter the search spans every tab.
795
+ const visibleRow = this.filter
796
+ ? this.visible.includes(this.selected)
797
+ : this.tabRows(this.tab).includes(this.selected);
798
+ const selectedRow = visibleRow ? flat[this.selected] : undefined;
799
+
800
+ // Empty filter result: keep the fixed chrome, say so in the pane. (The
801
+ // prompt arm stays empty — its body line is already pushed above.)
802
+ if (this.pendingPrompt) {
803
+ // nothing else renders behind the prompt
804
+ } else if (this.menuItem) {
805
+ this.renderMenu(body, iw, contentRows);
806
+ } else if (this.visible.length === 0) {
807
+ if (this.filter) {
808
+ body.push(this.color("dim", " No matching rows"));
809
+ body.push(this.color("dim", " ⌫ edit search · Esc clear"));
810
+ } else {
811
+ body.push(this.color("dim", " (no settings in this tab)"));
812
+ }
813
+ } else {
814
+ // Render-list. Filtering: a flat match list across every tab (OMP skips
815
+ // headings in search). Otherwise: the active tab's rows with a heading
816
+ // line per SECTION and, when the width allows, a left sidebar — OMP
817
+ // renders BOTH the sidebar and the in-pane underlined headings.
818
+ const items: ({ row: number } | { heading: string; section: number })[] = [];
819
+ const tabs = this.tabs();
820
+ const tab = tabs[this.tab];
821
+ const sections = tab ? tab.groups : [];
822
+ if (this.filter) {
823
+ for (const rowIdx of this.visible) items.push({ row: rowIdx });
824
+ } else {
825
+ // In-pane section headings lead every section (OMP always renders
826
+ // them, sidebar or not; they dim outside the active section).
827
+ for (const gi of sections) {
828
+ const start = this.groupStart(gi);
829
+ const count = this.groups[gi]?.rows.length ?? 0;
830
+ if (count === 0) continue;
831
+ items.push({ heading: this.groups[gi]!.label, section: gi });
832
+ for (let j = 0; j < count; j++) items.push({ row: start + j });
833
+ }
834
+ }
835
+ const selLine = items.findIndex((it) => "row" in it && it.row === this.selected);
836
+
837
+ // Sidebar (sections): pinned width across every tab (OMP), shown on
838
+ // ANY tab with sections when the rows pane stays readable — OMP hides
839
+ // it below a 60-column pane and falls back to headings only.
840
+ const sidebarWidth = this.sidebarCols();
841
+ const sidebarPanes = !this.filter && sections.length >= 1 && iw - sidebarWidth - 2 >= 60;
842
+ // Window: keep the selected line in view, roughly centered (OMP).
843
+ const budget = Math.max(1, contentRows);
844
+ const total = items.length;
845
+ const viewport = Math.min(budget, total);
846
+ const start = Math.max(0, Math.min(selLine - Math.floor(viewport / 2), total - viewport));
847
+ const windowItems = items.slice(start, start + viewport);
848
+ const useScrollbar = total > viewport;
849
+ const rowWidth = iw - (useScrollbar ? 1 : 0) - (sidebarPanes ? sidebarWidth + 2 : 0);
850
+
851
+ // Label column spans the WINDOW so it stays stable while scrolling.
852
+ const labelWidths = windowItems
853
+ .filter((it): it is { row: number } => "row" in it)
854
+ .map((it) => visibleWidth(flat[it.row]!.label) + (flat[it.row]!.warning ? 2 : 0));
855
+ const labelWidth = Math.min(MAX_LABEL_WIDTH, labelWidths.length ? Math.max(...labelWidths) : 0);
856
+ const scrollbar = useScrollbar ? this.scrollbarColumn(start, viewport, total) : [];
857
+
858
+ // Sidebar (OMP's split layout): section names STACKED at the top of the
859
+ // left column — sidebar line i sits beside pane line i — with the
860
+ // section holding the cursor accented, the rest dim. Not aligned to
861
+ // each section's pane position (OMP's exact model).
862
+ let activeSection = sections[0];
863
+ for (const gi of sections) if (this.selected >= this.groupStart(gi)) activeSection = gi;
864
+ const sidebarLines: string[] = [];
865
+ if (sidebarPanes) {
866
+ for (const gi of sections) {
867
+ const label = truncateToWidth(this.groups[gi]!.label, Math.max(1, sidebarWidth - 4));
868
+ const styled = gi === activeSection
869
+ ? this.color("accent", this.theme?.bold ? this.theme.bold(label) : label)
870
+ : this.color("dim", label);
871
+ sidebarLines.push(" " + styled + " ".repeat(Math.max(0, sidebarWidth - 2 - visibleWidth(label))));
872
+ }
873
+ }
874
+
875
+ for (let i = 0; i < windowItems.length; i++) {
876
+ const it = windowItems[i]!;
877
+ // In-pane section heading (OMP's underlined heading rows): dimmed
878
+ // outside the active section, muted+bold+underline on it. Rendered
879
+ // with the same sidebar prefix so the columns stay aligned.
880
+ if ("heading" in it) {
881
+ const active = it.section === activeSection;
882
+ const text = it.heading;
883
+ const styled = active
884
+ ? this.color("muted", this.theme?.bold ? this.theme.bold(text) : text)
885
+ : this.color("dim", text);
886
+ const underlined = this.theme?.underline ? this.theme.underline(styled) : styled;
887
+ const prefix = sidebarPanes
888
+ ? (sidebarLines[i] ?? " ".repeat(sidebarWidth)) + this.color("border", "│ ")
889
+ : "";
890
+ // Pad the heading to the row width so the scrollbar column stays
891
+ // pinned (an unpadded heading let the glyph drift into the text).
892
+ body.push(truncateToWidth(prefix + truncateToWidth(underlined, rowWidth, "...", true) + (scrollbar[i] ?? (useScrollbar ? " " : "")), iw));
893
+ continue;
894
+ }
895
+ const r = flat[it.row]!;
896
+ const selected = it.row === this.selected;
897
+ // OMP's dim wash: with a sidebar, rows OUTSIDE the active section are
898
+ // dimmed so the section under the cursor pops.
899
+ const dimmed = sidebarPanes && !selected && this.sectionOf(it.row) !== activeSection;
900
+ const pane = this.renderRow(r, selected, dimmed, labelWidth, rowWidth);
901
+ const prefix = sidebarPanes
902
+ ? (sidebarLines[i] ?? " ".repeat(sidebarWidth)) + this.color("border", "│ ")
903
+ : "";
904
+ for (let k = 0; k < pane.length; k++) {
905
+ body.push(truncateToWidth(prefix + (pane[k] ?? "") + (scrollbar[i] ?? (useScrollbar ? " " : "")), iw));
906
+ }
907
+ }
908
+ }
909
+
910
+ // Preview block (OMP's settings-screen preview window): a read-only
911
+ // render under the rows pane or the open submenu — the selected row's
912
+ // (menu: highlighted option's) previewLines, clamped into the remaining
913
+ // body budget. No key handling; the pad below still fills the frame.
914
+ const pvRow = this.menuItem?.row ?? selectedRow;
915
+ const pvValue = this.menuItem
916
+ ? String(this.menuItem.view[this.menuItem.idx]?.value ?? pvRow?.value ?? "")
917
+ : String(pvRow?.value ?? "");
918
+ const pvLines = pvRow?.previewLines ? pvRow.previewLines(pvValue, iw) : [];
919
+ if (pvLines.length > 0 && contentRows - body.length > 2) {
920
+ body.push("");
921
+ body.push(this.color("dim", "Preview:"));
922
+ for (const line of pvLines) {
923
+ if (body.length >= contentRows) break;
924
+ body.push(truncateToWidth(line, iw));
925
+ }
926
+ }
927
+
928
+ while (body.length < contentRows) body.push("");
929
+ for (const line of body.slice(0, contentRows)) lines.push(this.boxRow(line, w));
930
+
931
+ // Fixed-height description area: warning first (survives the clamp), then
932
+ // description; exactly DESC_ROWS lines so navigation never shifts layout.
933
+ lines.push(this.boxRow("", w));
934
+ const descLines: string[] = [];
935
+ if (selectedRow) {
936
+ if (selectedRow.warning) {
937
+ const mark = this.color("warning", "⚠ ");
938
+ for (const l of wrapTextWithAnsi(selectedRow.warning, Math.max(10, iw - 2))) {
939
+ descLines.push(" " + mark + this.color("warning", l));
940
+ }
941
+ }
942
+ if (selectedRow.description) {
943
+ for (const l of wrapTextWithAnsi(selectedRow.description, Math.max(10, iw - 2))) {
944
+ descLines.push(" " + this.color("dim", l));
945
+ }
946
+ }
947
+ }
948
+ if (descLines.length > DESC_ROWS) {
949
+ descLines.length = DESC_ROWS;
950
+ descLines[DESC_ROWS - 1] = truncateToWidth(descLines[DESC_ROWS - 1]!, Math.max(0, iw - 1)) + "…";
951
+ }
952
+ while (descLines.length < DESC_ROWS) descLines.push("");
953
+ for (const l of descLines) lines.push(this.boxRow(l, w));
954
+
955
+ lines.push(this.boxDivider(w));
956
+ lines.push(this.boxRow(this.footerLine(iw), w));
957
+ lines.push(this.boxBottom(w));
958
+ // Truncate every line to the panel width — the TUI throws when a custom
959
+ // component renders a line wider than the terminal (long URLs etc.).
960
+ return lines.map((l) => truncateToWidth(l, w));
961
+ }
962
+
963
+ /** Body (heading + rows window) height available inside the frame. */
964
+ private bodyRows(): number {
965
+ return Math.max(1, Math.max(14, this.getHeight()) - FRAME_ROWS);
966
+ }
967
+
968
+ /** Rounded top border with the title inset: `╭─ Title ─────╮` (OMP's
969
+ * overlay-box). */
970
+ private boxTop(w: number): string {
971
+ const bold = this.theme?.bold ? this.theme.bold.bind(this.theme) : (t: string) => t;
972
+ const title = this.color("accent", ` ${bold(this.title)} `);
973
+ const fill = Math.max(0, w - 3 - visibleWidth(title));
974
+ return this.color("border", "╭─") + title + this.color("border", "─".repeat(fill) + "╮");
975
+ }
976
+
977
+ /** Tee-jointed section divider: `├────────┤` (OMP). */
978
+ private boxDivider(w: number): string {
979
+ return this.color("border", "├" + "─".repeat(Math.max(0, w - 2)) + "┤");
980
+ }
981
+
982
+ /** Selection submenu body (OMP's select submenu): the row's own label as a
983
+ * heading, its per-option details, the current value marked, the cursor on
984
+ * the highlighted option, and the type-to-filter line. The row stays
985
+ * `selected` so the fixed description area below keeps rendering its
986
+ * description/warning — OMP keeps the setting context visible while its
987
+ * submenu is open. */
988
+ private renderMenu(body: string[], iw: number, contentRows: number): void {
989
+ const m = this.menuItem;
990
+ if (!m) return;
991
+ // Heading: the row label, bold + accent (OMP's FormField label).
992
+ const heading = this.theme?.bold ? this.theme.bold(m.row.label) : m.row.label;
993
+ body.push(this.color("accent", " " + heading));
994
+ body.push("");
995
+
996
+ // Window: cursor roughly centered, same shape as the rows pane.
997
+ const budget = Math.max(1, contentRows - 3); // heading + blank + filter line
998
+ const total = m.view.length;
999
+ const viewport = Math.min(budget, total);
1000
+ const start = Math.max(0, Math.min(m.idx - Math.floor(viewport / 2), total - viewport));
1001
+ const windowItems = m.view.slice(start, start + viewport);
1002
+ const useScrollbar = total > viewport;
1003
+ const scrollbar = useScrollbar ? this.scrollbarColumn(start, viewport, total) : [];
1004
+ const cursor = String(m.row.value ?? "");
1005
+
1006
+ for (let i = 0; i < windowItems.length; i++) {
1007
+ const o = windowItems[i]!;
1008
+ const highlighted = start + i === m.idx;
1009
+ const label = o.label ?? o.value;
1010
+ const isCurrent = o.value === cursor;
1011
+ const desc = o.description ? this.color("dim", ` — ${o.description}`) : "";
1012
+ const current = isCurrent ? this.color("dim", " (current)") : "";
1013
+ const line = `${highlighted ? this.color("accent", "›") : " "} ${highlighted ? this.color("text", label) : this.color("muted", label)}${desc}${current}`;
1014
+ body.push(truncateToWidth(line + (scrollbar[i] ?? (useScrollbar ? " " : "")), iw - 2));
1015
+ }
1016
+
1017
+ // Type-to-filter line (OMP's "Type to search"): query with cursor, right-
1018
+ // aligned match count; the plain hint when nothing is typed.
1019
+ const searching = m.query !== "";
1020
+ const q = this.color("accent", "▸ ") + m.query + this.color("accent", "█");
1021
+ const count = m.view.length === 1 ? "1 match" : `${m.view.length} matches`;
1022
+ const right = this.color(m.view.length > 0 ? "dim" : "warning", count);
1023
+ if (searching) {
1024
+ const gap = Math.max(1, iw - 2 - visibleWidth(q) - visibleWidth(right) - 1);
1025
+ body.push(truncateToWidth(q + " ".repeat(gap) + right, iw - 2));
1026
+ } else if (m.view.length === 0) {
1027
+ body.push(this.color("dim", " No matching options"));
1028
+ } else {
1029
+ body.push(this.color("dim", " Type to search"));
1030
+ }
1031
+ }
1032
+
1033
+ /** Rounded bottom border: `╰────────╯` (OMP). */
1034
+ private boxBottom(w: number): string {
1035
+ return this.color("border", "╰" + "─".repeat(Math.max(0, w - 2)) + "╯");
1036
+ }
1037
+
1038
+ /** One boxed content row: `│ content │`, single-column insets (OMP's row()). */
1039
+ private boxRow(content: string, w: number): string {
1040
+ const inner = Math.max(0, w - 4);
1041
+ const fill = inner - visibleWidth(content);
1042
+ const body = fill > 0 ? content + " ".repeat(fill) : truncateToWidth(content, inner);
1043
+ return this.color("border", "│") + " " + body + " " + this.color("border", "│");
1044
+ }
1045
+
1046
+ /** Sidebar column width pinned across EVERY tab from all section labels
1047
+ * (OMP's settingsSidebarWidth — the divider never jumps between tabs):
1048
+ * min(22, longest label) + 4 for the 2-column indent and 2-column gap. */
1049
+ private sidebarCols(): number {
1050
+ let max = 0;
1051
+ for (const g of this.groups) max = Math.max(max, visibleWidth(g.label));
1052
+ return Math.min(22, max) + 4;
1053
+ }
1054
+
1055
+ /** Pinned footer — the frame's last content row (OMP's hint bar): the
1056
+ * mode's key hints left, the dirty marker right. */
1057
+ private footerLine(w: number): string {
1058
+ const hint = this.footerHint();
1059
+ const dirty = this.dirty ? this.color("warning", "● unsaved changes") : "";
1060
+ const gap = w - visibleWidth(hint) - visibleWidth(dirty);
1061
+ if (!dirty) return truncateToWidth(hint, w);
1062
+ // Both can't fit: the unsaved marker is the more urgent signal (Esc saves).
1063
+ if (gap < 2) return truncateToWidth(dirty, w);
1064
+ return truncateToWidth(hint + " ".repeat(gap) + dirty, w);
1065
+ }
1066
+
1067
+ /** Footer hint text per mode (the former in-body hint row, now pinned).
1068
+ * The browse hint derives from the ACTIVE tab's row kinds (OMP's footer
1069
+ * does the same: its plugins tab shows different guidance than the
1070
+ * setting tabs): a tab of toggles/enums says "toggle", a read-only tab
1071
+ * drops the Enter pair, and a single-section tab drops the section jump. */
1072
+ private footerHint(): string {
1073
+ if (this.pendingPrompt) {
1074
+ return this.keyHint([["Enter", "confirm"], ["Esc", "cancel"]]);
1075
+ }
1076
+ if (this.menuItem) {
1077
+ return this.keyHint([["Enter", "select"], ["↑↓", "navigate"], ["type", "to search"], ["Esc", "back"]]);
1078
+ }
1079
+ if (this.filter) {
1080
+ return this.keyHint([["↑↓", "navigate"], ["←→", "jump category"], ["Enter", "change"], ["⌫", "edit"], ["Esc", "clear"]]);
1081
+ }
1082
+ if (this.editing?.completions) {
1083
+ return this.keyHint([["↑↓", "highlight"], ["Tab", "pick"], ["Enter", "keep typed"], ["Esc", "close"]]);
1084
+ }
1085
+ const rows = this.tabRows(this.tab).map((i) => this.flat[i]!);
1086
+ const actionable = rows.filter((r) => r.kind !== "info");
1087
+ if (actionable.length > 0) {
1088
+ const onlyToggles = actionable.every((r) => r.kind === "toggle");
1089
+ // Predicate only (never invoke menu() here — this runs every render and
1090
+ // providers build model/theme lists).
1091
+ const onlyChoices = actionable.every((r) => r.kind === "toggle" || !!r.menu || (r.values?.length ?? 0) > 0);
1092
+ const hint: [string, string][] = [["←→", "tab"], ["↑↓", "navigate"]];
1093
+ if (this.sectionCount() >= 2) hint.push(["⇞⇟", "section"]);
1094
+ hint.push(["Enter", onlyToggles ? "toggle" : onlyChoices ? "choose" : "change"]);
1095
+ hint.push(["type", "to search"], ["Esc", "save"]);
1096
+ return this.keyHint(hint);
1097
+ }
1098
+ const hint: [string, string][] = [["←→", "tab"], ["↑↓", "navigate"]];
1099
+ if (this.sectionCount() >= 2) hint.push(["⇞⇟", "section"]);
1100
+ hint.push(["type", "to search"], ["Esc", "save"]);
1101
+ return this.keyHint(hint);
1102
+ }
1103
+
1104
+ /** Sections (groups) of the active tab — 0 when the tab is unknown. */
1105
+ private sectionCount(): number {
1106
+ const tab = this.tabs()[this.tab];
1107
+ return tab ? tab.groups.length : 0;
1108
+ }
1109
+
1110
+ /** Scrollbar column for the window: track + proportional thumb. */
1111
+ private scrollbarColumn(start: number, viewport: number, total: number): string[] {
1112
+ const thumbSize = Math.max(1, Math.round((viewport * viewport) / total));
1113
+ const maxStart = Math.max(1, total - viewport);
1114
+ const thumbTop = Math.round((start / maxStart) * Math.max(0, viewport - thumbSize));
1115
+ const out: string[] = [];
1116
+ for (let i = 0; i < viewport; i++) {
1117
+ const thumb = i >= thumbTop && i < thumbTop + thumbSize;
1118
+ out.push(this.color(thumb ? "accent" : "dim", thumb ? "█" : "│"));
1119
+ }
1120
+ return out;
1121
+ }
1122
+
1123
+ /** One-line tab bar with per-tab icons (OMP look): the ACTIVE tab renders
1124
+ * as inverse/`selectedBg` ` icon Label `; inactive tabs show their icon (or
1125
+ * a dim label) — full label while it fits, compact icon-only otherwise. On
1126
+ * the way down the bar collapses the inactive tabs FARTHEST from the
1127
+ * active one first (OMP's TabBar); the active tab keeps its full label.
1128
+ * If it still overflows (tabs without icons), the window slides around the
1129
+ * active tab with `…` marking clipped sides. Returns null when there is
1130
+ * only ONE tab (nothing to switch). */
1131
+ private tabBarLine(width: number): string | null {
1132
+ const tabs = this.tabs();
1133
+ if (tabs.length < 2) return null;
1134
+ const textWidth = (t: (typeof tabs)[number]) => visibleWidth(` ${t.icon ? t.icon + " " : ""}${t.label} `);
1135
+ const iconWidth = (t: (typeof tabs)[number]) => visibleWidth(t.icon ? ` ${t.icon} ` : ` ${truncateToWidth(t.label, 3)} `);
1136
+ // Per-tab compaction: collapse inactive tabs farthest from the active one
1137
+ // until the bar fits one line; the active tab never compacts.
1138
+ const compact = tabs.map(() => false);
1139
+ const widthOf = (i: number) => (compact[i] ? iconWidth(tabs[i]!) : textWidth(tabs[i]!)) + 1; // + gap
1140
+ const totalWidth = () => tabs.reduce((sum, _, i) => sum + widthOf(i), 0) - 1;
1141
+ const order = tabs
1142
+ .map((_, i) => i)
1143
+ .filter((i) => i !== this.tab)
1144
+ .sort((a, b) => Math.abs(b - this.tab) - Math.abs(a - this.tab));
1145
+ for (const i of order) {
1146
+ if (totalWidth() <= width) break;
1147
+ compact[i] = true;
1148
+ }
1149
+
1150
+ // Still too wide: slide a window around the ACTIVE tab (left first —
1151
+ // reading order — then right), `…` marking clipped sides.
1152
+ let from = 0;
1153
+ let to = tabs.length - 1;
1154
+ if (totalWidth() > width) {
1155
+ from = this.tab;
1156
+ to = this.tab;
1157
+ let used = widthOf(this.tab) - 1; // no trailing gap yet
1158
+ for (;;) {
1159
+ const canLeft = from > 0 && used + widthOf(from - 1) + (to < tabs.length - 1 ? 2 : 0) <= width;
1160
+ if (canLeft) { from--; used += widthOf(from); continue; }
1161
+ const canRight = to < tabs.length - 1 && used + widthOf(to + 1) + (from > 0 ? 2 : 0) <= width;
1162
+ if (canRight) { to++; used += widthOf(to); continue; }
1163
+ break;
1164
+ }
1165
+ }
1166
+
1167
+ const style = (i: number) => {
1168
+ const t = tabs[i]!;
1169
+ const body = compact[i]
1170
+ ? (t.icon ?? truncateToWidth(t.label, 3))
1171
+ : (t.icon ? `${t.icon} ${t.label}` : t.label);
1172
+ const text = ` ${body} `;
1173
+ if (i !== this.tab) return this.color(compact[i] ? "dim" : "muted", text);
1174
+ const boldText = this.theme?.bold ? this.theme.bold(text) : text;
1175
+ return this.theme?.bg
1176
+ ? this.theme.bg("selectedBg", this.color("text", boldText))
1177
+ : this.color("accent", boldText);
1178
+ };
1179
+ const parts: string[] = [];
1180
+ if (from > 0) parts.push(this.color("dim", "…"));
1181
+ for (let i = from; i <= to; i++) parts.push(style(i));
1182
+ if (to < tabs.length - 1) parts.push(this.color("dim", "…"));
1183
+ return truncateToWidth(parts.join(""), width);
1184
+ }
1185
+
1186
+ /** True when a row's current value differs from its declared default. */
1187
+ private isChanged(r: PanelRow): boolean {
1188
+ return r.defaultValue !== undefined && String(r.value ?? "") !== String(r.defaultValue ?? "");
1189
+ }
1190
+
1191
+ private renderRow(r: PanelRow, selected: boolean, dimmed: boolean, labelWidth: number, width: number): string[] {
1192
+ const mark = selected ? this.color("accent", "›") : " ";
1193
+ const masked = r.mask && String(r.value ?? "") !== "";
1194
+ if (this.editing === r) {
1195
+ // Inline input row — the input's own render (single line) plus the
1196
+ // current value as a hint, then the live suggestion list (Tab picks).
1197
+ // Lines array, NOT a joined string: the outer render truncates each
1198
+ // element, and truncateToWidth collapses a multi-line styled blob into
1199
+ // one line, which silently dropped the suggestion list (real theme).
1200
+ const inputLines = this.input ? this.input.render(width - 4) : ["…"];
1201
+ // Masked rows only: the secret never renders, so hint at its presence.
1202
+ // Non-masked rows are prefilled — the value is in the input, no hint.
1203
+ const hint = masked ? this.color("dim", " (was: ••••)") : "";
1204
+ const lines = [`${mark} ${r.label}: ${inputLines[0] ?? ""}${hint}`];
1205
+ if (this.suggestions.length > 0) {
1206
+ for (let i = 0; i < this.suggestions.length; i++) {
1207
+ const s = this.suggestions[i]!;
1208
+ const hl = i === this.suggestionIdx;
1209
+ const label = s.label ?? s.value;
1210
+ const desc = s.description ? this.color("dim", ` — ${s.description}`) : "";
1211
+ const text = ` ${hl ? this.color("accent", "›") : " "}` +
1212
+ (hl ? this.color("text", `${label}${desc}`) : this.color("dim", `${label}${desc}`));
1213
+ lines.push(text);
1214
+ }
1215
+ }
1216
+ return lines;
1217
+ }
1218
+
1219
+ // Info rows: read-only derived state — dim value, never an action hint.
1220
+ if (r.kind === "info") {
1221
+ const raw = String(r.value ?? "");
1222
+ const labelPadI = " ".repeat(Math.max(1, labelWidth - visibleWidth(r.label) + 2));
1223
+ const text = `${mark} ${this.color("dim", r.label)}${labelPadI}${this.color("dim", raw)}`;
1224
+ return [truncateToWidth(text, width, "...", true)];
1225
+ }
1226
+
1227
+ // Label + (warning glyph) + padding + value column.
1228
+ const glyph = r.warning ? this.color("warning", " ⚠") : "";
1229
+ const labelPad = " ".repeat(Math.max(1, labelWidth - visibleWidth(r.label) - (r.warning ? 2 : 0) + 2));
1230
+ const changed = this.isChanged(r);
1231
+ let valueText: string;
1232
+ // Dim wash wins over semantic colors for rows outside the active section
1233
+ // (OMP renders them under one dim wash so nothing fights it).
1234
+ const selectedValue = (t: string) =>
1235
+ dimmed && !selected
1236
+ ? this.color("dim", t)
1237
+ : changed ? this.color("warning", t) : selected ? this.color("accent", t) : this.color("muted", t);
1238
+ if (r.kind === "toggle") {
1239
+ // Selected row wins over the semantic on/off color so the cursor line
1240
+ // reads as one unit; changed overrides both (warning).
1241
+ valueText = r.value
1242
+ ? (selected || changed || dimmed ? selectedValue("on") : this.color("success", "on"))
1243
+ : selectedValue("off");
1244
+ } else if (r.kind === "action") {
1245
+ valueText = this.color("accent", "press Enter");
1246
+ } else if (masked) {
1247
+ valueText = this.color("dim", "••••");
1248
+ } else {
1249
+ const raw = String(r.value ?? "");
1250
+ valueText = raw === "" ? this.color("dim", "(not set)") : selectedValue(raw);
1251
+ }
1252
+ // Label priority: selected → accent (the cursor line stays identifiable),
1253
+ // else changed → warning (OMP's screenshots: a selected+changed row shows
1254
+ // a blue label with an orange value). The dim wash wins outside the
1255
+ // active section.
1256
+ const labelText = dimmed && !selected
1257
+ ? this.color("dim", r.label)
1258
+ : selected ? this.color("accent", r.label) : changed ? this.color("warning", r.label) : this.color("text", r.label);
1259
+ const rowText = `${mark} ${labelText}${glyph}${labelPad}${valueText}`;
1260
+ return [truncateToWidth(rowText, width, "...", true)];
1261
+ }
1262
+
1263
+ handleInput(data: string): void {
1264
+ // The selection submenu owns EVERY key while open (↑/↓ browse, type to
1265
+ // filter, Enter commits, Esc backs out) — Tab/←/→ must not switch tabs
1266
+ // underneath it, and the panel Esc-close can't fire from here.
1267
+ if (this.menuItem && this.handleMenuInput(data)) return;
1268
+ // While editing or prompting, route ALL keys to the inline input — except
1269
+ // suggestion navigation (↑/↓), pick (Tab or Enter), and list dismiss
1270
+ // (Esc) while a completion list is up. Enter PICKS the highlighted item
1271
+ // (picker-first UX, like every other pi selector); after a pick the list
1272
+ // is off, so the NEXT Enter submits the typed text (custom refs still
1273
+ // reachable: Esc first, then edit + Enter). Tab keeps its fill role.
1274
+ if ((this.editing || this.pendingPrompt) && this.input) {
1275
+ if (this.editing && this.suggestions.length > 0) {
1276
+ const kb = this.keybindings;
1277
+ if (kb) {
1278
+ if (kb.matches(data, "tui.select.up")) return this.moveSuggestion(-1);
1279
+ if (kb.matches(data, "tui.select.down")) return this.moveSuggestion(1);
1280
+ if (kb.matches(data, "tui.select.confirm")) return this.acceptSuggestion();
1281
+ } else {
1282
+ if (data === "\u001b[A" || data === "\u001bOA") return this.moveSuggestion(-1);
1283
+ if (data === "\u001b[B" || data === "\u001bOB") return this.moveSuggestion(1);
1284
+ if (data === "\r" || data === "\n") return this.acceptSuggestion();
1285
+ }
1286
+ if (data === "\t") return this.acceptSuggestion();
1287
+ // Esc with the list OPEN dismisses the list only (typed text kept);
1288
+ // with no list it falls through to Input → cancels the edit.
1289
+ if (data === "\u001b" && this.suggestions.length > 0) {
1290
+ this.suggestions = [];
1291
+ this.lastFilteredValue = this.input.getValue();
1292
+ this.requestRender();
1293
+ return;
1294
+ }
1295
+ }
1296
+ this.input.handleInput(data);
1297
+ if (this.editing) this.refilterSuggestions();
1298
+ this.requestRender();
1299
+ return;
1300
+ }
1301
+ const kb = this.keybindings;
1302
+ if (kb) {
1303
+ if (kb.matches(data, "tui.select.up")) return this.move(-1);
1304
+ if (kb.matches(data, "tui.select.down")) return this.move(1);
1305
+ if (kb.matches(data, "tui.select.pageUp")) return this.jumpSection(-1);
1306
+ if (kb.matches(data, "tui.select.pageDown")) return this.jumpSection(1);
1307
+ // matchesKey normalizes every arrow encoding (CSI/SS3/kitty CSI-u) —
1308
+ // raw byte comparisons missed SS3 \u001bOD and kitty sequences.
1309
+ if (matchesKey(data, "left")) return this.stepTab(-1);
1310
+ if (matchesKey(data, "right")) return this.stepTab(1);
1311
+ if (matchesKey(data, "tab")) return this.stepTab(1);
1312
+ if (matchesKey(data, "shift+tab")) return this.stepTab(-1);
1313
+ if (this.filter) {
1314
+ // Search-mode keys: printable text edits the query, ⌫ shortens it,
1315
+ // Esc clears the filter (a second Esc closes the panel).
1316
+ if (kb.matches(data, "tui.select.cancel")) return this.setFilter("");
1317
+ if (kb.matches(data, "tui.editor.deleteCharBackward")) return this.setFilter([...this.filter].slice(0, -1).join(""));
1318
+ const printable = printableText(data);
1319
+ if (printable !== undefined) return this.setFilter(this.filter + printable);
1320
+ if (kb.matches(data, "tui.select.confirm") || kb.matches(data, "tui.input.submit")) {
1321
+ void this.activate();
1322
+ return;
1323
+ }
1324
+ return;
1325
+ }
1326
+ if (kb.matches(data, "tui.select.cancel")) return this.onClose?.();
1327
+ if (kb.matches(data, "tui.select.confirm") || kb.matches(data, "tui.input.submit")) {
1328
+ void this.activate();
1329
+ return;
1330
+ }
1331
+ const printable = printableText(data);
1332
+ if (printable !== undefined && (this.filter || printable.trim())) return this.setFilter(printable);
1333
+ return;
1334
+ }
1335
+ // Fallback raw parsing (tests / non-standard keybindings).
1336
+ if (this.filter) {
1337
+ if (matchesKey(data, "up")) return this.move(-1);
1338
+ if (matchesKey(data, "down")) return this.move(1);
1339
+ if (matchesKey(data, "left")) return this.stepTab(-1);
1340
+ if (matchesKey(data, "right")) return this.stepTab(1);
1341
+ if (matchesKey(data, "tab")) return this.stepTab(1);
1342
+ if (matchesKey(data, "shift+tab")) return this.stepTab(-1);
1343
+ if (matchesKey(data, "pageUp")) return this.jumpSection(-1);
1344
+ if (matchesKey(data, "pageDown")) return this.jumpSection(1);
1345
+ if (matchesKey(data, "escape") || data === "\u0003") return this.setFilter("");
1346
+ if (data === "\u007f" || data === "\b") return this.setFilter([...this.filter].slice(0, -1).join(""));
1347
+ const printable = printableText(data);
1348
+ if (printable !== undefined) return this.setFilter(this.filter + printable);
1349
+ if (matchesKey(data, "enter")) void this.activate();
1350
+ return;
1351
+ }
1352
+ if (matchesKey(data, "up") || data === "k") return this.move(-1);
1353
+ if (matchesKey(data, "down") || data === "j") return this.move(1);
1354
+ if (matchesKey(data, "left")) return this.stepTab(-1);
1355
+ if (matchesKey(data, "right")) return this.stepTab(1);
1356
+ if (matchesKey(data, "tab")) return this.stepTab(1);
1357
+ if (matchesKey(data, "shift+tab")) return this.stepTab(-1);
1358
+ if (matchesKey(data, "pageUp")) return this.jumpSection(-1);
1359
+ if (matchesKey(data, "pageDown")) return this.jumpSection(1);
1360
+ if (matchesKey(data, "escape") || data === "\u0003") return this.onClose?.();
1361
+ if (matchesKey(data, "enter")) void this.activate();
1362
+ else {
1363
+ const printable = printableText(data);
1364
+ // A bare space never starts a search (it would swallow the key).
1365
+ if (printable !== undefined && (this.filter || printable.trim())) this.setFilter(printable);
1366
+ }
1367
+ }
1368
+
1369
+ private async activate(): Promise<void> {
1370
+ const row = this.flat[this.selected];
1371
+ if (!row) return;
1372
+ // Only act on a row the user can actually SEE: an empty tab (or a search
1373
+ // with no matches) leaves `selected` on a hidden row — Enter there would
1374
+ // silently toggle an invisible setting. Same predicate render() uses.
1375
+ const inView = this.filter
1376
+ ? this.visible.includes(this.selected)
1377
+ : this.tabRows(this.tab).includes(this.selected);
1378
+ if (!inView) return;
1379
+ // Info rows are display-only (derived state the panel cannot edit).
1380
+ if (row.kind === "info") return;
1381
+ if (row.kind === "action") {
1382
+ // Route through onAction (wired by openConfigPanel) which passes the
1383
+ // inline prompt to the action's run(). Actions must NOT call
1384
+ // ctx.ui.input/select/confirm — those render under the overlay.
1385
+ await this.onAction?.(row);
1386
+ } else if (this.hasMenu(row)) {
1387
+ this.openMenu(row);
1388
+ } else if (row.kind === "toggle") {
1389
+ row.set(!row.value);
1390
+ this.dirty = true;
1391
+ this.editedKeys.add(row.key);
1392
+ this.onChanged?.();
1393
+ this.requestRender();
1394
+ } else {
1395
+ this.startEdit(row);
1396
+ }
1397
+ }
1398
+
1399
+ // -------------------------------------------------------------------------
1400
+ // Selection submenu (OMP's select submenu)
1401
+ // -------------------------------------------------------------------------
1402
+
1403
+ /** True when Enter opens the selection submenu: a `values` set or a dynamic
1404
+ * `menu` provider. Pure predicate — never invokes `menu()` (openMenu owns
1405
+ * the single provider call; empty results fall through to inline edit). */
1406
+ private hasMenu(row: PanelRow): boolean {
1407
+ return !!row.menu || (row.values?.length ?? 0) > 0;
1408
+ }
1409
+
1410
+ /** Open the submenu for a row: options from `menu()` or `values`, cursor on
1411
+ * the row's current value, and the row's own description/warning kept in
1412
+ * the fixed description area (the row stays `selected`). */
1413
+ private openMenu(row: PanelRow): void {
1414
+ const options: PanelMenuOption[] = row.menu
1415
+ ? row.menu()
1416
+ : (row.values ?? []).map((v) => ({ value: v }));
1417
+ if (options.length === 0) {
1418
+ if (row.kind === "string" || row.kind === "number") this.startEdit(row);
1419
+ return;
1420
+ }
1421
+ const original = String(row.value ?? "");
1422
+ const at = options.findIndex((o) => o.value === original);
1423
+ this.menuItem = {
1424
+ row,
1425
+ options,
1426
+ view: options,
1427
+ idx: at >= 0 ? at : 0,
1428
+ query: "",
1429
+ };
1430
+ this.requestRender();
1431
+ }
1432
+
1433
+ /** Selection menu is open (tests + render branch). */
1434
+ get menuOpen(): boolean {
1435
+ return this.menuItem !== null;
1436
+ }
1437
+
1438
+ /** Options the open menu currently shows (tests). */
1439
+ get menuOptions(): PanelMenuOption[] {
1440
+ return this.menuItem ? [...this.menuItem.view] : [];
1441
+ }
1442
+
1443
+ /** Highlighted index in the open menu (tests). */
1444
+ get menuIndex(): number {
1445
+ return this.menuItem?.idx ?? -1;
1446
+ }
1447
+
1448
+ /** Move the menu cursor (clamped, OMP SelectList) and fire the live preview
1449
+ * for the newly highlighted option. */
1450
+ private moveMenu(delta: number): void {
1451
+ const m = this.menuItem;
1452
+ if (!m || m.view.length === 0) return;
1453
+ const next = Math.max(0, Math.min(m.view.length - 1, m.idx + delta));
1454
+ if (next === m.idx) return;
1455
+ m.idx = next;
1456
+ m.row.preview?.(m.view[next]!.value);
1457
+ this.requestRender();
1458
+ }
1459
+
1460
+ /** Page the menu cursor by a viewport (PageUp/Dn). */
1461
+ private pageMenu(delta: number): void {
1462
+ const m = this.menuItem;
1463
+ if (!m || m.view.length === 0) return;
1464
+ const next = Math.max(0, Math.min(m.view.length - 1, m.idx + delta * this.bodyRows()));
1465
+ if (next === m.idx) return;
1466
+ m.idx = next;
1467
+ m.row.preview?.(m.view[next]!.value);
1468
+ this.requestRender();
1469
+ }
1470
+
1471
+ /** Re-filter the menu options against the typed query (case-insensitive
1472
+ * substring on option label + value) and clamp the cursor into range. */
1473
+ private refilterMenu(): void {
1474
+ const m = this.menuItem;
1475
+ if (!m) return;
1476
+ const q = m.query.trim().toLowerCase();
1477
+ const prev = m.view[m.idx];
1478
+ m.view = q
1479
+ ? m.options.filter((o) =>
1480
+ (o.label ?? o.value).toLowerCase().includes(q) || o.value.toLowerCase().includes(q))
1481
+ : m.options;
1482
+ if (m.view.length === 0) {
1483
+ m.idx = 0;
1484
+ } else {
1485
+ const at = prev ? m.view.findIndex((o) => o.value === prev.value) : -1;
1486
+ m.idx = at >= 0 ? at : 0;
1487
+ }
1488
+ // A filter change can re-target the highlight (the old option dropped
1489
+ // out) — keep the live preview in sync with whatever is now highlighted.
1490
+ const next = m.view[m.idx];
1491
+ if (next && next.value !== prev?.value) m.row.preview?.(next.value);
1492
+ this.requestRender();
1493
+ }
1494
+
1495
+ /** Commit the highlighted option: the normal enum write path, then close.
1496
+ * A commit never fires `preview` — the row's own setter is the effect. */
1497
+ private commitMenu(): void {
1498
+ const m = this.menuItem;
1499
+ if (!m) return;
1500
+ const picked = m.view[m.idx];
1501
+ this.menuItem = null;
1502
+ if (!picked) {
1503
+ this.requestRender();
1504
+ return;
1505
+ }
1506
+ if (picked.value !== String(m.row.value ?? "")) {
1507
+ m.row.set(picked.value);
1508
+ this.dirty = true;
1509
+ this.editedKeys.add(m.row.key);
1510
+ this.onChanged?.();
1511
+ }
1512
+ this.requestRender();
1513
+ }
1514
+
1515
+ /** Cancel the menu: let the row undo its live preview (OMP's
1516
+ * onPreviewCancel) and close. Never marks dirty. */
1517
+ private cancelMenu(): void {
1518
+ const m = this.menuItem;
1519
+ if (!m) return;
1520
+ this.menuItem = null;
1521
+ m.row.previewCancel?.();
1522
+ this.requestRender();
1523
+ }
1524
+
1525
+ /** Menu key handling. Returns true when the key was consumed. */
1526
+ private handleMenuInput(data: string): boolean {
1527
+ const m = this.menuItem;
1528
+ if (!m) return false;
1529
+ const kb = this.keybindings;
1530
+ const up = kb ? kb.matches(data, "tui.select.up") : false;
1531
+ const down = kb ? kb.matches(data, "tui.select.down") : false;
1532
+ const pageUp = kb ? kb.matches(data, "tui.select.pageUp") : false;
1533
+ const pageDown = kb ? kb.matches(data, "tui.select.pageDown") : false;
1534
+ const cancel = kb ? kb.matches(data, "tui.select.cancel") : false;
1535
+ const confirm = kb
1536
+ ? kb.matches(data, "tui.select.confirm") || kb.matches(data, "tui.input.submit")
1537
+ : false;
1538
+ if (up || (!kb && matchesKey(data, "up"))) return this.moveMenu(-1), true;
1539
+ if (down || (!kb && matchesKey(data, "down"))) return this.moveMenu(1), true;
1540
+ if (pageUp || (!kb && matchesKey(data, "pageUp"))) return this.pageMenu(-1), true;
1541
+ if (pageDown || (!kb && matchesKey(data, "pageDown"))) return this.pageMenu(1), true;
1542
+ if (confirm || (!kb && matchesKey(data, "enter"))) return this.commitMenu(), true;
1543
+ // Esc: a non-empty query clears first (OMP: search then back), a second
1544
+ // Esc leaves the menu and restores the original value.
1545
+ if (cancel || (!kb && (matchesKey(data, "escape") || data === "\u0003"))) {
1546
+ if (m.query !== "") {
1547
+ m.query = "";
1548
+ this.refilterMenu();
1549
+ } else {
1550
+ this.cancelMenu();
1551
+ }
1552
+ return true;
1553
+ }
1554
+ if (kb && kb.matches(data, "tui.editor.deleteCharBackward")) {
1555
+ if (m.query !== "") {
1556
+ m.query = [...m.query].slice(0, -1).join("");
1557
+ this.refilterMenu();
1558
+ }
1559
+ return true;
1560
+ }
1561
+ if (!kb && (data === "\u007f" || data === "\b")) {
1562
+ if (m.query !== "") {
1563
+ m.query = [...m.query].slice(0, -1).join("");
1564
+ this.refilterMenu();
1565
+ }
1566
+ return true;
1567
+ }
1568
+ const printable = printableText(data);
1569
+ if (printable !== undefined) {
1570
+ m.query += printable;
1571
+ this.refilterMenu();
1572
+ return true;
1573
+ }
1574
+ // Any other key is swallowed — the menu owns input while open (Tab/
1575
+ // arrows must not switch tabs or move the hidden rows pane).
1576
+ return true;
1577
+ }
1578
+
1579
+ /** Begin an inline prompt (for action rows like add/remove entries). */
1580
+ prompt(label: string, onDone: (value: string | undefined) => void): void {
1581
+ this.pendingPrompt = { label, onDone };
1582
+ this.input = new Input();
1583
+ this.suggestions = [];
1584
+ this.input.onSubmit = (raw: string) => {
1585
+ const p = this.pendingPrompt;
1586
+ this.pendingPrompt = null;
1587
+ this.input = null;
1588
+ p?.onDone(raw);
1589
+ this.requestRender();
1590
+ };
1591
+ this.input.onEscape = () => {
1592
+ const p = this.pendingPrompt;
1593
+ this.pendingPrompt = null;
1594
+ this.input = null;
1595
+ p?.onDone(undefined);
1596
+ this.requestRender();
1597
+ };
1598
+ this.input.focused = this._focused;
1599
+ this.requestRender();
1600
+ }
1601
+
1602
+ /** Begin inline editing of a row. String rows with a value start PREFILLED
1603
+ * (cursor at end) so existing entries are edited in place, not retyped;
1604
+ * blank submit still resets (callers define blank = default). Masked rows
1605
+ * start empty — never render the secret — and number rows keep
1606
+ * type-to-replace (prefill + digits would append). */
1607
+ private startEdit(row: PanelRow): void {
1608
+ this.editing = row;
1609
+ this.input = new Input();
1610
+ if (row.kind === "string" && !row.mask) {
1611
+ const existing = String(row.value ?? "");
1612
+ if (existing !== "") {
1613
+ this.input.setValue(existing);
1614
+ // pi-tui Input.setValue clamps the cursor instead of moving it — park
1615
+ // at the end explicitly (same pattern as acceptSuggestion).
1616
+ (this.input as unknown as { cursor: number }).cursor = existing.length;
1617
+ }
1618
+ }
1619
+ this.suggestionIdx = 0;
1620
+ this.lastFilteredValue = null; // first refilter after start counts as value-change
1621
+ this.refilterSuggestions();
1622
+ this.input.onSubmit = (raw: string) => {
1623
+ if (row.mask && raw === "") {
1624
+ this.editing = null;
1625
+ this.input = null;
1626
+ this.requestRender();
1627
+ return;
1628
+ }
1629
+ const next = kindValue(row.kind, raw);
1630
+ if (String(next) !== String(row.value)) {
1631
+ row.set(next);
1632
+ this.dirty = true;
1633
+ this.editedKeys.add(row.key);
1634
+ this.onChanged?.();
1635
+ }
1636
+ this.editing = null;
1637
+ this.input = null;
1638
+ this.suggestions = [];
1639
+ this.requestRender();
1640
+ };
1641
+ this.input.onEscape = () => {
1642
+ this.editing = null;
1643
+ this.input = null;
1644
+ this.suggestions = [];
1645
+ this.requestRender();
1646
+ };
1647
+ this.input.focused = this._focused;
1648
+ this.requestRender();
1649
+ }
1650
+
1651
+ /** Recompute the suggestion list from the input's current text (filtered by
1652
+ * the segment the cursor sits in — arrow left/right retargets the picker
1653
+ * to an earlier entry). Cursor moves WITHOUT value changes show the full
1654
+ * list for that segment (entering an existing entry shouldn't filter to
1655
+ * just itself); typing filters as usual. */
1656
+ private refilterSuggestions(): void {
1657
+ if (!this.editing?.completions || !this.input) {
1658
+ this.suggestions = [];
1659
+ return;
1660
+ }
1661
+ const valueChanged = this.input.getValue() !== this.lastFilteredValue;
1662
+ this.suggestions = filterSuggestions(
1663
+ this.editing.completions(),
1664
+ this.input.getValue(),
1665
+ (this.input as unknown as { cursor: number }).cursor,
1666
+ !valueChanged, // cursor-only move → empty query → full list
1667
+ ).slice(0, MAX_SUGGESTIONS);
1668
+ this.lastFilteredValue = this.input.getValue();
1669
+ if (valueChanged) {
1670
+ this.suggestionIdx = 0;
1671
+ } else {
1672
+ // Cursor-only retarget: pre-highlight the entry's CURRENT value so the
1673
+ // picker opens on what the segment already holds (↓ moves off it).
1674
+ const { suffix } = splitSegments(this.input.getValue(), (this.input as unknown as { cursor: number }).cursor);
1675
+ const cur = suffix.trim().toLowerCase();
1676
+ const at = this.suggestions.findIndex((o) => o.value.toLowerCase() === cur);
1677
+ this.suggestionIdx = at >= 0 ? at : 0;
1678
+ }
1679
+ }
1680
+
1681
+ private moveSuggestion(delta: number): void {
1682
+ const next = this.suggestionIdx + delta;
1683
+ if (next >= 0 && next < this.suggestions.length) {
1684
+ this.suggestionIdx = next;
1685
+ this.requestRender();
1686
+ }
1687
+ }
1688
+
1689
+ /** Pick the highlighted option into the segment at the cursor (Tab or
1690
+ * Enter). Always closes the list — the next Enter submits the value;
1691
+ * typing (`,` or chars) reopens it via refilter. */
1692
+ private acceptSuggestion(): void {
1693
+ const item = this.suggestions[this.suggestionIdx];
1694
+ if (!item || !this.input) return;
1695
+ const cursor = (this.input as unknown as { cursor: number }).cursor;
1696
+ const before = this.input.getValue();
1697
+ const joined = joinCompletion(before, item.value, cursor);
1698
+ const head = splitSegments(before, cursor).head;
1699
+ this.input.setValue(joined);
1700
+ // pi-tui Input.setValue clamps the cursor instead of moving it to the end
1701
+ // (stays at 0 on a fresh input). Park at the end of the REPLACED segment
1702
+ // (head + ", " + value) — with tail segments after the cursor's segment,
1703
+ // joined.length would overshoot into the next entry. Empty head joins
1704
+ // WITHOUT the ", " separator, so don't count it.
1705
+ (this.input as unknown as { cursor: number }).cursor = (head ? head.length + 2 : 0) + item.value.length;
1706
+ this.suggestionIdx = 0;
1707
+ // Close: sync lastFilteredValue so the next handleInput doesn't treat the
1708
+ // pick as a cursor-only move and "retarget" the list back open.
1709
+ this.suggestions = [];
1710
+ this.lastFilteredValue = this.input.getValue();
1711
+ this.requestRender();
1712
+ }
1713
+
1714
+ private move(delta: number): void {
1715
+ const pos = this.visiblePos() + delta;
1716
+ if (pos < 0 || pos >= this.visible.length) return;
1717
+ this.selected = this.visible[pos]!;
1718
+ this.requestRender();
1719
+ }
1720
+ }