Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 接入 Gateway 归一化能力字段并在状态栏展示账号额度 (#1075)

GaoWei Liuf818cea0b79d
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index 375b42060b..0dcea5fbf9 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -289,24 +289,31 @@ describe('maker:event hot path ordering', () => {
expect(codexDoneSource).not.toContain('hasCodexOAuthLogin()');
expect(codexDoneSource).toContain('promptTokens + completionTokens + cachedTokens');
expect(codexDoneSource).not.toContain('promptTokens + completionTokens + reasoningTokens + cachedTokens');
- expect(codexDoneSource).toContain('const isCodexBudgetRoute = pricingModel.startsWith(\'codex/\');');
- expect(codexDoneSource).toContain('const isCodexXaiProviderRoute = pricingModel.startsWith(XAI_MODEL_PREFIX);');
+ expect(codexDoneSource).toContain('const isCustomProviderRoute =');
+ expect(codexDoneSource).toContain('isUserProviderSession(session.id)');
+ expect(codexDoneSource).toContain("&& pricingModel.startsWith('codex/');");
+ expect(codexDoneSource).toContain('&& pricingModel.startsWith(XAI_MODEL_PREFIX);');
expect(codexDoneSource).toContain('const hasGatewayKey = Boolean(readClaudeApiKey());');
expect(codexDoneSource).toContain('const hasEffectiveGatewayRoute =');
+ expect(codexDoneSource).toContain('!isCustomProviderRoute');
expect(codexDoneSource).toContain('(sessionProvider === \'xd\' && hasGatewayKey)');
expect(codexDoneSource).toContain('const isSubscriptionValue = isRemoteCodexSession ||');
expect(codexDoneSource).toContain('isCodexXaiProviderRoute ||');
- expect(codexDoneSource).toContain("(codexAuthInjection === 'oauth-bearer' && !hasEffectiveGatewayRoute)");
+ // 用正则而非整串匹配:这段条件已按多行排版,单行字面量会因换行/缩进调整而假失败。
+ // 要守的语义是——订阅计价只在「OpenAI 供应商 + oauth-bearer 注入 + 无生效网关路由」时成立。
+ expect(codexDoneSource).toMatch(
+ /isCodexOpenAiProviderRoute\s*&&\s*codexAuthInjection === 'oauth-bearer'\s*&&\s*!hasEffectiveGatewayRoute/,
+ );
expect(codexDoneSource).toContain('const modelUsageKey = isSubscriptionValue');
expect(codexDoneSource).toContain('? codexSubscriptionUsageModelKey(pricingModel)');
expect(codexDoneSource).toContain(': codexApiUsageModelKey(pricingModel)');
expect(codexDoneSource).toContain('const price = isCodexXaiProviderRoute');
expect(codexDoneSource).toContain('? getSubscriptionDirectValuePrice(pricingModel)');
expect(codexDoneSource).toContain('? getCodexSubscriptionValuePrice(pricingModel, pricing)');
- expect(codexDoneSource).toContain(": getModelPriceQuote(pricing, 'xd', pricingModel)");
+ expect(codexDoneSource).toContain("? getModelPriceQuote(pricing, 'xd', pricingModel)");
expect(codexDoneSource).toContain('const pricing = isSubscriptionValue && !isCodexXaiProviderRoute');
expect(codexDoneSource).toContain('? await getModelPricing()');
- expect(codexDoneSource).toContain(": await getModelPricingForModel('xd', pricingModel)");
+ expect(codexDoneSource).toContain("? await getModelPricingForModel('xd', pricingModel)");
expect(codexDoneSource).toContain('price ?? undefined');
expect(codexDoneSource).toContain('if (!isSubscriptionValue && money)');
expect(codexDoneSource).toContain('void recordTurnSpend(money);');
@@ -327,6 +334,7 @@ describe('maker:event hot path ordering', () => {
expect(codexDoneSource).toContain('clientId: turnAssistantPersistId');
expect(codexDoneSource).toContain('money,');
expect(codexDoneSource).toContain('if (!isRemoteCodexSession &&');
+ expect(codexDoneSource).toContain('!isCustomProviderRoute &&');
expect(codexDoneSource).toContain("!model.startsWith(XAI_MODEL_PREFIX) &&");
expect(codexDoneSource).toContain("(codexAuthInjection === 'env-key' || model.startsWith('codex/') || (sessionProvider === 'xd' && hasGatewayKey))");
expect(codexDoneSource).not.toContain("sessionProvider !== 'xai'");
diff --git a/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts b/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts
index f416b43ddf..894c72f96a 100644
--- a/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/dailyLedgerCurrencyConflict.test.ts
@@ -17,6 +17,10 @@ import { clearCurrentDbClient, setCurrentDbClient } from '../client/current';
import { incrementDailySpend, localDayKey } from '../dailySpend';
import { incrementDailyModelUsage } from '../dailyModelUsage';
import { DEFAULT_USAGE_CURRENCY } from '../../../shared/regionalMoney';
+import {
+ __resetActiveLedgerCurrencyForTesting,
+ setActiveLedgerCurrency,
+} from '../../usage/ledgerCurrency';
const DDL = `
CREATE TABLE daily_spend (
@@ -199,4 +203,43 @@ describe('daily ledger currency invariant', () => {
harness.close();
}
});
+
+ it('accepts the account settlement currency even when it differs from the build region', async () => {
+ // 结算币种由服务端按账号所属租户下发,不是构建区域:CN 构建 + USD 结算账号是正常
+ // 组合。基准若取构建区域,这些账号的每一笔都会被拒收 —— 等于完全不计费。
+ // setActiveLedgerCurrency 由模型目录同步时写入(见 usage/modelPricing)。
+ const harness = createHarness();
+ const settlement = conflictingMoney(1).currency;
+ setActiveLedgerCurrency(settlement);
+ try {
+ await incrementDailySpend(conflictingMoney(1.5));
+ await incrementDailyModelUsage({
+ agentKind: 'claude-code',
+ model: 'claude-opus-4-8',
+ money: conflictingMoney(2),
+ inputTokensDelta: 100,
+ outputTokensDelta: 10,
+ cacheReadTokensDelta: 0,
+ cacheCreateTokensDelta: 0,
+ });
+
+ expect(
+ harness.sqlite.prepare('SELECT cost_amount, cost_currency FROM daily_spend').get(),
+ ).toEqual({ cost_amount: 1.5, cost_currency: settlement });
+ expect(
+ harness.sqlite
+ .prepare('SELECT cost_amount, cost_currency FROM daily_model_usage WHERE day = ?')
+ .get(localDayKey()),
+ ).toMatchObject({ cost_amount: 2, cost_currency: settlement });
+
+ // 反向:此时构建默认币种才是异币种,仍应被拒收以保护已有账本。
+ await incrementDailySpend(currentMoney(10));
+ expect(
+ harness.sqlite.prepare('SELECT cost_amount, cost_currency FROM daily_spend').get(),
+ ).toEqual({ cost_amount: 1.5, cost_currency: settlement });
+ } finally {
+ __resetActiveLedgerCurrencyForTesting();
+ harness.close();
+ }
+ });
});
diff --git a/apps/desktop/src/main/localDb/dailyModelUsage.ts b/apps/desktop/src/main/localDb/dailyModelUsage.ts
index c26d39f54a..c02ad6fdce 100644
--- a/apps/desktop/src/main/localDb/dailyModelUsage.ts
+++ b/apps/desktop/src/main/localDb/dailyModelUsage.ts
@@ -2,7 +2,6 @@ import { sql } from 'drizzle-orm';
import {
addRegionalMoney,
- DEFAULT_USAGE_CURRENCY,
legacyUsdMoney,
normalizeRegionalMoney,
zeroUsageMoney,
@@ -12,6 +11,7 @@ import { dailyModelUsage } from './schema.js';
import { localDayKey } from './dailySpend.js';
import { getDbClient } from './client/current.js';
import { createLogger } from '../logger.js';
+import { currentLedgerCurrency } from '../usage/ledgerCurrency.js';
const log = createLogger('localDb/dailyModelUsage');
@@ -44,14 +44,16 @@ export async function incrementDailyModelUsage(
delta: DailyModelUsageDelta,
ts: number = Date.now(),
): Promise<void> {
+ // 单币种行:只接受本账号的结算币种,基准取 currentLedgerCurrency() 而不是构建区域 ——
+ // 结算币种由服务端按账号所属租户下发,不保证等于发行区域;按区域判会让以 USD 结算的
+ // 账号每一行都只剩 token、金额永远是 0。
+ // 异币种金额被忽略但 token 仍累计。
const normalizedMoney = delta.money ? normalizeRegionalMoney(delta.money) : undefined;
- const money =
- normalizedMoney?.currency === DEFAULT_USAGE_CURRENCY
- ? normalizedMoney
- : undefined;
+ const ledgerCurrency = currentLedgerCurrency();
+ const money = normalizedMoney?.currency === ledgerCurrency ? normalizedMoney : undefined;
if (normalizedMoney && !money) {
log.warn(
- `daily model usage rejected currency mismatch: ${normalizedMoney.currency} != ${DEFAULT_USAGE_CURRENCY}`,
+ `daily model usage rejected currency mismatch: ${normalizedMoney.currency} != ${ledgerCurrency}`,
);
}
const inputTokens = sanitizeTokens(delta.inputTokensDelta);
diff --git a/apps/desktop/src/main/localDb/dailySpend.ts b/apps/desktop/src/main/localDb/dailySpend.ts
index 7d80d5eff7..47b1b2dbef 100644
--- a/apps/desktop/src/main/localDb/dailySpend.ts
+++ b/apps/desktop/src/main/localDb/dailySpend.ts
@@ -2,7 +2,6 @@ import { sql } from 'drizzle-orm';
import {
addRegionalMoney,
- DEFAULT_USAGE_CURRENCY,
legacyUsdMoney,
normalizeRegionalMoney,
zeroUsageMoney,
@@ -11,6 +10,7 @@ import {
import { dailySpend } from './schema.js';
import { getDbClient } from './client/current.js';
import { createLogger } from '../logger.js';
+import { currentLedgerCurrency } from '../usage/ledgerCurrency.js';
const log = createLogger('localDb/dailySpend');
@@ -71,16 +71,20 @@ export async function incrementDailySpend(
if (!normalized || normalized.amount < 1e-10) {
return { day, money: await getSpendForDay(day) };
}
- if (normalized.currency !== DEFAULT_USAGE_CURRENCY) {
+ // 单币种日账本:入口只接受本账号的结算币种。基准取 currentLedgerCurrency() 而不是
+ // 构建区域 —— 结算币种由服务端按账号所属租户下发,不保证等于发行区域;按区域判会把
+ // 以 USD 结算的账号在 CN 构建上的每一笔都拒收成不计费。
+ // 异币种(脏数据 / 上游 bug)仍然拒收,避免污染已有账本。
+ const ledgerCurrency = currentLedgerCurrency();
+ if (normalized.currency !== ledgerCurrency) {
log.warn(
- `daily spend rejected currency mismatch: ${normalized.currency} != ${DEFAULT_USAGE_CURRENCY}`,
+ `daily spend rejected currency mismatch: ${normalized.currency} != ${ledgerCurrency}`,
);
return { day, money: await getSpendForDay(day) };
}
const db = getDbClient().drizzle;
- // 单币种日账本:入口只允许当前区域币种。升级前当天若仍是旧币种,
- // 首笔新费用从当前区域币种重新起算;不猜测或换算旧聚合值,也不让当天
- // 后续费用永久停记。CASE 与写入保持原子,避免并发混加不同单位。
+ // 升级前 / 换号前当天若仍是旧币种,首笔新费用从当前账本币种重新起算;不猜测或换算
+ // 旧聚合值,也不让当天后续费用永久停记。CASE 与写入保持原子,避免并发混加不同单位。
const sameCurrency = sql`(${dailySpend.costCurrency} IS NULL OR ${dailySpend.costCurrency} = ${normalized.currency})`;
await db
.insert(dailySpend)
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index 6ba76b6191..8e04a5f845 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -63,6 +63,8 @@ export interface XdGatewayAgentOverride {
* 命名沿用历史("聊天"),但条目本身不保证是聊天模型——是否聊天模型看 mode,
* 服务端目前只透传已经过它自己 chat 过滤的条目,过滤范围以后可能放开(issue #882);
* 客户端一律用 isChatEligible 判定,不依赖本类型名字或服务端过滤范围。
+ *
+ * 能力字段已由服务端一次归一化,客户端不再二次转换(见 model-access/index.ts)。
*/
export interface XdGatewayModelInfo {
id: string;
@@ -82,6 +84,7 @@ export interface XdGatewayModelInfo {
group?: string;
description?: string;
contextWindow?: number;
+ maxOutputTokens?: number;
efforts?: string[];
defaultEffort?: string | null;
sortOrder?: number;
@@ -91,6 +94,7 @@ export interface XdGatewayModelInfo {
defaultEnabled?: boolean;
/** 展示图标 id(AI Gateway 设定;缺省 / 未知值渲染层回落来源供应商标)。 */
icon?: string;
+ modalities?: { input: string[]; output: string[] };
/** per-tab 能力覆盖。 */
perAgent?: Partial<Record<AgentKind, XdGatewayAgentOverride>>;
}
@@ -572,7 +576,11 @@ function computeMerged(): Catalog {
: rawEfforts.filter((e): e is Effort => VALID_EFFORTS.has(e));
const rawDefault = ov.defaultEffort !== undefined ? ov.defaultEffort : gm.defaultEffort;
const defaultEffort: Effort | null =
- rawDefault && VALID_EFFORTS.has(rawDefault) && efforts.includes(rawDefault as Effort)
+ rawDefault === null
+ ? null
+ : rawDefault &&
+ VALID_EFFORTS.has(rawDefault) &&
+ efforts.includes(rawDefault as Effort)
? (rawDefault as Effort)
: efforts.includes('high')
? 'high'
@@ -586,6 +594,7 @@ function computeMerged(): Catalog {
name: gm.name ?? gm.id,
group: gm.group ?? 'custom:xd',
contextWindow: ov.contextWindow ?? gm.contextWindow ?? 200_000,
+ ...(gm.maxOutputTokens !== undefined ? { maxOutput: gm.maxOutputTokens } : {}),
// override 或 gateway 模型显式给了才算真实上限;落到 200_000 兜底的不标记。
...(ov.contextWindow !== undefined || gm.contextWindow !== undefined
? { contextWindowVerified: true }
@@ -599,6 +608,7 @@ function computeMerged(): Catalog {
...(defaultEnabled !== undefined ? { defaultEnabled } : {}),
...(gm.icon !== undefined ? { icon: gm.icon } : {}),
...(cost ? { cost } : {}),
+ ...(gm.modalities !== undefined ? { modalities: gm.modalities } : {}),
};
models[agent]!.push(merged);
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 57e7c48496..117bb24da8 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -286,12 +286,17 @@ import {
import { recordModelMismatchOnMessage } from '../modelMismatchBroadcaster.js';
import { detectClaudeModelMismatch } from '../../shared/modelMismatch.js';
import { triggerClaudeAccountUsageRefresh } from '../usage/claudeAccountUsage.js';
-import { getCodexSubscriptionValuePrice, getModelPriceQuote, getModelPricing, getModelPricingForModel, getSubscriptionDirectValuePrice } from '../usage/modelPricing.js';
+import { getCodexSubscriptionValuePrice, getGatewayAccountCurrency, getModelPriceQuote, getModelPricing, getModelPricingForModel, getSubscriptionDirectValuePrice } from '../usage/modelPricing.js';
import { computeModelUsageDeltas, type ModelUsageCumulative, type ModelUsageDeltaEntry } from '../usage/modelUsageDelta.js';
import { claudeSubscriptionUsageModelKey, codexApiUsageModelKey, codexSubscriptionUsageModelKey } from '../usage/usageHistory.js';
import { buildClaudeTurnUsageDetails, computePriceQuoteTurnMoney, estimateClaudeSubscriptionTurnValue, isAnthropicModel, normalizeModelIdForPricing, resolveClaudeTurnCostSinks, type BillingRoute } from '../usage/turnCostCalculator.js';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX, isSubscriptionDirectModel } from '../../shared/subscriptionModels.js';
-import { addRegionalMoney, regionalizeUsd, type RegionalMoney } from '../../shared/regionalMoney.js';
+import {
+ addRegionalMoney,
+ usdToLedgerCurrency,
+ type RegionalMoney,
+} from '../../shared/regionalMoney.js';
+import { currentLedgerCurrency } from '../usage/ledgerCurrency.js';
import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import { triggerClaudeSubscriptionUsageRefresh, triggerCodexAccountUsageRefresh } from './usage.js';
import {
@@ -426,7 +431,10 @@ import {
import { getActiveCatalog, setDiscoveredProviderModels } from '../maker-host/active-catalog.js';
import { testProviderConnection } from '../maker-host/provider-diagnostics.js';
import { fetchProviderModels } from '../maker-host/provider-model-fetch.js';
-import { beginProviderRouteMutation } from '../maker-host/provider-route.js';
+import {
+ beginProviderRouteMutation,
+ isUserProviderSession,
+} from '../maker-host/provider-route.js';
import {
getAnthropicModelDiscoveryFailure,
refreshAnthropicModelsFromHttp,
@@ -3199,14 +3207,14 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
const value = computePriceQuoteTurnMoney(
m.deltas,
quote ?? undefined,
- CURRENT_CINDY_REGION,
+ currentLedgerCurrency(),
);
if (value?.amount) estimatedValues.push(value);
}
if (isClaudeSubscriptionSession) {
const claudeEstimated = estimateClaudeSubscriptionTurnValue(
perModel,
- CURRENT_CINDY_REGION,
+ currentLedgerCurrency(),
);
if (claudeEstimated?.amount) estimatedValues.push(claudeEstimated);
}
@@ -3255,7 +3263,9 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
? 'provider-api'
: 'unknown';
if (route === 'subscription' || route === 'xd-gateway') return;
- const money = regionalizeUsd(rawDelta, CURRENT_CINDY_REGION);
+ const ledgerCurrency =
+ (await getGatewayAccountCurrency()) ?? currentLedgerCurrency();
+ const money = usdToLedgerCurrency(rawDelta, ledgerCurrency);
const turnUsageDetails = buildClaudeTurnUsageDetails(doneData?.usage, undefined, resolvedModel);
recordTurnSpend(money);
recordSessionTurnSpend(session.id, money);
@@ -3293,6 +3303,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
// 「是否走订阅(不计网关费)」改由 spawn 注入 + 该会话是否显式选了 XD 网关决定。
const sessionProvider = getSessionProvider(session.id);
const isRemoteCodexSession = Boolean(session.remoteHostId);
+ const isCustomProviderRoute =
+ !isRemoteCodexSession && isUserProviderSession(session.id);
const codexAuthInjection = isRemoteCodexSession ? null : getCodexProxyAuthInjection();
const modelPromise = turnModelPromiseBySession.get(session.id) ?? readSessionModelForUsage(session.id);
turnModelPromiseBySession.delete(session.id);
@@ -3326,11 +3338,18 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
} catch {
// 模型读取失败时仍记录 token, 聚合 UI 会归到 unknown。
}
- const isCodexBudgetRoute = pricingModel.startsWith('codex/');
- const isCodexXaiProviderRoute = pricingModel.startsWith(XAI_MODEL_PREFIX);
+ const isCodexBudgetRoute =
+ (sessionProvider == null || sessionProvider === 'xd')
+ && pricingModel.startsWith('codex/');
+ const isCodexXaiProviderRoute =
+ (sessionProvider == null || sessionProvider === 'xai')
+ && pricingModel.startsWith(XAI_MODEL_PREFIX);
+ const isCodexOpenAiProviderRoute =
+ sessionProvider == null || sessionProvider === 'openai';
const hasGatewayKey = Boolean(readClaudeApiKey());
const hasEffectiveGatewayRoute =
!isRemoteCodexSession &&
+ !isCustomProviderRoute &&
(
codexAuthInjection === 'env-key' ||
isCodexBudgetRoute ||
@@ -3338,7 +3357,11 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
);
const isSubscriptionValue = isRemoteCodexSession ||
isCodexXaiProviderRoute ||
- (codexAuthInjection === 'oauth-bearer' && !hasEffectiveGatewayRoute);
+ (
+ isCodexOpenAiProviderRoute
+ && codexAuthInjection === 'oauth-bearer'
+ && !hasEffectiveGatewayRoute
+ );
const modelUsageKey = isSubscriptionValue
? codexSubscriptionUsageModelKey(pricingModel)
: codexApiUsageModelKey(pricingModel);
@@ -3362,18 +3385,20 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
try {
const pricing = isSubscriptionValue && !isCodexXaiProviderRoute
? await getModelPricing()
- : isSubscriptionValue
- ? null
- : await getModelPricingForModel('xd', pricingModel);
+ : hasEffectiveGatewayRoute
+ ? await getModelPricingForModel('xd', pricingModel)
+ : null;
const price = isCodexXaiProviderRoute
? getSubscriptionDirectValuePrice(pricingModel)
: isSubscriptionValue
? getCodexSubscriptionValuePrice(pricingModel, pricing)
- : getModelPriceQuote(pricing, 'xd', pricingModel);
+ : hasEffectiveGatewayRoute
+ ? getModelPriceQuote(pricing, 'xd', pricingModel)
+ : undefined;
const money = computePriceQuoteTurnMoney(
codexUsageToTokens(u),
price ?? undefined,
- CURRENT_CINDY_REGION,
+ currentLedgerCurrency(),
);
if (!isSubscriptionValue && money) {
await recordModelTurnUsage({
@@ -3419,6 +3444,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
.then((model) => {
const hasGatewayKey = Boolean(readClaudeApiKey());
if (!isRemoteCodexSession &&
+ !isCustomProviderRoute &&
!model.startsWith(XAI_MODEL_PREFIX) &&
(codexAuthInjection === 'env-key' || model.startsWith('codex/') || (sessionProvider === 'xd' && hasGatewayKey))) {
void triggerClaudeAccountUsageRefresh();
diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.ts
index d964a9ebe2..128af960df 100644
--- a/apps/desktop/src/main/model-access/index.ts
+++ b/apps/desktop/src/main/model-access/index.ts
@@ -171,12 +171,16 @@ function applyGatewayModels(
// dev:本地目录文件(catalog/providers.json)的 cindyModelMeta 段覆盖服务端下发的
// 元数据,改本地 json + 重启即可自测,无需发 OSS / 等服务端热加载;只覆盖同 id,
// 清单成员资格仍以网关为准。packaged 不走此分支(语义见 devMetaOverlay.ts)。
- const effective =
+ const overlaid =
isDev() && models.length > 0
? overlayCindyModelMeta(models, getActiveCatalog().cindyModelMeta, log)
: models;
+ // 能力字段不在客户端二次转换 —— Model Access Server 已把 Gateway 的
+ // contextLength / supportedEndpoints / reasoning / supportsServiceTier / architecture
+ // 一次归一化成 contextWindow / agents / efforts / supportsFastMode / modalities,
+ // 同一含义只下发一个字段。这里直接用下发值,唯一事实源在服务端。
// active-catalog 统一收口会原地刷新 Maker capabilities,再广播同一 revision。
- setXdGatewayModels(effective);
+ setXdGatewayModels(overlaid);
}
async function runModelsSync(
@@ -202,7 +206,8 @@ async function runModelsSync(
return;
}
if (myGen !== authGeneration) return; // 响应归属旧账号,丢弃
- const models = (payload.models ?? []).filter((m) => typeof m?.id === 'string' && m.id);
+ const models = (payload.models ?? [])
+ .filter((m) => typeof m?.id === 'string' && m.id);
if (models.length === 0) {
log.warn('xd gateway models fetch returned empty list; clearing current list');
applyGatewayModels([], authenticatedUserId);
diff --git a/apps/desktop/src/main/sessionSpendBroadcaster.ts b/apps/desktop/src/main/sessionSpendBroadcaster.ts
index 27031ab1fb..7cf80a95ed 100644
--- a/apps/desktop/src/main/sessionSpendBroadcaster.ts
+++ b/apps/desktop/src/main/sessionSpendBroadcaster.ts
@@ -27,11 +27,11 @@ import { createLogger } from './logger';
import { tapWindowBroadcast } from './device-link/broadcast-tap.js';
import {
addRegionalMoney,
- DEFAULT_USAGE_CURRENCY,
legacyUsdMoney,
normalizeRegionalMoney,
type RegionalMoney,
} from '../shared/regionalMoney.js';
+import { currentLedgerCurrency } from './usage/ledgerCurrency.js';
const log = createLogger('sessionSpendBroadcaster');
@@ -81,17 +81,21 @@ export async function recordSessionTurnSpend(
if (!sessionId) return;
const normalized = normalizeRegionalMoney(money);
if (!normalized || normalized.amount < 1e-10) return;
- if (normalized.currency !== DEFAULT_USAGE_CURRENCY) {
+ // 只接受本账号的结算币种。基准取 currentLedgerCurrency() 而不是构建区域 —— 结算币种
+ // 由服务端按账号所属租户下发,不保证等于发行区域;按区域判会让以 USD 结算的账号
+ // 「本对话」金额永远停在 0。异币种(脏数据 / 上游 bug)仍然拒收。
+ const ledgerCurrency = currentLedgerCurrency();
+ if (normalized.currency !== ledgerCurrency) {
log.warn(
- `recordSessionTurnSpend rejected currency mismatch: ${normalized.currency} != ${DEFAULT_USAGE_CURRENCY}`,
+ `recordSessionTurnSpend rejected currency mismatch: ${normalized.currency} != ${ledgerCurrency}`,
);
return;
}
try {
const db = getDbClient().drizzle;
- // 单币种累计列:恢复旧会话时若累计仍是旧币种,首笔当前币种费用重新
- // 起算聚合列;消息历史保持原样,不猜测旧总额应如何换算。CASE 与写入
- // 在同一条 UPDATE 里,避免并发混加不同单位。
+ // 单币种累计列:恢复旧会话时若累计仍是旧币种,首笔当前币种费用重新起算聚合列;
+ // 消息历史保持原样,不猜测旧总额应如何换算。CASE 与写入在同一条 UPDATE 里,
+ // 避免并发混加不同单位。
const sameCurrency = sql`(${sessions.totalCostCurrency} IS NULL OR ${sessions.totalCostCurrency} = ${normalized.currency})`;
await db
.update(sessions)
diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
index b7aa87a371..1f4eed424c 100644
--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
@@ -54,6 +54,11 @@ vi.mock('../../secrets/providerSecretStore', () => ({
}));
import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
+import { DEFAULT_USAGE_CURRENCY } from '../../../shared/regionalMoney';
+import {
+ __resetActiveLedgerCurrencyForTesting,
+ currentLedgerCurrency,
+} from '../ledgerCurrency';
import {
__resetModelPricingCacheForTesting,
clearGatewayModelPricing,
@@ -242,7 +247,9 @@ describe('pricing cache lifecycle', () => {
await vi.waitFor(async () => {
const raw = JSON.parse(await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'));
expect(raw).toMatchObject({
- version: 6,
+ // 账号币种与报价同快照持久化后升到 8:旧缓存缺少账号币种,
+ // 必须靠版本号失效掉。改缓存结构时同步这里。
+ version: 8,
scope: expectedScope(),
pricing,
});
@@ -254,6 +261,35 @@ describe('pricing cache lifecycle', () => {
expect(fetchMock).not.toHaveBeenCalled();
});
+ it('restores the active ledger currency when only the disk cache is hydrated', async () => {
+ // 模型即使没有可计价 quote,也可能明确声明账号结算币种;两者必须同快照恢复。
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ replaceGatewayModelPricing([
+ {
+ id: 'gpt-5.5',
+ currency: 'USD',
+ },
+ ]);
+ await vi.waitFor(async () => {
+ const raw = JSON.parse(await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'));
+ expect(raw).toMatchObject({
+ pricing: {},
+ accountCurrency: 'USD',
+ });
+ });
+
+ // 模拟重启:清掉内存缓存与账本币种,只留磁盘缓存
+ __resetModelPricingCacheForTesting();
+ __resetActiveLedgerCurrencyForTesting();
+ expect(currentLedgerCurrency()).toBe(DEFAULT_USAGE_CURRENCY);
+
+ await expect(getModelPricing()).resolves.toEqual({});
+
+ expect(currentLedgerCurrency()).toBe('USD');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it('persists a startup snapshot under the authenticated user before localDb is ready', async () => {
mocks.getCurrentDbClientUserId.mockReturnValue(null);
const pricing = replaceGatewayModelPricing(
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
index 5452194dbf..fa93e1c911 100644
--- a/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/turnCostCalculator.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
import type { ModelUsageDeltaEntry } from '../modelUsageDelta';
+import {
+ __resetActiveLedgerCurrencyForTesting,
+ setActiveLedgerCurrency,
+} from '../ledgerCurrency';
import {
buildClaudeTurnUsageDetails,
computeGatewayTurnCost,
@@ -208,6 +212,90 @@ describe('resolveTurnCost', () => {
});
});
+ it('falls back to the SDK USD amount for a USD-settled account on a CN build', () => {
+ // 结算币种由目录里其它 xd 报价声明,不看构建区域、也不按租户判断。
+ // 以 USD 结算的账号在某个模型缺报价时同样要记账,不能漏计。
+ const result = resolveTurnCost({
+ rawModel: 'unquoted-model',
+ tokens: {
+ inputTokens: 1_000,
+ outputTokens: 100,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ },
+ sdkCostDelta: 1.23,
+ pricing: catalog(quote('some-other-model', 3, 15)),
+ context: XD_GATEWAY_CN,
+ });
+ expect(result.source).toBe('sdk-fallback');
+ expect(result.money).toEqual({
+ amount: 1.23,
+ currency: 'USD',
+ approximate: false,
+ kind: 'actual-cost',
+ });
+ });
+
+ it('projects non-gateway costs to the ledger currency, not the build region', () => {
+ // 账本是单币种的,写入侧只接受账本币种。以 USD 结算的账号在 CN 构建上,若把第三方
+ // 供应商 / 订阅估值按区域折成 CNY,这些金额会被账本守卫整批丢弃 —— 那些渠道的花费
+ // 就再也记不进日账本、按模型统计与「本对话」累计。
+ const providerApiOnUsdLedger = resolveTurnCost({
+ rawModel: 'gpt-4o',
+ tokens: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },
+ sdkCostDelta: 2,
+ pricing: catalog(quote('some-other-model', 3, 15)),
+ context: { providerId: 'openai', billingRoute: 'provider-api', region: 'cn' },
+ });
+ expect(providerApiOnUsdLedger.money).toMatchObject({ amount: 2, currency: 'USD' });
+
+ // CNY 账本仍按固定汇率投影(原有行为)。
+ const providerApiOnCnyLedger = resolveTurnCost({
+ rawModel: 'gpt-4o',
+ tokens: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 },
+ sdkCostDelta: 2,
+ pricing: catalog(quote('some-other-model', 3, 15, { currency: 'CNY' })),
+ context: { providerId: 'openai', billingRoute: 'provider-api', region: 'cn' },
+ });
+ expect(providerApiOnCnyLedger.money).toMatchObject({ currency: 'CNY' });
+ expect(providerApiOnCnyLedger.money?.amount).toBeCloseTo(2 * 6.7, 6);
+ });
+
+ it('omits the SDK USD fallback for a CNY-settled account (wrong currency, no discount)', () => {
+ // CNY 账本下 SDK 的 USD 既不是该账号的报价口径、也不含 costDiscount,
+ // 折算进去只会误记,这一轮宁可不记。
+ const result = resolveTurnCost({
+ rawModel: 'unquoted-model',
+ tokens: {
+ inputTokens: 1_000,
+ outputTokens: 100,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ },
+ sdkCostDelta: 1.23,
+ pricing: catalog(quote('some-other-model', 3, 15, { currency: 'CNY' })),
+ context: XD_GATEWAY_CN,
+ });
+ expect(result.source).toBe('sdk-fallback');
+ expect(result.money).toBeNull();
+ });
+
+ it('uses the active ledger currency when the pricing catalog is entirely empty', () => {
+ try {
+ setActiveLedgerCurrency('USD');
+ const result = resolveTurnCost({
+ rawModel: 'unquoted-model',
+ tokens: { inputTokens: 1_000, outputTokens: 100, cacheReadTokens: 0, cacheCreateTokens: 0 },
+ sdkCostDelta: 1.23,
+ pricing: {},
+ context: XD_GATEWAY_CN,
+ });
+ expect(result.money).toMatchObject({ amount: 1.23, currency: 'USD' });
+ } finally {
+ __resetActiveLedgerCurrencyForTesting();
+ }
+ });
+
it('applies an ordinary Gateway model costDiscount exactly once', () => {
const result = resolveTurnCost({
rawModel: 'discounted-model',
@@ -233,6 +321,30 @@ describe('resolveTurnCost', () => {
});
});
+ it('keeps a USD Gateway quote unconverted on a CN build (XD enterprise settles in USD)', () => {
+ // 存在恒以 USD 结算的账号,即便客户端是 CN 构建也不能按
+ // USD_TO_CNY_FIXED_RATE 折成人民币:账号配额那条路径(gatewayMoney)保留 USD 原值,
+ // turn 若被换算就会在同一行出现 $ / ¥ 混排,且金额差一个汇率倍数、无法与账单核对。
+ const result = resolveTurnCost({
+ rawModel: 'gpt-5.5',
+ tokens: {
+ inputTokens: 1_000_000,
+ outputTokens: 0,
+ cacheReadTokens: 0,
+ cacheCreateTokens: 0,
+ },
+ pricing: catalog(quote('gpt-5.5', 3, 15)),
+ context: XD_GATEWAY_CN,
+ });
+ expect(result.source).toBe('gateway');
+ expect(result.money).toMatchObject({
+ amount: 3,
+ currency: 'USD',
+ approximate: false,
+ kind: 'actual-cost',
+ });
+ });
+
it('XD missing price with no SDK cost still resolves to null money', () => {
const result = resolveTurnCost({
rawModel: 'unknown-model',
@@ -378,7 +490,7 @@ describe('subscription value and usage details', () => {
outputTokens: 200_000,
}),
],
- 'global',
+ 'USD',
);
expect(value).toMatchObject({
amount: 10,
@@ -396,11 +508,11 @@ describe('subscription value and usage details', () => {
resolvedModel('claude-opus-4-8', { inputTokens: 1_000_000 }, usdMoney(1)),
resolvedModel('claude-unknown-9', { inputTokens: 1_000_000 }),
],
- 'global',
+ 'USD',
),
).toBeNull();
expect(
- estimateClaudeSubscriptionTurnValue([resolvedModel('claude-opus-4-8')], 'global'),
+ estimateClaudeSubscriptionTurnValue([resolvedModel('claude-opus-4-8')], 'USD'),
).toBeNull();
});
diff --git a/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts b/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts
index 4b3e0ba6d9..1c569089c0 100644
--- a/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/turnCostRouting.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest';
+import {
+ __resetActiveLedgerCurrencyForTesting,
+ setActiveLedgerCurrency,
+} from '../ledgerCurrency';
import type { ModelUsageDeltaEntry } from '../modelUsageDelta';
import { resolveClaudeTurnCostSinks } from '../turnCostCalculator';
import type {
@@ -77,24 +81,29 @@ describe('turn cost routing regression', () => {
});
it('provider API USD cost converts at 6.7 only when entering the CN ledger', () => {
- const result = resolveClaudeTurnCostSinks(
- [
- delta({ model: 'claude-opus-4-8', costUsdDelta: 1.5 }),
- delta({ model: 'mystery-model', costUsdDelta: 2 }),
- ],
- null,
- {
- providerId: 'anthropic',
- billingRoute: 'provider-api',
- region: 'cn',
- },
- );
+ try {
+ setActiveLedgerCurrency('CNY');
+ const result = resolveClaudeTurnCostSinks(
+ [
+ delta({ model: 'claude-opus-4-8', costUsdDelta: 1.5 }),
+ delta({ model: 'mystery-model', costUsdDelta: 2 }),
+ ],
+ null,
+ {
+ providerId: 'anthropic',
+ billingRoute: 'provider-api',
+ region: 'cn',
+ },
+ );
- expect(result.turnMoney).toMatchObject({
- currency: 'CNY',
- approximate: false,
- });
- expect(result.turnMoney?.amount).toBeCloseTo(23.45);
- expect(result.perModel.map((item) => item.source)).toEqual(['sdk', 'sdk']);
+ expect(result.turnMoney).toMatchObject({
+ currency: 'CNY',
+ approximate: false,
+ });
+ expect(result.turnMoney?.amount).toBeCloseTo(23.45);
+ expect(result.perModel.map((item) => item.source)).toEqual(['sdk', 'sdk']);
+ } finally {
+ __resetActiveLedgerCurrencyForTesting();
+ }
});
});
diff --git a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
index 05d90dbe58..cefb7585b2 100644
--- a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts
@@ -382,6 +382,43 @@ describe('readUsageHistoryWith', () => {
});
});
+ it('keeps a USD-settled account history intact regardless of build region', async () => {
+ // 结算币种由服务端按账号所属租户下发,不是构建区域。账本币种若按区域取,
+ // 以 USD 结算的账号在 CN 构建上每一行都会被判成异币种归零 —— 等于这些用户不计费。
+ // 判据取自当前 Gateway 报价目录的币种。
+ const usdRow = (amount: number): RegionalMoney => ({
+ amount,
+ currency: 'USD',
+ approximate: false,
+ kind: 'actual-cost',
+ });
+ const result = await readUsageHistoryWith(
+ makeDeps({
+ getAllSpendDays: async () => [
+ { day: '2026-06-10', money: usdRow(3) },
+ { day: TODAY, money: usdRow(5) },
+ ],
+ getModelUsageSince: async () => [],
+ getModelPricing: async () => ({
+ xd: {
+ 'gpt-5.5': {
+ providerId: 'xd',
+ modelId: 'gpt-5.5',
+ currency: 'USD',
+ source: 'gateway',
+ approximate: false,
+ inputPerMtok: 3,
+ outputPerMtok: 15,
+ },
+ },
+ }),
+ }),
+ );
+
+ expect(result.totals.today).toMatchObject({ amount: 5, currency: 'USD' });
+ expect(result.totals.last30Days).toMatchObject({ amount: 8, currency: 'USD' });
+ });
+
it('uses provider-scoped Anthropic reference pricing for Claude subscription rows', async () => {
const expected = regionalUsdAmount(5);
const result = await readUsageHistoryWith(makeDeps({
diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.ts
index f675be992d..f8532d97d6 100644
--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts
+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts
@@ -42,10 +42,14 @@
import { BrowserWindow } from 'electron';
+import type { MoneyCurrency } from '../../shared/regionalMoney';
+import { getAuthState } from '../authManager';
import { createLogger } from '../logger';
import { readClaudeApiKey } from '../maker-host/auth-adapters';
import { outboundFetch } from '../maker-host/outbound-fetch';
import { claudeUpstreamEndpoint } from '../maker-host/runtime-configs';
+import { getGatewayAccountCurrency } from './modelPricing';
+import { currentLedgerCurrency } from './ledgerCurrency';
const log = createLogger('claudeAccountUsage');
@@ -55,12 +59,13 @@ export const USAGE_CLAUDE_ACCOUNT_CHANGED = 'usage:claude-account-changed';
export interface ClaudeAccountUsageSnapshot {
/**
* 当前周期(网关部署为 30d / 月度) 跨所有客户端 + 所有 API key 的累计花费,
- * 来自 Gateway user.spend,数值保持 Gateway 原值(原生 USD 口径,展示层经
- * gatewayMoney 标注单位,不按构建区域改标)。不只本机本壳。
+ * 来自 Gateway user.spend,数值与币种均保持 Gateway 账号口径。不只本机本壳。
*/
spend: number;
/** 周期内预算上限,保持 Gateway 原值 (来自 user.max_budget)。 */
maxBudget: number;
+ /** 与当前 Model Access 模型目录声明一致的 Gateway 账号原生币种。 */
+ currency: MoneyCurrency;
/** 下次重置时间 ISO8601 (来自 user.budget_reset_at)。 */
budgetResetAt?: string | null;
/**
@@ -176,6 +181,12 @@ function resolveDailyActivitySpend(activity: LiteLlmDailyActivity): { todaySpend
}
async function fetchOnce(): Promise<ClaudeAccountUsageSnapshot | null> {
+ // 币种优先取账号目录声明。取不到时**不放弃整个快照**,回落本地账本币种:
+ // 手填 XD key 是明确支持的兜底流程(Model Access 处于 disabled / failed 时),那时没有
+ // 目录可推导,若直接 return 会让这些会话永久看不到账号配额 —— 比"币种按账本回落"更糟。
+ // 回落值与账本写入侧同源(currentLedgerCurrency),不会与同一行的其它金额混排。
+ const currency =
+ (await getGatewayAccountCurrency(getAuthState().user?.id)) ?? currentLedgerCurrency();
const apiKey = readClaudeApiKey();
// 直连真上游,不走本地 anthropic-compat-proxy —— 这条账号查询路径跟 Claude Code 子进程
// 无关,proxy 只服务于子进程的 chat completion 请求。
@@ -202,6 +213,7 @@ async function fetchOnce(): Promise<ClaudeAccountUsageSnapshot | null> {
return {
spend: cycle.spend,
maxBudget: cycle.maxBudget,
+ currency,
budgetResetAt: cycle.budgetResetAt,
todaySpend,
fetchedAt: Date.now(),
diff --git a/apps/desktop/src/main/usage/ledgerCurrency.ts b/apps/desktop/src/main/usage/ledgerCurrency.ts
new file mode 100644
index 0000000000..bd20206760
--- /dev/null
+++ b/apps/desktop/src/main/usage/ledgerCurrency.ts
@@ -0,0 +1,40 @@
+/**
+ * 当前登录账号的本地账本币种(单一事实源)。
+ *
+ * 为什么不能用构建区域(DEFAULT_USAGE_CURRENCY)代替:结算币种由服务端按账号所属租户
+ * 下发,不保证与客户端发行区域一致 —— 例如某些组织账号会以 USD 结算,而客户端可能是
+ * CN 构建。这是完全正常的组合,按区域判会把这些账号的每一笔都当成异币种拒收,
+ * 等于这些用户完全不计费。
+ *
+ * 值由模型目录同步时写入(见 usage/modelPricing.replaceGatewayModelPricing)——报价币种
+ * 就是该账号的结算币种。登出 / 切号 / 清空报价时置为未知,读侧回落构建默认值。
+ *
+ * 本模块刻意零依赖(只引 shared 常量):账本写入层(localDb/dailySpend、
+ * localDb/dailyModelUsage、sessionSpendBroadcaster)和报价层都要用它,
+ * 走这里可以避免两边互相 import 成环。
+ */
+
+import { DEFAULT_USAGE_CURRENCY, type MoneyCurrency } from '../../shared/regionalMoney.js';
+
+let active: MoneyCurrency | null = null;
+
+/**
+ * 记录当前账号的账本币种。传 null 表示未知(登出、切号、目录尚未同步,
+ * 或目录出现混合币种因而不可信),此时读侧回落构建默认值。
+ */
+export function setActiveLedgerCurrency(currency: MoneyCurrency | null): void {
+ active = currency;
+}
+
+/**
+ * 账本写入与聚合应当使用的币种。未知时回落构建默认值 —— 冷启动首帧、纯订阅账号
+ * (没有 Gateway 报价)都走这条,与历史行为一致。
+ */
+export function currentLedgerCurrency(): MoneyCurrency {
+ return active ?? DEFAULT_USAGE_CURRENCY;
+}
+
+/** 仅测试:重置为未知。 */
+export function __resetActiveLedgerCurrencyForTesting(): void {
+ active = null;
+}
diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.ts
index 8a53e1fe91..11df6668e4 100644
--- a/apps/desktop/src/main/usage/modelPricing.ts
+++ b/apps/desktop/src/main/usage/modelPricing.ts
@@ -3,7 +3,8 @@
*
* XD 模型与价格只来自 model-access-server 的同一次 GET /models 响应。这里不再
* 直接请求 LiteLLM;模型同步成功时整体替换 XD quote,失败时保留上一份成功快照。
- * Gateway per-token 数值在这里转换为 per-Mtok,币种只由构建区域决定。
+ * Gateway per-token 数值在这里转换为 per-Mtok;新版服务端下发的原生币种优先,
+ * 旧版服务端缺失时才回退构建区域。
*/
import { promises as fs, statSync } from 'node:fs';
@@ -12,14 +13,21 @@ import { app, BrowserWindow } from 'electron';
import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import {
+ gatewayLedgerCurrency,
gatewayPricingCatalog,
getModelPriceQuote,
subscriptionDirectPriceQuote,
} from '../../shared/modelPriceQuote.js';
import type { ModelAccessGatewayModel } from '../../shared/modelAccess.js';
import { providerSecretStorageKey } from '../../shared/providerSecrets.js';
-import { type ModelPriceQuote, type ModelPricingCatalog } from '../../shared/regionalMoney.js';
+import {
+ gatewayCurrencyForRegion,
+ type ModelPriceQuote,
+ type ModelPricingCatalog,
+ type MoneyCurrency,
+} from '../../shared/regionalMoney.js';
import { getCurrentDbClientUserId } from '../localDb/client/current.js';
+import { setActiveLedgerCurrency } from './ledgerCurrency.js';
import { createLogger } from '../logger.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
import { resolveOwnerScopedSecretStorageKey } from '../secrets/providerSecretStore.js';
@@ -31,9 +39,11 @@ export type {
} from '../../shared/regionalMoney.js';
const log = createLogger('modelPricing');
+// v8:账号币种与报价同快照持久化;无报价模型也可能明确声明结算币种。
+// v7:币种改为优先使用 Model Access 明确声明,不能复用按 region 猜测的旧 quote。
// v6:所有 Gateway 模型统一按服务端 costDiscount 计费。v5 的 codex/ quote 已
// 硬编码乘过 0.15 且丢弃 costDiscount,不能继续复用。
-const DISK_CACHE_VERSION = 6;
+const DISK_CACHE_VERSION = 8;
const DISK_CACHE_FILE = 'model-pricing.json';
export const MODEL_PRICING_CHANGED_CHANNEL = 'usage:model-pricing-changed';
@@ -43,15 +53,34 @@ interface DiskCachePayload {
scope: string;
fetchedAt: number;
pricing: ModelPricingCatalog;
+ accountCurrency: MoneyCurrency | null;
}
let cache: ModelPricingCatalog | null = null;
let cacheScope: string | null = null;
let cacheAt = 0;
let modelSyncInflight: Promise<unknown> | null = null;
+let gatewayAccountCurrency: MoneyCurrency | null = null;
+let gatewayAccountCurrencyScope: string | null = null;
const hydratedScopes = new Set<string>();
const hydrateInflightByScope = new Map<string, Promise<ModelPricingCatalog | null>>();
+function resolveGatewayAccountCurrency(
+ models: readonly ModelAccessGatewayModel[],
+): MoneyCurrency | null {
+ if (models.length === 0) return null;
+ const currencies = new Set(
+ models
+ .map((model) => model.currency)
+ .filter((currency): currency is MoneyCurrency => currency === 'CNY' || currency === 'USD'),
+ );
+ if (currencies.size > 1) {
+ log.warn('xd gateway models returned mixed currencies; account quota currency unavailable');
+ return null;
+ }
+ return currencies.values().next().value ?? gatewayCurrencyForRegion(CURRENT_CINDY_REGION);
+}
+
function currentKeyCacheIdentity(): string {
try {
const physicalKey = resolveOwnerScopedSecretStorageKey(providerSecretStorageKey('xd'));
@@ -147,6 +176,7 @@ function validateCatalog(value: unknown): ModelPricingCatalog | null {
async function writeDiskCache(
scope: string,
pricing: ModelPricingCatalog,
+ accountCurrency: MoneyCurrency | null,
fetchedAt: number,
): Promise<void> {
try {
@@ -157,6 +187,7 @@ async function writeDiskCache(
scope,
fetchedAt,
pricing,
+ accountCurrency,
};
await fs.writeFile(file, JSON.stringify(payload), 'utf8');
hydratedScopes.add(scope);
@@ -181,7 +212,10 @@ async function hydrateFromDisk(scope: string): Promise<ModelPricingCatalog | nul
raw.version !== DISK_CACHE_VERSION ||
raw.scope !== scope ||
!Number.isFinite(raw.fetchedAt) ||
- Number(raw.fetchedAt) <= 0
+ Number(raw.fetchedAt) <= 0 ||
+ (raw.accountCurrency !== null &&
+ raw.accountCurrency !== 'CNY' &&
+ raw.accountCurrency !== 'USD')
) {
return null;
}
@@ -191,6 +225,14 @@ async function hydrateFromDisk(scope: string): Promise<ModelPricingCatalog | nul
cache = pricing;
cacheScope = scope;
cacheAt = Number(raw.fetchedAt);
+ // 账本币种必须在这里恢复,而不是只在 getGatewayAccountCurrency 里:那个函数只服务
+ // 可选的账号配额查询,而计费热路径(register.ts 的 turn 记账、prewarm)走的是
+ // getModelPricing / getModelPricingForModel。冷启动只命中磁盘缓存(/models 尚未
+ // 完成或失败)时若不在此同步,currentLedgerCurrency() 会回落构建默认币种,把该账号
+ // 用缓存报价算出的金额当异币种丢弃 —— 等于这一段时间完全不计费。
+ gatewayAccountCurrency = raw.accountCurrency;
+ gatewayAccountCurrencyScope = scope;
+ setActiveLedgerCurrency(raw.accountCurrency);
log.debug(`hydrated model pricing cache: ${Object.keys(pricing.xd ?? {}).length} XD quotes`);
return pricing;
} catch (err) {
@@ -239,8 +281,13 @@ export function replaceGatewayModelPricing(
cache = pricing;
cacheScope = scope;
cacheAt = Date.now();
+ gatewayAccountCurrency = resolveGatewayAccountCurrency(models);
+ gatewayAccountCurrencyScope = scope;
+ // 账本写入层据此判断"这一笔是不是本账号的结算币种"。目录为空(登出 / clear)或混合
+ // 币种时 resolveGatewayAccountCurrency 返回 null,账本随之回落构建默认值。
+ setActiveLedgerCurrency(gatewayAccountCurrency);
hydratedScopes.add(scope);
- void writeDiskCache(scope, pricing, cacheAt);
+ void writeDiskCache(scope, pricing, gatewayAccountCurrency, cacheAt);
broadcastPricing(pricing);
return pricing;
}
@@ -279,6 +326,39 @@ export async function getModelPricing(): Promise<ModelPricingCatalog | null> {
*/
const PRICING_SYNC_WAIT_MS = 3_000;
+async function waitForModelPricingSync(): Promise<void> {
+ if (!modelSyncInflight) return;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ modelSyncInflight.catch(() => undefined),
+ new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, PRICING_SYNC_WAIT_MS);
+ }),
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}
+
+/**
+ * Model Access 账号用量与模型目录属于同一个 Gateway 租户,因而共用目录声明的
+ * 原生币种。混合币种或尚无当前账号目录时返回 null,调用方不再根据组织名称猜测。
+ */
+export async function getGatewayAccountCurrency(
+ authenticatedUserId?: string,
+): Promise<MoneyCurrency | null> {
+ await waitForModelPricingSync();
+ const scope = currentScope(authenticatedUserId);
+ if (gatewayAccountCurrencyScope === scope) return gatewayAccountCurrency;
+ // 本轮 /models 没跑成时,磁盘缓存里的报价同样能定出币种。hydrateFromDisk 内部会在
+ // 落盘缓存生效的同时把币种写回缓存与账本事实源(那里才是所有取价路径的共同入口),
+ // 所以这里只需触发一次 hydrate 再读结果。
+ await getModelPricing();
+ if (gatewayAccountCurrencyScope === scope) return gatewayAccountCurrency;
+ return cacheScope === scope ? gatewayLedgerCurrency(cache) : null;
+}
+
/**
* 计费热路径等待模型同步已经落下的本地投影,不再自己联网。providerId 是必需的,
* 同模型从 XD/OpenAI/订阅来源进入时不会串价。
@@ -287,19 +367,7 @@ export async function getModelPricingForModel(
providerId: string | null | undefined,
modelId: string,
): Promise<ModelPricingCatalog | null> {
- if (modelSyncInflight) {
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- await Promise.race([
- modelSyncInflight.catch(() => undefined),
- new Promise<void>((resolve) => {
- timer = setTimeout(resolve, PRICING_SYNC_WAIT_MS);
- }),
- ]);
- } finally {
- if (timer) clearTimeout(timer);
- }
- }
+ await waitForModelPricingSync();
const pricing = await getModelPricing();
void getModelPriceQuote(pricing, providerId, modelId);
return pricing;
@@ -330,6 +398,8 @@ export function __resetModelPricingCacheForTesting(): void {
cacheScope = null;
cacheAt = 0;
modelSyncInflight = null;
+ gatewayAccountCurrency = null;
+ gatewayAccountCurrencyScope = null;
hydratedScopes.clear();
hydrateInflightByScope.clear();
}
diff --git a/apps/desktop/src/main/usage/turnCostCalculator.ts b/apps/desktop/src/main/usage/turnCostCalculator.ts
index 647f73e623..5bc5f519e1 100644
--- a/apps/desktop/src/main/usage/turnCostCalculator.ts
+++ b/apps/desktop/src/main/usage/turnCostCalculator.ts
@@ -4,17 +4,24 @@
import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
-import { getModelPriceQuote, providerReferencePriceQuote } from '../../shared/modelPriceQuote.js';
+import {
+ gatewayLedgerCurrency,
+ getModelPriceQuote,
+ providerReferencePriceQuote,
+} from '../../shared/modelPriceQuote.js';
import {
addRegionalMoney,
- regionalizeMoney,
- regionalizeUsd,
+ toLedgerCurrency,
+ usdMoney,
+ usdToLedgerCurrency,
type ModelPriceQuote,
type ModelPricingCatalog,
+ type MoneyCurrency,
type RegionalMoney,
} from '../../shared/regionalMoney.js';
import { buildTurnUsageDetails, type TurnUsageDetails } from '../../shared/turnUsageDetails.js';
import { isSubscriptionDirectModel } from '../../shared/subscriptionModels.js';
+import { currentLedgerCurrency } from './ledgerCurrency.js';
import type { ModelUsageDeltaEntry } from './modelUsageDelta.js';
export interface TurnTokenDeltas {
@@ -32,6 +39,7 @@ export interface TurnPricingContext {
region: CindyRegion;
}
+
export type TurnCostSource = 'sdk' | 'gateway' | 'sdk-fallback' | 'subscription';
export interface TurnCostResolution {
@@ -75,10 +83,15 @@ export function computeGatewayTurnCost(
);
}
+/**
+ * @param ledgerCurrency 本账号的账本币种(结算币种)。非 Gateway 来源的 USD 口径金额
+ * 按它投影,而不是按构建区域 —— 本地账本单币种,按区域投影会让以 USD 结算的账号在
+ * CN 构建上收到 CNY 金额并被账本守卫整批丢弃。
+ */
export function computePriceQuoteTurnMoney(
tokens: TurnTokenDeltas,
price: ModelPriceQuote | undefined,
- region: CindyRegion,
+ ledgerCurrency: MoneyCurrency,
): RegionalMoney | null {
if (!price) return null;
const standardAmount = computeGatewayTurnCost(tokens, price);
@@ -93,20 +106,26 @@ export function computePriceQuoteTurnMoney(
: 0;
const amount = standardAmount * (1 - discount);
const valueEstimate = price.source === 'subscription-reference';
- return regionalizeMoney(
- {
- amount: Math.max(0, amount),
- currency: price.currency,
- approximate: price.approximate || valueEstimate,
- kind: valueEstimate ? 'value-estimate' : 'actual-cost',
- ...(valueEstimate
- ? { estimateReasons: ['subscription-value', 'reference-price'] }
- : price.approximate
- ? { estimateReasons: ['reference-price'] }
- : {}),
- },
- region,
- );
+ const money: RegionalMoney = {
+ amount: Math.max(0, amount),
+ currency: price.currency,
+ approximate: price.approximate || valueEstimate,
+ kind: valueEstimate ? 'value-estimate' : 'actual-cost',
+ ...(valueEstimate
+ ? { estimateReasons: ['subscription-value', 'reference-price'] }
+ : price.approximate
+ ? { estimateReasons: ['reference-price'] }
+ : {}),
+ };
+ // Gateway 报价的币种就是该账号的实际结算币种,原样记账才能与账单对账 —— 不做任何换算。
+ // 否则以 USD 结算的账号在 CN 构建上,turn 会被 USD_TO_CNY_FIXED_RATE 折成 CNY,而同一
+ // 界面的账号配额(走 gatewayMoney,不换算)仍是 USD 原值,造成同一行 $ / ¥ 混排且金额差
+ // 一个汇率倍数、无法与服务端账单核对。
+ //
+ // 其余来源(第三方参考价、订阅价值估算)是 USD 口径,投影到**账本币种**而不是构建区域:
+ // 账本是单币种的,按区域投影会让这些金额在 USD 结算账号上变成 CNY,继而被账本写入守卫
+ // 当异币种整批丢弃,订阅估算与自定义供应商花费就再也记不进来。
+ return price.source === 'gateway' ? money : toLedgerCurrency(money, ledgerCurrency);
}
export function resolveTurnCost(args: {
@@ -123,30 +142,37 @@ export function resolveTurnCost(args: {
return { model, money: null, source: 'subscription' };
}
+ // 本账号的账本币种:目录里有报价时以报价声明为准;目录为空时沿用模型同步已经写入的
+ // 活动账本币种。不能重新按构建区域推断——目录可能只是因为模型都缺标准价格而为空,
+ // 但账号结算币种仍已由完整模型目录确定,按区域回落会让金额被账本守卫拒收。
+ const ledgerCurrency = gatewayLedgerCurrency(pricing) ?? currentLedgerCurrency();
+
if (context.billingRoute === 'xd-gateway') {
const quote = getModelPriceQuote(pricing, 'xd', model);
if (!quote) {
- // Global 的 SDK costUSD 与账本同为 USD,可在冷缓存时保底;CN/Dev 的
- // Gateway 报价原生 CNY,SDK USD 既不是该报价也没有 costDiscount,不能误记。
+ // 该模型没有报价(上游未登记,或目录还没同步下来)。SDK 的 costDelta 是 USD,
+ // 只有账本币种同为 USD 时才能直接兜底记账 —— 这样以 USD 结算的账号不会漏记。
+ //
+ // 币种不同(CNY 账本)仍然不兜底:SDK 值既不是该账号的报价口径、也不含 costDiscount,
+ // 折算进去只会误记,宁可这一轮不记。
const fallbackUsd = Math.max(0, sdkCostDelta ?? 0);
return {
model,
- money:
- context.region === 'global' && fallbackUsd > 0
- ? regionalizeUsd(fallbackUsd, context.region)
- : null,
+ money: ledgerCurrency === 'USD' && fallbackUsd > 0 ? usdMoney(fallbackUsd) : null,
source: 'sdk-fallback',
};
}
return {
model,
- money: computePriceQuoteTurnMoney(tokens, quote, context.region),
+ money: computePriceQuoteTurnMoney(tokens, quote, ledgerCurrency),
source: 'gateway',
};
}
+ // 第三方供应商 / 未知路由:SDK 值是 USD 口径,投影到账本币种而不是构建区域,
+ // 否则 USD 结算账号上这些花费会变成 CNY 并被账本守卫丢弃。
const sdkAmount = Math.max(0, sdkCostDelta ?? 0);
- const money = sdkAmount > 0 ? regionalizeUsd(sdkAmount, context.region) : null;
+ const money = sdkAmount > 0 ? usdToLedgerCurrency(sdkAmount, ledgerCurrency) : null;
return {
model,
money,
@@ -202,16 +228,20 @@ export function resolveClaudeTurnCostSinks(
};
}
+/**
+ * @param ledgerCurrency 本账号账本币种。订阅参考价是 USD 口径,按它投影而不是按区域,
+ * 否则以 USD 结算的账号上这些估值会变成 CNY 并被账本守卫丢弃。
+ */
export function estimateClaudeSubscriptionTurnValue(
perModel: ResolvedModelCost[],
- region: CindyRegion,
+ ledgerCurrency: MoneyCurrency,
): RegionalMoney | null {
const values: RegionalMoney[] = [];
for (const item of perModel) {
if (!isAnthropicModel(item.model) || item.money?.amount) continue;
const quote = providerReferencePriceQuote('anthropic', item.model);
if (!quote) continue;
- const value = computePriceQuoteTurnMoney(item.deltas, quote, region);
+ const value = computePriceQuoteTurnMoney(item.deltas, quote, ledgerCurrency);
if (value && value.amount > 0) values.push(value);
}
return values.length > 0 ? addRegionalMoney(values) : null;
diff --git a/apps/desktop/src/main/usage/usageHistory.ts b/apps/desktop/src/main/usage/usageHistory.ts
index 062730fc99..20e993e89f 100644
--- a/apps/desktop/src/main/usage/usageHistory.ts
+++ b/apps/desktop/src/main/usage/usageHistory.ts
@@ -34,10 +34,10 @@ import { computePriceQuoteTurnMoney } from './turnCostCalculator';
import {
getModelPriceQuote,
} from '../../shared/modelPriceQuote.js';
+import { currentLedgerCurrency } from './ledgerCurrency.js';
import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import {
addCompatibleRegionalMoney,
- DEFAULT_USAGE_CURRENCY,
normalizeRegionalMoney,
USD_TO_CNY_FIXED_RATE,
type ModelPriceQuote,
@@ -57,8 +57,6 @@ const ANOMALY_MIN_TODAY_USD = 1;
const ANOMALY_MIN_ACTIVE_DAYS = 3;
/** 模型拆分统计窗口 (天)。 */
const MODEL_WINDOW_DAYS = 30;
-/** 等价格表的最长预算 (ms) — 缓存命中时是同步快返, 只有冷启动网络 fetch 会触及。 */
-const PRICING_WAIT_BUDGET_MS = 200;
// v4:恢复 CN usage 的 CNY 账本口径,并让订阅 USD 估值按 6.7 投影到 CNY。
const DISK_CACHE_VERSION = 4;
const DISK_CACHE_FILE = 'usage-history.json';
@@ -239,6 +237,7 @@ const defaultDeps: UsageHistoryDeps = {
todayKey: () => localDayKey(),
};
+
interface DiskCachePayload {
version?: number;
optsKey?: string;
@@ -489,7 +488,20 @@ export async function readUsageHistoryWith(
// 历史聚合只有一个金额口径:兼容当前账本币种的金额保留,无法确定换算语义的
// 异币种金额在入口丢弃为 0。token 等非金额统计仍保留。
- const ledgerCurrency = DEFAULT_USAGE_CURRENCY;
+ //
+ // 账本币种与写入侧同一事实源(currentLedgerCurrency):由服务端按账号所属租户下发,
+ // 不保证等于发行区域。按区域取会把以 USD 结算的账号在 CN 构建上的每一行判成异币种、
+ // 整段归零成不计费。历史遗留的异币种行(换号 / 跨区)仍按 keepCompatibleMoney 归零。
+ const [spendDayRows, pricing] = await Promise.all([
+ deps.getAllSpendDays(),
+ // getModelPricing 只读内存或账号作用域内的磁盘快照,不发网络请求。必须等它完成,
+ // 因为 hydrateFromDisk 还负责恢复同一快照声明的账本币种。
+ deps.getModelPricing(),
+ ]);
+ // 必须在上面 pricing 恢复之后再读:hydrateFromDisk 会在磁盘缓存生效的同时回写账本币种,
+ // 而 prewarmModelPricing 与首页首次聚合是并发的。先读会拿到构建默认值,把该账号的日账与
+ // 模型行全部归零,还可能把这个错结果写进 usage-history 缓存。
+ const ledgerCurrency = currentLedgerCurrency();
// 零值也用账本币种:无消费日的 today/空聚合不能把展示单位翻回默认币种。
const zeroActual = (): RegionalMoney => ({
amount: 0,
@@ -506,7 +518,7 @@ export async function readUsageHistoryWith(
});
const keepCompatibleMoney = (money: RegionalMoney): RegionalMoney =>
money.currency === ledgerCurrency ? money : zeroActual();
- const allDays = (await deps.getAllSpendDays()).map((row) => ({
+ const allDays = spendDayRows.map((row) => ({
...row,
money: keepCompatibleMoney(row.money),
}));
@@ -554,13 +566,7 @@ export async function readUsageHistoryWith(
else daysMap.set(day, { day, money: zeroActual(), tokens });
}
const days = [...daysMap.values()].sort((a, b) => (a.day < b.day ? -1 : 1));
- // pricing 不许阻塞首页首帧: 冷启动时 getModelPricing 是一次最长 5s 的网络请求,
- // race 一个短预算 — 没赶上就先按无价格返回 (Codex 行暂显 token 量), 后台 fetch
- // 仍会完成并写 6h 缓存, renderer 下一次刷新 (push 触发) 自然补上估算金额。
- const pricing = await Promise.race([
- deps.getModelPricing(),
- new Promise<null>((resolve) => setTimeout(resolve, PRICING_WAIT_BUDGET_MS, null)),
- ]);
+ // pricing 在函数开头已与消费行并行取好(见那里的 race 注释)。
const hasMissingPendingSubscriptionPrice = modelRows.some((r) =>
isSubscriptionUsageModel(r.model) &&
!getSubscriptionValuePriceFor(
@@ -618,7 +624,7 @@ export async function readUsageHistoryWith(
m.estimatedMoney = computePriceQuoteTurnMoney(
m,
getSubscriptionValuePriceFor(m.agentKind, m.model, pricing),
- CURRENT_CINDY_REGION,
+ ledgerCurrency,
);
}
}
@@ -635,7 +641,7 @@ export async function readUsageHistoryWith(
? (computePriceQuoteTurnMoney(
row,
getSubscriptionValuePriceFor(agentKind, model, pricing),
- CURRENT_CINDY_REGION,
+ ledgerCurrency,
) ?? zeroEstimate())
: zeroEstimate();
const money =
diff --git a/apps/desktop/src/renderer/__tests__/creditPoolTotals.test.ts b/apps/desktop/src/renderer/__tests__/creditPoolTotals.test.ts
new file mode 100644
index 0000000000..c50e2d0ce1
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/creditPoolTotals.test.ts
@@ -0,0 +1,172 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveCreditTotals } from '../lib/creditPoolTotals';
+import type { ModelAccessCreditUsage } from '../../shared/modelAccess';
+
+type Pool = { remaining: string; used: string | null; total: string | null };
+
+function usage(pools: Partial<Record<'plan' | 'purchased' | 'promotional', Pool>>): ModelAccessCreditUsage {
+ const empty: Pool = { remaining: '0', used: null, total: null };
+ return {
+ available: '0',
+ plan: pools.plan ?? empty,
+ purchased: pools.purchased ?? empty,
+ promotional: pools.promotional ?? empty,
+ promotionalGrants: [],
+ promotionalGrantsComplete: true,
+ promotionalGrantConsistency: 'OBSERVED',
+ ledgerUpdatedAt: null,
+ scale: 9,
+ observedAt: '2026-07-30T00:00:00Z',
+ };
+}
+
+describe('resolveCreditTotals', () => {
+ it('sums used and total across the three pools', () => {
+ expect(
+ resolveCreditTotals(
+ usage({
+ plan: { remaining: '38.20', used: '11.80', total: '50.00' },
+ purchased: { remaining: '10.00', used: '2.00', total: '12.00' },
+ promotional: { remaining: '0.00', used: '5.00', total: '5.00' },
+ }),
+ ),
+ ).toEqual({ used: 18.8, total: 67 });
+ });
+
+ it('keeps nine-decimal ledger precision without float drift', () => {
+ // 0.1 + 0.2 在 float 下是 0.30000000000000004; BigInt 汇总后再落地必须是 0.3
+ expect(
+ resolveCreditTotals(
+ usage({
+ plan: { remaining: '0.900000000', used: '0.100000000', total: '1' },
+ purchased: { remaining: '0.800000000', used: '0.200000000', total: '1' },
+ promotional: { remaining: '0', used: '0', total: '0' },
+ }),
+ ),
+ ).toEqual({ used: 0.3, total: 2 });
+ });
+
+ it('backfills a pool with unknown history from its remaining balance', () => {
+ // 实测回归: 订阅期末取消后 plan 池 used/total 为 null 但仍有 ¥1000 余额。
+ // 跳过该池会让总额从 ¥1604 掉成 ¥604 —— 与设置页「可用余额 ¥1594.68」自相矛盾。
+ const totals = resolveCreditTotals(
+ usage({
+ plan: { remaining: '1000.00', used: null, total: null },
+ purchased: { remaining: '583.00', used: '0.00', total: '583.00' },
+ promotional: { remaining: '11.68', used: '9.32', total: '21.00' },
+ }),
+ );
+ expect(totals).toEqual({ used: 9.32, total: 1604 });
+ // 核心不变量: 总额 − 已用 === Gateway 的 available (三池 remaining 之和)
+ expect(totals!.total - totals!.used).toBeCloseTo(1000 + 583 + 11.68, 9);
+ });
+
+ it('keeps total − used equal to available when every pool history is known', () => {
+ const totals = resolveCreditTotals(
+ usage({
+ plan: { remaining: '38.20', used: '11.80', total: '50.00' },
+ purchased: { remaining: '10.00', used: '2.00', total: '12.00' },
+ promotional: { remaining: '0.00', used: '5.00', total: '5.00' },
+ }),
+ );
+ expect(totals!.total - totals!.used).toBeCloseTo(38.2 + 10 + 0, 9);
+ });
+
+ it('reports used / total for a top-up-only account whose plan pool is empty', () => {
+ // 从未订阅过的账号: server 侧 planTotal 恒为 null, 但该池 remaining 是 0,
+ // 兜底贡献 0, 不影响其余池的用量事实。
+ expect(
+ resolveCreditTotals(
+ usage({
+ plan: { remaining: '0', used: null, total: null },
+ purchased: { remaining: '583.00', used: '17.00', total: '600.00' },
+ promotional: { remaining: '0', used: '21.00', total: '21.00' },
+ }),
+ ),
+ ).toEqual({ used: 38, total: 621 });
+ });
+
+ it('never reports used above total, whichever branch each pool takes', () => {
+ // 「已用 > 总额」是绝不能出现的自相矛盾。不变量的两个来源:
+ // 已知池 — server 用 used = total − remaining 反推且只在非负时返回值
+ // (nonNegativeDifference), 所以 used ≤ total;
+ // 兜底池 — used 记 0、total 记 remaining(已校验非负)。
+ // 混合两种分支、以及 rollover 让余额超过当期发放量(此时 server 返 null,
+ // 该池落到兜底分支)都要满足。
+ const cases: Partial<Record<'plan' | 'purchased' | 'promotional', Pool>>[] = [
+ {
+ // 订阅生效中: 三池用量全已知, plan 几乎花光
+ plan: { remaining: '90.68', used: '909.32', total: '1000.00' },
+ purchased: { remaining: '583.00', used: '0.00', total: '583.00' },
+ promotional: { remaining: '11.68', used: '9.32', total: '21.00' },
+ },
+ {
+ // 订阅过期: plan 用量转 null, 只剩余额可依
+ plan: { remaining: '1000.00', used: null, total: null },
+ purchased: { remaining: '583.00', used: '0.00', total: '583.00' },
+ promotional: { remaining: '11.68', used: '9.32', total: '21.00' },
+ },
+ {
+ // rollover 让 plan 余额超过当期发放量 → server 侧 used 为负, 返 null
+ plan: { remaining: '1500.00', used: null, total: null },
+ purchased: { remaining: '0.00', used: '600.00', total: '600.00' },
+ promotional: { remaining: '0', used: null, total: null },
+ },
+ ];
+ for (const pools of cases) {
+ const totals = resolveCreditTotals(usage(pools));
+ expect(totals).not.toBeNull();
+ expect(totals!.used).toBeLessThanOrEqual(totals!.total);
+ }
+ });
+
+ it('returns null when the account has no credits at all', () => {
+ expect(resolveCreditTotals(usage({}))).toBeNull();
+ });
+
+ it('returns null when totals are zero even though every pool is known', () => {
+ expect(
+ resolveCreditTotals(usage({ plan: { remaining: '0', used: '0', total: '0' } })),
+ ).toBeNull();
+ });
+
+ it('returns null on a malformed pool amount rather than partially summing', () => {
+ expect(
+ resolveCreditTotals(
+ usage({
+ plan: { remaining: '38.20', used: '11.80', total: '50.00' },
+ purchased: { remaining: '1', used: 'not-a-number', total: '12.00' },
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ it('returns null on a malformed remaining amount of an unknown-history pool', () => {
+ expect(
+ resolveCreditTotals(usage({ plan: { remaining: 'N/A', used: null, total: null } })),
+ ).toBeNull();
+ });
+
+ it('returns null for a negative ledger amount', () => {
+ expect(
+ resolveCreditTotals(usage({ plan: { remaining: '0', used: '-1.00', total: '50.00' } })),
+ ).toBeNull();
+ });
+
+ it('returns null instead of silently losing precision beyond the safe integer range', () => {
+ // 账本允许 10 位整数 + 9 位小数,汇总后的 ledger units 能超过 Number.MAX_SAFE_INTEGER。
+ // 那时转 number 会静默丢精度,破坏"全程 BigInt 不丢精度"的保证 —— 宁可整条不展示。
+ expect(
+ resolveCreditTotals(
+ usage({
+ plan: { remaining: '0', used: '9999999999', total: '9999999999' },
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ it('returns null when there is no usage snapshot', () => {
+ expect(resolveCreditTotals(null)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts b/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts
index 3d2845d366..7923be9ef5 100644
--- a/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts
+++ b/apps/desktop/src/renderer/__tests__/homeUsageDashboardSource.test.ts
@@ -19,7 +19,7 @@ const heatmapSource = readFileSync(
describe('HomeUsageDashboard source contract', () => {
it('uses the Claude account daily spend for the visible today amount when available', () => {
expect(source).toMatch(
- /const accountTodayMoney =\s+typeof claudeQuota\?\.todaySpend === 'number'\s+\? gatewayMoney\(claudeQuota\.todaySpend\)\s+: null;/,
+ /const accountTodayMoney =\s+typeof claudeQuota\?\.todaySpend === 'number'\s+\? gatewayMoney\(claudeQuota\.todaySpend, claudeQuota\.currency\)\s+: null;/,
);
expect(source).toContain('const hasAccountTodaySpend = accountTodayMoney !== null;');
expect(source).toContain('const layoutHistory = history ?? emptyLayoutHistory;');
diff --git a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
index 7b8d012359..c3e61273f0 100644
--- a/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
+++ b/apps/desktop/src/renderer/__tests__/todaySpendChip.test.ts
@@ -47,21 +47,19 @@ describe('TodaySpendChip dashboard routing', () => {
expect(source).toContain('todaySpend.openCodexUsage');
expect(source).toContain('todaySpend.openXaiUsage');
expect(source).toContain('todaySpend.openClaudeUsage');
- // codex 'api' 模式走 AI Gateway: 与 cc(非订阅 bridge)同用 cost metric, 复用同一把 XD key 的 quota
- expect(source).toContain(
- "((vendorKey === 'cc' && !isClaudeSubscription && !isSubscriptionBridge && !ccBillingFormPending) || isCodexApi)",
- );
+ // 只有实际 Gateway 会话读取 Model Access quota;自定义供应商只保留本会话统计。
+ expect(source).toContain('const usesGatewayQuota = isClaudeGateway || isCodexGateway;');
+ expect(source).toContain('useClaudeAccountUsage(usesGatewayQuota)');
});
it('treats cc + chatgpt/ / xai/ bridge sessions as subscription usage (no gateway quota / spend)', () => {
expect(source).toContain('modelId.startsWith(CHATGPT_MODEL_PREFIX)');
expect(source).toContain('modelId.startsWith(XAI_MODEL_PREFIX)');
expect(source).toContain('const isSubscriptionBridge = isChatgptBridge || isXaiBridge;');
- // gateway quota 对订阅 bridge 会话关闭;device-link 远程同样不读本机网关配额
- expect(source).toContain(
- "(((vendorKey === 'cc' && !isClaudeSubscription && !isSubscriptionBridge && !ccBillingFormPending) || isCodexApi)",
- );
- expect(source).toContain('&& !isDeviceLinkRemote),');
+ // bridge 只在匹配其内建来源时成立;显式自定义供应商优先于模型前缀。
+ expect(source).toContain("(providerId == null || providerId === 'openai')");
+ expect(source).toContain("(providerId == null || providerId === 'xai')");
+ expect(source).toContain('useClaudeAccountUsage(usesGatewayQuota)');
// chatgpt bridge 复用 codex 订阅 chip 形态;xai bridge / codex xai model 走价值估算 + 尽力限流 tooltip
expect(source).toContain('const usesCodexQuotaForm = isCodexOauth || isChatgptBridge;');
expect(source).toContain('const usesXaiQuotaForm = isCodexXaiProvider || isXaiBridge;');
@@ -79,9 +77,9 @@ describe('TodaySpendChip dashboard routing', () => {
expect(source).toContain("codexAuthInjection === 'oauth-bearer'");
expect(source).toContain("vendorKey === 'codex' && !isCodexXaiProvider");
expect(source).toContain("isRemoteCodexSession ||");
- expect(source).toContain("(codexAuthInjection === 'oauth-bearer' && !isCodexBudgetModel && providerId !== 'xd')");
- expect(source).toContain("vendorKey === 'codex' && typeof modelId === 'string' && modelId.startsWith(XAI_MODEL_PREFIX)");
- expect(source).not.toContain("providerId === 'xai'");
+ expect(source).toContain("(providerId == null || providerId === 'openai')");
+ expect(source).toContain('modelId.startsWith(XAI_MODEL_PREFIX)');
+ expect(source).toContain("providerId === 'xai'");
expect(source).toContain('const isCodexSubscription = isCodexOauth || isCodexXaiProvider;');
expect(source).toContain("const isCodexApi = vendorKey === 'codex' && !isCodexSubscription");
expect(source).not.toContain("codexAuthState.authSource === 'oauth'");
@@ -193,10 +191,10 @@ describe('TodaySpendChip dashboard routing', () => {
it('formats gateway quota amounts with the gateway-native currency', () => {
expect(source).toContain(
- 'formatCompactMoney(gatewayMoney(claudeQuota.spend))',
+ 'formatCompactMoney(gatewayMoney(claudeQuota.spend, claudeQuota.currency))',
);
expect(source).toContain(
- 'formatCompactMoney(gatewayMoney(claudeQuota.maxBudget))',
+ 'formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, claudeQuota.currency))',
);
expect(source).not.toContain('formatCompactUsd(claudeQuota.');
});
@@ -249,8 +247,11 @@ describe('TodaySpendChip dashboard routing', () => {
"status === 'allowed_warning' || hasAlertingClaudeSessionWindow(snapshot, modelId)",
);
// Claude 订阅 / bridge 订阅不读 gateway quota (不反映订阅花费); 默认路由 key reconcile
- // 完成前形态未定, 同样不放行网关 quota 读 (避免形态闪切)
- expect(source).toContain("vendorKey === 'cc' && !isClaudeSubscription && !isSubscriptionBridge && !ccBillingFormPending");
+ // 完成前形态未定, 同样不放行网关 quota 读 (避免形态闪切)。这些前置条件收敛到
+ // isClaudeGateway 里, 由 usesGatewayQuota 统一放行 quota 读取。
+ expect(source).toMatch(
+ /const isClaudeGateway =\s*vendorKey === 'cc'\s*&& !isAnyRemoteSession\s*&& !isSubscriptionBridge\s*&& !ccBillingFormPending/,
+ );
// 远端 Claude 会话恒走网关, 不显示本机订阅余量 (与 Codex 远端口径一致)
expect(source).toContain("const isRemoteClaudeSession = vendorKey === 'cc' && Boolean(remoteHostId);");
// 订阅判定: 显式选 Anthropic; 默认路由优先用 proxy 观察到的会话生效路由
@@ -374,8 +375,9 @@ describe('TodaySpendChip dashboard routing', () => {
expect(source).toContain('if (!usageDashboardUrl) return;');
// tooltip "打开看板" 行经 helper 统一追加,label 为 null(网关账号)时不追加。
expect(source).toContain('function pushDashboardLinkLine(lines: string[], label: string | null)');
- // 网关账号仍展示 daily/session 指标 + tooltip(仅去掉"打开看板"链接行)。
- expect(source).toContain("const PRIMARY_GATEWAY_METRICS: readonly MetricKey[] = ['daily', 'session']");
+ // 网关账号仍展示 daily/credit/session 指标 + tooltip(仅去掉"打开看板"链接行)。
+ // credit 段服务个人租户的三池账本(LiteLLM 语义的 daily/monthly 对它恒不可用)。
+ expect(source).toContain("const PRIMARY_GATEWAY_METRICS: readonly MetricKey[] = ['daily', 'credit', 'session']");
expect(source).toContain('const chipSegments = getGatewayChipSegments(slots)');
expect(source).toContain("t('todaySpend.dailyLimitLabel'");
expect(source).toContain('pushSessionUsageLines(tooltipLines, sessionUsage, null, t)');
diff --git a/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx b/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx
index 2d076f4b16..f5795b6195 100644
--- a/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx
@@ -188,7 +188,7 @@ export function HomeUsageDashboard(): React.JSX.Element {
const accountTodayMoney =
typeof claudeQuota?.todaySpend === 'number'
- ? gatewayMoney(claudeQuota.todaySpend)
+ ? gatewayMoney(claudeQuota.todaySpend, claudeQuota.currency)
: null;
const hasAccountTodaySpend = accountTodayMoney !== null;
@@ -199,9 +199,9 @@ export function HomeUsageDashboard(): React.JSX.Element {
isSameDisplayedTodaySpend(accountTodayMoney, layoutHistory.totals.today);
const softDailyLimit = hasMonthly ? (claudeQuota.maxBudget / 30) * DAILY_SOFT_LIMIT_FACTOR : null;
const softDailyLimitMoney =
- softDailyLimit === null
+ softDailyLimit === null || claudeQuota === null
? null
- : gatewayMoney(softDailyLimit);
+ : gatewayMoney(softDailyLimit, claudeQuota.currency);
const todayValue = !hasSpendValue
? UNKNOWN_VALUE
: softDailyLimitMoney
@@ -352,7 +352,7 @@ export function HomeUsageDashboard(): React.JSX.Element {
<StatCell
value={
hasMonthly
- ? `${formatCompactMoney(gatewayMoney(claudeQuota.spend))} / ${formatCompactMoney(gatewayMoney(claudeQuota.maxBudget))}`
+ ? `${formatCompactMoney(gatewayMoney(claudeQuota.spend, claudeQuota.currency))} / ${formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, claudeQuota.currency))}`
: `${UNKNOWN_VALUE} / ${UNKNOWN_VALUE}`
}
label={t('usageDashboard.monthly')}
diff --git a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
index d353fb5171..10b8b538c7 100644
--- a/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
+++ b/apps/desktop/src/renderer/components/status/TodaySpendChip.tsx
@@ -66,6 +66,8 @@ import {
useClaudeAccountUsage,
type ClaudeAccountUsageSnapshot,
} from '@/hooks/useClaudeAccountUsage';
+import { useModelAccessCreditUsage } from '@/hooks/useModelAccessCreditUsage';
+import { resolveCreditTotals, type CreditTotals } from '@/lib/creditPoolTotals';
import {
requestClaudeSubscriptionRefresh,
useClaudeSubscriptionUsage,
@@ -108,9 +110,12 @@ const CODEX_USAGE_DASHBOARD_URL = 'https://chatgpt.com/codex/settings/usage';
const XAI_ACCOUNT_URL = 'https://accounts.x.ai';
const CLAUDE_USAGE_DASHBOARD_URL = 'https://claude.ai/settings/usage';
-const METRIC_KEYS = ['daily', 'monthly', 'session'] as const;
+const METRIC_KEYS = ['daily', 'monthly', 'credit', 'session'] as const;
type MetricKey = (typeof METRIC_KEYS)[number];
-const PRIMARY_GATEWAY_METRICS: readonly MetricKey[] = ['daily', 'session'];
+// credit 排在 session 左边 —— 账号额度是"还能用多少"的前提, 本对话花费是它的增量。
+// daily / monthly 与 credit 来自服务端两种不同的额度语义(周期配额 vs 额度池账本),
+// 按账号所属租户二选一下发, 两组互斥, 同一形态下不会都占位。
+const PRIMARY_GATEWAY_METRICS: readonly MetricKey[] = ['daily', 'credit', 'session'];
const DAY_MS = 24 * 60 * 60 * 1000;
const DEFAULT_MONEY_SYMBOL = DEFAULT_USAGE_CURRENCY === 'CNY' ? '¥' : '$';
const DEFAULT_MONEY_PLACEHOLDER = `${DEFAULT_MONEY_SYMBOL}—`;
@@ -143,29 +148,49 @@ interface MetricSlot {
}
/**
- * 把 4 个候选 metric 一次性算好 (label + 是否可用)。
- * - daily / monthly: 需 claudeQuota 在线; 否则 available=false (整段隐藏)
+ * 把候选 metric 一次性算好 (label + 是否可用)。
+ * - daily / monthly: 需 claudeQuota 在线 (LiteLLM 语义租户); 否则 available=false
+ * - credit: 需三池账本汇总出非零总额 (个人租户); 否则 available=false
* - session: 需 sessionCostUsd > 0; 否则 available=false
*
* chip 段 / tooltip 段都从这里拿, 主显指标固定, 其它可用指标进 tooltip。
*/
function computeMetricSlots(
claudeQuota: ClaudeAccountUsageSnapshot | null,
+ creditTotals: CreditTotals | null,
sessionMoney: RegionalMoney | null,
t: TFunction,
): Record<MetricKey, MetricSlot> {
const slots: Record<MetricKey, MetricSlot> = {
daily: { label: t('todaySpend.dailyLimitLabel', { spend: DEFAULT_MONEY_PLACEHOLDER, limit: DEFAULT_MONEY_PLACEHOLDER }), available: false },
monthly: { label: t('todaySpend.monthlyLimitLabel', { spend: DEFAULT_MONEY_PLACEHOLDER, limit: DEFAULT_MONEY_PLACEHOLDER }), available: false },
+ credit: { label: t('todaySpend.creditLabel', { used: DEFAULT_MONEY_PLACEHOLDER, total: DEFAULT_MONEY_PLACEHOLDER }), available: false },
session: { label: t('todaySpend.sessionCostLabel', { cost: DEFAULT_MONEY_PLACEHOLDER }), available: false },
};
+ // 额度池账本没有周期概念(订阅发放 + 充值 + 赠送), 所以不派生日均软限额。
+ // 账本历史缺失的池按余额兜底(见 resolveCreditTotals), 保证「总额 − 已用」恒等于
+ // 设置页那个可用余额, chip 上永远是两个数、不退化成单值。
+ //
+ // 币种走 gatewayMoney 的默认值(DEFAULT_USAGE_CURRENCY = 按发行区域)。这三池是
+ // Cindy 自己的计费账本, 与账单页 BILLING_CURRENCY 同一笔钱、必须同口径 —— 不能
+ // 改用 Gateway 目录下发的币种, 否则同一笔余额在两个界面显示成不同货币。
+ if (creditTotals) {
+ const used = formatCompactMoney(gatewayMoney(creditTotals.used));
+ const total = formatCompactMoney(gatewayMoney(creditTotals.total));
+ slots.credit = {
+ label: t('todaySpend.creditLabel', { used, total }),
+ tooltipLabel: t('todaySpend.tooltip.creditUsed', { used, total }),
+ available: true,
+ };
+ }
+
if (claudeQuota && claudeQuota.maxBudget > 0) {
// monthly 永远跟 cycle 一起拿到; daily 走单独 endpoint 可能拉不到 (todaySpend=null) → 隐藏
slots.monthly = {
label: t('todaySpend.monthlyLimitLabel', {
- spend: formatCompactMoney(gatewayMoney(claudeQuota.spend)),
- limit: formatCompactMoney(gatewayMoney(claudeQuota.maxBudget)),
+ spend: formatCompactMoney(gatewayMoney(claudeQuota.spend, claudeQuota.currency)),
+ limit: formatCompactMoney(gatewayMoney(claudeQuota.maxBudget, claudeQuota.currency)),
}),
available: true,
};
@@ -174,9 +199,9 @@ function computeMetricSlots(
slots.daily = {
label: t('todaySpend.dailyLimitLabel', {
spend: formatCompactMoney(
- gatewayMoney(claudeQuota.todaySpend),
+ gatewayMoney(claudeQuota.todaySpend, claudeQuota.currency),
),
- limit: formatCompactMoney(gatewayMoney(softLimit)),
+ limit: formatCompactMoney(gatewayMoney(softLimit, claudeQuota.currency)),
}),
available: true,
};
@@ -1038,8 +1063,7 @@ export function TodaySpendChip({
// 自带跨实例广播 + auth-change 刷新)。无观察值且 key reconcile / OAuth 首查未完成
// 时默认路由形态未定 —— 不判订阅也不放行网关 quota 读, 避免 chip 先按一种形态
// 渲染再闪切(规则 7)。
- // 远端 Claude 会话恒走网关(runtime-configs 的 remoteEndpoint),本机订阅快照与实际
- // 服务账号无关 —— 排除出订阅形态,回落 gateway quota 展示(与 Codex 远端口径一致)。
+ // 远端 Claude 会话的额度事实在远端,本机订阅 / Gateway 快照都不能用于展示。
const isRemoteClaudeSession = vendorKey === 'cc' && Boolean(remoteHostId);
// device-link 远程会话不参与默认路由观察:本机 proxy 永远看不到被控端会话的请求,
// 用本机 OAuth / 网关 key 状态推断只会张冠李戴(形态由下方 device-link 专属分支接管)。
@@ -1064,21 +1088,35 @@ export function TodaySpendChip({
// - xai/ → SuperGrok 无订阅窗口端点,尽力显示 bridge 抓到的限流头,否则仅价值估算。
// 优先级高于 Claude 订阅形态(model 前缀决定实际消耗的额度)。
const isChatgptBridge =
- vendorKey === 'cc' && typeof modelId === 'string' && modelId.startsWith(CHATGPT_MODEL_PREFIX);
+ vendorKey === 'cc'
+ && (providerId == null || providerId === 'openai')
+ && typeof modelId === 'string'
+ && modelId.startsWith(CHATGPT_MODEL_PREFIX);
const isXaiBridge =
- vendorKey === 'cc' && typeof modelId === 'string' && modelId.startsWith(XAI_MODEL_PREFIX);
+ vendorKey === 'cc'
+ && (providerId == null || providerId === 'xai')
+ && typeof modelId === 'string'
+ && modelId.startsWith(XAI_MODEL_PREFIX);
const isSubscriptionBridge = isChatgptBridge || isXaiBridge;
const isRemoteCodexSession = vendorKey === 'codex' && Boolean(remoteHostId);
const isCodexBudgetModel = typeof modelId === 'string' && modelId.startsWith('codex/');
+ const isCodexGatewayBudgetModel =
+ isCodexBudgetModel && (providerId == null || providerId === 'xd');
const isCodexXaiProvider =
- vendorKey === 'codex' && typeof modelId === 'string' && modelId.startsWith(XAI_MODEL_PREFIX);
- // codex 走订阅价值估算:ChatGPT 订阅需要 oauth-bearer 且未显式选 XD;xAI 由 proxy 注入
- // SuperGrok OAuth,不依赖 Codex 子进程凭证。env-key fallback、codex/ 折扣、或显式选 XD
- // → 复用 cc 的 cost tooltip 形态。远端 Codex 的事实在远端 daemon 上,本机只记录 token
- // 价值估算,不写本地 gateway cost。
+ vendorKey === 'codex'
+ && (providerId == null || providerId === 'xai')
+ && typeof modelId === 'string'
+ && modelId.startsWith(XAI_MODEL_PREFIX);
+ // codex 走订阅价值估算:ChatGPT 订阅需要 oauth-bearer + OpenAI 来源;xAI 由 proxy 注入
+ // SuperGrok OAuth。显式自定义供应商优先于共享 host 的 authInjection 和模型名前缀。
+ // 远端 Codex 的事实在远端 daemon 上,本机只记录 token 价值估算,不写本地 gateway cost。
const isCodexOauth = vendorKey === 'codex' && !isCodexXaiProvider && (
isRemoteCodexSession ||
- (codexAuthInjection === 'oauth-bearer' && !isCodexBudgetModel && providerId !== 'xd')
+ (
+ codexAuthInjection === 'oauth-bearer'
+ && !isCodexGatewayBudgetModel
+ && (providerId == null || providerId === 'openai')
+ )
);
const isCodexSubscription = isCodexOauth || isCodexXaiProvider;
const isCodexApi = vendorKey === 'codex' && !isCodexSubscription;
@@ -1088,10 +1126,40 @@ export function TodaySpendChip({
// 远程会话不读本机账户快照 —— 额度事实在远端:SSH 用 remoteHostId 判,device-link 用
// deviceLinkDeviceId 判(两者互斥,任一非空即远程,turn 消耗的是远端账号的额度)。
const isAnyRemoteSession = Boolean(remoteHostId) || Boolean(deviceLinkDeviceId);
- // Claude 网关/订阅配额的本地读取只对 device-link 加门(isDeviceLinkRemote,声明在组件
- // 顶部):SSH 远程 cc 维持既有口径(isRemoteClaudeSession 已排除订阅形态、回落 gateway
- // quota 展示);device-link 的 turn 与凭证都在被控端,控制端本机的 LiteLLM / Claude.ai
- // 配额与之无关。
+ // Model Access 配额只属于实际走 XD/Cindy AI Gateway 的本地会话。显式自定义供应商即使
+ // 复用了 env-key / oauth-bearer host,也不能据 host 的启动凭证把 /v2/user/info 串进来。
+ const isClaudeGateway =
+ vendorKey === 'cc'
+ && !isAnyRemoteSession
+ && !isSubscriptionBridge
+ && !ccBillingFormPending
+ && (
+ providerId === 'xd'
+ || (
+ providerId == null
+ && (
+ observedClaudeRoute != null
+ ? observedClaudeRoute === 'gateway'
+ : !gatewayKeyReconciling && hasGatewayKey
+ )
+ )
+ );
+ const isCodexGateway =
+ vendorKey === 'codex'
+ && !isAnyRemoteSession
+ && !isCodexSubscription
+ && (
+ providerId === 'xd'
+ || (
+ providerId == null
+ && (
+ codexAuthInjection === 'env-key'
+ || isCodexGatewayBudgetModel
+ || (codexAuthInjection === 'provider-oauth' && hasGatewayKey)
+ )
+ )
+ );
+ const usesGatewayQuota = isClaudeGateway || isCodexGateway;
const shouldReadLocalCodexAccountUsage = usesCodexQuotaForm && !isAnyRemoteSession;
// 会话金额只由已发生的 turn 决定,不由当前选中的 provider/模型决定。实际费用从
// session ledger 读取,订阅价值从消息明细重建,再统一汇总成“本对话”投影。
@@ -1124,13 +1192,13 @@ export function TodaySpendChip({
} = useCodexRateLimits(isCodexOauth && !isAnyRemoteSession);
// xAI 限流快照同为本机 main 抓的 —— 远程会话(SSH / device-link)同样抑制,回落价值估算。
const xaiRateLimit = useXaiRateLimit(usesXaiQuotaForm && !isAnyRemoteSession);
- // cc 与 codex-api 共用同一把 XD gateway key 的 LiteLLM quota; codex-oauth 不订阅。
- // cc 走订阅(Anthropic / bridge 模型)同样不读 gateway quota —— 它不反映用户的订阅花费(见上);
- // 默认路由在 key reconcile 完成前形态未定, 同样先不读(几 ms 后判定落定, 避免形态闪切)。
- const claudeQuota = useClaudeAccountUsage(
- (((vendorKey === 'cc' && !isClaudeSubscription && !isSubscriptionBridge && !ccBillingFormPending) || isCodexApi)
- && !isDeviceLinkRemote),
- );
+ // 只有实际 Gateway 会话读取同一把 XD key 的 LiteLLM quota。订阅与自定义供应商
+ // 均只展示各自的额度/本地会话统计,不读取 Model Access 账号配额。
+ const claudeQuota = useClaudeAccountUsage(usesGatewayQuota);
+ // 个人租户的额度事实在 Gateway 三池账本里(推理入口不提供管理面接口), 与上面的
+ // LiteLLM quota 是两种租户的两种语义, 各自拿不到就各自隐藏 —— 不互相兜底。
+ const creditUsage = useModelAccessCreditUsage(usesGatewayQuota);
+ const creditTotals = React.useMemo(() => resolveCreditTotals(creditUsage), [creditUsage]);
// Claude 订阅账号余量 (5h/周/分模型窗口, 端点 + proxy 旁路 headers 双源)。bridge 模型形态
// 优先(不消耗 Claude 订阅额度),此时不读。
const claudeSubscriptionUsage = useClaudeSubscriptionUsage(
@@ -1353,7 +1421,7 @@ export function TodaySpendChip({
latestTurnUsage,
);
} else {
- const slots = computeMetricSlots(claudeQuota, sessionMoney, t);
+ const slots = computeMetricSlots(claudeQuota, creditTotals, sessionMoney, t);
const chipSegments = getGatewayChipSegments(slots);
const codexApiHasTokenFallback = isCodexApi
&& !slots.session.available
@@ -1376,9 +1444,11 @@ export function TodaySpendChip({
const tooltipLines: string[] = [];
// server-side endpoint 独立可能失败, 各自挂掉时都加一行 ⚠️ 提示, 让用户知道
// 那段是端点降级而非数据为 0
- if (!claudeQuota) {
+ // 个人租户没有"月度配额"这回事(三池账本是买断 + 赠送制), 拿到 credit 就不该再
+ // 提示月度降级 —— 只有两种语义都拿不到(未开户 / 网关不可用)才是真降级。
+ if (usesGatewayQuota && !claudeQuota && !creditTotals) {
tooltipLines.push(t('todaySpend.tooltip.monthlyUnavailable'));
- } else if (claudeQuota.todaySpend === null) {
+ } else if (claudeQuota?.todaySpend === null) {
tooltipLines.push(t('todaySpend.tooltip.dailyUnavailable'));
}
if (slots.session.available) {
diff --git a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
index ff32743f2b..de1e1e4348 100644
--- a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
+++ b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts
@@ -21,17 +21,21 @@
*
* enabled 语义 (而非 vendorKey): 这份 quota 是"XD gateway key 在 LiteLLM 上的 spend",
* 与发起请求的 agent 无关。cc 固然要看; codex 的 'api' 鉴权模式复用同一把 XD key 走
- * 同一个 AI Gateway, 所以也该看同一份 quota。调用方据此决定 enabled (cc || codex-api),
- * 本 hook 不感知 vendor。
+ * 同一个 AI Gateway, 所以也该看同一份 quota。调用方只在当前会话实际走 Gateway 时
+ * 启用;自定义供应商即使复用相同 host 也不会读这份账号配额。
*/
import { useEffect, useState } from 'react';
+import type { MoneyCurrency } from '../../shared/regionalMoney';
+
export interface ClaudeAccountUsageSnapshot {
/** 月度周期跨客户端累计,保持 Gateway 部署区域的原生金额。 */
spend: number;
/** 月度周期上限,保持 Gateway 部署区域的原生金额。 */
maxBudget: number;
+ /** Gateway 账号金额的原生币种。 */
+ currency: MoneyCurrency;
/** 下次月度 reset 时间 ISO8601。 */
budgetResetAt?: string | null;
/**
@@ -53,6 +57,7 @@ function isSnapshot(v: unknown): v is ClaudeAccountUsageSnapshot {
typeof r.spend === 'number' &&
typeof r.maxBudget === 'number' &&
r.maxBudget > 0 &&
+ (r.currency === 'CNY' || r.currency === 'USD') &&
(typeof r.todaySpend === 'number' || r.todaySpend === null)
);
}
diff --git a/apps/desktop/src/renderer/hooks/useModelAccessCreditUsage.ts b/apps/desktop/src/renderer/hooks/useModelAccessCreditUsage.ts
new file mode 100644
index 0000000000..15bad86e54
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useModelAccessCreditUsage.ts
@@ -0,0 +1,118 @@
+/**
+ * useModelAccessCreditUsage — 订阅当前账号的额度池账本
+ * (订阅 / 充值 / 赠送三池的 remaining / used / total)。
+ *
+ * 为什么不复用 useClaudeAccountUsage:
+ * 两者是**两种不同的额度语义**,不是同一份数据的两个入口。服务端按账号所属租户
+ * 二选一提供:
+ * - 周期配额语义(spend / max_budget,有月度周期):由 useClaudeAccountUsage
+ * 直接向推理入口查询。
+ * - 额度池账本语义(三池,发放 + 充值 + 赠送制,没有周期):推理入口不提供该查询,
+ * 只能经服务端的 /api/model-access/credit-usage 拿 —— 即本 hook。
+ *
+ * 数据通道: billingApi.getCreditUsage() → IPC billing:get-credit-usage
+ * → main/billing GET /api/model-access/credit-usage。是 invoke 拉取,没有 push 通道。
+ *
+ * 刷新: mount 拉一次 + enabled 期间定时轮询。额度只在跑 turn 后变化,轮询周期取
+ * 得比较松 —— 这是状态栏的辅助信息,不值得为它加高频请求。
+ *
+ * 失败一律返 null (消费方隐藏该指标,不显示会误导的 0):
+ * - 账号所属租户不提供该查询 → 服务端返回 BALANCE_NOT_SUPPORTED
+ * - 账号尚未开户 / 上游不可用 / 网络失败
+ *
+ * module-local cache 让切换会话时 chip 不闪空 (与 useClaudeAccountUsage 同做法)。
+ */
+
+import { useEffect, useState } from 'react';
+
+import type { ModelAccessCreditUsage } from '../../shared/modelAccess';
+import { billingApi } from '../features/billing/api';
+import { useAuth } from '../contexts/AuthContext';
+
+/** 额度变化只跟 turn 走,状态栏辅助信息不值得高频拉取。 */
+const REFRESH_INTERVAL_MS = 60_000;
+
+/**
+ * 防闪烁缓存,**按账号绑定**。
+ *
+ * 额度是财务数据,缓存必须跟着账号走:同一个 renderer 生命周期内可以登出再登录另一个
+ * 账号,若缓存不绑身份,新账号在自己的请求返回前会看到上一个账号的已用 / 总额;而下面
+ * 的 catch 又刻意保留旧值(避免网络抖动清空),新账号不支持该查询或请求失败时这个错值
+ * 会一直挂着。所以缓存连同当前账号 id 一起存,账号不匹配时视为无缓存。
+ *
+ * 本 hook 走 invoke 拉取、没有 main→renderer 的推送通道,不像 useClaudeAccountUsage
+ * 那样会被新账号的广播覆盖,因此必须自己做这层隔离。
+ */
+interface CreditUsageSnapshot {
+ accountId: string;
+ usage: ModelAccessCreditUsage;
+}
+
+let cache: CreditUsageSnapshot | null = null;
+
+function readCache(accountId: string | null): CreditUsageSnapshot | null {
+ if (!accountId || cache?.accountId !== accountId) return null;
+ return cache;
+}
+
+function isCreditPool(v: unknown): boolean {
+ if (!v || typeof v !== 'object') return false;
+ const pool = v as { remaining?: unknown; used?: unknown; total?: unknown };
+ return (
+ typeof pool.remaining === 'string' &&
+ (typeof pool.used === 'string' || pool.used === null) &&
+ (typeof pool.total === 'string' || pool.total === null)
+ );
+}
+
+function isCreditUsage(v: unknown): v is ModelAccessCreditUsage {
+ if (!v || typeof v !== 'object') return false;
+ const r = v as Partial<ModelAccessCreditUsage>;
+ return (
+ typeof r.available === 'string' &&
+ isCreditPool(r.plan) &&
+ isCreditPool(r.purchased) &&
+ isCreditPool(r.promotional)
+ );
+}
+
+export function useModelAccessCreditUsage(
+ enabled: boolean,
+): ModelAccessCreditUsage | null {
+ const { dataOwnerId } = useAuth();
+ // state 连账号 id 一起存,隔离在**渲染期**完成而不是 effect 里:effect 要等本轮渲染
+ // 提交后才执行,靠它清空会让切号后的首帧仍把上一个账号的额度渲染出去。
+ const [snapshot, setSnapshot] = useState<CreditUsageSnapshot | null>(() =>
+ readCache(dataOwnerId),
+ );
+
+ useEffect(() => {
+ if (!enabled || !dataOwnerId) return;
+ let cancelled = false;
+
+ const load = () => {
+ void billingApi
+ .getCreditUsage()
+ .then((res) => {
+ if (cancelled) return;
+ if (!isCreditUsage(res)) return;
+ cache = { accountId: dataOwnerId, usage: res };
+ setSnapshot(cache);
+ })
+ .catch(() => {
+ /* 租户不提供该查询 / 未开户 / 上游不可用 → 保持本账号上一次值, 不清空 */
+ });
+ };
+
+ load();
+ const timer = setInterval(load, REFRESH_INTERVAL_MS);
+ return () => {
+ cancelled = true;
+ clearInterval(timer);
+ };
+ }, [enabled, dataOwnerId]);
+
+ // 账号不匹配 / 未启用 → 当作没有数据。切号当帧即生效。
+ if (!enabled || !dataOwnerId || snapshot?.accountId !== dataOwnerId) return null;
+ return snapshot.usage;
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 0d9288d224..abec4ece4c 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3561,6 +3561,7 @@
},
"dailyLimitLabel": "Today {{spend}}/{{limit}}",
"monthlyLimitLabel": "Cycle {{spend}}/{{limit}}",
+ "creditLabel": "{{used}}/{{total}}",
"sessionCostLabel": "Session {{cost}}",
"codex": {
"waiting": "Codex --",
@@ -3605,6 +3606,7 @@
"tooltip": {
"todayUsedSoftLimit": "Today used ${{today}} / soft limit ${{limit}} ({{pct}}%)",
"sessionUsed": "This session used {{cost}}",
+ "creditUsed": "Account used {{used}} · total {{total}}",
"monthlyUnavailable": "⚠️ Monthly quota is temporarily unavailable",
"dailyUnavailable": "⚠️ Today's usage details are temporarily unavailable",
"softLimitFormula": "Soft limit formula: monthly quota ÷ 30 × {{factor}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 30f9b701c9..d7db2fb122 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3560,6 +3560,7 @@
},
"dailyLimitLabel": "本日 {{spend}}/{{limit}}",
"monthlyLimitLabel": "周期 {{spend}}/{{limit}}",
+ "creditLabel": "{{used}}/{{total}}",
"sessionCostLabel": "セッション {{cost}}",
"codex": {
"waiting": "Codex --",
@@ -3604,6 +3605,7 @@
"tooltip": {
"todayUsedSoftLimit": "本日使用 ${{today}} / ソフト上限 ${{limit}} ({{pct}}%)",
"sessionUsed": "このセッションで {{cost}} 使用",
+ "creditUsed": "アカウント 使用 {{used}} · 合計 {{total}}",
"monthlyUnavailable": "⚠️ 月次クォータを一時的に取得できません",
"dailyUnavailable": "⚠️ 本日の使用量明細を一時的に取得できません",
"softLimitFormula": "ソフト上限の式: 月次クォータ ÷ 30 × {{factor}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 0d9dba4eda..d1d614c39a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3560,6 +3560,7 @@
},
"dailyLimitLabel": "오늘 {{spend}}/{{limit}}",
"monthlyLimitLabel": "주기 {{spend}}/{{limit}}",
+ "creditLabel": "{{used}}/{{total}}",
"sessionCostLabel": "세션 {{cost}}",
"codex": {
"waiting": "Codex --",
@@ -3604,6 +3605,7 @@
"tooltip": {
"todayUsedSoftLimit": "오늘 사용 ${{today}} / 소프트 한도 ${{limit}} ({{pct}}%)",
"sessionUsed": "이 세션에서 {{cost}} 사용",
+ "creditUsed": "계정 사용 {{used}} · 총액 {{total}}",
"monthlyUnavailable": "⚠️ 월간 할당량을 일시적으로 가져올 수 없습니다",
"dailyUnavailable": "⚠️ 오늘 사용량 세부 정보를 일시적으로 가져올 수 없습니다",
"softLimitFormula": "소프트 한도 공식: 월 할당량 ÷ 30 × {{factor}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 34821c307f..2b30ae259d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3560,6 +3560,7 @@
},
"dailyLimitLabel": "今日 {{spend}}/{{limit}}",
"monthlyLimitLabel": "本周期 {{spend}}/{{limit}}",
+ "creditLabel": "{{used}}/{{total}}",
"sessionCostLabel": "本对话 {{cost}}",
"codex": {
"waiting": "Codex --",
@@ -3604,6 +3605,7 @@
"tooltip": {
"todayUsedSoftLimit": "今日已用 ${{today}} / 软限额 ${{limit}} ({{pct}}%)",
"sessionUsed": "本对话已用 {{cost}}",
+ "creditUsed": "账号已用 {{used}} · 总额 {{total}}",
"monthlyUnavailable": "⚠️ 月度配额暂时不可用",
"dailyUnavailable": "⚠️ 今日用量明细暂时不可用",
"softLimitFormula": "软限额口径:月度配额 ÷ 30 × {{factor}}",
diff --git a/apps/desktop/src/renderer/lib/creditPoolTotals.ts b/apps/desktop/src/renderer/lib/creditPoolTotals.ts
new file mode 100644
index 0000000000..69843c6b53
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/creditPoolTotals.ts
@@ -0,0 +1,99 @@
+/**
+ * creditPoolTotals — 把 model-access credit-usage 的额度池账本压成一条
+ * 「已用 / 总额」,供右下角 chip 在 Cindy 网关形态下显示账号额度。
+ *
+ * 两类数据来源的可靠性不同,决定了未知池必须按余额兜底而不能跳过:
+ * - remaining / available: Gateway /balance 直接给的原值, Server 侧强校验过
+ * 「三池之和 === available」(见 gateway.ts normalizeBalance), 永远有值、永远自洽。
+ * - used / total: Server 从 credit events 事件流**反推**的 —— 翻不到当期 grant 事件
+ * 就是 null(订阅期末取消、从未订阅过、事件超过 pageSize 100 × MAX_PAGES 10 = 1000
+ * 条被截断), 见 modelAccessCreditUsage.ts 的 planTotal / purchasedTotal 分支。
+ *
+ * 未知池的处理:把它的 remaining 记作该池 total、已用记 0。这样
+ *
+ * Σtotal − Σused ≡ Σremaining ≡ available
+ *
+ * 恒成立 —— 因为已知池满足 total − used = remaining(Server 侧就是用
+ * `used = total − remaining` 反推的, 见 modelAccessCreditUsage.ts:81), 未知池按定义
+ * 也满足。于是 chip 上的两个数与设置页「可用余额」永远自洽。代价是未知池的已用被
+ * 计为 0(低估已用), 这是账本历史缺失的固有限制, 但不会让总额偏小。
+ *
+ * 绝不跳过未知池 —— 那会把该池余额从总额里抹掉(实测: 订阅池 ¥1000 未知时总额从
+ * ¥1594.68 掉成 ¥604), 与设置页自相矛盾。
+ *
+ * 账本金额是 scale=9 的十进制字符串, 汇总全程走 BigInt, 只在最后一步转成展示用的
+ * number —— 不让 float 参与加法。
+ */
+
+import type { ModelAccessCreditUsage } from '../../shared/modelAccess';
+
+/** 账本 scale=9:1 单位货币 = 1e9 ledger units。 */
+const LEDGER_SCALE = 1_000_000_000n;
+/** 与 BillingPage 的 ledgerUnits 同口径:整数部分 ≤10 位,小数 ≤9 位。 */
+const LEDGER_PATTERN = /^(-?)(0|[1-9]\d{0,9})(?:\.(\d{1,9}))?$/;
+
+/** 十进制账本字符串 → BigInt ledger units;格式不合法返 null。 */
+function ledgerUnits(value: string): bigint | null {
+ const match = LEDGER_PATTERN.exec(value.trim());
+ if (!match) return null;
+ const fraction = (match[3] ?? '').padEnd(9, '0');
+ const units = BigInt(match[2]) * LEDGER_SCALE + BigInt(fraction || '0');
+ return match[1] === '-' ? -units : units;
+}
+
+/**
+ * ledger units → 货币单位。
+ *
+ * 账本允许 10 位整数 + 9 位小数,汇总后的 units 理论上能超过 Number.MAX_SAFE_INTEGER
+ * (9e15),转 number 会静默丢精度、破坏本模块"全程 BigInt 不丢精度"的保证。超出安全范围
+ * 时返回 null,让调用方整条不展示,而不是给出一个悄悄错掉的金额。
+ */
+function toCurrency(units: bigint): number | null {
+ if (units > BigInt(Number.MAX_SAFE_INTEGER) || units < -BigInt(Number.MAX_SAFE_INTEGER)) {
+ return null;
+ }
+ return Number(units) / Number(LEDGER_SCALE);
+}
+
+export interface CreditTotals {
+ /** 能确证的已用之和,货币单位。历史缺失的池按 0 计。 */
+ used: number;
+ /** 总额之和,货币单位。历史缺失的池按其当前余额计。 */
+ total: number;
+}
+
+/**
+ * @returns null 表示没有可展示的额度事实 —— 无快照、金额格式非法(数据不可信,
+ * 整条不展示), 或总额为 0(未订阅且未充值)。
+ */
+export function resolveCreditTotals(
+ usage: ModelAccessCreditUsage | null,
+): CreditTotals | null {
+ if (!usage) return null;
+
+ let usedUnits = 0n;
+ let totalUnits = 0n;
+
+ for (const pool of [usage.plan, usage.purchased, usage.promotional]) {
+ if (pool.used === null || pool.total === null) {
+ // 账本历史推不出用量:按当前余额兜底(total = remaining, used = 0)。
+ // 空池(remaining = 0)自然贡献 0,无需特判。
+ const remaining = ledgerUnits(pool.remaining);
+ if (remaining === null || remaining < 0n) return null;
+ totalUnits += remaining;
+ continue;
+ }
+ const used = ledgerUnits(pool.used);
+ const total = ledgerUnits(pool.total);
+ // 单个池金额格式非法 → 整条不可信, 不做部分汇总
+ if (used === null || total === null || used < 0n || total < 0n) return null;
+ usedUnits += used;
+ totalUnits += total;
+ }
+
+ if (totalUnits === 0n) return null;
+ const used = toCurrency(usedUnits);
+ const total = toCurrency(totalUnits);
+ if (used === null || total === null) return null;
+ return { used, total };
+}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index d1c150e453..5e5ce26e4b 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4600,6 +4600,7 @@ interface ElectronAPI {
cb: (p: {
spend: number;
maxBudget: number;
+ currency: import('../shared/regionalMoney').MoneyCurrency;
budgetResetAt?: string | null;
todaySpend: number | null;
fetchedAt: number;
diff --git a/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts b/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
index 515576dcd7..77a723d2e1 100644
--- a/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
+++ b/apps/desktop/src/shared/__tests__/modelPriceQuote.test.ts
@@ -16,13 +16,38 @@ function model(
}
describe('gatewayPricingCatalog', () => {
- it('keeps every priced CN Gateway model in the native CNY catalog', () => {
+ it('rejects the whole catalog when the Gateway declares mixed currencies', () => {
+ // 混币目录已被 resolveGatewayAccountCurrency 判定不可信(账本随之回退构建币种)。
+ // 若这里继续产出混币 catalog,非账本币种的那部分模型金额会被账本写入守卫选择性
+ // 丢弃,形成"按模型漏记账"——比整份没有报价更难发现。
+ expect(
+ gatewayPricingCatalog(
+ [model('a', { currency: 'CNY' }), model('b', { currency: 'USD' }), model('c')],
+ 'cn',
+ ),
+ ).toEqual({});
+ });
+
+ it('lets a single declared currency cover the models that omit it', () => {
+ // 同一账号的目录币种是统一的:省略 currency 的条目跟随同目录已声明的币种,
+ // 而不是各自回落构建区域(那会产出跨币种目录)。
const catalog = gatewayPricingCatalog(
- [model('a', { currency: 'CNY' }), model('b', { currency: 'USD' }), model('c')],
+ [model('a', { currency: 'USD' }), model('b')],
'cn',
);
- expect(Object.keys(catalog.xd)).toEqual(['a', 'b', 'c']);
- expect(Object.values(catalog.xd).map((quote) => quote.currency)).toEqual(['CNY', 'CNY', 'CNY']);
+ expect(Object.keys(catalog.xd ?? {})).toEqual(['a', 'b']);
+ expect(Object.values(catalog.xd ?? {}).map((quote) => quote.currency)).toEqual([
+ 'USD',
+ 'USD',
+ ]);
+ });
+
+ it('falls back to the build region only when no model declares a currency', () => {
+ const catalog = gatewayPricingCatalog([model('a'), model('b')], 'cn');
+ expect(Object.values(catalog.xd ?? {}).map((quote) => quote.currency)).toEqual([
+ 'CNY',
+ 'CNY',
+ ]);
});
it('carries Gateway costDiscount uniformly for ordinary and codex models', () => {
diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.ts
index 7f2b4fdd9b..f5899c8a40 100644
--- a/apps/desktop/src/shared/modelAccess.ts
+++ b/apps/desktop/src/shared/modelAccess.ts
@@ -84,10 +84,8 @@ export const MODEL_ACCESS_STATUS_CHANNEL = 'model-access:status-change';
/**
* 服务端下发的网关聊天模型条目(model-access-server GET /models):
- * AIGateway /model-groups 的 mode=chat 投影(存在性 + token 上限权威)+
- * 服务端内置常量表富化(agents/展示元数据)。XD 供应商模型列表的权威来源。
- * 客户端字段优先级:本条目 > 产品目录同 id 条目 > 合成默认
- * (active-catalog setXdGatewayModels)。
+ * 上游 model-groups 的公开字段 + 服务端生成的旧客户端兼容字段。
+ * 新字段优先转换为客户端 Catalog 能力;字段缺失时才回退兼容字段。
*/
/** 单个 runtime tab 上与基线不同的能力字段(服务端 perAgent 覆盖块,客户端按 agent 应用)。 */
export interface ModelAccessAgentOverride {
@@ -151,6 +149,18 @@ export interface ModelGroupPricing {
tieredPricing?: ModelGroupTieredPricing[];
}
+/**
+ * Model Access Server 下发的模型条目。
+ *
+ * 同一含义只有一个字段:Gateway 的能力字段(contextLength / maxInputTokens /
+ * supportedEndpoints / reasoning / supportsServiceTier / architecture)由服务端一次
+ * 归一化成这里的 contextWindow / agents / efforts + defaultEffort / supportsFastMode /
+ * modalities,上游原名字段不下发、客户端也不再二次转换(见 model-access/index.ts 的
+ * applyGatewayModels)。旧版服务端只给归一化字段,语义相同,故无需兼容分支。
+ *
+ * 其中 contextLength 与 maxInputTokens 在 Gateway 侧本就同值(文档:contextLength
+ * currently mirrors maxInputTokens),统一由 contextWindow 表达。
+ */
export interface ModelAccessGatewayModel extends ModelGroupPricing {
id: string;
/**
@@ -162,8 +172,9 @@ export interface ModelAccessGatewayModel extends ModelGroupPricing {
*/
mode?: string;
/**
- * Gateway 可选的币种声明。当前 Cindy AI 价格目录仍以构建 region 的渠道契约
- * 为准;该字段仅保留 wire 兼容,不能让同一构建产生混合币种目录。
+ * Gateway 原生价格币种,是该账号计价与记账的权威来源;旧版服务端未下发时才按
+ * 运行区域回退。它不保证等于构建区域 —— 结算币种由服务端按账号所属租户下发,
+ * 消费方一律以本字段(或其派生的 currentLedgerCurrency)为准,不按区域推断。
*/
currency?: 'USD' | 'CNY';
/** 进哪些 runtime tab;缺省 = 仅 claude-code(网关 /v1/messages 翻译覆盖面最广)。 */
@@ -173,6 +184,8 @@ export interface ModelAccessGatewayModel extends ModelGroupPricing {
description?: string;
contextWindow?: number;
maxOutputTokens?: number;
+ /** 输入 / 输出模态(服务端由 Gateway architecture 归一化而来)。 */
+ modalities?: { input: string[]; output: string[] };
efforts?: string[];
defaultEffort?: string | null;
sortOrder?: number;
diff --git a/apps/desktop/src/shared/modelPriceQuote.ts b/apps/desktop/src/shared/modelPriceQuote.ts
index fcde763d3d..7ff5ff6f90 100644
--- a/apps/desktop/src/shared/modelPriceQuote.ts
+++ b/apps/desktop/src/shared/modelPriceQuote.ts
@@ -7,6 +7,7 @@ import {
gatewayCurrencyForRegion,
type ModelPriceQuote,
type ModelPricingCatalog,
+ type MoneyCurrency,
} from './regionalMoney.js';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from './subscriptionModels.js';
@@ -39,19 +40,21 @@ function normalizedCostDiscount(value: unknown): number | undefined {
: undefined;
}
-/**
- * Cindy AI Gateway 的价格币种由构建 region 决定。CN /models 的数字原生是
- * CNY,Global 原生是 USD;条目缺少 currency 不改变该契约。
- */
+/** Gateway 原生币种优先;旧服务端未声明时才按构建 region 回退。 */
/** 该条目是否会产生报价(与币种无关;目录币种裁决与覆盖率统计共用此判定)。 */
export function isPricedGatewayModel(model: ModelAccessGatewayModel): boolean {
// 币种不影响“是否有价格”的判断,这里显式传值,避免计费 API 隐式回落 Global。
return gatewayModelPriceQuote(model, 'global') !== undefined;
}
+/**
+ * @param fallbackCurrency 该模型未声明 currency 时的回落币种。调用方(gatewayPricingCatalog)
+ * 会传同一目录里已声明的币种,让整份目录保持单一币种;缺省才按区域回落。
+ */
export function gatewayModelPriceQuote(
model: ModelAccessGatewayModel,
region: CindyRegion,
+ fallbackCurrency?: MoneyCurrency,
): ModelPriceQuote | undefined {
const modelId = model.id.trim();
const inputPerMtok = perMtok(model.inputCostPerToken);
@@ -75,7 +78,7 @@ export function gatewayModelPriceQuote(
return {
providerId: 'xd',
modelId,
- currency: gatewayCurrencyForRegion(region),
+ currency: model.currency ?? fallbackCurrency ?? gatewayCurrencyForRegion(region),
source: 'gateway',
approximate: false,
inputPerMtok,
@@ -90,9 +93,25 @@ export function gatewayPricingCatalog(
models: readonly ModelAccessGatewayModel[],
region: CindyRegion,
): ModelPricingCatalog {
+ // 整份目录必须是单一币种。
+ //
+ // 同一账号的目录币种本就统一,所以个别模型省略 currency 时跟随同目录已声明的币种,
+ // 而不是各自回落构建区域 —— 否则新旧字段混合的响应(一条声明 USD、一条省略)会产出
+ // 跨币种目录,那些回落成区域币种的模型金额会被账本写入守卫当异币种丢弃。
+ //
+ // 出现两种以上显式声明则整份拒绝:此时 resolveGatewayAccountCurrency 已判定该目录不可信
+ // 并让账本回退构建币种,若这里继续产出混币 catalog,非账本币种的那部分模型会被守卫
+ // 选择性丢弃 —— 形成"按模型漏记账",比整份没有报价更难发现。
+ const declared = new Set(
+ models
+ .map((model) => model.currency)
+ .filter((currency): currency is MoneyCurrency => currency === 'CNY' || currency === 'USD'),
+ );
+ if (declared.size > 1) return {};
+ const fallbackCurrency = declared.values().next().value ?? gatewayCurrencyForRegion(region);
const xd: Record<string, ModelPriceQuote> = {};
for (const model of models) {
- const quote = gatewayModelPriceQuote(model, region);
+ const quote = gatewayModelPriceQuote(model, region, fallbackCurrency);
if (quote) xd[quote.modelId] = quote;
}
return Object.keys(xd).length > 0 ? { xd } : {};
@@ -177,6 +196,25 @@ export function getModelPriceQuote(
);
}
+/**
+ * 从报价目录推断当前账号的 Gateway 结算币种。
+ *
+ * 结算币种由服务端按账号所属租户下发,不保证等于客户端发行区域:多数账号跟随区域
+ * (cn=CNY / global=USD),但也存在以 USD 结算的账号运行在 CN 构建上的正常情形。
+ * 所以凡是需要判断"这个账号按什么币种记账"的地方都应问本函数,既不看 region,
+ * 也不需要判断账号属于哪类租户。
+ *
+ * 同一账号的目录币种是统一的,所以任取一条即可;目录为空或出现混合币种(目录本身不可信)
+ * 时返回 null,由调用方回落到构建默认值。与 main 侧 modelPricing.getGatewayAccountCurrency
+ * 的判定口径一致。
+ */
+export function gatewayLedgerCurrency(
+ pricing: ModelPricingCatalog | null | undefined,
+): MoneyCurrency | null {
+ const currencies = new Set(Object.values(pricing?.xd ?? {}).map((quote) => quote.currency));
+ return currencies.size === 1 ? (currencies.values().next().value ?? null) : null;
+}
+
export function subscriptionDirectPriceQuote(modelId: string): ModelPriceQuote | undefined {
if (modelId.startsWith(CHATGPT_MODEL_PREFIX)) {
return providerReferencePriceQuote('openai', modelId);
diff --git a/apps/desktop/src/shared/regionalMoney.ts b/apps/desktop/src/shared/regionalMoney.ts
index 4cec48fb93..43b76f2a5e 100644
--- a/apps/desktop/src/shared/regionalMoney.ts
+++ b/apps/desktop/src/shared/regionalMoney.ts
@@ -125,13 +125,51 @@ export function regionalizeUsd(
return regionalizeMoney(usdMoney(amountUsd, kind, reason), region);
}
-/** 当前客户端 Gateway 数值,币种跟随本地 usage 账本。 */
-export function gatewayMoney(amount: number, kind: MoneyKind = 'actual-cost'): RegionalMoney {
+/**
+ * 把 USD 口径金额投影到目标账本币种。
+ *
+ * 与 regionalizeMoney 的区别:投影目标是**账号的结算币种**而不是构建区域。本地账本是
+ * 单币种的,写入侧只接受该币种(见 main/usage/ledgerCurrency),所以非 Gateway 渠道
+ * (订阅价值估算、第三方供应商 SDK 费用,原始口径都是 USD)必须按账本币种投影而不是按
+ * 区域 —— 否则以 USD 结算的账号在 CN 构建上会拿到 CNY 金额,被账本守卫当异币种全部丢弃,
+ * 这些渠道的花费就再也记不进日账本、按模型统计与「本对话」累计。
+ *
+ * 只支持 USD → CNY(固定汇率本就是为这个方向的展示投影设的)。已是目标币种的原样返回;
+ * CNY → USD 没有反向汇率契约,不猜、原样返回交给上层的异币种处理。
+ */
+export function toLedgerCurrency(
+ money: RegionalMoney,
+ ledgerCurrency: MoneyCurrency,
+): RegionalMoney {
+ assertAmount(money.amount);
+ if (money.currency === ledgerCurrency) return money;
+ if (ledgerCurrency === 'CNY' && money.currency === 'USD') {
+ return { ...money, amount: money.amount * USD_TO_CNY_FIXED_RATE, currency: 'CNY' };
+ }
+ return money;
+}
+
+/** usdMoney + 按账本币种投影(替代按区域投影的 regionalizeUsd)。 */
+export function usdToLedgerCurrency(
+ amountUsd: number,
+ ledgerCurrency: MoneyCurrency,
+ kind: MoneyKind = 'actual-cost',
+ reason?: MoneyEstimateReason,
+): RegionalMoney {
+ return toLedgerCurrency(usdMoney(amountUsd, kind, reason), ledgerCurrency);
+}
+
+/** Gateway 原生数值;缺省币种跟随本地 usage 账本,账号快照可显式传入币种。 */
+export function gatewayMoney(
+ amount: number,
+ currency: MoneyCurrency = DEFAULT_USAGE_CURRENCY,
+ kind: MoneyKind = 'actual-cost',
+): RegionalMoney {
assertAmount(amount);
const approximate = kind === 'value-estimate';
return {
amount,
- currency: DEFAULT_USAGE_CURRENCY,
+ currency,
approximate,
kind,
...(approximate ? { estimateReasons: ['subscription-value'] } : {}),