diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index 9337ee77d..2e71b0ba4 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -290,7 +290,9 @@ export const ClaudeDriver: ProviderDriver = { // same transcripts as the main instance; only one row counts them. const readTokenUsage = accountFolder?.sharesMainHistory ? undefined - : yield* makeClaudeTokenUsageHistoryReader(effectiveConfig, processEnv); + : yield* makeClaudeTokenUsageHistoryReader(effectiveConfig, processEnv, { + stateDir: serverConfig.stateDir, + }); const stampIdentity = withInstanceIdentity({ instanceId, displayName, diff --git a/apps/server/src/provider/Layers/ClaudeTokenUsageHistory.ts b/apps/server/src/provider/Layers/ClaudeTokenUsageHistory.ts index c10fdd9c9..d48d9859c 100644 --- a/apps/server/src/provider/Layers/ClaudeTokenUsageHistory.ts +++ b/apps/server/src/provider/Layers/ClaudeTokenUsageHistory.ts @@ -7,9 +7,10 @@ * that cache has not been generated yet. This reader imports both without * coupling the provider card to the all-environment `/usage` projection. * - * The returned buckets are merged into the provider status cache by - * `ProviderRegistry`, which turns the initial import into a rolling 366-day - * Threadlines history across restarts. + * Claude Code deletes transcripts `cleanupPeriodDays` after they were last + * written, so every read is folded into a saved history in the server's state + * folder (`providerTokenUsageStore`). Days whose files are gone keep their + * totals there, which turns the import into a rolling 366-day history. * * @module provider/Layers/ClaudeTokenUsageHistory */ @@ -32,6 +33,7 @@ import { shiftProviderTokenUsageDateKey, summarizeProviderTokenUsageBuckets, } from "../providerTokenUsageHistory.ts"; +import { makeProviderTokenUsageStore, mergeTokenUsageDays } from "../providerTokenUsageStore.ts"; import { UsageAggregator } from "../../usage/usageAggregation.ts"; import { dedupeWithinFile, type ScanCache } from "../../usage/usageScanCache.ts"; import { listTranscriptFiles, readTranscriptRecords } from "../../usage/usageTranscriptReader.ts"; @@ -116,9 +118,6 @@ export function parseClaudeStatsTokenUsage(document: unknown): ClaudeStatsTokenU }; } -const sumBuckets = (buckets: ReadonlyArray): number => - buckets.reduce((sum, bucket) => sum + bucket.tokens, 0); - const clampDateKey = (value: string, minimum: string, maximum: string): string => value < minimum ? minimum : value > maximum ? maximum : value; @@ -126,6 +125,10 @@ export const makeClaudeTokenUsageHistoryReader = Effect.fn("ClaudeTokenUsageHist function* ( settings: Pick, environment: NodeJS.ProcessEnv = process.env, + options: { + /** The server's state folder, where the saved history lives. Without it nothing is saved. */ + readonly stateDir?: string; + } = {}, ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -139,6 +142,13 @@ export const makeClaudeTokenUsageHistoryReader = Effect.fn("ClaudeTokenUsageHist const statsCachePath = path.join(dataDir, "stats-cache.json"); const transcriptDir = path.join(dataDir, "projects"); const fileCache: ScanCache = new Map(); + const store = options.stateDir + ? yield* makeProviderTokenUsageStore({ + stateDir: options.stateDir, + provider: "claude", + source: dataDir, + }) + : undefined; const readStatsCache = Effect.gen(function* () { const raw = yield* fileSystem @@ -226,7 +236,7 @@ export const makeClaudeTokenUsageHistoryReader = Effect.fn("ClaudeTokenUsageHist const transcriptDirExists = yield* fileSystem .exists(transcriptDir) .pipe(Effect.catchCause(() => Effect.succeed(false))); - if (!stats && !transcriptDirExists) return undefined; + if (!stats && !transcriptDirExists && !store) return undefined; const scanStartDate = clampDateKey( stats?.lastComputedDate ?? firstRetainedDate, @@ -238,30 +248,39 @@ export const makeClaudeTokenUsageHistoryReader = Effect.fn("ClaudeTokenUsageHist Effect.catchCause(() => Effect.succeed({ buckets: [], complete: false })), ) : { buckets: [], complete: false }; - if (!stats && !scan.complete) return undefined; - const allBucketsByDay = new Map( - (stats?.dailyBuckets ?? []).map((bucket) => [bucket.startDate, bucket] as const), - ); - if (scan.complete) { - for (const date of allBucketsByDay.keys()) { - if (date >= scanStartDate) allBucketsByDay.delete(date); - } - for (const bucket of scan.buckets) allBucketsByDay.set(bucket.startDate, bucket); - } - const allBuckets = [...allBucketsByDay.values()].toSorted((left, right) => - left.startDate.localeCompare(right.startDate), + // A day takes the larger of the stats cache and the transcripts. The + // cache's last day may have been computed mid-day, and a transcript it + // counted may be deleted since; a partial scan is still a lower bound. + const statsTokensByDay = new Map( + (stats?.dailyBuckets ?? []).map((bucket) => [bucket.startDate, bucket.tokens] as const), ); + const observedBuckets = [ + ...mergeTokenUsageDays([ + statsTokensByDay, + scan.buckets.map((bucket) => [bucket.startDate, bucket.tokens] as const), + ]), + ] + .map(([startDate, tokens]) => ({ startDate, tokens })) + .toSorted((left, right) => left.startDate.localeCompare(right.startDate)); + const allBuckets = store ? yield* store.remember(observedBuckets, today) : observedBuckets; + if (!stats && !scan.complete && (!store || allBuckets.length === 0)) return undefined; const retainedBuckets = retainProviderTokenUsageBuckets(allBuckets, today); - const statsReplacedTokens = sumBuckets( - (stats?.dailyBuckets ?? []).filter((bucket) => bucket.startDate >= scanStartDate), - ); + // Claude's own total, plus what the calendar knows beyond its daily + // figures. Each day only grows, so the total never goes down when a + // transcript is deleted. const lifetimeTokens = - stats?.lifetimeTokens !== undefined - ? Math.max(0, stats.lifetimeTokens - statsReplacedTokens) + - (scan.complete ? sumBuckets(scan.buckets) : statsReplacedTokens) - : sumBuckets(allBuckets); + (stats?.lifetimeTokens ?? 0) + + allBuckets.reduce( + (sum, bucket) => + sum + Math.max(0, bucket.tokens - (statsTokensByDay.get(bucket.startDate) ?? 0)), + 0, + ); + const lastBucketDate = retainedBuckets.at(-1)?.startDate; + const statsEndDate = stats?.lastComputedDate + ? clampDateKey(stats.lastComputedDate, firstRetainedDate, today) + : undefined; const coverageStartDate = scan.complete ? firstRetainedDate : stats?.firstSessionDate @@ -269,9 +288,11 @@ export const makeClaudeTokenUsageHistoryReader = Effect.fn("ClaudeTokenUsageHist : retainedBuckets[0]?.startDate; const coverageEndDate = scan.complete ? today - : stats?.lastComputedDate - ? clampDateKey(stats.lastComputedDate, firstRetainedDate, today) - : undefined; + : statsEndDate && lastBucketDate + ? statsEndDate > lastBucketDate + ? statsEndDate + : lastBucketDate + : (statsEndDate ?? lastBucketDate); const completeLifetimeHistory = Boolean( stats?.firstSessionDate && stats.firstSessionDate >= firstRetainedDate && diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 5bb07927a..3d0302175 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -3642,6 +3642,75 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T }), ); + it.effect("keeps days whose Claude transcripts were deleted", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const homePath = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "threadlines-claude-history-", + }); + const stateDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "threadlines-state-", + }); + const projectDir = path.join(homePath, ".claude", "projects", "project"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + const now = new Date(); + yield* TestClock.setTime(now.getTime()); + const today = now.toISOString().slice(0, 10); + const oldDay = new Date(now.getTime() - 60 * 86_400_000); + const writeTranscript = (name: string, at: Date, tokens: number) => + fileSystem.writeFileString( + path.join(projectDir, `${name}.jsonl`), + `${JSON.stringify({ + type: "assistant", + timestamp: at.toISOString(), + sessionId: name, + requestId: `request-${name}`, + message: { + id: `message-${name}`, + model: "claude-opus-4-6", + usage: { input_tokens: tokens, output_tokens: 0 }, + }, + })}\n`, + ); + yield* writeTranscript("old", oldDay, 700); + yield* writeTranscript("new", now, 30); + const settings = { homePath, accountFolder: "" }; + // Two readers of one folder: two instances, or one replaced by a settings change. + const readA = yield* makeClaudeTokenUsageHistoryReader(settings, {}, { stateDir }); + const readB = yield* makeClaudeTokenUsageHistoryReader(settings, {}, { stateDir }); + + const first = yield* readA; + assert.deepStrictEqual(first?.dailyBuckets, [ + { startDate: oldDay.toISOString().slice(0, 10), tokens: 700 }, + { startDate: today, tokens: 30 }, + ]); + + // Claude Code's cleanup deletes the old transcript before the other reader runs. + yield* fileSystem.remove(path.join(projectDir, "old.jsonl")); + yield* writeTranscript("newer", now, 5); + const second = yield* readB; + assert.deepStrictEqual(second?.dailyBuckets, [ + { startDate: oldDay.toISOString().slice(0, 10), tokens: 700 }, + { startDate: today, tokens: 35 }, + ]); + + assert.strictEqual(second?.summary.lifetimeTokens, 735); + + // What a restarted server reads back. + const historyDir = path.join(stateDir, "provider-token-history"); + const historyFiles = yield* fileSystem.readDirectory(historyDir); + assert.strictEqual(historyFiles.length, 1); + const saved = JSON.parse( + yield* fileSystem.readFileString(path.join(historyDir, historyFiles[0] ?? "")), + ) as { readonly days: Record }; + assert.deepStrictEqual(saved.days, { + [oldDay.toISOString().slice(0, 10)]: 700, + [today]: 35, + }); + }), + ); + it.effect("does not request account usage for API key auth", () => Effect.gen(function* () { let usageRequested = false; diff --git a/apps/server/src/provider/providerTokenUsageStore.ts b/apps/server/src/provider/providerTokenUsageStore.ts new file mode 100644 index 000000000..e647f78eb --- /dev/null +++ b/apps/server/src/provider/providerTokenUsageStore.ts @@ -0,0 +1,188 @@ +/** + * Saved daily token totals for usage history that a provider reads from local + * files the provider itself deletes over time. Claude Code removes transcripts + * `cleanupPeriodDays` (30 by default) after they were last written, so a + * calendar built only from what is on disk shrinks to about a month. + * + * Each read folds what it saw into the saved days and gets the union back, so a + * day keeps its total after its files are gone. A day only ever grows: a lower + * reading for a saved day means files went missing, not that usage went down. + * + * The file lives in the server's state folder (one per source folder), apart + * from the provider status cache: a status check that comes back signed out or + * unknown can't wipe it, and a dev server never writes the installed app's copy. + * + * @module provider/providerTokenUsageStore + */ +import { createHash } from "node:crypto"; + +import type { ServerProviderAccountTokenUsageDailyBucket } from "@threadlines/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; + +import { writeFileStringAtomically } from "../atomicWrite.ts"; +import { + parseProviderTokenUsageDateKey, + PROVIDER_TOKEN_USAGE_RETENTION_DAYS, + shiftProviderTokenUsageDateKey, +} from "./providerTokenUsageHistory.ts"; + +/** Folder under the server's state folder that holds the saved histories. */ +export const PROVIDER_TOKEN_HISTORY_DIR_NAME = "provider-token-history"; + +const SavedTokenHistory = Schema.Struct({ + version: Schema.Literal(1), + source: Schema.String, + days: Schema.Record(Schema.String, Schema.Number), +}); +type SavedTokenHistory = typeof SavedTokenHistory.Type; + +const decodeSavedTokenHistory = Schema.decodeUnknownEffect( + Schema.fromJsonString(SavedTokenHistory), +); + +type DayTotals = ReadonlyMap; + +/** + * Merge readings by day, keeping the larger total for a day both have. + * Days before `firstDateKey` are left out when it is given. + */ +export const mergeTokenUsageDays = ( + readings: ReadonlyArray>, + firstDateKey?: string, +): Map => { + const merged = new Map(); + for (const reading of readings) { + for (const [dateKey, tokens] of reading) { + if (firstDateKey !== undefined && dateKey < firstDateKey) continue; + merged.set(dateKey, Math.max(merged.get(dateKey) ?? 0, tokens)); + } + } + return merged; +}; + +const sameDays = (left: DayTotals, right: DayTotals): boolean => + left.size === right.size && [...left].every(([dateKey, tokens]) => right.get(dateKey) === tokens); + +const toBuckets = (days: DayTotals): ReadonlyArray => + [...days] + .map(([startDate, tokens]) => ({ startDate, tokens })) + .toSorted((left, right) => left.startDate.localeCompare(right.startDate)); + +// Every reader of one history file goes through the same lock and the same +// in-memory days, so two readers of one Claude folder (two instances, or an +// instance and its replacement after a settings change) can't overwrite each +// other from stale copies. The days also hold what a failed save left out. +const fileLocks = new Map(); +const sessionDays = new Map>(); + +/** + * Open the saved history for one source folder. `remember` merges a fresh + * reading into it, saves the last 366 days, and returns every day from the + * reading and the saved history together, sorted by date. + */ +export const makeProviderTokenUsageStore = Effect.fn("makeProviderTokenUsageStore")( + function* (input: { + /** The server's state folder (`ServerConfig.stateDir`). */ + readonly stateDir: string; + /** Names the history, e.g. `claude`. Part of the file name. */ + readonly provider: string; + /** The folder the readings come from. Different folders keep different histories. */ + readonly source: string; + }) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const sourceHash = createHash("sha256").update(input.source).digest("hex").slice(0, 16); + const filePath = path.join( + input.stateDir, + PROVIDER_TOKEN_HISTORY_DIR_NAME, + `${input.provider}-${sourceHash}.json`, + ); + let lock = fileLocks.get(filePath); + if (!lock) { + lock = Semaphore.makeUnsafe(1); + fileLocks.set(filePath, lock); + } + + // Read fresh on every use. `writable` is false when the file can't be read + // right now or holds something this build doesn't understand (a newer + // format, a damaged file): it is left alone and tried again next time. + const load = Effect.gen(function* () { + const exists = yield* fileSystem.exists(filePath).pipe(Effect.orElseSucceed(() => true)); + if (!exists) return { days: new Map(), writable: true }; + const raw = yield* fileSystem + .readFileString(filePath) + .pipe(Effect.catchCause(() => Effect.succeed(undefined))); + if (raw === undefined) return { days: new Map(), writable: false }; + return yield* decodeSavedTokenHistory(raw).pipe( + Effect.map((document) => ({ + days: mergeTokenUsageDays([ + Object.entries(document.days).filter( + ([dateKey, tokens]) => + parseProviderTokenUsageDateKey(dateKey) !== null && + Number.isSafeInteger(tokens) && + tokens >= 0, + ), + ]), + writable: true, + })), + Effect.catchCause(() => + Effect.logWarning("saved token history is unreadable, leaving it alone", { + path: filePath, + }).pipe(Effect.as({ days: new Map(), writable: false })), + ), + ); + }); + + const save = (days: DayTotals) => + writeFileStringAtomically({ + filePath, + contents: `${JSON.stringify({ + version: 1, + source: input.source, + days: Object.fromEntries(days), + } satisfies SavedTokenHistory)}\n`, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.catchCause((cause) => + Effect.logWarning("could not save token history", { path: filePath, cause }), + ), + ); + + const remember = ( + reading: ReadonlyArray, + todayDateKey: string, + ): Effect.Effect> => + lock.withPermits(1)( + Effect.gen(function* () { + const file = yield* load; + const readingDays = reading.map((bucket) => [bucket.startDate, bucket.tokens] as const); + const firstKept = shiftProviderTokenUsageDateKey( + todayDateKey, + -(PROVIDER_TOKEN_USAGE_RETENTION_DAYS - 1), + ); + const kept = new Map( + [ + ...mergeTokenUsageDays( + [file.days, sessionDays.get(filePath) ?? [], readingDays], + firstKept, + ), + ] + .filter(([dateKey]) => dateKey <= todayDateKey) + .toSorted(([left], [right]) => left.localeCompare(right)), + ); + sessionDays.set(filePath, kept); + if (file.writable && !sameDays(kept, file.days)) yield* save(kept); + // Older days in the reading (Claude's own stats cache keeps them) + // still count toward streaks, so they come back too. + return toBuckets(mergeTokenUsageDays([readingDays, kept])); + }), + ); + + return { filePath, remember } as const; + }, +);