import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { createTestSession, type TestSession } from "../../../test/harness"; import costExtension, { __test } from "../index.ts"; describe("cost pi-test-harness", () => { let t: TestSession | undefined; let root: string | undefined; afterEach(() => { t?.dispose(); if (root) rmSync(root, { recursive: true, force: true }); t = undefined; root = undefined; }); it("loads in real Pi extension runtime", async () => { t = await createTestSession({ extensionFactories: [costExtension] }); expect(t.session.extensionRunner.extensions).toHaveLength(1); }); it("scans monthly session costs asynchronously", async () => { root = mkdtempSync(path.join(tmpdir(), "pi-cost-test-")); const sessionDir = path.join(root, "project"); mkdirSync(sessionDir); const now = new Date(); const month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`; writeFileSync( path.join(sessionDir, `${month}-session.jsonl`), JSON.stringify({ type: "message", message: { role: "assistant", usage: { cost: { total: 1.25 } }, }, }), "utf8", ); await expect(__test.calculateMonthlyCost(sessionDir)).resolves.toBe(1.25); await expect( __test.calculateMonthlyCost(sessionDir, () => false), ).resolves.toBeUndefined(); }); it("formats cached token usage compactly", () => { expect( __test.tokenLabel({ input: 1100, output: 978, cacheRead: 108900, cacheWrite: 0, }), ).toBe("◐ 1.1k ↓978  99%"); }); });