oc-flight-deck 0.4.0 → 0.6.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
@@ -1,515 +1,563 @@
1
- /** @jsxImportSource @opentui/solid */
2
- import { Plugin } from "@opencode/plugin/tui";
3
- import { cautionDetail, cautionText, detectCautions, worstCaution, type Caution } from "./caution.js";
4
- import { cautionThresholds, mergeOptions, resolveConfig } from "./config.js";
5
- import { loadConfigFile } from "./file-config.js";
6
- import { footerLine, liveRowOffset, sidebarLines } from "./presentation.js";
7
- import { ANIMATED_FIELDS, type StatSource } from "./stats.js";
8
- import { startGuardBridge } from "./guard.js";
9
- import { startTicker } from "./ticker.js";
10
-
11
- // Flight Deck is a read-only instrument panel for the OpenCode V2 CLI/TUI. It
12
- // shows the open session's agent, model, branch, cost, tokens, and cache hit
13
- // rate in the sidebar. It uses only the official CLI plugin boundary —
14
- // `@opencode/plugin/tui`, `context.ui.slot`, and theme tokens.
15
- //
16
- // Read-only but for one thing: the animation tick writes a single counter into
17
- // the host's ephemeral plugin-memory store. It has to, because a timer owned by
18
- // this plugin cannot wake the host's renderer — see ./ticker.ts for why. That
19
- // counter is in-process, scoped to this plugin, and gone when the TUI exits.
20
- // Everything the rail displays is state the host already holds in memory.
21
- //
22
- // Appearance comes from, in order of precedence:
23
- // 1. `context.options` — the host's plugin options, when the host forwards them
24
- // 2. `flight-deck.jsonc` (or `.opencode/flight-deck.jsonc`) in the project
25
- // 3. the sane defaults in ./config.ts
26
- // See flight-deck.example.jsonc for the commented template.
27
-
28
- /** How many trailing messages are inspected for tool parts. */
29
- const RECENT_MESSAGES = 4;
30
-
31
- type SessionLike = { cost?: unknown; model?: unknown; time?: unknown };
32
-
33
- function asCount(value: unknown): number | undefined {
34
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
35
- }
36
-
37
- function asText(value: unknown): string | undefined {
38
- if (typeof value !== "string") return undefined;
39
- const text = value.trim();
40
- return text.length === 0 ? undefined : text;
41
- }
42
-
43
- function asRecord(value: unknown): Record<string, unknown> | undefined {
44
- return typeof value === "object" && value !== null && !Array.isArray(value)
45
- ? (value as Record<string, unknown>)
46
- : undefined;
47
- }
48
-
49
- export default Plugin.define({
50
- id: "flight-deck-tui",
51
- setup(context) {
52
- const directory = context.location?.directory ?? process.cwd();
53
- const file = loadConfigFile(directory);
54
- const { config, issues } = resolveConfig(mergeOptions(file.options, context.options));
55
-
56
- if (file.issue !== undefined && file.source !== undefined) {
57
- console.warn(`[flight-deck] ${file.issue}`);
58
- }
59
- const problems = file.issue !== undefined ? [file.issue, ...issues] : issues;
60
- if (problems.length > 0) {
61
- const extra = problems.length > 1 ? ` (+${problems.length - 1} more)` : "";
62
- context.ui.toast.show({
63
- title: "Flight Deck",
64
- message: `Ignoring invalid config: ${problems[0]}${extra}`,
65
- variant: "warning",
66
- });
67
- }
68
-
69
- const footer = footerLine(config);
70
- const releases: Array<() => void> = [];
71
-
72
- // The host owns these caches; a failure to read one must never break the
73
- // rail, so every lookup degrades to "no data" instead of throwing.
74
- const messagesOf = (sessionID: string): readonly unknown[] => {
75
- try {
76
- return context.data.session.message.list(sessionID) ?? [];
77
- } catch {
78
- return [];
79
- }
80
- };
81
-
82
- // A subagent session is already inside its parent's family total, and the
83
- // host keys `family()` by the family ROOT — so asking from a child returns
84
- // its ancestors and siblings as well. Merging that would report the whole
85
- // tree as this conversation's own, under a label that promises the
86
- // conversation plus *its* subagents. Only a root has a family beneath it.
87
- const isFamilyRoot = (sessionID: string): boolean => {
88
- try {
89
- return context.data.session.root(sessionID) === sessionID;
90
- } catch {
91
- // A host without `root` keeps the previous behaviour rather than
92
- // silently dropping everyone's subagent total.
93
- return true;
94
- }
95
- };
96
-
97
- // Subagent sessions are separate sessions, and the parent's `cost` does not
98
- // include them, so a bare `cost` row understates a swarm. Sum the family.
99
- const treeTotals = (sessionID: string, ownCost: unknown) => {
100
- if (!isFamilyRoot(sessionID)) return undefined;
101
-
102
- let ids: readonly string[];
103
- try {
104
- ids = context.data.session.family(sessionID) ?? [sessionID];
105
- } catch {
106
- return undefined;
107
- }
108
- if (ids.length <= 1) return undefined;
109
-
110
- let cost = asCount(ownCost) ?? 0;
111
- let count = 0;
112
- for (const id of ids) {
113
- if (id === sessionID) continue;
114
- const child = context.data.session.get(id) as SessionLike | undefined;
115
- if (child === undefined) continue;
116
- count += 1;
117
- cost += asCount(child.cost) ?? 0;
118
- }
119
- return count === 0 ? undefined : { cost, count };
120
- };
121
-
122
- // A message's own totals are per-request, so the last assistant message's
123
- // prompt size *is* the current context occupancy — not a running total.
124
- const contextUsage = (sessionID: string, model: unknown) => {
125
- const messages = messagesOf(sessionID);
126
- for (let index = messages.length - 1; index >= 0; index -= 1) {
127
- const tokens = asRecord(asRecord(messages[index])?.tokens);
128
- const input = asCount(tokens?.input);
129
- if (tokens === undefined || input === undefined) continue;
130
- const cache = asRecord(tokens.cache);
131
- const used = input + (asCount(cache?.read) ?? 0) + (asCount(cache?.write) ?? 0);
132
- if (used === 0) return undefined;
133
- return { used, limit: contextLimit(model) };
134
- }
135
- return undefined;
136
- };
137
-
138
- // The window lives at `limit.context` on the catalog entry, and two
139
- // providers can expose the same model id with different windows — so the
140
- // provider has to match too, or the gauge would read the wrong ceiling.
141
- const contextLimit = (model: unknown): number | undefined => {
142
- const ref = asRecord(model);
143
- const id = ref?.id;
144
- const providerID = ref?.providerID;
145
- if (typeof id !== "string") return undefined;
146
- try {
147
- const location = context.location ?? context.data.location.default();
148
- for (const entry of context.data.location.model.list(location) ?? []) {
149
- const record = asRecord(entry);
150
- if (record === undefined || record.id !== id) continue;
151
- if (typeof providerID === "string" && record.providerID !== providerID) continue;
152
- const limit = asRecord(record.limit);
153
- return asCount(limit?.context) ?? asCount(record.context) ?? asCount(record.contextWindow);
154
- }
155
- } catch {
156
- return undefined;
157
- }
158
- return undefined;
159
- };
160
-
161
- // Measured against the clock rather than the session's last update, so the
162
- // row keeps moving between events instead of freezing between turns.
163
- const sessionElapsed = (session: SessionLike | undefined): number | undefined => {
164
- const created = asCount(asRecord(session?.time)?.created);
165
- if (created === undefined) return undefined;
166
- const elapsed = Date.now() - created;
167
- return elapsed <= 0 ? undefined : elapsed;
168
- };
169
-
170
- // Project spend: every session in THIS project, not just the one on screen.
171
- //
172
- // `session.list()` is not scoped - it returns sessions across every
173
- // directory the host knows about, so summing it gives "everything you have
174
- // ever run" while claiming to be a project total. Filtered by `projectID`
175
- // rather than by directory, because one project legitimately spans several
176
- // directories (worktrees).
177
- //
178
- // If the host does not report a project id, the unfiltered list is used, so
179
- // this degrades to the old behaviour instead of showing nothing.
180
- const projectTotals = (sessionID: string) => {
181
- try {
182
- const sessions = context.data.session.list() ?? [];
183
- const projectID = asText(asRecord(context.data.session.get(sessionID))?.["projectID"]);
184
- const scoped =
185
- projectID === undefined
186
- ? sessions
187
- : sessions.filter((entry) => asText(asRecord(entry)?.["projectID"]) === projectID);
188
-
189
- let cost = 0;
190
- for (const entry of scoped) cost += asCount(asRecord(entry)?.["cost"]) ?? 0;
191
- return { cost, count: scoped.length };
192
- } catch {
193
- return undefined;
194
- }
195
- };
196
-
197
- const statusOf = (sessionID: string): string | undefined => {
198
- try {
199
- return context.data.session.status(sessionID);
200
- } catch {
201
- return undefined;
202
- }
203
- };
204
-
205
- // Recent tool parts, oldest first. Only the tail is inspected: a loop that is
206
- // not currently happening is history, and a hang is by definition now.
207
- const recentParts = (sessionID: string): readonly unknown[] => {
208
- const parts: unknown[] = [];
209
- for (const entry of messagesOf(sessionID).slice(-RECENT_MESSAGES)) {
210
- const content = asRecord(entry)?.["content"];
211
- if (Array.isArray(content)) parts.push(...content);
212
- }
213
- return parts;
214
- };
215
-
216
- // The host's own shell records, which outlive the tool call: a backgrounded
217
- // command returns its result immediately, so its part settles while the
218
- // process keeps running. This is the only signal that survives that.
219
- const shellsOf = (sessionID: string): readonly unknown[] => {
220
- try {
221
- const shellApi = context.data.shell as unknown as
222
- | { listBySession?: (id: string) => readonly unknown[] }
223
- | undefined;
224
- return shellApi?.listBySession?.(sessionID) ?? [];
225
- } catch {
226
- return [];
227
- }
228
- };
229
-
230
- // The newest thing the host recorded for this session that is not a tool
231
- // part, so the quiet-turn rule is not blind to a model that is streaming.
232
- const lastActivity = (sessionID: string): number | undefined => {
233
- const messages = messagesOf(sessionID);
234
- for (let index = messages.length - 1; index >= 0; index -= 1) {
235
- const time = asRecord(asRecord(messages[index])?.["time"]);
236
- const stamp =
237
- asCount(time?.["completed"]) ?? asCount(time?.["streamed"]) ?? asCount(time?.["created"]);
238
- if (stamp !== undefined) return stamp;
239
- }
240
- return undefined;
241
- };
242
-
243
- const cautionThreshold = cautionThresholds(config.caution);
244
-
245
- const cautionsOf = (sessionID: string, now: number): Caution[] =>
246
- detectCautions({
247
- parts: recentParts(sessionID),
248
- shells: shellsOf(sessionID),
249
- now,
250
- sessionRunning: statusOf(sessionID) === "running",
251
- lastMessageAt: lastActivity(sessionID),
252
- thresholds: cautionThreshold,
253
- });
254
-
255
- // What is waiting, not just how many. A bare count tells you to go and look;
256
- // naming the request tells you whether it is worth looking at.
257
- const permsOf = (
258
- sessionID: string,
259
- ): { count: number; action?: string; resource?: string } | undefined => {
260
- try {
261
- const requests = context.data.session.permission.list(sessionID);
262
- if (requests === undefined || requests.length === 0) return undefined;
263
- const first = asRecord(requests[0]);
264
- const action = typeof first?.["action"] === "string" ? first["action"] : undefined;
265
- const resources = Array.isArray(first?.["resources"]) ? first["resources"] : [];
266
- const resource = typeof resources[0] === "string" ? resources[0] : undefined;
267
- return { count: requests.length, action, resource };
268
- } catch {
269
- return undefined;
270
- }
271
- };
272
-
273
- // Anything genuinely working keeps the status glyph turning: this session
274
- // (thinking, streaming, running tools), any subagent in its tree, or a shell
275
- // command still running. Returns `undefined` when the host has not said
276
- // either way, so the rail can omit the row rather than invent "idle".
277
- const busy = (sessionID: string): boolean | undefined => {
278
- const status = statusOf(sessionID);
279
- if (status === "running") return true;
280
-
281
- try {
282
- for (const id of context.data.session.family(sessionID) ?? []) {
283
- if (id === sessionID) continue;
284
- try {
285
- if (context.data.session.status(id) === "running") return true;
286
- } catch {
287
- // One unreadable child must not hide a running sibling.
288
- }
289
- }
290
- } catch {
291
- // No subagent status on this host; the shell check below still applies.
292
- }
293
-
294
- try {
295
- // `listBySession` is on the reactive client the host hands the plugin,
296
- // but not on every published type surface, so it is reached defensively:
297
- // a host without it still falls back to the session's own status.
298
- const shellApi = context.data.shell as unknown as
299
- | { listBySession?: (id: string) => readonly unknown[] }
300
- | undefined;
301
- const shells = shellApi?.listBySession?.(sessionID);
302
- if (shells !== undefined && shells.some((entry) => asRecord(entry)?.status === "running")) return true;
303
- } catch {
304
- // Same again: unreadable shells just mean no shell signal.
305
- }
306
-
307
- return status === undefined ? undefined : false;
308
- };
309
-
310
- // Throughput of the last completed turn. The host records when streaming
311
- // finished, so this is measured rather than estimated from wall-clock.
312
- const lastTps = (sessionID: string): number | undefined => {
313
- const messages = messagesOf(sessionID);
314
- for (let index = messages.length - 1; index >= 0; index -= 1) {
315
- const message = asRecord(messages[index]);
316
- const tokens = asRecord(message?.tokens);
317
- const output = asCount(tokens?.output);
318
- const time = asRecord(message?.time);
319
- const created = asCount(time?.created);
320
- const streamed = asCount(time?.streamed);
321
- if (output === undefined || created === undefined || streamed === undefined) continue;
322
- const duration = streamed - created;
323
- if (duration <= 0) continue;
324
- return output / (duration / 1_000);
325
- }
326
- return undefined;
327
- };
328
-
329
- // Recent turn sizes, oldest first. Drawn from messages the host already
330
- // holds, so the sparkline needs no history of our own to accumulate.
331
- const sparkValues = (sessionID: string): readonly number[] => {
332
- const sizes: number[] = [];
333
- for (const entry of messagesOf(sessionID)) {
334
- const message = asRecord(entry);
335
- if (message?.type !== "assistant") continue;
336
- const output = asCount(asRecord(message.tokens)?.output);
337
- if (output === undefined) continue;
338
- sizes.push(output);
339
- }
340
- // Windowed by the configured width, not a hardcoded one: `sparkWidth` is
341
- // capped here first, so a wider setting used to be silently impossible.
342
- return sizes.slice(-config.layout.sparkWidth);
343
- };
344
-
345
- // A ticker exists only for clock-derived rows; everything else updates from
346
- // the host's own events. It is skipped entirely when nothing on the rail
347
- // animates, and `refresh: 0` opts out regardless. The tick has to live in the
348
- // host's reactive graph rather than ours, or it re-renders nothing at all.
349
- const animated =
350
- config.sidebar.enabled &&
351
- config.sidebar.rows.some((name) => (ANIMATED_FIELDS as readonly string[]).includes(name));
352
- const ticker = startTicker(context, animated ? config.refresh : 0);
353
-
354
- // The guard row is opt-in and polls its own RPC: starting the bridge only
355
- // when the row is on the rail means no timer and no request for a row
356
- // nobody renders. The bridge resolves `status` from `context.client` on
357
- // every poll, so installing guard later appears within its interval.
358
- const wantGuard = config.sidebar.enabled && config.sidebar.rows.includes("guard");
359
- const bridge = wantGuard ? startGuardBridge(context) : undefined;
360
-
361
- // Read session state inside the render so the rail stays live: cost and
362
- // tokens climb as the session runs, and the branch appears once VCS
363
- // resolves. Nothing here writes, requests, or leaves the process.
364
- // Only the worst is ever drawn: the rail has one line for this, and two
365
- // simultaneous observations is one problem with two symptoms.
366
- //
367
- // Returns a plain string, themed exactly like every other live row. The
368
- // annunciator carries its meaning in its glyph, not in a colour of its own:
369
- // a row that suddenly brightens reads as a different kind of thing rather
370
- // than as the same panel telling you something.
371
- const announce = (sessionID: string): string | undefined => {
372
- if (!config.caution.enabled) return undefined;
373
- const top = worstCaution(cautionsOf(sessionID, Date.now()));
374
- return top === undefined ? undefined : cautionText(top, config.glyphs);
375
- };
376
-
377
- // Both of these are host lookups like any other, and the slot render must
378
- // not throw: an unreachable default location, or a VCS call on a directory
379
- // with no repository, would take the whole rail down with it. Each degrades
380
- // to "no branch row", the same way every other missing value does.
381
- const locationOf = () => {
382
- try {
383
- return context.location ?? context.data.location.default();
384
- } catch {
385
- return context.location;
386
- }
387
- };
388
-
389
- const branchOf = (location: ReturnType<typeof locationOf>): string | undefined => {
390
- try {
391
- return context.data.location.vcs.info(location)?.branch?.current;
392
- } catch {
393
- return undefined;
394
- }
395
- };
396
-
397
- const snapshot = (sessionID: string): StatSource => {
398
- const location = locationOf();
399
- const session = context.data.session.get(sessionID) as SessionLike | undefined;
400
- // A "turn" is one prompt and the work it caused. The host's message list
401
- // also carries system, shell and switch records, so counting records
402
- // reports several times the turns actually taken.
403
- const turns = messagesOf(sessionID).filter((entry) => asRecord(entry)?.["type"] === "user").length;
404
-
405
- return {
406
- ...session,
407
- caution: announce(sessionID),
408
- branch: branchOf(location),
409
- tree: treeTotals(sessionID, session?.cost),
410
- context: contextUsage(sessionID, session?.model),
411
- project: projectTotals(sessionID),
412
- status: statusOf(sessionID),
413
- busy: busy(sessionID),
414
- perms: permsOf(sessionID),
415
- tps: lastTps(sessionID),
416
- spark: sparkValues(sessionID),
417
- elapsedMs: sessionElapsed(session),
418
- turns,
419
- guard: bridge?.status,
420
- // Read the tick inside the render so the host registers a dependency on
421
- // it; that read is what makes the rail re-run on the ticker's schedule.
422
- frame: ticker?.frame ?? 0,
423
- };
424
- };
425
-
426
- // The toast is opt-in and deliberately not the signal — the rail is. It
427
- // fires on the transition into a caution, once per distinct problem, and
428
- // re-arms when the session goes quiet, so a persistent hang cannot nag.
429
- // Reading state on a timer rather than inside the render keeps the render a
430
- // pure function of what it was given.
431
- let watchedSession: string | undefined;
432
- let toastedKey: string | undefined;
433
- let watchTimer: ReturnType<typeof setInterval> | undefined;
434
-
435
- if (config.caution.enabled && config.caution.toast) {
436
- watchTimer = setInterval(() => {
437
- const sessionID = watchedSession;
438
- if (sessionID === undefined) return;
439
- try {
440
- const top = worstCaution(cautionsOf(sessionID, Date.now()));
441
- if (top === undefined || top.severity !== "caution") {
442
- toastedKey = undefined;
443
- return;
444
- }
445
- if (top.key === toastedKey) return;
446
- toastedKey = top.key;
447
- context.ui.toast.show({
448
- title: "Flight Deck",
449
- message: cautionDetail(top),
450
- variant: "warning",
451
- });
452
- } catch {
453
- // A warning must never be able to break the panel it warns about.
454
- }
455
- }, config.refresh > 0 ? config.refresh : 1_000);
456
- }
457
-
458
- if (config.sidebar.enabled) {
459
- releases.push(
460
- context.ui.slot({
461
- append: "sidebar.content",
462
- render: ({ sessionID }) => {
463
- // The annunciator is drawn from a timer, so the toast watcher needs
464
- // to know which session is on screen. Reading the frame is what
465
- // subscribes this render to the host's tick — without it nothing
466
- // re-runs between host events, and a stall is precisely the failure
467
- // that produces no host events at all.
468
- watchedSession = sessionID;
469
- // Keep the guard bridge on the rendered session: the follow fetches
470
- // immediately on change, and the status read below subscribes this
471
- // render to the bridge's host store, so polls re-run the rail.
472
- bridge?.follow(sessionID);
473
- void ticker?.frame;
474
- void bridge?.status;
475
-
476
- const source = snapshot(sessionID);
477
- const lines = sidebarLines(config, source);
478
- if (lines.length === 0) return null;
479
- const offset = Math.min(liveRowOffset(config), lines.length);
480
-
481
- return (
482
- // No padding here: the host already lays out and pads the sidebar,
483
- // so adding our own would push the rows out of alignment with it.
484
- //
485
- // Every live row gets the same token, the annunciator included. It
486
- // is the same panel; only the glyph changes.
487
- <box flexDirection="column">
488
- {lines.map((line, index) => (
489
- <text fg={index < offset ? context.theme.text.default : context.theme.text.subdued}>{line}</text>
490
- ))}
491
- </box>
492
- );
493
- },
494
- }),
495
- );
496
- }
497
-
498
- if (footer !== undefined) {
499
- releases.push(
500
- context.ui.slot({
501
- append: "prompt.footer.status",
502
- render: () => <text fg={context.theme.text.subdued}>{footer}</text>,
503
- }),
504
- );
505
- }
506
-
507
- return () => {
508
- if (watchTimer !== undefined) clearInterval(watchTimer);
509
- watchTimer = undefined;
510
- ticker?.dispose();
511
- bridge?.dispose();
512
- for (const release of releases) release();
513
- };
514
- },
515
- });
1
+ /** @jsxImportSource @opentui/solid */
2
+ import { Plugin } from "@opencode/plugin/tui";
3
+ import { cautionDetail, cautionText, detectCautions, worstCaution, type Caution } from "./caution.js";
4
+ import { cautionThresholds, mergeOptions, resolveConfig } from "./config.js";
5
+ import { loadConfigFile } from "./file-config.js";
6
+ import { footerLine, liveRowOffset, sidebarLines } from "./presentation.js";
7
+ import { ANIMATED_FIELDS, sessionThroughput, type StatSource } from "./stats.js";
8
+ import { startGuardBridge } from "./guard.js";
9
+ import { startTicker } from "./ticker.js";
10
+
11
+ // Flight Deck is a read-only instrument panel for the OpenCode V2 CLI/TUI. It
12
+ // shows the open session's agent, model, branch, cost, tokens, and cache hit
13
+ // rate in the sidebar. It uses only the official CLI plugin boundary —
14
+ // `@opencode/plugin/tui`, `context.ui.slot`, and theme tokens.
15
+ //
16
+ // Read-only but for one thing: the animation tick writes a single counter into
17
+ // the host's ephemeral plugin-memory store. It has to, because a timer owned by
18
+ // this plugin cannot wake the host's renderer — see ./ticker.ts for why. That
19
+ // counter is in-process, scoped to this plugin, and gone when the TUI exits.
20
+ // Everything the rail displays is state the host already holds in memory.
21
+ //
22
+ // Appearance comes from, in order of precedence:
23
+ // 1. `context.options` — the host's plugin options, when the host forwards them
24
+ // 2. the one global config file, `flight-deck.jsonc` in the opencode
25
+ // configuration directory
26
+ // 3. the sane defaults in ./config.ts
27
+ // See flight-deck.example.jsonc for the commented template.
28
+
29
+ /** How many trailing messages are inspected for tool parts. */
30
+ const RECENT_MESSAGES = 4;
31
+
32
+ type SessionLike = { cost?: unknown; model?: unknown; time?: unknown; tokens?: unknown };
33
+
34
+ function asCount(value: unknown): number | undefined {
35
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
36
+ }
37
+
38
+ function asText(value: unknown): string | undefined {
39
+ if (typeof value !== "string") return undefined;
40
+ const text = value.trim();
41
+ return text.length === 0 ? undefined : text;
42
+ }
43
+
44
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
45
+ return typeof value === "object" && value !== null && !Array.isArray(value)
46
+ ? (value as Record<string, unknown>)
47
+ : undefined;
48
+ }
49
+
50
+ export default Plugin.define({
51
+ id: "flight-deck-tui",
52
+ setup(context) {
53
+ const file = loadConfigFile();
54
+ const { config, issues } = resolveConfig(mergeOptions(file.options, context.options));
55
+
56
+ // Only the rows actually on the rail are worth deriving: the rail re-runs on
57
+ // every tick, and a figure nobody asked to see should not cost a walk of the
58
+ // session database or the model catalog.
59
+ const rows = config.sidebar.enabled ? new Set(config.sidebar.rows) : new Set<string>();
60
+ const wants = (name: string): boolean => rows.has(name);
61
+
62
+ if (file.issue !== undefined && file.source !== undefined) {
63
+ console.warn(`[flight-deck] ${file.issue}`);
64
+ }
65
+ const problems = file.issue !== undefined ? [file.issue, ...issues] : issues;
66
+ if (problems.length > 0) {
67
+ const extra = problems.length > 1 ? ` (+${problems.length - 1} more)` : "";
68
+ context.ui.toast.show({
69
+ title: "Flight Deck",
70
+ message: `Ignoring invalid config: ${problems[0]}${extra}`,
71
+ variant: "warning",
72
+ });
73
+ }
74
+
75
+ const footer = footerLine(config);
76
+ const releases: Array<() => void> = [];
77
+
78
+ // The host owns these caches; a failure to read one must never break the
79
+ // rail, so every lookup degrades to "no data" instead of throwing.
80
+ const messagesOf = (sessionID: string): readonly unknown[] => {
81
+ try {
82
+ return context.data.session.message.list(sessionID) ?? [];
83
+ } catch {
84
+ return [];
85
+ }
86
+ };
87
+
88
+ // A subagent session is already inside its parent's family total, and the
89
+ // host keys `family()` by the family ROOT — so asking from a child returns
90
+ // its ancestors and siblings as well. Merging that would report the whole
91
+ // tree as this conversation's own, under a label that promises the
92
+ // conversation plus *its* subagents. Only a root has a family beneath it.
93
+ const isFamilyRoot = (sessionID: string): boolean => {
94
+ try {
95
+ return context.data.session.root(sessionID) === sessionID;
96
+ } catch {
97
+ // A host without `root` keeps the previous behaviour rather than
98
+ // silently dropping everyone's subagent total.
99
+ return true;
100
+ }
101
+ };
102
+
103
+ // Subagent sessions are separate sessions, and the parent's `cost` does not
104
+ // include them, so a bare `cost` row understates a swarm. Sum the family.
105
+ const treeTotals = (sessionID: string, ownCost: unknown) => {
106
+ if (!isFamilyRoot(sessionID)) return undefined;
107
+
108
+ let ids: readonly string[];
109
+ try {
110
+ ids = context.data.session.family(sessionID) ?? [sessionID];
111
+ } catch {
112
+ return undefined;
113
+ }
114
+ if (ids.length <= 1) return undefined;
115
+
116
+ let cost = asCount(ownCost) ?? 0;
117
+ let count = 0;
118
+ for (const id of ids) {
119
+ if (id === sessionID) continue;
120
+ const child = context.data.session.get(id) as SessionLike | undefined;
121
+ if (child === undefined) continue;
122
+ count += 1;
123
+ cost += asCount(child.cost) ?? 0;
124
+ }
125
+ return count === 0 ? undefined : { cost, count };
126
+ };
127
+
128
+ // A message's own totals are per-request, so the last assistant message's
129
+ // prompt size *is* the current context occupancy — not a running total.
130
+ const contextUsage = (sessionID: string, model: unknown) => {
131
+ const messages = messagesOf(sessionID);
132
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
133
+ const tokens = asRecord(asRecord(messages[index])?.tokens);
134
+ const input = asCount(tokens?.input);
135
+ if (tokens === undefined || input === undefined) continue;
136
+ const cache = asRecord(tokens.cache);
137
+ const used = input + (asCount(cache?.read) ?? 0) + (asCount(cache?.write) ?? 0);
138
+ if (used === 0) return undefined;
139
+ return { used, limit: contextLimit(model) };
140
+ }
141
+ return undefined;
142
+ };
143
+
144
+ // The window lives at `limit.context` on the catalog entry, and two
145
+ // providers can expose the same model id with different windows — so the
146
+ // provider has to match too, or the gauge would read the wrong ceiling.
147
+ const contextLimit = (model: unknown): number | undefined => {
148
+ const ref = asRecord(model);
149
+ const id = ref?.id;
150
+ const providerID = ref?.providerID;
151
+ if (typeof id !== "string") return undefined;
152
+ try {
153
+ const location = context.location ?? context.data.location.default();
154
+ for (const entry of context.data.location.model.list(location) ?? []) {
155
+ const record = asRecord(entry);
156
+ if (record === undefined || record.id !== id) continue;
157
+ if (typeof providerID === "string" && record.providerID !== providerID) continue;
158
+ const limit = asRecord(record.limit);
159
+ return asCount(limit?.context) ?? asCount(record.context) ?? asCount(record.contextWindow);
160
+ }
161
+ } catch {
162
+ return undefined;
163
+ }
164
+ return undefined;
165
+ };
166
+
167
+ // Measured against the clock rather than the session's last update, so the
168
+ // row keeps moving between events instead of freezing between turns.
169
+ const sessionElapsed = (session: SessionLike | undefined): number | undefined => {
170
+ const created = asCount(asRecord(session?.time)?.created);
171
+ if (created === undefined) return undefined;
172
+ const elapsed = Date.now() - created;
173
+ return elapsed <= 0 ? undefined : elapsed;
174
+ };
175
+
176
+ // Project spend: every session in THIS project, not just the one on screen.
177
+ //
178
+ // `session.list()` is not scoped - it returns sessions across every
179
+ // directory the host knows about, so summing it gives "everything you have
180
+ // ever run" while claiming to be a project total. Filtered by `projectID`
181
+ // rather than by directory, because one project legitimately spans several
182
+ // directories (worktrees).
183
+ //
184
+ // If the host does not report a project id, the unfiltered list is used, so
185
+ // this degrades to the old behaviour instead of showing nothing.
186
+ // `project` walks every session the host knows about, and that collection grows
187
+ // with your history rather than staying a handful. It moves slowly, so the walk
188
+ // is held briefly instead of repeated on every tick.
189
+ const PROJECT_CACHE_MS = 5_000;
190
+ let projectCache:
191
+ | { readonly projectID: string | undefined; readonly at: number; readonly value: { cost: number; count: number } }
192
+ | undefined;
193
+
194
+ const projectTotals = (sessionID: string) => {
195
+ try {
196
+ const projectID = asText(asRecord(context.data.session.get(sessionID))?.["projectID"]);
197
+ const cached = projectCache;
198
+ if (cached !== undefined && cached.projectID === projectID && Date.now() - cached.at < PROJECT_CACHE_MS) {
199
+ return cached.value;
200
+ }
201
+
202
+ const sessions = context.data.session.list() ?? [];
203
+ const scoped =
204
+ projectID === undefined
205
+ ? sessions
206
+ : sessions.filter((entry) => asText(asRecord(entry)?.["projectID"]) === projectID);
207
+
208
+ let cost = 0;
209
+ for (const entry of scoped) cost += asCount(asRecord(entry)?.["cost"]) ?? 0;
210
+ const value = { cost, count: scoped.length };
211
+ projectCache = { projectID, at: Date.now(), value };
212
+ return value;
213
+ } catch {
214
+ return undefined;
215
+ }
216
+ };
217
+
218
+ const statusOf = (sessionID: string): string | undefined => {
219
+ try {
220
+ return context.data.session.status(sessionID);
221
+ } catch {
222
+ return undefined;
223
+ }
224
+ };
225
+
226
+ // Recent tool parts, oldest first. Only the tail is inspected: a loop that is
227
+ // not currently happening is history, and a hang is by definition now.
228
+ const recentParts = (sessionID: string): readonly unknown[] => {
229
+ const parts: unknown[] = [];
230
+ for (const entry of messagesOf(sessionID).slice(-RECENT_MESSAGES)) {
231
+ const content = asRecord(entry)?.["content"];
232
+ if (Array.isArray(content)) parts.push(...content);
233
+ }
234
+ return parts;
235
+ };
236
+
237
+ // The host's own shell records, which outlive the tool call: a backgrounded
238
+ // command returns its result immediately, so its part settles while the
239
+ // process keeps running. This is the only signal that survives that.
240
+ //
241
+ // Shells are listed per LOCATION, not per session, so the session is matched
242
+ // on the record's own `metadata.sessionID` — the documented shape, rather
243
+ // than a session-scoped accessor the published API does not carry.
244
+ const shellsOf = (sessionID: string): readonly unknown[] => {
245
+ try {
246
+ const shells = context.data.shell.list(locationOf()) ?? [];
247
+ return shells.filter(
248
+ (entry) => asText(asRecord(asRecord(entry)?.["metadata"])?.["sessionID"]) === sessionID,
249
+ );
250
+ } catch {
251
+ return [];
252
+ }
253
+ };
254
+
255
+ // The newest thing the host recorded for this session that is not a tool
256
+ // part, so the quiet-turn rule is not blind to a model that is streaming.
257
+ const lastActivity = (sessionID: string): number | undefined => {
258
+ const messages = messagesOf(sessionID);
259
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
260
+ const time = asRecord(asRecord(messages[index])?.["time"]);
261
+ const stamp =
262
+ asCount(time?.["completed"]) ?? asCount(time?.["streamed"]) ?? asCount(time?.["created"]);
263
+ if (stamp !== undefined) return stamp;
264
+ }
265
+ return undefined;
266
+ };
267
+
268
+ const cautionThreshold = cautionThresholds(config.caution);
269
+
270
+ const cautionsOf = (sessionID: string, now: number): Caution[] =>
271
+ detectCautions({
272
+ parts: recentParts(sessionID),
273
+ shells: shellsOf(sessionID),
274
+ now,
275
+ sessionRunning: statusOf(sessionID) === "running",
276
+ lastMessageAt: lastActivity(sessionID),
277
+ thresholds: cautionThreshold,
278
+ });
279
+
280
+ // What is waiting, not just how many. A bare count tells you to go and look;
281
+ // naming the request tells you whether it is worth looking at.
282
+ const permsOf = (
283
+ sessionID: string,
284
+ ): { count: number; action?: string; resource?: string } | undefined => {
285
+ try {
286
+ const requests = context.data.session.permission.list(sessionID);
287
+ if (requests === undefined || requests.length === 0) return undefined;
288
+ const first = asRecord(requests[0]);
289
+ const action = typeof first?.["action"] === "string" ? first["action"] : undefined;
290
+ const resources = Array.isArray(first?.["resources"]) ? first["resources"] : [];
291
+ const resource = typeof resources[0] === "string" ? resources[0] : undefined;
292
+ return { count: requests.length, action, resource };
293
+ } catch {
294
+ return undefined;
295
+ }
296
+ };
297
+
298
+ // Anything genuinely working keeps the status glyph turning: this session
299
+ // (thinking, streaming, running tools), any subagent in its tree, or a shell
300
+ // command still running. Returns `undefined` when the host has not said
301
+ // either way, so the rail can omit the row rather than invent "idle".
302
+ const busy = (sessionID: string): boolean | undefined => {
303
+ const status = statusOf(sessionID);
304
+ if (status === "running") return true;
305
+
306
+ try {
307
+ for (const id of context.data.session.family(sessionID) ?? []) {
308
+ if (id === sessionID) continue;
309
+ try {
310
+ if (context.data.session.status(id) === "running") return true;
311
+ } catch {
312
+ // One unreadable child must not hide a running sibling.
313
+ }
314
+ }
315
+ } catch {
316
+ // No subagent status on this host; the shell check below still applies.
317
+ }
318
+
319
+ try {
320
+ if (shellsOf(sessionID).some((entry) => asRecord(entry)?.["status"] === "running")) return true;
321
+ } catch {
322
+ // Unreadable shells just mean no shell signal.
323
+ }
324
+
325
+ return status === undefined ? undefined : false;
326
+ };
327
+
328
+ // Overall session throughput: every output token the conversation has
329
+ // produced, divided by how long the session has been alive. Subagents run as
330
+ // separate sessions, so their output is summed in — this is the whole
331
+ // session's rate, not the main chat's last turn. Measured from the session's
332
+ // own clock (`time.updated`, falling back to now) so a finished session
333
+ // settles on a stable figure instead of decaying as it sits on screen.
334
+ const sessionTps = (sessionID: string, session: SessionLike | undefined): number | undefined => {
335
+ const time = asRecord(session?.time);
336
+ const created = asCount(time?.["created"]);
337
+ if (created === undefined) return undefined;
338
+ const updated = asCount(time?.["updated"]);
339
+ const end = updated === undefined ? Date.now() : Math.min(Date.now(), updated);
340
+ const elapsed = end - created;
341
+ if (elapsed <= 0) return undefined;
342
+
343
+ const own = asCount(asRecord(session?.tokens)?.["output"]);
344
+ let output = own;
345
+ // Only a family root owns the tree beneath it; a child asking `family()`
346
+ // gets its ancestors and siblings too, so it keeps its own figure.
347
+ if (isFamilyRoot(sessionID)) {
348
+ try {
349
+ const ids = context.data.session.family(sessionID) ?? [];
350
+ if (ids.length > 1) {
351
+ let total = 0;
352
+ let sawOne = false;
353
+ for (const id of ids) {
354
+ const member = context.data.session.get(id) as SessionLike | undefined;
355
+ const out = asCount(asRecord(member?.tokens)?.["output"]);
356
+ if (out === undefined) continue;
357
+ total += out;
358
+ sawOne = true;
359
+ }
360
+ if (sawOne) output = total;
361
+ }
362
+ } catch {
363
+ // No family on this host: the session's own tokens still stand.
364
+ }
365
+ }
366
+ return sessionThroughput(output, elapsed);
367
+ };
368
+
369
+ // Recent turn sizes, oldest first. Drawn from messages the host already
370
+ // holds, so the sparkline needs no history of our own to accumulate.
371
+ const sparkValues = (sessionID: string): readonly number[] => {
372
+ const sizes: number[] = [];
373
+ for (const entry of messagesOf(sessionID)) {
374
+ const message = asRecord(entry);
375
+ if (message?.type !== "assistant") continue;
376
+ const output = asCount(asRecord(message.tokens)?.output);
377
+ if (output === undefined) continue;
378
+ sizes.push(output);
379
+ }
380
+ // Windowed by the configured width, not a hardcoded one: `sparkWidth` is
381
+ // capped here first, so a wider setting used to be silently impossible.
382
+ return sizes.slice(-config.layout.sparkWidth);
383
+ };
384
+
385
+ // A ticker exists only for clock-derived rows; everything else updates from
386
+ // the host's own events. It is skipped entirely when nothing on the rail
387
+ // animates, and `refresh: 0` opts out regardless. The tick has to live in the
388
+ // host's reactive graph rather than ours, or it re-renders nothing at all.
389
+ const animated =
390
+ config.sidebar.enabled &&
391
+ config.sidebar.rows.some((name) => (ANIMATED_FIELDS as readonly string[]).includes(name));
392
+ let spinnerNeeded = false;
393
+ const ticker = startTicker(context, animated ? config.refresh : 0, () => spinnerNeeded);
394
+
395
+ // The guard row is opt-in and polls its own RPC: starting the bridge only
396
+ // when the row is on the rail means no timer and no request for a row
397
+ // nobody renders. The bridge resolves `status` from `context.client` on
398
+ // every poll, so installing guard later appears within its interval.
399
+ const wantGuard = config.sidebar.enabled && config.sidebar.rows.includes("guard");
400
+ const bridge = wantGuard ? startGuardBridge(context) : undefined;
401
+
402
+ // Read session state inside the render so the rail stays live: cost and
403
+ // tokens climb as the session runs, and the branch appears once VCS
404
+ // resolves. Nothing here writes, requests, or leaves the process.
405
+ // Only the worst is ever drawn: the rail has one line for this, and two
406
+ // simultaneous observations is one problem with two symptoms.
407
+ //
408
+ // Returns a plain string, themed exactly like every other live row. The
409
+ // annunciator carries its meaning in its glyph, not in a colour of its own:
410
+ // a row that suddenly brightens reads as a different kind of thing rather
411
+ // than as the same panel telling you something.
412
+ const announce = (sessionID: string): string | undefined => {
413
+ if (!config.caution.enabled) return undefined;
414
+ const top = worstCaution(cautionsOf(sessionID, Date.now()));
415
+ return top === undefined ? undefined : cautionText(top, config.glyphs);
416
+ };
417
+
418
+ // Both of these are host lookups like any other, and the slot render must
419
+ // not throw: an unreachable default location, or a VCS call on a directory
420
+ // with no repository, would take the whole rail down with it. Each degrades
421
+ // to "no branch row", the same way every other missing value does.
422
+ const locationOf = () => {
423
+ try {
424
+ return context.location ?? context.data.location.default();
425
+ } catch {
426
+ return context.location;
427
+ }
428
+ };
429
+
430
+ const branchOf = (location: ReturnType<typeof locationOf>): string | undefined => {
431
+ try {
432
+ return context.data.location.vcs.info(location)?.branch?.current;
433
+ } catch {
434
+ return undefined;
435
+ }
436
+ };
437
+
438
+ const snapshot = (sessionID: string): StatSource => {
439
+ const location = locationOf();
440
+ const session = context.data.session.get(sessionID) as SessionLike | undefined;
441
+ const isBusy = busy(sessionID);
442
+ // The fast tick exists for the spinner, and the spinner is only drawn while
443
+ // something is moving. Everything else on the rail reads in seconds.
444
+ spinnerNeeded = wants("status") && isBusy === true;
445
+
446
+ // A "turn" is one prompt and the work it caused. The host's message list
447
+ // also carries system, shell and switch records, so counting records
448
+ // reports several times the turns actually taken.
449
+ const turns = wants("turns")
450
+ ? messagesOf(sessionID).filter((entry) => asRecord(entry)?.["type"] === "user").length
451
+ : undefined;
452
+
453
+ return {
454
+ ...session,
455
+ caution: wants("caution") ? announce(sessionID) : undefined,
456
+ branch: wants("branch") ? branchOf(location) : undefined,
457
+ tree: wants("cost") || wants("total") ? treeTotals(sessionID, session?.cost) : undefined,
458
+ context: wants("context") ? contextUsage(sessionID, session?.model) : undefined,
459
+ project: wants("project") ? projectTotals(sessionID) : undefined,
460
+ status: wants("status") ? statusOf(sessionID) : undefined,
461
+ busy: isBusy,
462
+ perms: wants("perms") ? permsOf(sessionID) : undefined,
463
+ tps: wants("tps") ? sessionTps(sessionID, session) : undefined,
464
+ spark: wants("spark") ? sparkValues(sessionID) : undefined,
465
+ elapsedMs: wants("elapsed") ? sessionElapsed(session) : undefined,
466
+ turns,
467
+ guard: bridge?.status,
468
+ // Read the tick inside the render so the host registers a dependency on
469
+ // it; that read is what makes the rail re-run on the ticker's schedule.
470
+ frame: ticker?.frame ?? 0,
471
+ };
472
+ };
473
+
474
+ // The toast is opt-in and deliberately not the signal — the rail is. It
475
+ // fires on the transition into a caution, once per distinct problem, and
476
+ // re-arms when the session goes quiet, so a persistent hang cannot nag.
477
+ // Reading state on a timer rather than inside the render keeps the render a
478
+ // pure function of what it was given.
479
+ let watchedSession: string | undefined;
480
+ let toastedKey: string | undefined;
481
+ let watchTimer: ReturnType<typeof setInterval> | undefined;
482
+
483
+ if (config.caution.enabled && config.caution.toast) {
484
+ watchTimer = setInterval(() => {
485
+ const sessionID = watchedSession;
486
+ if (sessionID === undefined) return;
487
+ try {
488
+ const top = worstCaution(cautionsOf(sessionID, Date.now()));
489
+ if (top === undefined || top.severity !== "caution") {
490
+ toastedKey = undefined;
491
+ return;
492
+ }
493
+ if (top.key === toastedKey) return;
494
+ toastedKey = top.key;
495
+ context.ui.toast.show({
496
+ title: "Flight Deck",
497
+ message: cautionDetail(top),
498
+ variant: "warning",
499
+ });
500
+ } catch {
501
+ // A warning must never be able to break the panel it warns about.
502
+ }
503
+ }, config.refresh > 0 ? config.refresh : 1_000);
504
+ }
505
+
506
+ if (config.sidebar.enabled) {
507
+ releases.push(
508
+ context.ui.slot({
509
+ append: "sidebar.content",
510
+ render: ({ sessionID }) => {
511
+ // The annunciator is drawn from a timer, so the toast watcher needs
512
+ // to know which session is on screen. Reading the frame is what
513
+ // subscribes this render to the host's tick — without it nothing
514
+ // re-runs between host events, and a stall is precisely the failure
515
+ // that produces no host events at all.
516
+ watchedSession = sessionID;
517
+ // Keep the guard bridge on the rendered session: the follow fetches
518
+ // immediately on change, and the status read below subscribes this
519
+ // render to the bridge's host store, so polls re-run the rail.
520
+ bridge?.follow(sessionID);
521
+ void ticker?.frame;
522
+ void bridge?.status;
523
+
524
+ const source = snapshot(sessionID);
525
+ const lines = sidebarLines(config, source);
526
+ if (lines.length === 0) return null;
527
+ const offset = Math.min(liveRowOffset(config), lines.length);
528
+
529
+ return (
530
+ // No padding here: the host already lays out and pads the sidebar,
531
+ // so adding our own would push the rows out of alignment with it.
532
+ //
533
+ // Every live row gets the same token, the annunciator included. It
534
+ // is the same panel; only the glyph changes.
535
+ <box flexDirection="column">
536
+ {lines.map((line, index) => (
537
+ <text fg={index < offset ? context.theme.text.default : context.theme.text.subdued}>{line}</text>
538
+ ))}
539
+ </box>
540
+ );
541
+ },
542
+ }),
543
+ );
544
+ }
545
+
546
+ if (footer !== undefined) {
547
+ releases.push(
548
+ context.ui.slot({
549
+ append: "prompt.footer.status",
550
+ render: () => <text fg={context.theme.text.subdued}>{footer}</text>,
551
+ }),
552
+ );
553
+ }
554
+
555
+ return () => {
556
+ if (watchTimer !== undefined) clearInterval(watchTimer);
557
+ watchTimer = undefined;
558
+ ticker?.dispose();
559
+ bridge?.dispose();
560
+ for (const release of releases) release();
561
+ };
562
+ },
563
+ });