DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix: recover plugin readiness after delayed reinstall (#204)
Cloga Chen95220552addb
diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rsindex 728fb504..bcdb7fb5 100644--- a/src-tauri/src/bridge/plugin.rs+++ b/src-tauri/src/bridge/plugin.rs@@ -56,13 +56,17 @@ pub async fn skip_preinstall_plugins(app_handle: AppHandle) -> Result<(), String////// 与 service 启动路径(`workflow::launch` 内)共用 `plugin::ensure_internal_plugins`/// 同一实现:内部有并发锁、幂等,此后启动/重启路径会再核对但均为 no-op。-/// 最佳努力:失败只记告警,不阻断启动;前端据此在「Loading internal plugins…」-/// 与「Loading plugins…」之间切换加载屏文案。+/// 错误返回前端,由启动状态机按 plugin-install 阶段展示精确错误与重试入口;+/// workflow 自启动路径仍保留最佳努力语义。#[tauri::command]-pub async fn ensure_internal_plugins(app_handle: AppHandle) {- if let Err(e) = plugin::ensure_internal_plugins(&app_handle).await {- log::warn!("ensure internal plugins via bridge failed: {e}");- }+pub async fn ensure_internal_plugins(app_handle: AppHandle) -> Result<(), String> {+ plugin::ensure_internal_plugins(&app_handle).await+}++/// 取消共享的内置插件自愈并等待子进程树退出,供启动阶段超时后清理。+#[tauri::command]+pub async fn cancel_internal_plugins() -> Result<(), String> {+ plugin::cancel_internal_plugins().await}/// 是否有新的预装插件需要引导:预设清单内容与上次记录不一致(或老用户无基线)。diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 9acfbe78..5370c9da 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -506,6 +506,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::cancel_preinstall_plugins,crate::bridge::skip_preinstall_plugins,crate::bridge::ensure_internal_plugins,+ crate::bridge::cancel_internal_plugins,crate::bridge::open_preinstall_repo,crate::bridge::get_dsh_plugins,crate::bridge::refresh_plugin_updates,diff --git a/src-tauri/src/desktop/plugin_boot.js.inc b/src-tauri/src/desktop/plugin_boot.js.incnew file mode 100644index 00000000..16e78fa6--- /dev/null+++ b/src-tauri/src/desktop/plugin_boot.js.inc@@ -0,0 +1,111 @@+(function () {+ if (window.__dsh_plugin_boot_reload__) return+ window.__dsh_plugin_boot_reload__ = true+ if (window === window.top) return++ var stopped = false+ var sawSplash = false+ var stalledForCurrentSplash = false+ var stalledTimer = null+ var observer = null+ var fallbackTimer = null+ var loadingLabels = ['Loading plugins', 'Loading plugins…', 'Loading plugins...']++ function normalizedText(node) {+ return ((node && node.textContent) || '').replace(/\s+/g, ' ').trim()+ }++ function rootNode() {+ return document.getElementById('root')+ }++ function hasExactText(root, expected) {+ var nodes = root.querySelectorAll('div, span, p')+ for (var index = 0; index < nodes.length; index++) {+ if (normalizedText(nodes[index]) === expected) return true+ }+ return false+ }++ function isOfficialSplash() {+ var root = rootNode()+ if (!root || root.childElementCount !== 1) return false+ var boot = root.querySelector('[data-dsh-boot]')+ if (!boot || boot.parentElement !== root) return false+ if (root.querySelector('main, nav, [role="main"], button, input, textarea, form, iframe, [contenteditable="true"], [data-dsh-app-shell]')) {+ return false+ }+ var hasLoading = false+ for (var index = 0; index < loadingLabels.length; index++) {+ if (hasExactText(boot, loadingLabels[index])) {+ hasLoading = true+ break+ }+ }+ if (!hasExactText(boot, 'HARNESS') || !hasLoading) return false+ var compact = normalizedText(boot).replace(/\s+/g, '')+ return compact === 'HARNESSLoadingplugins'+ || compact === 'HARNESSLoadingplugins…'+ || compact === 'HARNESSLoadingplugins...'+ }++ function isApplicationShell() {+ var root = rootNode()+ if (!root || isOfficialSplash()) return false+ return root.querySelector('main, nav, [role="main"], button, input, textarea, form, iframe, [contenteditable="true"], [data-dsh-app-shell]') !== null+ }++ function send(type) {+ try {+ window.parent.postMessage({+ source: 'dsh-plugin-boot-bridge',+ type: type,+ }, '*')+ }+ catch (_) {}+ }++ function disarmSplash() {+ if (stalledTimer !== null) {+ clearTimeout(stalledTimer)+ stalledTimer = null+ }+ stalledForCurrentSplash = false+ }++ function stop() {+ if (stopped) return+ stopped = true+ disarmSplash()+ if (fallbackTimer !== null) clearInterval(fallbackTimer)+ if (observer !== null) observer.disconnect()+ window.removeEventListener('pagehide', stop)+ }++ function evaluate() {+ if (stopped) return+ if (isApplicationShell()) {+ if (sawSplash) send('dsh://plugin-boot:ready')+ stop()+ return+ }+ if (!isOfficialSplash()) {+ disarmSplash()+ return+ }+ sawSplash = true+ if (stalledTimer !== null || stalledForCurrentSplash) return+ stalledTimer = setTimeout(function () {+ stalledTimer = null+ if (stopped || !isOfficialSplash()) return+ stalledForCurrentSplash = true+ send('dsh://plugin-boot:stalled')+ }, 8000)+ }++ observer = new MutationObserver(evaluate)+ observer.observe(document.documentElement, { childList: true, subtree: true, characterData: true })+ fallbackTimer = setInterval(evaluate, 1000)+ window.addEventListener('pagehide', stop)+ evaluate()+})()diff --git a/src-tauri/src/desktop/plugin_boot.rs b/src-tauri/src/desktop/plugin_boot.rsindex 3372a95d..db436348 100644--- a/src-tauri/src/desktop/plugin_boot.rs+++ b/src-tauri/src/desktop/plugin_boot.rs@@ -1,47 +1,27 @@-//! 官方 dsh boot 页卡在 “Loading plugins…” 时的一次性自动刷新。+//! 官方 dsh boot 页卡在 “Loading plugins…” 时通知宿主执行有界恢复。//!-//! 桌面端曾把 SPA `/` 的 200 当成就绪并立刻挂 iframe。连接桥尚未注册时,-//! boot 页会无限转圈([#36](https://github.com/dsh-tauri-desk/deepseek-harness-desktop/issues/36)、-//! [#42](https://github.com/dsh-tauri-desk/deepseek-harness-desktop/issues/42));-//! 手动刷新即可恢复。本脚本注入 iframe,若仍停在 boot 文案则只 reload 一次。-//!-//! 注入通道与 [`crate::desktop::nav::NAV_SHIM_JS`] 相同。--/// iframe 内:boot 页卡住时自动 reload 一次(sessionStorage 防循环)。-pub(crate) const PLUGIN_BOOT_RELOAD_JS: &str = r#"(function () {- if (window.__dsh_plugin_boot_reload__) return;- window.__dsh_plugin_boot_reload__ = true;- if (window === window.top) return;-- var FLAG = '__dsh_plugin_boot_reloaded__';- try {- if (sessionStorage.getItem(FLAG) === '1') return;- } catch (_) {}-- function isSplash() {- var text = (document.body && (document.body.innerText || document.body.textContent)) || '';- return text.indexOf('Loading plugins') !== -1;- }-- function tick() {- if (!isSplash()) return;- try { sessionStorage.setItem(FLAG, '1'); } catch (_) {}- location.reload();- }+//! 脚本仅精确识别 `#root` 下单一 boot 根节点的 HARNESS wordmark 与 Loading+//! plugins 提示;普通页面正文出现同名文本不会触发。计时从 splash 首次被观察到+//! 才开始,消失后撤销,晚出现或再次出现都可重新计时;正常应用 shell 挂载后永久+//! 停止观察。- setTimeout(tick, 8000);-})();"#;+/// iframe 内:报告 boot 页 stalled/ready;实际重载预算由宿主管理。+pub(crate) const PLUGIN_BOOT_RELOAD_JS: &str = include_str!("plugin_boot.js.inc");#[cfg(test)]mod tests {use super::*;#[test]- fn boot_reload_script_is_one_shot_and_splash_scoped() {- assert!(PLUGIN_BOOT_RELOAD_JS.contains("__dsh_plugin_boot_reloaded__"));- assert!(PLUGIN_BOOT_RELOAD_JS.contains("Loading plugins"));- assert!(PLUGIN_BOOT_RELOAD_JS.contains("sessionStorage"));- assert!(PLUGIN_BOOT_RELOAD_JS.contains("window === window.top"));- assert!(PLUGIN_BOOT_RELOAD_JS.contains("location.reload"));+ fn boot_bridge_uses_exact_dom_and_cleans_up_without_self_reload() {+ assert!(PLUGIN_BOOT_RELOAD_JS.contains("getElementById('root')"));+ assert!(PLUGIN_BOOT_RELOAD_JS.contains("isOfficialSplash"));+ assert!(PLUGIN_BOOT_RELOAD_JS.contains("isApplicationShell"));+ assert!(PLUGIN_BOOT_RELOAD_JS.contains("MutationObserver"));+ assert!(PLUGIN_BOOT_RELOAD_JS.contains("pagehide"));+ assert!(PLUGIN_BOOT_RELOAD_JS.contains("dsh://plugin-boot:stalled"));+ assert!(PLUGIN_BOOT_RELOAD_JS.contains("dsh://plugin-boot:ready"));+ assert!(!PLUGIN_BOOT_RELOAD_JS.contains("body.innerText"));+ assert!(!PLUGIN_BOOT_RELOAD_JS.contains("location.reload"));}}diff --git a/src-tauri/src/service/plugin/cancel.rs b/src-tauri/src/service/plugin/cancel.rsindex 6e33d2c3..a10e4c9d 100644--- a/src-tauri/src/service/plugin/cancel.rs+++ b/src-tauri/src/service/plugin/cancel.rs@@ -2,20 +2,13 @@//!//! 跨平台结束由本应用拉起的 `dsh plugin` 安装进程树://! - Unix(macOS/Linux):进程以独立进程组启动(`process_group(0)`,见-//! `process.rs`),此处对注册的 PID 发 `kill -<pid> SIGTERM` 一次结束整组-//! (含 pnpm / git 等子进程);随后向前端推送 `preinstall-cancelled` 事件;-//! - Windows:按命令行特征(`plugin --profile <档案> add`)查找由本应用安装-//! 目录下 node 拉起的进程树并强制结束(`taskkill /T /F`)。+//! `process.rs`),此处对注册的 PID 强制结束整组(含 pnpm / git 等子进程);+//! - Windows:对创建时记录的精确 PID 执行 `taskkill /T /F`,不再按命令行模糊+//! 枚举,避免误杀其它插件操作或用户进程。use serde::Serialize;use tauri::{AppHandle, Emitter, Manager};-#[cfg(windows)]-use std::process::{Command, Stdio};--#[cfg(windows)]-use crate::config;-/// 前端监听“安装已取消”事件名const PREINSTALL_CANCEL_EVENT: &str = "preinstall-cancelled";@@ -24,74 +17,125 @@ const PREINSTALL_CANCEL_EVENT: &str = "preinstall-cancelled";#[serde(rename_all = "camelCase")]pub struct PreinstallCancelPayload {}-/// 取消正在进行的预装插件安装-pub async fn cancel(app_handle: &AppHandle) {- // Unix:结束注册 PID 对应的安装进程组;Windows:按命令行特征 taskkill。- #[cfg(not(windows))]- {- if let Some(pid) = super::process::active_plugin_pid() {- log::info!("Cancelling dsh plugin install process group led by pid {pid}");- // 负 PID 语义:对整个进程组发 SIGTERM(子进程 pnpm/git 一并结束)。- // 注意 `--` 之后的负数才被 kill 当进程组号,直接 `kill -<pid>` 会被- // 误解析为信号编号。- let ok = std::process::Command::new("kill")- .args(["-TERM", "--", &format!("-{pid}")])- .status()- .map(|s| s.success())- .unwrap_or(false);- if !ok {- // 兜底:kill 命令不可用/失败时,至少结束直接子进程- let _ = std::process::Command::new("pkill")- .arg("-TERM")- .arg("-P")- .arg(pid.to_string())- .status();- }- log::warn!("preinstall cancel: kill(-{pid}) success={ok}");- } else {- log::debug!("preinstall cancel: no active install process");+/// 强制结束当前插件安装进程树。返回是否找到并成功结束了活动进程。+pub(crate) async fn terminate_active_install() -> bool {+ let active = super::process::active_plugin_processes();+ if active.is_empty() {+ log::debug!("plugin install cancel: no active install process");+ return false;+ }+ tauri::async_runtime::spawn_blocking(move || {+ let mut all_terminated = true;+ for (_, pid) in active {+ all_terminated &= terminate_pid_tree(pid);}+ all_terminated+ })+ .await+ .unwrap_or_else(|e| {+ log::warn!("plugin install cancel task failed: {e}");+ false+ })+}++pub(crate) async fn terminate_owned_install(owner: super::process::ProcessOwner) -> bool {+ let Some(pid) = super::process::active_plugin_pid(owner) else {+ return false;+ };+ tauri::async_runtime::spawn_blocking(move || terminate_pid_tree(pid))+ .await+ .unwrap_or_else(|e| {+ log::warn!("owned plugin install cancel task failed: {e}");+ false+ })+}++#[cfg(windows)]+fn terminate_pid_tree(pid: u32) -> bool {+ use std::os::windows::process::CommandExt;+ let mut command = std::process::Command::new("taskkill");+ command+ .args(["/PID", &pid.to_string(), "/T", "/F"])+ .creation_flags(0x08000000);+ let ok = command+ .status()+ .map(|status| status.success())+ .unwrap_or(false);+ log::warn!("plugin install cancel: taskkill pid {pid} success={ok}");+ ok+}++#[cfg(not(windows))]+fn terminate_pid_tree(pid: u32) -> bool {+ // `--` 防止负 PID 被解析为信号;KILL 保证忽略 TERM 的 pnpm/git 后代也退出。+ let group = std::process::Command::new("kill")+ .args(["-KILL", "--", &format!("-{pid}")])+ .status()+ .map(|status| status.success())+ .unwrap_or(false);+ let direct = group+ || std::process::Command::new("kill")+ .args(["-KILL", &pid.to_string()])+ .status()+ .map(|status| status.success())+ .unwrap_or(false);+ log::warn!("plugin install cancel: kill process group {pid} success={direct}");+ direct+}++/// 取消正在进行的预装插件安装。+pub async fn cancel(app_handle: &AppHandle) {+ terminate_active_install().await;++ if let Some(window) = app_handle.get_webview_window("main") {+ let _ = window.emit(PREINSTALL_CANCEL_EVENT, PreinstallCancelPayload {});}+}++#[cfg(test)]+mod tests {+ use super::*;#[cfg(windows)]- {- // window 仅作「存在 main 窗口」的借位判定;实际 emit 在函数末尾统一做。- let Some(_window) = app_handle.get_webview_window("main") else {- return;- };-- // 按当前档案匹配命令行:`dsh plugin --profile <当前档案> add`(不再写死 web)- let profile = crate::service::profile::active_profile(app_handle);- let base = config::get_dsh_install_path(app_handle)- .to_string_lossy()- .replace('\\', "\\\\");- // PowerShell 单引号转义:`'` → `''`(防断串/注入)- let profile_escaped = profile.replace('\'', "''");- let base_escaped = base.replace('\'', "''");- let ps_cmd = format!(- "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Where-Object {{ ($_.CommandLine -like '*plugin*--profile*{profile_escaped}*add*') -and ($_.ExecutablePath -like '{base_escaped}\\*') }} | ForEach-Object {{ taskkill /PID $_.ProcessId /T /F 2>$null }}"- );-- let mut cmd = Command::new("powershell");- cmd.args([- "-NoProfile",- "-NonInteractive",- "-WindowStyle",- "Hidden",- "-Command",- &ps_cmd,- ]);+ fn spawn_hung_child() -> std::process::Child {use std::os::windows::process::CommandExt;- cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW- cmd.stdout(Stdio::null());- cmd.stderr(Stdio::null());+ let mut command = std::process::Command::new("cmd.exe");+ command+ .args(["/C", "ping -n 60 127.0.0.1 >NUL"])+ .creation_flags(0x08000000);+ command.spawn().unwrap()+ }- if let Err(e) = cmd.output() {- log::warn!("failed to run preinstall cancel: {e}");- }+ #[cfg(unix)]+ fn spawn_hung_child() -> std::process::Child {+ use std::os::unix::process::CommandExt;+ let mut command = std::process::Command::new("sh");+ command.args(["-c", "sleep 60"]).process_group(0);+ command.spawn().unwrap()}- if let Some(window) = app_handle.get_webview_window("main") {- let _ = window.emit(PREINSTALL_CANCEL_EVENT, PreinstallCancelPayload {});+ #[tokio::test]+ async fn forced_cancel_kills_hung_child_and_releases_pid_slot() {+ let mut child = spawn_hung_child();+ let pid = child.id();+ let owner = super::super::process::new_process_owner();+ let guard = super::super::process::PidGuard::set(owner, pid);++ assert_eq!(super::super::process::active_plugin_pid(owner), Some(pid));+ assert!(terminate_owned_install(owner).await);++ let exited = tokio::time::timeout(std::time::Duration::from_secs(5), async {+ loop {+ if child.try_wait().unwrap().is_some() {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;+ }+ })+ .await;+ assert!(exited.is_ok(), "hung plugin child should be force-killed");++ drop(guard);+ assert_eq!(super::super::process::active_plugin_pid(owner), None);}}diff --git a/src-tauri/src/service/plugin/install.rs b/src-tauri/src/service/plugin/install.rsindex 03a016e5..d211966e 100644--- a/src-tauri/src/service/plugin/install.rs+++ b/src-tauri/src/service/plugin/install.rs@@ -35,7 +35,10 @@ use tauri::{AppHandle, Emitter, Manager, WebviewWindow};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::{run_plugin_process, PreinstallLogPayload, PREINSTALL_LOG_EVENT};+use super::process::{+ 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;@@ -50,9 +53,31 @@ const MAX_ALLOW_LIST_RETRIES: usize = 8;/// 是 8/9 行为)。低于此版本时插件安装必须改用捆绑版 pnpm,否则会出现/// 自动合成 peer 后 `No matching version found for @deepseek-ai/...` 的假失败。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);/// 校验并安装选中的预装插件:`dsh plugin --profile <当前档案> add <ids...>`pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), String> {+ install_with_cancel(app_handle, ids, None, new_process_owner()).await+}++/// 内置插件启动自愈专用入口:取消信号会阻止被结束的 pnpm/dsh 进程再次进入+/// allowBuilds 重试,确保硬上限之后不会悄悄拉起下一棵进程树。+pub(crate) async fn install_internal(+ app_handle: &AppHandle,+ ids: &[String],+ cancel: tokio::sync::watch::Receiver<bool>,+ owner: ProcessOwner,+) -> Result<(), String> {+ install_with_cancel(app_handle, ids, Some(cancel), owner).await+}++async fn install_with_cancel(+ app_handle: &AppHandle,+ ids: &[String],+ cancel: Option<tokio::sync::watch::Receiver<bool>>,+ owner: ProcessOwner,+) -> Result<(), String> {if ids.is_empty() {return Err("PREINSTALL_EMPTY: no plugins selected".to_string());}@@ -110,7 +135,7 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin.ok_or("WINDOW_NOT_FOUND: main window missing")?;// 选定/补齐安装用的 pnpm:返回是否应强制使用捆绑版(版本感知,见 ensure_pnpm)- let prefer_bundled_pnpm = ensure_pnpm(app_handle, &window).await?;+ let prefer_bundled_pnpm = ensure_pnpm(app_handle, &window, owner).await?;// 首次安装可能早于服务启动;提前写入非交互清理配置,避免 pnpm 在无 TTY// 环境以 ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY 中止(issue #130)。super::ensure_profile_npmrc(app_handle)?;@@ -152,7 +177,15 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin// 后重试,直至成功或再无键可加(升级路径同样依赖该重试,见// [`run_plugin_with_allow_build_retry`])。let (exit_code, last_output) = run_plugin_with_allow_build_retry(- app_handle, &node, &args, &cwd, &envs, &window, "install",+ app_handle,+ &node,+ &args,+ &cwd,+ &envs,+ &window,+ "install",+ cancel.as_ref(),+ owner,).await?;@@ -569,11 +602,20 @@ async fn run_plugin_with_allow_build_retry(envs: &HashMap<String, String>,window: &WebviewWindow,action: &str,+ cancel: Option<&tokio::sync::watch::Receiver<bool>>,+ owner: ProcessOwner,) -> Result<(i32, String), String> {+ let _process_guard = acquire_process_lock().await;let mut retries = 0usize;let mut all_output = String::new();let exit_code = loop {- let (code, captured) = run_plugin_process(node, args, cwd, envs, window).await?;+ if cancel.is_some_and(|signal| *signal.borrow()) {+ return Err("PLUGIN_OPERATION_CANCELLED: plugin operation was cancelled".to_string());+ }+ let (code, captured) = run_plugin_process(node, args, cwd, envs, window, owner).await?;+ if cancel.is_some_and(|signal| *signal.borrow()) {+ return Err("PLUGIN_OPERATION_CANCELLED: plugin operation was cancelled".to_string());+ }append_command_output(&mut all_output, &captured);let new_keys = parse_allowlist_keys(&captured);// 有可补充的 allowBuilds 键且未达上限 → 写入并重试(无论本次退出码是否为 0,@@ -694,7 +736,8 @@ async fn run_single_plugin_command(return Err("HARNESS_NOT_FOUND: dsh CLI missing".to_string());}- let prefer_bundled_pnpm = ensure_pnpm(app_handle, &window).await?;+ let owner = new_process_owner();+ let prefer_bundled_pnpm = ensure_pnpm(app_handle, &window, owner).await?;// `.npmrc` 可能在服务启动后被删除;升级/卸载同样可能触发 pnpm 非交互清理。super::ensure_profile_npmrc(app_handle)?;@@ -724,9 +767,10 @@ async fn run_single_plugin_command(let cwd = config::get_dsh_install_path(app_handle);log::info!("Running dsh plugin {action} for {id}");- let (exit_code, output) =- run_plugin_with_allow_build_retry(app_handle, &node, &args, &cwd, &envs, &window, action)- .await?;+ let (exit_code, output) = run_plugin_with_allow_build_retry(+ app_handle, &node, &args, &cwd, &envs, &window, action, None, owner,+ )+ .await?;if exit_code != 0 {log::error!("dsh plugin {action} failed for {id} with exit code {exit_code}");@@ -844,10 +888,14 @@ fn strip_ansi(s: &str) -> String {/// 用户 pnpm 过旧(8/9:不读 pnpm-workspace.yaml 的 autoInstallPeers、有/// workspace-root gate;corepack shim 在 Node 24 上还会 ERR_INVALID_THIS 崩溃)/// 或版本不可探测 → 走捆绑版。-async fn ensure_pnpm(app_handle: &AppHandle, window: &WebviewWindow) -> Result<bool, String> {+async fn ensure_pnpm(+ app_handle: &AppHandle,+ window: &WebviewWindow,+ owner: ProcessOwner,+) -> Result<bool, String> {// 档案的 node_modules 由哪个 pnpm 主版本创建(.modules.yaml 的 storeDir 段)let store_major = profile_store_major(app_handle);- let user_major = user_pnpm_major_version(app_handle);+ let user_major = user_pnpm_major_version_bounded(app_handle, owner).await?;// 1) store 主版本已知 → 优先选与 store 一致的 pnpm(用户版或捆绑版)if let Some(store) = store_major {@@ -917,6 +965,76 @@ async fn ensure_pnpm(app_handle: &AppHandle, window: &WebviewWindow) -> Result<bOk(true)}+async fn user_pnpm_major_version_bounded(+ app_handle: &AppHandle,+ owner: ProcessOwner,+) -> Result<Option<u32>, String> {+ 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 = std::process::Command::new(&pnpm);+ command.arg("--version");+ if let Some(path) = pnpm_probe_path(&pnpm, Some(&node)) {+ command.env("PATH", path);+ }+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ command.creation_flags(0x0800_0000);+ }+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt;+ command.process_group(0);+ }++ let child = match command+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .spawn()+ {+ Ok(child) => child,+ Err(error) => {+ log::warn!(+ "pnpm version probe failed to spawn {}: {error}",+ pnpm.display()+ );+ return Ok(None);+ }+ };+ 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 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}"))?,+ Err(_) => {+ log::warn!(+ "PNPM_PROBE_TIMEOUT: pnpm version probe exceeded {} seconds",+ PNPM_PROBE_TIMEOUT.as_secs()+ );+ 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);+ }+ };+ Ok(parse_pnpm_major_output(&pnpm, &output))+}+/// 用户 pnpm 主版本号(解析 `pnpm --version` 首个点分字段);不存在或不可运行/// (corepack shim 在 Node 24 上 ERR_INVALID_THIS 崩溃等)返回 None。///@@ -957,6 +1075,10 @@ fn pnpm_major_version_at_with_node(pnpm: &Path, node: Option<&Path>) -> Option<ureturn None;}};+ parse_pnpm_major_output(pnpm, &output)+}++fn parse_pnpm_major_output(pnpm: &Path, output: &std::process::Output) -> Option<u32> {if !output.status.success() {let stderr = String::from_utf8_lossy(&output.stderr);log::warn!(diff --git a/src-tauri/src/service/plugin/internal.rs b/src-tauri/src/service/plugin/internal.rsindex cdc39e7e..18c54bb5 100644--- a/src-tauri/src/service/plugin/internal.rs+++ b/src-tauri/src/service/plugin/internal.rs@@ -11,6 +11,7 @@//! 要求——用户怎么卸载、何时卸载都不影响下次启动自动恢复,无需任何用户操作。use std::collections::{HashMap, HashSet};+use std::future::Future;#[cfg(windows)]use std::os::windows::fs::FileTypeExt;use std::path::Path;@@ -23,48 +24,270 @@ use super::preset::{bundled_dep_spec, bundled_plugin_dir, load_presets, Preinsta////// 最佳努力:任何失败只记告警(调用方不阻断启动);捆绑目录缺失(开发环境未跑/// prebuild)时跳过,交由常规引导流程处理;批量待装列表为空则不触发任何安装。-/// 内置插件阶段事件载荷:「loading」= 核对/安装进行中(前端加载屏显示-/// `status.loading_internal`),「done」= 结束(回到常规 `status.loading`)。+/// 内置插件阶段事件载荷:除开始/结束外定期发送 heartbeat,令前端只在安装确实+/// 无进展时触发 inactivity deadline,同时仍受绝对上限约束。#[derive(serde::Serialize, Clone)]struct InternalPluginsPhase {phase: &'static str,+ detail: &'static str,+ completed: usize,+ total: usize,}/// 串行化内置插件核对/安装:auto_start(Rust 侧 start→launch)与前端 boot 流程/// (新增的 boot 期 ensure 命令)可能并发触发,而安装会启动 `dsh plugin add`/// 子进程——两个 pnpm 抢同一档案目录会互相打断。若另一路正在执行,这里等它/// 完成后再核对(幂等:上次已装好则本轮全部 no-op)。-static ENSURE_LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();+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);++#[derive(Clone)]+struct EnsureFlight {+ id: u64,+ owner: super::process::ProcessOwner,+ state: EnsureFlightState,+ result: tokio::sync::watch::Receiver<Option<Result<(), String>>>,+ cancel: tokio::sync::watch::Sender<bool>,+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+enum EnsureFlightState {+ Running,+ Cancelling,+}++enum EnsureSubscription {+ Running(tokio::sync::watch::Receiver<Option<Result<(), String>>>),+ Cancelling(tokio::sync::watch::Receiver<Option<Result<(), String>>>),+}++#[derive(Default)]+struct EnsureCoordinator {+ next_id: u64,+ active: Option<EnsureFlight>,+}++impl EnsureCoordinator {+ fn subscribe(&self) -> Option<EnsureSubscription> {+ self.active.as_ref().map(|flight| match flight.state {+ EnsureFlightState::Running => EnsureSubscription::Running(flight.result.clone()),+ EnsureFlightState::Cancelling => EnsureSubscription::Cancelling(flight.result.clone()),+ })+ }++ fn start(+ &mut self,+ ) -> (+ u64,+ super::process::ProcessOwner,+ tokio::sync::watch::Sender<Option<Result<(), String>>>,+ tokio::sync::watch::Receiver<Option<Result<(), String>>>,+ tokio::sync::watch::Sender<bool>,+ tokio::sync::watch::Receiver<bool>,+ ) {+ self.next_id = self.next_id.wrapping_add(1);+ let id = self.next_id;+ let owner = super::process::new_process_owner();+ let (result_tx, result_rx) = tokio::sync::watch::channel(None);+ let (cancel_tx, cancel_rx) = tokio::sync::watch::channel(false);+ self.active = Some(EnsureFlight {+ id,+ owner,+ state: EnsureFlightState::Running,+ result: result_rx.clone(),+ cancel: cancel_tx.clone(),+ });+ (id, owner, result_tx, result_rx, cancel_tx, cancel_rx)+ }++ fn finish(&mut self, id: u64) {+ if self.active.as_ref().is_some_and(|flight| flight.id == id) {+ self.active = None;+ }+ }++ 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);+ Some(active.result.clone())+ }+}++static ENSURE_LOCK: std::sync::OnceLock<tokio::sync::Mutex<EnsureCoordinator>> =+ std::sync::OnceLock::new();++fn ensure_lock() -> &'static tokio::sync::Mutex<EnsureCoordinator> {+ ENSURE_LOCK.get_or_init(|| tokio::sync::Mutex::new(EnsureCoordinator::default()))+}pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {let presets = load_presets(app_handle);- let internal: Vec<_> = presets.iter().filter(|p| p.internal).collect();+ let internal: Vec<_> = presets.into_iter().filter(|p| p.internal).collect();if internal.is_empty() {return Ok(());}- let _guard = ENSURE_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .lock()- .await;- // 前端据此在「Loading internal plugins…」与「Loading plugins…」间切换;- // 事件在服务进程启动前发出,于健康轮询期间到达,先于 dsh 自家的 boot 输出。- let _ = app_handle.emit(- "internal-plugins-phase",- InternalPluginsPhase { phase: "loading" },- );- let outcome = ensure_inner(app_handle, &internal).await;+ receive_current_or_next_flight(|| subscribe_or_start(app_handle, &internal)).await+}++async fn subscribe_or_start(+ app_handle: &AppHandle,+ internal: &[PreinstallPluginInfo],+) -> EnsureSubscription {+ let mut coordinator = ensure_lock().lock().await;+ match coordinator.subscribe() {+ Some(subscription) => subscription,+ None => {+ let (id, owner, result_tx, result_rx, cancel_tx, cancel_rx) = coordinator.start();+ let app_handle = app_handle.clone();+ let internal = internal.to_vec();+ tauri::async_runtime::spawn(async move {+ let 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;+ }+ ensure_lock().lock().await.finish(id);+ let _ = result_tx.send(Some(outcome));+ });+ EnsureSubscription::Running(result_rx)+ }+ }+}++async fn receive_current_or_next_flight<F, Fut>(mut acquire: F) -> Result<(), String>+where+ F: FnMut() -> Fut,+ Fut: Future<Output = EnsureSubscription>,+{+ loop {+ let subscription = acquire().await;+ match subscription {+ EnsureSubscription::Running(mut result) => {+ return receive_flight_result(&mut result).await?;+ }+ EnsureSubscription::Cancelling(mut result) => {+ // Retry 不继承已取消 flight 的结果;等它完成清理并从 coordinator+ // 移除后回到循环,创建且只创建一个全新的 flight。+ let _ = receive_flight_result(&mut result).await?;+ }+ }+ }+}++async fn receive_flight_result(+ result: &mut tokio::sync::watch::Receiver<Option<Result<(), String>>>,+) -> Result<Result<(), String>, String> {+ loop {+ if let Some(outcome) = result.borrow().clone() {+ return Ok(outcome);+ }+ result.changed().await.map_err(|_| {+ "INTERNAL_PLUGIN_ENSURE_DROPPED: install task ended without result".to_string()+ })?;+ }+}++/// 取消共享的内置插件安装并等待拥有者完成清理,确保 Retry 不会叠加新进程。+pub(crate) async fn cancel() -> Result<(), String> {+ let mut result = {+ let mut coordinator = ensure_lock().lock().await;+ let Some(active) = &coordinator.active else {+ return Ok(());+ };+ log::info!(+ "cancelling internal plugin ensure flight owned by {:?}",+ active.owner+ );+ coordinator+ .begin_cancel()+ .expect("active flight must remain present while coordinator lock is held")+ };+ let _ = receive_flight_result(&mut result).await?;+ Ok(())+}++async fn run_ensure_operation(+ app_handle: &AppHandle,+ internal: &[PreinstallPluginInfo],+ owner: super::process::ProcessOwner,+ cancel_tx: tokio::sync::watch::Sender<bool>,+ 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);+ let refs: Vec<_> = internal.iter().collect();+ let operation = ensure_inner(app_handle, &refs, cancel.clone(), owner);+ tokio::pin!(operation);+ let deadline = tokio::time::sleep(ENSURE_ABSOLUTE_TIMEOUT);+ tokio::pin!(deadline);+ let period = std::time::Duration::from_secs(5);+ let mut heartbeat = tokio::time::interval_at(tokio::time::Instant::now() + period, period);+ heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);+ loop {+ tokio::select! {+ outcome = &mut operation => {+ emit_phase(app_handle, "done", "done", total, total);+ return outcome;+ }+ _ = &mut deadline => {+ let reason = "INTERNAL_PLUGIN_INSTALL_TIMEOUT: plugin install exceeded 600 seconds";+ log::error!("{reason}");+ let _ = cancel_tx.send(true);+ super::cancel::terminate_owned_install(owner).await;+ 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);+ return Err(reason.to_string());+ }+ changed = cancel.changed() => {+ if changed.is_err() || *cancel.borrow() {+ let reason = "INTERNAL_PLUGIN_INSTALL_CANCELLED: plugin install was cancelled";+ log::warn!("{reason}");+ super::cancel::terminate_owned_install(owner).await;+ 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);+ return Err(reason.to_string());+ }+ }+ _ = heartbeat.tick() => {+ emit_phase(app_handle, "progress", "heartbeat", 0, total);+ }+ }+ }+}++fn emit_phase(+ app_handle: &AppHandle,+ phase: &'static str,+ detail: &'static str,+ completed: usize,+ total: usize,+) {let _ = app_handle.emit("internal-plugins-phase",- InternalPluginsPhase { phase: "done" },+ InternalPluginsPhase {+ phase,+ detail,+ completed,+ total,+ },);- outcome}/// 实际的核对与安装:遍历 internal 预设,未安装 / 路径不对 / 被卸载 → 批量重装。async fn ensure_inner(app_handle: &AppHandle,internal: &[&PreinstallPluginInfo],+ cancel: tokio::sync::watch::Receiver<bool>,+ owner: super::process::ProcessOwner,) -> Result<(), String> {log::info!("checking {} internal preset plugins for install state",@@ -131,6 +354,7 @@ 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());// pnpm add 会先解析清单里的所有既有依赖。0.9.0 将随包目录从// `preset-plugins` 迁至 `internal-plugins` 后,旧 file:/link: 路径已不存在,pnpm@@ -158,7 +382,7 @@ async fn ensure_inner(}// 复用常规安装编排(环境准备/补齐 pnpm/`dsh plugin add file:<dir>`);// 启动阶段无持有进程,install 内部不会停服务。失败同样交给调用方告警。- if let Err(e) = super::install::install(app_handle, &ids).await {+ if let Err(e) = super::install::install_internal(app_handle, &ids, cancel, owner).await {return Err(format!("INTERNAL_PLUGIN_INSTALL_FAILED: {e}"));}Ok(())@@ -311,6 +535,126 @@ fn dep_matches_spec(actual: &str, expected: &str) -> bool {mod tests {use super::*;+ #[tokio::test]+ async fn coordinator_coalesces_waiters_and_releases_for_retry() {+ let mut coordinator = EnsureCoordinator::default();+ let (first_id, first_owner, result_tx, first, _, _) = coordinator.start();+ let EnsureSubscription::Running(duplicate) = coordinator.subscribe().unwrap() else {+ panic!("running flight must coalesce running waiters");+ };+ assert_eq!(coordinator.active.as_ref().unwrap().owner, first_owner);+ coordinator.finish(first_id);+ assert!(coordinator.subscribe().is_none());+ result_tx.send(Some(Ok(()))).unwrap();+ assert_eq!(first.borrow().as_ref(), Some(&Ok(())));+ assert_eq!(duplicate.borrow().as_ref(), Some(&Ok(())));++ let (retry_id, _, _, _, _, _) = coordinator.start();+ assert_ne!(retry_id, first_id);+ }++ #[tokio::test]+ async fn cancel_then_immediate_retry_starts_one_fresh_flight() {+ type FlightResultSender = tokio::sync::watch::Sender<Option<Result<(), String>>>;++ let coordinator =+ std::sync::Arc::new(tokio::sync::Mutex::new(EnsureCoordinator::default()));+ let fresh_flight = std::sync::Arc::new(tokio::sync::Mutex::new(+ None::<(u64, super::super::process::ProcessOwner, FlightResultSender)>,+ ));+ let fresh_started = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let cancelling_subscribers = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let cancelling_subscribed = std::sync::Arc::new(tokio::sync::Notify::new());++ let (cancelled_id, cancelled_owner, cancelled_tx) = {+ let mut coordinator = coordinator.lock().await;+ let (id, owner, result_tx, _, _, mut cancel_signal) = coordinator.start();+ coordinator.begin_cancel().unwrap();+ assert!(*cancel_signal.borrow_and_update());+ (id, owner, result_tx)+ };++ async fn retry(+ coordinator: std::sync::Arc<tokio::sync::Mutex<EnsureCoordinator>>,+ fresh_flight: std::sync::Arc<+ tokio::sync::Mutex<+ Option<(u64, super::super::process::ProcessOwner, FlightResultSender)>,+ >,+ >,+ fresh_started: std::sync::Arc<std::sync::atomic::AtomicUsize>,+ cancelling_subscribers: std::sync::Arc<std::sync::atomic::AtomicUsize>,+ cancelling_subscribed: std::sync::Arc<tokio::sync::Notify>,+ ) -> Result<(), String> {+ receive_current_or_next_flight(|| {+ let coordinator = coordinator.clone();+ let fresh_flight = fresh_flight.clone();+ let fresh_started = fresh_started.clone();+ let cancelling_subscribers = cancelling_subscribers.clone();+ let cancelling_subscribed = cancelling_subscribed.clone();+ async move {+ let mut coordinator = coordinator.lock().await;+ if let Some(subscription) = coordinator.subscribe() {+ if matches!(&subscription, EnsureSubscription::Cancelling(_)) {+ cancelling_subscribers+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ cancelling_subscribed.notify_one();+ }+ return subscription;+ }+ let (id, owner, result_tx, result_rx, _, _) = coordinator.start();+ fresh_started.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ *fresh_flight.lock().await = Some((id, owner, result_tx));+ EnsureSubscription::Running(result_rx)+ }+ })+ .await+ }++ let first_retry = tokio::spawn(retry(+ coordinator.clone(),+ fresh_flight.clone(),+ fresh_started.clone(),+ cancelling_subscribers.clone(),+ cancelling_subscribed.clone(),+ ));+ let second_retry = tokio::spawn(retry(+ coordinator.clone(),+ fresh_flight.clone(),+ fresh_started.clone(),+ cancelling_subscribers.clone(),+ cancelling_subscribed.clone(),+ ));++ while cancelling_subscribers.load(std::sync::atomic::Ordering::SeqCst) < 2 {+ cancelling_subscribed.notified().await;+ }+ {+ let mut coordinator = coordinator.lock().await;+ coordinator.finish(cancelled_id);+ }+ cancelled_tx+ .send(Some(Err(+ "INTERNAL_PLUGIN_INSTALL_CANCELLED: plugin install was cancelled".to_string(),+ )))+ .unwrap();++ let (retry_id, retry_owner, retry_tx) = loop {+ if let Some(flight) = fresh_flight.lock().await.take() {+ break flight;+ }+ tokio::task::yield_now().await;+ };+ assert_ne!(retry_owner, cancelled_owner);+ assert_eq!(fresh_started.load(std::sync::atomic::Ordering::SeqCst), 1);++ coordinator.lock().await.finish(retry_id);+ retry_tx.send(Some(Ok(()))).unwrap();+ assert!(first_retry.await.unwrap().is_ok());+ assert!(second_retry.await.unwrap().is_ok());+ assert_eq!(fresh_started.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert!(coordinator.lock().await.subscribe().is_none());+ }+#[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/mod.rs b/src-tauri/src/service/plugin/mod.rsindex 44d86e89..4e6a5749 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -42,6 +42,7 @@ pub(crate) use install::harness_prefer_bundled_pnpm;pub use install::{install, remove, update};pub(crate) use installed::ensure_profile_npmrc;pub use installed::{list, PreinstallPlugin};+pub(crate) use internal::cancel as cancel_internal_plugins;pub(crate) use internal::ensure as ensure_internal_plugins;pub use preset::repo_url_of;pub(crate) use preset::{current_preset_hash, preinstall_pending, remove_legacy_bundled_plugins};diff --git a/src-tauri/src/service/plugin/process.rs b/src-tauri/src/service/plugin/process.rsindex 4c3f3df2..86c9a4fe 100644--- a/src-tauri/src/service/plugin/process.rs+++ b/src-tauri/src/service/plugin/process.rs@@ -10,6 +10,7 @@ use std::collections::HashMap;use std::ffi::OsString;use std::io::{BufRead, BufReader, Read};use std::path::Path;+use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, Mutex, OnceLock};use tauri::{Emitter, WebviewWindow};@@ -33,37 +34,68 @@ pub struct PreinstallLogPayload {/// `cancel`(跨平台)用它结束安装进程树;安装结束/失败后必须复位,/// 防止把「下一个安装」或无关进程误杀。///-/// 仅在 Unix 被 `cancel` 使用(Windows 取消安装走 taskkill 按命令行匹配),-/// 故 Windows 下按项目约定允许 dead_code。-#[cfg_attr(windows, allow(dead_code))]-static ACTIVE_PLUGIN_PID: OnceLock<Mutex<Option<u32>>> = OnceLock::new();--#[cfg_attr(windows, allow(dead_code))]-fn active_pid_lock() -> &'static Mutex<Option<u32>> {- ACTIVE_PLUGIN_PID.get_or_init(|| Mutex::new(None))+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]+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();++fn active_pid_lock() -> &'static Mutex<HashMap<ProcessOwner, u32>> {+ ACTIVE_PLUGIN_PIDS.get_or_init(|| Mutex::new(HashMap::new()))+}++pub(crate) fn new_process_owner() -> ProcessOwner {+ ProcessOwner(NEXT_PROCESS_OWNER.fetch_add(1, Ordering::Relaxed))+}++pub(crate) fn active_plugin_pid(owner: ProcessOwner) -> Option<u32> {+ active_pid_lock()+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .get(&owner)+ .copied()+}++pub(crate) fn active_plugin_processes() -> Vec<(ProcessOwner, u32)> {+ active_pid_lock()+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .iter()+ .map(|(owner, pid)| (*owner, *pid))+ .collect()}-/// 当前进行中安装的根进程 PID(取消安装用)。-#[cfg_attr(windows, allow(dead_code))]-pub(crate) fn active_plugin_pid() -> Option<u32> {- *active_pid_lock().lock().unwrap_or_else(|e| e.into_inner())+pub(crate) async fn acquire_process_lock() -> tokio::sync::OwnedMutexGuard<()> {+ PLUGIN_PROCESS_LOCK+ .get_or_init(|| Arc::new(tokio::sync::Mutex::new(())))+ .clone()+ .lock_owned()+ .await}/// 记录/清除当前安装进程 PID(guard-drop 模式,作用域结束自动复位)。-#[cfg_attr(windows, allow(dead_code))]-struct PidGuard;+pub(crate) struct PidGuard {+ owner: ProcessOwner,+ pid: u32,+}-#[cfg_attr(windows, allow(dead_code))]impl PidGuard {- fn set(pid: u32) {- *active_pid_lock().lock().unwrap_or_else(|e| e.into_inner()) = Some(pid);+ pub(crate) fn set(owner: ProcessOwner, pid: u32) -> Self {+ active_pid_lock()+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .insert(owner, pid);+ Self { owner, pid }}}-#[cfg_attr(windows, allow(dead_code))]impl Drop for PidGuard {fn drop(&mut self) {- *active_pid_lock().lock().unwrap_or_else(|e| e.into_inner()) = None;+ let mut active = active_pid_lock().lock().unwrap_or_else(|e| e.into_inner());+ if active.get(&self.owner) == Some(&self.pid) {+ active.remove(&self.owner);+ }}}@@ -88,20 +120,24 @@ pub(crate) async fn run_plugin_process(cwd: &Path,envs: &HashMap<String, String>,window: &WebviewWindow,+ owner: ProcessOwner,) -> Result<(i32, String), String> {let captured = Arc::new(Mutex::new(String::new()));#[cfg(windows)]{- let (stdout, stderr, handle) =- workflow::win_spawn::spawn_with_hidden_console_tracked(node, args, Some(cwd), envs)+ let (stdout, stderr, pid, handle) =+ workflow::win_spawn::spawn_with_hidden_console_owned(node, args, Some(cwd), envs).map_err(|e| format!("PREINSTALL_SPAWN: {e}"))?;+ let pid_guard = PidGuard::set(owner, pid);+ log::info!("dsh plugin install started, pid {pid}");spawn_line_emitter(stdout, window.clone(), captured.clone());spawn_line_emitter(stderr, window.clone(), captured.clone());let handle = WaitableHandle(handle);let exit_code = tauri::async_runtime::spawn_blocking(move || {+ let _pid_guard = pid_guard;use windows_sys::Win32::Foundation::CloseHandle;use windows_sys::Win32::System::Threading::{GetExitCodeProcess, WaitForSingleObject, INFINITE,@@ -140,11 +176,10 @@ pub(crate) async fn run_plugin_process(.map_err(|e| format!("PREINSTALL_SPAWN: {e}"))?;let pid = child.id();- PidGuard::set(pid);+ let pid_guard = PidGuard::set(owner, pid);// 绑定守卫实例:本 cfg 块作用域结束时自动把共享 PID 槽复位为 None,// 避免把「这一次安装」的 PID 泄漏给之后的取消/下一次安装(误杀无关进程)。// 若 spawn_blocking 因错误提前 `?` 返回,守卫同样会 Drop 复位。- let _pid_guard = PidGuard;log::info!("dsh plugin install started, pid {pid}");if let Some(stdout) = child.stdout.take() {@@ -155,6 +190,7 @@ pub(crate) async fn run_plugin_process(}let exit_code = tauri::async_runtime::spawn_blocking(move || {+ let _pid_guard = pid_guard;child.wait().map(|s| s.code().unwrap_or(1)).unwrap_or(1)}).await@@ -198,3 +234,21 @@ fn spawn_line_emitter<R: Read + Send + 'static>(}});}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn stale_guard_cannot_clear_a_new_process_for_the_same_owner() {+ let owner = new_process_owner();+ let stale = PidGuard::set(owner, 100);+ let current = PidGuard::set(owner, 200);++ drop(stale);+ assert_eq!(active_plugin_pid(owner), Some(200));++ drop(current);+ assert_eq!(active_plugin_pid(owner), None);+ }+}diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rsindex e7e6ef86..4f998a12 100644--- a/src-tauri/src/service/workflow/mod.rs+++ b/src-tauri/src/service/workflow/mod.rs@@ -1298,6 +1298,10 @@ fn not_owned_probe_signal(launch_in_progress: bool) -> &'static str {}}+fn all_client_modules_ready(ready: usize, total: usize) -> bool {+ total > 0 && ready == total+}+/// 健康检查(通过 Rust 代理,避免 WebView CORS 问题)pub async fn proxy_health_check(port: u16) -> Result<String, String> {if !has_owned_process() {@@ -1305,18 +1309,19 @@ pub async fn proxy_health_check(port: u16) -> Result<String, String> {}let client = utils::loopback_http_client(config::HEALTH_CHECK_TIMEOUT).map_err(|e| format!("HARNESS_HEALTH_CLIENT_FAILED: {e}"))?;- let mut failures = Vec::with_capacity(2);+ let endpoints = utils::health_probe_plugin_urls(port);+ let total = endpoints.len();+ let mut ready = 0usize;+ let mut failures = Vec::with_capacity(total);- for endpoint in utils::health_probe_plugin_urls(port) {+ for endpoint in endpoints {match client.get(&endpoint).send().await {Ok(response) => {let status = response.status();let body = response.text().await.unwrap_or_default();if utils::looks_like_plugin_bundle(status.is_success(), &body) {- return Ok(format!(- "healthy - {status} - {}",- body.chars().take(80).collect::<String>()- ));+ ready += 1;+ continue;}let failure = format!("{endpoint} returned {status} (not a plugin bundle)");log::debug!("Health check failed: {failure}");@@ -1328,8 +1333,11 @@ pub async fn proxy_health_check(port: u16) -> Result<String, String> {}}}+ if all_client_modules_ready(ready, total) {+ return Ok(format!("healthy - {ready}/{total} client modules ready"));+ }Err(format!(- "HARNESS_NOT_READY: Harness client plugins are not ready ({})",+ "HARNESS_NOT_READY: Harness client modules are not ready ({ready}/{total} ready; {})",failures.join("; ")))}@@ -1369,6 +1377,13 @@ mod tests {assert!(not_owned_probe_signal(false).starts_with("HARNESS_NOT_OWNED"));}+ #[test]+ fn readiness_requires_every_client_module() {+ assert!(!all_client_modules_ready(1, 2));+ assert!(all_client_modules_ready(2, 2));+ assert!(!all_client_modules_ready(0, 0));+ }+/// 模拟“上个会话残留进程刚被杀、端口仍在释放”的场景:先占用端口,随后在/// 另一线程释放。验证 `wait_for_port_release` 在端口回落后立即返回,而不是/// 等到完整等待窗口——这正是避免端口永久顶高(dev 热更新下 3081→3082→…)diff --git a/src/hooks/use-iframe-shim.ts b/src/hooks/use-iframe-shim.tsindex e4ec5602..1da6bdc4 100644--- a/src/hooks/use-iframe-shim.ts+++ b/src/hooks/use-iframe-shim.ts@@ -5,6 +5,7 @@ import { getCurrentWindow } from '@tauri-apps/api/window'import { useEffect } from 'react'import { useEvent, useInterval, useMountedState } from 'react-use'import { queryClient } from '@/config/client'+import { store } from '@/store'import { getIframeOrigin } from '@/utils/iframe'interface NativeNotificationMessage {@@ -40,6 +41,11 @@ interface ClipboardImageRequest {id?: string}+interface PluginBootMessage {+ source?: 'dsh-plugin-boot-bridge'+ type?: 'dsh://plugin-boot:stalled' | 'dsh://plugin-boot:ready'+}+export function useIframeShim(iframeRef: RefObject<HTMLIFrameElement | null>) {const isMounted = useMountedState()@@ -137,9 +143,31 @@ export function useIframeShim(iframeRef: RefObject<HTMLIFrameElement | null>) {})}+ function handlePluginBoot(event: MessageEvent<PluginBootMessage>) {+ const data = event.data+ if (!data || typeof data !== 'object' || data.source !== 'dsh-plugin-boot-bridge') {+ return+ }+ if (event.source !== iframeRef.current?.contentWindow) {+ return+ }+ const iframeOrigin = getIframeOrigin(iframeRef)+ if (!iframeOrigin || event.origin !== iframeOrigin) {+ return+ }+ if (data.type === 'dsh://plugin-boot:ready') {+ store.harness.markIframeBootReady()+ return+ }+ if (data.type === 'dsh://plugin-boot:stalled') {+ void store.harness.recoverIframeBoot()+ }+ }+useEvent('message', handleMessage)useEvent('message', handlePluginError)useEvent('message', handleClipboardImage)+ useEvent('message', handlePluginBoot)// 系统通知点击 → 通知 iframe 聚焦对应会话useEffect(() => {diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex 035c4a51..e2a04cba 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -13,6 +13,15 @@"status.loading": "Loading plugins…","status.loading_plugins": "Loading plugins…","status.loading_internal": "Loading internal plugins…",+ "status.loading_process": "Starting Harness service…",+ "status.loading_client_modules": "Waiting for Harness client modules…",+ "status.internal_waiting": "Waiting to check internal plugins.",+ "status.internal_checking": "Checking {{total}} internal plugins.",+ "status.internal_installing": "Installing {{total}} internal plugins.",+ "status.internal_done": "Verified {{total}} internal plugins.",+ "startup.phase.plugin-install": "plugin installation",+ "startup.phase.process-boot": "process boot",+ "startup.phase.client-modules": "client modules","preinstall.title": "Install recommended plugins","preinstall.subtitle": "Choose which plugins to install before starting. You can manage them later from Settings → Plugin Market.","preinstall.recommend": "Recommended",@@ -64,7 +73,13 @@"download.saved_to": "Saved to","download.failed": "Session log download failed","download.show_in_folder": "Open",- "errors.service_start_timeout": "DeepSeek Harness startup timeout. Please check whether port {{port}} is occupied or the startup is too slow.",+ "errors.service_start_timeout": "DeepSeek Harness startup timed out.",+ "errors.startup_failed": "Harness failed during {{phase}}. Last readiness status: {{reason}}",+ "errors.startup_inactivity": "Harness made no progress during {{phase}} before its activity deadline. Last readiness status: {{reason}}",+ "errors.startup_absolute": "Harness exceeded the maximum allowed time for {{phase}}. Last readiness status: {{reason}}",+ "errors.startup_exited": "Harness exited during {{phase}}. Last readiness status: {{reason}}",+ "errors.no_readiness_reason": "No readiness reason was reported.",+ "errors.client_boot_stalled": "The client remained on Loading plugins after all bounded reload attempts.","errors.plugin_route_conflict": "Detected a plugin route conflict: two plugins registered the same route twice. Uninstall the recently added plugin (e.g. dsh-web-ui-all / dsh-better-sidebar) from the Plugins panel, or run dsh plugin --profile <profile> remove <package> for the active profile and retry.","errors.inotify_limit": "The Harness service crashed on startup: your system reached the limit for file watchers (inotify ENOSPC). Increase the watcher limit and restart — e.g. run `sudo sysctl fs.inotify.max_user_watches=524288` (and add `fs.inotify.max_user_watches=524288` to `/etc/sysctl.conf` to persist), then restart the app.","ui.service_url": "Service URL",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex d34eb548..07a8c249 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -13,6 +13,15 @@"status.loading": "Loading plugins…","status.loading_plugins": "Loading plugins…","status.loading_internal": "Loading internal plugins…",+ "status.loading_process": "正在启动 Harness 服务…",+ "status.loading_client_modules": "正在等待 Harness 客户端模块…",+ "status.internal_waiting": "正在等待检查内部插件。",+ "status.internal_checking": "正在检查 {{total}} 个内部插件。",+ "status.internal_installing": "正在安装 {{total}} 个内部插件。",+ "status.internal_done": "已核验 {{total}} 个内部插件。",+ "startup.phase.plugin-install": "插件安装",+ "startup.phase.process-boot": "进程启动",+ "startup.phase.client-modules": "客户端模块加载","preinstall.title": "安装推荐插件","preinstall.subtitle": "选择要在启动前安装的插件,之后也可以在设置中的插件市场里管理。","preinstall.recommend": "推荐",@@ -64,7 +73,13 @@"download.saved_to": "已保存到","download.failed": "Session 日志下载失败","download.show_in_folder": "打开",- "errors.service_start_timeout": "DeepSeek Harness 启动超时,请检查端口 {{port}} 是否被占用或启动过慢。",+ "errors.service_start_timeout": "DeepSeek Harness 启动超时。",+ "errors.startup_failed": "Harness 在{{phase}}阶段失败。最后的就绪状态:{{reason}}",+ "errors.startup_inactivity": "Harness 在{{phase}}阶段超过无活动期限。最后的就绪状态:{{reason}}",+ "errors.startup_absolute": "Harness 在{{phase}}阶段超过最长允许时间。最后的就绪状态:{{reason}}",+ "errors.startup_exited": "Harness 在{{phase}}阶段退出。最后的就绪状态:{{reason}}",+ "errors.no_readiness_reason": "后端未报告就绪原因。",+ "errors.client_boot_stalled": "客户端在全部有界刷新尝试后仍停留在 Loading plugins。","errors.plugin_route_conflict": "检测到插件路由冲突:两个插件重复注册了同一路由。请在「插件」面板卸载最近安装的插件(如 dsh-web-ui-all / dsh-better-sidebar),或在终端对当前档案执行 dsh plugin --profile <档案名> remove <包名> 后重试。","errors.inotify_limit": "Harness 服务启动即崩溃:系统文件监视(inotify)数量达到上限。请调高监视上限后重试——例如执行 `sudo sysctl fs.inotify.max_user_watches=524288`(并将 `fs.inotify.max_user_watches=524288` 写入 `/etc/sysctl.conf` 以持久化),然后重启应用。","ui.service_url": "服务地址",diff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsxindex 3003f08a..a7d7c168 100644--- a/src/layout/components/webview.tsx+++ b/src/layout/components/webview.tsx@@ -13,6 +13,12 @@ import { Navbar } from './navbar'import { PreinstallSetup } from './preinstall-setup'import { Setup } from './setup'+const STARTUP_STATUS_KEYS = {+ 'plugin-install': 'status.loading_internal',+ 'process-boot': 'status.loading_process',+ 'client-modules': 'status.loading_client_modules',+} as const+/*** 主区域视图:壳层导航栏(Navbar)常驻顶部,* 安装/错误态渲染 Setup,就绪态渲染 iframe@@ -24,7 +30,7 @@ export function Webview() {const {status,serviceHealthy,- internalLoading,+ startupPhase,iframeError,iframeKey,iframeSrc,@@ -82,7 +88,7 @@ export function Webview() {<div className="relative min-h-0 flex-1"><Ifcond={serviceHealthy}- else={<Loadable subtitle={internalLoading ? t('status.loading_internal') : t('status.loading')} />}+ else={<Loadable subtitle={t(STARTUP_STATUS_KEYS[startupPhase])} />}><iframekey={iframeKey}diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.tsindex 6139487d..d0dc99c3 100644--- a/src/store/modules/harness/store.ts+++ b/src/store/modules/harness/store.ts@@ -11,7 +11,7 @@ import type {SetupStatus,SidebarBusyAction,} from './types'-import type { ReadinessProbeResult } from '@/utils/readiness'+import type { ReadinessPollResult, ReadinessProbeResult, StartupPhase } from '@/utils/readiness'import { emitter } from '@hairy/react-lib'import { invoke } from '@tauri-apps/api/core'import { listen } from '@tauri-apps/api/event'@@ -19,11 +19,18 @@ import i18next from 'i18next'import { defineStore } from 'valtio-define'import { queryClient } from '@/config/client'import { containsInotifyLimitError, pickErrorLines } from '@/utils/log'-import { pollReadiness } from '@/utils/readiness'+import { BoundedReloadGate, pollReadiness, SingleFlight, waitForActivityTask } from '@/utils/readiness'import { harnessUpdater } from '../harness-updater'-const MAX_RETRIES = 8const IFRAME_LOAD_TIMEOUT = 20000+const HEALTH_PROBE_INITIAL_INTERVAL = 1000+const HEALTH_PROBE_MAX_INTERVAL = 5000+const STARTUP_INACTIVITY_TIMEOUT = 180000+const STARTUP_ABSOLUTE_TIMEOUT = 300000+const PLUGIN_INACTIVITY_TIMEOUT = 30000+const PLUGIN_ABSOLUTE_TIMEOUT = 600000+const PLUGIN_ACTIVITY_CHECK_INTERVAL = 1000+const IFRAME_RECOVERY_ABSOLUTE_TIMEOUT = 60000/** 启动失败时从服务日志尾部挑选的原始行上限(ANSI 清洗后按行截断) */const LOG_TAIL_MAX_BYTES = 16 * 1024@@ -35,8 +42,8 @@ interface StartupError extends Error {pluginConflictHint?: string/** Linux inotify 文件监视上限(ENOSPC)导致服务启动即崩溃时的针对性提示 */inotifyLimitHint?: string- /** 初始就绪窗口已耗尽,但后端进程仍由桌面端持有,可继续后台探测 */- readinessTimedOut?: boolean+ phase?: StartupPhase+ lastReason?: string}const initialInstaller: InstallerState = {@@ -57,6 +64,11 @@ const initialRecovery: RecoveryState = {let bootToken = 0/** 首次自动启动去重(React StrictMode 会重复挂载 effect) */let bootStarted = false+let pluginActivitySequence = 0+let pluginActivityReason = ''+const restartFlight = new SingleFlight<void>()+const iframeReloadGate = new BoundedReloadGate(3)+let iframeRefreshTimer: ReturnType<typeof setTimeout> | undefined/** 构建带时间戳的 iframe URL,避免 WebView2 缓存旧页面 */function generateTimestampedUrl(baseUrl: string): string {@@ -67,34 +79,44 @@ function generateTimestampedUrl(baseUrl: string): string {/** 通过 Rust 代理探测服务健康状态(超时 8s,网络抖动时重试) */async function checkHealthViaProxy(): Promise<ReadinessProbeResult> {+ let timeoutId: ReturnType<typeof setTimeout> | undefinedtry {const timeoutPromise = new Promise<never>((_, reject) => {- setTimeout(() => reject(new Error('health check timeout')), 8000)+ timeoutId = setTimeout(() => reject(new Error('health check timeout')), 8000)})const resultPromise = invoke<string>('proxy_health_check')const result = await Promise.race([resultPromise, timeoutPromise])const lower = result.toLowerCase()- if (- lower.includes('healthy')- || lower.includes('ready')- || result.includes('200')- || result.includes('201')- || lower.includes('ok')- ) {+ if (lower.startsWith('healthy')) {console.warn('[Harness] health check passed:', result.split(' - <!doctype html>')[0])- return { healthy: true, notOwned: false }+ return {+ healthy: true,+ notOwned: false,+ phase: 'client-modules',+ reason: result,+ }}console.warn('[Harness] health check returned:', result)- return { healthy: false, notOwned: false }+ return {+ healthy: false,+ notOwned: false,+ phase: 'client-modules',+ reason: result,+ }}catch (err) {const message = String(err)if (message.includes('HARNESS_NOT_OWNED')) {// dsh 进程已退出(典型如插件冲突导致启动即崩溃),继续等只会白白耗完- // 8 轮超时,让调用方立刻结束重试并展示日志里的真实错误。+ // 当前阶段 deadline,让调用方立刻结束并展示日志里的真实错误。console.warn('[Harness] dsh process exited during startup, failing fast')- return { healthy: false, notOwned: true }+ return {+ healthy: false,+ notOwned: true,+ phase: 'process-boot',+ reason: message,+ }}if (message.includes('502') || message.includes('Bad Gateway')) {console.warn('[Harness] transient 502 during health check, retrying')@@ -102,8 +124,65 @@ async function checkHealthViaProxy(): Promise<ReadinessProbeResult> {else {console.error('[Harness] health check failed:', err)}- return { healthy: false, notOwned: false }+ return {+ healthy: false,+ notOwned: false,+ phase: message.includes('client modules') || message.includes('client plugins')+ ? 'client-modules'+ : 'process-boot',+ reason: message,+ }+ }+ finally {+ if (timeoutId !== undefined) {+ clearTimeout(timeoutId)+ }+ }+}++function startupError(phase: StartupPhase, reason: string, kind: 'failed' | 'inactivity' | 'absolute' | 'exited'): StartupError {+ const phaseLabel = i18next.t(`startup.phase.${phase}`)+ const message = i18next.t(`errors.startup_${kind}`, {+ phase: phaseLabel,+ reason,+ })+ const error: StartupError = new Error(message)+ error.phase = phase+ error.lastReason = reason+ 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,+ onProbe?: (result: ReadinessProbeResult) => void,+): Promise<ReadinessPollResult> {+ return pollReadiness({+ probe: checkHealthViaProxy,+ intervalMs: HEALTH_PROBE_INITIAL_INTERVAL,+ maxIntervalMs: HEALTH_PROBE_MAX_INTERVAL,+ backoffFactor: 1.5,+ inactivityTimeoutMs: STARTUP_INACTIVITY_TIMEOUT,+ absoluteTimeoutMs,+ shouldContinue,+ onProbe,+ })}/** 读取服务日志尾部(去掉 ANSI 转义与空行),启动失败时展示真实错误 */@@ -188,8 +267,8 @@ export const harness = defineStore({iframeKey: 0,serviceHealthy: false,serviceRunning: false,- /** 内置插件核对/安装阶段:加载屏在「Loading internal plugins…」与「Loading plugins…」间切换 */- internalLoading: false,+ startupPhase: 'plugin-install' as StartupPhase,+ startupReason: '',busyAction: null as SidebarBusyAction,}),actions: {@@ -198,9 +277,15 @@ export const harness = defineStore({if (bootStarted)returnbootStarted = true- void this.listenPluginRecovery()- void this.listenInternalPhase()- void this.boot()+ void this.initialize()+ },++ async initialize() {+ await Promise.all([+ this.listenPluginRecovery(),+ this.listenInternalPhase(),+ ])+ await this.boot()},/**@@ -220,13 +305,19 @@ export const harness = defineStore({/*** 订阅后端「内置插件核对阶段」推送:`internal-plugins-phase` 事件- * (loading / done),加载屏据此在「Loading internal plugins…」与+ * (loading / progress / done),加载屏据此在「Loading internal plugins…」与* 「Loading plugins…」之间切换。事件在服务启动前发出,健康轮询期间到达。*/async listenInternalPhase() {try {await listen<InternalPluginsPhasePayload>('internal-plugins-phase', (event) => {- this.internalLoading = event.payload.phase === 'loading'+ const payload = event.payload+ pluginActivitySequence+++ pluginActivityReason = internalPluginReason(payload)+ if (payload.phase !== 'done') {+ this.startupPhase = 'plugin-install'+ this.startupReason = pluginActivityReason+ }})}catch (err) {@@ -238,7 +329,11 @@ export const harness = defineStore({refreshIframe() {this.iframeLoaded = falsethis.iframeError = false- setTimeout(() => {+ if (iframeRefreshTimer !== undefined) {+ clearTimeout(iframeRefreshTimer)+ }+ iframeRefreshTimer = setTimeout(() => {+ iframeRefreshTimer = undefinedthis.iframeKey++}, 800)},@@ -254,6 +349,44 @@ export const harness = defineStore({this.iframeLoaded = false},+ markIframeBootReady() {+ iframeReloadGate.markReady()+ if (iframeRefreshTimer !== undefined) {+ clearTimeout(iframeRefreshTimer)+ iframeRefreshTimer = undefined+ }+ },++ async recoverIframeBoot() {+ const generation = this.iframeKey+ const decision = iframeReloadGate.request(generation)+ if (decision === 'duplicate' || decision === 'ready')+ return+ if (decision === 'exhausted') {+ const reason = i18next.t('errors.client_boot_stalled')+ const error = startupError('client-modules', reason, 'absolute')+ this.fail(error.message, undefined, undefined, undefined, this.serviceRunning)+ return+ }++ const result = await pollHarnessReadiness(+ IFRAME_RECOVERY_ABSOLUTE_TIMEOUT,+ () => generation === this.iframeKey && this.serviceRunning,+ )+ if (generation !== this.iframeKey || !this.serviceRunning)+ return+ if (result.healthy) {+ this.refreshIframe()+ return+ }++ const phase = result.phase ?? 'client-modules'+ const reason = result.reason ?? i18next.t('errors.no_readiness_reason')+ const kind = result.notOwned ? 'exited' : result.timeout ?? 'failed'+ const error = startupError(phase, reason, kind)+ this.fail(error.message, undefined, undefined, undefined, !result.notOwned)+ },+/** 安装进度流:只前进不后退,供首次安装/手动更新共用 */async listenInstallProgress(): Promise<UnlistenFn> {return listen<InstallProgress>('install-progress', (e) => {@@ -292,6 +425,11 @@ export const harness = defineStore({// 服务(重)启动成功:清空插件异常修复态(若曾进入),并重置已「暂不处理」的插件this.recovery = { required: false, info: null, attempts: 0, busy: false }this.dismissedRecoveryIds = []+ iframeReloadGate.reset()+ if (iframeRefreshTimer !== undefined) {+ clearTimeout(iframeRefreshTimer)+ iframeRefreshTimer = undefined+ }// 服务(重)启动成功后,dsh 版本/端口/CLI 链接状态等运行时信息可能已变化// (典型:Harness 更新后旧版本缓存仍在,调试侧边栏需刷新页面才显示新版本)。// 使侧边栏相关查询缓存失效,重新打开/已挂载时自动拉取最新值。@@ -305,33 +443,6 @@ export const harness = defineStore({return true},- /**- * 初始就绪窗口超时后继续探测同一已持有进程。错误界面仍会及时出现,但只要后端- * 稍后完成插件加载,就自动恢复并挂载 iframe;新一轮 boot 会用 token 终止旧探测。- */- async recoverReadiness(token: number) {- const result = await pollReadiness({- probe: checkHealthViaProxy,- intervalMs: 2000,- shouldContinue: () => token === bootToken && this.serviceRunning && !this.serviceHealthy,- })- if (token !== bootToken)- return- if (result.notOwned) {- this.serviceRunning = false- return- }- if (!result.healthy)- return-- try {- await this.completeReadiness(token)- }- catch (err) {- console.error('[Harness] failed to complete delayed readiness recovery:', err)- }- },-/** 拉起服务并等待健康检查通过,通过后才允许挂载 iframe */async launchAndWait(token?: number) {this.status = 'ready'@@ -345,26 +456,42 @@ export const harness = defineStore({this.serviceHealthy = falsethis.iframeLoaded = falsethis.iframeError = false+ this.startupPhase = 'process-boot'+ this.startupReason = i18next.t('status.loading_process')try {await invoke('launch_harness')this.serviceRunning = true+ this.startupPhase = 'process-boot'+ this.startupReason = i18next.t('status.loading_process')// 后端遇到端口占用时会自动递增并持久化端口,启动后重新读取真实地址。const runtimeInfo = await invoke<{ service_url: string }>('get_runtime_info')this.serviceUrl = runtimeInfo.service_urlthis.iframeSrc = generateTimestampedUrl(runtimeInfo.service_url)- const result = await pollReadiness({- probe: checkHealthViaProxy,- intervalMs: 2000,- maxAttempts: MAX_RETRIES,- shouldContinue: () => token === undefined || token === bootToken,- })+ const result = await pollHarnessReadiness(+ STARTUP_ABSOLUTE_TIMEOUT,+ () => token === undefined || token === bootToken,+ (probe) => {+ if (probe.phase) {+ this.startupPhase = probe.phase+ }+ this.startupReason = probe.reason ?? ''+ },+ )+ if (token !== undefined && token !== bootToken) {+ return+ }if (!result.healthy) {- const error: StartupError = new Error(- i18next.t('errors.service_start_timeout', { port: new URL(this.serviceUrl).port || '3080' }),- )- error.readinessTimedOut = !result.notOwned- throw error+ const phase = result.phase ?? this.startupPhase+ const reason = result.reason ?? (this.startupReason || i18next.t('errors.no_readiness_reason'))+ if (result.notOwned) {+ this.serviceRunning = false+ throw startupError(phase, reason, 'exited')+ }+ if (result.timeout) {+ throw startupError(phase, reason, result.timeout)+ }+ throw startupError(phase, reason, 'failed')}// 服务已就绪后再取一次真实地址:`launch_harness` 可能因后端已在并发拉起// (auto_start)而提前返回,此刻端口若尚未落库,上面读到的 service_url 会是@@ -381,6 +508,11 @@ export const harness = defineStore({/** 启动流程:检测环境/安装依赖 → 拉起服务 → 已安装时后台检查更新 */async boot() {const token = ++bootToken+ iframeReloadGate.reset()+ if (iframeRefreshTimer !== undefined) {+ clearTimeout(iframeRefreshTimer)+ iframeRefreshTimer = undefined+ }// 回到加载态:已安装时不再显示检测/启动界面,直接进入页面加载状态this.serviceHealthy = falsethis.iframeLoaded = false@@ -426,19 +558,46 @@ export const harness = defineStore({await invoke('install_dependencies')}- // 内置插件自愈(独立于预装引导):无论是否进入预装页、点不点「继续/跳过」,- // 都在启动阶段先把内置插件核对/安装到位——加载屏先显示「Loading internal- // plugins…」(此处乐观置位消除文案闪跳,后端 internal-plugins-phase 事件为- // 权威信号),确保「下一步先加载内部插件」。后端幂等且不阻断:失败仅告警。- this.internalLoading = true+ // 内置插件自愈是独立、显式且有界的启动阶段。后端 heartbeat 只延长无活动+ // deadline,绝对上限不会延长;旧启动 token 失效时立即停止采纳结果。+ this.startupPhase = 'plugin-install'+ this.startupReason = i18next.t('status.loading_internal')+ pluginActivitySequence+++ pluginActivityReason = i18next.t('status.internal_waiting')try {- await invoke('ensure_internal_plugins')+ const result = await waitForActivityTask({+ task: invoke('ensure_internal_plugins'),+ getActivity: () => ({+ sequence: pluginActivitySequence,+ reason: pluginActivityReason,+ }),+ inactivityTimeoutMs: PLUGIN_INACTIVITY_TIMEOUT,+ absoluteTimeoutMs: PLUGIN_ABSOLUTE_TIMEOUT,+ intervalMs: PLUGIN_ACTIVITY_CHECK_INTERVAL,+ shouldContinue: () => token === bootToken,+ })+ if (result.cancelled) {+ return+ }+ if (result.timeout) {+ try {+ // 后端只在所属进程树已退出、共享 flight 已释放后返回;在此之前不+ // 进入失败态,避免用户立即 Retry 订阅到上一轮 cancelled 结果。+ await invoke('cancel_internal_plugins')+ }+ catch (cancelError) {+ console.error('[Harness] failed to cancel timed-out internal plugin install:', cancelError)+ throw startupError('plugin-install', String(cancelError), 'failed')+ }+ throw startupError('plugin-install', result.reason, result.timeout)+ }}catch (err) {- console.error('[Harness] ensure internal plugins failed (best-effort):', err)+ if (err instanceof Error && (err as StartupError).phase) {+ throw err+ }+ throw startupError('plugin-install', String(err), 'failed')}- this.internalLoading = false-// 预装插件引导:首次安装、老版本升级(无指纹基线)或 preset-plugins.json// 内容变更(社区新增推荐插件)时重新进入预设流程,装完/跳过后才拉起服务。// preset-plugins.json 随安装包发布、每次安装被强制覆盖,旧文件不可比对,@@ -465,17 +624,13 @@ export const harness = defineStore({const startupError = await attachStartupDiagnostics(err)// 尝试从日志定位问题插件:能定位则弹出修复界面(全屏恢复页)await this.reviewStartupRecovery(startupError.logLines ?? startupError.logs ?? [])- const keepServiceRunning = startupError.readinessTimedOut === truethis.fail(- String(startupError),+ startupError.message,startupError.logs,startupError.pluginConflictHint,startupError.inotifyLimitHint,- keepServiceRunning,+ this.serviceRunning,)- if (keepServiceRunning) {- void this.recoverReadiness(token)- }}finally {unlistenInstall?.()@@ -567,28 +722,30 @@ export const harness = defineStore({},/** 重启服务:先强杀再拉起,最终回到就绪/错误态 */- async restart() {- if (this.busyAction)- return- this.busyAction = 'restart'- // 手动重启(含修复界面上的「重启 Harness」):先退出恢复态,- // 若重启仍失败,boot 的 catch 会重新定位问题插件并再次弹出。- this.recovery = { ...this.recovery, required: false, busy: false }- try {- emitter.emit('config:dialog:hidden')- await invoke('shutdown_harness')- }- catch (err) {- console.error('[Harness] shutdown during restart failed:', err)- }- this.serviceRunning = false- this.iframeLoaded = false- try {- await this.boot()- }- finally {- this.busyAction = null- }+ restart(): Promise<void> {+ return restartFlight.run(async () => {+ if (this.busyAction)+ return+ this.busyAction = 'restart'+ // 手动重启(含修复界面上的「重启 Harness」):先退出恢复态,+ // 若重启仍失败,boot 的 catch 会重新定位问题插件并再次弹出。+ this.recovery = { ...this.recovery, required: false, busy: false }+ try {+ emitter.emit('config:dialog:hidden')+ await invoke('shutdown_harness')+ }+ catch (err) {+ console.error('[Harness] shutdown during restart failed:', err)+ }+ this.serviceRunning = false+ this.iframeLoaded = false+ try {+ await this.boot()+ }+ finally {+ this.busyAction = null+ }+ })},/** 停止服务并回到停止态界面 */@@ -696,9 +853,6 @@ export const harness = defineStore({this.preinstall.error = error.startsWith('NETWORK_ERROR:')? i18next.t('preinstall.network_error'): error- if (err instanceof Error && (err as StartupError).readinessTimedOut) {- void this.recoverReadiness(bootToken)- }}finally {unlisten?.()diff --git a/src/store/modules/harness/types.ts b/src/store/modules/harness/types.tsindex 1838cb14..ea405170 100644--- a/src/store/modules/harness/types.ts+++ b/src/store/modules/harness/types.ts@@ -23,9 +23,12 @@ export interface PreinstallLogPayload {line: string}-/** Rust 侧 internal-plugins-phase 事件载荷(内置插件核对阶段:loading / done) */+/** Rust 侧 internal-plugins-phase 事件载荷(内置插件核对/安装进度与 heartbeat) */export interface InternalPluginsPhasePayload {- phase: 'loading' | 'done'+ phase: 'loading' | 'progress' | 'done'+ detail: 'waiting' | 'checking' | 'installing' | 'heartbeat' | 'done'+ completed: number+ total: number}/** 安装器展示状态 */diff --git a/src/utils/readiness.ts b/src/utils/readiness.tsindex 129bdef6..de5506e7 100644--- a/src/utils/readiness.ts+++ b/src/utils/readiness.ts@@ -1,45 +1,296 @@+export type StartupPhase = 'plugin-install' | 'process-boot' | 'client-modules'+export type ReadinessTimeout = 'inactivity' | 'absolute'+export interface ReadinessProbeResult {healthy: booleannotOwned: boolean+ phase?: StartupPhase+ reason?: string+}++export interface ReadinessPollResult extends ReadinessProbeResult {+ timeout?: ReadinessTimeout}interface PollReadinessOptions {probe: () => Promise<ReadinessProbeResult>intervalMs: number+ maxIntervalMs?: number+ backoffFactor?: numbermaxAttempts?: number+ inactivityTimeoutMs?: number+ absoluteTimeoutMs?: number+ shouldContinue?: () => boolean+ onProbe?: (result: ReadinessProbeResult) => void+ now?: () => number+ wait?: (milliseconds: number) => Promise<void>+}++interface ActivitySnapshot {+ sequence: number+ reason: string+}++interface WaitForActivityTaskOptions<T> {+ task: Promise<T>+ getActivity: () => ActivitySnapshot+ inactivityTimeoutMs: number+ absoluteTimeoutMs: number+ intervalMs: numbershouldContinue?: () => boolean+ now?: () => numberwait?: (milliseconds: number) => Promise<void>}+export interface ActivityTaskResult<T> {+ completed: boolean+ cancelled: boolean+ timeout?: ReadinessTimeout+ value?: T+ reason: string+}+function delay(milliseconds: number): Promise<void> {return new Promise(resolve => setTimeout(resolve, milliseconds))}+function activityKey(result: ReadinessProbeResult): string {+ return `${result.phase ?? ''}\0${result.reason ?? ''}`+}++function timedOut(+ now: number,+ startedAt: number,+ lastActivityAt: number,+ inactivityTimeoutMs?: number,+ absoluteTimeoutMs?: number,+): ReadinessTimeout | undefined {+ if (absoluteTimeoutMs !== undefined && now - startedAt >= absoluteTimeoutMs) {+ return 'absolute'+ }+ if (inactivityTimeoutMs !== undefined && now - lastActivityAt >= inactivityTimeoutMs) {+ return 'inactivity'+ }+}++function boundedWait(+ requestedMs: number,+ now: number,+ startedAt: number,+ lastActivityAt: number,+ inactivityTimeoutMs?: number,+ absoluteTimeoutMs?: number,+): number {+ const limits = [requestedMs]+ if (absoluteTimeoutMs !== undefined) {+ limits.push(Math.max(0, absoluteTimeoutMs - (now - startedAt)))+ }+ if (inactivityTimeoutMs !== undefined) {+ limits.push(Math.max(0, inactivityTimeoutMs - (now - lastActivityAt)))+ }+ return Math.min(...limits)+}+export async function pollReadiness({probe,intervalMs,+ maxIntervalMs = intervalMs,+ backoffFactor = 1,maxAttempts,+ inactivityTimeoutMs,+ absoluteTimeoutMs,shouldContinue = () => true,+ onProbe,+ now = Date.now,wait = delay,-}: PollReadinessOptions): Promise<ReadinessProbeResult> {+}: PollReadinessOptions): Promise<ReadinessPollResult> {+ const startedAt = now()+ let lastActivityAt = startedAt+ let lastKey = ''+ let lastResult: ReadinessProbeResult = { healthy: false, notOwned: false }let remainingAttempts = maxAttempts+ let nextIntervalMs = intervalMswhile (shouldContinue() && remainingAttempts !== 0) {+ const beforeProbeTimeout = timedOut(+ now(),+ startedAt,+ lastActivityAt,+ inactivityTimeoutMs,+ absoluteTimeoutMs,+ )+ if (beforeProbeTimeout) {+ return { ...lastResult, timeout: beforeProbeTimeout }+ }+const result = await probe()if (!shouldContinue()) {return { healthy: false, notOwned: false }}+ lastResult = result+ onProbe?.(result)++ const nextKey = activityKey(result)+ if (nextKey !== lastKey) {+ lastKey = nextKey+ lastActivityAt = now()+ }if (remainingAttempts !== undefined) {remainingAttempts--}-if (result.healthy || result.notOwned) {return result}++ const afterProbeTimeout = timedOut(+ now(),+ startedAt,+ lastActivityAt,+ inactivityTimeoutMs,+ absoluteTimeoutMs,+ )+ if (afterProbeTimeout) {+ return { ...result, timeout: afterProbeTimeout }+ }if (shouldContinue() && remainingAttempts !== 0) {- await wait(intervalMs)+ const waitMs = boundedWait(+ nextIntervalMs,+ now(),+ startedAt,+ lastActivityAt,+ inactivityTimeoutMs,+ absoluteTimeoutMs,+ )+ await wait(waitMs)+ nextIntervalMs = Math.min(maxIntervalMs, Math.max(intervalMs, nextIntervalMs * backoffFactor))}}- return { healthy: false, notOwned: false }+ return lastResult+}++export async function waitForActivityTask<T>({+ task,+ getActivity,+ inactivityTimeoutMs,+ absoluteTimeoutMs,+ intervalMs,+ shouldContinue = () => true,+ now = Date.now,+ wait = delay,+}: WaitForActivityTaskOptions<T>): Promise<ActivityTaskResult<T>> {+ const startedAt = now()+ let lastActivityAt = startedAt+ let snapshot = getActivity()+ let settled = false+ let rejected = false+ let value: T | undefined+ let failure: unknown++ void task.then(+ (result) => {+ value = result+ settled = true+ },+ (error) => {+ failure = error+ rejected = true+ settled = true+ },+ )++ while (shouldContinue()) {+ if (settled) {+ if (rejected) {+ throw failure+ }+ return {+ completed: true,+ cancelled: false,+ value,+ reason: snapshot.reason,+ }+ }++ const nextSnapshot = getActivity()+ if (nextSnapshot.sequence !== snapshot.sequence) {+ snapshot = nextSnapshot+ lastActivityAt = now()+ }+ const timeout = timedOut(now(), startedAt, lastActivityAt, inactivityTimeoutMs, absoluteTimeoutMs)+ if (timeout) {+ return {+ completed: false,+ cancelled: false,+ timeout,+ reason: snapshot.reason,+ }+ }+ await wait(boundedWait(+ intervalMs,+ now(),+ startedAt,+ lastActivityAt,+ inactivityTimeoutMs,+ absoluteTimeoutMs,+ ))+ }++ return {+ completed: false,+ cancelled: true,+ reason: snapshot.reason,+ }+}++export class SingleFlight<T> {+ private pending: Promise<T> | null = null++ run(task: () => Promise<T>): Promise<T> {+ if (this.pending) {+ return this.pending+ }+ const pending = task().finally(() => {+ if (this.pending === pending) {+ this.pending = null+ }+ })+ this.pending = pending+ return pending+ }+}++export type ReloadDecision = 'reload' | 'duplicate' | 'exhausted' | 'ready'++export class BoundedReloadGate {+ private attempts = 0+ private lastGeneration = -1+ private ready = false++ constructor(private readonly maxAttempts: number) {}++ request(generation: number): ReloadDecision {+ if (this.ready) {+ return 'ready'+ }+ if (generation === this.lastGeneration) {+ return 'duplicate'+ }+ if (this.attempts >= this.maxAttempts) {+ return 'exhausted'+ }+ this.lastGeneration = generation+ this.attempts+++ return 'reload'+ }++ markReady(): void {+ this.ready = true+ }++ reset(): void {+ this.attempts = 0+ this.lastGeneration = -1+ this.ready = false+ }}diff --git a/test/plugin-boot.test.ts b/test/plugin-boot.test.tsnew file mode 100644index 00000000..819f82a5--- /dev/null+++ b/test/plugin-boot.test.ts@@ -0,0 +1,160 @@+import { readFileSync } from 'node:fs'+import { runInNewContext } from 'node:vm'+import { afterEach, describe, expect, it, vi } from 'vitest'++type PageState = 'empty' | 'splash' | 'chat' | 'normal'++interface BootHarness {+ messages: string[]+ setState: (state: PageState) => void+}++const script = readFileSync(+ new URL('../src-tauri/src/desktop/plugin_boot.js.inc', import.meta.url),+ 'utf8',+)++function createHarness(initialState: PageState): BootHarness {+ let state = initialState+ let mutationCallback = () => {}+ const messages: string[] = []++ function textNodes() {+ if (state === 'splash') {+ return [{ textContent: 'HARNESS' }, { textContent: 'Loading plugins…' }]+ }+ if (state === 'chat') {+ return [+ { textContent: 'HARNESS' },+ { textContent: 'Loading plugins…' },+ { textContent: 'A chat message mentioning Loading plugins…' },+ ]+ }+ return []+ }++ const boot = {+ parentElement: null as typeof root | null,+ get textContent() {+ return state === 'splash' ? 'HARNESS Loading plugins…' : ''+ },+ querySelectorAll(selector: string) {+ return selector === 'div, span, p' ? textNodes() : []+ },+ }++ const root = {+ get childElementCount() {+ return state === 'empty' ? 0 : 1+ },+ get textContent() {+ if (state === 'splash')+ return 'HARNESS Loading plugins…'+ if (state === 'chat')+ return 'HARNESS Loading plugins… A chat message mentioning Loading plugins…'+ if (state === 'normal')+ return 'Harness application'+ return ''+ },+ querySelector(selector: string) {+ if (selector === '[data-dsh-boot]' && state === 'splash')+ return boot+ if (state === 'normal' && selector.includes('main'))+ return { textContent: 'Harness application' }+ return null+ },+ }+ boot.parentElement = root++ class FakeMutationObserver {+ constructor(callback: () => void) {+ mutationCallback = callback+ }++ observe() {}++ disconnect() {}+ }++ const top = {}+ const window = {+ top,+ parent: {+ postMessage(message: { type: string }) {+ messages.push(message.type)+ },+ },+ addEventListener() {},+ removeEventListener() {},+ }+ runInNewContext(script, {+ window,+ document: {+ documentElement: {},+ getElementById: () => root,+ },+ MutationObserver: FakeMutationObserver,+ setTimeout,+ clearTimeout,+ setInterval,+ clearInterval,+ })++ return {+ messages,+ setState(nextState) {+ state = nextState+ mutationCallback()+ },+ }+}++afterEach(() => {+ vi.useRealTimers()+})++describe('plugin boot bridge', () => {+ it('starts the stall deadline when the splash appears late', () => {+ vi.useFakeTimers()+ const harness = createHarness('empty')++ vi.advanceTimersByTime(20_000)+ expect(harness.messages).toEqual([])++ harness.setState('splash')+ vi.advanceTimersByTime(7_999)+ expect(harness.messages).toEqual([])+ vi.advanceTimersByTime(1)+ expect(harness.messages).toEqual(['dsh://plugin-boot:stalled'])+ })++ it('resets the deadline when the splash disappears and rearms on reappearance', () => {+ vi.useFakeTimers()+ const harness = createHarness('splash')++ vi.advanceTimersByTime(4_000)+ harness.setState('empty')+ vi.advanceTimersByTime(10_000)+ expect(harness.messages).toEqual([])++ harness.setState('splash')+ vi.advanceTimersByTime(8_000)+ expect(harness.messages).toEqual(['dsh://plugin-boot:stalled'])+ })++ it('ignores matching page text and permanently disarms after the app shell mounts', () => {+ vi.useFakeTimers()+ const chat = createHarness('chat')+ vi.advanceTimersByTime(20_000)+ expect(chat.messages).toEqual([])++ const harness = createHarness('splash')+ vi.advanceTimersByTime(2_000)+ harness.setState('normal')+ expect(harness.messages).toEqual(['dsh://plugin-boot:ready'])++ harness.setState('splash')+ vi.advanceTimersByTime(20_000)+ expect(harness.messages).toEqual(['dsh://plugin-boot:ready'])+ })+})diff --git a/test/readiness.test.ts b/test/readiness.test.tsindex 5cb0b841..2a061c13 100644--- a/test/readiness.test.ts+++ b/test/readiness.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { pollReadiness } from '../src/utils/readiness'+import { BoundedReloadGate, pollReadiness, SingleFlight, waitForActivityTask } from '../src/utils/readiness'function noWait(): Promise<void> {return Promise.resolve()@@ -22,36 +22,92 @@ describe('pollReadiness', () => {expect(attempts).toBe(3)})- it('keeps recovery polling until a slow service becomes healthy', async () => {+ it('recovers when client modules become ready after the old attempt window', async () => {let attempts = 0const result = await pollReadiness({probe: async () => {attempts++- return { healthy: attempts === 5, notOwned: false }+ return {+ healthy: attempts === 12,+ notOwned: false,+ phase: 'client-modules',+ reason: attempts < 6 ? '0/2 modules ready' : '1/2 modules ready',+ }},intervalMs: 0,+ inactivityTimeoutMs: 20,+ absoluteTimeoutMs: 100,wait: noWait,})expect(result.healthy).toBe(true)- expect(attempts).toBe(5)+ expect(attempts).toBe(12)})- it('stops recovery when the owning startup is superseded', async () => {+ it('returns an absolute timeout even while readiness reasons keep changing', async () => {+ let clock = 0+ const result = await pollReadiness({+ probe: async () => ({+ healthy: false,+ notOwned: false,+ phase: 'client-modules',+ reason: `heartbeat ${clock}`,+ }),+ intervalMs: 10,+ inactivityTimeoutMs: 25,+ absoluteTimeoutMs: 50,+ now: () => clock,+ wait: async (milliseconds) => {+ clock += milliseconds+ },+ })++ expect(result.timeout).toBe('absolute')+ expect(clock).toBe(50)+ })++ it('returns an inactivity timeout when no progress is observed', async () => {+ let clock = 0+ const result = await pollReadiness({+ probe: async () => ({+ healthy: false,+ notOwned: false,+ phase: 'process-boot',+ reason: 'service is still starting',+ }),+ intervalMs: 10,+ inactivityTimeoutMs: 30,+ absoluteTimeoutMs: 100,+ now: () => clock,+ wait: async (milliseconds) => {+ clock += milliseconds+ },+ })++ expect(result.timeout).toBe('inactivity')+ expect(clock).toBe(30)+ })++ it('fails immediately when the owned process exits', async () => {let attempts = 0- let active = trueconst result = await pollReadiness({probe: async () => {attempts++- active = false- return { healthy: false, notOwned: false }+ return {+ healthy: false,+ notOwned: true,+ phase: 'process-boot',+ reason: 'owned process exited',+ }},- intervalMs: 0,- shouldContinue: () => active,+ intervalMs: 10,+ inactivityTimeoutMs: 30,+ absoluteTimeoutMs: 100,wait: noWait,})- expect(result).toEqual({ healthy: false, notOwned: false })+ expect(result.notOwned).toBe(true)+ expect(result.reason).toBe('owned process exited')expect(attempts).toBe(1)})@@ -71,3 +127,110 @@ describe('pollReadiness', () => {await expect(resultPromise).resolves.toEqual({ healthy: false, notOwned: false })})})++describe('waitForActivityTask', () => {+ it('allows plugin installation to exceed the old deadline while heartbeats continue', async () => {+ let clock = 0+ let sequence = 0+ const task = Promise.withResolvers<string>()+ const result = await waitForActivityTask({+ task: task.promise,+ getActivity: () => ({ sequence, reason: `plugin heartbeat ${sequence}` }),+ inactivityTimeoutMs: 30,+ absoluteTimeoutMs: 120,+ intervalMs: 10,+ now: () => clock,+ wait: async (milliseconds) => {+ clock += milliseconds+ sequence+++ if (clock === 70) {+ task.resolve('installed')+ }+ },+ })++ expect(result.completed).toBe(true)+ expect(result.value).toBe('installed')+ expect(clock).toBe(70)+ })++ it('caps a progressing plugin installation at its absolute deadline', async () => {+ let clock = 0+ let sequence = 0+ const result = await waitForActivityTask({+ task: new Promise<never>(() => {}),+ getActivity: () => ({ sequence, reason: `plugin heartbeat ${sequence}` }),+ inactivityTimeoutMs: 30,+ absoluteTimeoutMs: 50,+ intervalMs: 10,+ now: () => clock,+ wait: async (milliseconds) => {+ clock += milliseconds+ sequence+++ },+ })++ expect(result.timeout).toBe('absolute')+ expect(clock).toBe(50)+ })++ it('uses the absolute deadline when a no-progress phase has a longer inactivity allowance', async () => {+ let clock = 0+ const result = await waitForActivityTask({+ task: new Promise<never>(() => {}),+ getActivity: () => ({ sequence: 0, reason: 'waiting for plugin process' }),+ inactivityTimeoutMs: 100,+ absoluteTimeoutMs: 40,+ intervalMs: 10,+ now: () => clock,+ wait: async (milliseconds) => {+ clock += milliseconds+ },+ })++ expect(result.timeout).toBe('absolute')+ expect(result.reason).toBe('waiting for plugin process')+ })+})++describe('single flight', () => {+ it('coalesces concurrent restarts and permits a later restart', async () => {+ const flight = new SingleFlight<void>()+ const first = Promise.withResolvers<void>()+ let runs = 0+ function restart(): Promise<void> {+ return flight.run(async () => {+ runs+++ await first.promise+ })+ }++ const one = restart()+ const duplicate = restart()+ expect(one).toBe(duplicate)+ expect(runs).toBe(1)++ first.resolve()+ await one+ await restart()+ expect(runs).toBe(2)+ })+})++describe('bounded reload gate', () => {+ it('ignores duplicate stalled and ready events without creating reload loops', () => {+ const gate = new BoundedReloadGate(2)++ expect(gate.request(0)).toBe('reload')+ expect(gate.request(0)).toBe('duplicate')+ expect(gate.request(1)).toBe('reload')+ expect(gate.request(2)).toBe('exhausted')++ gate.markReady()+ expect(gate.request(3)).toBe('ready')+ expect(gate.request(3)).toBe('ready')++ gate.reset()+ expect(gate.request(0)).toBe('reload')+ })+})