import { EnvironmentId, ProviderDriverKind, ProviderInstanceId, UsageDay, USAGE_CONTRACT_VERSION, type ServerProvider, type UsageSummary, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import type { EnvironmentPresentation } from "../connection/presentation.ts"; import { EnvironmentRpcUnavailableError } from "../rpc/client.ts"; import { cursorKeychainAccessEnvironments, needsCursorKeychainAccess, refreshUsage, refreshUsageLimits, } from "./usage.ts"; const input = { sinceDay: UsageDay.make("2026-09-05"), untilDay: UsageDay.make("2026-09-05"), timeZone: "UTC", }; const pricing = { status: "fresh" as const, source: "test", fetchedAt: null, knownModels: 1 }; const summary: UsageSummary = { ...input, contractVersion: USAGE_CONTRACT_VERSION, readAt: "2026-09-05T12:00:00Z", buckets: [], sources: [], pricing, scanDurationMs: 1, }; const registries: AtomRegistry.AtomRegistry[] = []; afterEach(() => { for (const registry of registries.splice(0)) registry.dispose(); }); function harness(ids = ["a"]) { const registry = AtomRegistry.make(); registries.push(registry); const environments = ids.map((id) => { const environmentId = EnvironmentId.make(id); const rates = Promise.withResolvers< AsyncResult.Success | AsyncResult.Failure >(); const scan = Promise.withResolvers(); const scanStarted = Promise.withResolvers(); const presentation = Atom.make({ connection: { phase: "connected" }, } as EnvironmentPresentation | null); const query = Atom.make( Effect.promise(() => { scanStarted.resolve(); return scan.promise; }), ); return { environmentId, rates, scan, scanStarted, presentation, query }; }); function get(environmentId: EnvironmentId) { const environment = environments.find((entry) => entry.environmentId === environmentId); if (!environment) throw new Error(`Unknown environment: ${environmentId}`); return environment; } const options = { registry, environmentIds: environments.map((entry) => entry.environmentId), input, server: { usageSummary: ({ environmentId }: { environmentId: EnvironmentId }) => get(environmentId).query, refreshUsageRates: { label: "test:rates", requiredScopes: () => [], permissionAtom: () => Atom.make(true), run: ( _registry: AtomRegistry.AtomRegistry, { environmentId }: { environmentId: EnvironmentId }, ) => get(environmentId).rates.promise, }, }, presentations: { presentationAtom: (environmentId: EnvironmentId) => get(environmentId).presentation, }, } satisfies Parameters[0]; return { registry, environments, refresh: () => refreshUsage(options) }; } describe("manual usage refresh", () => { it.each(["success", "failure"])("waits for the rescan after a pricing %s", async (result) => { const { environments: [environment], refresh, } = harness(); const entry = environment!; let finished = false; const refreshing = refresh().then(() => { finished = true; }); expect(finished).toBe(false); entry.rates.resolve( result === "success" ? AsyncResult.success(pricing) : AsyncResult.fail(new Error("Pricing offline")), ); await entry.scanStarted.promise; expect(finished).toBe(false); entry.scan.resolve(summary); await refreshing; expect(finished).toBe(true); }); it("settles when an environment disconnects during the rescan", async () => { const { registry, environments: [environment], refresh, } = harness(); const entry = environment!; const refreshing = refresh(); entry.rates.resolve(AsyncResult.success(pricing)); await entry.scanStarted.promise; registry.set(entry.presentation, null); await refreshing; }); it("waits for healthy environments without waiting for a recovering environment", async () => { const { registry, environments, refresh } = harness(["healthy", "recovering"]); const [healthy, recovering] = environments; registry.set(recovering!.presentation, null); let finished = false; const refreshing = refresh().then(() => { finished = true; }); for (const entry of environments) entry.rates.resolve(AsyncResult.success(pricing)); await healthy!.scanStarted.promise; expect(finished).toBe(false); healthy!.scan.resolve(summary); await refreshing; expect(finished).toBe(true); }); it("settles when connected state has no usable RPC session", async () => { const { environments: [environment], refresh, } = harness(); const entry = environment!; const refreshing = refresh(); entry.rates.resolve( AsyncResult.fail( new EnvironmentRpcUnavailableError({ environmentId: entry.environmentId, message: "No session", }), ), ); await refreshing; }); it("replaces a scan that started before pricing was refreshed", async () => { const { registry, environments: [environment], refresh, } = harness(); const entry = environment!; let reads = 0; const rescanned = Promise.withResolvers(); const query = Atom.make( Effect.promise(() => { reads += 1; if (reads > 1) { rescanned.resolve(); return Promise.resolve(summary); } return new Promise(() => {}); }), ); entry.query = query; const unmount = registry.mount(query); expect(reads).toBe(1); const refreshing = refresh(); entry.rates.resolve(AsyncResult.success(pricing)); await rescanned.promise; await refreshing; expect(reads).toBe(2); unmount(); }); }); describe("limits refresh cooldown", () => { it("runs a fresh check after an in-flight check when settings change", async () => { const id = EnvironmentId.make("limits-after-enable"); const oldCheck = Promise.withResolvers(); const first = refreshUsageLimits(id, () => oldCheck.promise, true); const newCheck = vi.fn(async () => "new limits"); const afterEnable = refreshUsageLimits(id, newCheck, false, true); expect(newCheck).not.toHaveBeenCalled(); oldCheck.resolve("old limits"); expect(await first).toBe("old limits"); expect(await afterEnable).toBe("new limits"); expect(newCheck).toHaveBeenCalledTimes(1); }); it("joins manual calls and gates automatic refreshes after success or failure", async () => { const clock = vi.spyOn(Date, "now").mockReturnValue(1_000); try { for (const fails of [false, true]) { const id = EnvironmentId.make(`limits-${fails}`); const pending = Promise.withResolvers(); const refresh = vi.fn(() => pending.promise); const first = refreshUsageLimits(id, refresh, true); await refreshUsageLimits(id, refresh, true); const manual = refreshUsageLimits(id, refresh); const settled = vi.fn(); void manual.then(settled, settled); expect(settled).not.toHaveBeenCalled(); expect(refresh).toHaveBeenCalledTimes(1); if (fails) { const firstFailure = expect(first).rejects.toThrow("unavailable"); const manualFailure = expect(manual).rejects.toThrow("unavailable"); pending.reject(new Error("unavailable")); await Promise.all([firstFailure, manualFailure]); } else { pending.resolve("quota"); expect(await first).toBe("quota"); expect(await manual).toBe("quota"); } expect(settled).toHaveBeenCalledTimes(1); const next = vi.fn(async () => undefined); clock.mockReturnValue(300_999); await refreshUsageLimits(id, next, true); expect(next).not.toHaveBeenCalled(); clock.mockReturnValue(301_000); await refreshUsageLimits(id, next, true); expect(next).toHaveBeenCalledTimes(1); await refreshUsageLimits(id, next); expect(next).toHaveBeenCalledTimes(2); clock.mockReturnValue(1_000); } } finally { clock.mockRestore(); } }); }); describe("needsCursorKeychainAccess", () => { const cursorPrompt: UsageSummary = { ...summary, sources: [ { fingerprint: { hostId: "host", provider: "cursor", resolvedHomePath: "/Users/me/.cursor/auth.json", volumeId: "volume", }, status: "ok", scannedFiles: 0, skippedFiles: 0, malformedRecords: 0, distinctSessions: 0, message: "Cursor account usage is off on this environment.", action: "enableCursorKeychain", }, ], }; const cursor = (status: ServerProvider["status"]): ServerProvider => ({ instanceId: ProviderInstanceId.make("cursor"), driver: ProviderDriverKind.make("cursor"), enabled: status !== "disabled", installed: status === "ready", version: null, status, auth: { status: "unknown" }, checkedAt: "2026-09-05T12:00:00.000Z", models: [], slashCommands: [], skills: [], }); it("offers access only when Cursor is ready on that environment", () => { expect(needsCursorKeychainAccess(cursorPrompt, [cursor("ready")])).toBe(true); expect(needsCursorKeychainAccess(cursorPrompt, [cursor("error")])).toBe(false); expect(needsCursorKeychainAccess(cursorPrompt, [cursor("disabled")])).toBe(false); expect(needsCursorKeychainAccess(cursorPrompt, [])).toBe(false); expect(needsCursorKeychainAccess(cursorPrompt, null)).toBe(false); expect(needsCursorKeychainAccess(summary, [cursor("ready")])).toBe(false); }); it("stops offering access once any environment reads the Cursor account", () => { const off = { summary: cursorPrompt, needsCursorKeychainAccess: true }; const account: UsageSummary = { ...summary, sources: [ { fingerprint: { hostId: "cursor.com", provider: "cursor", resolvedHomePath: "cursor-account:abc", volumeId: "abc", }, status: "ok", scannedFiles: 1, skippedFiles: 0, malformedRecords: 0, distinctSessions: 1, message: null, }, ], }; expect(cursorKeychainAccessEnvironments([off, off])).toEqual([off, off]); expect( cursorKeychainAccessEnvironments([ off, { summary: account, needsCursorKeychainAccess: false }, ]), ).toEqual([]); }); });