@bismawy/pi-arnative 0.16.0 → 0.18.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/README.md +25 -16
- package/extensions/index.ts +41 -0
- package/lib/active-clock.ts +91 -0
- package/lib/ansi.ts +40 -78
- package/lib/box.ts +49 -68
- package/lib/chatbox.ts +371 -0
- package/lib/color.ts +3 -31
- package/lib/compat.ts +0 -60
- package/lib/edit-diff.ts +199 -0
- package/{extensions → lib/features}/arnative.ts +96 -423
- package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -325
- package/{extensions → lib/features}/budget.ts +17 -242
- package/lib/features/footer.ts +2232 -0
- package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
- package/{extensions → lib/features}/model-heal.ts +5 -28
- package/lib/features/progress-group.ts +1557 -0
- package/{extensions → lib/features}/render-cache.ts +130 -158
- package/{extensions → lib/features}/timestamps.ts +132 -131
- package/{extensions → lib/features}/todos.ts +44 -158
- package/lib/features/tools.ts +1202 -0
- package/lib/features/ui-render-tweaks.ts +606 -0
- package/lib/features/usage.ts +786 -0
- package/lib/format.ts +22 -4
- package/lib/git-status.ts +164 -0
- package/lib/list-picker.ts +1 -127
- package/lib/model-heal.ts +70 -162
- package/lib/patch.ts +0 -63
- package/lib/preset-store.ts +17 -133
- package/lib/provider-store.ts +573 -0
- package/lib/provider.ts +52 -851
- package/lib/runtime.ts +209 -0
- package/lib/shortcuts.ts +8 -58
- package/lib/spinner.ts +88 -162
- package/lib/status-widget.ts +4 -30
- package/lib/todos.ts +20 -143
- package/lib/usage-pricing.ts +143 -0
- package/lib/usage-store.ts +44 -378
- package/package.json +5 -6
- package/CHANGELOG.md +0 -678
- package/extensions/animations.ts +0 -242
- package/extensions/footer.ts +0 -2580
- package/extensions/tools.ts +0 -2231
- package/extensions/ui-render-tweaks.ts +0 -1005
- package/extensions/usage-export.ts +0 -283
- package/extensions/usage.ts +0 -1406
- package/lib/check.ts +0 -21
- package/themes/gen-themes.mjs +0 -715
package/extensions/footer.ts
DELETED
|
@@ -1,2580 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Arnative footer (fixed 3-row grid). Row 1: cwd | active time | branch — model + thinking;
|
|
3
|
-
* rows 2-3: extension status | tok/s · cache · token, each side wrapped in its half of the
|
|
4
|
-
* width. The clock counts active time, not wall-clock age — see {@link ActiveClock}.
|
|
5
|
-
* Preset (`/arnative footers`), live: "Arnative (Full)" (default), "Arnative (Minimal)"
|
|
6
|
-
* or "Pi (system)".
|
|
7
|
-
*/
|
|
8
|
-
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
9
|
-
import { CustomEditor, FooterComponent, InteractiveMode, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
-
import { truncateToWidth, visibleWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
|
|
11
|
-
import { execFile } from "node:child_process";
|
|
12
|
-
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
13
|
-
import { tmpdir } from "node:os";
|
|
14
|
-
import { dirname, join, resolve } from "node:path";
|
|
15
|
-
import { softOf, softSecondaryOf, stripAnsi } from "../lib/ansi.ts";
|
|
16
|
-
import { inSpans, textSpans, type TextSpan } from "../lib/box.ts";
|
|
17
|
-
import { assert, isMain } from "../lib/check.ts";
|
|
18
|
-
import { capitalize, markedLabels, modelDisplayParts } from "../lib/format.ts";
|
|
19
|
-
import { IS_WINDOWS_LIKE, SHORTCUT_RELOAD, SHORTCUT_TOGGLE_FOOTER } from "../lib/shortcuts.ts";
|
|
20
|
-
import { markPatched, originalOf, patchOnce } from "../lib/patch.ts";
|
|
21
|
-
import { estimateCost, formatTokens, loadPriceTable, TOOL_PROVIDER, type PriceTable } from "../lib/usage-store.ts";
|
|
22
|
-
import {
|
|
23
|
-
CHATBOX_DIALOG_KEY as CHATBOX_DIALOG_CONFIG_KEY,
|
|
24
|
-
CHATBOX_PRESET_KEY as CHATBOX_PRESET_CONFIG_KEY,
|
|
25
|
-
CHATBOX_PROMPT_KEY as CHATBOX_PROMPT_CONFIG_KEY,
|
|
26
|
-
FOOTER_COST_KEY as FOOTER_COST_CONFIG_KEY,
|
|
27
|
-
FOOTER_PRESET_KEY as FOOTER_PRESET_CONFIG_KEY,
|
|
28
|
-
choiceSetting,
|
|
29
|
-
flagSetting,
|
|
30
|
-
loadChoice,
|
|
31
|
-
resetPresetCache,
|
|
32
|
-
} from "../lib/preset-store.ts";
|
|
33
|
-
import { formatCost } from "./usage.ts";
|
|
34
|
-
import { isByteLimitedModel, wireBytesSnapshot } from "./autocompact.ts";
|
|
35
|
-
import { budgetLevelNow } from "./budget.ts";
|
|
36
|
-
import { EDITOR_KEY, activeSpinnerGradient, activeSpinnerPreset } from "./animations.ts";
|
|
37
|
-
import { spinnerPainter } from "../lib/spinner.ts";
|
|
38
|
-
|
|
39
|
-
// ctrl+alt+r (alt+r on Windows/WSL — see lib/shortcuts.ts).
|
|
40
|
-
// The TUI drops key-release events before handleInput, so press+release cannot
|
|
41
|
-
// fire this twice even when the terminal reports event types (Kitty flag 2).
|
|
42
|
-
|
|
43
|
-
// Footer preset chosen through `/arnative footers`. "Arnative (Full)" = this extension's
|
|
44
|
-
// 3-row grid footer; "Pi (system)" = pi's built-in footer (the boxed editor stays arnative
|
|
45
|
-
// in both — pi's `setEditorComponent()` would close the picker mid-preview). The picker
|
|
46
|
-
// lives in arnative.ts, so the choice is shared through globalThis like the header preset.
|
|
47
|
-
// Listed built-in-first: the `(Full)` suffix is rendered dim, so the plain row reads cleaner on top.
|
|
48
|
-
export const CHATBOX_PRESETS = ["Pi (system)", "Arnative"] as const;
|
|
49
|
-
export type ChatboxPreset = (typeof CHATBOX_PRESETS)[number];
|
|
50
|
-
export const DEFAULT_CHATBOX_PRESET: ChatboxPreset = "Arnative";
|
|
51
|
-
const chatboxPreset = choiceSetting(CHATBOX_PRESET_CONFIG_KEY, CHATBOX_PRESETS, DEFAULT_CHATBOX_PRESET);
|
|
52
|
-
const CHATBOX_PRESET_KEY = chatboxPreset.slot;
|
|
53
|
-
|
|
54
|
-
export const CHATBOX_PROMPTS = ["❯", ">", "›", "▸", "→", "\uf44f", "\udb82\udf79", "\uf51b", "\udb80\udf7d", "\uf120", "\uf489", "\udb80\udd7a"] as const;
|
|
55
|
-
export type ChatboxPrompt = (typeof CHATBOX_PROMPTS)[number];
|
|
56
|
-
export const DEFAULT_CHATBOX_PROMPT: ChatboxPrompt = "❯";
|
|
57
|
-
const chatboxPrompt = choiceSetting(CHATBOX_PROMPT_CONFIG_KEY, CHATBOX_PROMPTS, DEFAULT_CHATBOX_PROMPT);
|
|
58
|
-
const CHATBOX_PROMPT_KEY = chatboxPrompt.slot;
|
|
59
|
-
|
|
60
|
-
export const CHATBOX_DIALOGS = ["Left", "Center", "Right", "Inside", "Outside"] as const;
|
|
61
|
-
export type ChatboxDialog = (typeof CHATBOX_DIALOGS)[number];
|
|
62
|
-
export const DEFAULT_CHATBOX_DIALOG: ChatboxDialog = "Left";
|
|
63
|
-
const chatboxDialog = choiceSetting(CHATBOX_DIALOG_CONFIG_KEY, CHATBOX_DIALOGS, DEFAULT_CHATBOX_DIALOG);
|
|
64
|
-
const CHATBOX_DIALOG_KEY = chatboxDialog.slot;
|
|
65
|
-
|
|
66
|
-
export const PROMPT_IDLE_MS = 3_000;
|
|
67
|
-
const PROMPT_TYPED_AT_KEY = Symbol.for("pi-arnative.promptTypedAt");
|
|
68
|
-
const PROMPT_IDLE_TIMER_KEY = Symbol.for("pi-arnative.promptIdleTimer");
|
|
69
|
-
|
|
70
|
-
export const activeChatboxPreset = (): ChatboxPreset => chatboxPreset.get();
|
|
71
|
-
export function setChatboxPreset(name: ChatboxPreset): void {
|
|
72
|
-
chatboxPreset.set(name);
|
|
73
|
-
poke();
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
export const activeChatboxPrompt = (): ChatboxPrompt => chatboxPrompt.get();
|
|
77
|
-
export function setChatboxPrompt(prompt: ChatboxPrompt): void {
|
|
78
|
-
chatboxPrompt.set(prompt);
|
|
79
|
-
poke();
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export function nextChatboxPrompt(current: ChatboxPrompt = activeChatboxPrompt()): ChatboxPrompt {
|
|
83
|
-
const idx = CHATBOX_PROMPTS.indexOf(current);
|
|
84
|
-
return CHATBOX_PROMPTS[(idx + 1) % CHATBOX_PROMPTS.length]!;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export const activeChatboxDialog = (): ChatboxDialog => chatboxDialog.get();
|
|
88
|
-
export function setChatboxDialog(dialog: ChatboxDialog): void {
|
|
89
|
-
chatboxDialog.set(dialog);
|
|
90
|
-
poke();
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export function nextChatboxDialog(current: ChatboxDialog = activeChatboxDialog()): ChatboxDialog {
|
|
94
|
-
const idx = CHATBOX_DIALOGS.indexOf(current);
|
|
95
|
-
return CHATBOX_DIALOGS[(idx + 1) % CHATBOX_DIALOGS.length]!;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export function isPromptActive(
|
|
99
|
-
now: number = Date.now(),
|
|
100
|
-
lastTyped: number = ((globalThis as Record<symbol, unknown>)[PROMPT_TYPED_AT_KEY] as number | undefined) ?? 0,
|
|
101
|
-
): boolean {
|
|
102
|
-
return lastTyped > 0 && now - lastTyped <= PROMPT_IDLE_MS;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
export function stopPromptIdle(): void {
|
|
106
|
-
const g = globalThis as Record<symbol, ReturnType<typeof setTimeout> | null | undefined>;
|
|
107
|
-
if (g[PROMPT_IDLE_TIMER_KEY]) clearTimeout(g[PROMPT_IDLE_TIMER_KEY]!);
|
|
108
|
-
g[PROMPT_IDLE_TIMER_KEY] = null;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
export function markPromptTyped(now: number = Date.now()): void {
|
|
112
|
-
const g = globalThis as Record<symbol, unknown>;
|
|
113
|
-
g[PROMPT_TYPED_AT_KEY] = now;
|
|
114
|
-
stopPromptIdle();
|
|
115
|
-
const timer = setTimeout(() => {
|
|
116
|
-
g[PROMPT_IDLE_TIMER_KEY] = null;
|
|
117
|
-
poke();
|
|
118
|
-
}, PROMPT_IDLE_MS + 25);
|
|
119
|
-
timer.unref?.();
|
|
120
|
-
g[PROMPT_IDLE_TIMER_KEY] = timer;
|
|
121
|
-
poke();
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
export function chatboxPrimaryPaint(
|
|
125
|
-
th: { fg?(color: string, text: string): string } | null | undefined,
|
|
126
|
-
): (text: string) => string {
|
|
127
|
-
if (!th?.fg) return (t) => t;
|
|
128
|
-
for (const token of ["mdHeading", "accent"]) {
|
|
129
|
-
try {
|
|
130
|
-
const probe = th.fg(token, "x");
|
|
131
|
-
if (typeof probe === "string" && probe.includes("x")) return (t) => th.fg!(token, t);
|
|
132
|
-
} catch {
|
|
133
|
-
// try next
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
return (t) => t;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
export function isWideNerdPrompt(glyph: string): boolean {
|
|
140
|
-
const cp = glyph.codePointAt(0) ?? 0;
|
|
141
|
-
return (cp >= 0xe000 && cp <= 0xf8ff) || cp >= 0xf0000;
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
export function paintChatboxPrompt(
|
|
145
|
-
promptGlyph: string,
|
|
146
|
-
th: { fg?(color: string, text: string): string } | null | undefined,
|
|
147
|
-
active: boolean,
|
|
148
|
-
): string {
|
|
149
|
-
const text = isWideNerdPrompt(promptGlyph) ? ` ${promptGlyph} ` : ` ${promptGlyph} `;
|
|
150
|
-
if (!th?.fg) return text;
|
|
151
|
-
try {
|
|
152
|
-
if (!active) return th.fg("dim", text);
|
|
153
|
-
return chatboxPrimaryPaint(th)(text);
|
|
154
|
-
} catch {
|
|
155
|
-
return text;
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
export function renderChatboxScrollBorder(
|
|
160
|
-
direction: "\u2191" | "\u2193",
|
|
161
|
-
hiddenLineCount: number,
|
|
162
|
-
width: number,
|
|
163
|
-
borderColor: (text: string) => string,
|
|
164
|
-
primaryColor: (text: string) => string,
|
|
165
|
-
): string {
|
|
166
|
-
const availableWidth = Math.max(0, width);
|
|
167
|
-
if (hiddenLineCount <= 0) return borderColor("\u2500".repeat(availableWidth));
|
|
168
|
-
const core = `${direction} ${hiddenLineCount} more`;
|
|
169
|
-
const labelWidth = visibleWidth(core) + 2;
|
|
170
|
-
if (labelWidth + 2 <= availableWidth) {
|
|
171
|
-
const leftWidth = Math.floor((availableWidth - labelWidth) / 2);
|
|
172
|
-
const rightWidth = availableWidth - leftWidth - labelWidth;
|
|
173
|
-
return `${borderColor(`${"\u2500".repeat(leftWidth)} `)}${primaryColor(core)}${borderColor(` ${"\u2500".repeat(rightWidth)}`)}`;
|
|
174
|
-
}
|
|
175
|
-
const prefix = "\u2500\u2500\u2500 ";
|
|
176
|
-
const remaining = availableWidth - visibleWidth(prefix) - visibleWidth(core) - 1;
|
|
177
|
-
if (remaining >= 0) {
|
|
178
|
-
return `${borderColor(prefix)}${primaryColor(core)}${borderColor(` ${"\u2500".repeat(remaining)}`)}`;
|
|
179
|
-
}
|
|
180
|
-
return borderColor(".".repeat(Math.min(3, availableWidth)) + "\u2500".repeat(Math.max(0, availableWidth - 3)));
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
export const FOOTER_PRESETS = ["Pi (system)", "Arnative (Full)", "Arnative (Minimal)"] as const;
|
|
184
|
-
export type FooterPreset = (typeof FOOTER_PRESETS)[number];
|
|
185
|
-
export const DEFAULT_FOOTER_PRESET: FooterPreset = "Arnative (Full)";
|
|
186
|
-
/** Presets that this extension's registrar draws (everything but pi's built-in footer). */
|
|
187
|
-
const ARNATIVE_PRESETS: readonly FooterPreset[] = ["Arnative (Full)", "Arnative (Minimal)"];
|
|
188
|
-
/** Collapse state of the minimal footer: one flag per side, so a click on the left
|
|
189
|
-
* head does not open the right metrics. Session-scoped, not persisted. */
|
|
190
|
-
const MINIMAL_EXPAND_KEY = Symbol.for("pi-arnative.minimalFooter.expanded");
|
|
191
|
-
export function minimalExpanded(): { left: boolean; right: boolean } {
|
|
192
|
-
const slot = (globalThis as Record<symbol, { left: boolean; right: boolean } | undefined>)[MINIMAL_EXPAND_KEY];
|
|
193
|
-
if (slot) return slot;
|
|
194
|
-
const fresh = { left: false, right: false };
|
|
195
|
-
(globalThis as Record<symbol, { left: boolean; right: boolean }>)[MINIMAL_EXPAND_KEY] = fresh;
|
|
196
|
-
return fresh;
|
|
197
|
-
}
|
|
198
|
-
const footerPreset = choiceSetting(FOOTER_PRESET_CONFIG_KEY, FOOTER_PRESETS, DEFAULT_FOOTER_PRESET);
|
|
199
|
-
const FOOTER_PRESET_KEY = footerPreset.slot;
|
|
200
|
-
const FOOTER_REGISTRAR_KEY = Symbol.for("pi-arnative.footerRegistrar");
|
|
201
|
-
const footerCost = flagSetting(FOOTER_COST_CONFIG_KEY);
|
|
202
|
-
|
|
203
|
-
/** Is the session cost cell on? */
|
|
204
|
-
export const activeFooterCost = (): boolean => footerCost.get();
|
|
205
|
-
|
|
206
|
-
/** Flip the cost cell, persist it, and repaint the footer at once. */
|
|
207
|
-
export function setFooterCost(on: boolean): void {
|
|
208
|
-
footerCost.set(on);
|
|
209
|
-
poke();
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
export const activeFooterPreset = (): FooterPreset => footerPreset.get();
|
|
213
|
-
|
|
214
|
-
/**
|
|
215
|
-
* Hand the footer slot to the active preset: arnative's grid, or pi's built-in footer.
|
|
216
|
-
* The editor is deliberately never touched here — pi's `setEditorComponent()` calls
|
|
217
|
-
* `disposeActiveSelector()`, which would close the `/arnative` picker mid-preview.
|
|
218
|
-
*/
|
|
219
|
-
export function applyFooterPreset(ctx: ExtensionContext): void {
|
|
220
|
-
if (activeFooterPreset() === "Pi (system)") {
|
|
221
|
-
ctx.ui?.setFooter?.(undefined);
|
|
222
|
-
return;
|
|
223
|
-
}
|
|
224
|
-
const register = (globalThis as Record<symbol, ((ctx: ExtensionContext) => void) | undefined>)[FOOTER_REGISTRAR_KEY];
|
|
225
|
-
register?.(ctx);
|
|
226
|
-
}
|
|
227
|
-
/** Select a preset and apply it immediately (the footer swaps on the spot). */
|
|
228
|
-
export function setFooterPreset(name: FooterPreset, ctx: ExtensionContext): void {
|
|
229
|
-
footerPreset.set(name);
|
|
230
|
-
applyFooterPreset(ctx);
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// Intercept the built-in FooterComponent to force a pure 2-line footer.
|
|
234
|
-
// Reinstalled on every load (lib/patch.ts): `/reload` must pick up a footer change.
|
|
235
|
-
if (FooterComponent?.prototype?.render) {
|
|
236
|
-
const proto = FooterComponent.prototype as any;
|
|
237
|
-
const origRender = originalOf<(this: any, width: number) => string[]>(proto, "render");
|
|
238
|
-
proto.render = markPatched(function (this: any, width: number): string[] {
|
|
239
|
-
// "Pi (system)" preset = pi's own footer, so keep its stock line count.
|
|
240
|
-
if (activeFooterPreset() === "Pi (system)") return origRender.call(this, width);
|
|
241
|
-
const lines = origRender.call(this, width);
|
|
242
|
-
return lines.length > 2 ? lines.slice(0, 2) : lines;
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
let activeThemeProxy: { fg(color: string, text: string): string; bg?(color: string, text: string): string } | null = null;
|
|
247
|
-
|
|
248
|
-
type GitInfo = {
|
|
249
|
-
branch: string;
|
|
250
|
-
/** Absent (null) when git could not answer — never a false "-"/"clean". */
|
|
251
|
-
tag: string | null;
|
|
252
|
-
uncommitted: number | null;
|
|
253
|
-
/** Working tree vs HEAD, tracked files only (an untracked file is not a diff).
|
|
254
|
-
* Null when git could not answer. */
|
|
255
|
-
added: number | null;
|
|
256
|
-
removed: number | null;
|
|
257
|
-
ahead: number;
|
|
258
|
-
behind: number;
|
|
259
|
-
} | null;
|
|
260
|
-
let gitRefreshInFlight = false;
|
|
261
|
-
|
|
262
|
-
let git: GitInfo = null;
|
|
263
|
-
let currentThinkingLevel: string | undefined = undefined;
|
|
264
|
-
let currentModel: { id: string; name?: string; provider?: string } | undefined = undefined;
|
|
265
|
-
let rerender: (() => void) | null = null;
|
|
266
|
-
let lastPokeMs = 0;
|
|
267
|
-
/** Column ranges of the minimal footer's disclosure markers, recorded per render
|
|
268
|
-
* (mouse coordinates are component-local, so they must come from the same frame). */
|
|
269
|
-
let minimalRanges: { left: [number, number]; right: [number, number] } | null = null;
|
|
270
|
-
|
|
271
|
-
/** Maximum inactivity window before the session clock freezes (30 seconds). */
|
|
272
|
-
export const IDLE_PAUSE_MS = 30_000;
|
|
273
|
-
|
|
274
|
-
/**
|
|
275
|
-
* Tracks active session duration, freezing after inactivity periods.
|
|
276
|
-
* State is stored on globalThis to survive module reloads.
|
|
277
|
-
*/
|
|
278
|
-
export class ActiveClock {
|
|
279
|
-
active: number;
|
|
280
|
-
runStarted: number;
|
|
281
|
-
lastSeen: number;
|
|
282
|
-
readonly pauseMs: number;
|
|
283
|
-
|
|
284
|
-
constructor(startedAt: number, pauseMs: number = IDLE_PAUSE_MS) {
|
|
285
|
-
const saved = (globalThis as Record<symbol, unknown>)[ACTIVE_KEY] as
|
|
286
|
-
| { active?: number; runStarted?: number; lastSeen?: number }
|
|
287
|
-
| undefined;
|
|
288
|
-
this.pauseMs = pauseMs;
|
|
289
|
-
this.active = typeof saved?.active === "number" ? saved.active : 0;
|
|
290
|
-
this.runStarted = typeof saved?.runStarted === "number" ? saved.runStarted : startedAt;
|
|
291
|
-
this.lastSeen = typeof saved?.lastSeen === "number" ? saved.lastSeen : startedAt;
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
/** Committed runs plus the live one, the live part clamped at `lastSeen + pauseMs`. */
|
|
295
|
-
total(now: number = Date.now()): number {
|
|
296
|
-
return this.active + Math.max(0, Math.min(now, this.lastSeen + this.pauseMs) - this.runStarted);
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
/** Activity: commits a run left longer than `pauseMs`, else just moves `lastSeen`. */
|
|
300
|
-
tick(now: number = Date.now()): void {
|
|
301
|
-
if (now - this.lastSeen > this.pauseMs) {
|
|
302
|
-
this.active = this.total(now);
|
|
303
|
-
this.runStarted = now;
|
|
304
|
-
}
|
|
305
|
-
this.lastSeen = now;
|
|
306
|
-
(globalThis as Record<symbol, unknown>)[ACTIVE_KEY] = {
|
|
307
|
-
active: this.active,
|
|
308
|
-
runStarted: this.runStarted,
|
|
309
|
-
lastSeen: this.lastSeen,
|
|
310
|
-
};
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
idle(now: number = Date.now()): boolean {
|
|
314
|
-
return now - this.lastSeen > this.pauseMs;
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
/** Sums active duration from recorded session entries up to pause threshold. */
|
|
319
|
-
export function seedActiveMs(entries: readonly unknown[], pauseMs: number = IDLE_PAUSE_MS, now: number = Date.now()): number {
|
|
320
|
-
const times: number[] = [];
|
|
321
|
-
for (const entry of entries) {
|
|
322
|
-
const ts = (entry as { timestamp?: string } | null)?.timestamp;
|
|
323
|
-
const parsed = ts ? Date.parse(ts) : NaN;
|
|
324
|
-
if (Number.isFinite(parsed) && parsed <= now) times.push(parsed);
|
|
325
|
-
}
|
|
326
|
-
times.sort((a, b) => a - b);
|
|
327
|
-
let ms = 0;
|
|
328
|
-
for (let i = 1; i < times.length; i++) {
|
|
329
|
-
const gap = times[i]! - times[i - 1]!;
|
|
330
|
-
if (gap > 0 && gap <= pauseMs) ms += gap;
|
|
331
|
-
}
|
|
332
|
-
return ms;
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
// One shared clock: a /reload re-imports this module, so a fresh instance would restart
|
|
336
|
-
// a session that is already hours old. Exported so a test can drive the render path.
|
|
337
|
-
const ACTIVE_KEY = Symbol.for("pi-arnative.activeClock");
|
|
338
|
-
export let clock = new ActiveClock(Date.now());
|
|
339
|
-
|
|
340
|
-
const MODEL_KEY = Symbol.for("pi-arnative.currentModel");
|
|
341
|
-
const IDLE_TIMER_KEY = Symbol.for("pi-arnative.idleTimer");
|
|
342
|
-
const CLOCK_TIMER_KEY = Symbol.for("pi-arnative.clockTimer");
|
|
343
|
-
const THINKING_KEY = Symbol.for("pi-arnative.currentThinking");
|
|
344
|
-
const CWD_KEY = Symbol.for("pi-arnative.lastCwd");
|
|
345
|
-
const GIT_KEY = Symbol.for("pi-arnative.lastGit");
|
|
346
|
-
const GEN_KEY = Symbol.for("pi-arnative.footerGen");
|
|
347
|
-
let footerGen = (globalThis as Record<symbol, number>)[GEN_KEY] || 0;
|
|
348
|
-
|
|
349
|
-
let assistantStartMs: number | null = null;
|
|
350
|
-
let assistantChars = 0;
|
|
351
|
-
let latestSpeed: number | null = null;
|
|
352
|
-
|
|
353
|
-
// Live elapsed clock for the working loader: "⠴ Working (50s)".
|
|
354
|
-
const WORK_TIMER_KEY = Symbol.for("pi-arnative.workTimer");
|
|
355
|
-
const WORK_LABEL = "Working";
|
|
356
|
-
let workVerb = WORK_LABEL;
|
|
357
|
-
let workStartMs: number | null = null;
|
|
358
|
-
let workUI: { setWorkingMessage?: (message?: string) => void; setWorkingIndicator?: (options?: unknown) => void } | null =
|
|
359
|
-
null;
|
|
360
|
-
// Verbs of tools still running (toolCallId -> verb): the label must not reset to "Working"
|
|
361
|
-
// while a sibling tool is still going (pi executes tools in parallel).
|
|
362
|
-
const activeToolVerbs = new Map<string, string>();
|
|
363
|
-
|
|
364
|
-
/** Label while `active` tools remain: last started wins, empty -> default. */
|
|
365
|
-
export function currentToolVerb(active: ReadonlyMap<string, string>): string {
|
|
366
|
-
let verb = WORK_LABEL;
|
|
367
|
-
for (const v of active.values()) verb = v;
|
|
368
|
-
return verb;
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
/**
|
|
372
|
-
* Is this status value pi-jev-eye's own cell? It is matched on the LABEL the value carries (`Eye:`), not on
|
|
373
|
-
* the internal key name: the value is `Eye: ● ON (Clef Flash)` and contains no `jev-eye` anywhere, so the
|
|
374
|
-
* old `value.includes("jev-eye")` test went false and the whole cell fell through to the generic path —
|
|
375
|
-
* which is exactly how it silently lost its icon and its dim backend suffix.
|
|
376
|
-
*
|
|
377
|
-
* Recognising the label keeps the rule honest: if pi-jev-eye renames its label, this test fails loudly in
|
|
378
|
-
* the self-check below instead of degrading to a plain grey cell.
|
|
379
|
-
*/
|
|
380
|
-
export const isJevEyeStatus = (status: string): boolean => /^\s*Eye\s*:/i.test(stripAnsi(status));
|
|
381
|
-
|
|
382
|
-
/**
|
|
383
|
-
* The pi-jev-eye status cell: `Eye: ● MODE (Backend)`. pi-jev-eye writes the value plain because a status
|
|
384
|
-
* is a fact, not a layout; this decides the painting.
|
|
385
|
-
*
|
|
386
|
-
* The trailing parenthesised backend is a modifier, so it takes `dim` while the `Eye:` label and the state
|
|
387
|
-
* keep the soft and state tiers — that is what makes `(Clef Flash)` recede and `Eye: ● ON` stay readable
|
|
388
|
-
* at a glance. The backend name itself is read out of the value, never hardcoded here: the extension
|
|
389
|
-
* reports the active backend from `/jev-eye models`, so the footer cannot know it in advance.
|
|
390
|
-
*/
|
|
391
|
-
export function jevEyeStatusLine(
|
|
392
|
-
status: string,
|
|
393
|
-
acc: (text: string) => string,
|
|
394
|
-
dim: (text: string) => string,
|
|
395
|
-
soft: (text: string) => string,
|
|
396
|
-
theme?: { fg?: (color: string, text: string) => string },
|
|
397
|
-
): string {
|
|
398
|
-
const clean = stripAnsi(status);
|
|
399
|
-
const isOff = clean.includes("OFF") || clean.includes("\u25CB");
|
|
400
|
-
const isReview = /REVIEW/i.test(clean);
|
|
401
|
-
let bullet = isOff ? dim("\u25CB") : acc("\u25CF");
|
|
402
|
-
if (isReview && typeof theme?.fg === "function") {
|
|
403
|
-
try {
|
|
404
|
-
bullet = theme.fg("warning", "\u25CF");
|
|
405
|
-
} catch {
|
|
406
|
-
bullet = acc("\u25CF");
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
const label = isOff ? "OFF" : isReview ? "REVIEW" : "ON";
|
|
410
|
-
// `Eye: ● ON (Clef Flash)` -> the base before the first colon, the backend in the trailing parentheses.
|
|
411
|
-
const base = clean.split(":")[0]!.trim() || "Eye";
|
|
412
|
-
const at = clean.lastIndexOf("(");
|
|
413
|
-
const backend = at >= 0 && clean.trimEnd().endsWith(")") ? clean.slice(at, clean.lastIndexOf(")") + 1).trim() : "";
|
|
414
|
-
// One space, not the two the previous glyph needed: \uf21b's ink fits its own cell, so the label sits
|
|
415
|
-
// right after it. The space before the backend stays outside the dim run, so the modifier does not
|
|
416
|
-
// start with a painted blank.
|
|
417
|
-
return `${acc("\uf21b")} ${soft(`${base}:`)} ${bullet} ${soft(label)}${backend ? ` ${dim(backend)}` : ""}`;
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
/**
|
|
421
|
-
* The ponytail status cell. The horse lives at U+EF04 (fa-horse). U+EF51
|
|
422
|
-
* (fa-circle_radiation) carries no outline in the Windows Nerd Font build, so it
|
|
423
|
-
* renders as a blank cell there and the status silently loses its icon; U+EF04 does
|
|
424
|
-
* draw. Kept out of the render closure so the self-check drives this exact path.
|
|
425
|
-
*/
|
|
426
|
-
export function ponytailStatusLine(
|
|
427
|
-
status: string,
|
|
428
|
-
acc: (text: string) => string,
|
|
429
|
-
dim: (text: string) => string,
|
|
430
|
-
soft: (text: string) => string,
|
|
431
|
-
): string {
|
|
432
|
-
const bullet = status.includes("\u25CF") ? acc("\u25CF") : dim("\u25CB");
|
|
433
|
-
let mode = "FULL";
|
|
434
|
-
if (/LITE/i.test(status)) mode = "LITE";
|
|
435
|
-
else if (/ULTRA/i.test(status)) mode = "ULTRA";
|
|
436
|
-
return `${acc("\uef04")} ${soft("ponytail:")} ${bullet} ${soft(mode)}`;
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
type RunResult = { ok: boolean; out: string };
|
|
440
|
-
/** Distinguishes "git said nothing" from "git could not run" — the caller must not
|
|
441
|
-
* invent a clean tree when git is absent or the repo is not ours. */
|
|
442
|
-
function run(cmd: string, args: string[], cwd: string): Promise<RunResult> {
|
|
443
|
-
return new Promise((resolvePromise) => {
|
|
444
|
-
execFile(cmd, args, { cwd, timeout: 2000 }, (err, stdout) => {
|
|
445
|
-
resolvePromise({ ok: !err, out: String(stdout).trim() });
|
|
446
|
-
});
|
|
447
|
-
});
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
/**
|
|
451
|
-
* The branch, straight from `.git/HEAD` — the same trick pi's own footer uses.
|
|
452
|
-
* `git branch --show-current` fails identically for a repo the user does not own
|
|
453
|
-
* (git's dubious-ownership guard), a PATH without git, and a detached HEAD; all
|
|
454
|
-
* three collapsed into a silent null before. Reading the ref needs no binary and
|
|
455
|
-
* no ownership check, so a fresh user sees the branch without installing git.
|
|
456
|
-
*/
|
|
457
|
-
function branchFromDisk(cwd: string): string | null {
|
|
458
|
-
// Walk up like git does: a subfolder of a repo is still inside it.
|
|
459
|
-
for (let dir = resolve(cwd); ; ) {
|
|
460
|
-
try {
|
|
461
|
-
const dotGit = join(dir, ".git");
|
|
462
|
-
// A worktree/submodule has a `.git` file pointing at the real git dir.
|
|
463
|
-
const gitDir = statSync(dotGit).isDirectory()
|
|
464
|
-
? dotGit
|
|
465
|
-
: resolve(dir, readFileSync(dotGit, "utf8").trim().replace(/^gitdir:\s*/, ""));
|
|
466
|
-
const head = readFileSync(join(gitDir, "HEAD"), "utf8").trim();
|
|
467
|
-
const ref = /^ref:\s+refs\/heads\/(.+)$/.exec(head);
|
|
468
|
-
return ref ? ref[1] : "detached";
|
|
469
|
-
} catch (e) {
|
|
470
|
-
if ((e as NodeJS.ErrnoException).code !== "ENOENT") return null; // unreadable metadata
|
|
471
|
-
}
|
|
472
|
-
const parent = dirname(dir);
|
|
473
|
-
if (parent === dir) return null; // reached the filesystem root: not a repo
|
|
474
|
-
dir = parent;
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
// A refresh arriving while one is in flight is queued (last requested cwd wins) and
|
|
479
|
-
// re-run afterwards — it used to be dropped, leaving the footer's git state stale
|
|
480
|
-
// until the next trigger.
|
|
481
|
-
let gitRefreshQueuedCwd: string | null = null;
|
|
482
|
-
|
|
483
|
-
/**
|
|
484
|
-
* Row-1 git segment: branch(+sync), tag, worktree state. Halves git cannot answer
|
|
485
|
-
* (no binary, or a repo the user does not own) are omitted, so a fresh user still sees
|
|
486
|
-
* the branch but never a fabricated "-" or "clean".
|
|
487
|
-
*/
|
|
488
|
-
export function gitParts(
|
|
489
|
-
info: GitInfo,
|
|
490
|
-
acc: (t: string) => string,
|
|
491
|
-
soft: (t: string) => string,
|
|
492
|
-
): string[] {
|
|
493
|
-
if (!info) return [];
|
|
494
|
-
const branch = `${acc("\uf126")} ${soft(info.branch)}${info.ahead > 0 ? ` ${soft(`↑${info.ahead}`)}` : ""}${info.behind > 0 ? ` ${soft(`↓${info.behind}`)}` : ""}`;
|
|
495
|
-
const parts = [branch];
|
|
496
|
-
if (info.tag !== null) parts.push(`${acc("\uf02b")} ${soft(info.tag)}`);
|
|
497
|
-
if (info.uncommitted !== null) parts.push(`${acc("\uf172")} ${info.uncommitted > 0 ? soft(`~${info.uncommitted}`) : soft("clean")}`);
|
|
498
|
-
return parts;
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
/**
|
|
502
|
-
* Working-tree diff vs HEAD as `+500 -100`, or `""` when there is nothing to show:
|
|
503
|
-
* a clean tree, or git cannot answer (not a repo, no binary, unreadable HEAD). This is
|
|
504
|
-
* the whole uncommitted change, not just what this session touched — a snapshot at
|
|
505
|
-
* session start would be needed for that, which is not worth the cost here.
|
|
506
|
-
*/
|
|
507
|
-
export function formatDiffStat(
|
|
508
|
-
info: GitInfo,
|
|
509
|
-
acc: (t: string) => string,
|
|
510
|
-
pos: (t: string) => string,
|
|
511
|
-
neg: (t: string) => string,
|
|
512
|
-
): string {
|
|
513
|
-
if (!info || info.added === null || info.removed === null) return "";
|
|
514
|
-
if (info.added + info.removed === 0) return "";
|
|
515
|
-
return `${acc("\uf4d2")} ${pos(`+${info.added}`)} ${neg(`-${info.removed}`)}`;
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
async function refreshGit(cwd: string): Promise<void> {
|
|
519
|
-
if (gitRefreshInFlight) {
|
|
520
|
-
gitRefreshQueuedCwd = cwd;
|
|
521
|
-
return;
|
|
522
|
-
}
|
|
523
|
-
gitRefreshInFlight = true;
|
|
524
|
-
try {
|
|
525
|
-
const branch = branchFromDisk(cwd);
|
|
526
|
-
if (!branch) {
|
|
527
|
-
// Clear the shared slot too, or the previous cwd's branch survives a reload.
|
|
528
|
-
git = null;
|
|
529
|
-
(globalThis as Record<symbol, any>)[GIT_KEY] = null;
|
|
530
|
-
return;
|
|
531
|
-
}
|
|
532
|
-
const [tag, status, sync, numstat] = await Promise.all([
|
|
533
|
-
run("git", ["describe", "--tags", "--abbrev=0"], cwd),
|
|
534
|
-
run("git", ["status", "--porcelain"], cwd),
|
|
535
|
-
run("git", ["rev-list", "--left-right", "--count", "@{u}...HEAD"], cwd),
|
|
536
|
-
run("git", ["diff", "HEAD", "--numstat"], cwd),
|
|
537
|
-
]);
|
|
538
|
-
const uncommitted = status.ok ? status.out.split("\n").filter((l) => l.trim().length > 0).length : null;
|
|
539
|
-
const parts = sync.ok && sync.out !== "" ? sync.out.split(/\s+/).map(Number) : [];
|
|
540
|
-
const behind = parts.length > 0 && parts[0] > 0 ? parts[0] : 0;
|
|
541
|
-
const ahead = parts.length > 1 && parts[1] > 0 ? parts[1] : 0;
|
|
542
|
-
// An unborn HEAD (a repo with no commit yet) makes `diff HEAD` fail; compare the
|
|
543
|
-
// working tree against the canonical empty tree so a staged first commit still counts.
|
|
544
|
-
const numstat2 = numstat.ok ? numstat : await run("git", ["diff", "--numstat", "4b825dc642cb6eb9a060e54bf8d69288fbee4904"], cwd);
|
|
545
|
-
const { added, removed } = sumNumstat(numstat2.out);
|
|
546
|
-
git = {
|
|
547
|
-
branch,
|
|
548
|
-
tag: tag.ok && tag.out ? tag.out : null,
|
|
549
|
-
uncommitted,
|
|
550
|
-
added: numstat2.ok ? added : null,
|
|
551
|
-
removed: numstat2.ok ? removed : null,
|
|
552
|
-
ahead,
|
|
553
|
-
behind,
|
|
554
|
-
};
|
|
555
|
-
(globalThis as Record<symbol, any>)[GIT_KEY] = git;
|
|
556
|
-
} finally {
|
|
557
|
-
gitRefreshInFlight = false;
|
|
558
|
-
if (gitRefreshQueuedCwd !== null) {
|
|
559
|
-
const queued = gitRefreshQueuedCwd;
|
|
560
|
-
gitRefreshQueuedCwd = null;
|
|
561
|
-
void refreshGit(queued).then(() => poke());
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
/**
|
|
567
|
-
* Head row for the minimal footer, plus the exact click zones (0-based, inclusive
|
|
568
|
-
* columns) of its two heads. Placing the row here instead of guessing at `pairRow`'s
|
|
569
|
-
* arithmetic is deliberate: `pairRow` truncates with an ellipsis, which shifts columns,
|
|
570
|
-
* and a mirror of that logic silently drifts at narrow widths — the bug where a click on
|
|
571
|
-
* blank space toggled a side. Measuring the placed cells cannot drift. The blank gap and
|
|
572
|
-
* any padding stay inert; a head the row cannot fit gets `[-1, -1]`.
|
|
573
|
-
*/
|
|
574
|
-
export function placeMinimalHead(
|
|
575
|
-
left: string,
|
|
576
|
-
right: string,
|
|
577
|
-
width: number,
|
|
578
|
-
): { row: string; left: [number, number]; right: [number, number] } {
|
|
579
|
-
const lw = visibleWidth(left);
|
|
580
|
-
const rw = visibleWidth(right);
|
|
581
|
-
if (lw + 1 + rw <= width) {
|
|
582
|
-
const rightStart = width - rw;
|
|
583
|
-
return {
|
|
584
|
-
row: left + " ".repeat(rightStart - lw) + right,
|
|
585
|
-
left: lw > 0 ? [0, lw - 1] : [-1, -1],
|
|
586
|
-
right: rw > 0 ? [rightStart, width - 1] : [-1, -1],
|
|
587
|
-
};
|
|
588
|
-
}
|
|
589
|
-
// Too wide: the left head is cut, the right one keeps its edge column like pairRow.
|
|
590
|
-
const room = Math.max(1, width - Math.min(rw, width) - 1);
|
|
591
|
-
const lCut = truncateToWidth(left, room);
|
|
592
|
-
const rCut = truncateToWidth(right, width - room - 1);
|
|
593
|
-
const lCutW = visibleWidth(lCut);
|
|
594
|
-
const rCutW = visibleWidth(rCut);
|
|
595
|
-
const rightStart = lCutW + 1;
|
|
596
|
-
return {
|
|
597
|
-
row: lCut + " " + rCut,
|
|
598
|
-
left: lCutW > 0 ? [0, lCutW - 1] : [-1, -1],
|
|
599
|
-
right: rCutW > 0 ? [rightStart, rightStart + rCutW - 1] : [-1, -1],
|
|
600
|
-
};
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
function formatModelName(
|
|
604
|
-
model: { id: string; name?: string; provider?: string } | undefined,
|
|
605
|
-
thinkingLevel: string | undefined,
|
|
606
|
-
acc: (t: string) => string,
|
|
607
|
-
soft: (t: string) => string,
|
|
608
|
-
primary: (t: string) => string,
|
|
609
|
-
dim: (t: string) => string,
|
|
610
|
-
): string {
|
|
611
|
-
if (!model) return dim("No Model");
|
|
612
|
-
const { name, provider } = modelDisplayParts({ id: model.id, name: model.name, provider: model.provider });
|
|
613
|
-
const provStr = provider ? ` ${dim(`(${provider})`)}` : "";
|
|
614
|
-
const capThinking = thinkingLevel && thinkingLevel !== "off" ? capitalize(thinkingLevel) : "";
|
|
615
|
-
const thinkStr = capThinking ? `${acc("\uee9c")} ${soft(capThinking)} ${dim("·")} ` : "";
|
|
616
|
-
return `${thinkStr}${primary(name)}${provStr}`;
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
// Footer is a single line: a deep cwd (`/Users/x/Workspace/personal/proj`)
|
|
620
|
-
// pushes git state and the model off screen. Keep the last 2 segments.
|
|
621
|
-
export function shortenCwd(raw: string): string {
|
|
622
|
-
const p = (raw || "").trim();
|
|
623
|
-
if (!p) return p;
|
|
624
|
-
const drive = p.match(/^[A-Za-z]:/);
|
|
625
|
-
const body = drive ? p.slice(2) : p;
|
|
626
|
-
const parts = body.replace(/\\/g, "/").replace(/\/+$/, "").split("/").filter(Boolean);
|
|
627
|
-
if (parts.length <= 2) return p;
|
|
628
|
-
const head = drive ? `${drive[0]}/\u2026/` : p.startsWith("/") ? "\u2026/" : "\u2026";
|
|
629
|
-
return head + parts.slice(-2).join("/");
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
/** Resolves session start timestamp; reloads preserve state, startup/resume reads header. */
|
|
633
|
-
export function resolveSessionStartMs(reason: string, headerTimestamp: string | undefined, now: number): number {
|
|
634
|
-
if (reason === "reload") return now;
|
|
635
|
-
const parsed = headerTimestamp ? Date.parse(headerTimestamp) : NaN;
|
|
636
|
-
return Number.isFinite(parsed) && parsed > 0 && parsed <= now ? parsed : now;
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
/** Sum `git diff --numstat` output: `added<TAB>removed<TAB>path` per line. A `-`
|
|
640
|
-
* marks a binary file — no line count, so it is skipped, not counted as 0. */
|
|
641
|
-
export function sumNumstat(out: string): { added: number; removed: number } {
|
|
642
|
-
let added = 0;
|
|
643
|
-
let removed = 0;
|
|
644
|
-
for (const line of out.split("\n")) {
|
|
645
|
-
const [a, r] = line.split("\t");
|
|
646
|
-
if (!/^\d+$/.test(a ?? "") || !/^\d+$/.test(r ?? "")) continue;
|
|
647
|
-
added += Number(a);
|
|
648
|
-
removed += Number(r);
|
|
649
|
-
}
|
|
650
|
-
return { added, removed };
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
export function formatDuration(ms: number): string {
|
|
654
|
-
// Sub-second renders as "-" to avoid a "0s" flash on fresh session.
|
|
655
|
-
if (!ms || ms < 1000) return "-";
|
|
656
|
-
const totalSec = Math.floor(ms / 1000);
|
|
657
|
-
const h = Math.floor(totalSec / 3600);
|
|
658
|
-
const m = Math.floor((totalSec % 3600) / 60);
|
|
659
|
-
const s = totalSec % 60;
|
|
660
|
-
if (h > 0) return `${h}h ${m}m`;
|
|
661
|
-
if (m > 0) return `${m}m ${s}s`;
|
|
662
|
-
return `${s}s`;
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
// Full box editor: pi draws only the top/bottom lines (pi-tui editor.js: "no side
|
|
666
|
-
// borders, just horizontal lines above and below") and no prompt char, so the `│`
|
|
667
|
-
// sides, the round ╭╮╰╯ corners and the `> ` prompt are added here. `lines` are
|
|
668
|
-
// already rendered at width - 5 (2 sides + 3 prompt) and the border is patched with
|
|
669
|
-
// dashes to match. `visible` = content line count (private `renderedVisibleLineCount`);
|
|
670
|
-
// autocomplete lines stay outside the box. JetBrainsMono NF has the round glyphs.
|
|
671
|
-
export function renderChatboxLines(
|
|
672
|
-
preset: ChatboxPreset,
|
|
673
|
-
renderInner: (w: number) => string[],
|
|
674
|
-
width: number,
|
|
675
|
-
visible: number | undefined,
|
|
676
|
-
color: (text: string) => string,
|
|
677
|
-
prompt = " > ",
|
|
678
|
-
): string[] {
|
|
679
|
-
const promptW = visibleWidth(prompt);
|
|
680
|
-
if (preset === "Pi (system)" || typeof visible !== "number" || width < promptW + 8) return renderInner(width);
|
|
681
|
-
return boxEditorLines(renderInner(width - (2 + promptW)), visible, color, prompt);
|
|
682
|
-
}
|
|
683
|
-
|
|
684
|
-
export function boxEditorLines(
|
|
685
|
-
lines: readonly string[],
|
|
686
|
-
visible: number,
|
|
687
|
-
color: (text: string) => string,
|
|
688
|
-
prompt = " > ",
|
|
689
|
-
): string[] {
|
|
690
|
-
const inner = lines.length > 0 ? visibleWidth(lines[0]!) : 0;
|
|
691
|
-
const promptWidth = visibleWidth(prompt);
|
|
692
|
-
if (inner < promptWidth + 4 || visible < 1 || lines.length < visible + 2) return [...lines];
|
|
693
|
-
const out = [...lines];
|
|
694
|
-
const side = color("\u2502");
|
|
695
|
-
const indent = " ".repeat(promptWidth);
|
|
696
|
-
for (let i = 1; i <= visible; i++) out[i] = side + (i === 1 ? prompt : indent) + lines[i]! + side;
|
|
697
|
-
const patch = color("\u2500".repeat(promptWidth));
|
|
698
|
-
out[0] = color("\u256d") + lines[0]! + patch + color("\u256e");
|
|
699
|
-
out[visible + 1] = color("\u2570") + lines[visible + 1]! + patch + color("\u256f");
|
|
700
|
-
return out;
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
function formatTopBorderDialog(
|
|
704
|
-
innerW: number,
|
|
705
|
-
hiddenLineCount: number,
|
|
706
|
-
dialog: "Left" | "Center" | "Right",
|
|
707
|
-
status: string,
|
|
708
|
-
spinnerOnly: string,
|
|
709
|
-
color: (text: string) => string,
|
|
710
|
-
primaryColor: (text: string) => string = (t) => t,
|
|
711
|
-
): string {
|
|
712
|
-
const scrollCore = hiddenLineCount > 0 ? `\u2191 ${hiddenLineCount} more` : "";
|
|
713
|
-
const scrollW = scrollCore ? visibleWidth(scrollCore) + 2 : 0;
|
|
714
|
-
const scrollPainted = scrollCore ? `${color(" ")}${primaryColor(scrollCore)}${color(" ")}` : "";
|
|
715
|
-
const tryPlace = (label: string): string | null => {
|
|
716
|
-
const lw = visibleWidth(label);
|
|
717
|
-
if (lw === 0 || innerW < lw + 4) return null;
|
|
718
|
-
if (dialog === "Left") {
|
|
719
|
-
if (scrollW > 0) {
|
|
720
|
-
const centerStart = Math.floor((innerW - scrollW) / 2);
|
|
721
|
-
if (centerStart >= 4 + lw + 1) {
|
|
722
|
-
return `${color("\u2500\u2500 ")}${label}${color(` ${"\u2500".repeat(centerStart - (4 + lw))}`)}${scrollPainted}${color("\u2500".repeat(innerW - centerStart - scrollW))}`;
|
|
723
|
-
}
|
|
724
|
-
return null;
|
|
725
|
-
}
|
|
726
|
-
return color("\u2500\u2500 ") + label + color(` ${"\u2500".repeat(innerW - lw - 4)}`);
|
|
727
|
-
}
|
|
728
|
-
if (dialog === "Center") {
|
|
729
|
-
const leftD = Math.floor((innerW - lw - 2) / 2);
|
|
730
|
-
const rightD = innerW - lw - 2 - leftD;
|
|
731
|
-
if (scrollW > 0) {
|
|
732
|
-
const leftEnd = 2 + scrollW;
|
|
733
|
-
if (leftD >= leftEnd + 1) {
|
|
734
|
-
return `${color("\u2500\u2500")}${scrollPainted}${color(`${"\u2500".repeat(leftD - leftEnd)} `)}${label}${color(` ${"\u2500".repeat(rightD)}`)}`;
|
|
735
|
-
}
|
|
736
|
-
return null;
|
|
737
|
-
}
|
|
738
|
-
return color(`${"\u2500".repeat(leftD)} `) + label + color(` ${"\u2500".repeat(rightD)}`);
|
|
739
|
-
}
|
|
740
|
-
// Right
|
|
741
|
-
if (scrollW > 0) {
|
|
742
|
-
const centerStart = Math.floor((innerW - scrollW) / 2);
|
|
743
|
-
if (centerStart + scrollW + 1 <= innerW - lw - 4) {
|
|
744
|
-
return `${color("\u2500".repeat(centerStart))}${scrollPainted}${color(`${"\u2500".repeat(innerW - lw - 4 - centerStart - scrollW)} `)}${label}${color(" \u2500\u2500")}`;
|
|
745
|
-
}
|
|
746
|
-
return null;
|
|
747
|
-
}
|
|
748
|
-
return color(`${"\u2500".repeat(innerW - lw - 4)} `) + label + color(" \u2500\u2500");
|
|
749
|
-
};
|
|
750
|
-
const placed = tryPlace(status) ?? (spinnerOnly ? tryPlace(spinnerOnly) : null);
|
|
751
|
-
if (placed) return placed;
|
|
752
|
-
const fallback = spinnerOnly || status;
|
|
753
|
-
const fw = visibleWidth(fallback);
|
|
754
|
-
if (innerW >= fw + 4) {
|
|
755
|
-
if (dialog === "Right") return color(`${"\u2500".repeat(innerW - fw - 4)} `) + fallback + color(" \u2500\u2500");
|
|
756
|
-
if (dialog === "Center") {
|
|
757
|
-
const leftD = Math.floor((innerW - fw - 2) / 2);
|
|
758
|
-
return color(`${"\u2500".repeat(leftD)} `) + fallback + color(` ${"\u2500".repeat(innerW - fw - 2 - leftD)}`);
|
|
759
|
-
}
|
|
760
|
-
return color("\u2500\u2500 ") + fallback + color(` ${"\u2500".repeat(innerW - fw - 4)}`);
|
|
761
|
-
}
|
|
762
|
-
const sw = Math.min(fw, innerW);
|
|
763
|
-
const prefixW = dialog === "Right" ? Math.max(0, innerW - sw) : dialog === "Center" ? Math.max(0, Math.floor((innerW - sw) / 2)) : Math.min(2, Math.max(0, innerW - sw));
|
|
764
|
-
return color("\u2500".repeat(prefixW)) + truncateToWidth(fallback, sw, "") + color("\u2500".repeat(Math.max(0, innerW - prefixW - sw)));
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
/** Places the active working/status dialog relative to the chatbox per the user's Dialog preset. */
|
|
768
|
-
export function applyChatboxDialog(
|
|
769
|
-
lines: readonly string[],
|
|
770
|
-
boxed: boolean,
|
|
771
|
-
width: number,
|
|
772
|
-
hiddenLineCount: number,
|
|
773
|
-
dialog: ChatboxDialog,
|
|
774
|
-
status: string,
|
|
775
|
-
spinnerOnly: string,
|
|
776
|
-
color: (text: string) => string,
|
|
777
|
-
primaryColor: (text: string) => string = (t) => t,
|
|
778
|
-
): string[] {
|
|
779
|
-
const sw = visibleWidth(status);
|
|
780
|
-
if (sw === 0 || lines.length === 0) return [...lines];
|
|
781
|
-
const out = [...lines];
|
|
782
|
-
// Outside renders onto the existing above-editor widget row (no extra line added here).
|
|
783
|
-
if (dialog === "Outside") return out;
|
|
784
|
-
if (dialog === "Inside") {
|
|
785
|
-
if (out.length < 2) return out;
|
|
786
|
-
const side = boxed ? color("\u2502") : "";
|
|
787
|
-
if (boxed && (!out[1]!.startsWith(side) || !out[1]!.endsWith(side))) return out;
|
|
788
|
-
const inner = boxed ? out[1]!.slice(side.length, out[1]!.length - side.length) : out[1]!;
|
|
789
|
-
const innerW = boxed ? width - 2 : width;
|
|
790
|
-
const trimmed = inner.replace(/ +$/, "");
|
|
791
|
-
const gap = innerW - visibleWidth(trimmed);
|
|
792
|
-
if (gap >= sw + 2) {
|
|
793
|
-
out[1] = side + trimmed + " ".repeat(gap - sw - 1) + status + " " + side;
|
|
794
|
-
} else if (innerW >= sw + 6) {
|
|
795
|
-
const kept = truncateToWidth(trimmed, innerW - sw - 2, "");
|
|
796
|
-
const pad = Math.max(1, innerW - visibleWidth(kept) - sw - 1);
|
|
797
|
-
out[1] = side + kept + " ".repeat(pad) + status + " " + side;
|
|
798
|
-
}
|
|
799
|
-
return out;
|
|
800
|
-
}
|
|
801
|
-
const innerW = boxed ? Math.max(1, width - 2) : width;
|
|
802
|
-
const topInner = formatTopBorderDialog(innerW, hiddenLineCount, dialog, status, spinnerOnly, color, primaryColor);
|
|
803
|
-
out[0] = boxed ? color("\u256d") + topInner + color("\u256e") : topInner;
|
|
804
|
-
return out;
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
/** Left-aligns the Outside dialog status in the above-editor slot with 1 blank line
|
|
808
|
-
* above and below so it never crowds adjacent messages, Todos, or the chatbox, while
|
|
809
|
-
* keeping inline notices beside it on the same row. */
|
|
810
|
-
export function overlayOutsideDialogOnWidgetLines(lines: readonly string[], width: number, status: string): string[] {
|
|
811
|
-
const sw = visibleWidth(status);
|
|
812
|
-
if (sw === 0) return [...lines];
|
|
813
|
-
const leftRow = truncateToWidth(` ${status}`, width, "");
|
|
814
|
-
if (lines.length === 0) return ["", leftRow, ""];
|
|
815
|
-
const out = [...lines];
|
|
816
|
-
const lastIdx = out.length - 1;
|
|
817
|
-
const last = out[lastIdx]!;
|
|
818
|
-
const plainLast = stripAnsi(last).trim();
|
|
819
|
-
if (plainLast.length === 0) {
|
|
820
|
-
return ["", leftRow, ""];
|
|
821
|
-
}
|
|
822
|
-
if (!/^[╭╰│]/.test(plainLast)) {
|
|
823
|
-
const trimmed = last.replace(/ +$/, "");
|
|
824
|
-
const rest = trimmed.startsWith(" ") ? trimmed : ` ${trimmed}`;
|
|
825
|
-
out[lastIdx] = truncateToWidth(` ${status} ${rest}`, width, "");
|
|
826
|
-
if (stripAnsi(out[0]!).trim().length > 0) out.unshift("");
|
|
827
|
-
out.push("");
|
|
828
|
-
return out;
|
|
829
|
-
}
|
|
830
|
-
const boxStart = out.findIndex((line) => /^[╭╰│]/.test(stripAnsi(line).trim()));
|
|
831
|
-
const prefix = out.slice(0, boxStart).filter((line) => stripAnsi(line).trim().length > 0);
|
|
832
|
-
const boxed = out.slice(boxStart);
|
|
833
|
-
return prefix.length > 0 ? ["", leftRow, "", ...prefix, "", ...boxed] : ["", leftRow, "", ...boxed];
|
|
834
|
-
}
|
|
835
|
-
|
|
836
|
-
const OUTSIDE_HOOK_KEY = Symbol.for("pi-arnative.outsideDialogHook");
|
|
837
|
-
const ABOVE_WRAPPED_KEY = Symbol.for("pi-arnative.aboveWidgetWrapped");
|
|
838
|
-
const ABOVE_MODE_KEY = Symbol.for("pi-arnative.aboveWidgetMode");
|
|
839
|
-
|
|
840
|
-
function installAboveEditorHook(widgetContainer: { render?: (w: number) => string[] } | undefined, mode: unknown): void {
|
|
841
|
-
if (!widgetContainer || typeof widgetContainer.render !== "function") return;
|
|
842
|
-
const box = widgetContainer as Record<symbol, unknown> & { render: (w: number) => string[] };
|
|
843
|
-
box[ABOVE_MODE_KEY] = mode;
|
|
844
|
-
if (box[ABOVE_WRAPPED_KEY]) return;
|
|
845
|
-
box[ABOVE_WRAPPED_KEY] = true;
|
|
846
|
-
const ownOrig = Object.hasOwn(box, "render") ? box.render : null;
|
|
847
|
-
box.render = function (this: Record<symbol, unknown>, width: number): string[] {
|
|
848
|
-
// Delegate to the live prototype render when not overridden on the instance so `/reload`
|
|
849
|
-
// changes to Container.prototype.render still apply without touching prototype originals.
|
|
850
|
-
const baseRender = ownOrig ?? (Object.getPrototypeOf(this) as { render: (w: number) => string[] }).render;
|
|
851
|
-
const lines = baseRender.call(this, width);
|
|
852
|
-
try {
|
|
853
|
-
const hook = (globalThis as Record<symbol, ((l: string[], w: number, m: unknown) => string[]) | undefined>)[OUTSIDE_HOOK_KEY];
|
|
854
|
-
return hook ? hook(lines, width, this[ABOVE_MODE_KEY]) : lines;
|
|
855
|
-
} catch {
|
|
856
|
-
return lines;
|
|
857
|
-
}
|
|
858
|
-
};
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
if (InteractiveMode?.prototype) {
|
|
862
|
-
const modeProto = InteractiveMode.prototype as unknown as {
|
|
863
|
-
renderWidgetContainer?: (container: unknown, widgets: unknown, spacerWhenEmpty: boolean, leadingSpacer: boolean) => void;
|
|
864
|
-
showStatusIndicator?: (indicator: unknown) => void;
|
|
865
|
-
};
|
|
866
|
-
if (typeof modeProto.renderWidgetContainer === "function") {
|
|
867
|
-
patchOnce(modeProto, "renderWidgetContainer", (orig) => function (
|
|
868
|
-
this: any,
|
|
869
|
-
container: unknown,
|
|
870
|
-
widgets: unknown,
|
|
871
|
-
spacerWhenEmpty: boolean,
|
|
872
|
-
leadingSpacer: boolean,
|
|
873
|
-
): void {
|
|
874
|
-
if (container && container === this.widgetContainerAbove) {
|
|
875
|
-
installAboveEditorHook(container as { render?: (w: number) => string[] }, this);
|
|
876
|
-
}
|
|
877
|
-
orig.call(this, container, widgets, spacerWhenEmpty, leadingSpacer);
|
|
878
|
-
});
|
|
879
|
-
}
|
|
880
|
-
if (typeof modeProto.showStatusIndicator === "function") {
|
|
881
|
-
patchOnce(modeProto, "showStatusIndicator", (orig) => function (this: any, indicator: unknown): void {
|
|
882
|
-
installAboveEditorHook(this.widgetContainerAbove, this);
|
|
883
|
-
orig.call(this, indicator);
|
|
884
|
-
});
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
|
|
888
|
-
/**
|
|
889
|
-
* The footer as a fixed 3-row grid. Row 1 pairs the head cells (cwd line, model);
|
|
890
|
-
* rows 2-3 pair the wrapped left cells (extension status, mcp first) with the
|
|
891
|
-
* wrapped right cells (tok/s · cache · token), each side wrapping inside its half
|
|
892
|
-
* of the terminal so the columns never collide. Right cells stay right-aligned.
|
|
893
|
-
* A side that runs out of cells leaves its half blank, and a row where both sides
|
|
894
|
-
* ran out is dropped, so a quiet footer stays 1-3 rows tall.
|
|
895
|
-
*/
|
|
896
|
-
export function layoutFooterGrid(
|
|
897
|
-
headLeft: string,
|
|
898
|
-
headRight: string,
|
|
899
|
-
left: readonly string[],
|
|
900
|
-
right: readonly string[],
|
|
901
|
-
leftSep: string,
|
|
902
|
-
rightSep: string,
|
|
903
|
-
width: number,
|
|
904
|
-
vw: (s: string) => number = visibleWidth,
|
|
905
|
-
): string[] {
|
|
906
|
-
const half = Math.max(1, Math.floor(width / 2) - 1);
|
|
907
|
-
// Wrap each side at half width; the first break happens at most once (rows 2-3),
|
|
908
|
-
// after that the rest stays on the last row and the pairing truncates it.
|
|
909
|
-
const wrap = (cells: readonly string[], sep: string): string[] => {
|
|
910
|
-
const rows: string[] = [];
|
|
911
|
-
let line = "";
|
|
912
|
-
for (const cell of cells) {
|
|
913
|
-
const candidate = line ? line + sep + cell : cell;
|
|
914
|
-
if (line && rows.length === 0 && vw(candidate) > half) {
|
|
915
|
-
rows.push(line);
|
|
916
|
-
line = cell;
|
|
917
|
-
} else {
|
|
918
|
-
line = candidate;
|
|
919
|
-
}
|
|
920
|
-
}
|
|
921
|
-
if (line) rows.push(line);
|
|
922
|
-
return rows;
|
|
923
|
-
};
|
|
924
|
-
const leftRows = wrap(left, leftSep);
|
|
925
|
-
const rightRows = wrap(right, rightSep);
|
|
926
|
-
const out = [pairRow(headLeft, headRight, width, vw)];
|
|
927
|
-
for (let i = 0; i < Math.max(leftRows.length, rightRows.length); i++) {
|
|
928
|
-
const l = leftRows[i];
|
|
929
|
-
const r = rightRows[i];
|
|
930
|
-
if (l === undefined && r === undefined) break;
|
|
931
|
-
out.push(pairRow(l ?? "", r ?? "", width, vw));
|
|
932
|
-
}
|
|
933
|
-
return out;
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
/** One grid row: `left` at the start, `right` flush to the right edge. */
|
|
937
|
-
function pairRow(left: string, right: string, width: number, vw: (s: string) => number): string {
|
|
938
|
-
if (!right) return truncateToWidth(left, width);
|
|
939
|
-
const rightWidth = Math.min(vw(right), width);
|
|
940
|
-
if (!left) return " ".repeat(width - rightWidth) + truncateToWidth(right, width);
|
|
941
|
-
if (vw(left) + 1 + rightWidth <= width) {
|
|
942
|
-
return left + " ".repeat(width - vw(left) - rightWidth) + right;
|
|
943
|
-
}
|
|
944
|
-
// Too wide together: the right cell keeps its columns, the left one is cut.
|
|
945
|
-
const room = Math.max(1, width - rightWidth - 1);
|
|
946
|
-
return truncateToWidth(left, room) + " " + truncateToWidth(right, width - room - 1);
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
function parseOptimizer(raw: string | undefined): string | null {
|
|
950
|
-
|
|
951
|
-
if (!raw) return null;
|
|
952
|
-
const m = raw.match(/([A-Za-z0-9_-]+)\s+cache\s+(\d+\/\d+)·[^\s]+\s+([\d.]+%)/);
|
|
953
|
-
return m ? `${m[1]} ${m[2]} (${m[3]})` : null;
|
|
954
|
-
}
|
|
955
|
-
|
|
956
|
-
// Pi's own per-message usage: shown when pi-cache-optimizer has no adapter for the
|
|
957
|
-
// provider (a custom one like mytool.ts publishes no pi-cache-stats status).
|
|
958
|
-
// The denominator (`input + cacheRead`) includes tool-result (child) tokens, because the ↑
|
|
959
|
-
// cell above is total spend — the hit rate is measured against the same total, so do not
|
|
960
|
-
// "fix" the denominator back to assistant messages only.
|
|
961
|
-
let usageTotals = { inp: 0, read: 0 };
|
|
962
|
-
export function piCacheHit(): string | null {
|
|
963
|
-
const total = usageTotals.inp + usageTotals.read;
|
|
964
|
-
return total > 0 ? "pi " + ((usageTotals.read / total) * 100).toFixed(1) + "%" : null;
|
|
965
|
-
}
|
|
966
|
-
|
|
967
|
-
// The cache cell's COLOUR comes from a recent window, not the session-wide rate above: the
|
|
968
|
-
// last CACHE_WINDOW_MSGS assistant messages, with the session's first two always skipped
|
|
969
|
-
// (turn 1 is a cold cache, so colouring it would cry wolf on every session). The `pi …%`
|
|
970
|
-
// text stays session-wide; only the colour is windowed.
|
|
971
|
-
export const CACHE_WINDOW_MSGS = 10;
|
|
972
|
-
/** Windowed (input, cacheRead) sums of the last scan — read by the render for the colour. */
|
|
973
|
-
let usageWindow = { inp: 0, read: 0 };
|
|
974
|
-
|
|
975
|
-
export type CacheHitBand = "soft" | "warning" | "error";
|
|
976
|
-
/** Colour band of a windowed cache-hit rate: ≥70% keeps the current soft tier, 40–70% is
|
|
977
|
-
* amber (the theme's `warning` slot), below 40% is red (`error`). No rate yet (fewer than
|
|
978
|
-
* 3 assistant messages, so an empty window) stays soft. */
|
|
979
|
-
export function cacheHitBand(winInp: number, winRead: number): CacheHitBand {
|
|
980
|
-
const total = winInp + winRead;
|
|
981
|
-
if (total <= 0) return "soft";
|
|
982
|
-
const rate = winRead / total;
|
|
983
|
-
if (rate >= 0.7) return "soft";
|
|
984
|
-
if (rate >= 0.4) return "warning";
|
|
985
|
-
return "error";
|
|
986
|
-
}
|
|
987
|
-
|
|
988
|
-
let usageScanAt = 0;
|
|
989
|
-
let usageScanLen = -1;
|
|
990
|
-
interface UsageTotals {
|
|
991
|
-
inp: number;
|
|
992
|
-
out: number;
|
|
993
|
-
read: number;
|
|
994
|
-
/** Sum of `cost.total` over the messages the provider billed (`totalFromProvider`). */
|
|
995
|
-
costBilled: number;
|
|
996
|
-
/** Everything else: catalog totals, plus a price-table reconstruction for messages that
|
|
997
|
-
* carried no cost at all. Never blended into `costBilled`. */
|
|
998
|
-
costEstimated: number;
|
|
999
|
-
/** Only set on the branch-last snapshot (`lastUsageOf`): that entry is an assistant message. */
|
|
1000
|
-
assistant?: boolean;
|
|
1001
|
-
}
|
|
1002
|
-
|
|
1003
|
-
let usageScanManager: object | undefined;
|
|
1004
|
-
let usageScanLeaf: unknown;
|
|
1005
|
-
// A stream mutates the same leaf, so its delta updates the cached prefix. A different
|
|
1006
|
-
// manager or leaf must rescan: equal-length /tree branches can have different usage.
|
|
1007
|
-
|
|
1008
|
-
let usageScanNums: UsageTotals = { inp: 0, out: 0, read: 0, costBilled: 0, costEstimated: 0 };
|
|
1009
|
-
// Usage of the branch's last entry at scan time (assistant or tool result): a stream tick
|
|
1010
|
-
// mutates that entry in place (branch length unchanged), so the delta is applied on top of
|
|
1011
|
-
// the cached sums — O(1) per frame, numbers always fresh, still no O(N) rescan per frame.
|
|
1012
|
-
let usageScanLast: UsageTotals = { inp: 0, out: 0, read: 0, costBilled: 0, costEstimated: 0 };
|
|
1013
|
-
// Windowed sums at scan time, plus the window contribution of the branch's last entry
|
|
1014
|
-
// (`null` when that entry is not an assistant message inside the window): the in-place
|
|
1015
|
-
// delta of a stream tick lands in the window exactly when the last entry is one.
|
|
1016
|
-
let usageScanWin = { inp: 0, read: 0 };
|
|
1017
|
-
let usageScanWinLast: { inp: number; read: number } | null = null;
|
|
1018
|
-
|
|
1019
|
-
type MessageUsage = {
|
|
1020
|
-
input?: number;
|
|
1021
|
-
output?: number;
|
|
1022
|
-
cacheRead?: number;
|
|
1023
|
-
cacheWrite?: number;
|
|
1024
|
-
cost?: { total?: number; totalFromProvider?: boolean };
|
|
1025
|
-
/** Only set by a tool that names what produced its own usage; absent on the main LLM calls. */
|
|
1026
|
-
provider?: string;
|
|
1027
|
-
model?: string;
|
|
1028
|
-
};
|
|
1029
|
-
|
|
1030
|
-
/** True when a usage object carries any countable field: a tool result without usage (or with
|
|
1031
|
-
* an all-zero one) adds nothing to the sums. */
|
|
1032
|
-
const hasUsage = (u: MessageUsage | undefined): u is MessageUsage =>
|
|
1033
|
-
!!u && !!((u.input || 0) || (u.output || 0) || (u.cacheRead || 0) || (u.cacheWrite || 0) || (u.cost?.total || 0));
|
|
1034
|
-
|
|
1035
|
-
/** Attribution of one branch message's usage: a tool result's usage names no provider/model,
|
|
1036
|
-
* so it is attributed to the tool itself (`tool` · toolName), never to the parent's model. */
|
|
1037
|
-
/** A tool result names no provider/model: it is attributed to the tool itself, never to the
|
|
1038
|
-
* parent's model. pi-subagents does not set `totalFromProvider` on that usage, so child spend
|
|
1039
|
-
* always lands in the estimated part of the cell (`~`) even when the children were billed. */
|
|
1040
|
-
const attributionOf = (
|
|
1041
|
-
m: { role: string; provider?: string; model?: string; toolName?: string },
|
|
1042
|
-
u: MessageUsage,
|
|
1043
|
-
): { provider: string | undefined; model: string | undefined } =>
|
|
1044
|
-
m.role === "toolResult"
|
|
1045
|
-
? { provider: u.provider ?? TOOL_PROVIDER, model: u.model ?? m.toolName ?? TOOL_PROVIDER }
|
|
1046
|
-
: { provider: m.provider, model: m.model };
|
|
1047
|
-
|
|
1048
|
-
/** Billed vs estimated split of one message's usage: a provider-billed total goes to
|
|
1049
|
-
* `costBilled`, a catalog total (pi's own estimate) to `costEstimated`, and a message that
|
|
1050
|
-
* carried no cost at all is recomputed from the price table, cache writes included. */
|
|
1051
|
-
const costSplitOf = (
|
|
1052
|
-
u: MessageUsage,
|
|
1053
|
-
provider: string | undefined,
|
|
1054
|
-
model: string | undefined,
|
|
1055
|
-
table: PriceTable,
|
|
1056
|
-
): { costBilled: number; costEstimated: number } => {
|
|
1057
|
-
const total = u.cost?.total || 0;
|
|
1058
|
-
if (u.cost?.totalFromProvider === true) return { costBilled: total, costEstimated: 0 };
|
|
1059
|
-
if (total > 0) return { costBilled: 0, costEstimated: total };
|
|
1060
|
-
const est = provider && model ? estimateCost(u.input || 0, u.output || 0, u.cacheRead || 0, u.cacheWrite || 0, model, provider, table) : null;
|
|
1061
|
-
return { costBilled: 0, costEstimated: est ?? 0 };
|
|
1062
|
-
};
|
|
1063
|
-
|
|
1064
|
-
const lastUsageOf = (branch: readonly unknown[], table: PriceTable): UsageTotals => {
|
|
1065
|
-
const zeros: UsageTotals = { inp: 0, out: 0, read: 0, costBilled: 0, costEstimated: 0 };
|
|
1066
|
-
const last = branch[branch.length - 1] as
|
|
1067
|
-
| {
|
|
1068
|
-
type?: string;
|
|
1069
|
-
message?: { role?: string; provider?: string; model?: string; toolName?: string; usage?: MessageUsage };
|
|
1070
|
-
}
|
|
1071
|
-
| undefined;
|
|
1072
|
-
const m = last?.type === "message" ? last.message : undefined;
|
|
1073
|
-
const role = m?.role;
|
|
1074
|
-
const assistant = role === "assistant";
|
|
1075
|
-
const u = role === "assistant" || role === "toolResult" ? m!.usage : undefined;
|
|
1076
|
-
if (!hasUsage(u)) {
|
|
1077
|
-
zeros.assistant = assistant;
|
|
1078
|
-
return zeros;
|
|
1079
|
-
}
|
|
1080
|
-
const { provider, model } = attributionOf(m!, u);
|
|
1081
|
-
const { costBilled, costEstimated } = costSplitOf(u, provider, model, table);
|
|
1082
|
-
return { inp: u.input || 0, out: u.output || 0, read: u.cacheRead || 0, costBilled, costEstimated, assistant };
|
|
1083
|
-
};
|
|
1084
|
-
|
|
1085
|
-
/** No burn rate below five minutes of active time: dividing a two-minute clock prints nonsense. */
|
|
1086
|
-
export const RATE_MIN_ACTIVE_MS = 5 * 60_000;
|
|
1087
|
-
/** Terminals narrower than this drop the rate — the cost alone still fits. */
|
|
1088
|
-
export const RATE_MIN_WIDTH = 80;
|
|
1089
|
-
|
|
1090
|
-
/** The session cost cell, with the burn rate appended in parentheses (one cell, not two): `$0.42 ($1.80/h)`.
|
|
1091
|
-
* Billed and estimated never blend: `$0.42` when only the provider billed, `~$0.42` when only
|
|
1092
|
-
* an estimate exists, `$0.30 + ~$0.12` when the branch has both, and no cell at all when there
|
|
1093
|
-
* is no cost — the same promise `/usage` makes. The rate is cost per ACTIVE hour — the clock
|
|
1094
|
-
* counts active time (idle pauses excluded), not wall-clock — so it is labelled `$/h`; it
|
|
1095
|
-
* carries the `~` whenever estimated cost feeds it, like the estimated part of the cell, and
|
|
1096
|
-
* is hidden below RATE_MIN_ACTIVE_MS of active time and below RATE_MIN_WIDTH columns.
|
|
1097
|
-
* `bandPaint` paints the whole cell (icon and text) when a budget cap is near or over —
|
|
1098
|
-
* amber at `warn`, red at `over` (see `budgetLevelNow`); without it the icon keeps `acc` and
|
|
1099
|
-
* the text `soft`. The rate suffix is secondary information, so it renders `dim` (or the band
|
|
1100
|
-
* paint when a cap is active, keeping the alert one colour). */
|
|
1101
|
-
export function costCell(
|
|
1102
|
-
costBilled: number,
|
|
1103
|
-
costEstimated: number,
|
|
1104
|
-
acc: (t: string) => string,
|
|
1105
|
-
soft: (t: string) => string,
|
|
1106
|
-
width: number = RATE_MIN_WIDTH,
|
|
1107
|
-
bandPaint?: (t: string) => string,
|
|
1108
|
-
dim?: (t: string) => string,
|
|
1109
|
-
): string {
|
|
1110
|
-
if (!(costBilled > 0) && !(costEstimated > 0)) return "";
|
|
1111
|
-
const parts: string[] = [];
|
|
1112
|
-
if (costBilled > 0) parts.push(formatCost(costBilled));
|
|
1113
|
-
if (costEstimated > 0) parts.push(`~${formatCost(costEstimated)}`);
|
|
1114
|
-
const text = parts.join(" + ");
|
|
1115
|
-
let rate = "";
|
|
1116
|
-
const activeMs = clock.total();
|
|
1117
|
-
if (activeMs >= RATE_MIN_ACTIVE_MS && width >= RATE_MIN_WIDTH) {
|
|
1118
|
-
const perHour = (costBilled + costEstimated) / (activeMs / 3_600_000);
|
|
1119
|
-
rate = `(${costEstimated > 0 ? "~" : ""}${formatCost(perHour)}/h)`;
|
|
1120
|
-
}
|
|
1121
|
-
const cell = `${(bandPaint ?? acc)("\uf155")} ${(bandPaint ?? soft)(text)}`;
|
|
1122
|
-
return rate ? `${cell} ${(bandPaint ?? dim ?? soft)(rate)}` : cell;
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
// 2s cache + branch length: the footer renders on every poke/stream tick, so
|
|
1126
|
-
// without this every frame rescans the whole branch (O(N) per frame).
|
|
1127
|
-
export function getUsage(
|
|
1128
|
-
ctx: {
|
|
1129
|
-
sessionManager: { getBranch(): readonly unknown[] };
|
|
1130
|
-
getContextUsage(): { tokens: number | null; contextWindow: number; percent: number | null } | undefined;
|
|
1131
|
-
model?: { id?: string; provider?: string };
|
|
1132
|
-
},
|
|
1133
|
-
acc: (t: string) => string,
|
|
1134
|
-
soft: (t: string) => string,
|
|
1135
|
-
/** Off by default: the cost cell is opt-in (`/arnative` → Footers → `[c]`). */
|
|
1136
|
-
showCost: boolean = activeFooterCost(),
|
|
1137
|
-
/** Terminal width: the burn rate is dropped below RATE_MIN_WIDTH columns. */
|
|
1138
|
-
width: number = RATE_MIN_WIDTH,
|
|
1139
|
-
/** Budget band painter for the cost cell (amber at `warn`, red at `over`); absent keeps acc/soft. */
|
|
1140
|
-
bandPaint?: (t: string) => string,
|
|
1141
|
-
/** Painter for the divider that opens the cost group; the caller passes the footer `dim`. */
|
|
1142
|
-
dim: (t: string) => string = soft,
|
|
1143
|
-
): string {
|
|
1144
|
-
const branch = ctx.sessionManager.getBranch();
|
|
1145
|
-
// Memoized on models.json's stat, so this is one statSync per frame, not a read.
|
|
1146
|
-
const priceTable = loadPriceTable();
|
|
1147
|
-
const leaf = branch[branch.length - 1];
|
|
1148
|
-
const last = lastUsageOf(branch, priceTable);
|
|
1149
|
-
let inp = 0;
|
|
1150
|
-
let out = 0;
|
|
1151
|
-
let read = 0;
|
|
1152
|
-
let costBilled = 0;
|
|
1153
|
-
let costEstimated = 0;
|
|
1154
|
-
let winInp = 0;
|
|
1155
|
-
let winRead = 0;
|
|
1156
|
-
if (Date.now() - usageScanAt < 2000 && branch.length === usageScanLen && ctx.sessionManager === usageScanManager && leaf === usageScanLeaf) {
|
|
1157
|
-
// Cached sums + the streaming delta of the last message (mutated in place).
|
|
1158
|
-
inp = usageScanNums.inp + last.inp - usageScanLast.inp;
|
|
1159
|
-
out = usageScanNums.out + last.out - usageScanLast.out;
|
|
1160
|
-
read = usageScanNums.read + last.read - usageScanLast.read;
|
|
1161
|
-
costBilled = usageScanNums.costBilled + last.costBilled - usageScanLast.costBilled;
|
|
1162
|
-
costEstimated = usageScanNums.costEstimated + last.costEstimated - usageScanLast.costEstimated;
|
|
1163
|
-
// The window covers assistant messages only, so the in-place delta of the last
|
|
1164
|
-
// entry lands in it exactly when that entry is an assistant message in the window.
|
|
1165
|
-
winInp = usageScanWin.inp + (usageScanWinLast ? last.inp - usageScanWinLast.inp : 0);
|
|
1166
|
-
winRead = usageScanWin.read + (usageScanWinLast ? last.read - usageScanWinLast.read : 0);
|
|
1167
|
-
} else {
|
|
1168
|
-
// (input, cacheRead) of the trailing assistant messages, capped so the window below
|
|
1169
|
-
// is the last CACHE_WINDOW_MSGS of them once the first two are skipped.
|
|
1170
|
-
const assist: [number, number][] = [];
|
|
1171
|
-
for (const e of branch) {
|
|
1172
|
-
if (!e || typeof e !== "object" || !("type" in e) || e.type !== "message") continue;
|
|
1173
|
-
const m = (e as { message?: unknown }).message as
|
|
1174
|
-
| { role?: string; provider?: string; model?: string; toolName?: string; usage?: MessageUsage }
|
|
1175
|
-
| undefined;
|
|
1176
|
-
// Assistant messages carry their own call's usage; a tool result carries the child
|
|
1177
|
-
// (subagent / nested tool) spend — pi puts that nowhere else, so summing both roles
|
|
1178
|
-
// counts every token once, never twice.
|
|
1179
|
-
if (!m || (m.role !== "assistant" && m.role !== "toolResult")) continue;
|
|
1180
|
-
const u = m.usage;
|
|
1181
|
-
if (m.role === "assistant") {
|
|
1182
|
-
assist.push([u?.input || 0, u?.cacheRead || 0]);
|
|
1183
|
-
if (assist.length > CACHE_WINDOW_MSGS + 2) assist.shift();
|
|
1184
|
-
}
|
|
1185
|
-
if (!hasUsage(u)) continue;
|
|
1186
|
-
inp += u.input || 0;
|
|
1187
|
-
out += u.output || 0;
|
|
1188
|
-
read += u.cacheRead || 0;
|
|
1189
|
-
const { provider, model } = attributionOf(m, u);
|
|
1190
|
-
const split = costSplitOf(u, provider, model, priceTable);
|
|
1191
|
-
costBilled += split.costBilled;
|
|
1192
|
-
costEstimated += split.costEstimated;
|
|
1193
|
-
}
|
|
1194
|
-
usageScanNums = { inp, out, read, costBilled, costEstimated };
|
|
1195
|
-
usageScanLast = last;
|
|
1196
|
-
usageScanAt = Date.now();
|
|
1197
|
-
usageScanLen = branch.length;
|
|
1198
|
-
// Windowed cache rate, computed in this same pass: the last CACHE_WINDOW_MSGS
|
|
1199
|
-
// assistant messages, the session's first two skipped (turn 1 is always cold).
|
|
1200
|
-
const win = assist.slice(Math.max(2, assist.length - CACHE_WINDOW_MSGS));
|
|
1201
|
-
for (const [wi, wr] of win) {
|
|
1202
|
-
winInp += wi;
|
|
1203
|
-
winRead += wr;
|
|
1204
|
-
}
|
|
1205
|
-
usageScanWin = { inp: winInp, read: winRead };
|
|
1206
|
-
usageScanWinLast = last.assistant === true && assist.length > 2 ? { inp: last.inp, read: last.read } : null;
|
|
1207
|
-
usageScanManager = ctx.sessionManager;
|
|
1208
|
-
usageScanLeaf = leaf;
|
|
1209
|
-
}
|
|
1210
|
-
usageTotals = { inp, read };
|
|
1211
|
-
usageWindow = { inp: winInp, read: winRead };
|
|
1212
|
-
const parts: string[] = [];
|
|
1213
|
-
if (inp > 0) parts.push(`${acc("↑")}${soft(formatTokens(inp))}`);
|
|
1214
|
-
if (out > 0) parts.push(`${acc("↓")}${soft(formatTokens(out))}`);
|
|
1215
|
-
if (read > 0) parts.push(`${acc("\uf49b")} ${soft(formatTokens(read))}`);
|
|
1216
|
-
const u = ctx.getContextUsage();
|
|
1217
|
-
if (u && u.percent !== null && u.tokens !== null) {
|
|
1218
|
-
parts.push(`${acc("\ueb85")} ${soft(`${u.percent.toFixed(1)}%/${formatTokens(u.contextWindow)}`)}`);
|
|
1219
|
-
}
|
|
1220
|
-
if (showCost) {
|
|
1221
|
-
const cell = costCell(costBilled, costEstimated, acc, soft, width, bandPaint, dim);
|
|
1222
|
-
// The dollar icon opens a new group, so it takes the same divider the footer uses
|
|
1223
|
-
// between cells; the token and context parts stay a space apart.
|
|
1224
|
-
if (cell) parts.push(parts.length > 0 ? `${dim("·")} ${cell}` : cell);
|
|
1225
|
-
}
|
|
1226
|
-
return parts.join(" ");
|
|
1227
|
-
}
|
|
1228
|
-
|
|
1229
|
-
let editorTui: { requestRender?: () => void } | null = null;
|
|
1230
|
-
|
|
1231
|
-
function poke(): void {
|
|
1232
|
-
try {
|
|
1233
|
-
if (rerender) rerender();
|
|
1234
|
-
else editorTui?.requestRender?.();
|
|
1235
|
-
} catch {
|
|
1236
|
-
// ignore
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
|
|
1240
|
-
/**
|
|
1241
|
-
* Tool name → active progress text (gerund).
|
|
1242
|
-
* Fallback when unregistered: "Working".
|
|
1243
|
-
*/
|
|
1244
|
-
// Verb for an MCP sub-action (shared by the `mcp` and `mcp__*` tool names).
|
|
1245
|
-
function mcpStatusOf(sub: string): string {
|
|
1246
|
-
if (sub.includes("search") || sub.includes("find")) return "Searching";
|
|
1247
|
-
if (sub.includes("fetch") || sub.includes("get") || sub.includes("read")) return "Fetching";
|
|
1248
|
-
if (sub.includes("edit") || sub.includes("write") || sub.includes("patch")) return "Editing";
|
|
1249
|
-
return "Executing";
|
|
1250
|
-
}
|
|
1251
|
-
|
|
1252
|
-
/**
|
|
1253
|
-
* The spinner is one preset out of `lib/spinner.ts`, chosen through `/arnative` →
|
|
1254
|
-
* **Animations** and persisted in `arnative-config.json`. `Pi (system)` hands the slot back
|
|
1255
|
-
* to pi's own Braille indicator; every other preset installs its own frames and painter.
|
|
1256
|
-
* The frames are read fresh on each `session_start`, so a preset picked mid-session applies
|
|
1257
|
-
* on the next reload without re-registering the handler.
|
|
1258
|
-
*/
|
|
1259
|
-
/** Loader label with the elapsed suffix; no suffix below 1s (avoids a "(0s)" flicker). */
|
|
1260
|
-
export function workingLabel(verb: string, elapsedMs: number): string {
|
|
1261
|
-
return elapsedMs >= 1000 ? `${verb} (${formatDuration(elapsedMs)})` : verb;
|
|
1262
|
-
}
|
|
1263
|
-
|
|
1264
|
-
function paintWorking(): void {
|
|
1265
|
-
if (!workUI || workStartMs === null) return;
|
|
1266
|
-
try {
|
|
1267
|
-
workUI.setWorkingMessage?.(workingLabel(workVerb, Date.now() - workStartMs));
|
|
1268
|
-
} catch {
|
|
1269
|
-
// ignore
|
|
1270
|
-
}
|
|
1271
|
-
}
|
|
1272
|
-
|
|
1273
|
-
function stopWorkingClock(): void {
|
|
1274
|
-
const t = (globalThis as Record<symbol, any>)[WORK_TIMER_KEY];
|
|
1275
|
-
if (t) clearInterval(t);
|
|
1276
|
-
(globalThis as Record<symbol, any>)[WORK_TIMER_KEY] = null;
|
|
1277
|
-
workStartMs = null;
|
|
1278
|
-
workUI = null;
|
|
1279
|
-
activeToolVerbs.clear();
|
|
1280
|
-
}
|
|
1281
|
-
|
|
1282
|
-
let idleProbe: ReturnType<typeof setTimeout> | null = null;
|
|
1283
|
-
let idlePauseShown = false;
|
|
1284
|
-
let clockTick: ReturnType<typeof setInterval> | null = null;
|
|
1285
|
-
|
|
1286
|
-
/** 1s repaint ticker while clock is active. Stops when idle. */
|
|
1287
|
-
function startClockTick(): void {
|
|
1288
|
-
if (clockTick !== null) return;
|
|
1289
|
-
clockTick = setInterval(() => {
|
|
1290
|
-
if (clock.idle()) return stopClockTick();
|
|
1291
|
-
poke();
|
|
1292
|
-
}, 1000);
|
|
1293
|
-
(globalThis as Record<symbol, any>)[CLOCK_TIMER_KEY] = clockTick;
|
|
1294
|
-
}
|
|
1295
|
-
|
|
1296
|
-
function stopClockTick(): void {
|
|
1297
|
-
if (clockTick) clearInterval(clockTick);
|
|
1298
|
-
clockTick = null;
|
|
1299
|
-
(globalThis as Record<symbol, any>)[CLOCK_TIMER_KEY] = null;
|
|
1300
|
-
}
|
|
1301
|
-
|
|
1302
|
-
/** Repaint a frozen clock on the first activity, instead of waiting for the next tick. */
|
|
1303
|
-
export function repaintIdle(now: number = Date.now()): void {
|
|
1304
|
-
if (!clock.idle(now) || idlePauseShown) return;
|
|
1305
|
-
poke();
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
/** Pointer motion and terminal focus reports are not user activity. */
|
|
1309
|
-
export function isPointerOrFocusInput(data: string): boolean {
|
|
1310
|
-
return data.startsWith("\x1b[<") || data.startsWith("\x1b[M") || data === "\x1b[I" || data === "\x1b[O";
|
|
1311
|
-
}
|
|
1312
|
-
|
|
1313
|
-
/** Intercepts terminal input on TuiBase to register keystroke activity. */
|
|
1314
|
-
const WRAPPED_TUI_KEY = Symbol.for("pi-arnative.inputDispatchWrapped");
|
|
1315
|
-
const ACTIVITY_HOOK_KEY = Symbol.for("pi-arnative.activityHook");
|
|
1316
|
-
|
|
1317
|
-
export function wrapInputListener(tui: unknown): () => void {
|
|
1318
|
-
(globalThis as Record<symbol, any>)[ACTIVITY_HOOK_KEY] = (data: string) => {
|
|
1319
|
-
if (isPointerOrFocusInput(data)) return;
|
|
1320
|
-
clock.tick();
|
|
1321
|
-
repaintIdle();
|
|
1322
|
-
armIdleProbe();
|
|
1323
|
-
};
|
|
1324
|
-
const target = tui as { handleTerminalInput?: (data: string) => void };
|
|
1325
|
-
if (!target || typeof target.handleTerminalInput !== "function") return () => {};
|
|
1326
|
-
const g = globalThis as Record<symbol, unknown>;
|
|
1327
|
-
const wrapped = g[WRAPPED_TUI_KEY] instanceof WeakSet ? (g[WRAPPED_TUI_KEY] as WeakSet<object>) : (g[WRAPPED_TUI_KEY] = new WeakSet<object>());
|
|
1328
|
-
if (!wrapped.has(target)) {
|
|
1329
|
-
wrapped.add(target);
|
|
1330
|
-
const original = target.handleTerminalInput;
|
|
1331
|
-
target.handleTerminalInput = function (this: unknown, data: string): void {
|
|
1332
|
-
// One keystroke, one activity. The wrapper runs before `original`, and `pi-tui`
|
|
1333
|
-
// has a single caller for it (`terminal.start`), so there is nothing to dedupe.
|
|
1334
|
-
try {
|
|
1335
|
-
(globalThis as Record<symbol, any>)[ACTIVITY_HOOK_KEY]?.(data);
|
|
1336
|
-
} catch {
|
|
1337
|
-
// activity bookkeeping must never break input
|
|
1338
|
-
}
|
|
1339
|
-
original.call(this, data);
|
|
1340
|
-
};
|
|
1341
|
-
}
|
|
1342
|
-
return () => {
|
|
1343
|
-
// Only the hook is torn down; the wrapper stays, since a reload re-registers it.
|
|
1344
|
-
(globalThis as Record<symbol, any>)[ACTIVITY_HOOK_KEY] = null;
|
|
1345
|
-
};
|
|
1346
|
-
}
|
|
1347
|
-
|
|
1348
|
-
/** Past the boundary, where `idle()` is still false because it is a strict `>` (~one frame). */
|
|
1349
|
-
const IDLE_PROBE_EPSILON_MS = 25;
|
|
1350
|
-
|
|
1351
|
-
export function armIdleProbe(now: number = Date.now()): void {
|
|
1352
|
-
startClockTick();
|
|
1353
|
-
if (idleProbe) clearTimeout(idleProbe);
|
|
1354
|
-
const wait = Math.max(0, clock.pauseMs - (now - clock.lastSeen)) + IDLE_PROBE_EPSILON_MS;
|
|
1355
|
-
idleProbe = setTimeout(() => {
|
|
1356
|
-
idleProbe = null;
|
|
1357
|
-
(globalThis as Record<symbol, any>)[IDLE_TIMER_KEY] = null;
|
|
1358
|
-
if (!clock.idle()) return; // activity raced the probe: it re-armed itself
|
|
1359
|
-
idlePauseShown = true;
|
|
1360
|
-
stopClockTick();
|
|
1361
|
-
poke();
|
|
1362
|
-
}, wait);
|
|
1363
|
-
(globalThis as Record<symbol, any>)[IDLE_TIMER_KEY] = idleProbe;
|
|
1364
|
-
poke();
|
|
1365
|
-
}
|
|
1366
|
-
|
|
1367
|
-
/** Stop the idle machinery: the one-shot probe and the moving clock tick. */
|
|
1368
|
-
export function stopIdleProbe(): void {
|
|
1369
|
-
if (idleProbe) clearTimeout(idleProbe);
|
|
1370
|
-
idleProbe = null;
|
|
1371
|
-
stopClockTick();
|
|
1372
|
-
(globalThis as Record<symbol, any>)[IDLE_TIMER_KEY] = null;
|
|
1373
|
-
}
|
|
1374
|
-
|
|
1375
|
-
/** Start (or restart) the 1s tick from a fresh turn. */
|
|
1376
|
-
function startWorkingClock(ctx: { ui?: any }): void {
|
|
1377
|
-
stopWorkingClock();
|
|
1378
|
-
workUI = ctx.ui ?? null;
|
|
1379
|
-
workVerb = WORK_LABEL;
|
|
1380
|
-
workStartMs = Date.now();
|
|
1381
|
-
(globalThis as Record<symbol, any>)[WORK_TIMER_KEY] = setInterval(paintWorking, 1000);
|
|
1382
|
-
}
|
|
1383
|
-
|
|
1384
|
-
/** Swap the verb (tool change) without resetting the turn clock. */
|
|
1385
|
-
function setWorkingVerb(ctx: { ui?: any }, verb: string): void {
|
|
1386
|
-
workUI = ctx.ui ?? null;
|
|
1387
|
-
workVerb = verb;
|
|
1388
|
-
if (workStartMs === null) workStartMs = Date.now();
|
|
1389
|
-
paintWorking();
|
|
1390
|
-
}
|
|
1391
|
-
|
|
1392
|
-
export function getToolWorkingMessage(toolName: string, args?: any): string {
|
|
1393
|
-
const n = (toolName ?? "").trim();
|
|
1394
|
-
if (!n) return WORK_LABEL;
|
|
1395
|
-
|
|
1396
|
-
// Standard / file tools
|
|
1397
|
-
if (n === "edit") return "Editing";
|
|
1398
|
-
if (n === "write") return "Writing";
|
|
1399
|
-
if (n === "read") return "Reading";
|
|
1400
|
-
if (n === "grep" || n === "find" || n === "web_search" || n === "source_check") return "Searching";
|
|
1401
|
-
if (n === "bash") return "Executing";
|
|
1402
|
-
if (n === "fetch_content") return "Fetching";
|
|
1403
|
-
if (n === "get_search_content") return "Reading";
|
|
1404
|
-
if (n === "generate_image") return "Generating image";
|
|
1405
|
-
if (n === "todo" || n === "scratchpad") return "Updating tasks";
|
|
1406
|
-
if (n.startsWith("memory_")) return "Accessing memory";
|
|
1407
|
-
if (n.startsWith("lsp_")) return "Checking code";
|
|
1408
|
-
if (n.startsWith("chrome_devtools_")) return "Browsing";
|
|
1409
|
-
if (n === "ask_user_question" || n === "plan_mode_question") return "Waiting for input";
|
|
1410
|
-
|
|
1411
|
-
// MCP tools (mcp / mcpScript / mcp__*)
|
|
1412
|
-
if (n === "mcpScript") return "Running script";
|
|
1413
|
-
if (n === "mcp") {
|
|
1414
|
-
const sub = typeof args === "object" && args ? (args.tool || args.search || args.describe || args.action) : "";
|
|
1415
|
-
return sub ? mcpStatusOf(String(sub).toLowerCase()) : "Executing";
|
|
1416
|
-
}
|
|
1417
|
-
if (n.startsWith("mcp__")) {
|
|
1418
|
-
const sub = typeof args === "object" && args?.tool ? String(args.tool).toLowerCase() : "";
|
|
1419
|
-
return mcpStatusOf(sub);
|
|
1420
|
-
}
|
|
1421
|
-
|
|
1422
|
-
return WORK_LABEL;
|
|
1423
|
-
}
|
|
1424
|
-
|
|
1425
|
-
export default function (pi: ExtensionAPI) {
|
|
1426
|
-
let runtimeGen = 0;
|
|
1427
|
-
|
|
1428
|
-
// Keyboard path for the minimal footer's disclosure: mouse clicks only exist in
|
|
1429
|
-
// fullscreen mode, so pi's own rule ("always design a keyboard path") needs this.
|
|
1430
|
-
// One key toggles both sides: expand all unless everything is already open.
|
|
1431
|
-
const toggleMinimal = () => {
|
|
1432
|
-
const state = minimalExpanded();
|
|
1433
|
-
const allOpen = state.left && state.right;
|
|
1434
|
-
state.left = !allOpen;
|
|
1435
|
-
state.right = !allOpen;
|
|
1436
|
-
poke();
|
|
1437
|
-
};
|
|
1438
|
-
for (const key of SHORTCUT_TOGGLE_FOOTER.keys) {
|
|
1439
|
-
pi.registerShortcut(key, { description: "Expand/collapse the minimal footer", handler: toggleMinimal });
|
|
1440
|
-
}
|
|
1441
|
-
|
|
1442
|
-
// Assistant speed timer (user message timestamps come from extensions/timestamps.ts)
|
|
1443
|
-
pi.on("message_start", async (event) => {
|
|
1444
|
-
if (event.message.role === "assistant") {
|
|
1445
|
-
assistantStartMs = Date.now();
|
|
1446
|
-
assistantChars = 0;
|
|
1447
|
-
}
|
|
1448
|
-
});
|
|
1449
|
-
|
|
1450
|
-
pi.on("session_start", async (event, ctx) => {
|
|
1451
|
-
// A /reload re-imports this module while the old instance's interval (and its
|
|
1452
|
-
// ctx.ui closures) may still be alive; clear it before starting a new one.
|
|
1453
|
-
stopWorkingClock();
|
|
1454
|
-
if (event.reason !== "reload") {
|
|
1455
|
-
delete (globalThis as Record<symbol, unknown>)[ACTIVE_KEY];
|
|
1456
|
-
clock = new ActiveClock(resolveSessionStartMs(event.reason, ctx.sessionManager.getHeader()?.timestamp, Date.now()));
|
|
1457
|
-
try {
|
|
1458
|
-
const now = Date.now();
|
|
1459
|
-
clock.active = seedActiveMs(ctx.sessionManager.getEntries(), IDLE_PAUSE_MS, now);
|
|
1460
|
-
clock.runStarted = now;
|
|
1461
|
-
clock.lastSeen = now;
|
|
1462
|
-
} catch {
|
|
1463
|
-
// unreadable log -> start from now
|
|
1464
|
-
}
|
|
1465
|
-
stopIdleProbe();
|
|
1466
|
-
stopClockTick();
|
|
1467
|
-
idlePauseShown = false;
|
|
1468
|
-
currentModel = ctx.model;
|
|
1469
|
-
currentThinkingLevel = ctx.thinkingLevel;
|
|
1470
|
-
git = null;
|
|
1471
|
-
// A new session reuses this module (no re-import), so the 2s cache would serve the
|
|
1472
|
-
// previous session's sums whenever the fresh branch happens to be the same length.
|
|
1473
|
-
usageScanAt = 0;
|
|
1474
|
-
usageScanLen = -1;
|
|
1475
|
-
usageScanManager = undefined;
|
|
1476
|
-
usageScanLeaf = undefined;
|
|
1477
|
-
} else {
|
|
1478
|
-
currentModel = (globalThis as Record<symbol, any>)[MODEL_KEY] ?? ctx.model;
|
|
1479
|
-
currentThinkingLevel = (globalThis as Record<symbol, any>)[THINKING_KEY] ?? ctx.thinkingLevel;
|
|
1480
|
-
git = (globalThis as Record<symbol, any>)[GIT_KEY] ?? null;
|
|
1481
|
-
}
|
|
1482
|
-
(globalThis as Record<symbol, any>)[MODEL_KEY] = currentModel;
|
|
1483
|
-
(globalThis as Record<symbol, any>)[THINKING_KEY] = currentThinkingLevel;
|
|
1484
|
-
(globalThis as Record<symbol, any>)[GIT_KEY] = git;
|
|
1485
|
-
activeThemeProxy = ((ctx as unknown as { ui?: { theme?: typeof activeThemeProxy } }).ui?.theme) ?? activeThemeProxy;
|
|
1486
|
-
|
|
1487
|
-
const cwd = (event.reason === "reload" && (globalThis as Record<symbol, any>)[CWD_KEY])
|
|
1488
|
-
? (globalThis as Record<symbol, any>)[CWD_KEY]
|
|
1489
|
-
: ctx.cwd;
|
|
1490
|
-
(globalThis as Record<symbol, any>)[CWD_KEY] = cwd;
|
|
1491
|
-
|
|
1492
|
-
runtimeGen = ++footerGen;
|
|
1493
|
-
(globalThis as Record<symbol, number>)[GEN_KEY] = footerGen;
|
|
1494
|
-
|
|
1495
|
-
try {
|
|
1496
|
-
armIdleProbe();
|
|
1497
|
-
const registerArnative = (c: ExtensionContext) => {
|
|
1498
|
-
c.ui.setFooter((tui, theme, footerData) => {
|
|
1499
|
-
activeThemeProxy = theme;
|
|
1500
|
-
// Wraps the dispatch (see `wrapInputListener`): the TUI's own viewport
|
|
1501
|
-
// listener runs first and would swallow the keys an `addInputListener` waits for.
|
|
1502
|
-
const dot = wrapInputListener(tui);
|
|
1503
|
-
rerender = () => tui.requestRender();
|
|
1504
|
-
const unsub = footerData.onBranchChange(() => {
|
|
1505
|
-
void refreshGit(cwd).then(() => tui.requestRender());
|
|
1506
|
-
});
|
|
1507
|
-
return {
|
|
1508
|
-
dispose() {
|
|
1509
|
-
rerender = null;
|
|
1510
|
-
dot();
|
|
1511
|
-
unsub();
|
|
1512
|
-
},
|
|
1513
|
-
invalidate() {},
|
|
1514
|
-
render(width: number): string[] {
|
|
1515
|
-
const acc = (text: string) => theme.fg("accent", text);
|
|
1516
|
-
const dim = (text: string) => theme.fg("dim", text);
|
|
1517
|
-
const fgAny = theme.fg.bind(theme) as (color: string, text: string) => string;
|
|
1518
|
-
// `accentSoft`/`secondarySoft` are vars-only tokens on Pi 1.2+, so both soft tiers
|
|
1519
|
-
// are resolved through the shared painters instead of a raw fg() probe. Icons keep
|
|
1520
|
-
// `accent`; the cwd/branch/clock/status text takes the border-accent tier, so the
|
|
1521
|
-
// footer stays two-toned instead of the text inheriting the accent hue.
|
|
1522
|
-
const soft = softOf(theme as never);
|
|
1523
|
-
const softLabel = softSecondaryOf(theme as never);
|
|
1524
|
-
// Diff colors: the same theme slots pi uses for a diff body, with the
|
|
1525
|
-
// plain soft color as fallback for a theme that omits them.
|
|
1526
|
-
const colorOr = (name: string, fallback: (t: string) => string) => (t: string) => {
|
|
1527
|
-
try {
|
|
1528
|
-
return fgAny(name, t);
|
|
1529
|
-
} catch {
|
|
1530
|
-
return fallback(t);
|
|
1531
|
-
}
|
|
1532
|
-
};
|
|
1533
|
-
// `primary` is a var, not a token (Pi 1.2+ rejects custom `colors` keys); its
|
|
1534
|
-
// arnative carrier is the official token it maps to.
|
|
1535
|
-
const primary = colorOr("mdHeading", acc);
|
|
1536
|
-
const secondarySoft = softLabel;
|
|
1537
|
-
const diffAdd = colorOr("toolDiffAdded", soft);
|
|
1538
|
-
const diffDel = colorOr("toolDiffRemoved", soft);
|
|
1539
|
-
const sep = dim(" | ");
|
|
1540
|
-
|
|
1541
|
-
const durationStr = formatDuration(clock.total());
|
|
1542
|
-
const diffStat = formatDiffStat(git, acc, diffAdd, diffDel);
|
|
1543
|
-
const paused = clock.idle();
|
|
1544
|
-
idlePauseShown = paused;
|
|
1545
|
-
const clockIcon = paused ? dim("\uf017") : acc("\uf017");
|
|
1546
|
-
const clockText = paused ? dim(durationStr) : secondarySoft(durationStr);
|
|
1547
|
-
const pDuration = `${clockIcon} ${clockText}${diffStat ? `${sep}${diffStat}` : ""}`;
|
|
1548
|
-
const cwdShort = shortenCwd(cwd);
|
|
1549
|
-
const isMinimal = activeFooterPreset() === "Arnative (Minimal)";
|
|
1550
|
-
const open = minimalExpanded();
|
|
1551
|
-
const arrow = (expanded: boolean) => dim(expanded ? " ▼" : " ▲");
|
|
1552
|
-
let left1 = `${acc("\uf07b")} ${dim(cwdShort)}${sep}${pDuration}`;
|
|
1553
|
-
if (git) {
|
|
1554
|
-
left1 = `${acc("\uf07b")} ${dim(cwdShort)}${sep}${pDuration}${gitParts(git, acc, secondarySoft).map((p) => `${sep}${p}`).join("")}`;
|
|
1555
|
-
}
|
|
1556
|
-
if (isMinimal) left1 += arrow(open.left);
|
|
1557
|
-
const right1 = formatModelName(currentModel, currentThinkingLevel, acc, secondarySoft, primary, dim) + (isMinimal ? arrow(open.right) : "");
|
|
1558
|
-
|
|
1559
|
-
const statuses: ReadonlyMap<string, string> = (() => {
|
|
1560
|
-
try {
|
|
1561
|
-
return footerData.getExtensionStatuses();
|
|
1562
|
-
} catch {
|
|
1563
|
-
return new Map<string, string>();
|
|
1564
|
-
}
|
|
1565
|
-
})();
|
|
1566
|
-
const rawCache = statuses.get("pi-cache-stats");
|
|
1567
|
-
const cleanStatus = (s: string) => {
|
|
1568
|
-
if (s.includes("MCP:")) {
|
|
1569
|
-
let clean = stripAnsi(s);
|
|
1570
|
-
const idx = clean.indexOf("MCP:");
|
|
1571
|
-
let rest = (idx >= 0 ? clean.slice(idx) : clean).replace(/\uFFFD/g, "").trim();
|
|
1572
|
-
rest = rest.replace(/[\p{Extended_Pictographic}\uFE0F\u200D\u2800-\u28FF]/gu, "").replace(/\s{2,}/g, " ").trim();
|
|
1573
|
-
const m = rest.match(/MCP:\s*\d+\s*servers?\s*enabled/i);
|
|
1574
|
-
return `${acc("\uf233")} ${secondarySoft(m ? m[0] : rest || "MCP")}`;
|
|
1575
|
-
}
|
|
1576
|
-
if (s.includes("ponytail")) return ponytailStatusLine(s, acc, dim, secondarySoft);
|
|
1577
|
-
if (isJevEyeStatus(s)) return jevEyeStatusLine(s, acc, dim, secondarySoft, theme);
|
|
1578
|
-
let clean = stripAnsi(s);
|
|
1579
|
-
clean = clean.replace(/\uFFFD/g, "").replace(/\?{1,2}\s*/g, "");
|
|
1580
|
-
return secondarySoft(clean.trim());
|
|
1581
|
-
};
|
|
1582
|
-
|
|
1583
|
-
const groups: string[] = [];
|
|
1584
|
-
const mcp = statuses.get("mcp");
|
|
1585
|
-
if (mcp !== undefined) groups.push(cleanStatus(mcp));
|
|
1586
|
-
for (const [k, s] of statuses) {
|
|
1587
|
-
if (k !== "mcp" && k !== "pi-cache-stats") groups.push(cleanStatus(s));
|
|
1588
|
-
}
|
|
1589
|
-
// Payload pressure sits beside the extension statuses: the right rows
|
|
1590
|
-
// already carry speed, cache, tokens and cost. The denominator is the shed
|
|
1591
|
-
// trigger from the snapshot (900KB), not the 1MB proxy wall: showing /1MB
|
|
1592
|
-
// understated pressure by 10 points right before the trim starts.
|
|
1593
|
-
const wire = wireBytesSnapshot();
|
|
1594
|
-
if (wire && wire.bytes > 0 && isByteLimitedModel(ctx.model)) {
|
|
1595
|
-
// Under a 1 MB wall the label keeps the approved shape `0.74MB/900KB`: the
|
|
1596
|
-
// payload in MB, the ceiling in KB. A bigger wall scales both to MB so the
|
|
1597
|
-
// ceiling stays readable instead of printing 14336KB.
|
|
1598
|
-
const label = wire.limit >= 1024 * 1024
|
|
1599
|
-
? `${(wire.bytes / 1024 / 1024).toFixed(2)}MB/${(wire.limit / 1024 / 1024).toFixed(2)}MB`
|
|
1600
|
-
: `${(wire.bytes / 1024 / 1024).toFixed(2)}MB/${Math.round(wire.limit / 1024)}KB`;
|
|
1601
|
-
groups.push(`${acc("\udb80\udd93")} ${secondarySoft(label)}`);
|
|
1602
|
-
}
|
|
1603
|
-
|
|
1604
|
-
let usageStr = "";
|
|
1605
|
-
try {
|
|
1606
|
-
// The cost cell's colour follows the budget band — amber at ≥80% of a
|
|
1607
|
-
// cap, red at ≥100% — read from the memoized usage summary, so the
|
|
1608
|
-
// render path scans at most once per 5s memo expiry, never per frame.
|
|
1609
|
-
// Nothing is read at all while the cell is off.
|
|
1610
|
-
const band = activeFooterCost() ? budgetLevelNow() : "ok";
|
|
1611
|
-
const bandPaint = band === "warn" ? colorOr("warning", acc) : band === "over" ? colorOr("error", acc) : undefined;
|
|
1612
|
-
usageStr = getUsage(ctx, acc, secondarySoft, activeFooterCost(), width, bandPaint, dim);
|
|
1613
|
-
} catch {
|
|
1614
|
-
// fallback
|
|
1615
|
-
}
|
|
1616
|
-
const opt = parseOptimizer(rawCache) ?? piCacheHit();
|
|
1617
|
-
const speedStr = latestSpeed !== null && latestSpeed > 0 ? `${acc("\udb81\udcc5")} ${secondarySoft(`${latestSpeed.toFixed(1)} tok/s`)}` : "";
|
|
1618
|
-
// The cache cell's colour follows the recent window (the last 10 assistant
|
|
1619
|
-
// messages, the first two skipped): soft ≥70%, amber 40–70% (`warning`
|
|
1620
|
-
// slot, accent when the theme has none), red below 40% (`error`). A passive
|
|
1621
|
-
// colour only — never a notify. The `pi …%` text itself stays as is.
|
|
1622
|
-
// Only pi's own number may be coloured by pi's window: a cache-stats plugin
|
|
1623
|
-
// publishes its own rate (often per request, not per token), and painting it
|
|
1624
|
-
// with our band would contradict the number printed next to it.
|
|
1625
|
-
const fromPi = !parseOptimizer(rawCache);
|
|
1626
|
-
const band = fromPi ? cacheHitBand(usageWindow.inp, usageWindow.read) : null;
|
|
1627
|
-
const bandPaint = band === "warning" ? colorOr("warning", acc) : band === "error" ? colorOr("error", acc) : null;
|
|
1628
|
-
const cacheCell = opt ? `${(bandPaint ?? acc)("\udb80\udf5b")} ${(bandPaint ?? secondarySoft)(opt)}` : "";
|
|
1629
|
-
const metricCells = [speedStr, cacheCell, usageStr].filter(Boolean);
|
|
1630
|
-
|
|
1631
|
-
// Fixed 3-row grid: head (cwd/model), then statuses and metrics each
|
|
1632
|
-
// wrapped inside their half of the width. Arnative (Minimal) starts collapsed
|
|
1633
|
-
// and reveals the same rows on click/keypress, one side at a time.
|
|
1634
|
-
const leftRows = isMinimal && !open.left ? [] : groups;
|
|
1635
|
-
const rightRows = isMinimal && !open.right ? [] : metricCells;
|
|
1636
|
-
if (isMinimal) {
|
|
1637
|
-
// Own head row: it reports the zones measured from what it actually placed.
|
|
1638
|
-
const placed = placeMinimalHead(left1, right1, width);
|
|
1639
|
-
minimalRanges = { left: placed.left, right: placed.right };
|
|
1640
|
-
const rest = layoutFooterGrid("", "", leftRows, rightRows, sep, ` ${dim("·")} `, width).slice(1);
|
|
1641
|
-
return [placed.row, ...rest];
|
|
1642
|
-
}
|
|
1643
|
-
minimalRanges = null;
|
|
1644
|
-
return layoutFooterGrid(left1, right1, leftRows, rightRows, sep, ` ${dim("·")} `, width);
|
|
1645
|
-
},
|
|
1646
|
-
handleMouse(event: TuiMouseEvent) {
|
|
1647
|
-
// Clicks only reach here in fullscreen mode; the keyboard shortcut covers
|
|
1648
|
-
// regular mode. Return handled on press so pi records the target — without
|
|
1649
|
-
// that it never dispatches the follow-up click.
|
|
1650
|
-
if (event.button !== "left" || event.y !== 0) return undefined;
|
|
1651
|
-
const ranges = minimalRanges;
|
|
1652
|
-
if (!ranges) return undefined;
|
|
1653
|
-
const inside = (r: [number, number]) => event.x >= r[0] && event.x <= r[1];
|
|
1654
|
-
const hit = inside(ranges.left) ? "left" : inside(ranges.right) ? "right" : null;
|
|
1655
|
-
if (!hit) return undefined;
|
|
1656
|
-
if (event.type === "press") return { handled: true, render: false };
|
|
1657
|
-
if (event.type !== "click") return undefined;
|
|
1658
|
-
const state = minimalExpanded();
|
|
1659
|
-
state[hit] = !state[hit];
|
|
1660
|
-
poke();
|
|
1661
|
-
return { handled: true, render: true };
|
|
1662
|
-
},
|
|
1663
|
-
};
|
|
1664
|
-
});
|
|
1665
|
-
|
|
1666
|
-
};
|
|
1667
|
-
(globalThis as Record<symbol, (ctx: ExtensionContext) => void>)[FOOTER_REGISTRAR_KEY] = registerArnative;
|
|
1668
|
-
applyFooterPreset(ctx);
|
|
1669
|
-
class ArnativeEditor extends CustomEditor {
|
|
1670
|
-
private lastHiddenLineCount = 0;
|
|
1671
|
-
private lastBottomHiddenCount = 0;
|
|
1672
|
-
private topMoreSpans: TextSpan[] = [];
|
|
1673
|
-
private bottomMoreSpans: TextSpan[] = [];
|
|
1674
|
-
|
|
1675
|
-
constructor(tui: any, editorTheme: any, keybindings: any, options?: any) {
|
|
1676
|
-
super(tui, editorTheme, keybindings, { ...options, embedWorkingStatus: true });
|
|
1677
|
-
editorTui = tui;
|
|
1678
|
-
// Published so `/arnative` → Animations can repaint the live spinner without
|
|
1679
|
-
// waiting for the next session, and so workUI has a handle to the Loader.
|
|
1680
|
-
(globalThis as Record<symbol, any>)[EDITOR_KEY] = this;
|
|
1681
|
-
}
|
|
1682
|
-
|
|
1683
|
-
private getActiveTheme() {
|
|
1684
|
-
return ctx.ui?.theme ?? activeThemeProxy;
|
|
1685
|
-
}
|
|
1686
|
-
|
|
1687
|
-
private applyFixedIndicatorColors(indicator: any) {
|
|
1688
|
-
if (!indicator) return;
|
|
1689
|
-
// Clear renderIndicatorVerbatim so custom frames pass through spinnerColorFn.
|
|
1690
|
-
indicator.renderIndicatorVerbatim = false;
|
|
1691
|
-
indicator.spinnerColorFn = spinnerPainter(activeSpinnerPreset(), this.getActiveTheme(), activeSpinnerGradient());
|
|
1692
|
-
indicator.messageColorFn = (text: string) => {
|
|
1693
|
-
try {
|
|
1694
|
-
const th = this.getActiveTheme();
|
|
1695
|
-
if (!th) return text;
|
|
1696
|
-
return softSecondaryOf(th as never)(text);
|
|
1697
|
-
} catch {
|
|
1698
|
-
return text;
|
|
1699
|
-
}
|
|
1700
|
-
};
|
|
1701
|
-
}
|
|
1702
|
-
|
|
1703
|
-
setWorkingStatusIndicator(indicator: any) {
|
|
1704
|
-
this.applyFixedIndicatorColors(indicator);
|
|
1705
|
-
indicator?.updateDisplay?.();
|
|
1706
|
-
super.setWorkingStatusIndicator(indicator);
|
|
1707
|
-
}
|
|
1708
|
-
|
|
1709
|
-
renderTopBorder(width: number, hiddenLineCount: number): string {
|
|
1710
|
-
this.lastHiddenLineCount = hiddenLineCount;
|
|
1711
|
-
this.applyFixedIndicatorColors((this as any).workingStatusIndicator);
|
|
1712
|
-
if (activeChatboxPreset() === "Arnative") {
|
|
1713
|
-
return renderChatboxScrollBorder(
|
|
1714
|
-
"\u2191",
|
|
1715
|
-
hiddenLineCount,
|
|
1716
|
-
width,
|
|
1717
|
-
(t) => this.borderColor(t),
|
|
1718
|
-
chatboxPrimaryPaint(this.getActiveTheme()),
|
|
1719
|
-
);
|
|
1720
|
-
}
|
|
1721
|
-
// Plain/scroll border only; render() positions the status dialog after boxing.
|
|
1722
|
-
const editorProto = Object.getPrototypeOf(CustomEditor.prototype) as {
|
|
1723
|
-
renderTopBorder?: (w: number, h: number) => string;
|
|
1724
|
-
};
|
|
1725
|
-
if (typeof editorProto?.renderTopBorder === "function") {
|
|
1726
|
-
return editorProto.renderTopBorder.call(this, width, hiddenLineCount);
|
|
1727
|
-
}
|
|
1728
|
-
return this.borderColor("\u2500".repeat(width));
|
|
1729
|
-
}
|
|
1730
|
-
|
|
1731
|
-
renderBottomBorder(width: number, hiddenLineCount: number): string {
|
|
1732
|
-
this.lastBottomHiddenCount = hiddenLineCount;
|
|
1733
|
-
if (activeChatboxPreset() === "Arnative") {
|
|
1734
|
-
return renderChatboxScrollBorder(
|
|
1735
|
-
"\u2193",
|
|
1736
|
-
hiddenLineCount,
|
|
1737
|
-
width,
|
|
1738
|
-
(t) => this.borderColor(t),
|
|
1739
|
-
chatboxPrimaryPaint(this.getActiveTheme()),
|
|
1740
|
-
);
|
|
1741
|
-
}
|
|
1742
|
-
const editorProto = Object.getPrototypeOf(CustomEditor.prototype) as {
|
|
1743
|
-
renderBottomBorder?: (w: number, h: number) => string;
|
|
1744
|
-
};
|
|
1745
|
-
if (typeof editorProto?.renderBottomBorder === "function") {
|
|
1746
|
-
return editorProto.renderBottomBorder.call(this, width, hiddenLineCount);
|
|
1747
|
-
}
|
|
1748
|
-
return this.borderColor("\u2500".repeat(width));
|
|
1749
|
-
}
|
|
1750
|
-
|
|
1751
|
-
private scrollByBorderClick(direction: -1 | 1): void {
|
|
1752
|
-
const ed = this as unknown as {
|
|
1753
|
-
lastWidth?: number;
|
|
1754
|
-
scrollOffset?: number;
|
|
1755
|
-
renderedVisibleLineCount?: number;
|
|
1756
|
-
buildVisualLineMap?(w: number): unknown[];
|
|
1757
|
-
findCurrentVisualLine?(vls: unknown[]): number;
|
|
1758
|
-
moveToVisualLine?(vls: unknown[], cur: number, target: number): void;
|
|
1759
|
-
pageScroll?(dir: number): void;
|
|
1760
|
-
};
|
|
1761
|
-
if (
|
|
1762
|
-
typeof ed.buildVisualLineMap === "function" &&
|
|
1763
|
-
typeof ed.findCurrentVisualLine === "function" &&
|
|
1764
|
-
typeof ed.moveToVisualLine === "function"
|
|
1765
|
-
) {
|
|
1766
|
-
const vls = ed.buildVisualLineMap(ed.lastWidth ?? 80);
|
|
1767
|
-
if (vls.length > 0) {
|
|
1768
|
-
const cur = ed.findCurrentVisualLine(vls);
|
|
1769
|
-
const vis = Math.max(1, ed.renderedVisibleLineCount ?? 5);
|
|
1770
|
-
const step = Math.max(1, Math.floor(vis / 2));
|
|
1771
|
-
const scrollOff = Math.max(0, ed.scrollOffset ?? 0);
|
|
1772
|
-
const target =
|
|
1773
|
-
direction < 0
|
|
1774
|
-
? Math.max(0, scrollOff - step)
|
|
1775
|
-
: Math.min(vls.length - 1, scrollOff + vis - 1 + step);
|
|
1776
|
-
ed.moveToVisualLine(vls, cur, target);
|
|
1777
|
-
return;
|
|
1778
|
-
}
|
|
1779
|
-
}
|
|
1780
|
-
ed.pageScroll?.(direction);
|
|
1781
|
-
}
|
|
1782
|
-
|
|
1783
|
-
handleMouse(event: TuiMouseEvent) {
|
|
1784
|
-
if (activeChatboxPreset() === "Arnative" && event.type === "click" && event.button === "left") {
|
|
1785
|
-
if (inSpans(this.topMoreSpans, event.y, event.x)) {
|
|
1786
|
-
this.scrollByBorderClick(-1);
|
|
1787
|
-
return { handled: true, focus: true };
|
|
1788
|
-
}
|
|
1789
|
-
if (inSpans(this.bottomMoreSpans, event.y, event.x)) {
|
|
1790
|
-
this.scrollByBorderClick(1);
|
|
1791
|
-
return { handled: true, focus: true };
|
|
1792
|
-
}
|
|
1793
|
-
}
|
|
1794
|
-
return super.handleMouse(event);
|
|
1795
|
-
}
|
|
1796
|
-
|
|
1797
|
-
handleInput(data: string) {
|
|
1798
|
-
if (SHORTCUT_RELOAD.matches(data)) {
|
|
1799
|
-
this.setText("");
|
|
1800
|
-
if (this.onSubmit) {
|
|
1801
|
-
this.onSubmit("/reload");
|
|
1802
|
-
}
|
|
1803
|
-
return;
|
|
1804
|
-
}
|
|
1805
|
-
if (!isPointerOrFocusInput(data)) markPromptTyped();
|
|
1806
|
-
super.handleInput(data);
|
|
1807
|
-
}
|
|
1808
|
-
|
|
1809
|
-
render(width: number): string[] {
|
|
1810
|
-
const preset = activeChatboxPreset();
|
|
1811
|
-
const dialog = activeChatboxDialog();
|
|
1812
|
-
const indicator = (this as any).workingStatusIndicator as
|
|
1813
|
-
| { renderInBorder?(w: number): string; renderSpinnerInBorder?(w: number): string }
|
|
1814
|
-
| undefined;
|
|
1815
|
-
this.applyFixedIndicatorColors(indicator);
|
|
1816
|
-
// The box eats 5 columns: 2 sides + the 3-column prompt, so the
|
|
1817
|
-
// content is rendered 5 columns narrower.
|
|
1818
|
-
const visible = (this as unknown as { renderedVisibleLineCount?: number }).renderedVisibleLineCount;
|
|
1819
|
-
const prompt = paintChatboxPrompt(activeChatboxPrompt(), this.getActiveTheme(), isPromptActive());
|
|
1820
|
-
const promptW = visibleWidth(prompt);
|
|
1821
|
-
const lines = renderChatboxLines(preset, (w) => super.render(w), width, visible, (t) => this.borderColor(t), prompt);
|
|
1822
|
-
const boxed = preset === "Arnative" && typeof visible === "number" && width >= promptW + 8 && lines.length >= visible + 2;
|
|
1823
|
-
const statusMax = Math.max(1, width - (boxed ? promptW + 4 : 5));
|
|
1824
|
-
const status = indicator?.renderInBorder?.(statusMax) ?? "";
|
|
1825
|
-
const spinnerOnly = status ? (indicator?.renderSpinnerInBorder?.(width) ?? "") : "";
|
|
1826
|
-
const primary = chatboxPrimaryPaint(this.getActiveTheme());
|
|
1827
|
-
const out = applyChatboxDialog(lines, boxed, width, this.lastHiddenLineCount, dialog, status, spinnerOnly, (t) => this.borderColor(t), primary);
|
|
1828
|
-
const visNow = (this as unknown as { renderedVisibleLineCount?: number }).renderedVisibleLineCount ?? 0;
|
|
1829
|
-
this.topMoreSpans =
|
|
1830
|
-
this.lastHiddenLineCount > 0 && out.length > 0
|
|
1831
|
-
? textSpans([out[0]!], `\u2191 ${this.lastHiddenLineCount} more`)
|
|
1832
|
-
: [];
|
|
1833
|
-
const botRow = visNow + 1;
|
|
1834
|
-
this.bottomMoreSpans =
|
|
1835
|
-
this.lastBottomHiddenCount > 0 && botRow < out.length
|
|
1836
|
-
? textSpans([out[botRow]!], `\u2193 ${this.lastBottomHiddenCount} more`).map((s) => ({ ...s, row: botRow }))
|
|
1837
|
-
: [];
|
|
1838
|
-
return out;
|
|
1839
|
-
}
|
|
1840
|
-
}
|
|
1841
|
-
ctx.ui.setEditorComponent((tui, editorTheme, keybindings) => new ArnativeEditor(tui, editorTheme, keybindings));
|
|
1842
|
-
(globalThis as Record<symbol, unknown>)[OUTSIDE_HOOK_KEY] = (lines: string[], width: number, mode: any): string[] => {
|
|
1843
|
-
if (activeChatboxDialog() !== "Outside") return lines;
|
|
1844
|
-
const editor = (globalThis as Record<symbol, any>)[EDITOR_KEY] as
|
|
1845
|
-
| { workingStatusIndicator?: { renderInBorder?(w: number): string }; applyFixedIndicatorColors?: (ind: any) => void }
|
|
1846
|
-
| undefined;
|
|
1847
|
-
if (!editor || mode?.editor !== editor) return lines;
|
|
1848
|
-
const children = mode?.editorContainer?.children;
|
|
1849
|
-
if (Array.isArray(children) && !children.includes(editor)) return lines;
|
|
1850
|
-
const indicator = editor.workingStatusIndicator;
|
|
1851
|
-
if (!indicator) return lines;
|
|
1852
|
-
editor.applyFixedIndicatorColors?.(indicator);
|
|
1853
|
-
const status = indicator.renderInBorder?.(Math.max(1, width - 5)) ?? "";
|
|
1854
|
-
if (!status || visibleWidth(status) === 0) return lines;
|
|
1855
|
-
return overlayOutsideDialogOnWidgetLines(lines, width, status);
|
|
1856
|
-
};
|
|
1857
|
-
} catch {
|
|
1858
|
-
// fallback
|
|
1859
|
-
}
|
|
1860
|
-
void refreshGit(cwd).then(() => poke());
|
|
1861
|
-
});
|
|
1862
|
-
|
|
1863
|
-
pi.on("turn_start", async (_event, ctx) => {
|
|
1864
|
-
clock.tick();
|
|
1865
|
-
armIdleProbe();
|
|
1866
|
-
currentModel = ctx.model;
|
|
1867
|
-
currentThinkingLevel = ctx.thinkingLevel;
|
|
1868
|
-
(globalThis as Record<symbol, any>)[MODEL_KEY] = currentModel;
|
|
1869
|
-
(globalThis as Record<symbol, any>)[THINKING_KEY] = currentThinkingLevel;
|
|
1870
|
-
(globalThis as Record<symbol, any>)[CWD_KEY] = ctx.cwd;
|
|
1871
|
-
startWorkingClock(ctx);
|
|
1872
|
-
void refreshGit(ctx.cwd).then(() => poke());
|
|
1873
|
-
});
|
|
1874
|
-
|
|
1875
|
-
pi.on("tool_execution_start", async (event, ctx) => {
|
|
1876
|
-
clock.tick();
|
|
1877
|
-
armIdleProbe();
|
|
1878
|
-
const verb = getToolWorkingMessage(event.toolName, event.args);
|
|
1879
|
-
activeToolVerbs.set(event.toolCallId, verb);
|
|
1880
|
-
setWorkingVerb(ctx, verb);
|
|
1881
|
-
});
|
|
1882
|
-
|
|
1883
|
-
pi.on("tool_execution_end", async (event, ctx) => {
|
|
1884
|
-
clock.tick();
|
|
1885
|
-
armIdleProbe();
|
|
1886
|
-
activeToolVerbs.delete(event.toolCallId);
|
|
1887
|
-
setWorkingVerb(ctx, currentToolVerb(activeToolVerbs));
|
|
1888
|
-
// A finished edit/write/bash may have changed the tree (or committed it): without
|
|
1889
|
-
// this, the diff stat stays frozen at the turn_start snapshot — a session that
|
|
1890
|
-
// commits inside the turn shows "clean" forever. refreshGit coalesces concurrent
|
|
1891
|
-
// calls (in-flight + one queued), so a burst of tool ends costs at most two runs.
|
|
1892
|
-
void refreshGit(ctx.cwd).then(() => poke());
|
|
1893
|
-
});
|
|
1894
|
-
|
|
1895
|
-
pi.on("message_update", async (event) => {
|
|
1896
|
-
clock.tick();
|
|
1897
|
-
armIdleProbe();
|
|
1898
|
-
if (event.message.role === "assistant") {
|
|
1899
|
-
// Timer starts lazily if message_start never fired (fragile event pairing)
|
|
1900
|
-
if (assistantStartMs === null) assistantStartMs = Date.now();
|
|
1901
|
-
const streamEvent = (event as { assistantMessageEvent?: { type?: string; delta?: string } }).assistantMessageEvent;
|
|
1902
|
-
if (streamEvent?.delta) {
|
|
1903
|
-
assistantChars += streamEvent.delta.length;
|
|
1904
|
-
}
|
|
1905
|
-
const elapsed = (Date.now() - assistantStartMs) / 1000;
|
|
1906
|
-
if (elapsed >= 0.3) {
|
|
1907
|
-
const usageOut = (event.message as AssistantMessage).usage?.output;
|
|
1908
|
-
const currentTokens = typeof usageOut === "number" && usageOut > 0 ? usageOut : Math.ceil(assistantChars / 3.8);
|
|
1909
|
-
if (currentTokens > 0) {
|
|
1910
|
-
latestSpeed = currentTokens / elapsed;
|
|
1911
|
-
const now = Date.now();
|
|
1912
|
-
if (now - lastPokeMs >= 500) {
|
|
1913
|
-
lastPokeMs = now;
|
|
1914
|
-
poke();
|
|
1915
|
-
}
|
|
1916
|
-
}
|
|
1917
|
-
}
|
|
1918
|
-
}
|
|
1919
|
-
});
|
|
1920
|
-
|
|
1921
|
-
pi.on("message_end", async (event) => {
|
|
1922
|
-
clock.tick();
|
|
1923
|
-
armIdleProbe();
|
|
1924
|
-
if (event.message.role === "assistant") {
|
|
1925
|
-
const start = assistantStartMs ?? Date.now();
|
|
1926
|
-
const elapsed = (Date.now() - start) / 1000;
|
|
1927
|
-
assistantStartMs = null;
|
|
1928
|
-
const usageOut = (event.message as AssistantMessage).usage?.output;
|
|
1929
|
-
const finalTokens = typeof usageOut === "number" && usageOut > 0 ? usageOut : Math.ceil(assistantChars / 3.8);
|
|
1930
|
-
if (finalTokens > 0 && elapsed > 0.2) {
|
|
1931
|
-
latestSpeed = finalTokens / elapsed;
|
|
1932
|
-
}
|
|
1933
|
-
}
|
|
1934
|
-
poke();
|
|
1935
|
-
});
|
|
1936
|
-
|
|
1937
|
-
pi.on("turn_end", async (_event, ctx) => {
|
|
1938
|
-
clock.tick();
|
|
1939
|
-
armIdleProbe();
|
|
1940
|
-
stopWorkingClock();
|
|
1941
|
-
try {
|
|
1942
|
-
ctx.ui?.setWorkingMessage?.();
|
|
1943
|
-
} catch {
|
|
1944
|
-
// ignore
|
|
1945
|
-
}
|
|
1946
|
-
poke();
|
|
1947
|
-
});
|
|
1948
|
-
|
|
1949
|
-
pi.on("model_select", async (event) => {
|
|
1950
|
-
currentModel = event.model;
|
|
1951
|
-
(globalThis as Record<symbol, any>)[MODEL_KEY] = currentModel;
|
|
1952
|
-
poke();
|
|
1953
|
-
});
|
|
1954
|
-
|
|
1955
|
-
pi.on("thinking_level_select", async (event) => {
|
|
1956
|
-
currentThinkingLevel = event.level;
|
|
1957
|
-
(globalThis as Record<symbol, any>)[THINKING_KEY] = currentThinkingLevel;
|
|
1958
|
-
poke();
|
|
1959
|
-
});
|
|
1960
|
-
|
|
1961
|
-
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1962
|
-
usageScanManager = undefined;
|
|
1963
|
-
usageScanLeaf = undefined;
|
|
1964
|
-
stopWorkingClock();
|
|
1965
|
-
stopIdleProbe();
|
|
1966
|
-
stopPromptIdle();
|
|
1967
|
-
stopClockTick();
|
|
1968
|
-
editorTui = null;
|
|
1969
|
-
(globalThis as Record<symbol, unknown>)[OUTSIDE_HOOK_KEY] = null;
|
|
1970
|
-
try {
|
|
1971
|
-
ctx.ui?.setWorkingIndicator?.();
|
|
1972
|
-
} catch {
|
|
1973
|
-
// ignore
|
|
1974
|
-
}
|
|
1975
|
-
rerender = null;
|
|
1976
|
-
const cur = ((globalThis as Record<symbol, number>)[GEN_KEY] ?? 0);
|
|
1977
|
-
if (cur !== runtimeGen) return;
|
|
1978
|
-
footerGen++;
|
|
1979
|
-
(globalThis as Record<symbol, number>)[GEN_KEY] = footerGen;
|
|
1980
|
-
try {
|
|
1981
|
-
(ctx as unknown as { ui?: { setFooter?: (f?: undefined) => void } }).ui?.setFooter?.(undefined);
|
|
1982
|
-
} catch {
|
|
1983
|
-
// ignore
|
|
1984
|
-
}
|
|
1985
|
-
});
|
|
1986
|
-
}
|
|
1987
|
-
|
|
1988
|
-
// Self-check: `node extensions/footer.ts`
|
|
1989
|
-
if (isMain(import.meta.url)) {
|
|
1990
|
-
assert(shortenCwd("/run/media/dev/DATA/work/app") === "\u2026/work/app", "cwd inside -> last 2 segments");
|
|
1991
|
-
assert(shortenCwd("/home/dev") === "/home/dev", "shallow cwd left unchanged");
|
|
1992
|
-
assert(shortenCwd("D:\\Pi\\a\\pi-arnative") === "D:/\u2026/a/pi-arnative", "long Windows path: drive kept");
|
|
1993
|
-
assert(shortenCwd("D:\\Pi\\pi-arnative") === "D:\\Pi\\pi-arnative", "shallow Windows path left unchanged");
|
|
1994
|
-
assert(shortenCwd("/a/x/y/z") === "\u2026/y/z", "long path -> tail");
|
|
1995
|
-
assert(shortenCwd("") === "", "empty cwd");
|
|
1996
|
-
assert(formatDuration(0) === "-", "empty duration = -");
|
|
1997
|
-
assert(formatDuration(1) === "-" && formatDuration(999) === "-", "sub-second is '-' too: no 0s flicker on a fresh clock");
|
|
1998
|
-
assert(formatDuration(1_000) === "1s", "a full second reads as 1s");
|
|
1999
|
-
assert(formatDuration(5_000) === "5s", "seconds only");
|
|
2000
|
-
assert(formatDuration(65_000) === "1m 5s", "minutes + seconds");
|
|
2001
|
-
assert(formatDuration(3_700_000) === "1h 1m", "hours + minutes");
|
|
2002
|
-
|
|
2003
|
-
// Self-check: the footer grid — head row, then statuses/metrics paired per row.
|
|
2004
|
-
// truncateToWidth appends ANSI resets, so measure through stripAnsi (the real
|
|
2005
|
-
// renderer measures with visibleWidth, which ignores them the same way).
|
|
2006
|
-
const vw = (s: string) => stripAnsi(s).length;
|
|
2007
|
-
const g = (n: number) => "g".repeat(n);
|
|
2008
|
-
// Head row: cwd line left, model right-aligned; groups and metrics pair below.
|
|
2009
|
-
const grid = layoutFooterGrid("H".repeat(10), "M".repeat(6), [g(10), g(10), g(10)], ["s".repeat(10), "u".repeat(10)], " | ", " · ", 40, vw);
|
|
2010
|
-
assert(grid.length === 3, "grid: head + two paired rows");
|
|
2011
|
-
assert(grid[0]!.startsWith("H".repeat(10)) && grid[0]!.endsWith("M".repeat(6)), "grid: head pairs cwd and model");
|
|
2012
|
-
assert(grid[0]!.length === 40, "grid: head right-aligns the model");
|
|
2013
|
-
assert(grid[1]!.includes("g") && grid[1]!.endsWith("s".repeat(10)), "grid: row 2 pairs statuses and metrics");
|
|
2014
|
-
assert(grid.every((l) => vw(l) <= 40), "grid: every row fits the terminal");
|
|
2015
|
-
// Each side wraps inside its half: 3 groups + 2 metrics at width 20 -> 3 rows.
|
|
2016
|
-
const tight = layoutFooterGrid("h", "m", [g(6), g(6), g(6)], [g(6), g(6)], " | ", " · ", 20, vw);
|
|
2017
|
-
assert(tight.length === 3, "grid: wraps inside the half width");
|
|
2018
|
-
assert(tight.every((l) => vw(l) <= 20), "grid: wrapped rows still fit");
|
|
2019
|
-
// The right cell survives an oversized left cell (the left one is truncated).
|
|
2020
|
-
const cut = layoutFooterGrid("h", "m", [g(30)], ["R".repeat(4)], " | ", " · ", 12, vw);
|
|
2021
|
-
assert(cut[1]!.endsWith("R".repeat(4)) && vw(cut[1]!) === 12, "grid: right cell survives a wide left cell");
|
|
2022
|
-
// A side that runs out leaves its half blank; rows where both ran out drop.
|
|
2023
|
-
const blank = layoutFooterGrid("h", "m", [], [], " | ", " · ", 20, vw);
|
|
2024
|
-
assert(blank.length === 1, "grid: empty sides drop their rows");
|
|
2025
|
-
|
|
2026
|
-
const plain = (s: string) => s;
|
|
2027
|
-
const D = "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"; // 8 columns = content width in this test
|
|
2028
|
-
const boxed = boxEditorLines([D, " hi ", " lo ", D, " /mo "], 2, plain);
|
|
2029
|
-
assert(boxed[0] === `\u256d${D}\u2500\u2500\u2500\u256e`, "editor box: top corner spans the content");
|
|
2030
|
-
assert(boxed[1] === "\u2502 > hi \u2502", "editor box: ' > ' prompt on the first line");
|
|
2031
|
-
assert(boxed[2] === "\u2502 lo \u2502", "editor box: continuation indented, no second >");
|
|
2032
|
-
assert(boxed[3] === `\u2570${D}\u2500\u2500\u2500\u256f`, "editor box: bottom corner");
|
|
2033
|
-
assert(boxed[4] === " /mo ", "autocomplete lines stay outside the box");
|
|
2034
|
-
const dimP = (s: string) => `\x1b[2m${s}\x1b[0m`;
|
|
2035
|
-
const boxedDim = boxEditorLines([D, " hi ", D], 1, plain, dimP(" > "));
|
|
2036
|
-
assert(visibleWidth(boxedDim[1]!) === visibleWidth(D) + 5, "ANSI (dim) prompt does not shift the width");
|
|
2037
|
-
assert(boxedDim[1]!.startsWith(`\u2502${dimP(" > ")}`), "dim prompt kept as-is");
|
|
2038
|
-
|
|
2039
|
-
const widthsSeen: number[] = [];
|
|
2040
|
-
const piChatbox = renderChatboxLines("Pi (system)", (w) => (widthsSeen.push(w), [D, " hi ", D]), 16, 1, plain);
|
|
2041
|
-
assert(widthsSeen[0] === 16 && piChatbox[0] === D, "Pi (system) chatbox renders stock lines at full width");
|
|
2042
|
-
const arnativeChatbox = renderChatboxLines("Arnative", (w) => (widthsSeen.push(w), [D, " hi ", D]), 16, 1, plain);
|
|
2043
|
-
assert(widthsSeen[1] === 11 && arnativeChatbox[0]!.startsWith("\u256d"), "Arnative chatbox renders boxed lines at width - 5");
|
|
2044
|
-
|
|
2045
|
-
// Self-check: getToolWorkingMessage
|
|
2046
|
-
assert(getToolWorkingMessage("edit") === "Editing", "edit -> Editing");
|
|
2047
|
-
assert(getToolWorkingMessage("write") === "Writing", "write -> Writing");
|
|
2048
|
-
assert(getToolWorkingMessage("read") === "Reading", "read -> Reading");
|
|
2049
|
-
assert(getToolWorkingMessage("grep") === "Searching", "grep -> Searching");
|
|
2050
|
-
assert(getToolWorkingMessage("find") === "Searching", "find -> Searching");
|
|
2051
|
-
assert(getToolWorkingMessage("web_search") === "Searching", "web_search -> Searching");
|
|
2052
|
-
assert(getToolWorkingMessage("bash") === "Executing", "bash -> Executing");
|
|
2053
|
-
assert(getToolWorkingMessage("fetch_content") === "Fetching", "fetch_content -> Fetching");
|
|
2054
|
-
assert(getToolWorkingMessage("todo") === "Updating tasks", "todo -> Updating tasks");
|
|
2055
|
-
assert(getToolWorkingMessage("unknown_tool") === "Working", "unknown -> Working");
|
|
2056
|
-
assert(getToolWorkingMessage("mcp", { tool: "fetch_repo" }) === "Fetching", "mcp fetch -> Fetching");
|
|
2057
|
-
|
|
2058
|
-
// Self-check: working loader clock
|
|
2059
|
-
assert(workingLabel("Working", 0) === "Working", "no elapsed suffix below 1s");
|
|
2060
|
-
assert(workingLabel("Working", 999) === "Working", "no elapsed suffix at 999ms");
|
|
2061
|
-
assert(workingLabel("Working", 50_000) === "Working (50s)", "elapsed seconds suffix");
|
|
2062
|
-
assert(workingLabel("Executing", 65_000) === "Executing (1m 5s)", "elapsed minutes suffix");
|
|
2063
|
-
|
|
2064
|
-
assert(currentToolVerb(new Map()) === WORK_LABEL, "no active tool -> default label");
|
|
2065
|
-
assert(currentToolVerb(new Map([["a", "Reading"], ["b", "Writing"]])) === "Writing", "parallel tools: last started wins");
|
|
2066
|
-
assert(currentToolVerb(new Map([["a", "Reading"]])) === "Reading", "after one ends, the remaining tool's label shows");
|
|
2067
|
-
startWorkingClock({ ui: { setWorkingMessage: () => {} } });
|
|
2068
|
-
assert(Boolean((globalThis as Record<symbol, unknown>)[WORK_TIMER_KEY]), "clock starts: timer stored on globalThis");
|
|
2069
|
-
stopWorkingClock();
|
|
2070
|
-
assert((globalThis as Record<symbol, unknown>)[WORK_TIMER_KEY] == null, "clock stops: reload guard clears the timer");
|
|
2071
|
-
assert(boxed.slice(0, 4).every((l) => visibleWidth(l) === visibleWidth(D) + 5), "uniform box width (sides + prompt)");
|
|
2072
|
-
assert(boxEditorLines(["\u2500\u2500\u2500\u2500"], 1, plain).length === 1, "too narrow: left unchanged");
|
|
2073
|
-
|
|
2074
|
-
// Guard: the reload shortcut must match every encoding a terminal can deliver,
|
|
2075
|
-
// so a typo in the key id fails here instead of silently doing nothing.
|
|
2076
|
-
assert(SHORTCUT_RELOAD.matches("\x1b\x12"), "shortcut matches legacy ctrl+alt+r (ESC + 0x12)");
|
|
2077
|
-
assert(SHORTCUT_RELOAD.matches("\x1b[114;7u"), "shortcut matches Kitty CSI-u ctrl+alt+r");
|
|
2078
|
-
assert(SHORTCUT_RELOAD.matches("\x1br") === IS_WINDOWS_LIKE, "ESC + r triggers reload only where alt+r is bound");
|
|
2079
|
-
assert(!SHORTCUT_RELOAD.matches("\x12"), "plain ctrl+r does not trigger reload");
|
|
2080
|
-
assert(!SHORTCUT_RELOAD.matches("r"), "bare letter r does not trigger reload");
|
|
2081
|
-
|
|
2082
|
-
// getUsage cache: a stream tick mutates the last assistant message in place —
|
|
2083
|
-
// the delta is applied on top of the cached sums (fresh numbers, no O(N) rescan)
|
|
2084
|
-
const usageBranch: Array<{ type: string; message: { role: string; usage?: { input?: number; output?: number; cacheRead?: number } } }> = [
|
|
2085
|
-
{ type: "message", message: { role: "user", content: "hi" } as never },
|
|
2086
|
-
{ type: "message", message: { role: "assistant", usage: { input: 100, output: 50, cacheRead: 10 } } },
|
|
2087
|
-
];
|
|
2088
|
-
const usageCtx = { sessionManager: { getBranch: () => usageBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
|
|
2089
|
-
const id = (t: string) => t;
|
|
2090
|
-
const s1 = getUsage(usageCtx, id, id);
|
|
2091
|
-
assert(s1.includes("↑100") && s1.includes("↓50"), "getUsage scans the branch");
|
|
2092
|
-
usageBranch[1]!.message.usage = { input: 100, output: 80, cacheRead: 10 }; // stream tick in place
|
|
2093
|
-
const s2 = getUsage(usageCtx, id, id);
|
|
2094
|
-
assert(s2.includes("↓80") && !s2.includes("↓50"), "stream tick: delta applied without a rescan (length unchanged)");
|
|
2095
|
-
usageBranch.push({ type: "message", message: { role: "assistant", usage: { input: 1000, output: 2500, cacheRead: 0 } } });
|
|
2096
|
-
const s3 = getUsage(usageCtx, id, id);
|
|
2097
|
-
assert(s3.includes("↑1.1k") && s3.includes("↓2.6k"), "branch length changed: full rescan");
|
|
2098
|
-
// No pi-cache-stats status (provider without an optimizer adapter): the cache cell
|
|
2099
|
-
// falls back to Pi's own usage, cacheRead / (input + cacheRead) = 10 / 1110.
|
|
2100
|
-
assert(piCacheHit() === "pi 0.9%", "cache fallback reads Pi's built-in usage: " + piCacheHit());
|
|
2101
|
-
// Cost cell: opt-in, and the branch scan splits billed from estimated cost.
|
|
2102
|
-
assert(costCell(0, 0, id, id) === "", "no cost at all: no cell");
|
|
2103
|
-
assert(costCell(0.42, 0, id, id).endsWith("$0.42") && !costCell(0.42, 0, id, id).includes("~"), "billed only: $0.42 without ~");
|
|
2104
|
-
assert(costCell(0, 0.42, id, id).includes("~$0.42") && !costCell(0, 0.42, id, id).includes("+"), "estimated only: ~$0.42");
|
|
2105
|
-
assert(costCell(0.3, 0.12, id, id).includes("$0.30 + ~$0.12"), "both: $0.30 + ~$0.12, never blended");
|
|
2106
|
-
// The budget band paints the cost cell — amber at `warn`, red at `over`; no band keeps acc/soft.
|
|
2107
|
-
const warnPaint = (t: string) => `<warn>${t}</warn>`;
|
|
2108
|
-
const overPaint = (t: string) => `<error>${t}</error>`;
|
|
2109
|
-
assert(costCell(0.42, 0, id, id, RATE_MIN_WIDTH, warnPaint) === `<warn>\uf155</warn> <warn>$0.42</warn>`, "the warn band paints icon and text: " + costCell(0.42, 0, id, id, RATE_MIN_WIDTH, warnPaint));
|
|
2110
|
-
assert(costCell(0.42, 0, id, id, RATE_MIN_WIDTH, overPaint) === `<error>\uf155</error> <error>$0.42</error>`, "the over band paints icon and text: " + costCell(0.42, 0, id, id, RATE_MIN_WIDTH, overPaint));
|
|
2111
|
-
assert(costCell(0.42, 0, id, id, RATE_MIN_WIDTH) === "\uf155 $0.42", "no band: acc icon, soft text, as before");
|
|
2112
|
-
|
|
2113
|
-
// Self-check: the burn rate appended to the cost cell — cost / ACTIVE hours of the clock
|
|
2114
|
-
// (idle pauses excluded, not wall-clock), hidden below 5 active minutes, when the cost
|
|
2115
|
-
// is 0, and below 80 columns. Freeze the clock's live part so total() is exactly `active`.
|
|
2116
|
-
const clockBackup = { active: clock.active, runStarted: clock.runStarted, lastSeen: clock.lastSeen };
|
|
2117
|
-
const freezeClock = (activeMs: number) => {
|
|
2118
|
-
clock.active = activeMs;
|
|
2119
|
-
clock.runStarted = Date.now();
|
|
2120
|
-
clock.lastSeen = clock.runStarted - clock.pauseMs - 1;
|
|
2121
|
-
};
|
|
2122
|
-
freezeClock(14 * 60_000); // $0.42 over 14 active minutes = $1.80/h
|
|
2123
|
-
assert(costCell(0.42, 0, id, id).includes("$0.42 ($1.80/h)"), "the rate is cost / active hours: $0.42 over 14 active minutes is $1.80/h: " + costCell(0.42, 0, id, id));
|
|
2124
|
-
assert(!costCell(0.42, 0, id, id).includes("~"), "a billed-only rate carries no ~");
|
|
2125
|
-
assert(costCell(0, 0.42, id, id).includes("~$1.80/h"), "an estimate-based rate is prefixed ~, like the estimated part of the cell");
|
|
2126
|
-
freezeClock(RATE_MIN_ACTIVE_MS - 1);
|
|
2127
|
-
assert(!costCell(0.42, 0, id, id).includes("/h"), "no rate below 5 minutes of active time (a two-minute clock would print nonsense)");
|
|
2128
|
-
freezeClock(RATE_MIN_ACTIVE_MS);
|
|
2129
|
-
assert(costCell(0.42, 0, id, id).includes("/h"), "the rate appears at exactly 5 active minutes");
|
|
2130
|
-
assert(costCell(0.42, 0, id, id, RATE_MIN_WIDTH - 1).endsWith("$0.42"), "below 80 columns the rate is dropped, the cost stays");
|
|
2131
|
-
assert(costCell(0.42, 0, id, id, RATE_MIN_WIDTH).includes("/h"), "at 80 columns the rate is kept");
|
|
2132
|
-
assert(costCell(0, 0, id, id) === "", "zero cost: no cell at all, so no rate either");
|
|
2133
|
-
clock.active = clockBackup.active;
|
|
2134
|
-
clock.runStarted = clockBackup.runStarted;
|
|
2135
|
-
clock.lastSeen = clockBackup.lastSeen;
|
|
2136
|
-
|
|
2137
|
-
// Self-check: the cache cell's colour bands (the `pi …%` text itself stays session-wide).
|
|
2138
|
-
assert(cacheHitBand(300, 700) === "soft" && cacheHitBand(200, 800) === "soft", "a windowed rate ≥70% keeps the soft tier");
|
|
2139
|
-
assert(cacheHitBand(600, 400) === "warning" && cacheHitBand(550, 450) === "warning", "40–70% is the amber (warning) band");
|
|
2140
|
-
assert(cacheHitBand(700, 300) === "error" && cacheHitBand(601, 399) === "error", "below 40% is the red (error) band");
|
|
2141
|
-
assert(cacheHitBand(0, 0) === "soft", "an empty window (fewer than 3 assistant messages) stays soft");
|
|
2142
|
-
// The windowed rate itself, through the scan pass: the first two assistant messages are
|
|
2143
|
-
// ignored, the window is capped at the last CACHE_WINDOW_MSGS, and a stream tick moves
|
|
2144
|
-
// it through the in-place delta without a rescan.
|
|
2145
|
-
const asstMsg = (inp: number, read: number) => ({ type: "message", message: { role: "assistant", usage: { input: inp, output: 5, cacheRead: read } } });
|
|
2146
|
-
const winBranch = [asstMsg(1000, 0), asstMsg(1000, 0), asstMsg(1000, 1000), asstMsg(1000, 1000)];
|
|
2147
|
-
const winCtx = { sessionManager: { getBranch: () => winBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
|
|
2148
|
-
usageScanAt = 0;
|
|
2149
|
-
usageScanLen = -1;
|
|
2150
|
-
getUsage(winCtx, id, id, false);
|
|
2151
|
-
assert(usageWindow.inp === 2000 && usageWindow.read === 2000, "the windowed rate ignores the first two assistant messages: " + JSON.stringify(usageWindow));
|
|
2152
|
-
assert(piCacheHit() === "pi 33.3%", "the pi …% text stays session-wide while the colour is windowed: " + piCacheHit());
|
|
2153
|
-
const scanAtWin = usageScanAt;
|
|
2154
|
-
// A stream tick mutates the last entry in place; replacing it would be a new leaf, and the
|
|
2155
|
-
// i7 identity check would (correctly) rescan instead of taking the delta.
|
|
2156
|
-
(winBranch[3] as { message: { usage: { cacheRead: number } } }).message.usage.cacheRead = 0;
|
|
2157
|
-
getUsage(winCtx, id, id, false);
|
|
2158
|
-
assert(usageWindow.inp === 2000 && usageWindow.read === 1000, "a stream tick moves the window through the delta: " + JSON.stringify(usageWindow));
|
|
2159
|
-
assert(usageScanAt === scanAtWin, "the windowed delta took the cached path, not a rescan");
|
|
2160
|
-
assert(cacheHitBand(usageWindow.inp, usageWindow.read) === "error", "a collapsed recent window is red even though the session rate is still 33.3%");
|
|
2161
|
-
usageScanAt = 0;
|
|
2162
|
-
usageScanLen = -1;
|
|
2163
|
-
const capBranch = [asstMsg(1000, 0), asstMsg(1000, 0), asstMsg(1000, 0), ...Array.from({ length: CACHE_WINDOW_MSGS }, () => asstMsg(600, 400))];
|
|
2164
|
-
const capCtx = { sessionManager: { getBranch: () => capBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
|
|
2165
|
-
getUsage(capCtx, id, id, false);
|
|
2166
|
-
assert(usageWindow.inp === 6_000 && usageWindow.read === 4_000, "the window is capped at the last " + CACHE_WINDOW_MSGS + " assistant messages: " + JSON.stringify(usageWindow));
|
|
2167
|
-
assert(cacheHitBand(usageWindow.inp, usageWindow.read) === "warning", "a 40% windowed rate is the amber band");
|
|
2168
|
-
const costBranch: Array<{
|
|
2169
|
-
type: string;
|
|
2170
|
-
message: { role: string; usage?: { input?: number; output?: number; cacheRead?: number; cost?: { total?: number; totalFromProvider?: boolean } } };
|
|
2171
|
-
}> = [{ type: "message", message: { role: "assistant", usage: { input: 10, output: 5, cacheRead: 0, cost: { total: 0.42, totalFromProvider: true } } } }];
|
|
2172
|
-
const costCtx = { sessionManager: { getBranch: () => costBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
|
|
2173
|
-
assert(!getUsage(costCtx, id, id, false).includes("$0.42"), "cost cell is off unless the switch is on");
|
|
2174
|
-
assert(getUsage(costCtx, id, id, true).includes("$0.42"), "cost cell sums the branch's billed cost when on");
|
|
2175
|
-
assert(
|
|
2176
|
-
getUsage(costCtx, id, id, true).includes("· $0.42"),
|
|
2177
|
-
"the cost cell opens with the footer divider, so the dollar icon reads as its own group",
|
|
2178
|
-
);
|
|
2179
|
-
assert(getUsage(costCtx, id, id, true, RATE_MIN_WIDTH, warnPaint).includes("<warn>$0.42</warn>"), "the warn band reaches the cost cell through getUsage");
|
|
2180
|
-
assert(getUsage(costCtx, id, id, true, RATE_MIN_WIDTH, overPaint).includes("<error>$0.42</error>"), "the over band reaches the cost cell through getUsage");
|
|
2181
|
-
|
|
2182
|
-
// Child spend from a tool result: one assistant message + one tool result carrying usage —
|
|
2183
|
-
// the sums are the sum of both, once each — and a tool result mutated in place (a finished
|
|
2184
|
-
// child call updates its usage, branch length unchanged) still applies the delta on the
|
|
2185
|
-
// cached sums, no rescan.
|
|
2186
|
-
const childBranch: Array<{
|
|
2187
|
-
type: string;
|
|
2188
|
-
message: { role: string; toolName?: string; usage?: { input?: number; output?: number; cacheRead?: number; cost?: { total?: number; totalFromProvider?: boolean } } };
|
|
2189
|
-
}> = [
|
|
2190
|
-
{ type: "message", message: { role: "assistant", usage: { input: 100, output: 50, cacheRead: 10 } } },
|
|
2191
|
-
{
|
|
2192
|
-
type: "message",
|
|
2193
|
-
message: { role: "toolResult", toolName: "subagent", usage: { input: 400, output: 60, cacheRead: 20, cost: { total: 0.05, totalFromProvider: true } } },
|
|
2194
|
-
},
|
|
2195
|
-
];
|
|
2196
|
-
const childCtx = { sessionManager: { getBranch: () => childBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
|
|
2197
|
-
usageScanAt = 0;
|
|
2198
|
-
usageScanLen = -1;
|
|
2199
|
-
const child1 = getUsage(childCtx, id, id, true);
|
|
2200
|
-
assert(child1.includes("↑500") && child1.includes("↓110"), "a tool result's usage is summed with the assistant message's, once each: " + child1);
|
|
2201
|
-
assert(child1.includes("$0.05"), "the tool result's billed cost is summed too: " + child1);
|
|
2202
|
-
childBranch[1]!.message.usage = { input: 700, output: 60, cacheRead: 20, cost: { total: 0.05, totalFromProvider: true } }; // child finished, same branch length
|
|
2203
|
-
const scanAtBefore = usageScanAt;
|
|
2204
|
-
const child2 = getUsage(childCtx, id, id, true);
|
|
2205
|
-
assert(child2.includes("↑800") && !child2.includes("↑500"), "a tool result mutated in place: the delta is applied without a rescan (length unchanged): " + child2);
|
|
2206
|
-
assert(usageScanAt === scanAtBefore, "the tool-result tick took the in-place delta path, not a rescan");
|
|
2207
|
-
childBranch[1]!.message.usage = undefined; // a tool result without usage adds nothing
|
|
2208
|
-
usageScanAt = 0;
|
|
2209
|
-
usageScanLen = -1;
|
|
2210
|
-
const child3 = getUsage(childCtx, id, id, true);
|
|
2211
|
-
assert(child3.includes("↑100") && child3.includes("↓50") && !child3.includes("$0.05"), "a tool result without usage adds nothing: " + child3);
|
|
2212
|
-
|
|
2213
|
-
// Billed vs estimated in getUsage: a costless message is recomputed from models.json
|
|
2214
|
-
// (cache writes included) and shown next to the billed total, not folded into it.
|
|
2215
|
-
const costFixture = mkdtempSync(join(tmpdir(), "pi-arnative-cost-"));
|
|
2216
|
-
const prevCostDir = process.env.PI_CODING_AGENT_DIR;
|
|
2217
|
-
process.env.PI_CODING_AGENT_DIR = costFixture;
|
|
2218
|
-
writeFileSync(
|
|
2219
|
-
join(costFixture, "models.json"),
|
|
2220
|
-
JSON.stringify({ providers: { google: { models: [{ id: "m", cost: { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 3 } }] } } }),
|
|
2221
|
-
);
|
|
2222
|
-
usageScanAt = 0;
|
|
2223
|
-
usageScanLen = -1;
|
|
2224
|
-
const mixedBranch: Array<{
|
|
2225
|
-
type: string;
|
|
2226
|
-
message: { role: string; provider?: string; model?: string; usage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; cost?: { total?: number; totalFromProvider?: boolean } } };
|
|
2227
|
-
}> = [
|
|
2228
|
-
{ type: "message", message: { role: "assistant", provider: "google", model: "m", usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, cost: { total: 0.3, totalFromProvider: true } } } },
|
|
2229
|
-
// No cost at all: 1M input at $1/M + 500k cache writes at $3/M = ~$2.50.
|
|
2230
|
-
{ type: "message", message: { role: "assistant", provider: "google", model: "m", usage: { input: 1_000_000, output: 0, cacheRead: 0, cacheWrite: 500_000 } } },
|
|
2231
|
-
];
|
|
2232
|
-
const mixedCtx = { sessionManager: { getBranch: () => mixedBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
|
|
2233
|
-
const mixedCell = getUsage(mixedCtx, id, id, true);
|
|
2234
|
-
assert(mixedCell.includes("$0.30 + ~$2.50"), "a mixed branch shows the billed and estimated parts apart: " + mixedCell);
|
|
2235
|
-
usageScanAt = 0;
|
|
2236
|
-
usageScanLen = -1;
|
|
2237
|
-
const catalogBranch: typeof mixedBranch = [
|
|
2238
|
-
{ type: "message", message: { role: "assistant", provider: "google", model: "m", usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, cost: { total: 0.12 } } } },
|
|
2239
|
-
];
|
|
2240
|
-
const catalogCtx = { sessionManager: { getBranch: () => catalogBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
|
|
2241
|
-
const catalogCell = getUsage(catalogCtx, id, id, true);
|
|
2242
|
-
assert(catalogCell.includes("~$0.12") && !catalogCell.includes("+"), "a catalog total (no totalFromProvider) is an estimate, marked ~: " + catalogCell);
|
|
2243
|
-
if (prevCostDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
2244
|
-
else process.env.PI_CODING_AGENT_DIR = prevCostDir;
|
|
2245
|
-
rmSync(costFixture, { recursive: true, force: true });
|
|
2246
|
-
|
|
2247
|
-
// regression: a refresh arriving while one is in flight is re-run with the newest
|
|
2248
|
-
// cwd, not dropped (the footer's git state no longer stays stale until the next trigger).
|
|
2249
|
-
// "newest cwd" needs a real repo: the branch now comes from .git/HEAD, not from git.
|
|
2250
|
-
const repo = mkdtempSync(join(tmpdir(), "pi-arnative-repo-"));
|
|
2251
|
-
mkdirSync(join(repo, ".git"), { recursive: true });
|
|
2252
|
-
writeFileSync(join(repo, ".git", "HEAD"), "ref: refs/heads/arnative-tests\n");
|
|
2253
|
-
git = null;
|
|
2254
|
-
const noGit = mkdtempSync(join(tmpdir(), "pi-arnative-nogit-"));
|
|
2255
|
-
// `noGit` is not always repo-free: a temp dir under a versioned home finds the home
|
|
2256
|
-
// repo, so this first refresh really is in flight and can publish the home branch
|
|
2257
|
-
// before the queued one lands. Wait for the queued result, not for "not null".
|
|
2258
|
-
void refreshGit(noGit);
|
|
2259
|
-
await refreshGit(repo); // queued behind it with the newest cwd
|
|
2260
|
-
for (let i = 0; i < 250 && git?.branch !== "arnative-tests"; i++) await new Promise((r) => setTimeout(r, 20));
|
|
2261
|
-
assert(git !== null && git.branch === "arnative-tests", "queued git refresh re-ran on the newest cwd (not dropped)");
|
|
2262
|
-
rmSync(noGit, { recursive: true, force: true });
|
|
2263
|
-
rmSync(repo, { recursive: true, force: true });
|
|
2264
|
-
|
|
2265
|
-
// A repo whose branch is readable without git on PATH: the branch comes from .git/HEAD
|
|
2266
|
-
// (pi's own footer does this too), so a fresh user needs no git install for row 1.
|
|
2267
|
-
const bare = mkdtempSync(join(tmpdir(), "pi-arnative-disk-"));
|
|
2268
|
-
mkdirSync(join(bare, ".git"), { recursive: true });
|
|
2269
|
-
writeFileSync(join(bare, ".git", "HEAD"), "ref: refs/heads/arnative-smoke\n");
|
|
2270
|
-
assert(branchFromDisk(bare) === "arnative-smoke", "branch is read from .git/HEAD without running git");
|
|
2271
|
-
writeFileSync(join(bare, ".git", "HEAD"), "1234567890abcdef1234567890abcdef12345678\n");
|
|
2272
|
-
assert(branchFromDisk(bare) === "detached", "a raw HEAD hash reports detached, not null");
|
|
2273
|
-
// A subfolder of the repo resolves to the repo's branch (walks up like git).
|
|
2274
|
-
writeFileSync(join(bare, ".git", "HEAD"), "ref: refs/heads/arnative-smoke\n");
|
|
2275
|
-
mkdirSync(join(bare, "src", "deep"), { recursive: true });
|
|
2276
|
-
assert(branchFromDisk(join(bare, "src", "deep")) === "arnative-smoke", "branch resolves from a subfolder of the repo");
|
|
2277
|
-
rmSync(bare, { recursive: true, force: true });
|
|
2278
|
-
|
|
2279
|
-
// Honesty: with the branch known but git unable to answer, tag/status must be absent
|
|
2280
|
-
// rather than the old false "-"/"clean".
|
|
2281
|
-
const A = (t: string) => t;
|
|
2282
|
-
const S = (t: string) => t;
|
|
2283
|
-
const unknownGit = gitParts({ branch: "main", tag: null, uncommitted: null, added: null, removed: null, ahead: 0, behind: 0 }, A, S);
|
|
2284
|
-
assert(unknownGit.length === 1 && unknownGit[0]!.endsWith("main"), "unreadable git: branch only, no fake '-'/'clean'");
|
|
2285
|
-
const fullGit = gitParts({ branch: "main", tag: "v1.2.3", uncommitted: 2, added: 500, removed: 100, ahead: 1, behind: 0 }, A, S);
|
|
2286
|
-
assert(fullGit.length === 3 && fullGit[1]!.endsWith("v1.2.3") && fullGit[2]!.includes("~2"), "readable git: tag + dirty count present");
|
|
2287
|
-
assert(gitParts(null, A, S).length === 0, "not a repo: no git segment at all");
|
|
2288
|
-
// Diff stat is clock-adjacent, so it renders with or without a repo.
|
|
2289
|
-
const dirty = { branch: "main", tag: null, uncommitted: 2, added: 500, removed: 100, ahead: 0, behind: 0 };
|
|
2290
|
-
assert(formatDiffStat(dirty, A, (t) => `<A>${t}</A>`, (t) => `<D>${t}</D>`).includes("<A>+500</A> <D>-100</D>"), "+/- use the diff colors");
|
|
2291
|
-
assert(formatDiffStat({ ...dirty, added: 0, removed: 0 }, A, A, A) === "", "a clean tree hides the diff segment");
|
|
2292
|
-
assert(formatDiffStat(null, A, A, A) === "", "no repo: the diff segment is hidden, never a fake 0");
|
|
2293
|
-
assert(formatDiffStat({ ...dirty, added: null, removed: null }, A, A, A) === "", "git cannot answer: the diff segment is hidden");
|
|
2294
|
-
assert(sumNumstat("12\t3\tsrc/a.ts\n-\t-\timg.png\n4\t0\tb.ts\n").added === 16, "numstat sums added lines and skips binary");
|
|
2295
|
-
assert(sumNumstat("12\t3\tsrc/a.ts\n-\t-\timg.png\n4\t0\tb.ts\n").removed === 3, "numstat sums removed lines and skips binary");
|
|
2296
|
-
assert(sumNumstat("").added === 0 && sumNumstat("").removed === 0, "empty numstat is zero, not NaN")
|
|
2297
|
-
|
|
2298
|
-
// Footer presets: Arnative (Full) is the default; Pi (system) hands the footer slot back to pi (the editor stays arnative).
|
|
2299
|
-
assert(DEFAULT_FOOTER_PRESET === "Arnative (Full)" && FOOTER_PRESETS.length === 3, "Arnative (Full) is the default footer preset");
|
|
2300
|
-
assert(FOOTER_PRESETS.join(" | ") === "Pi (system) | Arnative (Full) | Arnative (Minimal)", "built-in preset is listed first, minimal last");
|
|
2301
|
-
assert(markedLabels(FOOTER_PRESETS, "Pi (system)").join(" | ") === "● Pi (system) | Arnative (Full) | Arnative (Minimal)", "footer preset labels mark the active one");
|
|
2302
|
-
assert(ARNATIVE_PRESETS.join(" | ") === "Arnative (Full) | Arnative (Minimal)", "the arnative-drawn presets exclude pi's built-in footer");
|
|
2303
|
-
// Minimal disclosure: both sides start closed, then toggle independently.
|
|
2304
|
-
delete (globalThis as Record<symbol, unknown>)[MINIMAL_EXPAND_KEY];
|
|
2305
|
-
const expand0 = minimalExpanded();
|
|
2306
|
-
assert(expand0.left === false && expand0.right === false, "the minimal footer starts fully collapsed");
|
|
2307
|
-
expand0.left = true;
|
|
2308
|
-
assert(minimalExpanded().left === true && minimalExpanded().right === false, "one side opens without opening the other");
|
|
2309
|
-
delete (globalThis as Record<symbol, unknown>)[MINIMAL_EXPAND_KEY];
|
|
2310
|
-
// Disclosure arrows: the left zone ends the left head, the right one the terminal edge.
|
|
2311
|
-
const normal = placeMinimalHead("L".repeat(20), "R".repeat(10), 80);
|
|
2312
|
-
assert(visibleWidth(normal.row) === 80, "the head row fills the terminal width");
|
|
2313
|
-
assert(normal.left[0] === 0 && normal.left[1] === 19, "the left zone is exactly the left head text");
|
|
2314
|
-
assert(normal.right[0] === 70 && normal.right[1] === 79, "the right zone is exactly the right head text");
|
|
2315
|
-
assert(50 > normal.left[1] && 50 < normal.right[0], "the gap between the heads is inert");
|
|
2316
|
-
const clipped = placeMinimalHead("L".repeat(70), "R".repeat(20), 80);
|
|
2317
|
-
assert(visibleWidth(clipped.row) <= 80, "a cut head row never exceeds the width");
|
|
2318
|
-
assert(clipped.left[1] < clipped.right[0], "cut zones stay ordered and disjoint");
|
|
2319
|
-
assert(clipped.row.slice(clipped.left[0], clipped.left[1] + 1) === clipped.row.slice(0, clipped.left[1] + 1), "the left zone matches the placed text");
|
|
2320
|
-
// Squeezed: the left head keeps at least one column, the right one is dropped once
|
|
2321
|
-
// nothing is left for it. Both outcomes are measured from the placed row.
|
|
2322
|
-
const squeezed = placeMinimalHead("L".repeat(30), "R".repeat(30), 12);
|
|
2323
|
-
assert(visibleWidth(squeezed.row) <= 12, "a squeezed head row never exceeds the width");
|
|
2324
|
-
assert(squeezed.left[0] === 0, "the left head keeps its columns");
|
|
2325
|
-
assert(squeezed.right[0] === -1 || squeezed.right[0] > squeezed.left[1], "zones stay disjoint when squeezed");
|
|
2326
|
-
const noRight = placeMinimalHead("L", "R".repeat(40), 2);
|
|
2327
|
-
assert(noRight.right[0] === -1, "a right head with no room gets no zone");
|
|
2328
|
-
const onlyLeft = placeMinimalHead("L".repeat(5), "", 20);
|
|
2329
|
-
assert(onlyLeft.left[0] === 0 && onlyLeft.left[1] === 4 && onlyLeft.right[0] === -1, "an empty head has no zone");
|
|
2330
|
-
let footerCleared = 0;
|
|
2331
|
-
let editorTouched = 0;
|
|
2332
|
-
const presetCtx: any = {
|
|
2333
|
-
ui: {
|
|
2334
|
-
setFooter: (f: unknown) => { if (f === undefined) footerCleared++; },
|
|
2335
|
-
setEditorComponent: () => { editorTouched++; },
|
|
2336
|
-
},
|
|
2337
|
-
};
|
|
2338
|
-
// Persisting a preset writes a config file: point it at a fixture so the real agent dir stays clean.
|
|
2339
|
-
const presetFixture = mkdtempSync(join(tmpdir(), "arnative-ftr-"));
|
|
2340
|
-
const prevAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
2341
|
-
process.env.PI_CODING_AGENT_DIR = presetFixture;
|
|
2342
|
-
resetPresetCache();
|
|
2343
|
-
setFooterPreset("Pi (system)", presetCtx);
|
|
2344
|
-
assert(footerCleared === 1 && editorTouched === 0 && activeFooterPreset() === "Pi (system)", "Pi (system) clears the footer only (an editor swap would close the picker)");
|
|
2345
|
-
let registered = 0;
|
|
2346
|
-
(globalThis as Record<symbol, (ctx: ExtensionContext) => void>)[FOOTER_REGISTRAR_KEY] = () => { registered++; };
|
|
2347
|
-
setFooterPreset("Arnative (Full)", presetCtx);
|
|
2348
|
-
assert(registered === 1 && activeFooterPreset() === "Arnative (Full)", "Arnative (Full) re-runs the arnative registrar");
|
|
2349
|
-
delete (globalThis as Record<symbol, unknown>)[FOOTER_REGISTRAR_KEY];
|
|
2350
|
-
// Persist a NON-default value: asserting the default survives proves nothing.
|
|
2351
|
-
setFooterPreset("Pi (system)", presetCtx);
|
|
2352
|
-
assert(loadChoice(FOOTER_PRESET_CONFIG_KEY, FOOTER_PRESETS) === "Pi (system)", "the footer preset is persisted to disk");
|
|
2353
|
-
delete (globalThis as Record<symbol, unknown>)[FOOTER_PRESET_KEY];
|
|
2354
|
-
resetPresetCache();
|
|
2355
|
-
assert(activeFooterPreset() === "Pi (system)", "a restart reads the non-default footer preset back from disk");
|
|
2356
|
-
|
|
2357
|
-
// Chatbox presets & prompt arrows: Arnative + ❯ are the defaults; Pi (system) and prompt choice persist across restarts.
|
|
2358
|
-
assert(DEFAULT_CHATBOX_PRESET === "Arnative" && CHATBOX_PRESETS.join(" | ") === "Pi (system) | Arnative", "chatbox presets are Pi (system) then Arnative");
|
|
2359
|
-
assert(activeChatboxPreset() === "Arnative", "Arnative is the default chatbox preset");
|
|
2360
|
-
assert(DEFAULT_CHATBOX_PROMPT === "❯" && CHATBOX_PROMPTS[0] === "❯" && CHATBOX_PROMPTS.length === 12, "chatbox prompts default to ❯ with 12 choices");
|
|
2361
|
-
assert(CHATBOX_PROMPTS.every((g) => visibleWidth(g) === 1), "every chatbox prompt glyph is 1 cell wide");
|
|
2362
|
-
assert(nextChatboxPrompt("❯") === ">" && nextChatboxPrompt("\udb80\udd7a") === "❯", "nextChatboxPrompt cycles through every arrow and wraps");
|
|
2363
|
-
assert(DEFAULT_CHATBOX_DIALOG === "Left" && CHATBOX_DIALOGS.join(" | ") === "Left | Center | Right | Inside | Outside", "chatbox dialog defaults to Left with 5 positions");
|
|
2364
|
-
assert(nextChatboxDialog("Left") === "Center" && nextChatboxDialog("Outside") === "Left", "nextChatboxDialog cycles through every position and wraps");
|
|
2365
|
-
setChatboxPreset("Pi (system)");
|
|
2366
|
-
setChatboxPrompt("▸");
|
|
2367
|
-
setChatboxDialog("Outside");
|
|
2368
|
-
assert(loadChoice(CHATBOX_PRESET_CONFIG_KEY, CHATBOX_PRESETS) === "Pi (system)", "the chatbox preset is persisted to disk");
|
|
2369
|
-
assert(loadChoice(CHATBOX_PROMPT_CONFIG_KEY, CHATBOX_PROMPTS) === "▸", "the chatbox prompt is persisted to disk");
|
|
2370
|
-
assert(loadChoice(CHATBOX_DIALOG_CONFIG_KEY, CHATBOX_DIALOGS) === "Outside", "the chatbox dialog is persisted to disk");
|
|
2371
|
-
delete (globalThis as Record<symbol, unknown>)[CHATBOX_PRESET_KEY];
|
|
2372
|
-
delete (globalThis as Record<symbol, unknown>)[CHATBOX_PROMPT_KEY];
|
|
2373
|
-
delete (globalThis as Record<symbol, unknown>)[CHATBOX_DIALOG_KEY];
|
|
2374
|
-
resetPresetCache();
|
|
2375
|
-
assert(activeChatboxPreset() === "Pi (system)", "a restart reads the non-default chatbox preset back from disk");
|
|
2376
|
-
assert(activeChatboxPrompt() === "▸", "a restart reads the non-default chatbox prompt back from disk");
|
|
2377
|
-
assert(activeChatboxDialog() === "Outside", "a restart reads the non-default chatbox dialog back from disk");
|
|
2378
|
-
delete (globalThis as Record<symbol, unknown>)[CHATBOX_PRESET_KEY];
|
|
2379
|
-
delete (globalThis as Record<symbol, unknown>)[CHATBOX_PROMPT_KEY];
|
|
2380
|
-
delete (globalThis as Record<symbol, unknown>)[CHATBOX_DIALOG_KEY];
|
|
2381
|
-
|
|
2382
|
-
// Chatbox dialog placement: Left, Center, Right, Inside, and Outside keep exact box width.
|
|
2383
|
-
const dW = 36;
|
|
2384
|
-
const dBox = boxEditorLines(["\u2500".repeat(dW - 5), "hi" + " ".repeat(dW - 7), "\u2500".repeat(dW - 5)], 1, plain, " ❯ ");
|
|
2385
|
-
const dStatus = "Working (1s)";
|
|
2386
|
-
for (const pos of CHATBOX_DIALOGS) {
|
|
2387
|
-
const rendered = applyChatboxDialog(dBox, true, dW, 0, pos, dStatus, "*", plain);
|
|
2388
|
-
assert(rendered.every((r) => visibleWidth(r) <= dW), `dialog ${pos} never exceeds width`);
|
|
2389
|
-
if (pos === "Outside") {
|
|
2390
|
-
assert(rendered.length === dBox.length && rendered[0] === dBox[0], "Outside dialog leaves editor box unchanged");
|
|
2391
|
-
} else if (pos === "Inside") {
|
|
2392
|
-
assert(rendered.length === dBox.length && rendered[0] === dBox[0] && rendered[1]!.includes(dStatus) && rendered[1]!.endsWith("│"), "Inside dialog sits inside line 1 at the right corner");
|
|
2393
|
-
} else if (pos === "Left") {
|
|
2394
|
-
assert(rendered[0]!.startsWith("╭── Working (1s) ") && visibleWidth(rendered[0]!) === dW, "Left dialog sits on the left of the top border");
|
|
2395
|
-
} else if (pos === "Center") {
|
|
2396
|
-
const idx = rendered[0]!.indexOf(dStatus);
|
|
2397
|
-
assert(idx > 4 && idx < dW - dStatus.length - 4 && visibleWidth(rendered[0]!) === dW, "Center dialog sits centered on the top border");
|
|
2398
|
-
} else if (pos === "Right") {
|
|
2399
|
-
assert(rendered[0]!.endsWith(" Working (1s) ──╮") && visibleWidth(rendered[0]!) === dW, "Right dialog sits on the right of the top border");
|
|
2400
|
-
}
|
|
2401
|
-
}
|
|
2402
|
-
const outZero = overlayOutsideDialogOnWidgetLines([], dW, dStatus);
|
|
2403
|
-
assert(outZero.length === 3 && outZero[0] === "" && outZero[1] === ` ${dStatus}` && outZero[2] === "", "Outside dialog renders with 1 blank line above and below even when widgetContainerAbove is empty");
|
|
2404
|
-
const outEmpty = overlayOutsideDialogOnWidgetLines([""], dW, dStatus);
|
|
2405
|
-
assert(outEmpty.length === 3 && outEmpty[0] === "" && outEmpty[1] === ` ${dStatus}` && outEmpty[2] === "", "Outside dialog pads 1 blank line above and below when no widget is shown");
|
|
2406
|
-
const outNotice = overlayOutsideDialogOnWidgetLines(["", " \ueb1b Chatbox: Arnative."], 60, dStatus);
|
|
2407
|
-
assert(outNotice.length === 3 && outNotice[0] === "" && outNotice[1] === ` ${dStatus} \ueb1b Chatbox: Arnative.` && outNotice[2] === "", "Outside dialog sits on the left with the notice beside it and 1 blank line below");
|
|
2408
|
-
const outTodos = overlayOutsideDialogOnWidgetLines(["", "\u256d" + "\u2500".repeat(58) + "\u256e", "\u2570" + "\u2500".repeat(58) + "\u256f"], 60, dStatus);
|
|
2409
|
-
assert(outTodos.length === 5 && outTodos[0] === "" && outTodos[1] === ` ${dStatus}` && outTodos[2] === "" && outTodos[3]!.startsWith("\u256d"), "Outside dialog leaves 1 blank line above and below when Todos is visible");
|
|
2410
|
-
|
|
2411
|
-
const scrollBorder = renderChatboxScrollBorder("\u2191", 3, 24, (t) => `<bdr>${t}</bdr>`, (t) => `<pri>${t}</pri>`);
|
|
2412
|
-
assert(scrollBorder.includes("<pri>↑ 3 more</pri>") && visibleWidth(stripAnsi(scrollBorder.replace(/<\/?(bdr|pri)>/g, ""))) === 24, "chatbox scroll border paints N more in primary at exact width");
|
|
2413
|
-
const dialogWithScroll = applyChatboxDialog(dBox, true, dW, 2, "Left", dStatus, "*", (t) => `<bdr>${t}</bdr>`, (t) => `<pri>${t}</pri>`);
|
|
2414
|
-
assert(dialogWithScroll[0]!.includes("<pri>↑ 2 more</pri>"), "top border dialog keeps ↑ N more painted in primary");
|
|
2415
|
-
|
|
2416
|
-
// Prompt idle/active coloring: idle uses dim, active typing uses primary (mdHeading, accent fallback).
|
|
2417
|
-
assert(isPromptActive(10_000, 0) === false, "untyped prompt starts idle");
|
|
2418
|
-
assert(isPromptActive(10_000, 8_000) === true, "prompt stays active within 3s of typing");
|
|
2419
|
-
assert(isPromptActive(10_000, 7_000) === true, "prompt is still active at exact 3s boundary");
|
|
2420
|
-
assert(isPromptActive(10_001, 7_000) === false, "prompt turns idle past 3s without typing");
|
|
2421
|
-
const promptTheme = { fg: (c: string, t: string) => `<${c}>${t}</${c}>` };
|
|
2422
|
-
assert(paintChatboxPrompt("❯", promptTheme, false) === "<dim> ❯ </dim>", "idle prompt paints with dim");
|
|
2423
|
-
assert(paintChatboxPrompt("❯", promptTheme, true) === "<mdHeading> ❯ </mdHeading>", "active prompt paints with primary (mdHeading)");
|
|
2424
|
-
assert(paintChatboxPrompt("\udb80\udf7d", promptTheme, false) === "<dim> \udb80\udf7d </dim>", "Nerd Font PUA prompt gets 2 trailing spaces");
|
|
2425
|
-
const nerdBox = renderChatboxLines("Arnative", (w) => ["\u2500".repeat(w), "hi" + " ".repeat(w - 2), "\u2500".repeat(w)], 30, 1, (t) => t, " \udb80\udf7d ");
|
|
2426
|
-
assert(nerdBox.length === 3 && nerdBox.every((l) => visibleWidth(l) === 30) && nerdBox[1]!.startsWith("\u2502 \udb80\udf7d hi"), "4-col Nerd Font prompt preserves exact box width");
|
|
2427
|
-
const fallbackTheme = {
|
|
2428
|
-
fg: (c: string, t: string) => {
|
|
2429
|
-
if (c === "mdHeading") throw new Error("missing");
|
|
2430
|
-
return `<${c}>${t}</${c}>`;
|
|
2431
|
-
},
|
|
2432
|
-
};
|
|
2433
|
-
assert(paintChatboxPrompt("❯", fallbackTheme, true) === "<accent> ❯ </accent>", "active prompt falls back to accent when mdHeading is absent");
|
|
2434
|
-
markPromptTyped(Date.now());
|
|
2435
|
-
assert(isPromptActive() === true && (globalThis as Record<symbol, unknown>)[PROMPT_IDLE_TIMER_KEY] != null, "markPromptTyped activates prompt and arms idle timer");
|
|
2436
|
-
stopPromptIdle();
|
|
2437
|
-
assert((globalThis as Record<symbol, unknown>)[PROMPT_IDLE_TIMER_KEY] == null, "stopPromptIdle clears the prompt idle timer");
|
|
2438
|
-
delete (globalThis as Record<symbol, unknown>)[PROMPT_TYPED_AT_KEY];
|
|
2439
|
-
rmSync(presetFixture, { recursive: true, force: true });
|
|
2440
|
-
if (prevAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
2441
|
-
else process.env.PI_CODING_AGENT_DIR = prevAgentDir;
|
|
2442
|
-
resetPresetCache();
|
|
2443
|
-
|
|
2444
|
-
// Self-check: formatModelName thinking icon
|
|
2445
|
-
const fmnRes = formatModelName({ id: "claude-3-7-sonnet", name: "Sonnet" }, "low", (s) => s, (s) => s, (s) => s, (s) => s);
|
|
2446
|
-
assert(fmnRes.includes("\uee9c Low"), "formatModelName includes \\uee9c Low thinking indicator");
|
|
2447
|
-
|
|
2448
|
-
// Self-check: the ponytail glyph. \uef51 carries no outline in the Windows Nerd Font
|
|
2449
|
-
// build and renders blank there, so the status silently loses its icon (this is what
|
|
2450
|
-
// a past commit did). Pin the codepoint so a swap back to an invisible one fails here.
|
|
2451
|
-
const ponyLine = ponytailStatusLine("ponytail: FULL", (s) => s, (s) => s, (s) => s);
|
|
2452
|
-
assert(ponyLine.includes("\uef04"), "the ponytail status renders the \\uef04 horse, not the blank \\uef51");
|
|
2453
|
-
assert(!ponyLine.includes("\uef51"), "the blank \\uef51 glyph must never come back");
|
|
2454
|
-
assert(ponytailStatusLine("ponytail: LITE", (s) => s, (s) => s, (s) => s).includes("LITE"), "the ponytail mode is read from the status text");
|
|
2455
|
-
|
|
2456
|
-
// Self-check: the status router must recognise the pi-jev-eye cell by the label its VALUE carries.
|
|
2457
|
-
// The old test was `value.includes("jev-eye")`, and the value is `Eye: ● ON (Clef Flash)` — no
|
|
2458
|
-
// `jev-eye` anywhere — so the branch went false and the cell silently lost its icon and dim suffix.
|
|
2459
|
-
// This pins the recognition rule itself, at the same place the router uses it.
|
|
2460
|
-
assert(isJevEyeStatus("Eye: ● ON (Clef Flash)"), "the value pi-jev-eye publishes is recognised as its own cell");
|
|
2461
|
-
assert(isJevEyeStatus("Eye: ○ OFF (Jev)"), "and so is every other mode's value");
|
|
2462
|
-
assert(!isJevEyeStatus("Jev: ● ON"), "the previous format is not claimed as this cell");
|
|
2463
|
-
assert(!isJevEyeStatus("MCP: 2 servers enabled"), "and neither is another extension's status");
|
|
2464
|
-
assert(
|
|
2465
|
-
!stripAnsi("Eye: ● ON (Clef Flash)").includes("jev-eye"),
|
|
2466
|
-
"the value carries no internal key name, which is what broke the old matcher",
|
|
2467
|
-
);
|
|
2468
|
-
|
|
2469
|
-
// Self-check: the pi-jev-eye status cell. The value is `Eye: ● MODE (Backend)`; the backend is read out
|
|
2470
|
-
// of that string rather than hardcoded, and it takes `dim` while the base label and the state stay
|
|
2471
|
-
// readable — a backend painted like the label would bury `Eye: ● ON`, which is the case this cell
|
|
2472
|
-
// exists for. Both footer formats the operator asked for are pinned here.
|
|
2473
|
-
const jevPlain = (s: string) => s;
|
|
2474
|
-
const jevDim = (s: string) => `[dim]${s}[/dim]`;
|
|
2475
|
-
assert(
|
|
2476
|
-
jevEyeStatusLine("Eye: ● ON (Clef Flash)", jevPlain, jevDim, jevPlain, undefined) ===
|
|
2477
|
-
"\uf21b" + " Eye: ● ON [dim](Clef Flash)[/dim]",
|
|
2478
|
-
"Clef Flash is dim while `Eye:` and the state are not",
|
|
2479
|
-
);
|
|
2480
|
-
assert(
|
|
2481
|
-
jevEyeStatusLine("Eye: ● ON (Jev)", jevPlain, jevDim, jevPlain, undefined) === "\uf21b" + " Eye: ● ON [dim](Jev)[/dim]",
|
|
2482
|
-
"TypeSafe and OpenRouter both read as (Jev)",
|
|
2483
|
-
);
|
|
2484
|
-
assert(
|
|
2485
|
-
jevEyeStatusLine("Eye: ● ON (Clef)", jevPlain, jevDim, jevPlain, undefined) === "\uf21b" + " Eye: ● ON [dim](Clef)[/dim]",
|
|
2486
|
-
"the untiered Clef model draws no tier word",
|
|
2487
|
-
);
|
|
2488
|
-
assert(
|
|
2489
|
-
jevEyeStatusLine("Eye: ● ON (Clef Omni)", jevPlain, jevDim, jevPlain, undefined) === "\uf21b" + " Eye: ● ON [dim](Clef Omni)[/dim]",
|
|
2490
|
-
"a model added upstream draws its own tier",
|
|
2491
|
-
);
|
|
2492
|
-
assert(
|
|
2493
|
-
jevEyeStatusLine("Eye: ○ OFF (Jev)", jevPlain, jevDim, jevPlain, undefined) === "\uf21b" + " Eye: [dim]○[/dim] OFF [dim](Jev)[/dim]",
|
|
2494
|
-
"OFF takes the dim bullet",
|
|
2495
|
-
);
|
|
2496
|
-
assert(
|
|
2497
|
-
jevEyeStatusLine("Eye: ● REVIEW (Clef Flash)", jevPlain, jevDim, jevPlain, { fg: (color, text) => `<${color}>${text}</${color}>` }) ===
|
|
2498
|
-
"\uf21b" + " Eye: <warning>●</warning> REVIEW [dim](Clef Flash)[/dim]",
|
|
2499
|
-
"REVIEW keeps the warning bullet",
|
|
2500
|
-
);
|
|
2501
|
-
// A value with no parenthesised backend (an older pi-jev-eye) must not gain a stray `(`: the suffix is
|
|
2502
|
-
// drawn only when the value actually carries one.
|
|
2503
|
-
assert(
|
|
2504
|
-
jevEyeStatusLine("Eye: ● ON", jevPlain, jevDim, jevPlain, undefined) === "\uf21b" + " Eye: ● ON",
|
|
2505
|
-
"no backend suffix means no parenthesis, never a guessed one",
|
|
2506
|
-
);
|
|
2507
|
-
|
|
2508
|
-
// Self-check: session age survives /resume (header timestamp wins over now).
|
|
2509
|
-
const NOW = Date.parse("2026-10-08T12:00:00.000Z");
|
|
2510
|
-
assert(resolveSessionStartMs("resume", "2026-10-08T09:00:00.000Z", NOW) === Date.parse("2026-10-08T09:00:00.000Z"), "resume restores the session age from the header");
|
|
2511
|
-
assert(resolveSessionStartMs("startup", "2026-10-08T11:59:59.000Z", NOW) === Date.parse("2026-10-08T11:59:59.000Z"), "startup reads the freshly written header");
|
|
2512
|
-
assert(resolveSessionStartMs("resume", undefined, NOW) === NOW, "a missing header falls back to now");
|
|
2513
|
-
assert(resolveSessionStartMs("resume", "not-a-date", NOW) === NOW, "an unparsable header falls back to now");
|
|
2514
|
-
assert(resolveSessionStartMs("resume", "2026-10-08T13:00:00.000Z", NOW) === NOW, "a future header is clamped to now, never a negative age");
|
|
2515
|
-
|
|
2516
|
-
// Self-check: the active clock. The run keeps counting after the last event and then
|
|
2517
|
-
// freezes at the threshold, so the display runs on its own and a pause costs at most
|
|
2518
|
-
// `pauseMs` — but the value never goes backwards.
|
|
2519
|
-
const ACTIVE_SYM = Symbol.for("pi-arnative.activeClock");
|
|
2520
|
-
const t0 = 1_000_000;
|
|
2521
|
-
const P = 180_000;
|
|
2522
|
-
delete (globalThis as Record<symbol, unknown>)[ACTIVE_SYM];
|
|
2523
|
-
const c = new ActiveClock(t0, P);
|
|
2524
|
-
assert(c.total(t0) === 0, "a fresh clock starts at zero");
|
|
2525
|
-
assert(c.total(t0 + 60_000) === 60_000, "the clock runs on its own, with no event arriving");
|
|
2526
|
-
assert(c.total(t0 + P) === P, "it keeps counting until the threshold");
|
|
2527
|
-
assert(c.total(t0 + P + 100_000) === P, "past the threshold the display freezes, it does not run forever");
|
|
2528
|
-
assert(c.total(t0 + 30_000) === 30_000 && c.total(t0 + 60_000) === 60_000, "an earlier read never rewinds the value");
|
|
2529
|
-
assert(c.total(t0 - 5_000) === 0, "a read before the run started is zero, never negative");
|
|
2530
|
-
assert(c.idle(t0) === false, "idle() is false at the start of a run");
|
|
2531
|
-
assert(c.idle(t0 + P) === false, "idle() at exactly the threshold is not idle");
|
|
2532
|
-
assert(c.idle(t0 + P + 1) === true, "idle() turns true past the threshold");
|
|
2533
|
-
// Activity after being away: the old run is committed at its frozen value and a new
|
|
2534
|
-
// run starts here, so a night away adds exactly `pauseMs`, never the away time.
|
|
2535
|
-
const away = t0 + P + 12 * 3600_000;
|
|
2536
|
-
c.tick(away);
|
|
2537
|
-
assert(c.total(away) === P, "an away gap commits the frozen run, not the away time");
|
|
2538
|
-
assert(c.idle(away) === false, "the tick resumes the clock");
|
|
2539
|
-
assert(c.total(away + 30_000) === P + 30_000, "the new run counts from the tick");
|
|
2540
|
-
const restored = new ActiveClock(away, P);
|
|
2541
|
-
assert(restored.active === c.active, "/reload reads the committed total back from globalThis");
|
|
2542
|
-
assert(restored.total(away) === P, "/reload does not restart the session at zero");
|
|
2543
|
-
delete (globalThis as Record<symbol, unknown>)[ACTIVE_SYM];
|
|
2544
|
-
|
|
2545
|
-
// Self-check: seedActiveMs reconstructs the active time already on disk. Sorted by
|
|
2546
|
-
// time first (a fork keeps the parent's older timestamps), unparsable and future
|
|
2547
|
-
// entries ignored, empty log -> zero.
|
|
2548
|
-
const at = (ms: number) => ({ timestamp: new Date(t0 + ms).toISOString() });
|
|
2549
|
-
const SEED_NOW = t0 + 86_400_000; // a day later: every fixture timestamp is in the past
|
|
2550
|
-
assert(seedActiveMs([], 180_000, SEED_NOW) === 0, "empty log seeds zero");
|
|
2551
|
-
assert(seedActiveMs([at(0), at(60_000), at(120_000)], 180_000, SEED_NOW) === 120_000, "short gaps all count");
|
|
2552
|
-
assert(seedActiveMs([at(0), at(5 * 3600_000), at(5 * 3600_000 + 30_000)], 180_000, SEED_NOW) === 30_000, "a long gap is dropped, the tail still counts");
|
|
2553
|
-
assert(seedActiveMs([at(120_000), at(0), at(60_000)], 180_000, SEED_NOW) === 120_000, "out-of-order entries are sorted before summing");
|
|
2554
|
-
assert(seedActiveMs([at(0), at(0), at(60_000)], 180_000, SEED_NOW) === 60_000, "duplicate timestamps add nothing");
|
|
2555
|
-
assert(seedActiveMs([{ timestamp: "not-a-date" }, at(0), at(60_000)], 180_000, SEED_NOW) === 60_000, "unparsable timestamps are ignored");
|
|
2556
|
-
assert(seedActiveMs([at(2 * 86_400_000)], 180_000, SEED_NOW) === 0, "a future timestamp is ignored");
|
|
2557
|
-
|
|
2558
|
-
// The watchdog: activity arms it, it paints the freeze once, then stops. The epsilon keeps
|
|
2559
|
-
// it off the boundary, where `idle()` is still false (strict `>`). `IDLE_PAUSE_MS` itself is
|
|
2560
|
-
// not pinned: it is a documented knob and the behaviour tests read `pauseMs` from the clock.
|
|
2561
|
-
assert(IDLE_PROBE_EPSILON_MS > 0, "the probe must fire past the boundary, not on it");
|
|
2562
|
-
const idleKey = Symbol.for("pi-arnative.idleTimer");
|
|
2563
|
-
clock.lastSeen = Date.now();
|
|
2564
|
-
armIdleProbe();
|
|
2565
|
-
assert((globalThis as Record<symbol, unknown>)[idleKey] != null, "activity arms the idle watchdog");
|
|
2566
|
-
stopIdleProbe();
|
|
2567
|
-
assert((globalThis as Record<symbol, unknown>)[idleKey] == null, "the watchdog is cleared on stop/shutdown");
|
|
2568
|
-
|
|
2569
|
-
// Only keyboard input is activity. Mouse motion is sent continuously by the terminal
|
|
2570
|
-
// (it asks for all-motion mode), so counting it kept the clock open for as long as
|
|
2571
|
-
// the terminal had focus and the dim freeze never appeared.
|
|
2572
|
-
assert(isPointerOrFocusInput("\u001b[<35;10;5M"), "SGR mouse motion is not activity");
|
|
2573
|
-
assert(isPointerOrFocusInput("\u001b[<64;10;5M"), "SGR wheel is not activity");
|
|
2574
|
-
assert(isPointerOrFocusInput("\u001b[M !!"), "legacy X10 mouse is not activity");
|
|
2575
|
-
assert(isPointerOrFocusInput("\u001b[I") && isPointerOrFocusInput("\u001b[O"), "terminal focus is not activity");
|
|
2576
|
-
assert(!isPointerOrFocusInput("a") && !isPointerOrFocusInput("\r"), "keystrokes are activity");
|
|
2577
|
-
assert(!isPointerOrFocusInput("\u001b[A") && !isPointerOrFocusInput("\u001b[5~"), "arrow and page keys are activity");
|
|
2578
|
-
|
|
2579
|
-
console.log("footer.ts self-check OK");
|
|
2580
|
-
}
|