🤯 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 database & desktop modules (#11578)
LobeHub Botd33d374a1108
diff --git a/apps/desktop/src/common/routes.ts b/apps/desktop/src/common/routes.tsindex 3dd5e67bf50..91190fe9b9c 100644--- a/apps/desktop/src/common/routes.ts+++ b/apps/desktop/src/common/routes.ts@@ -1,36 +1,36 @@/**- * 路由拦截类型,描述拦截路由和目标窗口的映射关系+ * Route interception type, describing the mapping between intercepted routes and target windows*/export interface RouteInterceptConfig {/**- * 是否始终在新窗口中打开,即使目标窗口已经存在+ * Whether to always open in a new window, even if target window already exists*/alwaysOpenNew?: boolean;/**- * 描述+ * Description*/description: string;/**- * 是否启用拦截+ * Whether interception is enabled*/enabled: boolean;/**- * 路由模式前缀,例如 '/settings'+ * Route pattern prefix, e.g., '/settings'*/pathPrefix: string;/**- * 目标窗口标识符+ * Target window identifier*/targetWindow: string;}/**- * 拦截路由配置列表- * 定义了所有需要特殊处理的路由+ * Intercepted route configuration list+ * Defines all routes that require special handling*/export const interceptRoutes: RouteInterceptConfig[] = [{diff --git a/apps/desktop/src/main/const/dir.ts b/apps/desktop/src/main/const/dir.tsindex 09401f82c7b..801a6bb1cf2 100644--- a/apps/desktop/src/main/const/dir.ts+++ b/apps/desktop/src/main/const/dir.ts@@ -25,9 +25,9 @@ export const appStorageDir = join(userDataDir, 'lobehub-storage');// ------ Application storage directory ---- //-// 本地存储文件(模拟 S3)+// Local storage files (simulating S3)export const FILE_STORAGE_DIR = 'file-storage';-// Plugin 安装目录+// Plugin installation directoryexport const INSTALL_PLUGINS_DIR = 'plugins';// Desktop file servicediff --git a/apps/desktop/src/main/const/env.ts b/apps/desktop/src/main/const/env.tsindex fb515b5e077..964746377b7 100644--- a/apps/desktop/src/main/const/env.ts+++ b/apps/desktop/src/main/const/env.ts@@ -13,18 +13,18 @@ export const isLinux = linux();function getIsWindows11() {if (!isWindows) return false;- // 获取操作系统版本(如 "10.0.22621")+ // Get OS version (e.g., "10.0.22621")const release = os.release();const parts = release.split('.');- // 主版本和次版本+ // Major and minor versionconst majorVersion = parseInt(parts[0], 10);const minorVersion = parseInt(parts[1], 10);- // 构建号是第三部分+ // Build number is the third partconst buildNumber = parseInt(parts[2], 10);- // Windows 11 的构建号从 22000 开始+ // Windows 11 build numbers start from 22000return majorVersion === 10 && minorVersion === 0 && buildNumber >= 22_000;}diff --git a/apps/desktop/src/main/const/store.ts b/apps/desktop/src/main/const/store.tsindex 6f568bdbfec..3564056d225 100644--- a/apps/desktop/src/main/const/store.ts+++ b/apps/desktop/src/main/const/store.ts@@ -1,5 +1,5 @@/**- * 应用设置存储相关常量+ * Application settings storage related constants*/import { NetworkProxySettings } from '@lobechat/electron-client-ipc';@@ -8,7 +8,7 @@ import { DEFAULT_SHORTCUTS_CONFIG } from '@/shortcuts';import { ElectronMainStore } from '@/types/store';/**- * 存储名称+ * Storage name*/export const STORE_NAME = 'lobehub-settings';@@ -22,7 +22,7 @@ export const defaultProxySettings: NetworkProxySettings = {};/**- * 存储默认值+ * Storage default values*/export const STORE_DEFAULTS: ElectronMainStore = {dataSyncConfig: { storageMode: 'cloud' },diff --git a/apps/desktop/src/main/controllers/AuthCtr.ts b/apps/desktop/src/main/controllers/AuthCtr.tsindex c8dfe1fc0ca..125500808f8 100644--- a/apps/desktop/src/main/controllers/AuthCtr.ts+++ b/apps/desktop/src/main/controllers/AuthCtr.ts@@ -143,7 +143,7 @@ export default class AuthCtr extends ControllerModule {}/**- * 启动轮询机制获取凭证+ * Start polling mechanism to get credentials*/private startPolling() {if (!this.authRequestState) {diff --git a/apps/desktop/src/main/controllers/McpInstallCtr.ts b/apps/desktop/src/main/controllers/McpInstallCtr.tsindex e71b050792f..949e8e099b5 100644--- a/apps/desktop/src/main/controllers/McpInstallCtr.ts+++ b/apps/desktop/src/main/controllers/McpInstallCtr.ts@@ -8,23 +8,23 @@ const logger = createLogger('controllers:McpInstallCtr');const protocolHandler = createProtocolHandler('plugin');/**- * 验证 MCP Schema 对象结构+ * Validate MCP Schema object structure*/function validateMcpSchema(schema: any): schema is McpSchema {if (!schema || typeof schema !== 'object') return false;- // 必填字段验证+ // Required field validationif (typeof schema.identifier !== 'string' || !schema.identifier) return false;if (typeof schema.name !== 'string' || !schema.name) return false;if (typeof schema.author !== 'string' || !schema.author) return false;if (typeof schema.description !== 'string' || !schema.description) return false;if (typeof schema.version !== 'string' || !schema.version) return false;- // 可选字段验证+ // Optional field validationif (schema.homepage !== undefined && typeof schema.homepage !== 'string') return false;if (schema.icon !== undefined && typeof schema.icon !== 'string') return false;- // config 字段验证+ // config field validationif (!schema.config || typeof schema.config !== 'object') return false;const config = schema.config;@@ -35,13 +35,13 @@ function validateMcpSchema(schema: any): schema is McpSchema {} else if (config.type === 'http') {if (typeof config.url !== 'string' || !config.url) return false;try {- new URL(config.url); // 验证URL格式+ new URL(config.url); // Validate URL format} catch {return false;}if (config.headers !== undefined && typeof config.headers !== 'object') return false;} else {- return false; // 未知的 config type+ return false; // Unknown config type}return true;@@ -54,8 +54,8 @@ interface McpInstallParams {}/**- * MCP 插件安装控制器- * 负责处理 MCP 插件安装流程+ * MCP plugin installation controller+ * Responsible for handling MCP plugin installation process*/export default class McpInstallController extends ControllerModule {/**diff --git a/apps/desktop/src/main/controllers/NetworkProxyCtr.ts b/apps/desktop/src/main/controllers/NetworkProxyCtr.tsindex 3f8629cdf05..cdd95e54f26 100644--- a/apps/desktop/src/main/controllers/NetworkProxyCtr.ts+++ b/apps/desktop/src/main/controllers/NetworkProxyCtr.ts@@ -16,13 +16,13 @@ import { ControllerModule, IpcMethod } from './index';const logger = createLogger('controllers:NetworkProxyCtr');/**- * 网络代理控制器- * 处理桌面应用的网络代理相关功能+ * Network proxy controller+ * Handle desktop application network proxy related functions*/export default class NetworkProxyCtr extends ControllerModule {static override readonly groupName = 'networkProxy';/**- * 获取代理设置+ * Get proxy settings*/@IpcMethod()async getDesktopSettings(): Promise<NetworkProxySettings> {@@ -43,18 +43,18 @@ export default class NetworkProxyCtr extends ControllerModule {}/**- * 设置代理配置+ * Set proxy configuration*/@IpcMethod()async setProxySettings(config: Partial<NetworkProxySettings>): Promise<void> {try {- // 获取当前配置+ // Get current configurationconst currentConfig = this.app.storeManager.get('networkProxy',defaultProxySettings,) as NetworkProxySettings;- // 合并配置并验证+ // Merge configuration and validateconst newConfig = merge({}, currentConfig, config);const validation = ProxyConfigValidator.validate(newConfig);@@ -69,10 +69,10 @@ export default class NetworkProxyCtr extends ControllerModule {return;}- // 应用代理设置+ // Apply proxy settingsawait ProxyDispatcherManager.applyProxySettings(newConfig);- // 保存到存储+ // Save to storagethis.app.storeManager.set('networkProxy', newConfig);logger.info('Proxy settings updated successfully', {@@ -149,7 +149,7 @@ export default class NetworkProxyCtr extends ControllerModule {return;}- // 应用代理设置+ // Apply proxy settingsawait ProxyDispatcherManager.applyProxySettings(networkProxy);logger.info('Initial proxy settings applied successfully', {diff --git a/apps/desktop/src/main/controllers/RemoteServerSyncCtr.ts b/apps/desktop/src/main/controllers/RemoteServerSyncCtr.tsindex a55b833beef..28ba36e947d 100644--- a/apps/desktop/src/main/controllers/RemoteServerSyncCtr.ts+++ b/apps/desktop/src/main/controllers/RemoteServerSyncCtr.ts@@ -47,7 +47,7 @@ export default class RemoteServerSyncCtr extends ControllerModule {}/**- * 处理流式请求的 IPC 调用+ * Handle IPC calls for streaming requests*/private handleStreamRequest = async (event: IpcMainEvent, args: ProxyTRPCStreamRequestParams) => {const { requestId } = args;@@ -79,7 +79,7 @@ export default class RemoteServerSyncCtr extends ControllerModule {return;}- // 调用新的流式转发方法+ // Call new streaming forwarding methodawait this.forwardStreamRequest(event.sender, {...args,accessToken: token,@@ -95,7 +95,7 @@ export default class RemoteServerSyncCtr extends ControllerModule {};/**- * 执行实际的流式请求转发+ * Execute actual streaming request forwarding*/private async forwardStreamRequest(sender: WebContents,@@ -123,14 +123,14 @@ export default class RemoteServerSyncCtr extends ControllerModule {const clientReq = requester.request(requestOptions, (clientRes: IncomingMessage) => {logger.debug(`${logPrefix} Received response with status ${clientRes.statusCode}`);- // 添加调试信息+ // Add debug informationlogger.debug(`${logPrefix} Response details:`, {headers: clientRes.headers,statusCode: clientRes.statusCode,statusMessage: clientRes.statusMessage,});- // 1. 立刻发送响应头和状态码+ // 1. Immediately send response headers and status codeconst responseData = {headers: clientRes.headers || {},status: clientRes.statusCode || 500,@@ -140,21 +140,21 @@ export default class RemoteServerSyncCtr extends ControllerModule {logger.debug(`${logPrefix} Sending response data:`, responseData);sender.send(`stream:response:${requestId}`, responseData);- // 2. 监听数据块并转发+ // 2. Listen for data chunks and forwardclientRes.on('data', (chunk: Buffer) => {if (sender.isDestroyed()) return;logger.debug(`${logPrefix} Received data chunk, size: ${chunk.length}. Forwarding...`);sender.send(`stream:data:${requestId}`, chunk);});- // 3. 监听结束信号并转发+ // 3. Listen for end signal and forwardclientRes.on('end', () => {logger.debug(`${logPrefix} Stream ended. Forwarding end signal...`);if (sender.isDestroyed()) return;sender.send(`stream:end:${requestId}`);});- // 4. 监听响应流错误并转发+ // 4. Listen for response stream errors and forwardclientRes.on('error', (error) => {logger.error(`${logPrefix} Error reading response stream:`, error);if (sender.isDestroyed()) return;diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.tsindex ac691ab5bc3..da98c9d98e9 100644--- a/apps/desktop/src/main/core/App.ts+++ b/apps/desktop/src/main/core/App.ts@@ -127,7 +127,7 @@ export class App {// initialize protocol handlersthis.protocolManager.initialize();- // 统一处理 before-quit 事件+ // Unified handling of before-quit eventapp.on('before-quit', this.handleBeforeQuit);// Initialize theme mode from store@@ -224,10 +224,10 @@ export class App {/*** Handle protocol request by dispatching to registered handlers- * @param urlType 协议URL类型 (如: 'plugin')- * @param action 操作类型 (如: 'install')- * @param data 解析后的协议数据- * @returns 是否成功处理+ * @param urlType Protocol URL type (e.g., 'plugin')+ * @param action Action type (e.g., 'install')+ * @param data Parsed protocol data+ * @returns Whether successfully handled*/async handleProtocolRequest(urlType: string, action: string, data: any): Promise<boolean> {const key = `${urlType}:${action}`;@@ -241,7 +241,7 @@ export class App {try {logger.debug(`Dispatching protocol request ${key} to controller`);const result = await handler.controller[handler.methodName](data);- return result !== false; // 假设控制器返回 false 表示处理失败+ return result !== false; // Assume controller returning false indicates handling failure} catch (error) {logger.error(`Error handling protocol request ${key}:`, error);return false;@@ -385,17 +385,17 @@ export class App {this.ipcServer = new ElectronIPCServer(name, ipcServerEvents);}- // 新增 before-quit 处理函数+ // Add before-quit handler functionprivate handleBeforeQuit = () => {logger.info('Application is preparing to quit');this.isQuiting = true;- // 销毁托盘+ // Destroy trayif (process.platform === 'win32') {this.trayManager.destroyAll();}- // 执行清理操作+ // Execute cleanup operationsthis.staticFileServerManager.destroy();};}diff --git a/apps/desktop/src/main/core/infrastructure/StaticFileServerManager.ts b/apps/desktop/src/main/core/infrastructure/StaticFileServerManager.tsindex b4ffe35a13d..d5ad9689286 100644--- a/apps/desktop/src/main/core/infrastructure/StaticFileServerManager.ts+++ b/apps/desktop/src/main/core/infrastructure/StaticFileServerManager.ts@@ -160,7 +160,7 @@ export class StaticFileServerManager {logger.debug(`Request method: ${req.method}`);logger.debug(`Request headers: ${JSON.stringify(req.headers)}`);- // 提取文件路径:从 /desktop-file/path/to/file.png 中提取相对路径+ // 提取File path:从 /desktop-file/path/to/file.png 中提取相对路径let filePath = decodeURIComponent(url.pathname.slice(1)); // 移除开头的 /logger.debug(`Initial file path after decode: ${filePath}`);@@ -243,7 +243,7 @@ export class StaticFileServerManager {}/**- * 获取文件服务器域名+ * Get file server domain*/getFileServerDomain(): string {if (!this.isInitialized || !this.serverPort) {diff --git a/apps/desktop/src/main/core/ui/ShortcutManager.ts b/apps/desktop/src/main/core/ui/ShortcutManager.tsindex 70e8dd6d1e7..736dc187497 100644--- a/apps/desktop/src/main/core/ui/ShortcutManager.ts+++ b/apps/desktop/src/main/core/ui/ShortcutManager.ts@@ -77,25 +77,25 @@ export class ShortcutManager {try {logger.debug(`Updating shortcut ${id} to ${accelerator}`);- // 1. 检查 ID 是否有效+ // 1. Check if ID is validif (!DEFAULT_SHORTCUTS_CONFIG[id]) {logger.error(`Invalid shortcut ID: ${id}`);return { errorType: 'INVALID_ID', success: false };}- // 2. 基本格式校验+ // 2. Basic format validationif (!accelerator || typeof accelerator !== 'string' || accelerator.trim() === '') {logger.error(`Invalid accelerator format: ${accelerator}`);return { errorType: 'INVALID_FORMAT', success: false };}- // 转换前端格式到 Electron 格式+ // Convert frontend format to Electron formatconst convertedAccelerator = this.convertAcceleratorFormat(accelerator.trim());const cleanAccelerator = convertedAccelerator.toLowerCase();logger.debug(`Converted accelerator from ${accelerator} to ${convertedAccelerator}`);- // 3. 检查是否包含 + 号(修饰键格式)+ // 3. Check if contains + sign (modifier key format)if (!cleanAccelerator.includes('+')) {logger.error(`Invalid accelerator format: ${cleanAccelerator}. Must contain modifier keys like 'CommandOrControl+E'`,@@ -103,7 +103,7 @@ export class ShortcutManager {return { errorType: 'INVALID_FORMAT', success: false };}- // 4. 检查是否有基本的修饰键+ // 4. Check if has basic modifier keysconst hasModifier = ['CommandOrControl', 'Command', 'Ctrl', 'Alt', 'Shift'].some((modifier) =>cleanAccelerator.includes(modifier.toLowerCase()),);@@ -113,7 +113,7 @@ export class ShortcutManager {return { errorType: 'NO_MODIFIER', success: false };}- // 5. 检查冲突+ // 5. Check for conflictsfor (const [existingId, existingAccelerator] of Object.entries(this.shortcutsConfig)) {if (existingId !== id &&@@ -125,7 +125,7 @@ export class ShortcutManager {}}- // 6. 尝试注册测试(检查是否被系统占用)+ // 6. Try test registration (check if occupied by system)const testSuccess = globalShortcut.register(convertedAccelerator, () => {});if (!testSuccess) {logger.error(@@ -133,11 +133,11 @@ export class ShortcutManager {);return { errorType: 'SYSTEM_OCCUPIED', success: false };} else {- // 测试成功,立即取消注册+ // Test successful, immediately unregisterglobalShortcut.unregister(convertedAccelerator);}- // 7. 更新配置+ // 7. Update configurationthis.shortcutsConfig[id] = convertedAccelerator;this.saveShortcutsConfig();@@ -285,7 +285,7 @@ export class ShortcutManager {Object.entries(this.shortcutsConfig).forEach(([id, accelerator]) => {logger.debug(`Registering shortcut '${id}' with ${accelerator}`);- // 只注册在 DEFAULT_SHORTCUTS_CONFIG 中存在的快捷键+ // Only register shortcuts that exist in DEFAULT_SHORTCUTS_CONFIGif (!DEFAULT_SHORTCUTS_CONFIG[id]) {logger.debug(`Skipping shortcut '${id}' - not found in DEFAULT_SHORTCUTS_CONFIG`);return;diff --git a/apps/desktop/src/main/core/ui/TrayManager.ts b/apps/desktop/src/main/core/ui/TrayManager.tsindex 51e9d55e186..379ca02b1a7 100644--- a/apps/desktop/src/main/core/ui/TrayManager.ts+++ b/apps/desktop/src/main/core/ui/TrayManager.ts@@ -8,11 +8,11 @@ import { createLogger } from '@/utils/logger';import type { App } from '../App';import { Tray, TrayOptions } from './Tray';-// 创建日志记录器+// Create loggerconst logger = createLogger('core:TrayManager');/**- * 托盘标识符类型+ * Tray identifier type*/export type TrayIdentifiers = 'main';@@ -20,41 +20,41 @@ export class TrayManager {app: App;/**- * 存储所有托盘实例+ * Store all tray instances*/trays: Map<TrayIdentifiers, Tray> = new Map();/**- * 构造方法- * @param app 应用实例+ * Constructor+ * @param app Application instance*/constructor(app: App) {- logger.debug('初始化 TrayManager');+ logger.debug('Initialize TrayManager');this.app = app;}/**- * 初始化所有托盘+ * Initialize all trays*/initializeTrays() {- logger.debug('初始化应用托盘');+ logger.debug('Initialize application tray');- // 初始化主托盘+ // Initialize main traythis.initializeMainTray();}/**- * 获取主托盘+ * Get main tray*/getMainTray() {return this.retrieveByIdentifier('main');}/**- * 初始化主托盘+ * Initialize main tray*/initializeMainTray() {- logger.debug('初始化主托盘');+ logger.debug('Initialize main tray');return this.retrieveOrInitialize({iconPath: isMac? nativeTheme.shouldUseDarkColorsForSystemIntegratedUIdiff --git a/apps/desktop/src/main/locales/resources.ts b/apps/desktop/src/main/locales/resources.tsindex 0b0e9a99315..0aec4c8e350 100644--- a/apps/desktop/src/main/locales/resources.ts+++ b/apps/desktop/src/main/locales/resources.ts@@ -1,12 +1,12 @@/**- * 规范化语言代码+ * Normalize language code*/export const normalizeLocale = (locale: string) => {return locale.toLowerCase().replace('_', '-');};/**- * 按需加载翻译资源+ * Load translation resources on demand*/export const loadResources = async (lng: string, ns: string) => {// All en-* locales fallback to 'en' and use default TypeScript files@@ -16,7 +16,7 @@ export const loadResources = async (lng: string, ns: string) => {return content;} catch (error) {- console.error(`[I18n] 无法加载翻译文件: ${ns}`, error);+ console.error(`[I18n] Unable to load translation file: ${ns}`, error);return {};}}@@ -26,7 +26,7 @@ export const loadResources = async (lng: string, ns: string) => {return content;} catch (error) {- console.error(`无法加载翻译文件: ${lng} - ${ns}`, error);+ console.error(`Unable to load translation file: ${lng} - ${ns}`, error);return {};}};diff --git a/apps/desktop/src/main/menus/impls/macOS.ts b/apps/desktop/src/main/menus/impls/macOS.tsindex 770563b1864..780cef2624c 100644--- a/apps/desktop/src/main/menus/impls/macOS.ts+++ b/apps/desktop/src/main/menus/impls/macOS.ts@@ -47,7 +47,7 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {}refresh(options?: MenuOptions): void {- // 重建应用菜单+ // 重建Application menuthis.buildAndSetAppMenu(options);// 如果托盘菜单存在,也重建它(如果需要动态更新)// this.trayMenu = this.buildTrayMenu();diff --git a/apps/desktop/src/main/menus/types.ts b/apps/desktop/src/main/menus/types.tsindex 67e28e9cebb..366e4b9fa0c 100644--- a/apps/desktop/src/main/menus/types.ts+++ b/apps/desktop/src/main/menus/types.ts@@ -2,27 +2,27 @@ import { Menu } from 'electron';export interface MenuOptions {showDevItems?: boolean;- // 其他可能的配置项+ // Other possible configuration items}export interface IMenuPlatform {/**- * 构建并设置应用菜单+ * Build and set application menu*/buildAndSetAppMenu(options?: MenuOptions): Menu;/**- * 构建上下文菜单+ * Build context menu*/buildContextMenu(type: string, data?: any): Menu;/**- * 构建托盘菜单+ * Build tray menu*/buildTrayMenu(): Menu;/**- * 刷新菜单+ * Refresh menu*/refresh(options?: MenuOptions): void;}diff --git a/apps/desktop/src/main/modules/updater/configs.ts b/apps/desktop/src/main/modules/updater/configs.tsindex 4e468271e5c..dda4de7149c 100644--- a/apps/desktop/src/main/modules/updater/configs.ts+++ b/apps/desktop/src/main/modules/updater/configs.ts@@ -1,34 +1,34 @@import { isDev } from '@/const/env';import { getDesktopEnv } from '@/env';-// 更新频道(stable, beta, alpha 等)+// Update channel (stable, beta, alpha, etc.)export const UPDATE_CHANNEL = getDesktopEnv().UPDATE_CHANNEL || 'stable';-// 判断是否为 stable 频道+// Determine if stable channelexport const isStableChannel = UPDATE_CHANNEL === 'stable' || !UPDATE_CHANNEL;-// 自定义更新服务器 URL (用于 stable 频道)+// Custom update server URL (for stable channel)// e.g., https://releases.lobehub.com/stableexport const UPDATE_SERVER_URL = getDesktopEnv().UPDATE_SERVER_URL;-// GitHub 配置 (用于 beta/nightly 频道,或作为 fallback)+// GitHub configuration (for beta/nightly channels, or as fallback)export const githubConfig = {owner: 'lobehub',repo: 'lobe-chat',};export const updaterConfig = {- // 应用更新配置+ // 应用Update configurationapp: {- // 是否自动检查更新+ // Whether to auto-check for updatesautoCheckUpdate: true,- // 是否自动下载更新+ // Whether to auto-download updatesautoDownloadUpdate: true,- // 检查更新的时间间隔(毫秒)- checkUpdateInterval: 60 * 60 * 1000, // 1小时+ // Update check interval (milliseconds)+ checkUpdateInterval: 60 * 60 * 1000, // 1 hour},- // 是否启用应用更新+ // Whether to enable application updatesenableAppUpdate: !isDev,// 是否启用渲染层热更新diff --git a/apps/desktop/src/main/modules/updater/utils.ts b/apps/desktop/src/main/modules/updater/utils.tsindex e3588969921..d848524fa33 100644--- a/apps/desktop/src/main/modules/updater/utils.ts+++ b/apps/desktop/src/main/modules/updater/utils.ts@@ -1,33 +1,33 @@import semver from 'semver';/**- * 判断是否需要应用更新而非仅渲染层更新- * @param currentVersion 当前版本- * @param nextVersion 新版本- * @returns 是否需要应用更新+ * Determine if application update is needed rather than just renderer update+ * @param currentVersion Current version+ * @param nextVersion New version+ * @returns Whether application update is needed*/export const shouldUpdateApp = (currentVersion: string, nextVersion: string): boolean => {- // 如果版本号包含 .app 后缀,强制进行应用更新+ // If version contains .app suffix, force application updateif (nextVersion.includes('.app')) {return true;}try {- // 解析版本号+ // Parse version numberconst current = semver.parse(currentVersion);const next = semver.parse(nextVersion);if (!current || !next) return true;- // 主版本号或次版本号变更时,需要进行应用更新+ // Application update needed when major or minor version changesif (current.major !== next.major || current.minor !== next.minor) {return true;}- // 仅修订版本号变更,优先进行渲染层热更新+ // For patch version changes only, prioritize renderer hot updatereturn false;} catch {- // 解析失败时,默认进行应用更新+ // Default to application update when parsing failsreturn true;}};diff --git a/apps/desktop/src/main/services/fileSrv.ts b/apps/desktop/src/main/services/fileSrv.tsindex 998a849d043..0ad8b38b2dc 100644--- a/apps/desktop/src/main/services/fileSrv.ts+++ b/apps/desktop/src/main/services/fileSrv.ts@@ -11,7 +11,7 @@ import { createLogger } from '@/utils/logger';import { ServiceModule } from './index';/**- * 文件未找到错误类+ * File not found error class*/export class FileNotFoundError extends Error {constructor(@@ -46,8 +46,8 @@ export interface FileMetadata {export default class FileService extends ServiceModule {/**- * 获取旧版上传目录路径- * @deprecated 仅用于向后兼容旧版文件访问,新文件应存储在 FILE_STORAGE_DIR 的自定义路径下+ * Get legacy upload directory path+ * @deprecated Only for backward compatibility with legacy file access, new files should be stored under custom paths in FILE_STORAGE_DIR*/get UPLOADS_DIR() {return join(this.app.appStoragePath, FILE_STORAGE_DIR, 'uploads');@@ -58,7 +58,7 @@ export default class FileService extends ServiceModule {}/**- * 上传文件到本地存储+ * Upload file to local storage*/async uploadFile({content,@@ -69,15 +69,15 @@ export default class FileService extends ServiceModule {}: UploadFileParams): Promise<{ metadata: FileMetadata; success: boolean }> {logger.info(`Starting to upload file: ${filename}, hash: ${hash}, path: ${filePath}`);try {- // 获取当前时间戳,避免重复调用 Date.now()+ // Get current timestamp, avoid repeated Date.now() callsconst now = Date.now();const date = (now / 1000 / 60 / 60).toFixed(0);- // 使用传入的 filePath 作为文件的存储路径+ // Use provided filePath as the file storage pathconst fullStoragePath = join(this.app.appStoragePath, FILE_STORAGE_DIR, filePath);logger.debug(`Target file storage path: ${fullStoragePath}`);- // 确保目标目录存在+ // Ensure target directory existsconst targetDir = path.dirname(fullStoragePath);logger.debug(`Ensuring target directory exists: ${targetDir}`);makeSureDirExist(targetDir);@@ -85,23 +85,23 @@ export default class FileService extends ServiceModule {const savedPath = fullStoragePath;logger.debug(`Final file save path: ${savedPath}`);- // 根据 content 类型创建 Buffer+ // Create Buffer based on content typelet buffer: Buffer;if (typeof content === 'string') {- // 来自服务端的 Base64 字符串+ // Base64 string from serverbuffer = Buffer.from(content, 'base64');logger.debug(`Creating buffer from Base64 string, size: ${buffer.length} bytes`);} else {- // 来自浏览器端的 ArrayBuffer+ // ArrayBuffer from browserbuffer = Buffer.from(content);logger.debug(`Creating buffer from ArrayBuffer, size: ${buffer.length} bytes`);}await writeFile(savedPath, buffer);- // 写入元数据文件+ // Write metadata fileconst metaFilePath = `${savedPath}.meta`;const metadata = {- createdAt: now, // 使用统一的时间戳+ createdAt: now, // Use unified timestampfilename,hash,size: buffer.length,@@ -110,18 +110,18 @@ export default class FileService extends ServiceModule {logger.debug(`Writing metadata file: ${metaFilePath}`);await writeFile(metaFilePath, JSON.stringify(metadata, null, 2));- // 返回与S3兼容的元数据格式+ // Return S3-compatible metadata formatconst desktopPath = `desktop://${filePath}`;logger.info(`File upload successful: ${desktopPath}`);- // 从路径中提取文件名和目录信息+ // Extract filename and directory information from pathconst parsedPath = path.parse(filePath);const dirname = parsedPath.dir || '';const savedFilename = parsedPath.base;return {metadata: {- date, // 保持时间戳格式,用于兼容性和时间追踪+ date, // Keep timestamp format for compatibility and time trackingdirname,filename: savedFilename,path: desktopPath,@@ -135,25 +135,25 @@ export default class FileService extends ServiceModule {}/**- * 判断路径是否为旧版格式(时间戳目录)+ * Check if path is in legacy format (timestamp directory)*- * 旧版路径格式: {timestamp}/{hash}.{ext} (例如: 1234567890/abc123.png)- * 新版路径格式: 任意自定义路径 (例如: user_uploads/images/photo.png, ai_generations/image.jpg)+ * Legacy path format: {timestamp}/{hash}.{ext} (e.g., 1234567890/abc123.png)+ * New path format: arbitrary custom paths (e.g., user_uploads/images/photo.png, ai_generations/image.jpg)*- * @param path - 相对路径,不包含 desktop:// 前缀- * @returns true 如果是旧版格式,false 如果是新版格式+ * @param path - Relative path, without desktop:// prefix+ * @returns true if legacy format, false if new format*/private isLegacyPath(path: string): boolean {const parts = path.split('/');if (parts.length < 2) return false;- // 如果第一部分是纯数字(时间戳),则认为是旧版格式- // 时间戳格式:精确到小时的 Unix 时间戳,通常是 10 位数字+ // If the first part is purely numeric (timestamp), consider it legacy format+ // Timestamp format: Unix timestamp accurate to the hour, typically 10 digitsreturn /^\d+$/.test(parts[0]);}/**- * 获取文件内容+ * Get file content*/async getFile(path: string): Promise<{ content: ArrayBuffer; mimeType: string }> {logger.info(`Getting file content: ${path}`);@@ -164,30 +164,30 @@ export default class FileService extends ServiceModule {throw new Error(`Invalid desktop file path: ${path}`);}- // 标准化路径格式- // 可能收到的格式: desktop:/12345/file.png 或 desktop://12345/file.png+ // Normalize path format+ // Possible formats received: desktop:/12345/file.png or desktop://12345/file.pngconst normalizedPath = path.replace(/^desktop:\/+/, 'desktop://');logger.debug(`Normalized path: ${normalizedPath}`);- // 解析路径+ // Parse pathconst relativePath = normalizedPath.replace('desktop://', '');- // 智能路由:根据路径格式决定从哪个目录读取文件+ // Smart routing: decide which directory to read file from based on path formatlet filePath: string;let isLegacyAttempt = false;if (this.isLegacyPath(relativePath)) {- // 旧版路径:从 uploads 目录读取(向后兼容)+ // Legacy path: read from uploads directory (backward compatibility)filePath = join(this.UPLOADS_DIR, relativePath);isLegacyAttempt = true;logger.debug(`Legacy path detected, reading from uploads directory: ${filePath}`);} else {- // 新版路径:从 FILE_STORAGE_DIR 根目录读取+ // New path: read from FILE_STORAGE_DIR root directoryfilePath = join(this.app.appStoragePath, FILE_STORAGE_DIR, relativePath);logger.debug(`New path format, reading from storage root: ${filePath}`);}- // 读取文件内容,如果第一次尝试失败且是 legacy 路径,则尝试新路径+ // Read file content, if first attempt fails and is legacy path, try new pathlogger.debug(`Starting to read file content`);let content: Buffer;try {@@ -195,14 +195,14 @@ export default class FileService extends ServiceModule {logger.debug(`File content read complete, size: ${content.length} bytes`);} catch (firstError) {if (isLegacyAttempt) {- // 如果是 legacy 路径读取失败,尝试从新路径读取+ // If legacy path read fails, try reading from new pathconst fallbackPath = join(this.app.appStoragePath, FILE_STORAGE_DIR, relativePath);logger.debug(`Legacy path read failed, attempting fallback to storage root: ${fallbackPath}`,);try {content = await readFilePromise(fallbackPath);- filePath = fallbackPath; // 更新 filePath 用于后续的元数据读取+ filePath = fallbackPath; // Update filePath for subsequent metadata readinglogger.debug(`Fallback read successful, size: ${content.length} bytes`);} catch (fallbackError) {logger.error(@@ -215,9 +215,9 @@ export default class FileService extends ServiceModule {}}- // 读取元数据获取MIME类型+ // Read metadata to get MIME typeconst metaFilePath = `${filePath}.meta`;- let mimeType = 'application/octet-stream'; // 默认MIME类型+ let mimeType = 'application/octet-stream'; // Default MIME typelogger.debug(`Attempting to read metadata file: ${metaFilePath}`);try {@@ -229,7 +229,7 @@ export default class FileService extends ServiceModule {logger.warn(`Failed to read metadata file: ${(metaError as Error).message}, using default MIME type`,);- // 如果元数据文件不存在,尝试从文件扩展名猜测MIME类型+ // If metadata file doesn't exist, try to guess MIME type from file extensionconst ext = path.split('.').pop()?.toLowerCase();if (ext) {if (['jpg', 'jpeg'].includes(ext)) mimeType = 'image/jpeg';@@ -271,7 +271,7 @@ export default class FileService extends ServiceModule {} catch (error) {logger.error(`File retrieval failed:`, error);- // 如果是文件不存在错误,抛出自定义的 FileNotFoundError+ // If file not found error, throw custom FileNotFoundErrorif (error instanceof Error && error.message.includes('ENOENT')) {throw new FileNotFoundError(`File not found: ${path}`, path);}@@ -281,7 +281,7 @@ export default class FileService extends ServiceModule {}/**- * 删除文件+ * Delete file*/async deleteFile(path: string): Promise<{ success: boolean }> {logger.info(`Deleting file: ${path}`);@@ -292,42 +292,42 @@ export default class FileService extends ServiceModule {throw new Error(`Invalid desktop file path: ${path}`);}- // 标准化路径格式+ // Normalize path formatconst normalizedPath = path.replace(/^desktop:\/+/, 'desktop://');- // 解析路径+ // Parse pathconst relativePath = normalizedPath.replace('desktop://', '');- // 智能路由:根据路径格式决定从哪个目录删除文件+ // Smart routing: decide which directory to delete file from based on path formatlet filePath: string;let isLegacyAttempt = false;if (this.isLegacyPath(relativePath)) {- // 旧版路径:从 uploads 目录删除(向后兼容)+ // Legacy path: delete from uploads directory (backward compatibility)filePath = join(this.UPLOADS_DIR, relativePath);isLegacyAttempt = true;logger.debug(`Legacy path detected, deleting from uploads directory: ${filePath}`);} else {- // 新版路径:从 FILE_STORAGE_DIR 根目录删除+ // New path: delete from FILE_STORAGE_DIR root directoryfilePath = join(this.app.appStoragePath, FILE_STORAGE_DIR, relativePath);logger.debug(`New path format, deleting from storage root: ${filePath}`);}- // 删除文件及其元数据,如果第一次尝试失败且是 legacy 路径,则尝试新路径+ // Delete file and its metadata, if first attempt fails and is legacy path, try new pathlogger.debug(`Starting file deletion`);try {await unlinkPromise(filePath);logger.debug(`File deletion successful`);} catch (firstError) {if (isLegacyAttempt) {- // 如果是 legacy 路径删除失败,尝试从新路径删除+ // If legacy path deletion fails, try deleting from new pathconst fallbackPath = join(this.app.appStoragePath, FILE_STORAGE_DIR, relativePath);logger.debug(`Legacy path deletion failed, attempting fallback to storage root: ${fallbackPath}`,);try {await unlinkPromise(fallbackPath);- filePath = fallbackPath; // 更新 filePath 用于后续的元数据删除+ filePath = fallbackPath; // Update filePath for subsequent metadata deletionlogger.debug(`Fallback deletion successful`);} catch (fallbackError) {logger.error(@@ -340,7 +340,7 @@ export default class FileService extends ServiceModule {}}- // 尝试删除元数据文件,但不强制要求存在+ // Try to delete metadata file, but don't require it to existtry {logger.debug(`Attempting to delete metadata file`);await unlinkPromise(`${filePath}.meta`);@@ -358,13 +358,13 @@ export default class FileService extends ServiceModule {}/**- * 批量删除文件+ * Batch delete files*/async deleteFiles(paths: string[]): Promise<DeleteFilesResponse> {logger.info(`Batch deleting files, count: ${paths.length}`);const errors: { message: string; path: string }[] = [];- // 并行处理所有删除请求+ // Process all deletion requests in parallellogger.debug(`Starting parallel deletion requests`);const results = await Promise.allSettled(paths.map(async (path) => {@@ -382,7 +382,7 @@ export default class FileService extends ServiceModule {}),);- // 处理结果+ // Process resultslogger.debug(`Processing batch deletion results`);results.forEach((result) => {if (result.status === 'rejected') {@@ -411,31 +411,31 @@ export default class FileService extends ServiceModule {async getFilePath(path: string): Promise<string> {logger.debug(`Getting filesystem path: ${path}`);- // 处理desktop://路径+ // Handle desktop:// pathsif (!path.startsWith('desktop://')) {logger.error(`Invalid desktop file path: ${path}`);throw new Error(`Invalid desktop file path: ${path}`);}- // 标准化路径格式+ // Normalize path formatconst normalizedPath = path.replace(/^desktop:\/+/, 'desktop://');- // 解析路径+ // Parse pathconst relativePath = normalizedPath.replace('desktop://', '');- // 智能路由:根据路径格式决定从哪个目录获取文件路径+ // Smart routing: decide which directory to get file path from based on path formatlet fullPath: string;if (this.isLegacyPath(relativePath)) {- // 旧版路径:从 uploads 目录获取(向后兼容)+ // Legacy path: get from uploads directory (backward compatibility)fullPath = join(this.UPLOADS_DIR, relativePath);logger.debug(`Legacy path detected, resolved to uploads directory: ${fullPath}`);- // 检查文件是否存在,如果不存在则尝试新路径+ // Check if file exists, if not try new pathtry {await fs.promises.access(fullPath, fs.constants.F_OK);logger.debug(`Legacy path file exists: ${fullPath}`);} catch {- // 如果 legacy 路径文件不存在,尝试新路径+ // If legacy path file doesn't exist, try new pathconst fallbackPath = join(this.app.appStoragePath, FILE_STORAGE_DIR, relativePath);logger.debug(`Legacy path file not found, trying fallback path: ${fallbackPath}`);try {@@ -443,14 +443,14 @@ export default class FileService extends ServiceModule {fullPath = fallbackPath;logger.debug(`Fallback path file exists: ${fullPath}`);} catch {- // 两个路径都不存在,返回原始的 legacy 路径(保持原有行为)+ // Neither path exists, return original legacy path (maintain existing behavior)logger.debug(`Neither legacy nor fallback path exists, returning legacy path: ${fullPath}`,);}}} else {- // 新版路径:从 FILE_STORAGE_DIR 根目录获取+ // New path: get from FILE_STORAGE_DIR root directoryfullPath = join(this.app.appStoragePath, FILE_STORAGE_DIR, relativePath);logger.debug(`New path format, resolved to storage root: ${fullPath}`);}@@ -460,19 +460,19 @@ export default class FileService extends ServiceModule {async getFileHTTPURL(path: string): Promise<string> {logger.debug(`Getting file HTTP URL: ${path}`);- // 处理desktop://路径+ // Handle desktop:// pathsif (!path.startsWith('desktop://')) {logger.error(`Invalid desktop file path: ${path}`);throw new Error(`Invalid desktop file path: ${path}`);}- // 标准化路径格式+ // Normalize path formatconst normalizedPath = path.replace(/^desktop:\/+/, 'desktop://');- // 解析路径:从 desktop://path/to/file.png 中提取 path/to/file.png+ // Parse path: extract path/to/file.png from desktop://path/to/file.pngconst relativePath = normalizedPath.replace('desktop://', '');- // 使用 StaticFileServerManager 获取文件服务器域名,然后构建完整 URL+ // Use StaticFileServerManager to get file server domain, then construct full URLconst serverDomain = this.app.staticFileServerManager.getFileServerDomain();const httpURL = `${serverDomain}${LOCAL_STORAGE_URL_PREFIX}/${relativePath}`;logger.debug(`Generated HTTP URL: ${httpURL}`);diff --git a/apps/desktop/src/main/shortcuts/config.ts b/apps/desktop/src/main/shortcuts/config.tsindex 170bd96e37a..e44676ae52b 100644--- a/apps/desktop/src/main/shortcuts/config.ts+++ b/apps/desktop/src/main/shortcuts/config.ts@@ -1,10 +1,10 @@/**- * 快捷键操作类型枚举+ * Shortcut action type enum*/export const ShortcutActionEnum = {openSettings: 'openSettings',/**- * 显示/隐藏主窗口+ * Show/hide main window*/showApp: 'showApp',} as const;@@ -12,7 +12,7 @@ export const ShortcutActionEnum = {export type ShortcutActionType = (typeof ShortcutActionEnum)[keyof typeof ShortcutActionEnum];/**- * 默认快捷键配置+ * Default shortcut configuration*/export const DEFAULT_SHORTCUTS_CONFIG: Record<ShortcutActionType, string> = {[ShortcutActionEnum.showApp]: 'Control+E',diff --git a/apps/desktop/src/main/types/protocol.ts b/apps/desktop/src/main/types/protocol.tsindex cedeea1188a..22bc881ebce 100644--- a/apps/desktop/src/main/types/protocol.ts+++ b/apps/desktop/src/main/types/protocol.ts@@ -1,5 +1,5 @@/**- * MCP Schema - stdio 配置类型+ * MCP Schema - stdio configuration type*/export interface McpStdioConfig {args?: string[];@@ -9,7 +9,7 @@ export interface McpStdioConfig {}/**- * MCP Schema - http 配置类型+ * MCP Schema - http configuration type*/export interface McpHttpConfig {headers?: Record<string, string>;@@ -18,26 +18,26 @@ export interface McpHttpConfig {}/**- * MCP Schema 配置类型+ * MCP Schema configuration type*/export type McpConfig = McpStdioConfig | McpHttpConfig;/**- * MCP Schema 对象- * 符合 RFC 0001 定义+ * MCP Schema object+ * Conforms to RFC 0001 definition*/export interface McpSchema {- /** 插件作者 */+ /** Plugin author */author: string;- /** 插件配置 */+ /** Plugin configuration */config: McpConfig;- /** 插件描述 */+ /** Plugin description */description: string;- /** 插件主页 */+ /** Plugin homepage */homepage?: string;- /** 插件图标 */+ /** Plugin icon */icon?: string;- /** 插件唯一标识符,必须与URL中的id参数匹配 */+ /** Plugin unique identifier,必须与URL中的id参数匹配 */identifier: string;/** 插件名称 */name: string;@@ -49,7 +49,7 @@ export interface McpSchema {* 协议URL解析结果*/export interface ProtocolUrlParsed {- /** 操作类型 (如: 'install') */+ /** Action type (e.g., 'install') */action: string;/** 原始URL */originalUrl: string;diff --git a/apps/desktop/src/main/utils/file-system.ts b/apps/desktop/src/main/utils/file-system.tsindex eb8f4a50e5e..096746818f6 100644--- a/apps/desktop/src/main/utils/file-system.ts+++ b/apps/desktop/src/main/utils/file-system.ts@@ -4,11 +4,11 @@ export const makeSureDirExist = (dir: string) => {try {statSync(dir);} catch {- // 使用 recursive: true,如果目录已存在则此操作无效果,如果不存在则创建+ // Use recursive: true, no effect if directory exists, create if it doesn'ttry {mkdirSync(dir, { recursive: true });} catch (mkdirError: any) {- // 如果创建目录失败(例如权限问题),则抛出错误+ // Throw error if directory creation fails (e.g., permission issues)throw new Error(`Could not create target directory: ${dir}. Error: ${mkdirError.message}`);}}diff --git a/apps/desktop/src/main/utils/logger.ts b/apps/desktop/src/main/utils/logger.tsindex e6ba9eefb0d..754e1fc2350 100644--- a/apps/desktop/src/main/utils/logger.ts+++ b/apps/desktop/src/main/utils/logger.ts@@ -3,14 +3,14 @@ import electronLog from 'electron-log';import { getDesktopEnv } from '@/env';-// 配置 electron-log-electronLog.transports.file.level = 'info'; // 生产环境记录 info 及以上级别+// Configure electron-log+electronLog.transports.file.level = 'info'; // Log info level and above in productionelectronLog.transports.console.level =getDesktopEnv().NODE_ENV === 'development'- ? 'debug' // 开发环境显示更多日志- : 'warn'; // 生产环境只显示警告和错误+ ? 'debug' // Show more logs in development+ : 'warn'; // Only show warnings and errors in production-// 创建命名空间调试器+// Create namespaced debuggerexport const createLogger = (namespace: string) => {const debugLogger = debug(namespace);diff --git a/apps/desktop/src/main/utils/protocol.ts b/apps/desktop/src/main/utils/protocol.tsindex 7341f545c60..ac05da0d5cf 100644--- a/apps/desktop/src/main/utils/protocol.ts+++ b/apps/desktop/src/main/utils/protocol.ts@@ -5,16 +5,16 @@ import { McpSchema, ProtocolUrlParsed } from '../types/protocol';export type AppChannel = 'stable' | 'beta' | 'nightly';export const getProtocolScheme = (): string => {- // 在 Electron 环境中可以通过多种方式判断版本+ // In Electron environment, version can be determined in multiple waysconst bundleId = app.name;const appPath = app.getPath('exe');- // 通过 bundle identifier 判断+ // Determine by bundle identifierif (bundleId?.toLowerCase().includes('nightly')) return 'lobehub-nightly';if (bundleId?.toLowerCase().includes('beta')) return 'lobehub-beta';if (bundleId?.includes('dev')) return 'lobehub-dev';- // 通过可执行文件路径判断+ // Determine by executable file pathif (appPath?.toLowerCase().includes('nightly')) return 'lobehub-nightly';if (appPath?.toLowerCase().includes('beta')) return 'lobehub-beta';if (appPath?.includes('dev')) return 'lobehub-dev';@@ -39,25 +39,25 @@ export const getVersionInfo = (): { channel: AppChannel; protocolScheme: string};/**- * 验证 MCP Schema 对象结构- * @param schema 待验证的对象- * @returns 是否为有效的 MCP Schema+ * Validate MCP Schema object structure+ * @param schema Object to validate+ * @returns Whether it's a valid MCP Schema*/function validateMcpSchema(schema: any): schema is McpSchema {if (!schema || typeof schema !== 'object') return false;- // 必填字段验证+ // Required field validationif (typeof schema.identifier !== 'string' || !schema.identifier) return false;if (typeof schema.name !== 'string' || !schema.name) return false;if (typeof schema.author !== 'string' || !schema.author) return false;if (typeof schema.description !== 'string' || !schema.description) return false;if (typeof schema.version !== 'string' || !schema.version) return false;- // 可选字段验证+ // Optional field validationif (schema.homepage !== undefined && typeof schema.homepage !== 'string') return false;if (schema.icon !== undefined && typeof schema.icon !== 'string') return false;- // config 字段验证+ // config field validationif (!schema.config || typeof schema.config !== 'object') return false;const config = schema.config;@@ -68,42 +68,42 @@ function validateMcpSchema(schema: any): schema is McpSchema {} else if (config.type === 'http') {if (typeof config.url !== 'string' || !config.url) return false;try {- new URL(config.url); // 验证URL格式+ new URL(config.url); // Validate URL format} catch {return false;}if (config.headers !== undefined && typeof config.headers !== 'object') return false;} else {- return false; // 未知的 config type+ return false; // Unknown config type}return true;}/**- * 解析 lobehub:// 协议 URL (支持多版本协议)+ * Parse lobehub:// protocol URL (supports multi-version protocols)*- * 支持的URL格式:+ * Supported URL formats:* - lobehub://plugin/install?id=figma&schema=xxx&marketId=lobehub* - lobehub://plugin/configure?id=xxx&...* - lobehub-bet://plugin/install?id=figma&schema=xxx&marketId=lobehub* - lobehub-nightly://plugin/install?id=figma&schema=xxx&marketId=lobehub* - lobehub-dev://plugin/install?id=figma&schema=xxx&marketId=lobehub*- * @param url 协议 URL- * @returns 解析结果,包含基本结构和所有查询参数+ * @param url Protocol URL+ * @returns Parse result, including basic structure and all query parameters*/export const parseProtocolUrl = (url: string): ProtocolUrlParsed | null => {try {const parsedUrl = new URL(url);- // 支持多种协议 scheme+ // Support multiple protocol schemesconst validProtocols = ['lobehub:', 'lobehub-dev:', 'lobehub-nightly:', 'lobehub-beta:'];if (!validProtocols.includes(parsedUrl.protocol)) {return null;}- // 对于自定义协议,URL 解析后:+ // For custom protocols, after URL parsing:// lobehub://plugin/install -> hostname: "plugin", pathname: "/install"const urlType = parsedUrl.hostname; // "plugin"const pathParts = parsedUrl.pathname.split('/').filter(Boolean); // ["install"]@@ -114,7 +114,7 @@ export const parseProtocolUrl = (url: string): ProtocolUrlParsed | null => {const action = pathParts[0]; // "install"- // 解析所有查询参数+ // Parse all query parametersconst params: Record<string, string> = {};const searchParams = new URLSearchParams(parsedUrl.search);@@ -135,48 +135,48 @@ export const parseProtocolUrl = (url: string): ProtocolUrlParsed | null => {};/**- * 生成符合 RFC 0001 的协议 URL+ * Generate RFC 0001 compliant protocol URL*- * @param params 协议参数- * @returns 生成的协议URL+ * @param params Protocol parameters+ * @returns Generated protocol URL*/export function generateRFCProtocolUrl(params: {- /** 插件唯一标识符 */+ /** Plugin unique identifier */id: string;/** Marketplace ID */marketId?: string;- /** MCP Schema 对象 */+ /** MCP Schema object */schema: McpSchema;- /** 协议 scheme (默认: lobehub) */+ /** Protocol scheme (default: lobehub) */scheme?: string;}): string {const { id, schema, marketId, scheme = 'lobehub' } = params;- // 验证 schema.identifier 与 id 匹配+ // Validate schema.identifier matches idif (schema.identifier !== id) {throw new Error('Schema identifier must match the id parameter');}- // 验证 schema 结构+ // Validate schema structureif (!validateMcpSchema(schema)) {throw new Error('Invalid MCP Schema structure');}- // 构建基础 URL+ // Build base URLconst baseUrl = `${scheme}://plugin/install`;- // 构建查询参数+ // Build query parametersconst searchParams = new URLSearchParams();- // 必需参数+ // Required parameterssearchParams.set('type', 'mcp');searchParams.set('id', id);- // 编码 schema - 直接传 JSON 字符串,让 URLSearchParams 自动编码+ // Encode schema - pass JSON string directly, let URLSearchParams auto-encodeconst schemaJson = JSON.stringify(schema);searchParams.set('schema', schemaJson);- // 可选参数+ // Optional parametersif (marketId) {searchParams.set('marketId', marketId);}@@ -185,7 +185,7 @@ export function generateRFCProtocolUrl(params: {}/**- * 生成协议 URL 示例+ * Generate protocol URL example** @example* ```typescriptdiff --git a/packages/database/src/schemas/relations.ts b/packages/database/src/schemas/relations.tsindex 4fe016e7fca..39861bdb068 100644--- a/packages/database/src/schemas/relations.ts+++ b/packages/database/src/schemas/relations.ts@@ -220,7 +220,7 @@ export const filesRelations = relations(files, ({ many, one }) => ({}),}));-// Document 相关关系定义+// Document-related relation definitionsexport const documentsRelations = relations(documents, ({ one, many }) => ({file: one(files, {fields: [documents.fileId],@@ -249,7 +249,7 @@ export const documentChunksRelations = relations(documentChunks, ({ one }) => ({}),}));-// Generation 相关关系定义+// Generation-related relation definitionsexport const generationTopicsRelations = relations(generationTopics, ({ one, many }) => ({user: one(users, {fields: [generationTopics.userId],@@ -289,7 +289,7 @@ export const generationsRelations = relations(generations, ({ one }) => ({}),}));-// Chat Groups 相关关系定义+// Chat Groups-related relation definitionsexport const chatGroupsRelations = relations(chatGroups, ({ many, one }) => ({user: one(users, {fields: [chatGroups.userId],@@ -313,7 +313,7 @@ export const chatGroupsAgentsRelations = relations(chatGroupsAgents, ({ one }) =}),}));-// Message Groups 相关关系定义+// Message Groups-related relation definitionsexport const messageGroupsRelations = relations(messageGroups, ({ many, one }) => ({user: one(users, {fields: [messageGroups.userId],