DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
perf: overlap verified Harness startup and frontend boot (#1098)
Hairyea6a68f71915
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0f7e7e3f..1ba88da2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -335,6 +335,11 @@ jobs:- name: Checkout repositoryuses: actions/checkout@v7+ - name: Setup Node.js+ uses: actions/setup-node@v7+ with:+ node-version: '22'+- name: Install Linux dependenciesif: runner.os == 'Linux'run: |diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex cbe41829..064ccf32 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -185,8 +185,12 @@ windows-sys = { version = "0.61", features = ["Win32_Globalization","Win32_Security","Win32_Storage_FileSystem",+ "Win32_System_Com",+ "Win32_System_Diagnostics_ToolHelp","Win32_System_Environment","Win32_System_IO",+ "Win32_System_JobObjects",+ "Win32_System_LibraryLoader","Win32_System_Ioctl","Win32_System_Pipes","Win32_System_Registry",diff --git a/src-tauri/src/bridge/system_os.rs b/src-tauri/src/bridge/system_os.rsindex ba01ebdf..58f62891 100644--- a/src-tauri/src/bridge/system_os.rs+++ b/src-tauri/src/bridge/system_os.rs@@ -15,7 +15,7 @@ use tauri_plugin_opener::OpenerExt;pub async fn proxy_health_check(window: tauri::WebviewWindow,app_handle: AppHandle,-) -> Result<String, String> {+) -> Result<crate::service::workflow::HealthCheck, String> {let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());crate::service::workflow::instances::scope(profile, async move {let port = crate::service::workflow::instances::port(&app_handle);diff --git a/src-tauri/src/config/dependencies.rs b/src-tauri/src/config/dependencies.rsindex e1251f7f..9087a205 100644--- a/src-tauri/src/config/dependencies.rs+++ b/src-tauri/src/config/dependencies.rs@@ -4,7 +4,7 @@//! 的**安装根**记在映射表里://!//! - 路径 → 使用该根(可为任意绝对路径,或 `resources/...` 令牌,见-//! [`super::manifest::resolve_location`]);+//! [`super::manifest::resolve_location_from`]);//! - `null` → 由系统环境满足,桌面端不托管该依赖;//! - 键缺失 → 尚未探测,按清单的 `managedRoot` 默认托管根解析。//!@@ -91,7 +91,7 @@ fn read_mapping_cached(path: &Path) -> DependencyMapping {mapping}-fn read_mapping_at(path: &Path) -> DependencyMapping {+pub(crate) fn read_mapping_at(path: &Path) -> DependencyMapping {let Ok(raw) = std::fs::read_to_string(path) else {return DependencyMapping::default();};@@ -167,16 +167,32 @@ pub fn mapped<R: Runtime>(app: &AppHandle<R>, key: &str) -> Option<Option<PathBu/// 清单声明的默认托管根(映射未记录或为系统时使用)pub fn managed_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {- let declared = manifest::dependency_spec(app, key).and_then(|spec| spec.managed_root);- match declared {- Some(raw) => manifest::resolve_location(app, &raw),- None => super::runtime::get_base_dir(app).join(default_managed_root(key)),+ let base = super::runtime::get_base_dir(app);+ let resources = manifest::resource_root(app);+ manifest::with_manifest(app, |manifest| {+ managed_root_from(&base, resources.as_deref(), Some(manifest), key)+ })+ .unwrap_or_else(|| managed_root_from(&base, resources.as_deref(), None, key))+}++pub(crate) fn managed_root_from(+ base: &Path,+ resources: Option<&Path>,+ manifest: Option<&manifest::Manifest>,+ key: &str,+) -> PathBuf {+ match manifest+ .and_then(|manifest| manifest.dependencies.get(key))+ .and_then(|spec| spec.managed_root.as_deref())+ {+ Some(raw) => manifest::resolve_location_from(base, resources, raw),+ None => base.join(default_managed_root(key)),}}/// 当前生效的依赖根:映射指定的根优先,否则回落清单默认托管根///-/// 映射表里的值同样按 [`manifest::resolve_location`] 解析:绝对路径原样使用(任意+/// 映射表里的值同样按 [`manifest::resolve_location_from`] 解析:绝对路径原样使用(任意/// 位置),`$AppData/...` / `$Resources/...` 指向数据目录 / 安装包资源根。因此本地/// 捆绑 / 切换内核只需在映射表里写 `"dsh": "$Resources/dsh"` 或任意绝对路径,不必/// 改动清单或重装。@@ -189,16 +205,35 @@ pub fn managed_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {/// 进而转去联网下载。此时回落到清单托管根——普通安装的托管根与记录值本就同路,/// 悬空回落不影响既有行为。pub fn active_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {- let overridable = manifest::dependency_spec(app, key).is_none_or(|spec| spec.overridable);+ let base = super::runtime::get_base_dir(app);+ let resources = manifest::resource_root(app);+ let mapping = read_mapping(app);+ manifest::with_manifest(app, |manifest| {+ active_root_from(&base, resources.as_deref(), Some(manifest), &mapping, key)+ })+ .unwrap_or_else(|| active_root_from(&base, resources.as_deref(), None, &mapping, key))+}++pub(crate) fn active_root_from(+ base: &Path,+ resources: Option<&Path>,+ manifest: Option<&manifest::Manifest>,+ mapping: &DependencyMapping,+ key: &str,+) -> PathBuf {+ let overridable = manifest+ .and_then(|manifest| manifest.dependencies.get(key))+ .is_none_or(|spec| spec.overridable);if overridable {- if let Some(Some(recorded)) = mapped(app, key) {- let resolved = manifest::resolve_location(app, &recorded.to_string_lossy());+ if let Some(Some(recorded)) = mapping.get(key) {+ let resolved =+ manifest::resolve_location_from(base, resources, &recorded.to_string_lossy());if resolved.exists() {return resolved;}}}- managed_root(app, key)+ managed_root_from(base, resources, manifest, key)}/// 随包资源构建的随包核心根(`$Resources/dsh`);非随包构建为 None。@@ -218,12 +253,15 @@ pub fn bundled_core_dir<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {/// 入口相对路径(相对依赖根):清单 `dependencies.<key>.entry`,未声明时用内置默认pub fn entry_relative<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {- let declared = manifest::dependency_spec(app, key)- .and_then(|spec| spec.entry.resolve().map(str::to_string));- match declared {- Some(raw) => split_entry(&raw),- None => split_entry(default_entry(key)),- }+ manifest::with_manifest(app, |manifest| entry_relative_from(Some(manifest), key))+ .unwrap_or_else(|| entry_relative_from(None, key))+}++pub(crate) fn entry_relative_from(manifest: Option<&manifest::Manifest>, key: &str) -> PathBuf {+ let declared = manifest+ .and_then(|manifest| manifest.dependencies.get(key))+ .and_then(|spec| spec.entry.resolve());+ split_entry(declared.unwrap_or_else(|| default_entry(key)))}/// 当前生效的依赖入口绝对路径(不校验存在性)@@ -318,6 +356,58 @@ mod tests {let _ = std::fs::remove_dir_all(dir);}+ #[test]+ fn root_resolution_preserves_mapping_and_manifest_precedence() {+ let dir = tempfile::tempdir().unwrap();+ let base = dir.path().join("data");+ let resources = dir.path().join("resources");+ std::fs::create_dir_all(resources.join("mapped")).unwrap();+ let mut manifest = manifest::parse(+ r#"{"dependencies":{"dsh":{"managedRoot":"$AppData/default-core","overridable":true,"entry":"lib\\bin.js"}}}"#,+ )+ .unwrap();+ let mut mapping = DependencyMapping::default();+ let resolve = |manifest: Option<&manifest::Manifest>, mapping: &DependencyMapping| {+ active_root_from(&base, Some(&resources), manifest, mapping, DEP_DSH)+ };+ assert_eq!(+ resolve(Some(&manifest), &mapping),+ base.join("default-core")+ );+ mapping.set(DEP_DSH, None);+ assert_eq!(+ resolve(Some(&manifest), &mapping),+ base.join("default-core")+ );+ mapping.set(DEP_DSH, Some("$Resources/missing".into()));+ assert_eq!(+ resolve(Some(&manifest), &mapping),+ base.join("default-core")+ );+ mapping.set(DEP_DSH, Some("$Resources/mapped".into()));+ assert_eq!(resolve(Some(&manifest), &mapping), resources.join("mapped"));+ manifest.dependencies.get_mut(DEP_DSH).unwrap().overridable = false;+ assert_eq!(+ resolve(Some(&manifest), &mapping),+ base.join("default-core")+ );+ assert_eq!(resolve(None, &mapping), resources.join("mapped"));+ mapping.set(DEP_DSH, Some("$AppData/missing".into()));+ assert_eq!(resolve(None, &mapping), base.join("dependencies/dsh"));+ assert_eq!(+ managed_root_from(&base, None, Some(&manifest), DEP_DSH),+ base.join("default-core")+ );+ assert_eq!(+ entry_relative_from(Some(&manifest), DEP_DSH),+ PathBuf::from("lib").join("bin.js")+ );+ assert_eq!(+ entry_relative_from(None, DEP_PNPM),+ PathBuf::from("bin").join("pnpm.cjs")+ );+ }+#[test]fn entry_split_accepts_both_separators() {assert_eq!(@@ -365,10 +455,26 @@ mod tests {let base = PathBuf::from("C:/app-data");let resources = PathBuf::from("C:/app-resources");for (key, root, entry) in [- (DEP_NODE, default_managed_root(DEP_NODE), default_entry(DEP_NODE)),- (DEP_PNPM, default_managed_root(DEP_PNPM), default_entry(DEP_PNPM)),- (DEP_DSH, default_managed_root(DEP_DSH), default_entry(DEP_DSH)),- (DEP_GIT, default_managed_root(DEP_GIT), default_entry(DEP_GIT)),+ (+ DEP_NODE,+ default_managed_root(DEP_NODE),+ default_entry(DEP_NODE),+ ),+ (+ DEP_PNPM,+ default_managed_root(DEP_PNPM),+ default_entry(DEP_PNPM),+ ),+ (+ DEP_DSH,+ default_managed_root(DEP_DSH),+ default_entry(DEP_DSH),+ ),+ (+ DEP_GIT,+ default_managed_root(DEP_GIT),+ default_entry(DEP_GIT),+ ),] {let spec = manifest.dependencies.get(key).expect("spec should exist");let declared = spec.managed_root.as_deref().expect("managedRoot");diff --git a/src-tauri/src/config/manifest.rs b/src-tauri/src/config/manifest.rsindex 5a6c84c5..470ed0c3 100644--- a/src-tauri/src/config/manifest.rs+++ b/src-tauri/src/config/manifest.rs@@ -387,9 +387,15 @@ impl EntrySpec {/// `EISDIR: illegal operation on a directory, lstat 'C:'` 退出(Node 25 实测),/// 随包核心因此永远起不来。CLI shim 也会把这个前缀写进 `.cmd`,同样要归一化。pub fn resource_root<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {- let dir = app.path().resource_dir().ok()?;- let root = pick_resource_root(&dir).unwrap_or(dir);- Some(dunce::simplified(&root).to_path_buf())+ app.path()+ .resource_dir()+ .ok()+ .map(|dir| resource_root_from(&dir))+}++pub(crate) fn resource_root_from(resource_dir: &Path) -> PathBuf {+ let root = pick_resource_root(resource_dir).unwrap_or_else(|| resource_dir.to_path_buf());+ dunce::simplified(&root).to_path_buf()}/// 资源根探测顺序:扁平布局(exe 同级)优先,再 `resources/` 子目录布局。@@ -409,17 +415,21 @@ fn source_manifest_path() -> PathBuf {/// 定位资源清单:debug 优先当前 checkout,release 优先进安装包资源。pub fn manifest_path<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {- let mut candidates: Vec<PathBuf> = Vec::new();- let packaged = resource_root(app).map(|root| root.join(MANIFEST_FILE));- let source = source_manifest_path();- if cfg!(debug_assertions) {- candidates.push(source.clone());- candidates.extend(packaged.clone());+ manifest_path_from(resource_root(app).as_deref(), cfg!(debug_assertions))+}++pub(crate) fn manifest_path_from(+ resource_root: Option<&Path>,+ source_first: bool,+) -> Option<PathBuf> {+ let packaged = resource_root.map(|root| root.join(MANIFEST_FILE));+ let source = Some(source_manifest_path());+ let candidates = if source_first {+ [source, packaged]} else {- candidates.extend(packaged.clone());- candidates.push(source.clone());- }- candidates.into_iter().find(|path| path.is_file())+ [packaged, source]+ };+ candidates.into_iter().flatten().find(|path| path.is_file())}/// 解析结果缓存:清单是热路径(核心来源判定、插件清单、宠物列表、依赖映射都要读),@@ -506,22 +516,6 @@ pub fn is_above_recommended<R: Runtime>(app: &AppHandle<R>, version: &str) -> bo}}-/// 依赖映射规范(清单缺失或未声明该键时返回 None)-pub fn dependency_spec<R: Runtime>(app: &AppHandle<R>, key: &str) -> Option<DependencySpec> {- with_manifest(app, |manifest| manifest.dependencies.get(key).cloned())?-}--/// 位置令牌解析:`resources/...` 相对安装包资源根,其余相对 AppData 基础目录,-/// 绝对路径原样返回——依赖可以位于任意位置(AppData 托管、安装目录捆绑、-/// 或用户指定的其它盘符)。-pub fn resolve_location<R: Runtime>(app: &AppHandle<R>, raw: &str) -> PathBuf {- resolve_location_from(- &super::runtime::get_base_dir(app),- resource_root(app).as_deref(),- raw,- )-}-/// 位置令牌解析(依赖可位于任意位置:AppData 托管、安装目录捆绑、或用户指定的其它盘符):////// - 绝对路径(`C:/...`、`/opt/...`)原样返回;@@ -957,16 +951,26 @@ mod tests {// 两处都没有 → 无资源根assert_eq!(pick_resource_root(&dir), None);+ assert_eq!(resource_root_from(&dir), dir);// 只有嵌套布局 → 命中 `resources/` 子目录let nested = dir.join("resources");std::fs::create_dir_all(&nested).unwrap();std::fs::write(nested.join(MANIFEST_FILE), "{}").unwrap();assert_eq!(pick_resource_root(&dir), Some(nested.clone()));+ assert_eq!(resource_root_from(&dir), nested);// 扁平布局存在 → 扁平优先(Tauri 2 的两种落盘形态同时出现时以 exe 同级为准)std::fs::write(dir.join(MANIFEST_FILE), "{}").unwrap();assert_eq!(pick_resource_root(&dir), Some(dir.clone()));+ assert_eq!(resource_root_from(&dir), dir);+ assert_eq!(+ manifest_path_from(Some(&dir), false),+ Some(dir.join(MANIFEST_FILE))+ );+ let source = source_manifest_path();+ assert!(source.is_file());+ assert_eq!(manifest_path_from(Some(&dir), true), Some(source));let _ = std::fs::remove_dir_all(dir);}@@ -978,7 +982,7 @@ mod tests {#[test]fn resource_root_simplifies_windows_verbatim_prefix() {let verbatim = PathBuf::from(r"\\?\C:\app\resources\dsh");- let simplified = dunce::simplified(&verbatim).to_path_buf();+ let simplified = resource_root_from(&verbatim);if cfg!(windows) {assert_eq!(simplified, PathBuf::from(r"C:\app\resources\dsh"));assert!(!simplified.to_string_lossy().starts_with(r"\\?\"));diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rsindex acc5a080..db062701 100644--- a/src-tauri/src/config/runtime.rs+++ b/src-tauri/src/config/runtime.rs@@ -19,15 +19,19 @@ use super::{detect_region, Region};/// 全新 scratch home,不覆盖就会反复重下;指向稳定目录即可让首次下载在后续/// 运行中复用(清空该目录即回到「首次装配」状态,用于测启动 setup 流程)。pub fn get_base_dir<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {- if let Some(dir) = env::var_os(DOWNLOAD_CACHE_ENV_VAR) {- if !dir.is_empty() {- return PathBuf::from(dir);- }+ base_dir_from(|| {+ app_handle+ .path()+ .app_data_dir()+ .expect("Failed to resolve app data directory")+ })+}++pub(crate) fn base_dir_from(app_data: impl FnOnce() -> PathBuf) -> PathBuf {+ if let Some(dir) = env::var_os(DOWNLOAD_CACHE_ENV_VAR).filter(|dir| !dir.is_empty()) {+ return PathBuf::from(dir);}- let base = app_handle- .path()- .app_data_dir()- .expect("Failed to resolve app data directory");+ let base = app_data();if cfg!(debug_assertions) {base.join(APP_DATA_DEV_DIR_NAME)} else {@@ -161,42 +165,92 @@ fn is_executable(_path: &Path) -> bool {true}-/// 运行 `node --version` 并捕获输出-///-/// Windows 打包版是 GUI 进程(没有控制台),必须以 CREATE_NO_WINDOW 启动-/// node.exe,否则每次版本检查都会闪现一个黑色 cmd 窗口。-fn node_version_output(node: &Path) -> Option<std::process::Output> {+fn node_version_output(node: &Path, args: &[&str]) -> Option<std::process::Output> {#[cfg(windows)]- {- use std::os::windows::process::CommandExt;- std::process::Command::new(node)- .arg("--version")- .creation_flags(0x08000000) // CREATE_NO_WINDOW- .output()- .ok()+ if let Some(output) = crate::service::workflow::early::probe_output(node, args, true) {+ return output.ok();}- #[cfg(not(windows))]+ let mut command = std::process::Command::new(node);+ // 版本查询不应执行用户的 preload;真实服务仍沿用其 NODE_OPTIONS。+ command.args(args).env_remove("NODE_OPTIONS");+ #[cfg(windows)]{- std::process::Command::new(node)- .arg("--version")- .output()- .ok()+ use std::os::windows::process::CommandExt;+ command.creation_flags(0x08000000);}+ command.output().ok()}-/// 获取指定 Node.js 二进制的版本号(例如 "22.22.0")-pub fn get_node_version_of_path(node: &Path) -> Option<String> {- let output = node_version_output(node)?;+fn probe_node_version(node: &Path) -> Option<(String, Option<PathBuf>)> {+ if let Some(output) = node_version_output(+ node,+ &[+ "-p",+ "JSON.stringify([process.versions.node,process.execPath])",+ ],+ ) {+ if output.status.success() {+ if let Ok((version, actual)) =+ serde_json::from_slice::<(String, PathBuf)>(&output.stdout)+ {+ if semver::Version::parse(&version).is_ok() && actual.is_absolute() {+ return Some((version, Some(actual)));+ }+ }+ }+ }+ let output = node_version_output(node, &["--version"])?;if !output.status.success() {return None;}let stdout = String::from_utf8_lossy(&output.stdout);let version = stdout.trim().trim_start_matches('v');- if version.is_empty() {- None- } else {- Some(version.to_string())+ (!version.is_empty()).then(|| (version.to_string(), None))+}++type NodeVersionIdentity = (PathBuf, u64, std::time::SystemTime);++static NODE_VERSION_CACHE: std::sync::Mutex<Option<(NodeVersionIdentity, String)>> =+ std::sync::Mutex::new(None);++fn cached_node_version(+ node: &Path,+ cache: &std::sync::Mutex<Option<(NodeVersionIdentity, String)>>,+ probe: impl FnOnce() -> Option<(String, Option<PathBuf>)>,+) -> Option<String> {+ let identity = || {+ let path = dunce::canonicalize(node).ok()?;+ let meta = fs::metadata(&path).ok()?;+ meta.is_file()+ .then_some((path, meta.len(), meta.modified().ok()?))+ };+ // ponytail: 串行版本探测;多运行时高并发时再按文件身份分锁。+ let mut guard = cache.lock().unwrap_or_else(|error| error.into_inner());+ let Some(key) = identity() else {+ drop(guard);+ return probe().map(|(version, _)| version);+ };+ if let Some((cached_key, version)) = guard.as_ref() {+ if cached_key == &key {+ return Some(version.clone());+ }}+ let (version, actual) = probe()?;+ // 静态转发器可不改自身文件就切换 Node,只有实际执行文件一致才可复用版本。+ if actual+ .and_then(|path| dunce::canonicalize(path).ok())+ .as_ref()+ == Some(&key.0)+ && identity().as_ref() == Some(&key)+ {+ *guard = Some((key, version.clone()));+ }+ Some(version)+}++/// 获取指定 Node.js 二进制的版本号(例如 "22.22.0")+pub fn get_node_version_of_path(node: &Path) -> Option<String> {+ cached_node_version(node, &NODE_VERSION_CACHE, || probe_node_version(node))}/// 检测本地是否存在版本兼容的 Node.js 环境,返回其二进制路径@@ -228,15 +282,19 @@ pub fn set_prefer_bundled_node_runtime(prefer: bool) {/// 已安装的捆绑运行时 node 二进制(未安装时返回 None)pub fn bundled_node_binary(app_handle: &tauri::AppHandle) -> Option<PathBuf> {- let runtime_dir = get_node_install_path(app_handle);- let entry = dependencies::entry_relative(app_handle, dependencies::DEP_NODE);- let direct_path = runtime_dir.join(&entry);+ bundled_node_binary_from(+ &get_node_install_path(app_handle),+ &dependencies::entry_relative(app_handle, dependencies::DEP_NODE),+ )+}++pub(crate) fn bundled_node_binary_from(runtime_dir: &Path, entry: &Path) -> Option<PathBuf> {+ let direct_path = runtime_dir.join(entry);if direct_path.exists() {return Some(direct_path);}- // 只有在直接路径不存在时才进行开销较大的递归搜索(解压可能多套一层目录)let bin_name = entry.file_name()?.to_string_lossy().into_owned();- search_node_binary(&runtime_dir, &bin_name)+ search_node_binary(&runtime_dir.to_path_buf(), &bin_name)}/// Node.js 二进制路径@@ -244,12 +302,23 @@ pub fn bundled_node_binary(app_handle: &tauri::AppHandle) -> Option<PathBuf> {/// 优先级:ABI 探测要求捆绑运行时(原生模块不匹配时的兜底)> 映射表(`null` =/// 系统环境 / 路径 = 指定根)> 未记录时沿用「本地版本兼容优先」> 已安装的捆绑运行时。pub fn get_node_binary_path(app_handle: &tauri::AppHandle) -> PathBuf {- let runtime_dir = get_node_install_path(app_handle);- let target = runtime_dir.join(dependencies::entry_relative(- app_handle,- dependencies::DEP_NODE,- ));- let bundled = bundled_node_binary(app_handle);+ node_binary_path_from(+ &get_node_install_path(app_handle),+ &dependencies::entry_relative(app_handle, dependencies::DEP_NODE),+ matches!(+ dependencies::mapped(app_handle, dependencies::DEP_NODE),+ Some(Some(_))+ ),+ )+}++pub(crate) fn node_binary_path_from(+ runtime_dir: &Path,+ entry: &Path,+ pinned_managed: bool,+) -> PathBuf {+ let target = runtime_dir.join(entry);+ let bundled = bundled_node_binary_from(runtime_dir, entry);if prefer_bundled_node_runtime() {if let Some(bundled) = bundled.clone() {@@ -264,11 +333,6 @@ pub fn get_node_binary_path(app_handle: &tauri::AppHandle) -> PathBuf {);}- // 映射显式指定了托管根:该根下的运行时优先(缺失时才回落到系统环境)。- let pinned_managed = matches!(- dependencies::mapped(app_handle, dependencies::DEP_NODE),- Some(Some(_))- );if pinned_managed {if let Some(bundled) = bundled.clone() {log::debug!("Using mapped Node.js runtime root: {}", bundled.display());@@ -378,6 +442,9 @@ pub fn find_system_git_binary() -> Option<PathBuf> {/// 运行 Git 并捕获输出;GUI 进程下禁止闪现控制台窗口。#[cfg(windows)]fn git_output(binary: &Path, arg: &str) -> Option<std::process::Output> {+ if let Some(output) = crate::service::workflow::early::probe_output(binary, &[arg], false) {+ return output.ok();+ }use std::os::windows::process::CommandExt;std::process::Command::new(binary)@@ -422,22 +489,26 @@ fn git_binary_works(binary: &Path) -> bool {}/// 返回桌面端应注入子进程 PATH 的已选 Git `cmd` 目录。-#[cfg(windows)]pub fn get_git_cmd_dir<R: Runtime>(app_handle: &AppHandle<R>) -> Option<PathBuf> {- if let Some(system_git) = find_system_git_binary() {- return system_git.parent().map(Path::to_path_buf);- }- let bundled = get_mingit_binary_path(app_handle);- if bundled.is_file() && git_binary_works(&bundled) {- return bundled.parent().map(Path::to_path_buf);- }- None+ git_cmd_dir_from(|| get_mingit_binary_path(app_handle))}-/// 非 Windows 平台依赖系统 Git,不额外注入目录。-#[cfg(not(windows))]-pub fn get_git_cmd_dir<R: Runtime>(_app_handle: &AppHandle<R>) -> Option<PathBuf> {- None+pub(crate) fn git_cmd_dir_from(_bundled: impl FnOnce() -> PathBuf) -> Option<PathBuf> {+ #[cfg(windows)]+ {+ if let Some(system_git) = find_system_git_binary() {+ return system_git.parent().map(Path::to_path_buf);+ }+ let bundled = _bundled();+ if bundled.is_file() && git_binary_works(&bundled) {+ return bundled.parent().map(Path::to_path_buf);+ }+ None+ }+ #[cfg(not(windows))]+ {+ None+ }}/// 当前环境是否已有可供插件 Git 依赖使用的 Git。@@ -484,6 +555,10 @@ pub(crate) fn user_home_dir() -> Option<PathBuf> {/// - debug 子进程由 launch 显式收到同一个 `~/.dsh.dev`,开发版与生产版的会话、档案、/// 插件与主题因此互不干扰。pub fn get_dsh_data_path<R: Runtime>(_app_handle: &AppHandle<R>) -> PathBuf {+ dsh_data_path_from_env()+}++pub(crate) fn dsh_data_path_from_env() -> PathBuf {let dir_name = if cfg!(debug_assertions) {DSH_HOME_DEV_DIR_NAME} else {@@ -504,13 +579,20 @@ pub fn get_dsh_data_path<R: Runtime>(_app_handle: &AppHandle<R>) -> PathBuf {/// debug 构建写入独立的 `dsh-web.dev.log`:开发版每次启动都会轮转日志,若与/// 生产共用同一个文件,会把正在运行的生产版日志记录轮转覆盖掉。pub fn get_service_log_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {+ service_log_path_from(+ &get_base_dir(app_handle),+ crate::service::workflow::instances::current_profile().as_deref(),+ )+}++pub(crate) fn service_log_path_from(base: &Path, profile: Option<&str>) -> PathBuf {let name = if cfg!(debug_assertions) {"dsh-web.dev.log"} else {"dsh-web.log"};- let logs = get_base_dir(app_handle).join("logs");- match crate::service::workflow::instances::current_profile() {+ let logs = base.join("logs");+ match profile {Some(profile) => logs.join(profile).join(name),None => logs.join(name),}@@ -562,15 +644,7 @@ pub fn is_runtime_compatible(app_handle: &tauri::AppHandle) -> bool {if !node.exists() {return false;}- let output = match node_version_output(&node) {- Some(out) => out,- None => return false,- };- if !output.status.success() {- return false;- }- let stdout = String::from_utf8_lossy(&output.stdout);- is_supported_node_version(stdout.trim())+ get_node_version_of_path(&node).is_some_and(|version| is_supported_node_version(&version))}/// 从打包的 Harness 清单读取 dsh 版本(界面展示用)@@ -630,6 +704,335 @@ pub fn runtime_info<R: Runtime>(app: &AppHandle<R>, port: u16) -> RuntimeInfo {mod tests {use super::*;+ #[test]+ fn base_directory_preserves_build_split_and_cache_short_circuit() {+ let override_dir = env::var_os(DOWNLOAD_CACHE_ENV_VAR).filter(|dir| !dir.is_empty());+ let base = base_dir_from(|| {+ assert!(+ override_dir.is_none(),+ "cache override must not resolve AppData"+ );+ PathBuf::from("app-data")+ });+ let expected = override_dir.map(PathBuf::from).unwrap_or_else(|| {+ if cfg!(debug_assertions) {+ PathBuf::from("app-data").join(APP_DATA_DEV_DIR_NAME)+ } else {+ PathBuf::from("app-data")+ }+ });+ assert_eq!(base, expected);+ }++ #[test]+ fn bundled_node_resolution_preserves_direct_and_nested_layouts() {+ let root = tempfile::tempdir().unwrap();+ let entry = PathBuf::from("bin").join("node");+ assert_eq!(bundled_node_binary_from(root.path(), &entry), None);+ let nested = root.path().join("unpacked").join("node.exe");+ fs::create_dir_all(nested.parent().unwrap()).unwrap();+ fs::write(&nested, b"fixture").unwrap();+ assert_eq!(bundled_node_binary_from(root.path(), &entry), Some(nested));+ let direct = root.path().join(&entry);+ fs::create_dir_all(direct.parent().unwrap()).unwrap();+ fs::write(&direct, b"fixture").unwrap();+ assert_eq!(+ bundled_node_binary_from(root.path(), &entry),+ Some(direct.clone())+ );+ assert_eq!(node_binary_path_from(root.path(), &entry, true), direct);+ }++ #[test]+ fn service_log_path_keeps_profile_and_build_filename() {+ let base = Path::new("app-data");+ let name = if cfg!(debug_assertions) {+ "dsh-web.dev.log"+ } else {+ "dsh-web.log"+ };+ assert_eq!(+ service_log_path_from(base, None),+ base.join("logs").join(name)+ );+ assert_eq!(+ service_log_path_from(base, Some("profile-a")),+ base.join("logs").join("profile-a").join(name)+ );+ }++ #[cfg(not(windows))]+ #[test]+ fn git_cmd_dir_does_not_resolve_bundled_on_unix() {+ assert_eq!(+ git_cmd_dir_from(|| panic!("system Git needs no bundled path")),+ None+ );+ }++ #[test]+ fn node_version_cache_runs_probe_once_for_the_same_resolved_file() {+ let root = tempfile::tempdir().unwrap();+ let node = root.path().join("node");+ fs::write(&node, b"fixture").unwrap();+ let cache = std::sync::Mutex::new(None);+ let calls = std::cell::Cell::new(0);+ for path in [&node, &root.path().join(".").join("node")] {+ assert_eq!(+ cached_node_version(path, &cache, || {+ calls.set(calls.get() + 1);+ Some(("24.0.0".into(), Some(node.clone())))+ }),+ Some("24.0.0".into())+ );+ }+ assert_eq!(calls.get(), 1);+ }++ #[test]+ fn node_version_cache_merges_concurrent_probes_of_the_same_file() {+ let root = tempfile::tempdir().unwrap();+ let node = root.path().join("node");+ fs::write(&node, b"fixture").unwrap();+ let cache = std::sync::Mutex::new(None);+ let calls = std::sync::atomic::AtomicUsize::new(0);+ let barrier = std::sync::Barrier::new(4);+ std::thread::scope(|scope| {+ for _ in 0..4 {+ scope.spawn(|| {+ barrier.wait();+ assert_eq!(+ cached_node_version(&node, &cache, || {+ calls.fetch_add(1, Ordering::SeqCst);+ Some(("24.0.0".into(), Some(node.clone())))+ }),+ Some("24.0.0".into())+ );+ });+ }+ });+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ }++ #[test]+ fn node_version_cache_invalidates_when_size_mtime_or_path_changes() {+ let root = tempfile::tempdir().unwrap();+ let node = root.path().join("node");+ fs::write(&node, b"first").unwrap();+ let cache = std::sync::Mutex::new(None);+ let calls = std::cell::Cell::new(0);+ let probe = |path: &Path| {+ calls.set(calls.get() + 1);+ Some((format!("24.0.{}", calls.get()), Some(path.to_path_buf())))+ };+ assert_eq!(+ cached_node_version(&node, &cache, || probe(&node)),+ Some("24.0.1".into())+ );+ let original_modified = fs::metadata(&node).unwrap().modified().unwrap();+ fs::write(&node, b"replacement").unwrap();+ fs::File::options()+ .write(true)+ .open(&node)+ .unwrap()+ .set_modified(original_modified)+ .unwrap();+ assert_eq!(+ cached_node_version(&node, &cache, || probe(&node)),+ Some("24.0.2".into())+ );+ let modified = fs::metadata(&node).unwrap().modified().unwrap();+ fs::File::options()+ .write(true)+ .open(&node)+ .unwrap()+ .set_modified(modified + std::time::Duration::from_secs(2))+ .unwrap();+ assert_eq!(+ cached_node_version(&node, &cache, || probe(&node)),+ Some("24.0.3".into())+ );+ let other = root.path().join("other-node");+ fs::copy(&node, &other).unwrap();+ fs::File::options()+ .write(true)+ .open(&other)+ .unwrap()+ .set_modified(fs::metadata(&node).unwrap().modified().unwrap())+ .unwrap();+ assert_eq!(+ cached_node_version(&other, &cache, || probe(&other)),+ Some("24.0.4".into())+ );+ assert_eq!(calls.get(), 4);+ }++ #[test]+ fn node_version_cache_does_not_store_a_probe_if_the_file_changes_during_it() {+ let root = tempfile::tempdir().unwrap();+ let node = root.path().join("node");+ fs::write(&node, b"first").unwrap();+ let cache = std::sync::Mutex::new(None);+ assert_eq!(+ cached_node_version(&node, &cache, || {+ fs::write(&node, b"replacement").unwrap();+ Some(("24.0.0".into(), Some(node.clone())))+ }),+ Some("24.0.0".into())+ );+ assert_eq!(+ cached_node_version(&node, &cache, || Some((+ "24.0.1".into(),+ Some(node.clone())+ ))),+ Some("24.0.1".into())+ );+ }++ #[test]+ fn node_version_cache_does_not_reuse_a_fixed_shim_after_its_target_version_changes() {+ let root = tempfile::tempdir().unwrap();+ let node = root+ .path()+ .join(if cfg!(windows) { "node.cmd" } else { "node" });+ let script = if cfg!(windows) {+ "@echo off\r\nif \"%~1\"==\"-p\" (type \"%~dp0identity\") else (type \"%~dp0version\")\r\n"+ } else {+ "#!/bin/sh\nif [ \"$1\" = '-p' ]; then cat \"${0%/*}/identity\"; else cat \"${0%/*}/version\"; fi\n"+ };+ fs::write(&node, script).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(&node, fs::Permissions::from_mode(0o755)).unwrap();+ }+ let actual = root.path().join("actual-node");+ fs::write(&actual, b"target").unwrap();+ let before = fs::metadata(&node).unwrap();+ fs::write(root.path().join("version"), "v22.19.0\n").unwrap();+ fs::write(+ root.path().join("identity"),+ serde_json::to_vec(&("22.19.0", &actual)).unwrap(),+ )+ .unwrap();+ let first = get_node_version_of_path(&node).unwrap();+ assert_eq!(first, "22.19.0");+ assert!(is_supported_node_version(&first));+ fs::write(root.path().join("version"), "v23.0.0\n").unwrap();+ fs::write(+ root.path().join("identity"),+ serde_json::to_vec(&("23.0.0", &actual)).unwrap(),+ )+ .unwrap();+ let second = get_node_version_of_path(&node).unwrap();+ assert_eq!(second, "23.0.0");+ assert!(!is_supported_node_version(&second));+ let after = fs::metadata(&node).unwrap();+ assert_eq!(before.len(), after.len());+ assert_eq!(before.modified().unwrap(), after.modified().unwrap());+ fs::write(root.path().join("identity"), b"invalid JSON").unwrap();+ for version in ["22.19.0", "23.0.0"] {+ fs::write(root.path().join("version"), format!("v{version}\n")).unwrap();+ assert_eq!(get_node_version_of_path(&node).as_deref(), Some(version));+ }+ }++ #[test]+ fn node_version_cache_requires_an_existing_matching_exec_path() {+ let root = tempfile::tempdir().unwrap();+ let node = root.path().join("node");+ fs::write(&node, b"fixture").unwrap();+ let cache = std::sync::Mutex::new(None);+ for actual in [None, Some(root.path().join("missing-node"))] {+ for version in ["22.19.0", "23.0.0"] {+ assert_eq!(+ cached_node_version(&node, &cache, || Some((version.into(), actual.clone()))),+ Some(version.into())+ );+ }+ }+ }++ #[test]+ fn node_version_cache_executes_the_actual_node_probe_once() {+ let candidate = find_local_node_binary().expect("Node.js required for version probe tests");+ let (_, actual) = probe_node_version(&candidate).expect("working Node.js required");+ let node = actual.expect("Node.js must expose its real executable path");+ let output = node_version_output(&node, &["--version"]).unwrap();+ assert!(output.status.success());+ let expected = String::from_utf8(output.stdout)+ .unwrap()+ .trim()+ .trim_start_matches('v')+ .to_string();+ let cache = std::sync::Mutex::new(None);+ let calls = std::cell::Cell::new(0);+ for _ in 0..3 {+ assert_eq!(+ cached_node_version(&node, &cache, || {+ calls.set(calls.get() + 1);+ let result = probe_node_version(&node).unwrap();+ assert_eq!(+ dunce::canonicalize(result.1.as_ref().unwrap()).unwrap(),+ dunce::canonicalize(&node).unwrap()+ );+ Some(result)+ }),+ Some(expected.clone())+ );+ }+ assert_eq!(calls.get(), 1);+ }++ #[test]+ fn node_version_cache_does_not_remember_failed_probes() {+ let root = tempfile::tempdir().unwrap();+ let node = root.path().join("node");+ fs::write(&node, b"fixture").unwrap();+ let cache = std::sync::Mutex::new(None);+ assert_eq!(cached_node_version(&node, &cache, || None), None);+ assert_eq!(+ cached_node_version(&node, &cache, || Some((+ "24.0.0".into(),+ Some(node.clone())+ ))),+ Some("24.0.0".into())+ );+ assert_eq!(+ cached_node_version(&node, &cache, || panic!("success must be cached")),+ Some("24.0.0".into())+ );+ }++ #[test]+ fn node_version_cache_never_hits_when_file_identity_is_unavailable() {+ let root = tempfile::tempdir().unwrap();+ let node = root.path().join("node");+ fs::write(&node, b"fixture").unwrap();+ let cache = std::sync::Mutex::new(None);+ assert_eq!(+ cached_node_version(&node, &cache, || Some((+ "24.0.0".into(),+ Some(node.clone())+ ))),+ Some("24.0.0".into())+ );+ fs::remove_file(&node).unwrap();+ for version in ["24.0.1", "24.0.2"] {+ assert_eq!(+ cached_node_version(&node, &cache, || Some((version.into(), Some(node.clone())))),+ Some(version.into())+ );+ }+ fs::create_dir(&node).unwrap();+ for version in ["24.0.3", "24.0.4"] {+ assert_eq!(+ cached_node_version(&node, &cache, || Some((version.into(), Some(node.clone())))),+ Some(version.into())+ );+ }+ }+/// 为文件布局测试生成互不冲突的临时目录。fn unique_runtime_test_dir(name: &str) -> PathBuf {use std::time::{SystemTime, UNIX_EPOCH};diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rsindex 70748076..2a292fe4 100644--- a/src-tauri/src/config/setting.rs+++ b/src-tauri/src/config/setting.rs@@ -298,14 +298,12 @@ static FIRST_INSTALL: OnceLock<bool> = OnceLock::new();/// 几何恢复/退出保存都会写 store 并创建文件,判定晚于它们会把首装误判为升级。/// 判定结果进程内缓存,之后任何时点读取都拿到本次启动的同一结论。pub fn detect_first_install<R: Runtime>(app_handle: &AppHandle<R>) -> bool {- *FIRST_INSTALL.get_or_init(|| {- app_handle- .path()- .app_data_dir()- // 目录解析失败按老用户处理(保守:不做引导,回落 web 档案老行为)- .map(|dir| !dir.join(store_dat_file_name()).exists())- .unwrap_or(false)- })+ detect_first_install_at(app_handle.path().app_data_dir().ok().as_deref())+}++pub(crate) fn detect_first_install_at(app_data: Option<&std::path::Path>) -> bool {+ *FIRST_INSTALL+ .get_or_init(|| app_data.is_some_and(|dir| !dir.join(store_dat_file_name()).exists()))}/// 读取首装检测结果;尚未检测(或检测失败)时返回 `false`,保守按老用户处理。@@ -323,7 +321,7 @@ pub(crate) fn unwrap_json_value(.unwrap_or(std::borrow::Cow::Borrowed(value))}-fn setting_from_value(value: Option<&serde_json::Value>) -> Setting {+pub(crate) fn setting_from_value(value: Option<&serde_json::Value>) -> Setting {let mut setting = value.and_then(|value| serde_json::from_value(unwrap_json_value(value).into_owned()).ok()).unwrap_or_default();diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex acc5b3f2..3c77a855 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -99,73 +99,79 @@ fn webview_data_directory(app: &tauri::AppHandle<Wry>) -> std::path::PathBuf {/// setup apppub fn setup(app_handle: tauri::AppHandle) {- // 升级清理:内置插件已迁至 resources/node_modules(pnpm deploy 产物);旧安装- // 可能残留 resources/preset-plugins 与 resources/internal-plugins 目录。仅删除- // 旧目录,失败告警并继续启动(查找回退见 preset::find_bundled_in_root)。- if let Err(e) = crate::service::plugin::remove_legacy_bundled_plugins(&app_handle) {- log::warn!("legacy bundled plugins cleanup skipped: {e}");- }-- // 启动前清扫上次崩溃残留的孤儿 Harness(端口/PID 双重确认,见- // workflow::sweep_orphan_harness),避免新实例一路漂移端口- crate::service::workflow::sweep_orphan_harness(&app_handle);-- // 启动自愈:清理指向旧位置的 pnpm `.modules.yaml`。老版本完成数据搬迁后该- // 文件仍记录旧 $DSH_HOME(AppData)下的绝对路径,导致任何 pnpm 操作抛- // `ERR_PNPM_UNEXPECTED_VIRTUAL_STORE`(插件安装/更新失败,issue #103)。- // 幂等、best-effort:仅在检测到失效路径时删除,下次 pnpm 操作自动重建。- let dsh_home = crate::config::get_dsh_data_path(&app_handle);- if let Err(e) = crate::service::migrate::heal_stale_pnpm_metadata(&dsh_home) {- log::warn!("pnpm modules metadata self-heal skipped: {e}");- }-- // 档案迁移 + 首装引导:官方核心 0.1.5 起 `desktop` 档案名被保留给 Electron- // 应用(`--profile desktop` 直接报错),先把老用户的 `profiles/desktop` 改名到- // `tauri` 并改指 `active_profile`,再在桌面端首次安装时新建独立档案并切换- // (与 CLI 用户既有插件/补丁隔离,见 service::profile)。必须先于 scheduler/- // auto_start:它们启动服务/装插件时会带上 active_profile,迁移完成前 dsh- // spawn 必然失败。- crate::service::profile::migrate_desktop_profile_name(&app_handle);+ crate::service::workflow::early::setup(move |prepared| {+ if !prepared {+ // 升级清理:内置插件已迁至 resources/node_modules(pnpm deploy 产物);旧安装+ // 可能残留 resources/preset-plugins 与 resources/internal-plugins 目录。仅删除+ // 旧目录,失败告警并继续启动(查找回退见 preset::find_bundled_in_root)。+ if let Err(e) = crate::service::plugin::remove_legacy_bundled_plugins(&app_handle) {+ log::warn!("legacy bundled plugins cleanup skipped: {e}");+ }- // 启动进程监控(tick 检测 dsh 服务状态)- crate::service::workflow::instances::window_profile(&app_handle, MAIN_WINDOW_LABEL);- crate::service::scheduler::start(&app_handle);+ // 启动前清扫上次崩溃残留的孤儿 Harness(端口/PID 双重确认,见+ // workflow::sweep_orphan_harness),避免新实例一路漂移端口+ crate::service::workflow::sweep_orphan_harness(&app_handle);++ // 启动自愈:清理指向旧位置的 pnpm `.modules.yaml`。老版本完成数据搬迁后该+ // 文件仍记录旧 $DSH_HOME(AppData)下的绝对路径,导致任何 pnpm 操作抛+ // `ERR_PNPM_UNEXPECTED_VIRTUAL_STORE`(插件安装/更新失败,issue #103)。+ // 幂等、best-effort:仅在检测到失效路径时删除,下次 pnpm 操作自动重建。+ let dsh_home = crate::config::get_dsh_data_path(&app_handle);+ if let Err(e) = crate::service::migrate::heal_stale_pnpm_metadata(&dsh_home) {+ log::warn!("pnpm modules metadata self-heal skipped: {e}");+ }- // `dsh://` 深链(成功页「打开应用」按钮):仅打包态注册协议并接管 open-url- // (debug 注册会把系统 `dsh:` 指向调试产物)。- #[cfg(not(debug_assertions))]- crate::desktop::deep_link::init(&app_handle);-- // 开机自启动:已安装且开启 auto_start 时拉起服务- let app_for_start = app_handle.clone();- tauri::async_runtime::spawn(async move {- let setting = crate::config::get_store_dat_setting(&app_for_start);- if !setting.auto_start {- log::debug!("auto_start disabled, skipping startup");- return;- }- let profile =- crate::service::workflow::instances::window_profile(&app_for_start, MAIN_WINDOW_LABEL);- if let Err(e) = crate::service::workflow::instances::scope(- profile,- crate::service::workflow::start(app_for_start),- )- .await- {- log::error!("start failed: {}", e);+ // 档案迁移 + 首装引导:官方核心 0.1.5 起 `desktop` 档案名被保留给 Electron+ // 应用(`--profile desktop` 直接报错),先把老用户的 `profiles/desktop` 改名到+ // `tauri` 并改指 `active_profile`,再在桌面端首次安装时新建独立档案并切换+ // (与 CLI 用户既有插件/补丁隔离,见 service::profile)。必须先于 scheduler/+ // auto_start:它们启动服务/装插件时会带上 active_profile,迁移完成前 dsh+ // spawn 必然失败。+ crate::service::profile::migrate_desktop_profile_name(&app_handle);}- });- // 命令行集成自愈:已安装且开启时,确保 shim 与 PATH 注册完整- // (shim 被删除、PATH 条目丢失等情况下自动重建)- tauri::async_runtime::spawn(async move {- let setting = crate::config::get_store_dat_setting(&app_handle);- if !setting.installed || !setting.cli_link_enabled {- return;- }- if let Err(e) = crate::service::cli::ensure(&app_handle) {- log::warn!("cli link self-heal failed: {e}");- }+ // 启动进程监控(tick 检测 dsh 服务状态)+ crate::service::workflow::instances::window_profile(&app_handle, MAIN_WINDOW_LABEL);+ crate::service::scheduler::start(&app_handle);++ // `dsh://` 深链(成功页「打开应用」按钮):仅打包态注册协议并接管 open-url+ // (debug 注册会把系统 `dsh:` 指向调试产物)。+ #[cfg(not(debug_assertions))]+ crate::desktop::deep_link::init(&app_handle);++ // 开机自启动:已安装且开启 auto_start 时拉起服务+ let app_for_start = app_handle.clone();+ tauri::async_runtime::spawn(async move {+ let setting = crate::config::get_store_dat_setting(&app_for_start);+ if !setting.auto_start {+ log::debug!("auto_start disabled, skipping startup");+ return;+ }+ let profile = crate::service::workflow::instances::window_profile(+ &app_for_start,+ MAIN_WINDOW_LABEL,+ );+ if let Err(e) = crate::service::workflow::instances::scope(+ profile,+ crate::service::workflow::start(app_for_start),+ )+ .await+ {+ log::error!("start failed: {}", e);+ }+ });++ // 命令行集成自愈:已安装且开启时,确保 shim 与 PATH 注册完整+ // (shim 被删除、PATH 条目丢失等情况下自动重建)+ tauri::async_runtime::spawn(async move {+ let setting = crate::config::get_store_dat_setting(&app_handle);+ if !setting.installed || !setting.cli_link_enabled {+ return;+ }+ if let Err(e) = crate::service::cli::ensure(&app_handle) {+ log::warn!("cli link self-heal failed: {e}");+ }+ });});}@@ -1126,6 +1132,11 @@ pub fn build_main_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::Welog::info!("[notification] scheduling handler registration from setup");let webview_for_dialog = webview_window.clone();if let Err(e) = webview_window.with_webview(move |webview| {+ if let Err(error) =+ crate::desktop::frontend_preload::install(&webview, &webview_for_dialog)+ {+ log::warn!("FRONTEND_PRELOAD_UNAVAILABLE: {error}");+ }if let Err(e) = crate::desktop::notification::enable_notification_permissions(webview,webview_for_dialog,@@ -1590,6 +1601,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::remove_core,crate::bridge::update_local_core,crate::bridge::proxy_health_check,+ crate::desktop::frontend_preload::prepare_frontend_preload,crate::bridge::harness_ownership,crate::bridge::get_runtime_info,crate::bridge::runtime_ready,@@ -1930,7 +1942,7 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {// 因此开发环境跳过该插件。// `deep-link` feature 只在单例在场时起作用:把二次启动携带的 `dsh://` URL// (成功页「打开应用」按钮)转发给主实例派发 open-url。- #[cfg(not(debug_assertions))]+ #[cfg(all(not(windows), not(debug_assertions)))]let builder = builder.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {crate::utils::show_main_window(app);}));diff --git a/src-tauri/src/desktop/frontend_preload.js.inc b/src-tauri/src/desktop/frontend_preload.js.incnew file mode 100644index 00000000..deda4a50--- /dev/null+++ b/src-tauri/src/desktop/frontend_preload.js.inc@@ -0,0 +1,134 @@+const gate = Promise.withResolvers();+globalThis.__DSH_BOOT_READY__ = gate;+gate.promise.catch(() => {});+let settled = false;++function notify(type, detail) {+ window.parent.postMessage({ type, id: preload.id, detail }, preload.parentOrigin);+}++function fail(error) {+ if (settled)+ return;+ settled = true;+ gate.reject(error);+ notify('dsh://frontend-preload:failed', String(error));+}++function sameAttributes(left, right) {+ return left.attributes.length === right.attributes.length+ && [...left.attributes].every(attribute => right.getAttribute(attribute.name) === attribute.value);+}++function prefix(live, template) {+ const actual = [...live.childNodes];+ const expected = [...template.childNodes];+ if (actual.length < expected.length)+ throw new Error('FRONTEND_PRELOAD_TEMPLATE: missing static nodes');+ const offset = actual.length - expected.length;+ if (!expected.every((node, index) => node.isEqualNode(actual[offset + index])))+ throw new Error('FRONTEND_PRELOAD_TEMPLATE: static frontend changed');+ return actual.slice(0, offset).filter(node => node.nodeType !== Node.TEXT_NODE || node.textContent.trim() !== '');+}++function plan(html) {+ const parser = new DOMParser();+ const live = parser.parseFromString(html, 'text/html');+ const template = parser.parseFromString(preload.template, 'text/html');+ if (!sameAttributes(live.documentElement, template.documentElement)+ || !sameAttributes(live.head, template.head) || !sameAttributes(live.body, template.body))+ throw new Error('FRONTEND_PRELOAD_TEMPLATE: document attributes changed');+ const head = prefix(live.head, template.head);+ const body = prefix(live.body, template.body);+ const ready = body.pop();+ if (ready?.nodeName !== 'SCRIPT' || ready.attributes.length !== 0+ || ready.textContent.trim() !== '(globalThis.__DSH_BOOT_READY__ ??= Promise.withResolvers()).resolve()')+ throw new Error('FRONTEND_PRELOAD_BOOT: missing authoritative ready marker');+ const rows = [...head.map(node => [document.head, node]), ...body.map(node => [document.body, node])];+ let loader = false;+ let graph = false;+ for (const [, node] of rows) {+ if (node.nodeType !== Node.ELEMENT_NODE)+ throw new Error('FRONTEND_PRELOAD_TEMPLATE: unsupported injection node');+ if (node.nodeName === 'BASE') {+ if (node.attributes.length !== 1 || node.getAttribute('href') !== './')+ throw new Error('FRONTEND_PRELOAD_TEMPLATE: unsupported base');+ }+ else if (node.nodeName === 'SCRIPT') {+ if ([...node.attributes].some(attribute => attribute.name !== 'src'))+ throw new Error('FRONTEND_PRELOAD_TEMPLATE: unsupported script attributes');+ if (node.hasAttribute('src')) {+ const url = new URL(node.getAttribute('src'), location.href);+ if (url.origin !== location.origin || !url.pathname.startsWith('/plugins/'))+ throw new Error('FRONTEND_PRELOAD_BOOT: script is not an owned plugin');+ }+ else {+ loader ||= node.textContent.includes('__ModuleLoader__');+ graph ||= node.textContent.includes('globalThis["__DSH_BOOT__"] = ');+ if (node.textContent.includes('__DSH_BOOT_READY__'))+ throw new Error('FRONTEND_PRELOAD_BOOT: unexpected readiness injection');+ }+ }+ else if (node.nodeName === 'LINK') {+ const url = new URL(node.getAttribute('href'), location.href);+ if (node.getAttribute('rel') !== 'preload' || node.getAttribute('as') !== 'script'+ || [...node.attributes].some(attribute => !['rel', 'as', 'href'].includes(attribute.name))+ || url.origin !== location.origin || !url.pathname.startsWith('/plugins/'))+ throw new Error('FRONTEND_PRELOAD_TEMPLATE: unsupported preload');+ }+ else if (node.nodeName !== 'STYLE' || node.attributes.length !== 0) {+ throw new Error('FRONTEND_PRELOAD_TEMPLATE: unsupported HTML injection');+ }+ }+ if (!loader || !graph)+ throw new Error('FRONTEND_PRELOAD_BOOT: missing module loader or graph');+ return rows;+}++async function apply(html) {+ const rows = plan(html);+ const anchors = new Map([[document.head, document.head.firstChild], [document.body, document.body.firstChild]]);+ for (const [target, node] of rows) {+ const element = document.createElement(node.localName);+ for (const attribute of node.attributes)+ element.setAttribute(attribute.name, attribute.value);+ element.textContent = node.textContent;+ if (node.nodeName === 'SCRIPT' && node.hasAttribute('src')) {+ await new Promise((resolve, reject) => {+ element.onload = resolve;+ element.onerror = () => reject(new Error('FRONTEND_PRELOAD_BOOT: plugin script failed'));+ target.insertBefore(element, anchors.get(target));+ });+ }+ else {+ target.insertBefore(element, anchors.get(target));+ }+ if (settled)+ throw new Error('FRONTEND_PRELOAD_BOOT: bootstrap interrupted');+ }+ if (!globalThis.__ModuleLoader__ || !globalThis.__DSH_BOOT__)+ throw new Error('FRONTEND_PRELOAD_BOOT: bootstrap did not initialize');+ settled = true;+ window.removeEventListener('message', receive);+ gate.resolve();+ notify('dsh://frontend-preload:applied');+}++function receive(event) {+ if (settled || event.source !== window.parent || event.origin !== preload.parentOrigin)+ return;+ const data = event.data;+ if (data?.source !== 'dsh-desktop' || data.type !== 'dsh://frontend-preload:boot' || data.id !== preload.id)+ return;+ if (typeof data.html !== 'string' || data.html.length > 4194304) {+ fail(new Error('FRONTEND_PRELOAD_BOOT: invalid live document'));+ return;+ }+ window.removeEventListener('message', receive);+ void apply(data.html).catch(fail);+}++window.addEventListener('message', receive);+window.addEventListener('pagehide', () => window.removeEventListener('message', receive), { once: true });+window.addEventListener('error', event => fail(event.error ?? new Error('FRONTEND_PRELOAD_ASSET: frontend asset failed')), { once: true });+window.addEventListener('DOMContentLoaded', () => notify('dsh://frontend-preload:waiting'), { once: true });diff --git a/src-tauri/src/desktop/frontend_preload.rs b/src-tauri/src/desktop/frontend_preload.rsnew file mode 100644index 00000000..116e819f--- /dev/null+++ b/src-tauri/src/desktop/frontend_preload.rs@@ -0,0 +1,358 @@+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex, OnceLock};++use tauri::{AppHandle, Manager, Url, WebviewWindow, Wry};++const PRELOAD_QUERY: &str = "_dshPreload";+const GATE_SCRIPT: &str = include_str!("frontend_preload.js.inc");+#[cfg(any(windows, test))]+const RESOURCE_FILTERS: [(&str, bool); 5] = [+ ("http://127.0.0.1:*/*", true),+ ("http://127.0.0.1:*/assets/*", false),+ ("http://127.0.0.1:*/manifest.webmanifest*", false),+ ("http://127.0.0.1:*/favicon.svg*", false),+ ("http://127.0.0.1:*/favicon-dark.svg*", false),+];++#[derive(Default)]+struct WindowPreload {+ generation: u64,+ frontend: Option<Frontend>,+ serving: bool,+}++struct Frontend {+ profile: String,+ origin: String,+ id: String,+ root: PathBuf,+ index: Vec<u8>,+}++fn windows() -> &'static Mutex<HashMap<String, Arc<Mutex<WindowPreload>>>> {+ static WINDOWS: OnceLock<Mutex<HashMap<String, Arc<Mutex<WindowPreload>>>>> = OnceLock::new();+ WINDOWS.get_or_init(Mutex::default)+}++fn frontend_root(core: &Path) -> Option<PathBuf> {+ core.ancestors().take(4).find_map(|base| {+ let package = base.join("node_modules/@deepseek-ai/dsh-web-frontend");+ let metadata: serde_json::Value =+ serde_json::from_slice(&std::fs::read(package.join("package.json")).ok()?).ok()?;+ (metadata.get("name")?.as_str()? == "@deepseek-ai/dsh-web-frontend")+ .then(|| dunce::canonicalize(package.join("dist")).ok())?+ })+}++fn asset_path(root: &Path, encoded: &str) -> Option<PathBuf> {+ let mut decoded = Vec::with_capacity(encoded.len());+ let mut bytes = encoded.bytes();+ while let Some(byte) = bytes.next() {+ decoded.push(if byte == b'%' {+ let high = char::from(bytes.next()?).to_digit(16)?;+ let low = char::from(bytes.next()?).to_digit(16)?;+ ((high << 4) | low) as u8+ } else {+ byte+ });+ }+ let decoded = String::from_utf8(decoded).ok()?;+ let relative = decoded.strip_prefix('/')?;+ if relative.is_empty()+ || relative.split('/').any(|part| {+ part.is_empty()+ || matches!(part, "." | "..")+ || part.ends_with(['.', ' '])+ || part+ .chars()+ .any(|c| c.is_control() || matches!(c, '\\' | ':' | '%'))+ })+ {+ return None;+ }+ if !relative.starts_with("assets/")+ && !matches!(+ relative,+ "manifest.webmanifest" | "favicon.svg" | "favicon-dark.svg"+ )+ {+ return None;+ }+ let target = dunce::canonicalize(root.join(relative)).ok()?;+ (target.starts_with(root) && target.is_file()).then_some(target)+}++fn content_type(path: &Path) -> &'static str {+ match path.extension().and_then(|extension| extension.to_str()) {+ Some("js" | "mjs") => "text/javascript; charset=utf-8",+ Some("css") => "text/css; charset=utf-8",+ Some("svg") => "image/svg+xml",+ Some("json" | "map" | "webmanifest") => "application/json",+ Some("woff2") => "font/woff2",+ Some("woff") => "font/woff",+ Some("ttf") => "font/ttf",+ Some("png") => "image/png",+ Some("jpg" | "jpeg") => "image/jpeg",+ Some("webp") => "image/webp",+ Some("gif") => "image/gif",+ Some("wasm") => "application/wasm",+ _ => "application/octet-stream",+ }+}++fn load_frontend(+ core: &Path,+ profile: String,+ origin: String,+ id: String,+ parent_origin: String,+) -> Option<Frontend> {+ let root = frontend_root(core)?;+ let index = std::fs::read_to_string(root.join("index.html")).ok()?;+ let script =+ regex::Regex::new(r#"<script type="module" crossorigin src="([^"<>]+)"></script>"#).ok()?;+ let entry = script+ .captures(&index)?+ .get(1)?+ .as_str()+ .trim_start_matches('.');+ let source = std::fs::read_to_string(asset_path(&root, entry)?).ok()?;+ if !source.contains("await globalThis.__DSH_BOOT_READY__?.promise")+ || index.matches("<head>").count() != 1+ || index.contains("__DSH_BOOT_READY__")+ {+ return None;+ }+ let metadata =+ serde_json::json!({ "id": id, "parentOrigin": parent_origin, "template": index });+ let metadata = metadata.to_string().replace('<', "\\u003c");+ let injected = index.replacen(+ "<head>",+ &format!("<head><script>(()=>{{const preload={metadata};{GATE_SCRIPT}}})()</script>"),+ 1,+ );+ Some(Frontend {+ profile,+ origin,+ id,+ root,+ index: injected.into_bytes(),+ })+}++#[tauri::command]+pub async fn prepare_frontend_preload(+ window: WebviewWindow<Wry>,+ app_handle: AppHandle,+) -> Result<Option<String>, String> {+ let slot = windows()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .get(window.label())+ .cloned();+ let Some(slot) = slot else { return Ok(None) };+ let generation = {+ let mut state = slot.lock().unwrap_or_else(|error| error.into_inner());+ state.generation += 1;+ state.frontend = None;+ state.serving = false;+ state.generation+ };+ let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());+ let port = crate::service::workflow::instances::scope_sync(profile.clone(), || {+ crate::service::workflow::instances::port(&app_handle)+ });+ let origin = crate::config::get_dsh_service_url(port);+ let core = crate::service::core::active_core_dir(&app_handle);+ let parent_origin = window+ .url()+ .map_err(|error| format!("FRONTEND_PRELOAD_URL: {error}"))?+ .origin()+ .ascii_serialization();+ let id = generation.to_string();+ let url = format!("{origin}/?dshDesktop&{PRELOAD_QUERY}={id}");+ let load_profile = profile.clone();+ let frontend = tauri::async_runtime::spawn_blocking(move || {+ load_frontend(&core, load_profile, origin, id, parent_origin)+ })+ .await+ .map_err(|error| format!("FRONTEND_PRELOAD_LOAD: {error}"))?;+ let current_profile =+ crate::service::workflow::instances::window_profile(&app_handle, window.label());+ let current_port =+ crate::service::workflow::instances::scope_sync(current_profile.clone(), || {+ crate::service::workflow::instances::port(&app_handle)+ });+ let mut state = slot.lock().unwrap_or_else(|error| error.into_inner());+ if state.generation != generation || profile != current_profile || port != current_port {+ return Ok(None);+ }+ if frontend.is_none() {+ log::warn!("FRONTEND_PRELOAD_UNSUPPORTED: active frontend is missing or has no boot gate");+ }+ state.frontend = frontend;+ Ok(state.frontend.as_ref().map(|_| url))+}++#[cfg(windows)]+pub fn install(+ platform: &tauri::webview::PlatformWebview,+ window: &WebviewWindow<Wry>,+) -> Result<(), String> {+ use webview2_com::{+ take_pwstr,+ Microsoft::Web::WebView2::Win32::{+ ICoreWebView2WebResourceResponse, ICoreWebView2_22,+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL, COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT,+ COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_DOCUMENT,+ },+ WebResourceRequestedEventHandler,+ };+ use windows_core::{Interface, HSTRING, PWSTR};++ let label = window.label().to_string();+ if windows()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .contains_key(&label)+ {+ return Ok(());+ }+ let slot = Arc::new(Mutex::new(WindowPreload::default()));+ let state_for_request = slot.clone();+ let parent = window.clone();+ let result = unsafe {+ (|| -> windows_core::Result<()> {+ let webview = platform.controller().CoreWebView2()?;+ let environment = platform.environment();+ let webview22 = webview.cast::<ICoreWebView2_22>()?;+ for (pattern, document_only) in RESOURCE_FILTERS {+ webview22.AddWebResourceRequestedFilterWithRequestSourceKinds(+ &HSTRING::from(pattern),+ if document_only {+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT+ } else {+ COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL+ },+ COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_DOCUMENT,+ )?;+ }+ let mut token = 0;+ webview.add_WebResourceRequested(+ &WebResourceRequestedEventHandler::create(Box::new(move |_, args| {+ let Some(args) = args else { return Ok(()) };+ let request = args.Request()?;+ let mut uri = PWSTR::null();+ request.Uri(&mut uri)?;+ let uri = take_pwstr(uri);+ let Ok(url) = Url::parse(&uri) else { return Ok(()) };+ let mut method = PWSTR::null();+ request.Method(&mut method)?;+ let method = take_pwstr(method);+ if !matches!(method.as_str(), "GET" | "HEAD") { return Ok(()) }+ let profile = crate::service::workflow::instances::window_profile(parent.app_handle(), parent.label());+ let port = crate::service::workflow::instances::scope_sync(profile.clone(), || {+ crate::service::workflow::instances::port(parent.app_handle())+ });+ let mut state = state_for_request.lock().unwrap_or_else(|error| error.into_inner());+ let Some(frontend) = state.frontend.as_ref() else { return Ok(()) };+ if profile != frontend.profile || url.origin().ascii_serialization() != frontend.origin || url.port_or_known_default() != Some(port) {+ return Ok(());+ }+ let index_request = matches!(url.path(), "/" | "/index.html");+ let body = if index_request {+ if !url.query_pairs().any(|(key, value)| key == PRELOAD_QUERY && value == frontend.id) {+ state.serving = false;+ return Ok(());+ }+ let body = frontend.index.clone();+ state.serving = true;+ Some((body, "text/html; charset=utf-8"))+ } else if state.serving {+ asset_path(&frontend.root, url.path())+ .and_then(|path| std::fs::read(&path).ok().map(|body| (body, content_type(&path))))+ } else { None };+ let Some((body, mime)) = body else { return Ok(()) };+ drop(state);+ let headers = HSTRING::from(format!("Content-Type: {mime}\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n"));+ let Ok(length) = u32::try_from(body.len()) else { return Ok(()) };+ let stream = if method == "HEAD" { std::ptr::null_mut() } else {+ windows_sys::Win32::UI::Shell::SHCreateMemStream(body.as_ptr(), length)+ };+ if stream.is_null() && method != "HEAD" && !body.is_empty() { return Ok(()) }+ let mut response = std::ptr::null_mut();+ let reason = HSTRING::from("OK");+ let status = (environment.vtable().CreateWebResourceResponse)(+ environment.as_raw(), stream, 200, windows_core::PCWSTR(reason.as_ptr()),+ windows_core::PCWSTR(headers.as_ptr()), &mut response,+ );+ if !stream.is_null() { drop(windows_core::IUnknown::from_raw(stream)); }+ status.ok()?;+ args.SetResponse(&ICoreWebView2WebResourceResponse::from_raw(response))?;+ Ok(())+ })),+ &mut token,+ )?;+ Ok(())+ })()+ };+ result.map_err(|error| format!("FRONTEND_PRELOAD_INSTALL: {error}"))?;+ windows()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .insert(label.clone(), slot);+ window.on_window_event(move |event| {+ if matches!(event, tauri::WindowEvent::Destroyed) {+ windows()+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .remove(&label);+ }+ });+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_static_subresources_reach_the_native_preload_handler() {+ assert_eq!(+ RESOURCE_FILTERS,+ [+ ("http://127.0.0.1:*/*", true),+ ("http://127.0.0.1:*/assets/*", false),+ ("http://127.0.0.1:*/manifest.webmanifest*", false),+ ("http://127.0.0.1:*/favicon.svg*", false),+ ("http://127.0.0.1:*/favicon-dark.svg*", false),+ ]+ );+ }++ #[test]+ fn static_paths_stay_inside_the_frontend_and_decode_once() {+ let directory = tempfile::tempdir().unwrap();+ let root = dunce::canonicalize(directory.path()).unwrap();+ std::fs::create_dir(root.join("assets")).unwrap();+ std::fs::write(root.join("assets/app.js"), b"ok").unwrap();+ assert_eq!(+ asset_path(&root, "/assets/%61pp.js"),+ Some(root.join("assets/app.js"))+ );+ for path in [+ "/assets/../app.js",+ "/assets/%2e%2e/app.js",+ "/assets/%252e%252e/app.js",+ "/assets/%zz",+ "/assets/%ff",+ "/assets/app.js:secret",+ "/assets/app.js.",+ "/assets/%5capp.js",+ "/plugins/client.js",+ ] {+ assert!(asset_path(&root, path).is_none(), "{path}");+ }+ }+}diff --git a/src-tauri/src/desktop/mod.rs b/src-tauri/src/desktop/mod.rsindex 374c99b3..f512b97b 100644--- a/src-tauri/src/desktop/mod.rs+++ b/src-tauri/src/desktop/mod.rs@@ -5,12 +5,15 @@ pub mod builder;pub mod compat;pub mod deep_link;pub mod frame_log;+pub(crate) mod frontend_preload;pub mod notification;pub mod paste;pub mod payload;pub mod pet;pub mod pet_mouse;pub mod plugin_boot;+#[cfg(all(windows, any(not(debug_assertions), test)))]+pub(crate) mod single_instance;pub mod startup;#[cfg(windows)]pub mod tauri_internals;diff --git a/src-tauri/src/desktop/single_instance.rs b/src-tauri/src/desktop/single_instance.rsnew file mode 100644index 00000000..5fd0d8cf--- /dev/null+++ b/src-tauri/src/desktop/single_instance.rs@@ -0,0 +1,650 @@+#![cfg(windows)]++use std::{+ ffi::c_void,+ os::windows::io::{FromRawHandle, OwnedHandle},+ ptr::{null, null_mut},+ sync::{mpsc, Arc, Mutex},+ thread::{self, JoinHandle},+ time::{Duration, Instant},+};+use tauri::{AppHandle, Manager};+use tauri_plugin_deep_link::DeepLink;+use windows_sys::Win32::{+ Foundation::{+ GetLastError, SetLastError, ERROR_ALREADY_EXISTS, HINSTANCE, HWND, LPARAM, LRESULT, WPARAM,+ },+ System::{LibraryLoader::GetModuleHandleW, Threading::CreateMutexW},+ UI::WindowsAndMessaging::{+ CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, FindWindowExW,+ GetClassLongW, GetMessageW, GetWindowLongPtrW, GetWindowLongW, GetWindowThreadProcessId,+ PostQuitMessage, SendMessageTimeoutW, SendMessageW, SetWindowLongPtrW, SetWindowLongW,+ UnregisterClassW, CREATESTRUCTW, GCL_CBWNDEXTRA, GWLP_USERDATA, MSG, SMTO_ABORTIFHUNG,+ SMTO_BLOCK, SMTO_ERRORONEXIT, WM_APP, WM_CLOSE, WM_COPYDATA, WM_NCCREATE, WM_NCDESTROY,+ WNDPROC, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_OVERLAPPED,+ },+};++const MESSAGE_TAG: usize = 1542;+const MAX_MESSAGE_BYTES: usize = 256 * 1024;+const SEND_TIMEOUT_MS: u32 = 5000;+const STOP_TARGET: u32 = WM_APP + 1;++// 直依赖未启用 Gdi/DataExchange;这里只声明协议所需的原生 ABI,不扩大 Cargo 特性。+#[repr(C)]+struct WindowClass {+ style: u32,+ procedure: WNDPROC,+ class_extra: i32,+ window_extra: i32,+ instance: HINSTANCE,+ icon: *mut c_void,+ cursor: *mut c_void,+ brush: *mut c_void,+ menu: *const u16,+ name: *const u16,+}++#[link(name = "user32")]+extern "system" {+ fn RegisterClassW(class: *const WindowClass) -> u16;+}++#[repr(C)]+struct CopyData {+ tag: usize,+ length: u32,+ data: *const c_void,+}++#[derive(Debug, PartialEq, Eq)]+struct Request {+ cwd: String,+ args: Vec<String>,+}++impl Request {+ fn parse(bytes: &[u8]) -> Option<Self> {+ let data = std::str::from_utf8(bytes.strip_suffix(&[0])?).ok()?;+ if data.contains('\0') {+ return None;+ }+ let (cwd, args) = data.split_once('|')?;+ Some(Self {+ cwd: cwd.into(),+ args: args.split('|').map(str::to_owned).collect(),+ })+ }++ fn send(&self, target: HWND) -> Result<(), String> {+ let data = format!("{}|{}\0", self.cwd, self.args.join("|"));+ if data.len() > MAX_MESSAGE_BYTES {+ return Err("SINGLE_INSTANCE_PAYLOAD_TOO_LARGE".into());+ }+ let copy = CopyData {+ tag: MESSAGE_TAG,+ length: data.len() as u32,+ data: data.as_ptr().cast(),+ };+ let mut accepted = 0;+ let sent = unsafe {+ SetLastError(0);+ SendMessageTimeoutW(+ target,+ WM_COPYDATA,+ 0,+ © as *const _ as _,+ SMTO_ABORTIFHUNG | SMTO_BLOCK | SMTO_ERRORONEXIT,+ SEND_TIMEOUT_MS,+ &mut accepted,+ )+ };+ if sent == 0 {+ return Err(win_error("SEND"));+ }+ if accepted == 0 {+ return Err("SINGLE_INSTANCE_REJECTED: target did not accept launch arguments".into());+ }+ Ok(())+ }+}++#[derive(Default)]+struct Inbox {+ app: Option<AppHandle>,+ pending: Vec<Request>,+}++fn dispatch(inbox: &Arc<Mutex<Inbox>>, app: &AppHandle) -> Result<(), String> {+ let inbox = Arc::clone(inbox);+ let handle = app.clone();+ app.run_on_main_thread(move || {+ let pending = std::mem::take(&mut inbox.lock().unwrap_or_else(|e| e.into_inner()).pending);+ for request in pending {+ if let Some(deep_link) = handle.try_state::<DeepLink<tauri::Wry>>() {+ deep_link.handle_cli_arguments(request.args.iter());+ }+ crate::utils::show_main_window(&handle);+ }+ })+ .map_err(|error| format!("SINGLE_INSTANCE_DISPATCH_FAILED: {error}"))+}++struct NativeWindow {+ hwnd: HWND,+ class: Vec<u16>,+ module: HINSTANCE,+ inbox: Option<Box<Arc<Mutex<Inbox>>>>,+}++impl NativeWindow {+ fn create(identifier: &str, inbox: &Arc<Mutex<Inbox>>) -> Result<Self, String> {+ let class = wide(&format!("{identifier}-sic"));+ let name = wide(&format!("{identifier}-siw"));+ let module = unsafe { GetModuleHandleW(null()) };+ if module.is_null() {+ return Err(win_error("MODULE"));+ }+ let definition = WindowClass {+ style: 0,+ procedure: Some(window_proc),+ class_extra: 0,+ window_extra: 4,+ instance: module,+ icon: null_mut(),+ cursor: null_mut(),+ brush: null_mut(),+ menu: null(),+ name: class.as_ptr(),+ };+ if unsafe { RegisterClassW(&definition) } == 0 {+ return Err(win_error("REGISTER_CLASS"));+ }+ let data = Box::new(Arc::clone(inbox));+ let userdata = (&*data as *const Arc<Mutex<Inbox>>).cast();+ let mut window = Self {+ hwnd: null_mut(),+ class,+ module,+ inbox: Some(data),+ };+ window.hwnd = unsafe {+ CreateWindowExW(+ WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW,+ window.class.as_ptr(),+ name.as_ptr(),+ WS_OVERLAPPED,+ 0,+ 0,+ 0,+ 0,+ null_mut(),+ null_mut(),+ module,+ userdata,+ )+ };+ if window.hwnd.is_null() {+ return Err(win_error("CREATE_WINDOW"));+ }+ Ok(window)+ }+}++impl Drop for NativeWindow {+ fn drop(&mut self) {+ unsafe {+ if !self.hwnd.is_null() && DestroyWindow(self.hwnd) == 0 {+ log::error!("{}", win_error("DESTROY_WINDOW"));+ // 销毁失败时窗口仍可能回调,不能提前释放它的 userdata。+ if let Some(data) = self.inbox.take() {+ let _ = Box::into_raw(data);+ }+ }+ if UnregisterClassW(self.class.as_ptr(), self.module) == 0 {+ log::error!("{}", win_error("UNREGISTER_CLASS"));+ }+ }+ }+}++unsafe extern "system" fn window_proc(+ hwnd: HWND,+ msg: u32,+ wparam: WPARAM,+ lparam: LPARAM,+) -> LRESULT {+ match msg {+ WM_NCCREATE => {+ let create = &*(lparam as *const CREATESTRUCTW);+ SetLastError(0);+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, create.lpCreateParams as _);+ if GetLastError() != 0 {+ return 0;+ }+ // 默认处理初始化窗口标题,旧协议依赖它按 class/title 查找。+ DefWindowProcW(hwnd, msg, wparam, lparam)+ }+ WM_COPYDATA => {+ if lparam == 0 {+ return 0;+ }+ let copy = &*(lparam as *const CopyData);+ let state = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *const Arc<Mutex<Inbox>>;+ if state.is_null()+ || copy.tag != MESSAGE_TAG+ || copy.data.is_null()+ || copy.length == 0+ || copy.length as usize > MAX_MESSAGE_BYTES+ {+ return 0;+ }+ let bytes = std::slice::from_raw_parts(copy.data.cast(), copy.length as usize);+ let Some(request) = Request::parse(bytes) else {+ return 0;+ };+ let inbox = &*state;+ let app = {+ let mut state = inbox.lock().unwrap_or_else(|e| e.into_inner());+ state.pending.push(request);+ state.app.clone()+ };+ if let Some(app) = app {+ if let Err(error) = dispatch(inbox, &app) {+ log::error!("{error}");+ return 0;+ }+ }+ 1+ }+ STOP_TARGET => {+ PostQuitMessage(0);+ 1+ }+ WM_CLOSE => 0,+ WM_NCDESTROY => {+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0);+ DefWindowProcW(hwnd, msg, wparam, lparam)+ }+ _ => DefWindowProcW(hwnd, msg, wparam, lparam),+ }+}++struct Target {+ hwnd: isize,+ thread: Option<JoinHandle<Result<(), String>>>,+ inbox: Arc<Mutex<Inbox>>,+}++impl Target {+ fn start(identifier: &str) -> Result<Self, String> {+ let inbox = Arc::new(Mutex::new(Inbox::default()));+ let receiver = Arc::clone(&inbox);+ let identifier = identifier.to_owned();+ let (ready, started) = mpsc::sync_channel(1);+ let thread = thread::Builder::new()+ .name("single-instance".into())+ .spawn(move || {+ let window = match NativeWindow::create(&identifier, &receiver) {+ Ok(window) => window,+ Err(error) => {+ let _ = ready.send(Err(error));+ return Ok(());+ }+ };+ if ready.send(Ok(window.hwnd as isize)).is_err() {+ return Ok(());+ }+ let mut message = MSG::default();+ loop {+ match unsafe { GetMessageW(&mut message, null_mut(), 0, 0) } {+ -1 => return Err(win_error("GET_MESSAGE")),+ 0 => return Ok(()),+ _ => unsafe {+ DispatchMessageW(&message);+ },+ }+ }+ })+ .map_err(|error| format!("SINGLE_INSTANCE_THREAD_FAILED: {error}"))?;+ let initialized = started+ .recv()+ .map_err(|error| format!("SINGLE_INSTANCE_START_FAILED: {error}"));+ match initialized {+ Ok(Ok(hwnd)) => Ok(Self {+ hwnd,+ thread: Some(thread),+ inbox,+ }),+ error => {+ let _ = thread.join();+ Err(match error {+ Ok(Err(error)) | Err(error) => error,+ _ => unreachable!(),+ })+ }+ }+ }++ fn stop(&mut self) -> Result<(), String> {+ if let Some(thread) = self.thread.take() {+ if !thread.is_finished() {+ unsafe { SendMessageW(self.hwnd as _, STOP_TARGET, 0, 0) };+ }+ thread+ .join()+ .map_err(|_| "SINGLE_INSTANCE_THREAD_PANICKED".to_owned())??;+ }+ Ok(())+ }+}++impl Drop for Target {+ fn drop(&mut self) {+ if let Err(error) = self.stop() {+ log::error!("{error}");+ }+ }+}++pub struct SingleInstance {+ target: Target,+ _mutex: OwnedHandle,+}++impl SingleInstance {+ pub fn attach(&self, app: &AppHandle) -> Result<(), String> {+ if crate::utils::shell_window(app).is_none()+ || app.try_state::<DeepLink<tauri::Wry>>().is_none()+ {+ return Err("SINGLE_INSTANCE_NOT_READY: attach after the main window and deep-link plugin are ready".into());+ }+ if self+ .target+ .thread+ .as_ref()+ .is_none_or(JoinHandle::is_finished)+ {+ return Err("SINGLE_INSTANCE_TARGET_STOPPED".into());+ }+ self.target+ .inbox+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .app = Some(app.clone());+ dispatch(&self.target.inbox, app)+ }+}++pub fn claim(identifier: &str) -> Result<Option<SingleInstance>, String> {+ if identifier.is_empty() || identifier.contains('\0') {+ return Err("SINGLE_INSTANCE_INVALID_IDENTIFIER".into());+ }+ // 先发布 target,旧插件在 CreateMutex 之后立即 FindWindow,反序会放过第二个 owner。+ let mut target = Target::start(identifier)?;+ let name = wide(&format!("{identifier}-sim"));+ // 旧协议只检查命名对象是否已存在,不等待 mutex;无需持有线程所有权。+ let mutex = unsafe { CreateMutexW(null(), 0, name.as_ptr()) };+ let existed = unsafe { GetLastError() } == ERROR_ALREADY_EXISTS;+ if mutex.is_null() {+ return Err(win_error("CREATE_MUTEX"));+ }+ let mutex = unsafe { OwnedHandle::from_raw_handle(mutex) };+ if !existed {+ unsafe {+ SetLastError(0);+ SetWindowLongW(target.hwnd as _, 0, 1);+ if GetLastError() != 0 {+ return Err(win_error("MARK_OWNER"));+ }+ }+ return Ok(Some(SingleInstance {+ target,+ _mutex: mutex,+ }));+ }+ let deadline = Instant::now() + Duration::from_secs(5);+ let owner = loop {+ if let Some(owner) = find_owner(identifier, std::process::id())? {+ break owner;+ }+ if Instant::now() >= deadline {+ return Err(+ "SINGLE_INSTANCE_TARGET_MISSING: existing mutex has no ready target".into(),+ );+ }+ thread::sleep(Duration::from_millis(10));+ };+ target.stop()?;+ let cwd =+ std::env::current_dir().map_err(|error| format!("SINGLE_INSTANCE_CWD_FAILED: {error}"))?;+ let cwd = cwd+ .into_os_string()+ .into_string()+ .map_err(|_| "SINGLE_INSTANCE_INVALID_CWD".to_owned())?;+ let args = std::env::args_os()+ .map(|arg| {+ arg.into_string()+ .map_err(|_| "SINGLE_INSTANCE_INVALID_ARGUMENT".to_owned())+ })+ .collect::<Result<Vec<_>, _>>()?;+ Request { cwd, args }.send(owner)?;+ for request in std::mem::take(+ &mut target+ .inbox+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .pending,+ ) {+ request.send(owner)?;+ }+ Ok(None)+}++fn find_owner(identifier: &str, excluded_pid: u32) -> Result<Option<HWND>, String> {+ let class = wide(&format!("{identifier}-sic"));+ let name = wide(&format!("{identifier}-siw"));+ let mut previous = null_mut();+ loop {+ unsafe { SetLastError(0) };+ let window = unsafe { FindWindowExW(null_mut(), previous, class.as_ptr(), name.as_ptr()) };+ if window.is_null() {+ return if unsafe { GetLastError() } == 0 {+ Ok(None)+ } else {+ Err(win_error("FIND_TARGET"))+ };+ }+ previous = window;+ let mut pid = 0;+ if unsafe { GetWindowThreadProcessId(window, &mut pid) } == 0 {+ return Err(win_error("TARGET_PID"));+ }+ if pid == excluded_pid {+ continue;+ }+ unsafe {+ SetLastError(0);+ let extra = GetClassLongW(window, GCL_CBWNDEXTRA);+ if GetLastError() != 0 {+ return Err(win_error("TARGET_CLASS"));+ }+ // 新 target 的 slot 0 未置位时仍在选举;不能转给另一个 follower,旧插件没有 extra。+ if extra >= 4 {+ SetLastError(0);+ let owner = GetWindowLongW(window, 0);+ if GetLastError() != 0 {+ return Err(win_error("TARGET_OWNER"));+ }+ if owner != 1 {+ continue;+ }+ }+ }+ return Ok(Some(window));+ }+}++fn wide(value: &str) -> Vec<u16> {+ value.encode_utf16().chain(Some(0)).collect()+}++fn win_error(operation: &str) -> String {+ format!(+ "SINGLE_INSTANCE_{operation}_FAILED: {}",+ std::io::Error::last_os_error()+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn legacy_utf8_payload_preserves_cli_arguments_and_rejects_malformed_data() {+ assert_eq!(+ Request::parse("C:\\工作|app.exe|--cli||dsh://open\0".as_bytes()),+ Some(Request {+ cwd: "C:\\工作".into(),+ args: vec![+ "app.exe".into(),+ "--cli".into(),+ "".into(),+ "dsh://open".into()+ ],+ })+ );+ for bytes in [+ b"cwd|app".as_slice(),+ b"cwd\0",+ b"cwd|app\0extra\0",+ b"cwd|\xff\0",+ ] {+ assert_eq!(Request::parse(bytes), None);+ }+ }++ #[test]+ fn real_copydata_queues_before_attach_and_target_is_released() {+ let identifier = format!(+ "single-instance-check-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ );+ let mut target = Target::start(&identifier).unwrap();+ let mut title = [0u16; 256];+ let length = unsafe {+ windows_sys::Win32::UI::WindowsAndMessaging::GetWindowTextW(+ target.hwnd as _,+ title.as_mut_ptr(),+ title.len() as i32,+ )+ };+ assert_eq!(+ String::from_utf16(&title[..length as usize]).unwrap(),+ format!("{identifier}-siw")+ );+ let class = wide(&format!("{identifier}-sic"));+ let name = wide(&format!("{identifier}-siw"));+ assert_eq!(+ unsafe {+ windows_sys::Win32::UI::WindowsAndMessaging::FindWindowW(+ class.as_ptr(),+ name.as_ptr(),+ )+ },+ target.hwnd as HWND+ );+ assert!(find_owner(&identifier, 0).unwrap().is_none());+ unsafe { SetWindowLongW(target.hwnd as _, 0, 1) };+ assert_eq!(+ find_owner(&identifier, 0).unwrap(),+ Some(target.hwnd as HWND)+ );+ assert!(find_owner(&identifier, std::process::id())+ .unwrap()+ .is_none());+ Request {+ cwd: "C:\\独立测试".into(),+ args: vec!["app.exe".into(), "dsh://open".into()],+ }+ .send(target.hwnd as _)+ .unwrap();+ assert_eq!(+ target.inbox.lock().unwrap().pending,+ vec![Request {+ cwd: "C:\\独立测试".into(),+ args: vec!["app.exe".into(), "dsh://open".into()],+ }]+ );+ target.stop().unwrap();+ assert!(+ unsafe { FindWindowExW(null_mut(), null_mut(), class.as_ptr(), name.as_ptr()) }+ .is_null()+ );+ Target::start(&identifier).unwrap().stop().unwrap();+ }++ #[test]+ fn worker_lease_keeps_real_mutex_and_target_until_completion() {+ use windows_sys::Win32::UI::WindowsAndMessaging::FindWindowW;++ fn assert_send_sync<T: Send + Sync>() {}+ assert_send_sync::<SingleInstance>();++ let identifier = format!(+ "single-instance-lease-check-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ );+ let main_lease = Arc::new(+ claim(&identifier)+ .unwrap()+ .expect("independent identifier must be owner"),+ );+ let hwnd = main_lease.target.hwnd as HWND;+ let worker_lease = Arc::clone(&main_lease);+ let (release, waiting) = mpsc::channel::<()>();+ let worker = thread::spawn(move || {+ let _single_instance = worker_lease;+ waiting.recv().expect("release the worker lease");+ });+ drop(main_lease);++ let mutex_name = wide(&format!("{identifier}-sim"));+ let class = wide(&format!("{identifier}-sic"));+ let name = wide(&format!("{identifier}-siw"));+ {+ let raw = unsafe { CreateMutexW(null(), 0, mutex_name.as_ptr()) };+ let error = unsafe { GetLastError() };+ assert!(+ !raw.is_null(),+ "{}",+ std::io::Error::from_raw_os_error(error as i32)+ );+ let _probe = unsafe { OwnedHandle::from_raw_handle(raw) };+ assert_eq!(error, ERROR_ALREADY_EXISTS);+ assert_eq!(unsafe { FindWindowW(class.as_ptr(), name.as_ptr()) }, hwnd);+ assert_eq!(find_owner(&identifier, 0).unwrap(), Some(hwnd));+ }++ release.send(()).unwrap();+ worker.join().unwrap();+ let raw = unsafe { CreateMutexW(null(), 0, mutex_name.as_ptr()) };+ let error = unsafe { GetLastError() };+ assert!(+ !raw.is_null(),+ "{}",+ std::io::Error::from_raw_os_error(error as i32)+ );+ let _probe = unsafe { OwnedHandle::from_raw_handle(raw) };+ assert_eq!(error, 0, "the worker must release the last mutex handle");+ assert!(unsafe { FindWindowW(class.as_ptr(), name.as_ptr()) }.is_null());+ }+}diff --git a/src-tauri/src/desktop/window.rs b/src-tauri/src/desktop/window.rsindex 1ef7a50a..3f1804da 100644--- a/src-tauri/src/desktop/window.rs+++ b/src-tauri/src/desktop/window.rs@@ -104,6 +104,9 @@ pub fn on_page_load(let parent = webview_window.clone();if let Err(e) = webview_window.with_webview(move |platform| {disable_external_drop(&platform);+ if let Err(error) = crate::desktop::frontend_preload::install(&platform, &parent) {+ log::warn!("FRONTEND_PRELOAD_UNAVAILABLE: {error}");+ }if let Err(e) =crate::desktop::notification::enable_notification_permissions(platform, parent){diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 1aaf5d5a..ffd45d85 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -19,6 +19,7 @@ pub fn patch_core_dir(core_dir: &std::path::Path) -> Result<(), String> {/// 应用入口:先做 Wayland 环境兼容,再初始化日志、装配桌面端并进入事件循环。pub fn run() -> Result<(), String> {+ let started = std::time::Instant::now();desktop::startup::verify()?;// Wayland EGL workaround:仅 AppImage 需要(见 `should_apply_wayland_egl_workaround`)。if should_apply_wayland_egl_workaround(@@ -58,15 +59,42 @@ pub fn run() -> Result<(), String> {}// 初始化日志系统logger::init();+ log::info!(+ "STARTUP_BOOT: name=logger_ready elapsed_ms={}",+ started.elapsed().as_millis()+ );// Unix:把持久化的 DSH_HOME 补回进程环境(issue #871)。必须在桌面端装配之前,// 否则首次 get_dsh_data_path 会落到默认目录,日志、store 与 shim 全部写错位置。service::data_dir::restore_process_env();+ let context = tauri::generate_context!();+ log::info!(+ "STARTUP_BOOT: name=context_ready elapsed_ms={}",+ started.elapsed().as_millis()+ );+ #[cfg(all(windows, not(debug_assertions)))]+ let single_instance = match desktop::single_instance::claim(&context.config().identifier)? {+ Some(instance) => std::sync::Arc::new(instance),+ None => return Ok(()),+ };+ let startup = service::workflow::early::Startup::begin(+ &context,+ #[cfg(all(windows, not(debug_assertions)))]+ single_instance.clone(),+ );desktop::builder().invoke_handler(desktop::handler())- .build(tauri::generate_context!())+ .build(context).map_err(|error| format!("STARTUP_FAILED: {error}"))?- .run(|app_handle, event| match event {+ .run(move |app_handle, event| match event {+ tauri::RunEvent::Ready => {+ startup.attach(app_handle);+ #[cfg(all(windows, not(debug_assertions)))]+ if let Err(error) = single_instance.attach(app_handle) {+ log::error!("SINGLE_INSTANCE_ATTACH_FAILED: {error}");+ app_handle.exit(1);+ }+ }#[cfg(target_os = "macos")]tauri::RunEvent::WindowEvent { event, .. } => {desktop::builder::on_macos_titlebar_event(&event);@@ -93,6 +121,7 @@ pub fn run() -> Result<(), String> {// 残留并把原生模块 DLL(如 sharp 的 libvips-42.dll)锁在内存,// 下次启动重新解压时会失败(Windows os error 32)tauri::RunEvent::Exit => {+ startup.shutdown();// 进行中的插件安装子进程是独立进程组,父进程退出不会连带回收;// 不显式结束就会留下占着档案 / pnpm store 的孤儿,让下一次启动// 永久卡在安装阶段(且日志无任何输出)。必须先于其它收尾动作。diff --git a/src-tauri/src/service/cli/mod.rs b/src-tauri/src/service/cli/mod.rsindex 3ef49c61..0556890c 100644--- a/src-tauri/src/service/cli/mod.rs+++ b/src-tauri/src/service/cli/mod.rs@@ -28,11 +28,12 @@ mod shim;pub use core::{ensure, ensure_shims, get_status, remove, CliLinkStatus};// 数据目录(issue #871)在 Unix 上复用同一套「标记块 + 备份写回」原语,// 免得再抄一份 rc 文件读写的实现。-#[cfg(unix)]-pub(crate) use path::{strip_rc_block, upsert_rc_block, write_rc_with_backup};#[cfg(windows)]pub(crate) use path::find_user_pnpm_executable;#[cfg(windows)]pub(crate) use path::{delete_user_env, notify_environment_change, read_user_env, write_user_env};pub use path::{find_user_pnpm, get_bin_dir, pnpm_env_value};+pub(crate) use path::{find_user_pnpm_from, get_bin_dir_from};+#[cfg(unix)]+pub(crate) use path::{strip_rc_block, upsert_rc_block, write_rc_with_backup};pub use shim::is_generated_shim;diff --git a/src-tauri/src/service/cli/path/mod.rs b/src-tauri/src/service/cli/path/mod.rsindex e7e80a64..b0041464 100644--- a/src-tauri/src/service/cli/path/mod.rs+++ b/src-tauri/src/service/cli/path/mod.rs@@ -9,7 +9,7 @@#[cfg(not(windows))]use std::fs;-use std::path::PathBuf;+use std::path::{Path, PathBuf};use tauri::{AppHandle, Manager};#[cfg(windows)]@@ -37,9 +37,10 @@ pub(crate) use registry::{};// 数据目录(issue #871)在 Unix 上复用 rc 的「标记块 + 备份写回」原语,// 免得再抄一份 rc 文件读写实现。rc 模块本身是私有的,跨模块用要在这里再导出。+pub(crate) use pnpm::find_user_pnpm_from;+pub use pnpm::{find_user_pnpm, pnpm_env_value};#[cfg(unix)]pub(crate) use rc::{strip_rc_block, upsert_rc_block, write_rc_with_backup};-pub use pnpm::{find_user_pnpm, pnpm_env_value};/// Windows 下 shim 根目录名(`%LOCALAPPDATA%\<此目录>\bin`)#[cfg_attr(not(windows), allow(dead_code))] // 仅 Windows 的 bin 目录计算使用@@ -57,16 +58,32 @@ const UNIX_BIN_DIR: &str = ".local/bin";/// - Windows:`%LOCALAPPDATA%\deepseek-harness\bin`(用户级、不随应用数据目录变动)/// - Unix:`~/.local/bin`(XDG 约定,通常已在 PATH 中)pub fn get_bin_dir(app_handle: &AppHandle) -> PathBuf {+ #[cfg(windows)]+ {+ let local_data_dir = std::env::var_os("LOCALAPPDATA")+ .is_none()+ .then(|| app_handle.path().local_data_dir().ok())+ .flatten();+ get_bin_dir_from(local_data_dir.as_deref(), None)+ }+ #[cfg(not(windows))]+ {+ get_bin_dir_from(None, app_handle.path().home_dir().ok().as_deref())+ }+}++pub(crate) fn get_bin_dir_from(+ _local_data_dir: Option<&Path>,+ _home_dir: Option<&Path>,+) -> PathBuf {#[cfg(windows)]{std::env::var_os("LOCALAPPDATA").map(PathBuf::from).or_else(|| {- app_handle- .path()- .local_data_dir()- .ok()- .and_then(|d| d.parent().map(|p| p.to_path_buf()))+ _local_data_dir+ .and_then(Path::parent)+ .map(Path::to_path_buf)}).unwrap_or_else(std::env::temp_dir).join(if cfg!(debug_assertions) {@@ -78,10 +95,7 @@ pub fn get_bin_dir(app_handle: &AppHandle) -> PathBuf {}#[cfg(not(windows))]{- let home = app_handle- .path()- .home_dir()- .unwrap_or_else(|_| PathBuf::from("."));+ let home = _home_dir.unwrap_or_else(|| Path::new("."));if cfg!(debug_assertions) {home.join(".local/bin/dev")} else {@@ -199,6 +213,51 @@ pub fn unregister_path(app_handle: &AppHandle) -> Result<(), String> {Ok(())}+#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn bin_directory_preserves_platform_inputs_and_build_split() {+ #[cfg(windows)]+ {+ let local_data = Path::new("local").join("application");+ let root = std::env::var_os("LOCALAPPDATA")+ .map(PathBuf::from)+ .unwrap_or_else(|| PathBuf::from("local"));+ let name = if cfg!(debug_assertions) {+ CLI_ROOT_DEV_DIR_NAME+ } else {+ CLI_ROOT_DIR_NAME+ };+ assert_eq!(+ get_bin_dir_from(Some(&local_data), Some(Path::new("unused"))),+ root.join(name).join("bin")+ );+ let fallback = std::env::var_os("LOCALAPPDATA")+ .map(PathBuf::from)+ .unwrap_or_else(std::env::temp_dir);+ assert_eq!(+ get_bin_dir_from(None, None),+ fallback.join(name).join("bin")+ );+ }+ #[cfg(not(windows))]+ {+ let suffix = if cfg!(debug_assertions) {+ ".local/bin/dev"+ } else {+ ".local/bin"+ };+ assert_eq!(+ get_bin_dir_from(Some(Path::new("unused")), Some(Path::new("home"))),+ Path::new("home").join(suffix)+ );+ assert_eq!(get_bin_dir_from(None, None), Path::new(".").join(suffix));+ }+ }+}+#[cfg(test)]mod test_util {use std::path::Path;diff --git a/src-tauri/src/service/cli/path/pnpm.rs b/src-tauri/src/service/cli/path/pnpm.rsindex b2238f38..cbfe05f1 100644--- a/src-tauri/src/service/cli/path/pnpm.rs+++ b/src-tauri/src/service/cli/path/pnpm.rs@@ -15,19 +15,26 @@ use super::get_bin_dir;/// 捆绑安装;Unix GUI 额外检查 mise 标准数据目录,生成的 `pnpm` shim 也会/// 优先转发到探测出的精确路径。pub fn find_user_pnpm(app_handle: &AppHandle) -> Option<PathBuf> {- let dirs = user_pnpm_dirs(app_handle);- find_pnpm_in_dirs(&get_bin_dir(app_handle), &dirs)+ #[cfg(unix)]+ let home = app_handle.path().home_dir().ok();+ #[cfg(not(unix))]+ let home: Option<PathBuf> = None;+ find_user_pnpm_from(&get_bin_dir(app_handle), home.as_deref())+}++pub(crate) fn find_user_pnpm_from(bin_dir: &Path, home_dir: Option<&Path>) -> Option<PathBuf> {+ find_pnpm_in_dirs(bin_dir, &user_pnpm_dirs(home_dir))}/// Windows 直接创建进程时不能执行 `.cmd`/`.bat`;为无需 shell 的修复流程单独/// 查找原生 `pnpm.exe`,不改变常规 shim 对 `.cmd` 的既有优先级。#[cfg(windows)]pub(crate) fn find_user_pnpm_executable(app_handle: &AppHandle) -> Option<PathBuf> {- let dirs = user_pnpm_dirs(app_handle);+ let dirs = user_pnpm_dirs(None);find_windows_executable_pnpm_in_dirs(&get_bin_dir(app_handle), &dirs)}-fn user_pnpm_dirs(_app_handle: &AppHandle) -> Vec<PathBuf> {+fn user_pnpm_dirs(_home_dir: Option<&Path>) -> Vec<PathBuf> {let mut dirs: Vec<PathBuf> =std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()).collect();#[cfg(windows)]@@ -36,12 +43,11 @@ fn user_pnpm_dirs(_app_handle: &AppHandle) -> Vec<PathBuf> {{let mise_data = std::env::var_os("MISE_DATA_DIR").map(PathBuf::from);let xdg_data = std::env::var_os("XDG_DATA_HOME").map(PathBuf::from);- let home = _app_handle.path().home_dir().ok();append_unix_mise_dirs(&mut dirs,mise_data.as_deref(),xdg_data.as_deref(),- home.as_deref(),+ _home_dir,);}dirsdiff --git a/src-tauri/src/service/cli/shim/build.rs b/src-tauri/src/service/cli/shim/build.rsindex 7d04c44c..a8e27101 100644--- a/src-tauri/src/service/cli/shim/build.rs+++ b/src-tauri/src/service/cli/shim/build.rs@@ -1037,6 +1037,11 @@ mod tests {node: &Path,path: &std::ffi::OsStr,) -> std::process::Output {+ std::fs::write(+ shim.parent().unwrap().join("git.cmd"),+ "@echo off\r\nexit /b 1\r\n",+ )+ .unwrap();let system_root = std::env::var_os("SystemRoot").unwrap();let system32 = PathBuf::from(system_root).join("System32");let mut command = if shim.extension().unwrap() == "ps1" {diff --git a/src-tauri/src/service/core/mod.rs b/src-tauri/src/service/core/mod.rsindex 1a65b771..2106c822 100644--- a/src-tauri/src/service/core/mod.rs+++ b/src-tauri/src/service/core/mod.rs@@ -28,12 +28,15 @@ mod version;pub use local::{local_core_package_dir, update_local_core};// 以下重导出为对外公开 API(部分项当前链路未直接引用,属有意保留,见模块头)。+pub(crate) use runtime::{+ prepare_active_runtime, prepare_active_runtime_at, RuntimePreparation, RuntimePreparationPaths,+ RuntimeRequiredPlugin,+};#[allow(unused_imports)]pub use source::{active_core_dir, active_dsh_binary, active_source, active_version, CoreSource, HarnessCore,};pub use version::{download_version, has_installed_version, list, remove_version, set_active};-pub(crate) use runtime::prepare_active_runtime;// 目录链接实现(Windows 符号链接 → 无特权时的 junction 回退)供插件模块复用:// pnpm 建链后回读失败时,桌面端自行落盘内置插件入口(见 plugin::internal::materialize)。pub(crate) use runtime::create_directory_link;diff --git a/src-tauri/src/service/core/runtime.rs b/src-tauri/src/service/core/runtime.rsindex d43f4931..5b941cde 100644--- a/src-tauri/src/service/core/runtime.rs+++ b/src-tauri/src/service/core/runtime.rs@@ -208,55 +208,118 @@ impl NativeProbe {}}-/// 在启动预打包核心前修复其插件入口并验证原生依赖(含 Node ABI 兼容性)。-///-/// 该函数是幂等的:已有正确链接和可加载的原生模块不会触发写入或联网。原生包-/// 缺失时只按核心清单中的 optionalDependencies 动态构造安装参数,避免把某一台-/// 机器的版本、平台或架构写死在桌面端。失败返回诊断错误,调用方不应继续启动-/// 一个已知无法加载的 dsh 进程。-pub(crate) async fn prepare_active_runtime(app_handle: &AppHandle) -> Result<(), String> {- if crate::service::core::active_source(app_handle) != CoreSource::App {- log::debug!("Skipping core runtime repair for user-owned local core");- return Ok(());- }+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum RuntimePreparation {+ Ready,+ Defer,+}- let core_root = crate::config::get_dsh_install_path(app_handle);- let node = crate::config::get_node_binary_path(app_handle);- if !core_root.is_dir() {+pub(crate) struct RuntimeRequiredPlugin<'a> {+ pub name: &'a str,+ pub source: Option<PathBuf>,+ pub version: Option<&'a crate::config::manifest::PluginVersion>,+}++pub(crate) struct RuntimePreparationPaths<'a> {+ pub source: CoreSource,+ pub base: &'a Path,+ pub core_root: &'a Path,+ pub node: &'a Path,+ pub profile: &'a Path,+ pub profiles: &'a Path,+ pub resources: Option<&'a Path>,+ pub core_version: Option<&'a str>,+ pub required_plugins: Option<&'a [RuntimeRequiredPlugin<'a>]>,+}++pub(crate) fn prepare_active_runtime_at(+ paths: &RuntimePreparationPaths<'_>,+) -> Result<RuntimePreparation, String> {+ if paths.source != CoreSource::App {+ return Ok(RuntimePreparation::Defer);+ }+ if !paths.core_root.is_dir() {return Err(format!("CORE_RUNTIME_NOT_FOUND: bundled core directory is missing: {}",- core_root.display()+ paths.core_root.display()));}- if !node.is_file() {+ if !paths.node.is_file() {return Err(format!("CORE_RUNTIME_NODE_NOT_FOUND: Node.js runtime is missing: {}",- node.display()+ paths.node.display()));}-- link_required_plugins(app_handle, &core_root)?;-- // 档案里的核心包残留必须在 dsh 启动前清掉:Node 从 profile 目录向上查找裸包时- // 会先命中它,核心自带的正确版本反而被跳过。清理失败不影响后续原生探测。- if let Err(e) = prune_stale_core_packages(app_handle, &core_root) {- log::warn!("{e}");+ let linked = link_required_plugins_at(paths)?;+ let pruned = match prune_stale_core_packages_at(paths.profile, paths.core_root) {+ Ok(ready) => ready,+ Err(error) => {+ log::warn!("{error}");+ false+ }+ };+ if !linked || !pruned || paths.core_version.is_none_or(str::is_empty) {+ return Ok(RuntimePreparation::Defer);}-- // 已核验过的运行时直接放行:跳过平台/架构探测与原生模块探测两个 node 子进程- // (issue #766)。指纹失配、戳缺失或不可解析时一律走原探测路径;指纹本身不完整- // (`None`)时既不比对也不落盘。- let stamp_key = native_probe_stamp_key(app_handle, &node, &core_root);- if let Some(key) = stamp_key.as_deref() {- if let Some((stored, platform, arch)) = read_native_probe_stamp(app_handle) {+ let key = native_probe_stamp_key_at(paths.node, paths.core_root, paths.core_version);+ if let Some(key) = key.as_deref() {+ if let Some((stored, platform, arch)) = read_native_probe_stamp_at(paths.base) {if stored == key {log::debug!("Bundled core native dependencies are ready for {platform}:{arch} (cached)");- return Ok(());+ return Ok(RuntimePreparation::Ready);}}}+ Ok(RuntimePreparation::Defer)+}++/// 在启动预打包核心前修复其插件入口并验证原生依赖(含 Node ABI 兼容性)。+///+/// 该函数是幂等的:已有正确链接和可加载的原生模块不会触发写入或联网。原生包+/// 缺失时只按核心清单中的 optionalDependencies 动态构造安装参数,避免把某一台+/// 机器的版本、平台或架构写死在桌面端。失败返回诊断错误,调用方不应继续启动+/// 一个已知无法加载的 dsh 进程。+pub(crate) async fn prepare_active_runtime(app_handle: &AppHandle) -> Result<(), String> {+ if crate::service::core::active_source(app_handle) != CoreSource::App {+ log::debug!("Skipping core runtime repair for user-owned local core");+ return Ok(());+ }++ let core_root = crate::config::get_dsh_install_path(app_handle);+ let node = crate::config::get_node_binary_path(app_handle);+ let base = crate::config::get_base_dir(app_handle);+ let profile = crate::service::plugin::profile_dir(app_handle);+ let profiles = crate::config::get_dsh_data_path(app_handle).join("profiles");+ let resources = crate::config::manifest::resource_root(app_handle);+ let core_version = crate::service::core::active_version(app_handle);+ let presets = crate::service::plugin::load_presets(app_handle);+ let required_plugins: Vec<_> = presets+ .iter()+ .filter(|preset| preset.internal)+ .map(|preset| RuntimeRequiredPlugin {+ name: crate::service::plugin::installed_name(preset),+ source: crate::service::plugin::bundled_plugin_dir(app_handle, &preset.id),+ version: preset.version.as_ref(),+ })+ .collect();+ let manifest_known = crate::config::manifest::with_manifest(app_handle, |_| ()).is_some();+ let paths = RuntimePreparationPaths {+ source: CoreSource::App,+ base: &base,+ core_root: &core_root,+ node: &node,+ profile: &profile,+ profiles: &profiles,+ resources: resources.as_deref(),+ core_version: core_version.as_deref(),+ required_plugins: manifest_known.then_some(required_plugins.as_slice()),+ };+ if prepare_active_runtime_at(&paths)? == RuntimePreparation::Ready {+ return Ok(());+ }+ let stamp_key = native_probe_stamp_key_at(&node, &core_root, core_version.as_deref());let target = detect_node_target(&node, &core_root).await?;let mut probe = probe_native_modules(&node, &core_root).await;@@ -267,7 +330,7 @@ pub(crate) async fn prepare_active_runtime(app_handle: &AppHandle) -> Result<(),target.arch);if let Some(key) = stamp_key.as_deref() {- write_native_probe_stamp(app_handle, key, &target);+ write_native_probe_stamp_at(&base, key, &target);}return Ok(());}@@ -369,16 +432,24 @@ pub(crate) async fn prepare_active_runtime(app_handle: &AppHandle) -> Result<(),/// 既有清理(上游 `removeLinkProjections` 与桌面端 `remove_legacy_profile_module_fallback`)/// 都只认符号链接、且要求 `.dsh-module-fallback` 源目录仍然存在;用户「无视风险切换」/// 升级核心时档案不重建,残留因此在 Node 的逐级查找里长期抢先命中,症状与病因脱钩。-fn prune_stale_core_packages(app_handle: &AppHandle, core_root: &Path) -> Result<(), String> {- let profile = crate::service::plugin::profile_dir(app_handle);- let Some(declared) = crate::service::plugin::declared_packages(app_handle) else {+fn prune_stale_core_packages_at(profile: &Path, core_root: &Path) -> Result<bool, String> {+ let declared = std::fs::read_to_string(profile.join("package.json"))+ .ok()+ .and_then(|raw| {+ serde_json::from_str::<crate::service::plugin::ProfilePackageJson>(&raw).ok()+ });+ let Some(manifest) = declared else {log::warn!("CORE_PLUGIN_STALE_CORE_DECLARED_UNKNOWN: {} is unreadable, skipping cleanup",profile.display());- return Ok(());+ return Ok(false);};- prune_stale_core_entries(&profile, &core_root.join("node_modules"), &declared)+ let mut declared: HashSet<_> = manifest.dependencies.into_keys().collect();+ if let Some(profile) = manifest.dsh.and_then(|dsh| dsh.profile) {+ declared.extend(profile.bundles);+ }+ prune_stale_core_entries(profile, &core_root.join("node_modules"), &declared)}/// 逐个比对档案与锚点的同名核心包版本,清除版本错配且档案未声明的条目。@@ -386,15 +457,21 @@ fn prune_stale_core_entries(profile_root: &Path,anchor_node_modules: &Path,declared: &HashSet<String>,-) -> Result<(), String> {+) -> Result<bool, String> {let profile_node_modules = profile_root.join("node_modules");let scope = profile_node_modules.join(CORE_PACKAGE_SCOPE);+ if std::fs::symlink_metadata(&scope)+ .is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound)+ {+ return Ok(true);+ }let Some(scope_root) = containment_root(&scope, profile_root) else {- return Ok(());+ return Ok(false);};+ let mut ready = true;let entries = match std::fs::read_dir(&scope) {Ok(entries) => entries,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(true),Err(e) => {return Err(format!("CORE_PLUGIN_STALE_CORE_SCAN_FAILED: {}: {e}",@@ -427,14 +504,17 @@ fn prune_stale_core_entries(path.display(),scope.display());+ ready = false;continue;}let Some(profile_version) = read_package_version(&path.join("package.json")) else {+ ready = false;continue;};let Some(anchor_version) =read_package_version(&anchor_node_modules.join(&name).join("package.json"))else {+ ready = false;continue;};if profile_version == anchor_version {@@ -442,13 +522,14 @@ fn prune_stale_core_entries(}if let Err(e) = remove_core_package_residue(&path) {log::warn!("{e}");+ ready = false;continue;}log::info!("CORE_PLUGIN_STALE_CORE_PRUNED: {name} {profile_version} (profile) != {anchor_version} (anchor), removed");}- Ok(())+ Ok(ready)}/// 解析 scope 的真实位置,并确认它既不是重定向入口、也仍留在档案目录内。@@ -534,8 +615,8 @@ fn remove_core_package_residue(path: &Path) -> Result<(), String> {}/// 共享核心只保留内置插件入口,并移除旧版投射的档案插件链接(issue #993)。-fn link_required_plugins(app_handle: &AppHandle, core_root: &Path) -> Result<(), String> {- let core_node_modules = core_root.join("node_modules");+fn link_required_plugins_at(paths: &RuntimePreparationPaths<'_>) -> Result<bool, String> {+ let core_node_modules = paths.core_root.join("node_modules");std::fs::create_dir_all(&core_node_modules).map_err(|e| {format!("CORE_PLUGIN_NODE_MODULES_CREATE_FAILED: {}: {e}",@@ -543,50 +624,54 @@ fn link_required_plugins(app_handle: &AppHandle, core_root: &Path) -> Result<(),)})?;- let presets = crate::service::plugin::load_presets(app_handle);- // 被核心吸收的内置插件(上限已被超越)不再链接到核心根:与启动退役、自愈的- // 判定同源,避免为已卸载插件留下悬空入口。- let core_version = crate::service::core::active_version(app_handle);- let internal: Vec<_> = presets+ let internal: Vec<_> = paths+ .required_plugins+ .unwrap_or_default().iter()- .filter(|preset| preset.internal && !preset.unsupported_on(core_version.as_deref()))+ .filter(|plugin| {+ !plugin+ .version+ .is_some_and(|version| version.unsupported_on(paths.core_version))+ }).collect();- let internal_ids: HashSet<String> = internal+ let internal_ids = internal.iter()- .map(|preset| crate::service::plugin::installed_name(preset).to_string())+ .map(|plugin| plugin.name.to_string()).collect();-- // 内置插件必须始终从当前安装包资源(debug 时为 workspace 源码)取源,不能信任- // profile 中旧版本遗留的 link 路径。这样应用升级后旧 link 会被精确替换。- for preset in internal {- let name = crate::service::plugin::installed_name(preset);- let Some(source) = crate::service::plugin::bundled_plugin_dir(app_handle, &preset.id)- else {+ let mut ready = paths.required_plugins.is_some();+ for plugin in internal {+ let source = plugin.source.as_deref().and_then(|source| {+ if source.is_absolute() {+ Some(source.to_path_buf())+ } else {+ paths.resources.map(|root| root.join(source))+ }+ });+ let Some(source) = source else {log::warn!(- "CORE_PLUGIN_BUNDLE_MISSING: bundled source unavailable for {name}, skipping core link"+ "CORE_PLUGIN_BUNDLE_MISSING: bundled source unavailable for {}, skipping core link",+ plugin.name);+ ready = false;continue;};- ensure_package_link(name, &source, &core_node_modules)?;+ ready &= ensure_package_link(plugin.name, &source, &core_node_modules)?;}- remove_profile_plugin_links(- &core_node_modules,- &crate::config::get_dsh_data_path(app_handle).join("profiles"),- &internal_ids,- )+ Ok(remove_profile_plugin_links(&core_node_modules, paths.profiles, &internal_ids)? && ready)}fn remove_profile_plugin_links(core_modules: &Path,profiles: &Path,internal_ids: &HashSet<String>,-) -> Result<(), String> {+) -> Result<bool, String> {let entries = match std::fs::read_dir(profiles) {Ok(entries) => entries,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(true),Err(error) => return Err(format!("CORE_PLUGIN_PROFILES_READ_FAILED: {error}")),};+ let mut ready = true;for entry in entries {let entry = entry.map_err(|error| format!("CORE_PLUGIN_PROFILE_READ_FAILED: {error}"))?;if !entry@@ -599,9 +684,11 @@ fn remove_profile_plugin_links(}let manifest_path = entry.path().join("package.json");let Ok(raw) = std::fs::read_to_string(&manifest_path) else {+ ready = false;continue;};let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&raw) else {+ ready = false;continue;};let mut names = HashSet::new();@@ -622,25 +709,38 @@ fn remove_profile_plugin_links(continue;}let destination = core_modules.join(name);- if !std::fs::symlink_metadata(&destination)- .is_ok_and(|metadata| metadata.file_type().is_symlink())- {+ let metadata = match std::fs::symlink_metadata(&destination) {+ Ok(metadata) => metadata,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,+ Err(_) => {+ ready = false;+ continue;+ }+ };+ let file_type = metadata.file_type();+ #[cfg(windows)]+ let is_link = file_type.is_symlink() || file_type.is_symlink_dir();+ #[cfg(not(windows))]+ let is_link = file_type.is_symlink();+ if !is_link {continue;}let source = entry.path().join("node_modules").join(name);- if let (Ok(source), Ok(target)) = (source.canonicalize(), destination.canonicalize()) {- if source == target {+ match (source.canonicalize(), destination.canonicalize()) {+ (Ok(source), Ok(target)) if source == target => {ensure_non_link_directory(destination.parent().unwrap(), core_modules)?;remove_link_only(&destination)?;}+ (Ok(_), Ok(_)) => {}+ _ => ready = false,}}}- Ok(())+ Ok(ready)}/// 为 npm 包名建立目录链接;真实目录/文件从不覆盖,避免误删核心自有依赖。-fn ensure_package_link(name: &str, source: &Path, node_modules: &Path) -> Result<(), String> {+fn ensure_package_link(name: &str, source: &Path, node_modules: &Path) -> Result<bool, String> {if !is_safe_package_name(name) {return Err(format!("CORE_PLUGIN_NAME_INVALID: {name}"));}@@ -680,12 +780,19 @@ fn ensure_package_link(name: &str, source: &Path, node_modules: &Path) -> Result}};if let Some(metadata) = existing {- if !metadata.file_type().is_symlink() {+ let file_type = metadata.file_type();+ #[cfg(windows)]+ let is_link = file_type.is_symlink() || file_type.is_symlink_dir();+ #[cfg(not(windows))]+ let is_link = file_type.is_symlink();+ if !is_link {log::debug!("CORE_PLUGIN_ENTRY_OCCUPIED: keeping core-owned entry {}",destination.display());- return Ok(());+ return Ok(file_type.is_dir()+ && read_package_name(&destination.join("package.json"))+ .is_ok_and(|package_name| package_name.as_deref() == Some(name)));}let matches = std::fs::read_link(&destination).ok()@@ -699,7 +806,7 @@ fn ensure_package_link(name: &str, source: &Path, node_modules: &Path) -> Result}).unwrap_or(false);if matches {- return Ok(());+ return Ok(true);}remove_link_only(&destination)?;}@@ -716,7 +823,7 @@ fn ensure_package_link(name: &str, source: &Path, node_modules: &Path) -> Resultdestination.display(),source.display());- Ok(())+ Ok(destination.canonicalize().ok().as_deref() == Some(source.as_path()))}/// 校验并创建 scope 目录;目录本身不能是链接,防止目的地逃逸核心根。@@ -732,7 +839,16 @@ fn ensure_non_link_directory(path: &Path, root: &Path) -> Result<(), String> {for component in relative.components() {current.push(component.as_os_str());match std::fs::symlink_metadata(¤t) {- Ok(metadata) if metadata.file_type().is_symlink() => {+ Ok(metadata)+ if {+ let file_type = metadata.file_type();+ #[cfg(windows)]+ let is_link = file_type.is_symlink() || file_type.is_symlink_dir();+ #[cfg(not(windows))]+ let is_link = file_type.is_symlink();+ is_link+ } =>+ {return Err(format!("CORE_PLUGIN_DESTINATION_PARENT_LINK: {}",current.display()@@ -827,7 +943,8 @@ fn create_directory_junction(source: &Path, destination: &Path) -> std::io::Resu// `\??\G:\...`,UNC 路径映射为 `\??\UNC\server\share\...`。// dunce::simplified 去掉 canonicalize 产生的 verbatim(`\\?\`)前缀,// 避免双重前缀导致内核解析失败。- let simplified = dunce::simplified(source);+ let source = source.canonicalize()?;+ let simplified = dunce::simplified(&source);let print_name = simplified.to_string_lossy().replace('/', "\\");let substitute_name = if print_name.starts_with("\\\\") {format!(r"\??\UNC\{}", print_name.trim_start_matches('\\'))@@ -1007,8 +1124,8 @@ fn read_package_version(path: &Path) -> Option<String> {}/// 结论戳文件路径:放在依赖根下。清空依赖目录(等价于重新装配)会一并清掉它。-fn native_probe_stamp_path(app_handle: &AppHandle) -> PathBuf {- crate::config::get_base_dir(app_handle).join(NATIVE_PROBE_STAMP_FILE)+fn native_probe_stamp_path_at(base: &Path) -> PathBuf {+ base.join(NATIVE_PROBE_STAMP_FILE)}/// 原生依赖探测的输入指纹:node 身份 + 核心目录与版本 + `node_modules` 前两层条目@@ -1020,7 +1137,11 @@ fn native_probe_stamp_path(app_handle: &AppHandle) -> PathBuf {////// 任何让指纹**不完整**的情况(目录读不到、条目数超过兜底上限)都返回 `None`:/// 不完整的指纹可能刚好和上次的完整指纹撞上,反而跳过一次本该做的探测。宁可不缓存。-fn native_probe_stamp_key(app_handle: &AppHandle, node: &Path, core_root: &Path) -> Option<String> {+fn native_probe_stamp_key_at(+ node: &Path,+ core_root: &Path,+ core_version: Option<&str>,+) -> Option<String> {use std::fmt::Write as _;let mut key = String::new();@@ -1033,7 +1154,7 @@ fn native_probe_stamp_key(app_handle: &AppHandle, node: &Path, core_root: &Path)key,"\ncore={}\nversion={}",core_root.display(),- crate::service::core::active_version(app_handle).unwrap_or_default()+ core_version.unwrap_or_default());let modules = probe_stamp_modules_digest(&core_root.join("node_modules"))?;@@ -1195,8 +1316,8 @@ fn file_modified_nanos(meta: &std::fs::Metadata) -> String {}/// 读取结论戳;文件缺失、不可解析或字段不全时返回 None(视为无戳)-fn read_native_probe_stamp(app_handle: &AppHandle) -> Option<(String, String, String)> {- let raw = std::fs::read_to_string(native_probe_stamp_path(app_handle)).ok()?;+fn read_native_probe_stamp_at(base: &Path) -> Option<(String, String, String)> {+ let raw = std::fs::read_to_string(native_probe_stamp_path_at(base)).ok()?;let value = serde_json::from_str::<serde_json::Value>(&raw).ok()?;Some((value.get("key")?.as_str()?.to_string(),@@ -1206,8 +1327,8 @@ fn read_native_probe_stamp(app_handle: &AppHandle) -> Option<(String, String, St}/// 写结论戳:只在探测确认 Ready 后调用。写失败不影响启动,只降级为「下次仍探测」。-fn write_native_probe_stamp(app_handle: &AppHandle, key: &str, target: &NodeTarget) {- let path = native_probe_stamp_path(app_handle);+fn write_native_probe_stamp_at(base: &Path, key: &str, target: &NodeTarget) {+ let path = native_probe_stamp_path_at(base);if let Some(parent) = path.parent() {if let Err(error) = std::fs::create_dir_all(parent) {log::debug!(@@ -1713,6 +1834,173 @@ fn command_output_tail(output: &std::process::Output) -> String {mod tests {use super::*;+ #[test]+ fn early_preparation_requires_shared_links_pruning_and_same_node_stamp() {+ let root = tempfile::tempdir().unwrap();+ let base = root.path().join("dependencies");+ let core = base.join("dsh");+ let node = base.join("node");+ let profiles = root.path().join("profiles");+ let profile = profiles.join("tauri");+ let resources = root.path().join("resources");+ let source = resources.join("node_modules/dsh-tauri");+ for dir in [&core, &profile, &source] {+ std::fs::create_dir_all(dir).unwrap();+ }+ std::fs::write(&node, "not an executable").unwrap();+ std::fs::write(profile.join("package.json"), "{}").unwrap();+ std::fs::write(source.join("package.json"), r#"{"name":"dsh-tauri"}"#).unwrap();+ let required = [RuntimeRequiredPlugin {+ name: "dsh-tauri",+ source: Some(PathBuf::from("node_modules/dsh-tauri")),+ version: None,+ }];+ let mut paths = RuntimePreparationPaths {+ source: CoreSource::App,+ base: &base,+ core_root: &core,+ node: &node,+ profile: &profile,+ profiles: &profiles,+ resources: Some(&resources),+ core_version: Some("2.0.0"),+ required_plugins: Some(&required),+ };+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Defer+ );+ let destination = core.join("node_modules/dsh-tauri");+ assert_eq!(+ destination.canonicalize().unwrap(),+ source.canonicalize().unwrap()+ );+ let stamp = |paths: &RuntimePreparationPaths<'_>| {+ let key =+ native_probe_stamp_key_at(paths.node, paths.core_root, paths.core_version).unwrap();+ write_native_probe_stamp_at(+ paths.base,+ &key,+ &NodeTarget {+ platform: "win32".into(),+ arch: "x64".into(),+ },+ );+ };+ stamp(&paths);+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Ready+ );+ std::fs::write(&node, "a different Node runtime").unwrap();+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Defer+ );+ stamp(&paths);++ let name = "@deepseek-ai/dsh-api";+ let anchor = core.join("node_modules").join(name);+ let stale = profile.join("node_modules").join(name);+ std::fs::create_dir_all(&anchor).unwrap();+ std::fs::create_dir_all(&stale).unwrap();+ std::fs::write(anchor.join("package.json"), r#"{"version":"2.0.0"}"#).unwrap();+ std::fs::write(stale.join("package.json"), r#"{"version":"1.0.0"}"#).unwrap();+ stamp(&paths);+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Ready+ );+ assert!(!stale.exists());+ paths.required_plugins = None;+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Defer+ );+ paths.required_plugins = Some(&required);+ std::fs::write(profile.join("package.json"), "invalid").unwrap();+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Defer+ );+ std::fs::write(profile.join("package.json"), "{}").unwrap();+ std::fs::write(native_probe_stamp_path_at(&base), r#"{"key":"incomplete"}"#).unwrap();+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Defer+ );+ stamp(&paths);+ paths.source = CoreSource::Local;+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Defer+ );+ paths.source = CoreSource::App;+ let invalid = [RuntimeRequiredPlugin {+ name: "../escape",+ source: Some(source.clone()),+ version: None,+ }];+ paths.required_plugins = Some(&invalid);+ assert!(prepare_active_runtime_at(&paths)+ .unwrap_err()+ .starts_with("CORE_PLUGIN_NAME_INVALID:"));+ remove_link_only(&destination).unwrap();+ assert!(source.is_dir());++ paths.required_plugins = Some(&required);+ std::fs::write(&destination, "core-owned file").unwrap();+ stamp(&paths);+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Defer+ );+ assert_eq!(+ std::fs::read_to_string(&destination).unwrap(),+ "core-owned file"+ );+ std::fs::remove_file(&destination).unwrap();+ std::fs::create_dir(&destination).unwrap();+ let package = destination.join("package.json");+ let marker = destination.join("core-owned.txt");+ std::fs::write(&marker, "keep").unwrap();+ for manifest in [+ None,+ Some("invalid"),+ Some("{}"),+ Some(r#"{"name":"other"}"#),+ ] {+ if let Some(raw) = manifest {+ std::fs::write(&package, raw).unwrap();+ }+ stamp(&paths);+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Defer+ );+ assert_eq!(std::fs::read_to_string(&package).ok().as_deref(), manifest);+ assert_eq!(std::fs::read_to_string(&marker).unwrap(), "keep");+ }+ let manifest = r#"{"name":"dsh-tauri","version":"9.0.0"}"#;+ std::fs::write(&package, manifest).unwrap();+ std::fs::remove_file(native_probe_stamp_path_at(&base)).unwrap();+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Defer+ );+ stamp(&paths);+ assert_eq!(+ prepare_active_runtime_at(&paths).unwrap(),+ RuntimePreparation::Ready+ );+ assert_ne!(+ destination.canonicalize().unwrap(),+ source.canonicalize().unwrap()+ );+ assert_eq!(std::fs::read_to_string(&package).unwrap(), manifest);+ assert_eq!(std::fs::read_to_string(&marker).unwrap(), "keep");+ }+/// 以生产同款方式执行探测脚本(落盘成 `.mjs` 再交给 node),保证测试覆盖的/// 正是运行时那条路径——`node -e` 会截断多行脚本,测出来的是假绿。fn run_probe_script(node: &std::path::Path, cwd: &std::path::Path) -> std::process::Output {@@ -2121,7 +2409,8 @@ mod tests {fn create_directory_junction_accepts_mixed_separators_and_is_idempotent() {let root = std::env::temp_dir().join(format!("dsh-junction-direct-{}", std::process::id()));let _ = std::fs::remove_dir_all(&root);- let source = root.join("@scope/package");+ std::fs::create_dir_all(root.join("src-tauri")).unwrap();+ let source = root.join("src-tauri/../@scope/package");std::fs::create_dir_all(&source).unwrap();std::fs::write(source.join("package.json"), r#"{"name":"dsh-tauri"}"#).unwrap();let destination = root.join("node_modules").join("dsh-tauri");@@ -2130,6 +2419,10 @@ mod tests {let canonical_source = source.canonicalize().unwrap();create_directory_junction(&source, &destination).unwrap_or_else(|e| panic!("junction must be creatable without privileges: {e}"));+ let manifest = std::fs::read_to_string(destination.join("package.json"));+ remove_link_only(&destination).unwrap();+ assert_eq!(manifest.unwrap(), r#"{"name":"dsh-tauri"}"#);+ create_directory_junction(&source, &destination).unwrap();let metadata = std::fs::symlink_metadata(&destination).unwrap();assert!(diff --git a/src-tauri/src/service/plugin/hmr.rs b/src-tauri/src/service/plugin/hmr.rsindex 45188db9..197e08e1 100644--- a/src-tauri/src/service/plugin/hmr.rs+++ b/src-tauri/src/service/plugin/hmr.rs@@ -65,13 +65,23 @@ pub(crate) fn patch_path(app_handle: &AppHandle) -> PathBuf {/// 每次启动都要重算:`--patch` 只在本次进程有效,而本地插件的安装状态可能已经变化。/// 任何一步失败都退化为「不传 `--patch`」(热重载只是便利功能,不该阻断启动)。pub(crate) fn sync_layer(app_handle: &AppHandle) -> Option<PathBuf> {- let path = patch_path(app_handle);- let roots = local_watch_roots(app_handle);- let rendered = if hmr_enabled(app_handle) {- render_layer(&roots)- } else {- None- };+ sync_layer_at(+ &config::get_base_dir(app_handle),+ &profile_dir(app_handle),+ app_handle.path().resource_dir().ok().as_deref(),+ hmr_enabled(app_handle),+ )+}++pub(crate) fn sync_layer_at(+ base: &Path,+ profile: &Path,+ resource_root: Option<&Path>,+ enabled: bool,+) -> Option<PathBuf> {+ let path = base.join(HMR_PATCH_FILENAME);+ let roots = local_watch_roots_at(profile, resource_root);+ let rendered = if enabled { render_layer(&roots) } else { None };let Some(rendered) = rendered else {remove_layer(&path);return None;@@ -111,12 +121,18 @@ fn hmr_enabled(app_handle: &AppHandle) -> bool {/// 需要热重载的本地插件源码目录:已装且已挂载(在 `dsh.profile.bundles` 里)、以/// `link:` / `file:` 声明、目录真实存在、且不属于随包分发的内置插件。pub(crate) fn local_watch_roots(app_handle: &AppHandle) -> Vec<PathBuf> {- let profile = profile_dir(app_handle);- let Some(manifest) = read_manifest(&profile) else {+ local_watch_roots_at(+ &profile_dir(app_handle),+ app_handle.path().resource_dir().ok().as_deref(),+ )+}++pub(crate) fn local_watch_roots_at(profile: &Path, resource_root: Option<&Path>) -> Vec<PathBuf> {+ let Some(manifest) = read_manifest(profile) else {return Vec::new();};- watch_roots_in(&profile, &manifest, |_name, dir| {- is_bundled(app_handle, dir)+ watch_roots_in(profile, &manifest, |_name, dir| {+ resource_root.is_some_and(|root| is_bundled(root, dir))})}@@ -179,10 +195,7 @@ fn resolve_dir(raw: &str, profile: &Path) -> Option<PathBuf> {}/// 随包分发的内置插件源码目录:改它没有意义(升级即被覆盖),不该进 watch root。-fn is_bundled(app_handle: &AppHandle, dir: &Path) -> bool {- let Ok(resource_dir) = app_handle.path().resource_dir() else {- return false;- };+fn is_bundled(resource_root: &Path, dir: &Path) -> bool {let flatten = |path: &Path| {let mut text = path.to_string_lossy()@@ -192,7 +205,7 @@ fn is_bundled(app_handle: &AppHandle, dir: &Path) -> bool {}text.to_lowercase()};- flatten(dir).starts_with(&flatten(dunce::simplified(&resource_dir)))+ flatten(dir).starts_with(&flatten(dunce::simplified(resource_root)))}/// 去掉被父目录覆盖的子目录:chokidar 递归监听父目录即可,重复 root 只增开销。@@ -445,6 +458,62 @@ mod tests {}}+ #[test]+ fn sync_layer_at_rereads_the_profile_and_excludes_only_the_explicit_resource_root() {+ let temp = tempfile::tempdir().unwrap();+ let root = dunce::canonicalize(temp.path()).unwrap();+ let profile = plugin_dir(&root, "profile");+ let resources = plugin_dir(&root, "resources");+ let bundled = plugin_dir(&resources, "builtin");+ let local = plugin_dir(&root, "resources-local");+ let base = root.join("app-data");+ let path = base.join(HMR_PATCH_FILENAME);+ let manifest_path = profile.join("package.json");+ std::fs::write(+ &manifest_path,+ serde_json::json!({+ "dependencies": {+ "local": format!("link:{}", local.display()),+ "bundled": format!("file:{}", bundled.display())+ },+ "dsh": { "profile": { "bundles": ["local", "bundled"] } }+ })+ .to_string(),+ )+ .unwrap();+ assert_eq!(+ local_watch_roots_at(&profile, Some(&resources)),+ vec![local.clone()]+ );+ assert_eq!(+ sync_layer_at(&base, &profile, Some(&resources), true),+ Some(path.clone())+ );+ let layer = std::fs::read_to_string(&path).unwrap();+ let entries: Vec<serde_yaml::Value> = serde_yaml::from_str(&layer).unwrap();+ let url = tauri::Url::parse(entries[0]["config"]["base"].as_str().unwrap()).unwrap();+ assert_eq!(url.to_file_path().unwrap(), local);+ assert_eq!(entries[0]["config"]["root"].as_sequence().unwrap().len(), 1);+ assert_eq!(entries[0]["config"]["root"][0].as_str(), Some("."));++ assert_eq!(+ sync_layer_at(&base, &profile, Some(&resources), false),+ None+ );+ assert!(!path.exists());+ assert_eq!(+ sync_layer_at(&base, &profile, Some(&resources), true),+ Some(path.clone())+ );+ std::fs::write(+ &manifest_path,+ r#"{"dependencies":{},"dsh":{"profile":{"bundles":[]}}}"#,+ )+ .unwrap();+ assert_eq!(sync_layer_at(&base, &profile, Some(&resources), true), None);+ assert!(!path.exists());+ }+#[test]fn local_dep_path_accepts_both_prefixes_and_trims_separators() {assert_eq!(diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rsindex 6be37fb3..d4673f1f 100644--- a/src-tauri/src/service/plugin/install/mod.rs+++ b/src-tauri/src/service/plugin/install/mod.rs@@ -72,8 +72,8 @@ pub(crate) use env::build_plugin_envs;pub use inspect::inspect_specs;pub(crate) use inspect::packument;pub(crate) use pnpm::{- bundled_pnpm_major, harness_prefer_bundled_pnpm, pnpm_major_version_at_bounded,- profile_store_major,+ bundled_pnpm_major, harness_prefer_bundled_pnpm, harness_prefer_bundled_pnpm_from,+ pnpm_major_version_at_bounded, profile_store_major,};pub(crate) use single::uninstall_deprecated_plugins;pub use single::{remove_many, update_many};diff --git a/src-tauri/src/service/plugin/install/pnpm.rs b/src-tauri/src/service/plugin/install/pnpm.rsindex 516fd328..8c531a7c 100644--- a/src-tauri/src/service/plugin/install/pnpm.rs+++ b/src-tauri/src/service/plugin/install/pnpm.rs@@ -485,7 +485,11 @@ fn pnpm_probe_path(pnpm: &Path, node: Option<&Path>, bin_dir: Option<&Path>) ->/// node_modules)时返回 `None`,由调用方走"全新档案"逻辑。/// 供 [`ensure_pnpm`] 选版与 [`crate::service::plugin::verify`] 的修复选版共用。pub(crate) fn profile_store_major(app_handle: &AppHandle) -> Option<u32> {- parse_store_major_from_modules_yaml(&read_modules_yaml(app_handle)?)+ profile_store_major_at(&profile_dir(app_handle))+}++pub(crate) fn profile_store_major_at(profile_dir: &Path) -> Option<u32> {+ parse_store_major_from_modules_yaml(&read_modules_yaml_at(profile_dir)?)}/// 档案 `node_modules/.modules.yaml` 记录的 pnpm store 基目录(去掉 `v10` 版本段)。@@ -500,7 +504,11 @@ pub(crate) fn profile_store_major(app_handle: &AppHandle) -> Option<u32> {/// 下传的必须是基目录而非记录原文(含版本段):版本段由 pnpm 按自身主版本追加,见/// [`strip_store_version`]。pub(crate) fn profile_store_base_dir(app_handle: &AppHandle) -> Option<String> {- let store_dir = parse_store_dir_from_modules_yaml(&read_modules_yaml(app_handle)?)?;+ profile_store_base_dir_at(&profile_dir(app_handle))+}++pub(crate) fn profile_store_base_dir_at(profile_dir: &Path) -> Option<String> {+ let store_dir = parse_store_dir_from_modules_yaml(&read_modules_yaml_at(profile_dir)?)?;Some(strip_store_version(&store_dir))}@@ -556,13 +564,8 @@ pub(crate) fn reset_incompatible_modules_metadata(app_handle: &AppHandle) -> boo}/// 读取档案的 `node_modules/.modules.yaml`;文件缺失(全新档案)返回 `None`。-fn read_modules_yaml(app_handle: &AppHandle) -> Option<String> {- std::fs::read_to_string(- profile_dir(app_handle)- .join("node_modules")- .join(".modules.yaml"),- )- .ok()+fn read_modules_yaml_at(profile_dir: &Path) -> Option<String> {+ std::fs::read_to_string(profile_dir.join("node_modules").join(".modules.yaml")).ok()}/// 从 `.modules.yaml` 文本解析 `storeDir`(纯函数,便于单测)。@@ -596,8 +599,11 @@ fn parse_store_major_from_modules_yaml(content: &str) -> Option<u32> {////// 供 [`ensure_pnpm`] 选版与 [`crate::service::plugin::verify`] 的修复选版共用(store 主版本匹配)。pub(crate) fn bundled_pnpm_major(app_handle: &AppHandle) -> Option<u32> {- let manifest = config::get_pnpm_install_path(app_handle).join("package.json");- let content = std::fs::read_to_string(manifest).ok()?;+ bundled_pnpm_major_at(&config::get_pnpm_install_path(app_handle))+}++pub(crate) fn bundled_pnpm_major_at(pnpm_root: &Path) -> Option<u32> {+ let content = std::fs::read_to_string(pnpm_root.join("package.json")).ok()?;let value: serde_json::Value = serde_json::from_str(&content).ok()?;value.get("version")?@@ -613,14 +619,39 @@ pub(crate) fn bundled_pnpm_major(app_handle: &AppHandle) -> Option<u32> {/// store 未知时用户 pnpm ≥ 10 优先,否则强制捆绑版。启动阶段绝不触发下载,/// 捆绑版未安装即返回 false(交由用户 pnpm)。pub(crate) async fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> Result<bool, String> {- if !config::get_pnpm_binary_path(app_handle).exists() {+ harness_prefer_bundled_pnpm_from(+ &profile_dir(app_handle),+ &config::get_pnpm_install_path(app_handle),+ &config::get_pnpm_binary_path(app_handle),+ cli::find_user_pnpm(app_handle).as_deref(),+ &config::get_node_binary_path(app_handle),+ &cli::get_bin_dir(app_handle),+ )+ .await+}++pub(crate) async fn harness_prefer_bundled_pnpm_from(+ profile_dir: &Path,+ pnpm_root: &Path,+ pnpm_binary: &Path,+ user_pnpm: Option<&Path>,+ node: &Path,+ bin_dir: &Path,+) -> Result<bool, String> {+ if !pnpm_binary.exists() {return Ok(false);}- let store_major = profile_store_major(app_handle);- if store_major.is_some_and(|store| bundled_pnpm_major(app_handle) != Some(store)) {+ let store_major = profile_store_major_at(profile_dir);+ if store_major.is_some_and(|store| bundled_pnpm_major_at(pnpm_root) != Some(store)) {return Ok(false);}- let user_major = user_pnpm_major_version_bounded(app_handle, new_process_owner()).await?;+ let user_major = match user_pnpm {+ Some(pnpm) => {+ pnpm_major_version_at_bounded(pnpm, Some(node), Some(bin_dir), new_process_owner())+ .await?+ }+ None => None,+ };Ok(match store_major {Some(store) => user_major != Some(store),None => !matches!(user_major, Some(major) if major >= MIN_TRUSTED_PNPM_MAJOR),@@ -632,6 +663,81 @@ mod tests {use super::super::super::process::TEST_PROCESS_LOCK;use super::*;+ #[tokio::test]+ async fn startup_pnpm_paths_reread_metadata_and_skip_unneeded_probes() {+ let _test_guard = TEST_PROCESS_LOCK.lock().await;+ let root = tempfile::tempdir().unwrap();+ let profile = root.path().join("profile");+ let modules = profile.join("node_modules").join(".modules.yaml");+ let pnpm_root = root.path().join("pnpm");+ let manifest = pnpm_root.join("package.json");+ let binary = pnpm_root.join("bin").join("pnpm.cjs");+ let user = root.path().join("must-not-be-probed");+ let node = root.path().join("node");+ let bin_dir = root.path().join("desktop-bin");+ std::fs::create_dir_all(modules.parent().unwrap()).unwrap();+ std::fs::create_dir_all(binary.parent().unwrap()).unwrap();+ let yaml = "storeDir: /store/v10\n";+ std::fs::write(&modules, yaml).unwrap();+ std::fs::write(&manifest, r#"{"version":"11.2.0"}"#).unwrap();+ assert_eq!(read_modules_yaml_at(&profile).as_deref(), Some(yaml));+ assert_eq!(profile_store_major_at(&profile), Some(10));+ assert_eq!(+ profile_store_base_dir_at(&profile).as_deref(),+ Some("/store")+ );+ assert_eq!(bundled_pnpm_major_at(&pnpm_root), Some(11));++ let process_guard = acquire_process_lock().await.unwrap();+ for present in [false, true] {+ if present {+ std::fs::write(&binary, "").unwrap();+ }+ let prefer = tokio::time::timeout(+ std::time::Duration::from_millis(100),+ harness_prefer_bundled_pnpm_from(+ &profile,+ &pnpm_root,+ &binary,+ Some(&user),+ &node,+ &bin_dir,+ ),+ )+ .await+ .expect("missing or incompatible bundled pnpm must not acquire the probe lock")+ .unwrap();+ assert!(!prefer);+ }+ drop(process_guard);++ for store in [11, 10] {+ let json = format!(r#"{{"storeDir":"/store/v{store}"}}"#);+ std::fs::write(&modules, &json).unwrap();+ assert_eq!(profile_store_major_at(&profile), Some(store));+ assert_eq!(+ profile_store_base_dir_at(&profile).as_deref(),+ Some("/store")+ );+ assert_eq!(+ harness_prefer_bundled_pnpm_from(+ &profile, &pnpm_root, &binary, None, &node, &bin_dir,+ )+ .await+ .unwrap(),+ store == 11+ );+ assert_eq!(std::fs::read_to_string(&modules).unwrap(), json);+ }+ std::fs::write(&manifest, r#"{"version":"10.9.0"}"#).unwrap();+ assert_eq!(bundled_pnpm_major_at(&pnpm_root), Some(10));+ assert!(harness_prefer_bundled_pnpm_from(+ &profile, &pnpm_root, &binary, None, &node, &bin_dir,+ )+ .await+ .unwrap());+ }+/// issue #449 回归:探测超时、但进程已被强杀并回收干净时,必须降级为/// 「用户 pnpm 不可用」(`None` → `ensure_pnpm` 回退捆绑版),而不是把/// `PNPM_PROBE_TIMEOUT` 当成整次插件安装的失败。diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rsindex 510ca4cb..95e1bb97 100644--- a/src-tauri/src/service/plugin/install/single.rs+++ b/src-tauri/src/service/plugin/install/single.rs@@ -3,6 +3,7 @@//! 卸载后核验 profile 清单,插件仍被引用时走离线卸载兜底(受保护包除外)。//! 另含启动期弃用插件自动卸载(`uninstall_deprecated_plugins`)。+#[cfg(test)]use std::collections::HashSet;use std::ffi::OsString;use std::path::Path;@@ -23,7 +24,6 @@ use super::diagnose::{};use super::errors;use super::harness_prefer_bundled_pnpm;-use super::installed_name;use super::is_actionable_plugin_ref;use super::is_installed;use super::load_deprecated_ids;@@ -33,6 +33,7 @@ use super::pnpm::ensure_pnpm;use super::profile_dir;use super::run_plugin_with_allow_build_retry;use super::uninstall_recovery;+#[cfg(test)]use super::PreinstallPluginInfo;use crate::service::plugin::update::known_latest;use crate::service::profile::profile_release_age_excluded;@@ -552,79 +553,32 @@ pub async fn remove_many(app_handle: &AppHandle, ids: &[String]) -> Result<(), S}}-/// 计算需要自动卸载的弃用插件已安装包名(纯函数,便于单测)。-///-/// 命中条件:id 登记在弃用名单(`resources/manifest.jsonc` 的 `plugins.depercated`,-/// 见 [`super::super::preset::load_deprecated_ids`])且当前已安装,或插件被当前核心-/// 淘汰([`PreinstallPluginInfo::retire_on`]:核心已超出清单声明的版本区间、或已安装-/// 版本不再落在该核心对应的插件版本区间内)。返回实际安装包名——离线卸载-/// (`uninstall_recovery`)以它为键从 profile 清单与 `node_modules` 精准移除-/// (scoped 包名与预设 id 不一致时也能正确卸载)。-///-/// 两条来源缺一不可:-/// 1. 预设仍声明该 id:以 `installed_name`(实际 npm 包名)为准;内部插件由启动-/// 自愈强制安装,不适用弃用语义,跳过。-/// 2. 兜底——预设清单已不存在该 id(被整体删除,如 `dsh-tauri-panel` 并入核心后-/// 从 `plugins.built-in` 移除):此时按弃用名单登记的 id 本身核对。少了-/// 这一步,弃用名单对「连预设条目一起删掉」的插件永远无效,其 `link:` 目标还会-/// 因安装目录残留而躲过失效链接清理,残留 bundle 直接拖垮启动。-fn deprecated_installed_names(- presets: &[PreinstallPluginInfo],- deprecated_ids: &HashSet<String>,- core_version: Option<&str>,- installed: impl Fn(&str) -> bool,- installed_version: impl Fn(&str) -> Option<String>,-) -> Vec<String> {- let mut names: Vec<String> = presets- .iter()- .filter(|p| {- let name = installed_name(p);- if !installed(name) {- return false;- }- if !p.internal && deprecated_ids.contains(&p.id) {- return true;- }- p.retire_on(core_version, installed_version(name).as_deref())- })- .map(|p| installed_name(p).to_string())- .collect();- for id in deprecated_ids {- if presets.iter().any(|p| p.id == *id) {- continue;- }- if installed(id) {- names.push(id.clone());- }- }- names.sort();- names.dedup();- names-}--/// 弃用插件在 profile 中的残留判定:清单引用或 `node_modules` 入口。-///-/// 入口用 `symlink_metadata` 判定:junction / 符号链接的目标目录消失时 `exists()`-/// 返回 false,但入口本身仍是 profile 解析路径上的残留,必须能被识别并清掉-/// (`uninstall_recovery` 对已清空清单的 id 幂等,只清入口与 patch 层)。-fn deprecated_residue_present(app_handle: &AppHandle, name: &str) -> bool {- is_installed(app_handle, name)- || std::fs::symlink_metadata(profile_dir(app_handle).join("node_modules").join(name))- .is_ok()-}+#[cfg(test)]+use super::super::installed::deprecated_installed_names;pub(crate) async fn uninstall_deprecated_plugins(app_handle: &AppHandle) -> Result<(), String> {let presets = load_presets(app_handle);let core_version = core::active_version(app_handle);let deprecated_ids = load_deprecated_ids(app_handle);let profile = profile_dir(app_handle);- let names = deprecated_installed_names(+ let manifest = match std::fs::read_to_string(profile.join("package.json")) {+ Ok(raw) => serde_json::from_str::<super::super::installed::ProfilePackageJson>(&raw)+ .map_err(|error| format!("DEPRECATED_PLUGIN_MANIFEST_PARSE_FAILED: {error}"))?,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ super::super::installed::ProfilePackageJson {+ dependencies: Default::default(),+ dsh: None,+ }+ }+ Err(error) => return Err(format!("DEPRECATED_PLUGIN_MANIFEST_READ_FAILED: {error}")),+ };+ let (names, _) = super::super::installed::deprecated_plugins_at(+ &profile,+ &manifest,&presets,&deprecated_ids,core_version.as_deref(),- |name| deprecated_residue_present(app_handle, name),- |name| installed_package_version(&profile, name),- );+ )?;if names.is_empty() {return Ok(());}diff --git a/src-tauri/src/service/plugin/installed.rs b/src-tauri/src/service/plugin/installed.rsindex 31a5afa2..6ad751b0 100644--- a/src-tauri/src/service/plugin/installed.rs+++ b/src-tauri/src/service/plugin/installed.rs@@ -3,7 +3,7 @@use serde::{Deserialize, Serialize};use std::collections::{HashMap, HashSet};-use std::path::PathBuf;+use std::path::{Path, PathBuf};use tauri::AppHandle;use super::preset::{load_deprecated_ids, load_presets, PreinstallPluginInfo};@@ -103,6 +103,97 @@ pub(crate) fn installed_name(p: &PreinstallPluginInfo) -> &str {p.package.as_deref().unwrap_or(p.id.as_str())}+pub(super) fn deprecated_installed_names(+ presets: &[PreinstallPluginInfo],+ deprecated_ids: &HashSet<String>,+ core_version: Option<&str>,+ mut installed: impl FnMut(&str) -> bool,+ mut installed_version: impl FnMut(&str) -> Option<String>,+) -> Vec<String> {+ let mut names: Vec<String> = presets+ .iter()+ .filter(|p| {+ let name = installed_name(p);+ if !installed(name) {+ return false;+ }+ if !p.internal && deprecated_ids.contains(&p.id) {+ return true;+ }+ matches!(+ p.version,+ Some(crate::config::manifest::PluginVersion::Matrix(_))+ ) && p.retire_on(core_version, installed_version(name).as_deref())+ })+ .map(|p| installed_name(p).to_string())+ .collect();+ for id in deprecated_ids {+ if !presets.iter().any(|p| p.id == *id) && installed(id) {+ names.push(id.clone());+ }+ }+ names.sort();+ names.dedup();+ names+}++pub(super) fn deprecated_plugins_at(+ profile: &Path,+ manifest: &ProfilePackageJson,+ presets: &[PreinstallPluginInfo],+ deprecated_ids: &HashSet<String>,+ core_version: Option<&str>,+) -> Result<(Vec<String>, bool), String> {+ let bundles = manifest.dsh.as_ref().and_then(|dsh| dsh.profile.as_ref());+ let mut failure = None;+ let mut known = true;+ let names = deprecated_installed_names(+ presets,+ deprecated_ids,+ core_version,+ |name| {+ if manifest.dependencies.contains_key(name)+ || bundles.is_some_and(|profile| profile.bundles.iter().any(|id| id == name))+ {+ return true;+ }+ match std::fs::symlink_metadata(profile.join("node_modules").join(name)) {+ Ok(_) => true,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,+ Err(error) => {+ failure = Some(format!(+ "DEPRECATED_PLUGIN_ENTRY_READ_FAILED: {name}: {error}"+ ));+ false+ }+ }+ },+ |name| {+ let version = std::fs::read_to_string(+ profile.join("node_modules").join(name).join("package.json"),+ )+ .ok()+ .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())+ .and_then(|manifest| manifest.get("version")?.as_str().map(String::from));+ known &= presets+ .iter()+ .filter(|preset| installed_name(preset) == name)+ .all(|preset| {+ preset.version.as_ref().is_some_and(|range| {+ range+ .outdated_for_core_generation(core_version, version.as_deref())+ .is_some()+ })+ });+ version+ },+ );+ match failure {+ Some(error) => Err(error),+ None => Ok((names, known)),+ }+}+/// 预装插件列表(含 installed 状态),前端渲染用pub fn list(app_handle: &AppHandle) -> Vec<PreinstallPlugin> {let installed = list_installed(app_handle);@@ -150,7 +241,7 @@ const NPMRC_KEY: &str = "confirmModulesPurge=false";////// 拆出纯路径版便于单元测试(不依赖 AppHandle);`ensure_profile_npmrc` 仅负责/// 把 profile 路径传进来。-fn ensure_npmrc_at(npmrc_path: &PathBuf) -> Result<(), String> {+pub(crate) fn ensure_npmrc_at(npmrc_path: &PathBuf) -> Result<(), String> {// 读取既有内容(不存在按空处理)let existing = match std::fs::read_to_string(npmrc_path) {Ok(c) => c,diff --git a/src-tauri/src/service/plugin/internal/mod.rs b/src-tauri/src/service/plugin/internal/mod.rsindex 66530b29..a281fc39 100644--- a/src-tauri/src/service/plugin/internal/mod.rs+++ b/src-tauri/src/service/plugin/internal/mod.rs@@ -21,8 +21,11 @@ use tauri::AppHandle;use super::cancel::terminate_owned_install;use super::install::install_internal;-use super::installed::{installed_name, profile_dir, ProfilePackageJson};-use super::preset::{bundled_dep_spec, bundled_plugin_dir, load_presets, PreinstallPluginInfo};+use super::installed::{deprecated_plugins_at, installed_name, profile_dir, ProfilePackageJson};+use super::preset::{+ bundled_dep_spec, bundled_plugin_dir, bundled_plugin_dir_from, load_presets,+ presets_from_manifest, PreinstallPluginInfo,+};use super::process::{new_process_owner, PreinstallLogPayload, ProcessOwner, PREINSTALL_LOG_EVENT};use crate::config;@@ -214,28 +217,35 @@ fn ensure_lock(profile: &str) -> std::sync::Arc<tokio::sync::Mutex<EnsureCoordin/// patch、home patch;如果旧 checkout 曾把内置插件 patch 写入其中,单纯重装/// `node_modules` 无法消除重复 loader entry。只清理桌面端明确拥有的内置 id,/// 绝不触碰用户插件。-pub(crate) fn repair_loader_state(app_handle: &AppHandle) -> Result<(), String> {- let core_version = crate::service::core::active_version(app_handle);- let internal: Vec<_> = load_presets(app_handle)- .into_iter()- .filter(|preset| preset.internal && !preset.unsupported_on(core_version.as_deref()))- .collect();+fn repair_loader_state(+ profile: &Path,+ dsh_home: &Path,+ internal: &[&PreinstallPluginInfo],+ manifest: &mut Option<serde_json::Value>,+ prepare: bool,+) -> Result<bool, String> {let bundle_ids: HashSet<&str> = internal.iter().map(|preset| preset.id.as_str()).collect();- let profile = profile_dir(app_handle);- let profile_manifest = profile.join("package.json");- let mut changed_manifest = false;- if let Ok(raw) = std::fs::read_to_string(&profile_manifest) {- let mut manifest = serde_json::from_str::<serde_json::Value>(&raw)- .map_err(|e| format!("INTERNAL_PLUGIN_MANIFEST_PARSE_FAILED: {e}"))?;- changed_manifest = dedupe_profile_bundles(&mut manifest);- if changed_manifest {- write_profile_manifest(&profile_manifest, &manifest)?;+ let mut pending = false;+ if let Some(manifest) = manifest.as_mut() {+ if dedupe_profile_bundles(manifest) {+ if prepare {+ write_profile_manifest(&profile.join("package.json"), manifest)?;+ } else {+ pending = true;+ }}}- for patch_path in super::patch_layer_paths(&profile, &config::get_dsh_data_path(app_handle)) {- let Ok(raw) = std::fs::read_to_string(&patch_path) else {- continue;+ for patch_path in super::patch_layer_paths(profile, dsh_home) {+ let raw = match std::fs::read_to_string(&patch_path) {+ Ok(raw) => raw,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,+ Err(error) => {+ return Err(format!(+ "INTERNAL_PLUGIN_PATCH_READ_FAILED: {}: {error}",+ patch_path.display()+ ))+ }};let mut patch = serde_yaml::from_str::<serde_yaml::Value>(&raw).map_err(|e| {format!(@@ -244,6 +254,10 @@ pub(crate) fn repair_loader_state(app_handle: &AppHandle) -> Result<(), String>)})?;if remove_duplicate_bundle_entries_from_patch(&mut patch, &bundle_ids) {+ if !prepare {+ pending = true;+ continue;+ }let rendered = serde_yaml::to_string(&patch).map_err(|e| format!("INTERNAL_PLUGIN_PATCH_RENDER_FAILED: {e}"))?;std::fs::write(&patch_path, rendered).map_err(|e| {@@ -259,11 +273,25 @@ pub(crate) fn repair_loader_state(app_handle: &AppHandle) -> Result<(), String>}}+ if !prepare {+ return Ok(pending);+ }+// dsh 会把运行时组合结果写回 cordis.yml;旧版本留下的组合结果会在下一次// 启动时与新 patch 再合并,必须恢复官方约定的空根配置。let root = profile.join("cordis.yml");const EMPTY_ROOT: &str = "# dsh profile root — an empty entry list. The tree is composed as patches:\n# each bundle in package.json's dsh.profile.bundles, then cordis.patch.yml, then any\n# --patch overlays. Edit cordis.patch.yml, not this file.\n[]\n";- if std::fs::read_to_string(&root).ok().as_deref() != Some(EMPTY_ROOT) && profile.is_dir() {+ let existing = match std::fs::read_to_string(&root) {+ Ok(raw) => Some(raw),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,+ Err(error) => {+ return Err(format!(+ "INTERNAL_PLUGIN_ROOT_READ_FAILED: {}: {error}",+ root.display()+ ))+ }+ };+ if existing.as_deref() != Some(EMPTY_ROOT) && profile.is_dir() {std::fs::write(&root, EMPTY_ROOT).map_err(|e| format!("INTERNAL_PLUGIN_ROOT_WRITE_FAILED: {}: {e}", root.display()))?;log::warn!(@@ -271,13 +299,7 @@ pub(crate) fn repair_loader_state(app_handle: &AppHandle) -> Result<(), String>root.display());}- if changed_manifest {- log::warn!(- "INTERNAL_PLUGIN_PROFILE_MIGRATED: deduplicated profile bundles in {}",- profile_manifest.display()- );- }- Ok(())+ Ok(false)}/// 核对输入指纹:档案路径 + loader 状态修复的全部输入 + 核心版本 + 内置插件的安装规格。@@ -327,6 +349,7 @@ pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {}async fn ensure_scoped(app_handle: &AppHandle) -> Result<(), String> {+ crate::service::workflow::early::wait_preparation().await?;let lock = ensure_lock(&crate::service::profile::active_profile(app_handle));let presets = load_presets(app_handle);// 被核心吸收的内置插件(当前核心已超出其声明的全部核心版本区间)自愈不再装回,@@ -336,6 +359,21 @@ async fn ensure_scoped(app_handle: &AppHandle) -> Result<(), String> {.into_iter().filter(|p| p.internal && !p.unsupported_on(core_version.as_deref())).collect();+ if crate::service::workflow::has_owned_process() {+ if config::manifest::read(app_handle).is_none() {+ return Err("INTERNAL_PLUGIN_RESTART_REQUIRED: 内置插件清单不可读;请恢复应用资源后通过正常启动重试。".into());+ }+ let refs: Vec<_> = internal.iter().collect();+ let profile = profile_dir(app_handle);+ let check = prepare_internal_plugins(+ &profile,+ &config::get_dsh_data_path(app_handle),+ &refs,+ false,+ |id| bundled_plugin_dir(app_handle, id),+ )?;+ return require_running_plugins_ready(&profile, &check);+ }// 同一次启动的两路调用:后到的一路输入未变、且前一路刚成功,直接复用结论,// 连下面的失效链接清理、可写性预检与 loader 状态修复一起跳过(issue #766)。let fingerprint = ensure_fingerprint(app_handle, &internal);@@ -350,26 +388,6 @@ async fn ensure_scoped(app_handle: &AppHandle) -> Result<(), String> {);return Ok(());}- prune_dangling_link_deps(app_handle, &internal);- if internal.is_empty() {- return Ok(());- }-- // 写入前可写性预检(issue #466):档案目录属主不是当前用户时(典型:此前用- // sudo 运行过 dsh,macOS 的 sudo 保留 $HOME)**读得到、写不了**——清单能读,- // 但 .npmrc、cordis.yml、链接、依赖全部 EACCES。必须在任何写入与 pnpm 之前- // 给出可执行诊断(失败路径 + 属主 + chown 命令),否则用户只会看到 pnpm/写盘的- // 裸 os error 13,或一路走到 spawn 之后 dsh 才崩在 cordis.yml 上(只剩- // "exited early")。放在 repair_loader_state 之前:它同样会写档案清单/patch/根- // 配置,权限错位时最先失败的就是那里。预检不创建目录:建档案留给- // dsh/init_profile_dir 自己的初始化逻辑(issue #452)。- crate::service::perm::ensure_writable_path(- &profile_dir(app_handle),- &config::get_dsh_data_path(app_handle),- "PROFILE_NOT_WRITABLE",- )?;-- repair_loader_state(app_handle)?;let outcome =receive_current_or_next_flight(|| subscribe_or_start(app_handle, &internal)).await;if outcome.is_ok() {@@ -382,41 +400,6 @@ async fn ensure_scoped(app_handle: &AppHandle) -> Result<(), String> {outcome}-/// 卸载「本地链接目标已不存在」的失效依赖(含已被删除的内置包),在服务启动前调用。-///-/// 已删除的包不再出现在预设清单里,孤儿分支(bundled 目录缺失)永远碰不到它,其-/// `link:` 悬空依赖与 `dsh.profile.bundles` 引用会永久留档,令 dsh 每次启动都报-/// `cannot resolve profile bundle <name>`。与孤儿卸载同一模式:best-effort、离线-/// 精准(改写清单 + 删入口 + 剥 patch 层),任何失败只记告警,绝不阻断启动。-fn prune_dangling_link_deps(app_handle: &AppHandle, internal: &[PreinstallPluginInfo]) {- let profile = profile_dir(app_handle);- let manifest_path = profile.join("package.json");- let Ok(raw) = std::fs::read_to_string(&manifest_path) else {- return;- };- let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&raw) else {- log::warn!("INTERNAL_PLUGIN_MANIFEST_PARSE_FAILED: 跳过失效链接依赖清理");- return;- };- let mut keep: HashSet<&str> = HashSet::new();- for preset in internal {- keep.insert(preset.id.as_str());- keep.insert(installed_name(preset));- }- for name in collect_dangling_local_link_deps(&manifest, &keep, &profile) {- if !super::recovery::is_actionable_plugin_ref(&name) {- log::warn!("INTERNAL_PLUGIN_DANGLING_LINK_SKIPPED: {name}(核心/官方包不执行卸载)");- continue;- }- log::warn!(- "INTERNAL_PLUGIN_DANGLING_LINK_UNINSTALLING: {name}(本地链接目标已不存在,卸载失效依赖)"- );- if let Err(e) = super::uninstall_recovery(app_handle, &name) {- log::warn!("INTERNAL_PLUGIN_DANGLING_LINK_UNINSTALL_FAILED: {name}: {e}");- }- }-}-async fn subscribe_or_start(app_handle: &AppHandle,internal: &[PreinstallPluginInfo],@@ -642,21 +625,22 @@ fn emit_phase();}-/// 实际的核对与安装:遍历 internal 预设,未安装 / 路径不对 / 被卸载 → 批量重装。-async fn ensure_inner(- app_handle: &AppHandle,- internal: &[&PreinstallPluginInfo],- cancel: tokio::sync::watch::Receiver<bool>,- owner: ProcessOwner,-) -> Result<(), String> {- log::info!(- "checking {} internal preset plugins for install state",- internal.len()- );+struct InternalPluginCheck {+ manifest: Option<serde_json::Value>,+ parsed: Option<ProfilePackageJson>,+ need: Vec<(String, String, PathBuf)>,+ orphans: Vec<String>,+ sources_ready: bool,+ migration_pending: bool,+}- // 一次读取当前档案;缺失时按「全部未安装」处理,由安装流程自行初始化。已有但- // 损坏的清单不能静默覆盖,否则可能丢失用户其它插件,故直接给出可诊断错误。- let profile = profile_dir(app_handle);+fn prepare_internal_plugins(+ profile: &Path,+ dsh_home: &Path,+ internal: &[&PreinstallPluginInfo],+ prepare: bool,+ resolve_bundle: impl Fn(&str) -> Option<PathBuf>,+) -> Result<InternalPluginCheck, String> {let manifest_path = profile.join("package.json");let mut manifest = match std::fs::read_to_string(&manifest_path) {Ok(raw) => Some(@@ -666,50 +650,31 @@ async fn ensure_inner(Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,Err(e) => return Err(format!("INTERNAL_PLUGIN_MANIFEST_READ_FAILED: {e}")),};- let dependencies: HashMap<String, String> = match manifest.as_ref() {- Some(value) => {- serde_json::from_value::<ProfilePackageJson>(value.clone())- .map_err(|e| format!("INTERNAL_PLUGIN_MANIFEST_SCHEMA_FAILED: {e}"))?- .dependencies- }- None => HashMap::new(),- };-- // 旧工作目录留下的 profile 可能含重复 bundle;先做幂等迁移,避免在- // 检查依赖正常时直接进入 Cordis 并触发 duplicate loader entry。- let mut migrated = false;- if let Some(value) = manifest.as_mut() {- migrated = dedupe_profile_bundles(value);- }-- let bundle_ids: HashSet<&str> = internal.iter().map(|preset| preset.id.as_str()).collect();- let patch_path = profile.join("cordis.patch.yml");- let mut patch = std::fs::read_to_string(&patch_path)- .ok()- .and_then(|raw| serde_yaml::from_str::<serde_yaml::Value>(&raw).ok());- if let Some(value) = patch.as_mut() {- if remove_duplicate_bundle_entries_from_patch(value, &bundle_ids) {- let rendered = serde_yaml::to_string(value)- .map_err(|e| format!("INTERNAL_PLUGIN_PATCH_RENDER_FAILED: {e}"))?;- std::fs::write(&patch_path, rendered)- .map_err(|e| format!("INTERNAL_PLUGIN_PATCH_WRITE_FAILED: {e}"))?;- migrated = true;- log::warn!(- "INTERNAL_PLUGIN_PROFILE_MIGRATED: removed duplicate bundle entries from {}",- patch_path.display()- );- }- }- if migrated {- if let Some(value) = manifest.as_ref() {- write_profile_manifest(&manifest_path, value)?;- }+ let parsed = manifest+ .as_ref()+ .map(|value| serde_json::from_value::<ProfilePackageJson>(value.clone()))+ .transpose()+ .map_err(|error| format!("INTERNAL_PLUGIN_MANIFEST_SCHEMA_FAILED: {error}"))?;+ if prepare {+ crate::service::perm::ensure_writable_path(profile, dsh_home, "PROFILE_NOT_WRITABLE")?;}-- let mut need: Vec<(String, String, PathBuf)> = Vec::new();- // 本分支要「直接卸载」的孤儿内置插件(安装包名):其捆绑目录已不存在且仍以- // `link:`/`file:` 本地依赖形式安装在 profile 里。见下方 bundle 缺失分支的说明。- let mut orphans: Vec<String> = Vec::new();+ let migration_pending =+ repair_loader_state(profile, dsh_home, internal, &mut manifest, prepare)?;+ let empty_dependencies = HashMap::new();+ let dependencies = parsed+ .as_ref()+ .map(|manifest| &manifest.dependencies)+ .unwrap_or(&empty_dependencies);+ let keep: HashSet<&str> = internal+ .iter()+ .flat_map(|preset| [preset.id.as_str(), installed_name(preset)])+ .collect();+ let mut orphans = manifest+ .as_ref()+ .map(|manifest| collect_dangling_local_link_deps(manifest, &keep, profile))+ .unwrap_or_default();+ let mut need = Vec::new();+ let mut sources_ready = true;for preset in internal {let name = installed_name(preset);if super::disable::has_patch_disable(&profile, &preset.id)@@ -717,7 +682,8 @@ async fn ensure_inner({continue;}- let Some(bundled) = bundled_plugin_dir(app_handle, &preset.id) else {+ let Some(bundled) = resolve_bundle(&preset.id) else {+ sources_ready = false;// 未找到内置插件目录:release 说明构建期 build:plugins 未打包(发布// 缺陷,由 build:plugins 响亮失败);debug 自动发现 packages/* 中非私有// 且含 dsh 对象的包,未命中时跳过(「找不到则不装」)。@@ -750,7 +716,7 @@ async fn ensure_inner(// 不存在目录的 `link:` 依赖会静默 exit 0(日志特征 `Installing a dependency// from a non-existent directory`),重装必然再次假成功,形成启动死循环。这类// 是「应用资源缺失」而非「路径变更」:直接给出精确错误,阻断本轮重装。- if !bundled.join("package.json").is_file() {+ if !internal_plugin_entry_is_ready(&bundled) {return Err(format!("INTERNAL_PLUGIN_SOURCE_MISSING: 内置插件 {name} 的捆绑源目录 {} 缺失或不可读(应用资源目录可能被移动/删除或盘符变更)。pnpm 会静默跳过安装(exit 0 无产物),导致服务启动时 loader 抛 ERR_MODULE_NOT_FOUND。请重新安装应用或恢复应用资源目录后重试。",bundled.display()@@ -789,6 +755,160 @@ async fn ensure_inner(need.push((preset.id.clone(), name, entry));}}+ orphans.sort();+ orphans.dedup();+ Ok(InternalPluginCheck {+ manifest,+ parsed,+ need,+ orphans,+ sources_ready,+ migration_pending,+ })+}++fn require_running_plugins_ready(+ profile: &Path,+ check: &InternalPluginCheck,+) -> Result<(), String> {+ let fallback = profile+ .join(".dsh-module-fallback")+ .try_exists()+ .map_err(|error| format!("INTERNAL_PLUGIN_FALLBACK_READ_FAILED: {error}"))?;+ if check.manifest.is_none()+ || !check.sources_ready+ || !check.need.is_empty()+ || !check.orphans.is_empty()+ || check.migration_pending+ || fallback+ {+ return Err(format!(+ "INTERNAL_PLUGIN_RESTART_REQUIRED: 内置插件需要修复;请停止当前服务后通过正常启动重试(need={:?}, orphans={:?}, migration={}, sources_ready={}, fallback={})。",+ check.need.iter().map(|(id, _, _)| id.as_str()).collect::<Vec<_>>(),+ check.orphans,+ check.migration_pending,+ check.sources_ready,+ fallback,+ ));+ }+ Ok(())+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum EarlyPluginState {+ Ready,+ Defer,+}++pub(crate) fn prepare_early_plugins(+ profile: &Path,+ dsh_home: &Path,+ resources: Option<&Path>,+ manifest: Option<&config::manifest::Manifest>,+ core_version: Option<&str>,+) -> Result<EarlyPluginState, String> {+ let Some(manifest) = manifest.filter(|manifest| !manifest.plugins.built_in.is_empty()) else {+ return Ok(EarlyPluginState::Defer);+ };+ let presets = presets_from_manifest(manifest, resources);+ let deprecated = manifest.plugins.deprecated.iter().cloned().collect();+ prepare_early_plugins_from(+ profile,+ dsh_home,+ &presets,+ &deprecated,+ core_version,+ |id| bundled_plugin_dir_from(resources, id),+ )+}++fn prepare_early_plugins_from(+ profile: &Path,+ dsh_home: &Path,+ presets: &[PreinstallPluginInfo],+ deprecated: &HashSet<String>,+ core_version: Option<&str>,+ resolve_bundle: impl Fn(&str) -> Option<PathBuf>,+) -> Result<EarlyPluginState, String> {+ if presets.is_empty()+ || presets.iter().any(|preset| {+ matches!(+ preset.version,+ Some(config::manifest::PluginVersion::Matrix(_))+ )+ }) && !core_version.is_some_and(|version| semver::Version::parse(version).is_ok())+ {+ return Ok(EarlyPluginState::Defer);+ }+ let internal: Vec<_> = presets+ .iter()+ .filter(|preset| preset.internal && !preset.unsupported_on(core_version))+ .collect();+ let check = match prepare_internal_plugins(profile, dsh_home, &internal, true, resolve_bundle) {+ Ok(check) => check,+ Err(error) if error.starts_with("INTERNAL_PLUGIN_SOURCE_MISSING:") => {+ log::warn!("{error}");+ return Ok(EarlyPluginState::Defer);+ }+ Err(error) => return Err(error),+ };+ let Some(parsed) = check.parsed.as_ref() else {+ return Ok(EarlyPluginState::Defer);+ };+ if !check.sources_ready+ || !check.need.is_empty()+ || !check.orphans.is_empty()+ || profile+ .join(".dsh-module-fallback")+ .try_exists()+ .map_err(|error| format!("INTERNAL_PLUGIN_FALLBACK_READ_FAILED: {error}"))?+ {+ return Ok(EarlyPluginState::Defer);+ }+ let bundles = parsed+ .dsh+ .as_ref()+ .and_then(|dsh| dsh.profile.as_ref())+ .map(|profile| profile.bundles.as_slice())+ .unwrap_or_default();+ if !super::verify::missing_plugin_ids(+ &presets,+ &parsed.dependencies,+ bundles,+ &profile.join("node_modules"),+ )+ .is_empty()+ {+ return Ok(EarlyPluginState::Defer);+ }+ let (names, known) = deprecated_plugins_at(profile, parsed, presets, deprecated, core_version)?;+ Ok(if known && names.is_empty() {+ EarlyPluginState::Ready+ } else {+ EarlyPluginState::Defer+ })+}++async fn ensure_inner(+ app_handle: &AppHandle,+ internal: &[&PreinstallPluginInfo],+ cancel: tokio::sync::watch::Receiver<bool>,+ owner: ProcessOwner,+) -> Result<(), String> {+ let profile = profile_dir(app_handle);+ let manifest_path = profile.join("package.json");+ let InternalPluginCheck {+ mut manifest,+ need,+ orphans,+ ..+ } = prepare_internal_plugins(+ &profile,+ &config::get_dsh_data_path(app_handle),+ internal,+ true,+ |id| bundled_plugin_dir(app_handle, id),+ )?;// 卸载孤儿内置插件:best-effort、离线精准,不依赖 node/pnpm(其源目录已// 不存在,走 `dsh plugin remove` 也没有可安装的本地链接可删)。与弃用插件// 自动卸载同一模式:任何失败只记告警,绝不阻断本轮其余重装或整体启动。@@ -799,8 +919,16 @@ async fn ensure_inner(log::warn!("INTERNAL_PLUGIN_ORPHAN_SKIPPED: {name}(核心/官方包不执行孤儿卸载)");continue;}- if let Err(e) = super::uninstall_recovery(app_handle, name) {- log::warn!("INTERNAL_PLUGIN_ORPHAN_UNINSTALL_FAILED: {name}: {e}");+ match super::uninstall_recovery(app_handle, name) {+ Ok(()) => {+ if let Some(value) = manifest.as_mut() {+ remove_internal_plugins_from_manifest(+ value,+ &HashSet::from([name.as_str()]),+ );+ }+ }+ Err(e) => log::warn!("INTERNAL_PLUGIN_ORPHAN_UNINSTALL_FAILED: {name}: {e}"),}}}@@ -1204,6 +1332,165 @@ mod tests {use super::*;+ #[test]+ fn early_prepare_uses_normal_kernel_and_defers_repairs_without_installing() {+ let root = tempfile::tempdir().unwrap();+ let profile = root.path().join("profiles/web");+ let source = root.path().join("resources/builtin");+ let entry = profile.join("node_modules/builtin");+ std::fs::create_dir_all(&source).unwrap();+ std::fs::create_dir_all(&entry).unwrap();+ std::fs::write(source.join("package.json"), "{}").unwrap();+ std::fs::write(entry.join("package.json"), "{}").unwrap();+ let preset = |id: &str, internal| PreinstallPluginInfo {+ id: id.into(),+ spec: id.into(),+ internal,+ package: None,+ version: None,+ name: id.into(),+ description: String::new(),+ repo_url: String::new(),+ recommended: false,+ fix: false,+ default_checked: false,+ default_unchecked: false,+ win_only: false,+ };+ let presets = vec![preset("builtin", true), preset("community", false)];+ let deprecated = HashSet::from(["old-plugin".to_string()]);+ let path = profile.join("package.json");+ let healthy = serde_json::json!({+ "dependencies": {"builtin": bundled_dep_spec(&source)},+ "dsh": {"profile": {"bundles": ["builtin", "builtin"]}}+ });+ let check = |manifest: &serde_json::Value| {+ std::fs::write(&path, manifest.to_string()).unwrap();+ prepare_early_plugins_from(&profile, root.path(), &presets, &deprecated, None, |_| {+ Some(source.clone())+ })+ };+ std::fs::write(+ profile.join("cordis.patch.yml"),+ "- insert:\n - id: builtin\n - id: user-plugin\n",+ )+ .unwrap();+ assert_eq!(check(&healthy).unwrap(), EarlyPluginState::Ready);+ let migrated: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();+ assert_eq!(+ migrated["dsh"]["profile"]["bundles"],+ serde_json::json!(["builtin"])+ );+ assert!(std::fs::read_to_string(profile.join("cordis.patch.yml"))+ .unwrap()+ .contains("user-plugin"));+ assert_eq!(+ prepare_early_plugins_from(&profile, root.path(), &presets, &deprecated, None, |_| {+ Some(source.clone())+ })+ .unwrap(),+ EarlyPluginState::Ready+ );+ let running_root = "- id: builtin\n name: runtime-composed\n";+ std::fs::write(profile.join("cordis.yml"), running_root).unwrap();+ let running_check = || {+ prepare_internal_plugins(&profile, root.path(), &[&presets[0]], false, |_| {+ Some(source.clone())+ })+ };+ let running = running_check().unwrap();+ require_running_plugins_ready(&profile, &running).unwrap();+ assert_eq!(+ std::fs::read_to_string(profile.join("cordis.yml")).unwrap(),+ running_root+ );+ let mut needs_repair = migrated.clone();+ needs_repair["dsh"]["profile"]["bundles"] = serde_json::json!([]);+ std::fs::write(&path, needs_repair.to_string()).unwrap();+ let running = running_check().unwrap();+ assert_eq!(+ running+ .need+ .iter()+ .map(|(id, _, _)| id.as_str())+ .collect::<Vec<_>>(),+ vec!["builtin"]+ );+ assert!(require_running_plugins_ready(&profile, &running)+ .unwrap_err()+ .starts_with("INTERNAL_PLUGIN_RESTART_REQUIRED:"));+ assert_eq!(+ std::fs::read_to_string(profile.join("cordis.yml")).unwrap(),+ running_root+ );+ assert_eq!(+ std::fs::read_to_string(&path).unwrap(),+ needs_repair.to_string()+ );+ assert_eq!(+ std::fs::read_to_string(entry.join("package.json")).unwrap(),+ "{}"+ );+ std::fs::write(&path, healthy.to_string()).unwrap();+ let running = running_check().unwrap();+ assert!(running.migration_pending);+ assert!(require_running_plugins_ready(&profile, &running)+ .unwrap_err()+ .starts_with("INTERNAL_PLUGIN_RESTART_REQUIRED:"));+ assert_eq!(std::fs::read_to_string(&path).unwrap(), healthy.to_string());+ assert_eq!(check(&healthy).unwrap(), EarlyPluginState::Ready);+ assert_eq!(+ prepare_early_plugins_from(&profile, root.path(), &presets, &deprecated, None, |_| {+ None+ })+ .unwrap(),+ EarlyPluginState::Defer+ );+ std::fs::remove_file(source.join("package.json")).unwrap();+ assert_eq!(check(&healthy).unwrap(), EarlyPluginState::Defer);+ std::fs::write(source.join("package.json"), "{}").unwrap();+ let mut missing_bundle = healthy.clone();+ missing_bundle["dsh"]["profile"]["bundles"] = serde_json::json!([]);+ assert_eq!(check(&missing_bundle).unwrap(), EarlyPluginState::Defer);+ assert_eq!(+ std::fs::read_to_string(entry.join("package.json")).unwrap(),+ "{}"+ );+ let mut wrong_dep = healthy.clone();+ wrong_dep["dependencies"]["builtin"] = serde_json::json!("link:/missing/source");+ assert_eq!(check(&wrong_dep).unwrap(), EarlyPluginState::Defer);+ let mut missing_preset = healthy.clone();+ missing_preset["dependencies"]["community"] = serde_json::json!("1.0.0");+ assert_eq!(check(&missing_preset).unwrap(), EarlyPluginState::Defer);+ let mut dangling = healthy.clone();+ dangling["dependencies"]["removed"] = serde_json::json!("link:missing-source");+ assert_eq!(check(&dangling).unwrap(), EarlyPluginState::Defer);+ std::fs::create_dir_all(profile.join("node_modules/old-plugin")).unwrap();+ assert_eq!(check(&healthy).unwrap(), EarlyPluginState::Defer);+ assert!(profile.join("node_modules/old-plugin").is_dir());+ std::fs::remove_dir(profile.join("node_modules/old-plugin")).unwrap();+ std::fs::remove_file(entry.join("package.json")).unwrap();+ assert_eq!(check(&healthy).unwrap(), EarlyPluginState::Defer);+ assert!(!entry.join("package.json").exists());+ std::fs::write(&path, "{").unwrap();+ assert!(prepare_early_plugins_from(+ &profile,+ root.path(),+ &presets,+ &deprecated,+ None,+ |_| None+ )+ .unwrap_err()+ .starts_with("INTERNAL_PLUGIN_MANIFEST_PARSE_FAILED:"));+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "{");+ assert_eq!(+ prepare_early_plugins(&profile, root.path(), None, None, None).unwrap(),+ EarlyPluginState::Defer+ );+ }+#[test]fn post_install_manifest_check_rejects_missing_or_unreadable_manifest() {let root = tempfile::tempdir().unwrap();diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex 2c6d1b0c..19786ee6 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -56,40 +56,41 @@ pub mod watch;pub(crate) use crate::service::profile::ensure_profile_pnpm_policy;pub use cancel::cancel;pub(crate) use cancel::terminate_active_installs_blocking;-pub(crate) use process::{acquire_operation_lock, is_process_cleanup_failure};-pub(crate) use install::harness_prefer_bundled_pnpm;+pub use disable::{disable, enable};+pub(crate) use hmr::sync_layer_at as local_plugin_hmr_sync_at;+pub use hmr::LocalHmrStatus;+pub(crate) use hmr::{status as local_plugin_hmr_status, sync_layer as local_plugin_hmr_sync};+pub(crate) use install::harness_prefer_bundled_pnpm_from;pub(crate) use install::local_spec_from_path;-pub(crate) use install::uninstall_deprecated_plugins;pub(crate) use install::packument;+pub(crate) use install::uninstall_deprecated_plugins;pub use install::{allow_policy_versions, allow_version_exemptions, inspect_specs, install, install_specs,remove_many, update_many, IncompatibleVersion, PolicyBlockedVersion,};pub(crate) use installed::{- declared_packages, ensure_profile_npmrc, installed_name, list_installed, profile_dir,- ProfilePackageJson,+ declared_packages, ensure_npmrc_at, ensure_profile_npmrc, installed_name, list_installed,+ profile_dir, ProfilePackageJson,};pub use installed::{list, PreinstallPlugin};-pub(crate) use hmr::{status as local_plugin_hmr_status, sync_layer as local_plugin_hmr_sync};-pub use hmr::LocalHmrStatus;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::{- bundled_plugin_dir, current_preset_hash, load_presets, preinstall_pending,- remove_legacy_bundled_plugins,-};-pub(crate) use safe::purge_user_plugins_in_safe_profile;+pub(crate) use internal::{prepare_early_plugins, EarlyPluginState};+pub(crate) use patch_entries::{strip_active_unresolved_entries, PatchEntryStripReport};+pub(crate) use patch_guard::preflight_at as preflight_patch_entries_at;pub(crate) use patch_guard::{patch_layer_paths, quarantine_active_patch_layers, quarantine_failure_message,quarantine_patch_layers_in, PatchQuarantineReport,};-pub(crate) use patch_entries::{- preflight_active_patch_entries, strip_active_unresolved_entries, PatchEntryStripReport,+pub use preset::repo_url_of;+pub(crate) use preset::{+ bundled_plugin_dir, bundled_plugin_dir_from, current_preset_hash, load_presets,+ preinstall_pending, presets_from_manifest, remove_legacy_bundled_plugins,};-pub use disable::{disable, enable};+pub(crate) use process::{acquire_operation_lock, is_process_cleanup_failure};pub use recovery::{detect as detect_recovery, uninstall as uninstall_recovery, PluginRecoveryInfo,};+pub(crate) use safe::purge_user_plugins_in_safe_profile;pub(crate) use verify::ensure_preset_plugins;pub use watch::DshPlugin;diff --git a/src-tauri/src/service/plugin/patch_entries.rs b/src-tauri/src/service/plugin/patch_entries.rsindex 0301385b..0dfaca0f 100644--- a/src-tauri/src/service/plugin/patch_entries.rs+++ b/src-tauri/src/service/plugin/patch_entries.rs@@ -78,27 +78,6 @@ pub(crate) fn unresolved_entries_message(entries: &[UnresolvedPatchEntry]) -> Stformat!("{PATCH_ENTRY_UNRESOLVED}: {payload}")}-/// 启动前预检:补丁层引用了装不出来的包时,用可操作的错误替代 loader 的裸堆栈。-///-/// 只在「必然被挂载」的条目上阻断(见模块说明):这类条目本来就会让本次启动失败,-/// 提前报错不改变结果,只是把原因说清楚并给出恢复入口。-pub(crate) fn preflight_active_patch_entries(app_handle: &AppHandle) -> Result<(), String> {- let profile = super::installed::profile_dir(app_handle);- let dsh_home = crate::config::get_dsh_data_path(app_handle);- let install_anchor = crate::service::core::active_dsh_binary(app_handle);- let entries = scan_unresolved_entries_in(&profile, &dsh_home, Some(&install_anchor));- if entries.is_empty() {- return Ok(());- }- let names = entries- .iter()- .map(|entry| format!("{}:{} {}", entry.layer, entry.line, entry.name))- .collect::<Vec<_>>()- .join(", ");- log::error!("{PATCH_ENTRY_UNRESOLVED}: {names}");- Err(unresolved_entries_message(&entries))-}-/// 从「当前档案层 + home 层」移除解析不到的 `insert` 条目并返回备份路径。pub(crate) fn strip_active_unresolved_entries(app_handle: &AppHandle,diff --git a/src-tauri/src/service/plugin/patch_guard.rs b/src-tauri/src/service/plugin/patch_guard.rsindex 457c4d88..49ff3a1d 100644--- a/src-tauri/src/service/plugin/patch_guard.rs+++ b/src-tauri/src/service/plugin/patch_guard.rs@@ -19,6 +19,9 @@ use std::path::{Path, PathBuf};use tauri::AppHandle;+use super::patch_entries::{+ scan_unresolved_entries_in, unresolved_entries_message, PATCH_ENTRY_UNRESOLVED,+};use super::profile_dir;use crate::config;@@ -76,6 +79,24 @@ pub(crate) fn patch_layer_paths(profile_dir: &Path, dsh_home: &Path) -> [PathBuf]}+pub(crate) fn preflight_at(+ profile: &Path,+ data_home: &Path,+ install_anchor: Option<&Path>,+) -> Result<(), String> {+ let entries = scan_unresolved_entries_in(profile, data_home, install_anchor);+ if entries.is_empty() {+ return Ok(());+ }+ let names = entries+ .iter()+ .map(|entry| format!("{}:{} {}", entry.layer, entry.line, entry.name))+ .collect::<Vec<_>>()+ .join(", ");+ log::error!("{PATCH_ENTRY_UNRESOLVED}: {names}");+ Err(unresolved_entries_message(&entries))+}+/// 解析补丁层:语法错误时返回 serde_yaml 的错误文本(含行列号)。////// 文件不存在、读不出来(权限错位/竞态)都不算语法错误——那些由可写性预检与@@ -218,6 +239,53 @@ mod tests {"#;const VALID_LAYER: &str = "- id: dsh-base\n disabled: false\n";+ #[test]+ fn preflight_at_rereads_both_layers_and_uses_the_real_install_anchor_resolution() {+ let temp = tempfile::tempdir().unwrap();+ let home = temp.path().join("home");+ let profile = home.join("profiles/probe");+ std::fs::create_dir_all(&profile).unwrap();+ let manifest = profile.join("package.json");+ std::fs::write(+ &manifest,+ r#"{"dependencies":{"dsh-preflight-probe":"1.0.0"}}"#,+ )+ .unwrap();+ let layer = "- insert:\n - id: probe\n name: dsh-preflight-probe\n";+ let paths = patch_layer_paths(&profile, &home);+ for path in &paths {+ std::fs::write(path, layer).unwrap();+ }++ let error = preflight_at(&profile, &home, None).unwrap_err();+ let payload: serde_json::Value = serde_json::from_str(+ error+ .strip_prefix("PATCH_LAYER_ENTRY_UNRESOLVED: ")+ .unwrap(),+ )+ .unwrap();+ let entries = payload["entries"].as_array().unwrap();+ assert_eq!(entries.len(), 2);+ for (entry, path) in entries.iter().zip(&paths) {+ assert_eq!(entry["layer"], path.display().to_string());+ assert_eq!(entry["line"], 3);+ assert_eq!(entry["name"], "dsh-preflight-probe");+ assert_eq!(entry["declared"], true);+ assert_eq!(std::fs::read_to_string(path).unwrap(), layer);+ }++ let anchor = temp.path().join("core/lib/bin.js");+ let installed = temp.path().join("core/node_modules/dsh-preflight-probe");+ std::fs::create_dir_all(&installed).unwrap();+ let package = installed.join("package.json");+ std::fs::write(&package, "{}\n").unwrap();+ assert_eq!(preflight_at(&profile, &home, Some(&anchor)), Ok(()));+ std::fs::remove_file(package).unwrap();+ assert!(preflight_at(&profile, &home, Some(&anchor))+ .unwrap_err()+ .starts_with("PATCH_LAYER_ENTRY_UNRESOLVED: "));+ }+#[test]fn parse_error_reports_unquoted_js_expression() {let dir = tmp_dir("parse-error");diff --git a/src-tauri/src/service/plugin/preset.rs b/src-tauri/src/service/plugin/preset.rsindex b66aba0d..8c0e53d0 100644--- a/src-tauri/src/service/plugin/preset.rs+++ b/src-tauri/src/service/plugin/preset.rs@@ -9,7 +9,7 @@ use std::path::{Path, PathBuf};use tauri::{AppHandle, Manager};use crate::config;-use crate::config::manifest::{PluginEntry, PluginVersion};+use crate::config::manifest::{Manifest, PluginEntry, PluginVersion};/// 插件静态信息,对应清单中的条目#[derive(Debug, Clone)]@@ -314,14 +314,16 @@ fn find_bundled_in_root(root: &std::path::Path, id: &str) -> Option<PathBuf> {/// git、无需构建期打包;仓库里不存在该 id 时回落随包目录,让开发与发布共用一套/// 兜底逻辑。pub(crate) fn bundled_plugin_dir(app_handle: &AppHandle, id: &str) -> Option<PathBuf> {+ bundled_plugin_dir_from(app_handle.path().resource_dir().ok().as_deref(), id)+}++pub(crate) fn bundled_plugin_dir_from(resources: Option<&Path>, id: &str) -> Option<PathBuf> {#[cfg(debug_assertions)]if let Some(dir) = dev_plugin_dir(id) {return Some(dir);}- if let Ok(dir) = app_handle.path().resource_dir() {- if let Some(candidate) = find_bundled_in_root(&dir, id) {- return Some(candidate);- }+ if let Some(candidate) = resources.and_then(|root| find_bundled_in_root(root, id)) {+ return Some(candidate);}let resources = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources");let deployed = resources.join("node_modules").join(id);@@ -346,8 +348,8 @@ struct PluginPackageJson {/// 在两处各存一份、升级时互相漂移。debug 的 dev 发现与 release 的随包清单最终都落到/// 同一个 `package.json`,两种构建因此得到同值。读取失败(目录缺失、JSON 损坏、/// 描述为空)返回 `None`,调用方沿用清单登记的空描述——不阻断启动。-fn bundled_plugin_description(app_handle: &AppHandle, id: &str) -> Option<String> {- let dir = bundled_plugin_dir(app_handle, id)?;+fn bundled_plugin_description(resources: Option<&Path>, id: &str) -> Option<String> {+ let dir = bundled_plugin_dir_from(resources, id)?;let raw = std::fs::read_to_string(dir.join("package.json")).ok()?;package_json_description(&raw)}@@ -442,30 +444,35 @@ pub(crate) fn load_presets(app_handle: &AppHandle) -> Vec<PreinstallPluginInfo>let Some(manifest) = config::manifest::read(app_handle) else {return Vec::new();};+ presets_from_manifest(&manifest, app_handle.path().resource_dir().ok().as_deref())+}++pub(crate) fn presets_from_manifest(+ manifest: &Manifest,+ resources: Option<&Path>,+) -> Vec<PreinstallPluginInfo> {let mut plugins: Vec<PreinstallPluginInfo> = manifest.plugins.preset- .into_iter()+ .iter()+ .cloned().map(|entry| plugin_info(entry, false)).collect();let internal: Vec<PreinstallPluginInfo> = manifest.plugins.built_in- .into_iter()+ .iter()+ .cloned().map(|entry| plugin_info(entry, true)).collect();#[cfg(debug_assertions)]let internal = merge_dev_internal_plugins(internal);- let internal: Vec<PreinstallPluginInfo> = internal- .into_iter()- .map(|mut plugin| {- if let Some(description) = bundled_plugin_description(app_handle, &plugin.id) {- plugin.description = description;- }- plugin- })- .collect();- plugins.extend(internal);+ plugins.extend(internal.into_iter().map(|mut plugin| {+ if let Some(description) = bundled_plugin_description(resources, &plugin.id) {+ plugin.description = description;+ }+ plugin+ }));plugins}diff --git a/src-tauri/src/service/plugin/verify.rs b/src-tauri/src/service/plugin/verify.rsindex 0beac63c..a925d75c 100644--- a/src-tauri/src/service/plugin/verify.rs+++ b/src-tauri/src/service/plugin/verify.rs@@ -36,7 +36,7 @@ use super::process::is_process_cleanup_failure;/// 命中条件:插件被 profile 清单引用(`dependencies` 键或 `dsh.profile.bundles`/// 列表,按实际 npm 包名 `installed_name`),但其包目录在 `node_modules` 下/// 缺少 `package.json`(目录不存在、被删、或只是残壳都不算就绪)。-fn missing_plugin_ids(+pub(super) fn missing_plugin_ids(presets: &[PreinstallPluginInfo],dependencies: &HashMap<String, String>,bundles: &[String],diff --git a/src-tauri/src/service/profile/mod.rs b/src-tauri/src/service/profile/mod.rsindex 675cbc74..00ab0f1e 100644--- a/src-tauri/src/service/profile/mod.rs+++ b/src-tauri/src/service/profile/mod.rs@@ -996,12 +996,18 @@ fn atomic_write(path: &Path, content: &str, code: &str) -> Result<(), String> {/// 形态:宿主不提供 webServer/connection,内置插件恒为 pending,服务必然启动/// 失败)时补齐并写回,令本轮启动即可恢复。pub fn ensure_active_profile_core_bundles(app_handle: &AppHandle) -> Result<bool, String> {- let id = active_profile(app_handle);- let dir = profile_dir_of(app_handle, &id);+ prepare_at(+ &config::get_dsh_data_path(app_handle),+ &active_profile(app_handle),+ )+}++pub(crate) fn prepare_at(data_home: &Path, id: &str) -> Result<bool, String> {+ let dir = fs_guard::join_safe(&data_home.join("profiles"), id)?;if !dir.is_dir() {return Ok(false);}- ensure_profile_core_bundles(&dir, &id)+ ensure_profile_core_bundles(&dir, id)}/// 初始化档案目录:与官方 `dsh-app-boot::initProfile` 的产物一致@@ -1189,6 +1195,48 @@ mod clone_tests {mod tests {use super::*;+ #[test]+ fn prepare_at_rereads_the_explicit_profile_without_creating_missing_directories() {+ let home = tempfile::tempdir().unwrap();+ let dir = home.path().join("profiles/beta");+ assert!(!prepare_at(home.path(), "beta").unwrap());+ assert!(!dir.exists());+ assert!(prepare_at(home.path(), "../beta")+ .unwrap_err()+ .starts_with("INVALID_ID:"));++ fs::create_dir_all(&dir).unwrap();+ let path = dir.join("package.json");+ fs::write(+ &path,+ r#"{"dependencies":{"user-plugin":"1.0.0"},"dsh":{"profile":{"bundles":["user-plugin"]}}}"#,+ )+ .unwrap();+ let patch = dir.join("cordis.patch.yml");+ fs::write(&patch, "# user patch\n[]\n").unwrap();+ assert!(prepare_at(home.path(), "beta").unwrap());+ let repaired = fs::read_to_string(&path).unwrap();+ let manifest: serde_json::Value = serde_json::from_str(&repaired).unwrap();+ assert_eq!(+ manifest["dsh"]["profile"]["bundles"],+ serde_json::json!([+ "@deepseek-ai/dsh-base",+ "@deepseek-ai/dsh-web-app",+ "user-plugin"+ ])+ );+ assert_eq!(manifest["dependencies"]["user-plugin"], "1.0.0");+ assert!(!prepare_at(home.path(), "beta").unwrap());+ assert_eq!(fs::read_to_string(&path).unwrap(), repaired);++ fs::write(&path, "{ broken").unwrap();+ assert!(prepare_at(home.path(), "beta")+ .unwrap_err()+ .starts_with("PROFILE_MANIFEST_PARSE_FAILED:"));+ assert_eq!(fs::read_to_string(&path).unwrap(), "{ broken");+ assert_eq!(fs::read_to_string(patch).unwrap(), "# user patch\n[]\n");+ }+#[test]fn normalize_id_lowercases_and_joins() {assert_eq!(normalize_profile_id("My Work Space"), "my-work-space");diff --git a/src-tauri/src/service/workflow/early.rs b/src-tauri/src/service/workflow/early.rsnew file mode 100644index 00000000..37c2142c--- /dev/null+++ b/src-tauri/src/service/workflow/early.rs@@ -0,0 +1,535 @@+use std::sync::{Arc, OnceLock};++struct Preparation {+ worker: tokio::sync::watch::Receiver<Option<Result<bool, String>>>,+ settled: tokio::sync::watch::Receiver<Option<Result<(), String>>>,+ setup_done: std::sync::Mutex<Option<tokio::sync::watch::Sender<Option<Result<(), String>>>>>,+}++static PREPARATION: OnceLock<Preparation> = OnceLock::new();++#[cfg(windows)]+struct Probe {+ job: Arc<super::win_spawn::ProcessJob>,+ failed: bool,+ fatal: Option<String>,+}++#[cfg(windows)]+thread_local! {+ static PROBE: std::cell::RefCell<Option<Probe>> = const { std::cell::RefCell::new(None) };+}++#[cfg(windows)]+pub(crate) fn probe_output(+ program: &std::path::Path,+ args: &[&str],+ remove_node_options: bool,+) -> Option<std::io::Result<std::process::Output>> {+ let job = PROBE+ .with(|probe| {+ probe.borrow().as_ref().map(|probe| match &probe.fatal {+ Some(error) => Err(std::io::Error::other(error.clone())),+ None => Ok(probe.job.clone()),+ })+ })+ .or_else(|| {+ PREPARATION.get().and_then(|preparation| {+ let error = match preparation.worker.borrow().as_ref() {+ Some(Err(error)) => Some(error.clone()),+ None if preparation.worker.has_changed().is_err() => {+ Some("STARTUP_PREPARATION_INTERRUPTED".to_string())+ }+ _ => preparation+ .settled+ .borrow()+ .as_ref()+ .and_then(|result| result.as_ref().err())+ .cloned(),+ };+ error.map(|error| Err(std::io::Error::other(error)))+ })+ })?;+ let job = match job {+ Ok(job) => job,+ Err(error) => return Some(Err(error)),+ };+ let args: Vec<_> = args.iter().map(std::ffi::OsString::from).collect();+ let started = std::time::Instant::now();+ let result = super::win_spawn::probe_in_job(+ program,+ &args,+ &job,+ super::instances::registration_gate(),+ remove_node_options,+ );+ log::info!(+ "STARTUP_EARLY_PROBE: program={} ms={} success={}",+ program.display(),+ started.elapsed().as_millis(),+ result.as_ref().is_ok_and(|output| output.status.success())+ );+ if let Err(error) = &result {+ PROBE.with(|probe| {+ if let Some(probe) = probe.borrow_mut().as_mut() {+ probe.failed = true;+ if error+ .get_ref()+ .is_some_and(|error| error.is::<super::win_spawn::ProcessCleanupFailed>())+ {+ probe.fatal = Some(format!("STARTUP_PROBE_CLEANUP_FAILED: {error}"));+ }+ }+ });+ }+ Some(result)+}++#[cfg(windows)]+fn prepare_in_job(+ app_data: &std::path::Path,+ resources: &std::path::Path,+ job: Arc<super::win_spawn::ProcessJob>,+) -> Result<Option<super::launch::LaunchPlan>, String> {+ struct Restore(Option<Probe>);+ impl Drop for Restore {+ fn drop(&mut self) {+ PROBE.with(|probe| *probe.borrow_mut() = self.0.take());+ }+ }+ let _restore = Restore(PROBE.with(|probe| {+ probe.replace(Some(Probe {+ job,+ failed: false,+ fatal: None,+ }))+ }));+ let plan = super::early_plan::prepare(app_data, resources);+ if !probes_ready()? {+ Ok(None)+ } else {+ plan+ }+}++#[cfg(windows)]+pub(super) fn probes_ready() -> Result<bool, String> {+ PROBE.with(|probe| match probe.borrow().as_ref() {+ Some(probe) => match &probe.fatal {+ Some(error) => Err(error.clone()),+ None => Ok(!probe.failed),+ },+ None => Ok(true),+ })+}++impl Preparation {+ async fn wait(&self) -> Result<(), String> {+ let mut receiver = self.settled.clone();+ let result = receiver+ .wait_for(Option::is_some)+ .await+ .map_err(|_| "STARTUP_PREPARATION_INTERRUPTED".to_string())?+ .as_ref()+ .expect("settled preparation")+ .clone();+ result+ }++ async fn setup(&self, setup: impl FnOnce(bool)) {+ let mut receiver = self.worker.clone();+ let complete = self+ .setup_done+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .take();+ let prepared = receiver+ .wait_for(Option::is_some)+ .await+ .ok()+ .and_then(|ready| ready.as_ref().cloned())+ .unwrap_or_else(|| Err("STARTUP_PREPARATION_INTERRUPTED".to_string()));+ let result = prepared.map(|prepared| setup(prepared));+ if let Err(error) = &result {+ log::error!("STARTUP_PREPARATION_FAILED: {error}");+ }+ if let Some(complete) = complete {+ let _ = complete.send(Some(result));+ }+ }+}++pub(crate) async fn wait_preparation() -> Result<(), String> {+ if let Some(preparation) = PREPARATION.get() {+ preparation.wait().await?;+ }+ Ok(())+}++pub(crate) fn setup(setup: impl FnOnce(bool) + Send + 'static) {+ if let Some(preparation) = PREPARATION.get() {+ tauri::async_runtime::spawn(preparation.setup(setup));+ } else {+ setup(false);+ }+}++#[cfg(windows)]+struct Cleanup {+ profile: String,+ marker: std::path::PathBuf,+ port: u16,+ entry: std::path::PathBuf,+}++pub(crate) struct Startup {+ notifications: Arc<OnceLock<tauri::AppHandle>>,+ #[cfg(windows)]+ job: Option<Arc<super::win_spawn::ProcessJob>>,+ #[cfg(windows)]+ cleanup: Arc<std::sync::Mutex<Option<Cleanup>>>,+}++impl Startup {+ pub(crate) fn begin(+ context: &tauri::Context<tauri::Wry>,+ #[cfg(all(windows, not(debug_assertions)))] single_instance: Arc<+ crate::desktop::single_instance::SingleInstance,+ >,+ ) -> Self {+ let startup = Self {+ notifications: Arc::new(OnceLock::new()),+ #[cfg(windows)]+ job: None,+ #[cfg(windows)]+ cleanup: Arc::default(),+ };+ #[cfg(windows)]+ return startup.start(+ context,+ #[cfg(not(debug_assertions))]+ single_instance,+ );+ #[cfg(not(windows))]+ {+ let _ = context;+ startup+ }+ }++ pub(crate) fn attach(&self, app: &tauri::AppHandle) {+ let _ = self.notifications.set(app.clone());+ }++ pub(crate) fn shutdown(&self) {+ super::instances::begin_shutdown();+ #[cfg(windows)]+ {+ if let Some(job) = &self.job {+ if let Err(error) = job.terminate() {+ log::error!("STARTUP_JOB_CLEANUP_FAILED: {error}");+ }+ }+ let cleanup = self+ .cleanup+ .lock()+ .unwrap_or_else(|error| error.into_inner());+ if let Some(cleanup) = cleanup.as_ref() {+ super::instances::scope_sync(cleanup.profile.clone(), || {+ if let Err(error) = super::process::stop_instance_at(+ &cleanup.marker,+ cleanup.port,+ &cleanup.entry,+ ) {+ log::error!("STARTUP_CLEANUP_FAILED: {error}");+ }+ });+ }+ }+ }++ #[cfg(windows)]+ fn start(+ mut self,+ context: &tauri::Context<tauri::Wry>,+ #[cfg(not(debug_assertions))] single_instance: Arc<+ crate::desktop::single_instance::SingleInstance,+ >,+ ) -> Self {+ let started = std::time::Instant::now();+ let Some(app_data) = app_data_dir(context.config()) else {+ return self;+ };+ if crate::config::detect_first_install_at(Some(&app_data)) {+ return self;+ }+ let Ok(resources) = tauri::utils::platform::resource_dir(+ context.package_info(),+ &tauri::utils::Env::default(),+ ) else {+ return self;+ };+ let Some(profile) = super::early_plan::profile(&app_data) else {+ return self;+ };+ let Some(entry) = super::early_plan::entry(&app_data, &resources) else {+ return self;+ };+ let job = match super::win_spawn::ProcessJob::new() {+ Ok(job) => Arc::new(job),+ Err(error) => {+ log::warn!("STARTUP_JOB_UNAVAILABLE: {error}");+ return self;+ }+ };+ let (complete, worker) = tokio::sync::watch::channel(None);+ let (setup_done, settled) = tokio::sync::watch::channel(None);+ if PREPARATION+ .set(Preparation {+ worker,+ settled,+ setup_done: std::sync::Mutex::new(Some(setup_done)),+ })+ .is_err()+ {+ return self;+ }+ let notifications = self.notifications.clone();+ let cleanup = self.cleanup.clone();+ let worker_job = job.clone();+ let worker_complete = complete.clone();+ self.job = Some(job);+ if let Err(error) = std::thread::Builder::new()+ .name("harness-prepare".into())+ .spawn(move || {+ #[cfg(not(debug_assertions))]+ let _single_instance = single_instance;+ log::info!(+ "STARTUP_EARLY_PHASE: name=worker_started elapsed_ms={}",+ started.elapsed().as_millis()+ );+ let result = super::instances::scope_sync(profile.clone(), || {+ tauri::async_runtime::block_on(async {+ let transition = super::process::acquire_core_transition().await?;+ let flag = super::process::launch_guard();+ if flag+ .compare_exchange(+ false,+ true,+ std::sync::atomic::Ordering::SeqCst,+ std::sync::atomic::Ordering::SeqCst,+ )+ .is_err()+ {+ return Ok(false);+ }+ let guard = super::process::LaunchGuard(flag);+ let _operation = crate::service::plugin::acquire_operation_lock().await;+ if super::early_plan::entry(&app_data, &resources).as_ref() != Some(&entry)+ {+ return Ok(false);+ }+ log::info!(+ "STARTUP_EARLY_PHASE: name=prepare_started elapsed_ms={}",+ started.elapsed().as_millis()+ );+ if super::process::take_startup_sweep() {+ if let Err(error) =+ super::process::terminate_stale_harness_processes_at(&entry)+ {+ super::process::retry_startup_sweep();+ return Err(error);+ }+ }+ let home = crate::config::dsh_data_path_from_env();+ crate::service::perm::ensure_dir_writable(&home, "DSH_HOME_MKDIR_FAILED")?;+ crate::service::perm::ensure_writable_path(+ &home.join("profiles").join(&profile),+ &home,+ "PROFILE_NOT_WRITABLE",+ )?;+ let Some(plan) = prepare_in_job(&app_data, &resources, worker_job.clone())?+ else {+ log::debug!("STARTUP_EARLY_DEFER: normal preparation required");+ return Ok(false);+ };+ if plan.dsh_binary != entry+ || super::utils::is_port_in_use(plan.setting.port)+ {+ return Ok(false);+ }+ {+ let shutdown = super::instances::registration_gate()+ .lock()+ .unwrap_or_else(|error| error.into_inner());+ if *shutdown {+ return Ok(false);+ }+ *cleanup.lock().unwrap_or_else(|error| error.into_inner()) =+ Some(Cleanup {+ profile: profile.clone(),+ marker: plan.pid_path.clone(),+ port: plan.setting.port,+ entry,+ });+ }+ super::instances::set_port(plan.setting.port);+ super::status::set_status(super::status::Status::Starting);+ log::info!(+ "STARTUP_EARLY_PHASE: name=prepared elapsed_ms={}",+ started.elapsed().as_millis()+ );+ super::launch::launch_prepared(+ plan,+ (guard, transition),+ notifications,+ Some(worker_job),+ )+ .await?;+ log::info!(+ "STARTUP_EARLY_PHASE: name=registered elapsed_ms={}",+ started.elapsed().as_millis()+ );+ Ok(true)+ })+ });+ if let Err(error) = &result {+ log::error!("STARTUP_EARLY_FAILED: {error}");+ }+ let _ = worker_complete.send(Some(result));+ })+ {+ log::warn!("STARTUP_EARLY_THREAD_FAILED: {error}");+ let _ = complete.send(Some(Ok(false)));+ }+ self+ }+}++impl Drop for Startup {+ fn drop(&mut self) {+ self.shutdown();+ }+}++#[cfg(windows)]+fn app_data_dir(config: &tauri::utils::config::Config) -> Option<std::path::PathBuf> {+ use tauri::utils::config::AppDirectoriesOverride;++ let path = match config.app.app_directories_override.as_ref() {+ Some(AppDirectoriesOverride::Root(path)) => Some(path),+ Some(AppDirectoriesOverride::Directories(paths)) => paths.data.as_ref(),+ None => None,+ };+ if let Some(path) = path {+ return path.is_absolute().then(|| path.components().collect());+ }+ roaming_app_data_dir(&config.identifier)+}++#[cfg(windows)]+fn roaming_app_data_dir(identifier: &str) -> Option<std::path::PathBuf> {+ use std::os::windows::ffi::OsStringExt;+ use windows_sys::Win32::System::Com::CoTaskMemFree;+ use windows_sys::Win32::UI::Shell::{FOLDERID_RoamingAppData, SHGetKnownFolderPath};++ let mut path = std::ptr::null_mut();+ let result = unsafe {+ SHGetKnownFolderPath(&FOLDERID_RoamingAppData, 0, std::ptr::null_mut(), &mut path)+ };+ let directory = if result >= 0 && !path.is_null() {+ let length = (0..)+ .take_while(|offset| unsafe { *path.add(*offset) != 0 })+ .count();+ Some(+ std::path::PathBuf::from(std::ffi::OsString::from_wide(unsafe {+ std::slice::from_raw_parts(path, length)+ }))+ .join(identifier),+ )+ } else {+ None+ };+ unsafe { CoTaskMemFree(path.cast()) };+ directory+}++#[cfg(test)]+mod tests {+ #[cfg(windows)]+ #[test]+ fn absolute_app_data_overrides_match_tauri() {+ use tauri::utils::config::{AppDirectoriesOverride, AppDirectoryOverrides};+ use tauri::Manager;++ let root = tempfile::tempdir().unwrap();+ let path = root.path().join(".").join("data").join("..").join("store");+ for directory in [+ AppDirectoriesOverride::Root(path.clone()),+ AppDirectoriesOverride::Directories(AppDirectoryOverrides {+ data: Some(path.clone()),+ ..Default::default()+ }),+ ] {+ let mut context = tauri::test::mock_context(tauri::test::noop_assets());+ context.config_mut().app.app_directories_override = Some(directory);+ let early = super::app_data_dir(context.config()).unwrap();+ let app = tauri::test::mock_builder().build(context).unwrap();+ assert_eq!(early, app.path().app_data_dir().unwrap());+ assert_eq!(early, path.components().collect::<std::path::PathBuf>());+ }+ let mut context: tauri::Context<tauri::test::MockRuntime> =+ tauri::test::mock_context(tauri::test::noop_assets());+ for path in ["relative", "$DATA/store", r"C:store", r"\store"] {+ context.config_mut().app.app_directories_override =+ Some(AppDirectoriesOverride::Root(path.into()));+ assert_eq!(super::app_data_dir(context.config()), None, "{path}");+ }+ }++ #[tokio::test]+ async fn preparation_blocks_launch_until_worker_and_setup_finish() {+ for result in [+ Some(Ok(true)),+ Some(Ok(false)),+ Some(Err("STARTUP_PROBE_CLEANUP_FAILED: fixture".to_string())),+ None,+ ] {+ let (worker_done, worker) = tokio::sync::watch::channel(None);+ let (setup_done, settled) = tokio::sync::watch::channel(None);+ let preparation = super::Preparation {+ worker,+ settled,+ setup_done: std::sync::Mutex::new(Some(setup_done)),+ };+ let called = std::cell::Cell::new(None);+ let setup = preparation.setup(|prepared| called.set(Some(prepared)));+ tokio::pin!(setup);+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(10), &mut setup)+ .await+ .is_err()+ );+ assert_eq!(called.get(), None);+ if let Some(result) = &result {+ worker_done.send(Some(result.clone())).unwrap();+ }+ drop(worker_done);+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(10), preparation.wait())+ .await+ .is_err()+ );+ setup.await;+ let expected =+ result.unwrap_or_else(|| Err("STARTUP_PREPARATION_INTERRUPTED".to_string()));+ assert_eq!(called.get(), expected.as_ref().ok().copied());+ assert_eq!(+ tokio::time::timeout(std::time::Duration::from_millis(100), preparation.wait())+ .await+ .unwrap(),+ expected.map(|_| ())+ );+ }+ }+}diff --git a/src-tauri/src/service/workflow/early_plan.rs b/src-tauri/src/service/workflow/early_plan.rsnew file mode 100644index 00000000..76856eb3--- /dev/null+++ b/src-tauri/src/service/workflow/early_plan.rs@@ -0,0 +1,407 @@+use crate::config::{self, dependencies as deps, manifest};+use crate::service::{cli, core, patch, plugin, profile as profiles};+use std::fs;+use std::path::{Path, PathBuf};++struct Inputs {+ setting: config::Setting,+ base: PathBuf,+ resource_root: PathBuf,+ manifest: manifest::Manifest,+ mapping: deps::DependencyMapping,+ dsh_home: PathBuf,+}++impl Inputs {+ fn root(&self, key: &str) -> PathBuf {+ deps::active_root_from(+ &self.base,+ Some(&self.resource_root),+ Some(&self.manifest),+ &self.mapping,+ key,+ )+ }++ fn binary(&self, key: &str) -> PathBuf {+ self.root(key)+ .join(deps::entry_relative_from(Some(&self.manifest), key))+ }+}++fn read_json(path: &Path) -> Option<serde_json::Value> {+ serde_json::from_slice(&fs::read(path).ok()?).ok()+}++fn read_setting(app_data: &Path) -> Option<config::Setting> {+ if !app_data.is_absolute() {+ return None;+ }+ let store = read_json(&app_data.join(config::store_dat_file_name()))?;+ let raw = store.get(config::STORE_SETTING_KEY)?;+ let value = config::unwrap_json_value(raw);+ if value.get("active_profile")?.as_str()? != profiles::DESKTOP_PROFILE+ || value.get("active_core")?.as_str()? != "app"+ {+ return None;+ }+ let setting = config::setting_from_value(Some(raw));+ (setting.installed && setting.auto_start && setting.port != 0).then_some(setting)+}++pub(super) fn profile(app_data: &Path) -> Option<String> {+ if !cfg!(windows) || config::is_first_install() {+ return None;+ }+ Some(read_setting(app_data)?.active_profile)+}++fn resolve(app_data: &Path, resources: &Path) -> Option<Inputs> {+ if !cfg!(windows)+ || config::is_first_install()+ || std::env::var_os("NODE_OPTIONS").is_some_and(|value| !value.is_empty())+ || !resources.is_absolute()+ || !resources.is_dir()+ {+ return None;+ }+ let setting = read_setting(app_data)?;+ let base = config::base_dir_from(|| app_data.to_path_buf());+ let resource_root = manifest::resource_root_from(resources);+ if !base.is_absolute() || !base.is_dir() || !resource_root.is_dir() {+ return None;+ }+ let path = manifest::manifest_path_from(Some(&resource_root), cfg!(debug_assertions))?;+ let manifest = manifest::read_at(&path).ok()?;+ let mapping = deps::read_mapping_at(&base.join(deps::MAPPING_FILE));+ let dsh_home = config::dsh_data_path_from_env();+ if !dsh_home.is_absolute() || !dsh_home.is_dir() {+ return None;+ }+ let profiles = dsh_home.join("profiles");+ if profiles.join("desktop").try_exists().ok()? {+ return None;+ }+ let package = read_json(+ &profiles+ .join(profiles::DESKTOP_PROFILE)+ .join("package.json"),+ )?;+ if !package.is_object()+ || package.get("name").and_then(|value| value.as_str()) == Some("dsh-profile-desktop")+ {+ return None;+ }+ for root in [resources.to_path_buf(), resources.join("resources")] {+ for legacy in ["preset-plugins", "internal-plugins"] {+ if root.join(legacy).try_exists().ok()? {+ return None;+ }+ }+ }+ let inputs = Inputs {+ setting,+ base,+ resource_root,+ manifest,+ mapping,+ dsh_home,+ };+ let root = inputs.root(deps::DEP_DSH);+ let entry = inputs.binary(deps::DEP_DSH);+ (root.is_absolute() && root.is_dir() && entry.is_absolute() && entry.is_file())+ .then_some(inputs)+}++pub(super) fn entry(app_data: &Path, resources: &Path) -> Option<PathBuf> {+ Some(resolve(app_data, resources)?.binary(deps::DEP_DSH))+}++fn exact_core_version(inputs: &Inputs, core_root: &Path) -> Option<String> {+ let package = read_json(&core_root.join(config::DSH_MANIFEST_RELATIVE))?;+ let direct = package.get("name").and_then(|value| value.as_str()) == Some("@deepseek-ai/dsh");+ if direct && package.pointer("/dependencies/@deepseek-ai~1dsh").is_some() {+ return None;+ }+ let version = if direct {+ package.get("version")?.as_str()?+ } else {+ package+ .get("dependencies")?+ .get("@deepseek-ai/dsh")?+ .as_str()?+ };+ semver::Version::parse(version).ok()?;+ if !direct {+ let installed = read_json(&core_root.join("node_modules/@deepseek-ai/dsh/package.json"))?;+ if installed.get("name").and_then(|value| value.as_str()) != Some("@deepseek-ai/dsh")+ || installed.get("version").and_then(|value| value.as_str()) != Some(version)+ {+ return None;+ }+ }+ let managed = deps::managed_root_from(+ &inputs.base,+ Some(&inputs.resource_root),+ Some(&inputs.manifest),+ deps::DEP_DSH,+ );+ let bundled = managed != inputs.resource_root+ && managed.starts_with(&inputs.resource_root)+ && managed == core_root;+ if !bundled+ && inputs+ .setting+ .dsh_pkg_tag+ .as_deref()+ .and_then(crate::service::download::parse_version_from_tag)+ .as_deref()+ != Some(version)+ {+ return None;+ }+ Some(version.to_string())+}++pub(super) fn prepare(+ app_data: &Path,+ resources: &Path,+) -> Result<Option<super::launch::LaunchPlan>, String> {+ let Some(profile) = profile(app_data) else {+ return Ok(None);+ };+ if super::instances::current_profile().as_deref() != Some(profile.as_str()) {+ return Ok(None);+ }+ let Some(inputs) = resolve(app_data, resources) else {+ return Ok(None);+ };+ if inputs.setting.active_profile != profile+ || inputs.setting.port+ != inputs+ .setting+ .manual_port+ .unwrap_or_else(config::default_port)+ || super::utils::is_port_in_use(inputs.setting.port)+ {+ return Ok(None);+ }+ let core_dir = inputs.root(deps::DEP_DSH);+ let Some(version) = exact_core_version(&inputs, &core_dir) else {+ return Ok(None);+ };+ let node_root = inputs.root(deps::DEP_NODE);+ let node_entry = deps::entry_relative_from(Some(&inputs.manifest), deps::DEP_NODE);+ let pinned = matches!(inputs.mapping.get(deps::DEP_NODE), Some(Some(_)));+ let node = config::node_binary_path_from(&node_root, &node_entry, pinned);+ #[cfg(windows)]+ if !super::early::probes_ready()? {+ return Ok(None);+ }+ let pnpm_root = inputs.root(deps::DEP_PNPM);+ let pnpm_binary = inputs.binary(deps::DEP_PNPM);+ let local_data = std::env::var_os("LOCALAPPDATA").map(PathBuf::from);+ if !node.is_absolute()+ || !node.is_file()+ || !pnpm_root.is_absolute()+ || !pnpm_binary.is_absolute()+ || !local_data.is_some_and(|path| path.is_absolute() && path.is_dir())+ {+ return Ok(None);+ }+ let bin_dir = cli::get_bin_dir_from(None, None);+ let git_dir = config::git_cmd_dir_from(|| inputs.binary(deps::DEP_GIT));+ #[cfg(windows)]+ if !super::early::probes_ready()? {+ return Ok(None);+ }+ let user_pnpm = cli::find_user_pnpm_from(&bin_dir, None);+ if !bin_dir.is_absolute()+ || !bin_dir.is_dir()+ || git_dir+ .as_ref()+ .is_some_and(|path| !path.is_absolute() || !path.is_dir())+ || match user_pnpm.as_ref() {+ Some(_) => pnpm_binary.exists(),+ None => !pnpm_root.is_dir() || !pnpm_binary.is_file(),+ }+ {+ return Ok(None);+ }+ let profile_root = inputs.dsh_home.join("profiles").join(&profile);+ if let Err(error) = crate::service::migrate::heal_stale_pnpm_metadata(&inputs.dsh_home) {+ log::warn!("pnpm modules metadata self-heal skipped: {error}");+ return Ok(None);+ }+ if let Err(error) = profiles::prepare_at(&inputs.dsh_home, &profile) {+ log::warn!("ensure active profile core bundles failed: {error}");+ return Ok(None);+ }+ if let Err(error) = super::win_inspector::apply_at(&profile_root) {+ log::warn!("win32 legacy patch cleanup failed: {error}");+ }+ for (label, apply) in [+ (+ "renderer SlotOutlet patch",+ patch::renderer::apply_at as fn(&Path) -> Result<(), String>,+ ),+ ("composer workspace-less patch", patch::composer::apply_at),+ (+ "conversation draft compatibility patch",+ patch::conversation_draft::apply_at,+ ),+ ("mobile composer patch", patch::mobile_composer::apply_at),+ ("mobile sidebar patch", patch::mobile_sidebar::apply_at),+ ("SessionStore.remove patch", patch::session::apply_at),+ ("pi-ai session header patch", patch::llm_session::apply_at),+ (+ "pi-ai thinking-as-text patch",+ patch::pi_ai_thinking::apply_at,+ ),+ (+ "model selection mouse click patch",+ patch::model_selection::apply_at,+ ),+ (+ "workspace worktree membership patch",+ patch::workspace::apply_at,+ ),+ (+ "workspace view state patch",+ patch::workspace_view::apply_at,+ ),+ (+ "plugin visibility patch",+ patch::plugin_visibility::apply_at,+ ),+ ] {+ if let Err(error) = apply(&core_dir) {+ log::warn!("{label} failed: {error}");+ }+ }+ patch::mcp_startup::apply_at(&core_dir)?;+ if let Err(error) = plugin::ensure_npmrc_at(&profile_root.join(".npmrc")) {+ log::warn!("ensure profile .npmrc failed: {error}");+ return Ok(None);+ }+ match plugin::prepare_early_plugins(+ &profile_root,+ &inputs.dsh_home,+ Some(resources),+ Some(&inputs.manifest),+ Some(&version),+ ) {+ Ok(plugin::EarlyPluginState::Ready) => {}+ Ok(plugin::EarlyPluginState::Defer) => return Ok(None),+ Err(error) if plugin::is_process_cleanup_failure(&error) => return Err(error),+ Err(error) => {+ log::warn!("ensure internal plugins failed: {error}");+ return Ok(None);+ }+ }+ if let Err(error) = patch::plugin_visibility::apply_at(&core_dir) {+ log::warn!("plugin visibility patch after plugin self-healing failed: {error}");+ }+ let presets = plugin::presets_from_manifest(&inputs.manifest, Some(resources));+ let required: Vec<_> = presets+ .iter()+ .filter(|preset| preset.internal)+ .map(|preset| core::RuntimeRequiredPlugin {+ name: plugin::installed_name(preset),+ source: plugin::bundled_plugin_dir_from(Some(resources), &preset.id),+ version: preset.version.as_ref(),+ })+ .collect();+ if core::prepare_active_runtime_at(&core::RuntimePreparationPaths {+ source: core::CoreSource::App,+ base: &inputs.base,+ core_root: &core_dir,+ node: &node,+ profile: &profile_root,+ profiles: &inputs.dsh_home.join("profiles"),+ resources: Some(&inputs.resource_root),+ core_version: Some(&version),+ required_plugins: Some(&required),+ })? != core::RuntimePreparation::Ready+ || config::node_binary_path_from(&node_root, &node_entry, pinned) != node+ {+ return Ok(None);+ }+ let channel = usize::from(config::APP_IDENTIFIER == "dsh-tauri-nightly");+ let dsh_binary = inputs.binary(deps::DEP_DSH);+ Ok(Some(super::launch::LaunchPlan {+ setting: inputs.setting,+ profile,+ node,+ dsh_binary,+ core_dir,+ pid_path: profile_root.join(config::HARNESS_PID_MARKER_NAMES[channel]),+ profile_root,+ dsh_home: inputs.dsh_home,+ base: inputs.base,+ bin_dir,+ pnpm_root,+ pnpm_binary,+ resources: Some(resources.to_path_buf()),+ git_dir,+ user_pnpm,+ }))+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn original_store_is_read_only_and_defaults_never_become_ready() {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join(config::store_dat_file_name());+ assert!(read_setting(root.path()).is_none());+ let ready = json!({+ "installed": true, "auto_start": true, "port": 3080,+ "language": "en", "active_core": "app", "active_profile": profiles::DESKTOP_PROFILE+ });+ for raw in [ready.clone(), json!(ready.to_string())] {+ let bytes = serde_json::to_vec(&json!({"setting": raw})).unwrap();+ fs::write(&path, &bytes).unwrap();+ assert_eq!(+ read_setting(root.path()).unwrap().active_profile,+ profiles::DESKTOP_PROFILE+ );+ assert_eq!(fs::read(&path).unwrap(), bytes);+ }+ for (key, value) in [+ ("installed", json!(false)),+ ("auto_start", json!(false)),+ ("port", json!(0)),+ ("language", json!(null)),+ ("active_core", json!(null)),+ ("active_core", json!("local")),+ ("active_profile", json!("safe")),+ ("active_profile", json!("desktop")),+ ("active_profile", json!("custom")),+ ("active_profile", json!("web")),+ ("active_profile", json!("../web")),+ ("active_profile", json!(" web")),+ ] {+ let mut setting = ready.clone();+ setting[key] = value;+ fs::write(&path, json!({"setting": setting}).to_string()).unwrap();+ assert!(read_setting(root.path()).is_none(), "{key}");+ }+ for key in ["active_core", "active_profile", "auto_start", "installed"] {+ let mut setting = ready.clone();+ setting.as_object_mut().unwrap().remove(key);+ fs::write(&path, json!({"setting": setting}).to_string()).unwrap();+ assert!(read_setting(root.path()).is_none(), "{key}");+ }+ fs::write(&path, json!({"setting": ready}).to_string()).unwrap();+ super::super::instances::scope_sync("other".into(), || {+ assert!(prepare(root.path(), &root.path().join("missing"))+ .unwrap()+ .is_none());+ });+ assert!(entry(root.path(), Path::new("relative-resources")).is_none());+ }+}diff --git a/src-tauri/src/service/workflow/health.rs b/src-tauri/src/service/workflow/health.rsindex 0b9309d6..9d51e6e1 100644--- a/src-tauri/src/service/workflow/health.rs+++ b/src-tauri/src/service/workflow/health.rs@@ -15,8 +15,15 @@ use super::utils;/// 上下,提高并发能直接缩短启动尾段的这一轮全量校验。const HEALTH_PROBE_CONCURRENCY: usize = 48;+#[derive(serde::Serialize)]+pub struct HealthCheck {+ pub status: String,+ pub boot_html: String,+ pub service_url: String,+}+/// 读取 Harness 首页并解析本次启动实际声明的客户端模块。-async fn client_probe_endpoints(port: u16) -> Result<Vec<String>, String> {+async fn client_probe_endpoints(port: u16) -> Result<(Vec<String>, String), String> {// 回环与通配地址都还绑得上,才说明没有任何进程在监听它,此时发起 HTTP 探测// 只会吃满建连超时(`LOOPBACK_CONNECT_TIMEOUT`)。判定成本不足 1ms;任一地址// 绑不上即照旧走 HTTP 探测,不会把占用误判成未监听。@@ -53,8 +60,9 @@ async fn client_probe_endpoints(port: u16) -> Result<Vec<String>, String> {.text().await.map_err(|e| format!("HARNESS_BOOT_MANIFEST_READ_FAILED: {e}"))?;- Ok(utils::client_urls_from_boot_html(port, &body)- .unwrap_or_else(|| utils::health_probe_plugin_urls(port)))+ let endpoints = utils::client_urls_from_boot_html(port, &body)+ .unwrap_or_else(|| utils::health_probe_plugin_urls(port));+ Ok((endpoints, body))}/// 无持有进程时应返回给前端的探测信号。@@ -132,18 +140,22 @@ async fn probe_client_bundles(}/// 健康检查(通过 Rust 代理,避免 WebView CORS 问题)-pub async fn proxy_health_check(port: u16) -> Result<String, String> {+pub async fn proxy_health_check(port: u16) -> Result<HealthCheck, String> {if !has_owned_process() {return Err(not_owned_probe_signal(launch_guard().load(Ordering::SeqCst)).to_string());}let client = utils::loopback_http_client(config::HEALTH_CHECK_TIMEOUT).map_err(|e| format!("HARNESS_HEALTH_CLIENT_FAILED: {e}"))?;- let endpoints = client_probe_endpoints(port).await?;+ let (endpoints, boot_html) = client_probe_endpoints(port).await?;let total = endpoints.len();let (ready, failures) = probe_client_bundles(&client, endpoints).await;if all_client_modules_ready(ready, total) {startup::note_client_modules_ready(ready, total);- return Ok(format!("healthy - {ready}/{total} client modules ready"));+ return Ok(HealthCheck {+ status: format!("healthy - {ready}/{total} client modules ready"),+ boot_html,+ service_url: config::get_dsh_service_url(port),+ });}Err(format!("HARNESS_NOT_READY: Harness client modules are not ready ({ready}/{total} ready; {})",@@ -305,10 +317,12 @@ mod tests {server.abort();served.expect("HTTP fixture did not complete").unwrap();if status == "200 OK" {+ let (endpoints, boot_html) = result.unwrap();assert_eq!(- result.unwrap(),+ endpoints,vec![format!("http://127.0.0.1:{port}/plugins/fixture/client.js")]);+ assert_eq!(boot_html, html);} else {assert_eq!(result.unwrap_err(),diff --git a/src-tauri/src/service/workflow/instances.rs b/src-tauri/src/service/workflow/instances.rsindex 7cf97d2e..cfca0f77 100644--- a/src-tauri/src/service/workflow/instances.rs+++ b/src-tauri/src/service/workflow/instances.rs@@ -37,6 +37,19 @@ fn registry() -> &'static Mutex<Registry> {REGISTRY.get_or_init(|| Mutex::new(Registry::default()))}+pub(super) fn registration_gate() -> &'static Mutex<bool> {+ static SHUTTING_DOWN: Mutex<bool> = Mutex::new(false);+ &SHUTTING_DOWN+}++pub(crate) fn begin_shutdown() {+ begin_shutdown_at(registration_gate());+}++pub(super) fn begin_shutdown_at(gate: &Mutex<bool>) {+ *gate.lock().unwrap_or_else(|error| error.into_inner()) = true;+}+pub fn current_profile() -> Option<String> {PROFILE.try_with(Clone::clone).ok()}@@ -117,15 +130,28 @@ pub fn attached_elsewhere(profile: &str, label: &str) -> bool {pub fn require_exclusive_profile() -> Result<(), String> {let profile = current_profile().unwrap_or_else(|| "web".into());- let registry = registry().lock().unwrap_or_else(|error| error.into_inner());- if registry.windows.values().any(|value| value != &profile)- || registry.instances.iter().any(|(id, instance)| {- id != &profile- && instance- .process- .lock()- .unwrap_or_else(|error| error.into_inner())- .is_some()+ let _gate = registration_gate()+ .lock()+ .unwrap_or_else(|error| error.into_inner());+ let (foreign_window, instances) = {+ let registry = registry().lock().unwrap_or_else(|error| error.into_inner());+ (+ registry.windows.values().any(|value| value != &profile),+ registry+ .instances+ .iter()+ .filter(|(id, _)| *id != &profile)+ .map(|(_, instance)| Arc::clone(instance))+ .collect::<Vec<_>>(),+ )+ };+ if foreign_window+ || instances.iter().any(|instance| {+ instance+ .process+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .is_some()}){return Err("CORE_IN_USE: close windows using other profiles before changing shared core or data files".into());diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rsindex 445602a4..8f266d32 100644--- a/src-tauri/src/service/workflow/launch.rs+++ b/src-tauri/src/service/workflow/launch.rs@@ -5,41 +5,48 @@ use crate::config;use std::collections::HashMap;use std::ffi::OsString;use std::fs;-#[cfg(not(windows))]-use std::io::Read;use std::path::{Path, PathBuf};#[cfg(not(windows))]use std::process::{Command, Stdio};use std::sync::atomic::Ordering;+use std::sync::{Arc, OnceLock};+use tauri::Manager;-#[cfg(not(windows))]-use super::process::set_owned_process;-#[cfg(windows)]-use super::process::set_owned_process_with_handle;#[cfg(unix)]use super::process::warn_if_inotify_watch_limit_low;use super::process::{- has_owned_process, launch_guard, on_owned_process_exit, stop, take_startup_sweep,- terminate_stale_harness_processes, LaunchGuard,+ has_owned_process, launch_guard, on_owned_process_exit_at, register_owned_process, stop,+ take_startup_sweep, terminate_stale_harness_processes, LaunchGuard, OwnedProcess,+ HARNESS_PROCESS_EXITED_EVENT,};use super::status;-use super::sweep::persist_harness_pid;#[cfg(windows)]use super::sweep::{dsh_bin_open_error, relaunch_marker_path, relaunch_via_shell_escape};use super::utils::{append_log, rotate_service_log, spawn_output_readers, wait_for_port_release};use super::win_inspector;#[cfg(windows)]-type SpawnResult = std::io::Result<(Option<std::fs::File>, Option<std::fs::File>, u32)>;+type HarnessChild = std::sync::Arc<std::os::windows::io::OwnedHandle>;#[cfg(unix)]-type SpawnResult = Result<- (- Option<std::process::ChildStdout>,- Option<std::process::ChildStderr>,- u32,- ),- String,->;+type HarnessChild = std::process::Child;++pub(super) struct LaunchPlan {+ pub(super) setting: config::Setting,+ pub(super) profile: String,+ pub(super) node: PathBuf,+ pub(super) dsh_binary: PathBuf,+ pub(super) core_dir: PathBuf,+ pub(super) profile_root: PathBuf,+ pub(super) dsh_home: PathBuf,+ pub(super) base: PathBuf,+ pub(super) bin_dir: PathBuf,+ pub(super) pnpm_root: PathBuf,+ pub(super) pnpm_binary: PathBuf,+ pub(super) pid_path: PathBuf,+ pub(super) resources: Option<PathBuf>,+ pub(super) git_dir: Option<PathBuf>,+ pub(super) user_pnpm: Option<PathBuf>,+}/// 端口释放等待上限:刚结束/清扫过上个会话的残留 dsh 进程后,TCP 端口释放/// 存在短暂滞后(taskkill 返回 ≠ 端口已可复用)。等待窗口内端口回落为空闲则@@ -190,6 +197,7 @@ fn resolve_heal_port(configured: u16, heal_target: u16, heal_target_free: bool)/// 检测并启动 Harness 服务pub async fn start(app_handle: tauri::AppHandle) -> Result<(), String> {+ super::early::wait_preparation().await?;let setting = config::get_store_dat_setting(&app_handle);let node_binary_path = config::get_node_binary_path(&app_handle);// 活动核心的入口:本地核心存在时优先本地(需求 3),否则预打包@@ -257,11 +265,7 @@ pub async fn restart(app_handle: tauri::AppHandle) -> Result<(), String> {/// tree)。上一轮被杀/崩溃的 dsh 若留下组合行,新 boot 会读到已含 bundle 行的/// 文件,再叠加同一批 patch → `duplicate loader entry`。spawn 前与「早期退出/// 重试」各调用一次,把竞态窗口关闭到最小;文件已是空根时静默跳过。-fn reset_active_profile_root(app_handle: &tauri::AppHandle) {- let profile_root = crate::service::profile::profile_dir_of(- app_handle,- &crate::service::profile::active_profile(app_handle),- );+fn reset_active_profile_root(profile_root: &Path) {if !profile_root.is_dir() {return;}@@ -279,18 +283,200 @@ fn reset_active_profile_root(app_handle: &tauri::AppHandle) {}}-/// 判断 dsh 早期退出是否命中「duplicate loader entry」竞态签名。-///-/// 竞态特征:exit code 1 且 stderr 含 `duplicate loader entry`(dsh-app-boot-/// 的 Include 把重复 bundle 行叠加进根树时抛出的 TypeError 文本,实测-/// `duplicate loader entry id: dsh-tauri-worktree`)。-#[cfg(windows)]-fn is_duplicate_loader_exit(exit_code: u32, stderr: &str) -> bool {- exit_code == 1 && stderr.contains("duplicate loader entry")+fn wait_harness(+ child: &mut HarnessChild,+ timeout: Option<std::time::Duration>,+) -> Result<Option<Option<i64>>, String> {+ #[cfg(windows)]+ {+ use std::os::windows::io::AsRawHandle;+ use windows_sys::Win32::Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT};+ use windows_sys::Win32::System::Threading::{+ GetExitCodeProcess, WaitForSingleObject, INFINITE,+ };++ let handle = child.as_raw_handle();+ let millis = timeout.map_or(INFINITE, |value| value.as_millis() as u32);+ match unsafe { WaitForSingleObject(handle, millis) } {+ WAIT_TIMEOUT => Ok(None),+ WAIT_OBJECT_0 => {+ let mut code = 0;+ Ok(Some(+ (unsafe { GetExitCodeProcess(handle, &mut code) } != 0)+ .then_some(i64::from(code)),+ ))+ }+ _ => Err(format!(+ "PROCESS_WAIT_FAILED: {}",+ std::io::Error::last_os_error()+ )),+ }+ }+ #[cfg(unix)]+ {+ let Some(timeout) = timeout else {+ return child+ .wait()+ .map(|exit| Some(exit.code().map(i64::from)))+ .map_err(|error| format!("PROCESS_WAIT_FAILED: {error}"));+ };+ let deadline = std::time::Instant::now() + timeout;+ loop {+ match child.try_wait() {+ Ok(Some(exit)) => return Ok(Some(exit.code().map(i64::from))),+ Ok(None) if std::time::Instant::now() >= deadline => return Ok(None),+ Ok(None) => std::thread::sleep(std::time::Duration::from_millis(20)),+ Err(error) => return Err(format!("PROCESS_WAIT_FAILED: {error}")),+ }+ }+ }+}++fn supervise_harness(+ mut on_exit: impl FnMut(u32, Option<i64>, Option<&Path>),+ log_path: &PathBuf,+ started: &mut Option<tokio::sync::oneshot::Sender<Result<(), String>>>,+ guards: (LaunchGuard, tokio::sync::OwnedMutexGuard<()>),+ mut spawn: impl FnMut(+ &Path,+ ) -> Result<+ (+ OwnedProcess,+ HarnessChild,+ std::io::Result<std::sync::mpsc::Receiver<bool>>,+ ),+ String,+ >,+ mut reset: impl FnMut(),+ mut persist: impl FnMut(u32),+) -> Result<(), String> {+ let mut guards = Some(guards);+ let mut previous_exit = None;+ for attempt in 1..=3 {+ let report_path = fatal_report_path(log_path);+ let registered = register_owned_process(previous_exit.map(|(pid, _)| pid), || {+ if previous_exit.is_some() {+ reset();+ }+ let (owned, child, signature) = spawn(&report_path)?;+ #[cfg(unix)]+ let mut child = child;+ let pid = owned.pid;+ let signature = match signature {+ Ok(signature) => {+ persist(pid);+ Ok(signature)+ }+ Err(error) => {+ let error = format!("PROCESS_START_FAILED: spawn output reader: {error}");+ #[cfg(windows)]+ let cleanup = {+ use std::os::windows::io::AsRawHandle;+ super::process::terminate_windows_process(+ pid,+ child.as_raw_handle(),+ super::process::kill_pid_tree,+ )+ };+ #[cfg(unix)]+ let cleanup = (|| {+ if child.try_wait()?.is_none() {+ // 线程耗尽时不依赖再创建外部 kill 进程;未 reap 的 PID 不会复用。+ unsafe { libc::kill(-(pid as libc::pid_t), libc::SIGKILL) };+ if let Err(kill) = child.kill() {+ if child.try_wait()?.is_none() {+ return Err(kill);+ }+ }+ }+ child.wait().map(|_| ())+ })()+ .map_err(|cleanup: std::io::Error| {+ format!("HARNESS_CLEANUP_FAILED: process {pid}: {cleanup}")+ });+ match cleanup {+ Ok(()) => return Err(error),+ Err(cleanup) => Err(format!("{error}; {cleanup}")),+ }+ }+ };+ Ok((owned, (pid, child, signature)))+ });+ let (pid, mut child, signature) = match registered {+ Ok(Some(process)) => process,+ Ok(None) => return Err("STARTUP_CANCELLED: Harness launch was stopped".into()),+ Err(error) => {+ if let Some((pid, code)) = previous_exit {+ on_exit(pid, code, None);+ }+ return Err(error);+ }+ };+ let signature = signature?;+ log::info!("Harness process spawned and registered: pid={pid}, attempt={attempt}");+ if let Some(started) = started.take() {+ let _ = started.send(Ok(()));+ }+ let mut wait = |timeout| {+ let result = wait_harness(&mut child, timeout);+ if let Err(error) = &result {+ log::error!(+ "{error}; terminating this Harness process before releasing its monitor"+ );+ #[cfg(windows)]+ {+ use std::os::windows::io::AsRawHandle;+ super::process::terminate_windows_process(+ pid,+ child.as_raw_handle(),+ super::process::kill_pid_tree,+ )?;+ }+ #[cfg(unix)]+ {+ super::process::kill_pid_tree(pid);+ child+ .wait()+ .map_err(|cleanup| format!("{error}; cleanup failed: {cleanup}"))?;+ }+ on_exit(pid, None, Some(&report_path));+ }+ result+ };+ let code = match wait(Some(std::time::Duration::from_millis(2500)))? {+ Some(code) => code,+ None => {+ let (launch, transition) = guards.take().unwrap();+ drop(launch);+ drop(transition);+ let code = wait(None)?.flatten();+ on_exit(pid, code, Some(&report_path));+ return Ok(());+ }+ };+ // 子孙进程可能继承 stderr 写端;只等本轮签名,不能等无界 EOF。+ let duplicate = matches!(+ signature.recv_timeout(std::time::Duration::from_millis(250)),+ Ok(true)+ );+ if code == Some(1) && duplicate && attempt < 3 {+ log_fatal_report(log_path, &report_path);+ log::warn!(+ "DUPLICATE_LOADER_ENTRY: dsh exited early with duplicate loader entry \+ (pid={pid}, code=1); resetting profile root and relaunching (attempt {attempt}/3)"+ );+ previous_exit = Some((pid, code));+ continue;+ }+ on_exit(pid, code, Some(&report_path));+ return Ok(());+ }+ unreachable!()}/// 启动 Harness 服务进程pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {+ super::early::wait_preparation().await?;// 启动分段计时(issue #766):只写日志,不改控制流。每段一行 `STARTUP_PHASE`,// `ms` 是本段耗时、`total` 是本次 launch 的累计耗时。启动慢的归因过去只能靠// 时间戳猜测(同一进程内 auto_start 与前端 invoke 并发交错),埋点后可直接@@ -311,7 +497,17 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {let mut setting = config::get_store_dat_setting(&app_handle);setting.port = super::instances::port(&app_handle);let node_binary_path = config::get_node_binary_path(&app_handle);- let _transition_guard = super::process::acquire_core_transition().await?;+ let transition = super::process::acquire_core_transition();+ tokio::pin!(transition);+ let _transition_guard = loop {+ if launch_guard().load(Ordering::SeqCst) && has_owned_process() {+ return Ok(());+ }+ tokio::select! {+ guard = &mut transition => break guard?,+ _ = tokio::time::sleep(std::time::Duration::from_millis(20)) => {}+ }+ };let dsh_binary_path = crate::service::core::active_dsh_binary(&app_handle);log::debug!("Checking Node.js path: {:?}", node_binary_path);@@ -341,7 +537,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {log::info!("Harness launch already in progress, skipping");return Ok(());}- let _launch_guard = LaunchGuard;+ let _launch_guard = LaunchGuard(launch_guard());// 只有持有启动守卫的这条路径清扫残留:并发启动的其它调用已在守卫处返回,// 不会误杀刚拉起的进程。崩溃/强杀残留的孤儿 Harness 实例(不在// .harness.pid 标记中)持续占用配置端口与 dependencies/dsh 的文件句柄,@@ -632,6 +828,70 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {node_binary_path.display()));}+ let profile = crate::service::profile::active_profile(&app_handle);+ let plan = LaunchPlan {+ setting,+ profile_root: crate::service::profile::profile_dir_of(&app_handle, &profile),+ profile,+ node: node_binary_path,+ dsh_binary: dsh_binary_path,+ core_dir: crate::service::core::active_core_dir(&app_handle),+ dsh_home,+ base: config::get_base_dir(&app_handle),+ bin_dir: crate::service::cli::get_bin_dir(&app_handle),+ pnpm_root: config::get_pnpm_install_path(&app_handle),+ pnpm_binary: config::get_pnpm_binary_path(&app_handle),+ pid_path: super::sweep::harness_pid_path(&app_handle),+ resources: app_handle.path().resource_dir().ok(),+ git_dir: config::get_git_cmd_dir(&app_handle),+ user_pnpm: crate::service::cli::find_user_pnpm(&app_handle),+ };+ let notifications = Arc::new(OnceLock::new());+ let _ = notifications.set(app_handle);+ launch_prepared(+ plan,+ (_launch_guard, _transition_guard),+ notifications,+ #[cfg(windows)]+ None,+ )+ .await+}++pub(super) async fn launch_prepared(+ plan: LaunchPlan,+ guards: (LaunchGuard, tokio::sync::OwnedMutexGuard<()>),+ notifications: Arc<OnceLock<tauri::AppHandle>>,+ #[cfg(windows)] job: Option<Arc<super::win_spawn::ProcessJob>>,+) -> Result<(), String> {+ let prepared_started = std::time::Instant::now();+ let mut phase_started = prepared_started;+ let mark_phase = |name: &str, phase_started: &mut std::time::Instant| {+ let now = std::time::Instant::now();+ log::info!(+ "STARTUP_PHASE: name={name} ms={} prepared_total={}",+ now.duration_since(*phase_started).as_millis(),+ now.duration_since(prepared_started).as_millis()+ );+ *phase_started = now;+ };+ let LaunchPlan {+ setting,+ profile: active_profile,+ node: node_binary_path,+ dsh_binary: dsh_binary_path,+ core_dir,+ profile_root,+ dsh_home,+ base,+ bin_dir,+ pnpm_root,+ pnpm_binary,+ pid_path,+ resources,+ git_dir,+ user_pnpm,+ } = plan;let mut envs: HashMap<String, String> = HashMap::new();envs.insert("DSH_HOME".to_string(),@@ -671,9 +931,9 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {for dir in &git_dirs {log::debug!("harness service PATH prepend: {}", dir.to_string_lossy());}- let mut paths = vec![crate::service::cli::get_bin_dir(&app_handle)];+ let mut paths = vec![bin_dir.clone()];paths.push(node_dir.to_path_buf());- if let Some(git_dir) = config::get_git_cmd_dir(&app_handle) {+ if let Some(git_dir) = git_dir {log::debug!("harness service Git PATH prepend: {}",git_dir.to_string_lossy()@@ -691,13 +951,10 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// GUI 进程可能启动在 pnpm 安装之前,继承的 PATH 因而没有 npm 全局目录。// 直接注入探测到的绝对路径,避免 dsh-market 的 pnpm --version 落到自身 shim// 后又因 PATH 看不到真正的 pnpm(issue #139)。- if let Some(user_pnpm) = crate::service::cli::find_user_pnpm(&app_handle) {+ if let Some(user_pnpm) = user_pnpm.as_deref() {// Unix mise shim 依赖调用路径中的 argv[0];只做字面绝对化,不能解析// `pnpm -> mise` 链接。Windows 仍由同一辅助函数处理连接点与 `\\?\`。- if let Some(pnpm_value) = crate::service::cli::pnpm_env_value(- &user_pnpm,- &crate::service::cli::get_bin_dir(&app_handle),- ) {+ if let Some(pnpm_value) = crate::service::cli::pnpm_env_value(user_pnpm, &bin_dir) {envs.insert("DSH_PNPM".to_string(), pnpm_value);}}@@ -706,7 +963,16 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// homebrew pnpm)。与插件安装路径的 ensure_pnpm 版本感知一致,但启动阶段绝不// 触发下载;捆绑版未安装或与 store 不匹配时不注入(交由用户 pnpm)。探测被正常// 安装占住或探针自身失败只告警,只有进程清理未确认才终止启动。- match crate::service::plugin::harness_prefer_bundled_pnpm(&app_handle).await {+ match crate::service::plugin::harness_prefer_bundled_pnpm_from(+ &profile_root,+ &pnpm_root,+ &pnpm_binary,+ user_pnpm.as_deref(),+ &node_binary_path,+ &bin_dir,+ )+ .await+ {Ok(true) => {envs.insert("DSH_PREFER_BUNDLED_PNPM".to_string(), "1".to_string());}@@ -741,7 +1007,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// 日志文件(前端日志面板读取)。// 每次真实启动前轮转:只保留最近 3 次启动的日志,旧文件后退为// `dsh-web.log.1` / `dsh-web.log.2`,避免单文件随多次启动无限增长。- let log_path = config::get_service_log_path(&app_handle);+ let log_path = config::service_log_path_from(&base, Some(&active_profile));fs::create_dir_all(log_path.parent().unwrap_or(std::path::Path::new("."))).map_err(|e| format!("LOG_DIR_MKDIR_FAILED: create log dir failed: {e}"))?;rotate_service_log(&log_path, 3);@@ -757,7 +1023,11 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// 是「补丁文件存在却应用不了就大声失败」,这里不改变契约,只把同一结果提前成// 一条可操作的错误(哪个文件、哪一行、哪个包),错误页据此给出「移除悬空条目」// 的一键恢复。必须在所有插件自愈之后:那些步骤会改变安装状态。- if let Err(e) = crate::service::plugin::preflight_active_patch_entries(&app_handle) {+ if let Err(e) = crate::service::plugin::preflight_patch_entries_at(+ &profile_root,+ &dsh_home,+ Some(&dsh_binary_path),+ ) {log::error!("patch layer entry preflight failed: {e}");return Err(e);}@@ -814,273 +1084,148 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// `duplicate loader entry id: dsh-tauri-worktree`)。spawn 前最后一刻重置// profile 根关闭常见窗口;回写恰好落在探测窗口内的残余竞态由下方// Windows 分支的「早期退出重试」兜底。- reset_active_profile_root(&app_handle);+ reset_active_profile_root(&profile_root);// 本地插件热重载:把已挂载的本地路径插件源码目录折算成桌面端独占的补丁层,// 随启动以 `--patch` 注入核心 HMR(本地插件没有版本号可升级,改源码即时生效)。// 该层只在本次进程有效,每次启动都要按当前安装状态重算;没有本地插件时不传// `--patch`(指向不存在的文件会让核心在读取补丁层时直接失败)。- let hmr_patch = crate::service::plugin::local_plugin_hmr_sync(&app_handle);+ let hmr_patch = crate::service::plugin::local_plugin_hmr_sync_at(+ &base,+ &profile_root,+ resources.as_deref(),+ setting.local_plugin_hmr,+ );if let Some(path) = hmr_patch.as_deref() {log::info!("Injecting local plugin HMR layer: {}", path.display());}- // Windows 打包版是 GUI 进程(没有控制台)。直接以 CREATE_NO_WINDOW 启动- // node 会让 dsh 派生的子进程各自新建可见控制台窗口(频繁闪烁 cmd 黑窗),- // 因此 Windows 上改用“隐藏控制台”方式启动,见 win_spawn 模块。- let active_profile = crate::service::profile::active_profile(&app_handle);- let core_dir = crate::service::core::active_core_dir(&app_handle);+ if let Some(parent) = pid_path.parent() {+ let _ = fs::create_dir_all(parent);+ }+ let port = setting.port;mark_phase("pre_spawn_setup", &mut phase_started);super::startup::note_spawn();- let spawn_result: SpawnResult = {- #[cfg(windows)]- {- use std::io::{BufReader, Read};- use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, WAIT_TIMEOUT};- use windows_sys::Win32::System::Threading::{- GetExitCodeProcess, WaitForSingleObject, INFINITE,- };-- let spawn_harness = |report_path: &Path| {- let args = build_harness_args(- &dsh_binary_path,- active_profile.as_str(),- hmr_patch.as_deref(),- setting.port,- heap_mb,- report_path,- );- super::win_spawn::spawn_with_hidden_console_owned(- &node_binary_path,- &args,- Some(&core_dir),- &envs,- )- };-- // 早期退出重试:崩溃的上一轮 dsh 回写 `cordis.yml` 落在「新进程- // prepareProfile 重置之后、Include 读取之前」时,新 boot 会把已含- // bundle 组合行的 root 再叠加同一批 patch → `duplicate loader- // entry`(实测 exit code 1)。spawn 前重置只覆盖常见窗口,这里在- // spawn 后探测 ≤2.5s:命中签名则丢弃实例、重置 profile 根并重试- //(最多 3 次,第二次 boot 基于干净状态必然成功);仍在运行则视为- // 健康立即放行登记。探测期间最长阻塞 2.5s,之后才返回给调用方。- let mut attempt = 0u32;- let mut report_path = fatal_report_path(&log_path);- let mut outcome = spawn_harness(&report_path);- loop {- attempt += 1;- let (stdout, stderr, pid, handle) = match outcome {- Ok(spawned) => spawned,- Err(error) => {- // spawn 自身失败(非竞态):保持 Err 交给下方 map 传播- outcome = Err(error);- break;- }- };- let wait = unsafe { WaitForSingleObject(handle, 2500) };- if wait == WAIT_TIMEOUT {- // 健康:进程仍在运行,交给下方登记 + 监视线程。- outcome = Ok((stdout, stderr, pid, handle));- break;- }- // 已提前退出:读 stderr 判断是否命中竞态签名。- let mut exit_code: u32 = 0;- let got_exit_code = unsafe { GetExitCodeProcess(handle, &mut exit_code) } != 0;- let mut stderr_text = String::new();- let mut stderr_reader = BufReader::new(stderr);- let _ = Read::read_to_string(&mut stderr_reader, &mut stderr_text);- let hit_duplicate =- got_exit_code && is_duplicate_loader_exit(exit_code, &stderr_text);- if hit_duplicate && attempt < 3 {- // 丢弃首个失败实例:从未登记,句柄由本分支关闭(此时没有- // 监视线程,不存在重复 close)。- drop(stdout);- unsafe { CloseHandle(handle) };- log::warn!(- "DUPLICATE_LOADER_ENTRY: dsh exited early with duplicate loader entry \- (pid={pid}, code={exit_code}); resetting profile root and relaunching \- (attempt {attempt}/3)"- );- log_fatal_report(&log_path, &report_path);- reset_active_profile_root(&app_handle);- report_path = fatal_report_path(&log_path);- outcome = spawn_harness(&report_path);- continue;- }- // 非签名提前退出或重试耗尽:走正常路径——已捕获的 stderr 补写- // 日志避免失败原因丢失,句柄保持有效交给监视线程等待并关闭。- for line in stderr_text.lines() {- log::warn!(target: "dsh", "{}", line);- }- outcome = Ok((stdout, stderr_reader.into_inner(), pid, handle));- break;- }-- outcome.map(|(stdout, stderr, pid, handle)| {- // PID 与句柄作为整体一次登记,与退出清理(take 一并取出)配对- let handle_value = handle as usize;- set_owned_process_with_handle(pid, handle_value);- let exit_app_handle = app_handle.clone();- let exit_log_path = log_path.clone();- let exit_profile = active_profile.clone();- std::thread::spawn(move || {- super::instances::scope_sync(exit_profile, || unsafe {- let process_handle = handle_value as HANDLE;- WaitForSingleObject(process_handle, INFINITE);- // 进程确已退出:清空持有 PID 并把 Status 从 Running 回落为- // Stopped(原有实现只清 PID、状态永远停留在 Running)。- // 仅当该 PID 仍是当前登记才取出——旧监视线程不会误清新进程。- // take 返回值里的句柄由本线程负责关闭(不会与- // terminate_owned_process 重复 close——进程已 exit,- // 通常是本线程取走)。- let owned = on_owned_process_exit(&exit_app_handle, pid, |owned| {- log_fatal_report(&exit_log_path, &report_path);- let handle = owned.handle as HANDLE;- let mut exit_code: u32 = 0;- (GetExitCodeProcess(handle, &mut exit_code) != 0)- .then_some(i64::from(exit_code))- });- if let Some(owned) = owned {- let h = owned.handle as HANDLE;- CloseHandle(h);- }- })- });- (Some(stdout), Some(stderr), pid)- })- }- #[cfg(not(windows))]- {- use std::os::unix::process::CommandExt;- let mut report_path = fatal_report_path(&log_path);- let mut cmd = Command::new(&node_binary_path);- cmd.args(build_harness_args(- &dsh_binary_path,- active_profile.as_str(),- hmr_patch.as_deref(),- setting.port,- heap_mb,- &report_path,- ));- #[cfg(target_os = "linux")]- if let Some(path) = &library_path {- cmd.env("LD_LIBRARY_PATH", path);- }- cmd.envs(&envs)- .current_dir(&core_dir)- // 核心修正:提供一个空的 stdin 防止 setRawMode 报错- .stdin(Stdio::null())- // 使用管道捕获输出,以便在子线程中读取- .stdout(Stdio::piped())- .stderr(Stdio::piped())- // 独立进程组让停止操作只影响 Harness 及其后代。- .process_group(0);- let mut attempt = 0u32;- let mut child = 'attempts: loop {- attempt += 1;- match cmd.spawn() {- Ok(mut child) => {- let deadline =- std::time::Instant::now() + std::time::Duration::from_millis(2500);- loop {- match child.try_wait() {- Ok(Some(exit)) => {- let mut stderr_text = String::new();- if let Some(mut stderr) = child.stderr.take() {- let _ = stderr.read_to_string(&mut stderr_text);- }- log_fatal_report(&log_path, &report_path);- if exit.code() == Some(1)- && stderr_text.contains("duplicate loader entry")- && attempt < 3- {- log::warn!(- "DUPLICATE_LOADER_ENTRY: dsh exited early with duplicate loader entry \- (pid={}, code=1); resetting profile root and relaunching \- (attempt {attempt}/3)",- child.id()- );- reset_active_profile_root(&app_handle);- report_path = fatal_report_path(&log_path);- cmd = Command::new(&node_binary_path);- cmd.args(build_harness_args(- &dsh_binary_path,- active_profile.as_str(),- hmr_patch.as_deref(),- setting.port,- heap_mb,- &report_path,- ));- #[cfg(target_os = "linux")]- if let Some(path) = &library_path {- cmd.env("LD_LIBRARY_PATH", path);- }- cmd.envs(&envs)- .current_dir(&core_dir)- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .process_group(0);- continue 'attempts;- }- for line in stderr_text.lines() {- log::warn!(target: "dsh", "{}", line);- }- return Err(format!("Harness exited early: {exit}"));+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();+ std::thread::Builder::new()+ .name("harness-startup".into())+ .spawn(move || {+ super::instances::scope_sync(active_profile.clone(), || {+ let mut started = Some(started_tx);+ let result = supervise_harness(+ |pid, code, report_path| {+ on_owned_process_exit_at(+ pid,+ |_| {+ if let Some(report_path) = report_path {+ log_fatal_report(&log_path, report_path);}- Ok(None) if std::time::Instant::now() >= deadline => break,- Ok(None) => {- std::thread::sleep(std::time::Duration::from_millis(50))+ code+ },+ |payload| {+ if let Some(app) = notifications.get() {+ status::emit_status(app);+ super::instances::emit(+ app,+ HARNESS_PROCESS_EXITED_EVENT,+ payload,+ );}- Err(error) => return Err(error.to_string()),+ },+ );+ },+ &log_path,+ &mut started,+ guards,+ |report_path| {+ let args = build_harness_args(+ &dsh_binary_path,+ &active_profile,+ hmr_patch.as_deref(),+ port,+ heap_mb,+ report_path,+ );+ #[cfg(windows)]+ {+ use std::os::windows::io::{FromRawHandle, OwnedHandle};+ let spawned = if let Some(job) = job.as_deref() {+ super::win_spawn::spawn_with_hidden_console_in_job(+ &node_binary_path,+ &args,+ Some(&core_dir),+ &envs,+ job,+ )+ } else {+ super::win_spawn::spawn_with_hidden_console_owned(+ &node_binary_path,+ &args,+ Some(&core_dir),+ &envs,+ )+ };+ let (stdout, stderr, pid, handle) = spawned+ .map_err(|error| format!("PROCESS_START_FAILED: {error}"))?;+ let handle = Arc::new(unsafe { OwnedHandle::from_raw_handle(handle) });+ let signature =+ spawn_output_readers(Some(stdout), Some(stderr), log_path.clone());+ Ok((+ OwnedProcess {+ pid,+ handle: handle.clone(),+ },+ handle,+ signature,+ ))+ }+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt;+ let mut command = Command::new(&node_binary_path);+ command+ .args(args)+ .envs(&envs)+ .current_dir(&core_dir)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .process_group(0);+ #[cfg(target_os = "linux")]+ if let Some(path) = &library_path {+ command.env("LD_LIBRARY_PATH", path);}+ let mut child = command+ .spawn()+ .map_err(|error| format!("PROCESS_START_FAILED: {error}"))?;+ let pid = child.id();+ let signature = spawn_output_readers(+ child.stdout.take(),+ child.stderr.take(),+ log_path.clone(),+ );+ Ok((OwnedProcess { pid }, child, signature))}- break child;+ },+ || reset_active_profile_root(&profile_root),+ |pid| {+ let _ = fs::write(&pid_path, format!("{pid}\n{port}\n"));+ },+ );+ if let Err(error) = result {+ log::error!("Harness startup supervisor failed: {error}");+ if let Some(started) = started.take() {+ let _ = started.send(Err(error));}- Err(error) => return Err(error.to_string()),}- };- let pid = child.id();- let stdout = child.stdout.take();- let stderr = child.stderr.take();- set_owned_process(pid);- let exit_app_handle = app_handle.clone();- let exit_log_path = log_path.clone();- let exit_profile = active_profile.clone();- std::thread::spawn(move || {- super::instances::scope_sync(exit_profile, || {- let code = child.wait().ok().and_then(|status| status.code());- let _ = on_owned_process_exit(&exit_app_handle, pid, |_| {- log_fatal_report(&exit_log_path, &report_path);- code.map(i64::from)- });- })});- Ok((stdout, stderr, pid))- }- };-- // 这一段包含 spawn、2.5s 存活探测与 `set_owned_process` 登记——登记写在 spawn 块- // 内部,无法单独切分,所以不再为「登记」另打一个只量到一行 log 的点。- mark_phase("spawn_probe_and_register", &mut phase_started);-- match spawn_result {- Ok((stdout, stderr, pid)) => {- log::info!(- "Harness process started successfully: pid={pid}, port={}",- setting.port- );- // 记录 PID+端口供下次启动清扫崩溃残留的孤儿实例(见 sweep_orphan_harness)- persist_harness_pid(&app_handle, pid, setting.port);- spawn_output_readers(stdout, stderr, log_path);- Ok(())- }- Err(e) => {- log::error!("Failed to start process: {}", e);- Err(format!("PROCESS_START_FAILED: {e}"))- }- }+ })+ .map_err(|error| format!("PROCESS_START_FAILED: spawn startup supervisor: {error}"))?;+ let result = started_rx+ .await+ .map_err(|error| format!("PROCESS_START_FAILED: startup supervisor ended: {error}"))?;+ mark_phase("spawn_and_register", &mut phase_started);+ result}#[cfg(test)]@@ -1337,23 +1482,414 @@ mod tests {assert!(!text.contains(&"--patch".to_string()));}- /// 「duplicate loader entry」竞态签名的判定:只认 exit code 1 + stderr 含- /// 该文本(实测失败日志:- /// `Error: dsh: plugin tree failed to load: failed to apply loader entry- /// include (cordis:include): duplicate loader entry id: dsh-tauri-worktree`)。- #[cfg(windows)]+ struct SupervisedNode {+ root: tempfile::TempDir,+ instance: std::sync::Arc<super::super::instances::Instance>,+ started: Option<tokio::sync::oneshot::Receiver<Result<(), String>>>,+ finished: std::sync::mpsc::Receiver<Result<(), String>>,+ worker: Option<std::thread::JoinHandle<()>>,+ attempts: std::sync::Arc<std::sync::atomic::AtomicUsize>,+ spawned: std::sync::Arc<std::sync::Mutex<Option<OwnedProcess>>>,+ resets: std::sync::Arc<std::sync::atomic::AtomicUsize>,+ transition: std::sync::Arc<tokio::sync::Mutex<()>>,+ }++ impl SupervisedNode {+ fn new(script: &str) -> Self {+ Self::with_reader_failure(script, 0)+ }++ fn with_reader_failure(script: &str, reader: usize) -> Self {+ use std::sync::{atomic::AtomicUsize, Arc, Mutex};++ let node = config::get_local_node_path()+ .expect("supported Node.js required for supervisor tests");+ let root = tempfile::tempdir().unwrap();+ let path = root.path().to_path_buf();+ let script_path = path.join("fixture.cjs");+ fs::write(&script_path, script).unwrap();+ fs::create_dir_all(path.join("AppData/Local")).unwrap();+ fs::create_dir_all(path.join("AppData/Roaming")).unwrap();+ let envs: HashMap<String, String> = HashMap::from([+ ("HOME".into(), path.to_string_lossy().into_owned()),+ ("USERPROFILE".into(), path.to_string_lossy().into_owned()),+ (+ "APPDATA".into(),+ path.join("AppData/Roaming").to_string_lossy().into_owned(),+ ),+ (+ "LOCALAPPDATA".into(),+ path.join("AppData/Local").to_string_lossy().into_owned(),+ ),+ ("DSH_E2E_HOME".into(), path.to_string_lossy().into_owned()),+ ("NODE_OPTIONS".into(), String::new()),+ ("NODE_PATH".into(), String::new()),+ ]);+ let profile = format!("supervisor-{}", path.file_name().unwrap().to_string_lossy());+ let instance = super::super::instances::instance_of(&profile);+ instance.launching.store(true, Ordering::SeqCst);+ *instance.status.lock().unwrap() = status::Status::Starting;+ let attempts = Arc::new(AtomicUsize::new(0));+ let resets = Arc::new(AtomicUsize::new(0));+ let transition = Arc::new(tokio::sync::Mutex::new(()));+ let guards = (+ LaunchGuard(instance.launching.clone()),+ transition.clone().try_lock_owned().unwrap(),+ );+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();+ let (finished_tx, finished) = std::sync::mpsc::channel();+ let spawned = Arc::new(Mutex::new(None));+ let spawned_process = spawned.clone();+ let spawn_count = attempts.clone();+ let reset_count = resets.clone();+ let worker = std::thread::spawn(move || {+ let log = path.join("dsh-web.log");+ let mut started = Some(started_tx);+ let result = super::super::utils::with_output_reader_failure(reader, || {+ super::super::instances::scope_sync(profile, || {+ supervise_harness(+ |pid, code, report_path| {+ on_owned_process_exit_at(+ pid,+ |_| {+ if let Some(report_path) = report_path {+ log_fatal_report(&log, report_path);+ }+ code+ },+ |_| {},+ );+ },+ &log,+ &mut started,+ guards,+ |_| {+ if spawn_count.fetch_add(1, Ordering::SeqCst) > 0+ && !fs::read_to_string(path.join("cordis.yml"))+ .unwrap()+ .ends_with("\n[]\n")+ {+ return Err("FIXTURE_PROFILE_NOT_RESET: stale root".into());+ }+ if path.join("fail-next-spawn").exists() {+ return Err(+ "PROCESS_START_FAILED: fixture retry spawn failure".into(),+ );+ }+ fs::write(path.join("cordis.yml"), "- stale-loader-entry\n")+ .unwrap();+ #[cfg(windows)]+ {+ use std::os::windows::io::{FromRawHandle, OwnedHandle};+ let (stdout, stderr, pid, handle) =+ super::super::win_spawn::spawn_with_hidden_console_owned(+ &node,+ &[script_path.clone().into_os_string()],+ Some(&path),+ &envs,+ )+ .map_err(+ |error| format!("PROCESS_START_FAILED: {error}"),+ )?;+ let handle =+ Arc::new(unsafe { OwnedHandle::from_raw_handle(handle) });+ let owned = OwnedProcess {+ pid,+ handle: handle.clone(),+ };+ *spawned_process.lock().unwrap() = Some(owned.clone());+ let signature = spawn_output_readers(+ Some(stdout),+ Some(stderr),+ log.clone(),+ );+ Ok((owned, handle, signature))+ }+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt;+ let mut child = Command::new(&node)+ .arg(&script_path)+ .envs(&envs)+ .current_dir(&path)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .process_group(0)+ .spawn()+ .map_err(|error| {+ format!("PROCESS_START_FAILED: {error}")+ })?;+ let pid = child.id();+ *spawned_process.lock().unwrap() = Some(OwnedProcess { pid });+ let signature = spawn_output_readers(+ child.stdout.take(),+ child.stderr.take(),+ log.clone(),+ );+ Ok((OwnedProcess { pid }, child, signature))+ }+ },+ || {+ reset_count.fetch_add(1, Ordering::SeqCst);+ reset_active_profile_root(&path);+ },+ |pid| fs::write(path.join("harness.pid"), pid.to_string()).unwrap(),+ )+ })+ });+ if let Some(started) = started.take() {+ let _ = started.send(result.clone());+ }+ finished_tx.send(result).unwrap();+ });+ Self {+ root,+ instance,+ started: Some(started_rx),+ finished,+ worker: Some(worker),+ attempts,+ spawned,+ resets,+ transition,+ }+ }++ fn acknowledge(&mut self) {+ tokio::runtime::Builder::new_current_thread()+ .enable_time()+ .build()+ .unwrap()+ .block_on(async {+ tokio::time::timeout(+ std::time::Duration::from_secs(2),+ self.started.take().unwrap(),+ )+ .await+ })+ .expect("spawn acknowledgement must not wait for the startup probe")+ .expect("supervisor must send acknowledgement")+ .expect("fixture must spawn and register");+ }++ fn wait_until(&self, check: impl Fn() -> bool) {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(6);+ while !check() {+ assert!(+ std::time::Instant::now() < deadline,+ "supervisor fixture condition timed out"+ );+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ }++ fn cancel(&self) -> Result<(), String> {+ let owned = {+ let mut slot = self+ .instance+ .process+ .lock()+ .unwrap_or_else(|error| error.into_inner());+ self.instance.launching.store(false, Ordering::SeqCst);+ slot.take()+ };+ if let Some(owned) = owned {+ #[cfg(windows)]+ {+ use std::os::windows::io::AsRawHandle;+ super::super::process::terminate_windows_process(+ owned.pid,+ owned.handle.as_raw_handle(),+ super::super::process::kill_pid_tree,+ )?;+ }+ #[cfg(unix)]+ super::super::process::kill_pid_tree(owned.pid);+ }+ Ok(())+ }++ fn finish(&mut self) -> Result<(), String> {+ let result = self+ .finished+ .recv_timeout(std::time::Duration::from_secs(10))+ .expect("supervisor must finish and reap its child");+ self.worker.take().unwrap().join().unwrap();+ result+ }+ }++ impl Drop for SupervisedNode {+ fn drop(&mut self) {+ let _ = self.cancel();+ if let Some(worker) = self.worker.take().filter(|worker| worker.is_finished()) {+ let _ = worker.join();+ }+ }+ }++ fn assert_reader_failure_is_reaped(reader: usize) {+ let mut fixture = SupervisedNode::with_reader_failure("setTimeout(()=>{},60000)", reader);+ let error = fixture.finish().unwrap_err();+ assert_eq!(+ error,+ "PROCESS_START_FAILED: spawn output reader: injected output reader spawn failure"+ );+ assert_eq!(+ fixture.started.take().unwrap().blocking_recv().unwrap(),+ Err(error)+ );+ assert_eq!(fixture.attempts.load(Ordering::SeqCst), 1);+ assert!(fixture.instance.process.lock().unwrap().is_none());+ assert!(!fixture.root.path().join("harness.pid").exists());+ assert!(!fixture.instance.launching.load(Ordering::SeqCst));+ assert!(fixture.transition.try_lock().is_ok());+ let spawned = fixture.spawned.lock().unwrap();+ let owned = spawned.as_ref().expect("fixture must create a real child");+ #[cfg(windows)]+ {+ use std::os::windows::io::AsRawHandle;+ assert_eq!(+ unsafe {+ windows_sys::Win32::System::Threading::WaitForSingleObject(+ owned.handle.as_raw_handle(),+ 0,+ )+ },+ windows_sys::Win32::Foundation::WAIT_OBJECT_0,+ "failed reader setup must confirm the exact process exited"+ );+ }+ #[cfg(unix)]+ {+ let mut status = 0;+ assert_eq!(unsafe { libc::kill(owned.pid as libc::pid_t, 0) }, -1);+ assert_eq!(+ std::io::Error::last_os_error().raw_os_error(),+ Some(libc::ESRCH)+ );+ assert_eq!(+ unsafe { libc::waitpid(owned.pid as libc::pid_t, &mut status, libc::WNOHANG) },+ -1+ );+ assert_eq!(+ std::io::Error::last_os_error().raw_os_error(),+ Some(libc::ECHILD)+ );+ }+ }+#[test]- fn duplicate_loader_exit_signature_matches_observed_error() {- let stderr = "Error: dsh: plugin tree failed to load: failed to apply loader entry include (cordis:include): duplicate loader entry id: dsh-tauri-worktree\nTypeError: duplicate loader entry id: dsh-tauri-worktree\n at EntryGroup.update (...)";- assert!(is_duplicate_loader_exit(1, stderr));- // 其他退出码、无关错误或没有该文本的启动失败不命中- assert!(!is_duplicate_loader_exit(0, stderr));- assert!(!is_duplicate_loader_exit(2, stderr));- assert!(!is_duplicate_loader_exit(- 1,- "Error: EADDRINUSE: address already in use"- ));- assert!(!is_duplicate_loader_exit(1, ""));+ fn supervisor_reaps_child_when_first_output_reader_spawn_fails() {+ assert_reader_failure_is_reaped(1);+ }++ #[test]+ fn supervisor_reaps_child_when_second_output_reader_spawn_fails() {+ assert_reader_failure_is_reaped(2);+ }++ #[test]+ fn supervisor_acknowledges_before_probe_and_drains_both_full_pipes() {+ let mut fixture = SupervisedNode::new(+ "const fs=require('fs'); const chunk='x'.repeat(1024)+'\\n'; for(let i=0;i<512;i++){fs.writeSync(1,'OUT:'+chunk);fs.writeSync(2,'ERR:'+chunk)} fs.writeSync(1,'STDOUT_DONE\\n');fs.writeSync(2,'STDERR_DONE\\n');setTimeout(()=>{},10000)",+ );+ fixture.acknowledge();+ let pid = fixture+ .instance+ .process+ .lock()+ .unwrap()+ .as_ref()+ .unwrap()+ .pid;+ assert_eq!(+ fs::read_to_string(fixture.root.path().join("harness.pid")).unwrap(),+ pid.to_string()+ );+ assert!(fixture.instance.launching.load(Ordering::SeqCst));+ assert!(fixture.transition.try_lock().is_err());+ let log = fixture.root.path().join("dsh-web.log");+ fixture.wait_until(|| {+ fs::read_to_string(&log)+ .is_ok_and(|text| text.contains("STDOUT_DONE") && text.contains("STDERR_DONE"))+ });+ let output = fs::read_to_string(log).unwrap();+ assert_eq!(output.matches("OUT:").count(), 512);+ assert_eq!(output.matches("ERR:").count(), 512);+ fixture.wait_until(|| {+ !fixture.instance.launching.load(Ordering::SeqCst)+ && fixture.transition.try_lock().is_ok()+ });+ assert!(fixture.instance.process.lock().unwrap().is_some());+ fixture.cancel().unwrap();+ fixture.finish().unwrap();+ assert!(fixture.instance.process.lock().unwrap().is_none());+ }++ #[test]+ fn supervisor_retries_only_duplicate_code_one_at_most_twice() {+ for (script, attempts, resets) in [+ ("require('fs').writeSync(2,'duplicate loader entry id: fixture\\n');process.exit(1)", 3, 2),+ ("require('fs').writeSync(2,'Error: EADDRINUSE\\n');process.exit(1)", 1, 0),+ ("require('fs').writeSync(2,'duplicate loader entry id: fixture\\n');process.exit(0)", 1, 0),+ ] {+ let mut fixture = SupervisedNode::new(script);+ fixture.acknowledge();+ fixture.finish().unwrap();+ assert_eq!(fixture.attempts.load(Ordering::SeqCst), attempts, "{script}");+ assert_eq!(fixture.resets.load(Ordering::SeqCst), resets, "{script}");+ assert!(fixture.instance.process.lock().unwrap().is_none());+ assert!(!fixture.instance.launching.load(Ordering::SeqCst));+ assert_eq!(*fixture.instance.status.lock().unwrap(), status::Status::Stopped);+ assert!(fixture.transition.try_lock().is_ok());+ }+ }++ #[test]+ fn supervisor_releases_ownership_and_guards_when_retry_spawn_fails() {+ let mut fixture = SupervisedNode::new(+ "const fs=require('fs');fs.writeFileSync('fail-next-spawn','1');fs.writeSync(2,'duplicate loader entry id: fixture\\n');process.exit(1)",+ );+ fixture.acknowledge();+ assert_eq!(+ fixture.finish().unwrap_err(),+ "PROCESS_START_FAILED: fixture retry spawn failure"+ );+ assert_eq!(fixture.attempts.load(Ordering::SeqCst), 2);+ assert_eq!(fixture.resets.load(Ordering::SeqCst), 1);+ assert!(fixture.instance.process.lock().unwrap().is_none());+ assert_eq!(+ *fixture.instance.status.lock().unwrap(),+ status::Status::Stopped+ );+ fixture.wait_until(|| {+ !fixture.instance.launching.load(Ordering::SeqCst)+ && fixture.transition.try_lock().is_ok()+ });+ }++ #[test]+ fn stopping_during_probe_cancels_retry_without_invalidating_monitor_handle() {+ let mut fixture = SupervisedNode::new(+ "require('fs').writeSync(2,'duplicate loader entry id: fixture\\n');setTimeout(()=>{},10000)",+ );+ fixture.acknowledge();+ let log = fixture.root.path().join("dsh-web.log");+ fixture.wait_until(|| {+ fs::read_to_string(&log).is_ok_and(|text| text.contains("duplicate loader entry"))+ });+ assert!(fixture.instance.launching.load(Ordering::SeqCst));+ fixture.cancel().unwrap();+ if let Err(error) = fixture.finish() {+ assert_eq!(error, "STARTUP_CANCELLED: Harness launch was stopped");+ }+ assert_eq!(fixture.attempts.load(Ordering::SeqCst), 1);+ assert_eq!(fixture.resets.load(Ordering::SeqCst), 0);+ assert!(fixture.instance.process.lock().unwrap().is_none());+ assert!(!fixture.instance.launching.load(Ordering::SeqCst));+ assert!(fixture.transition.try_lock().is_ok());}/// 端口自愈(issue #91):自动避让递增遗留的非默认端口,在回落目标空闲时diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rsindex 3584cd63..f598031f 100644--- a/src-tauri/src/service/workflow/mod.rs+++ b/src-tauri/src/service/workflow/mod.rs@@ -19,6 +19,8 @@ pub(crate) mod win_inspector;#[cfg(windows)]pub(crate) mod win_spawn;+pub(crate) mod early;+mod early_plan;mod health;mod heap;mod install;@@ -27,7 +29,7 @@ mod process;mod startup;mod sweep;-pub use health::{proxy_health_check, recheck_ownership};+pub use health::{proxy_health_check, recheck_ownership, HealthCheck};pub(crate) use heap::effective_heap_limit_mb;pub use install::install;pub use launch::{launch, restart, start};diff --git a/src-tauri/src/service/workflow/process.rs b/src-tauri/src/service/workflow/process.rsindex 1532f39e..1a044eed 100644--- a/src-tauri/src/service/workflow/process.rs+++ b/src-tauri/src/service/workflow/process.rs@@ -6,6 +6,7 @@use crate::config;use std::fs;#[cfg(windows)]+use std::os::windows::io::{AsRawHandle, OwnedHandle};use std::path::Path;use std::process::Command;#[cfg(windows)]@@ -43,13 +44,11 @@ pub(crate) fn launch_guard() -> Arc<AtomicBool> {/// 「PID 清空」与「句柄关闭」之间不存在跨原子竞态(WARN-6)。历史上 PID/句柄/// 分两个 `Atomic*` 存储,`stop` 读 PID 与监视线程清句柄之间有微窗口可能导致/// 漏杀或重复 close。-#[derive(Clone, Copy)]+#[derive(Clone)]pub(super) struct OwnedProcess {pub(super) pid: u32,- /// Windows 进程句柄(原始 HANDLE 转 usize 存储,避免 `*mut c_void` 非 Send)。- /// 只在 Windows 存在;Unix 无句柄概念。#[cfg(windows)]- pub(super) handle: usize,+ pub(super) handle: Arc<OwnedHandle>,}/// 本次启动是否已按 dsh 入口路径清扫过历史残留。@@ -70,31 +69,42 @@ pub(super) fn retry_startup_sweep() {STARTUP_SWEEP_DONE.store(false, Ordering::SeqCst);}-/// 记录新持有的 Harness 根进程(Unix,启动成功后调用)。-#[cfg(not(windows))]-pub(super) fn set_owned_process(pid: u32) {- let instance = super::instances::instance();- let mut guard = instance.process.lock().unwrap_or_else(|e| e.into_inner());- *guard = Some(OwnedProcess { pid });+pub(super) fn register_owned_process<T>(+ previous_pid: Option<u32>,+ spawn: impl FnOnce() -> Result<(OwnedProcess, T), String>,+) -> Result<Option<T>, String> {+ register_owned_process_at(+ &super::instances::instance(),+ super::instances::registration_gate(),+ previous_pid,+ spawn,+ )}-/// 若调用方 owns 该进程(Windows 额外存句柄),记录之。-#[cfg(windows)]-pub(super) fn set_owned_process_with_handle(pid: u32, handle: usize) {- let instance = super::instances::instance();+fn register_owned_process_at<T>(+ instance: &super::instances::Instance,+ shutdown: &std::sync::Mutex<bool>,+ previous_pid: Option<u32>,+ spawn: impl FnOnce() -> Result<(OwnedProcess, T), String>,+) -> Result<Option<T>, String> {+ let shutdown = shutdown.lock().unwrap_or_else(|error| error.into_inner());let mut guard = instance.process.lock().unwrap_or_else(|e| e.into_inner());- *guard = Some(OwnedProcess { pid, handle });- // 本应用此后持有自己的 Harness:再次启动前必须重新确认没有残留+ if *shutdown+ || !instance.launching.load(Ordering::SeqCst)+ || guard.as_ref().map(|process| process.pid) != previous_pid+ {+ return Ok(None);+ }+ let (owned, value) = spawn()?;+ *guard = Some(owned);+ Ok(Some(value))}-/// 原子取出持有的进程(PID+句柄一起)。取走者负责关闭 Windows 句柄;-/// 无条件取出(停止/退出路径)。fn take_owned_process() -> Option<OwnedProcess> {- crate::service::workflow::instances::instance()- .process- .lock()- .unwrap_or_else(|e| e.into_inner())- .take()+ let instance = super::instances::instance();+ let mut guard = instance.process.lock().unwrap_or_else(|e| e.into_inner());+ instance.launching.store(false, Ordering::SeqCst);+ guard.take()}/// 纯函数部分:便于单测,不触碰全局状态。@@ -109,11 +119,11 @@ fn take_owned_process_if_matching(}}-pub(crate) struct LaunchGuard;+pub(crate) struct LaunchGuard(pub(super) Arc<AtomicBool>);impl Drop for LaunchGuard {fn drop(&mut self) {- launch_guard().store(false, Ordering::SeqCst);+ self.0.store(false, Ordering::SeqCst);}}@@ -175,13 +185,23 @@ pub fn owned_process_pid() -> Option<u32> {/// - 匹配成功后无条件回落到 Stopped——进程可能在 Starting 或 Running 阶段/// 退出,任何情况下都不能继续广播一个已经失效的运行状态(WARN-5)。///-/// 返回被取出的进程记录(含 Windows 句柄),取到者负责 `CloseHandle`——保证-/// 「取走进程」与「关闭句柄」同属一个调用者,杜绝重复 close。幂等:多次调用-/// (tick 与监视线程并发)只会生效一次,后续调用返回 None。+/// 幂等:多次调用只会生效一次,后续调用返回 None。+#[cfg(test)]pub(super) fn on_owned_process_exit<R: tauri::Runtime>(app_handle: &AppHandle<R>,pid: u32,exit_code: impl FnOnce(&OwnedProcess) -> Option<i64>,+) -> Option<OwnedProcess> {+ on_owned_process_exit_at(pid, exit_code, |payload| {+ status::emit_status(app_handle);+ super::instances::emit(app_handle, HARNESS_PROCESS_EXITED_EVENT, payload);+ })+}++pub(super) fn on_owned_process_exit_at(+ pid: u32,+ exit_code: impl FnOnce(&OwnedProcess) -> Option<i64>,+ notify: impl FnOnce(HarnessProcessExitedPayload),) -> Option<OwnedProcess> {let (owned, exit_code) = {let instance = super::instances::instance();@@ -192,6 +212,10 @@ pub(super) fn on_owned_process_exit<R: tauri::Runtime>(let owned = take_owned_process_if_matching(&mut guard, pid)?;// issue #1075:报告路径落盘前不让健康探测观察到 ownership 丢失。let exit_code = exit_code(&owned);+ *instance+ .status+ .lock()+ .unwrap_or_else(|error| error.into_inner()) = status::Status::Stopped;(owned, exit_code)};@@ -215,13 +239,10 @@ pub(super) fn on_owned_process_exit<R: tauri::Runtime>();}- status::set_status(status::Status::Stopped);- status::emit_status(app_handle);- let payload = HarnessProcessExitedPayload {+ notify(HarnessProcessExitedPayload {pid: owned.pid,exit_code,- };- super::instances::emit(app_handle, HARNESS_PROCESS_EXITED_EVENT, payload);+ });Some(owned)}@@ -237,13 +258,10 @@ fn terminate_owned_process() -> Result<bool, ()> {#[cfg(windows)]{- use windows_sys::Win32::Foundation::CloseHandle;- let handle = owned.handle as windows_sys::Win32::Foundation::HANDLE;- if handle.is_null() {- return Err(());- }+ let handle = owned.handle.as_raw_handle();if let Err(error) = terminate_windows_process(owned.pid, handle, kill_pid_tree) {log::error!("{error}");+ log::error!("Harness process {} is still running after stop", owned.pid);let instance = super::instances::instance();let mut guard = instance.process@@ -251,13 +269,9 @@ fn terminate_owned_process() -> Result<bool, ()> {.unwrap_or_else(|error| error.into_inner());if guard.is_none() {*guard = Some(owned);- } else {- unsafe { CloseHandle(handle) };}- log::error!("Harness process {} is still running after stop", owned.pid);return Err(());}- unsafe { CloseHandle(handle) };}#[cfg(unix)]@@ -389,61 +403,217 @@ fn is_windows_harness_command_line(cmdline: &str, dsh_bin: &str) -> bool {regex::Regex::new(&boundary).is_ok_and(|pattern| pattern.is_match(&normalized))}+#[cfg(windows)]+#[repr(C)]+#[derive(Clone, Copy)]+struct WindowsCommandLine {+ length: u16,+ maximum_length: u16,+ buffer: *const u16,+}++#[cfg(windows)]+fn decode_windows_command_line(buffer: &[usize], returned: usize) -> Option<String> {+ let header = std::mem::size_of::<WindowsCommandLine>();+ if returned < header || returned > std::mem::size_of_val(buffer) {+ return None;+ }+ let command = unsafe { std::ptr::read(buffer.as_ptr().cast::<WindowsCommandLine>()) };+ let base = buffer.as_ptr() as usize;+ let start = command.buffer as usize;+ if command.length % 2 != 0+ || command.maximum_length % 2 != 0+ || command.length > command.maximum_length+ || start % std::mem::align_of::<u16>() != 0+ || start < base.checked_add(header)?+ || start.checked_add(usize::from(command.maximum_length))? > base.checked_add(returned)?+ {+ return None;+ }+ let units = unsafe {+ std::slice::from_raw_parts(+ buffer.as_ptr().cast::<u16>().add((start - base) / 2),+ usize::from(command.length) / 2,+ )+ };+ if units.contains(&0) {+ return None;+ }+ String::from_utf16(units).ok()+}+#[cfg(windows)]fn windows_process_snapshot(target_pid: Option<u32>) -> Result<Vec<u8>, String> {- use std::os::windows::process::CommandExt;- // 候选进程连同其上方仍活着的祖先一起上报:垫片转发链是否孤儿,只有整条链能判断。- // 祖先链被层数上限截断时单独标记,调用方据此放弃清扫(上方仍可能有持有者)。- let script = r#"$ErrorActionPreference = 'Stop'-[Console]::OutputEncoding = [System.Text.Encoding]::UTF8-try {- $all = Get-CimInstance Win32_Process- $byPid = @{}- foreach ($process in $all) { $byPid[$process.ProcessId] = $process }- foreach ($child in $all) {- if (-not $child.CommandLine -or -not $child.CommandLine.Contains('--no-open')) { continue }- $ancestors = @()- $parent = $byPid[$child.ParentProcessId]- for ($depth = 0; $depth -lt 8; $depth++) {- if (-not $parent) { break }- $ancestorCreated = 0- if ($parent.CreationDate) { $ancestorCreated = $parent.CreationDate.ToFileTimeUtc() }- $ancestors += [pscustomobject]@{ pid = $parent.ProcessId; name = $parent.Name; created = $ancestorCreated; commandLine = $parent.CommandLine }- $parent = $byPid[$parent.ParentProcessId]- }- $childCreated = 0- if ($child.CreationDate) { $childCreated = $child.CreationDate.ToFileTimeUtc() }- [pscustomobject]@{ pid = $child.ProcessId; created = $childCreated; commandLine = $child.CommandLine; ancestors = $ancestors; ancestorsTruncated = ($null -ne $parent) } | ConvertTo-Json -Compress -Depth 4- }-} catch { Write-Error $_; exit 1 }"#;- let script = match target_pid {- Some(pid) => script.replace("if (-not $child.CommandLine -or -not $child.CommandLine.Contains('--no-open')) { continue }", &format!("if ($child.ProcessId -ne {pid}) {{ continue }}")),- None => script.to_string(),+ use std::collections::HashMap;+ use std::os::windows::io::FromRawHandle;+ use windows_sys::Win32::Foundation::{+ ERROR_NO_MORE_FILES, FILETIME, HANDLE, INVALID_HANDLE_VALUE,};- let output = match Command::new("powershell")- .args(["-NoProfile", "-NonInteractive", "-Command", &script])- .creation_flags(0x08000000)- .output()- {- Ok(output) if output.status.success() => output,- Ok(output) => {- log::warn!(- "Failed to enumerate orphan Harness processes: {}",- String::from_utf8_lossy(&output.stderr)- );- return Err("HARNESS_SWEEP_FAILED: process enumeration failed".to_string());+ use windows_sys::Win32::System::Diagnostics::ToolHelp::{+ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,+ TH32CS_SNAPPROCESS,+ };+ use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};+ use windows_sys::Win32::System::SystemInformation::GetSystemTimePreciseAsFileTime;+ use windows_sys::Win32::System::Threading::{+ GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,+ };++ type QueryProcess =+ unsafe extern "system" fn(HANDLE, u32, *mut std::ffi::c_void, u32, *mut u32) -> i32;+ let module_name: Vec<_> = "ntdll.dll".encode_utf16().chain(Some(0)).collect();+ let module = unsafe { GetModuleHandleW(module_name.as_ptr()) };+ if module.is_null() {+ return Err("HARNESS_SWEEP_FAILED: process query unavailable".to_string());+ }+ let query: QueryProcess = unsafe {+ std::mem::transmute(+ GetProcAddress(module, b"NtQueryInformationProcess\0".as_ptr())+ .ok_or("HARNESS_SWEEP_FAILED: process query unavailable")?,+ )+ };+ let mut sampled: FILETIME = unsafe { std::mem::zeroed() };+ // Toolhelp 不记录创建时间:快照开始后才创建的 PID 可能已复用旧父链。+ unsafe { GetSystemTimePreciseAsFileTime(&mut sampled) };+ let sampled = u64::from(sampled.dwHighDateTime) << 32 | u64::from(sampled.dwLowDateTime);+ let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };+ if snapshot == INVALID_HANDLE_VALUE {+ return Err(format!(+ "HARNESS_SWEEP_FAILED: process enumeration failed: {}",+ std::io::Error::last_os_error()+ ));+ }+ let snapshot = unsafe { OwnedHandle::from_raw_handle(snapshot) };+ let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };+ entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;+ let mut processes = HashMap::new();+ let mut present = unsafe { Process32FirstW(snapshot.as_raw_handle(), &mut entry) };+ loop {+ if present == 0 {+ let error = std::io::Error::last_os_error();+ if error.raw_os_error() != Some(ERROR_NO_MORE_FILES as i32) {+ return Err(format!(+ "HARNESS_SWEEP_FAILED: process enumeration failed: {error}"+ ));+ }+ break;}- Err(error) => {- return Err(format!(- "HARNESS_SWEEP_FAILED: process enumeration failed: {error}"- ));+ let length = entry+ .szExeFile+ .iter()+ .position(|&unit| unit == 0)+ .unwrap_or(entry.szExeFile.len());+ processes.insert(+ entry.th32ProcessID,+ (+ entry.th32ParentProcessID,+ WindowsProcessAncestor {+ pid: entry.th32ProcessID,+ created: 0,+ name: String::from_utf16(&entry.szExeFile[..length]).unwrap_or_default(),+ command_line: None,+ },+ ),+ );+ present = unsafe { Process32NextW(snapshot.as_raw_handle(), &mut entry) };+ }+ for (_, process) in processes.values_mut() {+ let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, process.pid) };+ if handle.is_null() {+ continue;}- };- Ok(output.stdout)+ let handle = unsafe { OwnedHandle::from_raw_handle(handle) };+ let mut creation: FILETIME = unsafe { std::mem::zeroed() };+ let mut exit = creation;+ let mut kernel = creation;+ let mut user = creation;+ if unsafe {+ GetProcessTimes(+ handle.as_raw_handle(),+ &mut creation,+ &mut exit,+ &mut kernel,+ &mut user,+ )+ } == 0+ {+ continue;+ }+ let created = u64::from(creation.dwHighDateTime) << 32 | u64::from(creation.dwLowDateTime);+ if created == 0 || created > sampled {+ continue;+ }+ process.created = created;+ let mut needed = 0;+ let status = unsafe {+ query(+ handle.as_raw_handle(),+ 60,+ std::ptr::null_mut(),+ 0,+ &mut needed,+ )+ };+ if ![0xc0000004u32 as i32, 0xc0000023u32 as i32].contains(&status)+ || (needed as usize) < std::mem::size_of::<WindowsCommandLine>()+ || (needed as usize) > std::mem::size_of::<WindowsCommandLine>() + usize::from(u16::MAX)+ {+ continue;+ }+ let mut buffer = vec![0usize; (needed as usize).div_ceil(std::mem::size_of::<usize>())];+ let mut returned = 0;+ if unsafe {+ query(+ handle.as_raw_handle(),+ 60,+ buffer.as_mut_ptr().cast(),+ needed,+ &mut returned,+ )+ } < 0+ || returned > needed+ {+ continue;+ }+ process.command_line = decode_windows_command_line(&buffer, returned as usize);+ }+ let mut output = Vec::new();+ for (&pid, (parent, process)) in &processes {+ if target_pid.is_some_and(|target| target != pid) {+ continue;+ }+ let Some(command_line) = &process.command_line else {+ continue;+ };+ if target_pid.is_none() && !command_line.contains("--no-open") {+ continue;+ }+ let mut next = *parent;+ let mut ancestors = Vec::new();+ for _ in 0..8 {+ let Some((parent, ancestor)) = processes.get(&next) else {+ break;+ };+ ancestors.push(ancestor.clone());+ next = *parent;+ }+ let entry = WindowsProcessEntry {+ pid,+ created: process.created,+ command_line: command_line.clone(),+ ancestors,+ ancestors_truncated: processes.contains_key(&next),+ };+ serde_json::to_writer(&mut output, &entry).map_err(|error| {+ format!("HARNESS_SWEEP_FAILED: process snapshot serialization failed: {error}")+ })?;+ output.push(b'\n');+ }+ Ok(output)}#[cfg(windows)]-fn terminate_stale_harness_processes_at(dsh_bin: &Path) -> Result<(), String> {+pub(super) fn terminate_stale_harness_processes_at(dsh_bin: &Path) -> Result<(), String> {let output = windows_process_snapshot(None)?;let dsh_bin = dsh_bin.to_str()@@ -533,7 +703,7 @@ fn terminate_confirmed_process(pid: u32, created: u64) -> Result<bool, String> {}#[cfg(windows)]-fn terminate_windows_process(+pub(super) fn terminate_windows_process(pid: u32,handle: windows_sys::Win32::Foundation::HANDLE,kill_tree: impl FnOnce(u32),@@ -631,7 +801,7 @@ pub(super) fn reclaim_orphan_port(dsh_bin: &Path, port: u16) -> Result<bool, Str}#[cfg(windows)]-#[derive(serde::Deserialize)]+#[derive(serde::Deserialize, serde::Serialize)]struct WindowsProcessEntry {pid: u32,created: u64,@@ -644,7 +814,7 @@ struct WindowsProcessEntry {}#[cfg(windows)]-#[derive(serde::Deserialize)]+#[derive(Clone, serde::Deserialize, serde::Serialize)]struct WindowsProcessAncestor {pid: u32,created: u64,@@ -865,6 +1035,19 @@ pub async fn stop(app_handle: tauri::AppHandle) -> Result<(), String> {/// 但内核回收监听套接字仍有短暂滞后,故结束过进程后补一次有界等待,让紧随其后的/// 安装器/新实例看到端口已释放。没持有进程时不等待,避免在用户可见路径上白耗。fn stop_instance_for_installer(app_handle: &tauri::AppHandle) -> Result<(), String> {+ stop_instance_at(+ &harness_pid_path(app_handle),+ super::instances::port(app_handle),+ #[cfg(windows)]+ &crate::service::core::active_dsh_binary(app_handle),+ )+}++pub(super) fn stop_instance_at(+ pid_path: &Path,+ port: u16,+ #[cfg(windows)] entry: &Path,+) -> Result<(), String> {let terminated = terminate_owned_process().map_err(|()| "STOP_FAILED: Harness process did not stop".to_string())?;#[cfg(not(windows))]@@ -873,13 +1056,11 @@ fn stop_instance_for_installer(app_handle: &tauri::AppHandle) -> Result<(), Stri}#[cfg(windows)]let _ = terminated;- // 正常停止路径同样清理清扫标记(崩溃路径才需要下次启动清扫)- let _ = fs::remove_file(harness_pid_path(app_handle));- let port = super::instances::port(app_handle);+ let _ = fs::remove_file(pid_path);if !wait_for_port_release(port, PORT_RELEASE_WAIT) {#[cfg(windows)]{- reclaim_orphan_port(&crate::service::core::active_dsh_binary(app_handle), port)?;+ reclaim_orphan_port(entry, port)?;}}log::info!("Harness stopped for installer handoff");@@ -907,6 +1088,7 @@ pub fn stop_for_installer(app_handle: &tauri::AppHandle) -> Result<(), String> {}pub fn stop_on_exit(app_handle: &tauri::AppHandle) {+ super::instances::begin_shutdown();if let Err(error) = stop_for_installer(app_handle) {log::error!("Harness exit cleanup failed: {error}");}@@ -949,6 +1131,54 @@ mod tests {.ends_with("}).await}"));}+ #[test]+ fn stop_instance_without_app_cancels_an_unowned_launch() {+ let root = tempfile::tempdir().unwrap();+ let marker = root.path().join("harness.pid");+ fs::write(&marker, "stale marker").unwrap();+ super::super::instances::scope_sync("stop-without-app-test".into(), || {+ launch_guard().store(true, Ordering::SeqCst);+ assert!(!has_owned_process());+ assert_eq!(+ stop_instance_at(+ &marker,+ 0,+ #[cfg(windows)]+ &root.path().join("entry.js"),+ ),+ Ok(())+ );+ assert!(!launch_guard().load(Ordering::SeqCst));+ assert!(!has_owned_process());+ });+ assert_eq!(marker.exists(), !cfg!(windows));+ }++ #[test]+ fn exit_closes_registration_before_stop_but_installer_keeps_restarts_available() {+ let source = include_str!("process.rs");+ let exit = source+ .split("pub fn stop_on_exit(")+ .nth(1)+ .unwrap()+ .split("#[cfg(test)]")+ .next()+ .unwrap();+ assert!(+ exit.find("super::instances::begin_shutdown();").unwrap()+ < exit.find("stop_for_installer(app_handle)").unwrap()+ );+ let installer = source+ .split("fn stop_instance_for_installer(")+ .nth(1)+ .unwrap()+ .split("pub fn stop_on_exit(")+ .next()+ .unwrap();+ assert!(installer.contains("stop_instance_at("));+ assert!(!installer.contains("begin_shutdown"));+ }+#[test]fn orphan_port_reclaim_preserves_every_registered_profile_process() {let source = include_str!("process.rs");@@ -970,7 +1200,15 @@ mod tests {/// 构造一个测试用 `OwnedProcess`(跨平台处理 Windows 句柄字段)。#[cfg(windows)]fn test_owned(pid: u32) -> OwnedProcess {- OwnedProcess { pid, handle: 0 }+ use std::os::windows::io::FromRawHandle;+ use windows_sys::Win32::System::Threading::CreateEventW;++ let handle = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) };+ assert!(!handle.is_null(), "{}", std::io::Error::last_os_error());+ OwnedProcess {+ pid,+ handle: Arc::new(unsafe { OwnedHandle::from_raw_handle(handle) }),+ }}#[cfg(not(windows))]fn test_owned(pid: u32) -> OwnedProcess {@@ -1003,13 +1241,12 @@ mod tests {use std::sync::mpsc;use std::time::Duration;+ let profile = "exit-diagnostics-test";let app = tauri::test::mock_app();let root = tempfile::tempdir().unwrap();let marker = root.path().join("fatal-report.log");- *crate::service::workflow::instances::instance()- .process- .lock()- .unwrap() = Some(test_owned(42));+ let instance = super::super::instances::instance_of(profile);+ *instance.process.lock().unwrap() = Some(test_owned(42));let (entered_tx, entered_rx) = mpsc::channel();let (resume_tx, resume_rx) = mpsc::channel();let timeout = Duration::from_secs(5);@@ -1018,23 +1255,25 @@ mod tests {let callback_marker = marker.clone();let handle = app.handle().clone();let exit = scope.spawn(move || {- on_owned_process_exit(&handle, 42, |_| {- entered_tx.send(()).unwrap();- resume_rx.recv_timeout(timeout).unwrap();- fs::write(callback_marker, "ERROR HARNESS_FATAL_REPORT: fatal.json\n").unwrap();- Some(1)+ super::super::instances::scope_sync(profile.into(), || {+ on_owned_process_exit(&handle, 42, |_| {+ entered_tx.send(()).unwrap();+ resume_rx.recv_timeout(timeout).unwrap();+ fs::write(callback_marker, "ERROR HARNESS_FATAL_REPORT: fatal.json\n")+ .unwrap();+ Some(1)+ })})});entered_rx.recv_timeout(timeout).unwrap();let callback_holds_ownership = matches!(- crate::service::workflow::instances::instance()- .process- .try_lock(),+ instance.process.try_lock(),Err(std::sync::TryLockError::WouldBlock));let observer = scope.spawn(|| {- let owned = has_owned_process();- (owned, marker.is_file())+ super::super::instances::scope_sync(profile.into(), || {+ (has_owned_process(), marker.is_file())+ })});resume_tx.send(()).unwrap();assert_eq!(exit.join().unwrap().map(|owned| owned.pid), Some(42));@@ -1043,6 +1282,206 @@ mod tests {});}+ #[test]+ fn registration_rejects_cancelled_launch_and_replaces_only_expected_pid() {+ super::super::instances::scope_sync("registration-test".into(), || {+ let launching = launch_guard();+ launching.store(true, Ordering::SeqCst);+ assert!(take_owned_process().is_none());+ assert!(!launching.load(Ordering::SeqCst));+ assert!(+ register_owned_process::<()>(None, || panic!("cancelled spawn"))+ .unwrap()+ .is_none()+ );+ assert_eq!(owned_process_pid(), None);++ launching.store(true, Ordering::SeqCst);+ assert_eq!(+ register_owned_process(None, || Ok((test_owned(41), 41))).unwrap(),+ Some(41)+ );+ assert_eq!(+ register_owned_process(Some(41), || Ok((test_owned(42), 42))).unwrap(),+ Some(42)+ );+ assert!(+ register_owned_process::<()>(Some(41), || panic!("stale retry spawn"))+ .unwrap()+ .is_none()+ );+ assert_eq!(owned_process_pid(), Some(42));+ assert_eq!(+ register_owned_process::<()>(Some(42), || Err("spawn failed".into())).unwrap_err(),+ "spawn failed"+ );+ assert_eq!(owned_process_pid(), Some(42));+ assert_eq!(take_owned_process().map(|owned| owned.pid), Some(42));+ assert!(+ register_owned_process::<()>(Some(42), || panic!("cancelled retry spawn"))+ .unwrap()+ .is_none()+ );+ assert_eq!(owned_process_pid(), None);+ });+ }++ #[test]+ fn shutdown_gate_rejects_every_profile_after_inflight_registration() {+ use std::sync::{mpsc, Mutex, TryLockError};+ use std::time::Duration;++ let shutdown = Mutex::new(false);+ let first = super::super::instances::Instance::default();+ let second = super::super::instances::Instance::default();+ first.launching.store(true, Ordering::SeqCst);+ second.launching.store(true, Ordering::SeqCst);+ let (entered_tx, entered_rx) = mpsc::channel();+ let (resume_tx, resume_rx) = mpsc::channel();+ let timeout = Duration::from_secs(5);+ std::thread::scope(|scope| {+ let first = &first;+ let shutdown = &shutdown;+ let registration = scope.spawn(move || {+ register_owned_process_at(first, shutdown, None, || {+ entered_tx.send(()).unwrap();+ resume_rx.recv_timeout(timeout).unwrap();+ Ok((test_owned(41), 41))+ })+ });+ entered_rx.recv_timeout(timeout).unwrap();+ let holds_gate = matches!(shutdown.try_lock(), Err(TryLockError::WouldBlock));+ let holds_slot = matches!(first.process.try_lock(), Err(TryLockError::WouldBlock));+ let shutdown_thread = scope.spawn(move || {+ super::super::instances::begin_shutdown_at(shutdown);+ });+ resume_tx.send(()).unwrap();+ assert_eq!(registration.join().unwrap().unwrap(), Some(41));+ shutdown_thread.join().unwrap();+ assert!(holds_gate && holds_slot);+ });+ assert!(+ register_owned_process_at::<()>(&first, &shutdown, Some(41), || {+ panic!("shutdown must reject an existing profile retry")+ })+ .unwrap()+ .is_none()+ );+ assert!(+ register_owned_process_at::<()>(&second, &shutdown, None, || {+ panic!("shutdown must reject another profile's first launch")+ })+ .unwrap()+ .is_none()+ );+ assert_eq!(+ first+ .process+ .lock()+ .unwrap()+ .as_ref()+ .map(|owned| owned.pid),+ Some(41)+ );+ assert!(second.process.lock().unwrap().is_none());+ }++ #[test]+ fn launch_guard_clears_its_own_profile_outside_original_scope() {+ let guard = super::super::instances::scope_sync("guard-owner-test".into(), || {+ let launching = launch_guard();+ launching.store(true, Ordering::SeqCst);+ LaunchGuard(launching)+ });+ super::super::instances::scope_sync("guard-drop-test".into(), || {+ let launching = launch_guard();+ launching.store(true, Ordering::SeqCst);+ drop(guard);+ assert!(launching.load(Ordering::SeqCst));+ assert!(!super::super::instances::instance_of("guard-owner-test")+ .launching+ .load(Ordering::SeqCst));+ launching.store(false, Ordering::SeqCst);+ });+ }++ #[test]+ fn exit_holds_ownership_until_status_commit_and_preserves_new_registration() {+ use std::sync::mpsc;+ use std::time::Duration;++ let profile = "exit-status-commit-test";+ let instance = super::super::instances::instance_of(profile);+ instance.launching.store(true, Ordering::SeqCst);+ *instance.process.lock().unwrap() = Some(test_owned(41));+ let mut status_guard = instance.status.lock().unwrap();+ *status_guard = status::Status::Running;+ let (exiting_tx, exiting_rx) = mpsc::channel();+ let (observed_tx, observed_rx) = mpsc::channel();+ let (notified_tx, notified_rx) = mpsc::channel();+ let timeout = std::time::Duration::from_secs(5);++ std::thread::scope(|scope| {+ let exit = scope.spawn(move || {+ super::super::instances::scope_sync(profile.into(), || {+ on_owned_process_exit_at(+ 41,+ |_| {+ exiting_tx.send(()).unwrap();+ Some(1)+ },+ |payload| {+ assert_eq!(owned_process_pid(), None);+ assert_eq!(status::get_status(), status::Status::Stopped);+ notified_tx.send(payload).unwrap();+ },+ )+ })+ });+ exiting_rx.recv_timeout(timeout).unwrap();+ let observer_instance = instance.clone();+ let observer = scope.spawn(move || {+ let guard = observer_instance.process.lock().unwrap();+ observed_tx.send(guard.is_none()).unwrap();+ });+ let blocked_until_commit = observed_rx+ .recv_timeout(Duration::from_millis(100))+ .is_err();+ drop(status_guard);+ assert_eq!(exit.join().unwrap().map(|owned| owned.pid), Some(41));+ assert!(observed_rx.recv_timeout(timeout).unwrap());+ observer.join().unwrap();+ assert!(+ blocked_until_commit,+ "ownership must stay locked until Stopped is committed"+ );+ assert_eq!(+ notified_rx.recv_timeout(timeout).unwrap(),+ HarnessProcessExitedPayload {+ pid: 41,+ exit_code: Some(1)+ }+ );+ });++ super::super::instances::scope_sync(profile.into(), || {+ assert_eq!(status::get_status(), status::Status::Stopped);+ assert!(register_owned_process(None, || Ok((test_owned(42), ())))+ .unwrap()+ .is_some());+ status::set_status(status::Status::Running);+ assert!(on_owned_process_exit_at(+ 41,+ |_| panic!("stale exit must not report"),+ |_| panic!("stale exit must not notify"),+ )+ .is_none());+ assert_eq!(owned_process_pid(), Some(42));+ assert_eq!(status::get_status(), status::Status::Running);+ take_owned_process();+ });+ }+/// 退出载荷保留退出码(含 0),无法取得时显式序列化为 null。#[test]fn harness_process_exit_payload_serializes_exit_code() {@@ -1421,6 +1860,180 @@ mod tests {assert!(alive);}+ #[cfg(windows)]+ #[test]+ fn native_command_line_rejects_truncated_or_invalid_utf16() {+ let header = std::mem::size_of::<WindowsCommandLine>();+ let command: Vec<_> = r#"node.exe "path with spaces" "payload --no-open""#+ .encode_utf16()+ .collect();+ let bytes = header + (command.len() + 1) * 2;+ let mut buffer = vec![0usize; bytes.div_ceil(std::mem::size_of::<usize>())];+ let string = unsafe { buffer.as_mut_ptr().cast::<u8>().add(header).cast::<u16>() };+ let valid = WindowsCommandLine {+ length: (command.len() * 2) as u16,+ maximum_length: ((command.len() + 1) * 2) as u16,+ buffer: string,+ };+ unsafe {+ std::ptr::copy_nonoverlapping(command.as_ptr(), string, command.len());+ buffer+ .as_mut_ptr()+ .cast::<WindowsCommandLine>()+ .write(valid);+ }+ assert_eq!(+ decode_windows_command_line(&buffer, bytes).as_deref(),+ Some(r#"node.exe "path with spaces" "payload --no-open""#)+ );+ assert!(decode_windows_command_line(&buffer, header - 1).is_none());+ assert!(decode_windows_command_line(&buffer, bytes - 1).is_none());+ assert!(+ decode_windows_command_line(&buffer, std::mem::size_of_val(buffer.as_slice()) + 1)+ .is_none()+ );+ for invalid in [+ WindowsCommandLine {+ length: valid.length - 1,+ ..valid+ },+ WindowsCommandLine {+ maximum_length: valid.length - 2,+ ..valid+ },+ WindowsCommandLine {+ buffer: std::ptr::null(),+ ..valid+ },+ WindowsCommandLine {+ buffer: buffer.as_ptr().cast(),+ ..valid+ },+ WindowsCommandLine {+ buffer: usize::MAX as *const u16,+ ..valid+ },+ ] {+ unsafe {+ buffer+ .as_mut_ptr()+ .cast::<WindowsCommandLine>()+ .write(invalid)+ };+ assert!(decode_windows_command_line(&buffer, bytes).is_none());+ }+ unsafe {+ buffer+ .as_mut_ptr()+ .cast::<WindowsCommandLine>()+ .write(valid);+ string.write(0xd800);+ }+ assert!(decode_windows_command_line(&buffer, bytes).is_none());+ unsafe { string.write(0) };+ assert!(decode_windows_command_line(&buffer, bytes).is_none());+ }++ #[cfg(windows)]+ #[test]+ fn native_process_snapshot_preserves_raw_command_line_and_filetime() {+ use std::os::windows::process::CommandExt;+ use windows_sys::Win32::Foundation::FILETIME;+ use windows_sys::Win32::System::Threading::GetProcessTimes;++ let root = tempfile::Builder::new()+ .prefix("process-snapshot 空格-")+ .tempdir()+ .unwrap();+ let raw = format!(+ r#""{}" "payload --no-open" "escaped\"quote" --no-open"#,+ root.path().join("quoted path").join("entry.js").display()+ );+ let mut child = Command::new("node.exe")+ .args(["-e", "process.stdin.resume()", "--"])+ .raw_arg(&raw)+ .current_dir(root.path())+ .creation_flags(0x08000000)+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn isolated snapshot probe");+ let checked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let mut creation: FILETIME = unsafe { std::mem::zeroed() };+ let mut exit = creation;+ let mut kernel = creation;+ let mut user = creation;+ assert_ne!(+ unsafe {+ GetProcessTimes(+ child.as_raw_handle(),+ &mut creation,+ &mut exit,+ &mut kernel,+ &mut user,+ )+ },+ 0+ );+ let expected =+ u64::from(creation.dwHighDateTime) << 32 | u64::from(creation.dwLowDateTime);+ let started = std::time::Instant::now();+ let output = windows_process_snapshot(Some(child.id())).unwrap();+ eprintln!("native target snapshot: {:?}", started.elapsed());+ let entries = String::from_utf8(output).unwrap();+ let entries: Vec<WindowsProcessEntry> = entries+ .lines()+ .map(|line| serde_json::from_str(line).unwrap())+ .collect();+ assert_eq!(entries.len(), 1);+ let entry = &entries[0];+ assert_eq!(entry.pid, child.id());+ assert_eq!(+ entry.created, expected,+ "creation time must retain 100 ns precision"+ );+ assert!(+ entry.command_line.ends_with(&raw),+ "raw quoting must survive: {}",+ entry.command_line+ );+ assert_eq!(entry.ancestors[0].pid, std::process::id());+ assert_ne!(entry.ancestors[0].created, 0);+ assert!(!entry.ancestors_truncated || entry.ancestors.len() == 8);+ let started = std::time::Instant::now();+ let output = windows_process_snapshot(None).unwrap();+ eprintln!("native full snapshot: {:?}", started.elapsed());+ let entries = String::from_utf8(output).unwrap();+ let entry = entries+ .lines()+ .map(|line| serde_json::from_str::<WindowsProcessEntry>(line).unwrap())+ .find(|entry| entry.pid == child.id())+ .expect("full snapshot must retain the controlled probe");+ assert_eq!(entry.created, expected);+ assert!(entry.command_line.ends_with(&raw));++ let source = include_str!("process.rs");+ let snapshot = source+ .split("fn windows_process_snapshot(")+ .nth(1)+ .unwrap()+ .split("fn terminate_stale_harness_processes_at(")+ .next()+ .unwrap();+ assert!(+ !snapshot.contains("Command::new("),+ "process snapshots must not spawn an interpreter"+ );+ }));+ drop(child.stdin.take());+ let exited = child.wait().expect("wait for isolated snapshot probe");+ if let Err(error) = checked {+ std::panic::resume_unwind(error);+ }+ assert!(exited.success());+ }+#[cfg(windows)]#[test]fn creation_mismatch_preserves_the_live_process() {diff --git a/src-tauri/src/service/workflow/sweep.rs b/src-tauri/src/service/workflow/sweep.rsindex 8ad906c2..1c701af3 100644--- a/src-tauri/src/service/workflow/sweep.rs+++ b/src-tauri/src/service/workflow/sweep.rs@@ -61,15 +61,6 @@ mod tests {}}-/// 记录本次启动的 Harness PID 与端口,供下次启动清扫孤儿用。-pub(super) fn persist_harness_pid(app_handle: &tauri::AppHandle, pid: u32, port: u16) {- let path = harness_pid_path(app_handle);- if let Some(dir) = path.parent() {- let _ = fs::create_dir_all(dir);- }- let _ = fs::write(&path, format!("{pid}\n{port}\n"));-}-/// 启动前清扫上次崩溃残留的孤儿 Harness。Unix 标记回收经端口与 PID 双重确认:/// - 标记进程已死 → 仅清理陈旧标记;/// - 端口占用者正是标记中的 PID → 本应用残留,结束其进程树并清标记;diff --git a/src-tauri/src/service/workflow/utils.rs b/src-tauri/src/service/workflow/utils.rsindex a8d6312c..65cba171 100644--- a/src-tauri/src/service/workflow/utils.rs+++ b/src-tauri/src/service/workflow/utils.rs@@ -1,7 +1,7 @@-use std::io::{BufRead, BufReader, Read, Write};+use std::io::{self, BufRead, BufReader, Read, Write};use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};use std::path::{Path, PathBuf};-use std::sync::{Mutex, OnceLock};+use std::sync::{mpsc, Mutex, OnceLock};use std::thread;use std::time::Duration;@@ -198,31 +198,69 @@ pub fn is_port_in_use(port: u16) -> bool {.any(|ip| TcpListener::bind(SocketAddr::new(IpAddr::V4(*ip), port)).is_err())}-/// 在独立线程中读取子进程的输出,同时写入日志文件-///-/// # 参数-/// - `stdout`: 子进程的标准输出-/// - `stderr`: 子进程的标准错误输出-/// - `log_path`: 前端日志面板读取的日志文件-pub fn spawn_output_readers<R1, R2>(stdout: Option<R1>, stderr: Option<R2>, log_path: PathBuf)+#[cfg(test)]+thread_local! {+ static OUTPUT_READER_FAILURE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+}++#[cfg(test)]+pub(super) fn with_output_reader_failure<T>(reader: usize, task: impl FnOnce() -> T) -> T {+ struct Reset(usize);+ impl Drop for Reset {+ fn drop(&mut self) {+ OUTPUT_READER_FAILURE.set(self.0);+ }+ }+ let _reset = Reset(OUTPUT_READER_FAILURE.replace(reader));+ task()+}++#[cfg(test)]+fn check_output_reader_spawn() -> io::Result<()> {+ if OUTPUT_READER_FAILURE.with(|failure| {+ let remaining = failure.get();+ failure.set(remaining.saturating_sub(1));+ remaining == 1+ }) {+ return Err(io::Error::other("injected output reader spawn failure"));+ }+ Ok(())+}++pub fn spawn_output_readers<R1, R2>(+ stdout: Option<R1>,+ stderr: Option<R2>,+ log_path: PathBuf,+) -> io::Result<mpsc::Receiver<bool>>whereR1: Read + Send + 'static,R2: Read + Send + 'static,{- // 在独立线程中读取 stdoutif let Some(stdout) = stdout {let log_path = log_path.clone();- thread::spawn(move || {- drain_subprocess_output(BufReader::new(stdout), log_path, log::Level::Info);- });+ #[cfg(test)]+ check_output_reader_spawn()?;+ thread::Builder::new().spawn(move || {+ drain_subprocess_output(BufReader::new(stdout), log_path, log::Level::Info, |_| {});+ })?;}- // 在独立线程中读取 stderr+ let (signature, receiver) = mpsc::channel();if let Some(stderr) = stderr {- thread::spawn(move || {- drain_subprocess_output(BufReader::new(stderr), log_path, log::Level::Warn);- });+ #[cfg(test)]+ check_output_reader_spawn()?;+ thread::Builder::new().spawn(move || {+ let mut reported = false;+ drain_subprocess_output(BufReader::new(stderr), log_path, log::Level::Warn, |line| {+ if !reported && line.contains("duplicate loader entry") {+ reported = true;+ let _ = signature.send(true);+ }+ });+ let _ = signature.send(false);+ })?;}+ Ok(receiver)}/// 逐行读取子进程输出并写入日志。@@ -238,6 +276,7 @@ fn drain_subprocess_output<R: Read + Send + 'static>(mut reader: BufReader<R>,log_path: PathBuf,level: log::Level,+ mut on_line: impl FnMut(&str),) {loop {let mut bytes = Vec::new();@@ -248,6 +287,7 @@ fn drain_subprocess_output<R: Read + Send + 'static>(let bytes = bytes.strip_suffix(b"\n").unwrap_or(&bytes);let bytes = bytes.strip_suffix(b"\r").unwrap_or(bytes);let line = decode_process_line(bytes);+ on_line(&line);match level {log::Level::Warn => log::warn!(target: "dsh", "{}", line),_ => log::info!(target: "dsh", "{}", line),@@ -373,6 +413,7 @@ mod tests {std::io::BufReader::new(std::io::Cursor::new(data)),log.clone(),log::Level::Warn,+ |_| {},);let content = fs::read_to_string(&log).unwrap();@@ -417,6 +458,7 @@ mod tests {std::io::BufReader::new(std::io::Cursor::new(b"a\r\nb\n".to_vec())),log.clone(),log::Level::Info,+ |_| {},);let content = fs::read_to_string(&log).unwrap();@@ -424,6 +466,34 @@ mod tests {let _ = fs::remove_dir_all(&dir);}+ #[test]+ fn output_readers_report_only_this_attempts_stderr_signature() {+ let root = tempfile::tempdir().unwrap();+ let log = root.path().join("dsh-web.log");+ let mut data = b"duplicate loader entry\n".to_vec();+ data.extend_from_slice(&vec![b'x'; 256 * 1024]);+ data.extend_from_slice(b"\nlast stderr line\n");+ let duplicate = spawn_output_readers(+ Some(std::io::Cursor::new(b"stdout ready\n".to_vec())),+ Some(std::io::Cursor::new(data)),+ log.clone(),+ )+ .unwrap();+ let timeout = Duration::from_secs(5);+ assert!(duplicate.recv_timeout(timeout).unwrap());+ assert!(!duplicate.recv_timeout(timeout).unwrap());+ let content = fs::read_to_string(&log).unwrap();+ assert!(content.contains("last stderr line\n"));++ let clean = spawn_output_readers(+ Some(std::io::Cursor::new(b"duplicate loader entry\n".to_vec())),+ Some(std::io::Cursor::new(b"unrelated error\n".to_vec())),+ log,+ )+ .unwrap();+ assert!(!clean.recv_timeout(timeout).unwrap());+ }+#[test]fn append_keeps_the_new_line_in_current_log_when_size_limit_is_reached() {let root = tempfile::tempdir().unwrap();diff --git a/src-tauri/src/service/workflow/win_inspector.rs b/src-tauri/src/service/workflow/win_inspector.rsindex de5d7652..7ac31f52 100644--- a/src-tauri/src/service/workflow/win_inspector.rs+++ b/src-tauri/src/service/workflow/win_inspector.rs@@ -48,7 +48,7 @@ mod imp {////// 自愈保证:删除后若数组为空,序列化结果自然是 `[]`(而非纯注释/空——那是/// YAML `null`,`parsePatchList` 会抛「必须是顶层数组」直接崩掉启动)。- fn prune_legacy_patch_entry(profile: &Path) -> Result<(), String> {+ pub(super) fn apply_at(profile: &Path) -> Result<(), String> {let patch_path = profile.join("cordis.patch.yml");let existing = match fs::read_to_string(&patch_path) {Ok(s) => s,@@ -132,7 +132,7 @@ mod imp {/// 清理 profile 的遗留注入行(幂等)。pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {- prune_legacy_patch_entry(&profile_dir(app_handle))+ apply_at(&profile_dir(app_handle))}#[cfg(test)]@@ -154,13 +154,13 @@ mod imp {).unwrap();- prune_legacy_patch_entry(&dir).unwrap();+ apply_at(&dir).unwrap();let out = std::fs::read_to_string(&patch).unwrap();assert!(!out.contains("win-terminal-inspector"));assert!(!out.contains("insert:"));assert!(out.contains("some-row"));- prune_legacy_patch_entry(&dir).unwrap();+ apply_at(&dir).unwrap();let again = std::fs::read_to_string(&patch).unwrap();assert_eq!(out, again);@@ -180,12 +180,12 @@ mod imp {).unwrap();- prune_legacy_patch_entry(&dir).unwrap();+ apply_at(&dir).unwrap();let out = std::fs::read_to_string(&patch).unwrap();assert!(!out.contains("win-terminal-inspector"));assert!(out.contains("[]\n"));- prune_legacy_patch_entry(&dir).unwrap();+ apply_at(&dir).unwrap();let again = std::fs::read_to_string(&patch).unwrap();assert_eq!(out, again);@@ -200,7 +200,7 @@ mod imp {let content = "- id: some-row\n config:\n a: 1\n";std::fs::write(&patch, content).unwrap();- prune_legacy_patch_entry(&dir).unwrap();+ apply_at(&dir).unwrap();assert_eq!(std::fs::read_to_string(&patch).unwrap(), content);std::fs::remove_dir_all(&dir).ok();@@ -226,6 +226,10 @@ mod imp {Ok(())}+ pub(super) fn apply_at(_profile: &std::path::Path) -> Result<(), String> {+ Ok(())+ }+/// 非 Windows 无 Git Bash bin 目录。pub fn git_bash_bin_dirs() -> Vec<std::path::PathBuf> {Vec::new()@@ -237,6 +241,10 @@ pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {imp::apply(app_handle)}+pub(crate) fn apply_at(profile: &std::path::Path) -> Result<(), String> {+ imp::apply_at(profile)+}+/// 本机 Git Bash 的 bin 目录(供服务 PATH 注入)。////// 返回 bash.exe 所在目录(`<git>\bin`)与 `<git>\usr\bin`(`ls`/`sed`/`find` 等diff --git a/src-tauri/src/service/workflow/win_spawn.rs b/src-tauri/src/service/workflow/win_spawn.rsindex f39fa529..a8b90545 100644--- a/src-tauri/src/service/workflow/win_spawn.rs+++ b/src-tauri/src/service/workflow/win_spawn.rs@@ -12,26 +12,83 @@use std::collections::HashMap;use std::ffi::OsString;use std::fs::File;-use std::io;+use std::io::{self, Read};use std::os::windows::ffi::OsStrExt;-use std::os::windows::io::{FromRawHandle, RawHandle};+use std::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, OwnedHandle};+use std::os::windows::process::ExitStatusExt;use std::path::Path;+use std::process::{ExitStatus, Output};+use std::sync::Mutex;+use std::time::{Duration, Instant};use windows_sys::Win32::Foundation::{- CloseHandle, SetHandleInformation, GENERIC_READ, GENERIC_WRITE, HANDLE, HANDLE_FLAG_INHERIT,- INVALID_HANDLE_VALUE,+ CloseHandle, SetHandleInformation, ERROR_BROKEN_PIPE, GENERIC_READ, GENERIC_WRITE, HANDLE,+ HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE, WAIT_OBJECT_0, WAIT_TIMEOUT,};use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;use windows_sys::Win32::Storage::FileSystem::{CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,};-use windows_sys::Win32::System::Pipes::CreatePipe;+use windows_sys::Win32::System::JobObjects::{+ AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicAccountingInformation,+ JobObjectExtendedLimitInformation, QueryInformationJobObject, SetInformationJobObject,+ TerminateJobObject, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION,+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,+};+use windows_sys::Win32::System::Pipes::{CreatePipe, PeekNamedPipe};use windows_sys::Win32::System::Threading::{- CreateProcessW, GetProcessId, CREATE_NEW_CONSOLE, CREATE_UNICODE_ENVIRONMENT,- PROCESS_INFORMATION, STARTF_USESHOWWINDOW, STARTF_USESTDHANDLES, STARTUPINFOW,+ CreateProcessW, GetExitCodeProcess, ResumeThread, TerminateProcess, WaitForSingleObject,+ CREATE_NEW_CONSOLE, CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, PROCESS_INFORMATION,+ STARTF_USESHOWWINDOW, STARTF_USESTDHANDLES, STARTUPINFOW,};use windows_sys::Win32::UI::WindowsAndMessaging::SW_HIDE;+#[derive(Debug)]+pub(crate) struct ProcessCleanupFailed(pub(crate) String);++impl std::fmt::Display for ProcessCleanupFailed {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(&self.0)+ }+}++impl std::error::Error for ProcessCleanupFailed {}++pub(crate) struct ProcessJob {+ handle: OwnedHandle,+}++impl ProcessJob {+ pub(crate) fn new() -> io::Result<Self> {+ let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };+ if handle.is_null() {+ return Err(io::Error::last_os_error());+ }+ let handle = unsafe { OwnedHandle::from_raw_handle(handle) };+ let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();+ limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;+ if unsafe {+ SetInformationJobObject(+ handle.as_raw_handle(),+ JobObjectExtendedLimitInformation,+ &limits as *const _ as *const core::ffi::c_void,+ std::mem::size_of_val(&limits) as u32,+ )+ } == 0+ {+ return Err(io::Error::last_os_error());+ }+ Ok(Self { handle })+ }++ pub(crate) fn terminate(&self) -> io::Result<()> {+ if unsafe { TerminateJobObject(self.handle.as_raw_handle(), 1) } == 0 {+ return Err(io::Error::last_os_error());+ }+ Ok(())+ }+}+/// 以隐藏控制台方式启动 `program`,返回其 stdout / stderr 管道读取端。////// `envs` 中的键值会覆盖当前进程环境变量后传给子进程。@@ -60,16 +117,169 @@ pub fn spawn_with_hidden_console_owned(current_dir: Option<&Path>,envs: &HashMap<String, String>,) -> io::Result<(File, File, u32, HANDLE)> {- let (stdout, stderr, handle) =- spawn_with_hidden_console_tracked(program, args, current_dir, envs)?;- let pid = unsafe { GetProcessId(handle) };- if pid == 0 {- unsafe {- CloseHandle(handle);+ spawn_with_hidden_console_inner(program, args, current_dir, envs, None, &[])+}++pub(crate) fn spawn_with_hidden_console_in_job(+ program: &Path,+ args: &[OsString],+ current_dir: Option<&Path>,+ envs: &HashMap<String, String>,+ job: &ProcessJob,+) -> io::Result<(File, File, u32, HANDLE)> {+ spawn_with_hidden_console_inner(program, args, current_dir, envs, Some(job), &[])+}++pub(crate) fn probe_in_job(+ program: &Path,+ args: &[OsString],+ job: &ProcessJob,+ registration_gate: &Mutex<bool>,+ remove_node_options: bool,+) -> io::Result<Output> {+ let (mut stdout, mut stderr, _, handle) = {+ let shutdown = registration_gate+ .lock()+ .unwrap_or_else(|error| error.into_inner());+ if *shutdown {+ return Err(io::Error::new(+ io::ErrorKind::Interrupted,+ "probe rejected during shutdown",+ ));}- return Err(io::Error::last_os_error());+ spawn_with_hidden_console_inner(+ program,+ args,+ None,+ &HashMap::new(),+ Some(job),+ if remove_node_options {+ &["NODE_OPTIONS"]+ } else {+ &[]+ },+ )?+ };+ let process = unsafe { OwnedHandle::from_raw_handle(handle) };+ let mut output = [Vec::new(), Vec::new()];+ let result = (|| {+ let deadline = Instant::now() + Duration::from_secs(8);+ loop {+ drain_probe_pipe(&mut stdout, &mut output[0])?;+ drain_probe_pipe(&mut stderr, &mut output[1])?;+ match unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } {+ WAIT_OBJECT_0 => {+ let mut code = 0;+ if unsafe { GetExitCodeProcess(process.as_raw_handle(), &mut code) } == 0 {+ return Err(io::Error::last_os_error());+ }+ break Ok(ExitStatus::from_raw(code));+ }+ WAIT_TIMEOUT => {}+ _ => return Err(io::Error::last_os_error()),+ }+ if *registration_gate+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ {+ return Err(io::Error::new(+ io::ErrorKind::Interrupted,+ "probe cancelled during shutdown",+ ));+ }+ if Instant::now() >= deadline {+ return Err(io::Error::new(io::ErrorKind::TimedOut, "probe exceeded 8s"));+ }+ std::thread::sleep(Duration::from_millis(5));+ }+ })();+ let terminate = job.terminate();+ let cleanup = (|| {+ let deadline = Instant::now() + Duration::from_secs(5);+ loop {+ let mut accounting = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default();+ if unsafe {+ QueryInformationJobObject(+ job.handle.as_raw_handle(),+ JobObjectBasicAccountingInformation,+ &mut accounting as *mut _ as *mut core::ffi::c_void,+ std::mem::size_of_val(&accounting) as u32,+ std::ptr::null_mut(),+ )+ } == 0+ {+ return Err(io::Error::last_os_error());+ }+ if accounting.ActiveProcesses == 0 {+ match unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } {+ WAIT_OBJECT_0 => {+ while drain_probe_pipe(&mut stdout, &mut output[0])?+ | drain_probe_pipe(&mut stderr, &mut output[1])?+ {+ if Instant::now() >= deadline {+ return Err(io::Error::new(+ io::ErrorKind::TimedOut,+ "probe pipes did not drain within 5s",+ ));+ }+ }+ return Ok(());+ }+ WAIT_TIMEOUT => {}+ _ => return Err(io::Error::last_os_error()),+ }+ }+ if Instant::now() >= deadline {+ return Err(io::Error::new(+ io::ErrorKind::TimedOut,+ "probe job did not exit within 5s",+ ));+ }+ std::thread::sleep(Duration::from_millis(5));+ }+ })();+ if terminate.is_err() || cleanup.is_err() {+ let fallback = terminate_and_wait(process.as_raw_handle());+ return Err(io::Error::other(ProcessCleanupFailed(format!(+ "probe result: {result:?}; job terminate: {terminate:?}; job cleanup: {cleanup:?}; process cleanup: {fallback:?}"+ ))));+ }+ let [stdout, stderr] = output;+ Ok(Output {+ status: result?,+ stdout,+ stderr,+ })+}++fn drain_probe_pipe(pipe: &mut File, output: &mut Vec<u8>) -> io::Result<bool> {+ let mut available = 0;+ if unsafe {+ PeekNamedPipe(+ pipe.as_raw_handle(),+ std::ptr::null_mut(),+ 0,+ std::ptr::null_mut(),+ &mut available,+ std::ptr::null_mut(),+ )+ } == 0+ {+ let error = io::Error::last_os_error();+ return if error.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {+ Ok(false)+ } else {+ Err(error)+ };}- Ok((stdout, stderr, pid, handle))+ let mut buffer = [0; 8192];+ let count = available.min(buffer.len() as u32) as usize;+ if count == 0 {+ return Ok(false);+ }+ let count = pipe.read(&mut buffer[..count])?;+ output.extend_from_slice(&buffer[..count.min((64 * 1024usize).saturating_sub(output.len()))]);+ Ok(count != 0)}/// 同 [`spawn_with_hidden_console`],但额外返回进程句柄,供调用方等待进程@@ -80,86 +290,71 @@ pub fn spawn_with_hidden_console_tracked(current_dir: Option<&Path>,envs: &HashMap<String, String>,) -> io::Result<(File, File, HANDLE)> {+ let (stdout, stderr, _, handle) =+ spawn_with_hidden_console_inner(program, args, current_dir, envs, None, &[])?;+ Ok((stdout, stderr, handle))+}++fn spawn_with_hidden_console_inner(+ program: &Path,+ args: &[OsString],+ current_dir: Option<&Path>,+ envs: &HashMap<String, String>,+ job: Option<&ProcessJob>,+ remove_env: &[&str],+) -> io::Result<(File, File, u32, HANDLE)> {unsafe {- // 1. 创建 stdout / stderr 匿名管道(写端可继承,交给子进程)let pipe_attrs = SECURITY_ATTRIBUTES {nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,lpSecurityDescriptor: std::ptr::null_mut(),bInheritHandle: 1,};+ let (stdout_read, stdout_write) = create_output_pipe(&pipe_attrs)?;+ let (stderr_read, stderr_write) = create_output_pipe(&pipe_attrs)?;- let mut stdout_read: HANDLE = std::ptr::null_mut();- let mut stdout_write: HANDLE = std::ptr::null_mut();- if CreatePipe(&mut stdout_read, &mut stdout_write, &pipe_attrs, 0) == 0 {- return Err(io::Error::last_os_error());- }-- let mut stderr_read: HANDLE = std::ptr::null_mut();- let mut stderr_write: HANDLE = std::ptr::null_mut();- if CreatePipe(&mut stderr_read, &mut stderr_write, &pipe_attrs, 0) == 0 {- CloseHandle(stdout_read);- CloseHandle(stdout_write);- return Err(io::Error::last_os_error());- }-- // 读取端留在父进程,禁止被子进程继承- SetHandleInformation(stdout_read, HANDLE_FLAG_INHERIT, 0);- SetHandleInformation(stderr_read, HANDLE_FLAG_INHERIT, 0);-- // 2. stdin 指向 NUL,避免 dsh 尝试 setRawMode 时报错- let mut nul = "NUL".encode_utf16().collect::<Vec<u16>>();- nul.push(0);+ let nul: Vec<u16> = "NUL\0".encode_utf16().collect();let stdin_handle = CreateFileW(nul.as_ptr(),GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,- std::ptr::null(),+ &pipe_attrs,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,std::ptr::null_mut(),);if stdin_handle == INVALID_HANDLE_VALUE {- CloseHandle(stdout_read);- CloseHandle(stdout_write);- CloseHandle(stderr_read);- CloseHandle(stderr_write);return Err(io::Error::last_os_error());}- SetHandleInformation(stdin_handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);-- // 3. 组装命令行、环境块与启动参数+ let stdin_handle = OwnedHandle::from_raw_handle(stdin_handle);let mut command_line = build_command_line(program, args);- let env_block = build_env_block(envs);-+ let env_block = build_env_block(envs, remove_env);let mut application_name = program.as_os_str().encode_wide().collect::<Vec<u16>>();application_name.push(0);-- let mut current_dir_wide: Option<Vec<u16>> = None;- if let Some(dir) = current_dir {- let mut wide = dir.as_os_str().encode_wide().collect::<Vec<u16>>();- wide.push(0);- current_dir_wide = Some(wide);- }-+ let current_dir_wide = current_dir.map(|dir| {+ dir.as_os_str()+ .encode_wide()+ .chain(std::iter::once(0))+ .collect::<Vec<u16>>()+ });let startup_info = STARTUPINFOW {cb: std::mem::size_of::<STARTUPINFOW>() as u32,dwFlags: STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES,wShowWindow: SW_HIDE as u16,- hStdInput: stdin_handle,- hStdOutput: stdout_write,- hStdError: stderr_write,+ hStdInput: stdin_handle.as_raw_handle(),+ hStdOutput: stdout_write.as_raw_handle(),+ hStdError: stderr_write.as_raw_handle(),..Default::default()};-let mut process_info = PROCESS_INFORMATION::default();-- let created = CreateProcessW(+ if CreateProcessW(application_name.as_ptr(),command_line.as_mut_ptr(),std::ptr::null(),std::ptr::null(),- 1, // bInheritHandles- CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT,+ 1,+ CREATE_NEW_CONSOLE+ | CREATE_UNICODE_ENVIRONMENT+ | if job.is_some() { CREATE_SUSPENDED } else { 0 },env_block.as_ptr() as *const core::ffi::c_void,current_dir_wide.as_ref()@@ -167,31 +362,81 @@ pub fn spawn_with_hidden_console_tracked(.unwrap_or(std::ptr::null()),&startup_info,&mut process_info,- );-- // 无论成功与否,父进程都要关闭自己持有的写端和临时句柄- CloseHandle(stdout_write);- CloseHandle(stderr_write);- CloseHandle(stdin_handle);-- if created == 0 {- CloseHandle(stdout_read);- CloseHandle(stderr_read);+ ) == 0+ {return Err(io::Error::last_os_error());}+ let process = OwnedHandle::from_raw_handle(process_info.hProcess);+ let thread = OwnedHandle::from_raw_handle(process_info.hThread);+ drop((stdout_write, stderr_write, stdin_handle));+ if let Some(job) = job {+ assign_and_resume(job, process.as_raw_handle(), thread.as_raw_handle())?;+ }+ Ok((+ File::from(stdout_read),+ File::from(stderr_read),+ process_info.dwProcessId,+ process.into_raw_handle(),+ ))+ }+}++fn create_output_pipe(attrs: &SECURITY_ATTRIBUTES) -> io::Result<(OwnedHandle, OwnedHandle)> {+ let mut read = std::ptr::null_mut();+ let mut write = std::ptr::null_mut();+ if unsafe { CreatePipe(&mut read, &mut write, attrs, 0) } == 0 {+ return Err(io::Error::last_os_error());+ }+ let read = unsafe { OwnedHandle::from_raw_handle(read) };+ let write = unsafe { OwnedHandle::from_raw_handle(write) };+ if unsafe { SetHandleInformation(read.as_raw_handle(), HANDLE_FLAG_INHERIT, 0) } == 0 {+ return Err(io::Error::last_os_error());+ }+ Ok((read, write))+}- // 进程句柄不再需要时由调用方负责关闭(tracked 调用方等待退出后关闭;- // 非 tracked 由包装函数立即关闭)。关闭线程句柄避免泄漏- CloseHandle(process_info.hThread);+fn assign_and_resume(job: &ProcessJob, process: HANDLE, thread: HANDLE) -> io::Result<()> {+ let operation = if unsafe { AssignProcessToJobObject(job.handle.as_raw_handle(), process) } == 0+ {+ "AssignProcessToJobObject"+ } else if unsafe { ResumeThread(thread) } == u32::MAX {+ "ResumeThread"+ } else {+ return Ok(());+ };+ let error = io::Error::last_os_error();+ terminate_and_wait(process).map_err(|cleanup| {+ io::Error::other(ProcessCleanupFailed(format!(+ "{operation}: {error}; cleanup: {cleanup}"+ )))+ })?;+ Err(error)+}- let stdout = File::from_raw_handle(stdout_read as RawHandle);- let stderr = File::from_raw_handle(stderr_read as RawHandle);- Ok((stdout, stderr, process_info.hProcess))+fn terminate_and_wait(process: HANDLE) -> io::Result<()> {+ let terminated = unsafe { TerminateProcess(process, 1) };+ let terminate_error = (terminated == 0).then(io::Error::last_os_error);+ match unsafe { WaitForSingleObject(process, 5000) } {+ WAIT_OBJECT_0 => terminate_error.map_or(Ok(()), Err),+ wait => {+ let wait_error = if wait == WAIT_TIMEOUT {+ io::Error::new(io::ErrorKind::TimedOut, "process did not exit within 5s")+ } else {+ io::Error::last_os_error()+ };+ Err(match terminate_error {+ Some(error) => io::Error::new(+ wait_error.kind(),+ format!("TerminateProcess: {error}; wait: {wait_error}"),+ ),+ None => wait_error,+ })+ }}}/// 构建完整的 Unicode 环境块(每个条目以 `\0` 结尾,整个块以额外 `\0` 结尾)-fn build_env_block(extra: &HashMap<String, String>) -> Vec<u16> {+fn build_env_block(extra: &HashMap<String, String>, remove: &[&str]) -> Vec<u16> {let mut vars: Vec<(OsString, OsString)> = std::env::vars_os().collect();for (key, value) in extra {let key_os = OsString::from(key);@@ -208,6 +453,11 @@ fn build_env_block(extra: &HashMap<String, String>) -> Vec<u16> {}}+ vars.retain(|(key, _)| {+ !remove+ .iter()+ .any(|name| key.eq_ignore_ascii_case(std::ffi::OsStr::new(name)))+ });let mut block = Vec::new();for (key, value) in vars {block.extend(key.encode_wide());@@ -422,6 +672,260 @@ mod tests {assert_eq!(output, format!("[\"{spec}\"]"));}+ #[test]+ fn dropping_job_terminates_node_and_its_descendant() {+ use windows_sys::Win32::System::Threading::{+ OpenProcess, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,+ };++ fn assert_send_sync<T: Send + Sync>() {}+ assert_send_sync::<ProcessJob>();+ let node = find_node_on_path().expect("node.exe required for job tests");+ let root = tempfile::tempdir().unwrap();+ let envs = isolated_node_env(root.path());+ let ready = root.path().join("descendant.pid");+ let job = ProcessJob::new().unwrap();+ let args = [+ OsString::from("-e"),+ OsString::from("const child=require('child_process').spawn(process.execPath,['-e','setTimeout(()=>process.exit(0),60000)'],{stdio:'ignore',windowsHide:true});child.once('spawn',()=>require('fs').writeFileSync(process.argv[1],String(child.pid)));child.once('error',error=>{throw error});setTimeout(()=>process.exit(0),60000)"),+ ready.clone().into_os_string(),+ ];+ let (_stdout, _stderr, _, handle) =+ spawn_with_hidden_console_in_job(&node, &args, Some(root.path()), &envs, &job).unwrap();+ let process = unsafe { OwnedHandle::from_raw_handle(handle) };+ let mut descendant = None;+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ let pid = loop {+ if let Ok(pid) = std::fs::read_to_string(&ready)+ .and_then(|text| text.parse::<u32>().map_err(io::Error::other))+ {+ break pid;+ }+ assert!(+ std::time::Instant::now() < deadline,+ "Node descendant did not start"+ );+ std::thread::sleep(std::time::Duration::from_millis(10));+ };+ let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_TERMINATE, 0, pid) };+ assert!(+ !handle.is_null(),+ "retain Node descendant: {}",+ io::Error::last_os_error()+ );+ descendant = Some(unsafe { OwnedHandle::from_raw_handle(handle) });+ let handles = [+ process.as_raw_handle(),+ descendant.as_ref().unwrap().as_raw_handle(),+ ];+ for handle in handles {+ assert_eq!(unsafe { WaitForSingleObject(handle, 0) }, WAIT_TIMEOUT);+ }+ drop(job);+ for handle in handles {+ assert_eq!(+ unsafe { WaitForSingleObject(handle, 5000) },+ WAIT_OBJECT_0,+ "dropping the job must terminate both Node generations"+ );+ }+ }));+ for handle in [Some(&process), descendant.as_ref()].into_iter().flatten() {+ if unsafe { WaitForSingleObject(handle.as_raw_handle(), 0) } != WAIT_OBJECT_0 {+ terminate_and_wait(handle.as_raw_handle()).expect("clean up owned Node fixture");+ }+ }+ if let Err(error) = result {+ std::panic::resume_unwind(error);+ }+ }++ #[test]+ fn job_assignment_failure_terminates_and_reaps_suspended_node() {+ use std::os::windows::process::CommandExt;+ use windows_sys::Win32::Foundation::{DuplicateHandle, ERROR_ACCESS_DENIED};+ use windows_sys::Win32::System::SystemServices::JOB_OBJECT_QUERY;+ use windows_sys::Win32::System::Threading::{GetCurrentProcess, CREATE_NO_WINDOW};++ let node = find_node_on_path().expect("node.exe required for job tests");+ let root = tempfile::tempdir().unwrap();+ let envs = isolated_node_env(root.path());+ let job = ProcessJob::new().unwrap();+ let mut restricted = std::ptr::null_mut();+ assert_ne!(+ unsafe {+ DuplicateHandle(+ GetCurrentProcess(),+ job.handle.as_raw_handle(),+ GetCurrentProcess(),+ &mut restricted,+ JOB_OBJECT_QUERY,+ 0,+ 0,+ )+ },+ 0,+ "duplicate query-only job handle: {}",+ io::Error::last_os_error()+ );+ let restricted = ProcessJob {+ handle: unsafe { OwnedHandle::from_raw_handle(restricted) },+ };+ let mut child = std::process::Command::new(node)+ .args(["-e", "require('fs').writeFileSync('ran','unexpected');setTimeout(()=>process.exit(0),60000)"])+ .envs(envs)+ .current_dir(root.path())+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .creation_flags(CREATE_SUSPENDED | CREATE_NO_WINDOW)+ .spawn()+ .unwrap();+ let result = assign_and_resume(&restricted, child.as_raw_handle(), std::ptr::null_mut());+ let exited = unsafe { WaitForSingleObject(child.as_raw_handle(), 0) };+ if exited != WAIT_OBJECT_0 {+ child.kill().expect("clean up suspended Node fixture");+ assert_eq!(+ unsafe { WaitForSingleObject(child.as_raw_handle(), 5000) },+ WAIT_OBJECT_0+ );+ }+ assert_eq!(+ result.unwrap_err().raw_os_error(),+ Some(ERROR_ACCESS_DENIED as i32)+ );+ assert_eq!(+ exited, WAIT_OBJECT_0,+ "assignment failure must reap before returning"+ );+ assert_eq!(child.try_wait().unwrap().unwrap().code(), Some(1));+ assert!(+ !root.path().join("ran").exists(),+ "suspended Node must not run on assignment failure"+ );+ }++ #[test]+ fn job_probe_bounds_output_reaps_descendants_and_times_out() {+ let node = find_node_on_path().expect("node.exe required for probe tests");+ let root = tempfile::tempdir().unwrap();+ let envs = isolated_node_env(root.path());+ let job = ProcessJob::new().unwrap();+ let gate = Mutex::new(false);+ let vars = HashMap::from([("nOdE_OpTiOnS".into(), "--invalid-probe-option".into())]);+ let env = String::from_utf16_lossy(&build_env_block(&vars, &["NODE_OPTIONS"]));+ assert!(!env.to_ascii_lowercase().contains("node_options="));+ let env = String::from_utf16_lossy(&build_env_block(&vars, &[]));+ assert!(env.contains("--invalid-probe-option"));+ for timeout in [false, true] {+ let ready = root.path().join(if timeout {+ "timeout.pid"+ } else {+ "success.pid"+ });+ let script = format!(+ "Object.assign(process.env,{});const fs=require('fs');const child=require('child_process').spawn(process.execPath,['-e','setTimeout(()=>process.exit(0),60000)'],{{stdio:'inherit',windowsHide:true,env:{{...process.env,NODE_NO_WARNINGS:'1'}}}});child.once('error',error=>{{throw error}});child.once('spawn',()=>{{fs.writeFileSync({},String(child.pid));fs.writeSync(1,Buffer.alloc(131072,111));fs.writeSync(2,Buffer.alloc(131072,101));{}}});",+ serde_json::to_string(&envs).unwrap(),+ serde_json::to_string(&ready).unwrap(),+ if timeout { "setTimeout(()=>process.exit(0),60000)" } else { "process.exit(0)" },+ );+ let started = Instant::now();+ let result = probe_in_job(+ &node,+ &["--no-warnings".into(), "-e".into(), script.into()],+ &job,+ &gate,+ true,+ );+ let elapsed = started.elapsed();+ let mut accounting = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default();+ assert_ne!(+ unsafe {+ QueryInformationJobObject(+ job.handle.as_raw_handle(),+ JobObjectBasicAccountingInformation,+ &mut accounting as *mut _ as *mut core::ffi::c_void,+ std::mem::size_of_val(&accounting) as u32,+ std::ptr::null_mut(),+ )+ },+ 0,+ "query probe fixture job"+ );+ assert_eq!(+ accounting.ActiveProcesses, 0,+ "probe descendants must be reaped before returning"+ );+ assert!(+ std::fs::read_to_string(ready)+ .unwrap()+ .parse::<u32>()+ .unwrap()+ > 0+ );+ if timeout {+ assert_eq!(result.unwrap_err().kind(), io::ErrorKind::TimedOut);+ assert!(elapsed >= Duration::from_secs(8));+ } else {+ let output = result.unwrap();+ assert!(output.status.success());+ assert_eq!(output.stdout, vec![b'o'; 64 * 1024]);+ assert_eq!(output.stderr, vec![b'e'; 64 * 1024]);+ }+ assert!(+ elapsed < Duration::from_secs(15),+ "probe must have a finite deadline: {elapsed:?}"+ );+ }+ let (_stdout, _stderr, _, handle) = spawn_with_hidden_console_in_job(+ &node,+ &["-e".into(), "process.exit(23)".into()],+ Some(root.path()),+ &envs,+ &job,+ )+ .expect("backend spawn must reuse the job after completed probes");+ let process = unsafe { OwnedHandle::from_raw_handle(handle) };+ let wait = unsafe { WaitForSingleObject(process.as_raw_handle(), 5000) };+ if wait != WAIT_OBJECT_0 {+ terminate_and_wait(process.as_raw_handle()).expect("clean up backend fixture");+ }+ assert_eq!(wait, WAIT_OBJECT_0);+ let mut code = 0;+ assert_ne!(+ unsafe { GetExitCodeProcess(process.as_raw_handle(), &mut code) },+ 0+ );+ assert_eq!(code, 23);+ *gate.lock().unwrap() = true;+ let error = probe_in_job(+ &node,+ &["-e".into(), "process.exit(0)".into()],+ &job,+ &gate,+ true,+ )+ .unwrap_err();+ assert_eq!(error.kind(), io::ErrorKind::Interrupted);+ }++ fn isolated_node_env(root: &Path) -> HashMap<String, String> {+ let roaming = root.join("AppData/Roaming");+ let local = root.join("AppData/Local");+ std::fs::create_dir_all(&roaming).unwrap();+ std::fs::create_dir_all(&local).unwrap();+ HashMap::from([+ ("HOME".into(), root.to_string_lossy().into_owned()),+ ("USERPROFILE".into(), root.to_string_lossy().into_owned()),+ ("APPDATA".into(), roaming.to_string_lossy().into_owned()),+ ("LOCALAPPDATA".into(), local.to_string_lossy().into_owned()),+ ("DSH_E2E_HOME".into(), root.to_string_lossy().into_owned()),+ ("NODE_OPTIONS".into(), String::new()),+ ("NODE_PATH".into(), String::new()),+ ])+ }+fn find_node_on_path() -> Option<std::path::PathBuf> {let path = std::env::var_os("PATH")?;for dir in std::env::split_paths(&path) {diff --git a/src/layout/components/iframe-notification.test.ts b/src/layout/components/iframe-notification.test.tsindex 2ff69f8e..9cb4cd3f 100644--- a/src/layout/components/iframe-notification.test.ts+++ b/src/layout/components/iframe-notification.test.ts@@ -22,6 +22,7 @@ vi.mock('@reause/core', () => ({useEventListener: vi.fn(),useWatch: vi.fn(),useTimeoutFn: () => ({ start: vi.fn(), stop: vi.fn() }),+ useUnmountedRef: () => ({ current: false }),}))vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))vi.mock('valtio-define', () => ({ useStore: (value: unknown) => value }))diff --git a/src/layout/components/iframe.test.tsx b/src/layout/components/iframe.test.tsxindex dde623e1..327b538a 100644--- a/src/layout/components/iframe.test.tsx+++ b/src/layout/components/iframe.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+import { mockIPC } from '@tauri-apps/api/mocks'import { act, cleanup, render, screen } from '@testing-library/react'import { createRef } from 'react'import { afterEach, beforeEach, expect, it, vi } from 'vitest'@@ -19,7 +20,11 @@ vi.mock('@/hooks/use-zoom-factor', () => ({ useZoomFactor: vi.fn() }))beforeEach(() => {vi.useFakeTimers()vi.spyOn(console, 'warn').mockImplementation(() => {})+ mockIPC(() => undefined)Object.assign(store.harness, {+ serviceUrl: 'http://127.0.0.1:3081',+ frontendGeneration: 1,+ frontendBootHtml: null,status: 'ready',serviceHealthy: false,serviceRunning: true,@@ -80,6 +85,120 @@ it('logs local mount and document states once per transition without adding waitexpect(JSON.stringify(vi.mocked(console.warn).mock.calls)).not.toContain('secret')})+it('preloads before health, hands live boot to the same frame, and falls back only once on failure', async () => {+ const src = 'http://127.0.0.1:3081/?dshDesktop&_dshPreload=7'+ let prepares = 0+ mockIPC((command) => {+ if (command === 'prepare_frontend_preload') {+ prepares+++ return src+ }+ })+ await act(async () => {+ render(<Iframe iframeRef={createRef()} />)+ })+ const frame = screen.getByTestId<HTMLIFrameElement>('dsh-shell-iframe')+ const post = vi.spyOn(frame.contentWindow!, 'postMessage')+ await act(async () => {+ window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, origin: 'http://127.0.0.1:3081', data: { type: 7 } }))+ })+ expect(frame.getAttribute('src')).toBe(src)+ expect(store.harness.serviceHealthy).toBe(false)+ expect(store.harness.iframeAlive).toBe(false)+ async function report(type: string, origin = 'http://127.0.0.1:3081', id = '7') {+ await act(async () => {+ window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, origin, data: { type, id } }))+ })+ }+ await report('dsh://frontend-preload:waiting', 'http://untrusted.test')+ await report('dsh://frontend-preload:waiting', undefined, '6')+ await act(async () => {+ store.harness.iframeSrc = 'http://127.0.0.1:3081/?dshDesktop&t=ready'+ store.harness.frontendBootHtml = '<!doctype html><html>authoritative health round</html>'+ store.harness.serviceHealthy = true+ })+ expect(screen.getByTestId('dsh-shell-iframe')).toBe(frame)+ expect(frame.getAttribute('src')).toBe(src)+ expect(post).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'dsh://frontend-preload:boot' }), expect.anything())+ await report('dsh://frontend-preload:waiting')+ expect(post).toHaveBeenCalledWith({ source: 'dsh-desktop', type: 'dsh://frontend-preload:boot', id: '7', html: store.harness.frontendBootHtml }, 'http://127.0.0.1:3081')+ expect(store.harness.iframeAlive).toBe(false)+ await report('dsh://frontend-preload:applied')+ await act(async () => {+ await vi.advanceTimersByTimeAsync(9000)+ })+ expect(screen.getByTestId('dsh-shell-iframe')).toBe(frame)+ await report('dsh://frontend-preload:failed')+ const fallback = screen.getByTestId<HTMLIFrameElement>('dsh-shell-iframe')+ expect(fallback).not.toBe(frame)+ expect(fallback.getAttribute('src')).toBe(store.harness.iframeSrc)+ await act(async () => {+ await vi.advanceTimersByTimeAsync(9000)+ })+ expect(screen.getByTestId('dsh-shell-iframe')).toBe(fallback)+ expect(prepares).toBe(1)+})++it.each([+ ['template rejection', 'dsh://frontend-preload:failed'],+ ['timeout', null],+ ['missing health HTML', 'dsh://frontend-preload:waiting'],+ ['boot stall', 'dsh://plugin-boot:stalled'],+])('invalidates the old document on %s fallback so the replacement watchdog can report failure', async (_, type) => {+ mockIPC(command => command === 'prepare_frontend_preload' ? 'http://127.0.0.1:3081/?dshDesktop&_dshPreload=7' : undefined)+ await act(async () => {+ render(<Iframe iframeRef={createRef()} />)+ })+ const preload = screen.getByTestId<HTMLIFrameElement>('dsh-shell-iframe')+ await act(async () => {+ preload.dispatchEvent(new Event('load'))+ window.dispatchEvent(new MessageEvent('message', {+ source: preload.contentWindow,+ origin: 'http://127.0.0.1:3081',+ data: { type: 'dsh://sidebar:collapsed' },+ }))+ })+ expect(store.harness.iframeAlive).toBe(true)+ expect(store.harness.iframeLoaded).toBe(true)+ await act(async () => {+ store.harness.iframeSrc = 'http://127.0.0.1:3081/?dshDesktop&t=ready'+ store.harness.frontendBootHtml = type === 'dsh://frontend-preload:waiting' ? null : '<!doctype html><html>authoritative health round</html>'+ store.harness.serviceHealthy = true+ })+ await act(async () => {+ if (type === null) {+ await vi.advanceTimersByTimeAsync(8000)+ }+ else {+ window.dispatchEvent(new MessageEvent('message', {+ source: preload.contentWindow,+ origin: 'http://127.0.0.1:3081',+ data: { type, id: '7' },+ }))+ }+ })+ const fallback = screen.getByTestId<HTMLIFrameElement>('dsh-shell-iframe')+ expect(fallback).not.toBe(preload)+ expect(fallback.getAttribute('src')).toBe(store.harness.iframeSrc)+ expect(store.harness.iframeAlive).toBe(false)+ expect(store.harness.iframeLoaded).toBe(false)+ await act(async () => {+ fallback.dispatchEvent(new Event('load'))+ })+ expect(store.harness.iframeLoaded).toBe(true)+ await act(async () => {+ await vi.advanceTimersByTimeAsync(4999)+ })+ expect(screen.queryByText('ui.iframe_error')).toBeNull()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1)+ })+ expect(screen.getByText('ui.iframe_error')).not.toBeNull()+ expect(fallback.style.visibility).toBe('hidden')+ expect(store.harness.serviceHealthy).toBe(true)+ expect(store.harness.serviceRunning).toBe(true)+})+it('diagnoses remote frame visibility across local health and error transitions without changing it', async () => {render(<Iframe iframeRef={createRef()} srcOverride="https://example.test/?token=secret" />)expect(screen.getByTestId('dsh-shell-iframe').getAttribute('src')).toBe('https://example.test/?token=secret')diff --git a/src/layout/components/iframe.tsx b/src/layout/components/iframe.tsxindex e3a4113a..92ee3fcb 100644--- a/src/layout/components/iframe.tsx+++ b/src/layout/components/iframe.tsx@@ -11,7 +11,7 @@ import {import { CircleExclamation } from '@gravity-ui/icons'import { toast } from '@heroui/react'import { useOverlay } from '@overlastic/react'-import { useEventListener, useTimeoutFn, useWatch } from '@reause/core'+import { useEventListener, useTimeoutFn, useUnmountedRef, useWatch } from '@reause/core'import { invoke } from '@tauri-apps/api/core'import { getCurrentWindow } from '@tauri-apps/api/window'import { useRef, useState } from 'react'@@ -217,8 +217,13 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrconst remoteMode = srcOverride !== null && srcOverride !== ''const [loadedUrl, setLoadedUrl] = useState('')const remoteLoading = remoteMode && loadedUrl !== srcOverride+ const preloadKey = `${harness.frontendGeneration}#${harness.iframeKey}#${harness.serviceUrl}`+ const [preload, setPreload] = useState<{ key: string, src: string, id: string, waiting: boolean, applied: boolean } | null>(null)+ const [preloadFailed, setPreloadFailed] = useState('')+ const activePreload = !remoteMode && preload?.key === preloadKey && preloadFailed !== preloadKey ? preload : null+ const frameSrc = remoteMode ? srcOverride : activePreload?.src ?? harness.iframeSrc// 换帧(本地重挂 / 换远端隧道 / 重载)即视为新一代文档:旧文档的外观确认不能替它背书。- const frameKey = `${remoteMode ? srcOverride : 'local'}#${harness.iframeKey}`+ const frameKey = `${frameSrc}#${harness.iframeKey}`const [bootFrame, setBootFrame] = useState<string | null>(null)const appearance = normalizeAppearance(setting.appearance)const translucent = (window as Window & { __DSH_TRANSPARENT__?: boolean }).__DSH_TRANSPARENT__ === true@@ -228,7 +233,7 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr// 握手兜底:帧内接收器异常时不能让 iframe 永久藏住,超时后按「未确认」直接揭开。const appearancePending = translucent && bootFrame !== frameKeyconst iframeHidden = appearancePending || remoteLoading || harness.showIframeError- const mounted = remoteMode || harness.serviceHealthy+ const mounted = remoteMode || activePreload !== null || harness.serviceHealthyconst showIframeError = !remoteMode && harness.showIframeErrorconst documentWaiting = !remoteMode && mounted && !harness.iframeAlive && !showIframeError && !appearancePendingconst branch = !mounted ? 'service-wait' : showIframeError ? 'iframe-error' : remoteLoading ? 'remote-loading' : appearancePending ? 'appearance-wait' : documentWaiting ? 'document-wait' : remoteMode ? 'remote-frame' : 'local-frame'@@ -251,12 +256,55 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: IfriframeHidden,})}, { immediate: true })+ const unmounted = useUnmountedRef()+ const preloadRequestRef = useRef(0)+ useWatch([preloadKey, remoteMode], () => {+ const request = ++preloadRequestRef.current+ if (remoteMode) {+ setPreload(null)+ return+ }+ if (store.harness.serviceHealthy)+ return+ void invoke<string | null>('prepare_frontend_preload').then((src) => {+ if (unmounted.current || request !== preloadRequestRef.current || !src || store.harness.serviceHealthy)+ return+ const url = new URL(src)+ const id = url.searchParams.get('_dshPreload')+ if (id && url.origin === store.harness.serviceUrl)+ setPreload({ key: preloadKey, src, id, waiting: false, applied: false })+ }).catch(error => console.warn('[Iframe] native frontend preload unavailable:', error))+ }, { immediate: true })+ function fallbackPreload() {+ store.harness.markIframeLeaving()+ setPreloadFailed(preloadKey)+ }+ useWatch([activePreload?.id, activePreload?.waiting, harness.serviceHealthy, harness.frontendBootHtml], () => {+ if (!activePreload?.waiting || activePreload.applied || !harness.serviceHealthy)+ return+ if (!harness.frontendBootHtml) {+ fallbackPreload()+ return+ }+ post({ type: 'dsh://frontend-preload:boot', id: activePreload.id, html: harness.frontendBootHtml })+ }, { immediate: true })+ const { start: armPreloadFallback, stop: stopPreloadFallback } = useTimeoutFn(+ fallbackPreload,+ 8000,+ { immediate: false },+ )+ useWatch([activePreload?.id, activePreload?.applied, harness.serviceHealthy], () => {+ if (activePreload && !activePreload.applied && harness.serviceHealthy)+ armPreloadFallback()+ else+ stopPreloadFallback()+ }, { immediate: true })const { start: armAppearanceFallback, stop: stopAppearanceFallback } = useTimeoutFn(() => setBootFrame(frameKey),APPEARANCE_HANDSHAKE_TIMEOUT,{ immediate: false },)- useWatch([frameKey, remoteMode || harness.serviceHealthy], ([, mounted]) => {+ useWatch([frameKey, mounted], ([, mounted]) => {setBootFrame(null)if (mounted)armAppearanceFallback()@@ -266,7 +314,7 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr// iframe 与外观投影同一次提交挂载:src 落定后立刻把启动期 CSS 交给帧内接收器// (帧内自己也会 document-start 主动请求一次,两条通路互为兜底)。useWatch(- [remoteMode ? srcOverride : harness.iframeSrc, bootCss],+ [frameSrc, bootCss],([src, css]) => {if (!src)return@@ -301,6 +349,23 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr// iframe → 宿主:iframe 自身的桥共用一个监听器,按 `data.type` 分发useIframeMessage<IframeBridgeMessage>(iframeRef, (data) => {+ if (typeof data.type !== 'string')+ return+ if (data.type.startsWith('dsh://frontend-preload:')) {+ if (!activePreload || data.id !== activePreload.id)+ return+ if (data.type === 'dsh://frontend-preload:waiting') {+ setPreload({ ...activePreload, waiting: true })+ }+ else if (data.type === 'dsh://frontend-preload:applied') {+ setPreload({ ...activePreload, applied: true })+ }+ else if (data.type === 'dsh://frontend-preload:failed') {+ console.warn('[Iframe] native frontend preload failed; using live HTTP:', data.detail)+ fallbackPreload()+ }+ return+ }// 帧内文档离开(帧内导航):旧确认立刻作废,等新文档自己重新自报(issue #705);// 外观确认同样作废,并重新隐蔽 iframe + 重挂兜底,避免旧样式作用在新文档上。if (data.type === 'dsh://plugin-boot:leaving') {@@ -345,6 +410,11 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrstore.harness.markIframeBootReady()breakcase 'dsh://plugin-boot:stalled':+ if (activePreload && !activePreload.applied) {+ if (harness.serviceHealthy)+ fallbackPreload()+ break+ }void store.harness.recoverIframeBoot()breakcase 'dsh://plugin-boot:failed':@@ -605,11 +675,11 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrreturn (<div className="relative min-h-0 flex-1"><If- cond={remoteMode || harness.serviceHealthy}+ cond={mounted}else={<Loadable subtitle={t(harness.startupStatusKey)} />}><iframe- key={remoteMode ? `remote-${srcOverride}` : harness.iframeKey}+ key={`${remoteMode ? `remote-${srcOverride}` : activePreload?.id ?? 'http'}#${harness.iframeKey}`}ref={iframeRef}data-testid="dsh-shell-iframe"className="h-full w-full"@@ -617,7 +687,7 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr// 会先按不透明画一帧,露出那一下比等待更刺眼。上面的 Loadable 与之逐项同构,// 揭开时视觉无跳变,且有 4s 兜底不会永久藏住。style={{ visibility: appearancePending || remoteLoading || harness.showIframeError ? 'hidden' : 'visible' }}- src={remoteMode ? srcOverride : harness.iframeSrc}+ src={frameSrc}allow="accelerometer; ambient-light-sensor; autoplay; battery; camera; clipboard-read; clipboard-write; display-capture; document-domain; encrypted-media; fullscreen; gamepad; geolocation; gyroscope; hid; idle-detection; keyboard-map; magnetometer; microphone; midi; payment; picture-in-picture; publickey-credentials-get; screen-wake-lock; serial; speaker-selection; usb; web-share; xr-spatial-tracking"sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-modals allow-downloads allow-storage-access-by-user-activation"onLoad={() => {diff --git a/src/store/modules/harness/readiness.ts b/src/store/modules/harness/readiness.tsindex 08428dfe..a6cf83e0 100644--- a/src/store/modules/harness/readiness.ts+++ b/src/store/modules/harness/readiness.ts@@ -8,6 +8,8 @@ export type ReadinessTimeout = 'inactivity' | 'absolute'export interface ReadinessProbeResult {healthy: booleannotOwned: boolean+ bootHtml?: string+ bootOrigin?: string/*** 服务端口尚未被监听(本地门禁直接判定,探测几乎零成本)。*@@ -203,7 +205,7 @@ export async function waitForActivityTask<T>({let value: T | undefinedlet failure: unknown- void task.then(+ const completion = task.then((result) => {value = resultsettled = true@@ -242,14 +244,17 @@ export async function waitForActivityTask<T>({reason: snapshot.reason,}}- await wait(boundedWait(- intervalMs,- now(),- startedAt,- lastActivityAt,- inactivityTimeoutMs,- absoluteTimeoutMs,- ))+ await Promise.race([+ completion,+ wait(boundedWait(+ intervalMs,+ now(),+ startedAt,+ lastActivityAt,+ inactivityTimeoutMs,+ absoluteTimeoutMs,+ )),+ ])}return {diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.tsindex fa6b8d10..0c9be62b 100644--- a/src/store/modules/harness/store.ts+++ b/src/store/modules/harness/store.ts@@ -1,6 +1,6 @@import type { UnlistenFn } from '@tauri-apps/api/event'import type { PolicyBlockedVersion } from '../preinstall'-import type { StartupPhase } from './readiness'+import type { ReadinessProbeResult, StartupPhase } from './readiness'import type {HarnessProcessExitedPayload,InstallerState,@@ -113,6 +113,8 @@ export const harness = defineStore({serviceUrl: 'http://127.0.0.1:3080',/** 带时间戳的 iframe 地址(boot 时生成一次,避免缓存) */iframeSrc: '',+ frontendGeneration: 0,+ frontendBootHtml: null as string | null,iframeLoaded: false,iframeError: false,/**@@ -153,6 +155,11 @@ export const harness = defineStore({},},actions: {+ resetFrontendPreload() {+ this.frontendGeneration+++ this.frontendBootHtml = null+ },+/** 首次挂载时自动启动(StrictMode 重复挂载下保证只执行一次) */startup() {if (bootStarted)@@ -214,6 +221,7 @@ export const harness = defineStore({}const exitToken = ++bootToken+ this.resetFrontendPreload()const message = i18next.t(runtimeExitMessageKey(payload.exitCode), {code: payload.exitCode,})@@ -415,7 +423,7 @@ export const harness = defineStore({},/** 服务探测通过后的统一收尾;token 用于阻止旧启动流程覆盖新状态 */- async completeReadiness(token: number): Promise<boolean> {+ async completeReadiness(token: number, probe?: ReadinessProbeResult): Promise<boolean> {if (token !== bootToken)return false@@ -443,6 +451,7 @@ export const harness = defineStore({this.serviceUrl = readyInfo.service_urlthis.iframeSrc = generateTimestampedUrl(readyInfo.service_url)+ this.frontendBootHtml = probe?.bootOrigin === readyInfo.service_url ? probe.bootHtml ?? null : nullresetPortConflictRestarts()this.serviceHealthy = truethis.serviceRunning = true@@ -475,6 +484,12 @@ export const harness = defineStore({/** 拉起服务并等待健康检查通过,通过后才允许挂载 iframe */async launchAndWait(token?: number) {+ const launchToken = token ?? ++bootToken+ if (launchToken !== bootToken)+ return+ if (token === undefined)+ this.resetFrontendPreload()+ this.frontendBootHtml = nullthis.status = 'ready'this.installer = initialInstallerthis.errorMsg = ''@@ -492,17 +507,21 @@ export const harness = defineStore({this.startupReason = i18next.t('status.loading_process')try {await invoke('launch_harness')+ if (launchToken !== bootToken)+ returnthis.serviceRunning = truethis.startupPhase = 'process-boot'this.startupReason = i18next.t('status.loading_process')// 后端遇到端口占用时会自动递增并持久化端口,启动后重新读取真实地址。const runtimeInfo = await invoke<{ service_url: string }>('get_runtime_info')+ if (launchToken !== bootToken)+ returnthis.serviceUrl = runtimeInfo.service_urlthis.iframeSrc = generateTimestampedUrl(runtimeInfo.service_url)const result = await pollHarnessReadiness(STARTUP_ABSOLUTE_TIMEOUT,- () => token === undefined || token === bootToken,+ () => launchToken === bootToken,(probe) => {if (probe.phase) {this.startupPhase = probe.phase@@ -510,7 +529,7 @@ export const harness = defineStore({this.startupReason = probe.reason ?? ''},)- if (token !== undefined && token !== bootToken) {+ if (launchToken !== bootToken) {return}if (!result.healthy) {@@ -529,10 +548,10 @@ export const harness = defineStore({// (auto_start)而提前返回,此刻端口若尚未落库,上面读到的 service_url 会是// 旧端口;健康检查通过意味着服务已在最终端口就绪,此时读取必然准确。// 避免 iframe 挂载到一个无人监听的地址(表现为首次加载失败、刷新后恢复)。- const readinessToken = token ?? bootToken+ const readinessToken = launchTokenreadinessCommitToken = readinessTokentry {- await this.completeReadiness(readinessToken)+ await this.completeReadiness(readinessToken, result)}finally {if (readinessCommitToken === readinessToken)@@ -549,6 +568,7 @@ export const harness = defineStore({/** 启动流程:检测环境/安装依赖 → 拉起服务 → 已安装时后台检查更新 */async boot() {const token = ++bootToken+ this.resetFrontendPreload()if (policyApprovalKey !== undefined) {toast.close(policyApprovalKey)policyApprovalKey = undefined@@ -771,6 +791,7 @@ export const harness = defineStore({returnthis.busyAction = 'start'++bootToken+ this.resetFrontendPreload()const healthy = this.serviceHealthythis.serviceHealthy = falsetry {@@ -797,6 +818,8 @@ export const harness = defineStore({if (this.busyAction)returnthis.busyAction = 'restart'+ ++bootToken+ this.resetFrontendPreload()// 重启旧进程前先撤下旧 iframe;这样延迟到达的旧进程退出事件不会被// 误当成新一代启动失败。新进程通过 completeReadiness 后再恢复 healthy。this.serviceHealthy = false@@ -875,6 +898,7 @@ export const harness = defineStore({if (this.busyAction)return++bootToken+ this.resetFrontendPreload()this.busyAction = 'repair'try {await repair()@@ -906,6 +930,8 @@ export const harness = defineStore({if (this.busyAction)returnthis.busyAction = 'shutdown'+ ++bootToken+ this.resetFrontendPreload()// 停止服务后应用回到「已停止」态,配置弹窗已无意义,与 restart 一致地关闭它void hooks['config.dialog.hidden'].trigger()try {diff --git a/src/store/modules/harness/utils.ts b/src/store/modules/harness/utils.tsindex e61395e2..6284d730 100644--- a/src/store/modules/harness/utils.ts+++ b/src/store/modules/harness/utils.ts@@ -80,10 +80,10 @@ export async function checkHealthViaProxy(): Promise<ReadinessProbeResult> {const timeoutPromise = new Promise<never>((_, reject) => {timeoutId = setTimeout(() => reject(new Error('health check timeout')), 8000)})- const resultPromise = invoke<string>('proxy_health_check')+ const resultPromise = invoke<string | { status: string, boot_html: string, service_url: string }>('proxy_health_check')const result = await Promise.race([resultPromise, timeoutPromise])-- const lower = result.toLowerCase()+ const status = typeof result === 'string' ? result : result.status+ const lower = status.toLowerCase()if (lower.startsWith('healthy')) {// 正常路径不写日志:就绪轮询每 1s 成功一次,成功噪音只会盖住真正有用的// 失败重试行。@@ -91,15 +91,16 @@ export async function checkHealthViaProxy(): Promise<ReadinessProbeResult> {healthy: true,notOwned: false,phase: 'client-modules',- reason: result,+ reason: status,+ ...(typeof result === 'string' ? {} : { bootHtml: result.boot_html, bootOrigin: result.service_url }),}}- console.warn('[Harness] health check returned:', result)+ console.warn('[Harness] health check returned:', status)return {healthy: false,notOwned: false,phase: 'client-modules',- reason: result,+ reason: status,}}catch (err) {diff --git a/test/e2e/desktop/boot.e2e.ts b/test/e2e/desktop/boot.e2e.tsindex d831c9c7..4702f755 100644--- a/test/e2e/desktop/boot.e2e.ts+++ b/test/e2e/desktop/boot.e2e.ts@@ -163,8 +163,17 @@ describe.skipIf(process.platform === 'darwin')('桌面端启动冒烟', () => {await browser.$(SHELL_ROOT).waitForExist({ timeout: 30_000 })return handle}+ async function closeWindow(handle: string) {+ const { protocol, hostname, port, path } = browser.options+ // WDIO 的 closeWindow 回包会触发未等待的自动切窗,绕过该命令事件。+ const response = await fetch(`${protocol}://${hostname}:${port}${(path ?? '').replace(/\/+$/, '')}/session/${encodeURIComponent(browser.sessionId)}/window`, { method: 'DELETE', signal: AbortSignal.timeout(30_000) })+ const result = await response.json()+ expect(response.ok, `关闭原生窗口 ${handle} HTTP ${response.status}: ${JSON.stringify(result)}`).toBe(true)+ expect(result, `关闭原生窗口 ${handle} 协议失败`).toEqual({ value: expect.any(Array) })+ await browser.waitUntil(async () => !(await browser.getWindowHandles()).includes(handle), { timeout: 30_000, timeoutMsg: `原生窗口 ${handle} 未销毁` })+ }async function healthy() {- return invoke<string>('proxy_health_check')+ return (await invoke<{ status: string }>('proxy_health_check')).status}let clonedProfile: string | undefinedlet switchedProfile = false@@ -186,8 +195,8 @@ describe.skipIf(process.platform === 'darwin')('桌面端启动冒烟', () => {await invoke('launch_harness')await browser.waitUntil(async () => {const result = await browser.execute(async () => {- const bridge = (window as unknown as { __TAURI_INTERNALS__: { invoke: (command: string) => Promise<string> } }).__TAURI_INTERNALS__- return bridge.invoke('proxy_health_check').then(value => value.startsWith('healthy - '), (error: unknown) => {+ const bridge = (window as unknown as { __TAURI_INTERNALS__: { invoke: (command: string) => Promise<{ status: string }> } }).__TAURI_INTERNALS__+ return bridge.invoke('proxy_health_check').then(value => value.status.startsWith('healthy - '), (error: unknown) => {if (String(error).startsWith('HARNESS_NOT_READY:'))return falsethrow error@@ -212,10 +221,10 @@ describe.skipIf(process.platform === 'darwin')('桌面端启动冒烟', () => {expect(readFileSync(originalMarkerPath, 'utf8'), '其他窗口切档案不得重启原核心').toBe(originalMarker)expect(await healthy(), '第二档案启动后原核心必须仍健康').toMatch(/^healthy - /)await browser.switchToWindow(third)- await browser.closeWindow()+ await closeWindow(third)await browser.switchToWindow(second)expect(await healthy(), '关闭同档案的非最后窗口不得停止核心').toMatch(/^healthy - /)- await browser.closeWindow()+ await closeWindow(second)await browser.switchToWindow('main')await browser.waitUntil(async () => !existsSync(clonedMarkerPath), { timeout: 30_000, timeoutMsg: '关闭档案最后窗口后核心 PID 标记未回收' })expect(readFileSync(originalMarkerPath, 'utf8'), '关闭其他档案窗口不得重启原核心').toBe(originalMarker)@@ -225,7 +234,7 @@ describe.skipIf(process.platform === 'darwin')('桌面端启动冒烟', () => {for (const handle of windows.reverse()) {if ((await browser.getWindowHandles()).includes(handle)) {await browser.switchToWindow(handle)- await browser.closeWindow()+ await closeWindow(handle)}}await browser.switchToWindow('main')diff --git a/test/frontend-preload.test.ts b/test/frontend-preload.test.tsnew file mode 100644index 00000000..85a43e24--- /dev/null+++ b/test/frontend-preload.test.ts@@ -0,0 +1,139 @@+// @vitest-environment jsdom+import { createContext, runInContext } from 'node:vm'+import { expect, it } from 'vitest'+import script from '../src-tauri/src/desktop/frontend_preload.js.inc?raw'++const template = '<!doctype html><html lang="en"><head>\n<meta charset="utf-8"><script type="module" crossorigin src="./assets/app.js"></script>\n</head><body>\n<div id="root"></div>\n</body></html>'+const head = '<base href="./"><script>globalThis.order = ["loader"]; globalThis.__ModuleLoader__ = {};</script><script src="plugins/bootstrap/client.js?rev=1&x=2"></script><script>globalThis["__DSH_BOOT__"] = {entries:[]}; order.push("graph");</script><script>globalThis.dshDesktop = {protocolVersion:1};</script>'+const ready = '<script>(globalThis.__DSH_BOOT_READY__ ??= Promise.withResolvers()).resolve()</script>'+const live = template.replace('<head>', `<head>${head}`).replace('<body>', `<body>${ready}`)++function createHarness() {+ const document = new DOMParser().parseFromString(template, 'text/html')+ const messages: { type: string, id: string }[] = []+ const listeners = new Map<string, Set<(event: unknown) => void>>()+ const pending: HTMLScriptElement[] = []+ const parent = {+ postMessage(message: { type: string, id: string }, origin: string) {+ expect(origin).toBe('http://tauri.localhost')+ messages.push(message)+ },+ }+ const window = {+ parent,+ addEventListener(type: string, listener: (event: unknown) => void) {+ if (!listeners.has(type))+ listeners.set(type, new Set())+ listeners.get(type)!.add(listener)+ },+ removeEventListener(type: string, listener: (event: unknown) => void) {+ listeners.get(type)?.delete(listener)+ },+ }+ const VmContext = createContext({+ document,+ window,+ DOMParser,+ Node,+ URL,+ Promise,+ location: new URL('http://127.0.0.1:3081/?dshDesktop&_dshPreload=7'),+ preload: { id: '7', parentOrigin: 'http://tauri.localhost', template },+ })+ function fire(type: string, event: unknown) {+ for (const listener of [...(listeners.get(type) ?? [])])+ listener(event)+ }+ for (const target of [document.head, document.body]) {+ const insert = target.insertBefore.bind(target)+ target.insertBefore = function insertAndRun<T extends Node>(node: T, anchor: Node | null): T {+ const result = insert(node, anchor)+ if (node.nodeName === 'SCRIPT') {+ const element = node as unknown as HTMLScriptElement+ if (element.hasAttribute('src')) {+ pending.push(element)+ }+ else {+ try {+ runInContext(element.textContent ?? '', VmContext)+ }+ catch (error) {+ fire('error', { error })+ }+ }+ }+ return result+ }+ }+ runInContext(script, VmContext)+ function send(html = live, overrides: Record<string, unknown> = {}) {+ fire('message', {+ source: parent,+ origin: 'http://tauri.localhost',+ data: { source: 'dsh-desktop', type: 'dsh://frontend-preload:boot', id: '7', html },+ ...overrides,+ })+ }+ return { context: VmContext, document, messages, pending, send, fire }+}++it('keeps the real frontend gate closed until same-parent live injections and blocking scripts finish', async () => {+ const frame = createHarness()+ let resolved = false+ void frame.context.__DSH_BOOT_READY__.promise.then(() => {+ resolved = true+ })+ frame.fire('DOMContentLoaded', {})+ expect(frame.messages).toEqual([{ type: 'dsh://frontend-preload:waiting', id: '7', detail: undefined }])+ frame.send(live, { source: {} })+ frame.send(live, { origin: 'http://untrusted.test' })+ frame.send(live, { data: { source: 'dsh-desktop', type: 'dsh://frontend-preload:boot', id: '6', html: live } })+ expect(frame.pending).toHaveLength(0)+ expect(frame.context.__ModuleLoader__).toBeUndefined()++ frame.send()+ expect(frame.context.order).toEqual(['loader'])+ expect(frame.pending[0].getAttribute('src')).toBe('plugins/bootstrap/client.js?rev=1&x=2')+ expect(resolved).toBe(false)+ runInContext('order.push("bootstrap"); __ModuleLoader__.loaded = true', frame.context)+ frame.pending[0].onload!(new Event('load'))+ await new Promise(resolve => setTimeout(resolve, 0))+ expect(resolved).toBe(true)+ expect(frame.context.order).toEqual(['loader', 'bootstrap', 'graph'])+ expect(frame.context.__DSH_BOOT__).toEqual({ entries: [] })+ expect(frame.context.dshDesktop).toEqual({ protocolVersion: 1 })+ expect(frame.context.__DSH_TRANSPORT__).toBeUndefined()+ expect(frame.document.head.firstElementChild?.tagName).toBe('BASE')+ expect(frame.document.querySelectorAll('script[type="module"]')).toHaveLength(1)+ expect(frame.messages.at(-1)?.type).toBe('dsh://frontend-preload:applied')+})++it('rejects unknown live templates and non-owned script sources before executing any injection', async () => {+ for (const html of [+ live.replace('assets/app.js', 'assets/other.js'),+ live.replace('plugins/bootstrap/client.js', 'https://untrusted.test/plugins/client.js'),+ live.replace('<script src=', '<script async src='),+ live.replace(ready, ''),+ ]) {+ const frame = createHarness()+ frame.send(html)+ await Promise.resolve()+ await Promise.resolve()+ expect(frame.context.__ModuleLoader__).toBeUndefined()+ expect(frame.messages.at(-1)?.type).toBe('dsh://frontend-preload:failed')+ }+})++it('rejects failed bootstrap scripts instead of resolving a partial or fake session', async () => {+ const frame = createHarness()+ let resolved = false+ void frame.context.__DSH_BOOT_READY__.promise.then(() => {+ resolved = true+ }, () => {})+ frame.send(live.replace('order.push("graph");', 'throw new Error("bad graph");'))+ frame.pending[0].onload!(new Event('load'))+ await new Promise(resolve => setTimeout(resolve, 0))+ expect(resolved).toBe(false)+ expect(frame.messages.at(-1)?.type).toBe('dsh://frontend-preload:failed')+ expect(frame.messages.some(message => message.type === 'dsh://frontend-preload:applied')).toBe(false)+})diff --git a/test/harness-health-logging.test.ts b/test/harness-health-logging.test.tsindex dc2a4e3b..888ee926 100644--- a/test/harness-health-logging.test.ts+++ b/test/harness-health-logging.test.ts@@ -22,6 +22,13 @@ describe('harness health probe logging', () => {expect(warn).not.toHaveBeenCalled()})+ it('returns the authoritative document from the same successful health round without probing again', async () => {+ invokeMock.mockResolvedValue({ status: 'healthy - 70/70 client modules ready', boot_html: '<html>live boot</html>', service_url: 'http://127.0.0.1:3081' })+ const result = await checkHealthViaProxy()+ expect(result).toMatchObject({ healthy: true, bootHtml: '<html>live boot</html>', bootOrigin: 'http://127.0.0.1:3081' })+ expect(invokeMock).toHaveBeenCalledExactlyOnceWith('proxy_health_check')+ })+it('treats an unlistened port as a normal early-startup state', async () => {invokeMock.mockRejectedValue(new Error('HARNESS_NOT_READY: Harness service is not listening yet (port 3081)'),diff --git a/test/readiness.test.ts b/test/readiness.test.tsindex d0c48ad9..0a4980eb 100644--- a/test/readiness.test.ts+++ b/test/readiness.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { BoundedReloadGate, pollReadiness, SingleFlight, waitForActivityTask } from '../src/store/modules/harness/readiness'function noWait(): Promise<void> {@@ -197,6 +197,46 @@ describe('pollReadiness', () => {})describe('waitForActivityTask', () => {+ afterEach(() => vi.useRealTimers())++ it.each(['resolve', 'reject'] as const)('wakes when a pending task %s before the polling interval ends', async (settlement) => {+ vi.useFakeTimers()+ const startedAt = Date.now()+ const task = Promise.withResolvers<string>()+ const failure = new Error('plugin installation failed')+ const settled = vi.fn()+ const result = waitForActivityTask({+ task: task.promise,+ getActivity: () => ({ sequence: 0, reason: 'checking plugins' }),+ inactivityTimeoutMs: 30_000,+ absoluteTimeoutMs: 60_000,+ intervalMs: 1000,+ }).then(settled, settled)++ await vi.advanceTimersByTimeAsync(10)+ expect(settled).not.toHaveBeenCalled()+ if (settlement === 'resolve')+ task.resolve('installed')+ else+ task.reject(failure)+ await vi.advanceTimersByTimeAsync(0)++ expect(settled).toHaveBeenCalledTimes(1)+ if (settlement === 'resolve') {+ expect(settled.mock.calls[0][0]).toEqual({+ completed: true,+ cancelled: false,+ value: 'installed',+ reason: 'checking plugins',+ })+ }+ else {+ expect(settled.mock.calls[0][0]).toBe(failure)+ }+ expect(Date.now() - startedAt).toBe(10)+ await result+ })+it('allows plugin installation to exceed the old deadline while heartbeats continue', async () => {let clock = 0let sequence = 0@@ -222,6 +262,52 @@ describe('waitForActivityTask', () => {expect(clock).toBe(70)})+ it('keeps cancellation authoritative when a pending task rejects', async () => {+ let active = true+ const task = Promise.withResolvers<void>()+ const result = waitForActivityTask({+ task: task.promise,+ getActivity: () => ({ sequence: 0, reason: 'checking plugins' }),+ inactivityTimeoutMs: 30_000,+ absoluteTimeoutMs: 60_000,+ intervalMs: 1000,+ shouldContinue: () => active,+ wait: () => new Promise<void>(() => {}),+ })++ active = false+ task.reject(new Error('cancelled installation'))++ await expect(result).resolves.toEqual({+ completed: false,+ cancelled: true,+ reason: 'checking plugins',+ })+ })++ it('returns an inactivity timeout when a pending task has no heartbeat', async () => {+ let clock = 0+ const result = await waitForActivityTask({+ task: new Promise<never>(() => {}),+ getActivity: () => ({ sequence: 0, reason: 'checking plugins' }),+ inactivityTimeoutMs: 30,+ absoluteTimeoutMs: 100,+ intervalMs: 10,+ now: () => clock,+ wait: async (milliseconds) => {+ clock += milliseconds+ },+ })++ expect(result).toEqual({+ completed: false,+ cancelled: false,+ timeout: 'inactivity',+ reason: 'checking plugins',+ })+ expect(clock).toBe(30)+ })+it('caps a progressing plugin installation at its absolute deadline', async () => {let clock = 0let sequence = 0