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

accountUsage.test.ts

430 lines17.1 KB

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