oc-flight-deck 0.6.7 → 0.8.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.
@@ -0,0 +1,315 @@
1
+ // The Go usage model for the `go` row.
2
+ //
3
+ // Everything here is pure: no I/O, no timers, no hidden `Date.now()`. The poll
4
+ // bridge in ./go.ts owns the clock and the network; this module only turns the
5
+ // Zen Go usage payload into the small fixed window model the row renders.
6
+ // Keeping it pure is what lets both documented response shapes be exercised
7
+ // without a server, and keeps the row renderer a renderer.
8
+ //
9
+ // The verified live shape, and the older shapes kept as defence in depth,
10
+ // because the endpoint is young enough that none is frozen:
11
+ //
12
+ // (a) live — `{ usage: { rolling, weekly, monthly } }`, each window
13
+ // `{ status, percent, resetsAt }` where `percent` is 0–100 of
14
+ // the window USED and `resetsAt` is an ISO-8601 string;
15
+ // (b) flat — rolling/weekly/monthly usage + limit columns, updated-at
16
+ // timestamps, all siblings at the top level;
17
+ // (c) nested — `{ usage: { rolling, weekly, monthly } }`, `{ windows: [...] }`,
18
+ // or a bare array of `{ window, usage, limit, resetAt }` rows.
19
+ //
20
+ // Values are opaque numbers (integer micro-cents or counts). We never unit-
21
+ // convert here: only the ratio is derived, and a ratio needs no unit. A missing
22
+ // or non-positive limit leaves `ratio` undefined rather than inventing a
23
+ // percentage, so a broken payload can never render as a confident 100%.
24
+
25
+ import { asRecord, asText } from "./coerce.js";
26
+
27
+ export interface GoWindow {
28
+ readonly id: "5h" | "1w" | "1m";
29
+ readonly used?: number;
30
+ readonly limit?: number;
31
+ readonly ratio?: number;
32
+ readonly resetAtMs?: number;
33
+ /**
34
+ * Per-window health string. Additive: absent on the older shapes. Passed
35
+ * through only when it is a non-empty string.
36
+ */
37
+ readonly status?: string;
38
+ }
39
+
40
+ export interface GoUsage {
41
+ readonly windows: readonly GoWindow[];
42
+ }
43
+
44
+ /** Canonical order, so the row always renders 5h then 1w then 1m. */
45
+ const WINDOW_ORDER: readonly GoWindow["id"][] = ["5h", "1w", "1m"];
46
+
47
+ function asFiniteNumber(value: unknown): number | undefined {
48
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
49
+ }
50
+
51
+ function firstFinite(...candidates: readonly unknown[]): number | undefined {
52
+ for (const candidate of candidates) {
53
+ const value = asFiniteNumber(candidate);
54
+ if (value !== undefined) return value;
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ /**
60
+ * Read an absolute instant in milliseconds from either an epoch number or an
61
+ * ISO-8601 string.
62
+ *
63
+ * The verified live payload carries `resetsAt` as an ISO-8601 string, while the
64
+ * older defensive shapes used an epoch number. A string that `Date.parse` cannot
65
+ * read (or that is not a string at all) yields `undefined` rather than a
66
+ * fabricated instant, so a malformed reset never becomes a confident hint.
67
+ */
68
+ function asInstantMs(value: unknown): number | undefined {
69
+ const numeric = asFiniteNumber(value);
70
+ if (numeric !== undefined) return numeric;
71
+ const text = asText(value);
72
+ if (text === undefined) return undefined;
73
+ const parsed = Date.parse(text);
74
+ return Number.isFinite(parsed) ? parsed : undefined;
75
+ }
76
+
77
+ /** The first candidate that reads as an absolute instant, or `undefined`. */
78
+ function firstInstant(...candidates: readonly unknown[]): number | undefined {
79
+ for (const candidate of candidates) {
80
+ const value = asInstantMs(candidate);
81
+ if (value !== undefined) return value;
82
+ }
83
+ return undefined;
84
+ }
85
+
86
+ /**
87
+ * The verified live shape reports usage as `percent`, a number 0–100 of the
88
+ * window already used, rather than a `used`/`limit` pair. `0` is a real fresh
89
+ * window (ratio 0), not a missing value; a non-number such as the string `"79"`
90
+ * is dropped rather than coerced, so a mistyped payload cannot read as usage.
91
+ *
92
+ * A percent above 100 is CLAMPED to a ratio of 1, never rejected. Over-the-limit
93
+ * is precisely the state this row exists to reveal, so dropping the window would
94
+ * hide the worst case; a full dial plus the error tone is the honest read. The
95
+ * ratio is clamped into `[0, 1]` here so no caller has to wonder how full "150%"
96
+ * is, while a negative or non-finite percent is still dropped as garbage.
97
+ */
98
+ function ratioFromPercent(value: unknown): number | undefined {
99
+ const percent = asFiniteNumber(value);
100
+ if (percent === undefined || percent < 0) return undefined;
101
+ return Math.min(1, percent / 100);
102
+ }
103
+
104
+ /**
105
+ * Map a window name to one of the three known ids.
106
+ *
107
+ * Names are lowercased and stripped of separators so `5-hour`, `5h`, and
108
+ * `5h_rolling` all land on the same id; an unknown name is dropped so a new
109
+ * server-side window cannot silently masquerade as one the row understands.
110
+ */
111
+ function windowIdFrom(value: unknown): GoWindow["id"] | undefined {
112
+ const text = asText(value);
113
+ if (text === undefined) return undefined;
114
+ const key = text.toLowerCase().replace(/[^a-z0-9]/g, "");
115
+ if (key.startsWith("rolling") || key === "5h" || key === "5hour" || key === "session") return "5h";
116
+ if (key.startsWith("weekly") || key === "1w" || key === "week" || key === "7d") return "1w";
117
+ if (key.startsWith("monthly") || key === "1m" || key === "month" || key === "30d") return "1m";
118
+ return undefined;
119
+ }
120
+
121
+ /** `used / limit` only when both are known and the limit is strictly positive. */
122
+ function ratioOf(used: number | undefined, limit: number | undefined): number | undefined {
123
+ if (used === undefined || limit === undefined || limit <= 0) return undefined;
124
+ return used / limit;
125
+ }
126
+
127
+ /**
128
+ * Assemble a window from already-extracted parts, omitting rather than
129
+ * fabricating what is unknown. Returns `undefined` when the id is unknown or
130
+ * neither a use nor a limit was readable — a bare timestamp is not a window.
131
+ */
132
+ function buildWindow(
133
+ id: GoWindow["id"] | undefined,
134
+ used: number | undefined,
135
+ limit: number | undefined,
136
+ resetAtMs: number | undefined,
137
+ explicitRatio?: number,
138
+ status?: string,
139
+ ): GoWindow | undefined {
140
+ if (id === undefined) return undefined;
141
+ // An explicit ratio (from `percent`) wins over `used / limit`; `??` keeps a
142
+ // legitimate explicit zero. A window with no use, no limit and no ratio is
143
+ // not a window: a bare timestamp, name or status must not render as one.
144
+ const ratio = explicitRatio ?? ratioOf(used, limit);
145
+ if (used === undefined && limit === undefined && ratio === undefined) return undefined;
146
+ const result: {
147
+ -readonly [K in keyof GoWindow]: GoWindow[K];
148
+ } = { id };
149
+ if (used !== undefined) result.used = used;
150
+ if (limit !== undefined) result.limit = limit;
151
+ if (ratio !== undefined) result.ratio = ratio;
152
+ if (resetAtMs !== undefined) result.resetAtMs = resetAtMs;
153
+ if (status !== undefined) result.status = status;
154
+ return result;
155
+ }
156
+
157
+ /**
158
+ * Normalize one window value: a bare number (count, no known limit) or an
159
+ * object carrying the use/limit/reset columns under any documented name.
160
+ */
161
+ function normalizeWindowValue(value: unknown, idHint?: GoWindow["id"]): GoWindow | undefined {
162
+ if (typeof value === "number") {
163
+ // A keyed map may map a window straight to its count. No limit is known,
164
+ // so no ratio — buildWindow leaves it undefined.
165
+ return buildWindow(idHint, asFiniteNumber(value), undefined, undefined);
166
+ }
167
+ const record = asRecord(value);
168
+ if (record === undefined) return undefined;
169
+ const id = idHint ?? windowIdFrom(record.window) ?? windowIdFrom(record.id) ?? windowIdFrom(record.name);
170
+ const used = firstFinite(record.usage, record.used, record.value, record.current, record.count);
171
+ const limit = firstFinite(record.limit, record.max, record.total, record.cap, record.quota);
172
+ // Only an explicit absolute timestamp becomes `resetAtMs`. `resetInSec` and
173
+ // `resetIn` are relative, and Stage 1 leaves them unhandled on purpose: a
174
+ // relative field read against an unknown clock is worse than no reset hint.
175
+ // An ISO-8601 `resetsAt` (the verified live shape) is accepted alongside the
176
+ // older epoch number.
177
+ const resetAtMs = firstInstant(record.resetAtMs, record.resetsAt, record.resetAt);
178
+ // The verified live shape's `percent` is a usage fraction with no limit pair.
179
+ const ratio = ratioFromPercent(record.percent);
180
+ const status = asText(record.status);
181
+ return buildWindow(id, used, limit, resetAtMs, ratio, status);
182
+ }
183
+
184
+ /**
185
+ * The flat shape's rolling/weekly/monthly columns. The synthetic window id is
186
+ * supplied because the flat payload has no per-window name. Reset columns are
187
+ * not documented for this shape, so only a defensively-named absolute one is
188
+ * read; the `time*Updated` columns are "last updated", not "resets", and are
189
+ * deliberately ignored.
190
+ */
191
+ function normalizeFlatWindow(
192
+ top: Record<string, unknown>,
193
+ id: GoWindow["id"],
194
+ usedKey: string,
195
+ limitKey: string,
196
+ prefix: string,
197
+ ): GoWindow | undefined {
198
+ const used = asFiniteNumber(top[usedKey]);
199
+ const limit = asFiniteNumber(top[limitKey]);
200
+ const resetAtMs = firstInstant(top[`${prefix}ResetAtMs`], top[`${prefix}ResetsAt`], top[`${prefix}ResetAt`]);
201
+ return buildWindow(id, used, limit, resetAtMs);
202
+ }
203
+
204
+ /** Collect windows out of a name-keyed map, e.g. `{ rolling: {...} }`. */
205
+ function collectKeyed(record: Record<string, unknown>, push: (window: GoWindow | undefined) => void): void {
206
+ for (const [key, value] of Object.entries(record)) {
207
+ const id = windowIdFrom(key);
208
+ if (id === undefined) continue;
209
+ push(normalizeWindowValue(value, id));
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Normalize untrusted Go usage output, or `undefined` when there is no usable
215
+ * data. Never throws: every field is coerced and everything unrecognized is
216
+ * dropped, so drift degrades to the placeholder instead of the render.
217
+ */
218
+ export function normalizeGoUsage(raw: unknown): GoUsage | undefined {
219
+ try {
220
+ const windows: GoWindow[] = [];
221
+ const seen = new Set<GoWindow["id"]>();
222
+ const push = (window: GoWindow | undefined): void => {
223
+ if (window === undefined || seen.has(window.id)) return;
224
+ seen.add(window.id);
225
+ windows.push(window);
226
+ };
227
+
228
+ if (Array.isArray(raw)) {
229
+ for (const entry of raw) push(normalizeWindowValue(entry));
230
+ } else {
231
+ const top = asRecord(raw);
232
+ if (top === undefined) return undefined;
233
+
234
+ push(normalizeFlatWindow(top, "5h", "rollingUsage", "rollingLimit", "rolling"));
235
+ push(normalizeFlatWindow(top, "1w", "weeklyUsage", "weeklyLimit", "weekly"));
236
+ push(normalizeFlatWindow(top, "1m", "monthlyUsage", "monthlyLimit", "monthly"));
237
+
238
+ const usage = asRecord(top.usage);
239
+ if (usage !== undefined) collectKeyed(usage, push);
240
+
241
+ const list = top.windows;
242
+ if (Array.isArray(list)) {
243
+ for (const entry of list) push(normalizeWindowValue(entry));
244
+ } else {
245
+ const keyed = asRecord(list);
246
+ if (keyed !== undefined) collectKeyed(keyed, push);
247
+ }
248
+
249
+ // A payload that is itself a single unnamed window object.
250
+ if (windows.length === 0) push(normalizeWindowValue(top));
251
+ }
252
+
253
+ if (windows.length === 0) return undefined;
254
+ windows.sort((a, b) => WINDOW_ORDER.indexOf(a.id) - WINDOW_ORDER.indexOf(b.id));
255
+ return { windows };
256
+ } catch {
257
+ return undefined;
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Fraction of a window's limit at which the row switches to its error tone.
263
+ *
264
+ * Chosen below 1 so the row warns while there is still headroom to act (an
265
+ * account-wide limit cannot be topped up mid-run), and above the 0.5 midpoint
266
+ * so ordinary use does not read as distress.
267
+ */
268
+ export const GO_ERROR_RATIO = 0.9;
269
+
270
+ /**
271
+ * The per-window status values treated as benign.
272
+ *
273
+ * NOTE: the semantics of `status` are UNVERIFIED — only `"ok"` has been observed
274
+ * live on `GET /zen/go/v1/usage`. An unknown non-empty status is deliberately
275
+ * NOT in this set, so it renders as offending: a quota window that is not
276
+ * reporting `ok` is worth a red dial rather than a silent pass.
277
+ */
278
+ export const GO_OK_STATUSES: readonly string[] = ["ok"];
279
+
280
+ /**
281
+ * The row tone: `error` at or above {@link GO_ERROR_RATIO}, or when a window
282
+ * carries a non-benign status, else `normal`.
283
+ */
284
+ export function goTone(window: GoWindow): "error" | "normal" {
285
+ if (window.ratio !== undefined && window.ratio >= GO_ERROR_RATIO) return "error";
286
+ const status = window.status;
287
+ if (status !== undefined && status !== "" && !GO_OK_STATUSES.includes(status)) return "error";
288
+ return "normal";
289
+ }
290
+
291
+ function formatRemaining(ms: number): string {
292
+ const seconds = Math.ceil(ms / 1000);
293
+ if (seconds < 60) return `${seconds}s`;
294
+ const minutes = Math.ceil(ms / 60_000);
295
+ if (minutes < 60) return `${minutes}m`;
296
+ const hours = Math.ceil(ms / 3_600_000);
297
+ if (hours < 24) return `${hours}h`;
298
+ return `${Math.ceil(ms / 86_400_000)}d`;
299
+ }
300
+
301
+ /**
302
+ * A short "time until reset" suffix for the error tone, or `undefined`.
303
+ *
304
+ * Only shown when the window is actually in error and the reset time is a
305
+ * known future instant — a reset hint beside a calm bar is noise, and one in
306
+ * the past would read as a promise already broken.
307
+ */
308
+ export function goResetSuffix(window: GoWindow, nowMs: number): string | undefined {
309
+ if (goTone(window) !== "error") return undefined;
310
+ const resetAtMs = window.resetAtMs;
311
+ if (resetAtMs === undefined || !Number.isFinite(resetAtMs) || !Number.isFinite(nowMs)) return undefined;
312
+ const remaining = resetAtMs - nowMs;
313
+ if (remaining <= 0) return undefined;
314
+ return ` · ${formatRemaining(remaining)}`;
315
+ }
package/src/tui/go.ts ADDED
@@ -0,0 +1,266 @@
1
+ // Live Zen Go usage for the Flight Deck `go` row.
2
+ //
3
+ // This is the poll bridge only. The model it writes (./go-usage.ts) is pure; the
4
+ // row renderer is Stage 2. Shape is deliberately cloned from ./guard.ts — poll
5
+ // into the host's memory store, expose a reactive getter, never throw — with
6
+ // the differences the account-wide scope forces:
7
+ //
8
+ // * Guard is per-session, so it waits for `follow(sessionID)` before fetching.
9
+ // Go usage is account-wide: one API key, one shared quota, no session to
10
+ // target — so the timer starts at construction and there is no `follow`.
11
+ // * The key is read on every poll through the same env accessor the Zen Go
12
+ // client uses, so a key loaded or rotated after startup is picked up
13
+ // without a restart.
14
+ //
15
+ // Why the store bridge at all is documented in ./guard.ts and ./ticker.ts: the
16
+ // host's Solid and the plugin's are separate module instances, so only the
17
+ // host-owned `context.storage.memory` store can wake the host render.
18
+ //
19
+ // The bridge never throws. Any failure — no store, no key, refused request,
20
+ // non-OK status, malformed JSON — stores `null`, which the getter reads as
21
+ // `undefined` so the persist layer renders the placeholder. A missing key is
22
+ // explicitly not an error: it is the row's documented "no key" dash path.
23
+
24
+ import { normalizeGoUsage, type GoUsage } from "./go-usage.js";
25
+
26
+ /** The value kept in the host's memory store. Null means "no data". */
27
+ interface GoStoreState {
28
+ value: GoUsage | null;
29
+ }
30
+
31
+ /** The store the host hands back: read-only to us, reactive to the host. */
32
+ interface GoStore {
33
+ readonly value?: unknown;
34
+ }
35
+
36
+ /** The mutation function the host hands back. */
37
+ type GoUpdate = (mutation: (draft: GoStoreState) => void) => void;
38
+
39
+ /** The one host capability the bridge needs, so it stays trivially stubbable. */
40
+ export interface GoHost {
41
+ readonly storage?: {
42
+ /**
43
+ * Typed as `unknown` on the return on purpose: this is reached across a
44
+ * beta version boundary, so the shape is checked at runtime instead of
45
+ * trusted from a type that may not match the binary.
46
+ */
47
+ memory(key: string, options: { readonly initial: GoStoreState }): unknown;
48
+ };
49
+ }
50
+
51
+ /** Injectable key accessor and fetch, so tests never touch the network or env. */
52
+ export interface GoDeps {
53
+ readonly key?: () => string | undefined;
54
+ readonly fetchJson?: (url: string, init: RequestInit) => Promise<unknown>;
55
+ }
56
+
57
+ interface GoBridge {
58
+ /**
59
+ * Current usage, read from the host's store.
60
+ *
61
+ * This must be read inside the slot render, while the host's reactive scope
62
+ * is active, or it will not register as a dependency and nothing will update.
63
+ * `undefined` means no data, so the persist layer renders the placeholder.
64
+ */
65
+ readonly usage: GoUsage | undefined;
66
+ /** Stops the timer. Safe to call more than once. */
67
+ dispose(): void;
68
+ }
69
+
70
+ /** Namespaced so it cannot collide with another plugin's memory keys. */
71
+ export const GO_KEY = "flight-deck.go";
72
+
73
+ /**
74
+ * How often the bridge re-reads usage.
75
+ *
76
+ * Account-wide quota moves far more slowly than per-session telemetry, and the
77
+ * endpoint is remote, so a poll per minute keeps the row fresh without a
78
+ * request storm. Deliberately not `config.refresh` (that drives the spinner).
79
+ */
80
+ export const GO_POLL_MS = 60_000;
81
+
82
+ /** The Zen Go usage endpoint. Fixed: usage is account-wide, not per-session. */
83
+ export const GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
84
+
85
+ /** The env var the Zen Go client reads its key from, matched by name only. */
86
+ export const GO_KEY_ENV = "OPENCODE_GO_API_KEY";
87
+
88
+ const GO_TIMEOUT_MS = 10_000;
89
+
90
+ /**
91
+ * Fetch and parse a usage payload. A non-OK response throws so the poll's one
92
+ * catch handles both transport and status failures; the body is only parsed
93
+ * once the status is known good.
94
+ */
95
+ async function defaultFetchJson(url: string, init: RequestInit): Promise<unknown> {
96
+ const response = await fetch(url, init);
97
+ if (!response.ok) throw new Error(`go usage: HTTP ${response.status}`);
98
+ return response.json();
99
+ }
100
+
101
+ // A host whose store does not match the documented shape is treated as no store
102
+ // at all: half-opening one would throw on every poll instead of degrading.
103
+ // Validated exactly as ./ticker.ts and ./guard.ts validate theirs.
104
+ function openStore(storage: NonNullable<GoHost["storage"]>): { store: GoStore; update: GoUpdate } | undefined {
105
+ let opened: unknown;
106
+ try {
107
+ opened = storage.memory(GO_KEY, { initial: { value: null } });
108
+ } catch {
109
+ return undefined;
110
+ }
111
+
112
+ if (!Array.isArray(opened) || opened.length < 2) return undefined;
113
+ const [store, update] = opened as [unknown, unknown];
114
+ if (store === null || typeof store !== "object") return undefined;
115
+ if (typeof update !== "function") return undefined;
116
+
117
+ return { store: store as GoStore, update: update as GoUpdate };
118
+ }
119
+
120
+ function readUsage(store: GoStore | undefined): GoUsage | undefined {
121
+ try {
122
+ const value = store?.value;
123
+ if (value === null || value === undefined) return undefined;
124
+ return normalizeGoUsage(value);
125
+ } catch {
126
+ return undefined;
127
+ }
128
+ }
129
+
130
+ function writeValue(opened: { store: GoStore; update: GoUpdate }, value: GoUsage | null): boolean {
131
+ try {
132
+ opened.update((draft) => {
133
+ draft.value = value;
134
+ });
135
+ return true;
136
+ } catch {
137
+ return false;
138
+ }
139
+ }
140
+
141
+ function resolveKeyFn(deps: GoDeps | undefined): () => string | undefined {
142
+ if (deps !== undefined) {
143
+ try {
144
+ if (typeof deps.key === "function") return deps.key;
145
+ } catch {
146
+ // fall through to the env accessor
147
+ }
148
+ }
149
+ return () => process.env[GO_KEY_ENV];
150
+ }
151
+
152
+ function resolveFetchJson(deps: GoDeps | undefined): (url: string, init: RequestInit) => Promise<unknown> {
153
+ if (deps !== undefined) {
154
+ try {
155
+ if (typeof deps.fetchJson === "function") return deps.fetchJson;
156
+ } catch {
157
+ // fall through to the real fetch
158
+ }
159
+ }
160
+ return defaultFetchJson;
161
+ }
162
+
163
+ /**
164
+ * Start polling Go usage into the host's memory store, or return `undefined`
165
+ * when there is no usable store.
166
+ *
167
+ * Unlike ./guard.ts there is no `follow`: usage is account-wide, so the timer
168
+ * starts here and reads the key afresh on every poll. The first poll fires
169
+ * immediately so the row populates without waiting a full interval.
170
+ *
171
+ * Assumption: `deps` is a test-only override. Production omits it, so the
172
+ * accessor is `process.env[GO_KEY_ENV]` on each poll (late keys recover) and
173
+ * the request is the real `fetch` with a bounded timeout.
174
+ */
175
+ export function startGoBridge(
176
+ host: GoHost | undefined,
177
+ deps?: GoDeps | undefined,
178
+ intervalMs: number = GO_POLL_MS,
179
+ ): GoBridge | undefined {
180
+ const storage = host?.storage;
181
+ if (host === undefined || storage === undefined || typeof storage.memory !== "function") return undefined;
182
+
183
+ const opened = openStore(storage);
184
+ if (opened === undefined) return undefined;
185
+
186
+ const cadence = Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : GO_POLL_MS;
187
+ const keyFn = resolveKeyFn(deps);
188
+ const fetchJson = resolveFetchJson(deps);
189
+
190
+ let timer: ReturnType<typeof setInterval> | undefined;
191
+ // Generation invalidated on dispose, so a poll that outlives its bridge —
192
+ // after disposal or a hot reload where the host store is shared — cannot
193
+ // overwrite newer data.
194
+ let generation = 0;
195
+ // Monotonic request sequence so overlapping polls resolve in start order, not
196
+ // finish order: only the newest request of the current generation may write.
197
+ let nextSeq = 0;
198
+ let latestSeq = 0;
199
+ let disposed = false;
200
+
201
+ const stopTimer = (): void => {
202
+ if (timer !== undefined) clearInterval(timer);
203
+ timer = undefined;
204
+ };
205
+
206
+ const poll = async (): Promise<void> => {
207
+ if (disposed) return;
208
+ const myGeneration = generation;
209
+ const mySeq = ++nextSeq;
210
+ latestSeq = mySeq;
211
+ const stillCurrent = () => myGeneration === generation && mySeq === latestSeq && !disposed;
212
+
213
+ let key: string | undefined;
214
+ try {
215
+ key = keyFn();
216
+ } catch {
217
+ key = undefined;
218
+ }
219
+ // No key is the row's "no key" dash path, not an error: store null and
220
+ // make no request, so a keyless install never touches the endpoint.
221
+ if (typeof key !== "string" || key.length === 0) {
222
+ if (!stillCurrent()) return;
223
+ if (!writeValue(opened, null)) stopTimer();
224
+ return;
225
+ }
226
+
227
+ let raw: unknown;
228
+ try {
229
+ raw = await fetchJson(GO_USAGE_URL, {
230
+ headers: { Authorization: `Bearer ${key}` },
231
+ signal: AbortSignal.timeout(GO_TIMEOUT_MS),
232
+ });
233
+ } catch {
234
+ // Refused, timed out, non-OK status, or a transport failure: no data,
235
+ // not an error.
236
+ if (!stillCurrent()) return;
237
+ if (!writeValue(opened, null)) stopTimer();
238
+ return;
239
+ }
240
+ if (!stillCurrent()) return;
241
+ let normalized: GoUsage | null;
242
+ try {
243
+ normalized = normalizeGoUsage(raw) ?? null;
244
+ } catch {
245
+ normalized = null;
246
+ }
247
+ if (!writeValue(opened, normalized)) stopTimer();
248
+ };
249
+
250
+ timer = setInterval(() => {
251
+ void poll();
252
+ }, cadence);
253
+ // Populate the row now instead of after the first full cadence.
254
+ void poll();
255
+
256
+ return {
257
+ get usage() {
258
+ return readUsage(opened.store);
259
+ },
260
+ dispose() {
261
+ disposed = true;
262
+ generation += 1;
263
+ stopTimer();
264
+ },
265
+ };
266
+ }