🤯 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
🐛 fix(runtime): expose missing usage diagnostics (#15973)
YuTengjing9401e6eeac9f
diff --git a/apps/server/src/routers/lambda/__tests__/aiModel.test.ts b/apps/server/src/routers/lambda/__tests__/aiModel.test.tsindex 6ab230510f6..1e26261a8d9 100644--- a/apps/server/src/routers/lambda/__tests__/aiModel.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiModel.test.ts@@ -82,7 +82,7 @@ describe('aiModelRouter', () => {const duplicateError = Object.assign(new Error('failed query'), {cause: Object.assign(new Error('duplicate key'), {code: '23505',- constraint: 'ai_models_id_provider_id_user_id_unique',+ constraint: 'ai_models_id_provider_id_user_id_pk',}),});const mockCreate = vi.fn().mockRejectedValue(duplicateError);diff --git a/apps/server/src/routers/lambda/aiModel.ts b/apps/server/src/routers/lambda/aiModel.tsindex ae19e59c2b8..9137d85dd1d 100644--- a/apps/server/src/routers/lambda/aiModel.ts+++ b/apps/server/src/routers/lambda/aiModel.ts@@ -19,7 +19,7 @@ import { getServerGlobalConfig } from '@/server/globalConfig';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { type ProviderConfig } from '@/types/user/settings';-const AI_MODEL_UNIQUE_CONSTRAINT = 'ai_models_id_provider_id_user_id_unique';+const AI_MODEL_UNIQUE_CONSTRAINT = 'ai_models_id_provider_id_user_id_pk';const getPostgresErrorField = (error: unknown, field: 'code' | 'constraint') => {let current = error;diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.tsindex eb25f301fc5..91051d0af04 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts@@ -119,6 +119,69 @@ describe('createRouterRuntime', () => {expect(mockChat).toHaveBeenCalledWith(payload, undefined);});+ it('should attach route attempt metadata for lobehub runtime only', async () => {+ const mockChat = vi.fn().mockResolvedValue('chat-response');++ class MockRuntime implements LobeRuntimeAI {+ chat = mockChat;+ }++ const Runtime = createRouterRuntime({+ id: 'lobehub',+ routers: [+ {+ apiType: 'openai',+ options: { id: 'channel-1' },+ runtime: MockRuntime as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime();+ const metadata: Record<string, unknown> = { traceId: 'trace-1', trigger: 'chat' };++ await runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 }, { metadata });++ expect(metadata.routeAttempt).toEqual(+ expect.objectContaining({+ apiType: 'openai',+ channelId: 'channel-1',+ optionIndex: 0,+ providerId: 'lobehub',+ success: true,+ totalOptions: 1,+ }),+ );+ });++ it('should not attach route attempt metadata for non-lobehub runtime', async () => {+ const mockChat = vi.fn().mockResolvedValue('chat-response');++ class MockRuntime implements LobeRuntimeAI {+ chat = mockChat;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: { id: 'channel-1' },+ runtime: MockRuntime as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime();+ const metadata: Record<string, unknown> = { traceId: 'trace-1', trigger: 'chat' };++ await runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 }, { metadata });++ expect(metadata).not.toHaveProperty('routeAttempt');+ });+it('should handle errors when provided with handleError', async () => {const mockError = new Error('API Error');const mockChat = vi.fn().mockRejectedValue(mockError);diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex d602110d1b3..dc1d9e9c908 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -108,6 +108,17 @@ export interface RouteAttemptResult {userId?: string;}+interface RouteAttemptMetadata {+ apiType: string;+ channelId?: string;+ durationMs: number;+ optionIndex: number;+ providerId: string;+ routerId?: string;+ success: boolean;+ totalOptions: number;+}+export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any> {apiKey?: string;chatCompletion?: {@@ -191,6 +202,15 @@ export const createRouterRuntime = ({private _params: any;private _id: string;+ private attachRouteAttemptMetadata(+ metadata: Record<string, unknown> | undefined,+ routeAttempt: RouteAttemptMetadata,+ ) {+ if (!metadata || this._id !== 'lobehub') return;++ metadata.routeAttempt = routeAttempt;+ }+constructor(options: ClientOptions & Record<string, any> = {}) {const startedAt = Date.now();this._options = {@@ -522,6 +542,17 @@ export const createRouterRuntime = ({log('onRouteAttempt callback error: %O', e);});+ this.attachRouteAttemptMetadata(metadata, {+ apiType: resolvedApiType,+ channelId,+ durationMs: Date.now() - startTime,+ optionIndex: index,+ providerId: id,+ routerId: matchedRouter.id,+ success: true,+ totalOptions,+ });+return result;} catch (error) {lastError = error;diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.tsindex 8d169607a00..ea544b2f8f6 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts@@ -30,7 +30,7 @@ import {buildSearchTool,} from '../contextBuilders/anthropic';import { resolveModelSamplingParameters } from '../parameterResolver';-import { AnthropicStream } from '../streams';+import { AnthropicStream, type AnthropicStreamOptions } from '../streams';import { type ComputeChatCostOptions } from '../usageConverters/utils/computeChatCost';import { createAnthropicGenerateObject } from './generateObject';import { handleAnthropicError } from './handleAnthropicError';@@ -535,12 +535,13 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =const streamOptions = {callbacks: options?.callback,payload: {+ apiMode: 'messages',model: payload.model,pricing,pricingOptions,provider: this.id,},- };+ } satisfies Pick<AnthropicStreamOptions, 'callbacks' | 'payload'>;if (shouldStream) {const streamResponse = response as Stream<Anthropic.MessageStreamEvent>;diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 5e9aadaf493..c44a2a8a698 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -574,6 +574,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anforceVideoBase64: chatCompletion?.forceVideoBase64,model: postPayload.model,});+ const includeUsageRequested = Boolean(postPayload.stream && !chatCompletion?.excludeUsage);let response: Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;@@ -581,6 +582,8 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anbizErrorTypeTransformer: chatCompletion?.handleStreamBizErrorType,callbacks: options?.callback,payload: {+ apiMode: 'chat_completions',+ includeUsageRequested,model: payload.model,pricing: await getModelPricing(payload.model, this.id),provider: this.id,@@ -627,10 +630,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anoptions?.user,cleanedPayload.prompt_cache_key,),- stream_options:- postPayload.stream && !chatCompletion?.excludeUsage- ? { include_usage: true }- : undefined,+ stream_options: includeUsageRequested ? { include_usage: true } : undefined,};log('sending chat completion request with %d messages', messages.length);@@ -1347,6 +1347,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anbizErrorTypeTransformer: chatCompletion?.handleStreamBizErrorType,callbacks: options?.callback,payload: {+ apiMode: 'responses',model: payload.model,pricing: await getModelPricing(payload.model, this.id),provider: this.id,diff --git a/packages/model-runtime/src/core/streams/anthropic.test.ts b/packages/model-runtime/src/core/streams/anthropic.test.tsindex 4b703c8ed32..2c290c03327 100644--- a/packages/model-runtime/src/core/streams/anthropic.test.ts+++ b/packages/model-runtime/src/core/streams/anthropic.test.ts@@ -64,13 +64,16 @@ describe('AnthropicStream', () => {const onStartMock = vi.fn();const onTextMock = vi.fn();const onCompletionMock = vi.fn();+ const onFinalMock = vi.fn();const protocolStream = AnthropicStream(mockAnthropicStream, {callbacks: {onStart: onStartMock,onText: onTextMock,onCompletion: onCompletionMock,+ onFinal: onFinalMock,},+ payload: { apiMode: 'messages', model: 'claude-opus-4-8', provider: 'anthropic' },});const decoder = new TextDecoder();@@ -100,6 +103,19 @@ describe('AnthropicStream', () => {expect(onTextMock).toHaveBeenNthCalledWith(1, 'Hello');expect(onTextMock).toHaveBeenNthCalledWith(2, ' world!');expect(onCompletionMock).toHaveBeenCalledTimes(1);+ expect(onFinalMock).toHaveBeenCalledWith(+ expect.objectContaining({+ usageMissingDiagnostics: {+ apiMode: 'messages',+ finishReason: 'stop',+ hasUsageMetadata: false,+ model: 'claude-opus-4-8',+ provider: 'anthropic',+ source: 'anthropic_messages',+ terminalEventType: 'message_delta',+ },+ }),+ );});it('should handle tool use event and ReadableStream input', async () => {diff --git a/packages/model-runtime/src/core/streams/anthropic.ts b/packages/model-runtime/src/core/streams/anthropic.tsindex 97f8e89ff46..b4cb4147ede 100644--- a/packages/model-runtime/src/core/streams/anthropic.ts+++ b/packages/model-runtime/src/core/streams/anthropic.ts@@ -193,16 +193,38 @@ export const transformAnthropicStream = (}if (aggregatedUsage && (aggregatedUsage.totalTokens ?? 0) > 0) {+ delete context.usageMissingDiagnostics;return [{ data: chunk.delta.stop_reason, id: context.id, type: 'stop' },{ data: aggregatedUsage, id: context.id, type: 'usage' },];}+ context.usageMissingDiagnostics = {+ apiMode: 'messages',+ finishReason: chunk.delta.stop_reason,+ hasUsageMetadata: Boolean(chunk.usage),+ model: payload?.model,+ provider: payload?.provider,+ source: 'anthropic_messages',+ terminalEventType: chunk.type,+ };+return { data: chunk.delta.stop_reason, id: context.id, type: 'stop' };}case 'message_stop': {+ if (!context.usage && !context.usageMissingDiagnostics) {+ context.usageMissingDiagnostics = {+ apiMode: 'messages',+ hasUsageMetadata: false,+ model: payload?.model,+ provider: payload?.provider,+ source: 'anthropic_messages',+ terminalEventType: chunk.type,+ };+ }+return [...(context.returnedCitationArray?.length? [@@ -253,5 +275,5 @@ export const AnthropicStream = (}),).pipeThrough(createSSEProtocolTransformer((c) => c, streamStack))- .pipeThrough(createCallbacksTransformer(callbacks));+ .pipeThrough(createCallbacksTransformer(callbacks, { streamStack }));};diff --git a/packages/model-runtime/src/core/streams/google/google-ai.test.ts b/packages/model-runtime/src/core/streams/google/google-ai.test.tsindex d7bb2aa89d2..a0e0f02c832 100644--- a/packages/model-runtime/src/core/streams/google/google-ai.test.ts+++ b/packages/model-runtime/src/core/streams/google/google-ai.test.ts@@ -159,6 +159,46 @@ describe('GoogleGenerativeAIStream', () => {]);});+ it('should expose missing usage diagnostics when finishReason has no usageMetadata', async () => {+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('missingUsage');+ const mockGoogleStream = new ReadableStream({+ start(controller) {+ controller.enqueue({+ candidates: [+ {+ content: { parts: [{ text: '' }], role: 'model' },+ finishReason: 'STOP',+ index: 0,+ },+ ],+ modelVersion: 'gemini-test',+ } as unknown as GenerateContentResponse);+ controller.close();+ },+ });+ const onFinal = vi.fn();++ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {+ callbacks: { onFinal },+ payload: { model: 'gemini-3.1-flash-lite', provider: 'google' },+ });++ await decodeStreamChunks(protocolStream);++ expect(onFinal).toHaveBeenCalledWith(+ expect.objectContaining({+ usageMissingDiagnostics: {+ finishReason: 'STOP',+ hasUsageMetadata: false,+ model: 'gemini-3.1-flash-lite',+ provider: 'google',+ source: 'google_generative_ai',+ terminalEventType: 'GenerateContentResponse.candidates.finishReason',+ },+ }),+ );+ });+it('should return undefined data without text', async () => {vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');diff --git a/packages/model-runtime/src/core/streams/google/index.ts b/packages/model-runtime/src/core/streams/google/index.tsindex 4f042e93fe1..fa11ec4ec04 100644--- a/packages/model-runtime/src/core/streams/google/index.ts+++ b/packages/model-runtime/src/core/streams/google/index.ts@@ -112,12 +112,22 @@ const transformGoogleGenerativeAIStream = (const usageChunks: StreamProtocolChunk[] = [];if (candidate?.finishReason && usageMetadata) {+ delete context.usageMissingDiagnostics;usageChunks.push({ data: candidate.finishReason, id: context?.id, type: 'stop' });const convertedUsage = convertGoogleAIUsage(usageMetadata, payload?.pricing);if (convertedUsage) {usageChunks.push({ data: convertedUsage, id: context?.id, type: 'usage' });}+ } else if (candidate?.finishReason) {+ context.usageMissingDiagnostics = {+ finishReason: candidate.finishReason,+ hasUsageMetadata: false,+ model: payload?.model,+ provider: payload?.provider,+ source: 'google_generative_ai',+ terminalEventType: 'GenerateContentResponse.candidates.finishReason',+ };}// Parse function calls from candidate.content.parts@@ -408,5 +418,5 @@ export const GoogleGenerativeAIStream = (.pipeThrough(createSSEProtocolTransformer((c) => c, streamStack, { requireTerminalEvent: true }),)- .pipeThrough(createCallbacksTransformer(callbacks));+ .pipeThrough(createCallbacksTransformer(callbacks, { streamStack }));};diff --git a/packages/model-runtime/src/core/streams/openai/openai.test.ts b/packages/model-runtime/src/core/streams/openai/openai.test.tsindex 19391d0776e..217e2b10c92 100644--- a/packages/model-runtime/src/core/streams/openai/openai.test.ts+++ b/packages/model-runtime/src/core/streams/openai/openai.test.ts@@ -79,6 +79,57 @@ describe('OpenAIStream', () => {expect(onCompletionMock).toHaveBeenCalledTimes(1);});+ it('should expose missing usage diagnostics when terminal chunk has no usage', async () => {+ const mockOpenAIStream = new ReadableStream({+ start(controller) {+ controller.enqueue({+ choices: [+ {+ delta: {},+ finish_reason: 'stop',+ index: 0,+ },+ ],+ id: 'chatcmpl_missing_usage',+ });+ controller.close();+ },+ });+ const onFinal = vi.fn();++ const protocolStream = OpenAIStream(mockOpenAIStream, {+ callbacks: { onFinal },+ payload: {+ apiMode: 'chat_completions',+ includeUsageRequested: true,+ model: 'gpt-5.4-mini',+ provider: 'openai',+ },+ });++ const decoder = new TextDecoder();+ // @ts-ignore+ for await (const chunk of protocolStream) {+ decoder.decode(chunk, { stream: true });+ }++ expect(onFinal).toHaveBeenCalledWith(+ expect.objectContaining({+ usageMissingDiagnostics: expect.objectContaining({+ apiMode: 'chat_completions',+ finishReason: 'stop',+ hasUsageMetadata: false,+ includeUsageRequested: true,+ model: 'gpt-5.4-mini',+ provider: 'openai',+ responseId: 'chatcmpl_missing_usage',+ source: 'openai_chat_completions',+ terminalEventType: 'chat.completion.chunk',+ }),+ }),+ );+ });+it('should handle empty stream', async () => {const mockStream = new ReadableStream({start(controller) {@@ -3638,6 +3689,49 @@ describe('OpenAIStream', () => {]);});+ it('should handle finish_reason with text and usage', async () => {+ const mockOpenAIStream = new ReadableStream({+ start(controller) {+ controller.enqueue({+ id: 'finish-text-usage',+ choices: [+ {+ index: 0,+ delta: { content: 'done' },+ finish_reason: 'stop',+ },+ ],+ usage: {+ prompt_tokens: 10,+ completion_tokens: 20,+ total_tokens: 30,+ },+ });++ controller.close();+ },+ });++ const protocolStream = OpenAIStream(mockOpenAIStream);++ const decoder = new TextDecoder();+ const chunks = [];++ // @ts-ignore+ for await (const chunk of protocolStream) {+ chunks.push(decoder.decode(chunk, { stream: true }));+ }++ expect(chunks).toEqual([+ 'id: finish-text-usage\n',+ 'event: text\n',+ 'data: "done"\n\n',+ 'id: finish-text-usage\n',+ 'event: usage\n',+ `data: {"inputTextTokens":10,"outputTextTokens":20,"totalInputTokens":10,"totalOutputTokens":20,"totalTokens":30}\n\n`,+ ]);+ });+it('should handle mistral AI Magistral thinking blocks in content array', async () => {const mockOpenAIStream = new ReadableStream({start(controller) {diff --git a/packages/model-runtime/src/core/streams/openai/openai.ts b/packages/model-runtime/src/core/streams/openai/openai.tsindex fb59e036f37..d3d3eb08c47 100644--- a/packages/model-runtime/src/core/streams/openai/openai.ts+++ b/packages/model-runtime/src/core/streams/openai/openai.ts@@ -158,6 +158,7 @@ const transformOpenAIStream = (// maybe need another structure to add support for multiple choicesif (!Array.isArray(chunk.choices) || chunk.choices.length === 0) {if (chunk.usage) {+ delete streamContext.usageMissingDiagnostics;const usage = chunk.usage;return { data: convertOpenAIUsage(usage, payload), id: chunk.id, type: 'usage' };}@@ -275,13 +276,42 @@ const transformOpenAIStream = (// Handle finish reasonif (item.finish_reason) {+ const usageChunk: StreamProtocolChunk | undefined = chunk.usage+ ? { data: convertOpenAIUsage(chunk.usage, payload), id: chunk.id, type: 'usage' }+ : undefined;+ const appendUsageChunk = (+ protocolChunk: StreamProtocolChunk | StreamProtocolChunk[],+ ): StreamProtocolChunk | StreamProtocolChunk[] => {+ if (!usageChunk) return protocolChunk;++ delete streamContext.usageMissingDiagnostics;+ return Array.isArray(protocolChunk)+ ? [...protocolChunk, usageChunk]+ : [protocolChunk, usageChunk];+ };++ if (!usageChunk) {+ streamContext.usageMissingDiagnostics = {+ apiMode: 'chat_completions',+ chunkIndex: streamContext.chunkIndex,+ finishReason: item.finish_reason,+ hasUsageMetadata: false,+ includeUsageRequested: payload?.includeUsageRequested,+ model: payload?.model,+ provider: payload?.provider,+ responseId: chunk.id,+ source: 'openai_chat_completions',+ terminalEventType: 'chat.completion.chunk',+ };+ }+// one-api's streaming interface can have both finish_reason and content// {"id":"demo","model":"deepl-en","choices":[{"index":0,"delta":{"role":"assistant","content":"Introduce yourself."},"finish_reason":"stop"}]}if (typeof item.delta?.content === 'string' && !!item.delta.content) {// MiniMax built-in search returns citation sources in the first tool stream content, needs to be ignored// {"id":"0483748a25071c611e2f48d2982fbe96","choices":[{"finish_reason":"stop","index":0,"delta":{"content":"[{\"no\":1,\"url\":\"https://www.xiaohongshu.com/discovery/item/66d8de3c000000001f01e752\",\"title\":\"郑钦文为国而战,没有理由不坚持🏅\",\"content\":\"·2024年08月03日\\n中国队选手郑钦文夺得巴黎奥运会网球女单比赛金牌(巴黎奥运第16金)\\n#巴黎奥运会[话题]# #郑钦文[话题]# #人物素材积累[话题]# #作文素材积累[话题]# #申论素材[话题]#\",\"web_icon\":\"https://www.xiaohongshu.com/favicon.ico\"}]","role":"tool","tool_call_id":"call_function_6696730535"}}],"created":1748255114,"model":"abab6.5s-chat","object":"chat.completion.chunk","usage":{"total_tokens":0,"total_characters":0},"input_sensitive":false,"output_sensitive":false,"input_sensitive_type":0,"output_sensitive_type":0,"output_sensitive_int":0}if (typeof item.delta?.role === 'string' && item.delta.role === 'tool') {- return { data: null, id: chunk.id, type: 'text' };+ return appendUsageChunk({ data: null, id: chunk.id, type: 'text' });}const text = item.delta.content as string;@@ -296,10 +326,10 @@ const transformOpenAIStream = (type: 'base64_image' as const,})),);- return arr;+ return appendUsageChunk(arr);}- return { data: text, id: chunk.id, type: 'text' };+ return appendUsageChunk({ data: text, id: chunk.id, type: 'text' });}// OpenAI Search Preview model returns citation sources@@ -307,7 +337,7 @@ const transformOpenAIStream = (if ((item as any).delta?.annotations && (item as any).delta.annotations.length > 0) {const citations = (item as any).delta.annotations;- return [+ return appendUsageChunk([{data: {citations: filterValidCitations(@@ -323,7 +353,7 @@ const transformOpenAIStream = (id: chunk.id,type: 'grounding',},- ];+ ]);}// MiniMax built-in search returns 4 objects in the message array of the last stream, with the last one being annotations@@ -331,7 +361,7 @@ const transformOpenAIStream = (if ((item as any).messages && (item as any).messages.length > 0) {const citations = (item as any).messages.at(-1).annotations;- return [+ return appendUsageChunk([{data: {citations: filterValidCitations(@@ -347,12 +377,12 @@ const transformOpenAIStream = (id: chunk.id,type: 'grounding',},- ];+ ]);}- if (chunk.usage) {- const usage = chunk.usage;- return { data: convertOpenAIUsage(usage, payload), id: chunk.id, type: 'usage' };+ if (usageChunk) {+ delete streamContext.usageMissingDiagnostics;+ return usageChunk;}// xAI Live Search feature returns citation sources@@ -472,6 +502,7 @@ const transformOpenAIStream = (if (typeof content === 'string') {// If content is an empty string but chunk has usage, prioritize returning usage (e.g., Gemini image-preview eventually returns usage in a separate chunk)if (content === '' && chunk.usage) {+ delete streamContext.usageMissingDiagnostics;const usage = chunk.usage;return { data: convertOpenAIUsage(usage, payload), id: chunk.id, type: 'usage' };}@@ -588,6 +619,7 @@ const transformOpenAIStream = (// In litellm responses, there are cases where delta is empty but usage existsif (chunk.usage) {+ delete streamContext.usageMissingDiagnostics;const usage = chunk.usage;return { data: convertOpenAIUsage(usage, payload), id: chunk.id, type: 'usage' };}@@ -665,6 +697,6 @@ export const OpenAIStream = (}),).pipeThrough(createSSEProtocolTransformer((c) => c, streamStack))- .pipeThrough(createCallbacksTransformer(callbacks))+ .pipeThrough(createCallbacksTransformer(callbacks, { streamStack })));};diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.test.tsindex 3711ec973d4..529e3d9f1aa 100644--- a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts@@ -742,6 +742,7 @@ describe('OpenAIResponsesStream', () => {});it('should handle response.completed without usage', async () => {+ const onFinal = vi.fn();const mockOpenAIStream = createReadableStream([{type: 'response.created',@@ -759,10 +760,28 @@ describe('OpenAIResponsesStream', () => {},]);- const protocolStream = OpenAIResponsesStream(mockOpenAIStream);+ const protocolStream = OpenAIResponsesStream(mockOpenAIStream, {+ callbacks: { onFinal },+ payload: { apiMode: 'responses', model: 'gpt-5.4-mini', provider: 'openai' },+ });const chunks = await readStreamChunk(protocolStream);expect(chunks).toMatchSnapshot();+ expect(onFinal).toHaveBeenCalledWith(+ expect.objectContaining({+ usageMissingDiagnostics: {+ apiMode: 'responses',+ hasUsageMetadata: false,+ includeUsageRequested: undefined,+ model: 'gpt-5.4-mini',+ provider: 'openai',+ responseId: 'resp_completed_no_usage',+ source: 'openai_responses',+ terminalEventType: 'response.completed',+ terminalStatus: 'completed',+ },+ }),+ );});it('should handle unknown chunk type as data', async () => {diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.tsindex 311fac63807..8aff9574334 100644--- a/packages/model-runtime/src/core/streams/openai/responsesStream.ts+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.ts@@ -158,6 +158,7 @@ const transformOpenAIStream = (case 'response.completed': {if (chunk.response.usage) {+ delete streamContext.usageMissingDiagnostics;return {data: convertOpenAIResponseUsage(chunk.response.usage, payload),id: chunk.response.id,@@ -165,6 +166,18 @@ const transformOpenAIStream = (};}+ streamContext.usageMissingDiagnostics = {+ apiMode: 'responses',+ hasUsageMetadata: false,+ includeUsageRequested: payload?.includeUsageRequested,+ model: payload?.model,+ provider: payload?.provider,+ responseId: chunk.response.id,+ source: 'openai_responses',+ terminalEventType: chunk.type,+ terminalStatus: chunk.response.status,+ };+return { data: chunk, id: streamContext.id, type: 'data' };}@@ -227,6 +240,6 @@ export const OpenAIResponsesStream = (}),).pipeThrough(createSSEProtocolTransformer((c) => c, streamStack))- .pipeThrough(createCallbacksTransformer(callbacks))+ .pipeThrough(createCallbacksTransformer(callbacks, { streamStack })));};diff --git a/packages/model-runtime/src/core/streams/protocol.test.ts b/packages/model-runtime/src/core/streams/protocol.test.tsindex 570c88d8f6b..303b3c06a85 100644--- a/packages/model-runtime/src/core/streams/protocol.test.ts+++ b/packages/model-runtime/src/core/streams/protocol.test.ts@@ -972,6 +972,58 @@ describe('createCallbacksTransformer', () => {expect(onFinal).toHaveBeenCalledWith(expect.objectContaining({ finishReason: undefined }));});+ it('should include usageMissingDiagnostics on final data when no usage is received', async () => {+ const onFinal = vi.fn();+ const streamStack = {+ id: 'chat_1',+ usageMissingDiagnostics: {+ finishReason: 'stop',+ hasUsageMetadata: false,+ includeUsageRequested: true,+ model: 'gpt-5.4-mini',+ provider: 'openai',+ source: 'openai_chat_completions' as const,+ terminalEventType: 'chat.completion.chunk',+ },+ };+ const transformer = createCallbacksTransformer({ onFinal }, { streamStack });++ const chunks = ['event: stop\n', `data: ${JSON.stringify('stop')}\n\n`];++ await processChunks(transformer, chunks);++ expect(onFinal).toHaveBeenCalledWith(+ expect.objectContaining({+ usage: undefined,+ usageMissingDiagnostics: streamStack.usageMissingDiagnostics,+ }),+ );+ });++ it('should omit usageMissingDiagnostics when usage is received', async () => {+ const onFinal = vi.fn();+ const streamStack = {+ id: 'chat_1',+ usageMissingDiagnostics: {+ finishReason: 'stop',+ hasUsageMetadata: false,+ source: 'openai_chat_completions' as const,+ terminalEventType: 'chat.completion.chunk',+ },+ };+ const transformer = createCallbacksTransformer({ onFinal }, { streamStack });++ const chunks = ['event: usage\n', `data: ${JSON.stringify({ totalTokens: 10 })}\n\n`];++ await processChunks(transformer, chunks);++ expect(onFinal).toHaveBeenCalledWith(+ expect.not.objectContaining({+ usageMissingDiagnostics: expect.anything(),+ }),+ );+ });+it('should handle speed chunks and include in final data', async () => {const onFinal = vi.fn();const transformer = createCallbacksTransformer({ onFinal });diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.tsindex eda56044a3f..e12fdb44657 100644--- a/packages/model-runtime/src/core/streams/protocol.ts+++ b/packages/model-runtime/src/core/streams/protocol.ts@@ -2,13 +2,15 @@ import type { ChatCitationItem, ModelPerformance, ModelUsage } from '@lobechat/timport type { Pricing } from 'model-bank';import { parseToolCalls } from '../../helpers';-import type { ChatStreamCallbacks } from '../../types';+import type { ChatStreamCallbacks, OnFinishData, UsageMissingDiagnostics } from '../../types';import { AgentRuntimeErrorType } from '../../types/error';import { safeParseJSON } from '../../utils/safeParseJSON';import { nanoid } from '../../utils/uuid';import type { ComputeChatCostOptions } from '../usageConverters/utils/computeChatCost';export type ChatPayloadForTransformStream = {+ apiMode?: UsageMissingDiagnostics['apiMode'];+ includeUsageRequested?: boolean;model?: string;pricing?: Pricing;pricingOptions?: ComputeChatCostOptions;@@ -66,8 +68,34 @@ export interface StreamContext {*/tools?: Record<number, { id: string; index: number; name: string }>;usage?: ModelUsage;+ usageMissingDiagnostics?: UsageMissingDiagnostics;}+export const setOpenAIChatCompletionUsageMissingDiagnostics = (+ streamContext: StreamContext,+ payload: ChatPayloadForTransformStream | undefined,+ {+ finishReason,+ responseId,+ }: {+ finishReason?: string | null;+ responseId?: string;+ },+) => {+ streamContext.usageMissingDiagnostics = {+ apiMode: 'chat_completions',+ chunkIndex: streamContext.chunkIndex,+ finishReason,+ hasUsageMetadata: false,+ includeUsageRequested: payload?.includeUsageRequested,+ model: payload?.model,+ provider: payload?.provider,+ responseId,+ source: 'openai_chat_completions',+ terminalEventType: 'chat.completion.chunk',+ };+};+export interface StreamProtocolChunk {data: any;id?: string;@@ -401,7 +429,10 @@ export const createSSEProtocolTransformer = (});};-export function createCallbacksTransformer(cb: ChatStreamCallbacks | undefined) {+export function createCallbacksTransformer(+ cb: ChatStreamCallbacks | undefined,+ options?: { streamStack?: StreamContext },+) {const textEncoder = new TextEncoder();let aggregatedText = '';let aggregatedThinking: string | undefined = undefined;@@ -419,7 +450,7 @@ export function createCallbacksTransformer(cb: ChatStreamCallbacks | undefined)return new TransformStream<string, Uint8Array>({async flush(): Promise<void> {- const data = {+ const data: OnFinishData = {error: streamError,finishReason,grounding,@@ -429,6 +460,10 @@ export function createCallbacksTransformer(cb: ChatStreamCallbacks | undefined)toolsCalling,usage,};+ const usageMissingDiagnostics = usage+ ? undefined+ : options?.streamStack?.usageMissingDiagnostics;+ if (usageMissingDiagnostics) data.usageMissingDiagnostics = usageMissingDiagnostics;if (callbacks.onCompletion) {await callbacks.onCompletion(data);diff --git a/packages/model-runtime/src/core/streams/qwen.test.ts b/packages/model-runtime/src/core/streams/qwen.test.tsindex 8131daea093..2e0066483f3 100644--- a/packages/model-runtime/src/core/streams/qwen.test.ts+++ b/packages/model-runtime/src/core/streams/qwen.test.ts@@ -82,6 +82,61 @@ describe('QwenAIStream', () => {expect(onCompletionMock).toHaveBeenCalledTimes(1);});+ it('should expose missing usage diagnostics when terminal content chunk has no usage', async () => {+ const mockOpenAIStream = new ReadableStream({+ start(controller) {+ controller.enqueue({+ choices: [+ {+ delta: { content: 'final text' },+ finish_reason: 'stop',+ index: 0,+ },+ ],+ id: 'qwen-missing-usage',+ });+ controller.close();+ },+ });+ const onFinal = vi.fn();++ const protocolStream = QwenAIStream(mockOpenAIStream, {+ callbacks: { onFinal },+ payload: {+ apiMode: 'chat_completions',+ includeUsageRequested: true,+ model: 'qwen-plus',+ provider: 'qwen',+ },+ });++ const decoder = new TextDecoder();+ const chunks: string[] = [];++ // @ts-ignore+ for await (const chunk of protocolStream) {+ chunks.push(decoder.decode(chunk, { stream: true }));+ }++ expect(chunks).toEqual(['id: qwen-missing-usage\n', 'event: text\n', 'data: "final text"\n\n']);+ expect(onFinal).toHaveBeenCalledWith(+ expect.objectContaining({+ text: 'final text',+ usageMissingDiagnostics: expect.objectContaining({+ apiMode: 'chat_completions',+ finishReason: 'stop',+ hasUsageMetadata: false,+ includeUsageRequested: true,+ model: 'qwen-plus',+ provider: 'qwen',+ responseId: 'qwen-missing-usage',+ source: 'openai_chat_completions',+ terminalEventType: 'chat.completion.chunk',+ }),+ }),+ );+ });+it('should handle tool calls', async () => {const mockOpenAIStream = new ReadableStream({start(controller) {diff --git a/packages/model-runtime/src/core/streams/qwen.ts b/packages/model-runtime/src/core/streams/qwen.tsindex a8e4b9a6871..0eae94f2350 100644--- a/packages/model-runtime/src/core/streams/qwen.ts+++ b/packages/model-runtime/src/core/streams/qwen.ts@@ -20,6 +20,7 @@ import {createSSEProtocolTransformer,createTokenSpeedCalculator,generateToolCallId,+ setOpenAIChatCompletionUsageMissingDiagnostics,} from './protocol';export const transformQwenStream = (@@ -27,6 +28,14 @@ export const transformQwenStream = (streamContext?: StreamContext,payload?: ChatPayloadForTransformStream,): StreamProtocolChunk | StreamProtocolChunk[] => {+ if (streamContext) {+ if (streamContext.chunkIndex === undefined) {+ streamContext.chunkIndex = 0;+ } else {+ streamContext.chunkIndex++;+ }+ }+if (Array.isArray(chunk.choices) && chunk.choices.length === 0 && chunk.usage) {const usage = convertOpenAIUsage({@@ -39,6 +48,7 @@ export const transformQwenStream = (if (streamContext) {streamContext.usage = usage;+ delete streamContext.usageMissingDiagnostics;}return { data: usage, id: chunk.id, type: 'usage' };@@ -119,6 +129,32 @@ export const transformQwenStream = (} as StreamProtocolToolCallChunk;}+ const usageChunk: StreamProtocolChunk | undefined = chunk.usage+ ? { data: convertOpenAIUsage(chunk.usage, payload), id: chunk.id, type: 'usage' }+ : undefined;+ const appendUsageChunk = (+ protocolChunk: StreamProtocolChunk | StreamProtocolChunk[],+ ): StreamProtocolChunk | StreamProtocolChunk[] => {+ if (!usageChunk) return protocolChunk;++ if (streamContext) delete streamContext.usageMissingDiagnostics;++ return Array.isArray(protocolChunk)+ ? [...protocolChunk, usageChunk]+ : [protocolChunk, usageChunk];+ };++ if (item.finish_reason && streamContext) {+ if (usageChunk) {+ delete streamContext.usageMissingDiagnostics;+ } else {+ setOpenAIChatCompletionUsageMissingDiagnostics(streamContext, payload, {+ finishReason: item.finish_reason,+ responseId: chunk.id,+ });+ }+ }+// DeepSeek reasoner will put thinking in the reasoning_content fieldif (item.delta &&@@ -130,10 +166,14 @@ export const transformQwenStream = (}if (typeof item.delta?.content === 'string') {- return { data: item.delta.content, id: chunk.id, type: 'text' };+ const textChunk: StreamProtocolChunk = { data: item.delta.content, id: chunk.id, type: 'text' };++ return item.finish_reason ? appendUsageChunk(textChunk) : textChunk;}if (item.finish_reason) {+ if (usageChunk) return usageChunk;+return { data: item.finish_reason, id: chunk.id, type: 'stop' };}@@ -180,5 +220,5 @@ export const QwenAIStream = (}),).pipeThrough(createSSEProtocolTransformer((c) => c, streamContext))- .pipeThrough(createCallbacksTransformer(callbacks));+ .pipeThrough(createCallbacksTransformer(callbacks, { streamStack: streamContext }));};diff --git a/packages/model-runtime/src/core/streams/spark.test.ts b/packages/model-runtime/src/core/streams/spark.test.tsindex 7bb6136cf05..814635d31f7 100644--- a/packages/model-runtime/src/core/streams/spark.test.ts+++ b/packages/model-runtime/src/core/streams/spark.test.ts@@ -7,6 +7,71 @@ import { SparkAIStream, transformSparkResponseToStream } from './spark';describe('SparkAIStream', () => {beforeAll(() => {});+ it('should expose missing usage diagnostics when terminal content chunk has no usage', async () => {+ const mockSparkStream = new ReadableStream({+ start(controller) {+ controller.enqueue({+ id: 'spark-missing-usage',+ object: 'chat.completion.chunk',+ created: 1734395014,+ model: 'max-32k',+ choices: [+ {+ delta: {+ content: 'final text',+ role: 'assistant',+ },+ finish_reason: 'stop',+ index: 0,+ },+ ],+ } as OpenAI.ChatCompletionChunk);+ controller.close();+ },+ });+ const onFinal = vi.fn();++ const protocolStream = SparkAIStream(mockSparkStream, {+ callbacks: { onFinal },+ payload: {+ apiMode: 'chat_completions',+ includeUsageRequested: true,+ model: 'spark-max',+ provider: 'spark',+ },+ });++ const decoder = new TextDecoder();+ const chunks: string[] = [];++ // @ts-ignore+ for await (const chunk of protocolStream) {+ chunks.push(decoder.decode(chunk, { stream: true }));+ }++ expect(chunks).toEqual([+ 'id: spark-missing-usage\n',+ 'event: text\n',+ 'data: "final text"\n\n',+ ]);+ expect(onFinal).toHaveBeenCalledWith(+ expect.objectContaining({+ text: 'final text',+ usageMissingDiagnostics: expect.objectContaining({+ apiMode: 'chat_completions',+ finishReason: 'stop',+ hasUsageMetadata: false,+ includeUsageRequested: true,+ model: 'spark-max',+ provider: 'spark',+ responseId: 'spark-missing-usage',+ source: 'openai_chat_completions',+ terminalEventType: 'chat.completion.chunk',+ }),+ }),+ );+ });+it('should handle reasoning content in stream', async () => {const data = [{diff --git a/packages/model-runtime/src/core/streams/spark.ts b/packages/model-runtime/src/core/streams/spark.tsindex ff265411504..0a81b253f89 100644--- a/packages/model-runtime/src/core/streams/spark.ts+++ b/packages/model-runtime/src/core/streams/spark.ts@@ -5,6 +5,7 @@ import type { ChatStreamCallbacks } from '../../types';import { convertOpenAIUsage } from '../usageConverters';import type {ChatPayloadForTransformStream,+ StreamContext,StreamProtocolChunk,StreamProtocolToolCallChunk,} from './protocol';@@ -13,6 +14,7 @@ import {createCallbacksTransformer,createSSEProtocolTransformer,generateToolCallId,+ setOpenAIChatCompletionUsageMissingDiagnostics,} from './protocol';export function transformSparkResponseToStream(data: OpenAI.ChatCompletion) {@@ -86,9 +88,20 @@ export function transformSparkResponseToStream(data: OpenAI.ChatCompletion) {export const transformSparkStream = (chunk: OpenAI.ChatCompletionChunk,+ streamContext?: StreamContext,payload?: ChatPayloadForTransformStream,): StreamProtocolChunk | StreamProtocolChunk[] => {+ if (streamContext) {+ if (streamContext.chunkIndex === undefined) {+ streamContext.chunkIndex = 0;+ } else {+ streamContext.chunkIndex++;+ }+ }+if (Array.isArray(chunk.choices) && chunk.choices.length === 0 && chunk.usage) {+ if (streamContext) delete streamContext.usageMissingDiagnostics;+return { data: convertOpenAIUsage(chunk.usage, payload), id: chunk.id, type: 'usage' };}@@ -118,13 +131,41 @@ export const transformSparkStream = (}if (item.finish_reason) {+ const usageChunk: StreamProtocolChunk | undefined = chunk.usage+ ? { data: convertOpenAIUsage(chunk.usage, payload), id: chunk.id, type: 'usage' }+ : undefined;+ const appendUsageChunk = (+ protocolChunk: StreamProtocolChunk | StreamProtocolChunk[],+ ): StreamProtocolChunk | StreamProtocolChunk[] => {+ if (!usageChunk) return protocolChunk;++ if (streamContext) delete streamContext.usageMissingDiagnostics;++ return Array.isArray(protocolChunk)+ ? [...protocolChunk, usageChunk]+ : [protocolChunk, usageChunk];+ };++ if (streamContext) {+ if (usageChunk) {+ delete streamContext.usageMissingDiagnostics;+ } else {+ setOpenAIChatCompletionUsageMissingDiagnostics(streamContext, payload, {+ finishReason: item.finish_reason,+ responseId: chunk.id,+ });+ }+ }+// one-api's streaming interface can have both finish_reason and content// {"id":"demo","model":"deepl-en","choices":[{"index":0,"delta":{"role":"assistant","content":"Introduce yourself."},"finish_reason":"stop"}]}if (typeof item.delta?.content === 'string' && !!item.delta.content) {- return { data: item.delta.content, id: chunk.id, type: 'text' };+ return appendUsageChunk({ data: item.delta.content, id: chunk.id, type: 'text' });}+ if (usageChunk) return usageChunk;+return { data: item.finish_reason, id: chunk.id, type: 'stop' };}@@ -143,6 +184,8 @@ export const transformSparkStream = ({"code":0,"message":"Success","sid":"cha000d05ef@dx196553ae415b80a432","id":"cha000d05ef@dx196553ae415b80a432","created":1745186655,"choices":[{"delta":{"role":"assistant","content":"😊"},"index":0}],"usage":{"prompt_tokens":1,"completion_tokens":418,"total_tokens":419}}*/if (chunk.usage) {+ if (streamContext) delete streamContext.usageMissingDiagnostics;+return [{ data: item.delta.content, id: chunk.id, type: 'text' },{ data: convertOpenAIUsage(chunk.usage, payload), id: chunk.id, type: 'usage' },@@ -158,6 +201,8 @@ export const transformSparkStream = (// Handle v2 endpoint usageif (chunk.usage) {+ if (streamContext) delete streamContext.usageMissingDiagnostics;+return { data: convertOpenAIUsage(chunk.usage, payload), id: chunk.id, type: 'usage' };}@@ -180,12 +225,13 @@ export const SparkAIStream = (payload?: ChatPayloadForTransformStream;} = {},) => {+ const streamContext: StreamContext = { id: '' };const readableStream =stream instanceof ReadableStream ? stream : convertIterableToStream(stream);- const transformWithPayload = (chunk: OpenAI.ChatCompletionChunk) =>- transformSparkStream(chunk, payload);+ const transformWithPayload = (chunk: OpenAI.ChatCompletionChunk, streamContext: StreamContext) =>+ transformSparkStream(chunk, streamContext, payload);return readableStream- .pipeThrough(createSSEProtocolTransformer(transformWithPayload))- .pipeThrough(createCallbacksTransformer(callbacks));+ .pipeThrough(createSSEProtocolTransformer(transformWithPayload, streamContext))+ .pipeThrough(createCallbacksTransformer(callbacks, { streamStack: streamContext }));};diff --git a/packages/model-runtime/src/core/usageConverters/index.ts b/packages/model-runtime/src/core/usageConverters/index.tsindex d4f6636920c..16fa397e307 100644--- a/packages/model-runtime/src/core/usageConverters/index.ts+++ b/packages/model-runtime/src/core/usageConverters/index.ts@@ -1,6 +1,11 @@export { buildAnthropicInitialUsage, convertAnthropicUsage } from './anthropic';export { convertGoogleAIUsage } from './google-ai';export { convertOpenAIResponseUsage, convertOpenAIUsage } from './openai';+export {+ computeChatCost,+ type ComputeChatCostOptions,+ type PricingComputationResult,+} from './utils/computeChatCost';export { computeImageCost } from './utils/computeImageCost';export { computeVideoCost } from './utils/computeVideoCost';export {diff --git a/packages/model-runtime/src/providers/azureOpenai/index.test.ts b/packages/model-runtime/src/providers/azureOpenai/index.test.tsindex aa6d1b981de..a436b0d3c06 100644--- a/packages/model-runtime/src/providers/azureOpenai/index.test.ts+++ b/packages/model-runtime/src/providers/azureOpenai/index.test.ts@@ -124,11 +124,12 @@ describe('LobeAzureOpenAI', () => {mockProdStream,expect.objectContaining({inputStartAt: expect.any(Number),- payload: {+ payload: expect.objectContaining({+ apiMode: 'responses',model: 'gpt-5.4',pricing: mockPricing,provider: 'lobehub',- },+ }),}),);});@@ -171,11 +172,12 @@ describe('LobeAzureOpenAI', () => {expect(streamsModule.OpenAIResponsesStream).toHaveBeenCalledWith(mockProdStream,expect.objectContaining({- payload: {+ payload: expect.objectContaining({+ apiMode: 'responses',model: 'gpt-5.4',pricing: mockPricing,provider: 'lobehub',- },+ }),}),);});@@ -231,11 +233,13 @@ describe('LobeAzureOpenAI', () => {mockProdStream,expect.objectContaining({inputStartAt: expect.any(Number),- payload: {+ payload: expect.objectContaining({+ apiMode: 'chat_completions',+ includeUsageRequested: true,model: 'o3',pricing: mockPricing,provider: 'lobehub',- },+ }),}),);});diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.tsindex e9c6304d9f5..e5197abfe8d 100644--- a/packages/model-runtime/src/types/chat.ts+++ b/packages/model-runtime/src/types/chat.ts@@ -240,6 +240,25 @@ export interface OnFinishData {thinking?: string;toolsCalling?: MessageToolCall[];usage?: ModelUsage;+ usageMissingDiagnostics?: UsageMissingDiagnostics;+}++export interface UsageMissingDiagnostics {+ apiMode?: 'chat_completions' | 'messages' | 'responses';+ chunkIndex?: number;+ finishReason?: string | null;+ hasUsageMetadata: boolean;+ includeUsageRequested?: boolean;+ model?: string;+ provider?: string;+ responseId?: string;+ source:+ | 'anthropic_messages'+ | 'google_generative_ai'+ | 'openai_chat_completions'+ | 'openai_responses';+ terminalEventType: string;+ terminalStatus?: string;}/**diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxindex 334b90c48d1..495c4305df4 100644--- a/src/features/Conversation/Error/index.test.tsx+++ b/src/features/Conversation/Error/index.test.tsx@@ -1,6 +1,7 @@import type * as businessConstModule from '@lobechat/business-const';import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import type * as modelRuntimeModule from '@lobechat/model-runtime';+import { AgentRuntimeErrorType } from '@lobechat/model-runtime';import type * as lobechatTypesModule from '@lobechat/types';import type * as lobehubUiModule from '@lobehub/ui';import { render, screen } from '@testing-library/react';@@ -214,6 +215,24 @@ describe('ErrorMessageExtra', () => {expect(screen.getByText('response.GoogleAIBlockReason.SAFETY')).toBeInTheDocument();});+ it('renders the business rate-limit fallback for the canonical runtime code', () => {+ serverConfigMock.enableBusinessFeatures = true;++ render(+ <ErrorMessageExtra+ error={{ message: 'response.RateLimitExceeded' }}+ data={{+ error: {+ type: AgentRuntimeErrorType.RateLimitExceeded,+ } as any,+ id: 'msg-rate-limit-runtime',+ }}+ />,+ );++ expect(screen.getByText('dynamic')).toBeInTheDocument();+ });+it('renders the auth guide when the refreshed error is missing type but still carries session code', () => {render(<ErrorMessageExtradiff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 1f86582327d..ea433ac5812 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -308,7 +308,8 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data, onRebreak;}- case AgentRuntimeErrorType.QuotaLimitReached: {+ case AgentRuntimeErrorType.QuotaLimitReached:+ case AgentRuntimeErrorType.RateLimitExceeded: {if (enableBusinessFeatures) return <QuotaLimitError id={data.id} />;break;}