opencode-usage-insights 0.1.2 → 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
@@ -5,38 +5,43 @@
5
5
  [![Lint](https://img.shields.io/github/actions/workflow/status/hugobatista/opencode-usage-insights/lint.yml?label=Lint)](https://github.com/hugobatista/opencode-usage-insights/actions/workflows/lint.yml)
6
6
  [![npm](https://img.shields.io/npm/v/opencode-usage-insights.svg)](https://www.npmjs.com/package/opencode-usage-insights)
7
7
 
8
- OpenCode plugin for one question the host cannot answer: **which provider is
9
- actually serving each model** — and what that costs. It shows a telemetry line
10
- above the composer after every finished turn and records every assistant step
11
- in a local SQLite file, read back through an interactive `/usage` panel.
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 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.
12
13
 
13
14
  ![The telemetry line after a turn](docs/images/line.png)
14
15
 
15
- Everything stays local: one SQLite file under the OpenCode state directory,
16
- written by the server-side recorder and read by the TUI.
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.
17
20
 
18
21
  ## What it does
19
22
 
20
- - **The line** (`session.composer.top`): end time, the gap since the previous
21
- prompt, the provider and model that ran the turn, turn and session token
22
- totals, and warnings when the prompt cache or the provider identity changed.
23
- It belongs to finished work, so it stays hidden while a turn is running.
24
- - **The `/usage` panel**: nine keyboard-driven views — `overview`, `models`,
25
- `providers`, `cache`, `periods`, `latency`, `sessions`, `turns`,
26
- `db` — over five ranges (`session`, `today`, `7d`, `30d`, `all`), with
27
- drill-downs, sorting, filters and state remembered between openings.
28
- `/usage models 7d`, `/usage providers 30d`, `/usage turns 7d`.
29
- - **The session sidebar**: the session's own totals and its last turns, in the
30
- same buckets as the line. Three lines per turn — when and through which
31
- provider, the prompt volumes, then `hit · tok/s · cost` — plus the model at
32
- both ends of the block and on any turn that changed it, so the history reads
33
- whether it is the whole session or a window of a long one:
34
- `16:54 opencode-go` / `deepseek-v4.1-flash max` /
35
- `in 1.7k (427.3k) · out 1.06k` / `hit 99.7% · 1.2k/s · $0.0006`.
36
- - **The record** (server entry): every assistant step with tokens, charged cost,
37
- the list-price estimate when the host reported `$0`,
38
- timings, finish reason, the provider and model it ran as, and its session and
39
- parent ids; prompts, session lifecycle and compaction events too.
23
+ - **The line** (`session.composer.top`): what the turn cost, the tokens and
24
+ prompt cache behind it, when it ended, the gap since the previous prompt, the
25
+ model and configured provider, and warnings when the prompt cache or the
26
+ provider changed. It belongs to finished work, so it stays hidden while a
27
+ turn is running.
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.
40
45
  - **Portable data** (from a checkout): `bun run report --ndjson` exports the
41
46
  whole database, and `--import` merges it back on another machine.
42
47
  - **Observational by design**: the plugin never rewrites prompts, requests or
@@ -45,14 +50,16 @@ written by the server-side recorder and read by the TUI.
45
50
 
46
51
  ## Requirements
47
52
 
48
- - **OpenCode V2** (`>=2.0.0`). The V2 release changed the plugin API (slots,
49
- 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.
50
56
  - [Bun](https://bun.sh) to install dependencies (development only).
51
57
 
52
58
  | | |
53
59
  | --- | --- |
54
- | **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. |
55
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. |
56
63
 
57
64
  ## Install
58
65
 
@@ -62,8 +69,17 @@ The plugin is published on npm as `opencode-usage-insights`.
62
69
  opencode plugin add opencode-usage-insights
63
70
  ```
64
71
 
65
- Or add the package to `~/.config/opencode/opencode.jsonc` (server entry) and
66
- `~/.config/opencode/cli.json` (TUI entry):
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.
81
+
82
+ If you prefer to edit the configuration yourself:
67
83
 
68
84
  ```jsonc
69
85
  // ~/.config/opencode/opencode.jsonc
@@ -73,45 +89,41 @@ Or add the package to `~/.config/opencode/opencode.jsonc` (server entry) and
73
89
  }
74
90
  ```
75
91
 
76
- ```jsonc
77
- // ~/.config/opencode/cli.json
78
- {
79
- "$schema": "https://opencode.ai/v2/cli.json",
80
- "plugins": ["opencode-usage-insights"]
81
- }
82
- ```
83
-
84
92
  To pass [options](#configuration), use the object form:
85
93
 
86
94
  ```jsonc
87
95
  {
88
96
  "plugins": [
89
- { "package": "opencode-usage-insights", "options": { "sidebarTurns": 5 } }
97
+ { "package": "opencode-usage-insights", "options": { "sidebarTurns": 8 } }
90
98
  ]
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:
97
105
 
98
- ```jsonc
99
- // ~/.config/opencode/opencode.jsonc
100
- { "plugins": [{ "package": "/home/you/code/projects/opencode-usage-insights/src" }] }
106
+ ```sh
107
+ cd /home/you/code/projects/opencode-usage-insights
108
+ bun install
109
+ bun run build
101
110
  ```
102
111
 
103
112
  ```jsonc
104
- // ~/.config/opencode/cli.json
105
- { "plugins": [{ "package": "/home/you/code/projects/opencode-usage-insights/src" }] }
113
+ // ~/.config/opencode/opencode.jsonc
114
+ { "plugins": [{ "package": "/home/you/code/projects/opencode-usage-insights" }] }
106
115
  ```
107
116
 
108
- 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,
109
120
  restart the background service with `opencode service restart`.
110
121
 
111
- Send a prompt to verify: the telemetry line appears above the composer when the
112
- 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.
113
125
 
114
- ## The line
126
+ ## The TUI line
115
127
 
116
128
  ```text
117
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)
@@ -121,134 +133,149 @@ turn finishes, and `/usage` (alias `/insights`) opens the panel.
121
133
  | --- | --- |
122
134
  | `14:32:07` | When the response ended (`completed`, else `streamed`, else `created`). |
123
135
  | `Δ 3m12s` | Time since the previous prompt of the same session. |
124
- | `opencode-go/deepseek-v4.1-flash max` | The identity of the turn: the provider the model ran through, as OpenCode is configured, 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. |
125
- | `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. |
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. |
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. |
126
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. |
127
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. |
128
- | `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, 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`. |
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`. |
129
141
  | `⚠ cache expired (−11.7k)` | Yellow. The prompt cache read fell by that many tokens against a comparable previous step; `×N` when several steps in the turn lost cache. |
130
142
 
131
143
  The turn segment carries no label by default — the numbers are the turn's, and
132
144
  `sess` marks the session's; `labels.turn` (e.g. `"turn"`) brings a prefix back.
133
145
 
134
- `≈` is an estimate at the host's list price, never a charge. It appears when
135
- OpenCode reports a step at `$0` — subscription-covered Go requests, or a provider
136
- that stopped reporting a cost — and the host's model list still has a price. A
137
- genuinely free model has no price and therefore no estimate; it is recorded as
138
- known free rather than as an unknown price. The estimate is stored per step, so
139
- the line's `sess` segment, the panel, the sidebar, the NDJSON export and the CLI
140
- report all show the same number. The `db` view lists how many `$0` steps still
141
- 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).
142
152
 
143
153
  A turn is every consecutive assistant step after a prompt. Compaction, shell,
144
154
  `idle` and info messages do not split a turn; `user`, `synthetic` and `system`
145
155
  messages do. From a checkout, `bun run demo` prints one example per case,
146
156
  including the streaming one and both turn-total views.
147
157
 
148
- ## How costs are calculated
158
+ ## OpenCode Desktop
149
159
 
150
- **Charged money is never recalculated by the plugin.** `steps.cost` is what the
151
- host reports for the step (possibly `0` for an OpenCode Go subscription). When
152
- that number is `0` or missing and the model has a price in the host's model
153
- list, the plugin computes a **list-price estimate** and stores it in
154
- `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.
155
164
 
156
- The price source is the model list exposed by the OpenCode process that is
157
- currently serving the session, already resolved by the host (provider config,
158
- 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.
159
169
 
160
- | Surface | Where the price comes from |
161
- | --- | --- |
162
- | Server recorder | `ctx.model.list()` → `ModelInfo.cost` |
163
- | Live turn / backfill | `ctx.data.location.model.list(ctx.location)` → `ModelInfo.cost` |
164
- | Panel, sidebar, NDJSON, CLI report | stored `steps.list_cost` |
165
- | `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.
166
172
 
167
- The plugin does **not** read `~/.cache/opencode/models.json`, does **not** use
168
- `opencode models` for prices (it lists model IDs only), and makes no network
169
- call of its own. Each `ModelInfo` carries the prices as
170
- `cost: Array<{ input, output, cache: { read, write }, tier? }>` in USD per
171
- 1,000,000 tokens.
173
+ ### The cost badge
172
174
 
173
- 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`):
174
177
 
175
178
  ```text
176
- input fresh (uncached) prompt tokens
177
- cache.read prompt tokens read from the provider cache
178
- cache.write prompt tokens written to the provider cache
179
- output visible output tokens
180
- reasoning reasoning tokens
181
-
182
- prompt = input + cache.read + cache.write
183
- cost = (input * inputPrice
184
- + (output + reasoning) * outputPrice
185
- + cache.read * cacheReadPrice
186
- + cache.write * cacheWritePrice) / 1_000_000
179
+ $0.0210
187
180
  ```
188
181
 
189
- Reasoning is billed at the output price. For models with context tiers, the
190
- tier applies only when the whole prompt is **strictly greater** than the tier
191
- size; at exactly the threshold the untiered price applies. An unknown model or
192
- no applicable price means no estimate; an all-zero price means the model is
193
- 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.
194
187
 
195
- The buckets behind the line are the same ones the estimate uses, but folded for
196
- display:
188
+ ### Usage insights and Turns insights
197
189
 
198
- ```text
199
- in = input + cache.write (the uncached part of the prompt)
200
- cached = cache.read
201
- out = output + reasoning
202
- prompt = in + cached
203
- ```
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**.
204
198
 
205
- `list_cost` has three meanings: `NULL` means the step was charged or its price
206
- is unknown; `0` means the model is known to be free; a positive value is the
207
- estimate. That is why a free model reads as `$0`, while an older model the
208
- 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:
209
201
 
210
- A worked example, using the prices of `opencode-go/deepseek-v4.1-flash`
211
- (`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. |
212
207
 
213
- ```text
214
- 2,591 × 0.15 + (564 + 3,239) × 0.6 + 514,944 × 0.003
215
- = 4,215.282 per 1,000,000 tokens
216
- = $0.004215282
217
- ```
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.
217
+
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.
222
+
223
+ ### Desktop options
224
+
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).
218
229
 
219
- What each surface shows:
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
239
+
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.
220
269
 
221
270
  | Situation | Line | Panel |
222
271
  | --- | --- | --- |
223
272
  | Charged | `cost $0.12` | `$0.12` |
224
- | Subscription-covered (host `0`, host model price known) | `cost ≈ $3.40` | `≈$3.40` |
225
- | Mixed (some charged, some covered) | `cost $0.12 + ≈ $3.40` | overview `$0.12 + ≈ $3.40`; table cell `≈$3.52` (charged + estimate) |
226
- | Known free model | cost omitted | `$0` |
227
- | Price unknown | cost omitted | `$0` |
228
-
229
- The **turn** estimate on the live line uses the model list the TUI currently
230
- has. The **`sess`** segment uses the estimate recorded per step and summed for
231
- the session, as do the panel, the sidebar, the NDJSON export and the CLI report.
232
- If a price changes after a step is recorded, the live turn can therefore differ
233
- from the stored history; `list_cost` freezes the price from the recording time.
234
- The server loads its model list in the background, refreshes it on
235
- `model.updated` and keeps the previous table if a refresh fails; the TUI
236
- invalidates its table on the same event and refreshes it on a coarse TTL.
237
-
238
- For a session, the charged total is the host's; the estimate is
239
- `SUM(list_cost)` over the steps the plugin recorded. If the plugin started
240
- recording in the middle of a session, the estimate covers only the recorded
241
- steps; the charged total still follows the host. When the database is
242
- unavailable, the line falls back to the host's charged total with no estimate.
243
-
244
- The `db` view counts the `$0` steps that have no known price yet. `e` retries
245
- them with today's host model list: free models become `0`, models still in that
246
- list get an estimate, and models the list no longer contains stay unknown. Steps
247
- without a provider/model or without tokens have nothing to price and are not
248
- counted. `pricing: "off"` stops new estimates, hides stored ones everywhere and
249
- disables the backfill, without deleting the data.
250
-
251
- ## 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
252
279
 
253
280
  `/usage [view] [range]` opens the panel (`/usage` alone opens the last view, or
254
281
  `overview` over `all` the first time). While the panel is open it owns input, so
@@ -270,7 +297,7 @@ a help overlay that repeats the keys and defines every number.
270
297
  | --- | --- |
271
298
  | `↑` `↓` / `j` `k` | Move the cursor; the row under it is highlighted. |
272
299
  | `pageup` `pagedown` / `home` `end` | Move by ten rows / to the first or last row. |
273
- | `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). |
274
301
  | `backspace` | Go back from a drill-down. |
275
302
  | `1`–`9` / `[` `]` | Pick a view (`9` is `db`) / cycle views. |
276
303
  | `t` / `shift+t` | Next / previous range. |
@@ -292,15 +319,15 @@ durable storage, so the panel reopens where it was left.
292
319
 
293
320
  | View | Answers |
294
321
  | --- | --- |
295
- | `overview` | Steps, sessions, prompts, `in`/`cached`/`write`/`out`, `hit`, cost, an activity sparkline, a `this session` block and a **data coverage** block (how many models and providers were observed, and how many steps lack a model or a completion — a zero elsewhere is only trustworthy when this is complete). |
296
- | `models` | Every model with its cache (`hit` and the per-step `hit p50`), tokens, cost, the **providers it ran through** and how often it switched model or provider — with the cache a provider switch cost. `enter` opens the per-provider detail. |
297
- | `providers` | **Who ran the work**: one row per provider, with the models it served, steps, share, prompt, cached, `hit`, p50 throughput, wall time and cost. `enter` lists every model it served. Steps recorded without a provider (a model that was never observed) are dimmed and cannot be drilled into. |
322
+ | `overview` | Steps, sessions, prompts, `in`/`cached`/`write`/`out`, `hit`, cost (with an `other` row naming the compaction/title part), an activity sparkline, a `this session` block and a **data coverage** block (how many models and providers were observed, and how many steps lack a model or a completion — a zero elsewhere is only trustworthy when this is complete). |
323
+ | `models` | Every model with its cache (`hit` and the per-step `hit p50`), tokens, cost, the **providers it ran through** and how often it switched model or provider — with the cache a provider switch cost. Cost is assistant steps only; `enter` opens the per-provider detail. |
324
+ | `providers` | **Which configured provider ran each model**: one row per provider, with the models it served, steps, share, prompt, cached, `hit`, p50 throughput, wall time and cost. Cost is assistant steps only. `enter` lists every model it served. Steps recorded without a provider (a model that was never observed) are dimmed and cannot be drilled into. |
298
325
  | `cache` | Reuse by model, losses grouped by reason (`expired`, `compaction`, `unknown`), **cache survival against idle time**, reuse kept per provider, the observed TTL bounds (`hits up to` / `drops from`) and the most recent losses. |
299
- | `periods` | Day, week or month totals — steps, sessions, `in`, `cached`, `write`, `hit`, `out`, cost — with a sparkline per metric and a totals row. `enter` lists the providers of a period. |
326
+ | `periods` | Day, week or month totals — steps, sessions, `in`, `cached`, `write`, `hit`, `out`, cost (including compaction/title usage) — with a sparkline per metric and a totals row. `enter` lists the providers of a period. |
300
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. |
301
- | `sessions` | Each session with steps, prompts, tokens, `hit`, cost, its directory and how many models it used; subagent sessions are indented under their parent and rolled up. |
302
- | `turns` | The per-prompt history: one line per finished turn, rendered exactly like the live line. `a` widens it to every session, titled. |
303
- | `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); `v` gives the space back. It also counts the `$0` steps with no list estimate; `e` backfills them at today's list price. |
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. |
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. |
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. |
304
331
 
305
332
  The panel sums the stored per-step buckets over the selected range, so a number
306
333
  read in one place means the same in the other: `prompt` is everything the
@@ -310,41 +337,44 @@ A `cost` cell marked `≈` includes list-price estimates for steps the host
310
337
  reported as `$0`; the overview and the sidebar keep a mixed total in two parts
311
338
  (`$0.12 + ≈ $3.40`) so charged money is never mistaken for the estimate.
312
339
 
313
- The identity of a step is the **provider the model ran through** — `opencode`,
314
- `opencode-go`, `deepseek`, whatever the provider is called in the OpenCode
315
- configuration — and the model itself. That is what every view groups by, and it
316
- is also the whole answer available: a gateway such as OpenCode Console may
317
- re-route a request to another operator, but that upstream is not observable from
318
- the plugin, and the identity a request *would* have been routed to is not
319
- evidence of who ran it. The provider is: the same model through `deepseek` and
320
- through `opencode-go` are two rows, two caches and two latency profiles, and a
321
- switch between them forfeits the cache the previous one held (the switch counts
322
- and the cache losses in the `models` view count exactly that).
340
+ The identity of a step is the **configured provider** the model ran through —
341
+ `opencode`, `opencode-go`, `deepseek`, whatever the provider is called in the
342
+ OpenCode configuration — and the model itself. That is what every view groups
343
+ by. A gateway may route a request to another operator, but that upstream is not
344
+ observable, so it is not guessed. The same model through `deepseek` and through
345
+ `opencode-go` is two rows, two caches and two latency profiles, and a switch
346
+ between them forfeits the cache the previous one held (the switch counts and the
347
+ cache losses in the `models` view count exactly that).
323
348
 
324
349
  `tps`/`wall`/`stream` are produced tokens per streaming second / request to
325
- completed step / request to the last chunk. The sidebar's rate (per turn, and
326
- the session average on its totals) is the **weighted** one — produced tokens
327
- divided by the summed streaming windows — so it answers "how fast did this
328
- produce"; the `latency` view reports the p50 of the per-step rates instead, which
329
- answers "how fast is a typical step". A switch from one step to the next is not
330
- by itself a fault — moving to another model or provider is a deliberate choice —
331
- so the `models` view pairs the count with the cache the switch actually cost,
332
- which only a provider switch can: two models never share a cache to lose. The
333
- 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.
334
362
 
335
363
  ## Configuration
336
364
 
337
- Options apply to both entries (each side reads the ones it needs):
365
+ Options apply to all three parts (each side reads the ones it needs):
338
366
 
339
367
  | Option | Default | Meaning |
340
368
  | --- | --- | --- |
341
369
  | `enabled` | `true` | `false` disables that side completely — no line, no panel, no recording. |
342
- | `db` | per-OS state path | SQLite path override. Must match between the server and TUI entries. |
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. |
343
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. |
344
- | `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. |
345
- | `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). |
346
- | `sidebarTurns` | `5` | How many turns the sidebar history shows. |
347
- | `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. |
348
378
  | `fields` | see below | Toggle line segments. |
349
379
  | `labels` | see below | Override line labels (the plugin is English-only by default). |
350
380
 
@@ -375,17 +405,52 @@ The recorder writes to the per-user state directory:
375
405
 
376
406
  `OPENCODE_USAGE_INSIGHTS_DB=/path/to/usage.db` overrides the path, and the `db`
377
407
  option overrides both. The file is private to the user: its directory is created
378
- `0700` and the file `0600` (POSIX), re-applied on every open. The TUI's views
379
- read through a read-only connection, so they never write, migrate or take the
380
- recorder's lock; prune, backfill and compact use a separate short-lived writer.
381
- The server entry applies schema migrations on open; after an upgrade, start it
382
- 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.
383
415
 
384
416
  Per step the database holds tokens, charged cost, the list-price estimate when
385
- the host reported `$0`, timings, finish reason, the provider and the model it ran
386
- as, and the session title and working directory. **Prompts and responses are not
387
- stored**, and nothing leaves the machine. The schema, the indexes, the identity
388
- rules and the security notes live in [docs/internals.md](docs/internals.md).
417
+ the host reported `$0`, timings, finish reason, the configured provider and the
418
+ model it ran through, and the session title and working directory. **Prompts and
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
422
+ [docs/internals.md](docs/internals.md).
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.
389
454
 
390
455
  ## CLI report
391
456
 
@@ -405,21 +470,32 @@ bun run report --import backup.jsonl # merge an export (idempotent)
405
470
  bun run report --help
406
471
  ```
407
472
 
408
- The views come from the same `buildPanel` the TUI renders, so the terminal and
409
- the panel never drift apart. `--width`, `--granularity`, `--model`,
410
- `--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.
411
478
 
412
479
  ## Development
413
480
 
414
481
  ```sh
415
482
  bun install
416
- bun run typecheck # tsc --noEmit, strict
417
- bun test # pure logic + database + TUI harness + render tests
418
- 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
419
489
  bun run demo # print the line and every view from a seeded database
420
490
  bun run docs:images # re-render docs/images/*.png (needs ImageMagick)
491
+ bun run dev:gui # vite build --watch for the Desktop part
421
492
  ```
422
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
+
423
499
  - `src/core.ts`, `src/line.ts`, `src/panel-data.ts` and `src/stats/` are pure:
424
500
  turn accounting, the host-shape adapter, the view models, and the database,
425
501
  queries and analysis layer. No host imports, so they are unit-testable without
@@ -427,15 +503,23 @@ bun run docs:images # re-render docs/images/*.png (needs ImageMagick)
427
503
  - `src/text.ts` — text hygiene and the token shape a provider id is validated
428
504
  against.
429
505
  - `src/recorder.ts` — the event-stream state machine that fills the database.
430
- - `src/panel-build.ts`, `src/panel.tsx`, `src/sidebar.tsx` — panel assembly, the
431
- panel component, and the sidebar contribution.
432
- - `src/index.ts`, `src/tui.tsx` — the server and TUI entries.
433
- - `scripts/` — the demo, report, bench, platform-check and documentation-image
434
- 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.
435
519
 
436
520
  See [CONTRIBUTING.md](CONTRIBUTING.md) for the ground rules and review
437
521
  expectations, and [docs/internals.md](docs/internals.md) for the database
438
- design, performance rules and how the TUI side is tested.
522
+ design, performance rules and how the clients are tested.
439
523
 
440
524
  ## License
441
525