diff --git a/build/installer.nsh b/build/installer.nsh new file mode 100644 index 0000000..0a9b1c1 --- /dev/null +++ b/build/installer.nsh @@ -0,0 +1,347 @@ +!include "LogicLib.nsh" +!include "getProcessInfo.nsh" + +Var tmSelfPid + +!ifndef BUILD_UNINSTALLER + Var tmTempRedirected + Var tmOrigTemp + Var tmOrigTmp + Var tmAltTempDir + Var tmOldInstDir + Var tmOldDrive + Var tmTempDrive +!endif + +!macro TM_FIND_PROCESS _FILE _ERR + !ifdef INSTALL_MODE_PER_ALL_USERS + ${nsProcess::FindProcess} "${_FILE}" ${_ERR} + !else + nsExec::Exec `"$SYSDIR\cmd.exe" /c tasklist /FI "USERNAME eq %USERNAME%" /FI "IMAGENAME eq ${_FILE}" /FO csv | "$SYSDIR\find.exe" /I "${_FILE}"` + Pop ${_ERR} + !endif +!macroend + +!macro TM_TASKKILL_SOFT _FILE _PID + !ifdef INSTALL_MODE_PER_ALL_USERS + nsExec::Exec `taskkill /im "${_FILE}" /fi "PID ne ${_PID}"` + !else + nsExec::Exec `"$SYSDIR\cmd.exe" /c taskkill /im "${_FILE}" /fi "PID ne ${_PID}" /fi "USERNAME eq %USERNAME%"` + !endif + Pop $R9 +!macroend + +!macro TM_TASKKILL_FORCE_TREE _FILE _PID + !ifdef INSTALL_MODE_PER_ALL_USERS + nsExec::Exec `taskkill /f /t /im "${_FILE}" /fi "PID ne ${_PID}"` + !else + nsExec::Exec `"$SYSDIR\cmd.exe" /c taskkill /f /t /im "${_FILE}" /fi "PID ne ${_PID}" /fi "USERNAME eq %USERNAME%"` + !endif + Pop $R9 +!macroend + +!macro customHeader + !ifndef BUILD_UNINSTALLER + ; 旧版卸载器在 --updated 模式下会把文件 Rename 到 %TEMP% 下的 $PLUGINSDIR\old-install。 + ; 若旧版装在非系统盘,把子进程继承的 TEMP/TMP 暂指同盘符可写目录,避免跨卷 Rename 必败。 + Function tmPrepareCrossDriveUpdateTemp + Push $0 + Push $1 + + StrCpy $tmTempRedirected "0" + StrCpy $tmAltTempDir "" + StrCpy $tmOldInstDir "" + + ReadRegStr $tmOldInstDir SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation + ${if} $tmOldInstDir == "" + ReadRegStr $tmOldInstDir HKEY_CURRENT_USER "${INSTALL_REGISTRY_KEY}" InstallLocation + ${endIf} + ${if} $tmOldInstDir == "" + StrCpy $tmOldInstDir "$INSTDIR" + ${endIf} + + StrCpy $tmOldDrive $tmOldInstDir 2 + StrCpy $tmTempDrive $TEMP 2 + ${if} $tmOldDrive == "" + ${orIf} $tmTempDrive == "" + ${orIf} $tmOldDrive == $tmTempDrive + Goto tm_temp_done + ${endIf} + + StrCpy $0 $tmOldInstDir 1 -1 + ${if} $0 == "\" + StrCpy $tmOldInstDir $tmOldInstDir -1 + ${endIf} + + StrCpy $tmAltTempDir "$tmOldInstDir._tm_upd_tmp" + CreateDirectory "$tmAltTempDir" + ClearErrors + FileOpen $1 "$tmAltTempDir\.probe" w + ${if} ${Errors} + StrCpy $tmAltTempDir "$tmOldDrive\.tracememo_upd_tmp" + CreateDirectory "$tmAltTempDir" + ClearErrors + FileOpen $1 "$tmAltTempDir\.probe" w + ${if} ${Errors} + StrCpy $tmAltTempDir "" + Goto tm_temp_done + ${endIf} + ${endIf} + FileClose $1 + Delete "$tmAltTempDir\.probe" + + ReadEnvStr $tmOrigTemp "TEMP" + ReadEnvStr $tmOrigTmp "TMP" + System::Call 'kernel32::SetEnvironmentVariableW(w "TEMP", w "$tmAltTempDir") i.r0' + System::Call 'kernel32::SetEnvironmentVariableW(w "TMP", w "$tmAltTempDir") i.r0' + StrCpy $tmTempRedirected "1" + + tm_temp_done: + Pop $1 + Pop $0 + FunctionEnd + + Function tmRestoreCrossDriveUpdateTemp + Push $0 + ${if} $tmTempRedirected == "1" + ${if} $tmOrigTemp != "" + System::Call 'kernel32::SetEnvironmentVariableW(w "TEMP", w "$tmOrigTemp") i.r0' + ${endIf} + ${if} $tmOrigTmp != "" + System::Call 'kernel32::SetEnvironmentVariableW(w "TMP", w "$tmOrigTmp") i.r0' + ${endIf} + ${if} $tmAltTempDir != "" + RMDir /r "$tmAltTempDir" + ${endIf} + StrCpy $tmTempRedirected "0" + ${endIf} + Pop $0 + FunctionEnd + !else + Var /GLOBAL tmOldBackupRoot + + Function un.tmAtomicMoveToBackup + Exch $R0 + Push $R1 + Push $R2 + Push $R3 + + StrCpy $R3 "$INSTDIR$R0\*.*" + FindFirst $R1 $R2 $R3 + + tm_move_loop: + StrCmp $R2 "" tm_move_break + StrCmp $R2 "." tm_move_continue + StrCmp $R2 ".." tm_move_continue + + IfFileExists "$INSTDIR$R0\$R2\*.*" tm_move_is_dir tm_move_is_file + + tm_move_is_dir: + CreateDirectory "$tmOldBackupRoot$R0\$R2" + Push "$R0\$R2" + Call un.tmAtomicMoveToBackup + Pop $R3 + ${if} $R3 != 0 + Goto tm_move_done + ${endIf} + Goto tm_move_continue + + tm_move_is_file: + ClearErrors + Rename "$INSTDIR$R0\$R2" "$tmOldBackupRoot$R0\$R2" + StrCmp "$R0\$R2" "\${UNINSTALL_FILENAME}" 0 +2 + ClearErrors + StrCmp "$R0\$R2" "${UNINSTALL_FILENAME}" 0 +2 + ClearErrors + + IfErrors 0 +3 + StrCpy $R3 "$INSTDIR$R0\$R2" + Goto tm_move_done + + tm_move_continue: + FindNext $R1 $R2 + Goto tm_move_loop + + tm_move_break: + StrCpy $R3 0 + + tm_move_done: + FindClose $R1 + StrCpy $R0 $R3 + Pop $R3 + Pop $R2 + Pop $R1 + Exch $R0 + FunctionEnd + + Function un.tmRestoreFromBackup + Exch $R0 + Push $R1 + Push $R2 + Push $R3 + + StrCpy $R3 "$tmOldBackupRoot$R0\*.*" + FindFirst $R1 $R2 $R3 + + tm_restore_loop: + StrCmp $R2 "" tm_restore_break + StrCmp $R2 "." tm_restore_continue + StrCmp $R2 ".." tm_restore_continue + + IfFileExists "$tmOldBackupRoot$R0\$R2\*.*" tm_restore_is_dir tm_restore_is_file + + tm_restore_is_dir: + CreateDirectory "$INSTDIR$R0\$R2" + Push "$R0\$R2" + Call un.tmRestoreFromBackup + Pop $R3 + Goto tm_restore_continue + + tm_restore_is_file: + Rename "$tmOldBackupRoot$R0\$R2" "$INSTDIR$R0\$R2" + + tm_restore_continue: + FindNext $R1 $R2 + Goto tm_restore_loop + + tm_restore_break: + StrCpy $R0 0 + FindClose $R1 + Pop $R3 + Pop $R2 + Pop $R1 + Exch $R0 + FunctionEnd + !endif +!macroend + +!macro customCheckAppRunning + ${GetProcessInfo} 0 $tmSelfPid $1 $2 $3 $4 + ${if} $3 != "${APP_EXECUTABLE_FILENAME}" + ${if} ${isUpdated} + Sleep 500 + ${endIf} + + !insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0 + ${if} $R0 == 0 + ${if} ${isUpdated} + Sleep 1000 + !insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0 + ${if} $R0 != 0 + Goto tm_app_not_running + ${endIf} + Goto tm_do_stop_process + ${endIf} + MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "$(appRunning)" /SD IDOK IDOK tm_do_stop_process + Quit + + tm_do_stop_process: + DetailPrint `Closing running "${PRODUCT_NAME}"...` + !insertmacro TM_TASKKILL_SOFT "${APP_EXECUTABLE_FILENAME}" $tmSelfPid + Sleep 500 + + StrCpy $R1 0 + + tm_stop_loop: + IntOp $R1 $R1 + 1 + + !insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0 + ${if} $R0 == 0 + Sleep 1000 + !insertmacro TM_TASKKILL_FORCE_TREE "${APP_EXECUTABLE_FILENAME}" $tmSelfPid + Sleep 500 + !insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0 + ${if} $R0 == 0 + DetailPrint `Waiting for "${PRODUCT_NAME}" to close.` + Sleep 1500 + ${else} + Goto tm_app_not_running + ${endIf} + ${else} + Goto tm_app_not_running + ${endIf} + + ${if} $R1 > 1 + MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "$(appCannotBeClosed)" /SD IDCANCEL IDRETRY tm_stop_loop + Quit + ${else} + Goto tm_stop_loop + ${endIf} + + tm_app_not_running: + ${endIf} + ${endIf} + + !ifndef BUILD_UNINSTALLER + Call tmPrepareCrossDriveUpdateTemp + !endif +!macroend + +!ifndef BUILD_UNINSTALLER + !macro customInstall + Call tmRestoreCrossDriveUpdateTemp + !macroend +!endif + +!ifdef BUILD_UNINSTALLER + ; 同盘符沿用原生 $PLUGINSDIR\old-install,跨盘符改用同卷旁路目录避免 Rename 必败。 + !macro customRemoveFiles + ${if} ${isUpdated} + StrCpy $0 $INSTDIR 2 + StrCpy $1 $PLUGINSDIR 2 + ${if} $0 == $1 + CreateDirectory "$PLUGINSDIR\old-install" + Push "" + Call un.atomicRMDir + Pop $R0 + ${if} $R0 != 0 + DetailPrint "File is busy, aborting: $R0" + Push "" + Call un.restoreFiles + Pop $R0 + Abort `Can't rename "$INSTDIR" to "$PLUGINSDIR\old-install".` + ${endIf} + ${else} + StrCpy $2 $INSTDIR + StrCpy $3 $2 1 -1 + ${if} $3 == "\" + StrCpy $2 $2 -1 + ${endIf} + StrCpy $tmOldBackupRoot "$2._tm_old" + RMDir /r "$tmOldBackupRoot" + CreateDirectory "$tmOldBackupRoot" + + ClearErrors + FileOpen $4 "$tmOldBackupRoot\.probe" w + ${ifNot} ${Errors} + FileClose $4 + Delete "$tmOldBackupRoot\.probe" + Push "" + Call un.tmAtomicMoveToBackup + Pop $R0 + ${if} $R0 != 0 + DetailPrint "File is busy, aborting: $R0" + Push "" + Call un.tmRestoreFromBackup + Pop $R0 + RMDir /r "$tmOldBackupRoot" + Abort `Can't rename "$INSTDIR" to "$tmOldBackupRoot".` + ${endIf} + RMDir /r "$tmOldBackupRoot" + ${else} + ; 父目录不可写时检测主程序是否被锁,未锁再清理安装目录。 + ${if} ${FileExists} "$INSTDIR\${APP_EXECUTABLE_FILENAME}" + ClearErrors + Rename "$INSTDIR\${APP_EXECUTABLE_FILENAME}" "$INSTDIR\${APP_EXECUTABLE_FILENAME}.tm_bak" + ${if} ${Errors} + Abort `File is busy: "$INSTDIR\${APP_EXECUTABLE_FILENAME}".` + ${endIf} + Rename "$INSTDIR\${APP_EXECUTABLE_FILENAME}.tm_bak" "$INSTDIR\${APP_EXECUTABLE_FILENAME}" + ${endIf} + ${endIf} + ${endIf} + ${endIf} + + RMDir /r $INSTDIR + !macroend +!endif diff --git a/electron-builder.win.yml b/electron-builder.win.yml index 510d4cd..88b703f 100644 --- a/electron-builder.win.yml +++ b/electron-builder.win.yml @@ -63,6 +63,7 @@ win: nsis: oneClick: false allowToChangeInstallationDirectory: true + include: build/installer.nsh artifactName: ${name}-${version}-setup.${ext} shortcutName: ${productName} uninstallDisplayName: ${productName} diff --git a/electron-builder.yml b/electron-builder.yml index 13481fc..3cc3204 100644 --- a/electron-builder.yml +++ b/electron-builder.yml @@ -49,6 +49,7 @@ extraResources: nsis: oneClick: false allowToChangeInstallationDirectory: true + include: build/installer.nsh artifactName: ${name}-${version}-setup.${ext} shortcutName: ${productName} uninstallDisplayName: ${productName} diff --git a/src/main/extensions/extension-host.ts b/src/main/extensions/extension-host.ts index 973211d..b5bb108 100644 --- a/src/main/extensions/extension-host.ts +++ b/src/main/extensions/extension-host.ts @@ -1,5 +1,8 @@ -import { fork, spawn, type ChildProcess } from 'node:child_process' +import { fork, type ChildProcess } from 'node:child_process' import { randomUUID } from 'node:crypto' +import { existsSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { killProcessTree, type ProcessTreeKillResult } from '../process-tree' import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors' import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types' import { @@ -347,9 +350,14 @@ export class ExtensionHost { const result = await killProcessTree(pid, { timeoutMs: this.dependencies.forceExitMs ?? TASKKILL_TIMEOUT_MS }) - if (result === 'group') return + if (result === 'group' || result === 'taskkill') return + try { + child.kill() + } catch { + // 进程已退出。 + } if (process.platform === 'win32') { - this.dependencies.onLog?.('warn', '结束扩展进程树失败,可能有子进程仍在运行') + this.dependencies.onLog?.('warn', '结束扩展进程树失败,已退化为直接结束扩展进程') return } this.dependencies.onLog?.('warn', '未能结束扩展进程组,已退化为只结束主进程') @@ -881,80 +889,17 @@ export class ExtensionHost { } } -/** 结束进程树;taskkill 只在 exit 0 时算成功,发起成功不算。 */ -export type ProcessTreeKillResult = 'group' | 'taskkill' | 'fallback' - -export async function killProcessTree( - pid: number | undefined, - options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals; timeoutMs?: number } = {} -): Promise { - if (!pid) return 'fallback' - const platform = options.platform ?? process.platform - const signal = options.signal ?? 'SIGKILL' - - if (platform === 'win32') { - return killWindowsProcessTree(pid, options.timeoutMs ?? TASKKILL_TIMEOUT_MS) - } - - try { - process.kill(-pid, signal) - return 'group' - } catch { - try { - process.kill(pid, signal) - } catch { - // 进程已经退出。 - } - return 'fallback' - } -} - -/** Windows:等 taskkill 真实退出,只认 exit code 0。 */ -function killWindowsProcessTree( - pid: number, - timeoutMs: number -): Promise<'taskkill' | 'fallback'> { - return new Promise((resolve) => { - let killer: ChildProcess - try { - killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { - windowsHide: true, - stdio: 'ignore' - }) - } catch { - // 无法启动 taskkill(极少数受限环境):只能退化为「主进程可能已退出」。 - resolve('fallback') - return - } - - let settled = false - const finish = (result: 'taskkill' | 'fallback'): void => { - if (settled) return - settled = true - clearTimeout(timer) - resolve(result) - } - - const timer = setTimeout(() => { - try { - killer.kill() - } catch { - // 已经退出。 - } - finish('fallback') - }, timeoutMs) - - killer.on('error', () => finish('fallback')) - killer.on('exit', (code) => finish(code === 0 ? 'taskkill' : 'fallback')) - }) -} +export { killProcessTree, type ProcessTreeKillResult } /** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */ export function forkExtensionHost( scriptPath: string ): (options: ExtensionHostSpawnOptions) => ExtensionHostChild { return (options) => { + // 脱离应用安装目录作为 cwd,避免扩展及其孙进程在 Windows 更新时锁住安装目录。 + const cwd = existsSync(options.extensionDir) ? options.extensionDir : tmpdir() const child: ChildProcess = fork(scriptPath, [], { + cwd, stdio: ['ignore', 'ignore', 'pipe', 'ipc'], serialization: 'advanced', // POSIX 上建立独立进程组,停止时才能一次覆盖扩展派生的子进程。 diff --git a/src/main/extensions/extension-manager.ts b/src/main/extensions/extension-manager.ts index c4d4e25..fcf0357 100644 --- a/src/main/extensions/extension-manager.ts +++ b/src/main/extensions/extension-manager.ts @@ -136,6 +136,7 @@ export class ExtensionManager { private readonly eventBus: ExtensionEventBus private readonly now: () => number private initialized = false + private disposed = false /** 代码与 Registry 版本不一致的扩展:值为面向用户的原因,存在即禁止启动。 */ private readonly inconsistencies = new Map() /** 配置从旧备份恢复、尚未被用户确认的扩展。 */ @@ -1251,6 +1252,7 @@ export class ExtensionManager { } async dispose(): Promise { + this.disposed = true const ids = Array.from(this.hosts.keys()) await Promise.all(ids.map((id) => this.stopHost(id))) } @@ -1361,6 +1363,7 @@ export class ExtensionManager { } private async startHost(extensionId: string, manifest: ExtensionManifest): Promise { + if (this.disposed) return if (!manifest.entrypoints.background) return // 双保险:任何路径(含自动恢复、自动化触发)都不能绕过这两道闸。 const drift = this.inconsistencies.get(extensionId) diff --git a/src/main/http-server.ts b/src/main/http-server.ts index 884eb98..ca92e30 100644 --- a/src/main/http-server.ts +++ b/src/main/http-server.ts @@ -1494,7 +1494,18 @@ export function startHttpServer( port: actualPort, close: () => new Promise((res) => { - server.close(() => res()) + let settled = false + const finish = (): void => { + if (settled) return + settled = true + clearTimeout(timer) + res() + } + // HTTP keep-alive 或长连接会阻塞 server.close(),退出时主动断开全部连接。 + const timer = setTimeout(finish, 1_500) + server.close(() => finish()) + server.closeIdleConnections?.() + server.closeAllConnections?.() }) }) }) diff --git a/src/main/index.ts b/src/main/index.ts index 07072c7..a3c1360 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1529,6 +1529,9 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) { ipcMain.handle('app-update:getState', () => appUpdateService.getState()) ipcMain.handle('app-update:check', () => appUpdateService.check()) ipcMain.handle('app-update:download', () => appUpdateService.download()) + appUpdateService.setBeforeQuitAndInstall(() => + runQuitCleanup({ dbDrainTimeoutMs: 2_000, totalTimeoutMs: 4_000 }) + ) ipcMain.handle('app-update:install', () => appUpdateService.install()) ipcMain.handle('app-update:openDownloadPage', () => appUpdateService.openDownloadPage()) ipcMain.handle('app-update:getIgnoredVersion', () => loadSettings().skippedUpdateVersion) @@ -3800,30 +3803,49 @@ app.on('window-all-closed', () => { } }) -let quitCleanupStarted = false +let quitCleanupPromise: Promise | null = null let quitCleanupComplete = false -app.on('before-quit', (event) => { - if (quitCleanupComplete) return +function runQuitCleanup(options?: { + dbDrainTimeoutMs?: number + totalTimeoutMs?: number +}): Promise { + if (quitCleanupComplete) return Promise.resolve() + if (quitCleanupPromise) return quitCleanupPromise + isQuitting = true appShutdownRequested = true - event.preventDefault() - if (quitCleanupStarted) return - quitCleanupStarted = true voiceBatchService?.cancel() console.log('[Shutdown] cleanup started') - void (async () => { + const dbDrainTimeoutMs = options?.dbDrainTimeoutMs ?? 3_000 + const totalTimeoutMs = options?.totalTimeoutMs ?? 5_000 + + quitCleanupPromise = (async () => { agentHubService.stop() scheduledReportService.stop() groupExitMonitorService.stop() - await disposeExtensionSystem().catch(() => undefined) + if (tray) { + tray.destroy() + tray = null + } flushBootstrapCacheWritesSync() - const [, nativeCallsDrained] = await Promise.all([ + + let timedOut = false + let nativeCallsDrained = true + const cleanupAll = Promise.allSettled([ + disposeExtensionSystem().catch(() => undefined), apiServer.stop().catch(() => undefined), - chat.closeChatDbForQuit().catch(() => false), + chat.closeChatDbForQuit(dbDrainTimeoutMs).then( + (drained) => { + nativeCallsDrained = drained + }, + () => { + nativeCallsDrained = false + } + ), voiceRecognition?.dispose().catch(() => undefined), - knowledgeSearchService?.dispose().catch(() => undefined), + knowledgeSearchService?.dispose().catch(() => undefined) /* * Deliberately do NOT stop the macOS native runtime here. * @@ -3838,14 +3860,27 @@ app.on('before-quit', (event) => { * self-shutdown), and it can be restarted explicitly from the settings * card ("重新加载组件"). */ - Promise.resolve() ]) - if (!nativeCallsDrained) { - console.warn('[Shutdown] WCDB async calls did not fully drain before quit') + + let timer: ReturnType | null = null + try { + await Promise.race([ + cleanupAll, + new Promise((resolve) => { + timer = setTimeout(() => { + timedOut = true + resolve() + }, totalTimeoutMs) + }) + ]) + } finally { + if (timer) clearTimeout(timer) } - if (tray) { - tray.destroy() - tray = null + + if (timedOut) { + console.warn(`[Shutdown] cleanup timed out after ${totalTimeoutMs}ms`) + } else if (!nativeCallsDrained) { + console.warn('[Shutdown] WCDB async calls did not fully drain before quit') } console.log('[Shutdown] cleanup completed') })() @@ -3854,12 +3889,30 @@ app.on('before-quit', (event) => { }) .finally(() => { quitCleanupComplete = true - // The first quit request has already been cancelled so cleanup can finish safely. - // app.exit() avoids starting a second before-quit cycle that can leave Electron alive - // on macOS even after every application service has stopped. - console.log('[Shutdown] exiting application') - app.exit(0) }) + + return quitCleanupPromise +} + +app.on('before-quit', (event) => { + if (quitCleanupComplete) { + // 预清理已完成(例如自动更新前):放行本次退出,并在 Windows 兜底防句柄保活。 + if (process.platform === 'win32') { + setTimeout(() => app.exit(0), 500).unref() + } + return + } + isQuitting = true + appShutdownRequested = true + event.preventDefault() + + void runQuitCleanup().finally(() => { + // The first quit request has already been cancelled so cleanup can finish safely. + // app.exit() avoids starting a second before-quit cycle that can leave Electron alive + // on macOS even after every application service has stopped. + console.log('[Shutdown] exiting application') + app.exit(0) + }) }) function showMainWindow(): void { diff --git a/src/main/knowledge/knowledge-worker-host.ts b/src/main/knowledge/knowledge-worker-host.ts index 2e7b563..2eaace9 100644 --- a/src/main/knowledge/knowledge-worker-host.ts +++ b/src/main/knowledge/knowledge-worker-host.ts @@ -1,5 +1,7 @@ import { fork, type ChildProcess } from 'child_process' import { randomUUID } from 'crypto' +import { tmpdir } from 'os' +import { terminateChildProcess, waitForChildExit } from '../process-tree' import type { KnowledgeCapacityPreflight, KnowledgeCapacityPreflightRequest, @@ -163,16 +165,30 @@ export class KnowledgeWorkerHost { return this.request('cancel', { targetRequestId }) as Promise<{ removed: true }> } - async dispose(): Promise { + async dispose(options: { closeTimeoutMs?: number; exitTimeoutMs?: number } = {}): Promise { const child = this.child if (!child) return + const closeTimeoutMs = options.closeTimeoutMs ?? 1_500 + const exitTimeoutMs = options.exitTimeoutMs ?? 2_000 + // close 请求必须有超时,避免同步 SQLite 事务把应用退出永久挂死。 + const closePromise = this.request('close', {}).catch(() => undefined) + let timer: ReturnType | null = null try { - await this.request('close', {}) - } catch { - // The child is about to be stopped; its only job is a derived local index. + await Promise.race([ + closePromise, + new Promise((resolve) => { + timer = setTimeout(resolve, closeTimeoutMs) + }) + ]) + } finally { + if (timer) clearTimeout(timer) } if (this.child === child) this.child = null - if (!child.killed) child.kill() + const exited = await waitForChildExit(child, 300) + if (!exited) { + await terminateChildProcess(child, { timeoutMs: exitTimeoutMs }) + } + this.failAll(new Error('Knowledge worker disposed')) } private request( @@ -204,6 +220,7 @@ export class KnowledgeWorkerHost { private ensureChild(): ChildProcess { if (this.child?.connected) return this.child const child = fork(this.workerPath, [], { + cwd: tmpdir(), stdio: ['ignore', 'ignore', 'ignore', 'ipc'], serialization: 'advanced', env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' } diff --git a/src/main/process-tree.ts b/src/main/process-tree.ts new file mode 100644 index 0000000..07a6e9d --- /dev/null +++ b/src/main/process-tree.ts @@ -0,0 +1,143 @@ +import { spawn, type ChildProcess } from 'node:child_process' + +const DEFAULT_TASKKILL_TIMEOUT_MS = 5_000 +const DEFAULT_EXIT_TIMEOUT_MS = 2_000 + +/** 结束进程树的结果;Windows 上仅 taskkill 退出码为 0 时视为成功。 */ +export type ProcessTreeKillResult = 'group' | 'taskkill' | 'fallback' + +export interface TerminateChildProcessOptions { + platform?: NodeJS.Platform + signal?: NodeJS.Signals + timeoutMs?: number + killTree?: typeof killProcessTree +} + +export async function killProcessTree( + pid: number | undefined, + options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals; timeoutMs?: number } = {} +): Promise { + if (!pid) return 'fallback' + const platform = options.platform ?? process.platform + const signal = options.signal ?? 'SIGKILL' + + if (platform === 'win32') { + return killWindowsProcessTree(pid, options.timeoutMs ?? DEFAULT_TASKKILL_TIMEOUT_MS) + } + + try { + process.kill(-pid, signal) + return 'group' + } catch { + try { + process.kill(pid, signal) + } catch { + // 进程已退出。 + } + return 'fallback' + } +} + +function killWindowsProcessTree( + pid: number, + timeoutMs: number +): Promise<'taskkill' | 'fallback'> { + return new Promise((resolve) => { + let killer: ChildProcess + try { + killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { + windowsHide: true, + stdio: 'ignore' + }) + } catch { + resolve('fallback') + return + } + + let settled = false + const finish = (result: 'taskkill' | 'fallback'): void => { + if (settled) return + settled = true + clearTimeout(timer) + resolve(result) + } + + const timer = setTimeout(() => { + try { + killer.kill() + } catch { + // 进程已退出。 + } + finish('fallback') + }, timeoutMs) + + killer.on('error', () => finish('fallback')) + killer.on('exit', (code) => finish(code === 0 ? 'taskkill' : 'fallback')) + }) +} + +export interface ExitObservableChild { + exitCode: number | null + signalCode: NodeJS.Signals | null + once(event: 'exit', listener: (...args: unknown[]) => void): unknown + removeListener(event: 'exit', listener: (...args: unknown[]) => void): unknown +} + +export interface TerminatableChild extends ExitObservableChild { + pid?: number + killed: boolean + kill(signal?: NodeJS.Signals | number): boolean +} + +/** 等待子进程真实退出;仅发信号不等待会在 Windows 更新时残留文件锁与同名进程。 */ +export function waitForChildExit( + child: ExitObservableChild, + timeoutMs = DEFAULT_EXIT_TIMEOUT_MS +): Promise { + if (child.exitCode !== null || child.signalCode !== null) { + return Promise.resolve(true) + } + return new Promise((resolve) => { + let settled = false + const onExit = (): void => finish(true) + const finish = (exited: boolean): void => { + if (settled) return + settled = true + clearTimeout(timer) + child.removeListener('exit', onExit) + resolve(exited) + } + const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs)) + child.once('exit', onExit) + }) +} + +export async function terminateChildProcess( + child: TerminatableChild, + options: TerminateChildProcessOptions = {} +): Promise { + if (child.exitCode !== null || child.signalCode !== null) return true + + const timeoutMs = options.timeoutMs ?? DEFAULT_EXIT_TIMEOUT_MS + const exitPromise = waitForChildExit(child, timeoutMs) + const runKillTree = options.killTree ?? killProcessTree + + let result: ProcessTreeKillResult = 'fallback' + if (child.pid) { + result = await runKillTree(child.pid, { + platform: options.platform, + signal: options.signal, + timeoutMs + }) + } + + if (result === 'fallback' && !child.killed) { + try { + child.kill(options.signal ?? 'SIGKILL') + } catch { + // 进程已退出。 + } + } + + return exitPromise +} diff --git a/src/main/services/app-update-service.ts b/src/main/services/app-update-service.ts index 388bb84..d994baa 100644 --- a/src/main/services/app-update-service.ts +++ b/src/main/services/app-update-service.ts @@ -27,6 +27,7 @@ interface AppUpdateServiceOptions { platform?: NodeJS.Platform macAutoUpdateEnabled?: boolean broadcast?: (state: AppUpdateState) => void + beforeQuitAndInstall?: () => Promise | void } export class AppUpdateService { @@ -36,6 +37,7 @@ export class AppUpdateService { private readonly simulationDurationMs: number private readonly delivery: AppUpdateDelivery private readonly broadcast?: (state: AppUpdateState) => void + private beforeQuitAndInstall?: () => Promise | void private state: AppUpdateState private listeners = new Set<(state: AppUpdateState) => void>() private activeCheckSource: AppUpdateCheckSource = 'manual' @@ -62,6 +64,7 @@ export class AppUpdateService { ? 'release-page' : 'automatic' this.broadcast = options.broadcast + this.beforeQuitAndInstall = options.beforeQuitAndInstall this.state = { status: 'idle', currentVersion: this.currentVersion(), @@ -238,6 +241,10 @@ export class AppUpdateService { } } + setBeforeQuitAndInstall(hook?: () => Promise | void): void { + this.beforeQuitAndInstall = hook + } + install(): AppUpdateInstallResult { if (this.delivery !== 'automatic') { return { success: false, error: '当前 macOS 版本不支持自动安装,请前往 GitHub 下载更新。' } @@ -251,6 +258,17 @@ export class AppUpdateService { return { success: true, simulated: true, message } } this.setState({ status: 'installing', message: '正在重启并安装更新' }) + const beforeHook = this.beforeQuitAndInstall + if (beforeHook) { + // 先释放子进程与文件句柄再拉起安装器,避免 NSIS 检测到残留同名进程或目录锁。 + void Promise.resolve() + .then(() => beforeHook()) + .catch(() => undefined) + .finally(() => { + autoUpdater.quitAndInstall() + }) + return { success: true } + } autoUpdater.quitAndInstall() return { success: true } } diff --git a/src/main/services/chat-service.ts b/src/main/services/chat-service.ts index 3073230..fe16983 100644 --- a/src/main/services/chat-service.ts +++ b/src/main/services/chat-service.ts @@ -266,12 +266,12 @@ export function getImageMessageReference(messageId: string): ImageMessageReferen return imageMessageReferences.get(normalizedId) || null } -export async function closeChatDbForQuit(): Promise { +export async function closeChatDbForQuit(timeoutMs?: number): Promise { shutdownRequested = true const current = dbRef dbRef = null if (!current) return true - return current.closeAsync() + return current.closeAsync(timeoutMs) } export function getChatDb(): WechatDb | null { diff --git a/src/main/voice-pipeline/recognition-host.ts b/src/main/voice-pipeline/recognition-host.ts index 962d03c..aca536e 100644 --- a/src/main/voice-pipeline/recognition-host.ts +++ b/src/main/voice-pipeline/recognition-host.ts @@ -1,5 +1,7 @@ import { fork, type ChildProcess } from 'child_process' import { randomUUID } from 'crypto' +import { tmpdir } from 'os' +import { terminateChildProcess } from '../process-tree' import type { PipelineAudio, RecognitionMetadata, @@ -73,8 +75,16 @@ export class RecognitionHost { }) } - async dispose(): Promise { - this.terminate(new Error('Voice recognition host disposed')) + async dispose(exitTimeoutMs = 2_000): Promise { + if (this.idleTimer) { + clearTimeout(this.idleTimer) + this.idleTimer = null + } + const child = this.child + this.child = null + this.rejectAll(new Error('Voice recognition host disposed')) + if (!child) return + await terminateChildProcess(child, { timeoutMs: exitTimeoutMs }) } private ensureChild(): ChildProcess { @@ -84,6 +94,7 @@ export class RecognitionHost { } if (this.child?.connected) return this.child const child = fork(this.workerPath, [], { + cwd: tmpdir(), stdio: ['ignore', 'ignore', 'ignore', 'ipc'], serialization: 'advanced', env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' } diff --git a/tests/unit/app-update-service.test.ts b/tests/unit/app-update-service.test.ts index fafaa1e..0cccf5d 100644 --- a/tests/unit/app-update-service.test.ts +++ b/tests/unit/app-update-service.test.ts @@ -179,4 +179,53 @@ describe('AppUpdateService', () => { expect(service.install()).toEqual({ success: true }) expect(mocks.updater.quitAndInstall).toHaveBeenCalledOnce() }) + + it('waits for beforeQuitAndInstall cleanup before invoking quitAndInstall', async () => { + let releaseCleanup!: () => void + const cleanupPromise = new Promise((resolve) => { + releaseCleanup = resolve + }) + const beforeQuitAndInstall = vi.fn(() => cleanupPromise) + const service = new AppUpdateService({ + platform: 'win32', + packagedRuntime: () => true, + currentVersion: () => '2.7.0', + beforeQuitAndInstall + }) + mocks.updater.downloadUpdate.mockImplementationOnce(async () => { + mocks.emit('update-downloaded', { version: '2.7.1' }) + }) + + await service.download() + expect(service.install()).toEqual({ success: true }) + await Promise.resolve() + + expect(beforeQuitAndInstall).toHaveBeenCalledOnce() + expect(mocks.updater.quitAndInstall).not.toHaveBeenCalled() + expect(service.getState().status).toBe('installing') + + releaseCleanup() + await cleanupPromise + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(mocks.updater.quitAndInstall).toHaveBeenCalledOnce() + }) + + it('still invokes quitAndInstall when beforeQuitAndInstall rejects', async () => { + const service = new AppUpdateService({ + platform: 'win32', + packagedRuntime: () => true, + currentVersion: () => '2.7.0', + beforeQuitAndInstall: async () => { + throw new Error('cleanup failed') + } + }) + mocks.updater.downloadUpdate.mockImplementationOnce(async () => { + mocks.emit('update-downloaded', { version: '2.7.1' }) + }) + + await service.download() + expect(service.install()).toEqual({ success: true }) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(mocks.updater.quitAndInstall).toHaveBeenCalledOnce() + }) }) diff --git a/tests/unit/process-tree.test.ts b/tests/unit/process-tree.test.ts new file mode 100644 index 0000000..bab3327 --- /dev/null +++ b/tests/unit/process-tree.test.ts @@ -0,0 +1,70 @@ +import { EventEmitter } from 'node:events' +import { describe, expect, it, vi } from 'vitest' +import { terminateChildProcess, waitForChildExit } from '../../src/main/process-tree' + +class FakeChildProcess extends EventEmitter { + pid: number | undefined = 4242 + killed = false + exitCode: number | null = null + signalCode: NodeJS.Signals | null = null + kill = vi.fn((signal?: NodeJS.Signals | number) => { + this.killed = true + this.signalCode = typeof signal === 'string' ? signal : 'SIGTERM' + queueMicrotask(() => this.emit('exit', null, this.signalCode)) + return true + }) +} + +describe('process-tree', () => { + it('waitForChildExit resolves immediately for already exited process', async () => { + const child = new FakeChildProcess() + child.exitCode = 0 + await expect(waitForChildExit(child, 50)).resolves.toBe(true) + }) + + it('waitForChildExit waits for exit event and returns false on timeout', async () => { + const child = new FakeChildProcess() + const pending = waitForChildExit(child, 300) + setTimeout(() => { + child.exitCode = 0 + child.emit('exit', 0, null) + }, 10) + await expect(pending).resolves.toBe(true) + + const hanging = new FakeChildProcess() + await expect(waitForChildExit(hanging, 30)).resolves.toBe(false) + }) + + it('terminateChildProcess falls back to child.kill when killTree returns fallback', async () => { + const child = new FakeChildProcess() + const killTree = vi.fn(async () => 'fallback' as const) + + const exited = await terminateChildProcess(child, { + timeoutMs: 300, + killTree + }) + + expect(exited).toBe(true) + expect(killTree).toHaveBeenCalledOnce() + expect(child.kill).toHaveBeenCalledOnce() + }) + + it('terminateChildProcess waits for exit after killTree succeeds', async () => { + const child = new FakeChildProcess() + const killTree = vi.fn(async () => { + setTimeout(() => { + child.exitCode = 0 + child.emit('exit', 0, null) + }, 15) + return 'taskkill' as const + }) + + const exited = await terminateChildProcess(child, { + timeoutMs: 300, + killTree + }) + + expect(exited).toBe(true) + expect(child.kill).not.toHaveBeenCalled() + }) +}) diff --git a/tests/unit/windows-nsis-installer.test.ts b/tests/unit/windows-nsis-installer.test.ts new file mode 100644 index 0000000..84a55ba --- /dev/null +++ b/tests/unit/windows-nsis-installer.test.ts @@ -0,0 +1,30 @@ +import { existsSync, readFileSync } from 'node:fs' +import path from 'node:path' +import { describe, expect, it } from 'vitest' + +const ROOT = path.resolve(__dirname, '../..') + +describe('Windows NSIS installer configuration', () => { + it('wires build/installer.nsh in electron-builder configs', () => { + const winConfig = readFileSync(path.join(ROOT, 'electron-builder.win.yml'), 'utf8') + const baseConfig = readFileSync(path.join(ROOT, 'electron-builder.yml'), 'utf8') + + expect(winConfig).toContain('include: build/installer.nsh') + expect(baseConfig).toContain('include: build/installer.nsh') + expect(existsSync(path.join(ROOT, 'build', 'installer.nsh'))).toBe(true) + }) + + it('kills process trees and handles cross-drive updates in build/installer.nsh', () => { + const script = readFileSync(path.join(ROOT, 'build', 'installer.nsh'), 'utf8') + + expect(script).toContain('!macro customCheckAppRunning') + expect(script).toContain('taskkill /f /t /im') + expect(script).toContain('find.exe" /I') + expect(script).toContain('Function tmPrepareCrossDriveUpdateTemp') + expect(script).toContain('Function tmRestoreCrossDriveUpdateTemp') + expect(script).toContain('!macro customInstall') + expect(script).toContain('!macro customRemoveFiles') + expect(script).toContain('un.tmAtomicMoveToBackup') + expect(script).toContain('un.tmRestoreFromBackup') + }) +})