mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 19:07:41 +00:00
feat(accounts): show each saved Claude and Codex account's observed plan (#42917)
* feat(accounts): show each saved Claude and Codex account's observed plan
Settings > Accounts rows now show the plan Orca already observed for that
exact account ("Max 20x", "Pro", "Team"); unknown stays blank. The usage
roster's plan slot no longer shows "Unknown".
- Claude: read subscriptionType/rateLimitTier from the credential candidate
already chosen, tolerantly; the tier only refines Max.
- Codex: keep the plan the app-server already returns with usage.
- Each successful Claude/Codex reading names the saved account and runtime
slot it was read for; rows match that, never the roster's selection, so a
switch in another window cannot paint one account's plan on another.
Older hosts send no stamp and their rows stay blank.
- Remote rows use only the owner's account stream.
- A Codex workspace label that may itself name a plan is kept and gets no
second plan.
* fix(accounts): keep plan attribution through Codex resets and spend-capped supplements
- Stamp the usage read that follows a reset-credit redemption with the
redeemed home's account, so the row keeps its plan.
- Keep the backend plan when the HTTP supplement adds only a monthly window.
- Keep the Claude plan spelling Claude Code wrote.
- Remote scope ignores this desktop's usage pushes.
* fix(accounts): name the account on the reset reply and skip plans for hidden sections
- The reset reply replaces the renderer's usage state, so stamp it the same
way as the published reading.
- A provider section hidden by Settings search builds no plan index.
This commit is contained in:
@@ -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 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 } }
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 } }
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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<string, unknown> | 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) {
|
||||
|
||||
+2
-1
@@ -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)
|
||||
|
||||
@@ -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' }
|
||||
|
||||
+2
-1
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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' }
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseClaudeOAuthCredentialsJson } from './claude-oauth-credentials'
|
||||
|
||||
function parse(oauth: Record<string, unknown>): ReturnType<typeof parseClaudeOAuthCredentialsJson> {
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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' }
|
||||
}
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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<ProviderRateLimits> {
|
||||
return withCodexReadingAccount(await readCodexRateLimits(options), options?.readingAccount)
|
||||
}
|
||||
|
||||
async function readCodexRateLimits(
|
||||
options?: CodexRateLimitFetchOptions
|
||||
): Promise<ProviderRateLimits> {
|
||||
if (options?.signal?.aborted) {
|
||||
return abortedCodexRateLimitResult()
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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'
|
||||
|
||||
@@ -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 }
|
||||
: {})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -240,6 +240,7 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ
|
||||
: (missingWslCodexHome ??
|
||||
fetchCodexRateLimits({
|
||||
codexHomePath,
|
||||
readingAccount: codexHome.readingAccount,
|
||||
networkProxySettings: this.networkProxySettingsResolver?.(),
|
||||
signal
|
||||
})),
|
||||
|
||||
@@ -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
|
||||
})
|
||||
|
||||
@@ -40,6 +40,7 @@ export abstract class RateLimitServiceProviderCycles extends RateLimitServiceFul
|
||||
? Promise.resolve(missingWslCodexHome)
|
||||
: fetchCodexRateLimits({
|
||||
codexHomePath,
|
||||
readingAccount: codexHome.readingAccount,
|
||||
networkProxySettings: this.networkProxySettingsResolver?.(),
|
||||
signal
|
||||
})
|
||||
|
||||
@@ -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 } })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<InactiveCodexHome>
|
||||
}
|
||||
|
||||
@@ -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<ClaudeRateLimitAccountsState>(emptyClaudeAccountsState)
|
||||
const [claudeAction, setClaudeAction] = useState<ProviderAccountAction>('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,
|
||||
|
||||
@@ -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<SetStateAction<RemoveAccountTarget | null>>
|
||||
runCodexAccountAction: CodexAccountActionRunner
|
||||
recordOpenCodeSettingEdit: (field: 'cookie' | 'workspaceId' | 'apiKey') => void
|
||||
|
||||
+4
@@ -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<void> =>
|
||||
@@ -121,6 +124,7 @@ export function renderClaudeAccountRow(
|
||||
]
|
||||
: [
|
||||
account.organizationName,
|
||||
plan,
|
||||
namedEmail,
|
||||
formatAccountTimestamp(account.lastAuthenticatedAt, intlLocale)
|
||||
]
|
||||
|
||||
+13
@@ -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(
|
||||
<span className="shrink-0 opacity-50">•</span>
|
||||
</>
|
||||
) : null}
|
||||
{plan ? (
|
||||
<>
|
||||
<span className="shrink-0">{plan}</span>
|
||||
<span className="shrink-0 opacity-50">•</span>
|
||||
</>
|
||||
) : null}
|
||||
{account.displayName ? (
|
||||
<>
|
||||
<span className="min-w-0 truncate">{account.email}</span>
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -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<string, PlanReading>
|
||||
|
||||
/** 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<string, PlanReading & { updatedAt: number }>()
|
||||
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)
|
||||
}
|
||||
@@ -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() ?? '')
|
||||
}
|
||||
@@ -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 = {
|
||||
|
||||
Reference in New Issue
Block a user