oc-flight-deck 0.6.2 → 0.6.6

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.
@@ -1,34 +1,84 @@
1
- // Plain-string views of the Flight Deck rail.
2
- //
3
- // Keeping the text layer pure makes it trivial to test, and leaves the JSX in
4
- // index.tsx to do nothing but wrap these strings in themed <text> elements.
5
- // The live rows come from ./stats.ts and are read-only: nothing here mutates
6
- // session state, and nothing leaves the process.
7
-
8
- import type { FlightDeckConfig } from "./config.js";
9
- import { MAX_LINES } from "./config.js";
10
- import { statRows, type StatSource } from "./stats.js";
11
-
12
- /**
13
- * Sidebar lines to render, or an empty list when the sidebar rail is disabled.
14
- *
15
- * Configured `lines` render first (branding, separators, any fixed text), then
16
- * the live rows named by `sidebar.rows`. With `sidebar.persist` (the default)
17
- * every named row renders exactly once, using `sidebar.placeholder` when the
18
- * host has no data yet; with `persist: false` rows with no data are omitted.
19
- */
20
- export function sidebarLines(config: FlightDeckConfig, source: StatSource = {}): readonly string[] {
21
- if (!config.sidebar.enabled) return [];
22
- const layout = { ...config.layout, persist: config.sidebar.persist, placeholder: config.sidebar.placeholder };
23
- return [...config.sidebar.lines, ...statRows(config.sidebar.rows, source, layout)].slice(0, MAX_LINES);
24
- }
25
-
26
- /** Footer text to render, or `undefined` when the footer rail is disabled. */
27
- export function footerLine(config: FlightDeckConfig): string | undefined {
28
- return config.footer.enabled ? config.footer.text : undefined;
29
- }
30
-
31
- /** Index of the first live row, so the caller can theme branding apart from data. */
32
- export function liveRowOffset(config: FlightDeckConfig): number {
33
- return config.sidebar.enabled ? config.sidebar.lines.length : 0;
34
- }
1
+ // Plain-string and per-line views of the Flight Deck rail.
2
+ //
3
+ // Keeping the text layer pure makes it trivial to test, and leaves the JSX in
4
+ // index.tsx to do nothing but wrap these lines in themed <text> elements. The
5
+ // live rows come from ./stats.ts and are read-only: nothing here mutates
6
+ // session state, and nothing leaves the process.
7
+
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";
11
+
12
+ /**
13
+ * One line of the rail, before it is themed.
14
+ *
15
+ * `field` names the live row (`cost`, `tps`, ...) and is absent on the fixed
16
+ * branding lines. Carrying the name — rather than only "fixed or live" — is
17
+ * what lets the caller resolve the row's style, wildcard fallback included,
18
+ * without re-deriving which fields were drawn.
19
+ */
20
+ export interface RailLine {
21
+ readonly text: string;
22
+ /** The live row's field name; absent on a fixed line. */
23
+ readonly field?: string;
24
+ }
25
+
26
+ /**
27
+ * The rail's lines in render order: the fixed lines first, then the live rows
28
+ * named by `sidebar.rows`, together capped at `sidebar.maxLines`.
29
+ *
30
+ * With `sidebar.persist` (the default) every named row renders exactly once,
31
+ * using `sidebar.placeholder` when the host has no data yet; with
32
+ * `persist: false` rows with no data are omitted.
33
+ */
34
+ export function railLines(config: FlightDeckConfig, source: StatSource = {}): readonly RailLine[] {
35
+ if (!config.sidebar.enabled) return [];
36
+
37
+ // The display side of the config, which the row renderer reads alongside its
38
+ // geometry. `format` is a top-level section, so it is mapped here.
39
+ const layout = {
40
+ ...config.layout,
41
+ persist: config.sidebar.persist,
42
+ placeholder: config.sidebar.placeholder,
43
+ durationStyle: config.format.duration,
44
+ // Decided from the whole row list, the way `statRows` decides it: `cost`
45
+ // folds the subagent total into itself only when no `total` row was asked
46
+ // for, even if the cap later drops that row.
47
+ hasTotalRow: config.sidebar.rows.includes("total"),
48
+ };
49
+
50
+ const lines: RailLine[] = config.sidebar.lines.map((text) => ({ text }));
51
+ for (const field of config.sidebar.rows) {
52
+ // `statLine` is the half that knows the field's name; persistence stays in
53
+ // `statRows`, which turns a data-less known field into the placeholder.
54
+ // For a row that rendered, the fallback is never reached.
55
+ const text = statLine(field, source, layout) ?? statRows([field], source, layout)[0];
56
+ if (text !== undefined) lines.push({ field, text });
57
+ }
58
+
59
+ return lines.slice(0, config.sidebar.maxLines);
60
+ }
61
+
62
+ /** The rail's lines as plain strings, in render order. */
63
+ export function sidebarTextLines(config: FlightDeckConfig, source: StatSource = {}): readonly string[] {
64
+ return railLines(config, source).map((line) => line.text);
65
+ }
66
+
67
+ /**
68
+ * The pre-style-layer name for {@link sidebarTextLines}.
69
+ *
70
+ * Kept as an alias while callers migrate to the rail-line view: the string
71
+ * view is still the right one for tests and for anything that only wants the
72
+ * text.
73
+ */
74
+ export const sidebarLines = sidebarTextLines;
75
+
76
+ /** The resolved style for one line: fixed lines use `style.lines`, rows their own entry. */
77
+ export function railLineStyle(style: StyleConfig, line: RailLine): LineStyle {
78
+ return line.field === undefined ? style.lines : rowStyle(style, line.field);
79
+ }
80
+
81
+ /** Footer text to render, or `undefined` when the footer rail is disabled. */
82
+ export function footerLine(config: FlightDeckConfig): string | undefined {
83
+ return config.footer.enabled ? config.footer.text : undefined;
84
+ }
@@ -0,0 +1,49 @@
1
+ // Project spend: every session in THIS project, not just the one on screen.
2
+ //
3
+ // `session.list()` is not scoped - it returns sessions across every
4
+ // directory the host knows about, so summing it gives "everything you have
5
+ // ever run" while claiming to be a project total. Filtered by `projectID`
6
+ // rather than by directory, because one project legitimately spans several
7
+ // directories (worktrees).
8
+ //
9
+ // If the host does not report a project id, the unfiltered list is used, so
10
+ // this degrades to the old behaviour instead of showing nothing.
11
+ // `project` walks every session the host knows about, and that collection grows
12
+ // with your history rather than staying a handful. It moves slowly, so the walk
13
+ // is held briefly instead of repeated on every tick.
14
+
15
+ import type { Plugin } from "@opencode/plugin/tui";
16
+ import { asCount, asRecord, asText } from "./coerce.js";
17
+
18
+ export function createProjectTotals(context: Plugin.Context) {
19
+ const PROJECT_CACHE_MS = 5_000;
20
+ let projectCache:
21
+ | { readonly projectID: string | undefined; readonly at: number; readonly value: { cost: number; count: number } }
22
+ | undefined;
23
+
24
+ const projectTotals = (sessionID: string) => {
25
+ try {
26
+ const projectID = asText(asRecord(context.data.session.get(sessionID))?.["projectID"]);
27
+ const cached = projectCache;
28
+ if (cached !== undefined && cached.projectID === projectID && Date.now() - cached.at < PROJECT_CACHE_MS) {
29
+ return cached.value;
30
+ }
31
+
32
+ const sessions = context.data.session.list() ?? [];
33
+ const scoped =
34
+ projectID === undefined
35
+ ? sessions
36
+ : sessions.filter((entry) => asText(asRecord(entry)?.["projectID"]) === projectID);
37
+
38
+ let cost = 0;
39
+ for (const entry of scoped) cost += asCount(asRecord(entry)?.["cost"]) ?? 0;
40
+ const value = { cost, count: scoped.length };
41
+ projectCache = { projectID, at: Date.now(), value };
42
+ return value;
43
+ } catch {
44
+ return undefined;
45
+ }
46
+ };
47
+
48
+ return { projectTotals };
49
+ }
@@ -0,0 +1,281 @@
1
+ // Row rendering for the Flight Deck rail: one padded line per named field.
2
+ //
3
+ // `statLine` renders a single field or `undefined` when the host has not
4
+ // supplied it yet; `statRows` renders a list of fields and folds in the
5
+ // persistence behaviour. Every value passes through `plain`, so a control
6
+ // character in a host-supplied string cannot move the cursor. Pure, so the
7
+ // rendering is trivial to test.
8
+
9
+ import { DEFAULT_BAR_WIDTH, clip, formatCost, formatCount, formatDuration, fuelBar, sparkline } from "./format.js";
10
+ import { asCount, asRecord, asText } from "./coerce.js";
11
+ import { guardToken } from "./guard-tokens.js";
12
+ import {
13
+ DEFAULT_LABEL_WIDTH,
14
+ DEFAULT_PLACEHOLDER,
15
+ DEFAULT_SPARK_WIDTH,
16
+ isStatField,
17
+ type LayoutHint,
18
+ type StatSource,
19
+ } from "./stat-fields.js";
20
+
21
+ /** Braille frames, advanced by the ticker, shown only while the session runs. */
22
+ const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
23
+
24
+ /**
25
+ * Flatten control characters in anything about to be drawn.
26
+ *
27
+ * A rail is one line per row, so a newline or an escape sequence in a
28
+ * host-supplied string does not get seen — it moves the cursor. Config text is
29
+ * already flattened in ./config.ts, but a tool name, a permission resource or a
30
+ * branch name arrives straight from the host, so every row value passes through
31
+ * here on its way out. `replace` is unconditional rather than `test` + `replace`:
32
+ * a global regex used with `test` carries `lastIndex` between calls.
33
+ */
34
+ const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]/g;
35
+
36
+ function plain(value: string): string {
37
+ return value.replace(CONTROL_CHARS, " ");
38
+ }
39
+
40
+ /**
41
+ * One padded rail row: the label in its column, at least one space, then the
42
+ * flattened value. Shared by live rows and persistent placeholders so both
43
+ * keep the same column.
44
+ */
45
+ function formatRow(label: string, value: string, labelWidth: number): string {
46
+ return `${label.padEnd(labelWidth)}${label.length >= labelWidth ? " " : ""}${plain(value)}`;
47
+ }
48
+
49
+ /**
50
+ * Render one named field, or `undefined` when the host has not supplied it yet.
51
+ *
52
+ * Returning `undefined` rather than a placeholder is deliberate: a rail that
53
+ * shows `branch unknown` before the repo loads looks broken, while a rail
54
+ * that simply grows a row when the data arrives looks alive.
55
+ */
56
+ export function statLine(
57
+ field: string,
58
+ source: StatSource,
59
+ layout: LayoutHint = {},
60
+ ): string | undefined {
61
+ // Bound here rather than at module scope so a config file can change the
62
+ // column width without every call site having to know about it.
63
+ const labelWidth = layout.labelWidth ?? DEFAULT_LABEL_WIDTH;
64
+ const barWidth = layout.barWidth ?? DEFAULT_BAR_WIDTH;
65
+ const sparkWidth = layout.sparkWidth ?? DEFAULT_SPARK_WIDTH;
66
+ // At least one space, always.
67
+ //
68
+ // `padEnd` returns the label unchanged when it is already wider than the
69
+ // column, so a label longer than `labelWidth` was glued straight onto its
70
+ // value: at labelWidth 8 the `reasoning` row rendered as "reasoning153k".
71
+ // The label is nine characters, which made this reachable from a config file.
72
+ const row = (label: string, value: string): string => formatRow(label, value, labelWidth);
73
+
74
+ switch (field) {
75
+ case "caution": {
76
+ // Rendered only when the caller found something to say, which is what
77
+ // keeps a healthy session visually identical to one without the
78
+ // annunciator at all. The string already carries its glyph; nothing here
79
+ // knows or cares about severity.
80
+ const text = asText(source.caution);
81
+ return text === undefined ? undefined : row("caution", text);
82
+ }
83
+ case "status": {
84
+ const status = asText(source.status);
85
+ if (status === undefined && source.busy === undefined) return undefined;
86
+ // The spinner lives here rather than in a row of its own: an animated
87
+ // glyph beside "running" says the same thing without spending a line.
88
+ //
89
+ // `busy` folds in work the session's own status misses — a subagent
90
+ // running in its own session, or a shell command still going — so the
91
+ // glyph only stops when there is genuinely nothing happening. A host that
92
+ // does not report it falls back to the session's own status.
93
+ if (source.busy !== true && status !== "running") return row("status", "○ idle");
94
+ // Floored at the boundary: a fractional frame would index the frame list
95
+ // with a non-integer and render `undefined`.
96
+ const frame = Math.floor(asCount(source.frame) ?? 0);
97
+ return row("status", `${SPINNER[frame % SPINNER.length]} running`);
98
+ }
99
+ case "agent": {
100
+ const agent = asText(source.agent);
101
+ return agent === undefined ? undefined : row("agent", agent);
102
+ }
103
+ case "model": {
104
+ const model = asRecord(source.model);
105
+ const id = asText(model?.id);
106
+ if (id === undefined) return undefined;
107
+ const variant = asText(model?.variant);
108
+ return row("model", variant === undefined ? id : `${id} · ${variant}`);
109
+ }
110
+ case "branch": {
111
+ const branch = asText(source.branch);
112
+ return branch === undefined ? undefined : row("branch", branch);
113
+ }
114
+ case "cost": {
115
+ const cost = asCount(source.cost);
116
+ const tree = asRecord(source.tree);
117
+ const treeCost = asCount(tree?.cost);
118
+ const count = asCount(tree?.count);
119
+ const family = count !== undefined && count > 0 ? count : 0;
120
+
121
+ // Merge only when subagents actually ran, and only when the rail is not
122
+ // already showing a `total` row. Two rows holding a number and its own
123
+ // superset was the thing worth fixing; a setting to choose between them
124
+ // would just be that duplication with extra steps.
125
+ const merge =
126
+ layout.hasTotalRow !== true &&
127
+ cost !== undefined &&
128
+ treeCost !== undefined &&
129
+ family > 0 &&
130
+ treeCost > cost;
131
+
132
+ if (!merge) {
133
+ const value = layout.hasTotalRow === true ? (cost ?? treeCost) : (treeCost ?? cost);
134
+ return value === undefined ? undefined : row("cost", formatCost(value));
135
+ }
136
+
137
+ // The delta (`+$0.020`) used to be here and pushed the row to 40 columns,
138
+ // wide enough to wrap in a normal sidebar. It was real information that
139
+ // did not earn its width: the count already explains why the figure is
140
+ // higher, and this form is the same width as the old `total` row.
141
+ const plural = family === 1 ? "subagent" : "subagents";
142
+ return row("cost", `${formatCost(treeCost as number)} · ${family} ${plural}`);
143
+ }
144
+ case "total": {
145
+ // Only worth a row once a subagent has actually run: subagent sessions are
146
+ // separate, so the parent's `cost` alone understates what was spent.
147
+ const tree = asRecord(source.tree);
148
+ const count = asCount(tree?.count);
149
+ const cost = asCount(tree?.cost);
150
+ if (cost === undefined || count === undefined || count === 0) return undefined;
151
+ const plural = count === 1 ? "subagent" : "subagents";
152
+ return row("total", `${formatCost(cost)} · ${count} ${plural}`);
153
+ }
154
+ case "project": {
155
+ const project = asRecord(source.project);
156
+ const cost = asCount(project?.cost);
157
+ if (cost === undefined) return undefined;
158
+ const count = asCount(project?.count);
159
+ return row("project", `${formatCost(cost)}${count !== undefined && count > 1 ? ` · ${count} sessions` : ""}`);
160
+ }
161
+ case "tokens": {
162
+ const tokens = asRecord(source.tokens);
163
+ const input = asCount(tokens?.input);
164
+ const output = asCount(tokens?.output);
165
+ if (input === undefined && output === undefined) return undefined;
166
+ return row("tokens", `${formatCount(input ?? 0)} in · ${formatCount(output ?? 0)} out`);
167
+ }
168
+ case "cache": {
169
+ const tokens = asRecord(source.tokens);
170
+ const cache = asRecord(tokens?.cache);
171
+ const read = asCount(cache?.read);
172
+ if (read === undefined || read === 0) return undefined;
173
+ const input = asCount(tokens?.input);
174
+ // Hit ratio is the whole point: it explains a cheap bill on a huge token
175
+ // count, and it is the first thing to break when caching stops working.
176
+ const total = input === undefined ? undefined : read + input;
177
+ const value =
178
+ total === undefined || total === 0
179
+ ? `${formatCount(read)} read`
180
+ : `${Math.round((read / total) * 100)}% hit · ${formatCount(read)} read`;
181
+ return row("cache", value);
182
+ }
183
+ case "context": {
184
+ const context = asRecord(source.context);
185
+ const used = asCount(context?.used);
186
+ if (used === undefined || used === 0) return undefined;
187
+ const limit = asCount(context?.limit);
188
+ if (limit === undefined || limit === 0) return row("context", `${formatCount(used)} used`);
189
+ const ratio = used / limit;
190
+ // Show the percentage whenever the host reports it, but never a bar that
191
+ // reads as more than full.
192
+ return row("context", `${fuelBar(ratio, barWidth)} ${Math.round(Math.min(1, ratio) * 100)}%`);
193
+ }
194
+ case "perms": {
195
+ const perms = asRecord(source.perms);
196
+ const count = asCount(perms?.["count"]);
197
+ if (count === undefined || count === 0) return undefined;
198
+ const action = asText(perms?.["action"]);
199
+ const resource = asText(perms?.["resource"]);
200
+
201
+ // One request: name it, because that is the decision you are being asked
202
+ // to make. Several: the count leads, because the first request in the
203
+ // queue is not necessarily the one you are about to be shown.
204
+ if (count > 1) {
205
+ return row("perms", action === undefined ? `${count} waiting` : `${count} waiting · ${action}`);
206
+ }
207
+ if (action === undefined) return row("perms", "1 waiting");
208
+ // Clipped hard: a row that wraps costs the reader more than a row that
209
+ // shortens a path, and there is no way to ask the host how wide it is.
210
+ return row("perms", resource === undefined ? action : `${action} · ${clip(resource, 18)}`);
211
+ }
212
+ case "elapsed": {
213
+ const ms = asCount(source.elapsedMs);
214
+ if (ms === undefined || ms <= 0) return undefined;
215
+ return row("elapsed", formatDuration(ms, layout.durationStyle));
216
+ }
217
+ case "tps": {
218
+ const tps = asCount(source.tps);
219
+ if (tps === undefined || tps === 0) return undefined;
220
+ return row("tps", `${Math.round(tps)} tok/s`);
221
+ }
222
+ case "spark": {
223
+ const values = Array.isArray(source.spark) ? source.spark.map((value) => asCount(value) ?? 0) : [];
224
+ // The newest samples are the interesting ones, so a narrowed window keeps
225
+ // the recent shape rather than the oldest.
226
+ const windowed = values.slice(-Math.max(2, Math.floor(sparkWidth)));
227
+ if (windowed.length < 2) return undefined;
228
+ return row("spark", sparkline(windowed));
229
+ }
230
+ case "reasoning": {
231
+ const reasoning = asCount(asRecord(source.tokens)?.reasoning);
232
+ if (reasoning === undefined || reasoning === 0) return undefined;
233
+ return row("reasoning", formatCount(reasoning));
234
+ }
235
+ case "turns": {
236
+ const turns = asCount(source.turns);
237
+ if (turns === undefined || turns === 0) return undefined;
238
+ return row("turns", String(turns));
239
+ }
240
+ case "guard": {
241
+ const token = guardToken(source.guard);
242
+ return token === undefined ? undefined : row("guard", token);
243
+ }
244
+ default:
245
+ return undefined;
246
+ }
247
+ }
248
+
249
+ /** Render every named field, in the given order.
250
+ *
251
+ * By default only fields with data render; with `layout.persist` every known
252
+ * field renders exactly one row, using `layout.placeholder` (default `"—"`)
253
+ * for the value when the host has nothing to show yet. `statLine` keeps
254
+ * returning `string | undefined` — persistence lives here, not there.
255
+ */
256
+ export function statRows(
257
+ fields: readonly string[],
258
+ source: StatSource,
259
+ layout: LayoutHint = {},
260
+ ): readonly string[] {
261
+ // The rows list decides whether `cost` merges the subagent total into itself.
262
+ // Passing that down means the choice lives in `sidebar.rows`, where someone
263
+ // is already deciding what the rail shows.
264
+ const hint: LayoutHint = { ...layout, hasTotalRow: fields.includes("total") };
265
+ const persist = hint.persist === true;
266
+ const placeholder = hint.placeholder ?? DEFAULT_PLACEHOLDER;
267
+ const labelWidth = hint.labelWidth ?? DEFAULT_LABEL_WIDTH;
268
+ const rows: string[] = [];
269
+ for (const field of fields) {
270
+ const line = statLine(field, source, hint);
271
+ if (line !== undefined) {
272
+ rows.push(line);
273
+ continue;
274
+ }
275
+ // Unknown names stay skipped even when persistent: a typo must stay a
276
+ // reported-and-skipped row, not a placeholder that looks intentional.
277
+ if (!persist || !isStatField(field)) continue;
278
+ rows.push(formatRow(field, placeholder, labelWidth));
279
+ }
280
+ return rows;
281
+ }