Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/server/src/provider/Drivers/ClaudeDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,9 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
// 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,
Expand Down
79 changes: 50 additions & 29 deletions apps/server/src/provider/Layers/ClaudeTokenUsageHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand All @@ -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";
Expand Down Expand Up @@ -116,16 +118,17 @@ export function parseClaudeStatsTokenUsage(document: unknown): ClaudeStatsTokenU
};
}

const sumBuckets = (buckets: ReadonlyArray<ServerProviderAccountTokenUsageDailyBucket>): 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;

export const makeClaudeTokenUsageHistoryReader = Effect.fn("ClaudeTokenUsageHistory.makeReader")(
function* (
settings: Pick<ClaudeSettings, "homePath" | "accountFolder">,
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;
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -238,40 +248,51 @@ 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
? clampDateKey(stats.firstSessionDate, firstRetainedDate, today)
: 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 &&
Expand Down
69 changes: 69 additions & 0 deletions apps/server/src/provider/Layers/ProviderRegistry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, number> };
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;
Expand Down
Loading
Loading