feat: 拓展中心机器人模板

This commit is contained in:
Wxw-Gu committed 2026-11-18 17:42:18 +08:00
1 parent 4d86aa8d31
commit 0ec8029f17
10 files changed
+320 -181

No files matched your search

+59 -20
View File
@@ -43,6 +43,8 @@ const EVENT_REFILL_PER_SECOND = 60
const GRACEFUL_EXIT_MS = 2_500
/** 结束进程树之后等待 exit 事件的时间。 */
const FORCE_EXIT_MS = 3_000
/** taskkill 的等待上限:卡住时按降级处理,不能拖死停用流程。 */
const TASKKILL_TIMEOUT_MS = 5_000
/** stderr 采样窗口:只把有代表性的片段写进日志,避免日志洪水拖住主进程。 */
const STDERR_WINDOW_MS = 10_000
@@ -324,7 +326,7 @@ export class ExtensionHost {
}
this.dependencies.onLog?.('warn', '扩展未在预期时间内退出,正在结束进程树')
this.killTree(child)
await this.killTree(child)
if (!(await this.waitForExit(child, this.dependencies.forceExitMs ?? FORCE_EXIT_MS))) {
this.dependencies.onLog?.('error', '扩展进程树未能退出,可能有子进程仍在运行')
}
@@ -332,7 +334,7 @@ export class ExtensionHost {
}
/** 结束进程树;Windows 的 taskkill /T 必须在父进程存活时执行,否则找不到孙进程。 */
private killTree(child: ExtensionHostChild): void {
private async killTree(child: ExtensionHostChild): Promise<void> {
const pid = child.pid
if (!pid) {
try {
@@ -342,10 +344,15 @@ export class ExtensionHost {
}
return
}
const result = killProcessTree(pid)
if (result !== 'group' && process.platform !== 'win32') {
this.dependencies.onLog?.('warn', '未能结束扩展进程组,已退化为只结束主进程')
const result = await killProcessTree(pid, {
timeoutMs: this.dependencies.forceExitMs ?? TASKKILL_TIMEOUT_MS
})
if (result === 'group') return
if (process.platform === 'win32') {
this.dependencies.onLog?.('warn', '结束扩展进程树失败,可能有子进程仍在运行')
return
}
this.dependencies.onLog?.('warn', '未能结束扩展进程组,已退化为只结束主进程')
}
private waitForExit(child: ExtensionHostChild, timeoutMs: number): Promise<boolean> {
@@ -874,27 +881,19 @@ export class ExtensionHost {
}
}
/** 结束 `pid` 对应的进程树;`taskkill`:Windows 进程树,必须在父进程仍存活时调用。 */
export function killProcessTree(
/** 结束进程树;taskkill 只在 exit 0 时算成功,发起成功不算。 */
export type ProcessTreeKillResult = 'group' | 'taskkill' | 'fallback'
export async function killProcessTree(
pid: number | undefined,
options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals } = {}
): 'group' | 'taskkill' | 'fallback' {
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') {
try {
const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], {
windowsHide: true,
stdio: 'ignore'
})
killer.on('error', () => undefined)
killer.unref?.()
return 'taskkill'
} catch {
return 'fallback'
}
return killWindowsProcessTree(pid, options.timeoutMs ?? TASKKILL_TIMEOUT_MS)
}
try {
@@ -910,6 +909,46 @@ export function killProcessTree(
}
}
/** 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'))
})
}
/** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */
export function forkExtensionHost(
scriptPath: string
@@ -705,6 +705,9 @@ function logSendDiagnostic(
console.log(`[SendDiag] ${stage} ${JSON.stringify(detail)}`)
}
/** 能力轮询会反复打这些端点,成功时不计入发送诊断,否则日志被探测刷满。 */
const WINDOWS_PROBE_ENDPOINTS = new Set(['/getLoginInfo'])
/** 发送完成后**保留**图片临时文件的时长(毫秒)。默认 `0` = 立刻删除(现行行为)。 */
const WINDOWS_TEMP_IMAGE_GRACE_MS = 0
@@ -740,12 +743,15 @@ async function requestWindowsHook(
headers: { 'Content-Type': 'application/json' }
}
if (method !== 'GET') init.body = JSON.stringify(body)
logSendDiagnostic('hook-request', {
endpoint,
method,
// 只报 payload 里有没有内容,不报内容本身。
hasPayload: method !== 'GET' ? init.body !== undefined : false
})
const isProbe = WINDOWS_PROBE_ENDPOINTS.has(endpoint)
if (!isProbe) {
logSendDiagnostic('hook-request', {
endpoint,
method,
// 只报 payload 里有没有内容,不报内容本身。
hasPayload: method !== 'GET' ? init.body !== undefined : false
})
}
const response = await requestWithTimeout(`http://${host}${endpoint}`, init, timeoutMs)
const responseText = await response.text()
if (!response.ok) {
@@ -760,14 +766,16 @@ async function requestWindowsHook(
throw new WindowsHookHttpError(response.status, responseText)
}
const parsed = parseWindowsHookResponse(responseText, method === 'POST')
logSendDiagnostic('hook-response', {
endpoint,
httpStatus: response.status,
ok: true,
ret: typeof parsed.ret === 'number' ? parsed.ret : null,
retMessageLength: String(parsed.retmsg ?? parsed.msg ?? '').length,
elapsedMs: Date.now() - startedAt
})
if (!isProbe) {
logSendDiagnostic('hook-response', {
endpoint,
httpStatus: response.status,
ok: true,
ret: typeof parsed.ret === 'number' ? parsed.ret : null,
retMessageLength: String(parsed.retmsg ?? parsed.msg ?? '').length,
elapsedMs: Date.now() - startedAt
})
}
return parsed
}
@@ -105,6 +105,9 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
}
}
/** 发送能力探活间隔:轮询只为点亮导航红点,低频足够。 */
const SEND_CAPABILITY_POLL_MS = 30 * 60 * 1000
export function PrimaryNavigation({
activePage,
onPageChange
@@ -125,10 +128,16 @@ export function PrimaryNavigation({
.catch(() => undefined)
}
checkSendCapability()
const timer = window.setInterval(checkSendCapability, 8_000)
const timer = window.setInterval(checkSendCapability, SEND_CAPABILITY_POLL_MS)
// 半小时才轮一次,红点会过期;窗口重新可见时补查一次,成本可忽略。
const onVisibilityChange = (): void => {
if (!document.hidden) checkSendCapability()
}
document.addEventListener('visibilitychange', onVisibilityChange)
return () => {
disposed = true
window.clearInterval(timer)
document.removeEventListener('visibilitychange', onVisibilityChange)
}
}, [activePage])