oc-flight-deck 0.10.3 → 0.11.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/src/tui/rows.ts CHANGED
@@ -197,6 +197,49 @@ function goValueSegments(source: StatSource, layout: LayoutHint): StatSegment[]
197
197
  return segments;
198
198
  }
199
199
 
200
+ /**
201
+ * The annunciator mark the caller built, validated at the untrusted boundary.
202
+ *
203
+ * `source.caution` is `unknown`, so the shape is re-checked here: a mark is kept
204
+ * only when its glyph and text are non-empty strings and its tone is one of the
205
+ * two severity roles. Anything else falls through to the plain-string path.
206
+ */
207
+ function asCautionMark(value: unknown): { glyph: string; tone: StyleColor; text: string } | undefined {
208
+ const record = asRecord(value);
209
+ if (record === undefined) return undefined;
210
+ const glyph = asText(record["glyph"]);
211
+ const text = asText(record["text"]);
212
+ const tone = record["tone"];
213
+ if (glyph === undefined || text === undefined) return undefined;
214
+ if (tone !== "warning" && tone !== "error") return undefined;
215
+ return { glyph, tone, text };
216
+ }
217
+
218
+ /**
219
+ * The `caution` row's value as coloured segments, or `undefined` when there is
220
+ * nothing to draw.
221
+ *
222
+ * The annunciator carries its severity in the mark itself: the glyph runs in the
223
+ * severity's own tone (`error` for a caution, `warning` for a watch) while the
224
+ * words after it keep the row's colour, so the row does not read as a different
225
+ * kind of line. A legacy plain-string value is accepted unchanged, in the row's
226
+ * own colour, which keeps every existing caller working.
227
+ */
228
+ function cautionValueSegments(source: StatSource): StatSegment[] | undefined {
229
+ const mark = asCautionMark(source.caution);
230
+ if (mark !== undefined) {
231
+ // `plain` first, then split: flattening replaces each control character with
232
+ // one space, so the glyph's length still indexes the run boundary.
233
+ const text = plain(mark.text);
234
+ return [
235
+ { text: text.slice(0, mark.glyph.length), tone: mark.tone },
236
+ { text: text.slice(mark.glyph.length) },
237
+ ];
238
+ }
239
+ const text = asText(source.caution);
240
+ return text === undefined ? undefined : [{ text: plain(text) }];
241
+ }
242
+
200
243
  /**
201
244
  * Render one named field, or `undefined` when the host has not supplied it yet.
202
245
  *
@@ -226,10 +269,13 @@ export function statLine(
226
269
  case "caution": {
227
270
  // Rendered only when the caller found something to say, which is what
228
271
  // keeps a healthy session visually identical to one without the
229
- // annunciator at all. The string already carries its glyph; nothing here
230
- // knows or cares about severity.
231
- const text = asText(source.caution);
232
- return text === undefined ? undefined : row("caution", text);
272
+ // annunciator at all. The plain string is the exact join of the coloured
273
+ // segments, so the string view and the coloured view agree; a legacy plain
274
+ // string value is accepted too, with no tone.
275
+ const value = cautionValueSegments(source);
276
+ return value === undefined
277
+ ? undefined
278
+ : row("caution", value.map((segment) => segment.text).join(""));
233
279
  }
234
280
  case "status": {
235
281
  const status = asText(source.status);
@@ -318,13 +364,27 @@ export function statLine(
318
364
  }
319
365
  case "cache": {
320
366
  const tokens = asRecord(source.tokens);
321
- const cache = asRecord(tokens?.cache);
367
+ if (tokens === undefined) return undefined;
368
+ const cache = asRecord(tokens.cache);
322
369
  const read = asCount(cache?.read);
323
- if (read === undefined || read === 0) return undefined;
370
+ if (read === undefined) return undefined;
324
371
  const input = asCount(tokens?.input);
325
372
  // Hit ratio is the whole point: it explains a cheap bill on a huge token
326
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).
327
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
+ }
328
388
  const value =
329
389
  total === undefined || total === 0
330
390
  ? `${formatCount(read)} read`
@@ -336,11 +396,14 @@ export function statLine(
336
396
  const used = asCount(context?.used);
337
397
  if (used === undefined || used === 0) return undefined;
338
398
  const limit = asCount(context?.limit);
339
- 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`);
340
403
  const ratio = used / limit;
341
404
  // Show the percentage whenever the host reports it, but never a bar that
342
405
  // reads as more than full.
343
- 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)}%`);
344
407
  }
345
408
  case "perms": {
346
409
  const perms = asRecord(source.perms);
@@ -367,10 +430,14 @@ export function statLine(
367
430
  }
368
431
  case "tps": {
369
432
  const tps = asCount(source.tps);
370
- if (tps === undefined || tps === 0) return undefined;
371
- // One decimal, exactly as the official TUI renders it: rounding to a
372
- // whole number would overstate a slow turn by up to half a token/second.
373
- 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`);
374
441
  }
375
442
  case "spark": {
376
443
  const values = Array.isArray(source.spark) ? source.spark.map((value) => asCount(value) ?? 0) : [];
@@ -424,16 +491,21 @@ export function statLine(
424
491
  * One field's rail row as coloured segments, or `undefined` when the field is
425
492
  * not segment-aware or has nothing to draw.
426
493
  *
427
- * Only `go` is segment-aware today — the one row whose severity lives on part
428
- * of the line rather than the whole. Every other field returns `undefined` and
429
- * the caller falls through to {@link statLine}, so there is still exactly one
430
- * place that knows a row's text.
494
+ * The `go` dials and the `caution` mark are the segment-aware rows — the two
495
+ * whose severity lives on part of the line rather than the whole. Every other
496
+ * field returns `undefined` and the caller falls through to {@link statLine},
497
+ * so there is still exactly one place that knows a row's text.
431
498
  */
432
499
  export function statSegments(
433
500
  field: string,
434
501
  source: StatSource,
435
502
  layout: LayoutHint = {},
436
503
  ): readonly StatSegment[] | undefined {
504
+ if (field === "caution") {
505
+ const value = cautionValueSegments(source);
506
+ if (value === undefined) return undefined;
507
+ return [{ text: labelPrefix("caution", layout.labelWidth ?? DEFAULT_LABEL_WIDTH) }, ...value];
508
+ }
437
509
  if (field !== "go") return undefined;
438
510
  const value = goValueSegments(source, layout);
439
511
  if (value === undefined) return undefined;
@@ -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,24 @@
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 output tokens only - reasoning keeps its own row - and the
11
+ // denominator is generating time only: the union of the turns' own streaming
12
+ // spans on a stamped host, the busy-gated active clock on one without stamps.
13
+ // Idle is never divided by; when nothing is busy the tracker freezes and the
14
+ // row holds its last figure. The row hides until ~2 s of generating time and
15
+ // ~10 tokens are on record, rather than flashing a one-sample rate.
8
16
  //
9
17
  // The capability is learned once and remembered for the process. `undefined`
10
18
  // means "not yet known": a read that failed, or carried no assistant turns,
11
19
  // tells us nothing and must not choose a metric. Once known it is sticky in
12
20
  // 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) —
21
+ // stamped host back to the clock path (nor an unstamped host off it) -
14
22
  // a failure just hides the row. One value for the whole host, deliberately
15
23
  // not keyed by session.
16
24
  //
@@ -22,16 +30,19 @@
22
30
  // One factory closes over the plugin `context`; `isFamilyRoot` comes from
23
31
  // ./session-reads.js so a child session keeps its own figure while a root
24
32
  // 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
33
 
30
34
  import type { Plugin } from "@opencode/plugin/tui";
31
35
  import { asCount, asRecord, type SessionLike } from "./coerce.js";
32
- import { sessionThroughput, turnKey, turnSpan, unionSpanThroughput, type ThroughputSpan } from "./stats.js";
36
+ import {
37
+ createInstantTps,
38
+ turnKey,
39
+ turnSpan,
40
+ unionOutputTotals,
41
+ unionSpanMs,
42
+ type ThroughputSpan,
43
+ } from "./stats.js";
33
44
 
34
- /** What one session's message list contributes to its active-work average. */
45
+ /** What one session's message list contributes to its instantaneous rate. */
35
46
  interface TpsScan {
36
47
  /** False only when the host refused to list the session's messages. */
37
48
  readonly ok: boolean;
@@ -43,15 +54,53 @@ interface TpsScan {
43
54
  readonly spans: readonly ThroughputSpan[];
44
55
  }
45
56
 
57
+ /**
58
+ * The live signals the TPS reader borrows rather than re-deriving: the busy
59
+ * gate (is anything working?) freezes the row on idle, and the active clock
60
+ * (how much generating time is on record?) is the denominator for a host
61
+ * with no message timestamps. Both come from ./session-reads.js; absent, the
62
+ * stamped path still works and the unstamped path hides for lack of time.
63
+ */
64
+ export interface TpsLiveReads {
65
+ readonly busyOf?: (sessionID: string) => boolean | undefined;
66
+ readonly elapsedMsOf?: (sessionID: string, now: number) => number | undefined;
67
+ }
68
+
46
69
  export function createTpsReader(
47
70
  context: Plugin.Context,
48
71
  isFamilyRoot: (sessionID: string) => boolean,
72
+ live?: TpsLiveReads,
49
73
  ) {
50
74
  const TPS_CACHE_MS = 1_000;
51
75
  let hostStamps: boolean | undefined;
52
76
  let tpsCache:
53
77
  | { readonly sessionID: string; readonly at: number; readonly value: number | undefined }
54
78
  | undefined;
79
+ // One EWMA tracker per displayed session, bounded: without eviction a TUI
80
+ // lifetime of session-hopping grows this map forever. Eviction only drops
81
+ // smoothing - a revisit restarts its baselines, exactly like a first sight.
82
+ // Recency refreshes on every poll, so the watched session is always the last
83
+ // one evicted.
84
+ const MAX_TRACKERS = 50;
85
+ const trackers = new Map<string, ReturnType<typeof createInstantTps>>();
86
+
87
+ const trackerOf = (sessionID: string): ReturnType<typeof createInstantTps> => {
88
+ const known = trackers.get(sessionID);
89
+ if (known !== undefined) {
90
+ trackers.delete(sessionID);
91
+ trackers.set(sessionID, known);
92
+ return known;
93
+ }
94
+ const fresh = createInstantTps();
95
+ if (trackers.size >= MAX_TRACKERS) {
96
+ for (const oldest of trackers.keys()) {
97
+ trackers.delete(oldest);
98
+ break;
99
+ }
100
+ }
101
+ trackers.set(sessionID, fresh);
102
+ return fresh;
103
+ };
55
104
 
56
105
  const scanMessages = (id: string, now: number): TpsScan => {
57
106
  let messages: readonly unknown[];
@@ -81,86 +130,67 @@ export function createTpsReader(
81
130
  const span = turnSpan(created, completed, streamed, now, "streamed");
82
131
  if (span === undefined) continue;
83
132
  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.
133
+ // Output only: reasoning has its own row and no longer inflates the rate.
86
134
  spans.push({
87
- key: turnKey(message["id"], created, completed, tokens?.["output"]),
135
+ key: turnKey(message["id"], created, completed, tokens?.["output"], streamed),
88
136
  tokens: tokens?.["output"],
89
- reasoning: tokens?.["reasoning"],
90
137
  ...span,
91
138
  });
92
139
  }
93
140
  return { ok: true, assistant, stamped, spans };
94
141
  };
95
142
 
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 => {
143
+ // Output tokens on record for the scope, for a host with no message
144
+ // timestamps: the session records' own `output` rung, summed over the family
145
+ // from a root. A child asking `family()` gets its ancestors and siblings
146
+ // too, so it keeps its own figure. Reasoning is deliberately excluded.
147
+ const recordOutput = (sessionID: string, session: SessionLike | undefined): number => {
148
+ const outputOf = (source: SessionLike | undefined): number => {
115
149
  const tokens = asRecord(source?.tokens);
116
- if (tokens === undefined) return undefined;
117
- return (asCount(tokens["output"]) ?? 0) + (asCount(tokens["reasoning"]) ?? 0);
150
+ return asCount(tokens?.["output"]) ?? 0;
118
151
  };
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;
152
+ if (!isFamilyRoot(sessionID)) return outputOf(session);
153
+ try {
154
+ const ids = context.data.session.family(sessionID) ?? [];
155
+ if (ids.length <= 1) return outputOf(session);
156
+ let total = 0;
157
+ for (const id of ids) {
158
+ if (id === sessionID) continue;
159
+ try {
160
+ total += outputOf(context.data.session.get(id) as SessionLike | undefined);
161
+ } catch {
162
+ // One unreadable member must not hide the rest.
137
163
  }
138
- } catch {
139
- // No family on this host: the session's own tokens still stand.
140
164
  }
165
+ return outputOf(session) + total;
166
+ } catch {
167
+ // No family on this host: the session's own tokens still stand.
168
+ return outputOf(session);
169
+ }
170
+ };
171
+
172
+ const busyOf = (sessionID: string): boolean | undefined => {
173
+ try {
174
+ return live?.busyOf?.(sessionID);
175
+ } catch {
176
+ return undefined;
141
177
  }
142
- return sessionThroughput(output, elapsed);
143
178
  };
144
179
 
145
180
  const computeTps = (sessionID: string, session: SessionLike | undefined): number | undefined => {
146
181
  const time = asRecord(session?.time);
147
182
  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
183
 
154
184
  // One `now` for the whole scope, so every in-flight turn ends at the same
155
185
  // instant and the union cannot be skewed by the scans drifting apart.
156
186
  const now = Date.now();
187
+ const busy = busyOf(sessionID);
157
188
 
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)) {
189
+ // Timestamped assistant output this session has produced, plus - only from
190
+ // a family root - every subagent session's. A child asking `family()` gets
191
+ // its ancestors and siblings back, so it keeps its own spans.
192
+ const scans: TpsScan[] = hostStamps === false ? [] : [scanMessages(sessionID, now)];
193
+ if (hostStamps !== false && isFamilyRoot(sessionID)) {
164
194
  try {
165
195
  for (const id of context.data.session.family(sessionID) ?? []) {
166
196
  if (id !== sessionID) scans.push(scanMessages(id, now));
@@ -190,8 +220,29 @@ export function createTpsReader(
190
220
  else return undefined;
191
221
  }
192
222
 
193
- if (hostStamps === true) return unionSpanThroughput(spans);
194
- return lifetimeTps(sessionID, session, created, time);
223
+ const tracker = trackerOf(sessionID);
224
+ if (hostStamps === true) {
225
+ // Generating time is the union of the turns' own streaming spans: idle
226
+ // between turns was never recorded, so it can never enter the rate. An
227
+ // in-flight turn ends at now, so the denominator keeps pace with the
228
+ // decoder while work happens and freezes the instant it settles.
229
+ const { tokens } = unionOutputTotals(spans);
230
+ const genMs = unionSpanMs(spans);
231
+ return tracker(tokens, genMs, busy);
232
+ }
233
+
234
+ // No timestamps on this host: the denominator is the busy-gated active
235
+ // clock, which runs only while the scope is actually working. Without that
236
+ // clock there is no honest denominator - the row hides rather than falling
237
+ // back to a lifetime average that bills idle as work.
238
+ if (created === undefined) return tracker(recordOutput(sessionID, session), 0, busy);
239
+ let genMs = 0;
240
+ try {
241
+ genMs = live?.elapsedMsOf?.(sessionID, now) ?? 0;
242
+ } catch {
243
+ genMs = 0;
244
+ }
245
+ return tracker(recordOutput(sessionID, session), genMs, busy);
195
246
  };
196
247
 
197
248
  const sessionTps = (sessionID: string, session: SessionLike | undefined): number | undefined => {
@@ -12,9 +12,11 @@ export interface StatSource {
12
12
  /**
13
13
  * The annunciator line, precomputed by the caller.
14
14
  *
15
- * A plain string on purpose: the rules that decide whether something is wrong
16
- * live in ./caution.ts and need the clock and the session snapshot, not a
17
- * formatting function. Severity is already encoded in the glyph.
15
+ * Either a plain string (legacy, drawn in the row's own colour) or the mark
16
+ * returned by `caution.ts`'s `cautionMark`: its `glyph` and `tone` ride to
17
+ * the renderer so severity is carried by a coloured run. The rules that
18
+ * decide whether something is wrong live in ./caution.ts and need the clock
19
+ * and the session snapshot, not a formatting function.
18
20
  */
19
21
  readonly caution?: unknown;
20
22
  readonly agent?: unknown;
@@ -36,13 +38,11 @@ export interface StatSource {
36
38
  readonly busy?: unknown;
37
39
  readonly perms?: unknown;
38
40
  /**
39
- * Session throughput. On a host that stamps its messages this is an
40
- * active-work average: output plus reasoning tokens divided by the union of
41
- * the assistant turns' provider-active spans (`streamed - created`), with
42
- * idle between turns and the tool settlement after one excluded, subagents
43
- * summed in, so the figure freezes when work stops. On a host without
44
- * message timestamps it falls back to the lifetime average, which can still
45
- * 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.
46
46
  */
47
47
  readonly tps?: unknown;
48
48
  readonly elapsedMs?: unknown;
@@ -96,8 +96,12 @@ type StatField = (typeof STAT_FIELDS)[number];
96
96
  * `caution` belongs here for a stronger reason than the others: its whole job is
97
97
  * noticing that time has passed without anything happening, so without a tick
98
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.
99
103
  */
100
- export const ANIMATED_FIELDS = ["caution", "status", "elapsed"] as const;
104
+ export const ANIMATED_FIELDS = ["caution", "status", "elapsed", "tps"] as const;
101
105
 
102
106
  export function isStatField(value: string): value is StatField {
103
107
  return STAT_FIELDS.some((field) => field === value);
package/src/tui/stats.ts CHANGED
@@ -16,9 +16,19 @@ 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
+ unionOutputTotals,
22
32
  unionSpanMs,
23
33
  unionSpanThroughput,
24
34
  unionSpanTotals,