@bismawy/pi-arnative 0.16.0 → 0.18.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.
Files changed (47) hide show
  1. package/README.md +25 -16
  2. package/extensions/index.ts +41 -0
  3. package/lib/active-clock.ts +91 -0
  4. package/lib/ansi.ts +40 -78
  5. package/lib/box.ts +49 -68
  6. package/lib/chatbox.ts +371 -0
  7. package/lib/color.ts +3 -31
  8. package/lib/compat.ts +0 -60
  9. package/lib/edit-diff.ts +199 -0
  10. package/{extensions → lib/features}/arnative.ts +96 -423
  11. package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -325
  12. package/{extensions → lib/features}/budget.ts +17 -242
  13. package/lib/features/footer.ts +2232 -0
  14. package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
  15. package/{extensions → lib/features}/model-heal.ts +5 -28
  16. package/lib/features/progress-group.ts +1557 -0
  17. package/{extensions → lib/features}/render-cache.ts +130 -158
  18. package/{extensions → lib/features}/timestamps.ts +132 -131
  19. package/{extensions → lib/features}/todos.ts +44 -158
  20. package/lib/features/tools.ts +1202 -0
  21. package/lib/features/ui-render-tweaks.ts +606 -0
  22. package/lib/features/usage.ts +786 -0
  23. package/lib/format.ts +22 -4
  24. package/lib/git-status.ts +164 -0
  25. package/lib/list-picker.ts +1 -127
  26. package/lib/model-heal.ts +70 -162
  27. package/lib/patch.ts +0 -63
  28. package/lib/preset-store.ts +17 -133
  29. package/lib/provider-store.ts +573 -0
  30. package/lib/provider.ts +52 -851
  31. package/lib/runtime.ts +209 -0
  32. package/lib/shortcuts.ts +8 -58
  33. package/lib/spinner.ts +88 -162
  34. package/lib/status-widget.ts +4 -30
  35. package/lib/todos.ts +20 -143
  36. package/lib/usage-pricing.ts +143 -0
  37. package/lib/usage-store.ts +44 -378
  38. package/package.json +5 -6
  39. package/CHANGELOG.md +0 -678
  40. package/extensions/animations.ts +0 -242
  41. package/extensions/footer.ts +0 -2580
  42. package/extensions/tools.ts +0 -2231
  43. package/extensions/ui-render-tweaks.ts +0 -1005
  44. package/extensions/usage-export.ts +0 -283
  45. package/extensions/usage.ts +0 -1406
  46. package/lib/check.ts +0 -21
  47. package/themes/gen-themes.mjs +0 -715
package/lib/runtime.ts ADDED
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Centralized reload-safe runtime state and lifecycle dispatcher for @bismawy/pi-arnative.
3
+ *
4
+ * Pi's `/reload` re-evaluates `extensions/index.ts` with a fresh jiti module graph in the
5
+ * same Node process. Holding reload-persistent runtime state under one typed `globalThis`
6
+ * slot (`Symbol.for("pi-arnative.runtime")`) replaces 25+ scattered `Symbol.for` slots,
7
+ * and consolidating `pi.on(...)` fan-out installs one listener per event type instead of
8
+ * registering 40+ separate handlers (e.g. 13 `session_start`, 6 `session_shutdown`).
9
+ */
10
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
11
+
12
+ const RUNTIME_KEY = Symbol.for("pi-arnative.runtime");
13
+
14
+ // Per-component instance tags shared across `tools.ts` and `render-cache.ts`.
15
+ export const TOOL_BOX_SCROLL_HOLD_KEY = Symbol.for("pi-arnative.toolBoxScrollHold");
16
+ export const TOOL_BOX_SCROLL_OFFSET_KEY = Symbol.for("pi-arnative.toolBoxScrollOffset");
17
+
18
+ export interface ActiveClockSnapshot {
19
+ active: number;
20
+ runStarted: number;
21
+ lastSeen: number;
22
+ }
23
+
24
+ export interface ThinkingLabelState {
25
+ ui: { requestRender(): void } | null;
26
+ active: Set<object>;
27
+ starts: WeakMap<object, number[]>;
28
+ finished: WeakMap<object, Array<string | undefined>>;
29
+ timer: ReturnType<typeof setInterval> | null;
30
+ }
31
+
32
+ export interface RuntimeState {
33
+ activeTheme: object | null;
34
+ currentModel: unknown;
35
+ currentThinking: unknown;
36
+ lastCwd: string;
37
+ lastGit: unknown;
38
+ footerGen: number;
39
+ footerRegistrar: ((ctx: ExtensionContext) => void) | null;
40
+ activeClock: ActiveClockSnapshot | null;
41
+ idleTimer: ReturnType<typeof setTimeout> | null;
42
+ clockTimer: ReturnType<typeof setInterval> | null;
43
+ promptTypedAt: number;
44
+ promptIdleTimer: ReturnType<typeof setTimeout> | null;
45
+ minimalFooterExpanded: { left: boolean; right: boolean } | null;
46
+ zenFooterExpanded: { git: boolean; detail: "left" | "right" | null } | null;
47
+ outsideDialogHook: ((lines: string[], width: number, mode: unknown) => string[]) | null;
48
+ activityHook: ((data: string) => void) | null;
49
+ wrappedTuis: WeakSet<object>;
50
+ editor: unknown;
51
+ workingUi: unknown;
52
+ resourceStore: Map<string, string[]> | null;
53
+ headerInstance: unknown;
54
+ userTimestamps: Map<string, number> | null;
55
+ thinkingLabelState: ThinkingLabelState | null;
56
+ renderCacheState: unknown;
57
+ autocompactState: unknown;
58
+ todosWidget: unknown;
59
+ }
60
+
61
+ function createFreshRuntime(): RuntimeState {
62
+ return {
63
+ activeTheme: null,
64
+ currentModel: undefined,
65
+ currentThinking: undefined,
66
+ lastCwd: "",
67
+ lastGit: null,
68
+ footerGen: 0,
69
+ footerRegistrar: null,
70
+ activeClock: null,
71
+ idleTimer: null,
72
+ clockTimer: null,
73
+ promptTypedAt: 0,
74
+ promptIdleTimer: null,
75
+ minimalFooterExpanded: null,
76
+ zenFooterExpanded: null,
77
+ outsideDialogHook: null,
78
+ activityHook: null,
79
+ wrappedTuis: new WeakSet<object>(),
80
+ editor: null,
81
+ workingUi: null,
82
+ resourceStore: null,
83
+ headerInstance: null,
84
+ userTimestamps: null,
85
+ thinkingLabelState: null,
86
+ renderCacheState: null,
87
+ autocompactState: null,
88
+ todosWidget: null,
89
+ };
90
+ }
91
+
92
+ /** Single reload-safe runtime state bag stored under `globalThis[Symbol.for("pi-arnative.runtime")]`. */
93
+ export function getRuntime(): RuntimeState {
94
+ const g = globalThis as Record<symbol, RuntimeState | undefined>;
95
+ g[RUNTIME_KEY] ??= createFreshRuntime();
96
+ return g[RUNTIME_KEY]!;
97
+ }
98
+
99
+ type EventHandler = (event: any, ctx: any) => any;
100
+
101
+ function createEventDispatcher(eventName: string, handlers: readonly EventHandler[]): EventHandler {
102
+ if (eventName === "context") {
103
+ return async (event: any, ctx: any) => {
104
+ let current = event;
105
+ let changed = false;
106
+ for (const handler of handlers) {
107
+ const res = await handler(current, ctx);
108
+ if (res?.messages) {
109
+ current = { ...current, messages: res.messages };
110
+ changed = true;
111
+ }
112
+ }
113
+ return changed ? { messages: current.messages } : undefined;
114
+ };
115
+ }
116
+ if (eventName === "input") {
117
+ return async (event: any, ctx: any) => {
118
+ let current = event;
119
+ let transformed = false;
120
+ for (const handler of handlers) {
121
+ const res = await handler(current, ctx);
122
+ if (res?.action === "handled") return res;
123
+ if (res?.action === "transform") {
124
+ current = { ...current, text: res.text, images: res.images ?? current.images };
125
+ transformed = true;
126
+ }
127
+ }
128
+ return transformed ? { action: "transform", text: current.text, images: current.images } : undefined;
129
+ };
130
+ }
131
+ if (eventName === "before_provider_request") {
132
+ return async (event: any, ctx: any) => {
133
+ let current = event;
134
+ let modified: unknown = undefined;
135
+ for (const handler of handlers) {
136
+ const res = await handler(current, ctx);
137
+ if (res !== undefined) {
138
+ modified = res;
139
+ current = { ...current, payload: res };
140
+ }
141
+ }
142
+ return modified;
143
+ };
144
+ }
145
+ if (eventName.startsWith("session_before_")) {
146
+ return async (event: any, ctx: any) => {
147
+ let result: any = undefined;
148
+ for (const handler of handlers) {
149
+ const res = await handler(event, ctx);
150
+ if (res) {
151
+ result = res;
152
+ if (res.cancel) return result;
153
+ }
154
+ }
155
+ return result;
156
+ };
157
+ }
158
+ return async (event: any, ctx: any) => {
159
+ let firstError: unknown = undefined;
160
+ let hasError = false;
161
+ for (const handler of handlers) {
162
+ try {
163
+ await handler(event, ctx);
164
+ } catch (err) {
165
+ if (!hasError) {
166
+ firstError = err;
167
+ hasError = true;
168
+ }
169
+ }
170
+ }
171
+ if (hasError) throw firstError;
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Registers every feature through a centralized lifecycle hub so Pi receives at most one
177
+ * `pi.on(...)` listener per event type instead of 40+ individual handlers.
178
+ */
179
+ export function registerLifecycleFeatures(
180
+ pi: ExtensionAPI,
181
+ features: readonly ((api: ExtensionAPI) => void)[],
182
+ ): void {
183
+ const handlersByEvent = new Map<string, EventHandler[]>();
184
+ const scopedPi = new Proxy(pi, {
185
+ get(target, prop, receiver) {
186
+ if (prop === "on") {
187
+ return (event: string, handler: EventHandler) => {
188
+ let list = handlersByEvent.get(event);
189
+ if (!list) {
190
+ list = [];
191
+ handlersByEvent.set(event, list);
192
+ }
193
+ list.push(handler);
194
+ };
195
+ }
196
+ const value = Reflect.get(target, prop, receiver);
197
+ return typeof value === "function" ? value.bind(target) : value;
198
+ },
199
+ });
200
+
201
+ for (const register of features) {
202
+ register(scopedPi);
203
+ }
204
+
205
+ const on = pi.on.bind(pi) as (event: string, handler: EventHandler) => void;
206
+ for (const [event, handlers] of handlersByEvent) {
207
+ on(event, handlers.length === 1 ? handlers[0]! : createEventDispatcher(event, handlers));
208
+ }
209
+ }
package/lib/shortcuts.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  // Platform-aware single-letter shortcuts. Windows/WSL uses Alt+<char> to avoid AltGr
2
2
  // aliasing; macOS displays Option; other platforms use Ctrl+Alt.
3
3
  import { Key, matchesKey, visibleWidth } from "@earendil-works/pi-tui";
4
- import { assert, isMain } from "./check.ts";
5
4
 
6
5
  /** Windows Terminal's AltGr aliasing hits native Windows and WSL panes alike. */
7
6
  export const IS_WINDOWS_LIKE =
@@ -45,7 +44,7 @@ export const SHORTCUT_SCROLL_TODOS_UP = build("k");
45
44
 
46
45
  /** The `←` byte matcher. Esc is the advertised way out of a screen (Back, or Close at the
47
46
  * root); `←` stays as an alias so muscle memory keeps working, but no footer names it. */
48
- export const BACK_KEY_LABEL = "←";
47
+ const BACK_KEY_LABEL = "←";
49
48
  export function matchesBack(data: string): boolean {
50
49
  return matchesKey(data, "left");
51
50
  }
@@ -99,59 +98,10 @@ export function legendUsage(width: number, opts: { reset?: boolean; undo?: boole
99
98
  return width >= visibleWidth(full) ? full : legend([CANCEL.label, "Back"]);
100
99
  }
101
100
 
102
- if (isMain(import.meta.url)) {
103
- assert(SHORTCUT_RELOAD.keys[0] === Key.ctrlAlt("r"), "ctrl+alt+r is registered on every platform");
104
- assert(
105
- SHORTCUT_RELOAD.keys.includes(Key.alt("r")) === IS_WINDOWS_LIKE,
106
- "alt+r is registered only where Ctrl+Alt is aliased away",
107
- );
108
- assert(
109
- SHORTCUT_RELOAD.label.toLowerCase().replace(/option/, "alt") === SHORTCUT_RELOAD.keys[SHORTCUT_RELOAD.keys.length - 1],
110
- `label derives from the native key id (${SHORTCUT_RELOAD.label})`,
111
- );
112
- assert(SHORTCUT_RELOAD.matches("\x1b\x12"), "legacy ESC + 0x12 matches ctrl+alt+r");
113
- assert(SHORTCUT_RELOAD.matches("\x1b[114;7u"), "Kitty CSI-u matches ctrl+alt+r");
114
- assert(SHORTCUT_RELOAD.matches("\x1br") === IS_WINDOWS_LIKE, "ESC + r matches only where alt+r is registered");
115
- assert(
116
- SHORTCUT_RELOAD.matches("\x1b[114;3u") === IS_WINDOWS_LIKE,
117
- "Kitty CSI-u alt+r fires exactly where alt+r is registered",
118
- );
119
- assert(!SHORTCUT_RELOAD.matches("\x12"), "bare control char does not match ctrl+alt+r");
120
- assert(!SHORTCUT_RELOAD.matches("r"), "bare letter does not match ctrl+alt+r");
121
- assert(!SHORTCUT_NEXT_TAB.matches("\x1br"), "alt+r does not match the next-tab shortcut");
122
- assert(SHORTCUT_TOGGLE_FOOTER.keys[0] === Key.ctrlAlt("m"), "ctrl+alt+m is registered on every platform");
123
- assert(
124
- SHORTCUT_TOGGLE_FOOTER.keys.includes(Key.alt("m")) === IS_WINDOWS_LIKE,
125
- "alt+m is registered only where Ctrl+Alt is aliased away",
126
- );
127
- assert(!SHORTCUT_TOGGLE_FOOTER.matches("\x1b\x12"), "ctrl+alt+r does not match the footer toggle");
128
- assert(matchesBack("\x1b[D"), "← (CSI) matches the back key");
129
- assert(matchesBack("\x1bOD"), "← (SS3, application cursor mode) matches the back key");
130
- assert(!matchesBack("\x1b[C"), "→ is not the back key");
131
- assert(!matchesBack("\x1b"), "Esc is not the back key: Esc closes, ← steps back");
132
- assert(!matchesBack("h"), "a bare letter is not the back key");
133
- // The legends are built from the same keys the handlers match, so a key cannot be
134
- // advertised on one screen and handled on none.
135
- assert(LEGEND_MOVE === "[↑↓] Move [Enter] Select [Esc] Back", `submenu legend pinned, got ${LEGEND_MOVE}`);
136
- assert(LEGEND_READ_ONLY === "[↑↓] Move [Esc] Close", `read-only legend pinned, got ${LEGEND_READ_ONLY}`);
137
- assert(
138
- LEGEND_LIVE === `[↑↓] Preview [Enter] Select [${CANCEL.label}] Back`,
139
- `live legend pinned, got ${LEGEND_LIVE}`,
140
- );
141
- assert(MOVE.matches("\x1b[A") && MOVE.matches("\x1b[B"), "the ↑↓ key matches both arrows");
142
- assert(CHOOSE.matches("\r"), "[Enter] matches carriage return");
143
- assert(BACK.matches("\x1b[D"), "← is still the back key, even when the footer names only Esc");
144
- assert(CANCEL.matches("\x1b"), "[Esc] matches escape");
145
- assert(!CANCEL.matches("\x1b[D"), "[Esc] is not the ← byte sequence");
146
- assert(legendUsage(120).includes("[Esc] Back"), "a wide usage legend advertises Esc Back");
147
- assert(legendUsage(140).includes("[Space/Click] Show/Hide"), "a wide usage legend advertises Space and the mouse");
148
- assert(legendUsage(120).includes("[v] View"), "a wide usage legend advertises the view key the dashboard handles");
149
- assert(legendUsage(120, { next: "Project" }).includes("[v] Next: Project"), "the legend names the view the key would show");
150
- assert(legendUsage(20) === "[Esc] Back", "a narrow usage legend degrades to the one key that still fits");
151
- assert(!legendUsage(20).includes("[v]"), "the narrow usage legend drops the view key with the rest");
152
- assert(legendUsage(160, { reset: true }).includes("[R] Reset"), "a reset-capable dashboard advertises R Reset");
153
- assert(!legendUsage(160).includes("Reset"), "the read-only dashboard does not advertise a key it lacks");
154
- assert(RESET_USAGE.matches("R") && !RESET_USAGE.matches("r"), "a capital R is shift+r, not r");
155
- assert(UNDO_USAGE.matches("U") && !UNDO_USAGE.matches("u"), "a capital U is shift+u, not u");
156
- console.log("shortcuts.ts self-check OK");
157
- }
101
+ export const __test = {
102
+ MOVE,
103
+ CHOOSE,
104
+ BACK,
105
+ CANCEL,
106
+ legend,
107
+ };
package/lib/spinner.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * Working-indicator presets for `/arnative` → **Animations** and their painters.
3
- * Single source of truth for frames, cadence, and colours.
3
+ * Single source of truth for frames, cadence, colours, config persistence, and picker copy.
4
4
  */
5
- import { assert, isMain } from "./check.ts";
6
- import { visibleWidth } from "@earendil-works/pi-tui";
5
+ import { getActiveTheme } from "./ansi.ts";
6
+ import { ROW_DIVIDER } from "./format.ts";
7
+ import { choiceSetting, flagSetting } from "./preset-store.ts";
8
+ import { getRuntime } from "./runtime.ts";
7
9
 
8
10
  /** Picker order: the escape hatch first, this package's own spinner second, then the rest
9
11
  * alphabetically. `Pi (system)` and `Arnative` are not sorted in — they are the two rows a
@@ -303,177 +305,101 @@ export function previewFrameAt(preset: SpinnerPreset, now = Date.now()): { text:
303
305
  return { text: frames[index]!, width: Math.max(...frames.map((f) => [...f].length)) };
304
306
  }
305
307
 
308
+ const spinnerPresetSetting = choiceSetting(SPINNER_PRESET_KEY, SPINNER_PRESETS, DEFAULT_SPINNER_PRESET);
309
+ const spinnerGradientSetting = flagSetting(SPINNER_GRADIENT_KEY);
306
310
 
307
- // Self-check: `node lib/spinner.ts`
308
- if (isMain(import.meta.url)) {
309
- for (const p of SPINNER_PRESETS) {
310
- const def = SPINNER_PRESET_DEFS[p];
311
- assert(def.note.length > 0, `${p} carries a picker note`);
312
- for (const frame of def.frames) {
313
- assert(!/[\ufffd\ue000-\uf8ff]/.test(frame), `${p}: frame ${frame} is not a blank private-use cell`);
314
- }
315
- if (def.frames.length > 0) {
316
- assert(def.intervalMs > 0, `${p} with frames must set an interval`);
317
- assert(new Set(def.frames).size > 1, `${p} must animate, not repeat one frame`);
318
- }
319
- }
311
+ /** The `setWorkingMessage`/`setWorkingIndicator` surface of `ctx.ui`. */
312
+ export type WorkingUi = { setWorkingIndicator?: (options?: unknown) => void } | null | undefined;
313
+ type SpinnerThemeLike = { fg?(color: string, text: string): string } | null;
320
314
 
321
- // `Pi (system)` is the escape hatch: it must install nothing at all.
322
- assert(SPINNER_PRESET_DEFS["Pi (system)"].frames.length === 0, "Pi (system) leaves pi's frames alone");
323
- assert(SPINNER_PRESET_DEFS["Pi (system)"].intervalMs === 0, "Pi (system) leaves pi's interval alone");
315
+ /** Record the session's `ctx.ui`, so a later preset pick can install through it. */
316
+ export function setWorkingUi(ui: WorkingUi): void {
317
+ getRuntime().workingUi = ui ?? null;
318
+ }
324
319
 
325
- // Gemini's Braille is the one sanctioned exception: Braille Patterns is a block every
326
- // terminal font covers (it is pi's own default set, so a terminal that shows pi at all has
327
- // it), and the ten cells share one face because U+2800-U+28FF is a single contiguous run.
328
- const braille = /^[\u2800-\u28ff]+$/;
329
- assert(SPINNER_PRESET_DEFS.Gemini.frames.every((f) => braille.test(f)), "Gemini frames are Braille cells");
330
- assert(SPINNER_PRESET_DEFS.Gemini.frames.length === 10, "Gemini uses the ten-frame dots spinner");
331
- assert(
332
- SPINNER_PRESET_DEFS.Gemini.intervalMs === 80,
333
- "Gemini keeps the cli-spinners cadence (80ms)",
334
- );
320
+ function activeWorkingUi(): WorkingUi {
321
+ return (getRuntime().workingUi as WorkingUi) ?? null;
322
+ }
335
323
 
336
- // Diamond Glow uses the Geometric Shapes block; `⬥ ◈ ◆ ◇` all live in one contiguous run
337
- // and are hosted by the terminal face on the platforms this package targets.
338
- for (const f of SPINNER_PRESET_DEFS["Diamond Glow"].frames) {
339
- assert(/^[\u25a0-\u25ff\u2b00-\u2bff]$/.test(f), `Diamond Glow frame ${f} is a geometric shape`);
340
- }
324
+ export const activeSpinnerPreset = (): SpinnerPreset => spinnerPresetSetting.get();
341
325
 
342
- // Claudeon preset: a mark of our own, inspired by Claude Code's pulsing dingbats. The
343
- // attribution lives in the preset's note; the type and colour keep the `claudeon` name.
344
- const claudeon = SPINNER_PRESET_DEFS.Claudeon.frames;
345
- assert(claudeon[0] === "\u00b7", "Claudeon starts on the interpunct");
346
- assert(claudeon.length === 8, "Claudeon uses an 8-frame there-and-back loop over 4 base marks");
347
- assert(SPINNER_PRESET_DEFS.Claudeon.intervalMs === 120, "Claudeon matches upstream 120ms cadence");
348
- assert(claudeon.join("") === [...claudeon].reverse().join(""), "Claudeon's ping-pong frames are a palindrome");
349
- assert(
350
- claudeon.join("") === "\u00b7\u002a\u22c6\u2736\u2736\u22c6\u002a\u00b7",
351
- "Claudeon's base marks are pinned by codepoint",
352
- );
353
- // Every frame must be one column by the Unicode width tables — that catches a fullwidth or
354
- // CJK mark slipped in. It cannot catch the *real* failure mode (a glyph the terminal font
355
- // lacks, served ~1.5 cells wide by a fallback font), because that width is a font property
356
- // and is invisible from here. Those frames are pinned by codepoint above instead, so the set
357
- // cannot change silently.
358
- assert(
359
- claudeon.every((f) => visibleWidth(f) === 1),
360
- `Claudeon frames must be single-column, got ${claudeon.filter((f) => visibleWidth(f) !== 1).join(" ")}`,
361
- );
326
+ /** Is the `accent` → gradient override on? */
327
+ export const activeSpinnerGradient = (): boolean => spinnerGradientSetting.get();
362
328
 
363
- // Arrow Orbit, Arnative and Pacman each draw several glyphs per frame, so every frame must
364
- // be the same width or the label jumps sideways each tick. Pinned by codepoint: a font
365
- // fallback that swaps one arrow/star for a double-width glyph is exactly what this catches.
366
- const arrow = SPINNER_PRESET_DEFS["Arrow Orbit"].frames;
367
- assert(arrow.join("|") === "\u25b4\u25b8\u25be\u25c2|\u25b8\u25be\u25c2\u25b4|\u25be\u25c2\u25b4\u25b8|\u25c2\u25b4\u25b8\u25be", "Arrow Orbit turns clockwise one position per frame");
368
- const spark = SPINNER_PRESET_DEFS.Arnative.frames;
369
- assert(spark.join("|") === " \u2727\u2819| \u2727\u28e0|\u28c4\u2727 |\u280b\u2726 ", "Arnative frames as specified");
370
- const pacman = SPINNER_PRESET_DEFS.Pacman.frames;
371
- assert(
372
- pacman.join("|") === "\u15e7 + \u2212 \u00d7|~ \u15e7 \u2212 \u00d7|~ ~ \u15e7 \u00d7|~ ~ ~ \u15e7",
373
- "Pacman eats one cell per frame",
374
- );
375
- // The mouth moves one cell right each frame, so the glyph's column is the frame index.
376
- for (const [i, frame] of pacman.entries()) {
377
- assert([...frame].indexOf("\u15e7") === i * 2, `Pacman frame ${i} puts the mouth in column ${i * 2}`);
378
- }
379
- assert(DEFAULT_SPINNER_PRESET === "Arnative", "a fresh install gets the Arnative spinner");
380
- // The four I Ching digrams, pinned by codepoint, in the order the operator gave them.
381
- const yinYang = SPINNER_PRESET_DEFS["Yin Yang Lines"].frames;
382
- assert(
383
- yinYang.join("|") === "\u268c|\u268e|\u268d|\u268f",
384
- "Yin Yang Lines frames as specified (all whole, lower breaks, break rises, both break)",
385
- );
386
- assert(new Set(yinYang).size === 4, "Yin Yang Lines shows four distinct digrams");
387
- // The three bagua trigrams, pinned by codepoint, in the order the operator gave them.
388
- const bagua = SPINNER_PRESET_DEFS["Bagua Trigram"].frames;
389
- assert(bagua.join("|") === "\u2636|\u2635|\u2633", "Bagua Trigram frames as specified (mountain, water, thunder)");
390
- assert(new Set(bagua).size === 3, "Bagua Trigram shows three distinct trigrams");
391
- const worm = SPINNER_PRESET_DEFS["Dot Spine"].frames;
392
- assert(
393
- worm.join("|") === " \u2802\u2810 | \u283a \u2802\u2810 \u2817 |\u283a \u282a \u2802\u2810 \u2815 \u2817",
394
- "Dot Spine frames as specified",
395
- );
396
- // The core `⠂⠐` sits at columns 4-5 in every frame and the body grows outward around it, so
397
- // the centre never drifts; the glyph count grows 2 → 4 → 6.
398
- for (const frame of worm) assert([...frame].slice(4, 6).join("") === "\u2802\u2810", `Dot Spine keeps its core centred: ${JSON.stringify(frame)}`);
399
- assert(worm.map((f) => [...f].filter((c) => c !== " ").length).join() === "2,4,6", "Dot Spine adds one cell at each end per frame");
400
- for (const frames of [arrow, spark, pacman, worm]) {
401
- const widths = new Set(frames.map((f) => [...f].length));
402
- assert(widths.size === 1, `every frame of a multi-glyph preset is the same length: ${[...widths].join()}`);
403
- }
329
+ /** Flip the gradient override, persist it, and repaint the live spinner at once. */
330
+ export function setSpinnerGradient(on: boolean): void {
331
+ spinnerGradientSetting.set(on);
332
+ applySpinnerPreset(activeWorkingUi(), getActiveTheme<SpinnerThemeLike>());
333
+ }
404
334
 
405
- // The gradient closes: t=1 must equal t=0, or the 4s sweep would jump at the seam.
406
- assert(
407
- googleGradientRgb(0).join() === googleGradientRgb(1).join(),
408
- "the Google gradient wraps without a seam",
409
- );
410
- assert(googleGradientRgb(0.9999).join() !== googleGradientRgb(0.5).join(), "the gradient actually moves");
411
- assert(googleGradientRgb(-0.25).join() === googleGradientRgb(0.75).join(), "a negative t wraps like a positive one");
412
- for (const rgb of [googleGradientRgb(0), googleGradientRgb(0.37), googleGradientRgb(0.91)]) {
413
- assert(rgb.every((c) => Number.isInteger(c) && c >= 0 && c <= 255), `gradient stays in sRGB: ${rgb.join()}`);
414
- }
335
+ /** Publish the choice for this process, write it to config, and install it on the running session. */
336
+ export function setSpinnerPreset(preset: SpinnerPreset): void {
337
+ spinnerPresetSetting.set(preset);
338
+ applySpinnerPreset(activeWorkingUi(), getActiveTheme<SpinnerThemeLike>());
339
+ }
415
340
 
416
- // The accent painter must go through the theme, not a hardcoded colour.
417
- assert(
418
- spinnerPainter("Diamond Glow", { fg: (c, t) => `<${c}>${t}` })("x") === "<accent>x",
419
- "accent presets paint through the theme token",
420
- );
421
- assert(spinnerPainter("Diamond Glow", null)("x") === "x", "no theme -> identity painter, never a crash");
341
+ /** Updates custom painter on live workingStatusIndicator if available. */
342
+ export function paintLiveIndicator(painter: (text: string) => string): void {
343
+ const editor = getRuntime().editor as {
344
+ workingStatusIndicator?: {
345
+ renderIndicatorVerbatim?: boolean;
346
+ spinnerColorFn?: (text: string) => string;
347
+ updateDisplay?: () => void;
348
+ };
349
+ } | null;
350
+ const indicator = editor?.workingStatusIndicator;
351
+ if (!indicator) return;
352
+ indicator.renderIndicatorVerbatim = false;
353
+ indicator.spinnerColorFn = painter;
354
+ indicator.updateDisplay?.();
355
+ }
422
356
 
423
- // The `[g]` override reaches accent presets only: the two branded presets keep their identity.
424
- const override = spinnerPainter("Diamond Glow", { fg: (c, t) => `<${c}>${t}` }, true)("x");
425
- assert(override.startsWith("\x1b[38;2;") && override.endsWith("x\x1b[0m"), "gradient overrides an accent preset");
426
- assert(spinnerPainter("Diamond Glow", null, true)("x").startsWith("\x1b[38;2;"), "the override needs no theme");
427
- assert(
428
- spinnerPainter("Claudeon", { fg: (c, t) => `<${c}>${t}` }, true)("x").startsWith("\x1b[38;2;215;119;87m"),
429
- "gradient leaves Claudeon's own mark colour alone",
430
- );
431
- // Gemini already sweeps and Claudeon owns its mark colour, so `[g]` must not repaint either.
432
- assert(
433
- spinnerPainter("Gemini", null, true) === spinnerPainter("Gemini", null),
434
- "the flag is ignored on a preset that already sweeps",
435
- );
436
- assert(
437
- spinnerPainter("Claudeon", null, true)("x") === spinnerPainter("Claudeon", null)("x"),
438
- "the flag is ignored on the preset that carries a mark colour",
439
- );
440
- const grad = spinnerPainter("Gemini", null)("x");
441
- assert(grad.startsWith("\x1b[38;2;") && grad.endsWith("x\x1b[0m"), "the gradient painter emits truecolor + reset");
357
+ /** Applies preset to working indicator or restores system default for 'Pi (system)'. */
358
+ export function applySpinnerPreset(ui: WorkingUi, theme: SpinnerThemeLike = getActiveTheme<SpinnerThemeLike>()): void {
359
+ const preset = activeSpinnerPreset();
360
+ const def = SPINNER_PRESET_DEFS[preset];
361
+ const painter = spinnerPainter(preset, theme, activeSpinnerGradient());
362
+ try {
363
+ if (def.frames.length === 0) ui?.setWorkingIndicator?.();
364
+ else ui?.setWorkingIndicator?.({ frames: [...def.frames], intervalMs: def.intervalMs });
365
+ } catch {
366
+ // older host without the API -> pi's own frames stay
367
+ }
368
+ paintLiveIndicator(painter);
369
+ }
442
370
 
443
- // The sweep must be slow enough to read as motion: the frame interval is fixed per preset, so
444
- // the step size is what the cycle decides. Pin the measured ceiling rather than a taste.
445
- const stepCeiling = (intervalMs: number): number => {
446
- const steps = GRADIENT_CYCLE_MS / intervalMs;
447
- let worst = 0;
448
- for (let i = 0; i < steps; i++) {
449
- const a = googleGradientRgb(i / steps);
450
- const b = googleGradientRgb((i + 1) / steps);
451
- worst = Math.max(worst, Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]));
452
- }
453
- return worst;
371
+ /** Picker copy. The legend is built per call because its `[g]` row states the current mode. */
372
+ export function animationsPickerText(): { title: string; description: string; legend: string } {
373
+ return {
374
+ title: "Animations - Arnative\u2819",
375
+ description: "The working spinner — applies on the next tool call.",
376
+ legend: `[↑↓] Preview [g] Gradient ${activeSpinnerGradient() ? "on" : "off"} [Enter] Select [Esc] Back`,
454
377
  };
455
- assert(stepCeiling(200) <= 15, `the slowest preset steps <= 15 RGB units (got ${stepCeiling(200).toFixed(1)})`);
456
- assert(stepCeiling(80) <= 8, `the fastest preset steps <= 8 RGB units (got ${stepCeiling(80).toFixed(1)})`);
457
- assert(spinnerPainter("Claudeon", null)("x").startsWith("\x1b[38;2;215;119;87m"), "Claudeon uses its own mark colour");
378
+ }
458
379
 
459
- assert(previewFrames("Diamond Glow").split(" ").length === 4, "the picker preview shows every Diamond frame");
460
- assert(previewFrames("Pi (system)").length > 0, "Pi (system) still previews pi's Braille set");
380
+ /** One row per preset: the name, then its note and the frames it actually cycles. */
381
+ export function animationRows(): Array<{ label: string; note: string }> {
382
+ return SPINNER_PRESETS.map((preset) => ({
383
+ label: preset,
384
+ note: `${SPINNER_PRESET_DEFS[preset].note} ${previewFrames(preset)}`,
385
+ }));
386
+ }
461
387
 
462
- // Picker order: the two fixed rows first, then everything else alphabetically. Pinned
463
- // because a new preset must not land wherever the edit happened to be.
464
- assert(SPINNER_PRESETS[0] === "Pi (system)" && SPINNER_PRESETS[1] === "Arnative", "the two fixed rows lead the picker");
465
- const rest = SPINNER_PRESETS.slice(2);
466
- assert(
467
- rest.join() === [...rest].sort((a, b) => a.localeCompare(b)).join(),
468
- `the rest is alphabetical, got ${rest.join()}`,
469
- );
470
- assert(new Set(SPINNER_PRESETS).size === SPINNER_PRESETS.length, "every preset name is unique");
388
+ /** The row as one flat string, for the headless fallback and the self-check. */
389
+ export function animationRowText(preset: SpinnerPreset): string {
390
+ return `${preset}${ROW_DIVIDER}${SPINNER_PRESET_DEFS[preset].note} ${previewFrames(preset)}`;
391
+ }
392
+
393
+ /** Repaint cadence for the picker's animated row. */
394
+ export const PREVIEW_TICK_MS = 80;
471
395
 
472
- // The live preview reads the clock, so it advances without any stored counter.
473
- assert(previewFrameAt("Diamond Glow", 0).text === "\u2b25", "the preview starts on frame 0");
474
- assert(previewFrameAt("Diamond Glow", 200).text === "\u25c8", "the preview advances one frame per interval");
475
- assert(previewFrameAt("Diamond Glow", 800).text === "\u2b25", "the preview wraps at the end of the loop");
476
- assert(previewFrameAt("Pacman", 0).width === 7, "the preview reserves the widest frame");
396
+ /** Note for one row with the frame that is live now, padded to the widest frame. */
397
+ export function animationRowNote(preset: SpinnerPreset, now = Date.now()): string {
398
+ const { text, width } = previewFrameAt(preset, now);
399
+ const pad = " ".repeat(Math.max(0, width - [...text].length));
400
+ return `${SPINNER_PRESET_DEFS[preset].note} ${text}${pad}`;
401
+ }
477
402
 
478
- console.log("spinner.ts self-check OK");
479
- }
403
+ export const __test = {
404
+ SPINNER_PRESET_CONFIG_KEY: spinnerPresetSetting.slot,
405
+ };
@@ -12,8 +12,7 @@
12
12
  *
13
13
  * Lives outside `extensions/*.ts` so pi never loads it as an extension.
14
14
  */
15
- import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
16
- import { assert, isMain } from "./check.ts";
15
+ import { truncateToWidth } from "@earendil-works/pi-tui";
17
16
 
18
17
  /** The mark that leads a block of rows above the chat column. */
19
18
  export const STATUS_ICON = "\ueb1b";
@@ -64,31 +63,6 @@ export function announce(ui: { notify?(message: string, type?: string): void } |
64
63
  ui?.notify?.("[arnative] " + message, "info");
65
64
  }
66
65
 
67
- if (isMain(import.meta.url)) {
68
- const tag = (color: string, text: string) => `<${color}>${text}</${color}>`;
69
- assert(
70
- JSON.stringify(statusRows({ fg: tag }, ["model-heal: healed"])) === JSON.stringify(["<dim> \ueb1b model-heal: healed</dim>"]),
71
- "one space before the mark, one after, one dim span for the whole row",
72
- );
73
- assert(JSON.stringify(statusRows(null, ["plain"])) === JSON.stringify([" \ueb1b plain"]), "no theme renders the plain line");
74
- assert(
75
- JSON.stringify(statusRows(null, ["\u{f06de} model-heal: x", "y"])) === JSON.stringify([" \u{f06de} model-heal: x", " y"]),
76
- "a row that opens with its own glyph keeps it as the mark",
77
- );
78
- assert(
79
- JSON.stringify(statusRows({ fg: () => { throw new Error("unknown token"); } }, ["safe"])) === JSON.stringify([" \ueb1b safe"]),
80
- "a theme that rejects the token does not crash the render",
81
- );
82
- assert(
83
- JSON.stringify(statusRows({ fg: tag }, ["one", "\x1b[31mtwo\x1b[39m"])) ===
84
- JSON.stringify(["<dim> \ueb1b one</dim>", "<dim> </dim>\x1b[31mtwo\x1b[39m"]),
85
- "an already-painted row keeps its own colour, continuation rows align under the text",
86
- );
87
- const long = statusRows({ fg: tag }, new Array(20).fill("x"));
88
- assert(long.length === MAX_STATUS_ROWS + 1 && long.at(-1)!.includes("widget truncated"), "a long block is capped like pi's own");
89
- assert(statusRows(null, []).length === 0, "an empty block renders nothing");
90
- // A component owns its width: a line wider than the terminal must be cut, not wrapped.
91
- const wide = statusRows({ fg: tag }, ["x".repeat(200)], 20);
92
- assert(wide.length === 1 && visibleWidth(wide[0]!) === 20, "rows are cut to the render width");
93
- console.log("status-widget.ts self-check OK");
94
- }
66
+ export const __test = {
67
+ dim,
68
+ };