oc-flight-deck 0.11.0 → 0.19.1

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.
@@ -0,0 +1,637 @@
1
+ // The live Go usage panel for the sidebar footer slot.
2
+ //
3
+ // A designed instrument, not a data dump: three fixed lines - rolling (5h),
4
+ // weekly (1w), monthly (1m) - plus an opt-in dim header naming the plan. Each
5
+ // line is a strict fixed-width column layout - a breathing mark, a
6
+ // left-aligned label, a thin-rule meter, a percent cell and a reset
7
+ // countdown cell - separated by single spaces, so all three
8
+ // rows share one axis and the bar's start and end never wander between rows.
9
+ // The two trailing cells keep their widths; `align` moves each value inside
10
+ // its own cell, defaulting to the right edge.
11
+ //
12
+ // Pure, like ./go-usage.js: the clock arrives as `nowMs`, the animation phase
13
+ // as `frame`, and the usage and its no-data reason as values, so the panel is
14
+ // a function of its inputs and testable without a server, a store, or a
15
+ // frozen clock. There is no I/O, no timer and no hidden `Date.now()`.
16
+ // `layout` is `unknown` on principle - it crosses the config boundary - so
17
+ // its look is re-read defensively instead of trusted.
18
+ //
19
+ // Every glyph is written as a `\uXXXX` escape or a `String.fromCharCode`
20
+ // so this source stays ASCII whatever the write path does with it: U+25C8 is
21
+ // the header diamond, U+2500 is the meter's single cell - fill and track
22
+ // alike, told apart by tone alone so the bar's right edge can never drift
23
+ // row to row the way two different advance widths would - and
24
+ // U+25CB/U+25CE/U+25CF are the breathing mark's rest/swell/live rings. The
25
+ // bar is capped so the longest line stays within the ~40-column sidebar and
26
+ // can never overflow or wrap.
27
+
28
+ import { asCount, asRecord } from "./coerce.js";
29
+ import { goTone, type GoUsage, type GoWindow } from "./go-usage.js";
30
+ import type { RailLine } from "./presentation.js";
31
+ import type { StatSegment } from "./rows.js";
32
+ import { DEFAULT_PLACEHOLDER } from "./stat-fields.js";
33
+ import type { StyleColor } from "./style.js";
34
+
35
+ /** The panel's three windows, in canonical 5h -> 1w -> 1m order. Labels live in the look. */
36
+ const PANEL_WINDOWS: readonly GoWindow["id"][] = ["5h", "1w", "1m"];
37
+
38
+ /** Default labels by wire name: lowercase signature look. */
39
+ export const PANEL_DEFAULT_LABELS = {
40
+ rolling: "rolling",
41
+ weekly: "weekly",
42
+ monthly: "monthly",
43
+ } as const;
44
+
45
+ /** One label per window id. */
46
+ export interface GoPanelLabels {
47
+ readonly rolling: string;
48
+ readonly weekly: string;
49
+ readonly monthly: string;
50
+ }
51
+
52
+ function labelKeyFor(id: GoWindow["id"]): keyof GoPanelLabels {
53
+ if (id === "5h") return "rolling";
54
+ if (id === "1w") return "weekly";
55
+ return "monthly";
56
+ }
57
+
58
+ /** U+25C8 BLACK DIAMOND CONTAINING WHITE SMALL DIAMOND: the header mark. */
59
+ const HEADER_GLYPH = "\u25C8";
60
+ /** U+25CB WHITE CIRCLE, U+25CE BULLSEYE, U+25CF BLACK CIRCLE: the breathing mark. */
61
+ const MARK_REST = String.fromCharCode(0x25cb);
62
+ const MARK_MID = String.fromCharCode(0x25ce);
63
+ const MARK_LIVE = String.fromCharCode(0x25cf);
64
+ /** One slow breath: rest -> swell -> live -> swell, stepping once per `blinkMs`. */
65
+ const MARK_FRAMES: readonly string[] = [MARK_REST, MARK_MID, MARK_LIVE, MARK_MID];
66
+ /** Cells the mark column occupies: the glyph plus one space. */
67
+ const MARK_WIDTH = 2;
68
+ /**
69
+ * U+2500 BOX DRAWINGS LIGHT HORIZONTAL: the panel's one and only meter cell.
70
+ *
71
+ * Fill and track are the SAME glyph - the fill draws bright (the window's
72
+ * tone, or the theme's primary text when calm) and the track draws dim
73
+ * (`subdued`), so the two never differ in advance width and every row's right
74
+ * edge lands on the same pixel. The light line is the panel's existing
75
+ * aesthetic; the contrast that the heavy fill used to carry now lives in the
76
+ * tone alone.
77
+ */
78
+ const CELL = "\u2500";
79
+ /**
80
+ * The sweep highlight's tone: the travelling cell over the fill.
81
+ *
82
+ * `default` would vanish into a calm fill - the calm fill IS the theme's
83
+ * primary text - so the highlight is the neutral `info` tint instead, which
84
+ * stays visible over a bright, warning, or error fill alike.
85
+ */
86
+ const SWEEP_TONE: StyleColor = "info";
87
+
88
+ /**
89
+ * Fraction of a window at which the panel switches to the warning role.
90
+ *
91
+ * Between the error threshold (./go-usage.js's `GO_ERROR_RATIO`, 0.9) and the
92
+ * midpoint: it warns while there is still headroom to act, without colouring
93
+ * ordinary use. The error decision stays `goTone`'s, so the panel and the row
94
+ * can never disagree about what "in trouble" means.
95
+ */
96
+ export const GO_WARNING_RATIO = 0.6;
97
+
98
+ /** Bar width when the caller supplies no readable `layout.barWidth`. */
99
+ export const PANEL_DEFAULT_BAR_WIDTH = 10;
100
+ /** Label width when the caller supplies no readable `layout.labelWidth`. */
101
+ export const PANEL_DEFAULT_LABEL_WIDTH = 6;
102
+ /** Whether the breathing mark draws when the caller says nothing. */
103
+ export const PANEL_DEFAULT_BLINK = true;
104
+ /** Milliseconds per breath step when the caller supplies no readable `layout.blinkMs`. */
105
+ export const PANEL_DEFAULT_BLINK_MS = 700;
106
+ /** Slowest breath the panel honours; slower would read as stuck. */
107
+ const PANEL_MIN_BLINK_MS = 200;
108
+ /** Fastest breath the panel honours; faster would read as flicker. */
109
+ const PANEL_MAX_BLINK_MS = 5000;
110
+ /** Longest rename the panel honours per label; longer would eat the sidebar. */
111
+ const PANEL_MAX_LABEL_LENGTH = 24;
112
+ /** Whether the header draws when the caller says nothing. */
113
+ export const PANEL_DEFAULT_HEADER = false;
114
+ /** Whether the percent column draws when the caller says nothing. */
115
+ export const PANEL_DEFAULT_PERCENT = true;
116
+ /** Whether the reset column draws when the caller says nothing. */
117
+ export const PANEL_DEFAULT_RESET = true;
118
+ /**
119
+ * Where a trailing value sits inside its fixed-width cell when the caller
120
+ * says nothing: pinned to the cell's right edge.
121
+ */
122
+ export const PANEL_DEFAULT_ALIGN = "right" as const;
123
+ /**
124
+ * Whether the sweep may move when the caller says nothing.
125
+ *
126
+ * Off: the meter is static and changes only when the percentage itself
127
+ * changes. Opt in with `sweep: true` for the travelling highlight.
128
+ */
129
+ export const PANEL_DEFAULT_SWEEP = false;
130
+ /** Width of the right-aligned percent column: `100%` is the widest value. */
131
+ export const PANEL_PERCENT_WIDTH = 4;
132
+ /** Width of the right-aligned reset column: `30d21h` is the widest usual value. */
133
+ export const PANEL_RESET_WIDTH = 6;
134
+ /** The sidebar width budget: no line may draw past it. */
135
+ export const PANEL_SIDEBAR_BUDGET = 40;
136
+ /** Narrowest label column the panel honours; shorter would misalign the grid. */
137
+ const PANEL_MIN_LABEL_WIDTH = 5;
138
+ /** Widest label column the panel honours; wider would eat the sidebar. */
139
+ const PANEL_MAX_LABEL_WIDTH = 24;
140
+ /** Widest bar the config may name before the sidebar cap applies. */
141
+ const PANEL_MAX_NAMED_BAR_WIDTH = 40;
142
+
143
+ /** The panel's look, re-read from an untrusted hint. */
144
+ interface PanelLook {
145
+ readonly header: boolean;
146
+ readonly barWidth: number;
147
+ readonly labelWidth: number;
148
+ readonly showPercent: boolean;
149
+ readonly showReset: boolean;
150
+ readonly align: "left" | "right" | "center";
151
+ readonly sweep: boolean;
152
+ readonly labels: GoPanelLabels;
153
+ readonly blink: boolean;
154
+ readonly blinkMs: number;
155
+ }
156
+
157
+ function readLookFlag(value: unknown, fallback: boolean): boolean {
158
+ return typeof value === "boolean" ? value : fallback;
159
+ }
160
+
161
+ /**
162
+ * One trailing value inside its fixed-width cell.
163
+ *
164
+ * The width never moves - only the value does. `right` pins it to the cell's
165
+ * right edge so digits stay put as values change length; `left` hugs the bar
166
+ * with the padding trailing; `center` splits the padding, the odd cell going
167
+ * right. A value already at or past the width is returned as-is.
168
+ */
169
+ function alignCell(value: string, width: number, align: PanelLook["align"]): string {
170
+ if (value.length >= width) return value;
171
+ const padding = width - value.length;
172
+ if (align === "left") return value + " ".repeat(padding);
173
+ if (align === "center") {
174
+ const left = Math.floor(padding / 2);
175
+ return " ".repeat(left) + value + " ".repeat(padding - left);
176
+ }
177
+ return " ".repeat(padding) + value;
178
+ }
179
+
180
+ /**
181
+ * One label column: the label left-aligned to the common width.
182
+ *
183
+ * The single space AFTER it is the column separator, so every row's meter
184
+ * starts on the same axis regardless of label length.
185
+ */
186
+ function labelField(label: string, labelWidth: number): string {
187
+ return label.padEnd(labelWidth);
188
+ }
189
+
190
+ /**
191
+ * One rename, re-read from an untrusted hint.
192
+ *
193
+ * A non-string, an empty string, or a rename longer than the widest label
194
+ * column falls back to the default: a rename must never overflow or wrap the
195
+ * sidebar, and the auto-widen below can only grow to what fits.
196
+ */
197
+ function readLabel(value: unknown, fallback: string): string {
198
+ if (typeof value !== "string") return fallback;
199
+ const text = value.trim();
200
+ if (text.length === 0 || text.length > PANEL_MAX_LABEL_LENGTH) return fallback;
201
+ return text;
202
+ }
203
+
204
+ /** The three renames, each falling back per-key to its default. */
205
+ function readLabels(layout: unknown): GoPanelLabels {
206
+ const hint = asRecord(asRecord(layout)?.["labels"]) ?? {};
207
+ return {
208
+ rolling: readLabel(hint["rolling"], PANEL_DEFAULT_LABELS.rolling),
209
+ weekly: readLabel(hint["weekly"], PANEL_DEFAULT_LABELS.weekly),
210
+ monthly: readLabel(hint["monthly"], PANEL_DEFAULT_LABELS.monthly),
211
+ };
212
+ }
213
+
214
+ /**
215
+ * The breath step for one wall-clock instant: one ring per `blinkMs`,
216
+ * cycling rest -> swell -> live -> swell.
217
+ *
218
+ * Indexed from `nowMs`, never from the ticker frame, so the breath keeps its
219
+ * own cadence whatever the ticker's period is. A broken clock reads as the
220
+ * rest ring, never a throw.
221
+ */
222
+ function markIndex(nowMs: number, blinkMs: number): number {
223
+ if (!Number.isFinite(nowMs) || !Number.isFinite(blinkMs) || blinkMs <= 0) return 0;
224
+ const step = Math.floor(nowMs / blinkMs) % MARK_FRAMES.length;
225
+ return ((step % MARK_FRAMES.length) + MARK_FRAMES.length) % MARK_FRAMES.length;
226
+ }
227
+
228
+ /**
229
+ * The mark's tone at one breath step: dim at the rest ring, normal at the
230
+ * live dot, so the pulse reads in monochrome. The swell rings stay dim with
231
+ * the rest - only the live dot lights.
232
+ */
233
+ function markToneAt(index: number): StyleColor | undefined {
234
+ return index === 2 ? undefined : "subdued";
235
+ }
236
+
237
+ /**
238
+ * The panel's look, re-read from an untrusted hint.
239
+ *
240
+ * A missing, malformed, or out-of-range knob falls back to the panel's own
241
+ * default, and the bar is capped so the longest line - mark plus label plus
242
+ * meter plus the enabled columns - stays within the sidebar, so a bad
243
+ * `layout` can change the look but never break or wrap a line. The label
244
+ * column auto-widens past the configured width to hold the longest rendered
245
+ * rename, so a rename can never overflow its column.
246
+ */
247
+ function readLook(layout: unknown): PanelLook {
248
+ const hint = asRecord(layout) ?? {};
249
+ const header = readLookFlag(hint["header"], PANEL_DEFAULT_HEADER);
250
+ const showPercent = readLookFlag(hint["percent"], PANEL_DEFAULT_PERCENT);
251
+ const showReset = readLookFlag(hint["reset"], PANEL_DEFAULT_RESET);
252
+ const rawAlign = hint["align"];
253
+ const align: PanelLook["align"] =
254
+ rawAlign === "left" || rawAlign === "right" || rawAlign === "center" ? rawAlign : PANEL_DEFAULT_ALIGN;
255
+ const sweep = readLookFlag(hint["sweep"], PANEL_DEFAULT_SWEEP);
256
+ const rawLabel = hint["labelWidth"];
257
+ const flooredLabel = rawLabel === undefined ? undefined : Math.floor(asCount(rawLabel) ?? Number.NaN);
258
+ const configuredLabelWidth =
259
+ flooredLabel !== undefined &&
260
+ Number.isFinite(flooredLabel) &&
261
+ flooredLabel >= PANEL_MIN_LABEL_WIDTH &&
262
+ flooredLabel <= PANEL_MAX_LABEL_WIDTH
263
+ ? flooredLabel
264
+ : PANEL_DEFAULT_LABEL_WIDTH;
265
+ const labels = readLabels(layout);
266
+ // Auto-align: the column holds the longest rendered rename, never less
267
+ // than the configured width. A rename can widen the column but never
268
+ // overflow or wrap it.
269
+ const longestLabel = Math.max(labels.rolling.length, labels.weekly.length, labels.monthly.length);
270
+ const labelWidth = Math.max(configuredLabelWidth, longestLabel);
271
+ const blink = readLookFlag(hint["blink"], PANEL_DEFAULT_BLINK);
272
+ const rawBlinkMs = hint["blinkMs"];
273
+ const flooredBlinkMs = rawBlinkMs === undefined ? undefined : Math.floor(asCount(rawBlinkMs) ?? Number.NaN);
274
+ const blinkMs =
275
+ flooredBlinkMs !== undefined &&
276
+ Number.isFinite(flooredBlinkMs) &&
277
+ flooredBlinkMs >= PANEL_MIN_BLINK_MS &&
278
+ flooredBlinkMs <= PANEL_MAX_BLINK_MS
279
+ ? flooredBlinkMs
280
+ : PANEL_DEFAULT_BLINK_MS;
281
+ const rawBar = hint["barWidth"];
282
+ const flooredBar = rawBar === undefined ? undefined : Math.floor(asCount(rawBar) ?? Number.NaN);
283
+ const namedBar =
284
+ flooredBar !== undefined && Number.isFinite(flooredBar) && flooredBar >= 1
285
+ ? Math.min(flooredBar, PANEL_MAX_NAMED_BAR_WIDTH)
286
+ : PANEL_DEFAULT_BAR_WIDTH;
287
+ // Longest line is mark? + label + separator + bar + (separator + percent)? +
288
+ // (separator + reset)?: every separator is one space, and the mark column
289
+ // is two cells (the glyph plus one space) drawn only when blink is on.
290
+ const markWidth = blink ? MARK_WIDTH : 0;
291
+ const fixed =
292
+ markWidth + labelWidth + 1 + (showPercent ? 1 + PANEL_PERCENT_WIDTH : 0) + (showReset ? 1 + PANEL_RESET_WIDTH : 0);
293
+ const maxBar = Math.max(1, PANEL_SIDEBAR_BUDGET - fixed);
294
+ return { header, barWidth: Math.min(namedBar, maxBar), labelWidth, showPercent, showReset, align, sweep, labels, blink, blinkMs };
295
+ }
296
+
297
+ /**
298
+ * The usage's windows by id, re-validated at the boundary.
299
+ *
300
+ * The usage normally comes from the poll bridge, but it arrives through the
301
+ * host's memory store and may be a hand-built source in a test, so the shape
302
+ * is checked here rather than trusted from the declared type: an entry counts
303
+ * only when its id is one of the three windows. The ratio is clamped into
304
+ * `[0, 1]` as well as in ./rows.ts, so a source cannot fill a bar past full
305
+ * or print a percent above 100. A window with no readable ratio is kept - it
306
+ * draws an empty bar and the placeholder, which is the honest read of "no
307
+ * limit known" - and a bad entry is dropped rather than throwing.
308
+ */
309
+ function windowById(usage: GoUsage | undefined): Map<GoWindow["id"], GoWindow> {
310
+ const byId = new Map<GoWindow["id"], GoWindow>();
311
+ const list = asRecord(usage)?.["windows"];
312
+ if (!Array.isArray(list)) return byId;
313
+
314
+ for (const entry of list) {
315
+ const record = asRecord(entry);
316
+ if (record === undefined) continue;
317
+ const id = record["id"];
318
+ if (id !== "5h" && id !== "1w" && id !== "1m") continue;
319
+ // First one wins: the canonical order is decided here, not by the payload.
320
+ if (byId.has(id)) continue;
321
+
322
+ const window: {
323
+ -readonly [K in keyof GoWindow]: GoWindow[K];
324
+ } = { id };
325
+ const ratio = asCount(record["ratio"]);
326
+ if (ratio !== undefined) window.ratio = Math.min(1, ratio);
327
+ const resetAtMs = asCount(record["resetAtMs"]);
328
+ if (resetAtMs !== undefined) window.resetAtMs = resetAtMs;
329
+ const status = record["status"];
330
+ if (typeof status === "string" && status !== "") window.status = status;
331
+ byId.set(id, window);
332
+ }
333
+ return byId;
334
+ }
335
+
336
+ /**
337
+ * A duration as one or two compact units: `45s`, `12m`, `2h`, `4h44m`, `1d6h`,
338
+ * `30d23h`.
339
+ *
340
+ * Deliberately not ./go-usage.js's `formatRemaining`: that one is the one-line
341
+ * `go` row's hint and stays single-unit. The panel has the columns for the
342
+ * next unit down, and the next unit is what turns "4h" into something an agent
343
+ * can plan against. Seconds are dropped once hours are on the clock - two
344
+ * units is the whole budget - and a unit is omitted when it is zero, so an
345
+ * exact `2h` reads `2h` rather than `2h0m`.
346
+ *
347
+ * The sub-hour branches round up (as the row's hint does), so a countdown
348
+ * never understates the wait: 90s reads `2m`, not `1m30s`.
349
+ */
350
+ export function formatCompactRemaining(ms: number): string {
351
+ const totalSeconds = Math.ceil(ms / 1_000);
352
+ if (totalSeconds < 60) return `${totalSeconds}s`;
353
+ const totalMinutes = Math.ceil(ms / 60_000);
354
+ if (totalMinutes < 60) return `${totalMinutes}m`;
355
+ const totalHours = Math.floor(ms / 3_600_000);
356
+ if (totalHours < 24) {
357
+ // Just under the hour: `totalMinutes` is 60 and the hours place is empty,
358
+ // so name the minutes rather than print a hollow `0h59m`.
359
+ if (totalHours === 0) return `${totalMinutes}m`;
360
+ const minutes = Math.floor((ms - totalHours * 3_600_000) / 60_000);
361
+ return minutes > 0 ? `${totalHours}h${minutes}m` : `${totalHours}h`;
362
+ }
363
+ const totalDays = Math.floor(ms / 86_400_000);
364
+ const hours = Math.floor((ms - totalDays * 86_400_000) / 3_600_000);
365
+ return hours > 0 ? `${totalDays}d${hours}h` : `${totalDays}d`;
366
+ }
367
+
368
+ /**
369
+ * The reset countdown for one window, or `undefined` when the reset is unknown
370
+ * or already past.
371
+ *
372
+ * Just the compact time (`4h44m`): the column gap before it is the separator,
373
+ * so no dot is drawn. A past reset is omitted, since it would read as a
374
+ * promise already broken.
375
+ */
376
+ function resetCountdown(window: GoWindow, nowMs: number): string | undefined {
377
+ const resetAtMs = window.resetAtMs;
378
+ if (resetAtMs === undefined || !Number.isFinite(resetAtMs) || !Number.isFinite(nowMs)) return undefined;
379
+ const remaining = resetAtMs - nowMs;
380
+ if (remaining <= 0) return undefined;
381
+ return formatCompactRemaining(remaining);
382
+ }
383
+
384
+ /**
385
+ * The colour role a window's meter and percent draw in.
386
+ *
387
+ * `goTone` owns the error decision (>= 90% or a non-benign status), so the
388
+ * panel cannot disagree with the row; the warning band above
389
+ * {@link GO_WARNING_RATIO} is the panel's own, and everything below keeps the
390
+ * row's own colour (`undefined`, which the renderer inherits). The countdown
391
+ * stays dim regardless: it is relief, not severity.
392
+ */
393
+ function panelTone(window: GoWindow): StyleColor | undefined {
394
+ if (goTone(window) === "error") return "error";
395
+ const ratio = window.ratio;
396
+ if (ratio !== undefined && ratio >= GO_WARNING_RATIO) return "warning";
397
+ return undefined;
398
+ }
399
+
400
+ /**
401
+ * The frame the sweep reads, or `undefined` when there is no live animation.
402
+ *
403
+ * A missing, non-finite or negative frame means the ticker is not running, and
404
+ * the bar is drawn static: the sweep is motion, and inventing one from a
405
+ * broken phase would be a lie.
406
+ */
407
+ function readFrame(frame: unknown): number | undefined {
408
+ return typeof frame === "number" && Number.isFinite(frame) && frame >= 0 ? Math.floor(frame) : undefined;
409
+ }
410
+
411
+ /**
412
+ * The index of the bright cell within the filled region, or `-1` for no sweep.
413
+ *
414
+ * Sweeping only makes sense over a non-empty fill when the caller opted in, so
415
+ * a static panel (`sweep: false`, the default) or a 0% window is never given a
416
+ * bright cell. The modulo keeps the cell inside `[0, filled)` for any frame,
417
+ * including a frame the host advanced past the bar's width.
418
+ */
419
+ function sweepIndex(frame: number | undefined, filled: number, sweep: boolean): number {
420
+ if (!sweep || frame === undefined || filled <= 0) return -1;
421
+ return frame % filled;
422
+ }
423
+
424
+ /**
425
+ * Append one run to the line, merging it with the previous run when the colour
426
+ * role is the same. Merging is what keeps a uniform bar (or an all-error
427
+ * line) as one coloured span rather than one span per cell, so the renderer is
428
+ * handed a handful of runs, not `barWidth` of them.
429
+ */
430
+ function appendRun(runs: StatSegment[], text: string, tone: StyleColor | undefined): void {
431
+ if (text === "") return;
432
+ const last = runs[runs.length - 1];
433
+ if (last !== undefined && (last.tone ?? undefined) === tone) {
434
+ runs[runs.length - 1] = tone === undefined ? { text: last.text + text } : { text: last.text + text, tone };
435
+ return;
436
+ }
437
+ runs.push(tone === undefined ? { text } : { text, tone });
438
+ }
439
+
440
+ /**
441
+ * The reason tag, re-validated at the untrusted boundary.
442
+ *
443
+ * The reason comes from the bridge (or is the caller's `"no-bridge"`), so it
444
+ * is one of our own short tokens; anything else - a long string, whitespace,
445
+ * a control character - is dropped rather than rendered into the panel.
446
+ */
447
+ function readReason(reason: unknown): string | undefined {
448
+ return typeof reason === "string" && /^[a-z][a-z0-9-]{0,15}$/.test(reason) ? reason : undefined;
449
+ }
450
+
451
+ /**
452
+ * The dim header naming the plan: a small diamond plus the label.
453
+ *
454
+ * Drawn only when the caller opts in with `header: true`, above the three
455
+ * meters, in `subdued` so it frames the block without competing with a flagged
456
+ * meter. It carries the `go` field so the footer resolves the same row style
457
+ * the inline `go` row does.
458
+ */
459
+ function headerLine(): RailLine {
460
+ const text = ` ${HEADER_GLYPH} OPENCODE GO`;
461
+ return { field: "go", text, segments: [{ text, tone: "subdued" }] };
462
+ }
463
+
464
+ /**
465
+ * The mark column's cells for one row: the breathing glyph plus one space on
466
+ * the first meter line, two spaces on every other line so all three rows share
467
+ * one axis, and nothing at all when blink is off.
468
+ *
469
+ * The glyph steps rest -> swell -> live -> swell once per `blinkMs`, indexed
470
+ * from the wall clock (`nowMs`), so the breath is independent of the ticker
471
+ * period. Only this column breathes: the meter stays static and changes only
472
+ * when the percentage itself changes.
473
+ */
474
+ function markField(look: PanelLook, nowMs: number, isFirst: boolean): StatSegment | undefined {
475
+ if (!look.blink) return undefined;
476
+ if (!isFirst) return { text: " " };
477
+ const index = markIndex(nowMs, look.blinkMs);
478
+ const text = `${MARK_FRAMES[index] ?? MARK_REST} `;
479
+ const tone = markToneAt(index);
480
+ return tone === undefined ? { text } : { text, tone };
481
+ }
482
+
483
+ /**
484
+ * One resting line: the label, the empty track, and the placeholder - plus a
485
+ * dim reason tag when the caller knows why there is no data.
486
+ *
487
+ * Every column is fixed-width and separated by one space, so a resting line
488
+ * and a reading line share one grid. The tag sits IMMEDIATELY after the
489
+ * label's separator, before the track, and the track is shortened by the tag's
490
+ * width so the line never grows past the meter column and the tag can never be
491
+ * clipped off the sidebar's edge. The track is kept even with no data, so the
492
+ * panel's shape never jumps between "waiting" and "reading": the meter column
493
+ * is always there. Everything past the label is toned `subdued` explicitly so
494
+ * a resting line stays dim even when `style.rows.go` is set bright - none of
495
+ * it is a value.
496
+ */
497
+ function restingLine(
498
+ label: string,
499
+ look: PanelLook,
500
+ reason: string | undefined,
501
+ nowMs: number,
502
+ isFirst: boolean,
503
+ ): RailLine {
504
+ const cells = Math.max(1, Math.floor(look.barWidth));
505
+ const segments: StatSegment[] = [];
506
+ const mark = markField(look, nowMs, isFirst);
507
+ if (mark !== undefined) segments.push(mark);
508
+ segments.push({ text: `${labelField(label, look.labelWidth)} ` });
509
+ let trackCells = cells;
510
+ if (reason !== undefined) {
511
+ segments.push({ text: `${reason} `, tone: "subdued" });
512
+ trackCells = Math.max(0, cells - reason.length - 1);
513
+ }
514
+ const tail =
515
+ CELL.repeat(trackCells) +
516
+ (look.showPercent ? ` ${alignCell(DEFAULT_PLACEHOLDER, PANEL_PERCENT_WIDTH, look.align)}` : "");
517
+ segments.push({ text: tail, tone: "subdued" });
518
+ return { field: "go", text: segments.map((segment) => segment.text).join(""), segments };
519
+ }
520
+
521
+ /**
522
+ * One drawn line: the label, a single-glyph meter, the percent cell, and the
523
+ * dim countdown cell.
524
+ *
525
+ * Columns are fixed-width with one space between them: the label is
526
+ * left-aligned to `labelWidth`, the meter is exactly `barWidth` cells of
527
+ * `CELL` - the fill bright (the window's tone, or the theme's primary text
528
+ * when calm) over a `subdued` track - the percent is 4 wide and the reset 6,
529
+ * so the percent and the countdown sit on a shared axis on every row. `align`
530
+ * moves each trailing value inside its own cell without moving the axis.
531
+ * The meter carries one highlight cell (`info`, so it stays visible over a
532
+ * bright, warning, or error fill) sweeping across the filled region only when
533
+ * the caller opts in with `sweep: true` and supplies a live frame; by default
534
+ * the bar is static and changes only when the percentage itself changes. Only the meter and the
535
+ * percent can take the window's tone - the label keeps the line's own colour
536
+ * and the countdown stays dim, so a flagged window reads as this panel with a
537
+ * problem rather than as a different kind of line. A window whose ratio is
538
+ * unknown draws the placeholder for the number beside an empty meter: the
539
+ * percent is the precision, and inventing one from a count with no limit is
540
+ * exactly the confident guess the model refuses to make. Disabled columns are
541
+ * omitted entirely, never left as a gap.
542
+ */
543
+ function valueLine(
544
+ label: string,
545
+ look: PanelLook,
546
+ window: GoWindow,
547
+ nowMs: number,
548
+ frame: number | undefined,
549
+ isFirst: boolean,
550
+ ): RailLine {
551
+ const tone = panelTone(window);
552
+ const ratio = window.ratio;
553
+ const cells = Math.max(1, Math.floor(look.barWidth));
554
+ const filled = Math.max(0, Math.min(cells, Math.round((ratio ?? 0) * cells)));
555
+ const sweep = sweepIndex(frame, filled, look.sweep);
556
+ // Bright fill, dim track, one glyph throughout: the fill takes the window's
557
+ // tone - or the theme's primary text when calm - while the track stays
558
+ // `subdued`, so fill and track can never differ in advance width.
559
+ const fillTone: StyleColor | undefined = tone ?? "default";
560
+
561
+ const runs: StatSegment[] = [];
562
+ for (let index = 0; index < filled; index += 1) {
563
+ appendRun(runs, CELL, index === sweep ? SWEEP_TONE : fillTone);
564
+ }
565
+ for (let index = filled; index < cells; index += 1) {
566
+ appendRun(runs, CELL, "subdued");
567
+ }
568
+ if (look.showPercent) {
569
+ const percent = ratio === undefined ? DEFAULT_PLACEHOLDER : `${Math.round(ratio * 100)}%`;
570
+ // The percent joins the meter's trailing run so a uniform meter stays one
571
+ // span; the countdown is its own dim run (relief, not severity).
572
+ appendRun(runs, ` ${alignCell(percent, PANEL_PERCENT_WIDTH, look.align)}`, tone);
573
+ }
574
+
575
+ const segments: StatSegment[] = [];
576
+ const mark = markField(look, nowMs, isFirst);
577
+ if (mark !== undefined) segments.push(mark);
578
+ segments.push({ text: `${labelField(label, look.labelWidth)} ` }, ...runs);
579
+ if (look.showReset) {
580
+ const countdown = resetCountdown(window, nowMs);
581
+ if (countdown !== undefined) {
582
+ segments.push({ text: ` ${alignCell(countdown, PANEL_RESET_WIDTH, look.align)}`, tone: "subdued" });
583
+ }
584
+ }
585
+ return { field: "go", text: segments.map((segment) => segment.text).join(""), segments };
586
+ }
587
+
588
+ /**
589
+ * The footer's Go usage panel: exactly three {@link RailLine}s, rolling ->
590
+ * weekly -> monthly, ready for the host's themed renderer, plus the dim header
591
+ * only when the caller opts in with `header: true`.
592
+ *
593
+ * Never throws and never returns fewer than three lines - a panel that
594
+ * vanished or took the footer slot down with it would be worse than one that
595
+ * says nothing yet - so a missing, empty, or hostile usage payload degrades
596
+ * to the same three labels with the resting placeholder.
597
+ *
598
+ * `frame` is the host ticker's counter, passed in rather than read here so
599
+ * the panel stays pure; it moves a bright cell only when the look opts in
600
+ * with `sweep: true`, so by default the bar is static. The breathing mark is
601
+ * different: it steps from the wall clock (`nowMs`), so it breathes whether
602
+ * or not the ticker runs. `reason` names why there is no data (a ./go.js
603
+ * `GoNoDataReason`, or the caller's `"no-bridge"`) and is drawn once, on the
604
+ * first meter line, only when the whole panel is empty.
605
+ */
606
+ export function goPanelLines(
607
+ usage: GoUsage | undefined,
608
+ nowMs: number,
609
+ layout?: unknown,
610
+ frame?: number,
611
+ reason?: unknown,
612
+ ): readonly RailLine[] {
613
+ try {
614
+ const look = readLook(layout);
615
+ const windows = windowById(usage);
616
+ // The reason explains the whole panel, so it is only meaningful when no
617
+ // window rendered at all, and it is tagged once rather than three times.
618
+ const tag = windows.size === 0 ? readReason(reason) : undefined;
619
+ const sweepFrame = readFrame(frame);
620
+ const rows = PANEL_WINDOWS.map((id, index) => {
621
+ const label = look.labels[labelKeyFor(id)];
622
+ const window = windows.get(id);
623
+ return window === undefined
624
+ ? restingLine(label, look, index === 0 ? tag : undefined, nowMs, index === 0)
625
+ : valueLine(label, look, window, nowMs, sweepFrame, index === 0);
626
+ });
627
+ return look.header ? [headerLine(), ...rows] : rows;
628
+ } catch {
629
+ // Belt and braces: the body above is defensive, but a renderer must never
630
+ // be taken down by the panel, so any unexpected throw lands on the resting
631
+ // placeholder - the same three lines, with no values.
632
+ const fallback = readLook(undefined);
633
+ return PANEL_WINDOWS.map((id, index) =>
634
+ restingLine(fallback.labels[labelKeyFor(id)], fallback, undefined, nowMs, index === 0),
635
+ );
636
+ }
637
+ }
@@ -288,7 +288,14 @@ export function goTone(window: GoWindow): "error" | "normal" {
288
288
  return "normal";
289
289
  }
290
290
 
291
- function formatRemaining(ms: number): string {
291
+ /**
292
+ * A duration as one short unit: `45s`, `12m`, `2h`, `5d`.
293
+ *
294
+ * Exported because the footer's Go panel (./go-panel.ts) draws a countdown for
295
+ * every known future reset, while {@link goResetSuffix} draws one only under the
296
+ * error tone. Both must read the same way, so both read this.
297
+ */
298
+ export function formatRemaining(ms: number): string {
292
299
  const seconds = Math.ceil(ms / 1000);
293
300
  if (seconds < 60) return `${seconds}s`;
294
301
  const minutes = Math.ceil(ms / 60_000);