pi-status-footer 1.0.3 β†’ 1.0.5

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.
Files changed (3) hide show
  1. package/README.md +16 -15
  2. package/package.json +4 -1
  3. package/stats-footer.ts +156 -49
package/README.md CHANGED
@@ -7,15 +7,15 @@ A compact, zero-config two-line status footer for [pi](https://github.com/earend
7
7
  ![pi-status-footer demo](docs/footer-demo.png)
8
8
 
9
9
  ```
10
- πŸ€– openai/gpt-4o πŸ’­ medium ↑5.2k ↓8.1k ⚑42 t/s πŸ’Ύ63% πŸ“¦38%/128k
11
- πŸ“ my-project β–Έ ξœ₯ main +3 -1 ⏳ 4:32 πŸ’¬ 1:18
10
+ πŸ“¦ 38%/128k πŸ’Ύ 63% ↑5.2k ↓8.1k ⚑42 t/s ⏳ 4:32 πŸ’¬ 1:18
11
+ πŸ“ my-project β–Έ ξœ₯ main +3 -1 πŸ€– openai/ry-very-long-modelid-4o πŸ’­ medium
12
12
  ```
13
13
 
14
- **Line 1 β€” Model & stats:** provider/model, thinking level with themed color, input/output tokens, tokens per second (live while streaming), cache hit rate, context window usage with color-coded fullness (green < 60%, yellow < 80%, red β‰₯ 80%).
14
+ **Line 1 β€” Stats & timers:** context window usage with color-coded fullness (green < 60%, yellow < 80%, red β‰₯ 80%), cache hit rate, input/output tokens, tokens per second (live while streaming), agent run timer (⏳), current turn timer (πŸ’¬).
15
15
 
16
- **Line 2 β€” Project & timers:** repo folder name, git branch, live working-tree diff from HEAD (+N added lines, -M deleted), agent run timer (⏳), current turn timer (πŸ’¬).
16
+ **Line 2 β€” Project & model:** repo folder name, git branch, live working-tree diff from HEAD (+N added lines, -M deleted), provider/model, thinking level with themed color.
17
17
 
18
- Everything auto-fits to your terminal width β€” lower-priority segments drop off when space is tight (model name is always shown, truncated if needed).
18
+ Everything auto-fits to your terminal width. Line 1 always keeps every segment (it clips only on very narrow terminals). On line 2 the model is mandatory: the model id is shortened from the left, keeping the provider and thinking level intact β€” only if even that can't fit does the folder/git group drop off.
19
19
 
20
20
  ## Features
21
21
 
@@ -25,7 +25,8 @@ Everything auto-fits to your terminal width β€” lower-priority segments drop off
25
25
  - **Cache hit rate** β€” percentage of prompt tokens served from cache
26
26
  - **Context gauge** β€” percentage and raw max; shifts from green β†’ yellow β†’ red as you approach the limit
27
27
  - **Thinking level** β€” color-coded to match pi's thinking theme
28
- - **Segments drop gracefully** β€” only the model name is mandatory; everything else fits to width
28
+ - **Responsive model id** β€” shortened from the left (with an `…` marker) when space is tight, so the provider and thinking level stay fully readable; the folder/git group drops only when the model still can't share the line
29
+ - **Line 1 never drops stats** β€” every stat segment always renders; on very narrow terminals the line clips instead
29
30
  - **East Asian safe** β€” explicit ambiguous-width handling for CJK-friendly terminals
30
31
  - **Safe at all times** β€” footer rendering never crashes the TUI, even on edge cases
31
32
 
@@ -46,26 +47,26 @@ After installation, the footer appears automatically on the next pi TUI session.
46
47
 
47
48
  ## Display reference
48
49
 
49
- ### Line 1 β€” Model & stats
50
+ ### Line 1 β€” Stats & timers
50
51
 
51
52
  | Segment | Example | Source |
52
53
  |---|---|---|
53
- | πŸ€– model | `πŸ€– openai/gpt-4o` | `ctx.model.provider / ctx.model.id` |
54
- | πŸ’­ thinking | `πŸ’­ high` | `ctx.thinkingLevel`, themed via `theme.fg()` |
54
+ | πŸ“¦context | `πŸ“¦ 38%/128k` | `ctx.getContextUsage()`, color-coded by percent |
55
+ | πŸ’Ύcache | `πŸ’Ύ 63%` | `cacheRead / (input + cacheRead + cacheWrite)` |
55
56
  | ↑input ↓output | `↑5.2k ↓8.1k` | Session `usage.input / usage.output` (accumulated across all entries) |
56
57
  | ⚑tps | `⚑42 t/s` | Live during generation; last completed rate shown between turns |
57
- | πŸ’Ύcache | `πŸ’Ύ63%` | `cacheRead / (input + cacheRead + cacheWrite)` |
58
- | πŸ“¦context | `πŸ“¦38%/128k` | `ctx.getContextUsage()`, color-coded by percent |
58
+ | ⏳ working | `⏳ 4:32` | Elapsed time since `agent_start`, HH:MM:SS above 1h |
59
+ | πŸ’¬ turn | `πŸ’¬ 1:18` | Elapsed time since last `turn_start` |
59
60
 
60
- ### Line 2 β€” Project & timers
61
+ ### Line 2 β€” Project & model
61
62
 
62
63
  | Segment | Example | Source |
63
64
  |---|---|---|
64
65
  | πŸ“ repo | `πŸ“ my-project` | Git repo root basename (from `ctx.cwd` walk-up) |
65
66
  | β–Έ ξœ₯ branch | `β–Έ ξœ₯ main` | `footerData.getGitBranch()`, auto-updates |
66
67
  | +N -M diff | `+3 -1` | Async `git diff --shortstat HEAD` (1s debounced) |
67
- | ⏳ working | `⏳ 4:32` | Elapsed time since `agent_start`, HH:MM:SS above 1h |
68
- | πŸ’¬ turn | `πŸ’¬ 1:18` | Elapsed time since last `turn_start` |
68
+ | πŸ€– model | `πŸ€– openai/gpt-4o` | `ctx.model.provider / ctx.model.id`, id shortened from the left when narrow |
69
+ | πŸ’­ thinking | `πŸ’­ high` | `ctx.thinkingLevel`, themed via `theme.fg()` |
69
70
 
70
71
  ## How it works
71
72
 
@@ -74,7 +75,7 @@ The extension hooks into six pi lifecycle events:
74
75
  - **`session_start`** β€” registers the footer via `ctx.ui.setFooter()`, discovers repo root, starts branch-change listener
75
76
  - **`agent_start` / `agent_settled`** β€” controls the agent-run timer and a 1-second interval that triggers git diff refresh
76
77
  - **`turn_start` / `turn_end`** β€” drives the per-turn timer
77
- - **`message_start` / `message_update` / `message_end`** β€” tracks the generation window for live TPS
78
+ - **`message_start` / `message_update` / `message_end`** β€” tracks the generation window for live TPS. Most providers only report output-token usage at message end, so `message_update` estimates tokens live from the streamed delta characters (text/thinking/toolcall), calibrated against each message's real usage at `message_end`
78
79
  - **`model_select`** β€” clears stale TPS on model switch
79
80
  - **`session_shutdown`** β€” cleans up all state
80
81
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-status-footer",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "Compact two-line status footer for pi: model, thinking level, tokens, TPS, cache hit rate, context usage, live git diff, and working/turn timers.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -28,6 +28,9 @@
28
28
  "monitoring",
29
29
  "streaming"
30
30
  ],
31
+ "scripts": {
32
+ "test": "node --experimental-strip-types test-live-tps.ts && node --experimental-strip-types test-layout.ts"
33
+ },
31
34
  "license": "MIT",
32
35
  "repository": {
33
36
  "type": "git",
package/stats-footer.ts CHANGED
@@ -202,24 +202,94 @@ function joinSegments(segments: string[], separator: string): string {
202
202
  return segments.filter(Boolean).join(separator);
203
203
  }
204
204
 
205
- function fitSegments(
206
- segments: string[],
207
- separator: string,
208
- width: number,
205
+ /** Below this terminal width the footer gives up fitting and lets the line
206
+ * overflow (the TUI clips it); shortening arithmetic degenerates here. */
207
+ const MIN_FIT_WIDTH = 50;
208
+
209
+ /**
210
+ * Shorten a model id by dropping leading characters, keeping the trailing
211
+ * part (model ids usually end in the distinguishing version, e.g. `...-4o`).
212
+ * A leading ellipsis marks the cut. Returns "" when nothing fits.
213
+ */
214
+ export function shortenModelId(
215
+ id: string,
216
+ budget: number,
217
+ ellipsis = "…",
209
218
  ): string {
210
- if (width <= 0 || segments.length === 0) return "";
211
- // The first segment (model + thinking level) has top priority. If it
212
- // alone is wider than the terminal, show a truncated prefix of it
213
- // instead of skipping it in favor of lower-priority segments.
214
- if (measureWidth(segments[0]!) > width) {
215
- return truncateSafe(segments[0]!, width, "...");
219
+ if (budget <= 0) return "";
220
+ if (measureWidth(id) <= budget) return id;
221
+ const ellipsisWidth = measureWidth(ellipsis);
222
+ if (budget < ellipsisWidth) return "";
223
+ const chars = Array.from(id);
224
+ for (let start = 0; start < chars.length; start++) {
225
+ const candidate = ellipsis + chars.slice(start).join("");
226
+ if (measureWidth(candidate) <= budget) return candidate;
216
227
  }
217
- const fitted: string[] = [segments[0]!];
218
- for (const segment of segments.slice(1)) {
219
- const candidate = joinSegments([...fitted, segment], separator);
220
- if (measureWidth(candidate) <= width) fitted.push(segment);
228
+ return ellipsis;
229
+ }
230
+
231
+ export interface SecondLineParts {
232
+ /** Folder/branch/diff group; "" when there is no folder to show. */
233
+ gitGroup: string;
234
+ /** Prefix before the provider, e.g. "πŸ€– ". */
235
+ modelPrefix: string;
236
+ /** Provider name; may be "" when no model is selected. */
237
+ provider: string;
238
+ /** Model id, shortened from the left when space is tight. */
239
+ modelId: string;
240
+ /** Everything after the model id, e.g. " πŸ’­ medium". */
241
+ modelSuffix: string;
242
+ /** Between-segment separator. */
243
+ separator: string;
244
+ /** Color wrapper applied to the `provider/id` text. */
245
+ styleModelId?: (text: string) => string;
246
+ }
247
+
248
+ /**
249
+ * Line 2 = folder/git group + model segment. The model (provider + thinking
250
+ * level) is mandatory: when space is tight the model id loses leading
251
+ * characters first, and if even a bare `provider/` cannot share the line the
252
+ * whole git group is dropped.
253
+ */
254
+ export function fitSecondLine(parts: SecondLineParts, width: number): string {
255
+ const {
256
+ gitGroup,
257
+ modelPrefix,
258
+ provider,
259
+ modelId,
260
+ modelSuffix,
261
+ separator,
262
+ styleModelId = (text: string) => text,
263
+ } = parts;
264
+ const providerPrefix = provider ? `${provider}/` : "";
265
+ const fixedWidth =
266
+ measureWidth(modelPrefix) +
267
+ measureWidth(providerPrefix) +
268
+ measureWidth(modelSuffix);
269
+ const buildModel = (budget: number): string | null => {
270
+ if (fixedWidth > budget) return null;
271
+ const idText = shortenModelId(modelId, budget - fixedWidth);
272
+ return `${modelPrefix}${styleModelId(`${providerPrefix}${idText}`)}${modelSuffix}`;
273
+ };
274
+
275
+ const fullModel = buildModel(Number.POSITIVE_INFINITY)!;
276
+ if (width < MIN_FIT_WIDTH) {
277
+ // Too narrow to fit meaningfully β€” render everything and let the TUI clip.
278
+ return joinSegments([gitGroup, fullModel], separator);
221
279
  }
222
- return truncateSafe(joinSegments(fitted, separator), width, "");
280
+ const maxWidth = Math.max(0, width - SAFETY_MARGIN);
281
+ if (!gitGroup) return buildModel(maxWidth) ?? fullModel;
282
+
283
+ const full = joinSegments([gitGroup, fullModel], separator);
284
+ if (measureWidth(full) <= maxWidth) return full;
285
+
286
+ const withGit = buildModel(
287
+ maxWidth - measureWidth(gitGroup) - measureWidth(separator),
288
+ );
289
+ if (withGit !== null) return joinSegments([gitGroup, withGit], separator);
290
+
291
+ // The model alone can't share the line: drop the whole folder/git group.
292
+ return buildModel(maxWidth) ?? fullModel;
223
293
  }
224
294
 
225
295
  /** Walk up from cwd to find the git repo root directory (or null). */
@@ -256,6 +326,13 @@ export default function statsFooter(pi: ExtensionAPI) {
256
326
  let genStart: number | null = null;
257
327
  let liveOutput = 0;
258
328
  let lastTps: number | null = null;
329
+ // Characters streamed for the current assistant message (text + thinking
330
+ // + toolcall deltas). Used to estimate output tokens live, since most
331
+ // providers only report usage.output at message end.
332
+ let deltaChars = 0;
333
+ // Exponentially-averaged chars-per-token ratio, calibrated from each
334
+ // message's real usage.output at message_end. Default 4 β‰ˆ English prose.
335
+ let charsPerToken = 4;
259
336
  // Git status: repo folder name + working-tree diff stats (+N -M), fetched
260
337
  // asynchronously (render is synchronous, so results are cached).
261
338
  let sessionCwd: string | null = null;
@@ -309,6 +386,7 @@ export default function statsFooter(pi: ExtensionAPI) {
309
386
  genStart = null;
310
387
  liveOutput = 0;
311
388
  lastTps = null;
389
+ deltaChars = 0;
312
390
  sessionCwd = ctx.cwd;
313
391
  folderName = basename(ctx.cwd);
314
392
  const repoRoot = findRepoRoot(ctx.cwd);
@@ -350,9 +428,6 @@ export default function statsFooter(pi: ExtensionAPI) {
350
428
  else contextColor = "success";
351
429
  }
352
430
 
353
- const modelId = ctx.model
354
- ? `${ctx.model.provider}/${ctx.model.id}`
355
- : "no-model";
356
431
  const thinkingLevel = ctx.thinkingLevel || "off";
357
432
  const contextText =
358
433
  contextPercent === null
@@ -377,34 +452,35 @@ export default function statsFooter(pi: ExtensionAPI) {
377
452
  // TPS: live rate while the current assistant message streams,
378
453
  // falling back to the last completed message's rate so the value
379
454
  // keeps a fixed position instead of flashing only at message_end.
380
- let tpsSuffix = "";
381
455
  const liveTps =
382
456
  genStart !== null && liveOutput > 0
383
457
  ? computeTps(liveOutput, genStart, Date.now())
384
458
  : null;
385
459
  const tpsValue = liveTps ?? lastTps;
386
- tpsSuffix = ` ⚑${Math.round(tpsValue ?? 0)} t/s`;
387
- // Line 1 β€” model + tokens/stats, each segment icon-prefixed.
388
- const statsLine = fitSegments(
460
+ // Line 1 β€” stats only (context, cache, tokens, TPS, timers). Every
461
+ // segment always renders; on very narrow terminals the line overflows
462
+ // and the TUI clips it rather than dropping stats.
463
+ const statsLine = joinSegments(
389
464
  [
390
- `πŸ€– ${theme.fg("accent", modelId)} ${thinkingText}`,
465
+ `πŸ“¦ ${theme.fg(contextColor, contextText)}`,
391
466
  theme.fg(
392
467
  "dim",
393
- `↑${formatTokens(usage.input)} ↓${formatTokens(usage.output)}${tpsSuffix}`,
468
+ `πŸ’Ύ ${cacheRate === null ? "-" : `${cacheRate.toFixed(0)}%`}`,
394
469
  ),
395
470
  theme.fg(
396
471
  "dim",
397
- `πŸ’Ύ ${cacheRate === null ? "-" : `${cacheRate.toFixed(0)}%`}`,
472
+ `↑${formatTokens(usage.input)} ↓${formatTokens(usage.output)}`,
398
473
  ),
399
- `πŸ“¦ ${theme.fg(contextColor, contextText)}`,
474
+ theme.fg("dim", `⚑${Math.round(tpsValue ?? 0)} t/s`),
475
+ `⏳ ${theme.fg("accent", formatDuration(elapsed))}`,
476
+ `πŸ’¬ ${theme.fg("accent", formatDuration(turnElapsed))}`,
400
477
  ],
401
478
  separator,
402
- Math.max(0, width - SAFETY_MARGIN),
403
479
  );
404
- // Line 2 β€” folder/git status + working/turn timers. The folder
405
- // name always shows (repo root basename, or plain cwd basename
406
- // when not inside a git repo); branch + diff only when git is
407
- // present.
480
+ // Line 2 β€” folder/git status + model/thinking. The folder name
481
+ // always shows (repo root basename, or plain cwd basename when
482
+ // not inside a git repo); branch + diff only when git is present.
483
+ // The model id is shortened from the left before git is dropped.
408
484
  const branch = footerData.getGitBranch();
409
485
  const gitSegments: string[] = [];
410
486
  if (folderName !== null) {
@@ -422,15 +498,18 @@ export default function statsFooter(pi: ExtensionAPI) {
422
498
  gitSegments.push(folderText);
423
499
  }
424
500
  }
425
- // ⏳ = work in progress (whole agent run), πŸ’¬ = current turn.
426
- gitSegments.push(
427
- `⏳ ${theme.fg("accent", formatDuration(elapsed))}`,
428
- `πŸ’¬ ${theme.fg("accent", formatDuration(turnElapsed))}`,
429
- );
430
- const gitLine = fitSegments(
431
- gitSegments,
432
- separator,
433
- Math.max(0, width - SAFETY_MARGIN),
501
+ const gitGroup = joinSegments(gitSegments, separator);
502
+ const gitLine = fitSecondLine(
503
+ {
504
+ gitGroup,
505
+ modelPrefix: "πŸ€– ",
506
+ provider: ctx.model?.provider ?? "",
507
+ modelId: ctx.model?.id ?? "no-model",
508
+ modelSuffix: ` ${thinkingText}`,
509
+ separator,
510
+ styleModelId: (text) => theme.fg("accent", text),
511
+ },
512
+ width,
434
513
  );
435
514
 
436
515
  return [
@@ -481,12 +560,12 @@ export default function statsFooter(pi: ExtensionAPI) {
481
560
  stopTimer();
482
561
  tuiRef = null;
483
562
  runStart = null;
484
- lastRunDuration = 0;
485
563
  turnStart = null;
486
564
  lastTurnDuration = 0;
487
565
  genStart = null;
488
566
  liveOutput = 0;
489
567
  lastTps = null;
568
+ deltaChars = 0;
490
569
  sessionCwd = null;
491
570
  folderName = null;
492
571
  repoName = null;
@@ -498,28 +577,45 @@ export default function statsFooter(pi: ExtensionAPI) {
498
577
  // --- Tokens-per-second tracking ---
499
578
  // Each assistant message's generation window is measured from its
500
579
  // message_start (streaming begins) to message_end (stream done).
501
- // message_update carries progressively updated usage.output, giving a
502
- // live rate while streaming; message_end carries the final usage, whose
503
- // rate is kept as lastTps for display while idle.
580
+ // Each assistant message's generation window is measured from its
581
+ // message_start (streaming begins) to message_end (stream done).
582
+ // message_update carries progressively updated usage.output for providers
583
+ // that report it (e.g. some gateways); most providers (Anthropic, OpenAI)
584
+ // only send output usage at message end, so tokens are estimated live from
585
+ // the streamed delta characters, calibrated by charsPerToken. Real usage
586
+ // is preferred whenever it is reported and has grown past the estimate;
587
+ // message_end keeps the final usage's rate as lastTps for display while
588
+ // idle.
504
589
  pi.on("message_start", (event) => {
505
590
  if (event.message.role !== "assistant") return;
506
591
  genStart = Date.now();
507
592
  liveOutput = (event.message as AssistantMessage).usage?.output ?? 0;
593
+ deltaChars = 0;
508
594
  });
509
595
  pi.on("message_update", (event) => {
510
596
  if (event.message.role !== "assistant") return;
511
- // The raw stream event's partial message carries the most current
512
- // usage.output (Anthropic reports it progressively; OpenAI only at the
513
- // end), so prefer it over the session message's usage field.
514
597
  const assistantEvent = event.assistantMessageEvent;
598
+ if (
599
+ assistantEvent &&
600
+ "delta" in assistantEvent &&
601
+ typeof assistantEvent.delta === "string"
602
+ ) {
603
+ deltaChars += assistantEvent.delta.length;
604
+ }
515
605
  const partial =
516
606
  assistantEvent && "partial" in assistantEvent
517
607
  ? (assistantEvent as { partial?: AssistantMessage }).partial
518
608
  : undefined;
519
- const output =
609
+ const reported =
520
610
  partial?.usage?.output ??
521
611
  (event.message as AssistantMessage).usage?.output;
522
- if (typeof output === "number" && output > liveOutput) liveOutput = output;
612
+ const estimated = Math.round(deltaChars / charsPerToken);
613
+ const output = Math.max(
614
+ typeof reported === "number" ? reported : 0,
615
+ liveOutput,
616
+ estimated,
617
+ );
618
+ if (output > liveOutput) liveOutput = output;
523
619
  });
524
620
  pi.on("message_end", (event) => {
525
621
  if (event.message.role === "assistant") {
@@ -529,8 +625,18 @@ export default function statsFooter(pi: ExtensionAPI) {
529
625
  const tps = computeTps(output, genStart, Date.now());
530
626
  lastTps = tps === null ? null : Math.round(tps);
531
627
  }
628
+ // Calibrate the live chars-per-token estimate against the real
629
+ // output token count so the next message's estimate is accurate.
630
+ if (deltaChars > 0 && output > 0) {
631
+ const ratio = deltaChars / output;
632
+ charsPerToken = Math.min(
633
+ 12,
634
+ Math.max(1.5, charsPerToken * 0.7 + ratio * 0.3),
635
+ );
636
+ }
532
637
  genStart = null;
533
638
  liveOutput = 0;
639
+ deltaChars = 0;
534
640
  }
535
641
  rerender();
536
642
  });
@@ -540,6 +646,7 @@ export default function statsFooter(pi: ExtensionAPI) {
540
646
  lastTps = null;
541
647
  genStart = null;
542
648
  liveOutput = 0;
649
+ deltaChars = 0;
543
650
  rerender();
544
651
  });
545
652
  pi.on("session_info_changed", rerender);