Compare commits

2 Commits
v2 ... main

Author SHA1 Message Date
Stéphan Sainléger
d123b9b3be chg: [opencode-greenpt-usage] tighten the sidebar balance layout
Put the balance on the section header line and keep the folded header to
one row with today's spend. Remove the gap between the title and the
metrics line, then indent model tokens below the full model name so they
read as subordinate detail instead of wrapping mid-name.

The stacked model rows avoid the narrow sidebar splitting a model id;
costs stay right-aligned. Typecheck and the 49 unit tests pass.
2026-11-18 23:13:52 +01:00
Stéphan Sainléger
dadc93a22d chg: [opencode-greenpt-usage] port the TUI plugin to OpenCode 2
V1 TUI modules no longer load: replace ``{ id, tui }`` with
``Plugin.define({ id, setup })``, register the section on
``sidebar.content``, and expose commands through ``context.keymap.layer``.

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

Configure the package directory in ``cli.json`` instead of the source
file; document the V2 install. Typecheck, 49 unit tests and the live
GreenPT integration test pass, and the sidebar renders the balance.
2026-11-18 23:01:40 +01:00
14 changed files with 784 additions and 720 deletions

View File

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

View File

@@ -1,7 +1,7 @@
# opencode-greenpt-usage # opencode-greenpt-usage
An [OpenCode](https://opencode.ai) TUI plugin that shows the remaining An [OpenCode](https://opencode.ai) **OpenCode 2** TUI plugin that shows the
**GreenPT API credit balance** and the **consumption** of the API key remaining **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 durable - **Usage tracking** keeps per-day buckets, persisted in the plugin's durable
storage (90 days by default): TUI store (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,8 +47,7 @@ looks for a key.
## Requirements ## Requirements
- OpenCode `>= 2.0.0` (v2 CLI/TUI plugin system; for OpenCode 1.x use the - OpenCode `>= 2.0.0` (V2 TUI plugin API).
`main` branch).
- A GreenPT account and API key. - A GreenPT account and API key.
## Installation ## Installation
@@ -65,8 +64,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`, setting the 3. **Register the plugin** in `~/.config/opencode/cli.json`, pointing at the
**absolute path to your clone**: **repository directory** (the package's `./tui` export):
```jsonc ```jsonc
{ {
@@ -74,28 +73,29 @@ looks for a key.
"plugins": [ "plugins": [
{ {
"package": "file:///ABSOLUTE/PATH/TO/opencode-greenpt-usage", "package": "file:///ABSOLUTE/PATH/TO/opencode-greenpt-usage",
"options": { "showWhenUnavailable": false } "options": { "refreshInterval": 60 }
} }
] ]
} }
``` ```
> Point at the repository root, not at a source file: OpenCode v2 loads > V2 loads a package directory, not a source file. Do not point at
> the `./tui` entry (`src/tui.tsx`) from the package `exports` and > `src/index.tsx`: a configured file is skipped. OpenCode compiles the TSX
> resolves `@opencode/plugin` at runtime. > entrypoint itself.
4. **Fully quit OpenCode and relaunch it** (plugins are not hot-reloaded). 4. **Reload OpenCode**. V2 reloads configuration and plugins after a save; if
a running session keeps the old module, quit and relaunch it.
## Configuration ## Configuration
All options are optional and go in the `options` object of the plugin entry All options are optional and go in the plugin entry of `cli.json`:
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,7 +106,9 @@ in `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://`
path in `cli.json` points at the repository root. entry in `cli.json` points at the **repository directory**, not at
`src/index.tsx`. Check that `opencode plugin list` lists your repository
directory.
- **"invalid GreenPT key"**: the API key was rejected (HTTP 401). - **"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.2.0", "version": "0.1.0",
"description": "OpenCode v2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.", "description": "OpenCode 2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
"type": "module", "type": "module",
"license": "AGPL-3.0-or-later", "license": "AGPL-3.0-or-later",
"keywords": [ "keywords": [
@@ -15,26 +15,27 @@
"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"
}, },
"exports": { "dependencies": {
".": "./src/index.ts", "@opencode/plugin": "^2.0.32"
"./tui": "./src/tui.tsx"
}, },
"peerDependencies": { "peerDependencies": {
"@opencode/plugin": ">=2.0.0 <3", "@opentui/core": ">=0.6.6",
"@opentui/core": ">=0.5.17", "@opentui/solid": ">=0.6.6",
"@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",
"@opencode/theme": "^2.0.32", "@opentui/core": "^0.6.6",
"@opentui/core": "^0.5.17", "@opentui/solid": "^0.6.6",
"@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,7 +32,8 @@ 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 OpenCode state directory (from `api.state.path.state`). * @param stateDir Optional data-directory override used by tests; production
* resolution falls back to `$XDG_DATA_HOME` or `$HOME`.
* @param env Environment mapping, injectable for tests. * @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,7 +1,10 @@
import type { BalanceError } from "./balance" import type { BalanceError } from "./balance"
/** Key used to persist the section fold state in the durable plugin storage. */ /** Key used to persist the section fold state in the durable TUI store. */
export const FOLD_STORAGE_KEY = "greenpt.usage.open" 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"
/** 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 = "€"

View File

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

View File

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

View File

@@ -1,21 +1,19 @@
import { createSignal } from "solid-js" import type { Context } from "@opencode/plugin/tui/context"
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
@@ -29,6 +27,8 @@ 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,55 +47,34 @@ 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: () => Promise<void> resetUsage: () => 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 * Refreshes on creation, on `session.idle`, on `server.connected`, on a timer,
* timer, and on demand via `refresh()`. Errors are retried with an * and on demand via `refresh()`. Errors are retried with an exponential
* exponential backoff so a transient outage does not hammer the API. * 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 live in the * reconciled from local OpenCode assistant messages. Buckets are persisted in
* plugin durable storage and are pruned to `usageWindowDays`. * the plugin's durable TUI store and pruned to `usageWindowDays`.
* *
* @param context OpenCode v2 TUI plugin context. * @param context TUI plugin context (events, session data, storage).
* @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.
@@ -107,8 +86,16 @@ export function createBalanceStore(
env: CredentialEnv = process.env as CredentialEnv, env: CredentialEnv = process.env as CredentialEnv,
fetchImpl: FetchLike = nativeFetch, fetchImpl: FetchLike = nativeFetch,
): BalanceStore { ): BalanceStore {
const [state, setState] = createSignal<BalanceState>({ status: "loading" }) const [usagePayload, updateUsagePayload] = context.storage.store<UsagePayload>(
const [now, setNow] = createSignal(Date.now()) USAGE_DAYS_KV,
{ initial: { version: 1, days: [] } },
)
const [balance, setBalance] = context.storage.memory<BalanceState>("greenpt.balance", {
initial: { status: "loading" },
})
const [clock, setClock] = context.storage.memory<{ value: number }>("greenpt.now", {
initial: { value: Date.now() },
})
const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL
const interval = options.refreshInterval ?? DEFAULT_REFRESH_SECONDS const interval = options.refreshInterval ?? DEFAULT_REFRESH_SECONDS
@@ -116,17 +103,9 @@ 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
@@ -136,7 +115,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)
void reconcileSessions() reconcileSessions()
void refresh() void refresh()
}) })
const unsubscribeStatus = context.data.on("session.status", (event) => { const unsubscribeStatus = context.data.on("session.status", (event) => {
@@ -144,89 +123,123 @@ 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. */ /**
function mutateUsage(mutate: (days: UsageDays) => void): Promise<void> { * Apply usage mutations in the durable store.
if (!trackUsage) return Promise.resolve() *
return updateUsage((draft) => { * Writes are chained so concurrent refreshes cannot interleave payloads.
mutate(draft) *
pruneUsage(draft, usageWindowDays, Date.now()) * @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)
}
/** /**
* 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(): Promise<void> { function reconcileSessions(): void {
if (!trackUsage || trackedSessions.size === 0) return Promise.resolve() if (!trackUsage || trackedSessions.size === 0) return
const updates: Promise<void>[] = []
for (const sessionID of trackedSessions) { for (const sessionID of trackedSessions) {
let messages: ReadonlyArray<unknown> | undefined const messages = context.data.session.message.list(sessionID)
try {
messages = context.data.session.message.list(sessionID)
} catch {
continue
}
if (!messages?.length) continue if (!messages?.length) continue
updates.push(mutateUsage((days) => applyMessages(days, toUsageMessages(messages ?? [])))) mutateUsage((days) => applyMessages(days, 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 listed = await context.client.session.list({ const sessions = context.data.session.list()
limit: usageBackfillLimit, const recent = [...sessions]
}) .sort((a, b) => (b.time?.updated ?? 0) - (a.time?.updated ?? 0))
for (const session of listed.data ?? []) { .slice(0, usageBackfillLimit)
for (const session of recent) {
if (disposed) return if (disposed) return
const sessionID = (session as { id?: unknown })?.id trackedSessions.add(session.id)
if (typeof sessionID !== "string" || !sessionID) continue
trackedSessions.add(sessionID)
try { try {
const messages = await context.client.session.context({ sessionID }) await context.data.session.message.sync(session.id)
await mutateUsage((days) => applyMessages(days, toUsageMessages(messages))) mutateUsage((days) =>
} catch { applyMessages(days, context.data.session.message.list(session.id)),
// One unreadable session must not abort the whole backfill. )
} catch (error) {
console.error(`[greenpt.usage] backfill ${session.id}: ${error}`)
} }
} }
} catch { await persistChain
// Backfill is optional; live tracking continues regardless. } catch (error) {
console.error(`[greenpt.usage] backfill: ${error}`)
} }
} }
function scheduleNext() { /** Arm the next periodic refresh, backing off after errors. */
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 = state().status === "error" ? backoff : intervalMs const delay = balance.status === "error" ? backoff : intervalMs
refreshTimer = setTimeout(() => { refreshTimer = setTimeout(() => {
refreshTimer = undefined refreshTimer = undefined
void refresh() void refresh()
}, delay) }, delay)
} }
function tick() { /** Advance the clock used for day/month totals. */
function tick(): void {
if (disposed) return if (disposed) return
setNow(Date.now()) setClock((draft) => {
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) {
setState({ status: "error", error: { kind: "no-credential", reason: credential.reason } }) replaceBalance({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
return return
} }
@@ -245,34 +258,36 @@ 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
await mutateUsage((days) => addCreditsSpent(days, Date.now(), spent)) mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
} }
lastCredits = credits lastCredits = credits
} }
setState({ status: "ready", data: result, fetchedAt: Date.now() }) replaceBalance({ 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)
setState({ status: "error", error: result }) replaceBalance({ status: "error", error: result })
} }
} finally { } finally {
inFlight = false inFlight = false
} }
if (disposed) return if (disposed) return
await reconcileSessions() reconcileSessions()
await persistChain
scheduleNext() scheduleNext()
} }
/** Clear every persisted and in-memory usage bucket. */ /** Clear every persisted and in-memory usage bucket. */
async function resetUsage(): Promise<void> { function resetUsage(): void {
lastCredits = undefined lastCredits = undefined
await mutateUsage((days) => { 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)
function dispose() { /** Stop timers, network work and event subscriptions. */
function dispose(): void {
disposed = true disposed = true
controller.abort() controller.abort()
if (refreshTimer) clearTimeout(refreshTimer) if (refreshTimer) clearTimeout(refreshTimer)
@@ -284,5 +299,12 @@ export function createBalanceStore(
void backfillUsage() void backfillUsage()
return { state, now, usageDays, refresh, resetUsage, dispose } return {
state: () => balance as BalanceState,
now: () => clock.value,
usageDays,
refresh,
resetUsage,
dispose,
}
} }

View File

@@ -47,12 +47,14 @@ export type UsageTotals = {
byModel: ModelTotal[] byModel: ModelTotal[]
} }
/** Structural subset of an OpenCode assistant message used for accounting. */ /** Structural subset of an OpenCode 2 assistant message used for accounting. */
export type UsageMessage = { export type UsageMessage = {
id?: unknown id?: unknown
role?: unknown type?: unknown
model?: {
providerID?: unknown providerID?: unknown
modelID?: unknown id?: unknown
}
cost?: unknown cost?: unknown
time?: { created?: unknown } time?: { created?: unknown }
tokens?: { tokens?: {
@@ -108,7 +110,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.role === "assistant" && typeof message.id === "string" return message.type === "assistant" && typeof message.id === "string"
} }
/** /**
@@ -117,7 +119,7 @@ export function isUsageMessage(value: unknown): value is UsageMessage {
* @returns `true` when the message was newly recorded. * @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.providerID === "string" ? message.providerID : "" const provider = typeof message.model?.providerID === "string" ? message.model.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
@@ -128,7 +130,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.modelID === "string" && message.modelID ? message.modelID : "unknown" const model = typeof message.model?.id === "string" && message.model.id ? message.model.id : "unknown"
const date = dayKey(created) const 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,15 +1,27 @@
/** @jsxImportSource @opentui/solid */ /** @jsxImportSource @opentui/solid */
import { createSignal, For, Match, Show, Switch } from "solid-js" import { For, Match, Show, Switch } from "solid-js"
import type { ResolvedTheme } from "@opencode/theme/tui" import type { Context } from "@opencode/plugin/tui/context"
import { import { BALANCE_OPEN_KV, formatBalanceError, formatCredits, formatTokens, DEFAULT_UNIT } from "./format"
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
@@ -20,19 +32,25 @@ import type { BalanceStore } from "./store"
* 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.theme const theme = () => props.context.theme
const [fold, updateFold] = props.context.storage.store<{ open: boolean }>(
BALANCE_OPEN_KV,
{ initial: { open: true } },
)
const state = () => props.store.state() const state = () => props.store.state()
const status = () => state().status const status = () => state().status
const open = () => props.open() const open = () => fold.open
const toggle = () => props.toggleOpen() const toggle = () => {
void updateFold((draft) => {
draft.open = !draft.open
})
}
const error = () => { const error = () => {
const s = state() const s = state()
@@ -52,8 +70,7 @@ export function GreenptWidget(props: {
} }
const balanceColor = () => { const balanceColor = () => {
const s = state() const s = state()
const kind = s.status === "ready" && s.data.credits > 0 ? "success" : "error" return 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()
@@ -61,74 +78,89 @@ 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 `updated ${hh}:${mm}` return `${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 foldedSuffix = () => (usageVisible() ? ` · today ${todayText()}` : "") const modelRows = (): ModelTotal[] => monthUsage().byModel.slice(0, MODEL_ROWS_VISIBLE)
const modelRows = (): ModelTotal[] => monthUsage().byModel.slice(0, 5) const otherModels = () => Math.max(0, monthUsage().byModel.length - MODEL_ROWS_VISIBLE)
return ( return (
<Show when={!hidden()} fallback={<box />}> <Show when={!hidden()} fallback={<box />}>
<box flexDirection="column" gap={1}> <box flexDirection="column">
<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>
<Show when={!open() && balanceText()}> </text>
<box flexDirection="row" gap={1} justifyContent="flex-end">
<Show when={balanceText()}>
{(text) => ( {(text) => (
<span style={{ fg: balanceColor() }}> <text fg={theme().text.feedback[balanceColor()].base}>
{" "} <b>{text()}</b>
{text()} </text>
{foldedSuffix()}
</span>
)} )}
</Show> </Show>
</text> <Show when={!open() && usageVisible()}>
<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 flexDirection="row" gap={1} justifyContent="space-between"> <box paddingLeft={2}>
<text fg={theme().text.muted}>Balance</text> <text fg={theme().text.muted}>
<box flexDirection="row" gap={1}> today {todayText()} · month {monthText()} · {updatedAt()}
<text fg={balanceColor()}>{balanceText()}</text> </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="row" gap={1} justifyContent="space-between"> <box flexDirection="column" marginTop={1}>
<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="row" gap={1} justifyContent="space-between"> <box flexDirection="column" paddingLeft={2}>
<text fg={theme().text.muted}>{row.model}</text> <text fg={theme().text.muted}>{shortModel(row.model)}</text>
<box flexDirection="row" gap={1}> <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.muted}>
<text fg={theme().text.base}>~{formatCredits(row.usage.cost)} {unit()}</text> {formatTokens(row.usage.tokens.input + row.usage.tokens.output)} tok
</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>
@@ -140,7 +172,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: ResolvedTheme }) { function CredentialHint(props: { reason: "missing"; theme: Context["theme"] }) {
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,4 +49,3 @@ describe("formatBalanceError", () => {
expect(formatBalanceError({ kind: "no-credential", reason: "missing" })).toContain("GreenPT") expect(formatBalanceError({ kind: "no-credential", reason: "missing" })).toContain("GreenPT")
}) })
}) })

View File

@@ -1,19 +1,58 @@
import { describe, expect, it, vi } from "vitest" import { afterEach, beforeEach, 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 type { UsageDays } from "../src/usage" import { dayKey } 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 = "2026-10-19" const DAY = dayKey(NOW)
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>> }
/** Minimal structural fake of the OpenCode v2 TUI plugin context. */ function makeContext() {
function makeContext(storage = new Map<string, object>()) { const payload: UsagePayload = { version: 1, days: [] }
const storageData = storage const fold = { open: true }
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) ?? []
@@ -27,34 +66,18 @@ function makeContext(storage = new Map<string, object>()) {
} }
}, },
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, storageData, messages } return { context, payload, fold, messages, sessions }
} }
function balanceResponse(credits: number) { function balanceResponse(credits: number) {
@@ -71,7 +94,12 @@ function fetchSequence(credits: number[]) {
} }
function createTrackedStore(context: unknown, options: BalanceOptions = {}) { 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", () => { describe("usage tracking in the balance store", () => {
@@ -87,7 +115,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()
}) })
@@ -96,8 +124,8 @@ describe("usage tracking in the balance store", () => {
const store = createTrackedStore(context) const store = createTrackedStore(context)
messages.set("s1", [ messages.set("s1", [
{ {
type: "assistant",
id: "m1", id: "m1",
type: "assistant",
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 },
@@ -107,12 +135,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 durable storage and reloads them", async () => { it("persists buckets to the durable store and reloads them", async () => {
const { context, storageData } = makeContext() const { context, payload } = makeContext()
const first = createBalanceStore( const first = createBalanceStore(
context as never, context as never,
{ apiKey: "test-key" }, { apiKey: "test-key" },
@@ -121,20 +149,12 @@ describe("usage tracking in the balance store", () => {
) )
await first.refresh() await first.refresh()
await first.refresh() await first.refresh()
expect(storageData.has("greenpt.usage.days")).toBe(true) expect(payload.days.length).toBeGreaterThan(0)
first.dispose() first.dispose()
const stored: UsageDays = { [DAY]: { date: DAY, creditsSpent: 0.5, byModel: {}, ids: [] } } const second = createTrackedStore(context)
storageData.set("greenpt.usage.days", stored) expect(second.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.1)
const { context: secondContext } = makeContext(storageData) second.dispose()
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 () => {
@@ -142,13 +162,14 @@ 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()
await store.resetUsage() store.resetUsage()
expect(Object.keys(store.usageDays).length).toBe(0) await store.refresh()
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, storageData } = makeContext() const { context, payload } = makeContext()
const store = createBalanceStore( const store = createBalanceStore(
context as never, context as never,
{ apiKey: "test-key", trackUsage: false }, { apiKey: "test-key", trackUsage: false },
@@ -157,8 +178,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(storageData.has("greenpt.usage.days")).toBe(false) expect(payload.days.length).toBe(0)
store.dispose() store.dispose()
}) })
}) })

View File

@@ -17,9 +17,8 @@ const NOW = new Date(2026, 9, 19, 15, 30, 0).getTime()
function assistantMessage(overrides: Record<string, unknown> = {}) { function assistantMessage(overrides: Record<string, unknown> = {}) {
return { return {
id: "msg-1", id: "msg-1",
role: "assistant", type: "assistant",
providerID: "greenpt", model: { providerID: "greenpt", id: "glm-5.3-flash" },
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 } },
@@ -53,7 +52,12 @@ describe("recordMessage", () => {
it("ignores non-GreenPT providers", () => { it("ignores non-GreenPT providers", () => {
const days: UsageDays = {} const days: UsageDays = {}
expect(recordMessage(days, assistantMessage({ providerID: "anthropic" }))).toBe(false) expect(
recordMessage(
days,
assistantMessage({ model: { providerID: "anthropic", id: "claude-sonnet" } }),
),
).toBe(false)
expect(Object.keys(days).length).toBe(0) expect(Object.keys(days).length).toBe(0)
}) })
@@ -78,7 +82,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", role: "user" }, { id: "u1", type: "user" },
assistantMessage(), assistantMessage(),
null, null,
undefined, undefined,
@@ -104,7 +108,7 @@ describe("totals", () => {
recordMessage(days, assistantMessage()) recordMessage(days, assistantMessage())
recordMessage( recordMessage(
days, days,
assistantMessage({ id: "msg-2", modelID: "kimi-k2", cost: 0.05 }), assistantMessage({ id: "msg-2", model: { providerID: "greenpt", id: "kimi-k2" }, cost: 0.05 }),
) )
const day = dayTotals(days, NOW) 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"])