diff --git a/client.js b/client.js index c94b678..19db247 100644 --- a/client.js +++ b/client.js @@ -1527,13 +1527,16 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:var(--ds text: tr("restart.incomplete", { detail: parts.join(";") }), }); loadAll(); - setAskRestart(true); + return; + } + if (action === "apply" && (d.restarting || d.restart_after_apply)) { + loadAll(); + restartDsh(setNotice, function () {}, tr, hostSurfaceOf(state)); return; } if (action === "apply") { setNotice({ kind: "ok", text: tr("ok.done") }); loadAll(); - setAskRestart(true); return; } setNotice({ kind: "ok", text: tr("ok.done") }); @@ -1548,7 +1551,7 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:var(--ds }); }; run(); - }, [loadAll, rejectNeedPrompt]); + }, [loadAll, rejectNeedPrompt, state]); const saveOverride = useCallback(() => { const tr = t; diff --git a/lib/core.js b/lib/core.js index 0fed91a..7840092 100644 --- a/lib/core.js +++ b/lib/core.js @@ -2302,6 +2302,21 @@ const PATCHES = [ ], markers: ["[dsh-purge] preset shell network"], }, + { + id: 73, + name: "PRESET_BASH_MIRROR_LINE", + layer: "提示词", + layer_en: "Prompt", + desc: "极简 bash 去掉误留的镜像说明 / drop the extra mirror sentence", + file: ["preset-minimal", "preset-sdk-minimal"], + optional: true, + replacements: [ + { + pattern: /\n[ \t]*\* Network access depends on the task environment\. Prefer configured mirrors\/proxies when they are available\.\n/, + replace: "\n", + }, + ], + }, { id: 71, name: "LIANGSHEN_IDENTITY_LINE", diff --git a/lib/desktop.js b/lib/desktop.js index 72257b8..719ee7c 100644 --- a/lib/desktop.js +++ b/lib/desktop.js @@ -771,7 +771,9 @@ function helperEnv(payload) { function spawnHelper(helper, payload, opts = {}) { const plan = restartPlan(); - if (!plan.execPath) throw new Error(plan.error || "未找到 DSH Desktop.exe,无法重启桌面应用"); + const hinted = payload && payload.execPath ? payload.execPath : ""; + const execPath = hinted || plan.execPath; + if (!execPath) throw new Error(plan.error || "未找到 DSH Desktop.exe,无法重启桌面应用"); const child = spawn(process.execPath, [helper], { detached: true, stdio: "ignore", @@ -779,9 +781,9 @@ function spawnHelper(helper, payload, opts = {}) { shell: false, env: helperEnv({ kind: "desktop", - execPath: plan.execPath, + execPath, argv: plan.argv, - cwd: plan.cwd, + cwd: plan.cwd || path.dirname(execPath), pid: process.pid, ...payload, }), @@ -988,16 +990,22 @@ export function scheduleAsarRenameWhenIdle({ exe, asar } = {}) { return { pending: true }; } -/** 等当前桌面进程退出后把 app.asar 挪走,再启动 exe。解开后的 resources\\app 才会被加载。 */ +/** 等当前桌面进程退出后把 app.asar 挪走,再启动 exe。解开后的 resources/app 才会被加载。 */ export function scheduleAsarSwapRestart({ exe, asar, waitPid = process.pid, exit = false } = {}) { if (!exe || !asar) throw new Error("缺少桌面 exe 或 app.asar,无法重启"); - if (process.platform === "darwin") { + if (sealedSwapKind() === "helper") { const helper = fileURLToPath(new URL("./restart-desktop.js", import.meta.url)); - spawnHelper(helper, { respawn: true, killApp: true, asar, waitPid }, { exit: false }); + spawnHelper(helper, { + respawn: true, + killApp: true, + asar, + execPath: exe, + cwd: path.dirname(exe), + waitPid, + }, { exit: false }); if (exit !== false) setTimeout(() => process.exit(0), 800); return { scheduled: true }; } - if (process.platform !== "win32") return scheduleAsarRenameWhenIdle({ exe, asar }); const script = path.join(os.tmpdir(), `dsh-purge-asar-swap-${process.pid}.ps1`); fs.writeFileSync(script, ASAR_SWAP_PS1, "utf8"); const child = spawn( @@ -1022,8 +1030,30 @@ export function scheduleAsarSwapRestart({ exe, asar, waitPid = process.pid, exit return { scheduled: true }; } +/** + * 点「应用」之后走哪条重启。#64:宿主 requestRestart 在桌面端会空返回,进程不动。 + * Windows 官方包用 wscript 结束再打开。Linux / macOS 能定位到 exe 就走 restart-desktop.js。 + */ +export function desktopRestartChoice(input = {}) { + const platform = input.platform || process.platform; + const exe = input.exe || ""; + const desktopExe = Boolean(exe && isDesktopExecutable(exe)); + const official = Boolean(exe && isOfficialHarnessExecutable(exe)); + if (input.openBrowser === false) return "skip"; + if (platform === "win32" && official) return "windows-official"; + if (desktopExe && input.asarSealed === true) return "asar-swap"; + if (desktopExe) return "helper"; + if (input.hasRuntime) return "request-restart"; + return "helper"; +} + +/** 密封 asar 要先退出进程才能挪走文件。Windows 用 PowerShell;Linux / macOS 用同一份重启脚本。 */ +export function sealedSwapKind(platform = process.platform) { + return platform === "win32" ? "powershell" : "helper"; +} + function officialExeFromProcess() { - // macOS / Linux 的重启走宿主 requestRestart。这里的 wscript 只服务 Windows 官方包。 + // Windows 官方包用 wscript。macOS 解开后的重启走 restart-desktop.js,不靠 requestRestart。 if (process.platform !== "win32") return ""; if (isOfficialHarnessExecutable(process.execPath)) return path.normalize(process.execPath); const resources = process.resourcesPath; @@ -1061,6 +1091,28 @@ export function scheduleRestart(request, ctx, options = {}) { return { restarting: true, asarSwap: true }; } const runtime = desktopRuntimeOf(ctx); + const choice = desktopRestartChoice({ + exe, + asarSealed: false, + hasRuntime: Boolean(runtime), + }); + if (choice === "helper" && exe && isDesktopExecutable(exe)) { + const helper = fileURLToPath(new URL("./restart-desktop.js", import.meta.url)); + try { + spawnHelper(helper, { + respawn: true, + killApp: true, + execPath: exe, + cwd: path.dirname(exe), + }, { exit: false }); + } catch (error) { + return { + restarting: false, + error: error instanceof Error ? error.message : String(error), + }; + } + return { restarting: true }; + } if (runtime) { // 只走桌面整应用 relaunch,不要 exit Host(那会先把内嵌 web 单独拉起来)。 Promise.resolve(runtime.requestRestart()).catch((err) => { diff --git a/lib/index.js b/lib/index.js index 7c60903..aa9d878 100644 --- a/lib/index.js +++ b/lib/index.js @@ -626,6 +626,25 @@ async function autoApply(config) { } } +/** 应用之后的那一次重启。密封包退出再打开,不再干等用户自己退出。 */ +function scheduleApplyRestart(shouldRestart) { + if (!shouldRestart) return { restarting: false }; + if (core.desktopAsarStillSealed()) { + const planned = core.restartSealedDesktopIfNeeded(); + return { + ...(planned || {}), + restarting: Boolean(planned && (planned.restarting || planned.asarSwap)), + }; + } + try { + const planned = hostctl.scheduleRestart(null, null); + if (planned && (planned.restarting === false || planned.clean === false)) return planned; + return planned || { restarting: true }; + } catch (error) { + return { restarting: false, error: String(error && error.message ? error.message : error) }; + } +} + async function handlePurgeCommand(rawInput, config) { const args = (rawInput || "").trim().split(/\s+/).filter(Boolean); const sub = (args[0] || "status").toLowerCase(); @@ -644,14 +663,10 @@ async function handlePurgeCommand(rawInput, config) { const scrubbed = core.sanitizeDesktopCommandRuntimes(); const state = await core.gatherState(); if (home) state.dsh_home = home; - let handoff = null; if (!state.ai_base) { const opened = await core.openSealedDesktopHost(); if (!opened.aiBase) return { kind: "error", text: core.missingAiBaseMessage() }; state.ai_base = opened.aiBase; - if (opened.swapAsar) handoff = opened; - } else { - handoff = core.sealedAsarHandoff(); } const blocked = rejectIfNeedPrompt(state.dsh_home); if (blocked) return { kind: "error", text: blocked.error }; @@ -672,13 +687,26 @@ async function handlePurgeCommand(rawInput, config) { lines.push("", "Desktop in-bin .bak scrub:"); for (const row of scrubbed) lines.push(` ✓ ${row.dir} → ${row.cleaned.join(", ")}`); } - lines.push("", "全部完成 / All done。重启 dsh 生效 / Restart dsh to take effect."); lines.push("Desktop: host-commands 密封目录只清理不注入;bak 禁止写进 bin(issue #9)。"); - if (handoff) { - const swapped = core.scheduleSealedDesktopRestart(handoff); - if (swapped?.renamed || swapped?.pending) { - lines.push("", "补丁已写入。请在设置页点「重启」,客户端会自己重新打开。"); - } + const summary = core.summarizeApplyReport(report); + const complete = summary.failed.length === 0 && flash.ok === true; + const shouldRestart = applyShouldRestart({ + complete, + sealed: core.desktopAsarStillSealed(), + appliedCount: summary.applied, + }); + if (shouldRestart) reapply.markSettleRestart(); + const planned = scheduleApplyRestart(shouldRestart); + if (planned && planned.clean === false) { + lines.push("", "清洗没有写进当前宿主,已取消重启。"); + } else if (planned && planned.restarting === false && planned.error) { + lines.push("", String(planned.error)); + } else if (shouldRestart && planned && planned.restarting !== false) { + lines.push("", "正在重启。"); + } else if (!complete) { + lines.push("", "清洗没有完成,没有重启。"); + } else { + lines.push("", "补丁已经在宿主里,不再重启。"); } return { kind: "success", text: lines.join("\n") }; } @@ -1555,19 +1583,12 @@ function installWebServer(ctx, cfg) { const flash = core.silenceCmdFlash(state.ai_base); const summary = core.summarizeApplyReport(report); const complete = summary.failed.length === 0 && flash.ok === true; - let renamed = false; let pendingQuit = false; - if (handoff) { - if (core.desktopAsarStillSealed()) { - // 仍在读 app.asar:不要先挂 idle-rename(易留下 rename-pending 且与 wscript 重启抢锁)。 - pendingQuit = true; - } else { - const swapped = core.scheduleSealedDesktopRestart(handoff); - renamed = Boolean(swapped?.renamed); - pendingQuit = Boolean(swapped?.pending); - } + if (handoff && core.desktopAsarStillSealed()) { + // 仍在读 app.asar:等这次响应发出后由重启接口退出再打开,不要先挂 idle-rename。 + pendingQuit = true; } - const leaveTray = renamed || pendingQuit; + const leaveTray = pendingQuit; const onlyUnmatched = summary.failed.every((item) => item.status === "pattern_not_found"); if (flash.ok === true && onlyUnmatched && core.hostCleanMarkersPresent(state.ai_base)) { reapply.markPatchesApplied(); @@ -1794,15 +1815,18 @@ function installWebServer(ctx, cfg) { } // 用户已点重启:清掉粘性标记,避免同进程误刷新/再进面板又弹一次。 bootFullQuit = false; + const restarting = Boolean(planned && (planned.restarting || planned.asarSwap)); + const restartError = planned && planned.error ? String(planned.error) : ""; sendJson(response, 200, { - ok: true, + ok: restarting || !restartError, surface, fullApp: surface === "desktop", - restarting: Boolean(planned && (planned.restarting || planned.asarSwap)), + restarting, already: Boolean(planned && planned.already), needsFullQuit: Boolean(planned && planned.asarSwap), asar_still_sealed: core.desktopAsarStillSealed(), - note: "正在重启。", + error: restartError || undefined, + note: restarting ? "正在重启。" : restartError, }); } catch (e) { sendJson(response, 500, { ok: false, error: String(e) }); diff --git a/lib/restart-desktop.js b/lib/restart-desktop.js index bf80960..23294de 100644 --- a/lib/restart-desktop.js +++ b/lib/restart-desktop.js @@ -145,9 +145,40 @@ function listDarwinPids(exe) { return [...new Set(pids)]; } +function commandMatchesExe(cmd, exe) { + if (!cmd || !exe) return false; + if (cmd.includes("/dsh-desktop-host/lib/cli.js")) return false; + return cmd === exe || cmd.startsWith(`${exe} `) || cmd.startsWith(`${exe}\t`); +} + +function listPosixPids(exe) { + if (!exe) return []; + let out = ""; + try { + out = execFileSync("ps", ["-Ao", "pid=,command="], { + encoding: "utf8", + timeout: 8000, + }); + } catch { + return []; + } + const pids = []; + for (const line of String(out || "").split(/\n/)) { + const trimmed = line.trim(); + if (!trimmed) continue; + const sp = trimmed.search(/\s/); + if (sp < 0) continue; + const pid = Number(trimmed.slice(0, sp).trim()); + const cmd = trimmed.slice(sp + 1).trim(); + if (!pid || !commandMatchesExe(cmd, exe)) continue; + pids.push(pid); + } + return [...new Set(pids)]; +} + function listDesktopPids(exe = info.execPath) { if (process.platform === "darwin") return listDarwinPids(exe); - if (process.platform !== "win32") return []; + if (process.platform !== "win32") return listPosixPids(exe); const images = ["DeepSeek Harness.exe", "DSH Desktop.exe"]; const pids = []; for (const image of images) { @@ -181,6 +212,18 @@ async function waitDesktopGone(exe, timeoutMs = 8000) { return listDesktopPids(exe).filter((pid) => pid !== process.pid).length === 0; } +async function quitPosixDesktop(exe) { + signalPids(listDesktopPids(exe), "SIGTERM"); + if (await waitDesktopGone(exe, 8000)) { + log("quit by SIGTERM"); + return "SIGTERM"; + } + signalPids(listDesktopPids(exe), "SIGKILL"); + await waitDesktopGone(exe, 2000); + log("quit by SIGKILL"); + return "SIGKILL"; +} + async function quitDarwinDesktop(exe) { const bundle = darwinBundleOf(exe); const name = darwinBundleName(bundle); @@ -293,9 +336,11 @@ if (info.killApp) { } if (process.platform === "darwin") { await quitDarwinDesktop(info.execPath); - } else { + } else if (process.platform === "win32") { killOtherDesktopProcesses(process.pid); await sleep(500); + } else { + await quitPosixDesktop(info.execPath); } if (info.asar) await moveAsarAsideAsync(info.asar); } else {