Skip to content

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

fix(plugin): 修复 Windows scoped 包链接失败并让未确认的 pnpm 清理终止启动(#1002) (#1026)

Mao Mr99ebd590a107
diff --git a/src-tauri/src/service/core/runtime.rs b/src-tauri/src/service/core/runtime.rs
index 587d3487..c7f7f4c7 100644
--- a/src-tauri/src/service/core/runtime.rs
+++ b/src-tauri/src/service/core/runtime.rs
@@ -812,7 +812,7 @@ fn create_directory_junction(source: &Path, destination: &Path) -> std::io::Resu
// dunce::simplified 去掉 canonicalize 产生的 verbatim(`\\?\`)前缀,
// 避免双重前缀导致内核解析失败。
let simplified = dunce::simplified(source);
- let print_name = simplified.to_string_lossy();
+ let print_name = simplified.to_string_lossy().replace('/', "\\");
let substitute_name = if print_name.starts_with("\\\\") {
format!(r"\??\UNC\{}", print_name.trim_start_matches('\\'))
} else {
@@ -2005,20 +2005,21 @@ mod tests {
/// 确定性覆盖 junction 回退路径:无论本机是否启用开发者模式/管理员权限,
/// 直接构造 junction 并断言其可解析、可删除,且与 ensure_package_link 的
- /// matches 幂等检查兼容。
+ /// matches 幂等检查兼容。包路径带 scoped 包名的正斜杠(真实安装形态):
+ /// `\\??\\` 替换名不经过 Win32 分隔符归一化,混用分隔符必须仍可建链。
#[cfg(windows)]
#[test]
- fn create_directory_junction_is_resolvable_and_idempotent() {
+ fn create_directory_junction_accepts_mixed_separators_and_is_idempotent() {
let root = std::env::temp_dir().join(format!("dsh-junction-direct-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
- let source = root.join("source-pkg");
+ let source = root.join("@scope/package");
std::fs::create_dir_all(&source).unwrap();
std::fs::write(source.join("package.json"), r#"{"name":"dsh-tauri"}"#).unwrap();
let destination = root.join("node_modules").join("dsh-tauri");
std::fs::create_dir_all(destination.parent().unwrap()).unwrap();
let canonical_source = source.canonicalize().unwrap();
- create_directory_junction(&canonical_source, &destination)
+ create_directory_junction(&source, &destination)
.unwrap_or_else(|e| panic!("junction must be creatable without privileges: {e}"));
let metadata = std::fs::symlink_metadata(&destination).unwrap();
diff --git a/src-tauri/src/service/plugin/cancel.rs b/src-tauri/src/service/plugin/cancel.rs
index 621bded7..5de1cc8b 100644
--- a/src-tauri/src/service/plugin/cancel.rs
+++ b/src-tauri/src/service/plugin/cancel.rs
@@ -9,6 +9,8 @@
use serde::Serialize;
use tauri::{AppHandle, Emitter, Manager};
+use super::process::{ActivePluginProcess, ProcessOwner};
+
/// 前端监听“安装已取消”事件名
const PREINSTALL_CANCEL_EVENT: &str = "preinstall-cancelled";
@@ -52,24 +54,69 @@ pub(crate) fn terminate_active_installs_blocking() -> bool {
}
/// 逐个结束进程树;单个失败不影响其余,返回是否全部成功。
-fn terminate_pid_trees(active: Vec<(super::process::ProcessOwner, u32)>) -> bool {
+fn terminate_pid_trees(active: Vec<(ProcessOwner, ActivePluginProcess)>) -> bool {
let mut all_terminated = true;
- for (_, pid) in active {
- all_terminated &= terminate_pid_tree(pid);
+ for (owner, process) in active {
+ let terminate = if process.child.is_some() {
+ terminate_probe_tree
+ } else {
+ terminate_pid_tree
+ };
+ all_terminated &= terminate_registered_process(owner, &process, terminate);
}
all_terminated
}
-pub(crate) async fn terminate_owned_install(owner: super::process::ProcessOwner) -> bool {
- let Some(pid) = super::process::active_plugin_pid(owner) else {
- return false;
+pub(crate) fn terminate_registered_process(
+ owner: ProcessOwner,
+ process: &ActivePluginProcess,
+ terminate: impl FnOnce(u32) -> bool,
+) -> bool {
+ let Some(child) = &process.child else {
+ return terminate(process.pid);
};
- tauri::async_runtime::spawn_blocking(move || terminate_pid_tree(pid))
- .await
- .unwrap_or_else(|e| {
- log::warn!("owned plugin install cancel task failed: {e}");
+ let mut child = child.lock().unwrap_or_else(|error| error.into_inner());
+ let terminated = match child.try_wait() {
+ Ok(Some(_)) => return true,
+ Ok(None) => {
+ let tree_killed = terminate(process.pid);
+ let _ = child.kill();
+ tree_killed
+ }
+ Err(error) => {
+ log::warn!(
+ "registered plugin process wait failed for pid {}: {error}",
+ process.pid
+ );
false
- })
+ }
+ };
+ if !terminated {
+ super::process::mark_process_cleanup_failed(
+ owner,
+ "PNPM_PROBE_TREE_CLEANUP_FAILED: pnpm version probe process tree termination was not confirmed".to_string(),
+ );
+ }
+ terminated
+}
+
+pub(crate) async fn terminate_owned_install(owner: ProcessOwner) -> bool {
+ let Some(process) = super::process::active_plugin_process(owner) else {
+ return false;
+ };
+ tauri::async_runtime::spawn_blocking(move || {
+ let terminate = if process.child.is_some() {
+ terminate_probe_tree
+ } else {
+ terminate_pid_tree
+ };
+ terminate_registered_process(owner, &process, terminate)
+ })
+ .await
+ .unwrap_or_else(|e| {
+ log::warn!("owned plugin install cancel task failed: {e}");
+ false
+ })
}
#[cfg(windows)]
@@ -105,6 +152,14 @@ pub(crate) fn terminate_pid_tree(pid: u32) -> bool {
direct
}
+#[cfg(windows)]
+pub(crate) use terminate_pid_tree as terminate_probe_tree;
+
+#[cfg(not(windows))]
+pub(crate) fn terminate_probe_tree(pid: u32) -> bool {
+ unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) == 0 }
+}
+
/// 取消正在进行的预装插件安装。
pub async fn cancel(app_handle: &AppHandle) {
terminate_active_install().await;
@@ -136,8 +191,92 @@ mod tests {
command.spawn().unwrap()
}
+ #[tokio::test]
+ async fn stale_probe_snapshot_never_kills_after_the_child_is_reaped() {
+ use std::sync::{Arc, Mutex};
+
+ let _test_guard = super::super::process::TEST_PROCESS_LOCK.lock().await;
+ #[cfg(windows)]
+ let child = {
+ use std::os::windows::process::CommandExt;
+ std::process::Command::new("cmd.exe")
+ .creation_flags(0x08000000)
+ .args(["/D", "/C", "exit 0"])
+ .spawn()
+ .unwrap()
+ };
+ #[cfg(unix)]
+ let child = std::process::Command::new("sh")
+ .args(["-c", "exit 0"])
+ .spawn()
+ .unwrap();
+ let child = Arc::new(Mutex::new(child));
+ let owner = super::super::process::new_process_owner();
+ let guard = super::super::process::PidGuard::set_child(owner, &child);
+ let snapshot = super::super::process::active_plugin_processes()
+ .into_iter()
+ .find(|(active_owner, _)| *active_owner == owner)
+ .unwrap()
+ .1;
+ assert!(child.lock().unwrap().wait().unwrap().success());
+ drop(guard);
+ let mut killed = false;
+ assert!(terminate_registered_process(owner, &snapshot, |_| {
+ killed = true;
+ true
+ }));
+ assert!(
+ !killed,
+ "a copied probe record must preserve the reaped child identity"
+ );
+ assert_eq!(super::super::process::active_plugin_pid(owner), None);
+ }
+
+ #[tokio::test]
+ async fn failed_probe_cancel_keeps_tree_failure_after_root_exit() {
+ use std::sync::{Arc, Mutex};
+
+ let _test_guard = super::super::process::TEST_PROCESS_LOCK.lock().await;
+ #[cfg(windows)]
+ let mut command = {
+ use std::os::windows::process::CommandExt;
+ let mut command = std::process::Command::new("cmd.exe");
+ command
+ .creation_flags(0x08000000)
+ .args(["/D", "/C", "set /p token="]);
+ command
+ };
+ #[cfg(unix)]
+ let mut command = {
+ use std::os::unix::process::CommandExt;
+ let mut command = std::process::Command::new("sh");
+ command.args(["-c", "read -r token"]).process_group(0);
+ command
+ };
+ let child = Arc::new(Mutex::new(
+ command.stdin(std::process::Stdio::piped()).spawn().unwrap(),
+ ));
+ let owner = super::super::process::new_process_owner();
+ let guard = super::super::process::PidGuard::set_child(owner, &child);
+ let process = super::super::process::active_plugin_process(owner).unwrap();
+ let terminated = terminate_registered_process(owner, &process, |_| false);
+ {
+ let mut child = child.lock().unwrap();
+ let _ = child.kill();
+ child.wait().unwrap();
+ }
+ let failure = super::super::process::acquire_process_lock().await;
+ drop(guard);
+ super::super::process::clear_process_cleanup_failed(owner);
+ assert!(!terminated);
+ assert!(
+ matches!(failure, Err(reason) if reason.starts_with("PNPM_PROBE_TREE_CLEANUP_FAILED:"))
+ );
+ }
+
#[tokio::test]
async fn forced_cancel_kills_hung_child_and_releases_pid_slot() {
+ let _test_guard = super::super::process::TEST_PROCESS_LOCK.lock().await;
let mut child = spawn_hung_child();
let pid = child.id();
let owner = super::super::process::new_process_owner();
diff --git a/src-tauri/src/service/plugin/install/artifact.rs b/src-tauri/src/service/plugin/install/artifact.rs
index acfc014a..4d4c66fa 100644
--- a/src-tauri/src/service/plugin/install/artifact.rs
+++ b/src-tauri/src/service/plugin/install/artifact.rs
@@ -241,7 +241,7 @@ pub(super) async fn ensure_plugin_entry_built(
// 与 verify 修复路径同一套 store 主版本感知 pnpm 选择(捆绑版优先,不匹配
// 时回落用户 pnpm.exe),不硬编码单一 pnpm,避免「装了用户版却没捆绑版」
// 或 v10/v11 store 不兼容的假失败。
- let Some((program, pre_args)) = super::super::verify::pnpm_direct(app_handle) else {
+ let Some((program, pre_args)) = super::super::verify::pnpm_direct(app_handle).await? else {
return Err(format!(
"PNPM_NOT_FOUND: no usable pnpm (bundled or user) to rebuild plugin {id}"
));
diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rs
index 01f9c6e4..b0bbaaf3 100644
--- a/src-tauri/src/service/plugin/install/mod.rs
+++ b/src-tauri/src/service/plugin/install/mod.rs
@@ -70,7 +70,8 @@ pub(crate) use env::build_plugin_envs;
pub use inspect::inspect_specs;
pub(crate) use inspect::packument;
pub(crate) use pnpm::{
- bundled_pnpm_major, harness_prefer_bundled_pnpm, pnpm_major_version_at, profile_store_major,
+ bundled_pnpm_major, harness_prefer_bundled_pnpm, pnpm_major_version_at_bounded,
+ profile_store_major,
};
pub(crate) use single::uninstall_deprecated_plugins;
pub use single::{remove_many, update_many};
@@ -653,7 +654,9 @@ pub async fn allow_version_exemptions(
return Err("HARNESS_NOT_FOUND: dsh CLI missing".to_string());
}
- let envs = build_plugin_envs(app_handle, harness_prefer_bundled_pnpm(app_handle));
+ // 豁免分支不进 pnpm(见函数文档),这里不做 pnpm 就绪探测:探测失败不该
+ // 让一条本不需要 pnpm 的授权落不了地。
+ let envs = build_plugin_envs(app_handle, false);
let cwd = crate::service::core::active_core_dir(app_handle);
let profile = active_profile(app_handle);
let owner = new_process_owner();
diff --git a/src-tauri/src/service/plugin/install/pnpm.rs b/src-tauri/src/service/plugin/install/pnpm.rs
index c022a73a..516fd328 100644
--- a/src-tauri/src/service/plugin/install/pnpm.rs
+++ b/src-tauri/src/service/plugin/install/pnpm.rs
@@ -16,9 +16,11 @@ use std::io::Read;
use std::path::Path;
#[cfg(test)]
use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
use tauri::{AppHandle, Emitter, WebviewWindow};
use super::acquire_process_lock;
+use super::new_process_owner;
use super::profile_dir;
use super::PidGuard;
use super::PreinstallLogPayload;
@@ -28,7 +30,6 @@ use super::PREINSTALL_LOG_EVENT;
const MIN_TRUSTED_PNPM_MAJOR: u32 = 10;
const PNPM_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
const PNPM_PROBE_CLEANUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
-const PNPM_PROBE_REAP_RETRY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);
const PNPM_PROBE_REAP_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_millis(25);
const PNPM_PROBE_LIVENESS_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);
@@ -132,15 +133,33 @@ async fn user_pnpm_major_version_bounded(
let Some(pnpm) = cli::find_user_pnpm(app_handle) else {
return Ok(None);
};
- let node = config::get_node_binary_path(app_handle);
- let mut command = pnpm_probe_command(&pnpm, Some(&node), Some(&cli::get_bin_dir(app_handle)));
+ pnpm_major_version_at_bounded(
+ &pnpm,
+ Some(&config::get_node_binary_path(app_handle)),
+ Some(&cli::get_bin_dir(app_handle)),
+ owner,
+ )
+ .await
+}
+
+pub(crate) async fn pnpm_major_version_at_bounded(
+ pnpm: &Path,
+ node: Option<&Path>,
+ bin_dir: Option<&Path>,
+ owner: ProcessOwner,
+) -> Result<Option<u32>, String> {
+ let deadline = tokio::time::Instant::now() + PNPM_PROBE_TIMEOUT;
+ let mut command = pnpm_probe_command(pnpm, node, bin_dir);
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
-
- let process_guard = acquire_process_lock().await?;
+ let process_guard = tokio::time::timeout_at(deadline, acquire_process_lock())
+ .await
+ .map_err(|_| {
+ "PNPM_PROBE_LOCK_TIMEOUT: timed out waiting for the process lock".to_string()
+ })??;
let child = match command
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
@@ -148,152 +167,59 @@ async fn user_pnpm_major_version_bounded(
{
Ok(child) => child,
Err(error) => {
- log::warn!(
- "pnpm version probe failed to spawn {}: {error}",
- pnpm.display()
- );
+ log_probe_fallback(pnpm, "spawn", error);
return Ok(None);
}
};
- let pid = child.id();
- let pid_guard = PidGuard::set(owner, pid);
- let mut waiter = tauri::async_runtime::spawn_blocking(move || {
- let mut child = child;
- let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
- wait_for_probe_output(&mut child)
- }))
- .unwrap_or_else(|_| {
- super::super::cancel::terminate_pid_tree(pid);
- ProbeWaitResult::CleanupPending {
- pid,
- reason: format!(
- "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe pid {pid} panicked before cleanup completed"
- ),
- }
- });
- match result {
- ProbeWaitResult::Finished(result) => ProbeTaskResult::Finished(result),
- ProbeWaitResult::CleanupPending { pid, reason } => {
- ProbeTaskResult::CleanupPending { child, pid, reason }
- }
- }
- });
-
- let output = match tokio::time::timeout(PNPM_PROBE_TIMEOUT, &mut waiter).await {
- Ok(joined) => {
- let Some(task) = probe_task_or_fallback(&pnpm, joined) else {
- let reason =
- "PNPM_PROBE_WAIT_TASK_FAILED: pnpm version probe wait task failed".to_string();
- monitor_orphaned_probe_pid(owner, pid, reason, process_guard, pid_guard);
- return Ok(None);
- };
- match task {
- ProbeTaskResult::Finished(waited) => {
- match probe_output_or_fallback(&pnpm, waited)? {
- Some(output) => output,
- None => return Ok(None),
- }
- }
- ProbeTaskResult::CleanupPending { child, pid, reason } => {
- let pending = ProbeCleanupPending {
- child,
- pid,
- reason,
- owner,
- _process_guard: process_guard,
- _pid_guard: pid_guard,
- };
- let reason = pending.reason.clone();
- monitor_probe_cleanup(pending);
- return Err(reason);
+ let child = Arc::new(Mutex::new(child));
+ let pid_guard = PidGuard::set_child(owner, &child);
+ let pending = ProbeCleanupPending {
+ child,
+ owner,
+ _process_guard: process_guard,
+ _pid_guard: pid_guard,
+ };
+ let pnpm = pnpm.to_path_buf();
+ // 调用方取消只脱离等待;进程与守卫由独立任务持有到回收完成。
+ tauri::async_runtime::spawn(async move {
+ let child = pending.child.clone();
+ let mut waiter =
+ tauri::async_runtime::spawn_blocking(move || wait_for_probe_output(&child));
+ let (reason, waiter) = match tokio::time::timeout_at(deadline, &mut waiter).await {
+ Ok(Ok(Ok(output))) => {
+ if let Some(reason) = super::super::process::process_cleanup_failure(pending.owner)
+ {
+ (reason, None)
+ } else {
+ pending.release();
+ return Ok(parse_pnpm_major_output(&pnpm, &output));
}
}
- }
- Err(_) => {
- let reason = format!(
- "PNPM_PROBE_TIMEOUT: pnpm version probe exceeded {} seconds",
- PNPM_PROBE_TIMEOUT.as_secs()
- );
- log::error!("{reason}");
- super::super::process::mark_process_cleanup_failed(owner, reason.clone());
- super::super::cancel::terminate_owned_install(owner).await;
- let cleanup = match tokio::time::timeout(PNPM_PROBE_CLEANUP_TIMEOUT, &mut waiter).await
- {
- Ok(cleanup) => cleanup,
- Err(_) => {
- let cleanup_reason =
- "PNPM_PROBE_CLEANUP_TIMEOUT: pnpm version probe did not exit after forced termination"
- .to_string();
- monitor_probe_wait_task(
- waiter,
- owner,
- pid,
- cleanup_reason.clone(),
- process_guard,
- pid_guard,
- );
- return Err(cleanup_reason);
- }
- };
- match cleanup {
- Ok(ProbeTaskResult::Finished(_)) => {
- // 强杀 + 回收完成意味着没有遗留进程,只是这次探测没拿到结果:
- // 按「用户 pnpm 不可用」降级,由 ensure_pnpm 回退捆绑版,
- // 而不是把慢探测升级成整次插件安装失败(issue #449)。
- super::super::process::clear_process_cleanup_failed(owner);
- return Ok(probe_timeout_or_fallback(&pnpm, reason));
- }
- Ok(ProbeTaskResult::CleanupPending { child, pid, reason }) => {
- let pending = ProbeCleanupPending {
- child,
- pid,
- reason,
- owner,
- _process_guard: process_guard,
- _pid_guard: pid_guard,
- };
- let cleanup_reason = pending.reason.clone();
- monitor_probe_cleanup(pending);
- return Err(cleanup_reason);
- }
- Err(error) => {
- monitor_orphaned_probe_pid(
- owner,
- pid,
- format!(
- "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe wait task failed during cleanup: {error}"
- ),
- process_guard,
- pid_guard,
- );
- return Err(format!(
- "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe wait task failed during cleanup: {error}"
- ));
- }
+ Ok(joined) => {
+ let reason = match joined {
+ Ok(Err(error)) => format!("PNPM_PROBE_OUTPUT_FAILED: {error}"),
+ Err(error) => format!("PNPM_PROBE_WAIT_TASK_FAILED: {error}"),
+ Ok(Ok(_)) => unreachable!(),
+ };
+ (reason, None)
}
- }
- };
- Ok(parse_pnpm_major_output(&pnpm, &output))
-}
-
-enum ProbeWaitResult {
- Finished(std::io::Result<std::process::Output>),
- CleanupPending { pid: u32, reason: String },
-}
-
-enum ProbeTaskResult {
- Finished(std::io::Result<std::process::Output>),
- CleanupPending {
- child: std::process::Child,
- pid: u32,
- reason: String,
- },
+ Err(_) => (
+ format!(
+ "PNPM_PROBE_TIMEOUT: pnpm version probe exceeded {} seconds",
+ PNPM_PROBE_TIMEOUT.as_secs()
+ ),
+ Some(waiter),
+ ),
+ };
+ cleanup_probe(pending, waiter, reason.clone()).await?;
+ Ok(probe_timeout_or_fallback(&pnpm, reason))
+ })
+ .await
+ .map_err(|error| format!("PNPM_PROBE_TASK_FAILED: {error}"))?
}
struct ProbeCleanupPending {
- child: std::process::Child,
- pid: u32,
- reason: String,
+ child: Arc<Mutex<std::process::Child>>,
owner: ProcessOwner,
_process_guard: tokio::sync::OwnedMutexGuard<()>,
_pid_guard: PidGuard,
@@ -302,181 +228,147 @@ struct ProbeCleanupPending {
impl ProbeCleanupPending {
fn release(self) {
let Self {
- child,
owner,
_process_guard,
_pid_guard,
..
} = self;
super::super::process::release_process_cleanup(owner, _pid_guard, _process_guard);
- drop(child);
}
}
-fn wait_for_probe_output(child: &mut std::process::Child) -> ProbeWaitResult {
- let pid = child.id();
- let stdout = child.stdout.take();
- let stderr = child.stderr.take();
- let stdout_reader = match std::thread::Builder::new()
- .name("pnpm-probe-stdout".to_string())
- .spawn(move || read_probe_pipe(stdout))
- {
- Ok(reader) => reader,
- Err(error) => return reap_probe_after_wait_failure(child, pid, error),
- };
- let stderr_reader = match std::thread::Builder::new()
- .name("pnpm-probe-stderr".to_string())
- .spawn(move || read_probe_pipe(stderr))
- {
- Ok(reader) => reader,
- Err(error) => return reap_probe_after_wait_failure(child, pid, error),
- };
-
- let status = match child.wait() {
- Ok(status) => status,
- Err(error) => return reap_probe_after_wait_failure(child, pid, error),
- };
- let stdout = match join_probe_reader(stdout_reader) {
- Ok(stdout) => stdout,
- Err(error) => return ProbeWaitResult::Finished(Err(error)),
+fn wait_for_probe_output(
+ child: &Arc<Mutex<std::process::Child>>,
+) -> std::io::Result<std::process::Output> {
+ let (stdout, stderr) = {
+ let mut child = child.lock().unwrap_or_else(|error| error.into_inner());
+ (child.stdout.take(), child.stderr.take())
};
- let stderr = match join_probe_reader(stderr_reader) {
- Ok(stderr) => stderr,
- Err(error) => return ProbeWaitResult::Finished(Err(error)),
- };
- ProbeWaitResult::Finished(Ok(std::process::Output {
- status,
- stdout,
- stderr,
- }))
+ std::thread::scope(|scope| {
+ let stdout_reader = std::thread::Builder::new()
+ .name("pnpm-probe-stdout".to_string())
+ .spawn_scoped(scope, move || read_probe_pipe(stdout))?;
+ let stderr_reader = std::thread::Builder::new()
+ .name("pnpm-probe-stderr".to_string())
+ .spawn_scoped(scope, move || read_probe_pipe(stderr))?;
+ let stdout = stdout_reader
+ .join()
+ .map_err(|_| std::io::Error::other("pnpm version probe stdout reader panicked"))??;
+ let stderr = stderr_reader
+ .join()
+ .map_err(|_| std::io::Error::other("pnpm version probe stderr reader panicked"))??;
+ let status = loop {
+ if let Some(status) = child
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .try_wait()?
+ {
+ break status;
+ }
+ std::thread::sleep(PNPM_PROBE_REAP_RETRY_INTERVAL);
+ };
+ Ok(std::process::Output {
+ status,
+ stdout,
+ stderr,
+ })
+ })
}
-fn reap_probe_after_wait_failure(
- child: &mut std::process::Child,
- pid: u32,
- error: std::io::Error,
-) -> ProbeWaitResult {
- super::super::cancel::terminate_pid_tree(pid);
- if let Err(kill_error) = child.kill() {
- log::warn!("pnpm version probe kill after wait failure failed: {kill_error}");
- }
- let started = std::time::Instant::now();
- loop {
- match child.try_wait() {
- Ok(Some(_)) => return ProbeWaitResult::Finished(Err(error)),
- Ok(None) => {}
- Err(cleanup_error) => {
- log::warn!("pnpm version probe reap after wait failure failed: {cleanup_error}");
- if super::super::process::plugin_process_has_exited(pid) {
- return ProbeWaitResult::Finished(Err(error));
- }
- }
+use super::super::cancel::terminate_probe_tree;
+
+fn terminate_probe(
+ child: &Arc<Mutex<std::process::Child>>,
+ terminate_tree: fn(u32) -> bool,
+) -> std::io::Result<()> {
+ let mut child = child.lock().unwrap_or_else(|error| error.into_inner());
+ // 同一锁内确认存活并强杀;waiter 不得先回收后再按可能复用的 PID 杀进程。
+ if child.try_wait()?.is_none() {
+ let tree_killed = terminate_tree(child.id());
+ let root_killed = child.kill();
+ if !tree_killed {
+ return Err(std::io::Error::other(
+ "PNPM_PROBE_TREE_CLEANUP_FAILED: pnpm version probe process tree termination was not confirmed",
+ ));
}
- if started.elapsed() >= PNPM_PROBE_REAP_RETRY_TIMEOUT {
- return ProbeWaitResult::CleanupPending {
- pid,
- reason: format!(
- "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe pid {pid} could not be reaped after wait failure: {error}"
- ),
- };
+ if let Err(error) = root_killed {
+ if child.try_wait()?.is_none() {
+ return Err(error);
+ }
}
- std::thread::sleep(PNPM_PROBE_REAP_RETRY_INTERVAL);
}
+ Ok(())
}
-fn monitor_probe_cleanup(mut pending: ProbeCleanupPending) {
- super::super::process::mark_process_cleanup_failed(pending.owner, pending.reason.clone());
- tauri::async_runtime::spawn(async move {
- wait_for_probe_cleanup(&mut pending).await;
- pending.release();
- });
+async fn cleanup_probe(
+ pending: ProbeCleanupPending,
+ waiter: Option<tauri::async_runtime::JoinHandle<std::io::Result<std::process::Output>>>,
+ reason: String,
+) -> Result<(), String> {
+ let mut cleanup = monitor_probe_cleanup(pending, waiter, reason, terminate_probe_tree);
+ match tokio::time::timeout(PNPM_PROBE_CLEANUP_TIMEOUT, &mut cleanup).await {
+ Ok(Ok(())) => Ok(()),
+ Ok(Err(error)) => Err(format!("PNPM_PROBE_CLEANUP_FAILED: {error}")),
+ Err(_) => Err(
+ "PNPM_PROBE_CLEANUP_TIMEOUT: pnpm version probe cleanup did not finish within 5 seconds"
+ .to_string(),
+ ),
+ }
}
-fn monitor_probe_wait_task(
- waiter: tauri::async_runtime::JoinHandle<ProbeTaskResult>,
- owner: ProcessOwner,
- pid: u32,
+fn monitor_probe_cleanup(
+ pending: ProbeCleanupPending,
+ waiter: Option<tauri::async_runtime::JoinHandle<std::io::Result<std::process::Output>>>,
reason: String,
- process_guard: tokio::sync::OwnedMutexGuard<()>,
- pid_guard: PidGuard,
-) {
- super::super::process::mark_process_cleanup_failed(owner, reason);
+ terminate_tree: fn(u32) -> bool,
+) -> tauri::async_runtime::JoinHandle<()> {
+ super::super::process::mark_process_cleanup_failed(pending.owner, reason);
tauri::async_runtime::spawn(async move {
- match waiter.await {
- Ok(ProbeTaskResult::CleanupPending { child, pid, reason }) => {
- let mut pending = ProbeCleanupPending {
- child,
- pid,
- reason,
- owner,
- _process_guard: process_guard,
- _pid_guard: pid_guard,
- };
- wait_for_probe_cleanup(&mut pending).await;
- pending.release();
- }
- Ok(ProbeTaskResult::Finished(_)) => {
- super::super::process::release_process_cleanup(owner, pid_guard, process_guard);
- }
- Err(error) => {
- log::error!("pnpm version probe cleanup wait task failed: {error}");
- await_exit_then_release(owner, pid, pid_guard, process_guard).await;
+ let child = pending.child.clone();
+ let killer =
+ tauri::async_runtime::spawn_blocking(move || terminate_probe(&child, terminate_tree));
+ let wait = async move {
+ if let Some(waiter) = waiter {
+ if let Err(error) = waiter.await {
+ log::error!("pnpm version probe cleanup wait task failed: {error}");
+ }
}
+ };
+ let (killed, ()) = tokio::join!(killer, wait);
+ if !matches!(killed, Ok(Ok(()))) {
+ let reason = format!(
+ "PNPM_PROBE_TREE_CLEANUP_FAILED: pnpm version probe process tree termination was not confirmed: {killed:?}"
+ );
+ log::error!("{reason}");
+ super::super::process::mark_process_cleanup_failed(pending.owner, reason);
+ // ponytail: 未确认整树清理仅重启恢复;需自动恢复再跟踪可靠进程树身份。
+ std::future::pending::<()>().await;
}
- });
-}
-
-fn monitor_orphaned_probe_pid(
- owner: ProcessOwner,
- pid: u32,
- reason: String,
- process_guard: tokio::sync::OwnedMutexGuard<()>,
- pid_guard: PidGuard,
-) {
- super::super::process::mark_process_cleanup_failed(owner, reason);
- super::super::cancel::terminate_pid_tree(pid);
- tauri::async_runtime::spawn(await_exit_then_release(
- owner,
- pid,
- pid_guard,
- process_guard,
- ));
-}
-
-async fn await_exit_then_release(
- owner: ProcessOwner,
- pid: u32,
- pid_guard: PidGuard,
- process_guard: tokio::sync::OwnedMutexGuard<()>,
-) {
- wait_for_probe_cleanup_with(
- || !super::super::process::plugin_process_has_exited(pid),
- PNPM_PROBE_LIVENESS_INTERVAL,
- )
- .await;
- super::super::process::release_process_cleanup(owner, pid_guard, process_guard);
+ wait_for_probe_cleanup(&pending).await;
+ if super::super::process::process_cleanup_failure(pending.owner)
+ .is_some_and(|reason| reason.starts_with("PNPM_PROBE_TREE_CLEANUP_FAILED:"))
+ {
+ std::future::pending::<()>().await;
+ }
+ pending.release();
+ })
}
-async fn wait_for_probe_cleanup(pending: &mut ProbeCleanupPending) {
+async fn wait_for_probe_cleanup(pending: &ProbeCleanupPending) {
wait_for_probe_cleanup_with(
- || match pending.child.try_wait() {
- Ok(Some(_)) => false,
- Ok(None) => true,
- Err(error) => {
- log::warn!(
- "pnpm version probe cleanup monitor wait failed for pid {}: {error}",
- pending.pid
- );
- !super::super::process::plugin_process_has_exited(pending.pid)
- }
+ || {
+ !matches!(
+ pending
+ .child
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .try_wait(),
+ Ok(Some(_))
+ )
},
PNPM_PROBE_LIVENESS_INTERVAL,
)
.await;
- log::info!(
- "pnpm version probe cleanup monitor released pid {}",
- pending.pid
- );
}
async fn wait_for_probe_cleanup_with<F>(mut remains_active: F, interval: std::time::Duration)
@@ -496,14 +388,6 @@ fn read_probe_pipe<R: Read>(pipe: Option<R>) -> std::io::Result<Vec<u8>> {
Ok(output)
}
-fn join_probe_reader(
- reader: std::thread::JoinHandle<std::io::Result<Vec<u8>>>,
-) -> std::io::Result<Vec<u8>> {
- reader
- .join()
- .map_err(|_| std::io::Error::other("pnpm version probe output reader thread panicked"))?
-}
-
fn log_probe_fallback(pnpm: &Path, phase: &str, error: impl std::fmt::Display) {
log::warn!(
"pnpm version probe {phase} failed for {}: {error}; falling back to bundled pnpm",
@@ -511,29 +395,6 @@ fn log_probe_fallback(pnpm: &Path, phase: &str, error: impl std::fmt::Display) {
);
}
-fn probe_task_or_fallback<T, E: std::fmt::Display>(pnpm: &Path, result: Result<T, E>) -> Option<T> {
- match result {
- Ok(task) => Some(task),
- Err(error) => {
- log_probe_fallback(pnpm, "wait task", error);
- None
- }
- }
-}
-
-fn probe_output_or_fallback(
- pnpm: &Path,
- result: std::io::Result<std::process::Output>,
-) -> Result<Option<std::process::Output>, String> {
- match result {
- Ok(output) => Ok(Some(output)),
- Err(error) => {
- log_probe_fallback(pnpm, "output", error);
- Ok(None)
- }
- }
-}
-
/// 探测超时后进程已被强杀并回收干净时的处置:记降级日志并返回「用户 pnpm
/// 不可用」(`None`),让 [`ensure_pnpm`] 回退捆绑版 pnpm。
///
@@ -545,51 +406,7 @@ fn probe_timeout_or_fallback(pnpm: &Path, reason: String) -> Option<u32> {
None
}
-/// 用户 pnpm 主版本号(解析 `pnpm --version` 首个点分字段);不存在或不可运行
-/// (corepack shim 在 Node 24 上 ERR_INVALID_THIS 崩溃等)返回 None。
-///
-/// 供 [`ensure_pnpm`] 选版与 [`crate::service::plugin::verify`] 的修复选版共用(store 主版本匹配)。
-pub(crate) fn user_pnpm_major_version(app_handle: &AppHandle) -> Option<u32> {
- let pnpm = cli::find_user_pnpm(app_handle)?;
- let node = config::get_node_binary_path(app_handle);
- pnpm_major_version_at_with_node(&pnpm, Some(&node))
-}
-
-/// 探测精确 pnpm 可执行路径的主版本,供直接执行路径校验实际将运行的文件。
-pub(crate) fn pnpm_major_version_at(pnpm: &Path) -> Option<u32> {
- pnpm_major_version_at_with_node(pnpm, None)
-}
-
-/// 在受控 Node 环境中探测 pnpm 主版本。Windows GUI 进程继承的 PATH 可能早于
-/// 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, None).output() {
- Ok(output) => output,
- Err(error) => {
- log::warn!(
- "pnpm version probe failed to spawn {}: {error}",
- pnpm.display()
- );
- return None;
- }
- };
- parse_pnpm_major_output(pnpm, &output)
-}
-
-/// 构建 pnpm 版本探测命令:`--version`、注入选定 Node 的 PATH(issue #182)、
-/// Windows 无窗口,并**显式关闭 stdin**。
-///
-/// 探测只需要 `--version` 的标准输出,绝不该等待输入:corepack 在 pnpm 版本
-/// 未缓存时会先问 "Do you want to continue? [Y/n]",而 GUI 进程继承的 stdin
-/// 句柄无控制台可读,子进程读它会一直挂起——探测只能靠 10 秒超时强杀,用户
-/// 看到的是「pnpm 不能在这台电脑上运行」的安装失败(issue #449)。关闭 stdin
-/// 让这类读取立刻拿到 EOF,探测必定有界结束。有界探测(子进程 + 超时强杀)与
-/// 无界探测([`user_pnpm_major_version`] 的 `output()`)共用本函数,避免两套
-/// 探测策略再次分叉。
-///
-/// `bin_dir` 为桌面端 shim 目录:传入即复现安装子进程的解析条件(见
-/// [`pnpm_probe_path`]);按精确路径探测(`verify`)传 None。
+/// 关闭 stdin 避免 Corepack 交互挂起(issue #449),注入选定 Node 避免陈旧 PATH(issue #182)。
fn pnpm_probe_command(
pnpm: &Path,
node: Option<&Path>,
@@ -795,46 +612,26 @@ pub(crate) fn bundled_pnpm_major(app_handle: &AppHandle) -> Option<u32> {
/// 匹配且用户版不匹配时强制捆绑版(否则用户版会 `ERR_PNPM_UNEXPECTED_STORE`);
/// store 未知时用户 pnpm ≥ 10 优先,否则强制捆绑版。启动阶段绝不触发下载,
/// 捆绑版未安装即返回 false(交由用户 pnpm)。
-pub(crate) fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> bool {
- let store_major = profile_store_major(app_handle);
- let user_major = user_pnpm_major_version(app_handle);
- let bundled_major = bundled_pnpm_major(app_handle);
- // 捆绑版未安装 → 无法强制,交还用户 pnpm(shim 默认用户优先)
+pub(crate) async fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> Result<bool, String> {
if !config::get_pnpm_binary_path(app_handle).exists() {
- return false;
+ return Ok(false);
}
- match store_major {
- Some(store) => bundled_major == Some(store) && user_major != Some(store),
- None => !matches!(user_major, Some(major) if major >= MIN_TRUSTED_PNPM_MAJOR),
+ let store_major = profile_store_major(app_handle);
+ if store_major.is_some_and(|store| bundled_pnpm_major(app_handle) != Some(store)) {
+ return Ok(false);
}
+ let user_major = user_pnpm_major_version_bounded(app_handle, new_process_owner()).await?;
+ Ok(match store_major {
+ Some(store) => user_major != Some(store),
+ None => !matches!(user_major, Some(major) if major >= MIN_TRUSTED_PNPM_MAJOR),
+ })
}
#[cfg(test)]
mod tests {
+ use super::super::super::process::TEST_PROCESS_LOCK;
use super::*;
- #[test]
- fn pnpm_probe_wait_and_output_failures_fall_back_to_bundled() {
- let pnpm = PathBuf::from("broken-pnpm");
- let output = probe_output_or_fallback(
- &pnpm,
- Err(std::io::Error::new(
- std::io::ErrorKind::BrokenPipe,
- "output pipe closed",
- )),
- )
- .unwrap();
-
- assert!(output.is_none());
- }
-
- #[test]
- fn pnpm_probe_wait_task_join_failure_falls_back_to_bundled() {
- let pnpm = PathBuf::from("broken-pnpm");
- let task: Option<()> = probe_task_or_fallback(&pnpm, Err("blocking worker dropped"));
- assert!(task.is_none());
- }
-
/// issue #449 回归:探测超时、但进程已被强杀并回收干净时,必须降级为
/// 「用户 pnpm 不可用」(`None` → `ensure_pnpm` 回退捆绑版),而不是把
/// `PNPM_PROBE_TIMEOUT` 当成整次插件安装的失败。
@@ -938,6 +735,7 @@ mod tests {
#[tokio::test]
async fn exited_probe_releases_its_pid_and_process_guard() {
+ let _test_guard = TEST_PROCESS_LOCK.lock().await;
#[cfg(windows)]
let mut child = {
use std::os::windows::process::CommandExt;
@@ -959,9 +757,15 @@ mod tests {
let lock = std::sync::Arc::new(tokio::sync::Mutex::new(()));
let process_guard = lock.clone().lock_owned().await;
assert!(lock.try_lock().is_err());
- tokio::time::timeout(
- std::time::Duration::from_secs(5),
- await_exit_then_release(owner, pid, pid_guard, process_guard),
+ cleanup_probe(
+ ProbeCleanupPending {
+ child: Arc::new(Mutex::new(child)),
+ owner,
+ _process_guard: process_guard,
+ _pid_guard: pid_guard,
+ },
+ None,
+ "PNPM_PROBE_WAIT_TASK_FAILED: test cleanup".to_string(),
)
.await
.unwrap();
@@ -971,6 +775,7 @@ mod tests {
#[tokio::test]
async fn live_probe_retains_its_pid_and_process_guard_until_exit() {
+ let _test_guard = TEST_PROCESS_LOCK.lock().await;
#[cfg(windows)]
let mut command = {
use std::os::windows::process::CommandExt;
@@ -997,7 +802,17 @@ mod tests {
let pid_guard = PidGuard::set(owner, pid);
let lock = std::sync::Arc::new(tokio::sync::Mutex::new(()));
let process_guard = lock.clone().lock_owned().await;
- let release = await_exit_then_release(owner, pid, pid_guard, process_guard);
+ let mut input = child.stdin.take().unwrap();
+ let pending = ProbeCleanupPending {
+ child: Arc::new(Mutex::new(child)),
+ owner,
+ _process_guard: process_guard,
+ _pid_guard: pid_guard,
+ };
+ let release = async {
+ wait_for_probe_cleanup(&pending).await;
+ pending.release();
+ };
tokio::pin!(release);
assert!(
tokio::time::timeout(std::time::Duration::from_millis(50), &mut release)
@@ -1010,11 +825,10 @@ mod tests {
);
assert!(lock.try_lock().is_err());
use std::io::Write;
- child.stdin.take().unwrap().write_all(b"done\n").unwrap();
+ input.write_all(b"done\n").unwrap();
tokio::time::timeout(std::time::Duration::from_secs(5), &mut release)
.await
.unwrap();
- let _ = child.wait();
assert_eq!(super::super::super::process::active_plugin_pid(owner), None);
assert!(lock.try_lock().is_ok());
}
@@ -1037,8 +851,9 @@ mod tests {
}
#[cfg(unix)]
- #[test]
- fn pnpm_major_version_at_probes_the_exact_selected_path() {
+ #[tokio::test]
+ async fn pnpm_major_version_at_probes_the_exact_selected_path() {
+ let _test_guard = TEST_PROCESS_LOCK.lock().await;
use std::os::unix::fs::PermissionsExt;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -1059,16 +874,23 @@ mod tests {
std::fs::set_permissions(path, permissions).unwrap();
}
- assert_eq!(pnpm_major_version_at(&selected), Some(11));
- assert_eq!(pnpm_major_version_at(&other), Some(10));
+ for (path, major) in [(&selected, 11), (&other, 10)] {
+ assert_eq!(
+ pnpm_major_version_at_bounded(path, None, None, new_process_owner())
+ .await
+ .unwrap(),
+ Some(major)
+ );
+ }
let _ = std::fs::remove_dir_all(root);
}
/// 回归 Windows GUI 的陈旧 PATH:pnpm shim 必须解析到桌面端选定的 Node,
/// 即使 shim 同目录存在冲突的 node,且路径包含空格和 shell 元字符。
#[cfg(windows)]
- #[test]
- fn pnpm_major_version_probe_injects_selected_node_for_cmd_shim() {
+ #[tokio::test]
+ async fn pnpm_major_version_probe_injects_selected_node_for_cmd_shim() {
+ let _test_guard = TEST_PROCESS_LOCK.lock().await;
use std::time::{SystemTime, UNIX_EPOCH};
let nonce = SystemTime::now()
@@ -1089,12 +911,275 @@ mod tests {
std::fs::write(&node, "@echo off\r\necho 11.24.0\r\n").unwrap();
assert_eq!(
- pnpm_major_version_at_with_node(&selected, Some(&node)),
+ pnpm_major_version_at_bounded(&selected, Some(&node), None, new_process_owner())
+ .await
+ .unwrap(),
Some(11)
);
let _ = std::fs::remove_dir_all(root);
}
+ #[tokio::test]
+ async fn pnpm_version_probe_bounds_slow_shims_and_releases_the_process_lock() {
+ let _test_guard = TEST_PROCESS_LOCK.lock().await;
+ let root = tempfile::tempdir().unwrap();
+ #[cfg(windows)]
+ let pnpm = {
+ let pnpm = root.path().join("slow pnpm.cmd");
+ std::fs::write(
+ &pnpm,
+ "@echo off\r\npowershell.exe -NoProfile -NonInteractive -Command \"Start-Sleep -Seconds 20\"\r\necho 11.2.0\r\n",
+ )
+ .unwrap();
+ pnpm
+ };
+ #[cfg(unix)]
+ let pnpm = {
+ use std::os::unix::fs::PermissionsExt;
+ let pnpm = root.path().join("slow-pnpm");
+ std::fs::write(&pnpm, "#!/bin/sh\nsleep 20\nprintf '11.2.0\\n'\n").unwrap();
+ std::fs::set_permissions(&pnpm, std::fs::Permissions::from_mode(0o700)).unwrap();
+ pnpm
+ };
+ let started = std::time::Instant::now();
+ assert_eq!(
+ pnpm_major_version_at_bounded(&pnpm, None, None, new_process_owner())
+ .await
+ .unwrap(),
+ None
+ );
+ assert!(started.elapsed() < std::time::Duration::from_secs(18));
+ let process_guard =
+ tokio::time::timeout(std::time::Duration::from_secs(1), acquire_process_lock())
+ .await
+ .expect("finished probe must release the process lock")
+ .unwrap();
+ drop(process_guard);
+ }
+
+ #[tokio::test]
+ async fn cancelled_probe_keeps_its_pid_and_lock_until_the_child_exits() {
+ let _test_guard = TEST_PROCESS_LOCK.lock().await;
+ let root = tempfile::tempdir().unwrap();
+ let release = root.path().join("release");
+ #[cfg(windows)]
+ let pnpm = {
+ let pnpm = root.path().join("held pnpm.cmd");
+ let path = release.to_string_lossy().replace('\'', "''");
+ std::fs::write(
+ &pnpm,
+ format!("@echo off\r\npowershell.exe -NoProfile -NonInteractive -Command \"while (-not (Test-Path -LiteralPath '{path}')) {{ Start-Sleep -Milliseconds 25 }}\"\r\necho 11.2.0\r\n"),
+ )
+ .unwrap();
+ pnpm
+ };
+ #[cfg(unix)]
+ let pnpm = {
+ use std::os::unix::fs::PermissionsExt;
+ let pnpm = root.path().join("held-pnpm");
+ let path = release.to_string_lossy().replace('\'', "'\\''");
+ std::fs::write(
+ &pnpm,
+ format!("#!/bin/sh\nwhile [ ! -f '{path}' ]; do sleep 0.025; done\nprintf '11.2.0\\n'\n"),
+ )
+ .unwrap();
+ std::fs::set_permissions(&pnpm, std::fs::Permissions::from_mode(0o700)).unwrap();
+ pnpm
+ };
+ let owner = new_process_owner();
+ let caller =
+ tokio::spawn(
+ async move { pnpm_major_version_at_bounded(&pnpm, None, None, owner).await },
+ );
+ let pid = tokio::time::timeout(std::time::Duration::from_secs(2), async {
+ loop {
+ if let Some(pid) = super::super::super::process::active_plugin_pid(owner) {
+ break pid;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ caller.abort();
+ assert!(caller.await.unwrap_err().is_cancelled());
+ let retained_pid = super::super::super::process::active_plugin_pid(owner);
+ let held_lock =
+ tokio::time::timeout(std::time::Duration::from_millis(50), acquire_process_lock())
+ .await;
+ std::fs::write(release, "done").unwrap();
+ let released =
+ tokio::time::timeout(std::time::Duration::from_secs(5), acquire_process_lock())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(retained_pid, Some(pid));
+ assert!(
+ held_lock.is_err(),
+ "cancelled caller must not release a live probe lock"
+ );
+ assert_eq!(super::super::super::process::active_plugin_pid(owner), None);
+ drop(released);
+ }
+
+ #[tokio::test]
+ async fn cleanup_timeout_fails_closed_until_the_waiter_finishes() {
+ let _test_guard = TEST_PROCESS_LOCK.lock().await;
+ #[cfg(windows)]
+ let mut child = {
+ use std::os::windows::process::CommandExt;
+ std::process::Command::new("cmd.exe")
+ .creation_flags(0x08000000)
+ .args(["/D", "/C", "exit 0"])
+ .spawn()
+ .unwrap()
+ };
+ #[cfg(unix)]
+ let mut child = std::process::Command::new("sh")
+ .args(["-c", "exit 0"])
+ .spawn()
+ .unwrap();
+ let pid = child.id();
+ child.wait().unwrap();
+ let owner = new_process_owner();
+ let process_guard = acquire_process_lock().await.unwrap();
+ let pending = ProbeCleanupPending {
+ child: Arc::new(Mutex::new(child)),
+ owner,
+ _process_guard: process_guard,
+ _pid_guard: PidGuard::set(owner, pid),
+ };
+ let (release, held) = tokio::sync::oneshot::channel::<()>();
+ let waiter = tauri::async_runtime::spawn(async move {
+ held.await.unwrap();
+ Err(std::io::Error::other("probe output pipe closed"))
+ });
+ let started = std::time::Instant::now();
+ let result = cleanup_probe(
+ pending,
+ Some(waiter),
+ "PNPM_PROBE_WAIT_TASK_FAILED: held waiter".to_string(),
+ )
+ .await;
+ let retained_pid = super::super::super::process::active_plugin_pid(owner);
+ let blocked =
+ tokio::time::timeout(std::time::Duration::from_millis(50), acquire_process_lock())
+ .await;
+ release.send(()).unwrap();
+ let released = tokio::time::timeout(std::time::Duration::from_secs(2), async {
+ while super::super::super::process::active_plugin_pid(owner).is_some() {
+ tokio::task::yield_now().await;
+ }
+ acquire_process_lock().await
+ })
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(result
+ .unwrap_err()
+ .starts_with("PNPM_PROBE_CLEANUP_TIMEOUT:"));
+ assert!(started.elapsed() < std::time::Duration::from_secs(7));
+ assert_eq!(retained_pid, Some(pid));
+ assert!(blocked
+ .unwrap()
+ .unwrap_err()
+ .starts_with("PNPM_PROBE_WAIT_TASK_FAILED:"));
+ assert_eq!(super::super::super::process::active_plugin_pid(owner), None);
+ drop(released);
+ }
+
+ #[tokio::test]
+ async fn failed_tree_termination_retains_guards_even_after_root_exit() {
+ let _test_guard = TEST_PROCESS_LOCK.lock().await;
+ #[cfg(windows)]
+ let mut command = {
+ use std::os::windows::process::CommandExt;
+ let mut command = std::process::Command::new("cmd.exe");
+ command
+ .creation_flags(0x08000000)
+ .args(["/D", "/C", "set /p token="]);
+ command
+ };
+ #[cfg(unix)]
+ let mut command = {
+ use std::os::unix::process::CommandExt;
+ let mut command = std::process::Command::new("sh");
+ command.args(["-c", "read -r token"]).process_group(0);
+ command
+ };
+ let child = Arc::new(Mutex::new(
+ command
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()
+ .unwrap(),
+ ));
+ let pid = child.lock().unwrap().id();
+ let owner = new_process_owner();
+ let lock = Arc::new(tokio::sync::Mutex::new(()));
+ let pending = ProbeCleanupPending {
+ child: child.clone(),
+ owner,
+ _process_guard: lock.clone().lock_owned().await,
+ _pid_guard: PidGuard::set(owner, pid),
+ };
+ let waiting_child = child.clone();
+ let waiter =
+ tauri::async_runtime::spawn_blocking(move || wait_for_probe_output(&waiting_child));
+ let mut monitor = monitor_probe_cleanup(
+ pending,
+ Some(waiter),
+ "PNPM_PROBE_TIMEOUT: injected tree termination failure".to_string(),
+ |_| false,
+ );
+ let exited = tokio::time::timeout(std::time::Duration::from_secs(2), async {
+ while child.lock().unwrap().try_wait().unwrap().is_none() {
+ tokio::time::sleep(PNPM_PROBE_REAP_RETRY_INTERVAL).await;
+ }
+ })
+ .await;
+ let failure = tokio::time::timeout(std::time::Duration::from_secs(2), async {
+ loop {
+ if let Err(reason) = acquire_process_lock().await {
+ if reason.starts_with("PNPM_PROBE_TREE_CLEANUP_FAILED:") {
+ break reason;
+ }
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await;
+ let retained_pid = super::super::super::process::active_plugin_pid(owner);
+ let lock_held = lock.try_lock().is_err();
+ let retained = tokio::time::timeout(std::time::Duration::from_millis(50), &mut monitor)
+ .await
+ .is_err();
+ if retained {
+ monitor.abort();
+ let _ = monitor.await;
+ }
+ super::super::super::process::clear_process_cleanup_failed(owner);
+ if exited.is_err() {
+ let mut child = child.lock().unwrap();
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ assert!(
+ exited.is_ok(),
+ "root fallback must kill the real probe child"
+ );
+ assert!(
+ failure.is_ok(),
+ "root exit must not clear unconfirmed tree cleanup"
+ );
+ assert!(retained, "tree failure must retain the cleanup monitor");
+ assert!(lock_held, "tree failure must retain the process guard");
+ assert_eq!(retained_pid, Some(pid));
+ assert_eq!(super::super::super::process::active_plugin_pid(owner), None);
+ assert!(lock.try_lock().is_ok());
+ }
+
#[test]
fn store_major_parsed_from_modules_yaml() {
// 真实 pnpm v10 写入的 .modules.yaml:storeDir 指向 store\v10
diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rs
index 3ac9d1e4..8c3a25a6 100644
--- a/src-tauri/src/service/plugin/install/single.rs
+++ b/src-tauri/src/service/plugin/install/single.rs
@@ -961,7 +961,7 @@ async fn verify_update_landed(
let window = app_handle
.get_webview_window("main")
.ok_or("WINDOW_NOT_FOUND: main window missing")?;
- let envs = build_plugin_envs(app_handle, harness_prefer_bundled_pnpm(app_handle));
+ let envs = build_plugin_envs(app_handle, harness_prefer_bundled_pnpm(app_handle).await?);
let pkg_dir = profile_dir(app_handle).join("node_modules").join(name);
if let Err(e) = ensure_plugin_entry_built(app_handle, id, &pkg_dir, &envs, &window).await {
if let Err(err) = errors::record(app_handle, id, "update", &e) {
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index 8462ddb4..2c6d1b0c 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -56,7 +56,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 process::acquire_operation_lock;
+pub(crate) use process::{acquire_operation_lock, is_process_cleanup_failure};
pub(crate) use install::harness_prefer_bundled_pnpm;
pub(crate) use install::local_spec_from_path;
pub(crate) use install::uninstall_deprecated_plugins;
diff --git a/src-tauri/src/service/plugin/process.rs b/src-tauri/src/service/plugin/process.rs
index e8bbab68..afde0d61 100644
--- a/src-tauri/src/service/plugin/process.rs
+++ b/src-tauri/src/service/plugin/process.rs
@@ -39,15 +39,24 @@ pub struct PreinstallLogPayload {
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(crate) struct ProcessOwner(u64);
+#[derive(Clone)]
+pub(crate) struct ActivePluginProcess {
+ pub(crate) pid: u32,
+ pub(crate) child: Option<Arc<Mutex<std::process::Child>>>,
+}
+
static NEXT_PROCESS_OWNER: AtomicU64 = AtomicU64::new(1);
-static ACTIVE_PLUGIN_PIDS: OnceLock<Mutex<HashMap<ProcessOwner, u32>>> = OnceLock::new();
+static ACTIVE_PLUGIN_PIDS: OnceLock<Mutex<HashMap<ProcessOwner, ActivePluginProcess>>> =
+ OnceLock::new();
static PLUGIN_PROCESS_LOCK: OnceLock<Arc<tokio::sync::Mutex<()>>> = OnceLock::new();
static PLUGIN_OPERATION_LOCK: OnceLock<Arc<tokio::sync::Mutex<()>>> = OnceLock::new();
+#[cfg(test)]
+pub(crate) static TEST_PROCESS_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static PLUGIN_CLEANUP_FAILURE: OnceLock<
tokio::sync::watch::Sender<Option<(ProcessOwner, String)>>,
> = OnceLock::new();
-fn active_pid_lock() -> &'static Mutex<HashMap<ProcessOwner, u32>> {
+fn active_pid_lock() -> &'static Mutex<HashMap<ProcessOwner, ActivePluginProcess>> {
ACTIVE_PLUGIN_PIDS.get_or_init(|| Mutex::new(HashMap::new()))
}
@@ -60,19 +69,23 @@ pub(crate) fn new_process_owner() -> ProcessOwner {
}
pub(crate) fn active_plugin_pid(owner: ProcessOwner) -> Option<u32> {
+ active_plugin_process(owner).map(|process| process.pid)
+}
+
+pub(crate) fn active_plugin_process(owner: ProcessOwner) -> Option<ActivePluginProcess> {
active_pid_lock()
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&owner)
- .copied()
+ .cloned()
}
-pub(crate) fn active_plugin_processes() -> Vec<(ProcessOwner, u32)> {
+pub(crate) fn active_plugin_processes() -> Vec<(ProcessOwner, ActivePluginProcess)> {
active_pid_lock()
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
- .map(|(owner, pid)| (*owner, *pid))
+ .map(|(owner, process)| (*owner, process.clone()))
.collect()
}
@@ -151,8 +164,39 @@ pub(crate) fn clear_orphan_plugin_writer_lock(profile_dir: &Path) -> bool {
true
}
+pub(crate) fn process_cleanup_failure(owner: ProcessOwner) -> Option<String> {
+ cleanup_failure_sender()
+ .borrow()
+ .as_ref()
+ .filter(|(active, _)| *active == owner)
+ .map(|(_, reason)| reason.clone())
+}
+
+pub(crate) fn is_process_cleanup_failure(error: &str) -> bool {
+ [
+ // 不能整段匹配 `PNPM_PROBE_`:锁被正常安装占住时的 `PNPM_PROBE_LOCK_TIMEOUT`
+ // 只是竞争,不代表上一次清理未确认。
+ "PNPM_PROBE_TREE_CLEANUP_FAILED:",
+ "PNPM_PROBE_CLEANUP_",
+ "PLUGIN_PROCESS_",
+ "PREINSTALL_WAIT:",
+ "INTERNAL_PLUGIN_PROCESS_REAP_TIMEOUT:",
+ "INTERNAL_PLUGIN_ENSURE_DROPPED:",
+ ]
+ .iter()
+ .any(|prefix| error.starts_with(prefix))
+}
+
pub(crate) fn mark_process_cleanup_failed(owner: ProcessOwner, reason: String) {
- cleanup_failure_sender().send_replace(Some((owner, reason)));
+ cleanup_failure_sender().send_if_modified(|failure| {
+ if failure.as_ref().is_some_and(|(active, current)| {
+ *active == owner && current.starts_with("PNPM_PROBE_TREE_CLEANUP_FAILED:")
+ }) {
+ return false;
+ }
+ *failure = Some((owner, reason));
+ true
+ });
}
pub(crate) fn clear_process_cleanup_failed(owner: ProcessOwner) {
@@ -224,7 +268,22 @@ impl PidGuard {
active_pid_lock()
.lock()
.unwrap_or_else(|e| e.into_inner())
- .insert(owner, pid);
+ .insert(owner, ActivePluginProcess { pid, child: None });
+ Self { owner, pid }
+ }
+
+ pub(crate) fn set_child(owner: ProcessOwner, child: &Arc<Mutex<std::process::Child>>) -> Self {
+ let pid = child.lock().unwrap_or_else(|error| error.into_inner()).id();
+ active_pid_lock()
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .insert(
+ owner,
+ ActivePluginProcess {
+ pid,
+ child: Some(child.clone()),
+ },
+ );
Self { owner, pid }
}
}
@@ -232,7 +291,10 @@ impl PidGuard {
impl Drop for PidGuard {
fn drop(&mut self) {
let mut active = active_pid_lock().lock().unwrap_or_else(|e| e.into_inner());
- if active.get(&self.owner) == Some(&self.pid) {
+ if active
+ .get(&self.owner)
+ .is_some_and(|process| process.pid == self.pid)
+ {
active.remove(&self.owner);
}
}
@@ -440,8 +502,9 @@ mod tests {
);
}
- #[test]
- fn stale_guard_cannot_clear_a_new_process_for_the_same_owner() {
+ #[tokio::test]
+ async fn stale_guard_cannot_clear_a_new_process_for_the_same_owner() {
+ let _test_guard = TEST_PROCESS_LOCK.lock().await;
let owner = new_process_owner();
let stale = PidGuard::set(owner, 100);
let current = PidGuard::set(owner, 200);
@@ -455,6 +518,7 @@ mod tests {
#[tokio::test]
async fn cleanup_failure_clears_before_lock_handoff_and_preserves_other_owner() {
+ let _test_guard = TEST_PROCESS_LOCK.lock().await;
let guard = acquire_process_lock().await.unwrap();
let owner = new_process_owner();
let pid_guard = PidGuard::set(owner, 100);
@@ -495,6 +559,45 @@ mod tests {
"clearing a stale owner must not remove another owner's failure"
);
clear_process_cleanup_failed(other_owner);
+
+ let tree_reason = "PNPM_PROBE_TREE_CLEANUP_FAILED: tree exit is unconfirmed".to_string();
+ mark_process_cleanup_failed(owner, tree_reason.clone());
+ mark_process_cleanup_failed(owner, "PNPM_PROBE_TIMEOUT: cleanup started".to_string());
+ let retained = cleanup_failure_sender().borrow().clone();
+ assert_eq!(process_cleanup_failure(owner), Some(tree_reason.clone()));
+ clear_process_cleanup_failed(owner);
+ assert_eq!(retained, Some((owner, tree_reason)));
+ }
+
+ #[test]
+ fn cleanup_classifier_keeps_ordinary_install_failures_best_effort() {
+ for blocked in [
+ "PNPM_PROBE_TREE_CLEANUP_FAILED: tree exit is unconfirmed",
+ "PNPM_PROBE_CLEANUP_TIMEOUT: pnpm version probe cleanup did not finish within 5 seconds",
+ "PLUGIN_PROCESS_CLEANUP_FAILED: test process is still active",
+ "PLUGIN_PROCESS_COORDINATOR_DROPPED: cleanup coordinator ended unexpectedly",
+ "PREINSTALL_WAIT: wait task failed",
+ "INTERNAL_PLUGIN_PROCESS_REAP_TIMEOUT: owner remained active",
+ ] {
+ assert!(
+ is_process_cleanup_failure(blocked),
+ "{blocked} must terminate startup instead of warning"
+ );
+ }
+ for best_effort in [
+ "PNPM_PROBE_LOCK_TIMEOUT: timed out waiting for the process lock",
+ "PNPM_PROBE_TIMEOUT: pnpm version probe timed out but the process was recycled",
+ "PNPM_PROBE_TASK_FAILED: task panicked",
+ "PNPM_INSTALL_FAILED: exit code 1: ERR_PNPM_UNEXPECTED_STORE",
+ "INTERNAL_PLUGIN_INSTALL_FAILED: pnpm add failed",
+ "DEPRECATED_PLUGIN_UNINSTALL_FAILED: dshmarket: missing",
+ "PRESET_PLUGIN_STILL_MISSING: 修复后仍缺失以下插件产物",
+ ] {
+ assert!(
+ !is_process_cleanup_failure(best_effort),
+ "{best_effort} must stay best-effort"
+ );
+ }
}
#[test]
diff --git a/src-tauri/src/service/plugin/verify.rs b/src-tauri/src/service/plugin/verify.rs
index 6ef09d2f..5913d556 100644
--- a/src-tauri/src/service/plugin/verify.rs
+++ b/src-tauri/src/service/plugin/verify.rs
@@ -19,19 +19,17 @@
use std::collections::HashMap;
use std::ffi::OsString;
-use std::io::Read;
use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex};
-use tauri::AppHandle;
+use tauri::{AppHandle, Manager};
use crate::config;
use crate::service::cli;
use super::errors;
-use super::install::{build_plugin_envs, harness_prefer_bundled_pnpm};
+use super::install::{build_plugin_envs, new_process_owner, run_plugin_process};
use super::installed::{installed_name, profile_dir, ProfilePackageJson};
use super::preset::{load_presets, PreinstallPluginInfo};
-use super::process::drain_captured;
+use super::process::is_process_cleanup_failure;
/// 判定清单引用的预装插件是否缺失产物(纯函数,便于单测)。
///
@@ -68,7 +66,8 @@ fn record_missing(app_handle: &AppHandle, ids: &[String], detail: &str) {
}
}
-/// 启动前调用:核对并修复预装插件完整性。最佳努力:失败只返回 Err(调用方告警)。
+/// 启动前调用:核对并修复预装插件完整性。普通失败只告警并记录错误标记,返回 Ok;
+/// 仅进程清理/协调器失败会以 Err 上抛,交由调用方终止本次启动(见下文)。
pub(crate) async fn ensure_preset_plugins(app_handle: &AppHandle) -> Result<(), String> {
let presets = load_presets(app_handle);
if presets.is_empty() {
@@ -104,9 +103,16 @@ pub(crate) async fn ensure_preset_plugins(app_handle: &AppHandle) -> Result<(),
);
// 修复:在 profile 目录以现有 manifest + lockfile 为准执行 `pnpm install`,
- // 重建 node_modules 依赖图(不解析新版本)。修复失败不阻断启动,给缺失插件
+ // 重建 node_modules 依赖图(不解析新版本)。普通修复失败不阻断启动,给缺失插件
// 记录错误标记,让前端插件面板暴露问题、用户可走卸载兜底恢复。
+ //
+ // 例外是进程清理/协调器失败(`is_process_cleanup_failure`):那说明前一进程的
+ // 去向未确认,继续 spawn 新的 pnpm 会与残留进程抢同一个 store 与档案。此时必须
+ // 把失败交给调用方终止启动,而不是降级成一次「最佳努力」的告警。
if let Err(e) = repair_with_pnpm_install(app_handle, &profile).await {
+ if is_process_cleanup_failure(&e) {
+ return Err(e);
+ }
log::warn!("PRESET_PLUGIN_REPAIR_FAILED: {e}");
record_missing(app_handle, &missing, &e);
return Ok(());
@@ -131,19 +137,38 @@ pub(crate) async fn ensure_preset_plugins(app_handle: &AppHandle) -> Result<(),
/// 选定直接执行的 pnpm(见 [`pnpm_direct`]),环境沿用桌面端插件子进程策略
/// (`build_plugin_envs`:隔离 $DSH_HOME、PATH 前置 shim 与 node 目录、pnpm
/// 选版开关),与安装/升级/卸载同一套行为,避免意外的 store/版本不兼容。
+///
+/// 走 [`run_plugin_process`](与其他装机路径同一执行器):它持有共享进程锁直到
+/// 阻塞等待结束,因此前一进程清理未确认时这里会直接拿到协调器错误,而不是绕开
+/// 锁再起一个 pnpm。
async fn repair_with_pnpm_install(app_handle: &AppHandle, profile: &Path) -> Result<(), String> {
- let (program, mut args) = pnpm_direct(app_handle).ok_or_else(|| {
+ let (program, mut args) = pnpm_direct(app_handle).await?.ok_or_else(|| {
"PNPM_NOT_FOUND: 无捆绑 pnpm 且无用户 pnpm,无法修复插件依赖(如需可手动执行 pnpm install)"
.to_string()
})?;
+ let bundled = config::get_pnpm_binary_path(app_handle);
+ let prefer_bundled = args
+ .iter()
+ .any(|arg| arg.as_os_str() == bundled.as_os_str());
args.push(OsString::from("install"));
- let envs = build_plugin_envs(app_handle, harness_prefer_bundled_pnpm(app_handle));
+ let window = app_handle
+ .get_webview_window("main")
+ .ok_or("WINDOW_NOT_FOUND: main window missing")?;
+ let envs = build_plugin_envs(app_handle, prefer_bundled);
log::info!(
"repairing profile node_modules via pnpm install in {}",
profile.display()
);
- let (exit_code, output) = spawn_and_wait(&program, &args, profile, &envs).await?;
+ let (exit_code, output) = run_plugin_process(
+ &program,
+ &args,
+ profile,
+ &envs,
+ &window,
+ new_process_owner(),
+ )
+ .await?;
if exit_code != 0 {
// 日志只保留输出尾部,避免刷屏(pnpm 失败信息集中在末尾)。
let tail: String = output
@@ -175,8 +200,10 @@ const REPAIR_OUTPUT_LIMIT: usize = 4000;
///
/// Windows 上 `.cmd`/`.bat` 无法被 CreateProcess 直接执行(需 cmd.exe 解析),
/// 用户 pnpm 只接受 `.exe`。
-pub(crate) fn pnpm_direct(app_handle: &AppHandle) -> Option<(PathBuf, Vec<OsString>)> {
- use super::install::{bundled_pnpm_major, pnpm_major_version_at, profile_store_major};
+pub(crate) async fn pnpm_direct(
+ app_handle: &AppHandle,
+) -> Result<Option<(PathBuf, Vec<OsString>)>, String> {
+ use super::install::{bundled_pnpm_major, pnpm_major_version_at_bounded, profile_store_major};
let bundled = config::get_pnpm_binary_path(app_handle);
let bundled_ready = bundled.exists();
@@ -186,7 +213,7 @@ pub(crate) fn pnpm_direct(app_handle: &AppHandle) -> Option<(PathBuf, Vec<OsStri
if bundled_matches {
let node = config::get_node_binary_path(app_handle);
- return Some((node, vec![bundled.into_os_string()]));
+ return Ok(Some((node, vec![bundled.into_os_string()])));
}
// 用户 pnpm 主版本与 store 一致(或 store 未知)都可直接用。Windows
@@ -196,121 +223,30 @@ pub(crate) fn pnpm_direct(app_handle: &AppHandle) -> Option<(PathBuf, Vec<OsStri
#[cfg(not(windows))]
let user_pnpm = cli::find_user_pnpm(app_handle);
if let Some(user) = user_pnpm {
- if store.is_none_or(|s| pnpm_major_version_at(&user) == Some(s)) {
- return Some((user, Vec::new()));
+ let matches = match store {
+ None => true,
+ Some(store) => {
+ pnpm_major_version_at_bounded(
+ &user,
+ Some(&config::get_node_binary_path(app_handle)),
+ None,
+ super::process::new_process_owner(),
+ )
+ .await?
+ == Some(store)
+ }
+ };
+ if matches {
+ return Ok(Some((user, Vec::new())));
}
}
// 都不匹配:退回捆绑版尽力一试(pnpm 会因 store 不兼容失败,由调用方记录)
if bundled_ready {
let node = config::get_node_binary_path(app_handle);
- return Some((node, vec![bundled.into_os_string()]));
+ return Ok(Some((node, vec![bundled.into_os_string()])));
}
- None
-}
-
-/// 启动子进程 `program args...`(cwd=`cwd`)并等待退出,返回 (退出码, 合并输出)。
-///
-/// Windows 复用隐藏控制台方案(`workflow::win_spawn`):GUI 进程直接以
-/// CREATE_NO_WINDOW 启动会让 node 的子进程各自新建可见控制台窗口(黑窗闪烁)。
-/// 原始进程句柄(`*mut c_void`)非 Send,整个「spawn + 读管道 + 等待」都在单个
-/// `spawn_blocking` 内完成(与 `plugin::process` 的等待语义一致),句柄不外传。
-async fn spawn_and_wait(
- program: &Path,
- args: &[OsString],
- cwd: &Path,
- envs: &HashMap<String, String>,
-) -> Result<(i32, String), String> {
- let captured = Arc::new(Mutex::new(String::new()));
-
- #[cfg(windows)]
- {
- use crate::service::workflow;
- use std::time::Duration;
-
- let program = program.to_path_buf();
- let args = args.to_vec();
- let cwd = cwd.to_path_buf();
- let envs = envs.clone();
- let captured = captured.clone();
- let (exit_code, output) = tauri::async_runtime::spawn_blocking(move || {
- use windows_sys::Win32::Foundation::CloseHandle;
- use windows_sys::Win32::System::Threading::{
- GetExitCodeProcess, WaitForSingleObject, INFINITE,
- };
-
- let (stdout, stderr, handle) = workflow::win_spawn::spawn_with_hidden_console_tracked(
- &program,
- &args,
- Some(&cwd),
- &envs,
- )
- .map_err(|e| format!("PNPM_REPAIR_SPAWN: {e}"))?;
- drain_pipe(stdout, captured.clone());
- drain_pipe(stderr, captured.clone());
-
- // 等孤立读取线程把管道内容写完(短命令通常已结束,此等待为兜底)。
- std::thread::sleep(Duration::from_millis(200));
- let exit_code = unsafe {
- let wait = WaitForSingleObject(handle, INFINITE);
- let mut code: u32 = 0;
- if GetExitCodeProcess(handle, &mut code) == 0 {
- code = wait;
- }
- CloseHandle(handle);
- code as i32
- };
- Ok::<_, String>((exit_code, drain_captured(captured)))
- })
- .await
- .map_err(|e| format!("PNPM_REPAIR_WAIT: {e}"))??;
- Ok((exit_code, output))
- }
-
- #[cfg(not(windows))]
- {
- use std::os::unix::process::CommandExt;
- use std::process::{Command, Stdio};
-
- let mut child = Command::new(program)
- .args(args)
- .envs(envs)
- .current_dir(cwd)
- .stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .process_group(0) // 独立进程组,便于将来取消
- .spawn()
- .map_err(|e| format!("PNPM_REPAIR_SPAWN: {e}"))?;
- if let Some(out) = child.stdout.take() {
- drain_pipe(out, captured.clone());
- }
- if let Some(err) = child.stderr.take() {
- drain_pipe(err, captured.clone());
- }
- let exit_code = tauri::async_runtime::spawn_blocking(move || {
- child.wait().map(|s| s.code().unwrap_or(1)).unwrap_or(1)
- })
- .await
- .map_err(|e| format!("PNPM_REPAIR_WAIT: {e}"))?;
-
- tokio::time::sleep(std::time::Duration::from_millis(200)).await;
- Ok((exit_code, drain_captured(captured)))
- }
-}
-
-/// 在独立线程中把管道读取到 EOF 并追加进共享缓冲区(无事件转发:修复过程
-/// 只需落日志,进度反馈非必需)。
-fn drain_pipe<R: Read + Send + 'static>(mut reader: R, captured: Arc<Mutex<String>>) {
- std::thread::spawn(move || {
- let mut buffer = Vec::new();
- if reader.read_to_end(&mut buffer).is_err() {
- return;
- }
- if let Ok(mut acc) = captured.lock() {
- acc.push_str(&String::from_utf8_lossy(&buffer));
- }
- });
+ Ok(None)
}
#[cfg(test)]
diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rs
index 2eaa088c..757ed8fb 100644
--- a/src-tauri/src/service/workflow/launch.rs
+++ b/src-tauri/src/service/workflow/launch.rs
@@ -490,19 +490,26 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
mark_phase("deprecated_plugins", &mut phase_started);
// 内置插件自愈:随包分发的内置插件(dsh-tauri 等)必须在服务进程加载插件
// 前就绪——核对「已安装 + 安装路径指向当前捆绑目录」,未安装、路径不正确
- // 或用户卸载后重启,一律强制重装(见 service::plugin::internal)。最佳
- // 努力:失败只告警,不阻断启动(核心功能缺失是发布缺陷,由 build:plugins 报错)。
+ // 或用户卸载后重启,一律强制重装(见 service::plugin::internal)。普通
+ // 失败只告警,不阻断启动(核心功能缺失是发布缺陷,由 build:plugins 报错);
+ // 但进程清理/协调器失败意味着前一次 pnpm 去向未确认,必须终止本次启动。
if let Err(e) = crate::service::plugin::ensure_internal_plugins(&app_handle).await {
+ if crate::service::plugin::is_process_cleanup_failure(&e) {
+ log::error!("ensure internal plugins blocked by unconfirmed process cleanup: {e}");
+ return Err(e);
+ }
log::warn!("ensure internal plugins failed: {e}");
}
mark_phase("ensure_internal_plugins", &mut phase_started);
// 预装插件完整性自检:清单引用的预装插件若在 node_modules 缺失产物,服务
// 启动时 loader 会对每个缺失插件抛 ERR_MODULE_NOT_FOUND 而整体失败(issue
// #90,日志特征 `Cannot find package`)。用 `pnpm install` 以现有 manifest +
- // lockfile 为准重建依赖图修复;修复失败只告警并给缺失插件记录错误标记
- // (启动失败场景由前端 recovery 对话框兜底,见 service::plugin::recovery)。
+ // lockfile 为准重建依赖图修复;普通修复失败只告警并给缺失插件记录错误标记
+ // (启动失败场景由前端 recovery 对话框兜底,见 service::plugin::recovery),
+ // 只有进程清理/协调器失败会作为 Err 传上来并终止启动。
if let Err(e) = crate::service::plugin::ensure_preset_plugins(&app_handle).await {
- log::warn!("ensure preset plugins failed: {e}");
+ log::error!("ensure preset plugins blocked by unconfirmed process cleanup: {e}");
+ return Err(e);
}
mark_phase("ensure_preset_plugins", &mut phase_started);
// 插件自愈(内置插件重装 / 预装插件完整性自检)可能刚把插件市场装进档案,而上一轮补丁
@@ -603,10 +610,18 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
// 让市场子进程的 pnpm 与桌面端同一套受控策略(store 主版本感知、避免落到系统
// homebrew pnpm)。与插件安装路径的 ensure_pnpm 版本感知一致,但启动阶段绝不
- // 触发下载;捆绑版未安装或与 store 不匹配时不注入(交由用户 pnpm)。
- // 最佳努力:失败只告警,不阻断启动。
- if crate::service::plugin::harness_prefer_bundled_pnpm(&app_handle) {
- envs.insert("DSH_PREFER_BUNDLED_PNPM".to_string(), "1".to_string());
+ // 触发下载;捆绑版未安装或与 store 不匹配时不注入(交由用户 pnpm)。探测被正常
+ // 安装占住或探针自身失败只告警,只有进程清理未确认才终止启动。
+ match crate::service::plugin::harness_prefer_bundled_pnpm(&app_handle).await {
+ Ok(true) => {
+ envs.insert("DSH_PREFER_BUNDLED_PNPM".to_string(), "1".to_string());
+ }
+ Ok(false) => {}
+ Err(e) if crate::service::plugin::is_process_cleanup_failure(&e) => {
+ log::error!("prefer bundled pnpm blocked by unconfirmed process cleanup: {e}");
+ return Err(e);
+ }
+ Err(e) => log::warn!("prefer bundled pnpm probe failed, keeping user pnpm: {e}"),
}
// 桌面端代理设置(issue #110):核心(dsh-http-proxy)在启动时读