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.
186 lines
5.4 KiB
TypeScript
186 lines
5.4 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
|
|
import { createBalanceStore, type BalanceOptions } from "../src/store"
|
|
import { nativeFetch } from "../src/balance"
|
|
import { dayKey } from "../src/usage"
|
|
|
|
const NOW = new Date(2026, 9, 19, 15, 0, 0).getTime()
|
|
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 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) ?? []
|
|
list.push(handler)
|
|
handlers.set(type, list)
|
|
return () => {
|
|
handlers.set(
|
|
type,
|
|
(handlers.get(type) ?? []).filter((item) => item !== handler),
|
|
)
|
|
}
|
|
},
|
|
session: {
|
|
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 { context, payload, fold, messages, sessions }
|
|
}
|
|
|
|
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", [
|
|
{
|
|
id: "m1",
|
|
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 } },
|
|
},
|
|
])
|
|
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 durable store and reloads them", async () => {
|
|
const { context, payload } = makeContext()
|
|
const first = createBalanceStore(
|
|
context as never,
|
|
{ apiKey: "test-key" },
|
|
{},
|
|
fetchSequence([10, 9.9]),
|
|
)
|
|
await first.refresh()
|
|
await first.refresh()
|
|
expect(payload.days.length).toBeGreaterThan(0)
|
|
first.dispose()
|
|
|
|
const second = createTrackedStore(context)
|
|
expect(second.usageDays()[DAY]?.creditsSpent).toBeCloseTo(0.1)
|
|
second.dispose()
|
|
})
|
|
|
|
it("resetUsage clears buckets", async () => {
|
|
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 { context, payload } = 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(payload.days.length).toBe(0)
|
|
store.dispose()
|
|
})
|
|
})
|