mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 05:40:22 +08:00
feat: 发布 1.1.7,Web / 桌面端分开安装并跟随当前桌面目录清洗
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
2529db6088
commit
e84671d20a
14 files changed
+1370
-345
No files matched your search
+144
-83
@@ -12,6 +12,8 @@ import {
|
||||
resolveDshBinRoot,
|
||||
revertHideConsoleFromBin,
|
||||
} from "./hide-console.js";
|
||||
import * as desktop from "./desktop.js";
|
||||
import { adapterFor, detectSurface } from "./surface.js";
|
||||
|
||||
const isWindows = process.platform === "win32";
|
||||
const SHIM_NAMES = ["dsh.cmd", "dsh.ps1", "dsh"];
|
||||
@@ -251,27 +253,14 @@ export function dirHasDshLauncher(dir) {
|
||||
}
|
||||
|
||||
export function isDesktopCommandRuntimeDir(dir) {
|
||||
if (!dir) return false;
|
||||
const n = path.normalize(dir).replace(/\\/g, "/").toLowerCase();
|
||||
// host-commands/<profile>/bin
|
||||
if (n.includes("/host-commands/") && /(^|\/)bin\/?$/.test(n)) return true;
|
||||
// %APPDATA%/DSH Desktop/.../bin
|
||||
if (n.includes("/dsh desktop/") && /(^|\/)bin\/?$/.test(n)) return true;
|
||||
return false;
|
||||
return desktop.isSealedRuntimeDir(dir);
|
||||
}
|
||||
|
||||
export function listDesktopCommandRuntimeDirs() {
|
||||
const candidates = [...pathEnvDirs()];
|
||||
const appdata = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
|
||||
const root = path.join(appdata, "DSH Desktop", "host-commands");
|
||||
if (isDir(root)) {
|
||||
try {
|
||||
for (const ent of fs.readdirSync(root, { withFileTypes: true })) {
|
||||
if (ent.isDirectory()) candidates.push(path.join(root, ent.name, "bin"));
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
return collectDirs(candidates).filter(isDesktopCommandRuntimeDir);
|
||||
return collectDirs([
|
||||
...pathEnvDirs(),
|
||||
...desktop.listSealedRuntimeBins(),
|
||||
]).filter(isDesktopCommandRuntimeDir);
|
||||
}
|
||||
|
||||
function ensureDirSync(dir) {
|
||||
@@ -722,10 +711,41 @@ export function silenceLiangshenPhase1Strip(dshHome = findDshHome()) {
|
||||
return hit;
|
||||
}
|
||||
|
||||
function realNorm(fp) {
|
||||
if (!fp) return "";
|
||||
try {
|
||||
return fs.realpathSync(fp).replace(/\\/g, "/").toLowerCase();
|
||||
} catch {
|
||||
return path.resolve(fp).replace(/\\/g, "/").toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
export function pathZone(fp) {
|
||||
if (!fp) return "missing";
|
||||
const n = realNorm(fp);
|
||||
if (desktop.isInsideDesktopInstall(fp) || desktop.isInsideDesktopInstall(n)) return "desktop-install";
|
||||
if (/\/profiles\/desktop(\/|$)/.test(n)) return "desktop-profile";
|
||||
if (/\/profiles\/web(\/|$)/.test(n)) return "web-profile";
|
||||
if (n.includes("/npm-global")) return "web-install";
|
||||
return "shared";
|
||||
}
|
||||
|
||||
export function allowTargetPath(fp, surface = detectSurface()) {
|
||||
const zone = pathZone(fp);
|
||||
if (adapterFor(surface) === "desktop") {
|
||||
return zone === "desktop-install" || zone === "desktop-profile";
|
||||
}
|
||||
return zone !== "desktop-install" && zone !== "desktop-profile";
|
||||
}
|
||||
|
||||
function keepSurfaceFile(fp) {
|
||||
return fp && isFile(fp) && allowTargetPath(fp);
|
||||
}
|
||||
|
||||
function listLiangshenBootstrapFiles(dshHome) {
|
||||
const out = [];
|
||||
const push = (fp) => {
|
||||
if (fp && isFile(fp) && !out.includes(fp)) out.push(fp);
|
||||
if (keepSurfaceFile(fp) && !out.includes(fp)) out.push(fp);
|
||||
};
|
||||
const profilesRoot = path.join(dshHome, "profiles");
|
||||
push(path.join(profilesRoot, "web", "node_modules", "@linxin666", "dsh-liangshen", "presets", "liangshen", "tool-bootstrap.mjs"));
|
||||
@@ -811,7 +831,7 @@ export function silenceMnemonGitFlash(dshHome = findDshHome()) {
|
||||
function listMnemonIndexFiles(dshHome) {
|
||||
const out = [];
|
||||
const push = (fp) => {
|
||||
if (fp && isFile(fp) && !out.includes(fp)) out.push(fp);
|
||||
if (keepSurfaceFile(fp) && !out.includes(fp)) out.push(fp);
|
||||
};
|
||||
push(path.join(dshHome, "profiles", "web", "node_modules", "dsh-mnemon", "lib", "index.js"));
|
||||
push(path.join(dshHome, "profiles", "desktop", "node_modules", "dsh-mnemon", "lib", "index.js"));
|
||||
@@ -851,7 +871,7 @@ function listPiAiApiFiles(dshHome, aiBase, filename) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
const push = (fp) => {
|
||||
if (!fp || !isFile(fp)) return;
|
||||
if (!keepSurfaceFile(fp)) return;
|
||||
let key = fp;
|
||||
try { key = fs.realpathSync(fp); } catch { /* keep fp */ }
|
||||
key = String(key).toLowerCase();
|
||||
@@ -1403,6 +1423,7 @@ export function findShimDir() {
|
||||
}
|
||||
|
||||
export function listShimDirsForPatch() {
|
||||
if (adapterFor(detectSurface()) === "desktop") return [];
|
||||
return collectDirs([
|
||||
findShimDir(),
|
||||
...listDesktopCommandRuntimeDirs(),
|
||||
@@ -1413,21 +1434,61 @@ export function listShimDirsForPatch() {
|
||||
.filter((dir) => !isDesktopCommandRuntimeDir(dir));
|
||||
}
|
||||
|
||||
// Electron unpacked:app.asar.unpacked/node_modules/@deepseek-ai
|
||||
function findDesktopAiBase() {
|
||||
const candidates = [];
|
||||
if (typeof process.resourcesPath === "string" && process.resourcesPath.trim()) {
|
||||
candidates.push(path.join(process.resourcesPath, "app.asar.unpacked", "node_modules", "@deepseek-ai"));
|
||||
function findAiBaseDesktop() {
|
||||
const env = process.env.DSH_BASE;
|
||||
if (env && env.trim()) {
|
||||
const p = path.normalize(env.trim());
|
||||
if (isAiBase(p) && desktop.isInsideDesktopInstall(p)) return p;
|
||||
}
|
||||
const resolved = desktop.resolveDesktopAiBase();
|
||||
if (resolved) return resolved;
|
||||
const starts = [];
|
||||
if (process.argv[1]) {
|
||||
try { starts.push(path.resolve(process.argv[1])); } catch {}
|
||||
}
|
||||
if (process.resourcesPath) starts.push(path.normalize(process.resourcesPath));
|
||||
if (desktop.isDesktopExecutable(process.execPath)) starts.push(path.dirname(process.execPath));
|
||||
for (const start of starts) {
|
||||
try {
|
||||
const hit = walkAncestorsForAiBase(isDir(start) ? start : path.dirname(start));
|
||||
if (hit && desktop.isInsideDesktopInstall(hit)) return hit;
|
||||
} catch {}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function findAiBaseWeb() {
|
||||
const env = process.env.DSH_BASE;
|
||||
if (env && env.trim()) {
|
||||
const p = path.normalize(env.trim());
|
||||
if (isAiBase(p) && !desktop.isInsideDesktopInstall(p)) return p;
|
||||
}
|
||||
|
||||
// ELECTRON_RUN_AS_NODE 无稳定 resourcesPath,从 execPath 回推 Contents/Resources。
|
||||
const contentsDir = path.dirname(path.dirname(process.execPath));
|
||||
candidates.push(path.join(contentsDir, "Resources", "app.asar.unpacked", "node_modules", "@deepseek-ai"));
|
||||
const fromProcess = findAiBaseFromRunningProcess();
|
||||
if (fromProcess && !desktop.isInsideDesktopInstall(fromProcess)) return fromProcess;
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(path.join(candidate, "dsh-agent-instructions", "lib"))) {
|
||||
return path.normalize(candidate);
|
||||
}
|
||||
const fromHome = findAiBaseFromDshHome(findDshHome());
|
||||
if (fromHome && !desktop.isInsideDesktopInstall(fromHome)) return fromHome;
|
||||
|
||||
const nested = nestedAiPath();
|
||||
const prefix = findNpmPrefix();
|
||||
const shim = findShimDir();
|
||||
const search = [];
|
||||
for (const base of [prefix, ...launcherDirsOf(prefix), shim]) {
|
||||
search.push(...aiBaseGuessesFor(base));
|
||||
}
|
||||
for (const cand of search) {
|
||||
if (cand && isAiBase(cand) && !desktop.isInsideDesktopInstall(cand)) return path.normalize(cand);
|
||||
}
|
||||
const npmRoot = npmQuery(["root", "-g"]);
|
||||
for (const cand of [path.join(npmRoot, nested), path.join(npmRoot, "@deepseek-ai")]) {
|
||||
if (cand && isAiBase(cand) && !desktop.isInsideDesktopInstall(cand)) return path.normalize(cand);
|
||||
}
|
||||
|
||||
const needle = path.join("node_modules", nested);
|
||||
for (const sr of [findDshHome(), path.join(findDshHome(), ".."), os.homedir()]) {
|
||||
const found = findAiBaseRecursive(sr, needle, 0);
|
||||
if (found && !desktop.isInsideDesktopInstall(found)) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1444,47 +1505,20 @@ export function missingAiBaseMessage() {
|
||||
if (env.set && !env.valid) {
|
||||
return `DSH_BASE 已设置但不是有效的插件根(需要其下有 dsh-agent-instructions/lib): ${env.path}`;
|
||||
}
|
||||
if (adapterFor(detectSurface()) === "desktop") {
|
||||
const exe = desktop.findDesktopAppExecutable();
|
||||
if (exe) {
|
||||
return `已找到桌面应用 ${exe},但其 resources/app(或 app.asar.unpacked)下没有 @deepseek-ai`;
|
||||
}
|
||||
return "未定位到当前桌面应用的 @deepseek-ai。请在桌面端内打开设置再点「应用」(不要用官方 dsh)。安装目录可以是任意盘符;也可设置 DSH_DESKTOP_INSTALL 为安装目录,或 DSH_BASE 为该树下的 @deepseek-ai";
|
||||
}
|
||||
return "插件根未找到 / set DSH_BASE";
|
||||
}
|
||||
|
||||
export function findAiBase() {
|
||||
return remember("ai", () => {
|
||||
const env = process.env.DSH_BASE;
|
||||
if (env && env.trim()) {
|
||||
const p = path.normalize(env.trim());
|
||||
if (isAiBase(p)) return p;
|
||||
}
|
||||
|
||||
const fromProcess = findAiBaseFromRunningProcess();
|
||||
if (fromProcess) return fromProcess;
|
||||
|
||||
const fromHome = findAiBaseFromDshHome(findDshHome());
|
||||
if (fromHome) return fromHome;
|
||||
|
||||
const desktopBase = findDesktopAiBase();
|
||||
if (desktopBase) return desktopBase;
|
||||
|
||||
const nested = nestedAiPath();
|
||||
const prefix = findNpmPrefix();
|
||||
const shim = findShimDir();
|
||||
const search = [];
|
||||
for (const base of [prefix, ...launcherDirsOf(prefix), shim]) {
|
||||
search.push(...aiBaseGuessesFor(base));
|
||||
}
|
||||
for (const cand of search) {
|
||||
if (cand && isAiBase(cand)) return path.normalize(cand);
|
||||
}
|
||||
const npmRoot = npmQuery(["root", "-g"]);
|
||||
for (const cand of [path.join(npmRoot, nested), path.join(npmRoot, "@deepseek-ai")]) {
|
||||
if (cand && isAiBase(cand)) return path.normalize(cand);
|
||||
}
|
||||
|
||||
const needle = path.join("node_modules", nested);
|
||||
for (const sr of [findDshHome(), path.join(findDshHome(), ".."), os.homedir()]) {
|
||||
const found = findAiBaseRecursive(sr, needle, 0);
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
if (adapterFor(detectSurface()) === "desktop") return findAiBaseDesktop();
|
||||
return findAiBaseWeb();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2217,7 +2251,7 @@ const NEW_TOOL_PATCHES = [
|
||||
{
|
||||
id: 25, name: "PRESET_FETCH_ENABLED", layer: "代码", layer_en: "Code",
|
||||
desc: "preset tool-web fetch 打开 / preset fetch enabled",
|
||||
file: ["preset-unrestricted", "preset-standard", "preset-code", "preset-cordis", "preset-ptc"],
|
||||
file: ["preset-unrestricted", "preset-standard", "preset-cordis", "preset-ptc", "preset-liangshen", "preset-liangshen-pkg"],
|
||||
rel: ["agent.cordis.yml"],
|
||||
replacements: [
|
||||
{
|
||||
@@ -2248,7 +2282,6 @@ const NEW_TOOL_PATCHES = [
|
||||
"web-app",
|
||||
"headless",
|
||||
"preset-standard",
|
||||
"preset-code",
|
||||
"preset-cordis",
|
||||
"preset-unrestricted",
|
||||
"preset-ptc",
|
||||
@@ -3034,15 +3067,15 @@ function userPresetYml(dshHome, name) {
|
||||
}
|
||||
|
||||
function firstExisting(candidates) {
|
||||
return candidates.find((fp) => fp && fs.existsSync(fp)) ?? candidates[0];
|
||||
return candidates.find((fp) => fp && fs.existsSync(fp) && allowTargetPath(fp)) ?? "";
|
||||
}
|
||||
|
||||
function allExisting(candidates) {
|
||||
const hit = [];
|
||||
for (const fp of candidates) {
|
||||
if (fp && fs.existsSync(fp) && !hit.includes(fp)) hit.push(fp);
|
||||
if (fp && fs.existsSync(fp) && allowTargetPath(fp) && !hit.includes(fp)) hit.push(fp);
|
||||
}
|
||||
return hit.length ? hit : (candidates[0] ? [candidates[0]] : []);
|
||||
return hit;
|
||||
}
|
||||
|
||||
function pathsOf(files, key) {
|
||||
@@ -3157,9 +3190,26 @@ function removeWebFetchWorkspaceLinkIfUnused(aiBase) {
|
||||
}
|
||||
}
|
||||
|
||||
function filterTargetFiles(files) {
|
||||
const out = {};
|
||||
for (const [key, val] of Object.entries(files)) {
|
||||
if (Array.isArray(val)) {
|
||||
const kept = val.filter((fp) => !fp || !fs.existsSync(fp) || allowTargetPath(fp));
|
||||
const existing = kept.filter((fp) => fp && fs.existsSync(fp) && allowTargetPath(fp));
|
||||
out[key] = existing.length ? existing : [];
|
||||
} else if (val && fs.existsSync(val) && !allowTargetPath(val)) {
|
||||
out[key] = "";
|
||||
} else {
|
||||
out[key] = val;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function targetFiles(aiBase, dshHome = findDshHome()) {
|
||||
const root = packageRootFromAiBase(aiBase);
|
||||
return {
|
||||
const desktopHost = adapterFor(detectSurface()) === "desktop";
|
||||
const files = {
|
||||
"agent-instructions": firstExisting([
|
||||
path.join(aiBase, "dsh-agent-instructions", "lib", "index.js"),
|
||||
...(root ? [path.join(root, "packages", "context", "agent-instructions", "lib", "index.js")] : []),
|
||||
@@ -3178,11 +3228,17 @@ export function targetFiles(aiBase, dshHome = findDshHome()) {
|
||||
path.join(aiBase, "dsh-headless", "cordis.patch.yml"),
|
||||
...(root ? [path.join(root, "packages", "bundle", "headless", "cordis.patch.yml")] : []),
|
||||
]),
|
||||
"profile-web": firstExisting([
|
||||
path.join(dshHome, "profiles", "web", "cordis.patch.yml"),
|
||||
path.join(aiBase, "dsh-web-app", "cordis.patch.yml"),
|
||||
...(root ? [path.join(root, "packages", "bundle", "web-app", "cordis.patch.yml")] : []),
|
||||
]),
|
||||
"profile-web": firstExisting(desktopHost
|
||||
? [
|
||||
path.join(dshHome, "profiles", "desktop", "cordis.patch.yml"),
|
||||
path.join(aiBase, "dsh-web-app", "cordis.patch.yml"),
|
||||
...(root ? [path.join(root, "packages", "bundle", "web-app", "cordis.patch.yml")] : []),
|
||||
]
|
||||
: [
|
||||
path.join(dshHome, "profiles", "web", "cordis.patch.yml"),
|
||||
path.join(aiBase, "dsh-web-app", "cordis.patch.yml"),
|
||||
...(root ? [path.join(root, "packages", "bundle", "web-app", "cordis.patch.yml")] : []),
|
||||
]),
|
||||
"agent-preset": firstExisting([
|
||||
...userPresetYml(dshHome, "unrestricted"),
|
||||
...shippedPresetYml(root, "standard", aiBase),
|
||||
@@ -3250,7 +3306,6 @@ export function targetFiles(aiBase, dshHome = findDshHome()) {
|
||||
]),
|
||||
"preset-unrestricted": firstExisting(userPresetYml(dshHome, "unrestricted")),
|
||||
"preset-standard": allExisting(shippedPresetYml(root, "standard", aiBase)),
|
||||
"preset-code": allExisting(shippedPresetYml(root, "code", aiBase)),
|
||||
"preset-cordis": allExisting(shippedPresetYml(root, "cordis", aiBase)),
|
||||
"preset-minimal": allExisting(shippedPresetYml(root, "minimal", aiBase)),
|
||||
"preset-ptc": allExisting(shippedPresetYml(root, "ptc", aiBase)),
|
||||
@@ -3274,10 +3329,11 @@ export function targetFiles(aiBase, dshHome = findDshHome()) {
|
||||
...nestedPkg(aiBase, "dsh-tool-pwsh", "lib", "index.js"),
|
||||
...(root ? [path.join(root, "packages", "pwsh", "tool-pwsh", "lib", "index.js")] : []),
|
||||
]),
|
||||
"preset-liangshen": firstExisting(userPresetYml(dshHome, "liangshen")),
|
||||
"preset-liangshen-pkg": firstExisting([
|
||||
"preset-liangshen": allExisting(userPresetYml(dshHome, "liangshen")),
|
||||
"preset-liangshen-pkg": allExisting([
|
||||
path.join(dshHome, "profiles", "web", "node_modules", "@linxin666", "dsh-liangshen", "presets", "liangshen", "agent.cordis.yml"),
|
||||
path.join(dshHome, "profiles", "desktop", "node_modules", "@linxin666", "dsh-liangshen", "presets", "liangshen", "agent.cordis.yml"),
|
||||
path.join(dshHome, "profiles", "web", ".dsh-module-fallback", "node_modules", "@linxin666", "dsh-liangshen", "presets", "liangshen", "agent.cordis.yml"),
|
||||
path.join(dshHome, "profiles", "web", "node_modules", "@linxin666", "dsh-web-all", "node_modules", "@linxin666", "dsh-liangshen", "presets", "liangshen", "agent.cordis.yml"),
|
||||
]),
|
||||
"liangshen-tool-bootstrap": listLiangshenBootstrapFiles(dshHome),
|
||||
@@ -3320,6 +3376,7 @@ export function targetFiles(aiBase, dshHome = findDshHome()) {
|
||||
"pi-ai-completions": allExisting(listPiAiApiFiles(dshHome, aiBase, "openai-completions.js")),
|
||||
"pi-ai-responses-shared": allExisting(listPiAiApiFiles(dshHome, aiBase, "openai-responses-shared.js")),
|
||||
};
|
||||
return filterTargetFiles(files);
|
||||
}
|
||||
|
||||
function asLf(text) {
|
||||
@@ -4236,8 +4293,12 @@ export async function gatherState() {
|
||||
shim_bin = shimFileStatus(path.join(shimDir, "dsh"));
|
||||
}
|
||||
return {
|
||||
surface: detectSurface(),
|
||||
dsh_home: dshHome,
|
||||
ai_base: aiBase,
|
||||
desktop_install: adapterFor(detectSurface()) === "desktop"
|
||||
? (desktop.findDesktopAppExecutable() || desktop.listDesktopInstallRoots()[0] || "")
|
||||
: "",
|
||||
shim_dir: shimDir,
|
||||
desktop_runtimes,
|
||||
files,
|
||||
|
||||
+449
@@ -0,0 +1,449 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
function isFile(fp) {
|
||||
try {
|
||||
return Boolean(fp) && fs.existsSync(fp) && fs.statSync(fp).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isDir(fp) {
|
||||
try {
|
||||
return Boolean(fp) && fs.existsSync(fp) && fs.statSync(fp).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isAiBase(p) {
|
||||
return Boolean(p) && isDir(path.join(p, "dsh-agent-instructions", "lib"));
|
||||
}
|
||||
|
||||
function uniquePaths(list) {
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of list) {
|
||||
if (!item) continue;
|
||||
const n = path.normalize(item);
|
||||
const key = n.replace(/\\/g, "/").toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(n);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function slashNorm(p) {
|
||||
return path.normalize(String(p || "")).replace(/\\/g, "/").toLowerCase();
|
||||
}
|
||||
|
||||
function isSubPath(child, root) {
|
||||
const c = slashNorm(child).replace(/\/+$/, "");
|
||||
const r = slashNorm(root).replace(/\/+$/, "");
|
||||
if (!c || !r || r === "/") return false;
|
||||
if (/^[a-z]:$/.test(r)) return false;
|
||||
return c === r || c.startsWith(`${r}/`);
|
||||
}
|
||||
|
||||
/** 文件夹名带 DSH Desktop / dsh-desktop 时,任意盘符都算桌面安装树。 */
|
||||
export function looksLikeDesktopName(p) {
|
||||
const n = slashNorm(p);
|
||||
if (!n) return false;
|
||||
return (
|
||||
n.includes("/dsh desktop/") ||
|
||||
n.includes("/dsh desktop.app/") ||
|
||||
n.endsWith("/dsh desktop") ||
|
||||
n.endsWith("/dsh desktop.app") ||
|
||||
n.includes("dsh-desktop") ||
|
||||
/\/dsh desktop\.exe$/i.test(n)
|
||||
);
|
||||
}
|
||||
|
||||
export function isDesktopExecutable(fp) {
|
||||
const base = path.basename(String(fp || "")).toLowerCase();
|
||||
return base === "dsh desktop.exe" || base === "dsh desktop";
|
||||
}
|
||||
|
||||
function exeCandidatesBeside(dir) {
|
||||
if (!dir) return [];
|
||||
return [
|
||||
path.join(dir, "DSH Desktop.exe"),
|
||||
path.join(dir, "DSH Desktop"),
|
||||
path.join(dir, "MacOS", "DSH Desktop"),
|
||||
path.join(dir, "Contents", "MacOS", "DSH Desktop"),
|
||||
];
|
||||
}
|
||||
|
||||
function firstExistingExe(dirs) {
|
||||
for (const dir of dirs) {
|
||||
if (!dir) continue;
|
||||
for (const cand of exeCandidatesBeside(dir)) {
|
||||
if (isFile(cand)) return path.normalize(cand);
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
const APP_SCRIPT_RE = /(desktop-cli|host-process-entry)\.js$/i;
|
||||
|
||||
function installDirsFromAppScript(scriptPath) {
|
||||
if (!scriptPath) return [];
|
||||
const abs = path.resolve(scriptPath);
|
||||
const lib = path.dirname(abs);
|
||||
const app = path.dirname(lib);
|
||||
const resources = path.dirname(app);
|
||||
const install = path.dirname(resources);
|
||||
return uniquePaths([lib, app, resources, install]);
|
||||
}
|
||||
|
||||
/** 从任意 `.../resources/app/...` 树反推安装目录(不要求文件夹叫 DSH Desktop)。 */
|
||||
export function inferDesktopInstallDir(p) {
|
||||
const raw = path.normalize(String(p || "")).replace(/\\/g, "/");
|
||||
const n = raw.toLowerCase();
|
||||
if (!n) return "";
|
||||
const markers = [
|
||||
"/resources/app.asar.unpacked/",
|
||||
"/resources/app/",
|
||||
"/contents/resources/",
|
||||
];
|
||||
for (const marker of markers) {
|
||||
const i = n.indexOf(marker);
|
||||
if (i <= 0) continue;
|
||||
return path.normalize(raw.slice(0, i));
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function extraInstallsFromEnv(env = process.env) {
|
||||
return String(env.DSH_DESKTOP_INSTALL || "")
|
||||
.split(path.delimiter)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function trustedInstallDir(dir) {
|
||||
if (!dir) return false;
|
||||
if (looksLikeDesktopName(dir)) return true;
|
||||
if (firstExistingExe([dir])) return true;
|
||||
return (
|
||||
isAiBase(path.join(dir, "resources", "app", "node_modules", "@deepseek-ai")) ||
|
||||
isAiBase(path.join(dir, "resources", "app.asar.unpacked", "node_modules", "@deepseek-ai"))
|
||||
);
|
||||
}
|
||||
|
||||
/** 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)";
|
||||
return uniquePaths([
|
||||
...extraInstallsFromEnv(env).filter(trustedInstallDir),
|
||||
path.join(local, "Programs", "DSH Desktop"),
|
||||
path.join(pf, "DSH Desktop"),
|
||||
path.join(pf86, "DSH Desktop"),
|
||||
"/Applications/DSH Desktop.app",
|
||||
path.join(home, "Applications", "DSH Desktop.app"),
|
||||
]);
|
||||
}
|
||||
|
||||
export function listDesktopInstallRoots(input = {}) {
|
||||
const execPath = input.execPath ?? process.execPath;
|
||||
const resourcesPath = input.resourcesPath ?? process.resourcesPath;
|
||||
const argv = input.argv ?? process.argv;
|
||||
const env = input.env ?? process.env;
|
||||
const roots = [];
|
||||
|
||||
if (isDesktopExecutable(execPath)) {
|
||||
const dir = path.dirname(path.normalize(execPath));
|
||||
roots.push(dir);
|
||||
if (path.basename(dir) === "MacOS") {
|
||||
const contents = path.dirname(dir);
|
||||
roots.push(contents, path.join(contents, "Resources"), path.dirname(contents));
|
||||
}
|
||||
}
|
||||
|
||||
if (resourcesPath) {
|
||||
const res = path.normalize(resourcesPath);
|
||||
roots.push(res, path.dirname(res), path.join(res, "app"), path.join(res, "app.asar.unpacked"));
|
||||
}
|
||||
|
||||
for (const arg of argv) {
|
||||
if (typeof arg === "string" && APP_SCRIPT_RE.test(arg)) {
|
||||
roots.push(...installDirsFromAppScript(arg));
|
||||
}
|
||||
}
|
||||
|
||||
for (const extra of extraInstallsFromEnv(env)) {
|
||||
if (trustedInstallDir(extra)) roots.push(extra);
|
||||
}
|
||||
return uniquePaths(roots);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否落在社区 Desktop 安装树。
|
||||
* 不依赖盘符、也不要求文件夹叫 “DSH Desktop”:
|
||||
* 当前进程的 exe / resources / host-process-entry、旁边真有 DSH Desktop.exe、或名字启发式。
|
||||
*/
|
||||
export function isInsideDesktopInstall(p, input = {}) {
|
||||
if (!p) return false;
|
||||
if (looksLikeDesktopName(p)) return true;
|
||||
const roots = listDesktopInstallRoots(input);
|
||||
if (roots.some((root) => isSubPath(p, root))) return true;
|
||||
const inferred = inferDesktopInstallDir(p);
|
||||
if (!inferred) return false;
|
||||
if (roots.some((root) => isSubPath(inferred, root) || isSubPath(root, inferred))) return true;
|
||||
return Boolean(firstExistingExe([inferred]));
|
||||
}
|
||||
|
||||
export function findDesktopAppExecutable(input = {}) {
|
||||
const execPath = input.execPath ?? process.execPath;
|
||||
const resourcesPath = input.resourcesPath ?? process.resourcesPath;
|
||||
const argv = input.argv ?? process.argv;
|
||||
const env = input.env ?? process.env;
|
||||
|
||||
if (isDesktopExecutable(execPath) && isFile(execPath)) return path.normalize(execPath);
|
||||
|
||||
if (resourcesPath) {
|
||||
const hit = firstExistingExe([path.dirname(path.normalize(resourcesPath))]);
|
||||
if (hit) return hit;
|
||||
}
|
||||
|
||||
for (const arg of argv) {
|
||||
if (typeof arg !== "string" || !APP_SCRIPT_RE.test(arg)) continue;
|
||||
const hit = firstExistingExe(installDirsFromAppScript(arg));
|
||||
if (hit) return hit;
|
||||
}
|
||||
|
||||
const guessed = firstExistingExe([
|
||||
...extraInstallsFromEnv(env),
|
||||
...commonDesktopInstallDirs(env),
|
||||
]);
|
||||
return guessed || "";
|
||||
}
|
||||
|
||||
function packageRootsFromInstall(installDir) {
|
||||
if (!installDir) return [];
|
||||
const bases = [installDir];
|
||||
const name = path.basename(installDir);
|
||||
if (name === "MacOS") bases.push(path.join(path.dirname(installDir), "Resources"));
|
||||
if (name === "Contents") bases.push(path.join(installDir, "Resources"));
|
||||
if (name.toLowerCase().endsWith(".app")) bases.push(path.join(installDir, "Contents", "Resources"));
|
||||
const out = [];
|
||||
for (const base of bases) {
|
||||
out.push(
|
||||
path.join(base, "resources", "app", "node_modules", "@deepseek-ai"),
|
||||
path.join(base, "resources", "app.asar.unpacked", "node_modules", "@deepseek-ai"),
|
||||
path.join(base, "app", "node_modules", "@deepseek-ai"),
|
||||
path.join(base, "app.asar.unpacked", "node_modules", "@deepseek-ai"),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function listDesktopPackageRoots(input = {}) {
|
||||
const execPath = input.execPath ?? process.execPath;
|
||||
const resourcesPath = input.resourcesPath ?? process.resourcesPath;
|
||||
const argv = input.argv ?? process.argv;
|
||||
const env = input.env ?? process.env;
|
||||
const cands = [];
|
||||
|
||||
if (resourcesPath) {
|
||||
cands.push(
|
||||
path.join(resourcesPath, "app", "node_modules", "@deepseek-ai"),
|
||||
path.join(resourcesPath, "app.asar.unpacked", "node_modules", "@deepseek-ai"),
|
||||
);
|
||||
}
|
||||
|
||||
if (isDesktopExecutable(execPath)) {
|
||||
cands.push(...packageRootsFromInstall(path.dirname(execPath)));
|
||||
}
|
||||
|
||||
const exe = findDesktopAppExecutable(input);
|
||||
if (exe) cands.push(...packageRootsFromInstall(path.dirname(exe)));
|
||||
|
||||
for (const arg of argv) {
|
||||
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(...packageRootsFromInstall(path.dirname(path.dirname(appDir))));
|
||||
}
|
||||
|
||||
for (const install of commonDesktopInstallDirs(env)) {
|
||||
cands.push(...packageRootsFromInstall(install));
|
||||
}
|
||||
|
||||
return uniquePaths(cands).filter(isAiBase);
|
||||
}
|
||||
|
||||
export function resolveDesktopAiBase(input = {}) {
|
||||
return listDesktopPackageRoots(input)[0] || null;
|
||||
}
|
||||
|
||||
export function resolveDesktopCliScript(input = {}) {
|
||||
const exe = findDesktopAppExecutable(input);
|
||||
if (exe) {
|
||||
const install = path.dirname(exe);
|
||||
const packed = path.join(install, "resources", "app", "lib", "desktop-cli.js");
|
||||
if (isFile(packed)) return path.normalize(packed);
|
||||
const unpacked = path.join(install, "resources", "app.asar.unpacked", "lib", "desktop-cli.js");
|
||||
if (isFile(unpacked)) return path.normalize(unpacked);
|
||||
if (path.basename(install) === "MacOS") {
|
||||
const macPacked = path.join(path.dirname(install), "Resources", "app", "lib", "desktop-cli.js");
|
||||
if (isFile(macPacked)) return path.normalize(macPacked);
|
||||
}
|
||||
}
|
||||
for (const arg of input.argv ?? process.argv) {
|
||||
if (typeof arg === "string" && /desktop-cli\.js$/i.test(arg) && isFile(arg)) {
|
||||
return path.normalize(path.resolve(arg));
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function cliInvocation(input = {}) {
|
||||
const exe = findDesktopAppExecutable(input);
|
||||
const cli = resolveDesktopCliScript(input);
|
||||
if (!exe || !cli) return null;
|
||||
return {
|
||||
execPath: exe,
|
||||
argvPrefix: ["--expose-internals", cli],
|
||||
env: {
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
DSH_DESKTOP_DEFAULT_PROFILE: "desktop",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function isSealedRuntimeDir(dir) {
|
||||
if (!dir) return false;
|
||||
const n = path.normalize(dir).replace(/\\/g, "/").toLowerCase();
|
||||
if (!/(^|\/)bin\/?$/.test(n)) return false;
|
||||
return (
|
||||
n.includes("/host-commands/") ||
|
||||
n.includes("/runtime-commands/") ||
|
||||
n.includes("/dsh desktop/")
|
||||
);
|
||||
}
|
||||
|
||||
export function sealedRuntimeRoots(env = process.env) {
|
||||
const home = os.homedir();
|
||||
const appdata = env.APPDATA || path.join(home, "AppData", "Roaming");
|
||||
const localapp = env.LOCALAPPDATA || path.join(home, "AppData", "Local");
|
||||
return uniquePaths([
|
||||
path.join(appdata, "DSH Desktop", "host-commands"),
|
||||
path.join(appdata, "DSH Desktop", "runtime-commands"),
|
||||
path.join(localapp, "DSH Desktop", "host-commands"),
|
||||
path.join(localapp, "DSH Desktop", "runtime-commands"),
|
||||
path.join(home, "Library", "Application Support", "DSH Desktop", "host-commands"),
|
||||
]);
|
||||
}
|
||||
|
||||
function walkBinDirs(dir, out, depth) {
|
||||
if (depth < 0 || !isDir(dir)) return;
|
||||
const n = dir.replace(/\\/g, "/").toLowerCase();
|
||||
if (/(^|\/)bin$/.test(n)) {
|
||||
out.push(path.normalize(dir));
|
||||
return;
|
||||
}
|
||||
let ents = [];
|
||||
try {
|
||||
ents = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const ent of ents) {
|
||||
if (ent.isDirectory()) walkBinDirs(path.join(dir, ent.name), out, depth - 1);
|
||||
}
|
||||
}
|
||||
|
||||
export function listSealedRuntimeBins(env = process.env) {
|
||||
const out = [];
|
||||
for (const root of sealedRuntimeRoots(env)) walkBinDirs(root, out, 5);
|
||||
return uniquePaths(out).filter(isSealedRuntimeDir);
|
||||
}
|
||||
|
||||
export function restartNote() {
|
||||
return "正在重启桌面应用…";
|
||||
}
|
||||
|
||||
export function restartPlan(input = {}) {
|
||||
const exe = findDesktopAppExecutable(input);
|
||||
if (!exe) {
|
||||
return { kind: "desktop", execPath: "", argv: [], cwd: "", error: "未找到 DSH Desktop.exe,无法重启桌面应用" };
|
||||
}
|
||||
return {
|
||||
kind: "desktop",
|
||||
execPath: exe,
|
||||
argv: [],
|
||||
cwd: path.dirname(exe),
|
||||
};
|
||||
}
|
||||
|
||||
function helperEnv(payload) {
|
||||
const env = { ...process.env };
|
||||
delete env.DSH_PERMISSION_MODE;
|
||||
env.ELECTRON_RUN_AS_NODE = "1";
|
||||
env.DSH_PURGE_RESTART = JSON.stringify(payload);
|
||||
return env;
|
||||
}
|
||||
|
||||
function spawnHelper(helper, payload, opts = {}) {
|
||||
const plan = restartPlan();
|
||||
if (!plan.execPath) throw new Error(plan.error || "未找到 DSH Desktop.exe,无法重启桌面应用");
|
||||
const child = spawn(process.execPath, [helper], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
env: helperEnv({
|
||||
kind: "desktop",
|
||||
execPath: plan.execPath,
|
||||
argv: plan.argv,
|
||||
cwd: plan.cwd,
|
||||
pid: process.pid,
|
||||
...payload,
|
||||
}),
|
||||
});
|
||||
child.unref();
|
||||
if (opts.exit !== false) setTimeout(() => process.exit(0), opts.exitAfter ?? 250);
|
||||
}
|
||||
|
||||
function desktopRuntimeOf(ctx) {
|
||||
if (!ctx || typeof ctx.get !== "function") return null;
|
||||
const runtime = ctx.get("desktopRuntime") || ctx.get("desktopActions");
|
||||
return runtime && typeof runtime.requestRestart === "function" ? runtime : null;
|
||||
}
|
||||
|
||||
export function scheduleRestart(request, ctx) {
|
||||
const runtime = desktopRuntimeOf(ctx);
|
||||
if (runtime) {
|
||||
// 只走桌面整应用 relaunch,不要 exit Host(那会先把内嵌 web 单独拉起来)。
|
||||
Promise.resolve(runtime.requestRestart()).catch((err) => {
|
||||
console.warn("[dsh-purge] desktop requestRestart failed:", err);
|
||||
});
|
||||
return;
|
||||
}
|
||||
const helper = fileURLToPath(new URL("./restart-desktop.js", import.meta.url));
|
||||
spawnHelper(helper, { respawn: true, killApp: true }, { exit: false });
|
||||
}
|
||||
|
||||
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`);
|
||||
fs.copyFileSync(src, dest);
|
||||
const runtime = desktopRuntimeOf(ctx);
|
||||
if (runtime) {
|
||||
spawnHelper(dest, { cleanup, helper: dest, respawn: false }, { exit: false });
|
||||
Promise.resolve(runtime.requestRestart()).catch((err) => {
|
||||
console.warn("[dsh-purge] desktop uninstall restart failed:", err);
|
||||
});
|
||||
return;
|
||||
}
|
||||
spawnHelper(dest, { cleanup, helper: dest, respawn: true, killApp: true }, { exit: false });
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { adapterFor, detectSurface } from "./surface.js";
|
||||
import * as desktop from "./desktop.js";
|
||||
import * as web from "./web.js";
|
||||
|
||||
const ADAPTERS = {
|
||||
web,
|
||||
desktop,
|
||||
};
|
||||
|
||||
export function currentSurface(input) {
|
||||
return detectSurface(input);
|
||||
}
|
||||
|
||||
export function hostAdapter(kind = detectSurface()) {
|
||||
return ADAPTERS[adapterFor(kind)] || web;
|
||||
}
|
||||
|
||||
export function scheduleRestart(request, ctx) {
|
||||
return hostAdapter().scheduleRestart(request, ctx);
|
||||
}
|
||||
|
||||
export function scheduleCleanupRestart(opts) {
|
||||
return hostAdapter().scheduleCleanupRestart(opts);
|
||||
}
|
||||
|
||||
export function restartNote() {
|
||||
return hostAdapter().restartNote();
|
||||
}
|
||||
+23
-85
@@ -1,10 +1,8 @@
|
||||
import fs from "node:fs";
|
||||
import { promises as fsp } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as core from "./core.js";
|
||||
import * as hostctl from "./host.js";
|
||||
import * as rules from "./rules.js";
|
||||
import * as updater from "./update.js";
|
||||
import {
|
||||
@@ -77,7 +75,9 @@ function line(title, value, ok = null) {
|
||||
function renderStatus(state) {
|
||||
const out = [];
|
||||
out.push("dsh-purge 状态 / Status");
|
||||
out.push(line("宿主 / surface", state.surface || hostctl.currentSurface()));
|
||||
out.push(line("DSH_HOME", state.dsh_home));
|
||||
if (state.desktop_install) out.push(line("桌面安装 / desktop", state.desktop_install));
|
||||
if (state.ai_base) {
|
||||
out.push(line("插件根 / plugin root", state.ai_base));
|
||||
for (const [key, fp] of Object.entries(state.files)) {
|
||||
@@ -224,23 +224,12 @@ function installIdentityOverride(ctx, config = {}) {
|
||||
ctx.on("system-prompt/assemble", hook, { global: true, prepend: true });
|
||||
}
|
||||
|
||||
const LAUNCHER_SHIM_NAMES = ["dsh.cmd", "dsh.ps1", "dsh"];
|
||||
|
||||
function desktopShimNeedsPatch(dirs) {
|
||||
for (const dir of dirs || []) {
|
||||
for (const name of LAUNCHER_SHIM_NAMES) {
|
||||
if (core.shimFileStatus(path.join(dir, name)) === "original") return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function shimNeedsPatch(state) {
|
||||
if (hostctl.currentSurface() === "desktop") return false;
|
||||
return (
|
||||
state.shim_cmd === "original" ||
|
||||
state.shim_ps1 === "original" ||
|
||||
state.shim_bin === "original" ||
|
||||
desktopShimNeedsPatch(state.desktop_runtimes)
|
||||
state.shim_bin === "original"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -673,71 +662,6 @@ export function apply(ctx, config) {
|
||||
installWebServer(ctx, cfg);
|
||||
}
|
||||
|
||||
function portFromRequest(request) {
|
||||
const hostHeader = String(request.headers?.host || "");
|
||||
const match = hostHeader.match(/:(\d+)$/);
|
||||
if (match) return Number(match[1]);
|
||||
return 3080;
|
||||
}
|
||||
|
||||
function hostFromRequest(request) {
|
||||
const hostHeader = String(request.headers?.host || "127.0.0.1");
|
||||
return hostHeader.replace(/:\d+$/, "") || "127.0.0.1";
|
||||
}
|
||||
|
||||
function restartArgv() {
|
||||
const root = core.findDshBinRoot();
|
||||
const binJs = root ? path.join(root, "lib", "bin.js") : null;
|
||||
if (binJs && fs.existsSync(binJs)) {
|
||||
const args = [binJs];
|
||||
// 复用当前 argv 的 profile/子命令,入口改走 node + bin.js。
|
||||
const rest = process.argv.slice(2).filter((arg) => arg !== "--no-open");
|
||||
if (!rest.includes("web") && !rest.includes("desktop")) {
|
||||
const port = Number(process.env.PORT) || 3080;
|
||||
rest.unshift("web", "--port", String(port));
|
||||
}
|
||||
rest.push("--no-open");
|
||||
return [...args, ...rest];
|
||||
}
|
||||
const argv = process.argv.slice(1).filter((arg) => arg !== "--no-open");
|
||||
if (argv[0] && /\.(cmd|bat)$/i.test(argv[0])) {
|
||||
const dir = path.dirname(argv[0]);
|
||||
const candidates = [
|
||||
path.resolve(dir, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"),
|
||||
path.resolve(dir, "..", "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"),
|
||||
];
|
||||
const hit = candidates.find((p) => fs.existsSync(p));
|
||||
if (hit) argv[0] = hit;
|
||||
}
|
||||
argv.push("--no-open");
|
||||
return argv;
|
||||
}
|
||||
|
||||
function scheduleWebRestart(request) {
|
||||
try {
|
||||
core.silenceCmdFlash();
|
||||
} catch {}
|
||||
const helper = fileURLToPath(new URL("./restart-web.js", import.meta.url));
|
||||
const child = spawn(process.execPath, [helper], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
env: {
|
||||
...core.envForDetachedSpawn(),
|
||||
DSH_PURGE_RESTART: JSON.stringify({
|
||||
execPath: process.execPath,
|
||||
argv: restartArgv(),
|
||||
cwd: process.cwd(),
|
||||
host: hostFromRequest(request),
|
||||
port: portFromRequest(request),
|
||||
}),
|
||||
},
|
||||
});
|
||||
child.unref();
|
||||
setTimeout(() => process.exit(0), 250);
|
||||
}
|
||||
|
||||
function installWebServer(ctx, cfg) {
|
||||
watchWebTreeReady(ctx);
|
||||
ctx.inject(["webServer"], (host) => {
|
||||
@@ -762,7 +686,10 @@ function installWebServer(ctx, cfg) {
|
||||
sendJson(response, 200, {
|
||||
ok: true,
|
||||
ready: true,
|
||||
surface: state.surface || hostctl.currentSurface(),
|
||||
ai_base: state.ai_base,
|
||||
desktop_install: state.desktop_install || "",
|
||||
missing_ai_base: state.ai_base ? "" : core.missingAiBaseMessage(),
|
||||
patches_applied: state.patches_applied,
|
||||
patches_pending: state.patches_pending,
|
||||
patches_skipped: state.patches_skipped || 0,
|
||||
@@ -971,12 +898,17 @@ function installWebServer(ctx, cfg) {
|
||||
}
|
||||
try {
|
||||
const result = await uninstaller.uninstallPurge();
|
||||
sendJson(response, result.ok ? 200 : 500, result);
|
||||
sendJson(response, result.ok ? 200 : 500, {
|
||||
...result,
|
||||
surface: hostctl.currentSurface(),
|
||||
fullApp: hostctl.currentSurface() === "desktop",
|
||||
note: result.ok ? hostctl.restartNote() : undefined,
|
||||
});
|
||||
if (result.ok) {
|
||||
uninstaller.scheduleCleanupRestart({
|
||||
request,
|
||||
restartArgv: restartArgv(),
|
||||
cleanup: result.cleanup,
|
||||
ctx,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -1033,8 +965,14 @@ function installWebServer(ctx, cfg) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
scheduleWebRestart(request);
|
||||
sendJson(response, 200, { ok: true, note: "正在重启 dsh web…" });
|
||||
const surface = hostctl.currentSurface();
|
||||
hostctl.scheduleRestart(request, ctx);
|
||||
sendJson(response, 200, {
|
||||
ok: true,
|
||||
surface,
|
||||
fullApp: surface === "desktop",
|
||||
note: hostctl.restartNote(),
|
||||
});
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import fs from "node:fs";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
|
||||
const encoded = process.env.DSH_PURGE_RESTART;
|
||||
if (!encoded) process.exit(1);
|
||||
|
||||
let info;
|
||||
try {
|
||||
info = JSON.parse(encoded);
|
||||
} catch {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const cleanup = Array.isArray(info.cleanup) ? info.cleanup : [];
|
||||
|
||||
function spawnEnv() {
|
||||
const env = { ...process.env };
|
||||
delete env.DSH_PERMISSION_MODE;
|
||||
delete env.DSH_PURGE_RESTART;
|
||||
for (const key of Object.keys(env)) {
|
||||
if (key.toUpperCase() === "ELECTRON_RUN_AS_NODE") delete env[key];
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
function pidAlive(pid) {
|
||||
const n = Number(pid);
|
||||
if (!n) return false;
|
||||
try {
|
||||
process.kill(n, 0);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function waitPidGone(pid) {
|
||||
if (!pid) {
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
return true;
|
||||
}
|
||||
for (let i = 0; i < 80; i++) {
|
||||
if (!pidAlive(pid)) return true;
|
||||
await new Promise((r) => setTimeout(r, 120));
|
||||
}
|
||||
return !pidAlive(pid);
|
||||
}
|
||||
|
||||
function rmTree(dir) {
|
||||
if (!dir) return;
|
||||
try {
|
||||
fs.rmSync(dir, { recursive: true, force: true, maxRetries: 8, retryDelay: 120 });
|
||||
} catch {
|
||||
// 锁着就留下
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
return pids;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function killOtherDesktopProcesses(keepPid) {
|
||||
for (const pid of listDesktopPids()) {
|
||||
if (pid === keepPid || pid === process.pid) continue;
|
||||
try {
|
||||
process.kill(pid);
|
||||
} catch {
|
||||
// 已经退了
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (info.killApp) {
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
for (const dir of cleanup) rmTree(dir);
|
||||
if (info.helper) {
|
||||
try { fs.unlinkSync(info.helper); } catch { /* ignore */ }
|
||||
}
|
||||
killOtherDesktopProcesses(process.pid);
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
} else {
|
||||
const gone = await waitPidGone(info.pid);
|
||||
if (!gone) process.exit(1);
|
||||
for (const dir of cleanup) rmTree(dir);
|
||||
if (info.helper) {
|
||||
try { fs.unlinkSync(info.helper); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
if (info.respawn === false) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (!info.execPath) process.exit(1);
|
||||
|
||||
const child = spawn(info.execPath, Array.isArray(info.argv) ? info.argv : [], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
cwd: info.cwd || process.cwd(),
|
||||
env: spawnEnv(),
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
});
|
||||
child.on("error", () => process.exit(1));
|
||||
child.unref();
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
process.exit(0);
|
||||
@@ -0,0 +1,72 @@
|
||||
import path from "node:path";
|
||||
|
||||
/** 当前已接线的宿主面。gui / tui 先能识别,适配仍回退 web。 */
|
||||
export const SURFACES = Object.freeze(["web", "desktop", "gui", "tui"]);
|
||||
|
||||
function norm(value) {
|
||||
return String(value || "").trim().toLowerCase();
|
||||
}
|
||||
|
||||
function slash(value) {
|
||||
return String(value || "").replace(/\\/g, "/").toLowerCase();
|
||||
}
|
||||
|
||||
function exeName(execPath) {
|
||||
return path.basename(String(execPath || "")).toLowerCase();
|
||||
}
|
||||
|
||||
export function pathLooksDesktop(p) {
|
||||
const n = slash(p);
|
||||
if (!n) return false;
|
||||
return (
|
||||
n.includes("/dsh desktop/") ||
|
||||
n.includes("/dsh desktop.app/") ||
|
||||
n.includes("dsh-desktop") ||
|
||||
n.includes("dsh-plugin-desktop") ||
|
||||
/\/dsh desktop\.exe$/i.test(n) ||
|
||||
n.endsWith("/host-process-entry.js") ||
|
||||
n.endsWith("/desktop-cli.js")
|
||||
);
|
||||
}
|
||||
|
||||
export function isDesktopSurface(input = {}) {
|
||||
const env = input.env ?? process.env;
|
||||
const forced = norm(env.DSH_SURFACE);
|
||||
if (forced === "desktop") return true;
|
||||
if (forced && SURFACES.includes(forced)) return false;
|
||||
|
||||
const execPath = input.execPath ?? process.execPath;
|
||||
const name = exeName(execPath);
|
||||
if (name === "dsh desktop.exe" || name === "dsh desktop") return true;
|
||||
if (pathLooksDesktop(execPath)) return true;
|
||||
|
||||
const resourcesPath = input.resourcesPath ?? process.resourcesPath;
|
||||
if (pathLooksDesktop(resourcesPath)) return true;
|
||||
|
||||
const argv = input.argv ?? process.argv;
|
||||
if ((Array.isArray(argv) ? argv : []).some((arg) => pathLooksDesktop(arg))) return true;
|
||||
|
||||
const parentPort = input.parentPort !== undefined ? input.parentPort : process.parentPort;
|
||||
if (parentPort && (pathLooksDesktop(execPath) || pathLooksDesktop(resourcesPath))) return true;
|
||||
|
||||
if (env.ELECTRON_RUN_AS_NODE && pathLooksDesktop(execPath)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function forcedSurface(env) {
|
||||
const forced = norm(env.DSH_SURFACE);
|
||||
return SURFACES.includes(forced) ? forced : "";
|
||||
}
|
||||
|
||||
export function detectSurface(input = {}) {
|
||||
const env = input.env ?? process.env;
|
||||
const forced = forcedSurface(env);
|
||||
if (forced) return forced;
|
||||
if (isDesktopSurface(input)) return "desktop";
|
||||
return "web";
|
||||
}
|
||||
|
||||
/** gui / tui 尚未单独适配,先走 web 重启与探测。 */
|
||||
export function adapterFor(kind) {
|
||||
return kind === "desktop" ? "desktop" : "web";
|
||||
}
|
||||
+3
-29
@@ -1,10 +1,8 @@
|
||||
import fs from "node:fs";
|
||||
import { promises as fsp } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as core from "./core.js";
|
||||
import * as hostctl from "./host.js";
|
||||
import * as rules from "./rules.js";
|
||||
import * as updater from "./update.js";
|
||||
|
||||
@@ -265,30 +263,6 @@ export async function uninstallPurge() {
|
||||
return report;
|
||||
}
|
||||
|
||||
export function scheduleCleanupRestart({ request, restartArgv, cleanup = [] } = {}) {
|
||||
const src = fileURLToPath(new URL("./uninstall-restart.js", import.meta.url));
|
||||
const dest = path.join(os.tmpdir(), `dsh-purge-uninst-${process.pid}.mjs`);
|
||||
fs.copyFileSync(src, dest);
|
||||
const hostHeader = String(request?.headers?.host || "127.0.0.1");
|
||||
const portMatch = hostHeader.match(/:(\d+)$/);
|
||||
const child = spawn(process.execPath, [dest], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
env: {
|
||||
...core.envForDetachedSpawn(),
|
||||
DSH_PURGE_RESTART: JSON.stringify({
|
||||
execPath: process.execPath,
|
||||
argv: restartArgv || [process.argv[1], "--no-open"],
|
||||
cwd: process.cwd(),
|
||||
host: hostHeader.replace(/:\d+$/, "") || "127.0.0.1",
|
||||
port: portMatch ? Number(portMatch[1]) : 3080,
|
||||
cleanup,
|
||||
helper: dest,
|
||||
}),
|
||||
},
|
||||
});
|
||||
child.unref();
|
||||
setTimeout(() => process.exit(0), 400);
|
||||
export function scheduleCleanupRestart(opts = {}) {
|
||||
hostctl.scheduleCleanupRestart(opts);
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { findDshHome } from "./core.js";
|
||||
import { adapterFor, detectSurface } from "./surface.js";
|
||||
import { cliInvocation } from "./desktop.js";
|
||||
|
||||
const REPO = "YuJunZhiXue/dsh-purge";
|
||||
const BRANCH = "master";
|
||||
@@ -156,6 +158,7 @@ function resolveDshBin() {
|
||||
const names = process.platform === "win32" ? ["dsh.cmd", "dsh.exe", "dsh"] : ["dsh"];
|
||||
const dirs = [
|
||||
path.join(home, "..", "npm-global"),
|
||||
path.join(home, "..", "npm-global-0.1.5-rc.2"),
|
||||
path.join(home, "..", "npm-global-0.1.5-rc.1"),
|
||||
path.join(home, "bin"),
|
||||
];
|
||||
@@ -169,6 +172,23 @@ function resolveDshBin() {
|
||||
}
|
||||
|
||||
export function runDshPlugin(profile, args) {
|
||||
if (adapterFor(detectSurface()) === "desktop") {
|
||||
const inv = cliInvocation();
|
||||
if (!inv) throw new Error("找不到 DSH Desktop CLI");
|
||||
execFileSync(inv.execPath, [...inv.argvPrefix, "plugin", "--profile", profile, ...args], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
windowsHide: true,
|
||||
timeout: 120000,
|
||||
env: {
|
||||
...process.env,
|
||||
...inv.env,
|
||||
DSH_HOME: findDshHome(),
|
||||
CI: "1",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
const bin = resolveDshBin();
|
||||
if (!bin) throw new Error("找不到 dsh");
|
||||
execFileSync(bin, ["plugin", "--profile", profile, ...args], {
|
||||
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as core from "./core.js";
|
||||
|
||||
export function restartNote() {
|
||||
return "正在重启 dsh web…";
|
||||
}
|
||||
|
||||
export function portFromRequest(request) {
|
||||
const host = String(request?.headers?.host || "");
|
||||
const m = host.match(/:(\d+)$/);
|
||||
if (m) return Number(m[1]);
|
||||
return Number(process.env.PORT) || 3080;
|
||||
}
|
||||
|
||||
export function hostFromRequest(request) {
|
||||
const hostHeader = String(request?.headers?.host || "127.0.0.1");
|
||||
return hostHeader.replace(/:\d+$/, "") || "127.0.0.1";
|
||||
}
|
||||
|
||||
export function restartArgv({
|
||||
argv = process.argv,
|
||||
findBinRoot = core.findDshBinRoot,
|
||||
} = {}) {
|
||||
const root = findBinRoot();
|
||||
const binJs = root ? path.join(root, "lib", "bin.js") : null;
|
||||
if (binJs && fs.existsSync(binJs)) {
|
||||
const rest = argv.slice(2).filter((arg) => arg !== "--no-open");
|
||||
if (!rest.includes("web") && !rest.includes("desktop")) {
|
||||
const port = Number(process.env.PORT) || 3080;
|
||||
rest.unshift("web", "--port", String(port));
|
||||
}
|
||||
rest.push("--no-open");
|
||||
return [binJs, ...rest];
|
||||
}
|
||||
const next = argv.slice(1).filter((arg) => arg !== "--no-open");
|
||||
if (next[0] && /\.(cmd|bat)$/i.test(next[0])) {
|
||||
const dir = path.dirname(next[0]);
|
||||
const candidates = [
|
||||
path.resolve(dir, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"),
|
||||
path.resolve(dir, "..", "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js"),
|
||||
];
|
||||
const hit = candidates.find((p) => fs.existsSync(p));
|
||||
if (hit) next[0] = hit;
|
||||
}
|
||||
next.push("--no-open");
|
||||
return next;
|
||||
}
|
||||
|
||||
function spawnRestartHelper(helper, payload, exitAfter = 250) {
|
||||
try {
|
||||
core.silenceCmdFlash();
|
||||
} catch {}
|
||||
const child = spawn(process.execPath, [helper], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
env: {
|
||||
...core.envForDetachedSpawn(),
|
||||
DSH_PURGE_RESTART: JSON.stringify(payload),
|
||||
},
|
||||
});
|
||||
child.unref();
|
||||
setTimeout(() => process.exit(0), exitAfter);
|
||||
}
|
||||
|
||||
export function scheduleRestart(request) {
|
||||
const helper = fileURLToPath(new URL("./restart-web.js", import.meta.url));
|
||||
spawnRestartHelper(helper, {
|
||||
kind: "web",
|
||||
execPath: process.execPath,
|
||||
argv: restartArgv(),
|
||||
cwd: process.cwd(),
|
||||
host: hostFromRequest(request),
|
||||
port: portFromRequest(request),
|
||||
});
|
||||
}
|
||||
|
||||
export function scheduleCleanupRestart({ request, restartArgv: argv, cleanup = [] } = {}) {
|
||||
const src = fileURLToPath(new URL("./uninstall-restart.js", import.meta.url));
|
||||
const dest = path.join(os.tmpdir(), `dsh-purge-uninst-${process.pid}.mjs`);
|
||||
fs.copyFileSync(src, dest);
|
||||
spawnRestartHelper(dest, {
|
||||
kind: "web",
|
||||
execPath: process.execPath,
|
||||
argv: argv || restartArgv(),
|
||||
cwd: process.cwd(),
|
||||
host: hostFromRequest(request),
|
||||
port: portFromRequest(request),
|
||||
cleanup,
|
||||
helper: dest,
|
||||
}, 400);
|
||||
}
|
||||
Reference in new issue
Block a user