oc-flight-deck 0.6.7 → 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/README.md CHANGED
@@ -45,11 +45,11 @@ Every row is read from the open session at render time — except `caution`, whi
45
45
 
46
46
  | Row | What it shows |
47
47
  |---|---|
48
- | `caution` | **The annunciator** — silent unless something stopped moving |
48
+ | `caution` | **The annunciator** — silent unless something stopped moving · **off by default** |
49
49
  | `status` | A spinner while anything is working, a circle while it's idle |
50
50
  | `agent` | Which agent you're actually talking to |
51
51
  | `model` | The model **and its variant** — `high` behaves differently |
52
- | `branch` | The branch you're about to commit to |
52
+ | `branch` | The branch you're about to commit to · **off by default** |
53
53
  | `cost` | This conversation **plus its subagents**, and the count that explains it; with `total` on the rail, the session figure alone |
54
54
  | `total` | The family total and subagent count on a row of its own · **off by default** |
55
55
  | `project` | Every session in this project, not just the one on screen |
@@ -63,10 +63,11 @@ Every row is read from the open session at render time — except `caution`, whi
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
+ | `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** |
66
67
 
67
68
  `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.
68
69
 
69
- The rows marked **off by default** are available but not in the default rail: add any of them to `sidebar.rows`.
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.
70
71
 
71
72
  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.
72
73
 
@@ -78,6 +79,8 @@ The `guard` row only appears when oc-harness-guard is installed and answering; w
78
79
 
79
80
  A hang emits no events — its only signature is *absence*. So `caution` watches a clock, stays silent on healthy sessions, and when it speaks it reports what it saw, never what it means: `shell running 8m41s`, not "stuck".
80
81
 
82
+ The annunciator ships **off by default** — it is the one row that runs a clock of its own, so an install that never asks for it spends nothing on it. To use it, add `caution` to `sidebar.rows` **and** set `caution.enabled: true`.
83
+
81
84
  > Measured over **54,218 real settled tool calls**: 0.57% ran past three minutes — with the exempt list, **0.20%** light the row. A ten-minute build is not a hang.
82
85
 
83
86
  **Why cost carries the subagents:** subagents run as separate sessions; a session's own cost excludes them. On the session this was built against: reported `$0.2246`, true spend `$0.2447` — **9% low on money, 54% low on tokens.** One money row tells the truth.
@@ -119,7 +122,7 @@ Everything else lives in the example file, documented inline - a typo is never f
119
122
  "sidebar": {
120
123
  "maxLines": 24,
121
124
  "rows": [
122
- "caution", "status", "agent", "model", "branch", "cost", "project",
125
+ "status", "agent", "model", "cost", "project",
123
126
  "tokens", "cache", "context", "perms", "elapsed", "tps"
124
127
  ]
125
128
  },
@@ -69,11 +69,12 @@
69
69
  // them freely — an unknown name is ignored with a one-time warning, so a
70
70
  // typo can never break the panel.
71
71
  //
72
- // caution the annunciator: silent unless something stopped moving
72
+ // caution the annunciator: silent unless something stopped moving.
73
+ // Off by default — enables its own clock
73
74
  // status running or idle — the glyph turns while anything is working
74
75
  // agent which agent is running (orchestrator, build, plan, ...)
75
76
  // model model id, plus the variant when there is one
76
- // branch current git branch
77
+ // branch current git branch. Off by default — costs a VCS call
77
78
  // cost this conversation, plus its subagents when any ran; with
78
79
  // `total` on the rail, the session figure alone
79
80
  // total the family total and subagent count on a row of its own
@@ -100,17 +101,18 @@
100
101
  // turns how many prompts you have sent this session
101
102
  // guard harness status from oc-harness-guard: breaches, orphans,
102
103
  // findings, or ok. Available, off by default.
104
+ // go Zen Go account usage for the 5h / 1w / 1m windows: a dial and
105
+ // a percent each, turning red as a window approaches its limit.
106
+ // Reads OPENCODE_GO_API_KEY. Available, off by default.
103
107
  //
104
108
  // Every named row renders persistently, so the rail keeps a stable shape:
105
109
  // a row with no data yet shows the placeholder below, in the same label
106
110
  // column as a live row. The fixed lines and live rows share the maxLines
107
111
  // budget below, and anything past it is dropped.
108
112
  "rows": [
109
- "caution",
110
113
  "status",
111
114
  "agent",
112
115
  "model",
113
- "branch",
114
116
  "cost",
115
117
  "project",
116
118
  "tokens",
@@ -119,6 +121,9 @@
119
121
  "perms",
120
122
  "elapsed",
121
123
  "tps"
124
+ // ,"go" — Zen Go account usage (needs OPENCODE_GO_API_KEY)
125
+ // ,"caution" — the annunciator
126
+ // ,"branch" — current git branch
122
127
  ],
123
128
 
124
129
  // Every named row renders persistently: with no data yet it shows the
@@ -158,7 +163,9 @@
158
163
  //
159
164
  // It never aborts, kills, retries or blocks anything. Read-only.
160
165
  "caution": {
161
- "enabled": true,
166
+ // Off by default. Turn it on to run the annunciator; while off, the
167
+ // `caution` row never appears and no timer is spent on it.
168
+ "enabled": false,
162
169
 
163
170
  // A tool running longer than this draws a subdued triangle...
164
171
  "toolWatchSeconds": 180,
@@ -38,8 +38,8 @@
38
38
  },
39
39
  "rows": {
40
40
  "type": "array",
41
- "items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard"] },
42
- "default": ["caution", "status", "agent", "model", "branch", "cost", "project", "tokens", "cache", "context", "perms", "elapsed", "tps"],
41
+ "items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard", "go"] },
42
+ "default": ["status", "agent", "model", "cost", "project", "tokens", "cache", "context", "perms", "elapsed", "tps"],
43
43
  "maxItems": 24,
44
44
  "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."
45
45
  },
@@ -88,8 +88,8 @@
88
88
  "properties": {
89
89
  "enabled": {
90
90
  "type": "boolean",
91
- "default": true,
92
- "description": "Run the annunciator. false means the `caution` row never appears and no timer is spent on it."
91
+ "default": false,
92
+ "description": "Run the annunciator. Off by default. false means the `caution` row never appears and no timer is spent on it."
93
93
  },
94
94
  "toolWatchSeconds": {
95
95
  "type": "integer",
@@ -254,7 +254,7 @@
254
254
  }
255
255
  },
256
256
  "propertyNames": {
257
- "enum": ["*", "caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard"]
257
+ "enum": ["*", "caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard", "go"]
258
258
  },
259
259
  "default": { "*": { "color": "subdued", "attributes": [] } },
260
260
  "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.6.7",
3
+ "version": "0.7.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",
package/src/tui/config.ts CHANGED
@@ -57,7 +57,7 @@ interface FooterConfig {
57
57
  }
58
58
 
59
59
  interface CautionConfig {
60
- /** Show the caution annunciator. Default `true`. */
60
+ /** Show the caution annunciator. Default `false`. */
61
61
  readonly enabled: boolean;
62
62
  /** A tool running longer than this is worth noting. Default `180`. */
63
63
  readonly toolWatchSeconds: number;
@@ -93,7 +93,8 @@ export interface FlightDeckConfig {
93
93
  * The annunciator: the one thing on the rail that is not session state.
94
94
  *
95
95
  * It exists because a hang emits no events, so nothing else here can see it.
96
- * Silent when healthy, which is why it costs nothing visually.
96
+ * Silent when healthy, which is why it costs nothing visually. Off by default:
97
+ * it is opt-in, so an install that never asks for it spends no timer on it.
97
98
  */
98
99
  readonly caution: CautionConfig;
99
100
  /** Geometry of a row. Every value has a sane default. */
@@ -183,7 +184,7 @@ const DEFAULT_GLYPHS: GlyphConfig = {
183
184
  };
184
185
 
185
186
  const DEFAULT_CAUTION: CautionConfig = {
186
- enabled: true,
187
+ enabled: false,
187
188
  toolWatchSeconds: 180,
188
189
  toolCautionSeconds: 420,
189
190
  turnWatchSeconds: 600,
@@ -215,14 +216,14 @@ export const DEFAULT_SIDEBAR_LINES: readonly string[] = [
215
216
  * Live fields shown by default, in reading order.
216
217
  *
217
218
  * Every one of these is read from the open session at render time, so a fresh
218
- * install shows real numbers with no configuration file at all.
219
+ * install shows real numbers with no configuration file at all. The rows that
220
+ * need extra machinery or a second source — `caution` (a clock), `branch` (a
221
+ * VCS call), and `go` (an account-wide poll) — are opt-in via `sidebar.rows`.
219
222
  */
220
223
  export const DEFAULT_SIDEBAR_ROWS: readonly string[] = [
221
- "caution",
222
224
  "status",
223
225
  "agent",
224
226
  "model",
225
- "branch",
226
227
  "cost",
227
228
  "project",
228
229
  "tokens",
@@ -0,0 +1,315 @@
1
+ // The Go usage model for the `go` row.
2
+ //
3
+ // Everything here is pure: no I/O, no timers, no hidden `Date.now()`. The poll
4
+ // bridge in ./go.ts owns the clock and the network; this module only turns the
5
+ // Zen Go usage payload into the small fixed window model the row renders.
6
+ // Keeping it pure is what lets both documented response shapes be exercised
7
+ // without a server, and keeps the row renderer a renderer.
8
+ //
9
+ // The verified live shape, and the older shapes kept as defence in depth,
10
+ // because the endpoint is young enough that none is frozen:
11
+ //
12
+ // (a) live — `{ usage: { rolling, weekly, monthly } }`, each window
13
+ // `{ status, percent, resetsAt }` where `percent` is 0–100 of
14
+ // the window USED and `resetsAt` is an ISO-8601 string;
15
+ // (b) flat — rolling/weekly/monthly usage + limit columns, updated-at
16
+ // timestamps, all siblings at the top level;
17
+ // (c) nested — `{ usage: { rolling, weekly, monthly } }`, `{ windows: [...] }`,
18
+ // or a bare array of `{ window, usage, limit, resetAt }` rows.
19
+ //
20
+ // Values are opaque numbers (integer micro-cents or counts). We never unit-
21
+ // convert here: only the ratio is derived, and a ratio needs no unit. A missing
22
+ // or non-positive limit leaves `ratio` undefined rather than inventing a
23
+ // percentage, so a broken payload can never render as a confident 100%.
24
+
25
+ import { asRecord, asText } from "./coerce.js";
26
+
27
+ export interface GoWindow {
28
+ readonly id: "5h" | "1w" | "1m";
29
+ readonly used?: number;
30
+ readonly limit?: number;
31
+ readonly ratio?: number;
32
+ readonly resetAtMs?: number;
33
+ /**
34
+ * Per-window health string. Additive: absent on the older shapes. Passed
35
+ * through only when it is a non-empty string.
36
+ */
37
+ readonly status?: string;
38
+ }
39
+
40
+ export interface GoUsage {
41
+ readonly windows: readonly GoWindow[];
42
+ }
43
+
44
+ /** Canonical order, so the row always renders 5h then 1w then 1m. */
45
+ const WINDOW_ORDER: readonly GoWindow["id"][] = ["5h", "1w", "1m"];
46
+
47
+ function asFiniteNumber(value: unknown): number | undefined {
48
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
49
+ }
50
+
51
+ function firstFinite(...candidates: readonly unknown[]): number | undefined {
52
+ for (const candidate of candidates) {
53
+ const value = asFiniteNumber(candidate);
54
+ if (value !== undefined) return value;
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ /**
60
+ * Read an absolute instant in milliseconds from either an epoch number or an
61
+ * ISO-8601 string.
62
+ *
63
+ * The verified live payload carries `resetsAt` as an ISO-8601 string, while the
64
+ * older defensive shapes used an epoch number. A string that `Date.parse` cannot
65
+ * read (or that is not a string at all) yields `undefined` rather than a
66
+ * fabricated instant, so a malformed reset never becomes a confident hint.
67
+ */
68
+ function asInstantMs(value: unknown): number | undefined {
69
+ const numeric = asFiniteNumber(value);
70
+ if (numeric !== undefined) return numeric;
71
+ const text = asText(value);
72
+ if (text === undefined) return undefined;
73
+ const parsed = Date.parse(text);
74
+ return Number.isFinite(parsed) ? parsed : undefined;
75
+ }
76
+
77
+ /** The first candidate that reads as an absolute instant, or `undefined`. */
78
+ function firstInstant(...candidates: readonly unknown[]): number | undefined {
79
+ for (const candidate of candidates) {
80
+ const value = asInstantMs(candidate);
81
+ if (value !== undefined) return value;
82
+ }
83
+ return undefined;
84
+ }
85
+
86
+ /**
87
+ * The verified live shape reports usage as `percent`, a number 0–100 of the
88
+ * window already used, rather than a `used`/`limit` pair. `0` is a real fresh
89
+ * window (ratio 0), not a missing value; a non-number such as the string `"79"`
90
+ * is dropped rather than coerced, so a mistyped payload cannot read as usage.
91
+ *
92
+ * A percent above 100 is CLAMPED to a ratio of 1, never rejected. Over-the-limit
93
+ * is precisely the state this row exists to reveal, so dropping the window would
94
+ * hide the worst case; a full dial plus the error tone is the honest read. The
95
+ * ratio is clamped into `[0, 1]` here so no caller has to wonder how full "150%"
96
+ * is, while a negative or non-finite percent is still dropped as garbage.
97
+ */
98
+ function ratioFromPercent(value: unknown): number | undefined {
99
+ const percent = asFiniteNumber(value);
100
+ if (percent === undefined || percent < 0) return undefined;
101
+ return Math.min(1, percent / 100);
102
+ }
103
+
104
+ /**
105
+ * Map a window name to one of the three known ids.
106
+ *
107
+ * Names are lowercased and stripped of separators so `5-hour`, `5h`, and
108
+ * `5h_rolling` all land on the same id; an unknown name is dropped so a new
109
+ * server-side window cannot silently masquerade as one the row understands.
110
+ */
111
+ function windowIdFrom(value: unknown): GoWindow["id"] | undefined {
112
+ const text = asText(value);
113
+ if (text === undefined) return undefined;
114
+ const key = text.toLowerCase().replace(/[^a-z0-9]/g, "");
115
+ if (key.startsWith("rolling") || key === "5h" || key === "5hour" || key === "session") return "5h";
116
+ if (key.startsWith("weekly") || key === "1w" || key === "week" || key === "7d") return "1w";
117
+ if (key.startsWith("monthly") || key === "1m" || key === "month" || key === "30d") return "1m";
118
+ return undefined;
119
+ }
120
+
121
+ /** `used / limit` only when both are known and the limit is strictly positive. */
122
+ function ratioOf(used: number | undefined, limit: number | undefined): number | undefined {
123
+ if (used === undefined || limit === undefined || limit <= 0) return undefined;
124
+ return used / limit;
125
+ }
126
+
127
+ /**
128
+ * Assemble a window from already-extracted parts, omitting rather than
129
+ * fabricating what is unknown. Returns `undefined` when the id is unknown or
130
+ * neither a use nor a limit was readable — a bare timestamp is not a window.
131
+ */
132
+ function buildWindow(
133
+ id: GoWindow["id"] | undefined,
134
+ used: number | undefined,
135
+ limit: number | undefined,
136
+ resetAtMs: number | undefined,
137
+ explicitRatio?: number,
138
+ status?: string,
139
+ ): GoWindow | undefined {
140
+ if (id === undefined) return undefined;
141
+ // An explicit ratio (from `percent`) wins over `used / limit`; `??` keeps a
142
+ // legitimate explicit zero. A window with no use, no limit and no ratio is
143
+ // not a window: a bare timestamp, name or status must not render as one.
144
+ const ratio = explicitRatio ?? ratioOf(used, limit);
145
+ if (used === undefined && limit === undefined && ratio === undefined) return undefined;
146
+ const result: {
147
+ -readonly [K in keyof GoWindow]: GoWindow[K];
148
+ } = { id };
149
+ if (used !== undefined) result.used = used;
150
+ if (limit !== undefined) result.limit = limit;
151
+ if (ratio !== undefined) result.ratio = ratio;
152
+ if (resetAtMs !== undefined) result.resetAtMs = resetAtMs;
153
+ if (status !== undefined) result.status = status;
154
+ return result;
155
+ }
156
+
157
+ /**
158
+ * Normalize one window value: a bare number (count, no known limit) or an
159
+ * object carrying the use/limit/reset columns under any documented name.
160
+ */
161
+ function normalizeWindowValue(value: unknown, idHint?: GoWindow["id"]): GoWindow | undefined {
162
+ if (typeof value === "number") {
163
+ // A keyed map may map a window straight to its count. No limit is known,
164
+ // so no ratio — buildWindow leaves it undefined.
165
+ return buildWindow(idHint, asFiniteNumber(value), undefined, undefined);
166
+ }
167
+ const record = asRecord(value);
168
+ if (record === undefined) return undefined;
169
+ const id = idHint ?? windowIdFrom(record.window) ?? windowIdFrom(record.id) ?? windowIdFrom(record.name);
170
+ const used = firstFinite(record.usage, record.used, record.value, record.current, record.count);
171
+ const limit = firstFinite(record.limit, record.max, record.total, record.cap, record.quota);
172
+ // Only an explicit absolute timestamp becomes `resetAtMs`. `resetInSec` and
173
+ // `resetIn` are relative, and Stage 1 leaves them unhandled on purpose: a
174
+ // relative field read against an unknown clock is worse than no reset hint.
175
+ // An ISO-8601 `resetsAt` (the verified live shape) is accepted alongside the
176
+ // older epoch number.
177
+ const resetAtMs = firstInstant(record.resetAtMs, record.resetsAt, record.resetAt);
178
+ // The verified live shape's `percent` is a usage fraction with no limit pair.
179
+ const ratio = ratioFromPercent(record.percent);
180
+ const status = asText(record.status);
181
+ return buildWindow(id, used, limit, resetAtMs, ratio, status);
182
+ }
183
+
184
+ /**
185
+ * The flat shape's rolling/weekly/monthly columns. The synthetic window id is
186
+ * supplied because the flat payload has no per-window name. Reset columns are
187
+ * not documented for this shape, so only a defensively-named absolute one is
188
+ * read; the `time*Updated` columns are "last updated", not "resets", and are
189
+ * deliberately ignored.
190
+ */
191
+ function normalizeFlatWindow(
192
+ top: Record<string, unknown>,
193
+ id: GoWindow["id"],
194
+ usedKey: string,
195
+ limitKey: string,
196
+ prefix: string,
197
+ ): GoWindow | undefined {
198
+ const used = asFiniteNumber(top[usedKey]);
199
+ const limit = asFiniteNumber(top[limitKey]);
200
+ const resetAtMs = firstInstant(top[`${prefix}ResetAtMs`], top[`${prefix}ResetsAt`], top[`${prefix}ResetAt`]);
201
+ return buildWindow(id, used, limit, resetAtMs);
202
+ }
203
+
204
+ /** Collect windows out of a name-keyed map, e.g. `{ rolling: {...} }`. */
205
+ function collectKeyed(record: Record<string, unknown>, push: (window: GoWindow | undefined) => void): void {
206
+ for (const [key, value] of Object.entries(record)) {
207
+ const id = windowIdFrom(key);
208
+ if (id === undefined) continue;
209
+ push(normalizeWindowValue(value, id));
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Normalize untrusted Go usage output, or `undefined` when there is no usable
215
+ * data. Never throws: every field is coerced and everything unrecognized is
216
+ * dropped, so drift degrades to the placeholder instead of the render.
217
+ */
218
+ export function normalizeGoUsage(raw: unknown): GoUsage | undefined {
219
+ try {
220
+ const windows: GoWindow[] = [];
221
+ const seen = new Set<GoWindow["id"]>();
222
+ const push = (window: GoWindow | undefined): void => {
223
+ if (window === undefined || seen.has(window.id)) return;
224
+ seen.add(window.id);
225
+ windows.push(window);
226
+ };
227
+
228
+ if (Array.isArray(raw)) {
229
+ for (const entry of raw) push(normalizeWindowValue(entry));
230
+ } else {
231
+ const top = asRecord(raw);
232
+ if (top === undefined) return undefined;
233
+
234
+ push(normalizeFlatWindow(top, "5h", "rollingUsage", "rollingLimit", "rolling"));
235
+ push(normalizeFlatWindow(top, "1w", "weeklyUsage", "weeklyLimit", "weekly"));
236
+ push(normalizeFlatWindow(top, "1m", "monthlyUsage", "monthlyLimit", "monthly"));
237
+
238
+ const usage = asRecord(top.usage);
239
+ if (usage !== undefined) collectKeyed(usage, push);
240
+
241
+ const list = top.windows;
242
+ if (Array.isArray(list)) {
243
+ for (const entry of list) push(normalizeWindowValue(entry));
244
+ } else {
245
+ const keyed = asRecord(list);
246
+ if (keyed !== undefined) collectKeyed(keyed, push);
247
+ }
248
+
249
+ // A payload that is itself a single unnamed window object.
250
+ if (windows.length === 0) push(normalizeWindowValue(top));
251
+ }
252
+
253
+ if (windows.length === 0) return undefined;
254
+ windows.sort((a, b) => WINDOW_ORDER.indexOf(a.id) - WINDOW_ORDER.indexOf(b.id));
255
+ return { windows };
256
+ } catch {
257
+ return undefined;
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Fraction of a window's limit at which the row switches to its error tone.
263
+ *
264
+ * Chosen below 1 so the row warns while there is still headroom to act (an
265
+ * account-wide limit cannot be topped up mid-run), and above the 0.5 midpoint
266
+ * so ordinary use does not read as distress.
267
+ */
268
+ export const GO_ERROR_RATIO = 0.9;
269
+
270
+ /**
271
+ * The per-window status values treated as benign.
272
+ *
273
+ * NOTE: the semantics of `status` are UNVERIFIED — only `"ok"` has been observed
274
+ * live on `GET /zen/go/v1/usage`. An unknown non-empty status is deliberately
275
+ * NOT in this set, so it renders as offending: a quota window that is not
276
+ * reporting `ok` is worth a red dial rather than a silent pass.
277
+ */
278
+ export const GO_OK_STATUSES: readonly string[] = ["ok"];
279
+
280
+ /**
281
+ * The row tone: `error` at or above {@link GO_ERROR_RATIO}, or when a window
282
+ * carries a non-benign status, else `normal`.
283
+ */
284
+ export function goTone(window: GoWindow): "error" | "normal" {
285
+ if (window.ratio !== undefined && window.ratio >= GO_ERROR_RATIO) return "error";
286
+ const status = window.status;
287
+ if (status !== undefined && status !== "" && !GO_OK_STATUSES.includes(status)) return "error";
288
+ return "normal";
289
+ }
290
+
291
+ function formatRemaining(ms: number): string {
292
+ const seconds = Math.ceil(ms / 1000);
293
+ if (seconds < 60) return `${seconds}s`;
294
+ const minutes = Math.ceil(ms / 60_000);
295
+ if (minutes < 60) return `${minutes}m`;
296
+ const hours = Math.ceil(ms / 3_600_000);
297
+ if (hours < 24) return `${hours}h`;
298
+ return `${Math.ceil(ms / 86_400_000)}d`;
299
+ }
300
+
301
+ /**
302
+ * A short "time until reset" suffix for the error tone, or `undefined`.
303
+ *
304
+ * Only shown when the window is actually in error and the reset time is a
305
+ * known future instant — a reset hint beside a calm bar is noise, and one in
306
+ * the past would read as a promise already broken.
307
+ */
308
+ export function goResetSuffix(window: GoWindow, nowMs: number): string | undefined {
309
+ if (goTone(window) !== "error") return undefined;
310
+ const resetAtMs = window.resetAtMs;
311
+ if (resetAtMs === undefined || !Number.isFinite(resetAtMs) || !Number.isFinite(nowMs)) return undefined;
312
+ const remaining = resetAtMs - nowMs;
313
+ if (remaining <= 0) return undefined;
314
+ return ` · ${formatRemaining(remaining)}`;
315
+ }
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
@@ -46,6 +46,12 @@ export interface StatSource {
46
46
  readonly frame?: unknown;
47
47
  /** Harness status from oc-harness-guard's RPC, via the guard bridge. Untrusted. */
48
48
  readonly guard?: unknown;
49
+ /**
50
+ * Zen Go account usage, read from the go bridge's host store. Untrusted on
51
+ * principle: the row re-validates the window shape rather than trusting the
52
+ * type across the module boundary.
53
+ */
54
+ readonly go?: unknown;
49
55
  }
50
56
 
51
57
  /** Fields a user may name in `sidebar.rows`, in the order they are documented. */
@@ -68,6 +74,7 @@ export const STAT_FIELDS = [
68
74
  "reasoning",
69
75
  "turns",
70
76
  "guard",
77
+ "go",
71
78
  ] as const;
72
79
 
73
80
  type StatField = (typeof STAT_FIELDS)[number];
@@ -122,6 +129,14 @@ export interface LayoutHint {
122
129
  readonly persist?: boolean;
123
130
  /** Value shown for a row with no data when `persist` is on. Default `"—"`. */
124
131
  readonly placeholder?: string;
132
+ /**
133
+ * The clock the `go` row reads its relative reset hint against.
134
+ *
135
+ * An explicit instant rather than a hidden `Date.now()` inside the renderer,
136
+ * so a flagged window's "resets in 41m" is a pure function of its inputs and
137
+ * the row stays testable without freezing time. Absent means `Date.now()`.
138
+ */
139
+ readonly nowMs?: number;
125
140
  }
126
141
 
127
142
  /** Placeholder value for a persistent row with no data yet. */
package/src/tui/stats.ts CHANGED
@@ -11,7 +11,8 @@
11
11
  // public surface it has always had.
12
12
 
13
13
  export { clip, formatCost, formatCount, formatDuration, fuelBar, sparkline } from "./format.js";
14
- export { statLine, statRows } from "./rows.js";
14
+ export { statLine, statRows, statSegments } from "./rows.js";
15
+ export type { StatSegment } from "./rows.js";
15
16
  export { ANIMATED_FIELDS, DEFAULT_PLACEHOLDER, STAT_FIELDS, isStatField } from "./stat-fields.js";
16
17
  export type { StatSource } from "./stat-fields.js";
17
18
  export {