Skip to content
TypeScript

fix(clients): hide duplicate Cursor Keychain prompts (#13870)

Yash Singh679c34c09619
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
index 8fb2fe37aa8..4582c313569 100644
--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx
+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
@@ -1,6 +1,7 @@
import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
import { EnvironmentId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
import { type RouteProp, useIsFocused, useNavigation, useRoute } from "@react-navigation/native";
+import { cursorKeychainAccessEnvironments } from "@t3tools/client-runtime/state/usage";
import {
isCompatibleUsageContractVersion,
isModelCostUnknown,
@@ -102,9 +103,7 @@ export function UsageRouteScreen() {
);
const isFocused = useIsFocused();
const limits = useRefreshLimits(selectedEnvironmentIds, isFocused && tab === "limits");
- const cursorAccessEnvironments = selectedEnvironments.filter(
- (environment) => environment.needsCursorKeychainAccess,
- );
+ const cursorAccessEnvironments = cursorKeychainAccessEnvironments(selectedEnvironments);
const refreshAfterCursorEnable = () => {
void refresh();
void limits.refreshAfterEnable();
diff --git a/apps/server/src/provider/cursorCredentialStore.test.ts b/apps/server/src/provider/cursorCredentialStore.test.ts
index 051cb5425c6..f212ce110ea 100644
--- a/apps/server/src/provider/cursorCredentialStore.test.ts
+++ b/apps/server/src/provider/cursorCredentialStore.test.ts
@@ -1,6 +1,9 @@
import { assert, describe, it } from "@effect/vitest";
-import { makeCachedCursorAccessTokenReader } from "./cursorCredentialStore.ts";
+import {
+ CursorKeychainTimeoutError,
+ makeCachedCursorAccessTokenReader,
+} from "./cursorCredentialStore.ts";
describe("Cursor Keychain reader", () => {
it("shares concurrent reads and rechecks after the cache expires", async () => {
@@ -19,4 +22,25 @@ describe("Cursor Keychain reader", () => {
time = 5 * 60_000;
assert.strictEqual(await read(), "token-2");
});
+
+ it("gives up on an unanswered prompt and reuses it on the next read", async () => {
+ let reads = 0;
+ let allow: (token: string) => void = () => {};
+ const read = makeCachedCursorAccessTokenReader(
+ () => {
+ reads++;
+ return new Promise((resolve) => {
+ allow = resolve;
+ });
+ },
+ () => 0,
+ 1,
+ );
+ const error = await read().catch((cause: unknown) => cause);
+ assert.instanceOf(error, CursorKeychainTimeoutError);
+ const retry = read();
+ allow("token");
+ assert.strictEqual(await retry, "token");
+ assert.strictEqual(reads, 1);
+ });
});
diff --git a/apps/server/src/provider/cursorCredentialStore.ts b/apps/server/src/provider/cursorCredentialStore.ts
index 9d7d1c3bccf..2857683e482 100644
--- a/apps/server/src/provider/cursorCredentialStore.ts
+++ b/apps/server/src/provider/cursorCredentialStore.ts
@@ -4,17 +4,31 @@ const CACHE_MS = 5 * 60_000;
const requireForKeyring = NodeModule.createRequire(import.meta.url);
-/** Share one Keychain request across usage history and limits in this server process. */
+/** Rejected when nobody answers the macOS Keychain prompt in time. */
+export class CursorKeychainTimeoutError extends Error {
+ constructor() {
+ super("Timed out waiting for Keychain access.");
+ }
+}
+
+/**
+ * Share one Keychain request across usage history and limits in this server process.
+ *
+ * macOS shows the access prompt on the server's own screen, which a remote
+ * client cannot answer, so callers give up after `timeoutMs`. The read stays in
+ * flight: the next call reuses it instead of stacking a second prompt, and picks
+ * up the token once someone allows access.
+ */
export function makeCachedCursorAccessTokenReader(
read: () => Promise<string | null>,
now: () => number = Date.now,
+ timeoutMs = 30_000,
): () => Promise<string | null> {
let cached: { token: string; until: number } | null = null;
let pending: Promise<string | null> | null = null;
return () => {
if (cached && cached.until > now()) return Promise.resolve(cached.token);
- if (pending) return pending;
- pending = read()
+ pending ??= read()
.then((token) => {
cached = token ? { token, until: now() + CACHE_MS } : null;
return token;
@@ -22,7 +36,15 @@ export function makeCachedCursorAccessTokenReader(
.finally(() => {
pending = null;
});
- return pending;
+ const deadline = AbortSignal.timeout(timeoutMs);
+ return Promise.race([
+ pending,
+ new Promise<never>((_, reject) => {
+ deadline.addEventListener("abort", () => reject(new CursorKeychainTimeoutError()), {
+ once: true,
+ });
+ }),
+ ]);
};
}
diff --git a/apps/server/src/usage/cursorUsageReader.test.ts b/apps/server/src/usage/cursorUsageReader.test.ts
new file mode 100644
index 00000000000..4bfa647c0af
--- /dev/null
+++ b/apps/server/src/usage/cursorUsageReader.test.ts
@@ -0,0 +1,22 @@
+import { assert, describe, it } from "@effect/vitest";
+
+import { CursorKeychainTimeoutError } from "../provider/cursorCredentialStore.ts";
+import { readCursorAccountUsage } from "./cursorUsageReader.ts";
+
+describe("readCursorAccountUsage", () => {
+ it("asks for Keychain approval when the prompt goes unanswered", async () => {
+ const result = await readCursorAccountUsage(
+ { kind: "keychain" },
+ 0,
+ 1,
+ () => Promise.reject(new Error("no network expected")),
+ () => Promise.reject(new CursorKeychainTimeoutError()),
+ );
+ assert.deepStrictEqual(result, {
+ accountKey: null,
+ records: [],
+ missing: false,
+ error: "Allow Keychain access on the Mac running T3 Code, then refresh.",
+ });
+ });
+});
diff --git a/apps/server/src/usage/cursorUsageReader.ts b/apps/server/src/usage/cursorUsageReader.ts
index 1e07fcc7a82..573506d818a 100644
--- a/apps/server/src/usage/cursorUsageReader.ts
+++ b/apps/server/src/usage/cursorUsageReader.ts
@@ -5,7 +5,10 @@ import * as NodeCrypto from "node:crypto";
import * as NodeTimersPromises from "node:timers/promises";
import type { UsageRecord } from "./usageTranscripts.ts";
-import { readMacCursorAccessToken } from "../provider/cursorCredentialStore.ts";
+import {
+ CursorKeychainTimeoutError,
+ readMacCursorAccessToken,
+} from "../provider/cursorCredentialStore.ts";
function object(value: unknown): Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
@@ -86,7 +89,9 @@ export async function readCursorAccountUsage(
? null
: typeof credentialSource === "string"
? "Cursor credentials could not be read."
- : "Cursor Keychain credentials could not be read.",
+ : cause instanceof CursorKeychainTimeoutError
+ ? "Allow Keychain access on the Mac running T3 Code, then refresh."
+ : "Cursor Keychain credentials could not be read.",
};
}
if (typeof accessToken !== "string" || !accessToken) {
diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx
index e978963ce9b..3ced333c963 100644
--- a/apps/web/src/components/usage/UsagePage.tsx
+++ b/apps/web/src/components/usage/UsagePage.tsx
@@ -13,7 +13,10 @@ import {
SlidersHorizontalIcon,
} from "lucide-react";
import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
-import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
+import {
+ cursorKeychainAccessEnvironments,
+ refreshUsageLimits,
+} from "@t3tools/client-runtime/state/usage";
import {
isCompatibleUsageContractVersion,
@@ -129,9 +132,7 @@ export function UsagePage() {
selectedEnvironmentIds,
);
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
- const cursorAccessEnvironments = selectedEnvironments.filter(
- (environment) => environment.needsCursorKeychainAccess,
- );
+ const cursorAccessEnvironments = cursorKeychainAccessEnvironments(selectedEnvironments);
const sourceMessages = [
...new Set(
selectedEnvironments.flatMap(
diff --git a/packages/client-runtime/src/state/usage.test.ts b/packages/client-runtime/src/state/usage.test.ts
index 55fe46306dd..86914c768e3 100644
--- a/packages/client-runtime/src/state/usage.test.ts
+++ b/packages/client-runtime/src/state/usage.test.ts
@@ -13,7 +13,12 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import type { EnvironmentPresentation } from "../connection/presentation.ts";
import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
-import { needsCursorKeychainAccess, refreshUsage, refreshUsageLimits } from "./usage.ts";
+import {
+ cursorKeychainAccessEnvironments,
+ needsCursorKeychainAccess,
+ refreshUsage,
+ refreshUsageLimits,
+} from "./usage.ts";
const input = {
sinceDay: UsageDay.make("2026-09-05"),
@@ -285,4 +290,34 @@ describe("needsCursorKeychainAccess", () => {
expect(needsCursorKeychainAccess(cursorPrompt, null)).toBe(false);
expect(needsCursorKeychainAccess(summary, [cursor("ready")])).toBe(false);
});
+
+ it("stops offering access once any environment reads the Cursor account", () => {
+ const off = { summary: cursorPrompt, needsCursorKeychainAccess: true };
+ const account: UsageSummary = {
+ ...summary,
+ sources: [
+ {
+ fingerprint: {
+ hostId: "cursor.com",
+ provider: "cursor",
+ resolvedHomePath: "cursor-account:abc",
+ volumeId: "abc",
+ },
+ status: "ok",
+ scannedFiles: 1,
+ skippedFiles: 0,
+ malformedRecords: 0,
+ distinctSessions: 1,
+ message: null,
+ },
+ ],
+ };
+ expect(cursorKeychainAccessEnvironments([off, off])).toEqual([off, off]);
+ expect(
+ cursorKeychainAccessEnvironments([
+ off,
+ { summary: account, needsCursorKeychainAccess: false },
+ ]),
+ ).toEqual([]);
+ });
});
diff --git a/packages/client-runtime/src/state/usage.ts b/packages/client-runtime/src/state/usage.ts
index dc959c0fd8f..1f2377a89f4 100644
--- a/packages/client-runtime/src/state/usage.ts
+++ b/packages/client-runtime/src/state/usage.ts
@@ -26,6 +26,27 @@ export function needsCursorKeychainAccess(
);
}
+/**
+ * Environments to offer the Cursor Keychain prompt in the usage summary.
+ *
+ * Any environment reading a Cursor account already reports that account's
+ * history from every machine, so the prompt only adds duplicates there. A
+ * different account on another machine stays reachable from provider settings.
+ */
+export function cursorKeychainAccessEnvironments<
+ E extends { readonly summary: UsageSummary | null; readonly needsCursorKeychainAccess: boolean },
+>(environments: readonly E[]): readonly E[] {
+ const hasCursorAccount = environments.some((environment) =>
+ environment.summary?.sources.some(
+ (source) =>
+ source.fingerprint.provider === "cursor" && source.fingerprint.hostId === "cursor.com",
+ ),
+ );
+ return hasCursorAccount
+ ? []
+ : environments.filter((environment) => environment.needsCursorKeychainAccess);
+}
+
const limitsRefreshAfter = new Map<EnvironmentId, number>();
const limitsRefreshes = new Map<EnvironmentId, Promise<unknown>>();