Skip to content

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

fix: harden plugin readiness cleanup (#207)

Cloga Chend0b0c98e1502
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 2f599e71..10baefe9 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -823,6 +823,7 @@ dependencies = [
"flate2",
"futures-util",
"image",
+ "libc",
"log",
"objc2-foundation",
"regex",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 4efd78c9..7f0d4cce 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -69,6 +69,9 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = [
"NSProcessInfo",
] }
+[target.'cfg(unix)'.dependencies]
+libc = "0.2"
+
[target.'cfg(windows)'.dependencies]
rfd = "0.16"
webview2-com = "0.38"
diff --git a/src-tauri/src/service/plugin/cancel.rs b/src-tauri/src/service/plugin/cancel.rs
index a10e4c9d..46b83d72 100644
--- a/src-tauri/src/service/plugin/cancel.rs
+++ b/src-tauri/src/service/plugin/cancel.rs
@@ -51,7 +51,7 @@ pub(crate) async fn terminate_owned_install(owner: super::process::ProcessOwner)
}
#[cfg(windows)]
-fn terminate_pid_tree(pid: u32) -> bool {
+pub(crate) fn terminate_pid_tree(pid: u32) -> bool {
use std::os::windows::process::CommandExt;
let mut command = std::process::Command::new("taskkill");
command
@@ -66,7 +66,7 @@ fn terminate_pid_tree(pid: u32) -> bool {
}
#[cfg(not(windows))]
-fn terminate_pid_tree(pid: u32) -> bool {
+pub(crate) fn terminate_pid_tree(pid: u32) -> bool {
// `--` 防止负 PID 被解析为信号;KILL 保证忽略 TERM 的 pnpm/git 后代也退出。
let group = std::process::Command::new("kill")
.args(["-KILL", "--", &format!("-{pid}")])
diff --git a/src-tauri/src/service/plugin/install.rs b/src-tauri/src/service/plugin/install.rs
index d211966e..d4a9bd84 100644
--- a/src-tauri/src/service/plugin/install.rs
+++ b/src-tauri/src/service/plugin/install.rs
@@ -29,6 +29,7 @@ use crate::service::workflow;
use serde_yaml::{Mapping, Value};
use std::collections::HashMap;
use std::ffi::OsString;
+use std::io::Read;
use std::path::{Path, PathBuf};
use tauri::{AppHandle, Emitter, Manager, WebviewWindow};
@@ -36,8 +37,8 @@ use super::errors;
use super::installed::{installed_name, is_installed, profile_dir};
use super::preset::{bundled_dep_spec, bundled_plugin_dir, load_presets, PreinstallPluginInfo};
use super::process::{
- acquire_process_lock, new_process_owner, run_plugin_process, PidGuard, PreinstallLogPayload,
- ProcessOwner, PREINSTALL_LOG_EVENT,
+ acquire_operation_lock, acquire_process_lock, new_process_owner, run_plugin_process, PidGuard,
+ PreinstallLogPayload, ProcessOwner, PREINSTALL_LOG_EVENT,
};
use super::recovery::is_actionable_plugin_ref;
use super::uninstall_recovery;
@@ -55,6 +56,9 @@ const MAX_ALLOW_LIST_RETRIES: usize = 8;
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);
/// 校验并安装选中的预装插件:`dsh plugin --profile <当前档案> add <ids...>`
pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), String> {
@@ -605,7 +609,7 @@ async fn run_plugin_with_allow_build_retry(
cancel: Option<&tokio::sync::watch::Receiver<bool>>,
owner: ProcessOwner,
) -> Result<(i32, String), String> {
- let _process_guard = acquire_process_lock().await;
+ let _operation_guard = acquire_operation_lock().await;
let mut retries = 0usize;
let mut all_output = String::new();
let exit_code = loop {
@@ -989,6 +993,7 @@ async fn user_pnpm_major_version_bounded(
command.process_group(0);
}
+ let process_guard = acquire_process_lock().await?;
let child = match command
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
@@ -1006,35 +1011,372 @@ async fn user_pnpm_major_version_bounded(
let pid = child.id();
let pid_guard = PidGuard::set(owner, pid);
let mut waiter = tauri::async_runtime::spawn_blocking(move || {
- let _pid_guard = pid_guard;
- child.wait_with_output()
+ let mut child = child;
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ wait_for_probe_output(&mut child)
+ }))
+ .unwrap_or_else(|_| {
+ 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) => joined
- .map_err(|e| format!("PNPM_PROBE_WAIT_FAILED: {e}"))?
- .map_err(|e| format!("PNPM_PROBE_OUTPUT_FAILED: {e}"))?,
+ 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);
+ }
+ }
+ }
Err(_) => {
- log::warn!(
+ let reason = format!(
"PNPM_PROBE_TIMEOUT: pnpm version probe exceeded {} seconds",
PNPM_PROBE_TIMEOUT.as_secs()
);
+ log::error!("{reason}");
+ super::process::mark_process_cleanup_failed(owner, reason.clone());
super::cancel::terminate_owned_install(owner).await;
- let joined = tokio::time::timeout(PNPM_PROBE_CLEANUP_TIMEOUT, &mut waiter)
- .await
- .map_err(|_| {
- "PNPM_PROBE_CLEANUP_TIMEOUT: pnpm version probe did not exit after forced termination"
- .to_string()
- })?;
- joined
- .map_err(|e| format!("PNPM_PROBE_WAIT_FAILED: {e}"))?
- .map_err(|e| format!("PNPM_PROBE_OUTPUT_FAILED: {e}"))?;
- return Ok(None);
+ 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(_)) => {
+ super::process::clear_process_cleanup_failed(owner);
+ return Err(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(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,
+ },
+}
+
+struct ProbeCleanupPending {
+ child: std::process::Child,
+ pid: u32,
+ reason: String,
+ owner: ProcessOwner,
+ _process_guard: tokio::sync::OwnedMutexGuard<()>,
+ _pid_guard: PidGuard,
+}
+
+impl ProbeCleanupPending {
+ fn release(self) {
+ let Self {
+ child,
+ owner,
+ _process_guard,
+ _pid_guard,
+ ..
+ } = self;
+ 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)),
+ };
+ 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,
+ }))
+}
+
+fn reap_probe_after_wait_failure(
+ child: &mut std::process::Child,
+ pid: u32,
+ error: std::io::Error,
+) -> ProbeWaitResult {
+ 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::process::plugin_process_has_exited(pid) {
+ return ProbeWaitResult::Finished(Err(error));
+ }
+ }
+ }
+ 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}"
+ ),
+ };
+ }
+ std::thread::sleep(PNPM_PROBE_REAP_RETRY_INTERVAL);
+ }
+}
+
+fn monitor_probe_cleanup(mut pending: ProbeCleanupPending) {
+ 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();
+ });
+}
+
+fn monitor_probe_wait_task(
+ waiter: tauri::async_runtime::JoinHandle<ProbeTaskResult>,
+ owner: ProcessOwner,
+ pid: u32,
+ reason: String,
+ process_guard: tokio::sync::OwnedMutexGuard<()>,
+ pid_guard: PidGuard,
+) {
+ super::process::mark_process_cleanup_failed(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::process::release_process_cleanup(owner, pid_guard, process_guard);
+ }
+ Err(error) => {
+ log::error!("pnpm version probe cleanup wait task failed: {error}");
+ wait_for_probe_cleanup_with(
+ || !super::process::plugin_process_has_exited(pid),
+ PNPM_PROBE_LIVENESS_INTERVAL,
+ )
+ .await;
+ super::process::release_process_cleanup(owner, pid_guard, process_guard);
+ }
+ }
+ });
+}
+
+fn monitor_orphaned_probe_pid(
+ owner: ProcessOwner,
+ pid: u32,
+ reason: String,
+ process_guard: tokio::sync::OwnedMutexGuard<()>,
+ pid_guard: PidGuard,
+) {
+ super::process::mark_process_cleanup_failed(owner, reason);
+ super::cancel::terminate_pid_tree(pid);
+ tauri::async_runtime::spawn(async move {
+ wait_for_probe_cleanup_with(
+ || !super::process::plugin_process_has_exited(pid),
+ PNPM_PROBE_LIVENESS_INTERVAL,
+ )
+ .await;
+ super::process::release_process_cleanup(owner, pid_guard, process_guard);
+ });
+}
+
+async fn wait_for_probe_cleanup(pending: &mut 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::process::plugin_process_has_exited(pending.pid)
+ }
+ },
+ 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)
+where
+ F: FnMut() -> bool,
+{
+ while remains_active() {
+ tokio::time::sleep(interval).await;
+ }
+}
+
+fn read_probe_pipe<R: Read>(pipe: Option<R>) -> std::io::Result<Vec<u8>> {
+ let mut output = Vec::new();
+ if let Some(mut pipe) = pipe {
+ pipe.read_to_end(&mut output)?;
+ }
+ 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",
+ pnpm.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 主版本号(解析 `pnpm --version` 首个点分字段);不存在或不可运行
/// (corepack shim 在 Node 24 上 ERR_INVALID_THIS 崩溃等)返回 None。
///
@@ -1659,11 +2001,76 @@ mod tests {
dep_path_to_name, diagnostic_suffix, extract_allow_line_key, extract_only_builds_git_name,
git_transport_hint, has_github_ssh_rewrite_in_output, normalize_git_spec,
parse_allowlist_keys, parse_store_major_from_modules_yaml, preset_spec_for_install,
+ probe_output_or_fallback, probe_task_or_fallback, read_probe_pipe,
rewrite_rule_targets_ssh_github, shell_quote_spec, silent_install_failure_detail,
- PreinstallPluginInfo,
+ wait_for_probe_cleanup_with, PreinstallPluginInfo,
};
use std::path::PathBuf;
+ #[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());
+ }
+
+ #[tokio::test]
+ async fn pnpm_probe_cleanup_monitor_releases_after_process_disappears() {
+ let polls = std::sync::atomic::AtomicUsize::new(0);
+ tokio::time::timeout(
+ std::time::Duration::from_millis(50),
+ wait_for_probe_cleanup_with(
+ || polls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
+ std::time::Duration::from_millis(1),
+ ),
+ )
+ .await
+ .expect("cleanup monitor should release after liveness turns false");
+ assert_eq!(polls.load(std::sync::atomic::Ordering::SeqCst), 3);
+ }
+
+ #[tokio::test]
+ async fn pnpm_probe_cleanup_monitor_stays_fail_closed_while_process_lives() {
+ let pending = tokio::time::timeout(
+ std::time::Duration::from_millis(5),
+ wait_for_probe_cleanup_with(|| true, std::time::Duration::from_millis(1)),
+ )
+ .await;
+ assert!(pending.is_err());
+ }
+
+ struct BrokenPipeReader;
+
+ impl std::io::Read for BrokenPipeReader {
+ fn read(&mut self, _buffer: &mut [u8]) -> std::io::Result<usize> {
+ Err(std::io::Error::new(
+ std::io::ErrorKind::BrokenPipe,
+ "probe output pipe closed",
+ ))
+ }
+ }
+
+ #[test]
+ fn pnpm_probe_broken_output_pipe_is_reported_as_fallback_failure() {
+ let error = read_probe_pipe(Some(BrokenPipeReader)).unwrap_err();
+ assert_eq!(error.kind(), std::io::ErrorKind::BrokenPipe);
+ }
+
#[cfg(unix)]
#[test]
fn pnpm_major_version_at_probes_the_exact_selected_path() {
diff --git a/src-tauri/src/service/plugin/internal.rs b/src-tauri/src/service/plugin/internal.rs
index 18c54bb5..a365afb6 100644
--- a/src-tauri/src/service/plugin/internal.rs
+++ b/src-tauri/src/service/plugin/internal.rs
@@ -29,17 +29,31 @@ use super::preset::{bundled_dep_spec, bundled_plugin_dir, load_presets, Preinsta
#[derive(serde::Serialize, Clone)]
struct InternalPluginsPhase {
phase: &'static str,
- detail: &'static str,
+ detail: InternalPluginPhaseDetail,
completed: usize,
total: usize,
}
+#[derive(serde::Serialize, Clone, Copy)]
+#[serde(rename_all = "lowercase")]
+enum InternalPluginPhaseDetail {
+ Waiting,
+ Checking,
+ Installing,
+ Heartbeat,
+ Done,
+ Timeout,
+ Cancelled,
+}
+
/// 串行化内置插件核对/安装:auto_start(Rust 侧 start→launch)与前端 boot 流程
/// (新增的 boot 期 ensure 命令)可能并发触发,而安装会启动 `dsh plugin add`
/// 子进程——两个 pnpm 抢同一档案目录会互相打断。若另一路正在执行,这里等它
/// 完成后再核对(幂等:上次已装好则本轮全部 no-op)。
const ENSURE_ABSOLUTE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10 * 60);
const ENSURE_CLEANUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
+const ENSURE_OWNER_DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
+const ENSURE_OWNER_DRAIN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);
#[derive(Clone)]
struct EnsureFlight {
@@ -50,15 +64,17 @@ struct EnsureFlight {
cancel: tokio::sync::watch::Sender<bool>,
}
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+#[derive(Clone, Debug, Eq, PartialEq)]
enum EnsureFlightState {
Running,
Cancelling,
+ CleanupFailed(String),
}
enum EnsureSubscription {
Running(tokio::sync::watch::Receiver<Option<Result<(), String>>>),
Cancelling(tokio::sync::watch::Receiver<Option<Result<(), String>>>),
+ CleanupFailed(String),
}
#[derive(Default)]
@@ -69,9 +85,12 @@ struct EnsureCoordinator {
impl EnsureCoordinator {
fn subscribe(&self) -> Option<EnsureSubscription> {
- self.active.as_ref().map(|flight| match flight.state {
+ self.active.as_ref().map(|flight| match &flight.state {
EnsureFlightState::Running => EnsureSubscription::Running(flight.result.clone()),
EnsureFlightState::Cancelling => EnsureSubscription::Cancelling(flight.result.clone()),
+ EnsureFlightState::CleanupFailed(reason) => {
+ EnsureSubscription::CleanupFailed(reason.clone())
+ }
})
}
@@ -108,10 +127,18 @@ impl EnsureCoordinator {
fn begin_cancel(&mut self) -> Option<tokio::sync::watch::Receiver<Option<Result<(), String>>>> {
let active = self.active.as_mut()?;
- active.state = EnsureFlightState::Cancelling;
- let _ = active.cancel.send(true);
+ if !matches!(&active.state, EnsureFlightState::CleanupFailed(_)) {
+ active.state = EnsureFlightState::Cancelling;
+ let _ = active.cancel.send(true);
+ }
Some(active.result.clone())
}
+
+ fn mark_cleanup_failed(&mut self, id: u64, reason: String) {
+ if let Some(active) = self.active.as_mut().filter(|flight| flight.id == id) {
+ active.state = EnsureFlightState::CleanupFailed(reason);
+ }
+ }
}
static ENSURE_LOCK: std::sync::OnceLock<tokio::sync::Mutex<EnsureCoordinator>> =
@@ -143,12 +170,26 @@ async fn subscribe_or_start(
let app_handle = app_handle.clone();
let internal = internal.to_vec();
tauri::async_runtime::spawn(async move {
- let outcome =
+ let mut outcome =
run_ensure_operation(&app_handle, &internal, owner, cancel_tx, cancel_rx).await;
// 强杀返回不等于持有句柄的 wait 已完成;必须等精确 owner 的 PID
// 守卫随 wait 退出,才能发布结果并允许 Retry 创建下一次 flight。
- while super::process::active_plugin_pid(owner).is_some() {
- tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ if !wait_for_owner_release(owner, ENSURE_OWNER_DRAIN_TIMEOUT).await {
+ let reason = format!(
+ "INTERNAL_PLUGIN_PROCESS_REAP_TIMEOUT: plugin process owner {owner:?} remained active for {} seconds",
+ ENSURE_OWNER_DRAIN_TIMEOUT.as_secs()
+ );
+ log::error!("{reason}");
+ outcome = Err(reason.clone());
+ let _ = result_tx.send(Some(outcome));
+ ensure_lock().lock().await.mark_cleanup_failed(id, reason);
+ // 保留 cleanup-failed flight 与唯一 owner;进程锁仍由 wait 线程持有。
+ // 若系统最终完成 reap,再释放 flight 允许后续 Retry。
+ while super::process::active_plugin_pid(owner).is_some() {
+ tokio::time::sleep(ENSURE_OWNER_DRAIN_INTERVAL).await;
+ }
+ ensure_lock().lock().await.finish(id);
+ return;
}
ensure_lock().lock().await.finish(id);
let _ = result_tx.send(Some(outcome));
@@ -174,10 +215,44 @@ where
// 移除后回到循环,创建且只创建一个全新的 flight。
let _ = receive_flight_result(&mut result).await?;
}
+ EnsureSubscription::CleanupFailed(reason) => return Err(reason),
}
}
}
+async fn wait_for_owner_release(
+ owner: super::process::ProcessOwner,
+ timeout: std::time::Duration,
+) -> bool {
+ wait_for_release_with(
+ || super::process::active_plugin_pid(owner).is_some(),
+ timeout,
+ ENSURE_OWNER_DRAIN_INTERVAL,
+ )
+ .await
+}
+
+async fn wait_for_release_with<F>(
+ mut is_active: F,
+ timeout: std::time::Duration,
+ interval: std::time::Duration,
+) -> bool
+where
+ F: FnMut() -> bool,
+{
+ let started = tokio::time::Instant::now();
+ loop {
+ if !is_active() {
+ return true;
+ }
+ let elapsed = started.elapsed();
+ if elapsed >= timeout {
+ return false;
+ }
+ tokio::time::sleep(interval.min(timeout - elapsed)).await;
+ }
+}
+
async fn receive_flight_result(
result: &mut tokio::sync::watch::Receiver<Option<Result<(), String>>>,
) -> Result<Result<(), String>, String> {
@@ -206,8 +281,10 @@ pub(crate) async fn cancel() -> Result<(), String> {
.begin_cancel()
.expect("active flight must remain present while coordinator lock is held")
};
- let _ = receive_flight_result(&mut result).await?;
- Ok(())
+ match receive_flight_result(&mut result).await? {
+ Err(reason) if reason.starts_with("INTERNAL_PLUGIN_PROCESS_REAP_TIMEOUT:") => Err(reason),
+ _ => Ok(()),
+ }
}
async fn run_ensure_operation(
@@ -218,8 +295,20 @@ async fn run_ensure_operation(
mut cancel: tokio::sync::watch::Receiver<bool>,
) -> Result<(), String> {
let total = internal.len();
- emit_phase(app_handle, "loading", "waiting", 0, total);
- emit_phase(app_handle, "progress", "checking", 0, total);
+ emit_phase(
+ app_handle,
+ "loading",
+ InternalPluginPhaseDetail::Waiting,
+ 0,
+ total,
+ );
+ emit_phase(
+ app_handle,
+ "progress",
+ InternalPluginPhaseDetail::Checking,
+ 0,
+ total,
+ );
let refs: Vec<_> = internal.iter().collect();
let operation = ensure_inner(app_handle, &refs, cancel.clone(), owner);
tokio::pin!(operation);
@@ -231,7 +320,7 @@ async fn run_ensure_operation(
loop {
tokio::select! {
outcome = &mut operation => {
- emit_phase(app_handle, "done", "done", total, total);
+ emit_phase(app_handle, "done", InternalPluginPhaseDetail::Done, total, total);
return outcome;
}
_ = &mut deadline => {
@@ -242,7 +331,7 @@ async fn run_ensure_operation(
if tokio::time::timeout(ENSURE_CLEANUP_TIMEOUT, &mut operation).await.is_err() {
log::error!("INTERNAL_PLUGIN_CLEANUP_TIMEOUT: plugin process did not exit after forced termination");
}
- emit_phase(app_handle, "done", "timeout", 0, total);
+ emit_phase(app_handle, "done", InternalPluginPhaseDetail::Timeout, 0, total);
return Err(reason.to_string());
}
changed = cancel.changed() => {
@@ -253,12 +342,12 @@ async fn run_ensure_operation(
if tokio::time::timeout(ENSURE_CLEANUP_TIMEOUT, &mut operation).await.is_err() {
log::error!("INTERNAL_PLUGIN_CLEANUP_TIMEOUT: plugin process did not exit after forced termination");
}
- emit_phase(app_handle, "done", "cancelled", 0, total);
+ emit_phase(app_handle, "done", InternalPluginPhaseDetail::Cancelled, 0, total);
return Err(reason.to_string());
}
}
_ = heartbeat.tick() => {
- emit_phase(app_handle, "progress", "heartbeat", 0, total);
+ emit_phase(app_handle, "progress", InternalPluginPhaseDetail::Heartbeat, 0, total);
}
}
}
@@ -267,7 +356,7 @@ async fn run_ensure_operation(
fn emit_phase(
app_handle: &AppHandle,
phase: &'static str,
- detail: &'static str,
+ detail: InternalPluginPhaseDetail,
completed: usize,
total: usize,
) {
@@ -354,7 +443,13 @@ async fn ensure_inner(
let ids: Vec<String> = need.iter().map(|(id, _, _)| id.clone()).collect();
log::info!("Reinstalling internal preset plugins: {ids:?}");
- emit_phase(app_handle, "progress", "installing", 0, ids.len());
+ emit_phase(
+ app_handle,
+ "progress",
+ InternalPluginPhaseDetail::Installing,
+ 0,
+ ids.len(),
+ );
// pnpm add 会先解析清单里的所有既有依赖。0.9.0 将随包目录从
// `preset-plugins` 迁至 `internal-plugins` 后,旧 file:/link: 路径已不存在,pnpm
@@ -599,6 +694,7 @@ mod tests {
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
cancelling_subscribed.notify_one();
}
+
return subscription;
}
let (id, owner, result_tx, result_rx, _, _) = coordinator.start();
@@ -655,6 +751,31 @@ mod tests {
assert!(coordinator.lock().await.subscribe().is_none());
}
+ #[tokio::test]
+ async fn stuck_owner_is_bounded_and_blocks_new_flights_without_hanging_waiters() {
+ let released = wait_for_release_with(
+ || true,
+ std::time::Duration::from_millis(5),
+ std::time::Duration::from_millis(1),
+ )
+ .await;
+ assert!(!released);
+
+ let mut coordinator = EnsureCoordinator::default();
+ let (id, _, result_tx, mut result, _, _) = coordinator.start();
+ let reason = "INTERNAL_PLUGIN_PROCESS_REAP_TIMEOUT: test owner remained active".to_string();
+ result_tx.send(Some(Err(reason.clone()))).unwrap();
+ coordinator.mark_cleanup_failed(id, reason.clone());
+
+ assert!(matches!(
+ coordinator.subscribe(),
+ Some(EnsureSubscription::CleanupFailed(error)) if error == reason
+ ));
+ let outcome = receive_flight_result(&mut result).await.unwrap();
+ assert_eq!(outcome, Err(reason));
+ assert_eq!(coordinator.next_id, 1);
+ }
+
#[test]
fn internal_plugin_entry_requires_readable_manifest_object() {
let root = std::env::temp_dir().join(format!(
diff --git a/src-tauri/src/service/plugin/process.rs b/src-tauri/src/service/plugin/process.rs
index 86c9a4fe..fdfd1dc6 100644
--- a/src-tauri/src/service/plugin/process.rs
+++ b/src-tauri/src/service/plugin/process.rs
@@ -40,11 +40,19 @@ pub(crate) struct ProcessOwner(u64);
static NEXT_PROCESS_OWNER: AtomicU64 = AtomicU64::new(1);
static ACTIVE_PLUGIN_PIDS: OnceLock<Mutex<HashMap<ProcessOwner, u32>>> = OnceLock::new();
static PLUGIN_PROCESS_LOCK: OnceLock<Arc<tokio::sync::Mutex<()>>> = OnceLock::new();
+static PLUGIN_OPERATION_LOCK: OnceLock<Arc<tokio::sync::Mutex<()>>> = OnceLock::new();
+static PLUGIN_CLEANUP_FAILURE: OnceLock<
+ tokio::sync::watch::Sender<Option<(ProcessOwner, String)>>,
+> = OnceLock::new();
fn active_pid_lock() -> &'static Mutex<HashMap<ProcessOwner, u32>> {
ACTIVE_PLUGIN_PIDS.get_or_init(|| Mutex::new(HashMap::new()))
}
+fn cleanup_failure_sender() -> &'static tokio::sync::watch::Sender<Option<(ProcessOwner, String)>> {
+ PLUGIN_CLEANUP_FAILURE.get_or_init(|| tokio::sync::watch::channel(None).0)
+}
+
pub(crate) fn new_process_owner() -> ProcessOwner {
ProcessOwner(NEXT_PROCESS_OWNER.fetch_add(1, Ordering::Relaxed))
}
@@ -66,8 +74,98 @@ pub(crate) fn active_plugin_processes() -> Vec<(ProcessOwner, u32)> {
.collect()
}
-pub(crate) async fn acquire_process_lock() -> tokio::sync::OwnedMutexGuard<()> {
- PLUGIN_PROCESS_LOCK
+#[cfg(windows)]
+pub(crate) fn plugin_process_has_exited(pid: u32) -> bool {
+ use windows_sys::Win32::Foundation::CloseHandle;
+ use windows_sys::Win32::System::Threading::{
+ OpenProcess, WaitForSingleObject, PROCESS_QUERY_LIMITED_INFORMATION,
+ };
+ const SYNCHRONIZE_ACCESS: u32 = 0x0010_0000;
+ let handle = unsafe {
+ OpenProcess(
+ PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE_ACCESS,
+ 0,
+ pid,
+ )
+ };
+ if handle.is_null() {
+ return std::io::Error::last_os_error().raw_os_error() == Some(87);
+ }
+ let wait = unsafe { WaitForSingleObject(handle, 0) };
+ unsafe { CloseHandle(handle) };
+ wait == 0
+}
+
+#[cfg(not(windows))]
+pub(crate) fn plugin_process_has_exited(pid: u32) -> bool {
+ let mut status = 0;
+ let waited = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, libc::WNOHANG) };
+ if waited == pid as libc::pid_t {
+ return true;
+ }
+ if waited == 0 {
+ return false;
+ }
+ let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
+ result != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
+}
+
+pub(crate) fn mark_process_cleanup_failed(owner: ProcessOwner, reason: String) {
+ cleanup_failure_sender().send_replace(Some((owner, reason)));
+}
+
+pub(crate) fn clear_process_cleanup_failed(owner: ProcessOwner) {
+ cleanup_failure_sender().send_if_modified(|failure| {
+ if failure.as_ref().is_some_and(|(active, _)| *active == owner) {
+ *failure = None;
+ true
+ } else {
+ false
+ }
+ });
+}
+
+pub(crate) fn release_process_cleanup(
+ owner: ProcessOwner,
+ pid_guard: PidGuard,
+ process_guard: tokio::sync::OwnedMutexGuard<()>,
+) {
+ clear_process_cleanup_failed(owner);
+ drop(pid_guard);
+ drop(process_guard);
+}
+
+pub(crate) async fn acquire_process_lock() -> Result<tokio::sync::OwnedMutexGuard<()>, String> {
+ let lock = PLUGIN_PROCESS_LOCK
+ .get_or_init(|| Arc::new(tokio::sync::Mutex::new(())))
+ .clone();
+ let mut cleanup_failure = cleanup_failure_sender().subscribe();
+ loop {
+ if let Some((_, reason)) = cleanup_failure.borrow().as_ref() {
+ return Err(reason.clone());
+ }
+ tokio::select! {
+ guard = lock.clone().lock_owned() => {
+ if let Some((_, reason)) = cleanup_failure.borrow().as_ref() {
+ drop(guard);
+ return Err(reason.clone());
+ }
+ return Ok(guard);
+ }
+ changed = cleanup_failure.changed() => {
+ if changed.is_err() {
+ return Err(
+ "PLUGIN_PROCESS_COORDINATOR_DROPPED: cleanup coordinator ended unexpectedly"
+ .to_string(),
+ );
+ }
+ }
+ }
+ }
+}
+
+pub(crate) async fn acquire_operation_lock() -> tokio::sync::OwnedMutexGuard<()> {
+ PLUGIN_OPERATION_LOCK
.get_or_init(|| Arc::new(tokio::sync::Mutex::new(())))
.clone()
.lock_owned()
@@ -122,6 +220,7 @@ pub(crate) async fn run_plugin_process(
window: &WebviewWindow,
owner: ProcessOwner,
) -> Result<(i32, String), String> {
+ let process_guard = acquire_process_lock().await?;
let captured = Arc::new(Mutex::new(String::new()));
#[cfg(windows)]
@@ -137,6 +236,7 @@ pub(crate) async fn run_plugin_process(
let handle = WaitableHandle(handle);
let exit_code = tauri::async_runtime::spawn_blocking(move || {
+ let _process_guard = process_guard;
let _pid_guard = pid_guard;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::{
@@ -190,6 +290,7 @@ pub(crate) async fn run_plugin_process(
}
let exit_code = tauri::async_runtime::spawn_blocking(move || {
+ let _process_guard = process_guard;
let _pid_guard = pid_guard;
child.wait().map(|s| s.code().unwrap_or(1)).unwrap_or(1)
})
@@ -251,4 +352,48 @@ mod tests {
drop(current);
assert_eq!(active_plugin_pid(owner), None);
}
+
+ #[tokio::test]
+ async fn cleanup_failure_clears_before_lock_handoff_and_preserves_other_owner() {
+ let guard = acquire_process_lock().await.unwrap();
+ let owner = new_process_owner();
+ let pid_guard = PidGuard::set(owner, 100);
+ let reason = "PLUGIN_PROCESS_CLEANUP_FAILED: test process is still active".to_string();
+ mark_process_cleanup_failed(owner, reason.clone());
+
+ let waiter = tokio::spawn(acquire_process_lock());
+ tokio::task::yield_now().await;
+ assert!(
+ waiter.is_finished(),
+ "active cleanup failure should wake a queued waiter"
+ );
+ assert_eq!(waiter.await.unwrap().unwrap_err(), reason);
+
+ clear_process_cleanup_failed(owner);
+ let handoff = tokio::spawn(acquire_process_lock());
+ tokio::task::yield_now().await;
+ assert!(
+ !handoff.is_finished(),
+ "waiter should queue after failure clears while guard remains held"
+ );
+ drop(pid_guard);
+ drop(guard);
+ assert!(handoff.await.unwrap().is_ok());
+ assert_eq!(active_plugin_pid(owner), None);
+
+ let guard = acquire_process_lock().await.unwrap();
+ let other_owner = new_process_owner();
+ let stale_pid_guard = PidGuard::set(owner, 101);
+ let other_reason =
+ "PLUGIN_PROCESS_CLEANUP_FAILED: another owner is still active".to_string();
+ mark_process_cleanup_failed(other_owner, other_reason.clone());
+ release_process_cleanup(owner, stale_pid_guard, guard);
+
+ assert_eq!(
+ acquire_process_lock().await.unwrap_err(),
+ other_reason,
+ "clearing a stale owner must not remove another owner's failure"
+ );
+ clear_process_cleanup_failed(other_owner);
+ }
}
diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rs
index f77b341e..5507cd06 100644
--- a/src-tauri/src/service/workflow/mod.rs
+++ b/src-tauri/src/service/workflow/mod.rs
@@ -1397,7 +1397,7 @@ mod tests {
// 端口此刻确实被占用(模拟残留进程仍在监听)
assert!(is_port_in_use(held));
- std::thread::spawn(move || {
+ let releaser = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(150));
drop(listener);
});
@@ -1409,7 +1409,7 @@ mod tests {
started.elapsed() < std::time::Duration::from_millis(800),
"wait_for_port_release should return shortly after the port is released, not wait the full window"
);
- assert!(!is_port_in_use(held));
+ releaser.join().expect("port releaser thread");
}
#[test]
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index e2a04cba..0bfd40ed 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -19,6 +19,8 @@
"status.internal_checking": "Checking {{total}} internal plugins.",
"status.internal_installing": "Installing {{total}} internal plugins.",
"status.internal_done": "Verified {{total}} internal plugins.",
+ "status.internal_timeout": "Internal plugin installation timed out.",
+ "status.internal_cancelled": "Internal plugin installation was cancelled.",
"startup.phase.plugin-install": "plugin installation",
"startup.phase.process-boot": "process boot",
"startup.phase.client-modules": "client modules",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 07a8c249..1a5ed735 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -19,6 +19,8 @@
"status.internal_checking": "正在检查 {{total}} 个内部插件。",
"status.internal_installing": "正在安装 {{total}} 个内部插件。",
"status.internal_done": "已核验 {{total}} 个内部插件。",
+ "status.internal_timeout": "内部插件安装已超时。",
+ "status.internal_cancelled": "内部插件安装已取消。",
"startup.phase.plugin-install": "插件安装",
"startup.phase.process-boot": "进程启动",
"startup.phase.client-modules": "客户端模块加载",
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index d0dc99c3..b9b8b54f 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -18,6 +18,7 @@ import { listen } from '@tauri-apps/api/event'
import i18next from 'i18next'
import { defineStore } from 'valtio-define'
import { queryClient } from '@/config/client'
+import { internalPluginReason } from '@/utils/internal-plugin-phase'
import { containsInotifyLimitError, pickErrorLines } from '@/utils/log'
import { BoundedReloadGate, pollReadiness, SingleFlight, waitForActivityTask } from '@/utils/readiness'
import { harnessUpdater } from '../harness-updater'
@@ -152,22 +153,6 @@ function startupError(phase: StartupPhase, reason: string, kind: 'failed' | 'ina
return error
}
-function internalPluginReason(payload: InternalPluginsPhasePayload): string {
- if (payload.detail === 'waiting') {
- return i18next.t('status.internal_waiting')
- }
- if (payload.detail === 'checking') {
- return i18next.t('status.internal_checking', { total: payload.total })
- }
- if (payload.detail === 'installing') {
- return i18next.t('status.internal_installing', { total: payload.total })
- }
- if (payload.detail === 'done') {
- return i18next.t('status.internal_done', { total: payload.total })
- }
- return pluginActivityReason
-}
-
function pollHarnessReadiness(
absoluteTimeoutMs: number,
shouldContinue: () => boolean,
@@ -313,7 +298,11 @@ export const harness = defineStore({
await listen<InternalPluginsPhasePayload>('internal-plugins-phase', (event) => {
const payload = event.payload
pluginActivitySequence++
- pluginActivityReason = internalPluginReason(payload)
+ pluginActivityReason = internalPluginReason(
+ payload,
+ pluginActivityReason,
+ (key, options) => i18next.t(key, options),
+ )
if (payload.phase !== 'done') {
this.startupPhase = 'plugin-install'
this.startupReason = pluginActivityReason
diff --git a/src/store/modules/harness/types.ts b/src/store/modules/harness/types.ts
index ea405170..73d69c88 100644
--- a/src/store/modules/harness/types.ts
+++ b/src/store/modules/harness/types.ts
@@ -24,9 +24,21 @@ export interface PreinstallLogPayload {
}
/** Rust 侧 internal-plugins-phase 事件载荷(内置插件核对/安装进度与 heartbeat) */
+export const INTERNAL_PLUGIN_PHASE_DETAILS = [
+ 'waiting',
+ 'checking',
+ 'installing',
+ 'heartbeat',
+ 'done',
+ 'timeout',
+ 'cancelled',
+] as const
+
+export type InternalPluginPhaseDetail = typeof INTERNAL_PLUGIN_PHASE_DETAILS[number]
+
export interface InternalPluginsPhasePayload {
phase: 'loading' | 'progress' | 'done'
- detail: 'waiting' | 'checking' | 'installing' | 'heartbeat' | 'done'
+ detail: InternalPluginPhaseDetail
completed: number
total: number
}
diff --git a/src/utils/internal-plugin-phase.ts b/src/utils/internal-plugin-phase.ts
new file mode 100644
index 00000000..60a08d02
--- /dev/null
+++ b/src/utils/internal-plugin-phase.ts
@@ -0,0 +1,29 @@
+import type { InternalPluginsPhasePayload } from '@/store/modules/harness/types'
+
+export type InternalPluginPhaseTranslate = (
+ key: string,
+ options?: Record<string, number>,
+) => string
+
+export function internalPluginReason(
+ payload: InternalPluginsPhasePayload,
+ previousReason: string,
+ translate: InternalPluginPhaseTranslate,
+): string {
+ switch (payload.detail) {
+ case 'waiting':
+ return translate('status.internal_waiting')
+ case 'checking':
+ return translate('status.internal_checking', { total: payload.total })
+ case 'installing':
+ return translate('status.internal_installing', { total: payload.total })
+ case 'heartbeat':
+ return previousReason
+ case 'done':
+ return translate('status.internal_done', { total: payload.total })
+ case 'timeout':
+ return translate('status.internal_timeout')
+ case 'cancelled':
+ return translate('status.internal_cancelled')
+ }
+}
diff --git a/test/internal-plugin-phase.test.ts b/test/internal-plugin-phase.test.ts
new file mode 100644
index 00000000..24f6a823
--- /dev/null
+++ b/test/internal-plugin-phase.test.ts
@@ -0,0 +1,51 @@
+import type { InternalPluginsPhasePayload } from '../src/store/modules/harness/types'
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+import { INTERNAL_PLUGIN_PHASE_DETAILS } from '../src/store/modules/harness/types'
+import { internalPluginReason } from '../src/utils/internal-plugin-phase'
+
+function translate(key: string): string {
+ return key
+}
+
+function payload(detail: InternalPluginsPhasePayload['detail']): InternalPluginsPhasePayload {
+ return {
+ phase: 'done',
+ detail,
+ completed: 0,
+ total: 5,
+ }
+}
+
+describe('internal plugin phase contract', () => {
+ it('matches every Rust detail emitted by the startup phase', () => {
+ const rustSource = readFileSync(
+ new URL('../src-tauri/src/service/plugin/internal.rs', import.meta.url),
+ 'utf8',
+ )
+ const declaration = rustSource.match(
+ /enum InternalPluginPhaseDetail \{(?<variants>[^}]+)\}/,
+ )
+ const rustDetails = declaration?.groups?.variants
+ .match(/\b[A-Z][A-Za-z]+\b/g)
+ ?.map(variant => variant.toLowerCase())
+
+ expect(rustDetails).toEqual(INTERNAL_PLUGIN_PHASE_DETAILS)
+ })
+
+ it('replaces stale activity text for timeout and cancellation terminal events', () => {
+ const stale = 'status.internal_installing'
+
+ expect(internalPluginReason(payload('timeout'), stale, translate))
+ .toBe('status.internal_timeout')
+ expect(internalPluginReason(payload('cancelled'), stale, translate))
+ .toBe('status.internal_cancelled')
+ })
+
+ it('retains the active reason only for heartbeat events', () => {
+ expect(internalPluginReason(payload('heartbeat'), 'active install', translate))
+ .toBe('active install')
+ expect(internalPluginReason(payload('done'), 'active install', translate))
+ .toBe('status.internal_done')
+ })
+})