@bismawy/pi-arnative 0.18.0 → 0.18.2

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.
package/lib/box.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * never loads it as an extension.
5
5
  */
6
6
  import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
7
- import { stripAnsi, thinkingColorOf } from "./ansi.ts";
7
+ import { softSecondaryOf, stripAnsi, thinkingColorOf } from "./ansi.ts";
8
8
 
9
9
  /** A clickable span inside rendered lines: 0-based cell columns, inclusive. */
10
10
  export interface TextSpan {
@@ -125,9 +125,32 @@ export function screenTitle(setting: string, extension = `Arnative${BRAND}`): st
125
125
  return `${setting} - ${extension}`;
126
126
  }
127
127
 
128
+ const KEYCAP = /\[([^\]]+)\]/g;
129
+
130
+ /** Keybind legend paint, one style on every screen (skill arnative-pi §6): the brackets
131
+ * are `dim`, the key glyph inside takes the accent-soft tier, labels and separators stay
132
+ * `dim`. Each segment paints itself, because a `dim` wrap around the whole line would be
133
+ * erased by the reset at the end of the first painted keycap. */
134
+ export function paintKeycapLegend(
135
+ legend: string,
136
+ theme: BoxTheme | null,
137
+ soft: (s: string) => string,
138
+ ): string {
139
+ const dim = (s: string) => (theme ? theme.fg("dim", s) : s);
140
+ if (!theme) return legend;
141
+ let out = "";
142
+ let at = 0;
143
+ for (const match of legend.matchAll(KEYCAP)) {
144
+ out += dim(legend.slice(at, match.index)) + dim("[") + soft(match[1]!) + dim("]");
145
+ at = match.index + match[0].length;
146
+ }
147
+ return out + dim(legend.slice(at));
148
+ }
149
+
128
150
  /** The chrome every arnative screen shares: frame, title in `accent`+bold, description in
129
- * `muted`, blank, the screen's `body`, blank, legend in `dim`. One function so the screens
130
- * cannot drift apart; `body` rows arrive already painted and truncated. */
151
+ * `muted`, blank, the screen's `body`, blank, legend with accent-soft keycaps on `dim`.
152
+ * One function so the screens cannot drift apart; `body` rows arrive already painted and
153
+ * truncated. */
131
154
  export function renderScreen(
132
155
  theme: BoxTheme | null,
133
156
  width: number,
@@ -147,7 +170,7 @@ export function renderScreen(
147
170
  row(""),
148
171
  ...body.map(row),
149
172
  row(""),
150
- row(text.legend.includes("\u001b[") ? text.legend : fg("dim", text.legend)),
173
+ row(text.legend.includes("\u001b[") ? text.legend : paintKeycapLegend(text.legend, theme, softSecondaryOf(theme))),
151
174
  boxEdge("╰", "╯", width, border),
152
175
  ].map((l) => truncateToWidth(l, width, ""));
153
176
  }
@@ -11,6 +11,7 @@ import {
11
11
  AssistantMessageComponent,
12
12
  InteractiveMode,
13
13
  ToolExecutionComponent,
14
+ type ExtensionAPI,
14
15
  } from "@earendil-works/pi-coding-agent";
15
16
  import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
16
17
  import { getActiveTheme, softOf, stripAnsi } from "../ansi.ts";
@@ -88,8 +89,10 @@ export interface TurnBoxState {
88
89
  phaseOverrides: Map<number, boolean>;
89
90
  /** Explicit user overrides for nested tool detail previews. */
90
91
  detailOpen: WeakMap<object, boolean>;
91
- /** Explicit user override for whole-box open/collapsed state; undefined auto-opens while running and collapses when finished. */
92
+ /** Explicit user override for whole-box open/collapsed state; undefined auto-opens while running and collapses after agent_end delay. */
92
93
  boxExpanded?: boolean;
94
+ /** Holds the box open across inter-tool gaps until the whole agent run ends and its auto-collapse delay elapses. */
95
+ autoHoldOpen?: boolean;
93
96
  /** Header [expand all] / [collapse all] override. */
94
97
  allOverride?: boolean;
95
98
  /** Manual viewport scroll offset into logical body lines; null/undefined auto-anchors. */
@@ -769,6 +772,7 @@ export class TurnProgressBoxComponent {
769
772
  spin: string;
770
773
  interactionVersion: number;
771
774
  scrollOffset: number | null | undefined;
775
+ autoHoldOpen: boolean;
772
776
  itemsSig: number;
773
777
  lines: string[];
774
778
  } | null = null;
@@ -809,6 +813,43 @@ export class TurnProgressBoxComponent {
809
813
  update(items: (AssistantLike | ToolLike)[], requestRender?: () => void): void {
810
814
  this.items = items;
811
815
  if (requestRender) this.requestRender = requestRender;
816
+ if (agentTurnActive && this.hasLiveRunTool() && this.state.boxExpanded === undefined) {
817
+ if (!this.state.autoHoldOpen) {
818
+ this.state.autoHoldOpen = true;
819
+ this.state.interactionVersion += 1;
820
+ }
821
+ liveRunBoxes.add(this);
822
+ cancelAutoCollapse(this);
823
+ }
824
+ }
825
+
826
+ private hasLiveRunTool(): boolean {
827
+ for (const item of this.items) {
828
+ if (!isToolComponent(item) || item.hideComponent) continue;
829
+ if (item.isPartial || !item.result) return true;
830
+ if (item.toolCallId && liveRunToolCallIds.has(item.toolCallId)) return true;
831
+ }
832
+ return false;
833
+ }
834
+
835
+ scheduleAutoCollapse(delayMs: number): void {
836
+ cancelAutoCollapse(this);
837
+ if (this.state.boxExpanded !== undefined || !this.state.autoHoldOpen) return;
838
+ const finish = () => {
839
+ pendingCollapseTimers.delete(this);
840
+ if (agentTurnActive && this.hasLiveRunTool()) return;
841
+ this.state.autoHoldOpen = false;
842
+ if (this.state.boxExpanded === undefined) {
843
+ this.bumpAndRequestRender();
844
+ }
845
+ };
846
+ if (delayMs <= 0) {
847
+ finish();
848
+ return;
849
+ }
850
+ const timer = setTimeout(finish, delayMs);
851
+ timer.unref?.();
852
+ pendingCollapseTimers.set(this, timer);
812
853
  }
813
854
 
814
855
  getItems(): readonly (AssistantLike | ToolLike)[] {
@@ -877,10 +918,13 @@ export class TurnProgressBoxComponent {
877
918
  return sig;
878
919
  }
879
920
 
880
- private isPhaseExpanded(phase: ProgressPhase, index: number): boolean {
921
+ private isPhaseExpanded(phase: ProgressPhase, index: number, totalPhases: number): boolean {
881
922
  if (this.state.phaseOverrides.has(index)) return this.state.phaseOverrides.get(index)!;
882
923
  if (this.state.allOverride !== undefined) return this.state.allOverride;
883
924
  if (phase.running || phase.hasError) return true;
925
+ // Keep the latest phase open across inter-tool gaps and the post-agent_end grace delay
926
+ // so finished steps do not snap shut before the whole box collapses.
927
+ if (Boolean(this.state.autoHoldOpen) && index === totalPhases - 1) return true;
884
928
  if (phase.tools.some((t) => this.isDetailOpen(t))) return true;
885
929
  return false;
886
930
  }
@@ -916,6 +960,7 @@ export class TurnProgressBoxComponent {
916
960
  const maxBody = expandedBoxBodyLimit();
917
961
  const spin = spinIcon();
918
962
  const itemsSig = this.computeItemsSig();
963
+ const autoHoldOpen = Boolean(this.state.autoHoldOpen);
919
964
  const fc = this.frameCache;
920
965
  if (
921
966
  fc &&
@@ -925,6 +970,7 @@ export class TurnProgressBoxComponent {
925
970
  fc.spin === spin &&
926
971
  fc.interactionVersion === this.state.interactionVersion &&
927
972
  fc.scrollOffset === this.state.scrollOffset &&
973
+ fc.autoHoldOpen === autoHoldOpen &&
928
974
  fc.itemsSig === itemsSig
929
975
  ) {
930
976
  return fc.lines;
@@ -949,9 +995,14 @@ export class TurnProgressBoxComponent {
949
995
  if (p.running) anyRunning = true;
950
996
  }
951
997
 
952
- const expandedFlags = phases.map((p, i) => this.isPhaseExpanded(p, i));
998
+ if (anyRunning && agentTurnActive && this.state.boxExpanded === undefined) {
999
+ this.state.autoHoldOpen = true;
1000
+ liveRunBoxes.add(this);
1001
+ cancelAutoCollapse(this);
1002
+ }
1003
+ const expandedFlags = phases.map((p, i) => this.isPhaseExpanded(p, i, phases.length));
953
1004
  const allExpanded = expandedFlags.every(Boolean);
954
- const boxExpanded = this.state.boxExpanded ?? anyRunning;
1005
+ const boxExpanded = this.state.boxExpanded ?? (anyRunning || Boolean(this.state.autoHoldOpen));
955
1006
 
956
1007
  const stepCount = `${totalTools} ${totalTools === 1 ? "step" : "steps"}`;
957
1008
  const headerMeta = [
@@ -993,6 +1044,7 @@ export class TurnProgressBoxComponent {
993
1044
  spin,
994
1045
  interactionVersion: this.state.interactionVersion,
995
1046
  scrollOffset: this.state.scrollOffset,
1047
+ autoHoldOpen: Boolean(this.state.autoHoldOpen),
996
1048
  itemsSig,
997
1049
  lines,
998
1050
  };
@@ -1252,6 +1304,7 @@ export class TurnProgressBoxComponent {
1252
1304
  spin,
1253
1305
  interactionVersion: this.state.interactionVersion,
1254
1306
  scrollOffset: this.state.scrollOffset,
1307
+ autoHoldOpen: Boolean(this.state.autoHoldOpen),
1255
1308
  itemsSig,
1256
1309
  lines,
1257
1310
  };
@@ -1259,9 +1312,10 @@ export class TurnProgressBoxComponent {
1259
1312
  }
1260
1313
 
1261
1314
  private togglePhase(hit: RenderedHitMap, hitPhase: HitPhaseRow): boolean {
1262
- const phase = buildPhases(this.items)[hitPhase.phaseIndex];
1315
+ const phases = buildPhases(this.items);
1316
+ const phase = phases[hitPhase.phaseIndex];
1263
1317
  if (!phase) return false;
1264
- const nextExp = !this.isPhaseExpanded(phase, hitPhase.phaseIndex);
1318
+ const nextExp = !this.isPhaseExpanded(phase, hitPhase.phaseIndex, phases.length);
1265
1319
  const clickedBodyRow = hit.scrollOffset + (hitPhase.row - 2);
1266
1320
  if (nextExp && clickedBodyRow > hit.scrollOffset + Math.max(1, hit.maxBody - 3)) {
1267
1321
  this.state.scrollOffset = Math.max(hit.scrollOffset, clickedBodyRow - Math.max(1, hit.maxBody - 4));
@@ -1365,6 +1419,9 @@ export class TurnProgressBoxComponent {
1365
1419
  if (onHeaderBoxToggle) {
1366
1420
  const nextBox = !hit.boxExpanded;
1367
1421
  this.state.boxExpanded = nextBox;
1422
+ this.state.autoHoldOpen = false;
1423
+ liveRunBoxes.delete(this);
1424
+ cancelAutoCollapse(this);
1368
1425
  if (!nextBox) {
1369
1426
  this.state.scrollOffset = null;
1370
1427
  for (const item of this.items) {
@@ -1395,6 +1452,9 @@ export class TurnProgressBoxComponent {
1395
1452
  if (event.type === "click" && event.button === "left" && (event.clickCount ?? 1) === 1) {
1396
1453
  if (!hit.boxExpanded && hit.summaryRow === event.y) {
1397
1454
  this.state.boxExpanded = true;
1455
+ this.state.autoHoldOpen = false;
1456
+ liveRunBoxes.delete(this);
1457
+ cancelAutoCollapse(this);
1398
1458
  this.bumpAndRequestRender();
1399
1459
  return { handled: true, render: true };
1400
1460
  }
@@ -1418,6 +1478,71 @@ export class TurnProgressBoxComponent {
1418
1478
  const PROGRESS_STATES_KEY = Symbol.for("pi-arnative.progressGroupStates");
1419
1479
  const moduleBoxes = new WeakMap<object, TurnProgressBoxComponent>();
1420
1480
 
1481
+ const DEFAULT_AUTO_COLLAPSE_DELAY_MS = 3000;
1482
+ let autoCollapseDelayMs = DEFAULT_AUTO_COLLAPSE_DELAY_MS;
1483
+ let agentTurnActive = false;
1484
+ const liveRunToolCallIds = new Set<string>();
1485
+ const liveRunBoxes = new Set<TurnProgressBoxComponent>();
1486
+ const pendingCollapseTimers = new Map<TurnProgressBoxComponent, ReturnType<typeof setTimeout>>();
1487
+
1488
+ function cancelAutoCollapse(box: TurnProgressBoxComponent): void {
1489
+ const timer = pendingCollapseTimers.get(box);
1490
+ if (timer) {
1491
+ clearTimeout(timer);
1492
+ pendingCollapseTimers.delete(box);
1493
+ }
1494
+ }
1495
+
1496
+ function clearAllAutoCollapseTimers(): void {
1497
+ for (const timer of pendingCollapseTimers.values()) clearTimeout(timer);
1498
+ pendingCollapseTimers.clear();
1499
+ liveRunBoxes.clear();
1500
+ }
1501
+
1502
+ export function onProgressAgentStart(): void {
1503
+ agentTurnActive = true;
1504
+ liveRunToolCallIds.clear();
1505
+ }
1506
+
1507
+ export function onProgressToolStart(toolCallId?: string): void {
1508
+ agentTurnActive = true;
1509
+ if (toolCallId) liveRunToolCallIds.add(toolCallId);
1510
+ }
1511
+
1512
+ export function onProgressAgentEnd(): void {
1513
+ agentTurnActive = false;
1514
+ liveRunToolCallIds.clear();
1515
+ const boxes = [...liveRunBoxes];
1516
+ liveRunBoxes.clear();
1517
+ for (const box of boxes) {
1518
+ box.scheduleAutoCollapse(autoCollapseDelayMs);
1519
+ }
1520
+ }
1521
+
1522
+ export function onProgressSessionReset(): void {
1523
+ agentTurnActive = false;
1524
+ liveRunToolCallIds.clear();
1525
+ clearAllAutoCollapseTimers();
1526
+ }
1527
+
1528
+ export function registerProgressGroupLifecycle(pi: ExtensionAPI): void {
1529
+ pi.on("agent_start", async () => {
1530
+ onProgressAgentStart();
1531
+ });
1532
+ pi.on("tool_execution_start", async (event) => {
1533
+ onProgressToolStart((event as { toolCallId?: string } | undefined)?.toolCallId);
1534
+ });
1535
+ pi.on("agent_end", async () => {
1536
+ onProgressAgentEnd();
1537
+ });
1538
+ pi.on("session_start", async () => {
1539
+ onProgressSessionReset();
1540
+ });
1541
+ pi.on("session_shutdown", async () => {
1542
+ onProgressSessionReset();
1543
+ });
1544
+ }
1545
+
1421
1546
  function getProgressStates(): WeakMap<object, TurnBoxState> {
1422
1547
  const g = globalThis as Record<symbol, WeakMap<object, TurnBoxState> | undefined>;
1423
1548
  let states = g[PROGRESS_STATES_KEY];
@@ -1458,6 +1583,7 @@ export function syncProgressBoxesExpanded(children: readonly unknown[], expanded
1458
1583
  state.phaseOverrides.clear();
1459
1584
  state.detailOpen = new WeakMap();
1460
1585
  state.boxExpanded = expanded;
1586
+ state.autoHoldOpen = false;
1461
1587
  state.allOverride = expanded;
1462
1588
  state.scrollOffset = expanded ? 0 : null;
1463
1589
  state.interactionVersion += 1;
@@ -1551,7 +1677,15 @@ export const __test = {
1551
1677
  COLLAPSE_ALL_LABEL,
1552
1678
  SHOW_LABEL,
1553
1679
  HIDE_LABEL,
1680
+ DEFAULT_AUTO_COLLAPSE_DELAY_MS,
1554
1681
  extractNarration,
1555
1682
  countDiffStats,
1556
1683
  heuristicPhaseTitle,
1684
+ onProgressAgentStart,
1685
+ onProgressToolStart,
1686
+ onProgressAgentEnd,
1687
+ onProgressSessionReset,
1688
+ setAutoCollapseDelayMs(ms: number) {
1689
+ autoCollapseDelayMs = ms;
1690
+ },
1557
1691
  };
@@ -44,6 +44,7 @@ import {
44
44
  isProgressBox,
45
45
  onToolLayoutChange,
46
46
  projectTranscriptChildren,
47
+ registerProgressGroupLifecycle,
47
48
  } from "./progress-group.ts";
48
49
 
49
50
  /** Stored exactly as the picker shows them; `"On"` is the default. */
@@ -86,6 +87,30 @@ interface ContainerCacheEntry {
86
87
  mouseChildren: Array<{ component: unknown; height: number }>;
87
88
  }
88
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
+
89
114
  const MAX_WIDTH_ENTRIES = 3;
90
115
 
91
116
  // Exact prototypes exclude extension subclasses with unknown render/invalidation behavior.
@@ -110,6 +135,7 @@ interface RenderCacheState {
110
135
  versions: WeakMap<object, number>;
111
136
  childCache: WeakMap<object, ChildCacheEntry[]>;
112
137
  containerCache: WeakMap<object, ContainerCacheEntry[]>;
138
+ dynamicFrameCache: WeakMap<object, DynamicFrameEntry>;
113
139
  /** Incremented on every cache hit/miss when needed by diagnostics/self-checks. */
114
140
  stats: { containerHits: number; childHits: number; childRenders: number };
115
141
  }
@@ -122,10 +148,13 @@ function getCacheState(): RenderCacheState {
122
148
  versions: new WeakMap(),
123
149
  childCache: new WeakMap(),
124
150
  containerCache: new WeakMap(),
151
+ dynamicFrameCache: new WeakMap(),
125
152
  stats: { containerHits: 0, childHits: 0, childRenders: 0 },
126
153
  } satisfies RenderCacheState;
127
154
  }
128
- return rt.renderCacheState as RenderCacheState;
155
+ const s = rt.renderCacheState as RenderCacheState;
156
+ if (!s.dynamicFrameCache) s.dynamicFrameCache = new WeakMap();
157
+ return s;
129
158
  }
130
159
 
131
160
  const renderCacheSetting = choiceSetting(RENDER_CACHE_KEY, RENDER_CACHE_CHOICES, DEFAULT_RENDER_CACHE);
@@ -411,90 +440,260 @@ function renderCachedChatContainer(
411
440
  }
412
441
  }
413
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
+
414
658
  const lines: string[] = [];
415
659
  const mouseChildren: Array<{ component: unknown; height: number }> = [];
416
660
  const snapshot: unknown[] = new Array(children.length);
417
661
  const parts: Array<readonly string[]> = new Array(children.length);
418
662
  const childMeta: ChildMeta[] = new Array(children.length);
419
663
  let allChildrenCacheable = true;
664
+ let allKnownTail = true;
420
665
  let hasExpanded = false;
666
+ let prefixLen = 0;
667
+ let prefixHasExpanded = false;
668
+ let prefixLineCount = 0;
669
+ let stillPrefix = true;
421
670
 
422
671
  for (let i = 0; i < children.length; i++) {
423
672
  const child = children[i] as { render?: (w: number) => readonly string[] } & Record<string | symbol, unknown>;
424
673
  snapshot[i] = child;
425
- if (!child || typeof child.render !== "function") {
426
- parts[i] = [];
427
- childMeta[i] = { version: 0, interactionVersion: 0, scrollOffset: 0, expanded: false };
428
- continue;
429
- }
430
- if (!isProgressBox(child)) attachChildHooks(child);
431
-
432
- const isObj = typeof child === "object";
433
- const curMeta = childMetaOf(child, state);
434
- const { version: ver, interactionVersion, scrollOffset, expanded } = curMeta;
435
- if (expanded) hasExpanded = true;
436
- childMeta[i] = curMeta;
437
-
438
- let childLines: readonly string[];
439
- 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) {
440
678
  allChildrenCacheable = false;
441
- state.stats.childRenders += 1;
442
- childLines = child.render(width);
443
- } else {
444
- const hit = isObj
445
- ? findWidthEntry(
446
- state.childCache.get(child),
447
- width,
448
- (entry) =>
449
- entry.epoch === state.epoch &&
450
- entry.version === ver &&
451
- entry.interactionVersion === interactionVersion &&
452
- entry.scrollOffset === scrollOffset &&
453
- entry.expanded === expanded &&
454
- (!expanded || entry.rows === rows),
455
- )
456
- : undefined;
457
- if (hit) {
458
- state.stats.childHits += 1;
459
- childLines = hit.lines;
460
- } else {
461
- state.stats.childRenders += 1;
462
- childLines = child.render(width);
463
- if (isObj) {
464
- putWidthEntry(
465
- state.childCache,
466
- child,
467
- {
468
- width,
469
- rows,
470
- epoch: state.epoch,
471
- version: ver,
472
- interactionVersion,
473
- scrollOffset,
474
- expanded,
475
- lines: [...childLines],
476
- },
477
- (entry) =>
478
- entry.epoch === state.epoch &&
479
- entry.version === ver &&
480
- entry.interactionVersion === interactionVersion &&
481
- entry.scrollOffset === scrollOffset &&
482
- entry.expanded === expanded,
483
- );
484
- }
485
- }
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;
486
685
  }
487
-
488
- parts[i] = childLines;
489
- mouseChildren.push({ component: child, height: childLines.length });
490
- for (let j = 0; j < childLines.length; j++) {
491
- 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]!);
492
690
  }
493
691
  }
494
692
 
495
693
  container.mouseLayout = { width, children: mouseChildren };
496
694
  container.childLines = { width, children: snapshot, parts, lines };
497
695
  if (allChildrenCacheable) {
696
+ state.dynamicFrameCache.delete(container);
498
697
  putWidthEntry(
499
698
  state.containerCache,
500
699
  container,
@@ -514,6 +713,27 @@ function renderCachedChatContainer(
514
713
  );
515
714
  } else {
516
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
+ }
517
737
  }
518
738
  return lines;
519
739
  }
@@ -587,6 +807,7 @@ if (InteractiveMode?.prototype) {
587
807
  }
588
808
 
589
809
  export default function registerRenderCache(pi: ExtensionAPI): void {
810
+ registerProgressGroupLifecycle(pi);
590
811
  pi.on("session_start", async () => {
591
812
  clearRenderCache();
592
813
  });
package/package.json CHANGED
@@ -1,50 +1,50 @@
1
1
  {
2
- "name": "@bismawy/pi-arnative",
3
- "version": "0.18.0",
4
- "description": "Refined aesthetics. Cohesive tools. Built for Pi. Warm themes, rounded tool boxes, tabbed header, compact footer and a /usage dashboard.",
5
- "keywords": [
6
- "pi-package",
7
- "pi-theme",
8
- "pi-extension"
9
- ],
10
- "type": "module",
11
- "license": "MIT",
12
- "publishConfig": {
13
- "access": "public"
14
- },
15
- "repository": {
16
- "type": "git",
17
- "url": "git+https://github.com/bismawy/pi-arnative.git"
18
- },
19
- "homepage": "https://github.com/bismawy/pi-arnative#readme",
20
- "files": [
21
- "extensions",
22
- "lib",
23
- "themes/*.json",
24
- "LICENSE",
25
- "README.md"
26
- ],
27
- "pi": {
28
- "image": "https://raw.githubusercontent.com/bismawy/pi-arnative/main/assets/banner.webp",
29
- "extensions": [
30
- "./extensions/index.ts"
31
- ],
32
- "themes": [
33
- "./themes/*.json"
34
- ]
35
- },
36
- "peerDependencies": {
37
- "@earendil-works/pi-ai": "*",
38
- "@earendil-works/pi-coding-agent": "*",
39
- "@earendil-works/pi-tui": "*"
40
- },
41
- "scripts": {
42
- "dev": "pi --extension ./extensions/index.ts",
43
- "test": "node themes/gen-themes.mjs --check && node scripts/reporter.mjs --self-check && node --test --test-reporter=./scripts/reporter.mjs",
44
- "preview": "node scripts/preview.mjs",
45
- "overlay": "node scripts/overlay.mjs",
46
- "themes": "node themes/gen-themes.mjs",
47
- "release:check": "node scripts/release-check.mjs pre-tag",
48
- "prepublishOnly": "npm test && node scripts/release-check.mjs pre-publish"
49
- }
2
+ "name": "@bismawy/pi-arnative",
3
+ "version": "0.18.2",
4
+ "description": "Refined aesthetics. Cohesive tools. Built for Pi. Warm themes, rounded tool boxes, tabbed header, compact footer and a /usage dashboard.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi-theme",
8
+ "pi-extension"
9
+ ],
10
+ "type": "module",
11
+ "license": "MIT",
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/bismawy/pi-arnative.git"
18
+ },
19
+ "homepage": "https://github.com/bismawy/pi-arnative#readme",
20
+ "files": [
21
+ "extensions",
22
+ "lib",
23
+ "themes/*.json",
24
+ "LICENSE",
25
+ "README.md"
26
+ ],
27
+ "pi": {
28
+ "image": "https://raw.githubusercontent.com/bismawy/pi-arnative/main/assets/banner.webp",
29
+ "extensions": [
30
+ "./extensions/index.ts"
31
+ ],
32
+ "themes": [
33
+ "./themes/*.json"
34
+ ]
35
+ },
36
+ "peerDependencies": {
37
+ "@earendil-works/pi-ai": "*",
38
+ "@earendil-works/pi-coding-agent": "*",
39
+ "@earendil-works/pi-tui": "*"
40
+ },
41
+ "scripts": {
42
+ "dev": "pi --extension ./extensions/index.ts",
43
+ "test": "node themes/gen-themes.mjs --check && node scripts/reporter.mjs --self-check && node --test --test-reporter=./scripts/reporter.mjs",
44
+ "preview": "node scripts/preview.mjs",
45
+ "overlay": "node scripts/overlay.mjs",
46
+ "themes": "node themes/gen-themes.mjs",
47
+ "release:check": "node scripts/release-check.mjs pre-tag",
48
+ "prepublishOnly": "npm test && node scripts/release-check.mjs pre-publish"
49
+ }
50
50
  }