@bismawy/pi-arnative 0.16.1 → 0.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 -327
- 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 +1691 -0
- package/{extensions → lib/features}/render-cache.ts +391 -218
- package/{extensions → lib/features}/timestamps.ts +18 -94
- 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 +48 -49
- package/themes/arnative-blossom.json +0 -0
- package/themes/arnative-crimson.json +0 -0
- package/themes/arnative-cyberpunk.json +0 -0
- package/themes/arnative-dracula.json +0 -0
- package/themes/arnative-earthy.json +0 -0
- package/themes/arnative-garden.json +0 -0
- package/themes/arnative-gruvbox.json +0 -0
- package/themes/arnative-lemonade.json +0 -0
- package/themes/arnative-magical.json +0 -0
- package/themes/arnative-matrix.json +0 -0
- package/themes/arnative-neutral.json +0 -0
- package/themes/arnative-nord.json +0 -0
- package/themes/arnative-zinc.json +0 -0
- package/themes/arnative.json +0 -0
- package/CHANGELOG.md +0 -683
- package/extensions/animations.ts +0 -242
- package/extensions/footer.ts +0 -2617
- 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/usage.ts
DELETED
|
@@ -1,1406 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Arnative Usage Dashboard (/usage): table UI + the /usage command.
|
|
3
|
-
* Data layer (session scan + cache + aggregation) lives in lib/usage-store.ts —
|
|
4
|
-
* shared with the Model tab.
|
|
5
|
-
*/
|
|
6
|
-
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
7
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
8
|
-
import { tmpdir } from "node:os";
|
|
9
|
-
import { join, relative } from "node:path";
|
|
10
|
-
import { matchesKey, truncateToWidth, visibleWidth, type Component, type TUI, type TuiMouseEvent } from "@earendil-works/pi-tui";
|
|
11
|
-
import { renderScreen, screenTitle } from "../lib/box.ts";
|
|
12
|
-
import { assert, isMain } from "../lib/check.ts";
|
|
13
|
-
import { capitalize } from "../lib/format.ts";
|
|
14
|
-
import { thinkingColorOf, softOf, softSecondaryOf } from "../lib/ansi.ts";
|
|
15
|
-
import { legendUsage, matchesBack, RESET_USAGE, UNDO_USAGE } from "../lib/shortcuts.ts";
|
|
16
|
-
import {
|
|
17
|
-
collectUsageSummary,
|
|
18
|
-
estimateCost,
|
|
19
|
-
formatTokens,
|
|
20
|
-
getModelAllTimeUsage,
|
|
21
|
-
hasPrice,
|
|
22
|
-
loadPriceTable,
|
|
23
|
-
resetUsageCache,
|
|
24
|
-
resetUsageStats,
|
|
25
|
-
restoreUsageStats,
|
|
26
|
-
USAGE_RANGES,
|
|
27
|
-
type UsageRange,
|
|
28
|
-
type UsageSummary,
|
|
29
|
-
} from "../lib/usage-store.ts";
|
|
30
|
-
|
|
31
|
-
export function formatCost(n: number): string {
|
|
32
|
-
if (!n || n <= 0) return "-";
|
|
33
|
-
if (n < 0.01) return "<$0.01";
|
|
34
|
-
if (n < 1000) {
|
|
35
|
-
// Rounding at the boundary used to print "$1000.00" instead of "$1.0k".
|
|
36
|
-
const s = n.toFixed(2);
|
|
37
|
-
return s === "1000.00" ? "$1.0k" : `$${s}`;
|
|
38
|
-
}
|
|
39
|
-
return `$${(n / 1000).toFixed(1)}k`;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function formatCount(n: number): string {
|
|
43
|
-
return n > 0 ? n.toLocaleString("en-US") : "-";
|
|
44
|
-
}
|
|
45
|
-
// =============================================================================
|
|
46
|
-
// /usage TUI component
|
|
47
|
-
// =============================================================================
|
|
48
|
-
|
|
49
|
-
export interface RowItem {
|
|
50
|
-
type: "project" | "provider" | "model" | "price";
|
|
51
|
-
/** Set on project rows, and on the provider rows nested under one in Project view. */
|
|
52
|
-
projectName?: string;
|
|
53
|
-
providerName: string;
|
|
54
|
-
modelName?: string;
|
|
55
|
-
label: string;
|
|
56
|
-
sessions: number;
|
|
57
|
-
msgs: number;
|
|
58
|
-
tokens: number;
|
|
59
|
-
input: number;
|
|
60
|
-
output: number;
|
|
61
|
-
cacheRead: number;
|
|
62
|
-
/** Billed cost only; the estimate stays in `estimatedCost`. */
|
|
63
|
-
cost: number;
|
|
64
|
-
/** Catalog totals plus the price-table reconstruction when `cost` is 0 — shown with a `~`. */
|
|
65
|
-
estimatedCost: number;
|
|
66
|
-
expanded?: boolean;
|
|
67
|
-
/** Prices view only: the $/1M rates declared in models.json. */
|
|
68
|
-
rates?: { in: number; out: number; cacheRead: number; cacheWrite: number };
|
|
69
|
-
/** Prices view only: a model used in the sessions but absent from the price table. */
|
|
70
|
-
unpriced?: boolean;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** The stat columns every row shares; each view only adds its type, label and nesting. */
|
|
74
|
-
const statsOf = (
|
|
75
|
-
s: { sessions: number; msgs: number; totalTokens: number; input: number; output: number; cacheRead: number; cost: number; estimatedCost: number },
|
|
76
|
-
): Pick<RowItem, "sessions" | "msgs" | "tokens" | "input" | "output" | "cacheRead" | "cost" | "estimatedCost"> => ({
|
|
77
|
-
sessions: s.sessions,
|
|
78
|
-
msgs: s.msgs,
|
|
79
|
-
tokens: s.totalTokens,
|
|
80
|
-
input: s.input,
|
|
81
|
-
output: s.output,
|
|
82
|
-
cacheRead: s.cacheRead,
|
|
83
|
-
cost: s.cost,
|
|
84
|
-
estimatedCost: s.estimatedCost,
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
/** The dashboard views, cycled by `v`: Provider → Project → Prices. */
|
|
88
|
-
type UsageView = "provider" | "project" | "prices";
|
|
89
|
-
|
|
90
|
-
/** Labels on the range bar, in tab order. */
|
|
91
|
-
const RANGE_LABELS: Record<UsageRange, string> = { all: "All", today: "Today", "7d": "7 day", "30d": "30 day" };
|
|
92
|
-
/** The three views `v` cycles, in that order, and the view a press would show next. */
|
|
93
|
-
const VIEW_LABELS: Record<UsageView, string> = { provider: "Provider", project: "Project", prices: "Prices" };
|
|
94
|
-
const NEXT_VIEW: Record<UsageView, UsageView> = { provider: "project", project: "prices", prices: "provider" };
|
|
95
|
-
/** Data rows on screen at once: five reads as a table, sixteen pushed the Total row off. */
|
|
96
|
-
const USAGE_VIEWPORT = 5;
|
|
97
|
-
|
|
98
|
-
export class UsageModalComponent implements Component {
|
|
99
|
-
private expandedProviders = new Set<string>();
|
|
100
|
-
private expandedProjects = new Set<string>();
|
|
101
|
-
private view: UsageView = "provider";
|
|
102
|
-
private selectedIndex = 0;
|
|
103
|
-
private summary: UsageSummary;
|
|
104
|
-
/** Which window the numbers cover. `all` keeps the old dashboard's meaning. */
|
|
105
|
-
private range: UsageRange = "all";
|
|
106
|
-
/** Tab hitboxes of the last render: column span of each range on the bar line. */
|
|
107
|
-
private tabHitboxes: { line: number; start: number; end: number; range: UsageRange }[] = [];
|
|
108
|
-
|
|
109
|
-
private theme: { fg(c: string, t: string): string; bold?(t: string): string };
|
|
110
|
-
private onDone: (back: boolean) => void;
|
|
111
|
-
private requestRender: () => void;
|
|
112
|
-
/** Painter for the box border's thinking slot, probed once so a theme without
|
|
113
|
-
* `thinking*` falls back to dim. */
|
|
114
|
-
private edgeOf: (s: string) => string;
|
|
115
|
-
/** Row layout of the last render: which table row sits on which screen line. */
|
|
116
|
-
private rowHitboxes: { line: number; index: number }[] = [];
|
|
117
|
-
/** A destructive step waits here until the user answers it. Nothing is touched before. */
|
|
118
|
-
private confirmStep: "reset" | "undo" | null = null;
|
|
119
|
-
/** One line under the table, stating what the last reset changed. */
|
|
120
|
-
private notice: string | null = null;
|
|
121
|
-
/** A wrapper keeps the first reset undoable when no previous baseline existed. */
|
|
122
|
-
private undoBaseline: { previous: string | null } | null = null;
|
|
123
|
-
|
|
124
|
-
constructor(
|
|
125
|
-
theme: { fg(c: string, t: string): string; bold?(t: string): string },
|
|
126
|
-
/** Leave the dashboard. `true` when the user asked to go back (`←`), false for a plain close. */
|
|
127
|
-
onDone: (back: boolean) => void,
|
|
128
|
-
requestRender: () => void,
|
|
129
|
-
thinkingLevel?: string,
|
|
130
|
-
) {
|
|
131
|
-
this.theme = theme;
|
|
132
|
-
this.onDone = onDone;
|
|
133
|
-
this.requestRender = requestRender;
|
|
134
|
-
this.edgeOf = thinkingColorOf(theme, thinkingLevel);
|
|
135
|
-
this.summary = collectUsageSummary(true, this.range);
|
|
136
|
-
// Default: expand the first provider when there is one
|
|
137
|
-
if (this.summary.providers.length > 0) {
|
|
138
|
-
this.expandedProviders.add(this.summary.providers[0]!.name);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
invalidate(): void {}
|
|
143
|
-
|
|
144
|
-
dispose(): void {}
|
|
145
|
-
|
|
146
|
-
private buildFlatRows(): RowItem[] {
|
|
147
|
-
const rows: RowItem[] = [];
|
|
148
|
-
if (this.view === "prices") {
|
|
149
|
-
// Every models.json pair, grouped under its provider like the Provider view: a tree
|
|
150
|
-
// opened one provider at a time. Inside a group the cheapest input rate comes first,
|
|
151
|
-
// and a used model the table does not price ends its group marked `unpriced`.
|
|
152
|
-
const table = loadPriceTable();
|
|
153
|
-
const groups = new Map<string, RowItem[]>();
|
|
154
|
-
const addTo = (provider: string, row: RowItem): void => {
|
|
155
|
-
const list = groups.get(provider) ?? [];
|
|
156
|
-
list.push(row);
|
|
157
|
-
groups.set(provider, list);
|
|
158
|
-
};
|
|
159
|
-
for (const [provider, models] of Object.entries(table)) {
|
|
160
|
-
for (const [model, r] of Object.entries(models)) {
|
|
161
|
-
addTo(provider, {
|
|
162
|
-
type: "price",
|
|
163
|
-
providerName: provider,
|
|
164
|
-
modelName: model,
|
|
165
|
-
label: model,
|
|
166
|
-
sessions: 0,
|
|
167
|
-
msgs: 0,
|
|
168
|
-
tokens: 0,
|
|
169
|
-
input: 0,
|
|
170
|
-
output: 0,
|
|
171
|
-
cacheRead: 0,
|
|
172
|
-
cost: 0,
|
|
173
|
-
estimatedCost: 0,
|
|
174
|
-
rates: { in: r.input ?? 0, out: r.output ?? 0, cacheRead: r.cacheRead ?? 0, cacheWrite: r.cacheWrite ?? 0 },
|
|
175
|
-
});
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
for (const p of this.summary.providers) {
|
|
179
|
-
for (const m of p.models) {
|
|
180
|
-
// `models.json` holds the user's custom rates only: a built-in model has no entry
|
|
181
|
-
// yet still reports a cost, so it is priced, not unpriced. Only a model that
|
|
182
|
-
// shows `-` in the table (no rate, no cost) belongs here.
|
|
183
|
-
if (hasPrice(p.name, m.name, table) || m.cost > 0 || m.estimatedCost > 0) continue;
|
|
184
|
-
addTo(p.name, {
|
|
185
|
-
type: "price",
|
|
186
|
-
providerName: p.name,
|
|
187
|
-
modelName: m.name,
|
|
188
|
-
label: m.name,
|
|
189
|
-
...statsOf(m),
|
|
190
|
-
unpriced: true,
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
const cheapest = (list: RowItem[]): number => Math.min(...list.map((r) => r.rates?.in ?? Number.POSITIVE_INFINITY));
|
|
195
|
-
const ordered = [...groups.entries()].sort((a, b) => cheapest(a[1]) - cheapest(b[1]) || a[0].localeCompare(b[0]));
|
|
196
|
-
for (const [provider, models] of ordered) {
|
|
197
|
-
const isExpanded = this.expandedProviders.has(provider);
|
|
198
|
-
rows.push({
|
|
199
|
-
type: "provider",
|
|
200
|
-
providerName: provider,
|
|
201
|
-
label: capitalize(provider),
|
|
202
|
-
sessions: 0,
|
|
203
|
-
msgs: 0,
|
|
204
|
-
tokens: 0,
|
|
205
|
-
input: 0,
|
|
206
|
-
output: 0,
|
|
207
|
-
cacheRead: 0,
|
|
208
|
-
cost: 0,
|
|
209
|
-
estimatedCost: 0,
|
|
210
|
-
expanded: isExpanded,
|
|
211
|
-
});
|
|
212
|
-
if (!isExpanded) continue;
|
|
213
|
-
models.sort((a, b) => (a.rates?.in ?? Number.POSITIVE_INFINITY) - (b.rates?.in ?? Number.POSITIVE_INFINITY) || a.label.localeCompare(b.label));
|
|
214
|
-
for (const row of models) rows.push(row);
|
|
215
|
-
}
|
|
216
|
-
return rows;
|
|
217
|
-
}
|
|
218
|
-
if (this.view === "project") {
|
|
219
|
-
// Same grid and columns as the Provider view, one level up: Project → Provider.
|
|
220
|
-
for (const proj of this.summary.projects) {
|
|
221
|
-
const isExpanded = this.expandedProjects.has(proj.name);
|
|
222
|
-
rows.push({
|
|
223
|
-
type: "project",
|
|
224
|
-
projectName: proj.name,
|
|
225
|
-
providerName: proj.name,
|
|
226
|
-
label: proj.name,
|
|
227
|
-
...statsOf(proj),
|
|
228
|
-
expanded: isExpanded,
|
|
229
|
-
});
|
|
230
|
-
if (!isExpanded) continue;
|
|
231
|
-
for (const p of proj.providers) {
|
|
232
|
-
rows.push({
|
|
233
|
-
type: "provider",
|
|
234
|
-
projectName: proj.name,
|
|
235
|
-
providerName: p.name,
|
|
236
|
-
label: capitalize(p.name),
|
|
237
|
-
...statsOf(p),
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
return rows;
|
|
242
|
-
}
|
|
243
|
-
for (const p of this.summary.providers) {
|
|
244
|
-
const isExpanded = this.expandedProviders.has(p.name);
|
|
245
|
-
rows.push({
|
|
246
|
-
type: "provider",
|
|
247
|
-
providerName: p.name,
|
|
248
|
-
// No marker in the label: the row gutter draws the expand arrow, so a selected
|
|
249
|
-
// provider does not end up with two arrows on one line. Capitalized to match the
|
|
250
|
-
// detail line and the model rows beneath it.
|
|
251
|
-
label: capitalize(p.name),
|
|
252
|
-
...statsOf(p),
|
|
253
|
-
expanded: isExpanded,
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
if (isExpanded) {
|
|
257
|
-
for (const m of p.models) {
|
|
258
|
-
rows.push({
|
|
259
|
-
type: "model",
|
|
260
|
-
providerName: p.name,
|
|
261
|
-
modelName: m.name,
|
|
262
|
-
label: m.name,
|
|
263
|
-
...statsOf(m),
|
|
264
|
-
});
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
return rows;
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
private toggleRow(row: RowItem | undefined): boolean {
|
|
272
|
-
if (!row) return false;
|
|
273
|
-
if (row.type === "project") {
|
|
274
|
-
if (this.expandedProjects.has(row.projectName!)) this.expandedProjects.delete(row.projectName!);
|
|
275
|
-
else this.expandedProjects.add(row.projectName!);
|
|
276
|
-
return true;
|
|
277
|
-
}
|
|
278
|
-
if (row.type !== "provider") return false;
|
|
279
|
-
if (this.expandedProviders.has(row.providerName)) this.expandedProviders.delete(row.providerName);
|
|
280
|
-
else this.expandedProviders.add(row.providerName);
|
|
281
|
-
return true;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/** Cycle the view: Provider → Project → Prices → Provider. One key, one grid, one legend. */
|
|
285
|
-
private cycleView(): void {
|
|
286
|
-
this.view = this.view === "provider" ? "project" : this.view === "project" ? "prices" : "provider";
|
|
287
|
-
if (this.view === "project" && this.expandedProjects.size === 0 && this.summary.projects.length > 0) {
|
|
288
|
-
this.expandedProjects.add(this.summary.projects[0]!.name);
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/** Refresh every row after a baseline change; the selected provider may disappear. */
|
|
293
|
-
private runConfirm(step: "reset" | "undo"): void {
|
|
294
|
-
if (step === "reset") {
|
|
295
|
-
this.undoBaseline = { previous: resetUsageStats() };
|
|
296
|
-
this.notice = "Usage statistics reset. Sessions kept.";
|
|
297
|
-
} else if (this.undoBaseline) {
|
|
298
|
-
restoreUsageStats(this.undoBaseline.previous);
|
|
299
|
-
this.notice = "Previous statistics restored. Sessions kept.";
|
|
300
|
-
this.undoBaseline = null;
|
|
301
|
-
}
|
|
302
|
-
this.summary = collectUsageSummary(true, this.range);
|
|
303
|
-
this.selectedIndex = 0;
|
|
304
|
-
this.expandedProviders.clear();
|
|
305
|
-
const first = this.summary.providers[0];
|
|
306
|
-
if (first) this.expandedProviders.add(first.name);
|
|
307
|
-
this.requestRender();
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
/** Switch the window and re-read the numbers for it. Selection returns to the first row:
|
|
311
|
-
* a provider that carried the last 3 months can be absent from today. */
|
|
312
|
-
private setRange(range: UsageRange): void {
|
|
313
|
-
if (range === this.range) return;
|
|
314
|
-
this.range = range;
|
|
315
|
-
this.summary = collectUsageSummary(true, range);
|
|
316
|
-
this.selectedIndex = 0;
|
|
317
|
-
this.expandedProviders.clear();
|
|
318
|
-
const first = this.summary.providers[0];
|
|
319
|
-
if (first) this.expandedProviders.add(first.name);
|
|
320
|
-
this.requestRender();
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
handleInput(keyData: string): void {
|
|
324
|
-
const rows = this.buildFlatRows();
|
|
325
|
-
// A pending question owns the keyboard: any key but y answers no, so a stray press
|
|
326
|
-
// can neither delete anything nor navigate.
|
|
327
|
-
if (this.confirmStep) {
|
|
328
|
-
const yes = matchesKey(keyData, "y") || matchesKey(keyData, "Y");
|
|
329
|
-
const step = this.confirmStep;
|
|
330
|
-
this.confirmStep = null;
|
|
331
|
-
if (yes) this.runConfirm(step);
|
|
332
|
-
else this.requestRender();
|
|
333
|
-
return;
|
|
334
|
-
}
|
|
335
|
-
// Esc and ← both step out one level: the dashboard reports it upward so the /arnative
|
|
336
|
-
// menu reopens. q closes outright, for a dashboard opened by /usage on its own.
|
|
337
|
-
if (matchesBack(keyData) || matchesKey(keyData, "escape")) {
|
|
338
|
-
this.onDone(true);
|
|
339
|
-
return;
|
|
340
|
-
}
|
|
341
|
-
if (matchesKey(keyData, "q") || matchesKey(keyData, "shift+q")) {
|
|
342
|
-
this.onDone(false);
|
|
343
|
-
return;
|
|
344
|
-
}
|
|
345
|
-
if (RESET_USAGE.matches(keyData)) {
|
|
346
|
-
this.confirmStep = "reset";
|
|
347
|
-
this.notice = null;
|
|
348
|
-
this.requestRender();
|
|
349
|
-
return;
|
|
350
|
-
}
|
|
351
|
-
if (UNDO_USAGE.matches(keyData) && this.undoBaseline) {
|
|
352
|
-
this.confirmStep = "undo";
|
|
353
|
-
this.requestRender();
|
|
354
|
-
return;
|
|
355
|
-
}
|
|
356
|
-
if (matchesKey(keyData, "tab") || matchesKey(keyData, "shift+tab")) {
|
|
357
|
-
const at = USAGE_RANGES.indexOf(this.range);
|
|
358
|
-
const step = matchesKey(keyData, "shift+tab") ? -1 : 1;
|
|
359
|
-
this.setRange(USAGE_RANGES[(at + step + USAGE_RANGES.length) % USAGE_RANGES.length]!);
|
|
360
|
-
return;
|
|
361
|
-
}
|
|
362
|
-
if (matchesKey(keyData, "up") || matchesKey(keyData, "k")) {
|
|
363
|
-
// Up
|
|
364
|
-
if (this.selectedIndex > 0) {
|
|
365
|
-
this.selectedIndex--;
|
|
366
|
-
this.requestRender();
|
|
367
|
-
}
|
|
368
|
-
return;
|
|
369
|
-
}
|
|
370
|
-
if (matchesKey(keyData, "down") || matchesKey(keyData, "j")) {
|
|
371
|
-
// Down
|
|
372
|
-
if (this.selectedIndex < rows.length - 1) {
|
|
373
|
-
this.selectedIndex++;
|
|
374
|
-
this.requestRender();
|
|
375
|
-
}
|
|
376
|
-
return;
|
|
377
|
-
}
|
|
378
|
-
if (matchesKey(keyData, "enter") || matchesKey(keyData, "space")) {
|
|
379
|
-
if (this.toggleRow(rows[this.selectedIndex])) this.requestRender();
|
|
380
|
-
return;
|
|
381
|
-
}
|
|
382
|
-
if (matchesKey(keyData, "v")) {
|
|
383
|
-
this.cycleView();
|
|
384
|
-
this.requestRender();
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
/** A click on a provider row toggles it, using the hitboxes of the last render so a
|
|
389
|
-
* scrolled-out row is not clickable. Hover is not tracked: nothing reads it. */
|
|
390
|
-
handleMouse(event: TuiMouseEvent): { handled: boolean; render?: boolean } | undefined {
|
|
391
|
-
if (event.type === "wheel" || event.type === "move" || event.type === "drag" || event.type === "release") {
|
|
392
|
-
return undefined;
|
|
393
|
-
}
|
|
394
|
-
// A click on the range bar picks that window, so the bar is a control, not a label.
|
|
395
|
-
const tab = this.tabHitboxes.find((h) => h.line === event.y && event.x >= h.start && event.x <= h.end);
|
|
396
|
-
if (tab) {
|
|
397
|
-
if (event.type === "click") this.setRange(tab.range);
|
|
398
|
-
return { handled: true, render: event.type === "click" };
|
|
399
|
-
}
|
|
400
|
-
const hit = this.rowHitboxes.find((h) => h.line === event.y);
|
|
401
|
-
if (!hit) {
|
|
402
|
-
// A click outside the table is not ours to consume: let it fall through (text
|
|
403
|
-
// selection, scrollback).
|
|
404
|
-
return undefined;
|
|
405
|
-
}
|
|
406
|
-
if (event.type === "click") {
|
|
407
|
-
this.selectedIndex = hit.index;
|
|
408
|
-
this.toggleRow(this.buildFlatRows()[hit.index]);
|
|
409
|
-
return { handled: true, render: true };
|
|
410
|
-
}
|
|
411
|
-
// Press: claim the row so the terminal tracks it for the follow-up click.
|
|
412
|
-
return { handled: true, render: false };
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
render(width: number): string[] {
|
|
416
|
-
const th = this.theme;
|
|
417
|
-
const bold = th.bold ?? ((t: string) => `\x1b[1m${t}\x1b[22m`);
|
|
418
|
-
// The box accent follows the session's thinking level (theme `thinking*` slot), so the
|
|
419
|
-
// dashboard reads as belonging to the model that produced the usage.
|
|
420
|
-
const edge = (t: string) => this.edgeOf(t);
|
|
421
|
-
const boxW = width;
|
|
422
|
-
// `secondarySoft` is a vars-only token on Pi 1.2+; softSecondaryOf resolves the soft
|
|
423
|
-
// label tier (the border-accent hue) and falls back to the accent tier.
|
|
424
|
-
const soft = softSecondaryOf(th);
|
|
425
|
-
const acc = (s: string) => th.fg("accent", s);
|
|
426
|
-
// Selection follows the menu style: a chosen row takes the soft accent, not the accent
|
|
427
|
-
// that marks the provider level itself. `softOf` resolves the token on Pi <=1.1.0 and
|
|
428
|
-
// derives it from the resolved accent on 1.2+, where `fg("accentSoft")` throws.
|
|
429
|
-
const accSoft = softOf(th);
|
|
430
|
-
const dim = (s: string) => th.fg("dim", s);
|
|
431
|
-
|
|
432
|
-
const rows = this.buildFlatRows();
|
|
433
|
-
if (this.selectedIndex >= rows.length) {
|
|
434
|
-
this.selectedIndex = Math.max(0, rows.length - 1);
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
// Columns: full header words. `colW.name` is the header's own name column; a data row
|
|
438
|
-
// spends the first two cells on the expand arrow, so its name field is that much
|
|
439
|
-
// shorter and the numeric columns still start on the header's grid.
|
|
440
|
-
const gutter = 2;
|
|
441
|
-
const contentW = boxW - 4;
|
|
442
|
-
const colW = { name: 30, session: 10, messages: 11, tokens: 10, cost: 11 };
|
|
443
|
-
const allNumeric = colW.session + colW.messages + colW.tokens + colW.cost;
|
|
444
|
-
// A very narrow terminal drops Session/Messages rather than truncating Tokens or Cost.
|
|
445
|
-
const narrow = contentW - allNumeric < 18;
|
|
446
|
-
const numericW = narrow ? colW.tokens + colW.cost : allNumeric;
|
|
447
|
-
colW.name = Math.max(8, Math.min(colW.name, contentW - numericW));
|
|
448
|
-
const rowNameW = Math.max(4, colW.name - gutter);
|
|
449
|
-
|
|
450
|
-
const formatCol = (text: string, w: number, alignRight = true) => {
|
|
451
|
-
const str = truncateToWidth(text, w);
|
|
452
|
-
const diff = Math.max(0, w - visibleWidth(str));
|
|
453
|
-
return alignRight ? " ".repeat(diff) + str : str + " ".repeat(diff);
|
|
454
|
-
};
|
|
455
|
-
|
|
456
|
-
const sessionW = narrow ? 0 : colW.session;
|
|
457
|
-
const messagesW = narrow ? 0 : colW.messages;
|
|
458
|
-
// No leading gutter: the header is content, so it starts on the same left edge as the
|
|
459
|
-
// box title, the detail line and the Total row. The rows' numeric columns are measured
|
|
460
|
-
// to land on this grid despite their arrow. The header names the tree's two levels;
|
|
461
|
-
// the grid under it never moves between views. The Prices view reuses the same four
|
|
462
|
-
// numeric columns for the $/1M rates.
|
|
463
|
-
const nameHeader = this.view === "project" ? "Project / Provider" : "Provider / Model";
|
|
464
|
-
const [hSess, hMsgs, hToks, hCost] =
|
|
465
|
-
this.view === "prices" ? ["In $/M", "Out $/M", "Read $/M", "Write $/M"] : ["Session", "Messages", "Tokens", "Cost"];
|
|
466
|
-
const headerText =
|
|
467
|
-
formatCol(th.fg("dim", nameHeader), colW.name, false) +
|
|
468
|
-
formatCol(th.fg("dim", hSess), sessionW) +
|
|
469
|
-
formatCol(th.fg("dim", hMsgs), messagesW) +
|
|
470
|
-
formatCol(th.fg("dim", hToks), colW.tokens) +
|
|
471
|
-
formatCol(th.fg("dim", hCost), colW.cost);
|
|
472
|
-
|
|
473
|
-
// Body rows only — the frame comes from `renderScreen`, so this dashboard and the
|
|
474
|
-
// /arnative menus cannot drift. No inner `├─┤` rule (skill arnative-pi rule 7).
|
|
475
|
-
const body: string[] = [];
|
|
476
|
-
/** Rows the chrome draws above the body: top edge, title, description, blank. */
|
|
477
|
-
const CHROME_ROWS = 4;
|
|
478
|
-
this.rowHitboxes = [];
|
|
479
|
-
this.tabHitboxes = [];
|
|
480
|
-
|
|
481
|
-
// Row 1: the window bar. The active range is the only accented word, so the numbers
|
|
482
|
-
// below are read with the window they cover; the counter on the same line says how many
|
|
483
|
-
// rows exist beyond the viewport.
|
|
484
|
-
const bar: string[] = [];
|
|
485
|
-
let barCol = 0;
|
|
486
|
-
for (const r of USAGE_RANGES) {
|
|
487
|
-
if (bar.length > 0) {
|
|
488
|
-
bar.push(dim(" · "));
|
|
489
|
-
barCol += 3;
|
|
490
|
-
}
|
|
491
|
-
const label = RANGE_LABELS[r];
|
|
492
|
-
const text = r === this.range ? acc(bold(label)) : th.fg("muted", label);
|
|
493
|
-
this.tabHitboxes.push({ line: CHROME_ROWS + 2, start: barCol + 2, end: barCol + label.length + 1, range: r });
|
|
494
|
-
bar.push(text);
|
|
495
|
-
barCol += label.length;
|
|
496
|
-
}
|
|
497
|
-
const counter = `${Math.min(rows.length, USAGE_VIEWPORT)}/${rows.length}`;
|
|
498
|
-
const rule = th.fg("borderMuted", "\u2500".repeat(Math.max(0, contentW)));
|
|
499
|
-
const barLine = bar.join("");
|
|
500
|
-
const counterFits = contentW - barCol - counter.length - 1 >= 0;
|
|
501
|
-
// The bar is a control between two rules, so the eye reads it as a switch over the table
|
|
502
|
-
// below it, not as a line of the table itself.
|
|
503
|
-
body.push(rule);
|
|
504
|
-
body.push(counterFits ? barLine + " ".repeat(contentW - barCol - counter.length) + dim(counter) : barLine);
|
|
505
|
-
body.push(rule);
|
|
506
|
-
body.push(headerText);
|
|
507
|
-
|
|
508
|
-
// Row 2 onward: the table, windowed so the box keeps one height however long the list
|
|
509
|
-
// of providers and models grows. The line above and below say what is out of sight.
|
|
510
|
-
const maxVisibleRows = USAGE_VIEWPORT;
|
|
511
|
-
let startIdx = 0;
|
|
512
|
-
if (rows.length > maxVisibleRows) {
|
|
513
|
-
startIdx = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisibleRows / 2), rows.length - maxVisibleRows));
|
|
514
|
-
}
|
|
515
|
-
const visibleRows = rows.slice(startIdx, startIdx + maxVisibleRows);
|
|
516
|
-
if (startIdx > 0) body.push(dim(`↑ ${startIdx} more`));
|
|
517
|
-
|
|
518
|
-
for (let i = 0; i < visibleRows.length; i++) {
|
|
519
|
-
const item = visibleRows[i]!;
|
|
520
|
-
const actualIdx = startIdx + i;
|
|
521
|
-
const isSelected = actualIdx === this.selectedIndex;
|
|
522
|
-
|
|
523
|
-
// Provider and project group rows sit on the plain text color, and the rows beneath
|
|
524
|
-
// them are dim — including the providers nested under a project. The cursor paints
|
|
525
|
-
// any row the soft accent, and the expand arrow alone carries the accent so the eye
|
|
526
|
-
// can find the tree.
|
|
527
|
-
const plain = (s: string) => th.fg("text", s);
|
|
528
|
-
const nested =
|
|
529
|
-
item.type === "model" || item.type === "price" || (this.view === "project" && item.type === "provider");
|
|
530
|
-
const resting = nested ? dim : plain;
|
|
531
|
-
const paintName = isSelected ? accSoft : resting;
|
|
532
|
-
const paintVal = isSelected ? accSoft : resting;
|
|
533
|
-
const isPrice = item.type === "price";
|
|
534
|
-
// A Prices group row names the provider; its rate columns stay blank, so the tree
|
|
535
|
-
// reads as a heading instead of a provider with $0.00 rates.
|
|
536
|
-
const isPriceGroup = this.view === "prices" && item.type === "provider";
|
|
537
|
-
const blank = (w: number) => " ".repeat(w);
|
|
538
|
-
|
|
539
|
-
// One indent for the rows under a group (model, price, or the provider under a
|
|
540
|
-
// project): it eats name width so the figures keep their columns.
|
|
541
|
-
const groupType: RowItem["type"] = this.view === "project" ? "project" : "provider";
|
|
542
|
-
const indent = item.type === groupType ? "" : " ";
|
|
543
|
-
const cName = formatCol(paintName(isSelected ? bold(item.label) : item.label), Math.max(10, rowNameW - indent.length), false);
|
|
544
|
-
const cSess = isPriceGroup ? blank(sessionW) : formatCol(paintVal(isPrice ? formatCost(item.rates?.in ?? 0) : formatCount(item.sessions)), sessionW);
|
|
545
|
-
const cMsgs = isPriceGroup ? blank(messagesW) : formatCol(paintVal(isPrice ? formatCost(item.rates?.out ?? 0) : formatCount(item.msgs)), messagesW);
|
|
546
|
-
const cToks = isPriceGroup ? blank(colW.tokens) : formatCol(paintVal(isPrice ? formatCost(item.rates?.cacheRead ?? 0) : formatTokens(item.tokens)), colW.tokens);
|
|
547
|
-
// A row with no billed cost but a rate shows `~$x` in place of `-`, so the guess is
|
|
548
|
-
// visible exactly where it is one; the report line still keeps it out of the headline.
|
|
549
|
-
// The Prices view puts the cache-write rate here, or `unpriced` for a used model the
|
|
550
|
-
// table does not price.
|
|
551
|
-
const costCell = isPrice
|
|
552
|
-
? item.unpriced
|
|
553
|
-
? "unpriced"
|
|
554
|
-
: formatCost(item.rates?.cacheWrite ?? 0)
|
|
555
|
-
: item.cost > 0
|
|
556
|
-
? formatCost(item.cost)
|
|
557
|
-
: item.estimatedCost > 0
|
|
558
|
-
? `~${formatCost(item.estimatedCost)}`
|
|
559
|
-
: "-";
|
|
560
|
-
const cCost = isPriceGroup ? blank(colW.cost) : formatCol(paintVal(costCell), colW.cost);
|
|
561
|
-
|
|
562
|
-
// Gutter: the expand arrow carries the accent, blank indent for the rows beneath it.
|
|
563
|
-
const gutterText = item.type === groupType ? acc(item.expanded ? "▾" : "▸") : " ";
|
|
564
|
-
const line = indent + gutterText + " " + cName + cSess + cMsgs + cToks + cCost;
|
|
565
|
-
this.rowHitboxes.push({ line: CHROME_ROWS + body.length, index: actualIdx });
|
|
566
|
-
body.push(line);
|
|
567
|
-
}
|
|
568
|
-
const hiddenBelow = rows.length - (startIdx + visibleRows.length);
|
|
569
|
-
if (hiddenBelow > 0) body.push(dim(`↓ ${hiddenBelow} more`));
|
|
570
|
-
|
|
571
|
-
// The selected row's detail sits under the table, where the eye lands after scanning it.
|
|
572
|
-
body.push("");
|
|
573
|
-
body.push(this.selectedDetail(rows[this.selectedIndex], acc, soft));
|
|
574
|
-
if (this.notice) body.push(th.fg("muted", this.notice));
|
|
575
|
-
|
|
576
|
-
// Table-width separator above the Total band (skill arnative-pi §6 rule 7).
|
|
577
|
-
const tableW = colW.name + sessionW + messagesW + colW.tokens + colW.cost;
|
|
578
|
-
body.push(th.fg("borderMuted", "─".repeat(Math.max(0, tableW))));
|
|
579
|
-
|
|
580
|
-
if (this.view === "prices") {
|
|
581
|
-
// No Total band for rates: a count of what the table prices, and of the used models
|
|
582
|
-
// it does not, is the honest summary of this view.
|
|
583
|
-
const unpriced = rows.filter((r) => r.unpriced).length;
|
|
584
|
-
const priced = rows.filter((r) => r.type === "price" && !r.unpriced).length;
|
|
585
|
-
body.push(dim(`${priced} priced · ${unpriced} unpriced (models.json)`));
|
|
586
|
-
} else {
|
|
587
|
-
// Total row. Its cost column is the billed total only.
|
|
588
|
-
const t = this.summary.totals;
|
|
589
|
-
const totalName = formatCol(soft(bold("Total")), colW.name, false);
|
|
590
|
-
const totalSess = formatCol(soft(bold(formatCount(t.sessions))), sessionW);
|
|
591
|
-
const totalMsgs = formatCol(soft(bold(formatCount(t.msgs))), messagesW);
|
|
592
|
-
const totalToks = formatCol(soft(bold(formatTokens(t.totalTokens))), colW.tokens);
|
|
593
|
-
// Billed when a provider reported one; otherwise the catalog estimate, marked `~` so
|
|
594
|
-
// the Total row never claims a billed number it does not have.
|
|
595
|
-
const totalValue = t.cost > 0 ? formatCost(t.cost) : t.estimatedCost > 0 ? `~${formatCost(t.estimatedCost)}` : "-";
|
|
596
|
-
const totalCost = formatCol(soft(bold(totalValue)), colW.cost);
|
|
597
|
-
|
|
598
|
-
// Same left edge as the header: one table, three bands, one column grid.
|
|
599
|
-
body.push(totalName + totalSess + totalMsgs + totalToks + totalCost);
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
const viewName = VIEW_LABELS[this.view];
|
|
603
|
-
return renderScreen(
|
|
604
|
-
th,
|
|
605
|
-
width,
|
|
606
|
-
{
|
|
607
|
-
title: screenTitle("Usage"),
|
|
608
|
-
description: `${viewName} · ${
|
|
609
|
-
this.view === "prices"
|
|
610
|
-
? width >= 70
|
|
611
|
-
? "Rates per 1M tokens from models.json; `unpriced` marks a used model with no rate."
|
|
612
|
-
: "Rates per 1M tokens (models.json)."
|
|
613
|
-
: width >= 70
|
|
614
|
-
? "Token, message & cache usage across all local Pi sessions."
|
|
615
|
-
: "Usage across all local sessions."
|
|
616
|
-
}`,
|
|
617
|
-
legend: this.footer(width, th),
|
|
618
|
-
},
|
|
619
|
-
body,
|
|
620
|
-
edge,
|
|
621
|
-
);
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
/** The last row of the box: a pending question, or the keys that are live right now. */
|
|
625
|
-
private footer(width: number, th: { fg(c: string, t: string): string }): string {
|
|
626
|
-
if (this.confirmStep === "reset") {
|
|
627
|
-
return th.fg("accent", "Reset all usage statistics?") + " " + th.fg("muted", "sessions stay") + " " + th.fg("text", "[y] Yes [Esc] Cancel");
|
|
628
|
-
}
|
|
629
|
-
if (this.confirmStep === "undo") {
|
|
630
|
-
return (
|
|
631
|
-
th.fg("accent", "Undo the statistics reset?") +
|
|
632
|
-
" " +
|
|
633
|
-
th.fg("muted", "sessions stay") +
|
|
634
|
-
" " +
|
|
635
|
-
th.fg("text", "[y] Yes [Esc] Cancel")
|
|
636
|
-
);
|
|
637
|
-
}
|
|
638
|
-
return legendUsage(width, { reset: true, undo: this.undoBaseline !== null, next: VIEW_LABELS[NEXT_VIEW[this.view]] });
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
/** Detail for the selected row: icon in `accent`, text and `·` dividers in `accentSoft`. */
|
|
642
|
-
private selectedDetail(
|
|
643
|
-
row: RowItem | undefined,
|
|
644
|
-
accent: (t: string) => string,
|
|
645
|
-
soft: (t: string) => string,
|
|
646
|
-
): string {
|
|
647
|
-
if (!row) return soft("No usage recorded yet.");
|
|
648
|
-
const icon = `${accent("\uf4bc")} `;
|
|
649
|
-
if (row.type === "price") {
|
|
650
|
-
const title = `${row.providerName} · ${row.modelName}`;
|
|
651
|
-
const parts = row.unpriced
|
|
652
|
-
? ["unpriced", `↑${formatTokens(row.input)}`, `↓${formatTokens(row.output)}`]
|
|
653
|
-
: [
|
|
654
|
-
`in ${formatCost(row.rates!.in)}`,
|
|
655
|
-
`out ${formatCost(row.rates!.out)}`,
|
|
656
|
-
`cache read ${formatCost(row.rates!.cacheRead)}`,
|
|
657
|
-
`cache write ${formatCost(row.rates!.cacheWrite)}`,
|
|
658
|
-
];
|
|
659
|
-
if (row.unpriced && row.estimatedCost > 0) parts.push(`${formatCost(row.estimatedCost)} est.`);
|
|
660
|
-
const divider = soft(" · ");
|
|
661
|
-
return `${icon}${soft(capitalize(title))}${divider}${soft(parts.join(" · "))}`;
|
|
662
|
-
}
|
|
663
|
-
const title =
|
|
664
|
-
row.type === "model" ? `${row.providerName} · ${row.modelName}` : row.type === "project" ? row.projectName! : row.providerName;
|
|
665
|
-
const parts = [
|
|
666
|
-
`↑${formatTokens(row.input)}`,
|
|
667
|
-
`↓${formatTokens(row.output)}`,
|
|
668
|
-
`cache ${formatTokens(row.cacheRead)}`,
|
|
669
|
-
];
|
|
670
|
-
if (row.estimatedCost > 0) parts.push(`${formatCost(row.estimatedCost)} est.`);
|
|
671
|
-
const divider = soft(" · ");
|
|
672
|
-
return `${icon}${soft(capitalize(title))}${divider}${soft(parts.join(" · "))}`;
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
/** Open the dashboard. Shared by `/usage` and `/arnative` → Usage, so the two cannot drift. */
|
|
677
|
-
export async function openUsage(ctx: ExtensionCommandContext): Promise<boolean> {
|
|
678
|
-
if (!ctx.hasUI) return false;
|
|
679
|
-
// The thinking level colors the box, so read it when the dashboard opens.
|
|
680
|
-
const thinkingLevel = ctx.thinkingLevel;
|
|
681
|
-
const back = await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
|
|
682
|
-
return new UsageModalComponent(
|
|
683
|
-
theme,
|
|
684
|
-
(wantsBack) => done(wantsBack),
|
|
685
|
-
() => tui.requestRender(),
|
|
686
|
-
thinkingLevel,
|
|
687
|
-
);
|
|
688
|
-
});
|
|
689
|
-
return back === true;
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
export default function (pi: ExtensionAPI) {
|
|
693
|
-
pi.registerCommand("usage", {
|
|
694
|
-
description: "Arnative token & model usage dashboard",
|
|
695
|
-
handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
696
|
-
await openUsage(ctx);
|
|
697
|
-
},
|
|
698
|
-
});
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
// Self-check: `node extensions/usage.ts`
|
|
702
|
-
if (isMain(import.meta.url)) {
|
|
703
|
-
|
|
704
|
-
assert(formatTokens(0) === "-", "formatTokens 0 = -");
|
|
705
|
-
assert(formatTokens(500) === "500", "formatTokens 500 = 500");
|
|
706
|
-
assert(formatTokens(2500) === "2.5k", "formatTokens 2500 = 2.5k");
|
|
707
|
-
assert(formatTokens(2900000) === "2.9M", "formatTokens 2900000 = 2.9M");
|
|
708
|
-
assert(formatTokens(1863163057) === "1.9B", "formatTokens 1.86B = 1.9B");
|
|
709
|
-
assert(formatCost(0) === "-", "formatCost 0 = -");
|
|
710
|
-
assert(formatCost(0.004) === "<$0.01", "formatCost 0.004 = <$0.01");
|
|
711
|
-
assert(formatCost(12.345) === "$12.35", "formatCost 12.345 = $12.35");
|
|
712
|
-
assert(formatCost(1234.5) === "$1.2k", "formatCost 1234.5 = $1.2k");
|
|
713
|
-
// Boundary regressions: rounding used to print "1000k" / "$1000.00".
|
|
714
|
-
assert(formatTokens(999_500) === "999.5k", "formatTokens stays k below 1M");
|
|
715
|
-
assert(formatTokens(999_999) === "1M", "formatTokens promotes a k value that rounds to 1000");
|
|
716
|
-
assert(formatTokens(999_999_999) === "1B", "formatTokens promotes an M value that rounds to 1000");
|
|
717
|
-
assert(formatTokens(9_999) === "10k", "formatTokens strips a .0 k tail");
|
|
718
|
-
assert(formatCost(999.996) === "$1.0k", "formatCost rolls over at $1000");
|
|
719
|
-
|
|
720
|
-
// Fixture agent dir: the real history (and cache) must not decide pass/fail.
|
|
721
|
-
const fixture = mkdtempSync(join(tmpdir(), "arnative-usage-"));
|
|
722
|
-
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
723
|
-
mkdirSync(join(fixture, "sessions", "proj"), { recursive: true });
|
|
724
|
-
const asst = (model: string, input: number) =>
|
|
725
|
-
JSON.stringify({ message: { role: "assistant", provider: "google", model, usage: { input, output: 5, cacheRead: 1, cacheWrite: 2, cost: { total: 0.02, totalFromProvider: true } } } });
|
|
726
|
-
writeFileSync(
|
|
727
|
-
join(fixture, "sessions", "proj", "a.jsonl"),
|
|
728
|
-
[JSON.stringify({ message: { role: "user", content: "hi" } }), asst("gemini-3.8-flash", 100), asst("gemini-3.8-flash", 50), asst("other-model", 7)].join(String.fromCharCode(10)) + String.fromCharCode(10),
|
|
729
|
-
);
|
|
730
|
-
|
|
731
|
-
const summary = collectUsageSummary(true);
|
|
732
|
-
assert(summary.providers.length === 1, "collectUsageSummary detects providers");
|
|
733
|
-
assert(summary.totals.sessions === 1, "collectUsageSummary detects total sessions");
|
|
734
|
-
assert(summary.totals.msgs === 3, "collectUsageSummary counts assistant messages only");
|
|
735
|
-
assert(Math.abs(summary.totals.cost - 0.06) < 1e-9, "collectUsageSummary counts cost");
|
|
736
|
-
// Tokens is everything the model moved, cache reads included: a vendor dashboard counts
|
|
737
|
-
// the same three numbers, so 240M cached tokens cannot vanish from the headline.
|
|
738
|
-
assert(
|
|
739
|
-
summary.totals.totalTokens === summary.totals.input + summary.totals.output + summary.totals.cacheRead,
|
|
740
|
-
"the Tokens total is prompt + completion + cache reads",
|
|
741
|
-
);
|
|
742
|
-
assert(summary.totals.totalTokens === 175, `the fixture moves 175 tokens in total, got ${summary.totals.totalTokens}`);
|
|
743
|
-
assert(summary.providers[0]!.models[0]!.totalTokens === 162, "a model row counts its cache reads too");
|
|
744
|
-
|
|
745
|
-
const modelUsage = getModelAllTimeUsage("gemini-3.8-flash");
|
|
746
|
-
assert(modelUsage.input === 150 && modelUsage.output === 10 && modelUsage.cacheRead === 2, "getModelAllTimeUsage sums one model across messages");
|
|
747
|
-
assert(
|
|
748
|
-
getModelAllTimeUsage(undefined).input === 0 && getModelAllTimeUsage(undefined).output === 0,
|
|
749
|
-
"getModelAllTimeUsage without a model id matches nothing (no grand total)",
|
|
750
|
-
);
|
|
751
|
-
|
|
752
|
-
// A session file that grows is parsed from the tail only (byte offset in the cache), not re-read.
|
|
753
|
-
const file = join(fixture, "sessions", "proj", "a.jsonl");
|
|
754
|
-
const cachePath = join(fixture, "arnative", "usage-cache.json");
|
|
755
|
-
const cachedBefore = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, { c: number; s: number }>;
|
|
756
|
-
assert(cachedBefore[relative(join(fixture, "sessions"), file)]!.c === cachedBefore[relative(join(fixture, "sessions"), file)]!.s, "cache records the full parsed offset");
|
|
757
|
-
writeFileSync(file, asst("gemini-3.8-flash", 1000) + String.fromCharCode(10), { flag: "a" });
|
|
758
|
-
const grown = collectUsageSummary(true);
|
|
759
|
-
assert(grown.totals.msgs === 4, "an appended record is picked up from the tail");
|
|
760
|
-
assert(
|
|
761
|
-
getModelAllTimeUsage("gemini-3.8-flash").input === 1150,
|
|
762
|
-
"the appended record adds to the existing totals (no duplicate, no drop)",
|
|
763
|
-
);
|
|
764
|
-
|
|
765
|
-
// The per-file rollup is what makes a refresh cheap: folding a tail must reproduce the same
|
|
766
|
-
// totals as parsing the whole file from scratch. Compare the incremental answer to a cold one.
|
|
767
|
-
const incremental = JSON.stringify(getModelAllTimeUsage("gemini-3.8-flash"));
|
|
768
|
-
const cacheRaw = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, unknown>;
|
|
769
|
-
// Drop the cache (as a fresh machine, or a version bump, would) and rescan the whole file.
|
|
770
|
-
// Writing `{}` is not enough on its own: the disk cache is memoized per process, so the
|
|
771
|
-
// memo would answer and this assert would compare a value against itself, never failing.
|
|
772
|
-
resetUsageCache();
|
|
773
|
-
writeFileSync(cachePath, "{}", "utf8");
|
|
774
|
-
collectUsageSummary(true);
|
|
775
|
-
assert(
|
|
776
|
-
JSON.stringify(getModelAllTimeUsage("gemini-3.8-flash")) === incremental,
|
|
777
|
-
"an incremental tail fold equals a full cold parse of the same file",
|
|
778
|
-
);
|
|
779
|
-
assert(Object.keys(cacheRaw).length === 1, "one session file produces exactly one cache entry");
|
|
780
|
-
|
|
781
|
-
// A half-written trailing record must not be counted, then must appear once completed in place.
|
|
782
|
-
const pending = asst("other-model", 5);
|
|
783
|
-
writeFileSync(file, pending.slice(0, 40), { flag: "a" });
|
|
784
|
-
assert(collectUsageSummary(true).totals.msgs === 4, "a half-written trailing record is not counted");
|
|
785
|
-
writeFileSync(file, pending.slice(40) + String.fromCharCode(10), { flag: "a" });
|
|
786
|
-
assert(collectUsageSummary(true).totals.msgs === 5, "the record is counted once the write completes");
|
|
787
|
-
|
|
788
|
-
// Disk cache pruning: no cache key may point at a session file that is gone.
|
|
789
|
-
rmSync(join(fixture, "sessions", "proj", "a.jsonl"));
|
|
790
|
-
collectUsageSummary(true);
|
|
791
|
-
const raw = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, unknown>;
|
|
792
|
-
assert(Object.keys(raw).length === 0, "usage disk cache prunes deleted session files");
|
|
793
|
-
rmSync(fixture, { recursive: true, force: true });
|
|
794
|
-
|
|
795
|
-
// A flat pre-folder cache is moved into the arnative folder on first read; the v4
|
|
796
|
-
// items keep working (decode feeds the summary, a grown file tail-folds forward) and
|
|
797
|
-
// the next save is the compact v5 shape: session-dir-relative keys, model-only rows.
|
|
798
|
-
const mig = mkdtempSync(join(tmpdir(), "arnative-usage-mig-"));
|
|
799
|
-
process.env.PI_CODING_AGENT_DIR = mig;
|
|
800
|
-
mkdirSync(join(mig, "sessions", "p"), { recursive: true });
|
|
801
|
-
const migFile = join(mig, "sessions", "p", "a.jsonl");
|
|
802
|
-
const migLine = asst("gemini-3.8-flash", 5) + String.fromCharCode(10);
|
|
803
|
-
writeFileSync(migFile, migLine, "utf8");
|
|
804
|
-
const migStat = statSync(migFile);
|
|
805
|
-
writeFileSync(
|
|
806
|
-
join(mig, "arnative-usage-cache.json"),
|
|
807
|
-
JSON.stringify({
|
|
808
|
-
[migFile]: {
|
|
809
|
-
mtimeMs: migStat.mtimeMs,
|
|
810
|
-
size: migStat.size,
|
|
811
|
-
v: 4,
|
|
812
|
-
consumed: migStat.size,
|
|
813
|
-
rollup: {
|
|
814
|
-
providers: {
|
|
815
|
-
"x\u0000m": { sessions: 1, msgs: 3, input: 4, output: 5, cacheRead: 6, cost: 0 },
|
|
816
|
-
"x": { sessions: 1, msgs: 3, input: 4, output: 5, cacheRead: 6, cost: 0 },
|
|
817
|
-
},
|
|
818
|
-
},
|
|
819
|
-
},
|
|
820
|
-
}),
|
|
821
|
-
"utf8",
|
|
822
|
-
);
|
|
823
|
-
resetUsageCache();
|
|
824
|
-
assert(collectUsageSummary(true).totals.msgs === 1, "a migrated v4 entry is re-parsed once (it predates the day buckets and the billed split)");
|
|
825
|
-
writeFileSync(migFile, asst("gemini-3.8-flash", 7) + String.fromCharCode(10), { flag: "a" });
|
|
826
|
-
assert(collectUsageSummary(true).totals.msgs === 2, "a grown file is re-parsed whole after the v4 item was dropped, not tail-folded on stale sums");
|
|
827
|
-
assert(existsSync(join(mig, "arnative", "usage-cache.json")), "the cache is saved into the arnative folder");
|
|
828
|
-
const migrated = JSON.parse(readFileSync(join(mig, "arnative", "usage-cache.json"), "utf8")) as Record<string, { r: Record<string, number[]> }>;
|
|
829
|
-
const migKey = join("p", "a.jsonl");
|
|
830
|
-
assert(Object.keys(migrated)[0] === migKey, "v5 keys are stored relative to the sessions dir");
|
|
831
|
-
assert(
|
|
832
|
-
Object.keys(migrated[migKey]!.r).every((k) => k.includes("\u0000")),
|
|
833
|
-
"v5 stores model rows only (provider rows are derived on load)",
|
|
834
|
-
);
|
|
835
|
-
// Layout "1" cleanup: the dead flat prices file and a flat cache a downgrade recreated
|
|
836
|
-
// beside the folder copy are removed on the next load; the folder copy survives.
|
|
837
|
-
writeFileSync(join(mig, "arnative-prices.json"), "{}", "utf8");
|
|
838
|
-
writeFileSync(join(mig, "arnative-usage-cache.json"), "{}", "utf8");
|
|
839
|
-
resetUsageCache();
|
|
840
|
-
collectUsageSummary(true);
|
|
841
|
-
assert(!existsSync(join(mig, "arnative-prices.json")), "the dead flat prices file is removed");
|
|
842
|
-
assert(!existsSync(join(mig, "arnative-usage-cache.json")), "a flat cache recreated beside the folder copy is removed");
|
|
843
|
-
assert(existsSync(join(mig, "arnative", "usage-cache.json")), "the folder copy survives the cleanup");
|
|
844
|
-
rmSync(mig, { recursive: true, force: true });
|
|
845
|
-
// Back to the main fixture: the UI rows below still scan it.
|
|
846
|
-
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
847
|
-
resetUsageCache();
|
|
848
|
-
|
|
849
|
-
// UI checks need rows of their own: the scratch above ends with an empty, deleted file.
|
|
850
|
-
// These use a provider that reports NO cost (cost.total = 0), which is the case the estimate
|
|
851
|
-
// exists for; `asst` above reports 0.02 per message and would be priced by the provider.
|
|
852
|
-
mkdirSync(join(fixture, "sessions", "ui"), { recursive: true });
|
|
853
|
-
const freeAsstOf = (provider: string, model: string, input: number) =>
|
|
854
|
-
JSON.stringify({ message: { role: "assistant", provider, model, usage: { input, output: 5, cacheRead: 1, cacheWrite: 3, cost: { total: 0 } } } });
|
|
855
|
-
const freeAsst = (model: string, input: number) => freeAsstOf("alpha", model, input);
|
|
856
|
-
writeFileSync(
|
|
857
|
-
join(fixture, "sessions", "ui", "rows.jsonl"),
|
|
858
|
-
[
|
|
859
|
-
freeAsst("gemini-3.8-flash", 100),
|
|
860
|
-
freeAsst("other-model", 7),
|
|
861
|
-
// The shipped shape of the collision: a bare id and, on another provider, a path id
|
|
862
|
-
// that merely ENDS with it. Suffix matching folded the second into the first, so a first
|
|
863
|
-
// run under a shared alias showed two providers' usage as if it were one provider's own.
|
|
864
|
-
freeAsst("deepseek-v4.1-flash", 300),
|
|
865
|
-
freeAsstOf("shared", "team/deepseek-ai/DeepSeek-V4.1-Flash", 200),
|
|
866
|
-
].join(String.fromCharCode(10)),
|
|
867
|
-
);
|
|
868
|
-
collectUsageSummary(true);
|
|
869
|
-
|
|
870
|
-
// Per-id totals: a model id reports its own tokens only, whatever it is a suffix of.
|
|
871
|
-
assert(getModelAllTimeUsage("deepseek-v4.1-flash").input === 300, "a bare id does not absorb a longer id that ends with it");
|
|
872
|
-
assert(getModelAllTimeUsage("team/deepseek-ai/DeepSeek-V4.1-Flash").input === 200, "a path id counts its own provider's tokens only");
|
|
873
|
-
assert(getModelAllTimeUsage("TEAM/DeepSeek-AI/deepseek-V4.1-Flash").input === 200, "case still does not split one model's history");
|
|
874
|
-
assert(getModelAllTimeUsage("deepseek-v4.1-flash:free").input === 300, "a route tag folds into the model it tags");
|
|
875
|
-
|
|
876
|
-
// Cost estimation: unpriced pairs use rates declared automatically in models.json.
|
|
877
|
-
assert(loadPriceTable() !== null && Object.keys(loadPriceTable()).length === 0, "no models.json rates means an empty table");
|
|
878
|
-
assert(!hasPrice("alpha", "gemini-3.8-flash"), "a pair absent from models.json has no price");
|
|
879
|
-
assert(estimateCost(1000, 100, 0, 0, "gemini-3.8-flash", "alpha") === null, "an unknown pair estimates nothing");
|
|
880
|
-
assert(collectUsageSummary(true).totals.estimatedCost === 0, "nothing is estimated without rates");
|
|
881
|
-
assert(estimateCost(1000, 100, 0, 0, "other-model", "alpha") === null, "a second unpriced pair estimates nothing either");
|
|
882
|
-
|
|
883
|
-
writeFileSync(
|
|
884
|
-
join(fixture, "models.json"),
|
|
885
|
-
JSON.stringify({
|
|
886
|
-
providers: {
|
|
887
|
-
alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 1, output: 2, cacheRead: 0.1 } }] },
|
|
888
|
-
beta: { models: [{ id: "gemini-3.8-flash", cost: { input: 10, output: 20 } }] },
|
|
889
|
-
},
|
|
890
|
-
}),
|
|
891
|
-
);
|
|
892
|
-
const table0 = loadPriceTable();
|
|
893
|
-
assert(hasPrice("alpha", "gemini-3.8-flash"), "a priced provider+model is found in the table");
|
|
894
|
-
assert(!hasPrice("enclave", "gemini-3.8-flash"), "another provider with no entry is not priced");
|
|
895
|
-
assert(estimateCost(1_000_000, 0, 0, 0, "gemini-3.8-flash", "alpha") === 1, "1M input tokens at alpha's $1/M costs $1");
|
|
896
|
-
assert(
|
|
897
|
-
estimateCost(1_000_000, 0, 0, 0, "gemini-3.8-flash", "beta") === 10,
|
|
898
|
-
"the SAME model at beta costs 10x (rates are per provider, not per model)",
|
|
899
|
-
);
|
|
900
|
-
assert(estimateCost(0, 1_000_000, 0, 0, "gemini-3.8-flash", "alpha") === 2, "1M output tokens at $2/M costs $2");
|
|
901
|
-
assert(Math.abs(estimateCost(0, 0, 1_000_000, 0, "gemini-3.8-flash", "alpha")! - 0.1) < 1e-9, "cache reads use their own rate");
|
|
902
|
-
assert(estimateCost(1_000_000, 0, 0, 0, "vendor/gemini-3.8-flash", "alpha") === 1, "a vendor/my-model id matches the model rate");
|
|
903
|
-
const withPrices = collectUsageSummary(true);
|
|
904
|
-
assert(withPrices.totals.estimatedCost > 0, "models.json rates produce an estimate");
|
|
905
|
-
assert(withPrices.totals.reportedCost === 0, "the reported total stays at the provider's own number");
|
|
906
|
-
assert(withPrices.totals.cost === withPrices.totals.reportedCost, "the headline cost never absorbs the estimate");
|
|
907
|
-
assert(estimateCost(1_000_000, 0, 0, 0, "other-model", "alpha") === null, "a pair with no rate stays unpriced even when others are priced");
|
|
908
|
-
assert(loadPriceTable() === loadPriceTable(), "an unchanged models.json is read once (memo identity)");
|
|
909
|
-
await new Promise((r) => setTimeout(r, 5)); // mtime granularity: a rewrite must change the memo key
|
|
910
|
-
writeFileSync(
|
|
911
|
-
join(fixture, "models.json"),
|
|
912
|
-
JSON.stringify({
|
|
913
|
-
providers: {
|
|
914
|
-
alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 0.5 } }] },
|
|
915
|
-
beta: { models: [{ id: "gemini-3.8-flash", cost: { input: 10, output: 20 } }] },
|
|
916
|
-
},
|
|
917
|
-
}),
|
|
918
|
-
);
|
|
919
|
-
assert(loadPriceTable() !== table0 && estimateCost(0, 0, 0, 1_000_000, "gemini-3.8-flash", "alpha") === 0.5, "cache writes are priced, and a changed models.json is re-read");
|
|
920
|
-
|
|
921
|
-
const fakeTheme = {
|
|
922
|
-
fg: (_c: string, t: string) => `\x1b[38;2;100;100;100m${t}\x1b[39m`,
|
|
923
|
-
bold: (t: string) => `\x1b[1m${t}\x1b[22m`,
|
|
924
|
-
};
|
|
925
|
-
const modal = new UsageModalComponent(fakeTheme, () => {}, () => {});
|
|
926
|
-
const lines = modal.render(100);
|
|
927
|
-
assert(lines.length >= 8, "modal render produces table lines");
|
|
928
|
-
assert(lines[0]!.includes("╭") && lines[0]!.includes("╮"), "round top border");
|
|
929
|
-
assert(visibleWidth(lines[0]!) === 100, "box border full width (100 columns)");
|
|
930
|
-
// The title follows the one arnative shape, `<setting> - <extension>⠙` — the same helper the
|
|
931
|
-
// menus use, so this screen cannot keep an old title of its own.
|
|
932
|
-
assert(lines[1]!.includes(screenTitle("Usage")), "the dashboard title uses the shared <setting> - <extension> shape");
|
|
933
|
-
assert(lines[1]!.includes("Usage - Arnative\u2819"), "the dashboard title carries the arnative brand");
|
|
934
|
-
assert(!lines.map((l) => l.replace(/\x1b\[[0-9;]*m/g, "")).join("\n").includes("LLM Usage"), "the old one-off title is gone");
|
|
935
|
-
assert(lines[lines.length - 1]!.includes("╰") && lines[lines.length - 1]!.includes("╯"), "round bottom border");
|
|
936
|
-
assert(
|
|
937
|
-
lines.every((l) => visibleWidth(l) <= 100),
|
|
938
|
-
"every line fits within width 100",
|
|
939
|
-
);
|
|
940
|
-
assert(
|
|
941
|
-
lines.every((l) => ["╭", "│", "╰"].some((c) => l.includes(c))),
|
|
942
|
-
"no line missing a box side",
|
|
943
|
-
);
|
|
944
|
-
|
|
945
|
-
// Compact layout: the four noisy columns (↑In/↓Out/Cache) are gone from the table; the
|
|
946
|
-
// selected row states them in the detail line instead.
|
|
947
|
-
const plain = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, "");
|
|
948
|
-
// Prices view (`v` cycles Provider → Project → Prices): every models.json pair with its
|
|
949
|
-
// $/1M rates on the same column grid, sorted by input rate, and a used model the table does
|
|
950
|
-
// not price marked `unpriced` — that is the model whose Cost cell reads `-`.
|
|
951
|
-
const priceModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "high");
|
|
952
|
-
priceModal.handleInput("v");
|
|
953
|
-
priceModal.handleInput("v");
|
|
954
|
-
// Group rows are collapsed by default; the check opens both providers to read their children.
|
|
955
|
-
(priceModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["alpha", "beta"]);
|
|
956
|
-
const priceLines = priceModal.render(120);
|
|
957
|
-
const priceBody = priceLines.map(plain).join("\n");
|
|
958
|
-
assert(priceBody.includes("In $/M") && priceBody.includes("Write $/M"), "the Prices view header names the rate columns");
|
|
959
|
-
assert(priceBody.includes("Alpha") && priceBody.includes("gemini-3.8-flash"), "the Prices view nests models under their provider");
|
|
960
|
-
assert(priceBody.includes("$1.00"), "input rates render as $/1M");
|
|
961
|
-
assert(priceBody.includes("unpriced") && priceBody.includes("other-model"), "a used model absent from models.json is marked unpriced");
|
|
962
|
-
assert(priceBody.includes("2 priced · 2 unpriced (models.json)"), "the Prices view counts priced and unpriced rows");
|
|
963
|
-
priceModal.handleInput("v");
|
|
964
|
-
assert(priceModal.render(120).some((l) => plain(l).includes("Provider / Model")), "`v` cycles back to the Provider view");
|
|
965
|
-
|
|
966
|
-
const body = lines.map(plain).join("\n");
|
|
967
|
-
assert(body.includes("Tokens"), "compact table keeps the Tokens column");
|
|
968
|
-
assert(body.includes("Cost"), "compact table keeps the Cost column");
|
|
969
|
-
assert(!lines.some((l) => plain(l).includes("↑In")), "compact table drops the ↑In column");
|
|
970
|
-
assert(!lines.some((l) => plain(l).includes("↓Out")), "compact table drops the ↓Out column");
|
|
971
|
-
assert(lines.some((l) => plain(l).includes("↑")), "the selected row still shows its in/out detail");
|
|
972
|
-
|
|
973
|
-
// Layout contract: full header words, the detail line UNDER the table (not above it),
|
|
974
|
-
// and the total below the rule that closes the rows.
|
|
975
|
-
assert(body.includes("Session"), "the header spells Session in full");
|
|
976
|
-
assert(body.includes("Messages"), "the header spells Messages in full");
|
|
977
|
-
const at = (needle: string) => lines.findIndex((l) => plain(l).includes(needle));
|
|
978
|
-
const firstRow = lines.findIndex((l) => plain(l).includes("▾") || plain(l).includes("▸"));
|
|
979
|
-
const detailAt = lines.findIndex((l) => plain(l).includes("cache ") && plain(l).includes("↑"));
|
|
980
|
-
assert(detailAt > firstRow, "the detail line sits below the table, not above it");
|
|
981
|
-
assert(at("Total") > detailAt, "the total sits below the detail line");
|
|
982
|
-
assert(at("Provider / Model") < firstRow, "the header sits above the first row");
|
|
983
|
-
// The chrome is the whole chrome: no inner `├─┤` rule (skill arnative-pi rule 7), the sections
|
|
984
|
-
// are separated by blank rows the way every /arnative menu separates them.
|
|
985
|
-
assert(!lines.some((l) => /[├┤]/.test(l)), "the dashboard draws no inner rule");
|
|
986
|
-
assert(
|
|
987
|
-
lines.findIndex((l) => plain(l).includes("across all local Pi sessions")) < firstRow,
|
|
988
|
-
"the description sits above the table",
|
|
989
|
-
);
|
|
990
|
-
assert(plain(lines[detailAt]!).includes("\uf4bc"), "the detail line carries its icon");
|
|
991
|
-
// No rule between the header and its first row (the header labels the rows below it),
|
|
992
|
-
// while the rules after the description and before Total stay.
|
|
993
|
-
const headerAt = lines.findIndex((l) => plain(l).includes("Provider / Model"));
|
|
994
|
-
assert(
|
|
995
|
-
!lines.slice(headerAt + 1, firstRow).some((l) => l.includes("├")),
|
|
996
|
-
"no rule sits between the header and the first row",
|
|
997
|
-
);
|
|
998
|
-
assert(/^─+$/.test(plain(lines[headerAt - 1]!).slice(1, -1).trim()), "a rule closes the window bar above the header");
|
|
999
|
-
// The header is content: it sits flush with the title, and each column title ends on the
|
|
1000
|
-
// same cell its own numbers end on.
|
|
1001
|
-
const headerLine = plain(lines[headerAt]!);
|
|
1002
|
-
// The Total row always carries a value in every column, so it is the stable ruler to
|
|
1003
|
-
// measure the grid against (a provider row can show `-`).
|
|
1004
|
-
const dataLine = plain(lines[at("Total")]!);
|
|
1005
|
-
// Total sits on the header's grid, one table-width rule above it.
|
|
1006
|
-
const totalLine = plain(lines[at("Total")]!);
|
|
1007
|
-
assert(
|
|
1008
|
-
totalLine.indexOf("Total") === headerLine.indexOf("Provider / Model"),
|
|
1009
|
-
`Total is on the header grid (header ${headerLine.indexOf("Provider / Model")}, total ${totalLine.indexOf("Total")})`,
|
|
1010
|
-
);
|
|
1011
|
-
const totalAt = at("Total");
|
|
1012
|
-
const ruleLine = plain(lines[totalAt - 1]!);
|
|
1013
|
-
assert(/─{10,}/.test(ruleLine), "a table rule separates the table from Total");
|
|
1014
|
-
assert(!/[├┤]/.test(ruleLine), "the table rule is not a full-width frame junction");
|
|
1015
|
-
const ruleStart = ruleLine.indexOf("─");
|
|
1016
|
-
const ruleEnd = ruleLine.lastIndexOf("─") + 1;
|
|
1017
|
-
assert(ruleStart === headerLine.indexOf("Provider / Model"), "the rule starts at the table's left edge");
|
|
1018
|
-
assert(ruleEnd <= 100 - 3, `the rule stops at the table's right edge, got ${ruleEnd}`);
|
|
1019
|
-
// Every column title ends on the same cell its numbers end on, so the header reads as the
|
|
1020
|
-
// table's ruler instead of drifting a column or two to the left of its own data.
|
|
1021
|
-
const right = (line: string, text: string) => line.indexOf(text) + text.length;
|
|
1022
|
-
assert(headerLine.indexOf("Provider / Model") === dataLine.indexOf("Total"), "the header name column starts over the row names");
|
|
1023
|
-
// Flush left with the box title: no screen row is indented into a gutter the header does
|
|
1024
|
-
// not use, so the title, the table, the rule and Total share one left edge.
|
|
1025
|
-
const titleCol = plain(lines[1]!).indexOf("Usage - Arnative");
|
|
1026
|
-
for (const [what, col] of [
|
|
1027
|
-
["the header", headerLine.indexOf("Provider / Model")],
|
|
1028
|
-
["the table rule", ruleStart],
|
|
1029
|
-
["Total", dataLine.indexOf("Total")],
|
|
1030
|
-
] as const) {
|
|
1031
|
-
assert(col === titleCol, `${what} starts on the title's left edge (${col} vs ${titleCol})`);
|
|
1032
|
-
}
|
|
1033
|
-
// A right-aligned column ends exactly where its title ends: take the slice of the row up
|
|
1034
|
-
// to that boundary and it must be flush against it, never a cell short or a cell over.
|
|
1035
|
-
let edge = headerLine.indexOf("Provider / Model");
|
|
1036
|
-
for (const title of ["Session", "Messages", "Tokens", "Cost"]) {
|
|
1037
|
-
const boundary = right(headerLine, title);
|
|
1038
|
-
const cell = dataLine.slice(edge, boundary);
|
|
1039
|
-
assert(cell.trim() !== "", `the ${title} cell is not empty`);
|
|
1040
|
-
assert(cell === cell.trimEnd(), `the ${title} value is right-aligned to its column edge`);
|
|
1041
|
-
edge = boundary;
|
|
1042
|
-
}
|
|
1043
|
-
// The unpriced notice is gone: the `-` in Cost already says it.
|
|
1044
|
-
assert(!body.includes("unpriced"), "the unpriced notice line is removed");
|
|
1045
|
-
// Provider rows are capitalized so they read as names, not raw ids.
|
|
1046
|
-
assert(plain(lines[firstRow]!).includes("Alpha") || plain(lines[firstRow]!).includes("Google"), "provider rows are capitalized");
|
|
1047
|
-
|
|
1048
|
-
// Thinking level -> theme slot is unit-tested in lib/ansi.ts (one definition); here we
|
|
1049
|
-
// only prove the box border actually takes its color from that slot at render time.
|
|
1050
|
-
const taggedTheme = { fg: (c: string, t: string) => `<${c}>${t}</>`, bold: (t: string) => t };
|
|
1051
|
-
// Wide enough that the tagged theme's literal <tag> text does not force truncation.
|
|
1052
|
-
const high = new UsageModalComponent(taggedTheme, () => {}, () => {}, "high");
|
|
1053
|
-
const highLines = high.render(260);
|
|
1054
|
-
assert(highLines[0]!.includes("<thinkingHigh>"), "the box border uses the thinking slot from the session level");
|
|
1055
|
-
// The detail line: icon in accent, its text and dividers in accentSoft.
|
|
1056
|
-
const detailTagged = highLines.find((l) => l.includes("<accent>\uf4bc</>") || (l.includes("\uf4bc") && l.includes("↑")))!;
|
|
1057
|
-
assert(detailTagged.includes("<accent>\uf4bc</>"), "the detail icon is accent-colored");
|
|
1058
|
-
assert(!detailTagged.includes("<thinkingHigh>\uf4bc"), "the detail icon is NOT the border/thinking color");
|
|
1059
|
-
assert(/<accentSoft>[^<]*↑/.test(detailTagged), "the detail values are accentSoft");
|
|
1060
|
-
assert(detailTagged.includes("<accentSoft> · </>"), "the detail divider is accentSoft");
|
|
1061
|
-
const offLines = new UsageModalComponent(taggedTheme, () => {}, () => {}, "off").render(260);
|
|
1062
|
-
assert(offLines[0]!.includes("<thinkingOff>"), "thinking off colors the border with thinkingOff");
|
|
1063
|
-
// Pi 1.2+ rejects `accentSoft`/`secondarySoft` in `fg`; the rows and detail must still paint
|
|
1064
|
-
// (softOf derives the tint from `colors.accent`), or the dashboard crashes on render.
|
|
1065
|
-
const strictTheme = {
|
|
1066
|
-
fg: (c: string, t: string) => {
|
|
1067
|
-
if (c === "accentSoft" || c === "secondarySoft") throw new Error(`Unknown theme color: ${c}`);
|
|
1068
|
-
return t;
|
|
1069
|
-
},
|
|
1070
|
-
style: (t: string) => t,
|
|
1071
|
-
colors: { accent: { kind: "oklch", l: 0.7, c: 0.1, h: 200 } },
|
|
1072
|
-
} as never;
|
|
1073
|
-
assert(
|
|
1074
|
-
new UsageModalComponent(strictTheme, () => {}, () => {}, "off").render(120).length > 0,
|
|
1075
|
-
"a theme without the soft tokens still renders the rows",
|
|
1076
|
-
);
|
|
1077
|
-
// Project view: the project group row sits on plain text like a provider group row, its
|
|
1078
|
-
// folder content (the providers under it) on dim, and the expand arrow carries the accent.
|
|
1079
|
-
const taggedProject = new UsageModalComponent(taggedTheme, () => {}, () => {}, "off");
|
|
1080
|
-
taggedProject.handleInput("v");
|
|
1081
|
-
const projectLines = taggedProject.render(260);
|
|
1082
|
-
assert(projectLines.some((l) => /<accent>[▸▾]/.test(l)), "the expand arrow carries the accent");
|
|
1083
|
-
assert(
|
|
1084
|
-
projectLines.some((l) => /│<\/>\s{3,5}<dim>/.test(l)),
|
|
1085
|
-
"a provider row under a project sits on dim text, indented like a model row",
|
|
1086
|
-
);
|
|
1087
|
-
taggedProject.handleInput("j");
|
|
1088
|
-
const selectedLines = taggedProject.render(260);
|
|
1089
|
-
assert(selectedLines.some((l) => l.includes("<text>unknown")), "the project label sits on plain text");
|
|
1090
|
-
assert(!projectLines.some((l) => /│<\/>\s{3,5}<text>/.test(l)), "no provider under a project keeps the plain text color");
|
|
1091
|
-
assert(selectedLines.some((l) => /<accentSoft>\w/.test(l)), "the selected provider row takes the soft accent");
|
|
1092
|
-
// Shared chrome (per `renderScreen`): title accent+bold, description muted, legend dim.
|
|
1093
|
-
// `taggedTheme.bold` is identity, so only the accent wrapper shows here; the bold half is
|
|
1094
|
-
// pinned in lib/box.ts.
|
|
1095
|
-
assert(highLines[1]!.includes("<accent>Usage - Arnative"), "the dashboard title is accent-colored");
|
|
1096
|
-
assert(highLines[2]!.includes("<muted>Provider · Token, message"), "the dashboard description names the view and is muted");
|
|
1097
|
-
assert(highLines[highLines.length - 2]!.includes("<dim>["), "the dashboard legend is dim");
|
|
1098
|
-
assert(!highLines.some((l) => /[├┤]/.test(l)), "the dashboard draws no inner rule");
|
|
1099
|
-
|
|
1100
|
-
// Mouse: a click on a provider row toggles it, a click on empty space is ignored.
|
|
1101
|
-
const clickModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "medium");
|
|
1102
|
-
const clickLines = clickModal.render(100);
|
|
1103
|
-
const providerLine = clickLines.findIndex((l) => plain(l).includes("▸") || plain(l).includes("▾"));
|
|
1104
|
-
assert(providerLine > 0, "a provider row is rendered");
|
|
1105
|
-
const before = plain(clickModal.render(100)[providerLine]!);
|
|
1106
|
-
const toggled = clickModal.handleMouse!({
|
|
1107
|
-
type: "click",
|
|
1108
|
-
button: "left",
|
|
1109
|
-
x: 3,
|
|
1110
|
-
y: providerLine,
|
|
1111
|
-
screenX: 3,
|
|
1112
|
-
screenY: providerLine,
|
|
1113
|
-
width: 100,
|
|
1114
|
-
height: clickLines.length,
|
|
1115
|
-
shift: false,
|
|
1116
|
-
alt: false,
|
|
1117
|
-
ctrl: false,
|
|
1118
|
-
} as never);
|
|
1119
|
-
assert(toggled?.handled === true, "a click on a provider row is handled");
|
|
1120
|
-
const after = plain(clickModal.render(100)[providerLine]!);
|
|
1121
|
-
assert(before !== after, "clicking the row toggled the provider (marker changed)");
|
|
1122
|
-
assert(
|
|
1123
|
-
clickModal.handleMouse!({
|
|
1124
|
-
type: "click",
|
|
1125
|
-
button: "left",
|
|
1126
|
-
x: 3,
|
|
1127
|
-
y: clickLines.length + 50,
|
|
1128
|
-
screenX: 3,
|
|
1129
|
-
screenY: clickLines.length + 50,
|
|
1130
|
-
width: 100,
|
|
1131
|
-
height: clickLines.length,
|
|
1132
|
-
shift: false,
|
|
1133
|
-
alt: false,
|
|
1134
|
-
ctrl: false,
|
|
1135
|
-
} as never) === undefined,
|
|
1136
|
-
"a click outside any row is ignored",
|
|
1137
|
-
);
|
|
1138
|
-
// A hover move is not consumed and not repainted: nothing on screen depends on it.
|
|
1139
|
-
assert(
|
|
1140
|
-
clickModal.handleMouse!({
|
|
1141
|
-
type: "move",
|
|
1142
|
-
button: "none",
|
|
1143
|
-
x: 3,
|
|
1144
|
-
y: providerLine,
|
|
1145
|
-
screenX: 3,
|
|
1146
|
-
screenY: providerLine,
|
|
1147
|
-
width: 100,
|
|
1148
|
-
height: clickLines.length,
|
|
1149
|
-
shift: false,
|
|
1150
|
-
alt: false,
|
|
1151
|
-
ctrl: false,
|
|
1152
|
-
} as never) === undefined,
|
|
1153
|
-
"a hover move is passed through, not swallowed",
|
|
1154
|
-
);
|
|
1155
|
-
// A wheel event must not be swallowed: scrolling belongs to the terminal.
|
|
1156
|
-
assert(
|
|
1157
|
-
clickModal.handleMouse!({
|
|
1158
|
-
type: "wheel",
|
|
1159
|
-
button: "left",
|
|
1160
|
-
x: 3,
|
|
1161
|
-
y: providerLine,
|
|
1162
|
-
screenX: 3,
|
|
1163
|
-
screenY: providerLine,
|
|
1164
|
-
width: 100,
|
|
1165
|
-
height: clickLines.length,
|
|
1166
|
-
shift: false,
|
|
1167
|
-
alt: false,
|
|
1168
|
-
ctrl: false,
|
|
1169
|
-
} as never) === undefined,
|
|
1170
|
-
"a wheel event is left to the terminal",
|
|
1171
|
-
);
|
|
1172
|
-
// `←` and Esc are the arnative-wide "go back" keys: the dashboard reports them upward
|
|
1173
|
-
// instead of closing, so the /arnative menu can reopen. q still closes it outright.
|
|
1174
|
-
const doneArgs: boolean[] = [];
|
|
1175
|
-
const nav = new UsageModalComponent(fakeTheme, (back) => doneArgs.push(back), () => {}, "high");
|
|
1176
|
-
nav.handleInput("\x1b[D"); // ←
|
|
1177
|
-
nav.handleInput("\x1b"); // Esc
|
|
1178
|
-
nav.handleInput("q");
|
|
1179
|
-
assert(doneArgs.length === 3 && doneArgs[0] === true && doneArgs[1] === true && doneArgs[2] === false, "← and Esc report back, q closes");
|
|
1180
|
-
assert(
|
|
1181
|
-
new UsageModalComponent(fakeTheme, () => {}, () => {}, "high").render(120).some((l) => l.includes("[Esc] Back")),
|
|
1182
|
-
"the dashboard legend advertises Esc Back",
|
|
1183
|
-
);
|
|
1184
|
-
|
|
1185
|
-
// models.json rates price the provider and models directly.
|
|
1186
|
-
writeFileSync(
|
|
1187
|
-
join(fixture, "models.json"),
|
|
1188
|
-
JSON.stringify({
|
|
1189
|
-
providers: {
|
|
1190
|
-
alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 0.28, output: 0.42, cacheRead: 0.028, cacheWrite: 0.3 } }] },
|
|
1191
|
-
beta: { models: [{ id: "gemini-3.8-flash" }] },
|
|
1192
|
-
},
|
|
1193
|
-
}),
|
|
1194
|
-
);
|
|
1195
|
-
const fromModels = collectUsageSummary(true);
|
|
1196
|
-
const alpha = fromModels.providers.find((p) => p.name === "alpha")!;
|
|
1197
|
-
const expected = (100 / 1e6) * 0.28 + (5 / 1e6) * 0.42 + (1 / 1e6) * 0.028 + (3 / 1e6) * 0.3;
|
|
1198
|
-
assert(Math.abs(alpha.estimatedCost - expected) < 1e-12, `models.json cost prices the provider, got ${alpha.estimatedCost}`);
|
|
1199
|
-
assert(
|
|
1200
|
-
Math.abs(alpha.models.reduce((n, m) => n + m.estimatedCost, 0) - alpha.estimatedCost) < 1e-9,
|
|
1201
|
-
"a provider's estimate is the sum of its models' estimates",
|
|
1202
|
-
);
|
|
1203
|
-
assert(alpha.models.find((m) => m.name === "other-model")!.estimatedCost === 0, "a model without a declared cost stays unpriced");
|
|
1204
|
-
writeFileSync(join(fixture, "models.json"), "{}", "utf8");
|
|
1205
|
-
collectUsageSummary(true);
|
|
1206
|
-
|
|
1207
|
-
// Per-row estimates: a row whose provider reported nothing but has a rate shows `~$x`
|
|
1208
|
-
// instead of `-`, while a reported cost is never prefixed. The total line names both
|
|
1209
|
-
// sources, since a rate can come from `models.json` or the user's table.
|
|
1210
|
-
const estModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "low");
|
|
1211
|
-
(estModal as unknown as { summary: unknown }).summary = {
|
|
1212
|
-
providers: [
|
|
1213
|
-
{
|
|
1214
|
-
name: "alpha", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000,
|
|
1215
|
-
totalTokens: 3_500_000, cost: 0, estimatedCost: 0.546,
|
|
1216
|
-
models: [{ name: "deepseek-v4.1-flash", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000, totalTokens: 3_500_000, cost: 0, estimatedCost: 0.546 }],
|
|
1217
|
-
},
|
|
1218
|
-
{
|
|
1219
|
-
name: "antigravity", sessions: 1, msgs: 1, input: 2_200_000, output: 626_000, cacheRead: 0,
|
|
1220
|
-
totalTokens: 2_826_000, cost: 0.65, estimatedCost: 0,
|
|
1221
|
-
models: [{ name: "gemini-3.8-flash", sessions: 1, msgs: 1, input: 2_200_000, output: 626_000, cacheRead: 0, totalTokens: 2_826_000, cost: 0.65, estimatedCost: 0 }],
|
|
1222
|
-
},
|
|
1223
|
-
],
|
|
1224
|
-
totals: { sessions: 2, msgs: 3, input: 3_200_000, output: 1_126_000, cacheRead: 2_000_000, totalTokens: 6_326_000, cost: 0.65, reportedCost: 0.65, estimatedCost: 0.546 },
|
|
1225
|
-
projects: [],
|
|
1226
|
-
};
|
|
1227
|
-
(estModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["alpha"]);
|
|
1228
|
-
const estLines = estModal.render(90);
|
|
1229
|
-
const estBody = estLines.map(plain).join("\n");
|
|
1230
|
-
assert(estBody.includes("~$0.55"), "a row with a rate but no reported cost shows the estimate with `~`");
|
|
1231
|
-
assert(estBody.includes("$0.65") && !estBody.includes("~$0.65"), "a reported cost is shown as-is, never with `~`");
|
|
1232
|
-
assert(!estBody.includes("estimated (models.json)"), "the separate estimate line is gone; the Total row carries the number");
|
|
1233
|
-
// Only the two table rows — the detail line also carries the estimate.
|
|
1234
|
-
const estRows = estLines.map(plain).filter((l) => /^\u2502\s+(?:[\u25be\u25b8]\s+)?(Alpha|deepseek)/.test(l));
|
|
1235
|
-
assert(estRows.length === 2 && estRows.every((l) => l.includes("~$0.55")), `the estimate shows on the provider row and its model row, got ${JSON.stringify(estRows)}`);
|
|
1236
|
-
|
|
1237
|
-
// Cost must survive every width: a clipped `$5` is worse than a dropped column.
|
|
1238
|
-
for (const w of [60, 64, 78, 82, 90, 120]) {
|
|
1239
|
-
const wide = new UsageModalComponent(fakeTheme, () => {}, () => {}, "high");
|
|
1240
|
-
const rendered = wide.render(w);
|
|
1241
|
-
assert(
|
|
1242
|
-
!rendered.some((l) => /\$\d+[^\d.\s]/.test(plain(l))),
|
|
1243
|
-
`cost is never clipped at width ${w}`,
|
|
1244
|
-
);
|
|
1245
|
-
}
|
|
1246
|
-
|
|
1247
|
-
// The two sub-lines under the Total band are gone: the table and the Total row carry the
|
|
1248
|
-
// numbers, and a smaller window is not worth a second line under every view.
|
|
1249
|
-
assert(!estBody.includes("today $"), "no day-bucket line under the Total band");
|
|
1250
|
-
assert(
|
|
1251
|
-
new UsageModalComponent(fakeTheme, () => {}, () => {}, "high").render(120).some((l) => plain(l).includes("[v] Next: Project")),
|
|
1252
|
-
"the rendered legend names the next view",
|
|
1253
|
-
);
|
|
1254
|
-
|
|
1255
|
-
// View cycle (`v`): Provider → Project → Provider. The Project view keeps the one column
|
|
1256
|
-
// grid, its project rows sum to the Total row, and the day line sits under the Total band.
|
|
1257
|
-
const viewModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "high");
|
|
1258
|
-
const win = { cost: 0.07, input: 1300, output: 35, cacheRead: 6 };
|
|
1259
|
-
(viewModal as unknown as { summary: unknown }).summary = {
|
|
1260
|
-
providers: [
|
|
1261
|
-
{
|
|
1262
|
-
name: "alpha", sessions: 2, msgs: 3, input: 1200, output: 30, cacheRead: 5, totalTokens: 1230, cost: 0.05, estimatedCost: 0,
|
|
1263
|
-
models: [{ name: "m1", sessions: 2, msgs: 3, input: 1200, output: 30, cacheRead: 5, totalTokens: 1230, cost: 0.05, estimatedCost: 0 }],
|
|
1264
|
-
},
|
|
1265
|
-
{
|
|
1266
|
-
name: "beta", sessions: 1, msgs: 1, input: 100, output: 5, cacheRead: 1, totalTokens: 105, cost: 0.02, estimatedCost: 0,
|
|
1267
|
-
models: [{ name: "m2", sessions: 1, msgs: 1, input: 100, output: 5, cacheRead: 1, totalTokens: 105, cost: 0.02, estimatedCost: 0 }],
|
|
1268
|
-
},
|
|
1269
|
-
],
|
|
1270
|
-
projects: [
|
|
1271
|
-
{
|
|
1272
|
-
name: "/repo/alpha", sessions: 2, msgs: 3, input: 1200, output: 30, cacheRead: 5, totalTokens: 1230, cost: 0.05, estimatedCost: 0,
|
|
1273
|
-
providers: [{ name: "alpha", sessions: 2, msgs: 3, input: 1200, output: 30, cacheRead: 5, totalTokens: 1230, cost: 0.05, estimatedCost: 0, models: [] }],
|
|
1274
|
-
},
|
|
1275
|
-
{
|
|
1276
|
-
name: "unknown", sessions: 1, msgs: 1, input: 100, output: 5, cacheRead: 1, totalTokens: 105, cost: 0.02, estimatedCost: 0,
|
|
1277
|
-
providers: [{ name: "beta", sessions: 1, msgs: 1, input: 100, output: 5, cacheRead: 1, totalTokens: 105, cost: 0.02, estimatedCost: 0, models: [] }],
|
|
1278
|
-
},
|
|
1279
|
-
],
|
|
1280
|
-
totals: { sessions: 3, msgs: 4, input: 1300, output: 35, cacheRead: 6, totalTokens: 1335, cost: 0.07, reportedCost: 0.07, estimatedCost: 0, today: win, last7d: win, last30d: win },
|
|
1281
|
-
};
|
|
1282
|
-
(viewModal as unknown as { expandedProjects: Set<string> }).expandedProjects = new Set(["/repo/alpha"]);
|
|
1283
|
-
const provHeader = plain(viewModal.render(100).find((l) => l.includes("Provider / Model"))!);
|
|
1284
|
-
viewModal.handleInput("v");
|
|
1285
|
-
const projLines = viewModal.render(100);
|
|
1286
|
-
const projBody = projLines.map(plain).join("\n");
|
|
1287
|
-
const projHeader = plain(projLines.find((l) => l.includes("Project / Provider"))!);
|
|
1288
|
-
assert(projBody.includes("Project / Provider"), "`v` switches the header to the Project view");
|
|
1289
|
-
for (const col of ["Session", "Messages", "Tokens", "Cost"]) {
|
|
1290
|
-
assert(provHeader.indexOf(col) === projHeader.indexOf(col), `the Project view keeps the ${col} column on the same cell`);
|
|
1291
|
-
}
|
|
1292
|
-
// The last right-aligned cell of a row is its Cost column.
|
|
1293
|
-
const costCell = (l: string) => plain(l).replace(/\u2502$/, "").trimEnd().slice(-10).trim();
|
|
1294
|
-
const num = (cell: string) => (cell.startsWith("$") ? parseFloat(cell.slice(1)) : 0);
|
|
1295
|
-
const projRows = projLines.filter((l) => /^\u2502 [\u25be\u25b8]/.test(plain(l)));
|
|
1296
|
-
const totalCell = costCell(projLines.find((l) => plain(l).includes("Total"))!);
|
|
1297
|
-
assert(projRows.length === 2, "the Project view renders one row per project");
|
|
1298
|
-
assert(
|
|
1299
|
-
Math.abs(projRows.reduce((n, l) => n + num(costCell(l)), 0) - num(totalCell)) < 1e-9,
|
|
1300
|
-
`the project rows sum to the Total row, got ${projRows.map(costCell)} vs ${totalCell}`,
|
|
1301
|
-
);
|
|
1302
|
-
assert(!projBody.includes("today $") && !projBody.includes("estimated (models.json)"), "no summary sub-lines under the Total band");
|
|
1303
|
-
viewModal.handleInput("v");
|
|
1304
|
-
assert(viewModal.render(100).some((l) => plain(l).includes("Provider / Model")), "`v` cycles back to the Provider view");
|
|
1305
|
-
|
|
1306
|
-
// Ranges: three dated files — today, 10 days back, 45 days back — so each window has a
|
|
1307
|
-
// number only it can produce.
|
|
1308
|
-
const dayMs = 86_400_000;
|
|
1309
|
-
const nowMs = Date.now();
|
|
1310
|
-
const stampOf = (offsetDays: number): string => new Date(nowMs - offsetDays * dayMs).toISOString();
|
|
1311
|
-
const datedAsst = (provider: string, model: string, input: number, offsetDays: number) =>
|
|
1312
|
-
JSON.stringify({ timestamp: stampOf(offsetDays), message: { role: "assistant", provider, model, usage: { input, output: 1, cacheRead: 0, cost: { total: 0 } } } });
|
|
1313
|
-
writeFileSync(
|
|
1314
|
-
join(fixture, "sessions", "ui", "dated.jsonl"),
|
|
1315
|
-
[datedAsst("rangely", "m-today", 10, 0), datedAsst("rangely", "m-ten", 20, 10), datedAsst("rangely", "m-old", 40, 45)].join(String.fromCharCode(10)),
|
|
1316
|
-
);
|
|
1317
|
-
resetUsageCache();
|
|
1318
|
-
const msgIn = (range: UsageRange): number => {
|
|
1319
|
-
const found = collectUsageSummary(true, range).providers.find((p) => p.name === "rangely");
|
|
1320
|
-
return found?.msgs ?? 0;
|
|
1321
|
-
};
|
|
1322
|
-
assert(msgIn("all") === 3, "the all window keeps every dated message");
|
|
1323
|
-
assert(msgIn("today") === 1, "today counts only the message written today");
|
|
1324
|
-
assert(msgIn("7d") === 1, "7 day stops before the ten-day record, so only today counts");
|
|
1325
|
-
assert(msgIn("30d") === 2, "30 day covers today and ten days back, not forty-five");
|
|
1326
|
-
// A window with nothing in it is empty, not an error: the bar can be pressed on a quiet day.
|
|
1327
|
-
assert(collectUsageSummary(true, "today").totals.msgs >= 1, "today still reports the rows it has");
|
|
1328
|
-
|
|
1329
|
-
// The backfill: a cache item written before ranges existed has totals but no day buckets.
|
|
1330
|
-
// Asking for a range must re-parse that file rather than report a wrong window.
|
|
1331
|
-
const cacheFile = join(fixture, "arnative", "usage-cache.json");
|
|
1332
|
-
resetUsageCache();
|
|
1333
|
-
const legacy = JSON.parse(readFileSync(cacheFile, "utf8")) as Record<string, Record<string, unknown>>;
|
|
1334
|
-
for (const item of Object.values(legacy)) delete item.d;
|
|
1335
|
-
writeFileSync(cacheFile, JSON.stringify(legacy), "utf8");
|
|
1336
|
-
resetUsageCache();
|
|
1337
|
-
assert(msgIn("today") === 1, "an item without day buckets is re-parsed once a range is asked for");
|
|
1338
|
-
const reloaded = JSON.parse(readFileSync(cacheFile, "utf8")) as Record<string, { d?: unknown }>;
|
|
1339
|
-
assert(Object.values(reloaded).some((item) => item.d !== undefined), "the re-parse writes the day buckets back");
|
|
1340
|
-
|
|
1341
|
-
// The range bar: four windows, the active one accented, and the counter states how many
|
|
1342
|
-
// rows exist past the viewport. Tab moves the window and the numbers follow it.
|
|
1343
|
-
const barModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "high");
|
|
1344
|
-
const barOnce = barModal.render(100).map(plain);
|
|
1345
|
-
const barLine = barOnce.find((l) => l.includes("All") && l.includes("Today") && l.includes("30 day"));
|
|
1346
|
-
assert(barLine !== undefined, "the range bar names every window on one line");
|
|
1347
|
-
assert(USAGE_RANGES.every((r) => barLine!.includes(RANGE_LABELS[r])), "every range label is on the bar");
|
|
1348
|
-
assert(barLine!.indexOf("All") < barLine!.indexOf("Today"), "the bar keeps tab order");
|
|
1349
|
-
const beforeRange = barModal.render(100).map(plain).join("\n");
|
|
1350
|
-
barModal.handleInput("\t");
|
|
1351
|
-
const afterRange = barModal.render(100).map(plain).join("\n");
|
|
1352
|
-
assert(beforeRange !== afterRange, "Tab switches the window and repaints");
|
|
1353
|
-
barModal.handleInput("\x1b[Z");
|
|
1354
|
-
assert(barModal.render(100).map(plain).join("\n") === beforeRange, "Shift+Tab walks the bar back to where it started");
|
|
1355
|
-
|
|
1356
|
-
// The viewport: five rows on screen with a count and an arrow for what is out of sight.
|
|
1357
|
-
const manyModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "medium");
|
|
1358
|
-
const provider = (n: number) => ({
|
|
1359
|
-
name: `p${n}`, sessions: 1, msgs: 1, input: 1000, output: 10, cacheRead: 0, totalTokens: 1010, cost: 0.01, estimatedCost: 0,
|
|
1360
|
-
models: [{ name: "m", sessions: 1, msgs: 1, input: 1000, output: 10, cacheRead: 0, totalTokens: 1010, cost: 0.01, estimatedCost: 0 }],
|
|
1361
|
-
});
|
|
1362
|
-
(manyModal as unknown as { summary: unknown }).summary = {
|
|
1363
|
-
providers: [1, 2, 3, 4, 5, 6, 7].map(provider),
|
|
1364
|
-
totals: { sessions: 7, msgs: 7, input: 7000, output: 70, cacheRead: 0, totalTokens: 7070, cost: 0.07, reportedCost: 0.07, estimatedCost: 0 },
|
|
1365
|
-
};
|
|
1366
|
-
const many = manyModal.render(96).map(plain);
|
|
1367
|
-
assert(many.some((l) => l.includes("5/7")), "the counter reads 5/7 with five rows shown of seven");
|
|
1368
|
-
assert(many.some((l) => l.includes("↓ 2 more")), "rows below the window are counted");
|
|
1369
|
-
assert(!many.some((l) => l.includes("↑ ")), "nothing is announced above the top of the list");
|
|
1370
|
-
const dataRows = many.filter((l) => /^[│|] [▾▸ ] P[0-9]/.test(l));
|
|
1371
|
-
assert(dataRows.length === 5, `exactly five data rows are drawn (got ${dataRows.length})`);
|
|
1372
|
-
for (let i = 0; i < 6; i++) manyModal.handleInput("\x1b[B");
|
|
1373
|
-
const scrolled = manyModal.render(96).map(plain);
|
|
1374
|
-
assert(scrolled.some((l) => l.includes("↑ 2 more")), "moving down announces the rows now above the window");
|
|
1375
|
-
assert(!scrolled.some((l) => l.includes("↓ ")), "the bottom of the list announces only what is above");
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
// --- Reset: statistics change, session files stay intact -------------------
|
|
1379
|
-
const resetDir = mkdtempSync(join(tmpdir(), "arnative-reset-"));
|
|
1380
|
-
process.env.PI_CODING_AGENT_DIR = resetDir;
|
|
1381
|
-
const resetSessions = join(resetDir, "sessions", "proj");
|
|
1382
|
-
mkdirSync(resetSessions, { recursive: true });
|
|
1383
|
-
const resetLine = JSON.stringify({ message: { role: "assistant", provider: "google", model: "gemini-3.8-flash", usage: { input: 1000, output: 10, cacheRead: 0, cost: { total: 0.01 } } } }) + String.fromCharCode(10);
|
|
1384
|
-
const livePath = join(resetSessions, "live.jsonl");
|
|
1385
|
-
const oldPath = join(resetSessions, "old.jsonl");
|
|
1386
|
-
writeFileSync(livePath, resetLine);
|
|
1387
|
-
writeFileSync(oldPath, resetLine);
|
|
1388
|
-
resetUsageCache();
|
|
1389
|
-
const resetModal = new UsageModalComponent(fakeTheme, () => undefined, () => undefined, "high");
|
|
1390
|
-
assert(resetModal.render(120).map(plain).some((l) => l.includes("[R] Reset")), "the footer advertises R Reset");
|
|
1391
|
-
resetModal.handleInput("R");
|
|
1392
|
-
assert(resetModal.render(120).map(plain).some((l) => l.includes("Reset all usage statistics?") && l.includes("sessions stay")), "R confirms a statistics-only reset");
|
|
1393
|
-
resetModal.handleInput("\x1b");
|
|
1394
|
-
assert(collectUsageSummary(true).totals.msgs === 2, "cancel keeps the statistics");
|
|
1395
|
-
resetModal.handleInput("R");
|
|
1396
|
-
resetModal.handleInput("y");
|
|
1397
|
-
assert(readFileSync(oldPath, "utf8") === resetLine && readFileSync(livePath, "utf8") === resetLine, "reset leaves every session unchanged");
|
|
1398
|
-
assert(resetModal.render(120).map(plain).some((l) => l.includes("Usage statistics reset. Sessions kept.")), "the notice states what changed");
|
|
1399
|
-
assert(collectUsageSummary(true).totals.msgs === 0, "the reset excludes previous messages, including the active session");
|
|
1400
|
-
resetModal.handleInput("U");
|
|
1401
|
-
resetModal.handleInput("y");
|
|
1402
|
-
assert(collectUsageSummary(true).totals.msgs === 2, "undo restores the previous counting baseline");
|
|
1403
|
-
assert(resetModal.render(120).map(plain).some((l) => l.includes("Previous statistics restored.")), "the notice states what came back");
|
|
1404
|
-
rmSync(resetDir, { recursive: true, force: true });
|
|
1405
|
-
console.log("usage.ts self-check OK");
|
|
1406
|
-
}
|