The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import * as Layer from "effect/Layer"; |
| 4 | import { assert, describe, it } from "@effect/vitest"; |
| 5 | import * as Deferred from "effect/Deferred"; |
| 6 | import * as Queue from "effect/Queue"; |
| 7 | import * as Context from "effect/Context"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Fiber from "effect/Fiber"; |
| 10 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 11 | import * as HttpClient from "effect/http/HttpClient"; |
| 12 | import * as HttpClientError from "effect/http/HttpClientError"; |
| 13 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 14 | import * as TestClock from "effect/testing/TestClock"; |
| 15 | |
| 16 | import * as CursorAccountReader from "./CursorAccountReader.ts"; |
| 17 | |
| 18 | import { makeCursorAccountUsageReader } from "./accountUsage.ts"; |
| 19 | import type { CursorCredentialSource } from "./accountCache.ts"; |
| 20 | |
| 21 | interface DashboardRequest { |
| 22 | readonly url: string; |
| 23 | readonly init: RequestInit; |
| 24 | readonly page: number; |
| 25 | readonly headers: Headers; |
| 26 | } |
| 27 | |
| 28 | const dashboard = ( |
| 29 | answer: (request: DashboardRequest) => Response | Promise<Response>, |
| 30 | membership = { userId: 1, teamIds: [] as number[] }, |
| 31 | ) => |
| 32 | HttpClient.make((request, url, signal, fiber) => |
| 33 | Effect.tryPromise({ |
| 34 | try: async () => { |
| 35 | const init = Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit); |
| 36 | const body = |
| 37 | request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : ""; |
| 38 | if ( |
| 39 | url.pathname === "/auth/exchange_user_api_key" && |
| 40 | request.headers.authorization?.startsWith("Bearer header.") |
| 41 | ) { |
| 42 | return HttpClientResponse.fromWeb( |
| 43 | request, |
| 44 | Response.json({ accessToken: request.headers.authorization.slice(7) }), |
| 45 | ); |
| 46 | } |
| 47 | if (url.pathname.endsWith("/GetMe")) { |
| 48 | return HttpClientResponse.fromWeb(request, Response.json({ userId: membership.userId })); |
| 49 | } |
| 50 | if (url.pathname.endsWith("/GetTeams")) { |
| 51 | return HttpClientResponse.fromWeb( |
| 52 | request, |
| 53 | Response.json({ teams: membership.teamIds.map((id) => ({ id })) }), |
| 54 | ); |
| 55 | } |
| 56 | const response = await answer({ |
| 57 | url: url.toString(), |
| 58 | init: { ...init, signal, body }, |
| 59 | page: JSON.parse(body).page, |
| 60 | headers: new Headers(request.headers), |
| 61 | }); |
| 62 | return HttpClientResponse.fromWeb(request, response); |
| 63 | }, |
| 64 | catch: (cause) => |
| 65 | new HttpClientError.HttpClientError({ |
| 66 | reason: new HttpClientError.TransportError({ request, cause }), |
| 67 | }), |
| 68 | }), |
| 69 | ); |
| 70 | |
| 71 | const readAccountUsage = ( |
| 72 | credentialSource: CursorCredentialSource, |
| 73 | sinceMs: number, |
| 74 | endDate: number, |
| 75 | answer: (request: DashboardRequest) => Response | Promise<Response>, |
| 76 | membership?: { userId: number; teamIds: number[] }, |
| 77 | ) => |
| 78 | makeCursorAccountUsageReader.pipe( |
| 79 | Effect.flatMap((read) => read(credentialSource, sinceMs, endDate)), |
| 80 | Effect.provideService(HttpClient.HttpClient, dashboard(answer, membership)), |
| 81 | ); |
| 82 | |
| 83 | describe("Cursor account history", () => { |
| 84 | it.effect( |
| 85 | "reads paginated Cursor account history including headless calls with separate cache tokens", |
| 86 | () => |
| 87 | Effect.gen(function* () { |
| 88 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp: 4102444800 })).toString("base64url")}.signature`; |
| 89 | const credential = { kind: "apiKey", apiKey: accessToken } as const; |
| 90 | const pages: number[] = []; |
| 91 | const signals: AbortSignal[] = []; |
| 92 | const request = ({ url, init, headers, page }: DashboardRequest) => { |
| 93 | assert.strictEqual( |
| 94 | url, |
| 95 | "https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents", |
| 96 | ); |
| 97 | assert.strictEqual(init.redirect, "error"); |
| 98 | assert.strictEqual(headers.get("connect-protocol-version"), "1"); |
| 99 | assert.strictEqual(headers.get("content-type"), "application/json"); |
| 100 | assert.strictEqual(headers.get("authorization"), `Bearer ${accessToken}`); |
| 101 | const body = { page }; |
| 102 | pages.push(body.page); |
| 103 | if (init.signal) signals.push(init.signal); |
| 104 | return Response.json({ |
| 105 | totalUsageEventsCount: 1001, |
| 106 | usageEventsDisplay: Array.from({ length: body.page === 1 ? 1000 : 1 }, (_, index) => ({ |
| 107 | timestamp: String(1780000000000 + ((body.page - 1) * 1000 + index) * 1000), |
| 108 | model: "claude-sonnet-4-5", |
| 109 | conversationId: `conversation-${body.page}`, |
| 110 | isHeadless: body.page === 2, |
| 111 | chargedCents: 0, |
| 112 | tokenUsage: { |
| 113 | inputTokens: 10, |
| 114 | outputTokens: 5, |
| 115 | cacheReadTokens: 30, |
| 116 | cacheWriteTokens: 2, |
| 117 | totalCents: 25, |
| 118 | }, |
| 119 | })), |
| 120 | }); |
| 121 | }; |
| 122 | const result = yield* readAccountUsage(credential, 0, 1781000000000, request); |
| 123 | assert.isNull(result.error); |
| 124 | assert.deepStrictEqual(pages, [1, 2]); |
| 125 | assert.lengthOf(signals, 2); |
| 126 | assert.notStrictEqual(signals[0], signals[1]); |
| 127 | assert.strictEqual(result.records.length, 1001); |
| 128 | assert.strictEqual(result.records.at(-1)?.sessionId, "conversation-2"); |
| 129 | assert.deepStrictEqual(result.records[0]?.totals, { |
| 130 | uncachedInputTokens: 10, |
| 131 | cachedInputTokens: 30, |
| 132 | cacheCreationTokens: 2, |
| 133 | outputTokens: 5, |
| 134 | reasoningTokens: 0, |
| 135 | }); |
| 136 | assert.strictEqual(result.records[0]?.reportedCostUsd, 0.25); |
| 137 | assert.strictEqual( |
| 138 | result.records[0]?.dedupeKey, |
| 139 | "cursor-account:2188c26da759c4fae3aa0252fc6d725eff0922ef0b022551e6f0987d02bfab33:3149aaf8419ad6b66ef7330853d8fe85e6f2e9876e2ad5e85f88bee8c8d6d133:0", |
| 140 | ); |
| 141 | assert.isFalse(result.accountKey?.includes("demo") ?? true); |
| 142 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 143 | ); |
| 144 | |
| 145 | it.effect("includes each team's own-user history alongside personal history", () => |
| 146 | Effect.gen(function* () { |
| 147 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 148 | const scopes: unknown[] = []; |
| 149 | const result = yield* readAccountUsage( |
| 150 | { kind: "apiKey", apiKey: accessToken }, |
| 151 | 0, |
| 152 | 1781000000000, |
| 153 | async ({ init }) => { |
| 154 | const body = JSON.parse(String(init.body)); |
| 155 | scopes.push([body.teamId, body.userId]); |
| 156 | const team = body.teamId !== undefined; |
| 157 | return Response.json({ |
| 158 | totalUsageEventsCount: 1, |
| 159 | usageEventsDisplay: [ |
| 160 | { |
| 161 | timestamp: "1780000000000", |
| 162 | model: "gpt-5", |
| 163 | conversationId: "same-conversation", |
| 164 | tokenUsage: { cacheReadTokens: team ? 5_000_000 : 10 }, |
| 165 | }, |
| 166 | ], |
| 167 | }); |
| 168 | }, |
| 169 | { userId: 42, teamIds: [7, 8, 7] }, |
| 170 | ); |
| 171 | assert.isNull(result.error); |
| 172 | assert.deepStrictEqual(scopes, [ |
| 173 | [undefined, undefined], |
| 174 | [7, 42], |
| 175 | [8, 42], |
| 176 | ]); |
| 177 | assert.strictEqual( |
| 178 | result.records.reduce((sum, row) => sum + row.totals.cachedInputTokens, 0), |
| 179 | 10_000_010, |
| 180 | ); |
| 181 | assert.strictEqual(new Set(result.records.map((row) => row.dedupeKey)).size, 3); |
| 182 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 183 | ); |
| 184 | |
| 185 | it.effect("rejects unscoped or incomplete team history without keeping personal totals", () => |
| 186 | Effect.gen(function* () { |
| 187 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 188 | for (const userId of [0, 42]) { |
| 189 | const scopes: unknown[] = []; |
| 190 | const result = yield* readAccountUsage( |
| 191 | { kind: "apiKey", apiKey: accessToken }, |
| 192 | 0, |
| 193 | 1781000000000, |
| 194 | async ({ init }) => { |
| 195 | const body = JSON.parse(String(init.body)); |
| 196 | scopes.push(body.teamId); |
| 197 | return body.teamId === undefined |
| 198 | ? Response.json({ |
| 199 | totalUsageEventsCount: 1, |
| 200 | usageEventsDisplay: [ |
| 201 | { |
| 202 | timestamp: "1780000000000", |
| 203 | model: "gpt-5", |
| 204 | tokenUsage: { inputTokens: 10 }, |
| 205 | }, |
| 206 | ], |
| 207 | }) |
| 208 | : new Response(null, { status: 403 }); |
| 209 | }, |
| 210 | { userId, teamIds: [7] }, |
| 211 | ); |
| 212 | assert.isNotNull(result.error); |
| 213 | assert.deepStrictEqual(result.records, []); |
| 214 | assert.deepStrictEqual(scopes, userId === 0 ? [] : [undefined, 7]); |
| 215 | } |
| 216 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 217 | ); |
| 218 | |
| 219 | it.effect.each([ |
| 220 | { exp: undefined, lifetime: "5 minutes" }, |
| 221 | { exp: 90, lifetime: "1 minute" }, |
| 222 | ] as const)( |
| 223 | "reuses discovery for $lifetime, invalidates rejected auth, and isolates API keys", |
| 224 | ({ exp, lifetime }) => |
| 225 | Effect.gen(function* () { |
| 226 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp })).toString("base64url")}.signature`; |
| 227 | const requests: string[] = []; |
| 228 | let rejected = false; |
| 229 | const client = dashboard( |
| 230 | () => (rejected ? new Response(null, { status: 401 }) : Response.json({})), |
| 231 | { userId: 42, teamIds: [7] }, |
| 232 | ).pipe( |
| 233 | HttpClient.mapRequest((request) => { |
| 234 | requests.push(request.url.split("/").at(-1)!); |
| 235 | return request; |
| 236 | }), |
| 237 | ); |
| 238 | yield* Effect.gen(function* () { |
| 239 | const reader = yield* CursorAccountReader.CursorAccountReader; |
| 240 | const credential = { kind: "apiKey", apiKey: accessToken } as const; |
| 241 | assert.isNull((yield* reader.read(credential, 0, 1781000000000)).error); |
| 242 | requests.length = 0; |
| 243 | assert.isNull((yield* reader.read(credential, 0, 1781000000000)).error); |
| 244 | assert.deepStrictEqual(requests, ["GetFilteredUsageEvents", "GetFilteredUsageEvents"]); |
| 245 | rejected = true; |
| 246 | assert.isNotNull((yield* reader.read(credential, 0, 1781000000000)).error); |
| 247 | rejected = false; |
| 248 | requests.length = 0; |
| 249 | assert.isNull((yield* reader.read(credential, 0, 1781000000000)).error); |
| 250 | assert.include(requests, "GetTeams"); |
| 251 | requests.length = 0; |
| 252 | yield* TestClock.adjust(lifetime); |
| 253 | yield* reader.read(credential, 0, 1781000000000); |
| 254 | assert.include(requests, "GetTeams"); |
| 255 | requests.length = 0; |
| 256 | yield* reader.read({ ...credential, apiKey: accessToken + "other" }, 0, 1781000000000); |
| 257 | assert.include(requests, "GetTeams"); |
| 258 | }).pipe( |
| 259 | Effect.provide( |
| 260 | CursorAccountReader.layer.pipe( |
| 261 | Layer.provide(Layer.succeed(HttpClient.HttpClient, client)), |
| 262 | ), |
| 263 | ), |
| 264 | ); |
| 265 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 266 | ); |
| 267 | |
| 268 | it.effect("starts personal and team reads together without waiting for either response", () => |
| 269 | Effect.gen(function* () { |
| 270 | const personal = yield* Deferred.make<void>(); |
| 271 | const team = yield* Deferred.make<void>(); |
| 272 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 273 | const client = dashboard(() => Response.json({}), { userId: 42, teamIds: [7] }).pipe( |
| 274 | HttpClient.transform((response, request) => { |
| 275 | if (!request.url.endsWith("/GetFilteredUsageEvents")) return response; |
| 276 | const body = |
| 277 | request.body._tag === "Uint8Array" |
| 278 | ? JSON.parse(new TextDecoder().decode(request.body.body)) |
| 279 | : {}; |
| 280 | const isPersonal = body.teamId === undefined; |
| 281 | return Effect.gen(function* () { |
| 282 | yield* Deferred.succeed(isPersonal ? personal : team, undefined); |
| 283 | yield* Deferred.await(isPersonal ? team : personal); |
| 284 | return yield* response; |
| 285 | }); |
| 286 | }), |
| 287 | ); |
| 288 | const result = yield* makeCursorAccountUsageReader.pipe( |
| 289 | Effect.flatMap((read) => read({ kind: "apiKey", apiKey: accessToken }, 0, 1781000000000)), |
| 290 | Effect.provideService(HttpClient.HttpClient, client), |
| 291 | ); |
| 292 | assert.isNull(result.error); |
| 293 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 294 | ); |
| 295 | |
| 296 | it.effect("reads Cursor account history beyond 100 pages", () => |
| 297 | Effect.gen(function* () { |
| 298 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 299 | const credential = { kind: "apiKey", apiKey: accessToken } as const; |
| 300 | const fullPage = Array.from({ length: 1000 }, () => ({ tokenUsage: null })); |
| 301 | let requests = 0; |
| 302 | const result = yield* readAccountUsage(credential, 0, 1781000000000, async () => { |
| 303 | requests += 1; |
| 304 | return Response.json({ |
| 305 | totalUsageEventsCount: 100_001, |
| 306 | usageEventsDisplay: requests <= 100 ? fullPage : [{ tokenUsage: null }], |
| 307 | }); |
| 308 | }); |
| 309 | assert.isNull(result.error); |
| 310 | assert.strictEqual(requests, 101); |
| 311 | assert.deepStrictEqual(result.records, []); |
| 312 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 313 | ); |
| 314 | |
| 315 | it.effect("accepts confirmed empty Cursor usage but rejects error envelopes", () => |
| 316 | Effect.gen(function* () { |
| 317 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 318 | const credential = { kind: "apiKey", apiKey: accessToken } as const; |
| 319 | for (const body of [ |
| 320 | {}, |
| 321 | { totalUsageEventsCount: 0 }, |
| 322 | { totalUsageEventsCount: 0, usageEventsDisplay: [] }, |
| 323 | ]) { |
| 324 | const result = yield* readAccountUsage(credential, 0, 1781000000000, async () => |
| 325 | Response.json(body), |
| 326 | ); |
| 327 | assert.isNull(result.error); |
| 328 | assert.deepStrictEqual(result.records, []); |
| 329 | assert.isFalse(result.missing); |
| 330 | } |
| 331 | for (const body of [ |
| 332 | { error: "upstream error" }, |
| 333 | { detail: "unknown error envelope" }, |
| 334 | { totalUsageEventsCount: 0, error: "upstream error" }, |
| 335 | null, |
| 336 | [], |
| 337 | "invalid", |
| 338 | 0, |
| 339 | ]) { |
| 340 | const result = yield* readAccountUsage(credential, 0, 1781000000000, async () => |
| 341 | Response.json(body), |
| 342 | ); |
| 343 | assert.isNotNull(result.error); |
| 344 | assert.deepStrictEqual(result.records, []); |
| 345 | } |
| 346 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 347 | ); |
| 348 | |
| 349 | it.effect("requires a terminal Cursor page after a full page reaches the reported count", () => |
| 350 | Effect.gen(function* () { |
| 351 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 352 | const credential = { kind: "apiKey", apiKey: accessToken } as const; |
| 353 | let requests = 0; |
| 354 | const result = yield* readAccountUsage(credential, 0, 1781000000000, async () => { |
| 355 | requests++; |
| 356 | return Response.json( |
| 357 | requests === 1 |
| 358 | ? { |
| 359 | totalUsageEventsCount: 1000, |
| 360 | usageEventsDisplay: Array.from({ length: 1000 }, (_, index) => ({ |
| 361 | timestamp: String(1780000000000 + index), |
| 362 | model: "gpt-5", |
| 363 | tokenUsage: { inputTokens: 10, outputTokens: 5 }, |
| 364 | })), |
| 365 | } |
| 366 | : { totalUsageEventsCount: 1000 }, |
| 367 | ); |
| 368 | }); |
| 369 | assert.isNull(result.error); |
| 370 | assert.strictEqual(result.records.length, 1000); |
| 371 | assert.strictEqual(requests, 2); |
| 372 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 373 | ); |
| 374 | |
| 375 | it.effect( |
| 376 | "removes only count-proven Cursor boundary copies and preserves identical billed events", |
| 377 | () => |
| 378 | Effect.gen(function* () { |
| 379 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 380 | const credential = { kind: "apiKey", apiKey: accessToken } as const; |
| 381 | const event = (index: number) => ({ |
| 382 | timestamp: String(1780000000000 + index), |
| 383 | model: "gpt-5", |
| 384 | tokenUsage: { inputTokens: 10, outputTokens: 5, totalCents: 1 }, |
| 385 | }); |
| 386 | for (const total of [2000, 2001, undefined]) { |
| 387 | const expectedCount = total ?? 2001; |
| 388 | let requests = 0; |
| 389 | const result = yield* readAccountUsage(credential, 0, 1781000000000, async () => { |
| 390 | requests++; |
| 391 | return Response.json({ |
| 392 | totalUsageEventsCount: total, |
| 393 | usageEventsDisplay: |
| 394 | requests === 1 |
| 395 | ? Array.from({ length: 1000 }, (_, index) => event(index)) |
| 396 | : requests === 2 |
| 397 | ? Array.from({ length: 1000 }, (_, index) => { |
| 398 | const row = event(999 + index); |
| 399 | return { |
| 400 | tokenUsage: { |
| 401 | totalCents: row.tokenUsage.totalCents, |
| 402 | outputTokens: row.tokenUsage.outputTokens, |
| 403 | inputTokens: row.tokenUsage.inputTokens, |
| 404 | }, |
| 405 | model: row.model, |
| 406 | timestamp: row.timestamp, |
| 407 | }; |
| 408 | }) |
| 409 | : [event(1999)], |
| 410 | }); |
| 411 | }); |
| 412 | assert.isNull(result.error); |
| 413 | assert.strictEqual(result.records.length, expectedCount); |
| 414 | assert.strictEqual(requests, 3); |
| 415 | assert.strictEqual(result.records.at(-1)?.timestampMs, 1780000001999); |
| 416 | assert.strictEqual( |
| 417 | result.records.filter((record) => record.timestampMs === 1780000000999).length, |
| 418 | total === 2000 ? 1 : 2, |
| 419 | ); |
| 420 | assert.strictEqual( |
| 421 | new Set(result.records.map((record) => record.dedupeKey)).size, |
| 422 | expectedCount, |
| 423 | ); |
| 424 | } |
| 425 | let requests = 0; |
| 426 | const inconsistent = yield* readAccountUsage(credential, 0, 1781000000000, async () => { |
| 427 | requests++; |
| 428 | return Response.json({ |
| 429 | totalUsageEventsCount: 1001, |
| 430 | usageEventsDisplay: |
| 431 | requests === 1 |
| 432 | ? Array.from({ length: 1000 }, (_, index) => event(index)) |
| 433 | : [event(500), event(1000)], |
| 434 | }); |
| 435 | }); |
| 436 | assert.isNotNull(inconsistent.error); |
| 437 | assert.deepStrictEqual(inconsistent.records, []); |
| 438 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 439 | ); |
| 440 | |
| 441 | it.effect( |
| 442 | "does not present truncated Cursor account pages or authentication failures as complete history", |
| 443 | () => |
| 444 | Effect.gen(function* () { |
| 445 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo", exp: 4102444800 })).toString("base64url")}.signature`; |
| 446 | const credential = { kind: "apiKey", apiKey: accessToken } as const; |
| 447 | const truncated = yield* readAccountUsage(credential, 0, 1781000000000, async () => |
| 448 | Response.json({ totalUsageEventsCount: 101, usageEventsDisplay: [] }), |
| 449 | ); |
| 450 | assert.isNotNull(truncated.error); |
| 451 | assert.deepStrictEqual(truncated.records, []); |
| 452 | const denied = yield* readAccountUsage( |
| 453 | credential, |
| 454 | 0, |
| 455 | 1781000000000, |
| 456 | async () => new Response(accessToken, { status: 401 }), |
| 457 | ); |
| 458 | assert.isNotNull(denied.error); |
| 459 | assert.isFalse(denied.error?.includes(accessToken) ?? true); |
| 460 | assert.deepStrictEqual(denied.records, []); |
| 461 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 462 | ); |
| 463 | }); |
| 464 | |
| 465 | describe("readCursorAccountUsage", () => { |
| 466 | it.effect("reads an API key's account history through Cursor's API", () => |
| 467 | Effect.gen(function* () { |
| 468 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 469 | const requests: Array<readonly [string, string | null]> = []; |
| 470 | const result = yield* readAccountUsage( |
| 471 | { kind: "apiKey", apiKey: "api-key" }, |
| 472 | 0, |
| 473 | 1781000000000, |
| 474 | ({ url, headers }) => { |
| 475 | requests.push([url, headers.get("authorization")]); |
| 476 | return url.endsWith("/auth/exchange_user_api_key") |
| 477 | ? Response.json({ accessToken }) |
| 478 | : Response.json({ |
| 479 | totalUsageEventsCount: 1, |
| 480 | usageEventsDisplay: [ |
| 481 | { timestamp: "1780000000000", model: "gpt-5", tokenUsage: { outputTokens: 4 } }, |
| 482 | ], |
| 483 | }); |
| 484 | }, |
| 485 | ); |
| 486 | assert.isNull(result.error); |
| 487 | assert.deepStrictEqual(requests, [ |
| 488 | ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"], |
| 489 | [ |
| 490 | "https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents", |
| 491 | `Bearer ${accessToken}`, |
| 492 | ], |
| 493 | ]); |
| 494 | assert.strictEqual(result.records[0]?.totals.outputTokens, 4); |
| 495 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 496 | ); |
| 497 | |
| 498 | it.effect("stops waiting for an API key exchange that never answers", () => |
| 499 | Effect.gen(function* () { |
| 500 | const read = yield* Effect.forkChild( |
| 501 | readAccountUsage( |
| 502 | { kind: "apiKey", apiKey: "api-key" }, |
| 503 | 0, |
| 504 | 1781000000000, |
| 505 | () => new Promise<Response>(() => {}), |
| 506 | ), |
| 507 | ); |
| 508 | yield* TestClock.adjust("10 seconds"); |
| 509 | const result = yield* Fiber.join(read); |
| 510 | assert.strictEqual(result.error, "Cursor account usage could not be read."); |
| 511 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 512 | ); |
| 513 | |
| 514 | it.effect.each([{ queued: false }, { queued: true }])( |
| 515 | "reads concurrent pages in order with a full request deadline after queuing: $queued", |
| 516 | ({ queued }) => |
| 517 | Effect.gen(function* () { |
| 518 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 519 | const started = yield* Queue.unbounded<void>(); |
| 520 | const firstBatch = yield* Deferred.make<void>(); |
| 521 | const secondBatch = yield* Deferred.make<void>(); |
| 522 | let delayedRequests = 0; |
| 523 | let inFlight = 0; |
| 524 | let mostInFlight = 0; |
| 525 | const client = dashboard( |
| 526 | async ({ page }) => { |
| 527 | inFlight++; |
| 528 | mostInFlight = Math.max(mostInFlight, inFlight); |
| 529 | for (let turn = page; turn < 9; turn++) await Promise.resolve(); |
| 530 | inFlight--; |
| 531 | return Response.json({ |
| 532 | totalUsageEventsCount: 8001, |
| 533 | usageEventsDisplay: Array.from({ length: page === 9 ? 1 : 1000 }, (_, index) => ({ |
| 534 | timestamp: String(1780000000000 + (page - 1) * 1000 + index), |
| 535 | model: "gpt-5", |
| 536 | tokenUsage: { inputTokens: 1 }, |
| 537 | })), |
| 538 | }); |
| 539 | }, |
| 540 | { userId: 42, teamIds: queued ? [7] : [] }, |
| 541 | ).pipe( |
| 542 | HttpClient.transform((response, request) => { |
| 543 | if (!queued || !request.url.endsWith("/GetFilteredUsageEvents")) return response; |
| 544 | const body = |
| 545 | request.body._tag === "Uint8Array" |
| 546 | ? JSON.parse(new TextDecoder().decode(request.body.body)) |
| 547 | : {}; |
| 548 | if (body.page === 1) return response; |
| 549 | return Effect.gen(function* () { |
| 550 | const batch = delayedRequests++ < 6 ? firstBatch : secondBatch; |
| 551 | yield* Queue.offer(started, undefined); |
| 552 | yield* Deferred.await(batch); |
| 553 | return yield* response; |
| 554 | }); |
| 555 | }), |
| 556 | ); |
| 557 | const read = yield* Effect.forkChild( |
| 558 | makeCursorAccountUsageReader.pipe( |
| 559 | Effect.flatMap((reader) => |
| 560 | reader({ kind: "apiKey", apiKey: accessToken }, 0, 1781000000000), |
| 561 | ), |
| 562 | Effect.provideService(HttpClient.HttpClient, client), |
| 563 | ), |
| 564 | ); |
| 565 | if (queued) { |
| 566 | yield* Effect.all(Array.from({ length: 6 }, () => Queue.take(started))); |
| 567 | yield* TestClock.adjust("6 seconds"); |
| 568 | yield* Deferred.succeed(firstBatch, undefined); |
| 569 | yield* Effect.all(Array.from({ length: 6 }, () => Queue.take(started))); |
| 570 | yield* TestClock.adjust("6 seconds"); |
| 571 | yield* Deferred.succeed(secondBatch, undefined); |
| 572 | } |
| 573 | const result = yield* Fiber.join(read); |
| 574 | assert.isNull(result.error); |
| 575 | assert.strictEqual(mostInFlight, 6); |
| 576 | assert.deepStrictEqual( |
| 577 | result.records.map((record) => record.timestampMs), |
| 578 | Array.from( |
| 579 | { length: queued ? 16002 : 8001 }, |
| 580 | (_, index) => 1780000000000 + (index % 8001), |
| 581 | ), |
| 582 | ); |
| 583 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 584 | ); |
| 585 | |
| 586 | it.effect("ends like a page-by-page read when a page fails, leaving no request open", () => |
| 587 | Effect.gen(function* () { |
| 588 | const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; |
| 589 | const fullPage = { |
| 590 | totalUsageEventsCount: 8001, |
| 591 | usageEventsDisplay: Array.from({ length: 1000 }, () => ({ tokenUsage: null })), |
| 592 | }; |
| 593 | for (const [secondPage, error] of [ |
| 594 | [() => Response.json(fullPage), "Cursor account usage could not be read."], |
| 595 | [ |
| 596 | () => new Response(null, { status: 401 }), |
| 597 | "Sign in to Cursor again to read account usage.", |
| 598 | ], |
| 599 | ] as const) { |
| 600 | let open = 0; |
| 601 | const result = yield* readAccountUsage( |
| 602 | { kind: "apiKey", apiKey: accessToken }, |
| 603 | 0, |
| 604 | 1781000000000, |
| 605 | ({ init, page }) => { |
| 606 | if (page === 1) return Promise.resolve(Response.json(fullPage)); |
| 607 | if (page === 2) return Promise.resolve(secondPage()); |
| 608 | if (page === 3) return Promise.reject(new Error("connection reset")); |
| 609 | open++; |
| 610 | return new Promise((_resolve, reject) => { |
| 611 | init.signal?.addEventListener("abort", () => { |
| 612 | open--; |
| 613 | reject(init.signal?.reason); |
| 614 | }); |
| 615 | }); |
| 616 | }, |
| 617 | ); |
| 618 | assert.strictEqual(result.error, error); |
| 619 | assert.deepStrictEqual(result.records, []); |
| 620 | assert.strictEqual(open, 0); |
| 621 | } |
| 622 | }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 623 | ); |
| 624 | }); |