🤯 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: guard missing route attempt context (#16574)
YuTengjing0cadb0212108
diff --git a/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts b/apps/server/src/routers/lambda/__tests__/aiProvider.test.tsindex 66a421c3b17..57b7c44974f 100644--- a/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts@@ -1,12 +1,14 @@// @vitest-environment nodeimport type * as BusinessConst from '@lobechat/business-const';import { OFFICIAL_PROVIDER_DISABLE_ERROR } from '@lobechat/business-const';+import { RequestTrigger } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';import { AiProviderModel } from '@/database/models/aiProvider';import { AiInfraRepos } from '@/database/repositories/aiInfra';import { getServerGlobalConfig } from '@/server/globalConfig';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { type AiProviderDetailItem, type AiProviderRuntimeState } from '@/types/aiProvider';import { aiProviderRouter } from '../aiProvider';@@ -16,6 +18,9 @@ vi.mock('@/server/modules/KeyVaultsEncrypt');vi.mock('@/database/repositories/aiInfra');vi.mock('@/database/models/aiProvider');vi.mock('@/database/models/user');+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));vi.mock('@lobechat/business-const', async () => {const actual = await vi.importActual<typeof BusinessConst>('@lobechat/business-const');@@ -70,6 +75,34 @@ describe('aiProviderRouter', () => {userId: mockUserId,});+ describe('checkProviderConnectivity', () => {+ it('should pass api trigger metadata to the runtime connectivity check', async () => {+ const mockChat = vi.fn().mockResolvedValue({ ok: true });+ const mockGetDetail = vi+ .fn()+ .mockResolvedValue({ ...mockProviderDetail, checkModel: 'gpt-4' });++ vi.mocked(AiInfraRepos).prototype.getAiProviderDetail = mockGetDetail;+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);++ const caller = aiProviderRouter.createCaller(createMockContext());+ const result = await caller.checkProviderConnectivity({ id: mockProviderId });++ expect(result).toEqual({ model: 'gpt-4', ok: true });+ expect(mockChat).toHaveBeenCalledWith(+ {+ messages: [{ content: 'Hi', role: 'user' }],+ model: 'gpt-4',+ stream: false,+ temperature: 0,+ },+ {+ metadata: { trigger: RequestTrigger.Api },+ },+ );+ });+ });+describe('createAiProvider', () => {it('should create a new AI provider', async () => {const mockCreate = vi.fn().mockResolvedValue({ id: mockProviderId });diff --git a/apps/server/src/routers/lambda/aiProvider.ts b/apps/server/src/routers/lambda/aiProvider.tsindex c81c1a1633b..ff6cbd0f8fd 100644--- a/apps/server/src/routers/lambda/aiProvider.ts+++ b/apps/server/src/routers/lambda/aiProvider.ts@@ -1,4 +1,5 @@import { isOfficialProvider, OFFICIAL_PROVIDER_DISABLE_ERROR } from '@lobechat/business-const';+import { RequestTrigger } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -22,7 +23,6 @@ import { type ProviderConfig } from '@/types/user/settings';const aiProviderProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;- const wsId = ctx.workspaceId ?? undefined;const { aiProvider } = await getServerGlobalConfig();@@ -70,12 +70,17 @@ export const aiProviderRouter = router({ctx.workspaceId ?? undefined,);- const response = await modelRuntime.chat({- messages: [{ content: 'Hi', role: 'user' }],- model,- stream: false,- temperature: 0,- });+ const response = await modelRuntime.chat(+ {+ messages: [{ content: 'Hi', role: 'user' }],+ model,+ stream: false,+ temperature: 0,+ },+ {+ metadata: { trigger: RequestTrigger.Api },+ },+ );// If we get a response without error, connectivity is okif (response.ok) {@@ -86,11 +91,11 @@ export const aiProviderRouter = router({return { error: errorBody, model, ok: false, status: response.status };} catch (error: any) {const errorType = error.errorType || error.type;- const msg = errorType- ? errorType- : typeof error === 'string'+ const msg =+ errorType ||+ (typeof error === 'string'? error- : error.message || (typeof error === 'object' ? JSON.stringify(error) : String(error));+ : error.message || (typeof error === 'object' ? JSON.stringify(error) : String(error)));return { error: msg, model, ok: false };}}),diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.tsindex 573425871e8..8d0d044d067 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts@@ -1,5 +1,5 @@import { AgentRuntimeErrorType, RequestTrigger } from '@lobechat/types';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { LobeRuntimeAI } from '../BaseAI';import { createRouterRuntime } from './createRuntime';@@ -9,6 +9,11 @@ describe('createRouterRuntime', () => {vi.resetModules();});+ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ });+describe('initialization', () => {it('should throw NoAvailableProvider error when routers array is empty', async () => {const Runtime = createRouterRuntime({@@ -138,7 +143,7 @@ describe('createRouterRuntime', () => {],});- const runtime = new Runtime();+ const runtime = new Runtime({ userId: 'user-1' });const metadata: Record<string, unknown> = { traceId: 'trace-1', trigger: 'chat' };await runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 }, { metadata });@@ -155,6 +160,152 @@ describe('createRouterRuntime', () => {);});+ it('should throw in development when lobehub route attempt is missing trigger', async () => {+ vi.stubEnv('NODE_ENV', 'development');+ const mockChat = vi.fn().mockResolvedValue('chat-response');++ class MockRuntime implements LobeRuntimeAI {+ chat = mockChat;+ }++ const Runtime = createRouterRuntime({+ id: 'lobehub',+ routers: [+ {+ apiType: 'openai',+ models: ['gpt-4'],+ options: { id: 'channel-1' },+ runtime: MockRuntime as any,+ },+ ],+ });++ const runtime = new Runtime({ userId: 'user-1' });++ await expect(+ runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 }),+ ).rejects.toThrow('"missingTrigger":true');+ expect(mockChat).not.toHaveBeenCalled();+ });++ it('should throw in development when lobehub route attempt is missing user', async () => {+ vi.stubEnv('NODE_ENV', 'development');+ const mockChat = vi.fn().mockResolvedValue('chat-response');++ class MockRuntime implements LobeRuntimeAI {+ chat = mockChat;+ }++ const Runtime = createRouterRuntime({+ id: 'lobehub',+ routers: [+ {+ apiType: 'openai',+ models: ['gpt-4'],+ options: { id: 'channel-1' },+ runtime: MockRuntime as any,+ },+ ],+ });++ const runtime = new Runtime();+ const metadata = { trigger: RequestTrigger.Chat };++ await expect(+ runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 }, { metadata }),+ ).rejects.toThrow('"missingUser":true');+ expect(mockChat).not.toHaveBeenCalled();+ });++ it('should accept per-call user as the route attempt user in development', async () => {+ vi.stubEnv('NODE_ENV', 'development');+ const mockChat = vi.fn().mockResolvedValue('chat-response');+ const onRouteAttempt = vi.fn().mockResolvedValue(undefined);++ class MockRuntime implements LobeRuntimeAI {+ chat = mockChat;+ }++ const Runtime = createRouterRuntime({+ id: 'lobehub',+ onRouteAttempt,+ routers: [+ {+ apiType: 'openai',+ models: ['gpt-4'],+ options: { id: 'channel-1' },+ runtime: MockRuntime as any,+ },+ ],+ });++ const runtime = new Runtime();+ const metadata = { trigger: RequestTrigger.Chat };++ await runtime.chat(+ { messages: [], model: 'gpt-4', temperature: 0.7 },+ { metadata, user: 'user-1' },+ );++ expect(mockChat).toHaveBeenCalled();+ expect(onRouteAttempt).toHaveBeenCalledWith(+ expect.objectContaining({+ userId: 'user-1',+ }),+ );+ });++ it('should log missing route attempt context outside development without filtering by model', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const mockChat = vi.fn().mockResolvedValue('chat-response');++ class MockRuntime implements LobeRuntimeAI {+ chat = mockChat;+ }++ const Runtime = createRouterRuntime({+ id: 'lobehub',+ routers: [+ {+ apiType: 'openai',+ models: ['claude-3-sonnet'],+ options: { id: 'channel-1' },+ runtime: MockRuntime as any,+ },+ ],+ });++ const runtime = new Runtime();+ const result = await runtime.chat({+ messages: [{ content: 'do-not-log', role: 'user' }],+ model: 'claude-3-sonnet',+ temperature: 0.7,+ tools: [{ function: { name: 'secret_tool' }, type: 'function' }],+ });++ expect(result).toBe('chat-response');+ expect(consoleError).toHaveBeenCalledWith('[RouteAttemptMissingContext]', expect.any(String));++ const rawDiagnostic = consoleError.mock.calls[0][1] as string;+ const diagnostic = JSON.parse(rawDiagnostic);++ expect(diagnostic).toEqual(+ expect.objectContaining({+ apiType: 'openai',+ channelId: 'channel-1',+ metadataKeys: [],+ missingTrigger: true,+ missingUser: true,+ model: 'claude-3-sonnet',+ optionUserPresent: false,+ runtimeUserIdPresent: false,+ toolsCount: 1,+ }),+ );+ expect(rawDiagnostic).not.toContain('do-not-log');+ expect(rawDiagnostic).not.toContain('secret_tool');+ });+it('should not attach route attempt metadata for non-lobehub runtime', async () => {const mockChat = vi.fn().mockResolvedValue('chat-response');@@ -1339,8 +1490,11 @@ describe('createRouterRuntime', () => {],});- const runtime = new OuterRuntime();- await runtime.chat({ messages: [], model: 'deepseek-v4-pro', temperature: 0.7 });+ const runtime = new OuterRuntime({ userId: 'user-1' });+ await runtime.chat(+ { messages: [], model: 'deepseek-v4-pro', temperature: 0.7 },+ { metadata: { trigger: RequestTrigger.Chat } },+ );expect(constructorOptions[0]).toEqual(expect.objectContaining({ id: 'lobehub' }));});diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex 5a67c6f20f8..5cc26214685 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -126,6 +126,19 @@ interface RouteAttemptMetadata {totalOptions: number;}+interface RouteAttemptContext {+ metadata?: Record<string, unknown>;+ toolsCount?: number;+ user?: string;+}++interface RouteAttemptContextValidationParams extends RouteAttemptContext {+ apiType: string;+ channelId?: string;+ model: string;+ routerId?: string;+}+export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any> {apiKey?: string;chatCompletion?: {@@ -218,6 +231,50 @@ export const createRouterRuntime = ({metadata.routeAttempt = routeAttempt;}+ private validateRouteAttemptContext({+ apiType,+ channelId,+ metadata,+ model,+ routerId,+ toolsCount,+ user,+ }: RouteAttemptContextValidationParams) {+ const runtimeUserId =+ typeof this._options.userId === 'string' ? this._options.userId : undefined;+ const effectiveUserId = runtimeUserId || user;+ const trigger = metadata?.trigger;+ const traceId = typeof metadata?.traceId === 'string' ? metadata.traceId : undefined;++ if (this._id !== 'lobehub' || (effectiveUserId && trigger)) return effectiveUserId;++ const diagnostic = {+ apiType,+ channelId,+ metadataKeys: Object.keys(metadata ?? {}),+ missingTrigger: !trigger,+ missingUser: !effectiveUserId,+ model,+ optionUserPresent: Boolean(user),+ providerId: this._id,+ routerId,+ runtimeUserIdPresent: Boolean(runtimeUserId),+ stack: new Error('RouteAttemptMissingContext').stack?.split('\n').slice(0, 20),+ toolsCount: toolsCount ?? 0,+ traceId,+ trigger,+ };++ // Example bug: modelRuntime.chat(payload) without metadata would record trigger=null.+ if (process.env.NODE_ENV === 'development') {+ throw new Error(`[RouteAttemptMissingContext] ${JSON.stringify(diagnostic)}`);+ }++ console.error('[RouteAttemptMissingContext]', JSON.stringify(diagnostic));++ return effectiveUserId;+ }+constructor(options: LobeClientOptions & Record<string, any> = {}) {const startedAt = Date.now();this._options = {@@ -445,9 +502,10 @@ export const createRouterRuntime = ({private async runWithFallback<T>(model: string,requestHandler: (runtime: LobeRuntimeAI) => Promise<T>,- metadata?: Record<string, unknown>,+ routeContext: RouteAttemptContext = {},): Promise<T> {const totalStartedAt = Date.now();+ const { metadata, toolsCount, user } = routeContext;const matchedRouter = await this.resolveMatchedRouter(model);const routerOptions = this.normalizeRouterOptions(matchedRouter);const totalOptions = routerOptions.length;@@ -481,6 +539,15 @@ export const createRouterRuntime = ({remark,runtime,} = await this.createRuntimeFromOption(matchedRouter, optionItem);+ const routeAttemptUserId = this.validateRouteAttemptContext({+ apiType: resolvedApiType,+ channelId,+ metadata,+ model,+ routerId: matchedRouter.id,+ toolsCount,+ user,+ });try {if (this._id === 'lobehub') {@@ -543,7 +610,7 @@ export const createRouterRuntime = ({remark,routerId: matchedRouter.id,success: true,- userId: this._options.userId,+ userId: routeAttemptUserId,}).catch((e) => {log('onRouteAttempt callback error: %O', e);@@ -591,7 +658,7 @@ export const createRouterRuntime = ({remark,routerId: matchedRouter.id,success: false,- userId: this._options.userId,+ userId: routeAttemptUserId,}).catch((e) => {log('onRouteAttempt callback error: %O', e);@@ -705,7 +772,11 @@ export const createRouterRuntime = ({return await this.runWithFallback(payload.model,(runtime) => runtime.chat!(payload, options),- options?.metadata,+ {+ metadata: options?.metadata,+ toolsCount: payload.tools?.length ?? 0,+ user: options?.user,+ },);} catch (e) {if (params.chatCompletion?.handleError) {@@ -724,7 +795,7 @@ export const createRouterRuntime = ({return this.runWithFallback(payload.model,(runtime) => runtime.createImage!(payload, options),- options?.metadata,+ { metadata: options?.metadata },);}@@ -732,7 +803,7 @@ export const createRouterRuntime = ({return this.runWithFallback(payload.model,(runtime) => runtime.createVideo!(payload, options),- options?.metadata,+ { metadata: options?.metadata },);}@@ -764,7 +835,11 @@ export const createRouterRuntime = ({return this.runWithFallback(payload.model,(runtime) => runtime.generateObject!(payload, options),- options?.metadata,+ {+ metadata: options?.metadata,+ toolsCount: payload.tools?.length ?? 0,+ user: options?.user,+ },);}@@ -772,19 +847,26 @@ export const createRouterRuntime = ({return this.runWithFallback(payload.model,(runtime) => runtime.embeddings!(payload, options),- options?.metadata,+ { metadata: options?.metadata, user: options?.user },);}async textToSpeech(payload: TextToSpeechPayload, options?: EmbeddingsOptions) {- return this.runWithFallback(payload.model, (runtime) =>- runtime.textToSpeech!(payload, options),+ return this.runWithFallback(+ payload.model,+ (runtime) => runtime.textToSpeech!(payload, options),+ {+ metadata: options?.metadata,+ user: options?.user,+ },);}async transcribe(payload: ASRPayload, options?: ASROptions) {- return this.runWithFallback(payload.model, (runtime) =>- runtime.transcribe!(payload, options),+ return this.runWithFallback(+ payload.model,+ (runtime) => runtime.transcribe!(payload, options),+ { user: options?.user },);}};