oc-flight-deck 0.5.0 → 0.6.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.
package/README.md CHANGED
@@ -22,7 +22,7 @@ tokens 533k in · 91k out
22
22
  cache 98% hit · 32M read
23
23
  context ██░░░░░░░░ 18%
24
24
  elapsed 2h 14m
25
- tps 106 tok/s
25
+ tps 18 tok/s
26
26
  spark ▁▃▂▅█▄▃▂
27
27
  ```
28
28
 
@@ -54,7 +54,7 @@ learn. The panel appears beside an open session and starts reading.
54
54
  | `context` | A gauge of how full the window is. |
55
55
  | `perms` | What is waiting for approval, not just how many. |
56
56
  | `elapsed` | How long you've been at it. |
57
- | `tps` | Output tokens per second, measured from the last completed turn. |
57
+ | `tps` | Current speed: output tokens in the last 60 seconds, divided by that window, subagents included. Idle longer than the window and it hides — the `status` row already says `idle`. On a host that exposes no per-message timestamps it falls back to the lifetime average, which reads lower than a peak per-turn rate. Fixed at 60 s, not configurable. |
58
58
  | `spark` | Recent turn sizes as a shape. Available, off by default. |
59
59
  | `reasoning` | Reasoning tokens, when the model emits them. Available, off by default. |
60
60
  | `turns` | How many prompts you have sent this session. Available, off by default. |
@@ -183,7 +183,9 @@ all you get exactly the defaults written out below.
183
183
  ```jsonc
184
184
  {
185
185
  // Tick rate in ms. The spinner has ten frames, so 100 turns it once a
186
- // second. 0 turns the timer off entirely.
186
+ // second. 0 turns the timer off entirely. While nothing is running the
187
+ // tick backs off to about once a second — the spinner is hidden then, and
188
+ // the clock only reads in whole seconds.
187
189
  "refresh": 100,
188
190
 
189
191
  "sidebar": {
@@ -282,7 +284,7 @@ Built on the official
282
284
 
283
285
  ## Compatibility
284
286
 
285
- Built against `@opencode/plugin` `2.0.2`; pin a host version you've tested.
287
+ Built against `@opencode/plugin` `2.0.10`; pin a host version you've tested.
286
288
 
287
289
  Requires OpenCode V2 (`opencode2`). Building from source needs Bun 1.4+ or
288
290
  Node 22+.
@@ -39,6 +39,10 @@
39
39
  // `elapsed` plus the spinner are the reason this exists. Without a tick they
40
40
  // would sit frozen between turns.
41
41
  //
42
+ // While nothing is running the tick backs off to about once a second: the
43
+ // spinner is hidden then, and `elapsed` only reads in whole seconds, so the
44
+ // host's renderer is woken a tenth as often for the same picture.
45
+ //
42
46
  // 100 default — the spinner turns once a second, the clock stays live
43
47
  // 50 twice as lively, still negligible work per tick
44
48
  // 1000 a calm wall-clock tick, but the spinner visibly stutters
@@ -78,7 +82,10 @@
78
82
  // context a gauge of how full the context window is
79
83
  // perms what is waiting for approval, not just how many
80
84
  // elapsed wall-clock time since the session started
81
- // tps output tokens per second on the last completed turn
85
+ // tps current speed: output tokens in the last 60 seconds,
86
+ // subagents included. Hides while idle longer than the
87
+ // window; falls back to the session's lifetime average on
88
+ // hosts with no per-message timestamps
82
89
  // spark recent turn sizes as a sparkline
83
90
  // reasoning reasoning tokens, when the model emits them
84
91
  // turns how many prompts you have sent this session
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oc-flight-deck",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
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",
@@ -53,7 +53,7 @@
53
53
  "access": "public"
54
54
  },
55
55
  "dependencies": {
56
- "@opencode/plugin": "2.0.2"
56
+ "@opencode/plugin": "2.0.10"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@opentui/core": "0.5.10",
package/src/tui/index.tsx CHANGED
@@ -4,7 +4,7 @@ import { cautionDetail, cautionText, detectCautions, worstCaution, type Caution
4
4
  import { cautionThresholds, mergeOptions, resolveConfig } from "./config.js";
5
5
  import { loadConfigFile } from "./file-config.js";
6
6
  import { footerLine, liveRowOffset, sidebarLines } from "./presentation.js";
7
- import { ANIMATED_FIELDS, type StatSource } from "./stats.js";
7
+ import { ANIMATED_FIELDS, sessionThroughput, TPS_WINDOW_MS, windowedThroughput, type StatSource, type ThroughputSample } from "./stats.js";
8
8
  import { startGuardBridge } from "./guard.js";
9
9
  import { startTicker } from "./ticker.js";
10
10
 
@@ -29,7 +29,17 @@ import { startTicker } from "./ticker.js";
29
29
  /** How many trailing messages are inspected for tool parts. */
30
30
  const RECENT_MESSAGES = 4;
31
31
 
32
- type SessionLike = { cost?: unknown; model?: unknown; time?: unknown };
32
+ type SessionLike = { cost?: unknown; model?: unknown; time?: unknown; tokens?: unknown };
33
+
34
+ /** What one session's message list contributes to a throughput window. */
35
+ interface TpsScan {
36
+ /** False only when the host refused to list the session's messages. */
37
+ readonly ok: boolean;
38
+ /** Assistant messages seen, whether or not they carried a timestamp. */
39
+ readonly assistant: number;
40
+ /** Samples that carried a usable timestamp. */
41
+ readonly samples: readonly ThroughputSample[];
42
+ }
33
43
 
34
44
  function asCount(value: unknown): number | undefined {
35
45
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
@@ -53,6 +63,12 @@ export default Plugin.define({
53
63
  const file = loadConfigFile();
54
64
  const { config, issues } = resolveConfig(mergeOptions(file.options, context.options));
55
65
 
66
+ // Only the rows actually on the rail are worth deriving: the rail re-runs on
67
+ // every tick, and a figure nobody asked to see should not cost a walk of the
68
+ // session database or the model catalog.
69
+ const rows = config.sidebar.enabled ? new Set(config.sidebar.rows) : new Set<string>();
70
+ const wants = (name: string): boolean => rows.has(name);
71
+
56
72
  if (file.issue !== undefined && file.source !== undefined) {
57
73
  console.warn(`[flight-deck] ${file.issue}`);
58
74
  }
@@ -177,10 +193,23 @@ export default Plugin.define({
177
193
  //
178
194
  // If the host does not report a project id, the unfiltered list is used, so
179
195
  // this degrades to the old behaviour instead of showing nothing.
196
+ // `project` walks every session the host knows about, and that collection grows
197
+ // with your history rather than staying a handful. It moves slowly, so the walk
198
+ // is held briefly instead of repeated on every tick.
199
+ const PROJECT_CACHE_MS = 5_000;
200
+ let projectCache:
201
+ | { readonly projectID: string | undefined; readonly at: number; readonly value: { cost: number; count: number } }
202
+ | undefined;
203
+
180
204
  const projectTotals = (sessionID: string) => {
181
205
  try {
182
- const sessions = context.data.session.list() ?? [];
183
206
  const projectID = asText(asRecord(context.data.session.get(sessionID))?.["projectID"]);
207
+ const cached = projectCache;
208
+ if (cached !== undefined && cached.projectID === projectID && Date.now() - cached.at < PROJECT_CACHE_MS) {
209
+ return cached.value;
210
+ }
211
+
212
+ const sessions = context.data.session.list() ?? [];
184
213
  const scoped =
185
214
  projectID === undefined
186
215
  ? sessions
@@ -188,7 +217,9 @@ export default Plugin.define({
188
217
 
189
218
  let cost = 0;
190
219
  for (const entry of scoped) cost += asCount(asRecord(entry)?.["cost"]) ?? 0;
191
- return { cost, count: scoped.length };
220
+ const value = { cost, count: scoped.length };
221
+ projectCache = { projectID, at: Date.now(), value };
222
+ return value;
192
223
  } catch {
193
224
  return undefined;
194
225
  }
@@ -216,12 +247,16 @@ export default Plugin.define({
216
247
  // The host's own shell records, which outlive the tool call: a backgrounded
217
248
  // command returns its result immediately, so its part settles while the
218
249
  // process keeps running. This is the only signal that survives that.
250
+ //
251
+ // Shells are listed per LOCATION, not per session, so the session is matched
252
+ // on the record's own `metadata.sessionID` — the documented shape, rather
253
+ // than a session-scoped accessor the published API does not carry.
219
254
  const shellsOf = (sessionID: string): readonly unknown[] => {
220
255
  try {
221
- const shellApi = context.data.shell as unknown as
222
- | { listBySession?: (id: string) => readonly unknown[] }
223
- | undefined;
224
- return shellApi?.listBySession?.(sessionID) ?? [];
256
+ const shells = context.data.shell.list(locationOf()) ?? [];
257
+ return shells.filter(
258
+ (entry) => asText(asRecord(asRecord(entry)?.["metadata"])?.["sessionID"]) === sessionID,
259
+ );
225
260
  } catch {
226
261
  return [];
227
262
  }
@@ -292,38 +327,159 @@ export default Plugin.define({
292
327
  }
293
328
 
294
329
  try {
295
- // `listBySession` is on the reactive client the host hands the plugin,
296
- // but not on every published type surface, so it is reached defensively:
297
- // a host without it still falls back to the session's own status.
298
- const shellApi = context.data.shell as unknown as
299
- | { listBySession?: (id: string) => readonly unknown[] }
300
- | undefined;
301
- const shells = shellApi?.listBySession?.(sessionID);
302
- if (shells !== undefined && shells.some((entry) => asRecord(entry)?.status === "running")) return true;
330
+ if (shellsOf(sessionID).some((entry) => asRecord(entry)?.["status"] === "running")) return true;
303
331
  } catch {
304
- // Same again: unreadable shells just mean no shell signal.
332
+ // Unreadable shells just mean no shell signal.
305
333
  }
306
334
 
307
335
  return status === undefined ? undefined : false;
308
336
  };
309
337
 
310
- // Throughput of the last completed turn. The host records when streaming
311
- // finished, so this is measured rather than estimated from wall-clock.
312
- const lastTps = (sessionID: string): number | undefined => {
313
- const messages = messagesOf(sessionID);
314
- for (let index = messages.length - 1; index >= 0; index -= 1) {
315
- const message = asRecord(messages[index]);
316
- const tokens = asRecord(message?.tokens);
317
- const output = asCount(tokens?.output);
318
- const time = asRecord(message?.time);
319
- const created = asCount(time?.created);
320
- const streamed = asCount(time?.streamed);
321
- if (output === undefined || created === undefined || streamed === undefined) continue;
322
- const duration = streamed - created;
323
- if (duration <= 0) continue;
324
- return output / (duration / 1_000);
338
+ // Overall session throughput, from two sources chosen by host capability and
339
+ // never by the moment. A host that stamps its messages gets a trailing-window
340
+ // rate — output tokens over the last minute, subagents summed in — so the
341
+ // figure reflects current speed rather than a whole-conversation average. A
342
+ // host proven to expose no message timestamps uses the lifetime average.
343
+ //
344
+ // The capability is learned once and remembered for the process. `undefined`
345
+ // means "not yet known": a read that failed, or carried no assistant turns,
346
+ // tells us nothing and must not choose a metric. Once known it is sticky in
347
+ // BOTH directions, so a transient `message.list` failure can never flip a
348
+ // stamped host back to the lifetime average (nor an unstamped host off it) —
349
+ // a failure just hides the row. One value for the whole host, deliberately
350
+ // not keyed by session.
351
+ //
352
+ // The rail re-runs on the fast tick, and walking every family message for
353
+ // every session would repeat the same work fifty times a second, so the
354
+ // result is held briefly. `undefined` is cached too: an idle window must not
355
+ // be re-derived on each tick either.
356
+ const TPS_CACHE_MS = 1_000;
357
+ let hostStamps: boolean | undefined;
358
+ let tpsCache:
359
+ | { readonly sessionID: string; readonly at: number; readonly value: number | undefined }
360
+ | undefined;
361
+
362
+ const scanMessages = (id: string): TpsScan => {
363
+ let messages: readonly unknown[];
364
+ try {
365
+ messages = context.data.session.message.list(id) ?? [];
366
+ } catch {
367
+ // A refused read is not "this host has no messages".
368
+ return { ok: false, assistant: 0, samples: [] };
325
369
  }
326
- return undefined;
370
+ const samples: ThroughputSample[] = [];
371
+ let assistant = 0;
372
+ for (const entry of messages) {
373
+ const message = asRecord(entry);
374
+ if (message?.["type"] !== "assistant") continue;
375
+ assistant += 1;
376
+ const stamp = asRecord(message["time"]);
377
+ const at =
378
+ asCount(stamp?.["completed"]) ?? asCount(stamp?.["streamed"]) ?? asCount(stamp?.["created"]);
379
+ // "Stamped" depends only on the timestamp, never on the output count: a
380
+ // batch of zero-output assistant turns still proves the host stamps.
381
+ if (at === undefined) continue;
382
+ samples.push({ tokens: asRecord(message["tokens"])?.["output"], at });
383
+ }
384
+ return { ok: true, assistant, samples };
385
+ };
386
+
387
+ // The lifetime average, the metric of last resort for a host that exposes no
388
+ // per-message timestamps. Measured from the session's own clock
389
+ // (`time.updated`, falling back to now) so a finished session settles on a
390
+ // stable figure instead of decaying as it sits on screen.
391
+ const lifetimeTps = (
392
+ sessionID: string,
393
+ session: SessionLike | undefined,
394
+ created: number,
395
+ time: Record<string, unknown> | undefined,
396
+ ): number | undefined => {
397
+ const updated = asCount(time?.["updated"]);
398
+ const end = updated === undefined ? Date.now() : Math.min(Date.now(), updated);
399
+ const elapsed = end - created;
400
+ if (elapsed <= 0) return undefined;
401
+
402
+ const own = asCount(asRecord(session?.tokens)?.["output"]);
403
+ let output = own;
404
+ // Only a family root owns the tree beneath it; a child asking `family()`
405
+ // gets its ancestors and siblings too, so it keeps its own figure.
406
+ if (isFamilyRoot(sessionID)) {
407
+ try {
408
+ const ids = context.data.session.family(sessionID) ?? [];
409
+ if (ids.length > 1) {
410
+ let total = 0;
411
+ let sawOne = false;
412
+ for (const id of ids) {
413
+ const member = context.data.session.get(id) as SessionLike | undefined;
414
+ const out = asCount(asRecord(member?.tokens)?.["output"]);
415
+ if (out === undefined) continue;
416
+ total += out;
417
+ sawOne = true;
418
+ }
419
+ if (sawOne) output = total;
420
+ }
421
+ } catch {
422
+ // No family on this host: the session's own tokens still stand.
423
+ }
424
+ }
425
+ return sessionThroughput(output, elapsed);
426
+ };
427
+
428
+ const computeTps = (sessionID: string, session: SessionLike | undefined): number | undefined => {
429
+ const time = asRecord(session?.time);
430
+ const created = asCount(time?.["created"]);
431
+ if (created === undefined) return undefined;
432
+
433
+ // A host proven unstamped needs no message read at all: its metric is the
434
+ // lifetime average whether or not the read would have succeeded.
435
+ if (hostStamps === false) return lifetimeTps(sessionID, session, created, time);
436
+
437
+ // Timestamped assistant output this session has produced, plus — only from
438
+ // a family root — every subagent session's. A child asking `family()` gets
439
+ // its ancestors and siblings back, so it keeps its own samples.
440
+ const scans: TpsScan[] = [scanMessages(sessionID)];
441
+ if (isFamilyRoot(sessionID)) {
442
+ try {
443
+ for (const id of context.data.session.family(sessionID) ?? []) {
444
+ if (id !== sessionID) scans.push(scanMessages(id));
445
+ }
446
+ } catch {
447
+ // No family on this host: the session's own samples still stand.
448
+ }
449
+ }
450
+
451
+ const samples: ThroughputSample[] = [];
452
+ let assistant = 0;
453
+ let readOk = false;
454
+ for (const scan of scans) {
455
+ samples.push(...scan.samples);
456
+ assistant += scan.assistant;
457
+ readOk = readOk || scan.ok;
458
+ }
459
+
460
+ if (hostStamps === undefined) {
461
+ // A stamped assistant turn proves the host stamps. Assistant turns with
462
+ // no timestamp prove it does not. Neither, and the capability stays
463
+ // unknown so the row hides rather than guessing a metric.
464
+ if (samples.length > 0) hostStamps = true;
465
+ else if (readOk && assistant > 0) hostStamps = false;
466
+ else return undefined;
467
+ }
468
+
469
+ if (hostStamps === true) {
470
+ return windowedThroughput(samples, Date.now(), TPS_WINDOW_MS, created);
471
+ }
472
+ return lifetimeTps(sessionID, session, created, time);
473
+ };
474
+
475
+ const sessionTps = (sessionID: string, session: SessionLike | undefined): number | undefined => {
476
+ const cached = tpsCache;
477
+ if (cached !== undefined && cached.sessionID === sessionID && Date.now() - cached.at < TPS_CACHE_MS) {
478
+ return cached.value;
479
+ }
480
+ const value = computeTps(sessionID, session);
481
+ tpsCache = { sessionID, at: Date.now(), value };
482
+ return value;
327
483
  };
328
484
 
329
485
  // Recent turn sizes, oldest first. Drawn from messages the host already
@@ -349,7 +505,8 @@ export default Plugin.define({
349
505
  const animated =
350
506
  config.sidebar.enabled &&
351
507
  config.sidebar.rows.some((name) => (ANIMATED_FIELDS as readonly string[]).includes(name));
352
- const ticker = startTicker(context, animated ? config.refresh : 0);
508
+ let spinnerNeeded = false;
509
+ const ticker = startTicker(context, animated ? config.refresh : 0, () => spinnerNeeded);
353
510
 
354
511
  // The guard row is opt-in and polls its own RPC: starting the bridge only
355
512
  // when the row is on the rail means no timer and no request for a row
@@ -397,24 +554,31 @@ export default Plugin.define({
397
554
  const snapshot = (sessionID: string): StatSource => {
398
555
  const location = locationOf();
399
556
  const session = context.data.session.get(sessionID) as SessionLike | undefined;
557
+ const isBusy = busy(sessionID);
558
+ // The fast tick exists for the spinner, and the spinner is only drawn while
559
+ // something is moving. Everything else on the rail reads in seconds.
560
+ spinnerNeeded = wants("status") && isBusy === true;
561
+
400
562
  // A "turn" is one prompt and the work it caused. The host's message list
401
563
  // also carries system, shell and switch records, so counting records
402
564
  // reports several times the turns actually taken.
403
- const turns = messagesOf(sessionID).filter((entry) => asRecord(entry)?.["type"] === "user").length;
565
+ const turns = wants("turns")
566
+ ? messagesOf(sessionID).filter((entry) => asRecord(entry)?.["type"] === "user").length
567
+ : undefined;
404
568
 
405
569
  return {
406
570
  ...session,
407
- caution: announce(sessionID),
408
- branch: branchOf(location),
409
- tree: treeTotals(sessionID, session?.cost),
410
- context: contextUsage(sessionID, session?.model),
411
- project: projectTotals(sessionID),
412
- status: statusOf(sessionID),
413
- busy: busy(sessionID),
414
- perms: permsOf(sessionID),
415
- tps: lastTps(sessionID),
416
- spark: sparkValues(sessionID),
417
- elapsedMs: sessionElapsed(session),
571
+ caution: wants("caution") ? announce(sessionID) : undefined,
572
+ branch: wants("branch") ? branchOf(location) : undefined,
573
+ tree: wants("cost") || wants("total") ? treeTotals(sessionID, session?.cost) : undefined,
574
+ context: wants("context") ? contextUsage(sessionID, session?.model) : undefined,
575
+ project: wants("project") ? projectTotals(sessionID) : undefined,
576
+ status: wants("status") ? statusOf(sessionID) : undefined,
577
+ busy: isBusy,
578
+ perms: wants("perms") ? permsOf(sessionID) : undefined,
579
+ tps: wants("tps") ? sessionTps(sessionID, session) : undefined,
580
+ spark: wants("spark") ? sparkValues(sessionID) : undefined,
581
+ elapsedMs: wants("elapsed") ? sessionElapsed(session) : undefined,
418
582
  turns,
419
583
  guard: bridge?.status,
420
584
  // Read the tick inside the render so the host registers a dependency on
package/src/tui/stats.ts CHANGED
@@ -53,6 +53,12 @@ export interface StatSource {
53
53
  /** True when anything is working: this session, a subagent, or a shell. */
54
54
  readonly busy?: unknown;
55
55
  readonly perms?: unknown;
56
+ /**
57
+ * Current session throughput. On a host that stamps its messages this is a
58
+ * trailing-window rate over the last minute, subagents summed in; on a host
59
+ * without message timestamps it falls back to the lifetime average. Either
60
+ * way it is derived from state the host already holds.
61
+ */
56
62
  readonly tps?: unknown;
57
63
  readonly elapsedMs?: unknown;
58
64
  readonly turns?: unknown;
@@ -238,6 +244,84 @@ export function formatCost(value: number): string {
238
244
  return `$${value.toFixed(value < 1 ? 3 : 2)}`;
239
245
  }
240
246
 
247
+ /**
248
+ * Overall session throughput: output tokens over the session's lifetime.
249
+ *
250
+ * Unlike a per-turn rate, this is the whole conversation's average, so it
251
+ * includes every subagent and every pause. A just-started session is floored
252
+ * at one second so it cannot divide by a sliver of time and flash an absurd
253
+ * rate. Returns `undefined` when there is nothing to divide.
254
+ */
255
+ export function sessionThroughput(outputTokens: unknown, elapsedMs: unknown): number | undefined {
256
+ const output = asCount(outputTokens);
257
+ const elapsed = asCount(elapsedMs);
258
+ if (output === undefined || output <= 0) return undefined;
259
+ if (elapsed === undefined || elapsed <= 0) return undefined;
260
+ return output / (Math.max(elapsed, 1_000) / 1_000);
261
+ }
262
+
263
+ /** Length of the trailing window, in milliseconds, that `windowedThroughput` measures. */
264
+ export const TPS_WINDOW_MS = 60_000;
265
+
266
+ /**
267
+ * One assistant turn's contribution to a throughput window.
268
+ *
269
+ * Both fields are untrusted: `tokens` is the turn's output count and `at` is the
270
+ * timestamp it finished at. Anything unusable is skipped rather than guessed at.
271
+ */
272
+ export interface ThroughputSample {
273
+ readonly tokens?: unknown;
274
+ readonly at?: unknown;
275
+ }
276
+
277
+ /**
278
+ * A trailing-window throughput rate: output tokens per second over the last
279
+ * `windowMs`, measured from `nowMs`.
280
+ *
281
+ * The denominator is how much of the window the session has actually lived, so
282
+ * a just-started session ramps up against its real age instead of being divided
283
+ * by a full minute it has not run — floored at one second, the same floor the
284
+ * lifetime average uses, so a sliver of time cannot flash an absurd rate. Once
285
+ * the session is older than the window, it settles into a clean rolling minute.
286
+ *
287
+ * Returns `undefined` — the caller hides the row — unless at least one sample
288
+ * carries a usable timestamp inside the window and a positive output count. An
289
+ * idle session therefore reports no rate rather than a decaying one. The window
290
+ * is inclusive at both ends (`start <= at <= now`) so a boundary sample counts.
291
+ *
292
+ * Pure and dependency-free: no clock, no I/O, no rendering.
293
+ */
294
+ export function windowedThroughput(
295
+ samples: readonly ThroughputSample[],
296
+ nowMs: number,
297
+ windowMs: number,
298
+ sessionCreatedMs: number,
299
+ ): number | undefined {
300
+ if (!Number.isFinite(nowMs)) return undefined;
301
+ if (!Number.isFinite(windowMs) || windowMs <= 0) return undefined;
302
+
303
+ // An unusable creation time cannot tell us how long the session has lived, so
304
+ // the whole window is assumed available rather than dropping the rate.
305
+ const created = Number.isFinite(sessionCreatedMs) ? sessionCreatedMs : undefined;
306
+ const alive = created === undefined ? windowMs : nowMs - created;
307
+ const denominatorMs = Math.max(1_000, Math.min(windowMs, alive));
308
+
309
+ const start = nowMs - windowMs;
310
+ let output = 0;
311
+ let sawOne = false;
312
+ for (const sample of samples) {
313
+ const at = asCount(sample.at);
314
+ if (at === undefined || at < start || at > nowMs) continue;
315
+ const tokens = asCount(sample.tokens);
316
+ if (tokens === undefined || tokens <= 0) continue;
317
+ output += tokens;
318
+ sawOne = true;
319
+ }
320
+
321
+ if (!sawOne) return undefined;
322
+ return output / (denominatorMs / 1_000);
323
+ }
324
+
241
325
  /** `45s`, `14m`, `2h 14m`. */
242
326
  export function formatDuration(ms: number): string {
243
327
  const seconds = Math.floor(ms / 1_000);
package/src/tui/ticker.ts CHANGED
@@ -20,6 +20,11 @@
20
20
  // this plugin, gone when the TUI exits. Not the durable store, not a session,
21
21
  // not a file, not the network.
22
22
  //
23
+ // The tick serves the spinner first, but the spinner is only drawn while work
24
+ // is happening. When nothing is moving the store is written about once a second
25
+ // instead of on every interval — see `IDLE_REFRESH_MS` — so the host's reactive
26
+ // graph is woken a tenth as often for a picture that has not changed.
27
+ //
23
28
  // The host is a beta and its store is reached across a version boundary, so
24
29
  // everything about it is validated at runtime and every failure path degrades to
25
30
  // "no ticker" rather than raising into the TUI.
@@ -64,6 +69,17 @@ export interface Ticker {
64
69
  /** Namespaced so it cannot collide with another plugin's memory keys. */
65
70
  export const TICKER_KEY = "flight-deck.frame";
66
71
 
72
+ /**
73
+ * How often the frame still advances while nothing is moving.
74
+ *
75
+ * The spinner needs ~10 frames a second, but it is only drawn while work is
76
+ * happening. When idle, only `elapsed` and the annunciator still need a tick,
77
+ * and both read in whole seconds — so the host renderer is woken once a second
78
+ * instead of ten times. The timer itself keeps firing (cheap); it is the store
79
+ * write, which wakes the host's reactive graph, that is skipped.
80
+ */
81
+ export const IDLE_REFRESH_MS = 1_000;
82
+
67
83
  // Untrusted store values are normalised here rather than at the render, so a
68
84
  // corrupt frame can never reach the spinner's array index.
69
85
  function readFrame(store: FrameStore | undefined): number {
@@ -96,7 +112,11 @@ function openStore(storage: NonNullable<TickerHost["storage"]>): { store: FrameS
96
112
  * on host events, which is exactly how it behaved before the ticker was fixed.
97
113
  * Degrading quietly keeps a cosmetic panel from ever breaking the TUI.
98
114
  */
99
- export function startTicker(host: TickerHost | undefined, intervalMs: number): Ticker | undefined {
115
+ export function startTicker(
116
+ host: TickerHost | undefined,
117
+ intervalMs: number,
118
+ isBusy: () => boolean = () => true,
119
+ ): Ticker | undefined {
100
120
  if (!Number.isFinite(intervalMs) || intervalMs <= 0) return undefined;
101
121
 
102
122
  const storage = host?.storage;
@@ -105,7 +125,23 @@ export function startTicker(host: TickerHost | undefined, intervalMs: number): T
105
125
  const opened = openStore(storage);
106
126
  if (opened === undefined) return undefined;
107
127
 
128
+ const idleEvery = Math.max(1, Math.round(IDLE_REFRESH_MS / intervalMs));
129
+ let ticks = 0;
130
+
108
131
  let timer: ReturnType<typeof setInterval> | undefined = setInterval(() => {
132
+ ticks += 1;
133
+
134
+ // A broken busy predicate must never freeze the spinner, so it degrades to
135
+ // "busy" rather than propagating.
136
+ let busy = true;
137
+ try {
138
+ busy = isBusy();
139
+ } catch {
140
+ busy = true;
141
+ }
142
+ // While idle, skip the store write on all but every `idleEvery`th tick.
143
+ if (!busy && ticks % idleEvery !== 0) return;
144
+
109
145
  try {
110
146
  opened.update((draft) => {
111
147
  draft.frame = readFrame(draft) + 1;