Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5129f295da |
20
AGENTS.md
20
AGENTS.md
@@ -2,9 +2,10 @@
|
|||||||
|
|
||||||
## Project
|
## Project
|
||||||
|
|
||||||
`opencode-greenpt-usage` — an OpenCode **TUI** plugin (Solid + OpenTUI) that
|
`opencode-greenpt-usage` — an OpenCode **v2** CLI/TUI plugin (Solid + OpenTUI)
|
||||||
shows the remaining GreenPT API credit balance in the sidebar. Distributed by
|
that shows the remaining GreenPT API credit balance in the sidebar.
|
||||||
`git clone`; there is no npm publish.
|
Distributed by `git clone`; there is no npm publish. The `main` branch
|
||||||
|
targets OpenCode 1.x; this branch targets OpenCode `>= 2.0.0`.
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
@@ -17,17 +18,20 @@ 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 has two entries: `src/index.ts` (server side, minimal
|
||||||
Types come from `@opencode-ai/plugin/tui` as **type-only** imports; the
|
`Plugin.define`) and `src/tui.tsx` (CLI plugin, exposed as `./tui`).
|
||||||
host provides `solid-js` and `@opentui/solid` at runtime.
|
Types come from `@opencode/plugin` and `@opencode/plugin/tui`; the host
|
||||||
- The section is registered on the `sidebar_content` slot and is hidden when
|
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).
|
no GreenPT credential is present (`showWhenUnavailable` opts into a hint).
|
||||||
|
- Commands are registered through `context.keymap.layer` (palette).
|
||||||
- Balance probing must stay **free**: `HEAD /v1/chat/completions` returns
|
- 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, idempotent by message id, persisted in the plugin durable
|
||||||
|
storage (`context.storage.store`).
|
||||||
- Credential resolution order: `apiKey` option, `GREENPT_API_KEY`, active
|
- Credential resolution order: `apiKey` option, `GREENPT_API_KEY`, active
|
||||||
OpenCode `auth.json` (`greenpt`, `type: "api"`). No profile-switching
|
OpenCode `auth.json` (`greenpt`, `type: "api"`). No profile-switching
|
||||||
command may leak into this logic.
|
command may leak into this logic.
|
||||||
|
|||||||
31
README.md
31
README.md
@@ -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 durable
|
||||||
store (90 days by default):
|
storage (90 days by default):
|
||||||
- *real credit spend* is observed as the drop of `x-credits-remaining`
|
- *real credit spend* is observed as the drop of `x-credits-remaining`
|
||||||
between two balance probes — this covers **every client** of the API
|
between two balance probes — this covers **every client** of the API
|
||||||
key, not just OpenCode, but has no per-model detail;
|
key, not just OpenCode, but has no per-model detail;
|
||||||
@@ -47,7 +47,8 @@ looks for a key.
|
|||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- OpenCode `>= 1.18.0` (TUI plugin system).
|
- OpenCode `>= 2.0.0` (v2 CLI/TUI plugin system; for OpenCode 1.x use the
|
||||||
|
`main` branch).
|
||||||
- A GreenPT account and API key.
|
- A GreenPT account and API key.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
@@ -64,35 +65,37 @@ 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`, setting the
|
||||||
**absolute path to your clone**:
|
**absolute path to your clone**:
|
||||||
|
|
||||||
```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": { "showWhenUnavailable": false }
|
||||||
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
> Use a `file://` URL pointing at the source file `src/index.tsx`
|
> Point at the repository root, not at a source file: OpenCode v2 loads
|
||||||
> (OpenCode compiles the TSX itself). Do not point at a bundle: that
|
> the `./tui` entry (`src/tui.tsx`) from the package `exports` and
|
||||||
> would embed a second copy of `solid-js` and the section would stay
|
> resolves `@opencode/plugin` at runtime.
|
||||||
> blank.
|
|
||||||
|
|
||||||
4. **Fully quit OpenCode and relaunch it** (plugins are not hot-reloaded).
|
4. **Fully quit OpenCode and relaunch it** (plugins are not hot-reloaded).
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
All options are optional and go in the plugin entry of `tui.json`:
|
All options are optional and go in the `options` object of the plugin entry
|
||||||
|
in `cli.json`:
|
||||||
|
|
||||||
| Option | Type | Default | Description |
|
| 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. |
|
|
||||||
| `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,7 @@ All options are optional and go in the plugin entry of `tui.json`:
|
|||||||
|
|
||||||
- **The section does not appear**: make sure `opencode auth login` stored a
|
- **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.
|
path in `cli.json` points at the repository root.
|
||||||
- **"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.
|
||||||
|
|||||||
4768
package-lock.json
generated
4768
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",
|
"name": "opencode-greenpt-usage",
|
||||||
"version": "0.1.0",
|
"version": "0.2.0",
|
||||||
"description": "OpenCode TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
|
"description": "OpenCode v2 TUI plugin that shows the remaining GreenPT API credit balance in the sidebar.",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"license": "AGPL-3.0-or-later",
|
"license": "AGPL-3.0-or-later",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
@@ -13,21 +13,28 @@
|
|||||||
"balance"
|
"balance"
|
||||||
],
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"opencode": ">=1.18.0"
|
"opencode": ">=2.0.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:integration": "GREENPT_INTEGRATION=1 vitest run test/integration.greenpt.test.ts",
|
"test:integration": "GREENPT_INTEGRATION=1 vitest run test/integration.greenpt.test.ts",
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
|
"exports": {
|
||||||
|
".": "./src/index.ts",
|
||||||
|
"./tui": "./src/tui.tsx"
|
||||||
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@opencode-ai/plugin": "*",
|
"@opencode/plugin": ">=2.0.0 <3",
|
||||||
"@opentui/solid": "*",
|
"@opentui/core": ">=0.5.17",
|
||||||
"solid-js": "*"
|
"@opentui/solid": ">=0.5.17",
|
||||||
|
"solid-js": ">=1.9.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@opencode-ai/plugin": "^1.18.33",
|
"@opencode/plugin": "^2.0.32",
|
||||||
"@opentui/solid": "^0.5.12",
|
"@opencode/theme": "^2.0.32",
|
||||||
|
"@opentui/core": "^0.5.17",
|
||||||
|
"@opentui/solid": "^0.5.17",
|
||||||
"@types/node": "^24.0.0",
|
"@types/node": "^24.0.0",
|
||||||
"solid-js": "^1.9.0",
|
"solid-js": "^1.9.0",
|
||||||
"typescript": "^5.6.0",
|
"typescript": "^5.6.0",
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
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 plugin storage. */
|
||||||
export const BALANCE_OPEN_KV = "greenpt.usage.open"
|
export const FOLD_STORAGE_KEY = "greenpt.usage.open"
|
||||||
|
|
||||||
/** Key used to persist the usage day buckets in the shared KV store. */
|
|
||||||
export const USAGE_DAYS_KV = "greenpt.usage.days"
|
|
||||||
|
|
||||||
/** Default unit appended to the balance (GreenPT credits are euro-denominated). */
|
/** Default unit appended to the balance (GreenPT credits are euro-denominated). */
|
||||||
export const DEFAULT_UNIT = "€"
|
export const DEFAULT_UNIT = "€"
|
||||||
@@ -57,24 +54,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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
6
src/index.ts
Normal file
6
src/index.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { Plugin } from "@opencode/plugin"
|
||||||
|
|
||||||
|
export default Plugin.define({
|
||||||
|
id: "greenpt.usage",
|
||||||
|
setup() {},
|
||||||
|
})
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
/** @jsxImportSource @opentui/solid */
|
|
||||||
import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
|
|
||||||
import { createBalanceStore, type BalanceOptions } from "./store"
|
|
||||||
import { GreenptWidget } from "./widget"
|
|
||||||
|
|
||||||
/** Sidebar slot order; the OpenCode Go widget uses 600. */
|
|
||||||
const DEFAULT_ORDER = 700
|
|
||||||
|
|
||||||
const tui: TuiPlugin = async (api, options) => {
|
|
||||||
const opts = (options ?? {}) as BalanceOptions
|
|
||||||
const store = createBalanceStore(api, opts)
|
|
||||||
|
|
||||||
api.slots.register({
|
|
||||||
order:
|
|
||||||
typeof opts.order === "number" && Number.isFinite(opts.order) ? opts.order : DEFAULT_ORDER,
|
|
||||||
slots: {
|
|
||||||
sidebar_content() {
|
|
||||||
return (
|
|
||||||
<GreenptWidget
|
|
||||||
api={api}
|
|
||||||
store={store}
|
|
||||||
showWhenUnavailable={opts.showWhenUnavailable === true}
|
|
||||||
unit={opts.unit}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
api.command?.register(() => [
|
|
||||||
{
|
|
||||||
value: "greenpt.refresh",
|
|
||||||
title: "Refresh GreenPT balance",
|
|
||||||
category: "Plugin",
|
|
||||||
onSelect() {
|
|
||||||
void store.refresh()
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
value: "greenpt.usage.reset",
|
|
||||||
title: "Reset GreenPT usage counters",
|
|
||||||
category: "Plugin",
|
|
||||||
onSelect() {
|
|
||||||
store.resetUsage()
|
|
||||||
},
|
|
||||||
},
|
|
||||||
])
|
|
||||||
|
|
||||||
api.lifecycle.onDispose(() => store.dispose())
|
|
||||||
|
|
||||||
void store.refresh()
|
|
||||||
}
|
|
||||||
|
|
||||||
const plugin: TuiPluginModule & { id: string } = {
|
|
||||||
id: "greenpt.usage",
|
|
||||||
tui,
|
|
||||||
}
|
|
||||||
|
|
||||||
export default plugin
|
|
||||||
168
src/store.ts
168
src/store.ts
@@ -1,14 +1,11 @@
|
|||||||
import { createSignal } from "solid-js"
|
import { createSignal } from "solid-js"
|
||||||
import type { TuiPluginApi } from "@opencode-ai/plugin/tui"
|
import type { Context } from "@opencode/plugin/tui/plugin"
|
||||||
import { fetchBalance, nativeFetch, type Balance, type BalanceError, type FetchLike } from "./balance"
|
import { fetchBalance, nativeFetch, type Balance, type BalanceError, type FetchLike } from "./balance"
|
||||||
import { USAGE_DAYS_KV } from "./format"
|
|
||||||
import { resolveGreenptKey, type CredentialEnv } from "./credential"
|
import { resolveGreenptKey, type CredentialEnv } from "./credential"
|
||||||
import {
|
import {
|
||||||
addCreditsSpent,
|
addCreditsSpent,
|
||||||
applyMessages,
|
applyMessages,
|
||||||
parseUsageDays,
|
|
||||||
pruneUsage,
|
pruneUsage,
|
||||||
serializeUsage,
|
|
||||||
type UsageDays,
|
type UsageDays,
|
||||||
type UsageMessage,
|
type UsageMessage,
|
||||||
} from "./usage"
|
} from "./usage"
|
||||||
@@ -16,6 +13,9 @@ import {
|
|||||||
/** Default GreenPT API base URL. */
|
/** Default GreenPT API base URL. */
|
||||||
export const DEFAULT_BASE_URL = "https://api.greenpt.ai/v1"
|
export const DEFAULT_BASE_URL = "https://api.greenpt.ai/v1"
|
||||||
|
|
||||||
|
/** Storage key for the usage day buckets (durable plugin storage). */
|
||||||
|
export const USAGE_DAYS_KEY = "greenpt.usage.days"
|
||||||
|
|
||||||
/** Default refresh interval, in seconds. The probe is free but should stay gentle. */
|
/** Default refresh interval, in seconds. The probe is free but should stay gentle. */
|
||||||
export const DEFAULT_REFRESH_SECONDS = 300
|
export const DEFAULT_REFRESH_SECONDS = 300
|
||||||
|
|
||||||
@@ -29,7 +29,6 @@ export type BalanceOptions = {
|
|||||||
apiKey?: string
|
apiKey?: string
|
||||||
baseUrl?: string
|
baseUrl?: string
|
||||||
refreshInterval?: number
|
refreshInterval?: number
|
||||||
order?: number
|
|
||||||
showWhenUnavailable?: boolean
|
showWhenUnavailable?: boolean
|
||||||
unit?: string
|
unit?: string
|
||||||
trackUsage?: boolean
|
trackUsage?: boolean
|
||||||
@@ -48,17 +47,42 @@ export type BalanceState =
|
|||||||
export type BalanceStore = {
|
export type BalanceStore = {
|
||||||
state: () => BalanceState
|
state: () => BalanceState
|
||||||
now: () => number
|
now: () => number
|
||||||
usageDays: () => UsageDays
|
usageDays: UsageDays
|
||||||
refresh: () => Promise<void>
|
refresh: () => Promise<void>
|
||||||
resetUsage: () => void
|
resetUsage: () => Promise<void>
|
||||||
dispose: () => void
|
dispose: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
|
/** Structural view of a v2 assistant message used for accounting. */
|
||||||
|
function toUsageMessages(messages: ReadonlyArray<unknown>): ReadonlyArray<UsageMessage> {
|
||||||
|
const out: UsageMessage[] = []
|
||||||
|
for (const message of messages) {
|
||||||
|
const m = message as {
|
||||||
|
type?: unknown
|
||||||
|
id?: unknown
|
||||||
|
model?: { providerID?: unknown; id?: unknown }
|
||||||
|
cost?: unknown
|
||||||
|
time?: { created?: unknown }
|
||||||
|
tokens?: UsageMessage["tokens"]
|
||||||
|
}
|
||||||
|
if (m?.type !== "assistant" || typeof m.id !== "string") continue
|
||||||
|
out.push({
|
||||||
|
id: m.id,
|
||||||
|
role: "assistant",
|
||||||
|
providerID: m.model?.providerID,
|
||||||
|
modelID: m.model?.id,
|
||||||
|
cost: m.cost,
|
||||||
|
time: { created: m.time?.created },
|
||||||
|
tokens: m.tokens,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create the reactive store backing the sidebar widget.
|
* Create the reactive store backing the sidebar widget.
|
||||||
*
|
*
|
||||||
@@ -68,25 +92,23 @@ const TICK_MS = 30_000
|
|||||||
*
|
*
|
||||||
* 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 live in the
|
||||||
* in the plugin KV store and pruned to `usageWindowDays`.
|
* plugin durable storage and are pruned to `usageWindowDays`.
|
||||||
*
|
*
|
||||||
* @param api TUI plugin API (used for the auth store path, events, KV and
|
* @param context OpenCode v2 TUI plugin context.
|
||||||
* 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 [state, setState] = createSignal<BalanceState>({ status: "loading" })
|
||||||
const [now, setNow] = createSignal(Date.now())
|
const [now, setNow] = createSignal(Date.now())
|
||||||
const [usageDays, setUsageDays] = createSignal<UsageDays>(readUsageDays(api.kv))
|
|
||||||
|
|
||||||
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
|
||||||
@@ -94,107 +116,82 @@ export function createBalanceStore(
|
|||||||
const usageWindowDays = options.usageWindowDays ?? DEFAULT_USAGE_WINDOW_DAYS
|
const usageWindowDays = options.usageWindowDays ?? DEFAULT_USAGE_WINDOW_DAYS
|
||||||
const usageBackfillLimit = options.usageBackfill ?? DEFAULT_USAGE_BACKFILL
|
const usageBackfillLimit = options.usageBackfill ?? DEFAULT_USAGE_BACKFILL
|
||||||
|
|
||||||
|
let usageDays: UsageDays = {}
|
||||||
|
let updateUsage: (mutation: (draft: UsageDays) => void) => Promise<void> = () =>
|
||||||
|
Promise.resolve()
|
||||||
|
if (trackUsage) {
|
||||||
|
const stored = context.storage.store(USAGE_DAYS_KEY, { initial: {} as UsageDays })
|
||||||
|
usageDays = stored[0]
|
||||||
|
updateUsage = stored[1]
|
||||||
|
}
|
||||||
|
|
||||||
let refreshTimer: ReturnType<typeof setTimeout> | undefined
|
let refreshTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
let tickTimer: ReturnType<typeof setTimeout> | undefined
|
let tickTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
let stateRetryTimer: ReturnType<typeof setTimeout> | undefined
|
|
||||||
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()
|
void 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 {
|
|
||||||
const raw = kv.get(USAGE_DAYS_KV)
|
|
||||||
if (raw === undefined) return {}
|
|
||||||
return parseUsageDays(raw)
|
|
||||||
} catch {
|
|
||||||
return {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeUsageDays(kv: TuiPluginApi["kv"], days: UsageDays): void {
|
|
||||||
try {
|
|
||||||
kv.set(USAGE_DAYS_KV, serializeUsage(days))
|
|
||||||
} catch {
|
|
||||||
// KV persistence is optional; in-memory buckets remain usable.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 through the durable storage draft. */
|
||||||
function mutateUsage(mutate: (days: UsageDays) => void): void {
|
function mutateUsage(mutate: (days: UsageDays) => void): Promise<void> {
|
||||||
if (!trackUsage) return
|
if (!trackUsage) return Promise.resolve()
|
||||||
const days: UsageDays = { ...usageDays() }
|
return updateUsage((draft) => {
|
||||||
mutate(days)
|
mutate(draft)
|
||||||
pruneUsage(days, usageWindowDays, Date.now())
|
pruneUsage(draft, usageWindowDays, Date.now())
|
||||||
setUsageDays(days)
|
})
|
||||||
writeUsageDays(api.kv, days)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reconcile per-model usage from the messages of every tracked session.
|
* Reconcile per-model usage from the messages of every tracked session.
|
||||||
* Idempotent: messages are de-duplicated by id in `usage.ts`.
|
* Idempotent: messages are de-duplicated by id in `usage.ts`.
|
||||||
*/
|
*/
|
||||||
function reconcileSessions(): void {
|
function reconcileSessions(): Promise<void> {
|
||||||
if (!trackUsage || trackedSessions.size === 0) return
|
if (!trackUsage || trackedSessions.size === 0) return Promise.resolve()
|
||||||
|
const updates: Promise<void>[] = []
|
||||||
for (const sessionID of trackedSessions) {
|
for (const sessionID of trackedSessions) {
|
||||||
let messages: ReadonlyArray<UsageMessage> | undefined
|
let messages: ReadonlyArray<unknown> | undefined
|
||||||
try {
|
try {
|
||||||
messages = api.state.session.messages(sessionID)
|
messages = context.data.session.message.list(sessionID)
|
||||||
} catch {
|
} catch {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if (!messages?.length) continue
|
if (!messages?.length) continue
|
||||||
mutateUsage((days) => applyMessages(days, messages as ReadonlyArray<unknown>))
|
updates.push(mutateUsage((days) => applyMessages(days, toUsageMessages(messages ?? []))))
|
||||||
}
|
}
|
||||||
|
return Promise.all(updates).then(() => undefined)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Best-effort startup backfill from recently updated sessions. */
|
/** 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 listed = await context.client.session.list({
|
||||||
data?: unknown
|
limit: usageBackfillLimit,
|
||||||
}
|
})
|
||||||
if (!Array.isArray(listed?.data)) return
|
for (const session of listed.data ?? []) {
|
||||||
for (const session of listed.data) {
|
|
||||||
if (disposed) return
|
if (disposed) return
|
||||||
const sessionID = (session as { id?: unknown })?.id
|
const sessionID = (session as { id?: unknown })?.id
|
||||||
if (typeof sessionID !== "string" || !sessionID) continue
|
if (typeof sessionID !== "string" || !sessionID) continue
|
||||||
trackedSessions.add(sessionID)
|
trackedSessions.add(sessionID)
|
||||||
try {
|
try {
|
||||||
const result = (await client.session.messages({ sessionID })) as { data?: unknown }
|
const messages = await context.client.session.context({ sessionID })
|
||||||
if (!Array.isArray(result?.data)) continue
|
await mutateUsage((days) => applyMessages(days, toUsageMessages(messages)))
|
||||||
const messages = result.data
|
|
||||||
.map((row) => (row as { info?: unknown })?.info)
|
|
||||||
.filter((info) => info !== undefined && info !== null)
|
|
||||||
mutateUsage((days) => applyMessages(days, messages))
|
|
||||||
} catch {
|
} catch {
|
||||||
// One unreadable session must not abort the whole backfill.
|
// One unreadable session must not abort the whole backfill.
|
||||||
}
|
}
|
||||||
@@ -204,13 +201,6 @@ export function createBalanceStore(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Re-read persisted buckets once the KV store becomes ready. */
|
|
||||||
function reloadUsageWhenReady(): void {
|
|
||||||
if (!trackUsage || kvLoaded || api.kv.ready !== true) return
|
|
||||||
kvLoaded = true
|
|
||||||
setUsageDays(readUsageDays(api.kv))
|
|
||||||
}
|
|
||||||
|
|
||||||
function scheduleNext() {
|
function scheduleNext() {
|
||||||
if (disposed) return
|
if (disposed) return
|
||||||
if (refreshTimer) clearTimeout(refreshTimer)
|
if (refreshTimer) clearTimeout(refreshTimer)
|
||||||
@@ -233,15 +223,10 @@ export function createBalanceStore(
|
|||||||
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 } })
|
setState({ status: "error", error: { kind: "no-credential", reason: credential.reason } })
|
||||||
if (api.state.path.state === undefined && !retriedState) {
|
|
||||||
retriedState = true
|
|
||||||
stateRetryTimer = setTimeout(() => void refresh(), STATE_RETRY_MS)
|
|
||||||
}
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -260,7 +245,7 @@ export function createBalanceStore(
|
|||||||
if (trackUsage && Number.isFinite(credits)) {
|
if (trackUsage && Number.isFinite(credits)) {
|
||||||
if (lastCredits !== undefined && credits < lastCredits) {
|
if (lastCredits !== undefined && credits < lastCredits) {
|
||||||
const spent = lastCredits - credits
|
const spent = lastCredits - credits
|
||||||
mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
|
await mutateUsage((days) => addCreditsSpent(days, Date.now(), spent))
|
||||||
}
|
}
|
||||||
lastCredits = credits
|
lastCredits = credits
|
||||||
}
|
}
|
||||||
@@ -273,14 +258,14 @@ export function createBalanceStore(
|
|||||||
inFlight = false
|
inFlight = false
|
||||||
}
|
}
|
||||||
if (disposed) return
|
if (disposed) return
|
||||||
reconcileSessions()
|
await reconcileSessions()
|
||||||
scheduleNext()
|
scheduleNext()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Clear every persisted and in-memory usage bucket. */
|
/** Clear every persisted and in-memory usage bucket. */
|
||||||
function resetUsage(): void {
|
async function resetUsage(): Promise<void> {
|
||||||
lastCredits = undefined
|
lastCredits = undefined
|
||||||
mutateUsage((days) => {
|
await mutateUsage((days) => {
|
||||||
for (const date of Object.keys(days)) delete days[date]
|
for (const date of Object.keys(days)) delete days[date]
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -292,7 +277,6 @@ export function createBalanceStore(
|
|||||||
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()
|
||||||
|
|||||||
63
src/tui.tsx
Normal file
63
src/tui.tsx
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
/** @jsxImportSource @opentui/solid */
|
||||||
|
import { Plugin } from "@opencode/plugin/tui"
|
||||||
|
import { FOLD_STORAGE_KEY } from "./format"
|
||||||
|
import { createBalanceStore, type BalanceOptions } from "./store"
|
||||||
|
import { GreenptWidget } from "./widget"
|
||||||
|
|
||||||
|
export default Plugin.define({
|
||||||
|
id: "greenpt.usage.tui",
|
||||||
|
setup(context) {
|
||||||
|
const opts = (context.options ?? {}) as BalanceOptions
|
||||||
|
const store = createBalanceStore(context, opts)
|
||||||
|
const [fold, updateFold] = context.storage.store(FOLD_STORAGE_KEY, {
|
||||||
|
initial: { open: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
const unregisterSlot = context.ui.slot({
|
||||||
|
append: "sidebar.content",
|
||||||
|
render: () => (
|
||||||
|
<GreenptWidget
|
||||||
|
store={store}
|
||||||
|
theme={context.theme}
|
||||||
|
open={() => fold.open}
|
||||||
|
toggleOpen={() => {
|
||||||
|
void updateFold((draft) => {
|
||||||
|
draft.open = !fold.open
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
showWhenUnavailable={opts.showWhenUnavailable === true}
|
||||||
|
unit={opts.unit}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
context.keymap.layer(() => ({
|
||||||
|
mode: "global",
|
||||||
|
commands: [
|
||||||
|
{
|
||||||
|
id: "greenpt.refresh",
|
||||||
|
title: "Refresh GreenPT balance",
|
||||||
|
group: "GreenPT",
|
||||||
|
palette: true,
|
||||||
|
run() {
|
||||||
|
void store.refresh()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "greenpt.usage.reset",
|
||||||
|
title: "Reset GreenPT usage counters",
|
||||||
|
group: "GreenPT",
|
||||||
|
palette: true,
|
||||||
|
run() {
|
||||||
|
void store.resetUsage()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}))
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
unregisterSlot()
|
||||||
|
store.dispose()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
/** @jsxImportSource @opentui/solid */
|
/** @jsxImportSource @opentui/solid */
|
||||||
import { createSignal, For, Match, Show, Switch } from "solid-js"
|
import { createSignal, For, Match, Show, Switch } from "solid-js"
|
||||||
import type { TuiPluginApi, TuiThemeCurrent } from "@opencode-ai/plugin/tui"
|
import type { ResolvedTheme } from "@opencode/theme/tui"
|
||||||
import {
|
import {
|
||||||
formatBalanceError,
|
formatBalanceError,
|
||||||
formatCredits,
|
formatCredits,
|
||||||
formatTokens,
|
formatTokens,
|
||||||
readFoldOpen,
|
|
||||||
BALANCE_OPEN_KV,
|
|
||||||
DEFAULT_UNIT,
|
DEFAULT_UNIT,
|
||||||
} from "./format"
|
} from "./format"
|
||||||
import { dayTotals, monthTotals, type ModelTotal } from "./usage"
|
import { dayTotals, monthTotals, type ModelTotal } from "./usage"
|
||||||
@@ -22,25 +20,19 @@ 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
|
|
||||||
store: BalanceStore
|
store: BalanceStore
|
||||||
|
theme: ResolvedTheme
|
||||||
|
open: () => boolean
|
||||||
|
toggleOpen: () => void
|
||||||
showWhenUnavailable: boolean
|
showWhenUnavailable: boolean
|
||||||
unit?: string
|
unit?: string
|
||||||
}) {
|
}) {
|
||||||
const theme = () => props.api.theme.current
|
const theme = () => props.theme
|
||||||
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 = () => props.open()
|
||||||
|
|
||||||
const toggle = () => {
|
const toggle = () => props.toggleOpen()
|
||||||
const next = !open()
|
|
||||||
setOpen(next)
|
|
||||||
try {
|
|
||||||
props.api.kv.set(BALANCE_OPEN_KV, next)
|
|
||||||
} catch {
|
|
||||||
// KV persistence is optional; the local toggle still applies.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const error = () => {
|
const error = () => {
|
||||||
const s = state()
|
const s = state()
|
||||||
@@ -60,7 +52,8 @@ export function GreenptWidget(props: {
|
|||||||
}
|
}
|
||||||
const balanceColor = () => {
|
const balanceColor = () => {
|
||||||
const s = state()
|
const s = state()
|
||||||
return s.status === "ready" && s.data.credits > 0 ? "success" : "error"
|
const kind = s.status === "ready" && s.data.credits > 0 ? "success" : "error"
|
||||||
|
return theme().text.feedback[kind].base
|
||||||
}
|
}
|
||||||
const updatedAt = () => {
|
const updatedAt = () => {
|
||||||
const s = state()
|
const s = state()
|
||||||
@@ -71,7 +64,7 @@ export function GreenptWidget(props: {
|
|||||||
return `updated ${hh}:${mm}`
|
return `updated ${hh}:${mm}`
|
||||||
}
|
}
|
||||||
|
|
||||||
const usage = () => props.store.usageDays()
|
const usage = () => props.store.usageDays
|
||||||
const todayUsage = () => dayTotals(usage(), props.store.now())
|
const todayUsage = () => dayTotals(usage(), props.store.now())
|
||||||
const monthUsage = () => monthTotals(usage(), props.store.now())
|
const monthUsage = () => monthTotals(usage(), props.store.now())
|
||||||
const usageVisible = () => todayUsage().creditsSpent > 0 || monthUsage().cost > 0
|
const usageVisible = () => todayUsage().creditsSpent > 0 || monthUsage().cost > 0
|
||||||
@@ -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: balanceColor() }}>
|
||||||
{" "}
|
{" "}
|
||||||
{text()}
|
{text()}
|
||||||
{foldedSuffix()}
|
{foldedSuffix()}
|
||||||
@@ -100,38 +93,38 @@ 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={balanceColor()}>{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}>{formatTokens(row.usage.tokens.input + row.usage.tokens.output)} tok</text>
|
||||||
<text fg={theme().text}>~{formatCredits(row.usage.cost)} {unit()}</text>
|
<text fg={theme().text.base}>~{formatCredits(row.usage.cost)} {unit()}</text>
|
||||||
</box>
|
</box>
|
||||||
</box>
|
</box>
|
||||||
)}
|
)}
|
||||||
@@ -147,9 +140,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: ResolvedTheme }) {
|
||||||
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>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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", () => {
|
||||||
@@ -50,26 +50,3 @@ describe("formatBalanceError", () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("readFoldOpen", () => {
|
|
||||||
it("defaults to open when the KV store is absent", () => {
|
|
||||||
expect(readFoldOpen(undefined)).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it("reads a persisted boolean", () => {
|
|
||||||
expect(readFoldOpen({ get: () => false })).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it("falls back when the stored value is not a boolean", () => {
|
|
||||||
expect(readFoldOpen({ get: () => "nope" })).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it("survives a throwing KV store", () => {
|
|
||||||
expect(
|
|
||||||
readFoldOpen({
|
|
||||||
get: () => {
|
|
||||||
throw new Error("kv down")
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,19 +1,20 @@
|
|||||||
import { describe, expect, it, vi } from "vitest"
|
import { describe, expect, it, vi } from "vitest"
|
||||||
import { createBalanceStore, type BalanceOptions } from "../src/store"
|
import { createBalanceStore, type BalanceOptions } from "../src/store"
|
||||||
import { nativeFetch } from "../src/balance"
|
import { nativeFetch } from "../src/balance"
|
||||||
import { serializeUsage, type UsageDays } from "../src/usage"
|
import type { UsageDays } from "../src/usage"
|
||||||
|
|
||||||
const NOW = new Date(2026, 9, 19, 15, 0, 0).getTime()
|
const NOW = new Date(2026, 9, 19, 15, 0, 0).getTime()
|
||||||
const DAY = "2026-10-19"
|
const DAY = "2026-10-19"
|
||||||
|
|
||||||
type FakeMessage = Record<string, unknown>
|
type FakeMessage = Record<string, unknown>
|
||||||
|
|
||||||
function makeApi() {
|
/** Minimal structural fake of the OpenCode v2 TUI plugin context. */
|
||||||
const kvData = new Map<string, unknown>()
|
function makeContext(storage = new Map<string, object>()) {
|
||||||
|
const storageData = storage
|
||||||
const messages = new Map<string, FakeMessage[]>()
|
const messages = new Map<string, FakeMessage[]>()
|
||||||
const handlers = new Map<string, Array<(event: unknown) => void>>()
|
const handlers = new Map<string, Array<(event: unknown) => void>>()
|
||||||
const api = {
|
const context = {
|
||||||
event: {
|
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 +26,35 @@ function makeApi() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
|
||||||
kv: {
|
|
||||||
ready: true,
|
|
||||||
get: (key: string, fallback?: unknown) => (kvData.has(key) ? kvData.get(key) : fallback),
|
|
||||||
set: (key: string, value: unknown) => {
|
|
||||||
kvData.set(key, value)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
state: {
|
|
||||||
path: { state: "/tmp/fake-state" },
|
|
||||||
session: {
|
session: {
|
||||||
messages: (sessionID: string) => messages.get(sessionID) ?? [],
|
message: {
|
||||||
|
list: (sessionID: string) => messages.get(sessionID) ?? [],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
client: {
|
client: {
|
||||||
session: {
|
session: {
|
||||||
list: async () => ({ data: [] }),
|
list: async () => ({ data: [] }),
|
||||||
messages: async () => ({ data: [] }),
|
context: async () => [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
storage: {
|
||||||
|
store: (key: string, { initial }: { initial: object }) => {
|
||||||
|
if (!storageData.has(key)) storageData.set(key, initial)
|
||||||
|
const value = storageData.get(key)!
|
||||||
|
return [
|
||||||
|
value,
|
||||||
|
async (mutate: (draft: object) => void) => {
|
||||||
|
mutate(value)
|
||||||
|
},
|
||||||
|
] as const
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
emit(type: string, event: unknown) {
|
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, storageData, messages }
|
||||||
}
|
}
|
||||||
|
|
||||||
function balanceResponse(credits: number) {
|
function balanceResponse(credits: number) {
|
||||||
@@ -65,15 +70,15 @@ 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]),
|
||||||
@@ -82,73 +87,78 @@ describe("usage tracking in the balance store", () => {
|
|||||||
await store.refresh()
|
await store.refresh()
|
||||||
await store.refresh()
|
await store.refresh()
|
||||||
await store.refresh()
|
await store.refresh()
|
||||||
expect(store.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.1)
|
expect(store.usageDays[DAY]?.creditsSpent).toBeCloseTo(0.1)
|
||||||
store.dispose()
|
store.dispose()
|
||||||
})
|
})
|
||||||
|
|
||||||
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", [
|
||||||
{
|
{
|
||||||
|
type: "assistant",
|
||||||
id: "m1",
|
id: "m1",
|
||||||
role: "assistant",
|
model: { providerID: "greenpt", id: "glm-5.3-flash" },
|
||||||
providerID: "greenpt",
|
|
||||||
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 durable storage and reloads them", async () => {
|
||||||
const { api, kvData } = makeApi()
|
const { context, storageData } = 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(storageData.has("greenpt.usage.days")).toBe(true)
|
||||||
first.dispose()
|
first.dispose()
|
||||||
|
|
||||||
const stored: UsageDays = { [DAY]: { date: DAY, creditsSpent: 0.5, byModel: {}, ids: [] } }
|
const stored: UsageDays = { [DAY]: { date: DAY, creditsSpent: 0.5, byModel: {}, ids: [] } }
|
||||||
kvData.set("greenpt.usage.days", serializeUsage(stored))
|
storageData.set("greenpt.usage.days", stored)
|
||||||
const second = createTrackedStore(api)
|
const { context: secondContext } = makeContext(storageData)
|
||||||
expect(second.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.5)
|
const secondStore = createBalanceStore(
|
||||||
second.dispose()
|
secondContext as never,
|
||||||
|
{ apiKey: "test-key" },
|
||||||
|
{},
|
||||||
|
fetchSequence([10]),
|
||||||
|
)
|
||||||
|
expect(secondStore.usageDays[DAY]?.creditsSpent).toBeCloseTo(0.5)
|
||||||
|
secondStore.dispose()
|
||||||
})
|
})
|
||||||
|
|
||||||
it("resetUsage clears buckets", async () => {
|
it("resetUsage clears buckets", async () => {
|
||||||
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()
|
await store.resetUsage()
|
||||||
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, storageData } = 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]),
|
||||||
)
|
)
|
||||||
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(storageData.has("greenpt.usage.days")).toBe(false)
|
||||||
store.dispose()
|
store.dispose()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user