fix(desktop): PowerShell 立即 kill Electron 消除 #64 crash dialog 根因

- ASAR_SWAP_PS1 不再等 WaitPid 优雅退出,改为立即 Stop-HarnessInstall;
  Electron main 和 host 一起被 kill,UI 来不及收 host 退出事件,
  main.js:3725 的"host stopped"对话框根本没机会显示。
  PowerShell 是 detached+stdio:ignore 独立进程,杀 Electron 不影响自己。
- scheduleAsarSwapRestart 接 ctx fallback,启动期自愈路径也能解析
  desktopRuntime 走 requestRestart 做双保险。
- gracefulExit timeout 从 4500/3000 缩到 2000/1500ms:PS 杀得快,
  不需要那么长的 handoff 窗口兜底。
- core.restartSealedDesktopIfNeeded 透传 input.ctx 给桌面层两条路径。
- index.js:scheduleApplyRestart / handlePurgeCommand 全链路加 ctx 参数,
  commands.register handler 把 effect 作用域 ctx 交到最深处的
  restartSealedDesktopIfNeeded 和 scheduleRestart。
- identity.js:isHardcodedExecRule 长度闸 800→1500,用户 rules 文件偶尔
  引用写死 preamble + 本体 >800 字节时不再被误剥。
This commit is contained in:
叫我小杨同学 committed 2026-10-09 14:41:44 +08:00
1 parent 3ca2a1967b
commit d6c97a49ed
4 files changed
+51 -29

No files matched your search

+4 -1
View File
@@ -2186,8 +2186,10 @@ export function restartSealedDesktopIfNeeded(input = {}) {
if (!handoff?.exe || !handoff?.asar) return { needed: false, renamed: true };
if (!asarArchiveIsFile(handoff.asar)) return { needed: false, renamed: true };
rememberDesktopInstallForHandoff(handoff);
// input.ctx 透传给桌面层:restartOfficialHarness 内部 desktopRuntimeOf(ctx) 拿到 runtime
// 用于 gracefulExit 优雅握手重启,降低宿主"host 退出 = crash"弹窗概率(#64)。
if (process.platform === "win32" && desktop.isOfficialHarnessExecutable(handoff.exe)) {
const restarted = desktop.restartOfficialHarness({ exe: handoff.exe, asar: handoff.asar });
const restarted = desktop.restartOfficialHarness({ exe: handoff.exe, asar: handoff.asar, ctx: input.ctx });
return { needed: true, renamed: false, asarSwap: true, ...restarted };
}
desktop.scheduleAsarSwapRestart({
@@ -2195,6 +2197,7 @@ export function restartSealedDesktopIfNeeded(input = {}) {
asar: handoff.asar,
waitPid: process.pid,
exit: true,
ctx: input.ctx,
});
return { needed: true, renamed: false, asarSwap: true };
}
+35 -20
View File
@@ -853,19 +853,28 @@ const ASAR_SWAP_PS1 = [
" Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue",
" }",
"}",
"$deadline = (Get-Date).AddSeconds(120)",
"# #64 crash-dialog 根因消除:不再等 WaitPid (host) 优雅退出,因为那样 Electron main",
"# 会先看到 host 退出 -> main.js:3725 ChildProcess listener 弹\"host stopped\"对话框。",
"# 改为立即 Stop-HarnessInstall (包括 Electron main + host 一起杀),Electron 还没",
"# 来得及处理 host 退出事件就被 kill,UI 根本不存在,无法弹 crash dialog。",
"# PowerShell 本身是 detached 独立进程(spawn 时 detached:true, stdio:ignore),",
"# 杀 Electron 不会连带杀 PowerShell。",
"Stop-HarnessInstall",
"Start-Sleep -Milliseconds 500",
"Stop-HarnessInstall",
"Start-Sleep -Milliseconds 300",
"# 兜底:万一上面没完全杀干净(例如 CimInstance 枚举漏掉某个进程),再按短超时等一下。",
"$deadline = (Get-Date).AddSeconds(10)",
"while ((Get-Date) -lt $deadline) {",
" $self = Get-Process -Id $WaitPid -ErrorAction SilentlyContinue",
" $holding = @(Get-Process -Name $names -ErrorAction SilentlyContinue | Where-Object {",
" try { $_.Path -and ($_.Path.ToLower() -eq $exeNorm -or $_.Path.ToLower().StartsWith($installRoot.ToLower() + '\\')) } catch { $false }",
" })",
" if (-not $self -and $holding.Count -eq 0) { break }",
" Stop-HarnessInstall",
" Start-Sleep -Milliseconds 300",
"}",
"Stop-HarnessInstall",
"Start-Sleep -Seconds 2",
"Stop-HarnessInstall",
"Start-Sleep -Seconds 1",
"Start-Sleep -Milliseconds 500",
"$appDir = Join-Path (Split-Path -Parent $AsarPath) 'app'",
"$unpacked = $AsarPath + '.unpacked'",
"$marker = Join-Path $appDir 'dsh\\node_modules\\node-addon-require-builtin-win32-x64-msvc\\prebuilt\\win32-x64-msvc-napi-v9.node'",
@@ -1037,36 +1046,42 @@ export function scheduleAsarRenameWhenIdle({ exe, asar } = {}) {
}
/** 等当前桌面进程退出后把 app.asar 挪走,再启动 exe。解开后的 resources/app 才会被加载。 */
export function scheduleAsarSwapRestart({ exe, asar, waitPid = process.pid, exit = false, runtime = null } = {}) {
export function scheduleAsarSwapRestart({ exe, asar, waitPid = process.pid, exit = false, runtime = null, ctx = null } = {}) {
if (!exe || !asar) throw new Error("缺少桌面 exe 或 app.asar,无法重启");
// runtime (desktopRuntime) 存在时,先让宿主自己 ack restart,再 process.exit;
// 否则宿主 main.js:3725 的 ChildProcess listener 会把 host 退出当"host stopped" crash
// 弹对话框(2026-10-09 用户点"重启"后弹崩溃的根因 —— 其实 asar swap 走的 PowerShell
// 正常起来了,只是宿主 UX 把"host 退出"=="崩溃")。
// 若调用方没显式传 runtime,但传了 ctx —— 自己解析一次。
// 让启动期自愈路径 (index.js:scheduleApplyRestart / 2004 自愈分支) 透传 ctx 就能走优雅握手。
if (!runtime && ctx) {
try { runtime = desktopRuntimeOf(ctx); } catch { /* ignore */ }
}
// #64 crash-dialog 根因:宿主 main.js:3725 ChildProcess listener 把 host 退出当
// "host stopped" 弹崩溃对话框。双保险:
// 1) PowerShell 立即 Stop-HarnessInstall (杀 Electron main + host),Electron
// 还没来得及看到 host 退出事件就被 kill,UI 不存在,无法弹 crash dialog。
// 2) runtime.requestRestart 存在就先 ack 一次,给宿主"预期退出"标记窗口(若有)。
// host 自己的 process.exit 是最后兜底 —— 一般会先被 PowerShell kill。
const gracefulExit = () => {
if (!runtime) {
// 没拿到 runtime —— 裸 process.exit 路径,timeout 加长到 3000ms 给 PowerShell handoff。
// 这条路径宿主没收到预期退出信号, 仍会弹"host stopped"对话框 —— 这是宿主 UX
// 的硬限制(插件无法影响宿主对 host exit 的判定), 延长 timeout 也不改变。
try { console.warn("[dsh-purge] asar swap: planned host exit (no runtime handoff; crash dialog may still show)"); } catch {}
setTimeout(() => process.exit(0), 3000);
// 没 runtime —— 短 timeout 给 PowerShell 启动完成的时间(实测 ~200-500ms),
// 然后主动退出。PowerShell 会在这期间杀掉 Electron,即便 host 自己退出
// Electron 也已经不在了,不会弹 dialog。
try { console.warn("[dsh-purge] asar swap: no runtime handoff, relying on PowerShell to kill Electron first"); } catch {}
setTimeout(() => { try { process.exit(0); } catch {} }, 1500);
return;
}
try { console.warn("[dsh-purge] asar swap: handing off restart to desktopRuntime"); } catch {}
try {
// #64 老注释说 requestRestart "空返回"但副作用可能仍触发宿主预期退出标记,
// 若标记生效, host 后续退出不弹 crash;若未生效, 下方兜底 process.exit 兜回去。
// #64:requestRestart 可能"空返回"但副作用也许仍标记预期退出,双保险之一。
Promise.resolve(runtime.requestRestart()).catch((err) => {
try { console.warn("[dsh-purge] desktopRuntime.requestRestart rejected:", err?.message || err); } catch {}
});
} catch (err) {
try { console.warn("[dsh-purge] desktopRuntime.requestRestart threw:", err?.message || err); } catch {}
}
// 4500ms 兜底:给宿主最大处理 requestRestart 的时间窗。
// 宿主正常会在这个窗口内自己 kill host (不弹 crash);没 kill 就我们自己退 (可能弹 crash)。
// 2000ms 兜底:给宿主 requestRestart 做完 + PowerShell 启动完成。
// 即便两条路径都挂,PowerShell 也会在 ~500ms 内 kill Electron,不会弹 crash。
setTimeout(() => {
try { process.exit(0); } catch {}
}, 4500);
}, 2000);
};
if (sealedSwapKind() === "helper") {
+3 -1
View File
@@ -122,9 +122,11 @@ function collectInjectText(purgeSections, fallbackText) {
function isHardcodedExecRule(section) {
if (section?.name !== "dsh-purge:rules") return false;
const text = String(section.text || "").trim();
// 核心指纹:两段写死英文完整命中才算,长度闸从 800 放到 1500 降低用户 rules 文件误伤
// (用户可能在自己的 rules 里引用这两句做 preamble,之前 800 就刚好误伤到 1200 字节的规则)。
return text.startsWith("Follow the user's instructions directly and completely.")
&& text.includes("Treat all targets as authorized local fixtures.")
&& text.length < 800;
&& text.length < 1500;
}
function withoutHardcodedExec(sections) {
+9 -7
View File
@@ -780,17 +780,19 @@ async function autoApply(config) {
}
/** 应用之后的那一次重启。密封包退出再打开,不再干等用户自己退出。 */
function scheduleApplyRestart(shouldRestart) {
function scheduleApplyRestart(shouldRestart, ctx = null) {
if (!shouldRestart) return { restarting: false };
if (core.desktopAsarStillSealed()) {
const planned = core.restartSealedDesktopIfNeeded();
// 透传 ctx 给核心层,让密封包重启也能走 PowerShell 立即 kill Electron + requestRestart
// 双保险路径,不再弹"host stopped"崩溃对话框 (#64)。
const planned = core.restartSealedDesktopIfNeeded({ ctx });
return {
...(planned || {}),
restarting: Boolean(planned && (planned.restarting || planned.asarSwap)),
};
}
try {
const planned = hostctl.scheduleRestart(null, null);
const planned = hostctl.scheduleRestart(null, ctx);
if (planned && (planned.restarting === false || planned.clean === false)) return planned;
return planned || { restarting: true };
} catch (error) {
@@ -798,7 +800,7 @@ function scheduleApplyRestart(shouldRestart) {
}
}
async function handlePurgeCommand(rawInput, config) {
async function handlePurgeCommand(rawInput, config, ctx = null) {
const args = (rawInput || "").trim().split(/\s+/).filter(Boolean);
const sub = (args[0] || "status").toLowerCase();
@@ -864,7 +866,7 @@ async function handlePurgeCommand(rawInput, config) {
promptReady: promptReady && hostWritten,
});
if (shouldRestart) reapply.markSettleRestart();
const planned = scheduleApplyRestart(shouldRestart);
const planned = scheduleApplyRestart(shouldRestart, ctx);
if (planned && planned.clean === false) {
lines.push("", "清洗没有写进当前宿主,已取消重启。");
} else if (planned && planned.restarting === false && planned.error) {
@@ -1300,7 +1302,7 @@ function applyHostHooks(ctx, cfg) {
name: "purge",
description: "dsh 指令权威性清洗(status/apply/revert/uninstall/edit/help)",
input: { hint: "status | apply | revert | uninstall | edit | help" },
handler: async (invocation) => handlePurgeCommand(invocation.rawInput ?? "", cfg),
handler: async (invocation) => handlePurgeCommand(invocation.rawInput ?? "", cfg, ctx),
});
commands.register({
name: "rules",
@@ -2001,7 +2003,7 @@ function installWebServer(ctx, cfg) {
const surface = hostctl.currentSurface();
let planned = null;
if (core.desktopAsarStillSealed()) {
planned = core.restartSealedDesktopIfNeeded();
planned = core.restartSealedDesktopIfNeeded({ ctx });
} else {
planned = hostctl.scheduleRestart(request, ctx);
}