@bismawy/pi-arnative 0.16.1 → 0.18.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 (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 +1691 -0
  17. package/{extensions → lib/features}/render-cache.ts +391 -218
  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 +48 -49
  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
@@ -18,7 +18,7 @@
18
18
  * - When every child is known and settled, the container checks child state, then
19
19
  * reuses its cached `lines` and `mouseLayout` without rebuilding the combined array.
20
20
  * - Attaches at the `InteractiveMode.chatContainer` instance layer (not `Container.prototype`),
21
- * so it never collides with `section-headers.ts` or `ui-render-tweaks.ts` prototype
21
+ * so it never collides with `headers.ts` or `ui-render-tweaks.ts` prototype
22
22
  * patches and sits outside `tools.ts` / `timestamps.ts` render wrappers.
23
23
  */
24
24
  import {
@@ -32,30 +32,33 @@ import {
32
32
  type ExtensionAPI,
33
33
  } from "@earendil-works/pi-coding-agent";
34
34
  import { Text } from "@earendil-works/pi-tui";
35
- import { mkdtempSync, rmSync } from "node:fs";
36
- import { tmpdir } from "node:os";
37
- import { join } from "node:path";
38
- import { assert, isMain } from "../lib/check.ts";
39
- import { patchOnce } from "../lib/patch.ts";
40
- import { RENDER_CACHE_KEY, choiceSetting, loadChoice, resetPresetCache } from "../lib/preset-store.ts";
35
+ import { patchOnce } from "../patch.ts";
36
+ import { RENDER_CACHE_KEY, choiceSetting } from "../preset-store.ts";
37
+ import {
38
+ TOOL_BOX_SCROLL_HOLD_KEY as SCROLL_HOLD_KEY,
39
+ TOOL_BOX_SCROLL_OFFSET_KEY as SCROLL_OFFSET_KEY,
40
+ getRuntime,
41
+ } from "../runtime.ts";
42
+ import {
43
+ activeToolLayout,
44
+ isProgressBox,
45
+ onToolLayoutChange,
46
+ projectTranscriptChildren,
47
+ registerProgressGroupLifecycle,
48
+ } from "./progress-group.ts";
41
49
 
42
50
  /** Stored exactly as the picker shows them; `"On"` is the default. */
43
51
  export const RENDER_CACHE_CHOICES = ["On", "Off"] as const;
44
52
  export type RenderCacheChoice = (typeof RENDER_CACHE_CHOICES)[number];
45
- export const DEFAULT_RENDER_CACHE: RenderCacheChoice = "On";
53
+ const DEFAULT_RENDER_CACHE: RenderCacheChoice = "On";
46
54
 
47
55
  const RENDER_CACHE_CONFIG_KEY = Symbol.for("pi-arnative.renderCache");
48
- const RENDER_CACHE_STATE_KEY = Symbol.for("pi-arnative.renderCacheState");
49
56
  const INSTANCE_WRAP_KEY = Symbol.for("pi-arnative.renderCacheWrapped");
50
57
  const INSTANCE_ORIG_KEY = Symbol.for("pi-arnative.renderCacheOriginals");
51
58
 
52
- // Shared symbols from sibling extensions so active animations / scroll-holds bypass cache.
53
- const THINKING_STATE_KEY = Symbol.for("pi-arnative.thinkingLabelState");
54
- const SCROLL_OFFSET_KEY = Symbol.for("pi-arnative.toolBoxScrollOffset");
55
- const SCROLL_HOLD_KEY = Symbol.for("pi-arnative.toolBoxScrollHold");
56
-
57
59
  interface ChildMeta {
58
60
  version: number;
61
+ interactionVersion: number;
59
62
  scrollOffset: number;
60
63
  expanded: boolean;
61
64
  }
@@ -65,6 +68,7 @@ interface ChildCacheEntry {
65
68
  rows: number;
66
69
  epoch: number;
67
70
  version: number;
71
+ interactionVersion: number;
68
72
  scrollOffset: number;
69
73
  expanded: boolean;
70
74
  lines: string[];
@@ -83,6 +87,30 @@ interface ContainerCacheEntry {
83
87
  mouseChildren: Array<{ component: unknown; height: number }>;
84
88
  }
85
89
 
90
+ /**
91
+ * Settled-prefix + last-frame cache used while trailing children are dynamic (streaming
92
+ * assistant or active progress box). Reuses the settled transcript prefix via native
93
+ * `.slice()`, and returns `lines` directly with zero allocations when dynamic children
94
+ * return the same cached array reference (e.g. between 500ms progress spinner frames).
95
+ */
96
+ interface DynamicFrameEntry {
97
+ width: number;
98
+ rows: number;
99
+ epoch: number;
100
+ prefixLen: number;
101
+ prefixHasExpanded: boolean;
102
+ prefixChildren: unknown[];
103
+ prefixMeta: ChildMeta[];
104
+ prefixParts: Array<readonly string[]>;
105
+ prefixLines: string[];
106
+ prefixMouseChildren: Array<{ component: unknown; height: number }>;
107
+ allKnownTail: boolean;
108
+ children: unknown[];
109
+ parts: Array<readonly string[]>;
110
+ lines: string[];
111
+ mouseChildren: Array<{ component: unknown; height: number }>;
112
+ }
113
+
86
114
  const MAX_WIDTH_ENTRIES = 3;
87
115
 
88
116
  // Exact prototypes exclude extension subclasses with unknown render/invalidation behavior.
@@ -97,7 +125,9 @@ const CACHEABLE_CHILD_PROTOTYPES = new Set<object>([
97
125
  ]);
98
126
 
99
127
  function isCacheableChild(child: unknown): boolean {
100
- return !!child && typeof child === "object" && CACHEABLE_CHILD_PROTOTYPES.has(Object.getPrototypeOf(child));
128
+ if (!child || typeof child !== "object") return false;
129
+ if (isProgressBox(child)) return true;
130
+ return CACHEABLE_CHILD_PROTOTYPES.has(Object.getPrototypeOf(child));
101
131
  }
102
132
 
103
133
  interface RenderCacheState {
@@ -105,22 +135,26 @@ interface RenderCacheState {
105
135
  versions: WeakMap<object, number>;
106
136
  childCache: WeakMap<object, ChildCacheEntry[]>;
107
137
  containerCache: WeakMap<object, ContainerCacheEntry[]>;
138
+ dynamicFrameCache: WeakMap<object, DynamicFrameEntry>;
108
139
  /** Incremented on every cache hit/miss when needed by diagnostics/self-checks. */
109
140
  stats: { containerHits: number; childHits: number; childRenders: number };
110
141
  }
111
142
 
112
143
  function getCacheState(): RenderCacheState {
113
- const g = globalThis as Record<symbol, unknown>;
114
- if (!g[RENDER_CACHE_STATE_KEY]) {
115
- g[RENDER_CACHE_STATE_KEY] = {
144
+ const rt = getRuntime();
145
+ if (!rt.renderCacheState) {
146
+ rt.renderCacheState = {
116
147
  epoch: 0,
117
148
  versions: new WeakMap(),
118
149
  childCache: new WeakMap(),
119
150
  containerCache: new WeakMap(),
151
+ dynamicFrameCache: new WeakMap(),
120
152
  stats: { containerHits: 0, childHits: 0, childRenders: 0 },
121
153
  } satisfies RenderCacheState;
122
154
  }
123
- return g[RENDER_CACHE_STATE_KEY] as RenderCacheState;
155
+ const s = rt.renderCacheState as RenderCacheState;
156
+ if (!s.dynamicFrameCache) s.dynamicFrameCache = new WeakMap();
157
+ return s;
124
158
  }
125
159
 
126
160
  const renderCacheSetting = choiceSetting(RENDER_CACHE_KEY, RENDER_CACHE_CHOICES, DEFAULT_RENDER_CACHE);
@@ -186,14 +220,13 @@ function terminalRows(): number {
186
220
  /** True when a transcript component is currently animating, streaming, or hold-scrolling. */
187
221
  export function isDynamicChild(child: unknown): boolean {
188
222
  if (!child || typeof child !== "object") return false;
223
+ if (isProgressBox(child)) return child.isDynamic();
189
224
  const c = child as Record<string | symbol, unknown>;
190
225
  if (c.isStreaming === true) return true;
191
226
  if (c.isPartial === true || c.argsPending === true) return true;
192
227
  if (c.status === "running") return true;
193
228
  if (c[SCROLL_HOLD_KEY] !== undefined) return true;
194
- const thinking = (globalThis as Record<symbol, unknown>)[THINKING_STATE_KEY] as
195
- | { active?: Set<object> }
196
- | undefined;
229
+ const thinking = getRuntime().thinkingLabelState;
197
230
  if (thinking?.active?.has(child)) return true;
198
231
  return false;
199
232
  }
@@ -203,7 +236,7 @@ type MarkedWrap = AnyFn & { [INSTANCE_WRAP_KEY]?: true };
203
236
 
204
237
  /**
205
238
  * Wrap an instance method without touching the prototype chain, so prototype-level
206
- * patches from sibling extensions (`tools.ts`, `timestamps.ts`, `section-headers.ts`,
239
+ * patches from sibling extensions (`tools.ts`, `timestamps.ts`, `headers.ts`,
207
240
  * `ui-render-tweaks.ts`) continue to run and reinstall cleanly across `/reload`.
208
241
  */
209
242
  function wrapInstanceMethod(
@@ -295,17 +328,78 @@ export interface ChatContainerLike {
295
328
  handleMouse?: (event: unknown) => unknown;
296
329
  }
297
330
 
331
+ /** 32-bit FNV-1a mix (odd multiplier = bijective mod 2^32, so early values never shift out). */
332
+ function mixHash(hash: number, value: number): number {
333
+ return Math.imul(hash ^ (value | 0), 0x01000193) | 0;
334
+ }
335
+
336
+ function childMetaOf(child: unknown, state: RenderCacheState): ChildMeta {
337
+ if (!child || typeof child !== "object") {
338
+ return { version: 0, interactionVersion: 0, scrollOffset: 0, expanded: false };
339
+ }
340
+ if (isProgressBox(child)) {
341
+ const items = child.getItems();
342
+ let hash = mixHash(0x811c9dc5 | 0, items.length);
343
+ let expanded = false;
344
+ for (const item of items) {
345
+ if (item && typeof item === "object") {
346
+ attachChildHooks(item);
347
+ const itemVer = state.versions.get(item) ?? 0;
348
+ const itemExp = Boolean((item as { expanded?: boolean }).expanded);
349
+ if (itemExp) expanded = true;
350
+ hash = mixHash(hash, itemVer);
351
+ hash = mixHash(hash, itemExp ? 1 : 0);
352
+ }
353
+ }
354
+ return {
355
+ version: hash,
356
+ interactionVersion: child.getInteractionVersion(),
357
+ scrollOffset: child.getScrollSignature(),
358
+ expanded: expanded || items.length > 6,
359
+ };
360
+ }
361
+ const cObj = child as Record<string | symbol, unknown>;
362
+ return {
363
+ version: state.versions.get(cObj) ?? 0,
364
+ interactionVersion: 0,
365
+ scrollOffset: Number(cObj[SCROLL_OFFSET_KEY] ?? 0),
366
+ expanded: Boolean(cObj.expanded),
367
+ };
368
+ }
369
+
370
+ function renderProjectedDirect(container: ChatContainerLike, children: readonly unknown[], width: number): string[] {
371
+ const lines: string[] = [];
372
+ const mouseChildren: Array<{ component: unknown; height: number }> = [];
373
+ const snapshot: unknown[] = new Array(children.length);
374
+ const parts: Array<readonly string[]> = new Array(children.length);
375
+ for (let i = 0; i < children.length; i++) {
376
+ const child = children[i] as { render?: (w: number) => readonly string[] } | null | undefined;
377
+ snapshot[i] = child;
378
+ const childLines = child && typeof child.render === "function" ? child.render(width) : [];
379
+ parts[i] = childLines;
380
+ mouseChildren.push({ component: child, height: childLines.length });
381
+ for (let j = 0; j < childLines.length; j++) lines.push(childLines[j]!);
382
+ }
383
+ container.mouseLayout = { width, children: mouseChildren };
384
+ container.childLines = { width, children: snapshot, parts, lines };
385
+ return lines;
386
+ }
387
+
298
388
  function renderCachedChatContainer(
299
389
  container: ChatContainerLike,
300
390
  width: number,
301
391
  callNextRender: (self: any, args: unknown[]) => unknown,
302
392
  ): string[] {
393
+ const rawChildren = Array.isArray(container.children) ? container.children : [];
394
+ const grouped = activeToolLayout() === "Grouped";
395
+ const children = grouped ? projectTranscriptChildren(rawChildren) : rawChildren;
396
+
303
397
  if (activeRenderCache() !== "On") {
304
- return callNextRender(container, [width]) as string[];
398
+ if (!grouped) return callNextRender(container, [width]) as string[];
399
+ return renderProjectedDirect(container, children, width);
305
400
  }
306
401
 
307
402
  const state = getCacheState();
308
- const children = Array.isArray(container.children) ? container.children : [];
309
403
  const rows = terminalRows();
310
404
  const containerVer = state.versions.get(container) ?? 0;
311
405
 
@@ -326,12 +420,13 @@ function renderCachedChatContainer(
326
420
  allClean = false;
327
421
  break;
328
422
  }
329
- const cObj = child && typeof child === "object" ? (child as Record<string | symbol, unknown>) : null;
423
+ const cur = childMetaOf(child, state);
330
424
  const meta = cached.childMeta[i]!;
331
425
  if (
332
- meta.version !== (cObj ? (state.versions.get(cObj) ?? 0) : 0) ||
333
- meta.scrollOffset !== (cObj ? Number(cObj[SCROLL_OFFSET_KEY] ?? 0) : 0) ||
334
- meta.expanded !== Boolean(cObj?.expanded)
426
+ meta.version !== cur.version ||
427
+ meta.interactionVersion !== cur.interactionVersion ||
428
+ meta.scrollOffset !== cur.scrollOffset ||
429
+ meta.expanded !== cur.expanded
335
430
  ) {
336
431
  allClean = false;
337
432
  break;
@@ -345,88 +440,260 @@ function renderCachedChatContainer(
345
440
  }
346
441
  }
347
442
 
443
+ // Settled-prefix fast path when trailing children are dynamic: avoid rebuilding and
444
+ // re-pushing tens of thousands of settled lines on every spinner/streaming tick.
445
+ const prevDyn = state.dynamicFrameCache.get(container);
446
+ let reusedPrefix = 0;
447
+ if (
448
+ prevDyn &&
449
+ prevDyn.width === width &&
450
+ prevDyn.epoch === state.epoch &&
451
+ (!prevDyn.prefixHasExpanded || prevDyn.rows === rows) &&
452
+ prevDyn.prefixLen > 0 &&
453
+ prevDyn.prefixLen <= children.length
454
+ ) {
455
+ let prefixClean = true;
456
+ for (let i = 0; i < prevDyn.prefixLen; i++) {
457
+ const child = children[i];
458
+ if (child !== prevDyn.prefixChildren[i] || !isCacheableChild(child) || isDynamicChild(child)) {
459
+ prefixClean = false;
460
+ break;
461
+ }
462
+ const cur = childMetaOf(child, state);
463
+ const meta = prevDyn.prefixMeta[i]!;
464
+ if (
465
+ meta.version !== cur.version ||
466
+ meta.interactionVersion !== cur.interactionVersion ||
467
+ meta.scrollOffset !== cur.scrollOffset ||
468
+ meta.expanded !== cur.expanded
469
+ ) {
470
+ prefixClean = false;
471
+ break;
472
+ }
473
+ }
474
+ if (prefixClean) reusedPrefix = prevDyn.prefixLen;
475
+ }
476
+
477
+ const renderSingleChild = (
478
+ child: ({ render?: (w: number) => readonly string[] } & Record<string | symbol, unknown>) | null | undefined,
479
+ ): {
480
+ lines: readonly string[];
481
+ meta: ChildMeta;
482
+ cacheable: boolean;
483
+ dynamic: boolean;
484
+ expanded: boolean;
485
+ } => {
486
+ if (!child || typeof child.render !== "function") {
487
+ return {
488
+ lines: [],
489
+ meta: { version: 0, interactionVersion: 0, scrollOffset: 0, expanded: false },
490
+ cacheable: true,
491
+ dynamic: false,
492
+ expanded: false,
493
+ };
494
+ }
495
+ if (!isProgressBox(child)) attachChildHooks(child);
496
+ const isObj = typeof child === "object";
497
+ const curMeta = childMetaOf(child, state);
498
+ const { version: ver, interactionVersion, scrollOffset, expanded } = curMeta;
499
+ const cacheable = isCacheableChild(child);
500
+ const dynamic = isDynamicChild(child);
501
+ if (!cacheable || dynamic) {
502
+ state.stats.childRenders += 1;
503
+ return { lines: child.render(width), meta: curMeta, cacheable, dynamic, expanded };
504
+ }
505
+ const hit = isObj
506
+ ? findWidthEntry(
507
+ state.childCache.get(child),
508
+ width,
509
+ (entry) =>
510
+ entry.epoch === state.epoch &&
511
+ entry.version === ver &&
512
+ entry.interactionVersion === interactionVersion &&
513
+ entry.scrollOffset === scrollOffset &&
514
+ entry.expanded === expanded &&
515
+ (!expanded || entry.rows === rows),
516
+ )
517
+ : undefined;
518
+ if (hit) {
519
+ state.stats.childHits += 1;
520
+ return { lines: hit.lines, meta: curMeta, cacheable: true, dynamic: false, expanded };
521
+ }
522
+ state.stats.childRenders += 1;
523
+ const childLines = child.render(width);
524
+ if (isObj) {
525
+ putWidthEntry(
526
+ state.childCache,
527
+ child,
528
+ {
529
+ width,
530
+ rows,
531
+ epoch: state.epoch,
532
+ version: ver,
533
+ interactionVersion,
534
+ scrollOffset,
535
+ expanded,
536
+ lines: [...childLines],
537
+ },
538
+ (entry) =>
539
+ entry.epoch === state.epoch &&
540
+ entry.version === ver &&
541
+ entry.interactionVersion === interactionVersion &&
542
+ entry.scrollOffset === scrollOffset &&
543
+ entry.expanded === expanded,
544
+ );
545
+ }
546
+ return { lines: childLines, meta: curMeta, cacheable: true, dynamic: false, expanded };
547
+ };
548
+
549
+ if (reusedPrefix > 0 && prevDyn) {
550
+ const tailLen = children.length - reusedPrefix;
551
+ const tailLinesList: Array<readonly string[]> = new Array(tailLen);
552
+ const tailMetas: ChildMeta[] = new Array(tailLen);
553
+ const tailCacheable: boolean[] = new Array(tailLen);
554
+ const tailDynamic: boolean[] = new Array(tailLen);
555
+ let allTailSettled = true;
556
+ let allKnownTail = true;
557
+ let tailMatchesPrev = prevDyn.allKnownTail && children.length === prevDyn.children.length;
558
+ let hasExpanded = prevDyn.prefixHasExpanded;
559
+
560
+ for (let t = 0; t < tailLen; t++) {
561
+ const i = reusedPrefix + t;
562
+ const child = children[i] as { render?: (w: number) => readonly string[] } & Record<string | symbol, unknown>;
563
+ const res = renderSingleChild(child);
564
+ tailLinesList[t] = res.lines;
565
+ tailMetas[t] = res.meta;
566
+ tailCacheable[t] = res.cacheable;
567
+ tailDynamic[t] = res.dynamic;
568
+ if (res.expanded) hasExpanded = true;
569
+ if (!res.cacheable) allKnownTail = false;
570
+ if (!res.cacheable || res.dynamic) allTailSettled = false;
571
+ if (tailMatchesPrev && (!res.cacheable || child !== prevDyn.children[i] || res.lines !== prevDyn.parts[i])) {
572
+ tailMatchesPrev = false;
573
+ }
574
+ }
575
+
576
+ // Zero-allocation frame hit: settled prefix unchanged and every dynamic tail child
577
+ // returned the exact same cached array reference.
578
+ if (tailMatchesPrev && !allTailSettled) {
579
+ state.stats.containerHits += 1;
580
+ container.mouseLayout = { width, children: prevDyn.mouseChildren };
581
+ container.childLines = { width, children: prevDyn.children, parts: prevDyn.parts, lines: prevDyn.lines };
582
+ return prevDyn.lines;
583
+ }
584
+
585
+ const lines = prevDyn.prefixLines.slice();
586
+ const mouseChildren = prevDyn.prefixMouseChildren.slice();
587
+ const snapshot = prevDyn.prefixChildren.slice();
588
+ const parts = prevDyn.prefixParts.slice();
589
+ const childMeta = prevDyn.prefixMeta.slice();
590
+ let newPrefixLen = reusedPrefix;
591
+ let newPrefixHasExpanded = prevDyn.prefixHasExpanded;
592
+ let newPrefixLineCount = prevDyn.prefixLines.length;
593
+ let stillPrefix = true;
594
+
595
+ for (let t = 0; t < tailLen; t++) {
596
+ const i = reusedPrefix + t;
597
+ const child = children[i];
598
+ const childLines = tailLinesList[t]!;
599
+ snapshot.push(child);
600
+ parts.push(childLines);
601
+ childMeta.push(tailMetas[t]!);
602
+ mouseChildren.push({ component: child, height: childLines.length });
603
+ for (let j = 0; j < childLines.length; j++) lines.push(childLines[j]!);
604
+ if (stillPrefix && tailCacheable[t] && !tailDynamic[t]) {
605
+ newPrefixLen += 1;
606
+ if (tailMetas[t]!.expanded) newPrefixHasExpanded = true;
607
+ newPrefixLineCount += childLines.length;
608
+ } else {
609
+ stillPrefix = false;
610
+ }
611
+ }
612
+
613
+ container.mouseLayout = { width, children: mouseChildren };
614
+ container.childLines = { width, children: snapshot, parts, lines };
615
+ if (allTailSettled) {
616
+ state.dynamicFrameCache.delete(container);
617
+ putWidthEntry(
618
+ state.containerCache,
619
+ container,
620
+ {
621
+ width,
622
+ rows,
623
+ epoch: state.epoch,
624
+ version: containerVer,
625
+ hasExpanded,
626
+ children: snapshot,
627
+ childMeta,
628
+ parts,
629
+ lines,
630
+ mouseChildren,
631
+ },
632
+ (entry) => entry.epoch === state.epoch && entry.version === containerVer,
633
+ );
634
+ } else {
635
+ state.containerCache.delete(container);
636
+ const prefixChanged = newPrefixLen !== reusedPrefix;
637
+ state.dynamicFrameCache.set(container, {
638
+ width,
639
+ rows,
640
+ epoch: state.epoch,
641
+ prefixLen: newPrefixLen,
642
+ prefixHasExpanded: newPrefixHasExpanded,
643
+ prefixChildren: prefixChanged ? snapshot.slice(0, newPrefixLen) : prevDyn.prefixChildren,
644
+ prefixMeta: prefixChanged ? childMeta.slice(0, newPrefixLen) : prevDyn.prefixMeta,
645
+ prefixParts: prefixChanged ? parts.slice(0, newPrefixLen) : prevDyn.prefixParts,
646
+ prefixLines: prefixChanged ? lines.slice(0, newPrefixLineCount) : prevDyn.prefixLines,
647
+ prefixMouseChildren: prefixChanged ? mouseChildren.slice(0, newPrefixLen) : prevDyn.prefixMouseChildren,
648
+ allKnownTail,
649
+ children: snapshot,
650
+ parts,
651
+ lines,
652
+ mouseChildren,
653
+ });
654
+ }
655
+ return lines;
656
+ }
657
+
348
658
  const lines: string[] = [];
349
659
  const mouseChildren: Array<{ component: unknown; height: number }> = [];
350
660
  const snapshot: unknown[] = new Array(children.length);
351
661
  const parts: Array<readonly string[]> = new Array(children.length);
352
662
  const childMeta: ChildMeta[] = new Array(children.length);
353
663
  let allChildrenCacheable = true;
664
+ let allKnownTail = true;
354
665
  let hasExpanded = false;
666
+ let prefixLen = 0;
667
+ let prefixHasExpanded = false;
668
+ let prefixLineCount = 0;
669
+ let stillPrefix = true;
355
670
 
356
671
  for (let i = 0; i < children.length; i++) {
357
672
  const child = children[i] as { render?: (w: number) => readonly string[] } & Record<string | symbol, unknown>;
358
673
  snapshot[i] = child;
359
- if (!child || typeof child.render !== "function") {
360
- parts[i] = [];
361
- childMeta[i] = { version: 0, scrollOffset: 0, expanded: false };
362
- continue;
363
- }
364
- attachChildHooks(child);
365
-
366
- const isObj = typeof child === "object";
367
- const ver = isObj ? (state.versions.get(child) ?? 0) : 0;
368
- const scrollOffset = isObj ? Number(child[SCROLL_OFFSET_KEY] ?? 0) : 0;
369
- const expanded = Boolean(isObj && child.expanded);
370
- if (expanded) hasExpanded = true;
371
- childMeta[i] = { version: ver, scrollOffset, expanded };
372
-
373
- let childLines: readonly string[];
374
- if (!isCacheableChild(child) || isDynamicChild(child)) {
674
+ const res = renderSingleChild(child);
675
+ childMeta[i] = res.meta;
676
+ if (res.expanded) hasExpanded = true;
677
+ if (!res.cacheable || res.dynamic) {
375
678
  allChildrenCacheable = false;
376
- state.stats.childRenders += 1;
377
- childLines = child.render(width);
378
- } else {
379
- const hit = isObj
380
- ? findWidthEntry(
381
- state.childCache.get(child),
382
- width,
383
- (entry) =>
384
- entry.epoch === state.epoch &&
385
- entry.version === ver &&
386
- entry.scrollOffset === scrollOffset &&
387
- entry.expanded === expanded &&
388
- (!expanded || entry.rows === rows),
389
- )
390
- : undefined;
391
- if (hit) {
392
- state.stats.childHits += 1;
393
- childLines = hit.lines;
394
- } else {
395
- state.stats.childRenders += 1;
396
- childLines = child.render(width);
397
- if (isObj) {
398
- putWidthEntry(
399
- state.childCache,
400
- child,
401
- {
402
- width,
403
- rows,
404
- epoch: state.epoch,
405
- version: ver,
406
- scrollOffset,
407
- expanded,
408
- lines: [...childLines],
409
- },
410
- (entry) =>
411
- entry.epoch === state.epoch &&
412
- entry.version === ver &&
413
- entry.scrollOffset === scrollOffset &&
414
- entry.expanded === expanded,
415
- );
416
- }
417
- }
679
+ stillPrefix = false;
680
+ if (!res.cacheable) allKnownTail = false;
681
+ } else if (stillPrefix) {
682
+ prefixLen += 1;
683
+ if (res.expanded) prefixHasExpanded = true;
684
+ prefixLineCount += res.lines.length;
418
685
  }
419
-
420
- parts[i] = childLines;
421
- mouseChildren.push({ component: child, height: childLines.length });
422
- for (let j = 0; j < childLines.length; j++) {
423
- lines.push(childLines[j]!);
686
+ parts[i] = res.lines;
687
+ mouseChildren.push({ component: child, height: res.lines.length });
688
+ for (let j = 0; j < res.lines.length; j++) {
689
+ lines.push(res.lines[j]!);
424
690
  }
425
691
  }
426
692
 
427
693
  container.mouseLayout = { width, children: mouseChildren };
428
694
  container.childLines = { width, children: snapshot, parts, lines };
429
695
  if (allChildrenCacheable) {
696
+ state.dynamicFrameCache.delete(container);
430
697
  putWidthEntry(
431
698
  state.containerCache,
432
699
  container,
@@ -446,6 +713,27 @@ function renderCachedChatContainer(
446
713
  );
447
714
  } else {
448
715
  state.containerCache.delete(container);
716
+ if (prefixLen > 0) {
717
+ state.dynamicFrameCache.set(container, {
718
+ width,
719
+ rows,
720
+ epoch: state.epoch,
721
+ prefixLen,
722
+ prefixHasExpanded,
723
+ prefixChildren: snapshot.slice(0, prefixLen),
724
+ prefixMeta: childMeta.slice(0, prefixLen),
725
+ prefixParts: parts.slice(0, prefixLen),
726
+ prefixLines: lines.slice(0, prefixLineCount),
727
+ prefixMouseChildren: mouseChildren.slice(0, prefixLen),
728
+ allKnownTail,
729
+ children: snapshot,
730
+ parts,
731
+ lines,
732
+ mouseChildren,
733
+ });
734
+ } else {
735
+ state.dynamicFrameCache.delete(container);
736
+ }
449
737
  }
450
738
  return lines;
451
739
  }
@@ -480,6 +768,10 @@ export function attachChatContainer(container: unknown): void {
480
768
  }
481
769
  if (typeof obj.handleMouse === "function") {
482
770
  wrapInstanceMethod(obj, "handleMouse", (callNext) => function (this: any, ...args: unknown[]) {
771
+ const ev = args[0] as { width?: number } | undefined;
772
+ if (ev && typeof ev.width === "number" && this.childLines?.width !== ev.width && typeof this.render === "function") {
773
+ this.render(ev.width);
774
+ }
483
775
  const res = callNext(this, args);
484
776
  if (res !== undefined) bumpVersion(this);
485
777
  return res;
@@ -487,6 +779,8 @@ export function attachChatContainer(container: unknown): void {
487
779
  }
488
780
  }
489
781
 
782
+ onToolLayoutChange(clearRenderCache);
783
+
490
784
  // Install InteractiveMode hooks so `this.chatContainer` is attached on startup,
491
785
  // `/reload`, session switch, and any incoming chat/tool event.
492
786
  if (InteractiveMode?.prototype) {
@@ -513,6 +807,7 @@ if (InteractiveMode?.prototype) {
513
807
  }
514
808
 
515
809
  export default function registerRenderCache(pi: ExtensionAPI): void {
810
+ registerProgressGroupLifecycle(pi);
516
811
  pi.on("session_start", async () => {
517
812
  clearRenderCache();
518
813
  });
@@ -524,129 +819,7 @@ export default function registerRenderCache(pi: ExtensionAPI): void {
524
819
  });
525
820
  }
526
821
 
527
- // Self-check: `node extensions/render-cache.ts`
528
- if (isMain(import.meta.url)) {
529
- const fixture = mkdtempSync(join(tmpdir(), "arnative-rendercache-"));
530
- process.env.PI_CODING_AGENT_DIR = fixture;
531
- delete (globalThis as Record<symbol, unknown>)[RENDER_CACHE_CONFIG_KEY];
532
- resetPresetCache();
533
-
534
- // Choice persistence & default.
535
- assert(activeRenderCache() === "On", "the default is On");
536
- setRenderCache("Off");
537
- assert(activeRenderCache() === "Off", "Off persists immediately");
538
- assert(loadChoice(RENDER_CACHE_KEY, RENDER_CACHE_CHOICES) === "Off", "Off survives reload from disk");
539
- setRenderCache("On");
540
- assert(activeRenderCache() === "On", "switching back to On restores caching");
541
-
542
- // Use a known Text prototype to exercise cache policy without loading a theme.
543
- function makeChild(text: string) {
544
- const child = Object.assign(new Text(text, 0, 0), { renders: 0, isStreaming: false, isPartial: false, expanded: false });
545
- const setText = child.setText.bind(child);
546
- child.setText = (next: string): void => { text = next; setText(next); };
547
- const result = Object.assign(child, {
548
- handleInput(key: string): void { child.setText(`${text}:${key}`); },
549
- });
550
- result.render = (width: number): string[] => { result.renders += 1; return [`${text}@${width}`]; };
551
- return result as typeof result & { [key: symbol]: unknown };
552
- }
553
- type FakeChild = ReturnType<typeof makeChild>;
554
- class FakeContainer implements ChatContainerLike {
555
- children: FakeChild[] = [];
556
- mouseLayout?: { width: number; children: Array<{ component: unknown; height: number }> };
557
- addChild(c: FakeChild): void {
558
- this.children.push(c);
559
- }
560
- invalidate(): void {
561
- for (const c of this.children) c.invalidate();
562
- }
563
- render(width: number): string[] {
564
- const lines: string[] = [];
565
- const mouseChildren: Array<{ component: unknown; height: number }> = [];
566
- for (const c of this.children) {
567
- const out = c.render(width);
568
- mouseChildren.push({ component: c, height: out.length });
569
- lines.push(...out);
570
- }
571
- this.mouseLayout = { width, children: mouseChildren };
572
- return lines;
573
- }
574
- }
575
-
576
- const container = new FakeContainer();
577
- const c1 = makeChild("msg1");
578
- const c2 = makeChild("msg2");
579
- container.addChild(c1);
580
- container.addChild(c2);
581
- attachChatContainer(container);
582
-
583
- const out1 = container.render(80);
584
- assert(out1.join(",") === "msg1@80,msg2@80", "first render outputs both children");
585
- assert(c1.renders === 1 && c2.renders === 1, "first render calls each child once");
586
-
587
- // Second render at same width hits whole container cache: zero child.render calls.
588
- const out2 = container.render(80);
589
- assert(out2 === out1, "whole-container hit returns cached array reference");
590
- assert(c1.renders === 1 && c2.renders === 1, "container hit skips child renders");
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
- );
599
-
600
- // Streaming child bypasses cache while settled sibling stays cached.
601
- c2.isStreaming = true;
602
- c2.setText("streaming");
603
- const out3 = container.render(80);
604
- assert(out3.join(",") === "msg1@80,streaming@80", "streaming child updates live");
605
- assert(c1.renders === 1 && c2.renders === 2, "settled sibling stayed cached while streaming child re-rendered");
606
-
607
- c2.isStreaming = false;
608
- const out4 = container.render(80);
609
- assert(out4.join(",") === "msg1@80,streaming@80", "post-stream render caches final state");
610
- assert(c1.renders === 1 && c2.renders === 3, "settled after stream renders once then caches");
611
- container.render(80);
612
- assert(c1.renders === 1 && c2.renders === 3, "steady state hits container cache again");
613
-
614
- // Width change renders unseen width; toggling back to previous width hits 2-width LRU in O(1).
615
- const out5 = container.render(100);
616
- assert(out5.join(",") === "msg1@100,streaming@100", "width change re-renders at new width");
617
- assert(c1.renders === 2 && c2.renders === 4, "both re-rendered for new width");
618
- const out5Back = container.render(80);
619
- assert(out5Back === out4, "toggling back to prior width hits 2-width container LRU");
620
- assert(c1.renders === 2 && c2.renders === 4, "toggling back skips child renders");
621
- container.render(100);
622
-
623
- // Mutation on one child invalidates only that child.
624
- c1.setText("edited");
625
- const out6 = container.render(100);
626
- assert(out6.join(",") === "edited@100,streaming@100", "mutated child re-renders");
627
- assert(c1.renders === 3 && c2.renders === 4, "unchanged sibling stayed cached");
628
-
629
- // handleInput mutation invalidates that child without needing explicit invalidate().
630
- c1.handleInput("x");
631
- const out6Input = container.render(100);
632
- assert(out6Input.join(",") === "edited:x@100,streaming@100", "handleInput invalidates mutated child");
633
- assert(c1.renders === 4 && c2.renders === 4, "handleInput did not invalidate sibling");
634
-
635
- // Tool box scroll-offset change invalidates without explicit invalidate().
636
- c2[SCROLL_OFFSET_KEY] = 5;
637
- container.render(100);
638
- assert(c1.renders === 4 && c2.renders === 5, "scrollOffset change invalidates that tool box");
639
-
640
- // Off mode disables caching completely.
641
- setRenderCache("Off");
642
- container.render(100);
643
- container.render(100);
644
- assert(c1.renders === 6 && c2.renders === 7, "Off mode renders directly every frame");
645
- setRenderCache("On");
646
-
647
- rmSync(fixture, { recursive: true, force: true });
648
- delete process.env.PI_CODING_AGENT_DIR;
649
- delete (globalThis as Record<symbol, unknown>)[RENDER_CACHE_CONFIG_KEY];
650
- resetPresetCache();
651
- console.log("render-cache.ts self-check OK");
652
- }
822
+ export const __test = {
823
+ RENDER_CACHE_CONFIG_KEY,
824
+ SCROLL_OFFSET_KEY,
825
+ };