Skip to content

Commit 393a8f3

Browse files
committed
fix(usage): handle paginated and aliased history
1 parent f9c6a28 commit 393a8f3

5 files changed

Lines changed: 83 additions & 16 deletions

File tree

‎apps/server/src/usage/UsageService.test.ts‎

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,10 @@ describe("UsageService", () => {
212212
summary.sources.find((source) => source.fingerprint.provider === "cursor")?.status,
213213
"missing",
214214
);
215-
assert.strictEqual(summary.buckets[0]?.sourcePath, root);
215+
assert.strictEqual(
216+
summary.buckets[0]?.sourcePath,
217+
yield* Effect.promise(() => NodeFSP.realpath(root)),
218+
);
216219
assert.strictEqual(summary.buckets[0]?.totals.outputTokens, 7);
217220
assert.strictEqual(
218221
summary.sources.find((source) => source.fingerprint.provider === "opencode")
@@ -226,6 +229,60 @@ describe("UsageService", () => {
226229
}).pipe(Effect.scoped),
227230
);
228231

232+
it.live("counts aliased OpenCode and Antigravity directories once", () =>
233+
Effect.gen(function* () {
234+
const { settings, home } = yield* setup;
235+
const opencode = NodePath.join(home, "opencode-store");
236+
const opencodeAlias = NodePath.join(home, "opencode-alias");
237+
const conversations = NodePath.join(home, "antigravity-conversations");
238+
const antigravityA = NodePath.join(home, "antigravity-a");
239+
const antigravityB = NodePath.join(home, "antigravity-b");
240+
yield* Effect.promise(async () => {
241+
await NodeFSP.mkdir(opencode);
242+
await NodeFSP.symlink(opencode, opencodeAlias, "junction");
243+
await NodeFSP.mkdir(conversations);
244+
await NodeFSP.mkdir(antigravityA);
245+
await NodeFSP.mkdir(antigravityB);
246+
await NodeFSP.symlink(
247+
conversations,
248+
NodePath.join(antigravityA, "conversations"),
249+
"junction",
250+
);
251+
await NodeFSP.symlink(
252+
conversations,
253+
NodePath.join(antigravityB, "conversations"),
254+
"junction",
255+
);
256+
});
257+
const service = yield* UsageService.make.pipe(
258+
Effect.provide(
259+
serviceLayers({
260+
prefix: "usage-service-aliased-roots-test",
261+
home,
262+
settings,
263+
environment: {
264+
OPENCODE_DATA_DIR: `${opencode},${opencodeAlias}`,
265+
ANTIGRAVITY_DATA_DIR: `${antigravityA},${antigravityB}`,
266+
},
267+
}),
268+
),
269+
);
270+
const summary = yield* service.readSummary(WINDOW);
271+
const sourcesFor = (provider: "opencode" | "antigravity") =>
272+
summary.sources.filter((source) => source.fingerprint.provider === provider);
273+
assert.strictEqual(sourcesFor("opencode").length, 1);
274+
assert.strictEqual(sourcesFor("antigravity").length, 1);
275+
assert.strictEqual(
276+
sourcesFor("opencode")[0]?.fingerprint.resolvedHomePath,
277+
yield* Effect.promise(() => NodeFSP.realpath(opencode)),
278+
);
279+
assert.strictEqual(
280+
sourcesFor("antigravity")[0]?.fingerprint.resolvedHomePath,
281+
yield* Effect.promise(() => NodeFSP.realpath(conversations)),
282+
);
283+
}).pipe(Effect.scoped),
284+
);
285+
229286
it.live("reads configured and disabled accounts once across shared and aliased homes", () =>
230287
Effect.gen(function* () {
231288
const { transcript, settings, home } = yield* setup;

‎apps/server/src/usage/UsageService.ts‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -494,19 +494,22 @@ export const make = Effect.gen(function* () {
494494
}
495495

496496
const home = NodeOS.homedir();
497-
const envRoots = (key: string, defaults: readonly string[]) => {
497+
const envRoots = Effect.fnUntraced(function* (key: string, defaults: readonly string[]) {
498498
const roots = hostEnvironment[key]
499499
?.split(",")
500500
.map((value) => value.trim())
501501
.filter(Boolean);
502-
return [
503-
...new Set(
504-
(roots?.length ? roots : defaults).map((root) => path.resolve(expandHomePath(root))),
505-
),
506-
];
507-
};
502+
const canonical = new Set<string>();
503+
for (const root of roots?.length ? roots : defaults) {
504+
const resolved = path.resolve(expandHomePath(root));
505+
canonical.add(
506+
yield* fileSystem.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)),
507+
);
508+
}
509+
return [...canonical];
510+
});
508511
const dataHome = hostEnvironment["XDG_DATA_HOME"]?.trim();
509-
for (const dir of envRoots("OPENCODE_DATA_DIR", [
512+
for (const dir of yield* envRoots("OPENCODE_DATA_DIR", [
510513
path.join(
511514
dataHome && path.isAbsolute(dataHome) ? dataHome : path.join(home, ".local", "share"),
512515
"opencode",
@@ -522,7 +525,7 @@ export const make = Effect.gen(function* () {
522525
...(result.error ? { message: "Some OpenCode history could not be read." } : {}),
523526
});
524527
}
525-
const antigravityRoots = envRoots("ANTIGRAVITY_DATA_DIR", [
528+
const antigravityRoots = yield* envRoots("ANTIGRAVITY_DATA_DIR", [
526529
...["antigravity", "antigravity-cli", "antigravity-ide", "antigravity-backup"].map((name) =>
527530
path.join(home, ".gemini", name),
528531
),
@@ -549,14 +552,15 @@ export const make = Effect.gen(function* () {
549552
}
550553
}
551554
const antigravityDirs = new Set<string>();
552-
for (const root of new Set(antigravityRoots)) {
553-
const nested = path.join(root, "conversations");
555+
for (const root of antigravityRoots) {
556+
const resolvedRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root));
557+
const nested = path.join(resolvedRoot, "conversations");
554558
const dir = (yield* fileSystem
555559
.exists(nested)
556560
.pipe(Effect.catchCause(() => Effect.succeed(false))))
557561
? nested
558-
: root;
559-
antigravityDirs.add(dir);
562+
: resolvedRoot;
563+
antigravityDirs.add(yield* fileSystem.realPath(dir).pipe(Effect.orElseSucceed(() => dir)));
560564
}
561565
const antigravity = yield* Effect.promise(() =>
562566
readAntigravityUsage([...antigravityDirs], windowStartMs),

‎apps/server/src/usage/cursorUsageReader.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ export async function readCursorAccountUsage(
8383
accountKey = accountHash(subject);
8484
if (!Number.isFinite(sinceMs) || !Number.isFinite(endDate) || sinceMs < 0 || sinceMs > endDate)
8585
throw new Error("Invalid date window");
86-
const signal = AbortSignal.timeout(10_000);
86+
const deadline = AbortSignal.timeout(60_000);
8787
const records: UsageRecord[] = [];
8888
const occurrences = new Map<string, number>();
8989
const pages: unknown[][] = [];
@@ -94,7 +94,7 @@ export async function readCursorAccountUsage(
9494
const response = await request("https://cursor.com/api/dashboard/get-filtered-usage-events", {
9595
method: "POST",
9696
redirect: "error",
97-
signal,
97+
signal: AbortSignal.any([deadline, AbortSignal.timeout(10_000)]),
9898
headers: {
9999
"Content-Type": "application/json",
100100
Origin: "https://cursor.com",

‎apps/server/src/usage/usageTranscriptReader.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@ describe("SQLite usage readers", () => {
242242
const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp: 4102444800 })).toString("base64url")}.signature`;
243243
await NodeFSP.writeFile(authPath, JSON.stringify({ accessToken }));
244244
const pages: number[] = [];
245+
const signals: AbortSignal[] = [];
245246
const request = async (url: string, init: RequestInit) => {
246247
assert.strictEqual(String(url), "https://cursor.com/api/dashboard/get-filtered-usage-events");
247248
assert.strictEqual(init?.redirect, "error");
@@ -250,6 +251,7 @@ describe("SQLite usage readers", () => {
250251
assert.include(headers.get("cookie") ?? "", "WorkosCursorSessionToken=demo%3A%3A");
251252
const body = JSON.parse(String(init?.body));
252253
pages.push(body.page);
254+
if (init.signal) signals.push(init.signal);
253255
return Response.json({
254256
totalUsageEventsCount: 1001,
255257
usageEventsDisplay: Array.from({ length: body.page === 1 ? 1000 : 1 }, (_, index) => ({
@@ -271,6 +273,8 @@ describe("SQLite usage readers", () => {
271273
const result = await readCursorAccountUsage(authPath, 0, 1781000000000, request);
272274
assert.isNull(result.error);
273275
assert.deepStrictEqual(pages, [1, 2]);
276+
assert.lengthOf(signals, 2);
277+
assert.notStrictEqual(signals[0], signals[1]);
274278
assert.strictEqual(result.records.length, 1001);
275279
assert.strictEqual(result.records.at(-1)?.sessionId, "conversation-2");
276280
assert.deepStrictEqual(result.records[0]?.totals, {

‎docs/user/usage.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ Cursor reads account usage from Cursor's dashboard API using the CLI login saved
2121
This includes headless T3 sessions and desktop usage across machines; the same account counts
2222
once across connected environments. Without an accessible file-based CLI login, T3 shows a
2323
notice instead of incomplete local totals. T3 does not estimate missing tokens from conversation text.
24+
On macOS, [set up a file-based login](#track-subscription-limits) and set
25+
`AGENT_CLI_CREDENTIAL_STORE=file` on the server to enable Cursor history.
2426

2527
Usage includes each configured account's history, including disabled accounts. Custom homes follow
2628
the account's home setting or its `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, or `GROK_HOME` environment

0 commit comments

Comments
 (0)