@bismawy/pi-arnative 0.10.1 → 0.11.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.
@@ -11,7 +11,7 @@ import { matchesKey, truncateToWidth, visibleWidth, type Component, type TUI, ty
11
11
  import { renderScreen, screenTitle } from "../lib/box.ts";
12
12
  import { assert, isMain } from "../lib/check.ts";
13
13
  import { capitalize } from "../lib/format.ts";
14
- import { thinkingColorOf, softSecondaryOf } from "../lib/ansi.ts";
14
+ import { thinkingColorOf, softOf, softSecondaryOf } from "../lib/ansi.ts";
15
15
  import { legendUsage, matchesBack, RESET_USAGE, UNDO_USAGE } from "../lib/shortcuts.ts";
16
16
  import {
17
17
  collectUsageSummary,
@@ -20,12 +20,9 @@ import {
20
20
  getModelAllTimeUsage,
21
21
  hasPrice,
22
22
  loadPriceTable,
23
- dayKey,
24
- rangeStart,
25
23
  resetUsageCache,
26
- resetUsageHistory,
27
- restoreUsageHistory,
28
- usageHistorySize,
24
+ resetUsageStats,
25
+ restoreUsageStats,
29
26
  USAGE_RANGES,
30
27
  type UsageRange,
31
28
  type UsageSummary,
@@ -42,26 +39,6 @@ export function formatCost(n: number): string {
42
39
  return `$${(n / 1000).toFixed(1)}k`;
43
40
  }
44
41
 
45
- /** File size in the unit a person reads: 281 MB, 1.4 GB. */
46
- /** `1 session`, `312 sessions`: a count that reads as prose, because the notice is prose. */
47
- function countOf(n: number, noun: string): string {
48
- return n + " " + noun + (n === 1 ? "" : "s");
49
- }
50
-
51
- /** The trash path without the home prefix: the tail is what a person can type. */
52
- function shortTrash(dir: string): string {
53
- const at = dir.replaceAll("\\", "/").indexOf("arnative/usage-trash/");
54
- return at >= 0 ? dir.replaceAll("\\", "/").slice(at) : dir;
55
- }
56
-
57
- export function formatBytes(n: number): string {
58
- if (!n || n <= 0) return "0 B";
59
- if (n < 1024) return n + " B";
60
- if (n < 1024 * 1024) return Math.round(n / 1024) + " kB";
61
- if (n < 1024 * 1024 * 1024) return (n / (1024 * 1024)).toFixed(0) + " MB";
62
- return (n / (1024 * 1024 * 1024)).toFixed(1) + " GB";
63
- }
64
-
65
42
  export function formatCount(n: number): string {
66
43
  return n > 0 ? n.toLocaleString("en-US") : "-";
67
44
  }
@@ -70,7 +47,9 @@ export function formatCount(n: number): string {
70
47
  // =============================================================================
71
48
 
72
49
  export interface RowItem {
73
- type: "provider" | "model";
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;
74
53
  providerName: string;
75
54
  modelName?: string;
76
55
  label: string;
@@ -80,19 +59,46 @@ export interface RowItem {
80
59
  input: number;
81
60
  output: number;
82
61
  cacheRead: number;
62
+ /** Billed cost only; the estimate stays in `estimatedCost`. */
83
63
  cost: number;
84
- /** Cost reconstructed from the price table when `cost` is 0 — shown with a `~`. */
64
+ /** Catalog totals plus the price-table reconstruction when `cost` is 0 — shown with a `~`. */
85
65
  estimatedCost: number;
86
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;
87
71
  }
88
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
+
89
90
  /** Labels on the range bar, in tab order. */
90
91
  const RANGE_LABELS: Record<UsageRange, string> = { all: "All", today: "Today", "7d": "7 day", "30d": "30 day", "3m": "3 month" };
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" };
91
95
  /** Data rows on screen at once: five reads as a table, sixteen pushed the Total row off. */
92
96
  const USAGE_VIEWPORT = 5;
93
97
 
94
98
  export class UsageModalComponent implements Component {
95
99
  private expandedProviders = new Set<string>();
100
+ private expandedProjects = new Set<string>();
101
+ private view: UsageView = "provider";
96
102
  private selectedIndex = 0;
97
103
  private summary: UsageSummary;
98
104
  /** Which window the numbers cover. `all` keeps the old dashboard's meaning. */
@@ -110,12 +116,10 @@ export class UsageModalComponent implements Component {
110
116
  private rowHitboxes: { line: number; index: number }[] = [];
111
117
  /** A destructive step waits here until the user answers it. Nothing is touched before. */
112
118
  private confirmStep: "reset" | "undo" | null = null;
113
- /** One line under the table, stating what the last reset moved. */
119
+ /** One line under the table, stating what the last reset changed. */
114
120
  private notice: string | null = null;
115
- /** The folder the last reset parked the history in, so U can put it back. */
116
- private trashDir: string | null = null;
117
- /** The file pi is writing right now. Moving it would break the running session. */
118
- private activeFile: string | undefined;
121
+ /** A wrapper keeps the first reset undoable when no previous baseline existed. */
122
+ private undoBaseline: { previous: string | null } | null = null;
119
123
 
120
124
  constructor(
121
125
  theme: { fg(c: string, t: string): string; bold?(t: string): string },
@@ -123,11 +127,8 @@ export class UsageModalComponent implements Component {
123
127
  onDone: (back: boolean) => void,
124
128
  requestRender: () => void,
125
129
  thinkingLevel?: string,
126
- /** The session file in use. Excluded from a reset: pi keeps appending to it. */
127
- activeFile?: string,
128
130
  ) {
129
131
  this.theme = theme;
130
- this.activeFile = activeFile;
131
132
  this.onDone = onDone;
132
133
  this.requestRender = requestRender;
133
134
  this.edgeOf = thinkingColorOf(theme, thinkingLevel);
@@ -144,6 +145,101 @@ export class UsageModalComponent implements Component {
144
145
 
145
146
  private buildFlatRows(): RowItem[] {
146
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
+ }
147
243
  for (const p of this.summary.providers) {
148
244
  const isExpanded = this.expandedProviders.has(p.name);
149
245
  rows.push({
@@ -153,14 +249,7 @@ export class UsageModalComponent implements Component {
153
249
  // provider does not end up with two arrows on one line. Capitalized to match the
154
250
  // detail line and the model rows beneath it.
155
251
  label: capitalize(p.name),
156
- sessions: p.sessions,
157
- msgs: p.msgs,
158
- tokens: p.totalTokens,
159
- input: p.input,
160
- output: p.output,
161
- cacheRead: p.cacheRead,
162
- cost: p.cost,
163
- estimatedCost: p.estimatedCost,
252
+ ...statsOf(p),
164
253
  expanded: isExpanded,
165
254
  });
166
255
 
@@ -171,14 +260,7 @@ export class UsageModalComponent implements Component {
171
260
  providerName: p.name,
172
261
  modelName: m.name,
173
262
  label: m.name,
174
- sessions: m.sessions,
175
- msgs: m.msgs,
176
- tokens: m.totalTokens,
177
- input: m.input,
178
- output: m.output,
179
- cacheRead: m.cacheRead,
180
- cost: m.cost,
181
- estimatedCost: m.estimatedCost,
263
+ ...statsOf(m),
182
264
  });
183
265
  }
184
266
  }
@@ -186,24 +268,36 @@ export class UsageModalComponent implements Component {
186
268
  return rows;
187
269
  }
188
270
 
189
- private toggleProvider(row: RowItem | undefined): boolean {
190
- if (!row || row.type !== "provider") return false;
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;
191
279
  if (this.expandedProviders.has(row.providerName)) this.expandedProviders.delete(row.providerName);
192
280
  else this.expandedProviders.add(row.providerName);
193
281
  return true;
194
282
  }
195
283
 
196
- /** Do the step the user just confirmed, then re-read whatever is left on disk. */
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. */
197
293
  private runConfirm(step: "reset" | "undo"): void {
198
294
  if (step === "reset") {
199
- const kept = this.activeFile ? [this.activeFile] : [];
200
- const result = resetUsageHistory(kept);
201
- this.trashDir = result.moved > 0 ? result.dir : null;
202
- this.notice = "Moved " + countOf(result.moved, "session") + " (" + formatBytes(result.bytes) + ") to " + shortTrash(result.dir);
203
- } else if (this.trashDir) {
204
- const result = restoreUsageHistory(this.trashDir);
205
- this.notice = "Restored " + countOf(result.restored, "session");
206
- this.trashDir = null;
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;
207
301
  }
208
302
  this.summary = collectUsageSummary(true, this.range);
209
303
  this.selectedIndex = 0;
@@ -254,7 +348,7 @@ export class UsageModalComponent implements Component {
254
348
  this.requestRender();
255
349
  return;
256
350
  }
257
- if (UNDO_USAGE.matches(keyData) && this.trashDir) {
351
+ if (UNDO_USAGE.matches(keyData) && this.undoBaseline) {
258
352
  this.confirmStep = "undo";
259
353
  this.requestRender();
260
354
  return;
@@ -282,7 +376,12 @@ export class UsageModalComponent implements Component {
282
376
  return;
283
377
  }
284
378
  if (matchesKey(keyData, "enter") || matchesKey(keyData, "space")) {
285
- if (this.toggleProvider(rows[this.selectedIndex])) this.requestRender();
379
+ if (this.toggleRow(rows[this.selectedIndex])) this.requestRender();
380
+ return;
381
+ }
382
+ if (matchesKey(keyData, "v")) {
383
+ this.cycleView();
384
+ this.requestRender();
286
385
  }
287
386
  }
288
387
 
@@ -306,7 +405,7 @@ export class UsageModalComponent implements Component {
306
405
  }
307
406
  if (event.type === "click") {
308
407
  this.selectedIndex = hit.index;
309
- this.toggleProvider(this.buildFlatRows()[hit.index]);
408
+ this.toggleRow(this.buildFlatRows()[hit.index]);
310
409
  return { handled: true, render: true };
311
410
  }
312
411
  // Press: claim the row so the terminal tracks it for the follow-up click.
@@ -324,8 +423,11 @@ export class UsageModalComponent implements Component {
324
423
  // label tier (the border-accent hue) and falls back to the accent tier.
325
424
  const soft = softSecondaryOf(th);
326
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);
327
430
  const dim = (s: string) => th.fg("dim", s);
328
- const plain = (s: string) => th.fg("text", s);
329
431
 
330
432
  const rows = this.buildFlatRows();
331
433
  if (this.selectedIndex >= rows.length) {
@@ -337,7 +439,7 @@ export class UsageModalComponent implements Component {
337
439
  // shorter and the numeric columns still start on the header's grid.
338
440
  const gutter = 2;
339
441
  const contentW = boxW - 4;
340
- const colW = { name: 30, session: 9, messages: 10, tokens: 9, cost: 10 };
442
+ const colW = { name: 30, session: 10, messages: 11, tokens: 10, cost: 11 };
341
443
  const allNumeric = colW.session + colW.messages + colW.tokens + colW.cost;
342
444
  // A very narrow terminal drops Session/Messages rather than truncating Tokens or Cost.
343
445
  const narrow = contentW - allNumeric < 18;
@@ -355,13 +457,18 @@ export class UsageModalComponent implements Component {
355
457
  const messagesW = narrow ? 0 : colW.messages;
356
458
  // No leading gutter: the header is content, so it starts on the same left edge as the
357
459
  // box title, the detail line and the Total row. The rows' numeric columns are measured
358
- // to land on this grid despite their arrow.
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"];
359
466
  const headerText =
360
- formatCol(th.fg("dim", "Provider / Model"), colW.name, false) +
361
- formatCol(th.fg("dim", "Session"), sessionW) +
362
- formatCol(th.fg("dim", "Messages"), messagesW) +
363
- formatCol(th.fg("dim", "Tokens"), colW.tokens) +
364
- formatCol(th.fg("dim", "Cost"), colW.cost);
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);
365
472
 
366
473
  // Body rows only — the frame comes from `renderScreen`, so this dashboard and the
367
474
  // /arnative menus cannot drift. No inner `├─┤` rule (skill arnative-pi rule 7).
@@ -413,22 +520,45 @@ export class UsageModalComponent implements Component {
413
520
  const actualIdx = startIdx + i;
414
521
  const isSelected = actualIdx === this.selectedIndex;
415
522
 
416
- const paintName = isSelected ? acc : item.type === "provider" ? soft : plain;
417
- const paintVal = isSelected ? acc : dim;
418
-
419
- const cName = formatCol(paintName(isSelected ? bold(item.label) : item.label), rowNameW, false);
420
- const cSess = formatCol(paintVal(formatCount(item.sessions)), sessionW);
421
- const cMsgs = formatCol(paintVal(formatCount(item.msgs)), messagesW);
422
- const cToks = formatCol(paintVal(formatTokens(item.tokens)), colW.tokens);
423
- // A row with no reported cost but a rate shows `~$x` in place of `-`, so the guess is
523
+ // Provider and project group rows sit on the plain text color, and the rows beneath
524
+ // them are dim. The cursor paints any row the soft accent, and the expand arrow alone
525
+ // carries the accent so the eye can find the tree.
526
+ const plain = (s: string) => th.fg("text", s);
527
+ const resting = item.type === "model" || item.type === "price" ? dim : plain;
528
+ const paintName = isSelected ? accSoft : resting;
529
+ const paintVal = isSelected ? accSoft : resting;
530
+ const isPrice = item.type === "price";
531
+ // A Prices group row names the provider; its rate columns stay blank, so the tree
532
+ // reads as a heading instead of a provider with $0.00 rates.
533
+ const isPriceGroup = this.view === "prices" && item.type === "provider";
534
+ const blank = (w: number) => " ".repeat(w);
535
+
536
+ // One indent for the rows under a group (model, price, or the provider under a
537
+ // project): it eats name width so the figures keep their columns.
538
+ const groupType: RowItem["type"] = this.view === "project" ? "project" : "provider";
539
+ const indent = item.type === groupType ? "" : " ";
540
+ const cName = formatCol(paintName(isSelected ? bold(item.label) : item.label), Math.max(10, rowNameW - indent.length), false);
541
+ const cSess = isPriceGroup ? blank(sessionW) : formatCol(paintVal(isPrice ? formatCost(item.rates?.in ?? 0) : formatCount(item.sessions)), sessionW);
542
+ const cMsgs = isPriceGroup ? blank(messagesW) : formatCol(paintVal(isPrice ? formatCost(item.rates?.out ?? 0) : formatCount(item.msgs)), messagesW);
543
+ const cToks = isPriceGroup ? blank(colW.tokens) : formatCol(paintVal(isPrice ? formatCost(item.rates?.cacheRead ?? 0) : formatTokens(item.tokens)), colW.tokens);
544
+ // A row with no billed cost but a rate shows `~$x` in place of `-`, so the guess is
424
545
  // visible exactly where it is one; the report line still keeps it out of the headline.
425
- const costCell = item.cost > 0 ? formatCost(item.cost) : item.estimatedCost > 0 ? `~${formatCost(item.estimatedCost)}` : "-";
426
- const cCost = formatCol(paintVal(costCell), colW.cost);
427
-
428
- // Gutter: expand arrow for provider or blank indent for model.
429
- const gutterText =
430
- item.type === "provider" ? (item.expanded ? soft("▾") : dim("▸")) : " ";
431
- const line = gutterText + " " + cName + cSess + cMsgs + cToks + cCost;
546
+ // The Prices view puts the cache-write rate here, or `unpriced` for a used model the
547
+ // table does not price.
548
+ const costCell = isPrice
549
+ ? item.unpriced
550
+ ? "unpriced"
551
+ : formatCost(item.rates?.cacheWrite ?? 0)
552
+ : item.cost > 0
553
+ ? formatCost(item.cost)
554
+ : item.estimatedCost > 0
555
+ ? `~${formatCost(item.estimatedCost)}`
556
+ : "-";
557
+ const cCost = isPriceGroup ? blank(colW.cost) : formatCol(paintVal(costCell), colW.cost);
558
+
559
+ // Gutter: the expand arrow carries the accent, blank indent for the rows beneath it.
560
+ const gutterText = item.type === groupType ? acc(item.expanded ? "▾" : "▸") : " ";
561
+ const line = indent + gutterText + " " + cName + cSess + cMsgs + cToks + cCost;
432
562
  this.rowHitboxes.push({ line: CHROME_ROWS + body.length, index: actualIdx });
433
563
  body.push(line);
434
564
  }
@@ -440,31 +570,47 @@ export class UsageModalComponent implements Component {
440
570
  body.push(this.selectedDetail(rows[this.selectedIndex], acc, soft));
441
571
  if (this.notice) body.push(th.fg("muted", this.notice));
442
572
 
443
- // Table-width separator above Total band (skill arnative-pi §6 rule 7).
573
+ // Table-width separator above the Total band (skill arnative-pi §6 rule 7).
444
574
  const tableW = colW.name + sessionW + messagesW + colW.tokens + colW.cost;
445
575
  body.push(th.fg("borderMuted", "─".repeat(Math.max(0, tableW))));
446
576
 
447
- // Total row
448
- const t = this.summary.totals;
449
- const totalName = formatCol(soft(bold("Total")), colW.name, false);
450
- const totalSess = formatCol(soft(bold(formatCount(t.sessions))), sessionW);
451
- const totalMsgs = formatCol(soft(bold(formatCount(t.msgs))), messagesW);
452
- const totalToks = formatCol(soft(bold(formatTokens(t.totalTokens))), colW.tokens);
453
- const totalCost = formatCol(soft(bold(formatCost(t.cost))), colW.cost);
454
-
455
- // Same left edge as the header: one table, three bands, one column grid.
456
- body.push(totalName + totalSess + totalMsgs + totalToks + totalCost);
457
-
458
- // Unreported cost estimate displayed separately from verified cost total.
459
- const est = t.estimatedCost;
460
- if (est > 0) body.push(th.fg("muted", `~${formatCost(est)} estimated (models.json)`));
577
+ if (this.view === "prices") {
578
+ // No Total band for rates: a count of what the table prices, and of the used models
579
+ // it does not, is the honest summary of this view.
580
+ const unpriced = rows.filter((r) => r.unpriced).length;
581
+ const priced = rows.filter((r) => r.type === "price" && !r.unpriced).length;
582
+ body.push(dim(`${priced} priced · ${unpriced} unpriced (models.json)`));
583
+ } else {
584
+ // Total row. Its cost column is the billed total only.
585
+ const t = this.summary.totals;
586
+ const totalName = formatCol(soft(bold("Total")), colW.name, false);
587
+ const totalSess = formatCol(soft(bold(formatCount(t.sessions))), sessionW);
588
+ const totalMsgs = formatCol(soft(bold(formatCount(t.msgs))), messagesW);
589
+ const totalToks = formatCol(soft(bold(formatTokens(t.totalTokens))), colW.tokens);
590
+ // Billed when a provider reported one; otherwise the catalog estimate, marked `~` so
591
+ // the Total row never claims a billed number it does not have.
592
+ const totalValue = t.cost > 0 ? formatCost(t.cost) : t.estimatedCost > 0 ? `~${formatCost(t.estimatedCost)}` : "-";
593
+ const totalCost = formatCol(soft(bold(totalValue)), colW.cost);
594
+
595
+ // Same left edge as the header: one table, three bands, one column grid.
596
+ body.push(totalName + totalSess + totalMsgs + totalToks + totalCost);
597
+ }
461
598
 
599
+ const viewName = VIEW_LABELS[this.view];
462
600
  return renderScreen(
463
601
  th,
464
602
  width,
465
603
  {
466
604
  title: screenTitle("Usage"),
467
- description: width >= 70 ? "Token, message & cache usage across all local Pi sessions." : "Usage across all local sessions.",
605
+ description: `${viewName} · ${
606
+ this.view === "prices"
607
+ ? width >= 70
608
+ ? "Rates per 1M tokens from models.json; `unpriced` marks a used model with no rate."
609
+ : "Rates per 1M tokens (models.json)."
610
+ : width >= 70
611
+ ? "Token, message & cache usage across all local Pi sessions."
612
+ : "Usage across all local sessions."
613
+ }`,
468
614
  legend: this.footer(width, th),
469
615
  },
470
616
  body,
@@ -475,20 +621,18 @@ export class UsageModalComponent implements Component {
475
621
  /** The last row of the box: a pending question, or the keys that are live right now. */
476
622
  private footer(width: number, th: { fg(c: string, t: string): string }): string {
477
623
  if (this.confirmStep === "reset") {
478
- const size = usageHistorySize(this.activeFile ? [this.activeFile] : []);
479
- const what = countOf(size.files, "session") + " (" + formatBytes(size.bytes) + ")";
480
- return th.fg("accent", "Delete " + what + "?") + " " + th.fg("muted", "moves to the trash") + " " + th.fg("text", "[y] Yes [Esc] Cancel");
624
+ return th.fg("accent", "Reset all usage statistics?") + " " + th.fg("muted", "sessions stay") + " " + th.fg("text", "[y] Yes [Esc] Cancel");
481
625
  }
482
626
  if (this.confirmStep === "undo") {
483
627
  return (
484
- th.fg("accent", "Put the history back?") +
628
+ th.fg("accent", "Undo the statistics reset?") +
485
629
  " " +
486
- th.fg("muted", "the trash folder stays") +
630
+ th.fg("muted", "sessions stay") +
487
631
  " " +
488
632
  th.fg("text", "[y] Yes [Esc] Cancel")
489
633
  );
490
634
  }
491
- return legendUsage(width, { reset: true, undo: this.trashDir !== null });
635
+ return legendUsage(width, { reset: true, undo: this.undoBaseline !== null, next: VIEW_LABELS[NEXT_VIEW[this.view]] });
492
636
  }
493
637
 
494
638
  /** Detail for the selected row: icon in `accent`, text and `·` dividers in `accentSoft`. */
@@ -499,13 +643,28 @@ export class UsageModalComponent implements Component {
499
643
  ): string {
500
644
  if (!row) return soft("No usage recorded yet.");
501
645
  const icon = `${accent("\uf4bc")} `;
502
- const title = row.type === "provider" ? row.providerName : `${row.providerName} · ${row.modelName}`;
646
+ if (row.type === "price") {
647
+ const title = `${row.providerName} · ${row.modelName}`;
648
+ const parts = row.unpriced
649
+ ? ["unpriced", `↑${formatTokens(row.input)}`, `↓${formatTokens(row.output)}`]
650
+ : [
651
+ `in ${formatCost(row.rates!.in)}`,
652
+ `out ${formatCost(row.rates!.out)}`,
653
+ `cache read ${formatCost(row.rates!.cacheRead)}`,
654
+ `cache write ${formatCost(row.rates!.cacheWrite)}`,
655
+ ];
656
+ if (row.unpriced && row.estimatedCost > 0) parts.push(`${formatCost(row.estimatedCost)} est.`);
657
+ const divider = soft(" · ");
658
+ return `${icon}${soft(capitalize(title))}${divider}${soft(parts.join(" · "))}`;
659
+ }
660
+ const title =
661
+ row.type === "model" ? `${row.providerName} · ${row.modelName}` : row.type === "project" ? row.projectName! : row.providerName;
503
662
  const parts = [
504
663
  `↑${formatTokens(row.input)}`,
505
664
  `↓${formatTokens(row.output)}`,
506
665
  `cache ${formatTokens(row.cacheRead)}`,
507
666
  ];
508
- if (row.estimatedCost > 0) parts.push(`~${formatCost(row.estimatedCost)} est.`);
667
+ if (row.estimatedCost > 0) parts.push(`${formatCost(row.estimatedCost)} est.`);
509
668
  const divider = soft(" · ");
510
669
  return `${icon}${soft(capitalize(title))}${divider}${soft(parts.join(" · "))}`;
511
670
  }
@@ -522,7 +681,6 @@ export async function openUsage(ctx: ExtensionCommandContext): Promise<boolean>
522
681
  (wantsBack) => done(wantsBack),
523
682
  () => tui.requestRender(),
524
683
  thinkingLevel,
525
- ctx.sessionManager.getSessionFile() ?? undefined,
526
684
  );
527
685
  });
528
686
  return back === true;
@@ -560,7 +718,8 @@ if (isMain(import.meta.url)) {
560
718
  const fixture = mkdtempSync(join(tmpdir(), "arnative-usage-"));
561
719
  process.env.PI_CODING_AGENT_DIR = fixture;
562
720
  mkdirSync(join(fixture, "sessions", "proj"), { recursive: true });
563
- const asst = (model: string, input: number) => JSON.stringify({ message: { role: "assistant", provider: "google", model, usage: { input, output: 5, cacheRead: 1, cost: { total: 0.02 } } } });
721
+ const asst = (model: string, input: number) =>
722
+ JSON.stringify({ message: { role: "assistant", provider: "google", model, usage: { input, output: 5, cacheRead: 1, cacheWrite: 2, cost: { total: 0.02, totalFromProvider: true } } } });
564
723
  writeFileSync(
565
724
  join(fixture, "sessions", "proj", "a.jsonl"),
566
725
  [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),
@@ -659,9 +818,9 @@ if (isMain(import.meta.url)) {
659
818
  "utf8",
660
819
  );
661
820
  resetUsageCache();
662
- assert(collectUsageSummary(true).totals.msgs === 3, "a migrated v4 entry feeds the summary as-is (no reparse of an unchanged file)");
821
+ assert(collectUsageSummary(true).totals.msgs === 1, "a migrated v4 entry is re-parsed once (it predates the day buckets and the billed split)");
663
822
  writeFileSync(migFile, asst("gemini-3.8-flash", 7) + String.fromCharCode(10), { flag: "a" });
664
- assert(collectUsageSummary(true).totals.msgs === 4, "a grown file tail-folds on top of a migrated v4 entry");
823
+ 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");
665
824
  assert(existsSync(join(mig, "arnative", "usage-cache.json")), "the cache is saved into the arnative folder");
666
825
  const migrated = JSON.parse(readFileSync(join(mig, "arnative", "usage-cache.json"), "utf8")) as Record<string, { r: Record<string, number[]> }>;
667
826
  const migKey = join("p", "a.jsonl");
@@ -689,7 +848,7 @@ if (isMain(import.meta.url)) {
689
848
  // exists for; `asst` above reports 0.02 per message and would be priced by the provider.
690
849
  mkdirSync(join(fixture, "sessions", "ui"), { recursive: true });
691
850
  const freeAsstOf = (provider: string, model: string, input: number) =>
692
- JSON.stringify({ message: { role: "assistant", provider, model, usage: { input, output: 5, cacheRead: 1, cost: { total: 0 } } } });
851
+ JSON.stringify({ message: { role: "assistant", provider, model, usage: { input, output: 5, cacheRead: 1, cacheWrite: 3, cost: { total: 0 } } } });
693
852
  const freeAsst = (model: string, input: number) => freeAsstOf("alpha", model, input);
694
853
  writeFileSync(
695
854
  join(fixture, "sessions", "ui", "rows.jsonl"),
@@ -714,9 +873,9 @@ if (isMain(import.meta.url)) {
714
873
  // Cost estimation: unpriced pairs use rates declared automatically in models.json.
715
874
  assert(loadPriceTable() !== null && Object.keys(loadPriceTable()).length === 0, "no models.json rates means an empty table");
716
875
  assert(!hasPrice("alpha", "gemini-3.8-flash"), "a pair absent from models.json has no price");
717
- assert(estimateCost(1000, 100, 0, "gemini-3.8-flash", "alpha") === null, "an unknown pair estimates nothing");
876
+ assert(estimateCost(1000, 100, 0, 0, "gemini-3.8-flash", "alpha") === null, "an unknown pair estimates nothing");
718
877
  assert(collectUsageSummary(true).totals.estimatedCost === 0, "nothing is estimated without rates");
719
- assert(estimateCost(1000, 100, 0, "other-model", "alpha") === null, "a second unpriced pair estimates nothing either");
878
+ assert(estimateCost(1000, 100, 0, 0, "other-model", "alpha") === null, "a second unpriced pair estimates nothing either");
720
879
 
721
880
  writeFileSync(
722
881
  join(fixture, "models.json"),
@@ -727,21 +886,34 @@ if (isMain(import.meta.url)) {
727
886
  },
728
887
  }),
729
888
  );
889
+ const table0 = loadPriceTable();
730
890
  assert(hasPrice("alpha", "gemini-3.8-flash"), "a priced provider+model is found in the table");
731
891
  assert(!hasPrice("enclave", "gemini-3.8-flash"), "another provider with no entry is not priced");
732
- assert(estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "alpha") === 1, "1M input tokens at alpha's $1/M costs $1");
892
+ assert(estimateCost(1_000_000, 0, 0, 0, "gemini-3.8-flash", "alpha") === 1, "1M input tokens at alpha's $1/M costs $1");
733
893
  assert(
734
- estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "beta") === 10,
894
+ estimateCost(1_000_000, 0, 0, 0, "gemini-3.8-flash", "beta") === 10,
735
895
  "the SAME model at beta costs 10x (rates are per provider, not per model)",
736
896
  );
737
- assert(estimateCost(0, 1_000_000, 0, "gemini-3.8-flash", "alpha") === 2, "1M output tokens at $2/M costs $2");
738
- assert(Math.abs(estimateCost(0, 0, 1_000_000, "gemini-3.8-flash", "alpha")! - 0.1) < 1e-9, "cache reads use their own rate");
739
- assert(estimateCost(1_000_000, 0, 0, "vendor/gemini-3.8-flash", "alpha") === 1, "a vendor/my-model id matches the model rate");
897
+ assert(estimateCost(0, 1_000_000, 0, 0, "gemini-3.8-flash", "alpha") === 2, "1M output tokens at $2/M costs $2");
898
+ 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");
899
+ assert(estimateCost(1_000_000, 0, 0, 0, "vendor/gemini-3.8-flash", "alpha") === 1, "a vendor/my-model id matches the model rate");
740
900
  const withPrices = collectUsageSummary(true);
741
901
  assert(withPrices.totals.estimatedCost > 0, "models.json rates produce an estimate");
742
902
  assert(withPrices.totals.reportedCost === 0, "the reported total stays at the provider's own number");
743
903
  assert(withPrices.totals.cost === withPrices.totals.reportedCost, "the headline cost never absorbs the estimate");
744
- assert(estimateCost(1_000_000, 0, 0, "other-model", "alpha") === null, "a pair with no rate stays unpriced even when others are priced");
904
+ assert(estimateCost(1_000_000, 0, 0, 0, "other-model", "alpha") === null, "a pair with no rate stays unpriced even when others are priced");
905
+ assert(loadPriceTable() === loadPriceTable(), "an unchanged models.json is read once (memo identity)");
906
+ await new Promise((r) => setTimeout(r, 5)); // mtime granularity: a rewrite must change the memo key
907
+ writeFileSync(
908
+ join(fixture, "models.json"),
909
+ JSON.stringify({
910
+ providers: {
911
+ alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 0.5 } }] },
912
+ beta: { models: [{ id: "gemini-3.8-flash", cost: { input: 10, output: 20 } }] },
913
+ },
914
+ }),
915
+ );
916
+ 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");
745
917
 
746
918
  const fakeTheme = {
747
919
  fg: (_c: string, t: string) => `\x1b[38;2;100;100;100m${t}\x1b[39m`,
@@ -770,6 +942,24 @@ if (isMain(import.meta.url)) {
770
942
  // Compact layout: the four noisy columns (↑In/↓Out/Cache) are gone from the table; the
771
943
  // selected row states them in the detail line instead.
772
944
  const plain = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, "");
945
+ // Prices view (`v` cycles Provider → Project → Prices): every models.json pair with its
946
+ // $/1M rates on the same column grid, sorted by input rate, and a used model the table does
947
+ // not price marked `unpriced` — that is the model whose Cost cell reads `-`.
948
+ const priceModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "high");
949
+ priceModal.handleInput("v");
950
+ priceModal.handleInput("v");
951
+ // Group rows are collapsed by default; the check opens both providers to read their children.
952
+ (priceModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["alpha", "beta"]);
953
+ const priceLines = priceModal.render(120);
954
+ const priceBody = priceLines.map(plain).join("\n");
955
+ assert(priceBody.includes("In $/M") && priceBody.includes("Write $/M"), "the Prices view header names the rate columns");
956
+ assert(priceBody.includes("Alpha") && priceBody.includes("gemini-3.8-flash"), "the Prices view nests models under their provider");
957
+ assert(priceBody.includes("$1.00"), "input rates render as $/1M");
958
+ assert(priceBody.includes("unpriced") && priceBody.includes("other-model"), "a used model absent from models.json is marked unpriced");
959
+ assert(priceBody.includes("2 priced · 2 unpriced (models.json)"), "the Prices view counts priced and unpriced rows");
960
+ priceModal.handleInput("v");
961
+ assert(priceModal.render(120).some((l) => plain(l).includes("Provider / Model")), "`v` cycles back to the Provider view");
962
+
773
963
  const body = lines.map(plain).join("\n");
774
964
  assert(body.includes("Tokens"), "compact table keeps the Tokens column");
775
965
  assert(body.includes("Cost"), "compact table keeps the Cost column");
@@ -867,11 +1057,39 @@ if (isMain(import.meta.url)) {
867
1057
  assert(detailTagged.includes("<accentSoft> · </>"), "the detail divider is accentSoft");
868
1058
  const offLines = new UsageModalComponent(taggedTheme, () => {}, () => {}, "off").render(260);
869
1059
  assert(offLines[0]!.includes("<thinkingOff>"), "thinking off colors the border with thinkingOff");
1060
+ // Pi 1.2+ rejects `accentSoft`/`secondarySoft` in `fg`; the rows and detail must still paint
1061
+ // (softOf derives the tint from `colors.accent`), or the dashboard crashes on render.
1062
+ const strictTheme = {
1063
+ fg: (c: string, t: string) => {
1064
+ if (c === "accentSoft" || c === "secondarySoft") throw new Error(`Unknown theme color: ${c}`);
1065
+ return t;
1066
+ },
1067
+ style: (t: string) => t,
1068
+ colors: { accent: { kind: "oklch", l: 0.7, c: 0.1, h: 200 } },
1069
+ } as never;
1070
+ assert(
1071
+ new UsageModalComponent(strictTheme, () => {}, () => {}, "off").render(120).length > 0,
1072
+ "a theme without the soft tokens still renders the rows",
1073
+ );
1074
+ // Project view: the project group row sits on plain text like a provider group row, and the
1075
+ // expand arrow carries the accent.
1076
+ const taggedProject = new UsageModalComponent(taggedTheme, () => {}, () => {}, "off");
1077
+ taggedProject.handleInput("v");
1078
+ const projectLines = taggedProject.render(260);
1079
+ assert(projectLines.some((l) => /<accent>[▸▾]/.test(l)), "the expand arrow carries the accent");
1080
+ assert(
1081
+ projectLines.some((l) => /│<\/>\s{3,5}<text>/.test(l)),
1082
+ "a provider row under a project sits on plain text, indented like a model row",
1083
+ );
1084
+ taggedProject.handleInput("j");
1085
+ const selectedLines = taggedProject.render(260);
1086
+ assert(selectedLines.some((l) => l.includes("<text>unknown")), "the project label sits on plain text");
1087
+ assert(selectedLines.some((l) => /<accentSoft>\w/.test(l)), "the selected provider row takes the soft accent");
870
1088
  // Shared chrome (per `renderScreen`): title accent+bold, description muted, legend dim.
871
1089
  // `taggedTheme.bold` is identity, so only the accent wrapper shows here; the bold half is
872
1090
  // pinned in lib/box.ts.
873
1091
  assert(highLines[1]!.includes("<accent>Usage - Arnative"), "the dashboard title is accent-colored");
874
- assert(highLines[2]!.includes("<muted>Token, message"), "the dashboard description is muted");
1092
+ assert(highLines[2]!.includes("<muted>Provider · Token, message"), "the dashboard description names the view and is muted");
875
1093
  assert(highLines[highLines.length - 2]!.includes("<dim>["), "the dashboard legend is dim");
876
1094
  assert(!highLines.some((l) => /[├┤]/.test(l)), "the dashboard draws no inner rule");
877
1095
 
@@ -965,14 +1183,14 @@ if (isMain(import.meta.url)) {
965
1183
  join(fixture, "models.json"),
966
1184
  JSON.stringify({
967
1185
  providers: {
968
- alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 0.28, output: 0.42, cacheRead: 0.028 } }] },
1186
+ alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 0.28, output: 0.42, cacheRead: 0.028, cacheWrite: 0.3 } }] },
969
1187
  beta: { models: [{ id: "gemini-3.8-flash" }] },
970
1188
  },
971
1189
  }),
972
1190
  );
973
1191
  const fromModels = collectUsageSummary(true);
974
1192
  const alpha = fromModels.providers.find((p) => p.name === "alpha")!;
975
- const expected = (100 / 1e6) * 0.28 + (5 / 1e6) * 0.42 + (1 / 1e6) * 0.028;
1193
+ const expected = (100 / 1e6) * 0.28 + (5 / 1e6) * 0.42 + (1 / 1e6) * 0.028 + (3 / 1e6) * 0.3;
976
1194
  assert(Math.abs(alpha.estimatedCost - expected) < 1e-12, `models.json cost prices the provider, got ${alpha.estimatedCost}`);
977
1195
  assert(
978
1196
  Math.abs(alpha.models.reduce((n, m) => n + m.estimatedCost, 0) - alpha.estimatedCost) < 1e-9,
@@ -1000,15 +1218,16 @@ if (isMain(import.meta.url)) {
1000
1218
  },
1001
1219
  ],
1002
1220
  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 },
1221
+ projects: [],
1003
1222
  };
1004
1223
  (estModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["alpha"]);
1005
1224
  const estLines = estModal.render(90);
1006
1225
  const estBody = estLines.map(plain).join("\n");
1007
1226
  assert(estBody.includes("~$0.55"), "a row with a rate but no reported cost shows the estimate with `~`");
1008
1227
  assert(estBody.includes("$0.65") && !estBody.includes("~$0.65"), "a reported cost is shown as-is, never with `~`");
1009
- assert(estBody.includes("estimated (models.json)"), "the estimate line names models.json");
1228
+ assert(!estBody.includes("estimated (models.json)"), "the separate estimate line is gone; the Total row carries the number");
1010
1229
  // Only the two table rows — the detail line also carries the estimate.
1011
- const estRows = estLines.map(plain).filter((l) => /^\u2502 [\u25be\u25b8 ] (Alpha|deepseek)/.test(l));
1230
+ const estRows = estLines.map(plain).filter((l) => /^\u2502\s+(?:[\u25be\u25b8]\s+)?(Alpha|deepseek)/.test(l));
1012
1231
  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)}`);
1013
1232
 
1014
1233
  // Cost must survive every width: a clipped `$5` is worse than a dropped column.
@@ -1021,6 +1240,65 @@ if (isMain(import.meta.url)) {
1021
1240
  );
1022
1241
  }
1023
1242
 
1243
+ // The two sub-lines under the Total band are gone: the table and the Total row carry the
1244
+ // numbers, and a smaller window is not worth a second line under every view.
1245
+ assert(!estBody.includes("today $"), "no day-bucket line under the Total band");
1246
+ assert(
1247
+ new UsageModalComponent(fakeTheme, () => {}, () => {}, "high").render(120).some((l) => plain(l).includes("[v] Next: Project")),
1248
+ "the rendered legend names the next view",
1249
+ );
1250
+
1251
+ // View cycle (`v`): Provider → Project → Provider. The Project view keeps the one column
1252
+ // grid, its project rows sum to the Total row, and the day line sits under the Total band.
1253
+ const viewModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "high");
1254
+ const win = { cost: 0.07, input: 1300, output: 35, cacheRead: 6 };
1255
+ (viewModal as unknown as { summary: unknown }).summary = {
1256
+ providers: [
1257
+ {
1258
+ name: "alpha", sessions: 2, msgs: 3, input: 1200, output: 30, cacheRead: 5, totalTokens: 1230, cost: 0.05, estimatedCost: 0,
1259
+ models: [{ name: "m1", sessions: 2, msgs: 3, input: 1200, output: 30, cacheRead: 5, totalTokens: 1230, cost: 0.05, estimatedCost: 0 }],
1260
+ },
1261
+ {
1262
+ name: "beta", sessions: 1, msgs: 1, input: 100, output: 5, cacheRead: 1, totalTokens: 105, cost: 0.02, estimatedCost: 0,
1263
+ models: [{ name: "m2", sessions: 1, msgs: 1, input: 100, output: 5, cacheRead: 1, totalTokens: 105, cost: 0.02, estimatedCost: 0 }],
1264
+ },
1265
+ ],
1266
+ projects: [
1267
+ {
1268
+ name: "/repo/alpha", sessions: 2, msgs: 3, input: 1200, output: 30, cacheRead: 5, totalTokens: 1230, cost: 0.05, estimatedCost: 0,
1269
+ providers: [{ name: "alpha", sessions: 2, msgs: 3, input: 1200, output: 30, cacheRead: 5, totalTokens: 1230, cost: 0.05, estimatedCost: 0, models: [] }],
1270
+ },
1271
+ {
1272
+ name: "unknown", sessions: 1, msgs: 1, input: 100, output: 5, cacheRead: 1, totalTokens: 105, cost: 0.02, estimatedCost: 0,
1273
+ providers: [{ name: "beta", sessions: 1, msgs: 1, input: 100, output: 5, cacheRead: 1, totalTokens: 105, cost: 0.02, estimatedCost: 0, models: [] }],
1274
+ },
1275
+ ],
1276
+ 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 },
1277
+ };
1278
+ (viewModal as unknown as { expandedProjects: Set<string> }).expandedProjects = new Set(["/repo/alpha"]);
1279
+ const provHeader = plain(viewModal.render(100).find((l) => l.includes("Provider / Model"))!);
1280
+ viewModal.handleInput("v");
1281
+ const projLines = viewModal.render(100);
1282
+ const projBody = projLines.map(plain).join("\n");
1283
+ const projHeader = plain(projLines.find((l) => l.includes("Project / Provider"))!);
1284
+ assert(projBody.includes("Project / Provider"), "`v` switches the header to the Project view");
1285
+ for (const col of ["Session", "Messages", "Tokens", "Cost"]) {
1286
+ assert(provHeader.indexOf(col) === projHeader.indexOf(col), `the Project view keeps the ${col} column on the same cell`);
1287
+ }
1288
+ // The last right-aligned cell of a row is its Cost column.
1289
+ const costCell = (l: string) => plain(l).replace(/\u2502$/, "").trimEnd().slice(-10).trim();
1290
+ const num = (cell: string) => (cell.startsWith("$") ? parseFloat(cell.slice(1)) : 0);
1291
+ const projRows = projLines.filter((l) => /^\u2502 [\u25be\u25b8]/.test(plain(l)));
1292
+ const totalCell = costCell(projLines.find((l) => plain(l).includes("Total"))!);
1293
+ assert(projRows.length === 2, "the Project view renders one row per project");
1294
+ assert(
1295
+ Math.abs(projRows.reduce((n, l) => n + num(costCell(l)), 0) - num(totalCell)) < 1e-9,
1296
+ `the project rows sum to the Total row, got ${projRows.map(costCell)} vs ${totalCell}`,
1297
+ );
1298
+ assert(!projBody.includes("today $") && !projBody.includes("estimated (models.json)"), "no summary sub-lines under the Total band");
1299
+ viewModal.handleInput("v");
1300
+ assert(viewModal.render(100).some((l) => plain(l).includes("Provider / Model")), "`v` cycles back to the Provider view");
1301
+
1024
1302
  // Ranges: three dated files — today, 10 days back, 45 days back — so each window has a
1025
1303
  // number only it can produce.
1026
1304
  const dayMs = 86_400_000;
@@ -1094,33 +1372,32 @@ if (isMain(import.meta.url)) {
1094
1372
  assert(!scrolled.some((l) => l.includes("↓ ")), "the bottom of the list announces only what is above");
1095
1373
 
1096
1374
 
1097
- // --- Reset: history moves to the trash, never into oblivion ----------------
1098
- assert(formatBytes(0) === "0 B" && formatBytes(1536) === "2 kB" && formatBytes(281 * 1024 * 1024) === "281 MB", "formatBytes picks the readable unit");
1375
+ // --- Reset: statistics change, session files stay intact -------------------
1099
1376
  const resetDir = mkdtempSync(join(tmpdir(), "arnative-reset-"));
1100
1377
  process.env.PI_CODING_AGENT_DIR = resetDir;
1101
1378
  const resetSessions = join(resetDir, "sessions", "proj");
1102
1379
  mkdirSync(resetSessions, { recursive: true });
1103
- 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 } } } });
1380
+ 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);
1104
1381
  const livePath = join(resetSessions, "live.jsonl");
1105
- writeFileSync(livePath, resetLine + String.fromCharCode(10));
1106
- writeFileSync(join(resetSessions, "old.jsonl"), resetLine + String.fromCharCode(10));
1382
+ const oldPath = join(resetSessions, "old.jsonl");
1383
+ writeFileSync(livePath, resetLine);
1384
+ writeFileSync(oldPath, resetLine);
1107
1385
  resetUsageCache();
1108
- const resetModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "high", livePath);
1386
+ const resetModal = new UsageModalComponent(fakeTheme, () => undefined, () => undefined, "high");
1109
1387
  assert(resetModal.render(120).map(plain).some((l) => l.includes("[R] Reset")), "the footer advertises R Reset");
1110
1388
  resetModal.handleInput("R");
1111
- assert(resetModal.render(120).map(plain).some((l) => l.includes("Delete 1 session (151 B)?")), "R states the size and asks before anything is touched");
1112
- resetModal.handleInput("");
1113
- assert(existsSync(join(resetSessions, "old.jsonl")), "any other key cancels and no file moves");
1389
+ assert(resetModal.render(120).map(plain).some((l) => l.includes("Reset all usage statistics?") && l.includes("sessions stay")), "R confirms a statistics-only reset");
1390
+ resetModal.handleInput("\x1b");
1391
+ assert(collectUsageSummary(true).totals.msgs === 2, "cancel keeps the statistics");
1114
1392
  resetModal.handleInput("R");
1115
1393
  resetModal.handleInput("y");
1116
- assert(!existsSync(join(resetSessions, "old.jsonl")), "confirming moves the other sessions out");
1117
- assert(existsSync(livePath), "the session in use is never moved");
1118
- assert(resetModal.render(120).map(plain).some((l) => l.includes("Moved 1 session")), "the notice states what moved");
1119
- assert(collectUsageSummary(true).totals.msgs === 1, "only the live session is still counted");
1394
+ assert(readFileSync(oldPath, "utf8") === resetLine && readFileSync(livePath, "utf8") === resetLine, "reset leaves every session unchanged");
1395
+ assert(resetModal.render(120).map(plain).some((l) => l.includes("Usage statistics reset. Sessions kept.")), "the notice states what changed");
1396
+ assert(collectUsageSummary(true).totals.msgs === 0, "the reset excludes previous messages, including the active session");
1120
1397
  resetModal.handleInput("U");
1121
1398
  resetModal.handleInput("y");
1122
- assert(existsSync(join(resetSessions, "old.jsonl")), "U puts the history back");
1123
- assert(collectUsageSummary(true).totals.msgs === 2, "both sessions count again");
1124
- assert(resetModal.render(120).map(plain).some((l) => l.includes("Restored 1 session")), "the notice states what came back");
1399
+ assert(collectUsageSummary(true).totals.msgs === 2, "undo restores the previous counting baseline");
1400
+ assert(resetModal.render(120).map(plain).some((l) => l.includes("Previous statistics restored.")), "the notice states what came back");
1401
+ rmSync(resetDir, { recursive: true, force: true });
1125
1402
  console.log("usage.ts self-check OK");
1126
1403
  }