@bismawy/pi-arnative 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -429,10 +429,10 @@ if (isMain(import.meta.url)) {
429
429
  // Mirrors `soften()` (themes/gen-themes.mjs) and `softenColor` (lib/ansi.ts): the soft
430
430
  // tier is the base color at L 0.82 with a fifth of its chroma. Both sides read the
431
431
  // declared OKLCH string (not the 8-bit hex), so the comparison is not rounded twice.
432
- const softenToHex = (base: string) => {
432
+ const softenToHex = (base: string, scale = 0.35, l = 0.90) => {
433
433
  const o = parseOklch(base);
434
434
  assert(o !== null, `cannot soften a non-oklch color: ${base}`);
435
- return toHex(`oklch(82% ${oklchToRgb(0.82, o.C * 0.18, o.H).chroma} ${o.H})`);
435
+ return toHex(`oklch(${+(l * 100).toFixed(1)}% ${oklchToRgb(l, o.C * scale, o.H).chroma} ${o.H})`);
436
436
  };
437
437
  // The built-in theme adds fallbacks (scrollbarTrack<-muted, thinkingMax<-thinkingXhigh),
438
438
  // so the fg map must be complete; take the whole palette like pi's loader does.
@@ -477,10 +477,10 @@ if (isMain(import.meta.url)) {
477
477
  // Non-text keys (backgrounds/borders/scrollbar) — contrast is not measured.
478
478
  const nonText = new Set([
479
479
  "selectedBg", "userMessageBg", "customMessageBg", "toolPendingBg", "toolSuccessBg", "toolErrorBg",
480
- "searchMatchBg", "border", "borderAccent", "borderMuted", "mdCodeBlockBorder", "mdQuoteBorder",
480
+ "searchMatchBg", "border", "borderAccent", "borderMuted", "mdCodeBlockBorder", "mdQuoteBorder", "mdHr",
481
481
  "scrollbarTrack", "scrollbarThumb",
482
482
  ]);
483
- const secondary = new Set(["muted", "dim", "mdQuote", "mdHr", "mdLinkUrl", "toolOutput", "toolDiffContext", "thinkingText", "syntaxComment"]);
483
+ const secondary = new Set(["muted", "dim", "mdQuote", "mdLinkUrl", "toolOutput", "toolDiffContext", "thinkingText", "syntaxComment"]);
484
484
  // Thinking ramp: the higher the more readable; thinkingMax = accent (measured on the pill path).
485
485
  const ramp: Record<string, number> = {
486
486
  thinkingOff: 1.3, thinkingMinimal: 1.3, thinkingLow: 2.0,
@@ -552,7 +552,7 @@ if (isMain(import.meta.url)) {
552
552
  // The declared soft vars must equal what the extensions derive at runtime, or the
553
553
  // footer label colour drifts from the theme file. `softenToHex` mirrors
554
554
  // `soften()` in gen-themes.mjs and `softenColor` in lib/ansi.ts.
555
- for (const [softName, baseName] of [["accentSoft", "accent"], ["secondarySoft", "borderAccent"]] as const) {
555
+ for (const [softName, baseName] of [["accentSoft", "accent"], ["secondarySoft", "secondary"]] as const) {
556
556
  const base = d.vars[d.colors[baseName] ?? baseName]!;
557
557
  const declared = toHex(d.vars[softName]!);
558
558
  const derived = softenToHex(base);
@@ -12,8 +12,24 @@ 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
14
  import { thinkingColorOf, softSecondaryOf } from "../lib/ansi.ts";
15
- import { legendUsage, matchesBack } from "../lib/shortcuts.ts";
16
- import { collectUsageSummary, estimateCost, formatTokens, getModelAllTimeUsage, hasPrice, loadPriceTable, resetUsageCache, type UsageSummary } from "../lib/usage-store.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
+ dayKey,
24
+ rangeStart,
25
+ resetUsageCache,
26
+ resetUsageHistory,
27
+ restoreUsageHistory,
28
+ usageHistorySize,
29
+ USAGE_RANGES,
30
+ type UsageRange,
31
+ type UsageSummary,
32
+ } from "../lib/usage-store.ts";
17
33
 
18
34
  export function formatCost(n: number): string {
19
35
  if (!n || n <= 0) return "-";
@@ -26,6 +42,26 @@ export function formatCost(n: number): string {
26
42
  return `$${(n / 1000).toFixed(1)}k`;
27
43
  }
28
44
 
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
+
29
65
  export function formatCount(n: number): string {
30
66
  return n > 0 ? n.toLocaleString("en-US") : "-";
31
67
  }
@@ -50,10 +86,19 @@ export interface RowItem {
50
86
  expanded?: boolean;
51
87
  }
52
88
 
89
+ /** Labels on the range bar, in tab order. */
90
+ const RANGE_LABELS: Record<UsageRange, string> = { all: "All", today: "Today", "7d": "7 day", "30d": "30 day", "3m": "3 month" };
91
+ /** Data rows on screen at once: five reads as a table, sixteen pushed the Total row off. */
92
+ const USAGE_VIEWPORT = 5;
93
+
53
94
  export class UsageModalComponent implements Component {
54
95
  private expandedProviders = new Set<string>();
55
96
  private selectedIndex = 0;
56
97
  private summary: UsageSummary;
98
+ /** Which window the numbers cover. `all` keeps the old dashboard's meaning. */
99
+ private range: UsageRange = "all";
100
+ /** Tab hitboxes of the last render: column span of each range on the bar line. */
101
+ private tabHitboxes: { line: number; start: number; end: number; range: UsageRange }[] = [];
57
102
 
58
103
  private theme: { fg(c: string, t: string): string; bold?(t: string): string };
59
104
  private onDone: (back: boolean) => void;
@@ -63,6 +108,14 @@ export class UsageModalComponent implements Component {
63
108
  private edgeOf: (s: string) => string;
64
109
  /** Row layout of the last render: which table row sits on which screen line. */
65
110
  private rowHitboxes: { line: number; index: number }[] = [];
111
+ /** A destructive step waits here until the user answers it. Nothing is touched before. */
112
+ private confirmStep: "reset" | "undo" | null = null;
113
+ /** One line under the table, stating what the last reset moved. */
114
+ 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;
66
119
 
67
120
  constructor(
68
121
  theme: { fg(c: string, t: string): string; bold?(t: string): string },
@@ -70,12 +123,15 @@ export class UsageModalComponent implements Component {
70
123
  onDone: (back: boolean) => void,
71
124
  requestRender: () => void,
72
125
  thinkingLevel?: string,
126
+ /** The session file in use. Excluded from a reset: pi keeps appending to it. */
127
+ activeFile?: string,
73
128
  ) {
74
129
  this.theme = theme;
130
+ this.activeFile = activeFile;
75
131
  this.onDone = onDone;
76
132
  this.requestRender = requestRender;
77
133
  this.edgeOf = thinkingColorOf(theme, thinkingLevel);
78
- this.summary = collectUsageSummary(true);
134
+ this.summary = collectUsageSummary(true, this.range);
79
135
  // Default: expand the first provider when there is one
80
136
  if (this.summary.providers.length > 0) {
81
137
  this.expandedProviders.add(this.summary.providers[0]!.name);
@@ -137,16 +193,78 @@ export class UsageModalComponent implements Component {
137
193
  return true;
138
194
  }
139
195
 
196
+ /** Do the step the user just confirmed, then re-read whatever is left on disk. */
197
+ private runConfirm(step: "reset" | "undo"): void {
198
+ 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;
207
+ }
208
+ this.summary = collectUsageSummary(true, this.range);
209
+ this.selectedIndex = 0;
210
+ this.expandedProviders.clear();
211
+ const first = this.summary.providers[0];
212
+ if (first) this.expandedProviders.add(first.name);
213
+ this.requestRender();
214
+ }
215
+
216
+ /** Switch the window and re-read the numbers for it. Selection returns to the first row:
217
+ * a provider that carried the last 3 months can be absent from today. */
218
+ private setRange(range: UsageRange): void {
219
+ if (range === this.range) return;
220
+ this.range = range;
221
+ this.summary = collectUsageSummary(true, range);
222
+ this.selectedIndex = 0;
223
+ this.expandedProviders.clear();
224
+ const first = this.summary.providers[0];
225
+ if (first) this.expandedProviders.add(first.name);
226
+ this.requestRender();
227
+ }
228
+
140
229
  handleInput(keyData: string): void {
141
230
  const rows = this.buildFlatRows();
142
- if (matchesBack(keyData)) {
231
+ // A pending question owns the keyboard: any key but y answers no, so a stray press
232
+ // can neither delete anything nor navigate.
233
+ if (this.confirmStep) {
234
+ const yes = matchesKey(keyData, "y") || matchesKey(keyData, "Y");
235
+ const step = this.confirmStep;
236
+ this.confirmStep = null;
237
+ if (yes) this.runConfirm(step);
238
+ else this.requestRender();
239
+ return;
240
+ }
241
+ // Esc and ← both step out one level: the dashboard reports it upward so the /arnative
242
+ // menu reopens. q closes outright, for a dashboard opened by /usage on its own.
243
+ if (matchesBack(keyData) || matchesKey(keyData, "escape")) {
143
244
  this.onDone(true);
144
245
  return;
145
246
  }
146
- if (matchesKey(keyData, "q") || matchesKey(keyData, "Q") || matchesKey(keyData, "escape")) {
247
+ if (matchesKey(keyData, "q") || matchesKey(keyData, "shift+q")) {
147
248
  this.onDone(false);
148
249
  return;
149
250
  }
251
+ if (RESET_USAGE.matches(keyData)) {
252
+ this.confirmStep = "reset";
253
+ this.notice = null;
254
+ this.requestRender();
255
+ return;
256
+ }
257
+ if (UNDO_USAGE.matches(keyData) && this.trashDir) {
258
+ this.confirmStep = "undo";
259
+ this.requestRender();
260
+ return;
261
+ }
262
+ if (matchesKey(keyData, "tab") || matchesKey(keyData, "shift+tab")) {
263
+ const at = USAGE_RANGES.indexOf(this.range);
264
+ const step = matchesKey(keyData, "shift+tab") ? -1 : 1;
265
+ this.setRange(USAGE_RANGES[(at + step + USAGE_RANGES.length) % USAGE_RANGES.length]!);
266
+ return;
267
+ }
150
268
  if (matchesKey(keyData, "up") || matchesKey(keyData, "k")) {
151
269
  // Up
152
270
  if (this.selectedIndex > 0) {
@@ -174,6 +292,12 @@ export class UsageModalComponent implements Component {
174
292
  if (event.type === "wheel" || event.type === "move" || event.type === "drag" || event.type === "release") {
175
293
  return undefined;
176
294
  }
295
+ // A click on the range bar picks that window, so the bar is a control, not a label.
296
+ const tab = this.tabHitboxes.find((h) => h.line === event.y && event.x >= h.start && event.x <= h.end);
297
+ if (tab) {
298
+ if (event.type === "click") this.setRange(tab.range);
299
+ return { handled: true, render: event.type === "click" };
300
+ }
177
301
  const hit = this.rowHitboxes.find((h) => h.line === event.y);
178
302
  if (!hit) {
179
303
  // A click outside the table is not ours to consume: let it fall through (text
@@ -245,15 +369,44 @@ export class UsageModalComponent implements Component {
245
369
  /** Rows the chrome draws above the body: top edge, title, description, blank. */
246
370
  const CHROME_ROWS = 4;
247
371
  this.rowHitboxes = [];
372
+ this.tabHitboxes = [];
373
+
374
+ // Row 1: the window bar. The active range is the only accented word, so the numbers
375
+ // below are read with the window they cover; the counter on the same line says how many
376
+ // rows exist beyond the viewport.
377
+ const bar: string[] = [];
378
+ let barCol = 0;
379
+ for (const r of USAGE_RANGES) {
380
+ if (bar.length > 0) {
381
+ bar.push(dim(" · "));
382
+ barCol += 3;
383
+ }
384
+ const label = RANGE_LABELS[r];
385
+ const text = r === this.range ? acc(bold(label)) : th.fg("muted", label);
386
+ this.tabHitboxes.push({ line: CHROME_ROWS + 2, start: barCol + 2, end: barCol + label.length + 1, range: r });
387
+ bar.push(text);
388
+ barCol += label.length;
389
+ }
390
+ const counter = `${Math.min(rows.length, USAGE_VIEWPORT)}/${rows.length}`;
391
+ const rule = th.fg("borderMuted", "\u2500".repeat(Math.max(0, contentW)));
392
+ const barLine = bar.join("");
393
+ const counterFits = contentW - barCol - counter.length - 1 >= 0;
394
+ // The bar is a control between two rules, so the eye reads it as a switch over the table
395
+ // below it, not as a line of the table itself.
396
+ body.push(rule);
397
+ body.push(counterFits ? barLine + " ".repeat(contentW - barCol - counter.length) + dim(counter) : barLine);
398
+ body.push(rule);
248
399
  body.push(headerText);
249
400
 
250
- // Data rows (with a display height cap so it cannot overflow)
251
- const maxVisibleRows = 16;
401
+ // Row 2 onward: the table, windowed so the box keeps one height however long the list
402
+ // of providers and models grows. The line above and below say what is out of sight.
403
+ const maxVisibleRows = USAGE_VIEWPORT;
252
404
  let startIdx = 0;
253
405
  if (rows.length > maxVisibleRows) {
254
406
  startIdx = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisibleRows / 2), rows.length - maxVisibleRows));
255
407
  }
256
408
  const visibleRows = rows.slice(startIdx, startIdx + maxVisibleRows);
409
+ if (startIdx > 0) body.push(dim(`↑ ${startIdx} more`));
257
410
 
258
411
  for (let i = 0; i < visibleRows.length; i++) {
259
412
  const item = visibleRows[i]!;
@@ -279,14 +432,17 @@ export class UsageModalComponent implements Component {
279
432
  this.rowHitboxes.push({ line: CHROME_ROWS + body.length, index: actualIdx });
280
433
  body.push(line);
281
434
  }
435
+ const hiddenBelow = rows.length - (startIdx + visibleRows.length);
436
+ if (hiddenBelow > 0) body.push(dim(`↓ ${hiddenBelow} more`));
282
437
 
283
438
  // The selected row's detail sits under the table, where the eye lands after scanning it.
284
439
  body.push("");
285
440
  body.push(this.selectedDetail(rows[this.selectedIndex], acc, soft));
441
+ if (this.notice) body.push(th.fg("muted", this.notice));
286
442
 
287
443
  // Table-width separator above Total band (skill arnative-pi §6 rule 7).
288
444
  const tableW = colW.name + sessionW + messagesW + colW.tokens + colW.cost;
289
- body.push(th.fg("dim", "─".repeat(Math.max(0, tableW))));
445
+ body.push(th.fg("borderMuted", "─".repeat(Math.max(0, tableW))));
290
446
 
291
447
  // Total row
292
448
  const t = this.summary.totals;
@@ -309,13 +465,32 @@ export class UsageModalComponent implements Component {
309
465
  {
310
466
  title: screenTitle("Usage"),
311
467
  description: width >= 70 ? "Token, message & cache usage across all local Pi sessions." : "Usage across all local sessions.",
312
- legend: legendUsage(width),
468
+ legend: this.footer(width, th),
313
469
  },
314
470
  body,
315
471
  edge,
316
472
  );
317
473
  }
318
474
 
475
+ /** The last row of the box: a pending question, or the keys that are live right now. */
476
+ private footer(width: number, th: { fg(c: string, t: string): string }): string {
477
+ 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");
481
+ }
482
+ if (this.confirmStep === "undo") {
483
+ return (
484
+ th.fg("accent", "Put the history back?") +
485
+ " " +
486
+ th.fg("muted", "the trash folder stays") +
487
+ " " +
488
+ th.fg("text", "[y] Yes [Esc] Cancel")
489
+ );
490
+ }
491
+ return legendUsage(width, { reset: true, undo: this.trashDir !== null });
492
+ }
493
+
319
494
  /** Detail for the selected row: icon in `accent`, text and `·` dividers in `accentSoft`. */
320
495
  private selectedDetail(
321
496
  row: RowItem | undefined,
@@ -342,7 +517,13 @@ export async function openUsage(ctx: ExtensionCommandContext): Promise<boolean>
342
517
  // The thinking level colors the box, so read it when the dashboard opens.
343
518
  const thinkingLevel = ctx.thinkingLevel;
344
519
  const back = await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
345
- return new UsageModalComponent(theme, (wantsBack) => done(wantsBack), () => tui.requestRender(), thinkingLevel);
520
+ return new UsageModalComponent(
521
+ theme,
522
+ (wantsBack) => done(wantsBack),
523
+ () => tui.requestRender(),
524
+ thinkingLevel,
525
+ ctx.sessionManager.getSessionFile() ?? undefined,
526
+ );
346
527
  });
347
528
  return back === true;
348
529
  }
@@ -390,6 +571,14 @@ if (isMain(import.meta.url)) {
390
571
  assert(summary.totals.sessions === 1, "collectUsageSummary detects total sessions");
391
572
  assert(summary.totals.msgs === 3, "collectUsageSummary counts assistant messages only");
392
573
  assert(Math.abs(summary.totals.cost - 0.06) < 1e-9, "collectUsageSummary counts cost");
574
+ // Tokens is everything the model moved, cache reads included: a vendor dashboard counts
575
+ // the same three numbers, so 240M cached tokens cannot vanish from the headline.
576
+ assert(
577
+ summary.totals.totalTokens === summary.totals.input + summary.totals.output + summary.totals.cacheRead,
578
+ "the Tokens total is prompt + completion + cache reads",
579
+ );
580
+ assert(summary.totals.totalTokens === 175, `the fixture moves 175 tokens in total, got ${summary.totals.totalTokens}`);
581
+ assert(summary.providers[0]!.models[0]!.totalTokens === 162, "a model row counts its cache reads too");
393
582
 
394
583
  const modelUsage = getModelAllTimeUsage("gemini-3.8-flash");
395
584
  assert(modelUsage.input === 150 && modelUsage.output === 10 && modelUsage.cacheRead === 2, "getModelAllTimeUsage sums one model across messages");
@@ -613,7 +802,7 @@ if (isMain(import.meta.url)) {
613
802
  !lines.slice(headerAt + 1, firstRow).some((l) => l.includes("├")),
614
803
  "no rule sits between the header and the first row",
615
804
  );
616
- assert(plain(lines[headerAt - 1]!).slice(1, -1).trim() === "", "a blank row separates the description from the header");
805
+ assert(/^─+$/.test(plain(lines[headerAt - 1]!).slice(1, -1).trim()), "a rule closes the window bar above the header");
617
806
  // The header is content: it sits flush with the title, and each column title ends on the
618
807
  // same cell its own numbers end on.
619
808
  const headerLine = plain(lines[headerAt]!);
@@ -758,17 +947,17 @@ if (isMain(import.meta.url)) {
758
947
  } as never) === undefined,
759
948
  "a wheel event is left to the terminal",
760
949
  );
761
- // `←` is the arnative-wide "go back" key: the dashboard reports it upward instead of
762
- // closing, so the /arnative menu can reopen. Esc/q still close it outright.
950
+ // `←` and Esc are the arnative-wide "go back" keys: the dashboard reports them upward
951
+ // instead of closing, so the /arnative menu can reopen. q still closes it outright.
763
952
  const doneArgs: boolean[] = [];
764
953
  const nav = new UsageModalComponent(fakeTheme, (back) => doneArgs.push(back), () => {}, "high");
765
954
  nav.handleInput("\x1b[D"); // ←
766
955
  nav.handleInput("\x1b"); // Esc
767
956
  nav.handleInput("q");
768
- assert(doneArgs.length === 3 && doneArgs[0] === true && doneArgs[1] === false && doneArgs[2] === false, "← reports back, Esc/q close");
957
+ assert(doneArgs.length === 3 && doneArgs[0] === true && doneArgs[1] === true && doneArgs[2] === false, "← and Esc report back, q closes");
769
958
  assert(
770
- new UsageModalComponent(fakeTheme, () => {}, () => {}, "high").render(120).some((l) => l.includes("[←] Back")),
771
- "the dashboard legend advertises the back key",
959
+ new UsageModalComponent(fakeTheme, () => {}, () => {}, "high").render(120).some((l) => l.includes("[Esc] Back")),
960
+ "the dashboard legend advertises Esc Back",
772
961
  );
773
962
 
774
963
  // models.json rates price the provider and models directly.
@@ -801,8 +990,8 @@ if (isMain(import.meta.url)) {
801
990
  providers: [
802
991
  {
803
992
  name: "alpha", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000,
804
- totalTokens: 1_500_000, cost: 0, estimatedCost: 0.546,
805
- models: [{ name: "deepseek-v4.1-flash", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000, totalTokens: 1_500_000, cost: 0, estimatedCost: 0.546 }],
993
+ totalTokens: 3_500_000, cost: 0, estimatedCost: 0.546,
994
+ 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 }],
806
995
  },
807
996
  {
808
997
  name: "antigravity", sessions: 1, msgs: 1, input: 2_200_000, output: 626_000, cacheRead: 0,
@@ -810,7 +999,7 @@ if (isMain(import.meta.url)) {
810
999
  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 }],
811
1000
  },
812
1001
  ],
813
- totals: { sessions: 2, msgs: 3, input: 3_200_000, output: 1_126_000, cacheRead: 2_000_000, totalTokens: 4_326_000, cost: 0.65, reportedCost: 0.65, estimatedCost: 0.546 },
1002
+ 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 },
814
1003
  };
815
1004
  (estModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["alpha"]);
816
1005
  const estLines = estModal.render(90);
@@ -832,5 +1021,106 @@ if (isMain(import.meta.url)) {
832
1021
  );
833
1022
  }
834
1023
 
1024
+ // Ranges: three dated files — today, 10 days back, 45 days back — so each window has a
1025
+ // number only it can produce.
1026
+ const dayMs = 86_400_000;
1027
+ const nowMs = Date.now();
1028
+ const stampOf = (offsetDays: number): string => new Date(nowMs - offsetDays * dayMs).toISOString();
1029
+ const datedAsst = (provider: string, model: string, input: number, offsetDays: number) =>
1030
+ JSON.stringify({ timestamp: stampOf(offsetDays), message: { role: "assistant", provider, model, usage: { input, output: 1, cacheRead: 0, cost: { total: 0 } } } });
1031
+ writeFileSync(
1032
+ join(fixture, "sessions", "ui", "dated.jsonl"),
1033
+ [datedAsst("rangely", "m-today", 10, 0), datedAsst("rangely", "m-ten", 20, 10), datedAsst("rangely", "m-old", 40, 45)].join(String.fromCharCode(10)),
1034
+ );
1035
+ resetUsageCache();
1036
+ const msgIn = (range: UsageRange): number => {
1037
+ const found = collectUsageSummary(true, range).providers.find((p) => p.name === "rangely");
1038
+ return found?.msgs ?? 0;
1039
+ };
1040
+ assert(msgIn("all") === 3, "the all window keeps every dated message");
1041
+ assert(msgIn("today") === 1, "today counts only the message written today");
1042
+ assert(msgIn("7d") === 1, "7 day stops before the ten-day record, so only today counts");
1043
+ assert(msgIn("30d") === 2, "30 day covers today and ten days back, not forty-five");
1044
+ assert(msgIn("3m") === 3, "3 month covers all three");
1045
+ // A window with nothing in it is empty, not an error: the bar can be pressed on a quiet day.
1046
+ assert(collectUsageSummary(true, "today").totals.msgs >= 1, "today still reports the rows it has");
1047
+
1048
+ // The backfill: a cache item written before ranges existed has totals but no day buckets.
1049
+ // Asking for a range must re-parse that file rather than report a wrong window.
1050
+ const cacheFile = join(fixture, "arnative", "usage-cache.json");
1051
+ resetUsageCache();
1052
+ const legacy = JSON.parse(readFileSync(cacheFile, "utf8")) as Record<string, Record<string, unknown>>;
1053
+ for (const item of Object.values(legacy)) delete item.d;
1054
+ writeFileSync(cacheFile, JSON.stringify(legacy), "utf8");
1055
+ resetUsageCache();
1056
+ assert(msgIn("today") === 1, "an item without day buckets is re-parsed once a range is asked for");
1057
+ const reloaded = JSON.parse(readFileSync(cacheFile, "utf8")) as Record<string, { d?: unknown }>;
1058
+ assert(Object.values(reloaded).some((item) => item.d !== undefined), "the re-parse writes the day buckets back");
1059
+
1060
+ // The range bar: five windows, the active one accented, and the counter states how many
1061
+ // rows exist past the viewport. Tab moves the window and the numbers follow it.
1062
+ const barModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "high");
1063
+ const barOnce = barModal.render(100).map(plain);
1064
+ const barLine = barOnce.find((l) => l.includes("All") && l.includes("Today") && l.includes("3 month"));
1065
+ assert(barLine !== undefined, "the range bar names every window on one line");
1066
+ assert(USAGE_RANGES.every((r) => barLine!.includes(RANGE_LABELS[r])), "every range label is on the bar");
1067
+ assert(barLine!.indexOf("All") < barLine!.indexOf("Today"), "the bar keeps tab order");
1068
+ const beforeRange = barModal.render(100).map(plain).join("\n");
1069
+ barModal.handleInput("\t");
1070
+ const afterRange = barModal.render(100).map(plain).join("\n");
1071
+ assert(beforeRange !== afterRange, "Tab switches the window and repaints");
1072
+ barModal.handleInput("\x1b[Z");
1073
+ assert(barModal.render(100).map(plain).join("\n") === beforeRange, "Shift+Tab walks the bar back to where it started");
1074
+
1075
+ // The viewport: five rows on screen with a count and an arrow for what is out of sight.
1076
+ const manyModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "medium");
1077
+ const provider = (n: number) => ({
1078
+ name: `p${n}`, sessions: 1, msgs: 1, input: 1000, output: 10, cacheRead: 0, totalTokens: 1010, cost: 0.01, estimatedCost: 0,
1079
+ models: [{ name: "m", sessions: 1, msgs: 1, input: 1000, output: 10, cacheRead: 0, totalTokens: 1010, cost: 0.01, estimatedCost: 0 }],
1080
+ });
1081
+ (manyModal as unknown as { summary: unknown }).summary = {
1082
+ providers: [1, 2, 3, 4, 5, 6, 7].map(provider),
1083
+ totals: { sessions: 7, msgs: 7, input: 7000, output: 70, cacheRead: 0, totalTokens: 7070, cost: 0.07, reportedCost: 0.07, estimatedCost: 0 },
1084
+ };
1085
+ const many = manyModal.render(96).map(plain);
1086
+ assert(many.some((l) => l.includes("5/7")), "the counter reads 5/7 with five rows shown of seven");
1087
+ assert(many.some((l) => l.includes("↓ 2 more")), "rows below the window are counted");
1088
+ assert(!many.some((l) => l.includes("↑ ")), "nothing is announced above the top of the list");
1089
+ const dataRows = many.filter((l) => /^[│|] [▾▸ ] P[0-9]/.test(l));
1090
+ assert(dataRows.length === 5, `exactly five data rows are drawn (got ${dataRows.length})`);
1091
+ for (let i = 0; i < 6; i++) manyModal.handleInput("\x1b[B");
1092
+ const scrolled = manyModal.render(96).map(plain);
1093
+ assert(scrolled.some((l) => l.includes("↑ 2 more")), "moving down announces the rows now above the window");
1094
+ assert(!scrolled.some((l) => l.includes("↓ ")), "the bottom of the list announces only what is above");
1095
+
1096
+
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");
1099
+ const resetDir = mkdtempSync(join(tmpdir(), "arnative-reset-"));
1100
+ process.env.PI_CODING_AGENT_DIR = resetDir;
1101
+ const resetSessions = join(resetDir, "sessions", "proj");
1102
+ 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 } } } });
1104
+ const livePath = join(resetSessions, "live.jsonl");
1105
+ writeFileSync(livePath, resetLine + String.fromCharCode(10));
1106
+ writeFileSync(join(resetSessions, "old.jsonl"), resetLine + String.fromCharCode(10));
1107
+ resetUsageCache();
1108
+ const resetModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "high", livePath);
1109
+ assert(resetModal.render(120).map(plain).some((l) => l.includes("[R] Reset")), "the footer advertises R Reset");
1110
+ 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");
1114
+ resetModal.handleInput("R");
1115
+ 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");
1120
+ resetModal.handleInput("U");
1121
+ 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");
835
1125
  console.log("usage.ts self-check OK");
836
1126
  }
package/lib/ansi.ts CHANGED
@@ -39,15 +39,19 @@ export function setActiveTheme<T>(th: T | null): void {
39
39
  }
40
40
 
41
41
  /**
42
- * Soft tier of a resolved theme color: clone at L 0.82 with a fifth of its chroma and
43
- * the hue kept. The generator's `soften()` (themes/gen-themes.mjs) applies the identical
44
- * recipe, so a declared `vars.*Soft` and this derived value agree. `chroma * 0.18` is
45
- * the single tuning constant for how far a soft tone leans toward grey.
42
+ * Soft tiers of a resolved theme color: clone at a lightness with a share of the
43
+ * chroma and the hue kept. The generator's `soften()` (themes/gen-themes.mjs)
44
+ * applies the identical recipes, so declared `vars.*Soft` values and these
45
+ * derived ones agree. The accent tier approaches white (0.94 lightness, low
46
+ * chroma): it reads as a pale, near-white tint, clearly distinct from the accent,
47
+ * while footer labels stay a visible second color.
46
48
  */
47
- const SOFT_L = 0.82;
48
- const SOFT_CHROMA_SCALE = 0.18;
49
- function softenColor(c: { c?: number; h?: number }): { kind: "oklch"; l: number; c: number; h: number } {
50
- return { kind: "oklch", l: SOFT_L, c: (c.c ?? 0) * SOFT_CHROMA_SCALE, h: c.h ?? 0 };
49
+ const SOFT_L = 0.90;
50
+ const SOFT_CHROMA_SCALE = 0.35;
51
+ const SOFT_L_ACCENT = 0.90;
52
+ const SOFT_CHROMA_SCALE_ACCENT = 0.35;
53
+ function softenColor(c: { c?: number; h?: number }, scale = SOFT_CHROMA_SCALE, l = SOFT_L): { kind: "oklch"; l: number; c: number; h: number } {
54
+ return { kind: "oklch", l, c: (c.c ?? 0) * scale, h: c.h ?? 0 };
51
55
  }
52
56
 
53
57
  /**
@@ -77,7 +81,7 @@ export function softOf(th: {
77
81
  const accent = th?.colors?.accent;
78
82
  const style = th?.style?.bind(th);
79
83
  if (accent?.kind === "oklch" && style) {
80
- const soft = softenColor(accent);
84
+ const soft = softenColor(accent, SOFT_CHROMA_SCALE_ACCENT, SOFT_L_ACCENT);
81
85
  return (s) => style(s, { fg: soft });
82
86
  }
83
87
  return (s) => fg("muted", s);
@@ -173,14 +177,20 @@ if (isMain(import.meta.url)) {
173
177
  colors: { accent: { kind: "oklch", c: 0.2, h: 355 }, borderAccent: { kind: "oklch", c: 0.1, h: 200 } },
174
178
  };
175
179
  const modernOut = softOf(modern)("x");
176
- assert(modernOut.includes('"l":0.82') && modernOut.includes('"c":0.036'), "softOf derives the soft tint from accent (l=0.82, c=accent*0.18)");
180
+ assert(
181
+ Math.abs(JSON.parse(modernOut.match(/<soft:(.*)>x<\/soft>/)[1]!).c - 0.07) < 1e-9 &&
182
+ modernOut.includes('"l":0.9'),
183
+ "softOf derives the soft tint from accent (l=0.9, c=accent*0.35)",
184
+ );
177
185
  assert(modernOut.includes("x"), "softOf keeps the text");
178
186
  // The label tier softens `borderAccent`, NOT `accent`: that is what keeps footer text
179
187
  // on the blue tier instead of inheriting the pink accent hue.
180
188
  const labelOut = softSecondaryOf(modern)("x");
181
189
  assert(
182
- labelOut.includes('"l":0.82') && labelOut.includes('"c":0.018') && labelOut.includes('"h":200'),
183
- "softSecondaryOf softens borderAccent (l=0.82, c=borderAccent*0.18, same hue)",
190
+ Math.abs(JSON.parse(labelOut.match(/<soft:(.*)>x<\/soft>/)[1]!).c - 0.035) < 1e-9 &&
191
+ labelOut.includes('"l":0.9') &&
192
+ labelOut.includes('"h":200'),
193
+ "softSecondaryOf softens borderAccent (l=0.9, c=borderAccent*0.35, same hue)",
184
194
  );
185
195
  assert(labelOut !== modernOut, "the soft label tier differs from the soft accent tier");
186
196
  assert(softSecondaryOf({ fg: () => "", style: (t) => `<x>${t}</x>`, colors: {} })("x") === softOf({ fg: () => "", style: (t) => `<x>${t}</x>`, colors: {} })("x"), "softSecondaryOf falls back to softOf without a borderAccent");
package/lib/box.ts CHANGED
@@ -193,7 +193,7 @@ if (isMain(import.meta.url)) {
193
193
  // The header copy is longer than a narrow terminal: the wall must win over the text.
194
194
  const longCopy = "Selection previews live — arnative themes only (all themes: /settings → Theme).";
195
195
  for (const w of [40, 50, 56, 60]) {
196
- const narrow = renderScreen(th, w, { title: screenTitle("Themes"), description: longCopy, legend: "[Esc] Revert" }, []);
196
+ const narrow = renderScreen(th, w, { title: screenTitle("Themes"), description: longCopy, legend: "[Esc] Back" }, []);
197
197
  assert(narrow.every((l) => visibleWidth(l) === w), `a long description keeps every line at width ${w}`);
198
198
  assert(
199
199
  narrow.filter((l) => l.startsWith("│")).every((l) => l.endsWith("│")),