@bismawy/pi-arnative 0.6.2 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.7.0] - 2026-10-24
4
+
5
+ ### Added
6
+ - **Providers: a custom endpoint from three inputs.** `/arnative` → **Providers** asks for the endpoint URL, API key, and name, then probes the endpoint once (Ollama `/api/tags`, Gemini `/v1beta/models`, OpenAI/Anthropic `/models` lists), lists the models it answered with, and saves on Space-picked selection — the key into `auth.json` (the file `/login` writes), the declaration into `models.json`. `[a]` switches the API flavor when a relay answers in an ambiguous shape; no answer falls back to manual ids. Opening `/model` picks up the saved provider (`extensions/provider.ts`).
7
+ - **Provider actions: edit and delete on Enter.** Enter on a stored provider opens an action menu — Select models, Probe models (re-reads the endpoint, vanished models stay listed), Thinking, Delete. Every action writes through to `models.json` immediately (delete also removes the `auth.json` key); sibling provider fields like `compat` survive every edit.
8
+ - **Reasoning auto-detection.** Model ids decide the thinking flag on save: a `thinking`/`reasoner` token, an effort suffix (`-high`/`-medium`/`-low`), or an o1/o3/o4/r1-style generation marks reasoning models — `ag/claude-opus-4-6-thinking` and `ag/gemini-4-argon-high` on, `wally/glm-5.3-flash` off. The Thinking screen lists the flags with the detected values and Space overrides them.
9
+ - **Thinking levels on pi's full scale.** The Thinking screen no longer toggles a boolean: Space cycles each model through `off → auto → minimal → low → medium → high → xhigh → max`, detected from the id (an explicit `-high`/`-xhigh`/`-max`… suffix pins that level; a `thinking`/`reasoner`/o1/r1 token means `auto`). Levels write pi's own wire shape — `reasoning: true` plus a `thinkingLevelMap` that pins exactly the supported level — so `/think` offers the model's real levels and clamps to them (`xhigh`/`max` only appear when mapped, exactly as pi's schema defines).
10
+ - **Scrolling model lists.** The shared picker gains a 10-row viewport: long relay catalogs scroll a window centered on the cursor, with `↑ N more` / `↓ N more` rows announcing what is hidden, so the box keeps one height (`lib/list-picker.ts`).
11
+ - **Picked count in the models legend.** The models picker footer reads `34/44 picked · [↑↓] Move …` with the count in the accent color, next to the keys it describes (`lib/box.ts` renders a pre-styled legend verbatim).
12
+ - **Back where it belongs.** `←` works in submenus only: the provider list steps back to the `/arnative` menu, the provider actions step back to the list, and every settings screen keeps its `[←] Back` legend. The root menu hides the key entirely (`back: false`) — it has nothing behind it, so Esc and `q` stay the only closes and its legend reads `[↑↓] Move [Enter] Open [Esc] Close`. Fill screens (model pick, thinking levels) hide it too, so a stray `←` cannot throw away a half-picked list.
13
+ - **The provider list reflects its own edits.** After adding, editing or deleting a provider, the Providers screen re-reads `models.json` instead of showing the copy it opened with — a new provider appears immediately, no `/arnative` round-trip.
14
+ - **Wizard prompts in the arnative box.** Every text field the provider wizard asks for (endpoint, key, name, manual ids, headless fallbacks) renders as an arnative screen: rounded thinking-colored border, `Provider - Arnative⠙` title, the field as the description, a `> ` prompt with the pi-tui editor underneath (arrows, word motions, paste, undo all work), a dim example while empty, and the `[Enter] Save [Esc] Cancel` legend — replacing pi's full-width native input dialog (`lib/list-picker.ts`, `InputPicker`).
15
+ - **Probe status above the chat input.** While the wizard probes an endpoint (add flow and the Probe models action), a one-line dim `probing endpoint…` appears directly above the chat input (pi's `setWidget` aboveEditor slot) and disappears the moment the probe settles — no longer a status row in the bottom footer (`lib/provider.ts`, `probingStatus`).
16
+ - **All pi-arnative files in one folder, cache 55% smaller.** Everything the package writes now lives under `~/.pi/agent/arnative/` — `config.json` (preset choices) and `usage-cache.json` (the `/usage` scan cache) — instead of three flat `arnative-*.json` files in `~/.pi/agent/`; existing files are migrated in automatically on first read. The cache gained a compact disk shape: keys are session-dir-relative paths, rollups store one row per provider+model (provider rows are derived on load), and one-letter field names — 90 KB shrank to 40 KB on a real machine with identical answers. The legacy `arnative-prices.json` is deleted from the disk on first load (nothing has read it since pricing moved into `cost` fields in pi's `models.json`, which the provider wizard fills in), and a flat file a downgrade recreated beside the folder copy is removed the same way; `config.json` stamps a `layoutVersion` so the next layout change has one hook to migrate from. Preset choices and the cache are never deleted — only moved (`lib/preset-store.ts`, `lib/usage-store.ts`).
17
+ - **Footer diff stat now tracks edits as they land.** The git refresh ran only at session and turn start, so a session that edits or commits inside a turn (the normal pattern when each step is committed) kept showing the pre-turn snapshot — often clean — and the `+X -Y` working-tree diff never appeared. The footer now re-reads git state whenever a tool call finishes (edit, write, or a commit through bash); concurrent refreshes still coalesce into at most two `git` runs per burst (`extensions/footer.ts`).
18
+
19
+ ### Changed
20
+ - **`/arnative` → Themes lists this package's themes only.** The picker shows the `arnative` family (`arnative` and its variants) and nothing else — pi's own `system`/`dark`/`light` and a theme of your own (e.g. `omarchy-system`) stay in `/settings` → Theme, which keeps the full list. Esc still reverts to whatever theme was active when the picker opened, arnative or not, and the empty-list message now points at a reinstall instead of the themes folder (`extensions/arnative.ts`).
21
+
22
+ ### Fixed
23
+ - **Esc cancels the add-provider flow at every prompt.** The flow asked for endpoint, API key and provider name, but only Esc at the first prompt aborted: Esc at the key prompt continued keyless (and could save a provider with a dummy key that never authenticates), Esc at the name prompt silently accepted the suggested name. Both prompts now honor the `[Esc] Cancel` their legend promises — Enter on an empty key field still means keyless, and an empty name still accepts the suggestion (`lib/provider.ts`).
24
+ - **Provider config writes are atomic.** `writeJson` wrote `models.json` and `auth.json` with a direct `writeFileSync`, so a crash or power loss mid-write could truncate them — a truncated `auth.json` breaks the stored credentials of every provider, and the wizard then refuses to save until the file is repaired by hand. It now writes a temp file and renames it over the target, the same pattern `preset-store.ts` and `usage-store.ts` already use, and the self-check proves an interrupted save leaves the previous config intact (`lib/provider.ts`).
25
+
3
26
  ## [0.6.2] - 2026-10-20
4
27
 
5
28
  ### Fixed
package/README.md CHANGED
@@ -18,12 +18,13 @@ pi-arnative replaces pi’s default terminal chrome with a unified, cohesive vis
18
18
  - Enhanced Footer: 3-row status grid tracking branch, active duration (30s idle freeze), and token speed.
19
19
  - Transcript Clock: Timestamps for conversation messages with clean bubble backgrounds.
20
20
  - Usage Dashboard: Real-time token counts and cost tracking across all local sessions via `/usage`.
21
+ - Custom Providers: any OpenAI-, Anthropic-, Gemini- or Ollama-compatible endpoint from three inputs — URL, key, name; models are probed and picked, saved to pi's own `models.json`/`auth.json`. Enter on a stored provider edits: reselect models, re-probe the endpoint, cycle per-model thinking levels (off → auto → minimal → low → medium → high → xhigh → max, auto-detected from ids), or delete.
21
22
 
22
23
  <details>
23
24
  <summary><b>Configuration & Presets</b></summary>
24
25
 
25
26
  ### Working Spinner Presets
26
- Configurable via `/arnative` → **Animations** (saved to `arnative-config.json`).
27
+ Configurable via `/arnative` → **Animations** (saved to `~/.pi/agent/arnative/config.json`).
27
28
  Features 18 presets with live animated preview in the picker (`Arnative` as default, `Pi (system)`, and alphabetical variants). Press `[g]` in the picker to toggle Google brand gradient sweep on accent presets.
28
29
 
29
30
  ### Footer Presets
@@ -58,7 +59,7 @@ npm run dev
58
59
  | `ctrl+alt+n` · `alt+n` | New session (`/new`) |
59
60
  | `ctrl+alt+m` · `alt+m` | Toggle Minimal footer |
60
61
  | `/usage` | Token & cost dashboard (or `/arnative` → **Usage**) |
61
- | `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Usage) |
62
+ | `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Providers, Usage) |
62
63
  | Click tool / `ctrl+o` | Toggle tool output box |
63
64
  | `←` | Back — step back from submenus/dashboard to menu |
64
65
 
@@ -92,6 +93,8 @@ To bind `app.session.new` in `~/.pi/agent/keybindings.json`:
92
93
  | `extensions/animations.ts` | Working spinner presets and `/arnative` → Animations picker |
93
94
  | `lib/spinner.ts` | Spinner preset catalog: frames, cadence, and painters |
94
95
  | `extensions/arnative.ts` | Settings menu with live preview and navigation |
96
+ | `lib/provider.ts` | Custom provider wizard: probe, model pick, edit actions, `models.json`/`auth.json` save |
97
+ | `lib/list-picker.ts` | The live-preview/multi-select picker every arnative screen shares |
95
98
  | `extensions/timestamps.ts` | Message timestamps and bubble backgrounds |
96
99
  | `extensions/ui-render-tweaks.ts` | Contrast tweaks, selection style, and UI polish |
97
100
  | `extensions/usage.ts` | Token and cost dashboard (`/usage`) |
@@ -6,12 +6,11 @@
6
6
  * the session's thinking slot (`lib/ansi.ts`), so it belongs to the active model.
7
7
  */
8
8
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
9
- import { matchesKey, truncateToWidth, visibleWidth, type AutocompleteItem, type Component } from "@earendil-works/pi-tui";
10
- import { softSecondaryOf, stripAnsi, thinkingColorOf } from "../lib/ansi.ts";
11
- import { renderScreen, screenTitle, type ScreenText } from "../lib/box.ts";
9
+ import { visibleWidth, type AutocompleteItem } from "@earendil-works/pi-tui";
10
+ import { stripAnsi } from "../lib/ansi.ts";
11
+ import { screenTitle } from "../lib/box.ts";
12
12
  import { assert, isMain } from "../lib/check.ts";
13
13
  import { markedLabels, ROW_DIVIDER } from "../lib/format.ts";
14
- import { LEGEND_LIVE, LEGEND_MOVE, matchesBack } from "../lib/shortcuts.ts";
15
14
  import { SPINNER_PRESETS, type SpinnerPreset } from "../lib/spinner.ts";
16
15
  import {
17
16
  activeSpinnerGradient,
@@ -25,6 +24,8 @@ import {
25
24
  } from "./animations.ts";
26
25
  import { FOOTER_PRESETS, activeFooterPreset, setFooterPreset, type FooterPreset } from "./footer.ts";
27
26
  import { HEADER_PRESETS, activeHeaderPreset, setHeaderPreset, type HeaderPreset } from "./section-headers.ts";
27
+ import { LIST_LEGEND_LIVE, LIST_LEGEND_MOVE, LIST_LEGEND_ROOT, ListPicker, nameRows, rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
28
+ import { openProviders } from "../lib/provider.ts";
28
29
  import { openUsage } from "./usage.ts";
29
30
 
30
31
  export interface ArnativeMenu {
@@ -35,199 +36,30 @@ export interface ArnativeMenu {
35
36
  open: (ctx: ExtensionCommandContext) => Promise<boolean | void>;
36
37
  }
37
38
 
38
- /** One picker row: `Label · Note`. `note` is absent on the preset lists (themes, headers,
39
- * footers), which are bare names. */
40
- export interface ListRow {
41
- label: string;
42
- note?: string;
43
- }
44
-
45
39
  /** Menu rows: `Label · description` (same rhythm as /jev-eye's menu). */
46
40
  export function menuRows(menus: Pick<ArnativeMenu, "label" | "description">[]): ListRow[] {
47
41
  return menus.map((m) => ({ label: m.label, note: m.description }));
48
42
  }
49
43
 
50
- // Legends come from the `KeySet`s the handlers match, so a key cannot be advertised on a
51
- // screen that does not handle it; the root menu has nothing behind it and omits `←`.
52
- export const LIST_LEGEND_MOVE = LEGEND_MOVE;
53
- export const LIST_LEGEND_LIVE = LEGEND_LIVE;
54
-
55
- /** One row as a flat string — the headless/RPC `ctx.ui.select` fallback, which has no columns. */
56
- export function rowText(row: ListRow): string {
57
- return row.note ? `${row.label} · ${row.note}` : row.label;
58
- }
59
-
60
- /** Bare names (preset lists) as rows; the cursor's `→` marks the live value. */
61
- const nameRows = (names: readonly string[]): ListRow[] => names.map((label) => ({ label }));
62
-
63
44
  /** Title of the settings menu, derived from `screenTitle` so the format lives in one place. */
64
45
  export const MENU_TITLE = screenTitle("Settings");
65
46
  /** One-line description under the menu title. */
66
- export const MENU_DESC = "Themes, headers, footers, animations, usage";
67
-
68
- interface ListPickerHooks {
69
- /** Apply a value on every selection move (live preview). */
70
- preview: (name: string) => void;
71
- /** Restore the value the picker opened with (Esc). */
72
- revert: () => void;
73
- done: () => void;
74
- requestRender: () => void;
75
- /** Esc, when it must be told apart from Enter (a menu selects, it does not revert). */
76
- cancel?: () => void;
77
- /** `←`: leave this screen for its parent (the menu, or the chat when there is none).
78
- * Distinct from `cancel`/Esc, which closes or reverts the screen it is on. */
79
- back?: () => void;
80
- /** `g`: toggle a screen-level switch (Animations → gradient). Only a screen that passes
81
- * this hook reacts to the key, so `g` stays a plain letter everywhere else. */
82
- toggleGradient?: () => void;
83
- /** Note re-read on every render, so a row can animate (Animations → a moving frame).
84
- * Returning undefined keeps the row's static note. */
85
- note?: (label: string) => string | undefined;
86
- /** Repaint cadence for an animated note. The frame itself is read from the clock, so a
87
- * missed repaint costs one frame and never desynchronises the animation. */
88
- tickMs?: number;
89
- /** Legend re-read on every render, for a key row that states live state
90
- * (`[g] Gradient on`). A constant legend would keep advertising the value it opened with. */
91
- legend?: () => string;
92
- }
93
-
94
- /** Box copy, so one picker serves every menu ("Themes - Arnative⠙", "Headers - Arnative⠙", …).
95
- * The same shape every arnative screen uses — see {@link renderScreen}. */
96
- export type ListPickerText = ScreenText;
97
-
98
- /** Live-preview picker: ↑↓ previews instantly, Enter keeps, Esc reverts. A caller whose
99
- * preview does nothing (`livePreview: false`) gets a plain menu: no revert on Esc, and
100
- * Esc is reported through `cancel` so "chose nothing" stays distinguishable from Enter. */
101
- export class ListPicker implements Component {
102
- private theme: { fg(c: string, t: string): string; bold?(t: string): string };
103
- private rows: ListRow[];
104
- private hooks: ListPickerHooks;
105
- private text: ListPickerText;
106
- private selected: number;
107
- private applied: string | undefined;
108
- private readonly livePreview: boolean;
109
- private readonly opened: string | undefined;
110
- private readonly tick: ReturnType<typeof setInterval> | undefined;
111
- /** Border painter, from the session's thinking level — the box follows the model. */
112
- private readonly edge: (s: string) => string;
113
-
114
- constructor(
115
- theme: { fg(c: string, t: string): string; bold?(t: string): string },
116
- rows: ListRow[],
117
- current: string | undefined,
118
- hooks: ListPickerHooks,
119
- text: ListPickerText,
120
- /** False for a menu: the selection is applied only on Enter, never while moving. */
121
- livePreview = true,
122
- /** The session's thinking level; colors the box border (theme `thinking*` slot). */
123
- thinkingLevel?: string,
124
- ) {
125
- this.theme = theme;
126
- this.rows = rows;
127
- this.hooks = hooks;
128
- this.text = text;
129
- this.livePreview = livePreview;
130
- this.opened = current;
131
- this.applied = current;
132
- this.selected = Math.max(0, rows.findIndex((r) => r.label === current));
133
- this.edge = thinkingColorOf(theme, thinkingLevel);
134
- this.tick = hooks.tickMs ? setInterval(() => hooks.requestRender(), hooks.tickMs) : undefined;
135
- }
136
-
137
- invalidate(): void {}
138
- dispose(): void {
139
- if (this.tick) clearInterval(this.tick);
140
- }
141
-
142
- /** Selected row, for callers that need the choice after `done()` resolves. */
143
- get index(): number {
144
- return this.selected;
145
- }
146
-
147
- private move(delta: number): void {
148
- const next = Math.min(this.rows.length - 1, Math.max(0, this.selected + delta));
149
- if (next === this.selected) return;
150
- this.selected = next;
151
- if (!this.livePreview) {
152
- this.hooks.requestRender();
153
- return;
154
- }
155
- this.applied = this.rows[next]!.label;
156
- this.hooks.preview(this.applied);
157
- this.hooks.requestRender();
158
- }
159
-
160
- handleInput(keyData: string): void {
161
- if (matchesBack(keyData)) {
162
- // Leave for the parent without touching the preview: `back` owns the revert of an
163
- // uncommitted preview, because "cancel" here means "close", not "undo".
164
- if (this.hooks.back) {
165
- this.hooks.back();
166
- return;
167
- }
168
- // No parent (the root menu): ← behaves like Esc — close, reverting a live preview.
169
- if (this.applied !== this.opened) this.hooks.revert();
170
- (this.hooks.cancel ?? this.hooks.done)();
171
- return;
172
- }
173
- if (matchesKey(keyData, "q") || matchesKey(keyData, "Q") || matchesKey(keyData, "escape")) {
174
- if (this.applied !== this.opened) this.hooks.revert();
175
- (this.hooks.cancel ?? this.hooks.done)();
176
- return;
177
- }
178
- if (matchesKey(keyData, "up") || matchesKey(keyData, "k")) {
179
- this.move(-1);
180
- return;
181
- }
182
- if (matchesKey(keyData, "down") || matchesKey(keyData, "j")) {
183
- this.move(1);
184
- return;
185
- }
186
- if (matchesKey(keyData, "enter")) {
187
- this.hooks.done();
188
- return;
189
- }
190
- if (this.hooks.toggleGradient && matchesKey(keyData, "g")) this.hooks.toggleGradient();
191
- }
192
-
193
- render(width: number): string[] {
194
- const th = this.theme;
195
- const bold = th.bold ?? ((t: string) => `\x1b[1m${t}\x1b[22m`);
196
- const soft = softSecondaryOf(th);
197
- const edge = (text: string) => this.edge(text);
198
- const column = Math.max(0, ...this.rows.map((r) => visibleWidth(r.label)));
199
- const body: string[] = [];
200
- for (let i = 0; i < this.rows.length; i++) {
201
- const item = this.rows[i]!;
202
- const isSelected = i === this.selected;
203
- const paint = isSelected ? (s: string) => soft(bold(s)) : (s: string) => th.fg(item.note ? "text" : "muted", s);
204
- const pad = " ".repeat(Math.max(0, column - visibleWidth(item.label)));
205
- const noteText = this.hooks.note?.(item.label) ?? item.note;
206
- const note = noteText ? `${th.fg("dim", ROW_DIVIDER)}${th.fg("dim", noteText)}` : "";
207
- // Extract parenthetical suffix to render softly
208
- const suffix = /(\(.*\))$/.exec(item.label)?.[1] ?? "";
209
- const head = suffix ? item.label.slice(0, item.label.length - suffix.length) : item.label;
210
- const tail = suffix ? th.fg("dim", suffix) : "";
211
- const content = `${isSelected ? th.fg("accent", "→ ") : " "}${paint(head)}${tail}${pad}${note}`;
212
- body.push(truncateToWidth(content, width - 4, ""));
213
- }
214
- return renderScreen(th, width, this.hooks.legend ? { ...this.text, legend: this.hooks.legend() } : this.text, body, edge);
215
- }
216
- }
47
+ export const MENU_DESC = "Themes, headers, footers, animations, providers, usage";
217
48
 
218
49
  const THEMES_PICKER_TEXT: ListPickerText = {
219
50
  title: screenTitle("Themes"),
220
- description: "Selection previews live — same list as /settings → Theme.",
51
+ description: "Selection previews live — arnative themes only (all themes: /settings → Theme).",
221
52
  legend: LIST_LEGEND_LIVE,
222
53
  };
223
54
 
224
55
  const openThemes = async (ctx: ExtensionCommandContext): Promise<boolean | void> => {
225
- const themes = ctx.ui.getAllThemes();
226
- if (themes.length === 0) {
227
- ctx.ui.notify("[arnative] No themes found. Add files to ~/.pi/agent/themes/ and run /reload.", "warning");
56
+ // Only this package's family (`arnative`, `arnative-<variant>`): the picker brands itself
57
+ // arnative, so pi's own themes and the user's belong in /settings → Theme, not here.
58
+ const names = ctx.ui.getAllThemes().map((t) => t.name).filter(isArnativeThemeName);
59
+ if (names.length === 0) {
60
+ ctx.ui.notify("[arnative] No arnative themes found. Reinstall pi-arnative, or pick any theme in /settings → Theme.", "warning");
228
61
  return;
229
62
  }
230
- const names = themes.map((t) => t.name);
231
63
  const current = ctx.ui.theme.name;
232
64
 
233
65
  if (ctx.mode !== "tui") {
@@ -413,7 +245,7 @@ export const MENUS: ArnativeMenu[] = [
413
245
  {
414
246
  value: "themes",
415
247
  label: "Themes",
416
- description: "list & apply themes (the /settings → Theme list)",
248
+ description: "arnative themes only (all themes: /settings → Theme)",
417
249
  open: openThemes,
418
250
  },
419
251
  {
@@ -434,6 +266,12 @@ export const MENUS: ArnativeMenu[] = [
434
266
  description: "choose the working spinner",
435
267
  open: openAnimations,
436
268
  },
269
+ {
270
+ value: "providers",
271
+ label: "Providers",
272
+ description: "custom endpoints: endpoint, key, name — the rest is automatic",
273
+ open: openProviders,
274
+ },
437
275
  {
438
276
  value: "usage",
439
277
  label: "Usage",
@@ -465,8 +303,11 @@ async function openMainMenu(ctx: ExtensionCommandContext, startLabel?: string):
465
303
  revert: () => {},
466
304
  done: () => done(picker.index),
467
305
  cancel: () => done(null),
306
+ // Nothing is behind the root menu: `←` is not a close shortcut here, so the key
307
+ // is hidden — Esc (and `q`) close, and the legend says so.
308
+ back: false,
468
309
  requestRender: () => tui.requestRender(),
469
- }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_MOVE }, false, ctx.thinkingLevel);
310
+ }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_ROOT }, false, ctx.thinkingLevel);
470
311
  return picker;
471
312
  });
472
313
  if (index === null || index === undefined) return;
@@ -508,6 +349,13 @@ export function arnativeCompletions(prefix: string): AutocompleteItem[] | null {
508
349
  * fresh install lands on Arnative without ever overriding a choice someone made. */
509
350
  export const DEFAULT_THEME = "arnative";
510
351
 
352
+ /** A theme of this package's family: `arnative` itself or an `arnative-<variant>`. The
353
+ * generator (`themes/gen-themes.mjs`) ships only such names, so the name is the identity —
354
+ * pi may load them from the package dir or a user copy, and both answer to it. */
355
+ export function isArnativeThemeName(name: string): boolean {
356
+ return name === DEFAULT_THEME || name.startsWith(`${DEFAULT_THEME}-`);
357
+ }
358
+
511
359
  /** Should the shipped theme be installed? Only when no theme is set at all (pi would fall back
512
360
  * to `system`) and the theme actually loaded, which a headless or filtered load may not do. */
513
361
  export function shouldApplyDefaultTheme(
@@ -525,7 +373,7 @@ export default function (pi: ExtensionAPI) {
525
373
  ctx.ui.setTheme(DEFAULT_THEME);
526
374
  });
527
375
  pi.registerCommand("arnative", {
528
- description: "Arnative settings menu: themes, headers, footers, usage",
376
+ description: "Arnative settings menu: themes, headers, footers, providers, usage",
529
377
  getArgumentCompletions: arnativeCompletions,
530
378
  handler: arnativeHandler,
531
379
  });
@@ -538,14 +386,14 @@ if (isMain(import.meta.url)) {
538
386
  assert(markedLabels(["a"], undefined)[0] === " a", "markedLabels handles no active theme");
539
387
  const labels = menuRows(MENUS);
540
388
  assert(labels.length === MENUS.length, "menuRows one row per menu");
541
- assert(rowText(labels[0]!) === "Themes · list & apply themes (the /settings → Theme list)", "menu row text format");
542
- assert(labels[0]!.label === "Themes" && labels[0]!.note === "list & apply themes (the /settings → Theme list)", "menu row keeps label and note apart");
389
+ assert(rowText(labels[0]!) === "Themes · arnative themes only (all themes: /settings → Theme)", "menu row text format");
390
+ assert(labels[0]!.label === "Themes" && labels[0]!.note === "arnative themes only (all themes: /settings → Theme)", "menu row keeps label and note apart");
543
391
  assert(MENU_TITLE === "Settings - Arnative\u2819", `the menu title is the pinned string, got ${MENU_TITLE}`);
544
- assert(MENU_DESC === "Themes, headers, footers, animations, usage", `the menu description is the pinned string, got ${MENU_DESC}`);
392
+ assert(MENU_DESC === "Themes, headers, footers, animations, providers, usage", `the menu description is the pinned string, got ${MENU_DESC}`);
545
393
  // Every menu row is reachable and the description names them all, so a new screen cannot
546
394
  // be added to MENUS and forgotten in the copy a user reads first.
547
- assert(MENUS.length === 5, "five settings screens");
548
- for (const label of ["Themes", "Headers", "Footers", "Animations", "Usage"]) {
395
+ assert(MENUS.length === 6, "six settings screens");
396
+ for (const label of ["Themes", "Headers", "Footers", "Animations", "Providers", "Usage"]) {
549
397
  assert(MENUS.some((m) => m.label === label), `MENUS carries the ${label} screen`);
550
398
  }
551
399
  assert(/^Settings - Arnative/.test(MENU_TITLE), "title follows `<setting> - <extension>`");
@@ -558,11 +406,20 @@ if (isMain(import.meta.url)) {
558
406
  assert(arnativeCompletions("he")![0]!.value === "headers", "headers menu has completions");
559
407
  assert(arnativeCompletions("fo")![0]!.value === "footers", "footers menu has completions");
560
408
  assert(MENUS.some((m) => m.value === "footers"), "footers menu registered");
409
+ assert(arnativeCompletions("pr")![0]!.value === "providers", "providers menu has completions");
410
+ assert(MENUS.some((m) => m.value === "providers"), "providers menu registered");
561
411
  // Usage is reachable from /arnative even though it is a dashboard, not a setting.
562
412
  assert(MENUS.some((m) => m.value === "usage"), "usage menu registered");
563
413
  assert(arnativeCompletions("us")![0]!.value === "usage", "usage menu has completions");
564
414
  assert(typeof MENUS.find((m) => m.value === "usage")!.open === "function", "the usage row opens the dashboard");
565
415
 
416
+ // The /arnative picker lists the package's family only; everything else (system, dark,
417
+ // light, a theme of the user's own) stays in /settings → Theme.
418
+ assert(isArnativeThemeName("arnative"), "the default theme is family");
419
+ assert(isArnativeThemeName("arnative-sun"), "a variant is family");
420
+ for (const outsider of ["system", "dark", "light", "omarchy-system", "arnativeX", ""])
421
+ assert(!isArnativeThemeName(outsider), `${JSON.stringify(outsider)} is not family`);
422
+
566
423
  // The shipped theme is applied only when pi has no theme setting of its own.
567
424
  assert(shouldApplyDefaultTheme(undefined, [{ name: "arnative" }]), "an unset theme installs Arnative");
568
425
  assert(!shouldApplyDefaultTheme("arnative", [{ name: "arnative" }]), "an explicit Arnative setting is left alone");
@@ -599,8 +456,8 @@ if (isMain(import.meta.url)) {
599
456
 
600
457
  // `←` reports upward instead of closing on a screen with a parent, reverting the live
601
458
  // preview first; the root menu has nothing behind it and omits the key.
602
- assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Open [Esc] Close", "menu legend pinned, and free of a dead back key");
603
- assert(!LIST_LEGEND_MOVE.includes("←"), "the root menu does not advertise ←");
459
+ assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Open [Esc] Close", "the root menu legend omits ←");
460
+ assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Open [←] Back [Esc] Close", "submenu legend advertises ← Back");
604
461
  assert(LIST_LEGEND_LIVE === "[↑↓] Preview [Enter] Select [←] Back [Esc] Revert", "live legend pinned");
605
462
  let backs = 0;
606
463
  let backReverts = 0;
@@ -635,9 +492,10 @@ if (isMain(import.meta.url)) {
635
492
  done: () => {},
636
493
  cancel: () => { menuCancelled = true; },
637
494
  requestRender: () => {},
638
- }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_MOVE }, false);
495
+ }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_ROOT }, false);
639
496
  const menuLines = mainPicker.render(60);
640
497
  assert(menuLines.some((l) => l.includes(MENU_TITLE)), "the main menu renders its title");
498
+ assert(menuLines.some((l) => l.includes("[Esc] Close") && !l.includes("←")), "the root menu legend renders without a back key");
641
499
  assert(menuLines.some((l) => l.includes(MENU_DESC)), "the main menu renders the description under the title");
642
500
  assert(menuLines.findIndex((l) => l.includes(MENU_TITLE)) < menuLines.findIndex((l) => l.includes(MENU_DESC)), "description sits below the title");
643
501
  assert(menuLines.every((l) => visibleWidth(l) === 60), "main menu lines fit the width");
@@ -648,7 +506,7 @@ if (isMain(import.meta.url)) {
648
506
  // not a literal run of spaces, so adding a wider screen cannot break the layout test.
649
507
  const widest = Math.max(...MENUS.map((m) => m.label.length));
650
508
  assert(
651
- row0.startsWith(`│ → ${"Themes".padEnd(widest)}${ROW_DIVIDER}list & apply themes`),
509
+ row0.startsWith(`│ → ${"Themes".padEnd(widest)}${ROW_DIVIDER}arnative themes only`),
652
510
  `menu row layout, got ${JSON.stringify(row0)}`,
653
511
  );
654
512
  assert(plainMenu.filter((l) => l.includes(ROW_DIVIDER)).every((l) => l.indexOf(ROW_DIVIDER) === row0.indexOf(ROW_DIVIDER)), "every divider sits in one column");
@@ -665,7 +523,7 @@ if (isMain(import.meta.url)) {
665
523
  revert: () => {},
666
524
  done: () => {},
667
525
  requestRender: () => {},
668
- }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_MOVE }, false);
526
+ }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_ROOT }, false);
669
527
  const resumedRows = resumed.render(60).map(stripAnsi);
670
528
  assert(resumedRows.some((l) => l.startsWith("│ → Usage")), "the menu reopens on the row it was left on");
671
529
  assert(!resumedRows.some((l) => l.startsWith("│ → Themes")), "and not on the first row");
@@ -769,5 +627,54 @@ if (isMain(import.meta.url)) {
769
627
  mainPicker.handleInput("g");
770
628
  assert(gradientOn, "a screen without the hook ignores g");
771
629
 
630
+ // Multi-select (Providers → model list): Space toggles, `[x]` marks, the cursor still moves.
631
+ const picked: string[] = [];
632
+ const chosen = new Set<string>(["a"]);
633
+ const multiRows = nameRows(["a", "b", "c"]);
634
+ const multiPicker = new ListPicker(fakeTheme, multiRows, "a", {
635
+ preview: quiet,
636
+ revert: quiet,
637
+ done: quiet,
638
+ requestRender: quiet,
639
+ toggle: () => {
640
+ const label = multiRows[multiPicker.index]!.label;
641
+ if (chosen.has(label)) chosen.delete(label);
642
+ else chosen.add(label);
643
+ picked.push(label);
644
+ },
645
+ marked: (label) => chosen.has(label),
646
+ }, { title: screenTitle("Providers"), description: "pick models", legend: "[Space] Toggle" }, false);
647
+ const multiLines = multiPicker.render(50).map(stripAnsi);
648
+ assert(multiLines.some((l) => l.includes("→ [x] a")), "a checked row shows [x] behind the cursor");
649
+ assert(multiLines.some((l) => l.includes("[ ] b")), "unchecked rows show [ ]");
650
+ multiPicker.handleInput(" ");
651
+ assert(picked[0] === "a" && !chosen.has("a"), "Space toggles the row under the cursor");
652
+ multiPicker.handleInput("\x1b[B");
653
+ multiPicker.handleInput(" ");
654
+ assert(chosen.has("b"), "Space toggles the row the cursor moved to");
655
+ assert(multiPicker.render(50).map(stripAnsi).some((l) => l.includes("→ [x] b")), "the check follows the cursor");
656
+ mainPicker.handleInput(" ");
657
+ assert(chosen.has("b") && picked.length === 2, "a screen without the toggle hook ignores Space");
658
+
659
+ // Unhandled keys reach the screen's own switch (`press`), and no hook means no route.
660
+ let pressed: string[] = [];
661
+ const pressPicker = new ListPicker(fakeTheme, nameRows(["a", "b", "c"]), "a", {
662
+ preview: quiet,
663
+ revert: quiet,
664
+ done: quiet,
665
+ requestRender: quiet,
666
+ press: (keyData) => pressed.push(keyData),
667
+ }, { title: screenTitle("Providers"), description: "pick models", legend: "[a] API" }, false);
668
+ pressPicker.handleInput("a");
669
+ assert(pressed.length === 1 && pressed[0] === "a", "an unhandled key reaches the screen via press");
670
+ const routed = new ListPicker(fakeTheme, nameRows(["a"]), undefined, {
671
+ preview: quiet,
672
+ revert: quiet,
673
+ done: quiet,
674
+ requestRender: quiet,
675
+ });
676
+ routed.handleInput("a");
677
+ assert(pressed.length === 1, "a screen without press ignores stray letters");
678
+
772
679
  console.log("arnative.ts self-check OK");
773
680
  }
@@ -1168,6 +1168,11 @@ export default function (pi: ExtensionAPI) {
1168
1168
  armIdleProbe();
1169
1169
  activeToolVerbs.delete(event.toolCallId);
1170
1170
  setWorkingVerb(ctx, currentToolVerb(activeToolVerbs));
1171
+ // A finished edit/write/bash may have changed the tree (or committed it): without
1172
+ // this, the diff stat stays frozen at the turn_start snapshot — a session that
1173
+ // commits inside the turn shows "clean" forever. refreshGit coalesces concurrent
1174
+ // calls (in-flight + one queued), so a burst of tool ends costs at most two runs.
1175
+ void refreshGit(ctx.cwd).then(() => poke());
1171
1176
  });
1172
1177
 
1173
1178
  pi.on("message_update", async (event) => {
@@ -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}`);