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(model-access): 在模型详情展示可选复杂价目

liugaoweica33b93db7c0
diff --git a/apps/desktop/src/main/maker-host/__tests__/modelMetadataLayers.integration.test.ts b/apps/desktop/src/main/maker-host/__tests__/modelMetadataLayers.integration.test.ts
index a27b2a5970..c04aadf57c 100644
--- a/apps/desktop/src/main/maker-host/__tests__/modelMetadataLayers.integration.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/modelMetadataLayers.integration.test.ts
@@ -584,3 +584,20 @@ describe('metadata layers through the active catalog', () => {
);
});
});
+
+
+it('keeps complex quotes with their provider snapshot and clears them on successful replacement', () => {
+ const displayPricing = { items: [{ label: 'Generated video', tier: 'HD', price: 0.5, unit: 'second', quantity: 1, priceType: 'estimated' as const }], notes: ['Billed by output duration.'] };
+ const video = { id: 'example-video', name: 'Video', mode: 'video_generation', agents: [] as const,
+ currency: 'USD' as const, costDiscount: 0.2, displayPricing,
+ modalities: { input: ['text'], output: ['video'] } };
+ setActiveCatalog({ ...BUNDLED_CATALOG });
+ setXdGatewayModels([{ ...video, agents: [] }], { authoritative: true });
+ const provider = () => getActiveCatalog().providers.find((p) => p.id === 'xd')!;
+ expect(provider().videoModels?.[0]).toMatchObject({ displayPricing, currency: 'USD', costDiscount: 0.2 });
+ expect(Object.values(provider().models).flat().some((m) => m?.id === video.id)).toBe(false);
+ setXdGatewayModels([{ ...video, displayPricing: undefined, agents: [] }], { authoritative: true });
+ expect(provider().videoModels?.[0]).not.toHaveProperty('displayPricing');
+ setXdGatewayModels([], { authoritative: true });
+ expect(provider().videoModels).toEqual([]);
+});
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index 06402f70b4..802edc8c13 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -1,3 +1,4 @@
+import type { ModelDisplayPricing } from '@cindy/model-providers';
import {
projectProviderMediaModels,
isCustomRoutedProvider,
@@ -184,6 +185,8 @@ export interface XdGatewayAgentOverride {
* 能力字段已由服务端一次归一化,客户端不再二次转换(见 model-access/index.ts)。
*/
export interface XdGatewayModelInfo {
+ displayPricing?: ModelDisplayPricing;
+ currency?: 'USD' | 'CNY';
id: string;
availability?: 'available' | 'requires_payment';
/** Gateway 原生 mode(issue #882,权威分类字段;缺省时下游按 id 正则兜底)。 */
@@ -1107,6 +1110,14 @@ function declaredPiModels(providerId: string, discovered: readonly CatalogModel[
return [...byId.values()];
}
+function gatewayDisplayPricing(model: XdGatewayModelInfo): Pick<CatalogModel, 'displayPricing' | 'currency' | 'costDiscount'> {
+ return model.displayPricing && model.currency ? {
+ displayPricing: model.displayPricing,
+ currency: model.currency,
+ ...(model.costDiscount !== undefined ? { costDiscount: model.costDiscount } : {}),
+ } : {};
+}
+
function projectXdGatewayMediaModels(
provider: Provider,
gatewayModels: readonly XdGatewayModelInfo[],
@@ -1116,6 +1127,7 @@ function projectXdGatewayMediaModels(
.filter((model) => model.mode === 'image_generation')
.map((model) => ({
...pickModelMetadata(model),
+ ...gatewayDisplayPricing(model),
id: model.id,
name: model.name ?? model.id,
discoveredMetadata: pickModelMetadata(model),
@@ -1126,6 +1138,7 @@ function projectXdGatewayMediaModels(
.filter((model) => model.mode === 'video_generation')
.map((model) => ({
...pickModelMetadata(model),
+ ...gatewayDisplayPricing(model),
id: model.id,
name: model.name ?? model.id,
discoveredMetadata: pickModelMetadata(model),
@@ -1139,6 +1152,7 @@ function projectXdGatewayMediaModels(
.filter((model) => model.mode === 'embedding' && model.availability === 'available')
.map((model) => ({
...pickModelMetadata(model),
+ ...gatewayDisplayPricing(model),
id: model.id,
name: model.name ?? model.id,
discoveredMetadata: pickModelMetadata(model),
@@ -1151,6 +1165,7 @@ function projectXdGatewayMediaModels(
)
.map((model) => ({
...pickModelMetadata(model),
+ ...gatewayDisplayPricing(model),
id: model.id,
name: model.name ?? model.id,
mode: model.mode,
@@ -1562,6 +1577,7 @@ function computeMerged(): Catalog {
const cost = effectiveGatewayModelCost(gm);
const contextWindow = ov.contextWindow ?? gm.contextWindow;
const merged: CatalogModel = {
+ ...gatewayDisplayPricing(gm),
id: gm.id,
discoveredMetadata: { ...pickModelMetadata(gm), ...pickModelMetadata(ov) },
...(nativeApi !== undefined ? { nativeApi } : {}),
diff --git a/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts b/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts
index 6be16a8415..eee79af784 100644
--- a/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts
+++ b/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts
@@ -196,7 +196,7 @@ describe('listAvailableMediaModels', () => {
]);
expect(serverApiFetchMock).toHaveBeenCalledWith(
'/api/model-access/models?schemaVersion=5',
- expect.any(Object),
+ expect.objectContaining({ headers: { 'X-Cindy-Model-Capabilities': 'display_pricing' } }),
);
});
diff --git a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
index 68d55bc6ba..89ff8277b5 100644
--- a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
+++ b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
@@ -28,6 +28,20 @@ describe('parseModelsSyncPayload', () => {
},
);
+ it('accepts quote removal or an unsupported quote as a successful replacement', () => {
+ const model = {
+ id: 'example-video', name: 'Example Video', mode: 'video_generation',
+ currency: 'USD', agents: [], availability: 'available',
+ };
+ const quote = { items: [{ label: 'Output', price: 0.5, unit: 'second', quantity: 1 }] };
+ const response = { schemaVersion: 5, accountTier: 'paid', models: [{ ...model, displayPricing: quote }] };
+ expect(parseModelsSyncPayload(response)).toMatchObject({ ok: true, models: [{ displayPricing: quote }] });
+ for (const displayPricing of [undefined, null, { items: [] }, { items: [{ ...quote.items[0], priceType: 'future' }] }]) {
+ expect(parseModelsSyncPayload({ ...response, models: [{ ...model, displayPricing }] }))
+ .toEqual({ ok: true, accountTier: 'paid', models: [model] });
+ }
+ });
+
const baseModel = {
id: 'deepseek/deepseek-v4-pro',
name: 'DeepSeek V4 Pro',
@@ -237,7 +251,7 @@ describe('waitForModelsSyncRefresh', () => {
baseUrl: 'https://model-access.example.com',
timeoutMs: 20_000,
cache: 'no-store',
- headers: { 'X-Cindy-Model-Capabilities': 'audio_speech' },
+ headers: { 'X-Cindy-Model-Capabilities': 'audio_speech,display_pricing' },
},
});
expect(Number.isFinite(XD_MODELS_SYNC_TIMEOUT_MS)).toBe(true);
diff --git a/apps/desktop/src/main/model-access/mediaModels.ts b/apps/desktop/src/main/model-access/mediaModels.ts
index d1a24fe37d..9368ab1d83 100644
--- a/apps/desktop/src/main/model-access/mediaModels.ts
+++ b/apps/desktop/src/main/model-access/mediaModels.ts
@@ -200,6 +200,7 @@ async function fetchGatewayMediaModels(): Promise<GatewayMediaCatalogEntry[]> {
baseUrl: () => getClientEndpoint('modelAccessApiBaseUrl'),
timeoutMs: MEDIA_MODEL_REQUEST_TIMEOUT_MS,
logLabel: MEDIA_MODELS_PATH,
+ headers: { 'X-Cindy-Model-Capabilities': 'display_pricing' },
});
if (
typeof payload !== 'object' ||
diff --git a/apps/desktop/src/main/model-access/modelsSyncRefresh.ts b/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
index e370338567..552fc78816 100644
--- a/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
+++ b/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
@@ -86,7 +86,7 @@ export function buildModelsSyncRequest(baseUrl: string | (() => string)): {
// followed in 5c47051ac (2026-09-10). Earlier V5 parsers reject the whole list
// for audio_speech with agents: [], so schemaVersion=5 alone cannot prove support.
// This declares parser support only; older servers safely ignore the opt-in.
- headers: { 'X-Cindy-Model-Capabilities': 'audio_speech' },
+ headers: { 'X-Cindy-Model-Capabilities': 'audio_speech,display_pricing' },
// 模型权限随订阅权益变化,强制刷新不能命中 Electron HTTP cache。
cache: 'no-store',
},
diff --git a/apps/desktop/src/renderer/components/DisplayPricingDetails.tsx b/apps/desktop/src/renderer/components/DisplayPricingDetails.tsx
new file mode 100644
index 0000000000..e636739ccd
--- /dev/null
+++ b/apps/desktop/src/renderer/components/DisplayPricingDetails.tsx
@@ -0,0 +1,82 @@
+import { useTranslation } from 'react-i18next';
+import type { CatalogModel, ModelDisplayPricing } from '@cindy/model-providers';
+import { displayPricingAmount } from '@/lib/displayPricingFormat';
+
+type PricingModel = Pick<CatalogModel, 'displayPricing' | 'currency' | 'costDiscount'>;
+const UNIT_KEYS = {
+ token: 'newChat.modelSelector.displayPricing.units.token',
+ character: 'newChat.modelSelector.displayPricing.units.character',
+ image: 'newChat.modelSelector.displayPricing.units.image',
+ second: 'newChat.modelSelector.displayPricing.units.second',
+ minute: 'newChat.modelSelector.displayPricing.units.minute',
+ request: 'newChat.modelSelector.displayPricing.units.request',
+ megapixel: 'newChat.modelSelector.displayPricing.units.megapixel',
+ megapixel_second: 'newChat.modelSelector.displayPricing.units.megapixelSecond',
+} as const;
+
+/** Uses the selected source's snapshot, including currency and undiscounted amounts. */
+export function DisplayPricingDetails({ model }: { model: PricingModel }) {
+ const { t, i18n } = useTranslation();
+ if (!model.displayPricing || !model.currency) return null;
+ const locale = i18n.resolvedLanguage ?? i18n.language;
+ const groups = new Map<string, ModelDisplayPricing['items']>();
+ for (const item of model.displayPricing.items) {
+ const rows = groups.get(item.label) ?? [];
+ rows.push(item);
+ groups.set(item.label, rows);
+ }
+ return (
+ <div className="space-y-3 text-12 text-[var(--text-secondary)]">
+ {Array.from(groups, ([label, items]) => (
+ <div key={label} className="space-y-1">
+ <div className="break-words font-medium text-[var(--text-primary)]">{label}</div>
+ {items.map((item, index) => {
+ const amount = displayPricingAmount(item, model.currency!, model.costDiscount, locale);
+ const unit = Object.hasOwn(UNIT_KEYS, item.unit)
+ ? t(UNIT_KEYS[item.unit as keyof typeof UNIT_KEYS])
+ : item.unit;
+ const quantity =
+ item.quantity === 1
+ ? ''
+ : new Intl.NumberFormat(locale, {
+ maximumSignificantDigits: 12,
+ }).format(item.quantity) + ' ';
+ const price = amount.free ? t('newChat.modelSelector.pricing.free') : amount.current;
+ const qualifiedPrice =
+ item.priceType === 'estimated'
+ ? t('newChat.modelSelector.displayPricing.estimated', { price })
+ : item.priceType === 'starting_at'
+ ? t('newChat.modelSelector.displayPricing.startingAt', { price })
+ : price;
+ return (
+ <div
+ key={index}
+ className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1"
+ >
+ {item.tier && <span className="min-w-0 break-words">{item.tier}</span>}
+ <span className="min-w-0 break-words tabular-nums">
+ {qualifiedPrice}
+ {amount.original && (
+ <s className="ml-1.5 text-[var(--text-tertiary)]">{amount.original}</s>
+ )}
+ <span className="ml-1 text-[var(--text-tertiary)]">
+ / {quantity}
+ {unit}
+ </span>
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ ))}
+ {model.displayPricing.notes?.map((note, index) => (
+ <p
+ key={index}
+ className="whitespace-pre-wrap break-words text-11 leading-relaxed text-[var(--text-tertiary)]"
+ >
+ {note}
+ </p>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx b/apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx
index 9627ab5d20..7521293a20 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx
@@ -1,3 +1,4 @@
+import { DisplayPricingDetails } from '@/components/DisplayPricingDetails';
import { useModelContextLimit } from '@/hooks/useModelContextLimit';
import { localizedModelName } from '@/lib/modelDisplayNames';
import { Star, Zap } from 'lucide-react';
@@ -225,7 +226,12 @@ export function ModelConfigFlyout({
onChange={onEngineChange}
/>
- {price && (
+ {config.capability?.displayPricing && config.capability.currency && (
+ <div className="mt-2.5 max-h-72 overflow-y-auto border-t border-[var(--model-dropdown-border)] pt-2.5">
+ <DisplayPricingDetails model={config.capability} />
+ </div>
+ )}
+ {!config.capability?.displayPricing && price && (
// 价格区(设计稿 v4 定稿):**紧凑两行**,不画删除线表格。
// 第 1 行:每百万 token · 折扣中,较标准价省 X%(省 X% 绿色加粗)
// 第 2 行:折后价单行排列 —— 输入 ¥32 · 输出 ¥162 · 缓存读取 ¥3.2
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
index 5e38c93ead..5dca0803f8 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx
@@ -1,3 +1,4 @@
+import { DisplayPricingDetails } from '@/components/DisplayPricingDetails';
import { Button } from '@/components/ui/button';
import { localizedModelDescription } from '@/lib/modelDescriptions';
import { localizedModelName, matchesModelName } from '@/lib/modelDisplayNames';
@@ -2614,6 +2615,8 @@ function ModelSelectorContentView({
currentProviderId,
resolveCurrentSourceId,
]);
+ const editingDisplayPricingModel = editingProvider && editingModel && currentAgentKind
+ ? findCatalogModel(editingProvider, editingModel.id, currentAgentKind, { exact: true }) : undefined;
const editingPricePresentation = editingModel
? pricePresentationOf(editingProvider?.id ?? editingProviderId, editingModel.id)
: null;
@@ -2758,7 +2761,12 @@ function ModelSelectorContentView({
{(editShowFast || editHasEfforts) && (
<div className="mx-1 my-1 h-px bg-[var(--model-dropdown-border)]" />
)}
- {editingPricePresentation && (
+ {editingDisplayPricingModel?.displayPricing && editingDisplayPricingModel.currency && (
+ <div className="max-h-72 overflow-y-auto border-t border-[var(--model-dropdown-border)] pt-2.5">
+ <DisplayPricingDetails model={editingDisplayPricingModel} />
+ </div>
+ )}
+ {!editingDisplayPricingModel?.displayPricing && editingPricePresentation && (
<>
<div {...menuSkipAttrs} className="px-2 pb-1 pt-1">
<div
diff --git a/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx b/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx
index 133efd2f30..2a4b0fa9a7 100644
--- a/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx
+++ b/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx
@@ -1,3 +1,4 @@
+import { DisplayPricingDetails } from '@/components/DisplayPricingDetails';
import { Button } from '@/components/ui/button';
import { localizedModelDescription } from '@/lib/modelDescriptions';
import { localizedModelName, localizedBrandName } from '@/lib/modelDisplayNames';
@@ -965,7 +966,9 @@ export function ModelAdvancedDrawer({
</Section>
<Section title={t('settings.providers.models.advanced.pricing')}>
- {price === null ? (
+ {primaryModel.displayPricing && primaryModel.currency ? (
+ <DisplayPricingDetails model={primaryModel} />
+ ) : price === null ? (
<Row label={t('settings.providers.models.advanced.pricingLabel')} muted>
{t(
provider.access?.kind === 'subscription'
@@ -997,7 +1000,7 @@ export function ModelAdvancedDrawer({
</Row>
))
)}
- {price?.kind === 'priced' && price.discount !== undefined && (
+ {!primaryModel.displayPricing && price?.kind === 'priced' && price.discount !== undefined && (
<Row label={t('settings.providers.models.advanced.discount')}>
<span
className="inline-flex items-center rounded-full px-2 py-[1px] text-10 font-medium"
diff --git a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
index 1bf7604c01..a1693cbb05 100644
--- a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
+++ b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
@@ -227,6 +227,9 @@ export function buildUnionRows(provider: ProviderView): UnionModelRow[] {
disabled?: boolean;
availability?: CatalogModel['availability'];
group: 'image' | 'video' | 'embedding' | 'audio' | 'tts' | 'stt' | 'realtime';
+ displayPricing?: CatalogModel['displayPricing'];
+ currency?: CatalogModel['currency'];
+ costDiscount?: number;
mode?: string;
modalities?: CatalogModel['modalities'];
defaultEnabled?: boolean;
@@ -248,6 +251,7 @@ export function buildUnionRows(provider: ProviderView): UnionModelRow[] {
for (const m of media) {
if (realIds.has(m.id) || byKey.has(m.id)) continue;
const entry: CatalogModel = {
+ ...(m.displayPricing && m.currency ? { displayPricing: m.displayPricing, currency: m.currency, costDiscount: m.costDiscount } : {}),
id: m.id,
name: m.name,
contextWindow: 0,
@@ -985,6 +989,8 @@ export function UnifiedModelList({
是用来在读到某个模型名时顺手知道它贵不贵。拿不到报价就整个
不渲染 —— 不画假的「$」也不画「—」。 */}
{(() => {
+ // Mixed-unit quotes are shown in the existing model details only.
+ if (rep.displayPricing && rep.currency) return null;
const display = rowPriceDisplay(row);
if (!display) return null;
if (display.kind === 'free') {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 83d4bde1c1..f0cfdd9a13 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9696,6 +9696,20 @@
"addRemoteProject": "Add remote project"
},
"modelSelector": {
+ "displayPricing": {
+ "estimated": "About {{price}}",
+ "startingAt": "From {{price}}",
+ "units": {
+ "token": "tokens",
+ "character": "characters",
+ "image": "image",
+ "second": "second",
+ "minute": "minute",
+ "request": "request",
+ "megapixel": "MP",
+ "megapixelSecond": "MP·s"
+ }
+ },
"budgetNeedsApiKey": "This model needs an API key — configure it in Settings",
"paymentRequired": {
"badge": "Paid",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 56c9322e4d..4a0ad9ad0a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9658,6 +9658,20 @@
"addRemoteProject": "リモートプロジェクトを追加"
},
"modelSelector": {
+ "displayPricing": {
+ "estimated": "約 {{price}}",
+ "startingAt": "{{price}} から",
+ "units": {
+ "token": "トークン",
+ "character": "文字",
+ "image": "枚",
+ "second": "秒",
+ "minute": "分",
+ "request": "リクエスト",
+ "megapixel": "メガピクセル",
+ "megapixelSecond": "メガピクセル·秒"
+ }
+ },
"budgetNeedsApiKey": "このモデルは設定で API key を構成してから使用できます",
"paymentRequired": {
"badge": "有料",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 6a4a572695..8ef09ee546 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9658,6 +9658,20 @@
"addRemoteProject": "원격 프로젝트 추가"
},
"modelSelector": {
+ "displayPricing": {
+ "estimated": "약 {{price}}",
+ "startingAt": "{{price}}부터",
+ "units": {
+ "token": "토큰",
+ "character": "문자",
+ "image": "장",
+ "second": "초",
+ "minute": "분",
+ "request": "요청",
+ "megapixel": "메가픽셀",
+ "megapixelSecond": "메가픽셀·초"
+ }
+ },
"budgetNeedsApiKey": "이 모델은 설정에서 API key를 구성해야 사용할 수 있습니다",
"paymentRequired": {
"badge": "유료",
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 6cb0d3c049..c8f711fef4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9658,6 +9658,20 @@
"addRemoteProject": "添加远程项目"
},
"modelSelector": {
+ "displayPricing": {
+ "estimated": "约 {{price}}",
+ "startingAt": "{{price}} 起",
+ "units": {
+ "token": "token",
+ "character": "字符",
+ "image": "张",
+ "second": "秒",
+ "minute": "分钟",
+ "request": "次",
+ "megapixel": "百万像素",
+ "megapixelSecond": "百万像素·秒"
+ }
+ },
"budgetNeedsApiKey": "此模型需先在设置里配置 API key 才能使用",
"paymentRequired": {
"badge": "付费",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index b531e7a8b8..ae9032496d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9658,6 +9658,20 @@
"addRemoteProject": "新增遠端專案"
},
"modelSelector": {
+ "displayPricing": {
+ "estimated": "約 {{price}}",
+ "startingAt": "{{price}} 起",
+ "units": {
+ "token": "token",
+ "character": "字元",
+ "image": "張",
+ "second": "秒",
+ "minute": "分鐘",
+ "request": "次",
+ "megapixel": "百萬像素",
+ "megapixelSecond": "百萬像素·秒"
+ }
+ },
"budgetNeedsApiKey": "此模型需先在設定裡配置 API key 才能使用",
"paymentRequired": {
"badge": "付費",
diff --git a/apps/desktop/src/renderer/lib/__tests__/displayPricingFormat.test.ts b/apps/desktop/src/renderer/lib/__tests__/displayPricingFormat.test.ts
new file mode 100644
index 0000000000..d32e84ed1b
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/displayPricingFormat.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { displayPricingAmount } from '../displayPricingFormat';
+const row = { label: 'Output', price: 0.5, unit: 'second', quantity: 1 };
+describe('display pricing amounts', () => {
+ it('applies the provider discount once while retaining the quoted basis', () => {
+ const result = displayPricingAmount(row, 'USD', 0.2, 'en');
+ expect(result.current).toContain('0.4');
+ expect(result.original).toContain('0.5');
+ expect(result.current).toBe('$0.4');
+ expect(result.original).toBe('$0.5');
+ expect(row.price).toBe(0.5);
+ });
+ it('uses the existing yuan symbol without a currency code', () => {
+ expect(displayPricingAmount(row, 'CNY', 0, 'zh-CN').current).toBe('¥0.5');
+ });
+ it('retains small nonzero amounts', () => {
+ const result = displayPricingAmount({ ...row, price: 0.000000001 }, 'CNY', 0, 'en');
+ expect(result.current).toBe('¥0.000000001');
+ expect(result.free).toBe(false);
+ expect(result.original).toBeUndefined();
+ });
+ it('keeps zero valid and distinguishes fully discounted prices', () => {
+ expect(displayPricingAmount({ ...row, price: 0 }, 'USD', undefined, 'en').free).toBe(true);
+ expect(displayPricingAmount(row, 'USD', 1, 'en')).toMatchObject({ free: true });
+ expect(displayPricingAmount(row, 'USD', 1, 'en').original).toContain('0.5');
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/displayPricingFormat.ts b/apps/desktop/src/renderer/lib/displayPricingFormat.ts
new file mode 100644
index 0000000000..9d19dcb950
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/displayPricingFormat.ts
@@ -0,0 +1,30 @@
+import type { ModelDisplayPricing } from '@cindy/model-providers';
+
+/** Keep the quoted basis; do not convert mixed units or infer a model-wide starting price. */
+export function displayPricingAmount(
+ item: ModelDisplayPricing['items'][number],
+ currency: 'CNY' | 'USD',
+ costDiscount: number | undefined,
+ locale: string,
+): { current: string; original?: string; free: boolean } {
+ const discount =
+ typeof costDiscount === 'number' &&
+ Number.isFinite(costDiscount) &&
+ costDiscount >= 0 &&
+ costDiscount <= 1
+ ? costDiscount
+ : 0;
+ const amount = item.price * (1 - discount);
+ const number = new Intl.NumberFormat(locale, {
+ maximumSignificantDigits: 8,
+ useGrouping: false,
+ });
+ // Match existing model prices while preserving small per-unit amounts.
+ const symbol = currency === 'CNY' ? '¥' : '$';
+ const money = (value: number) => `${symbol}${number.format(value)}`;
+ return {
+ current: money(amount),
+ ...(discount > 0 && item.price > 0 ? { original: money(item.price) } : {}),
+ free: item.price === 0 || discount === 1,
+ };
+}
diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.ts
index 883de37856..4aeede085e 100644
--- a/apps/desktop/src/shared/modelAccess.ts
+++ b/apps/desktop/src/shared/modelAccess.ts
@@ -1,3 +1,4 @@
+import type { ModelDisplayPricing } from '@cindy/model-providers';
/**
* modelAccess.ts — 网关凭据自动下发(model-access-server)的 main / renderer 共享类型。
*
@@ -173,6 +174,7 @@ export interface ModelGroupPricing {
* currently mirrors maxInputTokens),统一由 contextWindow 表达。
*/
export interface ModelAccessGatewayModel extends ModelGroupPricing {
+ displayPricing?: ModelDisplayPricing;
id: string;
/** v5 entitlement projection; missing only on persisted/legacy snapshots. */
availability?: 'available' | 'requires_payment';
diff --git a/docs/dev-rules/model-catalog-maintenance.md b/docs/dev-rules/model-catalog-maintenance.md
index 0a233f533d..9a94c03625 100644
--- a/docs/dev-rules/model-catalog-maintenance.md
+++ b/docs/dev-rules/model-catalog-maintenance.md
@@ -57,6 +57,19 @@ Catalog (version)
Pi 走 `providers[].models.pi`(用户补丁 perAgent.pi 另属合法 schema)。媒体 route 使用 `agents: []`。
`contextWindowMax` 是客户端容量投影,不能填进 Registry;容量与工作预算见 [运行时细则](model-catalog-runtime.md)。
+### Gateway 复杂价目展示
+
+Model Access V5 通过 `X-Cindy-Model-Capabilities: display_pricing` 协商可选 `displayPricing`。
+聊天和媒体目录都保留该字段与同一连接快照的 `currency`、`costDiscount`;不进入公共
+Registry/defaults、ModelPriceQuote 或 token 成本估算,不跨供应商补价。
+成功刷新缺字段或价目不可解析时清除旧价目,模型仍正常更新;新增属性忽略,未知单位保留。
+展示字段变化不构成整份目录失败;网络或核心模型协议失败仍沿用既有目录恢复语义。
+
+Desktop 模型详情优先展示结构化价目,缺字段沿用原有价格。`price` 为每 `quantity` 个
+`unit` 的折扣前报价,只在展示时应用一次折扣,保留币种与“约/起价”语义;label、tier、
+notes 仅按纯文本呈现,未知单位不猜换算。列表不新增价格入口,统一从既有模型详情查看,也不从混合单位挑最低价。
+共享目录可传递这些可选展示字段,旧端缺字段仍合法;首期 UI 仅覆盖 Desktop 现有详情入口。
+
### 覆盖顺序
这里是**模型资料字段**的优先级,右边覆盖左边;成员、权限、实际计费、显示开关不套用此链:
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index a6670a7482..fc964da070 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -11,6 +11,17 @@
> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。
+## Model Access 复杂价目
+
+保持 V5,新增可组合的 `display_pricing` 能力声明,复用 `X-Cindy-Model-Capabilities` 与
+`Vary`。服务端只向声明支持的 V5 下发 `displayPricing`,旧 V5 和 V1–V4 不新增字段;
+新客户端接受旧服务端的无字段响应。缺失、null、空价目或无法理解的价目结构仅省略展示块,
+不拒绝模型或整份目录;新增对象属性忽略,未知单位原样保留,未知 priceType 不猜成 exact。
+模型必需字段及其它协议校验保持原规则。
+Gateway 边界对整块报价校验,非法或无有效币种即整体省略,保留模型。币种和折扣随同次
+模型快照投影,成功刷新缺字段会移除旧展示;没有新权限、数据库迁移或独立价格缓存。
+两端可独立升级,完整展示需两端支持。字段只用于报价展示,不参与账单或调用授权。
+
## 实时生成速度
既有 maker status 可选携带 `tokenSpeed`(`rate`、`average`、`tokens`、`elapsedMs`、
diff --git a/packages/model-providers/src/__tests__/modelAccessValidator.test.ts b/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
index 998f9d8d11..773f64cbf7 100644
--- a/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
+++ b/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
@@ -1168,3 +1168,50 @@ describe("public model registry contract", () => {
}
});
});
+
+
+describe('V5 display pricing extension', () => {
+ const displayPricing = { items: [{ label: 'Generated video', tier: 'HD', price: 0.5, unit: 'second', quantity: 1, priceType: 'estimated' as const }], notes: ['Billed by output duration.'] };
+ it('accepts display-only media without inventing token prices', () => {
+ const value = { schemaVersion: 5, accountTier: 'paid', models: [{
+ id: 'example-video', name: 'Example Video', mode: 'video_generation', agents: [],
+ availability: 'available', currency: 'USD', displayPricing,
+ }] };
+ expect(parseListModelsResponse(value)).toEqual({ ok: true, value });
+ });
+ it.each([
+ undefined,
+ null,
+ {},
+ { items: [] },
+ { items: [{ ...displayPricing.items[0], priceType: 'future_type' }] },
+ { items: [{ ...displayPricing.items[0], price: '0.5' }] },
+ { ...displayPricing, notes: { text: 'Future notes shape' } },
+ ])('omits absent or unsupported presentation data without rejecting models: %j', (quote) => {
+ const model = VALID_V5_RESPONSE.models[0];
+ const other = { ...model, id: 'another-model', displayPricing };
+ const result = parseListModelsResponse({
+ ...VALID_V5_RESPONSE,
+ models: [{ ...model, displayPricing: quote }, other],
+ });
+ expect(result).toEqual({
+ ok: true,
+ value: { ...VALID_V5_RESPONSE, models: [model, other] },
+ });
+ });
+ it('ignores added fields within quotes and preserves unfamiliar units', () => {
+ const row = { ...displayPricing.items[0], unit: 'future_unit' };
+ const model = VALID_V5_RESPONSE.models[0];
+ expect(parseListModelsResponse({
+ ...VALID_V5_RESPONSE,
+ models: [{ ...model, displayPricing: { items: [{ ...row, future: true }], extra: {} } }],
+ })).toEqual({
+ ok: true,
+ value: { ...VALID_V5_RESPONSE, models: [{ ...model, displayPricing: { items: [row] } }] },
+ });
+ });
+ it('still validates supplied model currency and preserves strict legacy shapes', () => {
+ expect(parseListModelsResponse({ ...VALID_V5_RESPONSE, models: [{ ...VALID_V5_RESPONSE.models[0], displayPricing, currency: 'INVALID' }] }).ok).toBe(false);
+ expect(parseListModelsResponse({ ...VALID_V4_RESPONSE, models: [{ ...VALID_V4_RESPONSE.models[0], displayPricing }] }).ok).toBe(false);
+ });
+});
diff --git a/packages/model-providers/src/__tests__/modelDisplayPricing.test.ts b/packages/model-providers/src/__tests__/modelDisplayPricing.test.ts
new file mode 100644
index 0000000000..2730ce1add
--- /dev/null
+++ b/packages/model-providers/src/__tests__/modelDisplayPricing.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+import { parseModelDisplayPricing } from "../modelDisplayPricing.js";
+const table = {
+ items: [
+ {
+ label: "Generated video",
+ tier: "HD",
+ price: 0.5,
+ unit: "second",
+ quantity: 1,
+ priceType: "estimated" as const,
+ },
+ ],
+ notes: ["Billed by output duration."],
+};
+
+describe("display pricing contract", () => {
+ it("preserves mixed units, zero prices, conditions and item order", () => {
+ const value = {
+ ...table,
+ items: [
+ ...table.items,
+ { label: "Input", price: 0, unit: "image", quantity: 5 },
+ ],
+ };
+ expect(parseModelDisplayPricing(value)).toEqual(value);
+ });
+ it.each([
+ { price: -1 },
+ { price: Infinity },
+ { price: NaN },
+ { price: "0.5" },
+ { quantity: 0 },
+ { quantity: -1 },
+ { quantity: Infinity },
+ { priceType: "future" },
+ { unit: "" },
+ { label: " " },
+ { tier: 8 },
+ ])("rejects the whole table if any charge is invalid: %j", (patch) => {
+ expect(
+ parseModelDisplayPricing({
+ ...table,
+ items: [table.items[0], { ...table.items[0], ...patch }],
+ }),
+ ).toBeUndefined();
+ });
+ it("rejects invalid notes and oversized tables instead of dropping billing conditions", () => {
+ expect(parseModelDisplayPricing({ ...table, notes: [5] })).toBeUndefined();
+ expect(parseModelDisplayPricing({ items: [] })).toBeUndefined();
+ expect(
+ parseModelDisplayPricing({ items: Array(129).fill(table.items[0]) }),
+ ).toBeUndefined();
+ });
+ it("copies only display fields, preserves unknown unit text and does not infer a price type", () => {
+ const row = {
+ label: "Usage",
+ price: 0.01,
+ unit: "future_unit",
+ quantity: 2.5,
+ };
+ expect(
+ parseModelDisplayPricing({
+ internal: "secret",
+ items: [{ ...row, internal: "secret" }],
+ }),
+ ).toEqual({ items: [row] });
+ });
+});
diff --git a/packages/model-providers/src/__tests__/unifiedSelection.test.ts b/packages/model-providers/src/__tests__/unifiedSelection.test.ts
index 8fde11b780..a78988aabd 100644
--- a/packages/model-providers/src/__tests__/unifiedSelection.test.ts
+++ b/packages/model-providers/src/__tests__/unifiedSelection.test.ts
@@ -1289,3 +1289,16 @@ describe('sortEntriesForAgent(原生底座优先,无主场不降级)', () => {
expect(codexOnly.every((e) => e.candidates.includes('codex'))).toBe(true);
});
});
+
+
+it('keeps display pricing attached to the selected provider and engine', () => {
+ const quote = { items: [{ label: 'Usage', price: 0.5, unit: 'second', quantity: 1 }] };
+ const providers = [
+ view({ id: 'xd', models: { codex: [m('same-model', { displayPricing: quote, currency: 'CNY', costDiscount: 0.2 })] } }),
+ view({ id: 'openai', models: { codex: [m('same-model')] } }),
+ ];
+ expect(resolveAgentCapability(providers, 'xd', 'same-model', 'codex')).toMatchObject({
+ displayPricing: quote, currency: 'CNY', costDiscount: 0.2,
+ });
+ expect(resolveAgentCapability(providers, 'openai', 'same-model', 'codex')).not.toHaveProperty('displayPricing');
+});
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index 79177f79bc..ef7985cea3 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -1,3 +1,4 @@
+export { parseModelDisplayPricing, type ModelDisplayPricing } from './modelDisplayPricing.js';
/**
* @cindy/model-providers — 模型供应商目录 + 路由抽象(纯逻辑,零 Electron / maker-core 运行时依赖)。
*
diff --git a/packages/model-providers/src/modelAccessBean.ts b/packages/model-providers/src/modelAccessBean.ts
index bb6bb0759a..4f7966521f 100644
--- a/packages/model-providers/src/modelAccessBean.ts
+++ b/packages/model-providers/src/modelAccessBean.ts
@@ -1,3 +1,4 @@
+import type { ModelDisplayPricing } from './modelDisplayPricing.js';
import type { BaseModel, ModelMetadata } from "./modelMetadataLayers.js";
import type { LocalModelCatalog } from "./localModelCatalog.js";
/**
@@ -273,6 +274,7 @@ interface ModelCatalogAgentOverride extends Omit<
}
interface ModelCatalogEntryBase extends ModelPricing {
+ displayPricing?: ModelDisplayPricing;
id: string;
mode?: string;
/** Optional for compatibility with older Model Access responses. */
diff --git a/packages/model-providers/src/modelAccessValidator.ts b/packages/model-providers/src/modelAccessValidator.ts
index 8ca740393c..8f1a084623 100644
--- a/packages/model-providers/src/modelAccessValidator.ts
+++ b/packages/model-providers/src/modelAccessValidator.ts
@@ -1,3 +1,4 @@
+import { parseModelDisplayPricing } from './modelDisplayPricing.js';
import {
validModelMetadata,
expandedRegistryEntries,
@@ -838,7 +839,10 @@ export function parseListModelsResponse(
`response.models[${index}].availability must be available or requires_payment`,
);
}
- const { availability, ...legacyShape } = raw;
+ const { availability, displayPricing: rawDisplayPricing, ...legacyShape } = raw;
+ // Optional presentation data evolves independently of model availability.
+ // An unsupported quote must not reject the catalog or retain an older quote.
+ const displayPricing = parseModelDisplayPricing(rawDisplayPricing);
const sanitized = sanitizeModelEntryAgents(
legacyShape,
MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
@@ -855,7 +859,7 @@ export function parseListModelsResponse(
MODEL_ACCESS_CATALOG_SCHEMA_VERSION,
);
if (error) return fail(error);
- models.push({ ...(sanitized as PlainObject), availability });
+ models.push({ ...(sanitized as PlainObject), availability, ...(displayPricing ? { displayPricing } : {}) });
}
return ok({
schemaVersion: MODEL_ACCESS_CATALOG_V5_SCHEMA_VERSION,
diff --git a/packages/model-providers/src/modelDisplayPricing.ts b/packages/model-providers/src/modelDisplayPricing.ts
new file mode 100644
index 0000000000..660fc6a7e4
--- /dev/null
+++ b/packages/model-providers/src/modelDisplayPricing.ts
@@ -0,0 +1,70 @@
+/** Provider presentation only; never used to calculate usage or authorize a model. */
+export interface ModelDisplayPricing {
+ items: Array<{
+ label: string;
+ tier?: string;
+ price: number;
+ unit: string;
+ quantity: number;
+ priceType?: "exact" | "estimated" | "starting_at";
+ }>;
+ notes?: string[];
+}
+
+/** The whole table is atomic: never silently drop a charge or billing condition. */
+export function parseModelDisplayPricing(
+ value: unknown,
+): ModelDisplayPricing | undefined {
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ return undefined;
+ const raw = value as Record<string, unknown>;
+ if (
+ !Array.isArray(raw.items) ||
+ raw.items.length === 0 ||
+ raw.items.length > 128
+ )
+ return undefined;
+ const text = (v: unknown, max: number): v is string =>
+ typeof v === "string" && v.trim().length > 0 && v.length <= max;
+ if (
+ raw.notes !== undefined &&
+ (!Array.isArray(raw.notes) ||
+ raw.notes.length > 32 ||
+ raw.notes.some((note) => !text(note, 2048)))
+ )
+ return undefined;
+ const items: ModelDisplayPricing["items"] = [];
+ for (const item of raw.items) {
+ if (!item || typeof item !== "object" || Array.isArray(item))
+ return undefined;
+ const row = item as Record<string, unknown>;
+ if (
+ !text(row.label, 256) ||
+ !text(row.unit, 128) ||
+ (row.tier !== undefined && !text(row.tier, 256)) ||
+ typeof row.price !== "number" ||
+ !Number.isFinite(row.price) ||
+ row.price < 0 ||
+ typeof row.quantity !== "number" ||
+ !Number.isFinite(row.quantity) ||
+ row.quantity <= 0 ||
+ (row.priceType !== undefined &&
+ row.priceType !== "exact" &&
+ row.priceType !== "estimated" &&
+ row.priceType !== "starting_at")
+ )
+ return undefined;
+ items.push({
+ label: row.label,
+ price: row.price,
+ unit: row.unit,
+ quantity: row.quantity,
+ ...(row.tier !== undefined ? { tier: row.tier } : {}),
+ ...(row.priceType !== undefined ? { priceType: row.priceType } : {}),
+ });
+ }
+ return {
+ items,
+ ...(raw.notes !== undefined ? { notes: [...(raw.notes as string[])] } : {}),
+ };
+}
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 731c0d7add..d17a22aac8 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -1,3 +1,4 @@
+import type { ModelDisplayPricing } from './modelDisplayPricing.js';
import type { ModelMetadata } from "./modelMetadataLayers.js";
/**
* @cindy/model-providers — 类型定义。
@@ -305,6 +306,11 @@ export interface ModelCost {
* 跨 provider(如 gpt-5.5 同时由 openai 与 xd 提供)则必须元数据一致(见 catalog.ts 校验)。
*/
export interface CatalogModel {
+ /** Same-provider display-only pricing; never inherited through public model metadata. */
+ displayPricing?: ModelDisplayPricing;
+ currency?: 'USD' | 'CNY';
+ costDiscount?: number;
+
supportsToolCalls?: boolean;
reasoningRequired?: boolean;
userModelConfig?: ProviderRuntimeModelConfig;
@@ -513,6 +519,10 @@ export interface ProviderMediaModel extends Pick<
discoveredMetadata?: ModelMetadata;
/** Local projection provenance; not part of the public Registry metadata. */
sourceAgent?: AgentKind;
+ /** Same-provider display-only pricing; never inherited through public model metadata. */
+ displayPricing?: ModelDisplayPricing;
+ currency?: 'USD' | 'CNY';
+ costDiscount?: number;
id: string;
name: string;
availability?: "available" | "requires_payment";
diff --git a/packages/model-providers/src/unifiedSelection.ts b/packages/model-providers/src/unifiedSelection.ts
index c0f309ce2a..24cc0829e6 100644
--- a/packages/model-providers/src/unifiedSelection.ts
+++ b/packages/model-providers/src/unifiedSelection.ts
@@ -426,7 +426,7 @@ export function recommendedAgentForModel(
}
/** 某 (provider, model, agent) 已解析的能力(规格 §2.2)。 */
-export interface UnifiedAgentCapability {
+export interface UnifiedAgentCapability extends Pick<CatalogModel, 'displayPricing' | 'currency' | 'costDiscount'> {
agent: AgentKind;
/**
* ★该引擎下真正要发出去的 model id(bridge 壳已还原)。写 draft / 建会话 / 切模型
@@ -494,6 +494,9 @@ function capabilityOf(
return {
agent,
wireModelId: model.id,
+ ...(model.displayPricing && model.currency ? {
+ displayPricing: model.displayPricing, currency: model.currency, costDiscount: model.costDiscount,
+ } : {}),
protocolMode: protocol?.mode ?? 'unknown',
nativeApi: comparison.reference,
outboundApi: protocol?.outbound ?? null,