oc-flight-deck 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.10.0] - 2026-10-02
9
+
10
+ ### Added
11
+
12
+ - Opt-in `ses` sidebar row: shows the session id shortened to its first 8 characters, and a mouse click copies the full id via the renderer's OSC52 clipboard path. Off by default, and degrades gracefully when the terminal cannot copy.
13
+
14
+ [0.10.0]: https://github.com/nathwn12/oc-flight-deck/compare/v0.9.0...v0.10.0
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  **Live session telemetry for your OpenCode terminal.**
6
6
  *The numbers where you're already looking — because your agent is spending money right now.*
7
7
 
8
- ![npm](https://img.shields.io/npm/v/oc-flight-deck) ![license](https://img.shields.io/badge/license-MIT-blue) ![opencode](https://img.shields.io/badge/opencode-V2-compatible-8A2BE2) ![node](https://img.shields.io/badge/node-%E2%89%A522-green)
8
+ ![npm](https://img.shields.io/npm/v/oc-flight-deck) ![license](https://img.shields.io/badge/license-MIT-blue) ![node](https://img.shields.io/badge/node-%E2%89%A522-green) ![downloads](https://img.shields.io/npm/dm/oc-flight-deck) ![check](https://img.shields.io/github/actions/workflow/status/nathwn12/oc-flight-deck/check.yml)
9
9
 
10
10
  </div>
11
11
 
@@ -36,7 +36,7 @@ tokens 533k in · 91k out
36
36
  cache 98% hit · 32M read
37
37
  context ██░░░░░░░░ 18%
38
38
  elapsed 2h 14m 37s
39
- tps 18 tok/s
39
+ tps 18.0 tok/s
40
40
  ```
41
41
 
42
42
  Every row is read from the open session at render time — except `caution`, which watches a clock rather than events (a hang emits none); `elapsed`, which is seeded once from the session's own recorded assistant turn spans and then accumulates the busy windows this run observes, rather than a value the session reports; and the opt-in `guard` row, which is polled from the local guard RPC.
@@ -58,16 +58,17 @@ The panel's only fixed text — `▸ FLIGHT DECK` over a separator — is **opt-
58
58
  | `context` | A gauge of how full the window is |
59
59
  | `perms` | What is waiting for approval, not just how many |
60
60
  | `elapsed` | Active time — the clock runs only while this session, a subagent in its tree, or one of its shells is working, and freezes when everything settles. It is seeded once from the assistant turn spans the host already recorded for that session, so it survives a restart instead of resetting to `—`; work observed live after that keeps counting in memory. It measures active time, not wall-clock since the session began |
61
- | `tps` | Average speed **while working**: output tokens divided by the time the assistant's turns actually ran, subagents included. Idle time between turns is never counted, so the figure freezes when everything settles instead of decaying or hiding; a turn still in flight counts up to now. On a host that exposes no per-message timestamps it falls back to the lifetime average, which includes idle and can therefore sag. Not configurable |
61
+ | `tps` | Average speed **while streaming**: output **plus reasoning** tokens divided by the time the provider was actively streaming (`streamed - created`), subagents included. Idle time between turns and the tool settlement after a turn are never counted, so the figure freezes when everything settles instead of decaying or hiding; a turn still in flight counts up to now. On a host that exposes no per-message timestamps it falls back to the lifetime average, which includes idle and can therefore sag. Not configurable |
62
62
  | `spark` | Recent turn sizes as a shape · **off by default** |
63
63
  | `reasoning` | Reasoning tokens, when the model emits them · **off by default** |
64
64
  | `turns` | How many prompts you've sent this session · **off by default** |
65
65
  | `guard` | Harness status from oc-harness-guard · **off by default** |
66
66
  | `go` | Zen Go account usage — a dial and a whole-number percent for the **5h**, **1w**, and **1m** windows, in that fixed order; a window at 90% or more turns its dial and number red, and the reset hint appears only then · **off by default** |
67
+ | `ses` | The open session id, shortened to its first **8 characters**; **click the row** to copy the full id to the terminal clipboard · **off by default** (requires the host's mouse) |
67
68
 
68
69
  `project` matches on the host's **project id**, not on a directory, so a worktree counts as part of the same project. A host that reports no project id leaves nothing to match on, and the row then totals every session that host knows about.
69
70
 
70
- The rows marked **off by default** — `caution`, `branch`, `total`, `spark`, `reasoning`, `turns`, `guard`, and `go` — are available but not in the default rail: add any of them to `sidebar.rows`. `caution` also needs `caution.enabled: true`; `go` needs `OPENCODE_GO_API_KEY` in the environment.
71
+ The rows marked **off by default** — `caution`, `branch`, `total`, `spark`, `reasoning`, `turns`, `guard`, `go`, and `ses` — are available but not in the default rail: add any of them to `sidebar.rows`. `caution` also needs `caution.enabled: true`; `go` needs `OPENCODE_GO_API_KEY` in the environment; `ses` needs the host's mouse enabled to click-copy.
71
72
 
72
73
  Every field named in `sidebar.rows` renders exactly one row, in order. With `sidebar.persist` (the default), a row with no data yet shows the `sidebar.placeholder` value (default `—`) in the same label column as a live row — so the rail keeps a stable shape instead of growing rows as the session produces data. Set `"persist": false` to restore omission: rows with no data are left out entirely.
73
74
 
@@ -154,10 +155,12 @@ Everything else lives in the example file, documented inline - a typo is never f
154
155
 
155
156
  ---
156
157
 
157
- ## 🔒 It reads. It writes one number — two with `guard` on.
158
+ ## 🔒 It reads. It writes almost nothing.
158
159
 
159
160
  Flight Deck shows what OpenCode already knows.
160
161
 
162
+ - **One clipboard write, and only on a click.** With the opt-in `ses` row on the rail, a mouse click on that row copies the full session id to the terminal clipboard. Nothing is copied on render, in the background, or without that gesture; a terminal that cannot take the write simply does nothing.
163
+
161
164
  - **No network calls while the opt-in `guard` row stays off.** Nothing is fetched, nothing is sent. With `guard` enabled, the panel polls the local guard RPC — same machine, no telemetry — about every ten seconds, plus right away when the rendered session changes.
162
165
  - **No telemetry.** Nothing is collected or phoned home.
163
166
  - **Nothing on disk.** The one thing it normally writes is an animation counter in the host's in-memory plugin state, so the spinner and a running `elapsed` clock keep moving between host events. It is scoped to this plugin and dies with the TUI; it is never persisted, and `"refresh": 0` removes even that. With `"refresh": 0` the rail re-reads only on host events, so a busy stretch that produces few events can undercount `elapsed` — no unobserved gap bills beyond its bound, and a longer gap banks nothing. With `guard` enabled there is a second in-memory write — that row's polled status — and `"refresh": 0` does not remove it; dropping `guard` from `sidebar.rows` does.
@@ -204,7 +207,7 @@ Built on the official [OpenCode V2 CLI plugin API](https://opencode.ai/v2/docs/b
204
207
  | Built against | `@opencode/plugin` `2.0.19` — pin a host version you've tested |
205
208
  | Host | OpenCode V2 (`opencode2`) |
206
209
  | Building from source | Node ≥ 22 or Bun ≥ 1.4 |
207
- | Writes | In-memory counters only — the animation tick, plus the `guard` row's polled status when `guard` is on; nothing to disk |
210
+ | Writes | In-memory counters only — the animation tick, plus the `guard` row's polled status when `guard` is on; with the opt-in `ses` row, a click copies the id to the terminal clipboard (never automatic); nothing to disk |
208
211
 
209
212
  ---
210
213
 
@@ -104,13 +104,14 @@
104
104
  // assistant turn spans the host already recorded, so it
105
105
  // survives a restart instead of resetting; work observed live
106
106
  // after that keeps counting in memory
107
- // tps average speed while working: output tokens divided by the
108
- // time the assistant's turns actually ran, subagents included.
109
- // Idle between turns is never counted, so the figure freezes
110
- // when everything settles rather than decaying or hiding; a
111
- // turn still in flight counts up to now. On a host with no
112
- // per-message timestamps it falls back to the lifetime
113
- // average, which includes idle and can sag
107
+ // tps average speed while streaming: output plus reasoning tokens
108
+ // divided by the time the provider was actively streaming
109
+ // (streamed minus created), subagents included. Idle between
110
+ // turns and the tool settlement after one are never counted,
111
+ // so the figure freezes when everything settles rather than
112
+ // decaying or hiding; a turn still in flight counts up to now.
113
+ // On a host with no per-message timestamps it falls back to
114
+ // the lifetime average, which includes idle and can sag
114
115
  // spark recent turn sizes as a sparkline
115
116
  // reasoning reasoning tokens, when the model emits them
116
117
  // turns how many prompts you have sent this session
@@ -119,6 +120,9 @@
119
120
  // go Zen Go account usage for the 5h / 1w / 1m windows: a dial and
120
121
  // a percent each, turning red as a window approaches its limit.
121
122
  // Reads OPENCODE_GO_API_KEY. Available, off by default.
123
+ // ses the open session id, shortened to its first 8 characters.
124
+ // A mouse click on the row copies the full id to the terminal
125
+ // clipboard. Off by default; needs the host's mouse enabled.
122
126
  //
123
127
  // Every named row renders persistently, so the rail keeps a stable shape:
124
128
  // a row with no data yet shows the placeholder below, in the same label
@@ -139,6 +143,7 @@
139
143
  // ,"go" — Zen Go account usage (needs OPENCODE_GO_API_KEY)
140
144
  // ,"caution" — the annunciator
141
145
  // ,"branch" — current git branch
146
+ // ,"ses" — current session id (first 8 chars); click to copy the full id
142
147
  ],
143
148
 
144
149
  // Every named row renders persistently: with no data yet it shows the
@@ -52,10 +52,10 @@
52
52
  },
53
53
  "rows": {
54
54
  "type": "array",
55
- "items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard", "go"] },
55
+ "items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard", "go", "ses"] },
56
56
  "default": ["status", "agent", "model", "cost", "project", "tokens", "cache", "context", "perms", "elapsed", "tps"],
57
57
  "maxItems": 24,
58
- "description": "Which live fields to draw, top to bottom. Any subset, any order — this is the single most useful thing to change. With `sidebar.persist` (the default) every named row always renders, using `sidebar.placeholder` until the host has data; with `persist: false` rows with no data are omitted entirely. Counted together with `sidebar.lines` against a 24-line cap on the whole rail."
58
+ "description": "Which live fields to draw, top to bottom. Any subset, any order — this is the single most useful thing to change. With `sidebar.persist` (the default) every named row always renders, using `sidebar.placeholder` until the host has data; with `persist: false` rows with no data are omitted entirely. Counted together with `sidebar.lines` against a 24-line cap on the whole rail. The opt-in `ses` row shows the open session id shortened to its first 8 characters; a mouse click on that row copies the full id to the terminal clipboard."
59
59
  },
60
60
  "persist": {
61
61
  "type": "boolean",
@@ -268,7 +268,7 @@
268
268
  }
269
269
  },
270
270
  "propertyNames": {
271
- "enum": ["*", "caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard", "go"]
271
+ "enum": ["*", "caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard", "go", "ses"]
272
272
  },
273
273
  "default": { "*": { "color": "subdued", "attributes": [] } },
274
274
  "description": "Style all live rows under `*`, then optionally override any known row name such as `cost`. A row can change one field and inherit the other from `*`; unknown row names are reported and ignored."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oc-flight-deck",
3
- "version": "0.8.1",
3
+ "version": "0.10.0",
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",
@@ -38,7 +38,8 @@
38
38
  "flight-deck.example.jsonc",
39
39
  "flight-deck.schema.json",
40
40
  "README.md",
41
- "LICENSE"
41
+ "LICENSE",
42
+ "CHANGELOG.md"
42
43
  ],
43
44
  "engines": {
44
45
  "node": ">=22",
@@ -47,7 +48,8 @@
47
48
  "scripts": {
48
49
  "typecheck": "tsc --noEmit",
49
50
  "test": "bun test",
50
- "check": "bun run typecheck && bun test"
51
+ "check": "bun run typecheck && bun test",
52
+ "prepublishOnly": "bun run check"
51
53
  },
52
54
  "publishConfig": {
53
55
  "access": "public"
@@ -0,0 +1,37 @@
1
+ // The one clipboard write in the plugin: a session id, copied on a gesture.
2
+ //
3
+ // The plugin Context exposes no clipboard member, so this reaches through the
4
+ // renderer OpenTUI already hands the plugin and writes OSC52 directly. That is
5
+ // not a sanctioned plugin API, so it is kept to a single narrow function and
6
+ // two rules hold it in place:
7
+ //
8
+ // 1. It is called only from an explicit mouse gesture on the `ses` row. There
9
+ // is no render-time, background, or automatic write, ever.
10
+ // 2. A renderer that cannot take the write degrades to a no-op. A copy that
11
+ // did not happen must never take the panel (or the click) down with it.
12
+ //
13
+ // `createRendererClipboardAdapter` is the OSC52 boundary: it reads the
14
+ // renderer's terminal capabilities and, unless OSC52 is reported unsupported,
15
+ // calls `renderer.copyToClipboardOSC52`. Wrapping it here keeps the rest of the
16
+ // rail from knowing the clipboard exists.
17
+
18
+ import { createRendererClipboardAdapter } from "@opentui/core";
19
+
20
+ type RendererBoundary = Parameters<typeof createRendererClipboardAdapter>[0];
21
+
22
+ /**
23
+ * Write `text` to the terminal clipboard, or do nothing.
24
+ *
25
+ * Returns true only when the adapter attempted the write. An absent renderer, a
26
+ * terminal without OSC52, or a renderer missing the OSC52 method all return
27
+ * false without throwing.
28
+ */
29
+ export function copyToClipboard(renderer: unknown, text: string): boolean {
30
+ if (renderer === undefined || renderer === null) return false;
31
+ try {
32
+ const terminal = createRendererClipboardAdapter(renderer as RendererBoundary);
33
+ return terminal.writeText(text, "clipboard").status === "attempted";
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
package/src/tui/index.tsx CHANGED
@@ -1,6 +1,7 @@
1
1
  /** @jsxImportSource @opentui/solid */
2
2
  import { Plugin } from "@opencode/plugin/tui";
3
3
  import { cautionDetail, cautionText, detectCautions, worstCaution, type Caution } from "./caution.js";
4
+ import { copyToClipboard } from "./clipboard.js";
4
5
  import { cautionThresholds, mergeOptions, resolveConfig } from "./config.js";
5
6
  import { loadConfigFile } from "./file-config.js";
6
7
  import { footerLine, railLineSpans, railLines, railLineStyle, type RailLine } from "./presentation.js";
@@ -70,14 +71,14 @@ export default Plugin.define({
70
71
  // instead of assigning `undefined` over it, so the shipped config draws
71
72
  // exactly what it always drew. Shared with the sidebar footer slot so both
72
73
  // rails stay one styling path.
73
- const themedLine = (line: RailLine) => {
74
+ const themedLine = (line: RailLine, copyId?: string) => {
74
75
  const style = railLineStyle(config.style, line);
75
76
  const lineFg = themeColor(style.color, context.theme) as string | undefined;
76
77
  // The span mapping — which run inherits the line's colour and which
77
78
  // takes its own tone — lives in a pure helper, so the "only the flagged
78
79
  // window is red" decision is tested directly. All this renderer does is
79
80
  // resolve each role to a theme colour and pass `fg`, never ANSI.
80
- return (
81
+ const text = (
81
82
  <text fg={lineFg} attributes={attributeMask(style.attributes) ?? 0}>
82
83
  {railLineSpans(line, style).map((span) => (
83
84
  <span style={{ fg: themeColor(span.color, context.theme) as string | undefined }}>
@@ -86,6 +87,13 @@ export default Plugin.define({
86
87
  ))}
87
88
  </text>
88
89
  );
90
+ // The `ses` row is the one live row with a second gesture: a click copies
91
+ // the full session id. The handler wraps the line in a box so it fires
92
+ // wherever the row is clicked (mouse events bubble up, never down), and
93
+ // it closes over the id from THIS render — see `snapshot` for why the id
94
+ // is never cached.
95
+ if (copyId === undefined) return text;
96
+ return <box onMouseUp={() => copyToClipboard(context.renderer, copyId)}>{text}</box>;
89
97
  };
90
98
 
91
99
  // Bound a bankable window to a few ticks: `min(60s, max(5s, 4 * refreshMs))`,
@@ -222,6 +230,10 @@ export default Plugin.define({
222
230
  // Read the go store inside the render too, so a poll re-runs the rail
223
231
  // exactly as the guard read does.
224
232
  go: goBridge?.usage,
233
+ // The id comes from the slot render props, read fresh on every render
234
+ // rather than cached: the sidebar is not remounted on a session switch,
235
+ // so a signal or module variable here would copy a stale session.
236
+ sessionId: wants("ses") ? sessionID : undefined,
225
237
  // Read the tick inside the render so the host registers a dependency on
226
238
  // it; that read is what makes the rail re-run on the ticker's schedule.
227
239
  frame: ticker?.frame ?? 0,
@@ -287,7 +299,7 @@ export default Plugin.define({
287
299
  // No padding here: the host already lays out and pads the sidebar,
288
300
  // so adding our own would push the rows out of alignment with it.
289
301
  <box flexDirection="column">
290
- {lines.map(themedLine)}
302
+ {lines.map((line) => themedLine(line, line.field === "ses" ? sessionID : undefined))}
291
303
  </box>
292
304
  );
293
305
  },
package/src/tui/rows.ts CHANGED
@@ -357,7 +357,9 @@ export function statLine(
357
357
  case "tps": {
358
358
  const tps = asCount(source.tps);
359
359
  if (tps === undefined || tps === 0) return undefined;
360
- return row("tps", `${Math.round(tps)} tok/s`);
360
+ // One decimal, exactly as the official TUI renders it: rounding to a
361
+ // whole number would overstate a slow turn by up to half a token/second.
362
+ return row("tps", `${tps.toFixed(1)} tok/s`);
361
363
  }
362
364
  case "spark": {
363
365
  const values = Array.isArray(source.spark) ? source.spark.map((value) => asCount(value) ?? 0) : [];
@@ -381,6 +383,13 @@ export function statLine(
381
383
  const token = guardToken(source.guard);
382
384
  return token === undefined ? undefined : row("guard", token);
383
385
  }
386
+ case "ses": {
387
+ const id = asText(source.sessionId);
388
+ // Only the first eight characters are drawn: a session id is longer than
389
+ // the rail and would wrap. The full id stays in the source so the row's
390
+ // copy gesture can write it.
391
+ return id === undefined ? undefined : row("ses", id.slice(0, 8));
392
+ }
384
393
  case "go": {
385
394
  // The plain string is the exact join of the coloured segments, so the
386
395
  // string view (tests, `sidebarTextLines`) and the JSX view agree
@@ -253,7 +253,9 @@ export function createSessionReads(context: Plugin.Context, maxBankedMs?: number
253
253
  const created = asCount(stamp?.["created"]);
254
254
  const completed = asCount(stamp?.["completed"]);
255
255
  const streamed = asCount(stamp?.["streamed"]);
256
- const span = turnSpan(created, completed, streamed, now);
256
+ // `elapsed` ends a settled turn at `completed`: the clock stays busy
257
+ // through the turn's tool settlement, which `streamed` would drop.
258
+ const span = turnSpan(created, completed, streamed, now, "completed");
257
259
  if (span === undefined) continue;
258
260
  const output = asRecord(message["tokens"])?.["output"];
259
261
  spans.push({ key: turnKey(message["id"], created, completed, output), ...span });
@@ -1,9 +1,10 @@
1
1
  // Session throughput, measured from the host's own message timestamps and never
2
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.
3
+ // an active-work average: output plus reasoning tokens divided by the union of
4
+ // the turns' own streaming spans (`streamed - created`, fallbacks in
5
+ // ./throughput.js), so idle between turns and the tool settlement after one are
6
+ // not in the denominator and the figure freezes once everything settles. A host
7
+ // proven to expose no message timestamps uses the lifetime average instead.
7
8
  //
8
9
  // The capability is learned once and remembered for the process. `undefined`
9
10
  // means "not yet known": a read that failed, or carried no assistant turns,
@@ -76,10 +77,18 @@ export function createTpsReader(
76
77
  if (created === undefined && completed === undefined && streamed === undefined) continue;
77
78
  stamped += 1;
78
79
  // Without `created` there is no start; the turn is skipped, not guessed.
79
- const span = turnSpan(created, completed, streamed, now);
80
+ // `tps` ends a turn at `streamed`: decoding stopped is the numerator clock.
81
+ const span = turnSpan(created, completed, streamed, now, "streamed");
80
82
  if (span === undefined) continue;
81
- const output = asRecord(message["tokens"])?.["output"];
82
- spans.push({ key: turnKey(message["id"], created, completed, output), tokens: output, ...span });
83
+ const tokens = asRecord(message["tokens"]);
84
+ // The numerator the TUI divides: output plus reasoning. Both are carried
85
+ // so the union can add them without losing either rung.
86
+ spans.push({
87
+ key: turnKey(message["id"], created, completed, tokens?.["output"]),
88
+ tokens: tokens?.["output"],
89
+ reasoning: tokens?.["reasoning"],
90
+ ...span,
91
+ });
83
92
  }
84
93
  return { ok: true, assistant, stamped, spans };
85
94
  };
@@ -87,7 +96,10 @@ export function createTpsReader(
87
96
  // The lifetime average, the metric of last resort for a host that exposes no
88
97
  // per-message timestamps. Measured from the session's own clock
89
98
  // (`time.updated`, falling back to now) so a finished session settles on a
90
- // stable figure instead of decaying as it sits on screen.
99
+ // stable figure instead of decaying as it sits on screen. The numerator is
100
+ // the session record's `output` plus its `reasoning`, the same pair the
101
+ // stamped path divides: `tokens` is a `TokenUsage.Info`, so the reasoning
102
+ // rung is present and counting output alone would under-report.
91
103
  const lifetimeTps = (
92
104
  sessionID: string,
93
105
  session: SessionLike | undefined,
@@ -99,8 +111,13 @@ export function createTpsReader(
99
111
  const elapsed = end - created;
100
112
  if (elapsed <= 0) return undefined;
101
113
 
102
- const own = asCount(asRecord(session?.tokens)?.["output"]);
103
- let output = own;
114
+ const tokensOf = (source: SessionLike | undefined): number | undefined => {
115
+ const tokens = asRecord(source?.tokens);
116
+ if (tokens === undefined) return undefined;
117
+ return (asCount(tokens["output"]) ?? 0) + (asCount(tokens["reasoning"]) ?? 0);
118
+ };
119
+
120
+ let output = tokensOf(session);
104
121
  // Only a family root owns the tree beneath it; a child asking `family()`
105
122
  // gets its ancestors and siblings too, so it keeps its own figure.
106
123
  if (isFamilyRoot(sessionID)) {
@@ -111,9 +128,9 @@ export function createTpsReader(
111
128
  let sawOne = false;
112
129
  for (const id of ids) {
113
130
  const member = context.data.session.get(id) as SessionLike | undefined;
114
- const out = asCount(asRecord(member?.tokens)?.["output"]);
115
- if (out === undefined) continue;
116
- total += out;
131
+ const memberTokens = tokensOf(member);
132
+ if (memberTokens === undefined) continue;
133
+ total += memberTokens;
117
134
  sawOne = true;
118
135
  }
119
136
  if (sawOne) output = total;
@@ -138,9 +155,10 @@ export function createTpsReader(
138
155
  // instant and the union cannot be skewed by the scans drifting apart.
139
156
  const now = Date.now();
140
157
 
141
- // Timestamped assistant output this session has produced, plus — only from
142
- // a family root — every subagent session's. A child asking `family()` gets
143
- // its ancestors and siblings back, so it keeps its own spans.
158
+ // Timestamped assistant tokens (output + reasoning) this session has
159
+ // produced, plus — only from a family root — every subagent session's. A
160
+ // child asking `family()` gets its ancestors and siblings back, so it keeps
161
+ // its own spans.
144
162
  const scans: TpsScan[] = [scanMessages(sessionID, now)];
145
163
  if (isFamilyRoot(sessionID)) {
146
164
  try {
@@ -22,6 +22,12 @@ export interface StatSource {
22
22
  readonly cost?: unknown;
23
23
  readonly tokens?: unknown;
24
24
  readonly branch?: unknown;
25
+ /**
26
+ * The open session id, straight from the slot render props. Untrusted like
27
+ * every other field: the `ses` row draws only the first eight characters,
28
+ * while the full value is what that row's copy gesture writes.
29
+ */
30
+ readonly sessionId?: unknown;
25
31
  readonly tree?: unknown;
26
32
  readonly context?: unknown;
27
33
  readonly project?: unknown;
@@ -31,11 +37,12 @@ export interface StatSource {
31
37
  readonly perms?: unknown;
32
38
  /**
33
39
  * 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.
40
+ * active-work average: output plus reasoning tokens divided by the union of
41
+ * the assistant turns' provider-active spans (`streamed - created`), with
42
+ * idle between turns and the tool settlement after one excluded, subagents
43
+ * summed in, so the figure freezes when work stops. On a host without
44
+ * message timestamps it falls back to the lifetime average, which can still
45
+ * sag. Either way it is derived from state the host already holds.
39
46
  */
40
47
  readonly tps?: unknown;
41
48
  readonly elapsedMs?: unknown;
@@ -75,6 +82,7 @@ export const STAT_FIELDS = [
75
82
  "turns",
76
83
  "guard",
77
84
  "go",
85
+ "ses",
78
86
  ] as const;
79
87
 
80
88
  type StatField = (typeof STAT_FIELDS)[number];
package/src/tui/stats.ts CHANGED
@@ -23,4 +23,4 @@ export {
23
23
  unionSpanThroughput,
24
24
  unionSpanTotals,
25
25
  } from "./throughput.js";
26
- export type { SpanTotals, ThroughputSpan } from "./throughput.js";
26
+ export type { SpanEndPreference, SpanTotals, ThroughputSpan } from "./throughput.js";
@@ -1,65 +1,93 @@
1
- // Session throughput: output tokens per second, measured over the active work
2
- // the host actually recorded rather than over the wall clock.
1
+ // Session throughput: output and reasoning tokens per second, measured over the
2
+ // provider-active time the host actually recorded rather than over the wall
3
+ // clock.
3
4
  //
4
5
  // Pure: no clock, no I/O, no rendering. Untrusted sample fields are coerced
5
6
  // through ./coerce.js so a garbage value is skipped rather than guessed at.
6
7
  //
7
8
  // Two rates live here. `sessionThroughput` is the whole-lifetime average, kept
8
9
  // as the metric of last resort for a host that exposes no per-message
9
- // timestamps. `unionSpanThroughput` is the active-work average: output tokens
10
- // divided by the union of the assistant turns' own spans, so idle between turns
11
- // is never in the denominator and the figure freezes once everything settles.
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
13
+ // figure freezes once everything settles.
12
14
 
13
15
  import { asCount, asText } from "./coerce.js";
14
16
 
15
17
  /**
16
- * Overall session throughput: output tokens over the session's lifetime.
18
+ * Overall session throughput: output plus reasoning tokens over the session's
19
+ * lifetime.
20
+ *
21
+ * `tokens` is the same numerator the active-work average divides — a session
22
+ * record's `tokens` is a `TokenUsage.Info`, so its `reasoning` rung is present
23
+ * and belongs on this path too. Counting output alone would under-report a
24
+ * thinking-heavy model and disagree with the row's stated definition.
17
25
  *
18
26
  * Unlike the active-work average, this is the whole conversation's average, so
19
27
  * it includes every subagent and every pause. A just-started session is floored
20
28
  * at one second so it cannot divide by a sliver of time and flash an absurd
21
29
  * rate. Returns `undefined` when there is nothing to divide.
22
30
  */
23
- export function sessionThroughput(outputTokens: unknown, elapsedMs: unknown): number | undefined {
24
- const output = asCount(outputTokens);
31
+ export function sessionThroughput(tokens: unknown, elapsedMs: unknown): number | undefined {
32
+ const total = asCount(tokens);
25
33
  const elapsed = asCount(elapsedMs);
26
- if (output === undefined || output <= 0) return undefined;
34
+ if (total === undefined || total <= 0) return undefined;
27
35
  if (elapsed === undefined || elapsed <= 0) return undefined;
28
- return output / (Math.max(elapsed, 1_000) / 1_000);
36
+ return total / (Math.max(elapsed, 1_000) / 1_000);
29
37
  }
30
38
 
31
39
  /**
32
40
  * One assistant turn's contribution to the active-work average.
33
41
  *
34
- * `key` is the turn's identity (see `turnKey`); `tokens` is its output count;
35
- * `start` and `end` are its span on the host's epoch clock. Every field is
36
- * untrusted and coerced before use.
42
+ * `key` is the turn's identity (see `turnKey`); `tokens` is its output count and
43
+ * `reasoning` its reasoning count, which the numerator adds together; `start`
44
+ * and `end` are its span on the host's epoch clock. Every field is untrusted and
45
+ * coerced before use.
37
46
  */
38
47
  export interface ThroughputSpan {
39
48
  readonly key?: unknown;
40
49
  readonly tokens?: unknown;
50
+ readonly reasoning?: unknown;
41
51
  readonly start?: unknown;
42
52
  readonly end?: unknown;
43
53
  }
44
54
 
55
+ /**
56
+ * Which recorded stamp ends an assistant turn's span when more than one is
57
+ * present. The choice is the caller's, not the helper's: the two consumers want
58
+ * different clocks off the same record.
59
+ *
60
+ * `"streamed"` ends at `time.streamed`, the moment the provider stopped
61
+ * decoding - the official TUI's numerator clock, used by `tps`.
62
+ * `"completed"` ends at `time.completed`, once the turn's tools have settled -
63
+ * the busy clock, used by the `elapsed` seed.
64
+ */
65
+ export type SpanEndPreference = "streamed" | "completed";
66
+
45
67
  /**
46
68
  * Resolve one assistant turn's span from its timestamp rungs.
47
69
  *
48
- * `start` is `time.created`. `end` is `time.completed`, else `time.streamed`,
49
- * else the caller's `nowMs` for a turn still in flight. A clock that steps
50
- * backwards is clamped to a zero-length span rather than a negative one, so
51
- * skew can never subtract time from the union. Returns `undefined` when there
52
- * is no usable start — the turn is skipped, never guessed at.
70
+ * `start` is `time.created`. `end` is the stamp `preference` names first when
71
+ * both are recorded, else the other rung, else the caller's `nowMs` for a turn
72
+ * still in flight. So `"streamed"` reads `streamed`, then `completed`;
73
+ * `"completed"` reads `completed`, then `streamed`. A clock that steps backwards
74
+ * is clamped to a zero-length span rather than a negative one, so skew can never
75
+ * subtract time from the union. Returns `undefined` when there is no usable
76
+ * start - the turn is skipped, never guessed at.
53
77
  */
54
78
  export function turnSpan(
55
79
  created: unknown,
56
80
  completed: unknown,
57
81
  streamed: unknown,
58
82
  nowMs: unknown,
83
+ preference: SpanEndPreference,
59
84
  ): { readonly start: number; readonly end: number } | undefined {
60
85
  const start = asCount(created);
61
86
  if (start === undefined) return undefined;
62
- const ended = asCount(completed) ?? asCount(streamed) ?? asCount(nowMs);
87
+ const ended =
88
+ preference === "streamed"
89
+ ? asCount(streamed) ?? asCount(completed) ?? asCount(nowMs)
90
+ : asCount(completed) ?? asCount(streamed) ?? asCount(nowMs);
63
91
  if (ended === undefined) return undefined;
64
92
  return { start, end: Math.max(start, ended) };
65
93
  }
@@ -76,7 +104,7 @@ export function turnKey(id: unknown, created: unknown, completed: unknown, outpu
76
104
  return `t:${asCount(created) ?? "?"}:${asCount(completed) ?? "?"}:${asCount(output) ?? "?"}`;
77
105
  }
78
106
 
79
- /** Output tokens and wall time the accepted turns actually cover. */
107
+ /** Output + reasoning tokens and wall time the accepted turns actually cover. */
80
108
  export interface SpanTotals {
81
109
  readonly tokens: number;
82
110
  readonly unionMs: number;
@@ -124,8 +152,14 @@ function mergedSpanMs(accepted: Array<{ start: number; end: number }>): number {
124
152
  * enters the union once — a dropped duplicate drops both sides together.
125
153
  * Spans are clamped (`end >= start`), then sorted and merged so overlapping
126
154
  * and touching turns count once and input order cannot change the result. A
127
- * turn with no usable token count contributes to neither side: the numerator
128
- * and the denominator always cover exactly the same turns.
155
+ * turn's numerator is its output plus its reasoning count, the same pair the
156
+ * official TUI divides.
157
+ *
158
+ * Every turn with a usable span counts in the denominator, including one that
159
+ * produced no tokens: a stamped step that streamed for two seconds still took
160
+ * two seconds, and dropping its span would inflate the rate above the official
161
+ * figure. The caller decides there is no rate at all when the total numerator
162
+ * or the total duration is not positive.
129
163
  */
130
164
  export function unionSpanTotals(spans: readonly ThroughputSpan[]): SpanTotals {
131
165
  const seen = new Set<string>();
@@ -138,27 +172,25 @@ export function unionSpanTotals(spans: readonly ThroughputSpan[]): SpanTotals {
138
172
 
139
173
  const start = asCount(span.start);
140
174
  const end = asCount(span.end);
141
- const output = asCount(span.tokens);
142
175
  if (start === undefined || end === undefined) continue;
143
- if (output === undefined || output <= 0) continue;
176
+ const output = asCount(span.tokens);
177
+ const reasoning = asCount(span.reasoning);
144
178
 
145
179
  seen.add(key);
146
180
  accepted.push({ start, end: Math.max(start, end) });
147
- tokens += output;
181
+ tokens += (output ?? 0) + (reasoning ?? 0);
148
182
  }
149
183
 
150
184
  return { tokens, unionMs: mergedSpanMs(accepted) };
151
185
  }
152
186
 
153
187
  /**
154
- * The union length of distinct turn spans, with tokens ignored entirely.
188
+ * The union length of distinct turn spans, returned without the token sum.
155
189
  *
156
- * The same identity rule, clamp, pre-sort and merge as `unionSpanTotals`, but
157
- * a turn's output count never enters the decision: a zero-output turn still
158
- * took wall time and still contributes its span. This is what seeds `elapsed`,
159
- * which must not undercount real work the way a token-gated union would.
160
- * A missing key is skipped; the first-seen key wins; a span without a usable
161
- * start and end is skipped; `0` when nothing is usable.
190
+ * The same identity rule, clamp, pre-sort and merge as `unionSpanTotals`:
191
+ * `elapsed` needs only the wall time, so the numerator never enters the
192
+ * decision. A missing key is skipped; the first-seen key wins; a span without
193
+ * a usable start and end is skipped; `0` when nothing is usable.
162
194
  */
163
195
  export function unionSpanMs(spans: readonly ThroughputSpan[]): number {
164
196
  const seen = new Set<string>();
@@ -180,15 +212,15 @@ export function unionSpanMs(spans: readonly ThroughputSpan[]): number {
180
212
  }
181
213
 
182
214
  /**
183
- * Active-work throughput: output tokens of the scope divided by the union of
184
- * its active turn spans. Idle time between turns is not in the denominator, so
185
- * the figure stops moving once everything settles instead of decaying or
186
- * hiding. A turn still in flight ends at the caller's `now`, so the value keeps
187
- * climbing while work happens.
215
+ * Active-work throughput: output and reasoning tokens of the scope divided by
216
+ * the union of its streaming turn spans. Idle time between turns and the
217
+ * settlement after a turn are not in the denominator, so the figure stops moving
218
+ * once everything settles instead of decaying or hiding. A turn still in flight
219
+ * ends at the caller's `now`, so the value keeps climbing while work happens.
188
220
  *
189
221
  * Floored at one second, the same floor the lifetime average uses, so a sliver
190
222
  * of time cannot flash an absurd rate. Returns `undefined` when there is
191
- * nothing to divide — no positive output, or no span with positive length.
223
+ * nothing to divide — no positive tokens, or no span with positive length.
192
224
  */
193
225
  export function unionSpanThroughput(spans: readonly ThroughputSpan[]): number | undefined {
194
226
  const { tokens, unionMs } = unionSpanTotals(spans);