feat: display provider usage limits in settings #1732
ClosedAditya190803(GitHub profile, opens in a new tab)wants to merge 21 commits into
main fromrefs/pull/1732/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/persistence/Layers/ProviderUsageLimits.ts lines 49 to 49OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +29,21 @@29+30+const makeProviderUsageLimitsRepository = Effect.gen(function* () {31+ const sql = yield* SqlClient.SqlClient;32+ const changesPubSub = yield* Effect.acquireRelease(33+ PubSub.unbounded<StoredProviderUsageLimits>(),34+ PubSub.shutdown,35+ );36+37+ const upsertUsageLimitsRow = SqlSchema.void({38+ Request: ProviderUsageLimitsDbRowSchema,39+ execute: (row) =>40+ sql`41+ INSERT INTO provider_usage_limits (42+ provider_name,43+ updated_at,44+ payload_json45+ )46+ VALUES (47+ ${row.provider},48+ ${row.updatedAt},49+ ${JSON.stringify(row.usageLimits)}
- apps/server/src/provider/Layers/CodexProvider.ts lines 574 to 578OutdatedResolvedby Aditya190803(GitHub profile, opens in a new tab)@@ -541,5 +567,12 @@541567 },542568 });543569544- const checkProvider = checkCodexProviderStatus((input) =>545- Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),570+ const checkProvider = checkCodexProviderStatus(571+ (input) =>572+ Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])).pipe(573+ Effect.tap((state) =>574+ state?.usageLimits575+ ? usageLimitsRepository576+ .upsert({577+ provider: PROVIDER,578+ usageLimits: state.usageLimits,apps/server/src/provider/Layers/CodexProvider.ts lines 494 to 496OutdatedResolvedby Aditya190803(GitHub profile, opens in a new tab)@@ -462,4 +489,8 @@462489 homePath: codexSettings.homePath,463490 })464491 : undefined;465- const resolvedModels = adjustCodexModelsForAccount(models, account);492+ const accountSnapshot = isResolvedCodexAccountState(account) ? account.snapshot : account;493+ const resolvedModels = adjustCodexModelsForAccount(models, accountSnapshot);494+ const usageLimits = isResolvedCodexAccountState(account)495+ ? (account.usageLimits ?? cachedUsageLimits)496+ : cachedUsageLimits;
- apps/server/src/provider/codexAppServer.ts line 248OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -152,3 +237,12 @@152237 });153238 });154239 }240+241+export async function probeCodexAccount(input: {242+ readonly binaryPath: string;243+ readonly homePath?: string;244+ readonly signal?: AbortSignal;245+}): Promise<CodexAccountSnapshot> {246+ const state = await probeCodexAccountState(input);247+ return state.snapshot;248+}
juliusmarminge reviewed
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/provider/Layers/ClaudeProvider.ts line 970OutdatedResolvedby Aditya190803(GitHub profile, opens in a new tab)@@ -603,17 +539,14 @@603539 });604540 }605541606- const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);607- const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });608- return buildServerProvider({609- provider: PROVIDER,610- enabled: claudeSettings.enabled,611- checkedAt,542+ const parsed = parseAuthStatusFromOutput(authProbe.success.value);543+ const authType = codexAuthSubType(accountSnapshot);544+ const authLabel = codexAuthSubLabel(accountSnapshot);545+ return buildProviderSnapshot({612546 models: resolvedModels,613547 probe: {614548 installed: true,615549 version: parsedVersion,616550 status: parsed.status,617551 auth: {618552 ...parsed.auth,619- ...(authMetadata ? authMetadata : {}),apps/server/src/server.ts line 323OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -160,4 +161,14 @@160161 }),161162 );162163163-const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));164+const PersistenceLayerLive = Layer.mergeAll(165+ SqlitePersistenceLayerLive,166+ ProviderUsageLimitsRepositoryLive.pipe(Layer.provide(SqlitePersistenceLayerLive)),167+);168+169+const GitManagerLayerLive = GitManagerLive.pipe(170+ Layer.provideMerge(ProjectSetupScriptRunnerLive),171+ Layer.provideMerge(GitCoreLive),172+ Layer.provideMerge(GitHubCliLive),173+ Layer.provideMerge(RoutingTextGenerationLive),174+);
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/provider/Layers/ClaudeProvider.ts lines 880 to 880OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -780,3 +863,18 @@780863 Cache.get(subscriptionProbeCache, binaryPath).pipe(781864 Effect.map((probe) => probe?.slashCommands),782865 ),866+ (input) =>867+ Effect.gen(function* () {868+ const key = JSON.stringify([input.binaryPath, input.launchArgs]);869+ const entry = (yield* Ref.get(usageProbeStateRef)).get(key);870+ const isFresh = entry !== undefined && Date.now() - entry.fetchedAtMs < usageProbeTtlMs;871+872+ if ((!entry || !isFresh) && !entry?.inFlight) {873+ yield* Effect.sync(() => {874+ void Effect.runPromiseExit(875+ refreshUsageProbe(key, input.binaryPath, input.launchArgs),876+ );877+ });878+ }879+880+ if (!entry) {
- apps/server/src/provider/providerUsageLimits.ts line 40OutdatedResolvedby Aditya190803(GitHub profile, opens in a new tab)@@ -0,0 +20,21 @@20+ }21+ const date = new Date(value * 1000);22+ return Number.isFinite(date.getTime()) ? date.toISOString() : undefined;23+}24+25+export function windowKindFromDuration(input: {26+ readonly windowDurationMins?: number;27+ readonly shortestWindowDurationMins?: number;28+ readonly longestWindowDurationMins?: number;29+}): ServerProviderUsageWindow["kind"] | undefined {30+ const duration = input.windowDurationMins;31+ if (typeof duration !== "number" || !Number.isFinite(duration)) {32+ return undefined;33+ }34+ if (duration === input.shortestWindowDurationMins) {35+ return "session";36+ }37+ if (duration === input.longestWindowDurationMins) {38+ return "weekly";39+ }40+ return undefined;
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/provider/codexAppServer.ts line 373OutdatedResolvedby Aditya190803(GitHub profile, opens in a new tab)@@ -105,3 +361,13 @@105361 child.kill();106362 }107363364+interface CodexDiscoveryProbeState {365+ account?: CodexAccountSnapshot;366+ skills?: ReadonlyArray<ServerProviderSkill>;367+ rateLimits: CodexRateLimitsSnapshot | undefined;368+ rateLimitsResponseReceived: boolean;369+}370+371+function isCodexDiscoveryComplete(state: CodexDiscoveryProbeState): boolean {372+ return Boolean(state.account) && state.skills !== undefined && state.rateLimitsResponseReceived;373+}
- apps/server/src/provider/Layers/ClaudeProvider.ts line 877OutdatedResolvedby Aditya190803(GitHub profile, opens in a new tab)@@ -780,3 +863,15 @@780863 Cache.get(subscriptionProbeCache, binaryPath).pipe(781864 Effect.map((probe) => probe?.slashCommands),782865 ),866+ (input) =>867+ Effect.gen(function* () {868+ const key = JSON.stringify([input.binaryPath, input.launchArgs]);869+ const entry = (yield* Ref.get(usageProbeStateRef)).get(key);870+ const isFresh = entry !== undefined && Date.now() - entry.fetchedAtMs < usageProbeTtlMs;871+872+ if ((!entry || !isFresh) && !entry?.inFlight) {873+ yield* Effect.sync(() => {874+ void Effect.runPromiseExit(875+ refreshUsageProbe(key, input.binaryPath, input.launchArgs),876+ );877+ });
- apps/web/src/components/settings/SettingsPanels.tsx line 243OutdatedResolvedby Aditya190803(GitHub profile, opens in a new tab)@@ -221,3 +225,19 @@221225 );222226 }223227228+function getUsageMeterToneClass(usedPercent: number): string {229+ if (usedPercent >= 90) return "bg-destructive";230+ if (usedPercent >= 70) return "bg-warning";231+ return "bg-foreground/88";232+}233+234+function getUsageRemainingLabel(usedPercent: number): string {235+ const remainingPercent = Math.max(0, Math.min(100, 100 - Math.round(usedPercent)));236+ return `${remainingPercent}% remaining`;237+}238+239+function getUsageTrackClass(usedPercent: number): string {240+ if (usedPercent >= 90) return "bg-destructive/12";241+ if (usedPercent >= 70) return "bg-warning/12";242+ return "bg-white/6 dark:bg-white/6";243+}
- apps/web/src/components/settings/SettingsPanels.tsx line 214OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -223,0 +309,21 @@309+ ) : null}310+ </div>311+ );312+ })}313+ </div>314+ );315+}316+317+function ProviderCardShell({ children, expanded }: { children: ReactNode; expanded: boolean }) {318+ return (319+ <div320+ className={cn(321+ "relative overflow-hidden border-t border-white/8 bg-[linear-gradient(180deg,rgba(255,255,255,0.028),rgba(255,255,255,0.01))] first:border-t-0",322+ expanded && "bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(255,255,255,0.016))]",323+ )}324+ >325+ <div className="pointer-events-none absolute inset-x-0 top-0 h-px bg-white/5" />326+ {children}327+ </div>328+ );329+}apps/web/src/components/settings/SettingsPanels.tsx line 283OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -223,0 +263,21 @@263+ }264+265+ if (!provider.usageLimits.available) {266+ return (267+ <p className="pt-2 text-[11px] text-muted-foreground/85">268+ {provider.usageLimits.reason ?? "Usage limits unavailable for this account"}269+ </p>270+ );271+ }272+273+ return (274+ <div className="space-y-4 pt-3">275+ {provider.usageLimits.windows.map((window) => {276+ const percentageLabel = `${Math.round(window.usedPercent)}%`;277+ const resetLabel = getUsageResetLabel(window.resetsAt);278+ const normalizedWidth = Math.max(0, Math.min(100, window.usedPercent));279+ const remainingLabel = getUsageRemainingLabel(window.usedPercent);280+281+ return (282+ <div283+ key={`${window.kind}-${window.label}-${window.windowDurationMins ?? "na"}-${window.resetsAt ?? "na"}-${Math.round(window.usedPercent)}`}
- apps/web/src/components/settings/SettingsPanels.tsx line 281OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -248,0 +261,21 @@261+ return `${remainingPercent}% remaining`;262+}263+264+function getUsageTrackClass(usedPercent: number): string {265+ if (usedPercent >= 90) return "bg-destructive/12";266+ if (usedPercent >= 70) return "bg-warning/12";267+ return "bg-black/5 dark:bg-white/6";268+}269+270+function getUsageResetLabel(resetsAt: string | undefined): string | null {271+ if (!resetsAt) return null;272+ const diffMs = new Date(resetsAt).getTime() - Date.now();273+ if (!Number.isFinite(diffMs) || diffMs <= 0) {274+ return null;275+ }276+ const dayMs = 24 * 60 * 60 * 1000;277+ if (diffMs >= dayMs && diffMs < dayMs * 2) {278+ return "Resets tomorrow";279+ }280+ return `Resets in ${formatRelativeTimeUntilLabel(resetsAt).replace(/ left$/, "")}`;281+}
- apps/server/src/provider/claudeUsageProbe.ts line 10OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,10 @@1+import type { ServerProviderUsageLimits } from "@t3tools/contracts";2+import { makeUnavailableUsageLimits, makeUsageLimitsSnapshot } from "./providerUsageLimits.ts";3+4+const CLAUDE_USAGE_PROBE_TIMEOUT_MS = 4_000;5+const CLAUDE_USAGE_FALLBACK_IDLE_MS = 150;6+const ANSI_PATTERN =7+ // Matches common CSI / OSC ANSI escape sequences.8+ // eslint-disable-next-line no-control-regex9+ /\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007]*(?:\u0007|\u001B\\))/g;10+const nodePtyModulePromise = import("node-pty");
- apps/server/src/provider/Layers/ClaudeProvider.ts line 919OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -808,0 +899,21 @@899+ if ((!entry || !isFresh) && !entry?.inFlight) {900+ yield* Effect.sync(() => {901+ void Effect.runPromiseExit(902+ refreshUsageProbe(key, input.binaryPath, input.launchArgs),903+ );904+ });905+ }906+907+ if (!entry || (entry.inFlight && entry.rawOutput.trim().length === 0)) {908+ return makeUnavailableUsageLimits({909+ source: "claudeStatusProbe",910+ checkedAt: input.checkedAt,911+ reason: "Usage limits are still loading for this Claude account.",912+ });913+ }914+915+ return parseClaudeUsageLimitsOutput({916+ output: entry.rawOutput,917+ checkedAt: input.checkedAt,918+ });919+ }),
- apps/server/src/provider/opencodeRuntime.ts line 589OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -548,9 +575,15 @@548575 input: OpenCodeInventory,549576 ): ReadonlyArray<ServerProviderModel> {550577 const connected = new Set(input.providerList.connected);578+ const officialProviderIds = new Set(579+ Object.keys(OPENCODE_MANAGED_PROVIDER_DESCRIPTORS),580+ );551581 const models: Array<ServerProviderModel> = [];552582553583 for (const provider of input.providerList.all) {554584 if (!connected.has(provider.id)) {555585 continue;556586 }587+ if (!officialProviderIds.has(provider.id)) {588+ continue;589+ }
- apps/server/src/provider/opencodeRuntime.ts line 580OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -548,3 +575,6 @@548575 input: OpenCodeInventory,549576 ): ReadonlyArray<ServerProviderModel> {550577 const connected = new Set(input.providerList.connected);578+ const officialProviderIds = new Set(579+ Object.keys(OPENCODE_MANAGED_PROVIDER_DESCRIPTORS),580+ );apps/server/src/provider/Layers/CodexProvider.ts line 484OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -465,3 +473,12 @@465473 }).pipe(Effect.orElseSucceed(() => undefined))466474 : undefined) ?? [];467475476+ const resolvedUsageLimits =477+ (resolveUsageLimits478+ ? yield* resolveUsageLimits({479+ binaryPath: codexSettings.binaryPath,480+ homePath: codexSettings.homePath,481+ cwd: process.cwd(),482+ checkedAt,483+ }).pipe(Effect.orElseSucceed(() => undefined))484+ : undefined) ?? undefined;
- apps/server/src/server.ts line 229OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -218,6 +219,11 @@218219 Layer.provide(ServerSecretStoreLive),219220 );220221221-const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(222- Layer.provideMerge(ProviderLayerLive),223- Layer.provideMerge(OrchestrationLayerLive),222+const ProviderRuntimeLayerLive = Layer.mergeAll(223+ ProviderLayerLive,224+ ProviderUsageStateLive.pipe(Layer.provide(ProviderLayerLive)),225+ ProviderSessionReaperLive.pipe(226+ Layer.provideMerge(OrchestrationLayerLive),227+ Layer.provide(ProviderLayerLive),228+ ),229+ OrchestrationLayerLive,apps/server/src/provider/codexAppServer.ts line 296OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -39,0 +276,21 @@276+ readonly rateLimits?: CodexRateLimitsSnapshot;277+}): ServerProviderUsageLimits {278+ const windows: RawUsageWindowInput[] =279+ input.rateLimits?.windows.map((window) => ({280+ label: "Codex quota window",281+ usedPercent: window.usedPercent,282+ ...(window.resetsAt ? { resetsAt: window.resetsAt } : {}),283+ ...(typeof window.windowDurationMins === "number"284+ ? { windowDurationMins: window.windowDurationMins }285+ : {}),286+ })) ?? [];287+288+ const hasWindows = windows.length > 0;289+ return makeUsageLimitsSnapshot({290+ source: "codexAppServer",291+ checkedAt: input.checkedAt,292+ windows,293+ ...(hasWindows294+ ? {}295+ : { unavailableReason: "No Codex subscription quota windows reported." }),296+ });
- apps/server/src/server.ts line 229OutdatedResolvedby Aditya190803(GitHub profile, opens in a new tab)@@ -218,6 +219,11 @@218219 Layer.provide(ServerSecretStoreLive),219220 );220221221-const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(222- Layer.provideMerge(ProviderLayerLive),223- Layer.provideMerge(OrchestrationLayerLive),222+const ProviderRuntimeLayerLive = Layer.mergeAll(223+ ProviderLayerLive.pipe(Layer.provideMerge(ProviderUsageStateLive)),224+ ProviderUsageStateLive.pipe(Layer.provide(ProviderLayerLive)),225+ ProviderSessionReaperLive.pipe(226+ Layer.provideMerge(OrchestrationLayerLive),227+ Layer.provide(ProviderLayerLive),228+ ),229+ OrchestrationLayerLive,apps/server/src/provider/codexAppServer.ts line 286OutdatedResolvedby Aditya190803(GitHub profile, opens in a new tab)@@ -39,0 +266,21 @@266+ record?.rateLimits ??267+ record?.limits ??268+ preferred ??269+ (record && readNumber(record.usedPercent) !== undefined ? record : undefined);270+ const windows = withFallbackCodexWindowDurations(collectCodexRateLimitWindows(candidate));271+ return windows.length > 0 ? { windows } : undefined;272+}273+274+export function normalizeCodexUsageLimits(input: {275+ readonly checkedAt: string;276+ readonly rateLimits?: CodexRateLimitsSnapshot;277+}): ServerProviderUsageLimits {278+ const windows: RawUsageWindowInput[] =279+ input.rateLimits?.windows.map((window) => ({280+ label: "Codex quota window",281+ usedPercent: window.usedPercent,282+ ...(window.resetsAt ? { resetsAt: window.resetsAt } : {}),283+ ...(typeof window.windowDurationMins === "number"284+ ? { windowDurationMins: window.windowDurationMins }285+ : {}),286+ })) ?? [];apps/server/src/provider/Layers/CursorProvider.ts line 44OutdatedResolvedby Aditya190803(GitHub profile, opens in a new tab)@@ -37,6 +39,6 @@3739 promptInjectedEffortLevels: [],3840 };394140-const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;41-const CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT = "4 seconds";42-const CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY = 4;42+const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 60_000;43+const CURSOR_ACP_MODEL_CAPABILITY_TIMEOUT = "15 seconds";44+const CURSOR_ACP_MODEL_DISCOVERY_CONCURRENCY = 2;
- apps/server/src/provider/codexAppServer.test.ts line 165OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +145,21 @@145+ rateLimits: {146+ shortWindow: {147+ used: 42,148+ limit: 100,149+ windowDurationMins: 300,150+ resetsAt: 1_776_384_000,151+ },152+ },153+ });154+155+ expect(snapshot).toEqual({156+ windows: [157+ {158+ usedPercent: 42,159+ windowDurationMins: 300,160+ resetsAt: "2026-04-17T00:00:00.000Z",161+ },162+ ],163+ });164+ });165+});
- apps/server/src/provider/Layers/CodexProvider.ts line 319OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -276,0 +299,21 @@299+ const windows: RawUsageWindowInput[] = [];300+301+ const addWindow = (window?: CodexSchema.V2GetAccountRateLimitsResponse__RateLimitWindow | null) => {302+ if (!window) return;303+ windows.push({304+ label: "Codex quota window",305+ usedPercent: window.usedPercent,306+ ...(typeof window.resetsAt === "number" ? { resetsAt: new Date(window.resetsAt * 1000).toISOString() } : {}),307+ ...(typeof window.windowDurationMins === "number" ? { windowDurationMins: window.windowDurationMins } : {}),308+ });309+ };310+311+ addWindow(rateLimitsSnapshot.primary);312+ addWindow(rateLimitsSnapshot.secondary);313+314+ return makeUsageLimitsSnapshot({315+ source: "codexAppServer",316+ checkedAt,317+ windows,318+ unavailableReason: "No Codex subscription quota windows reported.",319+ });
- apps/server/src/provider/providerUsageLimits.ts line 23OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +3,21 @@3+export interface RawUsageWindowInput {4+ readonly label: string;5+ readonly usedPercent: number;6+ readonly resetsAt?: string;7+ readonly windowDurationMins?: number;8+}9+10+export function clampPercent(value: number): number {11+ if (!Number.isFinite(value)) {12+ return 0;13+ }14+ return Math.max(0, Math.min(100, value));15+}16+17+export function toIsoDateTimeFromUnixSeconds(value: unknown): string | undefined {18+ if (typeof value !== "number" || !Number.isFinite(value)) {19+ return undefined;20+ }21+ const date = new Date(value * 1000);22+ return Number.isFinite(date.getTime()) ? date.toISOString() : undefined;23+}
- apps/server/src/provider/providerUsageLimits.ts line 66OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +46,21 @@46+ )47+ .toSorted((left, right) => left - right);48+ const shortestWindowDurationMins = normalizedDurations[0];49+ const longestWindowDurationMins = normalizedDurations.at(-1);50+51+ return windows52+ .flatMap((window) => {53+ const kind = windowKindFromDuration({54+ ...(typeof window.windowDurationMins === "number"55+ ? { windowDurationMins: window.windowDurationMins }56+ : {}),57+ ...(typeof shortestWindowDurationMins === "number" ? { shortestWindowDurationMins } : {}),58+ ...(typeof longestWindowDurationMins === "number" ? { longestWindowDurationMins } : {}),59+ });60+ if (!kind) {61+ return [];62+ }63+ return [64+ {65+ kind,66+ label: kind === "session" ? "Session" : "Weekly",apps/server/src/provider/Layers/ClaudeProvider.ts line 689OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -671,3 +679,11 @@671679 )672680 : undefined) ?? [];673681 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);682+ const resolvedUsageLimits =683+ (resolveUsageLimits684+ ? yield* resolveUsageLimits({685+ binaryPath: claudeSettings.binaryPath,686+ launchArgs: claudeSettings.launchArgs,687+ checkedAt,688+ }).pipe(Effect.orElseSucceed(() => undefined))689+ : undefined) ?? undefined;
- apps/server/src/persistence/Migrations.ts line 84OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -76,4 +80,5 @@7680 [23, "ProjectionThreadShellSummary", Migration0023],7781 [24, "BackfillProjectionThreadShellSummary", Migration0024],7882 [25, "CleanupInvalidProjectionPendingApprovals", Migration0025],79- [26, "CanonicalizeModelSelectionOptions", Migration0026],83+ [26, "AuthAccessManagementCompat", Migration0026],84+ [27, "CanonicalizeModelSelectionOptions", Migration0027],apps/server/src/provider/Layers/ClaudeProvider.ts line 1024OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -910,0 +1004,21 @@1004+ void Effect.runPromiseExit(1005+ refreshUsageProbe(key, input.binaryPath, input.launchArgs),1006+ );1007+ });1008+ }1009+1010+ const latestEntry = (yield* Ref.get(usageProbeStateRef)).get(key);1011+1012+ if (!latestEntry || (latestEntry.inFlight && latestEntry.rawOutput.trim().length === 0)) {1013+ return makeUnavailableUsageLimits({1014+ source: "claudeStatusProbe",1015+ checkedAt: input.checkedAt,1016+ reason: "Usage limits are still loading for this Claude account.",1017+ });1018+ }1019+1020+ return parseClaudeUsageLimitsOutput({1021+ output: latestEntry.rawOutput,1022+ checkedAt: input.checkedAt,1023+ });1024+ }),apps/server/src/provider/Layers/ClaudeProvider.ts line 1008OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -908,3 +992,17 @@908992 Cache.get(subscriptionProbeCache, binaryPath).pipe(909993 Effect.map((probe) => probe?.slashCommands),910994 ),995+ (input) =>996+ Effect.gen(function* () {997+ const key = JSON.stringify([input.binaryPath, input.launchArgs]);998+ const currentEntry = (yield* Ref.get(usageProbeStateRef)).get(key);999+ const isFresh =1000+ currentEntry !== undefined && Date.now() - currentEntry.fetchedAtMs < usageProbeTtlMs;1001+1002+ if ((!currentEntry || !isFresh) && !currentEntry?.inFlight) {1003+ yield* Effect.sync(() => {1004+ void Effect.runPromiseExit(1005+ refreshUsageProbe(key, input.binaryPath, input.launchArgs),1006+ );1007+ });1008+ }apps/web/src/components/settings/SettingsPanels.tsx line 284OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -247,0 +264,21 @@264+ if (usedPercent >= 90) return "bg-destructive/12";265+ if (usedPercent >= 70) return "bg-warning/12";266+ return "bg-black/5 dark:bg-white/6";267+}268+269+function getUsageResetLabel(resetsAt: string | undefined): string | null {270+ if (!resetsAt) return null;271+ const diffMs = new Date(resetsAt).getTime() - Date.now();272+ if (!Number.isFinite(diffMs) || diffMs <= 0) {273+ return null;274+ }275+ const dayMs = 24 * 60 * 60 * 1000;276+ if (diffMs >= dayMs && diffMs < dayMs * 2) {277+ return "Resets tomorrow";278+ }279+ const relativeLabel = formatRelativeTimeUntilLabel(resetsAt);280+ if (relativeLabel === "Soon") {281+ return "Resets soon";282+ }283+ return `Resets in ${relativeLabel.replace(/ left$/, "")}`;284+}apps/server/src/provider/Layers/CodexProvider.ts line 312OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -289,15 +296,17 @@289296 } satisfies CodexAppServerProviderSnapshot;290297 }291298292- const [skillsResponse, models] = yield* Effect.all(299+ const [skillsResponse, models, rateLimitsResponse] = yield* Effect.all(293300 [294301 client.request("skills/list", {295302 cwds: [input.cwd],296303 }),297304 requestAllCodexModels(client),305+ client.request("account/rateLimits/read", undefined).pipe(Effect.catch(() => Effect.void))298306 ],299307 { concurrency: "unbounded" },300308 );301309302310 return {303311 account: accountResponse,312+ ...(rateLimitsResponse?.rateLimits ? { rateLimits: rateLimitsResponse.rateLimits } : {}),
- apps/server/src/provider/Layers/ProviderUsageState.ts line 69OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +49,21 @@49+ clear: (provider) =>50+ Ref.update(stateRef, (state) => {51+ if (!state.has(provider)) {52+ return state;53+ }54+ const next = new Map(state);55+ next.delete(provider);56+ return next;57+ }),58+ };59+60+ yield* Stream.runForEach(providerService.streamEvents, (event) =>61+ Effect.gen(function* () {62+ if (event.provider !== "cursor") {63+ return;64+ }65+66+ if (event.type === "session.started" || event.type === "session.exited") {67+ yield* service.clear("cursor");68+ return;69+ }apps/server/src/provider/providerStatusCache.ts line 60OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -57,3 +57,4 @@5757 checkedAt: input.cachedProvider.checkedAt,5858 slashCommands: input.cachedProvider.slashCommands,5959 skills: input.cachedProvider.skills,60+ usageLimits: input.cachedProvider.usageLimits,apps/server/src/provider/claudeUsageProbe.ts line 300OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +140,21 @@140+ return [];141+ }142+143+ return [parsed];144+ });145+}146+147+export function parseClaudeUsageLimitsOutput(input: {148+ readonly output: string;149+ readonly checkedAt: string;150+}): ServerProviderUsageLimits {151+ const cleanedOutput = stripAnsi(input.output);152+ const lowerOutput = cleanedOutput.toLowerCase();153+154+ if (/\bapi key\b|\bapi-key\b/.test(lowerOutput)) {155+ return makeUnavailableUsageLimits({156+ source: "claudeStatusProbe",157+ checkedAt: input.checkedAt,158+ reason: "Usage limits unavailable for Claude API key accounts.",159+ });160+ }
- apps/server/src/provider/Layers/ProviderUsageState.ts lines 59 to 67OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +47,21 @@47+ }48+ const global = threadMap.get("global" as ThreadId);49+ if (global) {50+ return global;51+ }52+ const latest = Array.from(threadMap.values()).at(-1);53+ return latest;54+ }),55+ ),56+ set: (provider, usage) =>57+ Ref.update(stateRef, (state) => {58+ const next = new Map(state);59+ if (usage === undefined) {60+ next.delete(provider);61+ } else {62+ let threadMap = next.get(provider);63+ if (!threadMap) {64+ threadMap = new Map();65+ next.set(provider, threadMap);66+ }67+ threadMap.set("global" as ThreadId, usage);
- apps/server/src/provider/Layers/ProviderUsageState.ts line 55OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +35,21 @@35+ const providerService = yield* ProviderService;36+ const stateRef = yield* Ref.make(37+ new Map<ProviderKind, Map<ThreadId, ServerProviderUsageLimits>>(),38+ );39+40+ const service: ProviderUsageStateShape = {41+ get: (provider) =>42+ Ref.get(stateRef).pipe(43+ Effect.map((state) => {44+ const threadMap = state.get(provider);45+ if (!threadMap || threadMap.size === 0) {46+ return undefined;47+ }48+ const global = threadMap.get("global" as ThreadId);49+ if (global) {50+ return global;51+ }52+ const latest = Array.from(threadMap.values()).at(-1);53+ return latest;54+ }),55+ ),apps/server/src/provider/Layers/ClaudeProvider.ts line 808OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -777,3 +793,16 @@777793 subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);778794 }779795796+ const usageLimits =797+ normalizeClaudeAuthMethod(authMethod) === "apiKey"798+ ? makeUnavailableUsageLimits({799+ source: "claudeStatusProbe",800+ checkedAt,801+ reason: "Usage limits unavailable for Claude API key accounts.",802+ })803+ : (resolvedUsageLimits ??804+ makeUnavailableUsageLimits({805+ source: "claudeStatusProbe",806+ checkedAt,807+ reason: "Usage limits unavailable for this Claude account.",808+ }));apps/server/src/provider/Layers/CodexProvider.ts line 315OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -289,9 +296,20 @@289296 } satisfies CodexAppServerProviderSnapshot;290297 }291298292- const [skillsResponse, models] = yield* Effect.all(299+ const [skillsResponse, models, rateLimitsResponse] = yield* Effect.all(293300 [294301 client.request("skills/list", {295302 cwds: [input.cwd],296303 }),297304 requestAllCodexModels(client),305+ client.request("account/rateLimits/read", undefined).pipe(306+ Effect.catch((error: unknown) => {307+ const message = error instanceof Error ? error.message : String(error);308+ const isExpected =309+ message.includes("not found") ||310+ message.includes("not available") ||311+ message.includes("no rate limit") ||312+ message.includes("unavailable");313+ return isExpected ? Effect.void : Effect.fail(error as CodexErrors.CodexAppServerError);314+ }),315+ ),apps/server/src/provider/Layers/CodexProvider.ts line 366OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -309,0 +346,21 @@346+ const addWindow = (347+ window?: CodexSchema.V2GetAccountRateLimitsResponse__RateLimitWindow | null,348+ fallbackDurationMins?: number,349+ ) => {350+ if (!window) return;351+ const durationMins =352+ typeof window.windowDurationMins === "number"353+ ? window.windowDurationMins354+ : fallbackDurationMins;355+ windows.push({356+ label: "Codex quota window",357+ usedPercent: window.usedPercent,358+ ...(typeof window.resetsAt === "number"359+ ? { resetsAt: new Date(window.resetsAt * 1000).toISOString() }360+ : {}),361+ ...(typeof durationMins === "number" ? { windowDurationMins: durationMins } : {}),362+ });363+ };364+365+ addWindow(rateLimitsSnapshot.primary, CODEX_PRIMARY_WINDOW_DURATION_MINS);366+ addWindow(rateLimitsSnapshot.secondary, CODEX_SECONDARY_WINDOW_DURATION_MINS);apps/server/src/provider/claudeUsageProbe.ts line 215OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +61,21 @@61+62+function detectClaudeUsageWindowKind(value: string): "session" | "weekly" | undefined {63+ const lower = value.toLowerCase();64+ if (/\bweekly\b|\b7\s*(?:d|day|days)\b/.test(lower)) {65+ return "weekly";66+ }67+ if (/\b5\s*(?:h|hr|hrs|hour|hours)\b|\bsession\b/.test(lower)) {68+ return "session";69+ }70+ return undefined;71+}72+73+function extractResetTimestamp(value: string): string | undefined {74+ const resetMatch = value.match(75+ /\breset(?:s|ting)?(?:\s+(?:at|on|in))?[:\s-]*([A-Za-z]{3,9}[^,\n]*\d{1,2}[^,\n]*\d{2,4}[^,\n]*|\d{4}-\d{2}-\d{2}T[^\s,]+|\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}(?::\d{2})?(?:\s*[A-Z]{2,5})?)/i,76+ );77+ const candidate = resetMatch?.[1]?.trim();78+ if (!candidate) return undefined;79+ const parsed = Date.parse(candidate);80+ return Number.isFinite(parsed) ? new Date(parsed).toISOString() : undefined;81+}apps/web/src/components/settings/SettingsPanels.tsx line 290OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -247,0 +270,21 @@270+ if (!resetsAt) return null;271+ const diffMs = new Date(resetsAt).getTime() - Date.now();272+ if (!Number.isFinite(diffMs) || diffMs <= 0) {273+ return null;274+ }275+ const now = new Date();276+ const resetDate = new Date(resetsAt);277+ const tomorrow = new Date(now);278+ tomorrow.setDate(tomorrow.getDate() + 1);279+ const isResetTomorrow =280+ resetDate.toDateString() !== now.toDateString() &&281+ resetDate.toDateString() === tomorrow.toDateString();282+ if (isResetTomorrow) {283+ return "Resets tomorrow";284+ }285+ const relativeLabel = formatRelativeTimeUntilLabel(resetsAt);286+ if (relativeLabel === "Soon") {287+ return "Resets soon";288+ }289+ return `Resets in ${relativeLabel.replace(/ left$/, "")}`;290+}apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts line 17OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -4,3 +4,14 @@44 export default Effect.gen(function* () {55 const sql = yield* SqlClient.SqlClient;667+ const existingTables = yield* sql<{ readonly name: string }>`8+ SELECT name9+ FROM sqlite_master10+ WHERE type = 'table'11+ AND name IN ('auth_pairing_links', 'auth_sessions')12+ `;13+ const tableNames = new Set(existingTables.map((table) => table.name));14+15+ if (!tableNames.has("auth_pairing_links") || !tableNames.has("auth_sessions")) {16+ return;17+ }
- apps/server/src/provider/Layers/ClaudeProvider.ts line 1018OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -910,0 +998,21 @@998+ const currentEntry = (yield* Ref.get(usageProbeStateRef)).get(key);999+ const isFresh =1000+ currentEntry !== undefined && Date.now() - currentEntry.fetchedAtMs < usageProbeTtlMs;1001+1002+ if ((!currentEntry || !isFresh) && !currentEntry?.inFlight) {1003+ yield* Ref.update(usageProbeStateRef, (current) => {1004+ const next = new Map(current);1005+ const existing = next.get(key);1006+ next.set(key, {1007+ rawOutput: existing?.rawOutput ?? "",1008+ fetchedAtMs: existing?.fetchedAtMs ?? 0,1009+ inFlight: true,1010+ });1011+ return next;1012+ });1013+ yield* Effect.sync(() => {1014+ void Effect.runPromiseExit(1015+ refreshUsageProbe(key, input.binaryPath, input.launchArgs),1016+ );1017+ });1018+ }apps/server/src/provider/Layers/ProviderUsageState.ts line 30OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +10,21 @@10+import {11+ ProviderUsageState,12+ type ProviderUsageStateShape,13+} from "../Services/ProviderUsageState.ts";14+import { ProviderService } from "../Services/ProviderService.ts";15+16+function toCursorUsageLimits(17+ event: Extract<ProviderRuntimeEvent, { readonly type: "thread.token-usage.updated" }>,18+) {19+ const maxTokens = event.payload.usage.maxTokens;20+ if (typeof maxTokens !== "number") {21+ return undefined;22+ }23+24+ return runtimeUsageToProviderUsageLimits({25+ source: "cursorAcp",26+ checkedAt: event.createdAt,27+ usedTokens: event.payload.usage.usedTokens,28+ maxTokens,29+ });30+}apps/server/src/provider/Layers/ProviderUsageState.ts line 92OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +72,21 @@72+ let threadMap = next.get(provider);73+ if (!threadMap) {74+ threadMap = new Map();75+ } else {76+ threadMap = new Map(threadMap);77+ }78+ next.set(provider, threadMap);79+ threadMap.set("global" as ThreadId, { usage, updatedAtMs: Date.now() });80+ }81+ return next;82+ }),83+ clear: (provider) =>84+ Ref.update(stateRef, (state) => {85+ if (!state.has(provider)) {86+ return state;87+ }88+ const next = new Map(state);89+ next.delete(provider);90+ return next;91+ }),92+ };
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
1ee2bf19-dba6-4b48-840f-cced02ce3debYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Warning
Your free Security trial is over. An organization admin can activate Security or dismiss this notice.
Comment `@coderabbitai help` to get the list of available commands.