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

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

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

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

View File

@@ -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()
})
})