Compare commits

..

1 Commits

Author SHA1 Message Date
Stéphan Sainléger
5129f295da new: [opencode-greenpt-usage] port plugin to OpenCode v2
Rewrite the TUI plugin against the OpenCode v2 plugin API
(``@opencode/plugin`` + ``@opencode/plugin/tui``):

- ``src/index.ts``: minimal server-side ``Plugin.define`` entry.
- ``src/tui.tsx``: CLI plugin registered as ``./tui``, appending the
  widget to the ``sidebar.content`` slot through ``context.ui.slot``
  and exposing the refresh/reset commands via ``context.keymap.layer``.
- ``src/store.ts``: durable plugin storage (``context.storage.store``)
  replaces the KV store; ``session.idle``/``session.status`` events and
  the ``client.session`` API drive reconciliation and backfill.
- ``src/widget.tsx``: v2 semantic theme tokens
  (``theme.text.base``/``text.muted``/``text.feedback``).
- Tests updated to a structural fake of the v2 context.

The free ``HEAD /v1/chat/completions`` balance probe and the credential
resolution order are unchanged. The ``order`` option is gone: v2 slot
placement is additive.
2026-10-19 17:00:48 +02:00
14 changed files with 721 additions and 785 deletions

View File

@@ -2,9 +2,10 @@
## Project
`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.
`opencode-greenpt-usage` — an OpenCode **v2** CLI/TUI plugin (Solid + OpenTUI)
that shows the remaining GreenPT API credit balance in the sidebar.
Distributed by `git clone`; there is no npm publish. The `main` branch
targets OpenCode 1.x; this branch targets OpenCode `>= 2.0.0`.
## Commands
@@ -17,23 +18,21 @@ GREENPT_API_KEY=... npm run test:integration # live API test
## Conventions
- 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.
- The plugin has two entries: `src/index.ts` (server side, minimal
`Plugin.define`) and `src/tui.tsx` (CLI plugin, exposed as `./tui`).
Types come from `@opencode/plugin` and `@opencode/plugin/tui`; the host
provides `solid-js`, `@opentui/solid` and the theme at runtime.
- The section is appended to the `sidebar.content` slot and is hidden when
no GreenPT credential is present (`showWhenUnavailable` opts into a hint).
- Commands are registered through `context.keymap.layer` (palette).
- 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 (V2 `type: "assistant"`, `model.providerID`/`model.id`),
idempotent by message id, persisted with `context.storage.store`.
messages, idempotent by message id, persisted in the plugin durable
storage (`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 explanatory inline comments; function contract blocks are required.
- No code comments unless functionally required.

View File

@@ -1,7 +1,7 @@
# opencode-greenpt-usage
An [OpenCode](https://opencode.ai) **OpenCode 2** TUI plugin that shows the
remaining **GreenPT API credit balance** and the **consumption** of the API key
An [OpenCode](https://opencode.ai) 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's durable
TUI store (90 days by default):
- **Usage tracking** keeps per-day buckets, persisted in the plugin durable
storage (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,8 @@ looks for a key.
## Requirements
- OpenCode `>= 2.0.0` (V2 TUI plugin API).
- OpenCode `>= 2.0.0` (v2 CLI/TUI plugin system; for OpenCode 1.x use the
`main` branch).
- A GreenPT account and API key.
## Installation
@@ -64,8 +65,8 @@ looks for a key.
(Alternative: export `GREENPT_API_KEY` in your environment.)
3. **Register the plugin** in `~/.config/opencode/cli.json`, pointing at the
**repository directory** (the package's `./tui` export):
3. **Register the plugin** in `~/.config/opencode/cli.json`, setting the
**absolute path to your clone**:
```jsonc
{
@@ -73,29 +74,28 @@ looks for a key.
"plugins": [
{
"package": "file:///ABSOLUTE/PATH/TO/opencode-greenpt-usage",
"options": { "refreshInterval": 60 }
"options": { "showWhenUnavailable": false }
}
]
}
```
> 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.
> Point at the repository root, not at a source file: OpenCode v2 loads
> the `./tui` entry (`src/tui.tsx`) from the package `exports` and
> resolves `@opencode/plugin` at runtime.
4. **Reload OpenCode**. V2 reloads configuration and plugins after a save; if
a running session keeps the old module, quit and relaunch it.
4. **Fully quit OpenCode and relaunch it** (plugins are not hot-reloaded).
## Configuration
All options are optional and go in the plugin entry of `cli.json`:
All options are optional and go in the `options` object of the plugin entry
in `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 | 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. |
@@ -106,9 +106,7 @@ All options are optional and go in the plugin entry of `cli.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://`
entry in `cli.json` points at the **repository directory**, not at
`src/index.tsx`. Check that `opencode plugin list` lists your repository
directory.
path in `cli.json` points at the repository root.
- **"invalid GreenPT key"**: the API key was rejected (HTTP 401).
- **"balance unavailable"**: GreenPT did not return the balance header; try
again later.

841
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 2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
"version": "0.2.0",
"description": "OpenCode v2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
"type": "module",
"license": "AGPL-3.0-or-later",
"keywords": [
@@ -15,27 +15,26 @@
"engines": {
"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"
"exports": {
".": "./src/index.ts",
"./tui": "./src/tui.tsx"
},
"peerDependencies": {
"@opentui/core": ">=0.6.6",
"@opentui/solid": ">=0.6.6",
"@opencode/plugin": ">=2.0.0 <3",
"@opentui/core": ">=0.5.17",
"@opentui/solid": ">=0.5.17",
"solid-js": ">=1.9.0"
},
"devDependencies": {
"@opencode/plugin": "^2.0.32",
"@opentui/core": "^0.6.6",
"@opentui/solid": "^0.6.6",
"@opencode/theme": "^2.0.32",
"@opentui/core": "^0.5.17",
"@opentui/solid": "^0.5.17",
"@types/node": "^24.0.0",
"solid-js": "^1.9.0",
"typescript": "^5.6.0",

View File

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

View File

@@ -1,10 +1,7 @@
import type { BalanceError } from "./balance"
/** 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 durable TUI store. */
export const USAGE_DAYS_KV = "greenpt.usage.days"
/** Key used to persist the section fold state in the durable plugin storage. */
export const FOLD_STORAGE_KEY = "greenpt.usage.open"
/** Default unit appended to the balance (GreenPT credits are euro-denominated). */
export const DEFAULT_UNIT = "€"

6
src/index.ts Normal file
View File

@@ -0,0 +1,6 @@
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "greenpt.usage",
setup() {},
})

View File

@@ -1,19 +1,21 @@
import type { Context } from "@opencode/plugin/tui/context"
import { createSignal } from "solid-js"
import type { Context } from "@opencode/plugin/tui/plugin"
import { fetchBalance, nativeFetch, type Balance, type BalanceError, type FetchLike } from "./balance"
import { USAGE_DAYS_KV } from "./format"
import { resolveGreenptKey, type CredentialEnv } from "./credential"
import {
addCreditsSpent,
applyMessages,
parseUsageDays,
pruneUsage,
serializeUsage,
type UsageDays,
type UsageMessage,
} from "./usage"
/** Default GreenPT API base URL. */
export const DEFAULT_BASE_URL = "https://api.greenpt.ai/v1"
/** Storage key for the usage day buckets (durable plugin storage). */
export const USAGE_DAYS_KEY = "greenpt.usage.days"
/** Default refresh interval, in seconds. The probe is free but should stay gentle. */
export const DEFAULT_REFRESH_SECONDS = 300
@@ -27,8 +29,6 @@ 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
trackUsage?: boolean
@@ -47,34 +47,55 @@ export type BalanceState =
export type BalanceStore = {
state: () => BalanceState
now: () => number
usageDays: () => UsageDays
usageDays: UsageDays
refresh: () => Promise<void>
resetUsage: () => void
resetUsage: () => Promise<void>
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 TICK_MS = 30_000
/** Structural view of a v2 assistant message used for accounting. */
function toUsageMessages(messages: ReadonlyArray<unknown>): ReadonlyArray<UsageMessage> {
const out: UsageMessage[] = []
for (const message of messages) {
const m = message as {
type?: unknown
id?: unknown
model?: { providerID?: unknown; id?: unknown }
cost?: unknown
time?: { created?: unknown }
tokens?: UsageMessage["tokens"]
}
if (m?.type !== "assistant" || typeof m.id !== "string") continue
out.push({
id: m.id,
role: "assistant",
providerID: m.model?.providerID,
modelID: m.model?.id,
cost: m.cost,
time: { created: m.time?.created },
tokens: m.tokens,
})
}
return out
}
/**
* 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's durable TUI store and pruned to `usageWindowDays`.
* reconciled from local OpenCode assistant messages. Buckets live in the
* plugin durable storage and are pruned to `usageWindowDays`.
*
* @param context TUI plugin context (events, session data, storage).
* @param context OpenCode v2 TUI plugin context.
* @param options Plugin options.
* @param env Environment mapping, injectable for tests.
* @param fetchImpl Fetch implementation, injectable for tests.
@@ -86,16 +107,8 @@ export function createBalanceStore(
env: CredentialEnv = process.env as CredentialEnv,
fetchImpl: FetchLike = nativeFetch,
): BalanceStore {
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 [state, setState] = createSignal<BalanceState>({ status: "loading" })
const [now, setNow] = createSignal(Date.now())
const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL
const interval = options.refreshInterval ?? DEFAULT_REFRESH_SECONDS
@@ -103,9 +116,17 @@ export function createBalanceStore(
const usageWindowDays = options.usageWindowDays ?? DEFAULT_USAGE_WINDOW_DAYS
const usageBackfillLimit = options.usageBackfill ?? DEFAULT_USAGE_BACKFILL
let usageDays: UsageDays = {}
let updateUsage: (mutation: (draft: UsageDays) => void) => Promise<void> = () =>
Promise.resolve()
if (trackUsage) {
const stored = context.storage.store(USAGE_DAYS_KEY, { initial: {} as UsageDays })
usageDays = stored[0]
updateUsage = stored[1]
}
let refreshTimer: ReturnType<typeof setTimeout> | undefined
let tickTimer: ReturnType<typeof setTimeout> | undefined
let persistChain: Promise<void> = Promise.resolve()
let backoff = BACKOFF_BASE_MS
let inFlight = false
let disposed = false
@@ -115,7 +136,7 @@ export function createBalanceStore(
const unsubscribeIdle = context.data.on("session.idle", (event) => {
trackSession(event.data.sessionID)
reconcileSessions()
void reconcileSessions()
void refresh()
})
const unsubscribeStatus = context.data.on("session.status", (event) => {
@@ -123,123 +144,89 @@ export function createBalanceStore(
})
const unsubscribeConnected = context.data.on("server.connected", () => void refresh())
/**
* 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 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
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)
/** Apply usage mutations through the durable storage draft. */
function mutateUsage(mutate: (days: UsageDays) => void): Promise<void> {
if (!trackUsage) return Promise.resolve()
return updateUsage((draft) => {
mutate(draft)
pruneUsage(draft, usageWindowDays, Date.now())
})
}
/**
* Reconcile per-model usage from the messages of every tracked session.
* Idempotent: messages are de-duplicated by id in `usage.ts`.
*/
function reconcileSessions(): void {
if (!trackUsage || trackedSessions.size === 0) return
function reconcileSessions(): Promise<void> {
if (!trackUsage || trackedSessions.size === 0) return Promise.resolve()
const updates: Promise<void>[] = []
for (const sessionID of trackedSessions) {
const messages = context.data.session.message.list(sessionID)
let messages: ReadonlyArray<unknown> | undefined
try {
messages = context.data.session.message.list(sessionID)
} catch {
continue
}
if (!messages?.length) continue
mutateUsage((days) => applyMessages(days, messages))
updates.push(mutateUsage((days) => applyMessages(days, toUsageMessages(messages ?? []))))
}
return Promise.all(updates).then(() => undefined)
}
/** Best-effort startup backfill from recently updated sessions. */
async function backfillUsage(): Promise<void> {
if (!trackUsage || usageBackfillLimit <= 0) return
try {
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) {
const listed = await context.client.session.list({
limit: usageBackfillLimit,
})
for (const session of listed.data ?? []) {
if (disposed) return
trackedSessions.add(session.id)
const sessionID = (session as { id?: unknown })?.id
if (typeof sessionID !== "string" || !sessionID) continue
trackedSessions.add(sessionID)
try {
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}`)
const messages = await context.client.session.context({ sessionID })
await mutateUsage((days) => applyMessages(days, toUsageMessages(messages)))
} catch {
// One unreadable session must not abort the whole backfill.
}
}
await persistChain
} catch (error) {
console.error(`[greenpt.usage] backfill: ${error}`)
} catch {
// Backfill is optional; live tracking continues regardless.
}
}
/** Arm the next periodic refresh, backing off after errors. */
function scheduleNext(): void {
function scheduleNext() {
if (disposed) return
if (refreshTimer) clearTimeout(refreshTimer)
refreshTimer = undefined
const intervalMs = interval * 1000
if (intervalMs <= 0) return
const delay = balance.status === "error" ? backoff : intervalMs
const delay = state().status === "error" ? backoff : intervalMs
refreshTimer = setTimeout(() => {
refreshTimer = undefined
void refresh()
}, delay)
}
/** Advance the clock used for day/month totals. */
function tick(): void {
function tick() {
if (disposed) return
setClock((draft) => {
draft.value = Date.now()
})
setNow(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
try {
const credential = resolveGreenptKey(options, undefined, env)
if (!credential.ok) {
replaceBalance({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
setState({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
return
}
@@ -258,36 +245,34 @@ export function createBalanceStore(
if (trackUsage && Number.isFinite(credits)) {
if (lastCredits !== undefined && credits < lastCredits) {
const spent = lastCredits - credits
mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
await mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
}
lastCredits = credits
}
replaceBalance({ status: "ready", data: result, fetchedAt: Date.now() })
setState({ status: "ready", data: result, fetchedAt: Date.now() })
} else {
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS)
replaceBalance({ status: "error", error: result })
setState({ status: "error", error: result })
}
} finally {
inFlight = false
}
if (disposed) return
reconcileSessions()
await persistChain
await reconcileSessions()
scheduleNext()
}
/** Clear every persisted and in-memory usage bucket. */
function resetUsage(): void {
async function resetUsage(): Promise<void> {
lastCredits = undefined
mutateUsage((days) => {
await mutateUsage((days) => {
for (const date of Object.keys(days)) delete days[date]
})
}
tickTimer = setTimeout(tick, TICK_MS)
/** Stop timers, network work and event subscriptions. */
function dispose(): void {
function dispose() {
disposed = true
controller.abort()
if (refreshTimer) clearTimeout(refreshTimer)
@@ -299,12 +284,5 @@ export function createBalanceStore(
void backfillUsage()
return {
state: () => balance as BalanceState,
now: () => clock.value,
usageDays,
refresh,
resetUsage,
dispose,
}
return { state, now, usageDays, refresh, resetUsage, dispose }
}

View File

@@ -1,31 +1,32 @@
/** @jsxImportSource @opentui/solid */
import { Plugin } from "@opencode/plugin/tui"
import type { Context } from "@opencode/plugin/tui/context"
import { FOLD_STORAGE_KEY } from "./format"
import { createBalanceStore, type BalanceOptions } from "./store"
import { GreenptWidget } from "./widget"
/**
* 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",
setup(context: Context) {
const options = (context.options ?? {}) as BalanceOptions
const store = createBalanceStore(context, options)
id: "greenpt.usage.tui",
setup(context) {
const opts = (context.options ?? {}) as BalanceOptions
const store = createBalanceStore(context, opts)
const [fold, updateFold] = context.storage.store(FOLD_STORAGE_KEY, {
initial: { open: true },
})
const unregisterSlot = context.ui.slot({
append: "sidebar.content",
render: () => (
<GreenptWidget
context={context}
store={store}
showWhenUnavailable={options.showWhenUnavailable === true}
unit={options.unit}
theme={context.theme}
open={() => fold.open}
toggleOpen={() => {
void updateFold((draft) => {
draft.open = !fold.open
})
}}
showWhenUnavailable={opts.showWhenUnavailable === true}
unit={opts.unit}
/>
),
})
@@ -36,7 +37,8 @@ export default Plugin.define({
{
id: "greenpt.refresh",
title: "Refresh GreenPT balance",
group: "Plugin",
group: "GreenPT",
palette: true,
run() {
void store.refresh()
},
@@ -44,18 +46,15 @@ export default Plugin.define({
{
id: "greenpt.usage.reset",
title: "Reset GreenPT usage counters",
group: "Plugin",
group: "GreenPT",
palette: true,
run() {
store.resetUsage()
void store.resetUsage()
},
},
],
}))
void store.refresh().catch((error) => {
console.error(`[greenpt.usage] refresh: ${error}`)
})
return () => {
unregisterSlot()
store.dispose()

View File

@@ -47,14 +47,12 @@ export type UsageTotals = {
byModel: ModelTotal[]
}
/** Structural subset of an OpenCode 2 assistant message used for accounting. */
/** Structural subset of an OpenCode assistant message used for accounting. */
export type UsageMessage = {
id?: unknown
type?: unknown
model?: {
providerID?: unknown
id?: unknown
}
role?: unknown
providerID?: unknown
modelID?: unknown
cost?: unknown
time?: { created?: unknown }
tokens?: {
@@ -110,7 +108,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.type === "assistant" && typeof message.id === "string"
return message.role === "assistant" && typeof message.id === "string"
}
/**
@@ -119,7 +117,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.model?.providerID === "string" ? message.model.providerID : ""
const provider = typeof message.providerID === "string" ? message.providerID : ""
if (provider && !GREENPT_PROVIDER_PATTERN.test(provider)) return false
const created = message.time?.created
@@ -130,7 +128,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.model?.id === "string" && message.model.id ? message.model.id : "unknown"
const model = typeof message.modelID === "string" && message.modelID ? message.modelID : "unknown"
const date = dayKey(created)
const day = days[date] ?? emptyDay(date)
if (day.ids.includes(message.id as string)) return false

View File

@@ -1,27 +1,15 @@
/** @jsxImportSource @opentui/solid */
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 { createSignal, For, Match, Show, Switch } from "solid-js"
import type { ResolvedTheme } from "@opencode/theme/tui"
import {
formatBalanceError,
formatCredits,
formatTokens,
DEFAULT_UNIT,
} from "./format"
import { dayTotals, monthTotals, type ModelTotal } from "./usage"
import type { BalanceStore } from "./store"
/** Maximum characters before a model name is ellipsized in the table. */
const MODEL_NAME_MAX = 28
/** Number of model rows shown before the "other models" summary. */
const MODEL_ROWS_VISIBLE = 3
/**
* Shorten a model id for a narrow sidebar column.
*
* @param model Model id reported by OpenCode.
* @returns The id unchanged when short enough, otherwise an ellipsized form.
*/
function shortModel(model: string): string {
if (model.length <= MODEL_NAME_MAX) return model
return `${model.slice(0, MODEL_NAME_MAX - 1)}…`
}
/**
* Sidebar section showing the remaining GreenPT credit balance and the
* consumption of the API key: real credit spend per day/month plus a
@@ -32,25 +20,19 @@ function shortModel(model: string): string {
* GreenPT never sees an empty or misleading block.
*/
export function GreenptWidget(props: {
context: Context
store: BalanceStore
theme: ResolvedTheme
open: () => boolean
toggleOpen: () => void
showWhenUnavailable: boolean
unit?: string
}) {
const theme = () => props.context.theme
const [fold, updateFold] = props.context.storage.store<{ open: boolean }>(
BALANCE_OPEN_KV,
{ initial: { open: true } },
)
const theme = () => props.theme
const state = () => props.store.state()
const status = () => state().status
const open = () => fold.open
const open = () => props.open()
const toggle = () => {
void updateFold((draft) => {
draft.open = !draft.open
})
}
const toggle = () => props.toggleOpen()
const error = () => {
const s = state()
@@ -70,7 +52,8 @@ export function GreenptWidget(props: {
}
const balanceColor = () => {
const s = state()
return s.status === "ready" && s.data.credits > 0 ? "success" : "error"
const kind = s.status === "ready" && s.data.credits > 0 ? "success" : "error"
return theme().text.feedback[kind].base
}
const updatedAt = () => {
const s = state()
@@ -78,89 +61,74 @@ export function GreenptWidget(props: {
const d = new Date(s.fetchedAt)
const hh = String(d.getHours()).padStart(2, "0")
const mm = String(d.getMinutes()).padStart(2, "0")
return `${hh}:${mm}`
return `updated ${hh}:${mm}`
}
const usage = () => props.store.usageDays()
const usage = () => props.store.usageDays
const todayUsage = () => dayTotals(usage(), props.store.now())
const monthUsage = () => monthTotals(usage(), props.store.now())
const usageVisible = () => todayUsage().creditsSpent > 0 || monthUsage().cost > 0
const todayText = () => `${formatCredits(todayUsage().creditsSpent)} ${unit()}`
const monthText = () => `${formatCredits(monthUsage().cost)} ${unit()}`
const modelRows = (): ModelTotal[] => monthUsage().byModel.slice(0, MODEL_ROWS_VISIBLE)
const otherModels = () => Math.max(0, monthUsage().byModel.length - MODEL_ROWS_VISIBLE)
const foldedSuffix = () => (usageVisible() ? ` · today ${todayText()}` : "")
const modelRows = (): ModelTotal[] => monthUsage().byModel.slice(0, 5)
return (
<Show when={!hidden()} fallback={<box />}>
<box flexDirection="column">
<box flexDirection="row" justifyContent="space-between" gap={1}>
<text fg={theme().text.base} onMouseUp={toggle}>
<span style={{ fg: theme().text.muted }}>{open() ? "▼ " : "▶ "}</span>
<b>GreenPT</b>
</text>
<box flexDirection="row" gap={1} justifyContent="flex-end">
<Show when={balanceText()}>
{(text) => (
<text fg={theme().text.feedback[balanceColor()].base}>
<b>{text()}</b>
</text>
)}
</Show>
<Show when={!open() && usageVisible()}>
<text fg={theme().text.muted}>· today {todayText()}</text>
</Show>
</box>
</box>
<box flexDirection="column" gap={1}>
<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: balanceColor() }}>
{" "}
{text()}
{foldedSuffix()}
</span>
)}
</Show>
</text>
<Show when={open()}>
<Switch>
<Match when={status() === "ready"}>
<box paddingLeft={2}>
<text fg={theme().text.muted}>
today {todayText()} · month {monthText()} · {updatedAt()}
</text>
<box flexDirection="row" gap={1} justifyContent="space-between">
<text fg={theme().text.muted}>Balance</text>
<box flexDirection="row" gap={1}>
<text fg={balanceColor()}>{balanceText()}</text>
<text fg={theme().text.muted}>{updatedAt()}</text>
</box>
</box>
</Match>
<Match when={status() === "loading"}>
<box paddingLeft={2}>
<text fg={theme().text.muted}>loading…</text>
</box>
<text fg={theme().text.muted}>loading…</text>
</Match>
<Match when={credentialReason() !== undefined && props.showWhenUnavailable}>
<box paddingLeft={2}>
<CredentialHint reason={credentialReason()!} theme={theme()} />
</box>
<CredentialHint reason={credentialReason()!} theme={theme()} />
</Match>
<Match when={status() === "error"}>
<box paddingLeft={2}>
<text fg={theme().text.muted}>{formatBalanceError(error()!)}</text>
</box>
<text fg={theme().text.muted}>{formatBalanceError(error()!)}</text>
</Match>
</Switch>
<Show when={usageVisible()}>
<box flexDirection="column" marginTop={1}>
<For each={modelRows()}>
{(row) => (
<box flexDirection="column" paddingLeft={2}>
<text fg={theme().text.muted}>{shortModel(row.model)}</text>
<box flexDirection="row" justifyContent="space-between" paddingLeft={2}>
<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>
)}
</For>
<Show when={otherModels() > 0}>
<box paddingLeft={2}>
<text fg={theme().text.muted}>+ {otherModels()} more models</text>
</box>
</Show>
<box flexDirection="row" gap={1} justifyContent="space-between">
<text fg={theme().text.muted}>Spent</text>
<box flexDirection="row" gap={1}>
<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().text.muted}>{row.model}</text>
<box flexDirection="row" gap={1}>
<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>
)}
</For>
</Show>
</Show>
</box>
@@ -172,7 +140,7 @@ export function GreenptWidget(props: {
* Hint shown when the credential is missing and the section is explicitly
* kept visible.
*/
function CredentialHint(props: { reason: "missing"; theme: Context["theme"] }) {
function CredentialHint(props: { reason: "missing"; theme: ResolvedTheme }) {
return (
<text fg={props.theme.text.muted}>
{props.reason === "missing" ? "no GreenPT key (/connect)" : "no GreenPT key"}

View File

@@ -49,3 +49,4 @@ describe("formatBalanceError", () => {
expect(formatBalanceError({ kind: "no-credential", reason: "missing" })).toContain("GreenPT")
})
})

View File

@@ -1,58 +1,19 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { describe, expect, it, vi } from "vitest"
import { createBalanceStore, type BalanceOptions } from "../src/store"
import { nativeFetch } from "../src/balance"
import { dayKey } from "../src/usage"
import type { UsageDays } from "../src/usage"
const NOW = new Date(2026, 9, 19, 15, 0, 0).getTime()
const DAY = dayKey(NOW)
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(NOW)
})
afterEach(() => {
vi.useRealTimers()
})
const DAY = "2026-10-19"
type FakeMessage = Record<string, unknown>
type UsagePayload = { version: number; days: Array<Record<string, unknown>> }
function makeContext() {
const payload: UsagePayload = { version: 1, days: [] }
const fold = { open: true }
/** Minimal structural fake of the OpenCode v2 TUI plugin context. */
function makeContext(storage = new Map<string, object>()) {
const storageData = storage
const messages = new Map<string, FakeMessage[]>()
const sessions: Array<{ id: string; time: { updated: number } }> = []
const handlers = new Map<string, Array<(event: unknown) => void>>()
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) ?? []
@@ -66,18 +27,34 @@ function makeContext() {
}
},
session: {
list: () => sessions,
message: {
list: (sessionID: string) => messages.get(sessionID) ?? [],
sync: async () => {},
},
},
},
client: {
session: {
list: async () => ({ data: [] }),
context: async () => [],
},
},
storage: {
store: (key: string, { initial }: { initial: object }) => {
if (!storageData.has(key)) storageData.set(key, initial)
const value = storageData.get(key)!
return [
value,
async (mutate: (draft: object) => void) => {
mutate(value)
},
] as const
},
},
emit(type: string, event: unknown) {
for (const handler of handlers.get(type) ?? []) handler(event)
},
}
return { context, payload, fold, messages, sessions }
return { context, storageData, messages }
}
function balanceResponse(credits: number) {
@@ -94,12 +71,7 @@ function fetchSequence(credits: number[]) {
}
function createTrackedStore(context: unknown, options: BalanceOptions = {}) {
return createBalanceStore(
context as never,
{ apiKey: "test-key", ...options },
{},
fetchSequence([10]),
)
return createBalanceStore(context as never, { apiKey: "test-key", ...options }, {}, fetchSequence([10]))
}
describe("usage tracking in the balance store", () => {
@@ -115,7 +87,7 @@ describe("usage tracking in the balance store", () => {
await store.refresh()
await store.refresh()
await store.refresh()
expect(store.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.1)
expect(store.usageDays[DAY]?.creditsSpent).toBeCloseTo(0.1)
store.dispose()
})
@@ -124,8 +96,8 @@ describe("usage tracking in the balance store", () => {
const store = createTrackedStore(context)
messages.set("s1", [
{
id: "m1",
type: "assistant",
id: "m1",
model: { providerID: "greenpt", id: "glm-5.3-flash" },
cost: 0.02,
time: { created: NOW },
@@ -135,12 +107,12 @@ describe("usage tracking in the balance store", () => {
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)
expect(store.usageDays[DAY]?.byModel["glm-5.3-flash"]?.cost).toBeCloseTo(0.02)
store.dispose()
})
it("persists buckets to the durable store and reloads them", async () => {
const { context, payload } = makeContext()
it("persists buckets to durable storage and reloads them", async () => {
const { context, storageData } = makeContext()
const first = createBalanceStore(
context as never,
{ apiKey: "test-key" },
@@ -149,12 +121,20 @@ describe("usage tracking in the balance store", () => {
)
await first.refresh()
await first.refresh()
expect(payload.days.length).toBeGreaterThan(0)
expect(storageData.has("greenpt.usage.days")).toBe(true)
first.dispose()
const second = createTrackedStore(context)
expect(second.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.1)
second.dispose()
const stored: UsageDays = { [DAY]: { date: DAY, creditsSpent: 0.5, byModel: {}, ids: [] } }
storageData.set("greenpt.usage.days", stored)
const { context: secondContext } = makeContext(storageData)
const secondStore = createBalanceStore(
secondContext as never,
{ apiKey: "test-key" },
{},
fetchSequence([10]),
)
expect(secondStore.usageDays[DAY]?.creditsSpent).toBeCloseTo(0.5)
secondStore.dispose()
})
it("resetUsage clears buckets", async () => {
@@ -162,14 +142,13 @@ describe("usage tracking in the balance store", () => {
const store = createTrackedStore(context)
await store.refresh()
await store.refresh()
store.resetUsage()
await store.refresh()
expect(Object.keys(store.usageDays()).length).toBe(0)
await store.resetUsage()
expect(Object.keys(store.usageDays).length).toBe(0)
store.dispose()
})
it("skips tracking when disabled", async () => {
const { context, payload } = makeContext()
const { context, storageData } = makeContext()
const store = createBalanceStore(
context as never,
{ apiKey: "test-key", trackUsage: false },
@@ -178,8 +157,8 @@ describe("usage tracking in the balance store", () => {
)
await store.refresh()
await store.refresh()
expect(Object.keys(store.usageDays()).length).toBe(0)
expect(payload.days.length).toBe(0)
expect(Object.keys(store.usageDays).length).toBe(0)
expect(storageData.has("greenpt.usage.days")).toBe(false)
store.dispose()
})
})

View File

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