oc-flight-deck 0.1.1 → 0.2.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,18 +1,22 @@
1
1
  /** @jsxImportSource @opentui/solid */
2
2
  import { Plugin } from "@opencode/plugin/tui";
3
- import { createSignal } from "solid-js";
4
- import { mergeOptions, resolveConfig } from "./config.js";
3
+ import { cautionDetail, cautionText, detectCautions, worstCaution, type Caution } from "./caution.js";
4
+ import { cautionThresholds, mergeOptions, resolveConfig } from "./config.js";
5
5
  import { loadConfigFile } from "./file-config.js";
6
6
  import { footerLine, liveRowOffset, sidebarLines } from "./presentation.js";
7
- import type { StatSource } from "./stats.js";
7
+ import { ANIMATED_FIELDS, type StatSource } from "./stats.js";
8
+ import { startTicker } from "./ticker.js";
8
9
 
9
10
  // Flight Deck is a read-only instrument panel for the OpenCode V2 CLI/TUI. It
10
11
  // shows the open session's agent, model, branch, cost, tokens, and cache hit
11
12
  // rate in the sidebar. It uses only the official CLI plugin boundary —
12
13
  // `@opencode/plugin/tui`, `context.ui.slot`, and theme tokens.
13
14
  //
14
- // Read-only by construction: it never writes, requests, stores, subscribes, or
15
- // polls. Everything it shows is state the host already holds in memory.
15
+ // Read-only but for one thing: the animation tick writes a single counter into
16
+ // the host's ephemeral plugin-memory store. It has to, because a timer owned by
17
+ // this plugin cannot wake the host's renderer — see ./ticker.ts for why. That
18
+ // counter is in-process, scoped to this plugin, and gone when the TUI exits.
19
+ // Everything the rail displays is state the host already holds in memory.
16
20
  //
17
21
  // Appearance comes from, in order of precedence:
18
22
  // 1. `context.options` — the host's plugin options, when the host forwards them
@@ -20,6 +24,9 @@ import type { StatSource } from "./stats.js";
20
24
  // 3. the sane defaults in ./config.ts
21
25
  // See flight-deck.example.jsonc for the commented template.
22
26
 
27
+ /** How many trailing messages are inspected for tool parts. */
28
+ const RECENT_MESSAGES = 4;
29
+
23
30
  type SessionLike = { cost?: unknown; model?: unknown; time?: unknown };
24
31
 
25
32
  function asCount(value: unknown): number | undefined {
@@ -157,14 +164,111 @@ export default Plugin.define({
157
164
  }
158
165
  };
159
166
 
160
- const permsOf = (sessionID: string): number | undefined => {
167
+ // Recent tool parts, oldest first. Only the tail is inspected: a loop that is
168
+ // not currently happening is history, and a hang is by definition now.
169
+ const recentParts = (sessionID: string): readonly unknown[] => {
170
+ const parts: unknown[] = [];
171
+ for (const entry of messagesOf(sessionID).slice(-RECENT_MESSAGES)) {
172
+ const content = asRecord(entry)?.["content"];
173
+ if (Array.isArray(content)) parts.push(...content);
174
+ }
175
+ return parts;
176
+ };
177
+
178
+ // The host's own shell records, which outlive the tool call: a backgrounded
179
+ // command returns its result immediately, so its part settles while the
180
+ // process keeps running. This is the only signal that survives that.
181
+ const shellsOf = (sessionID: string): readonly unknown[] => {
182
+ try {
183
+ const shellApi = context.data.shell as unknown as
184
+ | { listBySession?: (id: string) => readonly unknown[] }
185
+ | undefined;
186
+ return shellApi?.listBySession?.(sessionID) ?? [];
187
+ } catch {
188
+ return [];
189
+ }
190
+ };
191
+
192
+ // The newest thing the host recorded for this session that is not a tool
193
+ // part, so the quiet-turn rule is not blind to a model that is streaming.
194
+ const lastActivity = (sessionID: string): number | undefined => {
195
+ const messages = messagesOf(sessionID);
196
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
197
+ const time = asRecord(asRecord(messages[index])?.["time"]);
198
+ const stamp =
199
+ asCount(time?.["completed"]) ?? asCount(time?.["streamed"]) ?? asCount(time?.["created"]);
200
+ if (stamp !== undefined) return stamp;
201
+ }
202
+ return undefined;
203
+ };
204
+
205
+ const cautionThreshold = cautionThresholds(config.caution);
206
+
207
+ const cautionsOf = (sessionID: string, now: number): Caution[] =>
208
+ detectCautions({
209
+ parts: recentParts(sessionID),
210
+ shells: shellsOf(sessionID),
211
+ now,
212
+ sessionRunning: statusOf(sessionID) === "running",
213
+ lastMessageAt: lastActivity(sessionID),
214
+ thresholds: cautionThreshold,
215
+ });
216
+
217
+ // What is waiting, not just how many. A bare count tells you to go and look;
218
+ // naming the request tells you whether it is worth looking at.
219
+ const permsOf = (
220
+ sessionID: string,
221
+ ): { count: number; action?: string; resource?: string } | undefined => {
161
222
  try {
162
- return context.data.session.permission.list(sessionID)?.length;
223
+ const requests = context.data.session.permission.list(sessionID);
224
+ if (requests === undefined || requests.length === 0) return undefined;
225
+ const first = asRecord(requests[0]);
226
+ const action = typeof first?.["action"] === "string" ? first["action"] : undefined;
227
+ const resources = Array.isArray(first?.["resources"]) ? first["resources"] : [];
228
+ const resource = typeof resources[0] === "string" ? resources[0] : undefined;
229
+ return { count: requests.length, action, resource };
163
230
  } catch {
164
231
  return undefined;
165
232
  }
166
233
  };
167
234
 
235
+ // Anything genuinely working keeps the status glyph turning: this session
236
+ // (thinking, streaming, running tools), any subagent in its tree, or a shell
237
+ // command still running. Returns `undefined` when the host has not said
238
+ // either way, so the rail can omit the row rather than invent "idle".
239
+ const busy = (sessionID: string): boolean | undefined => {
240
+ const status = statusOf(sessionID);
241
+ if (status === "running") return true;
242
+
243
+ try {
244
+ for (const id of context.data.session.family(sessionID) ?? []) {
245
+ if (id === sessionID) continue;
246
+ try {
247
+ if (context.data.session.status(id) === "running") return true;
248
+ } catch {
249
+ // One unreadable child must not hide a running sibling.
250
+ }
251
+ }
252
+ } catch {
253
+ // No subagent status on this host; the shell check below still applies.
254
+ }
255
+
256
+ try {
257
+ // `listBySession` is on the reactive client the host hands the plugin,
258
+ // but not on every published type surface, so it is reached defensively:
259
+ // a host without it still falls back to the session's own status.
260
+ const shellApi = context.data.shell as unknown as
261
+ | { listBySession?: (id: string) => readonly unknown[] }
262
+ | undefined;
263
+ const shells = shellApi?.listBySession?.(sessionID);
264
+ if (shells !== undefined && shells.some((entry) => asRecord(entry)?.status === "running")) return true;
265
+ } catch {
266
+ // Same again: unreadable shells just mean no shell signal.
267
+ }
268
+
269
+ return status === undefined ? undefined : false;
270
+ };
271
+
168
272
  // Throughput of the last completed turn. The host records when streaming
169
273
  // finished, so this is measured rather than estimated from wall-clock.
170
274
  const lastTps = (sessionID: string): number | undefined => {
@@ -199,14 +303,30 @@ export default Plugin.define({
199
303
  };
200
304
 
201
305
  // A ticker exists only for clock-derived rows; everything else updates from
202
- // the host's own events. `refresh: 0` opts out of it entirely.
203
- const [frame, setFrame] = createSignal(0);
204
- const timer =
205
- config.refresh > 0 ? setInterval(() => setFrame((value) => value + 1), config.refresh) : undefined;
306
+ // the host's own events. It is skipped entirely when nothing on the rail
307
+ // animates, and `refresh: 0` opts out regardless. The tick has to live in the
308
+ // host's reactive graph rather than ours, or it re-renders nothing at all.
309
+ const animated =
310
+ config.sidebar.enabled &&
311
+ config.sidebar.rows.some((name) => (ANIMATED_FIELDS as readonly string[]).includes(name));
312
+ const ticker = startTicker(context, animated ? config.refresh : 0);
206
313
 
207
314
  // Read session state inside the render so the rail stays live: cost and
208
315
  // tokens climb as the session runs, and the branch appears once VCS
209
316
  // resolves. Nothing here writes, requests, or leaves the process.
317
+ // Only the worst is ever drawn: the rail has one line for this, and two
318
+ // simultaneous observations is one problem with two symptoms.
319
+ //
320
+ // Returns a plain string, themed exactly like every other live row. The
321
+ // annunciator carries its meaning in its glyph, not in a colour of its own:
322
+ // a row that suddenly brightens reads as a different kind of thing rather
323
+ // than as the same panel telling you something.
324
+ const announce = (sessionID: string): string | undefined => {
325
+ if (!config.caution.enabled) return undefined;
326
+ const top = worstCaution(cautionsOf(sessionID, Date.now()));
327
+ return top === undefined ? undefined : cautionText(top, config.glyphs);
328
+ };
329
+
210
330
  const snapshot = (sessionID: string): StatSource => {
211
331
  const location = context.location ?? context.data.location.default();
212
332
  const session = context.data.session.get(sessionID) as SessionLike | undefined;
@@ -214,32 +334,80 @@ export default Plugin.define({
214
334
 
215
335
  return {
216
336
  ...session,
337
+ caution: announce(sessionID),
217
338
  branch: context.data.location.vcs.info(location)?.branch?.current,
218
339
  tree: treeTotals(sessionID, session?.cost),
219
340
  context: contextUsage(sessionID, session?.model),
220
341
  project: projectTotals(),
221
342
  status: statusOf(sessionID),
343
+ busy: busy(sessionID),
222
344
  perms: permsOf(sessionID),
223
345
  tps: lastTps(sessionID),
224
346
  spark: sparkValues(sessionID),
225
347
  elapsedMs: sessionElapsed(session),
226
348
  turns,
227
- // Read the tick so the slot re-runs each frame.
228
- frame: frame(),
349
+ // Read the tick inside the render so the host registers a dependency on
350
+ // it; that read is what makes the rail re-run on the ticker's schedule.
351
+ frame: ticker?.frame ?? 0,
229
352
  };
230
353
  };
231
354
 
355
+ // The toast is opt-in and deliberately not the signal — the rail is. It
356
+ // fires on the transition into a caution, once per distinct problem, and
357
+ // re-arms when the session goes quiet, so a persistent hang cannot nag.
358
+ // Reading state on a timer rather than inside the render keeps the render a
359
+ // pure function of what it was given.
360
+ let watchedSession: string | undefined;
361
+ let toastedKey: string | undefined;
362
+ let watchTimer: ReturnType<typeof setInterval> | undefined;
363
+
364
+ if (config.caution.enabled && config.caution.toast) {
365
+ watchTimer = setInterval(() => {
366
+ const sessionID = watchedSession;
367
+ if (sessionID === undefined) return;
368
+ try {
369
+ const top = worstCaution(cautionsOf(sessionID, Date.now()));
370
+ if (top === undefined || top.severity !== "caution") {
371
+ toastedKey = undefined;
372
+ return;
373
+ }
374
+ if (top.key === toastedKey) return;
375
+ toastedKey = top.key;
376
+ context.ui.toast.show({
377
+ title: "Flight Deck",
378
+ message: cautionDetail(top),
379
+ variant: "warning",
380
+ });
381
+ } catch {
382
+ // A warning must never be able to break the panel it warns about.
383
+ }
384
+ }, config.refresh > 0 ? config.refresh : 1_000);
385
+ }
386
+
232
387
  if (config.sidebar.enabled) {
233
388
  releases.push(
234
389
  context.ui.slot({
235
390
  append: "sidebar.content",
236
391
  render: ({ sessionID }) => {
237
- const lines = sidebarLines(config, snapshot(sessionID));
392
+ // The annunciator is drawn from a timer, so the toast watcher needs
393
+ // to know which session is on screen. Reading the frame is what
394
+ // subscribes this render to the host's tick — without it nothing
395
+ // re-runs between host events, and a stall is precisely the failure
396
+ // that produces no host events at all.
397
+ watchedSession = sessionID;
398
+ void ticker?.frame;
399
+
400
+ const source = snapshot(sessionID);
401
+ const lines = sidebarLines(config, source);
238
402
  if (lines.length === 0) return null;
239
403
  const offset = Math.min(liveRowOffset(config), lines.length);
404
+
240
405
  return (
241
406
  // No padding here: the host already lays out and pads the sidebar,
242
407
  // so adding our own would push the rows out of alignment with it.
408
+ //
409
+ // Every live row gets the same token, the annunciator included. It
410
+ // is the same panel; only the glyph changes.
243
411
  <box flexDirection="column">
244
412
  {lines.map((line, index) => (
245
413
  <text fg={index < offset ? context.theme.text.default : context.theme.text.subdued}>{line}</text>
@@ -261,7 +429,9 @@ export default Plugin.define({
261
429
  }
262
430
 
263
431
  return () => {
264
- if (timer !== undefined) clearInterval(timer);
432
+ if (watchTimer !== undefined) clearInterval(watchTimer);
433
+ watchTimer = undefined;
434
+ ticker?.dispose();
265
435
  for (const release of releases) release();
266
436
  };
267
437
  },
@@ -18,7 +18,7 @@ import { statRows, type StatSource } from "./stats.js";
18
18
  */
19
19
  export function sidebarLines(config: FlightDeckConfig, source: StatSource = {}): readonly string[] {
20
20
  if (!config.sidebar.enabled) return [];
21
- return [...config.sidebar.lines, ...statRows(config.sidebar.rows, source)].slice(0, MAX_LINES);
21
+ return [...config.sidebar.lines, ...statRows(config.sidebar.rows, source, config.layout)].slice(0, MAX_LINES);
22
22
  }
23
23
 
24
24
  /** Footer text to render, or `undefined` when the footer rail is disabled. */
package/src/tui/stats.ts CHANGED
@@ -30,6 +30,14 @@ export interface StatProject {
30
30
 
31
31
  /** The subset of a session snapshot the rail reads. All fields are untrusted. */
32
32
  export interface StatSource {
33
+ /**
34
+ * The annunciator line, precomputed by the caller.
35
+ *
36
+ * A plain string on purpose: the rules that decide whether something is wrong
37
+ * live in ./caution.ts and need the clock and the session snapshot, not a
38
+ * formatting function. Severity is already encoded in the glyph.
39
+ */
40
+ readonly caution?: unknown;
33
41
  readonly agent?: unknown;
34
42
  readonly model?: unknown;
35
43
  readonly cost?: unknown;
@@ -39,6 +47,8 @@ export interface StatSource {
39
47
  readonly context?: unknown;
40
48
  readonly project?: unknown;
41
49
  readonly status?: unknown;
50
+ /** True when anything is working: this session, a subagent, or a shell. */
51
+ readonly busy?: unknown;
42
52
  readonly perms?: unknown;
43
53
  readonly tps?: unknown;
44
54
  readonly elapsedMs?: unknown;
@@ -51,6 +61,7 @@ export interface StatSource {
51
61
 
52
62
  /** Fields a user may name in `sidebar.rows`, in the order they are documented. */
53
63
  export const STAT_FIELDS = [
64
+ "caution",
54
65
  "status",
55
66
  "agent",
56
67
  "model",
@@ -71,17 +82,39 @@ export const STAT_FIELDS = [
71
82
 
72
83
  export type StatField = (typeof STAT_FIELDS)[number];
73
84
 
85
+ /**
86
+ * Fields whose value only ever changes on a clock tick.
87
+ *
88
+ * The ticker exists to animate these. When none of them is on screen there is
89
+ * nothing to animate, so the plugin does not start a timer at all.
90
+ *
91
+ * `caution` belongs here for a stronger reason than the others: its whole job is
92
+ * noticing that time has passed without anything happening, so without a tick
93
+ * its thresholds could never be crossed on screen.
94
+ */
95
+ export const ANIMATED_FIELDS = ["caution", "status", "elapsed"] as const;
96
+
74
97
  export function isStatField(value: string): value is StatField {
75
98
  return (STAT_FIELDS as readonly string[]).includes(value);
76
99
  }
77
100
 
78
- const LABEL_WIDTH = 10;
79
- const BAR_WIDTH = 10;
80
-
81
- function row(label: string, value: string): string {
82
- return `${label.padEnd(LABEL_WIDTH)}${value}`;
101
+ /**
102
+ * Row geometry, overridable per call.
103
+ *
104
+ * A structural type rather than an import of `FlightDeckConfig`: ./config.ts
105
+ * imports this module, so reaching back into it would create a cycle. The
106
+ * shapes are compatible, so the config passes straight through.
107
+ */
108
+ export interface LayoutHint {
109
+ readonly labelWidth?: number;
110
+ readonly barWidth?: number;
111
+ readonly sparkWidth?: number;
83
112
  }
84
113
 
114
+ const DEFAULT_LABEL_WIDTH = 10;
115
+ const DEFAULT_BAR_WIDTH = 10;
116
+ const DEFAULT_SPARK_WIDTH = 12;
117
+
85
118
  function asRecord(value: unknown): Record<string, unknown> | undefined {
86
119
  return typeof value === "object" && value !== null && !Array.isArray(value)
87
120
  ? (value as Record<string, unknown>)
@@ -123,13 +156,25 @@ export function formatDuration(ms: number): string {
123
156
  }
124
157
 
125
158
  /** A ten-cell gauge, so a percentage is readable at a glance rather than parsed. */
126
- export function fuelBar(ratio: number): string {
127
- const filled = Math.max(0, Math.min(BAR_WIDTH, Math.round(ratio * BAR_WIDTH)));
128
- return `${"█".repeat(filled)}${"░".repeat(BAR_WIDTH - filled)}`;
159
+ export function fuelBar(ratio: number, width: number = DEFAULT_BAR_WIDTH): string {
160
+ const cells = Math.max(1, Math.floor(width));
161
+ const filled = Math.max(0, Math.min(cells, Math.round(ratio * cells)));
162
+ return `${"█".repeat(filled)}${"░".repeat(cells - filled)}`;
129
163
  }
130
164
 
131
165
  const SPARK_LEVELS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"] as const;
132
166
 
167
+ /**
168
+ * Shorten a value for a narrow rail.
169
+ *
170
+ * The sidebar is roughly thirty-odd columns wide and the label already costs
171
+ * ten, so a resource path has to be cut. The ellipsis is deliberate: a silently
172
+ * truncated path reads as a complete one.
173
+ */
174
+ export function clip(text: string, max: number): string {
175
+ return text.length <= max ? text : `${text.slice(0, Math.max(1, max - 1))}…`;
176
+ }
177
+
133
178
  /** Braille frames, advanced by the ticker, shown only while the session runs. */
134
179
  const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
135
180
 
@@ -158,15 +203,41 @@ export function sparkline(values: readonly number[]): string {
158
203
  * shows `branch unknown` before the repo loads looks broken, while a rail
159
204
  * that simply grows a row when the data arrives looks alive.
160
205
  */
161
- export function statLine(field: string, source: StatSource): string | undefined {
206
+ export function statLine(
207
+ field: string,
208
+ source: StatSource,
209
+ layout: LayoutHint = {},
210
+ ): string | undefined {
211
+ // Bound here rather than at module scope so a config file can change the
212
+ // column width without every call site having to know about it.
213
+ const labelWidth = layout.labelWidth ?? DEFAULT_LABEL_WIDTH;
214
+ const barWidth = layout.barWidth ?? DEFAULT_BAR_WIDTH;
215
+ const sparkWidth = layout.sparkWidth ?? DEFAULT_SPARK_WIDTH;
216
+ const row = (label: string, value: string): string => `${label.padEnd(labelWidth)}${value}`;
217
+
162
218
  switch (field) {
219
+ case "caution": {
220
+ // Rendered only when the caller found something to say, which is what
221
+ // keeps a healthy session visually identical to one without the
222
+ // annunciator at all. The string already carries its glyph; nothing here
223
+ // knows or cares about severity.
224
+ const text = asText(source.caution);
225
+ return text === undefined ? undefined : row("caution", text);
226
+ }
163
227
  case "status": {
164
228
  const status = asText(source.status);
165
- if (status === undefined) return undefined;
229
+ if (status === undefined && source.busy === undefined) return undefined;
166
230
  // The spinner lives here rather than in a row of its own: an animated
167
231
  // glyph beside "running" says the same thing without spending a line.
168
- if (status !== "running") return row("status", "○ idle");
169
- const frame = asCount(source.frame) ?? 0;
232
+ //
233
+ // `busy` folds in work the session's own status misses — a subagent
234
+ // running in its own session, or a shell command still going — so the
235
+ // glyph only stops when there is genuinely nothing happening. A host that
236
+ // does not report it falls back to the session's own status.
237
+ if (source.busy !== true && status !== "running") return row("status", "○ idle");
238
+ // Floored at the boundary: a fractional frame would index the frame list
239
+ // with a non-integer and render `undefined`.
240
+ const frame = Math.floor(asCount(source.frame) ?? 0);
170
241
  return row("status", `${SPINNER[frame % SPINNER.length]} running`);
171
242
  }
172
243
  case "agent": {
@@ -186,7 +257,26 @@ export function statLine(field: string, source: StatSource): string | undefined
186
257
  }
187
258
  case "cost": {
188
259
  const cost = asCount(source.cost);
189
- return cost === undefined ? undefined : row("cost", formatCost(cost));
260
+ const tree = asRecord(source.tree);
261
+ const treeCost = asCount(tree?.cost);
262
+ const count = asCount(tree?.count);
263
+
264
+ // When subagents ran, this session's own cost understates the bill. Show
265
+ // the family total and the delta that produced it, rather than spending a
266
+ // second row on a number that contains the first. `total` still exists for
267
+ // anyone who wants the two figures on separate rows.
268
+ if (
269
+ cost !== undefined &&
270
+ treeCost !== undefined &&
271
+ count !== undefined &&
272
+ count > 0 &&
273
+ treeCost > cost
274
+ ) {
275
+ const plural = count === 1 ? "subagent" : "subagents";
276
+ return row("cost", `${formatCost(treeCost)} · +${formatCost(treeCost - cost)} · ${count} ${plural}`);
277
+ }
278
+ const value = cost ?? treeCost;
279
+ return value === undefined ? undefined : row("cost", formatCost(value));
190
280
  }
191
281
  case "total": {
192
282
  // Only worth a row once a subagent has actually run: subagent sessions are
@@ -236,12 +326,23 @@ export function statLine(field: string, source: StatSource): string | undefined
236
326
  const ratio = used / limit;
237
327
  // Show the percentage whenever the host reports it, but never a bar that
238
328
  // reads as more than full.
239
- return row("context", `${fuelBar(ratio)} ${Math.round(Math.min(1, ratio) * 100)}%`);
329
+ return row("context", `${fuelBar(ratio, barWidth)} ${Math.round(Math.min(1, ratio) * 100)}%`);
240
330
  }
241
331
  case "perms": {
242
- const perms = asCount(source.perms);
243
- if (perms === undefined || perms === 0) return undefined;
244
- return row("perms", perms === 1 ? "1 waiting" : `${perms} waiting`);
332
+ const perms = asRecord(source.perms);
333
+ const count = asCount(perms?.["count"]);
334
+ if (count === undefined || count === 0) return undefined;
335
+ const action = asText(perms?.["action"]);
336
+ const resource = asText(perms?.["resource"]);
337
+
338
+ // One request: name it, because that is the decision you are being asked
339
+ // to make. Several: the count leads, because the first request in the
340
+ // queue is not necessarily the one you are about to be shown.
341
+ if (count > 1) {
342
+ return row("perms", action === undefined ? `${count} waiting` : `${count} waiting · ${action}`);
343
+ }
344
+ if (action === undefined) return row("perms", "1 waiting");
345
+ return row("perms", resource === undefined ? action : `${action} · ${clip(resource, 22)}`);
245
346
  }
246
347
  case "elapsed": {
247
348
  const ms = asCount(source.elapsedMs);
@@ -255,8 +356,11 @@ export function statLine(field: string, source: StatSource): string | undefined
255
356
  }
256
357
  case "spark": {
257
358
  const values = Array.isArray(source.spark) ? source.spark.map((value) => asCount(value) ?? 0) : [];
258
- if (values.length < 2) return undefined;
259
- return row("spark", sparkline(values));
359
+ // The newest samples are the interesting ones, so a narrowed window keeps
360
+ // the recent shape rather than the oldest.
361
+ const windowed = values.slice(-Math.max(2, Math.floor(sparkWidth)));
362
+ if (windowed.length < 2) return undefined;
363
+ return row("spark", sparkline(windowed));
260
364
  }
261
365
  case "reasoning": {
262
366
  const reasoning = asCount(asRecord(source.tokens)?.reasoning);
@@ -274,10 +378,14 @@ export function statLine(field: string, source: StatSource): string | undefined
274
378
  }
275
379
 
276
380
  /** Render every named field that currently has data, in the given order. */
277
- export function statRows(fields: readonly string[], source: StatSource): readonly string[] {
381
+ export function statRows(
382
+ fields: readonly string[],
383
+ source: StatSource,
384
+ layout: LayoutHint = {},
385
+ ): readonly string[] {
278
386
  const rows: string[] = [];
279
387
  for (const field of fields) {
280
- const line = statLine(field, source);
388
+ const line = statLine(field, source, layout);
281
389
  if (line !== undefined) rows.push(line);
282
390
  }
283
391
  return rows;
@@ -0,0 +1,130 @@
1
+ // The animation tick that drives Flight Deck's clock-derived rows.
2
+ //
3
+ // Why this is not a `createSignal`:
4
+ //
5
+ // The host's Solid is compiled into the `opencode2` binary. This plugin
6
+ // resolves its own `solid-js` from the npm cache, because the plugin packaging
7
+ // model has plugins supply their own renderer peers. Those are two module
8
+ // instances, and Solid keeps its dependency tracking in module state — so a
9
+ // signal created in one instance is invisible to an effect owned by the other.
10
+ // A `setInterval` + `createSignal` ticker therefore advanced a counter that
11
+ // nothing was listening to: `elapsed` sat frozen and the spinner never turned.
12
+ //
13
+ // `context.storage.memory` is the documented bridge. It returns a store owned
14
+ // by the *host's* Solid, so writing it from a timer notifies the host's render,
15
+ // and reading it inside the slot render registers the dependency that makes the
16
+ // rail re-run on that schedule.
17
+ //
18
+ // This is the only state the plugin writes, and it is deliberately the
19
+ // smallest, most disposable surface available: ephemeral, in-process, scoped to
20
+ // this plugin, gone when the TUI exits. Not the durable store, not a session,
21
+ // not a file, not the network.
22
+ //
23
+ // The host is a beta and its store is reached across a version boundary, so
24
+ // everything about it is validated at runtime and every failure path degrades to
25
+ // "no ticker" rather than raising into the TUI.
26
+
27
+ /** The value kept in the host's memory store. A single monotonic counter. */
28
+ interface FrameState {
29
+ frame: number;
30
+ }
31
+
32
+ /** The store the host hands back: read-only to us, reactive to the host. */
33
+ interface FrameStore {
34
+ readonly frame?: unknown;
35
+ }
36
+
37
+ /** The mutation function the host hands back. */
38
+ type FrameUpdate = (mutation: (draft: FrameState) => void) => void;
39
+
40
+ /** The one host capability the ticker needs, so it stays trivially stubbable. */
41
+ export interface TickerHost {
42
+ readonly storage?: {
43
+ /**
44
+ * Typed as `unknown` on purpose: this is the one host call reached across a
45
+ * beta version boundary, so the shape is checked at runtime instead of
46
+ * trusted from a type that may not match the binary.
47
+ */
48
+ memory(key: string, options: { readonly initial: FrameState }): unknown;
49
+ };
50
+ }
51
+
52
+ export interface Ticker {
53
+ /**
54
+ * Current frame, read from the host's store.
55
+ *
56
+ * This must be read inside the slot render, while the host's reactive scope
57
+ * is active, or it will not register as a dependency and nothing will update.
58
+ */
59
+ readonly frame: number;
60
+ /** Stops the timer. Safe to call once; the plugin calls it on cleanup. */
61
+ dispose(): void;
62
+ }
63
+
64
+ /** Namespaced so it cannot collide with another plugin's memory keys. */
65
+ export const TICKER_KEY = "flight-deck.frame";
66
+
67
+ // Untrusted store values are normalised here rather than at the render, so a
68
+ // corrupt frame can never reach the spinner's array index.
69
+ function readFrame(store: FrameStore | undefined): number {
70
+ const value = store?.frame;
71
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : 0;
72
+ }
73
+
74
+ // A host whose store does not match the documented shape is treated as no store
75
+ // at all: half-opening one would throw on every tick instead of degrading.
76
+ function openStore(storage: NonNullable<TickerHost["storage"]>): { store: FrameStore; update: FrameUpdate } | undefined {
77
+ let opened: unknown;
78
+ try {
79
+ opened = storage.memory(TICKER_KEY, { initial: { frame: 0 } });
80
+ } catch {
81
+ return undefined;
82
+ }
83
+
84
+ if (!Array.isArray(opened) || opened.length < 2) return undefined;
85
+ const [store, update] = opened as [unknown, unknown];
86
+ if (store === null || typeof store !== "object") return undefined;
87
+ if (typeof update !== "function") return undefined;
88
+
89
+ return { store: store as FrameStore, update: update as FrameUpdate };
90
+ }
91
+
92
+ /**
93
+ * Start the animation tick, or return `undefined` when it is switched off.
94
+ *
95
+ * A missing or unusable host store is not an error: the rail then updates only
96
+ * on host events, which is exactly how it behaved before the ticker was fixed.
97
+ * Degrading quietly keeps a cosmetic panel from ever breaking the TUI.
98
+ */
99
+ export function startTicker(host: TickerHost | undefined, intervalMs: number): Ticker | undefined {
100
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0) return undefined;
101
+
102
+ const storage = host?.storage;
103
+ if (storage === undefined || typeof storage.memory !== "function") return undefined;
104
+
105
+ const opened = openStore(storage);
106
+ if (opened === undefined) return undefined;
107
+
108
+ let timer: ReturnType<typeof setInterval> | undefined = setInterval(() => {
109
+ try {
110
+ opened.update((draft) => {
111
+ draft.frame = readFrame(draft) + 1;
112
+ });
113
+ } catch {
114
+ // A store that starts failing mid-run must not raise on every tick
115
+ // forever. Put the timer down and let the rail fall back to host events.
116
+ if (timer !== undefined) clearInterval(timer);
117
+ timer = undefined;
118
+ }
119
+ }, intervalMs);
120
+
121
+ return {
122
+ get frame() {
123
+ return readFrame(opened.store);
124
+ },
125
+ dispose() {
126
+ if (timer !== undefined) clearInterval(timer);
127
+ timer = undefined;
128
+ },
129
+ };
130
+ }