@cad0p/pi-usage 0.11.4 → 0.11.5-20261103.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/CHANGELOG.md +21 -0
- package/README.md +140 -35
- package/bin/piquota.js +25 -4
- package/extensions/quota-panel.ts +1879 -194
- package/omarchy/cad0p.pi-usage/UsageLogic.js +9 -4
- package/package.json +1 -1
- package/src/cache.js +128 -31
- package/src/cli/args.js +13 -0
- package/src/cli/commands/omarchy.js +21 -3
- package/src/cli/commands/stats.js +149 -1
- package/src/engine.js +178 -29
- package/src/http.js +34 -1
- package/src/local/history.js +53 -7
- package/src/local/pi-sessions.js +48 -5
- package/src/local/stats-worker.js +27 -0
- package/src/local/worker.js +157 -0
- package/src/model.js +39 -5
- package/src/omarchy/publish.js +9 -8
- package/src/omarchy/record.js +18 -11
- package/src/providers/antigravity-oauth.js +43 -3
- package/src/providers/antigravity.js +44 -5
- package/src/providers/opencode-go.js +4 -3
- package/src/refresh.js +4 -1
- package/src/render/panel.js +28 -7
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Pi quota line — read-only quota for the providers Pi already owns.
|
|
3
3
|
*
|
|
4
|
-
* Surface: nothing at session start. Bare /usage
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* Surface: nothing at session start. Bare /usage opens a fullscreen overlay that
|
|
5
|
+
* takes the keyboard, scrolls, folds a section per provider and closes on Esc or
|
|
6
|
+
* q; nothing stays on screen behind it. /usage box, /usage line or /usage panel
|
|
7
|
+
* pins a surface above the editor, /usage status enables the footer, and
|
|
8
|
+
* /usage hide removes it. No timer or post-turn refresh runs until a surface is on.
|
|
8
9
|
*
|
|
9
10
|
* Design rules:
|
|
10
11
|
* - the numbers are **used**, not remaining, so the line answers "how much have
|
|
@@ -23,16 +24,27 @@
|
|
|
23
24
|
*/
|
|
24
25
|
|
|
25
26
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
26
|
-
import { existsSync } from "node:fs";
|
|
27
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
27
28
|
import { homedir } from "node:os";
|
|
28
|
-
import {
|
|
29
|
+
import { join } from "node:path";
|
|
29
30
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
30
31
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
32
|
+
import { extractChatGptAccountId, extractExpiresAtMs } from "../src/auth/jwt.js";
|
|
33
|
+
import { mergeReportIntoCache, writeCache } from "../src/cache.js";
|
|
34
|
+
import { normalizeClaudeSourceMode, collectFamily, enabledFamilies, FAMILIES } from "../src/engine.js";
|
|
35
|
+
import { historyJson } from "../src/cli/commands/stats.js";
|
|
36
|
+
import { resolveHistoryDir } from "../src/local/history.js";
|
|
37
|
+
import { startLocalStatsWorker } from "../src/local/worker.js";
|
|
38
|
+
import { publishRecords } from "../src/omarchy/publish.js";
|
|
39
|
+
import { buildRecords } from "../src/omarchy/record.js";
|
|
40
|
+
import { skippedFamilies } from "../src/cli/commands/omarchy.js";
|
|
41
|
+
import { mergeLastGood } from "../src/sticky.js";
|
|
42
|
+
import { readRefreshState, resolveFamilyTtls, staleFamilies, writeRefreshState } from "../src/refresh.js";
|
|
43
|
+
|
|
44
|
+
// The in-process collector does not pass through the CLI's sticky layer, so this
|
|
45
|
+
// extension applies the same last-good merge as the CLI before painting or publishing.
|
|
46
|
+
// The classifier below mirrors src/providers/error-kind.js so the extension can
|
|
47
|
+
// render category-specific glyphs without depending on the repo.
|
|
36
48
|
|
|
37
49
|
const STATUS_KEY = "00-quota";
|
|
38
50
|
const WIDGET_KEY = "quota-line";
|
|
@@ -41,7 +53,12 @@ const RAIL_KEY = "quota";
|
|
|
41
53
|
const SIDEBAR_STATE_KEY = Symbol.for("gentle-pi.experimental-sidebar.state");
|
|
42
54
|
const REFRESH_MS = Number(process.env.PI_QUOTA_REFRESH_MS) || 300_000;
|
|
43
55
|
const AGENT_END_DEBOUNCE_MS = 1_500;
|
|
44
|
-
|
|
56
|
+
/** The report cache is keyed by the Claude source its numbers came from. */
|
|
57
|
+
const CLAUDE_SOURCE_CACHE_PREFIX = "claude-source:";
|
|
58
|
+
|
|
59
|
+
function cacheKeyFor(source: string): string {
|
|
60
|
+
return `${CLAUDE_SOURCE_CACHE_PREFIX}${normalizeClaudeSourceMode(source)}`;
|
|
61
|
+
}
|
|
45
62
|
|
|
46
63
|
type QuotaWindow = {
|
|
47
64
|
id: string;
|
|
@@ -83,6 +100,8 @@ type LocalAccountStats = {
|
|
|
83
100
|
todayPrompts?: number;
|
|
84
101
|
totalPrompts?: number;
|
|
85
102
|
totalTokens?: number;
|
|
103
|
+
/** The account's own model split for today; absent from an older report. */
|
|
104
|
+
todayTokensByModel?: Record<string, number>;
|
|
86
105
|
};
|
|
87
106
|
|
|
88
107
|
/**
|
|
@@ -121,14 +140,43 @@ type Theme = {
|
|
|
121
140
|
bg?: (key: string, text: string) => string;
|
|
122
141
|
};
|
|
123
142
|
|
|
143
|
+
/**
|
|
144
|
+
* One running local token scan. It is a handle, not a promise, because the scan
|
|
145
|
+
* can outlive the session that started it: a shutdown has to be able to end it
|
|
146
|
+
* and have its lock and cache left clean.
|
|
147
|
+
*/
|
|
148
|
+
type LocalStatsScan = {
|
|
149
|
+
result: Promise<{ byFamily: Record<string, LocalFamilyStats>; warnings: string[]; scan: { partial?: boolean } | null }>;
|
|
150
|
+
stop: () => Promise<void>;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
type ExtensionDependencies = {
|
|
154
|
+
collectFamily?: typeof collectFamily;
|
|
155
|
+
startLocalStats?: () => LocalStatsScan;
|
|
156
|
+
getProviderAuth?: (ctx: UiContext, provider: string) => Promise<{ auth?: { apiKey?: string }; accountId?: string; source?: string } | undefined>;
|
|
157
|
+
loadHistory?: (month: string | null) => Promise<HistoryPayload> | HistoryPayload;
|
|
158
|
+
publishOmarchy?: (report: QuotaReport, prune: boolean) => void;
|
|
159
|
+
railPatcherPath?: string;
|
|
160
|
+
};
|
|
161
|
+
|
|
124
162
|
/** Only the UI surface this extension uses. */
|
|
125
163
|
type UiContext = {
|
|
126
164
|
hasUI: boolean;
|
|
165
|
+
/** Pi resolves/renews its OAuth credentials under its own auth-store lock. */
|
|
166
|
+
modelRegistry?: {
|
|
167
|
+
getProviderAuth?: (provider: string) => Promise<{ auth?: { apiKey?: string }; source?: string } | undefined>;
|
|
168
|
+
};
|
|
169
|
+
/** Pi's run mode; `custom` components only exist in the TUI. */
|
|
170
|
+
mode?: string;
|
|
127
171
|
ui: {
|
|
128
172
|
theme: Theme;
|
|
129
173
|
setStatus: (key: string, value: string | undefined) => void;
|
|
130
174
|
setWidget: (key: string, value: any, options?: { placement?: string }) => void;
|
|
131
175
|
notify: (message: string, type?: string) => void;
|
|
176
|
+
custom?: (
|
|
177
|
+
factory: (tui: any, theme: Theme, keybindings: any, done: (result?: unknown) => void) => any,
|
|
178
|
+
options?: { overlay?: boolean; overlayOptions?: Record<string, unknown> },
|
|
179
|
+
) => Promise<unknown>;
|
|
132
180
|
};
|
|
133
181
|
};
|
|
134
182
|
|
|
@@ -184,23 +232,7 @@ function usedOf(window: QuotaWindow | null): number | null {
|
|
|
184
232
|
return null;
|
|
185
233
|
}
|
|
186
234
|
|
|
187
|
-
|
|
188
|
-
const override = process.env.PI_QUOTA_BIN;
|
|
189
|
-
if (override && existsSync(override)) return override;
|
|
190
|
-
try {
|
|
191
|
-
const sibling = fileURLToPath(new URL("../bin/piquota.js", import.meta.url));
|
|
192
|
-
if (existsSync(sibling)) return sibling;
|
|
193
|
-
} catch {}
|
|
194
|
-
for (const candidate of [
|
|
195
|
-
join(homedir(), ".local", "share", "pi-quota", "bin", "piquota.js"),
|
|
196
|
-
join(homedir(), ".local", "bin", "piquota"),
|
|
197
|
-
join(homedir(), ".pi", "agent", "npm", "node_modules", "@cad0p", "pi-usage", "bin", "piquota.js"),
|
|
198
|
-
join(homedir(), ".pi", "agent", "npm", "node_modules", "@j3pf", "piquota", "bin", "piquota.js"),
|
|
199
|
-
]) {
|
|
200
|
-
if (existsSync(candidate)) return candidate;
|
|
201
|
-
}
|
|
202
|
-
return null;
|
|
203
|
-
}
|
|
235
|
+
|
|
204
236
|
|
|
205
237
|
/**
|
|
206
238
|
* Rank by how soon a window constrains you: 5h/session first, then daily,
|
|
@@ -550,44 +582,103 @@ function clipToWidth(line: string, width: number): string {
|
|
|
550
582
|
return out;
|
|
551
583
|
}
|
|
552
584
|
|
|
585
|
+
/** One visible character with the SGR runs in front of it and the style it inherits. */
|
|
586
|
+
type StyledChar = { raw: string; char: string; style: string };
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Split a themed line into visible characters, folding each SGR run into the
|
|
590
|
+
* character that follows it and remembering the style open at that point.
|
|
591
|
+
* Wrapping needs both: a continuation row must re-open the style it inherits,
|
|
592
|
+
* and every produced row must close whatever it left open.
|
|
593
|
+
*/
|
|
594
|
+
function styledChars(line: string): { chars: StyledChar[]; trailing: string } {
|
|
595
|
+
const chars: StyledChar[] = [];
|
|
596
|
+
let pending = "";
|
|
597
|
+
let style = "";
|
|
598
|
+
for (let index = 0; index < line.length; ) {
|
|
599
|
+
const sgr = /^\u001b\[[0-9;]*m/.exec(line.slice(index));
|
|
600
|
+
if (sgr) {
|
|
601
|
+
pending += sgr[0];
|
|
602
|
+
style = sgr[0] === "\u001b[0m" ? "" : `${style}${sgr[0]}`;
|
|
603
|
+
index += sgr[0].length;
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
const char = String.fromCodePoint(line.codePointAt(index) as number);
|
|
607
|
+
chars.push({ raw: `${pending}${char}`, char, style });
|
|
608
|
+
pending = "";
|
|
609
|
+
index += char.length;
|
|
610
|
+
}
|
|
611
|
+
return { chars, trailing: pending };
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* Wrap one themed line to `width` columns, breaking at its " · " separators.
|
|
616
|
+
*
|
|
617
|
+
* A hard clip used to cut a row mid-token at 64 columns, which loses the datum
|
|
618
|
+
* that matters most: "(18d)" is when the month resets, and "token exp" is the
|
|
619
|
+
* state of the credential. So a row that does not fit wraps instead — the first
|
|
620
|
+
* row keeps the line's own indent, every continuation is indented by the line's
|
|
621
|
+
* leading spaces (or `hanging`), and no cell is ever dropped. A single cell
|
|
622
|
+
* wider than the terminal is the one case that still clips: there is nowhere to
|
|
623
|
+
* break it.
|
|
624
|
+
*/
|
|
625
|
+
function wrapLine(line: string, width: number, hanging?: string): string[] {
|
|
626
|
+
const limit = Math.max(1, Math.floor(width));
|
|
627
|
+
if (visibleLength(line) <= limit) return [line];
|
|
628
|
+
const { chars, trailing } = styledChars(line);
|
|
629
|
+
if (chars.length === 0) return [line];
|
|
630
|
+
const visible = chars.map((item) => item.char).join("");
|
|
631
|
+
// A break sits on the space in front of " · ", so neither row starts with a
|
|
632
|
+
// dangling middle dot.
|
|
633
|
+
const breaks: number[] = [];
|
|
634
|
+
const spaces: number[] = [];
|
|
635
|
+
for (let index = 0; index + 2 < visible.length; index += 1) {
|
|
636
|
+
if (visible[index] === " " && visible[index + 1] === "·" && visible[index + 2] === " ") breaks.push(index);
|
|
637
|
+
}
|
|
638
|
+
for (let index = 0; index < visible.length; index += 1) if (visible[index] === " ") spaces.push(index);
|
|
639
|
+
const indent = hanging ?? /^ */.exec(visible)?.[0] ?? "";
|
|
640
|
+
const row = (from: number, to: number, prefix: string, extra = ""): string => {
|
|
641
|
+
// A wrapped row must not end in the padding the break was taken on.
|
|
642
|
+
const text = `${prefix}${chars.slice(from, to).map((item) => item.raw).join("")}${extra}`.replace(/ +(?=(\u001b\[[0-9;]*m)*$)/, "");
|
|
643
|
+
return /\u001b\[/.test(text) ? `${text}\u001b[0m` : text;
|
|
644
|
+
};
|
|
645
|
+
|
|
646
|
+
const lines: string[] = [];
|
|
647
|
+
let start = 0;
|
|
648
|
+
while (start < chars.length) {
|
|
649
|
+
const prefix = start === 0 ? "" : chars[start].style === "" ? indent : `${indent}${chars[start].style}`;
|
|
650
|
+
const fits = start + Math.max(1, limit - visibleLength(prefix));
|
|
651
|
+
if (fits >= chars.length) {
|
|
652
|
+
lines.push(row(start, chars.length, prefix, trailing));
|
|
653
|
+
break;
|
|
654
|
+
}
|
|
655
|
+
// A " · " boundary is the natural break; a word boundary is the fallback, so
|
|
656
|
+
// a long warning wraps between words instead of mid-token; a single word
|
|
657
|
+
// wider than the pane is the only case left to hard-cut.
|
|
658
|
+
const breakAt = breaks.filter((index) => index > start && index <= fits).pop();
|
|
659
|
+
const spaceAt = breakAt === undefined ? spaces.filter((index) => index > start && index <= fits).pop() : undefined;
|
|
660
|
+
const cut = breakAt ?? spaceAt ?? fits;
|
|
661
|
+
lines.push(row(start, cut, prefix));
|
|
662
|
+
start = breakAt === undefined ? (spaceAt === undefined ? cut : cut + 1) : cut + 3;
|
|
663
|
+
}
|
|
664
|
+
return lines.length > 0 ? lines : [line];
|
|
665
|
+
}
|
|
666
|
+
|
|
553
667
|
/**
|
|
554
668
|
* The panel as a component rather than a string array: Pi caps string-array
|
|
555
669
|
* widgets at ten lines, and a multi-account family alone can exceed that.
|
|
670
|
+
*
|
|
671
|
+
* A line that does not fit wraps at its separators instead of being cut: at 64
|
|
672
|
+
* columns a hard clip used to lose the half of a row that says when the month
|
|
673
|
+
* resets, which is exactly the datum the row exists for.
|
|
556
674
|
*/
|
|
557
675
|
function panelComponent(lines: string[]) {
|
|
558
676
|
return () => ({
|
|
559
|
-
render: (width: number) => lines.
|
|
677
|
+
render: (width: number) => lines.flatMap((line) => wrapLine(line, Math.max(0, width - 1))).map((line) => ` ${line}`),
|
|
560
678
|
invalidate() {},
|
|
561
679
|
});
|
|
562
680
|
}
|
|
563
681
|
|
|
564
|
-
/**
|
|
565
|
-
* The one-line notify summary. A multi-account family reports how many accounts
|
|
566
|
-
* answer and the account with the most room, not whichever key happens to be #1.
|
|
567
|
-
*/
|
|
568
|
-
function summarize(report: QuotaReport): string {
|
|
569
|
-
const active = report.providers.filter((provider) => provider.notConfigured !== true);
|
|
570
|
-
return firstPerFamily(active)
|
|
571
|
-
.map((provider) => {
|
|
572
|
-
const name = SHORT_NAME[provider.family] ?? provider.family;
|
|
573
|
-
if (isMultiAccount(active, provider)) {
|
|
574
|
-
const accounts = active.filter((other) => other.family === provider.family);
|
|
575
|
-
const scored = accounts
|
|
576
|
-
.filter((account) => account.ok)
|
|
577
|
-
.map((account) => ({ account, used: usedOf(bindingWindow(account)) }))
|
|
578
|
-
.filter((entry): entry is { account: QuotaProvider; used: number } => entry.used !== null);
|
|
579
|
-
const counted = `${accounts.filter((account) => account.ok).length}/${accounts.length} ok`;
|
|
580
|
-
if (scored.length === 0) return `${name}: ${counted}`;
|
|
581
|
-
const lowest = scored.reduce((best, entry) => (entry.used < best.used ? entry : best));
|
|
582
|
-
return `${name}: ${counted} · lowest ${Math.round(lowest.used)}% (${lowest.account.account})`;
|
|
583
|
-
}
|
|
584
|
-
if (!provider.ok) return `${name}: ${errorCaption(provider.error)}`;
|
|
585
|
-
const used = usedOf(headline(provider));
|
|
586
|
-
return `${name}: ${used === null ? "n/a" : `${Math.round(used)}% used`}`;
|
|
587
|
-
})
|
|
588
|
-
.join(" · ");
|
|
589
|
-
}
|
|
590
|
-
|
|
591
682
|
/** Window names for the one-line account rows (same words as the Omarchy panel). */
|
|
592
683
|
const WINDOW_TAG: Record<string, string> = { "5h": "session", weekly: "week", monthly: "month" };
|
|
593
684
|
|
|
@@ -690,11 +781,29 @@ function accountReason(error: string | null | undefined): string {
|
|
|
690
781
|
return errorCaption(error);
|
|
691
782
|
}
|
|
692
783
|
|
|
693
|
-
/**
|
|
784
|
+
/**
|
|
785
|
+
* The slot label of an account: "" for the base auth.json entry (it has no
|
|
786
|
+
* number, so no surface may invent one) and "#<slot>" for a real sibling. A
|
|
787
|
+
* report cached before the fix still says "#1" for the base entry.
|
|
788
|
+
*/
|
|
789
|
+
function accountLabel(account: string | null | undefined): string {
|
|
790
|
+
const text = String(account ?? "");
|
|
791
|
+
if (text === "#1") return "";
|
|
792
|
+
return /^#\d+$/.test(text) ? text : text;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** The per-account token row, tolerating the old "#1" key in a cached scan. */
|
|
796
|
+
function accountStats(stats: LocalFamilyStats | undefined, label: string): LocalAccountStats | undefined {
|
|
797
|
+
if (!stats?.byAccount) return undefined;
|
|
798
|
+
return stats.byAccount[label] ?? (label === "" ? stats.byAccount["#1"] : undefined);
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* A family Pi holds several credentials for: one section and one line per
|
|
803
|
+
* account, whatever the account labels look like.
|
|
804
|
+
*/
|
|
694
805
|
function isMultiAccount(providers: QuotaProvider[], provider: QuotaProvider): boolean {
|
|
695
|
-
return
|
|
696
|
-
&& provider.account.startsWith("#")
|
|
697
|
-
&& providers.filter((other) => other.family === provider.family).length > 1;
|
|
806
|
+
return providers.filter((other) => other.family === provider.family).length > 1;
|
|
698
807
|
}
|
|
699
808
|
|
|
700
809
|
/**
|
|
@@ -708,20 +817,23 @@ function renderAccountRows(accounts: QuotaProvider[], theme: Theme, stats?: Loca
|
|
|
708
817
|
const healthy = accounts.filter((account) => account.ok).length;
|
|
709
818
|
const header = `${paint(BRAND[family] ?? "#8B949E", SHORT_NAME[family] ?? accounts[0].label)} ${theme.fg("dim", `· ${healthy} of ${accounts.length} accounts ok`)}`;
|
|
710
819
|
const lines = [header];
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
820
|
+
// The base entry has no number: its label column is blank but padded to the
|
|
821
|
+
// widest sibling, so the percentage columns still line up.
|
|
822
|
+
const labels = accounts.map((account) => accountLabel(account.account));
|
|
823
|
+
const width = Math.max(...labels.map((label) => label.length));
|
|
824
|
+
accounts.forEach((account, index) => {
|
|
825
|
+
const label = theme.fg("dim", labels[index].padEnd(width));
|
|
714
826
|
if (!account.ok) {
|
|
715
827
|
const kind = errorKind(account.error);
|
|
716
828
|
const color = kind === "transient" || kind === "throttle" ? "warning" : kind === "expired" || kind === "auth" ? "error" : "dim";
|
|
717
829
|
lines.push(` ${label} ${theme.fg(color, errorGlyph(account.error))} ${theme.fg("warning", accountReason(account.error))}`);
|
|
718
|
-
|
|
830
|
+
return;
|
|
719
831
|
}
|
|
720
832
|
const window = bindingWindow(account);
|
|
721
833
|
const used = usedOf(window);
|
|
722
834
|
if (window === null || used === null) {
|
|
723
835
|
lines.push(` ${label} ${theme.fg("dim", "no rate-limit windows reported")}`);
|
|
724
|
-
|
|
836
|
+
return;
|
|
725
837
|
}
|
|
726
838
|
// Every window on one line, each in its own band colour; the leading glyph
|
|
727
839
|
// is the fullest window's, so the column still sorts the accounts by eye.
|
|
@@ -733,98 +845,1389 @@ function renderAccountRows(accounts: QuotaProvider[], theme: Theme, stats?: Loca
|
|
|
733
845
|
const reset = each.resetsInSec === null ? "" : ` ${theme.fg("dim", `(${shortDuration(each.resetsInSec)})`.padEnd(5))}`;
|
|
734
846
|
return `${theme.fg("dim", WINDOW_TAG[each.id] ?? each.id)} ${paint(bandFor(pct).color, `${Math.round(pct)}%`.padStart(4))}${reset}`;
|
|
735
847
|
});
|
|
736
|
-
const today = Number(stats
|
|
848
|
+
const today = Number(accountStats(stats, labels[index])?.todayTokens) || 0;
|
|
737
849
|
const tokens = today > 0 ? ` · ${formatTokens(today)} today` : "";
|
|
738
850
|
lines.push(` ${label} ${paint(band.color, band.glyph)} ${cells.join(theme.fg("dim", " · "))}${theme.fg("dim", tokens)}`);
|
|
739
|
-
}
|
|
851
|
+
});
|
|
740
852
|
return lines;
|
|
741
853
|
}
|
|
742
854
|
|
|
743
|
-
|
|
855
|
+
/**
|
|
856
|
+
* One provider block of the panel: the header painted with the provider name
|
|
857
|
+
* and every window, account and token row that belongs to it. The overlay
|
|
858
|
+
* folds on these blocks; the pinned widget renders them flat, unchanged.
|
|
859
|
+
*/
|
|
860
|
+
type PanelSection = { key: string; header: string; body: string[] };
|
|
861
|
+
|
|
862
|
+
/** The provider block of a single-account provider: its header plus its detail. */
|
|
863
|
+
function renderProviderLines(provider: QuotaProvider, theme: Theme, localStats: LocalFamilyStats | undefined, partialScan: boolean): string[] {
|
|
744
864
|
const lines: string[] = [];
|
|
865
|
+
const labelWidth = Math.max(6, ...provider.windows.map((window) => String(window.label ?? "").length));
|
|
866
|
+
const name = paint(BRAND[provider.family] ?? "#8B949E", provider.label);
|
|
867
|
+
const account = accountLabel(provider.account);
|
|
868
|
+
const meta: string[] = account === "" ? [] : [account];
|
|
869
|
+
if (provider.plan) meta.push(`plan ${provider.plan}`);
|
|
870
|
+
// Two stores can back Claude, and this is the one place that says which.
|
|
871
|
+
if (provider.sourceKind === "claude-code") meta.push("Claude Code CLI");
|
|
872
|
+
if (provider.expiresInMin !== null && provider.expiresInMin <= 120) {
|
|
873
|
+
meta.push(
|
|
874
|
+
provider.expiresInMin < 0
|
|
875
|
+
? theme.fg("error", "token expired")
|
|
876
|
+
: theme.fg("dim", `token ${provider.expiresInMin}m`),
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
lines.push(meta.length > 0 ? `${name} ${theme.fg("dim", `· ${meta.join(" · ")}`)}` : name);
|
|
880
|
+
|
|
881
|
+
if (!provider.ok) {
|
|
882
|
+
const kind = errorKind(provider.error);
|
|
883
|
+
const glyph = errorGlyph(provider.error);
|
|
884
|
+
const color = kind === "transient" || kind === "throttle" ? "warning" : kind === "expired" || kind === "auth" ? "error" : "dim";
|
|
885
|
+
lines.push(` ${theme.fg(color, glyph)} ${theme.fg("warning", provider.note ?? errorCaption(provider.error))}`);
|
|
886
|
+
if (isRecoverableError(provider.error) && provider.note) lines.push(` ${theme.fg("warning", provider.note)}`);
|
|
887
|
+
} else if (provider.windows.length === 0) {
|
|
888
|
+
if (provider.note) lines.push(` ${theme.fg("warning", `~ ${provider.note}`)}`);
|
|
889
|
+
lines.push(` ${theme.fg("dim", "no rate-limit windows reported")}`);
|
|
890
|
+
} else {
|
|
891
|
+
if (provider.note) lines.push(` ${theme.fg("warning", `~ ${provider.note}`)}`);
|
|
892
|
+
for (const window of provider.windows) {
|
|
893
|
+
const used = usedOf(window);
|
|
894
|
+
const label = theme.fg("dim", window.label.padEnd(labelWidth));
|
|
895
|
+
if (used === null) {
|
|
896
|
+
lines.push(` ${label} ${theme.fg("dim", window.note ?? "no percentage reported")}`);
|
|
897
|
+
continue;
|
|
898
|
+
}
|
|
899
|
+
const band = bandFor(used);
|
|
900
|
+
const reset = window.resetsInSec === null ? "" : theme.fg("dim", ` · reset in ${humanDuration(window.resetsInSec)}`);
|
|
901
|
+
lines.push(
|
|
902
|
+
` ${label} ${paint(band.color, band.glyph)} ${paint(band.color, bar(used))} ` +
|
|
903
|
+
`${paint(band.color, `${used.toFixed(used < 10 ? 1 : 0)}%`.padStart(5))} ` +
|
|
904
|
+
`${theme.fg("dim", "used")}${reset}`,
|
|
905
|
+
);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
// Local token stats survive a failed quota probe: the credential may be
|
|
910
|
+
// rejected while the tokens already burned are still a fact on disk.
|
|
911
|
+
lines.push(...renderTokenRows(localStats, labelWidth, theme, partialScan));
|
|
912
|
+
return lines;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
* Split the panel into its foldable provider sections and the lines below them
|
|
917
|
+
* (byline, unconfigured providers, warnings). Bare `/usage` folds these; the
|
|
918
|
+
* pinned `/usage panel` flattens them back into the same list as before.
|
|
919
|
+
*/
|
|
920
|
+
function renderPanelLayout(report: QuotaReport, theme: Theme): { sections: PanelSection[]; tail: string[] } {
|
|
921
|
+
const sections: PanelSection[] = [];
|
|
745
922
|
const active = report.providers.filter((provider) => provider.notConfigured !== true);
|
|
746
923
|
const unconfigured = report.providers.filter((provider) => provider.notConfigured === true);
|
|
747
924
|
const renderedFamilies = new Set<string>();
|
|
748
|
-
|
|
749
925
|
const partialScan = report.localStatsMeta?.partial === true;
|
|
926
|
+
|
|
750
927
|
for (const provider of active) {
|
|
751
928
|
const localStats = report.localStats?.[provider.family];
|
|
752
929
|
const labelWidth = Math.max(6, ...provider.windows.map((window) => String(window.label ?? "").length));
|
|
753
930
|
if (isMultiAccount(active, provider)) {
|
|
754
931
|
if (renderedFamilies.has(provider.family)) continue;
|
|
755
932
|
renderedFamilies.add(provider.family);
|
|
756
|
-
|
|
757
|
-
|
|
933
|
+
const rows = renderAccountRows(active.filter((other) => other.family === provider.family), theme, localStats);
|
|
934
|
+
sections.push({
|
|
935
|
+
key: `${provider.family}`,
|
|
936
|
+
header: rows[0] ?? paint(BRAND[provider.family] ?? "#8B949E", provider.label),
|
|
937
|
+
body: [...rows.slice(1), ...renderTokenRows(localStats, labelWidth, theme, partialScan)],
|
|
938
|
+
});
|
|
758
939
|
continue;
|
|
759
940
|
}
|
|
760
|
-
const
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
941
|
+
const lines = renderProviderLines(provider, theme, localStats, partialScan);
|
|
942
|
+
sections.push({ key: `${provider.family}:${provider.account}`, header: lines[0] ?? "", body: lines.slice(1) });
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
const tail: string[] = [];
|
|
946
|
+
// No timestamp here: the overlay header already says when the report landed
|
|
947
|
+
// ("updated HH:MM"), and a second format for the same fact reads as a
|
|
948
|
+
// different number to check. The pinned panel prints this line alone.
|
|
949
|
+
tail.push(theme.fg("dim", "used % · read-only"));
|
|
950
|
+
if (unconfigured.length > 0) {
|
|
951
|
+
const names = unconfigured.map((p) => SHORT_NAME[p.family] ?? p.family).join(", ");
|
|
952
|
+
tail.push(theme.fg("dim", `not configured in Pi: ${names}`));
|
|
953
|
+
}
|
|
954
|
+
for (const warning of report.warnings.slice(0, 3)) {
|
|
955
|
+
tail.push(theme.fg("warning", `warn: ${warning}`));
|
|
956
|
+
}
|
|
957
|
+
return { sections, tail };
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/** The flat panel: every section, then the footer, unconfigured names, warnings. */
|
|
961
|
+
function renderPanel(report: QuotaReport, theme: Theme): string[] {
|
|
962
|
+
const { sections, tail } = renderPanelLayout(report, theme);
|
|
963
|
+
return [...sections.flatMap((section) => [section.header, ...section.body]), ...tail];
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
/**
|
|
967
|
+
* Raw input sequences for the keys the overlay turns into actions. The
|
|
968
|
+
* extension ships as one file with no runtime dependencies, so this mirrors
|
|
969
|
+
* the subset of pi-tui's matchesKey() the overlay needs: arrows, paging and
|
|
970
|
+
* home/end in the encodings terminals and tmux actually send.
|
|
971
|
+
*/
|
|
972
|
+
const KEY_SEQUENCES: Record<string, string[]> = {
|
|
973
|
+
up: ["\u001b[A", "\u001bOA"],
|
|
974
|
+
down: ["\u001b[B", "\u001bOB"],
|
|
975
|
+
left: ["\u001b[D", "\u001bOD"],
|
|
976
|
+
right: ["\u001b[C", "\u001bOC"],
|
|
977
|
+
pageUp: ["\u001b[5~", "\u001b[[5~"],
|
|
978
|
+
pageDown: ["\u001b[6~", "\u001b[[6~"],
|
|
979
|
+
home: ["\u001b[H", "\u001bOH", "\u001b[1~", "\u001b[7~"],
|
|
980
|
+
end: ["\u001b[F", "\u001bOF", "\u001b[4~", "\u001b[8~"],
|
|
981
|
+
};
|
|
982
|
+
|
|
983
|
+
function isKey(data: string, name: string): boolean {
|
|
984
|
+
return (KEY_SEQUENCES[name] ?? []).includes(data);
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/** Pi reports the terminal height as a number; fall back to a usable frame. */
|
|
988
|
+
function terminalRows(value: number | undefined): number {
|
|
989
|
+
return Number.isFinite(value) ? Math.max(1, Math.floor(value as number)) : 24;
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
function clampScroll(value: number, max: number): number {
|
|
993
|
+
return Math.max(0, Math.min(value, max));
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/** One line with its label left and its status right, clipped to the width. */
|
|
997
|
+
function spreadLine(left: string, right: string, width: number): string {
|
|
998
|
+
if (right === "") return clipToWidth(left, width);
|
|
999
|
+
const rightText = clipToWidth(right, width);
|
|
1000
|
+
const leftText = clipToWidth(left, Math.max(0, width - visibleLength(rightText) - 1));
|
|
1001
|
+
const gap = Math.max(0, width - visibleLength(leftText) - visibleLength(rightText));
|
|
1002
|
+
return `${leftText}${" ".repeat(gap)}${rightText}`;
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
/** One content row of the overlay, with the section it belongs to. */
|
|
1006
|
+
type OverlayRow = { text: string; section: number; header: boolean };
|
|
1007
|
+
|
|
1008
|
+
/** One month of the durable history, as `piquota stats --json` returns it. */
|
|
1009
|
+
type HistoryPayload = {
|
|
1010
|
+
generatedAt?: string;
|
|
1011
|
+
months?: string[];
|
|
1012
|
+
quarantined?: string[];
|
|
1013
|
+
month?: string;
|
|
1014
|
+
days?: Record<string, Record<string, HistoryFamilyDay>>;
|
|
1015
|
+
totals?: HistoryTotals | null;
|
|
1016
|
+
notes?: string[];
|
|
1017
|
+
};
|
|
1018
|
+
|
|
1019
|
+
type HistoryFamilyDay = {
|
|
1020
|
+
sessions?: number;
|
|
1021
|
+
tokens?: number;
|
|
1022
|
+
prompts?: number;
|
|
1023
|
+
slots?: Record<string, HistorySlotDay>;
|
|
1024
|
+
};
|
|
1025
|
+
|
|
1026
|
+
type HistorySlotDay = {
|
|
1027
|
+
sessions?: number;
|
|
1028
|
+
tokens?: number;
|
|
1029
|
+
prompts?: number;
|
|
1030
|
+
models?: Record<string, { tokens?: number; messages?: number }>;
|
|
1031
|
+
};
|
|
1032
|
+
|
|
1033
|
+
type HistoryTotals = {
|
|
1034
|
+
lastFrozenDay?: string;
|
|
1035
|
+
families?: Record<string, HistoryTotalsFamily>;
|
|
1036
|
+
};
|
|
1037
|
+
|
|
1038
|
+
type HistoryTotalsModel = {
|
|
1039
|
+
input?: number;
|
|
1040
|
+
output?: number;
|
|
1041
|
+
cacheRead?: number;
|
|
1042
|
+
cacheWrite?: number;
|
|
1043
|
+
};
|
|
1044
|
+
|
|
1045
|
+
type HistoryTotalsFamily = {
|
|
1046
|
+
firstDay?: string;
|
|
1047
|
+
activeDates?: string[];
|
|
1048
|
+
totalPrompts?: number;
|
|
1049
|
+
totalSessions?: number;
|
|
1050
|
+
modelUsage?: Record<string, HistoryTotalsModel>;
|
|
1051
|
+
accounts?: Record<string, { totalPrompts?: number; totalSessions?: number; modelUsage?: Record<string, HistoryTotalsModel> }>;
|
|
1052
|
+
};
|
|
1053
|
+
|
|
1054
|
+
/** One family's month, aggregated from the payload and the live report. */
|
|
1055
|
+
type HistoryFamily = {
|
|
1056
|
+
tokens: number;
|
|
1057
|
+
prompts: number;
|
|
1058
|
+
days: Map<string, number>;
|
|
1059
|
+
models: Map<string, number>;
|
|
1060
|
+
accounts: Map<string, { tokens: number; prompts: number; models: Map<string, number> }>;
|
|
1061
|
+
allTime: number;
|
|
1062
|
+
allTimePrompts: number;
|
|
1063
|
+
allTimeAccounts: Map<string, { tokens: number; prompts: number }>;
|
|
1064
|
+
/** The live day's delta, added to both the month and the all-time figures. */
|
|
1065
|
+
liveTokens: number;
|
|
1066
|
+
livePrompts: number;
|
|
1067
|
+
liveAccounts: Map<string, { tokens: number; prompts: number }>;
|
|
1068
|
+
};
|
|
1069
|
+
|
|
1070
|
+
/** An all-time figure, and whether the rollup behind it lags the month on screen. */
|
|
1071
|
+
type AllTimeFigure = { value: number; lags: boolean };
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* The all-time figure for one scope. All time contains every frozen day, so it
|
|
1075
|
+
* can never be smaller than a month of it: a smaller rollup means totals.json is
|
|
1076
|
+
* behind the month file — a freeze whose totals write failed, a month restored
|
|
1077
|
+
* behind the rollup. That is printed, dimmed and with a note, never hidden: the
|
|
1078
|
+
* figure is the only answer to "how much has this burned ever", and dropping it
|
|
1079
|
+
* silently is a worse lie than a number with a caveat.
|
|
1080
|
+
*/
|
|
1081
|
+
function allTimeFigure(month: number, allTime: number): AllTimeFigure {
|
|
1082
|
+
if (allTime <= 0) return { value: 0, lags: false };
|
|
1083
|
+
return { value: allTime, lags: allTime < month };
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
/** The note printed with an all-time figure that cannot cover the month on screen. */
|
|
1087
|
+
const ALL_TIME_LAGS_NOTE = "all-time lags this month; run piquota stats --rebuild-totals";
|
|
1088
|
+
|
|
1089
|
+
/**
|
|
1090
|
+
* What outlives one overlay instance. Every bare `/usage` builds a fresh view,
|
|
1091
|
+
* so the folds and the page it was closed on live in the extension — for the pi
|
|
1092
|
+
* session only, and never on disk.
|
|
1093
|
+
*/
|
|
1094
|
+
type OverlaySession = {
|
|
1095
|
+
expanded: Map<string, boolean>;
|
|
1096
|
+
view: "now" | "history";
|
|
1097
|
+
month: string | null;
|
|
1098
|
+
};
|
|
1099
|
+
|
|
1100
|
+
function newOverlaySession(): OverlaySession {
|
|
1101
|
+
return { expanded: new Map(), view: "now", month: null };
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
/**
|
|
1105
|
+
* The History page's fetch state. "Not asked yet", "in flight" and "the last
|
|
1106
|
+
* fetch failed" are three different frames: the failed one must not also claim
|
|
1107
|
+
* to be loading.
|
|
1108
|
+
*/
|
|
1109
|
+
type HistoryStatus =
|
|
1110
|
+
| { kind: "idle" }
|
|
1111
|
+
| { kind: "loading"; month: string | null }
|
|
1112
|
+
| { kind: "failed"; month: string | null; message: string };
|
|
1113
|
+
|
|
1114
|
+
/**
|
|
1115
|
+
* One id per `stats --json` request, for the whole pi process: a reopened overlay
|
|
1116
|
+
* issues the next id, so an answer to a closed view's request can never be taken
|
|
1117
|
+
* for an answer to its own.
|
|
1118
|
+
*/
|
|
1119
|
+
let historyRequestSeq = 0;
|
|
1120
|
+
|
|
1121
|
+
type UsageOverlayOptions = {
|
|
1122
|
+
/** Close the overlay through the component's completion callback. */
|
|
1123
|
+
done: () => void;
|
|
1124
|
+
/** Ask the TUI for a frame after state changed. */
|
|
1125
|
+
requestRender: () => void;
|
|
1126
|
+
/** Current terminal height. */
|
|
1127
|
+
getRows: () => number;
|
|
1128
|
+
/** The newest report the extension holds, or null before the first one. */
|
|
1129
|
+
getReport: () => QuotaReport | null;
|
|
1130
|
+
/**
|
|
1131
|
+
* Every family's refresh failure, one line each, in family order. A failure
|
|
1132
|
+
* is not cleared by another family's success: the families finish out of
|
|
1133
|
+
* order, and a single shared slot made the last arrival erase the others.
|
|
1134
|
+
*/
|
|
1135
|
+
getErrors: () => string[];
|
|
1136
|
+
isRefreshing: () => boolean;
|
|
1137
|
+
/** Run the same forced refresh `/usage` always ran, in the background. */
|
|
1138
|
+
refresh: () => void;
|
|
1139
|
+
/**
|
|
1140
|
+
* Ask the extension to read one month in-process (null: current month). The
|
|
1141
|
+
* request id comes back with the answer, so a slow read cannot apply a month
|
|
1142
|
+
* the last keypress did not ask for.
|
|
1143
|
+
*/
|
|
1144
|
+
loadHistory: (month: string | null, request: number) => void;
|
|
1145
|
+
};
|
|
1146
|
+
|
|
1147
|
+
/** Display names for a family the current report does not mention. */
|
|
1148
|
+
const FAMILY_LABEL: Record<string, string> = {
|
|
1149
|
+
claude: "Claude (Pi)",
|
|
1150
|
+
codex: "Codex (Pi)",
|
|
1151
|
+
antigravity: "Antigravity (Pi)",
|
|
1152
|
+
"opencode-go": "OpenCode Go (Pi)",
|
|
1153
|
+
"github-actions": "GitHub Actions",
|
|
1154
|
+
};
|
|
1155
|
+
|
|
1156
|
+
/**
|
|
1157
|
+
* The key legend. Every key the current view answers appears here; a pair a
|
|
1158
|
+
* view does not answer (month navigation outside History) is not listed. The
|
|
1159
|
+
* legend wraps instead of dropping pairs, so a 60-column terminal still shows
|
|
1160
|
+
* every key; the close key stays last.
|
|
1161
|
+
*/
|
|
1162
|
+
const NOW_HINTS: ReadonlyArray<readonly [string, string]> = [
|
|
1163
|
+
["↑↓/jk", "move"],
|
|
1164
|
+
["enter/space/←→/hl", "fold"],
|
|
1165
|
+
["pgup/pgdn", "page"],
|
|
1166
|
+
["g/G home/end", "top/end"],
|
|
1167
|
+
["wheel", "scroll"],
|
|
1168
|
+
["r", "refresh"],
|
|
1169
|
+
["tab/1/2", "history"],
|
|
1170
|
+
["esc/q", "close"],
|
|
1171
|
+
];
|
|
1172
|
+
|
|
1173
|
+
const HISTORY_HINTS: ReadonlyArray<readonly [string, string]> = [
|
|
1174
|
+
["↑↓/jk", "move"],
|
|
1175
|
+
["enter/space/h/l", "fold"],
|
|
1176
|
+
["←/[", "prev month"],
|
|
1177
|
+
["]/→", "next month"],
|
|
1178
|
+
["pgup/pgdn", "page"],
|
|
1179
|
+
["g/G home/end", "top/end"],
|
|
1180
|
+
["wheel", "scroll"],
|
|
1181
|
+
["r", "refresh"],
|
|
1182
|
+
["tab/1/2", "now"],
|
|
1183
|
+
["esc/q", "close"],
|
|
1184
|
+
];
|
|
1185
|
+
|
|
1186
|
+
/** The report cache the CLI and in-process extension share. */
|
|
1187
|
+
function reportCachePath(): string {
|
|
1188
|
+
const cacheHome = process.env.XDG_CACHE_HOME || join(homedir(), ".cache");
|
|
1189
|
+
return join(cacheHome, "pi-quota", "usage.json");
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
/**
|
|
1193
|
+
* The last report on disk, read synchronously so the overlay paints on the same
|
|
1194
|
+
* keystroke as /usage: read-only, age is irrelevant for a first frame, and a
|
|
1195
|
+
* missing or malformed cache is simply "no cached report". The key travels back
|
|
1196
|
+
* with it because it names the Claude source those numbers came from, and a
|
|
1197
|
+
* later partial write has to keep describing the same data.
|
|
1198
|
+
*/
|
|
1199
|
+
function readCachedReport(): { report: QuotaReport; key: string | null } | null {
|
|
1200
|
+
try {
|
|
1201
|
+
const parsed = JSON.parse(readFileSync(reportCachePath(), "utf-8"));
|
|
1202
|
+
const report = parsed?.report;
|
|
1203
|
+
if (!report || !Array.isArray(report.providers)) return null;
|
|
1204
|
+
// The cache stores absolute reset instants; the surfaces paint countdowns.
|
|
1205
|
+
const now = Date.now();
|
|
1206
|
+
for (const provider of report.providers) {
|
|
1207
|
+
for (const window of provider.windows ?? []) {
|
|
1208
|
+
if (!window.resetsAt) continue;
|
|
1209
|
+
const resetsAtMs = Date.parse(window.resetsAt);
|
|
1210
|
+
if (!Number.isNaN(resetsAtMs)) window.resetsInSec = Math.max(0, Math.round((resetsAtMs - now) / 1000));
|
|
1211
|
+
}
|
|
771
1212
|
}
|
|
772
|
-
|
|
1213
|
+
return {
|
|
1214
|
+
report: report as QuotaReport,
|
|
1215
|
+
key: typeof parsed?.key === "string" ? parsed.key : null,
|
|
1216
|
+
};
|
|
1217
|
+
} catch {
|
|
1218
|
+
return null;
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
773
1221
|
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
1222
|
+
/** The update time shown once a refresh lands, as the clock time it happened. */
|
|
1223
|
+
function updatedAtLabel(report: QuotaReport): string {
|
|
1224
|
+
const at = new Date(report.generatedAt);
|
|
1225
|
+
if (Number.isNaN(at.getTime())) return "updated";
|
|
1226
|
+
return `updated ${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}`;
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
/**
|
|
1230
|
+
* Mask what must never reach a TUI frame or a scrollback. Mirrors
|
|
1231
|
+
* `src/http.js:redact` (this extension is one dependency-free file), and adds the
|
|
1232
|
+
* ANSI strip: a CLI's stderr can carry its own colour codes.
|
|
1233
|
+
*/
|
|
1234
|
+
function redactCause(value: string): string {
|
|
1235
|
+
return value
|
|
1236
|
+
.replace(/\u001b\[[0-9;]*m/g, "")
|
|
1237
|
+
.replace(/[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}/g, "<email>")
|
|
1238
|
+
.replace(/\beyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{4,}\b/g, "<jwt>")
|
|
1239
|
+
.replace(/\b(sk-[A-Za-z0-9_-]{6})[A-Za-z0-9_-]+/g, "$1<redacted>")
|
|
1240
|
+
.replace(/\b(ya29\.)[A-Za-z0-9_-]+/g, "$1<redacted>")
|
|
1241
|
+
.replace(/\b(1\/\/)[A-Za-z0-9_-]+/g, "$1<redacted>")
|
|
1242
|
+
.replace(/\b(rt\.[\w.]{4})[A-Za-z0-9_-]+/g, "$1<redacted>")
|
|
1243
|
+
.replace(/\b(Bearer\s+)[A-Za-z0-9._~+/-]+=*/gi, "$1<redacted>")
|
|
1244
|
+
.replace(/\b((?:__Host-console_session|auth)=)[^;\s]+/gi, "$1<redacted>");
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
/** A stderr line or a thrown message can quote a whole path list; the frame gets one line. */
|
|
1248
|
+
function capCause(cause: string): string {
|
|
1249
|
+
return cause.length > 160 ? `${cause.slice(0, 157)}…` : cause;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
/** Append warnings that are not already there: a repeated scan repeats its notes. */
|
|
1253
|
+
function mergeWarnings(existing: string[], added: string[] | undefined): string[] {
|
|
1254
|
+
const seen = new Set(existing);
|
|
1255
|
+
const merged = [...existing];
|
|
1256
|
+
for (const warning of added ?? []) {
|
|
1257
|
+
if (typeof warning !== "string" || warning === "" || seen.has(warning)) continue;
|
|
1258
|
+
seen.add(warning);
|
|
1259
|
+
merged.push(warning);
|
|
1260
|
+
}
|
|
1261
|
+
return merged;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
/** Local YYYY-MM-DD, the history's day key. */
|
|
1265
|
+
function localDayKey(now = new Date()): string {
|
|
1266
|
+
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
/** Local YYYY-MM, the history's month key. */
|
|
1270
|
+
function localMonthKey(now = new Date()): string {
|
|
1271
|
+
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
/** Tokens in one compact history model bucket. */
|
|
1275
|
+
function historyModelTokens(bucket: { tokens?: number } | undefined): number {
|
|
1276
|
+
return Math.max(0, Math.round(Number(bucket?.tokens) || 0));
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
/** Tokens in one totals.json model bucket (the rollup's short keys). */
|
|
1280
|
+
function totalsModelTokens(bucket: HistoryTotalsModel | undefined): number {
|
|
1281
|
+
const values = [bucket?.input, bucket?.output, bucket?.cacheRead, bucket?.cacheWrite];
|
|
1282
|
+
return values.reduce((sum, value) => sum + Math.max(0, Math.round(Number(value) || 0)), 0);
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
/** Slot labels sort "" (the unnumbered base) first, then #2, #3 … #10 numerically. */
|
|
1286
|
+
function slotOrder(label: string): number {
|
|
1287
|
+
if (label === "") return -1;
|
|
1288
|
+
const numeric = Number.parseInt(label.replace(/^#/, ""), 10);
|
|
1289
|
+
return Number.isFinite(numeric) ? numeric : Number.MAX_SAFE_INTEGER;
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
/**
|
|
1293
|
+
* Greedy wrap of " · "-joined cells: the first line carries the label, the
|
|
1294
|
+
* continuation lines are indented under it, and no cell is dropped.
|
|
1295
|
+
*/
|
|
1296
|
+
function wrapCells(cells: string[], first: string, rest: string, width: number): string[] {
|
|
1297
|
+
const lines: string[] = [];
|
|
1298
|
+
let current = first;
|
|
1299
|
+
let count = 0;
|
|
1300
|
+
for (const cell of cells) {
|
|
1301
|
+
const separator = count === 0 ? "" : " · ";
|
|
1302
|
+
if (count > 0 && visibleLength(current) + separator.length + visibleLength(cell) > width) {
|
|
1303
|
+
lines.push(current);
|
|
1304
|
+
current = rest + cell;
|
|
1305
|
+
count = 1;
|
|
1306
|
+
continue;
|
|
1307
|
+
}
|
|
1308
|
+
current += separator + cell;
|
|
1309
|
+
count += 1;
|
|
1310
|
+
}
|
|
1311
|
+
lines.push(count > 0 ? current : first.trimEnd());
|
|
1312
|
+
return lines;
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
/**
|
|
1316
|
+
* Split `count` cells into the fewest rows that fit `width`, then even them out.
|
|
1317
|
+
*
|
|
1318
|
+
* Greedy filling is the row count; a second pass picks, among all splits into
|
|
1319
|
+
* that many rows, the one whose widest row is the narrowest. That is what turns
|
|
1320
|
+
* a 7+1 legend into 4+4 without ever adding a row or dropping a pair.
|
|
1321
|
+
*
|
|
1322
|
+
* @returns the number of cells on each row.
|
|
1323
|
+
*/
|
|
1324
|
+
function balanceRows(lengths: number[], width: number, separator: number): number[] {
|
|
1325
|
+
const count = lengths.length;
|
|
1326
|
+
if (count === 0) return [];
|
|
1327
|
+
const prefix: number[] = [0];
|
|
1328
|
+
for (const length of lengths) prefix.push(prefix[prefix.length - 1] + length);
|
|
1329
|
+
const cost = (from: number, to: number) => prefix[to] - prefix[from] + separator * (to - from - 1);
|
|
1330
|
+
|
|
1331
|
+
let rows = 1;
|
|
1332
|
+
let used = lengths[0];
|
|
1333
|
+
for (let index = 1; index < count; index += 1) {
|
|
1334
|
+
if (used + separator + lengths[index] <= width) used += separator + lengths[index];
|
|
1335
|
+
else {
|
|
1336
|
+
rows += 1;
|
|
1337
|
+
used = lengths[index];
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
if (rows <= 1) return [count];
|
|
1341
|
+
|
|
1342
|
+
// best[i][r]: the narrowest possible widest row for cells[i..] in exactly r rows.
|
|
1343
|
+
const best: number[][] = Array.from({ length: count + 1 }, () => Array(rows + 1).fill(Number.POSITIVE_INFINITY));
|
|
1344
|
+
best[count][0] = 0;
|
|
1345
|
+
for (let remaining = 1; remaining <= rows; remaining += 1) {
|
|
1346
|
+
for (let from = count - 1; from >= 0; from -= 1) {
|
|
1347
|
+
for (let take = 1; take <= count - from - (remaining - 1); take += 1) {
|
|
1348
|
+
const rest = best[from + take][remaining - 1];
|
|
1349
|
+
if (rest === Number.POSITIVE_INFINITY) continue;
|
|
1350
|
+
const widest = Math.max(cost(from, from + take), rest);
|
|
1351
|
+
if (widest < best[from][remaining]) best[from][remaining] = widest;
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
const counts: number[] = [];
|
|
1357
|
+
let from = 0;
|
|
1358
|
+
for (let remaining = rows; remaining > 0; remaining -= 1) {
|
|
1359
|
+
let chosen = 1;
|
|
1360
|
+
for (let take = 1; take <= count - from - (remaining - 1); take += 1) {
|
|
1361
|
+
const rest = best[from + take][remaining - 1];
|
|
1362
|
+
if (rest === Number.POSITIVE_INFINITY) continue;
|
|
1363
|
+
if (Math.max(cost(from, from + take), rest) === best[from][remaining]) {
|
|
1364
|
+
chosen = take;
|
|
1365
|
+
break;
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
counts.push(chosen);
|
|
1369
|
+
from += chosen;
|
|
1370
|
+
}
|
|
1371
|
+
return counts;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/**
|
|
1375
|
+
* The focused `/usage` view: two fullscreen pages the keyboard owns.
|
|
1376
|
+
*
|
|
1377
|
+
* Now is the panel, one collapsible section per provider, with a header cursor,
|
|
1378
|
+
* scrolling and a key legend. History is the durable token history for one
|
|
1379
|
+
* month, the same sections folded the same way, with ←/→ walking the months
|
|
1380
|
+
* that have a file. It reads the report, the error and the loaded month through
|
|
1381
|
+
* callbacks, so a background refresh only has to call redraw(); the view holds
|
|
1382
|
+
* no timer and no disk state.
|
|
1383
|
+
*/
|
|
1384
|
+
export class UsageOverlay {
|
|
1385
|
+
private readonly theme: Theme;
|
|
1386
|
+
private readonly options: UsageOverlayOptions;
|
|
1387
|
+
/** Fold state and the page, shared with the next view for this pi session. */
|
|
1388
|
+
private readonly session: OverlaySession;
|
|
1389
|
+
private cursor = 0;
|
|
1390
|
+
private scroll = 0;
|
|
1391
|
+
private disposed = false;
|
|
1392
|
+
/** Months the CLI says are browsable, newest last. */
|
|
1393
|
+
private historyMonths: string[] = [];
|
|
1394
|
+
/** One loaded month per month key, kept for the lifetime of this overlay. */
|
|
1395
|
+
private readonly historyCache = new Map<string, HistoryPayload>();
|
|
1396
|
+
/** Whether History is idle, loading a month, or showing a failed fetch. */
|
|
1397
|
+
private historyStatus: HistoryStatus = { kind: "idle" };
|
|
1398
|
+
/**
|
|
1399
|
+
* Id of the newest `stats --json` request this view issued. ←/→ fire
|
|
1400
|
+
* overlapping fetches; only the newest answer may move the page.
|
|
1401
|
+
*/
|
|
1402
|
+
private historyWanted = 0;
|
|
1403
|
+
/** Width of the last frame; history rows are wrapped for it. */
|
|
1404
|
+
private measureWidth = 80;
|
|
1405
|
+
private cachedLayout: { sections: PanelSection[]; tail: string[] } | null | undefined;
|
|
1406
|
+
private cachedLayoutWidth: number | undefined;
|
|
1407
|
+
private cachedMetrics: { rows: OverlayRow[]; headerRows: number[]; sectionEnds: number[] } | undefined;
|
|
1408
|
+
private cachedMetricsWidth: number | undefined;
|
|
1409
|
+
private cachedWidth: number | undefined;
|
|
1410
|
+
private cachedRows: number | undefined;
|
|
1411
|
+
private cachedLines: string[] | undefined;
|
|
1412
|
+
/** Legend rows the last frame needed; the viewport height depends on it. */
|
|
1413
|
+
private legendRows = 1;
|
|
1414
|
+
|
|
1415
|
+
constructor(theme: Theme, options: UsageOverlayOptions, session: OverlaySession = newOverlaySession()) {
|
|
1416
|
+
this.theme = theme;
|
|
1417
|
+
this.options = options;
|
|
1418
|
+
this.session = session;
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
/** The fold map shared with the next view, so a reopen keeps every fold. */
|
|
1422
|
+
private get expanded(): Map<string, boolean> {
|
|
1423
|
+
return this.session.expanded;
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
private get view(): "now" | "history" {
|
|
1427
|
+
return this.session.view;
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
private set view(value: "now" | "history") {
|
|
1431
|
+
this.session.view = value;
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
/** The month shown in History; null until a payload names one. */
|
|
1435
|
+
private get selectedMonth(): string | null {
|
|
1436
|
+
return this.session.month;
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
private set selectedMonth(value: string | null) {
|
|
1440
|
+
this.session.month = value;
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
/**
|
|
1444
|
+
* Load what a reopened view needs: a page that was closed on History has no
|
|
1445
|
+
* payload in its fresh cache, and its month must not render as empty.
|
|
1446
|
+
*/
|
|
1447
|
+
public begin(): void {
|
|
1448
|
+
if (this.disposed || this.view !== "history") return;
|
|
1449
|
+
if (this.selectedMonth !== null && this.historyCache.has(this.selectedMonth)) return;
|
|
1450
|
+
this.requestMonth(this.selectedMonth);
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
/** Drop cached rows and frames; the next render rebuilds from live state. */
|
|
1454
|
+
public invalidate(): void {
|
|
1455
|
+
this.cachedLayout = undefined;
|
|
1456
|
+
this.cachedLayoutWidth = undefined;
|
|
1457
|
+
this.cachedMetrics = undefined;
|
|
1458
|
+
this.cachedMetricsWidth = undefined;
|
|
1459
|
+
this.cachedWidth = undefined;
|
|
1460
|
+
this.cachedRows = undefined;
|
|
1461
|
+
this.cachedLines = undefined;
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
/** Re-render after the extension's background refresh landed. */
|
|
1465
|
+
public redraw(): void {
|
|
1466
|
+
if (this.disposed) return;
|
|
1467
|
+
this.invalidate();
|
|
1468
|
+
this.options.requestRender();
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
/** Stop drawing once the overlay closed, however it closed. */
|
|
1472
|
+
public dispose(): void {
|
|
1473
|
+
this.disposed = true;
|
|
1474
|
+
this.invalidate();
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
/**
|
|
1478
|
+
* Ask for one month (null: the newest with a file) and remember the request
|
|
1479
|
+
* id, so the answer can be matched against the last keypress rather than the
|
|
1480
|
+
* order the CLI happened to finish in.
|
|
1481
|
+
*/
|
|
1482
|
+
private requestMonth(month: string | null): void {
|
|
1483
|
+
// The counter lives in the module, not on the view: a reopened overlay must
|
|
1484
|
+
// not reuse an id, or an answer to the closed view's request would pass for
|
|
1485
|
+
// an answer to its own.
|
|
1486
|
+
historyRequestSeq += 1;
|
|
1487
|
+
this.historyWanted = historyRequestSeq;
|
|
1488
|
+
this.historyStatus = { kind: "loading", month };
|
|
1489
|
+
this.options.loadHistory(month, this.historyWanted);
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
/**
|
|
1493
|
+
* A month (or the first payload, with the month list) arrived from the in-process reader.
|
|
1494
|
+
* Every answer is cached — a later ← must not refetch what already arrived —
|
|
1495
|
+
* but only the answer to the newest request may move the page: ←/→ overlap,
|
|
1496
|
+
* and a late answer for a month the last keypress did not ask for used to snap
|
|
1497
|
+
* the page back and skip a month.
|
|
1498
|
+
*/
|
|
1499
|
+
public setHistory(payload: HistoryPayload, request?: number): void {
|
|
1500
|
+
if (this.disposed) return;
|
|
1501
|
+
if (Array.isArray(payload.months)) {
|
|
1502
|
+
this.historyMonths = payload.months.filter((month) => /^\d{4}-\d{2}$/.test(month));
|
|
1503
|
+
}
|
|
1504
|
+
const month = typeof payload.month === "string" && /^\d{4}-\d{2}$/.test(payload.month) ? payload.month : null;
|
|
1505
|
+
if (month !== null) this.historyCache.set(month, payload);
|
|
1506
|
+
// The newest request answered, so nothing is loading any more. It moves the
|
|
1507
|
+
// page only if the page still asks for that month: a newer keypress may have
|
|
1508
|
+
// left it, and the late answer then only fills the cache.
|
|
1509
|
+
if (request === undefined || request === this.historyWanted) {
|
|
1510
|
+
if (month !== null && (this.selectedMonth === null || month === this.selectedMonth)) this.selectedMonth = month;
|
|
1511
|
+
this.historyStatus = { kind: "idle" };
|
|
1512
|
+
}
|
|
1513
|
+
this.invalidate();
|
|
1514
|
+
this.options.requestRender();
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
/** The history fetch failed: a line in the view, never a thrown error. */
|
|
1518
|
+
public setHistoryError(message: string, request?: number): void {
|
|
1519
|
+
if (this.disposed) return;
|
|
1520
|
+
// A failure that answers an older request must not paint over the month the
|
|
1521
|
+
// user is on now: its own request (or its cached payload) owns the frame.
|
|
1522
|
+
if (request !== undefined && request !== this.historyWanted) return;
|
|
1523
|
+
// Keep the month the failed fetch was for: a retry must ask for that month,
|
|
1524
|
+
// and the frame must say "failed" rather than "loading".
|
|
1525
|
+
const month = this.historyStatus.kind === "loading" ? this.historyStatus.month : this.selectedMonth;
|
|
1526
|
+
this.historyStatus = { kind: "failed", month, message };
|
|
1527
|
+
this.invalidate();
|
|
1528
|
+
this.options.requestRender();
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
/** Handle one raw key: switch view, fold, move, month, refresh, close. */
|
|
1532
|
+
public handleInput(data: string): void {
|
|
1533
|
+
if (this.disposed) return;
|
|
1534
|
+
if (data === "\u001b" || data === "q") {
|
|
1535
|
+
this.dispose();
|
|
1536
|
+
this.options.done();
|
|
1537
|
+
return;
|
|
1538
|
+
}
|
|
1539
|
+
if (data === "\t" || data === "1" || data === "2") {
|
|
1540
|
+
const target = data === "1" ? "now" : data === "2" ? "history" : this.view === "now" ? "history" : "now";
|
|
1541
|
+
this.switchView(target);
|
|
1542
|
+
this.invalidate();
|
|
1543
|
+
return;
|
|
1544
|
+
}
|
|
1545
|
+
if (data === "r") {
|
|
1546
|
+
// History's today row comes from the live report, so a refresh there
|
|
1547
|
+
// reloads the month and the report together; one key, one meaning.
|
|
1548
|
+
if (this.view === "history") this.reloadMonth();
|
|
1549
|
+
this.options.refresh();
|
|
1550
|
+
this.invalidate();
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
if (isKey(data, "up") || data === "k") this.moveCursor(-1);
|
|
1554
|
+
else if (isKey(data, "down") || data === "j") this.moveCursor(1);
|
|
1555
|
+
else if (data === "\r" || data === "\n" || data === " ") this.toggleSection();
|
|
1556
|
+
else if (isKey(data, "pageUp")) this.page(-1);
|
|
1557
|
+
else if (isKey(data, "pageDown")) this.page(1);
|
|
1558
|
+
else if (isKey(data, "home") || data === "g") this.jumpTo(0);
|
|
1559
|
+
else if (isKey(data, "end") || data === "G") this.jumpTo(-1);
|
|
1560
|
+
else if (this.view === "history" && (isKey(data, "left") || data === "[")) this.moveMonth(-1);
|
|
1561
|
+
else if (this.view === "history" && (isKey(data, "right") || data === "]")) this.moveMonth(1);
|
|
1562
|
+
else if (isKey(data, "left") || data === "h") this.setExpanded(false);
|
|
1563
|
+
else if (isKey(data, "right") || data === "l") this.setExpanded(true);
|
|
1564
|
+
else return;
|
|
1565
|
+
// The TUI renders the component again after every key, so the cached frame
|
|
1566
|
+
// and the cached row map must be dropped here, not only on report changes.
|
|
1567
|
+
this.invalidate();
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
/**
|
|
1571
|
+
* Wheel notches scroll the body; every other mouse event stays with pi.
|
|
1572
|
+
*
|
|
1573
|
+
* pi's TUI routes fullscreen wheel events to the focused component but offers
|
|
1574
|
+
* no scrolling API for a custom screen: unhandled notches only move a
|
|
1575
|
+
* ScrollView, and this extension ships as one dependency-free file that
|
|
1576
|
+
* cannot import one. So the wheel is handled here, exactly as pi-context-view
|
|
1577
|
+
* does (one notch = wheelDelta lines, undefined for every other event).
|
|
1578
|
+
*/
|
|
1579
|
+
public handleMouse(event: { type?: string; wheelDelta?: number }): { handled: true; render: boolean } | undefined {
|
|
1580
|
+
if (this.disposed || event?.type !== "wheel" || !event.wheelDelta) return undefined;
|
|
1581
|
+
const before = this.scroll;
|
|
1582
|
+
this.scroll = clampScroll(this.scroll + event.wheelDelta, this.maxScroll());
|
|
1583
|
+
if (this.scroll === before) return { handled: true, render: false };
|
|
1584
|
+
this.invalidate();
|
|
1585
|
+
this.syncCursor();
|
|
1586
|
+
return { handled: true, render: true };
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
/** Render one fullscreen frame for the given width and terminal height. */
|
|
1590
|
+
public render(width: number): string[] {
|
|
1591
|
+
const rows = terminalRows(this.options.getRows());
|
|
1592
|
+
if (this.cachedLines && this.cachedWidth === width && this.cachedRows === rows) return this.cachedLines;
|
|
1593
|
+
|
|
1594
|
+
this.measureWidth = width;
|
|
1595
|
+
// The legend wraps, so its row count depends on the width: it is measured
|
|
1596
|
+
// before the viewport is cut, and the frame reserves exactly those rows.
|
|
1597
|
+
const legend = this.legendLines(width);
|
|
1598
|
+
this.legendRows = legend.length;
|
|
1599
|
+
const { rows: content } = this.metrics();
|
|
1600
|
+
const height = Math.max(1, rows - this.frameRows());
|
|
1601
|
+
this.scroll = clampScroll(this.scroll, Math.max(0, content.length - height));
|
|
1602
|
+
|
|
1603
|
+
const viewport: string[] = [];
|
|
1604
|
+
for (const row of content.slice(this.scroll, this.scroll + height)) {
|
|
1605
|
+
const text = row.header ? `${row.section === this.cursor ? "❯" : " "} ${row.text}` : row.text;
|
|
1606
|
+
viewport.push(clipToWidth(text, width));
|
|
1607
|
+
}
|
|
1608
|
+
while (viewport.length < height) viewport.push("");
|
|
1609
|
+
|
|
1610
|
+
const title = this.titleLine();
|
|
1611
|
+
const frame = [spreadLine(title, this.statusText(content.length, height), width), "", ...viewport, "", ...legend];
|
|
1612
|
+
while (frame.length < rows) frame.push("");
|
|
1613
|
+
this.cachedWidth = width;
|
|
1614
|
+
this.cachedRows = rows;
|
|
1615
|
+
this.cachedLines = frame.slice(0, rows);
|
|
1616
|
+
return this.cachedLines;
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
/** Rows the frame spends around the scrolling content: title, two blanks, legend. */
|
|
1620
|
+
private frameRows(): number {
|
|
1621
|
+
return 3 + Math.max(1, this.legendRows);
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
/** Visible content height, excluding the fixed frame rows. */
|
|
1625
|
+
private viewportHeight(): number {
|
|
1626
|
+
return Math.max(1, terminalRows(this.options.getRows()) - this.frameRows());
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
private maxScroll(): number {
|
|
1630
|
+
return Math.max(0, this.metrics().rows.length - this.viewportHeight());
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
private isExpanded(key: string): boolean {
|
|
1634
|
+
return this.expanded.get(key) ?? true;
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
/** The report split into its foldable sections; null while the first load runs. */
|
|
1638
|
+
private layout(): { sections: PanelSection[]; tail: string[] } | null {
|
|
1639
|
+
if (this.cachedLayout !== undefined && this.cachedLayoutWidth === this.measureWidth) return this.cachedLayout;
|
|
1640
|
+
this.cachedLayoutWidth = this.measureWidth;
|
|
1641
|
+
this.cachedLayout = this.view === "history" ? this.historyLayout(this.measureWidth) : this.nowLayout();
|
|
1642
|
+
return this.cachedLayout;
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
/** The Now page: the exactly same sections the pinned panel renders flat. */
|
|
1646
|
+
private nowLayout(): { sections: PanelSection[]; tail: string[] } | null {
|
|
1647
|
+
const report = this.options.getReport();
|
|
1648
|
+
return report ? renderPanelLayout(report, this.theme) : null;
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
/** Flattened rows, plus where every section's header starts and ends. */
|
|
1652
|
+
private metrics(): { rows: OverlayRow[]; headerRows: number[]; sectionEnds: number[] } {
|
|
1653
|
+
if (this.cachedMetrics && this.cachedMetricsWidth === this.measureWidth) return this.cachedMetrics;
|
|
1654
|
+
this.cachedMetricsWidth = this.measureWidth;
|
|
1655
|
+
const rows: OverlayRow[] = [];
|
|
1656
|
+
const headerRows: number[] = [];
|
|
1657
|
+
const sectionEnds: number[] = [];
|
|
1658
|
+
const layout = this.layout();
|
|
1659
|
+
if (this.view === "history") {
|
|
1660
|
+
const failure = this.historyFailure();
|
|
1661
|
+
if (failure !== null) {
|
|
1662
|
+
// With a month on screen the error is a line above it, so it carries the
|
|
1663
|
+
// retry hint itself; the no-payload state says it on the line below.
|
|
1664
|
+
const hint = layout ? ` ${this.theme.fg("dim", "· press r to retry")}` : "";
|
|
1665
|
+
// A CLI's stderr line is longer than a pane: wrapped, so neither the
|
|
1666
|
+
// cause nor the hint is lost to the right edge.
|
|
1667
|
+
this.pushRow(rows, ` ${this.theme.fg("error", `! ${failure}`)}${hint}`, -1, false);
|
|
1668
|
+
}
|
|
783
1669
|
} else {
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
1670
|
+
for (const error of this.options.getErrors()) {
|
|
1671
|
+
rows.push({ text: ` ${this.theme.fg("error", `! ${error}`)}`, section: -1, header: false });
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
if (!layout) {
|
|
1675
|
+
// Distinct states, distinct lines: a failed fetch used to say "loading
|
|
1676
|
+
// history …" under its own error, which reads as a spinner that never ends.
|
|
1677
|
+
const status = this.historyStatus;
|
|
1678
|
+
const label = this.view !== "history"
|
|
1679
|
+
? "loading quota …"
|
|
1680
|
+
: status.kind === "loading"
|
|
1681
|
+
? status.month === null
|
|
1682
|
+
? "loading history …"
|
|
1683
|
+
: `loading ${status.month} …`
|
|
1684
|
+
: status.kind === "failed"
|
|
1685
|
+
? "no history for this month; press r to retry"
|
|
1686
|
+
: "loading history …";
|
|
1687
|
+
rows.push({ text: ` ${this.theme.fg("dim", label)}`, section: -1, header: false });
|
|
1688
|
+
} else {
|
|
1689
|
+
layout.sections.forEach((section, index) => {
|
|
1690
|
+
const open = this.isExpanded(section.key);
|
|
1691
|
+
headerRows.push(rows.length);
|
|
1692
|
+
this.pushRow(rows, `${open ? "▾" : "▸"} ${section.header}`, index, true);
|
|
1693
|
+
if (open) for (const line of section.body) this.pushRow(rows, ` ${line}`, index, false);
|
|
1694
|
+
sectionEnds.push(rows.length - 1);
|
|
1695
|
+
});
|
|
1696
|
+
for (const line of layout.tail) this.pushRow(rows, ` ${line}`, -1, false);
|
|
1697
|
+
}
|
|
1698
|
+
this.cursor = Math.max(0, Math.min(this.cursor, Math.max(0, headerRows.length - 1)));
|
|
1699
|
+
this.cachedMetrics = { rows, headerRows, sectionEnds };
|
|
1700
|
+
return this.cachedMetrics;
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
/**
|
|
1704
|
+
* Append one content row, wrapped to the measured width. The cursor marker and
|
|
1705
|
+
* the body indent are two columns the wrap budget must leave room for, and a
|
|
1706
|
+
* wrapped header's continuation rows are body rows of the same section, so the
|
|
1707
|
+
* header indexes the cursor walks do not shift.
|
|
1708
|
+
*/
|
|
1709
|
+
private pushRow(rows: OverlayRow[], text: string, section: number, header: boolean): void {
|
|
1710
|
+
const width = Math.max(8, this.measureWidth - (header ? 2 : 0));
|
|
1711
|
+
const parts = wrapLine(text, width);
|
|
1712
|
+
rows.push({ text: parts[0], section, header });
|
|
1713
|
+
for (const part of parts.slice(1)) rows.push({ text: header ? ` ${part}` : part, section, header: false });
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
/** Walk the headers; a section taller than the viewport scrolls first. */
|
|
1717
|
+
private moveCursor(delta: -1 | 1): void {
|
|
1718
|
+
const { headerRows, sectionEnds } = this.metrics();
|
|
1719
|
+
if (headerRows.length === 0) return;
|
|
1720
|
+
const height = this.viewportHeight();
|
|
1721
|
+
const section = this.layout()?.sections[this.cursor];
|
|
1722
|
+
const open = section !== undefined && this.isExpanded(section.key);
|
|
1723
|
+
const end = sectionEnds[this.cursor] ?? 0;
|
|
1724
|
+
if (delta > 0 && open && end > this.scroll + height - 1) {
|
|
1725
|
+
this.scroll = clampScroll(this.scroll + 1, this.maxScroll());
|
|
1726
|
+
return;
|
|
1727
|
+
}
|
|
1728
|
+
if (delta < 0 && open && headerRows[this.cursor] < this.scroll) {
|
|
1729
|
+
this.scroll = clampScroll(this.scroll - 1, this.maxScroll());
|
|
1730
|
+
return;
|
|
1731
|
+
}
|
|
1732
|
+
const next = this.cursor + delta;
|
|
1733
|
+
if (next < 0 || next >= headerRows.length) {
|
|
1734
|
+
this.scroll = clampScroll(this.scroll + delta, this.maxScroll());
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
this.cursor = next;
|
|
1738
|
+
this.reveal();
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
/** Scroll the cursor's header into view; a tall section starts at its header. */
|
|
1742
|
+
private reveal(): void {
|
|
1743
|
+
const { headerRows, sectionEnds } = this.metrics();
|
|
1744
|
+
const height = this.viewportHeight();
|
|
1745
|
+
const top = headerRows[this.cursor] ?? 0;
|
|
1746
|
+
const bottom = sectionEnds[this.cursor] ?? top;
|
|
1747
|
+
if (top < this.scroll || bottom > this.scroll + height - 1) this.scroll = top;
|
|
1748
|
+
this.scroll = clampScroll(this.scroll, this.maxScroll());
|
|
1749
|
+
}
|
|
1750
|
+
|
|
1751
|
+
/**
|
|
1752
|
+
* Page the body. When nothing can scroll the keystroke does nothing: paging
|
|
1753
|
+
* used to re-snap the cursor to the last on-screen header, so PgUp on a short
|
|
1754
|
+
* page moved the selection *down*.
|
|
1755
|
+
*/
|
|
1756
|
+
private page(delta: -1 | 1): void {
|
|
1757
|
+
const before = this.scroll;
|
|
1758
|
+
this.scroll = clampScroll(this.scroll + delta * this.viewportHeight(), this.maxScroll());
|
|
1759
|
+
this.invalidate();
|
|
1760
|
+
if (this.scroll !== before) this.syncCursor();
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
private jumpTo(index: 0 | -1): void {
|
|
1764
|
+
const { headerRows } = this.metrics();
|
|
1765
|
+
if (headerRows.length === 0) {
|
|
1766
|
+
this.scroll = index === 0 ? 0 : this.maxScroll();
|
|
1767
|
+
return;
|
|
1768
|
+
}
|
|
1769
|
+
this.cursor = index === 0 ? 0 : headerRows.length - 1;
|
|
1770
|
+
this.scroll = index === 0 ? 0 : this.maxScroll();
|
|
1771
|
+
const top = headerRows[this.cursor] ?? 0;
|
|
1772
|
+
if (top < this.scroll) this.scroll = top;
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
/**
|
|
1776
|
+
* Keep the cursor on the header nearest the one it was on that is still on
|
|
1777
|
+
* screen. The last visible header is the wrong pick: scrolling a little used
|
|
1778
|
+
* to throw the selection to the bottom of the page. When no header is on
|
|
1779
|
+
* screen the cursor stays put, so scrolling back returns to it.
|
|
1780
|
+
*/
|
|
1781
|
+
private syncCursor(): void {
|
|
1782
|
+
const { headerRows } = this.metrics();
|
|
1783
|
+
if (headerRows.length === 0) return;
|
|
1784
|
+
const bottom = this.scroll + this.viewportHeight() - 1;
|
|
1785
|
+
let best: number | null = null;
|
|
1786
|
+
for (let index = 0; index < headerRows.length; index += 1) {
|
|
1787
|
+
const row = headerRows[index];
|
|
1788
|
+
if (row < this.scroll || row > bottom) continue;
|
|
1789
|
+
if (best === null || Math.abs(index - this.cursor) < Math.abs(best - this.cursor)) best = index;
|
|
1790
|
+
}
|
|
1791
|
+
if (best !== null) this.cursor = best;
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
private toggleSection(): void {
|
|
1795
|
+
const section = this.layout()?.sections[this.cursor];
|
|
1796
|
+
if (!section) return;
|
|
1797
|
+
this.setExpanded(!this.isExpanded(section.key));
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
private setExpanded(open: boolean): void {
|
|
1801
|
+
const section = this.layout()?.sections[this.cursor];
|
|
1802
|
+
if (!section || this.isExpanded(section.key) === open) return;
|
|
1803
|
+
this.expanded.set(section.key, open);
|
|
1804
|
+
this.invalidate();
|
|
1805
|
+
this.reveal();
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
private switchView(view: "now" | "history"): void {
|
|
1809
|
+
if (this.view === view) return;
|
|
1810
|
+
this.view = view;
|
|
1811
|
+
this.cursor = 0;
|
|
1812
|
+
this.scroll = 0;
|
|
1813
|
+
if (view === "history" && this.historyStatus.kind === "idle" && this.historyCache.size === 0) {
|
|
1814
|
+
this.requestMonth(this.selectedMonth);
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
|
|
1818
|
+
/** ←/→ (or [ and ]) walk only the months that actually have a file. */
|
|
1819
|
+
private moveMonth(delta: -1 | 1): void {
|
|
1820
|
+
const months = this.historyMonths;
|
|
1821
|
+
if (months.length === 0) return;
|
|
1822
|
+
const current = this.selectedMonth;
|
|
1823
|
+
let target: string | null;
|
|
1824
|
+
if (current === null) {
|
|
1825
|
+
target = delta > 0 ? months[0] : months[months.length - 1];
|
|
1826
|
+
} else if (delta < 0) {
|
|
1827
|
+
target = [...months].reverse().find((month) => month < current) ?? null;
|
|
1828
|
+
} else {
|
|
1829
|
+
target = months.find((month) => month > current) ?? null;
|
|
1830
|
+
}
|
|
1831
|
+
if (target === null) return;
|
|
1832
|
+
this.selectMonth(target);
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
private selectMonth(month: string): void {
|
|
1836
|
+
this.selectedMonth = month;
|
|
1837
|
+
this.cursor = 0;
|
|
1838
|
+
this.scroll = 0;
|
|
1839
|
+
if (!this.historyCache.has(month)) this.requestMonth(month);
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
private reloadMonth(): void {
|
|
1843
|
+
this.requestMonth(this.selectedMonth);
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
/**
|
|
1847
|
+
* The failure line for the month on screen, or null. A fetch that failed for a
|
|
1848
|
+
* month the user has since left must not paint over the page they are on, and
|
|
1849
|
+
* its "press r to retry" would retry the wrong month.
|
|
1850
|
+
*/
|
|
1851
|
+
private historyFailure(): string | null {
|
|
1852
|
+
const status = this.historyStatus;
|
|
1853
|
+
if (status.kind !== "failed") return null;
|
|
1854
|
+
if (this.selectedMonth === null || status.month === null || status.month === this.selectedMonth) return status.message;
|
|
1855
|
+
return null;
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
/** The History page: one section per family, days, models, accounts, totals. */
|
|
1859
|
+
private historyLayout(width: number): { sections: PanelSection[]; tail: string[] } | null {
|
|
1860
|
+
const month = this.selectedMonth;
|
|
1861
|
+
if (month === null) return null;
|
|
1862
|
+
const payload = this.historyCache.get(month);
|
|
1863
|
+
if (!payload) return null;
|
|
1864
|
+
|
|
1865
|
+
/** @type {Map<string, HistoryFamily>} */
|
|
1866
|
+
const families = new Map<string, HistoryFamily>();
|
|
1867
|
+
const ensure = (family: string): HistoryFamily => {
|
|
1868
|
+
let entry = families.get(family);
|
|
1869
|
+
if (!entry) {
|
|
1870
|
+
entry = {
|
|
1871
|
+
tokens: 0,
|
|
1872
|
+
prompts: 0,
|
|
1873
|
+
days: new Map(),
|
|
1874
|
+
models: new Map(),
|
|
1875
|
+
accounts: new Map(),
|
|
1876
|
+
allTime: 0,
|
|
1877
|
+
allTimePrompts: 0,
|
|
1878
|
+
allTimeAccounts: new Map(),
|
|
1879
|
+
liveTokens: 0,
|
|
1880
|
+
livePrompts: 0,
|
|
1881
|
+
liveAccounts: new Map(),
|
|
1882
|
+
};
|
|
1883
|
+
families.set(family, entry);
|
|
1884
|
+
}
|
|
1885
|
+
return entry;
|
|
1886
|
+
};
|
|
1887
|
+
|
|
1888
|
+
for (const [date, dayFamilies] of Object.entries(payload.days ?? {})) {
|
|
1889
|
+
for (const [family, day] of Object.entries(dayFamilies ?? {})) {
|
|
1890
|
+
const entry = ensure(family);
|
|
1891
|
+
const tokens = Math.max(0, Math.round(Number(day?.tokens) || 0));
|
|
1892
|
+
entry.tokens += tokens;
|
|
1893
|
+
entry.prompts += Math.max(0, Math.round(Number(day?.prompts) || 0));
|
|
1894
|
+
entry.days.set(date, (entry.days.get(date) ?? 0) + tokens);
|
|
1895
|
+
for (const [slot, slotRow] of Object.entries(day?.slots ?? {})) {
|
|
1896
|
+
const label = slot === "" ? "" : `#${slot}`;
|
|
1897
|
+
const account = entry.accounts.get(label) ?? { tokens: 0, prompts: 0, models: new Map<string, number>() };
|
|
1898
|
+
account.tokens += Math.max(0, Math.round(Number(slotRow?.tokens) || 0));
|
|
1899
|
+
account.prompts += Math.max(0, Math.round(Number(slotRow?.prompts) || 0));
|
|
1900
|
+
for (const [model, bucket] of Object.entries(slotRow?.models ?? {})) {
|
|
1901
|
+
const modelTokens = historyModelTokens(bucket);
|
|
1902
|
+
account.models.set(model, (account.models.get(model) ?? 0) + modelTokens);
|
|
1903
|
+
entry.models.set(model, (entry.models.get(model) ?? 0) + modelTokens);
|
|
1904
|
+
}
|
|
1905
|
+
entry.accounts.set(label, account);
|
|
791
1906
|
}
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
// The current month's open day is not frozen yet, so the month file has no
|
|
1911
|
+
// row for it. Merge today from the live report's localStats, by day key and
|
|
1912
|
+
// never by adding to an existing day: that is what makes double counting
|
|
1913
|
+
// impossible. The guard is per family, because one family the writer froze
|
|
1914
|
+
// today must not hide every other family's live row.
|
|
1915
|
+
//
|
|
1916
|
+
// The *report's* day decides, not the clock: `todayTotalTokens` is the day the
|
|
1917
|
+
// report was generated on. A pi session that crossed midnight still holds
|
|
1918
|
+
// yesterday's totals, and the first frame paints ~/.cache/pi-quota/usage.json,
|
|
1919
|
+
// which can be days old; merging either into today would add a frozen
|
|
1920
|
+
// yesterday to today. A stale report is skipped, and the tail says so.
|
|
1921
|
+
const now = new Date();
|
|
1922
|
+
const today = localDayKey(now);
|
|
1923
|
+
const report = this.options.getReport();
|
|
1924
|
+
const generatedAt = report?.generatedAt ? new Date(report.generatedAt) : null;
|
|
1925
|
+
// An unparseable generatedAt is no evidence of today: it is skipped, silently.
|
|
1926
|
+
const reportDay = generatedAt && !Number.isNaN(generatedAt.getTime()) ? localDayKey(generatedAt) : null;
|
|
1927
|
+
const frozenToday = payload.days?.[today] ?? {};
|
|
1928
|
+
let mergedToday = false;
|
|
1929
|
+
let skippedReportDay: string | null = null;
|
|
1930
|
+
if (month === localMonthKey(now)) {
|
|
1931
|
+
const stats = report?.localStats ?? {};
|
|
1932
|
+
for (const [family, familyStats] of Object.entries(stats)) {
|
|
1933
|
+
if (!familyStats || familyStats.hasLocalStats === false || frozenToday[family]) continue;
|
|
1934
|
+
const tokens = Math.max(0, Math.round(Number(familyStats.todayTotalTokens) || 0));
|
|
1935
|
+
const prompts = Math.max(0, Math.round(Number(familyStats.todayPrompts) || 0));
|
|
1936
|
+
if (tokens === 0 && prompts === 0) continue;
|
|
1937
|
+
// A day the report does not belong to is not today's row, however fresh
|
|
1938
|
+
// it looks: it is skipped whole, and never merged under today's key.
|
|
1939
|
+
if (reportDay !== today) {
|
|
1940
|
+
if (reportDay !== null) skippedReportDay = reportDay;
|
|
1941
|
+
break;
|
|
1942
|
+
}
|
|
1943
|
+
mergedToday = true;
|
|
1944
|
+
const entry = ensure(family);
|
|
1945
|
+
entry.tokens += tokens;
|
|
1946
|
+
entry.prompts += prompts;
|
|
1947
|
+
// Kept apart from the frozen month: the all-time figures add this same
|
|
1948
|
+
// delta below, and a live day may only ever be counted once in each.
|
|
1949
|
+
entry.liveTokens += tokens;
|
|
1950
|
+
entry.livePrompts += prompts;
|
|
1951
|
+
entry.days.set(today, (entry.days.get(today) ?? 0) + tokens);
|
|
1952
|
+
for (const [model, modelTokens] of Object.entries(familyStats.todayTokensByModel ?? {})) {
|
|
1953
|
+
entry.models.set(model, (entry.models.get(model) ?? 0) + Math.max(0, Math.round(Number(modelTokens) || 0)));
|
|
1954
|
+
}
|
|
1955
|
+
for (const [rawLabel, account] of Object.entries(familyStats.byAccount ?? {})) {
|
|
1956
|
+
const label = rawLabel === "#1" ? "" : rawLabel;
|
|
1957
|
+
const target = entry.accounts.get(label) ?? { tokens: 0, prompts: 0, models: new Map<string, number>() };
|
|
1958
|
+
const accountTokens = Math.max(0, Math.round(Number(account?.todayTokens) || 0));
|
|
1959
|
+
const accountPrompts = Math.max(0, Math.round(Number(account?.todayPrompts) || 0));
|
|
1960
|
+
target.tokens += accountTokens;
|
|
1961
|
+
target.prompts += accountPrompts;
|
|
1962
|
+
const liveAccount = entry.liveAccounts.get(label) ?? { tokens: 0, prompts: 0 };
|
|
1963
|
+
entry.liveAccounts.set(label, { tokens: liveAccount.tokens + accountTokens, prompts: liveAccount.prompts + accountPrompts });
|
|
1964
|
+
// The account's own models for today: without them the merged row
|
|
1965
|
+
// shows a month total and no model, which reads as "no usage".
|
|
1966
|
+
for (const [model, modelTokens] of Object.entries(account?.todayTokensByModel ?? {})) {
|
|
1967
|
+
target.models.set(model, (target.models.get(model) ?? 0) + Math.max(0, Math.round(Number(modelTokens) || 0)));
|
|
1968
|
+
}
|
|
1969
|
+
entry.accounts.set(label, target);
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
for (const [family, totals] of Object.entries(payload.totals?.families ?? {})) {
|
|
1975
|
+
const entry = ensure(family);
|
|
1976
|
+
entry.allTime = Object.values(totals?.modelUsage ?? {}).reduce((sum, bucket) => sum + totalsModelTokens(bucket), 0);
|
|
1977
|
+
entry.allTimePrompts = Math.max(0, Math.round(Number(totals?.totalPrompts) || 0));
|
|
1978
|
+
for (const [rawLabel, account] of Object.entries(totals?.accounts ?? {})) {
|
|
1979
|
+
const label = rawLabel === "#1" ? "" : rawLabel;
|
|
1980
|
+
const tokens = Object.values(account?.modelUsage ?? {}).reduce((sum, bucket) => sum + totalsModelTokens(bucket), 0);
|
|
1981
|
+
const prompts = Math.max(0, Math.round(Number(account?.totalPrompts) || 0));
|
|
1982
|
+
const seen = entry.allTimeAccounts.get(label) ?? { tokens: 0, prompts: 0 };
|
|
1983
|
+
entry.allTimeAccounts.set(label, { tokens: seen.tokens + tokens, prompts: seen.prompts + prompts });
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
// Today's live day is part of all time, not only of this month: it is the
|
|
1988
|
+
// same usage the month row and the day row above already show, so it is
|
|
1989
|
+
// added here exactly once — the single place the live delta is folded into
|
|
1990
|
+
// a rollup, and only under the merge guard above (the day frozen, or a
|
|
1991
|
+
// report from another day, never produces a delta at all).
|
|
1992
|
+
//
|
|
1993
|
+
// A family with no rollup in totals.json gets nothing: there is no all-time
|
|
1994
|
+
// figure to extend, and calling today's tokens "all-time" would hide every
|
|
1995
|
+
// frozen day before it. The page already carries the CLI's note for that.
|
|
1996
|
+
for (const [family, entry] of families) {
|
|
1997
|
+
if (!payload.totals?.families?.[family]) continue;
|
|
1998
|
+
if (entry.liveTokens === 0 && entry.livePrompts === 0) continue;
|
|
1999
|
+
entry.allTime += entry.liveTokens;
|
|
2000
|
+
entry.allTimePrompts += entry.livePrompts;
|
|
2001
|
+
for (const [label, delta] of entry.liveAccounts) {
|
|
2002
|
+
const seen = entry.allTimeAccounts.get(label) ?? { tokens: 0, prompts: 0 };
|
|
2003
|
+
entry.allTimeAccounts.set(label, { tokens: seen.tokens + delta.tokens, prompts: seen.prompts + delta.prompts });
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
|
|
2007
|
+
const sectionOf = (family: string): number => {
|
|
2008
|
+
const providers = this.options.getReport()?.providers ?? [];
|
|
2009
|
+
const index = providers.findIndex((provider) => provider.family === family);
|
|
2010
|
+
return index === -1 ? Number.MAX_SAFE_INTEGER : index;
|
|
2011
|
+
};
|
|
2012
|
+
const ordered = Array.from(families.entries()).sort(
|
|
2013
|
+
(a, b) => sectionOf(a[0]) - sectionOf(b[0]) || a[0].localeCompare(b[0]),
|
|
2014
|
+
);
|
|
2015
|
+
|
|
2016
|
+
// Section bodies are indented by four columns in metrics(); the wrap budget
|
|
2017
|
+
// must leave room for that or a long day list is clipped at the right edge.
|
|
2018
|
+
const bodyWidth = Math.max(24, width - 4);
|
|
2019
|
+
const sections: PanelSection[] = [];
|
|
2020
|
+
for (const [family, entry] of ordered) {
|
|
2021
|
+
// Every account the family has in the month *or* all-time: a month in which
|
|
2022
|
+
// one account carried the usage must still show the family's other keys,
|
|
2023
|
+
// or the page hides the very rows that answer "which key burned what".
|
|
2024
|
+
const accountLabels = Array.from(new Set([...entry.accounts.keys(), ...entry.allTimeAccounts.keys()])).sort(
|
|
2025
|
+
(a, b) => slotOrder(a) - slotOrder(b),
|
|
2026
|
+
);
|
|
2027
|
+
// Multi-account families use the same short name as the Now panel header.
|
|
2028
|
+
const display = accountLabels.length > 1 ? SHORT_NAME[family] ?? FAMILY_LABEL[family] ?? family : FAMILY_LABEL[family] ?? family;
|
|
2029
|
+
const name = paint(BRAND[family] ?? "#8B949E", display);
|
|
2030
|
+
// The month first, then the all-time rollup with today's live day folded
|
|
2031
|
+
// in: every figure here counts a live day once. Prompts are scope-labelled
|
|
2032
|
+
// in their own row below, because an unlabelled count reads as the wrong
|
|
2033
|
+
// one of the two.
|
|
2034
|
+
//
|
|
2035
|
+
// Every all-time figure is computed before the first line is built: the
|
|
2036
|
+
// note a lagging rollup earns belongs at the top of the section, where it
|
|
2037
|
+
// explains the header, the prompts row and the account rows at once.
|
|
2038
|
+
const meta = [`${formatTokens(entry.tokens)} in ${month}`];
|
|
2039
|
+
const familyAllTime = allTimeFigure(entry.tokens, entry.allTime);
|
|
2040
|
+
if (familyAllTime.value > 0) meta.push(`${formatTokens(familyAllTime.value)} all-time`);
|
|
2041
|
+
const promptsAllTime = allTimeFigure(entry.prompts, entry.allTimePrompts);
|
|
2042
|
+
const accountAllTime = new Map<string, AllTimeFigure>();
|
|
2043
|
+
for (const accountLabel of accountLabels) {
|
|
2044
|
+
accountAllTime.set(
|
|
2045
|
+
accountLabel,
|
|
2046
|
+
allTimeFigure(entry.accounts.get(accountLabel)?.tokens ?? 0, entry.allTimeAccounts.get(accountLabel)?.tokens ?? 0),
|
|
798
2047
|
);
|
|
799
2048
|
}
|
|
2049
|
+
const lagsMonth =
|
|
2050
|
+
familyAllTime.lags || promptsAllTime.lags || Array.from(accountAllTime.values()).some((figure) => figure.lags);
|
|
2051
|
+
const body: string[] = [];
|
|
2052
|
+
if (lagsMonth) body.push(` ${this.theme.fg("warning", `~ ${ALL_TIME_LAGS_NOTE}`)}`);
|
|
2053
|
+
const label = (text: string) => ` ${this.theme.fg("dim", text.padEnd(6))} `;
|
|
2054
|
+
const rest = ` ${" ".repeat(8)}`;
|
|
2055
|
+
const dayCells = Array.from(entry.days.entries())
|
|
2056
|
+
.sort((a, b) => a[0].localeCompare(b[0]))
|
|
2057
|
+
.map(([date, tokens]) => `${date.slice(5)} ${formatTokens(tokens)}`);
|
|
2058
|
+
body.push(...wrapCells(
|
|
2059
|
+
dayCells.length > 0 ? dayCells : [this.theme.fg("dim", "no frozen days in this month")],
|
|
2060
|
+
label("days"),
|
|
2061
|
+
rest,
|
|
2062
|
+
bodyWidth,
|
|
2063
|
+
));
|
|
2064
|
+
// Both scopes, always: the live day is merged into each of them once, so
|
|
2065
|
+
// the month count and the all-time count may never disagree about it.
|
|
2066
|
+
const promptCells: string[] = [];
|
|
2067
|
+
if (entry.prompts > 0) promptCells.push(`${entry.prompts} in ${month}`);
|
|
2068
|
+
if (promptsAllTime.value > 0) {
|
|
2069
|
+
// A figure that lags the month is still a figure: it is printed, dimmed
|
|
2070
|
+
// whole, and the note above the rows says why it is small.
|
|
2071
|
+
promptCells.push(
|
|
2072
|
+
promptsAllTime.lags
|
|
2073
|
+
? this.theme.fg("dim", `${promptsAllTime.value} all-time`)
|
|
2074
|
+
: `${promptsAllTime.value} ${this.theme.fg("dim", "all-time")}`,
|
|
2075
|
+
);
|
|
2076
|
+
}
|
|
2077
|
+
if (promptCells.length > 0) {
|
|
2078
|
+
body.push(...wrapCells(promptCells, label("prompts"), rest, bodyWidth));
|
|
2079
|
+
}
|
|
2080
|
+
if (entry.models.size > 0) {
|
|
2081
|
+
const top = Array.from(entry.models.entries()).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
|
|
2082
|
+
const shown = top.slice(0, 5).map(([model, tokens]) => `${shortModelName(model)} ${formatTokens(tokens)}`);
|
|
2083
|
+
if (top.length > shown.length) shown.push(this.theme.fg("dim", `+${top.length - shown.length} more`));
|
|
2084
|
+
body.push(...wrapCells(shown, label("models"), rest, bodyWidth));
|
|
2085
|
+
}
|
|
2086
|
+
if (accountLabels.length > 1) {
|
|
2087
|
+
const labelWidth = Math.max(...accountLabels.map((text) => text.length));
|
|
2088
|
+
for (const accountLabel of accountLabels) {
|
|
2089
|
+
const account = entry.accounts.get(accountLabel) ?? { tokens: 0, prompts: 0, models: new Map<string, number>() };
|
|
2090
|
+
const parts = [`${this.theme.fg("dim", "month")} ${formatTokens(account.tokens)}`];
|
|
2091
|
+
const accountFigure = accountAllTime.get(accountLabel) ?? { value: 0, lags: false };
|
|
2092
|
+
if (accountFigure.value > 0) {
|
|
2093
|
+
parts.push(
|
|
2094
|
+
accountFigure.lags
|
|
2095
|
+
? this.theme.fg("dim", `all-time ${formatTokens(accountFigure.value)}`)
|
|
2096
|
+
: `${this.theme.fg("dim", "all-time")} ${formatTokens(accountFigure.value)}`,
|
|
2097
|
+
);
|
|
2098
|
+
}
|
|
2099
|
+
const best = Array.from(account.models.entries()).sort((a, b) => b[1] - a[1])[0];
|
|
2100
|
+
if (best) parts.push(this.theme.fg("dim", shortModelName(best[0])));
|
|
2101
|
+
body.push(` ${this.theme.fg("dim", accountLabel.padEnd(labelWidth))} ${parts.join(this.theme.fg("dim", " · "))}`);
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
sections.push({ key: `history:${family}`, header: `${name} ${this.theme.fg("dim", `· ${meta.join(" · ")}`)}`, body });
|
|
800
2105
|
}
|
|
801
2106
|
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
2107
|
+
const tail: string[] = [];
|
|
2108
|
+
if (ordered.length === 0) tail.push(this.theme.fg("dim", `no token history for ${month}`));
|
|
2109
|
+
for (const note of payload.notes ?? []) tail.push(this.theme.fg("warning", `! ${note}`));
|
|
2110
|
+
if (mergedToday) {
|
|
2111
|
+
tail.push(this.theme.fg("warning", `~ ${today} comes from the live report; it is not frozen in history yet`));
|
|
2112
|
+
} else if (skippedReportDay !== null) {
|
|
2113
|
+
// The report on screen is older than today, so its open-day totals belong
|
|
2114
|
+
// to another day: say so, or a missing today row reads as a lost day.
|
|
2115
|
+
tail.push(this.theme.fg("dim", `the live report is from ${skippedReportDay}; ${today} is not merged`));
|
|
2116
|
+
}
|
|
2117
|
+
const lastFrozen = payload.totals?.lastFrozenDay || "none";
|
|
2118
|
+
tail.push(this.theme.fg("dim", `frozen through ${lastFrozen} · ${month} · read-only`));
|
|
2119
|
+
return { sections, tail };
|
|
805
2120
|
}
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
const
|
|
809
|
-
|
|
2121
|
+
|
|
2122
|
+
private titleLine(): string {
|
|
2123
|
+
const title = this.theme.fg("accent", this.theme.bold("Quota"));
|
|
2124
|
+
if (this.view !== "history") return title;
|
|
2125
|
+
const month = this.selectedMonth === null ? "…" : this.selectedMonth;
|
|
2126
|
+
return `${title} ${this.theme.fg("dim", `· History · ${month}`)}`;
|
|
810
2127
|
}
|
|
811
|
-
|
|
812
|
-
|
|
2128
|
+
|
|
2129
|
+
/**
|
|
2130
|
+
* The header's right side: a visible refresh indicator while the CLI runs,
|
|
2131
|
+
* the time the update landed afterwards, the view's position, and the scroll
|
|
2132
|
+
* range when the content is taller than the viewport.
|
|
2133
|
+
*/
|
|
2134
|
+
private statusText(total: number, height: number): string {
|
|
2135
|
+
const parts: string[] = [];
|
|
2136
|
+
// History's today row is merged from the live report, so the report's state
|
|
2137
|
+
// (refreshing, its update time, a failed refresh) heads both views.
|
|
2138
|
+
if (this.options.isRefreshing()) {
|
|
2139
|
+
parts.push(this.theme.fg("accent", "refreshing …"));
|
|
2140
|
+
} else {
|
|
2141
|
+
const report = this.options.getReport();
|
|
2142
|
+
if (report) parts.push(this.theme.fg("dim", updatedAtLabel(report)));
|
|
2143
|
+
if (this.options.getErrors().length > 0) parts.push(this.theme.fg("error", "refresh failed"));
|
|
2144
|
+
}
|
|
2145
|
+
if (this.view === "history") {
|
|
2146
|
+
const status = this.historyStatus;
|
|
2147
|
+
// Only the month on screen reports its own fetch: a fetch for a month the
|
|
2148
|
+
// user already left must not claim the header.
|
|
2149
|
+
const shown = this.selectedMonth;
|
|
2150
|
+
const waitsForShown = shown === null || status.month === null || status.month === shown || !this.historyCache.has(shown);
|
|
2151
|
+
if (status.kind === "loading" && waitsForShown) {
|
|
2152
|
+
parts.push(this.theme.fg("accent", status.month === null ? "loading …" : `loading ${status.month} …`));
|
|
2153
|
+
} else if (this.historyFailure() !== null) {
|
|
2154
|
+
parts.push(this.theme.fg("error", "history failed"));
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
if (total > height) {
|
|
2158
|
+
const last = Math.min(total, this.scroll + height);
|
|
2159
|
+
parts.push(this.theme.fg("dim", `${this.scroll + 1}-${last}/${total}`));
|
|
2160
|
+
}
|
|
2161
|
+
return parts.join(this.theme.fg("dim", " · "));
|
|
2162
|
+
}
|
|
2163
|
+
|
|
2164
|
+
/** Hint pairs for the active view; History adds its month navigation. */
|
|
2165
|
+
private legendHints(): ReadonlyArray<readonly [string, string]> {
|
|
2166
|
+
return this.view === "history" ? HISTORY_HINTS : NOW_HINTS;
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
/**
|
|
2170
|
+
* Wrap the legend pairs across as many rows as the width needs, balanced:
|
|
2171
|
+
* greedy filling leaves the last pair alone on a row of its own ("esc/q
|
|
2172
|
+
* close" under seven pairs), which reads as a lost key. The row count is the
|
|
2173
|
+
* minimum greedy needs, so widening the pane never adds a row.
|
|
2174
|
+
*/
|
|
2175
|
+
private legendLines(width: number): string[] {
|
|
2176
|
+
const separator = this.theme.fg("dim", " · ");
|
|
2177
|
+
const pairs = this.legendHints().map(([keys, label]) => `${this.theme.fg("dim", keys)} ${label}`);
|
|
2178
|
+
if (pairs.length === 0) return [""];
|
|
2179
|
+
const rows = balanceRows(pairs.map((pair) => visibleLength(pair)), width, 3);
|
|
2180
|
+
const lines: string[] = [];
|
|
2181
|
+
let index = 0;
|
|
2182
|
+
for (const count of rows) {
|
|
2183
|
+
lines.push(pairs.slice(index, index + count).join(separator));
|
|
2184
|
+
index += count;
|
|
2185
|
+
}
|
|
2186
|
+
return lines;
|
|
813
2187
|
}
|
|
814
|
-
return lines;
|
|
815
2188
|
}
|
|
816
2189
|
|
|
817
|
-
export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
2190
|
+
export default function quotaPanelExtension(pi: ExtensionAPI, dependencies: ExtensionDependencies = {}): void {
|
|
2191
|
+
const loadFamily = dependencies.collectFamily ?? collectFamily;
|
|
2192
|
+
const startScan = dependencies.startLocalStats ?? (() => startLocalStatsWorker() as LocalStatsScan);
|
|
2193
|
+
const getProviderAuth = dependencies.getProviderAuth ?? (async (ctx, provider) => ctx.modelRegistry?.getProviderAuth?.(provider));
|
|
2194
|
+
const readHistory = (month: string | null) => dependencies.loadHistory
|
|
2195
|
+
? dependencies.loadHistory(month)
|
|
2196
|
+
: (historyJson({ historyDir: resolveHistoryDir(), month }) as HistoryPayload);
|
|
2197
|
+
const publishOmarchy = dependencies.publishOmarchy ?? ((value, prune) => {
|
|
2198
|
+
const skip = skippedFamilies(process.env);
|
|
2199
|
+
const reportToPublish = skip.size > 0
|
|
2200
|
+
? { ...value, providers: value.providers.filter((provider) => !skip.has(provider.family)) }
|
|
2201
|
+
: value;
|
|
2202
|
+
publishRecords(buildRecords(reportToPublish as any), { prune });
|
|
2203
|
+
});
|
|
818
2204
|
let report: QuotaReport | null = null;
|
|
819
|
-
|
|
2205
|
+
const inFlight = new Map<string, Promise<boolean>>();
|
|
2206
|
+
let resultGeneration = 0;
|
|
2207
|
+
let prunedGeneration = 0;
|
|
2208
|
+
let localStatsInFlight: Promise<void> | null = null;
|
|
2209
|
+
let localStatsScan: LocalStatsScan | null = null;
|
|
2210
|
+
let localStatsResult: Awaited<LocalStatsScan["result"]> | null = null;
|
|
2211
|
+
/**
|
|
2212
|
+
* The notes the scan produced (its own warnings, or the one line a failure
|
|
2213
|
+
* becomes). They live here, not only in the report, because the scan can
|
|
2214
|
+
* finish before the first family does: it is the report that is late then,
|
|
2215
|
+
* not the warning.
|
|
2216
|
+
*/
|
|
2217
|
+
let localStatsWarnings: string[] = [];
|
|
820
2218
|
let timer: ReturnType<typeof setInterval> | null = null;
|
|
821
2219
|
let agentEndTimer: ReturnType<typeof setTimeout> | null = null;
|
|
822
2220
|
let panelVisible = false;
|
|
823
2221
|
/**
|
|
824
|
-
* The
|
|
825
|
-
*
|
|
2222
|
+
* The open fullscreen overlay, while there is one. Bare `/usage` opens it and
|
|
2223
|
+
* a background refresh redraws it; closing it leaves nothing behind.
|
|
2224
|
+
*/
|
|
2225
|
+
let overlayView: UsageOverlay | null = null;
|
|
2226
|
+
/**
|
|
2227
|
+
* What a reopened overlay keeps: every bare `/usage` builds a fresh view, so
|
|
2228
|
+
* the folds and the page live here, for the pi session and never on disk.
|
|
826
2229
|
*/
|
|
827
|
-
let
|
|
2230
|
+
let overlaySession = newOverlaySession();
|
|
828
2231
|
/**
|
|
829
2232
|
* Nothing is pinned by default. A box or line above the editor is a persistent
|
|
830
2233
|
* surface, and a quota command should not claim a row until asked.
|
|
@@ -834,22 +2237,30 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
834
2237
|
let explicitBox = false;
|
|
835
2238
|
/** gentle-pi owns the footer and truncates it from the end, so start off. */
|
|
836
2239
|
let statusVisible = false;
|
|
837
|
-
|
|
2240
|
+
/** One failure per family: an out-of-order success must not hide another's. */
|
|
2241
|
+
const familyErrors = new Map<string, string>();
|
|
2242
|
+
/**
|
|
2243
|
+
* The Claude source the report in memory actually came from. The extension
|
|
2244
|
+
* forces Pi's own OAuth when Pi resolves a token, and that is a different
|
|
2245
|
+
* fact from what PI_QUOTA_CLAUDE_SOURCE says: keying the cache by the setting
|
|
2246
|
+
* alone stored Pi-sourced numbers under the CLI's auto/claude-code key, where
|
|
2247
|
+
* the next reader asked the other question and was served them anyway.
|
|
2248
|
+
*/
|
|
2249
|
+
let claudeSourceUsed: string | null = null;
|
|
838
2250
|
let disposed = false;
|
|
839
2251
|
/** True once the installed gentle-pi is known to paint a rail slot for this card. */
|
|
840
2252
|
let railMode = false;
|
|
841
2253
|
|
|
842
2254
|
/**
|
|
843
|
-
* Load the rail inspector from
|
|
844
|
-
* native-layout detection; the runtime chaining
|
|
2255
|
+
* Load the rail inspector from this package, not from a quota CLI subprocess.
|
|
2256
|
+
* A missing patcher disables native-layout detection; the runtime chaining
|
|
2257
|
+
* hook remains available.
|
|
845
2258
|
*/
|
|
846
2259
|
async function loadRailPatcher(): Promise<{
|
|
847
2260
|
resolveGentlePiLayout: (options?: { dir?: string }) => { layoutPath: string; present: boolean };
|
|
848
2261
|
inspectRailPatch: (options: { layoutPath: string }) => { state: string };
|
|
849
2262
|
} | null> {
|
|
850
|
-
const
|
|
851
|
-
if (!cli) return null;
|
|
852
|
-
const modulePath = join(dirname(cli), "..", "src", "gentle-pi", "rail-patch.js");
|
|
2263
|
+
const modulePath = dependencies.railPatcherPath ?? fileURLToPath(new URL("../src/gentle-pi/rail-patch.js", import.meta.url));
|
|
853
2264
|
if (!existsSync(modulePath)) return null;
|
|
854
2265
|
try {
|
|
855
2266
|
return await import(pathToFileURL(modulePath).href);
|
|
@@ -869,32 +2280,213 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
869
2280
|
railMode = inspection.state === "patched";
|
|
870
2281
|
}
|
|
871
2282
|
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
2283
|
+
/** Whether a family refresh is in flight; the header shows it while one is. */
|
|
2284
|
+
function isRefreshing(): boolean {
|
|
2285
|
+
return inFlight.size > 0;
|
|
2286
|
+
}
|
|
2287
|
+
|
|
2288
|
+
/** Resolve Pi's own auth for the two rotating OAuth providers. Tokens stay local to this call. */
|
|
2289
|
+
async function authOverridesFor(ctx: UiContext, family: string): Promise<Record<string, { access: string; expiresAtMs: number | null; accountId?: string }> | undefined> {
|
|
2290
|
+
const provider = family === "claude" ? "anthropic" : family === "codex" ? "openai-codex" : null;
|
|
2291
|
+
if (!provider) return undefined;
|
|
878
2292
|
try {
|
|
879
|
-
const
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
2293
|
+
const resolved = await getProviderAuth(ctx, provider);
|
|
2294
|
+
// Pi can resolve api_key credentials through the same method. Quota
|
|
2295
|
+
// endpoints here require the subscription OAuth access token, not an API
|
|
2296
|
+
// key; only Pi's OAuth result is eligible for the in-memory override.
|
|
2297
|
+
if (resolved?.source !== "OAuth") return undefined;
|
|
2298
|
+
const token = resolved.auth?.apiKey;
|
|
2299
|
+
if (typeof token !== "string" || token.length === 0) return undefined;
|
|
2300
|
+
const accountId = (typeof resolved?.accountId === "string" && resolved.accountId) || extractChatGptAccountId(token) || undefined;
|
|
2301
|
+
return {
|
|
2302
|
+
[provider]: {
|
|
2303
|
+
access: token,
|
|
2304
|
+
expiresAtMs: extractExpiresAtMs(token),
|
|
2305
|
+
...(family === "codex" && accountId ? { accountId } : {}),
|
|
2306
|
+
},
|
|
2307
|
+
};
|
|
2308
|
+
} catch {
|
|
2309
|
+
// Never put arbitrary auth errors in a TUI frame; the engine will report its read-only credential state.
|
|
2310
|
+
return undefined;
|
|
895
2311
|
}
|
|
896
2312
|
}
|
|
897
2313
|
|
|
2314
|
+
function mergeFamilyReport(fragment: QuotaReport): void {
|
|
2315
|
+
const prior = report;
|
|
2316
|
+
const merged = mergeReportIntoCache(prior, fragment as any) as QuotaReport;
|
|
2317
|
+
merged.localStats = localStatsResult?.byFamily ?? prior?.localStats ?? fragment.localStats ?? {};
|
|
2318
|
+
merged.localStatsMeta = localStatsResult?.scan ?? prior?.localStatsMeta ?? fragment.localStatsMeta ?? null;
|
|
2319
|
+
merged.warnings = mergeWarnings(merged.warnings ?? [], localStatsWarnings);
|
|
2320
|
+
const families = enabledFamilies({ env: process.env, requested: FAMILIES });
|
|
2321
|
+
const ordering = [...families, ...Object.keys(merged.byFamily).filter((family) => !families.includes(family))];
|
|
2322
|
+
merged.providers = ordering.flatMap((family) => merged.providers.filter((provider) => provider.family === family));
|
|
2323
|
+
merged.byFamily = Object.fromEntries(
|
|
2324
|
+
ordering
|
|
2325
|
+
.map((family) => [family, merged.providers.filter((provider) => provider.family === family)] as const)
|
|
2326
|
+
.filter(([, providers]) => providers.length > 0),
|
|
2327
|
+
);
|
|
2328
|
+
report = merged;
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
/**
|
|
2332
|
+
* The report in memory, or the one on disk. Reading the cache also adopts the
|
|
2333
|
+
* Claude source its key names, so a codex-only write keeps describing the
|
|
2334
|
+
* Claude numbers the file already holds.
|
|
2335
|
+
*/
|
|
2336
|
+
function ensureReport(): QuotaReport | null {
|
|
2337
|
+
if (report) return report;
|
|
2338
|
+
const cached = readCachedReport();
|
|
2339
|
+
if (!cached) return null;
|
|
2340
|
+
const stored = cached.key?.startsWith(CLAUDE_SOURCE_CACHE_PREFIX)
|
|
2341
|
+
? cached.key.slice(CLAUDE_SOURCE_CACHE_PREFIX.length)
|
|
2342
|
+
: null;
|
|
2343
|
+
if (stored) claudeSourceUsed = normalizeClaudeSourceMode(stored);
|
|
2344
|
+
report = cached.report;
|
|
2345
|
+
return report;
|
|
2346
|
+
}
|
|
2347
|
+
|
|
2348
|
+
/** The key this report belongs under: the source it used, not the setting. */
|
|
2349
|
+
function cacheKey(): string {
|
|
2350
|
+
return cacheKeyFor(claudeSourceUsed ?? process.env.PI_QUOTA_CLAUDE_SOURCE ?? "");
|
|
2351
|
+
}
|
|
2352
|
+
|
|
2353
|
+
function persistReport(freshFamilies: string[] = []): void {
|
|
2354
|
+
if (!report) return;
|
|
2355
|
+
// Every family keeps the clock it was fetched on: this report is written one
|
|
2356
|
+
// family at a time, and stamping the whole file with "now" made Claude's
|
|
2357
|
+
// five-minute-old numbers look as fresh as the Codex ones saved beside them.
|
|
2358
|
+
// Only the family that just resolved is "now"; a family without a clock in
|
|
2359
|
+
// refresh-state keeps the cache's, or its own results' age.
|
|
2360
|
+
writeCache(report as any, { key: cacheKey(), fetchedAtMs: readRefreshState().fetchedAtMs, freshFamilies });
|
|
2361
|
+
}
|
|
2362
|
+
|
|
2363
|
+
function updateFamilyClock(family: string): void {
|
|
2364
|
+
const state = readRefreshState();
|
|
2365
|
+
writeRefreshState({ fetchedAtMs: { ...state.fetchedAtMs, [family]: Date.now() } });
|
|
2366
|
+
}
|
|
2367
|
+
|
|
2368
|
+
function startLocalStats(ctx: UiContext): void {
|
|
2369
|
+
if (process.env.PI_QUOTA_LOCAL_STATS === "0" || localStatsInFlight) return;
|
|
2370
|
+
const scan = startScan();
|
|
2371
|
+
localStatsScan = scan;
|
|
2372
|
+
const task = scan.result
|
|
2373
|
+
.then((result) => {
|
|
2374
|
+
if (disposed) return;
|
|
2375
|
+
localStatsResult = result;
|
|
2376
|
+
// The scan's own notes (a corrupt cache, an unreadable file) are part of
|
|
2377
|
+
// the report the CLI already publishes; dropping them here made the same
|
|
2378
|
+
// scan quieter inside Pi than in the terminal.
|
|
2379
|
+
localStatsWarnings = result.warnings ?? [];
|
|
2380
|
+
if (report) {
|
|
2381
|
+
report = {
|
|
2382
|
+
...report,
|
|
2383
|
+
localStats: result.byFamily,
|
|
2384
|
+
localStatsMeta: result.scan,
|
|
2385
|
+
warnings: mergeWarnings(report.warnings, localStatsWarnings),
|
|
2386
|
+
};
|
|
2387
|
+
persistReport();
|
|
2388
|
+
if (surfaceActive()) paintUi(ctx);
|
|
2389
|
+
try {
|
|
2390
|
+
publishOmarchy(report, false);
|
|
2391
|
+
} catch {
|
|
2392
|
+
// The quota view is independent of the optional Omarchy record writer.
|
|
2393
|
+
}
|
|
2394
|
+
overlayView?.redraw();
|
|
2395
|
+
}
|
|
2396
|
+
})
|
|
2397
|
+
.catch((error: { name?: string; message?: string }) => {
|
|
2398
|
+
// The scan is optional, so a failure never delays or erases quotas — but
|
|
2399
|
+
// it is not the same as a scan that found nothing. The CLI reports a
|
|
2400
|
+
// failed scan as one warning line; a swallowed worker error meant a
|
|
2401
|
+
// crash in the scanner looked exactly like an empty token history.
|
|
2402
|
+
if (disposed || error?.name === "AbortError") return;
|
|
2403
|
+
const cause = capCause(redactCause(error?.message ?? String(error)).split("\n")[0]);
|
|
2404
|
+
localStatsWarnings = mergeWarnings(localStatsWarnings, [`local token stats: ${cause}`]);
|
|
2405
|
+
if (!report) return;
|
|
2406
|
+
report = { ...report, warnings: mergeWarnings(report.warnings, localStatsWarnings) };
|
|
2407
|
+
if (surfaceActive()) paintUi(ctx);
|
|
2408
|
+
overlayView?.redraw();
|
|
2409
|
+
})
|
|
2410
|
+
.finally(() => {
|
|
2411
|
+
if (localStatsScan === scan) localStatsScan = null;
|
|
2412
|
+
if (localStatsInFlight === task) localStatsInFlight = null;
|
|
2413
|
+
});
|
|
2414
|
+
localStatsInFlight = task;
|
|
2415
|
+
}
|
|
2416
|
+
|
|
2417
|
+
/**
|
|
2418
|
+
* End the local scan this session started. Nothing it began may outlive the
|
|
2419
|
+
* session: a /quit or /reload one second into a cold scan would otherwise
|
|
2420
|
+
* keep reading the session store and hold the token-history lock until the
|
|
2421
|
+
* 120 s stale timeout, making the next scan read-only.
|
|
2422
|
+
*/
|
|
2423
|
+
async function stopLocalStats(): Promise<void> {
|
|
2424
|
+
const scan = localStatsScan;
|
|
2425
|
+
localStatsScan = null;
|
|
2426
|
+
if (!scan) return;
|
|
2427
|
+
await scan.stop();
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2430
|
+
async function refreshFamily(ctx: UiContext, family: string, force: boolean): Promise<boolean> {
|
|
2431
|
+
const running = inFlight.get(family);
|
|
2432
|
+
if (running) return running;
|
|
2433
|
+
let task: Promise<boolean>;
|
|
2434
|
+
task = (async () => {
|
|
2435
|
+
try {
|
|
2436
|
+
// Explicit delay seam used by the live progressive-refresh proof; absent in normal runs.
|
|
2437
|
+
if (process.env.PI_QUOTA_DEBUG_DELAY_FAMILY === family) {
|
|
2438
|
+
const delay = Math.max(0, Math.min(30_000, Number(process.env.PI_QUOTA_DEBUG_DELAY_MS) || 2_000));
|
|
2439
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
2440
|
+
}
|
|
2441
|
+
const authOverrides = await authOverridesFor(ctx, family);
|
|
2442
|
+
const env = family === "claude" && authOverrides
|
|
2443
|
+
? { ...process.env, PI_QUOTA_CLAUDE_SOURCE: "pi" }
|
|
2444
|
+
: process.env;
|
|
2445
|
+
const fragment = await loadFamily(family, { force, authOverrides, env, localStats: false } as any);
|
|
2446
|
+
if (disposed) return false;
|
|
2447
|
+
if (family === "claude") claudeSourceUsed = normalizeClaudeSourceMode(env.PI_QUOTA_CLAUDE_SOURCE);
|
|
2448
|
+
const stickyFragment = mergeLastGood(fragment as any, {}).report as QuotaReport;
|
|
2449
|
+
mergeFamilyReport(stickyFragment);
|
|
2450
|
+
updateFamilyClock(family);
|
|
2451
|
+
persistReport([family]);
|
|
2452
|
+
resultGeneration += 1;
|
|
2453
|
+
familyErrors.delete(family);
|
|
2454
|
+
try {
|
|
2455
|
+
const familyReport = { ...stickyFragment, localStats: report?.localStats ?? stickyFragment.localStats ?? {} };
|
|
2456
|
+
publishOmarchy(familyReport, false);
|
|
2457
|
+
} catch {
|
|
2458
|
+
// A bar-record failure must not turn a quota refresh into an error.
|
|
2459
|
+
}
|
|
2460
|
+
if (surfaceActive()) paintUi(ctx);
|
|
2461
|
+
return true;
|
|
2462
|
+
} catch (error) {
|
|
2463
|
+
const message = (error as { message?: string })?.message ?? String(error);
|
|
2464
|
+
familyErrors.set(family, capCause(redactCause(message).split("\n")[0]));
|
|
2465
|
+
return false;
|
|
2466
|
+
} finally {
|
|
2467
|
+
if (inFlight.get(family) === task) inFlight.delete(family);
|
|
2468
|
+
if (surfaceActive()) paintUi(ctx);
|
|
2469
|
+
overlayView?.redraw();
|
|
2470
|
+
}
|
|
2471
|
+
})();
|
|
2472
|
+
inFlight.set(family, task);
|
|
2473
|
+
return task;
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
/**
|
|
2477
|
+
* One line per failing family, in family order so the list does not reshuffle
|
|
2478
|
+
* as families land. The name is short for the same reason: this is a row in a
|
|
2479
|
+
* dense panel, not a log.
|
|
2480
|
+
*/
|
|
2481
|
+
function errorLines(): string[] {
|
|
2482
|
+
const order = [...enabledFamilies({ env: process.env, requested: FAMILIES })];
|
|
2483
|
+
for (const family of familyErrors.keys()) if (!order.includes(family)) order.push(family);
|
|
2484
|
+
return order.flatMap((family) => {
|
|
2485
|
+
const message = familyErrors.get(family);
|
|
2486
|
+
return message ? [`${SHORT_NAME[family] ?? family}: ${message}`] : [];
|
|
2487
|
+
});
|
|
2488
|
+
}
|
|
2489
|
+
|
|
898
2490
|
function paintUi(ctx: UiContext): void {
|
|
899
2491
|
if (disposed) return;
|
|
900
2492
|
const theme = ctx.ui.theme;
|
|
@@ -1043,18 +2635,42 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
1043
2635
|
}
|
|
1044
2636
|
|
|
1045
2637
|
async function refresh(ctx: UiContext, force: boolean): Promise<void> {
|
|
1046
|
-
if (
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
2638
|
+
if (disposed) return;
|
|
2639
|
+
report = ensureReport();
|
|
2640
|
+
const families = enabledFamilies({ env: process.env, requested: FAMILIES });
|
|
2641
|
+
const now = Date.now();
|
|
2642
|
+
const fetchedAtMs = { ...readRefreshState().fetchedAtMs };
|
|
2643
|
+
// Upgrade path: an older CLI cache has no per-family clock file, but each
|
|
2644
|
+
// provider already carries its own updatedAt. Do not refetch fresh cached data
|
|
2645
|
+
// merely because this extension version has not written clocks yet.
|
|
2646
|
+
for (const family of families) {
|
|
2647
|
+
if (typeof fetchedAtMs[family] === "number") continue;
|
|
2648
|
+
const providerTimes = (report?.providers ?? [])
|
|
2649
|
+
.filter((provider) => provider.family === family)
|
|
2650
|
+
.map((provider) => Date.parse(provider.updatedAt))
|
|
2651
|
+
.filter((time) => Number.isFinite(time));
|
|
2652
|
+
const generatedAt = report?.generatedAt ? Date.parse(report.generatedAt) : NaN;
|
|
2653
|
+
const fallback = providerTimes.length > 0 ? Math.max(...providerTimes) : generatedAt;
|
|
2654
|
+
if (Number.isFinite(fallback)) fetchedAtMs[family] = fallback;
|
|
2655
|
+
}
|
|
2656
|
+
const staleByClock = new Set(staleFamilies({
|
|
2657
|
+
fetchedAtMs,
|
|
2658
|
+
ttls: resolveFamilyTtls({ families }),
|
|
2659
|
+
families,
|
|
2660
|
+
now,
|
|
2661
|
+
}));
|
|
2662
|
+
const cachedFamilies = new Set(report?.providers.map((provider) => provider.family) ?? []);
|
|
2663
|
+
const selected = force ? families : families.filter((family) => !cachedFamilies.has(family) || staleByClock.has(family));
|
|
2664
|
+
if (selected.length === 0) return;
|
|
2665
|
+
startLocalStats(ctx);
|
|
2666
|
+
const outcomes = await Promise.all(selected.map((family) => refreshFamily(ctx, family, force)));
|
|
2667
|
+
if (outcomes.every(Boolean) && inFlight.size === 0 && report && resultGeneration !== prunedGeneration) {
|
|
2668
|
+
try {
|
|
2669
|
+
publishOmarchy(report, true);
|
|
2670
|
+
prunedGeneration = resultGeneration;
|
|
2671
|
+
} catch {
|
|
2672
|
+
// Keep fresh quota data even if the optional final stale-record prune fails.
|
|
1055
2673
|
}
|
|
1056
|
-
} finally {
|
|
1057
|
-
refreshing = false;
|
|
1058
2674
|
}
|
|
1059
2675
|
}
|
|
1060
2676
|
|
|
@@ -1063,6 +2679,8 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
1063
2679
|
const ui = ctx as unknown as UiContext;
|
|
1064
2680
|
if (!ui.hasUI) return;
|
|
1065
2681
|
disposed = false;
|
|
2682
|
+
// A new session starts with every section open, on the Now page.
|
|
2683
|
+
overlaySession = newOverlaySession();
|
|
1066
2684
|
// Resolve the native rail mode before the first paint.
|
|
1067
2685
|
await syncRailPatch();
|
|
1068
2686
|
if (disposed) return;
|
|
@@ -1072,17 +2690,7 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
1072
2690
|
paintUi(ui);
|
|
1073
2691
|
});
|
|
1074
2692
|
|
|
1075
|
-
|
|
1076
|
-
panelVisible = false;
|
|
1077
|
-
transientPanel = false;
|
|
1078
|
-
if (!surfaceActive()) stopPolling();
|
|
1079
|
-
paintUi(ui);
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
pi.on("agent_start", (_event, ctx) => {
|
|
1083
|
-
// SAFETY: Pi's agent_start context implements UiContext when hasUI is true.
|
|
1084
|
-
const ui = ctx as unknown as UiContext;
|
|
1085
|
-
if (transientPanel && panelVisible && ui?.hasUI && !disposed) dismissTransientPanel(ui);
|
|
2693
|
+
pi.on("agent_start", () => {
|
|
1086
2694
|
if (agentEndTimer) {
|
|
1087
2695
|
clearTimeout(agentEndTimer);
|
|
1088
2696
|
agentEndTimer = null;
|
|
@@ -1122,8 +2730,93 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
1122
2730
|
ui.ui.setStatus(STATUS_KEY, undefined);
|
|
1123
2731
|
ui.ui.setWidget(WIDGET_KEY, undefined);
|
|
1124
2732
|
}
|
|
2733
|
+
// Pi awaits session_shutdown (reason "reload" included), so the scan is gone
|
|
2734
|
+
// and its lock released before the next session or the process starts.
|
|
2735
|
+
await stopLocalStats();
|
|
1125
2736
|
});
|
|
1126
2737
|
|
|
2738
|
+
/**
|
|
2739
|
+
* Read one month (null: the current local month) in-process and hand the
|
|
2740
|
+
* aggregate-only payload to the overlay. Read-only, no lock: historyJson only reads.
|
|
2741
|
+
*
|
|
2742
|
+
* A reader failure is redacted and limited to one line. The JSON parser's
|
|
2743
|
+
* "Unexpected end of JSON input" says nothing about the cause.
|
|
2744
|
+
*/
|
|
2745
|
+
async function loadHistory(month: string | null, request: number): Promise<void> {
|
|
2746
|
+
try {
|
|
2747
|
+
const parsed = await readHistory(month);
|
|
2748
|
+
if (!parsed || !Array.isArray(parsed.months)) {
|
|
2749
|
+
overlayView?.setHistoryError("piquota stats returned no history payload", request);
|
|
2750
|
+
return;
|
|
2751
|
+
}
|
|
2752
|
+
overlayView?.setHistory(parsed, request);
|
|
2753
|
+
} catch (error) {
|
|
2754
|
+
const message = (error as { message?: string })?.message ?? String(error);
|
|
2755
|
+
overlayView?.setHistoryError(capCause(redactCause(message).split("\n")[0]), request);
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
|
|
2759
|
+
/**
|
|
2760
|
+
* Bare /usage: a fullscreen overlay that owns the keyboard and closes on Esc,
|
|
2761
|
+
* so no panel is left above the editor. It opens with the cached report and
|
|
2762
|
+
* refreshes in the background; a failure becomes a line in the view.
|
|
2763
|
+
*/
|
|
2764
|
+
async function showOverlay(ctx: UiContext): Promise<void> {
|
|
2765
|
+
// Paint on the same keystroke: the report already in memory, otherwise the
|
|
2766
|
+
// on-disk cache. Only stale families refresh behind the overlay; the first
|
|
2767
|
+
// frame never waits for the network.
|
|
2768
|
+
report = ensureReport();
|
|
2769
|
+
const custom = ctx.ui.custom;
|
|
2770
|
+
if (typeof custom !== "function" || (ctx.mode !== undefined && ctx.mode !== "tui")) {
|
|
2771
|
+
// A host without custom components still gets the panel that /usage panel pins.
|
|
2772
|
+
panelVisible = true;
|
|
2773
|
+
lineVisible = false;
|
|
2774
|
+
boxVisible = false;
|
|
2775
|
+
explicitBox = false;
|
|
2776
|
+
report = ensureReport();
|
|
2777
|
+
void refresh(ctx, false);
|
|
2778
|
+
ensurePolling(ctx);
|
|
2779
|
+
paintUi(ctx);
|
|
2780
|
+
ctx.ui.notify("This host has no fullscreen overlay; the quota panel is pinned above the editor", "info");
|
|
2781
|
+
return;
|
|
2782
|
+
}
|
|
2783
|
+
await custom(
|
|
2784
|
+
(tui, theme, _keybindings, done) => {
|
|
2785
|
+
const view = new UsageOverlay(theme, {
|
|
2786
|
+
done: () => done(undefined),
|
|
2787
|
+
requestRender: () => tui?.requestRender?.(),
|
|
2788
|
+
getRows: () => tui?.terminal?.rows ?? process.stdout.rows ?? 24,
|
|
2789
|
+
getReport: () => report,
|
|
2790
|
+
getErrors: () => errorLines(),
|
|
2791
|
+
isRefreshing: () => isRefreshing(),
|
|
2792
|
+
refresh: () => {
|
|
2793
|
+
void refresh(ctx, true);
|
|
2794
|
+
},
|
|
2795
|
+
loadHistory: (month, request) => {
|
|
2796
|
+
void loadHistory(month, request);
|
|
2797
|
+
},
|
|
2798
|
+
}, overlaySession);
|
|
2799
|
+
overlayView = view;
|
|
2800
|
+
// A view reopened on History holds no payload: ask for its month.
|
|
2801
|
+
view.begin();
|
|
2802
|
+
return {
|
|
2803
|
+
render: (width: number) => view.render(width),
|
|
2804
|
+
invalidate: () => view.invalidate(),
|
|
2805
|
+
dispose: () => {
|
|
2806
|
+
if (overlayView === view) overlayView = null;
|
|
2807
|
+
view.dispose();
|
|
2808
|
+
},
|
|
2809
|
+
handleInput: (data: string) => {
|
|
2810
|
+
view.handleInput(data);
|
|
2811
|
+
tui?.requestRender?.();
|
|
2812
|
+
},
|
|
2813
|
+
handleMouse: (event: any) => view.handleMouse(event),
|
|
2814
|
+
};
|
|
2815
|
+
},
|
|
2816
|
+
{ overlay: true, overlayOptions: { width: "100%", maxHeight: "100%", margin: 0 } },
|
|
2817
|
+
);
|
|
2818
|
+
}
|
|
2819
|
+
|
|
1127
2820
|
const handler = async (args: string, ctx: UiContext): Promise<void> => {
|
|
1128
2821
|
if (!ctx.hasUI) return;
|
|
1129
2822
|
const action = args.trim().toLowerCase();
|
|
@@ -1131,10 +2824,11 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
1131
2824
|
switch (action) {
|
|
1132
2825
|
case "refresh":
|
|
1133
2826
|
await refresh(ctx, true);
|
|
2827
|
+
const failures = errorLines();
|
|
1134
2828
|
ctx.ui.notify(
|
|
1135
2829
|
report
|
|
1136
2830
|
? `Quota refreshed (${report.providers.filter((provider) => provider.ok).length}/${report.providers.length} providers)`
|
|
1137
|
-
: `Quota refresh failed: ${
|
|
2831
|
+
: `Quota refresh failed: ${failures.length > 1 ? `${failures[0]} (+${failures.length - 1} more)` : failures[0] ?? "unknown error"}`,
|
|
1138
2832
|
report ? "info" : "error",
|
|
1139
2833
|
);
|
|
1140
2834
|
return;
|
|
@@ -1144,18 +2838,21 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
1144
2838
|
boxVisible = false;
|
|
1145
2839
|
explicitBox = false;
|
|
1146
2840
|
panelVisible = false;
|
|
2841
|
+
report = ensureReport();
|
|
1147
2842
|
if (!report) await refresh(ctx, false);
|
|
2843
|
+
else void refresh(ctx, false);
|
|
1148
2844
|
ensurePolling(ctx);
|
|
1149
2845
|
paintUi(ctx);
|
|
1150
2846
|
ctx.ui.notify("Quota line pinned above the editor", "info");
|
|
1151
2847
|
return;
|
|
1152
2848
|
case "panel":
|
|
1153
2849
|
panelVisible = true;
|
|
1154
|
-
transientPanel = false;
|
|
1155
2850
|
lineVisible = false;
|
|
1156
2851
|
boxVisible = false;
|
|
1157
2852
|
explicitBox = false;
|
|
2853
|
+
report = ensureReport();
|
|
1158
2854
|
if (!report) await refresh(ctx, false);
|
|
2855
|
+
else void refresh(ctx, false);
|
|
1159
2856
|
ensurePolling(ctx);
|
|
1160
2857
|
paintUi(ctx);
|
|
1161
2858
|
ctx.ui.notify("Quota panel shown above the editor", "info");
|
|
@@ -1165,7 +2862,9 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
1165
2862
|
boxVisible = true;
|
|
1166
2863
|
explicitBox = true;
|
|
1167
2864
|
panelVisible = false;
|
|
2865
|
+
report = ensureReport();
|
|
1168
2866
|
if (!report) await refresh(ctx, false);
|
|
2867
|
+
else void refresh(ctx, false);
|
|
1169
2868
|
ensurePolling(ctx);
|
|
1170
2869
|
paintUi(ctx);
|
|
1171
2870
|
ctx.ui.notify("Quota box pinned above the editor", "info");
|
|
@@ -1192,35 +2891,21 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
1192
2891
|
paintUi(ctx);
|
|
1193
2892
|
return;
|
|
1194
2893
|
case "json":
|
|
1195
|
-
ctx.ui.notify(
|
|
2894
|
+
ctx.ui.notify(`Report cache: ${reportCachePath()}`, "info");
|
|
1196
2895
|
return;
|
|
1197
2896
|
default:
|
|
1198
2897
|
break;
|
|
1199
2898
|
}
|
|
1200
2899
|
|
|
1201
|
-
// Bare /usage
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
// Bare /usage: one on-demand refresh, show the panel, report the percentages.
|
|
1208
|
-
panelVisible = true;
|
|
1209
|
-
transientPanel = true;
|
|
1210
|
-
lineVisible = false;
|
|
1211
|
-
boxVisible = false;
|
|
1212
|
-
await refresh(ctx, true);
|
|
1213
|
-
ensurePolling(ctx);
|
|
1214
|
-
paintUi(ctx);
|
|
1215
|
-
if (!report) {
|
|
1216
|
-
ctx.ui.notify(`Quota unavailable: ${lastError}`, "error");
|
|
1217
|
-
return;
|
|
1218
|
-
}
|
|
1219
|
-
ctx.ui.notify(summarize(report) || "No active providers configured in Pi", "info");
|
|
2900
|
+
// Bare /usage (or an unknown argument): open the overlay with whatever the
|
|
2901
|
+
// extension already has, and refresh in the background behind it.
|
|
2902
|
+
const opening = showOverlay(ctx);
|
|
2903
|
+
void refresh(ctx, false);
|
|
2904
|
+
await opening;
|
|
1220
2905
|
};
|
|
1221
2906
|
|
|
1222
2907
|
pi.registerCommand("usage", {
|
|
1223
|
-
description: "
|
|
2908
|
+
description: "Open the read-only quota overlay (used %, one foldable section per provider)",
|
|
1224
2909
|
getArgumentCompletions: (prefix: string) => {
|
|
1225
2910
|
const options = ["refresh", "line", "box", "panel", "hide", "status", "nostatus", "json"];
|
|
1226
2911
|
const matches = options.filter((option) => option.startsWith(prefix));
|