GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): include Cursor team usage in account history (#36237) · Pipyakas/t3code@20f4c79

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/provider-cursor/src/server
    • CursorAccountReader.ts
    • accountCache.ts
    • accountUsage.test.ts
    • accountUsage.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/provider-cursor/src/server/CursorAccountReader.ts‎

Copy file name to clipboardExpand all lines: packages/provider-cursor/src/server/CursorAccountReader.ts
+3-4Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import * as HttpClient from "effect/http/HttpClient";
55
import * as Layer from "effect/Layer";
66

77
import type { CursorCredentialSource } from "./accountCache.ts";
8-
import { readCursorAccountUsage, type CursorAccountUsageReadResult } from "./accountUsage.ts";
8+
import { makeCursorAccountUsageReader, type CursorAccountUsageReadResult } from "./accountUsage.ts";
99

1010
export class CursorAccountReader extends Context.Service<
1111
CursorAccountReader,
@@ -22,11 +22,10 @@ export const layer = Layer.effect(
2222
CursorAccountReader,
2323
Effect.gen(function* () {
2424
const context = yield* Effect.context<Digest.Digest | HttpClient.HttpClient>();
25+
const read = yield* makeCursorAccountUsageReader;
2526
return CursorAccountReader.of({
2627
read: Effect.fn("CursorAccountReader.read")(function (credentialSource, sinceMs, untilMs) {
27-
return readCursorAccountUsage(credentialSource, sinceMs, untilMs).pipe(
28-
Effect.provideContext(context),
29-
);
28+
return read(credentialSource, sinceMs, untilMs).pipe(Effect.provideContext(context));
3029
}),
3130
});
3231
}),
Collapse file

‎packages/provider-cursor/src/server/accountCache.ts‎

Copy file name to clipboardExpand all lines: packages/provider-cursor/src/server/accountCache.ts
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,8 @@ export function mergeCursorFetch(
8282
}
8383

8484
/** Versioned files isolate caches for different server versions sharing a state directory. */
85-
export const CURSOR_ACCOUNT_CACHE_FILE_NAME = "usage-cursor-account-cache-v1.json";
86-
const CURSOR_ACCOUNT_CACHE_VERSION = 1;
85+
export const CURSOR_ACCOUNT_CACHE_FILE_NAME = "usage-cursor-account-cache-v2.json";
86+
const CURSOR_ACCOUNT_CACHE_VERSION = 2;
8787

8888
type SerializedRecord = readonly [
8989
timestampMs: number,
Collapse file

‎packages/provider-cursor/src/server/accountUsage.test.ts‎

Copy file name to clipboardExpand all lines: packages/provider-cursor/src/server/accountUsage.test.ts
+245-36Lines changed: 245 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
22
import * as NodeServices from "@effect/platform-node/NodeServices";
33
import * as Layer from "effect/Layer";
44
import { assert, describe, it } from "@effect/vitest";
5+
import * as Deferred from "effect/Deferred";
6+
import * as Queue from "effect/Queue";
57
import * as Context from "effect/Context";
68
import * as Effect from "effect/Effect";
79
import * as Fiber from "effect/Fiber";
@@ -11,7 +13,10 @@ import * as HttpClientError from "effect/http/HttpClientError";
1113
import * as HttpClientResponse from "effect/http/HttpClientResponse";
1214
import * as TestClock from "effect/testing/TestClock";
1315

14-
import { readCursorAccountUsage } from "./accountUsage.ts";
16+
import * as CursorAccountReader from "./CursorAccountReader.ts";
17+
18+
import { makeCursorAccountUsageReader } from "./accountUsage.ts";
19+
import type { CursorCredentialSource } from "./accountCache.ts";
1520

1621
interface DashboardRequest {
1722
readonly url: string;
@@ -20,7 +25,10 @@ interface DashboardRequest {
2025
readonly headers: Headers;
2126
}
2227

23-
const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Response>) =>
28+
const dashboard = (
29+
answer: (request: DashboardRequest) => Response | Promise<Response>,
30+
membership = { userId: 1, teamIds: [] as number[] },
31+
) =>
2432
HttpClient.make((request, url, signal, fiber) =>
2533
Effect.tryPromise({
2634
try: async () => {
@@ -36,6 +44,15 @@ const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Res
3644
Response.json({ accessToken: request.headers.authorization.slice(7) }),
3745
);
3846
}
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+
}
3956
const response = await answer({
4057
url: url.toString(),
4158
init: { ...init, signal, body },
@@ -52,13 +69,15 @@ const dashboard = (answer: (request: DashboardRequest) => Response | Promise<Res
5269
);
5370

5471
const readAccountUsage = (
55-
credentialSource: Parameters<typeof readCursorAccountUsage>[0],
72+
credentialSource: CursorCredentialSource,
5673
sinceMs: number,
5774
endDate: number,
5875
answer: (request: DashboardRequest) => Response | Promise<Response>,
76+
membership?: { userId: number; teamIds: number[] },
5977
) =>
60-
readCursorAccountUsage(credentialSource, sinceMs, endDate).pipe(
61-
Effect.provideService(HttpClient.HttpClient, dashboard(answer)),
78+
makeCursorAccountUsageReader.pipe(
79+
Effect.flatMap((read) => read(credentialSource, sinceMs, endDate)),
80+
Effect.provideService(HttpClient.HttpClient, dashboard(answer, membership)),
6281
);
6382

6483
describe("Cursor account history", () => {
@@ -123,6 +142,157 @@ describe("Cursor account history", () => {
123142
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
124143
);
125144

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+
126296
it.effect("reads Cursor account history beyond 100 pages", () =>
127297
Effect.gen(function* () {
128298
const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
@@ -341,37 +511,76 @@ describe("readCursorAccountUsage", () => {
341511
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
342512
);
343513

344-
it.effect("reads the pages behind the first together and keeps them in page order", () =>
345-
Effect.gen(function* () {
346-
const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`;
347-
let inFlight = 0;
348-
let mostInFlight = 0;
349-
const result = yield* readAccountUsage(
350-
{ kind: "apiKey", apiKey: accessToken },
351-
0,
352-
1781000000000,
353-
async ({ page }) => {
354-
inFlight++;
355-
mostInFlight = Math.max(mostInFlight, inFlight);
356-
for (let turn = page; turn < 9; turn++) await Promise.resolve();
357-
inFlight--;
358-
return Response.json({
359-
totalUsageEventsCount: 8001,
360-
usageEventsDisplay: Array.from({ length: page === 9 ? 1 : 1000 }, (_, index) => ({
361-
timestamp: String(1780000000000 + (page - 1) * 1000 + index),
362-
model: "gpt-5",
363-
tokenUsage: { inputTokens: 1 },
364-
})),
365-
});
366-
},
367-
);
368-
assert.isNull(result.error);
369-
assert.strictEqual(mostInFlight, 6);
370-
assert.deepStrictEqual(
371-
result.records.map((record) => record.timestampMs),
372-
Array.from({ length: 8001 }, (_, index) => 1780000000000 + index),
373-
);
374-
}).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
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))),
375584
);
376585

377586
it.effect("ends like a page-by-page read when a page fails, leaving no request open", () =>

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.