@bismawy/pi-arnative 0.6.1 → 0.7.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.
@@ -4,9 +4,9 @@
4
4
  * shared with the Model tab.
5
5
  */
6
6
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
8
8
  import { tmpdir } from "node:os";
9
- import { join } from "node:path";
9
+ import { join, relative } from "node:path";
10
10
  import { matchesKey, truncateToWidth, visibleWidth, type Component, type TUI, type TuiMouseEvent } from "@earendil-works/pi-tui";
11
11
  import { renderScreen, screenTitle } from "../lib/box.ts";
12
12
  import { assert, isMain } from "../lib/check.ts";
@@ -400,8 +400,9 @@ if (isMain(import.meta.url)) {
400
400
 
401
401
  // A session file that grows is parsed from the tail only (byte offset in the cache), not re-read.
402
402
  const file = join(fixture, "sessions", "proj", "a.jsonl");
403
- const cachedBefore = JSON.parse(readFileSync(join(fixture, "arnative-usage-cache.json"), "utf8")) as Record<string, { consumed: number; size: number }>;
404
- assert(cachedBefore[file]!.consumed === cachedBefore[file]!.size, "cache records the full parsed offset");
403
+ const cachePath = join(fixture, "arnative", "usage-cache.json");
404
+ const cachedBefore = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, { c: number; s: number }>;
405
+ assert(cachedBefore[relative(join(fixture, "sessions"), file)]!.c === cachedBefore[relative(join(fixture, "sessions"), file)]!.s, "cache records the full parsed offset");
405
406
  writeFileSync(file, asst("gemini-3.8-flash", 1000) + String.fromCharCode(10), { flag: "a" });
406
407
  const grown = collectUsageSummary(true);
407
408
  assert(grown.totals.msgs === 4, "an appended record is picked up from the tail");
@@ -413,12 +414,12 @@ if (isMain(import.meta.url)) {
413
414
  // The per-file rollup is what makes a refresh cheap: folding a tail must reproduce the same
414
415
  // totals as parsing the whole file from scratch. Compare the incremental answer to a cold one.
415
416
  const incremental = JSON.stringify(getModelAllTimeUsage("gemini-3.8-flash"));
416
- const cacheRaw = JSON.parse(readFileSync(join(fixture, "arnative-usage-cache.json"), "utf8")) as Record<string, unknown>;
417
+ const cacheRaw = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, unknown>;
417
418
  // Drop the cache (as a fresh machine, or a version bump, would) and rescan the whole file.
418
419
  // Writing `{}` is not enough on its own: the disk cache is memoized per process, so the
419
420
  // memo would answer and this assert would compare a value against itself, never failing.
420
421
  resetUsageCache();
421
- writeFileSync(join(fixture, "arnative-usage-cache.json"), "{}", "utf8");
422
+ writeFileSync(cachePath, "{}", "utf8");
422
423
  collectUsageSummary(true);
423
424
  assert(
424
425
  JSON.stringify(getModelAllTimeUsage("gemini-3.8-flash")) === incremental,
@@ -436,10 +437,64 @@ if (isMain(import.meta.url)) {
436
437
  // Disk cache pruning: no cache key may point at a session file that is gone.
437
438
  rmSync(join(fixture, "sessions", "proj", "a.jsonl"));
438
439
  collectUsageSummary(true);
439
- const raw = JSON.parse(readFileSync(join(fixture, "arnative-usage-cache.json"), "utf8")) as Record<string, unknown>;
440
+ const raw = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, unknown>;
440
441
  assert(Object.keys(raw).length === 0, "usage disk cache prunes deleted session files");
441
442
  rmSync(fixture, { recursive: true, force: true });
442
443
 
444
+ // A flat pre-folder cache is moved into the arnative folder on first read; the v4
445
+ // items keep working (decode feeds the summary, a grown file tail-folds forward) and
446
+ // the next save is the compact v5 shape: session-dir-relative keys, model-only rows.
447
+ const mig = mkdtempSync(join(tmpdir(), "arnative-usage-mig-"));
448
+ process.env.PI_CODING_AGENT_DIR = mig;
449
+ mkdirSync(join(mig, "sessions", "p"), { recursive: true });
450
+ const migFile = join(mig, "sessions", "p", "a.jsonl");
451
+ const migLine = asst("gemini-3.8-flash", 5) + String.fromCharCode(10);
452
+ writeFileSync(migFile, migLine, "utf8");
453
+ const migStat = statSync(migFile);
454
+ writeFileSync(
455
+ join(mig, "arnative-usage-cache.json"),
456
+ JSON.stringify({
457
+ [migFile]: {
458
+ mtimeMs: migStat.mtimeMs,
459
+ size: migStat.size,
460
+ v: 4,
461
+ consumed: migStat.size,
462
+ rollup: {
463
+ providers: {
464
+ "x\u0000m": { sessions: 1, msgs: 3, input: 4, output: 5, cacheRead: 6, cost: 0 },
465
+ "x": { sessions: 1, msgs: 3, input: 4, output: 5, cacheRead: 6, cost: 0 },
466
+ },
467
+ },
468
+ },
469
+ }),
470
+ "utf8",
471
+ );
472
+ resetUsageCache();
473
+ assert(collectUsageSummary(true).totals.msgs === 3, "a migrated v4 entry feeds the summary as-is (no reparse of an unchanged file)");
474
+ writeFileSync(migFile, asst("gemini-3.8-flash", 7) + String.fromCharCode(10), { flag: "a" });
475
+ assert(collectUsageSummary(true).totals.msgs === 4, "a grown file tail-folds on top of a migrated v4 entry");
476
+ assert(existsSync(join(mig, "arnative", "usage-cache.json")), "the cache is saved into the arnative folder");
477
+ const migrated = JSON.parse(readFileSync(join(mig, "arnative", "usage-cache.json"), "utf8")) as Record<string, { r: Record<string, number[]> }>;
478
+ const migKey = join("p", "a.jsonl");
479
+ assert(Object.keys(migrated)[0] === migKey, "v5 keys are stored relative to the sessions dir");
480
+ assert(
481
+ Object.keys(migrated[migKey]!.r).every((k) => k.includes("\u0000")),
482
+ "v5 stores model rows only (provider rows are derived on load)",
483
+ );
484
+ // Layout "1" cleanup: the dead flat prices file and a flat cache a downgrade recreated
485
+ // beside the folder copy are removed on the next load; the folder copy survives.
486
+ writeFileSync(join(mig, "arnative-prices.json"), "{}", "utf8");
487
+ writeFileSync(join(mig, "arnative-usage-cache.json"), "{}", "utf8");
488
+ resetUsageCache();
489
+ collectUsageSummary(true);
490
+ assert(!existsSync(join(mig, "arnative-prices.json")), "the dead flat prices file is removed");
491
+ assert(!existsSync(join(mig, "arnative-usage-cache.json")), "a flat cache recreated beside the folder copy is removed");
492
+ assert(existsSync(join(mig, "arnative", "usage-cache.json")), "the folder copy survives the cleanup");
493
+ rmSync(mig, { recursive: true, force: true });
494
+ // Back to the main fixture: the UI rows below still scan it.
495
+ process.env.PI_CODING_AGENT_DIR = fixture;
496
+ resetUsageCache();
497
+
443
498
  // UI checks need rows of their own: the scratch above ends with an empty, deleted file.
444
499
  // These use a provider that reports NO cost (cost.total = 0), which is the case the estimate
445
500
  // exists for; `asst` above reports 0.02 per message and would be priced by the provider.
package/lib/box.ts CHANGED
@@ -32,7 +32,8 @@ const applyBg = (line: string, width: number, bgFn: (text: string) => string): s
32
32
  export interface ScreenText {
33
33
  title: string;
34
34
  description: string;
35
- /** Keybind legend, drawn as the last row above the bottom edge. */
35
+ /** Keybind legend, drawn as the last row above the bottom edge. Plain text is dimmed
36
+ * by the frame; a legend that already carries ANSI styling renders verbatim. */
36
37
  legend: string;
37
38
  }
38
39
 
@@ -66,7 +67,7 @@ export function renderScreen(
66
67
  row(""),
67
68
  ...body.map(row),
68
69
  row(""),
69
- row(fg("dim", text.legend)),
70
+ row(text.legend.includes("\u001b[") ? text.legend : fg("dim", text.legend)),
70
71
  boxEdge("╰", "╯", width, border),
71
72
  ].map((l) => truncateToWidth(l, width, ""));
72
73
  }
@@ -131,8 +132,12 @@ if (isMain(import.meta.url)) {
131
132
  assert(taggedScreen[2]!.includes("<muted>d"), "the description is muted");
132
133
  assert(taggedScreen[taggedScreen.length - 2]!.includes("<dim>l"), "the legend is dim");
133
134
  assert(renderScreen(null, 40, { title: "t", description: "d", legend: "l" }, ["x"]).every((l) => visibleWidth(l) === 40), "a null theme still frames the screen");
135
+ // A legend that styles itself (the models picker accents its picked count) renders
136
+ // verbatim: no dim wrap that would mute the accent and leak a reset into the tail.
137
+ const styled = renderScreen(th, 60, { title: "t", description: "d", legend: "<accent>34/44 picked</accent><dim> · keys</dim>" }, []);
138
+ assert(styled[styled.length - 2]!.includes("<accent>34/44 picked</accent>"), "a pre-styled legend renders verbatim");
134
139
  // The header copy is longer than a narrow terminal: the wall must win over the text.
135
- const longCopy = "Selection previews live — same list as /settings → Theme.";
140
+ const longCopy = "Selection previews live — arnative themes only (all themes: /settings → Theme).";
136
141
  for (const w of [40, 50, 56, 60]) {
137
142
  const narrow = renderScreen(th, w, { title: screenTitle("Themes"), description: longCopy, legend: "[Esc] Revert" }, []);
138
143
  assert(narrow.every((l) => visibleWidth(l) === w), `a long description keeps every line at width ${w}`);
@@ -0,0 +1,393 @@
1
+ /**
2
+ * The live-preview picker shared by every arnative screen (`/arnative` and friends):
3
+ * ↑↓ previews instantly, Enter keeps, Esc reverts — plus a multi-select mode (`marked`
4
+ * rows, Space toggles) for the Providers model list. Lives in its own module so screens
5
+ * can import it without importing the settings menu back (no import cycle).
6
+ */
7
+ import { Input, matchesKey, truncateToWidth, visibleWidth, type Component, type Focusable } from "@earendil-works/pi-tui";
8
+ import { softSecondaryOf, thinkingColorOf } from "../lib/ansi.ts";
9
+ import { renderScreen, screenTitle, type ScreenText } from "../lib/box.ts";
10
+ import { assert, isMain } from "../lib/check.ts";
11
+ import { ROW_DIVIDER } from "../lib/format.ts";
12
+ import { LEGEND_LIVE, LEGEND_MOVE, LEGEND_ROOT, matchesBack } from "../lib/shortcuts.ts";
13
+
14
+ // Legends come from the `KeySet`s the handlers match, so a key cannot be advertised on a
15
+ // screen that does not handle it; the root menu has nothing behind it and omits `←`.
16
+ export const LIST_LEGEND_ROOT = LEGEND_ROOT;
17
+ export const LIST_LEGEND_MOVE = LEGEND_MOVE;
18
+ export const LIST_LEGEND_LIVE = LEGEND_LIVE;
19
+ /** A text field: Enter keeps the value, Esc leaves it untouched. */
20
+ export const INPUT_LEGEND = "[Enter] Save [Esc] Cancel";
21
+
22
+ /** One picker row: `Label · Note`. `note` is absent on the preset lists (themes, headers,
23
+ * footers), which are bare names. */
24
+ export interface ListRow {
25
+ label: string;
26
+ note?: string;
27
+ }
28
+
29
+ /** One row as a flat string — the headless/RPC `ctx.ui.select` fallback, which has no columns. */
30
+ export function rowText(row: ListRow): string {
31
+ return row.note ? `${row.label} · ${row.note}` : row.label;
32
+ }
33
+
34
+ /** Bare names (preset lists) as rows; the cursor's `→` marks the live value. */
35
+ export const nameRows = (names: readonly string[]): ListRow[] => names.map((label) => ({ label }));
36
+
37
+ interface ListPickerHooks {
38
+ /** Apply a value on every selection move (live preview). */
39
+ preview: (name: string) => void;
40
+ /** Restore the value the picker opened with (Esc). */
41
+ revert: () => void;
42
+ done: () => void;
43
+ requestRender: () => void;
44
+ /** Esc, when it must be told apart from Enter (a menu selects, it does not revert). */
45
+ cancel?: () => void;
46
+ /** `←`: leave this screen for its parent (the menu, or the chat when there is none).
47
+ * Distinct from `cancel`/Esc, which closes or reverts the screen it is on. Pass
48
+ * `false` to hide the key entirely — a fill screen must not lose its work to a
49
+ * stray `←`; Esc stays the only way out and the legend says so. */
50
+ back?: (() => void) | false;
51
+ /** `g`: toggle a screen-level switch (Animations → gradient). Only a screen that passes
52
+ * this hook reacts to the key, so `g` stays a plain letter everywhere else. */
53
+ toggleGradient?: () => void;
54
+ /** Note re-read on every render, so a row can animate (Animations → a moving frame).
55
+ * Returning undefined keeps the row's static note. */
56
+ note?: (label: string) => string | undefined;
57
+ /** Space: toggle the row under the cursor (a multi-select screen). Only a screen that
58
+ * passes this hook reacts to Space, so every other screen keeps its meaning. */
59
+ toggle?: () => void;
60
+ /** Row check state for a multi-select screen; rows then render `[x]`/`[ ]` in front of
61
+ * the label. A screen without this hook renders no checkbox column at all. */
62
+ marked?: (label: string) => boolean;
63
+ /** Every key the picker does not handle, forwarded to the screen (a letter switch like
64
+ * `[a]` on the model list). The screen matches and acts; the picker only routes. */
65
+ press?: (keyData: string) => void;
66
+ /** Repaint cadence for an animated note. The frame itself is read from the clock, so a
67
+ * missed repaint costs one frame and never desynchronises the animation. */
68
+ tickMs?: number;
69
+ /** Legend re-read on every render, for a key row that states live state
70
+ * (`[g] Gradient on`). A constant legend would keep advertising the value it opened with. */
71
+ legend?: () => string;
72
+ /** Description re-read on every render, so the line under the title can follow screen
73
+ * state (the model list shows the API flavor `a` switched to). */
74
+ description?: () => string;
75
+ }
76
+
77
+ /** Box copy, so one picker serves every menu ("Themes - Arnative⠙", "Headers - Arnative⠙", …).
78
+ * The same shape every arnative screen uses — see {@link renderScreen}. */
79
+ export type ListPickerText = ScreenText;
80
+
81
+ /** Live-preview picker: ↑↓ previews instantly, Enter keeps, Esc reverts. A caller whose
82
+ * preview does nothing (`livePreview: false`) gets a plain menu: no revert on Esc, and
83
+ * Esc is reported through `cancel` so "chose nothing" stays distinguishable from Enter. */
84
+ export class ListPicker implements Component {
85
+ private theme: { fg(c: string, t: string): string; bold?(t: string): string };
86
+ private rows: ListRow[];
87
+ private hooks: ListPickerHooks;
88
+ private text: ListPickerText;
89
+ private selected: number;
90
+ private applied: string | undefined;
91
+ private readonly livePreview: boolean;
92
+ private readonly opened: string | undefined;
93
+ private readonly tick: ReturnType<typeof setInterval> | undefined;
94
+ /** Border painter, from the session's thinking level — the box follows the model. */
95
+ private readonly edge: (s: string) => string;
96
+ /** Rows shown before the list scrolls (a relay catalog can be far longer than the screen). */
97
+ private readonly maxRows: number | undefined;
98
+
99
+ constructor(
100
+ theme: { fg(c: string, t: string): string; bold?(t: string): string },
101
+ rows: ListRow[],
102
+ current: string | undefined,
103
+ hooks: ListPickerHooks,
104
+ text: ListPickerText,
105
+ /** False for a menu: the selection is applied only on Enter, never while moving. */
106
+ livePreview = true,
107
+ /** The session's thinking level; colors the box border (theme `thinking*` slot). */
108
+ thinkingLevel?: string,
109
+ /** Visible rows before scrolling; undefined shows every row. */
110
+ maxRows?: number,
111
+ ) {
112
+ this.theme = theme;
113
+ this.rows = rows;
114
+ this.hooks = hooks;
115
+ this.text = text;
116
+ this.livePreview = livePreview;
117
+ this.opened = current;
118
+ this.applied = current;
119
+ this.selected = Math.max(0, rows.findIndex((r) => r.label === current));
120
+ this.edge = thinkingColorOf(theme, thinkingLevel);
121
+ this.maxRows = maxRows;
122
+ this.tick = hooks.tickMs ? setInterval(() => hooks.requestRender(), hooks.tickMs) : undefined;
123
+ }
124
+
125
+ /** Component contract: renders are computed per call, so there is no cached output to drop. */
126
+ invalidate(): void {
127
+ /* intentionally no state */
128
+ }
129
+ dispose(): void {
130
+ if (this.tick) clearInterval(this.tick);
131
+ }
132
+
133
+ /** Selected row, for callers that need the choice after `done()` resolves. */
134
+ get index(): number {
135
+ return this.selected;
136
+ }
137
+
138
+ private move(delta: number): void {
139
+ const next = Math.min(this.rows.length - 1, Math.max(0, this.selected + delta));
140
+ if (next === this.selected) return;
141
+ this.selected = next;
142
+ if (!this.livePreview) {
143
+ this.hooks.requestRender();
144
+ return;
145
+ }
146
+ this.applied = this.rows[next]!.label;
147
+ this.hooks.preview(this.applied);
148
+ this.hooks.requestRender();
149
+ }
150
+
151
+ handleInput(keyData: string): void {
152
+ if (matchesBack(keyData)) {
153
+ // Leave for the parent without touching the preview: `back` owns the revert of an
154
+ // uncommitted preview, because "cancel" here means "close", not "undo".
155
+ if (this.hooks.back === false) return;
156
+ if (this.hooks.back) {
157
+ this.hooks.back();
158
+ return;
159
+ }
160
+ // No parent (the root menu): ← behaves like Esc — close, reverting a live preview.
161
+ if (this.applied !== this.opened) this.hooks.revert();
162
+ (this.hooks.cancel ?? this.hooks.done)();
163
+ return;
164
+ }
165
+ if (keyData === "Q" || matchesKey(keyData, "q") || matchesKey(keyData, "escape")) {
166
+ if (this.applied !== this.opened) this.hooks.revert();
167
+ (this.hooks.cancel ?? this.hooks.done)();
168
+ return;
169
+ }
170
+ if (matchesKey(keyData, "up") || matchesKey(keyData, "k")) {
171
+ this.move(-1);
172
+ return;
173
+ }
174
+ if (matchesKey(keyData, "down") || matchesKey(keyData, "j")) {
175
+ this.move(1);
176
+ return;
177
+ }
178
+ if (matchesKey(keyData, "enter")) {
179
+ this.hooks.done();
180
+ return;
181
+ }
182
+ if (this.hooks.toggle && matchesKey(keyData, "space")) this.hooks.toggle();
183
+ if (this.hooks.toggleGradient && matchesKey(keyData, "g")) this.hooks.toggleGradient();
184
+ if (this.hooks.press) this.hooks.press(keyData);
185
+ }
186
+
187
+ render(width: number): string[] {
188
+ const th = this.theme;
189
+ const bold = th.bold ?? ((t: string) => `\x1b[1m${t}\x1b[22m`);
190
+ const soft = softSecondaryOf(th);
191
+ const edge = (text: string) => this.edge(text);
192
+ const column = Math.max(0, ...this.rows.map((r) => visibleWidth(r.label)));
193
+ const body: string[] = [];
194
+ // A long list scrolls a window centered on the cursor, so the box keeps one height.
195
+ const max = this.maxRows ?? this.rows.length;
196
+ const windowStart = this.rows.length <= max ? 0 : Math.min(Math.max(0, this.selected - Math.floor(max / 2)), this.rows.length - max);
197
+ const windowEnd = Math.min(this.rows.length, windowStart + max);
198
+ for (let i = windowStart; i < windowEnd; i++) {
199
+ const item = this.rows[i]!;
200
+ const isSelected = i === this.selected;
201
+ const paint = isSelected ? (s: string) => soft(bold(s)) : (s: string) => th.fg(item.note ? "text" : "muted", s);
202
+ const pad = " ".repeat(Math.max(0, column - visibleWidth(item.label)));
203
+ const noteText = this.hooks.note?.(item.label) ?? item.note;
204
+ const note = noteText ? `${th.fg("dim", ROW_DIVIDER)}${th.fg("dim", noteText)}` : "";
205
+ // A checked state marker is chrome like the cursor: `[x]` accent, `[ ]` dim.
206
+ const mark = this.hooks.marked
207
+ ? this.hooks.marked(item.label)
208
+ ? th.fg("accent", "[x] ")
209
+ : th.fg("dim", "[ ] ")
210
+ : "";
211
+ // Extract parenthetical suffix to render softly
212
+ const suffix = /(\(.*\))$/.exec(item.label)?.[1] ?? "";
213
+ const head = suffix ? item.label.slice(0, item.label.length - suffix.length) : item.label;
214
+ const tail = suffix ? th.fg("dim", suffix) : "";
215
+ const content = `${isSelected ? th.fg("accent", "→ ") : " "}${mark}${paint(head)}${tail}${pad}${note}`;
216
+ body.push(truncateToWidth(content, width - 4, ""));
217
+ }
218
+ // Hidden rows are announced, never silently cut (an empty line is still a row).
219
+ if (windowStart > 0) body.unshift(truncateToWidth(th.fg("dim", `↑ ${windowStart} more`), width - 4, ""));
220
+ if (windowEnd < this.rows.length) body.push(truncateToWidth(th.fg("dim", `↓ ${this.rows.length - windowEnd} more`), width - 4, ""));
221
+ return renderScreen(
222
+ th,
223
+ width,
224
+ {
225
+ ...this.text,
226
+ legend: this.hooks.legend ? this.hooks.legend() : this.text.legend,
227
+ description: this.hooks.description ? this.hooks.description() : this.text.description,
228
+ },
229
+ body,
230
+ edge,
231
+ );
232
+ }
233
+ }
234
+
235
+ export interface InputPickerHooks {
236
+ /** Enter: submit the field's value. */
237
+ done: (value: string) => void;
238
+ /** Esc or ctrl+c: leave without a value. */
239
+ cancel: () => void;
240
+ requestRender: () => void;
241
+ }
242
+
243
+ /** An arnative-styled text field: the pi-tui `Input` editor — arrows, word motions,
244
+ * paste, undo — inside the same rounded box every other arnative screen uses, so a
245
+ * wizard prompt does not drop the user into a foreign full-width dialog. */
246
+ export class InputPicker implements Component, Focusable {
247
+ private readonly input: Input;
248
+ private readonly theme: { fg(c: string, t: string): string; bold?(t: string): string };
249
+ private readonly text: ScreenText;
250
+ private readonly hooks: InputPickerHooks;
251
+ /** Border painter, from the session's thinking level — the box follows the model. */
252
+ private readonly edge: (s: string) => string;
253
+ /** Set by the TUI; forwarded so the editor draws its cursor. */
254
+ focused = false;
255
+
256
+ constructor(
257
+ theme: { fg(c: string, t: string): string; bold?(t: string): string },
258
+ text: ScreenText,
259
+ initial: string,
260
+ hooks: InputPickerHooks,
261
+ /** Dim example shown while the field is empty. */
262
+ placeholder?: string,
263
+ thinkingLevel?: string,
264
+ ) {
265
+ this.theme = theme;
266
+ this.text = text;
267
+ this.hooks = hooks;
268
+ this.edge = thinkingColorOf(theme, thinkingLevel);
269
+ this.input = new Input({
270
+ prompt: "> ",
271
+ placeholder,
272
+ placeholderStyle: (t: string) => theme.fg("dim", t),
273
+ });
274
+ this.input.setValue(initial);
275
+ }
276
+
277
+ /** The field's current text — what Enter would submit. */
278
+ getValue(): string {
279
+ return this.input.getValue();
280
+ }
281
+
282
+ handleInput(data: string): void {
283
+ if (matchesKey(data, "enter")) {
284
+ this.hooks.done(this.input.getValue());
285
+ return;
286
+ }
287
+ if (matchesKey(data, "escape") || data === "\x03") {
288
+ this.hooks.cancel();
289
+ return;
290
+ }
291
+ this.input.handleInput(data);
292
+ this.hooks.requestRender();
293
+ }
294
+
295
+ render(width: number): string[] {
296
+ this.input.focused = this.focused;
297
+ const body = this.input.render(Math.max(8, width - 4));
298
+ return renderScreen(this.theme, width, this.text, body, this.edge);
299
+ }
300
+
301
+ invalidate(): void {
302
+ this.input.invalidate();
303
+ }
304
+
305
+ dispose(): void {
306
+ /* the editor holds nothing that outlives the screen */
307
+ }
308
+ }
309
+
310
+ /** Title of a sub-screen, derived from `screenTitle` so the format lives in one place. */
311
+ export const pickerTitle = (setting: string): ScreenText["title"] => screenTitle(setting);
312
+
313
+ // Self-check: `node lib/list-picker.ts`
314
+ if (isMain(import.meta.url)) {
315
+ assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Open [Esc] Close", "root legend pinned, no ← behind the root menu");
316
+ assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Open [←] Back [Esc] Close", "move legend pinned, ← advertised where a back target exists");
317
+ assert(LIST_LEGEND_LIVE === "[↑↓] Preview [Enter] Select [←] Back [Esc] Revert", "live legend pinned");
318
+ const fakeTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
319
+ const quiet = (): void => undefined;
320
+ const picker = new ListPicker(fakeTheme, nameRows(["a", "b"]), "a", { preview: quiet, revert: quiet, done: quiet, requestRender: quiet }, { title: screenTitle("Test"), description: "d", legend: "l" }, false);
321
+ const lines = picker.render(50);
322
+ assert(lines[0]!.startsWith("╭") && lines[lines.length - 1]!.startsWith("╰"), "picker framed");
323
+ assert(lines.every((l) => visibleWidth(l) === 50), "picker lines fit width 50");
324
+ assert(lines.some((l) => l.includes("→ a")), "the cursor marks the selection");
325
+
326
+ // `←` behavior is owned by the screen: a parent gets the back call, `false` swallows
327
+ // the key (a fill screen keeps its work), and a root menu closes like Esc.
328
+ const keyLeft = "\x1b[D";
329
+ let backCalls = 0;
330
+ let closedByBack = false;
331
+ const backPicker = new ListPicker(fakeTheme, nameRows(["a"]), "a", { preview: quiet, revert: quiet, done: quiet, cancel: quiet, requestRender: quiet, back: () => { backCalls++; } }, { title: screenTitle("Test"), description: "d", legend: "l" }, false);
332
+ backPicker.handleInput(keyLeft);
333
+ assert(backCalls === 1 && closedByBack === false, "a parent screen receives ← as back");
334
+ let closed = "none";
335
+ const noBackPicker = new ListPicker(fakeTheme, nameRows(["a"]), "a", { preview: quiet, revert: quiet, done: () => { closed = "done"; }, cancel: () => { closed = "cancel"; }, requestRender: quiet }, { title: screenTitle("Test"), description: "d", legend: "l" }, false);
336
+ noBackPicker.handleInput(keyLeft);
337
+ assert(closed === "cancel", "a root menu closes on ← like Esc");
338
+ let fillClosed = "none";
339
+ const fillPicker = new ListPicker(fakeTheme, nameRows(["a"]), "a", { preview: quiet, revert: quiet, done: () => { fillClosed = "done"; }, cancel: () => { fillClosed = "cancel"; }, requestRender: quiet, back: false }, { title: screenTitle("Test"), description: "d", legend: "l" }, false);
340
+ fillPicker.handleInput(keyLeft);
341
+ fillPicker.handleInput("\x1bOD");
342
+ assert(fillClosed === "none", "a fill screen swallows ← entirely");
343
+
344
+ // A long list scrolls: 10 rows visible, the cursor always inside the window, and one
345
+ // frame height whether the cursor sits at the top or the bottom.
346
+ const many = nameRows(Array.from({ length: 25 }, (_, i) => `m${i}`));
347
+ const scrolled = new ListPicker(fakeTheme, many, "m0", { preview: quiet, revert: quiet, done: quiet, requestRender: quiet }, { title: screenTitle("Test"), description: "d", legend: "l" }, false, undefined, 10);
348
+ const countItems = (ls: string[]): number => ls.filter((l) => /m\d/.test(l)).length;
349
+ let frame = scrolled.render(50);
350
+ assert(countItems(frame) === 10, "a scrolled list shows exactly 10 model rows");
351
+ assert(frame.some((l) => l.includes("↓ 15 more")) && !frame.some((l) => l.includes("↑")), "the top of the list announces only what is below");
352
+ for (let i = 0; i < 14; i++) scrolled.handleInput("\x1b[B");
353
+ frame = scrolled.render(50);
354
+ assert(countItems(frame) === 10, "still 10 rows after scrolling");
355
+ assert(frame.some((l) => l.includes("↑ 9 more")) && frame.some((l) => l.includes("↓ 6 more")), "both ends announce their hidden rows");
356
+ assert(frame.some((l) => l.includes("→ m14")), "the cursor row stays visible");
357
+ scrolled.handleInput("\x1b[B");
358
+ const frameNext = scrolled.render(50);
359
+ assert(frameNext.length === frame.length && countItems(frameNext) === 10, "the frame height stays constant while scrolling inside the list");
360
+ for (let i = 0; i < 20; i++) scrolled.handleInput("\x1b[B");
361
+ frame = scrolled.render(50);
362
+ assert(frame.some((l) => l.includes("→ m24")) && frame.some((l) => l.includes("↑ 15 more")) && !frame.some((l) => l.includes("↓")), "the bottom of the list announces only what is above");
363
+ const short = new ListPicker(fakeTheme, nameRows(["a", "b"]), "a", { preview: quiet, revert: quiet, done: quiet, requestRender: quiet }, { title: screenTitle("Test"), description: "d", legend: "l" }, false, undefined, 10);
364
+ assert(!short.render(50).some((l) => l.includes("more")), "a short list shows no scroll indicators");
365
+
366
+ // The text field: the pi-tui editor drives, the arnative box frames it.
367
+ let submitted: string | null | undefined;
368
+ let inputCancelled = false;
369
+ const field = new InputPicker(fakeTheme, { title: screenTitle("Provider"), description: "Endpoint API — the base URL", legend: INPUT_LEGEND }, "", {
370
+ done: (v) => { submitted = v; },
371
+ cancel: () => { inputCancelled = true; },
372
+ requestRender: quiet,
373
+ }, "https://api.example.com/v1");
374
+ field.focused = true;
375
+ const fieldLines = field.render(60);
376
+ // CSI and every APC wrapper (`\x1b_…\x07`): pi-tui 0.87 emitted only `_pi:c`, 1.4 adds
377
+ // `_pi:fc`/`_pi:/fc` around the placeholder — a narrow strip left escapes glued to the
378
+ // text and failed the include on CI's newer version.
379
+ const plain = (s: string): string => s.replace(/\x1b\[[0-9;]*[A-Za-z]/g, "").replace(/\x1b_.*?\x07/g, "");
380
+ assert(fieldLines[0]!.startsWith("╭") && fieldLines[1]!.includes("Provider - Arnative"), "the input renders in the arnative box");
381
+ assert(fieldLines.some((l) => plain(l).includes("> https://api.example.com/v1")), "an empty field shows its dim placeholder");
382
+ assert(fieldLines.some((l) => l.includes(INPUT_LEGEND)), "the input legend is pinned");
383
+ for (const ch of "https://x.io") field.handleInput(ch);
384
+ field.handleInput("\x1b[D");
385
+ field.handleInput("io");
386
+ assert(field.getValue() === "https://x.iioo", "typing with a moved cursor edits at the cursor");
387
+ field.handleInput("\r");
388
+ assert(submitted === "https://x.iioo", "Enter submits the value");
389
+ assert(!inputCancelled, "Enter is not a cancel");
390
+ field.handleInput("\x1b");
391
+ assert(inputCancelled, "Esc cancels the field");
392
+ console.log("list-picker.ts self-check OK");
393
+ }
@@ -9,7 +9,7 @@
9
9
  * Reads are memoised per process; every write re-reads the file and replaces it atomically
10
10
  * (temp file + rename), so concurrent pi sessions that write different keys keep both.
11
11
  */
12
- import { mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
12
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
13
13
  import { tmpdir } from "node:os";
14
14
  import { dirname, join } from "node:path";
15
15
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
@@ -19,21 +19,52 @@ export const HEADER_PRESET_KEY = "headerPreset";
19
19
  export const FOOTER_PRESET_KEY = "footerPreset";
20
20
 
21
21
  // Resolved per call, not at import: the self-check points getAgentDir() at a fixture dir.
22
- const configPath = (): string => join(getAgentDir(), "arnative-config.json");
22
+ // Everything pi-arnative writes lives in one folder (agent dir/arnative); the config moved
23
+ // there from a flat arnative-config.json, which is migrated in on first read.
24
+ const configDir = (): string => join(getAgentDir(), "arnative");
25
+ const configPath = (): string => join(configDir(), "config.json");
26
+ const legacyConfigPath = (): string => join(getAgentDir(), "arnative-config.json");
27
+
28
+ /** Layout "1": every file this package writes lives under `<agent>/arnative` — the flat
29
+ * `arnative-*.json` files are moved on first read, a leftover a downgrade recreated next
30
+ * to the folder copy is removed, and `layoutVersion` in config.json records the layout so
31
+ * the next layout change has one stamp to migrate from. */
32
+ const LAYOUT_VERSION = "1";
23
33
 
24
34
  let memo: Record<string, unknown> | null = null;
25
35
 
26
- function readDisk(): Record<string, unknown> {
36
+ function readDisk(): { parsed: boolean; record: Record<string, unknown> } {
27
37
  try {
38
+ // One-time move into the arnative folder (was a flat file next to it).
39
+ if (!existsSync(configPath()) && existsSync(legacyConfigPath())) {
40
+ mkdirSync(configDir(), { recursive: true });
41
+ renameSync(legacyConfigPath(), configPath());
42
+ } else if (existsSync(legacyConfigPath())) {
43
+ // Both exist — a downgrade recreated the flat file next to the folder copy. The
44
+ // folder copy belongs to the newer layout, so the flat one is dead.
45
+ rmSync(legacyConfigPath());
46
+ }
28
47
  const raw = JSON.parse(readFileSync(configPath(), "utf8")) as unknown;
29
- if (raw && typeof raw === "object" && !Array.isArray(raw)) return raw as Record<string, unknown>;
48
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) return { parsed: true, record: raw as Record<string, unknown> };
49
+ return { parsed: false, record: {} }; // readable JSON of the wrong shape: read as empty, never rewritten
30
50
  } catch {
31
51
  // absent, unreadable or corrupt: fall back to defaults rather than crash the header
52
+ return { parsed: false, record: {} };
32
53
  }
33
- return {};
34
54
  }
35
55
 
36
- const readConfig = (): Record<string, unknown> => (memo ??= readDisk());
56
+ const readConfig = (): Record<string, unknown> => {
57
+ if (memo) return memo;
58
+ const { parsed, record } = readDisk();
59
+ memo = record;
60
+ // Stamp once per layout version (idempotent; saveChoice re-reads and merges, so a
61
+ // concurrent session's keys survive the write) — but only over an absent file or a
62
+ // cleanly parsed one: a corrupt or transiently unreadable config must never be wiped.
63
+ if ((parsed || !existsSync(configPath())) && memo.layoutVersion !== LAYOUT_VERSION) {
64
+ saveChoice("layoutVersion", LAYOUT_VERSION);
65
+ }
66
+ return memo;
67
+ };
37
68
 
38
69
  /** The stored value for `key`, or undefined when absent or not one of `allowed`. */
39
70
  export function loadChoice<T extends string>(key: string, allowed: readonly T[]): T | undefined {
@@ -45,7 +76,7 @@ export function loadChoice<T extends string>(key: string, allowed: readonly T[])
45
76
  export function saveChoice(key: string, value: string): void {
46
77
  if (readConfig()[key] === value) return;
47
78
  // Re-read: another pi session may have written its own key since this one loaded.
48
- memo = { ...readDisk(), [key]: value };
79
+ memo = { ...readDisk().record, [key]: value };
49
80
  try {
50
81
  const path = configPath();
51
82
  const tmp = `${path}.${process.pid}.tmp`;
@@ -75,7 +106,7 @@ if (isMain(import.meta.url)) {
75
106
  assert(loadChoice(FOOTER_PRESET_KEY, ["a", "b"] as const) === "a", "a second key is stored without clobbering the first");
76
107
 
77
108
  // Another pi session writes its own key after this one loaded; a save must keep it.
78
- writeFileSync(join(fixture, "arnative-config.json"), JSON.stringify({ headerPreset: "b", footerPreset: "a", other: "x" }), "utf8");
109
+ writeFileSync(join(fixture, "arnative", "config.json"), JSON.stringify({ headerPreset: "b", footerPreset: "a", other: "x" }), "utf8");
79
110
  saveChoice(FOOTER_PRESET_KEY, "b");
80
111
  resetPresetCache();
81
112
  assert(loadChoice("other", ["x"] as const) === "x", "a key written by another process survives a save");
@@ -89,9 +120,36 @@ if (isMain(import.meta.url)) {
89
120
  assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === undefined, "an unknown stored value is rejected");
90
121
 
91
122
  // A corrupt file must not throw on the header's render path.
92
- writeFileSync(join(fixture, "arnative-config.json"), "{not json", "utf8");
123
+ writeFileSync(join(fixture, "arnative", "config.json"), "{not json", "utf8");
93
124
  resetPresetCache();
94
125
  assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === undefined, "a corrupt config file reads as empty");
126
+ assert(readFileSync(join(fixture, "arnative", "config.json"), "utf8") === "{not json", "a corrupt config is left untouched — no stamp over it");
127
+
128
+ // The flat pre-folder config is moved into the arnative folder on first read.
129
+ const mig = mkdtempSync(join(tmpdir(), "arnative-preset-mig-"));
130
+ process.env.PI_CODING_AGENT_DIR = mig;
131
+ writeFileSync(join(mig, "arnative-config.json"), JSON.stringify({ headerPreset: "b" }), "utf8");
132
+ resetPresetCache();
133
+ assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "a legacy flat config is migrated and read");
134
+ assert(existsSync(join(mig, "arnative", "config.json")), "the migrated config lives in the arnative folder");
135
+ rmSync(mig, { recursive: true, force: true });
136
+
137
+ // Layout stamp: the folder copy wins over a stale flat file a downgrade recreated,
138
+ // the stale file is removed, and stamping merges into the config instead of replacing it.
139
+ const stamp = mkdtempSync(join(tmpdir(), "arnative-preset-stamp-"));
140
+ process.env.PI_CODING_AGENT_DIR = stamp;
141
+ mkdirSync(join(stamp, "arnative"), { recursive: true });
142
+ writeFileSync(join(stamp, "arnative", "config.json"), JSON.stringify({ headerPreset: "b" }), "utf8");
143
+ writeFileSync(join(stamp, "arnative-config.json"), JSON.stringify({ headerPreset: "a" }), "utf8"); // stale, from a downgrade
144
+ resetPresetCache();
145
+ assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "the folder copy wins over the stale flat file");
146
+ assert(!existsSync(join(stamp, "arnative-config.json")), "the stale flat config is removed");
147
+ assert(loadChoice("layoutVersion", ["1"] as const) === "1", "the layout stamp is written on first read");
148
+ const stamped = JSON.parse(readFileSync(join(stamp, "arnative", "config.json"), "utf8")) as Record<string, unknown>;
149
+ assert(stamped.headerPreset === "b" && stamped.layoutVersion === "1", "stamping merges, it does not replace");
150
+ rmSync(stamp, { recursive: true, force: true });
151
+ process.env.PI_CODING_AGENT_DIR = fixture;
152
+ resetPresetCache();
95
153
 
96
154
  rmSync(fixture, { recursive: true, force: true });
97
155
  console.log("preset-store.ts self-check OK");