Skip to content

Commit af00cf7

Browse files
fix(cursor): show Cursor usage after signing in with Cursor (#29419)
Co-authored-by: maria-rcks <[email protected]>
1 parent cc59f99 commit af00cf7

11 files changed

Lines changed: 492 additions & 52 deletions

File tree

‎apps/server/src/usage/UsageService.test.ts‎

Lines changed: 221 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import * as Fiber from "effect/Fiber";
3030
import * as FileSystem from "effect/FileSystem";
3131
import * as Context from "effect/Context";
3232
import * as Layer from "effect/Layer";
33+
import * as Option from "effect/Option";
3334
import * as Scheduler from "effect/Scheduler";
3435
import * as Schema from "effect/Schema";
3536
import * as TestClock from "effect/testing/TestClock";
@@ -149,6 +150,7 @@ const layerService = (input: {
149150
readonly environment?: NodeJS.ProcessEnv;
150151
readonly platform?: NodeJS.Platform;
151152
readonly hostname?: string;
153+
readonly secretStore?: Partial<ServerSecretStore.ServerSecretStore["Service"]>;
152154
}) =>
153155
layerCursorUsageAccounts(
154156
CursorAccountReader.layer.pipe(Layer.provide(CursorKeychain.layer)),
@@ -158,7 +160,12 @@ const layerService = (input: {
158160
Layer.provideMerge(ProviderHostLive.layer),
159161
Layer.provideMerge(CodexUsageHistory.layer.pipe(Layer.provideMerge(Sqlite.layerMemory))),
160162
Layer.provideMerge(Layer.mock(BackgroundPolicy.BackgroundPolicy)({})),
161-
Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})),
163+
Layer.provideMerge(
164+
Layer.mock(ServerSecretStore.ServerSecretStore)({
165+
get: () => Effect.succeedNone,
166+
...input.secretStore,
167+
}),
168+
),
162169
Layer.provideMerge(
163170
ServerConfig.layerTest(process.cwd(), NodePath.join(input.home, input.prefix)),
164171
),
@@ -239,10 +246,12 @@ function makeFakeCursor() {
239246
error: null as string | null,
240247
gate: undefined as Deferred.Deferred<void> | undefined,
241248
calls: [] as { readonly sinceMs: number; readonly untilMs: number }[],
249+
credentials: [] as unknown[],
242250
};
243-
const read = (_credential: unknown, sinceMs: number, untilMs: number) =>
251+
const read = (credential: unknown, sinceMs: number, untilMs: number) =>
244252
Effect.gen(function* () {
245253
state.calls.push({ sinceMs, untilMs });
254+
state.credentials.push(credential);
246255
if (state.gate !== undefined) yield* Deferred.await(state.gate);
247256
const { accountKey, error } = state;
248257
if (error !== null) return { accountKey, records: [], missing: false, error };
@@ -286,6 +295,10 @@ function cursorSource(summary: { readonly sources: readonly UsageSource[] }) {
286295
return summary.sources.find((source) => source.fingerprint.provider === "cursor");
287296
}
288297

298+
function cursorSources(summary: { readonly sources: readonly UsageSource[] }) {
299+
return summary.sources.filter((source) => source.fingerprint.provider === "cursor");
300+
}
301+
289302
const seedCodexHistory = (input: {
290303
id: string;
291304
nativeTurnId?: string;
@@ -1512,11 +1525,6 @@ describe("UsageService", () => {
15121525
environment: { AGENT_CLI_CREDENTIAL_STORE: "memory" },
15131526
authPath: ["config", "cursor", "auth.json"],
15141527
},
1515-
{
1516-
platform: "linux" as const,
1517-
environment: { CURSOR_API_KEY: "different-account" },
1518-
authPath: ["config", "cursor", "auth.json"],
1519-
},
15201528
].entries()) {
15211529
const authPath = NodePath.join(home, ...testCase.authPath);
15221530
yield* Effect.promise(async () => {
@@ -1546,6 +1554,212 @@ describe("UsageService", () => {
15461554
}).pipe(Effect.scoped),
15471555
);
15481556

1557+
it.live("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () =>
1558+
Effect.gen(function* () {
1559+
const { settings, home } = yield* setup;
1560+
const signIn = new TextEncoder().encode(
1561+
encodeUnknownJsonString({
1562+
version: 1,
1563+
backendUrl: "https://api2.cursor.sh",
1564+
apiKey: "signed-in-key",
1565+
createdAtMs: 0,
1566+
}),
1567+
);
1568+
for (const [index, testCase] of [
1569+
{ environment: { CURSOR_API_KEY: "environment-key" }, stored: Option.none() },
1570+
{ environment: {}, stored: Option.some(signIn) },
1571+
].entries()) {
1572+
const cursor = makeFakeCursor();
1573+
const summary = yield* Effect.gen(function* () {
1574+
const service = yield* makeWithCursor(cursor.read);
1575+
return yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1576+
}).pipe(
1577+
Effect.provide(
1578+
layerService({
1579+
prefix: `usage-service-cursor-api-key-${index}`,
1580+
home,
1581+
settings,
1582+
platform: "darwin",
1583+
environment: testCase.environment,
1584+
secretStore: { get: () => Effect.succeed(testCase.stored) },
1585+
}),
1586+
),
1587+
);
1588+
assert.deepStrictEqual(cursor.state.credentials, [
1589+
{ kind: "apiKey", apiKey: index === 0 ? "environment-key" : "signed-in-key" },
1590+
]);
1591+
assert.strictEqual(cursorSource(summary)?.status, "ok");
1592+
}
1593+
}).pipe(Effect.scoped),
1594+
);
1595+
1596+
it.live("does not show a previous Cursor account's history after the API key changes", () =>
1597+
Effect.gen(function* () {
1598+
const { settings, home } = yield* setup;
1599+
yield* TestClock.setTime(CURSOR_NOW);
1600+
let apiKey = "first-account-key";
1601+
const signIn = () =>
1602+
Option.some(
1603+
new TextEncoder().encode(
1604+
encodeUnknownJsonString({
1605+
version: 1,
1606+
backendUrl: "https://api2.cursor.sh",
1607+
apiKey,
1608+
createdAtMs: 0,
1609+
}),
1610+
),
1611+
);
1612+
const cursor = makeFakeCursor();
1613+
cursor.state.events = [{ timestampMs: CURSOR_NOW - 3 * HOUR_MS, outputTokens: 7 }];
1614+
yield* Effect.gen(function* () {
1615+
const service = yield* makeWithCursor(cursor.read);
1616+
const first = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1617+
assert.isTrue(first.buckets.some((bucket) => bucket.provider === "cursor"));
1618+
1619+
apiKey = "second-account-key";
1620+
cursor.state.error = "Cursor account usage could not be read.";
1621+
const second = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1622+
assert.isFalse(second.buckets.some((bucket) => bucket.provider === "cursor"));
1623+
}).pipe(
1624+
Effect.provide(
1625+
layerService({
1626+
prefix: "usage-service-cursor-key-change",
1627+
home,
1628+
settings,
1629+
platform: "darwin",
1630+
environment: {},
1631+
secretStore: { get: () => Effect.sync(signIn) },
1632+
}),
1633+
),
1634+
);
1635+
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1636+
);
1637+
1638+
it.live("keeps a new Cursor key's refresh visible beside a failing key", () =>
1639+
Effect.gen(function* () {
1640+
const { settings, home } = yield* setup;
1641+
const cursor = makeFakeCursor();
1642+
const started = yield* Deferred.make<void>();
1643+
const gate = yield* Deferred.make<void>();
1644+
yield* Effect.gen(function* () {
1645+
const context = yield* Layer.build(
1646+
layerCursorUsageAccounts(
1647+
Layer.succeed(CursorAccountReader.CursorAccountReader, {
1648+
read: (credential, sinceMs, untilMs) =>
1649+
(credential as { apiKey?: string }).apiKey === "failing-key"
1650+
? Effect.succeed({
1651+
accountKey: null,
1652+
records: [],
1653+
missing: false,
1654+
error: "Cursor account usage could not be read.",
1655+
})
1656+
: Deferred.succeed(started, undefined).pipe(
1657+
Effect.andThen(Deferred.await(gate)),
1658+
Effect.andThen(cursor.read(credential, sinceMs, untilMs)),
1659+
),
1660+
}),
1661+
),
1662+
);
1663+
const accounts = Context.get(context, CursorUsageAccounts.CursorUsageAccounts);
1664+
const scan = (awaitRefresh: boolean) =>
1665+
accounts.scan({
1666+
instances: [
1667+
{
1668+
instanceId: ProviderInstanceId.make("cursor"),
1669+
environment: { CURSOR_API_KEY: "failing-key" },
1670+
},
1671+
{
1672+
instanceId: ProviderInstanceId.make("cursor-work"),
1673+
environment: { CURSOR_API_KEY: "new-key" },
1674+
},
1675+
],
1676+
keychainUsageEnabled: false,
1677+
windowStartMs: 0,
1678+
retentionCutoffMs: 0,
1679+
awaitRefresh,
1680+
});
1681+
const first = yield* Effect.forkChild(scan(true));
1682+
yield* Deferred.await(started);
1683+
const sources = yield* scan(false);
1684+
assert.isTrue(sources.some((source) => source.refreshing === true));
1685+
yield* Deferred.succeed(gate, undefined);
1686+
yield* Fiber.join(first);
1687+
}).pipe(
1688+
Effect.provide(
1689+
layerService({
1690+
prefix: "usage-service-cursor-new-key",
1691+
home,
1692+
settings,
1693+
platform: "linux",
1694+
environment: {},
1695+
}),
1696+
),
1697+
);
1698+
}).pipe(Effect.scoped),
1699+
);
1700+
1701+
it.live("reports one Cursor source when two API keys belong to the same account", () =>
1702+
Effect.gen(function* () {
1703+
const { settings, home } = yield* setup;
1704+
yield* TestClock.setTime(CURSOR_NOW);
1705+
const cursor = makeFakeCursor();
1706+
cursor.state.events = [{ timestampMs: CURSOR_NOW - 3 * HOUR_MS, outputTokens: 7 }];
1707+
let revoked = false;
1708+
yield* Effect.gen(function* () {
1709+
const service = yield* makeWithCursor((credential, sinceMs, untilMs) =>
1710+
revoked && (credential as { apiKey?: string }).apiKey === "second-key"
1711+
? Effect.succeed({
1712+
accountKey: null,
1713+
records: [],
1714+
missing: false,
1715+
error: "Cursor account usage could not be read.",
1716+
})
1717+
: cursor.read(credential, sinceMs, untilMs),
1718+
);
1719+
const first = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1720+
assert.strictEqual(cursor.state.credentials.length, 2);
1721+
assert.deepStrictEqual(
1722+
cursorSources(first).map((source) => source.distinctSessions),
1723+
[1],
1724+
);
1725+
1726+
// The revoked key keeps its stale cache, which must not replace the working key's history.
1727+
revoked = true;
1728+
cursor.state.events.push({ timestampMs: CURSOR_NOW + 60 * 1000, outputTokens: 5 });
1729+
yield* TestClock.adjust(Duration.minutes(2));
1730+
const second = yield* service.readSummary({ ...WINDOW, awaitRefresh: true });
1731+
assert.deepStrictEqual(
1732+
cursorSources(second).map((source) => source.status),
1733+
["ok"],
1734+
);
1735+
assert.strictEqual(totalOutputTokens(second), 12);
1736+
}).pipe(
1737+
Effect.provide(
1738+
layerService({
1739+
prefix: "usage-service-cursor-shared-account",
1740+
home,
1741+
settings: {
1742+
...settings,
1743+
providerInstances: {
1744+
...settings.providerInstances,
1745+
[ProviderInstanceId.make("cursor")]: {
1746+
driver: ProviderDriverKind.make("cursor"),
1747+
environment: [{ name: "CURSOR_API_KEY", value: "first-key", sensitive: true }],
1748+
},
1749+
[ProviderInstanceId.make("cursor-work")]: {
1750+
driver: ProviderDriverKind.make("cursor"),
1751+
environment: [{ name: "CURSOR_API_KEY", value: "second-key", sensitive: true }],
1752+
},
1753+
},
1754+
},
1755+
platform: "darwin",
1756+
environment: {},
1757+
}),
1758+
),
1759+
);
1760+
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1761+
);
1762+
15491763
it.live(
15501764
"includes OpenCode history but does not substitute desktop usage for an unavailable Cursor account",
15511765
() =>

‎docs/user/usage.md‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,13 @@ OpenCode reads its SQLite database and older JSON history. Antigravity reads loc
2424
databases, including T3-managed profiles. Set `OPENCODE_DATA_DIR` or `ANTIGRAVITY_DATA_DIR` on the
2525
server to read a different data directory; comma-separated paths read multiple directories.
2626

27-
Cursor reads account usage from Cursor's dashboard API using the CLI login saved on the server.
27+
Cursor reads account usage from Cursor's API for the account you signed in with in T3 or set as
28+
`CURSOR_API_KEY`, or otherwise the CLI login saved on the server.
2829
This includes headless T3 sessions and desktop usage across machines; the same account counts
29-
once across connected environments. Without an accessible CLI login, T3 shows a
30+
once across connected environments. Without any of these, T3 shows a
3031
notice instead of incomplete local totals. T3 does not estimate missing tokens from conversation text.
31-
On macOS, choose **Enable Cursor usage** on Usage to allow T3 to read your existing CLI login
32-
from Keychain. You can turn it off in **Settings → Providers → Usage providers**. macOS may ask
32+
On macOS without a T3 sign-in, choose **Enable Cursor usage** on Usage to allow T3 to read your
33+
existing CLI login from Keychain. You can turn it off in **Settings → Providers → Usage providers**. macOS may ask
3334
you to allow access on the server Mac.
3435

3536
Usage includes each configured account's history, including disabled accounts. Custom homes follow
@@ -159,10 +160,11 @@ belong to the remote server. Limits need an OpenCode Go API key, or an OpenCode
159160
in OpenCode with an API key. A Console browser sign-in alone does not report them. You can also add
160161
your Go API key as `OPENCODE_API_KEY` in the OpenCode instance's **Environment variables**, then
161162
refresh provider status. Cursor reports
162-
its monthly allowance, including separate Auto and API usage, using the CLI login or
163-
`CURSOR_AUTH_TOKEN`. On macOS, this includes the default Keychain login after you enable Cursor
164-
usage. Keychain login is used for limits only with Cursor's default API endpoint. If you configure
165-
a custom Cursor endpoint, use an explicit token or file-based CLI login for limits.
163+
its monthly allowance, including separate Auto and API usage, for `CURSOR_AUTH_TOKEN` when it is set,
164+
otherwise for the account you signed in with in T3 or set as `CURSOR_API_KEY`, otherwise for the CLI
165+
login. On macOS, this includes the default Keychain login after you enable Cursor usage. Sign-in, API key,
166+
and Keychain login report limits only with Cursor's default API endpoint. If you configure a custom
167+
Cursor endpoint, use an explicit token or file-based CLI login for limits.
166168

167169
Grok reports the remaining subscription allowance and reset time for its current billing period
168170
after signing in with `grok login`. Explicit `XAI_API_KEY` connections and custom authentication

0 commit comments

Comments
 (0)