chg: [opencode-greenpt-usage] port the TUI plugin to OpenCode 2
V1 TUI modules no longer load: replace ``{ id, tui }`` with
``Plugin.define({ id, setup })``, register the section on
``sidebar.content``, and expose commands through ``context.keymap.layer``.
Move balance, clock and usage state onto ``context.storage.store/memory``
so host subscribers rerender; plugin-created signals stayed stale in the
V2 renderer. Read V2 assistant messages (``type``,
``model.providerID``/``model.id``) and subscribe through ``context.data``.
Configure the package directory in ``cli.json`` instead of the source
file; document the V2 install. Typecheck, 49 unit tests and the live
GreenPT integration test pass, and the sidebar renders the balance.
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest"
|
||||
import { formatBalanceError, formatCredits, formatTokens, readFoldOpen } from "../src/format"
|
||||
import { formatBalanceError, formatCredits, formatTokens } from "../src/format"
|
||||
|
||||
describe("formatCredits", () => {
|
||||
it("formats with two decimals", () => {
|
||||
@@ -49,27 +49,3 @@ describe("formatBalanceError", () => {
|
||||
expect(formatBalanceError({ kind: "no-credential", reason: "missing" })).toContain("GreenPT")
|
||||
})
|
||||
})
|
||||
|
||||
describe("readFoldOpen", () => {
|
||||
it("defaults to open when the KV store is absent", () => {
|
||||
expect(readFoldOpen(undefined)).toBe(true)
|
||||
})
|
||||
|
||||
it("reads a persisted boolean", () => {
|
||||
expect(readFoldOpen({ get: () => false })).toBe(false)
|
||||
})
|
||||
|
||||
it("falls back when the stored value is not a boolean", () => {
|
||||
expect(readFoldOpen({ get: () => "nope" })).toBe(true)
|
||||
})
|
||||
|
||||
it("survives a throwing KV store", () => {
|
||||
expect(
|
||||
readFoldOpen({
|
||||
get: () => {
|
||||
throw new Error("kv down")
|
||||
},
|
||||
}),
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,19 +1,59 @@
|
||||
import { describe, expect, it, vi } from "vitest"
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
|
||||
import { createBalanceStore, type BalanceOptions } from "../src/store"
|
||||
import { nativeFetch } from "../src/balance"
|
||||
import { serializeUsage, type UsageDays } from "../src/usage"
|
||||
import { dayKey } from "../src/usage"
|
||||
|
||||
const NOW = new Date(2026, 9, 19, 15, 0, 0).getTime()
|
||||
const 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>> }
|
||||
|
||||
function makeApi() {
|
||||
const kvData = new Map<string, unknown>()
|
||||
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 api = {
|
||||
event: {
|
||||
|
||||
const memory = new Map<string, unknown>()
|
||||
const context = {
|
||||
storage: {
|
||||
store: (key: string, options: { initial: unknown }) => {
|
||||
const target =
|
||||
key === "greenpt.usage.days"
|
||||
? payload
|
||||
: key === "greenpt.usage.open"
|
||||
? fold
|
||||
: options.initial
|
||||
return [
|
||||
target,
|
||||
async (mutation: (draft: unknown) => void) => {
|
||||
mutation(target)
|
||||
},
|
||||
] as const
|
||||
},
|
||||
memory: (key: string, options: { initial: unknown }) => {
|
||||
if (!memory.has(key)) memory.set(key, options.initial)
|
||||
const target = memory.get(key)
|
||||
return [
|
||||
target,
|
||||
(mutation: (draft: unknown) => void) => {
|
||||
mutation(target)
|
||||
},
|
||||
] as const
|
||||
},
|
||||
},
|
||||
data: {
|
||||
on: (type: string, handler: (event: unknown) => void) => {
|
||||
const list = handlers.get(type) ?? []
|
||||
list.push(handler)
|
||||
@@ -25,31 +65,19 @@ function makeApi() {
|
||||
)
|
||||
}
|
||||
},
|
||||
},
|
||||
kv: {
|
||||
ready: true,
|
||||
get: (key: string, fallback?: unknown) => (kvData.has(key) ? kvData.get(key) : fallback),
|
||||
set: (key: string, value: unknown) => {
|
||||
kvData.set(key, value)
|
||||
},
|
||||
},
|
||||
state: {
|
||||
path: { state: "/tmp/fake-state" },
|
||||
session: {
|
||||
messages: (sessionID: string) => messages.get(sessionID) ?? [],
|
||||
},
|
||||
},
|
||||
client: {
|
||||
session: {
|
||||
list: async () => ({ data: [] }),
|
||||
messages: async () => ({ data: [] }),
|
||||
list: () => sessions,
|
||||
message: {
|
||||
list: (sessionID: string) => messages.get(sessionID) ?? [],
|
||||
sync: async () => {},
|
||||
},
|
||||
},
|
||||
},
|
||||
emit(type: string, event: unknown) {
|
||||
for (const handler of handlers.get(type) ?? []) handler(event)
|
||||
},
|
||||
}
|
||||
return { api, kvData, messages }
|
||||
return { context, payload, fold, messages, sessions }
|
||||
}
|
||||
|
||||
function balanceResponse(credits: number) {
|
||||
@@ -65,15 +93,20 @@ function fetchSequence(credits: number[]) {
|
||||
}) as unknown as typeof nativeFetch
|
||||
}
|
||||
|
||||
function createTrackedStore(api: unknown, options: BalanceOptions = {}) {
|
||||
return createBalanceStore(api as never, { apiKey: "test-key", ...options }, {}, fetchSequence([10]))
|
||||
function createTrackedStore(context: unknown, options: BalanceOptions = {}) {
|
||||
return createBalanceStore(
|
||||
context as never,
|
||||
{ apiKey: "test-key", ...options },
|
||||
{},
|
||||
fetchSequence([10]),
|
||||
)
|
||||
}
|
||||
|
||||
describe("usage tracking in the balance store", () => {
|
||||
it("accumulates real credit spend from balance deltas", async () => {
|
||||
const { api } = makeApi()
|
||||
const { context } = makeContext()
|
||||
const store = createBalanceStore(
|
||||
api as never,
|
||||
context as never,
|
||||
{ apiKey: "test-key" },
|
||||
{},
|
||||
fetchSequence([10, 9.95, 9.9, 12]),
|
||||
@@ -87,60 +120,58 @@ describe("usage tracking in the balance store", () => {
|
||||
})
|
||||
|
||||
it("reconciles per-model usage from tracked sessions on refresh", async () => {
|
||||
const { api, messages } = makeApi()
|
||||
const store = createTrackedStore(api)
|
||||
const { context, messages } = makeContext()
|
||||
const store = createTrackedStore(context)
|
||||
messages.set("s1", [
|
||||
{
|
||||
id: "m1",
|
||||
role: "assistant",
|
||||
providerID: "greenpt",
|
||||
modelID: "glm-5.3-flash",
|
||||
type: "assistant",
|
||||
model: { providerID: "greenpt", id: "glm-5.3-flash" },
|
||||
cost: 0.02,
|
||||
time: { created: NOW },
|
||||
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()
|
||||
expect(store.usageDays()[DAY]?.byModel["glm-5.3-flash"]?.cost).toBeCloseTo(0.02)
|
||||
store.dispose()
|
||||
})
|
||||
|
||||
it("persists buckets to the KV store and reloads them", async () => {
|
||||
const { api, kvData } = makeApi()
|
||||
it("persists buckets to the durable store and reloads them", async () => {
|
||||
const { context, payload } = makeContext()
|
||||
const first = createBalanceStore(
|
||||
api as never,
|
||||
context as never,
|
||||
{ apiKey: "test-key" },
|
||||
{},
|
||||
fetchSequence([10, 9.9]),
|
||||
)
|
||||
await first.refresh()
|
||||
await first.refresh()
|
||||
expect(kvData.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: [] } }
|
||||
kvData.set("greenpt.usage.days", serializeUsage(stored))
|
||||
const second = createTrackedStore(api)
|
||||
expect(second.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.5)
|
||||
const second = createTrackedStore(context)
|
||||
expect(second.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.1)
|
||||
second.dispose()
|
||||
})
|
||||
|
||||
it("resetUsage clears buckets", async () => {
|
||||
const { api } = makeApi()
|
||||
const store = createTrackedStore(api)
|
||||
const { context } = makeContext()
|
||||
const store = createTrackedStore(context)
|
||||
await store.refresh()
|
||||
await store.refresh()
|
||||
store.resetUsage()
|
||||
await store.refresh()
|
||||
expect(Object.keys(store.usageDays()).length).toBe(0)
|
||||
store.dispose()
|
||||
})
|
||||
|
||||
it("skips tracking when disabled", async () => {
|
||||
const { api, kvData } = makeApi()
|
||||
const { context, payload } = makeContext()
|
||||
const store = createBalanceStore(
|
||||
api as never,
|
||||
context as never,
|
||||
{ apiKey: "test-key", trackUsage: false },
|
||||
{},
|
||||
fetchSequence([10, 5]),
|
||||
@@ -148,7 +179,7 @@ describe("usage tracking in the balance store", () => {
|
||||
await store.refresh()
|
||||
await store.refresh()
|
||||
expect(Object.keys(store.usageDays()).length).toBe(0)
|
||||
expect(kvData.has("greenpt.usage.days")).toBe(false)
|
||||
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