@bismawy/pi-arnative 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/box.ts CHANGED
@@ -4,9 +4,42 @@
4
4
  * never loads it as an extension.
5
5
  */
6
6
  import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
7
- import { thinkingColorOf } from "./ansi.ts";
7
+ import { stripAnsi, thinkingColorOf } from "./ansi.ts";
8
8
  import { assert, isMain } from "./check.ts";
9
9
 
10
+ /** A clickable span inside rendered lines: 0-based cell columns, inclusive. */
11
+ export interface TextSpan {
12
+ row: number;
13
+ start: number;
14
+ end: number;
15
+ }
16
+
17
+ /**
18
+ * Where `text` sits in each rendered line, in cell columns. A mouse handler needs this to
19
+ * make one piece of a box clickable and leave the rest to pi: a press the handler does not
20
+ * take stays with the text selection, so a box can be clicked and copied at once.
21
+ * A line that shows the text in part (narrow width) yields no span, so a clipped label is
22
+ * never half-clickable.
23
+ */
24
+ export function textSpans(lines: readonly string[], text: string): TextSpan[] {
25
+ if (!text) return [];
26
+ const width = visibleWidth(text) - 1;
27
+ const spans: TextSpan[] = [];
28
+ lines.forEach((line, row) => {
29
+ const plain = stripAnsi(line);
30
+ const at = plain.indexOf(text);
31
+ if (at >= 0) {
32
+ const start = visibleWidth(plain.slice(0, at));
33
+ spans.push({ row, start, end: start + width });
34
+ }
35
+ });
36
+ return spans;
37
+ }
38
+
39
+ /** Whether the 0-based cell `x` on `row` lands inside one of `spans`. */
40
+ export const inSpans = (spans: readonly TextSpan[], row: number, x: number): boolean =>
41
+ spans.some((span) => span.row === row && x >= span.start && x <= span.end);
42
+
10
43
  export type BoxTheme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; bold?(text: string): string };
11
44
  type Dim = (s: string) => string;
12
45
 
@@ -72,26 +105,47 @@ export function renderScreen(
72
105
  ].map((l) => truncateToWidth(l, width, ""));
73
106
  }
74
107
 
75
- /** Wrap `rows` (plain or ANSI-colored) into a box. `bgType` = theme bg name (no-op when the theme has no `bg`); `borderColor` = border color.
76
- * `theme` may be null: a box is patched in at module load, before `session_start`
77
- * delivers the active theme. An uncolored box for that first frame beats a null
78
- * deref that kills the process. */
79
- export function renderBoxLines(theme: BoxTheme | null, width: number, rows: string[], bgType?: string, borderColor = "dim"): string[] {
80
- const dim = (s: string) => (theme ? theme.fg(borderColor, s) : s);
108
+ /** Border paint: a theme token name, or a painter for a tier that has no token (the thinking
109
+ * slots, which `thinkingColorOf` resolves). */
110
+ export type BoxBorder = string | ((text: string) => string);
111
+
112
+ /** `renderBoxLines` plus where each input row landed: `starts[i]` is the first line index of
113
+ * `rows[i]`. A caller that hit-tests a row (the task list's scroll counters) needs this,
114
+ * because a row long enough to wrap occupies more than one line. */
115
+ export function renderBoxRows(
116
+ theme: BoxTheme | null,
117
+ width: number,
118
+ rows: string[],
119
+ bgType?: string,
120
+ border: BoxBorder = "dim",
121
+ ): { lines: string[]; starts: number[] } {
122
+ const dim = typeof border === "string" ? (s: string) => (theme ? theme.fg(border, s) : s) : border;
81
123
  const inner = Math.max(8, width - 4);
82
124
  const lines = [boxEdge("╭", "╮", width, dim)];
125
+ const starts: number[] = [];
83
126
  for (const row of rows) {
127
+ starts.push(lines.length);
84
128
  for (const line of wrapTextWithAnsi(row, inner)) lines.push(boxRow(line, width, dim));
85
129
  }
86
130
  lines.push(boxEdge("╰", "╯", width, dim));
87
- if (bgType && theme?.bg) {
131
+ const paint = (input: string[]) => {
132
+ if (!bgType || !theme?.bg) return input;
88
133
  try {
89
- return lines.map((l) => applyBg(l, width, (s) => theme!.bg!(bgType, s)));
134
+ return input.map((l) => applyBg(l, width, (s) => theme!.bg!(bgType, s)));
90
135
  } catch {
91
- return lines;
136
+ return input;
92
137
  }
93
- }
94
- return lines;
138
+ };
139
+ return { lines: paint(lines), starts };
140
+ }
141
+
142
+ /** The box around `rows`. `bgType` = theme bg name (no-op when the theme has no `bg`);
143
+ * `borderColor` = border color.
144
+ * `theme` may be null: a box is patched in at module load, before `session_start`
145
+ * delivers the active theme. An uncolored box for that first frame beats a null
146
+ * deref that kills the process. */
147
+ export function renderBoxLines(theme: BoxTheme | null, width: number, rows: string[], bgType?: string, border: BoxBorder = "dim"): string[] {
148
+ return renderBoxRows(theme, width, rows, bgType, border).lines;
95
149
  }
96
150
 
97
151
  if (isMain(import.meta.url)) {
@@ -146,5 +200,16 @@ if (isMain(import.meta.url)) {
146
200
  `a long description keeps the right wall at width ${w}`,
147
201
  );
148
202
  }
203
+ // Click target on a piece of text: cells, not characters, and nothing when clipped.
204
+ const line = renderBoxRows(th, 40, ["Todos (3/7) [click to expand]"], undefined, undefined).lines[1]!;
205
+ const spans = textSpans([line], "[click to expand]");
206
+ assert(spans.length === 1 && spans[0]!.row === 0, "textSpans finds the hint on its row");
207
+ assert(spans[0]!.start === visibleWidth("│ Todos (3/7) "), `span starts at the hint, got ${spans[0]!.start}`);
208
+ assert(inSpans(spans, 0, spans[0]!.start) && inSpans(spans, 0, spans[0]!.end), "span covers the first and last cell");
209
+ assert(!inSpans(spans, 0, spans[0]!.start - 1) && !inSpans(spans, 1, spans[0]!.start), "span excludes the cell before and other rows");
210
+ assert(textSpans([boxRow("Todos (3/7) [click to exp…", 24, (t) => t)], "[click to expand]").length === 0, "a clipped hint is not clickable");
211
+ // Wide characters before the hint shift cells, not characters.
212
+ const wide = textSpans([boxRow("日本 [x]", 24, (t) => t)], "[x]");
213
+ assert(wide[0]!.start === visibleWidth("│ 日本 "), `a wide glyph shifts by cells, got ${wide[0]!.start}`);
149
214
  console.log("lib/box.ts OK");
150
215
  }
@@ -310,9 +310,6 @@ export class InputPicker implements Component, Focusable {
310
310
  }
311
311
  }
312
312
 
313
- /** Title of a sub-screen, derived from `screenTitle` so the format lives in one place. */
314
- export const pickerTitle = (setting: string): ScreenText["title"] => screenTitle(setting);
315
-
316
313
  // Self-check: `node lib/list-picker.ts`
317
314
  if (isMain(import.meta.url)) {
318
315
  assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Open [Esc] Close", "root legend pinned, no ← behind the root menu");
@@ -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 { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
12
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, 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";
@@ -72,8 +72,21 @@ export function loadChoice<T extends string>(key: string, allowed: readonly T[])
72
72
  return typeof value === "string" && (allowed as readonly string[]).includes(value) ? (value as T) : undefined;
73
73
  }
74
74
 
75
+ /** Reading order of `config.json`: the presets in the order the settings menu shows them,
76
+ * then `layoutVersion`, then anything else (a key from another module or a newer version).
77
+ * Times a user edits the file by hand or reads it back. */
78
+ const KEY_ORDER = ["headerPreset", "footerPreset", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "modelHeal"];
79
+
80
+ /** The record in {@link KEY_ORDER}; unknown keys keep the order they were written in. */
81
+ function ordered(record: Record<string, unknown>): Record<string, unknown> {
82
+ const out: Record<string, unknown> = {};
83
+ for (const key of KEY_ORDER) if (Object.hasOwn(record, key)) out[key] = record[key];
84
+ for (const [key, value] of Object.entries(record)) if (!Object.hasOwn(out, key)) out[key] = value;
85
+ return out;
86
+ }
87
+
75
88
  /** Store a choice. Best effort: an unwritable agent dir must not break the TUI. */
76
- export function saveChoice(key: string, value: string): void {
89
+ export function saveChoice(key: string, value: string, rename: (from: string, to: string) => void = renameSync): void {
77
90
  if (readConfig()[key] === value) return;
78
91
  // Re-read: another pi session may have written its own key since this one loaded.
79
92
  memo = { ...readDisk().record, [key]: value };
@@ -81,13 +94,35 @@ export function saveChoice(key: string, value: string): void {
81
94
  const path = configPath();
82
95
  const tmp = `${path}.${process.pid}.tmp`;
83
96
  mkdirSync(dirname(path), { recursive: true });
84
- writeFileSync(tmp, `${JSON.stringify(memo, null, 2)}\n`, "utf8");
85
- renameSync(tmp, path);
97
+ const payload = `${JSON.stringify(ordered(memo), null, 2)}\n`;
98
+ writeFileSync(tmp, payload, "utf8");
99
+ try {
100
+ rename(tmp, path);
101
+ } catch (e) {
102
+ // Windows: a running pi session can hold config.json open, and then the atomic
103
+ // replace fails with EPERM while an in-place write still lands. A setting that
104
+ // silently never reaches disk is worse than the small truncation window here.
105
+ const code = (e as NodeJS.ErrnoException).code;
106
+ if (code !== "EPERM" && code !== "EBUSY" && code !== "EXDEV") throw e;
107
+ writeFileSync(path, payload, "utf8");
108
+ rmSync(tmp, { force: true });
109
+ }
86
110
  } catch {
87
111
  // ignore: the choice still applies for this session
88
112
  }
89
113
  }
90
114
 
115
+ /** Record the choices in use, so `config.json` names every preset instead of only the ones a
116
+ * user changed — a fresh install then reads a complete profile instead of an empty file.
117
+ * Runs at `session_start`; after the first run every key already matches and nothing is
118
+ * written. A present-but-unreadable config is never replaced by this partial record (the
119
+ * same rule the layout stamp follows), because that would drop the other keys. */
120
+ export function ensureChoices(values: Record<string, string>): void {
121
+ const { parsed } = readDisk();
122
+ if (!parsed && existsSync(configPath())) return;
123
+ for (const [key, value] of Object.entries(values)) saveChoice(key, value);
124
+ }
125
+
91
126
  /** Drop the in-memory copy so the next read hits disk (a restart, in a test). */
92
127
  export function resetPresetCache(): void {
93
128
  memo = null;
@@ -148,6 +183,50 @@ if (isMain(import.meta.url)) {
148
183
  const stamped = JSON.parse(readFileSync(join(stamp, "arnative", "config.json"), "utf8")) as Record<string, unknown>;
149
184
  assert(stamped.headerPreset === "b" && stamped.layoutVersion === "1", "stamping merges, it does not replace");
150
185
  rmSync(stamp, { recursive: true, force: true });
186
+
187
+ // The startup record names every choice, including the ones still at their default.
188
+ const profile = mkdtempSync(join(tmpdir(), "arnative-preset-profile-"));
189
+ process.env.PI_CODING_AGENT_DIR = profile;
190
+ resetPresetCache();
191
+ ensureChoices({ headerPreset: "Arnative (Full)", footerPreset: "Arnative (Full)" });
192
+ assert(loadChoice(HEADER_PRESET_KEY, ["Arnative (Full)"] as const) === "Arnative (Full)", "a default choice is written, not skipped");
193
+ assert(loadChoice(FOOTER_PRESET_KEY, ["Arnative (Full)"] as const) === "Arnative (Full)", "every key in the batch is written");
194
+ const profiled = readFileSync(join(profile, "arnative", "config.json"), "utf8");
195
+ ensureChoices({ headerPreset: "Arnative (Full)", footerPreset: "Arnative (Full)" });
196
+ assert(readFileSync(join(profile, "arnative", "config.json"), "utf8") === profiled, "a second record writes nothing");
197
+
198
+ // The file keeps one key order whatever order the writes arrived in.
199
+ const keyOrder = () => Object.keys(JSON.parse(readFileSync(join(profile, "arnative", "config.json"), "utf8")) as Record<string, unknown>);
200
+ assert(
201
+ keyOrder().join(",") === "headerPreset,footerPreset,layoutVersion",
202
+ "known keys follow KEY_ORDER, layoutVersion after the presets: " + keyOrder().join(","),
203
+ );
204
+ saveChoice("spinnerPreset", "Circle Wave");
205
+ saveChoice("zzz-other", "x");
206
+ assert(
207
+ keyOrder().join(",") === "headerPreset,footerPreset,spinnerPreset,layoutVersion,zzz-other",
208
+ "a newly written key slots into place, an unknown one goes last: " + keyOrder().join(","),
209
+ );
210
+
211
+ // Windows: a running pi session can hold the file open, so the atomic replace fails
212
+ // while the setting still has to land. The seam stands in for that rename.
213
+ const locked = () => {
214
+ throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" });
215
+ };
216
+ saveChoice(HEADER_PRESET_KEY, "b", locked);
217
+ resetPresetCache();
218
+ assert(loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "a refused rename still writes the choice in place");
219
+ saveChoice(FOOTER_PRESET_KEY, "a", locked);
220
+ resetPresetCache();
221
+ assert(loadChoice(FOOTER_PRESET_KEY, ["a", "b"] as const) === "a" && loadChoice(HEADER_PRESET_KEY, ["a", "b"] as const) === "b", "the in-place write keeps the other keys");
222
+ assert(!existsSync(join(profile, "arnative")) || readdirSync(join(profile, "arnative")).every((f) => !f.endsWith(".tmp")), "no temp file is left behind");
223
+
224
+ writeFileSync(join(profile, "arnative", "config.json"), "{not json", "utf8");
225
+ resetPresetCache();
226
+ ensureChoices({ headerPreset: "b" });
227
+ assert(readFileSync(join(profile, "arnative", "config.json"), "utf8") === "{not json", "the startup record leaves an unreadable config alone");
228
+ rmSync(profile, { recursive: true, force: true });
229
+
151
230
  process.env.PI_CODING_AGENT_DIR = fixture;
152
231
  resetPresetCache();
153
232
 
package/lib/shortcuts.ts CHANGED
@@ -35,6 +35,11 @@ export const SHORTCUT_RELOAD = build("r");
35
35
  /** Expand/collapse the minimal footer. Ctrl+alt+m on macOS/Linux, alt+m on Windows/WSL
36
36
  * (same platform split as the shortcuts above). */
37
37
  export const SHORTCUT_TOGGLE_FOOTER = build("m");
38
+ /** Expand/collapse the task list widget. Same platform split: Alt+o on Windows/WSL. */
39
+ export const SHORTCUT_TOGGLE_TODOS = build("o");
40
+ /** Scroll the expanded task list: `j` down, `k` up, one task per press. */
41
+ export const SHORTCUT_SCROLL_TODOS_DOWN = build("j");
42
+ export const SHORTCUT_SCROLL_TODOS_UP = build("k");
38
43
 
39
44
  /** The one "go back" key: `←` leaves a screen for its parent, while Esc closes or reverts
40
45
  * it. Defined here so no screen can advertise a key another screen does not handle. */
@@ -71,6 +76,8 @@ export const LEGEND_ROOT = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"],
71
76
  export const LEGEND_MOVE = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"], [BACK.label, "Back"], [CANCEL.label, "Close"]);
72
77
  /** Live-preview list: moving applies, Enter keeps, `←` steps out, Esc reverts. */
73
78
  export const LEGEND_LIVE = legend([MOVE.label, "Preview"], [CHOOSE.label, "Select"], [BACK.label, "Back"], [CANCEL.label, "Revert"]);
79
+ /** A list you only read (the `/todos` recap): moving changes nothing, so there is no Open. */
80
+ export const LEGEND_READ_ONLY = legend([MOVE.label, "Move"], [CANCEL.label, "Close"]);
74
81
  /** The read-only usage dashboard. The full legend needs the room, so a narrow box degrades. */
75
82
  export function legendUsage(width: number): string {
76
83
  const full = legend([MOVE.label, "Move"], ["Click", "Open/close"], [BACK.label, "Back"], [QUIT.label, "Exit"]);
@@ -112,6 +119,7 @@ if (isMain(import.meta.url)) {
112
119
  // advertised on one screen and handled on none.
113
120
  assert(LEGEND_MOVE === "[↑↓] Move [Enter] Open [←] Back [Esc] Close", `root menu legend pinned, got ${LEGEND_MOVE}`);
114
121
  assert(LEGEND_MOVE.includes("[←] Back"), "the root menu advertises ← Back");
122
+ assert(LEGEND_READ_ONLY === "[↑↓] Move [Esc] Close", `read-only legend pinned, got ${LEGEND_READ_ONLY}`);
115
123
  assert(
116
124
  LEGEND_LIVE === `[↑↓] Preview [Enter] Select [${BACK_KEY_LABEL}] Back [Esc] Revert`,
117
125
  `live legend pinned, got ${LEGEND_LIVE}`,