Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): 优化模型价格与设置导航并修复支付恢复 (#401)

GaoWei Liu4f9dcce88352
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
index 82dcd618fe..4a359d5ca0 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
@@ -127,10 +127,7 @@ describe('XD 网关权威模型清单重建', () => {
it('defaultEnabled 显式 false 透传;缺省不写键(= 默认可见)', () => {
setActiveCatalog(BUNDLED_CATALOG);
- setXdGatewayModels([
- { id: 'hidden-model', defaultEnabled: false },
- { id: 'visible-model' },
- ]);
+ setXdGatewayModels([{ id: 'hidden-model', defaultEnabled: false }, { id: 'visible-model' }]);
const cc = xdModels('claude-code');
expect(cc.find((m) => m.id === 'hidden-model')?.defaultEnabled).toBe(false);
expect('defaultEnabled' in (cc.find((m) => m.id === 'visible-model') ?? {})).toBe(false);
@@ -138,19 +135,81 @@ describe('XD 网关权威模型清单重建', () => {
it('icon(AI Gateway 展示图标设定)透传;缺省不写键(渲染层回落来源供应商标)', () => {
setActiveCatalog(BUNDLED_CATALOG);
- setXdGatewayModels([
- { id: 'claude-fable-5', icon: 'claude' },
- { id: 'plain-model' },
- ]);
+ setXdGatewayModels([{ id: 'claude-fable-5', icon: 'claude' }, { id: 'plain-model' }]);
const cc = xdModels('claude-code');
expect(cc.find((m) => m.id === 'claude-fable-5')?.icon).toBe('claude');
expect('icon' in (cc.find((m) => m.id === 'plain-model') ?? {})).toBe(false);
});
+ it('把标准 token 价投影为每百万 token 的折后展示价', () => {
+ setActiveCatalog(BUNDLED_CATALOG);
+ setXdGatewayModels([
+ {
+ id: 'half-price',
+ costDiscount: 0.5,
+ inputCostPerToken: 0.000012,
+ outputCostPerToken: 0.000036,
+ },
+ {
+ id: 'twenty-percent-off',
+ costDiscount: 0.2,
+ inputCostPerToken: 0.00001,
+ outputCostPerToken: 0.00002,
+ },
+ {
+ id: 'free-model',
+ inputCostPerToken: 0,
+ outputCostPerToken: 0,
+ },
+ {
+ id: 'full-price',
+ inputCostPerToken: 0.000012,
+ outputCostPerToken: 0.000036,
+ },
+ {
+ id: 'invalid-discount',
+ costDiscount: 1.2,
+ inputCostPerToken: 0.000012,
+ outputCostPerToken: 0.000036,
+ },
+ {
+ id: 'missing-output',
+ inputCostPerToken: 0.000012,
+ },
+ ]);
+
+ const cc = xdModels('claude-code');
+ expect(cc.find((m) => m.id === 'half-price')?.cost).toEqual({
+ input: 6,
+ output: 18,
+ });
+ expect(cc.find((m) => m.id === 'twenty-percent-off')?.cost).toEqual({
+ input: 8,
+ output: 16,
+ });
+ expect(cc.find((m) => m.id === 'free-model')?.cost).toEqual({
+ input: 0,
+ output: 0,
+ });
+ expect(cc.find((m) => m.id === 'full-price')?.cost).toEqual({
+ input: 12,
+ output: 36,
+ });
+ expect(cc.find((m) => m.id === 'invalid-discount')?.cost).toEqual({
+ input: 12,
+ output: 36,
+ });
+ expect(cc.find((m) => m.id === 'missing-output')?.cost).toBeUndefined();
+ });
+
it('非法 effort 档位被白名单过滤;defaultEffort 不在档位集内时回落 high 规则', () => {
setActiveCatalog(BUNDLED_CATALOG);
setXdGatewayModels([
- { id: 'weird-model', efforts: ['high', 'bogus-effort', 'max'], defaultEffort: 'bogus-effort' },
+ {
+ id: 'weird-model',
+ efforts: ['high', 'bogus-effort', 'max'],
+ defaultEffort: 'bogus-effort',
+ },
]);
const cc = xdModels('claude-code');
expect(cc[0].efforts).toEqual(['high', 'max']);
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index 0a99d5163f..a5d3f7f2f5 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -23,7 +23,13 @@
* createDesktopProviderService.ts,这样依赖本 holder 的纯逻辑模块(及其单测)不被 electron 污染。
*/
-import { BUNDLED_CATALOG, type AgentKind, type Catalog, type CatalogModel, type Provider } from '@cindy/model-providers';
+import {
+ BUNDLED_CATALOG,
+ type AgentKind,
+ type Catalog,
+ type CatalogModel,
+ type Provider,
+} from '@cindy/model-providers';
import { CHATGPT_MODEL_PREFIX } from '../../shared/subscriptionModels.js';
@@ -55,6 +61,11 @@ export interface XdGatewayAgentOverride {
/** 服务端下发的 XD 网关聊天模型条目(shared/modelAccess ModelAccessGatewayModel 同形)。 */
export interface XdGatewayModelInfo {
id: string;
+ /** AIGateway 折扣比例(0..1),折后价 = 原价 × (1 - costDiscount)。 */
+ costDiscount?: number;
+ /** AIGateway 标准 token 单价(per token)。 */
+ inputCostPerToken?: number;
+ outputCostPerToken?: number;
/** 进哪些 runtime tab;缺省 = 仅 claude-code 兜底。 */
agents?: AgentKind[];
name?: string;
@@ -107,6 +118,34 @@ const VALID_EFFORTS: ReadonlySet<string> = new Set([
]);
type Effort = CatalogModel['efforts'][number];
+
+function effectiveGatewayModelCost(model: XdGatewayModelInfo): CatalogModel['cost'] | undefined {
+ const input = model.inputCostPerToken;
+ const output = model.outputCostPerToken;
+ if (
+ typeof input !== 'number' ||
+ !Number.isFinite(input) ||
+ input < 0 ||
+ typeof output !== 'number' ||
+ !Number.isFinite(output) ||
+ output < 0
+ ) {
+ return undefined;
+ }
+ const discount =
+ typeof model.costDiscount === 'number' &&
+ Number.isFinite(model.costDiscount) &&
+ model.costDiscount > 0 &&
+ model.costDiscount <= 1
+ ? model.costDiscount
+ : 0;
+ const multiplier = 1 - discount;
+ return {
+ input: input * 1_000_000 * multiplier,
+ output: output * 1_000_000 * multiplier,
+ };
+}
+
/** base + custom + discovered augment 的合并缓存;null = 待重算(惰性)。 */
let merged: Catalog | null = null;
/** bundled + active v1 `cindyModelMeta` 的合并索引;目录变化时与 merged 一起失效。 */
@@ -146,8 +185,7 @@ function augmentModels(
.sort(
(a, b) =>
(a.model.sortOrder ?? Number.MAX_SAFE_INTEGER) -
- (b.model.sortOrder ?? Number.MAX_SAFE_INTEGER) ||
- a.index - b.index,
+ (b.model.sortOrder ?? Number.MAX_SAFE_INTEGER) || a.index - b.index,
)
.map(({ model }) => model)
: combined;
@@ -175,7 +213,7 @@ function toChatgptBridgeModel(model: CatalogModel): CatalogModel {
model.defaultEffort && CLAUDE_BRIDGE_UNSUPPORTED_EFFORTS.has(model.defaultEffort)
? bridgeEfforts.includes('xhigh')
? 'xhigh'
- : bridgeEfforts[bridgeEfforts.length - 1] ?? null
+ : (bridgeEfforts[bridgeEfforts.length - 1] ?? null)
: model.defaultEffort;
return {
...model,
@@ -200,7 +238,8 @@ function projectCodexModelsToClaude(p: Provider): Provider {
const alignedExisting = existing.map((model) => {
if (!model.id.startsWith(CHATGPT_MODEL_PREFIX)) return model;
const source = canonical.get(model.id.slice(CHATGPT_MODEL_PREFIX.length));
- if (!source || (model.name === source.name && model.sortOrder === source.sortOrder)) return model;
+ if (!source || (model.name === source.name && model.sortOrder === source.sortOrder))
+ return model;
aligned = true;
return { ...model, name: source.name, sortOrder: source.sortOrder };
});
@@ -249,15 +288,22 @@ function buildCindyModelMetaIndex(meta: unknown): Map<string, CindyModelMetaFiel
const fields: CindyModelMetaFields = {};
if (typeof e.name === 'string' && e.name.length > 0) fields.name = e.name;
if (typeof e.group === 'string' && e.group.length > 0) fields.group = e.group;
- if (typeof e.description === 'string' && e.description.length > 0) fields.description = e.description;
- if (typeof e.sortOrder === 'number' && Number.isFinite(e.sortOrder)) fields.sortOrder = e.sortOrder;
+ if (typeof e.description === 'string' && e.description.length > 0)
+ fields.description = e.description;
+ if (typeof e.sortOrder === 'number' && Number.isFinite(e.sortOrder))
+ fields.sortOrder = e.sortOrder;
if (typeof e.defaultEnabled === 'boolean') fields.defaultEnabled = e.defaultEnabled;
- if (typeof e.contextWindow === 'number' && Number.isFinite(e.contextWindow) && e.contextWindow > 0) {
+ if (
+ typeof e.contextWindow === 'number' &&
+ Number.isFinite(e.contextWindow) &&
+ e.contextWindow > 0
+ ) {
fields.contextWindow = e.contextWindow;
}
if (Array.isArray(e.efforts)) {
- const efforts = e.efforts.filter((value): value is Effort =>
- typeof value === 'string' && VALID_EFFORTS.has(value));
+ const efforts = e.efforts.filter(
+ (value): value is Effort => typeof value === 'string' && VALID_EFFORTS.has(value),
+ );
if (efforts.length === e.efforts.length) fields.efforts = efforts;
}
if (e.defaultEffort === null) fields.defaultEffort = null;
@@ -327,7 +373,7 @@ export function getCindyModelEffortBaseline(modelId: string): CindyModelEffortBa
? fields.defaultEffort
: efforts.includes('high')
? 'high'
- : efforts[efforts.length - 1] ?? null;
+ : (efforts[efforts.length - 1] ?? null);
return { efforts, defaultEffort };
}
@@ -336,7 +382,10 @@ export function getCindyModelEffortBaseline(modelId: string): CindyModelEffortBa
* 典型修正:订阅 `/v1/models` / SDK 捕获给的家族级名字("Fable")→ 产品命名
* ("Fable 5");上游无排序 → 产品排序。
*/
-function overlayCindyMeta(model: CatalogModel, fields: CindyModelMetaFields | undefined): CatalogModel {
+function overlayCindyMeta(
+ model: CatalogModel,
+ fields: CindyModelMetaFields | undefined,
+): CatalogModel {
if (!fields) return model;
return {
...model,
@@ -376,7 +425,9 @@ function computeMerged(): Catalog {
// 动态清单供应商先清零静态模型(2026-07-19 统一重构):无论目录来自 bundled 还是
// 远端(含仍带静态段的旧版 v1 OSS 文件),这三家的清单**只信运行时注入**——
// 否则过渡期旧 OSS 文件会让静态清单复活,违反「无可用性证明不展示」。
- const normalized = providers.map((p) => (DYNAMIC_LIST_PROVIDER_IDS.has(p.id) ? withEmptyModels(p) : p));
+ const normalized = providers.map((p) =>
+ DYNAMIC_LIST_PROVIDER_IDS.has(p.id) ? withEmptyModels(p) : p,
+ );
if (normalized.some((p, index) => p !== providers[index])) providers = normalized;
// 同一份规范快照先进入 Codex,再从「静态 first-wins 后的生效 Codex 列表」投影 bridge。
@@ -418,9 +469,7 @@ function computeMerged(): Catalog {
anthropicModels.map((m) => overlayCindyMeta(m, metaIndex.get(m.id))),
);
providers = providers.map((p) =>
- p.id === 'anthropic'
- ? { ...p, models: { ...p.models, 'claude-code': overlaid } }
- : p,
+ p.id === 'anthropic' ? { ...p, models: { ...p.models, 'claude-code': overlaid } } : p,
);
}
@@ -443,7 +492,8 @@ function computeMerged(): Catalog {
for (const agent of agentKeys) models[agent] = [];
for (const gm of gwModels) {
// tab 归属:服务端 agents > 仅 claude-code(网关 /v1/messages 翻译覆盖面最广,不猜)
- const targetAgents: AgentKind[] = gm.agents && gm.agents.length > 0 ? gm.agents : ['claude-code'];
+ const targetAgents: AgentKind[] =
+ gm.agents && gm.agents.length > 0 ? gm.agents : ['claude-code'];
for (const agent of targetAgents) {
if (!models[agent]) continue; // 未知 agent 键防御(wire 数据)
const ov = gm.perAgent?.[agent] ?? {};
@@ -453,8 +503,7 @@ function computeMerged(): Catalog {
rawEfforts === undefined
? ['low', 'medium', 'high']
: rawEfforts.filter((e): e is Effort => VALID_EFFORTS.has(e));
- const rawDefault =
- ov.defaultEffort !== undefined ? ov.defaultEffort : gm.defaultEffort;
+ const rawDefault = ov.defaultEffort !== undefined ? ov.defaultEffort : gm.defaultEffort;
const defaultEffort: Effort | null =
rawDefault && VALID_EFFORTS.has(rawDefault) && efforts.includes(rawDefault as Effort)
? (rawDefault as Effort)
@@ -464,6 +513,7 @@ function computeMerged(): Catalog {
? efforts[efforts.length - 1]
: null;
const defaultEnabled = ov.defaultEnabled ?? gm.defaultEnabled;
+ const cost = effectiveGatewayModelCost(gm);
const merged: CatalogModel = {
id: gm.id,
name: gm.name ?? gm.id,
@@ -476,14 +526,14 @@ function computeMerged(): Catalog {
...(gm.sortOrder !== undefined ? { sortOrder: gm.sortOrder } : {}),
...(defaultEnabled !== undefined ? { defaultEnabled } : {}),
...(gm.icon !== undefined ? { icon: gm.icon } : {}),
+ ...(cost ? { cost } : {}),
};
models[agent]!.push(merged);
}
}
// 每个 tab 内按 sortOrder 稳定排序(无 sortOrder 的合成条目排最后,按进入序)。
for (const agent of agentKeys) {
- models[agent] = models[agent]!
- .map((model, index) => ({ model, index }))
+ models[agent] = models[agent]!.map((model, index) => ({ model, index }))
.sort(
(a, b) =>
(a.model.sortOrder ?? Number.MAX_SAFE_INTEGER) -
diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
index 0a8ba58a72..e75814400b 100644
--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts
@@ -27,10 +27,12 @@ vi.mock('electron', () => ({
getPath: mocks.electronAppGetPath,
},
BrowserWindow: {
- getAllWindows: () => [{
- isDestroyed: () => false,
- webContents: { send: mocks.send },
- }],
+ getAllWindows: () => [
+ {
+ isDestroyed: () => false,
+ webContents: { send: mocks.send },
+ },
+ ],
},
}));
vi.mock('../../logger', () => ({
@@ -48,8 +50,7 @@ vi.mock('../../clientEndpointsService', () => ({
getClientEndpoint: mocks.getClientEndpoint,
}));
vi.mock('../../secrets/providerSecretStore', () => ({
- resolveOwnerScopedSecretStorageKey:
- mocks.resolveOwnerScopedSecretStorageKey,
+ resolveOwnerScopedSecretStorageKey: mocks.resolveOwnerScopedSecretStorageKey,
}));
import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
@@ -83,9 +84,7 @@ beforeEach(async () => {
tempUserDataDir = await mkdtemp(path.join(os.tmpdir(), 'cindy-model-pricing-'));
mocks.electronAppGetPath.mockReturnValue(tempUserDataDir);
mocks.getCurrentDbClientUserId.mockReturnValue('user-a');
- mocks.getClientEndpoint.mockReturnValue(
- 'https://model-access.example.test',
- );
+ mocks.getClientEndpoint.mockReturnValue('https://model-access.example.test');
mocks.resolveOwnerScopedSecretStorageKey.mockReturnValue('provider-xd');
mocks.statSync.mockReturnValue({
dev: 1n,
@@ -154,10 +153,7 @@ describe('gateway model pricing projection', () => {
},
},
});
- expect(mocks.send).toHaveBeenCalledWith(
- MODEL_PRICING_CHANGED_CHANNEL,
- pricing,
- );
+ expect(mocks.send).toHaveBeenCalledWith(MODEL_PRICING_CHANGED_CHANNEL, pricing);
});
it('keeps legal zero tiers but drops missing, invalid and 0/0 standard prices', () => {
@@ -202,17 +198,29 @@ describe('gateway model pricing projection', () => {
]);
expect(await getModelPricing()).not.toBeNull();
- expect(replaceGatewayModelPricing([
- { id: 'unpriced' },
- ])).toBeNull();
- expect(await getModelPricing()).toBeNull();
- expect(mocks.send).toHaveBeenLastCalledWith(
- MODEL_PRICING_CHANGED_CHANNEL,
- null,
- );
+ expect(replaceGatewayModelPricing([{ id: 'unpriced' }])).toEqual({});
+ expect(await getModelPricing()).toEqual({});
+ expect(mocks.send).toHaveBeenLastCalledWith(MODEL_PRICING_CHANGED_CHANNEL, {});
clearGatewayModelPricing();
- expect(await getModelPricing()).toBeNull();
+ expect(await getModelPricing()).toEqual({});
+ });
+
+ it('hydrates a successful empty pricing snapshot as loaded', async () => {
+ replaceGatewayModelPricing([
+ {
+ id: 'free',
+ inputCostPerToken: 0,
+ outputCostPerToken: 0,
+ },
+ ]);
+ await vi.waitFor(async () => {
+ const raw = JSON.parse(await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'));
+ expect(raw.pricing).toEqual({});
+ });
+
+ __resetModelPricingCacheForTesting();
+ await expect(getModelPricing()).resolves.toEqual({});
});
});
@@ -229,9 +237,7 @@ describe('pricing cache lifecycle', () => {
]);
await vi.waitFor(async () => {
- const raw = JSON.parse(
- await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'),
- );
+ const raw = JSON.parse(await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'));
expect(raw).toMatchObject({
version: 3,
scope: expectedScope(),
diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.ts
index bd36821550..652c35587d 100644
--- a/apps/desktop/src/main/usage/modelPricing.ts
+++ b/apps/desktop/src/main/usage/modelPricing.ts
@@ -18,15 +18,11 @@ import {
} from '../../shared/modelPriceQuote.js';
import type { ModelAccessGatewayModel } from '../../shared/modelAccess.js';
import { providerSecretStorageKey } from '../../shared/providerSecrets.js';
-import {
- type ModelPriceQuote,
- type ModelPricingCatalog,
-} from '../../shared/regionalMoney.js';
+import { type ModelPriceQuote, type ModelPricingCatalog } from '../../shared/regionalMoney.js';
import { getCurrentDbClientUserId } from '../localDb/client/current.js';
import { createLogger } from '../logger.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
import { resolveOwnerScopedSecretStorageKey } from '../secrets/providerSecretStore.js';
-import { getCodexBudgetEffectiveCostMultiplier } from './turnCostCalculator.js';
export { getCodexBudgetEffectiveCostMultiplier } from './turnCostCalculator.js';
export { getModelPriceQuote } from '../../shared/modelPriceQuote.js';
@@ -53,22 +49,13 @@ let cacheScope: string | null = null;
let cacheAt = 0;
let modelSyncInflight: Promise<unknown> | null = null;
const hydratedScopes = new Set<string>();
-const hydrateInflightByScope = new Map<
- string,
- Promise<ModelPricingCatalog | null>
->();
+const hydrateInflightByScope = new Map<string, Promise<ModelPricingCatalog | null>>();
function currentKeyCacheIdentity(): string {
try {
- const physicalKey = resolveOwnerScopedSecretStorageKey(
- providerSecretStorageKey('xd'),
- );
+ const physicalKey = resolveOwnerScopedSecretStorageKey(providerSecretStorageKey('xd'));
if (!physicalKey) return 'key=missing';
- const file = path.join(
- app.getPath('userData'),
- 'safe-storage',
- `${physicalKey}.enc`,
- );
+ const file = path.join(app.getPath('userData'), 'safe-storage', `${physicalKey}.enc`);
const stat = statSync(file, { bigint: true });
return `key=${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
} catch {
@@ -132,16 +119,20 @@ function validateQuote(
function validateCatalog(value: unknown): ModelPricingCatalog | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
- const xdValue = (value as Record<string, unknown>).xd;
+ const catalog = value as Record<string, unknown>;
+ if (Object.keys(catalog).length === 0) return {};
+ const xdValue = catalog.xd;
if (!xdValue || typeof xdValue !== 'object' || Array.isArray(xdValue)) return null;
const xd: Record<string, ModelPriceQuote> = {};
- for (const [rawModelId, rawQuote] of Object.entries(xdValue)) {
+ const entries = Object.entries(xdValue);
+ for (const [rawModelId, rawQuote] of entries) {
const modelId = rawModelId.trim();
if (!modelId) continue;
const quote = validateQuote(rawQuote, 'xd', modelId);
if (quote) xd[modelId] = quote;
}
- return Object.keys(xd).length > 0 ? { xd } : null;
+ if (Object.keys(xd).length > 0) return { xd };
+ return entries.length === 0 ? {} : null;
}
async function writeDiskCache(
@@ -174,7 +165,9 @@ async function hydrateFromDisk(scope: string): Promise<ModelPricingCatalog | nul
if (existing) return existing;
const hydrateInflight = (async () => {
try {
- const raw = JSON.parse(await fs.readFile(diskCachePath(), 'utf8')) as Partial<DiskCachePayload>;
+ const raw = JSON.parse(
+ await fs.readFile(diskCachePath(), 'utf8'),
+ ) as Partial<DiskCachePayload>;
if (
raw.version !== DISK_CACHE_VERSION ||
raw.scope !== scope ||
@@ -189,9 +182,7 @@ async function hydrateFromDisk(scope: string): Promise<ModelPricingCatalog | nul
cache = pricing;
cacheScope = scope;
cacheAt = Number(raw.fetchedAt);
- log.debug(
- `hydrated model pricing cache: ${Object.keys(pricing.xd ?? {}).length} XD quotes`,
- );
+ log.debug(`hydrated model pricing cache: ${Object.keys(pricing.xd ?? {}).length} XD quotes`);
return pricing;
} catch (err) {
const code =
@@ -228,15 +219,14 @@ function broadcastPricing(pricing: ModelPricingCatalog | null): void {
*/
export function replaceGatewayModelPricing(
models: readonly ModelAccessGatewayModel[],
-): ModelPricingCatalog | null {
+): ModelPricingCatalog {
const scope = currentScope();
- const next = gatewayPricingCatalog(models, CURRENT_CINDY_REGION);
- const pricing = Object.keys(next.xd ?? {}).length > 0 ? next : null;
+ const pricing = gatewayPricingCatalog(models, CURRENT_CINDY_REGION);
cache = pricing;
cacheScope = scope;
cacheAt = Date.now();
hydratedScopes.add(scope);
- void writeDiskCache(scope, next, cacheAt);
+ void writeDiskCache(scope, pricing, cacheAt);
broadcastPricing(pricing);
return pricing;
}
@@ -307,9 +297,7 @@ export function getCodexSubscriptionValuePrice(
return getModelPriceQuote(pricing, 'openai', modelId);
}
-export function getSubscriptionDirectValuePrice(
- modelId: string,
-): ModelPriceQuote | undefined {
+export function getSubscriptionDirectValuePrice(modelId: string): ModelPriceQuote | undefined {
return subscriptionDirectPriceQuote(modelId);
}
@@ -318,10 +306,7 @@ export async function prewarmModelPricing(): Promise<void> {
try {
await getModelPricing();
} catch (err) {
- log.debug(
- 'prewarm model pricing failed:',
- err instanceof Error ? err.message : String(err),
- );
+ log.debug('prewarm model pricing failed:', err instanceof Error ? err.message : String(err));
}
}
diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts
index c0b867e6af..f00e148f66 100644
--- a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts
+++ b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts
@@ -20,12 +20,15 @@ vi.mock('react-i18next', async (importOriginal) => ({
model?: string;
effort?: string;
price?: string;
+ percent?: string;
+ rate?: string;
},
) => {
const translations: Record<string, string> = {
'effortLevels.xhigh': '超高',
'settings.providers.anthropic.title': 'Anthropic',
'newChat.modelSelector.trigger.placeholder': '选择模型',
+ 'newChat.modelSelector.pricing.free': '限时免费',
};
if (key === 'newChat.modelSelector.priceTip') {
return `Input ${options?.input} · Output ${options?.output} per 1M tokens`;
@@ -42,6 +45,9 @@ vi.mock('react-i18next', async (importOriginal) => ({
if (key === 'newChat.modelSelector.trigger.ariaWithEffort') {
return `Select model. Current: ${options?.model}, effort: ${options?.effort}`;
}
+ if (key === 'newChat.modelSelector.pricing.discount') {
+ return `立省 ${options?.percent}%`;
+ }
return translations[key] ?? options?.defaultValue ?? key;
},
}),
@@ -175,8 +181,8 @@ vi.mock('@/hooks/useConnectedSource', () => ({
}),
}));
-vi.mock('@/hooks/useModelPricing', () => ({
- useModelPricing: () => ({
+const pricingRef = vi.hoisted(() => {
+ const DEFAULT_PRICING = {
anthropic: {
'claude-opus-4-8': {
providerId: 'anthropic',
@@ -190,7 +196,14 @@ vi.mock('@/hooks/useModelPricing', () => ({
cacheCreatePerMtok: 3.75,
},
},
- }),
+ };
+ return { DEFAULT_PRICING, pricing: DEFAULT_PRICING as unknown, renderCalls: 0 };
+});
+vi.mock('@/hooks/useModelPricing', () => ({
+ useModelPricing: () => {
+ pricingRef.renderCalls += 1;
+ return pricingRef.pricing;
+ },
}));
// 可变 providers mock:默认 = anthropic fixture(分段/hover 用例依赖),
@@ -240,8 +253,9 @@ vi.mock('@/hooks/useProviders', () => ({
useProviders: () => ({ providers: providersRef.providers }),
}));
+const deviceProvidersRef = vi.hoisted(() => ({ providers: [] as unknown[] }));
vi.mock('@/hooks/useDeviceProviders', () => ({
- useDeviceProviders: () => ({ providers: [], loading: false }),
+ useDeviceProviders: () => ({ providers: deviceProvidersRef.providers, loading: false }),
}));
vi.mock('@/lib/providerModels', () => ({
@@ -249,50 +263,48 @@ vi.mock('@/lib/providerModels', () => ({
// #245 新增:ModelSelector 渲染路径直接调用;fixture providers 无 routing,按不过滤透传。
isChatBridgedCodexProvider: () => false,
filterChatBridgedCodexProviders: (providers: unknown[]) => providers,
- resolveVisibleModelAgentKind: ({
- agentKind,
- }: {
- agentKind: 'claude-code' | 'codex' | null;
- }) => agentKind ?? 'claude-code',
- selectVisibleModels: ({ agentKind }: { agentKind: 'claude-code' | 'codex' | null }) => [
- {
- id: 'claude-opus-4-8',
- displayName: 'Opus 4.8',
- description: 'Most capable for ambitious work',
- contextWindow: 200000,
- efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
- defaultEffort: 'high',
- effortDisplayNames: {
- xhigh: 'X-High',
+ resolveVisibleModelAgentKind: ({ agentKind }: { agentKind: 'claude-code' | 'codex' | null }) =>
+ agentKind ?? 'claude-code',
+ selectVisibleModels: ({ agentKind }: { agentKind: 'claude-code' | 'codex' | null }) =>
+ [
+ {
+ id: 'claude-opus-4-8',
+ displayName: 'Opus 4.8',
+ description: 'Most capable for ambitious work',
+ contextWindow: 200000,
+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
+ defaultEffort: 'high',
+ effortDisplayNames: {
+ xhigh: 'X-High',
+ },
},
- },
- {
- id: 'claude-sonnet-4-6',
- displayName: 'Sonnet 4.6',
- contextWindow: 200000,
- efforts: ['low', 'medium', 'high'],
- defaultEffort: 'medium',
- },
- {
- id: 'claude-haiku-4-5',
- displayName: 'Haiku 4.5',
- description: 'Fastest for quick answers',
- contextWindow: 200000,
- efforts: [],
- defaultEffort: null,
- },
- {
- id: 'gpt-5.5',
- displayName: 'GPT-5.5',
- contextWindow: 400000,
- efforts: ['low', 'medium', 'high'],
- defaultEffort: 'medium',
- },
- ].filter((model) => {
- if (agentKind === 'claude-code') return model.id.startsWith('claude-');
- if (agentKind === 'codex') return model.id.startsWith('gpt-');
- return true;
- }),
+ {
+ id: 'claude-sonnet-4-6',
+ displayName: 'Sonnet 4.6',
+ contextWindow: 200000,
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'medium',
+ },
+ {
+ id: 'claude-haiku-4-5',
+ displayName: 'Haiku 4.5',
+ description: 'Fastest for quick answers',
+ contextWindow: 200000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: 'gpt-5.5',
+ displayName: 'GPT-5.5',
+ contextWindow: 400000,
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'medium',
+ },
+ ].filter((model) => {
+ if (agentKind === 'claude-code') return model.id.startsWith('claude-');
+ if (agentKind === 'codex') return model.id.startsWith('gpt-');
+ return true;
+ }),
}));
const modelVisibilityRef = vi.hoisted(
@@ -432,6 +444,194 @@ describe('ModelSelector trigger variants', () => {
expect(trigger.textContent).toContain('Opus 4.8');
expect(trigger.textContent).toContain('超高');
expect(trigger.textContent).not.toContain('X-High');
+ expect(trigger.querySelector('[data-model-promotion-badge]')).toBeNull();
+ });
+
+ it('reuses the parent pricing snapshot when the model content opens', () => {
+ pricingRef.renderCalls = 0;
+ render(
+ React.createElement(ModelSelector, {
+ modelId: 'claude-opus-4-8',
+ effort: 'high',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'cc',
+ }),
+ );
+ expect(pricingRef.renderCalls).toBe(1);
+
+ pricingRef.renderCalls = 0;
+ fireEvent.click(screen.getByRole('button', { name: /Current: Opus 4\.8/ }));
+ expect(pricingRef.renderCalls).toBe(1);
+ });
+
+ it('shows Gateway discount and free promotions in the selected-model trigger', () => {
+ providersRef.providers = [
+ {
+ id: 'xd',
+ name: 'Cindy AI',
+ connected: true,
+ agents: ['claude-code'],
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ {
+ id: 'claude-opus-4-8',
+ name: 'Opus 4.8',
+ contextWindow: 200000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ cost: { input: 6, output: 18 },
+ },
+ {
+ id: 'claude-sonnet-4-6',
+ name: 'Sonnet 4.6',
+ contextWindow: 200000,
+ efforts: ['medium'],
+ defaultEffort: 'medium',
+ cost: { input: 0, output: 0 },
+ },
+ ],
+ },
+ },
+ ];
+ pricingRef.pricing = {
+ xd: {
+ 'claude-opus-4-8': {
+ providerId: 'xd',
+ modelId: 'claude-opus-4-8',
+ currency: 'CNY',
+ source: 'gateway',
+ approximate: false,
+ inputPerMtok: 12,
+ outputPerMtok: 36,
+ },
+ },
+ };
+
+ try {
+ const discounted = render(
+ React.createElement(ModelSelector, {
+ modelId: 'claude-opus-4-8',
+ effort: 'high',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'cc',
+ currentProviderId: 'xd',
+ onProviderChange: vi.fn(),
+ }),
+ );
+ const discountTrigger = screen.getByRole('button', { name: /Current: Opus 4\.8/ });
+ const discountBadge = within(discountTrigger).getByText('立省 50%');
+ expect(discountBadge.hasAttribute('data-model-promotion-badge')).toBe(true);
+ expect(discountBadge.className).toContain('bg-[var(--accent-cta-bg)]');
+ expect(discountBadge.className).toContain('text-[var(--accent-pure-cta-fg)]');
+ discounted.unmount();
+
+ pricingRef.pricing = {};
+ render(
+ React.createElement(ModelSelector, {
+ modelId: 'claude-sonnet-4-6',
+ effort: 'medium',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'cc',
+ currentProviderId: 'xd',
+ onProviderChange: vi.fn(),
+ }),
+ );
+ expect(
+ within(screen.getByRole('button', { name: /Current: Sonnet 4\.6/ })).getByText('限时免费'),
+ ).toBeTruthy();
+ } finally {
+ providersRef.providers = providersRef.DEFAULT_PROVIDERS;
+ pricingRef.pricing = pricingRef.DEFAULT_PRICING;
+ }
+ });
+
+ it('does not mix controller prices with remote provider costs', () => {
+ deviceProvidersRef.providers = [
+ {
+ id: 'xd',
+ name: 'Cindy AI',
+ connected: true,
+ agents: ['claude-code'],
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ {
+ id: 'claude-opus-4-8',
+ name: 'Opus 4.8',
+ contextWindow: 200000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ cost: { input: 6, output: 18 },
+ },
+ ],
+ },
+ },
+ ];
+ pricingRef.pricing = {
+ xd: {
+ 'claude-opus-4-8': {
+ providerId: 'xd',
+ modelId: 'claude-opus-4-8',
+ currency: 'CNY',
+ source: 'gateway',
+ approximate: false,
+ inputPerMtok: 12,
+ outputPerMtok: 36,
+ },
+ },
+ };
+
+ try {
+ const triggerView = render(
+ React.createElement(ModelSelector, {
+ modelId: 'claude-opus-4-8',
+ effort: 'high',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'cc',
+ deviceId: 'remote-device',
+ currentProviderId: 'xd',
+ onProviderChange: vi.fn(),
+ }),
+ );
+ expect(
+ screen
+ .getByRole('button', { name: /Current: Opus 4\.8/ })
+ .querySelector('[data-model-promotion-badge]'),
+ ).toBeNull();
+ triggerView.unmount();
+
+ render(
+ React.createElement(ModelSelectorContent, {
+ modelId: 'claude-opus-4-8',
+ effort: 'high',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'cc',
+ deviceId: 'remote-device',
+ currentProviderId: 'xd',
+ onProviderChange: vi.fn(),
+ }),
+ );
+ const row = screen.getByRole('option', { name: /Opus 4\.8/ });
+ expect(row.textContent).not.toContain('¥12 / ¥36');
+ expect(row.textContent).not.toContain('¥6 / ¥18');
+ expect(within(row).queryByText('立省 50%')).toBeNull();
+
+ fireEvent.pointerEnter(row);
+ expect(
+ within(screen.getByRole('group', { name: /Opus 4\.8/ })).queryByText(
+ 'newChat.modelSelector.pricing.title',
+ ),
+ ).toBeNull();
+ } finally {
+ deviceProvidersRef.providers = [];
+ pricingRef.pricing = pricingRef.DEFAULT_PRICING;
+ }
});
it('uses model effort display names only as fallback when i18n has no translation', () => {
@@ -538,7 +738,7 @@ describe('ModelSelector trigger variants', () => {
expect(screen.getByTestId('model-options-popover').className).toContain('z-[10020]');
});
- it('reveals the selected model options on row hover or keyboard focus without an Edit click', () => {
+ it('keeps non-Gateway prices in their source currency without an approximate marker', () => {
vi.useFakeTimers();
render(
React.createElement(ModelSelectorContent, {
@@ -563,10 +763,13 @@ describe('ModelSelector trigger variants', () => {
expect(within(options).getByText('Source: Anthropic')).toBeTruthy();
expect(within(options).getByText('200K context')).toBeTruthy();
const priceTitle = within(options).getByText('newChat.modelSelector.pricing.title');
- expect(within(options).getByText('≈¥20.1')).toBeTruthy();
- expect(within(options).getByText('≈¥100.5')).toBeTruthy();
- expect(within(options).getByText('≈¥2.01')).toBeTruthy();
- expect(within(options).getByText('≈¥25.13')).toBeTruthy();
+ expect(row.textContent).toContain('$3 / $15');
+ expect(row.textContent).not.toContain('¥');
+ expect(row.textContent).not.toContain('≈');
+ expect(within(options).getByText('$3')).toBeTruthy();
+ expect(within(options).getByText('$15')).toBeTruthy();
+ expect(within(options).getByText('$0.3')).toBeTruthy();
+ expect(within(options).getByText('$3.75')).toBeTruthy();
expect(
within(options).getByText('newChat.modelSelector.pricing.subscriptionEstimate'),
).toBeTruthy();
@@ -595,6 +798,155 @@ describe('ModelSelector trigger variants', () => {
vi.useRealTimers();
});
+ it('keeps discounted Gateway prices aligned between the row and model details', () => {
+ providersRef.providers = [
+ {
+ id: 'xd',
+ name: 'Cindy AI',
+ connected: true,
+ agents: ['claude-code'],
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ {
+ id: 'qwen-3.7',
+ name: 'Qwen 3.7',
+ contextWindow: 200000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ cost: { input: 6, output: 18 },
+ },
+ ],
+ },
+ },
+ ];
+ pricingRef.pricing = {
+ xd: {
+ 'qwen-3.7': {
+ providerId: 'xd',
+ modelId: 'qwen-3.7',
+ currency: 'CNY',
+ source: 'gateway',
+ approximate: false,
+ inputPerMtok: 12,
+ outputPerMtok: 36,
+ },
+ },
+ };
+
+ try {
+ render(
+ React.createElement(ModelSelectorContent, {
+ modelId: 'qwen-3.7',
+ effort: 'high',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'cc',
+ currentProviderId: 'xd',
+ onProviderChange: vi.fn(),
+ }),
+ );
+
+ const row = screen.getByRole('option', { name: /Qwen 3\.7/ });
+ expect(row.textContent).toContain('¥6 / ¥18');
+ expect(row.textContent).toContain('¥12 / ¥36');
+ const rowBadge = within(row).getByText('立省 50%');
+ expect(rowBadge.hasAttribute('data-model-promotion-badge')).toBe(true);
+ expect(rowBadge.parentElement?.hasAttribute('data-model-tags')).toBe(true);
+ const priceStack = within(row).getByText('¥6 / ¥18').parentElement;
+ expect(priceStack?.getAttribute('data-model-price-stack')).toBe('true');
+ expect(priceStack).not.toBe(rowBadge.parentElement);
+ expect(rowBadge.compareDocumentPosition(priceStack as Node)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+
+ fireEvent.pointerEnter(row);
+ const details = screen.getByRole('group', { name: /Qwen 3\.7/ });
+ expect(within(details).getByText('¥6')).toBeTruthy();
+ expect(within(details).getByText('¥18')).toBeTruthy();
+ expect(within(details).getByText('¥12').className).toContain('line-through');
+ expect(within(details).getByText('¥36').className).toContain('line-through');
+ const detailsBadge = within(details).getByText('立省 50%');
+ expect(detailsBadge.parentElement?.hasAttribute('data-model-tags')).toBe(true);
+ expect(detailsBadge.parentElement?.className).toContain('ml-auto');
+ } finally {
+ providersRef.providers = providersRef.DEFAULT_PROVIDERS;
+ pricingRef.pricing = pricingRef.DEFAULT_PRICING;
+ }
+ });
+
+ it('shows explicit double-zero Gateway models as free in the row and model details', () => {
+ providersRef.providers = [
+ {
+ id: 'xd',
+ name: 'Cindy AI',
+ connected: true,
+ agents: ['claude-code'],
+ routing: { 'claude-code': {} },
+ models: {
+ 'claude-code': [
+ {
+ id: 'free-gateway-model',
+ name: 'Free Gateway Model',
+ contextWindow: 200000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ cost: { input: 0, output: 0 },
+ },
+ ],
+ },
+ },
+ ];
+ pricingRef.pricing = null;
+
+ try {
+ const loading = render(
+ React.createElement(ModelSelectorContent, {
+ modelId: 'free-gateway-model',
+ effort: 'high',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'cc',
+ currentProviderId: 'xd',
+ onProviderChange: vi.fn(),
+ }),
+ );
+ expect(
+ within(screen.getByRole('option', { name: /Free Gateway Model/ })).queryByText('限时免费'),
+ ).toBeNull();
+ loading.unmount();
+
+ pricingRef.pricing = {};
+ render(
+ React.createElement(ModelSelectorContent, {
+ modelId: 'free-gateway-model',
+ effort: 'high',
+ onModelChange: vi.fn(),
+ onEffortChange: vi.fn(),
+ vendorKey: 'cc',
+ currentProviderId: 'xd',
+ onProviderChange: vi.fn(),
+ }),
+ );
+
+ const row = screen.getByRole('option', { name: /Free Gateway Model/ });
+ const rowBadge = within(row).getByText('限时免费');
+ expect(rowBadge.hasAttribute('data-model-promotion-badge')).toBe(true);
+ expect(rowBadge.parentElement?.hasAttribute('data-model-tags')).toBe(true);
+ expect(row.textContent).not.toContain('立省 100%');
+
+ fireEvent.pointerEnter(row);
+ const details = screen.getByRole('group', { name: /Free Gateway Model/ });
+ const detailsBadge = within(details).getByText('限时免费');
+ expect(detailsBadge.parentElement?.hasAttribute('data-model-tags')).toBe(true);
+ expect(detailsBadge.parentElement?.className).toContain('ml-auto');
+ expect(within(details).queryByText('newChat.modelSelector.pricing.perMillion')).toBeNull();
+ } finally {
+ providersRef.providers = providersRef.DEFAULT_PROVIDERS;
+ pricingRef.pricing = pricingRef.DEFAULT_PRICING;
+ }
+ });
+
it('shows model information even when a model has no configurable options', () => {
render(
React.createElement(ModelSelectorContent, {
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index d3c5e097c5..d9ab791db4 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -5,6 +5,7 @@ import {
useRef,
type CSSProperties,
type PointerEvent as ReactPointerEvent,
+ type ReactNode,
} from 'react';
import { Check, ChevronDown, PlugZap, Plus, Search, Unplug, Zap } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -27,7 +28,9 @@ import { useProviders } from '@/hooks/useProviders';
import { useDeviceProviders } from '@/hooks/useDeviceProviders';
import {
formatModelPricePair,
+ modelPriceDiscountLabelValues,
modelPriceDetailRows,
+ modelPricePresentation,
} from '@/lib/modelPriceFormat';
import {
filterChatBridgedCodexProviders,
@@ -50,12 +53,8 @@ import {
visibleModelUnion,
type ProviderView,
} from '@cindy/model-providers';
-import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
-import {
- getModelPriceQuote,
- regionalizeModelPriceQuote,
-} from '../../../shared/modelPriceQuote';
-import type { ModelPriceQuote } from '../../../shared/regionalMoney';
+import { getModelPriceQuote } from '../../../shared/modelPriceQuote';
+import type { ModelPricingCatalog } from '../../../shared/regionalMoney';
import { buildProviderSections } from './sourceSwitch';
// 厂商分类 / 分组标题 key 表的纯逻辑在 ./sourceSwitch。这里 re-export 给 ChatInput
@@ -236,6 +235,17 @@ export function modelEffortLabel(
});
}
+function ModelPromotionBadge({ children }: { children: ReactNode }) {
+ return (
+ <span
+ data-model-promotion-badge
+ className="inline-flex shrink-0 items-center rounded-full bg-[var(--accent-cta-bg)] px-2 py-[1px] text-11 font-medium leading-[1.45] text-[var(--accent-pure-cta-fg)]"
+ >
+ {children}
+ </span>
+ );
+}
+
interface ModelSelectorProps {
modelId: string;
effort: Effort;
@@ -380,7 +390,12 @@ function vendorKeyToAgentKind(v?: 'cc' | 'codex'): AgentKind | null {
return null;
}
-export function ModelSelectorContent({
+export function ModelSelectorContent(props: ModelSelectorContentProps) {
+ const pricing = useModelPricing();
+ return <ModelSelectorContentView {...props} pricing={pricing} />;
+}
+
+function ModelSelectorContentView({
modelId,
effort,
onModelChange,
@@ -401,7 +416,8 @@ export function ModelSelectorContent({
configurationEnabled = true,
pointerRevealRequiresIntent = false,
agentSwitch,
-}: ModelSelectorContentProps) {
+ pricing,
+}: ModelSelectorContentProps & { pricing: ModelPricingCatalog | null }) {
const { t } = useTranslation();
// session-agent-switch:两步式引擎切换的浏览态。browseVendor 初始 = 会话当前引擎;
// 切到另一家 tab 只是「浏览目标引擎的模型」,选中模型行才真正触发切换事务。
@@ -435,7 +451,6 @@ export function ModelSelectorContent({
// 同时拉两个 agent —— vendorKey 不传时把两边模型一起展示。hooks 必须按固定顺序调用。
const cc = useAgentCapabilities('claude-code', deviceId);
const codex = useAgentCapabilities('codex', deviceId);
- const pricing = useModelPricing();
// 本机骨折 GPT 仍按本机 API key gate;device-link 必须只看被控端 provider 状态。
// 旧被控端不支持 provider:list 时按远端 capabilities 退化,不得误用控制端 key。
const { hasSavedKey } = useApiKey();
@@ -633,25 +648,30 @@ export function ModelSelectorContent({
// ── 模型单价 ─────────────────────────────────────────────────────────────
// providerId 是价格索引的一部分。同模型经 XD / OpenAI / Anthropic 等来源出现时,
- // 必须按实际行来源查价,不能退化为 pricing[modelId]。
- const priceQuoteOf = (
- providerId: string | null,
- id: string,
- ): ModelPriceQuote | null => {
+ // 必须按实际行来源查价,不能退化为 pricing[modelId]。只有 XD Gateway 目录价会
+ // 叠加 CatalogModel.cost 作为折后展示价;其它来源保持价格源自带的币种。
+ const pricePresentationOf = (providerId: string | null, id: string) => {
+ // device-link 只同步被控端 provider 目录,不同步价格快照;不能把控制端价格与
+ // 被控端 CatalogModel.cost 拼成一个展示结果。在协议补齐前远程选择器不展示价格。
+ if (deviceId) return null;
const effectiveProviderId =
providerId ??
(currentAgentKind
- ? effectiveSourceIdForModel(
- providers,
- currentProviderId,
- id,
- currentAgentKind,
- )
+ ? effectiveSourceIdForModel(providers, currentProviderId, id, currentAgentKind)
: null);
const quote = getModelPriceQuote(pricing, effectiveProviderId, id);
- return quote
- ? regionalizeModelPriceQuote(quote, CURRENT_CINDY_REGION)
- : null;
+ if (effectiveProviderId === 'xd' && (!quote || quote.source === 'gateway')) {
+ if (!quote && pricing == null) return null;
+ const effectiveProvider = providers.find((provider) => provider.id === effectiveProviderId);
+ const effectiveCost =
+ effectiveProvider && currentAgentKind
+ ? getModel(effectiveProvider, id, currentAgentKind)?.cost
+ : undefined;
+ return modelPricePresentation(quote ?? null, effectiveCost);
+ }
+ if (!quote) return null;
+ const displayQuote = quote.approximate ? { ...quote, approximate: false } : quote;
+ return modelPricePresentation(displayQuote, undefined);
};
const modelDisabledOf = (id: string): boolean => {
if (!deviceId) return id.startsWith('codex/') && !hasSavedKey;
@@ -892,9 +912,20 @@ export function ModelSelectorContent({
effectiveSourceIdForModel(providers, currentProviderId, editingModel.id, currentAgentKind);
return providerId ? providers.find((provider) => provider.id === providerId) : undefined;
}, [editingModel, currentAgentKind, editingProviderId, providers, currentProviderId]);
- const editingPrice = editingModel
- ? priceQuoteOf(editingProvider?.id ?? editingProviderId, editingModel.id)
+ const editingPricePresentation = editingModel
+ ? pricePresentationOf(editingProvider?.id ?? editingProviderId, editingModel.id)
: null;
+ const editingDiscount =
+ editingPricePresentation?.kind === 'priced' ? editingPricePresentation.discount : undefined;
+ const editingPromotionLabel =
+ editingPricePresentation?.kind === 'free'
+ ? t('newChat.modelSelector.pricing.free')
+ : editingDiscount !== undefined
+ ? t(
+ 'newChat.modelSelector.pricing.discount',
+ modelPriceDiscountLabelValues(editingDiscount),
+ )
+ : null;
// 每个模型行的信息 / 配置内容由一个独立的 portaled Popover 承载,而不是拼进主菜单宽度。
// 这样浮层会像 Hermes 的 Radix submenu 一样贴着当前行移动,切行不触发主菜单重排。
@@ -977,32 +1008,56 @@ export function ModelSelectorContent({
{(editShowFast || editHasEfforts) && (
<div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
)}
- {editingPrice && (
+ {editingPricePresentation && (
<>
<div className="px-2 pb-1 pt-1">
- <div className="mb-1.5 text-11 font-medium text-[var(--text-tertiary)]">
- {t('newChat.modelSelector.pricing.title')}
+ <div
+ className={cn(
+ 'flex items-center gap-1.5 text-11 font-medium text-[var(--text-tertiary)]',
+ editingPricePresentation.kind === 'priced' && 'mb-1.5',
+ )}
+ >
+ <span>{t('newChat.modelSelector.pricing.title')}</span>
+ {editingPromotionLabel && (
+ <span data-model-tags className="ml-auto flex shrink-0 items-center">
+ <ModelPromotionBadge>{editingPromotionLabel}</ModelPromotionBadge>
+ </span>
+ )}
</div>
- <div className="grid grid-cols-[1fr_auto] gap-x-3 gap-y-1 text-12 leading-[1.4]">
- {modelPriceDetailRows(editingPrice).map((row) => (
- <div key={row.kind} className="contents">
- <span className="text-[var(--text-secondary)]">
- {t(`newChat.modelSelector.pricing.${row.kind}`)}
- </span>
- <span className="tabular-nums text-[var(--model-item-text)]">
- {editingPrice.approximate ? '≈' : ''}
- {row.value}
- </span>
+ {editingPricePresentation.kind === 'priced' && (
+ <>
+ <div className="grid grid-cols-[1fr_auto] gap-x-3 gap-y-1 text-12 leading-[1.4]">
+ {modelPriceDetailRows(
+ editingPricePresentation.current,
+ editingPricePresentation.original,
+ ).map((row) => (
+ <div key={row.kind} className="contents">
+ <span className="text-[var(--text-secondary)]">
+ {t(`newChat.modelSelector.pricing.${row.kind}`)}
+ </span>
+ <span className="flex items-center justify-end gap-1.5 tabular-nums">
+ <span className="text-[var(--model-item-text)]">
+ {editingPricePresentation.current.approximate ? '≈' : ''}
+ {row.value}
+ </span>
+ {row.originalValue && (
+ <span className="text-[var(--text-tertiary)] line-through">
+ {row.originalValue}
+ </span>
+ )}
+ </span>
+ </div>
+ ))}
</div>
- ))}
- </div>
- <div className="mt-1.5 text-11 leading-[1.4] text-[var(--text-tertiary)]">
- {editingPrice.source === 'subscription-reference'
- ? t('newChat.modelSelector.pricing.subscriptionEstimate')
- : editingPrice.approximate
- ? t('newChat.modelSelector.pricing.fixedFx')
- : t('newChat.modelSelector.pricing.perMillion')}
- </div>
+ <div className="mt-1.5 text-11 leading-[1.4] text-[var(--text-tertiary)]">
+ {editingPricePresentation.current.source === 'subscription-reference'
+ ? t('newChat.modelSelector.pricing.subscriptionEstimate')
+ : editingPricePresentation.current.approximate
+ ? t('newChat.modelSelector.pricing.fixedFx')
+ : t('newChat.modelSelector.pricing.perMillion')}
+ </div>
+ </>
+ )}
</div>
<div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
</>
@@ -1041,7 +1096,16 @@ export function ModelSelectorContent({
const disabled = modelDisabledOf(model.id);
const rowEffort = rowEffortOf(providerId, model);
const rowFastOn = fastOnOf(providerId, model);
- const rowPrice = priceQuoteOf(providerId, model.id);
+ const rowPrice = pricePresentationOf(providerId, model.id);
+ const rowPromotionLabel =
+ rowPrice?.kind === 'free'
+ ? t('newChat.modelSelector.pricing.free')
+ : rowPrice?.kind === 'priced' && rowPrice.discount !== undefined
+ ? t(
+ 'newChat.modelSelector.pricing.discount',
+ modelPriceDiscountLabelValues(rowPrice.discount),
+ )
+ : null;
// 信息面板对所有可用模型开放;能否编辑 effort / Fast 在面板内部另行判定。
// session-agent-switch 浏览目标引擎态同样开放:选模型前正需要看描述/上下文/价格/来源;
// 面板内配置写的是**目标引擎**的 per-(来源,模型) 全局预设(currentAgentKind 已随浏览态
@@ -1065,7 +1129,8 @@ export function ModelSelectorContent({
pointerRevealRequiresIntent &&
!hoverIntentArmedRef.current &&
event.nativeEvent.isTrusted
- ) return;
+ )
+ return;
if (!isEditingThis) revealOptions();
else cancelOptionsClose();
};
@@ -1122,8 +1187,7 @@ export function ModelSelectorContent({
disabled && 'cursor-not-allowed opacity-50 hover:bg-transparent',
)}
>
- {/* 外层 gap-2.5 = icon→名字间距(略宽,与行左内边距更协调);内层 gap-1.5 = 名字→徽标/effort。 */}
- <span className="flex min-w-0 items-center gap-2.5">
+ <span className="flex min-w-0 flex-1 items-center gap-2.5">
{provider && (
<ModelIconMark
icon={model.icon}
@@ -1135,39 +1199,61 @@ export function ModelSelectorContent({
dense
/>
)}
- <span className="flex min-w-0 items-center gap-1.5">
- <span className="truncate text-14 font-medium text-[var(--model-item-text)]">
- {model.displayName}
- </span>
- {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 className="flex min-w-0 flex-1 items-center gap-1.5">
+ <span className="flex min-w-0 flex-1 items-center gap-1.5">
+ <span className="truncate text-14 font-medium text-[var(--model-item-text)]">
+ {model.displayName}
</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>
- )}
- {rowEffort && (
- <span className="shrink-0 text-13 font-normal text-[var(--text-tertiary)]">
- {effortLabelFor(model, rowEffort)}
+ {rowEffort && (
+ <span className="shrink-0 text-13 font-normal text-[var(--text-tertiary)]">
+ {effortLabelFor(model, rowEffort)}
+ </span>
+ )}
+ {rowFastOn && (
+ <Zap
+ size={13}
+ className="shrink-0 text-[var(--text-tertiary)]"
+ aria-label={t('newChat.modelSelector.meta.fastBadge')}
+ />
+ )}
+ </span>
+ {(isSubscriptionModel || isBudgetModel || 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>
+ )}
</span>
)}
- {rowFastOn && (
- <Zap
- size={13}
- className="shrink-0 text-[var(--text-tertiary)]"
- aria-label={t('newChat.modelSelector.meta.fastBadge')}
- />
- )}
</span>
</span>
- {(rowPrice || isSelected) && (
+ {(rowPrice?.kind === 'priced' || isSelected) && (
<span className="ml-2 flex shrink-0 items-center gap-1.5">
- {rowPrice && (
- <span className="tabular-nums text-11 font-normal text-[var(--text-tertiary)]">
- {formatModelPricePair(rowPrice)}
+ {rowPrice?.kind === 'priced' && (
+ <span
+ data-model-price-stack={rowPrice.original ? 'true' : undefined}
+ className={cn(
+ 'flex tabular-nums text-11 font-normal leading-[1.25]',
+ rowPrice.original ? 'flex-col items-end' : 'items-center',
+ )}
+ >
+ <span className="text-[var(--text-secondary)]">
+ {formatModelPricePair(rowPrice.current)}
+ </span>
+ {rowPrice.original && (
+ <span className="text-[var(--text-tertiary)] line-through">
+ {formatModelPricePair(rowPrice.original)}
+ </span>
+ )}
</span>
)}
{isSelected && (
@@ -1423,6 +1509,7 @@ export function ModelSelector({
const agentKind = vendorKeyToAgentKind(vendorKey);
const cc = useAgentCapabilities('claude-code', deviceId);
const codex = useAgentCapabilities('codex', deviceId);
+ const pricing = useModelPricing();
// trigger 的来源 icon / 当前模型也按来源取:device-link 用被控端供应商目录(否则控制端本地
// 查不到被控端独有模型 → currentModel undefined → label 退成 "Select model")。
const localProviders = useProviders();
@@ -1518,6 +1605,27 @@ export function ModelSelector({
triggerActiveProvider && currentAgentKind
? getModel(triggerActiveProvider, modelId, currentAgentKind)?.icon
: undefined;
+ const triggerPricePresentation = (() => {
+ if (deviceId || activeSourceId !== 'xd' || !triggerActiveProvider || !currentAgentKind)
+ return null;
+ const quote = getModelPriceQuote(pricing, activeSourceId, modelId);
+ if (quote && quote.source !== 'gateway') return null;
+ if (!quote && pricing == null) return null;
+ return modelPricePresentation(
+ quote ?? null,
+ getModel(triggerActiveProvider, modelId, currentAgentKind)?.cost,
+ );
+ })();
+ const triggerPromotionLabel =
+ triggerPricePresentation?.kind === 'free'
+ ? t('newChat.modelSelector.pricing.free')
+ : triggerPricePresentation?.kind === 'priced' &&
+ triggerPricePresentation.discount !== undefined
+ ? t(
+ 'newChat.modelSelector.pricing.discount',
+ modelPriceDiscountLabelValues(triggerPricePresentation.discount),
+ )
+ : null;
// 断开态同一规则,只是来源取「真实断开来源」(currentProviderId)。
const disconnectedProvider = currentProviderId
? providers.find((p) => p.id === currentProviderId)
@@ -1563,216 +1671,215 @@ export function ModelSelector({
const trigger = (
<button
- type="button"
- disabled={switching || disabled}
- onClick={morphEnabled ? () => setOpen((prev) => (disabled ? false : !prev)) : undefined}
- aria-expanded={open && !disabled}
- aria-haspopup="listbox"
- title={displayLabel}
- className={cn(
- 'flex min-w-0 max-w-full items-center gap-1 transition-colors',
- isFieldTrigger
- ? cn(
- 'w-full rounded-lg border border-[var(--border-default)] bg-[var(--settings-input-bg)] px-3',
- dense ? 'h-9' : 'h-10',
- 'hover:bg-[var(--surface-hover-soft)]',
- )
- : cn(
- 'rounded-full',
- // 裸态工具条(2026-07-22 用户定稿):默认无框,hover 才浮现胶囊外框。
- // create-agent(新建对话框)与会话内共用同一套裸态,不再分叉 —— 静息/hover 逐字一致。
- 'h-[30px] min-w-[72px] max-w-full shrink overflow-hidden px-2.5',
- // 窄态工具条(#562):新建对话框空间不足时钳制触发器宽度,防与语音/发送重叠。
- isUltraCompactToolbar ? 'w-[64px]' : isCompactToolbar ? 'w-[148px]' : undefined,
- 'border border-transparent bg-transparent',
- 'hover:border-[var(--border-default)] hover:bg-[var(--composer-pill-bg,#FCFCFC)] dark:hover:bg-[var(--composer-pill-bg,#393838)]',
- ),
- // device-link 远程切换 in-flight:置灰 + 禁用点击(复用本文件 disabled 行的 opacity-50 习惯)。
- (switching || disabled) && 'pointer-events-none opacity-50',
+ type="button"
+ disabled={switching || disabled}
+ onClick={morphEnabled ? () => setOpen((prev) => (disabled ? false : !prev)) : undefined}
+ aria-expanded={open && !disabled}
+ aria-haspopup="listbox"
+ title={displayLabel}
+ className={cn(
+ 'flex min-w-0 max-w-full items-center gap-1 transition-colors',
+ isFieldTrigger
+ ? cn(
+ 'w-full rounded-lg border border-[var(--border-default)] bg-[var(--settings-input-bg)] px-3',
+ dense ? 'h-9' : 'h-10',
+ 'hover:bg-[var(--surface-hover-soft)]',
+ )
+ : cn(
+ 'rounded-full',
+ // 裸态工具条(2026-07-22 用户定稿):默认无框,hover 才浮现胶囊外框。
+ // create-agent(新建对话框)与会话内共用同一套裸态,不再分叉 —— 静息/hover 逐字一致。
+ 'h-[30px] min-w-[72px] max-w-full shrink overflow-hidden px-2.5',
+ // 窄态工具条(#562):新建对话框空间不足时钳制触发器宽度,防与语音/发送重叠。
+ isUltraCompactToolbar ? 'w-[64px]' : isCompactToolbar ? 'w-[148px]' : undefined,
+ 'border border-transparent bg-transparent',
+ 'hover:border-[var(--border-default)] hover:bg-[var(--composer-pill-bg,#FCFCFC)] dark:hover:bg-[var(--composer-pill-bg,#393838)]',
+ ),
+ // device-link 远程切换 in-flight:置灰 + 禁用点击(复用本文件 disabled 行的 opacity-50 习惯)。
+ (switching || disabled) && 'pointer-events-none opacity-50',
+ )}
+ aria-label={ariaLabel}
+ >
+ {noSource ? (
+ <>
+ <PlugZap
+ size={isCreateAgentVariant ? 11 : 13}
+ className={cn(
+ 'mr-0.5 shrink-0',
+ isCreateAgentVariant
+ ? 'text-[var(--create-agent-control-icon)]'
+ : 'text-[var(--text-primary)]',
+ )}
+ />
+ <span
+ className={cn(
+ 'min-w-0 font-medium',
+ isCreateAgentVariant
+ ? 'text-[var(--create-agent-control-text)]'
+ : 'text-[var(--text-primary)]',
+ isCreateAgentVariant
+ ? isUltraCompactToolbar
+ ? 'hidden'
+ : isCompactToolbar
+ ? 'max-w-[108px] truncate'
+ : 'truncate'
+ : cn('truncate', isFieldTrigger ? 'max-w-[260px]' : ''),
+ isCreateAgentVariant ? 'text-[12px]' : dense ? 'text-[12.5px]' : 'text-[13px]',
+ )}
+ >
+ {t('newChat.modelSelector.source.connect')}
+ </span>
+ </>
+ ) : showSourceDisconnected && currentProviderId ? (
+ // 选中来源已断开:显示**真实来源**(currentProviderId)而非 activeSourceId 的默认回落
+ // ——回落图标会让用户以为在用默认来源,而发送实际按 DB 里的断开来源走(no_oauth 事故)。
+ // 错误态用语义豁免 error token(规则 16);trigger 保持可点击,下拉换源即恢复。
+ <>
+ <ModelIconMark
+ icon={disconnectedModelIcon}
+ providerId={currentProviderId}
+ name={disconnectedProvider?.name}
+ routing={disconnectedProvider?.routing}
+ colorClass="text-[var(--error-fg)]"
+ />
+ <span
+ className={cn(
+ 'min-w-0 font-normal text-[var(--text-primary)]',
+ isCreateAgentVariant
+ ? isUltraCompactToolbar
+ ? 'hidden'
+ : isCompactToolbar
+ ? 'max-w-[108px] truncate'
+ : 'truncate'
+ : isFieldTrigger
+ ? 'max-w-[260px] truncate'
+ : 'truncate',
+ isCreateAgentVariant ? 'text-[12px]' : dense ? 'text-[12.5px]' : 'text-[13px]',
+ )}
+ >
+ {/* 断开来源可能是该模型的唯一提供方 → visibleModels 查不到,回落显示原始 id,
+ 比 "Select model" 占位更能说明「哪个模型的来源断了」。 */}
+ {currentModel?.displayName ?? modelId}
+ </span>
+ <Unplug
+ size={dense ? 11 : 12}
+ className="ml-0.5 shrink-0 text-[var(--error-fg)]"
+ aria-hidden
+ />
+ <span
+ className={cn(
+ 'shrink-0 font-medium text-[var(--error-fg)]',
+ dense ? 'text-[11.5px]' : 'text-[12px]',
+ )}
+ >
+ {t('newChat.modelSelector.source.disconnected')}
+ </span>
+ </>
+ ) : (
+ <>
+ {/* 图标统一规则:模型条目 icon(AI Gateway / 目录设定)优先,缺省回落
+ 当前真正路由的来源标(activeSourceId)——客户端不按 model id 猜厂牌。 */}
+ {activeSourceId && (
+ <ModelIconMark
+ icon={triggerModelIcon}
+ providerId={activeSourceId}
+ name={triggerActiveProvider?.name}
+ routing={triggerActiveProvider?.routing}
+ colorClass={
+ isCreateAgentVariant ? 'text-[var(--create-agent-control-icon)]' : undefined
+ }
+ />
+ )}
+ <span
+ className={cn(
+ 'min-w-0 font-normal',
+ isCreateAgentVariant
+ ? isUltraCompactToolbar
+ ? 'hidden'
+ : isCompactToolbar
+ ? 'max-w-[108px] truncate'
+ : 'truncate'
+ : isFieldTrigger
+ ? 'max-w-[260px] truncate'
+ : 'truncate',
+ !isBudget &&
+ (isCreateAgentVariant
+ ? 'text-[var(--create-agent-control-text)]'
+ : 'text-[var(--text-primary)]'),
+ isCreateAgentVariant ? 'text-[12px]' : dense ? 'text-[12.5px]' : 'text-[13px]',
+ )}
+ style={budgetGradientStyle}
+ >
+ {displayLabel}
+ </span>
+ {!fallbackOption?.active && triggerPromotionLabel && !isCompactToolbar && (
+ <ModelPromotionBadge>{triggerPromotionLabel}</ModelPromotionBadge>
)}
- aria-label={ariaLabel}
- >
- {noSource ? (
+ {effortLabel && !isCompactToolbar && (
<>
- <PlugZap
- size={isCreateAgentVariant ? 11 : 13}
- className={cn(
- 'mr-0.5 shrink-0',
- isCreateAgentVariant
- ? 'text-[var(--create-agent-control-icon)]'
- : 'text-[var(--text-primary)]',
- )}
- />
<span
className={cn(
- 'min-w-0 font-medium',
+ 'shrink-0 font-normal',
isCreateAgentVariant
? 'text-[var(--create-agent-control-text)]'
- : 'text-[var(--text-primary)]',
+ : 'text-[var(--model-trigger-meta)]',
isCreateAgentVariant
- ? isUltraCompactToolbar
- ? 'hidden'
- : isCompactToolbar
- ? 'max-w-[108px] truncate'
- : 'truncate'
- : cn('truncate', isFieldTrigger ? 'max-w-[260px]' : ''),
- isCreateAgentVariant ? 'text-[12px]' : dense ? 'text-[12.5px]' : 'text-[13px]',
- )}
- >
- {t('newChat.modelSelector.source.connect')}
- </span>
- </>
- ) : showSourceDisconnected && currentProviderId ? (
- // 选中来源已断开:显示**真实来源**(currentProviderId)而非 activeSourceId 的默认回落
- // ——回落图标会让用户以为在用默认来源,而发送实际按 DB 里的断开来源走(no_oauth 事故)。
- // 错误态用语义豁免 error token(规则 16);trigger 保持可点击,下拉换源即恢复。
- <>
- <ModelIconMark
- icon={disconnectedModelIcon}
- providerId={currentProviderId}
- name={disconnectedProvider?.name}
- routing={disconnectedProvider?.routing}
- colorClass="text-[var(--error-fg)]"
- />
- <span
- className={cn(
- 'min-w-0 font-normal text-[var(--text-primary)]',
- isCreateAgentVariant
- ? isUltraCompactToolbar
- ? 'hidden'
- : isCompactToolbar
- ? 'max-w-[108px] truncate'
- : 'truncate'
- : isFieldTrigger
- ? 'max-w-[260px] truncate'
- : 'truncate',
- isCreateAgentVariant ? 'text-[12px]' : dense ? 'text-[12.5px]' : 'text-[13px]',
+ ? 'shrink-0 text-[12px]'
+ : dense
+ ? 'shrink-0 text-[12.5px]'
+ : 'shrink-0 text-[13px]',
)}
+ aria-hidden="true"
>
- {/* 断开来源可能是该模型的唯一提供方 → visibleModels 查不到,回落显示原始 id,
- 比 "Select model" 占位更能说明「哪个模型的来源断了」。 */}
- {currentModel?.displayName ?? modelId}
+ ·
</span>
- <Unplug
- size={dense ? 11 : 12}
- className="ml-0.5 shrink-0 text-[var(--error-fg)]"
- aria-hidden
- />
- <span
- className={cn(
- 'shrink-0 font-medium text-[var(--error-fg)]',
- dense ? 'text-[11.5px]' : 'text-[12px]',
- )}
- >
- {t('newChat.modelSelector.source.disconnected')}
- </span>
- </>
- ) : (
- <>
- {/* 图标统一规则:模型条目 icon(AI Gateway / 目录设定)优先,缺省回落
- 当前真正路由的来源标(activeSourceId)——客户端不按 model id 猜厂牌。 */}
- {activeSourceId && (
- <ModelIconMark
- icon={triggerModelIcon}
- providerId={activeSourceId}
- name={triggerActiveProvider?.name}
- routing={triggerActiveProvider?.routing}
- colorClass={
- isCreateAgentVariant ? 'text-[var(--create-agent-control-icon)]' : undefined
- }
- />
- )}
<span
className={cn(
'min-w-0 font-normal',
isCreateAgentVariant
- ? isUltraCompactToolbar
- ? 'hidden'
- : isCompactToolbar
- ? 'max-w-[108px] truncate'
- : 'truncate'
+ ? 'text-[var(--create-agent-control-text)]'
+ : 'text-[var(--text-primary)]',
+ isCreateAgentVariant
+ ? 'truncate'
: isFieldTrigger
- ? 'max-w-[260px] truncate'
- : 'truncate',
- !isBudget &&
- (isCreateAgentVariant
- ? 'text-[var(--create-agent-control-text)]'
- : 'text-[var(--text-primary)]'),
+ ? 'max-w-[120px] truncate'
+ : 'shrink-0 whitespace-nowrap',
isCreateAgentVariant ? 'text-[12px]' : dense ? 'text-[12.5px]' : 'text-[13px]',
)}
- style={budgetGradientStyle}
>
- {displayLabel}
+ {effortLabel}
</span>
- {effortLabel && !isCompactToolbar && (
- <>
- <span
- className={cn(
- 'shrink-0 font-normal',
- isCreateAgentVariant
- ? 'text-[var(--create-agent-control-text)]'
- : 'text-[var(--model-trigger-meta)]',
- isCreateAgentVariant
- ? 'shrink-0 text-[12px]'
- : dense
- ? 'shrink-0 text-[12.5px]'
- : 'shrink-0 text-[13px]',
- )}
- aria-hidden="true"
- >
- ·
- </span>
- <span
- className={cn(
- 'min-w-0 font-normal',
- isCreateAgentVariant
- ? 'text-[var(--create-agent-control-text)]'
- : 'text-[var(--text-primary)]',
- isCreateAgentVariant
- ? 'truncate'
- : isFieldTrigger
- ? 'max-w-[120px] truncate'
- : 'shrink-0 whitespace-nowrap',
- isCreateAgentVariant
- ? 'text-[12px]'
- : dense
- ? 'text-[12.5px]'
- : 'text-[13px]',
- )}
- >
- {effortLabel}
- </span>
- </>
- )}
- {triggerFastOn && !isCompactToolbar && (
- <Zap
- size={isCreateAgentVariant ? 11 : dense ? 12 : 13}
- className={cn(
- 'ml-0.5 shrink-0',
- isCreateAgentVariant
- ? 'text-[var(--create-agent-control-icon)]'
- : 'text-[var(--composer-pill-icon,#3C3F43)] dark:text-[var(--composer-pill-icon,#D9D9D9)]',
- )}
- aria-label={t('newChat.modelSelector.meta.fastBadge')}
- />
- )}
</>
)}
- <ChevronDown
- size={isCreateAgentVariant ? 8 : dense ? 13 : 14}
- className={cn(
- 'shrink-0',
- isCreateAgentVariant
- ? 'text-[var(--create-agent-control-icon)]'
- : 'text-[var(--composer-pill-icon,#3C3F43)] dark:text-[var(--composer-pill-icon,#D9D9D9)]' /* spec 2026-07-17, token by 一哥 */,
- isFieldTrigger && 'ml-auto',
- )}
- />
+ {triggerFastOn && !isCompactToolbar && (
+ <Zap
+ size={isCreateAgentVariant ? 11 : dense ? 12 : 13}
+ className={cn(
+ 'ml-0.5 shrink-0',
+ isCreateAgentVariant
+ ? 'text-[var(--create-agent-control-icon)]'
+ : 'text-[var(--composer-pill-icon,#3C3F43)] dark:text-[var(--composer-pill-icon,#D9D9D9)]',
+ )}
+ aria-label={t('newChat.modelSelector.meta.fastBadge')}
+ />
+ )}
+ </>
+ )}
+ <ChevronDown
+ size={isCreateAgentVariant ? 8 : dense ? 13 : 14}
+ className={cn(
+ 'shrink-0',
+ isCreateAgentVariant
+ ? 'text-[var(--create-agent-control-icon)]'
+ : 'text-[var(--composer-pill-icon,#3C3F43)] dark:text-[var(--composer-pill-icon,#D9D9D9)]' /* spec 2026-07-17, token by 一哥 */,
+ isFieldTrigger && 'ml-auto',
+ )}
+ />
</button>
);
const content = (
- <ModelSelectorContent
+ <ModelSelectorContentView
modelId={modelId}
effort={effort}
onModelChange={onModelChange}
@@ -1791,6 +1898,7 @@ export function ModelSelector({
configurationEnabled={configurationEnabled}
pointerRevealRequiresIntent={morphEnabled}
agentSwitch={contentAgentSwitch}
+ pricing={pricing}
followSession={
fallbackOption
? {
diff --git a/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx b/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx
index 02a7634e2d..92a1a0a9cd 100644
--- a/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx
+++ b/apps/desktop/src/renderer/features/billing/BillingCheckoutDialog.tsx
@@ -71,7 +71,6 @@ export function BillingCheckoutDialog({
const title = useMemo(() => {
if (state.phase === 'CREATING') return t('billing.checkout.creatingTitle');
if (state.phase === 'AWAITING_PAYMENT') return t('billing.checkout.awaitingTitle');
- if (state.phase === 'FULFILLING') return t('billing.checkout.fulfillingTitle');
if (state.phase === 'COMPLETED') return t('billing.checkout.completedTitle');
if (state.phase === 'EXPIRED') return t('billing.checkout.expiredTitle');
if (state.phase === 'CANCELED') return t('billing.checkout.canceledTitle');
@@ -192,15 +191,6 @@ export function BillingCheckoutDialog({
</>
)}
- {state.phase === 'FULFILLING' && (
- <>
- <Spinner size={26} className="text-[var(--text-secondary)]" />
- <p className="mt-4 text-sm text-[var(--text-secondary)]">
- {t('billing.checkout.creditingBody')}
- </p>
- </>
- )}
-
{state.phase === 'COMPLETED' && (
<>
<div className="grid size-14 place-items-center rounded-full bg-[var(--text-primary)] text-[var(--surface)]">
@@ -243,7 +233,7 @@ export function BillingCheckoutDialog({
)}
</div>
<div className="flex items-center gap-2">
- {(state.phase === 'AWAITING_PAYMENT' || state.phase === 'FULFILLING') && (
+ {state.phase === 'AWAITING_PAYMENT' && (
<button
type="button"
onClick={onRefresh}
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
index 56f3cc318e..0b06ee07c9 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
+++ b/apps/desktop/src/renderer/features/billing/__tests__/BillingPage.test.tsx
@@ -638,18 +638,44 @@ describe('BillingPage remote catalog rendering', () => {
expect(window.electronAPI.billing.getBalance).not.toHaveBeenCalled();
});
- it('refreshes the balance once when a checkout becomes completed', async () => {
+ it('refreshes the balance once and shows no recovery action when a top-up succeeds', async () => {
+ const pendingOrder = {
+ orderId: 'order_paid',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_custom',
+ amount: '10',
+ currency: 'cny',
+ status: 'PENDING' as const,
+ paymentAction: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:01:00.000Z',
+ };
+ Object.assign(checkout.state, {
+ open: true,
+ kind: 'TOPUP',
+ phase: 'AWAITING_PAYMENT',
+ order: pendingOrder,
+ });
const getBalance = window.electronAPI.billing.getBalance;
const view = render(<BillingPage />);
await waitFor(() => expect(getBalance).toHaveBeenCalledTimes(1));
- Object.assign(checkout.state, { phase: 'AWAITING_PAYMENT' });
- view.rerender(<BillingPage />);
- expect(getBalance).toHaveBeenCalledTimes(1);
-
- Object.assign(checkout.state, { phase: 'COMPLETED' });
+ Object.assign(checkout.state, {
+ phase: 'COMPLETED',
+ order: {
+ ...pendingOrder,
+ status: 'SUCCEEDED',
+ fulfillmentStatus: 'FAILED',
+ },
+ });
view.rerender(<BillingPage />);
await waitFor(() => expect(getBalance).toHaveBeenCalledTimes(2));
+ expect(screen.getByText('billing.checkout.completedTitle')).toBeTruthy();
+ expect(screen.getByText('billing.checkout.paymentCompleted')).toBeTruthy();
+ expect(screen.queryByText('billing.recovery.title')).toBeNull();
+ expect(
+ screen.queryByText((text) => text.startsWith('billing.recovery.continueTopup')),
+ ).toBeNull();
view.rerender(<BillingPage />);
expect(getBalance).toHaveBeenCalledTimes(2);
@@ -924,34 +950,6 @@ describe('BillingPage remote catalog rendering', () => {
expect(screen.queryByText('alipay')).toBeNull();
});
- it('shows a crediting state until top-up fulfillment succeeds', async () => {
- Object.assign(checkout.state, {
- open: true,
- kind: 'TOPUP',
- phase: 'FULFILLING',
- order: {
- orderId: 'order_paid',
- productCode: 'credit_topup',
- offerCode: 'credit_topup_custom',
- amount: '10',
- currency: 'cny',
- status: 'SUCCEEDED',
- fulfillmentStatus: 'FAILED',
- paymentAction: null,
- createdAt: '2026-01-01T00:00:00.000Z',
- updatedAt: '2026-01-01T00:01:00.000Z',
- },
- });
-
- render(<BillingPage />);
- await screen.findByText('billing.settings.subscriptionCard.empty');
-
- expect(screen.getByText('billing.checkout.fulfillingTitle')).toBeTruthy();
- expect(screen.getByText('billing.checkout.creditingBody')).toBeTruthy();
- expect(screen.queryByText('billing.checkout.completedTitle')).toBeNull();
- expect(screen.queryByText('billing.checkout.paymentCompleted')).toBeNull();
- });
-
it('allows an uncertain failed checkout to be dismissed for later recovery', async () => {
Object.assign(checkout.state, {
open: true,
diff --git a/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts b/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts
index 1b37644cdb..2929ba6053 100644
--- a/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts
+++ b/apps/desktop/src/renderer/features/billing/__tests__/useBillingCheckout.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const api = vi.hoisted(() => ({
listOrders: vi.fn(),
@@ -46,7 +46,11 @@ describe('billing checkout phase projection', () => {
});
});
- it('keeps paid top-ups crediting until fulfillment succeeds', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('treats successful top-ups as completed regardless of fulfillment projection', () => {
const base = {
orderId: 'order_fixture',
productCode: 'credit_topup',
@@ -58,10 +62,10 @@ describe('billing checkout phase projection', () => {
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:01:00.000Z',
};
- expect(phaseForOrder(base)).toBe('FULFILLING');
- expect(phaseForOrder({ ...base, fulfillmentStatus: 'PENDING' })).toBe('FULFILLING');
+ expect(phaseForOrder(base)).toBe('COMPLETED');
+ expect(phaseForOrder({ ...base, fulfillmentStatus: 'PENDING' })).toBe('COMPLETED');
expect(phaseForOrder({ ...base, fulfillmentStatus: 'SUCCEEDED' })).toBe('COMPLETED');
- expect(phaseForOrder({ ...base, fulfillmentStatus: 'FAILED' })).toBe('FULFILLING');
+ expect(phaseForOrder({ ...base, fulfillmentStatus: 'FAILED' })).toBe('COMPLETED');
});
it('shows active subscriptions as paid without exposing entitlement state', () => {
@@ -82,60 +86,51 @@ describe('billing checkout phase projection', () => {
});
it('lets the server confirm expiry instead of trusting the client clock', () => {
- expect(
- isRecoverableTopup({
- status: 'PENDING',
- paymentAction: {
- expiresAt: '2000-01-01T00:00:00.000Z',
- },
- }),
- ).toBe(true);
+ const pendingOrder = {
+ status: 'PENDING' as const,
+ paymentAction: {
+ expiresAt: '2000-01-01T00:00:00.000Z',
+ },
+ };
+ expect(isRecoverableTopup(pendingOrder)).toBe(true);
});
it('keeps created top-ups with a payment action recoverable', () => {
- expect(
- isRecoverableTopup({
- status: 'CREATED',
- paymentAction: {
- expiresAt: '2099-01-01T00:00:00.000Z',
- },
- }),
- ).toBe(true);
+ const createdOrder = {
+ status: 'CREATED' as const,
+ paymentAction: {
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ },
+ };
+ expect(isRecoverableTopup(createdOrder)).toBe(true);
});
it('keeps pending top-ups recoverable before a payment action is projected', () => {
- expect(
- isRecoverableTopup({
- status: 'CREATED',
- paymentAction: null,
- }),
- ).toBe(true);
- expect(
- isRecoverableTopup({
- status: 'PENDING',
- paymentAction: null,
- }),
- ).toBe(true);
+ const createdOrder = { status: 'CREATED' as const, paymentAction: null };
+ const pendingOrder = { status: 'PENDING' as const, paymentAction: null };
+ expect(isRecoverableTopup(createdOrder)).toBe(true);
+ expect(isRecoverableTopup(pendingOrder)).toBe(true);
});
- it('keeps paid but unfulfilled top-ups recoverable without a payment action', () => {
- expect(
- isRecoverableTopup({
- status: 'SUCCEEDED',
- fulfillmentStatus: 'PENDING',
- paymentAction: null,
- }),
- ).toBe(true);
- expect(
- isRecoverableTopup({
- status: 'SUCCEEDED',
- fulfillmentStatus: 'SUCCEEDED',
- paymentAction: null,
- }),
- ).toBe(false);
+ it('never treats successful top-ups as recoverable', () => {
+ const base = {
+ orderId: 'order_paid',
+ productCode: 'credit_topup',
+ offerCode: 'credit_topup_20',
+ amount: '20',
+ currency: 'cny',
+ status: 'SUCCEEDED' as const,
+ paymentAction: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:01:00.000Z',
+ };
+ for (const fulfillmentStatus of [undefined, 'PENDING', 'FAILED', 'SUCCEEDED'] as const) {
+ const order = fulfillmentStatus ? { ...base, fulfillmentStatus } : base;
+ expect(isRecoverableTopup(order)).toBe(false);
+ }
});
- it('keeps the checkout intent until paid top-up fulfillment succeeds', async () => {
+ it('completes a successful top-up immediately and clears its checkout intent', async () => {
const paidOrder = {
orderId: 'order_paid',
productCode: 'credit_topup',
@@ -143,16 +138,12 @@ describe('billing checkout phase projection', () => {
amount: '20',
currency: 'cny',
status: 'SUCCEEDED' as const,
- fulfillmentStatus: 'PENDING' as const,
paymentAction: null,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:01:00.000Z',
};
api.createTopup.mockResolvedValue(paidOrder);
- api.getOrder.mockResolvedValue({
- ...paidOrder,
- fulfillmentStatus: 'SUCCEEDED',
- });
+ const setIntervalSpy = vi.spyOn(window, 'setInterval');
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
await waitFor(() => expect(result.current.recovering).toBe(false));
@@ -163,14 +154,11 @@ describe('billing checkout phase projection', () => {
}),
);
- expect(result.current.state.phase).toBe('FULFILLING');
- expect(readBillingCheckoutIntent(ACCOUNT_ID)).not.toBeNull();
-
- await act(() => result.current.refreshActive());
-
- expect(api.getOrder).toHaveBeenCalledWith('order_paid');
expect(result.current.state.phase).toBe('COMPLETED');
+ expect(result.current.recoverables.topups).toEqual([]);
expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();
+ expect(api.getOrder).not.toHaveBeenCalled();
+ expect(setIntervalSpy).not.toHaveBeenCalledWith(expect.any(Function), 3_000);
});
it('replays an unresolved persisted purchase in the background without opening it', async () => {
@@ -237,7 +225,7 @@ describe('billing checkout phase projection', () => {
expect(result.current.state.subscription).toEqual(pending);
});
- it('keeps polling a restored paid top-up in the background until fulfillment succeeds', async () => {
+ it('completes a restored successful top-up in the background without polling', async () => {
const paidOrder = {
orderId: 'order_paid',
productCode: 'credit_topup',
@@ -262,23 +250,20 @@ describe('billing checkout phase projection', () => {
createdAt: '2026-01-01T00:00:00.000Z',
});
api.listOrders.mockResolvedValue({ orders: [paidOrder], nextCursor: null });
- api.getOrder.mockResolvedValue({
- ...paidOrder,
- fulfillmentStatus: 'SUCCEEDED',
- });
+ const setIntervalSpy = vi.spyOn(window, 'setInterval');
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
await waitFor(() => expect(result.current.recovering).toBe(false));
expect(result.current.state).toMatchObject({
open: false,
- phase: 'FULFILLING',
+ phase: 'COMPLETED',
order: paidOrder,
});
act(() => window.dispatchEvent(new Event('focus')));
- await waitFor(() => expect(result.current.state.phase).toBe('COMPLETED'));
- expect(api.getOrder).toHaveBeenCalledWith(paidOrder.orderId);
+ expect(api.getOrder).not.toHaveBeenCalled();
+ expect(setIntervalSpy).not.toHaveBeenCalledWith(expect.any(Function), 3_000);
expect(result.current.state.open).toBe(false);
expect(result.current.recoverables.topups).toEqual([]);
expect(readBillingCheckoutIntent(ACCOUNT_ID)).toBeNull();
@@ -457,7 +442,19 @@ describe('billing checkout phase projection', () => {
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:01:00.000Z',
};
- api.listOrders.mockResolvedValue({ orders: [pendingOrder], nextCursor: null });
+ const succeededOrder = {
+ ...pendingOrder,
+ orderId: 'order_succeeded',
+ status: 'SUCCEEDED' as const,
+ };
+ api.listOrders.mockResolvedValue({
+ orders: [
+ succeededOrder,
+ { ...succeededOrder, orderId: 'order_succeeded_legacy', fulfillmentStatus: 'FAILED' },
+ pendingOrder,
+ ],
+ nextCursor: null,
+ });
const { result } = renderHook(() => useBillingCheckout(ACCOUNT_ID));
await waitFor(() => expect(result.current.recovering).toBe(false));
diff --git a/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts b/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts
index 2aa41728e4..c15e255be0 100644
--- a/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts
+++ b/apps/desktop/src/renderer/features/billing/useBillingCheckout.ts
@@ -16,14 +16,7 @@ import {
} from './checkoutIntent';
export type BillingCheckoutPhase =
- | 'IDLE'
- | 'CREATING'
- | 'AWAITING_PAYMENT'
- | 'FULFILLING'
- | 'COMPLETED'
- | 'FAILED'
- | 'EXPIRED'
- | 'CANCELED';
+ 'IDLE' | 'CREATING' | 'AWAITING_PAYMENT' | 'COMPLETED' | 'FAILED' | 'EXPIRED' | 'CANCELED';
export type BillingCheckoutState = {
open: boolean;
@@ -56,9 +49,7 @@ function phaseForOrder(order: BillingPaymentOrder): BillingCheckoutPhase {
if (order.status === 'FAILED') return 'FAILED';
if (order.status === 'EXPIRED') return 'EXPIRED';
if (order.status === 'CANCELED') return 'CANCELED';
- if (order.status === 'SUCCEEDED') {
- return order.fulfillmentStatus === 'SUCCEEDED' ? 'COMPLETED' : 'FULFILLING';
- }
+ if (order.status === 'SUCCEEDED') return 'COMPLETED';
return 'AWAITING_PAYMENT';
}
@@ -74,16 +65,8 @@ function isTerminal(phase: BillingCheckoutPhase): boolean {
return ['COMPLETED', 'FAILED', 'EXPIRED', 'CANCELED'].includes(phase);
}
-function isRecoverableTopup(value: {
- status: string;
- fulfillmentStatus?: string;
- paymentAction: { expiresAt: string } | null;
-}): boolean {
- return (
- value.status === 'CREATED' ||
- value.status === 'PENDING' ||
- (value.status === 'SUCCEEDED' && value.fulfillmentStatus !== 'SUCCEEDED')
- );
+function isRecoverableTopup(value: Pick<BillingPaymentOrder, 'status'>): boolean {
+ return value.status === 'CREATED' || value.status === 'PENDING';
}
function persistIntent(accountId: string | null, intent: BillingCheckoutIntentV1 | null): void {
@@ -578,8 +561,7 @@ export function useBillingCheckout(accountId: string | null) {
}, [accountId, applyOrder, applySubscription, failCurrentOperation]);
useEffect(() => {
- const shouldPoll =
- state.phase === 'FULFILLING' || (state.open && state.phase === 'AWAITING_PAYMENT');
+ const shouldPoll = state.open && state.phase === 'AWAITING_PAYMENT';
if (!shouldPoll) return;
const timer = window.setInterval(() => {
if (document.visibilityState === 'visible') void refreshActive();
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 52d3383c24..db08176b9a 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3787,6 +3787,8 @@
"output": "Output",
"cacheRead": "Cache read",
"cacheCreate": "Cache write",
+ "free": "Limited-time free",
+ "discount": "Save {{percent}}%",
"perMillion": "Standard model pricing",
"fixedFx": "Estimated at the fixed rate of 1 USD = 6.7 CNY",
"subscriptionEstimate": "Value estimate, not an actual bill"
@@ -7257,7 +7259,6 @@
"checkout": {
"creatingTitle": "Creating payment",
"awaitingTitle": "Awaiting payment",
- "fulfillingTitle": "Crediting your account",
"completedTitle": "Payment successful",
"failedTitle": "Unable to complete",
"expiredTitle": "Payment expired",
@@ -7272,7 +7273,6 @@
"redirectHint": "Complete payment on the provider page, then return to Cindy.",
"openPayment": "Open payment page",
"refreshingAction": "Loading payment instructions…",
- "creditingBody": "Payment succeeded. Waiting for the credits to be applied…",
"paymentCompleted": "Your payment was completed.",
"requestFailed": "The request failed. Retry safely; an uncertain create result keeps the original idempotency key.",
"expiredBody": "This payment link expired. Create a new payment to continue.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a054861fb8..f53983462e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3786,6 +3786,8 @@
"output": "出力",
"cacheRead": "キャッシュ読み取り",
"cacheCreate": "キャッシュ書き込み",
+ "free": "期間限定無料",
+ "discount": "{{percent}}%お得",
"perMillion": "モデル標準価格",
"fixedFx": "固定レート 1 USD = 6.7 CNY による概算",
"subscriptionEstimate": "価値の推定であり、実際の請求額ではありません"
@@ -7246,7 +7248,6 @@
"checkout": {
"creatingTitle": "支払いを作成中",
"awaitingTitle": "支払い待ち",
- "fulfillingTitle": "クレジットを反映中",
"completedTitle": "支払い完了",
"failedTitle": "完了できませんでした",
"expiredTitle": "支払い期限切れ",
@@ -7261,7 +7262,6 @@
"redirectHint": "支払いページで完了後、Cindyに戻ってください。",
"openPayment": "支払いページを開く",
"refreshingAction": "支払い情報を取得中…",
- "creditingBody": "支払いが完了しました。クレジットの反映を待っています…",
"paymentCompleted": "支払いが完了しました。",
"requestFailed": "リクエストに失敗しました。不明な作成結果では同じ冪等キーで安全に再試行します。",
"expiredBody": "支払いリンクの期限が切れました。新しい支払いを作成してください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 755bb242a7..4963687d3e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3786,6 +3786,8 @@
"output": "출력",
"cacheRead": "캐시 읽기",
"cacheCreate": "캐시 쓰기",
+ "free": "기간 한정 무료",
+ "discount": "{{percent}}% 절약",
"perMillion": "모델 표준 가격",
"fixedFx": "고정 환율 1 USD = 6.7 CNY 기준 추정",
"subscriptionEstimate": "가치 추정치이며 실제 청구 금액이 아닙니다"
@@ -7246,7 +7248,6 @@
"checkout": {
"creatingTitle": "결제 생성 중",
"awaitingTitle": "결제 대기",
- "fulfillingTitle": "크레딧 반영 중",
"completedTitle": "결제 완료",
"failedTitle": "완료할 수 없음",
"expiredTitle": "결제 만료",
@@ -7261,7 +7262,6 @@
"redirectHint": "결제 페이지에서 완료한 뒤 Cindy로 돌아오세요.",
"openPayment": "결제 페이지 열기",
"refreshingAction": "결제 정보를 불러오는 중…",
- "creditingBody": "결제가 완료되었습니다. 크레딧이 반영되기를 기다리는 중입니다…",
"paymentCompleted": "결제가 완료되었습니다.",
"requestFailed": "요청에 실패했습니다. 결과가 불확실한 생성 요청은 같은 멱등성 키로 안전하게 재시도합니다.",
"expiredBody": "결제 링크가 만료되었습니다. 새 결제를 생성하세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index feb432f315..b447723a2a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3786,6 +3786,8 @@
"output": "输出",
"cacheRead": "缓存读取",
"cacheCreate": "缓存写入",
+ "free": "限时免费",
+ "discount": "立省 {{percent}}%",
"perMillion": "模型标准价格",
"fixedFx": "按固定汇率 1 USD = 6.7 CNY 约算",
"subscriptionEstimate": "价值估算,不代表实际账单"
@@ -7246,7 +7248,6 @@
"checkout": {
"creatingTitle": "正在创建支付",
"awaitingTitle": "等待支付",
- "fulfillingTitle": "正在发放点数",
"completedTitle": "支付成功",
"failedTitle": "暂时无法完成",
"expiredTitle": "支付已过期",
@@ -7261,7 +7262,6 @@
"redirectHint": "请在支付页面完成操作,完成后返回 Cindy。",
"openPayment": "打开支付页面",
"refreshingAction": "正在获取支付方式…",
- "creditingBody": "支付已完成,正在等待点数到账…",
"paymentCompleted": "支付已完成。",
"requestFailed": "请求失败。可以重试;结果不确定时会继续复用原幂等请求。",
"expiredBody": "支付链接已过期,请重新创建支付。",
diff --git a/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.ts b/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.ts
index 4ff062307e..4053f9016e 100644
--- a/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.ts
@@ -3,7 +3,9 @@ import { describe, expect, it } from 'vitest';
import type { ModelPriceQuote } from '../../../shared/regionalMoney';
import {
formatModelPricePair,
+ modelPriceDiscountLabelValues,
modelPriceDetailRows,
+ modelPricePresentation,
} from '../modelPriceFormat';
function quote(overrides: Partial<ModelPriceQuote> = {}): ModelPriceQuote {
@@ -39,9 +41,7 @@ describe('modelPriceFormat', () => {
it('includes configured cache prices in details', () => {
expect(
- modelPriceDetailRows(
- quote({ cacheReadPerMtok: 0.3, cacheCreatePerMtok: 3.75 }),
- ),
+ modelPriceDetailRows(quote({ cacheReadPerMtok: 0.3, cacheCreatePerMtok: 3.75 })),
).toEqual([
{ kind: 'input', value: '¥3' },
{ kind: 'output', value: '¥15' },
@@ -49,4 +49,83 @@ describe('modelPriceFormat', () => {
{ kind: 'cacheCreate', value: '¥3.75' },
]);
});
+
+ it('uses the effective price while retaining the original for a 50% discount', () => {
+ const original = quote({ inputPerMtok: 12, outputPerMtok: 36 });
+ expect(modelPricePresentation(original, { input: 6, output: 18 })).toEqual({
+ kind: 'priced',
+ current: quote({ inputPerMtok: 6, outputPerMtok: 18 }),
+ original,
+ discount: 0.5,
+ });
+ expect(modelPriceDiscountLabelValues(0.5)).toEqual({
+ percent: '50',
+ rate: '5',
+ });
+ expect(modelPriceDiscountLabelValues(0.2)).toEqual({
+ percent: '20',
+ rate: '8',
+ });
+ expect(
+ modelPriceDetailRows(
+ quote({ inputPerMtok: 6, outputPerMtok: 18, cacheReadPerMtok: 0.3 }),
+ original,
+ ),
+ ).toEqual([
+ { kind: 'input', value: '¥6', originalValue: '¥12' },
+ { kind: 'output', value: '¥18', originalValue: '¥36' },
+ { kind: 'cacheRead', value: '¥0.3' },
+ ]);
+ });
+
+ it('marks only an explicit double-zero model price with a confirmed missing quote as free', () => {
+ expect(modelPricePresentation(null, { input: 0, output: 0 })).toEqual({
+ kind: 'free',
+ });
+ expect(modelPricePresentation(undefined, { input: 0, output: 0 })).toBeNull();
+ });
+
+ it('keeps double-zero effective prices as a 100% discount when the quote is nonzero', () => {
+ const original = quote({ inputPerMtok: 12, outputPerMtok: 36 });
+ expect(modelPricePresentation(original, { input: 0, output: 0 })).toEqual({
+ kind: 'priced',
+ current: quote({ inputPerMtok: 0, outputPerMtok: 0 }),
+ original,
+ discount: 1,
+ });
+ });
+
+ it('preserves the standard price when there is no discount', () => {
+ const standard = quote({ inputPerMtok: 12, outputPerMtok: 36 });
+ expect(modelPricePresentation(standard, { input: 12, output: 36 })).toEqual({
+ kind: 'priced',
+ current: standard,
+ });
+ });
+
+ it('ignores sub-threshold floating-point discount noise', () => {
+ const standard = quote({ inputPerMtok: 12, outputPerMtok: 36 });
+ expect(
+ modelPricePresentation(standard, {
+ input: 12 * (1 - 1e-12),
+ output: 36 * (1 - 1e-12),
+ }),
+ ).toEqual({
+ kind: 'priced',
+ current: standard,
+ });
+ });
+
+ it('keeps missing or inconsistent display costs on the existing fallback path', () => {
+ const standard = quote({ inputPerMtok: 12, outputPerMtok: 36 });
+ expect(modelPricePresentation(standard, { input: 6 })).toEqual({
+ kind: 'priced',
+ current: standard,
+ });
+ expect(modelPricePresentation(undefined, { input: 0 })).toBeNull();
+ expect(modelPricePresentation(standard, { input: 6, output: 30 })).toEqual({
+ kind: 'priced',
+ current: standard,
+ });
+ });
});
diff --git a/apps/desktop/src/renderer/lib/__tests__/tabLabels.test.ts b/apps/desktop/src/renderer/lib/__tests__/tabLabels.test.ts
new file mode 100644
index 0000000000..c1ee9f4faa
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/tabLabels.test.ts
@@ -0,0 +1,11 @@
+import { describe, expect, it } from 'vitest';
+
+import { TAB_IDS } from '@/lib/tabLabels';
+
+describe('Settings tab order', () => {
+ it('places billing immediately after model providers', () => {
+ const providersIndex = TAB_IDS.indexOf('providers');
+
+ expect(TAB_IDS.slice(providersIndex, providersIndex + 2)).toEqual(['providers', 'billing']);
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/modelPriceFormat.ts b/apps/desktop/src/renderer/lib/modelPriceFormat.ts
index 5a0d2e6a9d..98a9213bc0 100644
--- a/apps/desktop/src/renderer/lib/modelPriceFormat.ts
+++ b/apps/desktop/src/renderer/lib/modelPriceFormat.ts
@@ -1,7 +1,20 @@
-import type {
- ModelPriceQuote,
- MoneyCurrency,
-} from '../../shared/regionalMoney';
+import type { ModelPriceQuote, MoneyCurrency } from '../../shared/regionalMoney';
+
+interface EffectiveModelCost {
+ input?: number;
+ output?: number;
+}
+
+const MIN_DISPLAY_DISCOUNT = 0.0005;
+
+export type ModelPricePresentation =
+ | { kind: 'free' }
+ | {
+ kind: 'priced';
+ current: ModelPriceQuote;
+ original?: ModelPriceQuote;
+ discount?: number;
+ };
function compactNumber(value: number): string {
return new Intl.NumberFormat('en-US', {
@@ -10,10 +23,7 @@ function compactNumber(value: number): string {
}).format(value);
}
-export function formatModelPriceAmount(
- amount: number,
- currency: MoneyCurrency,
-): string {
+export function formatModelPriceAmount(amount: number, currency: MoneyCurrency): string {
return `${currency === 'CNY' ? '¥' : '$'}${compactNumber(amount)}`;
}
@@ -23,30 +33,122 @@ export function formatModelPricePair(quote: ModelPriceQuote): string {
return `${quote.approximate ? '≈' : ''}${input} / ${output}`;
}
+export function modelPriceDiscountLabelValues(discount: number): {
+ percent: string;
+ rate: string;
+} {
+ return {
+ percent: compactNumber(discount * 100),
+ rate: compactNumber((1 - discount) * 10),
+ };
+}
+
+function isNonNegativeFinite(value: unknown): value is number {
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
+}
+
+function inferDiscount(
+ quote: ModelPriceQuote,
+ cost: Required<EffectiveModelCost>,
+): number | undefined {
+ const candidates: number[] = [];
+ for (const [original, current] of [
+ [quote.inputPerMtok, cost.input],
+ [quote.outputPerMtok, cost.output],
+ ] as const) {
+ if (original === 0) {
+ if (current !== 0) return undefined;
+ continue;
+ }
+ const candidate = 1 - current / original;
+ if (candidate < MIN_DISPLAY_DISCOUNT || candidate > 1) return undefined;
+ candidates.push(candidate);
+ }
+ if (candidates.length === 0) return undefined;
+ const discount = candidates[0];
+ return candidates.every((candidate) => Math.abs(candidate - discount) < 1e-9)
+ ? discount
+ : undefined;
+}
+
+/**
+ * 构建模型选择器的展示价格。quote 继续保留用量估算所需的标准价;
+ * CatalogModel.cost 只承载 XD 模型的折后展示价。
+ */
+export function modelPricePresentation(
+ quote: ModelPriceQuote | null | undefined,
+ effectiveCost: EffectiveModelCost | null | undefined,
+): ModelPricePresentation | null {
+ if (quote === undefined) return null;
+
+ const input = effectiveCost?.input;
+ const output = effectiveCost?.output;
+ const hasEffectiveCost = isNonNegativeFinite(input) && isNonNegativeFinite(output);
+
+ if (
+ hasEffectiveCost &&
+ input === 0 &&
+ output === 0 &&
+ (quote === null || (quote.inputPerMtok === 0 && quote.outputPerMtok === 0))
+ ) {
+ return { kind: 'free' };
+ }
+ if (quote === null) return null;
+ if (!hasEffectiveCost) return { kind: 'priced', current: quote };
+
+ const discount = inferDiscount(quote, { input, output });
+ if (discount === undefined) return { kind: 'priced', current: quote };
+ return {
+ kind: 'priced',
+ current: {
+ ...quote,
+ inputPerMtok: input,
+ outputPerMtok: output,
+ },
+ original: quote,
+ discount,
+ };
+}
+
export function modelPriceDetailRows(
quote: ModelPriceQuote,
+ originalQuote?: ModelPriceQuote,
): Array<{
kind: 'input' | 'output' | 'cacheRead' | 'cacheCreate';
value: string;
+ originalValue?: string;
}> {
return [
{
kind: 'input' as const,
value: formatModelPriceAmount(quote.inputPerMtok, quote.currency),
+ ...(originalQuote
+ ? {
+ originalValue: formatModelPriceAmount(
+ originalQuote.inputPerMtok,
+ originalQuote.currency,
+ ),
+ }
+ : {}),
},
{
kind: 'output' as const,
value: formatModelPriceAmount(quote.outputPerMtok, quote.currency),
+ ...(originalQuote
+ ? {
+ originalValue: formatModelPriceAmount(
+ originalQuote.outputPerMtok,
+ originalQuote.currency,
+ ),
+ }
+ : {}),
},
...(quote.cacheReadPerMtok === undefined
? []
: [
{
kind: 'cacheRead' as const,
- value: formatModelPriceAmount(
- quote.cacheReadPerMtok,
- quote.currency,
- ),
+ value: formatModelPriceAmount(quote.cacheReadPerMtok, quote.currency),
},
]),
...(quote.cacheCreatePerMtok === undefined
@@ -54,10 +156,7 @@ export function modelPriceDetailRows(
: [
{
kind: 'cacheCreate' as const,
- value: formatModelPriceAmount(
- quote.cacheCreatePerMtok,
- quote.currency,
- ),
+ value: formatModelPriceAmount(quote.cacheCreatePerMtok, quote.currency),
},
]),
];
diff --git a/apps/desktop/src/renderer/lib/tabLabels.ts b/apps/desktop/src/renderer/lib/tabLabels.ts
index 1cc2043111..b442bcb9d0 100644
--- a/apps/desktop/src/renderer/lib/tabLabels.ts
+++ b/apps/desktop/src/renderer/lib/tabLabels.ts
@@ -25,9 +25,9 @@ export type SettingsTab =
export const TAB_IDS: ReadonlyArray<SettingsTab> = [
'general',
- 'billing',
'personalization',
'providers',
+ 'billing',
// 「工具密钥」(api-keys)已于 2026-07-13 下架:面板里最后一把 mivo key 随
// XD Mivo 意识化改由意识设置页收单(官方别名映射同一存储键)。id 仍留在
// SettingsTab 类型与 TAB_LABEL_KEY 保留,供旧深链重定向到插件页。