oc-flight-deck 0.6.7 → 0.8.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/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, type RailLine } 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";
@@ -59,6 +60,34 @@ export default Plugin.define({
59
60
  const footer = footerLine(config);
60
61
  const releases: Array<() => void> = [];
61
62
 
63
+ // One themed line, in the exact form the sidebar draws: the line resolves
64
+ // its own look from `config.style` (fixed lines use `style.lines`, every
65
+ // live row its own entry or the wildcard), and `themeColor`/`attributeMask`
66
+ // are the only things that know how a role or an attribute name becomes
67
+ // renderer state — they hand back plain props here, never escapes.
68
+ //
69
+ // `?? 0` keeps a line with no attributes on the renderer's own default
70
+ // instead of assigning `undefined` over it, so the shipped config draws
71
+ // exactly what it always drew. Shared with the sidebar footer slot so both
72
+ // rails stay one styling path.
73
+ const themedLine = (line: RailLine) => {
74
+ const style = railLineStyle(config.style, line);
75
+ const lineFg = themeColor(style.color, context.theme) as string | undefined;
76
+ // The span mapping — which run inherits the line's colour and which
77
+ // takes its own tone — lives in a pure helper, so the "only the flagged
78
+ // window is red" decision is tested directly. All this renderer does is
79
+ // resolve each role to a theme colour and pass `fg`, never ANSI.
80
+ return (
81
+ <text fg={lineFg} attributes={attributeMask(style.attributes) ?? 0}>
82
+ {railLineSpans(line, style).map((span) => (
83
+ <span style={{ fg: themeColor(span.color, context.theme) as string | undefined }}>
84
+ {span.text}
85
+ </span>
86
+ ))}
87
+ </text>
88
+ );
89
+ };
90
+
62
91
  // Bound a bankable window to a few ticks: `min(60s, max(5s, 4 * refreshMs))`,
63
92
  // so a suspended process or a sparse-event gap cannot be billed as work.
64
93
  const maxBankedMs = Math.min(60_000, Math.max(5_000, 4 * config.refresh));
@@ -126,6 +155,12 @@ export default Plugin.define({
126
155
  const wantGuard = config.sidebar.enabled && config.sidebar.rows.includes("guard");
127
156
  const bridge = wantGuard ? startGuardBridge(context) : undefined;
128
157
 
158
+ // The go row is opt-in the same way: a row nobody drew should cost no timer
159
+ // and no request. The bridge is account-wide (one key, one quota), so it
160
+ // starts here and has no session to follow — unlike guard.
161
+ const wantGo = config.sidebar.enabled && config.sidebar.rows.includes("go");
162
+ const goBridge = wantGo ? startGoBridge(context) : undefined;
163
+
129
164
  // Read session state inside the render so the rail stays live: cost and
130
165
  // tokens climb as the session runs, and the branch appears once VCS
131
166
  // resolves. Nothing here writes, requests, or leaves the process.
@@ -184,6 +219,9 @@ export default Plugin.define({
184
219
  elapsedMs: wants("elapsed") ? sessionElapsed(sessionID) : undefined,
185
220
  turns,
186
221
  guard: bridge?.status,
222
+ // Read the go store inside the render too, so a poll re-runs the rail
223
+ // exactly as the guard read does.
224
+ go: goBridge?.usage,
187
225
  // Read the tick inside the render so the host registers a dependency on
188
226
  // it; that read is what makes the rail re-run on the ticker's schedule.
189
227
  frame: ticker?.frame ?? 0,
@@ -239,6 +277,7 @@ export default Plugin.define({
239
277
  bridge?.follow(sessionID);
240
278
  void ticker?.frame;
241
279
  void bridge?.status;
280
+ void goBridge?.usage;
242
281
 
243
282
  const source = snapshot(sessionID);
244
283
  const lines = railLines(config, source);
@@ -247,28 +286,8 @@ export default Plugin.define({
247
286
  return (
248
287
  // No padding here: the host already lays out and pads the sidebar,
249
288
  // so adding our own would push the rows out of alignment with it.
250
- //
251
- // Each line resolves its own look from `config.style`: the fixed
252
- // lines use `style.lines`, and every live row its own entry or the
253
- // wildcard. `themeColor`/`attributeMask` are the only things that
254
- // know how a role or an attribute name becomes renderer state, and
255
- // they hand back plain props here — never escapes.
256
- //
257
- // `?? 0` keeps a line with no attributes on the renderer's own
258
- // default instead of assigning `undefined` over it, so the shipped
259
- // config draws exactly what it always drew.
260
289
  <box flexDirection="column">
261
- {lines.map((line) => {
262
- const style = railLineStyle(config.style, line);
263
- return (
264
- <text
265
- fg={themeColor(style.color, context.theme) as string | undefined}
266
- attributes={attributeMask(style.attributes) ?? 0}
267
- >
268
- {line.text}
269
- </text>
270
- );
271
- })}
290
+ {lines.map(themedLine)}
272
291
  </box>
273
292
  );
274
293
  },
@@ -276,11 +295,30 @@ export default Plugin.define({
276
295
  );
277
296
  }
278
297
 
298
+ if (config.sidebar.enabled && config.sidebar.footer.lines.length > 0) {
299
+ releases.push(
300
+ context.ui.slot({
301
+ // The sidebar footer: a separate host slot below the rows. The
302
+ // branding pair ships here by default since 0.8.0; an explicitly
303
+ // empty `sidebar.footer.lines` from a config file skips this
304
+ // registration entirely. It draws outside the `maxLines` budget and
305
+ // stays when `sidebar.lines` is customized. The lines are fixed, so
306
+ // nothing here subscribes to the ticker or the session.
307
+ append: "sidebar.footer",
308
+ render: () => (
309
+ <box flexDirection="column">
310
+ {config.sidebar.footer.lines.map((text) => themedLine({ text }))}
311
+ </box>
312
+ ),
313
+ }),
314
+ );
315
+ }
316
+
279
317
  if (footer !== undefined) {
280
318
  releases.push(
281
319
  context.ui.slot({
282
320
  append: "prompt.footer.status",
283
- render: () => <text fg={context.theme.text.subdued}>{footer}</text>,
321
+ render: () => <text fg={themeColor("subdued", context.theme) as string | undefined}>{footer}</text>,
284
322
  }),
285
323
  );
286
324
  }
@@ -290,6 +328,7 @@ export default Plugin.define({
290
328
  watchTimer = undefined;
291
329
  ticker?.dispose();
292
330
  bridge?.dispose();
331
+ goBridge?.dispose();
293
332
  for (const release of releases) release();
294
333
  };
295
334
  },
@@ -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 {
package/src/tui/style.ts CHANGED
@@ -45,7 +45,7 @@ export interface LineStyle {
45
45
 
46
46
  /** The `style` config section, resolved. */
47
47
  export interface StyleConfig {
48
- /** The fixed branding/separator lines above the live rows. */
48
+ /** Fixed separator/branding lines rendered at the top of the rail. */
49
49
  readonly lines: LineStyle;
50
50
  readonly rows: {
51
51
  /** Every live row inherits this unless it has its own entry. */