@bismawy/pi-arnative 0.16.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 +5 -0
  2. package/README.md +0 -0
  3. package/extensions/animations.ts +0 -0
  4. package/extensions/arnative.ts +0 -0
  5. package/extensions/autocompact.ts +12 -10
  6. package/extensions/budget.ts +0 -0
  7. package/extensions/footer.ts +52 -15
  8. package/extensions/model-heal.ts +0 -0
  9. package/extensions/render-cache.ts +24 -4
  10. package/extensions/section-headers.ts +0 -0
  11. package/extensions/timestamps.ts +118 -41
  12. package/extensions/todos.ts +0 -0
  13. package/extensions/tools.ts +0 -0
  14. package/extensions/ui-render-tweaks.ts +0 -0
  15. package/extensions/usage-export.ts +0 -0
  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 +0 -0
  22. package/lib/format.ts +0 -0
  23. package/lib/list-picker.ts +0 -0
  24. package/lib/model-heal.ts +0 -0
  25. package/lib/patch.ts +0 -0
  26. package/lib/preset-store.ts +0 -0
  27. package/lib/provider.ts +0 -0
  28. package/lib/shortcuts.ts +0 -0
  29. package/lib/spinner.ts +0 -0
  30. package/lib/status-widget.ts +0 -0
  31. package/lib/todos.ts +0 -0
  32. package/lib/usage-store.ts +0 -0
  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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.16.1] - 2026-11-21
6
+
7
+ ### Fixed
8
+ - **Pi 1.6.0 render immutability, `childLines` sync, and `wire-bytes` test isolation.** `timestamps.ts` now uses copy-on-write with per-instance render caching and idempotent `repairBubbleBg` so frozen `readonly string[]` outputs from Pi 1.6.0+ never throw `TypeError` or double-append ANSI resets; `render-cache.ts` synchronizes `Container.childLines` alongside `mouseLayout` and hooks Pi 1.6.0+ `InteractiveMode` session-render methods; `autocompact.ts` and `test/wire-bytes.test.ts` reset the preset cache after `PI_CODING_AGENT_DIR` overrides and read live `activeByteCeilings()`. Added `test/pi-compat-contract.test.ts` (`extensions/timestamps.ts`, `extensions/render-cache.ts`, `extensions/autocompact.ts`, `test/wire-bytes.test.ts`, `test/pi-compat-contract.test.ts`).
9
+
5
10
  ## [0.16.0] - 2026-11-20
6
11
 
7
12
  ### Added
package/README.md CHANGED
File without changes
File without changes
File without changes
@@ -691,6 +691,7 @@ if (isMain(import.meta.url)) {
691
691
  process.env.PI_CODING_AGENT_DIR = fixture;
692
692
  delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
693
693
  delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
694
+ resetPresetCache();
694
695
 
695
696
  // Payload limit parsing, persistence, and Off mode.
696
697
  assert(parsePayloadLimit("off") === "Off", "parses off case-insensitively");
@@ -706,6 +707,7 @@ if (isMain(import.meta.url)) {
706
707
  delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
707
708
  saveChoice(PAYLOAD_LIMIT_KEY, "1 MB");
708
709
  resetPresetCache();
710
+ const liveCeilings = activeByteCeilings()!;
709
711
 
710
712
  // Choice parsing and persistence.
711
713
  assert(activeAutoCompact() === "Off", "the default is off");
@@ -818,7 +820,7 @@ if (isMain(import.meta.url)) {
818
820
  // Emergency tail trim: a single massive toolResult in the newest turn still sheds below target.
819
821
  const tailOnlyHuge: MessageLike[] = [
820
822
  { role: "user", content: [{ type: "text", text: "run tool" }] },
821
- { role: "toolResult", content: [{ type: "text", text: "y".repeat(SHED_TRIGGER_BYTES + 20_000) }] },
823
+ { role: "toolResult", content: [{ type: "text", text: "y".repeat(liveCeilings.shedTriggerBytes + 20_000) }] },
822
824
  ];
823
825
  const tailShed = shedMessagesForByteLimit(tailOnlyHuge, 100_000);
824
826
  assert(tailShed.changed && tailShed.bytes <= 100_000, "emergency tail trim bounds even a single giant newest message");
@@ -879,17 +881,17 @@ if (isMain(import.meta.url)) {
879
881
  const hugeRunMsgs: MessageLike[] = [
880
882
  { role: "user", content: [{ type: "text", text: "start" }] },
881
883
  { role: "assistant", content: [{ type: "toolCall", arguments: { path: "x" } }] },
882
- { role: "toolResult", content: [{ type: "text", text: "z".repeat(SHED_TRIGGER_BYTES + 10_000) }] },
884
+ { role: "toolResult", content: [{ type: "text", text: "z".repeat(liveCeilings.shedTriggerBytes + 10_000) }] },
883
885
  { role: "user", content: [{ type: "text", text: "continue" }] },
884
886
  { role: "assistant", content: [{ type: "text", text: "ok" }] },
885
887
  ];
886
888
  const ctxResult = (await handlers.context!({ messages: hugeRunMsgs }, remoteCtx)) as { messages?: MessageLike[] } | undefined;
887
889
  assert(
888
890
  Array.isArray(ctxResult?.messages) &&
889
- jsonByteLength(ctxResult.messages) + DEFAULT_OVERHEAD_BYTES <= SHED_TARGET_BYTES,
891
+ jsonByteLength(ctxResult.messages) + DEFAULT_OVERHEAD_BYTES <= liveCeilings.shedTargetBytes,
890
892
  "context hook sheds payload with hysteresis down to the target ceiling",
891
893
  );
892
- await handlers.before_provider_request!({ payload: { blob: "p".repeat(SHED_TRIGGER_BYTES + 20_000) } }, remoteCtx);
894
+ await handlers.before_provider_request!({ payload: { blob: "p".repeat(liveCeilings.shedTriggerBytes + 20_000) } }, remoteCtx);
893
895
  await handlers.agent_before_settle!({}, remoteCtx);
894
896
  assert(compactCalls.length === 6, "remote byte shedding does not force premature compaction at 49k tokens");
895
897
 
@@ -902,10 +904,10 @@ if (isMain(import.meta.url)) {
902
904
 
903
905
  // Compaction input trimming shrinks split-turn prefixes cleanly without triggering follow-ups.
904
906
  const splitTurnPrefix: MessageLike[] = [
905
- { role: "assistant", content: [{ type: "toolCall", arguments: { content: "q".repeat(COMPACT_INPUT_BYTES) } }] },
907
+ { role: "assistant", content: [{ type: "toolCall", arguments: { content: "q".repeat(liveCeilings.compactInputBytes) } }] },
906
908
  ];
907
909
  await handlers.session_before_compact!({ preparation: { turnPrefixMessages: splitTurnPrefix } }, remoteCtx);
908
- assert(jsonByteLength(splitTurnPrefix) < COMPACT_INPUT_BYTES, "session_before_compact trims split-turn prefix messages too");
910
+ assert(jsonByteLength(splitTurnPrefix) < liveCeilings.compactInputBytes, "session_before_compact trims split-turn prefix messages too");
909
911
 
910
912
  // Remote byte silent shedding stays active even when Auto-compact is Off, and never triggers ctx.compact().
911
913
  setAutoCompact("Off");
@@ -924,11 +926,11 @@ if (isMain(import.meta.url)) {
924
926
  // A fixture sized for the 1 MB default says nothing once the wall scales: at 16 MB
925
927
  // the same array is far under the trigger and the hook rightly stays quiet.
926
928
  // Size it against the ceiling in force, or skip when scaling makes that impractical.
927
- const overTrigger = jsonByteLength(manyMsgs) > SHED_TRIGGER_BYTES;
929
+ const overTrigger = jsonByteLength(manyMsgs) > liveCeilings.shedTriggerBytes;
928
930
  if (overTrigger) {
929
931
  assert(
930
932
  Array.isArray(shedMany?.messages) &&
931
- jsonByteLength(shedMany.messages) <= SHED_TARGET_BYTES &&
933
+ jsonByteLength(shedMany.messages) <= liveCeilings.shedTargetBytes &&
932
934
  shedMany.messages[0]?.role === "user",
933
935
  "many-message session sheds below the ceiling even with Auto-compact Off",
934
936
  );
@@ -938,7 +940,7 @@ if (isMain(import.meta.url)) {
938
940
  const compactMany = manyMsgs.slice();
939
941
  await handlers.session_before_compact!({ preparation: { messagesToSummarize: compactMany } }, remoteCtx);
940
942
  assert(
941
- jsonByteLength(compactMany) <= COMPACT_INPUT_BYTES && compactMany[0]?.role !== "toolResult",
943
+ jsonByteLength(compactMany) <= liveCeilings.compactInputBytes && compactMany[0]?.role !== "toolResult",
942
944
  "many-message compaction input trims below 720 KB without orphaned toolResult",
943
945
  );
944
946
  await handlers.agent_before_settle!({}, ctxOf(950000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
@@ -950,7 +952,7 @@ if (isMain(import.meta.url)) {
950
952
  const after413 = (await handlers.context!({ messages: hugeRunMsgs }, nonRemoteCtx)) as { messages?: MessageLike[] } | undefined;
951
953
  assert(
952
954
  Array.isArray(after413?.messages) &&
953
- jsonByteLength(after413.messages) + DEFAULT_OVERHEAD_BYTES <= INITIAL_CEILINGS.shedTargetAfter413Bytes,
955
+ jsonByteLength(after413.messages) + DEFAULT_OVERHEAD_BYTES <= liveCeilings.shedTargetAfter413Bytes,
954
956
  "saw413 activates tighter silent shedding on any model",
955
957
  );
956
958
  // Payload limit Off skips shedding and clears wireBytesSnapshot even for remote models.
File without changes
@@ -377,16 +377,15 @@ export function currentToolVerb(active: ReadonlyMap<string, string>): string {
377
377
  * Recognising the label keeps the rule honest: if pi-jev-eye renames its label, this test fails loudly in
378
378
  * the self-check below instead of degrading to a plain grey cell.
379
379
  */
380
- 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));
381
381
 
382
382
  /**
383
- * The pi-jev-eye status cell: `Eye: ● MODE (Backend)`. pi-jev-eye writes the value plain because a status
384
- * is a fact, not a layout; this decides the painting.
383
+ * The pi-jev-eye / pi-decision-eye status cell: `[icon] Eye: ● MODE (Backend)`.
385
384
  *
386
385
  * The trailing parenthesised backend is a modifier, so it takes `dim` while the `Eye:` label and the state
387
- * keep the soft and state tiers — that is what makes `(Clef Flash)` recede and `Eye: ● ON` stay readable
388
- * at a glance. The backend name itself is read out of the value, never hardcoded here: the extension
389
- * 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.
390
389
  */
391
390
  export function jevEyeStatusLine(
392
391
  status: string,
@@ -395,18 +394,35 @@ export function jevEyeStatusLine(
395
394
  soft: (text: string) => string,
396
395
  theme?: { fg?: (color: string, text: string) => string },
397
396
  ): string {
398
- const clean = stripAnsi(status);
399
- const isOff = clean.includes("OFF") || clean.includes("\u25CB");
400
- const isReview = /REVIEW/i.test(clean);
401
- let bullet = isOff ? dim("\u25CB") : acc("\u25CF");
402
- 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");
403
405
  try {
404
- bullet = theme.fg("warning", "\u25CF");
406
+ return theme.fg(token, "\u25CF");
405
407
  } catch {
406
- bullet = acc("\u25CF");
408
+ return fallback("\u25CF");
407
409
  }
408
- }
409
- 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";
410
426
  // `Eye: ● ON (Clef Flash)` -> the base before the first colon, the backend in the trailing parentheses.
411
427
  const base = clean.split(":")[0]!.trim() || "Eye";
412
428
  const at = clean.lastIndexOf("(");
@@ -2504,6 +2520,27 @@ if (isMain(import.meta.url)) {
2504
2520
  jevEyeStatusLine("Eye: ● ON", jevPlain, jevDim, jevPlain, undefined) === "\uf21b" + " Eye: ● ON",
2505
2521
  "no backend suffix means no parenthesis, never a guessed one",
2506
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
+ );
2507
2544
 
2508
2545
  // Self-check: session age survives /resume (header timestamp wins over now).
2509
2546
  const NOW = Date.parse("2026-10-08T12:00:00.000Z");
File without changes
@@ -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
  }
@@ -282,8 +283,11 @@ function attachChildHooks(child: unknown): void {
282
283
 
283
284
  export interface ChatContainerLike {
284
285
  children: unknown[];
286
+ /** Pi < 1.6.0 mouse layout cache. */
285
287
  mouseLayout?: { width: number; children: Array<{ component: unknown; height: number }> };
286
- 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[];
287
291
  invalidate?: () => void;
288
292
  addChild?: (component: unknown) => void;
289
293
  removeChild?: (component: unknown) => void;
@@ -336,6 +340,7 @@ function renderCachedChatContainer(
336
340
  if (allClean) {
337
341
  state.stats.containerHits += 1;
338
342
  container.mouseLayout = { width, children: cached.mouseChildren };
343
+ container.childLines = { width, children: cached.children, parts: cached.parts, lines: cached.lines };
339
344
  return cached.lines;
340
345
  }
341
346
  }
@@ -343,14 +348,16 @@ function renderCachedChatContainer(
343
348
  const lines: string[] = [];
344
349
  const mouseChildren: Array<{ component: unknown; height: number }> = [];
345
350
  const snapshot: unknown[] = new Array(children.length);
351
+ const parts: Array<readonly string[]> = new Array(children.length);
346
352
  const childMeta: ChildMeta[] = new Array(children.length);
347
353
  let allChildrenCacheable = true;
348
354
  let hasExpanded = false;
349
355
 
350
356
  for (let i = 0; i < children.length; i++) {
351
- 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>;
352
358
  snapshot[i] = child;
353
359
  if (!child || typeof child.render !== "function") {
360
+ parts[i] = [];
354
361
  childMeta[i] = { version: 0, scrollOffset: 0, expanded: false };
355
362
  continue;
356
363
  }
@@ -363,7 +370,7 @@ function renderCachedChatContainer(
363
370
  if (expanded) hasExpanded = true;
364
371
  childMeta[i] = { version: ver, scrollOffset, expanded };
365
372
 
366
- let childLines: string[];
373
+ let childLines: readonly string[];
367
374
  if (!isCacheableChild(child) || isDynamicChild(child)) {
368
375
  allChildrenCacheable = false;
369
376
  state.stats.childRenders += 1;
@@ -398,7 +405,7 @@ function renderCachedChatContainer(
398
405
  version: ver,
399
406
  scrollOffset,
400
407
  expanded,
401
- lines: childLines,
408
+ lines: [...childLines],
402
409
  },
403
410
  (entry) =>
404
411
  entry.epoch === state.epoch &&
@@ -410,6 +417,7 @@ function renderCachedChatContainer(
410
417
  }
411
418
  }
412
419
 
420
+ parts[i] = childLines;
413
421
  mouseChildren.push({ component: child, height: childLines.length });
414
422
  for (let j = 0; j < childLines.length; j++) {
415
423
  lines.push(childLines[j]!);
@@ -417,6 +425,7 @@ function renderCachedChatContainer(
417
425
  }
418
426
 
419
427
  container.mouseLayout = { width, children: mouseChildren };
428
+ container.childLines = { width, children: snapshot, parts, lines };
420
429
  if (allChildrenCacheable) {
421
430
  putWidthEntry(
422
431
  state.containerCache,
@@ -429,6 +438,7 @@ function renderCachedChatContainer(
429
438
  hasExpanded,
430
439
  children: snapshot,
431
440
  childMeta,
441
+ parts,
432
442
  lines,
433
443
  mouseChildren,
434
444
  },
@@ -485,6 +495,9 @@ if (InteractiveMode?.prototype) {
485
495
  "init",
486
496
  "handleReloadCommand",
487
497
  "renderSessionContext",
498
+ "renderSessionEntries",
499
+ "renderSessionItems",
500
+ "renderCurrentSessionState",
488
501
  "rebuildChatFromMessages",
489
502
  "addMessageToChat",
490
503
  "handleEvent",
@@ -576,6 +589,13 @@ if (isMain(import.meta.url)) {
576
589
  assert(out2 === out1, "whole-container hit returns cached array reference");
577
590
  assert(c1.renders === 1 && c2.renders === 1, "container hit skips child renders");
578
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
+ );
579
599
 
580
600
  // Streaming child bypasses cache while settled sibling stays cached.
581
601
  c2.isStreaming = true;
File without changes
@@ -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
File without changes
File without changes
File without changes
File without changes
File without changes
package/lib/ansi.ts CHANGED
File without changes
package/lib/box.ts CHANGED
File without changes
package/lib/check.ts CHANGED
File without changes
package/lib/color.ts CHANGED
File without changes
package/lib/compat.ts CHANGED
File without changes
package/lib/format.ts CHANGED
File without changes
File without changes
package/lib/model-heal.ts CHANGED
File without changes
package/lib/patch.ts CHANGED
File without changes
File without changes
package/lib/provider.ts CHANGED
File without changes
package/lib/shortcuts.ts CHANGED
File without changes
package/lib/spinner.ts CHANGED
File without changes
File without changes
package/lib/todos.ts CHANGED
File without changes
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bismawy/pi-arnative",
3
- "version": "0.16.0",
3
+ "version": "0.16.1",
4
4
  "description": "Refined aesthetics. Cohesive tools. Built for Pi. Warm themes, rounded tool boxes, tabbed header, compact footer and a /usage dashboard.",
5
5
  "keywords": [
6
6
  "pi-package",
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes