@bismawy/pi-arnative 0.11.1 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -6
- package/README.md +16 -6
- package/extensions/arnative.ts +214 -24
- package/extensions/autocompact.ts +659 -63
- package/extensions/budget.ts +37 -10
- package/extensions/footer.ts +611 -21
- package/extensions/model-heal.ts +14 -17
- package/extensions/render-cache.ts +638 -0
- package/extensions/timestamps.ts +3 -3
- package/extensions/todos.ts +74 -4
- package/extensions/tools.ts +246 -12
- package/extensions/ui-render-tweaks.ts +273 -1
- package/extensions/usage.ts +11 -7
- package/lib/list-picker.ts +19 -3
- package/lib/model-heal.ts +38 -12
- package/lib/patch.ts +26 -1
- package/lib/preset-store.ts +6 -1
- package/lib/status-widget.ts +5 -16
- package/lib/todos.ts +7 -4
- package/package.json +3 -3
package/extensions/model-heal.ts
CHANGED
|
@@ -34,8 +34,9 @@ interface AssistantMessage {
|
|
|
34
34
|
errorMessage?: string;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/** models.json watcher debounce: batch rapid writes (a heal pass re-reading its own write). */
|
|
37
38
|
const DEBOUNCE_MS = 800;
|
|
38
|
-
|
|
39
|
+
|
|
39
40
|
|
|
40
41
|
const registryOf = (ctx: unknown): RegistryLike | undefined => (ctx as { modelRegistry?: RegistryLike } | undefined)?.modelRegistry;
|
|
41
42
|
|
|
@@ -83,28 +84,18 @@ export default function registerModelHeal(pi: ExtensionAPI): void {
|
|
|
83
84
|
bindSetModel((model) => pi.setModel(model as never));
|
|
84
85
|
let watcher: FSWatcher | undefined;
|
|
85
86
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
86
|
-
let widgetTimer: ReturnType<typeof setTimeout> | undefined;
|
|
87
87
|
let deferNoticeShown = false;
|
|
88
88
|
|
|
89
89
|
// ctx getters throw once the session was replaced or reloaded, and deferred callbacks
|
|
90
|
-
// (timer, watcher, network passes) can outlive it: capture ui while live, guard
|
|
90
|
+
// (timer, watcher, network passes) can outlive it: capture ui while live, guard access.
|
|
91
91
|
function notify(ctx: ExtensionContext, lines: string[]): void {
|
|
92
|
-
let ui: ExtensionContext["ui"] | undefined;
|
|
93
92
|
try {
|
|
94
|
-
|
|
95
|
-
|
|
93
|
+
// Transcript notify, like pi-jev-eye: the widget slot above the input box steals focus
|
|
94
|
+
// from the prompt, while a scrollback line stays visible without covering anything.
|
|
95
|
+
ctx.ui?.notify(lines.map((line) => "[arnative] model-heal: " + line).join("\n"), "info");
|
|
96
96
|
} catch {
|
|
97
97
|
return;
|
|
98
98
|
}
|
|
99
|
-
if (widgetTimer) clearTimeout(widgetTimer);
|
|
100
|
-
widgetTimer = setTimeout(() => {
|
|
101
|
-
widgetTimer = undefined;
|
|
102
|
-
try {
|
|
103
|
-
ui?.setWidget?.("model-heal", undefined);
|
|
104
|
-
} catch {
|
|
105
|
-
// session replaced while the widget was up
|
|
106
|
-
}
|
|
107
|
-
}, WIDGET_MS);
|
|
108
99
|
}
|
|
109
100
|
|
|
110
101
|
async function apply(ctx: ExtensionContext, label: string, result: HealResult): Promise<void> {
|
|
@@ -165,6 +156,14 @@ export default function registerModelHeal(pi: ExtensionAPI): void {
|
|
|
165
156
|
runFlags(ctx);
|
|
166
157
|
}, DEBOUNCE_MS);
|
|
167
158
|
});
|
|
159
|
+
// A missing models.json throws ENOENT synchronously (caught below), but lock
|
|
160
|
+
// errors (EPERM while a write holds the file) arrive as an async "error" event
|
|
161
|
+
// that no try/catch can intercept: without this handler that event is an
|
|
162
|
+
// uncaughtException and pi exits. Losing the watcher is fine — a later
|
|
163
|
+
// session_start retries it.
|
|
164
|
+
watcher.on("error", () => {
|
|
165
|
+
stopWatcher();
|
|
166
|
+
});
|
|
168
167
|
} catch {
|
|
169
168
|
// models.json missing or not watchable
|
|
170
169
|
}
|
|
@@ -218,8 +217,6 @@ export default function registerModelHeal(pi: ExtensionAPI): void {
|
|
|
218
217
|
pi.on("session_shutdown", () => {
|
|
219
218
|
cancelManualHeal();
|
|
220
219
|
stopWatcher();
|
|
221
|
-
if (widgetTimer) clearTimeout(widgetTimer);
|
|
222
|
-
widgetTimer = undefined;
|
|
223
220
|
});
|
|
224
221
|
|
|
225
222
|
registerCommands(pi, (_args, ctx) => healNow(ctx));
|
|
@@ -0,0 +1,638 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transcript render cache — keep 200k–1M token sessions responsive in pi's TUI.
|
|
3
|
+
*
|
|
4
|
+
* Why: `pi-tui`'s `renderLayoutFrame` allocates a fresh frame cache on every redraw,
|
|
5
|
+
* so `chatContainer.render(width)` re-renders every message and tool box from the start
|
|
6
|
+
* of the session on every streaming delta, spinner tick, or editor keystroke.
|
|
7
|
+
*
|
|
8
|
+
* How:
|
|
9
|
+
* - Known, settled transcript children inside `chatContainer` cache their `render(width)` output
|
|
10
|
+
* and reuse it until `width` changes, `rows` changes (for expanded tool boxes), the
|
|
11
|
+
* session/model resets, or the component mutates (`invalidate`, `updateContent`,
|
|
12
|
+
* `updateDisplay`, `setExpanded`, `handleMouse`, `SCROLL_OFFSET`, etc.).
|
|
13
|
+
* - Active components (`isStreaming`, `isPartial`, `argsPending`, `status === "running"`,
|
|
14
|
+
* active thinking dot animation, or active hold-scroll) always render fresh, while all
|
|
15
|
+
* earlier settled history hits the per-child cache in O(1).
|
|
16
|
+
* - Known Pi transcript components use tracked mutation methods. Custom and unknown
|
|
17
|
+
* components always render fresh because their nested mutations may not notify Pi.
|
|
18
|
+
* - When every child is known and settled, the container checks child state, then
|
|
19
|
+
* reuses its cached `lines` and `mouseLayout` without rebuilding the combined array.
|
|
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
|
|
22
|
+
* patches and sits outside `tools.ts` / `timestamps.ts` render wrappers.
|
|
23
|
+
*/
|
|
24
|
+
import {
|
|
25
|
+
AssistantMessageComponent,
|
|
26
|
+
BashExecutionComponent,
|
|
27
|
+
BranchSummaryMessageComponent,
|
|
28
|
+
CompactionSummaryMessageComponent,
|
|
29
|
+
InteractiveMode,
|
|
30
|
+
ToolExecutionComponent,
|
|
31
|
+
UserMessageComponent,
|
|
32
|
+
type ExtensionAPI,
|
|
33
|
+
} from "@earendil-works/pi-coding-agent";
|
|
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, loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
|
|
41
|
+
|
|
42
|
+
/** Stored exactly as the picker shows them; `"On"` is the default. */
|
|
43
|
+
export const RENDER_CACHE_CHOICES = ["On", "Off"] as const;
|
|
44
|
+
export type RenderCacheChoice = (typeof RENDER_CACHE_CHOICES)[number];
|
|
45
|
+
export const DEFAULT_RENDER_CACHE: RenderCacheChoice = "On";
|
|
46
|
+
|
|
47
|
+
const RENDER_CACHE_CONFIG_KEY = Symbol.for("pi-arnative.renderCache");
|
|
48
|
+
const RENDER_CACHE_STATE_KEY = Symbol.for("pi-arnative.renderCacheState");
|
|
49
|
+
const INSTANCE_WRAP_KEY = Symbol.for("pi-arnative.renderCacheWrapped");
|
|
50
|
+
const INSTANCE_ORIG_KEY = Symbol.for("pi-arnative.renderCacheOriginals");
|
|
51
|
+
|
|
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
|
+
interface ChildMeta {
|
|
58
|
+
version: number;
|
|
59
|
+
scrollOffset: number;
|
|
60
|
+
expanded: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface ChildCacheEntry {
|
|
64
|
+
width: number;
|
|
65
|
+
rows: number;
|
|
66
|
+
epoch: number;
|
|
67
|
+
version: number;
|
|
68
|
+
scrollOffset: number;
|
|
69
|
+
expanded: boolean;
|
|
70
|
+
lines: string[];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface ContainerCacheEntry {
|
|
74
|
+
width: number;
|
|
75
|
+
rows: number;
|
|
76
|
+
epoch: number;
|
|
77
|
+
version: number;
|
|
78
|
+
hasExpanded: boolean;
|
|
79
|
+
children: unknown[];
|
|
80
|
+
childMeta: ChildMeta[];
|
|
81
|
+
lines: string[];
|
|
82
|
+
mouseChildren: Array<{ component: unknown; height: number }>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const MAX_WIDTH_ENTRIES = 3;
|
|
86
|
+
|
|
87
|
+
// Exact prototypes exclude extension subclasses with unknown render/invalidation behavior.
|
|
88
|
+
const CACHEABLE_CHILD_PROTOTYPES = new Set<object>([
|
|
89
|
+
AssistantMessageComponent.prototype,
|
|
90
|
+
BashExecutionComponent.prototype,
|
|
91
|
+
BranchSummaryMessageComponent.prototype,
|
|
92
|
+
CompactionSummaryMessageComponent.prototype,
|
|
93
|
+
ToolExecutionComponent.prototype,
|
|
94
|
+
UserMessageComponent.prototype,
|
|
95
|
+
Text.prototype,
|
|
96
|
+
]);
|
|
97
|
+
|
|
98
|
+
function isCacheableChild(child: unknown): boolean {
|
|
99
|
+
return !!child && typeof child === "object" && CACHEABLE_CHILD_PROTOTYPES.has(Object.getPrototypeOf(child));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface RenderCacheState {
|
|
103
|
+
epoch: number;
|
|
104
|
+
versions: WeakMap<object, number>;
|
|
105
|
+
childCache: WeakMap<object, ChildCacheEntry[]>;
|
|
106
|
+
containerCache: WeakMap<object, ContainerCacheEntry[]>;
|
|
107
|
+
/** Incremented on every cache hit/miss when needed by diagnostics/self-checks. */
|
|
108
|
+
stats: { containerHits: number; childHits: number; childRenders: number };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function getCacheState(): RenderCacheState {
|
|
112
|
+
const g = globalThis as Record<symbol, unknown>;
|
|
113
|
+
if (!g[RENDER_CACHE_STATE_KEY]) {
|
|
114
|
+
g[RENDER_CACHE_STATE_KEY] = {
|
|
115
|
+
epoch: 0,
|
|
116
|
+
versions: new WeakMap(),
|
|
117
|
+
childCache: new WeakMap(),
|
|
118
|
+
containerCache: new WeakMap(),
|
|
119
|
+
stats: { containerHits: 0, childHits: 0, childRenders: 0 },
|
|
120
|
+
} satisfies RenderCacheState;
|
|
121
|
+
}
|
|
122
|
+
return g[RENDER_CACHE_STATE_KEY] as RenderCacheState;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Current Render cache mode (`"On"` by default). */
|
|
126
|
+
export function activeRenderCache(): RenderCacheChoice {
|
|
127
|
+
const stored =
|
|
128
|
+
(globalThis as Record<symbol, unknown>)[RENDER_CACHE_CONFIG_KEY] ??
|
|
129
|
+
loadChoice(RENDER_CACHE_KEY, RENDER_CACHE_CHOICES);
|
|
130
|
+
return RENDER_CACHE_CHOICES.includes(stored as RenderCacheChoice)
|
|
131
|
+
? (stored as RenderCacheChoice)
|
|
132
|
+
: DEFAULT_RENDER_CACHE;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Update the Render cache choice and drop stale cached frames. */
|
|
136
|
+
export function setRenderCache(choice: RenderCacheChoice): void {
|
|
137
|
+
(globalThis as Record<symbol, unknown>)[RENDER_CACHE_CONFIG_KEY] = choice;
|
|
138
|
+
saveChoice(RENDER_CACHE_KEY, choice);
|
|
139
|
+
clearRenderCache();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Drop all cached lines (e.g. on `/reload`, session switch, or model switch). */
|
|
143
|
+
export function clearRenderCache(): void {
|
|
144
|
+
const state = getCacheState();
|
|
145
|
+
state.epoch += 1;
|
|
146
|
+
state.childCache = new WeakMap();
|
|
147
|
+
state.containerCache = new WeakMap();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function findWidthEntry<T extends { width: number }>(
|
|
151
|
+
list: T[] | undefined,
|
|
152
|
+
width: number,
|
|
153
|
+
valid: (entry: T) => boolean,
|
|
154
|
+
): T | undefined {
|
|
155
|
+
if (!list) return undefined;
|
|
156
|
+
for (let i = list.length - 1; i >= 0; i--) {
|
|
157
|
+
const entry = list[i]!;
|
|
158
|
+
if (entry.width !== width || !valid(entry)) continue;
|
|
159
|
+
if (i !== list.length - 1) {
|
|
160
|
+
list.splice(i, 1);
|
|
161
|
+
list.push(entry);
|
|
162
|
+
}
|
|
163
|
+
return entry;
|
|
164
|
+
}
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function putWidthEntry<T extends { width: number }>(
|
|
169
|
+
map: WeakMap<object, T[]>,
|
|
170
|
+
key: object,
|
|
171
|
+
entry: T,
|
|
172
|
+
keepValid: (item: T) => boolean,
|
|
173
|
+
): void {
|
|
174
|
+
const prev = map.get(key);
|
|
175
|
+
const next = prev ? prev.filter((item) => item.width !== entry.width && keepValid(item)) : [];
|
|
176
|
+
next.push(entry);
|
|
177
|
+
if (next.length > MAX_WIDTH_ENTRIES) next.shift();
|
|
178
|
+
map.set(key, next);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function bumpVersion(comp: unknown): void {
|
|
182
|
+
if (!comp || typeof comp !== "object") return;
|
|
183
|
+
const state = getCacheState();
|
|
184
|
+
state.versions.set(comp, (state.versions.get(comp) ?? 0) + 1);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function terminalRows(): number {
|
|
188
|
+
return process.stdout?.rows || 28;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** True when a transcript component is currently animating, streaming, or hold-scrolling. */
|
|
192
|
+
export function isDynamicChild(child: unknown): boolean {
|
|
193
|
+
if (!child || typeof child !== "object") return false;
|
|
194
|
+
const c = child as Record<string | symbol, unknown>;
|
|
195
|
+
if (c.isStreaming === true) return true;
|
|
196
|
+
if (c.isPartial === true || c.argsPending === true) return true;
|
|
197
|
+
if (c.status === "running") return true;
|
|
198
|
+
if (c[SCROLL_HOLD_KEY] !== undefined) return true;
|
|
199
|
+
const thinking = (globalThis as Record<symbol, unknown>)[THINKING_STATE_KEY] as
|
|
200
|
+
| { active?: Set<object> }
|
|
201
|
+
| undefined;
|
|
202
|
+
if (thinking?.active?.has(child)) return true;
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
type AnyFn = (...args: any[]) => any;
|
|
207
|
+
type MarkedWrap = AnyFn & { [INSTANCE_WRAP_KEY]?: true };
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Wrap an instance method without touching the prototype chain, so prototype-level
|
|
211
|
+
* patches from sibling extensions (`tools.ts`, `timestamps.ts`, `section-headers.ts`,
|
|
212
|
+
* `ui-render-tweaks.ts`) continue to run and reinstall cleanly across `/reload`.
|
|
213
|
+
*/
|
|
214
|
+
function wrapInstanceMethod(
|
|
215
|
+
obj: Record<string | symbol, any>,
|
|
216
|
+
key: string,
|
|
217
|
+
build: (callNext: (self: any, args: unknown[]) => unknown) => AnyFn,
|
|
218
|
+
): void {
|
|
219
|
+
let originals = Object.hasOwn(obj, INSTANCE_ORIG_KEY)
|
|
220
|
+
? (obj[INSTANCE_ORIG_KEY] as Record<string, AnyFn>)
|
|
221
|
+
: undefined;
|
|
222
|
+
if (!originals) {
|
|
223
|
+
originals = {};
|
|
224
|
+
Object.defineProperty(obj, INSTANCE_ORIG_KEY, { value: originals, configurable: true });
|
|
225
|
+
}
|
|
226
|
+
const desc = Object.getOwnPropertyDescriptor(obj, key);
|
|
227
|
+
if (desc && typeof desc.value === "function" && !(desc.value as MarkedWrap)[INSTANCE_WRAP_KEY] && !Object.hasOwn(originals, key)) {
|
|
228
|
+
originals[key] = desc.value as AnyFn;
|
|
229
|
+
}
|
|
230
|
+
const callNext = (self: any, args: unknown[]): unknown => {
|
|
231
|
+
const own = Object.hasOwn(originals!, key) ? originals![key] : undefined;
|
|
232
|
+
const fn = own ?? Object.getPrototypeOf(self)?.[key];
|
|
233
|
+
return typeof fn === "function" ? fn.apply(self, args) : undefined;
|
|
234
|
+
};
|
|
235
|
+
const wrapped = build(callNext) as MarkedWrap;
|
|
236
|
+
wrapped[INSTANCE_WRAP_KEY] = true;
|
|
237
|
+
obj[key] = wrapped;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const CHILD_MUTATORS = [
|
|
241
|
+
"invalidate",
|
|
242
|
+
"addChild",
|
|
243
|
+
"removeChild",
|
|
244
|
+
"clear",
|
|
245
|
+
"updateContent",
|
|
246
|
+
"updateDisplay",
|
|
247
|
+
"updateArgs",
|
|
248
|
+
"updateResult",
|
|
249
|
+
"markExecutionStarted",
|
|
250
|
+
"setArgsComplete",
|
|
251
|
+
"setExpanded",
|
|
252
|
+
"setShowImages",
|
|
253
|
+
"setImageWidthCells",
|
|
254
|
+
"setOutputPad",
|
|
255
|
+
"setHideThinkingBlock",
|
|
256
|
+
"setHiddenThinkingLabel",
|
|
257
|
+
"setText",
|
|
258
|
+
"setCustomBgFn",
|
|
259
|
+
"rebuild",
|
|
260
|
+
"appendOutput",
|
|
261
|
+
"setComplete",
|
|
262
|
+
] as const;
|
|
263
|
+
|
|
264
|
+
// Per-module-load tracking so `/reload` reinstalls fresh wrappers once per object.
|
|
265
|
+
const hookedContainers = new WeakSet<object>();
|
|
266
|
+
const hookedChildren = new WeakSet<object>();
|
|
267
|
+
|
|
268
|
+
function attachChildHooks(child: unknown): void {
|
|
269
|
+
if (!child || typeof child !== "object" || !isCacheableChild(child) || hookedChildren.has(child)) return;
|
|
270
|
+
hookedChildren.add(child);
|
|
271
|
+
const obj = child as Record<string | symbol, any>;
|
|
272
|
+
for (const method of CHILD_MUTATORS) {
|
|
273
|
+
if (typeof obj[method] !== "function") continue;
|
|
274
|
+
wrapInstanceMethod(obj, method, (callNext) => function (this: any, ...args: unknown[]) {
|
|
275
|
+
bumpVersion(this);
|
|
276
|
+
return callNext(this, args);
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
for (const inputMethod of ["handleMouse", "handleInput"] as const) {
|
|
280
|
+
if (typeof obj[inputMethod] !== "function") continue;
|
|
281
|
+
wrapInstanceMethod(obj, inputMethod, (callNext) => function (this: any, ...args: unknown[]) {
|
|
282
|
+
const res = callNext(this, args);
|
|
283
|
+
if (inputMethod === "handleInput" || res !== undefined) bumpVersion(this);
|
|
284
|
+
return res;
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export interface ChatContainerLike {
|
|
290
|
+
children: unknown[];
|
|
291
|
+
mouseLayout?: { width: number; children: Array<{ component: unknown; height: number }> };
|
|
292
|
+
render(width: number): string[];
|
|
293
|
+
invalidate?: () => void;
|
|
294
|
+
addChild?: (component: unknown) => void;
|
|
295
|
+
removeChild?: (component: unknown) => void;
|
|
296
|
+
clear?: () => void;
|
|
297
|
+
handleMouse?: (event: unknown) => unknown;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function renderCachedChatContainer(
|
|
301
|
+
container: ChatContainerLike,
|
|
302
|
+
width: number,
|
|
303
|
+
callNextRender: (self: any, args: unknown[]) => unknown,
|
|
304
|
+
): string[] {
|
|
305
|
+
if (activeRenderCache() !== "On") {
|
|
306
|
+
return callNextRender(container, [width]) as string[];
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const state = getCacheState();
|
|
310
|
+
const children = Array.isArray(container.children) ? container.children : [];
|
|
311
|
+
const rows = terminalRows();
|
|
312
|
+
const containerVer = state.versions.get(container) ?? 0;
|
|
313
|
+
|
|
314
|
+
const cached = findWidthEntry(
|
|
315
|
+
state.containerCache.get(container),
|
|
316
|
+
width,
|
|
317
|
+
(entry) =>
|
|
318
|
+
(!entry.hasExpanded || entry.rows === rows) &&
|
|
319
|
+
entry.epoch === state.epoch &&
|
|
320
|
+
entry.version === containerVer &&
|
|
321
|
+
entry.children.length === children.length,
|
|
322
|
+
);
|
|
323
|
+
if (cached) {
|
|
324
|
+
let allClean = true;
|
|
325
|
+
for (let i = 0; i < children.length; i++) {
|
|
326
|
+
const child = children[i];
|
|
327
|
+
if (child !== cached.children[i] || !isCacheableChild(child) || isDynamicChild(child)) {
|
|
328
|
+
allClean = false;
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
const cObj = child && typeof child === "object" ? (child as Record<string | symbol, unknown>) : null;
|
|
332
|
+
const meta = cached.childMeta[i]!;
|
|
333
|
+
if (
|
|
334
|
+
meta.version !== (cObj ? (state.versions.get(cObj) ?? 0) : 0) ||
|
|
335
|
+
meta.scrollOffset !== (cObj ? Number(cObj[SCROLL_OFFSET_KEY] ?? 0) : 0) ||
|
|
336
|
+
meta.expanded !== Boolean(cObj?.expanded)
|
|
337
|
+
) {
|
|
338
|
+
allClean = false;
|
|
339
|
+
break;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (allClean) {
|
|
343
|
+
state.stats.containerHits += 1;
|
|
344
|
+
container.mouseLayout = { width, children: cached.mouseChildren };
|
|
345
|
+
return cached.lines;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const lines: string[] = [];
|
|
350
|
+
const mouseChildren: Array<{ component: unknown; height: number }> = [];
|
|
351
|
+
const snapshot: unknown[] = new Array(children.length);
|
|
352
|
+
const childMeta: ChildMeta[] = new Array(children.length);
|
|
353
|
+
let allChildrenCacheable = true;
|
|
354
|
+
let hasExpanded = false;
|
|
355
|
+
|
|
356
|
+
for (let i = 0; i < children.length; i++) {
|
|
357
|
+
const child = children[i] as { render?: (w: number) => string[] } & Record<string | symbol, unknown>;
|
|
358
|
+
snapshot[i] = child;
|
|
359
|
+
if (!child || typeof child.render !== "function") {
|
|
360
|
+
childMeta[i] = { version: 0, scrollOffset: 0, expanded: false };
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
attachChildHooks(child);
|
|
364
|
+
|
|
365
|
+
const isObj = typeof child === "object";
|
|
366
|
+
const ver = isObj ? (state.versions.get(child) ?? 0) : 0;
|
|
367
|
+
const scrollOffset = isObj ? Number(child[SCROLL_OFFSET_KEY] ?? 0) : 0;
|
|
368
|
+
const expanded = Boolean(isObj && child.expanded);
|
|
369
|
+
if (expanded) hasExpanded = true;
|
|
370
|
+
childMeta[i] = { version: ver, scrollOffset, expanded };
|
|
371
|
+
|
|
372
|
+
let childLines: string[];
|
|
373
|
+
if (!isCacheableChild(child) || isDynamicChild(child)) {
|
|
374
|
+
allChildrenCacheable = false;
|
|
375
|
+
state.stats.childRenders += 1;
|
|
376
|
+
childLines = child.render(width);
|
|
377
|
+
} else {
|
|
378
|
+
const hit = isObj
|
|
379
|
+
? findWidthEntry(
|
|
380
|
+
state.childCache.get(child),
|
|
381
|
+
width,
|
|
382
|
+
(entry) =>
|
|
383
|
+
entry.epoch === state.epoch &&
|
|
384
|
+
entry.version === ver &&
|
|
385
|
+
entry.scrollOffset === scrollOffset &&
|
|
386
|
+
entry.expanded === expanded &&
|
|
387
|
+
(!expanded || entry.rows === rows),
|
|
388
|
+
)
|
|
389
|
+
: undefined;
|
|
390
|
+
if (hit) {
|
|
391
|
+
state.stats.childHits += 1;
|
|
392
|
+
childLines = hit.lines;
|
|
393
|
+
} else {
|
|
394
|
+
state.stats.childRenders += 1;
|
|
395
|
+
childLines = child.render(width);
|
|
396
|
+
if (isObj) {
|
|
397
|
+
putWidthEntry(
|
|
398
|
+
state.childCache,
|
|
399
|
+
child,
|
|
400
|
+
{
|
|
401
|
+
width,
|
|
402
|
+
rows,
|
|
403
|
+
epoch: state.epoch,
|
|
404
|
+
version: ver,
|
|
405
|
+
scrollOffset,
|
|
406
|
+
expanded,
|
|
407
|
+
lines: childLines,
|
|
408
|
+
},
|
|
409
|
+
(entry) =>
|
|
410
|
+
entry.epoch === state.epoch &&
|
|
411
|
+
entry.version === ver &&
|
|
412
|
+
entry.scrollOffset === scrollOffset &&
|
|
413
|
+
entry.expanded === expanded,
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
mouseChildren.push({ component: child, height: childLines.length });
|
|
420
|
+
for (let j = 0; j < childLines.length; j++) {
|
|
421
|
+
lines.push(childLines[j]!);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
container.mouseLayout = { width, children: mouseChildren };
|
|
426
|
+
if (allChildrenCacheable) {
|
|
427
|
+
putWidthEntry(
|
|
428
|
+
state.containerCache,
|
|
429
|
+
container,
|
|
430
|
+
{
|
|
431
|
+
width,
|
|
432
|
+
rows,
|
|
433
|
+
epoch: state.epoch,
|
|
434
|
+
version: containerVer,
|
|
435
|
+
hasExpanded,
|
|
436
|
+
children: snapshot,
|
|
437
|
+
childMeta,
|
|
438
|
+
lines,
|
|
439
|
+
mouseChildren,
|
|
440
|
+
},
|
|
441
|
+
(entry) => entry.epoch === state.epoch && entry.version === containerVer,
|
|
442
|
+
);
|
|
443
|
+
} else {
|
|
444
|
+
state.containerCache.delete(container);
|
|
445
|
+
}
|
|
446
|
+
return lines;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Attach render caching to a `chatContainer` instance (idempotent per module load, reload-safe). */
|
|
450
|
+
export function attachChatContainer(container: unknown): void {
|
|
451
|
+
if (!container || typeof container !== "object" || hookedContainers.has(container)) return;
|
|
452
|
+
hookedContainers.add(container);
|
|
453
|
+
const obj = container as Record<string | symbol, any>;
|
|
454
|
+
|
|
455
|
+
if (typeof obj.render === "function") {
|
|
456
|
+
wrapInstanceMethod(obj, "render", (callNext) => function (this: ChatContainerLike, width: number): string[] {
|
|
457
|
+
return renderCachedChatContainer(this, width, callNext);
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
for (const method of ["addChild", "removeChild", "clear"] as const) {
|
|
461
|
+
if (typeof obj[method] !== "function") continue;
|
|
462
|
+
wrapInstanceMethod(obj, method, (callNext) => function (this: any, ...args: unknown[]) {
|
|
463
|
+
bumpVersion(this);
|
|
464
|
+
if (method === "addChild") attachChildHooks(args[0]);
|
|
465
|
+
return callNext(this, args);
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
if (typeof obj.invalidate === "function") {
|
|
469
|
+
wrapInstanceMethod(obj, "invalidate", (callNext) => function (this: any, ...args: unknown[]) {
|
|
470
|
+
bumpVersion(this);
|
|
471
|
+
if (Array.isArray(this.children)) {
|
|
472
|
+
for (const child of this.children) bumpVersion(child);
|
|
473
|
+
}
|
|
474
|
+
return callNext(this, args);
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
if (typeof obj.handleMouse === "function") {
|
|
478
|
+
wrapInstanceMethod(obj, "handleMouse", (callNext) => function (this: any, ...args: unknown[]) {
|
|
479
|
+
const res = callNext(this, args);
|
|
480
|
+
if (res !== undefined) bumpVersion(this);
|
|
481
|
+
return res;
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// Install InteractiveMode hooks so `this.chatContainer` is attached on startup,
|
|
487
|
+
// `/reload`, session switch, and any incoming chat/tool event.
|
|
488
|
+
if (InteractiveMode?.prototype) {
|
|
489
|
+
const modeProto = InteractiveMode.prototype as unknown as Record<string, unknown>;
|
|
490
|
+
const hookPoints = [
|
|
491
|
+
"init",
|
|
492
|
+
"handleReloadCommand",
|
|
493
|
+
"renderSessionContext",
|
|
494
|
+
"rebuildChatFromMessages",
|
|
495
|
+
"addMessageToChat",
|
|
496
|
+
"handleEvent",
|
|
497
|
+
"updateThinkingBlockVisibility",
|
|
498
|
+
] as const;
|
|
499
|
+
for (const method of hookPoints) {
|
|
500
|
+
if (typeof modeProto[method] !== "function") continue;
|
|
501
|
+
patchOnce(modeProto, method, (orig) => function (this: { chatContainer?: unknown }, ...args: unknown[]) {
|
|
502
|
+
attachChatContainer(this.chatContainer);
|
|
503
|
+
return orig.apply(this, args);
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
export default function registerRenderCache(pi: ExtensionAPI): void {
|
|
509
|
+
pi.on("session_start", async () => {
|
|
510
|
+
clearRenderCache();
|
|
511
|
+
});
|
|
512
|
+
pi.on("model_select", async () => {
|
|
513
|
+
clearRenderCache();
|
|
514
|
+
});
|
|
515
|
+
pi.on("session_compact", async () => {
|
|
516
|
+
clearRenderCache();
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// Self-check: `node extensions/render-cache.ts`
|
|
521
|
+
if (isMain(import.meta.url)) {
|
|
522
|
+
const fixture = mkdtempSync(join(tmpdir(), "arnative-rendercache-"));
|
|
523
|
+
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
524
|
+
delete (globalThis as Record<symbol, unknown>)[RENDER_CACHE_CONFIG_KEY];
|
|
525
|
+
resetPresetCache();
|
|
526
|
+
|
|
527
|
+
// Choice persistence & default.
|
|
528
|
+
assert(activeRenderCache() === "On", "the default is On");
|
|
529
|
+
setRenderCache("Off");
|
|
530
|
+
assert(activeRenderCache() === "Off", "Off persists immediately");
|
|
531
|
+
assert(loadChoice(RENDER_CACHE_KEY, RENDER_CACHE_CHOICES) === "Off", "Off survives reload from disk");
|
|
532
|
+
setRenderCache("On");
|
|
533
|
+
assert(activeRenderCache() === "On", "switching back to On restores caching");
|
|
534
|
+
|
|
535
|
+
// Use a known Text prototype to exercise cache policy without loading a theme.
|
|
536
|
+
function makeChild(text: string) {
|
|
537
|
+
const child = Object.assign(new Text(text, 0, 0), { renders: 0, isStreaming: false, isPartial: false, expanded: false });
|
|
538
|
+
const setText = child.setText.bind(child);
|
|
539
|
+
child.setText = (next: string): void => { text = next; setText(next); };
|
|
540
|
+
const result = Object.assign(child, {
|
|
541
|
+
handleInput(key: string): void { child.setText(`${text}:${key}`); },
|
|
542
|
+
});
|
|
543
|
+
result.render = (width: number): string[] => { result.renders += 1; return [`${text}@${width}`]; };
|
|
544
|
+
return result as typeof result & { [key: symbol]: unknown };
|
|
545
|
+
}
|
|
546
|
+
type FakeChild = ReturnType<typeof makeChild>;
|
|
547
|
+
class FakeContainer implements ChatContainerLike {
|
|
548
|
+
children: FakeChild[] = [];
|
|
549
|
+
mouseLayout?: { width: number; children: Array<{ component: unknown; height: number }> };
|
|
550
|
+
addChild(c: FakeChild): void {
|
|
551
|
+
this.children.push(c);
|
|
552
|
+
}
|
|
553
|
+
invalidate(): void {
|
|
554
|
+
for (const c of this.children) c.invalidate();
|
|
555
|
+
}
|
|
556
|
+
render(width: number): string[] {
|
|
557
|
+
const lines: string[] = [];
|
|
558
|
+
const mouseChildren: Array<{ component: unknown; height: number }> = [];
|
|
559
|
+
for (const c of this.children) {
|
|
560
|
+
const out = c.render(width);
|
|
561
|
+
mouseChildren.push({ component: c, height: out.length });
|
|
562
|
+
lines.push(...out);
|
|
563
|
+
}
|
|
564
|
+
this.mouseLayout = { width, children: mouseChildren };
|
|
565
|
+
return lines;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const container = new FakeContainer();
|
|
570
|
+
const c1 = makeChild("msg1");
|
|
571
|
+
const c2 = makeChild("msg2");
|
|
572
|
+
container.addChild(c1);
|
|
573
|
+
container.addChild(c2);
|
|
574
|
+
attachChatContainer(container);
|
|
575
|
+
|
|
576
|
+
const out1 = container.render(80);
|
|
577
|
+
assert(out1.join(",") === "msg1@80,msg2@80", "first render outputs both children");
|
|
578
|
+
assert(c1.renders === 1 && c2.renders === 1, "first render calls each child once");
|
|
579
|
+
|
|
580
|
+
// Second render at same width hits whole container cache: zero child.render calls.
|
|
581
|
+
const out2 = container.render(80);
|
|
582
|
+
assert(out2 === out1, "whole-container hit returns cached array reference");
|
|
583
|
+
assert(c1.renders === 1 && c2.renders === 1, "container hit skips child renders");
|
|
584
|
+
assert(container.mouseLayout?.children.length === 2, "mouseLayout preserved on container hit");
|
|
585
|
+
|
|
586
|
+
// Streaming child bypasses cache while settled sibling stays cached.
|
|
587
|
+
c2.isStreaming = true;
|
|
588
|
+
c2.setText("streaming");
|
|
589
|
+
const out3 = container.render(80);
|
|
590
|
+
assert(out3.join(",") === "msg1@80,streaming@80", "streaming child updates live");
|
|
591
|
+
assert(c1.renders === 1 && c2.renders === 2, "settled sibling stayed cached while streaming child re-rendered");
|
|
592
|
+
|
|
593
|
+
c2.isStreaming = false;
|
|
594
|
+
const out4 = container.render(80);
|
|
595
|
+
assert(out4.join(",") === "msg1@80,streaming@80", "post-stream render caches final state");
|
|
596
|
+
assert(c1.renders === 1 && c2.renders === 3, "settled after stream renders once then caches");
|
|
597
|
+
container.render(80);
|
|
598
|
+
assert(c1.renders === 1 && c2.renders === 3, "steady state hits container cache again");
|
|
599
|
+
|
|
600
|
+
// Width change renders unseen width; toggling back to previous width hits 2-width LRU in O(1).
|
|
601
|
+
const out5 = container.render(100);
|
|
602
|
+
assert(out5.join(",") === "msg1@100,streaming@100", "width change re-renders at new width");
|
|
603
|
+
assert(c1.renders === 2 && c2.renders === 4, "both re-rendered for new width");
|
|
604
|
+
const out5Back = container.render(80);
|
|
605
|
+
assert(out5Back === out4, "toggling back to prior width hits 2-width container LRU");
|
|
606
|
+
assert(c1.renders === 2 && c2.renders === 4, "toggling back skips child renders");
|
|
607
|
+
container.render(100);
|
|
608
|
+
|
|
609
|
+
// Mutation on one child invalidates only that child.
|
|
610
|
+
c1.setText("edited");
|
|
611
|
+
const out6 = container.render(100);
|
|
612
|
+
assert(out6.join(",") === "edited@100,streaming@100", "mutated child re-renders");
|
|
613
|
+
assert(c1.renders === 3 && c2.renders === 4, "unchanged sibling stayed cached");
|
|
614
|
+
|
|
615
|
+
// handleInput mutation invalidates that child without needing explicit invalidate().
|
|
616
|
+
c1.handleInput("x");
|
|
617
|
+
const out6Input = container.render(100);
|
|
618
|
+
assert(out6Input.join(",") === "edited:x@100,streaming@100", "handleInput invalidates mutated child");
|
|
619
|
+
assert(c1.renders === 4 && c2.renders === 4, "handleInput did not invalidate sibling");
|
|
620
|
+
|
|
621
|
+
// Tool box scroll-offset change invalidates without explicit invalidate().
|
|
622
|
+
c2[SCROLL_OFFSET_KEY] = 5;
|
|
623
|
+
container.render(100);
|
|
624
|
+
assert(c1.renders === 4 && c2.renders === 5, "scrollOffset change invalidates that tool box");
|
|
625
|
+
|
|
626
|
+
// Off mode disables caching completely.
|
|
627
|
+
setRenderCache("Off");
|
|
628
|
+
container.render(100);
|
|
629
|
+
container.render(100);
|
|
630
|
+
assert(c1.renders === 6 && c2.renders === 7, "Off mode renders directly every frame");
|
|
631
|
+
setRenderCache("On");
|
|
632
|
+
|
|
633
|
+
rmSync(fixture, { recursive: true, force: true });
|
|
634
|
+
delete process.env.PI_CODING_AGENT_DIR;
|
|
635
|
+
delete (globalThis as Record<symbol, unknown>)[RENDER_CACHE_CONFIG_KEY];
|
|
636
|
+
resetPresetCache();
|
|
637
|
+
console.log("render-cache.ts self-check OK");
|
|
638
|
+
}
|