opencode-usage-insights 0.1.3 → 0.3.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 CHANGED
@@ -6,15 +6,19 @@
6
6
  [![npm](https://img.shields.io/npm/v/opencode-usage-insights.svg)](https://www.npmjs.com/package/opencode-usage-insights)
7
7
 
8
8
  **See what each turn costs.** OpenCode reports the cost of each request, but the
9
- TUI no longer shows it. This plugin puts cost back in view: a telemetry line
10
- after every turn, the session's running spend in the sidebar, and an interactive
11
- `/usage` panel with charged cost, list-price estimates, tokens, prompt-cache
12
- reuse and latency.
9
+ TUI no longer shows it. This plugin puts cost back in view in the **TUI** and in
10
+ **OpenCode Desktop**: a telemetry line after every turn, the session's running
11
+ spend and turn history, and an interactive `/usage-insights` panel with charged cost,
12
+ list-price estimates, tokens, prompt-cache reuse and latency.
13
13
 
14
14
  ![The telemetry line after a turn](docs/images/line.png)
15
15
 
16
- Everything stays local: no prompts or responses are stored, and nothing leaves
17
- the machine.
16
+ Everything stays in your OpenCode server: no prompts or responses are stored,
17
+ and the plugin sends nothing to a third party. The Go view reads the usage
18
+ limits the host already fetched from the OpenCode Console; the plugin never
19
+ sees the API key. The TUI and Desktop both read the
20
+ same recorder through an authenticated server RPC, so a client connected to a
21
+ remote server shows that server's data.
18
22
 
19
23
  ## What it does
20
24
 
@@ -23,24 +27,27 @@ the machine.
23
27
  model and configured provider, and warnings when the prompt cache or the
24
28
  provider changed. It belongs to finished work, so it stays hidden while a
25
29
  turn is running.
26
- - **The `/usage` panel**: nine keyboard-driven views — `overview`, `models`,
27
- `providers`, `cache`, `periods`, `latency`, `sessions`, `turns`,
28
- `db` — over five ranges (`session`, `today`, `7d`, `30d`, `all`), with
29
- drill-downs, sorting, filters and state remembered between openings.
30
- `/usage models 7d`, `/usage providers 30d`, `/usage turns 7d`.
31
- - **The session sidebar**: the session's running spend and its last turns, in
32
- the same buckets as the line. Three lines per turn — when and through which
33
- provider, the prompt volumes, then `hit · tok/s · cost` — plus the model at
34
- both ends of the block and on any turn that changed it, so the history reads
35
- whether it is the whole session or a window of a long one:
36
- `16:54 opencode-go` / `deepseek-v4.1-flash max` /
37
- `in 1.7k (427.3k) · out 1.06k` / `hit 99.7% · 1.2k/s · $0.0006`.
38
- - **The record** (server part): every assistant step with tokens, charged cost,
39
- the list-price estimate when the host reported `$0`, timings, finish reason,
40
- the configured provider and model it ran through, and its session and parent
41
- ids; prompts, session lifecycle and compaction events too; and the host's
42
- `session.usage.recorded` for compactions and title generations, which have no
43
- assistant step of their own.
30
+ - **The `/usage-insights` panel**: ten views — `overview`, `models`,
31
+ `providers`, `cache`, `periods`, `latency`, `sessions`, `turns`, `db`, `go` —
32
+ over five ranges (`session`, `today`, `7d`, `30d`, `all`), with drill-downs,
33
+ sorting, filters and remembered state. Keyboard-driven in the TUI; the same
34
+ views with desktop controls in OpenCode Desktop. `/usage-insights models 7d`,
35
+ `/usage-insights go`.
36
+ - **The Desktop header badge and panels**: a spend badge in the session header,
37
+ next to the peak/off-peak badge; clicking it opens **Turns insights**, the
38
+ session history. **Usage insights** holds the ten views and opens from
39
+ `/usage-insights`. The Desktop window never opens SQLite: the server's worker serves
40
+ the panels and history over RPC.
41
+ - **The TUI sidebar**: the session's spend and last turns, in the same buckets
42
+ as the line — time, provider, wall duration, prompt volumes, then
43
+ `hit · tok/s · cost`. When OpenCode Go is active, a compact block above the
44
+ summary names the subscription and shows the 5-hour/weekly/monthly
45
+ percentages, the monthly forecast and the renewal date. The duration is
46
+ first request to last completion: tool waits inside the turn count, idle gaps
47
+ do not.
48
+ - **The record** (server): every step with tokens, charged cost, the list-price
49
+ estimate for `$0`, timings, finish reason and provider/model IDs; prompts,
50
+ lifecycle, compaction and `session.usage.recorded` events too.
44
51
  - **Portable data** (from a checkout): `bun run report --ndjson` exports the
45
52
  whole database, and `--import` merges it back on another machine.
46
53
  - **Observational by design**: the plugin never rewrites prompts, requests or
@@ -49,14 +56,16 @@ the machine.
49
56
 
50
57
  ## Requirements
51
58
 
52
- - **OpenCode V2** (`>=2.0.0`). The V2 release changed the plugin API (slots,
53
- panels, event stream).
59
+ - **OpenCode V2** (`>=2.4.2`). The Desktop GUI part uses the V2 GUI plugin API
60
+ (`./gui-experimental`), introduced in the 2.4 line. The server and TUI parts
61
+ run on the same server that records the sessions.
54
62
  - [Bun](https://bun.sh) to install dependencies (development only).
55
63
 
56
64
  | | |
57
65
  | --- | --- |
58
- | **OS** | Linux, macOS and Windows. The database lives in the per-user state directory of each (table below); `test/paths.test.ts` asserts the path rules of all three from any machine, and `bun run check:platform` exercises the data layer — paths, database, recorder, queries, panel assembly, dump round-trip, file permissions — on the OS it runs on. CI runs the whole suite (including the TUI render tests) on Linux. |
66
+ | **OS** | Linux, macOS and Windows. The database lives in the per-user state directory of each (table below). `bun run check:platform` exercises the data layer on the host OS; CI runs the full suite, including the TUI render tests, on Linux. |
59
67
  | **Runtime** | Bun, the runtime OpenCode ships with. SQLite comes from `bun:sqlite`: there is no native module to build and nothing to compile on install. |
68
+ | **Desktop** | OpenCode Desktop 2.4+. The GUI is one CommonJS bundle (`dist/gui-experimental.cjs`) that uses the app's shared Solid, Effect and OpenCode client modules; it never opens SQLite. |
60
69
 
61
70
  ## Install
62
71
 
@@ -66,10 +75,15 @@ The plugin is published on npm as `opencode-usage-insights`.
66
75
  opencode plugin add opencode-usage-insights
67
76
  ```
68
77
 
69
- This adds one entry to the global `opencode.json(c)`. That entry loads both
70
- parts: the server recorder and the TUI contributions. A TUI-only package goes in
71
- `~/.config/opencode/cli.json`; this plugin has both parts, so `opencode.json(c)`
72
- is enough.
78
+ This adds one entry to the global `opencode.json(c)`. That entry loads every
79
+ part of the package: the server recorder and RPC, the TUI contributions, and the
80
+ Desktop GUI. A TUI-only package goes in `~/.config/opencode/cli.json`; this
81
+ plugin has a server part, so `opencode.json(c)` is enough.
82
+
83
+ > **Desktop reads only `opencode.json(c)`.** If the plugin is in
84
+ > `~/.config/opencode/cli.json`, move that entry to `opencode.json(c)` and
85
+ > remove it from `cli.json`. One entry in `opencode.json(c)` covers the TUI and
86
+ > the Desktop; keeping both loads the TUI part twice.
73
87
 
74
88
  If you prefer to edit the configuration yourself:
75
89
 
@@ -91,22 +105,33 @@ To pass [options](#configuration), use the object form:
91
105
  }
92
106
  ```
93
107
 
94
- Or register a local checkout. V2 resolves a local *directory* plugin through its
95
- entry files, so pointing at `src/` loads the server recorder (`src/index.ts`)
96
- and the TUI contributions (`src/tui.tsx`) from source:
108
+ Or register a local checkout. Point at the **package root**, not `src/`: the
109
+ loader reads the package `exports`, which resolve the server, TUI, RPC and GUI
110
+ parts. Build once before loading it, and rebuild after source changes:
111
+
112
+ ```sh
113
+ cd /home/you/code/projects/opencode-usage-insights
114
+ bun install
115
+ bun run build
116
+ ```
97
117
 
98
118
  ```jsonc
99
119
  // ~/.config/opencode/opencode.jsonc
100
- { "plugins": [{ "package": "/home/you/code/projects/opencode-usage-insights/src" }] }
120
+ { "plugins": [{ "package": "/home/you/code/projects/opencode-usage-insights" }] }
101
121
  ```
102
122
 
103
- Configuration changes reload on their own; after changing the plugin's source,
104
- restart the background service with `opencode service restart`.
123
+ For GUI development, keep `bun run dev:gui` running in another terminal; each
124
+ rebuild reloads the Desktop GUI in every window without restarting the server.
125
+ Configuration changes reload on their own; after changing server or TUI source,
126
+ restart the background service with `opencode service restart`. The host's own
127
+ `/usage` command remains the place for the Console budget details; the plugin's
128
+ command is `/usage-insights`.
105
129
 
106
- Send a prompt to verify: the telemetry line appears above the composer when the
107
- turn finishes, and `/usage` (alias `/insights`) opens the panel.
130
+ Send a prompt to verify: the TUI line appears above the composer when the turn
131
+ finishes, the Desktop badge appears in the session header, and `/usage-insights`
132
+ (alias `/insights`) opens the panel.
108
133
 
109
- ## The line
134
+ ## The TUI line
110
135
 
111
136
  ```text
112
137
  14:32:07 · Δ 3m12s · opencode-go/deepseek-v4.1-flash max · in 85.4k (1.62M), cached 1.53M, out 3.7k, cost $0.21 · sess in 2.1M (14.5M), cached 12.4M, out 88k, cost $1.90 · ⚠ cache expired (−11.7k)
@@ -117,7 +142,7 @@ turn finishes, and `/usage` (alias `/insights`) opens the panel.
117
142
  | `14:32:07` | When the response ended (`completed`, else `streamed`, else `created`). |
118
143
  | `Δ 3m12s` | Time since the previous prompt of the same session. |
119
144
  | `opencode-go/deepseek-v4.1-flash max` | The identity of the turn: the configured provider the model ran through and the model (the variant as a trailing word; `fields.model`/`fields.variant` hide either). Yellow with `changed` when the provider differs from the previous prompt, `model changed` when only the model does. |
120
- | `in 85.4k (1.62M), cached 1.53M, out 3.7k, cost $0.21` | `in` is the uncached part of the prompt (fresh input + cache writes), the parenthesised value the whole prompt — shown only when the two differ — `cached` its cached part, `out` everything generated (visible output + reasoning), and `cost` what the turn was billed. With several steps the segment reads `3 steps · …` and reports the step the turn ended with (`latest`) for the tokens, while the cost is always the turn's own — every step is paid for; `turnTotals: "sum"` adds every step's tokens instead. |
145
+ | `in 85.4k (1.62M), cached 1.53M, out 3.7k, cost $0.21` | `in` is the uncached prompt; the parenthesised value is the whole prompt (only when different); `cached` its cached part; `out` generated tokens (visible + reasoning); `cost` the bill. Several steps read `3 steps · …` and report the last step's tokens (`latest`); cost sums the turn. `turnTotals: "sum"` sums every step. |
121
146
  | `cost $0.21` | Money, not tokens: a turn sums every step's cost whatever the token view shows. A cost of zero is left out, so a free model reads as free. `fields.cost: false` hides it. |
122
147
  | `cost ≈ $0.21` | A **list-price estimate**, not money charged. When the host reports `cost: 0` for a paid model (OpenCode 2.2.0+ with an OpenCode Go subscription), the plugin prices the step from the host's model list. A turn mixing covered and paid steps keeps both parts visible: `cost $0.12 + ≈ $3.40`. `pricing: "off"` hides estimates everywhere; `fields.cost: false` hides both. |
123
148
  | `sess in 2.1M (14.5M), cached 12.4M, out 88k, cost $1.90` | The session totals: tokens and charged money come from the host (including its compaction and title generations), and the list estimate comes from the steps the plugin recorded. A Go session reads `cost ≈ $3.40`; a session mixing charged and covered steps keeps both parts, `cost $0.12 + ≈ $3.40`. |
@@ -126,159 +151,154 @@ turn finishes, and `/usage` (alias `/insights`) opens the panel.
126
151
  The turn segment carries no label by default — the numbers are the turn's, and
127
152
  `sess` marks the session's; `labels.turn` (e.g. `"turn"`) brings a prefix back.
128
153
 
129
- `≈` is an estimate at the host's list price, never a charge. It appears when
130
- OpenCode reports a step at `$0` — subscription-covered Go requests, or a provider
131
- that stopped reporting a cost — and the host's model list still has a price. A
132
- genuinely free model has no price and therefore no estimate; it is recorded as
133
- known free rather than as an unknown price. The estimate is stored per step, so
134
- the line's `sess` segment, the panel, the sidebar, the NDJSON export and the CLI
135
- report all show the same number. The `db` view lists how many `$0` steps still
136
- lack one; `e` backfills them using today's model list.
154
+ `≈` marks a **list-price estimate**, never a charge. It appears when the host
155
+ reports `$0` for a model the catalog still prices; a known free model has no
156
+ estimate. The `sess` segment and historical views use the stored per-step
157
+ estimate, so they agree across clients; a live turn uses the client's current
158
+ catalog and can differ after a price change. The `db` view counts unpriced `$0`
159
+ steps and can backfill them (`e` in the TUI, **Backfill** in the Desktop panel).
137
160
 
138
161
  A turn is every consecutive assistant step after a prompt. Compaction, shell,
139
162
  `idle` and info messages do not split a turn; `user`, `synthetic` and `system`
140
163
  messages do. From a checkout, `bun run demo` prints one example per case,
141
164
  including the streaming one and both turn-total views.
142
165
 
143
- ## How costs are calculated
166
+ ## OpenCode Desktop
144
167
 
145
- **Charged money is never recalculated by the plugin.** `steps.cost` is what the
146
- host reports for the step (possibly `0` for an OpenCode Go subscription). When
147
- that number is `0` or missing and the model has a price in the host's model
148
- list, the plugin computes a **list-price estimate** and stores it in
149
- `steps.list_cost`. Prices are USD per 1,000,000 tokens.
168
+ The Desktop app loads the package's `./gui-experimental` bundle in every window.
169
+ The GUI plugin API is experimental in the 2.4 line; the bundle is tested against
170
+ OpenCode Desktop 2.4.2. The window is Electron/Chromium: it has no Bun, no
171
+ `bun:sqlite` and no Node filesystem.
150
172
 
151
- The price source is the model list exposed by the OpenCode process that is
152
- currently serving the session, already resolved by the host (provider config,
153
- overrides, Zen/Go pricing):
173
+ If the plugin was already installed before it gained the GUI part, restart the
174
+ background service once (`opencode service restart`) and reopen the Desktop
175
+ window. The plugin inventory caches the package's parts; a config reload may
176
+ reload the server entry without noticing the new `./gui-experimental` export.
154
177
 
155
- | Surface | Where the price comes from |
156
- | --- | --- |
157
- | Server recorder | `ctx.model.list()` → `ModelInfo.cost` |
158
- | Live turn / backfill | `ctx.data.location.model.list(ctx.location)` → `ModelInfo.cost` |
159
- | Panel, sidebar, NDJSON, CLI report | stored `steps.list_cost` |
160
- | `sess` segment | `SUM(list_cost)` from the plugin database |
178
+ The recorder, the database and the worker stay in the server; the window reads
179
+ them through the same RPC the TUI uses.
161
180
 
162
- The plugin does **not** read `~/.cache/opencode/models.json`, does **not** use
163
- `opencode models` for prices (it lists model IDs only), and makes no network
164
- call of its own. Each `ModelInfo` carries the prices as
165
- `cost: Array<{ input, output, cache: { read, write }, tier? }>` in USD per
166
- 1,000,000 tokens.
181
+ ### The cost badge
167
182
 
168
- The estimate uses the host's own fallback formula:
183
+ In the session header, next to the peak/off-peak badge, the usage insights badge
184
+ shows the finished turn's spend (`$0.0210` or `≈$0.0210`):
169
185
 
170
186
  ```text
171
- input fresh (uncached) prompt tokens
172
- cache.read prompt tokens read from the provider cache
173
- cache.write prompt tokens written to the provider cache
174
- output visible output tokens
175
- reasoning reasoning tokens
176
-
177
- prompt = input + cache.read + cache.write
178
- cost = (input * inputPrice
179
- + (output + reasoning) * outputPrice
180
- + cache.read * cacheReadPrice
181
- + cache.write * cacheWritePrice) / 1_000_000
187
+ $0.0210
182
188
  ```
183
189
 
184
- Reasoning is billed at the output price. For models with context tiers, the
185
- tier applies only when the whole prompt is **strictly greater** than the tier
186
- size; at exactly the threshold the untiered price applies. An unknown model or
187
- no applicable price means no estimate; an all-zero price means the model is
188
- known to be free.
190
+ Hovering shows the full telemetry line. While a turn runs the badge shows the
191
+ session's accumulated spend instead (`≈$1.90`) and returns to the turn's
192
+ spend when it ends. Clicking it opens **Turns insights**. The `fields`, `labels`,
193
+ `turnTotals` and `pricing` options apply to the line, badge tooltip and panel;
194
+ `fields.cost: false` hides the badge, and `fields.session: false` keeps it
195
+ hidden while a turn runs.
196
+
197
+ ### Usage insights and Turns insights
198
+
199
+ `/usage-insights` (and the hidden `/insights` alias) opens the **Usage
200
+ insights** panel in the side region. It has the same ten views, five ranges,
201
+ drill-downs, sorting and filters as the TUI, plus the database view's
202
+ maintenance buttons. The Desktop view menu lists **OpenCode Go** immediately
203
+ after **Overview**. The **Turns insights** tab shows the current session's
204
+ history. `/usage-insights turns` opens the same history inside **Usage insights**,
205
+ where the session/all-sessions scope is available. Both panels have the inverse shortcut: **Usage insights**
206
+ has an **Open turns insights** footer button, and **Turns insights** has
207
+ **Open usage insights**.
208
+
209
+ The TUI's always-visible sidebar has no Desktop slot. The Desktop equivalents
210
+ are:
211
+
212
+ | Where | What it shows |
213
+ | --- | --- |
214
+ | Session header badge | The turn spend and the full line on hover; click opens Turns insights. |
215
+ | Turns insights tab | The current session's complete history, with the same compact Go forecast block as the TUI sidebar. `/usage-insights turns` adds the session/all-sessions scope. |
216
+ | Side panel `+` menu | **Usage insights** and **Turns insights** launchers. |
189
217
 
190
- The buckets behind the line are the same ones the estimate uses, but folded for
191
- display:
218
+ The panel state is stored separately from the TUI: opening the Desktop panel
219
+ does not move the TUI panel, and vice versa.
192
220
 
193
- ```text
194
- in = input + cache.write (the uncached part of the prompt)
195
- cached = cache.read
196
- out = output + reasoning
197
- prompt = in + cached
198
- ```
221
+ ### The server side
199
222
 
200
- `list_cost` has three meanings: `NULL` means the step was charged or its price
201
- is unknown; `0` means the model is known to be free; a positive value is the
202
- estimate. That is why a free model reads as `$0`, while an older model the
203
- host's model list no longer contains stays without a price.
223
+ The server part registers the usage RPC and starts a **database worker**. The worker owns a read-only SQLite connection for the panel and the
224
+ turn history, and opens a short write connection for `prune`, `wipe`, `vacuum`
225
+ and `backfill`. Panel queries therefore never block the agent's event loop, and
226
+ the TUI does not open SQLite either: it works against a local or a remote server.
204
227
 
205
- A worked example, using the prices of `opencode-go/deepseek-v4.1-flash`
206
- (`input 0.15`, `output 0.6`, `cache.read 0.003`):
228
+ The worker starts lazily on the first usage request (the panel, the history or
229
+ the header badge estimate). If it cannot start (for example in a development
230
+ runtime), the server falls back to an in-process service and logs it; the
231
+ plugin still works, but the fallback shares the server's event loop.
207
232
 
208
- ```text
209
- 2,591 × 0.15 + (564 + 3,239) × 0.6 + 514,944 × 0.003
210
- = 4,215.282 per 1,000,000 tokens
211
- = $0.004215282
212
- ```
233
+ ### Desktop options
213
234
 
214
- ### Compactions and titles
235
+ All options are in [Configuration](#configuration). The two security-relevant
236
+ ones are `maintenance` (default `true`; set `false` on a server reachable from
237
+ other machines) and `exposePaths` (default `false`; keeps the absolute database
238
+ path out of the `db` view).
215
239
 
216
- The host also reports usage with no assistant step behind it:
217
- `session.usage.recorded` with `source: "compaction"` or `source: "title"`. It is
218
- part of the session's own `cost`, and the plugin stores it in the `usage` table,
219
- keyed by the host event ID so a replay never counts twice.
240
+ ### Remote servers
220
241
 
221
- Its cost is added to the **overview**, **periods** and **sessions** totals — the
222
- same money the host already includes in the session. The `models`, `providers`
223
- and `turns` rows stay step-based: the host's non-step usage record carries no
224
- model, so attributing the money to one would invent an identity. The overview
225
- shows the part as an `other` row, and a session row names it under its title.
242
+ The TUI and Desktop call the RPC on the server that owns the session. A TUI
243
+ connected to a remote server shows that server's usage; the Desktop GUI is
244
+ loaded from its own background server, but the panel targets the session's
245
+ server. The plugin's server part must be installed and enabled on that server.
246
+ If it is not, the panel explains that usage data is unavailable.
226
247
 
227
- This is host money, not a list-price estimate, so `pricing: "off"` does not hide
228
- it. A database written by an older plugin is healed at open: the stored
229
- compaction events already carry `cost` and `tokens`, and a migration recovers
230
- them. Title usage recorded before the upgrade was never stored anywhere and
231
- stays missing; the line's `sess` segment (which reads the host's own session
232
- total) keeps covering the whole session meanwhile.
248
+ ## How costs are calculated
233
249
 
234
- What each surface shows:
250
+ **Charged money is never recalculated.** `steps.cost` is what the host reports.
251
+ When it is `0` or missing and the model has a price in the host's model list, the
252
+ plugin stores a **list-price estimate** in `steps.list_cost` (USD per 1M tokens).
253
+ `≈` marks an estimate, never a charge.
254
+
255
+ | Surface | Price source |
256
+ | --- | --- |
257
+ | Server recorder and backfill | `ctx.model.list()` |
258
+ | Live line (TUI/Desktop) | `data.location.model.list(location)` |
259
+ | Panel, sidebar, NDJSON, CLI | stored `steps.list_cost` |
260
+ | `sess` segment | `SUM(list_cost)` over the RPC |
261
+
262
+ The host resolves provider config/overrides. The plugin does not read
263
+ `~/.cache/opencode/models.json`, does not use `opencode models` for prices, and
264
+ makes no network call. `list_cost` is `NULL` for charged/unknown, `0` for a known
265
+ free model, and positive for an estimate. An unknown or inapplicable price means
266
+ no estimate; an all-zero price means free. The formula, context tiers and worked
267
+ example are in [docs/internals.md](docs/internals.md#list-price-estimates).
268
+
269
+ The host also reports compaction and title usage with no assistant step. It is
270
+ stored in `usage`, keyed by the host event ID, and included in the overview,
271
+ periods and sessions totals; it is not attributed to a model because the host
272
+ record carries none. See [docs/internals.md](docs/internals.md#non-step-usage).
273
+
274
+ The live line's turn estimate uses the client's current model list; the `sess`
275
+ segment and historical views use the stored estimate, which freezes the price at
276
+ recording time. If the plugin started mid-session, the estimate covers only the
277
+ recorded steps; the charged total still follows the host. `pricing: "off"` hides
278
+ estimates and disables the backfill without deleting data.
235
279
 
236
280
  | Situation | Line | Panel |
237
281
  | --- | --- | --- |
238
282
  | Charged | `cost $0.12` | `$0.12` |
239
- | Subscription-covered (host `0`, host model price known) | `cost ≈ $3.40` | `≈$3.40` |
240
- | Mixed (some charged, some covered) | `cost $0.12 + ≈ $3.40` | overview `$0.12 + ≈ $3.40`; table cell `≈$3.52` (charged + estimate) |
241
- | Compaction/title (host `session.usage.recorded`) | included in the host's `sess` total | overview `other $0.0042`; session and period cost include it |
242
- | Known free model | cost omitted | `$0` |
243
- | Price unknown | cost omitted | `$0` |
244
-
245
- The **turn** estimate on the live line uses the model list the TUI currently
246
- has. The **`sess`** segment uses the estimate recorded per step and summed for
247
- the session, as do the panel, the sidebar, the NDJSON export and the CLI report.
248
- If a price changes after a step is recorded, the live turn can therefore differ
249
- from the stored history; `list_cost` freezes the price from the recording time.
250
- The server loads its model list in the background, refreshes it on
251
- `model.updated` and keeps the previous table if a refresh fails; the TUI
252
- invalidates its table on the same event and refreshes it on a coarse TTL.
253
-
254
- For a session, the charged total is the host's (including its compaction and
255
- title generations); the estimate is `SUM(list_cost)` over the steps the plugin
256
- recorded. The overview, periods and session rows additionally add the host's
257
- non-step usage cost; the line's `sess` segment already has it in the host's
258
- total, so it is not added twice. If the plugin started recording in the middle
259
- of a session, the estimate covers only the recorded steps; the charged total
260
- still follows the host. When the database is unavailable, the line falls back to
261
- the host's charged total with no estimate.
262
-
263
- The `db` view counts the `$0` steps that have no known price yet. `e` retries
264
- them with today's host model list: free models become `0`, models still in that
265
- list get an estimate, and models the list no longer contains stay unknown. Steps
266
- without a provider/model or without tokens have nothing to price and are not
267
- counted. `pricing: "off"` stops new estimates, hides stored ones everywhere and
268
- disables the backfill, without deleting the data.
269
-
270
- ## The panel
271
-
272
- `/usage [view] [range]` opens the panel (`/usage` alone opens the last view, or
273
- `overview` over `all` the first time). While the panel is open it owns input, so
274
- the prompt cannot take the command again: `escape` closes it, `f` toggles full
275
- screen, and the palette entry (`ctrl+p` → "Usage insights") toggles it closed.
276
- With the composer focused, `/usage` with no arguments also toggles it closed,
277
- and any argument — including an unknown token, which is ignored — keeps it open.
283
+ | Covered (host `0`, price known) | `cost ≈ $3.40` | `≈$3.40` |
284
+ | Mixed | `cost $0.12 + ≈ $3.40` | `$0.12 + ≈ $3.40`; table `≈$3.52` |
285
+ | Compaction/title | in the host `sess` total | overview `other`; session/period cost |
286
+ | Known free / price unknown | cost omitted | `$0` |
287
+
288
+ ## The TUI panel
289
+
290
+ `/usage-insights [view] [range]` opens the panel (`/usage-insights` alone opens
291
+ the last view, or `overview` over `all` the first time). While the panel is open
292
+ it owns input, so the prompt cannot take the command again: `escape` closes it,
293
+ `f` toggles full screen, and the palette entry (`ctrl+p` → "Usage insights")
294
+ toggles it closed. With the composer focused, `/usage-insights` with no
295
+ arguments also toggles it closed, and any argument — including an unknown token,
296
+ which is ignored — keeps it open. `/usage` stays the host's native usage-limits
297
+ dialog.
278
298
  There is no default key binding — the command is palette-only, so it never
279
299
  shadows a key you use.
280
300
 
281
- ![The /usage providers view](docs/images/panel-providers.png)
301
+ ![The /usage-insights providers view](docs/images/panel-providers.png)
282
302
 
283
303
  The view bar at the top names every view and brackets the active one; `?` opens
284
304
  a help overlay that repeats the keys and defines every number.
@@ -289,16 +309,16 @@ a help overlay that repeats the keys and defines every number.
289
309
  | --- | --- |
290
310
  | `↑` `↓` / `j` `k` | Move the cursor; the row under it is highlighted. |
291
311
  | `pageup` `pagedown` / `home` `end` | Move by ten rows / to the first or last row. |
292
- | `enter` | Drill into the row: a model → the providers it ran through and their latency; a provider → the models it served and its latency; a session → its turns; a period → the providers of the period. In `db`, prune the steps recorded before the selected retention's cutoff date (asks first). |
312
+ | `enter` | Drill into the row: a model → the providers it ran through and their latency; a provider → the models it served and its latency; a session → its turns; a period → the providers of the period. In `db`, prune the steps recorded before the selected retention's cutoff date, or wipe every recorded step, session and event from the last row (asks first). |
293
313
  | `backspace` | Go back from a drill-down. |
294
- | `1`–`9` / `[` `]` | Pick a view (`9` is `db`) / cycle views. |
314
+ | `1`–`9` `0` / `[` `]` | Pick a view (`9` is `db`, `0` is `go`) / cycle views. |
295
315
  | `t` / `shift+t` | Next / previous range. |
296
316
  | `s` / `shift+s` | Cycle the sort column / reverse it. |
297
317
  | `b` | `periods` bucket: day → week → month. |
298
318
  | `a` | `turns` scope: this session ↔ every session. |
299
319
  | `m` `p` | Filter by model or by **provider** (a picker of the values actually observed). |
300
320
  | `x` | Clear the filters. |
301
- | `r` | Re-read the database. |
321
+ | `r` | Re-read the database; in `go`, refresh the live allowance. |
302
322
  | `e` | `db`: backfill list-price estimates for the `$0` steps that have none (asks first; uses today's model list). |
303
323
  | `v` | `db`: compact the file, giving the space of deleted rows back. |
304
324
  | `?` | Help overlay. |
@@ -319,7 +339,8 @@ durable storage, so the panel reopens where it was left.
319
339
  | `latency` | Wall time, streaming window and throughput as p50/p90/p99 overall and per model (per provider when a model is filtered). `n < 5` is dimmed. |
320
340
  | `sessions` | Each session with steps, prompts, tokens, `hit`, cost (including compaction/title usage, named on the detail line), its directory and how many models it used; subagent sessions are indented under their parent and rolled up. |
321
341
  | `turns` | The per-prompt history: one line per finished turn, rendered exactly like the live line. Cost is assistant steps only. `a` widens it to every session, titled. |
322
- | `db` | Where the file lives, what it holds and how much of it is old. The retention table lists, per preset (`30`/`90`/`365` days), how many steps a prune would remove and the cutoff date it prunes from — pick one with `↑`/`↓` and `enter` prunes it (a confirmation first), removing the steps' compaction/title usage with them; `v` gives the space back. It also counts the `$0` steps with no list estimate; `e` backfills them at today's list price. |
342
+ | `db` | File name (full path with `exposePaths: true`), contents and age. The retention table lists `30`/`90`/`365`-day prunes with step counts and cutoff; `↑`/`↓` + `enter` prunes from a cutoff, and the row below the table wipes every recorded step, session and event (both ask first). `v` reclaims space. It counts `$0` steps without an estimate; `e` backfills at today's list price. |
343
+ | `go` | Live **OpenCode Go** allowance: the 5-hour (`rolling`), weekly and monthly meters, their reset countdowns, and a forecast of the monthly percentage at its renewal from the cycle's average pace. It also names the exact renewal instant. Read by the client from the host's usage-limits endpoint; no database rows. The TUI sidebar and the Desktop Turns insights tab carry the compact form, and the Desktop view draws the current-versus-forecast bars. |
323
344
 
324
345
  The panel sums the stored per-step buckets over the selected range, so a number
325
346
  read in one place means the same in the other: `prompt` is everything the
@@ -339,29 +360,82 @@ between them forfeits the cache the previous one held (the switch counts and the
339
360
  cache losses in the `models` view count exactly that).
340
361
 
341
362
  `tps`/`wall`/`stream` are produced tokens per streaming second / request to
342
- completed step / request to the last chunk. The sidebar's rate (per turn, and
343
- the session average on its totals) is the **weighted** one — produced tokens
344
- divided by the summed streaming windows — so it answers "how fast did this
345
- produce"; the `latency` view reports the p50 of the per-step rates instead, which
346
- answers "how fast is a typical step". A switch from one step to the next is not
347
- by itself a fault — moving to another model or provider is a deliberate choice —
348
- so the `models` view pairs the count with the cache the switch actually cost,
349
- which only a provider switch can: two models never share a cache to lose. The
350
- panel's `?` overlay defines every number in place.
363
+ completed step / request to the last chunk. The sidebar's turn header shows the
364
+ turn's wall time — the first request to the last completed step, so any tool
365
+ wait inside the turn counts — while its rate is only the streaming window. The
366
+ sidebar's rate (per turn, and the session average on its totals) is the
367
+ **weighted** one — produced tokens divided by the summed streaming windows — so
368
+ it answers "how fast did this produce"; the `latency` view reports the p50 of
369
+ the per-step rates instead, which answers "how fast is a typical step". A
370
+ switch from one step to the next is not by itself a fault — moving to another
371
+ model or provider is a deliberate choice — so the `models` view pairs the count
372
+ with the cache the switch actually cost, which only a provider switch can: two
373
+ models never share a cache to lose. The panel's `?` overlay defines every
374
+ number in place.
375
+
376
+ ### The Go forecast
377
+
378
+ OpenCode 2.4 already has a native **Usage** dialog: the Desktop command
379
+ **View usage** lists the Go rolling/weekly/monthly meters and the Console
380
+ budgets; the TUI `/usage` dialog lists the Console budgets and the remaining
381
+ allowance per model. The plugin's `go` view adds what that dialog does not
382
+ show: the monthly **forecast**, the exact renewal instant, and a chart in the
383
+ Desktop panel. `/usage` remains the host's command; the plugin command is
384
+ `/usage-insights`.
385
+
386
+ The forecast uses the average pace of the current monthly cycle:
387
+
388
+ ```text
389
+ start = monthly resetsAt - 1 calendar month (inferred)
390
+ elapsed = now - start
391
+ rate = percent / elapsedDays
392
+ projected = percent + rate * remainingDays
393
+ exhaustAt = now + (100 - percent) / rate
394
+ ```
395
+
396
+ It is a percentage projection, not a dollar amount or a token estimate. The
397
+ host exposes whole-number percentages and the reset instant, but not the start
398
+ of the cycle, so the start is inferred. When nothing has been used yet it reads
399
+ `no monthly usage yet`; when the cycle is younger than 30 minutes it says it is
400
+ too early to project. The `renews` line below the forecast is the exact
401
+ `monthly.resetsAt` in local time, with its countdown.
402
+
403
+ The TUI sidebar and the Desktop **Turns insights** tab show the compact form:
404
+
405
+ ```text
406
+ OpenCode Go
407
+ 5h 2% · week 9% · month 40%
408
+ forecast ~77% at reset
409
+ renews 15 Dec 22:06
410
+ ```
411
+
412
+ The values come from the host's local usage-limits endpoint. The plugin never
413
+ reads the Console API key and makes no external request; `quota: "off"` hides
414
+ the view, the TUI sidebar block and the Desktop Turns block, and stops the poll.
415
+
416
+ The host payload names the meters but not the paid plan (Go, Go Plus or Go
417
+ Teams); the UI therefore uses the provider display name or `quotaName`, and
418
+ falls back to the full `OpenCode Go`. Set `quotaName` to your plan name if you
419
+ want Go Plus/Teams reflected. The name line is shown above the numbers in both
420
+ sidebars and in the `go` view header.
351
421
 
352
422
  ## Configuration
353
423
 
354
- Options apply to both parts (each side reads the ones it needs):
424
+ Options apply to all three parts (each side reads the ones it needs):
355
425
 
356
426
  | Option | Default | Meaning |
357
427
  | --- | --- | --- |
358
428
  | `enabled` | `true` | `false` disables that side completely — no line, no panel, no recording. |
359
- | `db` | per-OS state path | SQLite path override. Must match between the server and TUI parts. |
429
+ | `db` | per-OS state path | SQLite path override, resolved by the **server**. The TUI and Desktop read it through the RPC and never open the file. |
360
430
  | `turnTotals` | `"latest"` | How the turn segment counts prompt usage: `latest` shows the prompt size the turn ended with; `sum` adds every step of the turn. |
361
- | `pricing` | `"auto"` | `"off"` disables list-price estimates everywhere: no new `list_cost` records, no `≈` on the line, in the panel or in the sidebar, and no historical backfill. Charged money is unaffected. |
362
- | `sidebar` | `true` | Show the session summary and the per-prompt history — cache hit and cost per turn — in the session sidebar (the slot is invisible while the sidebar is hidden). |
363
- | `sidebarTurns` | `8` | How many turns the sidebar history shows. The host sidebar scrolls; raise it for a longer history. |
364
- | `panel` | `true` | Show the `/usage` statistics panel and its command. `false` keeps the line and the sidebar. |
431
+ | `pricing` | `"auto"` | `"off"` disables list-price estimates everywhere: no new `list_cost` records, no `≈` on the line, badge, panel or sidebar, and no historical backfill. Charged money is unaffected. |
432
+ | `sidebar` | `true` | TUI-only: show the session summary and the per-prompt history in the session sidebar. The Desktop history is the Turns insights tab. |
433
+ | `sidebarTurns` | `8` | How many turns the TUI sidebar and the Desktop Turns insights tab show (`1`–`50`; values outside are clamped). |
434
+ | `panel` | `true` | Show the `/usage-insights` statistics panel and its command in the TUI and Desktop. `false` keeps the line and the history. |
435
+ | `quota` | `"auto"` | Client-side OpenCode Go allowance. `"off"` hides the `go` view, the TUI sidebar and Desktop Turns blocks, and makes no usage-limits request. |
436
+ | `quotaName` | `"OpenCode Go"` | Full subscription label shown in the `go` view and compact blocks. Set `"OpenCode Go Plus"` (or your Go Teams/Plus name) when the plan is not the standard Go; the host usage payload does not carry `planType`. |
437
+ | `maintenance` | `true` | Allow the RPC to prune, wipe, vacuum and backfill. Set `false` on servers reachable from other machines. |
438
+ | `exposePaths` | `false` | Return the absolute database path in the `db` view; the default returns only the file name. |
365
439
  | `fields` | see below | Toggle line segments. |
366
440
  | `labels` | see below | Override line labels (the plugin is English-only by default). |
367
441
 
@@ -392,19 +466,53 @@ The recorder writes to the per-user state directory:
392
466
 
393
467
  `OPENCODE_USAGE_INSIGHTS_DB=/path/to/usage.db` overrides the path, and the `db`
394
468
  option overrides both. The file is private to the user: its directory is created
395
- `0700` and the file `0600` (POSIX), re-applied on every open. The TUI's views
396
- read through a read-only connection, so they never write, migrate or take the
397
- recorder's lock; prune, backfill and compact use a separate short-lived writer.
398
- The server part applies schema migrations on open; after an upgrade, start it
399
- once before opening the panel if the file predates the new schema.
469
+ `0700` and the file `0600` (POSIX), re-applied on every open. The TUI and the
470
+ Desktop GUI never open the file. They call the usage RPC; the server's worker
471
+ holds a read-only connection for the panel and the history, so a view can never
472
+ write, migrate or take the recorder's lock. Prune, backfill and compact use a
473
+ separate short-lived writer inside the worker. The server part applies schema
474
+ migrations on open; after an upgrade, start it once before opening the panel if
475
+ the file predates the new schema.
400
476
 
401
477
  Per step the database holds tokens, charged cost, the list-price estimate when
402
478
  the host reported `$0`, timings, finish reason, the configured provider and the
403
479
  model it ran through, and the session title and working directory. **Prompts and
404
- responses are not stored**, and nothing leaves the machine. The schema, the
405
- indexes, the identity rules and the security notes live in
480
+ responses are not stored**, and the plugin sends nothing to a third party; a
481
+ remote client reads the server's data over the authenticated RPC. The schema,
482
+ indexes, identity rules and security notes live in
406
483
  [docs/internals.md](docs/internals.md).
407
484
 
485
+ ### Security and remote servers
486
+
487
+ The usage RPC is served by the OpenCode server and inherits its authentication.
488
+ It is not a new unauthenticated endpoint, but it is a new authenticated surface:
489
+ any client that can call the server API can call it, and the RPC handler has no
490
+ caller identity (`RpcCallContext` exposes only cancellation and declared
491
+ errors). The plugin therefore applies least privilege at the surface:
492
+
493
+ - **Read-only by default for queries.** `panel`, `turns`, `listCost`, `filters`
494
+ and `dbInfo` run on the worker's read-only SQLite connection. The only writes
495
+ are `prune`, `wipe`, `vacuum` and `backfill`, gated by `maintenance` and an
496
+ explicit confirmation.
497
+ - **No free-form access.** There is no SQL, path, import or export method. Inputs
498
+ are validated by JSON Schema with closed objects, enums, length limits and
499
+ numeric clamps; the service validates them again. SQL is parameterized.
500
+ - **Minimal output.** The RPC returns usage metadata — session titles,
501
+ directories, models, providers, tokens, costs and the database shape — never
502
+ prompts or responses. Database paths are returned as a file name unless
503
+ `exposePaths: true`.
504
+ - **Availability.** The worker keeps panel queries off the server's event loop;
505
+ the client queue is bounded while the worker is in use. Reads have a 10 s
506
+ watchdog; maintenance gets five minutes. Generic errors are returned; details
507
+ stay in the server log.
508
+
509
+ For a server reachable from another machine, set `maintenance: false` unless you
510
+ need the maintenance buttons there. The RPC is only as protected as the server:
511
+ do not expose an OpenCode server without its password/auth. The usage database
512
+ is per server user; every authenticated client on that server sees the same
513
+ sessions and aggregates. If you need per-user or per-tenant isolation, do not
514
+ expose the RPC until the database carries that dimension.
515
+
408
516
  ## CLI report
409
517
 
410
518
  From a checkout, the database can be read without opening the TUI:
@@ -423,21 +531,32 @@ bun run report --import backup.jsonl # merge an export (idempotent)
423
531
  bun run report --help
424
532
  ```
425
533
 
426
- The views come from the same `buildPanel` the TUI renders, so the terminal and
427
- the panel never drift apart. `--width`, `--granularity`, `--model`,
428
- `--provider`, `--sort` and `--asc` mirror what the panel's keys do.
534
+ The views come from the same `buildPanel` the TUI and the Desktop render, so the
535
+ terminal and the panels never drift apart. Run this on the server that owns the
536
+ database; it is the local CLI counterpart to the RPC. `--width`,
537
+ `--granularity`, `--model`, `--provider`, `--sort` and `--asc` mirror what the
538
+ panel's controls do.
429
539
 
430
540
  ## Development
431
541
 
432
542
  ```sh
433
543
  bun install
434
- bun run typecheck # tsc --noEmit, strict
435
- bun test # pure logic + database + TUI harness + render tests
436
- bun run build # dist/index.js, dist/tui.js and declarations
544
+ bun run typecheck # server, TUI and the separate Desktop DOM typecheck
545
+ bun run build # dist/index.js, tui.js, rpc.js, stats-worker.js, gui-experimental.cjs
546
+ bun test # pure logic + database + TUI harness + worker/RPC tests
547
+ bun run check:package
548
+ bun run bench # query budgets at 20k steps (--full for 120k)
549
+ bun run check:platform
437
550
  bun run demo # print the line and every view from a seeded database
438
551
  bun run docs:images # re-render docs/images/*.png (needs ImageMagick)
552
+ bun run dev:gui # vite build --watch for the Desktop part
439
553
  ```
440
554
 
555
+ For the Desktop development loop, point the local plugin at the package root
556
+ (built once) and keep `bun run dev:gui` running: each GUI rebuild reloads the
557
+ bundle in every Desktop window. Server or TUI source changes still need
558
+ `opencode service restart`.
559
+
441
560
  - `src/core.ts`, `src/line.ts`, `src/panel-data.ts` and `src/stats/` are pure:
442
561
  turn accounting, the host-shape adapter, the view models, and the database,
443
562
  queries and analysis layer. No host imports, so they are unit-testable without
@@ -445,15 +564,26 @@ bun run docs:images # re-render docs/images/*.png (needs ImageMagick)
445
564
  - `src/text.ts` — text hygiene and the token shape a provider id is validated
446
565
  against.
447
566
  - `src/recorder.ts` — the event-stream state machine that fills the database.
448
- - `src/panel-build.ts`, `src/panel.tsx`, `src/sidebar.tsx` — panel assembly, the
449
- panel component, and the sidebar contribution.
450
- - `src/index.ts`, `src/tui.tsx` — the server and TUI parts.
451
- - `scripts/` — the demo, report, bench, platform-check and documentation-image
452
- CLIs, plus the two-entry `Bun.build`.
567
+ - `src/quota.ts`, `src/quota-client.ts` — the OpenCode Go meter types, the
568
+ monthly forecast, formatting, and the local usage-limits read. No Console
569
+ credentials and no external request.
570
+ - `src/rpc.ts`, `src/rpc-client.ts` — the shared RPC contract and its typed
571
+ client wrapper.
572
+ - `src/service.ts`, `src/stats-worker.ts`, `src/stats-client.ts` — the database
573
+ service, the worker that runs it off the server's event loop, and the bounded
574
+ server-side client with its in-process fallback.
575
+ - `src/panel-build.ts`, `src/panel.tsx`, `src/sidebar.tsx` — server-side panel
576
+ assembly, the TUI panel component, and the TUI sidebar contribution.
577
+ - `src/gui.tsx`, `src/gui/` — the Desktop entry, header badge, panels, line
578
+ helpers, CSS, icon and copy.
579
+ - `src/index.ts`, `src/tui.tsx` — the server (recorder + RPC + worker) and TUI
580
+ parts.
581
+ - `scripts/` — the demo, report, bench, platform-check, package-check and
582
+ documentation-image CLIs, plus the Bun/Vite build.
453
583
 
454
584
  See [CONTRIBUTING.md](CONTRIBUTING.md) for the ground rules and review
455
585
  expectations, and [docs/internals.md](docs/internals.md) for the database
456
- design, performance rules and how the TUI side is tested.
586
+ design, performance rules and how the clients are tested.
457
587
 
458
588
  ## License
459
589