Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

accountUsage.test.ts

432 lines17.5 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Layer from "effect/Layer";
4import { assert, describe, it } from "@effect/vitest";
5import * as Context from "effect/Context";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as FetchHttpClient from "effect/http/FetchHttpClient";
10import * as HttpClient from "effect/http/HttpClient";
11import * as HttpClientError from "effect/http/HttpClientError";
12import * as HttpClientResponse from "effect/http/HttpClientResponse";
13import * as Path from "effect/Path";
14import * as TestClock from "effect/testing/TestClock";
15​
16import * as CursorKeychain from "./CursorKeychain.ts";
17import { readCursorAccountUsage } from "./accountUsage.ts";
18​
19const writeAuth = (accessToken: string) =>
20 Effect.gen(function* () {
21 const fileSystem = yield* FileSystem.FileSystem;
22 const path = yield* Path.Path;
23 const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "usage-reader-test-" });
24 const authPath = path.join(dir, "auth.json");
25 yield* fileSystem.writeFileString(authPath, JSON.stringify({ accessToken }));
26 return { dir, authPath };
27 });
28​
29interface DashboardRequest {
30 readonly url: string;
31 readonly init: RequestInit;
32 readonly page: number;
33 readonly headers: Headers;
35​
36const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Response>) =>
37 HttpClient.make((request, url, signal, fiber) =>
38 Effect.tryPromise({
39 try: async () => {
40 const init = Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit);
41 const body =
42 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
43 const response = await answer({
44 url: url.toString(),
45 init: { ...init, signal, body },
46 page: JSON.parse(body).page,
47 headers: new Headers(request.headers),
48 });
49 return HttpClientResponse.fromWeb(request, response);
50 },
51 catch: (cause) =>
52 new HttpClientError.HttpClientError({
53 reason: new HttpClientError.TransportError({ request, cause }),
54 }),
55 }),
56 );
57​
58const readAccountUsage = (
59 credentialSource: Parameters<typeof readCursorAccountUsage>[0],
60 sinceMs: number,
61 endDate: number,
62 answer: (request: DashboardRequest) => Response | Promise<Response>,
63 keychainToken?: Parameters<typeof readCursorAccountUsage>[3],
64) =>
65 readCursorAccountUsage(credentialSource, sinceMs, endDate, keychainToken).pipe(
66 Effect.provideService(HttpClient.HttpClient, dashboard(answer)),
67 );
68​
69describe("Cursor account history", () => {
70 it.effect(
71 "reads paginated Cursor account history including headless calls with separate cache tokens",
72 () =>
73 Effect.gen(function* () {
74 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp: 4102444800 })).toString("base64url")}.signature`;
75 const { authPath } = yield* writeAuth(accessToken);
76 const pages: number[] = [];
77 const signals: AbortSignal[] = [];
78 const request = ({ url, init, headers, page }: DashboardRequest) => {
79 assert.strictEqual(url, "https://cursor.com/api/dashboard/get-filtered-usage-events");
80 assert.strictEqual(init.redirect, "error");
81 assert.strictEqual(headers.get("origin"), "https://cursor.com");
82 assert.strictEqual(headers.get("content-type"), "application/json");
83 assert.include(headers.get("cookie") ?? "", "WorkosCursorSessionToken=demo%3A%3A");
84 const body = { page };
85 pages.push(body.page);
86 if (init.signal) signals.push(init.signal);
87 return Response.json({
88 totalUsageEventsCount: 1001,
89 usageEventsDisplay: Array.from({ length: body.page === 1 ? 1000 : 1 }, (_, index) => ({
90 timestamp: String(1780000000000 + ((body.page - 1) * 1000 + index) * 1000),
91 model: "claude-sonnet-4-5",
92 conversationId: `conversation-${body.page}`,
93 isHeadless: body.page === 2,
94 chargedCents: 0,
95 tokenUsage: {
96 inputTokens: 10,
97 outputTokens: 5,
98 cacheReadTokens: 30,
99 cacheWriteTokens: 2,
100 totalCents: 25,
101 },
102 })),
103 });
104 };
105 const result = yield* readAccountUsage(authPath, 0, 1781000000000, request);
106 assert.isNull(result.error);
107 assert.deepStrictEqual(pages, [1, 2]);
108 assert.lengthOf(signals, 2);
109 assert.notStrictEqual(signals[0], signals[1]);
110 assert.strictEqual(result.records.length, 1001);
111 assert.strictEqual(result.records.at(-1)?.sessionId, "conversation-2");
112 assert.deepStrictEqual(result.records[0]?.totals, {
113 uncachedInputTokens: 10,
114 cachedInputTokens: 30,
115 cacheCreationTokens: 2,
116 outputTokens: 5,
117 reasoningTokens: 0,
118 });
119 assert.strictEqual(result.records[0]?.reportedCostUsd, 0.25);
120 assert.isFalse(result.accountKey?.includes("demo") ?? true);
121 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
122 );
123​
124 it.effect("reads Cursor account history beyond 100 pages", () =>
125 Effect.gen(function* () {
126 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
127 const { authPath } = yield* writeAuth(accessToken);
128 const fullPage = Array.from({ length: 1000 }, () => ({ tokenUsage: null }));
129 let requests = 0;
130 const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
131 requests += 1;
132 return Response.json({
133 totalUsageEventsCount: 100_001,
134 usageEventsDisplay: requests <= 100 ? fullPage : [{ tokenUsage: null }],
135 });
136 });
137 assert.isNull(result.error);
138 assert.strictEqual(requests, 101);
139 assert.deepStrictEqual(result.records, []);
140 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
141 );
142​
143 it.effect("accepts confirmed empty Cursor usage but rejects error envelopes", () =>
144 Effect.gen(function* () {
145 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
146 const { authPath } = yield* writeAuth(accessToken);
147 for (const body of [
148 {},
149 { totalUsageEventsCount: 0 },
150 { totalUsageEventsCount: 0, usageEventsDisplay: [] },
151 ]) {
152 const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () =>
153 Response.json(body),
154 );
155 assert.isNull(result.error);
156 assert.deepStrictEqual(result.records, []);
157 assert.isFalse(result.missing);
158 }
159 for (const body of [
160 { error: "upstream error" },
161 { detail: "unknown error envelope" },
162 { totalUsageEventsCount: 0, error: "upstream error" },
163 null,
164 [],
165 "invalid",
166 0,
167 ]) {
168 const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () =>
169 Response.json(body),
170 );
171 assert.isNotNull(result.error);
172 assert.deepStrictEqual(result.records, []);
173 }
174 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
175 );
176​
177 it.effect("requires a terminal Cursor page after a full page reaches the reported count", () =>
178 Effect.gen(function* () {
179 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
180 const { authPath } = yield* writeAuth(accessToken);
181 let requests = 0;
182 const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
183 requests++;
184 return Response.json(
185 requests === 1
186 ? {
187 totalUsageEventsCount: 1000,
188 usageEventsDisplay: Array.from({ length: 1000 }, (_, index) => ({
189 timestamp: String(1780000000000 + index),
190 model: "gpt-5",
191 tokenUsage: { inputTokens: 10, outputTokens: 5 },
192 })),
193 }
194 : { totalUsageEventsCount: 1000 },
195 );
196 });
197 assert.isNull(result.error);
198 assert.strictEqual(result.records.length, 1000);
199 assert.strictEqual(requests, 2);
200 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
201 );
202​
203 it.effect(
204 "removes only count-proven Cursor boundary copies and preserves identical billed events",
205 () =>
206 Effect.gen(function* () {
207 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
208 const { authPath } = yield* writeAuth(accessToken);
209 const event = (index: number) => ({
210 timestamp: String(1780000000000 + index),
211 model: "gpt-5",
212 tokenUsage: { inputTokens: 10, outputTokens: 5, totalCents: 1 },
213 });
214 for (const total of [2000, 2001]) {
215 let requests = 0;
216 const result = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
217 requests++;
218 return Response.json({
219 totalUsageEventsCount: total,
220 usageEventsDisplay:
221 requests === 1
222 ? Array.from({ length: 1000 }, (_, index) => event(index))
223 : requests === 2
224 ? Array.from({ length: 1000 }, (_, index) => event(999 + index))
225 : [event(1999)],
226 });
227 });
228 assert.isNull(result.error);
229 assert.strictEqual(result.records.length, total);
230 assert.strictEqual(requests, 3);
231 assert.strictEqual(result.records.at(-1)?.timestampMs, 1780000001999);
232 assert.strictEqual(
233 result.records.filter((record) => record.timestampMs === 1780000000999).length,
234 total === 2000 ? 1 : 2,
235 );
236 assert.strictEqual(new Set(result.records.map((record) => record.dedupeKey)).size, total);
237 }
238 let requests = 0;
239 const inconsistent = yield* readAccountUsage(authPath, 0, 1781000000000, async () => {
240 requests++;
241 return Response.json({
242 totalUsageEventsCount: 1001,
243 usageEventsDisplay:
244 requests === 1
245 ? Array.from({ length: 1000 }, (_, index) => event(index))
246 : [event(500), event(1000)],
247 });
248 });
249 assert.isNotNull(inconsistent.error);
250 assert.deepStrictEqual(inconsistent.records, []);
251 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
252 );
253​
254 it.effect(
255 "does not present truncated Cursor account pages or authentication failures as complete history",
256 () =>
257 Effect.gen(function* () {
258 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp: 4102444800 })).toString("base64url")}.signature`;
259 const { dir, authPath } = yield* writeAuth(accessToken);
260 const truncated = yield* readAccountUsage(authPath, 0, 1781000000000, async () =>
261 Response.json({ totalUsageEventsCount: 101, usageEventsDisplay: [] }),
262 );
263 assert.isNotNull(truncated.error);
264 assert.deepStrictEqual(truncated.records, []);
265 const denied = yield* readAccountUsage(
266 authPath,
267 0,
268 1781000000000,
269 async () => new Response(accessToken, { status: 401 }),
270 );
271 assert.isNotNull(denied.error);
272 assert.isFalse(denied.error?.includes(accessToken) ?? true);
273 assert.deepStrictEqual(denied.records, []);
274 let requested = false;
275 const missing = yield* readAccountUsage(
276 (yield* Path.Path).join(dir, "missing.json"),
277 0,
278 1781000000000,
279 async () => {
280 requested = true;
281 return Response.json({});
282 },
283 );
284 assert.isTrue(missing.missing);
285 assert.isFalse(requested);
286 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
287 );
288});
289​
290describe("readCursorAccountUsage", () => {
291 it.effect("reads an API key's account history through Cursor's API", () =>
292 Effect.gen(function* () {
293 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
294 const requests: Array<readonly [string, string | null]> = [];
295 const result = yield* readAccountUsage(
296 { kind: "apiKey", apiKey: "api-key" },
297 0,
298 1781000000000,
299 ({ url, headers }) => {
300 requests.push([url, headers.get("authorization")]);
301 return url.endsWith("/auth/exchange_user_api_key")
302 ? Response.json({ accessToken })
303 : Response.json({
304 totalUsageEventsCount: 1,
305 usageEventsDisplay: [
306 { timestamp: "1780000000000", model: "gpt-5", tokenUsage: { outputTokens: 4 } },
307 ],
308 });
309 },
310 );
311 assert.isNull(result.error);
312 assert.deepStrictEqual(requests, [
313 ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"],
314 [
315 "https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents",
316 `Bearer ${accessToken}`,
317 ],
318 ]);
319 assert.strictEqual(result.records[0]?.totals.outputTokens, 4);
320 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
321 );
322​
323 it.effect("stops waiting for an API key exchange that never answers", () =>
324 Effect.gen(function* () {
325 const read = yield* Effect.forkChild(
326 readAccountUsage(
327 { kind: "apiKey", apiKey: "api-key" },
328 0,
329 1781000000000,
330 () => new Promise<Response>(() => {}),
331 ),
332 );
333 yield* TestClock.adjust("10 seconds");
334 const result = yield* Fiber.join(read);
335 assert.strictEqual(result.error, "Cursor account usage could not be read.");
336 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
337 );
338​
339 it.effect("asks for Keychain approval when the prompt goes unanswered", () =>
340 Effect.gen(function* () {
341 const result = yield* readAccountUsage(
342 { kind: "keychain" },
343 0,
344 1,
345 () => {
346 throw new Error("no network expected");
347 },
348 Effect.fail(new CursorKeychain.CursorKeychainTimeoutError()),
349 );
350 assert.deepStrictEqual(result, {
351 accountKey: null,
352 records: [],
353 missing: false,
354 error: "Allow Keychain access on the Mac running T3 Code, then refresh.",
355 });
356 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
357 );
358​
359 it.effect("reads the pages behind the first together and keeps them in page order", () =>
360 Effect.gen(function* () {
361 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
362 let inFlight = 0;
363 let mostInFlight = 0;
364 const result = yield* readAccountUsage(
365 { kind: "keychain" },
366 0,
367 1781000000000,
368 async ({ page }) => {
369 inFlight++;
370 mostInFlight = Math.max(mostInFlight, inFlight);
371 for (let turn = page; turn < 9; turn++) await Promise.resolve();
372 inFlight--;
373 return Response.json({
374 totalUsageEventsCount: 8001,
375 usageEventsDisplay: Array.from({ length: page === 9 ? 1 : 1000 }, (_, index) => ({
376 timestamp: String(1780000000000 + (page - 1) * 1000 + index),
377 model: "gpt-5",
378 tokenUsage: { inputTokens: 1 },
379 })),
380 });
381 },
382 Effect.succeed(accessToken),
383 );
384 assert.isNull(result.error);
385 assert.strictEqual(mostInFlight, 6);
386 assert.deepStrictEqual(
387 result.records.map((record) => record.timestampMs),
388 Array.from({ length: 8001 }, (_, index) => 1780000000000 + index),
389 );
390 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
391 );
392​
393 it.effect("ends like a page-by-page read when a page fails, leaving no request open", () =>
394 Effect.gen(function* () {
395 const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
396 const fullPage = {
397 totalUsageEventsCount: 8001,
398 usageEventsDisplay: Array.from({ length: 1000 }, () => ({ tokenUsage: null })),
399 };
400 for (const [secondPage, error] of [
401 [() => Response.json(fullPage), "Cursor account usage could not be read."],
402 [
403 () => new Response(null, { status: 401 }),
404 "Sign in to Cursor again to read account usage.",
405 ],
406 ] as const) {
407 let open = 0;
408 const result = yield* readAccountUsage(
409 { kind: "keychain" },
410 0,
411 1781000000000,
412 ({ init, page }) => {
413 if (page === 1) return Promise.resolve(Response.json(fullPage));
414 if (page === 2) return Promise.resolve(secondPage());
415 if (page === 3) return Promise.reject(new Error("connection reset"));
416 open++;
417 return new Promise((_resolve, reject) => {
418 init.signal?.addEventListener("abort", () => {
419 open--;
420 reject(init.signal?.reason);
421 });
422 });
423 },
424 Effect.succeed(accessToken),
425 );
426 assert.strictEqual(result.error, error);
427 assert.deepStrictEqual(result.records, []);
428 assert.strictEqual(open, 0);
429 }
430 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
431 );
432});