oc-flight-deck 0.6.3 → 0.6.7

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.
@@ -8,7 +8,9 @@
8
8
  // Coercion of untrusted values happens through ./coerce.js.
9
9
 
10
10
  import type { Plugin } from "@opencode/plugin/tui";
11
+ import { createActiveElapsed } from "./active-elapsed.js";
11
12
  import { asCount, asRecord, asText, type SessionLike } from "./coerce.js";
13
+ import { turnKey, turnSpan, unionSpanMs, type ThroughputSpan } from "./stats.js";
12
14
 
13
15
  /**
14
16
  * The location the rail reads shell records and VCS from: the host's current
@@ -23,7 +25,7 @@ export function locationOf(context: Plugin.Context) {
23
25
  }
24
26
  }
25
27
 
26
- export function createSessionReads(context: Plugin.Context) {
28
+ export function createSessionReads(context: Plugin.Context, maxBankedMs?: number) {
27
29
  /** How many trailing messages are inspected for tool parts. */
28
30
  const RECENT_MESSAGES = 4;
29
31
 
@@ -116,15 +118,6 @@ export function createSessionReads(context: Plugin.Context) {
116
118
  return undefined;
117
119
  };
118
120
 
119
- // Measured against the clock rather than the session's last update, so the
120
- // row keeps moving between events instead of freezing between turns.
121
- const sessionElapsed = (session: SessionLike | undefined): number | undefined => {
122
- const created = asCount(asRecord(session?.time)?.created);
123
- if (created === undefined) return undefined;
124
- const elapsed = Date.now() - created;
125
- return elapsed <= 0 ? undefined : elapsed;
126
- };
127
-
128
121
  const statusOf = (sessionID: string): string | undefined => {
129
122
  try {
130
123
  return context.data.session.status(sessionID);
@@ -223,6 +216,63 @@ export function createSessionReads(context: Plugin.Context) {
223
216
  return status === undefined ? undefined : false;
224
217
  };
225
218
 
219
+ // Accumulated active wall time: the clock runs only while `busy()` says the
220
+ // session, its family, or its shells is working, and freezes otherwise. The
221
+ // `now` parameter keeps the transition observation deterministic for tests.
222
+ //
223
+ // The seed gives that same clock the session's already-recorded work so a
224
+ // restart does not reset the row to `—`. It scans exactly the scope `busy()`
225
+ // consults — the displayed session plus every id `family()` returns — and
226
+ // takes the merged union of those assistant turns' spans, tokens ignored: a
227
+ // zero-output turn still took wall time. The scan is memoised one result per
228
+ // 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.
230
+ const seeds = new Map<string, number>();
231
+ const seedElapsed = (sessionID: string): number => {
232
+ const cached = seeds.get(sessionID);
233
+ if (cached !== undefined) return cached;
234
+
235
+ // One `now` for the whole scan, so every in-flight turn ends at the same
236
+ // instant and the union cannot be skewed by the reads drifting apart.
237
+ const now = Date.now();
238
+ const ids = new Set<string>([sessionID]);
239
+ try {
240
+ for (const id of context.data.session.family(sessionID) ?? []) ids.add(id);
241
+ } catch {
242
+ // No family on this host: the session's own turns still stand.
243
+ }
244
+
245
+ let seed = 0;
246
+ try {
247
+ const spans: ThroughputSpan[] = [];
248
+ for (const id of ids) {
249
+ for (const entry of messagesOf(id)) {
250
+ const message = asRecord(entry);
251
+ if (message?.["type"] !== "assistant") continue;
252
+ const stamp = asRecord(message["time"]);
253
+ const created = asCount(stamp?.["created"]);
254
+ const completed = asCount(stamp?.["completed"]);
255
+ const streamed = asCount(stamp?.["streamed"]);
256
+ const span = turnSpan(created, completed, streamed, now);
257
+ if (span === undefined) continue;
258
+ const output = asRecord(message["tokens"])?.["output"];
259
+ spans.push({ key: turnKey(message["id"], created, completed, output), ...span });
260
+ }
261
+ }
262
+ seed = unionSpanMs(spans);
263
+ } catch {
264
+ // A throwing read never reaches the rail: it degrades to today's zero.
265
+ seed = 0;
266
+ }
267
+
268
+ seeds.set(sessionID, seed);
269
+ return seed;
270
+ };
271
+
272
+ const activeElapsed = createActiveElapsed(busy, { maxBankedMs, seedOf: seedElapsed });
273
+ const sessionElapsed = (sessionID: string, now: number = Date.now()): number | undefined =>
274
+ activeElapsed(sessionID, now);
275
+
226
276
  return {
227
277
  messagesOf,
228
278
  isFamilyRoot,
@@ -1,8 +1,9 @@
1
- // Session throughput, measured from two sources chosen by host capability and
2
- // never by the moment. A host that stamps its messages gets a trailing-window
3
- // rate — output tokens over the last minute, subagents summed in — so the
4
- // figure reflects current speed rather than a whole-conversation average. A
5
- // host proven to expose no message timestamps uses the lifetime average.
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 tokens divided by the union of the turns' own
4
+ // spans, so idle between turns is not in the denominator and the figure freezes
5
+ // once everything settles. A host proven to expose no message timestamps uses
6
+ // the lifetime average instead.
6
7
  //
7
8
  // The capability is learned once and remembered for the process. `undefined`
8
9
  // means "not yet known": a read that failed, or carried no assistant turns,
@@ -14,26 +15,31 @@
14
15
  //
15
16
  // The rail re-runs on the fast tick, and walking every family message for
16
17
  // every session would repeat the same work fifty times a second, so the
17
- // result is held briefly. `undefined` is cached too: an idle window must not
18
+ // result is held briefly. `undefined` is cached too: an idle session must not
18
19
  // be re-derived on each tick either.
19
20
  //
20
21
  // One factory closes over the plugin `context`; `isFamilyRoot` comes from
21
22
  // ./session-reads.js so a child session keeps its own figure while a root
22
- // sums its tree. The math itself lives in ./throughput.js (pure) and
23
- // ./stats.js.
23
+ // sums its tree. The math itself lives in ./throughput.js (pure).
24
+ //
25
+ // RESIDUAL RISK, disclosed: the lifetime fallback for an unstamped host still
26
+ // includes idle time and can therefore sag below a peak per-turn rate. There is
27
+ // no timestamp on such a host with which to exclude it.
24
28
 
25
29
  import type { Plugin } from "@opencode/plugin/tui";
26
30
  import { asCount, asRecord, type SessionLike } from "./coerce.js";
27
- import { sessionThroughput, TPS_WINDOW_MS, windowedThroughput, type ThroughputSample } from "./stats.js";
31
+ import { sessionThroughput, turnKey, turnSpan, unionSpanThroughput, type ThroughputSpan } from "./stats.js";
28
32
 
29
- /** What one session's message list contributes to a throughput window. */
33
+ /** What one session's message list contributes to its active-work average. */
30
34
  interface TpsScan {
31
35
  /** False only when the host refused to list the session's messages. */
32
36
  readonly ok: boolean;
33
37
  /** Assistant messages seen, whether or not they carried a timestamp. */
34
38
  readonly assistant: number;
35
- /** Samples that carried a usable timestamp. */
36
- readonly samples: readonly ThroughputSample[];
39
+ /** Assistant turns that carried any usable timestamp, which proves the host stamps. */
40
+ readonly stamped: number;
41
+ /** Spans for turns that carried a usable `created` start. */
42
+ readonly spans: readonly ThroughputSpan[];
37
43
  }
38
44
 
39
45
  export function createTpsReader(
@@ -46,29 +52,36 @@ export function createTpsReader(
46
52
  | { readonly sessionID: string; readonly at: number; readonly value: number | undefined }
47
53
  | undefined;
48
54
 
49
- const scanMessages = (id: string): TpsScan => {
55
+ const scanMessages = (id: string, now: number): TpsScan => {
50
56
  let messages: readonly unknown[];
51
57
  try {
52
58
  messages = context.data.session.message.list(id) ?? [];
53
59
  } catch {
54
60
  // A refused read is not "this host has no messages".
55
- return { ok: false, assistant: 0, samples: [] };
61
+ return { ok: false, assistant: 0, stamped: 0, spans: [] };
56
62
  }
57
- const samples: ThroughputSample[] = [];
63
+ const spans: ThroughputSpan[] = [];
58
64
  let assistant = 0;
65
+ let stamped = 0;
59
66
  for (const entry of messages) {
60
67
  const message = asRecord(entry);
61
68
  if (message?.["type"] !== "assistant") continue;
62
69
  assistant += 1;
63
70
  const stamp = asRecord(message["time"]);
64
- const at =
65
- asCount(stamp?.["completed"]) ?? asCount(stamp?.["streamed"]) ?? asCount(stamp?.["created"]);
66
- // "Stamped" depends only on the timestamp, never on the output count: a
71
+ const created = asCount(stamp?.["created"]);
72
+ const completed = asCount(stamp?.["completed"]);
73
+ const streamed = asCount(stamp?.["streamed"]);
74
+ // "Stamped" depends only on the timestamps, never on the output count: a
67
75
  // batch of zero-output assistant turns still proves the host stamps.
68
- if (at === undefined) continue;
69
- samples.push({ tokens: asRecord(message["tokens"])?.["output"], at });
76
+ if (created === undefined && completed === undefined && streamed === undefined) continue;
77
+ stamped += 1;
78
+ // Without `created` there is no start; the turn is skipped, not guessed.
79
+ const span = turnSpan(created, completed, streamed, now);
80
+ if (span === undefined) continue;
81
+ const output = asRecord(message["tokens"])?.["output"];
82
+ spans.push({ key: turnKey(message["id"], created, completed, output), tokens: output, ...span });
70
83
  }
71
- return { ok: true, assistant, samples };
84
+ return { ok: true, assistant, stamped, spans };
72
85
  };
73
86
 
74
87
  // The lifetime average, the metric of last resort for a host that exposes no
@@ -121,26 +134,32 @@ export function createTpsReader(
121
134
  // lifetime average whether or not the read would have succeeded.
122
135
  if (hostStamps === false) return lifetimeTps(sessionID, session, created, time);
123
136
 
137
+ // One `now` for the whole scope, so every in-flight turn ends at the same
138
+ // instant and the union cannot be skewed by the scans drifting apart.
139
+ const now = Date.now();
140
+
124
141
  // Timestamped assistant output this session has produced, plus — only from
125
142
  // a family root — every subagent session's. A child asking `family()` gets
126
- // its ancestors and siblings back, so it keeps its own samples.
127
- const scans: TpsScan[] = [scanMessages(sessionID)];
143
+ // its ancestors and siblings back, so it keeps its own spans.
144
+ const scans: TpsScan[] = [scanMessages(sessionID, now)];
128
145
  if (isFamilyRoot(sessionID)) {
129
146
  try {
130
147
  for (const id of context.data.session.family(sessionID) ?? []) {
131
- if (id !== sessionID) scans.push(scanMessages(id));
148
+ if (id !== sessionID) scans.push(scanMessages(id, now));
132
149
  }
133
150
  } catch {
134
- // No family on this host: the session's own samples still stand.
151
+ // No family on this host: the session's own turns still stand.
135
152
  }
136
153
  }
137
154
 
138
- const samples: ThroughputSample[] = [];
155
+ const spans: ThroughputSpan[] = [];
139
156
  let assistant = 0;
157
+ let stamped = 0;
140
158
  let readOk = false;
141
159
  for (const scan of scans) {
142
- samples.push(...scan.samples);
160
+ spans.push(...scan.spans);
143
161
  assistant += scan.assistant;
162
+ stamped += scan.stamped;
144
163
  readOk = readOk || scan.ok;
145
164
  }
146
165
 
@@ -148,14 +167,12 @@ export function createTpsReader(
148
167
  // A stamped assistant turn proves the host stamps. Assistant turns with
149
168
  // no timestamp prove it does not. Neither, and the capability stays
150
169
  // unknown so the row hides rather than guessing a metric.
151
- if (samples.length > 0) hostStamps = true;
170
+ if (stamped > 0) hostStamps = true;
152
171
  else if (readOk && assistant > 0) hostStamps = false;
153
172
  else return undefined;
154
173
  }
155
174
 
156
- if (hostStamps === true) {
157
- return windowedThroughput(samples, Date.now(), TPS_WINDOW_MS, created);
158
- }
175
+ if (hostStamps === true) return unionSpanThroughput(spans);
159
176
  return lifetimeTps(sessionID, session, created, time);
160
177
  };
161
178
 
@@ -170,4 +187,4 @@ export function createTpsReader(
170
187
  };
171
188
 
172
189
  return { sessionTps };
173
- }
190
+ }
@@ -5,6 +5,8 @@
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 type { DurationStyle } from "./format.js";
9
+
8
10
  /** The subset of a session snapshot the rail reads. All fields are untrusted. */
9
11
  export interface StatSource {
10
12
  /**
@@ -28,10 +30,12 @@ export interface StatSource {
28
30
  readonly busy?: unknown;
29
31
  readonly perms?: unknown;
30
32
  /**
31
- * Current session throughput. On a host that stamps its messages this is a
32
- * trailing-window rate over the last minute, subagents summed in; on a host
33
- * without message timestamps it falls back to the lifetime average. Either
34
- * way it is derived from state the host already holds.
33
+ * Session throughput. On a host that stamps its messages this is an
34
+ * active-work average: output tokens divided by the union of the assistant
35
+ * turns' own spans, subagents summed in, so idle between turns is not
36
+ * counted and the figure freezes when work stops. On a host without message
37
+ * timestamps it falls back to the lifetime average, which can still sag.
38
+ * Either way it is derived from state the host already holds.
35
39
  */
36
40
  readonly tps?: unknown;
37
41
  readonly elapsedMs?: unknown;
@@ -95,6 +99,12 @@ export interface LayoutHint {
95
99
  readonly labelWidth?: number;
96
100
  readonly barWidth?: number;
97
101
  readonly sparkWidth?: number;
102
+ /**
103
+ * How the `elapsed` row joins its duration segments. The rail supplies this
104
+ * from `format.duration` (default `"spaced"`); when the hint is absent the
105
+ * formatter's own default, `"compact"`, applies.
106
+ */
107
+ readonly durationStyle?: DurationStyle;
98
108
  /**
99
109
  * True when the rail already draws a `total` row.
100
110
  *
package/src/tui/stats.ts CHANGED
@@ -14,5 +14,12 @@ export { clip, formatCost, formatCount, formatDuration, fuelBar, sparkline } fro
14
14
  export { statLine, statRows } from "./rows.js";
15
15
  export { ANIMATED_FIELDS, DEFAULT_PLACEHOLDER, STAT_FIELDS, isStatField } from "./stat-fields.js";
16
16
  export type { StatSource } from "./stat-fields.js";
17
- export { sessionThroughput, TPS_WINDOW_MS, windowedThroughput } from "./throughput.js";
18
- export type { ThroughputSample } from "./throughput.js";
17
+ export {
18
+ sessionThroughput,
19
+ turnKey,
20
+ turnSpan,
21
+ unionSpanMs,
22
+ unionSpanThroughput,
23
+ unionSpanTotals,
24
+ } from "./throughput.js";
25
+ export type { SpanTotals, ThroughputSpan } from "./throughput.js";
@@ -0,0 +1,130 @@
1
+ // Per-line appearance for the rail: colour roles and text attributes.
2
+ //
3
+ // A config file names a role, not a raw theme token: `default`, `subdued`,
4
+ // `warning`, `error`, `success`, `info`. This module maps a role onto the host
5
+ // theme at render time. The host renamed its text tokens in 2.0.16
6
+ // (`default` -> `base`, `subdued` -> `muted`, feedback `default` -> `base`), so
7
+ // each role prefers the name this plugin has always read and falls back to the
8
+ // renamed one. On a host that provides neither, the colour stays `undefined`
9
+ // and the renderer's own default stands — which is exactly what an absent
10
+ // token has always done.
11
+ //
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.
15
+
16
+ import { TextAttributes } from "@opentui/core";
17
+
18
+ /** Colours a config may name. Roles, not raw theme tokens. */
19
+ export const STYLE_COLORS = ["default", "subdued", "warning", "error", "success", "info"] as const;
20
+
21
+ export type StyleColor = (typeof STYLE_COLORS)[number];
22
+
23
+ /**
24
+ * Text attributes a config may name, exactly the vendored renderer's enum
25
+ * minus `NONE` (an empty list is how "no attributes" is written).
26
+ */
27
+ export const STYLE_ATTRIBUTES = [
28
+ "bold",
29
+ "dim",
30
+ "italic",
31
+ "underline",
32
+ "blink",
33
+ "inverse",
34
+ "hidden",
35
+ "strikethrough",
36
+ ] as const;
37
+
38
+ export type StyleAttribute = (typeof STYLE_ATTRIBUTES)[number];
39
+
40
+ /** One line's look: a named colour plus zero or more attributes. */
41
+ export interface LineStyle {
42
+ readonly color: StyleColor;
43
+ readonly attributes: readonly StyleAttribute[];
44
+ }
45
+
46
+ /** The `style` config section, resolved. */
47
+ export interface StyleConfig {
48
+ /** The fixed branding/separator lines above the live rows. */
49
+ readonly lines: LineStyle;
50
+ readonly rows: {
51
+ /** Every live row inherits this unless it has its own entry. */
52
+ readonly wildcard: LineStyle;
53
+ /** Per-row entries, only for known row names. */
54
+ readonly overrides: Readonly<Partial<Record<string, LineStyle>>>;
55
+ };
56
+ }
57
+
58
+ /**
59
+ * The shipped look: fixed lines in the theme's primary text colour, live rows
60
+ * subdued, no attributes. This is what an absent `style` section must keep.
61
+ */
62
+ export const DEFAULT_STYLE: StyleConfig = {
63
+ lines: { color: "default", attributes: [] },
64
+ rows: { wildcard: { color: "subdued", attributes: [] }, overrides: {} },
65
+ };
66
+
67
+ /** The style for one live row: its own entry when it has one, else the wildcard. */
68
+ export function rowStyle(style: StyleConfig, field: string): LineStyle {
69
+ return style.rows.overrides[field] ?? style.rows.wildcard;
70
+ }
71
+
72
+ /**
73
+ * The host theme surface the rail reads. Structural on purpose: ./config.ts
74
+ * must not import a renderer, and tests can pass plain values.
75
+ *
76
+ * Both naming generations are declared because the host renamed the text tokens
77
+ * in 2.0.16; a host provides one or the other.
78
+ */
79
+ export interface ThemeLike {
80
+ readonly text?: {
81
+ readonly default?: unknown;
82
+ readonly subdued?: unknown;
83
+ readonly base?: unknown;
84
+ readonly muted?: unknown;
85
+ readonly feedback?: Readonly<
86
+ Partial<Record<"error" | "warning" | "success" | "info", { readonly default?: unknown; readonly base?: unknown }>>
87
+ >;
88
+ };
89
+ }
90
+
91
+ /**
92
+ * The theme colour for a named role, or `undefined` when the host provides
93
+ * neither the current nor the renamed token.
94
+ */
95
+ export function themeColor(color: StyleColor, theme: ThemeLike): unknown {
96
+ const text = theme.text;
97
+ if (text === undefined) return undefined;
98
+ switch (color) {
99
+ case "default":
100
+ return text.default ?? text.base;
101
+ case "subdued":
102
+ return text.subdued ?? text.muted;
103
+ default: {
104
+ const feedback = text.feedback?.[color];
105
+ return feedback?.default ?? feedback?.base;
106
+ }
107
+ }
108
+ }
109
+
110
+ /**
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.
113
+ */
114
+ const ATTRIBUTE_BITS: Readonly<Record<StyleAttribute, number>> = {
115
+ bold: TextAttributes.BOLD,
116
+ dim: TextAttributes.DIM,
117
+ italic: TextAttributes.ITALIC,
118
+ underline: TextAttributes.UNDERLINE,
119
+ blink: TextAttributes.BLINK,
120
+ inverse: TextAttributes.INVERSE,
121
+ hidden: TextAttributes.HIDDEN,
122
+ strikethrough: TextAttributes.STRIKETHROUGH,
123
+ };
124
+
125
+ /** The renderer bitmask for a list of attributes, or `undefined` when there are none. */
126
+ export function attributeMask(attributes: readonly StyleAttribute[]): number | undefined {
127
+ let mask = 0;
128
+ for (const attribute of attributes) mask |= ATTRIBUTE_BITS[attribute];
129
+ return mask === 0 ? undefined : mask;
130
+ }