pi-usage-hub 1.1.5 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-usage-hub",
3
- "version": "1.1.5",
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",
@@ -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
  }