chg: [opencode-greenpt-usage] port the TUI plugin to OpenCode 2

V1 TUI modules no longer load: replace ``{ id, tui }`` with
``Plugin.define({ id, setup })``, register the section on
``sidebar.content``, and expose commands through ``context.keymap.layer``.

Move balance, clock and usage state onto ``context.storage.store/memory``
so host subscribers rerender; plugin-created signals stayed stale in the
V2 renderer. Read V2 assistant messages (``type``,
``model.providerID``/``model.id``) and subscribe through ``context.data``.

Configure the package directory in ``cli.json`` instead of the source
file; document the V2 install. Typecheck, 49 unit tests and the live
GreenPT integration test pass, and the sidebar renders the balance.
This commit is contained in:
Stéphan Sainléger
2026-11-18 23:01:40 +01:00
parent 9c84473266
commit dadc93a22d
13 changed files with 4757 additions and 671 deletions

View File

@@ -2,7 +2,7 @@
## Project
`opencode-greenpt-usage` — an OpenCode **TUI** plugin (Solid + OpenTUI) that
`opencode-greenpt-usage` — an OpenCode **2** TUI plugin (Solid + OpenTUI) that
shows the remaining GreenPT API credit balance in the sidebar. Distributed by
`git clone`; there is no npm publish.
@@ -17,18 +17,23 @@ GREENPT_API_KEY=... npm run test:integration # live API test
## Conventions
- The plugin entry is the `default export { id, tui }` in `src/index.tsx`.
Types come from `@opencode-ai/plugin/tui` as **type-only** imports; the
host provides `solid-js` and `@opentui/solid` at runtime.
- The section is registered on the `sidebar_content` slot and is hidden when
no GreenPT credential is present (`showWhenUnavailable` opts into a hint).
- The plugin entry is `Plugin.define({ id: "greenpt.usage", setup })` in
`src/index.tsx` (default export). Types come from `@opencode/plugin/tui` and
`@opencode/plugin/tui/context` as **type-only** imports; the host provides
`solid-js` and `@opentui/*` at runtime.
- The section is registered on the `sidebar.content` slot via
`context.ui.slot({ append: ..., render })`, hidden when no GreenPT credential
is present (`showWhenUnavailable` opts into a hint). Commands use
`context.keymap.layer`; `setup` returns a cleanup that unregisters the slot
and disposes the store.
- Balance probing must stay **free**: `HEAD /v1/chat/completions` returns
`400` plus `x-credits-remaining`. Never replace it with a billable call.
- Usage accounting lives in `src/usage.ts` (pure) and is consumed by the
balance store: real spend = delta of `x-credits-remaining` between
probes; per-model detail = reconciliation of local OpenCode assistant
messages, idempotent by message id, persisted in the plugin KV store.
messages (V2 `type: "assistant"`, `model.providerID`/`model.id`),
idempotent by message id, persisted with `context.storage.store`.
- Credential resolution order: `apiKey` option, `GREENPT_API_KEY`, active
OpenCode `auth.json` (`greenpt`, `type: "api"`). No profile-switching
command may leak into this logic.
- No code comments unless functionally required.
- No explanatory inline comments; function contract blocks are required.

View File

@@ -1,7 +1,7 @@
# opencode-greenpt-usage
An [OpenCode](https://opencode.ai) TUI plugin that shows the remaining
**GreenPT API credit balance** and the **consumption** of the API key
An [OpenCode](https://opencode.ai) **OpenCode 2** TUI plugin that shows the
remaining **GreenPT API credit balance** and the **consumption** of the API key
(real credit spend plus a per-model breakdown) in the sidebar.
```
@@ -24,8 +24,8 @@ kimi-k2 3.1k tok ~0.01 €
the API answers `400 Bad Request` before any billing, yet the response
still carries the `x-credits-remaining` header. No credit is consumed
and no generation is triggered.
- **Usage tracking** keeps per-day buckets, persisted in the plugin KV
store (90 days by default):
- **Usage tracking** keeps per-day buckets, persisted in the plugin's durable
TUI store (90 days by default):
- *real credit spend* is observed as the drop of `x-credits-remaining`
between two balance probes — this covers **every client** of the API
key, not just OpenCode, but has no per-model detail;
@@ -47,7 +47,7 @@ looks for a key.
## Requirements
- OpenCode `>= 1.18.0` (TUI plugin system).
- OpenCode `>= 2.0.0` (V2 TUI plugin API).
- A GreenPT account and API key.
## Installation
@@ -64,35 +64,38 @@ looks for a key.
(Alternative: export `GREENPT_API_KEY` in your environment.)
3. **Register the plugin** in `~/.config/opencode/tui.json`, setting the
**absolute path to your clone**:
3. **Register the plugin** in `~/.config/opencode/cli.json`, pointing at the
**repository directory** (the package's `./tui` export):
```jsonc
{
"$schema": "https://opencode.ai/tui.json",
"plugin": [
["file:///ABSOLUTE/PATH/TO/opencode-greenpt-usage/src/index.tsx", { "order": 700 }]
"$schema": "https://opencode.ai/v2/cli.json",
"plugins": [
{
"package": "file:///ABSOLUTE/PATH/TO/opencode-greenpt-usage",
"options": { "refreshInterval": 60 }
}
]
}
```
> Use a `file://` URL pointing at the source file `src/index.tsx`
> (OpenCode compiles the TSX itself). Do not point at a bundle: that
> would embed a second copy of `solid-js` and the section would stay
> blank.
> V2 loads a package directory, not a source file. Do not point at
> `src/index.tsx`: a configured file is skipped. OpenCode compiles the TSX
> entrypoint itself.
4. **Fully quit OpenCode and relaunch it** (plugins are not hot-reloaded).
4. **Reload OpenCode**. V2 reloads configuration and plugins after a save; if
a running session keeps the old module, quit and relaunch it.
## Configuration
All options are optional and go in the plugin entry of `tui.json`:
All options are optional and go in the plugin entry of `cli.json`:
| Option | Type | Default | Description |
| --------------------- | ------- | --------------------------- | ------------------------------------------------------- |
| `apiKey` | string | resolved automatically | Explicit GreenPT key. |
| `baseUrl` | string | `https://api.greenpt.ai/v1` | GreenPT API base URL. |
| `refreshInterval` | number | `300` | Refresh interval in seconds (`0` disables the timer). |
| `order` | number | `700` | Sidebar section position. |
| `order` | number | ignored | Accepted for V1 compatibility; V2 orders slots by plugin load order. |
| `showWhenUnavailable` | boolean | `false` | Show a hint when no GreenPT key exists. |
| `unit` | string | `€` | Unit appended after the amount. |
| `trackUsage` | boolean | `true` | Track credit spend and per-model usage. |
@@ -103,7 +106,9 @@ All options are optional and go in the plugin entry of `tui.json`:
- **The section does not appear**: make sure `opencode auth login` stored a
`greenpt` key (or that `GREENPT_API_KEY` is set), and that the `file://`
URL in `tui.json` points at the right path.
entry in `cli.json` points at the **repository directory**, not at
`src/index.tsx`. Check that `opencode plugin list` lists your repository
directory.
- **"invalid GreenPT key"**: the API key was rejected (HTTP 401).
- **"balance unavailable"**: GreenPT did not return the balance header; try
again later.

4741
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
{
"name": "opencode-greenpt-usage",
"version": "0.1.0",
"description": "OpenCode TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
"description": "OpenCode 2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
"type": "module",
"license": "AGPL-3.0-or-later",
"keywords": [
@@ -13,21 +13,29 @@
"balance"
],
"engines": {
"opencode": ">=1.18.0"
"opencode": ">=2.0.0"
},
"exports": {
".": "./src/index.tsx",
"./tui": "./src/index.tsx"
},
"scripts": {
"test": "vitest run",
"test:integration": "GREENPT_INTEGRATION=1 vitest run test/integration.greenpt.test.ts",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@opencode/plugin": "^2.0.32"
},
"peerDependencies": {
"@opencode-ai/plugin": "*",
"@opentui/solid": "*",
"solid-js": "*"
"@opentui/core": ">=0.6.6",
"@opentui/solid": ">=0.6.6",
"solid-js": ">=1.9.0"
},
"devDependencies": {
"@opencode-ai/plugin": "^1.18.33",
"@opentui/solid": "^0.5.12",
"@opencode/plugin": "^2.0.32",
"@opentui/core": "^0.6.6",
"@opentui/solid": "^0.6.6",
"@types/node": "^24.0.0",
"solid-js": "^1.9.0",
"typescript": "^5.6.0",

View File

@@ -32,7 +32,8 @@ export type CredentialResult =
* login` produces.
*
* @param options Plugin options, possibly carrying an explicit key.
* @param stateDir OpenCode state directory (from `api.state.path.state`).
* @param stateDir Optional data-directory override used by tests; production
* resolution falls back to `$XDG_DATA_HOME` or `$HOME`.
* @param env Environment mapping, injectable for tests.
* @returns `{ ok: true, key }` when a key is found, otherwise
* `{ ok: false, reason: "missing" }`.

View File

@@ -1,9 +1,9 @@
import type { BalanceError } from "./balance"
/** Key used to persist the section fold state in the shared KV store. */
/** Key used to persist the section fold state in the durable TUI store. */
export const BALANCE_OPEN_KV = "greenpt.usage.open"
/** Key used to persist the usage day buckets in the shared KV store. */
/** Key used to persist the usage day buckets in the durable TUI store. */
export const USAGE_DAYS_KV = "greenpt.usage.days"
/** Default unit appended to the balance (GreenPT credits are euro-denominated). */
@@ -57,24 +57,3 @@ export function formatTokens(tokens: number): string {
const m = tokens / 1_000_000
return `${m < 100 ? m.toFixed(1) : String(Math.round(m))}M`
}
/**
* Read the persisted fold state, tolerating a missing or broken KV store.
*
* @param kv KV store exposing `get`, if available.
* @param fallback Value returned when the state is absent or invalid.
* @returns Whether the section should start expanded.
*/
export function readFoldOpen(
kv: { get: (key: string, fallback?: boolean) => unknown } | undefined,
fallback = true,
): boolean {
if (!kv) return fallback
try {
const value = kv.get(BALANCE_OPEN_KV, fallback)
if (typeof value !== "boolean") return fallback
return value
} catch {
return fallback
}
}

View File

@@ -1,59 +1,64 @@
/** @jsxImportSource @opentui/solid */
import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
import { Plugin } from "@opencode/plugin/tui"
import type { Context } from "@opencode/plugin/tui/context"
import { createBalanceStore, type BalanceOptions } from "./store"
import { GreenptWidget } from "./widget"
/** Sidebar slot order; the OpenCode Go widget uses 600. */
const DEFAULT_ORDER = 700
const tui: TuiPlugin = async (api, options) => {
const opts = (options ?? {}) as BalanceOptions
const store = createBalanceStore(api, opts)
api.slots.register({
order:
typeof opts.order === "number" && Number.isFinite(opts.order) ? opts.order : DEFAULT_ORDER,
slots: {
sidebar_content() {
return (
<GreenptWidget
api={api}
store={store}
showWhenUnavailable={opts.showWhenUnavailable === true}
unit={opts.unit}
/>
)
},
},
})
api.command?.register(() => [
{
value: "greenpt.refresh",
title: "Refresh GreenPT balance",
category: "Plugin",
onSelect() {
void store.refresh()
},
},
{
value: "greenpt.usage.reset",
title: "Reset GreenPT usage counters",
category: "Plugin",
onSelect() {
store.resetUsage()
},
},
])
api.lifecycle.onDispose(() => store.dispose())
void store.refresh()
}
const plugin: TuiPluginModule & { id: string } = {
/**
* OpenCode 2 TUI plugin definition.
*
* Registers the GreenPT section on `sidebar.content`, exposes refresh and
* reset commands through the keymap layer, and owns the balance store's
* lifetime. `order` is still accepted in config for V1 compatibility, but V2
* orders slot contributions by plugin load order.
*/
export default Plugin.define({
id: "greenpt.usage",
tui,
}
setup(context: Context) {
const options = (context.options ?? {}) as BalanceOptions
const store = createBalanceStore(context, options)
export default plugin
const unregisterSlot = context.ui.slot({
append: "sidebar.content",
render: () => (
<GreenptWidget
context={context}
store={store}
showWhenUnavailable={options.showWhenUnavailable === true}
unit={options.unit}
/>
),
})
context.keymap.layer(() => ({
mode: "global",
commands: [
{
id: "greenpt.refresh",
title: "Refresh GreenPT balance",
group: "Plugin",
run() {
void store.refresh()
},
},
{
id: "greenpt.usage.reset",
title: "Reset GreenPT usage counters",
group: "Plugin",
run() {
store.resetUsage()
},
},
],
}))
void store.refresh().catch((error) => {
console.error(`[greenpt.usage] refresh: ${error}`)
})
return () => {
unregisterSlot()
store.dispose()
}
},
})

View File

@@ -1,5 +1,4 @@
import { createSignal } from "solid-js"
import type { TuiPluginApi } from "@opencode-ai/plugin/tui"
import type { Context } from "@opencode/plugin/tui/context"
import { fetchBalance, nativeFetch, type Balance, type BalanceError, type FetchLike } from "./balance"
import { USAGE_DAYS_KV } from "./format"
import { resolveGreenptKey, type CredentialEnv } from "./credential"
@@ -10,7 +9,6 @@ import {
pruneUsage,
serializeUsage,
type UsageDays,
type UsageMessage,
} from "./usage"
/** Default GreenPT API base URL. */
@@ -29,6 +27,7 @@ export type BalanceOptions = {
apiKey?: string
baseUrl?: string
refreshInterval?: number
/** Accepted for V1 config compatibility; V2 orders slots by plugin load order. */
order?: number
showWhenUnavailable?: boolean
unit?: string
@@ -54,39 +53,49 @@ export type BalanceStore = {
dispose: () => void
}
type UsagePayload = {
version: number
days: Array<Record<string, unknown>>
}
const BACKOFF_BASE_MS = 60_000
const BACKOFF_MAX_MS = 10 * 60_000
const STATE_RETRY_MS = 5_000
const TICK_MS = 30_000
/**
* Create the reactive store backing the sidebar widget.
*
* Refreshes on creation, on `session.idle`, on `server.connected`, on a
* timer, and on demand via `refresh()`. Errors are retried with an
* exponential backoff so a transient outage does not hammer the API.
* Refreshes on creation, on `session.idle`, on `server.connected`, on a timer,
* and on demand via `refresh()`. Errors are retried with an exponential
* backoff so a transient outage does not hammer the API.
*
* Usage tracking (opt-out via `trackUsage: false`) keeps per-day buckets:
* real credit spend from balance deltas, and per-model token/cost totals
* reconciled from local OpenCode assistant messages. Buckets are persisted
* in the plugin KV store and pruned to `usageWindowDays`.
* reconciled from local OpenCode assistant messages. Buckets are persisted in
* the plugin's durable TUI store and pruned to `usageWindowDays`.
*
* @param api TUI plugin API (used for the auth store path, events, KV and
* session messages).
* @param context TUI plugin context (events, session data, storage).
* @param options Plugin options.
* @param env Environment mapping, injectable for tests.
* @param fetchImpl Fetch implementation, injectable for tests.
* @returns The store.
*/
export function createBalanceStore(
api: TuiPluginApi,
context: Context,
options: BalanceOptions = {},
env: CredentialEnv = process.env as CredentialEnv,
fetchImpl: FetchLike = nativeFetch,
): BalanceStore {
const [state, setState] = createSignal<BalanceState>({ status: "loading" })
const [now, setNow] = createSignal(Date.now())
const [usageDays, setUsageDays] = createSignal<UsageDays>(readUsageDays(api.kv))
const [usagePayload, updateUsagePayload] = context.storage.store<UsagePayload>(
USAGE_DAYS_KV,
{ initial: { version: 1, days: [] } },
)
const [balance, setBalance] = context.storage.memory<BalanceState>("greenpt.balance", {
initial: { status: "loading" },
})
const [clock, setClock] = context.storage.memory<{ value: number }>("greenpt.now", {
initial: { value: Date.now() },
})
const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL
const interval = options.refreshInterval ?? DEFAULT_REFRESH_SECONDS
@@ -96,56 +105,69 @@ export function createBalanceStore(
let refreshTimer: ReturnType<typeof setTimeout> | undefined
let tickTimer: ReturnType<typeof setTimeout> | undefined
let stateRetryTimer: ReturnType<typeof setTimeout> | undefined
let persistChain: Promise<void> = Promise.resolve()
let backoff = BACKOFF_BASE_MS
let inFlight = false
let disposed = false
let retriedState = false
let lastCredits: number | undefined
let kvLoaded = false
const trackedSessions = new Set<string>()
const controller = new AbortController()
const unsubscribeIdle = api.event.on("session.idle", (event) => {
trackSession(event.properties.sessionID)
const unsubscribeIdle = context.data.on("session.idle", (event) => {
trackSession(event.data.sessionID)
reconcileSessions()
void refresh()
})
const unsubscribeStatus = api.event.on("session.status", (event) => {
trackSession(event.properties.sessionID)
const unsubscribeStatus = context.data.on("session.status", (event) => {
trackSession(event.data.sessionID)
})
const unsubscribeConnected = api.event.on("server.connected", () => void refresh())
const unsubscribeConnected = context.data.on("server.connected", () => void refresh())
function readUsageDays(kv: TuiPluginApi["kv"]): UsageDays {
try {
const raw = kv.get(USAGE_DAYS_KV)
if (raw === undefined) return {}
return parseUsageDays(raw)
} catch {
return {}
}
}
function writeUsageDays(kv: TuiPluginApi["kv"], days: UsageDays): void {
try {
kv.set(USAGE_DAYS_KV, serializeUsage(days))
} catch {
// KV persistence is optional; in-memory buckets remain usable.
}
/**
* Replace the balance snapshot in place so host store subscribers rerender.
*
* @param next Snapshot to publish.
*/
function replaceBalance(next: BalanceState): void {
setBalance((draft) => {
for (const key of Object.keys(draft)) delete (draft as Record<string, unknown>)[key]
Object.assign(draft, next)
})
}
/** Add a session to the set reconciled for per-model usage. */
function trackSession(sessionID: string): void {
if (sessionID) trackedSessions.add(sessionID)
}
/** Apply usage mutations through a fresh top-level record for reactivity. */
/**
* Apply usage mutations in the durable store.
*
* Writes are chained so concurrent refreshes cannot interleave payloads.
*
* @param mutate Callback mutating a fresh copy of the buckets.
*/
function mutateUsage(mutate: (days: UsageDays) => void): void {
if (!trackUsage) return
const days: UsageDays = { ...usageDays() }
mutate(days)
pruneUsage(days, usageWindowDays, Date.now())
setUsageDays(days)
writeUsageDays(api.kv, days)
persistChain = persistChain
.then(() =>
updateUsagePayload((draft) => {
const days = parseUsageDays(draft)
mutate(days)
pruneUsage(days, usageWindowDays, Date.now())
const payload = serializeUsage(days) as UsagePayload
draft.version = payload.version
draft.days = payload.days
}),
)
.catch((error) => {
console.error(`[greenpt.usage] persist: ${error}`)
})
}
/** Current usage buckets, read reactively from the durable store. */
function usageDays(): UsageDays {
return parseUsageDays(usagePayload)
}
/**
@@ -155,93 +177,69 @@ export function createBalanceStore(
function reconcileSessions(): void {
if (!trackUsage || trackedSessions.size === 0) return
for (const sessionID of trackedSessions) {
let messages: ReadonlyArray<UsageMessage> | undefined
try {
messages = api.state.session.messages(sessionID)
} catch {
continue
}
const messages = context.data.session.message.list(sessionID)
if (!messages?.length) continue
mutateUsage((days) => applyMessages(days, messages as ReadonlyArray<unknown>))
mutateUsage((days) => applyMessages(days, messages))
}
}
/** Best-effort startup backfill from recently updated sessions. */
async function backfillUsage(): Promise<void> {
if (!trackUsage || usageBackfillLimit <= 0) return
const client = api.client as
| {
session?: {
list?: (parameters?: { limit?: number }) => Promise<unknown>
messages?: (parameters: { sessionID: string }) => Promise<unknown>
}
}
| undefined
if (!client?.session?.list || !client.session.messages) return
try {
const listed = (await client.session.list({ limit: usageBackfillLimit })) as {
data?: unknown
}
if (!Array.isArray(listed?.data)) return
for (const session of listed.data) {
const sessions = context.data.session.list()
const recent = [...sessions]
.sort((a, b) => (b.time?.updated ?? 0) - (a.time?.updated ?? 0))
.slice(0, usageBackfillLimit)
for (const session of recent) {
if (disposed) return
const sessionID = (session as { id?: unknown })?.id
if (typeof sessionID !== "string" || !sessionID) continue
trackedSessions.add(sessionID)
trackedSessions.add(session.id)
try {
const result = (await client.session.messages({ sessionID })) as { data?: unknown }
if (!Array.isArray(result?.data)) continue
const messages = result.data
.map((row) => (row as { info?: unknown })?.info)
.filter((info) => info !== undefined && info !== null)
mutateUsage((days) => applyMessages(days, messages))
} catch {
// One unreadable session must not abort the whole backfill.
await context.data.session.message.sync(session.id)
mutateUsage((days) =>
applyMessages(days, context.data.session.message.list(session.id)),
)
} catch (error) {
console.error(`[greenpt.usage] backfill ${session.id}: ${error}`)
}
}
} catch {
// Backfill is optional; live tracking continues regardless.
await persistChain
} catch (error) {
console.error(`[greenpt.usage] backfill: ${error}`)
}
}
/** Re-read persisted buckets once the KV store becomes ready. */
function reloadUsageWhenReady(): void {
if (!trackUsage || kvLoaded || api.kv.ready !== true) return
kvLoaded = true
setUsageDays(readUsageDays(api.kv))
}
function scheduleNext() {
/** Arm the next periodic refresh, backing off after errors. */
function scheduleNext(): void {
if (disposed) return
if (refreshTimer) clearTimeout(refreshTimer)
refreshTimer = undefined
const intervalMs = interval * 1000
if (intervalMs <= 0) return
const delay = state().status === "error" ? backoff : intervalMs
const delay = balance.status === "error" ? backoff : intervalMs
refreshTimer = setTimeout(() => {
refreshTimer = undefined
void refresh()
}, delay)
}
function tick() {
/** Advance the clock used for day/month totals. */
function tick(): void {
if (disposed) return
setNow(Date.now())
setClock((draft) => {
draft.value = Date.now()
})
tickTimer = setTimeout(tick, TICK_MS)
}
/** Probe the balance and reconcile usage from tracked sessions. */
async function refresh(): Promise<void> {
if (disposed || inFlight) return
inFlight = true
reloadUsageWhenReady()
try {
const credential = resolveGreenptKey(options, api.state.path.state, env)
const credential = resolveGreenptKey(options, undefined, env)
if (!credential.ok) {
setState({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
if (api.state.path.state === undefined && !retriedState) {
retriedState = true
stateRetryTimer = setTimeout(() => void refresh(), STATE_RETRY_MS)
}
replaceBalance({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
return
}
@@ -264,16 +262,17 @@ export function createBalanceStore(
}
lastCredits = credits
}
setState({ status: "ready", data: result, fetchedAt: Date.now() })
replaceBalance({ status: "ready", data: result, fetchedAt: Date.now() })
} else {
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS)
setState({ status: "error", error: result })
replaceBalance({ status: "error", error: result })
}
} finally {
inFlight = false
}
if (disposed) return
reconcileSessions()
await persistChain
scheduleNext()
}
@@ -287,12 +286,12 @@ export function createBalanceStore(
tickTimer = setTimeout(tick, TICK_MS)
function dispose() {
/** Stop timers, network work and event subscriptions. */
function dispose(): void {
disposed = true
controller.abort()
if (refreshTimer) clearTimeout(refreshTimer)
if (tickTimer) clearTimeout(tickTimer)
if (stateRetryTimer) clearTimeout(stateRetryTimer)
unsubscribeIdle()
unsubscribeStatus()
unsubscribeConnected()
@@ -300,5 +299,12 @@ export function createBalanceStore(
void backfillUsage()
return { state, now, usageDays, refresh, resetUsage, dispose }
return {
state: () => balance as BalanceState,
now: () => clock.value,
usageDays,
refresh,
resetUsage,
dispose,
}
}

View File

@@ -47,12 +47,14 @@ export type UsageTotals = {
byModel: ModelTotal[]
}
/** Structural subset of an OpenCode assistant message used for accounting. */
/** Structural subset of an OpenCode 2 assistant message used for accounting. */
export type UsageMessage = {
id?: unknown
role?: unknown
providerID?: unknown
modelID?: unknown
type?: unknown
model?: {
providerID?: unknown
id?: unknown
}
cost?: unknown
time?: { created?: unknown }
tokens?: {
@@ -108,7 +110,7 @@ export function emptyDay(date: string): DayUsage {
export function isUsageMessage(value: unknown): value is UsageMessage {
if (typeof value !== "object" || value === null) return false
const message = value as UsageMessage
return message.role === "assistant" && typeof message.id === "string"
return message.type === "assistant" && typeof message.id === "string"
}
/**
@@ -117,7 +119,7 @@ export function isUsageMessage(value: unknown): value is UsageMessage {
* @returns `true` when the message was newly recorded.
*/
export function recordMessage(days: UsageDays, message: UsageMessage): boolean {
const provider = typeof message.providerID === "string" ? message.providerID : ""
const provider = typeof message.model?.providerID === "string" ? message.model.providerID : ""
if (provider && !GREENPT_PROVIDER_PATTERN.test(provider)) return false
const created = message.time?.created
@@ -128,7 +130,7 @@ export function recordMessage(days: UsageDays, message: UsageMessage): boolean {
const cost = num(message.cost)
if (totalTokens(tokens) === 0 && cost === 0) return false
const model = typeof message.modelID === "string" && message.modelID ? message.modelID : "unknown"
const model = typeof message.model?.id === "string" && message.model.id ? message.model.id : "unknown"
const date = dayKey(created)
const day = days[date] ?? emptyDay(date)
if (day.ids.includes(message.id as string)) return false

View File

@@ -1,14 +1,7 @@
/** @jsxImportSource @opentui/solid */
import { createSignal, For, Match, Show, Switch } from "solid-js"
import type { TuiPluginApi, TuiThemeCurrent } from "@opencode-ai/plugin/tui"
import {
formatBalanceError,
formatCredits,
formatTokens,
readFoldOpen,
BALANCE_OPEN_KV,
DEFAULT_UNIT,
} from "./format"
import { For, Match, Show, Switch } from "solid-js"
import type { Context } from "@opencode/plugin/tui/context"
import { BALANCE_OPEN_KV, formatBalanceError, formatCredits, formatTokens, DEFAULT_UNIT } from "./format"
import { dayTotals, monthTotals, type ModelTotal } from "./usage"
import type { BalanceStore } from "./store"
@@ -22,24 +15,24 @@ import type { BalanceStore } from "./store"
* GreenPT never sees an empty or misleading block.
*/
export function GreenptWidget(props: {
api: TuiPluginApi
context: Context
store: BalanceStore
showWhenUnavailable: boolean
unit?: string
}) {
const theme = () => props.api.theme.current
const theme = () => props.context.theme
const [fold, updateFold] = props.context.storage.store<{ open: boolean }>(
BALANCE_OPEN_KV,
{ initial: { open: true } },
)
const state = () => props.store.state()
const status = () => state().status
const [open, setOpen] = createSignal(readFoldOpen(props.api.kv))
const open = () => fold.open
const toggle = () => {
const next = !open()
setOpen(next)
try {
props.api.kv.set(BALANCE_OPEN_KV, next)
} catch {
// KV persistence is optional; the local toggle still applies.
}
void updateFold((draft) => {
draft.open = !draft.open
})
}
const error = () => {
@@ -83,12 +76,12 @@ export function GreenptWidget(props: {
return (
<Show when={!hidden()} fallback={<box />}>
<box flexDirection="column" gap={1}>
<text fg={theme().text} onMouseUp={toggle}>
<span style={{ fg: theme().textMuted }}>{open() ? "▼ " : "▶ "}</span>
<text fg={theme().text.base} onMouseUp={toggle}>
<span style={{ fg: theme().text.muted }}>{open() ? "▼ " : "▶ "}</span>
<b>GreenPT</b>
<Show when={!open() && balanceText()}>
{(text) => (
<span style={{ fg: theme()[balanceColor()] }}>
<span style={{ fg: theme().text.feedback[balanceColor()].base }}>
{" "}
{text()}
{foldedSuffix()}
@@ -100,38 +93,42 @@ export function GreenptWidget(props: {
<Switch>
<Match when={status() === "ready"}>
<box flexDirection="row" gap={1} justifyContent="space-between">
<text fg={theme().textMuted}>Balance</text>
<text fg={theme().text.muted}>Balance</text>
<box flexDirection="row" gap={1}>
<text fg={theme()[balanceColor()]}>{balanceText()}</text>
<text fg={theme().textMuted}>{updatedAt()}</text>
<text fg={theme().text.feedback[balanceColor()].base}>{balanceText()}</text>
<text fg={theme().text.muted}>{updatedAt()}</text>
</box>
</box>
</Match>
<Match when={status() === "loading"}>
<text fg={theme().textMuted}>loading…</text>
<text fg={theme().text.muted}>loading…</text>
</Match>
<Match when={credentialReason() !== undefined && props.showWhenUnavailable}>
<CredentialHint reason={credentialReason()!} theme={theme()} />
</Match>
<Match when={status() === "error"}>
<text fg={theme().textMuted}>{formatBalanceError(error()!)}</text>
<text fg={theme().text.muted}>{formatBalanceError(error()!)}</text>
</Match>
</Switch>
<Show when={usageVisible()}>
<box flexDirection="row" gap={1} justifyContent="space-between">
<text fg={theme().textMuted}>Spent</text>
<text fg={theme().text.muted}>Spent</text>
<box flexDirection="row" gap={1}>
<text fg={theme().text}>today {todayText()}</text>
<text fg={theme().textMuted}>month {monthText()}</text>
<text fg={theme().text.base}>today {todayText()}</text>
<text fg={theme().text.muted}>month {monthText()}</text>
</box>
</box>
<For each={modelRows()}>
{(row) => (
<box flexDirection="row" gap={1} justifyContent="space-between">
<text fg={theme().textMuted}>{row.model}</text>
<text fg={theme().text.muted}>{row.model}</text>
<box flexDirection="row" gap={1}>
<text fg={theme().textMuted}>{formatTokens(row.usage.tokens.input + row.usage.tokens.output)} tok</text>
<text fg={theme().text}>~{formatCredits(row.usage.cost)} {unit()}</text>
<text fg={theme().text.muted}>
{formatTokens(row.usage.tokens.input + row.usage.tokens.output)} tok
</text>
<text fg={theme().text.base}>
~{formatCredits(row.usage.cost)} {unit()}
</text>
</box>
</box>
)}
@@ -147,9 +144,9 @@ export function GreenptWidget(props: {
* Hint shown when the credential is missing and the section is explicitly
* kept visible.
*/
function CredentialHint(props: { reason: "missing"; theme: TuiThemeCurrent }) {
function CredentialHint(props: { reason: "missing"; theme: Context["theme"] }) {
return (
<text fg={props.theme.textMuted}>
<text fg={props.theme.text.muted}>
{props.reason === "missing" ? "no GreenPT key (/connect)" : "no GreenPT key"}
</text>
)

View File

@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"
import { formatBalanceError, formatCredits, formatTokens, readFoldOpen } from "../src/format"
import { formatBalanceError, formatCredits, formatTokens } from "../src/format"
describe("formatCredits", () => {
it("formats with two decimals", () => {
@@ -49,27 +49,3 @@ describe("formatBalanceError", () => {
expect(formatBalanceError({ kind: "no-credential", reason: "missing" })).toContain("GreenPT")
})
})
describe("readFoldOpen", () => {
it("defaults to open when the KV store is absent", () => {
expect(readFoldOpen(undefined)).toBe(true)
})
it("reads a persisted boolean", () => {
expect(readFoldOpen({ get: () => false })).toBe(false)
})
it("falls back when the stored value is not a boolean", () => {
expect(readFoldOpen({ get: () => "nope" })).toBe(true)
})
it("survives a throwing KV store", () => {
expect(
readFoldOpen({
get: () => {
throw new Error("kv down")
},
}),
).toBe(true)
})
})

View File

@@ -1,19 +1,59 @@
import { describe, expect, it, vi } from "vitest"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createBalanceStore, type BalanceOptions } from "../src/store"
import { nativeFetch } from "../src/balance"
import { serializeUsage, type UsageDays } from "../src/usage"
import { dayKey } from "../src/usage"
const NOW = new Date(2026, 9, 19, 15, 0, 0).getTime()
const DAY = "2026-10-19"
const DAY = dayKey(NOW)
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(NOW)
})
afterEach(() => {
vi.useRealTimers()
})
type FakeMessage = Record<string, unknown>
type UsagePayload = { version: number; days: Array<Record<string, unknown>> }
function makeApi() {
const kvData = new Map<string, unknown>()
function makeContext() {
const payload: UsagePayload = { version: 1, days: [] }
const fold = { open: true }
const messages = new Map<string, FakeMessage[]>()
const sessions: Array<{ id: string; time: { updated: number } }> = []
const handlers = new Map<string, Array<(event: unknown) => void>>()
const api = {
event: {
const memory = new Map<string, unknown>()
const context = {
storage: {
store: (key: string, options: { initial: unknown }) => {
const target =
key === "greenpt.usage.days"
? payload
: key === "greenpt.usage.open"
? fold
: options.initial
return [
target,
async (mutation: (draft: unknown) => void) => {
mutation(target)
},
] as const
},
memory: (key: string, options: { initial: unknown }) => {
if (!memory.has(key)) memory.set(key, options.initial)
const target = memory.get(key)
return [
target,
(mutation: (draft: unknown) => void) => {
mutation(target)
},
] as const
},
},
data: {
on: (type: string, handler: (event: unknown) => void) => {
const list = handlers.get(type) ?? []
list.push(handler)
@@ -25,31 +65,19 @@ function makeApi() {
)
}
},
},
kv: {
ready: true,
get: (key: string, fallback?: unknown) => (kvData.has(key) ? kvData.get(key) : fallback),
set: (key: string, value: unknown) => {
kvData.set(key, value)
},
},
state: {
path: { state: "/tmp/fake-state" },
session: {
messages: (sessionID: string) => messages.get(sessionID) ?? [],
},
},
client: {
session: {
list: async () => ({ data: [] }),
messages: async () => ({ data: [] }),
list: () => sessions,
message: {
list: (sessionID: string) => messages.get(sessionID) ?? [],
sync: async () => {},
},
},
},
emit(type: string, event: unknown) {
for (const handler of handlers.get(type) ?? []) handler(event)
},
}
return { api, kvData, messages }
return { context, payload, fold, messages, sessions }
}
function balanceResponse(credits: number) {
@@ -65,15 +93,20 @@ function fetchSequence(credits: number[]) {
}) as unknown as typeof nativeFetch
}
function createTrackedStore(api: unknown, options: BalanceOptions = {}) {
return createBalanceStore(api as never, { apiKey: "test-key", ...options }, {}, fetchSequence([10]))
function createTrackedStore(context: unknown, options: BalanceOptions = {}) {
return createBalanceStore(
context as never,
{ apiKey: "test-key", ...options },
{},
fetchSequence([10]),
)
}
describe("usage tracking in the balance store", () => {
it("accumulates real credit spend from balance deltas", async () => {
const { api } = makeApi()
const { context } = makeContext()
const store = createBalanceStore(
api as never,
context as never,
{ apiKey: "test-key" },
{},
fetchSequence([10, 9.95, 9.9, 12]),
@@ -87,60 +120,58 @@ describe("usage tracking in the balance store", () => {
})
it("reconciles per-model usage from tracked sessions on refresh", async () => {
const { api, messages } = makeApi()
const store = createTrackedStore(api)
const { context, messages } = makeContext()
const store = createTrackedStore(context)
messages.set("s1", [
{
id: "m1",
role: "assistant",
providerID: "greenpt",
modelID: "glm-5.3-flash",
type: "assistant",
model: { providerID: "greenpt", id: "glm-5.3-flash" },
cost: 0.02,
time: { created: NOW },
tokens: { input: 10, output: 5, reasoning: 0, cache: { read: 0, write: 0 } },
},
])
api.emit("session.idle", { properties: { sessionID: "s1" } })
context.emit("session.idle", { data: { sessionID: "s1" } })
await store.refresh()
await store.refresh()
expect(store.usageDays()[DAY]?.byModel["glm-5.3-flash"]?.cost).toBeCloseTo(0.02)
store.dispose()
})
it("persists buckets to the KV store and reloads them", async () => {
const { api, kvData } = makeApi()
it("persists buckets to the durable store and reloads them", async () => {
const { context, payload } = makeContext()
const first = createBalanceStore(
api as never,
context as never,
{ apiKey: "test-key" },
{},
fetchSequence([10, 9.9]),
)
await first.refresh()
await first.refresh()
expect(kvData.has("greenpt.usage.days")).toBe(true)
expect(payload.days.length).toBeGreaterThan(0)
first.dispose()
const stored: UsageDays = { [DAY]: { date: DAY, creditsSpent: 0.5, byModel: {}, ids: [] } }
kvData.set("greenpt.usage.days", serializeUsage(stored))
const second = createTrackedStore(api)
expect(second.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.5)
const second = createTrackedStore(context)
expect(second.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.1)
second.dispose()
})
it("resetUsage clears buckets", async () => {
const { api } = makeApi()
const store = createTrackedStore(api)
const { context } = makeContext()
const store = createTrackedStore(context)
await store.refresh()
await store.refresh()
store.resetUsage()
await store.refresh()
expect(Object.keys(store.usageDays()).length).toBe(0)
store.dispose()
})
it("skips tracking when disabled", async () => {
const { api, kvData } = makeApi()
const { context, payload } = makeContext()
const store = createBalanceStore(
api as never,
context as never,
{ apiKey: "test-key", trackUsage: false },
{},
fetchSequence([10, 5]),
@@ -148,7 +179,7 @@ describe("usage tracking in the balance store", () => {
await store.refresh()
await store.refresh()
expect(Object.keys(store.usageDays()).length).toBe(0)
expect(kvData.has("greenpt.usage.days")).toBe(false)
expect(payload.days.length).toBe(0)
store.dispose()
})
})

View File

@@ -17,9 +17,8 @@ const NOW = new Date(2026, 9, 19, 15, 30, 0).getTime()
function assistantMessage(overrides: Record<string, unknown> = {}) {
return {
id: "msg-1",
role: "assistant",
providerID: "greenpt",
modelID: "glm-5.3-flash",
type: "assistant",
model: { providerID: "greenpt", id: "glm-5.3-flash" },
cost: 0.01,
time: { created: NOW },
tokens: { input: 100, output: 50, reasoning: 10, cache: { read: 5, write: 2 } },
@@ -53,7 +52,12 @@ describe("recordMessage", () => {
it("ignores non-GreenPT providers", () => {
const days: UsageDays = {}
expect(recordMessage(days, assistantMessage({ providerID: "anthropic" }))).toBe(false)
expect(
recordMessage(
days,
assistantMessage({ model: { providerID: "anthropic", id: "claude-sonnet" } }),
),
).toBe(false)
expect(Object.keys(days).length).toBe(0)
})
@@ -78,7 +82,7 @@ describe("applyMessages", () => {
it("skips user messages and unknown shapes", () => {
const days: UsageDays = {}
applyMessages(days, [
{ id: "u1", role: "user" },
{ id: "u1", type: "user" },
assistantMessage(),
null,
undefined,
@@ -104,7 +108,7 @@ describe("totals", () => {
recordMessage(days, assistantMessage())
recordMessage(
days,
assistantMessage({ id: "msg-2", modelID: "kimi-k2", cost: 0.05 }),
assistantMessage({ id: "msg-2", model: { providerID: "greenpt", id: "kimi-k2" }, cost: 0.05 }),
)
const day = dayTotals(days, NOW)
expect(day.byModel.map((row) => row.model)).toEqual(["kimi-k2", "glm-5.3-flash"])