oc-flight-deck 0.10.4 → 0.12.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/CHANGELOG.md CHANGED
@@ -5,6 +5,27 @@ All notable changes to this project are 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.12.0] - 2026-10-09
9
+
10
+ ### Changed
11
+
12
+ - The `tps` numerator now counts generation tokens - output plus reasoning - over the same streaming-span union, so a thinking-heavy turn reads as speed instead of idle time with no output yet. Tool settlement is still excluded, the denominator still ends at `streamed`, and the `reasoning` row itself is unchanged.
13
+
14
+ ## [0.11.0] - 2026-10-08
15
+
16
+ ### Changed
17
+
18
+ - TPS now reports a delta-based instantaneous rate instead of the session-lifetime average. The display is an integer, smoothed with an EWMA, with hysteresis so the last digit does not flicker, a minimum token sample before the rate is trusted, and an idle freeze that holds the last value when no new tokens arrive.
19
+ - The `context` row now reads as an estimate (`~`), reflecting that the underlying usage figure is approximate.
20
+ - The cache hit-rate denominator is now documented as deliberate in code and docs.
21
+
22
+ ### Fixed
23
+
24
+ - `treeTotals` now wraps each per-id lookup in its own `try/catch`, so one bad id no longer blanks the cost/total rollup.
25
+ - Width-aware clipping keeps rows inside the rail instead of overflowing it.
26
+ - Per-session maps are now LRU-capped, closing a slow leak across long sessions.
27
+ - The `ses` row documents that the display is a pruned preview while click-to-copy still copies the full id.
28
+
8
29
  ## [0.10.4] - 2026-10-06
9
30
 
10
31
  ### Fixed
@@ -37,6 +58,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
37
58
 
38
59
  - Opt-in `ses` sidebar row: shows the full session id (the rail wraps it), and a mouse click copies that same full id and reports the outcome - a confirmation naming the id when the copy was sent, a distinct failure message when the terminal cannot take it. Off by default, and degrades gracefully when the terminal cannot copy.
39
60
 
61
+ [0.12.0]: https://github.com/nathwn12/oc-flight-deck/compare/v0.11.0...v0.12.0
62
+ [0.11.0]: https://github.com/nathwn12/oc-flight-deck/compare/v0.10.4...v0.11.0
40
63
  [0.10.4]: https://github.com/nathwn12/oc-flight-deck/compare/v0.10.3...v0.10.4
41
64
  [0.10.3]: https://github.com/nathwn12/oc-flight-deck/compare/v0.10.2...v0.10.3
42
65
  [0.10.2]: https://github.com/nathwn12/oc-flight-deck/compare/v0.10.1...v0.10.2
package/README.md CHANGED
@@ -41,9 +41,9 @@ branch main
41
41
  cost $0.245 · 2 subagents
42
42
  tokens 533k in · 91k out
43
43
  cache 98% hit · 32M read
44
- context ██░░░░░░░░ 18%
44
+ context ██░░░░░░░░ ~18%
45
45
  elapsed 2h 14m 37s
46
- tps 18.0 tok/s
46
+ tps 18 tok/s
47
47
  ```
48
48
 
49
49
  Every row is read from the open session at render time — except `caution`, which watches a clock rather than events (a hang emits none); `elapsed`, which is seeded once from the session's own recorded assistant turn spans and then accumulates the busy windows this run observes, rather than a value the session reports; and the opt-in `guard` row, which is polled from the local guard RPC.
@@ -61,17 +61,17 @@ The panel's only fixed text — `▸ FLIGHT DECK` over a separator — is **opt-
61
61
  | `total` | The family total and subagent count on a row of its own · **off by default** |
62
62
  | `project` | Every session in this project, not just the one on screen |
63
63
  | `tokens` | Input and output, cumulative |
64
- | `cache` | Hit rate first — the number that explains the bill — then cache reads |
65
- | `context` | A gauge of how full the window is |
64
+ | `cache` | Hit rate first - `read / (read + input)` - then cache reads. Cache writes are excluded from the rate (creating an entry is not a lookup) but counted in `context` occupancy (a written entry still occupies the window) |
65
+ | `context` | An estimated (`~`) gauge of how full the window is - occupancy is a proxy from the last request's `input + cache.read + cache.write`, not a host-reported figure |
66
66
  | `perms` | What is waiting for approval, not just how many |
67
67
  | `elapsed` | Active time — the clock runs only while this session, a subagent in its tree, or one of its shells is working, and freezes when everything settles. It is seeded once from the assistant turn spans the host already recorded for that session, so it survives a restart instead of resetting to `—`; work observed live after that keeps counting in memory. It measures active time, not wall-clock since the session began |
68
- | `tps` | Average speed **while streaming**: output **plus reasoning** tokens divided by the time the provider was actively streaming (`streamed - created`), subagents included. Idle time between turns and the tool settlement after a turn are never counted, so the figure freezes when everything settles instead of decaying or hiding; a turn still in flight counts up to now. On a host that exposes no per-message timestamps it falls back to the lifetime average, which includes idle and can therefore sag. Not configurable |
68
+ | `tps` | Live speed **while generating**: the generation-token (output + reasoning) delta between polls over the generating-time delta (streaming spans, or the busy-gated active clock), smoothed and drawn whole - no decimals. Reasoning keeps its own row too. Idle is never divided: the figure freezes when everything settles and hides until ~2 s of generating time and ~10 tokens are on record. Not configurable |
69
69
  | `spark` | Recent turn sizes as a shape · **off by default** |
70
70
  | `reasoning` | Reasoning tokens, when the model emits them · **off by default** |
71
71
  | `turns` | How many prompts you've sent this session · **off by default** |
72
72
  | `guard` | Harness status from oc-harness-guard · **off by default** |
73
73
  | `go` | Zen Go account usage — a dial and a whole-number percent for the **5h**, **1w**, and **1m** windows, in that fixed order; a window at 90% or more turns its dial and number red, and the reset hint appears only then · **off by default** |
74
- | `ses` | The open session id, which the rail wraps; **click the row** to copy the full id to the terminal clipboard · **off by default** (requires the host's mouse) |
74
+ | `ses` | An 18-wide clipped preview of the open session id (never the full id on the rail); **click the row** to copy the full id to the terminal clipboard . **off by default** (requires the host's mouse) |
75
75
 
76
76
  `project` matches on the host's **project id**, not on a directory, so a worktree counts as part of the same project. A host that reports no project id leaves nothing to match on, and the row then totals every session that host knows about.
77
77
 
@@ -55,7 +55,7 @@
55
55
  "items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard", "go", "ses"] },
56
56
  "default": ["status", "agent", "model", "cost", "project", "tokens", "cache", "context", "perms", "elapsed", "tps"],
57
57
  "maxItems": 24,
58
- "description": "Which live fields to draw, top to bottom. Any subset, any order - this is the single most useful thing to change. With `sidebar.persist` (the default) every named row always renders, using `sidebar.placeholder` until the host has data; with `persist: false` rows with no data are omitted entirely. Counted together with `sidebar.lines` against a 24-line cap on the whole rail. The opt-in `ses` row shows the full session id (the rail wraps it); a mouse click on that row copies the full id to the terminal clipboard."
58
+ "description": "Which live fields to draw, top to bottom. Any subset, any order - this is the single most useful thing to change. With `sidebar.persist` (the default) every named row always renders, using `sidebar.placeholder` until the host has data; with `persist: false` rows with no data are omitted entirely. Counted together with `sidebar.lines` against a 24-line cap on the whole rail. The opt-in `ses` row shows an 18-wide clipped preview of the session id; a mouse click on that row copies the full id to the terminal clipboard."
59
59
  },
60
60
  "persist": {
61
61
  "type": "boolean",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oc-flight-deck",
3
- "version": "0.10.4",
3
+ "version": "0.12.0",
4
4
  "description": "Live OpenCode V2 session telemetry — agent, model, branch, cost, tokens, cache hit rate and context usage in your sidebar.",
5
5
  "keywords": [
6
6
  "opencode",
@@ -71,6 +71,12 @@ interface ActiveState {
71
71
  * the boundary. Undercount is acceptable, over-count is not.
72
72
  */
73
73
  export function createActiveElapsed(isBusy: BusyRead, options: ActiveElapsedOptions = {}) {
74
+ // One entry per viewed session, bounded: without eviction a TUI lifetime of
75
+ // session-hopping grows this map forever. Eviction only drops a stale tally -
76
+ // a revisit rebaselines and re-seeds from the host, exactly like a first
77
+ // sight. Recency refreshes on every read, so the watched session is always
78
+ // the last one evicted.
79
+ const MAX_STATES = 50;
74
80
  const states = new Map<string, ActiveState>();
75
81
  // The module's own contract must hold without the caller opting in; the
76
82
  // production caller still passes its own derived bound.
@@ -97,7 +103,7 @@ export function createActiveElapsed(isBusy: BusyRead, options: ActiveElapsedOpti
97
103
  if (state === undefined) {
98
104
  // First sight of this session: take the seed once, here, so the record
99
105
  // covers everything up to the moment observation begins and the
100
- // accumulator below covers everything after — no overlap, no double
106
+ // accumulator below covers everything after - no overlap, no double
101
107
  // count. Floored at zero; a non-finite or throwing read is zero.
102
108
  let seed = 0;
103
109
  if (options.seedOf !== undefined) {
@@ -109,13 +115,23 @@ export function createActiveElapsed(isBusy: BusyRead, options: ActiveElapsedOpti
109
115
  }
110
116
  }
111
117
  state = { accumulated: seed, lastAt: now, running: false };
118
+ if (states.size >= MAX_STATES) {
119
+ for (const oldest of states.keys()) {
120
+ states.delete(oldest);
121
+ break;
122
+ }
123
+ }
112
124
  states.set(sessionID, state);
113
- } else if (!boundary && state.running && busy) {
114
- // Only a window that was busy at BOTH ends and short enough to have been
115
- // observed is work. A settled gap is idle; a stalled or stepped-back
116
- // clock must never subtract; an over-long window was not watched.
117
- const delta = now - state.lastAt;
118
- if (delta > 0 && delta <= maxBankedMs) state.accumulated += delta;
125
+ } else {
126
+ states.delete(sessionID);
127
+ states.set(sessionID, state);
128
+ if (!boundary && state.running && busy) {
129
+ // Only a window that was busy at BOTH ends and short enough to have been
130
+ // observed is work. A settled gap is idle; a stalled or stepped-back
131
+ // clock must never subtract; an over-long window was not watched.
132
+ const delta = now - state.lastAt;
133
+ if (delta > 0 && delta <= maxBankedMs) state.accumulated += delta;
134
+ }
119
135
  }
120
136
 
121
137
  state.running = busy;
package/src/tui/format.ts CHANGED
@@ -64,21 +64,69 @@ export function fuelBar(ratio: number, width: number = DEFAULT_BAR_WIDTH): strin
64
64
 
65
65
  const SPARK_LEVELS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"] as const;
66
66
 
67
+ /**
68
+ * Terminal cell width of one code point: East Asian wide/fullwidth ranges and
69
+ * emoji take two cells, everything else one. Deliberately conservative - an
70
+ * ambiguous or unknown character counts one, so the rail may clip slightly
71
+ * early but can never overrun its column. Combines nothing: a combining mark
72
+ * counts one for the same reason, since over-counting only ever clips earlier.
73
+ */
74
+ function cellWidthOf(code: number): number {
75
+ if (
76
+ (code >= 0x1100 && code <= 0x115f) ||
77
+ code === 0x2329 ||
78
+ code === 0x232a ||
79
+ (code >= 0x2e80 && code <= 0xa4cf) ||
80
+ (code >= 0xac00 && code <= 0xd7a3) ||
81
+ (code >= 0xf900 && code <= 0xfaff) ||
82
+ (code >= 0xfe10 && code <= 0xfe19) ||
83
+ (code >= 0xfe30 && code <= 0xfe4f) ||
84
+ (code >= 0xff00 && code <= 0xff60) ||
85
+ (code >= 0xffe0 && code <= 0xffe6) ||
86
+ (code >= 0x20000 && code <= 0x3fffd) ||
87
+ (code >= 0x2600 && code <= 0x27bf) ||
88
+ (code >= 0x2b00 && code <= 0x2bff) ||
89
+ (code >= 0x1f000 && code <= 0x1faff)
90
+ ) {
91
+ return 2;
92
+ }
93
+ return 1;
94
+ }
95
+
96
+ /** The columns a string draws: its cell width, not its length. */
97
+ function cellWidth(text: string): number {
98
+ let width = 0;
99
+ for (const char of text) width += cellWidthOf(char.codePointAt(0) ?? 0);
100
+ return width;
101
+ }
102
+
67
103
  /**
68
104
  * Shorten a value for a narrow rail.
69
105
  *
70
106
  * The sidebar is roughly thirty-odd columns wide and the label already costs
71
107
  * ten, so a resource path has to be cut. The ellipsis is deliberate: a silently
72
- * truncated path reads as a complete one.
108
+ * truncated path reads as a complete one. The budget is CELLS, not characters:
109
+ * a CJK or emoji value that fits in characters can still draw twice as wide,
110
+ * so the cut keeps the longest prefix of at most `max - 1` cells and reserves
111
+ * the last cell for the ellipsis. Iterating by code point never splits a
112
+ * surrogate pair, so the orphaned-half guard the length-based cut needed is
113
+ * structurally gone.
73
114
  */
74
115
  export function clip(text: string, max: number): string {
75
- if (text.length <= max) return text;
76
- const cut = text.slice(0, Math.max(1, max - 1));
77
- // Never cut a surrogate pair in half: the orphaned half renders as a
78
- // replacement character, which reads as corruption rather than as a shortened
79
- // path. Losing one more column is the cheaper mistake.
80
- const safe = /[\uD800-\uDBFF]$/.test(cut) ? cut.slice(0, -1) : cut;
81
- return `${safe}…`;
116
+ const ellipsis = String.fromCharCode(0x2026);
117
+ if (cellWidth(text) <= max) return text;
118
+ const budget = max - 1;
119
+ let kept = "";
120
+ let width = 0;
121
+ for (const char of text) {
122
+ const next = width + cellWidthOf(char.codePointAt(0) ?? 0);
123
+ // The first character is always kept, mirroring the old floor: a budget
124
+ // below one cell still shortens rather than returning a bare ellipsis.
125
+ if (kept !== "" && next > budget) break;
126
+ kept += char;
127
+ width = next;
128
+ }
129
+ return `${kept}${ellipsis}`;
82
130
  }
83
131
 
84
132
  /**
package/src/tui/index.tsx CHANGED
@@ -176,7 +176,10 @@ export default Plugin.define({
176
176
  thresholds: cautionThreshold,
177
177
  });
178
178
 
179
- const { sessionTps } = createTpsReader(context, isFamilyRoot);
179
+ const { sessionTps } = createTpsReader(context, isFamilyRoot, {
180
+ busyOf: busy,
181
+ elapsedMsOf: (id, now) => sessionElapsed(id, now),
182
+ });
180
183
 
181
184
  // Recent turn sizes, oldest first. Drawn from messages the host already
182
185
  // holds, so the sparkline needs no history of our own to accumulate.
package/src/tui/rows.ts CHANGED
@@ -364,13 +364,27 @@ export function statLine(
364
364
  }
365
365
  case "cache": {
366
366
  const tokens = asRecord(source.tokens);
367
- const cache = asRecord(tokens?.cache);
367
+ if (tokens === undefined) return undefined;
368
+ const cache = asRecord(tokens.cache);
368
369
  const read = asCount(cache?.read);
369
- if (read === undefined || read === 0) return undefined;
370
+ if (read === undefined) return undefined;
370
371
  const input = asCount(tokens?.input);
371
372
  // Hit ratio is the whole point: it explains a cheap bill on a huge token
372
373
  // count, and it is the first thing to break when caching stops working.
374
+ // The denominator is `read + input` only: a cache write creates a new
375
+ // entry rather than answering a lookup, so it is not a hit-or-miss event
376
+ // and would dilute the rate. Context occupancy (./session-reads.ts) DOES
377
+ // count `write`, because a written entry still occupies the window - the
378
+ // two denominators differ on purpose, and this comment is the record.
379
+ // A zero read is drawn, not hidden: "no cache" is a state worth seeing,
380
+ // distinct from "no data yet" (which still hides and lets persist draw
381
+ // the placeholder).
373
382
  const total = input === undefined ? undefined : read + input;
383
+ if (read === 0) {
384
+ return total === undefined || total === 0
385
+ ? row("cache", `0 read`)
386
+ : row("cache", `0% hit · 0 read`);
387
+ }
374
388
  const value =
375
389
  total === undefined || total === 0
376
390
  ? `${formatCount(read)} read`
@@ -382,11 +396,14 @@ export function statLine(
382
396
  const used = asCount(context?.used);
383
397
  if (used === undefined || used === 0) return undefined;
384
398
  const limit = asCount(context?.limit);
385
- if (limit === undefined || limit === 0) return row("context", `${formatCount(used)} used`);
399
+ // `used` is an occupancy PROXY (last request's input + cache read +
400
+ // cache write), not a host-reported figure, so both shapes below carry
401
+ // a `~`: the row reads as the estimate it is, never as an exact count.
402
+ if (limit === undefined || limit === 0) return row("context", `~${formatCount(used)} used`);
386
403
  const ratio = used / limit;
387
404
  // Show the percentage whenever the host reports it, but never a bar that
388
405
  // reads as more than full.
389
- return row("context", `${fuelBar(ratio, barWidth)} ${Math.round(Math.min(1, ratio) * 100)}%`);
406
+ return row("context", `${fuelBar(ratio, barWidth)} ~${Math.round(Math.min(1, ratio) * 100)}%`);
390
407
  }
391
408
  case "perms": {
392
409
  const perms = asRecord(source.perms);
@@ -413,10 +430,14 @@ export function statLine(
413
430
  }
414
431
  case "tps": {
415
432
  const tps = asCount(source.tps);
416
- if (tps === undefined || tps === 0) return undefined;
417
- // One decimal, exactly as the official TUI renders it: rounding to a
418
- // whole number would overstate a slow turn by up to half a token/second.
419
- return row("tps", `${tps.toFixed(1)} tok/s`);
433
+ if (tps === undefined) return undefined;
434
+ // Whole tokens/second, honestly rounded: the value is already an EWMA of
435
+ // per-poll deltas, so a decimal would fake a precision the samples never
436
+ // had. Anything below half a token/second hides rather than printing
437
+ // "0 tok/s".
438
+ const rounded = Math.round(tps);
439
+ if (rounded <= 0) return undefined;
440
+ return row("tps", `${rounded} tok/s`);
420
441
  }
421
442
  case "spark": {
422
443
  const values = Array.isArray(source.spark) ? source.spark.map((value) => asCount(value) ?? 0) : [];
@@ -71,7 +71,13 @@ export function createSessionReads(context: Plugin.Context, maxBankedMs?: number
71
71
  let count = 0;
72
72
  for (const id of ids) {
73
73
  if (id === sessionID) continue;
74
- const child = context.data.session.get(id) as SessionLike | undefined;
74
+ let child: SessionLike | undefined;
75
+ try {
76
+ child = context.data.session.get(id) as SessionLike | undefined;
77
+ } catch {
78
+ // One unreadable member must not blank the rest of the tree.
79
+ continue;
80
+ }
75
81
  if (child === undefined) continue;
76
82
  count += 1;
77
83
  cost += asCount(child.cost) ?? 0;
@@ -80,7 +86,11 @@ export function createSessionReads(context: Plugin.Context, maxBankedMs?: number
80
86
  };
81
87
 
82
88
  // A message's own totals are per-request, so the last assistant message's
83
- // prompt size *is* the current context occupancy — not a running total.
89
+ // prompt size is an ESTIMATE of the current context occupancy - not a running
90
+ // total, and not a host-reported figure (hence the `~` on the `context` row).
91
+ // It sums input + cache read + cache WRITE: a written entry still occupies
92
+ // the window, even though `write` is deliberately excluded from the `cache`
93
+ // row's hit-rate denominator (creating an entry is not a lookup).
84
94
  const contextUsage = (sessionID: string, model: unknown) => {
85
95
  const messages = messagesOf(sessionID);
86
96
  for (let index = messages.length - 1; index >= 0; index -= 1) {
@@ -226,11 +236,30 @@ export function createSessionReads(context: Plugin.Context, maxBankedMs?: number
226
236
  // takes the merged union of those assistant turns' spans, tokens ignored: a
227
237
  // zero-output turn still took wall time. The scan is memoised one result per
228
238
  // session id, and every read degrades to zero rather than throwing, so an
229
- // absent family or an unstamped host leaves today's behaviour untouched.
239
+ // The scan is memoised one result per session id, and every read degrades to zero rather than throwing, so an
240
+ // absent family or an unstamped host leaves today's behaviour untouched. The
241
+ // memo holds at most `MAX_SEEDS` entries: without eviction a TUI lifetime of
242
+ // session-hopping grows it forever, and an evicted revisit simply re-scans
243
+ // the host's own timestamps, so nothing is lost.
244
+ const MAX_SEEDS = 50;
230
245
  const seeds = new Map<string, number>();
246
+ const rememberSeed = (sessionID: string, seed: number): void => {
247
+ if (seeds.has(sessionID)) seeds.delete(sessionID);
248
+ else if (seeds.size >= MAX_SEEDS) {
249
+ for (const oldest of seeds.keys()) {
250
+ seeds.delete(oldest);
251
+ break;
252
+ }
253
+ }
254
+ seeds.set(sessionID, seed);
255
+ };
231
256
  const seedElapsed = (sessionID: string): number => {
232
257
  const cached = seeds.get(sessionID);
233
- if (cached !== undefined) return cached;
258
+ if (cached !== undefined) {
259
+ seeds.delete(sessionID);
260
+ seeds.set(sessionID, cached);
261
+ return cached;
262
+ }
234
263
 
235
264
  // One `now` for the whole scan, so every in-flight turn ends at the same
236
265
  // instant and the union cannot be skewed by the reads drifting apart.
@@ -258,7 +287,7 @@ export function createSessionReads(context: Plugin.Context, maxBankedMs?: number
258
287
  const span = turnSpan(created, completed, streamed, now, "completed");
259
288
  if (span === undefined) continue;
260
289
  const output = asRecord(message["tokens"])?.["output"];
261
- spans.push({ key: turnKey(message["id"], created, completed, output), ...span });
290
+ spans.push({ key: turnKey(message["id"], created, completed, output, streamed), ...span });
262
291
  }
263
292
  }
264
293
  seed = unionSpanMs(spans);
@@ -267,7 +296,7 @@ export function createSessionReads(context: Plugin.Context, maxBankedMs?: number
267
296
  seed = 0;
268
297
  }
269
298
 
270
- seeds.set(sessionID, seed);
299
+ rememberSeed(sessionID, seed);
271
300
  return seed;
272
301
  };
273
302
 
@@ -1,16 +1,25 @@
1
1
  // Session throughput, measured from the host's own message timestamps and never
2
- // from a clock this process keeps. A host that stamps its assistant turns gets
3
- // an active-work average: output plus reasoning tokens divided by the union of
4
- // the turns' own streaming spans (`streamed - created`, fallbacks in
5
- // ./throughput.js), so idle between turns and the tool settlement after one are
6
- // not in the denominator and the figure freezes once everything settles. A host
7
- // proven to expose no message timestamps uses the lifetime average instead.
2
+ // from a clock this process keeps - as a near-instantaneous output rate, not a
3
+ // lifetime average.
4
+ //
5
+ // Each poll feeds the scope's cumulative output tokens and cumulative
6
+ // generating milliseconds into a per-session EWMA tracker (`./throughput.js`):
7
+ // the rate is the DELTA between successive polls, smoothed (alpha 0.3) and
8
+ // repainted only on a move of >= 1 tok/s or >= 10%, so the row tracks live
9
+ // decoding instead of sagging behind everything the session ever did. The
10
+ // numerator is generation tokens - output plus reasoning, which keeps its own
11
+ // row too - and the denominator is generating time only: the union of the
12
+ // turns' own streaming
13
+ // spans on a stamped host, the busy-gated active clock on one without stamps.
14
+ // Idle is never divided by; when nothing is busy the tracker freezes and the
15
+ // row holds its last figure. The row hides until ~2 s of generating time and
16
+ // ~10 tokens are on record, rather than flashing a one-sample rate.
8
17
  //
9
18
  // The capability is learned once and remembered for the process. `undefined`
10
19
  // means "not yet known": a read that failed, or carried no assistant turns,
11
20
  // tells us nothing and must not choose a metric. Once known it is sticky in
12
21
  // BOTH directions, so a transient `message.list` failure can never flip a
13
- // stamped host back to the lifetime average (nor an unstamped host off it) —
22
+ // stamped host back to the clock path (nor an unstamped host off it) -
14
23
  // a failure just hides the row. One value for the whole host, deliberately
15
24
  // not keyed by session.
16
25
  //
@@ -22,16 +31,19 @@
22
31
  // One factory closes over the plugin `context`; `isFamilyRoot` comes from
23
32
  // ./session-reads.js so a child session keeps its own figure while a root
24
33
  // sums its tree. The math itself lives in ./throughput.js (pure).
25
- //
26
- // RESIDUAL RISK, disclosed: the lifetime fallback for an unstamped host still
27
- // includes idle time and can therefore sag below a peak per-turn rate. There is
28
- // no timestamp on such a host with which to exclude it.
29
34
 
30
35
  import type { Plugin } from "@opencode/plugin/tui";
31
36
  import { asCount, asRecord, type SessionLike } from "./coerce.js";
32
- import { sessionThroughput, turnKey, turnSpan, unionSpanThroughput, type ThroughputSpan } from "./stats.js";
37
+ import {
38
+ createInstantTps,
39
+ turnKey,
40
+ turnSpan,
41
+ unionGenerationTotals,
42
+ unionSpanMs,
43
+ type ThroughputSpan,
44
+ } from "./stats.js";
33
45
 
34
- /** What one session's message list contributes to its active-work average. */
46
+ /** What one session's message list contributes to its instantaneous rate. */
35
47
  interface TpsScan {
36
48
  /** False only when the host refused to list the session's messages. */
37
49
  readonly ok: boolean;
@@ -43,15 +55,53 @@ interface TpsScan {
43
55
  readonly spans: readonly ThroughputSpan[];
44
56
  }
45
57
 
58
+ /**
59
+ * The live signals the TPS reader borrows rather than re-deriving: the busy
60
+ * gate (is anything working?) freezes the row on idle, and the active clock
61
+ * (how much generating time is on record?) is the denominator for a host
62
+ * with no message timestamps. Both come from ./session-reads.js; absent, the
63
+ * stamped path still works and the unstamped path hides for lack of time.
64
+ */
65
+ export interface TpsLiveReads {
66
+ readonly busyOf?: (sessionID: string) => boolean | undefined;
67
+ readonly elapsedMsOf?: (sessionID: string, now: number) => number | undefined;
68
+ }
69
+
46
70
  export function createTpsReader(
47
71
  context: Plugin.Context,
48
72
  isFamilyRoot: (sessionID: string) => boolean,
73
+ live?: TpsLiveReads,
49
74
  ) {
50
75
  const TPS_CACHE_MS = 1_000;
51
76
  let hostStamps: boolean | undefined;
52
77
  let tpsCache:
53
78
  | { readonly sessionID: string; readonly at: number; readonly value: number | undefined }
54
79
  | undefined;
80
+ // One EWMA tracker per displayed session, bounded: without eviction a TUI
81
+ // lifetime of session-hopping grows this map forever. Eviction only drops
82
+ // smoothing - a revisit restarts its baselines, exactly like a first sight.
83
+ // Recency refreshes on every poll, so the watched session is always the last
84
+ // one evicted.
85
+ const MAX_TRACKERS = 50;
86
+ const trackers = new Map<string, ReturnType<typeof createInstantTps>>();
87
+
88
+ const trackerOf = (sessionID: string): ReturnType<typeof createInstantTps> => {
89
+ const known = trackers.get(sessionID);
90
+ if (known !== undefined) {
91
+ trackers.delete(sessionID);
92
+ trackers.set(sessionID, known);
93
+ return known;
94
+ }
95
+ const fresh = createInstantTps();
96
+ if (trackers.size >= MAX_TRACKERS) {
97
+ for (const oldest of trackers.keys()) {
98
+ trackers.delete(oldest);
99
+ break;
100
+ }
101
+ }
102
+ trackers.set(sessionID, fresh);
103
+ return fresh;
104
+ };
55
105
 
56
106
  const scanMessages = (id: string, now: number): TpsScan => {
57
107
  let messages: readonly unknown[];
@@ -81,86 +131,74 @@ export function createTpsReader(
81
131
  const span = turnSpan(created, completed, streamed, now, "streamed");
82
132
  if (span === undefined) continue;
83
133
  const tokens = asRecord(message["tokens"]);
84
- // The numerator the TUI divides: output plus reasoning. Both are carried
85
- // so the union can add them without losing either rung.
134
+ // Generation: output plus reasoning, which keeps its own row too. A
135
+ // settled id-less turn keys on its final counts, so two settled records
136
+ // sharing a start but differing in reasoning stay distinct.
137
+ const output = tokens?.["output"];
138
+ const reasoning = tokens?.["reasoning"];
139
+ const settled = completed !== undefined || streamed !== undefined;
140
+ const key = turnKey(message["id"], created, completed, output, streamed);
86
141
  spans.push({
87
- key: turnKey(message["id"], created, completed, tokens?.["output"]),
88
- tokens: tokens?.["output"],
89
- reasoning: tokens?.["reasoning"],
142
+ key: settled ? `${key}:${asCount(reasoning) ?? "?"}` : key,
143
+ tokens: output,
144
+ reasoning,
90
145
  ...span,
91
146
  });
92
147
  }
93
148
  return { ok: true, assistant, stamped, spans };
94
149
  };
95
150
 
96
- // The lifetime average, the metric of last resort for a host that exposes no
97
- // per-message timestamps. Measured from the session's own clock
98
- // (`time.updated`, falling back to now) so a finished session settles on a
99
- // stable figure instead of decaying as it sits on screen. The numerator is
100
- // the session record's `output` plus its `reasoning`, the same pair the
101
- // stamped path divides: `tokens` is a `TokenUsage.Info`, so the reasoning
102
- // rung is present and counting output alone would under-report.
103
- const lifetimeTps = (
104
- sessionID: string,
105
- session: SessionLike | undefined,
106
- created: number,
107
- time: Record<string, unknown> | undefined,
108
- ): number | undefined => {
109
- const updated = asCount(time?.["updated"]);
110
- const end = updated === undefined ? Date.now() : Math.min(Date.now(), updated);
111
- const elapsed = end - created;
112
- if (elapsed <= 0) return undefined;
113
-
114
- const tokensOf = (source: SessionLike | undefined): number | undefined => {
151
+ // Generation tokens on record for the scope, for a host with no message
152
+ // timestamps: the session records' own `output` and `reasoning` rungs,
153
+ // summed over the family from a root. A child asking `family()` gets its
154
+ // ancestors and siblings too, so it keeps its own figure.
155
+ const recordGeneration = (sessionID: string, session: SessionLike | undefined): number => {
156
+ const generationOf = (source: SessionLike | undefined): number => {
115
157
  const tokens = asRecord(source?.tokens);
116
- if (tokens === undefined) return undefined;
117
- return (asCount(tokens["output"]) ?? 0) + (asCount(tokens["reasoning"]) ?? 0);
158
+ return (asCount(tokens?.["output"]) ?? 0) + (asCount(tokens?.["reasoning"]) ?? 0);
118
159
  };
119
-
120
- let output = tokensOf(session);
121
- // Only a family root owns the tree beneath it; a child asking `family()`
122
- // gets its ancestors and siblings too, so it keeps its own figure.
123
- if (isFamilyRoot(sessionID)) {
124
- try {
125
- const ids = context.data.session.family(sessionID) ?? [];
126
- if (ids.length > 1) {
127
- let total = 0;
128
- let sawOne = false;
129
- for (const id of ids) {
130
- const member = context.data.session.get(id) as SessionLike | undefined;
131
- const memberTokens = tokensOf(member);
132
- if (memberTokens === undefined) continue;
133
- total += memberTokens;
134
- sawOne = true;
135
- }
136
- if (sawOne) output = total;
160
+ if (!isFamilyRoot(sessionID)) return generationOf(session);
161
+ try {
162
+ const ids = context.data.session.family(sessionID) ?? [];
163
+ if (ids.length <= 1) return generationOf(session);
164
+ let total = 0;
165
+ for (const id of ids) {
166
+ if (id === sessionID) continue;
167
+ try {
168
+ total += generationOf(context.data.session.get(id) as SessionLike | undefined);
169
+ } catch {
170
+ // One unreadable member must not hide the rest.
137
171
  }
138
- } catch {
139
- // No family on this host: the session's own tokens still stand.
140
172
  }
173
+ return generationOf(session) + total;
174
+ } catch {
175
+ // No family on this host: the session's own tokens still stand.
176
+ return generationOf(session);
177
+ }
178
+ };
179
+
180
+ const busyOf = (sessionID: string): boolean | undefined => {
181
+ try {
182
+ return live?.busyOf?.(sessionID);
183
+ } catch {
184
+ return undefined;
141
185
  }
142
- return sessionThroughput(output, elapsed);
143
186
  };
144
187
 
145
188
  const computeTps = (sessionID: string, session: SessionLike | undefined): number | undefined => {
146
189
  const time = asRecord(session?.time);
147
190
  const created = asCount(time?.["created"]);
148
- if (created === undefined) return undefined;
149
-
150
- // A host proven unstamped needs no message read at all: its metric is the
151
- // lifetime average whether or not the read would have succeeded.
152
- if (hostStamps === false) return lifetimeTps(sessionID, session, created, time);
153
191
 
154
192
  // One `now` for the whole scope, so every in-flight turn ends at the same
155
193
  // instant and the union cannot be skewed by the scans drifting apart.
156
194
  const now = Date.now();
195
+ const busy = busyOf(sessionID);
157
196
 
158
- // Timestamped assistant tokens (output + reasoning) this session has
159
- // produced, plus — only from a family root — every subagent session's. A
160
- // child asking `family()` gets its ancestors and siblings back, so it keeps
161
- // its own spans.
162
- const scans: TpsScan[] = [scanMessages(sessionID, now)];
163
- if (isFamilyRoot(sessionID)) {
197
+ // Timestamped assistant generation this session has produced, plus - only
198
+ // from a family root - every subagent session's. A child asking `family()`
199
+ // gets its ancestors and siblings back, so it keeps its own spans.
200
+ const scans: TpsScan[] = hostStamps === false ? [] : [scanMessages(sessionID, now)];
201
+ if (hostStamps !== false && isFamilyRoot(sessionID)) {
164
202
  try {
165
203
  for (const id of context.data.session.family(sessionID) ?? []) {
166
204
  if (id !== sessionID) scans.push(scanMessages(id, now));
@@ -190,8 +228,30 @@ export function createTpsReader(
190
228
  else return undefined;
191
229
  }
192
230
 
193
- if (hostStamps === true) return unionSpanThroughput(spans);
194
- return lifetimeTps(sessionID, session, created, time);
231
+ const tracker = trackerOf(sessionID);
232
+ if (hostStamps === true) {
233
+ // Generating time is the union of the turns' own streaming spans: idle
234
+ // between turns was never recorded, so it can never enter the rate. An
235
+ // in-flight turn ends at now, so the denominator keeps pace with the
236
+ // decoder while work happens and freezes the instant it settles. The
237
+ // numerator over it is generation: output plus reasoning.
238
+ const { tokens } = unionGenerationTotals(spans);
239
+ const genMs = unionSpanMs(spans);
240
+ return tracker(tokens, genMs, busy);
241
+ }
242
+
243
+ // No timestamps on this host: the denominator is the busy-gated active
244
+ // clock, which runs only while the scope is actually working. Without that
245
+ // clock there is no honest denominator - the row hides rather than falling
246
+ // back to a lifetime average that bills idle as work.
247
+ if (created === undefined) return tracker(recordGeneration(sessionID, session), 0, busy);
248
+ let genMs = 0;
249
+ try {
250
+ genMs = live?.elapsedMsOf?.(sessionID, now) ?? 0;
251
+ } catch {
252
+ genMs = 0;
253
+ }
254
+ return tracker(recordGeneration(sessionID, session), genMs, busy);
195
255
  };
196
256
 
197
257
  const sessionTps = (sessionID: string, session: SessionLike | undefined): number | undefined => {
@@ -38,13 +38,11 @@ export interface StatSource {
38
38
  readonly busy?: unknown;
39
39
  readonly perms?: unknown;
40
40
  /**
41
- * Session throughput. On a host that stamps its messages this is an
42
- * active-work average: output plus reasoning tokens divided by the union of
43
- * the assistant turns' provider-active spans (`streamed - created`), with
44
- * idle between turns and the tool settlement after one excluded, subagents
45
- * summed in, so the figure freezes when work stops. On a host without
46
- * message timestamps it falls back to the lifetime average, which can still
47
- * sag. Either way it is derived from state the host already holds.
41
+ * Session output rate, drawn whole. A near-instantaneous figure: the delta
42
+ * of output tokens between successive polls over the delta of generating
43
+ * time (streaming spans, or the busy-gated active clock), smoothed and held
44
+ * through noise, frozen while idle, hidden until a minimum sample is on
45
+ * record. Derived from state the host already holds.
48
46
  */
49
47
  readonly tps?: unknown;
50
48
  readonly elapsedMs?: unknown;
@@ -98,8 +96,12 @@ type StatField = (typeof STAT_FIELDS)[number];
98
96
  * `caution` belongs here for a stronger reason than the others: its whole job is
99
97
  * noticing that time has passed without anything happening, so without a tick
100
98
  * its thresholds could never be crossed on screen.
99
+ *
100
+ * `tps` belongs here because it is a per-poll rate: without a tick it would
101
+ * only recompute on host events and sit static between them, which is what
102
+ * made the old figure feel frozen.
101
103
  */
102
- export const ANIMATED_FIELDS = ["caution", "status", "elapsed"] as const;
104
+ export const ANIMATED_FIELDS = ["caution", "status", "elapsed", "tps"] as const;
103
105
 
104
106
  export function isStatField(value: string): value is StatField {
105
107
  return STAT_FIELDS.some((field) => field === value);
package/src/tui/stats.ts CHANGED
@@ -16,9 +16,20 @@ export type { StatSegment } from "./rows.js";
16
16
  export { ANIMATED_FIELDS, DEFAULT_PLACEHOLDER, STAT_FIELDS, isStatField } from "./stat-fields.js";
17
17
  export type { StatSource } from "./stat-fields.js";
18
18
  export {
19
+ createInstantTps,
20
+ instantTpsRate,
19
21
  sessionThroughput,
22
+ smoothTpsRate,
23
+ TPS_EWMA_ALPHA,
24
+ TPS_MIN_GEN_MS,
25
+ TPS_MIN_TOKENS,
26
+ TPS_REPAINT_ABS,
27
+ TPS_REPAINT_RATIO,
28
+ tpsNeedsRepaint,
20
29
  turnKey,
21
30
  turnSpan,
31
+ unionGenerationTotals,
32
+ unionOutputTotals,
22
33
  unionSpanMs,
23
34
  unionSpanThroughput,
24
35
  unionSpanTotals,
@@ -5,12 +5,15 @@
5
5
  // Pure: no clock, no I/O, no rendering. Untrusted sample fields are coerced
6
6
  // through ./coerce.js so a garbage value is skipped rather than guessed at.
7
7
  //
8
- // Two rates live here. `sessionThroughput` is the whole-lifetime average, kept
8
+ // Three rates live here. `sessionThroughput` is the whole-lifetime average, kept
9
9
  // as the metric of last resort for a host that exposes no per-message
10
10
  // timestamps. `unionSpanThroughput` is the active-work average: output plus
11
11
  // reasoning tokens divided by the union of the assistant turns' own streaming
12
12
  // spans, so idle and tool-settlement time is never in the denominator and the
13
- // figure freezes once everything settles.
13
+ // figure freezes once everything settles. `createInstantTps` is the live row's
14
+ // tracker: generation-token per-poll deltas over generating-time deltas, smoothed
15
+ // with an EWMA and repainted through hysteresis, so the rail shows what the
16
+ // decoder is doing now instead of everything the session ever did.
14
17
 
15
18
  import { asCount, asText } from "./coerce.js";
16
19
 
@@ -94,14 +97,28 @@ export function turnSpan(
94
97
 
95
98
  /**
96
99
  * Identity of one assistant turn: the host's own message id when it carries
97
- * one, otherwise the tuple `(created, completed, output)` that defines the
98
- * record. Retries, replays and re-sent records share a key, so they contribute
99
- * their tokens once and their time once.
100
+ * one, otherwise the tuple `(created, completed)` plus - only once the turn
101
+ * has stopped decoding - its `output` count. A turn with neither end rung yet
102
+ * is still streaming, so its output count is still growing: leaving it out of
103
+ * the key keeps one stable identity across polls instead of re-keying (and
104
+ * re-counting) every snapshot of the same turn. A turn that finished decoding
105
+ * (`streamed` or `completed` recorded) has a final output count, so it stays
106
+ * in the key and two settled turns that share a start stay distinct. Retries,
107
+ * replays and re-sent records share a key, so they contribute their tokens
108
+ * once and their time once.
100
109
  */
101
- export function turnKey(id: unknown, created: unknown, completed: unknown, output: unknown): string {
110
+ export function turnKey(
111
+ id: unknown,
112
+ created: unknown,
113
+ completed: unknown,
114
+ output: unknown,
115
+ streamed?: unknown,
116
+ ): string {
102
117
  const own = asText(id);
103
118
  if (own !== undefined) return `id:${own}`;
104
- return `t:${asCount(created) ?? "?"}:${asCount(completed) ?? "?"}:${asCount(output) ?? "?"}`;
119
+ const stamp = `t:${asCount(created) ?? "?"}:${asCount(completed) ?? "?"}`;
120
+ if (asCount(completed) === undefined && asCount(streamed) === undefined) return stamp;
121
+ return `${stamp}:${asCount(output) ?? "?"}`;
105
122
  }
106
123
 
107
124
  /** Output + reasoning tokens and wall time the accepted turns actually cover. */
@@ -227,3 +244,200 @@ export function unionSpanThroughput(spans: readonly ThroughputSpan[]): number |
227
244
  if (tokens <= 0 || unionMs <= 0) return undefined;
228
245
  return tokens / (Math.max(unionMs, 1_000) / 1_000);
229
246
  }
247
+
248
+ /**
249
+ * Smoothing weight for the instantaneous TPS rate: each new per-poll sample
250
+ * moves the displayed figure 30% of the way toward it. Heavy enough to stop
251
+ * the row flickering on every poll, light enough that a real speedup shows
252
+ * within a few polls rather than sagging behind a lifetime average.
253
+ */
254
+ export const TPS_EWMA_ALPHA = 0.3;
255
+
256
+ /**
257
+ * Minimum generating time (ms) and output tokens before the TPS row draws
258
+ * anything. Below either, a per-poll rate is one lucky sample over a sliver
259
+ * of time - the exact "cheaty" flash the row used to print.
260
+ */
261
+ export const TPS_MIN_GEN_MS = 2_000;
262
+ export const TPS_MIN_TOKENS = 10;
263
+
264
+ /**
265
+ * Hysteresis for the TPS repaint: the held figure moves only when the new
266
+ * smoothed rate differs by at least one whole token/second or by at least
267
+ * ten percent, so sub-token jitter never repaints the row.
268
+ */
269
+ export const TPS_REPAINT_ABS = 1;
270
+ export const TPS_REPAINT_RATIO = 0.1;
271
+
272
+ /**
273
+ * One per-poll instantaneous rate: generation-token DELTA over generating-time
274
+ * DELTA, never over idle time. The caller passes only what happened since the
275
+ * previous poll; both deltas exclude idle by construction (the union of
276
+ * streaming spans, or the busy-gated active clock), so a pause can never sag
277
+ * the figure. Returns `undefined` when there is no new generating time to
278
+ * divide by.
279
+ */
280
+ export function instantTpsRate(deltaTokens: unknown, deltaMs: unknown): number | undefined {
281
+ const tokens = asCount(deltaTokens);
282
+ const ms = asCount(deltaMs);
283
+ if (tokens === undefined || ms === undefined || ms <= 0) return undefined;
284
+ return tokens / (ms / 1_000);
285
+ }
286
+
287
+ /**
288
+ * Fold one instantaneous sample into the running rate. The first sample seeds
289
+ * the average directly; every later one moves it `alpha` of the way toward
290
+ * the sample, so a single fast or slow poll bends the figure instead of
291
+ * replacing it.
292
+ */
293
+ export function smoothTpsRate(previous: number | undefined, sample: number, alpha: number = TPS_EWMA_ALPHA): number {
294
+ if (previous === undefined || !Number.isFinite(previous)) return sample;
295
+ if (!Number.isFinite(sample)) return previous;
296
+ return previous + alpha * (sample - previous);
297
+ }
298
+
299
+ /**
300
+ * Whether the held TPS figure should repaint for a new smoothed rate. The
301
+ * first rate always paints; afterwards only a move of at least one tok/s or
302
+ * at least ten percent does, so the row holds steady through noise.
303
+ */
304
+ export function tpsNeedsRepaint(displayed: number | undefined, smoothed: number): boolean {
305
+ if (displayed === undefined || !Number.isFinite(displayed)) return true;
306
+ if (!Number.isFinite(smoothed)) return false;
307
+ if (Math.abs(smoothed - displayed) >= TPS_REPAINT_ABS) return true;
308
+ if (displayed === 0) return smoothed !== 0;
309
+ return Math.abs(smoothed - displayed) / Math.abs(displayed) >= TPS_REPAINT_RATIO;
310
+ }
311
+
312
+ /**
313
+ * Generation tokens and generating time for the TPS numerator: output plus
314
+ * reasoning, the same pair the official TUI divides.
315
+ *
316
+ * The same identity rule, clamp, pre-sort and merge as `unionSpanTotals`.
317
+ * Only the live TPS path uses this. `unionOutputTotals` below stays as the
318
+ * output-only twin, and `unionSpanTotals` (which feeds the other rows) is
319
+ * unchanged.
320
+ */
321
+ export function unionGenerationTotals(spans: readonly ThroughputSpan[]): SpanTotals {
322
+ const seen = new Set<string>();
323
+ const accepted: Array<{ start: number; end: number }> = [];
324
+ let tokens = 0;
325
+
326
+ for (const span of spans) {
327
+ const key = asText(span.key);
328
+ if (key === undefined || seen.has(key)) continue;
329
+
330
+ const start = asCount(span.start);
331
+ const end = asCount(span.end);
332
+ if (start === undefined || end === undefined) continue;
333
+ const output = asCount(span.tokens);
334
+ const reasoning = asCount(span.reasoning);
335
+
336
+ seen.add(key);
337
+ accepted.push({ start, end: Math.max(start, end) });
338
+ tokens += (output ?? 0) + (reasoning ?? 0);
339
+ }
340
+
341
+ return { tokens, unionMs: mergedSpanMs(accepted) };
342
+ }
343
+
344
+ /**
345
+ * Output tokens and generating time: the output-only twin of
346
+ * `unionGenerationTotals`.
347
+ *
348
+ * The same identity rule, clamp, pre-sort and merge as `unionSpanTotals`, but
349
+ * the numerator counts OUTPUT tokens only. The live TPS path no longer uses
350
+ * this - it divides generation tokens (`unionGenerationTotals`) - so a
351
+ * thinking-heavy turn reads as speed on that row rather than as time spent
352
+ * with no output yet.
353
+ */
354
+ export function unionOutputTotals(spans: readonly ThroughputSpan[]): SpanTotals {
355
+ const seen = new Set<string>();
356
+ const accepted: Array<{ start: number; end: number }> = [];
357
+ let tokens = 0;
358
+
359
+ for (const span of spans) {
360
+ const key = asText(span.key);
361
+ if (key === undefined || seen.has(key)) continue;
362
+
363
+ const start = asCount(span.start);
364
+ const end = asCount(span.end);
365
+ if (start === undefined || end === undefined) continue;
366
+ const output = asCount(span.tokens);
367
+
368
+ seen.add(key);
369
+ accepted.push({ start, end: Math.max(start, end) });
370
+ tokens += output ?? 0;
371
+ }
372
+
373
+ return { tokens, unionMs: mergedSpanMs(accepted) };
374
+ }
375
+
376
+ /**
377
+ * Near-instantaneous generation rate for one displayed session scope.
378
+ *
379
+ * The caller feeds each poll's cumulative generation tokens and cumulative
380
+ * generating milliseconds (streaming-span union, or the busy-gated active
381
+ * clock - both exclude idle by construction) plus whether the scope is busy,
382
+ * and gets back the figure to draw, or `undefined` while there is nothing
383
+ * honest to show yet. Deltas between successive polls are the rate; the
384
+ * EWMA smooths it; hysteresis holds the paint; the minimum sample hides the
385
+ * row until ~2 s of generating time and ~10 tokens are on record; and a
386
+ * non-busy poll freezes on the last figure without touching the baselines, so
387
+ * idle can never dilute the rate - it only holds it.
388
+ */
389
+ export function createInstantTps(alpha: number = TPS_EWMA_ALPHA) {
390
+ let prevTokens: number | undefined;
391
+ let prevGenMs: number | undefined;
392
+ let smoothed: number | undefined;
393
+ let displayed: number | undefined;
394
+
395
+ return function sample(
396
+ totalTokens: unknown,
397
+ totalGenMs: unknown,
398
+ busy: unknown,
399
+ ): number | undefined {
400
+ // Not busy means frozen: hold the last figure, baselines untouched, so
401
+ // the idle stretch contributes nothing to either side of the next delta.
402
+ if (busy === false) return displayed;
403
+
404
+ const tokens = asCount(totalTokens);
405
+ const genMs = asCount(totalGenMs);
406
+ if (tokens === undefined || genMs === undefined) return displayed;
407
+
408
+ // First sight sets the baselines. The cumulative active average seeds the
409
+ // smoother, but only once the minimum sample is on record - before that
410
+ // the row hides rather than flashing a one-sample rate.
411
+ if (prevTokens === undefined || prevGenMs === undefined) {
412
+ prevTokens = tokens;
413
+ prevGenMs = genMs;
414
+ if (tokens < TPS_MIN_TOKENS || genMs < TPS_MIN_GEN_MS) return displayed;
415
+ smoothed = tokens / (genMs / 1_000);
416
+ if (tpsNeedsRepaint(displayed, smoothed)) displayed = smoothed;
417
+ return displayed;
418
+ }
419
+
420
+ const deltaTokens = tokens - prevTokens;
421
+ const deltaMs = genMs - prevGenMs;
422
+ // Counters must not step backwards; a reset rebaselines - baselines and
423
+ // smoother alike, since the pre-reset average belongs to another era -
424
+ // instead of dividing a negative delta into a nonsense rate.
425
+ if (deltaTokens < 0 || deltaMs < 0) {
426
+ prevTokens = tokens;
427
+ prevGenMs = genMs;
428
+ smoothed = undefined;
429
+ return displayed;
430
+ }
431
+ prevTokens = tokens;
432
+ prevGenMs = genMs;
433
+
434
+ if (tokens < TPS_MIN_TOKENS || genMs < TPS_MIN_GEN_MS) return displayed;
435
+ // No new generating time: nothing was produced *in time*, so there is no
436
+ // sample - hold, rather than dividing zero new tokens by zero new time.
437
+ if (deltaMs <= 0) return displayed;
438
+ const instant = deltaTokens / (deltaMs / 1_000);
439
+ smoothed = smoothTpsRate(smoothed, instant, alpha);
440
+ if (tpsNeedsRepaint(displayed, smoothed)) displayed = smoothed;
441
+ return displayed;
442
+ };
443
+ }