Skip to content

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

fix: discover mise pnpm shims

Justin Skowyra0b04f9248a60
diff --git a/src-tauri/src/service/cli/mod.rs b/src-tauri/src/service/cli/mod.rs
index 54372d4a..dab37a69 100644
--- a/src-tauri/src/service/cli/mod.rs
+++ b/src-tauri/src/service/cli/mod.rs
@@ -26,5 +26,5 @@ mod path;
mod shim;
pub use core::{ensure, ensure_shims, get_status, remove, CliLinkStatus};
-pub use path::{find_user_pnpm, get_bin_dir};
+pub use path::{find_user_pnpm, get_bin_dir, pnpm_env_value};
pub use shim::is_generated_shim;
diff --git a/src-tauri/src/service/cli/path.rs b/src-tauri/src/service/cli/path.rs
index d8158181..71d31e8d 100644
--- a/src-tauri/src/service/cli/path.rs
+++ b/src-tauri/src/service/cli/path.rs
@@ -109,18 +109,76 @@ pub fn path_registered(app_handle: &AppHandle) -> bool {
}
}
-/// 在 PATH 中查找用户自己安装的 pnpm(排除应用注册的 shim 目录)。
+/// 在继承 PATH 与平台标准目录中查找用户 pnpm(排除应用注册的 shim)。
///
/// "用户优先"策略:安装时(`Pnpm::check_installed`)用户已有 pnpm 则跳过
-/// 捆绑安装;`pnpm` shim 运行时也会优先转发到用户的 pnpm。
+/// 捆绑安装;Unix GUI 额外检查 mise 标准数据目录,生成的 `pnpm` shim 也会
+/// 优先转发到探测出的精确路径。
pub fn find_user_pnpm(app_handle: &AppHandle) -> Option<PathBuf> {
let mut dirs: Vec<PathBuf> =
std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()).collect();
#[cfg(windows)]
append_windows_pnpm_dirs(&mut dirs);
+ #[cfg(unix)]
+ {
+ let mise_data = std::env::var_os("MISE_DATA_DIR").map(PathBuf::from);
+ let xdg_data = std::env::var_os("XDG_DATA_HOME").map(PathBuf::from);
+ let home = app_handle.path().home_dir().ok();
+ append_unix_mise_dirs(
+ &mut dirs,
+ mise_data.as_deref(),
+ xdg_data.as_deref(),
+ home.as_deref(),
+ );
+ }
find_pnpm_in_dirs(&get_bin_dir(app_handle), &dirs)
}
+/// Unix 图形进程不会读取交互式 shell 配置;在继承 PATH 之后补充 mise 的
+/// 官方数据目录,并保留先出现的字面路径,避免解析 `pnpm -> mise` 符号链接。
+#[cfg_attr(windows, allow(dead_code))]
+fn append_unix_mise_dirs(
+ dirs: &mut Vec<PathBuf>,
+ mise_data: Option<&Path>,
+ xdg_data: Option<&Path>,
+ home: Option<&Path>,
+) {
+ let candidates = [
+ mise_data.map(|path| path.join("shims")),
+ xdg_data.map(|path| path.join("mise/shims")),
+ home.map(|path| path.join(".local/share/mise/shims")),
+ ];
+ for candidate in candidates.into_iter().flatten() {
+ let candidate_key = std::path::absolute(&candidate).unwrap_or_else(|_| candidate.clone());
+ let duplicate = dirs.iter().any(|existing| {
+ std::path::absolute(existing).unwrap_or_else(|_| existing.clone()) == candidate_key
+ });
+ if candidate.is_absolute() && !duplicate {
+ dirs.push(candidate);
+ }
+ }
+}
+
+/// 子进程环境中的 pnpm 必须是绝对路径。Unix 只做字面绝对化,不能解析 mise
+/// 依赖 argv[0] 的 shim 符号链接;Windows 继续去除 `\\?\` 并解析连接点。
+fn pnpm_env_path(path: &Path) -> PathBuf {
+ #[cfg(windows)]
+ {
+ dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
+ }
+ #[cfg(not(windows))]
+ {
+ std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
+ }
+}
+
+/// 生成传给 shim 的精确 `DSH_PNPM` 值,并拒绝桌面端自身的 pnpm shim。
+pub fn pnpm_env_value(pnpm: &Path, bin_dir: &Path) -> Option<String> {
+ let pnpm = pnpm_env_path(pnpm);
+ let bin_dir = pnpm_env_path(bin_dir);
+ (pnpm.parent() != Some(bin_dir.as_path())).then(|| pnpm.to_string_lossy().into_owned())
+}
+
/// 在给定目录中按顺序查找用户 pnpm,便于不依赖全局环境测试探测规则。
fn find_pnpm_in_dirs(bin_dir: &Path, dirs: &[PathBuf]) -> Option<PathBuf> {
let candidates: &[&str] = if cfg!(windows) {
@@ -128,18 +186,18 @@ fn find_pnpm_in_dirs(bin_dir: &Path, dirs: &[PathBuf]) -> Option<PathBuf> {
} else {
&["pnpm"]
};
- let bin_dir = dunce::canonicalize(bin_dir).unwrap_or_else(|_| bin_dir.to_path_buf());
+ let bin_dir = pnpm_env_path(bin_dir);
for dir in dirs {
if dir.as_os_str().is_empty() {
continue;
}
- let normalized = dunce::canonicalize(dir).unwrap_or_else(|_| dir.clone());
+ let normalized = pnpm_env_path(dir);
if normalized == bin_dir {
continue;
}
for name in candidates {
- let candidate = dir.join(name);
- if candidate.is_file() {
+ let candidate = normalized.join(name);
+ if usable_pnpm_candidate(&candidate) {
return Some(candidate);
}
}
@@ -147,6 +205,31 @@ fn find_pnpm_in_dirs(bin_dir: &Path, dirs: &[PathBuf]) -> Option<PathBuf> {
None
}
+/// 只接受真实可执行文件,并拒绝复制或链接到其它目录的桌面端生成 shim。
+fn usable_pnpm_candidate(candidate: &Path) -> bool {
+ if !candidate.is_file() || !pnpm_is_executable(candidate) {
+ return false;
+ }
+ let is_small_wrapper = candidate
+ .metadata()
+ .map(|metadata| metadata.len() <= 16 * 1024)
+ .unwrap_or(false);
+ !is_small_wrapper || !super::shim::is_generated_shim(candidate)
+}
+
+#[cfg(unix)]
+fn pnpm_is_executable(path: &Path) -> bool {
+ use std::os::unix::fs::PermissionsExt;
+ path.metadata()
+ .map(|metadata| metadata.permissions().mode() & 0o111 != 0)
+ .unwrap_or(false)
+}
+
+#[cfg(not(unix))]
+fn pnpm_is_executable(_path: &Path) -> bool {
+ true
+}
+
/// Windows GUI 进程的 PATH 可能早于 npm/pnpm 安装,补充这些工具的标准用户目录。
#[cfg(windows)]
fn append_windows_pnpm_dirs(dirs: &mut Vec<PathBuf>) {
@@ -592,11 +675,207 @@ mod tests {
std::fs::write(shim_dir.join(name), "shim").unwrap();
std::fs::write(first.join(name), "first").unwrap();
std::fs::write(second.join(name), "second").unwrap();
+ make_executable(&shim_dir.join(name));
+ make_executable(&first.join(name));
+ make_executable(&second.join(name));
let found = find_pnpm_in_dirs(&shim_dir, &[shim_dir.clone(), first.clone(), second]);
assert_eq!(found, Some(first.join(name)));
let _ = std::fs::remove_dir_all(root);
}
+ #[test]
+ fn mise_dirs_follow_path_and_dedupe_in_source_order() {
+ let root = temp_dir("pnpm-mise-dirs");
+ let inherited = root.join("inherited");
+ let mise = root.join("mise-data");
+ let xdg = root.join("xdg-data");
+ let home = root.join("home");
+ let mut dirs = vec![inherited.clone(), xdg.join("mise/shims")];
+
+ append_unix_mise_dirs(&mut dirs, Some(&mise), Some(&xdg), Some(&home));
+
+ assert_eq!(
+ dirs,
+ vec![
+ inherited,
+ xdg.join("mise/shims"),
+ mise.join("shims"),
+ home.join(".local/share/mise/shims"),
+ ]
+ );
+ let mut fresh = vec![root.join("fresh-path")];
+ append_unix_mise_dirs(&mut fresh, Some(&mise), Some(&xdg), Some(&home));
+ assert_eq!(
+ fresh,
+ vec![
+ root.join("fresh-path"),
+ mise.join("shims"),
+ xdg.join("mise/shims"),
+ home.join(".local/share/mise/shims"),
+ ]
+ );
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn inherited_path_pnpm_precedes_appended_mise_pnpm() {
+ let root = temp_dir("pnpm-mise-precedence");
+ let desktop_bin = root.join("desktop-bin");
+ let inherited = root.join("inherited");
+ let mise_data = root.join("mise");
+ let mise_shims = mise_data.join("shims");
+ for dir in [&desktop_bin, &inherited, &mise_shims] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };
+ let inherited_pnpm = inherited.join(name);
+ let mise_pnpm = mise_shims.join(name);
+ std::fs::write(&inherited_pnpm, "inherited").unwrap();
+ std::fs::write(&mise_pnpm, "mise").unwrap();
+ make_executable(&inherited_pnpm);
+ make_executable(&mise_pnpm);
+ let mut dirs = vec![inherited];
+ append_unix_mise_dirs(&mut dirs, Some(&mise_data), None, None);
+
+ assert_eq!(find_pnpm_in_dirs(&desktop_bin, &dirs), Some(inherited_pnpm));
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn default_home_mise_pnpm_is_discovered_when_path_misses() {
+ let root = temp_dir("pnpm-mise-home-default");
+ let desktop_bin = root.join("desktop-bin");
+ let inherited = root.join("inherited");
+ let home = root.join("home");
+ let home_shims = home.join(".local/share/mise/shims");
+ for dir in [&desktop_bin, &inherited, &home_shims] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };
+ let pnpm = home_shims.join(name);
+ std::fs::write(&pnpm, "mise home").unwrap();
+ make_executable(&pnpm);
+ let mut dirs = vec![inherited];
+ append_unix_mise_dirs(&mut dirs, None, None, Some(&home));
+
+ assert_eq!(find_pnpm_in_dirs(&desktop_bin, &dirs), Some(pnpm));
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn discovery_misses_desktop_generated_shim_and_absent_candidates() {
+ let root = temp_dir("pnpm-own-shim-only");
+ let desktop_bin = root.join("desktop-bin");
+ let copied_bin = root.join("copied-bin");
+ let empty = root.join("empty");
+ std::fs::create_dir_all(&desktop_bin).unwrap();
+ std::fs::create_dir_all(&copied_bin).unwrap();
+ std::fs::create_dir_all(&empty).unwrap();
+ let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };
+ let own = desktop_bin.join(name);
+ let copied = copied_bin.join(name);
+ for path in [&own, &copied] {
+ std::fs::write(
+ path,
+ "# DeepSeek Harness Desktop - pnpm command shim (generated)\n",
+ )
+ .unwrap();
+ make_executable(path);
+ }
+
+ assert_eq!(
+ find_pnpm_in_dirs(&desktop_bin, &[desktop_bin.clone(), copied_bin, empty]),
+ None
+ );
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn pnpm_env_value_injects_exact_external_path_and_rejects_own_dir() {
+ let root = temp_dir("pnpm-env-value");
+ let desktop_bin = root.join("desktop-bin");
+ let external_bin = root.join("external-bin");
+ std::fs::create_dir_all(&desktop_bin).unwrap();
+ std::fs::create_dir_all(&external_bin).unwrap();
+ let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };
+ let own = desktop_bin.join(name);
+ let external = external_bin.join(name);
+ std::fs::write(&own, "own").unwrap();
+ std::fs::write(&external, "external").unwrap();
+
+ assert_eq!(pnpm_env_value(&own, &desktop_bin), None);
+ assert_eq!(
+ pnpm_env_value(&external, &desktop_bin),
+ Some(pnpm_env_path(&external).to_string_lossy().into_owned())
+ );
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn discovery_rejects_non_executable_pnpm() {
+ let root = temp_dir("pnpm-nonexec");
+ let desktop_bin = root.join("desktop-bin");
+ let mise_shims = root.join("mise/shims");
+ std::fs::create_dir_all(&desktop_bin).unwrap();
+ std::fs::create_dir_all(&mise_shims).unwrap();
+ std::fs::write(mise_shims.join("pnpm"), "not executable").unwrap();
+
+ assert_eq!(
+ find_pnpm_in_dirs(&desktop_bin, std::slice::from_ref(&mise_shims)),
+ None
+ );
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn discovery_preserves_argv0_style_mise_symlink() {
+ use std::os::unix::fs::{symlink, PermissionsExt};
+
+ let root = temp_dir("pnpm-mise-symlink");
+ let desktop_bin = root.join("desktop-bin");
+ let mise_bin = root.join("mise/bin");
+ let mise_shims = root.join("mise/shims");
+ for dir in [&desktop_bin, &mise_bin, &mise_shims] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ let target = mise_bin.join("mise");
+ std::fs::write(
+ &target,
+ "#!/bin/sh\n[ \"$(basename \"$0\")\" = pnpm ] || exit 51\nprintf 'argv0-ok\\n'\n",
+ )
+ .unwrap();
+ let mut permissions = std::fs::metadata(&target).unwrap().permissions();
+ permissions.set_mode(0o700);
+ std::fs::set_permissions(&target, permissions).unwrap();
+ let pnpm = mise_shims.join("pnpm");
+ symlink(&target, &pnpm).unwrap();
+
+ let found = find_pnpm_in_dirs(&desktop_bin, std::slice::from_ref(&mise_shims)).unwrap();
+ assert_eq!(found, pnpm);
+ assert_eq!(
+ pnpm_env_value(&found, &desktop_bin),
+ Some(found.to_string_lossy().into_owned())
+ );
+ let output = std::process::Command::new(&found).output().unwrap();
+ assert!(output.status.success());
+ assert_eq!(String::from_utf8_lossy(&output.stdout), "argv0-ok\n");
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ fn make_executable(path: &Path) {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mut permissions = std::fs::metadata(path).unwrap().permissions();
+ permissions.set_mode(0o700);
+ std::fs::set_permissions(path, permissions).unwrap();
+ }
+ #[cfg(not(unix))]
+ let _ = path;
+ }
+
fn temp_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!(
"dsh-rc-{tag}-{}-{}",
diff --git a/src-tauri/src/service/cli/shim.rs b/src-tauri/src/service/cli/shim.rs
index 9560a9dd..0bc6875f 100644
--- a/src-tauri/src/service/cli/shim.rs
+++ b/src-tauri/src/service/cli/shim.rs
@@ -372,22 +372,17 @@ 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 "%APP_DIR%\dependencies\git\cmd\git.exe" set "PATH=%APP_DIR%\dependencies\git\cmd;%PATH%"
-rem Use the absolute user pnpm selected and validated by the desktop app.
-if defined DSH_PNPM (
- if exist "%DSH_PNPM%" goto :use_selected
-)
-
-rem Use the absolute user pnpm selected and validated by the desktop app.
-if defined DSH_PNPM (
- if exist "%DSH_PNPM%" goto :use_selected
-)
-
rem App-internal installs (DSH_PREFER_BUNDLED_PNPM=1) use the bundled pnpm,
rem falling back to the user's only when the bundled one is missing.
if "%DSH_PREFER_BUNDLED_PNPM%"=="1" (
if exist "%PNPM_BIN%" goto :after_user
)
+rem Use the exact user pnpm discovered by the desktop app.
+if defined DSH_PNPM (
+ if exist "%DSH_PNPM%" goto :use_selected
+)
+
rem Prefer a user-installed pnpm (skip our own shim dir), fall back to bundled.
rem Accept only executable extensions (.cmd/.exe/.bat), ignore extensionless shell scripts.
set "SELF_PREFIX=%~dp0"
@@ -464,25 +459,28 @@ if (-not $systemGitWorks) {{
}}
}}
-{node_resolve}
+$useBundled = $env:DSH_PREFER_BUNDLED_PNPM -eq '1' -and (Test-Path -LiteralPath $pnpmBin -PathType Leaf)
-# App-internal installs (DSH_PREFER_BUNDLED_PNPM=1) use the bundled pnpm,
-# falling back to the user's only when the bundled one is missing.
-if ($env:DSH_PREFER_BUNDLED_PNPM -eq '1' -and (Test-Path -LiteralPath $pnpmBin)) {{
- & $node $pnpmBin @args
+# Use the exact user pnpm discovered by the desktop app unless bundled was requested.
+if (-not $useBundled -and $env:DSH_PNPM -and (Test-Path -LiteralPath $env:DSH_PNPM -PathType Leaf)) {{
+ & $env:DSH_PNPM @args
exit $LASTEXITCODE
}}
# Prefer a user-installed pnpm (skip our own shim dir), fall back to bundled.
-$selfDir = $PSScriptRoot.TrimEnd('\') + '\'
-$userPnpm = Get-Command pnpm -All -ErrorAction SilentlyContinue |
- Where-Object {{ $_.Source -and -not $_.Source.StartsWith($selfDir, [System.StringComparison]::OrdinalIgnoreCase) }} |
- Select-Object -First 1
-if ($userPnpm) {{
- & $userPnpm.Source @args
- exit $LASTEXITCODE
+if (-not $useBundled) {{
+ $selfDir = $PSScriptRoot.TrimEnd('\') + '\'
+ $userPnpm = Get-Command pnpm -All -ErrorAction SilentlyContinue |
+ Where-Object {{ $_.Source -and -not $_.Source.StartsWith($selfDir, [System.StringComparison]::OrdinalIgnoreCase) }} |
+ Select-Object -First 1
+ if ($userPnpm) {{
+ & $userPnpm.Source @args
+ exit $LASTEXITCODE
+ }}
}}
+{node_resolve}
+
if (-not (Test-Path -LiteralPath $pnpmBin)) {{
Write-Error '[pnpm] pnpm not found. Please run DeepSeek Harness Desktop to install it first.'
exit 1
@@ -509,26 +507,33 @@ pub fn build_pnpm_sh_shim(app_dir: &Path) -> String {
# Do not edit: regenerated by the desktop app on install/startup.
APP_DIR='{app_dir}'
PNPM_BIN='{pnpm_bin}'
-{node_resolve}
-# App-internal installs (DSH_PREFER_BUNDLED_PNPM=1) use the bundled pnpm,
-# falling back to the user's only when the bundled one is missing.
+USE_BUNDLED=
if [ "$DSH_PREFER_BUNDLED_PNPM" = "1" ] && [ -f "$PNPM_BIN" ]; then
- exec "$NODE" "$PNPM_BIN" "$@"
+ USE_BUNDLED=1
+fi
+
+# Use the exact user pnpm discovered by the desktop app unless bundled was requested.
+if [ -z "$USE_BUNDLED" ] && [ -n "$DSH_PNPM" ] && [ -x "$DSH_PNPM" ]; then
+ exec "$DSH_PNPM" "$@"
fi
# Prefer a user-installed pnpm (skip our own shim dir), fall back to bundled.
-SELF_DIR=$(cd "$(dirname "$0")" && pwd)
-IFS=:
-for dir in $PATH; do
- if [ "$dir" = "$SELF_DIR" ]; then
- continue
- fi
- if [ -x "$dir/pnpm" ]; then
- exec "$dir/pnpm" "$@"
- fi
-done
-unset IFS
+if [ -z "$USE_BUNDLED" ]; then
+ SELF_DIR=$(cd "$(dirname "$0")" && pwd)
+ IFS=:
+ for dir in $PATH; do
+ if [ "$dir" = "$SELF_DIR" ]; then
+ continue
+ fi
+ if [ -x "$dir/pnpm" ]; then
+ exec "$dir/pnpm" "$@"
+ fi
+ done
+ unset IFS
+fi
+
+{node_resolve}
if [ ! -f "$PNPM_BIN" ]; then
echo "[pnpm] pnpm not found. Please run DeepSeek Harness Desktop to install it first." >&2
@@ -794,8 +799,10 @@ mod tests {
// 应用内部安装可经 DSH_PREFER_BUNDLED_PNPM=1 强制捆绑版(须在用户搜索前生效)
assert!(content.contains("DSH_PREFER_BUNDLED_PNPM"));
let env_at = content.find("DSH_PREFER_BUNDLED_PNPM").unwrap();
+ let exact_at = content.find("if defined DSH_PNPM").unwrap();
let user_at = content.find("where pnpm").unwrap();
- assert!(env_at < user_at);
+ assert!(env_at < exact_at && exact_at < user_at);
+ assert_eq!(content.matches("if defined DSH_PNPM").count(), 1);
}
/// issue #130:真实执行生成的 cmd shim,确保用户 pnpm 的失败码不会因 cmd
@@ -827,8 +834,8 @@ mod tests {
#[test]
fn pnpm_cmd_shim_uses_selected_pnpm_with_restricted_path() {
let dir = temp_dir("pnpm-selected");
- let selected = dir.join("selected-pnpm.cmd");
- std::fs::write(&selected, "@echo off\r\necho SELECTED_PNPM %*\r\nexit /b 0\r\n").unwrap();
+ let selected = dir.join("selected pnpm.cmd");
+ std::fs::write(&selected, "@echo off\r\necho SELECTED_PNPM %*\r\nexit /b 37\r\n").unwrap();
let selected = dunce::canonicalize(&selected).unwrap();
assert!(!selected.to_string_lossy().starts_with(r"\\?\"));
let shim = dir.join("pnpm.cmd");
@@ -838,12 +845,42 @@ mod tests {
let output = std::process::Command::new(system32.join("cmd.exe"))
.args(["/d", "/c"]).arg(&shim).arg("probe-121")
.env("PATH", &system32).env("SystemRoot", system_root)
- .env("DSH_PNPM", &selected).output().unwrap();
- assert!(output.status.success());
+ .env("DSH_PNPM", &selected)
+ .env("DSH_PREFER_BUNDLED_PNPM", "1").output().unwrap();
+ assert_eq!(output.status.code(), Some(37));
assert!(String::from_utf8_lossy(&output.stdout).contains("SELECTED_PNPM probe-121"));
let _ = std::fs::remove_dir_all(dir);
}
+ /// 两个变量同时存在且捆绑文件可用时,显式的捆绑策略必须优先。
+ #[cfg(windows)]
+ #[test]
+ fn pnpm_cmd_shim_prefers_existing_bundle_over_selected_path() {
+ let dir = temp_dir("pnpm-both-vars");
+ let app_dir = dir.join("app");
+ let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");
+ std::fs::create_dir_all(pnpm_bin.parent().unwrap()).unwrap();
+ std::fs::write(&pnpm_bin, "fixture").unwrap();
+ let selected = dir.join("selected.cmd");
+ let node = dir.join("node.cmd");
+ std::fs::write(&selected, "@echo off\r\necho SELECTED\r\n").unwrap();
+ std::fs::write(&node, "@echo off\r\necho BUNDLED %*\r\nexit /b 0\r\n").unwrap();
+ let shim = dir.join("pnpm.cmd");
+ std::fs::write(&shim, build_pnpm_cmd_shim(&app_dir)).unwrap();
+ let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
+ let system32 = PathBuf::from(&system_root).join("System32");
+ let output = std::process::Command::new(system32.join("cmd.exe"))
+ .args(["/d", "/c"]).arg(&shim).arg("both-vars")
+ .env("PATH", &system32).env("SystemRoot", system_root)
+ .env("DSH_NODE", &node).env("DSH_PNPM", &selected)
+ .env("DSH_PREFER_BUNDLED_PNPM", "1").output().unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(output.status.success());
+ assert!(stdout.contains("BUNDLED"));
+ assert!(!stdout.contains("SELECTED"));
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
#[test]
fn pnpm_ps1_shim_contains_user_precedence() {
let content = build_pnpm_ps1_shim(&sample_app_dir());
@@ -853,6 +890,76 @@ mod tests {
assert!(content.contains("@args"));
assert!(content.contains("Join-Path $appDir 'runtime\\node.exe'"));
assert!(content.contains("$env:DSH_PREFER_BUNDLED_PNPM"));
+ assert!(content.contains("$env:DSH_PNPM"));
+ let bundled_at = content.find("$useBundled =").unwrap();
+ let exact_at = content.find("& $env:DSH_PNPM @args").unwrap();
+ let path_at = content.find("Get-Command pnpm -All").unwrap();
+ assert!(bundled_at < exact_at && exact_at < path_at);
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn pnpm_ps1_shim_dispatches_exact_path_with_spaces_args_and_exit_code() {
+ let dir = temp_dir("pnpm-ps1-selected");
+ let selected = dir.join("selected pnpm.cmd");
+ std::fs::write(
+ &selected,
+ "@echo off\r\necho SELECTED:%*\r\nexit /b 37\r\n",
+ )
+ .unwrap();
+ let shim = dir.join("pnpm.ps1");
+ std::fs::write(&shim, build_pnpm_ps1_shim(&dir.join("app"))).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)
+ .args(["alpha beta", "gamma"])
+ .env("DSH_PNPM", &selected)
+ .env("DSH_PREFER_BUNDLED_PNPM", "1")
+ .output()
+ .unwrap();
+ assert_eq!(output.status.code(), Some(37));
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("SELECTED:\"alpha beta\" gamma"),
+ "unexpected stdout: {stdout:?}"
+ );
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn pnpm_ps1_shim_prefers_existing_bundle_over_selected_path() {
+ let dir = temp_dir("pnpm-ps1-both-vars");
+ let app_dir = dir.join("app");
+ let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");
+ std::fs::create_dir_all(pnpm_bin.parent().unwrap()).unwrap();
+ std::fs::write(&pnpm_bin, "fixture").unwrap();
+ let selected = dir.join("selected.cmd");
+ let node = dir.join("node.cmd");
+ std::fs::write(&selected, "@echo off\r\necho SELECTED\r\n").unwrap();
+ std::fs::write(&node, "@echo off\r\necho BUNDLED %*\r\nexit /b 0\r\n").unwrap();
+ let shim = dir.join("pnpm.ps1");
+ std::fs::write(&shim, build_pnpm_ps1_shim(&app_dir)).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("both-vars")
+ .env("DSH_NODE", &node)
+ .env("DSH_PNPM", &selected)
+ .env("DSH_PREFER_BUNDLED_PNPM", "1")
+ .output()
+ .unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(output.status.success(), "stderr: {}", String::from_utf8_lossy(&output.stderr));
+ assert!(stdout.contains("BUNDLED"), "unexpected stdout: {stdout:?}");
+ assert!(!stdout.contains("SELECTED"));
+ let _ = std::fs::remove_dir_all(dir);
}
#[test]
@@ -864,6 +971,80 @@ mod tests {
assert!(content.contains(r#"exec "$NODE" "$PNPM_BIN" "$@""#));
assert!(content.contains(r#"$APP_DIR/runtime/bin/node"#));
assert!(content.contains("DSH_PREFER_BUNDLED_PNPM"));
+ assert!(content.contains(r#"exec "$DSH_PNPM" "$@""#));
+ let bundled_at = content.find("USE_BUNDLED=").unwrap();
+ let exact_at = content.find(r#"exec "$DSH_PNPM" "$@""#).unwrap();
+ let path_at = content.find("for dir in $PATH").unwrap();
+ assert!(bundled_at < exact_at && exact_at < path_at);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn pnpm_sh_shim_dispatches_exact_path_with_spaces_args_and_exit_code() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = temp_dir("pnpm-sh-selected");
+ let selected = dir.join("selected pnpm");
+ std::fs::write(&selected, "#!/bin/sh\nprintf 'SELECTED:%s\\n' \"$*\"\nexit 37\n").unwrap();
+ let mut permissions = std::fs::metadata(&selected).unwrap().permissions();
+ permissions.set_mode(0o700);
+ std::fs::set_permissions(&selected, permissions).unwrap();
+ let shim = dir.join("pnpm");
+ std::fs::write(&shim, build_pnpm_sh_shim(&dir.join("app"))).unwrap();
+ let mut permissions = std::fs::metadata(&shim).unwrap().permissions();
+ permissions.set_mode(0o700);
+ std::fs::set_permissions(&shim, permissions).unwrap();
+
+ let output = std::process::Command::new(&shim)
+ .args(["alpha beta", "gamma"])
+ .env("PATH", "/usr/bin:/bin")
+ .env("DSH_PNPM", &selected)
+ .env("DSH_PREFER_BUNDLED_PNPM", "1")
+ .output()
+ .unwrap();
+ assert_eq!(output.status.code(), Some(37));
+ assert_eq!(String::from_utf8_lossy(&output.stdout), "SELECTED:alpha beta gamma\n");
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn pnpm_sh_shim_prefers_existing_bundle_over_selected_path() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = temp_dir("pnpm-sh-both-vars");
+ let app_dir = dir.join("app");
+ let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");
+ std::fs::create_dir_all(pnpm_bin.parent().unwrap()).unwrap();
+ std::fs::write(&pnpm_bin, "fixture").unwrap();
+ let selected = dir.join("selected");
+ let node = dir.join("node");
+ std::fs::write(&selected, "#!/bin/sh\necho SELECTED\n").unwrap();
+ std::fs::write(&node, "#!/bin/sh\necho BUNDLED \"$@\"\n").unwrap();
+ for path in [&selected, &node] {
+ let mut permissions = std::fs::metadata(path).unwrap().permissions();
+ permissions.set_mode(0o700);
+ std::fs::set_permissions(path, permissions).unwrap();
+ }
+ let shim = dir.join("pnpm");
+ std::fs::write(&shim, build_pnpm_sh_shim(&app_dir)).unwrap();
+ let mut permissions = std::fs::metadata(&shim).unwrap().permissions();
+ permissions.set_mode(0o700);
+ std::fs::set_permissions(&shim, permissions).unwrap();
+
+ let output = std::process::Command::new(&shim)
+ .arg("both-vars")
+ .env("PATH", "/usr/bin:/bin")
+ .env("DSH_NODE", &node)
+ .env("DSH_PNPM", &selected)
+ .env("DSH_PREFER_BUNDLED_PNPM", "1")
+ .output()
+ .unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(output.status.success());
+ assert!(stdout.contains("BUNDLED"));
+ assert!(!stdout.contains("SELECTED"));
+ let _ = std::fs::remove_dir_all(dir);
}
/// issue #121:桌面端注入的 DSH_NODE(预检解析出的 node 路径)必须在
diff --git a/src-tauri/src/service/plugin/install.rs b/src-tauri/src/service/plugin/install.rs
index 2136e917..cbdadf3e 100644
--- a/src-tauri/src/service/plugin/install.rs
+++ b/src-tauri/src/service/plugin/install.rs
@@ -370,17 +370,11 @@ pub(crate) fn build_plugin_envs(app_handle: &AppHandle, prefer_bundled_pnpm: boo
if prefer_bundled_pnpm {
envs.insert("DSH_PREFER_BUNDLED_PNPM".to_string(), "1".to_string());
} else if let Some(pnpm) = cli::find_user_pnpm(app_handle) {
- // 应用预检选到的用户 pnpm 可能来自相对 PATH / junction;显式注入其绝对
- // 路径,避免 dsh 子进程在不同 PATH/CWD 下重新发现失败(issue #121)。
- // 防御性排除应用自身 shim,避免旧 PATH / 大小写差异导致递归调用。
- // `cmd.exe` 无法 `call` 带 `\\?\` 前缀的 .cmd;dunce 同时剥离该前缀。
- let pnpm_abs = dunce::canonicalize(&pnpm).unwrap_or(pnpm);
- let shim_dir = dunce::canonicalize(&bin_dir).unwrap_or_else(|_| bin_dir.clone());
- if pnpm_abs.parent() != Some(shim_dir.as_path()) {
- envs.insert(
- "DSH_PNPM".to_string(),
- pnpm_abs.to_string_lossy().into_owned(),
- );
+ // 显式注入绝对路径,避免子进程在不同 PATH/CWD 下重新发现失败。
+ // Unix 保留 mise 依赖 argv[0] 的 shim 链接;Windows 仍解析连接点并剥离
+ // `\\?\`。同时防御性排除应用自身 shim,避免递归调用。
+ if let Some(pnpm_value) = cli::pnpm_env_value(&pnpm, &bin_dir) {
+ envs.insert("DSH_PNPM".to_string(), pnpm_value);
}
}
diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rs
index 81a96aa7..eee49829 100644
--- a/src-tauri/src/service/workflow/mod.rs
+++ b/src-tauri/src/service/workflow/mod.rs
@@ -873,11 +873,13 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
// 直接注入探测到的绝对路径,避免 dsh-market 的 pnpm --version 落到自身 shim
// 后又因 PATH 看不到真正的 pnpm(issue #139)。
if let Some(user_pnpm) = crate::service::cli::find_user_pnpm(&app_handle) {
- let pnpm_abs = dunce::canonicalize(&user_pnpm).unwrap_or(user_pnpm);
- let shim_dir = dunce::canonicalize(crate::service::cli::get_bin_dir(&app_handle))
- .unwrap_or_else(|_| crate::service::cli::get_bin_dir(&app_handle));
- if pnpm_abs.parent() != Some(shim_dir.as_path()) {
- envs.insert("DSH_PNPM".to_string(), pnpm_abs.to_string_lossy().into_owned());
+ // Unix mise shim 依赖调用路径中的 argv[0];只做字面绝对化,不能解析
+ // `pnpm -> mise` 链接。Windows 仍由同一辅助函数处理连接点与 `\\?\`。
+ if let Some(pnpm_value) = crate::service::cli::pnpm_env_value(
+ &user_pnpm,
+ &crate::service::cli::get_bin_dir(&app_handle),
+ ) {
+ envs.insert("DSH_PNPM".to_string(), pnpm_value);
}
}