opencode-usage-insights 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,15 +6,17 @@
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` 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 TUI and Desktop both read the
18
+ same recorder through an authenticated server RPC, so a client connected to a
19
+ remote server shows that server's data.
18
20
 
19
21
  ## What it does
20
22
 
@@ -23,24 +25,23 @@ the machine.
23
25
  model and configured provider, and warnings when the prompt cache or the
24
26
  provider changed. It belongs to finished work, so it stays hidden while a
25
27
  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.
28
+ - **The `/usage` panel**: nine views — `overview`, `models`, `providers`,
29
+ `cache`, `periods`, `latency`, `sessions`, `turns`, `db` — over five ranges
30
+ (`session`, `today`, `7d`, `30d`, `all`), with drill-downs, sorting, filters
31
+ and remembered state. Keyboard-driven in the TUI; the same views with desktop
32
+ controls in OpenCode Desktop. `/usage models 7d`, `/usage turns 7d`.
33
+ - **The Desktop header badge and panels**: a spend badge in the session header,
34
+ next to the peak/off-peak badge; clicking it opens **Turns insights**, the
35
+ session history. **Usage insights** holds the nine views and opens from
36
+ `/usage`. The Desktop window never opens SQLite: the server's worker serves
37
+ the panels and history over RPC.
38
+ - **The TUI sidebar**: the session's spend and last turns, in the same buckets
39
+ as the line — time, provider, wall duration, prompt volumes, then
40
+ `hit · tok/s · cost`. The duration is first request to last completion: tool
41
+ waits inside the turn count, idle gaps do not.
42
+ - **The record** (server): every step with tokens, charged cost, the list-price
43
+ estimate for `$0`, timings, finish reason and provider/model IDs; prompts,
44
+ lifecycle, compaction and `session.usage.recorded` events too.
44
45
  - **Portable data** (from a checkout): `bun run report --ndjson` exports the
45
46
  whole database, and `--import` merges it back on another machine.
46
47
  - **Observational by design**: the plugin never rewrites prompts, requests or
@@ -49,14 +50,16 @@ the machine.
49
50
 
50
51
  ## Requirements
51
52
 
52
- - **OpenCode V2** (`>=2.0.0`). The V2 release changed the plugin API (slots,
53
- panels, event stream).
53
+ - **OpenCode V2** (`>=2.4.2`). The Desktop GUI part uses the V2 GUI plugin API
54
+ (`./gui-experimental`), introduced in the 2.4 line. The server and TUI parts
55
+ run on the same server that records the sessions.
54
56
  - [Bun](https://bun.sh) to install dependencies (development only).
55
57
 
56
58
  | | |
57
59
  | --- | --- |
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. |
60
+ | **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
61
  | **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. |
62
+ | **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
63
 
61
64
  ## Install
62
65
 
@@ -66,10 +69,15 @@ The plugin is published on npm as `opencode-usage-insights`.
66
69
  opencode plugin add opencode-usage-insights
67
70
  ```
68
71
 
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.
72
+ This adds one entry to the global `opencode.json(c)`. That entry loads every
73
+ part of the package: the server recorder and RPC, the TUI contributions, and the
74
+ Desktop GUI. A TUI-only package goes in `~/.config/opencode/cli.json`; this
75
+ plugin has a server part, so `opencode.json(c)` is enough.
76
+
77
+ > **Desktop reads only `opencode.json(c)`.** If the plugin is in
78
+ > `~/.config/opencode/cli.json`, move that entry to `opencode.json(c)` and
79
+ > remove it from `cli.json`. One entry in `opencode.json(c)` covers the TUI and
80
+ > the Desktop; keeping both loads the TUI part twice.
73
81
 
74
82
  If you prefer to edit the configuration yourself:
75
83
 
@@ -91,22 +99,31 @@ To pass [options](#configuration), use the object form:
91
99
  }
92
100
  ```
93
101
 
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:
102
+ Or register a local checkout. Point at the **package root**, not `src/`: the
103
+ loader reads the package `exports`, which resolve the server, TUI, RPC and GUI
104
+ parts. Build once before loading it, and rebuild after source changes:
105
+
106
+ ```sh
107
+ cd /home/you/code/projects/opencode-usage-insights
108
+ bun install
109
+ bun run build
110
+ ```
97
111
 
98
112
  ```jsonc
99
113
  // ~/.config/opencode/opencode.jsonc
100
- { "plugins": [{ "package": "/home/you/code/projects/opencode-usage-insights/src" }] }
114
+ { "plugins": [{ "package": "/home/you/code/projects/opencode-usage-insights" }] }
101
115
  ```
102
116
 
103
- Configuration changes reload on their own; after changing the plugin's source,
117
+ For GUI development, keep `bun run dev:gui` running in another terminal; each
118
+ rebuild reloads the Desktop GUI in every window without restarting the server.
119
+ Configuration changes reload on their own; after changing server or TUI source,
104
120
  restart the background service with `opencode service restart`.
105
121
 
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.
122
+ Send a prompt to verify: the TUI line appears above the composer when the turn
123
+ finishes, the Desktop badge appears in the session header, and `/usage` (alias
124
+ `/insights`) opens the panel.
108
125
 
109
- ## The line
126
+ ## The TUI line
110
127
 
111
128
  ```text
112
129
  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 +134,7 @@ turn finishes, and `/usage` (alias `/insights`) opens the panel.
117
134
  | `14:32:07` | When the response ended (`completed`, else `streamed`, else `created`). |
118
135
  | `Δ 3m12s` | Time since the previous prompt of the same session. |
119
136
  | `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. |
137
+ | `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
138
  | `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
139
  | `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
140
  | `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,148 +143,139 @@ turn finishes, and `/usage` (alias `/insights`) opens the panel.
126
143
  The turn segment carries no label by default — the numbers are the turn's, and
127
144
  `sess` marks the session's; `labels.turn` (e.g. `"turn"`) brings a prefix back.
128
145
 
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.
146
+ `≈` marks a **list-price estimate**, never a charge. It appears when the host
147
+ reports `$0` for a model the catalog still prices; a known free model has no
148
+ estimate. The `sess` segment and historical views use the stored per-step
149
+ estimate, so they agree across clients; a live turn uses the client's current
150
+ catalog and can differ after a price change. The `db` view counts unpriced `$0`
151
+ steps and can backfill them (`e` in the TUI, **Backfill** in the Desktop panel).
137
152
 
138
153
  A turn is every consecutive assistant step after a prompt. Compaction, shell,
139
154
  `idle` and info messages do not split a turn; `user`, `synthetic` and `system`
140
155
  messages do. From a checkout, `bun run demo` prints one example per case,
141
156
  including the streaming one and both turn-total views.
142
157
 
143
- ## How costs are calculated
158
+ ## OpenCode Desktop
144
159
 
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.
160
+ The Desktop app loads the package's `./gui-experimental` bundle in every window.
161
+ The GUI plugin API is experimental in the 2.4 line; the bundle is tested against
162
+ OpenCode Desktop 2.4.2. The window is Electron/Chromium: it has no Bun, no
163
+ `bun:sqlite` and no Node filesystem.
150
164
 
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):
165
+ If the plugin was already installed before it gained the GUI part, restart the
166
+ background service once (`opencode service restart`) and reopen the Desktop
167
+ window. The plugin inventory caches the package's parts; a config reload may
168
+ reload the server entry without noticing the new `./gui-experimental` export.
154
169
 
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 |
170
+ The recorder, the database and the worker stay in the server; the window reads
171
+ them through the same RPC the TUI uses.
161
172
 
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.
173
+ ### The cost badge
167
174
 
168
- The estimate uses the host's own fallback formula:
175
+ In the session header, next to the peak/off-peak badge, the usage insights badge
176
+ shows the finished turn's spend (`$0.0210` or `≈$0.0210`):
169
177
 
170
178
  ```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
179
+ $0.0210
182
180
  ```
183
181
 
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.
182
+ Hovering shows the full telemetry line. Clicking it opens **Turns insights**.
183
+ The badge follows the TUI line and hides while a turn is running; it reappears
184
+ with the final amount. The `fields`, `labels`, `turnTotals` and `pricing`
185
+ options apply to the line, badge tooltip and panel; `fields.cost: false` hides
186
+ the badge as well.
189
187
 
190
- The buckets behind the line are the same ones the estimate uses, but folded for
191
- display:
188
+ ### Usage insights and Turns insights
192
189
 
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
- ```
190
+ `/usage` (and the hidden `/insights` alias) opens the **Usage insights** panel
191
+ in the side region. It has the same nine views, five ranges, drill-downs,
192
+ sorting and filters as the TUI, plus the database view's maintenance buttons.
193
+ The **Turns insights** tab shows the current session's history. `/usage turns`
194
+ opens the same history inside **Usage insights**, where the session/all-sessions
195
+ scope is available. Both panels have the inverse shortcut: **Usage insights**
196
+ has an **Open turns insights** footer button, and **Turns insights** has
197
+ **Open usage insights**.
199
198
 
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.
199
+ The TUI's always-visible sidebar has no Desktop slot. The Desktop equivalents
200
+ are:
204
201
 
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`):
202
+ | Where | What it shows |
203
+ | --- | --- |
204
+ | Session header badge | The turn spend and the full line on hover; click opens Turns insights. |
205
+ | Turns insights tab | The current session's complete history. `/usage turns` adds the session/all-sessions scope. |
206
+ | Side panel `+` menu | **Usage insights** and **Turns insights** launchers. |
207
207
 
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
- ```
208
+ The panel state is stored separately from the TUI: opening the Desktop panel
209
+ does not move the TUI panel, and vice versa.
210
+
211
+ ### The server side
212
+
213
+ 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
214
+ turn history, and opens a short write connection for `prune`, `wipe`, `vacuum`
215
+ and `backfill`. Panel queries therefore never block the agent's event loop, and
216
+ the TUI does not open SQLite either: it works against a local or a remote server.
213
217
 
214
- ### Compactions and titles
218
+ The worker starts lazily on the first usage request (the panel, the history or
219
+ the header badge estimate). If it cannot start (for example in a development
220
+ runtime), the server falls back to an in-process service and logs it; the
221
+ plugin still works, but the fallback shares the server's event loop.
215
222
 
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.
223
+ ### Desktop options
220
224
 
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.
225
+ All options are in [Configuration](#configuration). The two security-relevant
226
+ ones are `maintenance` (default `true`; set `false` on a server reachable from
227
+ other machines) and `exposePaths` (default `false`; keeps the absolute database
228
+ path out of the `db` view).
226
229
 
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.
230
+ ### Remote servers
231
+
232
+ The TUI and Desktop call the RPC on the server that owns the session. A TUI
233
+ connected to a remote server shows that server's usage; the Desktop GUI is
234
+ loaded from its own background server, but the panel targets the session's
235
+ server. The plugin's server part must be installed and enabled on that server.
236
+ If it is not, the panel explains that usage data is unavailable.
237
+
238
+ ## How costs are calculated
233
239
 
234
- What each surface shows:
240
+ **Charged money is never recalculated.** `steps.cost` is what the host reports.
241
+ When it is `0` or missing and the model has a price in the host's model list, the
242
+ plugin stores a **list-price estimate** in `steps.list_cost` (USD per 1M tokens).
243
+ `≈` marks an estimate, never a charge.
244
+
245
+ | Surface | Price source |
246
+ | --- | --- |
247
+ | Server recorder and backfill | `ctx.model.list()` |
248
+ | Live line (TUI/Desktop) | `data.location.model.list(location)` |
249
+ | Panel, sidebar, NDJSON, CLI | stored `steps.list_cost` |
250
+ | `sess` segment | `SUM(list_cost)` over the RPC |
251
+
252
+ The host resolves provider config/overrides. The plugin does not read
253
+ `~/.cache/opencode/models.json`, does not use `opencode models` for prices, and
254
+ makes no network call. `list_cost` is `NULL` for charged/unknown, `0` for a known
255
+ free model, and positive for an estimate. An unknown or inapplicable price means
256
+ no estimate; an all-zero price means free. The formula, context tiers and worked
257
+ example are in [docs/internals.md](docs/internals.md#list-price-estimates).
258
+
259
+ The host also reports compaction and title usage with no assistant step. It is
260
+ stored in `usage`, keyed by the host event ID, and included in the overview,
261
+ periods and sessions totals; it is not attributed to a model because the host
262
+ record carries none. See [docs/internals.md](docs/internals.md#non-step-usage).
263
+
264
+ The live line's turn estimate uses the client's current model list; the `sess`
265
+ segment and historical views use the stored estimate, which freezes the price at
266
+ recording time. If the plugin started mid-session, the estimate covers only the
267
+ recorded steps; the charged total still follows the host. `pricing: "off"` hides
268
+ estimates and disables the backfill without deleting data.
235
269
 
236
270
  | Situation | Line | Panel |
237
271
  | --- | --- | --- |
238
272
  | 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
273
+ | Covered (host `0`, price known) | `cost ≈ $3.40` | `≈$3.40` |
274
+ | Mixed | `cost $0.12 + ≈ $3.40` | `$0.12 + ≈ $3.40`; table `≈$3.52` |
275
+ | Compaction/title | in the host `sess` total | overview `other`; session/period cost |
276
+ | Known free / price unknown | cost omitted | `$0` |
277
+
278
+ ## The TUI panel
271
279
 
272
280
  `/usage [view] [range]` opens the panel (`/usage` alone opens the last view, or
273
281
  `overview` over `all` the first time). While the panel is open it owns input, so
@@ -289,7 +297,7 @@ a help overlay that repeats the keys and defines every number.
289
297
  | --- | --- |
290
298
  | `↑` `↓` / `j` `k` | Move the cursor; the row under it is highlighted. |
291
299
  | `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). |
300
+ | `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
301
  | `backspace` | Go back from a drill-down. |
294
302
  | `1`–`9` / `[` `]` | Pick a view (`9` is `db`) / cycle views. |
295
303
  | `t` / `shift+t` | Next / previous range. |
@@ -319,7 +327,7 @@ durable storage, so the panel reopens where it was left.
319
327
  | `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
328
  | `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
329
  | `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. |
330
+ | `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. |
323
331
 
324
332
  The panel sums the stored per-step buckets over the selected range, so a number
325
333
  read in one place means the same in the other: `prompt` is everything the
@@ -339,29 +347,34 @@ between them forfeits the cache the previous one held (the switch counts and the
339
347
  cache losses in the `models` view count exactly that).
340
348
 
341
349
  `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.
350
+ completed step / request to the last chunk. The sidebar's turn header shows the
351
+ turn's wall time — the first request to the last completed step, so any tool
352
+ wait inside the turn counts — while its rate is only the streaming window. The
353
+ sidebar's rate (per turn, and the session average on its totals) is the
354
+ **weighted** one — produced tokens divided by the summed streaming windows — so
355
+ it answers "how fast did this produce"; the `latency` view reports the p50 of
356
+ the per-step rates instead, which answers "how fast is a typical step". A
357
+ switch from one step to the next is not by itself a fault — moving to another
358
+ model or provider is a deliberate choice — so the `models` view pairs the count
359
+ with the cache the switch actually cost, which only a provider switch can: two
360
+ models never share a cache to lose. The panel's `?` overlay defines every
361
+ number in place.
351
362
 
352
363
  ## Configuration
353
364
 
354
- Options apply to both parts (each side reads the ones it needs):
365
+ Options apply to all three parts (each side reads the ones it needs):
355
366
 
356
367
  | Option | Default | Meaning |
357
368
  | --- | --- | --- |
358
369
  | `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. |
370
+ | `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
371
  | `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. |
372
+ | `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. |
373
+ | `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. |
374
+ | `sidebarTurns` | `8` | How many turns the TUI sidebar and the Desktop Turns insights tab show (`1`–`50`; values outside are clamped). |
375
+ | `panel` | `true` | Show the `/usage` statistics panel and its command in the TUI and Desktop. `false` keeps the line and the history. |
376
+ | `maintenance` | `true` | Allow the RPC to prune, wipe, vacuum and backfill. Set `false` on servers reachable from other machines. |
377
+ | `exposePaths` | `false` | Return the absolute database path in the `db` view; the default returns only the file name. |
365
378
  | `fields` | see below | Toggle line segments. |
366
379
  | `labels` | see below | Override line labels (the plugin is English-only by default). |
367
380
 
@@ -392,19 +405,53 @@ The recorder writes to the per-user state directory:
392
405
 
393
406
  `OPENCODE_USAGE_INSIGHTS_DB=/path/to/usage.db` overrides the path, and the `db`
394
407
  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.
408
+ `0700` and the file `0600` (POSIX), re-applied on every open. The TUI and the
409
+ Desktop GUI never open the file. They call the usage RPC; the server's worker
410
+ holds a read-only connection for the panel and the history, so a view can never
411
+ write, migrate or take the recorder's lock. Prune, backfill and compact use a
412
+ separate short-lived writer inside the worker. The server part applies schema
413
+ migrations on open; after an upgrade, start it once before opening the panel if
414
+ the file predates the new schema.
400
415
 
401
416
  Per step the database holds tokens, charged cost, the list-price estimate when
402
417
  the host reported `$0`, timings, finish reason, the configured provider and the
403
418
  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
419
+ responses are not stored**, and the plugin sends nothing to a third party; a
420
+ remote client reads the server's data over the authenticated RPC. The schema,
421
+ indexes, identity rules and security notes live in
406
422
  [docs/internals.md](docs/internals.md).
407
423
 
424
+ ### Security and remote servers
425
+
426
+ The usage RPC is served by the OpenCode server and inherits its authentication.
427
+ It is not a new unauthenticated endpoint, but it is a new authenticated surface:
428
+ any client that can call the server API can call it, and the RPC handler has no
429
+ caller identity (`RpcCallContext` exposes only cancellation and declared
430
+ errors). The plugin therefore applies least privilege at the surface:
431
+
432
+ - **Read-only by default for queries.** `panel`, `turns`, `listCost`, `filters`
433
+ and `dbInfo` run on the worker's read-only SQLite connection. The only writes
434
+ are `prune`, `wipe`, `vacuum` and `backfill`, gated by `maintenance` and an
435
+ explicit confirmation.
436
+ - **No free-form access.** There is no SQL, path, import or export method. Inputs
437
+ are validated by JSON Schema with closed objects, enums, length limits and
438
+ numeric clamps; the service validates them again. SQL is parameterized.
439
+ - **Minimal output.** The RPC returns usage metadata — session titles,
440
+ directories, models, providers, tokens, costs and the database shape — never
441
+ prompts or responses. Database paths are returned as a file name unless
442
+ `exposePaths: true`.
443
+ - **Availability.** The worker keeps panel queries off the server's event loop;
444
+ the client queue is bounded while the worker is in use. Reads have a 10 s
445
+ watchdog; maintenance gets five minutes. Generic errors are returned; details
446
+ stay in the server log.
447
+
448
+ For a server reachable from another machine, set `maintenance: false` unless you
449
+ need the maintenance buttons there. The RPC is only as protected as the server:
450
+ do not expose an OpenCode server without its password/auth. The usage database
451
+ is per server user; every authenticated client on that server sees the same
452
+ sessions and aggregates. If you need per-user or per-tenant isolation, do not
453
+ expose the RPC until the database carries that dimension.
454
+
408
455
  ## CLI report
409
456
 
410
457
  From a checkout, the database can be read without opening the TUI:
@@ -423,21 +470,32 @@ bun run report --import backup.jsonl # merge an export (idempotent)
423
470
  bun run report --help
424
471
  ```
425
472
 
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.
473
+ The views come from the same `buildPanel` the TUI and the Desktop render, so the
474
+ terminal and the panels never drift apart. Run this on the server that owns the
475
+ database; it is the local CLI counterpart to the RPC. `--width`,
476
+ `--granularity`, `--model`, `--provider`, `--sort` and `--asc` mirror what the
477
+ panel's controls do.
429
478
 
430
479
  ## Development
431
480
 
432
481
  ```sh
433
482
  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
483
+ bun run typecheck # server, TUI and the separate Desktop DOM typecheck
484
+ bun run build # dist/index.js, tui.js, rpc.js, stats-worker.js, gui-experimental.cjs
485
+ bun test # pure logic + database + TUI harness + worker/RPC tests
486
+ bun run check:package
487
+ bun run bench # query budgets at 20k steps (--full for 120k)
488
+ bun run check:platform
437
489
  bun run demo # print the line and every view from a seeded database
438
490
  bun run docs:images # re-render docs/images/*.png (needs ImageMagick)
491
+ bun run dev:gui # vite build --watch for the Desktop part
439
492
  ```
440
493
 
494
+ For the Desktop development loop, point the local plugin at the package root
495
+ (built once) and keep `bun run dev:gui` running: each GUI rebuild reloads the
496
+ bundle in every Desktop window. Server or TUI source changes still need
497
+ `opencode service restart`.
498
+
441
499
  - `src/core.ts`, `src/line.ts`, `src/panel-data.ts` and `src/stats/` are pure:
442
500
  turn accounting, the host-shape adapter, the view models, and the database,
443
501
  queries and analysis layer. No host imports, so they are unit-testable without
@@ -445,15 +503,23 @@ bun run docs:images # re-render docs/images/*.png (needs ImageMagick)
445
503
  - `src/text.ts` — text hygiene and the token shape a provider id is validated
446
504
  against.
447
505
  - `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`.
506
+ - `src/rpc.ts`, `src/rpc-client.ts` — the shared RPC contract and its typed
507
+ client wrapper.
508
+ - `src/service.ts`, `src/stats-worker.ts`, `src/stats-client.ts` — the database
509
+ service, the worker that runs it off the server's event loop, and the bounded
510
+ server-side client with its in-process fallback.
511
+ - `src/panel-build.ts`, `src/panel.tsx`, `src/sidebar.tsx` — server-side panel
512
+ assembly, the TUI panel component, and the TUI sidebar contribution.
513
+ - `src/gui.tsx`, `src/gui/` — the Desktop entry, header badge, panels, line
514
+ helpers, CSS, icon and copy.
515
+ - `src/index.ts`, `src/tui.tsx` — the server (recorder + RPC + worker) and TUI
516
+ parts.
517
+ - `scripts/` — the demo, report, bench, platform-check, package-check and
518
+ documentation-image CLIs, plus the Bun/Vite build.
453
519
 
454
520
  See [CONTRIBUTING.md](CONTRIBUTING.md) for the ground rules and review
455
521
  expectations, and [docs/internals.md](docs/internals.md) for the database
456
- design, performance rules and how the TUI side is tested.
522
+ design, performance rules and how the clients are tested.
457
523
 
458
524
  ## License
459
525