mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 10:50:22 +08:00
feat: 发布 1.1.19,支持官方桌面 EXE
官方客户端可以应用并自己重启;修掉重启弹窗、残留 PowerShell,以及更新时要手动还原再应用的问题。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
00ccf4a1f1
commit
fd8d47c00f
16 files changed
+973
-72
No files matched your search
+62
-1
@@ -13,6 +13,7 @@ import {
|
||||
revertHideConsoleFromBin,
|
||||
} from "./hide-console.js";
|
||||
import * as desktop from "./desktop.js";
|
||||
import { asarArchiveIsFile, extractAsar, overlayAsarUnpacked, renameAsarAside } from "./extract-asar.js";
|
||||
import { adapterFor, detectSurface } from "./surface.js";
|
||||
import { openSlot } from "./table-read.js";
|
||||
|
||||
@@ -104,6 +105,7 @@ export function resetPathMemo() {
|
||||
|
||||
function isFile(fp) {
|
||||
try {
|
||||
if (desktop.isAsarSealedPath(fp)) return false;
|
||||
return fs.existsSync(fp) && fs.statSync(fp).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
@@ -112,6 +114,7 @@ function isFile(fp) {
|
||||
|
||||
function isDir(fp) {
|
||||
try {
|
||||
if (desktop.isAsarSealedPath(fp)) return false;
|
||||
return fs.existsSync(fp) && fs.statSync(fp).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
@@ -160,6 +163,8 @@ function aiBaseGuessesAround(dir) {
|
||||
path.join(dir, "@deepseek-ai"),
|
||||
path.join(dir, "node_modules", "@deepseek-ai"),
|
||||
path.join(dir, "node_modules", nested),
|
||||
path.join(dir, "dsh", "node_modules", "@deepseek-ai"),
|
||||
path.join(dir, "dsh", "node_modules", nested),
|
||||
path.join(dir, "..", "node_modules", "@deepseek-ai"),
|
||||
path.join(dir, "..", "node_modules", nested),
|
||||
path.join(dir, "..", "..", "node_modules", "@deepseek-ai"),
|
||||
@@ -313,6 +318,7 @@ export function silenceCmdFlash(aiBase = findAiBase()) {
|
||||
hide.entry === "already_injected" ||
|
||||
hide.entry === "skipped_not_win32" ||
|
||||
hide.entry === "missing_bin" ||
|
||||
hide.entry === "sealed_asar" ||
|
||||
(typeof hide.entry === "string" && hide.entry.startsWith("error:"));
|
||||
return {
|
||||
...hide,
|
||||
@@ -1572,13 +1578,68 @@ export function missingAiBaseMessage() {
|
||||
if (adapterFor(detectSurface()) === "desktop") {
|
||||
const exe = desktop.findDesktopAppExecutable();
|
||||
if (exe) {
|
||||
const asar = path.join(path.dirname(exe), "resources", "app.asar");
|
||||
if (asarArchiveIsFile(asar) && desktop.isOfficialHarnessExecutable(exe)) {
|
||||
return `已找到 ${exe}。官方宿主在 app.asar 里,点「应用」会解开 resources\\app 并自动重启,不用另跑脚本。`;
|
||||
}
|
||||
return `已找到桌面应用 ${exe},但其 resources/app(或 app.asar.unpacked)下没有 @deepseek-ai`;
|
||||
}
|
||||
return "未定位到当前桌面应用的 @deepseek-ai。请在桌面端内打开设置再点「应用」(不要用官方 dsh)。安装目录可以是任意盘符;也可设置 DSH_DESKTOP_INSTALL 为安装目录,或 DSH_BASE 为该树下的 @deepseek-ai";
|
||||
return "未定位到当前桌面应用的 @deepseek-ai。官方客户端点「应用」会解开 app.asar 并重启;第三方 DSH Desktop 直接点「应用」。安装目录任意盘符。";
|
||||
}
|
||||
return "插件根未找到 / set DSH_BASE";
|
||||
}
|
||||
|
||||
function aiBaseUnderAppDir(appDir) {
|
||||
const cands = [
|
||||
path.join(appDir, "dsh", "node_modules", "@deepseek-ai"),
|
||||
path.join(appDir, "node_modules", "@deepseek-ai"),
|
||||
];
|
||||
return cands.find((p) => isAiBase(p)) || null;
|
||||
}
|
||||
|
||||
export function sealedAsarHandoff(input = {}) {
|
||||
const surface = input.surface ?? detectSurface(input);
|
||||
if (adapterFor(surface) !== "desktop") return null;
|
||||
const hinted = input.execPath;
|
||||
const exe = hinted && desktop.isDesktopExecutable(hinted)
|
||||
? path.normalize(hinted)
|
||||
: desktop.findDesktopAppExecutable(input);
|
||||
if (!exe || !desktop.isOfficialHarnessExecutable(exe)) return null;
|
||||
const asar = path.join(path.dirname(exe), "resources", "app.asar");
|
||||
if (!asarArchiveIsFile(asar)) return null;
|
||||
return { exe, asar, swapAsar: true };
|
||||
}
|
||||
|
||||
/** 官方 app.asar 解开到 resources/app。点「应用」时调用,不要求用户先跑脚本。 */
|
||||
export async function openSealedDesktopHost() {
|
||||
const handoff = sealedAsarHandoff();
|
||||
if (!handoff) return { aiBase: null, swapAsar: false };
|
||||
const appDir = path.join(path.dirname(handoff.exe), "resources", "app");
|
||||
let aiBase = aiBaseUnderAppDir(appDir);
|
||||
if (!aiBase) {
|
||||
await extractAsar(handoff.asar, appDir);
|
||||
aiBase = aiBaseUnderAppDir(appDir);
|
||||
}
|
||||
overlayAsarUnpacked(handoff.asar, appDir);
|
||||
if (!aiBase) {
|
||||
throw new Error(`已解开 ${handoff.asar},但 resources\\app 下没有 @deepseek-ai`);
|
||||
}
|
||||
resetPathMemo();
|
||||
return { aiBase, swapAsar: true, exe: handoff.exe, asar: handoff.asar };
|
||||
}
|
||||
|
||||
export function scheduleSealedDesktopRestart(handoff) {
|
||||
if (!handoff?.asar) return { renamed: false };
|
||||
const moved = renameAsarAside(handoff.asar);
|
||||
if (moved.renamed || !moved.busy) return moved;
|
||||
const pending = desktop.scheduleAsarRenameWhenIdle({ exe: handoff.exe, asar: handoff.asar });
|
||||
return { renamed: false, pending: true, ...pending };
|
||||
}
|
||||
|
||||
export function officialHostMustStayUp() {
|
||||
return process.env.ELECTRON_RUN_AS_NODE === "1" && desktop.isOfficialHarnessExecutable(process.execPath);
|
||||
}
|
||||
|
||||
export function findAiBase() {
|
||||
return remember("ai", () => {
|
||||
if (adapterFor(detectSurface()) === "desktop") return findAiBaseDesktop();
|
||||
|
||||
+344
-8
@@ -1,11 +1,22 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
/** 路径落在 `app.asar/...` 里面。`app.asar` 文件本身和 `app.asar.unpacked` 不算。 */
|
||||
export function isAsarSealedPath(p) {
|
||||
const parts = String(p || "").replace(/\\/g, "/").split("/").filter(Boolean);
|
||||
if (parts.length < 2) return false;
|
||||
return parts.slice(0, -1).some((seg) => {
|
||||
const s = seg.toLowerCase();
|
||||
return s.endsWith(".asar") && !s.endsWith(".asar.unpacked");
|
||||
});
|
||||
}
|
||||
|
||||
function isFile(fp) {
|
||||
try {
|
||||
if (isAsarSealedPath(fp)) return false;
|
||||
return Boolean(fp) && fs.existsSync(fp) && fs.statSync(fp).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
@@ -14,6 +25,7 @@ function isFile(fp) {
|
||||
|
||||
function isDir(fp) {
|
||||
try {
|
||||
if (isAsarSealedPath(fp)) return false;
|
||||
return Boolean(fp) && fs.existsSync(fp) && fs.statSync(fp).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
@@ -60,22 +72,42 @@ export function looksLikeDesktopName(p) {
|
||||
n.endsWith("/dsh desktop") ||
|
||||
n.endsWith("/dsh desktop.app") ||
|
||||
n.includes("dsh-desktop") ||
|
||||
/\/dsh desktop\.exe$/i.test(n)
|
||||
n.includes("/deepseek harness/") ||
|
||||
n.includes("/deepseek harness.app/") ||
|
||||
n.endsWith("/deepseek harness") ||
|
||||
n.includes("deepseek-harness") ||
|
||||
/\/dsh desktop\.exe$/i.test(n) ||
|
||||
/\/deepseek harness\.exe$/i.test(n)
|
||||
);
|
||||
}
|
||||
|
||||
export function isDesktopExecutable(fp) {
|
||||
const base = path.basename(String(fp || "")).toLowerCase();
|
||||
return base === "dsh desktop.exe" || base === "dsh desktop";
|
||||
return (
|
||||
base === "dsh desktop.exe" ||
|
||||
base === "dsh desktop" ||
|
||||
base === "deepseek harness.exe" ||
|
||||
base === "deepseek-harness.exe"
|
||||
);
|
||||
}
|
||||
|
||||
/** 只有官方 DeepSeek Harness 会把宿主封进 app.asar 并在「应用」时解开。第三方 DSH Desktop 不走这条。 */
|
||||
export function isOfficialHarnessExecutable(fp) {
|
||||
const base = path.basename(String(fp || "")).toLowerCase();
|
||||
return base === "deepseek harness.exe" || base === "deepseek-harness.exe";
|
||||
}
|
||||
|
||||
function exeCandidatesBeside(dir) {
|
||||
if (!dir) return [];
|
||||
return [
|
||||
path.join(dir, "DeepSeek Harness.exe"),
|
||||
path.join(dir, "deepseek-harness.exe"),
|
||||
path.join(dir, "DSH Desktop.exe"),
|
||||
path.join(dir, "DSH Desktop"),
|
||||
path.join(dir, "MacOS", "DSH Desktop"),
|
||||
path.join(dir, "MacOS", "DeepSeek Harness"),
|
||||
path.join(dir, "Contents", "MacOS", "DSH Desktop"),
|
||||
path.join(dir, "Contents", "MacOS", "DeepSeek Harness"),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -131,23 +163,106 @@ function trustedInstallDir(dir) {
|
||||
if (looksLikeDesktopName(dir)) return true;
|
||||
if (firstExistingExe([dir])) return true;
|
||||
return (
|
||||
isAiBase(path.join(dir, "resources", "app", "dsh", "node_modules", "@deepseek-ai")) ||
|
||||
isAiBase(path.join(dir, "resources", "app", "node_modules", "@deepseek-ai")) ||
|
||||
isAiBase(path.join(dir, "resources", "app.asar.unpacked", "dsh", "node_modules", "@deepseek-ai")) ||
|
||||
isAiBase(path.join(dir, "resources", "app.asar.unpacked", "node_modules", "@deepseek-ai"))
|
||||
);
|
||||
}
|
||||
|
||||
/** NSIS / 商店默认位置;不是全盘扫描。自定义目录靠进程或 DSH_DESKTOP_INSTALL。 */
|
||||
const REGISTRY_INSTALL_SCRIPT = `
|
||||
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
|
||||
$names = @('DeepSeek Harness','DSH Desktop')
|
||||
$roots = @(
|
||||
'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
|
||||
'HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
|
||||
'HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
|
||||
)
|
||||
$rows = foreach ($root in $roots) {
|
||||
if (-not (Test-Path $root)) { continue }
|
||||
Get-ChildItem $root -ErrorAction SilentlyContinue | ForEach-Object {
|
||||
$p = Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue
|
||||
if (-not $p.DisplayName) { return }
|
||||
$hit = $false
|
||||
foreach ($n in $names) { if ($p.DisplayName -like ('*' + $n + '*')) { $hit = $true } }
|
||||
if (-not $hit) { return }
|
||||
[pscustomobject]@{
|
||||
InstallLocation = [string]$p.InstallLocation
|
||||
DisplayIcon = [string]$p.DisplayIcon
|
||||
UninstallString = [string]$p.UninstallString
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($rows) { @($rows) | ConvertTo-Json -Compress }
|
||||
`.trim();
|
||||
|
||||
function exeDirFromRegistryValue(value) {
|
||||
let val = String(value || "").trim();
|
||||
const quoted = val.match(/^"([^"]+)"/);
|
||||
if (quoted) val = quoted[1];
|
||||
val = val.replace(/,0$/, "").trim();
|
||||
if (!val) return "";
|
||||
return path.normalize(path.dirname(val));
|
||||
}
|
||||
|
||||
let cachedRegistryDirs;
|
||||
/** 从卸载登记读安装目录。盘符跟着用户安装位置,不写死。 */
|
||||
export function registryInstallDirs() {
|
||||
if (cachedRegistryDirs) return cachedRegistryDirs;
|
||||
if (process.platform !== "win32") {
|
||||
cachedRegistryDirs = [];
|
||||
return cachedRegistryDirs;
|
||||
}
|
||||
let text = "";
|
||||
try {
|
||||
text = execFileSync("powershell.exe", ["-NoProfile", "-Command", REGISTRY_INSTALL_SCRIPT], {
|
||||
encoding: "utf8",
|
||||
windowsHide: true,
|
||||
timeout: 15000,
|
||||
});
|
||||
} catch {
|
||||
cachedRegistryDirs = [];
|
||||
return cachedRegistryDirs;
|
||||
}
|
||||
let rows = [];
|
||||
try {
|
||||
const parsed = JSON.parse(String(text || "").replace(/^\uFEFF/, "").trim() || "[]");
|
||||
rows = Array.isArray(parsed) ? parsed : parsed ? [parsed] : [];
|
||||
} catch {
|
||||
rows = [];
|
||||
}
|
||||
const found = [];
|
||||
for (const row of rows) {
|
||||
const location = String(row.InstallLocation || "").trim();
|
||||
if (location) found.push(path.normalize(location));
|
||||
found.push(exeDirFromRegistryValue(row.DisplayIcon));
|
||||
found.push(exeDirFromRegistryValue(row.UninstallString));
|
||||
}
|
||||
cachedRegistryDirs = uniquePaths(found).filter((dir) => firstExistingExe([dir]));
|
||||
return cachedRegistryDirs;
|
||||
}
|
||||
|
||||
/** NSIS / 商店默认位置;不是全盘扫描。自定义目录靠当前进程、卸载登记或 DSH_DESKTOP_INSTALL。 */
|
||||
export function commonDesktopInstallDirs(env = process.env) {
|
||||
const home = os.homedir();
|
||||
const local = env.LOCALAPPDATA || path.join(home, "AppData", "Local");
|
||||
const pf = env.ProgramFiles || "C:\\Program Files";
|
||||
const pf86 = env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
|
||||
const pf = env.ProgramFiles || "";
|
||||
const pf86 = env["ProgramFiles(x86)"] || "";
|
||||
return uniquePaths([
|
||||
...extraInstallsFromEnv(env).filter(trustedInstallDir),
|
||||
...registryInstallDirs(),
|
||||
path.join(local, "Programs", "DeepSeek Harness"),
|
||||
path.join(local, "Programs", "DSH Desktop"),
|
||||
path.join(pf, "DSH Desktop"),
|
||||
path.join(pf86, "DSH Desktop"),
|
||||
path.join(local, "DeepSeek Harness"),
|
||||
...(pf
|
||||
? [path.join(pf, "DeepSeek Harness"), path.join(pf, "DSH Desktop")]
|
||||
: []),
|
||||
...(pf86
|
||||
? [path.join(pf86, "DeepSeek Harness"), path.join(pf86, "DSH Desktop")]
|
||||
: []),
|
||||
"/Applications/DeepSeek Harness.app",
|
||||
"/Applications/DSH Desktop.app",
|
||||
path.join(home, "Applications", "DeepSeek Harness.app"),
|
||||
path.join(home, "Applications", "DSH Desktop.app"),
|
||||
]);
|
||||
}
|
||||
@@ -237,9 +352,13 @@ function packageRootsFromInstall(installDir) {
|
||||
const out = [];
|
||||
for (const base of bases) {
|
||||
out.push(
|
||||
path.join(base, "resources", "app", "dsh", "node_modules", "@deepseek-ai"),
|
||||
path.join(base, "resources", "app", "node_modules", "@deepseek-ai"),
|
||||
path.join(base, "resources", "app.asar.unpacked", "dsh", "node_modules", "@deepseek-ai"),
|
||||
path.join(base, "resources", "app.asar.unpacked", "node_modules", "@deepseek-ai"),
|
||||
path.join(base, "app", "dsh", "node_modules", "@deepseek-ai"),
|
||||
path.join(base, "app", "node_modules", "@deepseek-ai"),
|
||||
path.join(base, "app.asar.unpacked", "dsh", "node_modules", "@deepseek-ai"),
|
||||
path.join(base, "app.asar.unpacked", "node_modules", "@deepseek-ai"),
|
||||
);
|
||||
}
|
||||
@@ -255,7 +374,9 @@ export function listDesktopPackageRoots(input = {}) {
|
||||
|
||||
if (resourcesPath) {
|
||||
cands.push(
|
||||
path.join(resourcesPath, "app", "dsh", "node_modules", "@deepseek-ai"),
|
||||
path.join(resourcesPath, "app", "node_modules", "@deepseek-ai"),
|
||||
path.join(resourcesPath, "app.asar.unpacked", "dsh", "node_modules", "@deepseek-ai"),
|
||||
path.join(resourcesPath, "app.asar.unpacked", "node_modules", "@deepseek-ai"),
|
||||
);
|
||||
}
|
||||
@@ -271,9 +392,14 @@ export function listDesktopPackageRoots(input = {}) {
|
||||
if (typeof arg !== "string" || !APP_SCRIPT_RE.test(arg)) continue;
|
||||
const appDir = path.dirname(path.dirname(path.resolve(arg)));
|
||||
cands.push(path.join(appDir, "node_modules", "@deepseek-ai"));
|
||||
cands.push(path.join(appDir, "dsh", "node_modules", "@deepseek-ai"));
|
||||
cands.push(...packageRootsFromInstall(path.dirname(path.dirname(appDir))));
|
||||
}
|
||||
|
||||
const localHits = uniquePaths(cands).filter(isAiBase);
|
||||
// 已经在某个桌面 exe 里时,只改这一份。旁边装了另一种客户端也不能被带上。
|
||||
if (isDesktopExecutable(execPath)) return localHits;
|
||||
|
||||
for (const install of commonDesktopInstallDirs(env)) {
|
||||
cands.push(...packageRootsFromInstall(install));
|
||||
}
|
||||
@@ -420,7 +546,159 @@ function desktopRuntimeOf(ctx) {
|
||||
return runtime && typeof runtime.requestRestart === "function" ? runtime : null;
|
||||
}
|
||||
|
||||
const ASAR_SWAP_PS1 = [
|
||||
"param(",
|
||||
" [Parameter(Mandatory = $true)][int]$WaitPid,",
|
||||
" [Parameter(Mandatory = $true)][string]$AsarPath,",
|
||||
" [Parameter(Mandatory = $true)][string]$ExePath",
|
||||
")",
|
||||
"$ErrorActionPreference = 'Continue'",
|
||||
"$names = @('DeepSeek Harness', 'DSH Desktop')",
|
||||
"$deadline = (Get-Date).AddSeconds(90)",
|
||||
"while ((Get-Date) -lt $deadline) {",
|
||||
" $self = Get-Process -Id $WaitPid -ErrorAction SilentlyContinue",
|
||||
" $holding = @(Get-Process -Name $names -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $ExePath })",
|
||||
" if (-not $self -and $holding.Count -eq 0) { break }",
|
||||
" Start-Sleep -Milliseconds 300",
|
||||
"}",
|
||||
"Get-Process -Name $names -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $ExePath } | Stop-Process -Force -ErrorAction SilentlyContinue",
|
||||
"Start-Sleep -Seconds 1",
|
||||
"$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'",
|
||||
"if ((Test-Path -LiteralPath $unpacked) -and -not (Test-Path -LiteralPath $marker)) {",
|
||||
" & robocopy.exe $unpacked $appDir /E /XC /XN /XO /NFL /NDL /NJH /NJS /nc /ns /np | Out-Null",
|
||||
"}",
|
||||
"if (Test-Path -LiteralPath $AsarPath) {",
|
||||
" $bak = \"$AsarPath.bak\"",
|
||||
" if (Test-Path -LiteralPath $bak) { Remove-Item -LiteralPath $bak -Force -ErrorAction SilentlyContinue }",
|
||||
" $moved = $false",
|
||||
" for ($i = 0; $i -lt 30; $i++) {",
|
||||
" try {",
|
||||
" Move-Item -LiteralPath $AsarPath -Destination $bak -Force",
|
||||
" $moved = $true",
|
||||
" break",
|
||||
" } catch {",
|
||||
" Start-Sleep -Milliseconds 400",
|
||||
" }",
|
||||
" }",
|
||||
" if (-not $moved) { throw \"could not rename app.asar\" }",
|
||||
"}",
|
||||
"Remove-Item Env:ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue",
|
||||
"Start-Process -FilePath $ExePath",
|
||||
"",
|
||||
].join("\r\n");
|
||||
|
||||
const ASAR_RENAME_WHEN_IDLE_PS1 = [
|
||||
"param(",
|
||||
" [Parameter(Mandatory = $true)][string]$AsarPath,",
|
||||
" [Parameter(Mandatory = $true)][string]$ExePath,",
|
||||
" [Parameter(Mandatory = $true)][string]$LockPath",
|
||||
")",
|
||||
"$ErrorActionPreference = 'Continue'",
|
||||
"$deadline = (Get-Date).AddMinutes(30)",
|
||||
"while ((Get-Date) -lt $deadline) {",
|
||||
" if (Test-Path -LiteralPath (Join-Path $env:TEMP 'dsh-purge-official-restarting')) { exit 0 }",
|
||||
" $holding = @(Get-Process -ErrorAction SilentlyContinue | Where-Object { try { $_.Path -eq $ExePath } catch { $false } })",
|
||||
" if ($holding.Count -gt 0) { Start-Sleep -Milliseconds 500; continue }",
|
||||
" if (-not (Test-Path -LiteralPath $AsarPath)) {",
|
||||
" Remove-Item -LiteralPath $LockPath -Force -ErrorAction SilentlyContinue",
|
||||
" exit 0",
|
||||
" }",
|
||||
" $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'",
|
||||
" if ((Test-Path -LiteralPath $unpacked) -and -not (Test-Path -LiteralPath $marker)) {",
|
||||
" & robocopy.exe $unpacked $appDir /E /XC /XN /XO /NFL /NDL /NJH /NJS /nc /ns /np | Out-Null",
|
||||
" }",
|
||||
" $bak = \"$AsarPath.bak\"",
|
||||
" if (Test-Path -LiteralPath $bak) { Remove-Item -LiteralPath $bak -Force -ErrorAction SilentlyContinue }",
|
||||
" try {",
|
||||
" Move-Item -LiteralPath $AsarPath -Destination $bak -Force -ErrorAction Stop",
|
||||
" } catch {",
|
||||
" Start-Sleep -Milliseconds 400",
|
||||
" continue",
|
||||
" }",
|
||||
" Remove-Item -LiteralPath $LockPath -Force -ErrorAction SilentlyContinue",
|
||||
" Remove-Item Env:ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue",
|
||||
" Start-Process -FilePath $ExePath",
|
||||
" exit 0",
|
||||
"}",
|
||||
"Remove-Item -LiteralPath $LockPath -Force -ErrorAction SilentlyContinue",
|
||||
"",
|
||||
].join("\r\n");
|
||||
|
||||
/** 官方壳开着时 app.asar 被占用。不结束进程,等用户退出后再改名并重新打开。 */
|
||||
export function scheduleAsarRenameWhenIdle({ exe, asar } = {}) {
|
||||
if (!exe || !asar) return { pending: false };
|
||||
const lock = `${asar}.rename-pending`;
|
||||
try {
|
||||
const age = Date.now() - fs.statSync(lock).mtimeMs;
|
||||
if (age >= 0 && age < 30 * 60 * 1000) return { pending: true, already: true };
|
||||
} catch {
|
||||
// 没有待处理标记,下面新建。
|
||||
}
|
||||
fs.writeFileSync(lock, `${Date.now()}\n`, "utf8");
|
||||
const script = path.join(os.tmpdir(), "dsh-purge-asar-rename-when-idle.ps1");
|
||||
fs.writeFileSync(script, ASAR_RENAME_WHEN_IDLE_PS1, "utf8");
|
||||
const child = spawn(
|
||||
"powershell.exe",
|
||||
[
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
script,
|
||||
"-AsarPath",
|
||||
asar,
|
||||
"-ExePath",
|
||||
exe,
|
||||
"-LockPath",
|
||||
lock,
|
||||
],
|
||||
{ detached: true, stdio: "ignore", windowsHide: true, shell: false },
|
||||
);
|
||||
child.unref();
|
||||
return { pending: true };
|
||||
}
|
||||
|
||||
/** 等当前桌面进程退出后把 app.asar 挪走,再启动 exe。解开后的 resources\\app 才会被加载。 */
|
||||
export function scheduleAsarSwapRestart({ exe, asar, waitPid = process.pid, exit = false } = {}) {
|
||||
if (!exe || !asar) throw new Error("缺少桌面 exe 或 app.asar,无法重启");
|
||||
const script = path.join(os.tmpdir(), `dsh-purge-asar-swap-${process.pid}.ps1`);
|
||||
fs.writeFileSync(script, ASAR_SWAP_PS1, "utf8");
|
||||
const child = spawn(
|
||||
"powershell.exe",
|
||||
[
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
script,
|
||||
"-WaitPid",
|
||||
String(waitPid),
|
||||
"-AsarPath",
|
||||
asar,
|
||||
"-ExePath",
|
||||
exe,
|
||||
],
|
||||
{ detached: true, stdio: "ignore", windowsHide: true, shell: false },
|
||||
);
|
||||
child.unref();
|
||||
if (exit !== false) setTimeout(() => process.exit(0), 800);
|
||||
return { scheduled: true };
|
||||
}
|
||||
|
||||
function officialExeFromProcess() {
|
||||
if (isOfficialHarnessExecutable(process.execPath)) return path.normalize(process.execPath);
|
||||
const resources = process.resourcesPath;
|
||||
if (!resources) return "";
|
||||
const beside = path.join(path.dirname(resources), "DeepSeek Harness.exe");
|
||||
return fs.existsSync(beside) ? beside : "";
|
||||
}
|
||||
|
||||
export function scheduleRestart(request, ctx) {
|
||||
if (officialExeFromProcess()) return restartOfficialHarness();
|
||||
const runtime = desktopRuntimeOf(ctx);
|
||||
if (runtime) {
|
||||
// 只走桌面整应用 relaunch,不要 exit Host(那会先把内嵌 web 单独拉起来)。
|
||||
@@ -433,6 +711,64 @@ export function scheduleRestart(request, ctx) {
|
||||
spawnHelper(helper, { respawn: true, killApp: true }, { exit: false });
|
||||
}
|
||||
|
||||
function jsString(value) {
|
||||
return JSON.stringify(String(value || ""));
|
||||
}
|
||||
|
||||
function officialRestartScript(exe, asar) {
|
||||
const log = path.join(os.tmpdir(), "dsh-purge-official-restart.log");
|
||||
return [
|
||||
"var exe = " + jsString(exe) + ";",
|
||||
"var asar = " + jsString(asar) + ";",
|
||||
"var logPath = " + jsString(log) + ";",
|
||||
"var fso = new ActiveXObject('Scripting.FileSystemObject');",
|
||||
"var sh = new ActiveXObject('WScript.Shell');",
|
||||
"var wmi = GetObject('winmgmts:\\\\\\\\.\\\\root\\\\cimv2');",
|
||||
"function z(n) { return (n < 10 ? '0' : '') + n; }",
|
||||
"function stamp() { var d = new Date(); return d.getFullYear() + '-' + z(d.getMonth() + 1) + '-' + z(d.getDate()) + 'T' + z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds()); }",
|
||||
"function log(m) { var f = fso.OpenTextFile(logPath, 8, true); f.WriteLine(stamp() + ' ' + m); f.Close(); }",
|
||||
"function samePath(a, b) { return String(a || '').toLowerCase() === String(b || '').toLowerCase(); }",
|
||||
"function pids() { var out = []; var e = new Enumerator(wmi.ExecQuery(\"SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE Name = 'DeepSeek Harness.exe'\")); for (; !e.atEnd(); e.moveNext()) { var p = e.item(); if (samePath(p.ExecutablePath, exe)) out.push(p.ProcessId); } return out; }",
|
||||
"log('begin');",
|
||||
"WScript.Sleep(800);",
|
||||
"var list = pids();",
|
||||
"log('pids ' + list.join(','));",
|
||||
"for (var i = 0; i < list.length; i++) sh.Run('taskkill.exe /F /PID ' + list[i], 0, true);",
|
||||
"var deadline = new Date().getTime() + 20000;",
|
||||
"var left = list;",
|
||||
"while (new Date().getTime() < deadline) { left = pids(); if (left.length === 0) break; WScript.Sleep(200); }",
|
||||
"log('left ' + left.length);",
|
||||
"var unpacked = asar + '.unpacked';",
|
||||
"var appDir = asar.replace(/app\\.asar$/i, 'app');",
|
||||
"var marker = appDir + '\\\\dsh\\\\node_modules\\\\node-addon-require-builtin-win32-x64-msvc\\\\prebuilt\\\\win32-x64-msvc-napi-v9.node';",
|
||||
"if (fso.FolderExists(unpacked) && !fso.FileExists(marker)) { sh.Run('robocopy.exe \"' + unpacked + '\" \"' + appDir + '\" /E /XC /XN /XO /NFL /NDL /NJH /NJS /nc /ns /np', 0, true); log('overlay'); }",
|
||||
"if (fso.FileExists(asar)) { var bak = asar + '.bak'; if (fso.FileExists(bak)) fso.DeleteFile(bak, true); for (var n = 0; n < 40; n++) { try { fso.MoveFile(asar, bak); log('renamed'); break; } catch (err) { log(err && err.message ? err.message : String(err)); WScript.Sleep(250); } } }",
|
||||
"try { sh.Environment('PROCESS').Remove('ELECTRON_RUN_AS_NODE'); } catch (ignore) {}",
|
||||
"sh.Run('\"' + exe + '\"', 1, false);",
|
||||
"log('started');",
|
||||
"",
|
||||
].join("\r\n");
|
||||
}
|
||||
|
||||
/** 点「重启」后结束当前官方客户端,挪开被占用的 app.asar,再自己打开。 */
|
||||
export function restartOfficialHarness() {
|
||||
const exe = officialExeFromProcess();
|
||||
if (!exe) return { restarting: false };
|
||||
const asar = path.join(path.dirname(exe), "resources", "app.asar");
|
||||
const script = path.join(os.tmpdir(), "dsh-purge-official-restart.js");
|
||||
const launcher = path.join(os.tmpdir(), "dsh-purge-official-restart.cmd");
|
||||
fs.writeFileSync(script, officialRestartScript(exe, asar), "utf8");
|
||||
fs.writeFileSync(launcher, `@echo off\r\nstart "" wscript.exe //nologo //B "${script}"\r\n`, "utf8");
|
||||
const child = spawn("cmd.exe", ["/d", "/c", launcher], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
});
|
||||
child.unref();
|
||||
return { restarting: true };
|
||||
}
|
||||
|
||||
export function scheduleCleanupRestart({ cleanup = [], ctx } = {}) {
|
||||
const src = fileURLToPath(new URL("./restart-desktop.js", import.meta.url));
|
||||
const dest = path.join(os.tmpdir(), `dsh-purge-uninst-${process.pid}.mjs`);
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
/** Electron 会把 app.asar 伪装成目录。读归档必须走 original-fs,否则 isFile 为假、解不开。 */
|
||||
function archiveFs() {
|
||||
process.noDeprecation = true;
|
||||
try {
|
||||
return createRequire(import.meta.url)("original-fs");
|
||||
} catch {
|
||||
return fs;
|
||||
}
|
||||
}
|
||||
|
||||
function renameBusy(error) {
|
||||
const code = error && error.code;
|
||||
return code === "EBUSY" || code === "EPERM" || code === "EACCES";
|
||||
}
|
||||
|
||||
export function renameAsarAside(asarPath) {
|
||||
const afs = archiveFs();
|
||||
if (!asarPath || !afs.existsSync(asarPath)) return { renamed: false };
|
||||
const bak = `${asarPath}.bak`;
|
||||
try {
|
||||
if (afs.existsSync(bak)) afs.rmSync(bak, { force: true });
|
||||
afs.renameSync(asarPath, bak);
|
||||
return { renamed: true, bak };
|
||||
} catch (error) {
|
||||
if (renameBusy(error)) return { renamed: false, busy: true, bak };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function asarArchiveIsFile(p) {
|
||||
try {
|
||||
const afs = archiveFs();
|
||||
return Boolean(p) && afs.existsSync(p) && afs.statSync(p).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function readHeader(fd, afs) {
|
||||
const pre = Buffer.alloc(16);
|
||||
if (afs.readSync(fd, pre, 0, 16, 0) !== 16) throw new Error("asar header truncated");
|
||||
if (pre.readUInt32LE(0) !== 4) throw new Error("not an asar archive");
|
||||
const headerSize = pre.readUInt32LE(4);
|
||||
const jsonSize = pre.readUInt32LE(12);
|
||||
if (!headerSize || !jsonSize || jsonSize > 256 * 1024 * 1024) throw new Error("asar header size invalid");
|
||||
const jsonBuf = Buffer.alloc(jsonSize);
|
||||
if (afs.readSync(fd, jsonBuf, 0, jsonSize, 16) !== jsonSize) throw new Error("asar header short");
|
||||
return {
|
||||
header: JSON.parse(jsonBuf.toString("utf8")),
|
||||
dataOffset: 8 + headerSize,
|
||||
};
|
||||
}
|
||||
|
||||
function walk(node, prefix, out) {
|
||||
const files = node && node.files;
|
||||
if (!files) return;
|
||||
for (const [name, info] of Object.entries(files)) {
|
||||
const rel = prefix ? `${prefix}/${name}` : name;
|
||||
if (info && info.files) walk(info, rel, out);
|
||||
else if (info) out.push({ rel, info });
|
||||
}
|
||||
}
|
||||
|
||||
export function listAsarEntries(asarPath) {
|
||||
const afs = archiveFs();
|
||||
const fd = afs.openSync(asarPath, "r");
|
||||
try {
|
||||
const { header } = readHeader(fd, afs);
|
||||
const out = [];
|
||||
walk(header, "", out);
|
||||
return out;
|
||||
} finally {
|
||||
afs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
function copyRange(afs, fd, offset, size, outPath) {
|
||||
const out = fs.openSync(outPath, "w");
|
||||
try {
|
||||
const buf = Buffer.alloc(Math.min(1024 * 1024, Math.max(size, 1)));
|
||||
let left = size;
|
||||
let pos = offset;
|
||||
while (left > 0) {
|
||||
const n = afs.readSync(fd, buf, 0, Math.min(buf.length, left), pos);
|
||||
if (n <= 0) throw new Error(`asar short read at ${outPath}`);
|
||||
fs.writeSync(out, buf, 0, n);
|
||||
pos += n;
|
||||
left -= n;
|
||||
}
|
||||
} finally {
|
||||
fs.closeSync(out);
|
||||
}
|
||||
}
|
||||
|
||||
/** asar 里标记 unpacked 的原生文件不在归档正文。解开目录启动前必须补到 resources/app。 */
|
||||
export function overlayAsarUnpacked(asarPath, destDir) {
|
||||
const unpacked = `${asarPath}.unpacked`;
|
||||
if (!destDir || !fs.existsSync(unpacked)) return { copied: 0, missing: true };
|
||||
let copied = 0;
|
||||
const walk = (dir) => {
|
||||
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const from = path.join(dir, ent.name);
|
||||
const to = path.join(destDir, path.relative(unpacked, from));
|
||||
if (ent.isDirectory()) {
|
||||
fs.mkdirSync(to, { recursive: true });
|
||||
walk(from);
|
||||
} else if (ent.isFile()) {
|
||||
if (fs.existsSync(to)) continue;
|
||||
fs.mkdirSync(path.dirname(to), { recursive: true });
|
||||
fs.copyFileSync(from, to);
|
||||
copied += 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(unpacked);
|
||||
return { copied };
|
||||
}
|
||||
|
||||
export function extractAsar(asarPath, destDir) {
|
||||
const afs = archiveFs();
|
||||
const fd = afs.openSync(asarPath, "r");
|
||||
let count = 0;
|
||||
try {
|
||||
const { header, dataOffset } = readHeader(fd, afs);
|
||||
const entries = [];
|
||||
walk(header, "", entries);
|
||||
fs.mkdirSync(destDir, { recursive: true });
|
||||
for (const entry of entries) {
|
||||
const info = entry.info;
|
||||
const outPath = path.join(destDir, ...entry.rel.split("/"));
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
if (info.unpacked) continue;
|
||||
if (typeof info.link === "string") {
|
||||
try {
|
||||
fs.symlinkSync(info.link, outPath);
|
||||
} catch {
|
||||
// 不能建链接就跳过,主程序文件仍在归档里
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const size = Number(info.size || 0);
|
||||
const offset = dataOffset + Number(info.offset || 0);
|
||||
if (size === 0) {
|
||||
fs.writeFileSync(outPath, Buffer.alloc(0));
|
||||
} else {
|
||||
copyRange(afs, fd, offset, size, outPath);
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
} finally {
|
||||
afs.closeSync(fd);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
+5
-1
@@ -2,6 +2,7 @@ import { createRequire, registerHooks } from "node:module";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import { isAsarSealedPath } from "./desktop.js";
|
||||
|
||||
const MARK = "__dshPurgeHideConsole";
|
||||
const IMPORT_MARK = "dsh-purge-hide-console";
|
||||
@@ -196,7 +197,9 @@ export function resolveDshBinRoot(hint, { fs, path: nodePath } = {}) {
|
||||
}
|
||||
for (const root of tries) {
|
||||
try {
|
||||
if (nodeFs.existsSync(p.join(root, "lib", "bin.js"))) return p.normalize(root);
|
||||
const binJs = p.join(root, "lib", "bin.js");
|
||||
if (isAsarSealedPath(root) || isAsarSealedPath(binJs)) continue;
|
||||
if (nodeFs.existsSync(binJs)) return p.normalize(root);
|
||||
} catch {}
|
||||
}
|
||||
return null;
|
||||
@@ -213,6 +216,7 @@ export function installHideConsoleIntoBin(aiBase, { fs, path: nodePath } = {}) {
|
||||
const binJs = p.join(root, "lib", "bin.js");
|
||||
const side = p.join(root, "lib", `${IMPORT_MARK}.js`);
|
||||
const facadeSide = p.join(root, "lib", "dsh-purge-child-process-hide.mjs");
|
||||
if (isAsarSealedPath(root) || isAsarSealedPath(binJs)) return "sealed_asar";
|
||||
|
||||
const facadeSrc = nodeFs.readFileSync(
|
||||
fileURLToPath(new URL("./child-process-hide.mjs", import.meta.url)),
|
||||
|
||||
+91
-12
@@ -5,6 +5,7 @@ import * as hostctl from "./host.js";
|
||||
import * as rules from "./rules.js";
|
||||
import * as skills from "./skills.js";
|
||||
import * as updater from "./update.js";
|
||||
import * as reapply from "./reapply.js";
|
||||
import {
|
||||
GLOBAL_PROMPT_ORDER,
|
||||
isMnemonPluginMessage,
|
||||
@@ -18,6 +19,8 @@ export const name = "dsh-purge";
|
||||
|
||||
export const inject = ["systemPrompt", "tools"];
|
||||
|
||||
let bootFullQuit = false;
|
||||
|
||||
const DEFAULTS = {
|
||||
enabled: true,
|
||||
autoApplyOnStart: true,
|
||||
@@ -268,6 +271,44 @@ function shimNeedsPatch(state) {
|
||||
);
|
||||
}
|
||||
|
||||
async function settleInstalledPatches(config, ctx) {
|
||||
if (!reapply.patchesMatchInstall()) {
|
||||
const result = await reapply.reapplyInstalled();
|
||||
if (!result.ok) {
|
||||
log(config, "reapply failed:", result.error || "");
|
||||
return "reapply-failed";
|
||||
}
|
||||
if (result.needsFullQuit) {
|
||||
bootFullQuit = true;
|
||||
log(config, "reapply wrote patches; official host needs a full quit");
|
||||
return "full-quit";
|
||||
}
|
||||
log(config, "reapply wrote patches; restarting");
|
||||
try {
|
||||
hostctl.scheduleRestart(null, ctx);
|
||||
} catch (e) {
|
||||
log(config, "restart after reapply failed:", String(e && e.message ? e.message : e));
|
||||
return "restart-failed";
|
||||
}
|
||||
return "restarting";
|
||||
}
|
||||
const applied = await autoApply(config);
|
||||
if (config.autoUpdateOnStart !== false) {
|
||||
updater.autoUpdateIfNeeded()
|
||||
.then((r) => {
|
||||
log(config, "auto-update:", JSON.stringify(r));
|
||||
if (r && r.needsFullQuit) bootFullQuit = true;
|
||||
if (r && r.restartAfter) {
|
||||
try { hostctl.scheduleRestart(null, ctx); } catch (e) {
|
||||
console.warn("[dsh-purge] auto-update restart failed:", e);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((e) => console.warn("[dsh-purge] auto-update error:", String(e)));
|
||||
}
|
||||
return applied;
|
||||
}
|
||||
|
||||
async function autoApply(config) {
|
||||
try {
|
||||
core.applyRuntimeEnv();
|
||||
@@ -330,8 +371,14 @@ async function handlePurgeCommand(rawInput, config) {
|
||||
core.applyRuntimeEnv();
|
||||
const scrubbed = core.sanitizeDesktopCommandRuntimes();
|
||||
const state = await core.gatherState();
|
||||
let handoff = null;
|
||||
if (!state.ai_base) {
|
||||
return { kind: "error", text: core.missingAiBaseMessage() };
|
||||
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 };
|
||||
@@ -354,6 +401,12 @@ async function handlePurgeCommand(rawInput, config) {
|
||||
}
|
||||
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("", "补丁已写入。请在设置页点「重启」,客户端会自己重新打开。");
|
||||
}
|
||||
}
|
||||
return { kind: "success", text: lines.join("\n") };
|
||||
}
|
||||
case "revert":
|
||||
@@ -655,15 +708,12 @@ export function apply(ctx, config) {
|
||||
}
|
||||
|
||||
setImmediate(() => {
|
||||
autoApply(cfg).then((r) => log(cfg, "auto-apply:", r));
|
||||
settleInstalledPatches(cfg, ctx)
|
||||
.then((r) => log(cfg, "settle:", r))
|
||||
.catch((e) => console.warn("[dsh-purge] settle error:", String(e)));
|
||||
rules.ensureInitialState(core.findDshHome())
|
||||
.then((r) => log(cfg, "rules init:", JSON.stringify(r)))
|
||||
.catch((e) => console.warn("[dsh-purge] rules init error:", String(e)));
|
||||
if (cfg.autoUpdateOnStart !== false) {
|
||||
updater.autoUpdateIfNeeded()
|
||||
.then((r) => log(cfg, "auto-update:", JSON.stringify(r)))
|
||||
.catch((e) => console.warn("[dsh-purge] auto-update error:", String(e)));
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -923,6 +973,7 @@ function installWebServer(ctx, cfg) {
|
||||
override_path: state.override_path,
|
||||
dsh_home: state.dsh_home,
|
||||
plugin_version: updater.localVersion(),
|
||||
boot_full_quit: bootFullQuit,
|
||||
update: updater.lastUpdateResult(),
|
||||
...updater.channelPublic(),
|
||||
...(await skills.skillsStatus(core.findDshHome()).catch(() => ({ skills: [] }))),
|
||||
@@ -1090,7 +1141,14 @@ function installWebServer(ctx, cfg) {
|
||||
if (request.method === "POST") {
|
||||
try {
|
||||
const body = await readJsonBody(request);
|
||||
sendJson(response, 200, await updater.handleUpdateOp(body || {}));
|
||||
const result = await updater.handleUpdateOp(body || {});
|
||||
if (result && result.needsFullQuit) bootFullQuit = true;
|
||||
sendJson(response, 200, result);
|
||||
if (result && result.restartAfter) {
|
||||
try { hostctl.scheduleRestart(request, ctx); } catch (e) {
|
||||
console.warn("[dsh-purge] update restart failed:", e);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
@@ -1113,9 +1171,17 @@ function installWebServer(ctx, cfg) {
|
||||
core.applyRuntimeEnv();
|
||||
const scrubbed = core.sanitizeDesktopCommandRuntimes();
|
||||
const state = await core.gatherState();
|
||||
let handoff = null;
|
||||
if (!state.ai_base) {
|
||||
sendJson(response, 500, { ok: false, error: core.missingAiBaseMessage() });
|
||||
return;
|
||||
const opened = await core.openSealedDesktopHost();
|
||||
if (!opened.aiBase) {
|
||||
sendJson(response, 500, { ok: false, error: core.missingAiBaseMessage() });
|
||||
return;
|
||||
}
|
||||
state.ai_base = opened.aiBase;
|
||||
if (opened.swapAsar) handoff = opened;
|
||||
} else {
|
||||
handoff = core.sealedAsarHandoff();
|
||||
}
|
||||
const body = await readJsonBody(request);
|
||||
const ui = await core.readOverrideForUi(state.dsh_home);
|
||||
@@ -1141,9 +1207,20 @@ 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) {
|
||||
const swapped = core.scheduleSealedDesktopRestart(handoff);
|
||||
renamed = Boolean(swapped?.renamed);
|
||||
pendingQuit = Boolean(swapped?.pending);
|
||||
}
|
||||
const leaveTray = renamed || pendingQuit;
|
||||
sendJson(response, 200, {
|
||||
ok: true,
|
||||
complete,
|
||||
restarting: false,
|
||||
unpacked_asar: leaveTray,
|
||||
needs_full_quit: leaveTray,
|
||||
applied: summary.applied,
|
||||
already: summary.already,
|
||||
failed: summary.failed.length,
|
||||
@@ -1276,12 +1353,14 @@ function installWebServer(ctx, cfg) {
|
||||
}
|
||||
try {
|
||||
const surface = hostctl.currentSurface();
|
||||
hostctl.scheduleRestart(request, ctx);
|
||||
const planned = hostctl.scheduleRestart(request, ctx);
|
||||
sendJson(response, 200, {
|
||||
ok: true,
|
||||
surface,
|
||||
fullApp: surface === "desktop",
|
||||
note: hostctl.restartNote(),
|
||||
restarting: Boolean(planned && planned.restarting),
|
||||
needsFullQuit: false,
|
||||
note: "正在重启。",
|
||||
});
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { reapplyInstalled } from "./reapply.js";
|
||||
|
||||
const result = await reapplyInstalled();
|
||||
process.stdout.write(`${JSON.stringify(result)}\n`);
|
||||
process.exit(result.ok ? 0 : 1);
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as core from "./core.js";
|
||||
|
||||
const PLUGIN_ROOT = path.resolve(fileURLToPath(new URL(".", import.meta.url)), "..");
|
||||
|
||||
function pluginVersion() {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(PLUGIN_ROOT, "package.json"), "utf8"));
|
||||
return String(pkg.version || "");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function installedRev() {
|
||||
try {
|
||||
return fs.readFileSync(path.join(core.findDshHome(), "dsh-purge", "installed-rev"), "utf8").trim();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function appliedStampPath() {
|
||||
return path.join(core.findDshHome(), "dsh-purge", "applied.json");
|
||||
}
|
||||
|
||||
export function readAppliedStamp() {
|
||||
try {
|
||||
const raw = JSON.parse(fs.readFileSync(appliedStampPath(), "utf8"));
|
||||
return {
|
||||
version: String(raw.version || ""),
|
||||
sha: String(raw.sha || ""),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function sameRev(a, b) {
|
||||
if (!a || !b) return false;
|
||||
return a === b || a.startsWith(b) || b.startsWith(a);
|
||||
}
|
||||
|
||||
/** 当前插件版本和已写入补丁的版本一致时,启动不必再还原重打。 */
|
||||
export function stampMatches(stamp, version, rev) {
|
||||
if (!stamp || !stamp.version || stamp.version !== version) return false;
|
||||
if (rev && stamp.sha && !sameRev(rev, stamp.sha)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function patchesMatchInstall() {
|
||||
return stampMatches(readAppliedStamp(), pluginVersion(), installedRev());
|
||||
}
|
||||
|
||||
function writeAppliedStamp(sha) {
|
||||
const fp = appliedStampPath();
|
||||
fs.mkdirSync(path.dirname(fp), { recursive: true });
|
||||
fs.writeFileSync(fp, `${JSON.stringify({
|
||||
version: pluginVersion(),
|
||||
sha: sha || "",
|
||||
at: new Date().toISOString(),
|
||||
}, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 先把宿主文件从备份还原,再按当前这份插件的补丁重写。
|
||||
* 低版本带着自己的补丁列表,高版本带着自己的;回退到哪一版就打哪一版。
|
||||
*/
|
||||
export async function reapplyInstalled() {
|
||||
core.applyRuntimeEnv();
|
||||
let aiBase = null;
|
||||
let handoff = null;
|
||||
try {
|
||||
const state = await core.gatherState();
|
||||
aiBase = state.ai_base;
|
||||
} catch (e) {
|
||||
return { ok: false, error: String(e && e.message ? e.message : e) };
|
||||
}
|
||||
if (!aiBase) {
|
||||
try {
|
||||
const opened = await core.openSealedDesktopHost();
|
||||
aiBase = opened.aiBase;
|
||||
if (opened.swapAsar) handoff = opened;
|
||||
} catch (e) {
|
||||
return { ok: false, error: String(e && e.message ? e.message : e) };
|
||||
}
|
||||
} else {
|
||||
handoff = core.sealedAsarHandoff();
|
||||
}
|
||||
if (!aiBase) return { ok: false, error: core.missingAiBaseMessage() };
|
||||
const reverted = await core.revertAll(aiBase);
|
||||
await core.revertAllShims();
|
||||
await core.backupAll(aiBase);
|
||||
const report = await core.applyPatches(aiBase);
|
||||
await core.patchAllShims();
|
||||
const flash = core.silenceCmdFlash(aiBase);
|
||||
let renamed = false;
|
||||
if (handoff?.asar) {
|
||||
const swapped = core.scheduleSealedDesktopRestart(handoff);
|
||||
renamed = Boolean(swapped?.renamed);
|
||||
}
|
||||
const summary = core.summarizeApplyReport(report);
|
||||
writeAppliedStamp(installedRev());
|
||||
return {
|
||||
ok: true,
|
||||
version: pluginVersion(),
|
||||
reverted: reverted.reverted?.length || 0,
|
||||
applied: summary.applied || 0,
|
||||
failed: summary.failed.length,
|
||||
renamed,
|
||||
needsFullQuit: renamed || core.officialHostMustStayUp(),
|
||||
cmdFlashOk: flash.ok === true,
|
||||
};
|
||||
}
|
||||
+23
-14
@@ -55,24 +55,33 @@ function rmTree(dir) {
|
||||
}
|
||||
}
|
||||
|
||||
function pidsForImage(image) {
|
||||
const out = execFileSync("tasklist", ["/FI", `IMAGENAME eq ${image}`, "/FO", "CSV", "/NH"], {
|
||||
encoding: "utf8",
|
||||
windowsHide: true,
|
||||
timeout: 8000,
|
||||
});
|
||||
const pids = [];
|
||||
for (const line of String(out || "").split(/\r?\n/)) {
|
||||
const cols = line.split(",");
|
||||
const pid = Number(String(cols[1] || "").replace(/"/g, "").trim());
|
||||
if (pid) pids.push(pid);
|
||||
}
|
||||
return pids;
|
||||
}
|
||||
|
||||
function listDesktopPids() {
|
||||
if (process.platform !== "win32") return [];
|
||||
try {
|
||||
const out = execFileSync("tasklist", ["/FI", "IMAGENAME eq DSH Desktop.exe", "/FO", "CSV", "/NH"], {
|
||||
encoding: "utf8",
|
||||
windowsHide: true,
|
||||
timeout: 8000,
|
||||
});
|
||||
const pids = [];
|
||||
for (const line of String(out || "").split(/\r?\n/)) {
|
||||
const cols = line.split(",");
|
||||
const pid = Number(String(cols[1] || "").replace(/"/g, "").trim());
|
||||
if (pid) pids.push(pid);
|
||||
const images = ["DeepSeek Harness.exe", "DSH Desktop.exe"];
|
||||
const pids = [];
|
||||
for (const image of images) {
|
||||
try {
|
||||
pids.push(...pidsForImage(image));
|
||||
} catch {
|
||||
// 该进程名不存在
|
||||
}
|
||||
return pids;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return pids;
|
||||
}
|
||||
|
||||
function killOtherDesktopProcesses(keepPid) {
|
||||
|
||||
+9
-1
@@ -23,7 +23,10 @@ export function pathLooksDesktop(p) {
|
||||
n.includes("/dsh desktop.app/") ||
|
||||
n.includes("dsh-desktop") ||
|
||||
n.includes("dsh-plugin-desktop") ||
|
||||
n.includes("/deepseek harness/") ||
|
||||
n.includes("deepseek-harness") ||
|
||||
/\/dsh desktop\.exe$/i.test(n) ||
|
||||
/\/deepseek harness\.exe$/i.test(n) ||
|
||||
n.endsWith("/host-process-entry.js") ||
|
||||
n.endsWith("/desktop-cli.js")
|
||||
);
|
||||
@@ -37,7 +40,12 @@ export function isDesktopSurface(input = {}) {
|
||||
|
||||
const execPath = input.execPath ?? process.execPath;
|
||||
const name = exeName(execPath);
|
||||
if (name === "dsh desktop.exe" || name === "dsh desktop") return true;
|
||||
if (
|
||||
name === "dsh desktop.exe" ||
|
||||
name === "dsh desktop" ||
|
||||
name === "deepseek harness.exe" ||
|
||||
name === "deepseek-harness.exe"
|
||||
) return true;
|
||||
if (pathLooksDesktop(execPath)) return true;
|
||||
|
||||
const resourcesPath = input.resourcesPath ?? process.resourcesPath;
|
||||
|
||||
+49
-3
@@ -1,4 +1,4 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import { promises as fsp } from "node:fs";
|
||||
import os from "node:os";
|
||||
@@ -875,6 +875,45 @@ async function overlayFromZip(dests, ref = STABLE_REF) {
|
||||
}
|
||||
}
|
||||
|
||||
function parseReapplyOutput(text) {
|
||||
const line = String(text || "")
|
||||
.split(/\r?\n/)
|
||||
.map((item) => item.trim())
|
||||
.filter((item) => item.startsWith("{"))
|
||||
.pop();
|
||||
if (!line) return null;
|
||||
try {
|
||||
return JSON.parse(line);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 用刚写好的插件文件在新进程里还原并重打,避免还在跑旧补丁列表。 */
|
||||
function runReapplyChild() {
|
||||
const cli = path.join(PLUGIN_ROOT, "lib", "reapply-cli.js");
|
||||
if (!fs.existsSync(cli)) return { ok: false, error: "缺少重新应用脚本" };
|
||||
const env = { ...process.env, ELECTRON_RUN_AS_NODE: "1" };
|
||||
delete env.DSH_PURGE_RESTART;
|
||||
let run;
|
||||
try {
|
||||
run = spawnSync(process.execPath, ["--expose-internals", cli], {
|
||||
cwd: PLUGIN_ROOT,
|
||||
env,
|
||||
encoding: "utf8",
|
||||
windowsHide: true,
|
||||
timeout: 180000,
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
});
|
||||
} catch (e) {
|
||||
return { ok: false, error: String(e && e.message ? e.message : e) };
|
||||
}
|
||||
const parsed = parseReapplyOutput(`${run.stdout || ""}\n${run.stderr || ""}`);
|
||||
if (parsed) return parsed;
|
||||
const detail = String(run.stderr || run.stdout || (run.error && run.error.message) || "重新应用失败").trim();
|
||||
return { ok: false, error: detail.slice(0, 500) || "重新应用失败" };
|
||||
}
|
||||
|
||||
export async function applyUpdate(jobs = planUpdates(), options = {}) {
|
||||
if (!Array.isArray(jobs)) {
|
||||
options = jobs && typeof jobs === "object" ? jobs : {};
|
||||
@@ -930,8 +969,11 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) {
|
||||
at: new Date().toISOString(),
|
||||
});
|
||||
const listed = await listRemoteVersions().catch(() => ({ versions: [], hasBeta: saved.channel === "beta" }));
|
||||
const reapplied = runReapplyChild();
|
||||
const restartAfter = reapplied.ok === true && !reapplied.needsFullQuit;
|
||||
const needsFullQuit = reapplied.ok === true && Boolean(reapplied.needsFullQuit);
|
||||
return rememberUpdate({
|
||||
ok: true,
|
||||
ok: reapplied.ok !== false,
|
||||
applied: true,
|
||||
hasUpdate: false,
|
||||
hasBeta: listed.hasBeta,
|
||||
@@ -941,7 +983,11 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) {
|
||||
localSha: sha ? String(sha).slice(0, 7) : "",
|
||||
remoteSha: sha ? String(sha).slice(0, 7) : "",
|
||||
needRestart: false,
|
||||
reloadClient: true,
|
||||
reloadClient: !restartAfter && !needsFullQuit,
|
||||
restartAfter,
|
||||
needsFullQuit,
|
||||
reapplied: reapplied.ok === true,
|
||||
error: reapplied.ok === false ? `文件已更新,但还原并重新应用失败: ${reapplied.error || "未知错误"}` : undefined,
|
||||
via,
|
||||
versions: listed.versions,
|
||||
lanes: lanesOf(listed, saved, localVer, sha),
|
||||
|
||||
Reference in new issue
Block a user