pi-usage-hub 1.1.4 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,6 +25,8 @@ pi install npm:pi-usage-hub
25
25
 
26
26
  Inside the panel, **Tab** switches between Quota and Session. In the Quota view, **↑↓** scrolls when content overflows.
27
27
 
28
+ The Session view scans the local session history in the background: the panel renders immediately and the numbers grow as files are read (newest files first, so today/week fill in first), with a `Scanning… n/total` footer while it runs. The result is kept for the whole process, and reopening the panel only re-reads files whose size or mtime changed — usually a few tens of milliseconds. **r** rebuilds it from scratch.
29
+
28
30
  ![pi-usage-hub quota panel](assets/usage-hub-panel.png)
29
31
 
30
32
  ![pi-usage-hub session panel](assets/usage-hub-session.png)
package/core/cache.ts CHANGED
@@ -14,6 +14,7 @@ type Subscriber = (e: { key: string; summary: string | null }) => void;
14
14
  export class UsageCache {
15
15
  private entries = new Map<string, CacheEntry>();
16
16
  private inflight = new Map<string, Promise<CacheEntry>>();
17
+ private generation = new Map<string, number>();
17
18
  private subscribers = new Set<Subscriber>();
18
19
 
19
20
  constructor(private ttlMs = DEFAULT_TTL_MS) {}
@@ -28,13 +29,19 @@ export class UsageCache {
28
29
 
29
30
  invalidate(key?: string): void {
30
31
  if (key) {
31
- this.entries.delete(key);
32
- this.notify(key, null);
32
+ this.drop(key);
33
33
  return;
34
34
  }
35
- const keys = [...this.entries.keys()];
36
- this.entries.clear();
37
- for (const k of keys) this.notify(k, null);
35
+ const keys = new Set([...this.entries.keys(), ...this.inflight.keys()]);
36
+ for (const k of keys) this.drop(k);
37
+ }
38
+
39
+ /** Bump the generation so requests started before this point cannot repopulate the cache. */
40
+ private drop(key: string): void {
41
+ this.generation.set(key, (this.generation.get(key) ?? 0) + 1);
42
+ this.inflight.delete(key);
43
+ this.entries.delete(key);
44
+ this.notify(key, null);
38
45
  }
39
46
 
40
47
  subscribe(fn: Subscriber): () => void {
@@ -48,10 +55,13 @@ export class UsageCache {
48
55
  const hit = this.entries.get(provider.key);
49
56
  if (!force && hit && Date.now() - hit.fetchedAt < this.ttlMs) return hit;
50
57
 
51
- const existing = this.inflight.get(provider.key);
58
+ const key = provider.key;
59
+ const existing = this.inflight.get(key);
52
60
  if (existing) return existing;
53
61
 
54
- const job = (async () => {
62
+ const generation = this.generation.get(key) ?? 0;
63
+ let job: Promise<CacheEntry>;
64
+ job = (async () => {
55
65
  let report: UsageReport;
56
66
  try {
57
67
  report = await provider.fetchUsage();
@@ -63,14 +73,16 @@ export class UsageCache {
63
73
  summary: shortReport(report, provider),
64
74
  fetchedAt: Date.now(),
65
75
  };
66
- this.entries.set(provider.key, entry);
67
- this.notify(provider.key, entry.summary);
76
+ if ((this.generation.get(key) ?? 0) === generation) {
77
+ this.entries.set(key, entry);
78
+ this.notify(key, entry.summary);
79
+ }
68
80
  return entry;
69
81
  })().finally(() => {
70
- this.inflight.delete(provider.key);
82
+ if (this.inflight.get(key) === job) this.inflight.delete(key);
71
83
  });
72
84
 
73
- this.inflight.set(provider.key, job);
85
+ this.inflight.set(key, job);
74
86
  return job;
75
87
  }
76
88
 
package/core/registry.ts CHANGED
@@ -112,9 +112,13 @@ export class ProviderRegistry {
112
112
  matchModel(model?: { provider?: string }): UsageProvider | null {
113
113
  const current = model?.provider;
114
114
  if (!current) return null;
115
- return this.detectActive().find(p =>
116
- p.key === current || (p.matchProviders?.includes(current) ?? false),
117
- ) ?? null;
115
+ const matches = (p: UsageProvider) =>
116
+ p.key === current || (p.matchProviders?.includes(current) ?? false);
117
+ // Match by name first: detect() may read credentials synchronously (Chrome cookie DB),
118
+ // and this runs on every footer update.
119
+ const direct = this.list().find(p => !p.hidden && matches(p));
120
+ if (direct) return direct;
121
+ return this.detectActive().find(matches) ?? null;
118
122
  }
119
123
 
120
124
  loadFromConfig(providers: ProviderConfig[]): void {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-usage-hub",
3
- "version": "1.1.4",
3
+ "version": "1.2.0",
4
4
  "description": "Usage hub for pi — provider quota/balance registry with cache, /usage-hub panel, and pull API",
5
5
  "keywords": [
6
6
  "pi",
package/providers/ark.ts CHANGED
@@ -117,7 +117,7 @@ export function makeArkProvider(name: string, cfg: ArkConfig = {}): UsageProvide
117
117
  return {
118
118
  error: manual
119
119
  ? "invalid cookie in config"
120
- : "not logged in — set cookie in config or /usage-hub login ark",
120
+ : `not logged in — set cookie in config or /usage-hub login ${name}`,
121
121
  };
122
122
  }
123
123
  const result = await callApi(auth.cookieHeader, auth.csrf);
@@ -125,7 +125,7 @@ export function makeArkProvider(name: string, cfg: ArkConfig = {}): UsageProvide
125
125
  return {
126
126
  error: manual
127
127
  ? "session expired — refresh cookie in config"
128
- : "session expired — run /usage-hub login ark",
128
+ : `session expired — run /usage-hub login ${name}`,
129
129
  };
130
130
  }
131
131
  return result;
@@ -36,6 +36,33 @@ function toWindow(
36
36
  return { pct: (used / limit) * 100, resetsIn: formatDurationSeconds(resetsInSec) };
37
37
  }
38
38
 
39
+ async function fetchStatus(session: string, workspaceId: string): Promise<Response> {
40
+ const controller = new AbortController();
41
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
42
+ try {
43
+ return await fetch(STATUS_URL, {
44
+ headers: {
45
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Gecko/20100101 Firefox/148.0",
46
+ Accept: "application/json",
47
+ "x-org-id": workspaceId,
48
+ Cookie: `${SESSION_COOKIE}=${session}`,
49
+ },
50
+ signal: controller.signal,
51
+ });
52
+ } finally {
53
+ clearTimeout(timer);
54
+ }
55
+ }
56
+
57
+ /** A cookie that exists locally may still be revoked server-side. */
58
+ async function sessionWorks(session: string, workspaceId: string): Promise<boolean> {
59
+ try {
60
+ return (await fetchStatus(session, workspaceId)).ok;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
39
66
  export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): UsageProvider {
40
67
  const workspaceId = cfg.workspaceId;
41
68
  const manual = !!cfg.auth?.trim();
@@ -56,26 +83,15 @@ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): Usa
56
83
  return {
57
84
  error: manual
58
85
  ? "invalid auth in config"
59
- : "not logged in — set auth in config or /usage-hub login ocg",
86
+ : `not logged in — set auth in config or /usage-hub login ${name}`,
60
87
  };
61
88
  }
62
89
 
63
- const controller = new AbortController();
64
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
65
-
66
90
  try {
67
- const res = await fetch(STATUS_URL, {
68
- headers: {
69
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Gecko/20100101 Firefox/148.0",
70
- Accept: "application/json",
71
- "x-org-id": workspaceId,
72
- Cookie: `${SESSION_COOKIE}=${session}`,
73
- },
74
- signal: controller.signal,
75
- });
91
+ const res = await fetchStatus(session, workspaceId);
76
92
 
77
93
  if (res.status === 401 || res.status === 403) {
78
- return { error: "session expired — /usage-hub login ocg" };
94
+ return { error: `session expired — /usage-hub login ${name}` };
79
95
  }
80
96
  if (!res.ok) return { error: `HTTP ${res.status}` };
81
97
 
@@ -100,8 +116,6 @@ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): Usa
100
116
  } catch (err: any) {
101
117
  if (err?.name === "AbortError") return { error: "timeout" };
102
118
  return { error: err?.message ?? String(err) };
103
- } finally {
104
- clearTimeout(timer);
105
119
  }
106
120
  },
107
121
 
@@ -109,11 +123,21 @@ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): Usa
109
123
  ? undefined
110
124
  : async (): Promise<boolean> => {
111
125
  if (!workspaceId) return false;
126
+ const before = readChromeSessionCookie();
127
+ if (before && await sessionWorks(before, workspaceId)) return true;
112
128
  execFile("open", ["-a", "Google Chrome", `https://opencode.ai/console/${workspaceId}/go`]);
113
129
  const deadline = Date.now() + 300_000;
130
+ let probed: string | null = null;
131
+ let probeCount = 0;
114
132
  while (Date.now() < deadline) {
115
133
  await new Promise(r => setTimeout(r, 2000));
116
- if (readChromeSessionCookie()) return true;
134
+ const current = readChromeSessionCookie();
135
+ if (!current || current === before) continue;
136
+ // Probe a new cookie value at most twice, so a stuck session cannot spin requests.
137
+ if (current === probed && probeCount >= 2) continue;
138
+ probeCount = current === probed ? probeCount + 1 : 1;
139
+ probed = current;
140
+ if (await sessionWorks(current, workspaceId)) return true;
117
141
  }
118
142
  return false;
119
143
  },
package/providers/xai.ts CHANGED
@@ -98,14 +98,14 @@ function isFresh(credentials: XaiCredentials): boolean {
98
98
  function validateTokenEndpoint(url: string): string {
99
99
  const normalized = url.replace(/\/$/, "");
100
100
  if (normalized !== DEFAULT_TOKEN_ENDPOINT) {
101
- throw new Error("unexpected xAI token endpoint — run /login xai-auth");
101
+ throw new Error("unexpected xAI token endpoint — run /login xai");
102
102
  }
103
103
  return DEFAULT_TOKEN_ENDPOINT;
104
104
  }
105
105
 
106
106
  async function refreshCredentials(credentials: XaiCredentials): Promise<XaiCredentials> {
107
107
  if (!credentials.refresh) {
108
- throw new Error("session expired — run /login xai-auth");
108
+ throw new Error("session expired — run /login xai");
109
109
  }
110
110
 
111
111
  const tokenEndpoint = validateTokenEndpoint(credentials.tokenEndpoint || DEFAULT_TOKEN_ENDPOINT);
@@ -283,13 +283,13 @@ export function makeXaiProvider(name: string, cfg: XaiConfig = {}): UsageProvide
283
283
  fetchUsage: async (): Promise<UsageReport> => {
284
284
  try {
285
285
  const credentials = await getCredentials(false);
286
- if (!credentials) return { error: "not logged in — run /login xai-auth" };
286
+ if (!credentials) return { error: "not logged in — run /login xai" };
287
287
  try {
288
288
  return mapUsage(await fetchBillingUsage(credentials.access));
289
289
  } catch (err) {
290
290
  if (!isUnauthorized(err)) throw err;
291
291
  const refreshed = await getCredentials(true);
292
- if (!refreshed) return { error: "session expired — run /login xai-auth" };
292
+ if (!refreshed) return { error: "session expired — run /login xai" };
293
293
  return mapUsage(await fetchBillingUsage(refreshed.access));
294
294
  }
295
295
  } catch (err: any) {
@@ -1,4 +1,4 @@
1
- import { readdir, readFile } from "node:fs/promises";
1
+ import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
 
@@ -72,16 +72,26 @@ function getSessionsDir(): string {
72
72
  return join(agentDir, "sessions");
73
73
  }
74
74
 
75
- async function collectSessionFiles(dir: string, files: string[], signal?: AbortSignal): Promise<void> {
75
+ interface SessionFile {
76
+ path: string;
77
+ size: number;
78
+ mtimeMs: number;
79
+ }
80
+
81
+ async function collectSessionFiles(dir: string, files: SessionFile[]): Promise<void> {
76
82
  try {
77
83
  const entries = await readdir(dir, { withFileTypes: true });
78
84
  for (const entry of entries) {
79
- if (signal?.aborted) return;
80
85
  const entryPath = join(dir, entry.name);
81
86
  if (entry.isDirectory()) {
82
- await collectSessionFiles(entryPath, files, signal);
87
+ await collectSessionFiles(entryPath, files);
83
88
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
84
- files.push(entryPath);
89
+ try {
90
+ const info = await stat(entryPath);
91
+ files.push({ path: entryPath, size: info.size, mtimeMs: info.mtimeMs });
92
+ } catch {
93
+ // The file can vanish between readdir and stat.
94
+ }
85
95
  }
86
96
  }
87
97
  } catch {
@@ -124,21 +134,16 @@ function periodsFor(timestamp: number, todayMs: number, weekStartMs: number, mon
124
134
  return periods;
125
135
  }
126
136
 
127
- async function parseSessionFile(
128
- filePath: string,
129
- seenHashes: Set<string>,
130
- signal?: AbortSignal,
131
- ): Promise<{ sessionId: string; messages: SessionMessage[] } | null> {
137
+ async function parseSessionFile(filePath: string): Promise<{ sessionId: string; messages: SessionMessage[] } | null> {
132
138
  try {
133
139
  const content = await readFile(filePath, "utf8");
134
- if (signal?.aborted) return null;
135
140
 
136
141
  let sessionId = "";
137
142
  const messages: SessionMessage[] = [];
138
143
  const lines = content.trim().split("\n");
139
144
 
140
145
  for (let i = 0; i < lines.length; i++) {
141
- if (signal?.aborted) return null;
146
+ // 大文件也要让出事件循环,否则扫描期间按键和渲染都会卡
142
147
  if (i % 500 === 0) await new Promise<void>(resolve => setImmediate(resolve));
143
148
 
144
149
  const line = lines[i]?.trim();
@@ -160,11 +165,6 @@ async function parseSessionFile(
160
165
  const cacheWrite = msg.usage.cacheWrite || 0;
161
166
  const fallbackTs = entry.timestamp ? new Date(entry.timestamp).getTime() : 0;
162
167
  const timestamp = msg.timestamp || (Number.isNaN(fallbackTs) ? 0 : fallbackTs);
163
- const totalTokens = input + output + cacheRead + cacheWrite;
164
- const hash = `${timestamp}:${totalTokens}`;
165
- if (seenHashes.has(hash)) continue;
166
- seenHashes.add(hash);
167
-
168
168
  messages.push({
169
169
  provider: msg.provider,
170
170
  model: msg.model || "unknown",
@@ -212,60 +212,67 @@ function finalizePeriod(period: MutablePeriod): SessionUsagePeriod {
212
212
  };
213
213
  }
214
214
 
215
- export async function collectSessionUsage(signal?: AbortSignal): Promise<SessionUsageSummary> {
215
+ function periodBoundaries() {
216
216
  const startOfToday = new Date();
217
217
  startOfToday.setHours(0, 0, 0, 0);
218
- const todayMs = startOfToday.getTime();
219
218
 
220
219
  const startOfWeek = new Date();
221
220
  const dayOfWeek = startOfWeek.getDay();
222
- const daysSinceMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
223
- startOfWeek.setDate(startOfWeek.getDate() - daysSinceMonday);
221
+ startOfWeek.setDate(startOfWeek.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));
224
222
  startOfWeek.setHours(0, 0, 0, 0);
225
- const weekStartMs = startOfWeek.getTime();
226
223
 
227
224
  const startOfMonth = new Date();
228
225
  startOfMonth.setDate(1);
229
226
  startOfMonth.setHours(0, 0, 0, 0);
230
- const monthStartMs = startOfMonth.getTime();
231
227
 
232
- const periods: Record<PeriodName, MutablePeriod> = {
228
+ return {
229
+ todayMs: startOfToday.getTime(),
230
+ weekStartMs: startOfWeek.getTime(),
231
+ monthStartMs: startOfMonth.getTime(),
232
+ };
233
+ }
234
+
235
+ function emptyPeriods(): Record<PeriodName, MutablePeriod> {
236
+ return {
233
237
  today: emptyPeriod(),
234
238
  thisWeek: emptyPeriod(),
235
239
  thisMonth: emptyPeriod(),
236
240
  allTime: emptyPeriod(),
237
241
  };
242
+ }
238
243
 
239
- const files: string[] = [];
240
- await collectSessionFiles(getSessionsDir(), files, signal);
241
- files.sort();
242
-
243
- const seenHashes = new Set<string>();
244
- for (const file of files) {
245
- if (signal?.aborted) break;
246
- const parsed = await parseSessionFile(file, seenHashes, signal);
247
- if (!parsed) continue;
248
-
249
- for (const message of parsed.messages) {
250
- for (const periodName of periodsFor(message.timestamp, todayMs, weekStartMs, monthStartMs)) {
251
- const period = periods[periodName];
252
- let provider = period.providers.get(message.provider);
253
- if (!provider) {
254
- provider = emptyProvider();
255
- period.providers.set(message.provider, provider);
256
- }
257
- let model = provider.models.get(message.model);
258
- if (!model) {
259
- model = emptyStats();
260
- provider.models.set(message.model, model);
261
- }
262
- addStats(model, parsed.sessionId, message);
263
- addStats(provider, parsed.sessionId, message);
264
- addStats(period.totals, parsed.sessionId, message);
244
+ function accumulateMessages(
245
+ periods: Record<PeriodName, MutablePeriod>,
246
+ sessionId: string,
247
+ messages: SessionMessage[],
248
+ seenHashes: Set<string>,
249
+ boundaries: { todayMs: number; weekStartMs: number; monthStartMs: number },
250
+ ): void {
251
+ for (const message of messages) {
252
+ const hash = `${message.timestamp}:${message.input + message.output + message.cacheRead + message.cacheWrite}`;
253
+ if (seenHashes.has(hash)) continue;
254
+ seenHashes.add(hash);
255
+
256
+ for (const periodName of periodsFor(message.timestamp, boundaries.todayMs, boundaries.weekStartMs, boundaries.monthStartMs)) {
257
+ const period = periods[periodName]!;
258
+ let provider = period.providers.get(message.provider);
259
+ if (!provider) {
260
+ provider = emptyProvider();
261
+ period.providers.set(message.provider, provider);
265
262
  }
263
+ let model = provider.models.get(message.model);
264
+ if (!model) {
265
+ model = emptyStats();
266
+ provider.models.set(message.model, model);
267
+ }
268
+ addStats(model, sessionId, message);
269
+ addStats(provider, sessionId, message);
270
+ addStats(period.totals, sessionId, message);
266
271
  }
267
272
  }
273
+ }
268
274
 
275
+ function finalizeAll(periods: Record<PeriodName, MutablePeriod>): SessionUsageSummary {
269
276
  return {
270
277
  today: finalizePeriod(periods.today),
271
278
  thisWeek: finalizePeriod(periods.thisWeek),
@@ -273,3 +280,150 @@ export async function collectSessionUsage(signal?: AbortSignal): Promise<Session
273
280
  allTime: finalizePeriod(periods.allTime),
274
281
  };
275
282
  }
283
+
284
+ export interface SessionUsageProgress {
285
+ scanned: number;
286
+ total: number;
287
+ running: boolean;
288
+ }
289
+
290
+ interface CachedFile {
291
+ size: number;
292
+ mtimeMs: number;
293
+ sessionId: string;
294
+ messages: SessionMessage[];
295
+ }
296
+
297
+ const EMIT_INTERVAL_MS = 120;
298
+ const EMIT_EVERY_FILES = 25;
299
+
300
+ /**
301
+ * 渐进式扫描器:逐文件累加,约每 120ms 推一次快照,面板不必等全量扫完才出结果。
302
+ * 进程内单例,关掉面板不丢结果;再次打开只补扫 size/mtime 变过的文件。
303
+ */
304
+ export class SessionUsageScanner {
305
+ private cache = new Map<string, CachedFile>();
306
+ private summary: SessionUsageSummary | null = null;
307
+ private error = "";
308
+ private progress: SessionUsageProgress = { scanned: 0, total: 0, running: false };
309
+ private listeners = new Set<() => void>();
310
+ private run: Promise<void> | null = null;
311
+ private generation = 0;
312
+
313
+ getSummary(): SessionUsageSummary | null {
314
+ return this.summary;
315
+ }
316
+
317
+ getError(): string {
318
+ return this.error;
319
+ }
320
+
321
+ getProgress(): SessionUsageProgress {
322
+ return this.progress;
323
+ }
324
+
325
+ subscribe(listener: () => void): () => void {
326
+ this.listeners.add(listener);
327
+ return () => {
328
+ this.listeners.delete(listener);
329
+ };
330
+ }
331
+
332
+ /** 首次打开面板才开始扫;已有结果时做一次只补差异的刷新 */
333
+ ensureStarted(): Promise<void> {
334
+ if (this.run) return this.run;
335
+ return this.start(this.summary ? "refresh" : "full");
336
+ }
337
+
338
+ /** 丢弃缓存从头扫(面板里按 r) */
339
+ rescan(): Promise<void> {
340
+ this.cache.clear();
341
+ this.summary = null;
342
+ this.error = "";
343
+ return this.start("full");
344
+ }
345
+
346
+ private start(mode: "full" | "refresh"): Promise<void> {
347
+ const generation = ++this.generation;
348
+ const run = this.execute(generation, mode).finally(() => {
349
+ if (generation === this.generation) this.run = null;
350
+ });
351
+ this.run = run;
352
+ return run;
353
+ }
354
+
355
+ private emit(): void {
356
+ for (const listener of [...this.listeners]) listener();
357
+ }
358
+
359
+ private async execute(generation: number, mode: "full" | "refresh"): Promise<void> {
360
+ const boundaries = periodBoundaries();
361
+ const files: SessionFile[] = [];
362
+ try {
363
+ await collectSessionFiles(getSessionsDir(), files);
364
+ } catch (error) {
365
+ this.error = error instanceof Error ? error.message : String(error);
366
+ this.progress = { ...this.progress, running: false };
367
+ this.emit();
368
+ return;
369
+ }
370
+ if (generation !== this.generation) return;
371
+
372
+ // 新文件先扫:当前会话的 today/week 先准,allTime 随后补齐
373
+ files.sort((a, b) => b.mtimeMs - a.mtimeMs);
374
+
375
+ const periods = emptyPeriods();
376
+ const seenHashes = new Set<string>();
377
+ const live = new Set<string>();
378
+ this.progress = { scanned: 0, total: files.length, running: true };
379
+ this.emit();
380
+
381
+ let lastEmit = Date.now();
382
+ for (const file of files) {
383
+ if (generation !== this.generation) return;
384
+ live.add(file.path);
385
+
386
+ let cached = this.cache.get(file.path);
387
+ if (!cached || cached.size !== file.size || cached.mtimeMs !== file.mtimeMs) {
388
+ const parsed = await parseSessionFile(file.path);
389
+ if (generation !== this.generation) return;
390
+ cached = {
391
+ size: file.size,
392
+ mtimeMs: file.mtimeMs,
393
+ sessionId: parsed?.sessionId ?? "",
394
+ messages: parsed?.messages ?? [],
395
+ };
396
+ this.cache.set(file.path, cached);
397
+ }
398
+
399
+ if (cached.sessionId) accumulateMessages(periods, cached.sessionId, cached.messages, seenHashes, boundaries);
400
+
401
+ this.progress = { scanned: this.progress.scanned + 1, total: this.progress.total, running: true };
402
+ if (this.progress.scanned % EMIT_EVERY_FILES === 0 || Date.now() - lastEmit >= EMIT_INTERVAL_MS) {
403
+ this.summary = finalizeAll(periods);
404
+ this.emit();
405
+ lastEmit = Date.now();
406
+ }
407
+ }
408
+
409
+ if (generation !== this.generation) return;
410
+ if (mode === "full") {
411
+ for (const path of this.cache.keys()) {
412
+ if (!live.has(path)) this.cache.delete(path);
413
+ }
414
+ }
415
+
416
+ this.summary = finalizeAll(periods);
417
+ this.progress = { ...this.progress, running: false };
418
+ this.emit();
419
+ }
420
+ }
421
+
422
+ /** 进程级共享:面板反复打开都复用同一份扫描结果 */
423
+ export const sessionUsageScanner = new SessionUsageScanner();
424
+
425
+ export async function collectSessionUsage(): Promise<SessionUsageSummary> {
426
+ const scanner = new SessionUsageScanner();
427
+ await scanner.ensureStarted();
428
+ return scanner.getSummary()!;
429
+ }
@@ -5,7 +5,8 @@
5
5
  import type { Theme } from "@earendil-works/pi-coding-agent";
6
6
  import { Key, matchesKey } from "@earendil-works/pi-tui";
7
7
  import {
8
- collectSessionUsage,
8
+ sessionUsageScanner,
9
+ type SessionUsageScanner,
9
10
  type ProviderSessionUsage,
10
11
  type SessionUsagePeriod,
11
12
  type SessionUsageSummary,
@@ -53,32 +54,27 @@ function statCols(name: string, t: { sessions: number; messages: number; cost: n
53
54
  }
54
55
 
55
56
  export class SessionPanel {
56
- private loading = false;
57
- private usage: SessionUsageSummary | null = null;
58
- private error = "";
59
- private load: Promise<void> | null = null;
60
57
  private periodIndex = 0;
61
58
  private providerIndex = 0;
62
59
  private expanded = new Set<string>();
63
-
64
- constructor(private requestRender: () => void) {}
60
+ private unsubscribe: (() => void) | null = null;
61
+
62
+ constructor(
63
+ private requestRender: () => void,
64
+ private scanner: SessionUsageScanner = sessionUsageScanner,
65
+ ) {
66
+ // 扫描器边扫边推快照,面板跟着重绘
67
+ this.unsubscribe = this.scanner.subscribe(() => this.requestRender());
68
+ }
65
69
 
66
70
  ensureLoaded(): void {
67
- if (this.usage || this.load) return;
68
- this.loading = true;
69
- this.error = "";
70
- this.load = collectSessionUsage()
71
- .then(usage => {
72
- this.usage = usage;
73
- })
74
- .catch(err => {
75
- this.error = err?.message ?? String(err);
76
- })
77
- .finally(() => {
78
- this.loading = false;
79
- this.load = null;
80
- this.requestRender();
81
- });
71
+ void this.scanner.ensureStarted();
72
+ }
73
+
74
+ /** Overlay 关闭时调用:pi-tui 不会替组件断订阅 */
75
+ dispose(): void {
76
+ this.unsubscribe?.();
77
+ this.unsubscribe = null;
82
78
  }
83
79
 
84
80
  /** Handle a key. Returns true if the panel consumed it. */
@@ -102,6 +98,13 @@ export class SessionPanel {
102
98
  return true;
103
99
  }
104
100
 
101
+ // r: rebuild the cache from scratch
102
+ if (data === "r" || data === "R") {
103
+ void this.scanner.rescan();
104
+ this.requestRender();
105
+ return true;
106
+ }
107
+
105
108
  // Space/Enter: expand selected provider
106
109
  if (matchesKey(data, Key.space) || matchesKey(data, Key.enter)) {
107
110
  const name = this.providers()[this.providerIndex]?.provider;
@@ -117,7 +120,8 @@ export class SessionPanel {
117
120
  }
118
121
 
119
122
  private currentPeriod(): SessionUsagePeriod | null {
120
- return this.usage ? this.usage[PERIODS[this.periodIndex]!.key] : null;
123
+ const usage = this.scanner.getSummary();
124
+ return usage ? usage[PERIODS[this.periodIndex]!.key] : null;
121
125
  }
122
126
 
123
127
  private providers(): ProviderSessionUsage[] {
@@ -126,9 +130,18 @@ export class SessionPanel {
126
130
 
127
131
  render(theme: Theme, contentWidth?: number): string[] {
128
132
  const th = theme;
129
- if (this.loading) return [` ${th.fg("muted", "Loading local session usage...")}`];
130
- if (this.error) return [` ${th.fg("warning", this.error)}`];
131
- if (!this.usage) return [` ${th.fg("muted", "Loading...")}`];
133
+ const usage = this.scanner.getSummary();
134
+ const progress = this.scanner.getProgress();
135
+ const error = this.scanner.getError();
136
+ const scanning = progress.running;
137
+ // 还没出第一份快照时才只显示进度;之后边扫边显示已经统计到的数字
138
+ if (!usage) {
139
+ if (error) return [` ${th.fg("warning", error)}`];
140
+ const label = scanning
141
+ ? `Scanning local session usage… ${progress.scanned}/${progress.total}`
142
+ : "No local session usage found";
143
+ return [` ${th.fg("muted", label)}`];
144
+ }
132
145
 
133
146
  // Dynamic column widths
134
147
  const fixedCols = sesW + msgW + inW + outW + cacheW + tokW + costW; // = 52
@@ -172,13 +185,15 @@ export class SessionPanel {
172
185
 
173
186
  // ── Period summary (single row) at bottom ──
174
187
  const period = PERIODS[this.periodIndex]!;
175
- const totals = this.usage[period.key].totals;
188
+ const totals = usage[period.key].totals;
176
189
  lines.push("");
177
190
  lines.push(th.fg("borderMuted", " " + "─".repeat(sepWidth)));
178
191
  lines.push(th.fg("accent", ` ${statCols("Total:", totals, dynamicNameW)}`));
179
192
 
180
193
  lines.push("");
181
- lines.push(` ${th.fg("dim", `←→ period · ↑↓ provider · Space expand · Tab switch · Esc close`)}`);
194
+ lines.push(` ${th.fg("dim", scanning
195
+ ? `Scanning… ${progress.scanned}/${progress.total} · numbers grow as history is read`
196
+ : "←→ period · ↑↓ provider · Space expand · r rescan · Tab switch · Esc close")}`);
182
197
  return lines;
183
198
  }
184
199
  }
@@ -73,6 +73,7 @@ export class UsageWindow {
73
73
 
74
74
  handleInput(data: string): void {
75
75
  if (isCloseKey(data)) {
76
+ this.session.dispose();
76
77
  this.done();
77
78
  return;
78
79
  }
@@ -171,6 +172,7 @@ export class UsageWindow {
171
172
  invalidate(): void {}
172
173
 
173
174
  dispose(): void {
175
+ this.session.dispose();
174
176
  this.unsubscribeInput?.();
175
177
  this.unsubscribeInput = undefined;
176
178
  }