@bismawy/pi-arnative 0.6.2 → 0.8.0-rc.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.
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Auto-compact — keep long sessions light without the manual /compact.
3
+ *
4
+ * Why: pi renders the whole transcript on every frame, so the drag a user feels tracks
5
+ * the ABSOLUTE size of the session, not how full the window is. A 1M-window model gets
6
+ * heavy around 200k tokens (a fifth of its window), while a 128k model can run to
7
+ * nearly 100% and let pi's own threshold compaction handle it safely.
8
+ *
9
+ * Two shapes of control, both off until picked in `/arnative` → Auto-compact:
10
+ * - **Smart** maps the context window through a tier table (≥768k→20%, ≥384k→40%,
11
+ * ≥192k→80%, smaller→defer to pi core). Every tier lands the trigger near the same
12
+ * ~200k-token transcript ceiling, and small windows never fire at all — pi's own
13
+ * `compaction.reserveTokens` compaction stays their safety net.
14
+ * - **A manual token budget** (100k–400k) fires at the same absolute size whatever the
15
+ * window, for users who want one number.
16
+ *
17
+ * The trigger is `agent_before_settle` (idle, nothing queued) and fires pi's compaction
18
+ * through `ctx.compact()` — the same machinery and summary as /compact, never mid-run.
19
+ * Pi's own `compaction.reserveTokens` threshold, including per-model overrides, is
20
+ * unaffected; whichever fires first wins.
21
+ */
22
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
23
+ import { mkdtempSync, rmSync } from "node:fs";
24
+ import { tmpdir } from "node:os";
25
+ import { join } from "node:path";
26
+ import { assert, isMain } from "../lib/check.ts";
27
+ import { loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
28
+
29
+ /** Stored exactly as the picker shows them; `Off` disables the trigger entirely. */
30
+ export const AUTO_COMPACT_CHOICES = ["Off", "Smart", "100k", "150k", "200k", "300k", "400k"] as const;
31
+ export type AutoCompactChoice = (typeof AUTO_COMPACT_CHOICES)[number];
32
+ export const DEFAULT_AUTO_COMPACT: AutoCompactChoice = "Off";
33
+ const AUTO_COMPACT_KEY = "autoCompact";
34
+
35
+ /** Smart's tier table, first match wins. `null` defers the window to pi's own
36
+ * compaction — the "100%" tier, where the current behavior is already safe. */
37
+ const SMART_TIERS: ReadonlyArray<{ minWindow: number; percent: number | null }> = [
38
+ { minWindow: 786432, percent: 20 }, // ≥768k: a 1M window triggers at ~200k tokens
39
+ { minWindow: 393216, percent: 40 }, // 384k–768k: a 512k window triggers at ~205k
40
+ { minWindow: 196608, percent: 80 }, // 192k–384k: a 256k window triggers at ~205k
41
+ { minWindow: 0, percent: null }, // below 192k (128k models): pi core stays in charge
42
+ ];
43
+
44
+ /** The Smart percent for a context window, or null when the window defers to pi core. */
45
+ export function smartPercent(contextWindow: number): number | null {
46
+ const tier = SMART_TIERS.find((t) => contextWindow >= t.minWindow);
47
+ return tier?.percent ?? null;
48
+ }
49
+
50
+ // Active choice on globalThis so the `/arnative` picker (a second module instance, see
51
+ // animations.ts) and this module's event handlers agree without sharing memo caches.
52
+ const AUTO_COMPACT_CONFIG_KEY = Symbol.for("pi-arnative.autoCompact");
53
+
54
+ export function activeAutoCompact(): AutoCompactChoice {
55
+ const stored =
56
+ (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY] ??
57
+ loadChoice(AUTO_COMPACT_KEY, AUTO_COMPACT_CHOICES);
58
+ return AUTO_COMPACT_CHOICES.includes(stored as AutoCompactChoice) ? (stored as AutoCompactChoice) : DEFAULT_AUTO_COMPACT;
59
+ }
60
+
61
+ /** The trigger threshold in context tokens for the given window, or null when the
62
+ * choice is off or Smart defers this window to pi's own compaction. */
63
+ export function activeAutoCompactThreshold(contextWindow: number): number | null {
64
+ const choice = activeAutoCompact();
65
+ if (choice === "Off") return null;
66
+ if (choice === "Smart") {
67
+ const percent = smartPercent(contextWindow);
68
+ return percent === null ? null : Math.round((contextWindow * percent) / 100);
69
+ }
70
+ return Number.parseInt(choice, 10) * 1000;
71
+ }
72
+
73
+ /** Pick a choice and persist it (the `/arnative` → Auto-compact rows call this). */
74
+ export function setAutoCompact(choice: AutoCompactChoice): void {
75
+ (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY] = choice;
76
+ saveChoice(AUTO_COMPACT_KEY, choice);
77
+ }
78
+
79
+ /** Session-scoped trigger state. Module-local: only this module's registrar mutates it. */
80
+ export interface AutoCompactState {
81
+ /** A compaction this module triggered has not finished yet. */
82
+ inFlight: boolean;
83
+ /** Context tokens at the last trigger; null once usage really dropped under the threshold. */
84
+ lastAttemptTokens: number | null;
85
+ /** The last triggered compaction finished, so its effect on usage is visible. */
86
+ attemptSettled: boolean;
87
+ /** Do not trigger while usage stays below this (failure backoff, anti-flap). */
88
+ blockedUntilTokens: number;
89
+ }
90
+
91
+ export function freshAutoCompactState(): AutoCompactState {
92
+ return { inFlight: false, lastAttemptTokens: null, attemptSettled: false, blockedUntilTokens: 0 };
93
+ }
94
+
95
+ /** How much usage must outgrow a previous attempt before it counts as real growth
96
+ * (5% of the threshold, at least 5k tokens). */
97
+ export function growthMargin(thresholdTokens: number): number {
98
+ return Math.max(5000, Math.round(thresholdTokens * 0.05));
99
+ }
100
+
101
+ /** Pure decision for the settle handler: fire pi's compaction now, or wait. */
102
+ export function autoCompactDecision(
103
+ state: AutoCompactState,
104
+ tokens: number | null,
105
+ thresholdTokens: number,
106
+ ): "compact" | "wait" {
107
+ if (tokens === null || tokens < thresholdTokens) return "wait";
108
+ if (state.inFlight) return "wait";
109
+ if (tokens < state.blockedUntilTokens) return "wait";
110
+ // A finished compaction that still left usage at or above the threshold freed too
111
+ // little: wait for real growth instead of re-summarizing every settle.
112
+ if (state.attemptSettled && state.lastAttemptTokens !== null && tokens < state.lastAttemptTokens + growthMargin(thresholdTokens)) {
113
+ return "wait";
114
+ }
115
+ return "compact";
116
+ }
117
+
118
+ /** Usage dropped back under the threshold (the handler's below-threshold branch).
119
+ * A shallow dip — still within the growth margin of the last attempt — keeps the
120
+ * attempt memory, so usage oscillating right at the threshold cannot re-summarize
121
+ * every turn. A real drop forgets the attempt and re-arms the trigger fully. */
122
+ export function rearmAfterDip(state: AutoCompactState, tokens: number, thresholdTokens: number): void {
123
+ if (state.lastAttemptTokens === null || tokens < state.lastAttemptTokens - growthMargin(thresholdTokens)) {
124
+ state.lastAttemptTokens = null;
125
+ state.attemptSettled = false;
126
+ state.blockedUntilTokens = 0;
127
+ }
128
+ }
129
+
130
+ export default function registerAutoCompact(pi: ExtensionAPI): void {
131
+ const state = freshAutoCompactState();
132
+
133
+ pi.on("session_start", async () => {
134
+ // Fresh session (or /reload): backoff and attempt state belonged to the previous branch.
135
+ Object.assign(state, freshAutoCompactState());
136
+ });
137
+
138
+ pi.on("agent_before_settle", async (_event, ctx) => {
139
+ const usage = typeof ctx.getContextUsage === "function" ? ctx.getContextUsage() : undefined;
140
+ const window = usage?.contextWindow;
141
+ if (typeof window !== "number" || window <= 0) return;
142
+ const threshold = activeAutoCompactThreshold(window);
143
+ if (threshold === null) return;
144
+ const tokens = usage.tokens ?? null;
145
+ if (tokens === null) return;
146
+ if (tokens < threshold) {
147
+ rearmAfterDip(state, tokens, threshold);
148
+ return;
149
+ }
150
+ if (autoCompactDecision(state, tokens, threshold) !== "compact") return;
151
+ if (typeof ctx.compact !== "function") return; // older host without the API
152
+ state.inFlight = true;
153
+ state.attemptSettled = false;
154
+ state.lastAttemptTokens = tokens;
155
+ state.blockedUntilTokens = tokens + 1; // anti-flap: re-fire only past this attempt
156
+ ctx.compact();
157
+ });
158
+
159
+ pi.on("session_compact", async () => {
160
+ // Also fires for pi's own compactions; harmless — the flags only matter after a trigger.
161
+ state.inFlight = false;
162
+ state.attemptSettled = true;
163
+ });
164
+
165
+ pi.on("session_compact_failed", async () => {
166
+ if (!state.inFlight) return;
167
+ // A failed (or user-aborted) compaction must not retry-loop at the same usage:
168
+ // wait until usage outgrows the attempt by the growth margin.
169
+ state.inFlight = false;
170
+ state.attemptSettled = true;
171
+ state.blockedUntilTokens = (state.lastAttemptTokens ?? 0) + growthMargin(state.lastAttemptTokens ?? 200000);
172
+ });
173
+ }
174
+
175
+ // Self-check: `node extensions/autocompact.ts`
176
+ if (isMain(import.meta.url)) {
177
+ // The real agent dir must not decide pass/fail, and the test must not touch it.
178
+ const fixture = mkdtempSync(join(tmpdir(), "arnative-autocompact-"));
179
+ process.env.PI_CODING_AGENT_DIR = fixture;
180
+ delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
181
+
182
+ // Choice parsing and persistence.
183
+ assert(activeAutoCompact() === "Off", "the default is off");
184
+ assert(activeAutoCompactThreshold(1_048_576) === null, "off reads as no threshold");
185
+ setAutoCompact("200k");
186
+ assert(activeAutoCompactThreshold(131072) === 200000, "a manual budget ignores the window");
187
+ assert(loadChoice(AUTO_COMPACT_KEY, AUTO_COMPACT_CHOICES) === "200k", "the choice survives a restart (read from disk)");
188
+
189
+ // Smart's tier table: the field examples land where they were asked to.
190
+ assert(smartPercent(131072) === null, "128k defers to pi core (the 100% tier)");
191
+ assert(smartPercent(196607) === null, "just under the 192k tier edge still defers");
192
+ assert(smartPercent(196608) === 80, "the 192k tier edge takes 80%");
193
+ assert(smartPercent(262144) === 80, "256k takes 80%");
194
+ assert(smartPercent(524288) === 40, "512k takes 40%");
195
+ assert(smartPercent(1048576) === 20, "1M takes 20%");
196
+ setAutoCompact("Smart");
197
+ assert(activeAutoCompactThreshold(1048576) === 209715, "Smart on 1M triggers at ~200k tokens");
198
+ assert(activeAutoCompactThreshold(262144) === 209715, "Smart on 256k triggers at ~205k tokens");
199
+ assert(activeAutoCompactThreshold(131072) === null, "Smart on 128k defers to pi core");
200
+ setAutoCompact("Off");
201
+ assert(activeAutoCompactThreshold(1048576) === null, "switching back to off disables the trigger");
202
+
203
+ // Decision table.
204
+ const s = freshAutoCompactState();
205
+ assert(autoCompactDecision(s, null, 200000) === "wait", "no usage estimate: wait");
206
+ assert(autoCompactDecision(s, 199999, 200000) === "wait", "below the threshold: wait");
207
+ assert(autoCompactDecision(s, 200000, 200000) === "compact", "at the threshold with fresh state: compact");
208
+ s.inFlight = true;
209
+ assert(autoCompactDecision(s, 250000, 200000) === "wait", "a compaction is still running: wait");
210
+ s.inFlight = false;
211
+ s.blockedUntilTokens = 260000;
212
+ assert(autoCompactDecision(s, 250000, 200000) === "wait", "below the failure backoff: wait");
213
+ s.blockedUntilTokens = 0;
214
+ s.attemptSettled = true;
215
+ s.lastAttemptTokens = 240000;
216
+ assert(autoCompactDecision(s, 245000, 200000) === "wait", "a settled attempt that freed too little waits for the growth margin");
217
+ assert(autoCompactDecision(s, 250500, 200000) === "compact", "usage outgrew the settled attempt: compact again");
218
+
219
+ // Rearm after a dip: shallow keeps the attempt memory, deep forgets it.
220
+ const r = freshAutoCompactState();
221
+ r.lastAttemptTokens = 200000;
222
+ r.attemptSettled = true;
223
+ r.blockedUntilTokens = 200001;
224
+ rearmAfterDip(r, 195000, 200000);
225
+ assert(r.lastAttemptTokens === 200000, "a shallow dip keeps the attempt memory");
226
+ rearmAfterDip(r, 189000, 200000);
227
+ assert(r.lastAttemptTokens === null && r.attemptSettled === false && r.blockedUntilTokens === 0, "a real drop forgets the attempt and re-arms");
228
+
229
+ // Registered handlers against a fake pi, driven like a Smart session on a 1M model.
230
+ setAutoCompact("Smart");
231
+ const handlers: Record<string, (event: unknown, ctx: unknown) => unknown> = {};
232
+ registerAutoCompact({ on: (name: string, fn: (event: unknown, ctx: unknown) => unknown) => void (handlers[name] = fn) } as never);
233
+ const compactCalls: number[] = [];
234
+ const ctxOf = (tokens: number | null, contextWindow = 1_048_576) => ({
235
+ getContextUsage: () => ({ tokens, contextWindow, percent: tokens === null ? null : (tokens / contextWindow) * 100 }),
236
+ compact: () => compactCalls.push(tokens ?? -1),
237
+ });
238
+
239
+ await handlers.session_start!({}, undefined);
240
+ await handlers.agent_before_settle!({}, ctxOf(210000));
241
+ assert(compactCalls.length === 1 && compactCalls[0] === 210000, "usage at/above the threshold triggers pi's compaction");
242
+ await handlers.agent_before_settle!({}, ctxOf(215000));
243
+ assert(compactCalls.length === 1, "the anti-flap guard blocks an immediate re-trigger");
244
+ await handlers.session_compact!({}, undefined);
245
+ await handlers.agent_before_settle!({}, ctxOf(215000));
246
+ assert(compactCalls.length === 1, "a settled attempt that still sits above the threshold waits for growth");
247
+ await handlers.agent_before_settle!({}, ctxOf(222000));
248
+ assert(compactCalls.length === 2 && compactCalls[1] === 222000, "usage outgrowing the attempt compacts again");
249
+ await handlers.session_compact!({}, undefined); // the compaction that made usage drop
250
+ await handlers.agent_before_settle!({}, ctxOf(60000));
251
+ assert(compactCalls.length === 2, "below the threshold nothing fires");
252
+ await handlers.agent_before_settle!({}, ctxOf(210500));
253
+ assert(compactCalls.length === 3 && compactCalls[2] === 210500, "the next crossing starts a fresh cycle");
254
+
255
+ // Oscillation at the threshold: one compaction per growth margin, not every turn.
256
+ await handlers.session_compact!({}, undefined);
257
+ await handlers.agent_before_settle!({}, ctxOf(208000)); // shallow dip under the threshold
258
+ await handlers.agent_before_settle!({}, ctxOf(211000));
259
+ assert(compactCalls.length === 3, "an oscillation at the threshold does not re-summarize every turn");
260
+ await handlers.agent_before_settle!({}, ctxOf(222000));
261
+ assert(compactCalls.length === 4 && compactCalls[3] === 222000, "real growth past the attempt compacts again");
262
+
263
+ // A failed compaction backs off; session_start clears the backoff for a fresh session.
264
+ await handlers.session_compact_failed!({}, undefined);
265
+ await handlers.agent_before_settle!({}, ctxOf(225000));
266
+ assert(compactCalls.length === 4, "after a failure the backoff holds below attempt + margin");
267
+ await handlers.agent_before_settle!({}, ctxOf(234000));
268
+ assert(compactCalls.length === 5, "and gives way once usage outgrows the failed attempt");
269
+ await handlers.session_compact_failed!({}, undefined);
270
+ await handlers.session_start!({}, undefined);
271
+ await handlers.agent_before_settle!({}, ctxOf(210500));
272
+ assert(compactCalls.length === 6, "a fresh session clears the backoff");
273
+
274
+ // The 128k case from the field: Smart defers the whole window to pi's own
275
+ // compaction — no percent, however close to full, ever fires ours.
276
+ await handlers.session_start!({}, undefined);
277
+ await handlers.agent_before_settle!({}, ctxOf(130000, 131072));
278
+ assert(compactCalls.length === 6, "a 128k window under Smart never triggers: pi core stays in charge");
279
+
280
+ // Older hosts: missing ctx APIs must degrade to a no-op, not throw.
281
+ await handlers.agent_before_settle!({}, { getContextUsage: () => undefined });
282
+ assert(compactCalls.length === 6, "no usage estimate: no trigger");
283
+ // Reset inFlight first, so the missing compact() — not a pending compaction — is what stops it.
284
+ await handlers.session_start!({}, undefined);
285
+ await handlers.agent_before_settle!({}, { getContextUsage: () => ({ tokens: 400000, contextWindow: 1_048_576, percent: 40 }) });
286
+ assert(compactCalls.length === 6, "no ctx.compact on the host: no trigger");
287
+
288
+ // Restore: the next module load starts from the real agent dir and the stored default.
289
+ rmSync(fixture, { recursive: true, force: true });
290
+ delete process.env.PI_CODING_AGENT_DIR;
291
+ delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
292
+ resetPresetCache();
293
+ console.log("autocompact.ts self-check OK");
294
+ }
@@ -599,7 +599,7 @@ function parseOptimizer(raw: string | undefined): string | null {
599
599
  }
600
600
 
601
601
  // Pi's own per-message usage: shown when pi-cache-optimizer has no adapter for the
602
- // provider (a custom one like hark.ts publishes no pi-cache-stats status).
602
+ // provider (a custom one like mytool.ts publishes no pi-cache-stats status).
603
603
  let usageTotals = { inp: 0, read: 0 };
604
604
  export function piCacheHit(): string | null {
605
605
  const total = usageTotals.inp + usageTotals.read;
@@ -1168,6 +1168,11 @@ export default function (pi: ExtensionAPI) {
1168
1168
  armIdleProbe();
1169
1169
  activeToolVerbs.delete(event.toolCallId);
1170
1170
  setWorkingVerb(ctx, currentToolVerb(activeToolVerbs));
1171
+ // A finished edit/write/bash may have changed the tree (or committed it): without
1172
+ // this, the diff stat stays frozen at the turn_start snapshot — a session that
1173
+ // commits inside the turn shows "clean" forever. refreshGit coalesces concurrent
1174
+ // calls (in-flight + one queued), so a burst of tool ends costs at most two runs.
1175
+ void refreshGit(ctx.cwd).then(() => poke());
1171
1176
  });
1172
1177
 
1173
1178
  pi.on("message_update", async (event) => {
@@ -1260,8 +1265,8 @@ export default function (pi: ExtensionAPI) {
1260
1265
 
1261
1266
  // Self-check: `node extensions/footer.ts`
1262
1267
  if (isMain(import.meta.url)) {
1263
- assert(shortenCwd("/run/media/bisma/DATA/Pi/pi-arnative") === "\u2026/Pi/pi-arnative", "cwd inside -> last 2 segments");
1264
- assert(shortenCwd("/home/bisma") === "/home/bisma", "shallow cwd left unchanged");
1268
+ assert(shortenCwd("/run/media/dev/DATA/work/app") === "\u2026/work/app", "cwd inside -> last 2 segments");
1269
+ assert(shortenCwd("/home/dev") === "/home/dev", "shallow cwd left unchanged");
1265
1270
  assert(shortenCwd("D:\\Pi\\a\\pi-arnative") === "D:/\u2026/a/pi-arnative", "long Windows path: drive kept");
1266
1271
  assert(shortenCwd("D:\\Pi\\pi-arnative") === "D:\\Pi\\pi-arnative", "shallow Windows path left unchanged");
1267
1272
  assert(shortenCwd("/a/x/y/z") === "\u2026/y/z", "long path -> tail");
@@ -78,10 +78,31 @@ export function formatTimeBadge(timeStr: string, th: { fg(color: string, text: s
78
78
  // \x1b[0m (full reset), so padding AFTER the reset loses the bubble bg and renders
79
79
  // dark for the rest of the line. Re-apply the bubble bg after every reset and close
80
80
  // it at end of line so it cannot leak. Same pattern as InputBgEditor below.
81
+ //
82
+ // The repair is pure per (line, bgOpen) pair, and pi's Markdown cache hands the render
83
+ // patch the SAME string references frame after frame — so a Map keyed by the source
84
+ // line turns every frame after the first into lookups instead of split/join rebuilds.
85
+ // Only the patched render closure calls this, so module-local state is correct even
86
+ // across /reload (the closure keeps this module instance alive). Reset when the bg
87
+ // code changes (theme switch); past the cap the whole map is dropped, because a
88
+ // session's user lines are far below it and correctness never depends on a hit.
89
+ const BUBBLE_BG_CACHE_MAX = 8192;
90
+ let bubbleBgOpen = "";
91
+ let bubbleBgCache = new Map<string, string>();
92
+
81
93
  export function repairBubbleBg(line: string, bgOpen: string): string {
82
94
  if (!bgOpen || (!line.includes("\x1b[0m") && !line.includes("\x1b[49m"))) return line;
95
+ if (bgOpen !== bubbleBgOpen) {
96
+ bubbleBgOpen = bgOpen;
97
+ bubbleBgCache = new Map();
98
+ }
99
+ const hit = bubbleBgCache.get(line);
100
+ if (hit !== undefined) return hit;
83
101
  const patched = line.split("\x1b[0m").join(`\x1b[0m${bgOpen}`).split("\x1b[49m").join(`\x1b[49m${bgOpen}`);
84
- return patched.endsWith(bgOpen) ? `${patched}\x1b[49m` : patched;
102
+ const result = patched.endsWith(bgOpen) ? `${patched}\x1b[49m` : patched;
103
+ if (bubbleBgCache.size >= BUBBLE_BG_CACHE_MAX) bubbleBgCache.clear();
104
+ bubbleBgCache.set(line, result);
105
+ return result;
85
106
  }
86
107
 
87
108
  /**
@@ -249,6 +270,14 @@ if (isMain(import.meta.url)) {
249
270
  assert(clean.includes(`\x1b[0m${bg}`), "bg re-applied after the reset");
250
271
  assert(clean.endsWith("\x1b[49m"), "bubble bg closed at end of line");
251
272
  assert(repairBubbleBg("plain", "") === "plain", "no bgOpen: unchanged");
273
+
274
+ // memoized repair: a different bg code resets the cache, so nothing repairs
275
+ // against a stale bubble background after a theme switch
276
+ const dirty2 = `${bg}Second\x1b[0m pad \x1b[49m`;
277
+ const otherBg = "\x1b[48;2;1;2;3m";
278
+ assert(repairBubbleBg(dirty2, otherBg).includes(`\x1b[0m${otherBg}`), "a new bg code repairs against that bg");
279
+ assert(repairBubbleBg(dirty2, bg).includes(`\x1b[0m${bg}`), "and back to the previous bg after another reset");
280
+ assert(repairBubbleBg(dirty2, bg) === repairBubbleBg(dirty2, bg), "repeat repair stays stable");
252
281
  assert(ansiBgOpen(null, "userMessageBg") === "", "no theme: empty bgOpen");
253
282
  assert(
254
283
  ansiBgOpen({ bg: (_c, t) => `\x1b[48;2;52;53;61m${t}\x1b[49m` }, "userMessageBg") === "\x1b[48;2;52;53;61m",
@@ -1042,7 +1042,7 @@ if (isMain(import.meta.url)) {
1042
1042
  );
1043
1043
 
1044
1044
  // pi-fff override mode: find/grep re-registered with own renderers, no renderShell
1045
- const fffCall = { render: () => ["\x1b[1mfind \x1b[22m\x1b[36m*.ts in D:/Pi/x\x1b[39m"] };
1045
+ const fffCall = { render: () => ["\x1b[1mfind \x1b[22m\x1b[36m*.ts in /tmp/work\x1b[39m"] };
1046
1046
  const fffRes = { render: () => ["src/a.ts \x1b[2m... (6 more lines)\x1b[22m"] };
1047
1047
  const fffFind = { toolName: "find", toolDefinition: { renderCall: () => fffCall, renderResult: () => fffRes } };
1048
1048
  assert(
@@ -1053,10 +1053,10 @@ if (isMain(import.meta.url)) {
1053
1053
  { content: [{ type: "text", text: "src/a.ts\nsrc/b.ts" }] },
1054
1054
  { expanded: false, isPartial: false },
1055
1055
  th,
1056
- { args: { pattern: "*.ts", path: "D:/Pi/x" }, state: {} },
1056
+ { args: { pattern: "*.ts", path: "/tmp/work" }, state: {} },
1057
1057
  ).render(60);
1058
1058
  assert(fffOut[0].startsWith("╭") && fffOut[fffOut.length - 1].startsWith("╰"), "pi-fff find: result wrapped in a box");
1059
- assert(fffOut.some((l: string) => l.includes("*.ts in D:/Pi/x")), "pi-fff find: renderCall title goes in the box");
1059
+ assert(fffOut.some((l: string) => l.includes("*.ts in /tmp/work")), "pi-fff find: renderCall title goes in the box");
1060
1060
  assert(fffOut.some((l: string) => l.includes("6 more lines")), "pi-fff find: renderResult summary goes in the box");
1061
1061
 
1062
1062
  // pi-fff default mode (`ffgrep`/`fffind`): same renderer shape, different names.
@@ -50,12 +50,19 @@ const activeTheme = () => getActiveTheme<Exclude<ActiveTheme, null>>();
50
50
  // (hardcoded in handleReloadCommand, no auto-hide). Patches Container.render
51
51
  // through the prototype chain (Container is not exported) and drops the whole box on match.
52
52
  const RELOAD_TEXT = "Reloading keybindings, extensions, skills, prompts, themes, and context files...";
53
+ /** The reload box is a fixed 5-child container (2 borders, 2 spacers, one 78-char line), so it
54
+ * renders at most ~9 rows even wrapped. Anything larger cannot be the box, and this predicate
55
+ * runs per frame on every plain Container — including a transcript of tens of thousands of
56
+ * lines, where the substring scan is the single most expensive arnative render patch. */
57
+ const RELOAD_BOX_MAX_LINES = 64;
53
58
  /**
54
59
  * True only for the box itself: border rows, blank spacers and (possibly wrapped) copy of the
55
60
  * message. The patch sits on every plain Container, so a bare substring test would blank a
56
- * whole chat the moment a transcript line mentioned the phrase.
61
+ * whole chat the moment a transcript line mentioned the phrase. Containers larger than
62
+ * {@link RELOAD_BOX_MAX_LINES} are refused before any scanning starts.
57
63
  */
58
64
  export function shouldHideReloadBox(lines: readonly string[]): boolean {
65
+ if (lines.length > RELOAD_BOX_MAX_LINES) return false;
59
66
  if (!lines.some((l) => l.includes("Reloading keybindings"))) return false;
60
67
  const rows = lines.map((l) => stripAnsi(l).trim());
61
68
  return rows.every((r) => r === "" || /^[─-]+$/.test(r) || RELOAD_TEXT.includes(r));
@@ -373,6 +380,10 @@ if (isMain(import.meta.url)) {
373
380
  assert(shouldHideReloadBox(["────", "", " Reloading keybindings, extensions,", " skills, prompts, themes, and context files...", "", "────"]) === true, "wrapped reload box detected");
374
381
  assert(shouldHideReloadBox(["hello", "the log says Reloading keybindings", "world"]) === false, "chat lines that mention the phrase stay visible");
375
382
  assert(shouldHideReloadBox(["hello", "world"]) === false, "normal lines pass through");
383
+ assert(
384
+ shouldHideReloadBox([...Array(RELOAD_BOX_MAX_LINES + 1).fill(""), " Reloading keybindings, extensions, skills, prompts, themes, and context files... "]) === false,
385
+ "a container larger than any reload box is refused before scanning",
386
+ );
376
387
 
377
388
  // selection: reverse video replaced with explicit colors (bg selectedBg + fg text)
378
389
  assert(