Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 退出 watchdog 弃用隐藏 PowerShell,改为 wscript 单进程脚本 (#1699)

Lizif794f87ead32
diff --git a/apps/desktop/src/main/__tests__/lifecycle.test.ts b/apps/desktop/src/main/__tests__/lifecycle.test.ts
index e7c86b0f32..d289a37ddf 100644
--- a/apps/desktop/src/main/__tests__/lifecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/lifecycle.test.ts
@@ -9,6 +9,10 @@
* installQuitHandler 只覆盖不触发真实退出的异常分支;真实 process / app 信号路径仍走集成验证。
*/
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// lifecycle.ts 里 import { app } from 'electron' —— 用最小 stub 喂给它。
@@ -55,11 +59,26 @@ vi.mock('../logger', async () => {
};
});
+// 每个用例独立的 watchdog 脚本落盘目录 (mkdtemp 唯一路径, 用完即删)。既满足
+// 测试资源规则, 也让 win32 宿主上 installQuitHandler 的启动期预生成不会写入
+// 真实 os.tmpdir (freshLifecycle 里用本目录预 seed 缓存)。
+let watchdogTmpDir: string;
+beforeEach(() => {
+ watchdogTmpDir = mkdtempSync(join(tmpdir(), 'lifecycle-wd-'));
+});
+afterEach(() => {
+ rmSync(watchdogTmpDir, { recursive: true, force: true });
+});
+
// 因为 registry 是 module-level state, 每个用例需要 reset。简单做法: 用
// vi.resetModules + 动态 import, 拿一份全新的 module 实例。
async function freshLifecycle() {
vi.resetModules();
- return import('../lifecycle');
+ const lifecycle = await import('../lifecycle');
+ // win32 宿主上把 watchdog 脚本缓存 seed 到本用例的 mkdtemp 目录; 非 win32
+ // 宿主上是 no-op (需要 win32 路径的用例自己显式传 platform + tmpDir)。
+ lifecycle.prepareShutdownWatchdogScript({ tmpDir: watchdogTmpDir });
+ return lifecycle;
}
type ProcessEventName =
@@ -244,16 +263,18 @@ describe('armShutdownHardKillWatchdog', () => {
);
});
- it('win32: PowerShell 捕获 StartTime → Start-Sleep → StartTime+Path 双校验后 Stop-Process — windowsHide + unref', async () => {
- const { armShutdownHardKillWatchdog, SHUTDOWN_HARD_KILL_GRACE_SECONDS } =
+ it('win32: wscript 单进程 watchdog — CreationDate+ExecutablePath 双校验, 无 PowerShell、无子进程', async () => {
+ const { armShutdownHardKillWatchdog, prepareShutdownWatchdogScript, SHUTDOWN_HARD_KILL_GRACE_SECONDS } =
await freshLifecycle();
const { spawn, child } = fakeSpawn();
+ const scriptPath = prepareShutdownWatchdogScript({ platform: 'win32', tmpDir: watchdogTmpDir })!;
armShutdownHardKillWatchdog({
spawn,
pid: 67890,
platform: 'win32',
execPath: 'C:\\Cindy\\Cindy.exe',
+ tmpDir: watchdogTmpDir,
});
expect(spawn).toHaveBeenCalledTimes(1);
@@ -262,34 +283,95 @@ describe('armShutdownHardKillWatchdog', () => {
string[],
Record<string, unknown>,
];
- // cmd/tasklist 只能比映像名, 区分不了两次运行;换 Windows PowerShell 5.1
- // (SystemRoot 绝对路径, 不依赖 PATH) 以进程创建时间为身份锚点。
+ // wscript 是 GUI 子系统程序: 天生无控制台、无窗口, detached 逃出 libuv 的
+ // kill-on-close job 才能活过父进程。SystemRoot 绝对路径, 不依赖 PATH。
expect(cmd).toBe(
- `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,
+ `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\wscript.exe`,
);
- expect(args.slice(0, 5)).toEqual([
- '-NoProfile',
- '-NonInteractive',
- '-WindowStyle',
- 'Hidden',
- '-Command',
+ // 路径在 mkdtemp 唯一目录下, 不可被同 tmpdir 下其他进程预测或篡改。
+ expect(scriptPath).toMatch(/cindy-wd-/);
+ expect(scriptPath).toMatch(/watchdog\.js$/);
+ expect(args).toEqual([
+ '//B',
+ '//E:JScript',
+ scriptPath,
+ '67890',
+ String(SHUTDOWN_HARD_KILL_GRACE_SECONDS * 1000),
+ 'C:\\Cindy\\Cindy.exe',
]);
- const script = args[5];
- // 布防时捕获创建时间;取不到 (进程已死) 则直接退出, 失败方向永远是"少杀"。
- expect(script).toContain(
- '$started = Get-Process -Id 67890 | Select-Object -ExpandProperty StartTime; if (-not $started) { exit }; ',
- );
- expect(script).toContain(`Start-Sleep -Seconds ${SHUTDOWN_HARD_KILL_GRACE_SECONDS}; `);
- // 补刀前 StartTime + Path 双校验;属性读取走 Select-Object -ExpandProperty
- // 兼容 Constrained Language Mode。
- expect(script).toContain(
- '$p = Get-Process -Id 67890; '
- + 'if ($p -and ($p | Select-Object -ExpandProperty StartTime) -eq $started '
- + "-and ($p | Select-Object -ExpandProperty Path) -eq 'C:\\Cindy\\Cindy.exe') "
- + '{ Stop-Process -Id 67890 -Force }',
- );
expect(opts).toEqual({ detached: true, windowsHide: true, stdio: 'ignore' });
expect(child.unref).toHaveBeenCalledTimes(1);
+
+ // 脚本已预生成落盘, 且保留原 PowerShell 实现同强度的身份校验 (review P1
+ // 两轮的 PID 复用防线): 布防时捕获 CreationDate, 杀前重取比对 + execPath。
+ expect(existsSync(scriptPath)).toBe(true);
+ const content = readFileSync(scriptPath, 'utf8');
+ expect(content).toContain('CreationDate');
+ expect(content).toContain('ExecutablePath');
+ expect(content).toContain('WScript.Sleep(graceMs)');
+ expect(content).toContain('.Terminate()');
+ // 回归锁 (2026-08 实证): 隐藏拉起 PowerShell 会被 360 等安全软件当高危动作
+ // 拦截, 每次正常退出都弹风控 —— 这条路径永远不许再出现 powershell。
+ expect(content.toLowerCase()).not.toContain('powershell');
+ // WSH 按系统 ANSI 代码页读文件 + JScript 只有 ES3: 必须纯 ASCII, 且不能有
+ // const/let/箭头函数 (踩坑实证: 尾逗号/新语法在 //B 下静默失败, 兜底形同虚设)。
+ expect(content).toMatch(/^[\x00-\x7f]*$/);
+ expect(content).not.toMatch(/\b(const|let)\b|=>/);
+ });
+
+ it('prepareShutdownWatchdogScript: 非 win32 no-op; win32 幂等复用同一路径 (mkdtemp 唯一目录)', async () => {
+ const { prepareShutdownWatchdogScript } = await freshLifecycle();
+
+ expect(
+ prepareShutdownWatchdogScript({ platform: 'darwin', tmpDir: watchdogTmpDir }),
+ ).toBeNull();
+
+ const first = prepareShutdownWatchdogScript({ platform: 'win32', tmpDir: watchdogTmpDir });
+ expect(first).not.toBeNull();
+ expect(first!).toMatch(/cindy-wd-/);
+ expect(first!).toMatch(/watchdog\.js$/);
+ expect(existsSync(first!)).toBe(true);
+ // 幂等: 第二次 (即使传别的目录) 复用已生成的路径, 不重复写盘
+ expect(
+ prepareShutdownWatchdogScript({ platform: 'win32', tmpDir: join(watchdogTmpDir, 'other') }),
+ ).toBe(first);
+ });
+
+ it('win32: 缓存路径被外部删除后重新生成到新目录', async () => {
+ const { prepareShutdownWatchdogScript } = await freshLifecycle();
+ const first = prepareShutdownWatchdogScript({ platform: 'win32', tmpDir: watchdogTmpDir })!;
+ expect(existsSync(first)).toBe(true);
+ rmSync(first);
+ const second = prepareShutdownWatchdogScript({ platform: 'win32', tmpDir: watchdogTmpDir })!;
+ expect(second).not.toBe(first);
+ expect(existsSync(second)).toBe(true);
+ expect(second).toMatch(/watchdog\.js$/);
+ });
+
+ it('win32: watchdog 脚本写盘失败 → 共享 spawn 失败预算, 耗尽打缺席标记, 不 throw', async () => {
+ // 不走 freshLifecycle: 那里会预 seed 脚本缓存, 而本用例要的就是"prepare
+ // 一直失败"(目标目录不存在) 的路径。
+ vi.resetModules();
+ const { armShutdownHardKillWatchdog } = await import('../lifecycle');
+ const child = { once: vi.fn(), unref: vi.fn() };
+ const spawn = vi.fn(() => child);
+
+ expect(() =>
+ armShutdownHardKillWatchdog({
+ spawn,
+ pid: 1,
+ platform: 'win32',
+ execPath: 'C:\\Cindy\\Cindy.exe',
+ tmpDir: join(watchdogTmpDir, 'missing', 'deep'),
+ }),
+ ).not.toThrow();
+
+ // 写盘失败发生在 spawn 之前: spawn 从未被调用, 预算耗尽后打缺席标记
+ expect(spawn).not.toHaveBeenCalled();
+ expect(mocks.logger.error).toHaveBeenCalledWith(
+ expect.stringContaining('external kill backstop ABSENT'),
+ expect.any(Error),
+ );
});
it('is idempotent — a second arm does not spawn again', async () => {
diff --git a/apps/desktop/src/main/lifecycle.ts b/apps/desktop/src/main/lifecycle.ts
index e7b7d5708f..f0dbfbdc27 100644
--- a/apps/desktop/src/main/lifecycle.ts
+++ b/apps/desktop/src/main/lifecycle.ts
@@ -34,6 +34,9 @@
*/
import { spawn } from 'node:child_process';
+import { existsSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { app, BrowserWindow, session } from 'electron';
@@ -197,6 +200,91 @@ type WatchdogSpawn = (
once?(event: 'error', listener: (err: Error) => void): unknown;
};
+/**
+ * win32 watchdog 脚本 (WSH JScript) —— 单进程完成 sleep / 身份校验 / 补刀,
+ * 零子进程。为什么是 wscript 而不是 PowerShell / cmd, 见
+ * armShutdownHardKillWatchdog 内 win32 分支的注释。
+ *
+ * 约束 (均为实机踩坑实证):
+ * - 纯 ASCII: WSH 按系统 ANSI 代码页读文件, 非 ASCII 注释会乱码;
+ * - ES3 语法: JScript 没有 const/let/箭头函数, 函数调用**不允许尾逗号**
+ * (尾逗号是语法错, //B 模式下静默失败, watchdog 形同虚设);
+ * - pid / 宽限期 / execPath 全部走命令行参数, 内容与具体一次运行无关; 脚本
+ * 文件在启动期预生成到 mkdtemp 唯一目录。
+ */
+const WATCHDOG_SCRIPT_CONTENT = [
+ '// Cindy shutdown hard-kill watchdog (win32).',
+ '// Regenerated by Cindy at every app startup; safe to delete when Cindy is not running.',
+ '// Usage: wscript.exe //B //E:JScript <this file> <pid> <graceMs> <expectedExePath>',
+ '// Kills <pid> after <graceMs> ONLY if the process still exists with the same',
+ '// WMI CreationDate (captured while the arming process was provably alive) and',
+ '// the same executable path - a reused PID never matches both.',
+ 'var args = WScript.Arguments;',
+ 'var pid = parseInt(args(0), 10);',
+ 'var graceMs = parseInt(args(1), 10);',
+ "var expectPath = ('' + args(2)).toLowerCase();",
+ '',
+ 'function query() {',
+ ' try {',
+ " var wmi = GetObject('winmgmts:{impersonationLevel=impersonate}!\\\\\\\\.\\\\root\\\\cimv2');",
+ " var sql = 'SELECT ProcessId, ExecutablePath, CreationDate FROM Win32_Process WHERE ProcessId=' + pid;",
+ ' var rows = new Enumerator(wmi.ExecQuery(sql));',
+ ' return rows.atEnd() ? null : rows.item();',
+ ' } catch (e) {',
+ " return null; // WMI unavailable -> never kill (fail toward 'no kill')",
+ ' }',
+ '}',
+ '',
+ 'var before = query();',
+ 'if (before !== null) {',
+ " var started = '' + before.CreationDate;",
+ ' WScript.Sleep(graceMs);',
+ ' var after = query();',
+ " if (after !== null && ('' + after.CreationDate) === started && ('' + after.ExecutablePath).toLowerCase() === expectPath) {",
+ ' try {',
+ ' after.Terminate();',
+ ' } catch (e2) {',
+ ' // already exiting / access denied -> nothing to do',
+ ' }',
+ ' }',
+ '}',
+ '',
+].join('\r\n');
+
+let _watchdogScriptPath: string | null = null;
+let _watchdogScriptPrepareFailed = false;
+
+/**
+ * 预生成 win32 watchdog 脚本到 mkdtemp 唯一目录 (不可预测路径)。
+ * 在 installQuitHandler (启动期) 调用; 布防期 (armShutdownHardKillWatchdog)
+ * 再次调用时先校验缓存路径的文件是否仍存在 —— 杀毒软件或临时目录清理可能
+ * 在运行期间删除脚本, 此时清除缓存并重新生成到新目录。
+ * 写盘失败直接抛给调用方: 启动期调用点只 warn (布防期走缺席标记路径)。
+ * 非 win32 平台 no-op 返回 null。失败一次后不再重试
+ * (避免退出热路径被无响应存储阻塞)。
+ */
+export function prepareShutdownWatchdogScript(
+ options: { platform?: NodeJS.Platform; tmpDir?: string } = {},
+): string | null {
+ const platform = options.platform ?? process.platform;
+ if (platform !== 'win32') return null;
+ if (_watchdogScriptPath) {
+ if (existsSync(_watchdogScriptPath)) return _watchdogScriptPath;
+ _watchdogScriptPath = null;
+ }
+ if (_watchdogScriptPrepareFailed) return null;
+ try {
+ const dir = mkdtempSync(join(options.tmpDir ?? tmpdir(), 'cindy-wd-'));
+ const scriptPath = join(dir, 'watchdog.js');
+ writeFileSync(scriptPath, WATCHDOG_SCRIPT_CONTENT);
+ _watchdogScriptPath = scriptPath;
+ return scriptPath;
+ } catch (e) {
+ _watchdogScriptPrepareFailed = true;
+ throw e;
+ }
+}
+
let _watchdogArmed = false;
/**
* watchdog spawn 总尝试预算(同步/异步失败共享计数,防 error→重试死循环):
@@ -234,8 +322,9 @@ function noteWatchdogSpawnFailure(err: unknown, options: Parameters<typeof armSh
* 正常退出时本进程早已死透, 补刀落空无害 (kill 静默失败)。PID 复用防护 (review
* P1 两轮): 映像名/命令行校验区分不了同一 App 的两次运行 (正常退出后更新器立即
* 重启、新实例在宽限期内拿到复用 PID 会被误杀), 所以 watchdog 在布防时刻 (本进程
- * 必然存活) 先捕获目标 PID 的**进程创建时间**, 补刀前重取一次, 不一致 = PID 已易主,
- * 放弃。残余窗口只剩 "本进程在 watchdog 子进程完成首次捕获前 (毫秒级) 就退出且
+ * 必然存活) 先捕获目标 PID 的**进程创建时间** (POSIX: ps lstart; win32: WMI
+ * CreationDate), 补刀前重取一次并比对 execPath, 不一致 = PID 已易主, 放弃。
+ * 残余窗口只剩 "本进程在 watchdog 子进程完成首次捕获前 (毫秒级) 就退出且
* PID 立即复用给另一个同路径进程", 视为可接受。
*
* 幂等: 进程生命周期内只布防一次。spawn/pid/platform 可注入, 便于单测;
@@ -249,6 +338,8 @@ export function armShutdownHardKillWatchdog(
graceSeconds?: number;
/** 进程身份锚点 (杀前校验用), 默认 process.execPath;测试注入。 */
execPath?: string;
+ /** win32 watchdog 脚本落盘目录, 默认 os.tmpdir();测试注入。 */
+ tmpDir?: string;
} = {},
): void {
if (_watchdogArmed) return;
@@ -262,33 +353,44 @@ export function armShutdownHardKillWatchdog(
const execPath = options.execPath ?? process.execPath;
try {
// 杀前校验进程身份 (review P1 两轮): 宽限期内 OS 复用了该 PID 时, 盲杀会误伤。
- // 映像名/命令行校验区分不了同一 App 的两次运行 (更新器重启的新实例), 所以以
- // **进程创建时间**为身份锚点: 布防时刻本进程必然存活, watchdog 子进程先捕获
+ // 两平台都以进程创建时间为身份锚点: 布防时刻本进程必然存活, watchdog 先捕获
// 目标 PID 的创建时间, 补刀前重取比对, 不一致 = PID 已易主, 放弃补刀。
const child =
platform === 'win32'
? (() => {
- // cmd 拿不到进程创建时间 (wmic 已从新版 Windows 移除), 改用 Windows
- // PowerShell 5.1 —— 所有受支持 Windows 内置, 用 SystemRoot 绝对路径,
- // 不假设它在 PATH。属性读取走 Select-Object -ExpandProperty 而非语言级
- // .StartTime, 兼容企业锁死环境的 Constrained Language Mode (其下语言级
- // 属性访问被禁, cmdlet 内部反射不受限);取不到创建时间时直接退出不杀,
- // 失败方向是"少杀"而非"误杀"。字符串 -eq 大小写不敏感, 路径比对安全。
- const psExe =
- `${process.env.SystemRoot ?? 'C:\\Windows'}` +
- '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';
- const script =
- `$ErrorActionPreference='SilentlyContinue'; ` +
- `$started = Get-Process -Id ${pid} | Select-Object -ExpandProperty StartTime; ` +
- `if (-not $started) { exit }; ` +
- `Start-Sleep -Seconds ${graceSeconds}; ` +
- `$p = Get-Process -Id ${pid}; ` +
- `if ($p -and ($p | Select-Object -ExpandProperty StartTime) -eq $started ` +
- `-and ($p | Select-Object -ExpandProperty Path) -eq '${execPath.replace(/'/g, "''")}') ` +
- `{ Stop-Process -Id ${pid} -Force }`;
+ // 不用 PowerShell —— 360 等安全软件把"隐藏拉起 PowerShell"当高危
+ // 动作拦截, 每次正常退出都弹风控 (2026-08 实证: 原实现的
+ // -WindowStyle Hidden 正中"隐藏执行 PowerShell"规则)。也不用
+ // cmd + tasklist 轮询 —— 实机验证发现两条死路:
+ // - 非 detached 的子进程在 libuv 的 kill-on-close job object 里,
+ // 父进程一死就被 OS 连带击杀, 根本活不到补刀;
+ // - detached 逃出 job 但没有控制台 (DETACHED_PROCESS 会让
+ // CREATE_NO_WINDOW 失效), cmd 的每个子工具进程都要另开控制台,
+ // 既闪窗, 管道还会因句柄泄进新 conhost 而永久收不到 EOF
+ // (实测 findstr 无限挂起, watchdog 名存实亡)。
+ // wscript (GUI 子系统, 天生无控制台) + 单进程 JScript 两个问题都
+ // 不存在: Sleep / WMI 查询 / Terminate 全部进程内完成, 零子进程;
+ // detached 逃出 libuv job 得以活过父进程; 身份校验与原 PowerShell
+ // 实现同强度 (CreationDate + ExecutablePath 双校验)。//B 批处理
+ // 模式吞掉一切脚本错误弹窗, WSH 被禁用/损坏时静默不杀 —— 失败
+ // 方向永远是"少杀"。脚本内容见 WATCHDOG_SCRIPT_CONTENT。
+ const scriptPath = prepareShutdownWatchdogScript({
+ platform,
+ tmpDir: options.tmpDir,
+ });
+ // platform 为 win32 时 prepare 只可能返回路径或 throw (写盘失败);
+ // throw 由外层 catch 接住, 走 spawn 失败的重试/缺席标记路径。
+ if (!scriptPath) throw new Error('watchdog script unavailable');
return spawnFn(
- psExe,
- ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', script],
+ `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\wscript.exe`,
+ [
+ '//B',
+ '//E:JScript',
+ scriptPath,
+ String(pid),
+ String(graceSeconds * 1000),
+ execPath,
+ ],
{ detached: true, windowsHide: true, stdio: 'ignore' },
);
})()
@@ -385,7 +487,9 @@ function beginShutdown(timeoutMs: number, reason: string): Promise<void> {
// watchdog 必须是 shutdown 的第一个动作 (review P1): log 与 noteShutdownBegin
// 都是同步盘 IO (日志文件 / run-marker 的 mkdirSync+writeFileSync), 落在坏盘
// 或网络盘上可能无限阻塞 —— 那正是 watchdog 要兜的挂死形态, 不能让布防
- // 排在它们后面。spawn 本身不做盘写。
+ // 排在它们后面。spawn 本身不做盘写 (win32 的 watchdog 脚本已在启动期由
+ // installQuitHandler 预生成; 布防期只做存在性校验——脚本被外部删除时
+ // prepareShutdownWatchdogScript 会清缓存并重建, 启动期写盘失败则直接走缺席标记)。
armShutdownHardKillWatchdog();
log.info(`beginShutdown timeoutMs=${timeoutMs} reason=${reason}`);
noteShutdownBegin(reason);
@@ -408,6 +512,17 @@ export function installQuitHandler(timeoutMs = 2000): void {
if (_installed) return;
_installed = true;
+ // win32 watchdog 脚本在启动期预生成 —— 布防发生在 shutdown 热路径, 必须保持
+ // 零盘 IO (见 beginShutdown 注释)。这里失败只 warn 并设 prepare-failed 标记:
+ // 后续布防直接走缺席路径, 不会在退出热路径再碰盘。
+ if (process.platform === 'win32') {
+ try {
+ prepareShutdownWatchdogScript();
+ } catch (err) {
+ log.warn('failed to pre-generate shutdown watchdog script (absent for this session)', err);
+ }
+ }
+
// ── Built-in: 强制 Chromium 把 renderer 攒批的 localStorage 写入落盘 ────
// Chromium 的 LocalStorageImpl 在 browser 进程里有秒级 batch 才提交到
// <userData>/Local Storage/leveldb。我们 disposer chain 末尾走 app.exit()