@bismawy/pi-arnative 0.15.0 → 0.16.1

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 (48) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +52 -67
  3. package/extensions/animations.ts +11 -26
  4. package/extensions/arnative.ts +253 -380
  5. package/extensions/autocompact.ts +17 -22
  6. package/extensions/budget.ts +87 -136
  7. package/extensions/footer.ts +79 -60
  8. package/extensions/model-heal.ts +0 -0
  9. package/extensions/render-cache.ts +29 -15
  10. package/extensions/section-headers.ts +4 -8
  11. package/extensions/timestamps.ts +118 -41
  12. package/extensions/todos.ts +83 -33
  13. package/extensions/tools.ts +13 -30
  14. package/extensions/ui-render-tweaks.ts +0 -0
  15. package/extensions/usage-export.ts +3 -12
  16. package/extensions/usage.ts +0 -0
  17. package/lib/ansi.ts +0 -0
  18. package/lib/box.ts +0 -0
  19. package/lib/check.ts +0 -0
  20. package/lib/color.ts +0 -0
  21. package/lib/compat.ts +117 -17
  22. package/lib/format.ts +0 -0
  23. package/lib/list-picker.ts +5 -5
  24. package/lib/model-heal.ts +4 -8
  25. package/lib/patch.ts +0 -0
  26. package/lib/preset-store.ts +63 -16
  27. package/lib/provider.ts +131 -17
  28. package/lib/shortcuts.ts +0 -0
  29. package/lib/spinner.ts +1 -1
  30. package/lib/status-widget.ts +0 -0
  31. package/lib/todos.ts +0 -0
  32. package/lib/usage-store.ts +11 -20
  33. package/package.json +1 -1
  34. package/themes/arnative-blossom.json +0 -0
  35. package/themes/arnative-crimson.json +0 -0
  36. package/themes/arnative-cyberpunk.json +0 -0
  37. package/themes/arnative-dracula.json +0 -0
  38. package/themes/arnative-earthy.json +0 -0
  39. package/themes/arnative-garden.json +0 -0
  40. package/themes/arnative-gruvbox.json +0 -0
  41. package/themes/arnative-lemonade.json +0 -0
  42. package/themes/arnative-magical.json +0 -0
  43. package/themes/arnative-matrix.json +0 -0
  44. package/themes/arnative-neutral.json +0 -0
  45. package/themes/arnative-nord.json +0 -0
  46. package/themes/arnative-zinc.json +0 -0
  47. package/themes/arnative.json +0 -0
  48. package/themes/gen-themes.mjs +0 -0
@@ -25,9 +25,10 @@ import {
25
25
  CHATBOX_PROMPT_KEY as CHATBOX_PROMPT_CONFIG_KEY,
26
26
  FOOTER_COST_KEY as FOOTER_COST_CONFIG_KEY,
27
27
  FOOTER_PRESET_KEY as FOOTER_PRESET_CONFIG_KEY,
28
+ choiceSetting,
29
+ flagSetting,
28
30
  loadChoice,
29
31
  resetPresetCache,
30
- saveChoice,
31
32
  } from "../lib/preset-store.ts";
32
33
  import { formatCost } from "./usage.ts";
33
34
  import { isByteLimitedModel, wireBytesSnapshot } from "./autocompact.ts";
@@ -47,41 +48,34 @@ import { spinnerPainter } from "../lib/spinner.ts";
47
48
  export const CHATBOX_PRESETS = ["Pi (system)", "Arnative"] as const;
48
49
  export type ChatboxPreset = (typeof CHATBOX_PRESETS)[number];
49
50
  export const DEFAULT_CHATBOX_PRESET: ChatboxPreset = "Arnative";
50
- const CHATBOX_PRESET_KEY = Symbol.for("pi-arnative.chatboxPreset");
51
+ const chatboxPreset = choiceSetting(CHATBOX_PRESET_CONFIG_KEY, CHATBOX_PRESETS, DEFAULT_CHATBOX_PRESET);
52
+ const CHATBOX_PRESET_KEY = chatboxPreset.slot;
51
53
 
52
54
  export const CHATBOX_PROMPTS = ["❯", ">", "›", "▸", "→", "\uf44f", "\udb82\udf79", "\uf51b", "\udb80\udf7d", "\uf120", "\uf489", "\udb80\udd7a"] as const;
53
55
  export type ChatboxPrompt = (typeof CHATBOX_PROMPTS)[number];
54
56
  export const DEFAULT_CHATBOX_PROMPT: ChatboxPrompt = "❯";
55
- const CHATBOX_PROMPT_KEY = Symbol.for("pi-arnative.chatboxPrompt");
57
+ const chatboxPrompt = choiceSetting(CHATBOX_PROMPT_CONFIG_KEY, CHATBOX_PROMPTS, DEFAULT_CHATBOX_PROMPT);
58
+ const CHATBOX_PROMPT_KEY = chatboxPrompt.slot;
56
59
 
57
60
  export const CHATBOX_DIALOGS = ["Left", "Center", "Right", "Inside", "Outside"] as const;
58
61
  export type ChatboxDialog = (typeof CHATBOX_DIALOGS)[number];
59
62
  export const DEFAULT_CHATBOX_DIALOG: ChatboxDialog = "Left";
60
- const CHATBOX_DIALOG_KEY = Symbol.for("pi-arnative.chatboxDialog");
63
+ const chatboxDialog = choiceSetting(CHATBOX_DIALOG_CONFIG_KEY, CHATBOX_DIALOGS, DEFAULT_CHATBOX_DIALOG);
64
+ const CHATBOX_DIALOG_KEY = chatboxDialog.slot;
61
65
 
62
66
  export const PROMPT_IDLE_MS = 3_000;
63
67
  const PROMPT_TYPED_AT_KEY = Symbol.for("pi-arnative.promptTypedAt");
64
68
  const PROMPT_IDLE_TIMER_KEY = Symbol.for("pi-arnative.promptIdleTimer");
65
69
 
66
- export function activeChatboxPreset(): ChatboxPreset {
67
- const stored = (globalThis as Record<symbol, unknown>)[CHATBOX_PRESET_KEY] ?? loadChoice(CHATBOX_PRESET_CONFIG_KEY, CHATBOX_PRESETS);
68
- return CHATBOX_PRESETS.includes(stored as ChatboxPreset) ? (stored as ChatboxPreset) : DEFAULT_CHATBOX_PRESET;
69
- }
70
-
70
+ export const activeChatboxPreset = (): ChatboxPreset => chatboxPreset.get();
71
71
  export function setChatboxPreset(name: ChatboxPreset): void {
72
- (globalThis as Record<symbol, unknown>)[CHATBOX_PRESET_KEY] = name;
73
- saveChoice(CHATBOX_PRESET_CONFIG_KEY, name);
72
+ chatboxPreset.set(name);
74
73
  poke();
75
74
  }
76
75
 
77
- export function activeChatboxPrompt(): ChatboxPrompt {
78
- const stored = (globalThis as Record<symbol, unknown>)[CHATBOX_PROMPT_KEY] ?? loadChoice(CHATBOX_PROMPT_CONFIG_KEY, CHATBOX_PROMPTS);
79
- return CHATBOX_PROMPTS.includes(stored as ChatboxPrompt) ? (stored as ChatboxPrompt) : DEFAULT_CHATBOX_PROMPT;
80
- }
81
-
76
+ export const activeChatboxPrompt = (): ChatboxPrompt => chatboxPrompt.get();
82
77
  export function setChatboxPrompt(prompt: ChatboxPrompt): void {
83
- (globalThis as Record<symbol, unknown>)[CHATBOX_PROMPT_KEY] = prompt;
84
- saveChoice(CHATBOX_PROMPT_CONFIG_KEY, prompt);
78
+ chatboxPrompt.set(prompt);
85
79
  poke();
86
80
  }
87
81
 
@@ -90,14 +84,9 @@ export function nextChatboxPrompt(current: ChatboxPrompt = activeChatboxPrompt()
90
84
  return CHATBOX_PROMPTS[(idx + 1) % CHATBOX_PROMPTS.length]!;
91
85
  }
92
86
 
93
- export function activeChatboxDialog(): ChatboxDialog {
94
- const stored = (globalThis as Record<symbol, unknown>)[CHATBOX_DIALOG_KEY] ?? loadChoice(CHATBOX_DIALOG_CONFIG_KEY, CHATBOX_DIALOGS);
95
- return CHATBOX_DIALOGS.includes(stored as ChatboxDialog) ? (stored as ChatboxDialog) : DEFAULT_CHATBOX_DIALOG;
96
- }
97
-
87
+ export const activeChatboxDialog = (): ChatboxDialog => chatboxDialog.get();
98
88
  export function setChatboxDialog(dialog: ChatboxDialog): void {
99
- (globalThis as Record<symbol, unknown>)[CHATBOX_DIALOG_KEY] = dialog;
100
- saveChoice(CHATBOX_DIALOG_CONFIG_KEY, dialog);
89
+ chatboxDialog.set(dialog);
101
90
  poke();
102
91
  }
103
92
 
@@ -206,29 +195,21 @@ export function minimalExpanded(): { left: boolean; right: boolean } {
206
195
  (globalThis as Record<symbol, { left: boolean; right: boolean }>)[MINIMAL_EXPAND_KEY] = fresh;
207
196
  return fresh;
208
197
  }
209
- const FOOTER_PRESET_KEY = Symbol.for("pi-arnative.footerPreset");
198
+ const footerPreset = choiceSetting(FOOTER_PRESET_CONFIG_KEY, FOOTER_PRESETS, DEFAULT_FOOTER_PRESET);
199
+ const FOOTER_PRESET_KEY = footerPreset.slot;
210
200
  const FOOTER_REGISTRAR_KEY = Symbol.for("pi-arnative.footerRegistrar");
211
- const FOOTER_COST_KEY = Symbol.for("pi-arnative.footerCost");
201
+ const footerCost = flagSetting(FOOTER_COST_CONFIG_KEY);
212
202
 
213
- /** Is the session cost cell on? Stored as `"on"`/`"off"` so an absent key reads as off
214
- * through the same allow-list path every other choice uses. */
215
- export function activeFooterCost(): boolean {
216
- const stored = (globalThis as Record<symbol, unknown>)[FOOTER_COST_KEY] ?? loadChoice(FOOTER_COST_CONFIG_KEY, ["on", "off"] as const);
217
- return stored === "on";
218
- }
203
+ /** Is the session cost cell on? */
204
+ export const activeFooterCost = (): boolean => footerCost.get();
219
205
 
220
- /** Flip the cost cell, persist it, and repaint the footer at once — the choice is a command
221
- * the user asked for, so it is not part of the picker's preview/revert dance. */
206
+ /** Flip the cost cell, persist it, and repaint the footer at once. */
222
207
  export function setFooterCost(on: boolean): void {
223
- (globalThis as Record<symbol, unknown>)[FOOTER_COST_KEY] = on ? "on" : "off";
224
- saveChoice(FOOTER_COST_CONFIG_KEY, on ? "on" : "off");
208
+ footerCost.set(on);
225
209
  poke();
226
210
  }
227
211
 
228
- export function activeFooterPreset(): FooterPreset {
229
- const stored = (globalThis as Record<symbol, unknown>)[FOOTER_PRESET_KEY] ?? loadChoice(FOOTER_PRESET_CONFIG_KEY, FOOTER_PRESETS);
230
- return FOOTER_PRESETS.includes(stored as FooterPreset) ? (stored as FooterPreset) : DEFAULT_FOOTER_PRESET;
231
- }
212
+ export const activeFooterPreset = (): FooterPreset => footerPreset.get();
232
213
 
233
214
  /**
234
215
  * Hand the footer slot to the active preset: arnative's grid, or pi's built-in footer.
@@ -245,8 +226,7 @@ export function applyFooterPreset(ctx: ExtensionContext): void {
245
226
  }
246
227
  /** Select a preset and apply it immediately (the footer swaps on the spot). */
247
228
  export function setFooterPreset(name: FooterPreset, ctx: ExtensionContext): void {
248
- (globalThis as Record<symbol, unknown>)[FOOTER_PRESET_KEY] = name;
249
- saveChoice(FOOTER_PRESET_CONFIG_KEY, name);
229
+ footerPreset.set(name);
250
230
  applyFooterPreset(ctx);
251
231
  }
252
232
 
@@ -397,16 +377,15 @@ export function currentToolVerb(active: ReadonlyMap<string, string>): string {
397
377
  * Recognising the label keeps the rule honest: if pi-jev-eye renames its label, this test fails loudly in
398
378
  * the self-check below instead of degrading to a plain grey cell.
399
379
  */
400
- export const isJevEyeStatus = (status: string): boolean => /^\s*Eye\s*:/i.test(stripAnsi(status));
380
+ export const isJevEyeStatus = (status: string): boolean => /^(?:(?:\uf21b|\ueb1b|\u{1F440})\s*)?Eye\s*:/iu.test(stripAnsi(status));
401
381
 
402
382
  /**
403
- * The pi-jev-eye status cell: `Eye: ● MODE (Backend)`. pi-jev-eye writes the value plain because a status
404
- * is a fact, not a layout; this decides the painting.
383
+ * The pi-jev-eye / pi-decision-eye status cell: `[icon] Eye: ● MODE (Backend)`.
405
384
  *
406
385
  * The trailing parenthesised backend is a modifier, so it takes `dim` while the `Eye:` label and the state
407
- * keep the soft and state tiers — that is what makes `(Clef Flash)` recede and `Eye: ● ON` stay readable
408
- * at a glance. The backend name itself is read out of the value, never hardcoded here: the extension
409
- * reports the active backend from `/jev-eye models`, so the footer cannot know it in advance.
386
+ * keep the soft and state tiers — that is what makes `(Clef Flash)` / `(mercury-decide)` recede and
387
+ * `Eye: ● ON` / `Eye: ● BALANCED` stay readable at a glance. The backend name itself is read out of the value,
388
+ * never hardcoded here.
410
389
  */
411
390
  export function jevEyeStatusLine(
412
391
  status: string,
@@ -415,18 +394,35 @@ export function jevEyeStatusLine(
415
394
  soft: (text: string) => string,
416
395
  theme?: { fg?: (color: string, text: string) => string },
417
396
  ): string {
418
- const clean = stripAnsi(status);
419
- const isOff = clean.includes("OFF") || clean.includes("\u25CB");
420
- const isReview = /REVIEW/i.test(clean);
421
- let bullet = isOff ? dim("\u25CB") : acc("\u25CF");
422
- if (isReview && typeof theme?.fg === "function") {
397
+ const clean = stripAnsi(status).replace(/^(?:\uf21b|\ueb1b|\u{1F440})\s*/u, "");
398
+ const isOff = /\bOFF\b/i.test(clean) || clean.includes("\u25CB");
399
+ const isReview = /\bREVIEW\b/i.test(clean);
400
+ const isStrict = /\bSTRICT\b/i.test(clean);
401
+ const isLight = /\bLIGHT\b/i.test(clean);
402
+ const isBalanced = /\bBALANCED\b/i.test(clean);
403
+ const fgToken = (token: string, fallback: (t: string) => string) => {
404
+ if (typeof theme?.fg !== "function") return fallback("\u25CF");
423
405
  try {
424
- bullet = theme.fg("warning", "\u25CF");
406
+ return theme.fg(token, "\u25CF");
425
407
  } catch {
426
- bullet = acc("\u25CF");
408
+ return fallback("\u25CF");
427
409
  }
428
- }
429
- const label = isOff ? "OFF" : isReview ? "REVIEW" : "ON";
410
+ };
411
+ let bullet = isOff ? dim("\u25CB") : acc("\u25CF");
412
+ if (isReview) bullet = fgToken("warning", acc);
413
+ else if (isStrict) bullet = fgToken("mdHeading", acc);
414
+ else if (isLight) bullet = fgToken("borderAccent", acc);
415
+ const label = isOff
416
+ ? "OFF"
417
+ : isReview
418
+ ? "REVIEW"
419
+ : isStrict
420
+ ? "STRICT"
421
+ : isLight
422
+ ? "LIGHT"
423
+ : isBalanced
424
+ ? "BALANCED"
425
+ : "ON";
430
426
  // `Eye: ● ON (Clef Flash)` -> the base before the first colon, the backend in the trailing parentheses.
431
427
  const base = clean.split(":")[0]!.trim() || "Eye";
432
428
  const at = clean.lastIndexOf("(");
@@ -1343,8 +1339,10 @@ export function wrapInputListener(tui: unknown): () => void {
1343
1339
  };
1344
1340
  const target = tui as { handleTerminalInput?: (data: string) => void };
1345
1341
  if (!target || typeof target.handleTerminalInput !== "function") return () => {};
1346
- if (!(globalThis as Record<symbol, boolean>)[WRAPPED_TUI_KEY]) {
1347
- (globalThis as Record<symbol, boolean>)[WRAPPED_TUI_KEY] = true;
1342
+ const g = globalThis as Record<symbol, unknown>;
1343
+ const wrapped = g[WRAPPED_TUI_KEY] instanceof WeakSet ? (g[WRAPPED_TUI_KEY] as WeakSet<object>) : (g[WRAPPED_TUI_KEY] = new WeakSet<object>());
1344
+ if (!wrapped.has(target)) {
1345
+ wrapped.add(target);
1348
1346
  const original = target.handleTerminalInput;
1349
1347
  target.handleTerminalInput = function (this: unknown, data: string): void {
1350
1348
  // One keystroke, one activity. The wrapper runs before `original`, and `pi-tui`
@@ -2522,6 +2520,27 @@ if (isMain(import.meta.url)) {
2522
2520
  jevEyeStatusLine("Eye: ● ON", jevPlain, jevDim, jevPlain, undefined) === "\uf21b" + " Eye: ● ON",
2523
2521
  "no backend suffix means no parenthesis, never a guessed one",
2524
2522
  );
2523
+ assert(isJevEyeStatus("\uf21b Eye: ● BALANCED (mercury-decide)"), "pi-decision-eye nerd-icon status is recognised");
2524
+ assert(
2525
+ jevEyeStatusLine("\uf21b Eye: ● BALANCED (mercury-decide)", jevPlain, jevDim, jevPlain, { fg: (color, text) => `<${color}>${text}</${color}>` }) ===
2526
+ "\uf21b" + " Eye: ● BALANCED [dim](mercury-decide)[/dim]",
2527
+ "BALANCED keeps accent bullet and dim backend",
2528
+ );
2529
+ assert(
2530
+ jevEyeStatusLine("\uf21b Eye: ● STRICT (mercury-decide)", jevPlain, jevDim, jevPlain, { fg: (color, text) => `<${color}>${text}</${color}>` }) ===
2531
+ "\uf21b" + " Eye: <mdHeading>●</mdHeading> STRICT [dim](mercury-decide)[/dim]",
2532
+ "STRICT takes primary (mdHeading) bullet",
2533
+ );
2534
+ assert(
2535
+ jevEyeStatusLine("\uf21b Eye: ● LIGHT (mercury-decide)", jevPlain, jevDim, jevPlain, { fg: (color, text) => `<${color}>${text}</${color}>` }) ===
2536
+ "\uf21b" + " Eye: <borderAccent>●</borderAccent> LIGHT [dim](mercury-decide)[/dim]",
2537
+ "LIGHT takes secondary (borderAccent) bullet",
2538
+ );
2539
+ assert(
2540
+ jevEyeStatusLine("\uf21b Eye: ○ OFF (mercury-decide)", jevPlain, jevDim, jevPlain, undefined) ===
2541
+ "\uf21b" + " Eye: [dim]○[/dim] OFF [dim](mercury-decide)[/dim]",
2542
+ "OFF takes dim bullet and dim backend",
2543
+ );
2525
2544
 
2526
2545
  // Self-check: session age survives /resume (header timestamp wins over now).
2527
2546
  const NOW = Date.parse("2026-10-08T12:00:00.000Z");
File without changes
@@ -37,7 +37,7 @@ import { tmpdir } from "node:os";
37
37
  import { join } from "node:path";
38
38
  import { assert, isMain } from "../lib/check.ts";
39
39
  import { patchOnce } from "../lib/patch.ts";
40
- import { RENDER_CACHE_KEY, loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
40
+ import { RENDER_CACHE_KEY, choiceSetting, loadChoice, resetPresetCache } from "../lib/preset-store.ts";
41
41
 
42
42
  /** Stored exactly as the picker shows them; `"On"` is the default. */
43
43
  export const RENDER_CACHE_CHOICES = ["On", "Off"] as const;
@@ -78,6 +78,7 @@ interface ContainerCacheEntry {
78
78
  hasExpanded: boolean;
79
79
  children: unknown[];
80
80
  childMeta: ChildMeta[];
81
+ parts: Array<readonly string[]>;
81
82
  lines: string[];
82
83
  mouseChildren: Array<{ component: unknown; height: number }>;
83
84
  }
@@ -122,20 +123,14 @@ function getCacheState(): RenderCacheState {
122
123
  return g[RENDER_CACHE_STATE_KEY] as RenderCacheState;
123
124
  }
124
125
 
126
+ const renderCacheSetting = choiceSetting(RENDER_CACHE_KEY, RENDER_CACHE_CHOICES, DEFAULT_RENDER_CACHE);
127
+
125
128
  /** Current Render cache mode (`"On"` by default). */
126
- export function activeRenderCache(): RenderCacheChoice {
127
- const stored =
128
- (globalThis as Record<symbol, unknown>)[RENDER_CACHE_CONFIG_KEY] ??
129
- loadChoice(RENDER_CACHE_KEY, RENDER_CACHE_CHOICES);
130
- return RENDER_CACHE_CHOICES.includes(stored as RenderCacheChoice)
131
- ? (stored as RenderCacheChoice)
132
- : DEFAULT_RENDER_CACHE;
133
- }
129
+ export const activeRenderCache = (): RenderCacheChoice => renderCacheSetting.get();
134
130
 
135
131
  /** Update the Render cache choice and drop stale cached frames. */
136
132
  export function setRenderCache(choice: RenderCacheChoice): void {
137
- (globalThis as Record<symbol, unknown>)[RENDER_CACHE_CONFIG_KEY] = choice;
138
- saveChoice(RENDER_CACHE_KEY, choice);
133
+ renderCacheSetting.set(choice);
139
134
  clearRenderCache();
140
135
  }
141
136
 
@@ -288,8 +283,11 @@ function attachChildHooks(child: unknown): void {
288
283
 
289
284
  export interface ChatContainerLike {
290
285
  children: unknown[];
286
+ /** Pi < 1.6.0 mouse layout cache. */
291
287
  mouseLayout?: { width: number; children: Array<{ component: unknown; height: number }> };
292
- render(width: number): string[];
288
+ /** Pi >= 1.6.0 child line + mouse layout cache (`renderChildLines`). */
289
+ childLines?: { width: number; children: unknown[]; parts: Array<readonly string[]>; lines: readonly string[] };
290
+ render(width: number): readonly string[];
293
291
  invalidate?: () => void;
294
292
  addChild?: (component: unknown) => void;
295
293
  removeChild?: (component: unknown) => void;
@@ -342,6 +340,7 @@ function renderCachedChatContainer(
342
340
  if (allClean) {
343
341
  state.stats.containerHits += 1;
344
342
  container.mouseLayout = { width, children: cached.mouseChildren };
343
+ container.childLines = { width, children: cached.children, parts: cached.parts, lines: cached.lines };
345
344
  return cached.lines;
346
345
  }
347
346
  }
@@ -349,14 +348,16 @@ function renderCachedChatContainer(
349
348
  const lines: string[] = [];
350
349
  const mouseChildren: Array<{ component: unknown; height: number }> = [];
351
350
  const snapshot: unknown[] = new Array(children.length);
351
+ const parts: Array<readonly string[]> = new Array(children.length);
352
352
  const childMeta: ChildMeta[] = new Array(children.length);
353
353
  let allChildrenCacheable = true;
354
354
  let hasExpanded = false;
355
355
 
356
356
  for (let i = 0; i < children.length; i++) {
357
- const child = children[i] as { render?: (w: number) => string[] } & Record<string | symbol, unknown>;
357
+ const child = children[i] as { render?: (w: number) => readonly string[] } & Record<string | symbol, unknown>;
358
358
  snapshot[i] = child;
359
359
  if (!child || typeof child.render !== "function") {
360
+ parts[i] = [];
360
361
  childMeta[i] = { version: 0, scrollOffset: 0, expanded: false };
361
362
  continue;
362
363
  }
@@ -369,7 +370,7 @@ function renderCachedChatContainer(
369
370
  if (expanded) hasExpanded = true;
370
371
  childMeta[i] = { version: ver, scrollOffset, expanded };
371
372
 
372
- let childLines: string[];
373
+ let childLines: readonly string[];
373
374
  if (!isCacheableChild(child) || isDynamicChild(child)) {
374
375
  allChildrenCacheable = false;
375
376
  state.stats.childRenders += 1;
@@ -404,7 +405,7 @@ function renderCachedChatContainer(
404
405
  version: ver,
405
406
  scrollOffset,
406
407
  expanded,
407
- lines: childLines,
408
+ lines: [...childLines],
408
409
  },
409
410
  (entry) =>
410
411
  entry.epoch === state.epoch &&
@@ -416,6 +417,7 @@ function renderCachedChatContainer(
416
417
  }
417
418
  }
418
419
 
420
+ parts[i] = childLines;
419
421
  mouseChildren.push({ component: child, height: childLines.length });
420
422
  for (let j = 0; j < childLines.length; j++) {
421
423
  lines.push(childLines[j]!);
@@ -423,6 +425,7 @@ function renderCachedChatContainer(
423
425
  }
424
426
 
425
427
  container.mouseLayout = { width, children: mouseChildren };
428
+ container.childLines = { width, children: snapshot, parts, lines };
426
429
  if (allChildrenCacheable) {
427
430
  putWidthEntry(
428
431
  state.containerCache,
@@ -435,6 +438,7 @@ function renderCachedChatContainer(
435
438
  hasExpanded,
436
439
  children: snapshot,
437
440
  childMeta,
441
+ parts,
438
442
  lines,
439
443
  mouseChildren,
440
444
  },
@@ -491,6 +495,9 @@ if (InteractiveMode?.prototype) {
491
495
  "init",
492
496
  "handleReloadCommand",
493
497
  "renderSessionContext",
498
+ "renderSessionEntries",
499
+ "renderSessionItems",
500
+ "renderCurrentSessionState",
494
501
  "rebuildChatFromMessages",
495
502
  "addMessageToChat",
496
503
  "handleEvent",
@@ -582,6 +589,13 @@ if (isMain(import.meta.url)) {
582
589
  assert(out2 === out1, "whole-container hit returns cached array reference");
583
590
  assert(c1.renders === 1 && c2.renders === 1, "container hit skips child renders");
584
591
  assert(container.mouseLayout?.children.length === 2, "mouseLayout preserved on container hit");
592
+ assert(
593
+ container.childLines?.width === 80 &&
594
+ container.childLines.children.length === 2 &&
595
+ container.childLines.parts.length === 2 &&
596
+ container.childLines.lines === out2,
597
+ "Pi 1.6.0+ childLines preserved on container hit",
598
+ );
585
599
 
586
600
  // Streaming child bypasses cache while settled sibling stays cached.
587
601
  c2.isStreaming = true;
@@ -37,7 +37,7 @@ import { BRAND, renderBoxLines } from "../lib/box.ts";
37
37
  import { getActiveTheme, setActiveTheme, softOf, softSecondaryOf, stripAnsi, themeOf } from "../lib/ansi.ts";
38
38
  import { capitalize, expandKeyName, modelDisplayParts } from "../lib/format.ts";
39
39
  import { SHORTCUT_NEW_SESSION, SHORTCUT_NEXT_TAB, SHORTCUT_RELOAD } from "../lib/shortcuts.ts";
40
- import { HEADER_PRESET_KEY as HEADER_PRESET_CONFIG_KEY, loadChoice, saveChoice } from "../lib/preset-store.ts";
40
+ import { HEADER_PRESET_KEY as HEADER_PRESET_CONFIG_KEY, choiceSetting } from "../lib/preset-store.ts";
41
41
  import { formatTokens, getModelAllTimeUsage } from "../lib/usage-store.ts";
42
42
 
43
43
  import { patchOnce } from "../lib/patch.ts";
@@ -417,12 +417,9 @@ export const tabStore: Map<TabKey, string[]> =
417
417
  export const HEADER_PRESETS = ["Pi (system)", "Arnative (Full)"] as const;
418
418
  export type HeaderPreset = (typeof HEADER_PRESETS)[number];
419
419
  export const DEFAULT_HEADER_PRESET: HeaderPreset = "Arnative (Full)";
420
- const HEADER_PRESET_KEY = Symbol.for("pi-arnative.headerPreset");
420
+ const headerPreset = choiceSetting(HEADER_PRESET_CONFIG_KEY, HEADER_PRESETS, DEFAULT_HEADER_PRESET);
421
421
 
422
- export function activeHeaderPreset(): HeaderPreset {
423
- const stored = (globalThis as Record<symbol, unknown>)[HEADER_PRESET_KEY] ?? loadChoice(HEADER_PRESET_CONFIG_KEY, HEADER_PRESETS);
424
- return HEADER_PRESETS.includes(stored as HeaderPreset) ? (stored as HeaderPreset) : DEFAULT_HEADER_PRESET;
425
- }
422
+ export const activeHeaderPreset = (): HeaderPreset => headerPreset.get();
426
423
 
427
424
  /** Hand the header slot to the active preset: arnative's box, or pi's built-in ("Pi (system)"). */
428
425
  export function applyHeaderPreset(ctx: ExtensionContext): void {
@@ -435,8 +432,7 @@ export function applyHeaderPreset(ctx: ExtensionContext): void {
435
432
 
436
433
  /** Select a preset and apply it immediately (real-time: the header swaps on the spot). */
437
434
  export function setHeaderPreset(name: HeaderPreset, ctx: ExtensionContext): void {
438
- (globalThis as Record<symbol, unknown>)[HEADER_PRESET_KEY] = name;
439
- saveChoice(HEADER_PRESET_CONFIG_KEY, name);
435
+ headerPreset.set(name);
440
436
  applyHeaderPreset(ctx);
441
437
  }
442
438
 
@@ -90,6 +90,39 @@ const BUBBLE_BG_CACHE_MAX = 8192;
90
90
  let bubbleBgOpen = "";
91
91
  let bubbleBgCache = new Map<string, string>();
92
92
 
93
+ function insertBgAfterResets(line: string, bgOpen: string): string {
94
+ let out = "";
95
+ let i = 0;
96
+ const n = line.length;
97
+ while (i < n) {
98
+ const c0 = line.indexOf("\x1b[0m", i);
99
+ const c49 = line.indexOf("\x1b[49m", i);
100
+ let pos = -1;
101
+ let tokenLen = 0;
102
+ if (c0 >= 0 && (c49 < 0 || c0 < c49)) {
103
+ pos = c0;
104
+ tokenLen = 4;
105
+ } else if (c49 >= 0) {
106
+ pos = c49;
107
+ tokenLen = 5;
108
+ }
109
+ if (pos < 0) {
110
+ out += line.slice(i);
111
+ break;
112
+ }
113
+ const after = pos + tokenLen;
114
+ out += line.slice(i, after);
115
+ // Leave a trailing \x1b[49m alone (it closes the bubble bg), and avoid duplicating
116
+ // bgOpen when a prior repair already placed it right after the reset.
117
+ const isTrailingClose = tokenLen === 5 && after === n;
118
+ if (!isTrailingClose && !line.startsWith(bgOpen, after)) {
119
+ out += bgOpen;
120
+ }
121
+ i = after;
122
+ }
123
+ return out.endsWith(bgOpen) ? `${out}\x1b[49m` : out;
124
+ }
125
+
93
126
  export function repairBubbleBg(line: string, bgOpen: string): string {
94
127
  if (!bgOpen || (!line.includes("\x1b[0m") && !line.includes("\x1b[49m"))) return line;
95
128
  if (bgOpen !== bubbleBgOpen) {
@@ -98,13 +131,38 @@ export function repairBubbleBg(line: string, bgOpen: string): string {
98
131
  }
99
132
  const hit = bubbleBgCache.get(line);
100
133
  if (hit !== undefined) return hit;
101
- const patched = line.split("\x1b[0m").join(`\x1b[0m${bgOpen}`).split("\x1b[49m").join(`\x1b[49m${bgOpen}`);
102
- const result = patched.endsWith(bgOpen) ? `${patched}\x1b[49m` : patched;
134
+ const result = insertBgAfterResets(line, bgOpen);
103
135
  if (bubbleBgCache.size >= BUBBLE_BG_CACHE_MAX) bubbleBgCache.clear();
104
136
  bubbleBgCache.set(line, result);
105
137
  return result;
106
138
  }
107
139
 
140
+ function resolveUserTimestamp(comp: { text?: string; timestamp?: string | number }): number | undefined {
141
+ if (typeof comp.timestamp === "number" && comp.timestamp > 0) return comp.timestamp;
142
+ if (typeof comp.timestamp === "string" && comp.timestamp) {
143
+ const parsed = Date.parse(comp.timestamp);
144
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
145
+ }
146
+ const textKey = comp.text?.trim() ?? "";
147
+ return USER_TIMESTAMPS_MAP.get(textKey);
148
+ }
149
+
150
+ type UserRenderCacheEntry = {
151
+ source: readonly string[];
152
+ width: number;
153
+ bgOpen: string;
154
+ badge: string;
155
+ lines: string[];
156
+ };
157
+ type AssistantRenderCacheEntry = {
158
+ source: readonly string[];
159
+ width: number;
160
+ badge: string;
161
+ lines: string[];
162
+ };
163
+ const userRenderCache = new WeakMap<object, UserRenderCacheEntry>();
164
+ const assistantRenderCache = new WeakMap<object, AssistantRenderCacheEntry>();
165
+
108
166
  /**
109
167
  * Paste the clock at the right end of a line, 1 column from the right edge.
110
168
  * When `bgOpen` is given (e.g. user chat) the padding and the clock use that bubble
@@ -127,72 +185,87 @@ export function placeTimeAtRight(
127
185
  }
128
186
 
129
187
  // Both patches reinstall on every load (lib/patch.ts) so a `/reload` applies them.
188
+ // Pi 1.6.0+ Container/Message `render()` returns a shared cached `readonly string[]`, so
189
+ // both wrappers copy before modifying and cache their own output per source array identity.
130
190
  if (UserMessageComponent?.prototype?.render || AssistantMessageComponent?.prototype?.render) {
131
191
  if (UserMessageComponent?.prototype?.render) {
132
192
  const proto = UserMessageComponent.prototype as any;
133
- const origRender = originalOf<(this: any, width: number) => string[]>(proto, "render");
134
- proto.render = markPatched(function (this: any, width: number): string[] {
135
- const lines = origRender.call(this, width);
136
- if (lines.length < 2) return lines;
193
+ const origRender = originalOf<(this: any, width: number) => readonly string[]>(proto, "render");
194
+ proto.render = markPatched(function (this: any, width: number): readonly string[] {
195
+ const source = origRender.call(this, width);
196
+ if (source.length < 2) return source;
197
+
198
+ const bgOpen = ansiBgOpen(tsState.theme, "userMessageBg");
199
+ const ts = resolveUserTimestamp(this as { text?: string; timestamp?: string | number });
200
+ const timeStr = ts ? formatClock(ts) : "";
201
+ const badge = timeStr ? formatTimeBadge(timeStr, tsState.theme) : "";
202
+
203
+ const prev = userRenderCache.get(this);
204
+ if (prev && prev.source === source && prev.width === width && prev.bgOpen === bgOpen && prev.badge === badge) {
205
+ return prev.lines;
206
+ }
137
207
 
138
208
  // Fix the bubble bg first (reset Markdown lines make padding dark),
139
209
  // then paste the clock (which deliberately drops the bg in the badge area).
140
- const bgOpen = ansiBgOpen(tsState.theme, "userMessageBg");
141
- for (let i = 0; i < lines.length; i++) lines[i] = repairBubbleBg(lines[i], bgOpen);
210
+ const lines = [...source];
211
+ for (let i = 0; i < lines.length; i++) lines[i] = repairBubbleBg(lines[i]!, bgOpen);
142
212
 
143
- const textKey = (this as { text?: string }).text?.trim() ?? "";
144
- const ts = USER_TIMESTAMPS_MAP.get(textKey);
145
213
  // No known timestamp -> no clock (a "now" clock would be a lie on old messages).
146
- if (!ts) return lines;
147
- const timeStr = formatClock(ts);
148
- const badge = formatTimeBadge(timeStr, tsState.theme);
149
- const timeW = visibleWidth(timeStr);
214
+ if (timeStr) {
215
+ const timeW = visibleWidth(timeStr);
216
+ // First text line sits at index 1 (below the box top padding)
217
+ const contentLine = lines[1]!;
218
+ const cleanContent = stripAnsi(contentLine).trimEnd();
219
+ const contentW = visibleWidth(cleanContent);
220
+ const minGap = 2;
150
221
 
151
- // First text line sits at index 1 (below the box top padding)
152
- const contentLine = lines[1];
153
- const cleanContent = stripAnsi(contentLine).trimEnd();
154
- const contentW = visibleWidth(cleanContent);
155
- const minGap = 2;
156
-
157
- if (contentW + minGap + timeW <= width) {
158
- // Fits on the first text line: paste right-aligned with a 1-space margin
159
- lines[1] = placeTimeAtRight(contentLine, width, badge, timeW, bgOpen);
160
- } else {
161
- // First text line is full: NEVER truncate content!
162
- // Clock goes to the TOP padding line (always empty, first line of the bubble)
163
- const topLine = lines[0];
164
- const oscMatch = topLine.match(/^(\x1b\]133;[A-Z]\x07)+/);
165
- const prefix = oscMatch ? oscMatch[0] : "";
166
- const rest = topLine.slice(prefix.length);
167
- lines[0] = `${prefix}${placeTimeAtRight(rest, width, badge, timeW, bgOpen)}`;
222
+ if (contentW + minGap + timeW <= width) {
223
+ // Fits on the first text line: paste right-aligned with a 1-space margin
224
+ lines[1] = placeTimeAtRight(contentLine, width, badge, timeW, bgOpen);
225
+ } else {
226
+ // First text line is full: NEVER truncate content!
227
+ // Clock goes to the TOP padding line (always empty, first line of the bubble)
228
+ const topLine = lines[0]!;
229
+ const oscMatch = topLine.match(/^(\x1b\]133;[A-Z]\x07)+/);
230
+ const prefix = oscMatch ? oscMatch[0] : "";
231
+ const rest = topLine.slice(prefix.length);
232
+ lines[0] = `${prefix}${placeTimeAtRight(rest, width, badge, timeW, bgOpen)}`;
233
+ }
168
234
  }
235
+
236
+ userRenderCache.set(this, { source, width, bgOpen, badge, lines });
169
237
  return lines;
170
238
  });
171
239
  }
172
240
 
173
241
  if (AssistantMessageComponent?.prototype?.render) {
174
242
  const proto = AssistantMessageComponent.prototype as any;
175
- const origRender = originalOf<(this: any, width: number) => string[]>(proto, "render");
176
- proto.render = markPatched(function (this: any, width: number): string[] {
177
- const lines = origRender.call(this, width);
243
+ const origRender = originalOf<(this: any, width: number) => readonly string[]>(proto, "render");
244
+ proto.render = markPatched(function (this: any, width: number): readonly string[] {
245
+ const source = origRender.call(this, width);
178
246
  const lastMsg = (this as { lastMessage?: AssistantMessage }).lastMessage;
179
247
 
180
248
  // Clock only on the final reply (a message with no toolCall)
181
249
  const hasToolCalls = lastMsg?.content?.some((c) => c.type === "toolCall");
182
- if (hasToolCalls) return lines;
250
+ if (hasToolCalls) return source;
183
251
 
184
252
  // and only when there is real answer text (not thinking only)
185
253
  const hasText = lastMsg?.content?.some((c) => c.type === "text" && c.text.trim());
186
- if (!hasText || lines.length === 0) return lines;
254
+ if (!hasText || source.length === 0) return source;
187
255
 
188
256
  const timeStr = formatClock(lastMsg?.timestamp);
189
257
  const badge = formatTimeBadge(timeStr, tsState.theme);
258
+ const prev = assistantRenderCache.get(this);
259
+ if (prev && prev.source === source && prev.width === width && prev.badge === badge) {
260
+ return prev.lines;
261
+ }
262
+
190
263
  const timeW = visibleWidth(timeStr);
191
264
 
192
265
  // First text line that is neither an OSC zone nor a thinking header
193
266
  let targetIdx = -1;
194
- for (let i = 0; i < lines.length; i++) {
195
- const plain = stripAnsi(lines[i].replace(/^(\x1b\]133;[A-Z]\x07)+/, "")).trim();
267
+ for (let i = 0; i < source.length; i++) {
268
+ const plain = stripAnsi(source[i]!.replace(/^(\x1b\]133;[A-Z]\x07)+/, "")).trim();
196
269
  // Never paste onto the hidden thinking line: `Thinking...` while it streams, `Thought for 3s` once it ends (plain or with the \uec21 icon)
197
270
  if (plain.length > 0 && !/^(?:\uec21\s+)?(?:thinking|thought for)\b/i.test(plain)) {
198
271
  targetIdx = i;
@@ -202,7 +275,7 @@ if (UserMessageComponent?.prototype?.render || AssistantMessageComponent?.protot
202
275
 
203
276
  if (targetIdx !== -1) {
204
277
  let prefix = "";
205
- let rest = lines[targetIdx];
278
+ let rest = source[targetIdx]!;
206
279
  const oscMatch = rest.match(/^(\x1b\]133;[A-Z]\x07)+/);
207
280
  if (oscMatch) {
208
281
  prefix = oscMatch[0];
@@ -214,10 +287,13 @@ if (UserMessageComponent?.prototype?.render || AssistantMessageComponent?.protot
214
287
  const minGap = 2;
215
288
 
216
289
  if (textW + minGap + timeW <= width) {
290
+ const lines = [...source];
217
291
  lines[targetIdx] = `${prefix}${placeTimeAtRight(rest, width, badge, timeW, "")}`;
292
+ assistantRenderCache.set(this, { source, width, badge, lines });
293
+ return lines;
218
294
  }
219
295
  }
220
- return lines;
296
+ return source;
221
297
  });
222
298
  }
223
299
  }
@@ -265,11 +341,12 @@ if (isMain(import.meta.url)) {
265
341
  assert(res2.endsWith("\x1b[49m"), "background closed at end of line");
266
342
  assert(visibleWidth(res2) === 30, "line length still matches the width");
267
343
 
268
- // bubble bg repair: padding after [0m] must be bg'd, line closed with [49m]
344
+ // bubble bg repair: padding after [0m] must be bg'd, line closed with [49m], and idempotent
269
345
  const dirty = `${bg}Hello\x1b[0m${" ".repeat(5)}\x1b[49m`;
270
346
  const clean = repairBubbleBg(dirty, bg);
271
347
  assert(clean.includes(`\x1b[0m${bg}`), "bg re-applied after the reset");
272
348
  assert(clean.endsWith("\x1b[49m"), "bubble bg closed at end of line");
349
+ assert(repairBubbleBg(clean, bg) === clean, "repairBubbleBg is idempotent across repeated frames");
273
350
  assert(repairBubbleBg("plain", "") === "plain", "no bgOpen: unchanged");
274
351
 
275
352
  // memoized repair: a different bg code resets the cache, so nothing repairs