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.

🌐 chore: translate non-English comments to English in services and desktop modules (#10339)

LobeHub Bot1ed9424166d9
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 064996c86e3..2bd879dbed5 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -4,9 +4,9 @@ import { setupRouteInterceptors } from './routeInterceptor';
const setupPreload = () => {
setupElectronApi();
- // 设置路由拦截逻辑
+ // Setup route interception logic
window.addEventListener('DOMContentLoaded', () => {
- // 设置客户端路由拦截器
+ // Setup client-side route interceptor
setupRouteInterceptors();
});
};
diff --git a/apps/desktop/src/preload/invoke.ts b/apps/desktop/src/preload/invoke.ts
index d7779c4ef5d..91a7a5e3dc3 100644
--- a/apps/desktop/src/preload/invoke.ts
+++ b/apps/desktop/src/preload/invoke.ts
@@ -2,7 +2,7 @@ import { ClientDispatchEventKey, DispatchInvoke } from '@lobechat/electron-clien
import { ipcRenderer } from 'electron';
/**
- * client 端请求 electron main 端方法
+ * Client-side method to invoke electron main process
*/
export const invoke: DispatchInvoke = async <T extends ClientDispatchEventKey>(
event: T,
diff --git a/apps/desktop/src/preload/routeInterceptor.ts b/apps/desktop/src/preload/routeInterceptor.ts
index 9c9c902c12d..b0a0732d3d4 100644
--- a/apps/desktop/src/preload/routeInterceptor.ts
+++ b/apps/desktop/src/preload/routeInterceptor.ts
@@ -9,7 +9,7 @@ const interceptRoute = async (
) => {
console.log(`[preload] Intercepted ${source} and prevented default behavior:`, path);
- // 使用electron-client-ipc的dispatch方法
+ // Use electron-client-ipc's dispatch method
try {
await invoke('interceptRoute', { path, source, url });
} catch (e) {
@@ -17,15 +17,15 @@ const interceptRoute = async (
}
};
/**
- * 路由拦截器 - 负责捕获和拦截客户端路由导航
+ * Route interceptor - Responsible for capturing and intercepting client-side route navigation
*/
export const setupRouteInterceptors = function () {
console.log('[preload] Setting up route interceptors');
- // 存储被阻止的路径,避免pushState重复触发
+ // Store prevented paths to avoid pushState duplicate triggers
const preventedPaths = new Set<string>();
- // 重写 window.open 方法来拦截 JavaScript 调用
+ // Override window.open method to intercept JavaScript calls
const originalWindowOpen = window.open;
window.open = function (url?: string | URL, target?: string, features?: string) {
if (url) {
@@ -33,15 +33,15 @@ export const setupRouteInterceptors = function () {
const urlString = typeof url === 'string' ? url : url.toString();
const urlObj = new URL(urlString, window.location.href);
- // 检查是否为外部链接
+ // Check if it's an external link
if (urlObj.origin !== window.location.origin) {
console.log(`[preload] Intercepted window.open for external URL:`, urlString);
- // 调用主进程处理外部链接
+ // Call main process to handle external link
invoke('openExternalLink', urlString);
- return null; // 返回 null 表示没有打开新窗口
+ return null; // Return null to indicate no window was opened
}
} catch (error) {
- // 处理无效 URL 或特殊协议
+ // Handle invalid URL or special protocol
console.error(`[preload] Intercepted window.open for special protocol:`, url);
console.error(error);
invoke('openExternalLink', typeof url === 'string' ? url : url.toString());
@@ -49,11 +49,11 @@ export const setupRouteInterceptors = function () {
}
}
- // 对于内部链接,调用原始的 window.open
+ // For internal links, call original window.open
return originalWindowOpen.call(window, url, target, features);
};
- // 拦截所有a标签的点击事件 - 针对Next.js的Link组件
+ // Intercept all a tag click events - For Next.js Link component
document.addEventListener(
'click',
async (e) => {
@@ -62,30 +62,30 @@ export const setupRouteInterceptors = function () {
try {
const url = new URL(link.href);
- // 检查是否为外部链接
+ // Check if it's an external link
if (url.origin !== window.location.origin) {
console.log(`[preload] Intercepted external link click:`, url.href);
- // 阻止默认的链接跳转行为
+ // Prevent default link navigation behavior
e.preventDefault();
e.stopPropagation();
- // 调用主进程处理外部链接
+ // Call main process to handle external link
await invoke('openExternalLink', url.href);
- return false; // 明确阻止后续处理
+ return false; // Explicitly prevent subsequent processing
}
- // 如果不是外部链接,则继续处理内部路由拦截逻辑
- // 使用共享配置检查是否需要拦截
+ // If not external link, continue with internal route interception logic
+ // Use shared config to check if interception is needed
const matchedRoute = findMatchingRoute(url.pathname);
- // 如果是需要拦截的路径
+ // If it's a path that needs interception
if (matchedRoute) {
const currentPath = window.location.pathname;
const isAlreadyInTargetPage = currentPath.startsWith(matchedRoute.pathPrefix);
- // 如果已经在目标页面下,则不拦截,让默认导航继续
+ // If already in target page, don't intercept, let default navigation continue
if (isAlreadyInTargetPage) return;
- // 立即阻止默认行为,避免Next.js接管路由
+ // Immediately prevent default behavior to avoid Next.js taking over routing
e.preventDefault();
e.stopPropagation();
@@ -94,15 +94,15 @@ export const setupRouteInterceptors = function () {
return false;
}
} catch (err) {
- // 处理可能的 URL 解析错误或其他问题
- // 例如 mailto:, tel: 等协议会导致 new URL() 抛出错误
+ // Handle possible URL parsing errors or other issues
+ // For example mailto:, tel: protocols will cause new URL() to throw error
if (err instanceof TypeError && err.message.includes('Invalid URL')) {
console.log(
'[preload] Non-HTTP link clicked, allowing default browser behavior:',
link.href,
);
- // 对于非 HTTP/HTTPS 链接,允许浏览器默认处理
- // 不需要 e.preventDefault() 或 invoke
+ // For non-HTTP/HTTPS links, allow browser default handling
+ // No need for e.preventDefault() or invoke
} else {
console.error('[preload] Link interception error:', err);
}
@@ -112,28 +112,28 @@ export const setupRouteInterceptors = function () {
true,
);
- // 拦截 history API (用于捕获Next.js的useRouter().push/replace等)
+ // Intercept history API (for capturing Next.js useRouter().push/replace etc.)
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;
- // 重写pushState
+ // Override pushState
history.pushState = function () {
const url = arguments[2];
if (typeof url === 'string') {
try {
- // 只处理相对路径或当前域的URL
+ // Only handle relative paths or current domain URLs
const parsedUrl = new URL(url, window.location.origin);
- // 使用共享配置检查是否需要拦截
+ // Use shared config to check if interception is needed
const matchedRoute = findMatchingRoute(parsedUrl.pathname);
- // 检查是否需要拦截这个导航
+ // Check if this navigation needs interception
if (matchedRoute) {
- // 检查当前页面是否已经在目标路径下,如果是则不拦截
+ // Check if current page is already under target path, if so don't intercept
const currentPath = window.location.pathname;
const isAlreadyInTargetPage = currentPath.startsWith(matchedRoute.pathPrefix);
- // 如果已经在目标页面下,则不拦截,让默认导航继续
+ // If already in target page, don't intercept, let default navigation continue
if (isAlreadyInTargetPage) {
console.log(
`[preload] Skip pushState interception for ${parsedUrl.pathname} because already in target page ${matchedRoute.pathPrefix}`,
@@ -141,13 +141,13 @@ export const setupRouteInterceptors = function () {
return Reflect.apply(originalPushState, this, arguments);
}
- // 将此路径添加到已阻止集合中
+ // Add this path to prevented set
preventedPaths.add(parsedUrl.pathname);
interceptRoute(parsedUrl.pathname, 'push-state', parsedUrl.href);
- // 不执行原始的pushState操作,阻止导航发生
- // 但返回undefined以避免错误
+ // Don't execute original pushState operation, prevent navigation
+ // But return undefined to avoid errors
return;
}
} catch (err) {
@@ -157,23 +157,23 @@ export const setupRouteInterceptors = function () {
return Reflect.apply(originalPushState, this, arguments);
};
- // 重写replaceState
+ // Override replaceState
history.replaceState = function () {
const url = arguments[2];
if (typeof url === 'string') {
try {
const parsedUrl = new URL(url, window.location.origin);
- // 使用共享配置检查是否需要拦截
+ // Use shared config to check if interception is needed
const matchedRoute = findMatchingRoute(parsedUrl.pathname);
- // 检查是否需要拦截这个导航
+ // Check if this navigation needs interception
if (matchedRoute) {
- // 检查当前页面是否已经在目标路径下,如果是则不拦截
+ // Check if current page is already under target path, if so don't intercept
const currentPath = window.location.pathname;
const isAlreadyInTargetPage = currentPath.startsWith(matchedRoute.pathPrefix);
- // 如果已经在目标页面下,则不拦截,让默认导航继续
+ // If already in target page, don't intercept, let default navigation continue
if (isAlreadyInTargetPage) {
console.log(
`[preload] Skip replaceState interception for ${parsedUrl.pathname} because already in target page ${matchedRoute.pathPrefix}`,
@@ -181,12 +181,12 @@ export const setupRouteInterceptors = function () {
return Reflect.apply(originalReplaceState, this, arguments);
}
- // 添加到已阻止集合
+ // Add to prevented set
preventedPaths.add(parsedUrl.pathname);
interceptRoute(parsedUrl.pathname, 'replace-state', parsedUrl.href);
- // 阻止导航
+ // Prevent navigation
return;
}
} catch (err) {
@@ -196,7 +196,7 @@ export const setupRouteInterceptors = function () {
return Reflect.apply(originalReplaceState, this, arguments);
};
- // 监听并拦截路由错误 - 有时Next.js会在路由错误时尝试恢复导航
+ // Listen and intercept routing errors - Sometimes Next.js tries to recover navigation on routing errors
window.addEventListener(
'error',
function (e) {
diff --git a/packages/database/src/client/db.ts b/packages/database/src/client/db.ts
index 75be57079a0..5c1be52de2c 100644
--- a/packages/database/src/client/db.ts
+++ b/packages/database/src/client/db.ts
@@ -38,7 +38,7 @@ export class DatabaseManager {
private callbacks?: DatabaseLoadingCallbacks;
private isLocalDBSchemaSynced = false;
- // CDN 配置
+ // CDN configuration
private static WASM_CDN_URL =
'https://registry.npmmirror.com/@electric-sql/pglite/0.2.17/files/dist/postgres.wasm';
@@ -57,7 +57,7 @@ export class DatabaseManager {
return DatabaseManager.instance;
}
- // 加载并编译 WASM 模块
+ // Load and compile WASM module
private async loadWasmModule(): Promise<WebAssembly.Module> {
const start = Date.now();
this.callbacks?.onStateChange?.(DatabaseLoadingState.LoadingWasm);
@@ -72,7 +72,7 @@ export class DatabaseManager {
let receivedLength = 0;
const chunks: Uint8Array[] = [];
- // 读取数据流
+ // Read data stream
// eslint-disable-next-line no-constant-condition
while (true) {
const { done, value } = await reader.read();
@@ -82,7 +82,7 @@ export class DatabaseManager {
chunks.push(value);
receivedLength += value.length;
- // 计算并报告进度
+ // Calculate and report progress
const progress = Math.min(Math.round((receivedLength / contentLength) * 100), 100);
this.callbacks?.onProgress?.({
phase: 'wasm',
@@ -90,7 +90,7 @@ export class DatabaseManager {
});
}
- // 合并数据块
+ // Merge data chunks
const wasmBytes = new Uint8Array(receivedLength);
let position = 0;
for (const chunk of chunks) {
@@ -104,7 +104,7 @@ export class DatabaseManager {
progress: 100,
});
- // 编译 WASM 模块
+ // Compile WASM module
return WebAssembly.compile(wasmBytes);
}
@@ -114,7 +114,7 @@ export class DatabaseManager {
return await res.blob();
};
- // 异步加载 PGlite 相关依赖
+ // Asynchronously load PGlite related dependencies
private async loadDependencies() {
const start = Date.now();
this.callbacks?.onStateChange?.(DatabaseLoadingState.LoadingDependencies);
@@ -135,7 +135,7 @@ export class DatabaseManager {
const result = await importPromise;
loaded += 1;
- // 计算加载进度
+ // Calculate loading progress
this.callbacks?.onProgress?.({
phase: 'dependencies',
progress: Math.min(Math.round((loaded / imports.length) * 100), 100),
@@ -156,7 +156,7 @@ export class DatabaseManager {
return { IdbFs, MemoryFS, PGlite, fsBundle, vector };
}
- // 数据库迁移方法
+ // Database migration method
private async migrate(skipMultiRun = false): Promise<DrizzleInstance> {
if (this.isLocalDBSchemaSynced && skipMultiRun) return this.db;
@@ -169,17 +169,17 @@ export class DatabaseManager {
try {
const drizzleMigration = new DrizzleMigrationModel(this.db as any);
- // 检查数据库中是否存在表
+ // Check if tables exist in database
const tableCount = await drizzleMigration.getTableCounts();
- // 如果表数量大于0,则认为数据库已正确初始化
+ // 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);
- // 如果查询失败,继续执行迁移以确保安全
+ // If query fails, continue migration to ensure safety
}
}
}
diff --git a/packages/database/src/repositories/dataImporter/index.ts b/packages/database/src/repositories/dataImporter/index.ts
index ca01f31187d..01d2447dbb6 100644
--- a/packages/database/src/repositories/dataImporter/index.ts
+++ b/packages/database/src/repositories/dataImporter/index.ts
@@ -17,39 +17,39 @@ interface ImportResult {
type ConflictStrategy = 'skip' | 'override' | 'merge';
interface TableImportConfig {
- // 冲突处理策略
+ // Conflict resolution strategy
conflictStrategy?: ConflictStrategy;
- // 字段处理函数
+ // Field processing functions
fieldProcessors?: {
[field: string]: (value: any) => any;
};
- // 是否使用复合主键(没有单独的id字段)
+ // Whether to use composite key (no separate id field)
isCompositeKey?: boolean;
- // 是否保留原始ID
+ // Whether to preserve original ID
preserveId?: boolean;
- // 关系字段定义
+ // Relation field definitions
relations?: {
field: string;
sourceField?: string;
sourceTable: string;
}[];
- // 自引用字段
+ // Self-reference fields
selfReferences?: {
field: string;
sourceField?: string;
}[];
- // 表名
+ // Table name
table: string;
- // 唯一约束字段
+ // Unique constraint fields
uniqueConstraints?: string[];
}
-// 导入表配置
+// Import table configuration
const IMPORT_TABLE_CONFIG: TableImportConfig[] = [
{
conflictStrategy: 'merge',
preserveId: true,
- // 特殊表,ID与用户ID相同
+ // Special table, ID same as user ID
table: 'userSettings',
uniqueConstraints: ['id'],
},
diff --git a/packages/database/src/schemas/topic.ts b/packages/database/src/schemas/topic.ts
index 77c5d37e9b7..7c2b6a1075a 100644
--- a/packages/database/src/schemas/topic.ts
+++ b/packages/database/src/schemas/topic.ts
@@ -77,7 +77,7 @@ export type ThreadItem = typeof threads.$inferSelect;
export const insertThreadSchema = createInsertSchema(threads);
/**
- * 文档与话题关联表 - 实现文档和话题的多对多关系
+ * Document-Topic association table - Implements many-to-many relationship between documents and topics
*/
export const topicDocuments = pgTable(
'topic_documents',
diff --git a/packages/database/src/server/models/ragEval/evaluation.ts b/packages/database/src/server/models/ragEval/evaluation.ts
index 1adff58cf35..345f2d21f22 100644
--- a/packages/database/src/server/models/ragEval/evaluation.ts
+++ b/packages/database/src/server/models/ragEval/evaluation.ts
@@ -56,7 +56,7 @@ export class EvalEvaluationModel {
),
);
- // 然后查询每个评估的记录统计
+ // Then query record statistics for each evaluation
const evaluationIds = evaluations.map((evals) => evals.id);
const recordStats = await this.db
diff --git a/src/services/debug.ts b/src/services/debug.ts
index 51ce6d59bcb..21db0d619cb 100644
--- a/src/services/debug.ts
+++ b/src/services/debug.ts
@@ -7,7 +7,7 @@ class DebugService {
// topicCount: 200,
// });
//
- // console.log('已插入10w');
+ // console.log('Inserted 100k');
//
// await DEBUG_MODEL.createRandomData({
// messageCount: 300_000,
@@ -15,7 +15,7 @@ class DebugService {
// startIndex: 100_001,
// topicCount: 200,
// });
- // console.log('已插入40w');
+ // console.log('Inserted 400k');
//
// await DEBUG_MODEL.createRandomData({
// messageCount: 300_000,
@@ -23,7 +23,7 @@ class DebugService {
// startIndex: 400_001,
// topicCount: 200,
// });
- // console.log('已插入70w');
+ // console.log('Inserted 700k');
//
// await DEBUG_MODEL.createRandomData({
// messageCount: 300_000,
@@ -31,7 +31,7 @@ class DebugService {
// startIndex: 700_001,
// topicCount: 200,
// });
- // console.log('已插入100w');
+ // console.log('Inserted 1M');
}
}
diff --git a/src/services/electron/remoteServer.ts b/src/services/electron/remoteServer.ts
index b9fd0b82aac..fcd8a4e10cc 100644
--- a/src/services/electron/remoteServer.ts
+++ b/src/services/electron/remoteServer.ts
@@ -2,35 +2,35 @@ import { DataSyncConfig, MarketAuthorizationParams, dispatch } from '@lobechat/e
class RemoteServerService {
/**
- * 获取远程服务器配置
+ * Get remote server configuration
*/
getRemoteServerConfig = async () => {
return dispatch('getRemoteServerConfig');
};
/**
- * 设置远程服务器配置
+ * Set remote server configuration
*/
setRemoteServerConfig = async (config: DataSyncConfig) => {
return dispatch('setRemoteServerConfig', config);
};
/**
- * 清除远程服务器配置
+ * Clear remote server configuration
*/
clearRemoteServerConfig = async () => {
return dispatch('clearRemoteServerConfig');
};
/**
- * 请求授权
+ * Request authorization
*/
requestAuthorization = async (config: DataSyncConfig) => {
return dispatch('requestAuthorization', config);
};
/**
- * 请求 Market 授权
+ * Request Market authorization
*/
requestMarketAuthorization = async (params: MarketAuthorizationParams) => {
return dispatch('requestMarketAuthorization', params);
diff --git a/src/services/electron/settings.ts b/src/services/electron/settings.ts
index 8c8d7a4514d..1b2490c00bf 100644
--- a/src/services/electron/settings.ts
+++ b/src/services/electron/settings.ts
@@ -6,42 +6,42 @@ import {
class DesktopSettingsService {
/**
- * 获取远程服务器配置
+ * Get proxy settings
*/
getProxySettings = async () => {
return dispatch('getProxySettings');
};
/**
- * 设置远程服务器配置
+ * Set proxy settings
*/
setSettings = async (data: Partial<NetworkProxySettings>) => {
return dispatch('setProxySettings', data);
};
/**
- * 获取桌面热键配置
+ * Get desktop hotkey configuration
*/
getDesktopHotkeys = async () => {
return dispatch('getShortcutsConfig');
};
/**
- * 更新桌面热键配置
+ * Update desktop hotkey configuration
*/
updateDesktopHotkey = async (id: string, accelerator: string): Promise<ShortcutUpdateResult> => {
return dispatch('updateShortcutConfig', { accelerator, id });
};
/**
- * 测试代理连接
+ * Test proxy connection
*/
testProxyConnection = async (url: string) => {
return dispatch('testProxyConnection', url);
};
/**
- * 测试指定的代理配置
+ * Test specified proxy configuration
*/
testProxyConfig = async (config: NetworkProxySettings, testUrl?: string) => {
return dispatch('testProxyConfig', { config, testUrl });
diff --git a/src/services/mcp.ts b/src/services/mcp.ts
index db81ba280b8..7358bbd9735 100644
--- a/src/services/mcp.ts
+++ b/src/services/mcp.ts
@@ -10,9 +10,9 @@ import { desktopClient, toolsClient } from '@/libs/trpc/client';
import { discoverService } from './discover';
/**
- * 计算对象的字节大小
- * @param obj 要计算大小的对象
- * @returns 字节大小
+ * Calculate byte size of object
+ * @param obj Object to calculate size of
+ * @returns Byte size
*/
function calculateObjectSizeBytes(obj: any): number {
try {
@@ -85,7 +85,7 @@ class MCPService {
const isStdio = plugin?.customParams?.mcp?.type === 'stdio';
- // 记录调用开始时间
+ // Record call start time
const callStartTime = Date.now();
let success = false;
let errorCode: string | undefined;
@@ -108,22 +108,22 @@ class MCPService {
errorCode = 'CALL_FAILED';
errorMessage = err.message;
- // 重新抛出错误,保持原有的错误处理逻辑
+ // 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
@@ -151,7 +151,7 @@ class MCPService {
version: plugin.manifest!.version || 'unknown',
};
- // 异步上报,不影响主流程
+ // Asynchronously report without affecting main flow
discoverService.reportPluginCall(reportData).catch((reportError) => {
console.warn('Failed to report MCP tool call:', reportError);
});
@@ -172,13 +172,13 @@ class MCPService {
},
signal?: AbortSignal,
) {
- // 如果是 Desktop 模式且 URL 是本地地址,使用 desktopClient
- // 这样可以避免在生产环境中通过远程服务器访问用户本地服务
+ // If in Desktop mode and URL is local address, use desktopClient
+ // This avoids accessing user local services through remote server in production
if (isDesktop && isLocalOrPrivateUrl(params.url)) {
return desktopClient.mcp.getStreamableMcpServerManifest.query(params, { signal });
}
- // 否则使用 toolsClient(通过服务器中转)
+ // Otherwise use toolsClient (via server relay)
return toolsClient.mcp.getStreamableMcpServerManifest.query(params, { signal });
}
@@ -199,16 +199,16 @@ class MCPService {
}
/**
- * 检查 MCP 插件安装状态
- * @param manifest MCP 插件清单
- * @param signal AbortSignal 用于取消请求
- * @returns 安装检测结果
+ * Check MCP plugin installation status
+ * @param manifest MCP plugin manifest
+ * @param signal AbortSignal for canceling request
+ * @returns Installation check result
*/
async checkInstallation(
manifest: PluginManifest,
signal?: AbortSignal,
): Promise<CheckMcpInstallResult> {
- // 将所有部署选项传递给主进程进行检查
+ // Pass all deployment options to main process for checking
return desktopClient.mcp.validMcpServerInstallable.mutate(
{ deploymentOptions: manifest.deploymentOptions as any },
{ signal },
diff --git a/src/services/models.ts b/src/services/models.ts
index 62292c2bce1..af88ff106d5 100644
--- a/src/services/models.ts
+++ b/src/services/models.ts
@@ -11,7 +11,7 @@ import { resolveRuntimeProvider } from './chat/helper';
const isEnableFetchOnClient = (provider: string) =>
aiProviderSelectors.isProviderFetchOnClient(provider)(getAiInfraStoreState());
-// 进度信息接口
+// Progress information interface
export interface ModelProgressInfo {
completed?: number;
digest?: string;
@@ -20,15 +20,15 @@ export interface ModelProgressInfo {
total?: number;
}
-// 进度回调函数类型
+// Progress callback function type
export type ProgressCallback = (progress: ModelProgressInfo) => void;
export type ErrorCallback = (error: { message: string }) => void;
export class ModelsService {
- // 用于中断下载的控制器
+ // Controller for aborting downloads
private _abortController: AbortController | null = null;
- // 获取模型列表
+ // Get model list
getModels = async (provider: string): Promise<ChatModelCard[] | undefined> => {
const headers = await createHeaderWithAuth({
headers: { 'Content-Type': 'application/json' },
@@ -59,14 +59,14 @@ export class ModelsService {
};
/**
- * 下载模型并通过回调函数返回进度信息
+ * Download model and return progress info through callback
*/
downloadModel = async (
{ model, provider }: { model: string; provider: string },
{ onProgress }: { onError?: ErrorCallback; onProgress?: ProgressCallback } = {},
): Promise<void> => {
try {
- // 创建一个新的 AbortController
+ // Create a new AbortController
this._abortController = new AbortController();
const signal = this._abortController.signal;
@@ -99,12 +99,12 @@ export class ModelsService {
throw await getMessageError(res);
}
- // 处理响应流
+ // Process response stream
if (res.body) {
await this.processModelPullStream(res, { onProgress });
}
} catch (error) {
- // 如果是取消操作,不需要继续抛出错误
+ // If operation is canceled, no need to continue throwing error
if (error instanceof DOMException && error.name === 'AbortError') {
return;
}
@@ -112,14 +112,14 @@ export class ModelsService {
console.error('download model error:', error);
throw error;
} finally {
- // 清理 AbortController
+ // Clean up AbortController
this._abortController = null;
}
};
- // 中断模型下载
+ // Abort model download
abortPull = () => {
- // 使用 AbortController 中断下载
+ // Use AbortController to abort download
if (this._abortController) {
this._abortController.abort();
this._abortController = null;
@@ -127,28 +127,28 @@ export class ModelsService {
};
/**
- * 处理模型下载流,解析进度信息并通过回调函数返回
- * @param response 响应对象
- * @param onProgress 进度回调函数
+ * Process model download stream, parse progress info and return via callback
+ * @param response Response object
+ * @param onProgress Progress callback function
* @returns Promise<void>
*/
private processModelPullStream = async (
response: Response,
{ onProgress, onError }: { onError?: ErrorCallback; onProgress?: ProgressCallback },
): Promise<void> => {
- // 处理响应流
+ // Process response stream
const reader = response.body?.getReader();
if (!reader) return;
- // 读取和处理流数据
+ // Read and process stream data
// eslint-disable-next-line no-constant-condition
while (true) {
const { done, value } = await reader.read();
if (done) break;
- // 解析进度数据
+ // Parse progress data
const progressText = new TextDecoder().decode(value);
- // 一行可能包含多个进度更新
+ // One line may contain multiple progress updates
const progressUpdates = progressText.trim().split('\n');
for (const update of progressUpdates) {
@@ -161,7 +161,7 @@ export class ModelsService {
}
if (progress.status === 'canceled') {
- console.log('progress:', progress);
+ console.log('progress:', progress);
// const abortError = new Error('abort');
// abortError.name = 'AbortError';
//
@@ -173,7 +173,7 @@ export class ModelsService {
throw new Error(progress.error);
}
- // 调用进度回调
+ // Call progress callback
if (progress.completed !== undefined || progress.status) {
onProgress?.(progress);
}