pi-footer-stats 0.1.1 → 0.1.2

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 CHANGED
@@ -5,6 +5,21 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.1.2] - 2026-12-04
9
+
10
+ ### Fixed
11
+
12
+ - `⚡` tok/s could be badly inflated when the provider's stream is delivered in
13
+ one burst after completion (observed against omlx: a 720 ms generation
14
+ produced an 8 ms `message_start`→`message_end` window, and a session averaged
15
+ 449 tok/s instead of the true ~94). The rate now uses pi-ai's monotonic
16
+ `message.durationMs` as the primary time source, falling back to the
17
+ wall-clock window for messages without it (invalid values — non-finite,
18
+ non-positive, non-numeric — fall back too, so they can never poison the
19
+ accumulator). History seeding likewise prefers `durationMs` over
20
+ entry-timestamp gaps. Regression suite extended with burst-delivery,
21
+ missing-`message_start`, invalid-value, and mixed-seeding cases.
22
+
8
23
  ## [0.1.1] - 2026-12-04
9
24
 
10
25
  ### Changed
package/README.md CHANGED
@@ -48,13 +48,6 @@ Then `/reload` (or restart pi) and the footer replaces the built-in one.
48
48
  - **Remove** — `pi remove npm:pi-footer-stats`
49
49
  - **Pin a version** — `pi install npm:pi-footer-stats@0.1.0`
50
50
 
51
- > **Why not Homebrew?** pi itself is brew-installable (`pi-coding-agent`),
52
- > but extensions ride pi's own package system by design. A brew formula would
53
- > have to write into `~/.pi/agent/extensions/` (outside Homebrew's Cellar),
54
- > and the copy would be invisible to pi's package manager — no automatic
55
- > updates, no **Extension Updates** changelog, no `pi remove`. We deliberately
56
- > keep one install story (npm / git) instead of three.
57
-
58
51
  ## What you get
59
52
 
60
53
  - **Cumulative session stats** — `↑` input, `↓` output, `↺ R` cache reads,
@@ -62,8 +55,8 @@ Then `/reload` (or restart pi) and the footer replaces the built-in one.
62
55
  - **`◎ CH`** cache-hit rate, color-coded (green ≥90 / yellow ≥50 / gray)
63
56
  - **`⚡` tokens/second** — average generation throughput **for the current
64
57
  session** — not a model benchmark: it reflects the model, hardware, and
65
- load of this session. Pure streaming time; reasoning tokens never
66
- double-counted
58
+ load of this session. Measured with pi's per-message monotonic timing
59
+ (`durationMs`); reasoning tokens never double-counted
67
60
  - **Context bar** — `▄▁▁▁▁▁▁▁▁▁`, one cell per 1%, dim → yellow >70% →
68
61
  **bold red >90%** as auto-compact nears, with `(auto)` when enabled
69
62
  - **Stable layout** — every indicator always shown (`0`/`—` placeholders),
package/demo.svg CHANGED
@@ -3,7 +3,7 @@
3
3
  <rect width="1400" height="230" rx="8" fill="#23232e"/>
4
4
  <g font-family="Menlo, Monaco, Consolas, 'DejaVu Sans Mono', monospace" font-size="14">
5
5
  <text x="18" y="34" xml:space="preserve"><tspan fill="#8a8fa3">~/workspace/apps/toolbox (main)</tspan></text>
6
- <text x="18" y="66" xml:space="preserve"><tspan fill="#8a8fa3">↑10k ↓5.4k ↺ R650k ✎ W0 ◎ CH98.5% ⚡77.1 tok/s $0.000 ▄▁▁▁▁▁▁▁▁▁ 2.5%/1.0M (auto) (omlx) Qwen4-35B-A3B-oQ4e-mtp • medium</tspan></text>
6
+ <text x="18" y="66" xml:space="preserve"><tspan fill="#a78bfa">↑10k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#56d364">↓5.4k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#768390">↺ R650k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#e3b341">✎ W0</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#56d364">◎ CH98.5%</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#63d9a8">⚡77.1 tok/s</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#58a6ff">$0.000</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#8a8fa3">▄▁▁▁▁▁▁▁▁▁ 2.5%/1.0M (auto)</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#8a8fa3">(omlx) Qwen4-35B-A3B-oQ4e-mtp • medium</tspan></text>
7
7
  </g>
8
8
  <line x1="18" y1="96" x2="1382" y2="96" stroke="#3a3a48" stroke-width="1"/>
9
9
  <g font-family="Menlo, Monaco, Consolas, 'DejaVu Sans Mono', monospace" font-size="15">
@@ -16,14 +16,16 @@
16
16
  * "(auto)" suffix when automatic compaction is enabled
17
17
  * Line 3: any other extension statuses via ctx.ui.setStatus() (dim)
18
18
  *
19
- * Token rate: exact wall time between message_start/message_end per assistant
20
- * message. message_start fires when the provider response headers arrive (after
21
- * connection setup and internal retries) and message_end when the stream is
22
- * finalized, so this measures pure generation throughput. Generated tokens use
19
+ * Token rate: per assistant message, pi-ai's `message.durationMs` (monotonic,
20
+ * measured inside pi-ai's AssistantMessageEventStream from stream creation to
21
+ * `done`) is the primary time source, falling back to wall time between
22
+ * message_start/message_end. The fallback matters because some providers/clients
23
+ * deliver a buffered stream in one burst, collapsing the message_start→
24
+ * message_end window to near-zero and inflating the rate. Generated tokens use
23
25
  * usage.output only — usage.reasoning is a subset of output per pi-ai's Usage
24
26
  * docs, so adding both would double-count thinking tokens. On session_start the
25
- * accumulator is reset and re-seeded from session entry timestamps
26
- * (approximate, includes queue/TTFT gaps).
27
+ * accumulator is reset and re-seeded from session entries (durationMs when
28
+ * present, otherwise entry timestamps — approximate, includes queue/TTFT gaps).
27
29
  */
28
30
 
29
31
  import { readFileSync } from "node:fs";
@@ -169,18 +171,26 @@ export default function (pi: ExtensionAPI) {
169
171
  totalMs = 0;
170
172
  turnStartMs = null;
171
173
 
172
- // Seed the rate accumulator from session history (approximate).
174
+ // Seed the rate accumulator from session history. Entries written by
175
+ // recent pi versions carry message.durationMs (exact); older entries fall
176
+ // back to entry-timestamp gaps (approximate, includes queue/TTFT gaps).
173
177
  let prevTs: number | null = null;
174
178
  for (const raw of ctx.sessionManager.getEntries()) {
175
179
  const entry = raw as {
176
180
  type?: string;
177
181
  timestamp?: string;
178
- message?: { role?: string; usage?: UsageLike };
182
+ message?: { role?: string; usage?: UsageLike; durationMs?: number };
179
183
  };
180
184
  const ts = entry.timestamp ? Date.parse(entry.timestamp) : Number.NaN;
181
185
  if (entry.type === "message" && entry.message?.role === "assistant") {
182
186
  const tokens = generatedTokens(entry.message.usage);
183
- if (tokens > 0 && !Number.isNaN(ts) && prevTs !== null && ts > prevTs) {
187
+ const durMs = entry.message.durationMs;
188
+ if (typeof durMs === "number" && Number.isFinite(durMs) && durMs > 0) {
189
+ if (tokens > 0) {
190
+ totalTokens += tokens;
191
+ totalMs += durMs;
192
+ }
193
+ } else if (tokens > 0 && !Number.isNaN(ts) && prevTs !== null && ts > prevTs) {
184
194
  totalTokens += tokens;
185
195
  totalMs += ts - prevTs;
186
196
  }
@@ -356,12 +366,20 @@ export default function (pi: ExtensionAPI) {
356
366
  });
357
367
 
358
368
  pi.on("message_end", async (event) => {
359
- if ((event.message as { role?: string } | undefined)?.role !== "assistant") return;
360
- if (turnStartMs === null) return;
361
- const elapsedMs = Date.now() - turnStartMs;
362
- const tokens = generatedTokens(
363
- (event.message as { usage?: UsageLike }).usage,
364
- );
369
+ const message = event.message as
370
+ | { role?: string; usage?: UsageLike; durationMs?: number }
371
+ | undefined;
372
+ if (message?.role !== "assistant") return;
373
+ // Prefer pi-ai's monotonic durationMs: some streams are delivered in one
374
+ // burst after completion, collapsing the wall-time window between
375
+ // message_start/message_end to near-zero (which would inflate the rate).
376
+ const wallMs = turnStartMs === null ? 0 : Date.now() - turnStartMs;
377
+ const durMs = message.durationMs;
378
+ const elapsedMs =
379
+ typeof durMs === "number" && Number.isFinite(durMs) && durMs > 0
380
+ ? durMs
381
+ : wallMs;
382
+ const tokens = generatedTokens(message.usage);
365
383
  turnStartMs = null;
366
384
  if (tokens > 0 && elapsedMs > 0) {
367
385
  totalTokens += tokens;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-footer-stats",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Custom pi footer: colored session stats, a tokens/second average, and a context-window progress bar",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -259,6 +259,126 @@ const rateFrom = (line) => {
259
259
  check("zero-token and aborted-start cases safe", Math.abs(rate - 500) / 500 < 0.3, `got ${rate}, expected ~500`);
260
260
  }
261
261
 
262
+ // --- 5b. durationMs is the primary time source (burst-delivered streams) ---
263
+ {
264
+ const h = makeInstance();
265
+ const { ctx, render } = makeCtx([]);
266
+ await h.session_start[0]({}, ctx);
267
+ h.message_start[0]({ message: { role: "assistant" } });
268
+ await sleep(200);
269
+ // Wall window ≈200ms would give ~500 tok/s; durationMs=1000 must win → ~100.
270
+ h.message_end[0]({ message: { role: "assistant", usage: { output: 100 }, durationMs: 1000 } });
271
+ const rate = parseFloat(rateFrom(render()));
272
+ check("durationMs overrides collapsed wall clock", Math.abs(rate - 100) / 100 < 0.25, `got ${rate}, expected ~100`);
273
+
274
+ // Invalid durationMs falls back to the wall window (started ~now → small).
275
+ h.message_start[0]({ message: { role: "assistant" } });
276
+ await sleep(100);
277
+ h.message_end[0]({ message: { role: "assistant", usage: { output: 50 }, durationMs: 0 } });
278
+ const rate2 = parseFloat(rateFrom(render()));
279
+ check("non-positive durationMs falls back to wall clock", Number.isFinite(rate2) && rate2 > 0, `got ${rate2}`);
280
+ }
281
+
282
+ // --- 5c. seeding prefers durationMs over timestamp gaps ---
283
+ {
284
+ const h = makeInstance();
285
+ // Timestamp gap says 10s (→100 tok/s); durationMs says 5s (→200 tok/s).
286
+ const entries = [
287
+ { type: "message", timestamp: iso(10000), message: { role: "user" } },
288
+ { type: "message", timestamp: iso(0), message: { role: "assistant", usage: { output: 1000 }, durationMs: 5000 } },
289
+ ];
290
+ const { ctx, render } = makeCtx(entries);
291
+ await h.session_start[0]({}, ctx);
292
+ const r = parseFloat(rateFrom(render()));
293
+ check("seeded rate uses durationMs when present", Math.abs(r - 200) <= 2, `got ${r}, expected ~200`);
294
+ }
295
+
296
+ // --- 5d. invalid durationMs values fall back to the wall clock -------------
297
+ // A bad value must never poison the accumulator (Infinity duration would make
298
+ // totalMs permanent-Inf and freeze the rate at —) nor produce a bogus rate.
299
+ {
300
+ const h = makeInstance();
301
+ const { ctx, render } = makeCtx([]);
302
+ await h.session_start[0]({}, ctx);
303
+ const bad = [Number.NaN, Number.POSITIVE_INFINITY, -1000, "1000", null, undefined];
304
+ for (const value of bad) {
305
+ h.message_start[0]({ message: { role: "assistant" } });
306
+ await sleep(50);
307
+ h.message_end[0]({ message: { role: "assistant", usage: { output: 100 }, durationMs: value } });
308
+ const rate = parseFloat(rateFrom(render()));
309
+ check(
310
+ `invalid durationMs ${String(value)} falls back to wall clock`,
311
+ Number.isFinite(rate) && rate > 0,
312
+ `got ${rateFrom(render())}`,
313
+ );
314
+ }
315
+ }
316
+
317
+ // --- 5e. durationMs alone suffices: message_end without message_start ------
318
+ // pi can finalize a message the extension never saw start (buffered burst,
319
+ // missed event ordering); durationMs must still count it.
320
+ {
321
+ const h = makeInstance();
322
+ const { ctx, render } = makeCtx([]);
323
+ await h.session_start[0]({}, ctx);
324
+ h.message_end[0]({ message: { role: "assistant", usage: { output: 200 }, durationMs: 2000 } });
325
+ const rate = parseFloat(rateFrom(render()));
326
+ check("durationMs-only message_end counts (no message_start needed)", Math.abs(rate - 100) / 100 < 0.25, `got ${rate}, expected ~100`);
327
+ }
328
+
329
+ // --- 5f. durationMs on non-assistant messages never affects the accumulator -
330
+ {
331
+ const h = makeInstance();
332
+ const { ctx, render } = makeCtx([]);
333
+ await h.session_start[0]({}, ctx);
334
+ h.message_end[0]({ message: { role: "toolResult", usage: { output: 999 }, durationMs: 5000 } });
335
+ h.message_end[0]({ message: { role: "user", usage: { output: 999 }, durationMs: 5000 } });
336
+ check("non-assistant durationMs ignored", rateFrom(render()) === "—");
337
+ }
338
+
339
+ // --- 5g. mixed seeding: durationMs and timestamp-gap entries combine --------
340
+ // An entry with durationMs must use ONLY that (its ts gap must not double-
341
+ // count); legacy entries without it fall back to the ts gap. 1000 tok / 5000 ms
342
+ // + 500 tok / 5000 ms = 1500 / 10s = 150 tok/s.
343
+ {
344
+ const h = makeInstance();
345
+ const entries = [
346
+ { type: "message", timestamp: iso(20000), message: { role: "user" } },
347
+ { type: "message", timestamp: iso(15000), message: { role: "assistant", usage: { output: 1000 }, durationMs: 5000 } },
348
+ { type: "message", timestamp: iso(10000), message: { role: "assistant", usage: { output: 500 } } },
349
+ ];
350
+ const { ctx, render } = makeCtx(entries);
351
+ await h.session_start[0]({}, ctx);
352
+ const r1 = parseFloat(rateFrom(render()));
353
+ await h.session_start[0]({}, ctx);
354
+ const r2 = parseFloat(rateFrom(render()));
355
+ check("mixed seeding combines durationMs + ts-gap entries", Math.abs(r1 - 150) <= 2, `got ${r1}, expected ~150`);
356
+ check("mixed re-seed is idempotent", r1 === r2, `${r1} vs ${r2}`);
357
+ }
358
+
359
+ // --- 5h. the original omlx failure: every stream burst-delivered ------------
360
+ // Regression fixture for the 449-vs-94 tok/s bug: three assistant messages
361
+ // whose message_start→message_end wall windows are ~0 (the provider delivered
362
+ // each finished stream in one burst), with real durations 4s/1s/5s.
363
+ // Pre-fix behavior: windows ~0ms → tokens dropped or rate wildly inflated.
364
+ // Correct behavior: Σtokens / ΣdurationMs = 1000 / 10s = 100 tok/s.
365
+ {
366
+ const h = makeInstance();
367
+ const { ctx, render } = makeCtx([]);
368
+ await h.session_start[0]({}, ctx);
369
+ const msgs = [
370
+ { output: 400, durationMs: 4000 },
371
+ { output: 100, durationMs: 1000 },
372
+ { output: 500, durationMs: 5000 },
373
+ ];
374
+ for (const m of msgs) {
375
+ h.message_start[0]({ message: { role: "assistant" } });
376
+ h.message_end[0]({ message: { role: "assistant", usage: { output: m.output }, durationMs: m.durationMs } });
377
+ }
378
+ const rate = parseFloat(rateFrom(render()));
379
+ check("burst-delivered session rates from durationMs sum", Math.abs(rate - 100) / 100 < 0.1, `got ${rate}, expected ~100`);
380
+ }
381
+
262
382
  // --- 6. layout: all indicators always present ---
263
383
  {
264
384
  const h = makeInstance();