oc-flight-deck 0.6.6 → 0.7.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/README.md +9 -6
- package/flight-deck.example.jsonc +16 -7
- package/flight-deck.schema.json +5 -5
- package/package.json +1 -1
- package/src/tui/active-elapsed.ts +32 -5
- package/src/tui/config.ts +7 -6
- package/src/tui/go-usage.ts +315 -0
- package/src/tui/go.ts +266 -0
- package/src/tui/index.tsx +25 -6
- package/src/tui/presentation.ts +47 -2
- package/src/tui/rows.ts +168 -1
- package/src/tui/session-reads.ts +52 -1
- package/src/tui/stat-fields.ts +15 -0
- package/src/tui/stats.ts +10 -2
- package/src/tui/throughput.ts +62 -21
package/README.md
CHANGED
|
@@ -41,15 +41,15 @@ elapsed 2h 14m 37s
|
|
|
41
41
|
tps 18 tok/s
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
-
Every row is read from the open session at render time — except `caution`, which watches a clock rather than events (a hang emits none); `elapsed`, which is
|
|
44
|
+
Every row is read from the open session at render time — except `caution`, which watches a clock rather than events (a hang emits none); `elapsed`, which is seeded once from the session's own recorded assistant turn spans and then accumulates the busy windows this run observes, rather than a value the session reports; and the opt-in `guard` row, which is polled from the local guard RPC.
|
|
45
45
|
|
|
46
46
|
| Row | What it shows |
|
|
47
47
|
|---|---|
|
|
48
|
-
| `caution` | **The annunciator** — silent unless something stopped moving |
|
|
48
|
+
| `caution` | **The annunciator** — silent unless something stopped moving · **off by default** |
|
|
49
49
|
| `status` | A spinner while anything is working, a circle while it's idle |
|
|
50
50
|
| `agent` | Which agent you're actually talking to |
|
|
51
51
|
| `model` | The model **and its variant** — `high` behaves differently |
|
|
52
|
-
| `branch` | The branch you're about to commit to |
|
|
52
|
+
| `branch` | The branch you're about to commit to · **off by default** |
|
|
53
53
|
| `cost` | This conversation **plus its subagents**, and the count that explains it; with `total` on the rail, the session figure alone |
|
|
54
54
|
| `total` | The family total and subagent count on a row of its own · **off by default** |
|
|
55
55
|
| `project` | Every session in this project, not just the one on screen |
|
|
@@ -57,16 +57,17 @@ Every row is read from the open session at render time — except `caution`, whi
|
|
|
57
57
|
| `cache` | Hit rate first — the number that explains the bill — then cache reads |
|
|
58
58
|
| `context` | A gauge of how full the window is |
|
|
59
59
|
| `perms` | What is waiting for approval, not just how many |
|
|
60
|
-
| `elapsed` | Active time — the clock runs only while this session, a subagent in its tree, or one of its shells is working, and freezes when everything settles. It is
|
|
60
|
+
| `elapsed` | Active time — the clock runs only while this session, a subagent in its tree, or one of its shells is working, and freezes when everything settles. It is seeded once from the assistant turn spans the host already recorded for that session, so it survives a restart instead of resetting to `—`; work observed live after that keeps counting in memory. It measures active time, not wall-clock since the session began |
|
|
61
61
|
| `tps` | Average speed **while working**: output tokens divided by the time the assistant's turns actually ran, subagents included. Idle time between turns is never counted, so the figure freezes when everything settles instead of decaying or hiding; a turn still in flight counts up to now. On a host that exposes no per-message timestamps it falls back to the lifetime average, which includes idle and can therefore sag. Not configurable |
|
|
62
62
|
| `spark` | Recent turn sizes as a shape · **off by default** |
|
|
63
63
|
| `reasoning` | Reasoning tokens, when the model emits them · **off by default** |
|
|
64
64
|
| `turns` | How many prompts you've sent this session · **off by default** |
|
|
65
65
|
| `guard` | Harness status from oc-harness-guard · **off by default** |
|
|
66
|
+
| `go` | Zen Go account usage — a dial and a whole-number percent for the **5h**, **1w**, and **1m** windows, in that fixed order; a window at 90% or more turns its dial and number red, and the reset hint appears only then · **off by default** |
|
|
66
67
|
|
|
67
68
|
`project` matches on the host's **project id**, not on a directory, so a worktree counts as part of the same project. A host that reports no project id leaves nothing to match on, and the row then totals every session that host knows about.
|
|
68
69
|
|
|
69
|
-
The rows marked **off by default** are available but not in the default rail: add any of them to `sidebar.rows`.
|
|
70
|
+
The rows marked **off by default** — `caution`, `branch`, `total`, `spark`, `reasoning`, `turns`, `guard`, and `go` — are available but not in the default rail: add any of them to `sidebar.rows`. `caution` also needs `caution.enabled: true`; `go` needs `OPENCODE_GO_API_KEY` in the environment.
|
|
70
71
|
|
|
71
72
|
Every field named in `sidebar.rows` renders exactly one row, in order. With `sidebar.persist` (the default), a row with no data yet shows the `sidebar.placeholder` value (default `—`) in the same label column as a live row — so the rail keeps a stable shape instead of growing rows as the session produces data. Set `"persist": false` to restore omission: rows with no data are left out entirely.
|
|
72
73
|
|
|
@@ -78,6 +79,8 @@ The `guard` row only appears when oc-harness-guard is installed and answering; w
|
|
|
78
79
|
|
|
79
80
|
A hang emits no events — its only signature is *absence*. So `caution` watches a clock, stays silent on healthy sessions, and when it speaks it reports what it saw, never what it means: `shell running 8m41s`, not "stuck".
|
|
80
81
|
|
|
82
|
+
The annunciator ships **off by default** — it is the one row that runs a clock of its own, so an install that never asks for it spends nothing on it. To use it, add `caution` to `sidebar.rows` **and** set `caution.enabled: true`.
|
|
83
|
+
|
|
81
84
|
> Measured over **54,218 real settled tool calls**: 0.57% ran past three minutes — with the exempt list, **0.20%** light the row. A ten-minute build is not a hang.
|
|
82
85
|
|
|
83
86
|
**Why cost carries the subagents:** subagents run as separate sessions; a session's own cost excludes them. On the session this was built against: reported `$0.2246`, true spend `$0.2447` — **9% low on money, 54% low on tokens.** One money row tells the truth.
|
|
@@ -119,7 +122,7 @@ Everything else lives in the example file, documented inline - a typo is never f
|
|
|
119
122
|
"sidebar": {
|
|
120
123
|
"maxLines": 24,
|
|
121
124
|
"rows": [
|
|
122
|
-
"
|
|
125
|
+
"status", "agent", "model", "cost", "project",
|
|
123
126
|
"tokens", "cache", "context", "perms", "elapsed", "tps"
|
|
124
127
|
]
|
|
125
128
|
},
|
|
@@ -69,11 +69,12 @@
|
|
|
69
69
|
// them freely — an unknown name is ignored with a one-time warning, so a
|
|
70
70
|
// typo can never break the panel.
|
|
71
71
|
//
|
|
72
|
-
// caution the annunciator: silent unless something stopped moving
|
|
72
|
+
// caution the annunciator: silent unless something stopped moving.
|
|
73
|
+
// Off by default — enables its own clock
|
|
73
74
|
// status running or idle — the glyph turns while anything is working
|
|
74
75
|
// agent which agent is running (orchestrator, build, plan, ...)
|
|
75
76
|
// model model id, plus the variant when there is one
|
|
76
|
-
// branch current git branch
|
|
77
|
+
// branch current git branch. Off by default — costs a VCS call
|
|
77
78
|
// cost this conversation, plus its subagents when any ran; with
|
|
78
79
|
// `total` on the rail, the session figure alone
|
|
79
80
|
// total the family total and subagent count on a row of its own
|
|
@@ -84,8 +85,10 @@
|
|
|
84
85
|
// perms what is waiting for approval, not just how many
|
|
85
86
|
// elapsed active time: the clock runs only while this session — or a
|
|
86
87
|
// subagent in its tree, or one of its shells — is working, and
|
|
87
|
-
// freezes when everything settles.
|
|
88
|
-
//
|
|
88
|
+
// freezes when everything settles. Seeded once from the
|
|
89
|
+
// assistant turn spans the host already recorded, so it
|
|
90
|
+
// survives a restart instead of resetting; work observed live
|
|
91
|
+
// after that keeps counting in memory
|
|
89
92
|
// tps average speed while working: output tokens divided by the
|
|
90
93
|
// time the assistant's turns actually ran, subagents included.
|
|
91
94
|
// Idle between turns is never counted, so the figure freezes
|
|
@@ -98,17 +101,18 @@
|
|
|
98
101
|
// turns how many prompts you have sent this session
|
|
99
102
|
// guard harness status from oc-harness-guard: breaches, orphans,
|
|
100
103
|
// findings, or ok. Available, off by default.
|
|
104
|
+
// go Zen Go account usage for the 5h / 1w / 1m windows: a dial and
|
|
105
|
+
// a percent each, turning red as a window approaches its limit.
|
|
106
|
+
// Reads OPENCODE_GO_API_KEY. Available, off by default.
|
|
101
107
|
//
|
|
102
108
|
// Every named row renders persistently, so the rail keeps a stable shape:
|
|
103
109
|
// a row with no data yet shows the placeholder below, in the same label
|
|
104
110
|
// column as a live row. The fixed lines and live rows share the maxLines
|
|
105
111
|
// budget below, and anything past it is dropped.
|
|
106
112
|
"rows": [
|
|
107
|
-
"caution",
|
|
108
113
|
"status",
|
|
109
114
|
"agent",
|
|
110
115
|
"model",
|
|
111
|
-
"branch",
|
|
112
116
|
"cost",
|
|
113
117
|
"project",
|
|
114
118
|
"tokens",
|
|
@@ -117,6 +121,9 @@
|
|
|
117
121
|
"perms",
|
|
118
122
|
"elapsed",
|
|
119
123
|
"tps"
|
|
124
|
+
// ,"go" — Zen Go account usage (needs OPENCODE_GO_API_KEY)
|
|
125
|
+
// ,"caution" — the annunciator
|
|
126
|
+
// ,"branch" — current git branch
|
|
120
127
|
],
|
|
121
128
|
|
|
122
129
|
// Every named row renders persistently: with no data yet it shows the
|
|
@@ -156,7 +163,9 @@
|
|
|
156
163
|
//
|
|
157
164
|
// It never aborts, kills, retries or blocks anything. Read-only.
|
|
158
165
|
"caution": {
|
|
159
|
-
|
|
166
|
+
// Off by default. Turn it on to run the annunciator; while off, the
|
|
167
|
+
// `caution` row never appears and no timer is spent on it.
|
|
168
|
+
"enabled": false,
|
|
160
169
|
|
|
161
170
|
// A tool running longer than this draws a subdued triangle...
|
|
162
171
|
"toolWatchSeconds": 180,
|
package/flight-deck.schema.json
CHANGED
|
@@ -38,8 +38,8 @@
|
|
|
38
38
|
},
|
|
39
39
|
"rows": {
|
|
40
40
|
"type": "array",
|
|
41
|
-
"items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard"] },
|
|
42
|
-
"default": ["
|
|
41
|
+
"items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard", "go"] },
|
|
42
|
+
"default": ["status", "agent", "model", "cost", "project", "tokens", "cache", "context", "perms", "elapsed", "tps"],
|
|
43
43
|
"maxItems": 24,
|
|
44
44
|
"description": "Which live fields to draw, top to bottom. Any subset, any order — this is the single most useful thing to change. With `sidebar.persist` (the default) every named row always renders, using `sidebar.placeholder` until the host has data; with `persist: false` rows with no data are omitted entirely. Counted together with `sidebar.lines` against a 24-line cap on the whole rail."
|
|
45
45
|
},
|
|
@@ -88,8 +88,8 @@
|
|
|
88
88
|
"properties": {
|
|
89
89
|
"enabled": {
|
|
90
90
|
"type": "boolean",
|
|
91
|
-
"default":
|
|
92
|
-
"description": "Run the annunciator. false means the `caution` row never appears and no timer is spent on it."
|
|
91
|
+
"default": false,
|
|
92
|
+
"description": "Run the annunciator. Off by default. false means the `caution` row never appears and no timer is spent on it."
|
|
93
93
|
},
|
|
94
94
|
"toolWatchSeconds": {
|
|
95
95
|
"type": "integer",
|
|
@@ -254,7 +254,7 @@
|
|
|
254
254
|
}
|
|
255
255
|
},
|
|
256
256
|
"propertyNames": {
|
|
257
|
-
"enum": ["*", "caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard"]
|
|
257
|
+
"enum": ["*", "caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard", "go"]
|
|
258
258
|
},
|
|
259
259
|
"default": { "*": { "color": "subdued", "attributes": [] } },
|
|
260
260
|
"description": "Style all live rows under `*`, then optionally override any known row name such as `cost`. A row can change one field and inherit the other from `*`; unknown row names are reported and ignored."
|
package/package.json
CHANGED
|
@@ -15,14 +15,21 @@
|
|
|
15
15
|
//
|
|
16
16
|
// State is a per-session accumulator held in this process and keyed by the
|
|
17
17
|
// displayed session, so an unrelated project's session can never contribute.
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
18
|
+
// The figure starts from a seed the caller may supply: the merged spans of the
|
|
19
|
+
// assistant turns the host already recorded for that session's scope. That is
|
|
20
|
+
// read once, from the host's own timestamps, so a restart comes back with the
|
|
21
|
+
// work already on record instead of zero. Work observed live after that first
|
|
22
|
+
// read keeps accumulating on top in memory, and a host that offers no seed
|
|
23
|
+
// (or no timestamps) starts at zero and behaves exactly as it did before. The
|
|
24
|
+
// seed is asked for once per session, when that session is first seen; an
|
|
25
|
+
// unknown busy state (`undefined`) freezes rather than inventing motion.
|
|
22
26
|
|
|
23
27
|
/** How the caller answers "is this session working right now?". */
|
|
24
28
|
export type BusyRead = (sessionID: string) => boolean | undefined;
|
|
25
29
|
|
|
30
|
+
/** How the caller answers "how much work is already on record for this session?". */
|
|
31
|
+
export type SeedRead = (sessionID: string) => number | undefined;
|
|
32
|
+
|
|
26
33
|
export interface ActiveElapsedOptions {
|
|
27
34
|
/**
|
|
28
35
|
* Longest window that may be banked as work. A longer one was not observed
|
|
@@ -33,6 +40,13 @@ export interface ActiveElapsedOptions {
|
|
|
33
40
|
* derived bound.
|
|
34
41
|
*/
|
|
35
42
|
readonly maxBankedMs?: number;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Starting tally for a session, read once — on the first observation of that
|
|
46
|
+
* session — so restart-stable work already on record is not lost. Floored at
|
|
47
|
+
* zero; a non-finite or throwing read is treated as zero, never propagated.
|
|
48
|
+
*/
|
|
49
|
+
readonly seedOf?: SeedRead;
|
|
36
50
|
}
|
|
37
51
|
|
|
38
52
|
/** One session's running tally and the last instant it was observed. */
|
|
@@ -81,7 +95,20 @@ export function createActiveElapsed(isBusy: BusyRead, options: ActiveElapsedOpti
|
|
|
81
95
|
|
|
82
96
|
let state = states.get(sessionID);
|
|
83
97
|
if (state === undefined) {
|
|
84
|
-
|
|
98
|
+
// First sight of this session: take the seed once, here, so the record
|
|
99
|
+
// covers everything up to the moment observation begins and the
|
|
100
|
+
// accumulator below covers everything after — no overlap, no double
|
|
101
|
+
// count. Floored at zero; a non-finite or throwing read is zero.
|
|
102
|
+
let seed = 0;
|
|
103
|
+
if (options.seedOf !== undefined) {
|
|
104
|
+
try {
|
|
105
|
+
const value = options.seedOf(sessionID);
|
|
106
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0) seed = value;
|
|
107
|
+
} catch {
|
|
108
|
+
seed = 0;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
state = { accumulated: seed, lastAt: now, running: false };
|
|
85
112
|
states.set(sessionID, state);
|
|
86
113
|
} else if (!boundary && state.running && busy) {
|
|
87
114
|
// Only a window that was busy at BOTH ends and short enough to have been
|
package/src/tui/config.ts
CHANGED
|
@@ -57,7 +57,7 @@ interface FooterConfig {
|
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
interface CautionConfig {
|
|
60
|
-
/** Show the caution annunciator. Default `
|
|
60
|
+
/** Show the caution annunciator. Default `false`. */
|
|
61
61
|
readonly enabled: boolean;
|
|
62
62
|
/** A tool running longer than this is worth noting. Default `180`. */
|
|
63
63
|
readonly toolWatchSeconds: number;
|
|
@@ -93,7 +93,8 @@ export interface FlightDeckConfig {
|
|
|
93
93
|
* The annunciator: the one thing on the rail that is not session state.
|
|
94
94
|
*
|
|
95
95
|
* It exists because a hang emits no events, so nothing else here can see it.
|
|
96
|
-
* Silent when healthy, which is why it costs nothing visually.
|
|
96
|
+
* Silent when healthy, which is why it costs nothing visually. Off by default:
|
|
97
|
+
* it is opt-in, so an install that never asks for it spends no timer on it.
|
|
97
98
|
*/
|
|
98
99
|
readonly caution: CautionConfig;
|
|
99
100
|
/** Geometry of a row. Every value has a sane default. */
|
|
@@ -183,7 +184,7 @@ const DEFAULT_GLYPHS: GlyphConfig = {
|
|
|
183
184
|
};
|
|
184
185
|
|
|
185
186
|
const DEFAULT_CAUTION: CautionConfig = {
|
|
186
|
-
enabled:
|
|
187
|
+
enabled: false,
|
|
187
188
|
toolWatchSeconds: 180,
|
|
188
189
|
toolCautionSeconds: 420,
|
|
189
190
|
turnWatchSeconds: 600,
|
|
@@ -215,14 +216,14 @@ export const DEFAULT_SIDEBAR_LINES: readonly string[] = [
|
|
|
215
216
|
* Live fields shown by default, in reading order.
|
|
216
217
|
*
|
|
217
218
|
* Every one of these is read from the open session at render time, so a fresh
|
|
218
|
-
* install shows real numbers with no configuration file at all.
|
|
219
|
+
* install shows real numbers with no configuration file at all. The rows that
|
|
220
|
+
* need extra machinery or a second source — `caution` (a clock), `branch` (a
|
|
221
|
+
* VCS call), and `go` (an account-wide poll) — are opt-in via `sidebar.rows`.
|
|
219
222
|
*/
|
|
220
223
|
export const DEFAULT_SIDEBAR_ROWS: readonly string[] = [
|
|
221
|
-
"caution",
|
|
222
224
|
"status",
|
|
223
225
|
"agent",
|
|
224
226
|
"model",
|
|
225
|
-
"branch",
|
|
226
227
|
"cost",
|
|
227
228
|
"project",
|
|
228
229
|
"tokens",
|
|
@@ -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
|
+
}
|