🤯 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
🌐 chore: translate non-English comments to English in server routers lambda (#11301)
LobeHub Botf60c1fd86f03
diff --git a/src/server/routers/lambda/_helpers/resolveContext.ts b/src/server/routers/lambda/_helpers/resolveContext.tsindex 526fe229913..68352838ab9 100644--- a/src/server/routers/lambda/_helpers/resolveContext.ts+++ b/src/server/routers/lambda/_helpers/resolveContext.ts@@ -14,15 +14,15 @@ export interface ResolvedContext {}/**- * 解析会话上下文+ * Resolve conversation context*- * 将 agentId 解析为 sessionId(如果提供了 agentId)- * 优先级:agentId > sessionId+ * Resolves agentId to sessionId (if agentId is provided)+ * Priority: agentId > sessionId*- * @param input - 输入的上下文参数- * @param db - 数据库实例- * @param userId - 用户 ID- * @returns 解析后的上下文,sessionId 已从 agentId 解析+ * @param input - Input context parameters+ * @param db - Database instance+ * @param userId - User ID+ * @returns Resolved context with sessionId resolved from agentId*/export const resolveContext = async (input: ConversationContextInput,@@ -31,7 +31,7 @@ export const resolveContext = async (): Promise<ResolvedContext> => {let resolvedSessionId: string | null = input.sessionId ?? null;- // 如果提供了 agentId,优先从 agentsToSessions 表查找对应的 sessionId+ // If agentId is provided, prioritize looking up the corresponding sessionId from agentsToSessions tableif (input.agentId) {const [relation] = await db.select({ sessionId: agentsToSessions.sessionId })diff --git a/src/server/routers/lambda/agent.ts b/src/server/routers/lambda/agent.tsindex eec39421d38..1223d4ecfec 100644--- a/src/server/routers/lambda/agent.ts+++ b/src/server/routers/lambda/agent.ts@@ -213,7 +213,7 @@ export const agentRouter = router({return [...files- // 过滤掉所有图片+ // Filter out all images.filter((file) => !file.fileType.startsWith('image')).map((file) => ({enabled: knowledge.files.some((item) => item.id === file.id),diff --git a/src/server/routers/lambda/aiModel.ts b/src/server/routers/lambda/aiModel.tsindex a05a0bec119..4a1044a0b57 100644--- a/src/server/routers/lambda/aiModel.ts+++ b/src/server/routers/lambda/aiModel.ts@@ -52,7 +52,7 @@ export const aiModelRouter = router({.input(z.object({id: z.string(),- // TODO: 补齐校验 Schema+ // TODO: Complete validation schemamodels: z.array(z.any()),}),)diff --git a/src/server/routers/lambda/comfyui.ts b/src/server/routers/lambda/comfyui.tsindex 65ec1aa6fa0..368ff281a87 100644--- a/src/server/routers/lambda/comfyui.ts+++ b/src/server/routers/lambda/comfyui.ts@@ -13,7 +13,7 @@ import type { WorkflowContext } from '@/server/services/comfyui/types';// Other RuntimeImageGenParams fields are passed through automaticallyconst ComfyUIParamsSchema = z.object({- prompt: z.string(), // 只验证必需字段+ prompt: z.string(), // Only validate required fields}).passthrough();diff --git a/src/server/routers/lambda/exporter.ts b/src/server/routers/lambda/exporter.tsindex 750fbf5d2ff..bda2ff5e69d 100644--- a/src/server/routers/lambda/exporter.ts+++ b/src/server/routers/lambda/exporter.ts@@ -156,7 +156,7 @@ const generatePdfFromMarkdown = async (});}- // 完成文档+ // Finalize documentdoc.end();} catch (error) {reject(diff --git a/src/server/routers/lambda/image.ts b/src/server/routers/lambda/image.tsindex 7150eb25420..68d8677ce46 100644--- a/src/server/routers/lambda/image.ts+++ b/src/server/routers/lambda/image.ts@@ -97,9 +97,9 @@ export const imageRouter = router({log('Starting image creation process, input: %O', input);- // 规范化参考图地址,统一存储 S3 key(避免把会过期的预签名 URL 存进数据库)+ // Normalize reference image addresses, store S3 keys uniformly (avoid storing expiring presigned URLs in database)let configForDatabase = { ...params };- // 1) 处理多图 imageUrls+ // 1) Process multiple images in imageUrlsif (Array.isArray(params.imageUrls) && params.imageUrls.length > 0) {log('Converting imageUrls to S3 keys for database storage: %O', params.imageUrls);try {@@ -119,7 +119,7 @@ export const imageRouter = router({log('Keeping original imageUrls due to conversion error');}}- // 2) 处理单图 imageUrl+ // 2) Process single image in imageUrlif (typeof params.imageUrl === 'string' && params.imageUrl) {try {const key = fileService.getKeyFromFullUrl(params.imageUrl);@@ -127,11 +127,11 @@ export const imageRouter = router({configForDatabase = { ...configForDatabase, imageUrl: key };} catch (error) {log('Error converting imageUrl to key: %O', error);- // 转换失败则保留原始值+ // Keep original value if conversion fails}}- // 防御性检测:确保没有完整URL进入数据库+ // Defensive check: ensure no full URLs enter the databasevalidateNoUrlsInConfig(configForDatabase, 'configForDatabase');const chargeResult = await chargeBeforeGenerate({@@ -148,11 +148,11 @@ export const imageRouter = router({return chargeResult;}- // 步骤 1: 在事务中原子性地创建所有数据库记录+ // Step 1: Atomically create all database records in a transactionconst { batch: createdBatch, generationsWithTasks } = await serverDB.transaction(async (tx) => {log('Starting database transaction for image generation');- // 1. 创建 generationBatch+ // 1. Create generationBatchconst newBatch: NewGenerationBatch = {config: configForDatabase,generationTopicId,@@ -161,13 +161,13 @@ export const imageRouter = router({prompt: params.prompt,provider,userId,- width: params.width, // 使用转换后的配置存储到数据库+ width: params.width, // Use converted config for database storage};log('Creating generation batch: %O', newBatch);const [batch] = await tx.insert(generationBatches).values(newBatch).returning();log('Generation batch created successfully: %s', batch.id);- // 2. 创建 4 个 generation(一期固定生成 4 张)+ // 2. Create 4 generations (fixed at 4 images for phase one)const seeds ='seed' in params? generateUniqueSeeds(imageNum)@@ -187,11 +187,11 @@ export const imageRouter = router({createdGenerations.map((g) => g.id),);- // 3. 并发为每个 generation 创建 asyncTask(在事务中)+ // 3. Concurrently create asyncTask for each generation (within transaction)log('Creating async tasks for generations');const generationsWithTasks = await Promise.all(createdGenerations.map(async (generation) => {- // 在事务中直接创建 asyncTask+ // Create asyncTask directly in transactionconst [createdAsyncTask] = await tx.insert(asyncTasks).values({@@ -204,7 +204,7 @@ export const imageRouter = router({const asyncTaskId = createdAsyncTask.id;log('Created async task %s for generation %s', asyncTaskId, generation.id);- // 更新 generation 的 asyncTaskId+ // Update generation's asyncTaskIdawait tx.update(generations).set({ asyncTaskId })@@ -259,7 +259,7 @@ export const imageRouter = router({console.error('[createImage] Failed to process async tasks:', e);log('Failed to process async tasks: %O', e);- // 如果整体失败,更新所有任务状态为失败+ // If overall failure occurs, update all task statuses to failedtry {await Promise.allSettled(generationsWithTasks.map(({ asyncTaskId }) =>diff --git a/src/server/routers/lambda/klavis.ts b/src/server/routers/lambda/klavis.tsindex 817f5f4d26e..ad9df1cb45f 100644--- a/src/server/routers/lambda/klavis.ts+++ b/src/server/routers/lambda/klavis.ts@@ -36,7 +36,7 @@ export const klavisRouter = router({.mutation(async ({ input, ctx }) => {const { serverName, userId, identifier } = input;- // 创建单个服务器实例+ // Create a single server instanceconst response = await ctx.klavisClient.mcpServer.createServerInstance({serverName: serverName as any,userId,@@ -44,11 +44,11 @@ export const klavisRouter = router({const { serverUrl, instanceId, oauthUrl } = response;- // 获取该服务器的工具列表+ // Get the tool list for this serverconst toolsResponse = await ctx.klavisClient.mcpServer.getTools(serverName as any);const tools = toolsResponse.tools || [];- // 保存到数据库,使用传入的 identifier(格式:小写,空格替换为连字符)+ // Save to database using the provided identifier (format: lowercase, spaces replaced with hyphens)const manifest: LobeChatPluginManifest = {api: tools.map((tool: any) => ({description: tool.description || '',@@ -64,8 +64,8 @@ export const klavisRouter = router({type: 'default',};- // 保存到数据库,包含 oauthUrl 和 isAuthenticated 状态- const isAuthenticated = !oauthUrl; // 如果没有 oauthUrl,说明不需要认证或已认证+ // Save to database with oauthUrl and isAuthenticated status+ const isAuthenticated = !oauthUrl; // If there's no oauthUrl, authentication is not required or already authenticatedawait ctx.pluginModel.create({customParams: {klavis: {@@ -104,10 +104,10 @@ export const klavisRouter = router({}),).mutation(async ({ input, ctx }) => {- // 调用 Klavis API 删除服务器实例+ // Call Klavis API to delete server instanceawait ctx.klavisClient.mcpServer.deleteServerInstance(input.instanceId);- // 从数据库删除(使用 identifier)+ // Delete from database (using identifier)await ctx.pluginModel.delete(input.identifier);return { success: true };@@ -200,10 +200,10 @@ export const klavisRouter = router({const { identifier, serverName, serverUrl, instanceId, tools, isAuthenticated, oauthUrl } =input;- // 获取现有插件(使用 identifier)+ // Get existing plugin (using identifier)const existingPlugin = await ctx.pluginModel.findById(identifier);- // 构建包含所有工具的 manifest+ // Build manifest containing all toolsconst manifest: LobeChatPluginManifest = {api: tools.map((tool) => ({description: tool.description || '',@@ -229,7 +229,7 @@ export const klavisRouter = router({},};- // 更新或创建插件+ // Update or create pluginif (existingPlugin) {await ctx.pluginModel.update(identifier, { customParams, manifest });} else {diff --git a/src/server/routers/lambda/market/index.ts b/src/server/routers/lambda/market/index.tsindex 4812d28cb0c..4c9f0e66c7b 100644--- a/src/server/routers/lambda/market/index.ts+++ b/src/server/routers/lambda/market/index.ts@@ -559,11 +559,11 @@ export const marketRouter = router({log('get access token, expiresIn value:', expiresIn);log('expiresIn type:', typeof expiresIn);- const expirationTime = new Date(Date.now() + (expiresIn - 60) * 1000); // 提前 60 秒过期+ const expirationTime = new Date(Date.now() + (expiresIn - 60) * 1000); // Expire 60 seconds earlylog('expirationTime:', expirationTime.toISOString());- // 设置 HTTP-Only Cookie 存储实际的 access token+ // Set HTTP-Only Cookie to store the actual access tokenconst tokenCookie = serialize('mp_token', accessToken, {expires: expirationTime,httpOnly: true,@@ -572,7 +572,7 @@ export const marketRouter = router({secure: process.env.NODE_ENV === 'production',});- // 设置客户端可读的状态标记 cookie(不包含实际 token)+ // Set client-readable status marker cookie (without actual token)const statusCookie = serialize('mp_token_status', 'active', {expires: expirationTime,httpOnly: false,@@ -581,7 +581,7 @@ export const marketRouter = router({secure: process.env.NODE_ENV === 'production',});- // 通过 context 的 resHeaders 设置 Set-Cookie 头+ // Set Set-Cookie header via context's resHeadersctx.resHeaders?.append('Set-Cookie', tokenCookie);ctx.resHeaders?.append('Set-Cookie', statusCookie);@@ -650,7 +650,7 @@ export const marketRouter = router({return { success: true };} catch (error) {console.error('Error reporting call: %O', error);- // 不抛出错误,因为上报失败不应影响主流程+ // Don't throw error, as reporting failure should not affect main flowreturn { success: false };}}),@@ -678,7 +678,7 @@ export const marketRouter = router({return { success: true };} catch (error) {log('Error reporting MCP installation result: %O', error);- // 不抛出错误,因为上报失败不应影响主流程+ // Don't throw error, as reporting failure should not affect main flowreturn { success: false };}}),diff --git a/src/server/routers/lambda/message.ts b/src/server/routers/lambda/message.tsindex 9b0b9270200..b521e7e12cb 100644--- a/src/server/routers/lambda/message.ts+++ b/src/server/routers/lambda/message.ts@@ -75,13 +75,13 @@ export const messageRouter = router({createMessage: messageProcedure.input(CreateNewMessageParamsSchema).mutation(async ({ input, ctx }) => {- // 如果没有 agentId 但有 sessionId,从 sessionId 解析出 agentId+ // If there's no agentId but has sessionId, resolve agentId from sessionIdlet agentId = input.agentId;if (!agentId && input.sessionId) {agentId = (await resolveAgentIdFromSession(input.sessionId, ctx.serverDB, ctx.userId))!;}- // 使用解析后的 agentId 创建消息+ // Create message with the resolved agentIdreturn ctx.messageService.createMessage({ ...input, agentId } as any);}),diff --git a/src/server/routers/lambda/plugin.ts b/src/server/routers/lambda/plugin.tsindex 3c9d705aaa7..37c4bccde30 100644--- a/src/server/routers/lambda/plugin.ts+++ b/src/server/routers/lambda/plugin.ts@@ -65,7 +65,7 @@ export const pluginRouter = router({return data.identifier;}),- // TODO: 未来这部分方法也需要使用 authedProcedure+ // TODO: In the future, this method also needs to use authedProceduregetPlugins: publicProcedure.query(async ({ ctx }): Promise<LobeTool[]> => {if (!ctx.userId) return [];diff --git a/src/server/routers/lambda/ragEval.ts b/src/server/routers/lambda/ragEval.tsindex 1828112a28e..21b38a37753 100644--- a/src/server/routers/lambda/ragEval.ts+++ b/src/server/routers/lambda/ragEval.ts@@ -251,7 +251,7 @@ export const ragEvalRouter = router({const isSuccess = records.every((record) => record.status === EvalEvaluationStatus.Success);if (isSuccess) {- // 将结果上传到 S3+ // Upload results to S3const evalRecords = records.map((record) => ({question: record.question,@@ -265,7 +265,7 @@ export const ragEvalRouter = router({await ctx.fileService.uploadContent(path, JSONL.stringify(evalRecords));- // 保存数据+ // Save dataawait ctx.evaluationModel.update(input.id, {status: EvalEvaluationStatus.Success,evalRecordsUrl: await ctx.fileService.getFullFileUrl(path),diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.tsindex fadbbac181a..5248a89465a 100644--- a/src/server/routers/lambda/topic.ts+++ b/src/server/routers/lambda/topic.ts@@ -49,7 +49,7 @@ export const topicRouter = router({),).mutation(async ({ input, ctx }): Promise<BatchTaskResult> => {- // 解析每个 topic 的 sessionId+ // Resolve sessionId for each topicconst resolvedTopics = await Promise.all(input.map(async (item) => {const { agentId, ...rest } = item;@@ -162,7 +162,7 @@ export const topicRouter = router({return { items: result.items, total: result.total };}- // 如果提供了 sessionId 但没有 agentId,需要反向查找 agentId+ // If sessionId is provided but no agentId, need to reverse lookup agentIdlet effectiveAgentId = rest.agentId;if (!effectiveAgentId && sessionId) {effectiveAgentId = await resolveAgentIdFromSession(sessionId, ctx.serverDB, ctx.userId);@@ -430,7 +430,7 @@ export const topicRouter = router({.mutation(async ({ input, ctx }) => {const { agentId, ...restValue } = input.value;- // 如果提供了 agentId,解析为 sessionId+ // If agentId is provided, resolve to sessionIdlet resolvedSessionId = restValue.sessionId;if (agentId && !resolvedSessionId) {const resolved = await resolveContext({ agentId }, ctx.serverDB, ctx.userId);diff --git a/src/server/routers/lambda/user.ts b/src/server/routers/lambda/user.tsindex 8129b0305e1..7c228be9cdc 100644--- a/src/server/routers/lambda/user.ts+++ b/src/server/routers/lambda/user.ts@@ -150,7 +150,7 @@ export const userRouter = router({firstName: state.firstName,fullName: state.fullName,- // 有消息,或者创建过助理,则认为有 conversation+ // Has conversation if there are messages or has created any assistanthasConversation: hasAnyMessages || hasExtraSession,interests: state.interests,@@ -190,40 +190,40 @@ export const userRouter = router({}),updateAvatar: userProcedure.input(z.string()).mutation(async ({ ctx, input }) => {- // 如果是 Base64 数据,需要上传到 S3+ // If it's Base64 data, need to upload to S3if (input.startsWith('data:image')) {try {- // 提取 mimeType,例如 "image/png"+ // Extract mimeType, e.g., "image/png"const prefix = 'data:';const semicolonIndex = input.indexOf(';');const mimeType =semicolonIndex !== -1 ? input.slice(prefix.length, semicolonIndex) : 'image/png';const fileType = mimeType.split('/')[1];- // 分割字符串,获取 Base64 部分+ // Split string to get the Base64 partconst commaIndex = input.indexOf(',');if (commaIndex === -1) {throw new Error('Invalid Base64 data');}const base64Data = input.slice(commaIndex + 1);- // 创建 S3 客户端+ // Create S3 clientconst s3 = new FileS3();- // 使用 UUID 生成唯一文件名,防止缓存问题- // 获取旧头像 URL, 后面删除该头像+ // Use UUID to generate unique filename to prevent caching issues+ // Get old avatar URL for later deletionconst userState = await ctx.userModel.getUserState(KeyVaultsGateKeeper.getUserKeyVaults);const oldAvatarUrl = userState.avatar;const fileName = `${uuidv4()}.${fileType}`;const filePath = `user/avatar/${ctx.userId}/${fileName}`;- // 将 Base64 数据转换为 Buffer 再上传到 S3+ // Convert Base64 data to Buffer and upload to S3const buffer = Buffer.from(base64Data, 'base64');await s3.uploadBuffer(filePath, buffer, mimeType);- // 删除旧头像+ // Delete old avatarif (oldAvatarUrl && oldAvatarUrl.startsWith('/webapi/')) {const oldFilePath = oldAvatarUrl.replace('/webapi/', '');await s3.deleteFile(oldFilePath);@@ -239,7 +239,7 @@ export const userRouter = router({}}- // 如果不是 Base64 数据,直接使用 URL 更新用户头像+ // If it's not Base64 data, directly use URL to update user avatarreturn ctx.userModel.updateUser({ avatar: input });}),diff --git a/src/server/routers/lambda/userMemories.ts b/src/server/routers/lambda/userMemories.tsindex c2f0daaf3c1..7fc52f070b8 100644--- a/src/server/routers/lambda/userMemories.ts+++ b/src/server/routers/lambda/userMemories.ts@@ -305,11 +305,11 @@ export const userMemoriesRouter = router({}}),- // REVIEW:根据当前 topic 直接提取记忆- // REVIEW: 我们需要一个既可以 cron 也可以主动用户触发进行「每日/每周/每隔一段时间的」记忆提取/生成的函数实现- // REVIEW: 定时任务- // 不用 tRPC,直接 server/service- // 可以参考 https://github.com/lobehub/lobe-chat-cloud/blob/886ff2fcd44b7b00a3aa8906f84914a6dcaa1815/src/app/(backend)/cron/reset-budgets/route.ts#L214+ // REVIEW: Extract memories directly from current topic+ // REVIEW: We need a function implementation that can be triggered both by cron and manually by users for "daily/weekly/periodic" memory extraction/generation+ // REVIEW: Scheduled task+ // Don't use tRPC, use server/service directly+ // Reference: https://github.com/lobehub/lobe-chat-cloud/blob/886ff2fcd44b7b00a3aa8906f84914a6dcaa1815/src/app/(backend)/cron/reset-budgets/route.ts#L214reEmbedMemories: memoryProcedure.input(reEmbedInputSchema.optional()).mutation(async ({ ctx, input }) => {@@ -740,7 +740,7 @@ export const userMemoriesRouter = router({}}),- // REVIEW: 需要实现 tool memory api+ // REVIEW: Need to implement tool memory apitoolAddContextMemory: memoryProcedure.input(ContextMemoryItemSchema).mutation(async ({ input, ctx }) => {