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

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

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

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

View File

@@ -2,7 +2,7 @@
## Project ## Project
`opencode-greenpt-usage` — an OpenCode **TUI** plugin (Solid + OpenTUI) that `opencode-greenpt-usage` — an OpenCode **2** TUI plugin (Solid + OpenTUI) that
shows the remaining GreenPT API credit balance in the sidebar. Distributed by shows the remaining GreenPT API credit balance in the sidebar. Distributed by
`git clone`; there is no npm publish. `git clone`; there is no npm publish.
@@ -17,18 +17,23 @@ GREENPT_API_KEY=... npm run test:integration # live API test
## Conventions ## Conventions
- The plugin entry is the `default export { id, tui }` in `src/index.tsx`. - The plugin entry is `Plugin.define({ id: "greenpt.usage", setup })` in
Types come from `@opencode-ai/plugin/tui` as **type-only** imports; the `src/index.tsx` (default export). Types come from `@opencode/plugin/tui` and
host provides `solid-js` and `@opentui/solid` at runtime. `@opencode/plugin/tui/context` as **type-only** imports; the host provides
- The section is registered on the `sidebar_content` slot and is hidden when `solid-js` and `@opentui/*` at runtime.
no GreenPT credential is present (`showWhenUnavailable` opts into a hint). - The section is registered on the `sidebar.content` slot via
`context.ui.slot({ append: ..., render })`, hidden when no GreenPT credential
is present (`showWhenUnavailable` opts into a hint). Commands use
`context.keymap.layer`; `setup` returns a cleanup that unregisters the slot
and disposes the store.
- Balance probing must stay **free**: `HEAD /v1/chat/completions` returns - 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 KV store. messages (V2 `type: "assistant"`, `model.providerID`/`model.id`),
idempotent by message id, persisted with `context.storage.store`.
- Credential resolution order: `apiKey` option, `GREENPT_API_KEY`, active - 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 KV - **Usage tracking** keeps per-day buckets, persisted in the plugin's durable
store (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,7 +47,7 @@ looks for a key.
## Requirements ## Requirements
- OpenCode `>= 1.18.0` (TUI plugin system). - OpenCode `>= 2.0.0` (V2 TUI plugin API).
- A GreenPT account and API key. - A GreenPT account and API key.
## Installation ## Installation
@@ -64,35 +64,38 @@ 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/tui.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
{ {
"$schema": "https://opencode.ai/tui.json", "$schema": "https://opencode.ai/v2/cli.json",
"plugin": [ "plugins": [
["file:///ABSOLUTE/PATH/TO/opencode-greenpt-usage/src/index.tsx", { "order": 700 }] {
"package": "file:///ABSOLUTE/PATH/TO/opencode-greenpt-usage",
"options": { "refreshInterval": 60 }
}
] ]
} }
``` ```
> Use a `file://` URL pointing at the source file `src/index.tsx` > V2 loads a package directory, not a source file. Do not point at
> (OpenCode compiles the TSX itself). Do not point at a bundle: that > `src/index.tsx`: a configured file is skipped. OpenCode compiles the TSX
> would embed a second copy of `solid-js` and the section would stay > entrypoint itself.
> blank.
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 plugin entry of `tui.json`: All options are optional and go in the plugin entry of `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 | `700` | Sidebar section position. | | `order` | number | ignored | Accepted for V1 compatibility; V2 orders slots by plugin load order. |
| `showWhenUnavailable` | boolean | `false` | Show a hint when no GreenPT key exists. | | `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. |
@@ -103,7 +106,9 @@ All options are optional and go in the plugin entry of `tui.json`:
- **The section does not appear**: make sure `opencode auth login` stored a - **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://`
URL in `tui.json` points at the right path. entry in `cli.json` points at the **repository directory**, not at
`src/index.tsx`. Check that `opencode plugin list` lists your repository
directory.
- **"invalid GreenPT key"**: the API key was rejected (HTTP 401). - **"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.

4735
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.1.0",
"description": "OpenCode TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.", "description": "OpenCode 2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
"type": "module", "type": "module",
"license": "AGPL-3.0-or-later", "license": "AGPL-3.0-or-later",
"keywords": [ "keywords": [
@@ -13,21 +13,29 @@
"balance" "balance"
], ],
"engines": { "engines": {
"opencode": ">=1.18.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": {
"@opencode/plugin": "^2.0.32"
},
"peerDependencies": { "peerDependencies": {
"@opencode-ai/plugin": "*", "@opentui/core": ">=0.6.6",
"@opentui/solid": "*", "@opentui/solid": ">=0.6.6",
"solid-js": "*" "solid-js": ">=1.9.0"
}, },
"devDependencies": { "devDependencies": {
"@opencode-ai/plugin": "^1.18.33", "@opencode/plugin": "^2.0.32",
"@opentui/solid": "^0.5.12", "@opentui/core": "^0.6.6",
"@opentui/solid": "^0.6.6",
"@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,9 +1,9 @@
import type { BalanceError } from "./balance" import type { BalanceError } from "./balance"
/** Key used to persist the section fold state in the shared KV store. */ /** Key used to persist the section fold state in the durable TUI store. */
export const BALANCE_OPEN_KV = "greenpt.usage.open" export const BALANCE_OPEN_KV = "greenpt.usage.open"
/** Key used to persist the usage day buckets in the shared KV store. */ /** Key used to persist the usage day buckets in the durable TUI store. */
export const USAGE_DAYS_KV = "greenpt.usage.days" 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). */
@@ -57,24 +57,3 @@ export function formatTokens(tokens: number): string {
const m = tokens / 1_000_000 const m = tokens / 1_000_000
return `${m < 100 ? m.toFixed(1) : String(Math.round(m))}M` return `${m < 100 ? m.toFixed(1) : String(Math.round(m))}M`
} }
/**
* Read the persisted fold state, tolerating a missing or broken KV store.
*
* @param kv KV store exposing `get`, if available.
* @param fallback Value returned when the state is absent or invalid.
* @returns Whether the section should start expanded.
*/
export function readFoldOpen(
kv: { get: (key: string, fallback?: boolean) => unknown } | undefined,
fallback = true,
): boolean {
if (!kv) return fallback
try {
const value = kv.get(BALANCE_OPEN_KV, fallback)
if (typeof value !== "boolean") return fallback
return value
} catch {
return fallback
}
}

View File

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

View File

@@ -1,5 +1,4 @@
import { createSignal } from "solid-js" import type { Context } from "@opencode/plugin/tui/context"
import type { TuiPluginApi } from "@opencode-ai/plugin/tui"
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 { USAGE_DAYS_KV } from "./format"
import { resolveGreenptKey, type CredentialEnv } from "./credential" import { resolveGreenptKey, type CredentialEnv } from "./credential"
@@ -10,7 +9,6 @@ import {
pruneUsage, pruneUsage,
serializeUsage, serializeUsage,
type UsageDays, type UsageDays,
type UsageMessage,
} from "./usage" } from "./usage"
/** Default GreenPT API base URL. */ /** Default GreenPT API base URL. */
@@ -29,6 +27,7 @@ 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 order?: number
showWhenUnavailable?: boolean showWhenUnavailable?: boolean
unit?: string unit?: string
@@ -54,39 +53,49 @@ export type BalanceStore = {
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 STATE_RETRY_MS = 5_000
const TICK_MS = 30_000 const TICK_MS = 30_000
/** /**
* 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 are persisted * reconciled from local OpenCode assistant messages. Buckets are persisted in
* in the plugin KV store and pruned to `usageWindowDays`. * the plugin's durable TUI store and pruned to `usageWindowDays`.
* *
* @param api TUI plugin API (used for the auth store path, events, KV and * @param context TUI plugin context (events, session data, storage).
* session messages).
* @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.
* @returns The store. * @returns The store.
*/ */
export function createBalanceStore( export function createBalanceStore(
api: TuiPluginApi, context: Context,
options: BalanceOptions = {}, options: BalanceOptions = {},
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,
const [usageDays, setUsageDays] = createSignal<UsageDays>(readUsageDays(api.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
@@ -96,56 +105,69 @@ export function createBalanceStore(
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 stateRetryTimer: 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
let retriedState = false
let lastCredits: number | undefined let lastCredits: number | undefined
let kvLoaded = false
const trackedSessions = new Set<string>() const trackedSessions = new Set<string>()
const controller = new AbortController() const controller = new AbortController()
const unsubscribeIdle = api.event.on("session.idle", (event) => { const unsubscribeIdle = context.data.on("session.idle", (event) => {
trackSession(event.properties.sessionID) trackSession(event.data.sessionID)
reconcileSessions() reconcileSessions()
void refresh() void refresh()
}) })
const unsubscribeStatus = api.event.on("session.status", (event) => { const unsubscribeStatus = context.data.on("session.status", (event) => {
trackSession(event.properties.sessionID) trackSession(event.data.sessionID)
}) })
const unsubscribeConnected = api.event.on("server.connected", () => void refresh()) const unsubscribeConnected = context.data.on("server.connected", () => void refresh())
function readUsageDays(kv: TuiPluginApi["kv"]): UsageDays { /**
try { * Replace the balance snapshot in place so host store subscribers rerender.
const raw = kv.get(USAGE_DAYS_KV) *
if (raw === undefined) return {} * @param next Snapshot to publish.
return parseUsageDays(raw) */
} catch { function replaceBalance(next: BalanceState): void {
return {} setBalance((draft) => {
} for (const key of Object.keys(draft)) delete (draft as Record<string, unknown>)[key]
} Object.assign(draft, next)
})
function writeUsageDays(kv: TuiPluginApi["kv"], days: UsageDays): void {
try {
kv.set(USAGE_DAYS_KV, serializeUsage(days))
} catch {
// KV persistence is optional; in-memory buckets remain usable.
}
} }
/** 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 a fresh top-level record for reactivity. */ /**
* Apply usage mutations in the durable store.
*
* Writes are chained so concurrent refreshes cannot interleave payloads.
*
* @param mutate Callback mutating a fresh copy of the buckets.
*/
function mutateUsage(mutate: (days: UsageDays) => void): void { function mutateUsage(mutate: (days: UsageDays) => void): void {
if (!trackUsage) return if (!trackUsage) return
const days: UsageDays = { ...usageDays() } persistChain = persistChain
.then(() =>
updateUsagePayload((draft) => {
const days = parseUsageDays(draft)
mutate(days) mutate(days)
pruneUsage(days, usageWindowDays, Date.now()) pruneUsage(days, usageWindowDays, Date.now())
setUsageDays(days) const payload = serializeUsage(days) as UsagePayload
writeUsageDays(api.kv, days) draft.version = payload.version
draft.days = payload.days
}),
)
.catch((error) => {
console.error(`[greenpt.usage] persist: ${error}`)
})
}
/** Current usage buckets, read reactively from the durable store. */
function usageDays(): UsageDays {
return parseUsageDays(usagePayload)
} }
/** /**
@@ -155,93 +177,69 @@ export function createBalanceStore(
function reconcileSessions(): void { function reconcileSessions(): void {
if (!trackUsage || trackedSessions.size === 0) return if (!trackUsage || trackedSessions.size === 0) return
for (const sessionID of trackedSessions) { for (const sessionID of trackedSessions) {
let messages: ReadonlyArray<UsageMessage> | undefined const messages = context.data.session.message.list(sessionID)
try {
messages = api.state.session.messages(sessionID)
} catch {
continue
}
if (!messages?.length) continue if (!messages?.length) continue
mutateUsage((days) => applyMessages(days, messages as ReadonlyArray<unknown>)) mutateUsage((days) => applyMessages(days, messages))
} }
} }
/** Best-effort startup backfill from recently updated sessions. */ /** 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
const client = api.client as
| {
session?: {
list?: (parameters?: { limit?: number }) => Promise<unknown>
messages?: (parameters: { sessionID: string }) => Promise<unknown>
}
}
| undefined
if (!client?.session?.list || !client.session.messages) return
try { try {
const listed = (await client.session.list({ limit: usageBackfillLimit })) as { const sessions = context.data.session.list()
data?: unknown const recent = [...sessions]
} .sort((a, b) => (b.time?.updated ?? 0) - (a.time?.updated ?? 0))
if (!Array.isArray(listed?.data)) return .slice(0, usageBackfillLimit)
for (const session of listed.data) { 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 result = (await client.session.messages({ sessionID })) as { data?: unknown } await context.data.session.message.sync(session.id)
if (!Array.isArray(result?.data)) continue mutateUsage((days) =>
const messages = result.data applyMessages(days, context.data.session.message.list(session.id)),
.map((row) => (row as { info?: unknown })?.info) )
.filter((info) => info !== undefined && info !== null) } catch (error) {
mutateUsage((days) => applyMessages(days, messages)) console.error(`[greenpt.usage] backfill ${session.id}: ${error}`)
} catch {
// One unreadable session must not abort the whole backfill.
} }
} }
} catch { await persistChain
// Backfill is optional; live tracking continues regardless. } catch (error) {
console.error(`[greenpt.usage] backfill: ${error}`)
} }
} }
/** Re-read persisted buckets once the KV store becomes ready. */ /** Arm the next periodic refresh, backing off after errors. */
function reloadUsageWhenReady(): void { function scheduleNext(): void {
if (!trackUsage || kvLoaded || api.kv.ready !== true) return
kvLoaded = true
setUsageDays(readUsageDays(api.kv))
}
function scheduleNext() {
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
reloadUsageWhenReady()
try { try {
const credential = resolveGreenptKey(options, api.state.path.state, 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 } })
if (api.state.path.state === undefined && !retriedState) {
retriedState = true
stateRetryTimer = setTimeout(() => void refresh(), STATE_RETRY_MS)
}
return return
} }
@@ -264,16 +262,17 @@ export function createBalanceStore(
} }
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
reconcileSessions() reconcileSessions()
await persistChain
scheduleNext() scheduleNext()
} }
@@ -287,12 +286,12 @@ export function createBalanceStore(
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)
if (tickTimer) clearTimeout(tickTimer) if (tickTimer) clearTimeout(tickTimer)
if (stateRetryTimer) clearTimeout(stateRetryTimer)
unsubscribeIdle() unsubscribeIdle()
unsubscribeStatus() unsubscribeStatus()
unsubscribeConnected() unsubscribeConnected()
@@ -300,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,14 +1,7 @@
/** @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 { TuiPluginApi, TuiThemeCurrent } from "@opencode-ai/plugin/tui" import type { Context } from "@opencode/plugin/tui/context"
import { import { BALANCE_OPEN_KV, formatBalanceError, formatCredits, formatTokens, DEFAULT_UNIT } from "./format"
formatBalanceError,
formatCredits,
formatTokens,
readFoldOpen,
BALANCE_OPEN_KV,
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"
@@ -22,24 +15,24 @@ 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: {
api: TuiPluginApi context: Context
store: BalanceStore store: BalanceStore
showWhenUnavailable: boolean showWhenUnavailable: boolean
unit?: string unit?: string
}) { }) {
const theme = () => props.api.theme.current const theme = () => props.context.theme
const [fold, updateFold] = props.context.storage.store<{ open: boolean }>(
BALANCE_OPEN_KV,
{ initial: { open: true } },
)
const state = () => props.store.state() const state = () => props.store.state()
const status = () => state().status const status = () => state().status
const [open, setOpen] = createSignal(readFoldOpen(props.api.kv)) const open = () => fold.open
const toggle = () => { const toggle = () => {
const next = !open() void updateFold((draft) => {
setOpen(next) draft.open = !draft.open
try { })
props.api.kv.set(BALANCE_OPEN_KV, next)
} catch {
// KV persistence is optional; the local toggle still applies.
}
} }
const error = () => { const error = () => {
@@ -83,12 +76,12 @@ export function GreenptWidget(props: {
return ( return (
<Show when={!hidden()} fallback={<box />}> <Show when={!hidden()} fallback={<box />}>
<box flexDirection="column" gap={1}> <box flexDirection="column" gap={1}>
<text fg={theme().text} onMouseUp={toggle}> <text fg={theme().text.base} onMouseUp={toggle}>
<span style={{ fg: theme().textMuted }}>{open() ? "▼ " : "▶ "}</span> <span style={{ fg: theme().text.muted }}>{open() ? "▼ " : "▶ "}</span>
<b>GreenPT</b> <b>GreenPT</b>
<Show when={!open() && balanceText()}> <Show when={!open() && balanceText()}>
{(text) => ( {(text) => (
<span style={{ fg: theme()[balanceColor()] }}> <span style={{ fg: theme().text.feedback[balanceColor()].base }}>
{" "} {" "}
{text()} {text()}
{foldedSuffix()} {foldedSuffix()}
@@ -100,38 +93,42 @@ export function GreenptWidget(props: {
<Switch> <Switch>
<Match when={status() === "ready"}> <Match when={status() === "ready"}>
<box flexDirection="row" gap={1} justifyContent="space-between"> <box flexDirection="row" gap={1} justifyContent="space-between">
<text fg={theme().textMuted}>Balance</text> <text fg={theme().text.muted}>Balance</text>
<box flexDirection="row" gap={1}> <box flexDirection="row" gap={1}>
<text fg={theme()[balanceColor()]}>{balanceText()}</text> <text fg={theme().text.feedback[balanceColor()].base}>{balanceText()}</text>
<text fg={theme().textMuted}>{updatedAt()}</text> <text fg={theme().text.muted}>{updatedAt()}</text>
</box> </box>
</box> </box>
</Match> </Match>
<Match when={status() === "loading"}> <Match when={status() === "loading"}>
<text fg={theme().textMuted}>loading…</text> <text fg={theme().text.muted}>loading…</text>
</Match> </Match>
<Match when={credentialReason() !== undefined && props.showWhenUnavailable}> <Match when={credentialReason() !== undefined && props.showWhenUnavailable}>
<CredentialHint reason={credentialReason()!} theme={theme()} /> <CredentialHint reason={credentialReason()!} theme={theme()} />
</Match> </Match>
<Match when={status() === "error"}> <Match when={status() === "error"}>
<text fg={theme().textMuted}>{formatBalanceError(error()!)}</text> <text fg={theme().text.muted}>{formatBalanceError(error()!)}</text>
</Match> </Match>
</Switch> </Switch>
<Show when={usageVisible()}> <Show when={usageVisible()}>
<box flexDirection="row" gap={1} justifyContent="space-between"> <box flexDirection="row" gap={1} justifyContent="space-between">
<text fg={theme().textMuted}>Spent</text> <text fg={theme().text.muted}>Spent</text>
<box flexDirection="row" gap={1}> <box flexDirection="row" gap={1}>
<text fg={theme().text}>today {todayText()}</text> <text fg={theme().text.base}>today {todayText()}</text>
<text fg={theme().textMuted}>month {monthText()}</text> <text fg={theme().text.muted}>month {monthText()}</text>
</box> </box>
</box> </box>
<For each={modelRows()}> <For each={modelRows()}>
{(row) => ( {(row) => (
<box flexDirection="row" gap={1} justifyContent="space-between"> <box flexDirection="row" gap={1} justifyContent="space-between">
<text fg={theme().textMuted}>{row.model}</text> <text fg={theme().text.muted}>{row.model}</text>
<box flexDirection="row" gap={1}> <box flexDirection="row" gap={1}>
<text fg={theme().textMuted}>{formatTokens(row.usage.tokens.input + row.usage.tokens.output)} tok</text> <text fg={theme().text.muted}>
<text fg={theme().text}>~{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>
)} )}
@@ -147,9 +144,9 @@ 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: TuiThemeCurrent }) { function CredentialHint(props: { reason: "missing"; theme: Context["theme"] }) {
return ( return (
<text fg={props.theme.textMuted}> <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"}
</text> </text>
) )

View File

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

View File

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