fix: resolve main thread block and high CPU issues

Switch 'fs.appendFileSync' to 'fs.appendFile' and optimize 'getSessionsCached' to reduce DB access.

Co-authored-by: Jason <159670257+Jasonzhu1207@users.noreply.github.com>
This commit is contained in:
v0
2026-04-06 11:28:33 +00:00
parent b130165831
commit 4beddb7a62

View File

@@ -65,13 +65,13 @@ function insightLog(level: 'INFO' | 'WARN' | 'ERROR', message: string): void {
console.log(`[InsightService] ${message}`) console.log(`[InsightService] ${message}`)
} }
// 写入桌面日志文件 // 异步写入桌面日志文件,避免同步磁盘 I/O 阻塞 Electron 主线程事件循环
try { try {
const desktopPath = app.getPath('desktop') const desktopPath = app.getPath('desktop')
const logFile = path.join(desktopPath, `weflow-insight-${dateStr}.log`) const logFile = path.join(desktopPath, `weflow-insight-${dateStr}.log`)
fs.appendFileSync(logFile, line, 'utf-8') fs.appendFile(logFile, line, 'utf-8', () => { /* 失败静默处理 */ })
} catch { } catch {
// 写文件失败静默处理,不影响主流程 // getPath 失败静默处理
} }
} }
@@ -372,10 +372,12 @@ class InsightService {
/** /**
* 获取会话列表优先使用缓存5 分钟 TTL * 获取会话列表优先使用缓存5 分钟 TTL
* 缓存命中时不访问 DB显著减少对主线程的占用 * 缓存命中时完全跳过数据库访问,避免频繁 connect() + getSessions() 消耗 CPU
* forceRefresh=true 时强制重新拉取(仅用于沉默扫描等低频场景)。
*/ */
private async getSessionsCached(forceRefresh = false): Promise<ChatSession[]> { private async getSessionsCached(forceRefresh = false): Promise<ChatSession[]> {
const now = Date.now() const now = Date.now()
// 缓存命中:直接返回,零数据库操作
if ( if (
!forceRefresh && !forceRefresh &&
this.sessionCache !== null && this.sessionCache !== null &&
@@ -383,13 +385,21 @@ class InsightService {
) { ) {
return this.sessionCache return this.sessionCache
} }
// 缓存未命中或强制刷新:连接数据库并拉取
try {
const connectResult = await chatService.connect() const connectResult = await chatService.connect()
if (!connectResult.success) return this.sessionCache ?? [] if (!connectResult.success) {
insightLog('WARN', '数据库连接失败,使用旧缓存')
return this.sessionCache ?? []
}
const result = await chatService.getSessions() const result = await chatService.getSessions()
if (result.success && result.sessions) { if (result.success && result.sessions) {
this.sessionCache = result.sessions as ChatSession[] this.sessionCache = result.sessions as ChatSession[]
this.sessionCacheAt = now this.sessionCacheAt = now
} }
} catch (e) {
insightLog('WARN', `获取会话缓存失败: ${(e as Error).message}`)
}
return this.sessionCache ?? [] return this.sessionCache ?? []
} }