@bismawy/pi-arnative 0.16.1 → 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 (61) 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 -327
  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 +113 -161
  18. package/{extensions → lib/features}/timestamps.ts +18 -94
  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/themes/arnative-blossom.json +0 -0
  40. package/themes/arnative-crimson.json +0 -0
  41. package/themes/arnative-cyberpunk.json +0 -0
  42. package/themes/arnative-dracula.json +0 -0
  43. package/themes/arnative-earthy.json +0 -0
  44. package/themes/arnative-garden.json +0 -0
  45. package/themes/arnative-gruvbox.json +0 -0
  46. package/themes/arnative-lemonade.json +0 -0
  47. package/themes/arnative-magical.json +0 -0
  48. package/themes/arnative-matrix.json +0 -0
  49. package/themes/arnative-neutral.json +0 -0
  50. package/themes/arnative-nord.json +0 -0
  51. package/themes/arnative-zinc.json +0 -0
  52. package/themes/arnative.json +0 -0
  53. package/CHANGELOG.md +0 -683
  54. package/extensions/animations.ts +0 -242
  55. package/extensions/footer.ts +0 -2617
  56. package/extensions/tools.ts +0 -2231
  57. package/extensions/ui-render-tweaks.ts +0 -1005
  58. package/extensions/usage-export.ts +0 -283
  59. package/extensions/usage.ts +0 -1406
  60. package/lib/check.ts +0 -21
  61. package/themes/gen-themes.mjs +0 -715
package/README.md CHANGED
@@ -14,7 +14,7 @@ Refined aesthetics. Cohesive tools. Built for Pi.
14
14
 
15
15
  - **Themes:** 14 contrast-checked OKLCH themes (`arnative` and 13 variants).
16
16
  - **Header:** Tabbed box showing Directory, Model, Context, Skills, Extensions, and Shortcuts.
17
- - **Tool boxes:** Rounded borders with status, spinner, duration, and clickable `[show]` or `[hide]` toggles.
17
+ - **Tool boxes:** Grouped by default into one clickable chronological phase accordion per turn (`/arnative` → `Tool layout`), with the final reply below it. `Classic` restores the per-tool rounded boxes with status, spinner, duration, and clickable `[show]` or `[hide]` toggles.
18
18
  - **Task list:** `todo` tool, `/todos` recap screen, and a boxed widget above the editor that hides 30s after all tasks finish.
19
19
  - **Footer:** 3-row status grid (`Arnative (Full)`) or a single collapsible row (`Arnative (Minimal)`) with git branch, diff stats, active duration, token speed, and optional session cost.
20
20
  - **Spinners and timestamps:** 18 animated spinner presets with an optional `[g]` gradient sweep, plus per-message timestamps and bubble backgrounds.
@@ -89,6 +89,7 @@ Settings from `/arnative` are saved in `~/.pi/agent/arnative/config.json`:
89
89
  - **Footer cost:** Off by default. Press `[c]` in the Footers picker to show session cost (`$0.42`, or `~$0.42` when estimated) in the metrics row.
90
90
  - **Chatbox:** `Arnative` (default rounded box with 12 prompt icons cycled via `[i]`, colored `primary` while typing and `dim` after 3s idle) or `Pi (system)`. Press `[D]` to position the working status dialog (`Left`, `Center`, `Right`, `Inside`, `Outside`).
91
91
  - **Animations:** 18 presets (`Arnative` default, `Pi (system)`, and variants). Press `[g]` in the picker to toggle the gradient sweep.
92
+ - **Tool layout:** `Grouped` by default. Each turn collapses into one accordion of chronological phases (`Explored`, `Updated`, `Ran`, named from what the tools did) with auto-expanded running and failed phases and `↑`/`↓ N more` scrolling on tall turns. `Classic` renders every tool in its own box.
92
93
  - **Render cache:** `On` by default. Reuses rendered lines for settled transcript items in `chatContainer`. Streaming items, active animations, and custom renderers bypass the cache.
93
94
  - **Auto-compact:** `Off` by default (Pi core compaction handles context). `Smart` adapts to `Render cache` and `contextWindow` (triggers at 90% on `>= 192k` windows when `Render cache` is `On`, or conservative tiers when `Off`). Fixed budgets (`100k` to `400k`) trigger at an absolute token count, subject to Pi core `reserveTokens` and provider limits.
94
95
  - **Payload limit:** Configured in `/arnative` or `PI_ARNATIVE_BYTE_WALL_MB` (`Off`, `1 MB`, `4 MB`, `8 MB`, `16 MB`, `32 MB`, or `Custom` from 1 to 1024 MB). For `remote/*`, `remote-magpie/*`, and models that return HTTP 413, payloads near the ceiling are trimmed in memory before sending without changing session history.
@@ -102,23 +103,31 @@ Settings from `/arnative` are saved in `~/.pi/agent/arnative/config.json`:
102
103
 
103
104
  | File | Role |
104
105
  | --- | --- |
105
- | `extensions/arnative.ts` | `/arnative` settings menu and live preview pickers |
106
- | `extensions/section-headers.ts` | Tabbed header and resource box |
107
- | `extensions/footer.ts` | 3-row status grid, Minimal footer, and boxed editor |
108
- | `extensions/tools.ts` | Rounded tool boxes, spinners, duration, and `[show]` / `[hide]` toggles |
109
- | `extensions/todos.ts` | `todo` tool, boxed widget above editor, and `/todos` screen |
110
- | `extensions/animations.ts` | Spinner preset picker and live preview |
111
- | `extensions/autocompact.ts` | Smart and fixed-budget context compaction plus silent byte-wall shedding |
112
- | `extensions/render-cache.ts` | Per-child and container transcript render cache for `chatContainer` |
113
- | `extensions/budget.ts` | UTC day and rolling 30-day spend caps and footer warnings |
114
- | `extensions/usage-export.ts` | Prometheus textfile metric export (`usage.prom`) |
115
- | `extensions/model-heal.ts` | Automatic `models.json` heal triggers and `/model-heal` |
116
- | `extensions/timestamps.ts` | Message timestamps and bubble backgrounds |
117
- | `extensions/ui-render-tweaks.ts` | Contrast tweaks, selection styling, and UI polish |
118
- | `extensions/usage.ts` | Token and cost dashboard (`/usage`) |
106
+ | `extensions/index.ts` | Single Pi extension entry point composing all features |
107
+ | `lib/runtime.ts` | Centralized reload-safe `RuntimeState` and single-listener lifecycle hub |
108
+ | `lib/features/arnative.ts` | `/arnative` settings menu and live preview pickers |
109
+ | `lib/features/headers.ts` | Tabbed header and resource box |
110
+ | `lib/features/footer.ts` | 3-row status grid, Minimal footer, and boxed editor |
111
+ | `lib/features/tools.ts` | Rounded tool boxes, spinners, duration, and `[show]` / `[hide]` toggles |
112
+ | `lib/features/todos.ts` | `todo` tool, boxed widget above editor, and `/todos` screen |
113
+ | `lib/features/animations.ts` | Spinner preset picker and live preview |
114
+ | `lib/features/auto-compact.ts` | Smart and fixed-budget context compaction plus silent byte-wall shedding |
115
+ | `lib/features/render-cache.ts` | Per-child and container transcript render cache for `chatContainer` |
116
+ | `lib/features/budget.ts` | UTC day and rolling 30-day spend caps and footer warnings |
117
+ | `lib/features/usage-export.ts` | Prometheus textfile metric export (`usage.prom`) |
118
+ | `lib/features/model-heal.ts` | Automatic `models.json` heal triggers and `/model-heal` |
119
+ | `lib/features/timestamps.ts` | Message timestamps and bubble backgrounds |
120
+ | `lib/features/ui-render-tweaks.ts` | Contrast tweaks, selection styling, and UI polish |
121
+ | `lib/features/usage.ts` | Token and cost dashboard (`/usage`) |
119
122
  | `lib/todos.ts` | Task state, window layout, box rows, and session store |
120
123
  | `lib/spinner.ts` | Spinner preset catalog, frames, and gradient painters |
121
- | `lib/provider.ts` | Custom provider probe, model picker, and config writer |
124
+ | `lib/active-clock.ts` | Active session clock, duration formatting, and input activity filter |
125
+ | `lib/git-status.ts` | Git branch/status/diff-stat collector and path shortener |
126
+ | `lib/chatbox.ts` | Editor frame, prompt glyph styling, scroll borders, and dialog placement |
127
+ | `lib/edit-diff.ts` | Unified and side-by-side word-level edit diff renderer |
128
+ | `lib/provider-store.ts` | Custom provider probe, metadata merge, and `models.json` / `auth.json` store |
129
+ | `lib/provider.ts` | Interactive `/providers` wizard UI |
130
+ | `lib/usage-pricing.ts` | `models.json` price table loader, cost estimation, and UTC range math |
122
131
  | `lib/model-heal.ts` | Compat flags, `/models` limit sync, and reasoning effort probe |
123
132
  | `lib/list-picker.ts` | Shared live-preview and multi-select picker component |
124
133
 
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Single Pi extension entry point for @bismawy/pi-arnative.
3
+ *
4
+ * Pi's loader evaluates each file listed in `pi.extensions` with an isolated
5
+ * jiti instance (`moduleCache: false`). Composing all features from one entry
6
+ * point keeps a single module graph per load/reload instead of recompiling
7
+ * shared `lib/` modules up to 14 times.
8
+ */
9
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
+ import { registerLifecycleFeatures } from "../lib/runtime.ts";
11
+ import registerArnative from "../lib/features/arnative.ts";
12
+ import registerAutoCompact from "../lib/features/auto-compact.ts";
13
+ import registerBudget from "../lib/features/budget.ts";
14
+ import registerFooter from "../lib/features/footer.ts";
15
+ import registerModelHeal from "../lib/features/model-heal.ts";
16
+ import registerRenderCache from "../lib/features/render-cache.ts";
17
+ import registerSectionHeaders from "../lib/features/headers.ts";
18
+ import registerTimestamps from "../lib/features/timestamps.ts";
19
+ import registerTodos from "../lib/features/todos.ts";
20
+ import registerTools from "../lib/features/tools.ts";
21
+ import registerUiRenderTweaks from "../lib/features/ui-render-tweaks.ts";
22
+ import registerUsage from "../lib/features/usage.ts";
23
+
24
+ const FEATURES: readonly ((pi: ExtensionAPI) => void)[] = [
25
+ registerTools,
26
+ registerSectionHeaders,
27
+ registerFooter,
28
+ registerTimestamps,
29
+ registerUiRenderTweaks,
30
+ registerRenderCache,
31
+ registerUsage,
32
+ registerBudget,
33
+ registerAutoCompact,
34
+ registerModelHeal,
35
+ registerTodos,
36
+ registerArnative,
37
+ ];
38
+
39
+ export default function registerPiArnative(pi: ExtensionAPI): void {
40
+ registerLifecycleFeatures(pi, FEATURES);
41
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Active session duration tracking and duration formatting.
3
+ *
4
+ * `ActiveClock` stores its snapshot in `RuntimeState` so `/reload` keeps accumulated
5
+ * active time without resetting a running session.
6
+ */
7
+ import { getRuntime } from "./runtime.ts";
8
+
9
+ export const IDLE_PAUSE_MS = 30_000;
10
+
11
+ /**
12
+ * Tracks active session duration, freezing after inactivity periods.
13
+ * State is stored on RuntimeState to survive module reloads.
14
+ */
15
+ export class ActiveClock {
16
+ active: number;
17
+ runStarted: number;
18
+ lastSeen: number;
19
+ readonly pauseMs: number;
20
+
21
+ constructor(startedAt: number, pauseMs: number = IDLE_PAUSE_MS) {
22
+ const saved = getRuntime().activeClock;
23
+ this.pauseMs = pauseMs;
24
+ this.active = typeof saved?.active === "number" ? saved.active : 0;
25
+ this.runStarted = typeof saved?.runStarted === "number" ? saved.runStarted : startedAt;
26
+ this.lastSeen = typeof saved?.lastSeen === "number" ? saved.lastSeen : startedAt;
27
+ }
28
+
29
+ /** Committed runs plus the live one, the live part clamped at `lastSeen + pauseMs`. */
30
+ total(now: number = Date.now()): number {
31
+ return this.active + Math.max(0, Math.min(now, this.lastSeen + this.pauseMs) - this.runStarted);
32
+ }
33
+
34
+ /** Activity: commits a run left longer than `pauseMs`, else just moves `lastSeen`. */
35
+ tick(now: number = Date.now()): void {
36
+ if (now - this.lastSeen > this.pauseMs) {
37
+ this.active = this.total(now);
38
+ this.runStarted = now;
39
+ }
40
+ this.lastSeen = now;
41
+ getRuntime().activeClock = {
42
+ active: this.active,
43
+ runStarted: this.runStarted,
44
+ lastSeen: this.lastSeen,
45
+ };
46
+ }
47
+
48
+ idle(now: number = Date.now()): boolean {
49
+ return now - this.lastSeen > this.pauseMs;
50
+ }
51
+ }
52
+
53
+ /** Sums active duration from recorded session entries up to pause threshold. */
54
+ export function seedActiveMs(entries: readonly unknown[], pauseMs: number = IDLE_PAUSE_MS, now: number = Date.now()): number {
55
+ const times: number[] = [];
56
+ for (const entry of entries) {
57
+ const ts = (entry as { timestamp?: string } | null)?.timestamp;
58
+ const parsed = ts ? Date.parse(ts) : NaN;
59
+ if (Number.isFinite(parsed) && parsed <= now) times.push(parsed);
60
+ }
61
+ times.sort((a, b) => a - b);
62
+ let ms = 0;
63
+ for (let i = 1; i < times.length; i++) {
64
+ const gap = times[i]! - times[i - 1]!;
65
+ if (gap > 0 && gap <= pauseMs) ms += gap;
66
+ }
67
+ return ms;
68
+ }
69
+
70
+ export function resolveSessionStartMs(reason: string, headerTimestamp: string | undefined, now: number): number {
71
+ if (reason === "reload") return now;
72
+ const parsed = headerTimestamp ? Date.parse(headerTimestamp) : NaN;
73
+ return Number.isFinite(parsed) && parsed > 0 && parsed <= now ? parsed : now;
74
+ }
75
+
76
+ export function formatDuration(ms: number): string {
77
+ // Sub-second renders as "-" to avoid a "0s" flash on fresh session.
78
+ if (!ms || ms < 1000) return "-";
79
+ const totalSec = Math.floor(ms / 1000);
80
+ const h = Math.floor(totalSec / 3600);
81
+ const m = Math.floor((totalSec % 3600) / 60);
82
+ const s = totalSec % 60;
83
+ if (h > 0) return `${h}h ${m}m`;
84
+ if (m > 0) return `${m}m ${s}s`;
85
+ return `${s}s`;
86
+ }
87
+
88
+ /** Pointer motion and terminal focus reports are not user activity. */
89
+ export function isPointerOrFocusInput(data: string): boolean {
90
+ return data.startsWith("\x1b[<") || data.startsWith("\x1b[M") || data === "\x1b[I" || data === "\x1b[O";
91
+ }
package/lib/ansi.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { assert, isMain } from "./check.ts";
1
+
2
+ import { getRuntime } from "./runtime.ts";
2
3
 
3
4
  /** Theme bg open-code, stripped of its trailing \x1b[49m reset. */
4
5
  export function ansiBgOpen(th: { bg?(color: string, text: string): string } | null, color: string): string {
@@ -20,22 +21,49 @@ export function stripAnsi(s: string): string {
20
21
  return s.replace(ANSI_RE, "");
21
22
  }
22
23
 
24
+ /** Per-theme cache of whether each `fg` token exists. Pi's `Theme.fg` throws for an unknown
25
+ * token, and the footer probes optional slots (`toolDiffAdded`, `warning`, ...) on every
26
+ * frame — one throw per frame per missing token. The answer never changes for a theme
27
+ * instance, so both hits and misses are cached once. */
28
+ const fgTokenSupport = new WeakMap<object, Map<string, boolean>>();
29
+
30
+ /** Painter for `color` when the theme defines it, else `fallback`. Probed once per theme. */
31
+ export function fgOr(
32
+ th: { fg?(color: string, text: string): string } | null | undefined,
33
+ color: string,
34
+ fallback: (text: string) => string,
35
+ ): (text: string) => string {
36
+ const fg = th?.fg?.bind(th);
37
+ if (!fg || !th) return fallback;
38
+ let known = fgTokenSupport.get(th);
39
+ if (!known) {
40
+ known = new Map();
41
+ fgTokenSupport.set(th, known);
42
+ }
43
+ let ok = known.get(color);
44
+ if (ok === undefined) {
45
+ try {
46
+ fg(color, "");
47
+ ok = true;
48
+ } catch {
49
+ ok = false;
50
+ }
51
+ known.set(color, ok);
52
+ }
53
+ return ok ? (text) => fg(color, text) : fallback;
54
+ }
55
+
23
56
  /** The active pi theme out of an event ctx (`ctx.ui.theme`), null when absent. */
24
57
  export function themeOf<T>(ctx: unknown): T | null {
25
58
  return (ctx as { ui?: { theme?: T } } | null | undefined)?.ui?.theme ?? null;
26
59
  }
27
60
 
28
- // Shared active-theme slot. `/reload` re-imports an extension's modules, so two copies
29
- // can coexist: one carries the session_start handler, the other owns a stacked UI patch.
30
- // globalThis gives both the same theme, so the patched copy paints instead of drawing
31
- // uncolored (or, before the null-guard fix, crashing). Set from `session_start`.
32
- const THEME_PROXY_KEY = Symbol.for("pi-arnative.activeThemeProxy");
61
+ // Shared active-theme slot on RuntimeState so `/reload` keeps the live theme.
33
62
  export function getActiveTheme<T>(): T | null {
34
- return (globalThis as Record<symbol, T>)[THEME_PROXY_KEY] ?? null;
63
+ return (getRuntime().activeTheme as T | null) ?? null;
35
64
  }
36
65
  export function setActiveTheme<T>(th: T | null): void {
37
- if (th) (globalThis as Record<symbol, T>)[THEME_PROXY_KEY] = th;
38
- else delete (globalThis as Record<symbol, T>)[THEME_PROXY_KEY];
66
+ getRuntime().activeTheme = (th as object | null) ?? null;
39
67
  }
40
68
 
41
69
  /**
@@ -144,72 +172,6 @@ export function thinkingColorOf(
144
172
  }
145
173
  }
146
174
 
147
- // Self-check: `node lib/ansi.ts`
148
- if (isMain(import.meta.url)) {
149
- assert(ansiBgOpen(null, "selectedBg") === "", "no theme: empty");
150
- assert(ansiBgOpen({ bg: (_c, t) => `\x1b[48;2;9;9;9m${t}\x1b[49m` }, "selectedBg") === "\x1b[48;2;9;9;9m", "bg probe without reset");
151
- assert(stripAnsi("\x1b[2mA\x1b[22m") === "A", "stripAnsi removes SGR colors");
152
- assert(stripAnsi("x\x1b[K") === "x", "stripAnsi removes non-SGR CSI too");
153
- assert(themeOf({ ui: { theme: "T" } }) === "T", "themeOf reads ctx.ui.theme");
154
- assert(themeOf(null) === null, "themeOf tolerates a missing ctx");
155
-
156
- setActiveTheme({ fg: (c, t) => `<${c}>${t}</${c}>` });
157
- assert(getActiveTheme<object>() !== null, "active theme round-trips through globalThis");
158
- setActiveTheme(null);
159
- assert(getActiveTheme<object>() === null, "clearing the active theme leaves no stale slot");
160
-
161
- const tag = { fg: (c: string, t: string) => `<${c}>${t}</${c}>` };
162
- assert(softOf(tag)("x") === "<accentSoft>x</accentSoft>", "softOf uses accentSoft when the theme defines it");
163
- const noSoft = {
164
- fg: (c: string, t: string) => {
165
- if (c === "accentSoft") throw new Error("Unknown theme color: accentSoft");
166
- return `<${c}>${t}</${c}>`;
167
- },
168
- };
169
- assert(softOf(noSoft)("x") === "<muted>x</muted>", "softOf falls back to muted without the token or colors");
170
- assert(softOf(null)("x") === "x", "softOf without a theme is identity");
171
- // Pi 1.2.0: accentSoft is rejected, so the soft tint is derived from `colors.accent`.
172
- const modern = {
173
- fg: (c: string, t: string) => {
174
- throw new Error(`Unknown theme color: ${c}`);
175
- },
176
- style: (t: string, o: { fg: unknown }) => `<soft:${JSON.stringify(o.fg)}>${t}</soft>`,
177
- colors: { accent: { kind: "oklch", c: 0.2, h: 355 }, borderAccent: { kind: "oklch", c: 0.1, h: 200 } },
178
- };
179
- const modernOut = softOf(modern)("x");
180
- assert(
181
- Math.abs(JSON.parse(modernOut.match(/<soft:(.*)>x<\/soft>/)[1]!).c - 0.07) < 1e-9 &&
182
- modernOut.includes('"l":0.9'),
183
- "softOf derives the soft tint from accent (l=0.9, c=accent*0.35)",
184
- );
185
- assert(modernOut.includes("x"), "softOf keeps the text");
186
- // The label tier softens `borderAccent`, NOT `accent`: that is what keeps footer text
187
- // on the blue tier instead of inheriting the pink accent hue.
188
- const labelOut = softSecondaryOf(modern)("x");
189
- assert(
190
- Math.abs(JSON.parse(labelOut.match(/<soft:(.*)>x<\/soft>/)[1]!).c - 0.035) < 1e-9 &&
191
- labelOut.includes('"l":0.9') &&
192
- labelOut.includes('"h":200'),
193
- "softSecondaryOf softens borderAccent (l=0.9, c=borderAccent*0.35, same hue)",
194
- );
195
- assert(labelOut !== modernOut, "the soft label tier differs from the soft accent tier");
196
- assert(softSecondaryOf({ fg: () => "", style: (t) => `<x>${t}</x>`, colors: {} })("x") === softOf({ fg: () => "", style: (t) => `<x>${t}</x>`, colors: {} })("x"), "softSecondaryOf falls back to softOf without a borderAccent");
197
-
198
- assert(thinkingColorSlot("off") === "thinkingOff", "thinking off maps to thinkingOff");
199
- assert(thinkingColorSlot(undefined) === "thinkingOff", "missing level falls back to thinkingOff");
200
- assert(thinkingColorSlot("HIGH") === "thinkingHigh", "matching is case-insensitive");
201
- assert(thinkingColorSlot("xhigh") === "thinkingXhigh", "xhigh has its own slot");
202
- assert(thinkingColorSlot("max") === "thinkingMax", "max maps to thinkingMax");
203
- assert(thinkingColorSlot("nonsense") === "thinkingOff", "an unknown level degrades to thinkingOff");
204
- assert(thinkingColorOf(tag, "high")("x") === "<thinkingHigh>x</thinkingHigh>", "thinkingColorOf paints the level's slot");
205
- assert(thinkingColorOf(tag, undefined)("x") === "<thinkingOff>x</thinkingOff>", "thinkingColorOf defaults to thinkingOff");
206
- assert(thinkingColorOf(null, "high")("x") === "x", "thinkingColorOf without a theme is identity");
207
- const noThinking = {
208
- fg: (c: string, t: string) => {
209
- if (c.startsWith("thinking")) throw new Error(`Unknown theme color: ${c}`);
210
- return `<${c}>${t}</${c}>`;
211
- },
212
- };
213
- assert(thinkingColorOf(noThinking, "max")("x") === "<dim>x</dim>", "thinkingColorOf falls back to dim without the slot");
214
- console.log("lib/ansi.ts OK");
215
- }
175
+ export const __test = {
176
+ thinkingColorSlot,
177
+ };
package/lib/box.ts CHANGED
@@ -5,7 +5,6 @@
5
5
  */
6
6
  import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
7
7
  import { stripAnsi, thinkingColorOf } from "./ansi.ts";
8
- import { assert, isMain } from "./check.ts";
9
8
 
10
9
  /** A clickable span inside rendered lines: 0-based cell columns, inclusive. */
11
10
  export interface TextSpan {
@@ -40,10 +39,58 @@ export function textSpans(lines: readonly string[], text: string): TextSpan[] {
40
39
  export const inSpans = (spans: readonly TextSpan[], row: number, x: number): boolean =>
41
40
  spans.some((span) => span.row === row && x >= span.start && x <= span.end);
42
41
 
42
+ /** Delay before holding a scroll affordance starts repeating, so a normal click scrolls once. */
43
+ export const HOLD_DELAY_MS = 250;
44
+ /** Repeat interval while holding a scroll affordance. */
45
+ const HOLD_REPEAT_MS = 90;
46
+
47
+ export interface HoldRepeat {
48
+ start(step: () => boolean): void;
49
+ stop(): void;
50
+ }
51
+
52
+ /** Shared press-and-hold auto-repeat timer for scrollable TUI boxes. */
53
+ export function createHoldRepeat(delayMs = HOLD_DELAY_MS, repeatMs = HOLD_REPEAT_MS): HoldRepeat {
54
+ let delay: ReturnType<typeof setTimeout> | undefined;
55
+ let repeat: ReturnType<typeof setInterval> | undefined;
56
+ let token = 0;
57
+
58
+ const stop = (): void => {
59
+ token++;
60
+ if (delay) {
61
+ clearTimeout(delay);
62
+ delay = undefined;
63
+ }
64
+ if (repeat) {
65
+ clearInterval(repeat);
66
+ repeat = undefined;
67
+ }
68
+ };
69
+
70
+ const start = (step: () => boolean): void => {
71
+ stop();
72
+ const run = token;
73
+ delay = setTimeout(() => {
74
+ delay = undefined;
75
+ if (run !== token) return;
76
+ if (!step()) {
77
+ stop();
78
+ return;
79
+ }
80
+ if (run !== token) return;
81
+ repeat = setInterval(() => {
82
+ if (run !== token || !step()) stop();
83
+ }, repeatMs);
84
+ }, delayMs);
85
+ };
86
+
87
+ return { start, stop };
88
+ }
89
+
43
90
  export type BoxTheme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; bold?(text: string): string };
44
91
  type Dim = (s: string) => string;
45
92
 
46
- export const boxEdge = (l: string, r: string, width: number, dim: Dim): string =>
93
+ const boxEdge = (l: string, r: string, width: number, dim: Dim): string =>
47
94
  dim(`${l}${"─".repeat(Math.max(0, width - 2))}${r}`);
48
95
 
49
96
  /** Content row: │ <text> │, exactly `width` wide. Content is truncated to preserve border. */
@@ -147,69 +194,3 @@ export function renderBoxRows(
147
194
  export function renderBoxLines(theme: BoxTheme | null, width: number, rows: string[], bgType?: string, border: BoxBorder = "dim"): string[] {
148
195
  return renderBoxRows(theme, width, rows, bgType, border).lines;
149
196
  }
150
-
151
- if (isMain(import.meta.url)) {
152
- const th: BoxTheme = { fg: (_c, t) => t };
153
- const plain = renderBoxLines(th, 24, ["hello", "a rather long world"]);
154
- assert(plain[0]!.startsWith("╭") && plain[plain.length - 1]!.startsWith("╰"), "top/bottom frame intact");
155
- assert(plain.every((l) => visibleWidth(l) === 24), "every line is 24 wide");
156
- assert(plain[1] === "│ hello │", "content line padded flush");
157
- assert(renderBoxLines(th, 24, ["x".repeat(40)]).length === 4, "long line wrapped");
158
- assert(renderBoxLines(th, 20, ["hi"], "customMessageBg").length === 3, "bg ignored when the theme has no bg");
159
- // A row wider than the box must lose its own tail, never its right wall: `boxRow` used to
160
- // pad only, so the wall overflowed `width` and the caller's `truncateToWidth` cut the wall.
161
- const overlong = boxRow("x".repeat(60), 20, (s) => s);
162
- assert(visibleWidth(overlong) === 20, `an overlong row is still exactly the width, got ${visibleWidth(overlong)}`);
163
- assert(overlong.endsWith("│"), `an overlong row keeps its right wall, got ${JSON.stringify(overlong)}`);
164
- assert(!overlong.includes("x".repeat(17)), "an overlong row truncates its own content");
165
- const nullTheme = renderBoxLines(null, 24, ["hello"], "customMessageBg");
166
- assert(nullTheme.every((l) => visibleWidth(l) === 24), "null theme renders an uncolored box instead of throwing");
167
- assert(nullTheme[0]!.startsWith("╭") && nullTheme[1] === "│ hello │", "null-theme frame and padding intact");
168
- // Rule 5: too narrow for `│ │`, a row is empty rather than 4 columns wide — pi may hand a
169
- // component the width of a sidebar, and a 4-wide row would overflow it.
170
- for (const w of [1, 2, 3]) assert(boxRow("hello", w, (s) => s) === "", `a row narrower than four columns is empty at width ${w}`);
171
-
172
- // The shared screen chrome: one sequence for every arnative screen.
173
- assert(screenTitle("Settings") === `Settings - Arnative${BRAND}`, "screenTitle pins the <setting> - <extension> shape");
174
- assert(screenTitle("Usage") === "Usage - Arnative\u2819", "the brand is the braille mark, not a Nerd Font glyph");
175
- const screen = renderScreen(th, 60, { title: "Usage - Arnative\u2819", description: "Token & cost", legend: "[Esc] Close" }, ["a row", ""]);
176
- assert(screen[0]!.startsWith("╭") && screen[screen.length - 1]!.startsWith("╰"), "screen frame intact");
177
- assert(screen.every((l) => visibleWidth(l) === 60), "every screen line is exactly the width");
178
- assert(screen[1]!.includes("Usage - Arnative\u2819"), "the title sits on the first row inside the frame");
179
- assert(screen[2]!.includes("Token & cost"), "the description sits under the title");
180
- assert(screen[screen.length - 2]!.includes("[Esc] Close"), "the legend is the last row above the bottom edge");
181
- // No full-width rule inside the frame (skill rule 7): the chrome is the whole chrome.
182
- assert(!screen.some((l) => /[├┤]/.test(l)), "the shared chrome draws no inner rule");
183
- const taggedBox = { fg: (c: string, t: string) => `<${c}>${t}</>`, bold: (t: string) => `<bold>${t}</bold>` };
184
- const taggedScreen = renderScreen(taggedBox, 60, { title: "T", description: "d", legend: "l" }, []);
185
- assert(taggedScreen[1]!.includes("<accent><bold>T"), "the title is accent + bold");
186
- assert(taggedScreen[2]!.includes("<muted>d"), "the description is muted");
187
- assert(taggedScreen[taggedScreen.length - 2]!.includes("<dim>l"), "the legend is dim");
188
- assert(renderScreen(null, 40, { title: "t", description: "d", legend: "l" }, ["x"]).every((l) => visibleWidth(l) === 40), "a null theme still frames the screen");
189
- // A legend that styles itself (the models picker accents its picked count) renders
190
- // verbatim: no dim wrap that would mute the accent and leak a reset into the tail.
191
- const styled = renderScreen(th, 60, { title: "t", description: "d", legend: "<accent>34/44 picked</accent><dim> · keys</dim>" }, []);
192
- assert(styled[styled.length - 2]!.includes("<accent>34/44 picked</accent>"), "a pre-styled legend renders verbatim");
193
- // The header copy is longer than a narrow terminal: the wall must win over the text.
194
- const longCopy = "Selection previews live — arnative themes only (all themes: /settings → Theme).";
195
- for (const w of [40, 50, 56, 60]) {
196
- const narrow = renderScreen(th, w, { title: screenTitle("Themes"), description: longCopy, legend: "[Esc] Back" }, []);
197
- assert(narrow.every((l) => visibleWidth(l) === w), `a long description keeps every line at width ${w}`);
198
- assert(
199
- narrow.filter((l) => l.startsWith("│")).every((l) => l.endsWith("│")),
200
- `a long description keeps the right wall at width ${w}`,
201
- );
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}`);
214
- console.log("lib/box.ts OK");
215
- }