Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 隔离 Cindy AI 价格与账号额度 (#1487)
GaoWei Liu2cbde87379a0
diff --git a/apps/desktop/src/main/__tests__/claudeAccountUsageSource.test.ts b/apps/desktop/src/main/__tests__/claudeAccountUsageSource.test.tsindex 0c7d60a3cc..76119f1102 100644--- a/apps/desktop/src/main/__tests__/claudeAccountUsageSource.test.ts+++ b/apps/desktop/src/main/__tests__/claudeAccountUsageSource.test.ts@@ -36,4 +36,10 @@ describe('claudeAccountUsage today accounting', () => {it('uses a relaxed timeout for background quota refreshes', () => {expect(source).toContain('const FETCH_TIMEOUT_MS = 8000;');});++ it('exposes LiteLLM quota only to its owning organization or local gateway', () => {+ expect(source).toContain("auth.user?.membershipKind !== 'org'");+ expect(source).toContain('snapshotOwnerKey === owner.key');+ expect(source).toContain('currentQuotaOwner()?.key !== owner.key');+ });});diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 35b7e8a430..92e2e6a018 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -560,8 +560,8 @@ describe('maker:event hot path ordering', () => {);expect(codexDoneSource).toContain('const pricing = isSubscriptionValue');expect(codexDoneSource).not.toContain('isSubscriptionValue && !isCodexXaiProviderRoute');- expect(codexDoneSource).toContain('? await getModelPricing()');- expect(codexDoneSource).toContain("? await getModelPricingForModel('xd', pricingModel)");+ expect(codexDoneSource).toContain('? getReferenceModelPricing()');+ expect(codexDoneSource).toContain('? await getGatewayModelPricingForModel()');expect(codexDoneSource).toContain('price ?? undefined');expect(codexDoneSource).toContain("if (!isSubscriptionValue && money && price?.source === 'gateway')",@@ -605,10 +605,8 @@ describe('maker:event hot path ordering', () => {// 主路径:按真实 provider / billing route 取价,所有 sink 共用区域金额结果。expect(claudeDoneSource).toContain('const billingRoute: BillingRoute = session.remoteHostId');expect(claudeDoneSource).toContain("billingRoute === 'xd-gateway'");- expect(claudeDoneSource).toContain("await getModelPricingForModel(");- expect(claudeDoneSource).toContain("'xd',");- expect(claudeDoneSource).toContain('normalizeModelIdForPricing(deltas[0]?.model)');- expect(claudeDoneSource).toContain(': await getModelPricing();');+ expect(claudeDoneSource).toContain('await getGatewayModelPricingForModel()');+ expect(claudeDoneSource).toContain(': getReferenceModelPricing();');expect(claudeDoneSource).toContain('const { turnMoney, estimatedTurnMoney, perModel } = resolveClaudeTurnCostSinks(',);@@ -630,6 +628,9 @@ describe('maker:event hot path ordering', () => {expect(claudeDoneSource).toContain("m.source === 'subscription' && isSubscriptionDirectModel(m.model)",);+ expect(claudeDoneSource).toMatch(+ /estimateClaudeSubscriptionTurnValue\(\s*perModel,\s*currentLedgerCurrency\(\),\s*pricing,\s*\)/,+ );// 订阅判定对齐 proxy 路由: 显式选 Anthropic, 或默认路由优先按 observed route, 未观察再回落无网关 key 启发式expect(claudeDoneSource).toContain("sessionProviderForBilling === 'anthropic'");expect(claudeDoneSource).toContain('const observedClaudeRoute =');diff --git a/apps/desktop/src/main/localDb/dailySpend.ts b/apps/desktop/src/main/localDb/dailySpend.tsindex 33acad00c9..233ee15fe5 100644--- a/apps/desktop/src/main/localDb/dailySpend.ts+++ b/apps/desktop/src/main/localDb/dailySpend.ts@@ -64,7 +64,7 @@ function dayMonies(rows: readonly SpendRow[]): RegionalMoney[] {** **币种参数必须由调用方显式传入**:折叠是一个依赖账本币种的决定,而账本币种在冷启动* 期间要等报价快照恢复才确定。此前这里直接读 currentLedgerCurrency(),于是- * getAllSpendDays() 与 getModelPricing() 并发时会先按兜底币种把 CNY 行全丢掉,+ * getAllSpendDays() 与 getGatewayModelPricing() 并发时会先按兜底币种把 CNY 行全丢掉,* 调用方拿到的已经是折叠过的错值,首页整段历史短暂显示为 0。*/export function collapseDayMonies(diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.tsindex d24c53c966..24b1a9f842 100644--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts@@ -47,6 +47,29 @@ describe('XD 网关权威模型清单重建', () => {expect(xdModels('codex')).toEqual([]);});+ it('远端 Catalog 不能覆盖 XD Provider 壳或注入 XD 模型', () => {+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as typeof BUNDLED_CATALOG;+ const catalogXd = catalog.providers.find((provider) => provider.id === 'xd');+ const builtinXd = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xd');+ if (!catalogXd || !builtinXd) throw new Error('missing XD provider fixture');+ catalogXd.name = 'Catalog-supplied XD';+ catalogXd.models['claude-code'] = [+ {+ id: 'catalog-only-model',+ name: 'Catalog-only model',+ contextWindow: 1,+ efforts: [],+ defaultEffort: null,+ },+ ];++ setActiveCatalog(catalog);++ const activeXd = getActiveCatalog().providers.find((provider) => provider.id === 'xd');+ expect(activeXd?.name).toBe(builtinXd.name);+ expect(xdModels('claude-code')).toEqual([]);+ });+it('未登记模型按 Claude-only 兜底并投影到 Codex bridge:3 档 effort + fast=false + 200k 窗口', () => {setActiveCatalog(BUNDLED_CATALOG);setXdGatewayModels([{ id: 'brand-new-model' }]);diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.tsindex 181bea3e4b..283def1a22 100644--- a/apps/desktop/src/main/maker-host/active-catalog.ts+++ b/apps/desktop/src/main/maker-host/active-catalog.ts@@ -123,12 +123,8 @@ export interface XdGatewayModelInfo {* AIGateway /model-groups 投影 + 服务端内置常量表富化;2026-07-17 定案:XD 模型* 列表完全以网关为准,不再由 OSS 产品目录决定)。未登录 / 拉取失败 / 空响应时* 保持空数组,绝不把产品目录里的静态模型冒充成网关实时可用模型。有值时 xd- * 供应商的模型列表整体重建,每个条目:- * - tab 归属:服务端 `agents` > 目录同 id 条目的归属 > 仅 claude-code 兜底- * (网关 /v1/messages 跨供应商翻译覆盖面最广;Responses 协议不猜);- * - 展示元数据逐字段:服务端条目 > 目录同 id 条目 > 合成默认(id 当展示名,- * 口径同自定义 OAuth 模型发现,见 maker-ipc/register.ts oauthLogin);- * - 目录里有、网关没有 → 不展示。+ * 供应商的模型列表整体重建。模型、tab 归属、展示元数据和价格都只读服务端条目;+ * 字段缺失时使用确定性客户端默认值,不读取公共 Catalog 补充。*/let xdGatewayModels: XdGatewayModelInfo[] = [];/**@@ -494,7 +490,13 @@ function computeMerged(): Catalog {// 作者错误隔离进 warnings,由刷新路径读走打日志,不拖垮其余条目。const plan = planRegistryRoots(b.modelRegistry);lastPlanWarnings = plan.warnings;- let providers: Provider[] = b.providers.map((provider): Provider => {+ // XD Provider 使用随客户端发布的固定壳,远端 Catalog 只能管理非 XD Provider。+ // `/models` 会在下方重建固定壳的全部模型,Catalog 缺失、刷新或异常都不能改变 XD。+ const builtinXd = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xd');+ const remoteXdIndex = b.providers.findIndex((provider) => provider.id === 'xd');+ const providerSources = b.providers.filter((provider) => provider.id !== 'xd');+ if (builtinXd) providerSources.splice(Math.max(0, remoteXdIndex), 0, builtinXd);+ let providers: Provider[] = providerSources.map((provider): Provider => {if (provider.id !== 'xai') return provider;const claudeRoute = provider.routing['claude-code'];const claudeModels = provider.models['claude-code'] ?? [];diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.tsindex 3c7c3ba642..c4b0a87e78 100644--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts@@ -100,7 +100,7 @@ import {migrateLegacyNativeProviderAuthBindings,} from './nativeProviderAuthBinding.js';import { hasLegacyOwnerNamespaceClaim } from '../ownerNamespaceMigration.js';-import { broadcastEffectiveModelPricing } from '../usage/modelPricing.js';+import { broadcastReferenceModelPricing } from '../usage/referenceModelPricing.js';const log = createLogger('provider-service');@@ -468,7 +468,7 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {syncLocalCatalogOverridesIntoActiveCatalog();getActiveCatalog();logModelPlaneWarnings();- broadcastEffectiveModelPricing();+ broadcastReferenceModelPricing();// 读 codex models_cache.json 得到规范化快照,由 active-catalog 同时投影到 Codex 与// Claude bridge。null 表示没读到有效 cache,保留现值 / 静态兜底;[] 表示合法空快照。try {@@ -520,7 +520,7 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {activeCatalogSourceKey = null;// 必须在网络 await 前失效:登录提交后 renderer/agent 可能立即读取目录。setActiveCatalog(BUNDLED_CATALOG);- broadcastEffectiveModelPricing();+ broadcastReferenceModelPricing();const flight = loadCatalog(source, io).then((catalog) => {@@ -532,7 +532,7 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {}activeCatalogSourceKey = sourceKey;setActiveCatalog(catalog);- broadcastEffectiveModelPricing();+ broadcastReferenceModelPricing();return getActiveCatalog();}).finally(() => {@@ -605,7 +605,7 @@ export async function refreshActiveCatalogFromSource(): Promise<Catalog> {// 上一代惰性缓存留下的 warnings。const activeCatalog = getActiveCatalog();logModelPlaneWarnings();- broadcastEffectiveModelPricing();+ broadcastReferenceModelPricing();return activeCatalog;}).finally(() => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.tsindex ecb378a3c3..2e0b558fff 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts@@ -1194,6 +1194,7 @@ describe('maker usage IPC handlers', () => {readClaudeAccountUsageSnapshot: vi.fn(),triggerClaudeAccountUsageRefresh: vi.fn(),readModelPricing: vi.fn(),+ readReferenceModelPricing: vi.fn(() => ({})),readUsageHistory: vi.fn().mockResolvedValue(emptyHistory),emptyUsageHistory: vi.fn(() => emptyHistory),...over,@@ -1269,6 +1270,36 @@ describe('maker usage IPC handlers', () => {expect(readModelPricing).toHaveBeenCalledTimes(2);});+ it('serves non-XD reference prices on a channel independent from XD pricing', async () => {+ const harness = new IpcHarness();+ const referencePricing = {+ anthropic: {+ 'claude-sonnet-4-6': {+ providerId: 'anthropic',+ modelId: 'claude-sonnet-4-6',+ currency: 'USD',+ source: 'provider-reference',+ approximate: true,+ inputPerMtok: 3,+ outputPerMtok: 15,+ },+ },+ };+ const readReferenceModelPricing = vi.fn(() => referencePricing);+ const readModelPricing = vi.fn();++ registerMakerUsageHandlers(+ harness,+ makeUsageDeps({ readReferenceModelPricing, readModelPricing }),+ );++ await expect(harness.invoke(MAKER_INVOKE.USAGE_REFERENCE_MODEL_PRICING)).resolves.toEqual(+ referencePricing,+ );+ expect(readReferenceModelPricing).toHaveBeenCalledOnce();+ expect(readModelPricing).not.toHaveBeenCalled();+ });+it('reads Codex reset credits and consumes only a UUID offer key', async () => {const harness = new IpcHarness();const snapshot = {diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 4d041f0dcd..26c1e0cc82 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -289,8 +289,10 @@ export const MAKER_INVOKE = {USAGE_CLAUDE_SUBSCRIPTION: 'maker:usage:claude-subscription',// device-link v1 模型单价表:保留 modelId → USD/Mtok 扁平形状,旧控制端继续可读。USAGE_MODEL_PRICING: 'maker:usage:model-pricing',- // Desktop renderer v2:provider-scoped + currency-aware 模型单价表。+ // Desktop renderer v2:Cindy AI `/models` 下发的 XD 原生报价。USAGE_MODEL_PRICING_V2: 'maker:usage:model-pricing-v2',+ // 非 XD Provider 的 Catalog 参考价与用户覆盖;只用于 BYOK / 订阅估值。+ USAGE_REFERENCE_MODEL_PRICING: 'maker:usage:reference-model-pricing',// 用量历史聚合 (daily_spend + daily_model_usage, main 侧算好 streak/异常/估算) — 首页仪表盘用USAGE_HISTORY: 'maker:usage:history',// Memory 控制 — 走 Maker.{getAgentMemoryStatus/setAgentMemory/resetAgentMemory},diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 96472e5c41..85abaddad5 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -307,7 +307,8 @@ import {import { recordModelMismatchOnMessage } from '../modelMismatchBroadcaster.js';import { detectClaudeModelMismatch } from '../../shared/modelMismatch.js';import { triggerClaudeAccountUsageRefresh } from '../usage/claudeAccountUsage.js';-import { broadcastEffectiveModelPricing, getCodexProviderSubscriptionValuePrice, getGatewayAccountCurrency, getModelPriceQuote, getModelPricing, getModelPricingForModel, getSubscriptionDirectValuePrice } from '../usage/modelPricing.js';+import { getGatewayAccountCurrency, getGatewayModelPricingForModel, getModelPriceQuote } from '../usage/modelPricing.js';+import { broadcastReferenceModelPricing, getCodexProviderSubscriptionValuePrice, getReferenceModelPricing, getSubscriptionDirectValuePrice } from '../usage/referenceModelPricing.js';import { clearModelPriceOverride, stageProviderModelPriceOverridesClear, readModelPriceOverrideView, setModelPriceOverride } from '../usage/modelPriceOverrideStore.js';import { computeModelUsageDeltas, detectOutputLag, type ModelUsageCumulative, type ModelUsageDeltaEntry } from '../usage/modelUsageDelta.js';import { claudeSubscriptionUsageModelKey, codexApiUsageModelKey, codexSubscriptionUsageModelKey, piSubscriptionUsageModelKey } from '../usage/usageHistory.js';@@ -3534,11 +3535,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void?? (observedClaudeRoute === 'gateway' ? 'xd-gateway' : 'unknown');const pricing =billingRoute === 'xd-gateway'- ? await getModelPricingForModel(- 'xd',- normalizeModelIdForPricing(deltas[0]?.model),- )- : await getModelPricing();+ ? await getGatewayModelPricingForModel()+ : getReferenceModelPricing();const { turnMoney, estimatedTurnMoney, perModel } = resolveClaudeTurnCostSinks(deltas,pricing,@@ -3622,7 +3620,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidconst claudeEstimated = estimateClaudeSubscriptionTurnValue(perModel,currentLedgerCurrency(),- await getModelPricing(),+ pricing,);if (claudeEstimated?.amount) estimatedValues.push(claudeEstimated);}@@ -3859,11 +3857,11 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void};try {const pricing = isSubscriptionValue- ? await getModelPricing()+ ? getReferenceModelPricing(): hasEffectiveGatewayRoute- ? await getModelPricingForModel('xd', pricingModel)+ ? await getGatewayModelPricingForModel(): usesReferencePriceEstimate- ? await getModelPricing()+ ? getReferenceModelPricing(): null;// 订阅估值按显式来源取各自的日期定价路由:内置 anthropic 走 Anthropic// registry 参考价(含 codex 侧价格覆盖),默认/openai 保持 OpenAI 价表。@@ -4019,7 +4017,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidconst pricing =isSubscriptionValue || isCustomProviderRoute? null- : await getModelPricingForModel('xd', pricingModel);+ : await getGatewayModelPricingForModel();const price =effectiveProvider === 'openai'|| effectiveProvider === 'anthropic'@@ -4616,7 +4614,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)setModelPriceOverride(target, desired, getActiveCatalog().modelRegistry),clearModelPriceOverride,stageClearProviderModelPriceOverrides: stageProviderModelPriceOverridesClear,- broadcastPricingChanged: broadcastEffectiveModelPricing,+ broadcastPricingChanged: broadcastReferenceModelPricing,// 通用 OAuth(目录 auth.oauth 描述符驱动):login 成功后 best-effort 拉动态模型发现// (additions-only merge 进 active-catalog) 并广播 PROVIDER_CHANGED 让 UI 刷新连接态。oauthLogin: async (providerId, isCurrent) => {diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.tsindex 2c986b2973..14c04d1e3e 100644--- a/apps/desktop/src/main/maker-ipc/usage.ts+++ b/apps/desktop/src/main/maker-ipc/usage.ts@@ -23,7 +23,8 @@ import {} from '../usage/claudeSubscriptionUsage.js';import { createClaudeSubscriptionUsageReader } from '../usage/claudeSubscriptionUsageRefresh.js';import { createCodexAccountUsageSnapshotReader } from '../usage/codexAccountUsageRefresh.js';-import { getModelPricing } from '../usage/modelPricing.js';+import { getGatewayModelPricing } from '../usage/modelPricing.js';+import { getReferenceModelPricing } from '../usage/referenceModelPricing.js';import {CodexWebUsageUnauthorizedError,fetchCodexWebUsageSnapshot,@@ -219,7 +220,8 @@ export function registerMakerUsageIpc(maker: Maker): void {readClaudeSubscriptionUsageSnapshot: () => claudeSubscriptionUsageReader.read(),readClaudeAccountUsageSnapshot,triggerClaudeAccountUsageRefresh,- readModelPricing: getModelPricing,+ readModelPricing: getGatewayModelPricing,+ readReferenceModelPricing: getReferenceModelPricing,readUsageHistory,emptyUsageHistory: emptyUsageHistoryPayload,});diff --git a/apps/desktop/src/main/maker-ipc/usageHandlers.ts b/apps/desktop/src/main/maker-ipc/usageHandlers.tsindex aa9e465841..0f7bb18968 100644--- a/apps/desktop/src/main/maker-ipc/usageHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/usageHandlers.ts@@ -63,6 +63,7 @@ export interface MakerUsageHandlerDeps {readClaudeAccountUsageSnapshot(): ClaudeAccountUsageSnapshot | null;triggerClaudeAccountUsageRefresh(force: boolean): Promise<void>;readModelPricing(): Promise<ModelPricingMap | null>;+ readReferenceModelPricing(): ModelPricingMap;readUsageHistory(opts?: UsageHistoryReadOptions): Promise<UsageHistoryPayload>;emptyUsageHistory(): UsageHistoryPayload;}@@ -127,11 +128,15 @@ export function registerMakerUsageHandlers(return toLegacyUsdModelPricing(await deps.readModelPricing());});- // Desktop renderer v2:provider-scoped、带币种和约值语义的完整价格目录。+ // Desktop renderer v2:Cindy AI `/models` 的 XD 原生报价,不混入 Catalog。registry.handle(MAKER_INVOKE.USAGE_MODEL_PRICING_V2, async () => {return await deps.readModelPricing();});+ registry.handle(MAKER_INVOKE.USAGE_REFERENCE_MODEL_PRICING, async () => {+ return deps.readReferenceModelPricing();+ });+// 用量历史聚合 (首页仪表盘) — 查询型 handler, DB 出错回退空 payload 让// renderer 正常渲染空态 (与同文件其它 usage 读取的 fallback-data 口径一致)。registry.handle(MAKER_INVOKE.USAGE_HISTORY, async (_e, opts: unknown) => {diff --git a/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.ts b/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.tsdeleted file mode 100644index a7ac4df172..0000000000--- a/apps/desktop/src/main/model-access/__tests__/devMetaOverlay.test.ts+++ /dev/null@@ -1,146 +0,0 @@-/**- * Dev ModelRegistry overlay contract: live Gateway membership and prices stay- * authoritative while the local registry can replace curated metadata.- */-import { describe, expect, it, vi } from 'vitest';--import type { ModelRegistry, ModelRegistryEntry } from '@cindy/model-providers';--import { overlayModelRegistryMeta } from '../devMetaOverlay.js';-import type { ModelAccessGatewayModel } from '../../../shared/modelAccess.js';--const SERVER_MODEL: ModelAccessGatewayModel = {- id: 'gpt-5.5',- contextWindow: 272_000,- maxOutputTokens: 32_000,- agents: ['claude-code', 'codex'],- name: 'GPT-5.5(server)',- group: 'gpt',- efforts: ['low', 'medium', 'high'],- defaultEffort: 'high',- sortOrder: 20,- supportsFastMode: true,-};--const LOCAL_ENTRY: ModelRegistryEntry = {- id: 'openai/gpt-5.5',- name: 'GPT-5.5(local)',- group: 'gpt-local',- contextWindow: 999_000,- maxOutputTokens: 64_000,- efforts: ['low', 'high', 'xhigh'],- defaultEffort: 'xhigh',- sortOrder: 3,- supportsFastMode: false,- defaultEnabled: false,- perAgent: { codex: { supportsFastMode: true } },- routes: [{ providerId: 'xd', modelId: 'gpt-5.5', agents: ['codex'] }],-};--function registry(...entries: ModelRegistryEntry[]): ModelRegistry {- return {- schemaVersion: 1,- updatedAt: '2026-07-31T00:00:00.000Z',- models: entries,- };-}--describe('overlayModelRegistryMeta', () => {- it('同 id 路由整体替换元数据;Gateway 上报的窗口和输出上限保持权威', () => {- const [model] = overlayModelRegistryMeta([SERVER_MODEL], registry(LOCAL_ENTRY));- expect(model).toMatchObject({- id: 'gpt-5.5',- contextWindow: 272_000,- maxOutputTokens: 32_000,- agents: ['codex'],- name: 'GPT-5.5(local)',- group: 'gpt-local',- efforts: ['low', 'high', 'xhigh'],- defaultEffort: 'xhigh',- sortOrder: 3,- supportsFastMode: false,- defaultEnabled: false,- perAgent: { codex: { supportsFastMode: true } },- });- });-- it('Gateway 未提供窗口或输出上限时才用 registry 兜底', () => {- const live: ModelAccessGatewayModel = {- id: 'gpt-5.5',- name: 'x',- agents: ['claude-code'],- };- const [model] = overlayModelRegistryMeta([live], registry(LOCAL_ENTRY));- expect(model.contextWindow).toBe(999_000);- expect(model.maxOutputTokens).toBe(64_000);- });-- it('元数据覆盖和 retired 路由都保留 Gateway 价格字段', () => {- const priced: ModelAccessGatewayModel = {- ...SERVER_MODEL,- costDiscount: 0.2,- inputCostPerToken: 0.000003,- outputCostPerToken: 0.000015,- tieredPricing: [- {- range: [0, 200_000],- inputCostPerToken: 0.000003,- outputCostPerToken: 0.000015,- },- ],- };- const [overridden] = overlayModelRegistryMeta([priced], registry(LOCAL_ENTRY));- const [retired] = overlayModelRegistryMeta(- [priced],- registry({ ...LOCAL_ENTRY, status: 'retired' }),- );-- for (const model of [overridden, retired]) {- expect(model).toMatchObject({- costDiscount: 0.2,- inputCostPerToken: 0.000003,- outputCostPerToken: 0.000015,- tieredPricing: [- {- range: [0, 200_000],- inputCostPerToken: 0.000003,- outputCostPerToken: 0.000015,- },- ],- });- }- expect(retired).toEqual({- id: 'gpt-5.5',- contextWindow: 272_000,- maxOutputTokens: 32_000,- costDiscount: 0.2,- inputCostPerToken: 0.000003,- outputCostPerToken: 0.000015,- tieredPricing: [- {- range: [0, 200_000],- inputCostPerToken: 0.000003,- outputCostPerToken: 0.000015,- },- ],- });- });-- it('无 XD 路由不会覆盖,也不会凭 registry 增加可用模型', () => {- const officialOnly: ModelRegistryEntry = {- ...LOCAL_ENTRY,- routes: [{ providerId: 'openai', modelId: 'gpt-5.5', agents: ['codex'] }],- };- const out = overlayModelRegistryMeta([SERVER_MODEL], registry(officialOnly));- expect(out).toEqual([SERVER_MODEL]);- expect(out).toHaveLength(1);- });-- it('缺少 registry 时原样返回且不产生日志', () => {- const info = vi.fn();- expect(overlayModelRegistryMeta([SERVER_MODEL], undefined, { info, warn: vi.fn() })).toEqual([- SERVER_MODEL,- ]);- expect(info).not.toHaveBeenCalled();- });-});diff --git a/apps/desktop/src/main/model-access/devMetaOverlay.ts b/apps/desktop/src/main/model-access/devMetaOverlay.tsdeleted file mode 100644index ee54c29850..0000000000--- a/apps/desktop/src/main/model-access/devMetaOverlay.ts+++ /dev/null@@ -1,124 +0,0 @@-/**- * Dev-only projection of the local public ModelRegistry onto the XD Gateway's- * live model list.- *- * Availability and prices remain Gateway-authoritative: registry entries only- * enrich ids that the server already returned. A retired XD route removes the- * curated metadata and lets downstream deterministic defaults apply. Packaged- * builds never call this function.- */--import type {- ModelRegistry,- ModelRegistryEntry,- ModelRegistryRoute,-} from '@cindy/model-providers';--import type {- ModelAccessAgentOverride,- ModelAccessGatewayModel,-} from '../../shared/modelAccess.js';--/** 覆盖日志回调(生产接统一 logger;测试可缺省)。 */-export interface OverlayLog {- warn(msg: string, meta?: Record<string, unknown>): void;- info(msg: string, meta?: Record<string, unknown>): void;-}--/**- * 去掉可由 registry 覆盖的展示、归属和能力字段,保留 token 上限和全部- * Gateway 价格。这样本地 overlay 或 retired 路由都不会把同快照里的价格静默丢掉。- */-function gatewayFields(m: ModelAccessGatewayModel): ModelAccessGatewayModel {- const fields = { ...m };- delete fields.agents;- delete fields.name;- delete fields.group;- delete fields.description;- delete fields.efforts;- delete fields.defaultEffort;- delete fields.sortOrder;- delete fields.supportsFastMode;- delete fields.defaultEnabled;- delete fields.perAgent;- return fields;-}--function findXdRoute(- registry: ModelRegistry,- modelId: string,-): { entry: ModelRegistryEntry; route: ModelRegistryRoute } | undefined {- for (const entry of registry.models) {- const route = entry.routes.find(- (candidate) => candidate.providerId === 'xd' && candidate.modelId === modelId,- );- if (route) return { entry, route };- }- return undefined;-}--/** 以 registry 条目重建服务端下发条目(Gateway 权威字段保留,策展元数据整体替换)。 */-function rebuildModel(- model: ModelAccessGatewayModel,- entry: ModelRegistryEntry,- route: ModelRegistryRoute,-): ModelAccessGatewayModel {- return {- ...gatewayFields(model),- // Gateway 上报的 token 上限权威;registry 仅在服务端条目缺失时兜底。- ...(model.contextWindow === undefined && entry.contextWindow !== undefined- ? { contextWindow: entry.contextWindow }- : {}),- ...(model.maxOutputTokens === undefined && entry.maxOutputTokens !== undefined- ? { maxOutputTokens: entry.maxOutputTokens }- : {}),- agents: route.agents,- name: entry.name,- ...(entry.group ? { group: entry.group } : {}),- ...(entry.description ? { description: entry.description } : {}),- ...(entry.efforts ? { efforts: entry.efforts } : {}),- ...(entry.defaultEffort !== undefined ? { defaultEffort: entry.defaultEffort } : {}),- ...(entry.sortOrder !== undefined ? { sortOrder: entry.sortOrder } : {}),- ...(entry.supportsFastMode !== undefined ? { supportsFastMode: entry.supportsFastMode } : {}),- ...(entry.defaultEnabled !== undefined ? { defaultEnabled: entry.defaultEnabled } : {}),- ...(entry.perAgent- ? {- perAgent: entry.perAgent as Partial<- Record<'claude-code' | 'codex', ModelAccessAgentOverride>- >,- }- : {}),- };-}--/**- * 用本地 ModelRegistry 的 XD 路由覆盖服务端下发的网关模型清单(纯函数)。- * 本地无 registry / 无匹配路由 → 原样返回;不会凭 registry 增加可用模型。- */-export function overlayModelRegistryMeta(- models: ModelAccessGatewayModel[],- registry: ModelRegistry | undefined,- log?: OverlayLog,-): ModelAccessGatewayModel[] {- if (!registry) return models;- let overridden = 0;- let retired = 0;- const out = models.map((model) => {- const matched = findXdRoute(registry, model.id);- if (!matched) return model;- if (matched.entry.status === 'retired') {- retired += 1;- return gatewayFields(model);- }- overridden += 1;- return rebuildModel(model, matched.entry, matched.route);- });- if (overridden > 0 || retired > 0) {- log?.info('dev modelRegistry overlay applied', {- overridden,- retired,- total: models.length,- });- }- return out;-}diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.tsindex ca4a120c26..8965b40d96 100644--- a/apps/desktop/src/main/model-access/index.ts+++ b/apps/desktop/src/main/model-access/index.ts@@ -11,13 +11,8 @@ import {finalizeCodexAfterAuthModeChange,cancelCodexAuthModeChange,} from '../maker-host/index.js';-import { getActiveCatalog, setXdGatewayModels } from '../maker-host/active-catalog.js';-import { isDev } from '../manifestService.js';-import { overlayModelRegistryMeta } from './devMetaOverlay.js';-import {- replaceGatewayModelPricing,- trackGatewayModelPricingSync,-} from '../usage/modelPricing.js';+import { setXdGatewayModels } from '../maker-host/active-catalog.js';+import { replaceGatewayModelPricing, trackGatewayModelPricingSync } from '../usage/modelPricing.js';import { isPricedGatewayModel } from '../../shared/modelPriceQuote.js';import { throwIpcError } from '../utils/ipcValidate.js';import {@@ -128,7 +123,7 @@ function broadcastStatus(status: ModelAccessStatus): void {}}-// ─── XD 网关模型目录同步(网关为准,目录仅补元数据)────────────────────+// ─── XD 网关模型目录同步(`/models` 是模型、能力与价格的唯一事实源)─────────// 凭据同步成功后从 model-access-server 拉 GET /models(AIGateway /model-groups// 的 mode=chat 投影),整体重建 xd 供应商的模型列表(active-catalog// setXdGatewayModels)。拉取失败保留最后一次完整成功快照;成功空列表同时清空模型和价格。@@ -154,8 +149,7 @@ function applyGatewayModels(models: ModelAccessGatewayModel[],authenticatedUserId?: string,): void {- // 同一次 /models 响应先建立 provider-scoped 价格投影,再做仅影响展示元数据的- // dev overlay。空成功响应会同时清空模型和价格;请求失败不会调用本函数,+ // 同一次 /models 响应建立 XD 模型与价格投影。空成功响应会同时清空模型和价格;请求失败不会调用本函数,// 因而保留上一份完整成功快照。const pricing = replaceGatewayModelPricing(models, authenticatedUserId);// 分母只算会产生报价的条目:免费/无价条目按设计不出报价,不该把健康目录@@ -168,18 +162,12 @@ function applyGatewayModels(`xd gateway pricing quotes cover ${quoteCount}/${pricedCount} priced models (${models.length} total)`,);}- // dev:本地统一 registry 的 XD 路由覆盖服务端下发的策展元数据;只覆盖同 id,- // 清单成员资格与价格仍以 Gateway 为准。packaged 不走此分支。- const overlaid =- isDev() && models.length > 0- ? overlayModelRegistryMeta(models, getActiveCatalog().modelRegistry, log)- : models;// 能力字段不在客户端二次转换 —— Model Access Server 已把 Gateway 的// contextLength / supportedEndpoints / reasoning / supportsServiceTier / architecture// 一次归一化成 contextWindow / agents / efforts / supportsFastMode / modalities,// 同一含义只下发一个字段。这里直接用下发值,唯一事实源在服务端。// active-catalog 统一收口会原地刷新 Maker capabilities,再广播同一 revision。- setXdGatewayModels(overlaid);+ setXdGatewayModels(models);}async function runModelsSync(diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.tsindex 311490c95e..62bc53e6d1 100644--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts@@ -63,24 +63,23 @@ import {readModelPriceOverridesSnapshot,setModelPriceOverride,} from '../modelPriceOverrideStore';-import {- __resetActiveLedgerCurrencyForTesting,- currentLedgerCurrency,-} from '../ledgerCurrency';+import { __resetActiveLedgerCurrencyForTesting, currentLedgerCurrency } from '../ledgerCurrency';import {__resetModelPricingCacheForTesting,clearGatewayModelPricing,- getClaudeSubscriptionValuePrice,- getCodexProviderSubscriptionValuePrice,- getCodexSubscriptionValuePrice,- getModelPricing,- getModelPricingForModel,- getSubscriptionDirectValuePrice,+ getGatewayModelPricing,+ getGatewayModelPricingForModel,MODEL_PRICING_CHANGED_CHANNEL,prewarmModelPricing,replaceGatewayModelPricing,trackGatewayModelPricingSync,} from '../modelPricing';+import {+ getClaudeSubscriptionValuePrice,+ getCodexProviderSubscriptionValuePrice,+ getCodexSubscriptionValuePrice,+ getSubscriptionDirectValuePrice,+} from '../referenceModelPricing';let tempUserDataDir: string | null = null;// 目录整份没声明 currency 时的回落值。不再按构建区域推断 —— 服务端漏发 currency 时@@ -248,17 +247,14 @@ describe('gateway model pricing projection', () => {outputCostPerToken: 0.000002,},]);- expect(await getModelPricing()).not.toBeNull();+ expect(await getGatewayModelPricing()).not.toBeNull();expect(replaceGatewayModelPricing([{ id: 'unpriced' }])).toEqual({});- expect((await getModelPricing())?.xd).toBeUndefined();- expect(mocks.send).toHaveBeenLastCalledWith(- MODEL_PRICING_CHANGED_CHANNEL,- expect.objectContaining({ openai: expect.any(Object) }),- );+ expect((await getGatewayModelPricing())?.xd).toBeUndefined();+ expect(mocks.send).toHaveBeenLastCalledWith(MODEL_PRICING_CHANGED_CHANNEL, {});clearGatewayModelPricing();- expect((await getModelPricing())?.xd).toBeUndefined();+ expect((await getGatewayModelPricing())?.xd).toBeUndefined();});it('hydrates a successful empty pricing snapshot as loaded', async () => {@@ -275,10 +271,7 @@ describe('gateway model pricing projection', () => {});__resetModelPricingCacheForTesting();- await expect(getModelPricing()).resolves.toMatchObject({- openai: expect.any(Object),- anthropic: expect.any(Object),- });+ await expect(getGatewayModelPricing()).resolves.toEqual({});});});@@ -315,7 +308,7 @@ describe('pricing cache lifecycle', () => {});__resetModelPricingCacheForTesting();- await expect(getModelPricing()).resolves.toMatchObject(pricing);+ await expect(getGatewayModelPricing()).resolves.toMatchObject(pricing);await prewarmModelPricing();expect(fetchMock).not.toHaveBeenCalled();});@@ -343,10 +336,8 @@ describe('pricing cache lifecycle', () => {__resetActiveLedgerCurrencyForTesting();expect(currentLedgerCurrency()).toBe(DEFAULT_USAGE_CURRENCY);- const hydrated = await getModelPricing();- // Gateway 报价为空,但统一 registry 的参考价仍属于有效价格目录。- expect(hydrated?.xd).toBeUndefined();- expect(hydrated?.openai).toBeDefined();+ const hydrated = await getGatewayModelPricing();+ expect(hydrated).toEqual({});expect(currentLedgerCurrency()).toBe('USD');expect(fetchMock).not.toHaveBeenCalled();@@ -374,7 +365,7 @@ describe('pricing cache lifecycle', () => {});mocks.getCurrentDbClientUserId.mockReturnValue('user-a');- await expect(getModelPricing()).resolves.toMatchObject(pricing);+ await expect(getGatewayModelPricing()).resolves.toMatchObject(pricing);});it('does not hydrate another account pricing snapshot', async () => {@@ -403,9 +394,7 @@ describe('pricing cache lifecycle', () => {);mocks.getCurrentDbClientUserId.mockReturnValue('user-b');- await expect(getModelPricing()).resolves.toMatchObject({- openai: expect.any(Object),- });+ await expect(getGatewayModelPricing()).resolves.toBeNull();});it('discards a v8 snapshot whose currency was guessed by build region', async () => {@@ -439,9 +428,8 @@ describe('pricing cache lifecycle', () => {);__resetActiveLedgerCurrencyForTesting();- const hydrated = await getModelPricing();- // 那份 v8 的 xd 报价一条都不能进来(registry 参考价不受影响,另有来源)。- expect(hydrated?.xd).toBeUndefined();+ const hydrated = await getGatewayModelPricing();+ expect(hydrated).toBeNull();// 账本币种也不能被它带偏,回退链重新从「上次已知 → USD」起算。expect(currentLedgerCurrency()).toBe('USD');});@@ -469,9 +457,7 @@ describe('pricing cache lifecycle', () => {ctimeNs: 7n,});- await expect(getModelPricing()).resolves.toMatchObject({- openai: expect.any(Object),- });+ await expect(getGatewayModelPricing()).resolves.toBeNull();});it('rejects malformed or non-gateway disk quotes', async () => {@@ -498,12 +484,10 @@ describe('pricing cache lifecycle', () => {}),'utf8',);- await expect(getModelPricing()).resolves.toMatchObject({- openai: expect.any(Object),- });+ await expect(getGatewayModelPricing()).resolves.toBeNull();});- it('requires provider identity on accounting lookups', async () => {+ it('returns only the Gateway snapshot on accounting lookups', async () => {replaceGatewayModelPricing([{id: 'same-id',@@ -511,10 +495,7 @@ describe('pricing cache lifecycle', () => {outputCostPerToken: 0.000002,},]);- await expect(getModelPricingForModel('xd', 'same-id')).resolves.toMatchObject({- xd: { 'same-id': { inputPerMtok: 1, outputPerMtok: 2 } },- });- await expect(getModelPricingForModel('openai', 'same-id')).resolves.toMatchObject({+ await expect(getGatewayModelPricingForModel()).resolves.toMatchObject({xd: { 'same-id': { inputPerMtok: 1, outputPerMtok: 2 } },});});@@ -532,7 +513,7 @@ describe('pricing cache lifecycle', () => {// 永不 settle 的同步:黑洞网络下 /models fetch 没有超时。trackGatewayModelPricingSync(new Promise(() => {}));let settled = false;- const lookup = getModelPricingForModel('xd', 'gpt-x').then((value) => {+ const lookup = getGatewayModelPricingForModel().then((value) => {settled = true;return value;});@@ -550,24 +531,22 @@ describe('pricing cache lifecycle', () => {describe('reference pricing helpers', () => {it('resolves historical subscription prices by their effective date', () => {+ expect(getClaudeSubscriptionValuePrice('claude-sonnet-5', null, '2026-08-31')).toMatchObject({+ inputPerMtok: 2,+ outputPerMtok: 10,+ });+ expect(getClaudeSubscriptionValuePrice('claude-sonnet-5', null, '2026-09-01')).toMatchObject({+ inputPerMtok: 3,+ outputPerMtok: 15,+ });+ expect(getClaudeSubscriptionValuePrice('claude-sonnet-5', null, '2026-06-29')).toBeUndefined();+ expect(getClaudeSubscriptionValuePrice('sonnet', null, '2026-03-01')).toMatchObject({+ modelId: 'sonnet',+ inputPerMtok: 3,+ outputPerMtok: 15,+ });expect(- getClaudeSubscriptionValuePrice('claude-sonnet-5', null, '2026-08-31'),- ).toMatchObject({ inputPerMtok: 2, outputPerMtok: 10 });- expect(- getClaudeSubscriptionValuePrice('claude-sonnet-5', null, '2026-09-01'),- ).toMatchObject({ inputPerMtok: 3, outputPerMtok: 15 });- expect(- getClaudeSubscriptionValuePrice('claude-sonnet-5', null, '2026-06-29'),- ).toBeUndefined();- expect(- getClaudeSubscriptionValuePrice('sonnet', null, '2026-03-01'),- ).toMatchObject({ modelId: 'sonnet', inputPerMtok: 3, outputPerMtok: 15 });- expect(- getClaudeSubscriptionValuePrice(- 'claude-sonnet-4-6-20260701',- null,- '2026-08-01',- ),+ getClaudeSubscriptionValuePrice('claude-sonnet-4-6-20260701', null, '2026-08-01'),).toMatchObject({modelId: 'claude-sonnet-4-6-20260701',inputPerMtok: 3,diff --git a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts b/apps/desktop/src/main/usage/__tests__/usageHistory.test.tsindex ff37b9612a..aac20a6304 100644--- a/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts+++ b/apps/desktop/src/main/usage/__tests__/usageHistory.test.ts@@ -21,8 +21,11 @@ vi.mock('../../localDb/client/current', () => ({getCurrentDbClientUserId: () => currentDbClient.userId,}));vi.mock('../modelPricing', () => ({- getModelPricing: vi.fn(),+ getGatewayModelPricing: vi.fn(),isModelPricingRefreshInFlight: vi.fn(() => false),+}));+vi.mock('../referenceModelPricing', () => ({+ getReferenceModelPricing: vi.fn(() => ({})),readModelPriceOverridesSnapshot: vi.fn(() => ({})),getClaudeSubscriptionValuePrice: (model: string,@@ -115,7 +118,8 @@ import {} from '../usageHistory';import { getAllSpendDays } from '../../localDb/dailySpend';import { getModelUsageSince } from '../../localDb/dailyModelUsage';-import { getModelPricing, isModelPricingRefreshInFlight } from '../modelPricing';+import { getGatewayModelPricing, isModelPricingRefreshInFlight } from '../modelPricing';+import { getReferenceModelPricing } from '../referenceModelPricing';import {__resetActiveLedgerCurrencyForTesting,setActiveLedgerCurrency,@@ -191,7 +195,8 @@ function makeDeps(overrides: Partial<UsageHistoryDeps> = {}): UsageHistoryDeps {return {getAllSpendDays: async () => [],getModelUsageSince: async () => [],- getModelPricing: async () => null,+ getGatewayModelPricing: async () => null,+ getReferenceModelPricing: () => ({}),getModelPriceOverridesSnapshot: () => ({}),isModelPricingRefreshInFlight: () => false,todayKey: () => TODAY,@@ -210,7 +215,8 @@ beforeEach(async () => {__resetActiveLedgerCurrencyForTesting();vi.mocked(getAllSpendDays).mockResolvedValue([]);vi.mocked(getModelUsageSince).mockResolvedValue([]);- vi.mocked(getModelPricing).mockResolvedValue(null);+ vi.mocked(getGatewayModelPricing).mockResolvedValue(null);+ vi.mocked(getReferenceModelPricing).mockReturnValue({});vi.mocked(isModelPricingRefreshInFlight).mockReturnValue(false);});@@ -323,7 +329,7 @@ describe('readUsageHistoryWith', () => {{ outputTokens: 100 },),],- getModelPricing: async () => ({+ getReferenceModelPricing: () => ({openai: {'gpt-5.5': subscriptionQuote('openai', 'gpt-5.5', 2, 8),},@@ -419,7 +425,7 @@ describe('readUsageHistoryWith', () => {{ outputTokens: 20 },),],- getModelPricing: async () => ({+ getReferenceModelPricing: () => ({openai: {'gpt-5.5': subscriptionQuote('openai', 'gpt-5.5', 2, 8),},@@ -479,7 +485,7 @@ describe('readUsageHistoryWith', () => {{ day: TODAY, monies: [usdRow(5)] },],getModelUsageSince: async () => [],- getModelPricing: async () => ({+ getGatewayModelPricing: async () => ({xd: {'gpt-5.5': {providerId: 'xd',@@ -511,7 +517,7 @@ describe('readUsageHistoryWith', () => {{ inputTokens: 1_000_000 },),],- getModelPricing: async () => ({+ getReferenceModelPricing: () => ({anthropic: {'claude-opus-4-8': subscriptionQuote('anthropic',diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.tsindex f8532d97d6..198fc37c38 100644--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts@@ -90,7 +90,10 @@ const THROTTLE_MS = 10_000;const IDLE_POLL_INTERVAL_MS = 5 * 60 * 1000;let snapshot: ClaudeAccountUsageSnapshot | null = null;+let snapshotOwnerKey: string | null = null;let fetchInFlight = false;+let fetchOwnerKey: string | null = null;+let refreshQueued = false;let lastFetchAt = 0;let idlePollTimer: NodeJS.Timeout | null = null;@@ -107,6 +110,24 @@ interface LiteLlmDailyActivity {}>;}+interface QuotaOwner {+ key: string;+ authenticatedUserId?: string;+}++/** 组织账号与 local 手填网关可读周期配额;个人账号只读额度池账本。 */+function currentQuotaOwner(): QuotaOwner | null {+ const auth = getAuthState();+ if (auth.mode === 'cloud') {+ if (auth.user?.membershipKind !== 'org' || !auth.dataOwnerId) return null;+ return { key: `cloud:${auth.dataOwnerId}`, authenticatedUserId: auth.user.id };+ }+ if (auth.mode === 'local' && auth.dataOwnerId) {+ return { key: `local:${auth.dataOwnerId}` };+ }+ return null;+}+/** UTC YYYY-MM-DD。跟 web 看板 的 daily 边界对齐。 */function utcTodayKey(): string {const d = new Date();@@ -180,13 +201,13 @@ function resolveDailyActivitySpend(activity: LiteLlmDailyActivity): { todaySpendreturn { todaySpend: Number.isFinite(totalSpend) ? totalSpend : 0 };}-async function fetchOnce(): Promise<ClaudeAccountUsageSnapshot | null> {+async function fetchOnce(authenticatedUserId?: string): Promise<ClaudeAccountUsageSnapshot | null> {// 币种优先取账号目录声明。取不到时**不放弃整个快照**,回落本地账本币种:// 手填 XD key 是明确支持的兜底流程(Model Access 处于 disabled / failed 时),那时没有// 目录可推导,若直接 return 会让这些会话永久看不到账号配额 —— 比"币种按账本回落"更糟。// 回落值与账本写入侧同源(currentLedgerCurrency),不会与同一行的其它金额混排。const currency =- (await getGatewayAccountCurrency(getAuthState().user?.id)) ?? currentLedgerCurrency();+ (await getGatewayAccountCurrency(authenticatedUserId)) ?? currentLedgerCurrency();const apiKey = readClaudeApiKey();// 直连真上游,不走本地 anthropic-compat-proxy —— 这条账号查询路径跟 Claude Code 子进程// 无关,proxy 只服务于子进程的 chat completion 请求。@@ -231,19 +252,32 @@ async function fetchOnce(): Promise<ClaudeAccountUsageSnapshot | null> {* - 首次成功 fetch 后启动空闲轮询定时器 (5 分钟周期, 保活 dailyBaselineStore.lastSeenSpend)*/export async function triggerClaudeAccountUsageRefresh(force = false): Promise<void> {- if (fetchInFlight) return;+ const owner = currentQuotaOwner();+ if (!owner) return;+ if (fetchInFlight) {+ if (fetchOwnerKey !== owner.key) refreshQueued = true;+ return;+ }if (!force && Date.now() - lastFetchAt < THROTTLE_MS) return;fetchInFlight = true;+ fetchOwnerKey = owner.key;lastFetchAt = Date.now();try {- const next = await fetchOnce();+ const next = await fetchOnce(owner.authenticatedUserId);if (!next) return;+ if (currentQuotaOwner()?.key !== owner.key) return;snapshot = next;+ snapshotOwnerKey = owner.key;broadcast(next);ensureIdlePoll();} finally {fetchInFlight = false;+ fetchOwnerKey = null;+ if (refreshQueued) {+ refreshQueued = false;+ void triggerClaudeAccountUsageRefresh(true);+ }}}@@ -263,7 +297,8 @@ function ensureIdlePoll(): void {}export function readClaudeAccountUsageSnapshot(): ClaudeAccountUsageSnapshot | null {- return snapshot;+ const owner = currentQuotaOwner();+ return owner && snapshotOwnerKey === owner.key ? snapshot : null;}function broadcast(payload: ClaudeAccountUsageSnapshot): void {diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.tsindex c4c433eee2..9e004b36e5 100644--- a/apps/desktop/src/main/usage/modelPricing.ts+++ b/apps/desktop/src/main/usage/modelPricing.ts@@ -1,5 +1,5 @@/**- * modelPricing — Desktop 的 provider-scoped 价格投影。+ * modelPricing — Cindy AI Gateway 的 XD 实际报价投影。** XD 模型与价格只来自 model-access-server 的同一次 GET /models 响应。这里不再* 直接请求 LiteLLM;模型同步成功时整体替换 XD quote,失败时保留上一份成功快照。@@ -12,14 +12,7 @@ import path from 'node:path';import { app, BrowserWindow } from 'electron';import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';-import {- gatewayLedgerCurrency,- gatewayPricingCatalog,- getModelPriceQuote,- providerReferencePriceQuote,- registryPricingCatalog,- subscriptionDirectPriceQuote,-} from '../../shared/modelPriceQuote.js';+import { gatewayLedgerCurrency, gatewayPricingCatalog } from '../../shared/modelPriceQuote.js';import type { ModelAccessGatewayModel } from '../../shared/modelAccess.js';import { providerSecretStorageKey } from '../../shared/providerSecrets.js';import {@@ -37,15 +30,6 @@ import { currentLedgerCurrency, setActiveLedgerCurrency } from './ledgerCurrencyimport { createLogger } from '../logger.js';import { getClientEndpoint } from '../clientEndpointsService.js';import { resolveOwnerScopedSecretStorageKey } from '../secrets/providerSecretStore.js';-import { getActiveCatalog } from '../maker-host/active-catalog.js';-import {- applyModelPriceOverrides,- mergeStoredModelPriceOverride,- type ModelPriceOverridesSnapshot,-} from './modelPriceOverrideStore.js';--export type { ModelPriceOverridesSnapshot } from './modelPriceOverrideStore.js';-export { readModelPriceOverridesSnapshot } from './modelPriceOverrideStore.js';export { getModelPriceQuote } from '../../shared/modelPriceQuote.js';export type {@@ -309,7 +293,7 @@ async function hydrateFromDisk(scope: string): Promise<ModelPricingCatalog | nulcacheAt = Number(raw.fetchedAt);// 账本币种必须在这里恢复,而不是只在 getGatewayAccountCurrency 里:那个函数只服务// 可选的账号配额查询,而计费热路径(register.ts 的 turn 记账、prewarm)走的是- // getModelPricing / getModelPricingForModel。冷启动只命中磁盘缓存(/models 尚未+ // getGatewayModelPricing / getGatewayModelPricingForModel。冷启动只命中磁盘缓存(/models 尚未// 完成或失败)时若不在此同步,currentLedgerCurrency() 会回落构建默认币种,把该账号// 用缓存报价算出的金额当异币种丢弃 —— 等于这一段时间完全不计费。gatewayAccountCurrency = raw.accountCurrency;@@ -348,23 +332,6 @@ function broadcastPricing(pricing: ModelPricingCatalog | null): void {}}-function effectivePricingCatalog(gatewayPricing: ModelPricingCatalog | null): ModelPricingCatalog {- const registry = getActiveCatalog().modelRegistry;- const reference = registryPricingCatalog(registry);- return applyModelPriceOverrides(- {- ...reference,- ...(gatewayPricing?.xd ? { xd: gatewayPricing.xd } : {}),- },- registry,- );-}--export function broadcastEffectiveModelPricing(): void {- const scope = currentScope();- broadcastPricing(effectivePricingCatalog(cacheScope === scope ? cache : null));-}-/*** 与模型同步同快照更新 XD quote。models 非空但没有标准 input/output 价格时,* 价格投影会被清空,不复活旧模型价格。@@ -386,7 +353,7 @@ export function replaceGatewayModelPricing(// 账本写入层据此判断"这一笔是不是本账号的结算币种"。目录为空(登出 / clear)或混合// 币种时返回 null,账本回退到「上次已知 → USD」,绝不按区域猜。//- // 顺序要紧:先落 active,下面的 catalog 兜底才能读到本次刚确认的币种;本次没确认时+ // 顺序要紧:先落 active,下面的 XD 报价投影兜底才能读到本次刚确认的币种;本次没确认时// currentLedgerCurrency() 给出的也是上次已知值,而不是区域默认值。setActiveLedgerCurrency(gatewayAccountCurrency);const previousLedgerCurrency = activeLedgerCurrencySnapshot;@@ -409,7 +376,7 @@ export function replaceGatewayModelPricing(cacheAt = Date.now();hydratedScopes.add(scope);void writeDiskCache(scope, pricing, gatewayAccountCurrency, cacheAt);- broadcastPricing(effectivePricingCatalog(pricing));+ broadcastPricing(pricing);return pricing;}@@ -433,10 +400,9 @@ export function isModelPricingRefreshInFlight(): boolean {return modelSyncInflight !== null;}-export async function getModelPricing(): Promise<ModelPricingCatalog | null> {+export async function getGatewayModelPricing(): Promise<ModelPricingCatalog | null> {const scope = currentScope();- const gatewayPricing = cacheScope === scope ? cache : await hydrateFromDisk(scope);- return effectivePricingCatalog(gatewayPricing);+ return cacheScope === scope ? cache : await hydrateFromDisk(scope);}/**@@ -475,143 +441,15 @@ export async function getGatewayAccountCurrency(// 本轮 /models 没跑成时,磁盘缓存里的报价同样能定出币种。hydrateFromDisk 内部会在// 落盘缓存生效的同时把币种写回缓存与账本事实源(那里才是所有取价路径的共同入口),// 所以这里只需触发一次 hydrate 再读结果。- await getModelPricing();+ await getGatewayModelPricing();if (gatewayAccountCurrencyScope === scope) return gatewayAccountCurrency;return cacheScope === scope ? gatewayLedgerCurrency(cache) : null;}-/**- * 计费热路径等待模型同步已经落下的本地投影,不再自己联网。providerId 是必需的,- * 同模型从 XD/OpenAI/订阅来源进入时不会串价。- */-export async function getModelPricingForModel(- providerId: string | null | undefined,- modelId: string,-): Promise<ModelPricingCatalog | null> {+/** 计费热路径只等待 `/models` 写入 XD 报价,不读取 Catalog。 */+export async function getGatewayModelPricingForModel(): Promise<ModelPricingCatalog | null> {await waitForModelPricingSync();- const pricing = await getModelPricing();- void getModelPriceQuote(pricing, providerId, modelId);- return pricing;-}--/**- * Codex 订阅轮的估算价,按显式来源 provider 取该 provider 的 registry 参考价- * (含用户价格覆盖)。openai 之外的订阅来源(如内置 anthropic 的 Claude.ai 订阅)- * 也走各自的日期定价路由,不能一律套 OpenAI 价表。- */-export function getCodexProviderSubscriptionValuePrice(- providerId: string,- modelId: string,- pricing: ModelPricingCatalog | null | undefined,- at?: string | Date,- overrides?: ModelPriceOverridesSnapshot,-): ModelPriceQuote | undefined {- const effective = getModelPriceQuote(pricing, providerId, modelId, 'codex');- if (effective?.source === 'user-override') {- if (at === undefined) return effective;- // 目录里烘焙的 user-override 是按当前日期合并的;历史窗口跨过参考价生效边界时,- // 未覆盖字段必须按 at 时点的参考价重新合并,不能直接回用当前合并结果。- return (- mergeStoredModelPriceOverride(- { providerId, agent: 'codex', modelId: effective.modelId },- providerReferencePriceQuote(- providerId,- effective.modelId,- getActiveCatalog().modelRegistry,- { agent: 'codex', at },- ),- overrides,- ) ?? effective- );- }- const reference = providerReferencePriceQuote(- providerId,- modelId,- getActiveCatalog().modelRegistry,- { agent: 'codex', at },- );- return reference ?? (at === undefined ? effective : undefined);-}--export function getCodexSubscriptionValuePrice(- modelId: string,- pricing: ModelPricingCatalog | null | undefined,- at?: string | Date,- overrides?: ModelPriceOverridesSnapshot,-): ModelPriceQuote | undefined {- return getCodexProviderSubscriptionValuePrice('openai', modelId, pricing, at, overrides);-}--export function getClaudeSubscriptionValuePrice(- modelId: string,- pricing: ModelPricingCatalog | null | undefined,- at?: string | Date,- overrides?: ModelPriceOverridesSnapshot,-): ModelPriceQuote | undefined {- const effective = getModelPriceQuote(pricing, 'anthropic', modelId, 'claude-code');- if (effective?.source === 'user-override') {- if (at === undefined) return effective;- // 同 getCodexSubscriptionValuePrice:历史估值按 at 时点参考价重新合并稀疏覆盖。- return (- mergeStoredModelPriceOverride(- { providerId: 'anthropic', agent: 'claude-code', modelId: effective.modelId },- providerReferencePriceQuote(- 'anthropic',- effective.modelId,- getActiveCatalog().modelRegistry,- { agent: 'claude-code', at },- ),- overrides,- ) ?? effective- );- }- const reference = providerReferencePriceQuote(- 'anthropic',- modelId,- getActiveCatalog().modelRegistry,- { agent: 'claude-code', at },- );- return reference ?? (at === undefined ? effective : undefined);-}--export function getSubscriptionDirectValuePrice(- modelId: string,- agent?: 'claude-code' | 'codex',- pricing?: ModelPricingCatalog | null,- at?: string | Date,- overrides?: ModelPriceOverridesSnapshot,-): ModelPriceQuote | undefined {- const registry = getActiveCatalog().modelRegistry;- const fallback = subscriptionDirectPriceQuote(- modelId,- registry,- agent,- at,- );- const routingQuote = fallback ?? subscriptionDirectPriceQuote(modelId, registry, agent);- if (!routingQuote) return undefined;- const effective = getModelPriceQuote(pricing, routingQuote.providerId, modelId, agent);- const quote =- effective?.source === 'user-override'- ? at === undefined || agent === undefined- ? effective- : // 同上:历史窗口内的订阅直连估值也要按 at 时点参考价重新合并稀疏覆盖。- (mergeStoredModelPriceOverride(- { providerId: effective.providerId, agent, modelId: effective.modelId },- providerReferencePriceQuote(effective.providerId, effective.modelId, registry, {- agent,- at,- }),- overrides,- ) ?? effective)- : fallback;- if (!quote) return undefined;- return {- ...quote,- modelId,- source:- quote.source === 'provider-reference' ? 'subscription-reference' : quote.source,- };+ return await getGatewayModelPricing();}/**@@ -631,7 +469,7 @@ export async function prewarmModelPricing(): Promise<void> {);}try {- await getModelPricing();+ await getGatewayModelPricing();} catch (err) {log.debug('prewarm model pricing failed:', err instanceof Error ? err.message : String(err));}diff --git a/apps/desktop/src/main/usage/referenceModelPricing.ts b/apps/desktop/src/main/usage/referenceModelPricing.tsnew file mode 100644index 0000000000..fc6afe4c98--- /dev/null+++ b/apps/desktop/src/main/usage/referenceModelPricing.ts@@ -0,0 +1,149 @@+/**+ * 非 XD 渠道的参考报价投影。+ *+ * 数据只来自公共 Model Registry 与用户覆盖,用于 BYOK / 订阅价值估算。Cindy AI+ * Gateway 的模型与售价由 modelPricing.ts 独占维护,本模块显式拒绝 XD 数据。+ */++import { BrowserWindow } from 'electron';++import {+ getModelPriceQuote,+ providerReferencePriceQuote,+ registryPricingCatalog,+ subscriptionDirectPriceQuote,+} from '../../shared/modelPriceQuote.js';+import type { ModelPriceQuote, ModelPricingCatalog } from '../../shared/regionalMoney.js';+import { getActiveCatalog } from '../maker-host/active-catalog.js';+import {+ applyModelPriceOverrides,+ mergeStoredModelPriceOverride,+ type ModelPriceOverridesSnapshot,+} from './modelPriceOverrideStore.js';++export type { ModelPriceOverridesSnapshot } from './modelPriceOverrideStore.js';+export { readModelPriceOverridesSnapshot } from './modelPriceOverrideStore.js';++export const REFERENCE_MODEL_PRICING_CHANGED_CHANNEL = 'usage:reference-model-pricing-changed';++/** Catalog 刷新只重建非 XD 参考价;registryPricingCatalog 本身也会过滤 XD route。 */+export function getReferenceModelPricing(): ModelPricingCatalog {+ const registry = getActiveCatalog().modelRegistry;+ return applyModelPriceOverrides(registryPricingCatalog(registry), registry);+}++export function broadcastReferenceModelPricing(): void {+ const pricing = getReferenceModelPricing();+ for (const win of BrowserWindow.getAllWindows()) {+ if (!win.isDestroyed()) {+ win.webContents.send(REFERENCE_MODEL_PRICING_CHANGED_CHANNEL, pricing);+ }+ }+}++/** 按显式来源估算 Codex 订阅轮价值,不读取 XD Gateway 报价。 */+export function getCodexProviderSubscriptionValuePrice(+ providerId: string,+ modelId: string,+ pricing: ModelPricingCatalog | null | undefined,+ at?: string | Date,+ overrides?: ModelPriceOverridesSnapshot,+): ModelPriceQuote | undefined {+ if (providerId === 'xd') return undefined;+ const effective = getModelPriceQuote(pricing, providerId, modelId, 'codex');+ if (effective?.source === 'user-override') {+ if (at === undefined) return effective;+ return (+ mergeStoredModelPriceOverride(+ { providerId, agent: 'codex', modelId: effective.modelId },+ providerReferencePriceQuote(+ providerId,+ effective.modelId,+ getActiveCatalog().modelRegistry,+ { agent: 'codex', at },+ ),+ overrides,+ ) ?? effective+ );+ }+ const reference = providerReferencePriceQuote(+ providerId,+ modelId,+ getActiveCatalog().modelRegistry,+ { agent: 'codex', at },+ );+ return reference ?? (at === undefined ? effective : undefined);+}++export function getCodexSubscriptionValuePrice(+ modelId: string,+ pricing: ModelPricingCatalog | null | undefined,+ at?: string | Date,+ overrides?: ModelPriceOverridesSnapshot,+): ModelPriceQuote | undefined {+ return getCodexProviderSubscriptionValuePrice('openai', modelId, pricing, at, overrides);+}++export function getClaudeSubscriptionValuePrice(+ modelId: string,+ pricing: ModelPricingCatalog | null | undefined,+ at?: string | Date,+ overrides?: ModelPriceOverridesSnapshot,+): ModelPriceQuote | undefined {+ const effective = getModelPriceQuote(pricing, 'anthropic', modelId, 'claude-code');+ if (effective?.source === 'user-override') {+ if (at === undefined) return effective;+ return (+ mergeStoredModelPriceOverride(+ { providerId: 'anthropic', agent: 'claude-code', modelId: effective.modelId },+ providerReferencePriceQuote(+ 'anthropic',+ effective.modelId,+ getActiveCatalog().modelRegistry,+ { agent: 'claude-code', at },+ ),+ overrides,+ ) ?? effective+ );+ }+ const reference = providerReferencePriceQuote(+ 'anthropic',+ modelId,+ getActiveCatalog().modelRegistry,+ { agent: 'claude-code', at },+ );+ return reference ?? (at === undefined ? effective : undefined);+}++export function getSubscriptionDirectValuePrice(+ modelId: string,+ agent?: 'claude-code' | 'codex',+ pricing?: ModelPricingCatalog | null,+ at?: string | Date,+ overrides?: ModelPriceOverridesSnapshot,+): ModelPriceQuote | undefined {+ const registry = getActiveCatalog().modelRegistry;+ const fallback = subscriptionDirectPriceQuote(modelId, registry, agent, at);+ const routingQuote = fallback ?? subscriptionDirectPriceQuote(modelId, registry, agent);+ if (!routingQuote || routingQuote.providerId === 'xd') return undefined;+ const effective = getModelPriceQuote(pricing, routingQuote.providerId, modelId, agent);+ const quote =+ effective?.source === 'user-override'+ ? at === undefined || agent === undefined+ ? effective+ : (mergeStoredModelPriceOverride(+ { providerId: effective.providerId, agent, modelId: effective.modelId },+ providerReferencePriceQuote(effective.providerId, effective.modelId, registry, {+ agent,+ at,+ }),+ overrides,+ ) ?? effective)+ : fallback;+ if (!quote) return undefined;+ return {+ ...quote,+ modelId,+ source: quote.source === 'provider-reference' ? 'subscription-reference' : quote.source,+ };+}diff --git a/apps/desktop/src/main/usage/usageHistory.ts b/apps/desktop/src/main/usage/usageHistory.tsindex f2fa3b793e..f0b3cbf255 100644--- a/apps/desktop/src/main/usage/usageHistory.ts+++ b/apps/desktop/src/main/usage/usageHistory.ts@@ -23,20 +23,22 @@ import { getAllSpendDays, localDayKey } from '../localDb/dailySpend';import { getModelUsageSince, type DailyModelUsageRow } from '../localDb/dailyModelUsage';import { getCurrentDbClientUserId } from '../localDb/client/current';import { createLogger } from '../logger';+import {+ getGatewayModelPricing,+ isModelPricingRefreshInFlight,+ type ModelPricingMap,+} from './modelPricing';import {getClaudeSubscriptionValuePrice,getCodexProviderSubscriptionValuePrice,getCodexSubscriptionValuePrice,- getModelPricing,+ getReferenceModelPricing,getSubscriptionDirectValuePrice,- isModelPricingRefreshInFlight,readModelPriceOverridesSnapshot,type ModelPriceOverridesSnapshot,- type ModelPricingMap,-} from './modelPricing';+} from './referenceModelPricing';import { computePriceQuoteTurnMoney } from './turnCostCalculator';import { currentLedgerCurrency } from './ledgerCurrency.js';-import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';import {addCompatibleRegionalMoney,normalizeRegionalMoney,@@ -227,7 +229,8 @@ export function computeAnomaly(export interface UsageHistoryDeps {getAllSpendDays(): Promise<Array<{ day: string; monies: RegionalMoney[] }>>;getModelUsageSince(sinceDayKey: string): Promise<DailyModelUsageRow[]>;- getModelPricing(): Promise<ModelPricingMap | null>;+ getGatewayModelPricing(): Promise<ModelPricingMap | null>;+ getReferenceModelPricing(): ModelPricingMap;/** 覆盖记录快照,一次聚合读一份——历史重合并逐行读文件会在慢盘上拖垮 Main 线程。 */getModelPriceOverridesSnapshot(): ModelPriceOverridesSnapshot;isModelPricingRefreshInFlight(): boolean;@@ -237,7 +240,8 @@ export interface UsageHistoryDeps {const defaultDeps: UsageHistoryDeps = {getAllSpendDays,getModelUsageSince,- getModelPricing,+ getGatewayModelPricing,+ getReferenceModelPricing,getModelPriceOverridesSnapshot: readModelPriceOverridesSnapshot,isModelPricingRefreshInFlight,todayKey: () => localDayKey(),@@ -516,11 +520,12 @@ export async function readUsageHistoryWith(// 账本币种与写入侧同一事实源(currentLedgerCurrency):由服务端按账号所属租户下发,// 不保证等于发行区域。按区域取会把以 USD 结算的账号在 CN 构建上的每一行判成异币种、// 整段归零成不计费。历史遗留的异币种行(换号 / 跨区)仍按 keepCompatibleMoney 归零。- const [spendDayRows, pricing] = await Promise.all([+ const [spendDayRows, , pricing] = await Promise.all([deps.getAllSpendDays(),- // getModelPricing 只读内存或账号作用域内的磁盘快照,不发网络请求。必须等它完成,+ // Gateway 报价只读内存或账号作用域内的磁盘快照,不发网络请求。必须等它完成,// 因为 hydrateFromDisk 还负责恢复同一快照声明的账本币种。- deps.getModelPricing(),+ deps.getGatewayModelPricing(),+ Promise.resolve(deps.getReferenceModelPricing()),]);// 必须在上面 pricing 恢复之后再读:hydrateFromDisk 会在磁盘缓存生效的同时回写账本币种,// 而 prewarmModelPricing 与首页首次聚合是并发的。先读会拿到构建默认值,把该账号的日账与diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.tsindex 9755376ef7..16a2c1d35d 100644--- a/apps/desktop/src/main/usageBroadcaster.ts+++ b/apps/desktop/src/main/usageBroadcaster.ts@@ -23,7 +23,7 @@import { BrowserWindow } from 'electron';import { incrementDailySpend, getTodaySpend, localDayKey } from './localDb/dailySpend';-import { getModelPricing } from './usage/modelPricing';+import { getGatewayModelPricing } from './usage/modelPricing';import type { XaiRateLimitSnapshot } from '../shared/xaiRateLimit';import { incrementDailyModelUsage, type DailyModelUsageDelta } from './localDb/dailyModelUsage';import { getDbClient } from './localDb/client/current';@@ -136,9 +136,9 @@ export async function recordTurnSpend(/** Claude 今日 USD 累计 (供 IPC handler / 内部消费)。 */export async function readTodaySpend(): Promise<TodaySpendPayload> {// getTodaySpend 要按账本币种从多币种日账里挑行,而账本币种由报价快照恢复。- // getModelPricing 只读内存或磁盘快照、不发网络请求,等它一下就能避免冷启动首帧+ // getGatewayModelPricing 只读内存或磁盘快照、不发网络请求,等它一下就能避免冷启动首帧// 按兜底币种折叠掉本账号真正的那一行(与 usageHistory 里同一个理由)。- await getModelPricing().catch(() => null);+ await getGatewayModelPricing().catch(() => null);const money = await getTodaySpend();return {day: localDayKey(),diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex c61a456bd1..e5a2a54038 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -519,6 +519,7 @@ const fanOutMakerSessionBackgroundActivityChanged = createIpcFanOut('maker:sessiconst fanOutMakerUsageTodaySpend = createIpcFanOut('usage:today-spend-changed'); // Claude USDconst fanOutMakerUsageTodayTokens = createIpcFanOut('usage:today-tokens-changed'); // Codex tokenconst fanOutMakerUsageModelPricing = createIpcFanOut('usage:model-pricing-changed');+const fanOutMakerUsageReferenceModelPricing = createIpcFanOut('usage:reference-model-pricing-changed');const fanOutMakerUsageClaudeAccount = createIpcFanOut('usage:claude-account-changed'); // Claude 月度配额const fanOutMakerUsageCodexAccount = createIpcFanOut('usage:codex-account-changed'); // Codex 订阅用量const fanOutMakerUsageXaiRateLimit = createIpcFanOut('usage:xai-rate-limit-changed'); // xAI bridge 限流快照@@ -5337,10 +5338,14 @@ contextBridge.exposeInMainWorld('electronAPI', {/** Claude 订阅账号余量 (5h/周/分模型窗口, cached-first, main 侧按需后台刷新)。 */getClaudeSubscription: (): Promise<unknown | null> =>ipcRenderer.invoke('maker:usage:claude-subscription'),- /** provider-scoped 模型单价表,由 model-access /models 同次快照更新。 */+ /** Cindy AI /models 下发的 XD 原生报价。 */getModelPricing: (): Promise<unknown | null> =>ipcRenderer.invoke('maker:usage:model-pricing-v2'),onModelPricingChanged: fanOutMakerUsageModelPricing,+ /** 非 XD Provider 的 Catalog 参考价与用户覆盖。 */+ getReferenceModelPricing: (): Promise<unknown> =>+ ipcRenderer.invoke('maker:usage:reference-model-pricing'),+ onReferenceModelPricingChanged: fanOutMakerUsageReferenceModelPricing,/** 用量历史聚合 (首页仪表盘: 热力图 + streak + 按模型拆分, main 侧算好)。 */getHistory: (opts?: { days?: number; forceRefresh?: boolean }): Promise<unknown> =>ipcRenderer.invoke('maker:usage:history', opts),diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx b/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsxindex 132a4ae144..3ea4d79a42 100644--- a/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx+++ b/apps/desktop/src/renderer/__tests__/modelSelectorProviderGroups.test.tsx@@ -92,7 +92,8 @@ vi.mock('@/hooks/useConnectedSource', () => ({}));vi.mock('@/hooks/useModelPricing', () => ({- useModelPricing: () => ({}),+ useGatewayModelPricing: () => ({}),+ useReferenceModelPricing: () => ({}),}));const providersRef = vi.hoisted(() => {diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.tsindex ae825a4ac2..817817df6d 100644--- a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts+++ b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts@@ -235,10 +235,11 @@ const pricingRef = vi.hoisted(() => {return { DEFAULT_PRICING, pricing: DEFAULT_PRICING as unknown, renderCalls: 0 };});vi.mock('@/hooks/useModelPricing', () => ({- useModelPricing: () => {+ useGatewayModelPricing: () => {pricingRef.renderCalls += 1;return pricingRef.pricing;},+ useReferenceModelPricing: () => pricingRef.pricing,}));// 可变 providers mock:默认 = anthropic fixture(分段/hover 用例依赖),diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex 24f8189b47..9d716dfc53 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@ -41,7 +41,7 @@ import {} from '@/hooks/useAgentCapabilities';import { useApiKey } from '@/hooks/useApiKey';import { useConnectedSource } from '@/hooks/useConnectedSource';-import { useModelPricing } from '@/hooks/useModelPricing';+import { useGatewayModelPricing, useReferenceModelPricing } from '@/hooks/useModelPricing';import { useProviders } from '@/hooks/useProviders';import {evictDeviceProviders,@@ -635,8 +635,15 @@ export function resolveRemoteModelListStatus({}export function ModelSelectorContent(props: ModelSelectorContentProps) {- const pricing = useModelPricing();- return <ModelSelectorContentView {...props} pricing={pricing} />;+ const gatewayPricing = useGatewayModelPricing();+ const referencePricing = useReferenceModelPricing();+ return (+ <ModelSelectorContentView+ {...props}+ gatewayPricing={gatewayPricing}+ referencePricing={referencePricing}+ />+ );}function ModelSelectorContentView({@@ -666,8 +673,12 @@ function ModelSelectorContentView({agentSwitch,discoveringModels = false,interactionDisabled = false,- pricing,-}: ModelSelectorContentProps & { pricing: ModelPricingCatalog | null }) {+ gatewayPricing,+ referencePricing,+}: ModelSelectorContentProps & {+ gatewayPricing: ModelPricingCatalog | null;+ referencePricing: ModelPricingCatalog | null;+}) {// 当前来源解析器:已建会话 = 实际路由口径(含停用拷贝),其余 = 准入口径。const resolveCurrentSourceId = actualRoute ? actualSourceIdForModel : effectiveSourceIdForModel;const { t } = useTranslation();@@ -950,9 +961,8 @@ function ModelSelectorContentView({};// ── 模型单价 ─────────────────────────────────────────────────────────────- // providerId 是价格索引的一部分。同模型经 XD / OpenAI / Anthropic 等来源出现时,- // 必须按实际行来源查价,不能退化为 pricing[modelId]。只有 XD Gateway 目录价会- // 叠加 CatalogModel.cost 作为折后展示价;其它来源保持价格源自带的币种。+ // XD 实际报价与非 XD Catalog 参考价是两份独立快照。这里只按行来源选择快照,+ // 相同 modelId 不跨 Provider 复用或兜底。const pricePresentationOf = (providerId: string | null, id: string) => {// device-link 只同步被控端 provider 目录,不同步价格快照;不能把控制端价格与// 被控端 CatalogModel.cost 拼成一个展示结果。在协议补齐前远程选择器不展示价格。@@ -962,6 +972,7 @@ function ModelSelectorContentView({(currentAgentKind? resolveCurrentSourceId(providers, currentProviderId, id, currentAgentKind): null);+ const pricing = effectiveProviderId === 'xd' ? gatewayPricing : referencePricing;const quote = getModelPriceQuote(pricing,effectiveProviderId,@@ -969,7 +980,7 @@ function ModelSelectorContentView({currentAgentKind ?? undefined,);if (effectiveProviderId === 'xd' && (!quote || quote.source === 'gateway')) {- if (!quote && pricing == null) return null;+ if (!quote && gatewayPricing == null) return null;const effectiveProvider = providers.find((provider) => provider.id === effectiveProviderId);const effectiveCost =effectiveProvider && currentAgentKind@@ -1514,7 +1525,6 @@ function ModelSelectorContentView({const renderModelItem = (provider: ProviderView | null, model: RowModel) => {const providerId = provider?.id ?? null;const isSelected = isSelectedRow(providerId, model.id);- const isBudgetModel = model.id.startsWith('codex/');const isSubscriptionModel = provider?.access?.kind === 'subscription';const disabled = interactionDisabled || modelDisabledOf(model.id);const disabledReason = subscriptionDirectDisabledReason(model.id);@@ -1644,18 +1654,13 @@ function ModelSelectorContentView({/>)}</span>- {(isSubscriptionModel || isBudgetModel || rowPromotionLabel) && (+ {(isSubscriptionModel || rowPromotionLabel) && (<span data-model-tags className="ml-auto flex shrink-0 items-center gap-1.5">{isSubscriptionModel && (<span className="inline-flex shrink-0 items-center rounded-full bg-[var(--surface-chip)] px-2 py-[1px] text-[11px] font-medium text-[var(--text-secondary)]">{t('settings.providers.models.subscription')}</span>)}- {isBudgetModel && (- <span className="inline-flex shrink-0 items-center rounded-full bg-[var(--model-budget-badge-bg)] px-2 py-[1px] text-[11px] font-medium text-[var(--model-budget-badge-text)]">- {t('newChat.modelSelector.meta.budgetDiscount')}- </span>- )}{rowPromotionLabel && (<ModelPromotionBadge>{rowPromotionLabel}</ModelPromotionBadge>)}@@ -2068,7 +2073,8 @@ export function ModelSelector({const cc = useAgentCapabilities('claude-code', deviceId);const codex = useAgentCapabilities('codex', deviceId);const pi = useAgentCapabilities('pi', deviceId);- const pricing = useModelPricing();+ const gatewayPricing = useGatewayModelPricing();+ const referencePricing = useReferenceModelPricing();// trigger 的来源 icon / 当前模型也按来源取:device-link 用被控端供应商目录(否则控制端本地// 查不到被控端独有模型 → currentModel undefined → label 退成 "Select model")。const localProviders = useProviders();@@ -2560,7 +2566,8 @@ export function ModelSelector({agentSwitch={contentAgentSwitch}discoveringModels={showDiscoveryPending && discovery.pending}interactionDisabled={switching || disabled}- pricing={pricing}+ gatewayPricing={gatewayPricing}+ referencePricing={referencePricing}followSession={fallbackOption? {diff --git a/apps/desktop/src/renderer/hooks/__tests__/useModelPricing.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useModelPricing.test.tsindex 031bcdb53f..251f1a0aca 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useModelPricing.test.ts+++ b/apps/desktop/src/renderer/hooks/__tests__/useModelPricing.test.ts@@ -14,16 +14,22 @@ function deferred<T>() {return { promise, resolve };}-let useModelPricing: typeof import('../useModelPricing').useModelPricing;+let useGatewayModelPricing: typeof import('../useModelPricing').useGatewayModelPricing;+let useReferenceModelPricing: typeof import('../useModelPricing').useReferenceModelPricing;+let setDataOwnerGeneration: typeof import('../../contexts/dataOwnerGeneration').setDataOwnerGeneration;describe('useModelPricing', () => {beforeEach(async () => {vi.resetModules();delete (window as unknown as { electronAPI?: unknown }).electronAPI;- ({ useModelPricing } = await import('../useModelPricing'));+ const ownerModule = await import('../../contexts/dataOwnerGeneration');+ ownerModule.__testing.reset();+ setDataOwnerGeneration = ownerModule.setDataOwnerGeneration;+ setDataOwnerGeneration('account-a');+ ({ useGatewayModelPricing, useReferenceModelPricing } = await import('../useModelPricing'));});- it('does not let a stale initial IPC result overwrite a newer pricing push', async () => {+ it('does not let a stale initial IPC result overwrite a newer XD pricing push', async () => {const initialRead = deferred<ModelPricingCatalog | null>();const listeners = new Set<PricingListener>();const usage = {@@ -33,11 +39,9 @@ describe('useModelPricing', () => {return () => listeners.delete(listener);}),};- (- window as unknown as {- electronAPI: { maker: { usage: typeof usage } };- }- ).electronAPI = { maker: { usage } };+ (window as unknown as { electronAPI: { maker: { usage: typeof usage } } }).electronAPI = {+ maker: { usage },+ };const pricing: ModelPricingCatalog = {xd: {'early-model': {@@ -52,7 +56,7 @@ describe('useModelPricing', () => {},};- const hook = renderHook(() => useModelPricing());+ const hook = renderHook(() => useGatewayModelPricing());await waitFor(() => expect(listeners.size).toBe(1));act(() => {@@ -68,4 +72,235 @@ describe('useModelPricing', () => {expect(hook.result.current).toEqual(pricing);expect(usage.getModelPricing).toHaveBeenCalledOnce();});++ it('keeps XD pricing when the reference catalog becomes invalid', async () => {+ const referenceListeners = new Set<PricingListener>();+ const gatewayPricing: ModelPricingCatalog = {+ xd: {+ model: {+ providerId: 'xd',+ modelId: 'model',+ currency: 'CNY',+ source: 'gateway',+ approximate: false,+ inputPerMtok: 3,+ outputPerMtok: 6,+ },+ },+ };+ const usage = {+ getModelPricing: vi.fn(async () => gatewayPricing),+ onModelPricingChanged: vi.fn(() => () => undefined),+ getReferenceModelPricing: vi.fn(async () => ({+ openai: {+ model: {+ providerId: 'openai',+ modelId: 'model',+ currency: 'USD',+ source: 'provider-reference',+ approximate: true,+ inputPerMtok: 1,+ outputPerMtok: 2,+ },+ },+ })),+ onReferenceModelPricingChanged: vi.fn((listener: PricingListener) => {+ referenceListeners.add(listener);+ return () => referenceListeners.delete(listener);+ }),+ };+ (window as unknown as { electronAPI: { maker: { usage: typeof usage } } }).electronAPI = {+ maker: { usage },+ };++ const hook = renderHook(() => ({+ gateway: useGatewayModelPricing(),+ reference: useReferenceModelPricing(),+ }));+ await waitFor(() => expect(hook.result.current.gateway).toEqual(gatewayPricing));++ act(() => {+ for (const listener of referenceListeners) listener({ xd: gatewayPricing.xd });+ });+ expect(hook.result.current.reference).toBeNull();+ expect(hook.result.current.gateway).toEqual(gatewayPricing);+ });++ it('accepts agent-scoped user overrides in the reference catalog', async () => {+ const referencePricing: ModelPricingCatalog = {+ anthropic: {+ ['claude-sonnet-5\u0000claude-code']: {+ providerId: 'anthropic',+ modelId: 'claude-sonnet-5',+ currency: 'USD',+ source: 'user-override',+ approximate: true,+ inputPerMtok: 3,+ outputPerMtok: 15,+ },+ },+ };+ const usage = {+ getReferenceModelPricing: vi.fn(async () => referencePricing),+ onReferenceModelPricingChanged: vi.fn(() => () => undefined),+ };+ (window as unknown as { electronAPI: { maker: { usage: typeof usage } } }).electronAPI = {+ maker: { usage },+ };++ const hook = renderHook(() => useReferenceModelPricing());+ await waitFor(() => expect(hook.result.current).toEqual(referencePricing));+ });++ it('reloads both pricing chains after the data owner changes', async () => {+ const gatewayA: ModelPricingCatalog = {+ xd: {+ model: {+ providerId: 'xd',+ modelId: 'model',+ currency: 'CNY',+ source: 'gateway',+ approximate: false,+ inputPerMtok: 1,+ outputPerMtok: 2,+ },+ },+ };+ const gatewayB: ModelPricingCatalog = {+ xd: {+ model: {+ providerId: 'xd',+ modelId: 'model',+ currency: 'USD',+ source: 'gateway',+ approximate: false,+ inputPerMtok: 3,+ outputPerMtok: 6,+ },+ },+ };+ const referenceA: ModelPricingCatalog = {+ openai: {+ model: {+ providerId: 'openai',+ modelId: 'model',+ currency: 'CNY',+ source: 'user-override',+ approximate: true,+ inputPerMtok: 10,+ outputPerMtok: 20,+ },+ },+ };+ const referenceB: ModelPricingCatalog = {+ openai: {+ model: {+ providerId: 'openai',+ modelId: 'model',+ currency: 'USD',+ source: 'provider-reference',+ approximate: true,+ inputPerMtok: 4,+ outputPerMtok: 8,+ },+ },+ };+ const usage = {+ getModelPricing: vi+ .fn<() => Promise<ModelPricingCatalog | null>>()+ .mockResolvedValueOnce(gatewayA)+ .mockResolvedValueOnce(gatewayB),+ onModelPricingChanged: vi.fn(() => () => undefined),+ getReferenceModelPricing: vi+ .fn<() => Promise<ModelPricingCatalog | null>>()+ .mockResolvedValueOnce(referenceA)+ .mockResolvedValueOnce(referenceB),+ onReferenceModelPricingChanged: vi.fn(() => () => undefined),+ };+ (window as unknown as { electronAPI: { maker: { usage: typeof usage } } }).electronAPI = {+ maker: { usage },+ };++ const first = renderHook(() => ({+ gateway: useGatewayModelPricing(),+ reference: useReferenceModelPricing(),+ }));+ await waitFor(() =>+ expect(first.result.current).toEqual({+ gateway: gatewayA,+ reference: referenceA,+ }),+ );+ first.unmount();++ setDataOwnerGeneration('account-b');+ const second = renderHook(() => ({+ gateway: useGatewayModelPricing(),+ reference: useReferenceModelPricing(),+ }));+ expect(second.result.current).toEqual({ gateway: null, reference: null });+ await waitFor(() =>+ expect(second.result.current).toEqual({+ gateway: gatewayB,+ reference: referenceB,+ }),+ );++ expect(usage.getModelPricing).toHaveBeenCalledTimes(2);+ expect(usage.getReferenceModelPricing).toHaveBeenCalledTimes(2);+ });++ it('ignores a pricing read that completes after the data owner changes', async () => {+ const staleRead = deferred<ModelPricingCatalog | null>();+ const freshPricing: ModelPricingCatalog = {+ xd: {+ model: {+ providerId: 'xd',+ modelId: 'model',+ currency: 'USD',+ source: 'gateway',+ approximate: false,+ inputPerMtok: 5,+ outputPerMtok: 10,+ },+ },+ };+ const stalePricing: ModelPricingCatalog = {+ xd: {+ model: {+ providerId: 'xd',+ modelId: 'model',+ currency: 'CNY',+ source: 'gateway',+ approximate: false,+ inputPerMtok: 1,+ outputPerMtok: 2,+ },+ },+ };+ const usage = {+ getModelPricing: vi+ .fn<() => Promise<ModelPricingCatalog | null>>()+ .mockImplementationOnce(() => staleRead.promise)+ .mockResolvedValueOnce(freshPricing),+ onModelPricingChanged: vi.fn(() => () => undefined),+ };+ (window as unknown as { electronAPI: { maker: { usage: typeof usage } } }).electronAPI = {+ maker: { usage },+ };++ const first = renderHook(() => useGatewayModelPricing());+ await waitFor(() => expect(usage.getModelPricing).toHaveBeenCalledOnce());+ first.unmount();++ setDataOwnerGeneration('account-b');+ const second = renderHook(() => useGatewayModelPricing());+ await waitFor(() => expect(second.result.current).toEqual(freshPricing));++ await act(async () => {+ staleRead.resolve(stalePricing);+ await staleRead.promise;+ });+ expect(second.result.current).toEqual(freshPricing);+ });});diff --git a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.tsindex de1e1e4348..170d127936 100644--- a/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts+++ b/apps/desktop/src/renderer/hooks/useClaudeAccountUsage.ts@@ -28,6 +28,7 @@import { useEffect, useState } from 'react';import type { MoneyCurrency } from '../../shared/regionalMoney';+import { useAuth } from '../contexts/AuthContext';export interface ClaudeAccountUsageSnapshot {/** 月度周期跨客户端累计,保持 Gateway 部署区域的原生金额。 */@@ -48,7 +49,12 @@ export interface ClaudeAccountUsageSnapshot {fetchedAt: number;}-let lastSnapshot: ClaudeAccountUsageSnapshot | null = null;+interface OwnerBoundSnapshot {+ ownerKey: string;+ usage: ClaudeAccountUsageSnapshot;+}++let lastSnapshot: OwnerBoundSnapshot | null = null;function isSnapshot(v: unknown): v is ClaudeAccountUsageSnapshot {if (!v || typeof v !== 'object') return false;@@ -65,40 +71,46 @@ function isSnapshot(v: unknown): v is ClaudeAccountUsageSnapshot {export function useClaudeAccountUsage(enabled: boolean,): ClaudeAccountUsageSnapshot | null {- const [snapshot, setSnapshot] = useState<ClaudeAccountUsageSnapshot | null>(() =>- enabled ? lastSnapshot : null,+ const { dataOwnerId, mode, user } = useAuth();+ const ownerKey =+ enabled &&+ dataOwnerId &&+ (mode === 'local' || (mode === 'cloud' && user?.membershipKind === 'org'))+ ? `${mode}:${dataOwnerId}`+ : null;+ const [snapshot, setSnapshot] = useState<OwnerBoundSnapshot | null>(() =>+ ownerKey && lastSnapshot?.ownerKey === ownerKey ? lastSnapshot : null,);- useEffect(() => {- setSnapshot(enabled ? lastSnapshot : null);- }, [enabled]);-// mount 拉一次 (warm-start: main 若无 snapshot 会 force 刷新, 那一次的结果走 push 通道补帧)useEffect(() => {- if (!enabled) return;+ if (!ownerKey) return;let cancelled = false;- void window.electronAPI.maker.usage.getAccount('claude-code').then((res) => {- if (cancelled) return;- if (!isSnapshot(res)) return;- lastSnapshot = res;- setSnapshot(res);- }).catch(() => {- /* best-effort warm-start */- });+ void window.electronAPI.maker.usage+ .getAccount('claude-code')+ .then((res) => {+ if (cancelled) return;+ if (!isSnapshot(res)) return;+ lastSnapshot = { ownerKey, usage: res };+ setSnapshot(lastSnapshot);+ })+ .catch(() => {+ /* best-effort warm-start */+ });return () => {cancelled = true;};- }, [enabled]);+ }, [ownerKey]);// 订阅 push (cc / codex-api turn done 后 main 推 — 都是同一把 XD key 的 spend)useEffect(() => {- if (!enabled) return;+ if (!ownerKey) return;return window.electronAPI.maker.usage.onClaudeAccountChanged((p) => {if (!isSnapshot(p)) return;- lastSnapshot = p;- setSnapshot(p);+ lastSnapshot = { ownerKey, usage: p };+ setSnapshot(lastSnapshot);});- }, [enabled]);+ }, [ownerKey]);- return snapshot;+ return ownerKey && snapshot?.ownerKey === ownerKey ? snapshot.usage : null;}diff --git a/apps/desktop/src/renderer/hooks/useModelAccessCreditUsage.ts b/apps/desktop/src/renderer/hooks/useModelAccessCreditUsage.tsindex 15bad86e54..c738640864 100644--- a/apps/desktop/src/renderer/hooks/useModelAccessCreditUsage.ts+++ b/apps/desktop/src/renderer/hooks/useModelAccessCreditUsage.ts@@ -79,7 +79,8 @@ function isCreditUsage(v: unknown): v is ModelAccessCreditUsage {export function useModelAccessCreditUsage(enabled: boolean,): ModelAccessCreditUsage | null {- const { dataOwnerId } = useAuth();+ const { dataOwnerId, mode, user } = useAuth();+ const creditEnabled = enabled && mode === 'cloud' && user?.membershipKind === 'personal';// state 连账号 id 一起存,隔离在**渲染期**完成而不是 effect 里:effect 要等本轮渲染// 提交后才执行,靠它清空会让切号后的首帧仍把上一个账号的额度渲染出去。const [snapshot, setSnapshot] = useState<CreditUsageSnapshot | null>(() =>@@ -87,7 +88,7 @@ export function useModelAccessCreditUsage();useEffect(() => {- if (!enabled || !dataOwnerId) return;+ if (!creditEnabled || !dataOwnerId) return;let cancelled = false;const load = () => {@@ -110,9 +111,9 @@ export function useModelAccessCreditUsage(cancelled = true;clearInterval(timer);};- }, [enabled, dataOwnerId]);+ }, [creditEnabled, dataOwnerId]);// 账号不匹配 / 未启用 → 当作没有数据。切号当帧即生效。- if (!enabled || !dataOwnerId || snapshot?.accountId !== dataOwnerId) return null;+ if (!creditEnabled || !dataOwnerId || snapshot?.accountId !== dataOwnerId) return null;return snapshot.usage;}diff --git a/apps/desktop/src/renderer/hooks/useModelPricing.ts b/apps/desktop/src/renderer/hooks/useModelPricing.tsindex 60a432875c..ac542f4a25 100644--- a/apps/desktop/src/renderer/hooks/useModelPricing.ts+++ b/apps/desktop/src/renderer/hooks/useModelPricing.ts@@ -1,16 +1,61 @@-/** renderer 侧 provider-scoped 模型价格快照。 */+/** Renderer 侧相互独立的 XD 实际报价与非 XD Catalog 参考价快照。 */import { useEffect, useState } from 'react';-import type {- ModelPriceQuote,- ModelPricingCatalog,-} from '../../shared/regionalMoney';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+ type DataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';+import type { ModelPriceQuote, ModelPricingCatalog } from '../../shared/regionalMoney';-let cache: ModelPricingCatalog | null = null;-let cacheLoaded = false;-let inflight: Promise<ModelPricingCatalog | null> | null = null;-let cacheRevision = 0;+type PricingKind = 'gateway' | 'reference';++interface PricingState {+ owner: DataOwnerGeneration | null;+ cache: ModelPricingCatalog | null;+ loaded: boolean;+ inflight: Promise<ModelPricingCatalog | null> | null;+ revision: number;+}++interface PricingSnapshot {+ ownerGeneration: number;+ pricing: ModelPricingCatalog | null;+}++const gatewayState: PricingState = {+ owner: null,+ cache: null,+ loaded: false,+ inflight: null,+ revision: 0,+};+const referenceState: PricingState = {+ owner: null,+ cache: null,+ loaded: false,+ inflight: null,+ revision: 0,+};++function stateBelongsToOwner(state: PricingState, owner: DataOwnerGeneration): boolean {+ return (+ state.owner?.dataOwnerId === owner.dataOwnerId && state.owner.generation === owner.generation+ );+}++function stateFor(kind: PricingKind, owner: DataOwnerGeneration): PricingState {+ const state = kind === 'gateway' ? gatewayState : referenceState;+ if (!stateBelongsToOwner(state, owner)) {+ state.owner = owner;+ state.cache = null;+ state.loaded = false;+ state.inflight = null;+ state.revision += 1;+ }+ return state;+}function isNonNegativeFinite(value: unknown): value is number {return typeof value === 'number' && Number.isFinite(value) && value >= 0;@@ -19,87 +64,138 @@ function isNonNegativeFinite(value: unknown): value is number {function isValidQuote(value: unknown,providerId: string,- modelId: string,+ catalogKey: string,+ kind: PricingKind,): value is ModelPriceQuote {if (!value || typeof value !== 'object' || Array.isArray(value)) return false;const quote = value as Partial<ModelPriceQuote>;+ const modelId = kind === 'reference' ? catalogKey.split('\u0000', 1)[0] : catalogKey;+ const sourceMatches =+ kind === 'gateway'+ ? providerId === 'xd' && quote.source === 'gateway' && quote.approximate === false+ : providerId !== 'xd' && quote.source !== 'gateway' && quote.approximate === true;return (quote.providerId === providerId &"e.modelId === modelId &&(quote.currency === 'CNY' || quote.currency === 'USD') &&- quote.source === 'gateway' &&- quote.approximate === false &&+ sourceMatches &&isNonNegativeFinite(quote.inputPerMtok) &&isNonNegativeFinite(quote.outputPerMtok) &&- (quote.cacheReadPerMtok === undefined ||- isNonNegativeFinite(quote.cacheReadPerMtok)) &&- (quote.cacheCreatePerMtok === undefined ||- isNonNegativeFinite(quote.cacheCreatePerMtok))+ (quote.cacheReadPerMtok === undefined || isNonNegativeFinite(quote.cacheReadPerMtok)) &&+ (quote.cacheCreatePerMtok === undefined || isNonNegativeFinite(quote.cacheCreatePerMtok)));}-function isValidCatalog(v: unknown): v is ModelPricingCatalog {- if (!v || typeof v !== 'object' || Array.isArray(v)) return false;- return Object.entries(v as Record<string, unknown>).every(+function isValidCatalog(value: unknown, kind: PricingKind): value is ModelPricingCatalog {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ return Object.entries(value as Record<string, unknown>).every(([providerId, rawModels]) =>!!providerId &&!!rawModels &&typeof rawModels === 'object' &&!Array.isArray(rawModels) &&- Object.entries(rawModels as Record<string, unknown>).every(- ([modelId, quote]) => isValidQuote(quote, providerId, modelId),+ Object.entries(rawModels as Record<string, unknown>).every(([modelId, quote]) =>+ isValidQuote(quote, providerId, modelId, kind),),);}-function load(): Promise<ModelPricingCatalog | null> {- if (cacheLoaded) return Promise.resolve(cache);- if (!inflight) {- const revisionAtStart = cacheRevision;- inflight = window.electronAPI.maker.usage- .getModelPricing()- .then((res) => {- // A push received after this read started is newer than its snapshot.- // Keep the pushed value instead of letting a stale startup `null`- // remove prices until the next application restart.- if (cacheRevision !== revisionAtStart) return cache;- cacheLoaded = true;- cache = isValidCatalog(res) ? res : null;- return cache;+function readPricing(kind: PricingKind): Promise<unknown> {+ return kind === 'gateway'+ ? window.electronAPI.maker.usage.getModelPricing()+ : window.electronAPI.maker.usage.getReferenceModelPricing();+}++function subscribePricing(kind: PricingKind, listener: (pricing: unknown) => void): () => void {+ return kind === 'gateway'+ ? window.electronAPI.maker.usage.onModelPricingChanged(listener)+ : window.electronAPI.maker.usage.onReferenceModelPricingChanged(listener);+}++function load(+ kind: PricingKind,+ state: PricingState,+ owner: DataOwnerGeneration,+): Promise<ModelPricingCatalog | null> {+ if (!stateBelongsToOwner(state, owner) || !isDataOwnerGenerationCurrent(owner)) {+ return Promise.resolve(null);+ }+ if (state.loaded) return Promise.resolve(state.cache);+ if (!state.inflight) {+ const revisionAtStart = state.revision;+ const flight = readPricing(kind)+ .then((result) => {+ if (+ !stateBelongsToOwner(state, owner) ||+ !isDataOwnerGenerationCurrent(owner)+ ) {+ return null;+ }+ if (state.revision !== revisionAtStart) return state.cache;+ state.loaded = true;+ state.cache = isValidCatalog(result, kind) ? result : null;+ return state.cache;}).catch(() => {- if (cacheRevision !== revisionAtStart) return cache;- cacheLoaded = true;- cache = null;+ if (+ !stateBelongsToOwner(state, owner) ||+ !isDataOwnerGenerationCurrent(owner)+ ) {+ return null;+ }+ if (state.revision !== revisionAtStart) return state.cache;+ state.loaded = true;+ state.cache = null;return null;- })- .finally(() => {- inflight = null;});+ state.inflight = flight;+ void flight.finally(() => {+ if (state.inflight === flight) state.inflight = null;+ });}- return inflight;+ return state.inflight;}-export function useModelPricing(): ModelPricingCatalog | null {- const [pricing, setPricing] = useState<ModelPricingCatalog | null>(cache);+function usePricing(kind: PricingKind): ModelPricingCatalog | null {+ const owner = getDataOwnerGeneration();+ const source = stateFor(kind, owner);+ const [snapshot, setSnapshot] = useState<PricingSnapshot>(() => ({+ ownerGeneration: owner.generation,+ pricing: source.cache,+ }));useEffect(() => {let active = true;- const unsubscribe =- window.electronAPI.maker.usage.onModelPricingChanged((next) => {- cacheRevision += 1;- cacheLoaded = true;- cache = isValidCatalog(next) ? next : null;- if (active) setPricing(cache);- });- void load().then((res) => {- if (active) setPricing(res);+ setSnapshot({ ownerGeneration: owner.generation, pricing: source.cache });+ const unsubscribe = subscribePricing(kind, (next) => {+ if (!stateBelongsToOwner(source, owner) || !isDataOwnerGenerationCurrent(owner)) return;+ source.revision += 1;+ source.loaded = true;+ source.cache = isValidCatalog(next, kind) ? next : null;+ if (active) {+ setSnapshot({ ownerGeneration: owner.generation, pricing: source.cache });+ }+ });+ void load(kind, source, owner).then((result) => {+ if (active && stateBelongsToOwner(source, owner) && isDataOwnerGenerationCurrent(owner)) {+ setSnapshot({ ownerGeneration: owner.generation, pricing: result });+ }});return () => {active = false;unsubscribe();};- }, []);+ }, [kind, owner, source]);++ return snapshot.ownerGeneration === owner.generation ? snapshot.pricing : source.cache;+}++/** Cindy AI `/models` 下发的实际报价。 */+export function useGatewayModelPricing(): ModelPricingCatalog | null {+ return usePricing('gateway');+}- return pricing;+/** 非 XD Provider 的 Catalog 参考价与用户覆盖。 */+export function useReferenceModelPricing(): ModelPricingCatalog | null {+ return usePricing('reference');}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex d00542d47c..2196c93320 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5014,8 +5014,7 @@"context": "{{value}} context","codexCompatibilityMode": "Codex compatibility mode","price": "{{input}}/{{output}} per 1M",- "fastBadge": "Fast",- "budgetDiscount": "Special discount"+ "fastBadge": "Fast"},"source": {"railLabel": "Source",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex e16320cc4c..da5669ccb6 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5012,8 +5012,7 @@"context": "コンテキスト {{value}}","codexCompatibilityMode": "Codex 互換モード","price": "{{input}}/{{output}} / 100万",- "fastBadge": "高速",- "budgetDiscount": "特別割引"+ "fastBadge": "高速"},"source": {"railLabel": "ソース",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex a7188dd1d5..6f8e007738 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5012,8 +5012,7 @@"context": "컨텍스트 {{value}}","codexCompatibilityMode": "Codex 호환 모드","price": "{{input}}/{{output}} / 100만",- "fastBadge": "고속",- "budgetDiscount": "특별 할인"+ "fastBadge": "고속"},"source": {"railLabel": "소스",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 31d8420831..e08642851f 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5012,8 +5012,7 @@"context": "{{value}} 上下文","codexCompatibilityMode": "Codex 兼容模式","price": "{{input}}/{{output}} / 百万",- "fastBadge": "快速",- "budgetDiscount": "特别折扣"+ "fastBadge": "快速"},"source": {"railLabel": "来源",diff --git a/apps/desktop/src/renderer/themes/colors.ts b/apps/desktop/src/renderer/themes/colors.tsindex 45b48dcce3..6bf3d4dc96 100644--- a/apps/desktop/src/renderer/themes/colors.ts+++ b/apps/desktop/src/renderer/themes/colors.ts@@ -1017,15 +1017,6 @@ registerColor('model-section-label', {light: 'var(--text-secondary)',dark: 'var(--text-secondary)',}, 'Stone — "Effort" header');-registerColor('model-budget-badge-bg', {- light: '#dcfce7',- dark: '#14532d',-}, 'Budget model badge background');-registerColor('model-budget-badge-text', {- light: '#16a34a',- dark: '#86efac',-}, 'Budget model badge text');-// Permission selectorregisterColor('perm-item-selected-bg', {light: '#f8f8f6',diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex fa2c64a989..1e65c30c0d 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4929,7 +4929,7 @@ interface ElectronAPI {getCodexRateLimits: () => Promise<import('@cindy/maker-shared/device-link-contract').MobileCodexRateLimitsResult>;- /** provider-scoped 模型单价表;XD 价格与 model-access /models 同快照更新。 */+ /** Cindy AI /models 下发的 XD 原生报价。 */getModelPricing: () => Promise<import('../shared/regionalMoney').ModelPricingCatalog | null>;@@ -4938,6 +4938,13 @@ interface ElectronAPI {pricing: import('../shared/regionalMoney').ModelPricingCatalog | null,) => void,) => () => void;+ /** 非 XD Provider 的 Catalog 参考价与用户覆盖。 */+ getReferenceModelPricing: () => Promise<+ import('../shared/regionalMoney').ModelPricingCatalog+ >;+ onReferenceModelPricingChanged: (+ cb: (pricing: import('../shared/regionalMoney').ModelPricingCatalog) => void,+ ) => () => void;/** 用量历史聚合 (首页仪表盘)。wire 形态与 main/usage/usageHistory.ts 的 UsageHistoryPayload 同形。 */getHistory: (opts?: { days?: number; forceRefresh?: boolean },diff --git a/apps/mobile/src/i18n/locales/en/models.json b/apps/mobile/src/i18n/locales/en/models.jsonindex ee96e255d1..3b000f33c8 100644--- a/apps/mobile/src/i18n/locales/en/models.json+++ b/apps/mobile/src/i18n/locales/en/models.json@@ -8,7 +8,6 @@"emptyDefault": "No models available","loadingDefault": "Loading models…","subscriptionBadge": "Subscription",- "discountBadge": "Special discount","backToModels": "Back to model list","agentSwitchHint": "After you pick a model, the next message switches to {{agent}}","crossAgentEmptyHint": "Connect a {{agent}} model source on the controlled device first",diff --git a/apps/mobile/src/i18n/locales/ja/models.json b/apps/mobile/src/i18n/locales/ja/models.jsonindex 4d14c76aae..a8a6c4aa03 100644--- a/apps/mobile/src/i18n/locales/ja/models.json+++ b/apps/mobile/src/i18n/locales/ja/models.json@@ -8,7 +8,6 @@"emptyDefault": "利用可能なモデルがありません","loadingDefault": "モデルを読み込み中…","subscriptionBadge": "サブスク",- "discountBadge": "特別割引","backToModels": "モデル一覧に戻る","agentSwitchHint": "モデルを選択すると、次のメッセージから {{agent}} に切り替わります","crossAgentEmptyHint": "先に操作対象のデバイスで {{agent}} のモデルソースを接続してください",diff --git a/apps/mobile/src/i18n/locales/ko/models.json b/apps/mobile/src/i18n/locales/ko/models.jsonindex 4019db8976..731bdf521b 100644--- a/apps/mobile/src/i18n/locales/ko/models.json+++ b/apps/mobile/src/i18n/locales/ko/models.json@@ -8,7 +8,6 @@"emptyDefault": "사용 가능한 모델이 없습니다","loadingDefault": "모델을 불러오는 중…","subscriptionBadge": "구독",- "discountBadge": "특별 할인","backToModels": "모델 목록으로 돌아가기","agentSwitchHint": "모델을 선택하면 다음 메시지부터 {{agent}}(으)로 전환됩니다","crossAgentEmptyHint": "먼저 제어 대상 기기에서 {{agent}} 모델 소스를 연결하세요",diff --git a/apps/mobile/src/i18n/locales/zh-CN/models.json b/apps/mobile/src/i18n/locales/zh-CN/models.jsonindex 476820a151..721af3b275 100644--- a/apps/mobile/src/i18n/locales/zh-CN/models.json+++ b/apps/mobile/src/i18n/locales/zh-CN/models.json@@ -8,7 +8,6 @@"emptyDefault": "暂无可用模型","loadingDefault": "正在加载模型…","subscriptionBadge": "订阅",- "discountBadge": "特别折扣","backToModels": "返回模型列表","agentSwitchHint": "选择模型后,下一条消息将切换到 {{agent}}","crossAgentEmptyHint": "请先在被控设备连接 {{agent}} 的模型来源",diff --git a/apps/mobile/src/session/MobileModelPickerList.tsx b/apps/mobile/src/session/MobileModelPickerList.tsxindex 1258ea8bbf..1ec23897e1 100644--- a/apps/mobile/src/session/MobileModelPickerList.tsx+++ b/apps/mobile/src/session/MobileModelPickerList.tsx@@ -3,7 +3,7 @@* 由 ModelPickerSheet 装配)。** 展现内容对齐桌面 ModelSelector 的 renderModelItem:每行 = 来源官方 mark + 模型名 +- * `订阅`(订阅制来源)+ `特别折扣`(折扣版)+ 当前 effort 标签 + Fast 闪电(点亮时)++ * `订阅`(订阅制来源)+ 当前 effort 标签 + Fast 闪电(点亮时)+* 选中 Check + 行内「配置」入口。* 触屏适配:桌面 hover「Edit」→ 每行右侧常驻配置图标,点击经 `onOpenOptions` 通知浮窗* 打开二级「模型选项」SheetSurface(元信息 / 快速开关 / 推理强度,见 ModelOptionsSheetView),@@ -126,13 +126,13 @@ const makeStyles = (c: ThemeColors) =>fontSize: typeScale.micro,marginTop: 1,},- budgetBadge: {+ subscriptionBadge: {backgroundColor: c.surfaceChip,borderRadius: radius.pill,paddingHorizontal: spacing.sm,paddingVertical: 1,},- budgetBadgeText: {+ subscriptionBadgeText: {color: c.textSecondary,fontSize: typeScale.micro,fontWeight: fontWeight.semibold,@@ -193,7 +193,6 @@ export function MobileModelPickerList({<>{providerRows.map((row) => {const selected = row.model.id === activeModelId && row.provider.id === activeSourceId;- const isBudget = row.model.id.startsWith('codex/');// 对齐桌面 ModelSelector:订阅制来源(Claude.ai / ChatGPT 等)的模型带「订阅」徽标。const isSubscription = row.provider.access?.kind === 'subscription';const rowDisabled = budgetRowDisabled(row.model.id, apiKeyStatus);@@ -270,13 +269,8 @@ export function MobileModelPickerList({<View style={styles.optionTitleRow}><Text numberOfLines={1} style={styles.optionText}>{row.model.displayName}</Text>{isSubscription ? (- <View style={styles.budgetBadge}>- <Text style={styles.budgetBadgeText}>{t('models.picker.subscriptionBadge')}</Text>- </View>- ) : null}- {isBudget ? (- <View style={styles.budgetBadge}>- <Text style={styles.budgetBadgeText}>{t('models.picker.discountBadge')}</Text>+ <View style={styles.subscriptionBadge}>+ <Text style={styles.subscriptionBadgeText}>{t('models.picker.subscriptionBadge')}</Text></View>) : null}{rowEffort ? (