diff --git a/src/main/claude-accounts/profiles/routing/claude-account-usage-preparation.ts b/src/main/claude-accounts/profiles/routing/claude-account-usage-preparation.ts index a0da0271e78..39ffc701f33 100644 --- a/src/main/claude-accounts/profiles/routing/claude-account-usage-preparation.ts +++ b/src/main/claude-accounts/profiles/routing/claude-account-usage-preparation.ts @@ -18,6 +18,7 @@ export function claudeAccountUsagePreparation( return { configDir: home, envPatch: { CLAUDE_CONFIG_DIR: home }, - provenance: `profile:${accountId}` + provenance: `profile:${accountId}`, + readingAccount: { accountId, runtime: 'host', wslDistro: null } } } diff --git a/src/main/claude-accounts/profiles/routing/claude-profile-router.ts b/src/main/claude-accounts/profiles/routing/claude-profile-router.ts index 3973867d655..27e6ce3cea1 100644 --- a/src/main/claude-accounts/profiles/routing/claude-profile-router.ts +++ b/src/main/claude-accounts/profiles/routing/claude-profile-router.ts @@ -306,7 +306,10 @@ export class ClaudeProfileRouter { wslDistro: null, wslLinuxConfigDir: null, envPatch: this.launchEnv(), - provenance: home ? `profile:${profile?.accountId}` : 'system' + provenance: home ? `profile:${profile?.accountId}` : 'system', + ...(home && profile + ? { readingAccount: { accountId: profile.accountId, runtime: 'host', wslDistro: null } } + : {}) } } diff --git a/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts index 509666496e9..129b8c2da8c 100644 --- a/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts +++ b/src/main/claude-accounts/profiles/wsl/claude-profile-wsl-router.ts @@ -221,7 +221,10 @@ export class ClaudeWslProfileRouter { ? { CLAUDE_CONFIG_DIR: profile.home, [CLAUDE_INJECTED_CONFIG_DIR_ENV]: profile.home } : {}) }, - provenance: profile ? `profile:${profile.accountId}:wsl:${distro}` : `wsl:${distro}:system` + provenance: profile ? `profile:${profile.accountId}:wsl:${distro}` : `wsl:${distro}:system`, + ...(profile + ? { readingAccount: { accountId: profile.accountId, runtime: 'wsl', wslDistro: distro } } + : {}) } } diff --git a/src/main/claude-accounts/runtime-auth/runtime-auth-types.ts b/src/main/claude-accounts/runtime-auth/runtime-auth-types.ts index df7fe11cc37..b6919e015d7 100644 --- a/src/main/claude-accounts/runtime-auth/runtime-auth-types.ts +++ b/src/main/claude-accounts/runtime-auth/runtime-auth-types.ts @@ -1,4 +1,5 @@ import type { ClaudeEnvPatch } from './environment' +import type { UsageReadingAccount } from '../../../shared/agent-usage/rate-limits/rate-limit-types' export type ClaudeRuntimeAuthPreparation = { configDir: string @@ -7,6 +8,8 @@ export type ClaudeRuntimeAuthPreparation = { wslLinuxConfigDir?: string | null envPatch: ClaudeEnvPatch provenance: string + /** The saved account whose login this reads; absent for System default and covered accounts. */ + readingAccount?: UsageReadingAccount /** Report unavailable usage without throwing out the entire polling cycle. */ usageError?: string } diff --git a/src/main/codex-accounts/credentials/codex-auth-identity.ts b/src/main/codex-accounts/credentials/codex-auth-identity.ts index 5d38a667175..618aa164dfc 100644 --- a/src/main/codex-accounts/credentials/codex-auth-identity.ts +++ b/src/main/codex-accounts/credentials/codex-auth-identity.ts @@ -1,4 +1,5 @@ import type { CodexManagedAccount } from '../../../shared/agent-accounts/managed-account-types' +import { codexPlanWorkspaceLabel } from '../../../shared/agent-accounts/codex/codex-plan-workspace-label' export type CodexAuthIdentity = { email: string | null @@ -184,7 +185,7 @@ export function readCodexAuthIdentity(contents: string): CodexAuthIdentity | nul workspaceLabel: normalizeField(readStringClaim(authClaims, 'workspace_name')) ?? normalizeField(readStringClaim(profileClaims, 'workspace_name')) ?? - readPlanWorkspaceLabel(authClaims), + codexPlanWorkspaceLabel(normalizeField(readStringClaim(authClaims, 'chatgpt_plan_type'))), workspaceAccountId: normalizeField( readStringClaim(authClaims, 'workspace_account_id') ?? tokenAccountId ?? @@ -193,31 +194,6 @@ export function readCodexAuthIdentity(contents: string): CodexAuthIdentity | nul } } -function readPlanWorkspaceLabel(authClaims: Record | null): string | null { - // Codex tokens commonly omit workspace_name but identify the account's plan. - switch (normalizeField(readStringClaim(authClaims, 'chatgpt_plan_type'))?.toLowerCase()) { - case 'free': - return 'Personal (Free)' - case 'go': - return 'Personal (Go)' - case 'plus': - return 'Personal (Plus)' - case 'pro': - return 'Personal (Pro)' - case 'team': - return 'Team' - case 'business': - return 'Business' - case 'enterprise': - return 'Enterprise' - case 'edu': - return 'Education' - case undefined: - default: - return null - } -} - function readFreshnessFromAuthContents(contents: string): number | null { const raw = parseJsonRecord(contents) if (!raw) { diff --git a/src/main/codex-accounts/runtime-home/credentials/runtime-home-managed-auth-recovery.test.ts b/src/main/codex-accounts/runtime-home/credentials/runtime-home-managed-auth-recovery.test.ts index 57a0ba8a9bd..95f3b1d59e6 100644 --- a/src/main/codex-accounts/runtime-home/credentials/runtime-home-managed-auth-recovery.test.ts +++ b/src/main/codex-accounts/runtime-home/credentials/runtime-home-managed-auth-recovery.test.ts @@ -111,7 +111,8 @@ describe('CodexRuntimeHomeService', () => { expect(service.isHostSystemDefaultRealHomeSelected()).toBe(false) expect(service.prepareForRateLimitFetch()).toEqual({ kind: 'ready', - codexHomePath: managedHomePath1 + codexHomePath: managedHomePath1, + readingAccount: { accountId: 'account-1', runtime: 'host', wslDistro: null } }) expect(service.prepareForCodexLaunch()).toBe(managedHomePath1) expect(existsSync(join(managedHomePath1, 'auth.json'))).toBe(false) diff --git a/src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts index 5a580d0ccb7..797a1b83492 100644 --- a/src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts +++ b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-home-routing.ts @@ -255,17 +255,18 @@ export abstract class CodexRuntimeHomeRouting extends CodexRuntimeHomeManagedHom pinnedWslDistro?: string ): CodexRateLimitHomeResolution { if (target?.runtime === 'wsl') { - return { - kind: 'ready', - codexHomePath: this.getPreparedWslRateLimitHomePath(target, pinnedWslDistro) - } + return this.getPreparedWslRateLimitHome(target, pinnedWslDistro) } const selfContainedAccount = this.getSelfContainedManagedHostAccount() if (selfContainedAccount) { const resolved = this.resolveSelfContainedManagedHome(selfContainedAccount) if (resolved.kind === 'owned') { // Quota probes read account auth in place; resource synchronization belongs to launch prep. - return { kind: 'ready', codexHomePath: resolved.homePath } + return { + kind: 'ready', + codexHomePath: resolved.homePath, + readingAccount: { accountId: selfContainedAccount.id, runtime: 'host', wslDistro: null } + } } if (resolved.kind === 'indeterminate') { return { kind: 'skip' } diff --git a/src/main/codex-accounts/runtime-home/routing/runtime-home-service-per-account-migration.test.ts b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-per-account-migration.test.ts index db0f3ee6f64..334b79a30b9 100644 --- a/src/main/codex-accounts/runtime-home/routing/runtime-home-service-per-account-migration.test.ts +++ b/src/main/codex-accounts/runtime-home/routing/runtime-home-service-per-account-migration.test.ts @@ -168,7 +168,8 @@ describe('CodexRuntimeHomeService per-account takeover composition', () => { expect(service.prepareForCodexLaunch()).toBe(account.managedHomePath) expect(service.prepareForRateLimitFetch()).toEqual({ kind: 'ready', - codexHomePath: account.managedHomePath + codexHomePath: account.managedHomePath, + readingAccount: { accountId: 'account-1', runtime: 'host', wslDistro: null } }) expect(existsSync(accountAuthPath)).toBe(false) expect(settings.activeCodexManagedAccountId).toBe(account.id) diff --git a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts index 5fcd89edf32..418cb0dfcda 100644 --- a/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-state.ts @@ -132,9 +132,10 @@ export abstract class CodexRuntimeHomeState { protected abstract getWslManagedHomeIdentity( account: CodexManagedAccount | null ): { distro: string; linuxHomePath: string } | null - protected abstract getPreparedWslRateLimitHomePath( - target: CodexAccountSelectionTarget - ): string | null + protected abstract getPreparedWslRateLimitHome( + target: CodexAccountSelectionTarget, + pinnedWslDistro?: string + ): CodexRateLimitHomeResolution protected abstract getWslCodexHomePathForSelection( target: CodexAccountSelectionTarget ): string | null diff --git a/src/main/codex-accounts/runtime-home/runtime-home-service-types.ts b/src/main/codex-accounts/runtime-home/runtime-home-service-types.ts index ab1dfde9003..f88335ca2eb 100644 --- a/src/main/codex-accounts/runtime-home/runtime-home-service-types.ts +++ b/src/main/codex-accounts/runtime-home/runtime-home-service-types.ts @@ -1,4 +1,5 @@ import type { CodexManagedAccount } from '../../../shared/agent-accounts/managed-account-types' +import type { UsageReadingAccount } from '../../../shared/agent-usage/rate-limits/rate-limit-types' export type CodexHomeLaunchOptions = { unavailableManagedHomePath?: string @@ -63,5 +64,6 @@ export type CodexMirroredHomeStatus = /** Result used by quota polling, where `skip` means no process should be spawned. */ export type CodexRateLimitHomeResolution = - | { kind: 'ready'; codexHomePath: string | null } + /** `readingAccount`: the saved account whose own home this is; absent for System default and the shared mirror. */ + | { kind: 'ready'; codexHomePath: string | null; readingAccount?: UsageReadingAccount } | { kind: 'skip' } diff --git a/src/main/codex-accounts/runtime-home/wsl/runtime-home-service-wsl.ts b/src/main/codex-accounts/runtime-home/wsl/runtime-home-service-wsl.ts index 248e22cf621..369fee196b6 100644 --- a/src/main/codex-accounts/runtime-home/wsl/runtime-home-service-wsl.ts +++ b/src/main/codex-accounts/runtime-home/wsl/runtime-home-service-wsl.ts @@ -17,16 +17,26 @@ import { } from '../../legacy-wsl-auth-drain/legacy-wsl-runtime-auth-drain' import { readWslCodexAuths, type WslCodexAuthRead } from './wsl-codex-auth-batch-reader' import type { CodexManagedAccount } from '../../../../shared/agent-accounts/managed-account-types' +import type { CodexRateLimitHomeResolution } from '../runtime-home-service-types' import { CodexRuntimeHomeWslCore } from '../credentials/runtime-home-service-wsl-core' export abstract class CodexRuntimeHomeWsl extends CodexRuntimeHomeWslCore { - protected getPreparedWslRateLimitHomePath( + protected getPreparedWslRateLimitHome( target: CodexAccountSelectionTarget, pinnedWslDistro?: string - ): string | null { + ): CodexRateLimitHomeResolution { // Unpinned polls pin the resolved default, as they always read that distro's lane. const distro = pinnedWslDistro ?? this.resolveWslDefaultTarget(target).wslDistro?.trim() - return this.getWslCodexHomePathForSelection(target, { pinnedWslDistro: distro || undefined }) + const home = this.resolveWslCodexHomeForSelection(target, { + pinnedWslDistro: distro || undefined + }) + return { + kind: 'ready', + codexHomePath: home.path, + ...(home.account && distro + ? { readingAccount: { accountId: home.account.id, runtime: 'wsl', wslDistro: distro } } + : {}) + } } /** @@ -37,6 +47,14 @@ export abstract class CodexRuntimeHomeWsl extends CodexRuntimeHomeWslCore { target: CodexAccountSelectionTarget, options: { probeHome?: boolean; pinnedWslDistro?: string } = {} ): string | null { + return this.resolveWslCodexHomeForSelection(target, options).path + } + + /** `account` is set only when the path is that account's own home, not a System default fallback. */ + private resolveWslCodexHomeForSelection( + target: CodexAccountSelectionTarget, + options: { probeHome?: boolean; pinnedWslDistro?: string } + ): { path: string | null; account: CodexManagedAccount | null } { const settings = this.store.getSettings() const pathTarget: CodexAccountSelectionTarget = options.pinnedWslDistro ? { runtime: 'wsl', wslDistro: options.pinnedWslDistro } @@ -49,10 +67,13 @@ export abstract class CodexRuntimeHomeWsl extends CodexRuntimeHomeWslCore { if (account) { const accountHome = this.getWslLaunchCodexHomePath(account, pathTarget.wslDistro?.trim()) if (accountHome) { - return accountHome + return { path: accountHome, account } } } - return this.getWslSystemCodexHomePath(options.pinnedWslDistro ? pathTarget : target, options) + return { + path: this.getWslSystemCodexHomePath(options.pinnedWslDistro ? pathTarget : target, options), + account: null + } } protected getWslLaunchCodexHomePath( diff --git a/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-managed-accounts.test.ts b/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-managed-accounts.test.ts index bf806b77e0d..9177a2b3d55 100644 --- a/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-managed-accounts.test.ts +++ b/src/main/codex-accounts/runtime-home/wsl/runtime-home-wsl-managed-accounts.test.ts @@ -112,7 +112,8 @@ describe('CodexRuntimeHomeService', () => { }) expect(service.prepareForRateLimitFetch({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toEqual({ kind: 'ready', - codexHomePath: wslManagedHomePath + codexHomePath: wslManagedHomePath, + readingAccount: { accountId: 'account-1', runtime: 'wsl', wslDistro: 'Ubuntu' } }) } finally { if (originalPlatform) { diff --git a/src/main/providers/accounts/provider-account-services.ts b/src/main/providers/accounts/provider-account-services.ts index 69fd1bf49ad..aa85450081e 100644 --- a/src/main/providers/accounts/provider-account-services.ts +++ b/src/main/providers/accounts/provider-account-services.ts @@ -195,6 +195,19 @@ export function createProviderAccountServices( .filter((account) => !activeIds.has(account.id)) .map((account) => ({ id: account.id, + ...(account.managedHomeRuntime === 'wsl' + ? account.wslDistro + ? { + readingAccount: { + accountId: account.id, + runtime: 'wsl' as const, + wslDistro: account.wslDistro + } + } + : {} + : { + readingAccount: { accountId: account.id, runtime: 'host' as const, wslDistro: null } + }), resolveHome: () => inactiveCodexHomeUnlessStopped( codexRuntimeHome.resolveCodexManagedAccountHomeForInactiveFetch(account) diff --git a/src/main/rate-limits/providers/claude/claude-active-usage-fetch.ts b/src/main/rate-limits/providers/claude/claude-active-usage-fetch.ts index daca33e8af0..fefcac27cbd 100644 --- a/src/main/rate-limits/providers/claude/claude-active-usage-fetch.ts +++ b/src/main/rate-limits/providers/claude/claude-active-usage-fetch.ts @@ -60,7 +60,21 @@ export async function fetchActiveClaudeRateLimits( ) } try { - return await fetchClaudeOAuthUsage(credentials.token, options?.signal) + const usage = await fetchClaudeOAuthUsage(credentials.token, options?.signal) + // Name the login a reading came from so its plan never follows another account's reading. + return usage.status === 'ok' + ? { + ...usage, + ...(credentials.planType ? { planType: credentials.planType } : {}), + usageMetadata: { + ...usage.usageMetadata, + ...metadata, + ...(options?.authPreparation?.readingAccount + ? { readingAccount: options.authPreparation.readingAccount } + : {}) + } + } + : usage } catch (error) { const { failureKind } = classifyClaudeOAuthUsageError(error) if (failureKind === 'stale-token' && !canClaudeRenewLogin(credentials, error)) { diff --git a/src/main/rate-limits/providers/claude/claude-oauth-credentials.test.ts b/src/main/rate-limits/providers/claude/claude-oauth-credentials.test.ts new file mode 100644 index 00000000000..4b7a114ddea --- /dev/null +++ b/src/main/rate-limits/providers/claude/claude-oauth-credentials.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { parseClaudeOAuthCredentialsJson } from './claude-oauth-credentials' + +function parse(oauth: Record): ReturnType { + return parseClaudeOAuthCredentialsJson( + JSON.stringify({ claudeAiOauth: { accessToken: 'token', refreshToken: 'refresh', ...oauth } }), + 'credentials-file' + ) +} + +describe('parseClaudeOAuthCredentialsJson plan', () => { + it('names Max by the tier Claude Code saved beside it', () => { + expect( + parse({ subscriptionType: 'max', rateLimitTier: 'default_claude_max_20x' }).planType + ).toBe('max_20x') + }) + + it('never lets the tier name or override a plan', () => { + expect(parse({ rateLimitTier: 'default_claude_max_20x' }).planType).toBeUndefined() + expect( + parse({ subscriptionType: 'pro', rateLimitTier: 'default_claude_max_20x' }).planType + ).toBe('pro') + }) + + it('keeps the token and the supplied plan when the tier is malformed', () => { + const result = parse({ subscriptionType: 'Team_XL', rateLimitTier: { tier: 'max_20x' } }) + expect(result).toMatchObject({ token: 'token', planType: 'Team_XL' }) + expect(result.unavailable).toBeUndefined() + }) +}) diff --git a/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts b/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts index 4f4163a51bd..8279019f484 100644 --- a/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts +++ b/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts @@ -18,6 +18,8 @@ export type ClaudeOAuthCredentialReadResult = { hasRefreshableCredentials: boolean /** Epoch ms; Claude Code 2.1.x records it beside the refresh token. */ refreshTokenExpiresAt?: number + /** Last plan Claude Code wrote beside this token, e.g. "pro" or "max_20x"; not live billing. */ + planType?: string source: ClaudeOAuthCredentialSource keychainUnavailable?: boolean unavailable?: boolean @@ -33,7 +35,10 @@ const schema = z.object({ .object({ accessToken: z.string().optional(), refreshToken: z.string().optional(), - refreshTokenExpiresAt: z.unknown().optional() + refreshTokenExpiresAt: z.unknown().optional(), + // Plan metadata never decides whether the token is usable. + subscriptionType: z.unknown().optional(), + rateLimitTier: z.unknown().optional() }) .optional() }) @@ -43,6 +48,7 @@ export function parseClaudeOAuthCredentialsJson( ): ClaudeOAuthCredentialReadResult { try { const oauth = schema.parse(JSON.parse(raw)).claudeAiOauth + const planType = readClaudePlanType(oauth?.subscriptionType, oauth?.rateLimitTier) // The usage server, not stored expiresAt, decides token validity. return { token: oauth?.accessToken || null, @@ -50,12 +56,23 @@ export function parseClaudeOAuthCredentialsJson( ...(typeof oauth?.refreshTokenExpiresAt === 'number' ? { refreshTokenExpiresAt: oauth.refreshTokenExpiresAt } : {}), + ...(planType ? { planType } : {}), source } } catch { return { ...emptyClaudeOAuthCredentialReadResult(), unavailable: true } } } +// The tier only refines Max ("default_claude_max_20x" → "max_20x"); it never names a plan alone. +function readClaudePlanType(subscription: unknown, tier: unknown): string | undefined { + const plan = typeof subscription === 'string' ? subscription.trim() : '' + if (!plan) { + return undefined + } + const multiplier = typeof tier === 'string' ? /(?:^|_)max_(\d+x)$/i.exec(tier.trim())?.[1] : null + // Other values keep the spelling Claude Code wrote. + return plan.toLowerCase() === 'max' && multiplier ? `max_${multiplier.toLowerCase()}` : plan +} export function emptyClaudeOAuthCredentialReadResult(): ClaudeOAuthCredentialReadResult { return { token: null, hasRefreshableCredentials: false, source: 'none' } } diff --git a/src/main/rate-limits/providers/codex/codex-backend-usage-client.test.ts b/src/main/rate-limits/providers/codex/codex-backend-usage-client.test.ts new file mode 100644 index 00000000000..fe8f309d471 --- /dev/null +++ b/src/main/rate-limits/providers/codex/codex-backend-usage-client.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it, vi } from 'vitest' +import type { ProviderRateLimits } from '../../../../shared/agent-usage/rate-limits/rate-limit-types' +import { supplementCodexUsageWindows } from './codex-backend-usage-client' + +vi.mock('./codex-backend-auth', () => ({ + CODEX_BACKEND_TIMEOUT_MS: 10_000, + getCodexBackendAuthHeaders: vi.fn(async () => ({ Authorization: 'Bearer test' })) +})) + +describe('supplementCodexUsageWindows', () => { + it('keeps the plan the usage response reports for a spend-capped seat', async () => { + const rpc: ProviderRateLimits = { + provider: 'codex', + session: null, + weekly: null, + monthly: null, + planType: 'unknown', + updatedAt: 1, + error: null, + status: 'ok' + } + const request = vi.fn( + async () => + new Response( + JSON.stringify({ + plan_type: 'business', + spend_control: { individual_limit: { remaining_percent: 80, reset_at: 2_000_000_000 } } + }) + ) + ) + const limits = await supplementCodexUsageWindows(rpc, request) + expect(limits.planType).toBe('business') + }) +}) diff --git a/src/main/rate-limits/providers/codex/codex-backend-usage-client.ts b/src/main/rate-limits/providers/codex/codex-backend-usage-client.ts index 5e77e4fcaab..0bc22149421 100644 --- a/src/main/rate-limits/providers/codex/codex-backend-usage-client.ts +++ b/src/main/rate-limits/providers/codex/codex-backend-usage-client.ts @@ -135,17 +135,20 @@ export async function supplementCodexUsageWindows( return limits } const rateLimitResetCredits = backend.rateLimitResetCredits ?? limits.rateLimitResetCredits + const planType = backend.planType ?? limits.planType if (!backend.session) { const monthly = limits.weekly ? null : backend.monthly - return !monthly && rateLimitResetCredits === limits.rateLimitResetCredits + return !monthly && + rateLimitResetCredits === limits.rateLimitResetCredits && + planType === limits.planType ? limits - : { ...limits, monthly, rateLimitResetCredits } + : { ...limits, monthly, rateLimitResetCredits, planType } } return { ...limits, session: backend.session, weekly: backend.weekly ?? limits.weekly, - planType: backend.planType ?? limits.planType, + planType, ...(rateLimitResetCredits !== undefined ? { rateLimitResetCredits } : {}), updatedAt: backend.updatedAt } diff --git a/src/main/rate-limits/providers/codex/codex-fetcher.ts b/src/main/rate-limits/providers/codex/codex-fetcher.ts index c5c3757d9f7..e47a6bc9a07 100644 --- a/src/main/rate-limits/providers/codex/codex-fetcher.ts +++ b/src/main/rate-limits/providers/codex/codex-fetcher.ts @@ -2,6 +2,7 @@ import type { CodexRateLimitResetOutcome, ProviderRateLimits } from '../../../../shared/agent-usage/rate-limits/rate-limit-types' +import { withCodexReadingAccount } from './codex-reading-account' import { isCodexAuthError } from '../../../../shared/agent-accounts/codex/codex-auth-errors' import { buildWslExecArgs, @@ -165,6 +166,12 @@ async function fetchBackendUsage( export async function fetchCodexRateLimits( options?: CodexRateLimitFetchOptions +): Promise { + return withCodexReadingAccount(await readCodexRateLimits(options), options?.readingAccount) +} + +async function readCodexRateLimits( + options?: CodexRateLimitFetchOptions ): Promise { if (options?.signal?.aborted) { return abortedCodexRateLimitResult() diff --git a/src/main/rate-limits/providers/codex/codex-rate-limit-fetch-options.ts b/src/main/rate-limits/providers/codex/codex-rate-limit-fetch-options.ts index 5d583330458..60140a87e45 100644 --- a/src/main/rate-limits/providers/codex/codex-rate-limit-fetch-options.ts +++ b/src/main/rate-limits/providers/codex/codex-rate-limit-fetch-options.ts @@ -1,7 +1,10 @@ import type { NetworkProxySettings } from '../../../../shared/network-proxy' +import type { UsageReadingAccount } from '../../../../shared/agent-usage/rate-limits/rate-limit-types' export type CodexRateLimitFetchOptions = { codexHomePath?: string | null + /** The saved account that owns `codexHomePath`; named on a successful reading. */ + readingAccount?: UsageReadingAccount networkProxySettings?: NetworkProxySettings signal?: AbortSignal } diff --git a/src/main/rate-limits/providers/codex/codex-rate-limit-window-classification.ts b/src/main/rate-limits/providers/codex/codex-rate-limit-window-classification.ts index c425d8b9d2e..12f95d2d7a0 100644 --- a/src/main/rate-limits/providers/codex/codex-rate-limit-window-classification.ts +++ b/src/main/rate-limits/providers/codex/codex-rate-limit-window-classification.ts @@ -25,6 +25,8 @@ export type CodexRateLimitWindowsSnapshot = { unlimited?: boolean balance?: string | number } | null + /** The account's plan, e.g. "pro"; older app-servers omit it. */ + planType?: unknown } type MappableCodexRateWindowSnapshot = CodexRateWindowSnapshot & { usedPercent: number } diff --git a/src/main/rate-limits/providers/codex/codex-reading-account.ts b/src/main/rate-limits/providers/codex/codex-reading-account.ts new file mode 100644 index 00000000000..7818233ddd5 --- /dev/null +++ b/src/main/rate-limits/providers/codex/codex-reading-account.ts @@ -0,0 +1,14 @@ +import type { + ProviderRateLimits, + UsageReadingAccount +} from '../../../../shared/agent-usage/rate-limits/rate-limit-types' + +/** Names the saved account on a successful reading of its own home; failures never carry it. */ +export function withCodexReadingAccount( + limits: ProviderRateLimits, + readingAccount: UsageReadingAccount | undefined +): ProviderRateLimits { + return readingAccount && limits.status === 'ok' + ? { ...limits, usageMetadata: { ...limits.usageMetadata, readingAccount } } + : limits +} diff --git a/src/main/rate-limits/providers/codex/codex-rpc-rate-limit-mapper.test.ts b/src/main/rate-limits/providers/codex/codex-rpc-rate-limit-mapper.test.ts new file mode 100644 index 00000000000..7fdb66322b0 --- /dev/null +++ b/src/main/rate-limits/providers/codex/codex-rpc-rate-limit-mapper.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from 'vitest' +import { mapCodexRpcRateLimits } from './codex-rpc-rate-limit-mapper' + +describe('mapCodexRpcRateLimits', () => { + it('keeps the plan the app-server reports with usage', () => { + const limits = mapCodexRpcRateLimits({ + rateLimits: { primary: { usedPercent: 10, windowDurationMins: 300 }, planType: 'pro' } + }) + expect(limits.planType).toBe('pro') + }) +}) diff --git a/src/main/rate-limits/providers/codex/codex-rpc-rate-limit-mapper.ts b/src/main/rate-limits/providers/codex/codex-rpc-rate-limit-mapper.ts index 081436ee3e1..282e727be1a 100644 --- a/src/main/rate-limits/providers/codex/codex-rpc-rate-limit-mapper.ts +++ b/src/main/rate-limits/providers/codex/codex-rpc-rate-limit-mapper.ts @@ -29,6 +29,7 @@ export function mapCodexRpcRateLimits(wrapper: RpcRateLimitsResponse): ProviderR // Why: workspace seats can report only a spend cap; like Claude's spend limit, show it only when no 5h/7d window exists. const monthly = session || weekly ? null : mapCodexIndividualLimitWindow(wrapper?.rateLimits?.individualLimit) + const planType = wrapper?.rateLimits?.planType return { provider: 'codex', session, @@ -36,6 +37,7 @@ export function mapCodexRpcRateLimits(wrapper: RpcRateLimitsResponse): ProviderR monthly, ...(credits !== undefined ? { rateLimitResetCredits: credits } : {}), ...(extraUsage ? { extraUsage } : {}), + ...(typeof planType === 'string' ? { planType } : {}), updatedAt: Date.now(), error: null, status: 'ok' diff --git a/src/main/rate-limits/service/service-fetch-policy.ts b/src/main/rate-limits/service/service-fetch-policy.ts index 78d303ba1cc..3468ae98c77 100644 --- a/src/main/rate-limits/service/service-fetch-policy.ts +++ b/src/main/rate-limits/service/service-fetch-policy.ts @@ -177,6 +177,8 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT } // Kept snapshots can outlive a reset; never relabel a past-reset window as live. const inherited = previous ? withoutResetWindows(previous, now) : null + // Statusline posts carry no plan; keep the one read for this same login, with its account. + const sameLogin = inherited?.usageMetadata?.authProvenance === snapshot.provenance // Partial statusline payloads leave unreported windows unchanged. const session = freshSession ?? inherited?.session ?? null const weekly = freshWeekly ?? inherited?.weekly ?? null @@ -228,6 +230,7 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT // Statusline lacks Fable scope and credits; retain the latest OAuth values. fableWeekly: inherited?.fableWeekly ?? null, extraUsage: inherited?.extraUsage ?? null, + ...(sameLogin && inherited.planType ? { planType: inherited.planType } : {}), updatedAt: Date.now(), error: null, status: 'ok', @@ -236,7 +239,10 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT lastSuccessfulSource: 'live-session', credentialSource: previous?.usageMetadata?.credentialSource, retryAtMs: previous?.usageMetadata?.retryAtMs, - authProvenance: snapshot.provenance + authProvenance: snapshot.provenance, + ...(sameLogin && inherited.usageMetadata?.readingAccount + ? { readingAccount: inherited.usageMetadata.readingAccount } + : {}) } } }) diff --git a/src/main/rate-limits/service/service-fetch-targets.ts b/src/main/rate-limits/service/service-fetch-targets.ts index 13e0370974c..c1b7b2404ea 100644 --- a/src/main/rate-limits/service/service-fetch-targets.ts +++ b/src/main/rate-limits/service/service-fetch-targets.ts @@ -1,5 +1,6 @@ import { RateLimitServiceResultPolicy } from './service-result-policy' import { fetchCodexRateLimits } from '../providers/codex/codex-fetcher' +import { withCodexReadingAccount } from '../providers/codex/codex-reading-account' import { fetchKimiRateLimits } from '../providers/kimi/kimi-fetcher' import { isSystemDefaultClaudeAuth, @@ -17,7 +18,8 @@ import type { NormalizedClaudeAccountSelectionTarget } from '../../claude-accoun import type { ProviderRateLimits, RateLimitState, - CodexRateLimitResetOutcome + CodexRateLimitResetOutcome, + UsageReadingAccount } from '../../../shared/agent-usage/rate-limits/rate-limit-types' import { ApiKeyFileUnreadableError } from '../../credentials/api-key-file-unreadable-error' @@ -51,6 +53,7 @@ export abstract class RateLimitServiceFetchTargets extends RateLimitServiceResul protected async resolveCodexHome(target?: CodexAccountSelectionTarget): Promise<{ skip: boolean homePath: string | null + readingAccount?: UsageReadingAccount }> { const resolution = await this.codexHomePathResolver?.(target) if (!resolution) { @@ -58,7 +61,11 @@ export abstract class RateLimitServiceFetchTargets extends RateLimitServiceResul } return resolution.kind === 'skip' ? { skip: true, homePath: null } - : { skip: false, homePath: resolution.codexHomePath } + : { + skip: false, + homePath: resolution.codexHomePath, + readingAccount: resolution.readingAccount + } } // WSL home resolution probes wsl.exe; chain it so other providers start immediately. @@ -153,7 +160,6 @@ export abstract class RateLimitServiceFetchTargets extends RateLimitServiceResul } } - const scopedCodex = this.applyStalePolicy(fresh, stateBeforeReset.codex) const currentCodexHome = await this.resolveCodexHome(target) // Skips carry no provenance; never publish them as System Default usage. const stillActive = @@ -161,13 +167,18 @@ export abstract class RateLimitServiceFetchTargets extends RateLimitServiceResul this.isSameCodexTarget(this.codexFetchTarget, target) && this.getCodexProvenance(target, currentCodexHome.homePath) === this.getCodexProvenance(target, codexHomePath) + // Still the redeemed home, so its account (if it is that account's own home) took this reading. + const attributed = stillActive + ? withCodexReadingAccount(fresh, currentCodexHome.readingAccount) + : fresh + const scopedCodex = this.applyStalePolicy(attributed, stateBeforeReset.codex) if (stillActive) { // Redemption is newer than prior reads; invalidate their generations before publishing. this.codexFetchGeneration += 1 this.trackActiveFailureStreak('codex', fresh) this.updateState({ ...this.state, - codex: this.applyStalePolicy(fresh, this.state.codex) + codex: this.applyStalePolicy(attributed, this.state.codex) }) } diff --git a/src/main/rate-limits/service/service-full-cycle-preparation.ts b/src/main/rate-limits/service/service-full-cycle-preparation.ts index 97a0148a86a..6c9e5e04102 100644 --- a/src/main/rate-limits/service/service-full-cycle-preparation.ts +++ b/src/main/rate-limits/service/service-full-cycle-preparation.ts @@ -240,6 +240,7 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ : (missingWslCodexHome ?? fetchCodexRateLimits({ codexHomePath, + readingAccount: codexHome.readingAccount, networkProxySettings: this.networkProxySettingsResolver?.(), signal })), diff --git a/src/main/rate-limits/service/service-inactive-accounts.ts b/src/main/rate-limits/service/service-inactive-accounts.ts index 60b86fced7a..f2fcc7a4ef7 100644 --- a/src/main/rate-limits/service/service-inactive-accounts.ts +++ b/src/main/rate-limits/service/service-inactive-accounts.ts @@ -146,6 +146,7 @@ export abstract class RateLimitServiceInactiveAccounts extends RateLimitServiceP // Read the managed home directly; do not materialize credentials in the shared runtime. const fresh = await fetchCodexRateLimits({ codexHomePath: home.managedHomePath, + readingAccount: account.readingAccount, networkProxySettings: this.networkProxySettingsResolver?.(), signal }) diff --git a/src/main/rate-limits/service/service-provider-cycles.ts b/src/main/rate-limits/service/service-provider-cycles.ts index cae1f3332e1..71f74da5766 100644 --- a/src/main/rate-limits/service/service-provider-cycles.ts +++ b/src/main/rate-limits/service/service-provider-cycles.ts @@ -40,6 +40,7 @@ export abstract class RateLimitServiceProviderCycles extends RateLimitServiceFul ? Promise.resolve(missingWslCodexHome) : fetchCodexRateLimits({ codexHomePath, + readingAccount: codexHome.readingAccount, networkProxySettings: this.networkProxySettingsResolver?.(), signal }) diff --git a/src/main/rate-limits/service/service-refresh-orchestration.test.ts b/src/main/rate-limits/service/service-refresh-orchestration.test.ts index c81e5264bf7..c1fb7e761e1 100644 --- a/src/main/rate-limits/service/service-refresh-orchestration.test.ts +++ b/src/main/rate-limits/service/service-refresh-orchestration.test.ts @@ -3,7 +3,10 @@ import type { ProviderRateLimits } from '../../../shared/agent-usage/rate-limits import { RateLimitService } from './rate-limit-service' import { fetchActiveClaudeRateLimits } from '../providers/claude/claude-active-usage-fetch' import { fetchInactiveClaudeAccountUsage } from '../providers/claude/claude-managed-account-usage' -import { fetchCodexRateLimits } from '../providers/codex/codex-fetcher' +import { + consumeCodexRateLimitResetCredit, + fetchCodexRateLimits +} from '../providers/codex/codex-fetcher' import { deferred, flushMicrotasks, @@ -306,4 +309,70 @@ describe('RateLimitService', () => { }) } ) + it('keeps the read plan and its account on live posts only from that same login', async () => { + mockFreshBackgroundProviderFetches() + const service = new RateLimitService() + let provenance = 'profile:a' + service.setClaudeAuthPreparationResolver(async () => ({ + configDir: '/claude/a', + envPatch: { CLAUDE_CONFIG_DIR: '/claude/a' }, + provenance + })) + const readingAccount = { accountId: 'a', runtime: 'host', wslDistro: null } as const + vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce({ + ...okProvider('claude', 10), + planType: 'max_20x', + usageMetadata: { authProvenance: 'profile:a', readingAccount } + }) + await service.refresh() + service.ingestLiveClaudeRateLimits({ + configDir: '/claude/a', + fiveHour: { used_percentage: 30 }, + sevenDay: null + }) + expect(service.getState().claude).toMatchObject({ + session: { usedPercent: 30 }, + planType: 'max_20x', + usageMetadata: { source: 'live-session', readingAccount } + }) + + // The same folder now holds another login: its posts must not inherit a's plan. + provenance = 'system' + vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce(okProvider('claude', 5)) + await service.refreshClaudeForTarget() + service.ingestLiveClaudeRateLimits({ + configDir: '/claude/a', + fiveHour: { used_percentage: 40 }, + sevenDay: null + }) + expect(service.getState().claude?.session?.usedPercent).toBe(40) + expect(service.getState().claude?.planType).toBeUndefined() + expect(service.getState().claude?.usageMetadata?.readingAccount).toBeUndefined() + }) + it('keeps the account on the usage read right after redeeming a Codex reset', async () => { + mockFreshBackgroundProviderFetches() + const service = new RateLimitService() + const readingAccount = { accountId: 'a', runtime: 'host', wslDistro: null } as const + service.setCodexHomePathResolver(() => ({ + kind: 'ready', + codexHomePath: '/codex/a', + readingAccount + })) + vi.mocked(fetchCodexRateLimits).mockResolvedValueOnce(okProvider('codex', 50)) + await service.refresh() + vi.mocked(consumeCodexRateLimitResetCredit).mockResolvedValueOnce('reset') + vi.mocked(fetchCodexRateLimits).mockResolvedValueOnce({ + ...okProvider('codex', 0), + planType: 'pro' + }) + const { state } = await service.consumeCodexRateLimitResetCredit({ + idempotencyKey: 'key', + target: { runtime: 'host', wslDistro: null }, + codexHomePath: '/codex/a' + }) + // The reply replaces the renderer's state, so it must name the account as the push does. + for (const codex of [service.getState().codex, state.codex]) { + expect(codex).toMatchObject({ planType: 'pro', usageMetadata: { readingAccount } }) + } + }) }) diff --git a/src/main/rate-limits/service/service-types.ts b/src/main/rate-limits/service/service-types.ts index 6a3f0fd03bd..7b429a4670f 100644 --- a/src/main/rate-limits/service/service-types.ts +++ b/src/main/rate-limits/service/service-types.ts @@ -1,4 +1,7 @@ -import type { ProviderRateLimits } from '../../../shared/agent-usage/rate-limits/rate-limit-types' +import type { + ProviderRateLimits, + UsageReadingAccount +} from '../../../shared/agent-usage/rate-limits/rate-limit-types' import type { ZcodePlanSite } from '../../../shared/agent-accounts/usage-credentials/zcode-plan-sites' import type { ClaudeRuntimeAuthPreparation } from '../../claude-accounts/runtime-auth/runtime-auth-types' import type { ClaudeAccountSelectionTarget } from '../../claude-accounts/selection/runtime-selection' @@ -10,6 +13,8 @@ export type InactiveCodexHome = { kind: 'ready'; managedHomePath: string } | { k export type InactiveCodexAccountInfo = { id: string + /** Absent when the saved account cannot name its runtime slot, e.g. a WSL account without a distro. */ + readingAccount?: UsageReadingAccount /** May be async: a WSL home is checked before a preview reads it. */ resolveHome: () => InactiveCodexHome | Promise } diff --git a/src/renderer/src/components/settings/accounts/AccountsPane.tsx b/src/renderer/src/components/settings/accounts/AccountsPane.tsx index f97d5d0bae3..6cebbb0110b 100644 --- a/src/renderer/src/components/settings/accounts/AccountsPane.tsx +++ b/src/renderer/src/components/settings/accounts/AccountsPane.tsx @@ -5,6 +5,8 @@ import type { CodexRateLimitAccountsState } from '../../../../../shared/agent-accounts/managed-account-types' import type { CodexConfigSyncStatus } from '../../../../../shared/agent-accounts/codex/codex-config-sync-types' +import type { RateLimitState } from '../../../../../shared/agent-usage/rate-limits/rate-limit-types' +import { useObservedAccountPlans } from './use-observed-account-plans' import { toast } from 'sonner' import { useAppStore } from '../../../store/index' import { translate } from '@/i18n/i18n' @@ -146,6 +148,22 @@ export function AccountsPane({ const [ownerClaudeAccounts, setClaudeAccounts] = useState(emptyClaudeAccountsState) const [claudeAction, setClaudeAction] = useState('idle') + // A remote host's usage comes only from its own stream; this desktop's polls describe other logins. + const [ownerUsage, setOwnerUsage] = useState<{ + environmentId: string + rateLimits: RateLimitState | null + } | null>(null) + const claudeSectionShown = matchesSettingsSearch(searchQuery, getAccountsClaudeSearchEntries()) + const codexSectionShown = matchesSettingsSearch(searchQuery, getAccountsCodexSearchEntries()) + const { claudeAccountPlans, codexAccountPlans } = useObservedAccountPlans({ + isRemoteAccountScope, + ownerUsage: + scopeEnvironmentId && ownerUsage?.environmentId === scopeEnvironmentId + ? ownerUsage.rateLimits + : null, + claudeShown: claudeSectionShown, + codexShown: codexSectionShown + }) // This desktop's names change with its settings, e.g. a rename in another window. const localNames = isRemoteAccountScope ? undefined : settings.managedAccountDisplayNames const codexAccounts = useMemo( @@ -249,7 +267,11 @@ export function AccountsPane({ if (!snapshot.failedProviders?.includes('claude')) { setClaudeAccounts(snapshot.claude) } + if (scopeEnvironmentId) { + setOwnerUsage({ environmentId: scopeEnvironmentId, rateLimits: snapshot.rateLimits }) + } }, + onClosedAfterSnapshot: () => setOwnerUsage(null), onError: (error) => { toast.error( translate( @@ -328,6 +350,8 @@ export function AccountsPane({ codexConfigSyncWarning, codexRateLimits, codexRateLimitTarget, + claudeAccountPlans, + codexAccountPlans, setRemoveCodexTarget, runCodexAccountAction, recordOpenCodeSettingEdit @@ -345,12 +369,8 @@ export function AccountsPane({ matchesSettingsSearch(searchQuery, getAccountsLocationSearchEntries()) ? renderAccountsLocationSection(model, t) : null, - matchesSettingsSearch(searchQuery, getAccountsClaudeSearchEntries()) - ? renderClaudeAccountsSection(model, t, intlLocale) - : null, - matchesSettingsSearch(searchQuery, getAccountsCodexSearchEntries()) - ? renderCodexAccountsSection(model, t, intlLocale) - : null, + claudeSectionShown ? renderClaudeAccountsSection(model, t, intlLocale) : null, + codexSectionShown ? renderCodexAccountsSection(model, t, intlLocale) : null, matchesSettingsSearch(searchQuery, getAccountsGeminiSearchEntries()) ? renderGeminiAccountsSection(model, t) : null, diff --git a/src/renderer/src/components/settings/accounts/accounts-pane-types.ts b/src/renderer/src/components/settings/accounts/accounts-pane-types.ts index b498fee06f2..2ad779bd788 100644 --- a/src/renderer/src/components/settings/accounts/accounts-pane-types.ts +++ b/src/renderer/src/components/settings/accounts/accounts-pane-types.ts @@ -1,3 +1,4 @@ +import type { ObservedAccountPlans } from '@/lib/provider-accounts/observed-account-plans' import type { Dispatch, ReactNode, SetStateAction } from 'react' import type { GlobalSettings } from '../../../../../shared/global-settings-types' import type { @@ -118,6 +119,9 @@ export type AccountsPaneSectionModel = { | null codexRateLimits: ProviderRateLimits | null codexRateLimitTarget: RateLimitRuntimeTarget + /** Plans by the saved account each reading names; see `getObservedAccountPlan`. */ + claudeAccountPlans: ObservedAccountPlans + codexAccountPlans: ObservedAccountPlans setRemoveCodexTarget: Dispatch> runCodexAccountAction: CodexAccountActionRunner recordOpenCodeSettingEdit: (field: 'cookie' | 'workspaceId' | 'apiKey') => void diff --git a/src/renderer/src/components/settings/accounts/claude/accounts-pane-claude-account-row.tsx b/src/renderer/src/components/settings/accounts/claude/accounts-pane-claude-account-row.tsx index 53b4a37d189..7273a063134 100644 --- a/src/renderer/src/components/settings/accounts/claude/accounts-pane-claude-account-row.tsx +++ b/src/renderer/src/components/settings/accounts/claude/accounts-pane-claude-account-row.tsx @@ -23,6 +23,7 @@ import { withCopiedClaudeLink } from './claude-sign-in-link-menu' import { AccountRenameButton, renameTargetFor } from '../account-rename-button' +import { getObservedAccountPlan } from '@/lib/provider-accounts/observed-account-plans' export function renderClaudeAccountRow( account: ClaudeRateLimitAccountsState['accounts'][number], @@ -35,6 +36,7 @@ export function renderClaudeAccountRow( accountRuntime, accountRuntimeUnavailable, accountVisibilityOptions, + claudeAccountPlans, claudeAccounts, claudeAction, isRemoteAccountScope, @@ -53,6 +55,7 @@ export function renderClaudeAccountRow( const isBusy = claudeAction !== 'idle' || accountRuntimeUnavailable const accountRuntimeView = getProviderAccountRuntime(account) const accountLabel = getManagedAccountPrimaryLabel(account) + const plan = getObservedAccountPlan(claudeAccountPlans, account.id, accountRuntimeView) // A named row keeps its sign-in email visible, most of all when it needs signing in. const namedEmail = account.displayName ? account.email : null const reauthenticate = (copyLink: boolean): Promise => @@ -121,6 +124,7 @@ export function renderClaudeAccountRow( ] : [ account.organizationName, + plan, namedEmail, formatAccountTimestamp(account.lastAuthenticatedAt, intlLocale) ] diff --git a/src/renderer/src/components/settings/accounts/codex/accounts-pane-codex-account-row.tsx b/src/renderer/src/components/settings/accounts/codex/accounts-pane-codex-account-row.tsx index 8f27d12130f..b293ebe4be4 100644 --- a/src/renderer/src/components/settings/accounts/codex/accounts-pane-codex-account-row.tsx +++ b/src/renderer/src/components/settings/accounts/codex/accounts-pane-codex-account-row.tsx @@ -15,6 +15,7 @@ import { formatAccountTimestamp, getCodexAccountRuntimeLabel } from '../scope/ac import type { AccountsPaneSectionModel } from '../accounts-pane-types' import { getManagedAccountPrimaryLabel } from '../../../../../../shared/agent-accounts/managed-account-display-names' import { AccountRenameButton, renameTargetFor } from '../account-rename-button' +import { getObservedCodexAccountPlan } from '@/lib/provider-accounts/observed-account-plans' export function renderCodexAccountRow( account: CodexRateLimitAccountsState['accounts'][number], @@ -27,6 +28,7 @@ export function renderCodexAccountRow( accountRuntimeUnavailable, accountVisibilityOptions, activeCodexAccountId, + codexAccountPlans, codexAccounts, codexAction, codexRateLimits, @@ -55,6 +57,11 @@ export function renderCodexAccountRow( }) const needsReauthentication = Boolean(accountAuthWarning) const accountDetail = getCodexAccountDisplayDetail(account, codexAccounts.accounts) + const plan = getObservedCodexAccountPlan( + codexAccountPlans, + account, + getProviderAccountRuntime(account) + ) const isReauthing = codexAction === `reauth:${account.id}` const isRemoving = codexAction === `remove:${account.id}` const isBusy = codexAction !== 'idle' || accountRuntimeUnavailable @@ -126,6 +133,12 @@ export function renderCodexAccountRow( • ) : null} + {plan ? ( + <> + {plan} + • + + ) : null} {account.displayName ? ( <> {account.email} diff --git a/src/renderer/src/components/settings/accounts/use-observed-account-plans.ts b/src/renderer/src/components/settings/accounts/use-observed-account-plans.ts new file mode 100644 index 00000000000..e19655915c9 --- /dev/null +++ b/src/renderer/src/components/settings/accounts/use-observed-account-plans.ts @@ -0,0 +1,45 @@ +import { useMemo } from 'react' +import type { RateLimitState } from '../../../../../shared/agent-usage/rate-limits/rate-limit-types' +import { + indexObservedAccountPlans, + type ObservedAccountPlans +} from '@/lib/provider-accounts/observed-account-plans' +import { useAppStore } from '../../../store/index' + +/** Remote rows read only their owner's streamed usage; this desktop's polls describe other logins. + * A provider section hidden by search reads nothing, so usage pushes rebuild no index for it. */ +export function useObservedAccountPlans({ + isRemoteAccountScope, + ownerUsage, + claudeShown, + codexShown +}: { + isRemoteAccountScope: boolean + ownerUsage: RateLimitState | null + claudeShown: boolean + codexShown: boolean +}): { claudeAccountPlans: ObservedAccountPlans; codexAccountPlans: ObservedAccountPlans } { + const readsLocal = !isRemoteAccountScope + const usage = isRemoteAccountScope ? ownerUsage : null + const localClaude = useAppStore((s) => (readsLocal && claudeShown ? s.rateLimits.claude : null)) + const localInactiveClaude = useAppStore((s) => + readsLocal && claudeShown ? s.rateLimits.inactiveClaudeAccounts : null + ) + const localCodex = useAppStore((s) => (readsLocal && codexShown ? s.rateLimits.codex : null)) + const localInactiveCodex = useAppStore((s) => + readsLocal && codexShown ? s.rateLimits.inactiveCodexAccounts : null + ) + const claude = claudeShown ? (usage?.claude ?? localClaude) : null + const inactiveClaude = claudeShown ? (usage?.inactiveClaudeAccounts ?? localInactiveClaude) : null + const codex = codexShown ? (usage?.codex ?? localCodex) : null + const inactiveCodex = codexShown ? (usage?.inactiveCodexAccounts ?? localInactiveCodex) : null + const claudeAccountPlans = useMemo( + () => indexObservedAccountPlans(claude, inactiveClaude), + [claude, inactiveClaude] + ) + const codexAccountPlans = useMemo( + () => indexObservedAccountPlans(codex, inactiveCodex), + [codex, inactiveCodex] + ) + return { claudeAccountPlans, codexAccountPlans } +} diff --git a/src/renderer/src/components/status-bar/usage/usage-roster-formatting.ts b/src/renderer/src/components/status-bar/usage/usage-roster-formatting.ts index e2078854710..2aeb56241e3 100644 --- a/src/renderer/src/components/status-bar/usage/usage-roster-formatting.ts +++ b/src/renderer/src/components/status-bar/usage/usage-roster-formatting.ts @@ -1,6 +1,7 @@ export function formatPlanLabel(planType: string | null | undefined): string | null { const trimmed = planType?.trim() - if (!trimmed) { + // Codex reports "unknown" when it cannot tell; that is no plan, not a plan named Unknown. + if (!trimmed || trimmed.toLowerCase() === 'unknown') { return null } return trimmed diff --git a/src/renderer/src/lib/provider-accounts/observed-account-plans.test.ts b/src/renderer/src/lib/provider-accounts/observed-account-plans.test.ts new file mode 100644 index 00000000000..d8a050459bd --- /dev/null +++ b/src/renderer/src/lib/provider-accounts/observed-account-plans.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest' +import type { + ProviderRateLimits, + UsageReadingAccount +} from '../../../../shared/agent-usage/rate-limits/rate-limit-types' +import { + getObservedAccountPlan, + getObservedCodexAccountPlan, + indexObservedAccountPlans +} from './observed-account-plans' + +const HOST = { runtime: 'host', wslDistro: null } as const + +function reading(planType: string, readingAccount?: UsageReadingAccount): ProviderRateLimits { + return { + provider: 'codex', + session: null, + weekly: null, + planType, + updatedAt: 1, + error: null, + status: 'ok', + ...(readingAccount ? { usageMetadata: { readingAccount } } : {}) + } +} + +describe('observed account plans', () => { + it('shows the active plan on the account it was read for, not the roster selection', () => { + // Another window switched to B; this roster still lists A as selected. + const plans = indexObservedAccountPlans(reading('pro', { accountId: 'b', ...HOST }), []) + expect(getObservedAccountPlan(plans, 'a', HOST)).toBeNull() + expect(getObservedAccountPlan(plans, 'b', HOST)).toBe('Pro') + }) + + it('leaves rows blank for readings that name no account or another one', () => { + const plans = indexObservedAccountPlans(reading('max_20x'), [ + { + accountId: 'a', + rateLimits: reading('team', { accountId: 'c', ...HOST }), + updatedAt: 1, + isFetching: false + }, + { + accountId: 'd', + rateLimits: reading('unknown', { accountId: 'd', ...HOST }), + updatedAt: 1, + isFetching: false + } + ]) + expect(getObservedAccountPlan(plans, 'a', HOST)).toBeNull() + expect(getObservedAccountPlan(plans, 'c', HOST)).toBeNull() + expect(getObservedAccountPlan(plans, 'd', HOST)).toBeNull() + }) + + it('matches a WSL reading only to its own distro', () => { + const plans = indexObservedAccountPlans(null, [ + { + accountId: 'w', + rateLimits: reading('max_20x', { accountId: 'w', runtime: 'wsl', wslDistro: 'Ubuntu' }), + updatedAt: 1, + isFetching: false + } + ]) + expect(getObservedAccountPlan(plans, 'w', { runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe( + 'Max 20x' + ) + expect(getObservedAccountPlan(plans, 'w', { runtime: 'wsl', wslDistro: 'Debian' })).toBeNull() + expect(getObservedAccountPlan(plans, 'w', HOST)).toBeNull() + }) + + it('keeps a Codex workspace label and adds no plan when the label may name one', () => { + const plans = indexObservedAccountPlans(reading('pro', { accountId: 'a', ...HOST }), []) + expect( + getObservedCodexAccountPlan(plans, { id: 'a', workspaceLabel: 'Personal (Plus)' }, HOST) + ).toBeNull() + expect(getObservedCodexAccountPlan(plans, { id: 'a', workspaceLabel: 'Acme' }, HOST)).toBe( + 'Pro' + ) + }) +}) diff --git a/src/renderer/src/lib/provider-accounts/observed-account-plans.ts b/src/renderer/src/lib/provider-accounts/observed-account-plans.ts new file mode 100644 index 00000000000..e04b787f66a --- /dev/null +++ b/src/renderer/src/lib/provider-accounts/observed-account-plans.ts @@ -0,0 +1,73 @@ +import type { + InactiveAccountUsage, + ProviderRateLimits +} from '../../../../shared/agent-usage/rate-limits/rate-limit-types' +import { formatPlanLabel } from '@/components/status-bar/usage/usage-roster-formatting' +import { isCodexPlanWorkspaceLabel } from '../../../../shared/agent-accounts/codex/codex-plan-workspace-label' + +type PlanReading = { label: string; runtime: 'host' | 'wsl'; wslDistro: string | null } + +export type ObservedAccountPlans = ReadonlyMap + +/** Plans keyed by the saved account each successful reading names, never by which account a + * roster says is selected: another window may have switched since that roster was read. */ +export function indexObservedAccountPlans( + active: ProviderRateLimits | null | undefined, + inactive: readonly InactiveAccountUsage[] | null | undefined +): ObservedAccountPlans { + const plans = new Map() + const add = (reading: ProviderRateLimits | null | undefined, cacheId?: string): void => { + const account = reading?.usageMetadata?.readingAccount + const label = formatPlanLabel(reading?.planType) + if ( + !reading || + !account || + !label || + (cacheId !== undefined && cacheId !== account.accountId) + ) { + return + } + const current = plans.get(account.accountId) + if (!current || current.updatedAt < reading.updatedAt) { + plans.set(account.accountId, { + label, + runtime: account.runtime, + wslDistro: account.wslDistro, + updatedAt: reading.updatedAt + }) + } + } + add(active) + for (const entry of inactive ?? []) { + add(entry.rateLimits, entry.accountId) + } + return plans +} + +export function getObservedAccountPlan( + plans: ObservedAccountPlans, + accountId: string, + slot: { runtime: 'host' | 'wsl'; wslDistro: string | null } +): string | null { + const reading = plans.get(accountId) + if (!reading || reading.runtime !== slot.runtime) { + return null + } + // A WSL reading belongs to one named distro, never to whichever distro is the default. + return slot.runtime === 'host' || + (reading.wslDistro !== null && + reading.wslDistro.toLowerCase() === slot.wslDistro?.toLowerCase()) + ? reading.label + : null +} + +/** A saved label like "Personal (Plus)" may already name a plan; never add a second, different one. */ +export function getObservedCodexAccountPlan( + plans: ObservedAccountPlans, + account: { id: string; workspaceLabel?: string | null }, + slot: { runtime: 'host' | 'wsl'; wslDistro: string | null } +): string | null { + return isCodexPlanWorkspaceLabel(account.workspaceLabel) + ? null + : getObservedAccountPlan(plans, account.id, slot) +} diff --git a/src/shared/agent-accounts/codex/codex-plan-workspace-label.ts b/src/shared/agent-accounts/codex/codex-plan-workspace-label.ts new file mode 100644 index 00000000000..6ced3b7cf49 --- /dev/null +++ b/src/shared/agent-accounts/codex/codex-plan-workspace-label.ts @@ -0,0 +1,22 @@ +// Codex tokens often omit workspace_name; the saved workspace label then names the token's plan. +const PLAN_WORKSPACE_LABELS = new Map([ + ['free', 'Personal (Free)'], + ['go', 'Personal (Go)'], + ['plus', 'Personal (Plus)'], + ['pro', 'Personal (Pro)'], + ['team', 'Team'], + ['business', 'Business'], + ['enterprise', 'Enterprise'], + ['edu', 'Education'] +]) + +const PLAN_WORKSPACE_LABEL_VALUES = new Set(PLAN_WORKSPACE_LABELS.values()) + +export function codexPlanWorkspaceLabel(planType: string | null | undefined): string | null { + return (planType && PLAN_WORKSPACE_LABELS.get(planType.toLowerCase())) || null +} + +/** A label that may stand for a plan rather than a workspace; a saved label cannot say which. */ +export function isCodexPlanWorkspaceLabel(label: string | null | undefined): boolean { + return PLAN_WORKSPACE_LABEL_VALUES.has(label?.trim() ?? '') +} diff --git a/src/shared/agent-usage/rate-limits/rate-limit-types.ts b/src/shared/agent-usage/rate-limits/rate-limit-types.ts index 45ff7c408f9..f808f06a654 100644 --- a/src/shared/agent-usage/rate-limits/rate-limit-types.ts +++ b/src/shared/agent-usage/rate-limits/rate-limit-types.ts @@ -70,6 +70,13 @@ export type OwnerNotSetUpPlaceholder = /** The host reports Claude on API-key billing and with no login alike, so it cannot say which. */ | { kind: 'claude-unknown'; ownerLabel: string } +/** The saved account and runtime slot whose credentials a successful reading used. */ +export type UsageReadingAccount = { + accountId: string + runtime: 'host' | 'wsl' + wslDistro: string | null +} + export type UsageRateLimitMetadata = { source?: UsageRateLimitSource attemptedSources?: UsageRateLimitSource[] @@ -85,6 +92,8 @@ export type UsageRateLimitMetadata = { ownerNotSetUp?: OwnerNotSetUpPlaceholder /** Antigravity: the native login verified before and after the read; id is null for an unsaved login. */ account?: { id: string | null; email: string | null } + /** Claude/Codex: set only on a successful reading of one saved account; older hosts omit it. */ + readingAccount?: UsageReadingAccount } export type ProviderRateLimits = {