|
| 1 | +import { afterEach, describe, expect, test } from "bun:test"; |
| 2 | +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; |
| 3 | +import { tmpdir } from "node:os"; |
| 4 | +import { join } from "node:path"; |
| 5 | +import type { RegistryRequirements, Session, SessionSummary } from "@cookielab.io/klovi-plugin-core"; |
| 6 | +import { PluginError, SqliteClientTag } from "@cookielab.io/klovi-plugin-core"; |
| 7 | +import { NodeFileSystem } from "@effect/platform-node"; |
| 8 | +import { Effect, Layer } from "effect"; |
| 9 | +import type { ToolPlugin } from "./plugin-types.ts"; |
| 10 | +import { PluginRegistry } from "./registry.ts"; |
| 11 | +import { getStats, getStatsCachePath, invalidateStatsCache } from "./stats-service.ts"; |
| 12 | + |
| 13 | +const testLayer = Layer.merge( |
| 14 | + NodeFileSystem.layer, |
| 15 | + Layer.succeed(SqliteClientTag, { open: () => Effect.succeed(null) }), |
| 16 | +); |
| 17 | +const runEffect = <A>(effect: Effect.Effect<A, never, RegistryRequirements>) => |
| 18 | + Effect.runPromise(effect.pipe(Effect.provide(testLayer))); |
| 19 | + |
| 20 | +const testConfig = { dataDir: "/test" }; |
| 21 | +const tempDirs = new Set<string>(); |
| 22 | + |
| 23 | +function isoDaysAgo(days: number): string { |
| 24 | + const d = new Date(); |
| 25 | + d.setHours(12, 0, 0, 0); |
| 26 | + d.setDate(d.getDate() - days); |
| 27 | + return d.toISOString(); |
| 28 | +} |
| 29 | + |
| 30 | +// biome-ignore lint/complexity/useMaxParams: test helper with positional args for readability |
| 31 | +function makeSession( |
| 32 | + id: string, |
| 33 | + project: string, |
| 34 | + timestamp: string, |
| 35 | + model: string, |
| 36 | + inputTokens: number, |
| 37 | + outputTokens: number, |
| 38 | +): Session { |
| 39 | + return { |
| 40 | + sessionId: id, |
| 41 | + project: project, |
| 42 | + pluginId: "mock-plugin", |
| 43 | + turns: [ |
| 44 | + { |
| 45 | + kind: "user", |
| 46 | + uuid: `${id}-user`, |
| 47 | + timestamp: timestamp, |
| 48 | + text: "hello", |
| 49 | + }, |
| 50 | + { |
| 51 | + kind: "assistant", |
| 52 | + uuid: `${id}-assistant`, |
| 53 | + timestamp: timestamp, |
| 54 | + model: model, |
| 55 | + usage: { |
| 56 | + inputTokens: inputTokens, |
| 57 | + outputTokens: outputTokens, |
| 58 | + cacheReadTokens: 3, |
| 59 | + cacheCreationTokens: 2, |
| 60 | + }, |
| 61 | + contentBlocks: [{ type: "text", text: "result" }], |
| 62 | + }, |
| 63 | + ], |
| 64 | + }; |
| 65 | +} |
| 66 | + |
| 67 | +function createMockPlugin(sessionsById: Record<string, Session>, list: SessionSummary[]): ToolPlugin { |
| 68 | + return { |
| 69 | + id: "mock-plugin", |
| 70 | + displayName: "Mock", |
| 71 | + getDefaultDataDir: () => null, |
| 72 | + isDataAvailable: Effect.succeed(true), |
| 73 | + discoverProjects: Effect.succeed([ |
| 74 | + { |
| 75 | + pluginId: "mock-plugin", |
| 76 | + nativeId: "project-1", |
| 77 | + resolvedPath: "/tmp/project-1", |
| 78 | + displayName: "project-1", |
| 79 | + sessionCount: list.length, |
| 80 | + lastActivity: list[0]?.timestamp ?? "", |
| 81 | + }, |
| 82 | + ]), |
| 83 | + listSessions: () => Effect.succeed(list), |
| 84 | + loadSession: (_nativeId, sessionId) => { |
| 85 | + const session = sessionsById[sessionId]; |
| 86 | + if (!session) { |
| 87 | + return Effect.fail( |
| 88 | + new PluginError({ |
| 89 | + pluginId: "mock-plugin", |
| 90 | + operation: "loadSession", |
| 91 | + message: "missing session", |
| 92 | + }), |
| 93 | + ); |
| 94 | + } |
| 95 | + return Effect.succeed(session); |
| 96 | + }, |
| 97 | + }; |
| 98 | +} |
| 99 | + |
| 100 | +async function makeSettingsPath(): Promise<string> { |
| 101 | + const dir = await mkdtemp(join(tmpdir(), "klovi-stats-cache-")); |
| 102 | + tempDirs.add(dir); |
| 103 | + return join(dir, "settings.json"); |
| 104 | +} |
| 105 | + |
| 106 | +function waitFor(condition: () => Promise<boolean>, timeoutMs = 1000): Promise<void> { |
| 107 | + const startedAt = Date.now(); |
| 108 | + |
| 109 | + const poll = async (): Promise<void> => { |
| 110 | + if (await condition()) { |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + if (Date.now() - startedAt >= timeoutMs) { |
| 115 | + throw new Error("Timed out waiting for condition"); |
| 116 | + } |
| 117 | + |
| 118 | + await new Promise((resolve) => setTimeout(resolve, 10)); |
| 119 | + return poll(); |
| 120 | + }; |
| 121 | + |
| 122 | + return poll(); |
| 123 | +} |
| 124 | + |
| 125 | +afterEach(async () => { |
| 126 | + await Promise.all([...tempDirs].map((dir) => rm(dir, { recursive: true, force: true }))); |
| 127 | + tempDirs.clear(); |
| 128 | +}); |
| 129 | + |
| 130 | +describe("stats-service", () => { |
| 131 | + test("writes a stats cache file next to settings.json on cold load", async () => { |
| 132 | + const settingsPath = await makeSettingsPath(); |
| 133 | + const registry = new PluginRegistry(); |
| 134 | + const session = makeSession("s1", "project-1", isoDaysAgo(0), "claude-opus", 10, 5); |
| 135 | + const list: SessionSummary[] = [ |
| 136 | + { |
| 137 | + sessionId: "s1", |
| 138 | + timestamp: session.turns[0]?.timestamp ?? "", |
| 139 | + slug: "s1", |
| 140 | + firstMessage: "session 1", |
| 141 | + model: "claude-opus", |
| 142 | + gitBranch: "main", |
| 143 | + }, |
| 144 | + ]; |
| 145 | + |
| 146 | + registry.register(createMockPlugin({ s1: session }, list), testConfig); |
| 147 | + |
| 148 | + const result = await runEffect(getStats(settingsPath, registry)); |
| 149 | + expect(result.refreshing).toBe(false); |
| 150 | + expect(result.stats.inputTokens).toBe(10); |
| 151 | + |
| 152 | + const cachedRaw = await readFile(getStatsCachePath(settingsPath), "utf-8"); |
| 153 | + const cached = JSON.parse(cachedRaw) as { |
| 154 | + version: number; |
| 155 | + cachedAt: string; |
| 156 | + stats: { inputTokens: number }; |
| 157 | + }; |
| 158 | + |
| 159 | + expect(cached.version).toBe(1); |
| 160 | + expect(typeof cached.cachedAt).toBe("string"); |
| 161 | + expect(cached.stats.inputTokens).toBe(10); |
| 162 | + }); |
| 163 | + |
| 164 | + test("returns the sidecar cache first and refreshes it in the background", async () => { |
| 165 | + const settingsPath = await makeSettingsPath(); |
| 166 | + const registry = new PluginRegistry(); |
| 167 | + const session = makeSession("s1", "project-1", isoDaysAgo(0), "claude-opus", 99, 5); |
| 168 | + const list: SessionSummary[] = [ |
| 169 | + { |
| 170 | + sessionId: "s1", |
| 171 | + timestamp: session.turns[0]?.timestamp ?? "", |
| 172 | + slug: "s1", |
| 173 | + firstMessage: "session 1", |
| 174 | + model: "claude-opus", |
| 175 | + gitBranch: "main", |
| 176 | + }, |
| 177 | + ]; |
| 178 | + |
| 179 | + registry.register(createMockPlugin({ s1: session }, list), testConfig); |
| 180 | + |
| 181 | + await writeFile( |
| 182 | + getStatsCachePath(settingsPath), |
| 183 | + JSON.stringify( |
| 184 | + { |
| 185 | + version: 1, |
| 186 | + cachedAt: "2000-01-01T00:00:00.000Z", |
| 187 | + stats: { |
| 188 | + projects: 1, |
| 189 | + sessions: 1, |
| 190 | + messages: 2, |
| 191 | + todaySessions: 0, |
| 192 | + thisWeekSessions: 0, |
| 193 | + inputTokens: 10, |
| 194 | + outputTokens: 5, |
| 195 | + cacheReadTokens: 3, |
| 196 | + cacheCreationTokens: 2, |
| 197 | + toolCalls: 0, |
| 198 | + models: {}, |
| 199 | + }, |
| 200 | + }, |
| 201 | + null, |
| 202 | + 2, |
| 203 | + ), |
| 204 | + ); |
| 205 | + |
| 206 | + const cachedFirst = await runEffect(getStats(settingsPath, registry)); |
| 207 | + expect(cachedFirst.stats.inputTokens).toBe(10); |
| 208 | + expect(cachedFirst.refreshing).toBe(true); |
| 209 | + |
| 210 | + await waitFor(async () => { |
| 211 | + const refreshedRaw = await readFile(getStatsCachePath(settingsPath), "utf-8"); |
| 212 | + const refreshed = JSON.parse(refreshedRaw) as { stats: { inputTokens: number } }; |
| 213 | + return refreshed.stats.inputTokens === 99; |
| 214 | + }); |
| 215 | + |
| 216 | + const refreshed = await runEffect(getStats(settingsPath, registry)); |
| 217 | + expect(refreshed.stats.inputTokens).toBe(99); |
| 218 | + expect(refreshed.refreshing).toBe(false); |
| 219 | + }); |
| 220 | + |
| 221 | + test("invalidates the sidecar cache file", async () => { |
| 222 | + const settingsPath = await makeSettingsPath(); |
| 223 | + await writeFile( |
| 224 | + getStatsCachePath(settingsPath), |
| 225 | + JSON.stringify({ version: 1, cachedAt: "2000-01-01T00:00:00.000Z", stats: {} }), |
| 226 | + ); |
| 227 | + |
| 228 | + await runEffect(invalidateStatsCache(settingsPath)); |
| 229 | + |
| 230 | + await expect(readFile(getStatsCachePath(settingsPath), "utf-8")).rejects.toThrow(); |
| 231 | + }); |
| 232 | +}); |
0 commit comments