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
14 changed files with 721 additions and 785 deletions

View File

@@ -2,9 +2,10 @@
## Project ## Project
`opencode-greenpt-usage` — an OpenCode **2** TUI plugin (Solid + OpenTUI) that `opencode-greenpt-usage` — an OpenCode **v2** CLI/TUI plugin (Solid + OpenTUI)
shows the remaining GreenPT API credit balance in the sidebar. Distributed by that shows the remaining GreenPT API credit balance in the sidebar.
`git clone`; there is no npm publish. Distributed by `git clone`; there is no npm publish. The `main` branch
targets OpenCode 1.x; this branch targets OpenCode `>= 2.0.0`.
## Commands ## Commands
@@ -17,23 +18,21 @@ GREENPT_API_KEY=... npm run test:integration # live API test
## Conventions ## Conventions
- The plugin entry is `Plugin.define({ id: "greenpt.usage", setup })` in - The plugin has two entries: `src/index.ts` (server side, minimal
`src/index.tsx` (default export). Types come from `@opencode/plugin/tui` and `Plugin.define`) and `src/tui.tsx` (CLI plugin, exposed as `./tui`).
`@opencode/plugin/tui/context` as **type-only** imports; the host provides Types come from `@opencode/plugin` and `@opencode/plugin/tui`; the host
`solid-js` and `@opentui/*` at runtime. provides `solid-js`, `@opentui/solid` and the theme at runtime.
- The section is registered on the `sidebar.content` slot via - The section is appended to the `sidebar.content` slot and is hidden when
`context.ui.slot({ append: ..., render })`, hidden when no GreenPT credential no GreenPT credential is present (`showWhenUnavailable` opts into a hint).
is present (`showWhenUnavailable` opts into a hint). Commands use - Commands are registered through `context.keymap.layer` (palette).
`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 - Balance probing must stay **free**: `HEAD /v1/chat/completions` returns
`400` plus `x-credits-remaining`. Never replace it with a billable call. `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 - Usage accounting lives in `src/usage.ts` (pure) and is consumed by the
balance store: real spend = delta of `x-credits-remaining` between balance store: real spend = delta of `x-credits-remaining` between
probes; per-model detail = reconciliation of local OpenCode assistant probes; per-model detail = reconciliation of local OpenCode assistant
messages (V2 `type: "assistant"`, `model.providerID`/`model.id`), messages, idempotent by message id, persisted in the plugin durable
idempotent by message id, persisted with `context.storage.store`. storage (`context.storage.store`).
- Credential resolution order: `apiKey` option, `GREENPT_API_KEY`, active - Credential resolution order: `apiKey` option, `GREENPT_API_KEY`, active
OpenCode `auth.json` (`greenpt`, `type: "api"`). No profile-switching OpenCode `auth.json` (`greenpt`, `type: "api"`). No profile-switching
command may leak into this logic. 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 # opencode-greenpt-usage
An [OpenCode](https://opencode.ai) **OpenCode 2** TUI plugin that shows the An [OpenCode](https://opencode.ai) TUI plugin that shows the remaining
remaining **GreenPT API credit balance** and the **consumption** of the API key **GreenPT API credit balance** and the **consumption** of the API key
(real credit spend plus a per-model breakdown) in the sidebar. (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 the API answers `400 Bad Request` before any billing, yet the response
still carries the `x-credits-remaining` header. No credit is consumed still carries the `x-credits-remaining` header. No credit is consumed
and no generation is triggered. and no generation is triggered.
- **Usage tracking** keeps per-day buckets, persisted in the plugin's durable - **Usage tracking** keeps per-day buckets, persisted in the plugin durable
TUI store (90 days by default): storage (90 days by default):
- *real credit spend* is observed as the drop of `x-credits-remaining` - *real credit spend* is observed as the drop of `x-credits-remaining`
between two balance probes — this covers **every client** of the API between two balance probes — this covers **every client** of the API
key, not just OpenCode, but has no per-model detail; key, not just OpenCode, but has no per-model detail;
@@ -47,7 +47,8 @@ looks for a key.
## Requirements ## 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. - A GreenPT account and API key.
## Installation ## Installation
@@ -64,8 +65,8 @@ looks for a key.
(Alternative: export `GREENPT_API_KEY` in your environment.) (Alternative: export `GREENPT_API_KEY` in your environment.)
3. **Register the plugin** in `~/.config/opencode/cli.json`, pointing at the 3. **Register the plugin** in `~/.config/opencode/cli.json`, setting the
**repository directory** (the package's `./tui` export): **absolute path to your clone**:
```jsonc ```jsonc
{ {
@@ -73,29 +74,28 @@ looks for a key.
"plugins": [ "plugins": [
{ {
"package": "file:///ABSOLUTE/PATH/TO/opencode-greenpt-usage", "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 > Point at the repository root, not at a source file: OpenCode v2 loads
> `src/index.tsx`: a configured file is skipped. OpenCode compiles the TSX > the `./tui` entry (`src/tui.tsx`) from the package `exports` and
> entrypoint itself. > resolves `@opencode/plugin` at runtime.
4. **Reload OpenCode**. V2 reloads configuration and plugins after a save; if 4. **Fully quit OpenCode and relaunch it** (plugins are not hot-reloaded).
a running session keeps the old module, quit and relaunch it.
## Configuration ## 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 | | Option | Type | Default | Description |
| --------------------- | ------- | --------------------------- | ------------------------------------------------------- | | --------------------- | ------- | --------------------------- | ------------------------------------------------------- |
| `apiKey` | string | resolved automatically | Explicit GreenPT key. | | `apiKey` | string | resolved automatically | Explicit GreenPT key. |
| `baseUrl` | string | `https://api.greenpt.ai/v1` | GreenPT API base URL. | | `baseUrl` | string | `https://api.greenpt.ai/v1` | GreenPT API base URL. |
| `refreshInterval` | number | `300` | Refresh interval in seconds (`0` disables the timer). | | `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. | | `showWhenUnavailable` | boolean | `false` | Show a hint when no GreenPT key exists. |
| `unit` | string | `€` | Unit appended after the amount. | | `unit` | string | `€` | Unit appended after the amount. |
| `trackUsage` | boolean | `true` | Track credit spend and per-model usage. | | `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 - **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://` `greenpt` key (or that `GREENPT_API_KEY` is set), and that the `file://`
entry in `cli.json` points at the **repository directory**, not at path in `cli.json` points at the repository root.
`src/index.tsx`. Check that `opencode plugin list` lists your repository
directory.
- **"invalid GreenPT key"**: the API key was rejected (HTTP 401). - **"invalid GreenPT key"**: the API key was rejected (HTTP 401).
- **"balance unavailable"**: GreenPT did not return the balance header; try - **"balance unavailable"**: GreenPT did not return the balance header; try
again later. 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", "name": "opencode-greenpt-usage",
"version": "0.1.0", "version": "0.2.0",
"description": "OpenCode 2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.", "description": "OpenCode v2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
"type": "module", "type": "module",
"license": "AGPL-3.0-or-later", "license": "AGPL-3.0-or-later",
"keywords": [ "keywords": [
@@ -15,27 +15,26 @@
"engines": { "engines": {
"opencode": ">=2.0.0" "opencode": ">=2.0.0"
}, },
"exports": {
".": "./src/index.tsx",
"./tui": "./src/index.tsx"
},
"scripts": { "scripts": {
"test": "vitest run", "test": "vitest run",
"test:integration": "GREENPT_INTEGRATION=1 vitest run test/integration.greenpt.test.ts", "test:integration": "GREENPT_INTEGRATION=1 vitest run test/integration.greenpt.test.ts",
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "exports": {
"@opencode/plugin": "^2.0.32" ".": "./src/index.ts",
"./tui": "./src/tui.tsx"
}, },
"peerDependencies": { "peerDependencies": {
"@opentui/core": ">=0.6.6", "@opencode/plugin": ">=2.0.0 <3",
"@opentui/solid": ">=0.6.6", "@opentui/core": ">=0.5.17",
"@opentui/solid": ">=0.5.17",
"solid-js": ">=1.9.0" "solid-js": ">=1.9.0"
}, },
"devDependencies": { "devDependencies": {
"@opencode/plugin": "^2.0.32", "@opencode/plugin": "^2.0.32",
"@opentui/core": "^0.6.6", "@opencode/theme": "^2.0.32",
"@opentui/solid": "^0.6.6", "@opentui/core": "^0.5.17",
"@opentui/solid": "^0.5.17",
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"solid-js": "^1.9.0", "solid-js": "^1.9.0",
"typescript": "^5.6.0", "typescript": "^5.6.0",

View File

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

View File

@@ -1,10 +1,7 @@
import type { BalanceError } from "./balance" import type { BalanceError } from "./balance"
/** Key used to persist the section fold state in the durable TUI store. */ /** Key used to persist the section fold state in the durable plugin storage. */
export const BALANCE_OPEN_KV = "greenpt.usage.open" export const FOLD_STORAGE_KEY = "greenpt.usage.open"
/** 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). */ /** Default unit appended to the balance (GreenPT credits are euro-denominated). */
export const DEFAULT_UNIT = "€" 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 { fetchBalance, nativeFetch, type Balance, type BalanceError, type FetchLike } from "./balance"
import { USAGE_DAYS_KV } from "./format"
import { resolveGreenptKey, type CredentialEnv } from "./credential" import { resolveGreenptKey, type CredentialEnv } from "./credential"
import { import {
addCreditsSpent, addCreditsSpent,
applyMessages, applyMessages,
parseUsageDays,
pruneUsage, pruneUsage,
serializeUsage,
type UsageDays, type UsageDays,
type UsageMessage,
} from "./usage" } from "./usage"
/** Default GreenPT API base URL. */ /** Default GreenPT API base URL. */
export const DEFAULT_BASE_URL = "https://api.greenpt.ai/v1" 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. */ /** Default refresh interval, in seconds. The probe is free but should stay gentle. */
export const DEFAULT_REFRESH_SECONDS = 300 export const DEFAULT_REFRESH_SECONDS = 300
@@ -27,8 +29,6 @@ export type BalanceOptions = {
apiKey?: string apiKey?: string
baseUrl?: string baseUrl?: string
refreshInterval?: number refreshInterval?: number
/** Accepted for V1 config compatibility; V2 orders slots by plugin load order. */
order?: number
showWhenUnavailable?: boolean showWhenUnavailable?: boolean
unit?: string unit?: string
trackUsage?: boolean trackUsage?: boolean
@@ -47,34 +47,55 @@ export type BalanceState =
export type BalanceStore = { export type BalanceStore = {
state: () => BalanceState state: () => BalanceState
now: () => number now: () => number
usageDays: () => UsageDays usageDays: UsageDays
refresh: () => Promise<void> refresh: () => Promise<void>
resetUsage: () => void resetUsage: () => Promise<void>
dispose: () => void dispose: () => void
} }
type UsagePayload = {
version: number
days: Array<Record<string, unknown>>
}
const BACKOFF_BASE_MS = 60_000 const BACKOFF_BASE_MS = 60_000
const BACKOFF_MAX_MS = 10 * 60_000 const BACKOFF_MAX_MS = 10 * 60_000
const TICK_MS = 30_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. * Create the reactive store backing the sidebar widget.
* *
* Refreshes on creation, on `session.idle`, on `server.connected`, on a timer, * Refreshes on creation, on `session.idle`, on `server.connected`, on a
* and on demand via `refresh()`. Errors are retried with an exponential * timer, and on demand via `refresh()`. Errors are retried with an
* backoff so a transient outage does not hammer the API. * exponential backoff so a transient outage does not hammer the API.
* *
* Usage tracking (opt-out via `trackUsage: false`) keeps per-day buckets: * Usage tracking (opt-out via `trackUsage: false`) keeps per-day buckets:
* real credit spend from balance deltas, and per-model token/cost totals * real credit spend from balance deltas, and per-model token/cost totals
* reconciled from local OpenCode assistant messages. Buckets are persisted in * reconciled from local OpenCode assistant messages. Buckets live in the
* the plugin's durable TUI store and pruned to `usageWindowDays`. * 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 options Plugin options.
* @param env Environment mapping, injectable for tests. * @param env Environment mapping, injectable for tests.
* @param fetchImpl Fetch implementation, injectable for tests. * @param fetchImpl Fetch implementation, injectable for tests.
@@ -86,16 +107,8 @@ export function createBalanceStore(
env: CredentialEnv = process.env as CredentialEnv, env: CredentialEnv = process.env as CredentialEnv,
fetchImpl: FetchLike = nativeFetch, fetchImpl: FetchLike = nativeFetch,
): BalanceStore { ): BalanceStore {
const [usagePayload, updateUsagePayload] = context.storage.store<UsagePayload>( const [state, setState] = createSignal<BalanceState>({ status: "loading" })
USAGE_DAYS_KV, const [now, setNow] = createSignal(Date.now())
{ 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 baseUrl = options.baseUrl ?? DEFAULT_BASE_URL
const interval = options.refreshInterval ?? DEFAULT_REFRESH_SECONDS const interval = options.refreshInterval ?? DEFAULT_REFRESH_SECONDS
@@ -103,9 +116,17 @@ export function createBalanceStore(
const usageWindowDays = options.usageWindowDays ?? DEFAULT_USAGE_WINDOW_DAYS const usageWindowDays = options.usageWindowDays ?? DEFAULT_USAGE_WINDOW_DAYS
const usageBackfillLimit = options.usageBackfill ?? DEFAULT_USAGE_BACKFILL 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 refreshTimer: ReturnType<typeof setTimeout> | undefined
let tickTimer: ReturnType<typeof setTimeout> | undefined let tickTimer: ReturnType<typeof setTimeout> | undefined
let persistChain: Promise<void> = Promise.resolve()
let backoff = BACKOFF_BASE_MS let backoff = BACKOFF_BASE_MS
let inFlight = false let inFlight = false
let disposed = false let disposed = false
@@ -115,7 +136,7 @@ export function createBalanceStore(
const unsubscribeIdle = context.data.on("session.idle", (event) => { const unsubscribeIdle = context.data.on("session.idle", (event) => {
trackSession(event.data.sessionID) trackSession(event.data.sessionID)
reconcileSessions() void reconcileSessions()
void refresh() void refresh()
}) })
const unsubscribeStatus = context.data.on("session.status", (event) => { const unsubscribeStatus = context.data.on("session.status", (event) => {
@@ -123,123 +144,89 @@ export function createBalanceStore(
}) })
const unsubscribeConnected = context.data.on("server.connected", () => void refresh()) 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 { function trackSession(sessionID: string): void {
if (sessionID) trackedSessions.add(sessionID) if (sessionID) trackedSessions.add(sessionID)
} }
/** /** Apply usage mutations through the durable storage draft. */
* Apply usage mutations in the durable store. function mutateUsage(mutate: (days: UsageDays) => void): Promise<void> {
* if (!trackUsage) return Promise.resolve()
* Writes are chained so concurrent refreshes cannot interleave payloads. return updateUsage((draft) => {
* mutate(draft)
* @param mutate Callback mutating a fresh copy of the buckets. pruneUsage(draft, usageWindowDays, Date.now())
*/
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)
}
/** /**
* Reconcile per-model usage from the messages of every tracked session. * Reconcile per-model usage from the messages of every tracked session.
* Idempotent: messages are de-duplicated by id in `usage.ts`. * Idempotent: messages are de-duplicated by id in `usage.ts`.
*/ */
function reconcileSessions(): void { function reconcileSessions(): Promise<void> {
if (!trackUsage || trackedSessions.size === 0) return if (!trackUsage || trackedSessions.size === 0) return Promise.resolve()
const updates: Promise<void>[] = []
for (const sessionID of trackedSessions) { for (const sessionID of trackedSessions) {
const messages = context.data.session.message.list(sessionID) let messages: ReadonlyArray<unknown> | undefined
if (!messages?.length) continue try {
mutateUsage((days) => applyMessages(days, messages)) messages = context.data.session.message.list(sessionID)
} catch {
continue
} }
if (!messages?.length) continue
updates.push(mutateUsage((days) => applyMessages(days, toUsageMessages(messages ?? []))))
}
return Promise.all(updates).then(() => undefined)
} }
/** Best-effort startup backfill from recently updated sessions. */ /** Best-effort startup backfill from recently updated sessions. */
async function backfillUsage(): Promise<void> { async function backfillUsage(): Promise<void> {
if (!trackUsage || usageBackfillLimit <= 0) return if (!trackUsage || usageBackfillLimit <= 0) return
try { try {
const sessions = context.data.session.list() const listed = await context.client.session.list({
const recent = [...sessions] limit: usageBackfillLimit,
.sort((a, b) => (b.time?.updated ?? 0) - (a.time?.updated ?? 0)) })
.slice(0, usageBackfillLimit) for (const session of listed.data ?? []) {
for (const session of recent) {
if (disposed) return if (disposed) return
trackedSessions.add(session.id) const sessionID = (session as { id?: unknown })?.id
if (typeof sessionID !== "string" || !sessionID) continue
trackedSessions.add(sessionID)
try { try {
await context.data.session.message.sync(session.id) const messages = await context.client.session.context({ sessionID })
mutateUsage((days) => await mutateUsage((days) => applyMessages(days, toUsageMessages(messages)))
applyMessages(days, context.data.session.message.list(session.id)), } catch {
) // One unreadable session must not abort the whole backfill.
} catch (error) {
console.error(`[greenpt.usage] backfill ${session.id}: ${error}`)
} }
} }
await persistChain } catch {
} catch (error) { // Backfill is optional; live tracking continues regardless.
console.error(`[greenpt.usage] backfill: ${error}`)
} }
} }
/** Arm the next periodic refresh, backing off after errors. */ function scheduleNext() {
function scheduleNext(): void {
if (disposed) return if (disposed) return
if (refreshTimer) clearTimeout(refreshTimer) if (refreshTimer) clearTimeout(refreshTimer)
refreshTimer = undefined refreshTimer = undefined
const intervalMs = interval * 1000 const intervalMs = interval * 1000
if (intervalMs <= 0) return if (intervalMs <= 0) return
const delay = balance.status === "error" ? backoff : intervalMs const delay = state().status === "error" ? backoff : intervalMs
refreshTimer = setTimeout(() => { refreshTimer = setTimeout(() => {
refreshTimer = undefined refreshTimer = undefined
void refresh() void refresh()
}, delay) }, delay)
} }
/** Advance the clock used for day/month totals. */ function tick() {
function tick(): void {
if (disposed) return if (disposed) return
setClock((draft) => { setNow(Date.now())
draft.value = Date.now()
})
tickTimer = setTimeout(tick, TICK_MS) tickTimer = setTimeout(tick, TICK_MS)
} }
/** Probe the balance and reconcile usage from tracked sessions. */
async function refresh(): Promise<void> { async function refresh(): Promise<void> {
if (disposed || inFlight) return if (disposed || inFlight) return
inFlight = true inFlight = true
try { try {
const credential = resolveGreenptKey(options, undefined, env) const credential = resolveGreenptKey(options, undefined, env)
if (!credential.ok) { if (!credential.ok) {
replaceBalance({ status: "error", error: { kind: "no-credential", reason: credential.reason } }) setState({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
return return
} }
@@ -258,36 +245,34 @@ export function createBalanceStore(
if (trackUsage && Number.isFinite(credits)) { if (trackUsage && Number.isFinite(credits)) {
if (lastCredits !== undefined && credits < lastCredits) { if (lastCredits !== undefined && credits < lastCredits) {
const spent = lastCredits - credits const spent = lastCredits - credits
mutateUsage((days) => addCreditsSpent(days, Date.now(), spent)) await mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
} }
lastCredits = credits lastCredits = credits
} }
replaceBalance({ status: "ready", data: result, fetchedAt: Date.now() }) setState({ status: "ready", data: result, fetchedAt: Date.now() })
} else { } else {
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS) backoff = Math.min(backoff * 2, BACKOFF_MAX_MS)
replaceBalance({ status: "error", error: result }) setState({ status: "error", error: result })
} }
} finally { } finally {
inFlight = false inFlight = false
} }
if (disposed) return if (disposed) return
reconcileSessions() await reconcileSessions()
await persistChain
scheduleNext() scheduleNext()
} }
/** Clear every persisted and in-memory usage bucket. */ /** Clear every persisted and in-memory usage bucket. */
function resetUsage(): void { async function resetUsage(): Promise<void> {
lastCredits = undefined lastCredits = undefined
mutateUsage((days) => { await mutateUsage((days) => {
for (const date of Object.keys(days)) delete days[date] for (const date of Object.keys(days)) delete days[date]
}) })
} }
tickTimer = setTimeout(tick, TICK_MS) tickTimer = setTimeout(tick, TICK_MS)
/** Stop timers, network work and event subscriptions. */ function dispose() {
function dispose(): void {
disposed = true disposed = true
controller.abort() controller.abort()
if (refreshTimer) clearTimeout(refreshTimer) if (refreshTimer) clearTimeout(refreshTimer)
@@ -299,12 +284,5 @@ export function createBalanceStore(
void backfillUsage() void backfillUsage()
return { return { state, now, usageDays, refresh, resetUsage, dispose }
state: () => balance as BalanceState,
now: () => clock.value,
usageDays,
refresh,
resetUsage,
dispose,
}
} }

View File

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

View File

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

View File

@@ -1,27 +1,15 @@
/** @jsxImportSource @opentui/solid */ /** @jsxImportSource @opentui/solid */
import { For, Match, Show, Switch } from "solid-js" import { createSignal, For, Match, Show, Switch } from "solid-js"
import type { Context } from "@opencode/plugin/tui/context" import type { ResolvedTheme } from "@opencode/theme/tui"
import { BALANCE_OPEN_KV, formatBalanceError, formatCredits, formatTokens, DEFAULT_UNIT } from "./format" import {
formatBalanceError,
formatCredits,
formatTokens,
DEFAULT_UNIT,
} from "./format"
import { dayTotals, monthTotals, type ModelTotal } from "./usage" import { dayTotals, monthTotals, type ModelTotal } from "./usage"
import type { BalanceStore } from "./store" 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 * Sidebar section showing the remaining GreenPT credit balance and the
* consumption of the API key: real credit spend per day/month plus a * 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. * GreenPT never sees an empty or misleading block.
*/ */
export function GreenptWidget(props: { export function GreenptWidget(props: {
context: Context
store: BalanceStore store: BalanceStore
theme: ResolvedTheme
open: () => boolean
toggleOpen: () => void
showWhenUnavailable: boolean showWhenUnavailable: boolean
unit?: string unit?: string
}) { }) {
const theme = () => props.context.theme const theme = () => props.theme
const [fold, updateFold] = props.context.storage.store<{ open: boolean }>(
BALANCE_OPEN_KV,
{ initial: { open: true } },
)
const state = () => props.store.state() const state = () => props.store.state()
const status = () => state().status const status = () => state().status
const open = () => fold.open const open = () => props.open()
const toggle = () => { const toggle = () => props.toggleOpen()
void updateFold((draft) => {
draft.open = !draft.open
})
}
const error = () => { const error = () => {
const s = state() const s = state()
@@ -70,7 +52,8 @@ export function GreenptWidget(props: {
} }
const balanceColor = () => { const balanceColor = () => {
const s = state() 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 updatedAt = () => {
const s = state() const s = state()
@@ -78,89 +61,74 @@ export function GreenptWidget(props: {
const d = new Date(s.fetchedAt) const d = new Date(s.fetchedAt)
const hh = String(d.getHours()).padStart(2, "0") const hh = String(d.getHours()).padStart(2, "0")
const mm = String(d.getMinutes()).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 todayUsage = () => dayTotals(usage(), props.store.now())
const monthUsage = () => monthTotals(usage(), props.store.now()) const monthUsage = () => monthTotals(usage(), props.store.now())
const usageVisible = () => todayUsage().creditsSpent > 0 || monthUsage().cost > 0 const usageVisible = () => todayUsage().creditsSpent > 0 || monthUsage().cost > 0
const todayText = () => `${formatCredits(todayUsage().creditsSpent)} ${unit()}` const todayText = () => `${formatCredits(todayUsage().creditsSpent)} ${unit()}`
const monthText = () => `${formatCredits(monthUsage().cost)} ${unit()}` const monthText = () => `${formatCredits(monthUsage().cost)} ${unit()}`
const modelRows = (): ModelTotal[] => monthUsage().byModel.slice(0, MODEL_ROWS_VISIBLE) const foldedSuffix = () => (usageVisible() ? ` · today ${todayText()}` : "")
const otherModels = () => Math.max(0, monthUsage().byModel.length - MODEL_ROWS_VISIBLE) const modelRows = (): ModelTotal[] => monthUsage().byModel.slice(0, 5)
return ( return (
<Show when={!hidden()} fallback={<box />}> <Show when={!hidden()} fallback={<box />}>
<box flexDirection="column"> <box flexDirection="column" gap={1}>
<box flexDirection="row" justifyContent="space-between" gap={1}>
<text fg={theme().text.base} onMouseUp={toggle}> <text fg={theme().text.base} onMouseUp={toggle}>
<span style={{ fg: theme().text.muted }}>{open() ? "▼ " : "▶ "}</span> <span style={{ fg: theme().text.muted }}>{open() ? "▼ " : "▶ "}</span>
<b>GreenPT</b> <b>GreenPT</b>
</text> <Show when={!open() && balanceText()}>
<box flexDirection="row" gap={1} justifyContent="flex-end">
<Show when={balanceText()}>
{(text) => ( {(text) => (
<text fg={theme().text.feedback[balanceColor()].base}> <span style={{ fg: balanceColor() }}>
<b>{text()}</b> {" "}
</text> {text()}
{foldedSuffix()}
</span>
)} )}
</Show> </Show>
<Show when={!open() && usageVisible()}> </text>
<text fg={theme().text.muted}>· today {todayText()}</text>
</Show>
</box>
</box>
<Show when={open()}> <Show when={open()}>
<Switch> <Switch>
<Match when={status() === "ready"}> <Match when={status() === "ready"}>
<box paddingLeft={2}> <box flexDirection="row" gap={1} justifyContent="space-between">
<text fg={theme().text.muted}> <text fg={theme().text.muted}>Balance</text>
today {todayText()} · month {monthText()} · {updatedAt()} <box flexDirection="row" gap={1}>
</text> <text fg={balanceColor()}>{balanceText()}</text>
<text fg={theme().text.muted}>{updatedAt()}</text>
</box>
</box> </box>
</Match> </Match>
<Match when={status() === "loading"}> <Match when={status() === "loading"}>
<box paddingLeft={2}>
<text fg={theme().text.muted}>loading…</text> <text fg={theme().text.muted}>loading…</text>
</box>
</Match> </Match>
<Match when={credentialReason() !== undefined && props.showWhenUnavailable}> <Match when={credentialReason() !== undefined && props.showWhenUnavailable}>
<box paddingLeft={2}>
<CredentialHint reason={credentialReason()!} theme={theme()} /> <CredentialHint reason={credentialReason()!} theme={theme()} />
</box>
</Match> </Match>
<Match when={status() === "error"}> <Match when={status() === "error"}>
<box paddingLeft={2}>
<text fg={theme().text.muted}>{formatBalanceError(error()!)}</text> <text fg={theme().text.muted}>{formatBalanceError(error()!)}</text>
</box>
</Match> </Match>
</Switch> </Switch>
<Show when={usageVisible()}> <Show when={usageVisible()}>
<box flexDirection="column" marginTop={1}> <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()}> <For each={modelRows()}>
{(row) => ( {(row) => (
<box flexDirection="column" paddingLeft={2}> <box flexDirection="row" gap={1} justifyContent="space-between">
<text fg={theme().text.muted}>{shortModel(row.model)}</text> <text fg={theme().text.muted}>{row.model}</text>
<box flexDirection="row" justifyContent="space-between" paddingLeft={2}> <box flexDirection="row" gap={1}>
<text fg={theme().text.muted}> <text fg={theme().text.muted}>{formatTokens(row.usage.tokens.input + row.usage.tokens.output)} tok</text>
{formatTokens(row.usage.tokens.input + row.usage.tokens.output)} tok <text fg={theme().text.base}>~{formatCredits(row.usage.cost)} {unit()}</text>
</text>
<text fg={theme().text.base}>
~{formatCredits(row.usage.cost)} {unit()}
</text>
</box> </box>
</box> </box>
)} )}
</For> </For>
<Show when={otherModels() > 0}>
<box paddingLeft={2}>
<text fg={theme().text.muted}>+ {otherModels()} more models</text>
</box>
</Show>
</box>
</Show> </Show>
</Show> </Show>
</box> </box>
@@ -172,7 +140,7 @@ export function GreenptWidget(props: {
* Hint shown when the credential is missing and the section is explicitly * Hint shown when the credential is missing and the section is explicitly
* kept visible. * kept visible.
*/ */
function CredentialHint(props: { reason: "missing"; theme: Context["theme"] }) { function CredentialHint(props: { reason: "missing"; theme: ResolvedTheme }) {
return ( return (
<text fg={props.theme.text.muted}> <text fg={props.theme.text.muted}>
{props.reason === "missing" ? "no GreenPT key (/connect)" : "no GreenPT key"} {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") 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 { createBalanceStore, type BalanceOptions } from "../src/store"
import { nativeFetch } from "../src/balance" 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 NOW = new Date(2026, 9, 19, 15, 0, 0).getTime()
const DAY = dayKey(NOW) const DAY = "2026-10-19"
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(NOW)
})
afterEach(() => {
vi.useRealTimers()
})
type FakeMessage = Record<string, unknown> type FakeMessage = Record<string, unknown>
type UsagePayload = { version: number; days: Array<Record<string, unknown>> }
function makeContext() { /** Minimal structural fake of the OpenCode v2 TUI plugin context. */
const payload: UsagePayload = { version: 1, days: [] } function makeContext(storage = new Map<string, object>()) {
const fold = { open: true } const storageData = storage
const messages = new Map<string, FakeMessage[]>() const messages = new Map<string, FakeMessage[]>()
const sessions: Array<{ id: string; time: { updated: number } }> = []
const handlers = new Map<string, Array<(event: unknown) => void>>() const handlers = new Map<string, Array<(event: unknown) => void>>()
const memory = new Map<string, unknown>()
const context = { 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: { data: {
on: (type: string, handler: (event: unknown) => void) => { on: (type: string, handler: (event: unknown) => void) => {
const list = handlers.get(type) ?? [] const list = handlers.get(type) ?? []
@@ -66,18 +27,34 @@ function makeContext() {
} }
}, },
session: { session: {
list: () => sessions,
message: { message: {
list: (sessionID: string) => messages.get(sessionID) ?? [], 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) { emit(type: string, event: unknown) {
for (const handler of handlers.get(type) ?? []) handler(event) for (const handler of handlers.get(type) ?? []) handler(event)
}, },
} }
return { context, payload, fold, messages, sessions } return { context, storageData, messages }
} }
function balanceResponse(credits: number) { function balanceResponse(credits: number) {
@@ -94,12 +71,7 @@ function fetchSequence(credits: number[]) {
} }
function createTrackedStore(context: unknown, options: BalanceOptions = {}) { function createTrackedStore(context: unknown, options: BalanceOptions = {}) {
return createBalanceStore( return createBalanceStore(context as never, { apiKey: "test-key", ...options }, {}, fetchSequence([10]))
context as never,
{ apiKey: "test-key", ...options },
{},
fetchSequence([10]),
)
} }
describe("usage tracking in the balance store", () => { 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() 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() store.dispose()
}) })
@@ -124,8 +96,8 @@ describe("usage tracking in the balance store", () => {
const store = createTrackedStore(context) const store = createTrackedStore(context)
messages.set("s1", [ messages.set("s1", [
{ {
id: "m1",
type: "assistant", type: "assistant",
id: "m1",
model: { providerID: "greenpt", id: "glm-5.3-flash" }, model: { providerID: "greenpt", id: "glm-5.3-flash" },
cost: 0.02, cost: 0.02,
time: { created: NOW }, time: { created: NOW },
@@ -135,12 +107,12 @@ describe("usage tracking in the balance store", () => {
context.emit("session.idle", { data: { sessionID: "s1" } }) context.emit("session.idle", { data: { sessionID: "s1" } })
await store.refresh() await store.refresh()
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() store.dispose()
}) })
it("persists buckets to the durable store and reloads them", async () => { it("persists buckets to durable storage and reloads them", async () => {
const { context, payload } = makeContext() const { context, storageData } = makeContext()
const first = createBalanceStore( const first = createBalanceStore(
context as never, context as never,
{ apiKey: "test-key" }, { apiKey: "test-key" },
@@ -149,12 +121,20 @@ describe("usage tracking in the balance store", () => {
) )
await first.refresh() await first.refresh()
await first.refresh() await first.refresh()
expect(payload.days.length).toBeGreaterThan(0) expect(storageData.has("greenpt.usage.days")).toBe(true)
first.dispose() first.dispose()
const second = createTrackedStore(context) const stored: UsageDays = { [DAY]: { date: DAY, creditsSpent: 0.5, byModel: {}, ids: [] } }
expect(second.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.1) storageData.set("greenpt.usage.days", stored)
second.dispose() 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 () => { it("resetUsage clears buckets", async () => {
@@ -162,14 +142,13 @@ describe("usage tracking in the balance store", () => {
const store = createTrackedStore(context) const store = createTrackedStore(context)
await store.refresh() await store.refresh()
await store.refresh() await store.refresh()
store.resetUsage() await store.resetUsage()
await store.refresh() expect(Object.keys(store.usageDays).length).toBe(0)
expect(Object.keys(store.usageDays()).length).toBe(0)
store.dispose() store.dispose()
}) })
it("skips tracking when disabled", async () => { it("skips tracking when disabled", async () => {
const { context, payload } = makeContext() const { context, storageData } = makeContext()
const store = createBalanceStore( const store = createBalanceStore(
context as never, context as never,
{ apiKey: "test-key", trackUsage: false }, { apiKey: "test-key", trackUsage: false },
@@ -178,8 +157,8 @@ describe("usage tracking in the balance store", () => {
) )
await store.refresh() await store.refresh()
await store.refresh() await store.refresh()
expect(Object.keys(store.usageDays()).length).toBe(0) expect(Object.keys(store.usageDays).length).toBe(0)
expect(payload.days.length).toBe(0) expect(storageData.has("greenpt.usage.days")).toBe(false)
store.dispose() 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> = {}) { function assistantMessage(overrides: Record<string, unknown> = {}) {
return { return {
id: "msg-1", id: "msg-1",
type: "assistant", role: "assistant",
model: { providerID: "greenpt", id: "glm-5.3-flash" }, providerID: "greenpt",
modelID: "glm-5.3-flash",
cost: 0.01, cost: 0.01,
time: { created: NOW }, time: { created: NOW },
tokens: { input: 100, output: 50, reasoning: 10, cache: { read: 5, write: 2 } }, tokens: { input: 100, output: 50, reasoning: 10, cache: { read: 5, write: 2 } },
@@ -52,12 +53,7 @@ describe("recordMessage", () => {
it("ignores non-GreenPT providers", () => { it("ignores non-GreenPT providers", () => {
const days: UsageDays = {} const days: UsageDays = {}
expect( expect(recordMessage(days, assistantMessage({ providerID: "anthropic" }))).toBe(false)
recordMessage(
days,
assistantMessage({ model: { providerID: "anthropic", id: "claude-sonnet" } }),
),
).toBe(false)
expect(Object.keys(days).length).toBe(0) expect(Object.keys(days).length).toBe(0)
}) })
@@ -82,7 +78,7 @@ describe("applyMessages", () => {
it("skips user messages and unknown shapes", () => { it("skips user messages and unknown shapes", () => {
const days: UsageDays = {} const days: UsageDays = {}
applyMessages(days, [ applyMessages(days, [
{ id: "u1", type: "user" }, { id: "u1", role: "user" },
assistantMessage(), assistantMessage(),
null, null,
undefined, undefined,
@@ -108,7 +104,7 @@ describe("totals", () => {
recordMessage(days, assistantMessage()) recordMessage(days, assistantMessage())
recordMessage( recordMessage(
days, 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) const day = dayTotals(days, NOW)
expect(day.byModel.map((row) => row.model)).toEqual(["kimi-k2", "glm-5.3-flash"]) expect(day.byModel.map((row) => row.model)).toEqual(["kimi-k2", "glm-5.3-flash"])