🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-quota): open the quota calendar to codex and kimi-code, ledger codex turns (#19770)
Arvin Xu5cfd45f2480b
diff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.tsindex 71fdb68b7f8..642081041c5 100644--- a/apps/server/src/routers/lambda/agentQuota.ts+++ b/apps/server/src/routers/lambda/agentQuota.ts@@ -336,9 +336,18 @@ export const agentQuotaRouter = router({.query(async ({ ctx, input }) => ctx.quotaService.resolveAccountLoads(input.accountIds)),selectAccountForAgent: quotaProcedure- .input(z.object({ agentId: z.string(), modelScope: z.string().optional() }))+ .input(+ z.object({+ agentId: z.string(),+ modelScope: z.string().optional(),+ provider: z.string().optional(),+ }),+ ).query(async ({ ctx, input }) =>- ctx.quotaService.selectForAgent(input.agentId, { modelScope: input.modelScope }),+ ctx.quotaService.selectForAgent(input.agentId, {+ modelScope: input.modelScope,+ provider: input.provider,+ }),),});diff --git a/apps/server/src/services/agentQuota/__tests__/index.test.ts b/apps/server/src/services/agentQuota/__tests__/index.test.tsindex 2487b31fdf4..ae7549b6ca3 100644--- a/apps/server/src/services/agentQuota/__tests__/index.test.ts+++ b/apps/server/src/services/agentQuota/__tests__/index.test.ts@@ -4,13 +4,15 @@ import type { QuotaLimitReading } from '@lobechat/heterogeneous-agents/quota';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import {+ AgentAccountBindingModel,AgentProviderAccountModel,AgentQuotaCalibrationModel,AgentQuotaUsageLedgerModel,AgentQuotaWindowModel,} from '@/database/models/agentQuota';-import { users } from '@/database/schemas';+import { agents, users } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { QuotaBindingRole } from '@/database/types/agentQuota';import { AgentQuotaService } from '../index';@@ -142,6 +144,48 @@ describe('AgentQuotaService.ingestSnapshot', () => {});});+describe('AgentQuotaService.selectForAgent', () => {+ it('never routes a caller onto another provider’s account, pinned or pooled', async () => {+ // Bindings are written provider-blind from the account manager; a claude+ // caller must not inherit a codex/kimi pin (Codex review on PR #19770).+ const bindings = new AgentAccountBindingModel(serverDB, userId);+ await serverDB.insert(agents).values([+ { id: 'agent-1', slug: 'agent-1', title: 'Agent 1', userId },+ { id: 'agent-2', slug: 'agent-2', title: 'Agent 2', userId },+ ]);+ const claudeAccount = await service.ingestSnapshot({+ identity: { externalAccountId: 'claude-acc' },+ provider: 'claude-code',+ readings: [],+ });+ const codexAccount = await service.ingestSnapshot({+ identity: { externalAccountId: 'codex-acc' },+ provider: 'codex',+ readings: [],+ });+ await bindings.upsert({+ accountId: codexAccount.id,+ agentId: 'agent-1',+ role: QuotaBindingRole.pinned,+ });++ // Without a provider the historical behavior is unchanged…+ expect((await service.selectForAgent('agent-1'))?.accountId).toBe(codexAccount.id);+ // …but a claude caller skips the foreign pin and finds no route.+ expect(await service.selectForAgent('agent-1', { provider: 'claude-code' })).toBeNull();++ // A same-provider pin is honored.+ await bindings.upsert({+ accountId: claudeAccount.id,+ agentId: 'agent-2',+ role: QuotaBindingRole.pinned,+ });+ expect((await service.selectForAgent('agent-2', { provider: 'claude-code' }))?.accountId).toBe(+ claudeAccount.id,+ );+ });+});+describe('AgentQuotaService.listLatestReadings', () => {const now = Date.parse('2026-07-02T00:00:00Z');const weeklyReading = {@@ -238,6 +282,31 @@ describe('AgentQuotaService.recordUsage', () => {expect(await ledger.sumCostUsd(account.id, from, to)).toBeCloseTo(2.175, 6);});+ it('creates the account for a first-run turn instead of landing it unattributed', async () => {+ // A codex run can outrun the quota menu's ingestion: the account row does+ // not exist yet when the first usage arrives (Codex review on PR #19770).+ const accounts = new AgentProviderAccountModel(serverDB, userId);+ await service.recordUsage({+ externalAccountId: 'codex-fresh-acc',+ messageId: 'msg-first-run',+ model: 'gpt-5.3-codex',+ occurredAt: Date.parse('2026-07-01T01:00:00Z'),+ provider: 'codex',+ usage: { input: 1000, output: 500 },+ });++ const account = await accounts.findByExternalId('codex', 'codex-fresh-acc');+ expect(account).not.toBeNull();+ // The ledger row is attributed to the freshly created account.+ expect(+ await ledger.sumCostUsd(+ account!.id,+ new Date('2026-07-01T00:00:00Z'),+ new Date('2026-07-01T02:00:00Z'),+ ),+ ).toBeGreaterThan(0);+ });+it('stores tokens without a cost for a model the bank does not know', async () => {const account = await service.ingestSnapshot({identity,@@ -274,6 +343,59 @@ describe('AgentQuotaService.recordUsage', () => {});// no throw = pass; the row is accountId-null and excluded from calibration});++ it('prices a codex turn from the openai model bank, reasoning at the output rate', async () => {+ const account = await service.ingestSnapshot({+ identity,+ provider: 'codex',+ readings: [],+ });++ await service.recordUsage({+ externalAccountId: identity.externalAccountId,+ messageId: 'msg-codex-1',+ model: 'gpt-5.3-codex',+ occurredAt: Date.parse('2026-07-01T01:00:00Z'),+ provider: 'codex',+ usage: { cacheRead: 1_000_000, input: 10_000, output: 30_000, reasoning: 10_000 },+ });++ // gpt-5.3-codex: in $1.75, out $14, cacheRead $0.175 per MTok →+ // 0.01*1.75 + (0.03+0.01)*14 + 1*0.175 = 0.7525+ expect(+ await ledger.sumCostUsd(+ account.id,+ new Date('2026-07-01T00:00:00Z'),+ new Date('2026-07-01T02:00:00Z'),+ ),+ ).toBeCloseTo(0.7525, 6);+ });++ it('stores tokens without a cost for a codex model the bank does not know', async () => {+ const account = await service.ingestSnapshot({+ identity,+ provider: 'codex',+ readings: [],+ });++ await service.recordUsage({+ externalAccountId: identity.externalAccountId,+ messageId: 'msg-unknown-codex-model',+ model: 'gpt-9-codex',+ occurredAt: Date.parse('2026-07-01T01:00:00Z'),+ provider: 'codex',+ usage: { output: 40_000 },+ });++ // row exists (tokens kept) but contributes no fabricated cost+ expect(+ await ledger.sumCostUsd(+ account.id,+ new Date('2026-07-01T00:00:00Z'),+ new Date('2026-07-01T02:00:00Z'),+ ),+ ).toBe(0);+ });});describe('Codex quota persistence', () => {diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.tsindex 2c28161bfa5..b0822cc8edb 100644--- a/apps/server/src/services/agentQuota/index.ts+++ b/apps/server/src/services/agentQuota/index.ts@@ -33,7 +33,7 @@ import {QuotaCostSource,} from '@/database/types/agentQuota';-import { claudeModelPrice } from './pricing';+import { claudeModelPrice, codexModelPrice } from './pricing';const readQuotaWindowMetadata = (raw: Record<string, unknown> | null) => ({...(typeof raw?.windowMinutes === 'number' &&@@ -242,10 +242,21 @@ export class AgentQuotaService {if (!externalEventId) return;const account = params.externalAccountId- ? await this.accounts.findByExternalId(params.provider, params.externalAccountId)+ ? ((await this.accounts.findByExternalId(params.provider, params.externalAccountId)) ??+ // A first-run turn can arrive before any snapshot ingestion created the+ // account row. Create it here or the turn is permanently unattributed —+ // later snapshot ingestion does not backfill existing ledger rows. The+ // remaining identity fields are enriched by the next snapshot upsert.+ (await this.accounts.upsertByIdentity(params.provider, {+ externalAccountId: params.externalAccountId,+ }))): null;- const price = params.model ? claudeModelPrice(params.model) : null;+ const price = params.model+ ? params.provider === 'codex'+ ? codexModelPrice(params.model)+ : claudeModelPrice(params.model)+ : null;const costUsd = price ? computeTurnCostUsd(params.usage, price) : null;const row = {@@ -405,7 +416,7 @@ export class AgentQuotaService {*/selectForAgent = async (agentId: string,- options: { modelScope?: string; now?: number } = {},+ options: { modelScope?: string; now?: number; provider?: string } = {},): Promise<{accountId: string;credentialMode: string;@@ -430,9 +441,19 @@ export class AgentQuotaService {private selectAccountId = async (agentId: string,- options: { modelScope?: string; now?: number },+ options: { modelScope?: string; now?: number; provider?: string },): Promise<{ accountId: string; reason: 'pinned' | 'balanced' } | null> => {- const bindings = (await this.bindings.listByAgent(agentId)).filter((b) => b.enabled);+ let bindings = (await this.bindings.listByAgent(agentId)).filter((b) => b.enabled);+ // Bindings are written provider-blind; a caller that names its provider+ // must never be routed onto another provider's account, pinned or pooled.+ if (options.provider) {+ const candidates = await Promise.all(+ bindings.map((binding) => this.accounts.findById(binding.accountId)),+ );+ bindings = bindings.filter(+ (binding, index) => candidates[index]?.provider === options.provider,+ );+ }const pinned = bindings.find((b) => b.role === QuotaBindingRole.pinned);if (pinned) return { accountId: pinned.accountId, reason: 'pinned' };diff --git a/apps/server/src/services/agentQuota/pricing.ts b/apps/server/src/services/agentQuota/pricing.tsindex 2841f26edba..65fd35069e8 100644--- a/apps/server/src/services/agentQuota/pricing.ts+++ b/apps/server/src/services/agentQuota/pricing.ts@@ -1,16 +1,26 @@import type { QuotaModelPrice } from '@lobechat/heterogeneous-agents/quota';import anthropicModels from 'model-bank/anthropic';+import openaiModels from 'model-bank/openai';/**- * $ per million tokens for a Claude model, from the model bank. The bank lists- * the base input/output rates plus the cache-read and 5-minute cache-write- * rates; the 1-hour write rate is derived inside `computeTurnCostUsd` (2x base- * input) when not provided. Returns null for models the bank doesn't know —- * the caller should then store the tokens without a computed cost rather than- * guess a price.+ * $ per million tokens for a model, from the model bank. The bank lists the+ * base input/output rates plus the cache-read and 5-minute cache-write rates+ * when the provider has them (OpenAI has no cache-write tier, so it stays+ * undefined); the 1-hour write rate is derived inside `computeTurnCostUsd`+ * (2x base input) when not provided. Returns null for models the bank doesn't+ * know — the caller should then store the tokens without a computed cost+ * rather than guess a price.*/-export const claudeModelPrice = (modelId: string): QuotaModelPrice | null => {- const model = anthropicModels.find((m) => m.id === modelId);+interface BankModelCard {+ id: string;+ pricing?: { units?: { name: string; rate?: number; unit: string }[] };+}++const bankModelPrice = (+ models: readonly BankModelCard[],+ modelId: string,+): QuotaModelPrice | null => {+ const model = models.find((m) => m.id === modelId);const units = model?.pricing?.units;if (!units) return null;@@ -30,3 +40,10 @@ export const claudeModelPrice = (modelId: string): QuotaModelPrice | null => {output,};};++export const claudeModelPrice = (modelId: string): QuotaModelPrice | null =>+ bankModelPrice(anthropicModels, modelId);++/** Codex turns run OpenAI models, priced out of the bank's openai table. */+export const codexModelPrice = (modelId: string): QuotaModelPrice | null =>+ bankModelPrice(openaiModels, modelId);diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex e299e33fc26..e914166f4d3 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -852,6 +852,7 @@"heteroAgent.claudeQuota.calendar.legendMore": "Heavy","heteroAgent.claudeQuota.calendar.legendReset": "Window reset","heteroAgent.claudeQuota.calendar.monthSpend": "Daily spend",+ "heteroAgent.claudeQuota.calendar.monthlyHistory": "Monthly windows","heteroAgent.claudeQuota.calendar.noLedgerSpend": "No token usage recorded in this window","heteroAgent.claudeQuota.calendar.noLedgerSpendHint": "Token history is only recorded for runs started in LobeHub after usage tracking was enabled. Earlier usage and runs started directly from the terminal cannot be backfilled.","heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "History not recorded",@@ -934,6 +935,7 @@"heteroAgent.cloudRepo.noRepos": "No repositories configured. Add them in agent settings.","heteroAgent.cloudRepo.notSet": "No repo selected","heteroAgent.cloudRepo.sectionTitle": "Repositories",+ "heteroAgent.codexQuota.calendar.title": "Codex usage calendar","heteroAgent.codexQuota.doesNotExpire": "Does not expire","heteroAgent.codexQuota.errorConnection": "Couldn't reach the Codex quota endpoint. Check your network or LobeHub proxy settings.","heteroAgent.codexQuota.errorGeneric": "Couldn't load Codex quota. Try again later.",@@ -997,6 +999,7 @@"heteroAgent.executionTarget.workspaceGroup": "Workspace Devices","heteroAgent.fullAccess.label": "Full access","heteroAgent.fullAccess.tooltip": "The local coding agent runs with full read/write access to the working directory. Switching permission modes is not available yet.",+ "heteroAgent.kimiCodeQuota.calendar.title": "Kimi Code usage calendar","heteroAgent.kimiCodeQuota.errorGeneric": "Couldn't load Kimi Code quota. Try again later.","heteroAgent.kimiCodeQuota.extraUsage": "Extra Usage","heteroAgent.kimiCodeQuota.fiveHour": "5-hour",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex c5743c7feda..7feeb77f449 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -852,6 +852,7 @@"heteroAgent.claudeQuota.calendar.legendMore": "多","heteroAgent.claudeQuota.calendar.legendReset": "窗口重置","heteroAgent.claudeQuota.calendar.monthSpend": "每日开销",+ "heteroAgent.claudeQuota.calendar.monthlyHistory": "月限额窗口","heteroAgent.claudeQuota.calendar.noLedgerSpend": "本窗口暂无 token 用量记录","heteroAgent.claudeQuota.calendar.noLedgerSpendHint": "token 历史只记录启用用量追踪后、由 LobeHub 发起的运行;更早的用量以及直接从终端发起的运行无法回填。","heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "历史未记录",@@ -934,6 +935,7 @@"heteroAgent.cloudRepo.noRepos": "未配置仓库,请在助理设置中添加。","heteroAgent.cloudRepo.notSet": "未选择仓库","heteroAgent.cloudRepo.sectionTitle": "代码仓库",+ "heteroAgent.codexQuota.calendar.title": "Codex 用量日历","heteroAgent.codexQuota.doesNotExpire": "永不过期","heteroAgent.codexQuota.errorConnection": "无法访问 Codex 额度接口,请检查网络或 LobeHub 代理设置。","heteroAgent.codexQuota.errorGeneric": "无法获取 Codex 额度,请稍后重试。",@@ -997,6 +999,7 @@"heteroAgent.executionTarget.workspaceGroup": "工作区设备","heteroAgent.fullAccess.label": "完全访问权限","heteroAgent.fullAccess.tooltip": "本地编码 Agent 运行时对工作目录拥有完全的读写权限。当前暂不支持切换权限模式。",+ "heteroAgent.kimiCodeQuota.calendar.title": "Kimi Code 用量日历","heteroAgent.kimiCodeQuota.errorGeneric": "无法获取 Kimi Code 额度,请稍后重试。","heteroAgent.kimiCodeQuota.extraUsage": "额外用量","heteroAgent.kimiCodeQuota.fiveHour": "5 小时",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex d57b2f5519d..d7695053c86 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -412,6 +412,7 @@ export default {'heteroAgent.claudeQuota.calendar.legendMore': 'Heavy','heteroAgent.claudeQuota.calendar.legendReset': 'Window reset','heteroAgent.claudeQuota.calendar.monthSpend': 'Daily spend',+ 'heteroAgent.claudeQuota.calendar.monthlyHistory': 'Monthly windows','heteroAgent.claudeQuota.calendar.noLedgerSpend': 'No token usage recorded in this window','heteroAgent.claudeQuota.calendar.noLedgerSpendHint':'Token history is only recorded for runs started in LobeHub after usage tracking was enabled. Earlier usage and runs started directly from the terminal cannot be backfilled.',@@ -480,6 +481,7 @@ export default {'heteroAgent.claudeSdkRuntime.state.stale': 'SDK stale','heteroAgent.claudeSdkRuntime.state.starting': 'SDK starting','heteroAgent.claudeSdkRuntime.tooltip': '{{state}}. Active background tasks: {{count}}.',+ 'heteroAgent.codexQuota.calendar.title': 'Codex usage calendar','heteroAgent.codexQuota.doesNotExpire': 'Does not expire','heteroAgent.codexQuota.errorConnection':"Couldn't reach the Codex quota endpoint. Check your network or LobeHub proxy settings.",@@ -509,6 +511,7 @@ export default {'heteroAgent.codexQuota.totalEarned_one': '{{count}} earned in total','heteroAgent.codexQuota.totalEarned_other': '{{count}} earned in total','heteroAgent.codexQuota.tooltip': 'View Codex quota',+ 'heteroAgent.kimiCodeQuota.calendar.title': 'Kimi Code usage calendar','heteroAgent.kimiCodeQuota.errorGeneric': "Couldn't load Kimi Code quota. Try again later.",'heteroAgent.kimiCodeQuota.extraUsage': 'Extra Usage','heteroAgent.kimiCodeQuota.fiveHour': '5-hour',diff --git a/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx b/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsxindex f5b71afc9b3..e6d8dd04616 100644--- a/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx+++ b/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx@@ -32,13 +32,14 @@ import {currentWindow,dayKeyOf,type DaySpend,+ discoverSessionBuckets,formatCost,formatTokens,isCalendarMonthAvailable,projectBurnout,type QuotaSeriesKey,type QuotaWindowSpan,- selectQuotaAccount,+ selectProviderQuotaAccount,seriesId,SESSION_SERIES,shouldShowHeatDot,@@ -46,6 +47,7 @@ import {trackedCostOf,type UsageTurn,utilizationStatusOf,+ windowSeriesIdOf,type WindowStat,} from './quotaCalendarModel';@@ -355,7 +357,7 @@ const normalizeWindows = (rows: WindowLike[]): NormalizedWindow[] =>peakUtilization: row.peakUtilization,rateLimitedAt: toMs(row.rateLimitedAt),resetsAt: toMs(row.resetsAt)!,- seriesId: row.limitType.startsWith('weekly') ? `weekly:${row.scopeKey || ''}` : 'session:',+ seriesId: windowSeriesIdOf(row.limitType, row.scopeKey),windowStartAt: toMs(row.windowStartAt)!,}));@@ -696,7 +698,11 @@ const WindowHistory = memo<{<Flexbox gap={6}><Flexbox horizontal align={'baseline'} justify={'space-between'}><Text strong style={{ fontSize: 13 }}>- {t('heteroAgent.claudeQuota.calendar.weeklyHistory')}+ {t(+ series.type === 'monthly'+ ? 'heteroAgent.claudeQuota.calendar.monthlyHistory'+ : 'heteroAgent.claudeQuota.calendar.weeklyHistory',+ )}</Text><Text style={{ fontSize: 11 }} type={'secondary'}>{t('heteroAgent.claudeQuota.calendar.weeklyHistoryHint')}@@ -751,11 +757,24 @@ const WindowHistory = memo<{WindowHistory.displayName = 'WindowHistory';+/** Quota providers that persist accounts readable by the calendar. */+export type QuotaCalendarProvider = 'claude-code' | 'codex' | 'kimi-code';+interface QuotaCalendarProps {externalAccountId?: string;+ provider: QuotaCalendarProvider;}-const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {+/** Labels for the monthly series Kimi Code reports; anything else falls back to its raw limitType. */+const MONTHLY_LABEL_KEYS: Record<+ string,+ 'heteroAgent.kimiCodeQuota.monthly' | 'heteroAgent.kimiCodeQuota.monthlyCode'+> = {+ month_code: 'heteroAgent.kimiCodeQuota.monthlyCode',+ month_total: 'heteroAgent.kimiCodeQuota.monthly',+};++const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId, provider }) => {const { t } = useTranslation('chat');const [accountUnavailable, setAccountUnavailable] = useState(false);const [loading, setLoading] = useState(true);@@ -770,8 +789,7 @@ const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {let cancelled = false;(async () => {const accounts = await agentQuotaService.listAccounts().catch(() => []);- const claude = accounts.filter((a) => a.provider === 'claude-code');- const account = selectQuotaAccount(claude, externalAccountId);+ const account = selectProviderQuotaAccount(accounts, provider, externalAccountId);if (!account) {if (!cancelled) setAccountUnavailable(true);return;@@ -794,11 +812,16 @@ const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {return () => {cancelled = true;};- }, [externalAccountId]);+ }, [externalAccountId, provider]);- // The 5-hour session window comes first: it is the window an agent actually- // works inside, and the one that stops a run mid-task.+ // The session window comes first: it is the window an agent actually+ // works inside, and the one that stops a run mid-task. Codex reports one+ // primary bucket per rate-limit scope, so each discovered bucket gets its+ // own series instead of folding into the base session view.const seriesOptions = useMemo(() => {+ const sessionBuckets = discoverSessionBuckets(readings).filter(+ (bucket) => bucket.scopeKey !== '',+ );const scoped = [...new Set(readings@@ -806,14 +829,25 @@ const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {.map((r) => r.scopeKey),),].sort();+ const monthly = [+ ...new Set(readings.filter((r) => r.limitType.startsWith('month')).map((r) => r.limitType)),+ ].sort();return [{ label: t('heteroAgent.claudeQuota.calendar.sessionWindow'), value: 'session:' },+ ...sessionBuckets.map((bucket) => ({+ label: bucket.limitName ?? bucket.scopeKey,+ value: `session:${bucket.scopeKey}`,+ })),{ label: t('heteroAgent.quota.weekly'), value: 'weekly:' },...scoped.map((key) => ({label: t('heteroAgent.claudeQuota.scopedWeekly', { model: key }),value: `weekly:${key}`,})),+ ...monthly.map((limitType) => ({+ label: MONTHLY_LABEL_KEYS[limitType] ? t(MONTHLY_LABEL_KEYS[limitType]) : limitType,+ value: `monthly:${limitType}`,+ })),];}, [readings, t]);@@ -934,7 +968,10 @@ const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {value={seriesId(series)}onChange={(value) => {const [type, scopeKey = ''] = String(value).split(':');- setSeries({ scopeKey, type: type === 'session' ? 'session' : 'weekly' });+ setSeries({+ scopeKey,+ type: type === 'session' ? 'session' : type === 'monthly' ? 'monthly' : 'weekly',+ });}}/>@@ -1086,15 +1123,28 @@ const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {QuotaCalendar.displayName = 'QuotaCalendar';+const CALENDAR_TITLE_KEYS: Record<+ QuotaCalendarProvider,+ | 'heteroAgent.claudeQuota.calendar.title'+ | 'heteroAgent.codexQuota.calendar.title'+ | 'heteroAgent.kimiCodeQuota.calendar.title'+> = {+ 'claude-code': 'heteroAgent.claudeQuota.calendar.title',+ 'codex': 'heteroAgent.codexQuota.calendar.title',+ 'kimi-code': 'heteroAgent.kimiCodeQuota.calendar.title',+};+/** Calling this opens the modal — `createModal` mounts immediately. */export const openQuotaCalendarModal = (- params: { externalAccountId?: string } = {},-): ModalInstance =>- createModal({- content: <QuotaCalendar externalAccountId={params.externalAccountId} />,+ params: { externalAccountId?: string; provider?: QuotaCalendarProvider } = {},+): ModalInstance => {+ const provider = params.provider ?? 'claude-code';+ return createModal({+ content: <QuotaCalendar externalAccountId={params.externalAccountId} provider={provider} />,footer: null,- title: i18nT('heteroAgent.claudeQuota.calendar.title', { ns: 'chat' }),+ title: i18nT(CALENDAR_TITLE_KEYS[provider], { ns: 'chat' }),width: 1040,});+};export default QuotaCalendar;diff --git a/src/features/AgentQuotaCalendar/index.ts b/src/features/AgentQuotaCalendar/index.tsindex 1d6f72c37c2..cdadcf55e49 100644--- a/src/features/AgentQuotaCalendar/index.ts+++ b/src/features/AgentQuotaCalendar/index.ts@@ -1 +1 @@-export { openQuotaCalendarModal } from './QuotaCalendarModal';+export { openQuotaCalendarModal, type QuotaCalendarProvider } from './QuotaCalendarModal';diff --git a/src/features/AgentQuotaCalendar/quotaCalendarModel.test.ts b/src/features/AgentQuotaCalendar/quotaCalendarModel.test.tsindex f2cbc3771de..5de86720fd8 100644--- a/src/features/AgentQuotaCalendar/quotaCalendarModel.test.ts+++ b/src/features/AgentQuotaCalendar/quotaCalendarModel.test.ts@@ -1,19 +1,32 @@+import type { QuotaLimitReading } from '@lobechat/heterogeneous-agents/quota';import dayjs from 'dayjs';import { describe, expect, it } from 'vitest';import {+ buildBurnSeries,+ buildDailyBurn,buildDailyHeatLevels,buildDailySpend,buildSessionGrid,buildWindowStats,+ currentWindow,+ discoverSessionBuckets,formatTokens,isCalendarMonthAvailable,+ matchesSeries,+ MONTHLY_WINDOW_MS,+ type QuotaSeriesKey,type QuotaWindowSpan,+ selectProviderQuotaAccount,selectQuotaAccount,+ seriesId,+ SESSION_SERIES,shouldShowHeatDot,trackedCostOf,utilizationLevelOf,utilizationStatusOf,+ windowMsOf,+ windowSeriesIdOf,} from './quotaCalendarModel';const hour = 60 * 60 * 1000;@@ -150,6 +163,23 @@ describe('quota calendar window statistics', () => {expect(selectQuotaAccount([accounts[0]])).toEqual(accounts[0]);});+ it('selects the calendar account only inside the pool of the provider it opened for', () => {+ const accounts = [+ { externalAccountId: 'claude-ext', id: 'acc-claude', provider: 'claude-code' },+ { externalAccountId: 'codex-ext', id: 'acc-codex', provider: 'codex' },+ { externalAccountId: 'kimi-a', id: 'acc-kimi-a', provider: 'kimi-code' },+ { externalAccountId: 'kimi-b', id: 'acc-kimi-b', provider: 'kimi-code' },+ ];++ expect(selectProviderQuotaAccount(accounts, 'kimi-code', 'kimi-b')).toEqual(accounts[3]);+ expect(selectProviderQuotaAccount(accounts, 'codex')).toEqual(accounts[1]);+ // Two kimi accounts and no explicit choice: ambiguous, not "any of them".+ expect(selectProviderQuotaAccount(accounts, 'kimi-code')).toBeUndefined();+ // No account of the opened provider: unavailable, never another provider's.+ expect(selectProviderQuotaAccount(accounts, 'kimi-code', 'claude-ext')).toBeUndefined();+ expect(selectProviderQuotaAccount([accounts[0]], 'codex')).toBeUndefined();+ });+it('limits calendar navigation to the two fully loaded months', () => {const now = at('2026-08-09T12:00:00');@@ -183,6 +213,194 @@ describe('quota calendar window statistics', () => {});});+describe('monthly quota series', () => {+ const monthlySeries = (scopeKey: string): QuotaSeriesKey => ({ scopeKey, type: 'monthly' });+ const monthReading = (limitType: string, capturedAt: number, resetsAt: number | null) => ({+ capturedAt,+ limitType,+ resetsAt,+ scopeKey: '',+ utilization: 40,+ windowMinutes: 43_200,+ });++ it('keeps month buckets out of the session and weekly series', () => {+ const total = monthReading('month_total', 0, null);++ expect(matchesSeries(total, { scopeKey: '', type: 'session' })).toBe(false);+ expect(matchesSeries(total, { scopeKey: '', type: 'weekly' })).toBe(false);+ expect(matchesSeries(total, monthlySeries('month_total'))).toBe(true);+ // month_total and month_code are distinct quotas, not one monthly bucket.+ expect(matchesSeries(monthReading('month_code', 0, null), monthlySeries('month_total'))).toBe(+ false,+ );+ expect(matchesSeries(monthReading('month_code', 0, null), monthlySeries('month_code'))).toBe(+ true,+ );+ });++ it('buckets monthly windows by limitType instead of folding them into session', () => {+ expect(windowSeriesIdOf('month_total', '')).toBe('monthly:month_total');+ expect(windowSeriesIdOf('month_code', '')).toBe('monthly:month_code');+ expect(windowSeriesIdOf('weekly_all', '')).toBe('weekly:');+ expect(windowSeriesIdOf('weekly_scoped', 'Fable')).toBe('weekly:Fable');+ expect(windowSeriesIdOf('session', '')).toBe('session:');+ expect(windowSeriesIdOf('five_hour', '')).toBe('session:');+ });++ it('spans the 30-day window Kimi reports for its monthly buckets', () => {+ expect(windowMsOf(monthlySeries('month_total'))).toBe(MONTHLY_WINDOW_MS);+ expect(seriesId(monthlySeries('month_total'))).toBe('monthly:month_total');+ });++ it('finds the live monthly window from readings', () => {+ const now = at('2026-08-09T12:00:00');+ const resetsAt = at('2026-09-01T00:00:00');++ const live = currentWindow(+ [monthReading('month_total', now - 60_000, resetsAt)],+ monthlySeries('month_total'),+ now,+ );++ expect(live).toMatchObject({+ peakUtilization: 40,+ resetsAt,+ windowStartAt: resetsAt - MONTHLY_WINDOW_MS,+ });+ });+});++describe('scoped session buckets (codex)', () => {+ const OTHER_SERIES: QuotaSeriesKey = { scopeKey: 'codex_other', type: 'session' };++ const sessionReading = (+ scopeKey: string,+ capturedAt: number,+ resetsAt: number | null,+ utilization: number,+ windowMinutes = 300,+ limitName: string | null = null,+ ): QuotaLimitReading => ({+ capturedAt,+ limitName,+ limitType: 'session',+ resetsAt,+ scopeKey,+ utilization,+ windowMinutes,+ });++ it('keeps session buckets with distinct scopeKeys apart', () => {+ const baseReading = sessionReading('', 0, null, 40);+ const scopedReading = sessionReading('codex_other', 0, null, 40);++ expect(matchesSeries(baseReading, SESSION_SERIES)).toBe(true);+ expect(matchesSeries(scopedReading, SESSION_SERIES)).toBe(false);+ expect(matchesSeries(scopedReading, OTHER_SERIES)).toBe(true);+ expect(matchesSeries(baseReading, OTHER_SERIES)).toBe(false);+ // Claude's legacy alias still lands in the base session series.+ expect(matchesSeries({ ...baseReading, limitType: 'five_hour' }, SESSION_SERIES)).toBe(true);+ });++ it('buckets session windows by scopeKey instead of merging them', () => {+ expect(windowSeriesIdOf('session', '')).toBe('session:');+ expect(windowSeriesIdOf('session', 'codex_other')).toBe('session:codex_other');+ expect(windowSeriesIdOf('five_hour', 'codex_other')).toBe('session:codex_other');+ });++ it('sizes a bucket window from its own windowMinutes, not the 5-hour default', () => {+ const now = at('2026-08-09T12:00:00');+ const resetsAt = at('2026-08-09T12:40:00');++ const live = currentWindow(+ [sessionReading('codex_other', now - 60_000, resetsAt, 55, 60)],+ OTHER_SERIES,+ now,+ );++ expect(live).toMatchObject({ resetsAt, windowStartAt: resetsAt - hour });+ });++ it('finds the live window per bucket, not across buckets', () => {+ const now = at('2026-08-09T12:00:00');+ const baseResetsAt = at('2026-08-09T15:00:00');+ const otherResetsAt = at('2026-08-09T13:00:00');+ const readings = [+ sessionReading('', now - 60_000, baseResetsAt, 30),+ sessionReading('codex_other', now - 30_000, otherResetsAt, 70, 60),+ ];++ expect(currentWindow(readings, SESSION_SERIES, now)).toMatchObject({+ resetsAt: baseResetsAt,+ windowStartAt: baseResetsAt - 5 * hour,+ });+ expect(currentWindow(readings, OTHER_SERIES, now)).toMatchObject({+ resetsAt: otherResetsAt,+ windowStartAt: otherResetsAt - hour,+ });+ });++ it('burns each bucket from its own consecutive samples', () => {+ const t0 = at('2026-08-09T08:00:00');+ const baseResetsAt = at('2026-08-09T13:00:00');+ const readings = [+ sessionReading('', t0, baseResetsAt, 10),+ sessionReading('codex_other', t0 + 10 * 60_000, at('2026-08-09T09:00:00'), 60, 60),+ sessionReading('', t0 + 20 * 60_000, baseResetsAt, 30),+ ];++ // 10 -> 30 inside one window: 20 points, unpolluted by the other bucket's 60.+ expect(buildDailyBurn(readings, SESSION_SERIES)).toEqual(new Map([['2026-08-09', 20]]));+ // A single sample has no delta to attribute.+ expect(buildDailyBurn(readings, OTHER_SERIES).size).toBe(0);+ });++ it("drops deltas spanning more than the bucket's own window", () => {+ const t0 = at('2026-08-09T08:00:00');+ const readings = [+ sessionReading('codex_other', t0, t0 + hour, 80, 60),+ sessionReading('codex_other', t0 + 2 * hour, t0 + 3 * hour, 20, 60),+ ];++ // A 2-hour gap inside a 60-minute bucket can hide entire windows.+ expect(buildDailyBurn(readings, OTHER_SERIES).size).toBe(0);+ });++ it('draws the burn curve from one bucket only', () => {+ const resetsAt = at('2026-08-09T15:00:00');+ const window: QuotaWindowSpan = {+ peakUtilization: 40,+ rateLimitedAt: null,+ resetsAt,+ windowStartAt: resetsAt - 5 * hour,+ };+ const readings = [+ sessionReading('', resetsAt - 4 * hour, resetsAt, 20),+ sessionReading('codex_other', resetsAt - 3 * hour, resetsAt, 90, 60),+ sessionReading('', resetsAt - 2 * hour, resetsAt, 40),+ ];++ expect(buildBurnSeries(readings, SESSION_SERIES, window).map((p) => p.utilization)).toEqual([+ 0, 20, 40,+ ]);+ });++ it('enumerates one series option per session bucket, base first', () => {+ const buckets = discoverSessionBuckets([+ sessionReading('codex_other', 0, null, 10, 60, 'GPT-5 Codex'),+ sessionReading('', 0, null, 20),+ sessionReading('codex_spark', 0, null, 30, 60),+ ]);++ expect(buckets).toEqual([+ { limitName: null, scopeKey: '' },+ { limitName: 'GPT-5 Codex', scopeKey: 'codex_other' },+ { limitName: null, scopeKey: 'codex_spark' },+ ]);+ });+});+describe('formatTokens', () => {it('keeps sub-billion counts in K and M', () => {expect(formatTokens(820)).toBe('820');diff --git a/src/features/AgentQuotaCalendar/quotaCalendarModel.ts b/src/features/AgentQuotaCalendar/quotaCalendarModel.tsindex 5f645c83731..830cf333272 100644--- a/src/features/AgentQuotaCalendar/quotaCalendarModel.ts+++ b/src/features/AgentQuotaCalendar/quotaCalendarModel.ts@@ -12,12 +12,18 @@ import dayjs from 'dayjs';* fetching — kept apart so the shapes are unit-testable.** Two limit windows matter to a coding agent and both are first-class here: the- * 5-hour session window it actually works in, and the 7-day weekly window that- * caps the week.+ * session window it actually works in, and the 7-day weekly window that caps+ * the week. Kimi Code adds monthly buckets (`month_total` / `month_code`),+ * which get their own series so they are never folded into the session view.+ * Codex reports one primary bucket per rate-limit scope with its own duration,+ * so session series are keyed by bucket scopeKey and sized from each reading's+ * `windowMinutes` rather than a fixed span.*/export const WEEKLY_WINDOW_MS = CLAUDE_WEEKLY_WINDOW_SECONDS * 1000;export const SESSION_WINDOW_MS = CLAUDE_SESSION_WINDOW_SECONDS * 1000;+/** Kimi reports its month buckets as a 43200-minute (30-day) window. */+export const MONTHLY_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;/** Two provider-reported reset instants for the same window may jitter a bit. */const RESET_MATCH_TOLERANCE_MS = 5 * 60 * 1000;@@ -26,17 +32,47 @@ export const dayKeyOf = (time: number) => dayjs(time).format('YYYY-MM-DD');/** Which limit series a calendar view is reading. */export interface QuotaSeriesKey {- /** `''` for the account-wide weekly; a model name for a scoped weekly. */+ /**+ * `''` for the account-wide bucket; the provider's scope id otherwise. For a+ * weekly series that is a model name; for a session series it is the+ * rate-limit bucket id (Codex reports one primary bucket per scope). For a+ * monthly series it carries the limitType itself (`month_total` /+ * `month_code` are distinct quotas with an empty provider scopeKey).+ */scopeKey: string;- type: 'session' | 'weekly';+ type: 'monthly' | 'session' | 'weekly';}export const SESSION_SERIES: QuotaSeriesKey = { scopeKey: '', type: 'session' };export const seriesId = (series: QuotaSeriesKey) => `${series.type}:${series.scopeKey}`;+/**+ * Series bucket for a persisted or projected window row, mirroring+ * `matchesSeries` for readings: weekly rows keep their model scope, monthly+ * rows keep their limitType, session rows keep their bucket scope.+ */+export const windowSeriesIdOf = (limitType: string, scopeKey: string): string =>+ limitType.startsWith('weekly')+ ? `weekly:${scopeKey || ''}`+ : limitType.startsWith('month')+ ? `monthly:${limitType}`+ : `session:${scopeKey || ''}`;+export const windowMsOf = (series: QuotaSeriesKey) =>- series.type === 'session' ? SESSION_WINDOW_MS : WEEKLY_WINDOW_MS;+ series.type === 'session'+ ? SESSION_WINDOW_MS+ : series.type === 'weekly'+ ? WEEKLY_WINDOW_MS+ : MONTHLY_WINDOW_MS;++/**+ * A reading's own window span when the provider reported it, else the series+ * default. Codex primary buckets are not all 5 hours (a 60-minute primary is+ * in the wild), so the fixed default is only a fallback.+ */+const readingWindowMs = (reading: QuotaLimitReading, fallback: number) =>+ reading.windowMinutes && reading.windowMinutes > 0 ? reading.windowMinutes * 60_000 : fallback;export interface BurnPoint {time: number;@@ -87,6 +123,21 @@ export const selectQuotaAccount = <T extends QuotaAccountCandidate>(return accounts.length === 1 ? accounts[0] : undefined;};+/**+ * The account a calendar view reads: only the pool of the provider it was+ * opened for, narrowed by the requested external account. Never falls back to+ * another provider's account.+ */+export const selectProviderQuotaAccount = <T extends QuotaAccountCandidate & { provider: string }>(+ accounts: T[],+ provider: string,+ externalAccountId?: string,+): T | undefined =>+ selectQuotaAccount(+ accounts.filter((account) => account.provider === provider),+ externalAccountId,+ );+/** The 90-day query guarantees complete data for the current and previous month. */export const isCalendarMonthAvailable = (month: dayjs.Dayjs, now: number) => {const current = dayjs(now).startOf('month');@@ -97,14 +148,44 @@ const isSessionReading = (reading: QuotaLimitReading) =>reading.limitType === 'session' || reading.limitType === 'five_hour';/** Does this reading belong to the series a view is showing? */-export const matchesSeries = (reading: QuotaLimitReading, series: QuotaSeriesKey) =>- series.type === 'session'- ? isSessionReading(reading)- : reading.limitType.startsWith('weekly') && (reading.scopeKey || '') === series.scopeKey;+export const matchesSeries = (reading: QuotaLimitReading, series: QuotaSeriesKey) => {+ switch (series.type) {+ case 'session': {+ return isSessionReading(reading) && (reading.scopeKey || '') === series.scopeKey;+ }+ case 'weekly': {+ return reading.limitType.startsWith('weekly') && (reading.scopeKey || '') === series.scopeKey;+ }+ case 'monthly': {+ return reading.limitType.startsWith('month') && reading.limitType === series.scopeKey;+ }+ }+};const sortByCapturedAt = (readings: QuotaLimitReading[]) =>[...readings].sort((a, b) => a.capturedAt - b.capturedAt);+/**+ * Distinct session buckets seen in the readings, base bucket (`''`) first.+ * Codex persists one primary bucket per rate-limit scope, so each scopeKey+ * becomes its own series instead of interleaving into the base one.+ */+export const discoverSessionBuckets = (+ readings: QuotaLimitReading[],+): { limitName: string | null; scopeKey: string }[] => {+ const buckets = new Map<string, string | null>();+ for (const reading of readings) {+ if (!isSessionReading(reading)) continue;+ const scopeKey = reading.scopeKey || '';+ if (!buckets.get(scopeKey) && reading.limitName) buckets.set(scopeKey, reading.limitName);+ else if (!buckets.has(scopeKey)) buckets.set(scopeKey, null);+ }++ return [...buckets.entries()]+ .sort(([a], [b]) => (a === '' ? -1 : b === '' ? 1 : a.localeCompare(b)))+ .map(([scopeKey, limitName]) => ({ limitName, scopeKey }));+};+const sameWindow = (a: QuotaLimitReading, b: QuotaLimitReading) =>a.resetsAt != null && b.resetsAt != null? Math.abs(a.resetsAt - b.resetsAt) < RESET_MATCH_TOLERANCE_MS@@ -146,7 +227,7 @@ export const buildDailyBurn = (series: QuotaSeriesKey,): Map<string, number> => {const list = sortByCapturedAt(readings.filter((r) => matchesSeries(r, series)));- const windowMs = windowMsOf(series);+ const fallbackWindowMs = windowMsOf(series);const burnByDay = new Map<string, number>();for (const [index, current] of list.entries()) {@@ -154,7 +235,8 @@ export const buildDailyBurn = (const previous = list[index - 1];// A gap longer than one full window can hide entire windows — attributing// its delta to one day would paint a false spike.- if (current.capturedAt - previous.capturedAt > windowMs) continue;+ if (current.capturedAt - previous.capturedAt > readingWindowMs(current, fallbackWindowMs))+ continue;const burn = sameWindow(previous, current)? Math.max(0, current.utilization - previous.utilization)@@ -227,7 +309,7 @@ export const currentWindow = (peakUtilization: newest.utilization,rateLimitedAt: null,resetsAt: newest.resetsAt!,- windowStartAt: newest.resetsAt! - windowMsOf(series),+ windowStartAt: newest.resetsAt! - readingWindowMs(newest, windowMsOf(series)),};};diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsxindex 3078e8feb6a..b7d2fc5d5f1 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx@@ -243,10 +243,12 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =getRefreshErrorText={getRefreshErrorText}getUnavailableText={getUnavailableText}getWindows={getWindows}- renderHeader={(quota) => <QuotaAccountSwitcher placement="top" snapshot={quota} />}sourceKey={sourceKey}title={t('heteroAgent.claudeQuota.title')}tooltip={t('heteroAgent.claudeQuota.tooltip')}+ renderHeader={(quota) => (+ <QuotaAccountSwitcher placement="top" provider="claude-code" snapshot={quota} />+ )}/>);});diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsxindex 7e5f04857b4..6b79fa00ea4 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/CodexQuotaMenu.tsx@@ -17,6 +17,7 @@ import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { createCodexQuotaReader } from '@/services/codexQuota';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';+import QuotaAccountSwitcher from './QuotaAccountSwitcher';import type { QuotaMenuHelpers, QuotaWindowItem } from './QuotaMenu';import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';@@ -464,6 +465,9 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, deviceId, env }) =>sourceKey={sourceKey}title={t('heteroAgent.codexQuota.title')}tooltip={t('heteroAgent.codexQuota.tooltip')}+ renderHeader={(quota) => (+ <QuotaAccountSwitcher placement="top" provider="codex" snapshot={quota} />+ )}/>);});diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsxindex 4480d891492..381a56b76ba 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/KimiCodeQuotaMenu.tsx@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { createKimiCodeQuotaReader } from '@/services/kimiCodeQuota';+import QuotaAccountSwitcher from './QuotaAccountSwitcher';import type { QuotaWindowItem } from './QuotaMenu';import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';@@ -149,6 +150,9 @@ const KimiCodeQuotaMenu = memo<KimiCodeQuotaMenuProps>(({ deviceId, env }) => {sourceKey={sourceKey}title={t('heteroAgent.kimiCodeQuota.title')}tooltip={t('heteroAgent.kimiCodeQuota.tooltip')}+ renderHeader={(quota) => (+ <QuotaAccountSwitcher placement="top" provider="kimi-code" snapshot={quota} />+ )}/>);});diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsxindex bad1117677f..15969ee186d 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx@@ -1,6 +1,6 @@'use client';-import type { ClaudeCodeQuotaSnapshot } from '@lobechat/electron-client-ipc';+import type { QuotaAccountIdentity } from '@lobechat/heterogeneous-agents/quota';import { Flexbox } from '@lobehub/ui';import { ActionIcon, Button, Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';@@ -8,7 +8,7 @@ import { CalendarDaysIcon } from 'lucide-react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';-import { openQuotaCalendarModal } from '@/features/AgentQuotaCalendar';+import { openQuotaCalendarModal, type QuotaCalendarProvider } from '@/features/AgentQuotaCalendar';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { openQuotaAccountManagerModal } from './QuotaAccountManagerModal';@@ -32,8 +32,9 @@ const styles = createStaticStyles(({ css }) => ({*/const QuotaAccountSwitcher = memo<{placement?: 'top' | 'bottom';- snapshot: ClaudeCodeQuotaSnapshot;-}>(({ snapshot, placement = 'top' }) => {+ provider: QuotaCalendarProvider;+ snapshot: { identity?: QuotaAccountIdentity | null };+}>(({ snapshot, provider, placement = 'top' }) => {const { t } = useTranslation('chat');const agentId = useAgentId();const identity = snapshot.identity;@@ -66,12 +67,23 @@ const QuotaAccountSwitcher = memo<{size={'small'}style={{ flex: 'none' }}title={t('heteroAgent.claudeQuota.calendar.entry')}- onClick={() => openQuotaCalendarModal({ externalAccountId: identity?.externalAccountId })}+ onClick={() =>+ openQuotaCalendarModal({ externalAccountId: identity?.externalAccountId, provider })+ }/></Flexbox>- <Button size={'small'} style={{ flex: 'none' }} onClick={openManager}>- {t('heteroAgent.claudeQuota.manage.entry')}- </Button>+ {/*+ * The account manager edits provider-blind agent bindings and runtime+ * routing only honors them for claude-code, so offering it from another+ * provider's panel could pin a foreign account onto Claude runs. Until+ * management and routing are provider-scoped end to end, the other+ * providers get a calendar-only header.+ */}+ {provider === 'claude-code' && (+ <Button size={'small'} style={{ flex: 'none' }} onClick={openManager}>+ {t('heteroAgent.claudeQuota.manage.entry')}+ </Button>+ )}</Flexbox>);});diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsxindex 6e2792441f5..434536df165 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx@@ -9,6 +9,8 @@ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { openQuotaCalendarModal } from '@/features/AgentQuotaCalendar';+import HeteroControlBar from '..';import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';import CodexQuotaMenu from './CodexQuotaMenu';@@ -314,6 +316,7 @@ beforeEach(() => {mockQuotaService.ingestKimiCodeSnapshot.mockClear();mockQuotaService.listAccounts.mockResolvedValue([]);mockQuotaService.listBindings.mockResolvedValue([]);+ vi.mocked(openQuotaCalendarModal).mockClear();});describe('HeteroControlBar', () => {@@ -517,9 +520,43 @@ describe('KimiCodeQuotaMenu', () => {expect(await screen.findByText('heteroAgent.kimiCodeQuota.unavailableNotFound')).toBeTruthy();});++ it('opens the usage calendar for the kimi-code account from the header switcher', async () => {+ mockService.getKimiCodeQuota.mockResolvedValue(+ kimiCodeSnapshot({+ identity: { displayName: 'Kimi User', externalAccountId: 'kimi-ext-1' },+ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 },+ }),+ );++ render(<KimiCodeQuotaMenu />);++ fireEvent.click(await screen.findByTestId('calendar'));++ expect(openQuotaCalendarModal).toHaveBeenCalledWith({+ externalAccountId: 'kimi-ext-1',+ provider: 'kimi-code',+ });+ });});describe('ClaudeCodeQuotaMenu', () => {+ it('opens the usage calendar for the claude-code account from the header switcher', async () => {+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);+ mockQuotaService.getLatestReadings.mockResolvedValue([+ persistedSessionReading(Date.now() - 60_000),+ ]);++ render(<ClaudeCodeQuotaMenu />);++ fireEvent.click(await screen.findByTestId('calendar'));++ expect(openQuotaCalendarModal).toHaveBeenCalledWith({+ externalAccountId: 'ext-1',+ provider: 'claude-code',+ });+ });+it('renders session, weekly, and model-scoped windows from the snapshot', async () => {mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot({@@ -1123,6 +1160,24 @@ describe('ClaudeCodeQuotaMenu', () => {});describe('CodexQuotaMenu', () => {+ it('opens the usage calendar for the codex account from the header switcher', async () => {+ mockService.getCodexQuota.mockResolvedValue(+ codexSnapshot({+ identity: { displayName: 'Codex User', externalAccountId: 'codex-ext-1' },+ session: { resetsAt: null, usedPercent: 19, windowMinutes: 300 },+ }),+ );++ render(<CodexQuotaMenu command="codex" />);++ fireEvent.click(await screen.findByTestId('calendar'));++ expect(openQuotaCalendarModal).toHaveBeenCalledWith({+ externalAccountId: 'codex-ext-1',+ provider: 'codex',+ });+ });+it.each([['failed to fetch codex rate limits: error sending request for url (https://chatgpt.com/backend-api/wham/usage)',diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.tsindex 0dc4013755a..513af70d73f 100644--- a/src/services/agentQuota.ts+++ b/src/services/agentQuota.ts@@ -100,8 +100,10 @@ class AgentQuotaService {lambdaClient.agentQuota.updateAccount.mutate({ id, value });/** Who the load balancer would pick right now (Auto mode preview + reason). */- selectAccountForAgent = async (agentId: string, modelScope?: string) =>- lambdaClient.agentQuota.selectAccountForAgent.query({ agentId, modelScope });+ selectAccountForAgent = async (+ agentId: string,+ options?: { modelScope?: string; provider?: string },+ ) => lambdaClient.agentQuota.selectAccountForAgent.query({ agentId, ...options });/** One assistant turn's consumption → usage ledger (idempotent by message id). */recordUsage = async (params: {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 8e8d6d6415f..279f3b43abb 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -76,11 +76,13 @@ const mockStopSession = vi.fn();const mockCancelSession = vi.fn();const mockGetSessionInfo = vi.fn();const mockGetClaudeCodeIdentity = vi.fn(async (..._args: any[]) => null);+const mockGetCodexQuota = vi.fn(async (..._args: any[]): Promise<unknown> => null);vi.mock('@/services/electron/heterogeneousAgent', () => ({heterogeneousAgentService: {cancelSession: (...args: unknown[]) => mockCancelSession(...args),getClaudeCodeIdentity: (...args: any[]) => mockGetClaudeCodeIdentity(...args),+ getCodexQuota: (...args: any[]) => mockGetCodexQuota(...args),getSessionInfo: (...args: any[]) => mockGetSessionInfo(...args),sendPrompt: (...args: any[]) => mockSendPrompt(...args),startSession: (...args: any[]) => mockStartSession(...args),@@ -519,6 +521,7 @@ const codexTurnCompleted = (usage?: {cached_input_tokens?: number;input_tokens?: number;output_tokens?: number;+ reasoning_output_tokens?: number;}) => ({...(usage ? { usage } : {}),type: 'turn.completed',@@ -4821,6 +4824,140 @@ describe('heterogeneousAgentExecutor DB persistence', () => {});});+ // Codex turns burn the same subscription-shaped quota as Claude's, so they+ // ledger too — with reasoning output split into its own tier (it bills at+ // the output rate but is priced separately) and no cache-write tier.+ it('ledgers codex turn usage via agentQuotaService.recordUsage with the reasoning split', async () => {+ await runWithEvents(+ [+ codexSessionConfigured('gpt-5.3-codex'),+ codexThreadStarted(),+ codexTurnStarted(),+ codexAgentMessage('item_0', 'Done.'),+ codexTurnCompleted({+ cached_input_tokens: 400,+ input_tokens: 1000,+ output_tokens: 300,+ reasoning_output_tokens: 100,+ }),+ ],+ {+ params: {+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ },+ },+ );++ const codexLedgerCall = mockRecordQuotaUsage.mock.calls.find(+ ([p]: any) => p.provider === 'codex',+ );+ expect(codexLedgerCall).toBeDefined();+ expect(codexLedgerCall![0]).toMatchObject({+ model: 'gpt-5.3-codex',+ provider: 'codex',+ usage: { cacheRead: 400, input: 600, output: 200, reasoning: 100 },+ });+ expect(codexLedgerCall![0].usage.cacheWrite5m).toBeUndefined();+ });++ // Codex has no per-account spawn mapping, so attribution reads the live+ // sampler identity of the login the run actually uses.+ it('attributes codex ledger rows to the live codex login identity', async () => {+ mockGetCodexQuota.mockResolvedValueOnce({+ identity: { externalAccountId: 'chatgpt-acc-1' },+ });++ await runWithEvents(+ [+ codexSessionConfigured('gpt-5.3-codex'),+ codexThreadStarted(),+ codexTurnStarted(),+ codexAgentMessage('item_0', 'Done.'),+ codexTurnCompleted({ input_tokens: 100, output_tokens: 50 }),+ ],+ {+ params: {+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ },+ },+ );++ const codexLedgerCall = mockRecordQuotaUsage.mock.calls.find(+ ([p]: any) => p.provider === 'codex',+ );+ expect(codexLedgerCall).toBeDefined();+ expect(codexLedgerCall![0].externalAccountId).toBe('chatgpt-acc-1');+ });++ // A fast first turn must not beat a slow sampler: the ledger row is+ // permanent, so it waits for the identity read instead of landing+ // unattributed (Codex review on PR #19770).+ it('holds the codex ledger write until the sampler identity settles', async () => {+ let resolveIdentity!: (value: unknown) => void;+ mockGetCodexQuota.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveIdentity = resolve;+ }),+ );++ await runWithEvents(+ [+ codexSessionConfigured('gpt-5.3-codex'),+ codexThreadStarted(),+ codexTurnStarted(),+ codexAgentMessage('item_0', 'Done.'),+ codexTurnCompleted({ input_tokens: 100, output_tokens: 50 }),+ ],+ {+ params: {+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ },+ },+ );++ // The turn already completed, but the identity read is still pending.+ expect(mockRecordQuotaUsage).not.toHaveBeenCalled();++ resolveIdentity({ identity: { externalAccountId: 'chatgpt-acc-slow' } });+ await vi.waitFor(() => expect(mockRecordQuotaUsage).toHaveBeenCalled());+ const codexLedgerCall = mockRecordQuotaUsage.mock.calls.find(+ ([p]: any) => p.provider === 'codex',+ );+ expect(codexLedgerCall![0].externalAccountId).toBe('chatgpt-acc-slow');+ });++ // kimi-code must stay out of the ledger: its adapter emits no usage, and+ // even if a usage-bearing turn_metadata event arrived, the gate only+ // ledgers subscription-billed providers (claude-code, codex).+ it('does NOT ledger kimi-code turn usage', async () => {+ await runWithEvents(+ [+ () =>+ ipc.emitStreamEvent('ipc-sess-1', {+ data: {+ model: 'kimi-k2.6',+ phase: 'turn_metadata',+ provider: 'kimi-code',+ usage: {+ inputCacheMissTokens: 10,+ totalInputTokens: 10,+ totalOutputTokens: 5,+ totalTokens: 15,+ },+ },+ type: 'step_complete',+ }),+ ],+ {+ params: {+ heterogeneousProvider: { command: 'kimi', type: 'kimi-code' as const },+ },+ },+ );++ expect(mockRecordQuotaUsage).not.toHaveBeenCalled();+ });+it('does NOT create a Thread when topicId is missing (non-topic-scoped run)', async () => {await runWithEvents([diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex b998151b8ab..1466eb1c88e 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -497,6 +497,10 @@ export const executeHeterogeneousAgent = async (// from the FINAL env (so an agent-env override is attributed correctly, not// the routed choice). Read by the per-turn usage→ledger hook below.let runExternalAccountId: string | undefined;+ // Settles when that identity read finishes, one way or another. Ledger rows+ // are permanent, so a turn must never be submitted before this settles — an+ // early unattributed row is one the later assignment cannot repair.+ let runIdentitySettled: Promise<unknown> = Promise.resolve();// Usage ledger: one turn's spend, attributed to the account the run is on —// the "our own cost" half calibration crosses with the provider's utilization@@ -510,28 +514,47 @@ export const executeHeterogeneousAgent = async (usage: unknown;}) => {if (- adapterType !== 'claude-code' ||- (heterogeneousProvider.authMode ?? 'subscription') !== 'subscription'+ (adapterType !== 'claude-code' && adapterType !== 'codex') ||+ (heterogeneousProvider.authMode ?? 'subscription') !== 'subscription' ||+ // turn_metadata can carry only model/provider — nothing to ledger.+ !intent.usage)return;- const u = intent.usage as ModelUsage;- agentQuotaService- .recordUsage({- agentId: context.agentId,- externalAccountId: runExternalAccountId,- messageId: intent.messageId,- model: intent.model,- operationId,- provider: 'claude-code',- topicId: context.topicId ?? undefined,- usage: {- cacheRead: u.inputCachedTokens,- cacheWrite5m: u.inputWriteCacheTokens,- input: u.inputCacheMissTokens,- output: u.totalOutputTokens,- },- })- .catch(() => {});+ const submit = () => {+ const u = intent.usage as ModelUsage;+ agentQuotaService+ .recordUsage({+ agentId: context.agentId,+ externalAccountId: runExternalAccountId,+ messageId: intent.messageId,+ model: intent.model,+ operationId,+ provider: adapterType,+ topicId: context.topicId ?? undefined,+ usage:+ adapterType === 'codex'+ ? {+ // Codex has no cache-write tier, and its reasoning output bills+ // at the output rate as its own ledger tier — split it out of+ // the plain output count.+ cacheRead: u.inputCachedTokens,+ input: u.inputCacheMissTokens,+ output:+ u.totalOutputTokens === undefined+ ? undefined+ : u.totalOutputTokens - (u.outputReasoningTokens ?? 0),+ reasoning: u.outputReasoningTokens,+ }+ : {+ cacheRead: u.inputCachedTokens,+ cacheWrite5m: u.inputWriteCacheTokens,+ input: u.inputCacheMissTokens,+ output: u.totalOutputTokens,+ },+ })+ .catch(() => {});+ };+ runIdentitySettled.then(submit, submit);};// Shared run lifecycle — hetero owns its terminal lifecycle here@@ -1970,7 +1993,7 @@ export const executeHeterogeneousAgent = async (// agent-env CLAUDE_CONFIG_DIR beats routing, and unbound agents use the// default login). Falls back to the routed choice when the file read fails.if (adapterType === 'claude-code' && !providerBindingActive) {- heterogeneousAgentService+ runIdentitySettled = heterogeneousAgentService.getClaudeCodeIdentity({ env: sessionEnv }).then((identity) => {runExternalAccountId = identity?.externalAccountId ?? quotaAccountPlan.externalAccountId;@@ -1979,6 +2002,21 @@ export const executeHeterogeneousAgent = async (runExternalAccountId = quotaAccountPlan.externalAccountId;});}+ if (adapterType === 'codex' && !providerBindingActive) {+ // Same attribution contract as Claude, but Codex has no per-account spawn+ // mapping (resolveQuotaAccountSpawnPlan returns NO_ROUTING), so the live+ // sampler identity is the only source. A sampler failure leaves the run+ // unattributed rather than misattributed.+ runIdentitySettled = heterogeneousAgentService+ .getCodexQuota({+ command: resolveHeterogeneousAgentCommand(adapterType, heterogeneousProvider.command),+ env: sessionEnv,+ })+ .then((snapshot) => {+ runExternalAccountId = snapshot?.identity?.externalAccountId ?? undefined;+ })+ .catch(() => {});+ }ipcRunSessionId = result.sessionId;if (!ipcRunSessionId) throw new Error('Agent session returned no sessionId');diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.tsindex 5bc37fd0829..0550c7da485 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resolveQuotaAccountEnv.ts@@ -32,7 +32,9 @@ export const resolveQuotaAccountSpawnPlan = async (// Codex accounts exist in the DB but have no runnable credential mapping yet.if (adapterType !== 'claude-code' || !agentId) return NO_ROUTING;- const selection = await agentQuotaService.selectAccountForAgent(agentId).catch(() => null);+ const selection = await agentQuotaService+ .selectAccountForAgent(agentId, { provider: adapterType })+ .catch(() => null);if (!selection) return NO_ROUTING;const attribution = {