Compare commits

1 Commits
main ... v2

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
12 changed files with 4704 additions and 654 deletions

View File

@@ -2,9 +2,10 @@
## Project
`opencode-greenpt-usage` — an OpenCode **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,17 +18,20 @@ 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
- 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, idempotent by message id, persisted in the plugin KV 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.

View File

@@ -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 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 `>= 1.18.0` (TUI plugin system).
- 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,35 +65,37 @@ looks for a key.
(Alternative: export `GREENPT_API_KEY` in your environment.)
3. **Register the plugin** in `~/.config/opencode/tui.json`, setting the
3. **Register the plugin** in `~/.config/opencode/cli.json`, setting the
**absolute path to your clone**:
```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": { "showWhenUnavailable": false }
}
]
}
```
> 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.
> 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. **Fully quit OpenCode and relaunch it** (plugins are not hot-reloaded).
## Configuration
All options are optional and go in the plugin entry of `tui.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 | `700` | Sidebar section position. |
| `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,7 @@ 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.
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.

4768
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.",
"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": [
@@ -13,21 +13,28 @@
"balance"
],
"engines": {
"opencode": ">=1.18.0"
"opencode": ">=2.0.0"
},
"scripts": {
"test": "vitest run",
"test:integration": "GREENPT_INTEGRATION=1 vitest run test/integration.greenpt.test.ts",
"typecheck": "tsc --noEmit"
},
"exports": {
".": "./src/index.ts",
"./tui": "./src/tui.tsx"
},
"peerDependencies": {
"@opencode-ai/plugin": "*",
"@opentui/solid": "*",
"solid-js": "*"
"@opencode/plugin": ">=2.0.0 <3",
"@opentui/core": ">=0.5.17",
"@opentui/solid": ">=0.5.17",
"solid-js": ">=1.9.0"
},
"devDependencies": {
"@opencode-ai/plugin": "^1.18.33",
"@opentui/solid": "^0.5.12",
"@opencode/plugin": "^2.0.32",
"@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

@@ -1,10 +1,7 @@
import type { BalanceError } from "./balance"
/** Key used to persist the section fold state in the shared KV store. */
export const BALANCE_OPEN_KV = "greenpt.usage.open"
/** Key used to persist the usage day buckets in the shared KV 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 = "€"
@@ -57,24 +54,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
}
}

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,59 +0,0 @@
/** @jsxImportSource @opentui/solid */
import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
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 } = {
id: "greenpt.usage",
tui,
}
export default plugin

View File

@@ -1,14 +1,11 @@
import { createSignal } from "solid-js"
import type { TuiPluginApi } from "@opencode-ai/plugin/tui"
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"
@@ -16,6 +13,9 @@ import {
/** 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
@@ -29,7 +29,6 @@ export type BalanceOptions = {
apiKey?: string
baseUrl?: string
refreshInterval?: number
order?: number
showWhenUnavailable?: boolean
unit?: string
trackUsage?: boolean
@@ -48,17 +47,42 @@ export type BalanceState =
export type BalanceStore = {
state: () => BalanceState
now: () => number
usageDays: () => UsageDays
usageDays: UsageDays
refresh: () => Promise<void>
resetUsage: () => void
resetUsage: () => Promise<void>
dispose: () => void
}
const BACKOFF_BASE_MS = 60_000
const BACKOFF_MAX_MS = 10 * 60_000
const STATE_RETRY_MS = 5_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.
*
@@ -68,25 +92,23 @@ const TICK_MS = 30_000
*
* 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 live in the
* plugin durable storage and are pruned to `usageWindowDays`.
*
* @param api TUI plugin API (used for the auth store path, events, KV and
* session messages).
* @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.
* @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 baseUrl = options.baseUrl ?? DEFAULT_BASE_URL
const interval = options.refreshInterval ?? DEFAULT_REFRESH_SECONDS
@@ -94,107 +116,82 @@ 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 stateRetryTimer: ReturnType<typeof setTimeout> | undefined
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)
reconcileSessions()
const unsubscribeIdle = context.data.on("session.idle", (event) => {
trackSession(event.data.sessionID)
void 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())
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.
}
}
const unsubscribeConnected = context.data.on("server.connected", () => void refresh())
function trackSession(sessionID: string): void {
if (sessionID) trackedSessions.add(sessionID)
}
/** Apply usage mutations through a fresh top-level record for reactivity. */
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)
/** 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) {
let messages: ReadonlyArray<UsageMessage> | undefined
let messages: ReadonlyArray<unknown> | undefined
try {
messages = api.state.session.messages(sessionID)
messages = context.data.session.message.list(sessionID)
} catch {
continue
}
if (!messages?.length) continue
mutateUsage((days) => applyMessages(days, messages as ReadonlyArray<unknown>))
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
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 listed = await context.client.session.list({
limit: usageBackfillLimit,
})
for (const session of listed.data ?? []) {
if (disposed) return
const sessionID = (session as { id?: unknown })?.id
if (typeof sessionID !== "string" || !sessionID) continue
trackedSessions.add(sessionID)
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))
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.
}
@@ -204,13 +201,6 @@ export function createBalanceStore(
}
}
/** 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() {
if (disposed) return
if (refreshTimer) clearTimeout(refreshTimer)
@@ -233,15 +223,10 @@ export function createBalanceStore(
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)
}
return
}
@@ -260,7 +245,7 @@ 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
}
@@ -273,14 +258,14 @@ export function createBalanceStore(
inFlight = false
}
if (disposed) return
reconcileSessions()
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]
})
}
@@ -292,7 +277,6 @@ export function createBalanceStore(
controller.abort()
if (refreshTimer) clearTimeout(refreshTimer)
if (tickTimer) clearTimeout(tickTimer)
if (stateRetryTimer) clearTimeout(stateRetryTimer)
unsubscribeIdle()
unsubscribeStatus()
unsubscribeConnected()

63
src/tui.tsx Normal file
View File

@@ -0,0 +1,63 @@
/** @jsxImportSource @opentui/solid */
import { Plugin } from "@opencode/plugin/tui"
import { FOLD_STORAGE_KEY } from "./format"
import { createBalanceStore, type BalanceOptions } from "./store"
import { GreenptWidget } from "./widget"
export default Plugin.define({
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
store={store}
theme={context.theme}
open={() => fold.open}
toggleOpen={() => {
void updateFold((draft) => {
draft.open = !fold.open
})
}}
showWhenUnavailable={opts.showWhenUnavailable === true}
unit={opts.unit}
/>
),
})
context.keymap.layer(() => ({
mode: "global",
commands: [
{
id: "greenpt.refresh",
title: "Refresh GreenPT balance",
group: "GreenPT",
palette: true,
run() {
void store.refresh()
},
},
{
id: "greenpt.usage.reset",
title: "Reset GreenPT usage counters",
group: "GreenPT",
palette: true,
run() {
void store.resetUsage()
},
},
],
}))
return () => {
unregisterSlot()
store.dispose()
}
},
})

View File

@@ -1,12 +1,10 @@
/** @jsxImportSource @opentui/solid */
import { createSignal, For, Match, Show, Switch } from "solid-js"
import type { TuiPluginApi, TuiThemeCurrent } from "@opencode-ai/plugin/tui"
import type { ResolvedTheme } from "@opencode/theme/tui"
import {
formatBalanceError,
formatCredits,
formatTokens,
readFoldOpen,
BALANCE_OPEN_KV,
DEFAULT_UNIT,
} from "./format"
import { dayTotals, monthTotals, type ModelTotal } from "./usage"
@@ -22,25 +20,19 @@ import type { BalanceStore } from "./store"
* GreenPT never sees an empty or misleading block.
*/
export function GreenptWidget(props: {
api: TuiPluginApi
store: BalanceStore
theme: ResolvedTheme
open: () => boolean
toggleOpen: () => void
showWhenUnavailable: boolean
unit?: string
}) {
const theme = () => props.api.theme.current
const theme = () => props.theme
const state = () => props.store.state()
const status = () => state().status
const [open, setOpen] = createSignal(readFoldOpen(props.api.kv))
const open = () => props.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.
}
}
const toggle = () => props.toggleOpen()
const error = () => {
const s = state()
@@ -60,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()
@@ -71,7 +64,7 @@ export function GreenptWidget(props: {
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
@@ -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: balanceColor() }}>
{" "}
{text()}
{foldedSuffix()}
@@ -100,38 +93,38 @@ 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={balanceColor()}>{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 +140,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: ResolvedTheme }) {
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", () => {
@@ -50,26 +50,3 @@ describe("formatBalanceError", () => {
})
})
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,20 @@
import { 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 type { UsageDays } from "../src/usage"
const NOW = new Date(2026, 9, 19, 15, 0, 0).getTime()
const DAY = "2026-10-19"
type FakeMessage = Record<string, unknown>
function makeApi() {
const kvData = new Map<string, unknown>()
/** 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 handlers = new Map<string, Array<(event: unknown) => void>>()
const api = {
event: {
const context = {
data: {
on: (type: string, handler: (event: unknown) => void) => {
const list = handlers.get(type) ?? []
list.push(handler)
@@ -25,31 +26,35 @@ 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) ?? [],
message: {
list: (sessionID: string) => messages.get(sessionID) ?? [],
},
},
},
client: {
session: {
list: async () => ({ data: [] }),
messages: 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 { api, kvData, messages }
return { context, storageData, messages }
}
function balanceResponse(credits: number) {
@@ -65,15 +70,15 @@ 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]),
@@ -82,73 +87,78 @@ 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()
})
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", [
{
type: "assistant",
id: "m1",
role: "assistant",
providerID: "greenpt",
modelID: "glm-5.3-flash",
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)
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 durable storage and reloads them", async () => {
const { context, storageData } = 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(storageData.has("greenpt.usage.days")).toBe(true)
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)
second.dispose()
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 () => {
const { api } = makeApi()
const store = createTrackedStore(api)
const { context } = makeContext()
const store = createTrackedStore(context)
await store.refresh()
await store.refresh()
store.resetUsage()
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 { api, kvData } = makeApi()
const { context, storageData } = makeContext()
const store = createBalanceStore(
api as never,
context as never,
{ apiKey: "test-key", trackUsage: false },
{},
fetchSequence([10, 5]),
)
await store.refresh()
await store.refresh()
expect(Object.keys(store.usageDays()).length).toBe(0)
expect(kvData.has("greenpt.usage.days")).toBe(false)
expect(Object.keys(store.usageDays).length).toBe(0)
expect(storageData.has("greenpt.usage.days")).toBe(false)
store.dispose()
})
})