🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: support contextual model pricing (#16135)
YuTengjing724659f10dca
diff --git a/apps/server/src/routers/async/image.ts b/apps/server/src/routers/async/image.tsindex f740d49dbdc..a2d7a972348 100644--- a/apps/server/src/routers/async/image.ts+++ b/apps/server/src/routers/async/image.ts@@ -4,6 +4,7 @@ import {buildMappedBusinessModelFields,resolveBusinessModelMapping,} from '@lobechat/business-model-runtime';+import { type CreateImageMethodOptions } from '@lobechat/model-runtime';import { AsyncTaskError, AsyncTaskStatus, RequestTrigger } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -144,19 +145,20 @@ export const imageRouter = router({// Check if operation has been cancelledcheckAbortSignal(signal);log('Agent runtime initialized, calling createImage');+ const runtimeOptions: CreateImageMethodOptions = {+ metadata: {+ generationBatchId,+ generationId,+ taskId,+ trigger: RequestTrigger.Image,+ },+ };const response = await modelRuntime.createImage!({model: resolvedModelId,params: params as unknown as RuntimeImageGenParams,},- {- metadata: {- generationBatchId,- generationId,- taskId,- trigger: RequestTrigger.Image,- },- },+ runtimeOptions,);if (!response) {@@ -277,6 +279,7 @@ export const imageRouter = router({}),},modelUsage,+ pricingContext: runtimeOptions.pricingContext,provider,userId: ctx.userId,workspaceId,diff --git a/packages/business-server/src/image-generation/chargeAfterGenerate.ts b/packages/business-server/src/image-generation/chargeAfterGenerate.tsindex 57505f8842e..73649d110ee 100644--- a/packages/business-server/src/image-generation/chargeAfterGenerate.ts+++ b/packages/business-server/src/image-generation/chargeAfterGenerate.ts@@ -1,3 +1,5 @@+import { type ModelPricingContext } from '@lobechat/model-runtime';+import { type ModelPerformance, type ModelUsage } from '@/types/index';interface ChargeParams {@@ -9,6 +11,7 @@ interface ChargeParams {};metrics?: ModelPerformance;modelUsage?: ModelUsage;+ pricingContext?: ModelPricingContext;provider: string;userId: string;workspaceId?: string;diff --git a/packages/business/model-bank/src/model-config.ts b/packages/business/model-bank/src/model-config.tsindex eb3953434fd..fb04a742fa2 100644--- a/packages/business/model-bank/src/model-config.ts+++ b/packages/business/model-bank/src/model-config.ts@@ -8,6 +8,15 @@ interface LobeHubModelConfig {version: number;}+export interface LobeHubModelPricingContext {+ plan: string;+ scope: 'personal';+}++export interface LobeHubModelPricingOptions {+ pricingContext?: LobeHubModelPricingContext;+}+const getDefaultLobeHubModelConfig = (): LobeHubModelConfig => ({models: [],planCardModels: [],@@ -17,7 +26,7 @@ const getDefaultLobeHubModelConfig = (): LobeHubModelConfig => ({const loadLobeHubModelConfig = async (): Promise<LobeHubModelConfig> =>getDefaultLobeHubModelConfig();-export const loadModels = async () =>+export const loadModels = async (_options?: LobeHubModelPricingOptions) =>loadModelBankModels({providerLoaders: {[ModelProvider.LobeHub]: loadLobeHubModels,diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.tsindex 0697d9a20c9..fcaacb5eabd 100644--- a/packages/model-bank/src/types/aiModel.ts+++ b/packages/model-bank/src/types/aiModel.ts@@ -192,6 +192,10 @@ export interface FixedPricingUnit extends PricingUnitBase {export interface TieredPricingUnit extends PricingUnitBase {strategy: 'tiered';tiers: Array<{+ /**+ * Original display price before discounts. Billing and cost calculation use `rate`.+ */+ originalRate?: number;rate: number;upTo: number | 'infinity';}>;@@ -199,6 +203,10 @@ export interface TieredPricingUnit extends PricingUnitBase {export interface LookupPricingUnit extends PricingUnitBase {lookup: {+ /**+ * Original display prices before discounts. Billing and cost calculation use `prices`.+ */+ originalPrices?: Record<string, number>;prices: Record<string, number>;pricingParams: string[];};diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.tsindex de8a1c6ae8d..11733967b30 100644--- a/packages/model-runtime/src/core/ModelRuntime.test.ts+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts@@ -3,11 +3,16 @@ import type { ClientSecretPayload } from '@lobechat/types';import { ModelProvider } from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { ChatStreamCallbacks, ChatStreamPayload, ModelRuntimeHooks } from '../index';-import { LobeOpenAI, ModelRuntime } from '../index';+import { LobeOpenAI } from '../providers/openai';import { providerRuntimeMap } from '../runtimeMap';+import type { ChatStreamCallbacks, ChatStreamPayload } from '../types';import type { CreateImagePayload } from '../types/image';import type { CreateVideoPayload } from '../types/video';+import { ModelRuntime, type ModelRuntimeHooks } from './ModelRuntime';++vi.mock('../providers/lobehub', () => ({+ LobeHubAI: class LobeHubAI {},+}));/*** Mock createTraceOptions for testing purposes.@@ -557,10 +562,23 @@ describe('ModelRuntime', () => {await runtime.chat(chatPayload);- expect(beforeChat).toHaveBeenCalledWith(chatPayload, undefined);+ expect(beforeChat).toHaveBeenCalledWith(chatPayload, {});expect(mockRuntimeAI.chat).toHaveBeenCalled();});+ it('forwards beforeChat option mutations to runtime.chat', async () => {+ const pricingContext = { plan: 'premium', scope: 'personal' } as const;+ const beforeChat: ModelRuntimeHooks['beforeChat'] = async (_payload, options) => {+ if (options) options.pricingContext = pricingContext;+ };+ const { runtime, mockRuntimeAI } = createMockRuntime({ beforeChat });+ mockRuntimeAI.chat.mockResolvedValue(new Response(''));++ await runtime.chat(chatPayload);++ expect(mockRuntimeAI.chat).toHaveBeenCalledWith(chatPayload, { pricingContext });+ });+it('beforeChat throwing aborts chat call', async () => {const beforeChat = vi.fn().mockRejectedValue(new Error('budget exceeded'));const { runtime, mockRuntimeAI } = createMockRuntime({ beforeChat });@@ -649,7 +667,7 @@ describe('ModelRuntime', () => {await runtime.generateObject(genObjPayload);- expect(beforeGenerateObject).toHaveBeenCalledWith(genObjPayload, undefined);+ expect(beforeGenerateObject).toHaveBeenCalledWith(genObjPayload, {});expect(mockRuntimeAI.generateObject).toHaveBeenCalled();});diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex 78ba41b591d..0b612ff214c 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -67,6 +67,14 @@ export interface ModelRuntimeHooks {* Runs before the LLM call. Throw to abort (e.g., budget exceeded).*/beforeChat?: (payload: ChatStreamPayload, options?: ChatMethodOptions) => Promise<void>;+ beforeCreateImage?: (+ payload: CreateImagePayload,+ options?: CreateImageMethodOptions,+ ) => Promise<void>;+ beforeCreateVideo?: (+ payload: CreateVideoPayload,+ options?: CreateVideoMethodOptions,+ ) => Promise<void>;beforeEmbeddings?: (payload: EmbeddingsPayload, options?: EmbeddingsOptions) => Promise<void>;beforeGenerateObject?: (payload: GenerateObjectPayload,@@ -243,6 +251,7 @@ export class ModelRuntime {payload: ChatStreamPayload,options?: ChatMethodOptions,): Promise<ChatMethodOptions | undefined> {+ const hookOptions = this._hooks?.beforeChat && !options ? {} : options;const metadata = getLobeHubTimingMetadata(options);const beforeChatStartedAt = Date.now();if (metadata) {@@ -254,7 +263,7 @@ export class ModelRuntime {);}try {- await this._hooks?.beforeChat?.(payload, options);+ await this._hooks?.beforeChat?.(payload, hookOptions);} catch (error) {if (metadata) {timing(@@ -275,14 +284,14 @@ export class ModelRuntime {);}- if (!this._hooks?.onChatFinal) return options;+ if (!this._hooks?.onChatFinal) return hookOptions;const hookFn = this._hooks.onChatFinal;- const existingOnFinal = options?.callback?.onFinal;+ const existingOnFinal = hookOptions?.callback?.onFinal;return {- ...options,+ ...hookOptions,callback: {- ...options?.callback,+ ...hookOptions?.callback,async onFinal(data) {const finalStartedAt = Date.now();if (metadata) {@@ -348,7 +357,8 @@ export class ModelRuntime {};try {- await this._hooks?.beforeGenerateObject?.(payload, options);+ const hookOptions = this._hooks?.beforeGenerateObject && !options ? {} : options;+ await this._hooks?.beforeGenerateObject?.(payload, hookOptions);const runtimeStartedAt = Date.now();const needsUsageCapture =@@ -356,11 +366,11 @@ export class ModelRuntime {const finalOptions = needsUsageCapture? {- ...options,+ ...hookOptions,onUsage: async (usage: ModelUsage) => {usageCapture = usage;const speed = buildGenerateObjectSpeed(runtimeStartedAt, usage);- await options?.onUsage?.(usage);+ await hookOptions?.onUsage?.(usage);try {await this._hooks?.onGenerateObjectFinal?.({ speed, usage }, { options, payload });} catch (e) {@@ -369,7 +379,7 @@ export class ModelRuntime {}},}- : options;+ : hookOptions;const output = await this._runtime.generateObject!(payload, finalOptions);await fireComplete({ output, success: true });@@ -397,11 +407,17 @@ export class ModelRuntime {}async createImage(payload: CreateImagePayload, options?: CreateImageMethodOptions) {- return this._runtime.createImage?.(payload, options);+ const finalOptions = this._hooks?.beforeCreateImage && !options ? {} : options;+ await this._hooks?.beforeCreateImage?.(payload, finalOptions);++ return this._runtime.createImage?.(payload, finalOptions);}async createVideo(payload: CreateVideoPayload, options?: CreateVideoMethodOptions) {- return this._runtime.createVideo?.(payload, options);+ const finalOptions = this._hooks?.beforeCreateVideo && !options ? {} : options;+ await this._hooks?.beforeCreateVideo?.(payload, finalOptions);++ return this._runtime.createVideo?.(payload, finalOptions);}async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {@@ -418,15 +434,16 @@ export class ModelRuntime {async embeddings(payload: EmbeddingsPayload, options?: EmbeddingsOptions) {try {- await this._hooks?.beforeEmbeddings?.(payload, options);+ const hookOptions = this._hooks?.beforeEmbeddings && !options ? {} : options;+ await this._hooks?.beforeEmbeddings?.(payload, hookOptions);const startTime = Date.now();const finalOptions = this._hooks?.onEmbeddingsFinal? {- ...options,+ ...hookOptions,onUsage: async (usage: ModelUsage) => {- await options?.onUsage?.(usage);+ await hookOptions?.onUsage?.(usage);try {const latencyMs = Date.now() - startTime;await this._hooks!.onEmbeddingsFinal!({ latencyMs, usage }, { options, payload });@@ -435,7 +452,7 @@ export class ModelRuntime {}},}- : options;+ : hookOptions;return await this._runtime.embeddings?.(payload, finalOptions);} catch (error) {diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.tsindex 91051d0af04..0288bd2bb06 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts@@ -1041,7 +1041,7 @@ describe('createRouterRuntime', () => {const result = await runtime.createImage(payload);expect(result).toEqual({ imageUrl: 'https://example.com/image.png' });- expect(mockCreateImage).toHaveBeenCalledWith(payload);+ expect(mockCreateImage).toHaveBeenCalledWith(payload, undefined);});it('should forward options.metadata to onRouteAttempt', async () => {@@ -1070,10 +1070,14 @@ describe('createRouterRuntime', () => {const runtime = new Runtime();const payload = { model: 'gpt-image-1', params: { prompt: 'a cat' } };const metadata = { trigger: 'image' };+ const options = {+ metadata,+ pricingContext: { plan: 'premium', scope: 'personal' },+ } as const;- await runtime.createImage(payload, { metadata });+ await runtime.createImage(payload, options);- expect(mockCreateImage).toHaveBeenCalledWith(payload);+ expect(mockCreateImage).toHaveBeenCalledWith(payload, options);expect(onRouteAttempt).toHaveBeenCalledWith(expect.objectContaining({ metadata }));});});@@ -1103,7 +1107,7 @@ describe('createRouterRuntime', () => {const result = await runtime.createVideo(payload);expect(result).toEqual({ inferenceId: 'job-1' });- expect(mockCreateVideo).toHaveBeenCalledWith(payload);+ expect(mockCreateVideo).toHaveBeenCalledWith(payload, undefined);});it('should forward options.metadata to onRouteAttempt', async () => {@@ -1130,10 +1134,14 @@ describe('createRouterRuntime', () => {const runtime = new Runtime();const payload = { model: 'sora-1', params: { prompt: 'a cat' } } as any;const metadata = { trigger: 'video' };+ const options = {+ metadata,+ pricingContext: { plan: 'premium', scope: 'personal' },+ } as const;- await runtime.createVideo(payload, { metadata });+ await runtime.createVideo(payload, options);- expect(mockCreateVideo).toHaveBeenCalledWith(payload);+ expect(mockCreateVideo).toHaveBeenCalledWith(payload, options);expect(onRouteAttempt).toHaveBeenCalledWith(expect.objectContaining({ metadata }));});diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex 1c80f247fe3..ae0da1ea717 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -720,7 +720,7 @@ export const createRouterRuntime = ({async createImage(payload: CreateImagePayload, options?: CreateImageMethodOptions) {return this.runWithFallback(payload.model,- (runtime) => runtime.createImage!(payload),+ (runtime) => runtime.createImage!(payload, options),options?.metadata,);}@@ -728,7 +728,7 @@ export const createRouterRuntime = ({async createVideo(payload: CreateVideoPayload, options?: CreateVideoMethodOptions) {return this.runWithFallback(payload.model,- (runtime) => runtime.createVideo!(payload),+ (runtime) => runtime.createVideo!(payload, options),options?.metadata,);}diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.tsindex 009c18dcaab..6e1cd4abe6e 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts@@ -561,7 +561,7 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =},);- const pricing = await getModelPricing(payload.model, this.id);+ const pricing = await getModelPricing(payload.model, this.id, options?.pricingContext);const pricingOptions = await chatCompletion?.getPricingOptions?.(payload, postPayload);const streamOptions = {callbacks: options?.callback,@@ -694,7 +694,7 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =}try {- const pricing = await getModelPricing(payload.model, this.id);+ const pricing = await getModelPricing(payload.model, this.id, options?.pricingContext);return await generateObject(this.client, payload, options, pricing, {requestModel: resolveMappedModelId(payload.model, this.modelIdMappingOptions),});diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.tsindex 173baa5430a..6e5c87dc5d7 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts@@ -4,7 +4,11 @@ import createDebug from 'debug';import type { RuntimeImageGenParamsValue } from 'model-bank';import type OpenAI from 'openai';-import type { CreateImagePayload, CreateImageResponse } from '../../types/image';+import type {+ CreateImageMethodOptions,+ CreateImagePayload,+ CreateImageResponse,+} from '../../types/image';import { getModelPricing } from '../../utils/getModelPricing';import { parseDataUri } from '../../utils/uriParser';import { convertImageUrlToFile } from '../contextBuilders/openai';@@ -13,6 +17,7 @@ import { convertOpenAIImageUsage } from '../usageConverters/openai';const log = createDebug('lobe-image:openai-compatible');interface CreateOpenAICompatibleImageOptions {+ pricingContext?: CreateImageMethodOptions['pricingContext'];pricingModel?: string;requestModel?: string;routingModel?: string;@@ -137,7 +142,11 @@ async function generateByImageMode(? {modelUsage: convertOpenAIImageUsage(img.usage,- await getModelPricing(imageOptions?.pricingModel ?? routingModel, provider),+ await getModelPricing(+ imageOptions?.pricingModel ?? routingModel,+ provider,+ imageOptions?.pricingContext,+ ),),}: {}),diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 4b0da82f3d4..c97b790009f 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -33,7 +33,11 @@ import type {} from '../../types';import type { ILobeAgentRuntimeErrorType } from '../../types/error';import { AgentRuntimeErrorType } from '../../types/error';-import type { CreateImagePayload, CreateImageResponse } from '../../types/image';+import type {+ CreateImageMethodOptions,+ CreateImagePayload,+ CreateImageResponse,+} from '../../types/image';import type {CreateVideoPayload,CreateVideoResponse,@@ -629,7 +633,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anapiMode: 'chat_completions',includeUsageRequested,model: payload.model,- pricing: await getModelPricing(payload.model, this.id),+ pricing: await getModelPricing(payload.model, this.id, options?.pricingContext),provider: this.id,},};@@ -751,7 +755,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an}}- async createImage(payload: CreateImagePayload) {+ async createImage(payload: CreateImagePayload, options?: CreateImageMethodOptions) {const log = debug(`${this.logPrefix}:createImage`);// If custom createImage implementation is provided, use it@@ -768,6 +772,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anlog('using default createOpenAICompatibleImage');// Use the new createOpenAICompatibleImage functionreturn createOpenAICompatibleImage(this.client, payload, this.id, {+ pricingContext: options?.pricingContext,pricingModel: payload.model,requestModel: resolveMappedModelId(payload.model, this.modelIdMappingOptions),routingModel: payload.model,@@ -976,7 +981,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an!!schema,);- const pricing = await getModelPricing(model, this.id);+ const pricing = await getModelPricing(model, this.id, options?.pricingContext);const usagePayload = { model, pricing, provider: this.id };if (tools) {@@ -1133,7 +1138,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an);if (res.usage && options?.onUsage) {- const pricing = await getModelPricing(payload.model, this.id);+ const pricing = await getModelPricing(payload.model, this.id, options?.pricingContext);await options.onUsage(convertOpenAIUsage(res.usage as any, {model: payload.model,@@ -1445,7 +1450,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anpayload: {apiMode: 'responses',model: usageModel,- pricing: await getModelPricing(usageModel, this.id),+ pricing: await getModelPricing(usageModel, this.id, options?.pricingContext),provider: this.id,},};diff --git a/packages/model-runtime/src/providers/azureOpenai/index.test.ts b/packages/model-runtime/src/providers/azureOpenai/index.test.tsindex fc7ce96bcc2..1cfb8e7a429 100644--- a/packages/model-runtime/src/providers/azureOpenai/index.test.ts+++ b/packages/model-runtime/src/providers/azureOpenai/index.test.ts@@ -229,7 +229,11 @@ describe('LobeAzureOpenAI', () => {expect(createCall.top_logprobs).toBeUndefined();expect(createCall.top_p).toBeUndefined();- expect(getModelPricingModule.getModelPricing).toHaveBeenCalledWith('o3', 'lobehub');+ expect(getModelPricingModule.getModelPricing).toHaveBeenCalledWith(+ 'o3',+ 'lobehub',+ undefined,+ );expect(streamsModule.OpenAIStream).toHaveBeenCalledWith(mockProdStream,expect.objectContaining({diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.tsindex d72e8950c57..b39b9c825bf 100644--- a/packages/model-runtime/src/providers/bedrock/index.ts+++ b/packages/model-runtime/src/providers/bedrock/index.ts@@ -178,7 +178,7 @@ export class LobeBedrockAI implements LobeRuntimeAI {try {const [res, pricing] = await Promise.all([this.client.send(command, { abortSignal: options?.signal }),- getModelPricing(payload.model, this.id),+ getModelPricing(payload.model, this.id, options?.pricingContext),]);const responseBody = JSON.parse(new TextDecoder().decode(res.body),@@ -353,7 +353,7 @@ export class LobeBedrockAI implements LobeRuntimeAI {debugStream(debug).catch(console.error);}- const pricing = await getModelPricing(payload.model, this.id);+ const pricing = await getModelPricing(payload.model, this.id, options?.pricingContext);const cacheTTL = resolveCacheTTL({ ...payload, enabledContextCaching }, anthropicBase);const pricingOptions = cacheTTL ? { lookupParams: { ttl: cacheTTL } } : undefined;diff --git a/packages/model-runtime/src/providers/githubCopilot/index.ts b/packages/model-runtime/src/providers/githubCopilot/index.tsindex 7fd72711113..67bd864d516 100644--- a/packages/model-runtime/src/providers/githubCopilot/index.ts+++ b/packages/model-runtime/src/providers/githubCopilot/index.ts@@ -223,7 +223,11 @@ export class LobeGithubCopilotAI implements LobeRuntimeAI {},);- const pricing = await getModelPricing(model, ModelProvider.GithubCopilot);+ const pricing = await getModelPricing(+ model,+ ModelProvider.GithubCopilot,+ options?.pricingContext,+ );const streamResponse = response as any;const [prod, useForDebug] = streamResponse.tee();diff --git a/packages/model-runtime/src/providers/google/createImage.test.ts b/packages/model-runtime/src/providers/google/createImage.test.tsindex 107dac83b1a..a9cf2f0eadd 100644--- a/packages/model-runtime/src/providers/google/createImage.test.ts+++ b/packages/model-runtime/src/providers/google/createImage.test.ts@@ -467,6 +467,7 @@ describe('createGoogleImage', () => {expect(getModelPricingMock).toHaveBeenCalledWith('gemini-3-pro-image-preview:image',provider,+ undefined,);expect(result.modelUsage).toMatchObject({cost: 0.178_04,diff --git a/packages/model-runtime/src/providers/google/createImage.ts b/packages/model-runtime/src/providers/google/createImage.tsindex 400c0006467..67b535e7536 100644--- a/packages/model-runtime/src/providers/google/createImage.ts+++ b/packages/model-runtime/src/providers/google/createImage.ts@@ -9,7 +9,11 @@ import { imageUrlToBase64 } from '@lobechat/utils';import { convertGoogleAIUsage } from '../../core/usageConverters/google-ai';import { AgentRuntimeErrorType } from '../../types/error';-import type { CreateImagePayload, CreateImageResponse } from '../../types/image';+import type {+ CreateImageMethodOptions,+ CreateImagePayload,+ CreateImageResponse,+} from '../../types/image';import { AgentRuntimeError } from '../../utils/createError';import { getModelPricing } from '../../utils/getModelPricing';import { parseGoogleErrorMessage } from '../../utils/googleErrorParser';@@ -84,6 +88,7 @@ interface GoogleImageErrorMetadata {}interface GoogleImageOptions {+ pricingContext?: CreateImageMethodOptions['pricingContext'];pricingModel?: string;routingModel?: string;}@@ -291,7 +296,7 @@ async function generateImageByChatModel(client: GoogleGenAI,payload: CreateImagePayload,provider: string,- options?: Pick<GoogleImageOptions, 'pricingModel'>,+ options?: Pick<GoogleImageOptions, 'pricingContext' | 'pricingModel'>,): Promise<CreateImageResponse> {const { model, params } = payload;const actualModel = model.replace(':image', '');@@ -355,7 +360,11 @@ async function generateImageByChatModel(const imageResponse = extractImageFromResponse(response);if (response.usageMetadata) {- const pricing = await getModelPricing(options?.pricingModel ?? model, provider);+ const pricing = await getModelPricing(+ options?.pricingModel ?? model,+ provider,+ options?.pricingContext,+ );imageResponse.modelUsage = convertGoogleAIUsage(response.usageMetadata, pricing);}diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.tsindex ade95a94ae3..678317843dc 100644--- a/packages/model-runtime/src/providers/google/index.test.ts+++ b/packages/model-runtime/src/providers/google/index.test.ts@@ -80,7 +80,7 @@ describe('LobeGoogleAI', () => {const callArgs = (mappedInstance['client'].models.generateContentStream as any).mock.calls[0];expect(callArgs[0].model).toBe('gemini-upstream');- expect(getModelPricingMock).toHaveBeenCalledWith('gemini-logical', provider);+ expect(getModelPricingMock).toHaveBeenCalledWith('gemini-logical', provider, undefined);});it('should handle text messages correctly', async () => {@@ -1127,7 +1127,7 @@ describe('modelIdMapping', () => {expect(result.imageUrl).toBe('data:image/png;base64,image-base64');expect(generateContentMock.mock.calls[0][0].model).toBe('gemini-upstream-image');- expect(getModelPricingMock).toHaveBeenCalledWith('gemini-logical:image', provider);+ expect(getModelPricingMock).toHaveBeenCalledWith('gemini-logical:image', provider, undefined);});it('should use mapped model id for upstream generateObject requests while keeping pricing on logical model', async () => {@@ -1157,7 +1157,7 @@ describe('modelIdMapping', () => {expect(result).toEqual({ ok: true });expect(generateContentMock.mock.calls[0][0].model).toBe('gemini-upstream');- expect(getModelPricingMock).toHaveBeenCalledWith('gemini-logical', provider);+ expect(getModelPricingMock).toHaveBeenCalledWith('gemini-logical', provider, undefined);});});diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.tsindex 9d05170ac2c..17f0edf9354 100644--- a/packages/model-runtime/src/providers/google/index.ts+++ b/packages/model-runtime/src/providers/google/index.ts@@ -7,23 +7,24 @@ import type {import { GoogleGenAI } from '@google/genai';import debug from 'debug';-import { type LobeRuntimeAI } from '../../core/BaseAI';+import type { LobeRuntimeAI } from '../../core/BaseAI';import { buildGoogleMessages, buildGoogleTools } from '../../core/contextBuilders/google';import { GoogleGenerativeAIStream } from '../../core/streams';import { LOBE_ERROR_KEY } from '../../core/streams/google';-import {- type ASROptions,- type ASRPayload,- type ASRResponse,- type ChatCompletionTool,- type ChatMethodOptions,- type ChatStreamPayload,- type GenerateObjectOptions,- type GenerateObjectPayload,+import type {+ ASROptions,+ ASRPayload,+ ASRResponse,+ ChatCompletionTool,+ ChatMethodOptions,+ ChatStreamPayload,+ CreateImageMethodOptions,+ GenerateObjectOptions,+ GenerateObjectPayload,} from '../../types';import { AgentRuntimeErrorType } from '../../types/error';-import { type CreateImagePayload, type CreateImageResponse } from '../../types/image';-import { type CreateVideoPayload, type CreateVideoResponse } from '../../types/video';+import type { CreateImagePayload, CreateImageResponse } from '../../types/image';+import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';import { AgentRuntimeError } from '../../utils/createError';import { debugStream } from '../../utils/debugStream';import { getModelPricing } from '../../utils/getModelPricing';@@ -241,7 +242,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {}// Convert the response into a friendly text-stream- const pricing = await getModelPricing(model, this.provider);+ const pricing = await getModelPricing(model, this.provider, options?.pricingContext);const stream = GoogleGenerativeAIStream(prod, {callbacks: options?.callback,@@ -275,10 +276,14 @@ export class LobeGoogleAI implements LobeRuntimeAI {* Generate images using Google AI Imagen API or Gemini Chat Models* @see https://ai.google.dev/gemini-api/docs/image-generation#imagen*/- async createImage(payload: CreateImagePayload): Promise<CreateImageResponse> {+ async createImage(+ payload: CreateImagePayload,+ options?: CreateImageMethodOptions,+ ): Promise<CreateImageResponse> {const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);return createGoogleImage(this.client, this.provider, requestPayload, {+ pricingContext: options?.pricingContext,pricingModel: payload.model,routingModel: payload.model,});@@ -334,7 +339,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {// Convert OpenAI messages to Google formatconst contents = await buildGoogleMessages(payload.messages, { model: payload.model });- const pricing = await getModelPricing(payload.model, this.provider);+ const pricing = await getModelPricing(payload.model, this.provider, options?.pricingContext);const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);// Handle tools-based structured outputdiff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.tsindex 9d3ba984204..a96357b3a42 100644--- a/packages/model-runtime/src/types/chat.ts+++ b/packages/model-runtime/src/types/chat.ts@@ -1,5 +1,6 @@import type { ModelPerformance, ModelTokensUsage, ModelUsage } from '@lobechat/types';+import type { ModelPricingContext } from './pricing';import type { MessageToolCall, MessageToolCallChunk } from './toolsCalling';export type LLMRoleType = 'user' | 'system' | 'assistant' | 'function' | 'tool';@@ -187,6 +188,8 @@ export interface ChatMethodOptions {headers?: Record<string, any>;/** Metadata passed to hooks (billing, tracing, etc.) */metadata?: Record<string, unknown>;+ /** Request-scoped pricing context for model-bank pricing lookups. */+ pricingContext?: ModelPricingContext;/*** send the request to the ai api endpoint*/diff --git a/packages/model-runtime/src/types/embeddings.ts b/packages/model-runtime/src/types/embeddings.tsindex e4ee7b3dd3d..b2d805ac467 100644--- a/packages/model-runtime/src/types/embeddings.ts+++ b/packages/model-runtime/src/types/embeddings.ts@@ -1,5 +1,7 @@import type { ModelUsage } from '@lobechat/types';+import type { ModelPricingContext } from './pricing';+export interface EmbeddingsPayload {/*** The number of dimensions the resulting output embeddings should have. Only@@ -23,6 +25,8 @@ export interface EmbeddingsOptions {/** Metadata passed to hooks (billing, tracing, etc.) */metadata?: Record<string, unknown>;onUsage?: (usage: ModelUsage) => void | Promise<void>;+ /** Request-scoped pricing context for model-bank pricing lookups. */+ pricingContext?: ModelPricingContext;signal?: AbortSignal;/*** userId for the embeddingsdiff --git a/packages/model-runtime/src/types/image.ts b/packages/model-runtime/src/types/image.tsindex 24a7b53fef9..6f326d09fe7 100644--- a/packages/model-runtime/src/types/image.ts+++ b/packages/model-runtime/src/types/image.ts@@ -1,6 +1,8 @@import type { ModelUsage } from '@lobechat/types';import type { RuntimeImageGenParams } from 'model-bank';+import type { ModelPricingContext } from './pricing';+export type CreateImagePayload = {model: string;params: RuntimeImageGenParams;@@ -9,6 +11,8 @@ export type CreateImagePayload = {export interface CreateImageMethodOptions {/** Metadata passed to hooks (billing, tracing, etc.) */metadata?: Record<string, unknown>;+ /** Request-scoped pricing context for model-bank pricing lookups. */+ pricingContext?: ModelPricingContext;}/**diff --git a/packages/model-runtime/src/types/index.ts b/packages/model-runtime/src/types/index.tsindex a1063db0914..cd2bebf3151 100644--- a/packages/model-runtime/src/types/index.ts+++ b/packages/model-runtime/src/types/index.ts@@ -4,6 +4,7 @@ export * from './embeddings';export * from './error';export * from './image';export * from './model';+export * from './pricing';export * from './structureOutput';export * from './toolsCalling';export * from './tts';diff --git a/packages/model-runtime/src/types/pricing.ts b/packages/model-runtime/src/types/pricing.tsnew file mode 100644index 00000000000..2be5e936f43--- /dev/null+++ b/packages/model-runtime/src/types/pricing.ts@@ -0,0 +1,4 @@+export interface ModelPricingContext {+ plan: string;+ scope: 'personal';+}diff --git a/packages/model-runtime/src/types/structureOutput.ts b/packages/model-runtime/src/types/structureOutput.tsindex 1f54734e8b4..a0f4504bc69 100644--- a/packages/model-runtime/src/types/structureOutput.ts+++ b/packages/model-runtime/src/types/structureOutput.ts@@ -1,6 +1,7 @@import type { ModelUsage } from '@lobechat/types';import type { ChatCompletionTool, ChatStreamPayload } from './chat';+import type { ModelPricingContext } from './pricing';interface GenerateObjectMessage {content: string;@@ -41,6 +42,9 @@ export interface GenerateObjectOptions {onUsage?: (usage: ModelUsage) => void | Promise<void>;+ /** Request-scoped pricing context for model-bank pricing lookups. */+ pricingContext?: ModelPricingContext;+signal?: AbortSignal;/*** Structured tracing config consumed by tracing hooks (e.g.diff --git a/packages/model-runtime/src/types/video.ts b/packages/model-runtime/src/types/video.tsindex 07c821d002e..e5b97cf2182 100644--- a/packages/model-runtime/src/types/video.ts+++ b/packages/model-runtime/src/types/video.ts@@ -1,5 +1,7 @@import type { RuntimeVideoGenParams } from 'model-bank';+import type { ModelPricingContext } from './pricing';+export type CreateVideoErrorPayload = {error: any;errorType: string;@@ -15,6 +17,8 @@ export type CreateVideoPayload = {export interface CreateVideoMethodOptions {/** Metadata passed to hooks (billing, tracing, etc.) */metadata?: Record<string, unknown>;+ /** Request-scoped pricing context for model-bank pricing lookups. */+ pricingContext?: ModelPricingContext;}export type CreateVideoResponse =diff --git a/packages/model-runtime/src/utils/getModelPricing.test.ts b/packages/model-runtime/src/utils/getModelPricing.test.tsindex 408001fcfa6..425c5df496c 100644--- a/packages/model-runtime/src/utils/getModelPricing.test.ts+++ b/packages/model-runtime/src/utils/getModelPricing.test.ts@@ -69,4 +69,12 @@ describe('getModelPricing', () => {units: [{ name: 'textInput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' }],});});++ it('should pass explicit pricing context to loadModels', async () => {+ await getModelPricing('gpt-4o', 'openai', { plan: 'premium', scope: 'personal' });++ expect(loadModelsMock).toHaveBeenCalledWith({+ pricingContext: { plan: 'premium', scope: 'personal' },+ });+ });});diff --git a/packages/model-runtime/src/utils/getModelPricing.ts b/packages/model-runtime/src/utils/getModelPricing.tsindex b4ff24988f1..f9d79d9fa8a 100644--- a/packages/model-runtime/src/utils/getModelPricing.ts+++ b/packages/model-runtime/src/utils/getModelPricing.ts@@ -1,7 +1,11 @@import type { LobeDefaultAiModelListItem, Pricing } from 'model-bank';+import type { ModelPricingContext } from '../types';+interface BusinessModelConfigModule {- loadModels: () => Promise<LobeDefaultAiModelListItem[]>;+ loadModels: (options?: {+ pricingContext?: ModelPricingContext;+ }) => Promise<LobeDefaultAiModelListItem[]>;}/**@@ -14,10 +18,11 @@ interface BusinessModelConfigModule {export async function getModelPricing(model: string,provider?: string,+ pricingContext?: ModelPricingContext,): Promise<Pricing | undefined> {const { loadModels } =(await import('@lobechat/business-model-bank/model-config')) as BusinessModelConfigModule;- const models = await loadModels();+ const models = await loadModels(pricingContext ? { pricingContext } : undefined);// 1. First try to get pricing from the specified providerif (provider) {diff --git a/packages/utils/src/pricing.test.ts b/packages/utils/src/pricing.test.tsindex 643093d7f22..ab6bab9f788 100644--- a/packages/utils/src/pricing.test.ts+++ b/packages/utils/src/pricing.test.ts@@ -164,17 +164,21 @@ describe('pricing utilities (new)', () => {expect(getOriginalUnitRateByName(pricing, 'textOutput')).toBeUndefined();});- it('returns undefined for non-fixed pricing units', () => {+ it('returns tiered and lookup original prices when they are higher than current rates', () => {const pricing: Pricing = {units: [{name: 'textInput',strategy: 'tiered',- tiers: [{ rate: 0.1, upTo: 'infinity' }],+ tiers: [{ originalRate: 0.2, rate: 0.1, upTo: 'infinity' }],unit: 'millionTokens',},{- lookup: { prices: { default: 0.2 }, pricingParams: ['quality'] },+ lookup: {+ originalPrices: { default: 0.4 },+ prices: { default: 0.2 },+ pricingParams: ['quality'],+ },name: 'textOutput',strategy: 'lookup',unit: 'millionTokens',@@ -182,8 +186,8 @@ describe('pricing utilities (new)', () => {],};- expect(getOriginalUnitRateByName(pricing, 'textInput')).toBeUndefined();- expect(getOriginalUnitRateByName(pricing, 'textOutput')).toBeUndefined();+ expect(getOriginalUnitRateByName(pricing, 'textInput')).toBe(0.2);+ expect(getOriginalUnitRateByName(pricing, 'textOutput')).toBe(0.4);});});diff --git a/packages/utils/src/pricing.ts b/packages/utils/src/pricing.tsindex f88c962f249..944fd17e82f 100644--- a/packages/utils/src/pricing.ts+++ b/packages/utils/src/pricing.ts@@ -25,9 +25,21 @@ const getRateFromUnit = (unit: PricingUnit): number | undefined => {};const getOriginalRateFromUnit = (unit: PricingUnit): number | undefined => {- if (unit.strategy !== 'fixed') return undefined;-- return unit.originalRate;+ switch (unit.strategy) {+ case 'fixed': {+ return unit.originalRate;+ }+ case 'tiered': {+ return unit.tiers?.[0]?.originalRate;+ }+ case 'lookup': {+ const firstKey = Object.keys(unit.lookup?.prices || {})[0];+ return firstKey ? unit.lookup.originalPrices?.[firstKey] : undefined;+ }+ default: {+ return undefined;+ }+ }};/**@@ -44,7 +56,7 @@ export const getUnitRateByName = (};/**- * Get fixed unit original rate by unit name when it is higher than the current rate.+ * Get unit original rate by unit name when it is higher than the current rate.*/export const getOriginalUnitRateByName = (pricing?: Pricing,diff --git a/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsx b/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsxindex ebbf9f40968..21002b0b248 100644--- a/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsx+++ b/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsx@@ -115,6 +115,25 @@ const imagePricing = {units: [{ name: 'imageGeneration', rate: 0.04, strategy: 'fixed', unit: 'image' }],};+const emptyLookupPricing = {+ currency: 'USD',+ units: [+ {+ lookup: { prices: {} },+ name: 'imageGeneration',+ strategy: 'lookup',+ unit: 'image',+ },+ ],+};++const discountedTextPricing = {+ currency: 'USD',+ units: [+ { name: 'textInput', originalRate: 5, rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },+ ],+};+const createEnabledList = (provider: string,pricing: Record<string, unknown>,@@ -151,6 +170,22 @@ describe('ModelDetailPanel pricing', () => {expect(container).not.toHaveTextContent('$5.00');});+ it('renders the original branding price without repeating the unit suffix', () => {+ const { container } = render(+ <ModelDetailPanel+ enabledList={createEnabledList('lobehub', discountedTextPricing)}+ model="test-model"+ provider="lobehub"+ />,+ );++ const originalPrice = container.querySelector('.originalPriceText');++ expect(originalPrice).toHaveTextContent('5M');+ expect(originalPrice).not.toHaveTextContent('credits/M tokens');+ expect(container).toHaveTextContent('2.5M credits/M tokens');+ });+it('keeps dollar pricing for non-branding providers', () => {const { container } = render(<ModelDetailPanel@@ -193,4 +228,17 @@ describe('ModelDetailPanel pricing', () => {expect(videoResult.container).toHaveTextContent('~ 800.0K credits / video');expect(videoResult.container).not.toHaveTextContent('$0.80');});++ it('renders a placeholder for empty lookup pricing tables', () => {+ const { container } = render(+ <ModelDetailPanel+ enabledList={createEnabledList('lobehub', emptyLookupPricing)}+ model="test-model"+ provider="lobehub"+ />,+ );++ expect(container).toHaveTextContent('Image Generation');+ expect(container).toHaveTextContent('- credits/img');+ });});diff --git a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsxindex 86f5844426e..13e24fbace9 100644--- a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx+++ b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx@@ -1,46 +1,17 @@-import { BRANDING_PROVIDER } from '@lobechat/business-const';-import { getCachedTextInputUnitRate } from '@lobechat/utils';import { Accordion, AccordionItem, Flexbox, Icon, Tag, Tooltip } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';-import type { LucideIcon } from 'lucide-react';-import {- ArrowDownToDot,- ArrowUpFromDot,- AtomIcon,- AudioLinesIcon,- CircleFadingArrowUp,- EyeIcon,- GlobeIcon,- ImageIcon,- PaperclipIcon,- VideoIcon,- WrenchIcon,-} from 'lucide-react';-import type {- FixedPricingUnit,- ModelPriceCurrency,- Pricing,- PricingUnit,- PricingUnitName,- TieredPricingUnit,-} from 'model-bank';+import { ArrowDownToDot, ArrowUpFromDot, CircleFadingArrowUp } from 'lucide-react';import type { FC } from 'react';-import { memo, useMemo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useBusinessModelPricing } from '@/business/client/hooks/useBusinessModelPricing';-import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';-import { useGlobalStore } from '@/store/global';-import type { ModelDetailPanelExpandedKey } from '@/store/global/initialState';-import { systemStatusSelectors } from '@/store/global/selectors';import type { EnabledProviderWithModels } from '@/types/aiProvider';-import { formatNumber, formatShortenNumber, formatTokenNumber } from '@/utils/format';-import {- formatPriceByCurrency,- getOriginalUnitRateByName,- getTextInputUnitRate,- getTextOutputUnitRate,-} from '@/utils/index';++import type { FormattedUnitPrice } from '../hooks/useModelDetailPanel';+import { UNIT_ICON_MAP, useModelDetailPanel } from '../hooks/useModelDetailPanel';+import type { PricingMode } from '../types';++export type { PricingMode } from '../types';const styles = createStaticStyles(({ css, cssVar }) => ({actionText: css`@@ -73,134 +44,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-interface FormattedUnitPrice {- current: string;- original?: string;-}--const BRANDING_CREDIT_UNIT = 1_000_000;-const MILLION_SCALE_UNITS = new Set<PricingUnit['unit']>(['millionCharacters', 'millionTokens']);--interface FormatPricingRateOptions {- isCreditPricing?: boolean;- unit?: PricingUnit['unit'];-}--const formatBrandingCreditRate = (rate: number, unit?: PricingUnit['unit']) => {- if (unit && MILLION_SCALE_UNITS.has(unit)) return `${formatNumber(rate)}M`;-- return String(formatShortenNumber(Math.round(rate * BRANDING_CREDIT_UNIT)));-};--const formatPricingRate = (- rate: number | undefined,- currency?: ModelPriceCurrency,- options: FormatPricingRateOptions = {},-) => {- if (typeof rate !== 'number') return '0';-- return options.isCreditPricing- ? formatBrandingCreditRate(rate, options.unit)- : formatPriceByCurrency(rate, currency);-};--const getFormattedUnitPrice = (- pricing: Pricing,- unitName: PricingUnitName,- isCreditPricing: boolean,-): FormattedUnitPrice => {- const currency = pricing.currency as ModelPriceCurrency | undefined;- const currentRate =- unitName === 'textInput'- ? getTextInputUnitRate(pricing)- : unitName === 'textOutput'- ? getTextOutputUnitRate(pricing)- : getCachedTextInputUnitRate(pricing);- const originalRate = getOriginalUnitRateByName(pricing, unitName);-- return {- current: formatPricingRate(currentRate, currency, {- isCreditPricing,- unit: 'millionTokens',- }),- original:- typeof originalRate === 'number'- ? formatPricingRate(originalRate, currency, {- isCreditPricing,- unit: 'millionTokens',- })- : undefined,- };-};--const getPrice = (pricing: Pricing, isCreditPricing: boolean) => {- return {- cachedInput: getFormattedUnitPrice(pricing, 'textInput_cacheRead', isCreditPricing),- input: getFormattedUnitPrice(pricing, 'textInput', isCreditPricing),- output: getFormattedUnitPrice(pricing, 'textOutput', isCreditPricing),- };-};--// --- Pricing detail helpers -----type PricingGroup = 'audio' | 'image' | 'text' | 'video';--const UNIT_GROUP_MAP: Record<PricingUnitName, PricingGroup> = {- audioInput: 'audio',- audioInput_cacheRead: 'audio',- audioOutput: 'audio',- imageGeneration: 'image',- imageInput: 'image',- imageInput_cacheRead: 'image',- imageOutput: 'image',- textInput: 'text',- textInput_cacheRead: 'text',- textInput_cacheWrite: 'text',- textOutput: 'text',- videoInput: 'video',- videoGeneration: 'video',-};--const GROUP_ORDER: PricingGroup[] = ['text', 'image', 'audio', 'video'];--const UNIT_ICON_MAP: Partial<Record<PricingUnitName, LucideIcon>> = {- audioInput: ArrowUpFromDot,- audioInput_cacheRead: CircleFadingArrowUp,- audioOutput: ArrowDownToDot,- imageGeneration: ImageIcon,- imageInput: ArrowUpFromDot,- imageInput_cacheRead: CircleFadingArrowUp,- imageOutput: ArrowDownToDot,- textInput: ArrowUpFromDot,- textInput_cacheRead: CircleFadingArrowUp,- textInput_cacheWrite: CircleFadingArrowUp,- textOutput: ArrowDownToDot,-};--const UNIT_SORT_ORDER: Record<PricingUnitName, number> = {- textInput: 0,- textOutput: 1,- textInput_cacheRead: 2,- textInput_cacheWrite: 3,- imageInput: 0,- imageOutput: 1,- imageInput_cacheRead: 2,- imageGeneration: 3,- audioInput: 0,- audioOutput: 1,- audioInput_cacheRead: 2,- videoInput: 0,- videoGeneration: 1,-};--const UNIT_LABEL_MAP: Record<string, string> = {- image: '/img',- megapixel: '/MP',- millionCharacters: '/M chars',- millionTokens: '/M tokens',- second: '/s',-};-interface PriceValueProps {prefix?: string;price: FormattedUnitPrice;@@ -213,7 +56,6 @@ const PriceValue: FC<PriceValueProps> = ({ price, prefix = '', suffix = '' }) =><span className={styles.originalPriceText}>{prefix}{price.original}- {suffix}</span>)}<span>@@ -224,92 +66,6 @@ const PriceValue: FC<PriceValueProps> = ({ price, prefix = '', suffix = '' }) =></span>);-const formatUnitRate = (- unit: PricingUnit,- currency?: ModelPriceCurrency,- isCreditPricing?: boolean,-): FormattedUnitPrice => {- const formatRate = (rate: number) =>- formatPricingRate(rate, currency, { isCreditPricing, unit: unit.unit });- const formatRange = (low: string, high: string) =>- isCreditPricing ? `${low} ~ ${high}` : `${low} ~ $${high}`;-- if (unit.strategy === 'fixed') {- const fixedUnit = unit as FixedPricingUnit;- return {- current: formatRate(fixedUnit.rate),- original:- typeof fixedUnit.originalRate === 'number' && fixedUnit.originalRate > fixedUnit.rate- ? formatRate(fixedUnit.originalRate)- : undefined,- };- }-- if (unit.strategy === 'tiered') {- const tiers = (unit as TieredPricingUnit).tiers;- if (tiers.length === 1) {- const price = formatRate(tiers[0].rate);- return { current: price };- }- const low = formatRate(tiers[0].rate);- const high = formatRate(tiers.at(-1)!.rate);- return { current: formatRange(low, high) };- }-- // lookup strategy- if (unit.strategy === 'lookup') {- const prices = Object.values(unit.lookup.prices);- if (prices.length === 1) {- const price = formatRate(prices[0]);- return { current: price };- }- const sorted = [...prices].sort((a, b) => a - b);- const low = formatRate(sorted[0]);- const high = formatRate(sorted.at(-1)!);- return { current: formatRange(low, high) };- }-- return { current: '-' };-};--interface PricingGroupData {- group: PricingGroup;- units: PricingUnit[];-}--const groupPricingUnits = (units: PricingUnit[]): PricingGroupData[] => {- const map = new Map<PricingGroup, PricingUnit[]>();- for (const unit of units) {- const group = UNIT_GROUP_MAP[unit.name] || 'text';- const arr = map.get(group) || [];- arr.push(unit);- map.set(group, arr);- }- for (const [, arr] of map) {- arr.sort((a, b) => (UNIT_SORT_ORDER[a.name] ?? 99) - (UNIT_SORT_ORDER[b.name] ?? 99));- }- return GROUP_ORDER.filter((g) => map.has(g)).map((g) => ({ group: g, units: map.get(g)! }));-};--interface AbilityItem {- color: string;- icon: LucideIcon;- key: string;-}--const ABILITY_CONFIG: AbilityItem[] = [- { color: 'success', icon: EyeIcon, key: 'vision' },- { color: 'success', icon: PaperclipIcon, key: 'files' },- { color: 'success', icon: ImageIcon, key: 'imageOutput' },- { color: 'magenta', icon: VideoIcon, key: 'video' },- { color: 'gold', icon: AudioLinesIcon, key: 'audio' },- { color: 'info', icon: WrenchIcon, key: 'functionCall' },- { color: 'purple', icon: AtomIcon, key: 'reasoning' },- { color: 'cyan', icon: GlobeIcon, key: 'search' },-];--export type PricingMode = 'image' | 'video';-interface ModelDetailPanelProps {enabledList?: EnabledProviderWithModels[];model?: string;@@ -320,121 +76,49 @@ interface ModelDetailPanelProps {const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(({ model: modelId, provider, enabledList: enabledListProp, pricingMode }) => {const { t } = useTranslation('components');-- const enabledListFromHook = useEnabledChatModels();- const enabledList = enabledListProp ?? enabledListFromHook;- const model = useMemo(() => {- if (!modelId || !provider) return undefined;- const providerData = enabledList.find((p) => p.id === provider);- return providerData?.children.find((m) => m.id === modelId);- }, [enabledList, modelId, provider]);-- const expandedKeys = useGlobalStore(systemStatusSelectors.modelDetailPanelExpandedKeys);- const updateExpandedKeys = useGlobalStore((s) => s.updateModelDetailPanelExpandedKeys);- const applyBusinessModelPricing = useBusinessModelPricing();-- const pricing = model?.pricing;- const displayPricing = useMemo(- () => applyBusinessModelPricing({ model: modelId, pricing, provider }),- [applyBusinessModelPricing, modelId, pricing, provider],- );- const isCreditPricing = provider === BRANDING_PROVIDER;- const hasPricing = !!displayPricing;- const formatPrice = displayPricing ? getPrice(displayPricing, isCreditPricing) : null;- const pricingGroups = useMemo(- () => (displayPricing ? groupPricingUnits(displayPricing.units) : []),- [displayPricing],- );-- const approximatePriceLabel = useMemo(() => {- if (!displayPricing || !pricingMode) return null;- const currency = displayPricing.currency as ModelPriceCurrency | undefined;- if (pricingMode === 'image' && typeof displayPricing.approximatePricePerImage === 'number') {- const amount = isCreditPricing- ? formatBrandingCreditRate(displayPricing.approximatePricePerImage, 'image')- : formatPriceByCurrency(displayPricing.approximatePricePerImage, currency);- return t(- isCreditPricing- ? 'ModelSwitchPanel.detail.pricing.credits.perImage'- : 'ModelSwitchPanel.detail.pricing.perImage',- {- amount,- defaultValue: isCreditPricing- ? '~ {{amount}} credits / image'- : '~ ${{amount}} / image',- },- );- }- if (pricingMode === 'video' && typeof displayPricing.approximatePricePerVideo === 'number') {- const amount = isCreditPricing- ? formatBrandingCreditRate(displayPricing.approximatePricePerVideo)- : formatPriceByCurrency(displayPricing.approximatePricePerVideo, currency);- return t(- isCreditPricing- ? 'ModelSwitchPanel.detail.pricing.credits.perVideo'- : 'ModelSwitchPanel.detail.pricing.perVideo',- {- amount,- defaultValue: isCreditPricing- ? '~ {{amount}} credits / video'- : '~ ${{amount}} / video',- },- );- }- return null;- }, [displayPricing, isCreditPricing, pricingMode, t]);-- const getCreditsUnitLabel = (unit: PricingUnit['unit']) =>- t(`ModelSwitchPanel.detail.pricing.credits.${unit}` as any, {- defaultValue: `credits${UNIT_LABEL_MAP[unit] || ''}`,- });-- const getPricingTooltip = (key: 'cachedInput' | 'input' | 'output', amount: string): string => {- if (isCreditPricing) {- return t(`ModelSwitchPanel.detail.pricing.credits.${key}` as any, { amount });- }-- const fallbackKey =- key === 'cachedInput'- ? 'ModelSwitchPanel.detail.pricing.cachedInput'- : `ModelSwitchPanel.detail.pricing.${key}`;-- return t(fallbackKey as any, { amount });- };+ const {+ approximatePriceLabel,+ contextWindowLabel,+ enabledAbilities,+ expandedKeys,+ formatPrice,+ formatUnitPrice,+ getPricingTooltip,+ getUnitPriceSuffix,+ handleExpandedChange,+ hasAbilities,+ hasCachedInputPricing,+ hasPricing,+ isAbilitiesExpanded,+ isCreditPricing,+ isPricingExpanded,+ model,+ pricingGroups,+ } = useModelDetailPanel({+ enabledList: enabledListProp,+ modelId,+ pricingMode,+ provider,+ t,+ });if (!model) return null;- const hasContext = typeof model.contextWindowTokens === 'number';- const enabledAbilities = ABILITY_CONFIG.filter(- (a) => model.abilities[a.key as keyof typeof model.abilities],- );- const hasAbilities = enabledAbilities.length > 0;-return (<Flexbox className={styles.container}>{/* Sections */}- {(hasPricing || hasContext || hasAbilities) && (- <Accordion- expandedKeys={expandedKeys}- gap={8}- onExpandedChange={(keys) => updateExpandedKeys(keys as ModelDetailPanelExpandedKey[])}- >+ {(hasPricing || contextWindowLabel || hasAbilities) && (+ <Accordion expandedKeys={expandedKeys} gap={8} onExpandedChange={handleExpandedChange}>{/* Context Length */}- {hasContext && (+ {contextWindowLabel && (<AccordionItemalwaysShowActionhideIndicator+ action={<span className={styles.actionText}>{contextWindowLabel}</span>}allowExpand={false}itemKey="context"paddingBlock={6}paddingInline={8}- action={- <span className={styles.actionText}>- {model.contextWindowTokens === 0- ? '∞'- : `${formatTokenNumber(model.contextWindowTokens!)} tokens`}- </span>- }title={<Flexbox horizontal align={'center'} gap={8}><div@@ -460,7 +144,7 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(paddingBlock={6}paddingInline={8}action={- !expandedKeys.includes('abilities') && (+ !isAbilitiesExpanded && (<Flexbox horizontal gap={2}>{enabledAbilities.map((ability) => (<Tag@@ -523,12 +207,12 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(paddingBlock={6}paddingInline={8}action={- !expandedKeys.includes('pricing') &&+ !isPricingExpanded &&(approximatePriceLabel ? (<span className={styles.actionText}>{approximatePriceLabel}</span>) : (<Flexbox horizontal align={'center'} className={styles.actionText} gap={8}>- {getCachedTextInputUnitRate(displayPricing) && (+ {hasCachedInputPricing && (<Tooltiptitle={getPricingTooltip('cachedInput', formatPrice!.cachedInput.current)}>@@ -599,16 +283,8 @@ const ModelDetailPanel: FC<ModelDetailPanelProps> = memo(</Flexbox><PriceValueprefix={isCreditPricing ? '' : '$'}- price={formatUnitRate(- unit,- displayPricing.currency as ModelPriceCurrency,- isCreditPricing,- )}- suffix={- isCreditPricing- ? ` ${getCreditsUnitLabel(unit.unit)}`- : UNIT_LABEL_MAP[unit.unit] || ''- }+ price={formatUnitPrice(unit)}+ suffix={getUnitPriceSuffix(unit.unit)}/></Flexbox>))}diff --git a/src/features/ModelSwitchPanel/hooks/useModelDetailPanel.test.ts b/src/features/ModelSwitchPanel/hooks/useModelDetailPanel.test.tsnew file mode 100644index 00000000000..c2e36d14dab--- /dev/null+++ b/src/features/ModelSwitchPanel/hooks/useModelDetailPanel.test.ts@@ -0,0 +1,206 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import type { TFunction } from 'i18next';+import type { Pricing } from 'model-bank';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { EnabledProviderWithModels } from '@/types/aiProvider';++import { useModelDetailPanel } from './useModelDetailPanel';++const {+ globalState,+ updateExpandedKeysMock,+ useBusinessModelPricingMock,+ useEnabledChatModelsMock,+} = vi.hoisted(() => ({+ globalState: {+ status: {+ modelDetailPanelExpandedKeys: ['pricing'],+ },+ updateModelDetailPanelExpandedKeys: vi.fn(),+ },+ updateExpandedKeysMock: vi.fn(),+ useBusinessModelPricingMock: vi.fn(),+ useEnabledChatModelsMock: vi.fn(),+}));++vi.mock('@/hooks/useEnabledChatModels', () => ({+ useEnabledChatModels: useEnabledChatModelsMock,+}));++vi.mock('@/business/client/hooks/useBusinessModelPricing', () => ({+ useBusinessModelPricing: useBusinessModelPricingMock,+}));++vi.mock('@/store/global', () => ({+ useGlobalStore: (selector: (state: typeof globalState) => unknown) => selector(globalState),+}));++vi.mock('@/store/global/selectors', () => ({+ systemStatusSelectors: {+ modelDetailPanelExpandedKeys: (state: typeof globalState) =>+ state.status.modelDetailPanelExpandedKeys,+ },+}));++const translations: Record<string, string> = {+ 'ModelSwitchPanel.detail.pricing.credits.input': 'Input {{amount}} credits/M tokens',+ 'ModelSwitchPanel.detail.pricing.credits.millionTokens': 'credits/M tokens',+ 'ModelSwitchPanel.detail.pricing.credits.output': 'Output {{amount}} credits/M tokens',+ 'ModelSwitchPanel.detail.pricing.credits.perImage': '~ {{amount}} credits / image',+ 'ModelSwitchPanel.detail.pricing.credits.perVideo': '~ {{amount}} credits / video',+};++const t = ((key: string, options?: Record<string, string>) => {+ const template = translations[key] ?? options?.defaultValue ?? key;++ return template.replaceAll(/\{\{(\w+)\}\}/g, (_, name) => options?.[name] ?? '');+}) as TFunction<'components'>;++const basePricing = {+ currency: 'USD',+ units: [+ { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 25, strategy: 'fixed', unit: 'millionTokens' },+ ],+} as Pricing;++const discountedPricing = {+ currency: 'USD',+ units: [+ { name: 'textInput', originalRate: 5, rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', originalRate: 25, rate: 12.5, strategy: 'fixed', unit: 'millionTokens' },+ {+ name: 'textInput_cacheRead',+ originalRate: 1,+ rate: 0.3,+ strategy: 'fixed',+ unit: 'millionTokens',+ },+ ],+} as Pricing;++const unitPricing = {+ currency: 'USD',+ units: [+ {+ name: 'imageGeneration',+ strategy: 'tiered',+ tiers: [{ originalRate: 0.05, rate: 0.02, upTo: 'infinity' }],+ unit: 'image',+ },+ {+ lookup: { originalPrices: { standard: 0.5 }, prices: { standard: 0.3 } },+ name: 'videoGeneration',+ strategy: 'lookup',+ unit: 'video',+ },+ ],+} as Pricing;++const createEnabledList = (+ provider: string,+ pricing: Pricing,+ overrides: Record<string, unknown> = {},+): EnabledProviderWithModels[] => [+ {+ children: [+ {+ abilities: {},+ contextWindowTokens: 1_000_000,+ displayName: 'Test Model',+ id: 'test-model',+ pricing,+ type: 'chat',+ ...overrides,+ } as any,+ ],+ id: provider,+ name: provider,+ source: 'builtin',+ },+];++const renderModelDetailPanelHook = (+ params: Partial<Parameters<typeof useModelDetailPanel>[0]> = {},+) =>+ renderHook(() =>+ useModelDetailPanel({+ enabledList: createEnabledList('lobehub', basePricing),+ modelId: 'test-model',+ provider: 'lobehub',+ t,+ ...params,+ }),+ );++describe('useModelDetailPanel', () => {+ beforeEach(() => {+ globalState.status.modelDetailPanelExpandedKeys = ['pricing'];+ globalState.updateModelDetailPanelExpandedKeys = updateExpandedKeysMock;+ updateExpandedKeysMock.mockReset();+ useEnabledChatModelsMock.mockReturnValue([]);+ useBusinessModelPricingMock.mockReturnValue(({ pricing }: { pricing?: Pricing }) => pricing);+ });++ it('applies business pricing before formatting LobeHub credit prices', () => {+ useBusinessModelPricingMock.mockReturnValue(+ ({ pricing, model, provider }: { model?: string; pricing?: Pricing; provider?: string }) =>+ provider === 'lobehub' && model === 'test-model' ? discountedPricing : pricing,+ );++ const { result } = renderModelDetailPanelHook();++ expect(result.current.isCreditPricing).toBe(true);+ expect(result.current.formatPrice?.input).toEqual({ current: '2.5M', original: '5M' });+ expect(result.current.formatPrice?.output).toEqual({ current: '12.5M', original: '25M' });+ expect(result.current.formatPrice?.cachedInput).toEqual({+ current: '0.3M',+ original: '1M',+ });+ expect(result.current.hasCachedInputPricing).toBe(true);+ expect(result.current.getUnitPriceSuffix('millionTokens')).toBe(' credits/M tokens');+ });++ it('formats original unit prices for tiered and lookup units', () => {+ const { result } = renderModelDetailPanelHook({+ enabledList: createEnabledList('lobehub', unitPricing),+ });++ expect(result.current.formatUnitPrice(unitPricing.units[0])).toEqual({+ current: '20.0K',+ original: '50.0K',+ });+ expect(result.current.formatUnitPrice(unitPricing.units[1])).toEqual({+ current: '300.0K',+ original: '500.0K',+ });+ });++ it('uses the enabled model list hook when no list is provided', () => {+ useEnabledChatModelsMock.mockReturnValue(+ createEnabledList('lobehub', basePricing, {+ abilities: { reasoning: true },+ }),+ );++ const { result } = renderModelDetailPanelHook({ enabledList: undefined });++ expect(result.current.model?.id).toBe('test-model');+ expect(result.current.contextWindowLabel).toBe('1M tokens');+ expect(result.current.hasAbilities).toBe(true);+ });++ it('updates expanded detail sections', () => {+ const { result } = renderModelDetailPanelHook();++ act(() => {+ result.current.handleExpandedChange(['abilities']);+ });++ expect(updateExpandedKeysMock).toHaveBeenCalledWith(['abilities']);+ });+});diff --git a/src/features/ModelSwitchPanel/hooks/useModelDetailPanel.ts b/src/features/ModelSwitchPanel/hooks/useModelDetailPanel.tsnew file mode 100644index 00000000000..f15833fd527--- /dev/null+++ b/src/features/ModelSwitchPanel/hooks/useModelDetailPanel.ts@@ -0,0 +1,433 @@+import { BRANDING_PROVIDER } from '@lobechat/business-const';+import { getCachedTextInputUnitRate } from '@lobechat/utils';+import type { TFunction } from 'i18next';+import type { LucideIcon } from 'lucide-react';+import {+ ArrowDownToDot,+ ArrowUpFromDot,+ AtomIcon,+ AudioLinesIcon,+ CircleFadingArrowUp,+ EyeIcon,+ GlobeIcon,+ ImageIcon,+ PaperclipIcon,+ VideoIcon,+ WrenchIcon,+} from 'lucide-react';+import type {+ FixedPricingUnit,+ ModelPriceCurrency,+ Pricing,+ PricingUnit,+ PricingUnitName,+ TieredPricingUnit,+} from 'model-bank';+import { useCallback, useMemo } from 'react';++import { useBusinessModelPricing } from '@/business/client/hooks/useBusinessModelPricing';+import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';+import { useGlobalStore } from '@/store/global';+import type { ModelDetailPanelExpandedKey } from '@/store/global/initialState';+import { systemStatusSelectors } from '@/store/global/selectors';+import type { EnabledProviderWithModels } from '@/types/aiProvider';+import { formatNumber, formatShortenNumber, formatTokenNumber } from '@/utils/format';+import { formatPriceByCurrency, getOriginalUnitRateByName, getUnitRateByName } from '@/utils/index';++import type { PricingMode } from '../types';++export interface FormattedUnitPrice {+ current: string;+ original?: string;+}++interface TextPriceSummary {+ cachedInput: FormattedUnitPrice;+ input: FormattedUnitPrice;+ output: FormattedUnitPrice;+}++const BRANDING_CREDIT_UNIT = 1_000_000;+const MILLION_SCALE_UNITS = new Set<PricingUnit['unit']>(['millionCharacters', 'millionTokens']);++interface FormatPricingRateOptions {+ isCreditPricing?: boolean;+ unit?: PricingUnit['unit'];+}++const formatBrandingCreditRate = (rate: number, unit?: PricingUnit['unit']) => {+ if (unit && MILLION_SCALE_UNITS.has(unit)) return `${formatNumber(rate)}M`;++ return String(formatShortenNumber(Math.round(rate * BRANDING_CREDIT_UNIT)));+};++const formatPricingRate = (+ rate: number | undefined,+ currency?: ModelPriceCurrency,+ options: FormatPricingRateOptions = {},+) => {+ if (typeof rate !== 'number') return '0';++ return options.isCreditPricing+ ? formatBrandingCreditRate(rate, options.unit)+ : formatPriceByCurrency(rate, currency);+};++const getFormattedUnitPrice = (+ pricing: Pricing,+ unitName: PricingUnitName,+ isCreditPricing: boolean,+): FormattedUnitPrice => {+ const currency = pricing.currency as ModelPriceCurrency | undefined;+ const currentRate = getUnitRateByName(pricing, unitName);+ const originalRate = getOriginalUnitRateByName(pricing, unitName);++ return {+ current: formatPricingRate(currentRate, currency, {+ isCreditPricing,+ unit: 'millionTokens',+ }),+ original:+ typeof originalRate === 'number'+ ? formatPricingRate(originalRate, currency, {+ isCreditPricing,+ unit: 'millionTokens',+ })+ : undefined,+ };+};++const getPrice = (pricing: Pricing, isCreditPricing: boolean): TextPriceSummary => {+ return {+ cachedInput: getFormattedUnitPrice(pricing, 'textInput_cacheRead', isCreditPricing),+ input: getFormattedUnitPrice(pricing, 'textInput', isCreditPricing),+ output: getFormattedUnitPrice(pricing, 'textOutput', isCreditPricing),+ };+};++type PricingGroup = 'audio' | 'image' | 'text' | 'video';++const UNIT_GROUP_MAP: Record<PricingUnitName, PricingGroup> = {+ audioInput: 'audio',+ audioInput_cacheRead: 'audio',+ audioOutput: 'audio',+ imageGeneration: 'image',+ imageInput: 'image',+ imageInput_cacheRead: 'image',+ imageOutput: 'image',+ textInput: 'text',+ textInput_cacheRead: 'text',+ textInput_cacheWrite: 'text',+ textOutput: 'text',+ videoInput: 'video',+ videoGeneration: 'video',+};++const GROUP_ORDER: PricingGroup[] = ['text', 'image', 'audio', 'video'];++export const UNIT_ICON_MAP: Partial<Record<PricingUnitName, LucideIcon>> = {+ audioInput: ArrowUpFromDot,+ audioInput_cacheRead: CircleFadingArrowUp,+ audioOutput: ArrowDownToDot,+ imageGeneration: ImageIcon,+ imageInput: ArrowUpFromDot,+ imageInput_cacheRead: CircleFadingArrowUp,+ imageOutput: ArrowDownToDot,+ textInput: ArrowUpFromDot,+ textInput_cacheRead: CircleFadingArrowUp,+ textInput_cacheWrite: CircleFadingArrowUp,+ textOutput: ArrowDownToDot,+};++const UNIT_SORT_ORDER: Record<PricingUnitName, number> = {+ textInput: 0,+ textOutput: 1,+ textInput_cacheRead: 2,+ textInput_cacheWrite: 3,+ imageInput: 0,+ imageOutput: 1,+ imageInput_cacheRead: 2,+ imageGeneration: 3,+ audioInput: 0,+ audioOutput: 1,+ audioInput_cacheRead: 2,+ videoInput: 0,+ videoGeneration: 1,+};++const UNIT_LABEL_MAP: Record<string, string> = {+ image: '/img',+ megapixel: '/MP',+ millionCharacters: '/M chars',+ millionTokens: '/M tokens',+ second: '/s',+};++const formatUnitRate = (+ unit: PricingUnit,+ currency?: ModelPriceCurrency,+ isCreditPricing?: boolean,+): FormattedUnitPrice => {+ const formatRate = (rate: number) =>+ formatPricingRate(rate, currency, { isCreditPricing, unit: unit.unit });+ const formatRange = (low: string, high: string) =>+ isCreditPricing ? `${low} ~ ${high}` : `${low} ~ $${high}`;++ if (unit.strategy === 'fixed') {+ const fixedUnit = unit as FixedPricingUnit;+ return {+ current: formatRate(fixedUnit.rate),+ original:+ typeof fixedUnit.originalRate === 'number' && fixedUnit.originalRate > fixedUnit.rate+ ? formatRate(fixedUnit.originalRate)+ : undefined,+ };+ }++ if (unit.strategy === 'tiered') {+ const tiers = (unit as TieredPricingUnit).tiers;+ if (tiers.length === 1) {+ const price = formatRate(tiers[0].rate);+ return {+ current: price,+ original:+ typeof tiers[0].originalRate === 'number' && tiers[0].originalRate > tiers[0].rate+ ? formatRate(tiers[0].originalRate)+ : undefined,+ };+ }+ const low = formatRate(tiers[0].rate);+ const high = formatRate(tiers.at(-1)!.rate);+ const originalLow = tiers[0].originalRate;+ const originalHigh = tiers.at(-1)!.originalRate;+ const original =+ typeof originalLow === 'number' &&+ typeof originalHigh === 'number' &&+ (originalLow > tiers[0].rate || originalHigh > tiers.at(-1)!.rate)+ ? formatRange(formatRate(originalLow), formatRate(originalHigh))+ : undefined;+ return { current: formatRange(low, high), original };+ }++ if (unit.strategy === 'lookup') {+ const entries = Object.entries(unit.lookup.prices);+ if (entries.length === 0) return { current: '-' };++ if (entries.length === 1) {+ const [key, price] = entries[0];+ const originalPrice = unit.lookup.originalPrices?.[key];+ return {+ current: formatRate(price),+ original:+ typeof originalPrice === 'number' && originalPrice > price+ ? formatRate(originalPrice)+ : undefined,+ };+ }+ const sorted = [...entries].sort((a, b) => a[1] - b[1]);+ const [lowKey, lowPrice] = sorted[0];+ const [highKey, highPrice] = sorted.at(-1)!;+ const originalLow = unit.lookup.originalPrices?.[lowKey];+ const originalHigh = unit.lookup.originalPrices?.[highKey];+ const original =+ typeof originalLow === 'number' &&+ typeof originalHigh === 'number' &&+ (originalLow > lowPrice || originalHigh > highPrice)+ ? formatRange(formatRate(originalLow), formatRate(originalHigh))+ : undefined;+ return { current: formatRange(formatRate(lowPrice), formatRate(highPrice)), original };+ }++ return { current: '-' };+};++interface PricingGroupData {+ group: PricingGroup;+ units: PricingUnit[];+}++const groupPricingUnits = (units: PricingUnit[]): PricingGroupData[] => {+ const map = new Map<PricingGroup, PricingUnit[]>();+ for (const unit of units) {+ const group = UNIT_GROUP_MAP[unit.name] || 'text';+ const arr = map.get(group) || [];+ arr.push(unit);+ map.set(group, arr);+ }+ for (const [, arr] of map) {+ arr.sort((a, b) => (UNIT_SORT_ORDER[a.name] ?? 99) - (UNIT_SORT_ORDER[b.name] ?? 99));+ }+ return GROUP_ORDER.filter((g) => map.has(g)).map((g) => ({ group: g, units: map.get(g)! }));+};++interface AbilityItem {+ color: string;+ icon: LucideIcon;+ key: string;+}++const ABILITY_CONFIG: AbilityItem[] = [+ { color: 'success', icon: EyeIcon, key: 'vision' },+ { color: 'success', icon: PaperclipIcon, key: 'files' },+ { color: 'success', icon: ImageIcon, key: 'imageOutput' },+ { color: 'magenta', icon: VideoIcon, key: 'video' },+ { color: 'gold', icon: AudioLinesIcon, key: 'audio' },+ { color: 'info', icon: WrenchIcon, key: 'functionCall' },+ { color: 'purple', icon: AtomIcon, key: 'reasoning' },+ { color: 'cyan', icon: GlobeIcon, key: 'search' },+];++interface UseModelDetailPanelParams {+ enabledList?: EnabledProviderWithModels[];+ modelId?: string;+ pricingMode?: PricingMode;+ provider?: string;+ t: TFunction<'components'>;+}++export const useModelDetailPanel = ({+ enabledList: enabledListProp,+ modelId,+ pricingMode,+ provider,+ t,+}: UseModelDetailPanelParams) => {+ const enabledListFromHook = useEnabledChatModels();+ const enabledList = enabledListProp ?? enabledListFromHook;+ const model = useMemo(() => {+ if (!modelId || !provider) return undefined;+ const providerData = enabledList.find((p) => p.id === provider);+ return providerData?.children.find((m) => m.id === modelId);+ }, [enabledList, modelId, provider]);++ const expandedKeys = useGlobalStore(systemStatusSelectors.modelDetailPanelExpandedKeys);+ const updateExpandedKeys = useGlobalStore((s) => s.updateModelDetailPanelExpandedKeys);+ const applyBusinessModelPricing = useBusinessModelPricing();++ const pricing = model?.pricing;+ const displayPricing = useMemo(+ () => applyBusinessModelPricing({ model: modelId, pricing, provider }),+ [applyBusinessModelPricing, modelId, pricing, provider],+ );+ const isCreditPricing = provider === BRANDING_PROVIDER;+ const hasPricing = !!displayPricing;+ const formatPrice = displayPricing ? getPrice(displayPricing, isCreditPricing) : null;+ const hasCachedInputPricing = displayPricing+ ? !!getCachedTextInputUnitRate(displayPricing)+ : false;+ const pricingGroups = useMemo(+ () => (displayPricing ? groupPricingUnits(displayPricing.units) : []),+ [displayPricing],+ );++ const approximatePriceLabel = useMemo(() => {+ if (!displayPricing || !pricingMode) return null;+ const currency = displayPricing.currency as ModelPriceCurrency | undefined;+ if (pricingMode === 'image' && typeof displayPricing.approximatePricePerImage === 'number') {+ const amount = isCreditPricing+ ? formatBrandingCreditRate(displayPricing.approximatePricePerImage, 'image')+ : formatPriceByCurrency(displayPricing.approximatePricePerImage, currency);+ return t(+ isCreditPricing+ ? 'ModelSwitchPanel.detail.pricing.credits.perImage'+ : 'ModelSwitchPanel.detail.pricing.perImage',+ {+ amount,+ defaultValue: isCreditPricing ? '~ {{amount}} credits / image' : '~ ${{amount}} / image',+ },+ );+ }+ if (pricingMode === 'video' && typeof displayPricing.approximatePricePerVideo === 'number') {+ const amount = isCreditPricing+ ? formatBrandingCreditRate(displayPricing.approximatePricePerVideo)+ : formatPriceByCurrency(displayPricing.approximatePricePerVideo, currency);+ return t(+ isCreditPricing+ ? 'ModelSwitchPanel.detail.pricing.credits.perVideo'+ : 'ModelSwitchPanel.detail.pricing.perVideo',+ {+ amount,+ defaultValue: isCreditPricing ? '~ {{amount}} credits / video' : '~ ${{amount}} / video',+ },+ );+ }+ return null;+ }, [displayPricing, isCreditPricing, pricingMode, t]);++ const getCreditsUnitLabel = useCallback(+ (unit: PricingUnit['unit']) =>+ t(`ModelSwitchPanel.detail.pricing.credits.${unit}` as any, {+ defaultValue: `credits${UNIT_LABEL_MAP[unit] || ''}`,+ }),+ [t],+ );++ const getPricingTooltip = useCallback(+ (key: 'cachedInput' | 'input' | 'output', amount: string): string => {+ if (isCreditPricing) {+ return t(`ModelSwitchPanel.detail.pricing.credits.${key}` as any, { amount });+ }++ const fallbackKey =+ key === 'cachedInput'+ ? 'ModelSwitchPanel.detail.pricing.cachedInput'+ : `ModelSwitchPanel.detail.pricing.${key}`;++ return t(fallbackKey as any, { amount });+ },+ [isCreditPricing, t],+ );++ const formatUnitPrice = useCallback(+ (unit: PricingUnit) =>+ formatUnitRate(unit, displayPricing?.currency as ModelPriceCurrency, isCreditPricing),+ [displayPricing?.currency, isCreditPricing],+ );++ const getUnitPriceSuffix = useCallback(+ (unit: PricingUnit['unit']) =>+ isCreditPricing ? ` ${getCreditsUnitLabel(unit)}` : UNIT_LABEL_MAP[unit] || '',+ [getCreditsUnitLabel, isCreditPricing],+ );++ const handleExpandedChange = useCallback(+ (keys: unknown[]) => updateExpandedKeys(keys as ModelDetailPanelExpandedKey[]),+ [updateExpandedKeys],+ );++ const contextWindowLabel = useMemo(() => {+ if (typeof model?.contextWindowTokens !== 'number') return null;++ return model.contextWindowTokens === 0+ ? '∞'+ : `${formatTokenNumber(model.contextWindowTokens)} tokens`;+ }, [model?.contextWindowTokens]);++ const enabledAbilities = useMemo(+ () =>+ model+ ? ABILITY_CONFIG.filter((a) => model.abilities[a.key as keyof typeof model.abilities])+ : [],+ [model],+ );++ return {+ approximatePriceLabel,+ contextWindowLabel,+ enabledAbilities,+ expandedKeys,+ formatPrice,+ formatUnitPrice,+ getPricingTooltip,+ getUnitPriceSuffix,+ handleExpandedChange,+ hasAbilities: enabledAbilities.length > 0,+ hasCachedInputPricing,+ hasPricing,+ isAbilitiesExpanded: expandedKeys.includes('abilities'),+ isCreditPricing,+ isPricingExpanded: expandedKeys.includes('pricing'),+ model,+ pricingGroups,+ };+};diff --git a/src/features/ModelSwitchPanel/types.ts b/src/features/ModelSwitchPanel/types.tsindex c14cf89a06f..ae065029425 100644--- a/src/features/ModelSwitchPanel/types.ts+++ b/src/features/ModelSwitchPanel/types.ts@@ -4,10 +4,10 @@ import { type ComponentType } from 'react';import { type EnabledProviderWithModels } from '@/types/aiProvider';-import { type PricingMode } from './components/ModelDetailPanel';-export type GroupMode = 'byModel' | 'byProvider';+export type PricingMode = 'image' | 'video';+export interface ModelWithProviders {displayName: string;model: AiModelForSelect;