oc-flight-deck 0.12.0 → 0.19.2

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/guard.ts CHANGED
@@ -262,13 +262,14 @@ function resolveStatusFn(host: GuardHost, deps: GuardDeps | undefined): GuardDep
262
262
  // The payload is normalized defensively after the call, so drift degrades
263
263
  // to the placeholder instead of throwing.
264
264
  //
265
- // NEVER use `.call`/`.apply` on the rpc factory itself: the real client
266
- // attaches its raw API onto the callable (`Object.assign(makeRpc(...),
267
- // raw.rpc)`), so the factory's `.call` is the raw `rpc.call` endpoint —
268
- // not `Function.prototype.call`. Using it would POST
269
- // `/api/rpc/undefined/undefined` and silently yield `undefined`. Invoke
270
- // the factory directly; the resulting `status` is a plain function, so a
271
- // direct call is safe there too.
265
+ // The factory is public API: the installed types declare
266
+ // `rpc: RpcApi<...> & { call }` (`client.d.ts`) with
267
+ // `interface RpcApi<...> { <D extends Rpc.PortableDefinition>(definition: D):
268
+ // RpcClient<D, ...> }` (`rpc.d.ts`); the rpc doc's cross-plugin example
269
+ // is `context.client.rpc(<contract>)`. The sibling `.call` is the raw
270
+ // `rpc.call` endpoint, not `Function.prototype.call`, so the factory is
271
+ // invoked directly and `.call` is never used on it. The resulting
272
+ // `status` is a plain function, so a direct call is safe there too.
272
273
  const factory = rpc as (definition: typeof GUARD_CONTRACT) => { readonly status?: unknown };
273
274
  const remote = factory(GUARD_CONTRACT) as { readonly status?: unknown };
274
275
  const status = (remote as Record<string, unknown>).status;
@@ -374,6 +375,13 @@ export function startGuardBridge(
374
375
  if (!writeValue(opened, normalized)) stopTimer();
375
376
  };
376
377
 
378
+ // No host subscription: `context.data.on` / `data.listen` carry server
379
+ // events (`permission.asked`, `session.execution.succeeded`); a cross-plugin
380
+ // event exists only when the other plugin declares and emits it. This
381
+ // bridge's mirrored contract declares `events: {}`, and the live config
382
+ // installs no guard plugin, so there is nothing to subscribe to. The
383
+ // ten-second poll is the read itself, not a fallback: each tick re-resolves
384
+ // `status`, so a later guard install appears within one interval.
377
385
  timer = setInterval(() => {
378
386
  const sessionID = currentSessionID;
379
387
  if (sessionID === undefined) return;
@@ -1,9 +1,26 @@
1
1
  // The host-clipboard seam, split from `./clipboard.ts` for one reason: the
2
2
  // render tests mount the real JSX in a real headless renderer, where mocking
3
- // all of `@opentui/core` would break the renderer itself. This module is the
3
+ // the whole UI toolkit would break the renderer itself. This module is the
4
4
  // only thing those tests replace, so they can stand in a fake host write while
5
- // the renderer and the OSC52 adapter stay real.
5
+ // the renderer stays real.
6
6
  //
7
- // Production always resolves to the real process host clipboard.
7
+ // Production resolves to NO host backend: the plugin contract sanctions no
8
+ // host clipboard surface, so this factory returns `undefined` and the copy
9
+ // path degrades cleanly to the OSC52/no-backend outcomes (which are never
10
+ // reported as a verified copy). The `HostClipboardLike` shape is structural so
11
+ // a future sanctioned backend can plug in without touching the call site.
8
12
 
9
- export { createHostClipboard } from "@opentui/core";
13
+ /** The subset of a host clipboard service the copy path uses. */
14
+ interface HostClipboardLike {
15
+ writeText(text: string): Promise<{ readonly status: string }>;
16
+ }
17
+
18
+ /**
19
+ * The default host clipboard factory: explicitly absent. Returning
20
+ * `undefined` (rather than throwing) marks "no host service at all", so the
21
+ * copy path reports `no-backend` when no renderer can take the OSC52 fallback
22
+ * either.
23
+ */
24
+ export function createHostClipboard(): HostClipboardLike | undefined {
25
+ return undefined;
26
+ }
package/src/tui/index.tsx CHANGED
@@ -11,7 +11,9 @@ import {
11
11
  import { copyFeedback, copyToClipboard } from "./clipboard.js";
12
12
  import { cautionThresholds, mergeOptions, resolveConfig } from "./config.js";
13
13
  import { loadConfigFile } from "./file-config.js";
14
+ import { createGoLookReader } from "./go-look.js";
14
15
  import { footerLine, railLineSpans, railLines, railLineStyle, type RailLine } from "./presentation.js";
16
+ import { goPanelLines } from "./go-panel.js";
15
17
  import { ANIMATED_FIELDS, type StatSource } from "./stats.js";
16
18
  import { attributeMask, themeColor } from "./style.js";
17
19
  import { startGuardBridge } from "./guard.js";
@@ -144,13 +146,9 @@ export default Plugin.define({
144
146
  );
145
147
  };
146
148
 
147
- // Bound a bankable window to a few ticks: `min(60s, max(5s, 4 * refreshMs))`,
148
- // so a suspended process or a sparse-event gap cannot be billed as work.
149
- const maxBankedMs = Math.min(60_000, Math.max(5_000, 4 * config.refresh));
150
- const reads = createSessionReads(context, maxBankedMs);
149
+ const reads = createSessionReads(context);
151
150
  const {
152
151
  messagesOf,
153
- isFamilyRoot,
154
152
  treeTotals,
155
153
  contextUsage,
156
154
  sessionElapsed,
@@ -176,10 +174,13 @@ export default Plugin.define({
176
174
  thresholds: cautionThreshold,
177
175
  });
178
176
 
179
- const { sessionTps } = createTpsReader(context, isFamilyRoot, {
180
- busyOf: busy,
181
- elapsedMsOf: (id, now) => sessionElapsed(id, now),
182
- });
177
+ const { sessionTps } = createTpsReader(
178
+ context,
179
+ {
180
+ elapsedMsOf: (id, now) => sessionElapsed(id, now),
181
+ },
182
+ config.sidebar.tps.scope,
183
+ );
183
184
 
184
185
  // Recent turn sizes, oldest first. Drawn from messages the host already
185
186
  // holds, so the sparkline needs no history of our own to accumulate.
@@ -201,9 +202,15 @@ export default Plugin.define({
201
202
  // the host's own events. It is skipped entirely when nothing on the rail
202
203
  // animates, and `refresh: 0` opts out regardless. The tick has to live in the
203
204
  // host's reactive graph rather than ours, or it re-renders nothing at all.
205
+ // The footer's Go panel draws a clock-derived countdown, so its being
206
+ // enabled is reason enough for a ticker on its own (its sweep rides this
207
+ // frame only when the look opts in; by default the bar is static).
208
+ const goOption = config.sidebar.footer.go;
209
+ const goPanelEnabled = goOption === true || (typeof goOption === "object" && goOption !== null);
204
210
  const animated =
205
211
  config.sidebar.enabled &&
206
- config.sidebar.rows.some((name) => ANIMATED_FIELDS.some((field) => field === name));
212
+ (goPanelEnabled ||
213
+ config.sidebar.rows.some((name) => ANIMATED_FIELDS.some((field) => field === name)));
207
214
  let spinnerNeeded = false;
208
215
  const ticker = startTicker(context, animated ? config.refresh : 0, () => spinnerNeeded);
209
216
 
@@ -217,9 +224,26 @@ export default Plugin.define({
217
224
  // The go row is opt-in the same way: a row nobody drew should cost no timer
218
225
  // and no request. The bridge is account-wide (one key, one quota), so it
219
226
  // starts here and has no session to follow — unlike guard.
220
- const wantGo = config.sidebar.enabled && config.sidebar.rows.includes("go");
227
+ // The footer's Go panel (0.13.0) draws the same account-wide usage as three
228
+ // wider lines, so it wants the same bridge: either surface is reason enough
229
+ // to start the one poll, and neither starts it alone.
230
+ const wantGo =
231
+ config.sidebar.enabled && (config.sidebar.rows.includes("go") || goPanelEnabled);
221
232
  const goBridge = wantGo ? startGoBridge(context) : undefined;
222
233
 
234
+ // The footer panel's look, re-resolved live from the config file: the
235
+ // reader cheap-stats the file each render (mtime + size) and re-reads +
236
+ // re-parses only when it moved, so `sidebar.footer.go` edits take effect
237
+ // on the next tick with no restart. `true` passes nothing (the panel's own
238
+ // defaults); an object passes its look straight through for the panel to
239
+ // re-read defensively. Host options keep setup precedence on every
240
+ // re-read; a missing, unreadable, or malformed file keeps the last good
241
+ // look and never throws out of the render below.
242
+ // `true` passes nothing (the panel's own defaults); an object passes its
243
+ // look straight through for the panel to re-read defensively.
244
+ const goPanelLayout = goOption === true ? undefined : (typeof goOption === "object" && goOption !== null ? goOption : undefined);
245
+ const goLook = createGoLookReader({ hostOptions: context.options, initial: goPanelLayout });
246
+
223
247
  // Read session state inside the render so the rail stays live: cost and
224
248
  // tokens climb as the session runs, and the branch appears once VCS
225
249
  // resolves. Nothing here writes, requests, or leaves the process.
@@ -262,11 +286,21 @@ export default Plugin.define({
262
286
  ? messagesOf(sessionID).filter((entry) => asRecord(entry)?.["type"] === "user").length
263
287
  : undefined;
264
288
 
289
+ // The money row already shows the family, so the token rows beside it
290
+ // share its scope: when the tree is on record its rolled-up tokens
291
+ // replace the session's own, and the cost/total rows read `tree` itself.
292
+ // The tree is derived only when a row that needs it is on the rail.
293
+ const tree =
294
+ wants("cost") || wants("total") || wants("tokens") || wants("cache") || wants("reasoning")
295
+ ? treeTotals(sessionID, session?.cost)
296
+ : undefined;
297
+
265
298
  return {
266
299
  ...session,
300
+ tokens: tree?.tokens ?? session?.tokens,
267
301
  caution: wants("caution") ? announce(sessionID) : undefined,
268
302
  branch: wants("branch") ? branchOf(location) : undefined,
269
- tree: wants("cost") || wants("total") ? treeTotals(sessionID, session?.cost) : undefined,
303
+ tree,
270
304
  context: wants("context") ? contextUsage(sessionID, session?.model) : undefined,
271
305
  project: wants("project") ? projectTotals(sessionID) : undefined,
272
306
  status: wants("status") ? statusOf(sessionID) : undefined,
@@ -299,7 +333,16 @@ export default Plugin.define({
299
333
  let toastedKey: string | undefined;
300
334
  let watchTimer: ReturnType<typeof setInterval> | undefined;
301
335
 
302
- if (config.caution.enabled && config.caution.toast) {
336
+ // Floored at one second: cautions display whole seconds, so polling faster
337
+ // than that only multiplies host reads (message lists, shells, statuses)
338
+ // for a display that cannot change any faster. `refresh` still drives the
339
+ // rail's own ticker; the toast keeps its own slower cadence.
340
+ //
341
+ // Gated on the sidebar too: `watchedSession` is assigned only inside the
342
+ // `sidebar.content` render, which exists only when the sidebar is enabled,
343
+ // so without it this timer could never fire and would leak a live interval.
344
+ const toastMs = Math.max(1_000, config.refresh > 0 ? config.refresh : 1_000);
345
+ if (config.sidebar.enabled && config.caution.enabled && config.caution.toast) {
303
346
  watchTimer = setInterval(() => {
304
347
  const sessionID = watchedSession;
305
348
  if (sessionID === undefined) return;
@@ -319,7 +362,7 @@ export default Plugin.define({
319
362
  } catch {
320
363
  // A warning must never be able to break the panel it warns about.
321
364
  }
322
- }, config.refresh > 0 ? config.refresh : 1_000);
365
+ }, toastMs);
323
366
  }
324
367
 
325
368
  if (config.sidebar.enabled) {
@@ -357,22 +400,51 @@ export default Plugin.define({
357
400
  );
358
401
  }
359
402
 
360
- if (config.sidebar.enabled && config.sidebar.footer.lines.length > 0) {
403
+ if (config.sidebar.enabled && (config.sidebar.footer.lines.length > 0 || goPanelEnabled)) {
361
404
  releases.push(
362
405
  context.ui.slot({
363
406
  // The sidebar footer: a separate host slot below the rows. The
364
407
  // lines are empty by default since 0.8.1, so this registration is
365
- // purely opt-in — set `sidebar.footer.lines` (the documented
408
+ // purely opt-in - set `sidebar.footer.lines` (the documented
366
409
  // `▸ FLIGHT DECK` pair, or your own) to claim the slot. It draws
367
410
  // outside the `maxLines` budget and stays when `sidebar.lines` is
368
- // customized. The lines are fixed, so nothing here subscribes to
369
- // the ticker or the session.
370
- append: "sidebar.footer",
371
- render: () => (
372
- <box flexDirection="column">
373
- {config.sidebar.footer.lines.map((text) => themedLine({ text }))}
374
- </box>
375
- ),
411
+ // customized. The fixed lines are static; the Go panel below is live,
412
+ // so this render subscribes to the tick and to the go store.
413
+ //
414
+ // `prepend` puts our claim FIRST inside the footer's boundary, so
415
+ // the panel sits directly ABOVE the host's own location row (the
416
+ // `~` path line): the host's row stays the absolute last line.
417
+ // Per the slot docs, `prepend`/`append` are first/last inside the
418
+ // target's boundary, and several claims at one anchor coexist in
419
+ // plugin enable order.
420
+ prepend: "sidebar.footer",
421
+ render: () => {
422
+ // Read the tick and the go store INSIDE the render, the same way
423
+ // the rail subscribes to the session snapshot: the countdown is
424
+ // clock-derived, and the read is what registers the dependency so
425
+ // a poll re-runs this slot. `goBridge` is absent when neither
426
+ // surface asked for it, so both reads are safe to skip.
427
+ void ticker?.frame;
428
+ const goUsage = goBridge?.usage;
429
+ // A blank panel must name its cause. `goBridge` absent means
430
+ // `startGoBridge` found no usable host store - distinct from a
431
+ // bridge that ran but had nothing to report, which carries its own
432
+ // reason. A bridge with neither a value nor a reason yet (its first
433
+ // poll still in flight) is `"pending"`, so the panel is never silent.
434
+ const goReason =
435
+ goBridge === undefined
436
+ ? "no-bridge"
437
+ : (goBridge.reason ?? (goUsage === undefined ? "pending" : undefined));
438
+ const panel = goPanelEnabled
439
+ ? goPanelLines(goUsage, Date.now(), goLook.current(), ticker?.frame ?? 0, goReason)
440
+ : [];
441
+ return (
442
+ <box flexDirection="column">
443
+ {config.sidebar.footer.lines.map((text) => themedLine({ text }))}
444
+ {panel.map((line) => themedLine(line))}
445
+ </box>
446
+ );
447
+ },
376
448
  }),
377
449
  );
378
450
  }
package/src/tui/rows.ts CHANGED
@@ -15,7 +15,10 @@ import {
15
15
  DEFAULT_LABEL_WIDTH,
16
16
  DEFAULT_PLACEHOLDER,
17
17
  DEFAULT_SPARK_WIDTH,
18
+ canonicalField,
19
+ fieldLabel,
18
20
  isStatField,
21
+ skeletonValue,
19
22
  type LayoutHint,
20
23
  type StatSource,
21
24
  } from "./stat-fields.js";
@@ -24,13 +27,15 @@ import {
24
27
  const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
25
28
 
26
29
  /**
27
- * Value-column budget for the `ses` row's preview, in cells.
30
+ * Value-column design budget for the `ses` row's preview, in cells.
28
31
  *
29
32
  * Same width the `perms` row clips its resource to, because that is the column
30
33
  * this roughly thirty-odd-column rail was designed to fit: the label column
31
34
  * plus a value of this length stays inside the panel. A full 30-character
32
35
  * session id is always shortened at this budget and gets the ellipsis appended
33
- * - the row reads as a preview of a longer value, never as the value.
36
+ * - the row reads as a preview of a longer value, never as the value. The
37
+ * `ses` case adapts this budget down by the label's column overflow, so the
38
+ * effective budget at a narrow `labelWidth` is smaller than this number.
34
39
  */
35
40
  const SES_PREVIEW_WIDTH = 18;
36
41
 
@@ -245,7 +250,12 @@ function cautionValueSegments(source: StatSource): StatSegment[] | undefined {
245
250
  *
246
251
  * Returning `undefined` rather than a placeholder is deliberate: a rail that
247
252
  * shows `branch unknown` before the repo loads looks broken, while a rail
248
- * that simply grows a row when the data arrives looks alive.
253
+ * that simply grows a row when the data arrives looks alive. Persistence lives
254
+ * in `statRows`, which draws `skeletonValue` for a data-less known field.
255
+ *
256
+ * The field is canonicalized at entry (`session` renders as `ses`), and the
257
+ * label is resolved through `fieldLabel` — which draws `layout.labels`' override
258
+ * for the row when one is set, else the built-in name.
249
259
  */
250
260
  export function statLine(
251
261
  field: string,
@@ -263,9 +273,13 @@ export function statLine(
263
273
  // column, so a label longer than `labelWidth` was glued straight onto its
264
274
  // value: at labelWidth 8 the `reasoning` row rendered as "reasoning153k".
265
275
  // The label is nine characters, which made this reachable from a config file.
266
- const row = (label: string, value: string): string => formatRow(label, value, labelWidth);
276
+ //
277
+ // The label is resolved here rather than at each call site, so the `ses`
278
+ // case keeps saying `row("ses", …)` while drawing `session`.
279
+ const row = (label: string, value: string): string =>
280
+ formatRow(fieldLabel(label, layout.labels), value, labelWidth);
267
281
 
268
- switch (field) {
282
+ switch (canonicalField(field)) {
269
283
  case "caution": {
270
284
  // Rendered only when the caller found something to say, which is what
271
285
  // keeps a healthy session visually identical to one without the
@@ -339,12 +353,17 @@ export function statLine(
339
353
  return row("cost", `${formatCost(treeCost as number)} · ${family} ${plural}`);
340
354
  }
341
355
  case "total": {
342
- // Only worth a row once a subagent has actually run: subagent sessions are
343
- // separate, so the parent's `cost` alone understates what was spent.
356
+ // The family figure: this session plus its subagent sessions. Since 0.20.0
357
+ // it is drawn even when no subagent has run — the true family total is then
358
+ // the session's own cost, and the row reads `$0.000 · 0 subagents` rather
359
+ // than blanking, because the row the owner renames to `lifetime` must never
360
+ // have a hole in it. Still `undefined` when there is no family data at all,
361
+ // so the persist layer keeps its zero skeleton for a session with no record.
344
362
  const tree = asRecord(source.tree);
345
- const count = asCount(tree?.count);
346
- const cost = asCount(tree?.cost);
347
- if (cost === undefined || count === undefined || count === 0) return undefined;
363
+ if (tree === undefined) return undefined;
364
+ const cost = asCount(tree.cost);
365
+ if (cost === undefined) return undefined;
366
+ const count = asCount(tree.count) ?? 0;
348
367
  const plural = count === 1 ? "subagent" : "subagents";
349
368
  return row("total", `${formatCost(cost)} · ${count} ${plural}`);
350
369
  }
@@ -470,10 +489,25 @@ export function statLine(
470
489
  // full id still lives on `source.sessionId`, which is what the row's click
471
490
  // gesture copies - the display and the copy are separate values.
472
491
  //
473
- // Budget `SES_PREVIEW_WIDTH` (18), matching the `perms` row's clip width:
474
- // that is the column this rail was designed to fit, so a preview of that
475
- // length sits inside it beside the label.
476
- return id === undefined ? undefined : row("ses", clip(id, SES_PREVIEW_WIDTH));
492
+ // The label grew from `ses` to `session`, overflowing narrow columns, so
493
+ // the preview budget shrinks by exactly that overflow measured through
494
+ // `labelPrefix` itself: at labelWidth 6 the prefix grows 6 -> 8 so the
495
+ // budget is 16, at 7 it grows 7 -> 8 so the budget is 17, at 8+ there is
496
+ // no overflow and the row keeps the full `SES_PREVIEW_WIDTH` (18). The
497
+ // renamed row's total cell width then equals the pre-rename row's at
498
+ // every label width (24 at 6, 25 at 7, 26 at 8, 28 at 10). Floored at 8
499
+ // so the preview cannot collapse to nothing; `clip` still marks it as
500
+ // a preview with the ellipsis.
501
+ const budget = Math.max(
502
+ 8,
503
+ SES_PREVIEW_WIDTH -
504
+ Math.max(
505
+ 0,
506
+ labelPrefix(fieldLabel("ses", layout.labels), labelWidth).length -
507
+ labelPrefix("ses", labelWidth).length,
508
+ ),
509
+ );
510
+ return id === undefined ? undefined : row("ses", clip(id, budget));
477
511
  }
478
512
  case "go": {
479
513
  // The plain string is the exact join of the coloured segments, so the
@@ -501,23 +535,31 @@ export function statSegments(
501
535
  source: StatSource,
502
536
  layout: LayoutHint = {},
503
537
  ): readonly StatSegment[] | undefined {
504
- if (field === "caution") {
538
+ // Canonicalized like `statLine`, and the label resolved the same way, so the
539
+ // two views of one row agree character-for-character.
540
+ const name = canonicalField(field);
541
+ if (name === "caution") {
505
542
  const value = cautionValueSegments(source);
506
543
  if (value === undefined) return undefined;
507
- return [{ text: labelPrefix("caution", layout.labelWidth ?? DEFAULT_LABEL_WIDTH) }, ...value];
544
+ return [
545
+ { text: labelPrefix(fieldLabel("caution", layout.labels), layout.labelWidth ?? DEFAULT_LABEL_WIDTH) },
546
+ ...value,
547
+ ];
508
548
  }
509
- if (field !== "go") return undefined;
549
+ if (name !== "go") return undefined;
510
550
  const value = goValueSegments(source, layout);
511
551
  if (value === undefined) return undefined;
512
- return [{ text: labelPrefix("go", layout.labelWidth ?? DEFAULT_LABEL_WIDTH) }, ...value];
552
+ return [{ text: labelPrefix(fieldLabel("go", layout.labels), layout.labelWidth ?? DEFAULT_LABEL_WIDTH) }, ...value];
513
553
  }
514
554
 
515
555
  /** Render every named field, in the given order.
516
556
  *
517
557
  * By default only fields with data render; with `layout.persist` every known
518
- * field renders exactly one row, using `layout.placeholder` (default `"—"`)
519
- * for the value when the host has nothing to show yet. `statLine` keeps
520
- * returning `string | undefined` — persistence lives here, not there.
558
+ * field renders exactly one row, using `skeletonValue` (a live-shaped zero)
559
+ * for the value when the host has nothing to show yet and falling back to
560
+ * `layout.placeholder` (default `"—"`) for the fields with no skeleton.
561
+ * `statLine` keeps returning `string | undefined` — persistence lives here,
562
+ * not there.
521
563
  */
522
564
  export function statRows(
523
565
  fields: readonly string[],
@@ -533,15 +575,20 @@ export function statRows(
533
575
  const labelWidth = hint.labelWidth ?? DEFAULT_LABEL_WIDTH;
534
576
  const rows: string[] = [];
535
577
  for (const field of fields) {
536
- const line = statLine(field, source, hint);
578
+ // Canonicalized once, so the alias and the key take the same path below.
579
+ const name = canonicalField(field);
580
+ const line = statLine(name, source, hint);
537
581
  if (line !== undefined) {
538
582
  rows.push(line);
539
583
  continue;
540
584
  }
541
585
  // Unknown names stay skipped even when persistent: a typo must stay a
542
586
  // reported-and-skipped row, not a placeholder that looks intentional.
543
- if (!persist || !isStatField(field)) continue;
544
- rows.push(formatRow(field, placeholder, labelWidth));
587
+ // `caution` stays skipped too: the annunciator has no skeleton and takes
588
+ // no placeholder — with nothing to say there is no row, and its silence
589
+ // is the design.
590
+ if (!persist || !isStatField(name) || name === "caution") continue;
591
+ rows.push(formatRow(fieldLabel(name, hint.labels), skeletonValue(name, hint) ?? placeholder, labelWidth));
545
592
  }
546
593
  return rows;
547
594
  }
@@ -0,0 +1,122 @@
1
+ // Active time over a session scope's whole lifetime, derived rather than
2
+ // accumulated.
3
+ //
4
+ // The figure is the merged union of the assistant-turn spans the host already
5
+ // recorded for the scope (see ./stats.js), with a still-in-flight turn ending
6
+ // at `now` — recomputed from the host's own records on every fresh read, never
7
+ // from wall-clock since `time.created` and never persisted to disk. So a
8
+ // restart comes back with the same value instead of resetting (the host
9
+ // retains message rows across compaction), while a turn that is in flight
10
+ // climbs as `now` advances; when everything settles the figure freezes.
11
+ //
12
+ // A per-session high-water mark held in this process guarantees the row can
13
+ // never visibly step backwards while the host still reports those turns: a
14
+ // compaction that drops old messages, or a transient read failure, must not
15
+ // shrink what is on screen. Every read is floored at zero, and reads while
16
+ // the high-water is still zero return `undefined`, matching the row's own
17
+ // "nothing to show yet" behaviour.
18
+ //
19
+ // The row reads in whole seconds, so the computed union is cached per session
20
+ // for `cacheMs` (default one second — the display resolution): the fast tick
21
+ // must not rescan every message of the scope twenty times a second. The
22
+ // high-water moves only on a fresh computation, never on a cached read. One
23
+ // entry per session carries BOTH the mark and the short-lived computed union,
24
+ // and the mark is not a cache entry: it must never share a cache's eviction.
25
+ // The map is pruned only by a sweep that runs when it grows past `maxSessions`
26
+ // (default 256): the sweep drops exactly the entries whose session the host
27
+ // no longer knows — asked through `reads.knows`, which defaults to "known"
28
+ // when absent — and never an arbitrary recency cut that could evict a live
29
+ // session's mark. A TUI lifetime of session-hopping therefore cannot grow the
30
+ // map forever, yet a live session's figure cannot step backwards no matter how
31
+ // many other sessions were viewed since.
32
+ //
33
+ // Pure except for its own memory: it takes no clock and no context, so it is
34
+ // trivially testable.
35
+
36
+ import { unionSpanMs, type ThroughputSpan } from "./stats.js";
37
+
38
+ /** The assistant-turn spans on record for the scope, in-flight turns ending at `now`. */
39
+ export interface ActiveSpanReads {
40
+ spansOf(sessionID: string, now: number): readonly ThroughputSpan[];
41
+ /**
42
+ * Whether the host still knows the session. The sweep consults this before
43
+ * dropping an entry; absent, every session counts as known and nothing is
44
+ * ever swept.
45
+ */
46
+ knows?(sessionID: string): boolean;
47
+ }
48
+
49
+ export interface ActiveTimeOptions {
50
+ readonly cacheMs?: number;
51
+ readonly maxSessions?: number;
52
+ }
53
+
54
+ /** One session's cached union and the most it has ever computed. */
55
+ interface ActiveEntry {
56
+ union: number;
57
+ at: number;
58
+ high: number;
59
+ }
60
+
61
+ /**
62
+ * Build the active clock. Each fresh computation re-derives the figure from
63
+ * the host's own spans, so the record covers the scope's whole lifetime with
64
+ * no overlap to double-count and nothing held over a restart to go stale —
65
+ * and the high-water keeps the row monotonic across compactions and failed
66
+ * reads alike. Reads while the high-water is zero return `undefined`,
67
+ * matching the row's own "nothing to show yet" behaviour.
68
+ */
69
+ export function createActiveTime(
70
+ reads: ActiveSpanReads,
71
+ options?: ActiveTimeOptions,
72
+ ): (sessionID: string, now: number) => number | undefined {
73
+ const cacheMs = options?.cacheMs ?? 1_000;
74
+ const maxSessions = options?.maxSessions ?? 256;
75
+ const entries = new Map<string, ActiveEntry>();
76
+
77
+ // Drop only what the host has forgotten. A generous bound keeps a TUI
78
+ // lifetime of session-hopping from growing the map forever, but the cut is
79
+ // never by recency: evicting a live session would throw away its
80
+ // high-water mark and let the row step backwards.
81
+ const sweepForgotten = (): void => {
82
+ for (const id of entries.keys()) {
83
+ let known = true;
84
+ try {
85
+ known = reads.knows?.(id) ?? true;
86
+ } catch {
87
+ known = true;
88
+ }
89
+ if (!known) entries.delete(id);
90
+ }
91
+ };
92
+
93
+ return function activeTimeMs(sessionID: string, now: number): number | undefined {
94
+ let entry = entries.get(sessionID);
95
+ // A stepped-back clock serves whatever is on record rather than rescanning
96
+ // against a `now` the spans never belonged to, and a non-finite `now`
97
+ // serves it too rather than inventing a figure.
98
+ const fresh =
99
+ entry === undefined || (Number.isFinite(now) && now - entry.at >= cacheMs);
100
+ if (fresh && Number.isFinite(now)) {
101
+ let union = 0;
102
+ try {
103
+ union = unionSpanMs(reads.spansOf(sessionID, now));
104
+ } catch {
105
+ union = 0;
106
+ }
107
+ if (!Number.isFinite(union) || union < 0) union = 0;
108
+ const high = Math.max(entry?.high ?? 0, union);
109
+ if (entry === undefined) {
110
+ if (entries.size >= maxSessions) sweepForgotten();
111
+ entry = { union, at: now, high };
112
+ entries.set(sessionID, entry);
113
+ } else {
114
+ entry.union = union;
115
+ entry.at = now;
116
+ entry.high = high;
117
+ }
118
+ }
119
+ const high = entry?.high ?? 0;
120
+ return high <= 0 ? undefined : high;
121
+ };
122
+ }