fix: 修复 Windows 自动更新提示无法关闭与退出残留

This commit is contained in:
Wxw-Gu committed 2026-11-20 14:21:58 +08:00
1 parent b86582e606
commit c0b921c109
15 files changed
+801 -102

No files matched your search

+15 -70
View File
@@ -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<ProcessTreeKillResult> {
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 上建立独立进程组,停止时才能一次覆盖扩展派生的子进程。
+3
View File
@@ -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<string, string>()
/** 配置从旧备份恢复、尚未被用户确认的扩展。 */
@@ -1251,6 +1252,7 @@ export class ExtensionManager {
}
async dispose(): Promise<void> {
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<void> {
if (this.disposed) return
if (!manifest.entrypoints.background) return
// 双保险:任何路径(含自动恢复、自动化触发)都不能绕过这两道闸。
const drift = this.inconsistencies.get(extensionId)
+12 -1
View File
@@ -1494,7 +1494,18 @@ export function startHttpServer(
port: actualPort,
close: () =>
new Promise<void>((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?.()
})
})
})
+75 -22
View File
@@ -1513,6 +1513,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)
@@ -3749,30 +3752,49 @@ app.on('window-all-closed', () => {
}
})
let quitCleanupStarted = false
let quitCleanupPromise: Promise<void> | null = null
let quitCleanupComplete = false
app.on('before-quit', (event) => {
if (quitCleanupComplete) return
function runQuitCleanup(options?: {
dbDrainTimeoutMs?: number
totalTimeoutMs?: number
}): Promise<void> {
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.
*
@@ -3787,14 +3809,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<typeof setTimeout> | null = null
try {
await Promise.race([
cleanupAll,
new Promise<void>((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')
})()
@@ -3803,12 +3838,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 {
+22 -5
View File
@@ -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,
@@ -100,16 +102,30 @@ export class KnowledgeWorkerHost {
return this.request('cancel', { targetRequestId }) as Promise<{ removed: true }>
}
async dispose(): Promise<void> {
async dispose(options: { closeTimeoutMs?: number; exitTimeoutMs?: number } = {}): Promise<void> {
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<typeof setTimeout> | 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<void>((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(
@@ -141,6 +157,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' }
+143
View File
@@ -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<ProcessTreeKillResult> {
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<boolean> {
if (child.exitCode !== null || child.signalCode !== null) {
return Promise.resolve(true)
}
return new Promise<boolean>((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<boolean> {
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
}
+18
View File
@@ -27,6 +27,7 @@ interface AppUpdateServiceOptions {
platform?: NodeJS.Platform
macAutoUpdateEnabled?: boolean
broadcast?: (state: AppUpdateState) => void
beforeQuitAndInstall?: () => Promise<void> | 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> | 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): 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 }
}
+2 -2
View File
@@ -266,12 +266,12 @@ export function getImageMessageReference(messageId: string): ImageMessageReferen
return imageMessageReferences.get(normalizedId) || null
}
export async function closeChatDbForQuit(): Promise<boolean> {
export async function closeChatDbForQuit(timeoutMs?: number): Promise<boolean> {
shutdownRequested = true
const current = dbRef
dbRef = null
if (!current) return true
return current.closeAsync()
return current.closeAsync(timeoutMs)
}
export function getChatDb(): WechatDb | null {
+13 -2
View File
@@ -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<void> {
this.terminate(new Error('Voice recognition host disposed'))
async dispose(exitTimeoutMs = 2_000): Promise<void> {
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' }