oc-flight-deck 0.6.6 → 0.7.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/src/tui/go.ts ADDED
@@ -0,0 +1,266 @@
1
+ // Live Zen Go usage for the Flight Deck `go` row.
2
+ //
3
+ // This is the poll bridge only. The model it writes (./go-usage.ts) is pure; the
4
+ // row renderer is Stage 2. Shape is deliberately cloned from ./guard.ts — poll
5
+ // into the host's memory store, expose a reactive getter, never throw — with
6
+ // the differences the account-wide scope forces:
7
+ //
8
+ // * Guard is per-session, so it waits for `follow(sessionID)` before fetching.
9
+ // Go usage is account-wide: one API key, one shared quota, no session to
10
+ // target — so the timer starts at construction and there is no `follow`.
11
+ // * The key is read on every poll through the same env accessor the Zen Go
12
+ // client uses, so a key loaded or rotated after startup is picked up
13
+ // without a restart.
14
+ //
15
+ // Why the store bridge at all is documented in ./guard.ts and ./ticker.ts: the
16
+ // host's Solid and the plugin's are separate module instances, so only the
17
+ // host-owned `context.storage.memory` store can wake the host render.
18
+ //
19
+ // The bridge never throws. Any failure — no store, no key, refused request,
20
+ // non-OK status, malformed JSON — stores `null`, which the getter reads as
21
+ // `undefined` so the persist layer renders the placeholder. A missing key is
22
+ // explicitly not an error: it is the row's documented "no key" dash path.
23
+
24
+ import { normalizeGoUsage, type GoUsage } from "./go-usage.js";
25
+
26
+ /** The value kept in the host's memory store. Null means "no data". */
27
+ interface GoStoreState {
28
+ value: GoUsage | null;
29
+ }
30
+
31
+ /** The store the host hands back: read-only to us, reactive to the host. */
32
+ interface GoStore {
33
+ readonly value?: unknown;
34
+ }
35
+
36
+ /** The mutation function the host hands back. */
37
+ type GoUpdate = (mutation: (draft: GoStoreState) => void) => void;
38
+
39
+ /** The one host capability the bridge needs, so it stays trivially stubbable. */
40
+ export interface GoHost {
41
+ readonly storage?: {
42
+ /**
43
+ * Typed as `unknown` on the return on purpose: this is reached across a
44
+ * beta version boundary, so the shape is checked at runtime instead of
45
+ * trusted from a type that may not match the binary.
46
+ */
47
+ memory(key: string, options: { readonly initial: GoStoreState }): unknown;
48
+ };
49
+ }
50
+
51
+ /** Injectable key accessor and fetch, so tests never touch the network or env. */
52
+ export interface GoDeps {
53
+ readonly key?: () => string | undefined;
54
+ readonly fetchJson?: (url: string, init: RequestInit) => Promise<unknown>;
55
+ }
56
+
57
+ interface GoBridge {
58
+ /**
59
+ * Current usage, read from the host's store.
60
+ *
61
+ * This must be read inside the slot render, while the host's reactive scope
62
+ * is active, or it will not register as a dependency and nothing will update.
63
+ * `undefined` means no data, so the persist layer renders the placeholder.
64
+ */
65
+ readonly usage: GoUsage | undefined;
66
+ /** Stops the timer. Safe to call more than once. */
67
+ dispose(): void;
68
+ }
69
+
70
+ /** Namespaced so it cannot collide with another plugin's memory keys. */
71
+ export const GO_KEY = "flight-deck.go";
72
+
73
+ /**
74
+ * How often the bridge re-reads usage.
75
+ *
76
+ * Account-wide quota moves far more slowly than per-session telemetry, and the
77
+ * endpoint is remote, so a poll per minute keeps the row fresh without a
78
+ * request storm. Deliberately not `config.refresh` (that drives the spinner).
79
+ */
80
+ export const GO_POLL_MS = 60_000;
81
+
82
+ /** The Zen Go usage endpoint. Fixed: usage is account-wide, not per-session. */
83
+ export const GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
84
+
85
+ /** The env var the Zen Go client reads its key from, matched by name only. */
86
+ export const GO_KEY_ENV = "OPENCODE_GO_API_KEY";
87
+
88
+ const GO_TIMEOUT_MS = 10_000;
89
+
90
+ /**
91
+ * Fetch and parse a usage payload. A non-OK response throws so the poll's one
92
+ * catch handles both transport and status failures; the body is only parsed
93
+ * once the status is known good.
94
+ */
95
+ async function defaultFetchJson(url: string, init: RequestInit): Promise<unknown> {
96
+ const response = await fetch(url, init);
97
+ if (!response.ok) throw new Error(`go usage: HTTP ${response.status}`);
98
+ return response.json();
99
+ }
100
+
101
+ // A host whose store does not match the documented shape is treated as no store
102
+ // at all: half-opening one would throw on every poll instead of degrading.
103
+ // Validated exactly as ./ticker.ts and ./guard.ts validate theirs.
104
+ function openStore(storage: NonNullable<GoHost["storage"]>): { store: GoStore; update: GoUpdate } | undefined {
105
+ let opened: unknown;
106
+ try {
107
+ opened = storage.memory(GO_KEY, { initial: { value: null } });
108
+ } catch {
109
+ return undefined;
110
+ }
111
+
112
+ if (!Array.isArray(opened) || opened.length < 2) return undefined;
113
+ const [store, update] = opened as [unknown, unknown];
114
+ if (store === null || typeof store !== "object") return undefined;
115
+ if (typeof update !== "function") return undefined;
116
+
117
+ return { store: store as GoStore, update: update as GoUpdate };
118
+ }
119
+
120
+ function readUsage(store: GoStore | undefined): GoUsage | undefined {
121
+ try {
122
+ const value = store?.value;
123
+ if (value === null || value === undefined) return undefined;
124
+ return normalizeGoUsage(value);
125
+ } catch {
126
+ return undefined;
127
+ }
128
+ }
129
+
130
+ function writeValue(opened: { store: GoStore; update: GoUpdate }, value: GoUsage | null): boolean {
131
+ try {
132
+ opened.update((draft) => {
133
+ draft.value = value;
134
+ });
135
+ return true;
136
+ } catch {
137
+ return false;
138
+ }
139
+ }
140
+
141
+ function resolveKeyFn(deps: GoDeps | undefined): () => string | undefined {
142
+ if (deps !== undefined) {
143
+ try {
144
+ if (typeof deps.key === "function") return deps.key;
145
+ } catch {
146
+ // fall through to the env accessor
147
+ }
148
+ }
149
+ return () => process.env[GO_KEY_ENV];
150
+ }
151
+
152
+ function resolveFetchJson(deps: GoDeps | undefined): (url: string, init: RequestInit) => Promise<unknown> {
153
+ if (deps !== undefined) {
154
+ try {
155
+ if (typeof deps.fetchJson === "function") return deps.fetchJson;
156
+ } catch {
157
+ // fall through to the real fetch
158
+ }
159
+ }
160
+ return defaultFetchJson;
161
+ }
162
+
163
+ /**
164
+ * Start polling Go usage into the host's memory store, or return `undefined`
165
+ * when there is no usable store.
166
+ *
167
+ * Unlike ./guard.ts there is no `follow`: usage is account-wide, so the timer
168
+ * starts here and reads the key afresh on every poll. The first poll fires
169
+ * immediately so the row populates without waiting a full interval.
170
+ *
171
+ * Assumption: `deps` is a test-only override. Production omits it, so the
172
+ * accessor is `process.env[GO_KEY_ENV]` on each poll (late keys recover) and
173
+ * the request is the real `fetch` with a bounded timeout.
174
+ */
175
+ export function startGoBridge(
176
+ host: GoHost | undefined,
177
+ deps?: GoDeps | undefined,
178
+ intervalMs: number = GO_POLL_MS,
179
+ ): GoBridge | undefined {
180
+ const storage = host?.storage;
181
+ if (host === undefined || storage === undefined || typeof storage.memory !== "function") return undefined;
182
+
183
+ const opened = openStore(storage);
184
+ if (opened === undefined) return undefined;
185
+
186
+ const cadence = Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : GO_POLL_MS;
187
+ const keyFn = resolveKeyFn(deps);
188
+ const fetchJson = resolveFetchJson(deps);
189
+
190
+ let timer: ReturnType<typeof setInterval> | undefined;
191
+ // Generation invalidated on dispose, so a poll that outlives its bridge —
192
+ // after disposal or a hot reload where the host store is shared — cannot
193
+ // overwrite newer data.
194
+ let generation = 0;
195
+ // Monotonic request sequence so overlapping polls resolve in start order, not
196
+ // finish order: only the newest request of the current generation may write.
197
+ let nextSeq = 0;
198
+ let latestSeq = 0;
199
+ let disposed = false;
200
+
201
+ const stopTimer = (): void => {
202
+ if (timer !== undefined) clearInterval(timer);
203
+ timer = undefined;
204
+ };
205
+
206
+ const poll = async (): Promise<void> => {
207
+ if (disposed) return;
208
+ const myGeneration = generation;
209
+ const mySeq = ++nextSeq;
210
+ latestSeq = mySeq;
211
+ const stillCurrent = () => myGeneration === generation && mySeq === latestSeq && !disposed;
212
+
213
+ let key: string | undefined;
214
+ try {
215
+ key = keyFn();
216
+ } catch {
217
+ key = undefined;
218
+ }
219
+ // No key is the row's "no key" dash path, not an error: store null and
220
+ // make no request, so a keyless install never touches the endpoint.
221
+ if (typeof key !== "string" || key.length === 0) {
222
+ if (!stillCurrent()) return;
223
+ if (!writeValue(opened, null)) stopTimer();
224
+ return;
225
+ }
226
+
227
+ let raw: unknown;
228
+ try {
229
+ raw = await fetchJson(GO_USAGE_URL, {
230
+ headers: { Authorization: `Bearer ${key}` },
231
+ signal: AbortSignal.timeout(GO_TIMEOUT_MS),
232
+ });
233
+ } catch {
234
+ // Refused, timed out, non-OK status, or a transport failure: no data,
235
+ // not an error.
236
+ if (!stillCurrent()) return;
237
+ if (!writeValue(opened, null)) stopTimer();
238
+ return;
239
+ }
240
+ if (!stillCurrent()) return;
241
+ let normalized: GoUsage | null;
242
+ try {
243
+ normalized = normalizeGoUsage(raw) ?? null;
244
+ } catch {
245
+ normalized = null;
246
+ }
247
+ if (!writeValue(opened, normalized)) stopTimer();
248
+ };
249
+
250
+ timer = setInterval(() => {
251
+ void poll();
252
+ }, cadence);
253
+ // Populate the row now instead of after the first full cadence.
254
+ void poll();
255
+
256
+ return {
257
+ get usage() {
258
+ return readUsage(opened.store);
259
+ },
260
+ dispose() {
261
+ disposed = true;
262
+ generation += 1;
263
+ stopTimer();
264
+ },
265
+ };
266
+ }
package/src/tui/index.tsx CHANGED
@@ -3,10 +3,11 @@ import { Plugin } from "@opencode/plugin/tui";
3
3
  import { cautionDetail, cautionText, detectCautions, worstCaution, type Caution } from "./caution.js";
4
4
  import { cautionThresholds, mergeOptions, resolveConfig } from "./config.js";
5
5
  import { loadConfigFile } from "./file-config.js";
6
- import { footerLine, railLines, railLineStyle } from "./presentation.js";
6
+ import { footerLine, railLineSpans, railLines, railLineStyle } from "./presentation.js";
7
7
  import { ANIMATED_FIELDS, type StatSource } from "./stats.js";
8
8
  import { attributeMask, themeColor } from "./style.js";
9
9
  import { startGuardBridge } from "./guard.js";
10
+ import { startGoBridge } from "./go.js";
10
11
  import { startTicker } from "./ticker.js";
11
12
  import { asCount, asRecord, type SessionLike } from "./coerce.js";
12
13
  import { createProjectTotals } from "./project-totals.js";
@@ -126,6 +127,12 @@ export default Plugin.define({
126
127
  const wantGuard = config.sidebar.enabled && config.sidebar.rows.includes("guard");
127
128
  const bridge = wantGuard ? startGuardBridge(context) : undefined;
128
129
 
130
+ // The go row is opt-in the same way: a row nobody drew should cost no timer
131
+ // and no request. The bridge is account-wide (one key, one quota), so it
132
+ // starts here and has no session to follow — unlike guard.
133
+ const wantGo = config.sidebar.enabled && config.sidebar.rows.includes("go");
134
+ const goBridge = wantGo ? startGoBridge(context) : undefined;
135
+
129
136
  // Read session state inside the render so the rail stays live: cost and
130
137
  // tokens climb as the session runs, and the branch appears once VCS
131
138
  // resolves. Nothing here writes, requests, or leaves the process.
@@ -184,6 +191,9 @@ export default Plugin.define({
184
191
  elapsedMs: wants("elapsed") ? sessionElapsed(sessionID) : undefined,
185
192
  turns,
186
193
  guard: bridge?.status,
194
+ // Read the go store inside the render too, so a poll re-runs the rail
195
+ // exactly as the guard read does.
196
+ go: goBridge?.usage,
187
197
  // Read the tick inside the render so the host registers a dependency on
188
198
  // it; that read is what makes the rail re-run on the ticker's schedule.
189
199
  frame: ticker?.frame ?? 0,
@@ -239,6 +249,7 @@ export default Plugin.define({
239
249
  bridge?.follow(sessionID);
240
250
  void ticker?.frame;
241
251
  void bridge?.status;
252
+ void goBridge?.usage;
242
253
 
243
254
  const source = snapshot(sessionID);
244
255
  const lines = railLines(config, source);
@@ -260,12 +271,19 @@ export default Plugin.define({
260
271
  <box flexDirection="column">
261
272
  {lines.map((line) => {
262
273
  const style = railLineStyle(config.style, line);
274
+ const lineFg = themeColor(style.color, context.theme) as string | undefined;
275
+ // The span mapping — which run inherits the row's colour and
276
+ // which takes its own tone — lives in a pure helper, so the
277
+ // "only the flagged window is red" decision is tested directly.
278
+ // All this renderer does is resolve each role to a theme colour
279
+ // and pass `fg`, never ANSI or escapes.
263
280
  return (
264
- <text
265
- fg={themeColor(style.color, context.theme) as string | undefined}
266
- attributes={attributeMask(style.attributes) ?? 0}
267
- >
268
- {line.text}
281
+ <text fg={lineFg} attributes={attributeMask(style.attributes) ?? 0}>
282
+ {railLineSpans(line, style).map((span) => (
283
+ <span style={{ fg: themeColor(span.color, context.theme) as string | undefined }}>
284
+ {span.text}
285
+ </span>
286
+ ))}
269
287
  </text>
270
288
  );
271
289
  })}
@@ -290,6 +308,7 @@ export default Plugin.define({
290
308
  watchTimer = undefined;
291
309
  ticker?.dispose();
292
310
  bridge?.dispose();
311
+ goBridge?.dispose();
293
312
  for (const release of releases) release();
294
313
  };
295
314
  },
@@ -6,8 +6,8 @@
6
6
  // session state, and nothing leaves the process.
7
7
 
8
8
  import type { FlightDeckConfig } from "./config.js";
9
- import { statLine, statRows, type StatSource } from "./stats.js";
10
- import { rowStyle, type LineStyle, type StyleConfig } from "./style.js";
9
+ import { statLine, statRows, statSegments, type StatSource, type StatSegment } from "./stats.js";
10
+ import { rowStyle, type LineStyle, type StyleColor, type StyleConfig } from "./style.js";
11
11
 
12
12
  /**
13
13
  * One line of the rail, before it is themed.
@@ -21,6 +21,12 @@ export interface RailLine {
21
21
  readonly text: string;
22
22
  /** The live row's field name; absent on a fixed line. */
23
23
  readonly field?: string;
24
+ /**
25
+ * The same line split into coloured runs, when a row's severity lives on part
26
+ * of it (only `go` today). `text` is always the exact join of these segments,
27
+ * so a caller that ignores them draws the row unchanged.
28
+ */
29
+ readonly segments?: readonly StatSegment[];
24
30
  }
25
31
 
26
32
  /**
@@ -49,6 +55,13 @@ export function railLines(config: FlightDeckConfig, source: StatSource = {}): re
49
55
 
50
56
  const lines: RailLine[] = config.sidebar.lines.map((text) => ({ text }));
51
57
  for (const field of config.sidebar.rows) {
58
+ // A segment-aware row carries its own coloured runs; its plain text is the
59
+ // exact join, so the string view is not a second source of truth.
60
+ const segments = statSegments(field, source, layout);
61
+ if (segments !== undefined) {
62
+ lines.push({ field, text: segments.map((segment) => segment.text).join(""), segments });
63
+ continue;
64
+ }
52
65
  // `statLine` is the half that knows the field's name; persistence stays in
53
66
  // `statRows`, which turns a data-less known field into the placeholder.
54
67
  // For a row that rendered, the fallback is never reached.
@@ -78,6 +91,38 @@ export function railLineStyle(style: StyleConfig, line: RailLine): LineStyle {
78
91
  return line.field === undefined ? style.lines : rowStyle(style, line.field);
79
92
  }
80
93
 
94
+ /**
95
+ * One themed run of a rail line: the text and the colour role it draws in.
96
+ *
97
+ * The role is the segment's own tone when it carries one, and the line's own
98
+ * colour otherwise — so a healthy row reads exactly as it did before part of a
99
+ * row could colour itself. Resolving a role into a renderer colour is left to
100
+ * the caller (and its theme); this type is deliberately the pure half.
101
+ */
102
+ export interface RailSpan {
103
+ readonly text: string;
104
+ /** The theme role: the segment's own tone, else the line's colour. */
105
+ readonly color: StyleColor;
106
+ }
107
+
108
+ /**
109
+ * A line's coloured runs with each role resolved, ready for the renderer.
110
+ *
111
+ * This is the "which part of the row is red" decision lifted out of the JSX: a
112
+ * flagged `go` window's dial and number take `error` while every other run
113
+ * inherits the line's own role. It is pure, so the mapping can be asserted
114
+ * directly rather than only through a renderer that may not even carry the
115
+ * theme token. A line with no segments is one run in the line's own colour, and
116
+ * the runs always concatenate back to `line.text`.
117
+ */
118
+ export function railLineSpans(line: RailLine, style: LineStyle): readonly RailSpan[] {
119
+ if (line.segments === undefined) return [{ text: line.text, color: style.color }];
120
+ return line.segments.map((segment) => ({
121
+ text: segment.text,
122
+ color: segment.tone ?? style.color,
123
+ }));
124
+ }
125
+
81
126
  /** Footer text to render, or `undefined` when the footer rail is disabled. */
82
127
  export function footerLine(config: FlightDeckConfig): string | undefined {
83
128
  return config.footer.enabled ? config.footer.text : undefined;
package/src/tui/rows.ts CHANGED
@@ -8,7 +8,9 @@
8
8
 
9
9
  import { DEFAULT_BAR_WIDTH, clip, formatCost, formatCount, formatDuration, fuelBar, sparkline } from "./format.js";
10
10
  import { asCount, asRecord, asText } from "./coerce.js";
11
+ import { goResetSuffix, goTone, type GoWindow } from "./go-usage.js";
11
12
  import { guardToken } from "./guard-tokens.js";
13
+ import type { StyleColor } from "./style.js";
12
14
  import {
13
15
  DEFAULT_LABEL_WIDTH,
14
16
  DEFAULT_PLACEHOLDER,
@@ -43,7 +45,145 @@ function plain(value: string): string {
43
45
  * keep the same column.
44
46
  */
45
47
  function formatRow(label: string, value: string, labelWidth: number): string {
46
- return `${label.padEnd(labelWidth)}${label.length >= labelWidth ? " " : ""}${plain(value)}`;
48
+ return `${labelPrefix(label, labelWidth)}${plain(value)}`;
49
+ }
50
+
51
+ /**
52
+ * The label column plus its guaranteed separator, before a row's value.
53
+ *
54
+ * Extracted so the plain and segmented renderers pad a label identically: a
55
+ * label wider than its column (`reasoning` at width 8) must still get a space
56
+ * in both, or the two views of one row would differ by one character.
57
+ */
58
+ function labelPrefix(label: string, labelWidth: number): string {
59
+ return `${label.padEnd(labelWidth)}${label.length >= labelWidth ? " " : ""}`;
60
+ }
61
+
62
+ /**
63
+ * One coloured run of a rail row.
64
+ *
65
+ * `tone` is a theme role from ./style.js, absent when the run keeps the row's
66
+ * own colour — a healthy row must read exactly as it did before the row could
67
+ * colour part of itself. A row's plain text is exactly the join of its
68
+ * segments, so the string view and the coloured view can never disagree.
69
+ */
70
+ export interface StatSegment {
71
+ readonly text: string;
72
+ readonly tone?: StyleColor;
73
+ }
74
+
75
+ /** Canonical `go` window order, so the dials always read 5h then 1w then 1m. */
76
+ const GO_ORDER: readonly GoWindow["id"][] = ["5h", "1w", "1m"];
77
+
78
+ /**
79
+ * Quarter-fill dials, from the approved design.
80
+ *
81
+ * The glyph is the shape, the number beside it is the precision; the thresholds
82
+ * are the design's own percent cutoffs kept exact. The empty circle doubles as
83
+ * the sane-zero, so a fresh window reads `○ 0` rather than a dash — the dash is
84
+ * reserved for "no data yet", which the persist layer draws.
85
+ */
86
+ const DIAL_STEPS: readonly (readonly [number, string])[] = [
87
+ [13, "○"],
88
+ [38, "◔"],
89
+ [63, "◑"],
90
+ [88, "◕"],
91
+ [101, "●"],
92
+ ];
93
+
94
+ function dialGlyph(percent: number): string {
95
+ for (const [limit, glyph] of DIAL_STEPS) {
96
+ if (percent < limit) return glyph;
97
+ }
98
+ return "●";
99
+ }
100
+
101
+ /**
102
+ * The Go windows the row can draw, in canonical order.
103
+ *
104
+ * The source is `unknown` on principle, so the shape is re-validated here: an
105
+ * entry is kept only when its `id` is one of the three windows and its `ratio`
106
+ * is a finite, non-negative number. The ratio is clamped to 1 at this boundary
107
+ * too, so a hand-built source cannot fill a dial past full or print `150`. A
108
+ * window with no ratio cannot draw an honest dial — a count with no known limit
109
+ * would fill the gauge by guesswork — so it is dropped rather than shown
110
+ * half-read.
111
+ */
112
+ function asGoWindows(value: unknown): readonly GoWindow[] {
113
+ const list = asRecord(value)?.windows;
114
+ if (!Array.isArray(list)) return [];
115
+ const windows: GoWindow[] = [];
116
+ for (const entry of list) {
117
+ const window = asRecord(entry);
118
+ if (window === undefined) continue;
119
+ const id = asText(window["id"]);
120
+ if (id !== "5h" && id !== "1w" && id !== "1m") continue;
121
+ const ratio = asCount(window["ratio"]);
122
+ if (ratio === undefined) continue;
123
+ const result: {
124
+ -readonly [K in keyof GoWindow]: GoWindow[K];
125
+ } = { id, ratio: Math.min(1, ratio) };
126
+ const resetAtMs = asCount(window["resetAtMs"]);
127
+ if (resetAtMs !== undefined) result.resetAtMs = resetAtMs;
128
+ const status = asText(window["status"]);
129
+ if (status !== undefined) result.status = status;
130
+ windows.push(result);
131
+ }
132
+ windows.sort((a, b) => GO_ORDER.indexOf(a.id) - GO_ORDER.indexOf(b.id));
133
+ return windows;
134
+ }
135
+
136
+ /**
137
+ * The `go` row's value as coloured segments, or `undefined` when there is
138
+ * nothing to draw (so the caller falls back to the placeholder).
139
+ *
140
+ * Only the offending window takes the error tone: the dial and its number turn
141
+ * red while its healthy neighbours keep the row's own colour, which is what
142
+ * makes the row read as one panel with a problem rather than as a different
143
+ * kind of line.
144
+ */
145
+ function goValueSegments(source: StatSource, layout: LayoutHint): StatSegment[] | undefined {
146
+ const windows = asGoWindows(source.go);
147
+ if (windows.length === 0) return undefined;
148
+
149
+ const nowMs = layout.nowMs ?? Date.now();
150
+ // Only the worst flagged window carries a reset hint. With every window red,
151
+ // three hints overflow the rail (the 38-column budget) for information that is
152
+ // redundant three times over; the fullest window is the one actually in
153
+ // trouble, so it is the one worth naming — not merely the first. `windows` is
154
+ // already in the fixed 5h → 1w → 1m order and a strict `>` keeps the earlier
155
+ // window on a tie, so equal ratios resolve to the nearest relief. A single
156
+ // flagged window is unchanged: it is the worst, and it keeps its hint.
157
+ let flagged = -1;
158
+ let flaggedRatio = Number.NEGATIVE_INFINITY;
159
+ for (const [index, window] of windows.entries()) {
160
+ if (goTone(window) !== "error") continue;
161
+ const ratio = window.ratio ?? 0;
162
+ if (flagged < 0 || ratio > flaggedRatio) {
163
+ flagged = index;
164
+ flaggedRatio = ratio;
165
+ }
166
+ }
167
+ const chunks: StatSegment[][] = [];
168
+ for (const [index, window] of windows.entries()) {
169
+ const percent = Math.round((window.ratio ?? 0) * 100);
170
+ const tone: StyleColor | undefined = goTone(window) === "error" ? "error" : undefined;
171
+ const chunk: StatSegment[] = [{ text: `${dialGlyph(percent)} ${percent}`, tone }];
172
+ // A reset hint beside a calm dial is noise and one in the past is a promise
173
+ // already broken, so it is drawn only on the flagged window that needs it.
174
+ const suffix = index === flagged ? goResetSuffix(window, nowMs) : undefined;
175
+ if (suffix !== undefined) chunk.push({ text: suffix, tone });
176
+ chunks.push(chunk);
177
+ }
178
+
179
+ const segments: StatSegment[] = [];
180
+ chunks.forEach((chunk, index) => {
181
+ // The separator inherits the row's colour: only the dial and number of a
182
+ // flagged window go red, never the space between windows.
183
+ if (index > 0) segments.push({ text: " " });
184
+ segments.push(...chunk);
185
+ });
186
+ return segments;
47
187
  }
48
188
 
49
189
  /**
@@ -241,11 +381,38 @@ export function statLine(
241
381
  const token = guardToken(source.guard);
242
382
  return token === undefined ? undefined : row("guard", token);
243
383
  }
384
+ case "go": {
385
+ // The plain string is the exact join of the coloured segments, so the
386
+ // string view (tests, `sidebarTextLines`) and the JSX view agree
387
+ // character-for-character.
388
+ const value = goValueSegments(source, layout);
389
+ return value === undefined ? undefined : row("go", value.map((segment) => segment.text).join(""));
390
+ }
244
391
  default:
245
392
  return undefined;
246
393
  }
247
394
  }
248
395
 
396
+ /**
397
+ * One field's rail row as coloured segments, or `undefined` when the field is
398
+ * not segment-aware or has nothing to draw.
399
+ *
400
+ * Only `go` is segment-aware today — the one row whose severity lives on part
401
+ * of the line rather than the whole. Every other field returns `undefined` and
402
+ * the caller falls through to {@link statLine}, so there is still exactly one
403
+ * place that knows a row's text.
404
+ */
405
+ export function statSegments(
406
+ field: string,
407
+ source: StatSource,
408
+ layout: LayoutHint = {},
409
+ ): readonly StatSegment[] | undefined {
410
+ if (field !== "go") return undefined;
411
+ const value = goValueSegments(source, layout);
412
+ if (value === undefined) return undefined;
413
+ return [{ text: labelPrefix("go", layout.labelWidth ?? DEFAULT_LABEL_WIDTH) }, ...value];
414
+ }
415
+
249
416
  /** Render every named field, in the given order.
250
417
  *
251
418
  * By default only fields with data render; with `layout.persist` every known
@@ -10,6 +10,7 @@
10
10
  import type { Plugin } from "@opencode/plugin/tui";
11
11
  import { createActiveElapsed } from "./active-elapsed.js";
12
12
  import { asCount, asRecord, asText, type SessionLike } from "./coerce.js";
13
+ import { turnKey, turnSpan, unionSpanMs, type ThroughputSpan } from "./stats.js";
13
14
 
14
15
  /**
15
16
  * The location the rail reads shell records and VCS from: the host's current
@@ -218,7 +219,57 @@ export function createSessionReads(context: Plugin.Context, maxBankedMs?: number
218
219
  // Accumulated active wall time: the clock runs only while `busy()` says the
219
220
  // session, its family, or its shells is working, and freezes otherwise. The
220
221
  // `now` parameter keeps the transition observation deterministic for tests.
221
- const activeElapsed = createActiveElapsed(busy, { maxBankedMs });
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 });
222
273
  const sessionElapsed = (sessionID: string, now: number = Date.now()): number | undefined =>
223
274
  activeElapsed(sessionID, now);
224
275