DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(plugin): 消除 pnpm shim 互相转发死循环导致的启动永久卡死
ruan.lj50a7b1c6e47e
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex de7101ab..d446ce6c 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -64,6 +64,10 @@ pub fn run() {// 残留并把原生模块 DLL(如 sharp 的 libvips-42.dll)锁在内存,// 下次启动重新解压时会失败(Windows os error 32)tauri::RunEvent::Exit => {+ // 进行中的插件安装子进程是独立进程组,父进程退出不会连带回收;+ // 不显式结束就会留下占着档案 / pnpm store 的孤儿,让下一次启动+ // 永久卡在安装阶段(且日志无任何输出)。必须先于其它收尾动作。+ service::plugin::terminate_active_installs_blocking();let setting = config::get_store_dat_setting(app_handle);if setting.installed {service::workflow::stop_on_exit(app_handle);diff --git a/src-tauri/src/service/cli/shim/build.rs b/src-tauri/src/service/cli/shim/build.rsindex 2299c1b1..2143b675 100644--- a/src-tauri/src/service/cli/shim/build.rs+++ b/src-tauri/src/service/cli/shim/build.rs@@ -189,6 +189,7 @@ if defined DSH_PNPM (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.+:user_searchset "SELF_PREFIX=%~dp0"set "SELF_PREFIX=%SELF_PREFIX:~0,-1%"set "USER_PNPM="@@ -210,10 +211,18 @@ if defined USER_PNPM goto :use_usergoto :after_user:use_selected+rem Re-entry guard: DSH_PNPM may itself be a shim that resolves back through PATH+rem into this file; forwarding twice would exec the two shims into each other+rem forever and the installer child would never exit. Once forwarded, fall back+rem to the PATH search and then to the bundled pnpm.+if "%DSH_PNPM_SHIM_GUARD%"=="1" goto :user_search+set "DSH_PNPM_SHIM_GUARD=1"call "%DSH_PNPM%" %*exit /b %ERRORLEVEL%:use_user+if "%DSH_PNPM_SHIM_GUARD%"=="1" goto :after_user+set "DSH_PNPM_SHIM_GUARD=1"call "%USER_PNPM%" %*exit /b %ERRORLEVEL%@@ -266,19 +275,25 @@ if (-not $systemGitWorks) {{$useBundled = $env:DSH_PREFER_BUNDLED_PNPM -eq '1' -and (Test-Path -LiteralPath $pnpmBin -PathType Leaf)-# 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-}}+# Re-entry guard: DSH_PNPM, or the first pnpm found on PATH, may itself be a shim+# that resolves back through PATH into this file; forwarding twice would exec the+# two shims into each other forever and the installer child would never exit.+# Once forwarded, skip user resolution and use the bundled pnpm.+if (-not $useBundled -and $env:DSH_PNPM_SHIM_GUARD -ne '1') {{+ # Use the exact user pnpm discovered by the desktop app.+ if ($env:DSH_PNPM -and (Test-Path -LiteralPath $env:DSH_PNPM -PathType Leaf)) {{+ $env:DSH_PNPM_SHIM_GUARD = '1'+ & $env:DSH_PNPM @args+ exit $LASTEXITCODE+ }}-# Prefer a user-installed pnpm (skip our own shim dir), fall back to bundled.-if (-not $useBundled) {{+ # 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 1if ($userPnpm) {{+ $env:DSH_PNPM_SHIM_GUARD = '1'& $userPnpm.Source @argsexit $LASTEXITCODE}}@@ -318,13 +333,20 @@ if [ "$DSH_PREFER_BUNDLED_PNPM" = "1" ] && [ -f "$PNPM_BIN" ]; thenUSE_BUNDLED=1fi-# 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.-if [ -z "$USE_BUNDLED" ]; then+# Re-entry guard: DSH_PNPM, or the first pnpm found on PATH, may itself be a shim+# that resolves back through PATH into this file (mise shims exec whatever `pnpm`+# PATH resolves to). Forwarding twice would then exec the two shims into each+# other forever, so the installer child never exits and the app hangs with no+# output at all. Once forwarded, skip user resolution and use the bundled pnpm.+if [ -z "$USE_BUNDLED" ] && [ "$DSH_PNPM_SHIM_GUARD" != "1" ]; then+ # Use the exact user pnpm discovered by the desktop app unless bundled was requested.+ if [ -n "$DSH_PNPM" ] && [ -x "$DSH_PNPM" ]; then+ DSH_PNPM_SHIM_GUARD=1+ export DSH_PNPM_SHIM_GUARD+ 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@@ -332,6 +354,8 @@ if [ -z "$USE_BUNDLED" ]; thencontinuefiif [ -x "$dir/pnpm" ]; then+ DSH_PNPM_SHIM_GUARD=1+ export DSH_PNPM_SHIM_GUARDexec "$dir/pnpm" "$@"fidone@@ -740,6 +764,109 @@ mod tests {let _ = std::fs::remove_dir_all(dir);}+ /// 三个平台的 pnpm shim 都必须带重入保护(见各模板注释)。+ #[test]+ fn pnpm_shims_guard_against_reentrant_forwarding() {+ let app_dir = sample_app_dir();+ for (name, content) in [+ ("pnpm.sh", build_pnpm_sh_shim(&app_dir)),+ ("pnpm.cmd", build_pnpm_cmd_shim(&app_dir)),+ ("pnpm.ps1", build_pnpm_ps1_shim(&app_dir)),+ ] {+ assert!(+ content.contains("DSH_PNPM_SHIM_GUARD"),+ "{name}: missing re-entry guard"+ );+ }+ // cmd 的转发目标改用标签回跳,两个 `:use_*` 都必须受保护(各含一次判断 + 一次置位)。+ let cmd = build_pnpm_cmd_shim(&app_dir);+ assert_eq!(cmd.matches("\n:user_search").count(), 1);+ assert_eq!(cmd.matches("DSH_PNPM_SHIM_GUARD").count(), 4);+ }++ /// 回归:`DSH_PNPM` 指向的 shim 若按 PATH 解析回本 shim(mise shims 的真实+ /// 行为,见 `cli::path::pnpm` 的 mise 目录回退),没有重入保护时两者会互相+ /// `exec` 形成死循环——安装子进程永不退出,应用表现为永久卡在+ /// 「Loading internal plugins…」且后端日志一行输出都没有。有保护时必须有界+ /// 结束并回退捆绑 pnpm。+ #[cfg(unix)]+ #[test]+ fn pnpm_sh_shim_breaks_self_referential_forward_loop() {+ use std::os::unix::fs::PermissionsExt;++ let dir = temp_dir("pnpm-sh-reentry");+ 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 bin_dir = dir.join("bin");+ let loop_dir = dir.join("loop-bin");+ std::fs::create_dir_all(&bin_dir).unwrap();+ std::fs::create_dir_all(&loop_dir).unwrap();++ let node = dir.join("node");+ std::fs::write(&node, "#!/bin/sh\necho BUNDLED \"$@\"\n").unwrap();+ // 本 shim 落在 PATH 中,等价于桌面端把自身 shim 目录前置到子进程 PATH。+ let shim = bin_dir.join("pnpm");+ std::fs::write(&shim, build_pnpm_sh_shim(&app_dir)).unwrap();+ // 模拟 mise shim:自身没有实现,只把调用交回 PATH 上的 pnpm。+ let forwarder = loop_dir.join("pnpm");+ std::fs::write(&forwarder, "#!/bin/sh\nexec pnpm \"$@\"\n").unwrap();++ for path in [&node, &shim, &forwarder] {+ let mut permissions = std::fs::metadata(path).unwrap().permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(path, permissions).unwrap();+ }++ let path_env = std::env::join_paths([+ bin_dir.clone(),+ loop_dir.clone(),+ PathBuf::from("/usr/bin"),+ PathBuf::from("/bin"),+ ])+ .unwrap();+ let child = std::process::Command::new(&shim)+ .arg("reentry")+ .env("PATH", &path_env)+ .env("DSH_NODE", &node)+ .env("DSH_PNPM", &forwarder)+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::null())+ .spawn()+ .unwrap();+ // exec 保留 pid,因此超时后按 pid 一定杀得中循环中的那个进程。+ let pid = child.id();++ let (sender, receiver) = std::sync::mpsc::channel();+ let waiter = std::thread::spawn(move || {+ let output = child.wait_with_output();+ let _ = sender.send(output);+ });+ let output = match receiver.recv_timeout(std::time::Duration::from_secs(20)) {+ Ok(output) => output.unwrap(),+ Err(_) => {+ let _ = std::process::Command::new("kill")+ .args(["-9", &pid.to_string()])+ .status();+ let _ = waiter.join();+ let _ = std::fs::remove_dir_all(&dir);+ panic!(+ "self-referential pnpm shim chain must terminate instead of looping forever"+ );+ }+ };+ let _ = waiter.join();++ assert!(output.status.success());+ assert!(+ String::from_utf8_lossy(&output.stdout).contains("BUNDLED"),+ "re-entered shim must fall back to the bundled pnpm"+ );+ let _ = std::fs::remove_dir_all(dir);+ }+/// issue #121:桌面端注入的 DSH_NODE(预检解析出的 node 路径)必须在/// 本地 node / 捆绑运行时解析之前被采用——shim 与应用预检保持一致。#[test]diff --git a/src-tauri/src/service/plugin/cancel.rs b/src-tauri/src/service/plugin/cancel.rsindex 46b83d72..753bdb6d 100644--- a/src-tauri/src/service/plugin/cancel.rs+++ b/src-tauri/src/service/plugin/cancel.rs@@ -24,18 +24,40 @@ pub(crate) async fn terminate_active_install() -> bool {log::debug!("plugin install cancel: no active install process");return false;}- tauri::async_runtime::spawn_blocking(move || {- let mut all_terminated = true;- for (_, pid) in active {- all_terminated &= terminate_pid_tree(pid);- }- all_terminated- })- .await- .unwrap_or_else(|e| {- log::warn!("plugin install cancel task failed: {e}");- false- })+ tauri::async_runtime::spawn_blocking(move || terminate_pid_trees(active))+ .await+ .unwrap_or_else(|e| {+ log::warn!("plugin install cancel task failed: {e}");+ false+ })+}++/// 退出前同步回收所有进行中的插件安装进程树(`RunEvent::Exit` 调用)。+///+/// 安装子进程以独立进程组启动(`process_group(0)`),父进程退出**不会**连带结束+/// 它们;而取消只由前端命令(`cancel_preinstall_plugins` / `cancel_internal_plugins`)+/// 触发。用户在安装看起来毫无进展时关窗,留下的孤儿会继续占着档案与 pnpm store,+/// 下一次启动的安装便排在它后面——表现为永久卡在「Loading internal plugins…」且+/// 后端日志一行输出都没有。回收必须在退出路径上显式做。+pub(crate) fn terminate_active_installs_blocking() -> bool {+ let active = super::process::active_plugin_processes();+ if active.is_empty() {+ return false;+ }+ log::warn!(+ "plugin install cancel: reaping {} in-flight install process(es) before exit",+ active.len()+ );+ terminate_pid_trees(active)+}++/// 逐个结束进程树;单个失败不影响其余,返回是否全部成功。+fn terminate_pid_trees(active: Vec<(super::process::ProcessOwner, u32)>) -> bool {+ let mut all_terminated = true;+ for (_, pid) in active {+ all_terminated &= terminate_pid_tree(pid);+ }+ all_terminated}pub(crate) async fn terminate_owned_install(owner: super::process::ProcessOwner) -> bool {diff --git a/src-tauri/src/service/plugin/install/pnpm.rs b/src-tauri/src/service/plugin/install/pnpm.rsindex 1f15c502..aef4e38b 100644--- a/src-tauri/src/service/plugin/install/pnpm.rs+++ b/src-tauri/src/service/plugin/install/pnpm.rs@@ -131,7 +131,7 @@ async fn user_pnpm_major_version_bounded(return Ok(None);};let node = config::get_node_binary_path(app_handle);- let mut command = pnpm_probe_command(&pnpm, Some(&node));+ let mut command = pnpm_probe_command(&pnpm, Some(&node), Some(&cli::get_bin_dir(app_handle)));#[cfg(unix)]{use std::os::unix::process::CommandExt;@@ -555,7 +555,7 @@ pub(crate) fn pnpm_major_version_at(pnpm: &Path) -> Option<u32> {/// Node/pnpm 安装,而 corepack 的 `pnpm.cmd` 需要通过 PATH 调用 `node`;探测时/// 必须注入桌面端已经选定的 Node 目录,否则会把健康 pnpm 误判为不可用(issue #182)。fn pnpm_major_version_at_with_node(pnpm: &Path, node: Option<&Path>) -> Option<u32> {- let output = match pnpm_probe_command(pnpm, node).output() {+ let output = match pnpm_probe_command(pnpm, node, None).output() {Ok(output) => output,Err(error) => {log::warn!(@@ -578,12 +578,26 @@ fn pnpm_major_version_at_with_node(pnpm: &Path, node: Option<&Path>) -> Option<u/// 让这类读取立刻拿到 EOF,探测必定有界结束。有界探测(子进程 + 超时强杀)与/// 无界探测([`user_pnpm_major_version`] 的 `output()`)共用本函数,避免两套/// 探测策略再次分叉。-fn pnpm_probe_command(pnpm: &Path, node: Option<&Path>) -> std::process::Command {+///+/// `bin_dir` 为桌面端 shim 目录:传入即复现安装子进程的解析条件(见+/// [`pnpm_probe_path`]);按精确路径探测(`verify`)传 None。+fn pnpm_probe_command(+ pnpm: &Path,+ node: Option<&Path>,+ bin_dir: Option<&Path>,+) -> std::process::Command {let mut command = std::process::Command::new(pnpm);command.arg("--version");- if let Some(path) = pnpm_probe_path(pnpm, node) {+ if let Some(path) = pnpm_probe_path(pnpm, node, bin_dir) {command.env("PATH", path);}+ // 探测必须与安装走同一套解析:`build_plugin_envs` 会把候选路径写进 `DSH_PNPM`+ // 并把桌面端 shim 目录前置,`dsh plugin` 经 PATH 命中的正是那个 shim。只测+ // 候选自身会漏掉这条间接层——探测顺利拿到版本,实际安装却在两个 shim 之间+ // 反复 exec 永不返回(症状:日志停在 `dsh plugin install started` 再无下文)。+ if bin_dir.is_some() {+ command.env("DSH_PNPM", pnpm);+ }command.stdin(std::process::Stdio::null());// 打包版是 GUI 进程(无控制台):版本探测不能弹出可见黑窗。#[cfg(windows)]@@ -609,14 +623,26 @@ fn parse_pnpm_major_output(pnpm: &Path, output: &std::process::Output) -> Optionstdout.split('.').next()?.trim().parse::<u32>().ok()}-/// 构建 pnpm 探测专用 PATH:用户 pnpm 所在目录和选定 Node 目录前置,其余环境保留。-fn pnpm_probe_path(pnpm: &Path, node: Option<&Path>) -> Option<OsString> {+/// 构建 pnpm 探测专用 PATH:选定 Node 目录、桌面端 shim 目录、用户 pnpm 所在+/// 目录依次前置,其余环境保留。+///+/// `bin_dir` 必须参与:`build_plugin_envs` 把它放在子进程 PATH 首位,`dsh plugin`+/// 的 `spawnSync("pnpm")` 命中的就是它。探测少了这一层,就会在一个「自身没有实现、+/// 只按 PATH 转交」的用户 shim(如 mise shims)上得出与真实安装相反的结论。+fn pnpm_probe_path(+ pnpm: &Path,+ node: Option<&Path>,+ bin_dir: Option<&Path>,+) -> Option<OsString> {let mut paths = Vec::new();// 选定 Node 必须位于 pnpm shim 目录之前:corepack 目录可能残留另一份 node,// bare `node` 应与桌面端预检和后续插件命令使用同一运行时。if let Some(parent) = node.and_then(Path::parent) {paths.push(parent.to_path_buf());}+ if let Some(bin_dir) = bin_dir {+ paths.push(bin_dir.to_path_buf());+ }if let Some(parent) = pnpm.parent() {paths.push(parent.to_path_buf());}@@ -716,19 +742,20 @@ fn read_modules_yaml(app_handle: &AppHandle) -> Option<String> {/// 从 `.modules.yaml` 文本解析 `storeDir`(纯函数,便于单测)。///-/// 兼容 pnpm 的两种写法:未加引号的裸路径(Windows 反斜杠、Unix 正斜杠),以及-/// 含特殊字符时 YAML 双引号包裹 + `\\` 转义的形式。+/// pnpm 落盘该文件可能是 YAML 块结构,也可能是 **JSON 流结构**(pnpm 11 实测输出+/// `{ "storeDir": "..." }`)。旧实现按行前缀匹配裸 `storeDir:`,遇到 JSON 形态+/// 恒定返回 None,于是 `profile_store_major` 永远未知:store 主版本选版、+/// `reset_incompatible_modules_metadata` 与 `pnpm_config_store_dir` 下传全部静默+/// 失效(症状是 `ensure_pnpm` 打「for plugin install」而不是「matching profile+/// store」、`build_plugin_envs` 从不打 store 固定日志)。JSON 是 YAML 的子集,+/// 统一按 YAML 解析即可覆盖两种形态;转义也交给解析器,不再手工替换 `\\`。fn parse_store_dir_from_modules_yaml(content: &str) -> Option<String> {- let raw = content- .lines()- .find_map(|line| line.trim().strip_prefix("storeDir:").map(str::trim))?- .trim_matches(['"', '\''])- .trim();+ let value: serde_yaml::Value = serde_yaml::from_str(content).ok()?;+ let raw = value.get("storeDir")?.as_str()?.trim();if raw.is_empty() {return None;}- // YAML 双引号标量里的 `\\` 表示单个反斜杠;裸路径不会出现连续反斜杠,替换是安全的。- Some(raw.replace("\\\\", "\\"))+ Some(raw.to_string())}/// 从 `.modules.yaml` 文本解析 store 主版本(纯函数,便于单测)。@@ -850,7 +877,7 @@ mod tests {permissions.set_mode(0o700);std::fs::set_permissions(&pnpm, permissions).unwrap();- let mut child = pnpm_probe_command(&pnpm, None)+ let mut child = pnpm_probe_command(&pnpm, None, None).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn()@@ -1061,6 +1088,41 @@ virtualStoreDir: node_modules/.pnpm);}+ /// 回归:pnpm 11 把 `.modules.yaml` 写成 JSON 流结构(`"storeDir": "..."`)。+ /// 旧实现按行前缀匹配裸 `storeDir:`,对真实文件恒定失败,导致 store 主版本+ /// 感知、元数据重置与 store 下传全部静默失效。+ #[test]+ fn store_dir_parsed_from_json_modules_yaml() {+ let content = r#"{+ "hoistPattern": [+ "*"+ ],+ "layoutVersion": 5,+ "storeDir": "/Users/ruan/Library/pnpm/store/v11",+ "virtualStoreDir": "node_modules/.pnpm"+}"#;+ assert_eq!(+ parse_store_dir_from_modules_yaml(content).as_deref(),+ Some("/Users/ruan/Library/pnpm/store/v11")+ );+ assert_eq!(parse_store_major_from_modules_yaml(content), Some(11));++ // JSON 双引号里的 `\\` 由解析器还原为单个反斜杠(Windows 档案同样命中)。+ let windows = r#"{"storeDir": "C:\\Users\\test\\AppData\\Local\\pnpm\\store\\v10"}"#;+ assert_eq!(+ parse_store_dir_from_modules_yaml(windows).as_deref(),+ Some(r"C:\Users\test\AppData\Local\pnpm\store\v10")+ );+ assert_eq!(parse_store_major_from_modules_yaml(windows), Some(10));++ // 合法 JSON 但没有 storeDir(或值不是字符串)→ 仍视为未知+ assert_eq!(parse_store_dir_from_modules_yaml("{}"), None);+ assert_eq!(+ parse_store_dir_from_modules_yaml(r#"{"storeDir": 5}"#),+ None+ );+ }+#[test]fn store_base_dir_strips_trailing_pnpm_version_segment() {assert_eq!(diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex ae2f9d23..c6048cf8 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -50,6 +50,7 @@ pub mod watch;pub(crate) use crate::service::profile::ensure_profile_pnpm_policy;pub use cancel::cancel;+pub(crate) use cancel::terminate_active_installs_blocking;pub(crate) use install::harness_prefer_bundled_pnpm;pub(crate) use install::uninstall_deprecated_plugins;pub use install::{install, remove, update};