oc-flight-deck 0.12.0 → 0.19.1

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.
@@ -5,6 +5,7 @@
5
5
  // ticker; `LayoutHint` carries per-call row geometry. Untrusted values are read
6
6
  // through ./coerce.js rather than re-checked here.
7
7
 
8
+ import { DEFAULT_BAR_WIDTH, formatCost, formatCount, formatDuration, fuelBar } from "./format.js";
8
9
  import type { DurationStyle } from "./format.js";
9
10
 
10
11
  /** The subset of a session snapshot the rail reads. All fields are untrusted. */
@@ -104,7 +105,41 @@ type StatField = (typeof STAT_FIELDS)[number];
104
105
  export const ANIMATED_FIELDS = ["caution", "status", "elapsed", "tps"] as const;
105
106
 
106
107
  export function isStatField(value: string): value is StatField {
107
- return STAT_FIELDS.some((field) => field === value);
108
+ // `session` is the display alias for `ses`: accepted here and folded back by
109
+ // `canonicalField`, but kept out of `STAT_FIELDS` on purpose — that array is
110
+ // the config vocabulary echoed in config error messages, and the key stays
111
+ // `ses`.
112
+ return value === "session" || STAT_FIELDS.some((field) => field === value);
113
+ }
114
+
115
+ /**
116
+ * The canonical config key for a field name.
117
+ *
118
+ * `session` is accepted as an alias for `ses` and folds back to it; every
119
+ * other name is returned unchanged. The renderers canonicalize their field
120
+ * argument at entry, so `statLine("session", …)` renders byte-identically to
121
+ * `statLine("ses", …)`.
122
+ */
123
+ export function canonicalField(name: string): string {
124
+ return name === "session" ? "ses" : name;
125
+ }
126
+
127
+ /**
128
+ * The label a field draws in the label column.
129
+ *
130
+ * `ses` draws as `session`, which is what the row's value previews; every
131
+ * other field draws its own name. Both renderers resolve through here, so the
132
+ * plain-string view and the segmented view can never disagree on a label.
133
+ *
134
+ * `labels` is `layout.labels` — the per-row rename, keyed by the SAME canonical
135
+ * name `sidebar.rows` uses (`session` folded to `ses`), so one override lands
136
+ * on whichever spelling the row list carried. An absent map or an absent key
137
+ * draws the built-in label untouched.
138
+ */
139
+ export function fieldLabel(field: string, labels?: Readonly<Record<string, string>>): string {
140
+ const override = labels?.[canonicalField(field)];
141
+ if (override !== undefined) return override;
142
+ return field === "ses" ? "session" : field;
108
143
  }
109
144
 
110
145
  /**
@@ -132,14 +167,22 @@ export interface LayoutHint {
132
167
  * a property of `sidebar.rows`, not a separate setting to find.
133
168
  */
134
169
  readonly hasTotalRow?: boolean;
170
+ /**
171
+ * Per-row label overrides, keyed by the canonical row name (`ses`, not
172
+ * `session`). Carried here rather than read from config directly so both
173
+ * renderers resolve a row's label from the same place they already resolve
174
+ * its geometry.
175
+ */
176
+ readonly labels?: Readonly<Record<string, string>>;
135
177
  /**
136
178
  * When true, `statRows` renders one row per named field even when the host
137
- * has no data for it, using `placeholder` as the value. Default off when
138
- * calling `statRows` directly; `sidebarLines` turns it on from
179
+ * has no data for it, using `skeletonValue` (a live-shaped zero) and falling
180
+ * back to `placeholder` for the fields that have no skeleton. Default off
181
+ * when calling `statRows` directly; `sidebarLines` turns it on from
139
182
  * `config.sidebar.persist`.
140
183
  */
141
184
  readonly persist?: boolean;
142
- /** Value shown for a row with no data when `persist` is on. Default `"—"`. */
185
+ /** Fallback value for a data-less row with no skeleton when `persist` is on. Default `"—"`. */
143
186
  readonly placeholder?: string;
144
187
  /**
145
188
  * The clock the `go` row reads its relative reset hint against.
@@ -151,9 +194,60 @@ export interface LayoutHint {
151
194
  readonly nowMs?: number;
152
195
  }
153
196
 
154
- /** Placeholder value for a persistent row with no data yet. */
197
+ /** Fallback placeholder for a persistent row with no data and no skeleton. */
155
198
  export const DEFAULT_PLACEHOLDER = "—";
156
199
 
157
200
  export const DEFAULT_LABEL_WIDTH = 10;
158
201
  export const DEFAULT_SPARK_WIDTH = 12;
159
202
 
203
+ /**
204
+ * The value a data-less row draws when `sidebar.persist` is on.
205
+ *
206
+ * Zero skeletons, not dashes: each is built from the same formatter a live
207
+ * zero would use, so it is byte-identical to a real zero and the rail keeps
208
+ * its shape while reading alive rather than reading broken. `caution` has no
209
+ * skeleton — returning `undefined` keeps the annunciator silent when there is
210
+ * nothing to say, and its silence is the design. An unknown name also yields
211
+ * `undefined`, so a typo stays skipped rather than drawn.
212
+ */
213
+ export function skeletonValue(field: string, layout: LayoutHint): string | undefined {
214
+ switch (canonicalField(field)) {
215
+ case "cost":
216
+ case "total":
217
+ case "project":
218
+ return formatCost(0);
219
+ case "tokens":
220
+ return "0 in · 0 out";
221
+ case "cache":
222
+ return "0 read";
223
+ case "context":
224
+ return `${fuelBar(0, layout.barWidth ?? DEFAULT_BAR_WIDTH)} ~0%`;
225
+ case "perms":
226
+ return "0 waiting";
227
+ case "elapsed":
228
+ return formatDuration(0, layout.durationStyle);
229
+ case "tps":
230
+ return "0 tok/s";
231
+ case "spark":
232
+ return "▁".repeat(Math.max(0, Math.floor(layout.sparkWidth ?? DEFAULT_SPARK_WIDTH)));
233
+ case "reasoning":
234
+ return formatCount(0);
235
+ case "turns":
236
+ return "0";
237
+ case "go":
238
+ return "○ 0 ○ 0 ○ 0";
239
+ case "status":
240
+ return "○ idle";
241
+ case "agent":
242
+ case "model":
243
+ case "ses":
244
+ return "none";
245
+ case "branch":
246
+ return "no branch";
247
+ case "guard":
248
+ return "unknown";
249
+ default:
250
+ return undefined;
251
+ }
252
+ }
253
+
package/src/tui/stats.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  // Live session readouts for the Flight Deck rail.
2
2
  //
3
3
  // Everything here is derived from state the host already holds in memory and
4
- // hands to the plugin. There is no network call, no server, and no storage
5
- // write: this module turns a session snapshot into strings.
4
+ // hands to the plugin. This module itself makes no network call, no server,
5
+ // and no storage write: it turns a session snapshot into strings. The opt-in
6
+ // `go` row and `sidebar.footer.go` panel live outside this module (./go.ts):
7
+ // enabling either polls https://opencode.ai/zen/go/v1/usage every 60 seconds,
8
+ // and only with FLIGHT_DECK_GO_LOG=1 appends one observation line per poll to
9
+ // tmpdir()/opencode/flight-deck-go.log (never the key).
6
10
  //
7
11
  // The implementation is split by responsibility: ./stat-fields.js holds the
8
12
  // vocabulary, ./coerce.js the coercion guards, ./format.js the short strings
@@ -13,25 +17,20 @@
13
17
  export { clip, formatCost, formatCount, formatDuration, fuelBar, sparkline } from "./format.js";
14
18
  export { statLine, statRows, statSegments } from "./rows.js";
15
19
  export type { StatSegment } from "./rows.js";
16
- export { ANIMATED_FIELDS, DEFAULT_PLACEHOLDER, STAT_FIELDS, isStatField } from "./stat-fields.js";
20
+ export { ANIMATED_FIELDS, DEFAULT_PLACEHOLDER, STAT_FIELDS, canonicalField, fieldLabel, isStatField, skeletonValue } from "./stat-fields.js";
17
21
  export type { StatSource } from "./stat-fields.js";
18
22
  export {
19
23
  createInstantTps,
20
24
  instantTpsRate,
21
- sessionThroughput,
22
25
  smoothTpsRate,
23
26
  TPS_EWMA_ALPHA,
24
- TPS_MIN_GEN_MS,
25
- TPS_MIN_TOKENS,
26
27
  TPS_REPAINT_ABS,
27
28
  TPS_REPAINT_RATIO,
28
29
  tpsNeedsRepaint,
29
30
  turnKey,
30
31
  turnSpan,
31
32
  unionGenerationTotals,
32
- unionOutputTotals,
33
33
  unionSpanMs,
34
- unionSpanThroughput,
35
34
  unionSpanTotals,
36
35
  } from "./throughput.js";
37
- export type { SpanEndPreference, SpanTotals, ThroughputSpan } from "./throughput.js";
36
+ export type { SpanTotals, ThroughputSpan } from "./throughput.js";
package/src/tui/style.ts CHANGED
@@ -10,10 +10,27 @@
10
10
  // token has always done.
11
11
  //
12
12
  // Everything is a table lookup, so the config surface is trivial to test.
13
- // `attributeMask` is the one place that reads @opentui/core, because the bits
14
- // must be the vendored renderer's own constants — never re-derived, never ANSI.
13
+ // `attributeMask` pins the host renderer's descriptor bits as local literals
14
+ // rather than value-importing them: the plugin consumes the host's renderer
15
+ // through the plugin context and must not ship or import a vendored copy, so
16
+ // no `@opentui/*` import may appear here. The values are the host's
17
+ // `TextAttributes` bits (NONE=0, BOLD=1, DIM=2, ITALIC=4, UNDERLINE=8,
18
+ // BLINK=16, INVERSE=32, HIDDEN=64, STRIKETHROUGH=128); fixtures/style.test.ts
19
+ // asserts them against the vendored enum, so a host change fails loudly
20
+ // instead of desyncing silently.
15
21
 
16
- import { TextAttributes } from "@opentui/core";
22
+ /** The host renderer's text-attribute bits, pinned as literals (see above). */
23
+ const TextAttributes = {
24
+ NONE: 0,
25
+ BOLD: 1,
26
+ DIM: 2,
27
+ ITALIC: 4,
28
+ UNDERLINE: 8,
29
+ BLINK: 16,
30
+ INVERSE: 32,
31
+ HIDDEN: 64,
32
+ STRIKETHROUGH: 128,
33
+ } as const;
17
34
 
18
35
  /** Colours a config may name. Roles, not raw theme tokens. */
19
36
  export const STYLE_COLORS = ["default", "subdued", "warning", "error", "success", "info"] as const;
@@ -108,8 +125,10 @@ export function themeColor(color: StyleColor, theme: ThemeLike): unknown {
108
125
  }
109
126
 
110
127
  /**
111
- * Renderer bits for each name, read from the vendored enum rather than
112
- * re-derived, so a renderer change cannot silently desync the config surface.
128
+ * Renderer bits for each name, pinned to the host's descriptor values so no
129
+ * vendored copy is imported; fixtures/style.test.ts asserts these literals
130
+ * against the vendored enum, so a renderer change fails loudly rather than
131
+ * desyncing silently.
113
132
  */
114
133
  const ATTRIBUTE_BITS: Readonly<Record<StyleAttribute, number>> = {
115
134
  bold: TextAttributes.BOLD,
@@ -5,11 +5,9 @@
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
- // Three rates live here. `sessionThroughput` is the whole-lifetime average, kept
9
- // as the metric of last resort for a host that exposes no per-message
10
- // timestamps. `unionSpanThroughput` is the active-work average: output plus
11
- // reasoning tokens divided by the union of the assistant turns' own streaming
12
- // spans, so idle and tool-settlement time is never in the denominator and the
8
+ // Two pieces live here. The union helpers sum generation tokens (output plus
9
+ // reasoning, the same pair the official TUI divides) and merge the assistant
10
+ // turns' own streaming spans, so idle time is never in the denominator and the
13
11
  // figure freezes once everything settles. `createInstantTps` is the live row's
14
12
  // tracker: generation-token per-poll deltas over generating-time deltas, smoothed
15
13
  // with an EWMA and repainted through hysteresis, so the rail shows what the
@@ -17,28 +15,6 @@
17
15
 
18
16
  import { asCount, asText } from "./coerce.js";
19
17
 
20
- /**
21
- * Overall session throughput: output plus reasoning tokens over the session's
22
- * lifetime.
23
- *
24
- * `tokens` is the same numerator the active-work average divides — a session
25
- * record's `tokens` is a `TokenUsage.Info`, so its `reasoning` rung is present
26
- * and belongs on this path too. Counting output alone would under-report a
27
- * thinking-heavy model and disagree with the row's stated definition.
28
- *
29
- * Unlike the active-work average, this is the whole conversation's average, so
30
- * it includes every subagent and every pause. A just-started session is floored
31
- * at one second so it cannot divide by a sliver of time and flash an absurd
32
- * rate. Returns `undefined` when there is nothing to divide.
33
- */
34
- export function sessionThroughput(tokens: unknown, elapsedMs: unknown): number | undefined {
35
- const total = asCount(tokens);
36
- const elapsed = asCount(elapsedMs);
37
- if (total === undefined || total <= 0) return undefined;
38
- if (elapsed === undefined || elapsed <= 0) return undefined;
39
- return total / (Math.max(elapsed, 1_000) / 1_000);
40
- }
41
-
42
18
  /**
43
19
  * One assistant turn's contribution to the active-work average.
44
20
  *
@@ -55,25 +31,16 @@ export interface ThroughputSpan {
55
31
  readonly end?: unknown;
56
32
  }
57
33
 
58
- /**
59
- * Which recorded stamp ends an assistant turn's span when more than one is
60
- * present. The choice is the caller's, not the helper's: the two consumers want
61
- * different clocks off the same record.
62
- *
63
- * `"streamed"` ends at `time.streamed`, the moment the provider stopped
64
- * decoding - the official TUI's numerator clock, used by `tps`.
65
- * `"completed"` ends at `time.completed`, once the turn's tools have settled -
66
- * the busy clock, used by the `elapsed` seed.
67
- */
68
- export type SpanEndPreference = "streamed" | "completed";
69
-
70
34
  /**
71
35
  * Resolve one assistant turn's span from its timestamp rungs.
72
36
  *
73
- * `start` is `time.created`. `end` is the stamp `preference` names first when
74
- * both are recorded, else the other rung, else the caller's `nowMs` for a turn
75
- * still in flight. So `"streamed"` reads `streamed`, then `completed`;
76
- * `"completed"` reads `completed`, then `streamed`. A clock that steps backwards
37
+ * `start` is `time.created`. `end` is `time.streamed` — the moment the
38
+ * provider stopped decoding, the official TUI's numerator clock — then
39
+ * `time.completed`, else the caller's `nowMs` for a turn still in flight.
40
+ * (The elapsed clock used to prefer `completed` here so a turn's tool
41
+ * settlement stayed in its tally; it now resolves that end itself in
42
+ * ./session-reads.js, leaving this helper with the single decoding clock
43
+ * both remaining callers want.) A clock that steps backwards
77
44
  * is clamped to a zero-length span rather than a negative one, so skew can never
78
45
  * subtract time from the union. Returns `undefined` when there is no usable
79
46
  * start - the turn is skipped, never guessed at.
@@ -83,14 +50,10 @@ export function turnSpan(
83
50
  completed: unknown,
84
51
  streamed: unknown,
85
52
  nowMs: unknown,
86
- preference: SpanEndPreference,
87
53
  ): { readonly start: number; readonly end: number } | undefined {
88
54
  const start = asCount(created);
89
55
  if (start === undefined) return undefined;
90
- const ended =
91
- preference === "streamed"
92
- ? asCount(streamed) ?? asCount(completed) ?? asCount(nowMs)
93
- : asCount(completed) ?? asCount(streamed) ?? asCount(nowMs);
56
+ const ended = asCount(streamed) ?? asCount(completed) ?? asCount(nowMs);
94
57
  if (ended === undefined) return undefined;
95
58
  return { start, end: Math.max(start, ended) };
96
59
  }
@@ -228,23 +191,6 @@ export function unionSpanMs(spans: readonly ThroughputSpan[]): number {
228
191
  return mergedSpanMs(accepted);
229
192
  }
230
193
 
231
- /**
232
- * Active-work throughput: output and reasoning tokens of the scope divided by
233
- * the union of its streaming turn spans. Idle time between turns and the
234
- * settlement after a turn are not in the denominator, so the figure stops moving
235
- * once everything settles instead of decaying or hiding. A turn still in flight
236
- * ends at the caller's `now`, so the value keeps climbing while work happens.
237
- *
238
- * Floored at one second, the same floor the lifetime average uses, so a sliver
239
- * of time cannot flash an absurd rate. Returns `undefined` when there is
240
- * nothing to divide — no positive tokens, or no span with positive length.
241
- */
242
- export function unionSpanThroughput(spans: readonly ThroughputSpan[]): number | undefined {
243
- const { tokens, unionMs } = unionSpanTotals(spans);
244
- if (tokens <= 0 || unionMs <= 0) return undefined;
245
- return tokens / (Math.max(unionMs, 1_000) / 1_000);
246
- }
247
-
248
194
  /**
249
195
  * Smoothing weight for the instantaneous TPS rate: each new per-poll sample
250
196
  * moves the displayed figure 30% of the way toward it. Heavy enough to stop
@@ -253,14 +199,6 @@ export function unionSpanThroughput(spans: readonly ThroughputSpan[]): number |
253
199
  */
254
200
  export const TPS_EWMA_ALPHA = 0.3;
255
201
 
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
202
  /**
265
203
  * Hysteresis for the TPS repaint: the held figure moves only when the new
266
204
  * smoothed rate differs by at least one whole token/second or by at least
@@ -314,9 +252,7 @@ export function tpsNeedsRepaint(displayed: number | undefined, smoothed: number)
314
252
  * reasoning, the same pair the official TUI divides.
315
253
  *
316
254
  * 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.
255
+ * Only the live TPS path uses this.
320
256
  */
321
257
  export function unionGenerationTotals(spans: readonly ThroughputSpan[]): SpanTotals {
322
258
  const seen = new Set<string>();
@@ -341,50 +277,24 @@ export function unionGenerationTotals(spans: readonly ThroughputSpan[]): SpanTot
341
277
  return { tokens, unionMs: mergedSpanMs(accepted) };
342
278
  }
343
279
 
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
280
  /**
377
281
  * Near-instantaneous generation rate for one displayed session scope.
378
282
  *
379
283
  * 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.
284
+ * generating milliseconds (the streaming-span union, which excludes idle by
285
+ * construction) and gets back the figure to draw. The rule is per-session and
286
+ * honest about idle: the first sample only sets the baselines and reads as
287
+ * zero — no rate is known yet, and a session deep into its life must not flash
288
+ * its lifetime average as if it were live. A poll whose generating time did
289
+ * not advance means the session is not generating right now: it reads as zero
290
+ * with the smoother untouched, so the next poll that does add generating time
291
+ * resumes from the held smoothed figure rather than from zero. A backwards
292
+ * counter rebaselines (baselines and smoother alike, since the pre-reset
293
+ * average belongs to another era) and reads as zero. Otherwise the
294
+ * instantaneous rate is the delta of generation tokens over the delta of
295
+ * generating milliseconds, smoothed by the EWMA and held through the
296
+ * hysteresis. Deltas between successive polls are the rate, so a pause can
297
+ * never sag the figure — it reads as zero while it lasts.
388
298
  */
389
299
  export function createInstantTps(alpha: number = TPS_EWMA_ALPHA) {
390
300
  let prevTokens: number | undefined;
@@ -392,29 +302,19 @@ export function createInstantTps(alpha: number = TPS_EWMA_ALPHA) {
392
302
  let smoothed: number | undefined;
393
303
  let displayed: number | undefined;
394
304
 
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
-
305
+ return function sample(totalTokens: unknown, totalGenMs: unknown): number | undefined {
404
306
  const tokens = asCount(totalTokens);
405
307
  const genMs = asCount(totalGenMs);
406
308
  if (tokens === undefined || genMs === undefined) return displayed;
407
309
 
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.
310
+ // First sight sets the baselines. No rate is known yet — not even the
311
+ // cumulative lifetime average, which would flash a whole session's history
312
+ // as if it were live — so the row reads as zero until the next poll
313
+ // brings a delta to divide.
411
314
  if (prevTokens === undefined || prevGenMs === undefined) {
412
315
  prevTokens = tokens;
413
316
  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;
317
+ return 0;
418
318
  }
419
319
 
420
320
  const deltaTokens = tokens - prevTokens;
@@ -426,15 +326,16 @@ export function createInstantTps(alpha: number = TPS_EWMA_ALPHA) {
426
326
  prevTokens = tokens;
427
327
  prevGenMs = genMs;
428
328
  smoothed = undefined;
429
- return displayed;
329
+ return 0;
430
330
  }
431
331
  prevTokens = tokens;
432
332
  prevGenMs = genMs;
433
333
 
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;
334
+ // No new generating time: the session is not generating right now, so the
335
+ // rate is zero — and the smoother is left untouched, so the next poll that
336
+ // does add generating time resumes from the held smoothed figure rather
337
+ // than from zero.
338
+ if (deltaMs <= 0) return 0;
438
339
  const instant = deltaTokens / (deltaMs / 1_000);
439
340
  smoothed = smoothTpsRate(smoothed, instant, alpha);
440
341
  if (tpsNeedsRepaint(displayed, smoothed)) displayed = smoothed;
@@ -1,141 +0,0 @@
1
- // Accumulated active time for one session, measured rather than assumed.
2
- //
3
- // Wall-clock since `time.created` reports a session left open overnight as a
4
- // night's work. This clock only advances while the session — or something in
5
- // its family, or one of its shells — is actually running, and it freezes the
6
- // instant everything settles. `busy()` decides that, so the `elapsed` and
7
- // `status` rows can never disagree about whether work is happening.
8
- //
9
- // One session is watched at a time. Reading a different session means the gap
10
- // on the previous one happened off-watch, so its next read rebaselines and
11
- // banks nothing. A window is billed only when the session was busy at both
12
- // ends and the window was observed within the bound — so no single unobserved
13
- // gap is ever billed beyond the optional `maxBankedMs`, and a longer gap banks
14
- // nothing at all.
15
- //
16
- // State is a per-session accumulator held in this process and keyed by the
17
- // displayed session, so an unrelated project's session can never contribute.
18
- // The figure starts from a seed the caller may supply: the merged spans of the
19
- // assistant turns the host already recorded for that session's scope. That is
20
- // read once, from the host's own timestamps, so a restart comes back with the
21
- // work already on record instead of zero. Work observed live after that first
22
- // read keeps accumulating on top in memory, and a host that offers no seed
23
- // (or no timestamps) starts at zero and behaves exactly as it did before. The
24
- // seed is asked for once per session, when that session is first seen; an
25
- // unknown busy state (`undefined`) freezes rather than inventing motion.
26
-
27
- /** How the caller answers "is this session working right now?". */
28
- export type BusyRead = (sessionID: string) => boolean | undefined;
29
-
30
- /** How the caller answers "how much work is already on record for this session?". */
31
- export type SeedRead = (sessionID: string) => number | undefined;
32
-
33
- export interface ActiveElapsedOptions {
34
- /**
35
- * Longest window that may be banked as work. A longer one was not observed
36
- * — a suspended process, sparse host events — so it banks nothing.
37
- *
38
- * Defaults to 60_000 so the module's own contract holds even when the
39
- * caller supplies no bound. A production caller still passes its own
40
- * derived bound.
41
- */
42
- readonly maxBankedMs?: number;
43
-
44
- /**
45
- * Starting tally for a session, read once — on the first observation of that
46
- * session — so restart-stable work already on record is not lost. Floored at
47
- * zero; a non-finite or throwing read is treated as zero, never propagated.
48
- */
49
- readonly seedOf?: SeedRead;
50
- }
51
-
52
- /** One session's running tally and the last instant it was observed. */
53
- interface ActiveState {
54
- accumulated: number;
55
- lastAt: number;
56
- running: boolean;
57
- }
58
-
59
- /**
60
- * Build the active clock. One session is watched at a time. A read banks the
61
- * time since the previous read only when the session was running at BOTH ends
62
- * of that window — so overlapping activities record one wall-clock window, not
63
- * one per activity, and a window in which the session settled is treated as
64
- * idle rather than billed. Reads while the tally is zero return `undefined`,
65
- * matching the row's own "nothing to show yet" behaviour.
66
- *
67
- * The observation boundary is unconditional: a read of a different session than
68
- * the one before it rebaselines and banks nothing, because the gap happened
69
- * off-watch. The optional `maxBankedMs` is an independent cap on top of that —
70
- * any window longer than it was unobserved and banks nothing — not a switch for
71
- * the boundary. Undercount is acceptable, over-count is not.
72
- */
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;
80
- const states = new Map<string, ActiveState>();
81
- // The module's own contract must hold without the caller opting in; the
82
- // production caller still passes its own derived bound.
83
- const maxBankedMs = options.maxBankedMs ?? 60_000;
84
- let lastRead: string | undefined;
85
-
86
- return function activeElapsedMs(sessionID: string, now: number): number | undefined {
87
- if (!Number.isFinite(now)) return undefined;
88
-
89
- // A throwing or unknown read means "not known to be busy", which freezes.
90
- let busy = false;
91
- try {
92
- busy = isBusy(sessionID) === true;
93
- } catch {
94
- busy = false;
95
- }
96
-
97
- // Observation boundary: a different session on screen means this one's
98
- // gap since the last read happened off-watch, so take a fresh baseline.
99
- const boundary = lastRead !== undefined && lastRead !== sessionID;
100
- lastRead = sessionID;
101
-
102
- let state = states.get(sessionID);
103
- if (state === undefined) {
104
- // First sight of this session: take the seed once, here, so the record
105
- // covers everything up to the moment observation begins and the
106
- // accumulator below covers everything after - no overlap, no double
107
- // count. Floored at zero; a non-finite or throwing read is zero.
108
- let seed = 0;
109
- if (options.seedOf !== undefined) {
110
- try {
111
- const value = options.seedOf(sessionID);
112
- if (typeof value === "number" && Number.isFinite(value) && value > 0) seed = value;
113
- } catch {
114
- seed = 0;
115
- }
116
- }
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
- }
124
- states.set(sessionID, state);
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
- }
135
- }
136
-
137
- state.running = busy;
138
- state.lastAt = now;
139
- return state.accumulated <= 0 ? undefined : state.accumulated;
140
- };
141
- }