Rewrite the TUI plugin against the OpenCode v2 plugin API (``@opencode/plugin`` + ``@opencode/plugin/tui``): - ``src/index.ts``: minimal server-side ``Plugin.define`` entry. - ``src/tui.tsx``: CLI plugin registered as ``./tui``, appending the widget to the ``sidebar.content`` slot through ``context.ui.slot`` and exposing the refresh/reset commands via ``context.keymap.layer``. - ``src/store.ts``: durable plugin storage (``context.storage.store``) replaces the KV store; ``session.idle``/``session.status`` events and the ``client.session`` API drive reconciliation and backfill. - ``src/widget.tsx``: v2 semantic theme tokens (``theme.text.base``/``text.muted``/``text.feedback``). - Tests updated to a structural fake of the v2 context. The free ``HEAD /v1/chat/completions`` balance probe and the credential resolution order are unchanged. The ``order`` option is gone: v2 slot placement is additive.
165 lines
5.1 KiB
TypeScript
165 lines
5.1 KiB
TypeScript
import { describe, expect, it, vi } from "vitest"
|
|
import { createBalanceStore, type BalanceOptions } from "../src/store"
|
|
import { nativeFetch } from "../src/balance"
|
|
import type { UsageDays } from "../src/usage"
|
|
|
|
const NOW = new Date(2026, 9, 19, 15, 0, 0).getTime()
|
|
const DAY = "2026-10-19"
|
|
|
|
type FakeMessage = Record<string, unknown>
|
|
|
|
/** Minimal structural fake of the OpenCode v2 TUI plugin context. */
|
|
function makeContext(storage = new Map<string, object>()) {
|
|
const storageData = storage
|
|
const messages = new Map<string, FakeMessage[]>()
|
|
const handlers = new Map<string, Array<(event: unknown) => void>>()
|
|
const context = {
|
|
data: {
|
|
on: (type: string, handler: (event: unknown) => void) => {
|
|
const list = handlers.get(type) ?? []
|
|
list.push(handler)
|
|
handlers.set(type, list)
|
|
return () => {
|
|
handlers.set(
|
|
type,
|
|
(handlers.get(type) ?? []).filter((item) => item !== handler),
|
|
)
|
|
}
|
|
},
|
|
session: {
|
|
message: {
|
|
list: (sessionID: string) => messages.get(sessionID) ?? [],
|
|
},
|
|
},
|
|
},
|
|
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 }
|
|
}
|
|
|
|
function balanceResponse(credits: number) {
|
|
return new Response(null, { status: 400, headers: { "x-credits-remaining": String(credits) } })
|
|
}
|
|
|
|
function fetchSequence(credits: number[]) {
|
|
let index = 0
|
|
return vi.fn(() => {
|
|
const response = balanceResponse(credits[Math.min(index, credits.length - 1)] ?? 0)
|
|
index += 1
|
|
return Promise.resolve(response)
|
|
}) as unknown as typeof nativeFetch
|
|
}
|
|
|
|
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 { context } = makeContext()
|
|
const store = createBalanceStore(
|
|
context as never,
|
|
{ apiKey: "test-key" },
|
|
{},
|
|
fetchSequence([10, 9.95, 9.9, 12]),
|
|
)
|
|
await store.refresh()
|
|
await store.refresh()
|
|
await store.refresh()
|
|
await store.refresh()
|
|
expect(store.usageDays[DAY]?.creditsSpent).toBeCloseTo(0.1)
|
|
store.dispose()
|
|
})
|
|
|
|
it("reconciles per-model usage from tracked sessions on refresh", async () => {
|
|
const { context, messages } = makeContext()
|
|
const store = createTrackedStore(context)
|
|
messages.set("s1", [
|
|
{
|
|
type: "assistant",
|
|
id: "m1",
|
|
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 } },
|
|
},
|
|
])
|
|
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 durable storage and reloads them", async () => {
|
|
const { context, storageData } = makeContext()
|
|
const first = createBalanceStore(
|
|
context as never,
|
|
{ apiKey: "test-key" },
|
|
{},
|
|
fetchSequence([10, 9.9]),
|
|
)
|
|
await first.refresh()
|
|
await first.refresh()
|
|
expect(storageData.has("greenpt.usage.days")).toBe(true)
|
|
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()
|
|
})
|
|
|
|
it("resetUsage clears buckets", async () => {
|
|
const { context } = makeContext()
|
|
const store = createTrackedStore(context)
|
|
await store.refresh()
|
|
await store.refresh()
|
|
await store.resetUsage()
|
|
expect(Object.keys(store.usageDays).length).toBe(0)
|
|
store.dispose()
|
|
})
|
|
|
|
it("skips tracking when disabled", async () => {
|
|
const { context, storageData } = makeContext()
|
|
const store = createBalanceStore(
|
|
context as never,
|
|
{ apiKey: "test-key", trackUsage: false },
|
|
{},
|
|
fetchSequence([10, 5]),
|
|
)
|
|
await store.refresh()
|
|
await store.refresh()
|
|
expect(Object.keys(store.usageDays).length).toBe(0)
|
|
expect(storageData.has("greenpt.usage.days")).toBe(false)
|
|
store.dispose()
|
|
})
|
|
})
|