Skip to content

🤯 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.

🐛 fix: fix tool call message content missing (#11116)

Arvin Xu885964e1bcf8
diff --git a/packages/database/src/client/db.test.ts b/packages/database/src/client/db.test.ts
deleted file mode 100644
index d3cbc786ba3..00000000000
--- a/packages/database/src/client/db.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { PGlite } from '@electric-sql/pglite';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-vi.mock('@electric-sql/pglite', () => ({
- PGlite: vi.fn(() => ({})),
-}));
-
-vi.mock('@electric-sql/pglite/vector', () => ({
- vector: vi.fn(),
-}));
-
-vi.mock('drizzle-orm/pglite', () => ({
- drizzle: vi.fn(() => ({
- dialect: {
- migrate: vi.fn().mockResolvedValue(undefined),
- },
- })),
-}));
-
-beforeEach(() => {
- vi.clearAllMocks();
- vi.resetModules();
-});
-
-describe('DatabaseManager', () => {
- describe('initializeDB', () => {
- it('should initialize database with PGlite', async () => {
- const { initializeDB } = await import('./db');
- await initializeDB();
-
- expect(PGlite).toHaveBeenCalledWith('idb://lobechat', {
- extensions: { vector: expect.any(Function) },
- relaxedDurability: true,
- });
- });
-
- it('should only initialize once when called multiple times', async () => {
- const { initializeDB } = await import('./db');
- await Promise.all([initializeDB(), initializeDB()]);
-
- expect(PGlite).toHaveBeenCalledTimes(1);
- });
- });
-
- describe('clientDB proxy', () => {
- it('should provide access to database after initialization', async () => {
- const { clientDB, initializeDB } = await import('./db');
- await initializeDB();
- expect(clientDB).toBeDefined();
- });
- });
-});
diff --git a/packages/database/src/client/db.ts b/packages/database/src/client/db.ts
deleted file mode 100644
index 499138d25a0..00000000000
--- a/packages/database/src/client/db.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { PGlite } from '@electric-sql/pglite';
-import { vector } from '@electric-sql/pglite/vector';
-import { sql } from 'drizzle-orm';
-import { PgliteDatabase, drizzle } from 'drizzle-orm/pglite';
-import { Md5 } from 'ts-md5';
-
-import migrations from '../core/migrations.json';
-import { DrizzleMigrationModel } from '../models/drizzleMigration';
-import * as schema from '../schemas';
-
-const pgliteSchemaHashCache = 'LOBE_CHAT_PGLITE_SCHEMA_HASH';
-const DB_NAME = 'lobechat';
-
-type DrizzleInstance = PgliteDatabase<typeof schema>;
-
-class DatabaseManager {
- private static instance: DatabaseManager;
- private dbInstance: DrizzleInstance | null = null;
- private initPromise: Promise<DrizzleInstance> | null = null;
- private isLocalDBSchemaSynced = false;
-
- private constructor() {}
-
- static getInstance() {
- if (!DatabaseManager.instance) {
- DatabaseManager.instance = new DatabaseManager();
- }
- return DatabaseManager.instance;
- }
-
- private async migrate(): Promise<DrizzleInstance> {
- if (this.isLocalDBSchemaSynced) return this.db;
-
- let hash: string | undefined;
- if (typeof localStorage !== 'undefined') {
- const cacheHash = localStorage.getItem(pgliteSchemaHashCache);
- hash = Md5.hashStr(JSON.stringify(migrations));
- // if hash is the same, no need to migrate
- if (hash === cacheHash) {
- try {
- const drizzleMigration = new DrizzleMigrationModel(this.db as any);
-
- // Check if tables exist in database
- const tableCount = await drizzleMigration.getTableCounts();
-
- // If table count > 0, consider database properly initialized
- if (tableCount > 0) {
- this.isLocalDBSchemaSynced = true;
- return this.db;
- }
- } catch (error) {
- console.warn('Error checking table existence, proceeding with migration', error);
- }
- }
- }
-
- const start = Date.now();
- try {
- // @ts-expect-error - migrate internal API
- await this.db.dialect.migrate(migrations, this.db.session, {});
-
- if (typeof localStorage !== 'undefined' && hash) {
- localStorage.setItem(pgliteSchemaHashCache, hash);
- }
-
- this.isLocalDBSchemaSynced = true;
- console.info(`🗂 Migration success, take ${Date.now() - start}ms`);
- } catch (cause) {
- console.error('❌ Local database schema migration failed', cause);
- throw cause;
- }
-
- return this.db;
- }
-
- async initialize(): Promise<DrizzleInstance> {
- if (this.initPromise) return this.initPromise;
-
- this.initPromise = (async () => {
- if (this.dbInstance) return this.dbInstance;
-
- const time = Date.now();
-
- // 直接使用 pglite,自动处理 wasm 加载
- const pglite = new PGlite(`idb://${DB_NAME}`, {
- extensions: { vector },
- relaxedDurability: true,
- });
-
- this.dbInstance = drizzle({ client: pglite, schema });
-
- await this.migrate();
-
- console.log(`✅ Database initialized in ${Date.now() - time}ms`);
-
- return this.dbInstance;
- })();
-
- return this.initPromise;
- }
-
- get db(): DrizzleInstance {
- if (!this.dbInstance) {
- throw new Error('Database not initialized. Please call initialize() first.');
- }
- return this.dbInstance;
- }
-
- createProxy(): DrizzleInstance {
- return new Proxy({} as DrizzleInstance, {
- get: (target, prop) => {
- return this.db[prop as keyof DrizzleInstance];
- },
- });
- }
-
- async resetDatabase(): Promise<void> {
- // 1. Close existing PGlite connection
- if (this.dbInstance) {
- try {
- // @ts-ignore
- await (this.dbInstance.session as any).client.close();
- console.log('PGlite instance closed successfully.');
- } catch (e) {
- console.error('Error closing PGlite instance:', e);
- }
- }
-
- // 2. Reset database instance and initialization state
- this.dbInstance = null;
- this.initPromise = null;
- this.isLocalDBSchemaSynced = false;
-
- // 3. Delete IndexedDB database
- return new Promise<void>((resolve, reject) => {
- if (typeof indexedDB === 'undefined') {
- console.warn('IndexedDB is not available, cannot delete database');
- resolve();
- return;
- }
-
- const dbName = `/pglite/${DB_NAME}`;
- const request = indexedDB.deleteDatabase(dbName);
-
- request.onsuccess = () => {
- console.log(`✅ Database '${dbName}' reset successfully`);
-
- if (typeof localStorage !== 'undefined') {
- localStorage.removeItem(pgliteSchemaHashCache);
- }
-
- resolve();
- };
-
- // eslint-disable-next-line unicorn/prefer-add-event-listener
- request.onerror = (event) => {
- const error = (event.target as IDBOpenDBRequest)?.error;
- console.error(`❌ Error resetting database '${dbName}':`, error);
- reject(
- new Error(
- `Failed to reset database '${dbName}'. Error: ${error?.message || 'Unknown error'}`,
- ),
- );
- };
-
- request.onblocked = (event) => {
- console.warn(`Deletion of database '${dbName}' is blocked.`, event);
- reject(
- new Error(
- `Failed to reset database '${dbName}' because it is blocked by other open connections.`,
- ),
- );
- };
- });
- }
-}
-
-// Export singleton
-const dbManager = DatabaseManager.getInstance();
-
-export const clientDB = dbManager.createProxy();
-
-export const initializeDB = () => dbManager.initialize();
-
-export const resetClientDatabase = async () => {
- await dbManager.resetDatabase();
-};
-
-export const updateMigrationRecord = async (migrationHash: string) => {
- await clientDB.execute(
- sql`INSERT INTO "drizzle"."__drizzle_migrations" ("hash", "created_at") VALUES (${migrationHash}, ${Date.now()});`,
- );
-
- await initializeDB();
-};
diff --git a/packages/database/src/client/type.ts b/packages/database/src/client/type.ts
deleted file mode 100644
index 2c7dd2e17be..00000000000
--- a/packages/database/src/client/type.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export interface InitMeta {
- dbName: string;
- fsBundle: Blob;
- vectorBundlePath: string;
- wasmModule: WebAssembly.Module;
-}
diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.ts
index 212d9306a31..5867ae03d6e 100644
--- a/packages/database/src/models/user.ts
+++ b/packages/database/src/models/user.ts
@@ -165,6 +165,14 @@ export class UserModel {
return this.db.query.userSettings.findFirst({ where: eq(userSettings.id, this.userId) });
};
+ getUserPreference = async (): Promise<UserPreference | undefined> => {
+ const user = await this.db.query.users.findFirst({
+ columns: { preference: true },
+ where: eq(users.id, this.userId),
+ });
+ return user?.preference as UserPreference | undefined;
+ };
+
getUserSettingsDefaultAgentConfig = async () => {
const result = await this.db
.select({ defaultAgent: userSettings.defaultAgent })
diff --git a/packages/database/src/repositories/aiInfra/index.test.ts b/packages/database/src/repositories/aiInfra/index.test.ts
index 5f17e7e1256..681dbdfa842 100644
--- a/packages/database/src/repositories/aiInfra/index.test.ts
+++ b/packages/database/src/repositories/aiInfra/index.test.ts
@@ -6,10 +6,10 @@ import type {
} from '@lobechat/types';
import { AiProviderModelListItem, EnabledAiModel } from 'model-bank';
import { DEFAULT_MODEL_PROVIDER_LIST } from 'model-bank/modelProviders';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { clientDB, initializeDB } from '@/database/client/db';
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { getTestDB } from '../../models/__tests__/_util';
+import { LobeChatDatabase } from '../../type';
import { AiInfraRepos } from './index';
const userId = 'test-user-id';
@@ -18,15 +18,18 @@ const mockProviderConfigs = {
anthropic: { enabled: false },
};
+let serverDB: LobeChatDatabase;
let repo: AiInfraRepos;
-beforeEach(async () => {
- await initializeDB();
- vi.clearAllMocks();
-
- repo = new AiInfraRepos(clientDB as any, userId, mockProviderConfigs);
+beforeAll(async () => {
+ serverDB = await getTestDB();
}, 30000);
+beforeEach(() => {
+ vi.clearAllMocks();
+ repo = new AiInfraRepos(serverDB, userId, mockProviderConfigs);
+});
+
describe('AiInfraRepos', () => {
describe('getAiProviderList', () => {
it('should merge builtin and user providers correctly', async () => {
diff --git a/packages/database/src/repositories/dataExporter/index.test.ts b/packages/database/src/repositories/dataExporter/index.test.ts
index faefd74eacf..099927dbddb 100644
--- a/packages/database/src/repositories/dataExporter/index.test.ts
+++ b/packages/database/src/repositories/dataExporter/index.test.ts
@@ -1,7 +1,6 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { clientDB, initializeDB } from '@/database/client/db';
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { getTestDB } from '../../models/__tests__/_util';
import {
agents,
agentsKnowledgeBases,
@@ -21,7 +20,7 @@ import {
import { LobeChatDatabase } from '../../type';
import { DATA_EXPORT_CONFIG, DataExporterRepos } from './index';
-let db = clientDB as LobeChatDatabase;
+let db: LobeChatDatabase;
// 设置测试数据
describe('DataExporterRepos', () => {
@@ -38,7 +37,11 @@ describe('DataExporterRepos', () => {
};
// 设置测试环境
- let userId: string = testIds.userId;
+ const userId: string = testIds.userId;
+
+ beforeAll(async () => {
+ db = await getTestDB();
+ }, 30000);
const setupTestData = async () => {
await db.transaction(async (trx) => {
@@ -152,10 +155,9 @@ describe('DataExporterRepos', () => {
};
beforeEach(async () => {
- // 创建内存数据库
- await initializeDB();
-
- // 插入测试数据
+ // 清理并插入测试数据
+ await db.delete(users);
+ await db.delete(globalFiles);
await setupTestData();
}, 30000);
diff --git a/packages/database/src/repositories/tableViewer/index.test.ts b/packages/database/src/repositories/tableViewer/index.test.ts
index cfbd888499c..d1334669699 100644
--- a/packages/database/src/repositories/tableViewer/index.test.ts
+++ b/packages/database/src/repositories/tableViewer/index.test.ts
@@ -1,11 +1,10 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { clientDB, initializeDB } from '@/database/client/db';
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { getTestDB } from '../../models/__tests__/_util';
+import { LobeChatDatabase } from '../../type';
import { TableViewerRepo } from './index';
const userId = 'user-table-viewer';
-const repo = new TableViewerRepo(clientDB as any, userId);
// Mock database execution
const mockExecute = vi.fn();
@@ -13,20 +12,20 @@ const mockDB = {
execute: mockExecute,
};
-beforeEach(async () => {
- await initializeDB();
- vi.clearAllMocks();
+let serverDB: LobeChatDatabase;
+let repo: TableViewerRepo;
+
+beforeAll(async () => {
+ serverDB = await getTestDB();
+ repo = new TableViewerRepo(serverDB, userId);
}, 30000);
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
describe('TableViewerRepo', () => {
describe('getAllTables', () => {
- it('should return all tables with counts', async () => {
- const result = await repo.getAllTables();
-
- expect(result.length).toEqual(73);
- expect(result[0]).toEqual({ name: 'accounts', count: 0, type: 'BASE TABLE' });
- });
-
it('should handle custom schema', async () => {
const result = await repo.getAllTables('custom_schema');
expect(result).toBeDefined();
diff --git a/src/envs/app.ts b/src/envs/app.ts
index a52fd201bd6..14630a06ec8 100644
--- a/src/envs/app.ts
+++ b/src/envs/app.ts
@@ -82,6 +82,7 @@ export const getAppConfig = () => {
* @default false
*/
enableQueueAgentRuntime: z.boolean().optional(),
+ TELEMETRY_DISABLED: z.boolean().optional(),
},
runtimeEnv: {
// Sentry
@@ -121,6 +122,7 @@ export const getAppConfig = () => {
MARKET_TRUSTED_CLIENT_ID: process.env.MARKET_TRUSTED_CLIENT_ID,
enableQueueAgentRuntime: process.env.AGENT_RUNTIME_MODE === 'queue',
+ TELEMETRY_DISABLED: process.env.TELEMETRY_DISABLED === '1',
},
});
};
diff --git a/src/libs/trpc/lambda/middleware/index.ts b/src/libs/trpc/lambda/middleware/index.ts
index 521c451f470..9405154749b 100644
--- a/src/libs/trpc/lambda/middleware/index.ts
+++ b/src/libs/trpc/lambda/middleware/index.ts
@@ -1,3 +1,4 @@
export * from './keyVaults';
export * from './marketUserInfo';
export * from './serverDatabase';
+export * from './telemetry';
diff --git a/src/libs/trpc/lambda/middleware/telemetry.test.ts b/src/libs/trpc/lambda/middleware/telemetry.test.ts
new file mode 100644
index 00000000000..539dd19f783
--- /dev/null
+++ b/src/libs/trpc/lambda/middleware/telemetry.test.ts
@@ -0,0 +1,237 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { appEnv } from '@/envs/app';
+
+import { TelemetryContext, checkTelemetryEnabled } from './telemetry';
+
+const { mockGetUserSettings, mockGetUserPreference, MockUserModel } = vi.hoisted(() => {
+ const mockGetUserSettings = vi.fn();
+ const mockGetUserPreference = vi.fn();
+ const MockUserModel = vi.fn().mockImplementation(() => ({
+ getUserPreference: mockGetUserPreference,
+ getUserSettings: mockGetUserSettings,
+ })) as any;
+ return { MockUserModel, mockGetUserPreference, mockGetUserSettings };
+});
+
+vi.mock('@/envs/app', () => ({
+ appEnv: {
+ TELEMETRY_DISABLED: false,
+ },
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: MockUserModel,
+}));
+
+describe('checkTelemetryEnabled', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Reset appEnv mock
+ vi.mocked(appEnv).TELEMETRY_DISABLED = false;
+ // Default mock returns
+ mockGetUserSettings.mockResolvedValue(null);
+ mockGetUserPreference.mockResolvedValue(null);
+ });
+
+ describe('environment variable priority (highest)', () => {
+ it('should return telemetryEnabled: false when TELEMETRY_DISABLED=true', async () => {
+ vi.mocked(appEnv).TELEMETRY_DISABLED = true;
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ expect(result).toEqual({ telemetryEnabled: false });
+ // Should not call database
+ expect(mockGetUserSettings).not.toHaveBeenCalled();
+ });
+
+ it('should check database when TELEMETRY_DISABLED is false', async () => {
+ await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ expect(mockGetUserSettings).toHaveBeenCalled();
+ });
+
+ it('should check database when TELEMETRY_DISABLED is undefined', async () => {
+ vi.mocked(appEnv).TELEMETRY_DISABLED = undefined;
+
+ await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ expect(mockGetUserSettings).toHaveBeenCalled();
+ });
+ });
+
+ describe('user_settings.general.telemetry', () => {
+ it('should return telemetryEnabled: true when settings.general.telemetry is true and preference is not set', async () => {
+ mockGetUserSettings.mockResolvedValue({
+ general: { telemetry: true },
+ });
+ mockGetUserPreference.mockResolvedValue(null);
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ expect(result).toEqual({ telemetryEnabled: true });
+ });
+
+ it('should return telemetryEnabled: false from settings.general', async () => {
+ mockGetUserSettings.mockResolvedValue({
+ general: { telemetry: false },
+ });
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ expect(result).toEqual({ telemetryEnabled: false });
+ });
+
+ it('should check preference when settings.general.telemetry is not set', async () => {
+ mockGetUserSettings.mockResolvedValue({
+ general: { fontSize: 14 }, // no telemetry field
+ });
+ mockGetUserPreference.mockResolvedValue({ telemetry: true });
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ // Should fall back to preference.telemetry
+ expect(result).toEqual({ telemetryEnabled: true });
+ expect(mockGetUserPreference).toHaveBeenCalled();
+ });
+ });
+
+ describe('users.preference.telemetry (deprecated, fallback)', () => {
+ it('should return telemetryEnabled: true from preference.telemetry', async () => {
+ mockGetUserSettings.mockResolvedValue(null);
+ mockGetUserPreference.mockResolvedValue({ telemetry: true });
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ expect(result).toEqual({ telemetryEnabled: true });
+ });
+
+ it('should return telemetryEnabled: false from preference.telemetry', async () => {
+ mockGetUserSettings.mockResolvedValue(null);
+ mockGetUserPreference.mockResolvedValue({ telemetry: false });
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ expect(result).toEqual({ telemetryEnabled: false });
+ });
+
+ it('should use preference.telemetry when settings.general.telemetry is not false', async () => {
+ mockGetUserSettings.mockResolvedValue({
+ general: { telemetry: true },
+ });
+ mockGetUserPreference.mockResolvedValue({ telemetry: false });
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ // preference.telemetry is checked when settings.general.telemetry is not false
+ expect(result).toEqual({ telemetryEnabled: false });
+ expect(mockGetUserPreference).toHaveBeenCalled();
+ });
+
+ it('should not call getUserPreference when settings.general.telemetry is explicitly false', async () => {
+ mockGetUserSettings.mockResolvedValue({
+ general: { telemetry: false },
+ });
+ mockGetUserPreference.mockResolvedValue({ telemetry: true });
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ expect(result).toEqual({ telemetryEnabled: false });
+ expect(mockGetUserPreference).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('default value', () => {
+ it('should default to true when settings is null', async () => {
+ mockGetUserSettings.mockResolvedValue(null);
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ // Default to true (enabled) unless explicitly disabled
+ expect(result).toEqual({ telemetryEnabled: true });
+ });
+
+ it('should default to true when general is null', async () => {
+ mockGetUserSettings.mockResolvedValue({
+ general: null,
+ });
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ // Default to true (enabled) unless explicitly disabled
+ expect(result).toEqual({ telemetryEnabled: true });
+ });
+ });
+
+ describe('missing context', () => {
+ it('should return telemetryEnabled: false when userId is missing', async () => {
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: null,
+ });
+
+ expect(result).toEqual({ telemetryEnabled: false });
+ expect(mockGetUserSettings).not.toHaveBeenCalled();
+ });
+
+ it('should return telemetryEnabled: false when serverDB is missing', async () => {
+ const result = await checkTelemetryEnabled({
+ serverDB: undefined,
+ userId: 'test-user',
+ });
+
+ expect(result).toEqual({ telemetryEnabled: false });
+ expect(mockGetUserSettings).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('error handling', () => {
+ it('should return telemetryEnabled: false when getUserSettings fails', async () => {
+ mockGetUserSettings.mockRejectedValue(new Error('Database error'));
+
+ const result = await checkTelemetryEnabled({
+ serverDB: {} as TelemetryContext['serverDB'],
+ userId: 'test-user',
+ });
+
+ expect(result).toEqual({ telemetryEnabled: false });
+ });
+ });
+});
diff --git a/src/libs/trpc/lambda/middleware/telemetry.ts b/src/libs/trpc/lambda/middleware/telemetry.ts
new file mode 100644
index 00000000000..a9953f6ed28
--- /dev/null
+++ b/src/libs/trpc/lambda/middleware/telemetry.ts
@@ -0,0 +1,74 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { UserGeneralConfig } from '@lobechat/types';
+
+import { UserModel } from '@/database/models/user';
+import { appEnv } from '@/envs/app';
+
+import { trpc } from '../init';
+
+export interface TelemetryContext {
+ serverDB?: LobeChatDatabase;
+ userId?: string | null;
+}
+
+export interface TelemetryResult {
+ telemetryEnabled: boolean;
+}
+
+/**
+ * Check if telemetry is enabled for the current user
+ *
+ * Priority:
+ * 1. Environment variable TELEMETRY_DISABLED=1 → telemetryEnabled: false (highest priority)
+ * 2. User settings from database user_settings.general.telemetry (new location)
+ * 3. User preference from database users.preference.telemetry (old location, deprecated)
+ * 4. Default to true if not explicitly set
+ */
+export const checkTelemetryEnabled = async (ctx: TelemetryContext): Promise<TelemetryResult> => {
+ // Priority 1: Check environment variable (highest priority)
+ if (appEnv.TELEMETRY_DISABLED) {
+ return { telemetryEnabled: false };
+ }
+
+ // If userId or serverDB is not available, default to disabled
+ if (!ctx.userId || !ctx.serverDB) {
+ return { telemetryEnabled: false };
+ }
+
+ try {
+ const userModel = new UserModel(ctx.serverDB, ctx.userId);
+
+ // Priority 2: Check user settings (new location: settings.general.telemetry)
+ const settings = await userModel.getUserSettings();
+ const generalConfig = settings?.general as UserGeneralConfig | null | undefined;
+
+ if (generalConfig?.telemetry === false) {
+ return { telemetryEnabled: false };
+ }
+
+ // Priority 3: Check user preference (old location: preference.telemetry)
+ const preference = await userModel.getUserPreference();
+
+ if (typeof preference?.telemetry === 'boolean') {
+ return { telemetryEnabled: preference?.telemetry };
+ }
+
+ // Priority 4: Default to true if not explicitly set
+ return { telemetryEnabled: true };
+ } catch {
+ // If fetching user settings fails, default to disabled
+ return { telemetryEnabled: false };
+ }
+};
+
+/**
+ * Middleware that checks if telemetry is enabled for the current user
+ * and adds telemetryEnabled to the context
+ *
+ * Requires serverDatabase middleware to be applied first
+ */
+export const telemetry = trpc.middleware(async (opts) => {
+ const result = await checkTelemetryEnabled(opts.ctx as TelemetryContext);
+
+ return opts.next({ ctx: result });
+});
diff --git a/src/server/routers/lambda/market/index.ts b/src/server/routers/lambda/market/index.ts
index cea3422430a..7c31579c5bb 100644
--- a/src/server/routers/lambda/market/index.ts
+++ b/src/server/routers/lambda/market/index.ts
@@ -4,15 +4,9 @@ import { serialize } from 'cookie';
import debug from 'debug';
import { z } from 'zod';
-import { type ToolCallContent } from '@/libs/mcp';
-import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';
+import { publicProcedure, router } from '@/libs/trpc/lambda';
import { marketUserInfo, serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DiscoverService } from '@/server/services/discover';
-import { FileService } from '@/server/services/file';
-import {
- contentBlocksToString,
- processContentBlocks,
-} from '@/server/services/mcp/contentProcessor';
import {
AssistantSorts,
McpConnectionType,
@@ -41,93 +35,7 @@ const marketProcedure = publicProcedure
});
});
-// Procedure with user authentication for operations requiring user access token
-const authedMarketProcedure = authedProcedure
- .use(serverDatabase)
- .use(marketUserInfo)
- .use(async ({ ctx, next }) => {
- const { UserModel } = await import('@/database/models/user');
- const userModel = new UserModel(ctx.serverDB, ctx.userId);
-
- return next({
- ctx: {
- discoverService: new DiscoverService({
- accessToken: ctx.marketAccessToken,
- userInfo: ctx.marketUserInfo,
- }),
- fileService: new FileService(ctx.serverDB, ctx.userId),
- userModel,
- },
- });
- });
-
export const marketRouter = router({
- // ============================== Cloud MCP Gateway ==============================
- callCloudMcpEndpoint: authedMarketProcedure
- .input(
- z.object({
- apiParams: z.record(z.any()),
- identifier: z.string(),
- toolName: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- log('callCloudMcpEndpoint input: %O', input);
-
- try {
- // Query user_settings to get market.accessToken
- const userState = await ctx.userModel.getUserState(async () => ({}));
- const userAccessToken = userState.settings?.market?.accessToken;
-
- log('callCloudMcpEndpoint: userAccessToken exists=%s', !!userAccessToken);
-
- if (!userAccessToken) {
- throw new TRPCError({
- code: 'UNAUTHORIZED',
- message: 'User access token not found. Please sign in to Market first.',
- });
- }
-
- const cloudResult = await ctx.discoverService.callCloudMcpEndpoint({
- apiParams: input.apiParams,
- identifier: input.identifier,
- toolName: input.toolName,
- userAccessToken,
- });
- const cloudResultContent = (cloudResult?.content ?? []) as ToolCallContent[];
-
- // Format the cloud result to MCPToolCallResult format
- // Process content blocks (upload images, etc.)
- const newContent =
- cloudResult?.isError || !ctx.fileService
- ? cloudResultContent
- : // FIXME: the type assertion here is a temporary solution, need to remove it after refactoring
- await processContentBlocks(cloudResultContent, ctx.fileService);
-
- // Convert content blocks to string
- const content = contentBlocksToString(newContent);
- const state = { ...cloudResult, content: newContent };
-
- if (cloudResult?.isError) {
- return { content, state, success: true };
- }
-
- return { content, state, success: true };
- } catch (error) {
- log('Error calling cloud MCP endpoint: %O', error);
-
- // Re-throw TRPCError as-is
- if (error instanceof TRPCError) {
- throw error;
- }
-
- throw new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to call cloud MCP endpoint',
- });
- }
- }),
-
// ============================== Assistant Market ==============================
getAssistantCategories: marketProcedure
.input(
diff --git a/src/server/routers/tools/_helpers/index.ts b/src/server/routers/tools/_helpers/index.ts
new file mode 100644
index 00000000000..d18c9d48e8c
--- /dev/null
+++ b/src/server/routers/tools/_helpers/index.ts
@@ -0,0 +1 @@
+export * from './scheduleToolCallReport';
diff --git a/src/server/routers/tools/_helpers/scheduleToolCallReport.ts b/src/server/routers/tools/_helpers/scheduleToolCallReport.ts
new file mode 100644
index 00000000000..cfb4b52e111
--- /dev/null
+++ b/src/server/routers/tools/_helpers/scheduleToolCallReport.ts
@@ -0,0 +1,113 @@
+import { CURRENT_VERSION } from '@lobechat/const';
+import { type CallReportRequest } from '@lobehub/market-types';
+import { after } from 'next/server';
+
+import { DiscoverService } from '@/server/services/discover';
+
+/**
+ * Calculate byte size of object
+ */
+const calculateObjectSizeBytes = (obj: unknown): number => {
+ try {
+ const jsonString = JSON.stringify(obj);
+ return new TextEncoder().encode(jsonString).length;
+ } catch {
+ return 0;
+ }
+};
+
+export interface ToolCallReportMeta {
+ customPluginInfo?: {
+ avatar?: string;
+ description?: string;
+ name?: string;
+ };
+ isCustomPlugin?: boolean;
+ sessionId?: string;
+ version?: string;
+}
+
+export interface ScheduleToolCallReportParams {
+ /** Error code if call failed */
+ errorCode?: string;
+ /** Error message if call failed */
+ errorMessage?: string;
+ /** Plugin/tool identifier */
+ identifier: string;
+ /** Market access token for reporting */
+ marketAccessToken?: string;
+ /** MCP connection type */
+ mcpType: string;
+ /** Metadata for reporting */
+ meta?: ToolCallReportMeta;
+ /** Request payload for size calculation */
+ requestPayload: unknown;
+ /** Result for size calculation */
+ result?: unknown;
+ /** Start time of the call */
+ startTime: number;
+ /** Whether the call was successful */
+ success: boolean;
+ /** Whether telemetry is enabled */
+ telemetryEnabled: boolean;
+ /** Tool/method name */
+ toolName: string;
+}
+
+/**
+ * Schedule a tool call report to be sent after the response.
+ * Uses Next.js after() to avoid blocking the response.
+ */
+export function scheduleToolCallReport(params: ScheduleToolCallReportParams): void {
+ const {
+ telemetryEnabled,
+ marketAccessToken,
+ startTime,
+ success,
+ errorCode,
+ errorMessage,
+ result,
+ meta,
+ identifier,
+ toolName,
+ mcpType,
+ requestPayload,
+ } = params;
+
+ // Only report when telemetry is enabled and marketAccessToken exists
+ if (!telemetryEnabled || !marketAccessToken) return;
+
+ // Use Next.js after() to report after response is sent
+ after(async () => {
+ try {
+ const callDurationMs = Date.now() - startTime;
+ const requestSizeBytes = calculateObjectSizeBytes(requestPayload);
+ const responseSizeBytes = success && result ? calculateObjectSizeBytes(result) : 0;
+
+ const reportData: CallReportRequest = {
+ callDurationMs,
+ customPluginInfo: meta?.customPluginInfo,
+ errorCode,
+ errorMessage,
+ identifier,
+ isCustomPlugin: meta?.isCustomPlugin,
+ metadata: {
+ appVersion: CURRENT_VERSION,
+ mcpType,
+ },
+ methodName: toolName,
+ methodType: 'tool',
+ requestSizeBytes,
+ responseSizeBytes,
+ sessionId: meta?.sessionId,
+ success,
+ version: meta?.version || 'unknown',
+ };
+
+ const discoverService = new DiscoverService({ accessToken: marketAccessToken });
+ await discoverService.reportCall(reportData);
+ } catch (reportError) {
+ console.error('Failed to report tool call: %O', reportError);
+ }
+ });
+}
diff --git a/src/server/routers/tools/codeInterpreter.ts b/src/server/routers/tools/codeInterpreter.ts
deleted file mode 100644
index 20dfb874ce8..00000000000
--- a/src/server/routers/tools/codeInterpreter.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-import { type CodeInterpreterToolName, MarketSDK } from '@lobehub/market-sdk';
-import debug from 'debug';
-import { z } from 'zod';
-
-import { DocumentModel } from '@/database/models/document';
-import { FileModel } from '@/database/models/file';
-import { authedProcedure, router } from '@/libs/trpc/lambda';
-import { marketUserInfo, serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { generateTrustedClientToken } from '@/libs/trusted-client';
-import { FileS3 } from '@/server/modules/S3';
-
-const log = debug('lobe-server:tools:code-interpreter');
-
-const codeInterpreterProcedure = authedProcedure.use(serverDatabase).use(marketUserInfo);
-
-// Schema for tool call request
-const callToolSchema = z.object({
- /** Market access token from OIDC (stored in user settings) */
- marketAccessToken: z.string().optional(),
- params: z.record(z.any()),
- toolName: z.string(),
- // Session context for isolation
- topicId: z.string(),
- userId: z.string(),
-});
-
-// Schema for getting export file upload URL
-const getExportFileUploadUrlSchema = z.object({
- /** Original filename from sandbox */
- filename: z.string(),
- /** Topic ID for organizing files */
- topicId: z.string(),
-});
-
-// Schema for saving exported file content to document
-const saveExportedFileContentSchema = z.object({
- /** File content (text content from code-interpreter export) */
- content: z.string(),
- /** File ID to associate with the document */
- fileId: z.string(),
- /** File MIME type */
- fileType: z.string(),
- /** Filename */
- filename: z.string(),
- /** File URL */
- url: z.string(),
-});
-
-export type CallToolInput = z.infer<typeof callToolSchema>;
-export type GetExportFileUploadUrlInput = z.infer<typeof getExportFileUploadUrlSchema>;
-export type SaveExportedFileContentInput = z.infer<typeof saveExportedFileContentSchema>;
-
-export interface CallToolResult {
- error?: {
- message: string;
- name?: string;
- };
- result: any;
- sessionExpiredAndRecreated?: boolean;
- success: boolean;
-}
-
-export interface GetExportFileUploadUrlResult {
- /** The download URL after file is uploaded */
- downloadUrl: string;
- error?: {
- message: string;
- };
- /** The S3 key where file will be stored */
- key: string;
- success: boolean;
- /** Pre-signed upload URL */
- uploadUrl: string;
-}
-
-export interface SaveExportedFileContentResult {
- /** Created document ID */
- documentId?: string;
- error?: {
- message: string;
- };
- success: boolean;
-}
-
-export const codeInterpreterRouter = router({
- callTool: codeInterpreterProcedure.input(callToolSchema).mutation(async ({ input, ctx }) => {
- const { toolName, params, userId, topicId, marketAccessToken } = input;
-
- log('Calling cloud code interpreter tool: %s with params: %O', toolName, {
- params,
- topicId,
- userId,
- });
- log('Market access token available: %s', marketAccessToken ? 'yes' : 'no');
-
- // Generate trusted client token if user info is available
- const trustedClientToken = ctx.marketUserInfo
- ? generateTrustedClientToken(ctx.marketUserInfo)
- : undefined;
-
- try {
- // Initialize MarketSDK with market access token and trusted client token
- const market = new MarketSDK({
- accessToken: marketAccessToken,
- baseURL: process.env.NEXT_PUBLIC_MARKET_BASE_URL,
- trustedClientToken,
- });
-
- // Call market-sdk's runBuildInTool
- // API signature: runBuildInTool(toolName, params, context, options?)
- const response = await market.plugins.runBuildInTool(
- toolName as CodeInterpreterToolName,
- params as any,
- { topicId, userId },
- );
-
- log('Cloud code interpreter tool %s response: %O', toolName, response);
-
- if (!response.success) {
- return {
- error: {
- message: response.error?.message || 'Unknown error',
- name: response.error?.code,
- },
- result: null,
- sessionExpiredAndRecreated: false,
- success: false,
- } as CallToolResult;
- }
-
- return {
- result: response.data?.result,
- sessionExpiredAndRecreated: response.data?.sessionExpiredAndRecreated || false,
- success: true,
- } as CallToolResult;
- } catch (error) {
- log('Error calling cloud code interpreter tool %s: %O', toolName, error);
-
- return {
- error: {
- message: (error as Error).message,
- name: (error as Error).name,
- },
- result: null,
- sessionExpiredAndRecreated: false,
- success: false,
- } as CallToolResult;
- }
- }),
-
- /**
- * Generate a pre-signed upload URL for exporting files from sandbox
- * The URL can be used by the sandbox to upload the file directly to S3
- */
- getExportFileUploadUrl: codeInterpreterProcedure
- .input(getExportFileUploadUrlSchema)
-
- // TODO if upload success, should add it path to files db
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- .mutation(async ({ ctx, input }) => {
- const { filename, topicId } = input;
-
- log('Generating export file upload URL for: %s in topic: %s', filename, topicId);
-
- try {
- const s3 = new FileS3();
-
- // Generate a unique key for the exported file
- // Format: code-interpreter-exports/{topicId}/{filename}
- const key = `code-interpreter-exports/${topicId}/${filename}`;
-
- // Generate pre-signed upload URL
- const uploadUrl = await s3.createPreSignedUrl(key);
-
- // Generate download URL (pre-signed for preview)
- const downloadUrl = await s3.createPreSignedUrlForPreview(key);
-
- log('Generated upload URL for key: %s', key);
-
- return {
- downloadUrl,
- key,
- success: true,
- uploadUrl,
- } as GetExportFileUploadUrlResult;
- } catch (error) {
- log('Error generating export file upload URL: %O', error);
-
- return {
- downloadUrl: '',
- error: {
- message: (error as Error).message,
- },
- key: '',
- success: false,
- uploadUrl: '',
- } as GetExportFileUploadUrlResult;
- }
- }),
-
- /**
- * Save exported file content to documents table
- * This creates a document record linked to the file, allowing content to be retrieved
- * when querying messages with file attachments
- */
- saveExportedFileContent: codeInterpreterProcedure
- .input(saveExportedFileContentSchema)
- .use(serverDatabase)
- .mutation(async ({ ctx, input }) => {
- const { content, fileId, fileType, filename, url } = input;
-
- log('Saving exported file content: fileId=%s, filename=%s', fileId, filename);
-
- try {
- const documentModel = new DocumentModel(ctx.serverDB, ctx.userId);
- const fileModel = new FileModel(ctx.serverDB, ctx.userId);
-
- // Verify the file exists
- const file = await fileModel.findById(fileId);
- if (!file) {
- return {
- error: { message: 'File not found' },
- success: false,
- } as SaveExportedFileContentResult;
- }
-
- // Create document record with the file content
- const document = await documentModel.create({
- content,
- fileId,
- fileType,
- filename,
- source: url,
- sourceType: 'file',
- title: filename,
- totalCharCount: content.length,
- totalLineCount: content.split('\n').length,
- });
-
- log('Created document for exported file: documentId=%s, fileId=%s', document.id, fileId);
-
- return {
- documentId: document.id,
- success: true,
- } as SaveExportedFileContentResult;
- } catch (error) {
- log('Error saving exported file content: %O', error);
-
- return {
- error: { message: (error as Error).message },
- success: false,
- } as SaveExportedFileContentResult;
- }
- }),
-});
diff --git a/src/server/routers/tools/index.ts b/src/server/routers/tools/index.ts
index 8fcd51b39c4..846a7d54be2 100644
--- a/src/server/routers/tools/index.ts
+++ b/src/server/routers/tools/index.ts
@@ -1,14 +1,14 @@
import { publicProcedure, router } from '@/libs/trpc/lambda';
-import { codeInterpreterRouter } from './codeInterpreter';
import { klavisRouter } from './klavis';
+import { marketRouter } from './market';
import { mcpRouter } from './mcp';
import { searchRouter } from './search';
export const toolsRouter = router({
- codeInterpreter: codeInterpreterRouter,
healthcheck: publicProcedure.query(() => "i'm live!"),
klavis: klavisRouter,
+ market: marketRouter,
mcp: mcpRouter,
search: searchRouter,
});
diff --git a/src/server/routers/tools/market.ts b/src/server/routers/tools/market.ts
new file mode 100644
index 00000000000..a8cf1eaadca
--- /dev/null
+++ b/src/server/routers/tools/market.ts
@@ -0,0 +1,375 @@
+import { type CodeInterpreterToolName, MarketSDK } from '@lobehub/market-sdk';
+import { TRPCError } from '@trpc/server';
+import debug from 'debug';
+import { z } from 'zod';
+
+import { DocumentModel } from '@/database/models/document';
+import { FileModel } from '@/database/models/file';
+import { type ToolCallContent } from '@/libs/mcp';
+import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { marketUserInfo, serverDatabase, telemetry } from '@/libs/trpc/lambda/middleware';
+import { generateTrustedClientToken } from '@/libs/trusted-client';
+import { FileS3 } from '@/server/modules/S3';
+import { DiscoverService } from '@/server/services/discover';
+import { FileService } from '@/server/services/file';
+import {
+ contentBlocksToString,
+ processContentBlocks,
+} from '@/server/services/mcp/contentProcessor';
+
+import { scheduleToolCallReport } from './_helpers';
+
+const log = debug('lobe-server:tools:market');
+
+// ============================== Common Procedure ==============================
+const marketToolProcedure = authedProcedure
+ .use(serverDatabase)
+ .use(telemetry)
+ .use(marketUserInfo)
+ .use(async ({ ctx, next }) => {
+ const { UserModel } = await import('@/database/models/user');
+ const userModel = new UserModel(ctx.serverDB, ctx.userId);
+
+ return next({
+ ctx: {
+ discoverService: new DiscoverService({
+ accessToken: ctx.marketAccessToken,
+ userInfo: ctx.marketUserInfo,
+ }),
+ fileService: new FileService(ctx.serverDB, ctx.userId),
+ userModel,
+ },
+ });
+ });
+
+// ============================== Schema Definitions ==============================
+
+// Schema for metadata that frontend needs to pass (for cloud MCP reporting)
+const metaSchema = z
+ .object({
+ customPluginInfo: z
+ .object({
+ avatar: z.string().optional(),
+ description: z.string().optional(),
+ name: z.string().optional(),
+ })
+ .optional(),
+ isCustomPlugin: z.boolean().optional(),
+ sessionId: z.string().optional(),
+ version: z.string().optional(),
+ })
+ .optional();
+
+// Schema for code interpreter tool call request
+const callCodeInterpreterToolSchema = z.object({
+ marketAccessToken: z.string().optional(),
+ params: z.record(z.any()),
+ toolName: z.string(),
+ topicId: z.string(),
+ userId: z.string(),
+});
+
+// Schema for getting export file upload URL
+const getExportFileUploadUrlSchema = z.object({
+ filename: z.string(),
+ topicId: z.string(),
+});
+
+// Schema for saving exported file content to document
+const saveExportedFileContentSchema = z.object({
+ content: z.string(),
+ fileId: z.string(),
+ fileType: z.string(),
+ filename: z.string(),
+ url: z.string(),
+});
+
+// Schema for cloud MCP endpoint call
+const callCloudMcpEndpointSchema = z.object({
+ apiParams: z.record(z.any()),
+ identifier: z.string(),
+ meta: metaSchema,
+ toolName: z.string(),
+});
+
+// ============================== Type Exports ==============================
+export type CallCodeInterpreterToolInput = z.infer<typeof callCodeInterpreterToolSchema>;
+export type GetExportFileUploadUrlInput = z.infer<typeof getExportFileUploadUrlSchema>;
+export type SaveExportedFileContentInput = z.infer<typeof saveExportedFileContentSchema>;
+
+export interface CallToolResult {
+ error?: {
+ message: string;
+ name?: string;
+ };
+ result: any;
+ sessionExpiredAndRecreated?: boolean;
+ success: boolean;
+}
+
+export interface GetExportFileUploadUrlResult {
+ downloadUrl: string;
+ error?: {
+ message: string;
+ };
+ key: string;
+ success: boolean;
+ uploadUrl: string;
+}
+
+export interface SaveExportedFileContentResult {
+ documentId?: string;
+ error?: {
+ message: string;
+ };
+ success: boolean;
+}
+
+// ============================== Router ==============================
+export const marketRouter = router({
+ // ============================== Cloud MCP Gateway ==============================
+ callCloudMcpEndpoint: marketToolProcedure
+ .input(callCloudMcpEndpointSchema)
+ .mutation(async ({ input, ctx }) => {
+ log('callCloudMcpEndpoint input: %O', input);
+
+ const startTime = Date.now();
+ let success = true;
+ let errorCode: string | undefined;
+ let errorMessage: string | undefined;
+ let result: { content: string; state: any; success: boolean } | undefined;
+
+ try {
+ // Query user_settings to get market.accessToken
+ const userState = await ctx.userModel.getUserState(async () => ({}));
+ const userAccessToken = userState.settings?.market?.accessToken;
+
+ log('callCloudMcpEndpoint: userAccessToken exists=%s', !!userAccessToken);
+
+ if (!userAccessToken) {
+ throw new TRPCError({
+ code: 'UNAUTHORIZED',
+ message: 'User access token not found. Please sign in to Market first.',
+ });
+ }
+
+ const cloudResult = await ctx.discoverService.callCloudMcpEndpoint({
+ apiParams: input.apiParams,
+ identifier: input.identifier,
+ toolName: input.toolName,
+ userAccessToken,
+ });
+ const cloudResultContent = (cloudResult?.content ?? []) as ToolCallContent[];
+
+ // Format the cloud result to MCPToolCallResult format
+ // Process content blocks (upload images, etc.)
+ const newContent =
+ cloudResult?.isError || !ctx.fileService
+ ? cloudResultContent
+ : await processContentBlocks(cloudResultContent, ctx.fileService);
+
+ // Convert content blocks to string
+ const content = contentBlocksToString(newContent);
+ const state = { ...cloudResult, content: newContent };
+
+ result = { content, state, success: true };
+ return result;
+ } catch (error) {
+ success = false;
+ const err = error as Error;
+ errorCode = 'CALL_FAILED';
+ errorMessage = err.message;
+
+ log('Error calling cloud MCP endpoint: %O', error);
+
+ // Re-throw TRPCError as-is
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+
+ throw new TRPCError({
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to call cloud MCP endpoint',
+ });
+ } finally {
+ scheduleToolCallReport({
+ errorCode,
+ errorMessage,
+ identifier: input.identifier,
+ marketAccessToken: ctx.marketAccessToken,
+ mcpType: 'cloud',
+ meta: input.meta,
+ requestPayload: input.apiParams,
+ result,
+ startTime,
+ success,
+ telemetryEnabled: ctx.telemetryEnabled,
+ toolName: input.toolName,
+ });
+ }
+ }),
+
+ // ============================== Code Interpreter ==============================
+ callCodeInterpreterTool: marketToolProcedure
+ .input(callCodeInterpreterToolSchema)
+ .mutation(async ({ input, ctx }) => {
+ const { toolName, params, userId, topicId, marketAccessToken } = input;
+
+ log('Calling cloud code interpreter tool: %s with params: %O', toolName, {
+ params,
+ topicId,
+ userId,
+ });
+ log('Market access token available: %s', marketAccessToken ? 'yes' : 'no');
+
+ // Generate trusted client token if user info is available
+ const trustedClientToken = ctx.marketUserInfo
+ ? generateTrustedClientToken(ctx.marketUserInfo)
+ : undefined;
+
+ try {
+ // Initialize MarketSDK with market access token and trusted client token
+ const market = new MarketSDK({
+ accessToken: marketAccessToken,
+ baseURL: process.env.NEXT_PUBLIC_MARKET_BASE_URL,
+ trustedClientToken,
+ });
+
+ // Call market-sdk's runBuildInTool
+ const response = await market.plugins.runBuildInTool(
+ toolName as CodeInterpreterToolName,
+ params as any,
+ { topicId, userId },
+ );
+
+ log('Cloud code interpreter tool %s response: %O', toolName, response);
+
+ if (!response.success) {
+ return {
+ error: {
+ message: response.error?.message || 'Unknown error',
+ name: response.error?.code,
+ },
+ result: null,
+ sessionExpiredAndRecreated: false,
+ success: false,
+ } as CallToolResult;
+ }
+
+ return {
+ result: response.data?.result,
+ sessionExpiredAndRecreated: response.data?.sessionExpiredAndRecreated || false,
+ success: true,
+ } as CallToolResult;
+ } catch (error) {
+ log('Error calling cloud code interpreter tool %s: %O', toolName, error);
+
+ return {
+ error: {
+ message: (error as Error).message,
+ name: (error as Error).name,
+ },
+ result: null,
+ sessionExpiredAndRecreated: false,
+ success: false,
+ } as CallToolResult;
+ }
+ }),
+
+ /**
+ * Generate a pre-signed upload URL for exporting files from sandbox
+ */
+ getExportFileUploadUrl: marketToolProcedure
+ .input(getExportFileUploadUrlSchema)
+ .mutation(async ({ input }) => {
+ const { filename, topicId } = input;
+
+ log('Generating export file upload URL for: %s in topic: %s', filename, topicId);
+
+ try {
+ const s3 = new FileS3();
+
+ // Generate a unique key for the exported file
+ const key = `code-interpreter-exports/${topicId}/${filename}`;
+
+ // Generate pre-signed upload URL
+ const uploadUrl = await s3.createPreSignedUrl(key);
+
+ // Generate download URL (pre-signed for preview)
+ const downloadUrl = await s3.createPreSignedUrlForPreview(key);
+
+ log('Generated upload URL for key: %s', key);
+
+ return {
+ downloadUrl,
+ key,
+ success: true,
+ uploadUrl,
+ } as GetExportFileUploadUrlResult;
+ } catch (error) {
+ log('Error generating export file upload URL: %O', error);
+
+ return {
+ downloadUrl: '',
+ error: {
+ message: (error as Error).message,
+ },
+ key: '',
+ success: false,
+ uploadUrl: '',
+ } as GetExportFileUploadUrlResult;
+ }
+ }),
+
+ /**
+ * Save exported file content to documents table
+ */
+ saveExportedFileContent: marketToolProcedure
+ .input(saveExportedFileContentSchema)
+ .mutation(async ({ ctx, input }) => {
+ const { content, fileId, fileType, filename, url } = input;
+
+ log('Saving exported file content: fileId=%s, filename=%s', fileId, filename);
+
+ try {
+ const documentModel = new DocumentModel(ctx.serverDB, ctx.userId);
+ const fileModel = new FileModel(ctx.serverDB, ctx.userId);
+
+ // Verify the file exists
+ const file = await fileModel.findById(fileId);
+ if (!file) {
+ return {
+ error: { message: 'File not found' },
+ success: false,
+ } as SaveExportedFileContentResult;
+ }
+
+ // Create document record with the file content
+ const document = await documentModel.create({
+ content,
+ fileId,
+ fileType,
+ filename,
+ source: url,
+ sourceType: 'file',
+ title: filename,
+ totalCharCount: content.length,
+ totalLineCount: content.split('\n').length,
+ });
+
+ log('Created document for exported file: documentId=%s, fileId=%s', document.id, fileId);
+
+ return {
+ documentId: document.id,
+ success: true,
+ } as SaveExportedFileContentResult;
+ } catch (error) {
+ log('Error saving exported file content: %O', error);
+
+ return {
+ error: { message: (error as Error).message },
+ success: false,
+ } as SaveExportedFileContentResult;
+ }
+ }),
+});
diff --git a/src/server/routers/tools/mcp.ts b/src/server/routers/tools/mcp.ts
index d96682156e3..9e01c039ffb 100644
--- a/src/server/routers/tools/mcp.ts
+++ b/src/server/routers/tools/mcp.ts
@@ -8,11 +8,13 @@ import { z } from 'zod';
import { type ToolCallContent } from '@/libs/mcp';
import { authedProcedure, router } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { serverDatabase, telemetry } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
import { mcpService } from '@/server/services/mcp';
import { processContentBlocks } from '@/server/services/mcp/contentProcessor';
+import { scheduleToolCallReport } from './_helpers';
+
// Define Zod schemas for MCP Client parameters
const httpParamsSchema = z.object({
auth: StreamableHTTPAuthSchema,
@@ -41,13 +43,36 @@ const checkStdioEnvironment = (params: z.infer<typeof mcpClientParamsSchema>) =>
}
};
-const mcpProcedure = authedProcedure.use(serverDatabase).use(async ({ ctx, next }) => {
- return next({
- ctx: {
- fileService: new FileService(ctx.serverDB, ctx.userId),
- },
+// Schema for metadata that frontend needs to pass (fields that backend cannot determine)
+const metaSchema = z
+ .object({
+ // Custom plugin info (only for custom plugins)
+ customPluginInfo: z
+ .object({
+ avatar: z.string().optional(),
+ description: z.string().optional(),
+ name: z.string().optional(),
+ })
+ .optional(),
+ // Whether this is a custom plugin
+ isCustomPlugin: z.boolean().optional(),
+ // Session/topic ID
+ sessionId: z.string().optional(),
+ // Plugin manifest version
+ version: z.string().optional(),
+ })
+ .optional();
+
+const mcpProcedure = authedProcedure
+ .use(serverDatabase)
+ .use(telemetry)
+ .use(async ({ ctx, next }) => {
+ return next({
+ ctx: {
+ fileService: new FileService(ctx.serverDB, ctx.userId),
+ },
+ });
});
-});
export const mcpRouter = router({
getStreamableMcpServerManifest: mcpProcedure
@@ -100,8 +125,9 @@ export const mcpRouter = router({
callTool: mcpProcedure
.input(
z.object({
- params: mcpClientParamsSchema, // Use the unified schema for client params
args: z.any(), // Arguments for the tool call
+ meta: metaSchema, // Optional metadata for reporting
+ params: mcpClientParamsSchema, // Use the unified schema for client params
toolName: z.string(),
}),
)
@@ -109,17 +135,48 @@ export const mcpRouter = router({
// Stdio check can be done here or rely on the service/client layer
checkStdioEnvironment(input.params);
- // Create a closure that binds fileService and userId to processContentBlocks
- const boundProcessContentBlocks = async (blocks: ToolCallContent[]) => {
- return processContentBlocks(blocks, ctx.fileService);
- };
-
- // Pass the validated params, toolName, args, and bound processContentBlocks to the service
- return await mcpService.callTool({
- clientParams: input.params,
- toolName: input.toolName,
- argsStr: input.args,
- processContentBlocks: boundProcessContentBlocks,
- });
+ const startTime = Date.now();
+ let success = true;
+ let errorCode: string | undefined;
+ let errorMessage: string | undefined;
+ let result: Awaited<ReturnType<typeof mcpService.callTool>> | undefined;
+
+ try {
+ // Create a closure that binds fileService and userId to processContentBlocks
+ const boundProcessContentBlocks = async (blocks: ToolCallContent[]) => {
+ return processContentBlocks(blocks, ctx.fileService);
+ };
+
+ // Pass the validated params, toolName, args, and bound processContentBlocks to the service
+ result = await mcpService.callTool({
+ argsStr: input.args,
+ clientParams: input.params,
+ processContentBlocks: boundProcessContentBlocks,
+ toolName: input.toolName,
+ });
+
+ return result;
+ } catch (error) {
+ success = false;
+ const err = error as Error;
+ errorCode = 'CALL_FAILED';
+ errorMessage = err.message;
+ throw error;
+ } finally {
+ scheduleToolCallReport({
+ errorCode,
+ errorMessage,
+ identifier: input.params.name,
+ marketAccessToken: ctx.marketAccessToken,
+ mcpType: 'http',
+ meta: input.meta,
+ requestPayload: input.args,
+ result,
+ startTime,
+ success,
+ telemetryEnabled: ctx.telemetryEnabled,
+ toolName: input.toolName,
+ });
+ }
}),
});
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 173fb75533c..7b6f3bd9513 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -129,8 +129,6 @@ class ChatService {
const targetAgentId = getTargetAgentId(agentId);
- console.log('[chatService.createAssistantMessage] Resolving with scope:', scope);
-
// Resolve agent config with builtin agent runtime config merged
// plugins is already merged (runtime plugins > agent config plugins)
const {
diff --git a/src/services/codeInterpreter.ts b/src/services/codeInterpreter.ts
index 39b5800eee4..d5fbc6ff949 100644
--- a/src/services/codeInterpreter.ts
+++ b/src/services/codeInterpreter.ts
@@ -1,12 +1,12 @@
import { toolsClient } from '@/libs/trpc/client';
import type {
- CallToolInput,
+ CallCodeInterpreterToolInput,
CallToolResult,
GetExportFileUploadUrlInput,
GetExportFileUploadUrlResult,
SaveExportedFileContentInput,
SaveExportedFileContentResult,
-} from '@/server/routers/tools/codeInterpreter';
+} from '@/server/routers/tools/market';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/slices/settings/selectors/settings';
@@ -32,7 +32,7 @@ class CodeInterpreterService {
): Promise<CallToolResult> {
const marketAccessToken = getMarketAccessToken();
- const input: CallToolInput = {
+ const input: CallCodeInterpreterToolInput = {
marketAccessToken,
params,
toolName,
@@ -40,7 +40,7 @@ class CodeInterpreterService {
userId: context.userId,
};
- return toolsClient.codeInterpreter.callTool.mutate(input);
+ return toolsClient.market.callCodeInterpreterTool.mutate(input);
}
/**
@@ -57,7 +57,7 @@ class CodeInterpreterService {
topicId,
};
- return toolsClient.codeInterpreter.getExportFileUploadUrl.mutate(input);
+ return toolsClient.market.getExportFileUploadUrl.mutate(input);
}
/**
@@ -68,7 +68,7 @@ class CodeInterpreterService {
async saveExportedFileContent(
params: SaveExportedFileContentInput,
): Promise<SaveExportedFileContentResult> {
- return toolsClient.codeInterpreter.saveExportedFileContent.mutate(params);
+ return toolsClient.market.saveExportedFileContent.mutate(params);
}
}
diff --git a/src/services/mcp.test.ts b/src/services/mcp.test.ts
index 54b39f07c4c..670a7ef1563 100644
--- a/src/services/mcp.test.ts
+++ b/src/services/mcp.test.ts
@@ -36,6 +36,11 @@ vi.mock('@lobechat/utils', () => ({
vi.mock('@/libs/trpc/client', () => ({
toolsClient: {
+ market: {
+ callCloudMcpEndpoint: {
+ mutate: vi.fn(),
+ },
+ },
mcp: {
callTool: {
mutate: vi.fn(),
@@ -53,6 +58,7 @@ vi.mock('@/utils/electron/ipc', () => ({
vi.mock('./discover', () => ({
discoverService: {
+ injectMPToken: vi.fn().mockResolvedValue(undefined),
reportPluginCall: vi.fn().mockResolvedValue(undefined),
},
}));
@@ -129,22 +135,20 @@ describe('MCPService', () => {
name: 'test-plugin',
env: { API_KEY: 'test-key' },
},
+ meta: {
+ customPluginInfo: undefined,
+ isCustomPlugin: false,
+ sessionId: 'topic-1',
+ version: '1.0.0',
+ },
toolName: 'testMethod',
},
{ signal: undefined },
);
- // Wait for async reporting to complete
+ // For SSE type, reporting is handled by server-side, frontend should NOT call reportPluginCall
await new Promise((resolve) => setTimeout(resolve, 10));
-
- expect(discoverService.reportPluginCall).toHaveBeenCalled();
- const reportCall = vi.mocked(discoverService.reportPluginCall).mock.calls[0][0];
- expect(reportCall).toMatchObject({
- identifier: 'test-plugin',
- methodName: 'testMethod',
- success: true,
- isCustomPlugin: false,
- });
+ expect(discoverService.reportPluginCall).not.toHaveBeenCalled();
});
it('should invoke tool call with custom plugin', async () => {
@@ -274,28 +278,22 @@ describe('MCPService', () => {
await expect(mcpService.invokeMcpToolCall(payload, {})).rejects.toThrow('Tool call failed');
- // Wait for async reporting to complete
+ // For SSE type, reporting is handled by server-side, frontend should NOT call reportPluginCall
await new Promise((resolve) => setTimeout(resolve, 10));
-
- expect(discoverService.reportPluginCall).toHaveBeenCalled();
- const reportCall = vi.mocked(discoverService.reportPluginCall).mock.calls[0][0];
- expect(reportCall).toMatchObject({
- success: false,
- errorCode: 'CALL_FAILED',
- errorMessage: 'Tool call failed',
- });
+ expect(discoverService.reportPluginCall).not.toHaveBeenCalled();
});
- it('should calculate request and response sizes correctly', async () => {
- const { toolsClient } = await import('@/libs/trpc/client');
+ it('should call toolsClient.market.callCloudMcpEndpoint for cloud type and not report from frontend', async () => {
const { discoverService } = await import('./discover');
+ const { toolsClient } = await import('@/libs/trpc/client');
+ // Use cloud type which now reports from server-side
const mockPlugin = {
customParams: {
- mcp: { type: 'sse' },
+ mcp: { type: 'cloud' },
},
manifest: {
- meta: { title: 'Size Test Plugin' },
+ meta: { title: 'Cloud Plugin' },
version: '1.0.0',
},
};
@@ -303,32 +301,44 @@ describe('MCPService', () => {
mockPluginSelectors.getInstalledPluginById.mockReturnValue(() => mockPlugin);
mockPluginSelectors.getCustomPluginById.mockReturnValue(() => null);
+ // Mock the toolsClient for cloud type
const mockResult = {
content: 'response data',
state: {
- content: [{ text: 'response data', type: 'text' }],
+ content: [{ text: 'response data', type: 'text' as const }],
},
success: true,
};
- vi.mocked(toolsClient.mcp.callTool.mutate).mockResolvedValue(mockResult);
+ vi.mocked(toolsClient.market.callCloudMcpEndpoint.mutate).mockResolvedValue(mockResult);
const payload: ChatToolPayload = {
id: 'tool-call-6',
- identifier: 'size-plugin',
- apiName: 'sizeMethod',
+ identifier: 'cloud-plugin',
+ apiName: 'cloudMethod',
arguments: '{"key": "value"}',
type: 'standalone',
};
- await mcpService.invokeMcpToolCall(payload, {});
+ const result = await mcpService.invokeMcpToolCall(payload, { topicId: 'topic-123' });
+
+ expect(result).toEqual(mockResult);
+ expect(toolsClient.market.callCloudMcpEndpoint.mutate).toHaveBeenCalledWith({
+ apiParams: { key: 'value' },
+ identifier: 'cloud-plugin',
+ meta: {
+ customPluginInfo: undefined,
+ isCustomPlugin: false,
+ sessionId: 'topic-123',
+ version: '1.0.0',
+ },
+ toolName: 'cloudMethod',
+ });
// Wait for async reporting
await new Promise((resolve) => setTimeout(resolve, 10));
- expect(discoverService.reportPluginCall).toHaveBeenCalled();
- const reportCall = vi.mocked(discoverService.reportPluginCall).mock.calls[0][0];
- expect(reportCall.requestSizeBytes).toBeGreaterThan(0);
- expect(reportCall.responseSizeBytes).toBeGreaterThan(0);
+ // Cloud type should NOT report from frontend (handled server-side)
+ expect(discoverService.reportPluginCall).not.toHaveBeenCalled();
});
it('should handle abort signal', async () => {
@@ -372,9 +382,8 @@ describe('MCPService', () => {
expect(result).toEqual(mockResult);
});
- it('should report custom plugin info correctly', async () => {
+ it('should pass meta to server for custom plugin', async () => {
const { toolsClient } = await import('@/libs/trpc/client');
- const { discoverService } = await import('./discover');
const mockCustomPlugin = {
customParams: {
@@ -406,19 +415,24 @@ describe('MCPService', () => {
type: 'standalone',
};
- await mcpService.invokeMcpToolCall(payload, {});
-
- // Wait for async reporting
- await new Promise((resolve) => setTimeout(resolve, 10));
+ await mcpService.invokeMcpToolCall(payload, { topicId: 'topic-123' });
- expect(discoverService.reportPluginCall).toHaveBeenCalled();
- const reportCall = vi.mocked(discoverService.reportPluginCall).mock.calls[0][0];
- expect(reportCall.isCustomPlugin).toBe(true);
- expect(reportCall.customPluginInfo).toEqual({
- avatar: '🔧',
- description: 'Custom tool description',
- name: 'Custom Tool',
- });
+ // Verify meta is passed to server
+ expect(toolsClient.mcp.callTool.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ meta: {
+ customPluginInfo: {
+ avatar: '🔧',
+ description: 'Custom tool description',
+ name: 'Custom Tool',
+ },
+ isCustomPlugin: true,
+ sessionId: 'topic-123',
+ version: '3.0.0',
+ },
+ }),
+ expect.anything(),
+ );
});
});
diff --git a/src/services/mcp.ts b/src/services/mcp.ts
index 138e220400b..b14a2426bba 100644
--- a/src/services/mcp.ts
+++ b/src/services/mcp.ts
@@ -1,12 +1,16 @@
import { CURRENT_VERSION, isDesktop } from '@lobechat/const';
-import { type ChatToolPayload, type CheckMcpInstallResult, type CustomPluginMetadata } from '@lobechat/types';
+import {
+ type ChatToolPayload,
+ type CheckMcpInstallResult,
+ type CustomPluginMetadata,
+} from '@lobechat/types';
import { isLocalOrPrivateUrl, safeParseJSON } from '@lobechat/utils';
import { type PluginManifest } from '@lobehub/market-sdk';
import { type CallReportRequest } from '@lobehub/market-types';
import superjson from 'superjson';
import { type MCPToolCallResult } from '@/libs/mcp';
-import { lambdaClient, toolsClient } from '@/libs/trpc/client';
+import { toolsClient } from '@/libs/trpc/client';
import { ensureElectronIpc } from '@/utils/electron/ipc';
import { discoverService } from './discover';
@@ -31,6 +35,8 @@ class MCPService {
payload: ChatToolPayload,
{ signal, topicId }: { signal?: AbortSignal; topicId?: string },
) {
+ await discoverService.injectMPToken();
+
const { pluginSelectors } = await import('@/store/tool/selectors');
const { getToolStoreState } = await import('@/store/tool/store');
@@ -80,12 +86,28 @@ class MCPService {
const isStdio = plugin?.customParams?.mcp?.type === 'stdio';
const isCloud = plugin?.customParams?.mcp?.type === 'cloud';
+ const isCustomPlugin = !!customPlugin;
+
+ // Build meta for server-side reporting
+ const meta = {
+ customPluginInfo: isCustomPlugin
+ ? {
+ avatar: plugin.manifest?.meta.avatar,
+ description: plugin.manifest?.meta.description,
+ name: plugin.manifest?.meta.title,
+ }
+ : undefined,
+ isCustomPlugin,
+ sessionId: topicId,
+ version: plugin.manifest?.version || 'unknown',
+ };
const data = {
// For desktop IPC, always pass a record/object for tool "arguments"
// (IPC layer will superjson serialize the whole payload).
args: isDesktop && isStdio ? (safeParseJSON(args) ?? {}) : args,
env: connection?.type === 'stdio' ? params.env : (pluginSettings ?? connection?.env),
+ meta,
params,
toolName: apiName,
};
@@ -103,13 +125,14 @@ class MCPService {
// Parse args
const apiParams = safeParseJSON(args) || {};
- // Call cloud gateway via lambda market endpoint
+ // Call cloud gateway via tools market endpoint
// Server will automatically get user access token from database
// and format the result to MCPToolCallResult
- // @ts-ignore tsgo 误报错误
- result = await lambdaClient.market.callCloudMcpEndpoint.mutate({
+ // Server-side also handles telemetry reporting
+ result = await toolsClient.market.callCloudMcpEndpoint.mutate({
apiParams,
identifier,
+ meta,
toolName: apiName,
});
} else if (isDesktop && isStdio) {
@@ -134,50 +157,46 @@ class MCPService {
// Rethrow error, maintain original error handling logic
throw error;
} finally {
- // Asynchronously report call result without affecting main flow
- const callEndTime = Date.now();
- const callDurationMs = callEndTime - callStartTime;
-
- // Calculate request size
- const inputParams = safeParseJSON(args) || args;
-
- const requestSizeBytes = calculateObjectSizeBytes(inputParams);
- // Calculate response size
- const responseSizeBytes = success && result ? calculateObjectSizeBytes(result.state) : 0;
-
- const isCustomPlugin = !!customPlugin;
- // Construct report data
- const reportData: CallReportRequest = {
- callDurationMs,
- customPluginInfo: isCustomPlugin
- ? {
- avatar: plugin.manifest?.meta.avatar,
- description: plugin.manifest?.meta.description,
- name: plugin.manifest?.meta.title,
- }
- : undefined,
- errorCode,
- errorMessage,
- identifier,
- isCustomPlugin,
- metadata: {
- appVersion: CURRENT_VERSION,
- command: plugin.customParams?.mcp?.command,
- mcpType: plugin.customParams?.mcp?.type,
- },
- methodName: apiName,
- methodType: 'tool' as const,
- requestSizeBytes,
- responseSizeBytes,
- sessionId: topicId,
- success,
- version: plugin.manifest!.version || 'unknown',
- };
+ // HTTP/SSE/streamable types: reporting is handled by server-side via mcp.callTool
+ // Cloud type: reporting is handled by server-side via market.callCloudMcpEndpoint
+ // Only report from frontend for stdio types (desktop only)
+ if (isStdio) {
+ const callEndTime = Date.now();
+ const callDurationMs = callEndTime - callStartTime;
+
+ // Calculate request size
+ const inputParams = safeParseJSON(args) || args;
+ const requestSizeBytes = calculateObjectSizeBytes(inputParams);
+ // Calculate response size
+ const responseSizeBytes = success && result ? calculateObjectSizeBytes(result.state) : 0;
- // Asynchronously report without affecting main flow
- discoverService.reportPluginCall(reportData).catch((reportError) => {
- console.warn('Failed to report MCP tool call:', reportError);
- });
+ // Construct report data
+ const reportData: CallReportRequest = {
+ callDurationMs,
+ customPluginInfo: meta.customPluginInfo,
+ errorCode,
+ errorMessage,
+ identifier,
+ isCustomPlugin,
+ metadata: {
+ appVersion: CURRENT_VERSION,
+ command: plugin.customParams?.mcp?.command,
+ mcpType: plugin.customParams?.mcp?.type,
+ },
+ methodName: apiName,
+ methodType: 'tool' as const,
+ requestSizeBytes,
+ responseSizeBytes,
+ sessionId: topicId,
+ success,
+ version: meta.version,
+ };
+
+ // Asynchronously report without affecting main flow
+ discoverService.reportPluginCall(reportData).catch((reportError) => {
+ console.warn('Failed to report MCP tool call:', reportError);
+ });
+ }
}
}
diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.ts
index 51252ceffc8..2cc5fb8dc3d 100644
--- a/src/store/chat/slices/plugin/action.test.ts
+++ b/src/store/chat/slices/plugin/action.test.ts
@@ -1429,4 +1429,195 @@ describe('ChatPluginAction', () => {
});
});
});
+
+ describe('Plugin invoke functions use optimisticUpdateToolMessage', () => {
+ const messageId = 'message-id';
+ const payload: ChatToolPayload = {
+ apiName: 'test-api',
+ arguments: '{}',
+ id: 'tool-call-id',
+ identifier: 'test-plugin',
+ type: 'default',
+ };
+
+ describe('invokeMCPTypePlugin', () => {
+ it('should use optimisticUpdateToolMessage for successful result', async () => {
+ const mockResult = {
+ content: 'mcp result content',
+ state: { content: [], isError: false },
+ success: true,
+ };
+
+ // Mock the mcpService
+ const mcpService = await import('@/services/mcp');
+ vi.spyOn(mcpService.mcpService, 'invokeMcpToolCall').mockResolvedValue(mockResult);
+
+ const optimisticUpdateToolMessageMock = vi.fn().mockResolvedValue(undefined);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: 'session-id',
+ messagesMap: { [messageMapKey({ agentId: 'session-id' })]: [] },
+ optimisticUpdateToolMessage: optimisticUpdateToolMessageMock,
+ replaceMessages: vi.fn(),
+ messageOperationMap: {},
+ operations: {},
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+
+ await act(async () => {
+ await result.current.invokeMCPTypePlugin(messageId, payload);
+ });
+
+ expect(optimisticUpdateToolMessageMock).toHaveBeenCalledWith(
+ messageId,
+ {
+ content: mockResult.content,
+ pluginError: undefined,
+ pluginState: mockResult.state,
+ },
+ undefined,
+ );
+ });
+
+ it('should use optimisticUpdateToolMessage for error result', async () => {
+ const mockResult = {
+ content: 'error content',
+ error: { message: 'test error' },
+ state: { content: [], isError: true },
+ success: false,
+ };
+
+ const mcpService = await import('@/services/mcp');
+ vi.spyOn(mcpService.mcpService, 'invokeMcpToolCall').mockResolvedValue(mockResult);
+
+ const optimisticUpdateToolMessageMock = vi.fn().mockResolvedValue(undefined);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: 'session-id',
+ messagesMap: { [messageMapKey({ agentId: 'session-id' })]: [] },
+ optimisticUpdateToolMessage: optimisticUpdateToolMessageMock,
+ replaceMessages: vi.fn(),
+ messageOperationMap: {},
+ operations: {},
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+
+ await act(async () => {
+ await result.current.invokeMCPTypePlugin(messageId, payload);
+ });
+
+ expect(optimisticUpdateToolMessageMock).toHaveBeenCalledWith(
+ messageId,
+ {
+ content: mockResult.content,
+ pluginError: mockResult.error,
+ pluginState: undefined,
+ },
+ undefined,
+ );
+ });
+ });
+
+ describe('invokeKlavisTypePlugin', () => {
+ it('should use optimisticUpdateToolMessage for successful result', async () => {
+ const mockResult = {
+ content: 'klavis result content',
+ state: { data: 'test-data' },
+ success: true,
+ };
+
+ // Mock useToolStore to return a server
+ vi.spyOn(useToolStore, 'getState').mockReturnValue({
+ servers: [{ identifier: 'test-plugin', serverUrl: 'http://test.com' }],
+ callKlavisTool: vi.fn().mockResolvedValue({
+ success: true,
+ data: mockResult,
+ }),
+ } as any);
+
+ const optimisticUpdateToolMessageMock = vi.fn().mockResolvedValue(undefined);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: 'session-id',
+ messagesMap: { [messageMapKey({ agentId: 'session-id' })]: [] },
+ optimisticUpdateToolMessage: optimisticUpdateToolMessageMock,
+ replaceMessages: vi.fn(),
+ messageOperationMap: {},
+ operations: {},
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+
+ await act(async () => {
+ await result.current.invokeKlavisTypePlugin(messageId, payload);
+ });
+
+ expect(optimisticUpdateToolMessageMock).toHaveBeenCalledWith(
+ messageId,
+ {
+ content: mockResult.content,
+ pluginError: undefined,
+ pluginState: mockResult.state,
+ },
+ undefined,
+ );
+ });
+ });
+
+ describe('invokeCloudCodeInterpreterTool', () => {
+ it('should use optimisticUpdateToolMessage for successful result', async () => {
+ const mockResult = {
+ content: 'code interpreter result',
+ state: { output: 'test output' },
+ success: true,
+ };
+
+ // Mock CloudSandboxExecutionRuntime using doMock for dynamic mocking
+ vi.doMock('@lobechat/builtin-tool-cloud-sandbox/executionRuntime', () => ({
+ CloudSandboxExecutionRuntime: class {
+ 'test-api' = vi.fn().mockResolvedValue(mockResult);
+ },
+ }));
+
+ const optimisticUpdateToolMessageMock = vi.fn().mockResolvedValue(undefined);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: 'session-id',
+ messagesMap: { [messageMapKey({ agentId: 'session-id' })]: [] },
+ optimisticUpdateToolMessage: optimisticUpdateToolMessageMock,
+ replaceMessages: vi.fn(),
+ messageOperationMap: {},
+ operations: {},
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+
+ await act(async () => {
+ await result.current.invokeCloudCodeInterpreterTool(messageId, payload);
+ });
+
+ expect(optimisticUpdateToolMessageMock).toHaveBeenCalledWith(
+ messageId,
+ {
+ content: mockResult.content,
+ pluginError: undefined,
+ pluginState: mockResult.state,
+ },
+ undefined,
+ );
+
+ vi.doUnmock('@lobechat/builtin-tool-cloud-sandbox/executionRuntime');
+ });
+ });
+ });
});
diff --git a/src/store/chat/slices/plugin/actions/internals.ts b/src/store/chat/slices/plugin/actions/internals.ts
index 083901a8d21..60da7d04561 100644
--- a/src/store/chat/slices/plugin/actions/internals.ts
+++ b/src/store/chat/slices/plugin/actions/internals.ts
@@ -1,6 +1,6 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
import { ToolNameResolver } from '@lobechat/context-engine';
-import { type ChatToolPayload, type MessageToolCall, type ToolsCallingContext } from '@lobechat/types';
+import { type ChatToolPayload, type MessageToolCall } from '@lobechat/types';
import { type LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
import { type StateCreator } from 'zustand/vanilla';
@@ -9,8 +9,6 @@ import { useToolStore } from '@/store/tool';
import { klavisStoreSelectors, pluginSelectors } from '@/store/tool/selectors';
import { builtinTools } from '@/tools';
-import { displayMessageSelectors } from '../../message/selectors';
-
/**
* Internal utility methods and runtime state management
* These are building blocks used by other actions
@@ -20,11 +18,6 @@ export interface PluginInternalsAction {
* Transform tool calls from runtime format to storage format
*/
internal_transformToolCalls: (toolCalls: MessageToolCall[]) => ChatToolPayload[];
-
- /**
- * Construct tools calling context for plugin invocation
- */
- internal_constructToolsCallingContext: (id: string) => ToolsCallingContext | undefined;
}
export const pluginInternals: StateCreator<
@@ -32,7 +25,7 @@ export const pluginInternals: StateCreator<
[['zustand/devtools', never]],
[],
PluginInternalsAction
-> = (set, get) => ({
+> = () => ({
internal_transformToolCalls: (toolCalls) => {
const toolNameResolver = new ToolNameResolver();
@@ -77,13 +70,4 @@ export const pluginInternals: StateCreator<
source: sourceMap[payload.identifier],
}));
},
-
- internal_constructToolsCallingContext: (id: string) => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(get());
- if (!message) return;
-
- return {
- topicId: message.topicId,
- };
- },
});
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index 11aac61d203..d32437d1ea8 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -261,12 +261,6 @@ export const pluginTypes: StateCreator<
},
invokeCloudCodeInterpreterTool: async (id, payload) => {
- const {
- optimisticUpdateMessageContent,
- optimisticUpdatePluginState,
- optimisticUpdateMessagePluginError,
- } = get();
-
// Get message to extract topicId
const message = dbMessageSelectors.getDbMessageById(id)(get());
@@ -336,16 +330,16 @@ export const pluginTypes: StateCreator<
const context = operationId ? { operationId } : undefined;
- await Promise.all([
- optimisticUpdateMessageContent(id, data.content, undefined, context),
- (async () => {
- if (data.success && data.state) {
- await optimisticUpdatePluginState(id, data.state, context);
- } else if (!data.success && data.error) {
- await optimisticUpdateMessagePluginError(id, data.error, context);
- }
- })(),
- ]);
+ // Use optimisticUpdateToolMessage to update content and state/error in a single call
+ await get().optimisticUpdateToolMessage(
+ id,
+ {
+ content: data.content,
+ pluginError: data.success ? undefined : data.error,
+ pluginState: data.success ? data.state : undefined,
+ },
+ context,
+ );
// Handle exportFile: save exported file and associate with assistant message (parent)
if (payload.apiName === 'exportFile' && data.success && data.state) {
@@ -422,12 +416,6 @@ export const pluginTypes: StateCreator<
},
invokeKlavisTypePlugin: async (id, payload) => {
- const {
- optimisticUpdateMessageContent,
- optimisticUpdatePluginState,
- optimisticUpdateMessagePluginError,
- } = get();
-
let data: MCPToolCallResult | undefined;
// Get message to extract sessionId/topicId
@@ -510,13 +498,16 @@ export const pluginTypes: StateCreator<
// operationId already declared above, reuse it
const context = operationId ? { operationId } : undefined;
- await Promise.all([
- optimisticUpdateMessageContent(id, data.content, undefined, context),
- (async () => {
- if (data.success) await optimisticUpdatePluginState(id, data.state, context);
- else await optimisticUpdateMessagePluginError(id, data.error, context);
- })(),
- ]);
+ // Use optimisticUpdateToolMessage to update content and state/error in a single call
+ await get().optimisticUpdateToolMessage(
+ id,
+ {
+ content: data.content,
+ pluginError: data.success ? undefined : data.error,
+ pluginState: data.success ? data.state : undefined,
+ },
+ context,
+ );
return data.content;
},
@@ -561,12 +552,6 @@ export const pluginTypes: StateCreator<
},
invokeMCPTypePlugin: async (id, payload) => {
- const {
- optimisticUpdateMessageContent,
- internal_constructToolsCallingContext,
- optimisticUpdatePluginState,
- optimisticUpdateMessagePluginError,
- } = get();
let data: MCPToolCallResult | undefined;
// Get message to extract agentId/topicId
@@ -586,10 +571,9 @@ export const pluginTypes: StateCreator<
);
try {
- const context = internal_constructToolsCallingContext(id);
const result = await mcpService.invokeMcpToolCall(payload, {
signal: abortController?.signal,
- topicId: context?.topicId,
+ topicId: message?.topicId,
});
if (!!result) data = result;
@@ -620,13 +604,16 @@ export const pluginTypes: StateCreator<
// operationId already declared above, reuse it
const context = operationId ? { operationId } : undefined;
- await Promise.all([
- optimisticUpdateMessageContent(id, data.content, undefined, context),
- (async () => {
- if (data.success) await optimisticUpdatePluginState(id, data.state, context);
- else await optimisticUpdateMessagePluginError(id, data.error, context);
- })(),
- ]);
+ // Use optimisticUpdateToolMessage to update content and state/error in a single call
+ await get().optimisticUpdateToolMessage(
+ id,
+ {
+ content: data.content,
+ pluginError: data.success ? undefined : data.error,
+ pluginState: data.success ? data.state : undefined,
+ },
+ context,
+ );
return data.content;
},