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

accountUsage.test.ts

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