oc-flight-deck 0.6.1 → 0.6.3

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