Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(models): show multi-unit display pricing summaries
fmfsaisai966e665f0992
diff --git a/apps/desktop/scripts/fixtures/display-pricing/display-pricing-fixture.tsx b/apps/desktop/scripts/fixtures/display-pricing/display-pricing-fixture.tsxnew file mode 100644index 0000000000..0355e171f7--- /dev/null+++ b/apps/desktop/scripts/fixtures/display-pricing/display-pricing-fixture.tsx@@ -0,0 +1,143 @@+import { mountPage, subscription } from '../../ui-page/harness';+import { ModelAdvancedDrawer } from '../../../src/renderer/components/settings/ModelAdvancedDrawer';+import {+ buildUnionRows,+ UnifiedModelList,+} from '../../../src/renderer/components/settings/UnifiedModelList';+import {+ BUNDLED_CATALOG,+ type ProviderView,+ type ModelDisplayPricing,+} from '@cindy/model-providers';++const speech: ModelDisplayPricing = {+ items: [{ label: 'Text input', price: 140, unit: 'character', quantity: 1000000 }],+ summary: { input: [{ price: 140, unit: 'character', quantity: 1000000 }] },+};+const image: ModelDisplayPricing = {+ items: [+ { label: 'Input image', price: 0.02, unit: 'image', quantity: 1 },+ { label: 'Output image', price: 0.3, unit: 'image', quantity: 1 },+ ],+ summary: {+ input: [{ price: 0.02, unit: 'image', quantity: 1 }],+ output: [{ price: 0.3, unit: 'image', quantity: 1 }],+ },+};+const video: ModelDisplayPricing = {+ items: [+ { label: 'Video generation', price: 6, tier: '480P', unit: 'token', quantity: 1000000 },+ { label: 'Video generation', price: 10, tier: '720P', unit: 'token', quantity: 1000000 },+ ],+ notes: ['Billed by generated resolution.'],+ summary: {+ output: [+ {+ price: 6,+ maxPrice: 10,+ tier: '480P/720P',+ unit: 'token',+ quantity: 1000000,+ priceType: 'starting_at',+ },+ ],+ },+};+const mixed: ModelDisplayPricing = {+ ...video,+ summary: {+ input: [+ { price: 140, unit: 'character', quantity: 1000000 },+ { price: 0.02, unit: 'image', quantity: 1, tier: 'HD', priceType: 'estimated' },+ ],+ output: video.summary!.output,+ cacheRead: [{ price: 0.5, unit: 'request', quantity: 1234.5 }],+ cacheWrite: [{ price: 1, unit: 'second', quantity: 1 }],+ },+};++void mountPage({+ host: {+ maker: {+ getModelContextLimit: async () => ({ limit: null, isCustomized: false }),+ onProvidersChanged: subscription('providersChanged'),+ getModelPricing: async () => null,+ syncModelVisibility: async () => undefined,+ claimLegacyModelVisibilityOwner: async () => ({+ dataOwnerId: 'pricing-fixture',+ ownerGeneration: 1,+ canWriteOwnerScoped: true,+ canInitialize: true,+ }),+ },+ },+ render: (ctx) => {+ const quote =+ (+ { speech, image, video, mixed, legacy: { items: speech.items } } as Record<+ string,+ ModelDisplayPricing+ >+ )[ctx.case] ?? mixed;+ const provider: ProviderView = {+ ...BUNDLED_CATALOG.providers.find((p) => p.id === 'xd')!,+ connected: true,+ availableMediaModelIds: ['speech', 'image', 'video'],+ models: {},+ agents: [],+ embeddingModels: [],+ audioModels: [+ {+ id: 'speech',+ name: 'Qwen Speech',+ mode: 'audio_speech',+ currency: 'CNY',+ costDiscount: 0.2,+ displayPricing: ctx.case === 'legacy' ? quote : speech,+ modalities: { input: ['text'], output: ['audio'] },+ },+ ],+ imageModels: [+ {+ id: 'image',+ name: 'Seedream',+ mode: 'image_generation',+ currency: 'USD',+ costDiscount: 0.2,+ displayPricing: image,+ modalities: { input: ['text', 'image'], output: ['image'] },+ },+ ],+ videoModels: [+ {+ id: 'video',+ name: 'Video',+ mode: 'video_generation',+ currency: 'CNY',+ costDiscount: 0.2,+ displayPricing: ctx.case === 'list' ? video : quote,+ modalities: { input: ['text'], output: ['video'] },+ },+ ],+ };+ if (ctx.case === 'list')+ return (+ <main className="p-5">+ <UnifiedModelList provider={provider} />+ </main>+ );+ const rowId = ['speech', 'legacy'].includes(ctx.case) ? 'speech' : ctx.case === 'image' ? 'image' : 'video';+ return (+ <ModelAdvancedDrawer+ provider={provider}+ row={buildUnionRows(provider).find((row) => row.id === rowId)!}+ open+ onOpenChange={() => {}}+ pricePresentationOf={() => null}+ onDisable={() => {}}+ disabled={false}+ paymentRequired={false}+ />+ );+ },+});diff --git a/apps/desktop/scripts/fixtures/display-pricing/ui-page.mjs b/apps/desktop/scripts/fixtures/display-pricing/ui-page.mjsnew file mode 100644index 0000000000..cdb47f6f91--- /dev/null+++ b/apps/desktop/scripts/fixtures/display-pricing/ui-page.mjs@@ -0,0 +1,42 @@+export default {+ name: 'display-pricing',+ entry: './display-pricing-fixture.tsx',+ viewport: { width: 800, height: 800 },+ real: 'ModelAdvancedDrawer, UnifiedModelList, DisplayPricingDetails, localized roles, quantities, ranges and discounts',+ notCovered:+ 'Live Gateway responses, account permissions and actual billing; prices are fixture inputs',+ cases: {+ speech: { about: 'Character input per million' },+ image: { about: 'Input and output per image' },+ video: { about: 'Resolution tier with discounted range and starting price' },+ default: { about: 'Multiple units, all four roles and supplementary conditions' },+ legacy: { about: 'Existing table without summary' },+ list: {+ about: 'Media list selects output first, then input',+ viewport: { width: 800, height: 600 },+ },+ },+ async check(page, ui) {+ if (ui.case === 'list') {+ const groups = page.locator('button[aria-expanded="false"]:not([aria-haspopup])');+ while (await groups.count()) await groups.first().click();+ await page.getByText('¥112', { exact: false }).waitFor();+ if (!(await page.locator('body').textContent()).includes('¥4.8–¥8'))+ throw Error('Missing discounted video summary');+ } else {+ const pricing = page.getByText(await ui.t('settings.providers.models.advanced.pricing'), {+ exact: true,+ });+ await pricing.scrollIntoViewIfNeeded();+ if (ui.case !== 'legacy') {+ const role = ['video'].includes(ui.case) ? 'output' : 'input';+ await page+ .getByText(await ui.t(`settings.providers.models.advanced.price.${role}`), {+ exact: true,+ })+ .waitFor();+ }+ }+ await ui.capture('pricing');+ },+};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.tsindex c04aadf57c..6f1962f375 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@@ -587,7 +587,7 @@ 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 displayPricing = { items: [{ label: 'Generated video', tier: 'HD', price: 0.5, unit: 'second', quantity: 1, priceType: 'estimated' as const }], notes: ['Billed by output duration.'], summary: { output: [{ price: 6, maxPrice: 10, unit: 'token', quantity: 1000000, tier: '480P/720P' }] } };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'] } };@@ -600,4 +600,9 @@ it('keeps complex quotes with their provider snapshot and clears them on successexpect(provider().videoModels?.[0]).not.toHaveProperty('displayPricing');setXdGatewayModels([], { authoritative: true });expect(provider().videoModels).toEqual([]);+ // Unit/integration contract: gatewayDisplayPricing must also retain summaries on the chat projection.+ // Previously only the media table was covered; one chat summary is the minimum dropped-field input.+ setXdGatewayModels([{ ...video, id: 'chat', mode: 'chat', agents: ['codex'], contextWindow: 100000,+ perAgent: { codex: { wireProtocol: 'openai-responses' } } }], { authoritative: true });+ expect(provider().models.codex?.find(m => m.id === 'chat')).toMatchObject({ displayPricing, currency: 'USD', costDiscount: 0.2 });});diff --git a/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts b/apps/desktop/src/main/model-access/__tests__/mediaModels.test.tsindex eee79af784..c54d858ca3 100644--- a/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts+++ b/apps/desktop/src/main/model-access/__tests__/mediaModels.test.ts@@ -97,6 +97,15 @@ describe('listAvailableMediaModels', () => {isCatalogMediaModelVisibleMock.mockReset().mockReturnValue(true);});+ // Unit contract: listAvailableMediaModels preserves the parsed summary and provider discount.+ // Existing fixtures had no pricing; minimal regression is a Gateway image with one summary.output quote.+ it('preserves the optional summary through media parsing and provider projection', async () => {+ const displayPricing = { items: [{ label: 'Output', price: 0.3, unit: 'image', quantity: 1 }],+ summary: { input: [{ price: 0.02, unit: 'image', quantity: 1 }], output: [{ price: 0.3, unit: 'image', quantity: 1 }] } };+ serverApiFetchMock.mockResolvedValue({ ...payload, models: [{ ...payload.models[0], displayPricing, costDiscount: 0.2 }] });+ await expect(listAvailableMediaModels()).resolves.toMatchObject([{ displayPricing, costDiscount: 0.2, currency: 'CNY', providerId: 'xd' }]);+ });+it('不带操作筛选时按 Gateway mode 返回图片/视频模型', async () => {await expect(listAvailableMediaModels()).resolves.toMatchObject([{ id: 'image-without-guide' },diff --git a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.tsindex 8acf4b38e2..814365c2a3 100644--- a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts+++ b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts@@ -34,9 +34,14 @@ describe('parseModelsSyncPayload', () => {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 }] };+ // Unit contract: refresh must preserve an optional summary, not only the existing table.+ const quote = { items: [{ label: 'Output', price: 0.5, unit: 'second', quantity: 1 }], summary: {+ output: [{ price: 6, maxPrice: 10, unit: 'token', quantity: 1000000, tier: '480P/720P' }],+ } };const response = { schemaVersion: 5, accountTier: 'paid', models: [{ ...model, displayPricing: quote }] };expect(parseModelsSyncPayload(response)).toMatchObject({ ok: true, models: [{ displayPricing: quote }] });+ expect(parseModelsSyncPayload({ ...response, models: [{ ...model, displayPricing: { ...quote, summary: { output: [] } } }] }))+ .toMatchObject({ ok: true, models: [{ displayPricing: { items: quote.items } }] });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] });diff --git a/apps/desktop/src/renderer/__tests__/modelManagementActions.test.tsx b/apps/desktop/src/renderer/__tests__/modelManagementActions.test.tsxindex c24c10571c..563e966659 100644--- a/apps/desktop/src/renderer/__tests__/modelManagementActions.test.tsx+++ b/apps/desktop/src/renderer/__tests__/modelManagementActions.test.tsx@@ -13,7 +13,7 @@ import {const writeFailure = vi.hoisted(() => vi.fn());vi.mock('@/lib/toast', () => ({ toast: { error: writeFailure } }));-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, values?: { price?: string }) => values?.price ? `${key} ${values.price}` : key, i18n: { resolvedLanguage: 'en' } }) }));vi.mock('../components/ui/confirm-dialog-provider', () => ({useConfirmDialog: () => ({ confirm: vi.fn() }),}));@@ -141,3 +141,26 @@ it('waits for the shared lock and reports asynchronous write failures', async ()expect(enabled('pi')).toBe(true);} finally { vi.unstubAllGlobals(); }});++// Unit regression: real list rows previously hid all displayPricing. Summary chooses output, then input;+// cache-only or absent summaries retain the previous behavior. Existing tests only covered visibility actions.+it.each(['output', 'input', 'cacheRead', 'absent'] as const)('shows the first eligible %s summary quote in a media row', role => {+ const quote = { price: 6, maxPrice: 10, unit: 'token', quantity: 1000000, tier: '480P/720P', priceType: 'starting_at' as const };+ const summary = role === 'absent' ? undefined : {+ [role]: [quote, { ...quote, price: 15, maxPrice: 20, unit: 'second' }],+ ...(role === 'output' ? { input: [{ price: 140, unit: 'character', quantity: 1000000 }] } : {}),+ };+ render(<UnifiedModelList provider={{ ...provider, models: {}, videoModels: [{+ id: 'video', name: 'Video', mode: 'video_generation', currency: 'CNY', costDiscount: 0.2,+ modalities: { input: ['text'], output: ['video'] },+ displayPricing: { items: [{ ...quote, label: 'Supplier quote' }], summary },+ }] }} />);+ if (role === 'cacheRead' || role === 'absent') {+ expect(screen.queryByText(/¥/)).toBeNull();+ } else {+ expect(screen.getByText(/480P\/720P/).textContent).toContain('¥4.8–¥8');+ expect(screen.getByText('¥6–¥10').tagName).toBe('S');+ expect(screen.queryByText(/¥112|¥12/)).toBeNull();+ expect(screen.getByText(/480P\/720P/).textContent).toContain('newChat.modelSelector.displayPricing.startingAt');+ }+});diff --git a/apps/desktop/src/renderer/components/DisplayPricingDetails.tsx b/apps/desktop/src/renderer/components/DisplayPricingDetails.tsxindex 2720805cef..99a458b7a9 100644--- a/apps/desktop/src/renderer/components/DisplayPricingDetails.tsx+++ b/apps/desktop/src/renderer/components/DisplayPricingDetails.tsx@@ -1,6 +1,6 @@import { useTranslation } from 'react-i18next';-import type { CatalogModel, ModelDisplayPricing } from '@cindy/model-providers';-import { displayPricingAmount } from '@/lib/displayPricingFormat';+import type { CatalogModel, ModelDisplayPricing, SummaryQuote } from '@cindy/model-providers';+import { displayPricingAmount, displayPricingQuantity } from '@/lib/displayPricingFormat';type PricingModel = Pick<CatalogModel, 'displayPricing' | 'currency' | 'costDiscount'>;const UNIT_KEYS = {@@ -14,11 +14,50 @@ const UNIT_KEYS = {megapixel_second: 'newChat.modelSelector.displayPricing.units.megapixelSecond',} as const;+/** Shared amount and denominator for both detailed items and primary summary quotes. */+export function DisplayPricingQuote({+ quote,+ currency,+ costDiscount,+}: {+ quote: SummaryQuote;+ currency: 'CNY' | 'USD';+ costDiscount?: number;+}) {+ const { t, i18n } = useTranslation();+ const locale = i18n.resolvedLanguage ?? i18n.language;+ const amount = displayPricingAmount(quote, currency, costDiscount, locale);+ const unit = Object.hasOwn(UNIT_KEYS, quote.unit)+ ? t(UNIT_KEYS[quote.unit as keyof typeof UNIT_KEYS])+ : quote.unit;+ const quantity = displayPricingQuantity(+ quote.quantity,+ locale,+ t('newChat.modelSelector.displayPricing.million'),+ );+ const price = amount.free ? t('newChat.modelSelector.displayPricing.free') : amount.current;+ const qualifiedPrice =+ quote.priceType === 'estimated'+ ? t('newChat.modelSelector.displayPricing.estimated', { price })+ : quote.priceType === 'starting_at'+ ? t('newChat.modelSelector.displayPricing.startingAt', { price })+ : price;+ return (+ <span className="min-w-0 break-words tabular-nums">+ {quote.tier && <>{quote.tier} </>}+ {qualifiedPrice}+ {amount.original && <s className="ml-1.5 text-[var(--text-tertiary)]">{amount.original}</s>}+ <span className="ml-1 text-[var(--text-tertiary)]">+ / {quantity ? `${quantity} ` : ''}+ {unit}+ </span>+ </span>+ );+}+/** 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) ?? [];@@ -30,43 +69,19 @@ export function DisplayPricingDetails({ model }: { model: PricingModel }) {{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.displayPricing.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>- );- })}+ {items.map((item, index) => (+ <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>}+ <DisplayPricingQuote+ quote={{ ...item, tier: undefined }}+ currency={model.currency!}+ costDiscount={model.costDiscount}+ />+ </div>+ ))}</div>))}{model.displayPricing.notes?.map((note, index) => (diff --git a/apps/desktop/src/renderer/components/__tests__/DisplayPricingDetails.test.tsx b/apps/desktop/src/renderer/components/__tests__/DisplayPricingDetails.test.tsxindex 8aa4d7a529..796e67edc7 100644--- a/apps/desktop/src/renderer/components/__tests__/DisplayPricingDetails.test.tsx+++ b/apps/desktop/src/renderer/components/__tests__/DisplayPricingDetails.test.tsx@@ -9,18 +9,18 @@ import zhCN from '@/i18n/locales/zh-CN/common.json';import zhTW from '@/i18n/locales/zh-TW/common.json';import ja from '@/i18n/locales/ja/common.json';import ko from '@/i18n/locales/ko/common.json';-import { DisplayPricingDetails } from '../DisplayPricingDetails';+import { DisplayPricingDetails, DisplayPricingQuote } from '../DisplayPricingDetails';const locales = { en, 'zh-CN': zhCN, 'zh-TW': zhTW, ja, ko };type PricingModel = Pick<CatalogModel, 'displayPricing' | 'currency' | 'costDiscount'>;const item = { label: 'Output', price: 0.5, unit: 'second', quantity: 1 };-async function renderPricing(model: PricingModel, locale: keyof typeof locales = 'en') {+async function renderPricing(model: PricingModel, locale: keyof typeof locales = 'en', summary = false) {const i18n = createInstance();await i18n.init({ lng: locale, resources: { [locale]: { translation: locales[locale] } } });return render(<I18nextProvider i18n={i18n}>- <DisplayPricingDetails model={model} />+ {summary ? <DisplayPricingQuote quote={model.displayPricing!.summary!.output![0]} currency={model.currency!} costDiscount={model.costDiscount} /> : <DisplayPricingDetails model={model} />}</I18nextProvider>,);}@@ -52,7 +52,7 @@ describe('DisplayPricingDetails', () => {expect(within(output).getByText('$0.5').tagName).toBe('S');expect(within(output).getByText('/ second')).toBeTruthy();expect(within(output).getByText('/ 3 custom-unit')).toBeTruthy();- expect(within(input).getByText('/ 1,000,000 tokens')).toBeTruthy();+ expect(within(input).getByText('/ 1M tokens')).toBeTruthy();expect(screen.getByText('Billed by output duration.')).toBeTruthy();expect(screen.getByText('<b>Provider terms</b>')).toBeTruthy();expect(container.querySelector('b')).toBeNull();@@ -82,6 +82,24 @@ describe('DisplayPricingDetails', () => {},);+ // Summary contract, unit tier: real quote/table rendering with million quantities and range qualifiers.+ // Earlier cases had no summary or localized million denominator; minimal input is one output quote.+ it.each(['estimated', 'starting_at'] as const)('renders summary range, tier, discount and %s in this locale', async priceType => {+ const copy = locales[locale].newChat.modelSelector.displayPricing;+ const { container } = await renderPricing({ currency: 'CNY', costDiscount: 0.2, displayPricing: {+ items: [item], summary: { output: [{ price: 6, maxPrice: 10, tier: '480P/720P', unit: 'token', quantity: 1000000, priceType }] },+ } }, locale, true);+ expect(container.textContent).toContain('480P/720P');+ expect(container.textContent).toContain((priceType === 'estimated' ? copy.estimated : copy.startingAt).replace('{{price}}', '¥4.8–¥8'));+ expect(container.querySelector('s')?.textContent).toBe('¥6–¥10');+ expect(screen.getByText(`/ ${copy.million} ${copy.units.token}`)).toBeTruthy();+ });+ it('uses the same million denominator in the supplementary price table', async () => {+ await renderPricing({ currency: 'CNY', displayPricing: { items: [{ ...item, unit: 'character', quantity: 1000000 }] } }, locale);+ const copy = locales[locale].newChat.modelSelector.displayPricing;+ expect(screen.getByText(`/ ${copy.million} ${copy.units.character}`)).toBeTruthy();+ });+it('localizes known image units and keeps unknown provider units unchanged', async () => {await renderPricing({currency: 'CNY',diff --git a/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx b/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsxindex f8ec1f9a36..2e4492cc70 100644--- a/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx+++ b/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx@@ -1,4 +1,4 @@-import { DisplayPricingDetails } from '@/components/DisplayPricingDetails';+import { DisplayPricingDetails, DisplayPricingQuote } from '@/components/DisplayPricingDetails';import { Button } from '@/components/ui/button';import { localizedModelDescription } from '@/lib/modelDescriptions';import { localizedModelName, localizedBrandName } from '@/lib/modelDisplayNames';@@ -995,7 +995,33 @@ export function ModelAdvancedDrawer({<Section title={t('settings.providers.models.advanced.pricing')}>{primaryModel.displayPricing && primaryModel.currency ? (- <DisplayPricingDetails model={primaryModel} />+ <>+ {(['input', 'output', 'cacheRead', 'cacheWrite'] as const).map((role) => {+ const quotes = primaryModel.displayPricing?.summary?.[role];+ if (!quotes?.length) return null;+ return (+ <Row+ key={role}+ label={t(`settings.providers.models.advanced.price.${role === 'cacheWrite' ? 'cacheCreate' : role}`)}+ >+ {quotes.map((quote, index) => (+ <span key={index}>+ {index > 0 && ' · '}+ <DisplayPricingQuote+ quote={quote}+ currency={primaryModel.currency!}+ costDiscount={primaryModel.costDiscount}+ />+ </span>+ ))}+ </Row>+ );+ })}+ {/* Item labels may carry conditions absent from summary; retain the supplier's full table. */}+ <div className={primaryModel.displayPricing.summary ? 'pt-3' : undefined}>+ <DisplayPricingDetails model={primaryModel} />+ </div>+ </>) : price === null ? (<Row label={t('settings.providers.models.advanced.pricingLabel')} muted>{t(diff --git a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsxindex 8b6366adf8..14cee635ce 100644--- a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx+++ b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx@@ -1,3 +1,4 @@+import { DisplayPricingQuote } from '@/components/DisplayPricingDetails';import { Button } from '@/components/ui/button';import { localizedModelName, localizedBrandName, matchesModelName } from '@/lib/modelDisplayNames';import { modelManagementState } from './modelManagementState';@@ -991,8 +992,15 @@ export function UnifiedModelList({是用来在读到某个模型名时顺手知道它贵不贵。拿不到报价就整个不渲染 —— 不画假的「$」也不画「—」。 */}{(() => {- // Mixed-unit quotes are shown in the existing model details only.- if (rep.displayPricing && rep.currency) return null;+ if (rep.displayPricing && rep.currency) {+ const summary = rep.displayPricing.summary;+ const quote = summary?.output?.[0] ?? summary?.input?.[0];+ return quote ? (+ <span className="min-w-0 text-11 text-[var(--text-secondary)]">+ <DisplayPricingQuote quote={quote} currency={rep.currency} costDiscount={rep.costDiscount} />+ </span>+ ) : null;+ }const display = rowPriceDisplay(row);if (!display) return null;if (display.kind === 'free') {diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsxindex 9505c81ad2..3e40b15199 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx@@ -785,3 +785,33 @@ it('keeps enterprise reference prices read-only in the model drawer', () => {screen.queryByRole('button', { name: 'settings.providers.models.priceOverride.menu' }),).toBeNull();});++// Unit contract: drawer summary must show translated roles while retaining supplier conditions below.+// Previous drawer tests had no displayPricing; one input quote previously showed only the English table.+it.each([{ hasSummary: true, withNotes: true }, { hasSummary: true, withNotes: false }, { hasSummary: false, withNotes: false }])('keeps supplier detail labels even without tiers or notes: %j', ({ hasSummary, withNotes }) => {+ const quote = { price: 0.02, unit: 'image', quantity: 1 };+ const summary = { input: [quote, { price: 140, unit: 'character', quantity: 1000000 }],+ output: [{ ...quote, price: 6, maxPrice: 10, tier: '480P/720P' }],+ cacheRead: [quote], cacheWrite: [quote] };+ draw({ ...model, currency: 'CNY', costDiscount: 0.2, displayPricing: {+ items: [{ ...quote, label: 'Supplier-specific charge' }], ...(withNotes ? { notes: ['Provider billing condition'] } : {}),+ ...(hasSummary ? { summary } : {}),+ } });+ expect(screen.getByText('Supplier-specific charge')).toBeTruthy();+ if (withNotes) expect(screen.getByText('Provider billing condition')).toBeTruthy();+ if (!hasSummary) {+ expect(screen.queryByText('settings.providers.models.advanced.price.input')).toBeNull();+ return;+ }+ const input = screen.getByText('settings.providers.models.advanced.price.input').parentElement!;+ expect(input.textContent).toContain('¥0.016');+ expect(input.textContent).toContain(' · ');+ expect(input.textContent).toContain('¥112');+ expect(input.querySelector('s')?.textContent).toBe('¥0.02');+ const output = screen.getByText('settings.providers.models.advanced.price.output').parentElement!;+ expect(output.textContent).toContain('480P/720P ¥4.8–¥8');+ expect(output.querySelector('s')?.textContent).toBe('¥6–¥10');+ expect(screen.getByText('settings.providers.models.advanced.price.cacheRead')).toBeTruthy();+ expect(screen.getByText('settings.providers.models.advanced.price.cacheCreate')).toBeTruthy();+ expect(output.compareDocumentPosition(screen.getByText('Supplier-specific charge')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex fd904388c2..94087f2b53 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10815,6 +10815,7 @@},"modelSelector": {"displayPricing": {+ "million": "1M","free": "Free","estimated": "About {{price}}","startingAt": "From {{price}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 5658a2a556..479b19724c 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -10780,6 +10780,7 @@},"modelSelector": {"displayPricing": {+ "million": "100万","free": "無料","estimated": "約 {{price}}","startingAt": "{{price}} から",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex ee7ef042a9..a3fef6ace8 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10780,6 +10780,7 @@},"modelSelector": {"displayPricing": {+ "million": "100만","free": "무료","estimated": "약 {{price}}","startingAt": "{{price}}부터",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 99a89422e1..7d4ae18020 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -10780,6 +10780,7 @@},"modelSelector": {"displayPricing": {+ "million": "百万","free": "免费","estimated": "约 {{price}}","startingAt": "{{price}} 起",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 6512ad1390..89233c6a09 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -10780,6 +10780,7 @@},"modelSelector": {"displayPricing": {+ "million": "百萬","free": "免費","estimated": "約 {{price}}","startingAt": "{{price}} 起",diff --git a/apps/desktop/src/renderer/lib/__tests__/displayPricingFormat.test.ts b/apps/desktop/src/renderer/lib/__tests__/displayPricingFormat.test.tsindex d32e84ed1b..21d4d3d848 100644--- a/apps/desktop/src/renderer/lib/__tests__/displayPricingFormat.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/displayPricingFormat.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { displayPricingAmount } from '../displayPricingFormat';+import { displayPricingAmount, displayPricingQuantity } 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', () => {@@ -25,3 +25,21 @@ describe('display pricing amounts', () => {expect(displayPricingAmount(row, 'USD', 1, 'en').original).toContain('0.5');});});++// Unit contract: ranges must discount both endpoints once, including zero-to-paid ranges.+// Previous coverage only checked single amounts; minimum regression is { price: 6, maxPrice: 10 }.+it('discounts both range endpoints without marking a zero lower bound as free', () => {+ expect(displayPricingAmount({ price: 6, maxPrice: 10 }, 'CNY', 0.2, 'en'))+ .toEqual({ current: '¥4.8–¥8', original: '¥6–¥10', free: false });+ expect(displayPricingAmount({ price: 0, maxPrice: 10 }, 'USD', 0, 'en'))+ .toEqual({ current: '$0–$10', free: false });+ expect(displayPricingAmount({ price: 0, maxPrice: 10 }, 'USD', 1, 'en'))+ .toEqual({ current: '$0', original: '$0–$10', free: true });+});+// Unit contract: quantity 1 is omitted; million is localized; arbitrary values retain their basis.+it.each([+ [1, 'en', '1M', ''], [1000000, 'zh-CN', '百万', '百万'],+ [1000000, 'en', '1M', '1M'], [1234.5, 'en', '1M', '1,234.5'],+])('formats quantity %s in %s', (quantity, locale, million, expected) => {+ expect(displayPricingQuantity(quantity as number, locale as string, million as string)).toBe(expected);+});diff --git a/apps/desktop/src/renderer/lib/displayPricingFormat.ts b/apps/desktop/src/renderer/lib/displayPricingFormat.tsindex 9d19dcb950..8f830e456b 100644--- a/apps/desktop/src/renderer/lib/displayPricingFormat.ts+++ b/apps/desktop/src/renderer/lib/displayPricingFormat.ts@@ -1,8 +1,8 @@-import type { ModelDisplayPricing } from '@cindy/model-providers';+import type { SummaryQuote } 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],+ item: Pick<SummaryQuote, 'price' | 'maxPrice'>,currency: 'CNY' | 'USD',costDiscount: number | undefined,locale: string,@@ -22,9 +22,19 @@ export function displayPricingAmount(// Match existing model prices while preserving small per-unit amounts.const symbol = currency === 'CNY' ? '¥' : '$';const money = (value: number) => `${symbol}${number.format(value)}`;+ const upper = item.maxPrice ?? item.price;+ const range = (low: number, high: number) =>+ low === high ? money(low) : `${money(low)}–${money(high)}`;return {- current: money(amount),- ...(discount > 0 && item.price > 0 ? { original: money(item.price) } : {}),- free: item.price === 0 || discount === 1,+ current: range(amount, upper * (1 - discount)),+ ...(discount > 0 && upper > 0 ? { original: range(item.price, upper) } : {}),+ free: upper === 0 || discount === 1,};}++/** Quantity is a display denominator, never a conversion of the supplier's price. */+export function displayPricingQuantity(quantity: number, locale: string, million: string): string {+ if (quantity === 1) return '';+ if (quantity === 1_000_000) return million;+ return new Intl.NumberFormat(locale, { maximumSignificantDigits: 12 }).format(quantity);+}diff --git a/docs/dev-rules/model-catalog-maintenance.md b/docs/dev-rules/model-catalog-maintenance.mdindex 5be27a191d..e39e7f11ae 100644--- a/docs/dev-rules/model-catalog-maintenance.md+++ b/docs/dev-rules/model-catalog-maintenance.md@@ -109,10 +109,16 @@ Registry/defaults、ModelPriceQuote 或 token 成本估算,不跨供应商补成功刷新缺字段或价目不可解析时清除旧价目,模型仍正常更新;新增属性忽略,未知单位保留。展示字段变化不构成整份目录失败;网络或核心模型协议失败仍沿用既有目录恢复语义。-Desktop 模型详情优先展示结构化价目,缺字段沿用原有价格。`price` 为每 `quantity` 个-`unit` 的折扣前报价,只在展示时应用一次折扣,保留币种与“约/起价”语义;label、tier、-notes 仅按纯文本呈现,未知单位不猜换算。列表不新增价格入口,统一从既有模型详情查看,也不从混合单位挑最低价。-共享目录可传递这些可选展示字段,旧端缺字段仍合法;首期 UI 仅覆盖 Desktop 现有详情入口。+Desktop 设置页模型详情有 `displayPricing.summary` 时优先按输入、输出、缓存读取、缓存写入+展示主报价,每个角色允许 1–4 段、各带单位与数量,可带最高价形成区间。summary 缺失或无效时+沿用原价目表;summary 无效只清除摘要,不丢价目表。详细价目表保留在摘要下方,因为供应商+label 可能包含摘要没有的条件,不能仅凭金额相同判断重复。设置页列表取 output 首段,没有则取+input 首段;不从混合单位挑最低价。选择器、浮层和聊天价格档位逻辑保持原样。+`price` / `maxPrice` 为每 `quantity` 个 `unit` 的折扣前报价,只在展示时应用一次折扣,保留币种+与“约/起价”语义;角色和已知单位本地化,label、tier、notes 仅按纯文本呈现,未知单位不猜换算。+数量 1 省略,百万按语言简写,其余按本地数字格式显示。共享目录可传递这些可选展示字段,旧端+缺字段仍合法,不新增能力声明;此 UI 仅覆盖 Desktop 设置页。解析与展示回归见+`modelDisplayPricing.test.ts`、`DisplayPricingDetails.test.tsx` 与 `modelManagementActions.test.tsx`。### 覆盖顺序diff --git a/packages/model-providers/src/__tests__/modelDisplayPricing.test.ts b/packages/model-providers/src/__tests__/modelDisplayPricing.test.tsindex 2730ce1add..e54907d9de 100644--- a/packages/model-providers/src/__tests__/modelDisplayPricing.test.ts+++ b/packages/model-providers/src/__tests__/modelDisplayPricing.test.ts@@ -67,3 +67,74 @@ describe("display pricing contract", () => {).toEqual({ items: [row] });});});++// Contract regression: the old parser dropped a valid summary. Unit tier; existing cases only covered items.+// Minimum input: one summary.input quote. Invalid roles must drop the summary, preserving the full table.+describe("optional primary quote summary", () => {+ const quote = { price: 0, unit: "image", quantity: 1 };+ it("preserves all roles, ranges, units and conditions but strips unknown fields", () => {+ const summary = {+ input: [quote, { price: 140, unit: "character", quantity: 1000000 }],+ output: [+ {+ price: 6,+ maxPrice: 10,+ unit: "token",+ quantity: 1000000,+ tier: "480P/720P",+ priceType: "starting_at",+ },+ ],+ cacheRead: [{ ...quote, priceType: "exact" }],+ cacheWrite: [{ ...quote, priceType: "estimated" }],+ };+ expect(+ parseModelDisplayPricing({+ ...table,+ summary: { ...summary, future: true },+ }),+ ).toEqual({ ...table, summary });+ });+ it.each([+ undefined,+ null,+ {},+ [],+ "summary",+ { input: null },+ { input: [] },+ { input: Array(5).fill(quote) },+ { input: [quote, quote] },+ ...[+ { price: -1 },+ { price: Infinity },+ { price: "1" },+ { quantity: 0 },+ { quantity: NaN },+ { unit: " " },+ { unit: "x".repeat(129) },+ { tier: "" },+ { priceType: "future" },+ { maxPrice: 0 },+ { maxPrice: -1 },+ { maxPrice: Infinity },+ { maxPrice: null },+ { maxPrice: "2" },+ ].map((patch) => ({ output: [quote], input: [{ ...quote, ...patch }] })),+ ])("drops absent or invalid summary only: %j", (summary) => {+ expect(parseModelDisplayPricing({ ...table, summary })).toEqual(table);+ });+ it("allows four distinct denominators and preserves unknown units", () => {+ const summary = {+ input: [+ quote,+ { ...quote, quantity: 2 },+ { ...quote, unit: "future" },+ { ...quote, quantity: 0.5 },+ ],+ };+ expect(parseModelDisplayPricing({ ...table, summary })?.summary).toEqual(+ summary,+ );+ });+});diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.tsindex 269da87fe5..4051f44ec6 100644--- a/packages/model-providers/src/index.ts+++ b/packages/model-providers/src/index.ts@@ -1,4 +1,4 @@-export { parseModelDisplayPricing, type ModelDisplayPricing } from './modelDisplayPricing.js';+export { parseModelDisplayPricing, type ModelDisplayPricing, type ModelDisplayPricingSummary, type SummaryQuote } from './modelDisplayPricing.js';export { providerProtocolCandidates, type ProviderProtocolCandidate } from './providerProtocolProbe.js';export { remoteInvocationModels } from './remoteModels.js';/**diff --git a/packages/model-providers/src/modelDisplayPricing.ts b/packages/model-providers/src/modelDisplayPricing.tsindex 660fc6a7e4..cb330999e7 100644--- a/packages/model-providers/src/modelDisplayPricing.ts+++ b/packages/model-providers/src/modelDisplayPricing.ts@@ -1,3 +1,17 @@+/** Undiscounted presentation quote; its unit never participates in token cost estimates. */+export interface SummaryQuote {+ price: number;+ maxPrice?: number;+ unit: string;+ quantity: number;+ tier?: string;+ priceType?: "exact" | "estimated" | "starting_at";+}++export type ModelDisplayPricingSummary = Partial<+ Record<"input" | "output" | "cacheRead" | "cacheWrite", SummaryQuote[]>+>;+/** Provider presentation only; never used to calculate usage or authorize a model. */export interface ModelDisplayPricing {items: Array<{@@ -9,6 +23,7 @@ export interface ModelDisplayPricing {priceType?: "exact" | "estimated" | "starting_at";}>;notes?: string[];+ summary?: ModelDisplayPricingSummary;}/** The whole table is atomic: never silently drop a charge or billing condition. */@@ -24,8 +39,6 @@ export function parseModelDisplayPricing(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) ||@@ -38,33 +51,91 @@ export function parseModelDisplayPricing(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 } : {}),- });+ if (!text(row.label, 256)) return undefined;+ const quote = parseQuote(row);+ if (!quote) return undefined;+ items.push({ label: row.label, ...quote });}+ const summary = parseSummary(raw.summary);return {items,+ ...(summary ? { summary } : {}),...(raw.notes !== undefined ? { notes: [...(raw.notes as string[])] } : {}),};}++/** Invalid optional summaries never discard the independent detailed price table. */+function parseSummary(value: unknown): ModelDisplayPricingSummary | undefined {+ if (!value || typeof value !== "object" || Array.isArray(value))+ return undefined;+ const raw = value as Record<string, unknown>;+ const summary: ModelDisplayPricingSummary = {};+ for (const role of ["input", "output", "cacheRead", "cacheWrite"] as const) {+ const quotes = raw[role];+ if (quotes === undefined) continue;+ if (!Array.isArray(quotes) || quotes.length === 0 || quotes.length > 4)+ return undefined;+ const result: SummaryQuote[] = [];+ for (const quote of quotes) {+ if (!quote || typeof quote !== "object" || Array.isArray(quote))+ return undefined;+ // Reuse the item's unit, quantity, tier and priceType contract, without retaining labels.+ const item = parseQuote(quote as Record<string, unknown>);+ if (!item) return undefined;+ const maxPrice: unknown = quote.maxPrice;+ if (+ maxPrice !== undefined &&+ (typeof maxPrice !== "number" ||+ !Number.isFinite(maxPrice) ||+ maxPrice <= item.price)+ ) {+ return undefined;+ }+ if (+ result.some(+ (previous) =>+ previous.unit === item.unit && previous.quantity === item.quantity,+ )+ ) {+ return undefined;+ }+ result.push({ ...item, ...(maxPrice !== undefined ? { maxPrice } : {}) });+ }+ summary[role] = result;+ }+ return Object.keys(summary).length ? summary : undefined;+}++function text(value: unknown, max: number): value is string {+ return (+ typeof value === "string" && value.trim().length > 0 && value.length <= max+ );+}++/** Detailed rows and summaries use exactly the same single-quote validation. */+function parseQuote(+ row: Record<string, unknown>,+): Omit<SummaryQuote, "maxPrice"> | undefined {+ if (+ !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;+ return {+ price: row.price,+ unit: row.unit,+ quantity: row.quantity,+ ...(row.tier !== undefined ? { tier: row.tier } : {}),+ ...(row.priceType !== undefined ? { priceType: row.priceType } : {}),+ };+}