Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d123b9b3be | ||
|
|
dadc93a22d |
29
AGENTS.md
29
AGENTS.md
@@ -2,10 +2,9 @@
|
||||
|
||||
## Project
|
||||
|
||||
`opencode-greenpt-usage` — an OpenCode **v2** CLI/TUI plugin (Solid + OpenTUI)
|
||||
that shows the remaining GreenPT API credit balance in the sidebar.
|
||||
Distributed by `git clone`; there is no npm publish. The `main` branch
|
||||
targets OpenCode 1.x; this branch targets OpenCode `>= 2.0.0`.
|
||||
`opencode-greenpt-usage` — an OpenCode **2** TUI plugin (Solid + OpenTUI) that
|
||||
shows the remaining GreenPT API credit balance in the sidebar. Distributed by
|
||||
`git clone`; there is no npm publish.
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -18,21 +17,23 @@ GREENPT_API_KEY=... npm run test:integration # live API test
|
||||
|
||||
## Conventions
|
||||
|
||||
- The plugin has two entries: `src/index.ts` (server side, minimal
|
||||
`Plugin.define`) and `src/tui.tsx` (CLI plugin, exposed as `./tui`).
|
||||
Types come from `@opencode/plugin` and `@opencode/plugin/tui`; the host
|
||||
provides `solid-js`, `@opentui/solid` and the theme at runtime.
|
||||
- The section is appended to the `sidebar.content` slot and is hidden when
|
||||
no GreenPT credential is present (`showWhenUnavailable` opts into a hint).
|
||||
- Commands are registered through `context.keymap.layer` (palette).
|
||||
- The plugin entry is `Plugin.define({ id: "greenpt.usage", setup })` in
|
||||
`src/index.tsx` (default export). Types come from `@opencode/plugin/tui` and
|
||||
`@opencode/plugin/tui/context` as **type-only** imports; the host provides
|
||||
`solid-js` and `@opentui/*` at runtime.
|
||||
- The section is registered on the `sidebar.content` slot via
|
||||
`context.ui.slot({ append: ..., render })`, hidden when no GreenPT credential
|
||||
is present (`showWhenUnavailable` opts into a hint). Commands use
|
||||
`context.keymap.layer`; `setup` returns a cleanup that unregisters the slot
|
||||
and disposes the store.
|
||||
- Balance probing must stay **free**: `HEAD /v1/chat/completions` returns
|
||||
`400` plus `x-credits-remaining`. Never replace it with a billable call.
|
||||
- Usage accounting lives in `src/usage.ts` (pure) and is consumed by the
|
||||
balance store: real spend = delta of `x-credits-remaining` between
|
||||
probes; per-model detail = reconciliation of local OpenCode assistant
|
||||
messages, idempotent by message id, persisted in the plugin durable
|
||||
storage (`context.storage.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
|
||||
OpenCode `auth.json` (`greenpt`, `type: "api"`). No profile-switching
|
||||
command may leak into this logic.
|
||||
- No code comments unless functionally required.
|
||||
- No explanatory inline comments; function contract blocks are required.
|
||||
|
||||
34
README.md
34
README.md
@@ -1,7 +1,7 @@
|
||||
# opencode-greenpt-usage
|
||||
|
||||
An [OpenCode](https://opencode.ai) TUI plugin that shows the remaining
|
||||
**GreenPT API credit balance** and the **consumption** of the API key
|
||||
An [OpenCode](https://opencode.ai) **OpenCode 2** TUI plugin that shows the
|
||||
remaining **GreenPT API credit balance** and the **consumption** of the API key
|
||||
(real credit spend plus a per-model breakdown) in the sidebar.
|
||||
|
||||
```
|
||||
@@ -24,8 +24,8 @@ kimi-k2 3.1k tok ~0.01 €
|
||||
the API answers `400 Bad Request` before any billing, yet the response
|
||||
still carries the `x-credits-remaining` header. No credit is consumed
|
||||
and no generation is triggered.
|
||||
- **Usage tracking** keeps per-day buckets, persisted in the plugin durable
|
||||
storage (90 days by default):
|
||||
- **Usage tracking** keeps per-day buckets, persisted in the plugin's durable
|
||||
TUI store (90 days by default):
|
||||
- *real credit spend* is observed as the drop of `x-credits-remaining`
|
||||
between two balance probes — this covers **every client** of the API
|
||||
key, not just OpenCode, but has no per-model detail;
|
||||
@@ -47,8 +47,7 @@ looks for a key.
|
||||
|
||||
## Requirements
|
||||
|
||||
- OpenCode `>= 2.0.0` (v2 CLI/TUI plugin system; for OpenCode 1.x use the
|
||||
`main` branch).
|
||||
- OpenCode `>= 2.0.0` (V2 TUI plugin API).
|
||||
- A GreenPT account and API key.
|
||||
|
||||
## Installation
|
||||
@@ -65,8 +64,8 @@ looks for a key.
|
||||
|
||||
(Alternative: export `GREENPT_API_KEY` in your environment.)
|
||||
|
||||
3. **Register the plugin** in `~/.config/opencode/cli.json`, setting the
|
||||
**absolute path to your clone**:
|
||||
3. **Register the plugin** in `~/.config/opencode/cli.json`, pointing at the
|
||||
**repository directory** (the package's `./tui` export):
|
||||
|
||||
```jsonc
|
||||
{
|
||||
@@ -74,28 +73,29 @@ looks for a key.
|
||||
"plugins": [
|
||||
{
|
||||
"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
|
||||
> the `./tui` entry (`src/tui.tsx`) from the package `exports` and
|
||||
> resolves `@opencode/plugin` at runtime.
|
||||
> V2 loads a package directory, not a source file. Do not point at
|
||||
> `src/index.tsx`: a configured file is skipped. OpenCode compiles the TSX
|
||||
> entrypoint itself.
|
||||
|
||||
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
|
||||
|
||||
All options are optional and go in the `options` object of the plugin entry
|
||||
in `cli.json`:
|
||||
All options are optional and go in the plugin entry of `cli.json`:
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| --------------------- | ------- | --------------------------- | ------------------------------------------------------- |
|
||||
| `apiKey` | string | resolved automatically | Explicit GreenPT key. |
|
||||
| `baseUrl` | string | `https://api.greenpt.ai/v1` | GreenPT API base URL. |
|
||||
| `refreshInterval` | number | `300` | Refresh interval in seconds (`0` disables the timer). |
|
||||
| `order` | number | ignored | Accepted for V1 compatibility; V2 orders slots by plugin load order. |
|
||||
| `showWhenUnavailable` | boolean | `false` | Show a hint when no GreenPT key exists. |
|
||||
| `unit` | string | `€` | Unit appended after the amount. |
|
||||
| `trackUsage` | boolean | `true` | Track credit spend and per-model usage. |
|
||||
@@ -106,7 +106,9 @@ in `cli.json`:
|
||||
|
||||
- **The section does not appear**: make sure `opencode auth login` stored a
|
||||
`greenpt` key (or that `GREENPT_API_KEY` is set), and that the `file://`
|
||||
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).
|
||||
- **"balance unavailable"**: GreenPT did not return the balance header; try
|
||||
again later.
|
||||
|
||||
841
package-lock.json
generated
841
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
23
package.json
23
package.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "opencode-greenpt-usage",
|
||||
"version": "0.2.0",
|
||||
"description": "OpenCode v2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
|
||||
"version": "0.1.0",
|
||||
"description": "OpenCode 2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
|
||||
"type": "module",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"keywords": [
|
||||
@@ -15,26 +15,27 @@
|
||||
"engines": {
|
||||
"opencode": ">=2.0.0"
|
||||
},
|
||||
"exports": {
|
||||
".": "./src/index.tsx",
|
||||
"./tui": "./src/index.tsx"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"test:integration": "GREENPT_INTEGRATION=1 vitest run test/integration.greenpt.test.ts",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./tui": "./src/tui.tsx"
|
||||
"dependencies": {
|
||||
"@opencode/plugin": "^2.0.32"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opencode/plugin": ">=2.0.0 <3",
|
||||
"@opentui/core": ">=0.5.17",
|
||||
"@opentui/solid": ">=0.5.17",
|
||||
"@opentui/core": ">=0.6.6",
|
||||
"@opentui/solid": ">=0.6.6",
|
||||
"solid-js": ">=1.9.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@opencode/plugin": "^2.0.32",
|
||||
"@opencode/theme": "^2.0.32",
|
||||
"@opentui/core": "^0.5.17",
|
||||
"@opentui/solid": "^0.5.17",
|
||||
"@opentui/core": "^0.6.6",
|
||||
"@opentui/solid": "^0.6.6",
|
||||
"@types/node": "^24.0.0",
|
||||
"solid-js": "^1.9.0",
|
||||
"typescript": "^5.6.0",
|
||||
|
||||
@@ -32,7 +32,8 @@ export type CredentialResult =
|
||||
* login` produces.
|
||||
*
|
||||
* @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.
|
||||
* @returns `{ ok: true, key }` when a key is found, otherwise
|
||||
* `{ ok: false, reason: "missing" }`.
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { BalanceError } from "./balance"
|
||||
|
||||
/** Key used to persist the section fold state in the durable plugin storage. */
|
||||
export const FOLD_STORAGE_KEY = "greenpt.usage.open"
|
||||
/** Key used to persist the section fold state in the durable TUI store. */
|
||||
export const BALANCE_OPEN_KV = "greenpt.usage.open"
|
||||
|
||||
/** Key used to persist the usage day buckets in the durable TUI store. */
|
||||
export const USAGE_DAYS_KV = "greenpt.usage.days"
|
||||
|
||||
/** Default unit appended to the balance (GreenPT credits are euro-denominated). */
|
||||
export const DEFAULT_UNIT = "€"
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
import { Plugin } from "@opencode/plugin"
|
||||
|
||||
export default Plugin.define({
|
||||
id: "greenpt.usage",
|
||||
setup() {},
|
||||
})
|
||||
@@ -1,32 +1,31 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
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 { GreenptWidget } from "./widget"
|
||||
|
||||
/**
|
||||
* OpenCode 2 TUI plugin definition.
|
||||
*
|
||||
* Registers the GreenPT section on `sidebar.content`, exposes refresh and
|
||||
* reset commands through the keymap layer, and owns the balance store's
|
||||
* lifetime. `order` is still accepted in config for V1 compatibility, but V2
|
||||
* orders slot contributions by plugin load order.
|
||||
*/
|
||||
export default Plugin.define({
|
||||
id: "greenpt.usage.tui",
|
||||
setup(context) {
|
||||
const opts = (context.options ?? {}) as BalanceOptions
|
||||
const store = createBalanceStore(context, opts)
|
||||
const [fold, updateFold] = context.storage.store(FOLD_STORAGE_KEY, {
|
||||
initial: { open: true },
|
||||
})
|
||||
id: "greenpt.usage",
|
||||
setup(context: Context) {
|
||||
const options = (context.options ?? {}) as BalanceOptions
|
||||
const store = createBalanceStore(context, options)
|
||||
|
||||
const unregisterSlot = context.ui.slot({
|
||||
append: "sidebar.content",
|
||||
render: () => (
|
||||
<GreenptWidget
|
||||
context={context}
|
||||
store={store}
|
||||
theme={context.theme}
|
||||
open={() => fold.open}
|
||||
toggleOpen={() => {
|
||||
void updateFold((draft) => {
|
||||
draft.open = !fold.open
|
||||
})
|
||||
}}
|
||||
showWhenUnavailable={opts.showWhenUnavailable === true}
|
||||
unit={opts.unit}
|
||||
showWhenUnavailable={options.showWhenUnavailable === true}
|
||||
unit={options.unit}
|
||||
/>
|
||||
),
|
||||
})
|
||||
@@ -37,8 +36,7 @@ export default Plugin.define({
|
||||
{
|
||||
id: "greenpt.refresh",
|
||||
title: "Refresh GreenPT balance",
|
||||
group: "GreenPT",
|
||||
palette: true,
|
||||
group: "Plugin",
|
||||
run() {
|
||||
void store.refresh()
|
||||
},
|
||||
@@ -46,15 +44,18 @@ export default Plugin.define({
|
||||
{
|
||||
id: "greenpt.usage.reset",
|
||||
title: "Reset GreenPT usage counters",
|
||||
group: "GreenPT",
|
||||
palette: true,
|
||||
group: "Plugin",
|
||||
run() {
|
||||
void store.resetUsage()
|
||||
store.resetUsage()
|
||||
},
|
||||
},
|
||||
],
|
||||
}))
|
||||
|
||||
void store.refresh().catch((error) => {
|
||||
console.error(`[greenpt.usage] refresh: ${error}`)
|
||||
})
|
||||
|
||||
return () => {
|
||||
unregisterSlot()
|
||||
store.dispose()
|
||||
214
src/store.ts
214
src/store.ts
@@ -1,21 +1,19 @@
|
||||
import { createSignal } from "solid-js"
|
||||
import type { Context } from "@opencode/plugin/tui/plugin"
|
||||
import type { Context } from "@opencode/plugin/tui/context"
|
||||
import { fetchBalance, nativeFetch, type Balance, type BalanceError, type FetchLike } from "./balance"
|
||||
import { USAGE_DAYS_KV } from "./format"
|
||||
import { resolveGreenptKey, type CredentialEnv } from "./credential"
|
||||
import {
|
||||
addCreditsSpent,
|
||||
applyMessages,
|
||||
parseUsageDays,
|
||||
pruneUsage,
|
||||
serializeUsage,
|
||||
type UsageDays,
|
||||
type UsageMessage,
|
||||
} from "./usage"
|
||||
|
||||
/** Default GreenPT API base URL. */
|
||||
export const DEFAULT_BASE_URL = "https://api.greenpt.ai/v1"
|
||||
|
||||
/** Storage key for the usage day buckets (durable plugin storage). */
|
||||
export const USAGE_DAYS_KEY = "greenpt.usage.days"
|
||||
|
||||
/** Default refresh interval, in seconds. The probe is free but should stay gentle. */
|
||||
export const DEFAULT_REFRESH_SECONDS = 300
|
||||
|
||||
@@ -29,6 +27,8 @@ export type BalanceOptions = {
|
||||
apiKey?: string
|
||||
baseUrl?: string
|
||||
refreshInterval?: number
|
||||
/** Accepted for V1 config compatibility; V2 orders slots by plugin load order. */
|
||||
order?: number
|
||||
showWhenUnavailable?: boolean
|
||||
unit?: string
|
||||
trackUsage?: boolean
|
||||
@@ -47,55 +47,34 @@ export type BalanceState =
|
||||
export type BalanceStore = {
|
||||
state: () => BalanceState
|
||||
now: () => number
|
||||
usageDays: UsageDays
|
||||
usageDays: () => UsageDays
|
||||
refresh: () => Promise<void>
|
||||
resetUsage: () => Promise<void>
|
||||
resetUsage: () => void
|
||||
dispose: () => void
|
||||
}
|
||||
|
||||
type UsagePayload = {
|
||||
version: number
|
||||
days: Array<Record<string, unknown>>
|
||||
}
|
||||
|
||||
const BACKOFF_BASE_MS = 60_000
|
||||
const BACKOFF_MAX_MS = 10 * 60_000
|
||||
const TICK_MS = 30_000
|
||||
|
||||
/** Structural view of a v2 assistant message used for accounting. */
|
||||
function toUsageMessages(messages: ReadonlyArray<unknown>): ReadonlyArray<UsageMessage> {
|
||||
const out: UsageMessage[] = []
|
||||
for (const message of messages) {
|
||||
const m = message as {
|
||||
type?: unknown
|
||||
id?: unknown
|
||||
model?: { providerID?: unknown; id?: unknown }
|
||||
cost?: unknown
|
||||
time?: { created?: unknown }
|
||||
tokens?: UsageMessage["tokens"]
|
||||
}
|
||||
if (m?.type !== "assistant" || typeof m.id !== "string") continue
|
||||
out.push({
|
||||
id: m.id,
|
||||
role: "assistant",
|
||||
providerID: m.model?.providerID,
|
||||
modelID: m.model?.id,
|
||||
cost: m.cost,
|
||||
time: { created: m.time?.created },
|
||||
tokens: m.tokens,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the reactive store backing the sidebar widget.
|
||||
*
|
||||
* Refreshes on creation, on `session.idle`, on `server.connected`, on a
|
||||
* timer, and on demand via `refresh()`. Errors are retried with an
|
||||
* exponential backoff so a transient outage does not hammer the API.
|
||||
* Refreshes on creation, on `session.idle`, on `server.connected`, on a timer,
|
||||
* and on demand via `refresh()`. Errors are retried with an exponential
|
||||
* backoff so a transient outage does not hammer the API.
|
||||
*
|
||||
* Usage tracking (opt-out via `trackUsage: false`) keeps per-day buckets:
|
||||
* real credit spend from balance deltas, and per-model token/cost totals
|
||||
* reconciled from local OpenCode assistant messages. Buckets live in the
|
||||
* plugin durable storage and are pruned to `usageWindowDays`.
|
||||
* reconciled from local OpenCode assistant messages. Buckets are persisted in
|
||||
* 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 env Environment mapping, injectable for tests.
|
||||
* @param fetchImpl Fetch implementation, injectable for tests.
|
||||
@@ -107,8 +86,16 @@ export function createBalanceStore(
|
||||
env: CredentialEnv = process.env as CredentialEnv,
|
||||
fetchImpl: FetchLike = nativeFetch,
|
||||
): BalanceStore {
|
||||
const [state, setState] = createSignal<BalanceState>({ status: "loading" })
|
||||
const [now, setNow] = createSignal(Date.now())
|
||||
const [usagePayload, updateUsagePayload] = context.storage.store<UsagePayload>(
|
||||
USAGE_DAYS_KV,
|
||||
{ initial: { version: 1, days: [] } },
|
||||
)
|
||||
const [balance, setBalance] = context.storage.memory<BalanceState>("greenpt.balance", {
|
||||
initial: { status: "loading" },
|
||||
})
|
||||
const [clock, setClock] = context.storage.memory<{ value: number }>("greenpt.now", {
|
||||
initial: { value: Date.now() },
|
||||
})
|
||||
|
||||
const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL
|
||||
const interval = options.refreshInterval ?? DEFAULT_REFRESH_SECONDS
|
||||
@@ -116,17 +103,9 @@ export function createBalanceStore(
|
||||
const usageWindowDays = options.usageWindowDays ?? DEFAULT_USAGE_WINDOW_DAYS
|
||||
const usageBackfillLimit = options.usageBackfill ?? DEFAULT_USAGE_BACKFILL
|
||||
|
||||
let usageDays: UsageDays = {}
|
||||
let updateUsage: (mutation: (draft: UsageDays) => void) => Promise<void> = () =>
|
||||
Promise.resolve()
|
||||
if (trackUsage) {
|
||||
const stored = context.storage.store(USAGE_DAYS_KEY, { initial: {} as UsageDays })
|
||||
usageDays = stored[0]
|
||||
updateUsage = stored[1]
|
||||
}
|
||||
|
||||
let refreshTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let tickTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let persistChain: Promise<void> = Promise.resolve()
|
||||
let backoff = BACKOFF_BASE_MS
|
||||
let inFlight = false
|
||||
let disposed = false
|
||||
@@ -136,7 +115,7 @@ export function createBalanceStore(
|
||||
|
||||
const unsubscribeIdle = context.data.on("session.idle", (event) => {
|
||||
trackSession(event.data.sessionID)
|
||||
void reconcileSessions()
|
||||
reconcileSessions()
|
||||
void refresh()
|
||||
})
|
||||
const unsubscribeStatus = context.data.on("session.status", (event) => {
|
||||
@@ -144,89 +123,123 @@ export function createBalanceStore(
|
||||
})
|
||||
const unsubscribeConnected = context.data.on("server.connected", () => void refresh())
|
||||
|
||||
/**
|
||||
* Replace the balance snapshot in place so host store subscribers rerender.
|
||||
*
|
||||
* @param next Snapshot to publish.
|
||||
*/
|
||||
function replaceBalance(next: BalanceState): void {
|
||||
setBalance((draft) => {
|
||||
for (const key of Object.keys(draft)) delete (draft as Record<string, unknown>)[key]
|
||||
Object.assign(draft, next)
|
||||
})
|
||||
}
|
||||
|
||||
/** Add a session to the set reconciled for per-model usage. */
|
||||
function trackSession(sessionID: string): void {
|
||||
if (sessionID) trackedSessions.add(sessionID)
|
||||
}
|
||||
|
||||
/** Apply usage mutations through the durable storage draft. */
|
||||
function mutateUsage(mutate: (days: UsageDays) => void): Promise<void> {
|
||||
if (!trackUsage) return Promise.resolve()
|
||||
return updateUsage((draft) => {
|
||||
mutate(draft)
|
||||
pruneUsage(draft, usageWindowDays, Date.now())
|
||||
})
|
||||
/**
|
||||
* Apply usage mutations in the durable store.
|
||||
*
|
||||
* Writes are chained so concurrent refreshes cannot interleave payloads.
|
||||
*
|
||||
* @param mutate Callback mutating a fresh copy of the buckets.
|
||||
*/
|
||||
function mutateUsage(mutate: (days: UsageDays) => void): void {
|
||||
if (!trackUsage) return
|
||||
persistChain = persistChain
|
||||
.then(() =>
|
||||
updateUsagePayload((draft) => {
|
||||
const days = parseUsageDays(draft)
|
||||
mutate(days)
|
||||
pruneUsage(days, usageWindowDays, Date.now())
|
||||
const payload = serializeUsage(days) as UsagePayload
|
||||
draft.version = payload.version
|
||||
draft.days = payload.days
|
||||
}),
|
||||
)
|
||||
.catch((error) => {
|
||||
console.error(`[greenpt.usage] persist: ${error}`)
|
||||
})
|
||||
}
|
||||
|
||||
/** Current usage buckets, read reactively from the durable store. */
|
||||
function usageDays(): UsageDays {
|
||||
return parseUsageDays(usagePayload)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile per-model usage from the messages of every tracked session.
|
||||
* Idempotent: messages are de-duplicated by id in `usage.ts`.
|
||||
*/
|
||||
function reconcileSessions(): Promise<void> {
|
||||
if (!trackUsage || trackedSessions.size === 0) return Promise.resolve()
|
||||
const updates: Promise<void>[] = []
|
||||
function reconcileSessions(): void {
|
||||
if (!trackUsage || trackedSessions.size === 0) return
|
||||
for (const sessionID of trackedSessions) {
|
||||
let messages: ReadonlyArray<unknown> | undefined
|
||||
try {
|
||||
messages = context.data.session.message.list(sessionID)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const messages = context.data.session.message.list(sessionID)
|
||||
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. */
|
||||
async function backfillUsage(): Promise<void> {
|
||||
if (!trackUsage || usageBackfillLimit <= 0) return
|
||||
try {
|
||||
const listed = await context.client.session.list({
|
||||
limit: usageBackfillLimit,
|
||||
})
|
||||
for (const session of listed.data ?? []) {
|
||||
const sessions = context.data.session.list()
|
||||
const recent = [...sessions]
|
||||
.sort((a, b) => (b.time?.updated ?? 0) - (a.time?.updated ?? 0))
|
||||
.slice(0, usageBackfillLimit)
|
||||
for (const session of recent) {
|
||||
if (disposed) return
|
||||
const sessionID = (session as { id?: unknown })?.id
|
||||
if (typeof sessionID !== "string" || !sessionID) continue
|
||||
trackedSessions.add(sessionID)
|
||||
trackedSessions.add(session.id)
|
||||
try {
|
||||
const messages = await context.client.session.context({ sessionID })
|
||||
await mutateUsage((days) => applyMessages(days, toUsageMessages(messages)))
|
||||
} catch {
|
||||
// One unreadable session must not abort the whole backfill.
|
||||
await context.data.session.message.sync(session.id)
|
||||
mutateUsage((days) =>
|
||||
applyMessages(days, context.data.session.message.list(session.id)),
|
||||
)
|
||||
} catch (error) {
|
||||
console.error(`[greenpt.usage] backfill ${session.id}: ${error}`)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Backfill is optional; live tracking continues regardless.
|
||||
await persistChain
|
||||
} 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 (refreshTimer) clearTimeout(refreshTimer)
|
||||
refreshTimer = undefined
|
||||
const intervalMs = interval * 1000
|
||||
if (intervalMs <= 0) return
|
||||
const delay = state().status === "error" ? backoff : intervalMs
|
||||
const delay = balance.status === "error" ? backoff : intervalMs
|
||||
refreshTimer = setTimeout(() => {
|
||||
refreshTimer = undefined
|
||||
void refresh()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
function tick() {
|
||||
/** Advance the clock used for day/month totals. */
|
||||
function tick(): void {
|
||||
if (disposed) return
|
||||
setNow(Date.now())
|
||||
setClock((draft) => {
|
||||
draft.value = Date.now()
|
||||
})
|
||||
tickTimer = setTimeout(tick, TICK_MS)
|
||||
}
|
||||
|
||||
/** Probe the balance and reconcile usage from tracked sessions. */
|
||||
async function refresh(): Promise<void> {
|
||||
if (disposed || inFlight) return
|
||||
inFlight = true
|
||||
try {
|
||||
const credential = resolveGreenptKey(options, undefined, env)
|
||||
if (!credential.ok) {
|
||||
setState({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
|
||||
replaceBalance({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -245,34 +258,36 @@ export function createBalanceStore(
|
||||
if (trackUsage && Number.isFinite(credits)) {
|
||||
if (lastCredits !== undefined && credits < lastCredits) {
|
||||
const spent = lastCredits - credits
|
||||
await mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
|
||||
mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
|
||||
}
|
||||
lastCredits = credits
|
||||
}
|
||||
setState({ status: "ready", data: result, fetchedAt: Date.now() })
|
||||
replaceBalance({ status: "ready", data: result, fetchedAt: Date.now() })
|
||||
} else {
|
||||
backoff = Math.min(backoff * 2, BACKOFF_MAX_MS)
|
||||
setState({ status: "error", error: result })
|
||||
replaceBalance({ status: "error", error: result })
|
||||
}
|
||||
} finally {
|
||||
inFlight = false
|
||||
}
|
||||
if (disposed) return
|
||||
await reconcileSessions()
|
||||
reconcileSessions()
|
||||
await persistChain
|
||||
scheduleNext()
|
||||
}
|
||||
|
||||
/** Clear every persisted and in-memory usage bucket. */
|
||||
async function resetUsage(): Promise<void> {
|
||||
function resetUsage(): void {
|
||||
lastCredits = undefined
|
||||
await mutateUsage((days) => {
|
||||
mutateUsage((days) => {
|
||||
for (const date of Object.keys(days)) delete days[date]
|
||||
})
|
||||
}
|
||||
|
||||
tickTimer = setTimeout(tick, TICK_MS)
|
||||
|
||||
function dispose() {
|
||||
/** Stop timers, network work and event subscriptions. */
|
||||
function dispose(): void {
|
||||
disposed = true
|
||||
controller.abort()
|
||||
if (refreshTimer) clearTimeout(refreshTimer)
|
||||
@@ -284,5 +299,12 @@ export function createBalanceStore(
|
||||
|
||||
void backfillUsage()
|
||||
|
||||
return { state, now, usageDays, refresh, resetUsage, dispose }
|
||||
return {
|
||||
state: () => balance as BalanceState,
|
||||
now: () => clock.value,
|
||||
usageDays,
|
||||
refresh,
|
||||
resetUsage,
|
||||
dispose,
|
||||
}
|
||||
}
|
||||
|
||||
16
src/usage.ts
16
src/usage.ts
@@ -47,12 +47,14 @@ export type UsageTotals = {
|
||||
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 = {
|
||||
id?: unknown
|
||||
role?: unknown
|
||||
providerID?: unknown
|
||||
modelID?: unknown
|
||||
type?: unknown
|
||||
model?: {
|
||||
providerID?: unknown
|
||||
id?: unknown
|
||||
}
|
||||
cost?: unknown
|
||||
time?: { created?: unknown }
|
||||
tokens?: {
|
||||
@@ -108,7 +110,7 @@ export function emptyDay(date: string): DayUsage {
|
||||
export function isUsageMessage(value: unknown): value is UsageMessage {
|
||||
if (typeof value !== "object" || value === null) return false
|
||||
const message = value as UsageMessage
|
||||
return message.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.
|
||||
*/
|
||||
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
|
||||
|
||||
const created = message.time?.created
|
||||
@@ -128,7 +130,7 @@ export function recordMessage(days: UsageDays, message: UsageMessage): boolean {
|
||||
const cost = num(message.cost)
|
||||
if (totalTokens(tokens) === 0 && cost === 0) return false
|
||||
|
||||
const model = typeof message.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 day = days[date] ?? emptyDay(date)
|
||||
if (day.ids.includes(message.id as string)) return false
|
||||
|
||||
152
src/widget.tsx
152
src/widget.tsx
@@ -1,15 +1,27 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { createSignal, For, Match, Show, Switch } from "solid-js"
|
||||
import type { ResolvedTheme } from "@opencode/theme/tui"
|
||||
import {
|
||||
formatBalanceError,
|
||||
formatCredits,
|
||||
formatTokens,
|
||||
DEFAULT_UNIT,
|
||||
} from "./format"
|
||||
import { For, Match, Show, Switch } from "solid-js"
|
||||
import type { Context } from "@opencode/plugin/tui/context"
|
||||
import { BALANCE_OPEN_KV, formatBalanceError, formatCredits, formatTokens, DEFAULT_UNIT } from "./format"
|
||||
import { dayTotals, monthTotals, type ModelTotal } from "./usage"
|
||||
import type { BalanceStore } from "./store"
|
||||
|
||||
/** Maximum characters before a model name is ellipsized in the table. */
|
||||
const MODEL_NAME_MAX = 28
|
||||
|
||||
/** Number of model rows shown before the "other models" summary. */
|
||||
const MODEL_ROWS_VISIBLE = 3
|
||||
|
||||
/**
|
||||
* Shorten a model id for a narrow sidebar column.
|
||||
*
|
||||
* @param model Model id reported by OpenCode.
|
||||
* @returns The id unchanged when short enough, otherwise an ellipsized form.
|
||||
*/
|
||||
function shortModel(model: string): string {
|
||||
if (model.length <= MODEL_NAME_MAX) return model
|
||||
return `${model.slice(0, MODEL_NAME_MAX - 1)}…`
|
||||
}
|
||||
|
||||
/**
|
||||
* Sidebar section showing the remaining GreenPT credit balance and the
|
||||
* consumption of the API key: real credit spend per day/month plus a
|
||||
@@ -20,19 +32,25 @@ import type { BalanceStore } from "./store"
|
||||
* GreenPT never sees an empty or misleading block.
|
||||
*/
|
||||
export function GreenptWidget(props: {
|
||||
context: Context
|
||||
store: BalanceStore
|
||||
theme: ResolvedTheme
|
||||
open: () => boolean
|
||||
toggleOpen: () => void
|
||||
showWhenUnavailable: boolean
|
||||
unit?: string
|
||||
}) {
|
||||
const theme = () => props.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 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 s = state()
|
||||
@@ -52,8 +70,7 @@ export function GreenptWidget(props: {
|
||||
}
|
||||
const balanceColor = () => {
|
||||
const s = state()
|
||||
const kind = s.status === "ready" && s.data.credits > 0 ? "success" : "error"
|
||||
return theme().text.feedback[kind].base
|
||||
return s.status === "ready" && s.data.credits > 0 ? "success" : "error"
|
||||
}
|
||||
const updatedAt = () => {
|
||||
const s = state()
|
||||
@@ -61,74 +78,89 @@ export function GreenptWidget(props: {
|
||||
const d = new Date(s.fetchedAt)
|
||||
const hh = String(d.getHours()).padStart(2, "0")
|
||||
const mm = String(d.getMinutes()).padStart(2, "0")
|
||||
return `updated ${hh}:${mm}`
|
||||
return `${hh}:${mm}`
|
||||
}
|
||||
|
||||
const usage = () => props.store.usageDays
|
||||
const usage = () => props.store.usageDays()
|
||||
const todayUsage = () => dayTotals(usage(), props.store.now())
|
||||
const monthUsage = () => monthTotals(usage(), props.store.now())
|
||||
const usageVisible = () => todayUsage().creditsSpent > 0 || monthUsage().cost > 0
|
||||
const todayText = () => `${formatCredits(todayUsage().creditsSpent)} ${unit()}`
|
||||
const monthText = () => `${formatCredits(monthUsage().cost)} ${unit()}`
|
||||
const foldedSuffix = () => (usageVisible() ? ` · today ${todayText()}` : "")
|
||||
const modelRows = (): ModelTotal[] => monthUsage().byModel.slice(0, 5)
|
||||
const modelRows = (): ModelTotal[] => monthUsage().byModel.slice(0, MODEL_ROWS_VISIBLE)
|
||||
const otherModels = () => Math.max(0, monthUsage().byModel.length - MODEL_ROWS_VISIBLE)
|
||||
|
||||
return (
|
||||
<Show when={!hidden()} fallback={<box />}>
|
||||
<box flexDirection="column" gap={1}>
|
||||
<text fg={theme().text.base} onMouseUp={toggle}>
|
||||
<span style={{ fg: theme().text.muted }}>{open() ? "▼ " : "▶ "}</span>
|
||||
<b>GreenPT</b>
|
||||
<Show when={!open() && balanceText()}>
|
||||
{(text) => (
|
||||
<span style={{ fg: balanceColor() }}>
|
||||
{" "}
|
||||
{text()}
|
||||
{foldedSuffix()}
|
||||
</span>
|
||||
)}
|
||||
</Show>
|
||||
</text>
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row" justifyContent="space-between" gap={1}>
|
||||
<text fg={theme().text.base} onMouseUp={toggle}>
|
||||
<span style={{ fg: theme().text.muted }}>{open() ? "▼ " : "▶ "}</span>
|
||||
<b>GreenPT</b>
|
||||
</text>
|
||||
<box flexDirection="row" gap={1} justifyContent="flex-end">
|
||||
<Show when={balanceText()}>
|
||||
{(text) => (
|
||||
<text fg={theme().text.feedback[balanceColor()].base}>
|
||||
<b>{text()}</b>
|
||||
</text>
|
||||
)}
|
||||
</Show>
|
||||
<Show when={!open() && usageVisible()}>
|
||||
<text fg={theme().text.muted}>· today {todayText()}</text>
|
||||
</Show>
|
||||
</box>
|
||||
</box>
|
||||
|
||||
<Show when={open()}>
|
||||
<Switch>
|
||||
<Match when={status() === "ready"}>
|
||||
<box flexDirection="row" gap={1} justifyContent="space-between">
|
||||
<text fg={theme().text.muted}>Balance</text>
|
||||
<box flexDirection="row" gap={1}>
|
||||
<text fg={balanceColor()}>{balanceText()}</text>
|
||||
<text fg={theme().text.muted}>{updatedAt()}</text>
|
||||
</box>
|
||||
<box paddingLeft={2}>
|
||||
<text fg={theme().text.muted}>
|
||||
today {todayText()} · month {monthText()} · {updatedAt()}
|
||||
</text>
|
||||
</box>
|
||||
</Match>
|
||||
<Match when={status() === "loading"}>
|
||||
<text fg={theme().text.muted}>loading…</text>
|
||||
<box paddingLeft={2}>
|
||||
<text fg={theme().text.muted}>loading…</text>
|
||||
</box>
|
||||
</Match>
|
||||
<Match when={credentialReason() !== undefined && props.showWhenUnavailable}>
|
||||
<CredentialHint reason={credentialReason()!} theme={theme()} />
|
||||
<box paddingLeft={2}>
|
||||
<CredentialHint reason={credentialReason()!} theme={theme()} />
|
||||
</box>
|
||||
</Match>
|
||||
<Match when={status() === "error"}>
|
||||
<text fg={theme().text.muted}>{formatBalanceError(error()!)}</text>
|
||||
<box paddingLeft={2}>
|
||||
<text fg={theme().text.muted}>{formatBalanceError(error()!)}</text>
|
||||
</box>
|
||||
</Match>
|
||||
</Switch>
|
||||
|
||||
<Show when={usageVisible()}>
|
||||
<box flexDirection="row" gap={1} justifyContent="space-between">
|
||||
<text fg={theme().text.muted}>Spent</text>
|
||||
<box flexDirection="row" gap={1}>
|
||||
<text fg={theme().text.base}>today {todayText()}</text>
|
||||
<text fg={theme().text.muted}>month {monthText()}</text>
|
||||
</box>
|
||||
</box>
|
||||
<For each={modelRows()}>
|
||||
{(row) => (
|
||||
<box flexDirection="row" gap={1} justifyContent="space-between">
|
||||
<text fg={theme().text.muted}>{row.model}</text>
|
||||
<box flexDirection="row" gap={1}>
|
||||
<text fg={theme().text.muted}>{formatTokens(row.usage.tokens.input + row.usage.tokens.output)} tok</text>
|
||||
<text fg={theme().text.base}>~{formatCredits(row.usage.cost)} {unit()}</text>
|
||||
<box flexDirection="column" marginTop={1}>
|
||||
<For each={modelRows()}>
|
||||
{(row) => (
|
||||
<box flexDirection="column" paddingLeft={2}>
|
||||
<text fg={theme().text.muted}>{shortModel(row.model)}</text>
|
||||
<box flexDirection="row" justifyContent="space-between" paddingLeft={2}>
|
||||
<text fg={theme().text.muted}>
|
||||
{formatTokens(row.usage.tokens.input + row.usage.tokens.output)} tok
|
||||
</text>
|
||||
<text fg={theme().text.base}>
|
||||
~{formatCredits(row.usage.cost)} {unit()}
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
)}
|
||||
</For>
|
||||
<Show when={otherModels() > 0}>
|
||||
<box paddingLeft={2}>
|
||||
<text fg={theme().text.muted}>+ {otherModels()} more models</text>
|
||||
</box>
|
||||
)}
|
||||
</For>
|
||||
</Show>
|
||||
</box>
|
||||
</Show>
|
||||
</Show>
|
||||
</box>
|
||||
@@ -140,7 +172,7 @@ export function GreenptWidget(props: {
|
||||
* Hint shown when the credential is missing and the section is explicitly
|
||||
* kept visible.
|
||||
*/
|
||||
function CredentialHint(props: { reason: "missing"; theme: ResolvedTheme }) {
|
||||
function CredentialHint(props: { reason: "missing"; theme: Context["theme"] }) {
|
||||
return (
|
||||
<text fg={props.theme.text.muted}>
|
||||
{props.reason === "missing" ? "no GreenPT key (/connect)" : "no GreenPT key"}
|
||||
|
||||
@@ -49,4 +49,3 @@ describe("formatBalanceError", () => {
|
||||
expect(formatBalanceError({ kind: "no-credential", reason: "missing" })).toContain("GreenPT")
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -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 { 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 DAY = "2026-10-19"
|
||||
const DAY = dayKey(NOW)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(NOW)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
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(storage = new Map<string, object>()) {
|
||||
const storageData = storage
|
||||
function makeContext() {
|
||||
const payload: UsagePayload = { version: 1, days: [] }
|
||||
const fold = { open: true }
|
||||
const messages = new Map<string, FakeMessage[]>()
|
||||
const sessions: Array<{ id: string; time: { updated: number } }> = []
|
||||
const handlers = new Map<string, Array<(event: unknown) => void>>()
|
||||
|
||||
const memory = new Map<string, unknown>()
|
||||
const context = {
|
||||
storage: {
|
||||
store: (key: string, options: { initial: unknown }) => {
|
||||
const target =
|
||||
key === "greenpt.usage.days"
|
||||
? payload
|
||||
: key === "greenpt.usage.open"
|
||||
? fold
|
||||
: options.initial
|
||||
return [
|
||||
target,
|
||||
async (mutation: (draft: unknown) => void) => {
|
||||
mutation(target)
|
||||
},
|
||||
] as const
|
||||
},
|
||||
memory: (key: string, options: { initial: unknown }) => {
|
||||
if (!memory.has(key)) memory.set(key, options.initial)
|
||||
const target = memory.get(key)
|
||||
return [
|
||||
target,
|
||||
(mutation: (draft: unknown) => void) => {
|
||||
mutation(target)
|
||||
},
|
||||
] as const
|
||||
},
|
||||
},
|
||||
data: {
|
||||
on: (type: string, handler: (event: unknown) => void) => {
|
||||
const list = handlers.get(type) ?? []
|
||||
@@ -27,34 +66,18 @@ function makeContext(storage = new Map<string, object>()) {
|
||||
}
|
||||
},
|
||||
session: {
|
||||
list: () => sessions,
|
||||
message: {
|
||||
list: (sessionID: string) => messages.get(sessionID) ?? [],
|
||||
sync: async () => {},
|
||||
},
|
||||
},
|
||||
},
|
||||
client: {
|
||||
session: {
|
||||
list: async () => ({ data: [] }),
|
||||
context: async () => [],
|
||||
},
|
||||
},
|
||||
storage: {
|
||||
store: (key: string, { initial }: { initial: object }) => {
|
||||
if (!storageData.has(key)) storageData.set(key, initial)
|
||||
const value = storageData.get(key)!
|
||||
return [
|
||||
value,
|
||||
async (mutate: (draft: object) => void) => {
|
||||
mutate(value)
|
||||
},
|
||||
] as const
|
||||
},
|
||||
},
|
||||
emit(type: string, event: unknown) {
|
||||
for (const handler of handlers.get(type) ?? []) handler(event)
|
||||
},
|
||||
}
|
||||
return { context, storageData, messages }
|
||||
return { context, payload, fold, messages, sessions }
|
||||
}
|
||||
|
||||
function balanceResponse(credits: number) {
|
||||
@@ -71,7 +94,12 @@ function fetchSequence(credits: number[]) {
|
||||
}
|
||||
|
||||
function createTrackedStore(context: unknown, options: BalanceOptions = {}) {
|
||||
return createBalanceStore(context as never, { apiKey: "test-key", ...options }, {}, fetchSequence([10]))
|
||||
return createBalanceStore(
|
||||
context as never,
|
||||
{ apiKey: "test-key", ...options },
|
||||
{},
|
||||
fetchSequence([10]),
|
||||
)
|
||||
}
|
||||
|
||||
describe("usage tracking in the balance store", () => {
|
||||
@@ -87,7 +115,7 @@ describe("usage tracking in the balance store", () => {
|
||||
await store.refresh()
|
||||
await store.refresh()
|
||||
await store.refresh()
|
||||
expect(store.usageDays[DAY]?.creditsSpent).toBeCloseTo(0.1)
|
||||
expect(store.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.1)
|
||||
store.dispose()
|
||||
})
|
||||
|
||||
@@ -96,8 +124,8 @@ describe("usage tracking in the balance store", () => {
|
||||
const store = createTrackedStore(context)
|
||||
messages.set("s1", [
|
||||
{
|
||||
type: "assistant",
|
||||
id: "m1",
|
||||
type: "assistant",
|
||||
model: { providerID: "greenpt", id: "glm-5.3-flash" },
|
||||
cost: 0.02,
|
||||
time: { created: NOW },
|
||||
@@ -107,12 +135,12 @@ describe("usage tracking in the balance store", () => {
|
||||
context.emit("session.idle", { data: { sessionID: "s1" } })
|
||||
await store.refresh()
|
||||
await store.refresh()
|
||||
expect(store.usageDays[DAY]?.byModel["glm-5.3-flash"]?.cost).toBeCloseTo(0.02)
|
||||
expect(store.usageDays()[DAY]?.byModel["glm-5.3-flash"]?.cost).toBeCloseTo(0.02)
|
||||
store.dispose()
|
||||
})
|
||||
|
||||
it("persists buckets to durable storage and reloads them", async () => {
|
||||
const { context, storageData } = makeContext()
|
||||
it("persists buckets to the durable store and reloads them", async () => {
|
||||
const { context, payload } = makeContext()
|
||||
const first = createBalanceStore(
|
||||
context as never,
|
||||
{ apiKey: "test-key" },
|
||||
@@ -121,20 +149,12 @@ describe("usage tracking in the balance store", () => {
|
||||
)
|
||||
await first.refresh()
|
||||
await first.refresh()
|
||||
expect(storageData.has("greenpt.usage.days")).toBe(true)
|
||||
expect(payload.days.length).toBeGreaterThan(0)
|
||||
first.dispose()
|
||||
|
||||
const stored: UsageDays = { [DAY]: { date: DAY, creditsSpent: 0.5, byModel: {}, ids: [] } }
|
||||
storageData.set("greenpt.usage.days", stored)
|
||||
const { context: secondContext } = makeContext(storageData)
|
||||
const secondStore = createBalanceStore(
|
||||
secondContext as never,
|
||||
{ apiKey: "test-key" },
|
||||
{},
|
||||
fetchSequence([10]),
|
||||
)
|
||||
expect(secondStore.usageDays[DAY]?.creditsSpent).toBeCloseTo(0.5)
|
||||
secondStore.dispose()
|
||||
const second = createTrackedStore(context)
|
||||
expect(second.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.1)
|
||||
second.dispose()
|
||||
})
|
||||
|
||||
it("resetUsage clears buckets", async () => {
|
||||
@@ -142,13 +162,14 @@ describe("usage tracking in the balance store", () => {
|
||||
const store = createTrackedStore(context)
|
||||
await store.refresh()
|
||||
await store.refresh()
|
||||
await store.resetUsage()
|
||||
expect(Object.keys(store.usageDays).length).toBe(0)
|
||||
store.resetUsage()
|
||||
await store.refresh()
|
||||
expect(Object.keys(store.usageDays()).length).toBe(0)
|
||||
store.dispose()
|
||||
})
|
||||
|
||||
it("skips tracking when disabled", async () => {
|
||||
const { context, storageData } = makeContext()
|
||||
const { context, payload } = makeContext()
|
||||
const store = createBalanceStore(
|
||||
context as never,
|
||||
{ apiKey: "test-key", trackUsage: false },
|
||||
@@ -157,8 +178,8 @@ describe("usage tracking in the balance store", () => {
|
||||
)
|
||||
await store.refresh()
|
||||
await store.refresh()
|
||||
expect(Object.keys(store.usageDays).length).toBe(0)
|
||||
expect(storageData.has("greenpt.usage.days")).toBe(false)
|
||||
expect(Object.keys(store.usageDays()).length).toBe(0)
|
||||
expect(payload.days.length).toBe(0)
|
||||
store.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -17,9 +17,8 @@ const NOW = new Date(2026, 9, 19, 15, 30, 0).getTime()
|
||||
function assistantMessage(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "msg-1",
|
||||
role: "assistant",
|
||||
providerID: "greenpt",
|
||||
modelID: "glm-5.3-flash",
|
||||
type: "assistant",
|
||||
model: { providerID: "greenpt", id: "glm-5.3-flash" },
|
||||
cost: 0.01,
|
||||
time: { created: NOW },
|
||||
tokens: { input: 100, output: 50, reasoning: 10, cache: { read: 5, write: 2 } },
|
||||
@@ -53,7 +52,12 @@ describe("recordMessage", () => {
|
||||
|
||||
it("ignores non-GreenPT providers", () => {
|
||||
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)
|
||||
})
|
||||
|
||||
@@ -78,7 +82,7 @@ describe("applyMessages", () => {
|
||||
it("skips user messages and unknown shapes", () => {
|
||||
const days: UsageDays = {}
|
||||
applyMessages(days, [
|
||||
{ id: "u1", role: "user" },
|
||||
{ id: "u1", type: "user" },
|
||||
assistantMessage(),
|
||||
null,
|
||||
undefined,
|
||||
@@ -104,7 +108,7 @@ describe("totals", () => {
|
||||
recordMessage(days, assistantMessage())
|
||||
recordMessage(
|
||||
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)
|
||||
expect(day.byModel.map((row) => row.model)).toEqual(["kimi-k2", "glm-5.3-flash"])
|
||||
|
||||
Reference in New Issue
Block a user