Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(cli): 生成 npx/npm shim,修复插件子进程找不到 npx (#1029)

iuuuuuuuua100347b4dc4
diff --git a/src-tauri/src/service/cli/core.rs b/src-tauri/src/service/cli/core.rs
index 7da18c3b..40c4bf17 100644
--- a/src-tauri/src/service/cli/core.rs
+++ b/src-tauri/src/service/cli/core.rs
@@ -91,11 +91,18 @@ pub fn remove(app_handle: &AppHandle) -> Result<CliLinkStatus, String> {
#[cfg(windows)]
{
- use super::shim::{PNPM_SHIM_CMD_NAME, PNPM_SHIM_PS1_NAME, SHIM_CMD_NAME, SHIM_PS1_NAME};
+ use super::shim::{
+ NPM_SHIM_CMD_NAME, NPM_SHIM_PS1_NAME, NPX_SHIM_CMD_NAME, NPX_SHIM_PS1_NAME,
+ PNPM_SHIM_CMD_NAME, PNPM_SHIM_PS1_NAME, SHIM_CMD_NAME, SHIM_PS1_NAME,
+ };
let _ = fs::remove_file(bin_dir.join(SHIM_CMD_NAME));
let _ = fs::remove_file(bin_dir.join(SHIM_PS1_NAME));
let _ = fs::remove_file(bin_dir.join(PNPM_SHIM_CMD_NAME));
let _ = fs::remove_file(bin_dir.join(PNPM_SHIM_PS1_NAME));
+ let _ = fs::remove_file(bin_dir.join(NPX_SHIM_CMD_NAME));
+ let _ = fs::remove_file(bin_dir.join(NPX_SHIM_PS1_NAME));
+ let _ = fs::remove_file(bin_dir.join(NPM_SHIM_CMD_NAME));
+ let _ = fs::remove_file(bin_dir.join(NPM_SHIM_PS1_NAME));
}
#[cfg(not(windows))]
{
diff --git a/src-tauri/src/service/cli/shim/build.rs b/src-tauri/src/service/cli/shim/build.rs
index c1002786..fc58ca17 100644
--- a/src-tauri/src/service/cli/shim/build.rs
+++ b/src-tauri/src/service/cli/shim/build.rs
@@ -483,6 +483,254 @@ exec "$NODE" "$PNPM_BIN" "$@"
)
}
+// ---------------------------------------------------------------------------
+// npx / npm shim(用 node 运行 npm 自带的 cli 入口)
+//
+// 这两个名字在应用自身 bin 目录里必须存在:插件安装器与 MCP 服务端常以
+// `cmd /c npx -y <pkg>` 拉起,而用户 PATH 上的 npx 可能是 npm 官方安装器留
+// 下的相对路径包装(`%~dp0` 自指),一旦 node 不在同一目录就会静默失败或
+// 长时间卡住。cli 入口按「与所选 node 同目录的 npm 安装」→「应用捆绑 node 的
+// 同级 npm」→「PATH 上的用户 npx」顺序解析,全部只依赖已烘焙的绝对路径。
+// ---------------------------------------------------------------------------
+
+fn build_npm_cli_cmd_shim(
+ paths: &ShimPaths,
+ shim_name: &str,
+ cli_file: &str,
+ bundled_cli: &Path,
+) -> String {
+ normalize_cmd_line_endings(format!(
+ r#"@echo off
+rem DeepSeek Harness Desktop - {shim_name} command shim (generated)
+rem Do not edit: regenerated by the desktop app on install/startup.
+setlocal
+set "NODE_BIN={node_bin}"
+set "NODE_DIR={node_dir}"
+rem Use bundled MinGit only when system Git lacks its HTTPS transport helper.
+rem Never export it as GIT_DIR: that variable names a repository, not a bin dir.
+set "SYSTEM_GIT_WORKS="
+for /f "delims=" %%g in ('git --exec-path 2^>nul') do if exist "%%g\git-remote-https.exe" set "SYSTEM_GIT_WORKS=1"
+if not defined SYSTEM_GIT_WORKS if exist "{git_dir}\git.exe" set "PATH={git_dir};%PATH%"
+{node_resolve}
+rem CMD_NODE_RESOLVE jumps here for every node it accepts, so the cli lookup
+rem below must sit at :launch rather than after a separate label.
+:launch
+rem The cli entry ships with npm, so it is looked up next to the node that will
+rem run it: a version manager's node directory may hold no npm at all, and a
+rem relative wrapper cannot reach one.
+set "NPM_CLI="
+set "NPM_NODE_DIR="
+if /i "%NODE%"=="node" goto :npm_node_from_path
+for %%c in ("%NODE%") do set "NPM_NODE_DIR=%%~dpc"
+goto :npm_node_dir_ready
+:npm_node_from_path
+for /f "delims=" %%c in ('where node 2^>nul') do if not defined NPM_NODE_DIR set "NPM_NODE_DIR=%%~dpc"
+:npm_node_dir_ready
+for %%c in (
+ "%NPM_NODE_DIR%node_modules\npm\bin\{cli_file}"
+ "%NPM_NODE_DIR%lib\node_modules\npm\bin\{cli_file}"
+ "%NPM_NODE_DIR%..\lib\node_modules\npm\bin\{cli_file}"
+) do if not defined NPM_CLI if exist "%%~c" set "NPM_CLI=%%~c"
+if defined NPM_CLI goto :npm_run
+rem The bundled runtime always carries its own npm installation.
+if exist "{bundled_cli}" set "NPM_CLI={bundled_cli}"
+if defined NPM_CLI goto :npm_run
+
+rem No usable npm next to node: forward the user's own {shim_name} instead
+rem (skipping our own shim dir, and only executable extensions).
+set "SELF_PREFIX=%~dp0"
+set "SELF_PREFIX=%SELF_PREFIX:~0,-1%"
+set "USER_NPM="
+for /f "delims=" %%p in ('where {shim_name} 2^>nul') do (
+ if not defined USER_NPM (
+ if /i not "%%p"=="%SELF_PREFIX%\{shim_name}.cmd" (
+ if /i not "%%p"=="%SELF_PREFIX%\{shim_name}.exe" (
+ if /i not "%%p"=="%SELF_PREFIX%\{shim_name}.bat" (
+ if /i "%%~xp"==".cmd" set "USER_NPM=%%p"
+ if /i "%%~xp"==".exe" set "USER_NPM=%%p"
+ if /i "%%~xp"==".bat" set "USER_NPM=%%p"
+ )
+ )
+ )
+ )
+)
+if not defined USER_NPM goto :no_npm
+if defined DSH_NPM_SHIM_CHAIN goto :npm_append_user
+set "DSH_NPM_SHIM_CHAIN=1"
+goto :npm_forward_user
+:npm_append_user
+if not "%DSH_NPM_SHIM_CHAIN:~15,1%"=="" goto :npm_reentry_limit
+set "DSH_NPM_SHIM_CHAIN=%DSH_NPM_SHIM_CHAIN%1"
+:npm_forward_user
+rem Forward by invoking the target directly, never through `call`: the extra
+rem interpretation layer re-expands %* and mangles already-escaped arguments.
+"%USER_NPM%" %*
+exit /b %ERRORLEVEL%
+
+:npm_run
+if not exist "%NPM_CLI%" goto :no_npm
+"%NODE%" "%NPM_CLI%" %*
+exit /b %ERRORLEVEL%
+
+:npm_reentry_limit
+1>&2 echo [{shim_name}] NPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls.
+exit /b 1
+
+:no_npm
+echo [{shim_name}] npm cli not found. Please run DeepSeek Harness Desktop to install it first. 1>&2
+exit /b 1
+
+:no_node
+echo [{shim_name}] Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first. 1>&2
+exit /b 1
+"#,
+ node_bin = portable_path_cmd(&paths.node_bin),
+ node_dir = portable_path_cmd(&paths.node_dir()),
+ git_dir = portable_path_cmd(&paths.git_dir()),
+ bundled_cli = portable_path_cmd(bundled_cli),
+ shim_name = shim_name,
+ cli_file = cli_file,
+ node_resolve = CMD_NODE_RESOLVE,
+ ))
+}
+
+/// Windows `npx.cmd` 内容(见 npx/npm shim 段注释)。
+#[cfg_attr(all(not(windows), not(test)), allow(dead_code))]
+pub fn build_npx_cmd_shim(paths: &ShimPaths) -> String {
+ build_npm_cli_cmd_shim(
+ paths,
+ "npx",
+ "npx-cli.js",
+ &paths
+ .node_dir()
+ .join("node_modules")
+ .join("npm")
+ .join("bin")
+ .join("npx-cli.js"),
+ )
+}
+
+/// Windows `npm.cmd` 内容(见 npx/npm shim 段注释)。
+#[cfg_attr(all(not(windows), not(test)), allow(dead_code))]
+pub fn build_npm_cmd_shim(paths: &ShimPaths) -> String {
+ build_npm_cli_cmd_shim(
+ paths,
+ "npm",
+ "npm-cli.js",
+ &paths
+ .node_dir()
+ .join("node_modules")
+ .join("npm")
+ .join("bin")
+ .join("npm-cli.js"),
+ )
+}
+
+fn build_npm_cli_ps1_shim(
+ paths: &ShimPaths,
+ shim_name: &str,
+ cli_file: &str,
+ bundled_cli: &Path,
+) -> String {
+ format!(
+ r#"# DeepSeek Harness Desktop - {shim_name} command shim (generated)
+# Do not edit: regenerated by the desktop app on install/startup.
+$ErrorActionPreference = "Stop"
+$nodeBin = '{node_bin}'
+$nodeDir = '{node_dir}'
+$gitDir = '{git_dir}'
+# Use bundled MinGit only when system Git lacks its HTTPS transport helper.
+$systemGitWorks = $false
+try {{
+ $gitExecPath = & git --exec-path 2> $null
+ $systemGitWorks = ($LASTEXITCODE -eq 0) -and (Test-Path -LiteralPath (Join-Path $gitExecPath 'git-remote-https.exe'))
+}} catch {{}}
+if (-not $systemGitWorks -and $gitDir -and (Test-Path -LiteralPath (Join-Path $gitDir 'git.exe'))) {{
+ $env:PATH = $gitDir + ';' + $env:PATH
+}}
+{node_resolve}
+# The cli entry ships with npm, so it is looked up next to the node that will run
+# it: a version manager's node directory may hold no npm at all, and a relative
+# wrapper cannot reach one.
+$nodePath = $node
+if ($node -eq 'node') {{
+ $nodeCommand = Get-Command node -ErrorAction SilentlyContinue
+ if ($nodeCommand) {{ $nodePath = $nodeCommand.Source }}
+}}
+$npmNodeDir = $null
+if ($nodePath -and $nodePath -ne 'node') {{ $npmNodeDir = Split-Path -Parent $nodePath }}
+$cli = $null
+if ($npmNodeDir) {{
+ foreach ($candidate in @(
+ (Join-Path $npmNodeDir 'node_modules\npm\bin\{cli_file}'),
+ (Join-Path $npmNodeDir 'lib\node_modules\npm\bin\{cli_file}'),
+ (Join-Path $npmNodeDir '..\lib\node_modules\npm\bin\{cli_file}')
+ )) {{
+ if (-not $cli -and (Test-Path -LiteralPath $candidate -PathType Leaf)) {{ $cli = $candidate }}
+ }}
+}}
+# The bundled runtime always carries its own npm installation.
+if (-not $cli -and (Test-Path -LiteralPath '{bundled_cli}' -PathType Leaf)) {{ $cli = '{bundled_cli}' }}
+
+if (-not $cli) {{
+ # No usable npm next to node: forward the user's own {shim_name} instead
+ # (skipping our own shim dir).
+ $selfDir = $PSScriptRoot.TrimEnd('\') + '\'
+ $userCommand = Get-Command {shim_name} -All -ErrorAction SilentlyContinue |
+ Where-Object {{ $_.Source -and -not $_.Source.StartsWith($selfDir, [System.StringComparison]::OrdinalIgnoreCase) }} |
+ Select-Object -First 1
+ if ($userCommand) {{
+ & $userCommand.Source @args
+ exit $LASTEXITCODE
+ }}
+ Write-Error '[{shim_name}] npm cli not found. Please run DeepSeek Harness Desktop to install it first.'
+ exit 1
+}}
+& $node $cli @args
+exit $LASTEXITCODE
+"#,
+ node_bin = escape_path_ps1(&paths.node_bin),
+ node_dir = escape_path_ps1(&paths.node_dir()),
+ git_dir = escape_path_ps1(&paths.git_dir()),
+ bundled_cli = escape_path_ps1(bundled_cli),
+ shim_name = shim_name,
+ cli_file = cli_file,
+ node_resolve = PS1_NODE_RESOLVE,
+ )
+}
+
+/// Windows `npx.ps1` 内容(见 npx/npm shim 段注释)。
+#[cfg_attr(all(not(windows), not(test)), allow(dead_code))]
+pub fn build_npx_ps1_shim(paths: &ShimPaths) -> String {
+ build_npm_cli_ps1_shim(
+ paths,
+ "npx",
+ "npx-cli.js",
+ &paths
+ .node_dir()
+ .join("node_modules")
+ .join("npm")
+ .join("bin")
+ .join("npx-cli.js"),
+ )
+}
+
+/// Windows `npm.ps1` 内容(见 npx/npm shim 段注释)。
+#[cfg_attr(all(not(windows), not(test)), allow(dead_code))]
+pub fn build_npm_ps1_shim(paths: &ShimPaths) -> String {
+ build_npm_cli_ps1_shim(
+ paths,
+ "npm",
+ "npm-cli.js",
+ &paths
+ .node_dir()
+ .join("node_modules")
+ .join("npm")
+ .join("bin")
+ .join("npm-cli.js"),
+ )
+}
+
#[cfg(test)]
mod tests {
use super::super::test_util::{
@@ -513,6 +761,58 @@ mod tests {
assert!(!content.contains(r#"set "APP_DIR=C:\Users\100%test""#));
}
+ /// npx/npm shim 的 cli 入口必须按「与所选 node 同目录的 npm」优先解析,
+ /// 且 PATH 上用户的同名命令只作最后兜底(排除本 shim 目录,防自指递归)。
+ #[cfg(windows)]
+ #[test]
+ fn npm_cli_shims_resolve_cli_next_to_node() {
+ for (shim_name, content) in [
+ ("npx", build_npx_cmd_shim(&sample_shim_paths())),
+ ("npm", build_npm_cmd_shim(&sample_shim_paths())),
+ ] {
+ let cli_file = format!("{shim_name}-cli.js");
+ assert!(content.contains(&format!("- {shim_name} command shim")));
+ assert!(content.contains("if not defined DSH_NODE goto :skip_dsh_node"));
+ assert!(content.contains(&format!(
+ "for /f \"delims=\" %%p in ('where {shim_name} 2^>nul') do ("
+ )));
+ assert!(content.contains(&format!("\"%SELF_PREFIX%\\{shim_name}.cmd\"")));
+ assert!(content.contains(&format!("\"%SELF_PREFIX%\\{shim_name}.exe\"")));
+ assert!(content.contains("\"%NODE%\" \"%NPM_CLI%\" %*"));
+ assert!(content.contains("DSH_NPM_SHIM_CHAIN"));
+ assert!(content
+ .contains("if not \"%DSH_NPM_SHIM_CHAIN:~15,1%\"==\"\" goto :npm_reentry_limit"));
+ let same_dir = content
+ .find(&format!("%NPM_NODE_DIR%node_modules\\npm\\bin\\{cli_file}"))
+ .expect("same-dir cli candidate");
+ let lib_dir = content
+ .find(&format!(
+ "%NPM_NODE_DIR%lib\\node_modules\\npm\\bin\\{cli_file}"
+ ))
+ .expect("lib cli candidate");
+ let parent_lib = content
+ .find(&format!(
+ "%NPM_NODE_DIR%..\\lib\\node_modules\\npm\\bin\\{cli_file}"
+ ))
+ .expect("parent lib cli candidate");
+ let user_scan = content
+ .find(&format!("where {shim_name} 2^>nul"))
+ .expect("user shim scan");
+ assert!(same_dir < lib_dir && lib_dir < parent_lib && parent_lib < user_scan);
+ // 捆绑运行时同级始终带 npm 安装,是解析链的固定兜底
+ let bundled = sample_shim_paths();
+ let bundled_cli = bundled
+ .node_bin
+ .parent()
+ .unwrap()
+ .join("node_modules")
+ .join("npm")
+ .join("bin")
+ .join(&cli_file);
+ assert!(content.contains(&bundled_cli.to_string_lossy().to_string()));
+ }
+ }
+
/// issue #581:Windows `.cmd` 必须全 CRLF。Rust 源码被 `.gitattributes`
/// 固定为 LF,多行字符串里的裸 LF 会让部分环境下的 cmd.exe 解析
/// label/括号块错位,`dsh plugin install` 因此整体失败。
@@ -524,6 +824,8 @@ mod tests {
build_cmd_shim(&sample_shim_paths(), &sample_dsh_home()),
),
("pnpm.cmd", build_pnpm_cmd_shim(&sample_shim_paths())),
+ ("npx.cmd", build_npx_cmd_shim(&sample_shim_paths())),
+ ("npm.cmd", build_npm_cmd_shim(&sample_shim_paths())),
] {
assert!(content.contains("@echo off"), "{name}: missing header");
let bytes = content.as_bytes();
@@ -663,6 +965,112 @@ mod tests {
assert_eq!(content.matches("if defined DSH_PNPM (").count(), 1);
}
+ /// 生成的 `npx.cmd` 必须能真正跑起来:所选 node 目录没有 npm 时回落到
+ /// 捆绑运行时的 cli,由替身 node 回报它拿到的 cli 入口与参数。
+ #[cfg(windows)]
+ #[test]
+ fn generated_npx_cmd_runs_with_bundled_cli() {
+ let dir = temp_dir("npx-run");
+ let paths = shim_paths_for(&dir);
+ let cli = paths
+ .node_bin
+ .parent()
+ .unwrap()
+ .join("node_modules")
+ .join("npm")
+ .join("bin")
+ .join("npx-cli.js");
+ std::fs::create_dir_all(cli.parent().unwrap()).unwrap();
+ std::fs::write(&cli, "// stub").unwrap();
+
+ let node = dir.join("fake-node.cmd");
+ std::fs::write(
+ &node,
+ "@echo off\r\necho CLI=[%~1] ARG=[%~2]\r\nexit /b 0\r\n",
+ )
+ .unwrap();
+
+ let shim = dir.join("npx.cmd");
+ std::fs::write(&shim, build_npx_cmd_shim(&paths)).unwrap();
+
+ let mut command = std::process::Command::new("cmd");
+ command.args(["/d", "/C", shim.to_str().unwrap(), "--version"]);
+ command.env("DSH_NODE", &node);
+ // PATH 只留 System32:本机 .nvmd 的坏 npx 与自建 shim 都不会被选中
+ let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| "C:\\Windows".to_string());
+ command.env("PATH", Path::new(&system_root).join("System32"));
+ let output = command.output().unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ assert!(
+ output.status.success(),
+ "generated npx.cmd exited with {:?}: {stdout} / {}",
+ output.status,
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ stdout.contains(&format!("CLI=[{}]", cli.display())),
+ "the shim did not pick the bundled npm cli: {stdout}"
+ );
+ assert!(stdout.contains("ARG=[--version]"), "{stdout}");
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// 真实执行生成的 `npx.ps1`:DSH_NODE 指向的目录没有 npm 时回落到捆绑 cli。
+ #[cfg(windows)]
+ #[test]
+ fn generated_npx_ps1_runs_with_bundled_cli() {
+ let dir = temp_dir("npx-ps1-run");
+ let paths = shim_paths_for(&dir);
+ let cli = paths
+ .node_bin
+ .parent()
+ .unwrap()
+ .join("node_modules")
+ .join("npm")
+ .join("bin")
+ .join("npx-cli.js");
+ std::fs::create_dir_all(cli.parent().unwrap()).unwrap();
+ std::fs::write(&cli, "// stub").unwrap();
+
+ let node = dir.join("fake-node.cmd");
+ std::fs::write(
+ &node,
+ "@echo off\r\necho CLI=[%~1] ARG=[%~2]\r\nexit /b 0\r\n",
+ )
+ .unwrap();
+
+ let shim = dir.join("npx.ps1");
+ std::fs::write(&shim, build_npx_ps1_shim(&paths)).unwrap();
+
+ let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
+ let powershell =
+ PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
+ let output = std::process::Command::new(powershell)
+ .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])
+ .arg(&shim)
+ .arg("--version")
+ .env("DSH_NODE", &node)
+ .output()
+ .unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+
+ assert!(
+ output.status.success(),
+ "generated npx.ps1 exited with {:?}: {stdout} / {}",
+ output.status,
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ stdout.contains(&format!("CLI=[{}]", cli.display())),
+ "the ps1 shim did not pick the bundled npm cli: {stdout}"
+ );
+ assert!(stdout.contains("ARG=[--version]"), "{stdout}");
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
/// issue #130:真实执行生成的 cmd shim,确保用户 pnpm 的失败码不会因 cmd
/// 括号块预展开 `%ERRORLEVEL%` 而被吞成 0。
///
diff --git a/src-tauri/src/service/cli/shim/mod.rs b/src-tauri/src/service/cli/shim/mod.rs
index 061ef8d3..d25e08dd 100644
--- a/src-tauri/src/service/cli/shim/mod.rs
+++ b/src-tauri/src/service/cli/shim/mod.rs
@@ -24,6 +24,14 @@ pub const SHIM_PS1_NAME: &str = "dsh.ps1";
pub const PNPM_SHIM_CMD_NAME: &str = "pnpm.cmd";
#[cfg(windows)]
pub const PNPM_SHIM_PS1_NAME: &str = "pnpm.ps1";
+#[cfg(windows)]
+pub const NPX_SHIM_CMD_NAME: &str = "npx.cmd";
+#[cfg(windows)]
+pub const NPX_SHIM_PS1_NAME: &str = "npx.ps1";
+#[cfg(windows)]
+pub const NPM_SHIM_CMD_NAME: &str = "npm.cmd";
+#[cfg(windows)]
+pub const NPM_SHIM_PS1_NAME: &str = "npm.ps1";
/// Unix 下 shim 文件名
#[cfg(unix)]
diff --git a/src-tauri/src/service/cli/shim/write.rs b/src-tauri/src/service/cli/shim/write.rs
index 4fa3c530..b22e27f4 100644
--- a/src-tauri/src/service/cli/shim/write.rs
+++ b/src-tauri/src/service/cli/shim/write.rs
@@ -4,20 +4,23 @@
use crate::config;
use std::fs;
use std::path::{Path, PathBuf};
-use tauri::AppHandle;
+use tauri::{AppHandle, Runtime};
#[cfg(not(windows))]
#[allow(unused_imports)] // debug 构建 dsh shim 不写入;测试仍引用
use super::build::build_sh_shim;
#[allow(unused_imports)] // 构建函数在 debug 构建/异平台下由 cfg 裁剪,测试仍引用
use super::build::{
- build_cmd_shim, build_pnpm_cmd_shim, build_pnpm_ps1_shim, build_pnpm_sh_shim, build_ps1_shim,
- ShimPaths,
+ build_cmd_shim, build_npm_cmd_shim, build_npm_ps1_shim, build_npx_cmd_shim, build_npx_ps1_shim,
+ build_pnpm_cmd_shim, build_pnpm_ps1_shim, build_pnpm_sh_shim, build_ps1_shim, ShimPaths,
};
#[cfg(all(windows, not(debug_assertions)))]
use super::SHIM_PS1_NAME;
#[cfg(windows)]
-use super::{PNPM_SHIM_CMD_NAME, PNPM_SHIM_PS1_NAME, SHIM_CMD_NAME};
+use super::{
+ NPM_SHIM_CMD_NAME, NPM_SHIM_PS1_NAME, NPX_SHIM_CMD_NAME, NPX_SHIM_PS1_NAME, PNPM_SHIM_CMD_NAME,
+ PNPM_SHIM_PS1_NAME, SHIM_CMD_NAME,
+};
#[cfg(not(windows))]
use super::{PNPM_SHIM_SH_NAME, SHIM_SH_NAME};
@@ -147,7 +150,7 @@ pub fn user_dsh_preserved(bin_dir: &Path) -> bool {
/// shim 生成时烘焙的依赖路径:按依赖映射表解析,可能指向 AppData 之外的任意
/// 位置(如安装目录的 `resources/*` 捆绑副本)。
-pub fn shim_paths(app_handle: &AppHandle) -> ShimPaths {
+pub fn shim_paths<R: Runtime>(app_handle: &AppHandle<R>) -> ShimPaths {
ShimPaths {
node_bin: config::dependencies::binary_path(app_handle, config::dependencies::DEP_NODE),
dsh_bin: config::get_dsh_binary_path(app_handle),
@@ -158,14 +161,14 @@ pub fn shim_paths(app_handle: &AppHandle) -> ShimPaths {
/// 捆绑 MinGit 的 `cmd` 目录(系统 Git 缺 HTTPS helper 时由 shim 注入 PATH)。
#[cfg(windows)]
-fn bundled_git_dir(app_handle: &AppHandle) -> Option<PathBuf> {
+fn bundled_git_dir<R: Runtime>(app_handle: &AppHandle<R>) -> Option<PathBuf> {
config::get_mingit_binary_path(app_handle)
.parent()
.map(Path::to_path_buf)
}
#[cfg(not(windows))]
-fn bundled_git_dir(_app_handle: &AppHandle) -> Option<PathBuf> {
+fn bundled_git_dir<R: Runtime>(_app_handle: &AppHandle<R>) -> Option<PathBuf> {
None
}
@@ -175,8 +178,9 @@ fn bundled_git_dir(_app_handle: &AppHandle) -> Option<PathBuf> {
///
/// 覆盖式仅针对本应用生成的 shim(自愈时内容与当前安装一致);用户手动放置的
/// 同名 `dsh`/`pnpm` 一律保留不动,避免覆盖用户自己的安装与配置。
-pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String> {
+pub fn write_shims<R: Runtime>(app_handle: &AppHandle<R>, bin_dir: &Path) -> Result<(), String> {
let paths = shim_paths(app_handle);
+ let dsh_home = config::get_dsh_data_path(app_handle);
fs::create_dir_all(bin_dir)
.map_err(|e| format!("SHIM_MKDIR_FAILED: create bin dir failed: {e}"))?;
@@ -194,7 +198,6 @@ pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String>
// 目录,并覆盖生产的命令行集成;生产版生成的 dsh shim 原样保留。
#[cfg(not(debug_assertions))]
{
- let dsh_home = config::get_dsh_data_path(app_handle);
#[cfg(windows)]
{
write_if_ours!(SHIM_CMD_NAME, build_cmd_shim(&paths, &dsh_home));
@@ -206,15 +209,22 @@ pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String>
}
}
#[cfg(debug_assertions)]
- log::debug!("debug build: skip dsh shim write (shared user state kept for release)");
+ {
+ let _ = &dsh_home;
+ log::debug!("debug build: skip dsh shim write (shared user state kept for release)");
+ }
- // pnpm shim 不烘焙 $DSH_HOME(仅绑定 bundle 目录与“用户 pnpm 优先”逻辑),
- // 内容与生产完全一致,开发构建也可写入——dsh plugin 子进程经 PATH 解析
- // pnpm 依赖它,写它不污染任何共享数据。
+ // pnpm/npx/npm shim 不烘焙 $DSH_HOME(仅绑定 bundle 目录与“用户命令优先”
+ // 逻辑),内容与生产完全一致,开发构建也可写入——dsh plugin 子进程经 PATH
+ // 解析这些命令依赖它,写它不污染任何共享数据。
#[cfg(windows)]
{
write_if_ours!(PNPM_SHIM_CMD_NAME, build_pnpm_cmd_shim(&paths));
write_if_ours!(PNPM_SHIM_PS1_NAME, build_pnpm_ps1_shim(&paths));
+ write_if_ours!(NPX_SHIM_CMD_NAME, build_npx_cmd_shim(&paths));
+ write_if_ours!(NPX_SHIM_PS1_NAME, build_npx_ps1_shim(&paths));
+ write_if_ours!(NPM_SHIM_CMD_NAME, build_npm_cmd_shim(&paths));
+ write_if_ours!(NPM_SHIM_PS1_NAME, build_npm_ps1_shim(&paths));
}
#[cfg(not(windows))]
{
@@ -241,6 +251,7 @@ pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String>
mod tests {
use super::super::test_util::{sample_dsh_home, sample_shim_paths, shim_paths_for};
use super::*;
+ use tauri::test::{mock_builder, mock_context, noop_assets};
#[test]
fn foreign_file_detection() {
@@ -510,4 +521,38 @@ mod tests {
assert_eq!(std::fs::read(&target).unwrap(), expected);
let _ = std::fs::remove_dir_all(&dir);
}
+ /// 生产入口 `write_shims` 的落盘编排:pnpm/npx/npm 的 cmd 与 ps1 shim 必须一并
+ /// 写入 bin 目录——这些 shim 是 dsh plugin 子进程解析 npx 的唯一可靠来源。
+ /// 用 mock app 走真实入口,保证「接线断了」这类事故会被测试挡住。
+ #[test]
+ #[cfg(windows)]
+ fn write_shims_writes_npx_and_npm_shims() {
+ let dir = temp_dir("write-npx-npm");
+ let bin_dir = dir.join("bin");
+ let mut context = mock_context(noop_assets());
+ context.config_mut().identifier = "dsh-tauri".into();
+ let app = mock_builder().build(context).unwrap();
+
+ write_shims(app.handle(), &bin_dir).unwrap();
+
+ for name in [
+ "pnpm.cmd", "pnpm.ps1", "npx.cmd", "npx.ps1", "npm.cmd", "npm.ps1",
+ ] {
+ let path = bin_dir.join(name);
+ assert!(path.is_file(), "{name} was not written");
+ assert!(!is_foreign_file(&path), "{name} must be a generated shim");
+ }
+
+ let npx = std::fs::read_to_string(bin_dir.join("npx.cmd")).unwrap();
+ assert!(
+ npx.contains("npx-cli.js"),
+ "npx.cmd must bake the npm cli entry: {npx}"
+ );
+ assert!(
+ npx.contains("npx command shim (generated)"),
+ "npx.cmd lost its generated marker: {npx}"
+ );
+ assert!(!bin_dir.join("dsh.cmd").exists());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/src-tauri/src/service/core/runtime.rs b/src-tauri/src/service/core/runtime.rs
index c7f7f4c7..1699a9ef 100644
--- a/src-tauri/src/service/core/runtime.rs
+++ b/src-tauri/src/service/core/runtime.rs
@@ -1254,26 +1254,38 @@ async fn detect_node_target(node: &Path, core_root: &Path) -> Result<NodeTarget,
})
}
+/// 用指定运行时执行原生模块探测脚本:脚本先落盘成临时 `.mjs` 再以文件路径交给 node。
+///
+/// 不能走 `node -e`:`-e` 只取脚本的第一行(本脚本以换行开头,载荷会退化成空串,
+/// 于是永远没有标记行、探测结论永远是"未知"),而 `--input-type=module` 与脚本
+/// 文件路径不能同时给出(ERR_INPUT_TYPE_NOT_ALLOWED)。脚本本身不读 argv,改用文件
+/// 路径不损失任何信息:解析根仍由 `cwd` 提供,require 根仍是核心根。
+fn run_native_probe(node: &Path, core_root: &Path) -> Result<std::process::Output, String> {
+ let script = std::env::temp_dir().join(format!("dsh-native-probe-{}.mjs", std::process::id()));
+ std::fs::write(&script, NATIVE_PROBE_SCRIPT).map_err(|error| {
+ format!(
+ "CORE_NATIVE_PROBE_SCRIPT_FAILED: write {} failed: {error}",
+ script.display()
+ )
+ })?;
+ let program = node.as_os_str().to_os_string();
+ let args = vec![script.clone().into_os_string()];
+ let output = run_process_with_timeout(
+ &program,
+ &args,
+ core_root,
+ NATIVE_PROBE_TIMEOUT,
+ "native probe",
+ );
+ let _ = std::fs::remove_file(&script);
+ output
+}
+
/// 用指定运行时执行原生模块探测脚本,返回结构化结论。
async fn probe_native_modules(node: &Path, core_root: &Path) -> NativeProbe {
let node = node.to_path_buf();
let core_root = core_root.to_path_buf();
- let result = tokio::task::spawn_blocking(move || {
- let program = node.as_os_str().to_os_string();
- let args = vec![
- OsString::from("--input-type=module"),
- OsString::from("-e"),
- OsString::from(NATIVE_PROBE_SCRIPT),
- ];
- run_process_with_timeout(
- &program,
- &args,
- &core_root,
- NATIVE_PROBE_TIMEOUT,
- "native probe",
- )
- })
- .await;
+ let result = tokio::task::spawn_blocking(move || run_native_probe(&node, &core_root)).await;
match result {
Ok(Ok(output)) if output.status.success() => {
@@ -1685,6 +1697,25 @@ fn command_output_tail(output: &std::process::Output) -> String {
mod tests {
use super::*;
+ /// 以生产同款方式执行探测脚本(落盘成 `.mjs` 再交给 node),保证测试覆盖的
+ /// 正是运行时那条路径——`node -e` 会截断多行脚本,测出来的是假绿。
+ fn run_probe_script(node: &std::path::Path, cwd: &std::path::Path) -> std::process::Output {
+ let script = cwd.join("dsh-native-probe-test.mjs");
+ std::fs::write(&script, NATIVE_PROBE_SCRIPT).unwrap();
+ let mut command = Command::new(node);
+ command
+ .arg(&script)
+ .current_dir(cwd)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ command.creation_flags(0x08000000);
+ }
+ command.output().expect("node must be runnable")
+ }
+
/// 指纹摘要必须与条目规模无关:真实安装的条目数已超过早先的固定上限,
/// 若还按条目数放弃缓存,结论戳永远写不下来(每次启动都重跑两个 node 子进程)。
#[test]
@@ -2205,18 +2236,7 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("node_modules")).unwrap();
- let mut command = Command::new(&node);
- command
- .args(["--input-type=module", "-e", NATIVE_PROBE_SCRIPT])
- .current_dir(&root)
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
- #[cfg(windows)]
- {
- use std::os::windows::process::CommandExt;
- command.creation_flags(0x08000000);
- }
- let output = command.output().expect("node must be runnable");
+ let output = run_probe_script(&node, &root);
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success(),
@@ -2259,18 +2279,7 @@ mod tests {
)
.unwrap();
- let mut command = Command::new(&node);
- command
- .args(["--input-type=module", "-e", NATIVE_PROBE_SCRIPT])
- .current_dir(&root)
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
- #[cfg(windows)]
- {
- use std::os::windows::process::CommandExt;
- command.creation_flags(0x08000000);
- }
- let output = command.output().expect("node must be runnable");
+ let output = run_probe_script(&node, &root);
let failures = parse_native_probe_failures(&String::from_utf8_lossy(&output.stdout))
.expect("marker line");
let probe = NativeProbe::Failed(failures);