DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor(service): split oversized modules into cohesive submodules (#210)
Mao Mr0eddaf471a58
diff --git a/src-tauri/resources/internal-plugins.json b/src-tauri/resources/internal-plugins.jsonindex 110ad3f8..a83f7408 100644--- a/src-tauri/resources/internal-plugins.json+++ b/src-tauri/resources/internal-plugins.json@@ -38,5 +38,13 @@"description": "Skills and MCP management in the DeepSeek Harness desktop extension panel.","repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-panel-extension","recommended": true+ },+ {+ "id": "dsh-tauri-session",+ "spec": "dsh-tauri-session",+ "name": "DSH Tauri Session",+ "description": "Session archive for the desktop: rewrites the workspace browser's 'delete workspace' action into 'archive workspace', and adds an 'Archived chats' settings page with search, sort, grouping, project filter and unarchive.",+ "repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-session",+ "recommended": true}]diff --git a/src-tauri/src/service/cli/path.rs b/src-tauri/src/service/cli/path.rsdeleted file mode 100644index 1e026cc4..00000000--- a/src-tauri/src/service/cli/path.rs+++ /dev/null@@ -1,1035 +0,0 @@-//! 用户 PATH 注册与路径计算:bin 目录定位、Windows 注册表读写与-//! `WM_SETTINGCHANGE` 广播、Unix shell rc 幂等块更新(备份 + 失败回滚),以及用户 pnpm 探测。--#[cfg(not(windows))]-use std::fs;-use std::path::{Path, PathBuf};-use tauri::{AppHandle, Manager};--#[cfg(windows)]-use super::shim::SHIM_CMD_NAME;-#[cfg(unix)]-use super::shim::SHIM_SH_NAME;--/// Windows 下 shim 根目录名(`%LOCALAPPDATA%\<此目录>\bin`)-const CLI_ROOT_DIR_NAME: &str = "deepseek-harness";--/// Unix 下 shim 所在目录(XDG 约定)-#[cfg(unix)]-const UNIX_BIN_DIR: &str = ".local/bin";--/// shell rc 注入标记(用于幂等增删;Windows 无 rc 逻辑,仅测试引用)-#[cfg_attr(windows, allow(dead_code))]-const RC_MARK_START: &str = "# >>> deepseek-harness dsh >>>";-#[cfg_attr(windows, allow(dead_code))]-const RC_MARK_END: &str = "# <<< deepseek-harness dsh <<<";--/// Unix 下需要写入 PATH 导出的 rc 文件(按顺序处理;同上,Windows 仅测试引用)-#[cfg_attr(windows, allow(dead_code))]-const RC_FILES: [&str; 2] = [".zshrc", ".bashrc"];--// ----------------------------------------------------------------------------// 路径计算-// -----------------------------------------------------------------------------/// bin 目录:-/// - Windows:`%LOCALAPPDATA%\deepseek-harness\bin`(用户级、不随应用数据目录变动)-/// - Unix:`~/.local/bin`(XDG 约定,通常已在 PATH 中)-pub fn get_bin_dir(app_handle: &AppHandle) -> 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()))- })- .unwrap_or_else(std::env::temp_dir)- .join(CLI_ROOT_DIR_NAME)- .join("bin")- }- #[cfg(not(windows))]- {- app_handle- .path()- .home_dir()- .unwrap_or_else(|_| PathBuf::from("."))- .join(UNIX_BIN_DIR)- }-}--/// 主 shim 文件路径(状态展示用)-pub fn get_shim_path(app_handle: &AppHandle) -> PathBuf {- let bin_dir = get_bin_dir(app_handle);- #[cfg(windows)]- {- bin_dir.join(SHIM_CMD_NAME)- }- #[cfg(not(windows))]- {- bin_dir.join(SHIM_SH_NAME)- }-}--/// 当前用户 PATH 中是否已包含 bin 目录(Windows 以注册表为准,-/// 因为进程内 PATH 在广播 WM_SETTINGCHANGE 后不会自动更新)-pub fn path_registered(app_handle: &AppHandle) -> bool {- #[cfg(windows)]- {- let bin_dir = get_bin_dir(app_handle);- let Some(bin_str) = bin_dir.to_str() else {- return false;- };- read_user_path()- .map(|value| path_contains_token(&value, bin_str))- .unwrap_or(false)- }- #[cfg(not(windows))]- {- let bin_dir = get_bin_dir(app_handle);- // 1. 当前进程 PATH 已包含(新终端直接可用)- if std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())- .any(|p| p == bin_dir)- {- return true;- }- // 2. rc 文件中已注入标记块(重启 shell 后可用)- let home = app_handle- .path()- .home_dir()- .unwrap_or_else(|_| PathBuf::from("."));- RC_FILES.iter().any(|name| {- fs::read_to_string(home.join(name))- .map(|content| content.contains(RC_MARK_START))- .unwrap_or(false)- })- }-}--/// 在继承 PATH 与平台标准目录中查找用户 pnpm(排除应用注册的 shim)。-///-/// "用户优先"策略:安装时(`Pnpm::check_installed`)用户已有 pnpm 则跳过-/// 捆绑安装;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)-}--/// 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);- find_windows_executable_pnpm_in_dirs(&get_bin_dir(app_handle), &dirs)-}--fn user_pnpm_dirs(_app_handle: &AppHandle) -> Vec<PathBuf> {- let mut dirs: Vec<PathBuf> =- std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()).collect();- #[cfg(windows)]- append_windows_pnpm_dirs(&mut dirs);- #[cfg(unix)]- {- 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(),- );- }- dirs-}--/// Unix 图形进程不会读取交互式 shell 配置;在继承 PATH 之后补充 mise 的-/// 官方数据目录,并保留先出现的字面路径,避免解析 `pnpm -> mise` 符号链接。-#[cfg_attr(windows, allow(dead_code))]-fn append_unix_mise_dirs(- dirs: &mut Vec<PathBuf>,- mise_data: Option<&Path>,- xdg_data: Option<&Path>,- home: Option<&Path>,-) {- let candidates = [- mise_data.map(|path| path.join("shims")),- xdg_data.map(|path| path.join("mise/shims")),- home.map(|path| path.join(".local/share/mise/shims")),- ];- for candidate in candidates.into_iter().flatten() {- let candidate_key = std::path::absolute(&candidate).unwrap_or_else(|_| candidate.clone());- let duplicate = dirs.iter().any(|existing| {- std::path::absolute(existing).unwrap_or_else(|_| existing.clone()) == candidate_key- });- if candidate.is_absolute() && !duplicate {- dirs.push(candidate);- }- }-}--/// 子进程环境中的 pnpm 必须是绝对路径。Unix 只做字面绝对化,不能解析 mise-/// 依赖 argv[0] 的 shim 符号链接;Windows 继续去除 `\\?\` 并解析连接点。-fn pnpm_env_path(path: &Path) -> PathBuf {- #[cfg(windows)]- {- dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())- }- #[cfg(not(windows))]- {- std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())- }-}--/// 生成传给 shim 的精确 `DSH_PNPM` 值,并拒绝桌面端自身的 pnpm shim。-pub fn pnpm_env_value(pnpm: &Path, bin_dir: &Path) -> Option<String> {- let pnpm = pnpm_env_path(pnpm);- let bin_dir = pnpm_env_path(bin_dir);- (pnpm.parent() != Some(bin_dir.as_path())).then(|| pnpm.to_string_lossy().into_owned())-}--/// 在给定目录中按顺序查找用户 pnpm,便于不依赖全局环境测试探测规则。-fn find_pnpm_in_dirs(bin_dir: &Path, dirs: &[PathBuf]) -> Option<PathBuf> {- let candidates: &[&str] = if cfg!(windows) {- &["pnpm.cmd", "pnpm.exe", "pnpm.bat"]- } else {- &["pnpm"]- };- find_pnpm_candidates_in_dirs(bin_dir, dirs, candidates)-}--#[cfg(windows)]-fn find_windows_executable_pnpm_in_dirs(bin_dir: &Path, dirs: &[PathBuf]) -> Option<PathBuf> {- find_pnpm_candidates_in_dirs(bin_dir, dirs, &["pnpm.exe"])-}--fn find_pnpm_candidates_in_dirs(- bin_dir: &Path,- dirs: &[PathBuf],- candidates: &[&str],-) -> Option<PathBuf> {- let bin_dir = pnpm_env_path(bin_dir);- for dir in dirs {- if dir.as_os_str().is_empty() {- continue;- }- let normalized = pnpm_env_path(dir);- if normalized == bin_dir {- continue;- }- for name in candidates {- let candidate = normalized.join(name);- if usable_pnpm_candidate(&candidate) {- return Some(candidate);- }- }- }- None-}--/// 只接受真实可执行文件,并拒绝复制或链接到其它目录的桌面端生成 shim。-fn usable_pnpm_candidate(candidate: &Path) -> bool {- if !candidate.is_file() || !pnpm_is_executable(candidate) {- return false;- }- let is_small_wrapper = candidate- .metadata()- .map(|metadata| metadata.len() <= 16 * 1024)- .unwrap_or(false);- !is_small_wrapper || !super::shim::is_generated_shim(candidate)-}--#[cfg(unix)]-fn pnpm_is_executable(path: &Path) -> bool {- use std::os::unix::fs::PermissionsExt;- path.metadata()- .map(|metadata| metadata.permissions().mode() & 0o111 != 0)- .unwrap_or(false)-}--#[cfg(not(unix))]-fn pnpm_is_executable(_path: &Path) -> bool {- true-}--/// Windows GUI 进程的 PATH 可能早于 npm/pnpm 安装,补充这些工具的标准用户目录。-#[cfg(windows)]-fn append_windows_pnpm_dirs(dirs: &mut Vec<PathBuf>) {- let mut append = |dir: PathBuf| {- if dir.is_absolute() && !dirs.iter().any(|existing| existing == &dir) {- dirs.push(dir);- }- };- if let Some(appdata) = std::env::var_os("APPDATA") {- append(PathBuf::from(appdata).join("npm"));- }- for variable in ["PNPM_HOME", "NPM_CONFIG_PREFIX", "npm_config_prefix"] {- if let Some(value) = std::env::var_os(variable) {- append(PathBuf::from(value));- }- }- if let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") {- append(PathBuf::from(local_app_data).join("pnpm"));- }-}--// ----------------------------------------------------------------------------// PATH 注册 / 注销(Windows:注册表 + WM_SETTINGCHANGE;Unix:shell rc)-// -----------------------------------------------------------------------------/// 注册 bin 目录到用户 PATH(幂等)-pub fn register_path(app_handle: &AppHandle) -> Result<(), String> {- if path_registered(app_handle) {- return Ok(());- }- #[cfg(windows)]- {- let bin_dir = get_bin_dir(app_handle);- let bin_str = bin_dir- .to_str()- .ok_or_else(|| "bin dir is not valid UTF-8".to_string())?;- let current = read_user_path().unwrap_or_default();- let new_value = if current.trim().is_empty() {- bin_str.to_string()- } else {- format!("{};{}", current.trim_end_matches(';'), bin_str)- };- write_user_path(&new_value)?;- notify_environment_change();- log::info!("Registered dsh bin dir in user PATH: {bin_str}");- }- #[cfg(not(windows))]- {- inject_shell_rc(app_handle)?;- }- Ok(())-}--/// 从用户 PATH 中移除 bin 目录(幂等)-pub fn unregister_path(app_handle: &AppHandle) -> Result<(), String> {- #[cfg(windows)]- {- let bin_dir = get_bin_dir(app_handle);- let Some(bin_str) = bin_dir.to_str() else {- return Ok(());- };- if let Some(current) = read_user_path() {- if !path_contains_token(¤t, bin_str) {- return Ok(());- }- let new_value = remove_path_token(¤t, bin_str);- write_user_path(&new_value)?;- notify_environment_change();- log::info!("Removed dsh bin dir from user PATH");- }- }- #[cfg(not(windows))]- {- strip_shell_rc(app_handle)?;- }- Ok(())-}--// ----------------------------------------------------------------------------// Windows 注册表辅助-// -----------------------------------------------------------------------------#[cfg(windows)]-#[inline]-fn to_wide_null(s: &str) -> Vec<u16> {- s.encode_utf16().chain(std::iter::once(0)).collect()-}--#[cfg(windows)]-fn read_user_path() -> Option<String> {- use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_MORE_DATA};- use windows_sys::Win32::System::Registry::{- RegCloseKey, RegOpenKeyExW, RegQueryValueExW, HKEY, HKEY_CURRENT_USER, KEY_QUERY_VALUE,- };-- unsafe {- let mut hkey: HKEY = std::ptr::null_mut();- let key_name = to_wide_null("Environment");- let ret = RegOpenKeyExW(- HKEY_CURRENT_USER,- key_name.as_ptr(),- 0,- KEY_QUERY_VALUE,- &mut hkey,- );- if ret != 0 {- log::warn!("failed to open HKCU\\Environment (error {ret})");- return None;- }-- let value_name = to_wide_null("Path");- let mut value_type: u32 = 0;- let mut size: u32 = 0;- let mut ret = RegQueryValueExW(- hkey,- value_name.as_ptr(),- std::ptr::null(),- &mut value_type,- std::ptr::null_mut(),- &mut size,- );-- if ret == ERROR_FILE_NOT_FOUND {- RegCloseKey(hkey);- return Some(String::new());- }- if ret != ERROR_MORE_DATA && ret != 0 {- RegCloseKey(hkey);- log::warn!("failed to query HKCU\\Environment\\Path (error {ret})");- return None;- }-- let mut buf = vec![0u16; (size as usize / 2).max(1) + 1];- ret = RegQueryValueExW(- hkey,- value_name.as_ptr(),- std::ptr::null(),- &mut value_type,- buf.as_mut_ptr() as *mut u8,- &mut size,- );- RegCloseKey(hkey);-- if ret != 0 {- log::warn!("failed to read HKCU\\Environment\\Path (error {ret})");- return None;- }- let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());- Some(String::from_utf16_lossy(&buf[..end]))- }-}--#[cfg(windows)]-fn write_user_path(new_value: &str) -> Result<(), String> {- use windows_sys::Win32::System::Registry::{- RegCloseKey, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW, HKEY, HKEY_CURRENT_USER,- KEY_QUERY_VALUE, KEY_SET_VALUE, REG_EXPAND_SZ, REG_SZ,- };-- unsafe {- let mut hkey: HKEY = std::ptr::null_mut();- let key_name = to_wide_null("Environment");- let ret = RegOpenKeyExW(- HKEY_CURRENT_USER,- key_name.as_ptr(),- 0,- KEY_QUERY_VALUE | KEY_SET_VALUE,- &mut hkey,- );- if ret != 0 {- return Err(format!("failed to open HKCU\\Environment (error {ret})"));- }-- let value_name = to_wide_null("Path");- let mut value_type: u32 = REG_EXPAND_SZ;- let mut size: u32 = 0;- RegQueryValueExW(- hkey,- value_name.as_ptr(),- std::ptr::null(),- &mut value_type,- std::ptr::null_mut(),- &mut size,- );- if value_type != REG_SZ && value_type != REG_EXPAND_SZ {- value_type = REG_EXPAND_SZ;- }-- let wide_value = to_wide_null(new_value);- let bytes = (wide_value.len() * 2) as u32;- let ret = RegSetValueExW(- hkey,- value_name.as_ptr(),- 0,- value_type,- wide_value.as_ptr() as *const u8,- bytes,- );- RegCloseKey(hkey);-- if ret != 0 {- return Err(format!(- "failed to write HKCU\\Environment\\Path (error {ret})"- ));- }- Ok(())- }-}--#[cfg(windows)]-fn notify_environment_change() {- use windows_sys::Win32::Foundation::{LPARAM, WPARAM};- use windows_sys::Win32::UI::WindowsAndMessaging::{- SendMessageTimeoutW, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE,- };- let wide = to_wide_null("Environment");- unsafe {- SendMessageTimeoutW(- HWND_BROADCAST,- WM_SETTINGCHANGE,- 0 as WPARAM,- wide.as_ptr() as LPARAM,- SMTO_ABORTIFHUNG,- 5000,- std::ptr::null_mut(),- );- }-}--/// 展开字符串中的 `%VAR%`(Windows)-#[cfg(windows)]-fn expand_env(value: &str) -> String {- use windows_sys::Win32::System::Environment::ExpandEnvironmentStringsW;- let wide = to_wide_null(value);- let mut buf = vec![0u16; 32768];- let n = unsafe { ExpandEnvironmentStringsW(wide.as_ptr(), buf.as_mut_ptr(), buf.len() as u32) };- if n == 0 || n > buf.len() as u32 {- return value.to_string();- }- let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());- String::from_utf16_lossy(&buf[..end])-}--/// PATH 值(`;` 分隔)中是否已包含指定目录(大小写不敏感,先展开 %VAR%)-#[cfg(windows)]-fn path_contains_token(path_value: &str, token: &str) -> bool {- let expanded = expand_env(path_value);- let token_lower = token.to_lowercase();- expanded- .split(';')- .any(|p| !p.is_empty() && p.trim_end_matches('\\').to_lowercase() == token_lower)-}--/// 从 PATH 值中移除指定目录 token(同时处理 `%LOCALAPPDATA%` 未展开形式)-#[cfg(windows)]-fn remove_path_token(path_value: &str, token: &str) -> String {- let token_lower = token.to_lowercase();- let unexpanded_lower = token_lower.replace(- &std::env::var("LOCALAPPDATA")- .unwrap_or_default()- .to_lowercase(),- "%localappdata%",- );- let kept: Vec<&str> = path_value- .split(';')- .filter(|p| {- if p.is_empty() {- return false;- }- let norm = p.trim_end_matches('\\').to_lowercase();- norm != token_lower && norm != unexpanded_lower- })- .collect();- kept.join(";")-}--// ----------------------------------------------------------------------------// Unix shell rc 辅助-// -----------------------------------------------------------------------------/// Unix:向 `~/.zshrc` / `~/.bashrc` 幂等注入 `~/.local/bin` 的 PATH 导出。-///-/// 只更新自身标记块:读取原文件 → 移除旧块 → 末尾追加新块;仅当文件不存在时-/// 才新建。读失败(非"不存在")直接报错退出,绝不把"读不到"当作空文件去-/// 全量覆盖用户配置;写入前先备份,写失败自动回滚(见 `write_rc_with_backup`)。-#[cfg(not(windows))]-fn inject_shell_rc(app_handle: &AppHandle) -> Result<(), String> {- let home = app_handle- .path()- .home_dir()- .map_err(|_| "failed to resolve home directory".to_string())?;- let block = format!("{RC_MARK_START}\nexport PATH=\"$HOME/.local/bin:$PATH\"\n{RC_MARK_END}\n");-- for name in RC_FILES {- let rc_path = home.join(name);- let original = match fs::read_to_string(&rc_path) {- Ok(content) => content,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),- Err(e) => {- return Err(format!(- "READ_RC_FAILED: read {} failed: {e}",- rc_path.display()- ))- }- };- let next = upsert_rc_block(&original, &block);- if next == original {- continue;- }- write_rc_with_backup(&rc_path, &next)?;- log::info!("Injected PATH export into {}", rc_path.display());- }- Ok(())-}--/// Unix:从 rc 文件中移除注入块(保留用户其余配置,同样走备份 + 回滚写入)-#[cfg(not(windows))]-fn strip_shell_rc(app_handle: &AppHandle) -> Result<(), String> {- let home = app_handle- .path()- .home_dir()- .map_err(|_| "failed to resolve home directory".to_string())?;- for name in RC_FILES {- let rc_path = home.join(name);- let original = match fs::read_to_string(&rc_path) {- Ok(content) => content,- // 文件不存在则无需清理- Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,- Err(e) => {- return Err(format!(- "READ_RC_FAILED: read {} failed: {e}",- rc_path.display()- ))- }- };- let cleaned = strip_rc_block(&original);- if cleaned != original {- write_rc_with_backup(&rc_path, &cleaned)?;- log::info!("Removed PATH export from {}", rc_path.display());- }- }- Ok(())-}--/// 将 PATH 导出块并入 rc 内容:先移除已有标记块,再在文件末尾追加新块,-/// 只更新自身块、保留用户其余配置,且块始终落在文件末尾。-#[cfg_attr(windows, allow(dead_code))]-fn upsert_rc_block(content: &str, block: &str) -> String {- let mut out = strip_rc_block(content);- if !out.is_empty() && !out.ends_with('\n') {- out.push('\n');- }- out.push_str(block);- if !out.ends_with('\n') {- out.push('\n');- }- out-}--/// 原子写回 rc 文件:写入前先备份为 `<file>.dsh-backup`,再通过同目录-/// 临时文件 + rename 原子替换;写失败时删除临时文件并回滚备份内容,-/// 保证任何异常路径下用户原文件都不会被半写/被清空。-#[cfg_attr(windows, allow(dead_code))]-fn write_rc_with_backup(rc_path: &std::path::Path, new_content: &str) -> Result<(), String> {- use std::fs;-- let backup_path = rc_path.with_extension("dsh-backup");- let had_original = rc_path.exists();- if had_original {- fs::copy(rc_path, &backup_path).map_err(|e| {- format!(- "BACKUP_RC_FAILED: backup {} to {} failed: {e}",- rc_path.display(),- backup_path.display()- )- })?;- }-- let tmp_path = rc_path.with_extension("dsh-rc-tmp");- fs::write(&tmp_path, new_content)- .map_err(|e| format!("WRITE_RC_FAILED: write {} failed: {e}", tmp_path.display()))?;- let rename_res = match fs::rename(&tmp_path, rc_path) {- Ok(()) => Ok(()),- // Windows 下 rename 不覆盖已存在目标(仅测试环境会走到):删旧文件后重试- Err(_) => {- let _ = fs::remove_file(rc_path);- fs::rename(&tmp_path, rc_path)- }- };- if let Err(e) = rename_res {- let _ = fs::remove_file(&tmp_path);- if had_original {- let _ = fs::copy(&backup_path, rc_path);- }- return Err(format!(- "RENAME_RC_FAILED: rename into {} failed: {e}",- rc_path.display()- ));- }- Ok(())-}--/// 移除 rc 文件中的标记块(含标记行本身)。-/// 同时被注入(`upsert_rc_block`)与移除路径使用;Windows 仅测试引用。-#[cfg_attr(windows, allow(dead_code))]-fn strip_rc_block(content: &str) -> String {- let mut lines = content.lines().peekable();- let mut out = String::with_capacity(content.len());- let mut skipping = false;- while let Some(line) = lines.next() {- if line.trim() == RC_MARK_START {- skipping = true;- continue;- }- if skipping {- if line.trim() == RC_MARK_END {- skipping = false;- }- continue;- }- out.push_str(line);- out.push('\n');- }- out-}--#[cfg(test)]-mod tests {- use super::*;-- const RC_BLOCK: &str =- "# >>> deepseek-harness dsh >>>\nexport PATH=\"$HOME/.local/bin:$PATH\"\n# <<< deepseek-harness dsh <<<\n";-- /// 独立的临时目录,避免测试间互相干扰- #[test]- fn find_pnpm_prefers_path_order_and_skips_shim_dir() {- let root = temp_dir("pnpm-discovery");- let shim_dir = root.join("shim");- let first = root.join("first");- let second = root.join("second");- std::fs::create_dir_all(&shim_dir).unwrap();- std::fs::create_dir_all(&first).unwrap();- std::fs::create_dir_all(&second).unwrap();- let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };- std::fs::write(shim_dir.join(name), "shim").unwrap();- std::fs::write(first.join(name), "first").unwrap();- std::fs::write(second.join(name), "second").unwrap();- make_executable(&shim_dir.join(name));- make_executable(&first.join(name));- make_executable(&second.join(name));- let found = find_pnpm_in_dirs(&shim_dir, &[shim_dir.clone(), first.clone(), second]);- assert_eq!(found, Some(pnpm_env_path(&first.join(name))));- let _ = std::fs::remove_dir_all(root);- }-- #[cfg(windows)]- #[test]- fn direct_discovery_uses_exe_when_cmd_and_exe_share_a_directory() {- let root = temp_dir("pnpm-direct-exe");- let desktop_bin = root.join("desktop-bin");- let user_bin = root.join("user-bin");- std::fs::create_dir_all(&desktop_bin).unwrap();- std::fs::create_dir_all(&user_bin).unwrap();- let cmd = user_bin.join("pnpm.cmd");- let exe = user_bin.join("pnpm.exe");- std::fs::write(&cmd, "cmd").unwrap();- std::fs::write(&exe, "exe").unwrap();-- assert_eq!(- find_pnpm_in_dirs(&desktop_bin, std::slice::from_ref(&user_bin)),- Some(pnpm_env_path(&cmd))- );- assert_eq!(- find_windows_executable_pnpm_in_dirs(&desktop_bin, std::slice::from_ref(&user_bin)),- Some(pnpm_env_path(&exe))- );- let _ = std::fs::remove_dir_all(root);- }-- #[test]- fn mise_dirs_follow_path_and_dedupe_in_source_order() {- let root = temp_dir("pnpm-mise-dirs");- let inherited = root.join("inherited");- let mise = root.join("mise-data");- let xdg = root.join("xdg-data");- let home = root.join("home");- let mut dirs = vec![inherited.clone(), xdg.join("mise/shims")];-- append_unix_mise_dirs(&mut dirs, Some(&mise), Some(&xdg), Some(&home));-- assert_eq!(- dirs,- vec![- inherited,- xdg.join("mise/shims"),- mise.join("shims"),- home.join(".local/share/mise/shims"),- ]- );- let mut fresh = vec![root.join("fresh-path")];- append_unix_mise_dirs(&mut fresh, Some(&mise), Some(&xdg), Some(&home));- assert_eq!(- fresh,- vec![- root.join("fresh-path"),- mise.join("shims"),- xdg.join("mise/shims"),- home.join(".local/share/mise/shims"),- ]- );- let _ = std::fs::remove_dir_all(root);- }-- #[test]- fn inherited_path_pnpm_precedes_appended_mise_pnpm() {- let root = temp_dir("pnpm-mise-precedence");- let desktop_bin = root.join("desktop-bin");- let inherited = root.join("inherited");- let mise_data = root.join("mise");- let mise_shims = mise_data.join("shims");- for dir in [&desktop_bin, &inherited, &mise_shims] {- std::fs::create_dir_all(dir).unwrap();- }- let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };- let inherited_pnpm = inherited.join(name);- let mise_pnpm = mise_shims.join(name);- std::fs::write(&inherited_pnpm, "inherited").unwrap();- std::fs::write(&mise_pnpm, "mise").unwrap();- make_executable(&inherited_pnpm);- make_executable(&mise_pnpm);- let mut dirs = vec![inherited];- append_unix_mise_dirs(&mut dirs, Some(&mise_data), None, None);-- assert_eq!(- find_pnpm_in_dirs(&desktop_bin, &dirs),- Some(pnpm_env_path(&inherited_pnpm))- );- let _ = std::fs::remove_dir_all(root);- }-- #[test]- fn default_home_mise_pnpm_is_discovered_when_path_misses() {- let root = temp_dir("pnpm-mise-home-default");- let desktop_bin = root.join("desktop-bin");- let inherited = root.join("inherited");- let home = root.join("home");- let home_shims = home.join(".local/share/mise/shims");- for dir in [&desktop_bin, &inherited, &home_shims] {- std::fs::create_dir_all(dir).unwrap();- }- let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };- let pnpm = home_shims.join(name);- std::fs::write(&pnpm, "mise home").unwrap();- make_executable(&pnpm);- let mut dirs = vec![inherited];- append_unix_mise_dirs(&mut dirs, None, None, Some(&home));-- assert_eq!(- find_pnpm_in_dirs(&desktop_bin, &dirs),- Some(pnpm_env_path(&pnpm))- );- let _ = std::fs::remove_dir_all(root);- }-- #[test]- fn discovery_misses_desktop_generated_shim_and_absent_candidates() {- let root = temp_dir("pnpm-own-shim-only");- let desktop_bin = root.join("desktop-bin");- let copied_bin = root.join("copied-bin");- let empty = root.join("empty");- std::fs::create_dir_all(&desktop_bin).unwrap();- std::fs::create_dir_all(&copied_bin).unwrap();- std::fs::create_dir_all(&empty).unwrap();- let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };- let own = desktop_bin.join(name);- let copied = copied_bin.join(name);- for path in [&own, &copied] {- std::fs::write(- path,- "# DeepSeek Harness Desktop - pnpm command shim (generated)\n",- )- .unwrap();- make_executable(path);- }-- assert_eq!(- find_pnpm_in_dirs(&desktop_bin, &[desktop_bin.clone(), copied_bin, empty]),- None- );- let _ = std::fs::remove_dir_all(root);- }-- #[test]- fn pnpm_env_value_injects_exact_external_path_and_rejects_own_dir() {- let root = temp_dir("pnpm-env-value");- let desktop_bin = root.join("desktop-bin");- let external_bin = root.join("external-bin");- std::fs::create_dir_all(&desktop_bin).unwrap();- std::fs::create_dir_all(&external_bin).unwrap();- let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };- let own = desktop_bin.join(name);- let external = external_bin.join(name);- std::fs::write(&own, "own").unwrap();- std::fs::write(&external, "external").unwrap();-- assert_eq!(pnpm_env_value(&own, &desktop_bin), None);- assert_eq!(- pnpm_env_value(&external, &desktop_bin),- Some(pnpm_env_path(&external).to_string_lossy().into_owned())- );- let _ = std::fs::remove_dir_all(root);- }-- #[cfg(unix)]- #[test]- fn discovery_rejects_non_executable_pnpm() {- let root = temp_dir("pnpm-nonexec");- let desktop_bin = root.join("desktop-bin");- let mise_shims = root.join("mise/shims");- std::fs::create_dir_all(&desktop_bin).unwrap();- std::fs::create_dir_all(&mise_shims).unwrap();- std::fs::write(mise_shims.join("pnpm"), "not executable").unwrap();-- assert_eq!(- find_pnpm_in_dirs(&desktop_bin, std::slice::from_ref(&mise_shims)),- None- );- let _ = std::fs::remove_dir_all(root);- }-- #[cfg(unix)]- #[test]- fn discovery_preserves_argv0_style_mise_symlink() {- use std::os::unix::fs::{symlink, PermissionsExt};-- let root = temp_dir("pnpm-mise-symlink");- let desktop_bin = root.join("desktop-bin");- let mise_bin = root.join("mise/bin");- let mise_shims = root.join("mise/shims");- for dir in [&desktop_bin, &mise_bin, &mise_shims] {- std::fs::create_dir_all(dir).unwrap();- }- let target = mise_bin.join("mise");- std::fs::write(- &target,- "#!/bin/sh\n[ \"$(basename \"$0\")\" = pnpm ] || exit 51\nprintf 'argv0-ok\\n'\n",- )- .unwrap();- let mut permissions = std::fs::metadata(&target).unwrap().permissions();- permissions.set_mode(0o700);- std::fs::set_permissions(&target, permissions).unwrap();- let pnpm = mise_shims.join("pnpm");- symlink(&target, &pnpm).unwrap();-- let found = find_pnpm_in_dirs(&desktop_bin, std::slice::from_ref(&mise_shims)).unwrap();- assert_eq!(found, pnpm);- assert_eq!(- pnpm_env_value(&found, &desktop_bin),- Some(found.to_string_lossy().into_owned())- );- let output = std::process::Command::new(&found).output().unwrap();- assert!(output.status.success());- assert_eq!(String::from_utf8_lossy(&output.stdout), "argv0-ok\n");- let _ = std::fs::remove_dir_all(root);- }-- fn make_executable(path: &Path) {- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let mut permissions = std::fs::metadata(path).unwrap().permissions();- permissions.set_mode(0o700);- std::fs::set_permissions(path, permissions).unwrap();- }- #[cfg(not(unix))]- let _ = path;- }-- fn temp_dir(tag: &str) -> std::path::PathBuf {- let dir = std::env::temp_dir().join(format!(- "dsh-rc-{tag}-{}-{}",- std::process::id(),- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_nanos())- .unwrap_or(0)- ));- let _ = std::fs::remove_dir_all(&dir);- std::fs::create_dir_all(&dir).unwrap();- dir- }-- /// issue #57:目标 rc 文件已存在且包含用户自定义内容 → 只追加块,原内容保留- #[test]- fn upsert_keeps_user_content_and_appends_block() {- let content = "# oh-my-zsh\nplugins=(git)\nalias ll='ls -alF'\n";- let next = upsert_rc_block(content, RC_BLOCK);- assert!(next.starts_with(content));- assert!(next.ends_with(RC_BLOCK));- assert_eq!(next.matches(RC_MARK_START).count(), 1);- }-- /// issue #57:旧块位于文件中间时 → 移除并移动到末尾,周围用户内容保留- #[test]- fn upsert_moves_stale_block_to_end() {- let stale = format!("alias ll='ls -alF'\n{RC_BLOCK}export NVM_DIR=\"$HOME/.nvm\"\n");- let next = upsert_rc_block(&stale, RC_BLOCK);- let stripped = strip_rc_block(&next);- assert_eq!(- stripped,- "alias ll='ls -alF'\nexport NVM_DIR=\"$HOME/.nvm\"\n"- );- assert!(next.ends_with(RC_BLOCK));- assert_eq!(next.matches(RC_MARK_START).count(), 1);- }-- /// 幂等:重复注入不产生第二块- #[test]- fn upsert_is_idempotent() {- let content = "user content\n";- let once = upsert_rc_block(content, RC_BLOCK);- assert_eq!(upsert_rc_block(&once, RC_BLOCK), once);- }-- /// 空内容(文件不存在时的新建场景)→ 仅注入块,没有多余空行- #[test]- fn upsert_from_missing_file_creates_block_only() {- assert_eq!(upsert_rc_block("", RC_BLOCK), RC_BLOCK.to_string());- }-- /// 无末尾换行的内容 → 补换行后再追加块- #[test]- fn upsert_handles_missing_trailing_newline() {- let next = upsert_rc_block("no trailing nl", RC_BLOCK);- assert_eq!(next, "no trailing nl\n".to_string() + RC_BLOCK);- }-- /// strip 原语:移除标记块且幂等- #[test]- fn strip_rc_block_removes_block_and_is_idempotent() {- let content = format!("keep\n{RC_BLOCK}tail\n");- let cleaned = strip_rc_block(&content);- assert_eq!(cleaned, "keep\ntail\n");- assert_eq!(strip_rc_block(&cleaned), cleaned);- }-- /// 写回:备份保留原内容、目标被替换为 new_content- #[test]- fn write_rc_with_backup_preserves_backup() {- let dir = temp_dir("backup");- let rc_path = dir.join(".zshrc");- std::fs::write(&rc_path, "original\n").unwrap();-- write_rc_with_backup(&rc_path, "original\n# block\n").unwrap();-- assert_eq!(- std::fs::read_to_string(&rc_path).unwrap(),- "original\n# block\n"- );- assert_eq!(- std::fs::read_to_string(rc_path.with_extension("dsh-backup")).unwrap(),- "original\n"- );- let _ = std::fs::remove_dir_all(&dir);- }-- /// 写回:文件原本不存在 → 新建成功且不产生备份- #[test]- fn write_rc_with_backup_creates_missing_file() {- let dir = temp_dir("create");- let rc_path = dir.join(".bashrc");- write_rc_with_backup(&rc_path, "# block\n").unwrap();- assert_eq!(std::fs::read_to_string(&rc_path).unwrap(), "# block\n");- assert!(!rc_path.with_extension("dsh-backup").exists());- let _ = std::fs::remove_dir_all(&dir);- }-}diff --git a/src-tauri/src/service/cli/path/mod.rs b/src-tauri/src/service/cli/path/mod.rsnew file mode 100644index 00000000..22c509cb--- /dev/null+++ b/src-tauri/src/service/cli/path/mod.rs@@ -0,0 +1,211 @@+//! 用户 PATH 注册与路径计算:bin 目录定位、Windows 注册表读写与+//! `WM_SETTINGCHANGE` 广播、Unix shell rc 幂等块更新(备份 + 失败回滚),以及+//! 用户 pnpm 探测。+//!+//! 模块划分:+//! - [`pnpm`]:用户 pnpm 探测(PATH + mise/Windows 标准目录,排除本应用 shim)+//! - [`registry`]:Windows 注册表辅助(仅 Windows)+//! - [`rc`]:Unix shell rc 幂等块注入/移除(仅 Unix)++#[cfg(not(windows))]+use std::fs;+use std::path::PathBuf;+use tauri::{AppHandle, Manager};++#[cfg(windows)]+use super::shim::SHIM_CMD_NAME;+#[cfg(unix)]+use super::shim::SHIM_SH_NAME;++#[cfg(not(windows))]+use rc::{inject_shell_rc, strip_shell_rc, RC_FILES, RC_MARK_START};+#[cfg(windows)]+use registry::{+ notify_environment_change, path_contains_token, read_user_path, remove_path_token,+ write_user_path,+};++mod pnpm;+mod rc;+#[cfg(windows)]+mod registry;++#[cfg(windows)]+pub(crate) use pnpm::find_user_pnpm_executable;+pub use pnpm::{find_user_pnpm, pnpm_env_value};++/// Windows 下 shim 根目录名(`%LOCALAPPDATA%\<此目录>\bin`)+const CLI_ROOT_DIR_NAME: &str = "deepseek-harness";++/// Unix 下 shim 所在目录(XDG 约定)+#[cfg(unix)]+const UNIX_BIN_DIR: &str = ".local/bin";++// ---------------------------------------------------------------------------+// 路径计算+// ---------------------------------------------------------------------------++/// bin 目录:+/// - Windows:`%LOCALAPPDATA%\deepseek-harness\bin`(用户级、不随应用数据目录变动)+/// - Unix:`~/.local/bin`(XDG 约定,通常已在 PATH 中)+pub fn get_bin_dir(app_handle: &AppHandle) -> 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()))+ })+ .unwrap_or_else(std::env::temp_dir)+ .join(CLI_ROOT_DIR_NAME)+ .join("bin")+ }+ #[cfg(not(windows))]+ {+ app_handle+ .path()+ .home_dir()+ .unwrap_or_else(|_| PathBuf::from("."))+ .join(UNIX_BIN_DIR)+ }+}++/// 主 shim 文件路径(状态展示用)+pub fn get_shim_path(app_handle: &AppHandle) -> PathBuf {+ let bin_dir = get_bin_dir(app_handle);+ #[cfg(windows)]+ {+ bin_dir.join(SHIM_CMD_NAME)+ }+ #[cfg(not(windows))]+ {+ bin_dir.join(SHIM_SH_NAME)+ }+}++/// 当前用户 PATH 中是否已包含 bin 目录(Windows 以注册表为准,+/// 因为进程内 PATH 在广播 WM_SETTINGCHANGE 后不会自动更新)+pub fn path_registered(app_handle: &AppHandle) -> bool {+ #[cfg(windows)]+ {+ let bin_dir = get_bin_dir(app_handle);+ let Some(bin_str) = bin_dir.to_str() else {+ return false;+ };+ read_user_path()+ .map(|value| path_contains_token(&value, bin_str))+ .unwrap_or(false)+ }+ #[cfg(not(windows))]+ {+ let bin_dir = get_bin_dir(app_handle);+ // 1. 当前进程 PATH 已包含(新终端直接可用)+ if std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())+ .any(|p| p == bin_dir)+ {+ return true;+ }+ // 2. rc 文件中已注入标记块(重启 shell 后可用)+ let home = app_handle+ .path()+ .home_dir()+ .unwrap_or_else(|_| PathBuf::from("."));+ RC_FILES.iter().any(|name| {+ fs::read_to_string(home.join(name))+ .map(|content| content.contains(RC_MARK_START))+ .unwrap_or(false)+ })+ }+}++// ---------------------------------------------------------------------------+// PATH 注册 / 注销(Windows:注册表 + WM_SETTINGCHANGE;Unix:shell rc)+// ---------------------------------------------------------------------------++/// 注册 bin 目录到用户 PATH(幂等)+pub fn register_path(app_handle: &AppHandle) -> Result<(), String> {+ if path_registered(app_handle) {+ return Ok(());+ }+ #[cfg(windows)]+ {+ let bin_dir = get_bin_dir(app_handle);+ let bin_str = bin_dir+ .to_str()+ .ok_or_else(|| "bin dir is not valid UTF-8".to_string())?;+ let current = read_user_path().unwrap_or_default();+ let new_value = if current.trim().is_empty() {+ bin_str.to_string()+ } else {+ format!("{};{}", current.trim_end_matches(';'), bin_str)+ };+ write_user_path(&new_value)?;+ notify_environment_change();+ log::info!("Registered dsh bin dir in user PATH: {bin_str}");+ }+ #[cfg(not(windows))]+ {+ inject_shell_rc(app_handle)?;+ }+ Ok(())+}++/// 从用户 PATH 中移除 bin 目录(幂等)+pub fn unregister_path(app_handle: &AppHandle) -> Result<(), String> {+ #[cfg(windows)]+ {+ let bin_dir = get_bin_dir(app_handle);+ let Some(bin_str) = bin_dir.to_str() else {+ return Ok(());+ };+ if let Some(current) = read_user_path() {+ if !path_contains_token(¤t, bin_str) {+ return Ok(());+ }+ let new_value = remove_path_token(¤t, bin_str);+ write_user_path(&new_value)?;+ notify_environment_change();+ log::info!("Removed dsh bin dir from user PATH");+ }+ }+ #[cfg(not(windows))]+ {+ strip_shell_rc(app_handle)?;+ }+ Ok(())+}++#[cfg(test)]+mod test_util {+ use std::path::Path;++ pub(super) fn make_executable(path: &Path) {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mut permissions = std::fs::metadata(path).unwrap().permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(path, permissions).unwrap();+ }+ #[cfg(not(unix))]+ let _ = path;+ }++ pub(super) fn temp_dir(tag: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "dsh-rc-{tag}-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }+}diff --git a/src-tauri/src/service/cli/path/pnpm.rs b/src-tauri/src/service/cli/path/pnpm.rsnew file mode 100644index 00000000..b2238f38--- /dev/null+++ b/src-tauri/src/service/cli/path/pnpm.rs@@ -0,0 +1,416 @@+//! 用户 pnpm 探测:在继承 PATH 与平台标准目录中查找用户 pnpm(排除应用注册的+//! shim),并生成传给 shim 的精确 `DSH_PNPM` 值。++use std::path::{Path, PathBuf};+use tauri::AppHandle;+#[cfg(unix)]+use tauri::Manager;++use super::super::shim::is_generated_shim;+use super::get_bin_dir;++/// 在继承 PATH 与平台标准目录中查找用户 pnpm(排除应用注册的 shim)。+///+/// "用户优先"策略:安装时(`Pnpm::check_installed`)用户已有 pnpm 则跳过+/// 捆绑安装;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)+}++/// 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);+ find_windows_executable_pnpm_in_dirs(&get_bin_dir(app_handle), &dirs)+}++fn user_pnpm_dirs(_app_handle: &AppHandle) -> Vec<PathBuf> {+ let mut dirs: Vec<PathBuf> =+ std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()).collect();+ #[cfg(windows)]+ append_windows_pnpm_dirs(&mut dirs);+ #[cfg(unix)]+ {+ 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(),+ );+ }+ dirs+}++/// Unix 图形进程不会读取交互式 shell 配置;在继承 PATH 之后补充 mise 的+/// 官方数据目录,并保留先出现的字面路径,避免解析 `pnpm -> mise` 符号链接。+#[cfg_attr(windows, allow(dead_code))]+fn append_unix_mise_dirs(+ dirs: &mut Vec<PathBuf>,+ mise_data: Option<&Path>,+ xdg_data: Option<&Path>,+ home: Option<&Path>,+) {+ let candidates = [+ mise_data.map(|path| path.join("shims")),+ xdg_data.map(|path| path.join("mise/shims")),+ home.map(|path| path.join(".local/share/mise/shims")),+ ];+ for candidate in candidates.into_iter().flatten() {+ let candidate_key = std::path::absolute(&candidate).unwrap_or_else(|_| candidate.clone());+ let duplicate = dirs.iter().any(|existing| {+ std::path::absolute(existing).unwrap_or_else(|_| existing.clone()) == candidate_key+ });+ if candidate.is_absolute() && !duplicate {+ dirs.push(candidate);+ }+ }+}++/// 子进程环境中的 pnpm 必须是绝对路径。Unix 只做字面绝对化,不能解析 mise+/// 依赖 argv[0] 的 shim 符号链接;Windows 继续去除 `\\?\` 并解析连接点。+fn pnpm_env_path(path: &Path) -> PathBuf {+ #[cfg(windows)]+ {+ dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())+ }+ #[cfg(not(windows))]+ {+ std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())+ }+}++/// 生成传给 shim 的精确 `DSH_PNPM` 值,并拒绝桌面端自身的 pnpm shim。+pub fn pnpm_env_value(pnpm: &Path, bin_dir: &Path) -> Option<String> {+ let pnpm = pnpm_env_path(pnpm);+ let bin_dir = pnpm_env_path(bin_dir);+ (pnpm.parent() != Some(bin_dir.as_path())).then(|| pnpm.to_string_lossy().into_owned())+}++/// 在给定目录中按顺序查找用户 pnpm,便于不依赖全局环境测试探测规则。+fn find_pnpm_in_dirs(bin_dir: &Path, dirs: &[PathBuf]) -> Option<PathBuf> {+ let candidates: &[&str] = if cfg!(windows) {+ &["pnpm.cmd", "pnpm.exe", "pnpm.bat"]+ } else {+ &["pnpm"]+ };+ find_pnpm_candidates_in_dirs(bin_dir, dirs, candidates)+}++#[cfg(windows)]+fn find_windows_executable_pnpm_in_dirs(bin_dir: &Path, dirs: &[PathBuf]) -> Option<PathBuf> {+ find_pnpm_candidates_in_dirs(bin_dir, dirs, &["pnpm.exe"])+}++fn find_pnpm_candidates_in_dirs(+ bin_dir: &Path,+ dirs: &[PathBuf],+ candidates: &[&str],+) -> Option<PathBuf> {+ let bin_dir = pnpm_env_path(bin_dir);+ for dir in dirs {+ if dir.as_os_str().is_empty() {+ continue;+ }+ let normalized = pnpm_env_path(dir);+ if normalized == bin_dir {+ continue;+ }+ for name in candidates {+ let candidate = normalized.join(name);+ if usable_pnpm_candidate(&candidate) {+ return Some(candidate);+ }+ }+ }+ None+}++/// 只接受真实可执行文件,并拒绝复制或链接到其它目录的桌面端生成 shim。+fn usable_pnpm_candidate(candidate: &Path) -> bool {+ if !candidate.is_file() || !pnpm_is_executable(candidate) {+ return false;+ }+ let is_small_wrapper = candidate+ .metadata()+ .map(|metadata| metadata.len() <= 16 * 1024)+ .unwrap_or(false);+ !is_small_wrapper || !is_generated_shim(candidate)+}++#[cfg(unix)]+fn pnpm_is_executable(path: &Path) -> bool {+ use std::os::unix::fs::PermissionsExt;+ path.metadata()+ .map(|metadata| metadata.permissions().mode() & 0o111 != 0)+ .unwrap_or(false)+}++#[cfg(not(unix))]+fn pnpm_is_executable(_path: &Path) -> bool {+ true+}++/// Windows GUI 进程的 PATH 可能早于 npm/pnpm 安装,补充这些工具的标准用户目录。+#[cfg(windows)]+fn append_windows_pnpm_dirs(dirs: &mut Vec<PathBuf>) {+ let mut append = |dir: PathBuf| {+ if dir.is_absolute() && !dirs.iter().any(|existing| existing == &dir) {+ dirs.push(dir);+ }+ };+ if let Some(appdata) = std::env::var_os("APPDATA") {+ append(PathBuf::from(appdata).join("npm"));+ }+ for variable in ["PNPM_HOME", "NPM_CONFIG_PREFIX", "npm_config_prefix"] {+ if let Some(value) = std::env::var_os(variable) {+ append(PathBuf::from(value));+ }+ }+ if let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") {+ append(PathBuf::from(local_app_data).join("pnpm"));+ }+}++#[cfg(test)]+mod tests {+ use super::super::test_util::{make_executable, temp_dir};+ use super::*;++ #[test]+ fn find_pnpm_prefers_path_order_and_skips_shim_dir() {+ let root = temp_dir("pnpm-discovery");+ let shim_dir = root.join("shim");+ let first = root.join("first");+ let second = root.join("second");+ std::fs::create_dir_all(&shim_dir).unwrap();+ std::fs::create_dir_all(&first).unwrap();+ std::fs::create_dir_all(&second).unwrap();+ let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };+ std::fs::write(shim_dir.join(name), "shim").unwrap();+ std::fs::write(first.join(name), "first").unwrap();+ std::fs::write(second.join(name), "second").unwrap();+ make_executable(&shim_dir.join(name));+ make_executable(&first.join(name));+ make_executable(&second.join(name));+ let found = find_pnpm_in_dirs(&shim_dir, &[shim_dir.clone(), first.clone(), second]);+ assert_eq!(found, Some(pnpm_env_path(&first.join(name))));+ let _ = std::fs::remove_dir_all(root);+ }++ #[cfg(windows)]+ #[test]+ fn direct_discovery_uses_exe_when_cmd_and_exe_share_a_directory() {+ let root = temp_dir("pnpm-direct-exe");+ let desktop_bin = root.join("desktop-bin");+ let user_bin = root.join("user-bin");+ std::fs::create_dir_all(&desktop_bin).unwrap();+ std::fs::create_dir_all(&user_bin).unwrap();+ let cmd = user_bin.join("pnpm.cmd");+ let exe = user_bin.join("pnpm.exe");+ std::fs::write(&cmd, "cmd").unwrap();+ std::fs::write(&exe, "exe").unwrap();++ assert_eq!(+ find_pnpm_in_dirs(&desktop_bin, std::slice::from_ref(&user_bin)),+ Some(pnpm_env_path(&cmd))+ );+ assert_eq!(+ find_windows_executable_pnpm_in_dirs(&desktop_bin, std::slice::from_ref(&user_bin)),+ Some(pnpm_env_path(&exe))+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn mise_dirs_follow_path_and_dedupe_in_source_order() {+ let root = temp_dir("pnpm-mise-dirs");+ let inherited = root.join("inherited");+ let mise = root.join("mise-data");+ let xdg = root.join("xdg-data");+ let home = root.join("home");+ let mut dirs = vec![inherited.clone(), xdg.join("mise/shims")];++ append_unix_mise_dirs(&mut dirs, Some(&mise), Some(&xdg), Some(&home));++ assert_eq!(+ dirs,+ vec![+ inherited,+ xdg.join("mise/shims"),+ mise.join("shims"),+ home.join(".local/share/mise/shims"),+ ]+ );+ let mut fresh = vec![root.join("fresh-path")];+ append_unix_mise_dirs(&mut fresh, Some(&mise), Some(&xdg), Some(&home));+ assert_eq!(+ fresh,+ vec![+ root.join("fresh-path"),+ mise.join("shims"),+ xdg.join("mise/shims"),+ home.join(".local/share/mise/shims"),+ ]+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn inherited_path_pnpm_precedes_appended_mise_pnpm() {+ let root = temp_dir("pnpm-mise-precedence");+ let desktop_bin = root.join("desktop-bin");+ let inherited = root.join("inherited");+ let mise_data = root.join("mise");+ let mise_shims = mise_data.join("shims");+ for dir in [&desktop_bin, &inherited, &mise_shims] {+ std::fs::create_dir_all(dir).unwrap();+ }+ let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };+ let inherited_pnpm = inherited.join(name);+ let mise_pnpm = mise_shims.join(name);+ std::fs::write(&inherited_pnpm, "inherited").unwrap();+ std::fs::write(&mise_pnpm, "mise").unwrap();+ make_executable(&inherited_pnpm);+ make_executable(&mise_pnpm);+ let mut dirs = vec![inherited];+ append_unix_mise_dirs(&mut dirs, Some(&mise_data), None, None);++ assert_eq!(+ find_pnpm_in_dirs(&desktop_bin, &dirs),+ Some(pnpm_env_path(&inherited_pnpm))+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn default_home_mise_pnpm_is_discovered_when_path_misses() {+ let root = temp_dir("pnpm-mise-home-default");+ let desktop_bin = root.join("desktop-bin");+ let inherited = root.join("inherited");+ let home = root.join("home");+ let home_shims = home.join(".local/share/mise/shims");+ for dir in [&desktop_bin, &inherited, &home_shims] {+ std::fs::create_dir_all(dir).unwrap();+ }+ let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };+ let pnpm = home_shims.join(name);+ std::fs::write(&pnpm, "mise home").unwrap();+ make_executable(&pnpm);+ let mut dirs = vec![inherited];+ append_unix_mise_dirs(&mut dirs, None, None, Some(&home));++ assert_eq!(+ find_pnpm_in_dirs(&desktop_bin, &dirs),+ Some(pnpm_env_path(&pnpm))+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn discovery_misses_desktop_generated_shim_and_absent_candidates() {+ let root = temp_dir("pnpm-own-shim-only");+ let desktop_bin = root.join("desktop-bin");+ let copied_bin = root.join("copied-bin");+ let empty = root.join("empty");+ std::fs::create_dir_all(&desktop_bin).unwrap();+ std::fs::create_dir_all(&copied_bin).unwrap();+ std::fs::create_dir_all(&empty).unwrap();+ let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };+ let own = desktop_bin.join(name);+ let copied = copied_bin.join(name);+ for path in [&own, &copied] {+ std::fs::write(+ path,+ "# DeepSeek Harness Desktop - pnpm command shim (generated)\n",+ )+ .unwrap();+ make_executable(path);+ }++ assert_eq!(+ find_pnpm_in_dirs(&desktop_bin, &[desktop_bin.clone(), copied_bin, empty]),+ None+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn pnpm_env_value_injects_exact_external_path_and_rejects_own_dir() {+ let root = temp_dir("pnpm-env-value");+ let desktop_bin = root.join("desktop-bin");+ let external_bin = root.join("external-bin");+ std::fs::create_dir_all(&desktop_bin).unwrap();+ std::fs::create_dir_all(&external_bin).unwrap();+ let name = if cfg!(windows) { "pnpm.cmd" } else { "pnpm" };+ let own = desktop_bin.join(name);+ let external = external_bin.join(name);+ std::fs::write(&own, "own").unwrap();+ std::fs::write(&external, "external").unwrap();++ assert_eq!(pnpm_env_value(&own, &desktop_bin), None);+ assert_eq!(+ pnpm_env_value(&external, &desktop_bin),+ Some(pnpm_env_path(&external).to_string_lossy().into_owned())+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[cfg(unix)]+ #[test]+ fn discovery_rejects_non_executable_pnpm() {+ let root = temp_dir("pnpm-nonexec");+ let desktop_bin = root.join("desktop-bin");+ let mise_shims = root.join("mise/shims");+ std::fs::create_dir_all(&desktop_bin).unwrap();+ std::fs::create_dir_all(&mise_shims).unwrap();+ std::fs::write(mise_shims.join("pnpm"), "not executable").unwrap();++ assert_eq!(+ find_pnpm_in_dirs(&desktop_bin, std::slice::from_ref(&mise_shims)),+ None+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[cfg(unix)]+ #[test]+ fn discovery_preserves_argv0_style_mise_symlink() {+ use std::os::unix::fs::{symlink, PermissionsExt};++ let root = temp_dir("pnpm-mise-symlink");+ let desktop_bin = root.join("desktop-bin");+ let mise_bin = root.join("mise/bin");+ let mise_shims = root.join("mise/shims");+ for dir in [&desktop_bin, &mise_bin, &mise_shims] {+ std::fs::create_dir_all(dir).unwrap();+ }+ let target = mise_bin.join("mise");+ std::fs::write(+ &target,+ "#!/bin/sh\n[ \"$(basename \"$0\")\" = pnpm ] || exit 51\nprintf 'argv0-ok\\n'\n",+ )+ .unwrap();+ let mut permissions = std::fs::metadata(&target).unwrap().permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(&target, permissions).unwrap();+ let pnpm = mise_shims.join("pnpm");+ symlink(&target, &pnpm).unwrap();++ let found = find_pnpm_in_dirs(&desktop_bin, std::slice::from_ref(&mise_shims)).unwrap();+ assert_eq!(found, pnpm);+ assert_eq!(+ pnpm_env_value(&found, &desktop_bin),+ Some(found.to_string_lossy().into_owned())+ );+ let output = std::process::Command::new(&found).output().unwrap();+ assert!(output.status.success());+ assert_eq!(String::from_utf8_lossy(&output.stdout), "argv0-ok\n");+ let _ = std::fs::remove_dir_all(root);+ }+}diff --git a/src-tauri/src/service/cli/path/rc.rs b/src-tauri/src/service/cli/path/rc.rsnew file mode 100644index 00000000..27d4600a--- /dev/null+++ b/src-tauri/src/service/cli/path/rc.rs@@ -0,0 +1,257 @@+//! Unix shell rc 幂等块更新:向 `~/.zshrc` / `~/.bashrc` 注入/移除+//! `~/.local/bin` 的 PATH 导出块(备份 + 失败回滚)。+//!+//! 注入/移除(依赖 `AppHandle::path()`)仅 Unix 编译;纯文本操作辅助(upsert /+//! strip / 备份写回)在全部平台编译(Windows 上按 dead_code 允许,供测试覆盖)。++use std::fs;+#[cfg(not(windows))]+use tauri::{AppHandle, Manager};++/// shell rc 注入标记(用于幂等增删)+#[cfg_attr(windows, allow(dead_code))]+pub(super) const RC_MARK_START: &str = "# >>> deepseek-harness dsh >>>";+#[cfg_attr(windows, allow(dead_code))]+pub(super) const RC_MARK_END: &str = "# <<< deepseek-harness dsh <<<";++/// Unix 下需要写入 PATH 导出的 rc 文件(按顺序处理)+#[cfg_attr(windows, allow(dead_code))]+pub(super) const RC_FILES: [&str; 2] = [".zshrc", ".bashrc"];++/// Unix:向 `~/.zshrc` / `~/.bashrc` 幂等注入 `~/.local/bin` 的 PATH 导出。+///+/// 只更新自身标记块:读取原文件 → 移除旧块 → 末尾追加新块;仅当文件不存在时+/// 才新建。读失败(非"不存在")直接报错退出,绝不把"读不到"当作空文件去+/// 全量覆盖用户配置;写入前先备份,写失败自动回滚(见 `write_rc_with_backup`)。+#[cfg(not(windows))]+pub(super) fn inject_shell_rc(app_handle: &AppHandle) -> Result<(), String> {+ let home = app_handle+ .path()+ .home_dir()+ .map_err(|_| "failed to resolve home directory".to_string())?;+ let block = format!("{RC_MARK_START}\nexport PATH=\"$HOME/.local/bin:$PATH\"\n{RC_MARK_END}\n");++ for name in RC_FILES {+ let rc_path = home.join(name);+ let original = match fs::read_to_string(&rc_path) {+ Ok(content) => content,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),+ Err(e) => {+ return Err(format!(+ "READ_RC_FAILED: read {} failed: {e}",+ rc_path.display()+ ))+ }+ };+ let next = upsert_rc_block(&original, &block);+ if next == original {+ continue;+ }+ write_rc_with_backup(&rc_path, &next)?;+ log::info!("Injected PATH export into {}", rc_path.display());+ }+ Ok(())+}++/// Unix:从 rc 文件中移除注入块(保留用户其余配置,同样走备份 + 回滚写入)+#[cfg(not(windows))]+pub(super) fn strip_shell_rc(app_handle: &AppHandle) -> Result<(), String> {+ let home = app_handle+ .path()+ .home_dir()+ .map_err(|_| "failed to resolve home directory".to_string())?;+ for name in RC_FILES {+ let rc_path = home.join(name);+ let original = match fs::read_to_string(&rc_path) {+ Ok(content) => content,+ // 文件不存在则无需清理+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,+ Err(e) => {+ return Err(format!(+ "READ_RC_FAILED: read {} failed: {e}",+ rc_path.display()+ ))+ }+ };+ let cleaned = strip_rc_block(&original);+ if cleaned != original {+ write_rc_with_backup(&rc_path, &cleaned)?;+ log::info!("Removed PATH export from {}", rc_path.display());+ }+ }+ Ok(())+}++/// 将 PATH 导出块并入 rc 内容:先移除已有标记块,再在文件末尾追加新块,+/// 只更新自身块、保留用户其余配置,且块始终落在文件末尾。+#[cfg_attr(windows, allow(dead_code))]+fn upsert_rc_block(content: &str, block: &str) -> String {+ let mut out = strip_rc_block(content);+ if !out.is_empty() && !out.ends_with('\n') {+ out.push('\n');+ }+ out.push_str(block);+ if !out.ends_with('\n') {+ out.push('\n');+ }+ out+}++/// 原子写回 rc 文件:写入前先备份为 `<file>.dsh-backup`,再通过同目录+/// 临时文件 + rename 原子替换;写失败时删除临时文件并回滚备份内容,+/// 保证任何异常路径下用户原文件都不会被半写/被清空。+#[cfg_attr(windows, allow(dead_code))]+fn write_rc_with_backup(rc_path: &std::path::Path, new_content: &str) -> Result<(), String> {+ let backup_path = rc_path.with_extension("dsh-backup");+ let had_original = rc_path.exists();+ if had_original {+ fs::copy(rc_path, &backup_path).map_err(|e| {+ format!(+ "BACKUP_RC_FAILED: backup {} to {} failed: {e}",+ rc_path.display(),+ backup_path.display()+ )+ })?;+ }++ let tmp_path = rc_path.with_extension("dsh-rc-tmp");+ fs::write(&tmp_path, new_content)+ .map_err(|e| format!("WRITE_RC_FAILED: write {} failed: {e}", tmp_path.display()))?;+ let rename_res = match fs::rename(&tmp_path, rc_path) {+ Ok(()) => Ok(()),+ // Windows 下 rename 不覆盖已存在目标(仅测试环境会走到):删旧文件后重试+ Err(_) => {+ let _ = fs::remove_file(rc_path);+ fs::rename(&tmp_path, rc_path)+ }+ };+ if let Err(e) = rename_res {+ let _ = fs::remove_file(&tmp_path);+ if had_original {+ let _ = fs::copy(&backup_path, rc_path);+ }+ return Err(format!(+ "RENAME_RC_FAILED: rename into {} failed: {e}",+ rc_path.display()+ ));+ }+ Ok(())+}++/// 移除 rc 文件中的标记块(含标记行本身)。+/// 同时被注入(`upsert_rc_block`)与移除路径使用。+#[cfg_attr(windows, allow(dead_code))]+fn strip_rc_block(content: &str) -> String {+ let mut lines = content.lines().peekable();+ let mut out = String::with_capacity(content.len());+ let mut skipping = false;+ while let Some(line) = lines.next() {+ if line.trim() == RC_MARK_START {+ skipping = true;+ continue;+ }+ if skipping {+ if line.trim() == RC_MARK_END {+ skipping = false;+ }+ continue;+ }+ out.push_str(line);+ out.push('\n');+ }+ out+}++#[cfg(test)]+mod tests {+ use super::super::test_util::temp_dir;+ use super::*;++ const RC_BLOCK: &str =+ "# >>> deepseek-harness dsh >>>\nexport PATH=\"$HOME/.local/bin:$PATH\"\n# <<< deepseek-harness dsh <<<\n";++ /// issue #57:目标 rc 文件已存在且包含用户自定义内容 → 只追加块,原内容保留+ #[test]+ fn upsert_keeps_user_content_and_appends_block() {+ let content = "# oh-my-zsh\nplugins=(git)\nalias ll='ls -alF'\n";+ let next = upsert_rc_block(content, RC_BLOCK);+ assert!(next.starts_with(content));+ assert!(next.ends_with(RC_BLOCK));+ assert_eq!(next.matches(RC_MARK_START).count(), 1);+ }++ /// issue #57:旧块位于文件中间时 → 移除并移动到末尾,周围用户内容保留+ #[test]+ fn upsert_moves_stale_block_to_end() {+ let stale = format!("alias ll='ls -alF'\n{RC_BLOCK}export NVM_DIR=\"$HOME/.nvm\"\n");+ let next = upsert_rc_block(&stale, RC_BLOCK);+ let stripped = strip_rc_block(&next);+ assert_eq!(+ stripped,+ "alias ll='ls -alF'\nexport NVM_DIR=\"$HOME/.nvm\"\n"+ );+ assert!(next.ends_with(RC_BLOCK));+ assert_eq!(next.matches(RC_MARK_START).count(), 1);+ }++ /// 幂等:重复注入不产生第二块+ #[test]+ fn upsert_is_idempotent() {+ let content = "user content\n";+ let once = upsert_rc_block(content, RC_BLOCK);+ assert_eq!(upsert_rc_block(&once, RC_BLOCK), once);+ }++ /// 空内容(文件不存在时的新建场景)→ 仅注入块,没有多余空行+ #[test]+ fn upsert_from_missing_file_creates_block_only() {+ assert_eq!(upsert_rc_block("", RC_BLOCK), RC_BLOCK.to_string());+ }++ /// 无末尾换行的内容 → 补换行后再追加块+ #[test]+ fn upsert_handles_missing_trailing_newline() {+ let next = upsert_rc_block("no trailing nl", RC_BLOCK);+ assert_eq!(next, "no trailing nl\n".to_string() + RC_BLOCK);+ }++ /// strip 原语:移除标记块且幂等+ #[test]+ fn strip_rc_block_removes_block_and_is_idempotent() {+ let content = format!("keep\n{RC_BLOCK}tail\n");+ let cleaned = strip_rc_block(&content);+ assert_eq!(cleaned, "keep\ntail\n");+ assert_eq!(strip_rc_block(&cleaned), cleaned);+ }++ /// 写回:备份保留原内容、目标被替换为 new_content+ #[test]+ fn write_rc_with_backup_preserves_backup() {+ let dir = temp_dir("backup");+ let rc_path = dir.join(".zshrc");+ std::fs::write(&rc_path, "original\n").unwrap();++ write_rc_with_backup(&rc_path, "original\n# block\n").unwrap();++ assert_eq!(+ std::fs::read_to_string(&rc_path).unwrap(),+ "original\n# block\n"+ );+ assert_eq!(+ std::fs::read_to_string(rc_path.with_extension("dsh-backup")).unwrap(),+ "original\n"+ );+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// 写回:文件原本不存在 → 新建成功且不产生备份+ #[test]+ fn write_rc_with_backup_creates_missing_file() {+ let dir = temp_dir("create");+ let rc_path = dir.join(".bashrc");+ write_rc_with_backup(&rc_path, "# block\n").unwrap();+ assert_eq!(std::fs::read_to_string(&rc_path).unwrap(), "# block\n");+ assert!(!rc_path.with_extension("dsh-backup").exists());+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/src-tauri/src/service/cli/path/registry.rs b/src-tauri/src/service/cli/path/registry.rsnew file mode 100644index 00000000..383c3b90--- /dev/null+++ b/src-tauri/src/service/cli/path/registry.rs@@ -0,0 +1,190 @@+//! Windows 注册表辅助:`HKCU\Environment\Path` 读写、`WM_SETTINGCHANGE` 广播+//! 与 PATH token 展开/匹配。仅 Windows 编译(`mod registry` 已在 mod.rs 门控)。++/// Windows 下 shim 根目录名(`%LOCALAPPDATA%\<此目录>\bin`)+#[inline]+pub(super) fn to_wide_null(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(std::iter::once(0)).collect()+}++pub(super) fn read_user_path() -> Option<String> {+ use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_MORE_DATA};+ use windows_sys::Win32::System::Registry::{+ RegCloseKey, RegOpenKeyExW, RegQueryValueExW, HKEY, HKEY_CURRENT_USER, KEY_QUERY_VALUE,+ };++ unsafe {+ let mut hkey: HKEY = std::ptr::null_mut();+ let key_name = to_wide_null("Environment");+ let ret = RegOpenKeyExW(+ HKEY_CURRENT_USER,+ key_name.as_ptr(),+ 0,+ KEY_QUERY_VALUE,+ &mut hkey,+ );+ if ret != 0 {+ log::warn!("failed to open HKCU\\Environment (error {ret})");+ return None;+ }++ let value_name = to_wide_null("Path");+ let mut value_type: u32 = 0;+ let mut size: u32 = 0;+ let mut ret = RegQueryValueExW(+ hkey,+ value_name.as_ptr(),+ std::ptr::null(),+ &mut value_type,+ std::ptr::null_mut(),+ &mut size,+ );++ if ret == ERROR_FILE_NOT_FOUND {+ RegCloseKey(hkey);+ return Some(String::new());+ }+ if ret != ERROR_MORE_DATA && ret != 0 {+ RegCloseKey(hkey);+ log::warn!("failed to query HKCU\\Environment\\Path (error {ret})");+ return None;+ }++ let mut buf = vec![0u16; (size as usize / 2).max(1) + 1];+ ret = RegQueryValueExW(+ hkey,+ value_name.as_ptr(),+ std::ptr::null(),+ &mut value_type,+ buf.as_mut_ptr() as *mut u8,+ &mut size,+ );+ RegCloseKey(hkey);++ if ret != 0 {+ log::warn!("failed to read HKCU\\Environment\\Path (error {ret})");+ return None;+ }+ let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());+ Some(String::from_utf16_lossy(&buf[..end]))+ }+}++pub(super) fn write_user_path(new_value: &str) -> Result<(), String> {+ use windows_sys::Win32::System::Registry::{+ RegCloseKey, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW, HKEY, HKEY_CURRENT_USER,+ KEY_QUERY_VALUE, KEY_SET_VALUE, REG_EXPAND_SZ, REG_SZ,+ };++ unsafe {+ let mut hkey: HKEY = std::ptr::null_mut();+ let key_name = to_wide_null("Environment");+ let ret = RegOpenKeyExW(+ HKEY_CURRENT_USER,+ key_name.as_ptr(),+ 0,+ KEY_QUERY_VALUE | KEY_SET_VALUE,+ &mut hkey,+ );+ if ret != 0 {+ return Err(format!("failed to open HKCU\\Environment (error {ret})"));+ }++ let value_name = to_wide_null("Path");+ let mut value_type: u32 = REG_EXPAND_SZ;+ let mut size: u32 = 0;+ RegQueryValueExW(+ hkey,+ value_name.as_ptr(),+ std::ptr::null(),+ &mut value_type,+ std::ptr::null_mut(),+ &mut size,+ );+ if value_type != REG_SZ && value_type != REG_EXPAND_SZ {+ value_type = REG_EXPAND_SZ;+ }++ let wide_value = to_wide_null(new_value);+ let bytes = (wide_value.len() * 2) as u32;+ let ret = RegSetValueExW(+ hkey,+ value_name.as_ptr(),+ 0,+ value_type,+ wide_value.as_ptr() as *const u8,+ bytes,+ );+ RegCloseKey(hkey);++ if ret != 0 {+ return Err(format!(+ "failed to write HKCU\\Environment\\Path (error {ret})"+ ));+ }+ Ok(())+ }+}++pub(super) fn notify_environment_change() {+ use windows_sys::Win32::Foundation::{LPARAM, WPARAM};+ use windows_sys::Win32::UI::WindowsAndMessaging::{+ SendMessageTimeoutW, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE,+ };+ let wide = to_wide_null("Environment");+ unsafe {+ SendMessageTimeoutW(+ HWND_BROADCAST,+ WM_SETTINGCHANGE,+ 0 as WPARAM,+ wide.as_ptr() as LPARAM,+ SMTO_ABORTIFHUNG,+ 5000,+ std::ptr::null_mut(),+ );+ }+}++/// 展开字符串中的 `%VAR%`(Windows)+fn expand_env(value: &str) -> String {+ use windows_sys::Win32::System::Environment::ExpandEnvironmentStringsW;+ let wide = to_wide_null(value);+ let mut buf = vec![0u16; 32768];+ let n = unsafe { ExpandEnvironmentStringsW(wide.as_ptr(), buf.as_mut_ptr(), buf.len() as u32) };+ if n == 0 || n > buf.len() as u32 {+ return value.to_string();+ }+ let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());+ String::from_utf16_lossy(&buf[..end])+}++/// PATH 值(`;` 分隔)中是否已包含指定目录(大小写不敏感,先展开 %VAR%)+pub(super) fn path_contains_token(path_value: &str, token: &str) -> bool {+ let expanded = expand_env(path_value);+ let token_lower = token.to_lowercase();+ expanded+ .split(';')+ .any(|p| !p.is_empty() && p.trim_end_matches('\\').to_lowercase() == token_lower)+}++/// 从 PATH 值中移除指定目录 token(同时处理 `%LOCALAPPDATA%` 未展开形式)+pub(super) fn remove_path_token(path_value: &str, token: &str) -> String {+ let token_lower = token.to_lowercase();+ let unexpanded_lower = token_lower.replace(+ &std::env::var("LOCALAPPDATA")+ .unwrap_or_default()+ .to_lowercase(),+ "%localappdata%",+ );+ let kept: Vec<&str> = path_value+ .split(';')+ .filter(|p| {+ if p.is_empty() {+ return false;+ }+ let norm = p.trim_end_matches('\\').to_lowercase();+ norm != token_lower && norm != unexpanded_lower+ })+ .collect();+ kept.join(";")+}diff --git a/src-tauri/src/service/cli/shim.rs b/src-tauri/src/service/cli/shim/build.rssimilarity index 59%rename from src-tauri/src/service/cli/shim.rsrename to src-tauri/src/service/cli/shim/build.rsindex f2f87c67..b37cb882 100644--- a/src-tauri/src/service/cli/shim.rs+++ b/src-tauri/src/service/cli/shim/build.rs@@ -1,234 +1,18 @@-//! shim 脚本内容生成:`dsh` / `pnpm` 的 cmd、ps1、sh 包装脚本与落盘。-//!-//! 各构建函数是纯函数(便于测试),`write_shims` 负责写入 bin 目录。+//! shim 脚本内容生成:`dsh` / `pnpm` 的 cmd、ps1、sh 包装脚本构建函数。+//! 各构建函数是纯函数(便于测试),落盘见 [`super::write`]。//! shim 文本必须全英文:cmd/ps1 按系统代码页解析,中文注释会乱码成命令执行。-use crate::config;-use std::fs;use std::path::Path;-use tauri::AppHandle;-/// Windows 下 shim 文件名(cmd 为主入口,ps1 供 PowerShell 原生体验)-pub const SHIM_CMD_NAME: &str = "dsh.cmd";-pub const SHIM_PS1_NAME: &str = "dsh.ps1";-pub const PNPM_SHIM_CMD_NAME: &str = "pnpm.cmd";-pub const PNPM_SHIM_PS1_NAME: &str = "pnpm.ps1";--/// Unix 下 shim 文件名-#[cfg(unix)]-pub const SHIM_SH_NAME: &str = "dsh";-#[cfg(unix)]-pub const PNPM_SHIM_SH_NAME: &str = "pnpm";--// ----------------------------------------------------------------------------// shim 共享片段:node 解析逻辑(dsh / pnpm shim 共用)-//-// 规则:优先 `DSH_NODE` 环境变量(桌面端注入其已解析并核验过的 node 路径,-// 保证 shim 与应用预检一致),其次 PATH 中版本兼容的本地 node(v22.15+ /-// v23.8+ / v24+,与 config::is_supported_node_version 一致),否则回退捆绑-// 运行时。`DSH_NODE` 只在桌面端自身派生的子进程里存在,终端用户环境不受影响。-// 变量约定:cmd 用 %APP_DIR%,ps1 用 $appDir,sh 用 $APP_DIR。-// 这些常量作为 format! 的参数传入,其中的 `{`/`}` 是字面量。-// -----------------------------------------------------------------------------const CMD_NODE_RESOLVE: &str = r#"-rem Prefer the desktop-resolved node (DSH_NODE, injected by the app into its-rem own child processes), then a version-compatible local node, then the-rem bundled runtime. DSH_NODE makes the shim and the app's pre-check agree:-rem the app verified the node exists before spawning the child, and the shim-rem must not re-derive it from PATH (which can miss nodes the app found).-rem Pure batch version check (for /f tokens + numeric compare), no powershell-rem child: avoids console flashes when invoked without a console and skips the-rem per-call powershell startup cost.-if not defined DSH_NODE goto :skip_dsh_node-set "NODE=%DSH_NODE%"-rem Windows canonical paths may carry a \\?\ verbatim prefix that cmd.exe-rem cannot launch directly; strip it before checking/using the path.-if "%NODE:~0,4%"=="\\?\" set "NODE=%NODE:~4%"-if exist "%NODE%" goto :launch-:skip_dsh_node-where node >nul 2>nul-if errorlevel 1 goto :use_bundled-for /f "tokens=1,2 delims=v." %%a in ('node --version 2^>nul ^| findstr /b "v"') do set "NODE_MAJOR=%%a" & set "NODE_MINOR=%%b"-if not defined NODE_MAJOR goto :use_bundled-if %NODE_MAJOR% GEQ 24 goto :node_ok-if %NODE_MAJOR% EQU 22 if defined NODE_MINOR if %NODE_MINOR% GEQ 15 goto :node_ok-if %NODE_MAJOR% EQU 23 if defined NODE_MINOR if %NODE_MINOR% GEQ 8 goto :node_ok-goto :use_bundled--:node_ok-set "NODE=node"-goto :launch--:node_dsh-set "NODE=%DSH_NODE%"-goto :launch--:use_bundled-if not exist "%APP_DIR%\runtime\node.exe" goto :no_node-set "NODE=%APP_DIR%\runtime\node.exe"-set "PATH=%APP_DIR%\runtime;%PATH%"-"#;--const PS1_NODE_RESOLVE: &str = r#"-# Prefer the desktop-resolved node (DSH_NODE, injected by the app into its-# own child processes), then a version-compatible local node, then the-# bundled runtime — see the CMD shim for why DSH_NODE wins first.-$node = $null-if ($env:DSH_NODE) {- $node = $env:DSH_NODE- # Windows canonical paths may carry a \\?\ verbatim prefix; strip it so- # PowerShell/cmd can launch the path directly.- if ($node.StartsWith('\\?\')) { $node = $node.Substring(4) }- if (-not (Test-Path -LiteralPath $node)) { $node = $null }-}-if (-not $node) {- $localNode = Get-Command node -ErrorAction SilentlyContinue- if ($localNode) {- try {- $version = & node --version 2>$null- if ($version -match '^v(\d+)\.(\d+)') {- $major = [int]$matches[1]- $minor = [int]$matches[2]- if (($major -eq 22 -and $minor -ge 15) -or ($major -eq 23 -and $minor -ge 8) -or $major -ge 24) {- $node = 'node'- }- }- } catch { }- }-}-if (-not $node) {- $bundled = Join-Path $appDir 'runtime\node.exe'- if (Test-Path -LiteralPath $bundled) {- $node = $bundled- $env:PATH = (Split-Path -Parent $bundled) + ';' + $env:PATH- }-}-if (-not $node) {- Write-Error 'Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first.'- exit 1-}-"#;--const SH_NODE_RESOLVE: &str = r#"-NODE=""-# Prefer the desktop-resolved node (DSH_NODE, injected by the app into its-# own child processes), then a version-compatible local node, then the-# bundled runtime — see the CMD shim for why DSH_NODE wins first.-if [ -n "$DSH_NODE" ] && [ -x "$DSH_NODE" ]; then- NODE="$DSH_NODE"-fi-if [ -z "$NODE" ] && command -v node >/dev/null 2>&1; then- NODE_V=$(node --version 2>/dev/null)- MAJOR=$(printf '%s' "$NODE_V" | awk -F. '{ gsub(/^v/, "", $1); print $1 }')- MINOR=$(printf '%s' "$NODE_V" | awk -F. '{ print $2 }')- if { [ -n "$MAJOR" ] && [ "$MAJOR" -ge 24 ]; } 2>/dev/null || \- { [ "$MAJOR" -eq 22 ] && [ "$MINOR" -ge 15 ]; } 2>/dev/null || \- { [ "$MAJOR" -eq 23 ] && [ "$MINOR" -ge 8 ]; } 2>/dev/null; then- NODE="node"- fi-fi-if [ -z "$NODE" ]; then- if [ -x "$APP_DIR/runtime/bin/node" ]; then- NODE="$APP_DIR/runtime/bin/node"- export PATH="$APP_DIR/runtime/bin:$PATH"- fi-fi-if [ -z "$NODE" ]; then- echo "Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first." >&2- exit 1-fi-"#;--// ----------------------------------------------------------------------------// dsh shim 共享片段:用户已安装的 dsh 优先(避免覆盖/遮蔽用户自己的 dsh 与-// $DSH_HOME)。与 pnpm shim 的"用户优先"策略一致:先转发 PATH 中(排除本-// shim 目录)的用户 dsh,转发时不注入本应用的 DSH_HOME,保留用户环境;-// 仅找不到用户 dsh 时才回退到捆绑 dsh。-// 变量约定:cmd 用 %SELF_PREFIX%/%USER_DSH%,ps1 用 $selfDir/$userDsh,-// sh 用 $SELF_DIR。dsh shim 仅 release 构建写入(debug 构建不覆盖共享的-// dsh shim,见 write_shims),debug 下这些常量/函数未使用,允许 dead_code。-#[cfg_attr(debug_assertions, allow(dead_code))]-const CMD_USER_DSH_PRECEDENCE: &str = r#"-rem Prefer a user-installed dsh on PATH (skip our own shim dir), fall back to bundled.-rem This preserves your own dsh binary and its $DSH_HOME config; nothing is overwritten.-set "SELF_PREFIX=%~dp0"-set "SELF_PREFIX=%SELF_PREFIX:~0,-1%"-set "USER_DSH="-for /f "delims=" %%d in ('where dsh 2^>nul') do (- if not defined USER_DSH (- if /i not "%%d"=="%SELF_PREFIX%\dsh.cmd" (- if /i not "%%d"=="%SELF_PREFIX%\dsh.ps1" (- if /i not "%%d"=="%SELF_PREFIX%\dsh.exe" (- if /i not "%%d"=="%SELF_PREFIX%\dsh.bat" (- if /i "%%~xd"==".cmd" set "USER_DSH=%%d"- if /i "%%~xd"==".exe" set "USER_DSH=%%d"- if /i "%%~xd"==".bat" set "USER_DSH=%%d"- )- )- )- )- )-)-if defined USER_DSH (- call "%USER_DSH%" %*- exit /b %ERRORLEVEL%-)-"#;--#[cfg_attr(debug_assertions, allow(dead_code))]-const PS1_USER_DSH_PRECEDENCE: &str = r#"-# Prefer a user-installed dsh on PATH (skip our own shim dir), fall back to bundled.-# This preserves your own dsh binary and its $env:DSH_HOME config; nothing is overwritten.-$selfDir = $PSScriptRoot.TrimEnd('\') + '\'-$userDsh = Get-Command dsh -All -ErrorAction SilentlyContinue |- Where-Object { $_.Source -and -not $_.Source.StartsWith($selfDir, [System.StringComparison]::OrdinalIgnoreCase) } |- Select-Object -First 1-if ($userDsh) {- & $userDsh.Source @args- exit $LASTEXITCODE-}-"#;--#[cfg_attr(windows, allow(dead_code))] // 仅 Unix shim 使用-#[cfg_attr(debug_assertions, allow(dead_code))]-const SH_USER_DSH_PRECEDENCE: &str = r#"-# Prefer a user-installed dsh on PATH (skip our own shim dir), fall back to bundled.-# This preserves your own dsh binary and its $DSH_HOME config; nothing is overwritten.-SELF_DIR=$(cd "$(dirname "$0")" && pwd)-IFS=:-for dir in $PATH; do- if [ "$dir" = "$SELF_DIR" ]; then- continue- fi- if [ -x "$dir/dsh" ]; then- exec "$dir/dsh" "$@"- fi-done-unset IFS-"#;--// ----------------------------------------------------------------------------// 路径转义(按目标脚本语言的字符串规则)-// -----------------------------------------------------------------------------/// 批处理中 `%` 会被展开,需写成 `%%`-#[inline]-pub fn escape_path_cmd(path: &Path) -> String {- path.to_string_lossy().replace('%', "%%")-}--/// 单引号字符串中 `'` 需翻倍-#[inline]-pub fn escape_path_ps1(path: &Path) -> String {- path.to_string_lossy().replace('\'', "''")-}--/// 单引号字符串中 `'` 需写成 `'\''`-#[inline]-pub fn escape_path_sh(path: &Path) -> String {- path.to_string_lossy().replace('\'', "'\\''")-}+use super::escape_path_cmd;+use super::escape_path_ps1;+use super::escape_path_sh;+#[cfg(not(windows))]+use super::templates::SH_USER_DSH_PRECEDENCE;+use super::templates::{+ CMD_NODE_RESOLVE, CMD_USER_DSH_PRECEDENCE, PS1_NODE_RESOLVE, PS1_USER_DSH_PRECEDENCE,+ SH_NODE_RESOLVE,+};// ---------------------------------------------------------------------------// dsh shim@@ -555,210 +339,14 @@ exec "$NODE" "$PNPM_BIN" "$@")}-// ----------------------------------------------------------------------------// 落盘-// -----------------------------------------------------------------------------/// 生成的 shim 自带的可识别标记(首行注释)。用于区分"本应用生成的 shim"-/// 与"用户自行放置的同名文件"。读文件只读该标记行,避免误删用户自有文件。-const GENERATED_MARKER: &str = "DeepSeek Harness Desktop - ";--/// 目标路径已存在且不是本应用生成的 shim(即用户手动放置的 `dsh`/`pnpm`)。-///-/// 此时绝不覆盖,保留用户文件,避免"安装后清空了之前手动安装的工具"。-fn is_foreign_file(path: &Path) -> bool {- !is_generated_shim(path)-}--/// 路径是否为悬空符号链接(链接本身存在,但指向的目标不存在)。-///-/// 官方 dsh 安装器会在 `~/.local/bin/dsh -> ~/.dsh/source/current/bin/dsh` 留下-/// 符号链接;当 `current` 指向的目录被移动/删除后链接即悬空。此时-/// `Path::exists()` 跟随链接返回 `false`,但直接 `fs::write` 会沿链接打开目标-/// 并在其父目录缺失时报 `No such file or directory (os error 2)`——必须先把-/// 已失效的链接本身移除,才能按"文件不存在"正常写入。-fn is_dangling_symlink(path: &Path) -> bool {- match path.symlink_metadata() {- Ok(meta) => meta.file_type().is_symlink() && !path.exists(),- Err(_) => false,- }-}--/// 判断路径是否为本应用生成的 shim(内容含生成标记)。-///-/// 用于在本地 dsh 探测中区分"本应用 shim"与"用户自行放置的同名文件":-/// 前者应被排除(它转发到捆绑 dsh,不构成用户本地核心),后者应被识别。-pub fn is_generated_shim(path: &Path) -> bool {- match std::fs::read_to_string(path) {- Ok(content) => content.contains(GENERATED_MARKER),- Err(_) => false,- }-}--/// 写入单个 shim 文件,处理目标已存在时的三种情形:-///-/// 1. 悬空符号链接(用户/官方安装器残留、目标已失效)→ 移除链接后正常写入;-/// 2. 已存在且非本应用生成(用户手动放置的 `dsh`/`pnpm`)→ 跳过,保留用户文件;-/// 3. 其余(不存在,或本应用生成的 shim)→ 直接写入/覆盖。-fn write_shim_file(target: &Path, content: &str) -> Result<(), String> {- if is_dangling_symlink(target) {- log::warn!(- "Removing dangling symlink {:?} before writing shim (its target is gone)",- target- );- fs::remove_file(target)- .map_err(|e| format!("remove dangling symlink {} failed: {e}", target.display()))?;- }- if target.exists() && is_foreign_file(target) {- log::warn!(- "Skipping shim write to {:?}: an existing user file is preserved",- target- );- return Ok(());- }- fs::write(target, content).map_err(|e| format!("write {} failed: {e}", target.display()))-}--/// 主 `dsh` shim 路径下是否保留了用户自行安装的同名文件(用于状态展示)。-pub fn user_dsh_preserved(bin_dir: &Path) -> bool {- let path = {- #[cfg(windows)]- {- bin_dir.join(SHIM_CMD_NAME)- }- #[cfg(not(windows))]- {- bin_dir.join(SHIM_SH_NAME)- }- };- path.is_file() && is_foreign_file(&path)-}--/// 将 shim 文件写入 bin 目录;目标已存在但非本应用生成的同名文件时跳过(保留)。-/// 目标为悬空符号链接时先移除链接再写入(链接目标已失效,保留只会让写入-/// 报 ENOENT)。-///-/// 覆盖式仅针对本应用生成的 shim(自愈时内容与当前安装一致);用户手动放置的-/// 同名 `dsh`/`pnpm` 一律保留不动,避免覆盖用户自己的安装与配置。-pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String> {- let app_dir = config::get_base_dir(app_handle);- fs::create_dir_all(bin_dir).map_err(|e| format!("create bin dir failed: {e}"))?;-- // 写入单个 shim:若目标已存在且非本应用生成,则跳过不覆盖(保留用户文件)。- macro_rules! write_if_ours {- ($path:expr, $content:expr) => {{- let target = bin_dir.join($path);- write_shim_file(&target, &$content)?;- target- }};- }-- // dsh shim 会在内容里烘焙 $DSH_HOME(生产为 ~/.dsh、开发为 ~/.dsh.dev)。- // 开发构建禁止改写用户共享的 dsh shim——改写会让终端 `dsh` 指向开发数据- // 目录,并覆盖生产的命令行集成;生产版生成的 dsh shim 原样保留。- #[cfg(not(debug_assertions))]- {- let dsh_home = config::get_dsh_data_path(app_handle);- #[cfg(windows)]- {- write_if_ours!(SHIM_CMD_NAME, build_cmd_shim(&app_dir, &dsh_home));- write_if_ours!(SHIM_PS1_NAME, build_ps1_shim(&app_dir, &dsh_home));- }- #[cfg(not(windows))]- {- write_if_ours!(SHIM_SH_NAME, build_sh_shim(&app_dir, &dsh_home));- }- }- #[cfg(debug_assertions)]- log::debug!("debug build: skip dsh shim write (shared user state kept for release)");-- // pnpm shim 不烘焙 $DSH_HOME(仅绑定 bundle 目录与“用户 pnpm 优先”逻辑),- // 内容与生产完全一致,开发构建也可写入——dsh plugin 子进程经 PATH 解析- // pnpm 依赖它,写它不污染任何共享数据。- #[cfg(windows)]- {- write_if_ours!(PNPM_SHIM_CMD_NAME, build_pnpm_cmd_shim(&app_dir));- write_if_ours!(PNPM_SHIM_PS1_NAME, build_pnpm_ps1_shim(&app_dir));- }- #[cfg(not(windows))]- {- write_if_ours!(PNPM_SHIM_SH_NAME, build_pnpm_sh_shim(&app_dir));- // 仅对本应用生成/覆盖过的 shim 设置可执行位;保留的用户文件不动- let chmod_names: &[&str] = if cfg!(debug_assertions) {- &[PNPM_SHIM_SH_NAME]- } else {- &[SHIM_SH_NAME, PNPM_SHIM_SH_NAME]- };- for name in chmod_names {- let path = bin_dir.join(name);- if path.is_file() && !is_foreign_file(&path) {- use std::os::unix::fs::PermissionsExt;- fs::set_permissions(&path, fs::Permissions::from_mode(0o755))- .map_err(|e| format!("chmod shim failed: {e}"))?;- }- }- }- Ok(())-}-#[cfg(test)]mod tests {+ use super::super::test_util::{sample_app_dir, sample_dsh_home, temp_dir};use super::*;use std::path::PathBuf;- // ------------------------------------------------------------------- // escape_path_* 纯函数基线(与 shim 内嵌路径的场景一致)- // -------------------------------------------------------------------- #[test]- fn escape_path_cmd_doubles_percent() {- assert_eq!(- escape_path_cmd(Path::new(r"C:\Users\%test%\x")),- r"C:\Users\%%test%%\x"- );- assert_eq!(escape_path_cmd(Path::new("/tmp/a b")), "/tmp/a b");- }-- #[test]- fn escape_path_ps1_doubles_single_quotes() {- assert_eq!(- escape_path_ps1(Path::new(r"C:\Users\o'brien")),- r"C:\Users\o''brien"- );- assert_eq!(escape_path_ps1(Path::new("/plain/path")), "/plain/path");- }-- #[test]- fn escape_path_sh_escapes_single_quotes() {- assert_eq!(- escape_path_sh(Path::new("/home/o'brien/.dsh")),- r"/home/o'\''brien/.dsh"- );- assert_eq!(escape_path_sh(Path::new("/plain/.dsh")), "/plain/.dsh");- }-- fn sample_app_dir() -> PathBuf {- if cfg!(windows) {- PathBuf::from(- r"C:\Users\test\AppData\Roaming\io.github.hairyf.deepseek-harness-desktop",- )- } else {- PathBuf::from("/home/test/.local/share/io.github.hairyf.deepseek-harness-desktop")- }- }-- /// 官方 $DSH_HOME(~/.dsh)- fn sample_dsh_home() -> PathBuf {- if cfg!(windows) {- PathBuf::from(r"C:\Users\test\.dsh")- } else {- PathBuf::from("/home/test/.dsh")- }- }-#[cfg(windows)]#[test]- #[cfg(windows)]fn cmd_shim_contains_baked_paths() {let content = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());assert!(content.contains(r"C:\Users\test\AppData\Roaming"));@@ -1154,7 +742,6 @@ mod tests {#[cfg(windows)]#[test]- #[cfg(windows)]fn ps1_shim_escapes_quotes() {let dir = PathBuf::from(r"C:\Users\o'brien\AppData\Roaming\io.github.hairyf.deepseek-harness-desktop",@@ -1202,133 +789,4 @@ mod tests {assert!(user_at < home_at);}}-- #[test]- fn foreign_file_detection() {- let dir = std::env::temp_dir().join(format!("dsh-shim-test-{}", std::process::id()));- let _ = std::fs::remove_dir_all(&dir);- std::fs::create_dir_all(&dir).unwrap();-- // 用户手动放置的 dsh 脚本 -> 视为 foreign,不应被覆盖- let user_dsh = dir.join(if cfg!(windows) { "dsh.cmd" } else { "dsh" });- std::fs::write(&user_dsh, "#!/bin/sh\necho my real dsh\n").unwrap();- assert!(- is_foreign_file(&user_dsh),- "user file must be treated as foreign"- );-- // 本应用生成的 shim -> 不是 foreign,可覆盖- #[cfg(not(windows))]- let generated = build_sh_shim(&sample_app_dir(), &sample_dsh_home());- #[cfg(windows)]- let generated = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());- std::fs::write(&user_dsh, generated).unwrap();- assert!(- !is_foreign_file(&user_dsh),- "generated shim must not be foreign"- );-- let _ = std::fs::remove_dir_all(&dir);- }-- // ------------------------------------------------------------------- // write_shim_file 目标文件处理(悬空符号链接 / 用户文件保留 / 生成文件覆盖)- // -------------------------------------------------------------------- /// 独立的临时目录,避免测试间互相干扰- fn temp_dir(tag: &str) -> std::path::PathBuf {- let dir = std::env::temp_dir().join(format!(- "dsh-shim-write-{tag}-{}-{}",- std::process::id(),- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_nanos())- .unwrap_or(0)- ));- let _ = std::fs::remove_dir_all(&dir);- std::fs::create_dir_all(&dir).unwrap();- dir- }-- /// 悬空符号链接(官方 dsh 安装器残留 `~/.local/bin/dsh -> ~/.dsh/source/current/bin/dsh`- /// 且目标已消失)时:先移除失效链接,再正常写入生成 shim——修复原报错- /// `write ... failed: No such file or directory (os error 2)`- #[test]- #[cfg(unix)]- fn write_shim_file_removes_dangling_symlink() {- use std::os::unix::fs::symlink;-- let dir = temp_dir("dangling");- let target = dir.join("dsh");- symlink(dir.join("missing/source/current/bin/dsh"), &target).unwrap();- assert!(is_dangling_symlink(&target));-- write_shim_file(&target, "#!/bin/sh\ngenerated shim\n").unwrap();-- assert_eq!(- std::fs::read_to_string(&target).unwrap(),- "#!/bin/sh\ngenerated shim\n"- );- assert!(- !std::fs::symlink_metadata(&target)- .unwrap()- .file_type()- .is_symlink(),- "dangling symlink must be replaced by a regular file"- );- assert!(!is_dangling_symlink(&target));- let _ = std::fs::remove_dir_all(&dir);- }-- /// 指向真实用户 dsh 的符号链接(目标仍存在)→ 视为用户文件,保留不动- #[test]- #[cfg(unix)]- fn write_shim_file_preserves_valid_user_symlink() {- use std::os::unix::fs::symlink;-- let dir = temp_dir("userlink");- let real = dir.join("real-dsh");- std::fs::write(&real, "#!/bin/sh\necho my real dsh\n").unwrap();- let target = dir.join("dsh");- symlink(&real, &target).unwrap();-- write_shim_file(&target, "#!/bin/sh\ngenerated shim\n").unwrap();-- assert!(- std::fs::symlink_metadata(&target)- .unwrap()- .file_type()- .is_symlink(),- "valid user symlink must be preserved"- );- assert_eq!(- std::fs::read_to_string(&real).unwrap(),- "#!/bin/sh\necho my real dsh\n"- );- let _ = std::fs::remove_dir_all(&dir);- }-- /// 本应用生成的 shim → 覆盖自愈内容- #[test]- fn write_shim_file_overwrites_generated_shim() {- let dir = temp_dir("overwrite");- let target = dir.join("dsh");- std::fs::write(- &target,- "#!/bin/sh\n# DeepSeek Harness Desktop - old shim\n",- )- .unwrap();-- write_shim_file(- &target,- "#!/bin/sh\n# DeepSeek Harness Desktop - new shim\n",- )- .unwrap();-- assert_eq!(- std::fs::read_to_string(&target).unwrap(),- "#!/bin/sh\n# DeepSeek Harness Desktop - new shim\n"- );- let _ = std::fs::remove_dir_all(&dir);- }}diff --git a/src-tauri/src/service/cli/shim/mod.rs b/src-tauri/src/service/cli/shim/mod.rsnew file mode 100644index 00000000..e6e60264--- /dev/null+++ b/src-tauri/src/service/cli/shim/mod.rs@@ -0,0 +1,125 @@+//! shim 脚本内容生成与落盘:`dsh` / `pnpm` 的 cmd、ps1、sh 包装脚本。+//!+//! 模块划分:+//! - [`templates`]:共享脚本片段常量(node 解析、用户优先逻辑)+//! - [`build`]:各平台 shim 构建函数(纯函数,便于测试)+//! - [`write`]:落盘(生成标记识别、悬空符号链接、用户文件保留)+//!+//! shim 文本必须全英文:cmd/ps1 按系统代码页解析,中文注释会乱码成命令执行。++use std::path::Path;++mod build;+mod templates;+mod write;++pub use write::{is_generated_shim, user_dsh_preserved, write_shims};++/// Windows 下 shim 文件名(cmd 为主入口,ps1 供 PowerShell 原生体验)+pub const SHIM_CMD_NAME: &str = "dsh.cmd";+pub const SHIM_PS1_NAME: &str = "dsh.ps1";+pub const PNPM_SHIM_CMD_NAME: &str = "pnpm.cmd";+pub const PNPM_SHIM_PS1_NAME: &str = "pnpm.ps1";++/// Unix 下 shim 文件名+#[cfg(unix)]+pub const SHIM_SH_NAME: &str = "dsh";+#[cfg(unix)]+pub const PNPM_SHIM_SH_NAME: &str = "pnpm";++// ---------------------------------------------------------------------------+// 路径转义(按目标脚本语言的字符串规则)+// ---------------------------------------------------------------------------++/// 批处理中 `%` 会被展开,需写成 `%%`+#[inline]+pub fn escape_path_cmd(path: &Path) -> String {+ path.to_string_lossy().replace('%', "%%")+}++/// 单引号字符串中 `'` 需翻倍+#[inline]+pub fn escape_path_ps1(path: &Path) -> String {+ path.to_string_lossy().replace('\'', "''")+}++/// 单引号字符串中 `'` 需写成 `'\''`+#[inline]+pub fn escape_path_sh(path: &Path) -> String {+ path.to_string_lossy().replace('\'', "'\\''")+}++#[cfg(test)]+mod test_util {+ use std::path::PathBuf;++ pub(super) fn sample_app_dir() -> PathBuf {+ if cfg!(windows) {+ PathBuf::from(+ r"C:\Users\test\AppData\Roaming\io.github.hairyf.deepseek-harness-desktop",+ )+ } else {+ PathBuf::from("/home/test/.local/share/io.github.hairyf.deepseek-harness-desktop")+ }+ }++ /// 官方 $DSH_HOME(~/.dsh)+ pub(super) fn sample_dsh_home() -> PathBuf {+ if cfg!(windows) {+ PathBuf::from(r"C:\Users\test\.dsh")+ } else {+ PathBuf::from("/home/test/.dsh")+ }+ }++ /// 独立的临时目录,避免测试间互相干扰+ pub(super) fn temp_dir(tag: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "dsh-shim-{tag}-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ // ------------------------------------------------------------------+ // escape_path_* 纯函数基线(与 shim 内嵌路径的场景一致)+ // ------------------------------------------------------------------++ #[test]+ fn escape_path_cmd_doubles_percent() {+ assert_eq!(+ escape_path_cmd(Path::new(r"C:\Users\%test%\x")),+ r"C:\Users\%%test%%\x"+ );+ assert_eq!(escape_path_cmd(Path::new("/tmp/a b")), "/tmp/a b");+ }++ #[test]+ fn escape_path_ps1_doubles_single_quotes() {+ assert_eq!(+ escape_path_ps1(Path::new(r"C:\Users\o'brien")),+ r"C:\Users\o''brien"+ );+ assert_eq!(escape_path_ps1(Path::new("/plain/path")), "/plain/path");+ }++ #[test]+ fn escape_path_sh_escapes_single_quotes() {+ assert_eq!(+ escape_path_sh(Path::new("/home/o'brien/.dsh")),+ r"/home/o'\''brien/.dsh"+ );+ assert_eq!(escape_path_sh(Path::new("/plain/.dsh")), "/plain/.dsh");+ }+}diff --git a/src-tauri/src/service/cli/shim/templates.rs b/src-tauri/src/service/cli/shim/templates.rsnew file mode 100644index 00000000..7cbd5aad--- /dev/null+++ b/src-tauri/src/service/cli/shim/templates.rs@@ -0,0 +1,193 @@+//! shim 共享脚本片段(纯文本常量,作为 format! 的参数嵌入各构建函数)。+//!+//! shim 文本必须全英文:cmd/ps1 按系统代码页解析,中文注释会乱码成命令执行。+//! 变量约定:cmd 用 `%APP_DIR%`,ps1 用 `$appDir`,sh 用 `$APP_DIR`;+//! 这些常量里的 `{`/`}` 是字面量(由 format! 的参数占位符区分)。++// ---------------------------------------------------------------------------+// shim 共享片段:node 解析逻辑(dsh / pnpm shim 共用)+//+// 规则:优先 `DSH_NODE` 环境变量(桌面端注入其已解析并核验过的 node 路径,+// 保证 shim 与应用预检一致),其次 PATH 中版本兼容的本地 node(v22.15+ /+// v23.8+ / v24+,与 config::is_supported_node_version 一致),否则回退捆绑+// 运行时。`DSH_NODE` 只在桌面端自身派生的子进程里存在,终端用户环境不受影响。+// ---------------------------------------------------------------------------++pub(super) const CMD_NODE_RESOLVE: &str = r#"+rem Prefer the desktop-resolved node (DSH_NODE, injected by the app into its+rem own child processes), then a version-compatible local node, then the+rem bundled runtime. DSH_NODE makes the shim and the app's pre-check agree:+rem the app verified the node exists before spawning the child, and the shim+rem must not re-derive it from PATH (which can miss nodes the app found).+rem Pure batch version check (for /f tokens + numeric compare), no powershell+rem child: avoids console flashes when invoked without a console and skips the+rem per-call powershell startup cost.+if not defined DSH_NODE goto :skip_dsh_node+set "NODE=%DSH_NODE%"+rem Windows canonical paths may carry a \\?\ verbatim prefix that cmd.exe+rem cannot launch directly; strip it before checking/using the path.+if "%NODE:~0,4%"=="\\?\" set "NODE=%NODE:~4%"+if exist "%NODE%" goto :launch+:skip_dsh_node+where node >nul 2>nul+if errorlevel 1 goto :use_bundled+for /f "tokens=1,2 delims=v." %%a in ('node --version 2^>nul ^| findstr /b "v"') do set "NODE_MAJOR=%%a" & set "NODE_MINOR=%%b"+if not defined NODE_MAJOR goto :use_bundled+if %NODE_MAJOR% GEQ 24 goto :node_ok+if %NODE_MAJOR% EQU 22 if defined NODE_MINOR if %NODE_MINOR% GEQ 15 goto :node_ok+if %NODE_MAJOR% EQU 23 if defined NODE_MINOR if %NODE_MINOR% GEQ 8 goto :node_ok+goto :use_bundled++:node_ok+set "NODE=node"+goto :launch++:node_dsh+set "NODE=%DSH_NODE%"+goto :launch++:use_bundled+if not exist "%APP_DIR%\runtime\node.exe" goto :no_node+set "NODE=%APP_DIR%\runtime\node.exe"+set "PATH=%APP_DIR%\runtime;%PATH%"+"#;++pub(super) const PS1_NODE_RESOLVE: &str = r#"+# Prefer the desktop-resolved node (DSH_NODE, injected by the app into its+# own child processes), then a version-compatible local node, then the+# bundled runtime — see the CMD shim for why DSH_NODE wins first.+$node = $null+if ($env:DSH_NODE) {+ $node = $env:DSH_NODE+ # Windows canonical paths may carry a \\?\ verbatim prefix; strip it so+ # PowerShell/cmd can launch the path directly.+ if ($node.StartsWith('\\?\')) { $node = $node.Substring(4) }+ if (-not (Test-Path -LiteralPath $node)) { $node = $null }+}+if (-not $node) {+ $localNode = Get-Command node -ErrorAction SilentlyContinue+ if ($localNode) {+ try {+ $version = & node --version 2>$null+ if ($version -match '^v(\d+)\.(\d+)') {+ $major = [int]$matches[1]+ $minor = [int]$matches[2]+ if (($major -eq 22 -and $minor -ge 15) -or ($major -eq 23 -and $minor -ge 8) -or $major -ge 24) {+ $node = 'node'+ }+ }+ } catch { }+ }+}+if (-not $node) {+ $bundled = Join-Path $appDir 'runtime\node.exe'+ if (Test-Path -LiteralPath $bundled) {+ $node = $bundled+ $env:PATH = (Split-Path -Parent $bundled) + ';' + $env:PATH+ }+}+if (-not $node) {+ Write-Error 'Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first.'+ exit 1+}+"#;++pub(super) const SH_NODE_RESOLVE: &str = r#"+NODE=""+# Prefer the desktop-resolved node (DSH_NODE, injected by the app into its+# own child processes), then a version-compatible local node, then the+# bundled runtime — see the CMD shim for why DSH_NODE wins first.+if [ -n "$DSH_NODE" ] && [ -x "$DSH_NODE" ]; then+ NODE="$DSH_NODE"+fi+if [ -z "$NODE" ] && command -v node >/dev/null 2>&1; then+ NODE_V=$(node --version 2>/dev/null)+ MAJOR=$(printf '%s' "$NODE_V" | awk -F. '{ gsub(/^v/, "", $1); print $1 }')+ MINOR=$(printf '%s' "$NODE_V" | awk -F. '{ print $2 }')+ if { [ -n "$MAJOR" ] && [ "$MAJOR" -ge 24 ]; } 2>/dev/null || \+ { [ "$MAJOR" -eq 22 ] && [ "$MINOR" -ge 15 ]; } 2>/dev/null || \+ { [ "$MAJOR" -eq 23 ] && [ "$MINOR" -ge 8 ]; } 2>/dev/null; then+ NODE="node"+ fi+fi+if [ -z "$NODE" ]; then+ if [ -x "$APP_DIR/runtime/bin/node" ]; then+ NODE="$APP_DIR/runtime/bin/node"+ export PATH="$APP_DIR/runtime/bin:$PATH"+ fi+fi+if [ -z "$NODE" ]; then+ echo "Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first." >&2+ exit 1+fi+"#;++// ---------------------------------------------------------------------------+// dsh shim 共享片段:用户已安装的 dsh 优先(避免覆盖/遮蔽用户自己的 dsh 与+// $DSH_HOME)。与 pnpm shim 的"用户优先"策略一致:先转发 PATH 中(排除本+// shim 目录)的用户 dsh,转发时不注入本应用的 DSH_HOME,保留用户环境;+// 仅找不到用户 dsh 时才回退到捆绑 dsh。+// 变量约定:cmd 用 %SELF_PREFIX%/%USER_DSH%,ps1 用 $selfDir/$userDsh,+// sh 用 $SELF_DIR。dsh shim 仅 release 构建写入(debug 构建不覆盖共享的+// dsh shim,见 write_shims),debug 下这些常量/函数未使用,允许 dead_code。+// ---------------------------------------------------------------------------++#[cfg_attr(debug_assertions, allow(dead_code))]+pub(super) const CMD_USER_DSH_PRECEDENCE: &str = r#"+rem Prefer a user-installed dsh on PATH (skip our own shim dir), fall back to bundled.+rem This preserves your own dsh binary and its $DSH_HOME config; nothing is overwritten.+set "SELF_PREFIX=%~dp0"+set "SELF_PREFIX=%SELF_PREFIX:~0,-1%"+set "USER_DSH="+for /f "delims=" %%d in ('where dsh 2^>nul') do (+ if not defined USER_DSH (+ if /i not "%%d"=="%SELF_PREFIX%\dsh.cmd" (+ if /i not "%%d"=="%SELF_PREFIX%\dsh.ps1" (+ if /i not "%%d"=="%SELF_PREFIX%\dsh.exe" (+ if /i not "%%d"=="%SELF_PREFIX%\dsh.bat" (+ if /i "%%~xd"==".cmd" set "USER_DSH=%%d"+ if /i "%%~xd"==".exe" set "USER_DSH=%%d"+ if /i "%%~xd"==".bat" set "USER_DSH=%%d"+ )+ )+ )+ )+ )+)+if defined USER_DSH (+ call "%USER_DSH%" %*+ exit /b %ERRORLEVEL%+)+"#;++#[cfg_attr(debug_assertions, allow(dead_code))]+pub(super) const PS1_USER_DSH_PRECEDENCE: &str = r#"+# Prefer a user-installed dsh on PATH (skip our own shim dir), fall back to bundled.+# This preserves your own dsh binary and its $env:DSH_HOME config; nothing is overwritten.+$selfDir = $PSScriptRoot.TrimEnd('\') + '\'+$userDsh = Get-Command dsh -All -ErrorAction SilentlyContinue |+ Where-Object { $_.Source -and -not $_.Source.StartsWith($selfDir, [System.StringComparison]::OrdinalIgnoreCase) } |+ Select-Object -First 1+if ($userDsh) {+ & $userDsh.Source @args+ exit $LASTEXITCODE+}+"#;++#[cfg_attr(windows, allow(dead_code))] // 仅 Unix shim 使用+#[cfg_attr(debug_assertions, allow(dead_code))]+pub(super) const SH_USER_DSH_PRECEDENCE: &str = r#"+# Prefer a user-installed dsh on PATH (skip our own shim dir), fall back to bundled.+# This preserves your own dsh binary and its $DSH_HOME config; nothing is overwritten.+SELF_DIR=$(cd "$(dirname "$0")" && pwd)+IFS=:+for dir in $PATH; do+ if [ "$dir" = "$SELF_DIR" ]; then+ continue+ fi+ if [ -x "$dir/dsh" ]; then+ exec "$dir/dsh" "$@"+ fi+done+unset IFS+"#;diff --git a/src-tauri/src/service/cli/shim/write.rs b/src-tauri/src/service/cli/shim/write.rsnew file mode 100644index 00000000..a2d9213f--- /dev/null+++ b/src-tauri/src/service/cli/shim/write.rs@@ -0,0 +1,297 @@+//! shim 落盘:生成标记识别、悬空符号链接处理、用户文件保留与写入编排。++use crate::config;+use std::fs;+use std::path::Path;+use tauri::AppHandle;++#[cfg(not(windows))]+#[allow(unused_imports)] // debug 构建 dsh shim 不写入;测试仍引用+use super::build::build_sh_shim;+#[allow(unused_imports)] // 构建函数在 debug 构建/异平台下由 cfg 裁剪,测试仍引用+use super::build::{+ build_cmd_shim, build_pnpm_cmd_shim, build_pnpm_ps1_shim, build_pnpm_sh_shim, build_ps1_shim,+};+#[cfg(all(windows, not(debug_assertions)))]+use super::SHIM_PS1_NAME;+#[cfg(windows)]+use super::{PNPM_SHIM_CMD_NAME, PNPM_SHIM_PS1_NAME, SHIM_CMD_NAME};+#[cfg(not(windows))]+use super::{PNPM_SHIM_SH_NAME, SHIM_SH_NAME};++/// 生成的 shim 自带的可识别标记(首行注释)。用于区分"本应用生成的 shim"+/// 与"用户自行放置的同名文件"。读文件只读该标记行,避免误删用户自有文件。+const GENERATED_MARKER: &str = "DeepSeek Harness Desktop - ";++/// 目标路径已存在且不是本应用生成的 shim(即用户手动放置的 `dsh`/`pnpm`)。+///+/// 此时绝不覆盖,保留用户文件,避免"安装后清空了之前手动安装的工具"。+fn is_foreign_file(path: &Path) -> bool {+ !is_generated_shim(path)+}++/// 路径是否为悬空符号链接(链接本身存在,但指向的目标不存在)。+///+/// 官方 dsh 安装器会在 `~/.local/bin/dsh -> ~/.dsh/source/current/bin/dsh` 留下+/// 符号链接;当 `current` 指向的目录被移动/删除后链接即悬空。此时+/// `Path::exists()` 跟随链接返回 `false`,但直接 `fs::write` 会沿链接打开目标+/// 并在其父目录缺失时报 `No such file or directory (os error 2)`——必须先把+/// 已失效的链接本身移除,才能按"文件不存在"正常写入。+fn is_dangling_symlink(path: &Path) -> bool {+ match path.symlink_metadata() {+ Ok(meta) => meta.file_type().is_symlink() && !path.exists(),+ Err(_) => false,+ }+}++/// 判断路径是否为本应用生成的 shim(内容含生成标记)。+///+/// 用于在本地 dsh 探测中区分"本应用 shim"与"用户自行放置的同名文件":+/// 前者应被排除(它转发到捆绑 dsh,不构成用户本地核心),后者应被识别。+pub fn is_generated_shim(path: &Path) -> bool {+ match std::fs::read_to_string(path) {+ Ok(content) => content.contains(GENERATED_MARKER),+ Err(_) => false,+ }+}++/// 写入单个 shim 文件,处理目标已存在时的三种情形:+///+/// 1. 悬空符号链接(用户/官方安装器残留、目标已失效)→ 移除链接后正常写入;+/// 2. 已存在且非本应用生成(用户手动放置的 `dsh`/`pnpm`)→ 跳过,保留用户文件;+/// 3. 其余(不存在,或本应用生成的 shim)→ 直接写入/覆盖。+fn write_shim_file(target: &Path, content: &str) -> Result<(), String> {+ if is_dangling_symlink(target) {+ log::warn!(+ "Removing dangling symlink {:?} before writing shim (its target is gone)",+ target+ );+ fs::remove_file(target)+ .map_err(|e| format!("remove dangling symlink {} failed: {e}", target.display()))?;+ }+ if target.exists() && is_foreign_file(target) {+ log::warn!(+ "Skipping shim write to {:?}: an existing user file is preserved",+ target+ );+ return Ok(());+ }+ fs::write(target, content).map_err(|e| format!("write {} failed: {e}", target.display()))+}++/// 主 `dsh` shim 路径下是否保留了用户自行安装的同名文件(用于状态展示)。+pub fn user_dsh_preserved(bin_dir: &Path) -> bool {+ let path = {+ #[cfg(windows)]+ {+ bin_dir.join(SHIM_CMD_NAME)+ }+ #[cfg(not(windows))]+ {+ bin_dir.join(SHIM_SH_NAME)+ }+ };+ path.is_file() && is_foreign_file(&path)+}++/// 将 shim 文件写入 bin 目录;目标已存在但非本应用生成的同名文件时跳过(保留)。+/// 目标为悬空符号链接时先移除链接再写入(链接目标已失效,保留只会让写入+/// 报 ENOENT)。+///+/// 覆盖式仅针对本应用生成的 shim(自愈时内容与当前安装一致);用户手动放置的+/// 同名 `dsh`/`pnpm` 一律保留不动,避免覆盖用户自己的安装与配置。+pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String> {+ let app_dir = config::get_base_dir(app_handle);+ fs::create_dir_all(bin_dir).map_err(|e| format!("create bin dir failed: {e}"))?;++ // 写入单个 shim:若目标已存在且非本应用生成,则跳过不覆盖(保留用户文件)。+ macro_rules! write_if_ours {+ ($path:expr, $content:expr) => {{+ let target = bin_dir.join($path);+ write_shim_file(&target, &$content)?;+ target+ }};+ }++ // dsh shim 会在内容里烘焙 $DSH_HOME(生产为 ~/.dsh、开发为 ~/.dsh.dev)。+ // 开发构建禁止改写用户共享的 dsh shim——改写会让终端 `dsh` 指向开发数据+ // 目录,并覆盖生产的命令行集成;生产版生成的 dsh shim 原样保留。+ #[cfg(not(debug_assertions))]+ {+ let dsh_home = config::get_dsh_data_path(app_handle);+ #[cfg(windows)]+ {+ write_if_ours!(SHIM_CMD_NAME, build_cmd_shim(&app_dir, &dsh_home));+ write_if_ours!(SHIM_PS1_NAME, build_ps1_shim(&app_dir, &dsh_home));+ }+ #[cfg(not(windows))]+ {+ write_if_ours!(SHIM_SH_NAME, build_sh_shim(&app_dir, &dsh_home));+ }+ }+ #[cfg(debug_assertions)]+ log::debug!("debug build: skip dsh shim write (shared user state kept for release)");++ // pnpm shim 不烘焙 $DSH_HOME(仅绑定 bundle 目录与“用户 pnpm 优先”逻辑),+ // 内容与生产完全一致,开发构建也可写入——dsh plugin 子进程经 PATH 解析+ // pnpm 依赖它,写它不污染任何共享数据。+ #[cfg(windows)]+ {+ write_if_ours!(PNPM_SHIM_CMD_NAME, build_pnpm_cmd_shim(&app_dir));+ write_if_ours!(PNPM_SHIM_PS1_NAME, build_pnpm_ps1_shim(&app_dir));+ }+ #[cfg(not(windows))]+ {+ write_if_ours!(PNPM_SHIM_SH_NAME, build_pnpm_sh_shim(&app_dir));+ // 仅对本应用生成/覆盖过的 shim 设置可执行位;保留的用户文件不动+ let chmod_names: &[&str] = if cfg!(debug_assertions) {+ &[PNPM_SHIM_SH_NAME]+ } else {+ &[SHIM_SH_NAME, PNPM_SHIM_SH_NAME]+ };+ for name in chmod_names {+ let path = bin_dir.join(name);+ if path.is_file() && !is_foreign_file(&path) {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(&path, fs::Permissions::from_mode(0o755))+ .map_err(|e| format!("chmod shim failed: {e}"))?;+ }+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::super::test_util::{sample_app_dir, sample_dsh_home};+ use super::*;++ #[test]+ fn foreign_file_detection() {+ let dir = std::env::temp_dir().join(format!("dsh-shim-test-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();++ // 用户手动放置的 dsh 脚本 -> 视为 foreign,不应被覆盖+ let user_dsh = dir.join(if cfg!(windows) { "dsh.cmd" } else { "dsh" });+ std::fs::write(&user_dsh, "#!/bin/sh\necho my real dsh\n").unwrap();+ assert!(+ is_foreign_file(&user_dsh),+ "user file must be treated as foreign"+ );++ // 本应用生成的 shim -> 不是 foreign,可覆盖+ #[cfg(not(windows))]+ let generated = build_sh_shim(&sample_app_dir(), &sample_dsh_home());+ #[cfg(windows)]+ let generated = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());+ std::fs::write(&user_dsh, generated).unwrap();+ assert!(+ !is_foreign_file(&user_dsh),+ "generated shim must not be foreign"+ );++ let _ = std::fs::remove_dir_all(&dir);+ }++ // ------------------------------------------------------------------+ // write_shim_file 目标文件处理(悬空符号链接 / 用户文件保留 / 生成文件覆盖)+ // ------------------------------------------------------------------++ /// 独立的临时目录,避免测试间互相干扰+ fn temp_dir(tag: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "dsh-shim-write-{tag}-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ /// 悬空符号链接(官方 dsh 安装器残留 `~/.local/bin/dsh -> ~/.dsh/source/current/bin/dsh`+ /// 且目标已消失)时:先移除失效链接,再正常写入生成 shim——修复原报错+ /// `write ... failed: No such file or directory (os error 2)`+ #[test]+ #[cfg(unix)]+ fn write_shim_file_removes_dangling_symlink() {+ use std::os::unix::fs::symlink;++ let dir = temp_dir("dangling");+ let target = dir.join("dsh");+ symlink(dir.join("missing/source/current/bin/dsh"), &target).unwrap();+ assert!(is_dangling_symlink(&target));++ write_shim_file(&target, "#!/bin/sh\ngenerated shim\n").unwrap();++ assert_eq!(+ std::fs::read_to_string(&target).unwrap(),+ "#!/bin/sh\ngenerated shim\n"+ );+ assert!(+ !std::fs::symlink_metadata(&target)+ .unwrap()+ .file_type()+ .is_symlink(),+ "dangling symlink must be replaced by a regular file"+ );+ assert!(!is_dangling_symlink(&target));+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// 指向真实用户 dsh 的符号链接(目标仍存在)→ 视为用户文件,保留不动+ #[test]+ #[cfg(unix)]+ fn write_shim_file_preserves_valid_user_symlink() {+ use std::os::unix::fs::symlink;++ let dir = temp_dir("userlink");+ let real = dir.join("real-dsh");+ std::fs::write(&real, "#!/bin/sh\necho my real dsh\n").unwrap();+ let target = dir.join("dsh");+ symlink(&real, &target).unwrap();++ write_shim_file(&target, "#!/bin/sh\ngenerated shim\n").unwrap();++ assert!(+ std::fs::symlink_metadata(&target)+ .unwrap()+ .file_type()+ .is_symlink(),+ "valid user symlink must be preserved"+ );+ assert_eq!(+ std::fs::read_to_string(&real).unwrap(),+ "#!/bin/sh\necho my real dsh\n"+ );+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// 本应用生成的 shim → 覆盖自愈内容+ #[test]+ fn write_shim_file_overwrites_generated_shim() {+ let dir = temp_dir("overwrite");+ let target = dir.join("dsh");+ std::fs::write(+ &target,+ "#!/bin/sh\n# DeepSeek Harness Desktop - old shim\n",+ )+ .unwrap();++ write_shim_file(+ &target,+ "#!/bin/sh\n# DeepSeek Harness Desktop - new shim\n",+ )+ .unwrap();++ assert_eq!(+ std::fs::read_to_string(&target).unwrap(),+ "#!/bin/sh\n# DeepSeek Harness Desktop - new shim\n"+ );+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/src-tauri/src/service/download/core.rs b/src-tauri/src/service/download/core.rsindex 717d47ed..5cf00111 100644--- a/src-tauri/src/service/download/core.rs+++ b/src-tauri/src/service/download/core.rs@@ -1,10 +1,12 @@+//! 文件下载(断点续传 + 多源回退)、SHA-256 完整性校验与原子解压落盘。+//! GitHub 发行版元数据与更新判定见 [`super::github`]。+use futures_util::StreamExt;use sha2::{Digest, Sha256};use std::fs;use std::path::{Path, PathBuf};use std::time::Duration;-use crate::config;use crate::service::download::ProgressTracker;use tauri::Runtime;@@ -554,495 +556,6 @@ pub async fn ensure_extract<'a, R: Runtime>(Ok(())}-/// GitHub API 地址(未认证限流 60 次/小时/IP,仅供每次启动检查一次)-const DSH_PKG_GITHUB_API: &str = "https://api.github.com/repos/dsh-tauri-desk/deepseek-harness-pkg";-/// pkg 仓库 HTML 来源;`releases.atom` 走 github.com 而非 api.github.com,不受未认证限流约束。-const DSH_PKG_REPO: &str = "https://github.com/dsh-tauri-desk/deepseek-harness-pkg";--/// 最新 Harness 发行版信息(版本 tag + 对应 commit hash)-#[derive(Debug, Clone, serde::Serialize)]-pub struct LatestDshPkg {- pub tag: String,- pub commit: String,- pub asset_url: String,- /// 可信 SHA-256 摘要。为 `None` 表示 GitHub API 限流/不可用未能取得可信摘要,- /// 此时该信息**仅可作更新提示**(tag/commit 仍有效),不可用于自动重装——- /// 重装路径会因完整性校验缺失而中止(沿用 DSH_INTEGRITY_UNAVAILABLE 安全设计)。- pub digest: Option<String>,-}--/// 构造带 User-Agent 与超时的 GitHub 请求客户端。-fn github_client() -> Result<reqwest::Client, String> {- reqwest::Client::builder()- .user_agent("deepseek-harness-desktop")- .timeout(std::time::Duration::from_secs(5))- .build()- .map_err(|e| format!("Failed to create HTTP client: {}", e))-}--/// 访问 api.github.com 的 GET 请求(所有 API 调用统一走这里)。-///-/// 带 GitHub 未认证限流(403)冷却:冷却期内直接返回 Err(由调用方走兜底来源),-/// 命中 403 时记录冷却开始。返回的 `reqwest::Response` 已通过 `error_for_status`,-/// 403 已被拦截并标记冷却,不会作为普通错误继续向下传输。-async fn github_api_get(client: &reqwest::Client, url: &str) -> Result<reqwest::Response, String> {- if crate::service::download::github_api::rate_limited() {- return Err("GitHub API rate limited (cached, using fallback sources)".to_string());- }- let res = client.get(url).send().await.map_err(|e| e.to_string())?;- if res.status() == reqwest::StatusCode::FORBIDDEN {- crate::service::download::github_api::mark_rate_limited();- return Err(format!("GitHub API rate limited: HTTP {}", res.status()));- }- res.error_for_status().map_err(|e| e.to_string())-}--/// 拉取最新 release 的 JSON(含 tag、资产、摘要)。-async fn fetch_releases_latest(client: &reqwest::Client) -> Result<serde_json::Value, String> {- github_api_get(client, &format!("{DSH_PKG_GITHUB_API}/releases/latest"))- .await- .map_err(|e| format!("Latest release request failed: {e}"))?- .json()- .await- .map_err(|e| format!("Failed to parse latest release response: {e}"))-}--/// 通过 commits 端点把 release tag 解析为完整 commit hash。-async fn fetch_tag_commit(client: &reqwest::Client, tag: &str) -> Result<String, String> {- let commit: serde_json::Value =- github_api_get(client, &format!("{DSH_PKG_GITHUB_API}/commits/{tag}"))- .await- .map_err(|e| format!("Release commit request failed: {e}"))?- .json()- .await- .map_err(|e| format!("Failed to parse release commit response: {e}"))?;- commit- .get("sha")- .and_then(|v| v.as_str())- .map(|s| s.to_string())- .ok_or_else(|| "Missing sha in release commit response".to_string())-}--/// 从 tag 内嵌的 build-id 提取 commit 标识:`dsh-0.1.0-rc.8-32331963388` → `32331963388`。-///-/// 当 `/commits/{tag}` 因 api.github.com 限流/网络失败时,用 build-id 兜底作为 commit,-/// 保证「版本升级」判定不因这一次要调用而整体中断(issue:rc.8 发布后无更新提示)。-fn commit_fallback_from_tag(tag: &str) -> String {- tag.rsplit('-').next().unwrap_or(tag).to_string()-}--/// 从 releases.atom(github.com,非 api.github.com)解析最新 release tag。-///-/// 用作 API 限流/不可用时的兜底来源,仅在 API 完全不可达时调用。-async fn fetch_latest_dsh_tag_from_atom() -> Result<String, String> {- let client = github_client()?;- let body = client- .get(format!("{DSH_PKG_REPO}/releases.atom"))- .send()- .await- .map_err(|e| format!("DSH_ATOM: {e}"))?- .error_for_status()- .map_err(|e| format!("DSH_ATOM: {e}"))?- .text()- .await- .map_err(|e| format!("DSH_ATOM: {e}"))?;- // 取第一条 <entry> 作为最新 release,从中提取 releases/tag/<TAG>- let entry = body- .find("<entry>")- .and_then(|p| body[p..].find("</entry>").map(|e| &body[p..p + e]))- .unwrap_or(&body);- entry- .split("releases/tag/")- .nth(1)- .and_then(|s| s.split('"').next())- .filter(|t| !t.is_empty())- .map(|t| t.to_string())- .ok_or_else(|| "DSH_ATOM: missing tag in atom feed".to_string())-}--/// 从 expanded_assets HTML 片段中解析指定资产文件名后的 `sha256:<64hex>` 摘要。-///-/// 纯函数,便于对真实页面片段做离线单元测试;解析失败返回 `None`。-fn parse_digest_from_expanded_assets(body: &str, expected_name: &str) -> Option<String> {- let pos = body.find(expected_name)?;- // 4096 字节窗口的终点回退到 UTF-8 字符边界,避免切片落在多字节字符中间 panic- let mut end = (pos + 4096).min(body.len());- while end > pos && !body.is_char_boundary(end) {- end -= 1;- }- let window = &body[pos..end];- const START: &str = "sha256:";- let hash_start = window.find(START)?;- let hash = &window[hash_start + START.len()..];- let hex_end = hash- .find(|c: char| !c.is_ascii_hexdigit())- .unwrap_or(hash.len());- if hex_end != 64 {- return None;- }- Some(format!("sha256:{}", &hash[..64]))-}--/// 从 release 的 expanded_assets HTML(github.com,非 api.github.com,不受未认证-/// 限流 403 约束)解析指定资产的 SHA-256 摘要。-///-/// GitHub release 资产的 `digest` 字段默认只由 api.github.com 的 JSON 返回,一旦-/// API 被限流就拿不到可信摘要,更新会因完整性校验缺失被 `DSH_INTEGRITY_UNAVAILABLE`-/// 卡死。但 GitHub 的 `expanded_assets` 页面片段同样呈现作者填写的 `sha256:<hex>`-/// 摘要(发行版页面资产区展开时的 HTML),且走 github.com 普通请求、不受 API 配额-/// 限制——以它作为 API 限流时的非限流兜底来源,保证完整性校验不因 403 而失效。-async fn fetch_dsh_digest_from_expanded_assets(- client: &reqwest::Client,- tag: &str,- expected_name: &str,-) -> Result<Option<String>, String> {- let body = client- .get(format!("{DSH_PKG_REPO}/releases/expanded_assets/{tag}"))- .send()- .await- .map_err(|e| format!("DSH_EXPANDED: {e}"))?- .error_for_status()- .map_err(|e| format!("DSH_EXPANDED: {e}"))?- .text()- .await- .map_err(|e| format!("DSH_EXPANDED: {e}"))?;- Ok(parse_digest_from_expanded_assets(&body, expected_name))-}--/// 查询 GitHub 上最新 Harness 发行版信息。-///-/// 优先走 api.github.com(`/releases/latest` + `/commits/{tag}`),拿到可用的 tag、-/// 资产地址与可信 SHA-256 摘要。API 限流/网络失败时**不整体中断**:-/// - tag 兜底用 releases.atom(github.com,不受未认证限流约束);-/// - commit 兜底用 tag 内嵌 build-id;-/// - 资产 URL 由平台确定性推导;-/// - digest 置 `None`(仅可提示、不可自动重装,重装时重取摘要或安全中止)。-///-/// 修复前:api.github.com 一限流 `fetch_latest_dsh_pkg_info` 直接返回 Err,-/// `check_dsh_update` 静默跳过,导致上游 rc.8 发布后桌面端迟迟不出现更新提示。-pub async fn fetch_latest_dsh_pkg_info() -> Result<LatestDshPkg, String> {- let client = github_client()?;- let expected_name = config::get_dsh_download_url()?- .rsplit('/')- .next()- .ok_or_else(|| "Missing DSH asset filename".to_string())?- .to_string();-- // 1. 首选 GitHub API 拉最新 release(含 tag + 资产 + 可信摘要)- let api_release = match fetch_releases_latest(&client).await {- Ok(release) => Some(release),- Err(e) => {- // 限流冷却期内不重复打 403 警告(进入冷却时已提示一次),静默走兜底- if crate::service::download::github_api::rate_limited() {- log::debug!(- "GitHub API latest release unavailable (rate-limited), using fallback sources: {e}"- );- } else {- log::warn!(- "GitHub API latest release unavailable ({}), falling back to atom feed",- e- );- }- None- }- };-- // 2. tag:优先 API,失败则从 releases.atom 兜底- let tag_name = match &api_release {- Some(release) => release- .get("tag_name")- .and_then(|v| v.as_str())- .ok_or_else(|| "Missing tag_name in latest release response".to_string())?- .to_string(),- None => fetch_latest_dsh_tag_from_atom().await?,- };-- // 3. commit:优先 API /commits/{tag},失败用 tag 内嵌 build-id 兜底- let commit = match fetch_tag_commit(&client, &tag_name).await {- Ok(sha) => sha,- Err(e) => {- if crate::service::download::github_api::rate_limited() {- log::debug!("GitHub API commit resolution rate-limited, using build-id fallback");- } else {- log::warn!(- "Failed to resolve commit for tag {} ({}), using build-id fallback",- tag_name,- e- );- }- commit_fallback_from_tag(&tag_name)- }- };-- // 4. 资产 URL 与摘要:仅 API 可达时资产/摘要可信;否则 URL 平台确定性回退、digest=None- let (asset_url, mut digest) = match api_release.as_ref() {- Some(release) => {- let asset = release- .get("assets")- .and_then(|value| value.as_array())- .and_then(|assets| {- assets.iter().find(|asset| {- asset.get("name").and_then(|value| value.as_str())- == Some(expected_name.as_str())- })- });- let asset_url = asset- .and_then(|a| a.get("browser_download_url").and_then(|v| v.as_str()))- .map(|u| u.to_string())- .unwrap_or_else(|| config::get_dsh_download_url().unwrap_or_default());- let digest = asset- .and_then(|a| a.get("digest").and_then(|v| v.as_str()))- .filter(|v| v.starts_with("sha256:"))- .map(|v| v.to_string());- (asset_url, digest)- }- None => (config::get_dsh_download_url()?, None),- };-- // 4b. API 限流/不可用导致取不到可信摘要时,改从 expanded_assets HTML- // (github.com,非 api.github.com,不受 403 限流)解析作者填写的 sha256,- // 保证完整性校验不因 api.github.com 限流而失效、更新不被卡死。- if digest.is_none() {- match fetch_dsh_digest_from_expanded_assets(&client, &tag_name, &expected_name).await {- Ok(Some(d)) => {- log::info!(- "Trusted digest unavailable from GitHub API, recovered from release HTML for {}",- expected_name- );- digest = Some(d);- }- Ok(None) => {- log::warn!(- "No digest found in release HTML for {} (tag {})",- expected_name,- tag_name- );- }- Err(e) => {- log::warn!("Failed to fetch digest from release HTML: {}", e);- }- }- }-- Ok(LatestDshPkg {- tag: tag_name,- commit,- asset_url,- digest,- })-}--/// 拉取指定 tag 的发行版信息(资产 URL + 可信摘要),供核心面板按版本下载。-///-/// 与 `fetch_latest_dsh_pkg_info` 同源策略:优先走 api.github.com-/// (`/releases/tags/{tag}` 拿资产与摘要),失败时资产 URL 平台确定性推导-/// (latest 地址的 tag 位替换)、摘要走 expanded_assets HTML;digest 仍取不到-/// 则置 `None`,调用方据此安全中止下载(沿用 DSH_INTEGRITY_UNAVAILABLE 设计)。-pub async fn fetch_dsh_pkg_asset(tag: &str) -> Result<LatestDshPkg, String> {- let client = github_client()?;- let expected_name = config::get_dsh_download_url()?- .rsplit('/')- .next()- .ok_or_else(|| "Missing DSH asset filename".to_string())?- .to_string();-- // 1. 优先 API 拉该 tag 的 release(含资产 + 可信摘要)- let release = github_api_get(- &client,- &format!("{DSH_PKG_GITHUB_API}/releases/tags/{tag}"),- )- .await- .map_err(|e| format!("Release {tag} request failed: {e}"))?;- let json: serde_json::Value = release- .json()- .await- .map_err(|e| format!("Failed to parse release {tag} response: {e}"))?;-- let asset = json- .get("assets")- .and_then(|value| value.as_array())- .and_then(|assets| {- assets.iter().find(|asset| {- asset.get("name").and_then(|value| value.as_str()) == Some(expected_name.as_str())- })- });- let asset_url = asset- .and_then(|a| a.get("browser_download_url").and_then(|v| v.as_str()))- .map(|u| u.to_string())- .unwrap_or_else(|| config::get_dsh_download_url_for_tag(tag).unwrap_or_default());- let mut digest = asset- .and_then(|a| a.get("digest").and_then(|v| v.as_str()))- .filter(|v| v.starts_with("sha256:"))- .map(|v| v.to_string());-- // 2. 摘要兜底:expanded_assets HTML(github.com,非 api.github.com)- if digest.is_none() {- match fetch_dsh_digest_from_expanded_assets(&client, tag, &expected_name).await {- Ok(Some(d)) => {- log::info!(- "Trusted digest unavailable from GitHub API, recovered from release HTML for {}",- expected_name- );- digest = Some(d);- }- Ok(None) => {- log::warn!(- "No digest found in release HTML for {} (tag {})",- expected_name,- tag- );- }- Err(e) => {- log::warn!("Failed to fetch digest from release HTML: {}", e);- }- }- }-- Ok(LatestDshPkg {- tag: tag.to_string(),- commit: commit_fallback_from_tag(tag),- asset_url,- digest,- })-}--/// 从 release tag 中解析版本号:`dsh-0.1.0-rc.7-32054485373` → `0.1.0-rc.7`。-///-/// tag 约定为 `dsh-<version>-<commit 后缀>`;格式不符时返回 `None`,-/// 调用方据此回退到仅 commit 比对的旧行为,避免误判。-pub fn parse_version_from_tag(tag: &str) -> Option<String> {- let version = tag.strip_prefix("dsh-")?.rsplit_once('-')?.0;- (!version.is_empty()).then(|| version.to_string())-}--/// 安装记录(`dsh_pkg_commit` / `dsh_pkg_tag`)是否对应「最新 release 的同一发布」。-///-/// commit 存在两种合法形态:完整 git SHA(api.github.com 正常时解析,如-/// `1eed6dd6c078…`)与 tag 内嵌 build-id(api.github.com 限流时兜底,见-/// [`commit_fallback_from_tag`],如 `32485170079`)。同一 tag 的两种形态互不-/// 相等,而安装记录写成哪一种取决于安装当时 API 是否可用:限流期安装会把-/// build-id 写进记录,API 恢复后的检查却解析出完整 SHA。若只按字符串相等比对,-/// API 状态在两次启动之间翻转(限流 ↔ 恢复)会让同一 release 永远比对不上,-/// `resolve_update` 把同版本误判为「同版本热修」→ 每次启动都提示更新-/// (issue #92)。因此需归一化:记录 tag 与最新 tag 相同(同一次发布,任何-/// 形态的 commit 都来自该 tag),或记录 commit 与 release 的任一合法标识一致。-pub fn record_matches_latest_release(- record_commit: Option<&str>,- record_tag: Option<&str>,- latest: &LatestDshPkg,-) -> bool {- record_tag == Some(latest.tag.as_str())- || record_commit.is_some_and(|rc| {- rc == latest.commit.as_str() || rc == commit_fallback_from_tag(&latest.tag)- })-}--/// 更新判定结果-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum UpdateCheck {- /// 无更新- UpToDate,- /// 无更新,但本地记录滞后于实际安装文件,需要修正记录- HealUpToDate,- /// 有更新- UpdateAvailable,-}--/// 结合本地记录与实际安装文件判定是否有新版 Harness 可用。-///-/// 本地记录(release commit + tag)由安装流程写入;但当安装文件被外围途径-/// 更新、或安装时 GitHub API 失败未落盘,记录会滞后于文件,造成每次都误报-/// 更新。这里以磁盘上实际的 `@deepseek-ai/dsh` 版本为准核对:-/// - 最新 release 版本号与已装版本不同 → 有更新(不论 commit);-/// - 版本号相同且记录对应同一 release(commit 任一形态匹配,或记录 tag 相同)→ 无更新;-/// - 版本号相同但记录是同一版本的另一发布(不同 build-id 的 tag)→ 同版本热修 → 有更新;-/// 记录 tag 版本更旧(或记录无 tag,经 `legacy_tags` 反查)→ 记录滞后 → 修正记录。-///-/// 注意必须先比版本、再比 commit:dsh 仓库的 rc 发布会重打同一 git commit,-/// 因此「最新 release 的 commit 等于已装记录的 commit」并不代表没有更新,-/// 只有 tag 里的版本号才能正确区分(如 rc.8 之于 rc.7)。-///-/// `legacy_tags` 是 pkg 仓库的 tags 列表(tag, commit),仅用于反查历史安装-/// 记录的版本;反查不到时以实际文件为准(视为记录滞后)。-pub fn resolve_update(- record_commit: Option<&str>,- record_tag: Option<&str>,- installed_version: Option<&str>,- latest: &LatestDshPkg,- legacy_tags: &[(String, String)],-) -> UpdateCheck {- let (Some(installed), Some(latest_version)) =- (installed_version, parse_version_from_tag(&latest.tag))- else {- // 版本信息不可解析时回退旧行为:记录不一致即视为有更新- return if record_matches_latest_release(record_commit, record_tag, latest) {- UpdateCheck::UpToDate- } else {- UpdateCheck::UpdateAvailable- };- };-- // 先按“最新 release 的版本号”判定:与已装版本不同 → 有更新。- // 不能先看 commit 相等就跳过:dsh 仓库的 rc 发布可能重打同一 git commit- // (build-id 不同但 underlying commit 相同),此时 commit 不是可分辨信号,- // 只有 tag 里的版本号才能正确识别 rc.8 之于 rc.7 是更新。- if installed != latest_version {- return UpdateCheck::UpdateAvailable;- }- // 版本相同 → 确认是否「同一发布」再判免打扰:记录与最新 release 对应- // (见 [`record_matches_latest_release`])即文件已是最新,无更新。- if record_matches_latest_release(record_commit, record_tag, latest) {- return UpdateCheck::UpToDate;- }- // 文件已经是“最新版本”,此时需要甄别记录是否滞后- match record_tag.and_then(parse_version_from_tag) {- Some(record_version) if record_version < latest_version => UpdateCheck::HealUpToDate,- Some(_) => UpdateCheck::UpdateAvailable,- None => match legacy_tags- .iter()- .find(|(_, commit)| Some(commit.as_str()) == record_commit)- {- Some((tag, _)) => match parse_version_from_tag(tag) {- Some(record_version) if record_version < latest_version => {- UpdateCheck::HealUpToDate- }- // 反查到的版本与最新版本相同(或解析失败)→ 视为同版本热修- _ => UpdateCheck::UpdateAvailable,- },- // 无法考证记录对应的版本 → 以实际安装文件为准,修正记录- None => UpdateCheck::HealUpToDate,- },- }-}--/// 拉取 pkg 仓库的 release tag 列表(tag, commit),用于反查历史记录对应的版本。-///-/// 仅在更新判定需要反查“无 tag 的老记录”时调用,失败时由调用方回退到-/// “以实际文件为准”的保守分支。-pub async fn fetch_dsh_pkg_tags() -> Result<Vec<(String, String)>, String> {- let client = github_client()?;- let tags: serde_json::Value = github_api_get(- &client,- &format!("{}/tags?per_page=100", DSH_PKG_GITHUB_API),- )- .await- .map_err(|e| format!("Release tags request failed: {e}"))?- .json()- .await- .map_err(|e| format!("Failed to parse release tags response: {e}"))?;-- Ok(tags- .as_array()- .into_iter()- .flatten()- .filter_map(|entry| {- let name = entry.get("name")?.as_str()?.to_string();- let sha = entry.get("commit")?.get("sha")?.as_str()?.to_string();- Some((name, sha))- })- .collect())-}-#[cfg(test)]mod tests {use super::*;@@ -1132,264 +645,4 @@ mod tests {assert!(!backup.exists());fs::remove_dir_all(root).ok();}-- fn latest(tag: &str, commit: &str) -> LatestDshPkg {- LatestDshPkg {- tag: tag.to_string(),- commit: commit.to_string(),- asset_url: "https://example.invalid/dsh.zip".to_string(),- digest: Some(format!("sha256:{}", "0".repeat(64))),- }- }-- #[test]- fn commit_fallback_extracts_build_id_from_tag() {- assert_eq!(- commit_fallback_from_tag("dsh-0.1.0-rc.8-32331963388"),- "32331963388"- );- // 无 build-id 的 tag 兜底取最后一段,仍为非空稳定标识,避免空 commit 破坏比对- assert_eq!(commit_fallback_from_tag("dsh-0.2.0"), "0.2.0");- }-- #[test]- fn parses_digest_from_expanded_assets_html() {- // 模拟 expanded_assets 片段:资产文件名之后紧跟作者填写的 sha256:<64hex>。- // 来自真实 rc.8 页面:windows 资产摘要为 4d541676...- let html = concat!(- "…/deepseek-harness-pkg-windows.zip…<span>sha256:4d5416766eb4a66e81b83532abeea64de7e7e2e0bac69a4f0c0508e1d91936c0</span>",- );- let got = parse_digest_from_expanded_assets(html, "deepseek-harness-pkg-windows.zip");- assert_eq!(- got.as_deref(),- Some("sha256:4d5416766eb4a66e81b83532abeea64de7e7e2e0bac69a4f0c0508e1d91936c0")- );- // 文件名不存在 → None- assert_eq!(- parse_digest_from_expanded_assets(html, "deepseek-harness-pkg-linux.zip"),- None- );- // 摘要缺失 → None- assert_eq!(- parse_digest_from_expanded_assets(- "<p>no digest here</p>",- "deepseek-harness-pkg-windows.zip"- ),- None- );- }-- #[test]- fn parsed_digest_window_clamps_to_char_boundary() {- // 构造一个 body 使 `(pos + 4096)` 恰好落在多字节字符的中间字节:- // 旧实现 `&body[pos..pos + 4096]` 会在非字符边界切片而 panic,修复后回退到边界再解析。- let name = "deepseek-harness-pkg-windows.zip";- let digest = "4d5416766eb4a66e81b83532abeea64de7e7e2e0bac69a4f0c0508e1d91936c0";- let prefix = format!("{name}<span>sha256:{digest}</span>");- let mut body = prefix.clone();- // 补齐到字节 4094 处,放一个 3 字节汉字(占用 4094..4097),使索引 4096 落在其中间字节- let needed = 4094usize.saturating_sub(body.len());- body.push_str(&"a".repeat(needed));- body.push('中');- body.push_str(&"a".repeat(16));- // 确保总长 > 4096,维持 (pos + 4096) 处于非边界字节(否则不会触发回退分支)- assert!(body.len() > 4096);- let got = parse_digest_from_expanded_assets(&body, name);- let expected = format!("sha256:{digest}");- assert_eq!(got.as_deref(), Some(expected.as_str()));- }-- #[test]- fn parse_version_from_tag_formats() {- assert_eq!(- parse_version_from_tag("dsh-0.1.0-rc.7-32054485373").as_deref(),- Some("0.1.0-rc.7")- );- assert_eq!(- parse_version_from_tag("dsh-0.1.0-rc.6-31773193667").as_deref(),- Some("0.1.0-rc.6")- );- assert_eq!(parse_version_from_tag("dsh-0.2.0"), None);- assert_eq!(parse_version_from_tag("0.1.0-rc.7-abc"), None);- assert_eq!(parse_version_from_tag(""), None);- }-- #[test]- fn resolve_matching_commit_is_up_to_date() {- let latest = latest(- "dsh-0.1.0-rc.7-32054485373",- "6c659bb2636b3ad396a204c4c6ff110276fa3a09",- );- let decision = resolve_update(- Some("6c659bb2636b3ad396a204c4c6ff110276fa3a09"),- Some("dsh-0.1.0-rc.7-32054485373"),- Some("0.1.0-rc.7"),- &latest,- &[],- );- assert_eq!(decision, UpdateCheck::UpToDate);- }-- #[test]- fn resolve_build_id_record_vs_real_sha_latest_is_up_to_date() {- // issue #92 现场:限流期安装把 build-id 写进记录,API 恢复后的检查解析出- // 完整 SHA——同一 release(dsh-0.1.1-rc.2-32485170079)的两种标识互不相等,- // 必须归一化判定为无更新,而不是每次启动都误报「同版本热修」。- let latest = latest(- "dsh-0.1.1-rc.2-32485170079",- "1eed6dd6c0780000000000000000000000000000",- );- let decision = resolve_update(- Some("32485170079"), // 记录 commit:限流期写入的 build-id- Some("dsh-0.1.1-rc.2-32485170079"),- Some("0.1.1-rc.2"),- &latest,- &[],- );- assert_eq!(decision, UpdateCheck::UpToDate);- }-- #[test]- fn resolve_real_sha_record_vs_build_id_latest_is_up_to_date() {- // 反向翻转:记录是完整 SHA,本次检查因 API 限流兜底出 build-id。- // record_tag 与 latest.tag 相同即同一发布,不得误报更新。- let latest = latest(- "dsh-0.1.1-rc.2-32485170079",- "32485170079", // 本次检查限流,commit 兜底为 build-id- );- let decision = resolve_update(- Some("1eed6dd6c0780000000000000000000000000000"), // 记录:完整 SHA- Some("dsh-0.1.1-rc.2-32485170079"),- Some("0.1.1-rc.2"),- &latest,- &[],- );- assert_eq!(decision, UpdateCheck::UpToDate);- }-- #[test]- fn resolve_different_installed_version_is_update() {- let latest = latest(- "dsh-0.1.0-rc.7-32054485373",- "6c659bb2636b3ad396a204c4c6ff110276fa3a09",- );- let decision = resolve_update(- Some("564019027fd9469991aef6e57bb0a96325491c4e"),- Some("dsh-0.1.0-rc.6-31773193667"),- Some("0.1.0-rc.6"),- &latest,- &[],- );- assert_eq!(decision, UpdateCheck::UpdateAvailable);- }-- #[test]- fn resolve_same_version_hotfix_is_update() {- // 记录正确(与文件一致),最新 release 是同版本热修:应提示更新- let latest = latest(- "dsh-0.1.0-rc.6-31773193667",- "564019027fd9469991aef6e57bb0a96325491c4e",- );- let decision = resolve_update(- Some("995e261e117617780dc50db16c70d445255978fd"),- Some("dsh-0.1.0-rc.6-31762761461"),- Some("0.1.0-rc.6"),- &latest,- &[],- );- assert_eq!(decision, UpdateCheck::UpdateAvailable);- }-- #[test]- fn resolve_stale_record_behind_files_heals() {- // 用户现场:记录停留在 rc.6,文件已是 rc.7 → 修正记录、免打扰- let latest = latest(- "dsh-0.1.0-rc.7-32054485373",- "6c659bb2636b3ad396a204c4c6ff110276fa3a09",- );- let decision = resolve_update(- Some("564019027fd9469991aef6e57bb0a96325491c4e"),- Some("dsh-0.1.0-rc.6-31773193667"),- Some("0.1.0-rc.7"),- &latest,- &[],- );- assert_eq!(decision, UpdateCheck::HealUpToDate);- }-- #[test]- fn resolve_legacy_record_without_tag_heals_via_tags_lookup() {- // 老记录没有 tag:反查 tags 列表发现记录版本低于文件版本 → 修正- let latest = latest(- "dsh-0.1.0-rc.7-32054485373",- "6c659bb2636b3ad396a204c4c6ff110276fa3a09",- );- let tags = vec![(- "dsh-0.1.0-rc.6-31773193667".to_string(),- "564019027fd9469991aef6e57bb0a96325491c4e".to_string(),- )];- let decision = resolve_update(- Some("564019027fd9469991aef6e57bb0a96325491c4e"),- None,- Some("0.1.0-rc.7"),- &latest,- &tags,- );- assert_eq!(decision, UpdateCheck::HealUpToDate);- }-- #[test]- fn resolve_legacy_same_version_still_updates() {- // 老记录无 tag 但反查为同版本热修:仍应提示- let latest = latest(- "dsh-0.1.0-rc.6-31773193667",- "564019027fd9469991aef6e57bb0a96325491c4e",- );- let tags = vec![(- "dsh-0.1.0-rc.6-31762761461".to_string(),- "995e261e117617780dc50db16c70d445255978fd".to_string(),- )];- let decision = resolve_update(- Some("995e261e117617780dc50db16c70d445255978fd"),- None,- Some("0.1.0-rc.6"),- &latest,- &tags,- );- assert_eq!(decision, UpdateCheck::UpdateAvailable);- }-- #[test]- fn resolve_without_version_metadata_falls_back_to_update() {- // 最新 tag 无法解析出版本时回退旧行为:记录不一致即提示- let latest = latest("0.1.0-rc.7", "6c659bb2636b3ad396a204c4c6ff110276fa3a09");- let decision = resolve_update(- Some("564019027fd9469991aef6e57bb0a96325491c4e"),- None,- Some("0.1.0-rc.7"),- &latest,- &[],- );- assert_eq!(decision, UpdateCheck::UpdateAvailable);- }-- #[test]- fn resolve_rc7_installed_rc8_released_is_update() {- // 用户现场(已实测真实网络):已装 rc.7,上游发布 rc.8。仓库 rc 发布会- // 重打同一 git commit(/commits/{tag} 解析出的 rc.8 commit 与 rc.7 完全相同- // 6c659bb...),因此 commit 相等不能当作“无更新”——版本号 rc.8 > rc.7- // 才是有更新。正是这个 commit 相等快路径导致更新提示被吞。- let latest = latest(- "dsh-0.1.0-rc.8-32331963388",- "6c659bb2636b3ad396a204c4c6ff110276fa3a09", // 与已装记录相同 commit- );- let decision = resolve_update(- Some("6c659bb2636b3ad396a204c4c6ff110276fa3a09"), // rc.7 记录- Some("dsh-0.1.0-rc.7-32054485373"),- Some("0.1.0-rc.7"),- &latest,- &[],- );- assert_eq!(decision, UpdateCheck::UpdateAvailable);- }}diff --git a/src-tauri/src/service/download/github.rs b/src-tauri/src/service/download/github.rsnew file mode 100644index 00000000..1ce0ef1a--- /dev/null+++ b/src-tauri/src/service/download/github.rs@@ -0,0 +1,762 @@+//! GitHub 发行版元数据:查询最新/指定 tag 的 Harness 发行信息(版本 tag、+//! commit、资产 URL 与可信 SHA-256 摘要),以及更新判定(`resolve_update`)。+//!+//! 所有访问 api.github.com 的调用统一经 `download::utils::github_api` 冷却器收敛;+//! API 限流/不可用时逐级兜底到 releases.atom / expanded_assets HTML /+//! tag 内嵌 build-id,保证更新提示与完整性校验不因 403 而失效。++use crate::config;++/// GitHub API 地址(未认证限流 60 次/小时/IP,仅供每次启动检查一次)+const DSH_PKG_GITHUB_API: &str = "https://api.github.com/repos/dsh-tauri-desk/deepseek-harness-pkg";+/// pkg 仓库 HTML 来源;`releases.atom` 走 github.com 而非 api.github.com,不受未认证限流约束。+const DSH_PKG_REPO: &str = "https://github.com/dsh-tauri-desk/deepseek-harness-pkg";++/// 最新 Harness 发行版信息(版本 tag + 对应 commit hash)+#[derive(Debug, Clone, serde::Serialize)]+pub struct LatestDshPkg {+ pub tag: String,+ pub commit: String,+ pub asset_url: String,+ /// 可信 SHA-256 摘要。为 `None` 表示 GitHub API 限流/不可用未能取得可信摘要,+ /// 此时该信息**仅可作更新提示**(tag/commit 仍有效),不可用于自动重装——+ /// 重装路径会因完整性校验缺失而中止(沿用 DSH_INTEGRITY_UNAVAILABLE 安全设计)。+ pub digest: Option<String>,+}++/// 构造带 User-Agent 与超时的 GitHub 请求客户端。+fn github_client() -> Result<reqwest::Client, String> {+ reqwest::Client::builder()+ .user_agent("deepseek-harness-desktop")+ .timeout(std::time::Duration::from_secs(5))+ .build()+ .map_err(|e| format!("Failed to create HTTP client: {}", e))+}++/// 访问 api.github.com 的 GET 请求(所有 API 调用统一走这里)。+///+/// 带 GitHub 未认证限流(403)冷却:冷却期内直接返回 Err(由调用方走兜底来源),+/// 命中 403 时记录冷却开始。返回的 `reqwest::Response` 已通过 `error_for_status`,+/// 403 已被拦截并标记冷却,不会作为普通错误继续向下传输。+async fn github_api_get(client: &reqwest::Client, url: &str) -> Result<reqwest::Response, String> {+ if crate::service::download::github_api::rate_limited() {+ return Err("GitHub API rate limited (cached, using fallback sources)".to_string());+ }+ let res = client.get(url).send().await.map_err(|e| e.to_string())?;+ if res.status() == reqwest::StatusCode::FORBIDDEN {+ crate::service::download::github_api::mark_rate_limited();+ return Err(format!("GitHub API rate limited: HTTP {}", res.status()));+ }+ res.error_for_status().map_err(|e| e.to_string())+}++/// 拉取最新 release 的 JSON(含 tag、资产、摘要)。+async fn fetch_releases_latest(client: &reqwest::Client) -> Result<serde_json::Value, String> {+ github_api_get(client, &format!("{DSH_PKG_GITHUB_API}/releases/latest"))+ .await+ .map_err(|e| format!("Latest release request failed: {e}"))?+ .json()+ .await+ .map_err(|e| format!("Failed to parse latest release response: {e}"))+}++/// 通过 commits 端点把 release tag 解析为完整 commit hash。+async fn fetch_tag_commit(client: &reqwest::Client, tag: &str) -> Result<String, String> {+ let commit: serde_json::Value =+ github_api_get(client, &format!("{DSH_PKG_GITHUB_API}/commits/{tag}"))+ .await+ .map_err(|e| format!("Release commit request failed: {e}"))?+ .json()+ .await+ .map_err(|e| format!("Failed to parse release commit response: {e}"))?;+ commit+ .get("sha")+ .and_then(|v| v.as_str())+ .map(|s| s.to_string())+ .ok_or_else(|| "Missing sha in release commit response".to_string())+}++/// 从 tag 内嵌的 build-id 提取 commit 标识:`dsh-0.1.0-rc.8-32331963388` → `32331963388`。+///+/// 当 `/commits/{tag}` 因 api.github.com 限流/网络失败时,用 build-id 兜底作为 commit,+/// 保证「版本升级」判定不因这一次要调用而整体中断(issue:rc.8 发布后无更新提示)。+fn commit_fallback_from_tag(tag: &str) -> String {+ tag.rsplit('-').next().unwrap_or(tag).to_string()+}++/// 从 releases.atom(github.com,非 api.github.com)解析最新 release tag。+///+/// 用作 API 限流/不可用时的兜底来源,仅在 API 完全不可达时调用。+async fn fetch_latest_dsh_tag_from_atom() -> Result<String, String> {+ let client = github_client()?;+ let body = client+ .get(format!("{DSH_PKG_REPO}/releases.atom"))+ .send()+ .await+ .map_err(|e| format!("DSH_ATOM: {e}"))?+ .error_for_status()+ .map_err(|e| format!("DSH_ATOM: {e}"))?+ .text()+ .await+ .map_err(|e| format!("DSH_ATOM: {e}"))?;+ // 取第一条 <entry> 作为最新 release,从中提取 releases/tag/<TAG>+ let entry = body+ .find("<entry>")+ .and_then(|p| body[p..].find("</entry>").map(|e| &body[p..p + e]))+ .unwrap_or(&body);+ entry+ .split("releases/tag/")+ .nth(1)+ .and_then(|s| s.split('"').next())+ .filter(|t| !t.is_empty())+ .map(|t| t.to_string())+ .ok_or_else(|| "DSH_ATOM: missing tag in atom feed".to_string())+}++/// 从 expanded_assets HTML 片段中解析指定资产文件名后的 `sha256:<64hex>` 摘要。+///+/// 纯函数,便于对真实页面片段做离线单元测试;解析失败返回 `None`。+fn parse_digest_from_expanded_assets(body: &str, expected_name: &str) -> Option<String> {+ let pos = body.find(expected_name)?;+ // 4096 字节窗口的终点回退到 UTF-8 字符边界,避免切片落在多字节字符中间 panic+ let mut end = (pos + 4096).min(body.len());+ while end > pos && !body.is_char_boundary(end) {+ end -= 1;+ }+ let window = &body[pos..end];+ const START: &str = "sha256:";+ let hash_start = window.find(START)?;+ let hash = &window[hash_start + START.len()..];+ let hex_end = hash+ .find(|c: char| !c.is_ascii_hexdigit())+ .unwrap_or(hash.len());+ if hex_end != 64 {+ return None;+ }+ Some(format!("sha256:{}", &hash[..64]))+}++/// 从 release 的 expanded_assets HTML(github.com,非 api.github.com,不受未认证+/// 限流 403 约束)解析指定资产的 SHA-256 摘要。+///+/// GitHub release 资产的 `digest` 字段默认只由 api.github.com 的 JSON 返回,一旦+/// API 被限流就拿不到可信摘要,更新会因完整性校验缺失被 `DSH_INTEGRITY_UNAVAILABLE`+/// 卡死。但 GitHub 的 `expanded_assets` 页面片段同样呈现作者填写的 `sha256:<hex>`+/// 摘要(发行版页面资产区展开时的 HTML),且走 github.com 普通请求、不受 API 配额+/// 限制——以它作为 API 限流时的非限流兜底来源,保证完整性校验不因 403 而失效。+async fn fetch_dsh_digest_from_expanded_assets(+ client: &reqwest::Client,+ tag: &str,+ expected_name: &str,+) -> Result<Option<String>, String> {+ let body = client+ .get(format!("{DSH_PKG_REPO}/releases/expanded_assets/{tag}"))+ .send()+ .await+ .map_err(|e| format!("DSH_EXPANDED: {e}"))?+ .error_for_status()+ .map_err(|e| format!("DSH_EXPANDED: {e}"))?+ .text()+ .await+ .map_err(|e| format!("DSH_EXPANDED: {e}"))?;+ Ok(parse_digest_from_expanded_assets(&body, expected_name))+}++/// 查询 GitHub 上最新 Harness 发行版信息。+///+/// 优先走 api.github.com(`/releases/latest` + `/commits/{tag}`),拿到可用的 tag、+/// 资产地址与可信 SHA-256 摘要。API 限流/网络失败时**不整体中断**:+/// - tag 兜底用 releases.atom(github.com,不受未认证限流约束);+/// - commit 兜底用 tag 内嵌 build-id;+/// - 资产 URL 由平台确定性推导;+/// - digest 置 `None`(仅可提示、不可自动重装,重装时重取摘要或安全中止)。+///+/// 修复前:api.github.com 一限流 `fetch_latest_dsh_pkg_info` 直接返回 Err,+/// `check_dsh_update` 静默跳过,导致上游 rc.8 发布后桌面端迟迟不出现更新提示。+pub async fn fetch_latest_dsh_pkg_info() -> Result<LatestDshPkg, String> {+ let client = github_client()?;+ let expected_name = config::get_dsh_download_url()?+ .rsplit('/')+ .next()+ .ok_or_else(|| "Missing DSH asset filename".to_string())?+ .to_string();++ // 1. 首选 GitHub API 拉最新 release(含 tag + 资产 + 可信摘要)+ let api_release = match fetch_releases_latest(&client).await {+ Ok(release) => Some(release),+ Err(e) => {+ // 限流冷却期内不重复打 403 警告(进入冷却时已提示一次),静默走兜底+ if crate::service::download::github_api::rate_limited() {+ log::debug!(+ "GitHub API latest release unavailable (rate-limited), using fallback sources: {e}"+ );+ } else {+ log::warn!(+ "GitHub API latest release unavailable ({}), falling back to atom feed",+ e+ );+ }+ None+ }+ };++ // 2. tag:优先 API,失败则从 releases.atom 兜底+ let tag_name = match &api_release {+ Some(release) => release+ .get("tag_name")+ .and_then(|v| v.as_str())+ .ok_or_else(|| "Missing tag_name in latest release response".to_string())?+ .to_string(),+ None => fetch_latest_dsh_tag_from_atom().await?,+ };++ // 3. commit:优先 API /commits/{tag},失败用 tag 内嵌 build-id 兜底+ let commit = match fetch_tag_commit(&client, &tag_name).await {+ Ok(sha) => sha,+ Err(e) => {+ if crate::service::download::github_api::rate_limited() {+ log::debug!("GitHub API commit resolution rate-limited, using build-id fallback");+ } else {+ log::warn!(+ "Failed to resolve commit for tag {} ({}), using build-id fallback",+ tag_name,+ e+ );+ }+ commit_fallback_from_tag(&tag_name)+ }+ };++ // 4. 资产 URL 与摘要:仅 API 可达时资产/摘要可信;否则 URL 平台确定性回退、digest=None+ let (asset_url, mut digest) = match api_release.as_ref() {+ Some(release) => {+ let asset = release+ .get("assets")+ .and_then(|value| value.as_array())+ .and_then(|assets| {+ assets.iter().find(|asset| {+ asset.get("name").and_then(|value| value.as_str())+ == Some(expected_name.as_str())+ })+ });+ let asset_url = asset+ .and_then(|a| a.get("browser_download_url").and_then(|v| v.as_str()))+ .map(|u| u.to_string())+ .unwrap_or_else(|| config::get_dsh_download_url().unwrap_or_default());+ let digest = asset+ .and_then(|a| a.get("digest").and_then(|v| v.as_str()))+ .filter(|v| v.starts_with("sha256:"))+ .map(|v| v.to_string());+ (asset_url, digest)+ }+ None => (config::get_dsh_download_url()?, None),+ };++ // 4b. API 限流/不可用导致取不到可信摘要时,改从 expanded_assets HTML+ // (github.com,非 api.github.com,不受 403 限流)解析作者填写的 sha256,+ // 保证完整性校验不因 api.github.com 限流而失效、更新不被卡死。+ if digest.is_none() {+ match fetch_dsh_digest_from_expanded_assets(&client, &tag_name, &expected_name).await {+ Ok(Some(d)) => {+ log::info!(+ "Trusted digest unavailable from GitHub API, recovered from release HTML for {}",+ expected_name+ );+ digest = Some(d);+ }+ Ok(None) => {+ log::warn!(+ "No digest found in release HTML for {} (tag {})",+ expected_name,+ tag_name+ );+ }+ Err(e) => {+ log::warn!("Failed to fetch digest from release HTML: {}", e);+ }+ }+ }++ Ok(LatestDshPkg {+ tag: tag_name,+ commit,+ asset_url,+ digest,+ })+}++/// 拉取指定 tag 的发行版信息(资产 URL + 可信摘要),供核心面板按版本下载。+///+/// 与 `fetch_latest_dsh_pkg_info` 同源策略:优先走 api.github.com+/// (`/releases/tags/{tag}` 拿资产与摘要),失败时资产 URL 平台确定性推导+/// (latest 地址的 tag 位替换)、摘要走 expanded_assets HTML;digest 仍取不到+/// 则置 `None`,调用方据此安全中止下载(沿用 DSH_INTEGRITY_UNAVAILABLE 设计)。+pub async fn fetch_dsh_pkg_asset(tag: &str) -> Result<LatestDshPkg, String> {+ let client = github_client()?;+ let expected_name = config::get_dsh_download_url()?+ .rsplit('/')+ .next()+ .ok_or_else(|| "Missing DSH asset filename".to_string())?+ .to_string();++ // 1. 优先 API 拉该 tag 的 release(含资产 + 可信摘要)+ let release = github_api_get(+ &client,+ &format!("{DSH_PKG_GITHUB_API}/releases/tags/{tag}"),+ )+ .await+ .map_err(|e| format!("Release {tag} request failed: {e}"))?;+ let json: serde_json::Value = release+ .json()+ .await+ .map_err(|e| format!("Failed to parse release {tag} response: {e}"))?;++ let asset = json+ .get("assets")+ .and_then(|value| value.as_array())+ .and_then(|assets| {+ assets.iter().find(|asset| {+ asset.get("name").and_then(|value| value.as_str()) == Some(expected_name.as_str())+ })+ });+ let asset_url = asset+ .and_then(|a| a.get("browser_download_url").and_then(|v| v.as_str()))+ .map(|u| u.to_string())+ .unwrap_or_else(|| config::get_dsh_download_url_for_tag(tag).unwrap_or_default());+ let mut digest = asset+ .and_then(|a| a.get("digest").and_then(|v| v.as_str()))+ .filter(|v| v.starts_with("sha256:"))+ .map(|v| v.to_string());++ // 2. 摘要兜底:expanded_assets HTML(github.com,非 api.github.com)+ if digest.is_none() {+ match fetch_dsh_digest_from_expanded_assets(&client, tag, &expected_name).await {+ Ok(Some(d)) => {+ log::info!(+ "Trusted digest unavailable from GitHub API, recovered from release HTML for {}",+ expected_name+ );+ digest = Some(d);+ }+ Ok(None) => {+ log::warn!(+ "No digest found in release HTML for {} (tag {})",+ expected_name,+ tag+ );+ }+ Err(e) => {+ log::warn!("Failed to fetch digest from release HTML: {}", e);+ }+ }+ }++ Ok(LatestDshPkg {+ tag: tag.to_string(),+ commit: commit_fallback_from_tag(tag),+ asset_url,+ digest,+ })+}++/// 从 release tag 中解析版本号:`dsh-0.1.0-rc.7-32054485373` → `0.1.0-rc.7`。+///+/// tag 约定为 `dsh-<version>-<commit 后缀>`;格式不符时返回 `None`,+/// 调用方据此回退到仅 commit 比对的旧行为,避免误判。+pub fn parse_version_from_tag(tag: &str) -> Option<String> {+ let version = tag.strip_prefix("dsh-")?.rsplit_once('-')?.0;+ (!version.is_empty()).then(|| version.to_string())+}++/// 安装记录(`dsh_pkg_commit` / `dsh_pkg_tag`)是否对应「最新 release 的同一发布」。+///+/// commit 存在两种合法形态:完整 git SHA(api.github.com 正常时解析,如+/// `1eed6dd6c078…`)与 tag 内嵌 build-id(api.github.com 限流时兜底,见+/// [`commit_fallback_from_tag`],如 `32485170079`)。同一 tag 的两种形态互不+/// 相等,而安装记录写成哪一种取决于安装当时 API 是否可用:限流期安装会把+/// build-id 写进记录,API 恢复后的检查却解析出完整 SHA。若只按字符串相等比对,+/// API 状态在两次启动之间翻转(限流 ↔ 恢复)会让同一 release 永远比对不上,+/// `resolve_update` 把同版本误判为「同版本热修」→ 每次启动都提示更新+/// (issue #92)。因此需归一化:记录 tag 与最新 tag 相同(同一次发布,任何+/// 形态的 commit 都来自该 tag),或记录 commit 与 release 的任一合法标识一致。+pub fn record_matches_latest_release(+ record_commit: Option<&str>,+ record_tag: Option<&str>,+ latest: &LatestDshPkg,+) -> bool {+ record_tag == Some(latest.tag.as_str())+ || record_commit.is_some_and(|rc| {+ rc == latest.commit.as_str() || rc == commit_fallback_from_tag(&latest.tag)+ })+}++/// 更新判定结果+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum UpdateCheck {+ /// 无更新+ UpToDate,+ /// 无更新,但本地记录滞后于实际安装文件,需要修正记录+ HealUpToDate,+ /// 有更新+ UpdateAvailable,+}++/// 结合本地记录与实际安装文件判定是否有新版 Harness 可用。+///+/// 本地记录(release commit + tag)由安装流程写入;但当安装文件被外围途径+/// 更新、或安装时 GitHub API 失败未落盘,记录会滞后于文件,造成每次都误报+/// 更新。这里以磁盘上实际的 `@deepseek-ai/dsh` 版本为准核对:+/// - 最新 release 版本号与已装版本不同 → 有更新(不论 commit);+/// - 版本号相同且记录对应同一 release(commit 任一形态匹配,或记录 tag 相同)→ 无更新;+/// - 版本号相同但记录是同一版本的另一发布(不同 build-id 的 tag)→ 同版本热修 → 有更新;+/// 记录 tag 版本更旧(或记录无 tag,经 `legacy_tags` 反查)→ 记录滞后 → 修正记录。+///+/// 注意必须先比版本、再比 commit:dsh 仓库的 rc 发布会重打同一 git commit,+/// 因此「最新 release 的 commit 等于已装记录的 commit」并不代表没有更新,+/// 只有 tag 里的版本号才能正确区分(如 rc.8 之于 rc.7)。+///+/// `legacy_tags` 是 pkg 仓库的 tags 列表(tag, commit),仅用于反查历史安装+/// 记录的版本;反查不到时以实际文件为准(视为记录滞后)。+pub fn resolve_update(+ record_commit: Option<&str>,+ record_tag: Option<&str>,+ installed_version: Option<&str>,+ latest: &LatestDshPkg,+ legacy_tags: &[(String, String)],+) -> UpdateCheck {+ let (Some(installed), Some(latest_version)) =+ (installed_version, parse_version_from_tag(&latest.tag))+ else {+ // 版本信息不可解析时回退旧行为:记录不一致即视为有更新+ return if record_matches_latest_release(record_commit, record_tag, latest) {+ UpdateCheck::UpToDate+ } else {+ UpdateCheck::UpdateAvailable+ };+ };++ // 先按“最新 release 的版本号”判定:与已装版本不同 → 有更新。+ // 不能先看 commit 相等就跳过:dsh 仓库的 rc 发布可能重打同一 git commit+ // (build-id 不同但 underlying commit 相同),此时 commit 不是可分辨信号,+ // 只有 tag 里的版本号才能正确识别 rc.8 之于 rc.7 是更新。+ if installed != latest_version {+ return UpdateCheck::UpdateAvailable;+ }+ // 版本相同 → 确认是否「同一发布」再判免打扰:记录与最新 release 对应+ // (见 [`record_matches_latest_release`])即文件已是最新,无更新。+ if record_matches_latest_release(record_commit, record_tag, latest) {+ return UpdateCheck::UpToDate;+ }+ // 文件已经是“最新版本”,此时需要甄别记录是否滞后+ match record_tag.and_then(parse_version_from_tag) {+ Some(record_version) if record_version < latest_version => UpdateCheck::HealUpToDate,+ Some(_) => UpdateCheck::UpdateAvailable,+ None => match legacy_tags+ .iter()+ .find(|(_, commit)| Some(commit.as_str()) == record_commit)+ {+ Some((tag, _)) => match parse_version_from_tag(tag) {+ Some(record_version) if record_version < latest_version => {+ UpdateCheck::HealUpToDate+ }+ // 反查到的版本与最新版本相同(或解析失败)→ 视为同版本热修+ _ => UpdateCheck::UpdateAvailable,+ },+ // 无法考证记录对应的版本 → 以实际安装文件为准,修正记录+ None => UpdateCheck::HealUpToDate,+ },+ }+}++/// 拉取 pkg 仓库的 release tag 列表(tag, commit),用于反查历史记录对应的版本。+///+/// 仅在更新判定需要反查“无 tag 的老记录”时调用,失败时由调用方回退到+/// “以实际文件为准”的保守分支。+pub async fn fetch_dsh_pkg_tags() -> Result<Vec<(String, String)>, String> {+ let client = github_client()?;+ let tags: serde_json::Value = github_api_get(+ &client,+ &format!("{}/tags?per_page=100", DSH_PKG_GITHUB_API),+ )+ .await+ .map_err(|e| format!("Release tags request failed: {e}"))?+ .json()+ .await+ .map_err(|e| format!("Failed to parse release tags response: {e}"))?;++ Ok(tags+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|entry| {+ let name = entry.get("name")?.as_str()?.to_string();+ let sha = entry.get("commit")?.get("sha")?.as_str()?.to_string();+ Some((name, sha))+ })+ .collect())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn latest(tag: &str, commit: &str) -> LatestDshPkg {+ LatestDshPkg {+ tag: tag.to_string(),+ commit: commit.to_string(),+ asset_url: "https://example.invalid/dsh.zip".to_string(),+ digest: Some(format!("sha256:{}", "0".repeat(64))),+ }+ }++ #[test]+ fn commit_fallback_extracts_build_id_from_tag() {+ assert_eq!(+ commit_fallback_from_tag("dsh-0.1.0-rc.8-32331963388"),+ "32331963388"+ );+ // 无 build-id 的 tag 兜底取最后一段,仍为非空稳定标识,避免空 commit 破坏比对+ assert_eq!(commit_fallback_from_tag("dsh-0.2.0"), "0.2.0");+ }++ #[test]+ fn parses_digest_from_expanded_assets_html() {+ // 模拟 expanded_assets 片段:资产文件名之后紧跟作者填写的 sha256:<64hex>。+ // 来自真实 rc.8 页面:windows 资产摘要为 4d541676...+ let html = concat!(+ "…/deepseek-harness-pkg-windows.zip…<span>sha256:4d5416766eb4a66e81b83532abeea64de7e7e2e0bac69a4f0c0508e1d91936c0</span>",+ );+ let got = parse_digest_from_expanded_assets(html, "deepseek-harness-pkg-windows.zip");+ assert_eq!(+ got.as_deref(),+ Some("sha256:4d5416766eb4a66e81b83532abeea64de7e7e2e0bac69a4f0c0508e1d91936c0")+ );+ // 文件名不存在 → None+ assert_eq!(+ parse_digest_from_expanded_assets(html, "deepseek-harness-pkg-linux.zip"),+ None+ );+ // 摘要缺失 → None+ assert_eq!(+ parse_digest_from_expanded_assets(+ "<p>no digest here</p>",+ "deepseek-harness-pkg-windows.zip"+ ),+ None+ );+ }++ #[test]+ fn parsed_digest_window_clamps_to_char_boundary() {+ // 构造一个 body 使 `(pos + 4096)` 恰好落在多字节字符的中间字节:+ // 旧实现 `&body[pos..pos + 4096]` 会在非字符边界切片而 panic,修复后回退到边界再解析。+ let name = "deepseek-harness-pkg-windows.zip";+ let digest = "4d5416766eb4a66e81b83532abeea64de7e7e2e0bac69a4f0c0508e1d91936c0";+ let prefix = format!("{name}<span>sha256:{digest}</span>");+ let mut body = prefix.clone();+ // 补齐到字节 4094 处,放一个 3 字节汉字(占用 4094..4097),使索引 4096 落在其中间字节+ let needed = 4094usize.saturating_sub(body.len());+ body.push_str(&"a".repeat(needed));+ body.push('中');+ body.push_str(&"a".repeat(16));+ // 确保总长 > 4096,维持 (pos + 4096) 处于非边界字节(否则不会触发回退分支)+ assert!(body.len() > 4096);+ let got = parse_digest_from_expanded_assets(&body, name);+ let expected = format!("sha256:{digest}");+ assert_eq!(got.as_deref(), Some(expected.as_str()));+ }++ #[test]+ fn parse_version_from_tag_formats() {+ assert_eq!(+ parse_version_from_tag("dsh-0.1.0-rc.7-32054485373").as_deref(),+ Some("0.1.0-rc.7")+ );+ assert_eq!(+ parse_version_from_tag("dsh-0.1.0-rc.6-31773193667").as_deref(),+ Some("0.1.0-rc.6")+ );+ assert_eq!(parse_version_from_tag("dsh-0.2.0"), None);+ assert_eq!(parse_version_from_tag("0.1.0-rc.7-abc"), None);+ assert_eq!(parse_version_from_tag(""), None);+ }++ #[test]+ fn resolve_matching_commit_is_up_to_date() {+ let latest = latest(+ "dsh-0.1.0-rc.7-32054485373",+ "6c659bb2636b3ad396a204c4c6ff110276fa3a09",+ );+ let decision = resolve_update(+ Some("6c659bb2636b3ad396a204c4c6ff110276fa3a09"),+ Some("dsh-0.1.0-rc.7-32054485373"),+ Some("0.1.0-rc.7"),+ &latest,+ &[],+ );+ assert_eq!(decision, UpdateCheck::UpToDate);+ }++ #[test]+ fn resolve_build_id_record_vs_real_sha_latest_is_up_to_date() {+ // issue #92 现场:限流期安装把 build-id 写进记录,API 恢复后的检查解析出+ // 完整 SHA——同一 release(dsh-0.1.1-rc.2-32485170079)的两种标识互不相等,+ // 必须归一化判定为无更新,而不是每次启动都误报「同版本热修」。+ let latest = latest(+ "dsh-0.1.1-rc.2-32485170079",+ "1eed6dd6c0780000000000000000000000000000",+ );+ let decision = resolve_update(+ Some("32485170079"), // 记录 commit:限流期写入的 build-id+ Some("dsh-0.1.1-rc.2-32485170079"),+ Some("0.1.1-rc.2"),+ &latest,+ &[],+ );+ assert_eq!(decision, UpdateCheck::UpToDate);+ }++ #[test]+ fn resolve_real_sha_record_vs_build_id_latest_is_up_to_date() {+ // 反向翻转:记录是完整 SHA,本次检查因 API 限流兜底出 build-id。+ // record_tag 与 latest.tag 相同即同一发布,不得误报更新。+ let latest = latest(+ "dsh-0.1.1-rc.2-32485170079",+ "32485170079", // 本次检查限流,commit 兜底为 build-id+ );+ let decision = resolve_update(+ Some("1eed6dd6c0780000000000000000000000000000"), // 记录:完整 SHA+ Some("dsh-0.1.1-rc.2-32485170079"),+ Some("0.1.1-rc.2"),+ &latest,+ &[],+ );+ assert_eq!(decision, UpdateCheck::UpToDate);+ }++ #[test]+ fn resolve_different_installed_version_is_update() {+ let latest = latest(+ "dsh-0.1.0-rc.7-32054485373",+ "6c659bb2636b3ad396a204c4c6ff110276fa3a09",+ );+ let decision = resolve_update(+ Some("564019027fd9469991aef6e57bb0a96325491c4e"),+ Some("dsh-0.1.0-rc.6-31773193667"),+ Some("0.1.0-rc.6"),+ &latest,+ &[],+ );+ assert_eq!(decision, UpdateCheck::UpdateAvailable);+ }++ #[test]+ fn resolve_same_version_hotfix_is_update() {+ // 记录正确(与文件一致),最新 release 是同版本热修:应提示更新+ let latest = latest(+ "dsh-0.1.0-rc.6-31773193667",+ "564019027fd9469991aef6e57bb0a96325491c4e",+ );+ let decision = resolve_update(+ Some("995e261e117617780dc50db16c70d445255978fd"),+ Some("dsh-0.1.0-rc.6-31762761461"),+ Some("0.1.0-rc.6"),+ &latest,+ &[],+ );+ assert_eq!(decision, UpdateCheck::UpdateAvailable);+ }++ #[test]+ fn resolve_stale_record_behind_files_heals() {+ // 用户现场:记录停留在 rc.6,文件已是 rc.7 → 修正记录、免打扰+ let latest = latest(+ "dsh-0.1.0-rc.7-32054485373",+ "6c659bb2636b3ad396a204c4c6ff110276fa3a09",+ );+ let decision = resolve_update(+ Some("564019027fd9469991aef6e57bb0a96325491c4e"),+ Some("dsh-0.1.0-rc.6-31773193667"),+ Some("0.1.0-rc.7"),+ &latest,+ &[],+ );+ assert_eq!(decision, UpdateCheck::HealUpToDate);+ }++ #[test]+ fn resolve_legacy_record_without_tag_heals_via_tags_lookup() {+ // 老记录没有 tag:反查 tags 列表发现记录版本低于文件版本 → 修正+ let latest = latest(+ "dsh-0.1.0-rc.7-32054485373",+ "6c659bb2636b3ad396a204c4c6ff110276fa3a09",+ );+ let tags = vec![(+ "dsh-0.1.0-rc.6-31773193667".to_string(),+ "564019027fd9469991aef6e57bb0a96325491c4e".to_string(),+ )];+ let decision = resolve_update(+ Some("564019027fd9469991aef6e57bb0a96325491c4e"),+ None,+ Some("0.1.0-rc.7"),+ &latest,+ &tags,+ );+ assert_eq!(decision, UpdateCheck::HealUpToDate);+ }++ #[test]+ fn resolve_legacy_same_version_still_updates() {+ // 老记录无 tag 但反查为同版本热修:仍应提示+ let latest = latest(+ "dsh-0.1.0-rc.6-31773193667",+ "564019027fd9469991aef6e57bb0a96325491c4e",+ );+ let tags = vec![(+ "dsh-0.1.0-rc.6-31762761461".to_string(),+ "995e261e117617780dc50db16c70d445255978fd".to_string(),+ )];+ let decision = resolve_update(+ Some("995e261e117617780dc50db16c70d445255978fd"),+ None,+ Some("0.1.0-rc.6"),+ &latest,+ &tags,+ );+ assert_eq!(decision, UpdateCheck::UpdateAvailable);+ }++ #[test]+ fn resolve_without_version_metadata_falls_back_to_update() {+ // 最新 tag 无法解析出版本时回退旧行为:记录不一致即提示+ let latest = latest("0.1.0-rc.7", "6c659bb2636b3ad396a204c4c6ff110276fa3a09");+ let decision = resolve_update(+ Some("564019027fd9469991aef6e57bb0a96325491c4e"),+ None,+ Some("0.1.0-rc.7"),+ &latest,+ &[],+ );+ assert_eq!(decision, UpdateCheck::UpdateAvailable);+ }++ #[test]+ fn resolve_rc7_installed_rc8_released_is_update() {+ // 用户现场(已实测真实网络):已装 rc.7,上游发布 rc.8。仓库 rc 发布会+ // 重打同一 git commit(/commits/{tag} 解析出的 rc.8 commit 与 rc.7 完全相同+ // 6c659bb...),因此 commit 相等不能当作“无更新”——版本号 rc.8 > rc.7+ // 才是有更新。正是这个 commit 相等快路径导致更新提示被吞。+ let latest = latest(+ "dsh-0.1.0-rc.8-32331963388",+ "6c659bb2636b3ad396a204c4c6ff110276fa3a09", // 与已装记录相同 commit+ );+ let decision = resolve_update(+ Some("6c659bb2636b3ad396a204c4c6ff110276fa3a09"), // rc.7 记录+ Some("dsh-0.1.0-rc.7-32054485373"),+ Some("0.1.0-rc.7"),+ &latest,+ &[],+ );+ assert_eq!(decision, UpdateCheck::UpdateAvailable);+ }+}diff --git a/src-tauri/src/service/download/mod.rs b/src-tauri/src/service/download/mod.rsindex 1091eadb..c15f82d1 100644--- a/src-tauri/src/service/download/mod.rs+++ b/src-tauri/src/service/download/mod.rs@@ -1,14 +1,17 @@mod core;mod extractor;+mod github;mod installable;mod progress;mod utils;// 导出公共接口pub use core::{- download_file, download_file_from_sources, ensure_extract, fetch_dsh_pkg_asset,- fetch_dsh_pkg_tags, fetch_latest_dsh_pkg_info, fetch_node_sha256, parse_version_from_tag,- record_matches_latest_release, resolve_update, verify_sha256, LatestDshPkg, UpdateCheck,+ download_file, download_file_from_sources, ensure_extract, fetch_node_sha256, verify_sha256,+};+pub use github::{+ fetch_dsh_pkg_asset, fetch_dsh_pkg_tags, fetch_latest_dsh_pkg_info, parse_version_from_tag,+ record_matches_latest_release, resolve_update, LatestDshPkg, UpdateCheck,};// 供核心面板切换版本时使用(跨模块内部接口,不进公共 API)pub(crate) use core::{remove_dir_with_retry, rename_with_retry};diff --git a/src-tauri/src/service/plugin/install.rs b/src-tauri/src/service/plugin/install.rsdeleted file mode 100644index 11e66b2b..00000000--- a/src-tauri/src/service/plugin/install.rs+++ /dev/null@@ -1,3225 +0,0 @@-//! 预装插件安装:校验选中项、准备环境(pnpm/dsh shim、按需补齐捆绑 pnpm、-//! 停止运行中的服务),随后调用 `dsh plugin --profile web add <specs...>`,-//! 成功后执行 Windows 极简模式专项修复。-//!-//! pnpm 对两类构建脚本默认不放行、缺白名单时报硬错误:-//! 1. git 托管插件的 `prepare` 构建(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`)——-//! 其允许键随 pnpm 的克隆方式变化(git+ssh#sha / codeload tar.gz),无法预先确定;-//! 2. 传递依赖的原生构建(如 `node-pty`,`ERR_PNPM_IGNORED_BUILDS`)。-//! 因此从 pnpm 错误输出解析它建议的允许键,写入 profile 的-//! `pnpm-workspace.yaml` 后重试,直至成功或无可解析项。-//!-//! pnpm 10 与 11 对放行项的配置键与输出形式不同(均由各自报错提示决定,只能运行期-//! 读取,见 [`parse_allowlist_keys`] 与 [`apply_allow_build_keys`]):-//! - pnpm 10(旧 store 复用用户版)只认 `onlyBuiltDependencies`(list 形式);-//! - pnpm 11(捆绑版)认 `allowBuilds`(map 形式)。-//! 应用会把同一批包名同时写入这两个键,保证任一版本 pnpm 都能读到放行项。-//!-//! 关键陷阱:pnpm v11 在 `allowBuilds` 阻断时可能仍以 **exit 0** 退出(假成功),-//! 所以重试逻辑不能只看退出码(见 [`run_plugin_with_allow_build_retry`]),安装成功-//! 后还会核验 `node_modules` 产物是否真实落盘(见 [`verify_installed_products`])。--use crate::config;-use crate::service::cli;-use crate::service::core;-use crate::service::download;-use crate::service::download::Installable;-use crate::service::profile::active_profile;-use crate::service::workflow;-use serde_yaml::{Mapping, Value};-use serde_json::Value as JsonValue;-use std::collections::HashMap;-use std::ffi::OsString;-use std::io::Read;-use std::path::{Path, PathBuf};-use tauri::{AppHandle, Emitter, Manager, WebviewWindow};--use super::errors;-use super::installed::{installed_name, is_installed, profile_dir};-use super::preset::{bundled_dep_spec, bundled_plugin_dir, load_presets, PreinstallPluginInfo};-use super::process::{- acquire_operation_lock, acquire_process_lock, new_process_owner, run_plugin_process, PidGuard,- PreinstallLogPayload, ProcessOwner, PREINSTALL_LOG_EVENT,-};-use super::recovery::is_actionable_plugin_ref;-use super::uninstall_recovery;--/// 允许构建重试的上限。每次重试解决 pnpm 报出的一个允许键(git depPath 或-/// 传递构建包名),多个 git 插件 / 多个原生依赖各占一次,上限封顶防死循环。-const MAX_ALLOW_LIST_RETRIES: usize = 8;--/// 可安全用于插件安装的用户 pnpm 最低主版本。-///-/// pnpm 10+ 才从 `pnpm-workspace.yaml` 读取 `autoInstallPeers`(9 及更早只读-/// `.npmrc`),且 10+ 移除了 workspace-root 安装门槛(`ERR_PNPM_ADDING_TO_ROOT`-/// 是 8/9 行为)。低于此版本时插件安装必须改用捆绑版 pnpm,否则会出现-/// 自动合成 peer 后 `No matching version found for @deepseek-ai/...` 的假失败。-const MIN_TRUSTED_PNPM_MAJOR: u32 = 10;-const PNPM_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);-const PNPM_PROBE_CLEANUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);-const PNPM_PROBE_REAP_RETRY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);-const PNPM_PROBE_REAP_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_millis(25);-const PNPM_PROBE_LIVENESS_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);--/// 校验并安装选中的预装插件:`dsh plugin --profile <当前档案> add <ids...>`-pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), String> {- install_with_cancel(app_handle, ids, None, new_process_owner()).await-}--/// 内置插件启动自愈专用入口:取消信号会阻止被结束的 pnpm/dsh 进程再次进入-/// allowBuilds 重试,确保硬上限之后不会悄悄拉起下一棵进程树。-pub(crate) async fn install_internal(- app_handle: &AppHandle,- ids: &[String],- cancel: tokio::sync::watch::Receiver<bool>,- owner: ProcessOwner,-) -> Result<(), String> {- install_with_cancel(app_handle, ids, Some(cancel), owner).await-}--async fn install_with_cancel(- app_handle: &AppHandle,- ids: &[String],- cancel: Option<tokio::sync::watch::Receiver<bool>>,- owner: ProcessOwner,-) -> Result<(), String> {- if ids.is_empty() {- return Err("PREINSTALL_EMPTY: no plugins selected".to_string());- }-- // 单次读取预设并构建查找表,提升算法效率至 O(N)- let presets = load_presets(app_handle);- let preset_map: HashMap<&str, &PreinstallPluginInfo> =- presets.iter().map(|p| (p.id.as_str(), p)).collect();-- let mut specs = Vec::with_capacity(ids.len());- for id in ids {- let preset = preset_map- .get(id.as_str())- .ok_or_else(|| format!("PREINSTALL_INVALID_ID: {id}"))?;- // 内置插件改为从随包分发的捆绑目录安装(`link:` 本地联接依赖,见- // preset::bundled_dep_spec;不用 `file:`——pnpm 对盘符冒号的绝对路径- // 会当相对路径解析),其余沿用清单声明的 spec;随后统一把- // `github:user/repo` 规范为显式 `git+https://...`,绕开 pnpm 对- // GitHub 简写「HTTPS 探测失败即回退 SSH」的已知缺陷(pnpm issue- // #3948 / #7243 / #13276):公开仓库一旦落进 git+ssh,在没有 SSH 配置- // 的桌面机上必然 `Host key verification failed` / `Permission denied (publickey)`。- //- // 最后经 shell_quote_spec 给含空格的 spec 加内嵌双引号(**仅 Windows**):- // dsh CLI 只在 win32 用 `shell:true` 启动 pnpm、把参数按空格拼接(Node- // 不引号转义,DEP0190),内置插件指向应用安装目录(如- // `G:\Deepseek Harness Desktop\...`,路径常含空格),拼进 shell 后会被- // 切碎成多个 spec,pnpm 报 `ERR_PNPM_SPEC_NOT_SUPPORTED`,插件装不上、- // 启动自愈每次重装(死循环)。引号让 cmd 把整条 spec 视为单一 token;- // pnpm 解析后自行剥离引号,落盘值仍是不带引号的 `link:<路径>`,与内核- // 对账的 `expected`(bundled_dep_spec)一致。macOS/Linux 是直接- // `spawnSync`(无 shell),spec 作为单个 argv 传递、空格天然保留,- // 引号只会被当作包名字符导致安装失败(见 [`shell_quote_spec`])。- let raw = normalize_git_spec(&preset_spec_for_install(- preset,- bundled_dir_of(app_handle, preset),- )?);- specs.push(shell_quote_spec(&raw));- }-- // 确保 pnpm/dsh shim 存在- cli::ensure_shims(app_handle)?;-- let node = config::get_node_binary_path(app_handle);- // 活动核心的 dsh 入口:本地核心存在时用本地 CLI,否则预打包- let dsh_bin = core::active_dsh_binary(app_handle);- if !node.exists() {- return Err("NODE_NOT_FOUND: Node.js runtime missing".to_string());- }- if !dsh_bin.exists() {- return Err("HARNESS_NOT_FOUND: dsh CLI missing".to_string());- }-- let window = app_handle- .get_webview_window("main")- .ok_or("WINDOW_NOT_FOUND: main window missing")?;-- // 选定/补齐安装用的 pnpm:返回是否应强制使用捆绑版(版本感知,见 ensure_pnpm)- let prefer_bundled_pnpm = ensure_pnpm(app_handle, &window, owner).await?;- // 首次安装可能早于服务启动;提前写入非交互清理配置,避免 pnpm 在无 TTY- // 环境以 ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY 中止(issue #130)。- super::ensure_profile_npmrc(app_handle)?;-- // 安装前停止运行中的服务,避免资源冲突- if workflow::has_owned_process() {- // 停服务会让用户感到"重启",先在日志面板讲清缘由(issue #48)- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: "[harness] 正在停止运行中的服务(安装插件需要短暂重启)…".to_string(),- },- );- log::info!("Stopping running harness service before installing plugins");- if let Err(e) = workflow::stop(app_handle.clone()).await {- log::warn!("failed to stop harness before plugin install: {e}");- }- }-- let envs = build_plugin_envs(app_handle, prefer_bundled_pnpm);-- // 拼装命令行参数- let mut args = vec![- dsh_bin.as_os_str().to_os_string(),- OsString::from("plugin"),- OsString::from("--profile"),- OsString::from(active_profile(app_handle)),- OsString::from("add"),- ];- args.extend(specs.iter().map(|s| OsString::from(s.as_str())));-- let cwd = config::get_dsh_install_path(app_handle);- // 日志打印实际传给 dsh 的 spec(此前打印 id 会误导排查:安装用的是 spec)- log::info!("Running dsh plugin install for {specs:?}");-- // `dsh plugin add` 在 profile 目录里驱动 pnpm。pnpm v11 会拦下 git 托管- // 插件的 prepare 构建与传递原生依赖(见模块头注),其允许键不可预知,因此- // 失败时解析输出里印出的 `allowBuilds` 键写回 profile 的 pnpm-workspace.yaml- // 后重试,直至成功或再无键可加(升级路径同样依赖该重试,见- // [`run_plugin_with_allow_build_retry`])。- let (exit_code, last_output) = run_plugin_with_allow_build_retry(- app_handle,- &node,- &args,- &cwd,- &envs,- &window,- "install",- cancel.as_ref(),- owner,- )- .await?;-- if exit_code != 0 {- log::error!("dsh plugin install failed with exit code {exit_code}");- // 区分 git 传输层失败与 allowBuilds 构建门禁:前者是 pnpm 走了 git+ssh- // (用户环境无 SSH 配置),后者才是补充白名单可自愈的。传输层错误给出- // 可读指引,避免用户被 dsh 那条 allowBuilds 提示误导。- let network_error = network_error_hint(&last_output).is_some()- || (exit_code == 3 && last_output.trim().is_empty());- let hint = git_transport_hint(&last_output);- let network_hint = network_error.then_some(- "NETWORK_ERROR: plugin registry request failed; check network or proxy settings and retry.",- );- let message = if network_error {- network_hint.unwrap_or_default().to_string()- } else {- pick_error_message(&last_output, hint)- };- // 批量安装失败时给本次选中的每个插件记一条错误(前端据此展示异常标记,- // 可针对单个插件重试更新/卸载)- for id in ids {- if let Err(e) = errors::record(app_handle, id, "install", &message) {- log::warn!("failed to record plugin error for {id}: {e}");- }- }- if let Some(network_hint) = network_hint {- log::warn!("network failure detected during plugin install: {network_hint}");- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: format!("[network] {network_hint}"),- },- );- return Err(format!("NETWORK_ERROR: {network_hint}"));- }- if let Some(hint) = hint {- log::warn!("git transport failure detected during plugin install: {hint}");- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: format!("[pnpm] {hint}"),- },- );- return Err(format!(- "PREINSTALL_FAILED: dsh plugin exited with code {exit_code} ({hint})"- ));- }- let detail = pick_error_message(&last_output, None);- if !detail.is_empty() {- log::error!("dsh plugin install diagnostic: {detail}");- }- return Err(format!(- "PREINSTALL_FAILED: dsh plugin exited with code {exit_code}{}",- diagnostic_suffix(&detail)- ));- }-- // 真正修复:核验本次安装是否真实落盘。pnpm 可能在 allowBuilds 阻断时仍以- // exit 0 退出(假成功),若产物缺失则记录错误并返回 Err,让前端如实展示失败、- // 允许重试,而不是误报「已安装」。已落盘的插件在上一步被核验并清除历史错误。- verify_installed_products(app_handle, ids, &preset_map, &last_output)?;-- // 产物级核验:包已落盘但声明入口(如 `lib/index.js`)未构建时,本次安装- // 同样是假成功——cordis 加载器在下一次启动必然 ERR_MODULE_NOT_FOUND 崩溃- // (见 [`ensure_plugin_entry_built`])。就地补构建或如实报错,不让坏态- // 静默进入下一次启动;包目录按预设的 `installed_name` 解析(scoped 插件- // 与 id 不同名),失败跨插件聚合后一次性返回,前端可一并重试。- let mut entry_errors = Vec::new();- for id in ids {- let Some(preset) = preset_map.get(id.as_str()) else {- continue;- };- let pkg_dir = profile_dir(app_handle)- .join("node_modules")- .join(installed_name(preset));- if let Err(e) = ensure_plugin_entry_built(app_handle, id, &pkg_dir, &envs, &window).await {- if let Err(err) = errors::record(app_handle, id, "install", &e) {- log::warn!("failed to record plugin error for {id}: {err}");- }- entry_errors.push(format!("{id}: {e}"));- }- }- if !entry_errors.is_empty() {- return Err(format!("PREINSTALL_ENTRY_FAILED:\n{}", entry_errors.join("\n")));- }-- // Windows 极简模式专项修复- if ids.iter().any(|id| id == "dsh-win-terminal-inspector") {- if let Err(e) = workflow::win_inspector::apply(app_handle) {- log::warn!("win inspector apply failed after install: {e}");- }- }-- // 告知用户安装阶段结束;随后的服务重启由前端 continueAfterPreinstall 负责- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: format!("[harness] 已安装 {} 个插件", ids.len()),- },- );-- log::info!("Preinstall plugins installed successfully: {ids:?}");- Ok(())-}--/// 内置插件才需要解析捆绑目录(普通插件无此概念),避免无谓的资源探测-fn bundled_dir_of(app_handle: &AppHandle, preset: &PreinstallPluginInfo) -> Option<PathBuf> {- if !preset.internal {- return None;- }- bundled_plugin_dir(app_handle, &preset.id)-}--/// 解析某预设的安装 spec(纯函数,便于单测):内置插件固定为随包捆绑目录的-/// `file:` 本地依赖(路径正确性由 [`super::internal::ensure`] 启动自愈核对);-/// 普通插件沿用清单声明。-///-/// 捆绑目录缺失时返回错误:内置插件缺失意味着构建期 prebuild 未执行或产物被-/// 删,属发布缺陷而非用户侧的普通安装失败,错误前缀便于区分。-fn preset_spec_for_install(- preset: &PreinstallPluginInfo,- bundled_dir: Option<PathBuf>,-) -> Result<String, String> {- if !preset.internal {- return Ok(preset.spec.clone());- }- let dir = bundled_dir.ok_or_else(|| {- format!(- "BUNDLED_PLUGIN_MISSING: no bundled dir for internal plugin {} (run scripts/prebuild.ts at build time)",- preset.id- )- })?;- Ok(bundled_dep_spec(&dir))-}--/// 校验本次安装是否真正落盘(防「假成功」):pnpm v11 在 `allowBuilds` 阻断-/// git 托管插件 / 传递依赖构建时仍可能以 exit 0 退出,仅凭退出码不足以认定安装-/// 成功。此处逐插件核验 profile 的 `node_modules/<安装名>/package.json` 是否真实-/// 存在:缺失者记录错误并整体返回 Err,避免前端误报「已安装 N 个插件」。-///-/// 已落盘的插件同步清除其历史错误;`ids` 里未匹配到预设的条目忽略(调用处已先-/// 校验过 ID,正常不可达)。同时接收全部命令输出,以便静默失败时保留早期重试的-/// 诊断,而不是因最后一次重试无输出而误报「子进程完全无输出」。-fn verify_installed_products(- app_handle: &AppHandle,- ids: &[String],- preset_map: &HashMap<&str, &PreinstallPluginInfo>,- command_output: &str,-) -> Result<(), String> {- let node_modules = profile_dir(app_handle).join("node_modules");- let mut missing = Vec::new();- for id in ids {- let Some(preset) = preset_map.get(id.as_str()) else {- continue;- };- let name = installed_name(preset);- let manifest = node_modules.join(name).join("package.json");- if manifest.is_file() {- if let Err(e) = errors::clear(app_handle, id) {- log::warn!("failed to clear plugin error for {id}: {e}");- }- } else {- missing.push((id.clone(), manifest));- }- }- if missing.is_empty() {- return Ok(());- }- let detail = silent_install_failure_detail(&missing, command_output);- log::error!("{detail}");- for (id, _) in &missing {- if let Err(e) = errors::record(app_handle, id, "install", &detail) {- log::warn!("failed to record plugin error for {id}: {e}");- }- }- Err(detail)-}--/// 为 exit 0 但无落盘产物的假成功生成可操作诊断:明确缺失插件、预期清单路径,-/// 并区分「子进程完全无输出」与「有输出但仍未落盘」,方便日志反馈直接定位。-fn silent_install_failure_detail(missing: &[(String, PathBuf)], command_output: &str) -> String {- let ids = missing- .iter()- .map(|(id, _)| id.as_str())- .collect::<Vec<_>>()- .join(", ");- let manifests = missing- .iter()- .map(|(_, path)| path.display().to_string())- .collect::<Vec<_>>()- .join(", ");- let output_hint = if command_output.trim().is_empty() {- "The dsh plugin command produced no output."- } else {- "Review the preinstall log above for the command output."- };- format!(- "PREINSTALL_SILENT_FAIL: dsh plugin exited with code 0, but no install artifact was created for [{ids}]. Expected package manifests: [{manifests}]. {output_hint} Retry the installation; if it repeats, include the preinstall log and these paths in the bug report."- )-}--/// 构建 `dsh plugin` 子进程的环境变量:隔离 $DSH_HOME、关闭遥测与颜色、-/// 注入预检解析出的 node 路径(`DSH_NODE`,shim 优先采用,见 shim.rs)、-/// PATH 前置 shim、node 与桌面端自动配置的 Git 目录;用户 pnpm 过旧时强制-/// 捆绑版(见 ensure_pnpm)。-///-/// 供本模块的安装/升级/卸载与 [`super::verify`] 的完整性修复共用:子进程(dsh-/// 或 pnpm)都按同一套桌面端环境策略运行,保证 $DSH_HOME / PATH 布局一致。-pub(crate) fn build_plugin_envs(- app_handle: &AppHandle,- prefer_bundled_pnpm: bool,-) -> HashMap<String, String> {- let node = config::get_node_binary_path(app_handle);- // 规范化为绝对路径:get_node_binary_path 可能返回相对路径(PATH 上出现- // 相对条目时,如 `.` 或 `tools\node`),而子进程 CWD 与应用进程不同,- // 相对路径会被解析到错误位置——shim 经 DSH_NODE / PATH 都找不到 node- // (issue #121 的 "Node.js runtime not found")。已存在(预检通过)的- // node 可安全 canonicalize;失败时回退原值。- let node_abs = dunce::canonicalize(&node).unwrap_or_else(|_| node.clone());- let bin_dir = cli::get_bin_dir(app_handle);- let mut envs = HashMap::from([- (- "DSH_HOME".to_string(),- config::get_dsh_data_path(app_handle)- .to_string_lossy()- .into_owned(),- ),- ("DSH_TELEMETRY_DISABLED".to_string(), "1".to_string()),- ("NO_COLOR".to_string(), "1".to_string()),- // 把预检解析出的 node 路径显式交给 pnpm/dsh shim(DSH_NODE 优先):- // shim 自身经 PATH 解析 node 可能与应用预检不一致(PATH 上的相对条目、- // junction/符号链接、或子进程 PATH 布局差异),导致 pnpm shim 报- // "Node.js runtime not found" 而应用预检却通过(issue #121)。- (- "DSH_NODE".to_string(),- node_abs.to_string_lossy().into_owned(),- ),- ]);- // 用户 pnpm 过旧/不可探测时强制 pnpm shim 优先捆绑版,避免 8/9 的- // autoInstallPeers 语义与 workspace-root gate 破坏插件安装(见 ensure_pnpm)- if prefer_bundled_pnpm {- envs.insert("DSH_PREFER_BUNDLED_PNPM".to_string(), "1".to_string());- } else if let Some(pnpm) = cli::find_user_pnpm(app_handle) {- // 显式注入绝对路径,避免子进程在不同 PATH/CWD 下重新发现失败。- // Unix 保留 mise 依赖 argv[0] 的 shim 链接;Windows 仍解析连接点并剥离- // `\\?\`。同时防御性排除应用自身 shim,避免递归调用。- if let Some(pnpm_value) = cli::pnpm_env_value(&pnpm, &bin_dir) {- envs.insert("DSH_PNPM".to_string(), pnpm_value);- }- }-- let mut paths = vec![bin_dir];- if let Some(node_dir) = node_abs.parent() {- paths.push(node_dir.to_path_buf());- }- // pnpm 安装 github:/git+ssh: 插件时会直接调用 git。Windows 空白环境使用- // 桌面端已校验安装的 MinGit,仅对子进程 PATH 生效,不污染用户系统 PATH。- if let Some(git_dir) = config::get_git_cmd_dir(app_handle) {- paths.push(git_dir);- }- paths.extend(std::env::split_paths(- &std::env::var_os("PATH").unwrap_or_default(),- ));-- if let Ok(joined) = std::env::join_paths(paths) {- envs.insert("PATH".to_string(), joined.to_string_lossy().into_owned());- }- // 用户 git 配置若把 GitHub HTTPS 改写为 SSH(url.<base>.insteadOf),pnpm 的- // git 传输会落进 SSH 而硬失败;按需隔离子进程 git 配置强制 HTTPS- // (见 [`git_https_isolation_env`],未命中改写规则时返回空 map,零影响)。- envs.extend(git_https_isolation_env(app_handle));- envs-}--/// 检测用户 git 配置中「把 GitHub HTTPS 改写为 SSH」的 `url.<base>.insteadOf`-/// 规则,命中时返回隔离子进程 git 配置所需的环境变量,强制插件安装走 HTTPS。-///-/// 背景:不少用户按 GitHub 官方文档配置过-/// `git config --global url."[email protected]:".insteadOf "https://github.com/"`-/// 让个人 git 操作走 SSH。pnpm 解析 `git+https://github.com/...` 插件时同样调用-/// git,URL 被该规则改写后实际走 SSH;桌面机通常没有 SSH 密钥(非交互子进程也-/// 无法应答 known_hosts 询问),于是 `Permission denied (publickey)` /-/// `Host key verification failed` 硬失败(用户可见提示见 [`git_transport_hint`])。-/// 检测到该类规则后,把子进程的 git 配置隔离为空文件(`GIT_CONFIG_GLOBAL`)或-/// 关闭系统配置(`GIT_CONFIG_NOSYSTEM`),让 HTTPS 地址原样生效——公开仓库无需-/// 任何凭据即可克隆。-///-/// 未命中时返回空 map:普通用户(含只配代理/凭据助手、无 SSH 改写者)的子进程-/// git 配置原样保留,零影响。探测全部为最佳努力——git 缺失、命令失败或输出异常-/// 都视为「无需隔离」,不阻断安装。-///-/// 仅用于桌面端驱动的 `dsh plugin` 子进程(`build_plugin_envs`):不注入长驻服务-/// 进程的环境——那里会被 agent 子进程继承,隔离 git 配置会让 agent 的 git 操作-/// 丢失 user.name/凭据助手/代理等用户配置。-fn git_https_isolation_env(app_handle: &AppHandle) -> HashMap<String, String> {- let Some(git) = plugin_git_binary(app_handle) else {- return HashMap::new();- };- let mut envs = HashMap::new();- if git_scope_has_github_ssh_rewrite(&git, &["--global"]) {- if let Some(config) = empty_git_config_file() {- log::info!(- "git config rewrites GitHub HTTPS to SSH (global); isolating GIT_CONFIG_GLOBAL to force HTTPS"- );- envs.insert(- "GIT_CONFIG_GLOBAL".to_string(),- config.to_string_lossy().into_owned(),- );- }- }- if git_scope_has_github_ssh_rewrite(&git, &["--system"]) {- log::info!(- "git config rewrites GitHub HTTPS to SSH (system); disabling system git config to force HTTPS"- );- envs.insert("GIT_CONFIG_NOSYSTEM".to_string(), "1".to_string());- }- envs-}--/// 解析插件子进程将使用的 git 可执行文件:Windows 用桌面端已选 Git(系统 Git 或-/// 捆绑 MinGit,见 [`config::get_git_cmd_dir`],与注入子进程 PATH 的目录一致),-/// Unix 直接用 PATH 上的 `git`。-fn plugin_git_binary(app_handle: &AppHandle) -> Option<PathBuf> {- #[cfg(windows)]- {- config::get_git_cmd_dir(app_handle).map(|dir| dir.join("git.exe"))- }- #[cfg(not(windows))]- {- Some(PathBuf::from("git"))- }-}--/// 运行 `git config <scope> --get-regexp '^url\.'`,判断该作用域的配置里是否存在-/// 把 GitHub HTTP(S) 改写为 SSH 的 insteadOf 规则。无匹配(git 返回 1)或命令-/// 失败都视为不存在。-fn git_scope_has_github_ssh_rewrite(git: &Path, scope: &[&str]) -> bool {- let mut cmd = std::process::Command::new(git);- cmd.args(scope).args(["--get-regexp", "^url\\."]);- #[cfg(windows)]- {- use std::os::windows::process::CommandExt;- // CREATE_NO_WINDOW:GUI 进程下禁止闪现控制台窗口- cmd.creation_flags(0x0800_0000);- }- let Ok(output) = cmd.output() else {- return false;- };- if !output.status.success() {- return false;- }- has_github_ssh_rewrite_in_output(&String::from_utf8_lossy(&output.stdout))-}--/// 从 `git config --get-regexp '^url\.'` 的输出文本中判定是否存在把 GitHub-/// HTTP(S) 改写为 SSH 的规则(纯函数,便于单测)。-fn has_github_ssh_rewrite_in_output(output: &str) -> bool {- output.lines().any(rewrite_rule_targets_ssh_github)-}--/// 判定单条 `url.<base>.insteadOf <value>` 输出行是否为「把 GitHub HTTP(S) 地址-/// 改写为 SSH」的有害规则。git 会把 section/key 名小写化(实际形如-/// `[email protected]:.insteadof`),subsection 与 value 大小写保留;-/// pushInsteadOf(`.pushinsteadof`)不会命中 `.insteadof` 后缀剥离,天然排除-/// (只影响 push,不影响拉取)。-fn rewrite_rule_targets_ssh_github(line: &str) -> bool {- let mut parts = line.splitn(2, ' ');- let (key, value) = match (parts.next(), parts.next()) {- (Some(k), Some(v)) => (k.to_ascii_lowercase(), v.trim()),- _ => return false,- };- let Some(base) = key- .strip_prefix("url.")- .and_then(|k| k.strip_suffix(".insteadof"))- else {- return false;- };- let ssh_base = base.starts_with("git@")- || base.starts_with("ssh://")- || base.starts_with("git+ssh://");- ssh_base && github_http_host(value)-}--/// value 是否为 GitHub 的 HTTP(S) URL 前缀(如 `https://github.com/`、-/// `https://github.com`、`http://github.com/`)。-fn github_http_host(value: &str) -> bool {- let value = value.trim();- let scheme_end = value.find("://").map(|i| i + 3).unwrap_or(0);- let host = value[scheme_end..]- .split('/')- .next()- .unwrap_or(&value[scheme_end..]);- host == "github.com" || host == "www.github.com"-}--/// 在系统临时目录创建一个空配置文件,作为隔离后的 `GIT_CONFIG_GLOBAL`。-/// 文件名带进程号与纳秒时间戳防碰撞(0 字节文件由 OS 临时目录回收,无需主动-/// 清理;GIT_CONFIG_GLOBAL 语义为「仅读取该文件」,空文件即无任何全局配置)。-fn empty_git_config_file() -> Option<PathBuf> {- let nanos = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_nanos())- .unwrap_or(0);- let path = std::env::temp_dir().join(format!(- "dsh-gitconfig-{}-{nanos:x}.empty",- std::process::id()- ));- std::fs::write(&path, "").ok()?;- Some(path)-}--/// 运行 `dsh plugin` 子命令并应用 `allowBuilds` 重试:-/// pnpm 会拦截 git 托管插件的 `prepare` 构建(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`)-/// 与传递依赖的原生构建(`ERR_PNPM_IGNORED_BUILDS`)。其允许键(git depPath 含克隆-/// 提交 SHA)会随新版本变化,升级时旧条目无法匹配新依赖,必须从失败输出重新解析-/// 该键写回 profile 的 `pnpm-workspace.yaml` 后重试。-///-/// 安装与升级共用此逻辑——此前仅升级路径缺失该重试(issue #82):git 托管插件-/// (如 dsh-better-sidebar)一升级就必然以退出码 1 失败,且包停在「prepare 未构建 →-/// `lib/index.js` 缺失」的坏态,下一次启动便因 `${DSH_HOME}/profiles/<档案>/node_modules/<pkg>/lib/index.js`-/// 无法解析而 `ERR_MODULE_NOT_FOUND` 失败。-///-/// 返回 `(退出码, 所有尝试累积的输出)`,避免最后一次重试无输出时丢失此前诊断。-/// 输出仍逐行经 `preinstall-log` 实时推送。-///-/// 注意:pnpm v11 在 `allowBuilds` 将 git 托管插件(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`)-/// 或传递依赖(`ERR_PNPM_IGNORED_BUILDS`)拦截时仍可能以 **exit 0** 退出(假成功),-/// 因此不能仅凭退出码判断成败——必须先解析输出里的 `allowBuilds` 键,有键就写入-/// profile 的 `pnpm-workspace.yaml` 并重试。无键可加(或到达重试上限)才以本次退出码为准。-///-/// 每次重试的输出都必须累积,避免最终尝试无输出时覆盖此前真正有用的 pnpm 诊断。-async fn run_plugin_with_allow_build_retry(- app_handle: &AppHandle,- node: &Path,- args: &[OsString],- cwd: &Path,- envs: &HashMap<String, String>,- window: &WebviewWindow,- action: &str,- cancel: Option<&tokio::sync::watch::Receiver<bool>>,- owner: ProcessOwner,-) -> Result<(i32, String), String> {- let _operation_guard = acquire_operation_lock().await;- let mut retries = 0usize;- let mut all_output = String::new();- let exit_code = loop {- if cancel.is_some_and(|signal| *signal.borrow()) {- return Err("PLUGIN_OPERATION_CANCELLED: plugin operation was cancelled".to_string());- }- let (code, captured) = run_plugin_process(node, args, cwd, envs, window, owner).await?;- if cancel.is_some_and(|signal| *signal.borrow()) {- return Err("PLUGIN_OPERATION_CANCELLED: plugin operation was cancelled".to_string());- }- append_command_output(&mut all_output, &captured);- let new_keys = parse_allowlist_keys(&captured);- // 有可补充的 allowBuilds 键且未达上限 → 写入并重试(无论本次退出码是否为 0,- // 见上方注释:pnpm 可能在阻断时仍以 0 退出)。- if !new_keys.is_empty() && retries < MAX_ALLOW_LIST_RETRIES {- retries += 1;- add_allow_build_keys(app_handle, &new_keys)?;- log::info!("pnpm allowBuilds updated with {new_keys:?}, retrying {action} ({retries})");- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: format!("[pnpm] 已放行插件构建(allowBuilds),重试{action}…"),- },- );- continue;- }- // 到达重试上限仍解析到待放行键:pnpm 的 exit 0 在 allowBuilds 场景不可信,- // 直接视为失败(即便退出码为 0),交由调用方走失败 / 产物核验分支。- if !new_keys.is_empty() {- log::error!(- "dsh plugin {action}: allowBuilds retry limit reached ({retries}), keys {new_keys:?} unresolved"- );- break if code == 0 { 1 } else { code };- }- if code != 0 {- log::error!(- "dsh plugin {action} failed with exit code {code}; no allowBuilds entries to add"- );- }- break code;- };- Ok((exit_code, all_output))-}--/// 合并单次命令输出,并在相邻尝试之间补换行,保证后续错误解析不会粘连两段日志。-fn append_command_output(all_output: &mut String, captured: &str) {- if captured.is_empty() {- return;- }- if !all_output.is_empty() && !all_output.ends_with('\n') {- all_output.push('\n');- }- all_output.push_str(captured);-}--/// 解析插件包声明的主入口(与 cordis 加载器实际读取的字段一致):-/// 优先 `dsh.plugin.json` 的 `main`(加载器入口,见 loader 报错路径),-/// 回落 `package.json` 的 `main` / `exports["."]`(字符串简写 → 对象-/// `default` → `import` → `require`)。-/// 仅负责解析声明,不校验产物是否存在;入口越界(`../` 逃逸/绝对路径)-/// 或无可解析入口时返回 None。-fn declared_main_entry(pkg_dir: &Path) -> Option<PathBuf> {- /// 拼接声明入口并拒绝越界:绝对路径会被 `join` 整体替换基路径,`../`- /// 逃逸在 `starts_with` 的词法比较下不会被解析——两者都会让核验目标指向- /// 包外文件,导致假通过。- fn join_contained(pkg_dir: &Path, entry: &str) -> Option<PathBuf> {- let candidate = Path::new(entry);- if candidate.is_absolute()- || candidate- .components()- .any(|c| matches!(c, std::path::Component::ParentDir))- {- return None;- }- let joined = pkg_dir.join(candidate);- joined.starts_with(pkg_dir).then_some(joined)- }- let from_main_field = |value: &JsonValue| -> Option<PathBuf> {- value- .get("main")- .and_then(|v| v.as_str())- .and_then(|main| join_contained(pkg_dir, main))- };- let plugin_manifest_text = std::fs::read_to_string(pkg_dir.join("dsh.plugin.json")).ok();- if let Some(text) = plugin_manifest_text {- if let Ok(value) = serde_json::from_str::<JsonValue>(&text) {- if let Some(entry) = from_main_field(&value) {- return Some(entry);- }- }- }- let pkg_text = std::fs::read_to_string(pkg_dir.join("package.json")).ok()?;- let value = serde_json::from_str::<JsonValue>(&pkg_text).ok()?;- if let Some(entry) = from_main_field(&value) {- return Some(entry);- }- let exports = value.get("exports");- // 字符串简写:"exports": "./lib/index.js"(`get(".")` 对字符串取值会落空,- // 必须先试字符串形态)- if let Some(shorthand) = exports.and_then(|v| v.as_str()) {- return join_contained(pkg_dir, shorthand);- }- let dot = exports.and_then(|v| v.get("."));- for key in ["default", "import", "require"] {- if let Some(entry) = dot- .and_then(|d| d.get(key))- .and_then(|v| v.as_str())- .and_then(|s| join_contained(pkg_dir, s))- {- return Some(entry);- }- }- None-}--/// 把插件 id 解析为 profile 中实际的 npm 包名:预设表(`package` 覆盖字段)-/// 优先;找不到预设时按 profile 清单 `dependencies` 键的 basename 匹配-/// (覆盖 `@scope/name` 形态,如 `dsh-session-context-menu` →-/// `@baihejiangnan/dsh-session-context-menu`)。-fn installed_package_name(app_handle: &AppHandle, id: &str) -> Option<String> {- if let Some(preset) = load_presets(app_handle).iter().find(|p| p.id == id) {- return Some(installed_name(preset).to_string());- }- let manifest_path = profile_dir(app_handle).join("package.json");- let text = std::fs::read_to_string(&manifest_path).ok()?;- let value = serde_json::from_str::<JsonValue>(&text).ok()?;- value- .get("dependencies")- .and_then(|d| d.as_object())- .and_then(|deps| {- deps.keys()- .find(|name| name.rsplit('/').next() == Some(id))- .cloned()- })-}--/// 核验已装插件包的声明入口产物,缺失时就地补构建或如实报错。-///-/// 背景:`verify_installed_products` 核验的是「包是否落盘」(`package.json`-/// 存在),但 pnpm 放行 git 托管插件的 `prepare` 后,构建仍可能停在不产出的-/// 坏态:tsdown 在 `node_modules` 内加载其 TS 配置受 Node 版本限制(报错建议-/// `--config-loader` 用 `tsx`/`unrun`),此时 `dsh plugin add` 以 0 退出且-/// `package.json` 已落盘,但 `lib/index.js` 缺失——下一次启动 cordis 加载器-/// `ERR_MODULE_NOT_FOUND` 崩溃(应用内所有 fetch 必挂,表现为「插件目录 /-/// 历史会话全部 Failed to fetch」)。-/// 补构建按成本递增:`run build` → `run prepare` → `exec tsdown --config-loader unrun`-/// (社区已知绕过方式,unrun 已随 tsdown 进插件 devDeps)。全部失败则记录错误并-/// 如实返回,杜绝「装上了却跑不起来」的静默成功。-///-/// `pkg_dir` 由调用方解析(install 用预设的 `installed_name`,update 用-/// `installed_package_name`),本函数不再假设 id 即包名。-async fn ensure_plugin_entry_built(- app_handle: &AppHandle,- id: &str,- pkg_dir: &Path,- envs: &HashMap<String, String>,- window: &WebviewWindow,-) -> Result<(), String> {- if !pkg_dir.is_dir() {- return Err(format!(- "PLUGIN_ENTRY_MISSING: {id} 未安装({} 不存在),请重新安装",- pkg_dir.display()- ));- }- let Some(entry) = declared_main_entry(pkg_dir) else {- // 无声明入口(包本身不暴露可核验产物):不阻塞,仅告警- log::warn!("plugin {id} declares no verifiable main entry, skipping build verify");- return Ok(());- };- if entry.is_file() {- return Ok(());- }-- // 与 verify 修复路径同一套 store 主版本感知 pnpm 选择(捆绑版优先,不匹配- // 时回落用户 pnpm.exe),不硬编码单一 pnpm,避免「装了用户版却没捆绑版」- // 或 v10/v11 store 不兼容的假失败。- let Some((program, pre_args)) = super::verify::pnpm_direct(app_handle) else {- return Err(format!(- "PNPM_NOT_FOUND: no usable pnpm (bundled or user) to rebuild plugin {id}"- ));- };- log::warn!(- "plugin {id} declared entry {} is missing; rebuilding in place",- entry.display()- );- let attempts: [(&str, &[&str]); 3] = [- ("build", &["run", "build"]),- ("prepare", &["run", "prepare"]),- (- "tsdown --config-loader unrun",- &["exec", "tsdown", "--config-loader", "unrun"],- ),- ];- let mut all_output = String::new();- for (label, args) in attempts {- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: format!(- "[pnpm] {id} 缺少构建产物({}),正在补构建({label})…",- entry.display()- ),- },- );- let mut full_args = pre_args.clone();- full_args.extend(args.iter().map(|a| OsString::from(*a)));- // 单次 spawn 失败(pnpm 瞬时不可用等)不致命:记日志后尝试下一策略,- // 输出跨尝试累计,保证最终报错携带最早一次的有效诊断。- // main 侧 `run_plugin_process` 要求显式 ProcessOwner(pid 槽位跟踪/取消);- // 补构建是独立的一次性构建,不隶属 install/update 的操作锁,取新 owner。- match run_plugin_process(&program, &full_args, pkg_dir, envs, window, new_process_owner())- .await- {- Ok((code, output)) => {- append_command_output(&mut all_output, &output);- // 产物出现即视为成功(目标=「入口存在、加载器不崩」);- // 退出码非 0 但产物已生成(如 post-build 钩子失败)仅记警告。- if entry.is_file() {- if code != 0 {- log::warn!(- "plugin {id} build via {label} exited {code} but entry {} exists",- entry.display()- );- }- log::info!("plugin {id} rebuilt via {label}: {}", entry.display());- return Ok(());- }- log::warn!("plugin {id} build via {label} exited {code}; trying next strategy");- }- Err(e) => {- log::warn!("plugin {id} build via {label} failed to spawn: {e}; trying next strategy");- }- }- }- let tail = all_output- .lines()- .rev()- .take(8)- .collect::<Vec<_>>()- .into_iter()- .rev()- .collect::<Vec<_>>()- .join("\n");- Err(format!(- "PLUGIN_ENTRY_MISSING: {id} 声明的入口 {} 构建失败(build/prepare 均未产出),尾部日志:\n{tail}",- entry.display()- ))-}--/// 升级单个插件:`dsh plugin --profile <当前档案> update <id>`-pub async fn update(app_handle: &AppHandle, id: &str) -> Result<(), String> {- run_single_plugin_command(- app_handle,- id,- "update",- &["update".to_string(), id.to_string()],- )- .await-}--/// 卸载单个插件:`dsh plugin --profile <当前档案> remove <id>`-pub async fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {- let command_result = run_single_plugin_command(- app_handle,- id,- "remove",- &["remove".to_string(), id.to_string()],- )- .await;- // `dsh plugin remove` 以子进程退出码为准,可能出现「命令成功但插件仍在」的- // 边界(如 bundle 层残留、pnpm 静默失败);node_modules / lockfile 损坏时- // (典型:安装只写入了 profile 清单而产物缺失,见 issue #90)pnpm 甚至会- // 直接失败。两种情形统一核验 profile 清单:只要插件仍被引用就回落离线卸载- // (直接改清单 + 删目录 + 清 lockfile),确保插件真正移除- // (参考 dsh-market 的「卸载后核验」约定:确认插件离开 profile 才算成功)。- if is_installed(app_handle, id) {- // 第三方可卸载插件才允许离线兜底;核心/官方等受保护包即使残留也不强删- // (`uninstall_recovery` 对它们会拒绝)。- if is_actionable_plugin_ref(id) {- let outcome = match &command_result {- Ok(()) => "reported success".to_string(),- Err(e) => format!("failed: {e}"),- };- log::warn!(- "dsh plugin remove {outcome} but {id} is still referenced by profile manifest; forcing offline uninstall"- );- uninstall_recovery(app_handle, id)?;- } else {- // 受保护包:命令失败则如实上报(不要把失败误报为成功),成功则仅告警。- command_result?;- log::warn!(- "dsh plugin remove reported success but protected package {id} is still referenced by profile manifest; skipping offline uninstall"- );- }- }- Ok(())-}--/// 计算需要自动卸载的弃用插件已安装包名(纯函数,便于单测)。-///-/// 命中条件:清单中带 `deprecated` 标记、非内部插件(内部插件由启动自愈强制-/// 安装,不适用弃用语义),且当前已安装(以实际 npm 包名 `installed_name` 为准)。-/// 返回实际安装包名——离线卸载(`uninstall_recovery`)以它为键从 profile 清单与-/// `node_modules` 精准移除(scoped 包名与预设 id 不一致时也能正确卸载)。-fn deprecated_installed_names(- presets: &[PreinstallPluginInfo],- installed: impl Fn(&str) -> bool,-) -> Vec<String> {- presets- .iter()- .filter(|p| p.deprecated && !p.internal)- .filter(|p| installed(installed_name(p)))- .map(|p| installed_name(p).to_string())- .collect()-}--/// 启动时自动卸载清单中带 `deprecated` 标记的插件。-///-/// 弃用是发布侧决策:某个社区插件下架/被替换后,在 `preset-plugins.json` 里给它-/// 打上 `deprecated` 标记,桌面端每次启动核对「已安装 → 自动卸载」,无需用户手动-/// 处理,也避免残留插件继续在 profile 里加载破坏启动。仅处理社区预设;未被引用-/// 的条目跳过。已卸载/未安装的插件跳过,绝不误伤其它插件。-///-/// 启动阶段走离线精准卸载(`uninstall_recovery`):不依赖 node/pnpm/窗口,即使-/// 插件产物已损坏也能移除,也不会触发服务停止或 pnpm 下载。最佳努力:任何失败-/// 只记告警,不阻断启动(调用方仅打日志)。-pub(crate) async fn uninstall_deprecated_plugins(app_handle: &AppHandle) -> Result<(), String> {- let presets = load_presets(app_handle);- let names = deprecated_installed_names(&presets, |name| is_installed(app_handle, name));- if names.is_empty() {- return Ok(());- }- log::info!("uninstalling deprecated preset plugins: {names:?}");- let mut failures = Vec::new();- for name in &names {- log::info!("DEPRECATED_PLUGIN_UNINSTALL: removing deprecated plugin {name}");- if let Err(e) = uninstall_recovery(app_handle, name) {- log::warn!("DEPRECATED_PLUGIN_UNINSTALL_FAILED: {name}: {e}");- failures.push(format!("{name}: {e}"));- }- }- if failures.is_empty() {- Ok(())- } else {- Err(failures.join("; "))- }-}--/// 执行单个插件的升级/卸载:准备环境 → 停止服务 → 运行 `dsh plugin` →-/// 失败记录错误、成功清除错误。-async fn run_single_plugin_command(- app_handle: &AppHandle,- id: &str,- action: &str,- sub_args: &[String],-) -> Result<(), String> {- if id.is_empty() {- return Err("PLUGIN_EMPTY_ID: plugin id is empty".to_string());- }- let window = app_handle- .get_webview_window("main")- .ok_or("WINDOW_NOT_FOUND: main window missing")?;-- cli::ensure_shims(app_handle)?;-- let node = config::get_node_binary_path(app_handle);- let dsh_bin = core::active_dsh_binary(app_handle);- if !node.exists() {- return Err("NODE_NOT_FOUND: Node.js runtime missing".to_string());- }- if !dsh_bin.exists() {- return Err("HARNESS_NOT_FOUND: dsh CLI missing".to_string());- }-- let owner = new_process_owner();- let prefer_bundled_pnpm = ensure_pnpm(app_handle, &window, owner).await?;- // `.npmrc` 可能在服务启动后被删除;升级/卸载同样可能触发 pnpm 非交互清理。- super::ensure_profile_npmrc(app_handle)?;-- // 插件操作会改写 profile,先停止运行中的服务(与安装一致)- if workflow::has_owned_process() {- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: format!("[harness] 正在停止运行中的服务({action}插件需要短暂重启)…"),- },- );- if let Err(e) = workflow::stop(app_handle.clone()).await {- log::warn!("failed to stop harness before plugin {action}: {e}");- }- }-- let envs = build_plugin_envs(app_handle, prefer_bundled_pnpm);-- let mut args = vec![- dsh_bin.as_os_str().to_os_string(),- OsString::from("plugin"),- OsString::from("--profile"),- OsString::from(active_profile(app_handle)),- OsString::from(action),- ];- args.extend(sub_args.iter().map(OsString::from));-- let cwd = config::get_dsh_install_path(app_handle);- log::info!("Running dsh plugin {action} for {id}");- let (exit_code, output) = run_plugin_with_allow_build_retry(- app_handle, &node, &args, &cwd, &envs, &window, action, None, owner,- )- .await?;-- if exit_code != 0 {- log::error!("dsh plugin {action} failed for {id} with exit code {exit_code}");- let network_error =- network_error_hint(&output).is_some() || (exit_code == 3 && output.trim().is_empty());- let message = if network_error {- "NETWORK_ERROR: plugin registry request failed; check network or proxy settings and retry."- .to_string()- } else {- pick_error_message(&output, git_transport_hint(&output))- };- if let Err(e) = errors::record(app_handle, id, action, &message) {- log::warn!("failed to record plugin error for {id}: {e}");- }- if network_error {- return Err("NETWORK_ERROR: plugin registry request failed; check network or proxy settings and retry.".to_string());- }- return Err(format!(- "PLUGIN_{}_FAILED: dsh plugin exited with code {exit_code}",- action.to_uppercase()- ));- }-- // 成功:清除历史错误;卸载 win-terminal-inspector 时顺带清理 patch 挂载- if let Err(e) = errors::clear(app_handle, id) {- log::warn!("failed to clear plugin error for {id}: {e}");- }- // 升级路径与安装一致地核验构建产物:git 托管插件升级后同样可能停在- // 「prepare 未构建 → 声明入口缺失」坏态,若不拦截,下一次启动即崩溃- // (见 [`ensure_plugin_entry_built`])。包名先解析(预设 package 覆盖 /- // 清单依赖 basename),解析不到时跳过核验(警告即可,不误杀成功更新)。- if action == "update" {- let Some(name) = installed_package_name(app_handle, id) else {- log::warn!("plugin {id} not resolvable to a package name, skipping entry verify");- return Ok(());- };- let pkg_dir = profile_dir(app_handle).join("node_modules").join(name);- if let Err(e) = ensure_plugin_entry_built(app_handle, id, &pkg_dir, &envs, &window).await- {- if let Err(err) = errors::record(app_handle, id, action, &e) {- log::warn!("failed to record plugin error for {id}: {err}");- }- return Err(e);- }- }- if action == "remove" && id == "dsh-win-terminal-inspector" {- if let Err(e) = workflow::win_inspector::apply(app_handle) {- log::warn!("win inspector patch prune failed after remove: {e}");- }- }- log::info!("dsh plugin {action} succeeded for {id}");- Ok(())-}--/// 从 dsh/pnpm 失败输出中提取可展示的错误消息:优先 git 传输层提示;-/// 否则挑出命中错误标记的行(最多 8 行),没有则取输出尾部,ANSI 清洗后-/// 截断到 2000 字符。-fn diagnostic_suffix(detail: &str) -> String {- if detail.is_empty() {- String::new()- } else {- format!(": {detail}")- }-}--fn pick_error_message(output: &str, hint: Option<&str>) -> String {- if let Some(hint) = hint {- return hint.to_string();- }- let cleaned: Vec<String> = output- .split('\n')- .filter_map(|line| {- let trimmed = strip_ansi(line);- let trimmed = trimmed.trim();- (!trimmed.is_empty()).then(|| trimmed.to_string())- })- .filter(|line| {- line.contains("ERR_")- || line.contains("error")- || line.contains("Error")- || line.contains("failed")- || line.contains("✖")- || line.contains("warning")- })- .take(8)- .collect();- let base = if cleaned.is_empty() {- output.trim().to_string()- } else {- cleaned.join("\n")- };- base.chars().take(2000).collect()-}--/// 去除 ANSI 转义序列(`\x1B[...m`,含颜色/样式码)。-fn strip_ansi(s: &str) -> String {- let mut out = String::with_capacity(s.len());- let mut chars = s.chars().peekable();- while let Some(c) = chars.next() {- if c == '\x1b' && chars.peek() == Some(&'[') {- chars.next(); // '['- while let Some(&n) = chars.peek() {- if n.is_ascii_digit() || n == ';' {- chars.next();- } else {- break;- }- }- if chars.peek() == Some(&'m') {- chars.next();- }- } else {- out.push(c);- }- }- out-}--/// 确保插件安装使用的 pnpm 可用,返回是否应强制使用捆绑版-/// (true 时调用方注入 `DSH_PREFER_BUNDLED_PNPM=1`,pnpm shim 优先捆绑版)。-///-/// 版本感知策略,避免给已装正确 pnpm 的用户增加下载步骤:-/// - 档案 store 主版本已知 → 只接受与其一致的 pnpm(用户版或捆绑版)。-/// pnpm 10 与 11 的 store 布局互不兼容(`.../store/v10` vs `v11`),用与-/// store 主版本不一致的 pnpm 更新已装插件会直接 `ERR_PNPM_UNEXPECTED_STORE`-/// 退出码 1 失败——升级失败的根因(此前捆绑版 v11 一存在就强制使用,-/// 对 v10 store 的档案必然失败);-/// - 用户 pnpm 主版本 == store 主版本 → 复用用户 pnpm,零额外步骤;-/// - 捆绑版 pnpm 主版本 == store 主版本 → 用捆绑版(不下载);-/// - store 未知(全新档案/未装过依赖)或无可匹配版本 → 用户 pnpm ≥ 10 优先,-/// 否则捆绑版已存在则用,再否则下载捆绑版并强制使用。-///-/// 用户 pnpm 过旧(8/9:不读 pnpm-workspace.yaml 的 autoInstallPeers、有-/// workspace-root gate;corepack shim 在 Node 24 上还会 ERR_INVALID_THIS 崩溃)-/// 或版本不可探测 → 走捆绑版。-async fn ensure_pnpm(- app_handle: &AppHandle,- window: &WebviewWindow,- owner: ProcessOwner,-) -> Result<bool, String> {- // 档案的 node_modules 由哪个 pnpm 主版本创建(.modules.yaml 的 storeDir 段)- let store_major = profile_store_major(app_handle);- let user_major = user_pnpm_major_version_bounded(app_handle, owner).await?;-- // 1) store 主版本已知 → 优先选与 store 一致的 pnpm(用户版或捆绑版)- if let Some(store) = store_major {- if user_major == Some(store) {- log::info!("Reusing user-installed pnpm (major {store}) matching profile store");- return Ok(false);- }- if bundled_pnpm_major(app_handle) == Some(store) {- log::info!("Using bundled pnpm (major {store}) matching profile store");- return Ok(true);- }- log::warn!(- "No pnpm matches profile store major {store} (user {user_major:?}), falling back to user pnpm"- );- }-- // 2) store 未知(全新档案/未装过依赖)或无可匹配版本 → 用户 pnpm ≥ 10 优先- match user_major {- Some(major) if major >= MIN_TRUSTED_PNPM_MAJOR => {- log::info!("Reusing user-installed pnpm (major {major}) for plugin install");- return Ok(false);- }- Some(major) => {- log::warn!(- "User pnpm major {major} < {MIN_TRUSTED_PNPM_MAJOR} (missing autoInstallPeers/workspace-root semantics), using bundled pnpm"- );- }- None => {- log::warn!(- "User pnpm version not detectable (broken/blocked shim?), using bundled pnpm"- );- }- }-- // 捆绑版已存在 → 直接用(零额外下载);否则下载。- if config::get_pnpm_binary_path(app_handle).exists() {- return Ok(true);- }-- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: "[pnpm] bundled pnpm not found, downloading before plugin install".to_string(),- },- );-- let tracker = download::ProgressTracker::new(window, 2);- let url = download::Pnpm.get_download_url()?;- let name = url.split('/').next_back().unwrap_or(&url).to_string();- let buffer = download::download_file(&tracker, url)- .await- .map_err(|e| format!("PNPM_DOWNLOAD_FAILED: {e}"))?;- download::verify_sha256(&buffer, config::PNPM_SHA256)- .map_err(|e| format!("PNPM_INTEGRITY_FAILED: {e}"))?;- let dest = download::Pnpm.get_install_path(app_handle);-- download::ensure_extract(&tracker, name, buffer, dest)- .await- .map_err(|e| format!("PNPM_EXTRACT_FAILED: {e}"))?;-- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: "[pnpm] bundled pnpm ready".to_string(),- },- );- Ok(true)-}--async fn user_pnpm_major_version_bounded(- app_handle: &AppHandle,- owner: ProcessOwner,-) -> Result<Option<u32>, String> {- let Some(pnpm) = cli::find_user_pnpm(app_handle) else {- return Ok(None);- };- let node = config::get_node_binary_path(app_handle);- let mut command = std::process::Command::new(&pnpm);- command.arg("--version");- if let Some(path) = pnpm_probe_path(&pnpm, Some(&node)) {- command.env("PATH", path);- }- #[cfg(windows)]- {- use std::os::windows::process::CommandExt;- command.creation_flags(0x0800_0000);- }- #[cfg(unix)]- {- use std::os::unix::process::CommandExt;- command.process_group(0);- }-- let process_guard = acquire_process_lock().await?;- let child = match command- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped())- .spawn()- {- Ok(child) => child,- Err(error) => {- log::warn!(- "pnpm version probe failed to spawn {}: {error}",- pnpm.display()- );- return Ok(None);- }- };- let pid = child.id();- let pid_guard = PidGuard::set(owner, pid);- let mut waiter = tauri::async_runtime::spawn_blocking(move || {- let mut child = child;- let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- wait_for_probe_output(&mut child)- }))- .unwrap_or_else(|_| {- super::cancel::terminate_pid_tree(pid);- ProbeWaitResult::CleanupPending {- pid,- reason: format!(- "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe pid {pid} panicked before cleanup completed"- ),- }- });- match result {- ProbeWaitResult::Finished(result) => ProbeTaskResult::Finished(result),- ProbeWaitResult::CleanupPending { pid, reason } => {- ProbeTaskResult::CleanupPending { child, pid, reason }- }- }- });-- let output = match tokio::time::timeout(PNPM_PROBE_TIMEOUT, &mut waiter).await {- Ok(joined) => {- let Some(task) = probe_task_or_fallback(&pnpm, joined) else {- let reason =- "PNPM_PROBE_WAIT_TASK_FAILED: pnpm version probe wait task failed".to_string();- monitor_orphaned_probe_pid(owner, pid, reason, process_guard, pid_guard);- return Ok(None);- };- match task {- ProbeTaskResult::Finished(waited) => {- match probe_output_or_fallback(&pnpm, waited)? {- Some(output) => output,- None => return Ok(None),- }- }- ProbeTaskResult::CleanupPending { child, pid, reason } => {- let pending = ProbeCleanupPending {- child,- pid,- reason,- owner,- _process_guard: process_guard,- _pid_guard: pid_guard,- };- let reason = pending.reason.clone();- monitor_probe_cleanup(pending);- return Err(reason);- }- }- }- Err(_) => {- let reason = format!(- "PNPM_PROBE_TIMEOUT: pnpm version probe exceeded {} seconds",- PNPM_PROBE_TIMEOUT.as_secs()- );- log::error!("{reason}");- super::process::mark_process_cleanup_failed(owner, reason.clone());- super::cancel::terminate_owned_install(owner).await;- let cleanup = match tokio::time::timeout(PNPM_PROBE_CLEANUP_TIMEOUT, &mut waiter).await- {- Ok(cleanup) => cleanup,- Err(_) => {- let cleanup_reason =- "PNPM_PROBE_CLEANUP_TIMEOUT: pnpm version probe did not exit after forced termination"- .to_string();- monitor_probe_wait_task(- waiter,- owner,- pid,- cleanup_reason.clone(),- process_guard,- pid_guard,- );- return Err(cleanup_reason);- }- };- match cleanup {- Ok(ProbeTaskResult::Finished(_)) => {- super::process::clear_process_cleanup_failed(owner);- return Err(reason);- }- Ok(ProbeTaskResult::CleanupPending { child, pid, reason }) => {- let pending = ProbeCleanupPending {- child,- pid,- reason,- owner,- _process_guard: process_guard,- _pid_guard: pid_guard,- };- let cleanup_reason = pending.reason.clone();- monitor_probe_cleanup(pending);- return Err(cleanup_reason);- }- Err(error) => {- monitor_orphaned_probe_pid(- owner,- pid,- format!(- "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe wait task failed during cleanup: {error}"- ),- process_guard,- pid_guard,- );- return Err(format!(- "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe wait task failed during cleanup: {error}"- ));- }- }- }- };- Ok(parse_pnpm_major_output(&pnpm, &output))-}--enum ProbeWaitResult {- Finished(std::io::Result<std::process::Output>),- CleanupPending { pid: u32, reason: String },-}--enum ProbeTaskResult {- Finished(std::io::Result<std::process::Output>),- CleanupPending {- child: std::process::Child,- pid: u32,- reason: String,- },-}--struct ProbeCleanupPending {- child: std::process::Child,- pid: u32,- reason: String,- owner: ProcessOwner,- _process_guard: tokio::sync::OwnedMutexGuard<()>,- _pid_guard: PidGuard,-}--impl ProbeCleanupPending {- fn release(self) {- let Self {- child,- owner,- _process_guard,- _pid_guard,- ..- } = self;- super::process::release_process_cleanup(owner, _pid_guard, _process_guard);- drop(child);- }-}--fn wait_for_probe_output(child: &mut std::process::Child) -> ProbeWaitResult {- let pid = child.id();- let stdout = child.stdout.take();- let stderr = child.stderr.take();- let stdout_reader = match std::thread::Builder::new()- .name("pnpm-probe-stdout".to_string())- .spawn(move || read_probe_pipe(stdout))- {- Ok(reader) => reader,- Err(error) => return reap_probe_after_wait_failure(child, pid, error),- };- let stderr_reader = match std::thread::Builder::new()- .name("pnpm-probe-stderr".to_string())- .spawn(move || read_probe_pipe(stderr))- {- Ok(reader) => reader,- Err(error) => return reap_probe_after_wait_failure(child, pid, error),- };-- let status = match child.wait() {- Ok(status) => status,- Err(error) => return reap_probe_after_wait_failure(child, pid, error),- };- let stdout = match join_probe_reader(stdout_reader) {- Ok(stdout) => stdout,- Err(error) => return ProbeWaitResult::Finished(Err(error)),- };- let stderr = match join_probe_reader(stderr_reader) {- Ok(stderr) => stderr,- Err(error) => return ProbeWaitResult::Finished(Err(error)),- };- ProbeWaitResult::Finished(Ok(std::process::Output {- status,- stdout,- stderr,- }))-}--fn reap_probe_after_wait_failure(- child: &mut std::process::Child,- pid: u32,- error: std::io::Error,-) -> ProbeWaitResult {- super::cancel::terminate_pid_tree(pid);- if let Err(kill_error) = child.kill() {- log::warn!("pnpm version probe kill after wait failure failed: {kill_error}");- }- let started = std::time::Instant::now();- loop {- match child.try_wait() {- Ok(Some(_)) => return ProbeWaitResult::Finished(Err(error)),- Ok(None) => {}- Err(cleanup_error) => {- log::warn!("pnpm version probe reap after wait failure failed: {cleanup_error}");- if super::process::plugin_process_has_exited(pid) {- return ProbeWaitResult::Finished(Err(error));- }- }- }- if started.elapsed() >= PNPM_PROBE_REAP_RETRY_TIMEOUT {- return ProbeWaitResult::CleanupPending {- pid,- reason: format!(- "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe pid {pid} could not be reaped after wait failure: {error}"- ),- };- }- std::thread::sleep(PNPM_PROBE_REAP_RETRY_INTERVAL);- }-}--fn monitor_probe_cleanup(mut pending: ProbeCleanupPending) {- super::process::mark_process_cleanup_failed(pending.owner, pending.reason.clone());- tauri::async_runtime::spawn(async move {- wait_for_probe_cleanup(&mut pending).await;- pending.release();- });-}--fn monitor_probe_wait_task(- waiter: tauri::async_runtime::JoinHandle<ProbeTaskResult>,- owner: ProcessOwner,- pid: u32,- reason: String,- process_guard: tokio::sync::OwnedMutexGuard<()>,- pid_guard: PidGuard,-) {- super::process::mark_process_cleanup_failed(owner, reason);- tauri::async_runtime::spawn(async move {- match waiter.await {- Ok(ProbeTaskResult::CleanupPending { child, pid, reason }) => {- let mut pending = ProbeCleanupPending {- child,- pid,- reason,- owner,- _process_guard: process_guard,- _pid_guard: pid_guard,- };- wait_for_probe_cleanup(&mut pending).await;- pending.release();- }- Ok(ProbeTaskResult::Finished(_)) => {- super::process::release_process_cleanup(owner, pid_guard, process_guard);- }- Err(error) => {- log::error!("pnpm version probe cleanup wait task failed: {error}");- wait_for_probe_cleanup_with(- || !super::process::plugin_process_has_exited(pid),- PNPM_PROBE_LIVENESS_INTERVAL,- )- .await;- super::process::release_process_cleanup(owner, pid_guard, process_guard);- }- }- });-}--fn monitor_orphaned_probe_pid(- owner: ProcessOwner,- pid: u32,- reason: String,- process_guard: tokio::sync::OwnedMutexGuard<()>,- pid_guard: PidGuard,-) {- super::process::mark_process_cleanup_failed(owner, reason);- super::cancel::terminate_pid_tree(pid);- tauri::async_runtime::spawn(async move {- wait_for_probe_cleanup_with(- || !super::process::plugin_process_has_exited(pid),- PNPM_PROBE_LIVENESS_INTERVAL,- )- .await;- super::process::release_process_cleanup(owner, pid_guard, process_guard);- });-}--async fn wait_for_probe_cleanup(pending: &mut ProbeCleanupPending) {- wait_for_probe_cleanup_with(- || match pending.child.try_wait() {- Ok(Some(_)) => false,- Ok(None) => true,- Err(error) => {- log::warn!(- "pnpm version probe cleanup monitor wait failed for pid {}: {error}",- pending.pid- );- !super::process::plugin_process_has_exited(pending.pid)- }- },- PNPM_PROBE_LIVENESS_INTERVAL,- )- .await;- log::info!(- "pnpm version probe cleanup monitor released pid {}",- pending.pid- );-}--async fn wait_for_probe_cleanup_with<F>(mut remains_active: F, interval: std::time::Duration)-where- F: FnMut() -> bool,-{- while remains_active() {- tokio::time::sleep(interval).await;- }-}--fn read_probe_pipe<R: Read>(pipe: Option<R>) -> std::io::Result<Vec<u8>> {- let mut output = Vec::new();- if let Some(mut pipe) = pipe {- pipe.read_to_end(&mut output)?;- }- Ok(output)-}--fn join_probe_reader(- reader: std::thread::JoinHandle<std::io::Result<Vec<u8>>>,-) -> std::io::Result<Vec<u8>> {- reader- .join()- .map_err(|_| std::io::Error::other("pnpm version probe output reader thread panicked"))?-}--fn log_probe_fallback(pnpm: &Path, phase: &str, error: impl std::fmt::Display) {- log::warn!(- "pnpm version probe {phase} failed for {}: {error}; falling back to bundled pnpm",- pnpm.display()- );-}--fn probe_task_or_fallback<T, E: std::fmt::Display>(pnpm: &Path, result: Result<T, E>) -> Option<T> {- match result {- Ok(task) => Some(task),- Err(error) => {- log_probe_fallback(pnpm, "wait task", error);- None- }- }-}--fn probe_output_or_fallback(- pnpm: &Path,- result: std::io::Result<std::process::Output>,-) -> Result<Option<std::process::Output>, String> {- match result {- Ok(output) => Ok(Some(output)),- Err(error) => {- log_probe_fallback(pnpm, "output", error);- Ok(None)- }- }-}--/// 用户 pnpm 主版本号(解析 `pnpm --version` 首个点分字段);不存在或不可运行-/// (corepack shim 在 Node 24 上 ERR_INVALID_THIS 崩溃等)返回 None。-///-/// 供 [`ensure_pnpm`] 选版与 [`super::verify`] 的修复选版共用(store 主版本匹配)。-pub(crate) fn user_pnpm_major_version(app_handle: &AppHandle) -> Option<u32> {- let pnpm = cli::find_user_pnpm(app_handle)?;- let node = config::get_node_binary_path(app_handle);- pnpm_major_version_at_with_node(&pnpm, Some(&node))-}--/// 探测精确 pnpm 可执行路径的主版本,供直接执行路径校验实际将运行的文件。-pub(crate) fn pnpm_major_version_at(pnpm: &Path) -> Option<u32> {- pnpm_major_version_at_with_node(pnpm, None)-}--/// 在受控 Node 环境中探测 pnpm 主版本。Windows GUI 进程继承的 PATH 可能早于-/// Node/pnpm 安装,而 corepack 的 `pnpm.cmd` 需要通过 PATH 调用 `node`;探测时-/// 必须注入桌面端已经选定的 Node 目录,否则会把健康 pnpm 误判为不可用(issue #182)。-fn pnpm_major_version_at_with_node(pnpm: &Path, node: Option<&Path>) -> Option<u32> {- let mut cmd = std::process::Command::new(pnpm);- cmd.arg("--version");- if let Some(path) = pnpm_probe_path(pnpm, node) {- cmd.env("PATH", path);- }- // 打包版是 GUI 进程(无控制台):版本探测不能弹出可见黑窗。- #[cfg(windows)]- {- use std::os::windows::process::CommandExt;- cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW- }- let output = match cmd.output() {- Ok(output) => output,- Err(error) => {- log::warn!(- "pnpm version probe failed to spawn {}: {error}",- pnpm.display()- );- return None;- }- };- parse_pnpm_major_output(pnpm, &output)-}--fn parse_pnpm_major_output(pnpm: &Path, output: &std::process::Output) -> Option<u32> {- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- log::warn!(- "pnpm version probe failed for {} with status {}: {}",- pnpm.display(),- output.status,- stderr.trim()- );- return None;- }- let stdout = String::from_utf8_lossy(&output.stdout);- stdout.split('.').next()?.trim().parse::<u32>().ok()-}--/// 构建 pnpm 探测专用 PATH:用户 pnpm 所在目录和选定 Node 目录前置,其余环境保留。-fn pnpm_probe_path(pnpm: &Path, node: Option<&Path>) -> Option<OsString> {- let mut paths = Vec::new();- // 选定 Node 必须位于 pnpm shim 目录之前:corepack 目录可能残留另一份 node,- // bare `node` 应与桌面端预检和后续插件命令使用同一运行时。- if let Some(parent) = node.and_then(Path::parent) {- paths.push(parent.to_path_buf());- }- if let Some(parent) = pnpm.parent() {- paths.push(parent.to_path_buf());- }- paths.extend(std::env::split_paths(- &std::env::var_os("PATH").unwrap_or_default(),- ));- std::env::join_paths(paths).ok()-}--/// 档案 `node_modules` 使用的 pnpm store 主版本(`<profile>/node_modules/.modules.yaml`-/// 的 `storeDir` 路径段,如 `...\store\v10` → 10)。-///-/// pnpm 10 与 11 的 store 布局互不兼容:用与 store 主版本不一致的 pnpm 更新-/// 已装插件会 `ERR_PNPM_UNEXPECTED_STORE` 退出。档案尚未安装过依赖(没有-/// node_modules)时返回 `None`,由调用方走"全新档案"逻辑。-/// 供 [`ensure_pnpm`] 选版与 [`super::verify`] 的修复选版共用。-pub(crate) fn profile_store_major(app_handle: &AppHandle) -> Option<u32> {- let modules_yaml = profile_dir(app_handle)- .join("node_modules")- .join(".modules.yaml");- let content = std::fs::read_to_string(modules_yaml).ok()?;- parse_store_major_from_modules_yaml(&content)-}--/// 从 `.modules.yaml` 文本解析 store 主版本(纯函数,便于单测)。-fn parse_store_major_from_modules_yaml(content: &str) -> Option<u32> {- let store_dir = content- .lines()- .find_map(|line| line.trim().strip_prefix("storeDir:").map(str::trim))?;- // storeDir 形如 `C:\Users\xx\AppData\Local\pnpm\store\v10`,取末段 `v10` 的数字- let major = store_dir- .trim_matches(['"', '\''])- .rsplit(['\\', '/'])- .next()?- .strip_prefix('v')?;- major.parse().ok()-}--/// 捆绑版 pnpm 的主版本(读 `dependencies/pnpm/package.json` 的 version 字段);-/// 未安装或清单缺失返回 None。-///-/// 供 [`ensure_pnpm`] 选版与 [`super::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()?;- let value: serde_json::Value = serde_json::from_str(&content).ok()?;- value- .get("version")?- .as_str()?- .split('.')- .next()?- .parse()- .ok()-}--/// 从 pnpm 失败输出中解析需写入构建放行白名单的包名/键集合。-///-/// 兼容 pnpm 10 与 11 的两套输出形式(两者对 git 托管插件 prepare 门禁的提示不同):-/// - pnpm 11(捆绑版)提示 `allowBuilds:\n <key>: true`(map 形式),原样采纳 `<key>`;-/// - pnpm 10(旧 store 复用用户版)提示 `onlyBuiltDependencies:\n - "<name>"`-/// (list 形式)与报错文本里的包名,二者归并取包名;-/// - 传递原生依赖被忽略构建(`Ignored build scripts:`)时,取其 `name@version` 的包名。-fn parse_allowlist_keys(output: &str) -> Vec<String> {- let mut keys: Vec<String> = Vec::new();- let lines: Vec<&str> = output.lines().collect();-- // 1) git 托管插件的允许键:跟随 `allowBuilds:` 示例行后的缩进 `<key>: true`。- // pnpm 11 的报错(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`)建议按此形式放行。- for (idx, line) in lines.iter().enumerate() {- if line.trim() == "allowBuilds:" {- if let Some(next) = lines.get(idx + 1) {- if let Some(key) = extract_allow_line_key(next) {- push_unique(&mut keys, key);- }- }- }- }-- // 2) 传递原生构建包名:`Ignored build scripts: <name>@<ver>, ...`。- for line in &lines {- if let Some(sub) = line.split("Ignored build scripts:").nth(1) {- for token in sub.split([',', ' ']) {- let token = token.trim();- if token.is_empty() {- continue;- }- // 版本号在最后一个 `@` 之后:scoped 包名(`@scope/name`)本身含 `@`,- // 必须从尾部切分才能保留完整包名,否则 `split('@').next()` 会得到空串。- let name = token- .rsplit_once('@')- .map_or(token, |(name, _)| name)- .trim();- if !name.is_empty() {- push_unique(&mut keys, name.to_string());- }- }- }- }-- // 3) pnpm 10 的 `onlyBuiltDependencies:` 列表(git 托管插件 prepare 门禁):- // onlyBuiltDependencies:- // - "dsh-better-sidebar"- for (idx, line) in lines.iter().enumerate() {- if line.trim() == "onlyBuiltDependencies:" {- for next in lines.iter().skip(idx + 1) {- let trimmed = next.trim_start();- if let Some(rest) = trimmed.strip_prefix('-') {- // 列表项:可能带缩进也可能不带(pnpm 提示段两种形式都出现过),- // 先于「顶层键」判定接受,避免无缩进条目被误当作顶层键提前退出。- let item = rest.trim().trim_matches(['"', '\'']);- if !item.is_empty() {- push_unique(&mut keys, item.to_string());- }- } else if !next.starts_with(' ')- && !next.starts_with('\t')- && !trimmed.is_empty()- && !trimmed.starts_with('#')- {- break; // 顶层键(无缩进且非列表项),已离开列表- }- // 其余(缩进行的非列表项、空行、注释):继续扫描- }- }- }-- // 4) pnpm 10 报错文本里的包名(`The git-hosted package "NAME@VER" ... "onlyBuiltDependencies" allowlist.`),- // 与第 3 步归并:即便列表被截断也能从消息取回名字。- for line in &lines {- if let Some(name) = extract_only_builds_git_name(line) {- push_unique(&mut keys, name);- }- }-- keys-}--/// 若 `line` 形如 ` <key>: true`(有缩进),返回 `<key>`(去缩进与后缀)。-/// pnpm 报出的 depPath 键本身不带引号,这里只做剥离该行格式。-fn extract_allow_line_key(line: &str) -> Option<String> {- let trimmed = line.trim_start();- if trimmed.len() == line.len() {- return None; // 无缩进,不是白名单条目- }- let suffix = trimmed.strip_suffix(": true")?;- let key = suffix.trim_end();- if key.is_empty() {- return None;- }- Some(key.to_string())-}--/// 去重追加:避免同一键在不同输出块被重复计为待放行项。-fn push_unique(keys: &mut Vec<String>, key: String) {- if !keys.iter().any(|k| k == &key) {- keys.push(key);- }-}--/// 从 pnpm 10 的 git 托管插件 prepare 门禁报错文本提取包名。-///-/// 形如 `The git-hosted package "NAME@VERSION" needs to execute build scripts-/// but is not in the "onlyBuiltDependencies" allowlist.`。-/// 仅匹配 `onlyBuiltDependencies` 形式的文本(pnpm 10);pnpm 11 的 `allowBuilds`-/// 形式仍由 [`extract_allow_line_key`] 解析 `allowBuilds:` 块,二者互不干扰。-fn extract_only_builds_git_name(line: &str) -> Option<String> {- if !line.contains("\"onlyBuiltDependencies\" allowlist") {- return None;- }- let marker = "The git-hosted package \"";- let start = line.find(marker)? + marker.len();- let rest = &line[start..];- let end = rest.find('"')?;- let quoted = &rest[..end]; // "name@version"- // 包名(含 scoped 前缀 `@scope/name`)在最末一个 `@` 之前,版本号在之后。- let (name, _version) = quoted.rsplit_once('@')?;- (!name.is_empty()).then(|| name.to_string())-}--/// 从 pnpm 11 的 git depPath 允许键(`name@<pkgResolutionId>`)提取纯包名;-/// 普通包名 / `name@version` 选择器原样返回。-///-/// pnpm 10 的 `onlyBuiltDependencies` 只按包名(或包名@版本)匹配,git depPath 里的-/// resolution id(`git+ssh://…` / `https://…` 等)对它没有意义,必须剥掉,否则该-/// 放行项在 pnpm 10 下不生效、git 插件的 prepare 构建仍会被构建门禁拦截。-fn dep_path_to_name(key: &str) -> String {- const GIT_RES_ID_MARKERS: &[&str] =- &["@git+", "@https://", "@http://", "@git://", "@github.com/"];- for marker in GIT_RES_ID_MARKERS {- if let Some(pos) = key.find(marker) {- return key[..pos].to_string();- }- }- key.to_string()-}--/// profile 下的 `pnpm-workspace.yaml` 路径($DSH_HOME/profiles/<当前档案>)。-///-/// 构建放行项必须写进**当前活动档案**的工作区配置:`dsh plugin --profile <档案>`-/// 驱动的 pnpm 只读取该档案目录下的 `pnpm-workspace.yaml`,写错路径(如全局或其它-/// 档案)会让放行项失效,安装/升级仍会被 pnpm 的构建门禁拦截。-fn profile_workspace_path(app_handle: &AppHandle) -> PathBuf {- profile_dir(app_handle).join("pnpm-workspace.yaml")-}--/// 把新的构建放行键合并写回 profile 的 `pnpm-workspace.yaml`,同时写入-/// `allowBuilds`(map,pnpm 11)与 `onlyBuiltDependencies`(list,pnpm 10)。-///-/// 用 YAML 库(serde_yaml)整体改写而非字符串拼接,避免格式错乱:-/// - 键(git depPath 含 `@`/`/`/`:`/`#`)由库自动按需加引号,不再手工拼;-/// - 已存在的同名键会被就地覆盖,不会残留占位值。-///-/// TODO(v1): 移除对旧版损坏文件(issue #49)的自愈逻辑。v1 起只解析干净配置,-/// `apply_allow_build_keys` 中解析失败后的「同键去重再解析」与-/// `collapse_allow_builds_duplicates` 一并删除。-///-/// 防御性修复:旧版本用字符串拼接可能留下「重复映射键」的损坏文件-/// (最多见的是 `node-pty: set this to true or false` 占位行与真正的-/// `'node-pty': true` 并存,见 issue #49)。此处解析失败时先做一次-/// `allowBuilds` 同键去重再解析,把损坏文件自愈回合法 YAML。-fn add_allow_build_keys(app_handle: &AppHandle, keys: &[String]) -> Result<(), String> {- let path = profile_workspace_path(app_handle);- let dir = path- .parent()- .ok_or("PREINSTALL_BAD_PROFILE_DIR: no profile dir")?;- std::fs::create_dir_all(dir).map_err(|e| format!("PREINSTALL_MKDIR: {e}"))?;-- let content = if path.exists() {- std::fs::read_to_string(&path).map_err(|e| format!("PREINSTALL_READ_WORKSPACE: {e}"))?- } else {- // 与 dsh `initProfile` 生成的基础模板保持一致(尚无 allowBuilds)。- "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n".to_string()- };-- let rendered = apply_allow_build_keys(&content, keys)?;- if rendered == content {- return Ok(()); // 无变化(所有键已就位),避免无意义写盘- }-- log::info!(- "pnpm-workspace.yaml rewritten with allowBuilds {keys:?} at {}",- path.display()- );- std::fs::write(&path, rendered).map_err(|e| format!("PREINSTALL_WRITE_WORKSPACE: {e}"))-}--/// 把新的构建放行键合并进 `pnpm-workspace.yaml` 文本并返回新文本。-///-/// 用 YAML 库(serde_yaml)整体改写而非字符串拼接,避免格式错乱:-/// - `allowBuilds`(pnpm 11)写为 map:键(git depPath 含 `@`/`/`/`:`/`#`)由库-/// 自动按需加引号,已存在的同名键会被就地覆盖为 `true`,不残留占位值、不产生重复键;-/// - `onlyBuiltDependencies`(pnpm 10)写为 list:追加唯一的包名,不清空已有条目。-///-/// 防御性修复:旧版本用字符串拼接可能留下「重复映射键」的损坏文件-/// (最多见的是 `node-pty: set this to true or false` 占位行与真正的-/// `'node-pty': true` 并存,见 issue #49)。此处先尝试严格解析;解析失败时-/// 做一次 `allowBuilds` 同键去重再解析,把损坏文件自愈回合法 YAML。-fn apply_allow_build_keys(content: &str, keys: &[String]) -> Result<String, String> {- // 先尝试严格解析。旧的损坏文件(重复映射键)严格解析会失败:- // 把 `allowBuilds` 内同名键去重(保留最后写入的值)后再解析,自愈损坏状态。- let mut repaired = false;- let mut doc: Value = match serde_yaml::from_str(content) {- Ok(v) => v,- Err(first_err) => {- let normalized = collapse_allow_builds_duplicates(content);- if normalized == content {- return Err(format!("PREINSTALL_WORKSPACE_INVALID_YAML: {first_err}"));- }- repaired = true;- serde_yaml::from_str(&normalized)- .map_err(|e| format!("PREINSTALL_WORKSPACE_INVALID_YAML: {e}"))?- }- };-- // 空/注释-only 内容解析为 `Value::Null`,视为全新空配置(pnpm-workspace.yaml- // 可加载的最小映射);其余非映射内容才是真正的损坏。- if doc.is_null() {- doc = Value::Mapping(Mapping::new());- }-- let map = doc.as_mapping_mut().ok_or_else(|| {- "PREINSTALL_WORKSPACE_NOT_MAP: pnpm-workspace.yaml must be a mapping".to_string()- })?;-- let allow_key = Value::String("allowBuilds".to_string());- if !map.contains_key(&allow_key) {- map.insert(allow_key.clone(), Value::Mapping(Mapping::new()));- }- let allow_builds = map- .get_mut(&allow_key)- .and_then(Value::as_mapping_mut)- .ok_or_else(|| {- "PREINSTALL_WORKSPACE_ALLOWBUILDS_NOT_MAP: allowBuilds must be a mapping".to_string()- })?;-- let mut dirty = false;- for key in keys {- let k = Value::String(key.clone());- if allow_builds.get(&k) == Some(&Value::Bool(true)) {- continue; // 已是 true,幂等跳过- }- // 直接覆盖旧值(含占位值/旧 false),由库负责按需加引号- allow_builds.insert(k, Value::Bool(true));- dirty = true;- }-- // `allowBuilds` 的借用已在上面循环结束后释放(NLL),此处才能对 `map`- // 再次取可变引用处理 `onlyBuiltDependencies`。- //- // pnpm 10(旧 store 复用的用户版)只认 `onlyBuiltDependencies`(list 形式,- // 见其报错提示),因此这里一并写回,保证 pnpm 10 / 11 两版都能读到放行项;- // `allowBuilds`(map 形式)覆盖 pnpm 11(捆绑版),二者共存互不冲突。- //- // 注意:pnpm 11 的 git 允许键是 `name@<pkgResolutionId>` 完整 depPath(按- // resolution id 匹配,只能写进 allowBuilds);pnpm 10 只按包名匹配,因此写入- // onlyBuiltDependencies 前必须经 [`dep_path_to_name`] 剥成纯包名。- let only_key = Value::String("onlyBuiltDependencies".to_string());- let to_add: Vec<Value> = {- let existing_only = map.get(&only_key).and_then(Value::as_sequence);- keys.iter()- .map(|k| dep_path_to_name(k))- .filter(|name| {- existing_only.map_or(true, |seq| !seq.contains(&Value::String(name.clone())))- })- .map(Value::String)- .collect()- };- if !to_add.is_empty() {- if !map.contains_key(&only_key) {- map.insert(only_key.clone(), Value::Sequence(Vec::new()));- }- let only_builds = map- .get_mut(&only_key)- .and_then(Value::as_sequence_mut)- .ok_or_else(|| {- "PREINSTALL_WORKSPACE_ONLYBUILT_NOT_SEQ: onlyBuiltDependencies must be a sequence"- .to_string()- })?;- for v in to_add {- only_builds.push(v);- dirty = true;- }- }- if !dirty && !repaired {- return Ok(content.to_string());- }- // 有键新增,或损坏文件已被自愈归一化——两种都要落回解析后的完整文档,- // 否则会把损坏的原始文本原样返回。-- serde_yaml::to_string(&doc).map_err(|e| format!("PREINSTALL_WORKSPACE_RENDER: {e}"))-}--/// 把损坏的 `allowBuilds` 映射(同一键出现多次)去重为合法 YAML。-///-/// 仅作为旧版字符串拼接遗留损坏(重复映射键,见 issue #49)的兜底归一化:-/// 扫描 `allowBuilds:` 之后、下一个顶层键之前的缩进 `key: value` 行,同一键-/// 只保留最后一次出现的行(与 YAML「后者覆盖前者」语义一致),其余行原样保留。-fn collapse_allow_builds_duplicates(content: &str) -> String {- let lines: Vec<&str> = content.lines().collect();- let mut in_allow = false;- // 记录(键 → 该键所有行的索引),用于去重- let mut key_indexes: HashMap<String, Vec<usize>> = HashMap::new();- let mut order: Vec<String> = Vec::new();-- for (idx, line) in lines.iter().enumerate() {- let trimmed = line.trim_start();- if trimmed == "allowBuilds:" {- in_allow = true;- continue;- }- if in_allow {- let is_indent = line.starts_with(' ') || line.starts_with('\t');- let is_comment = trimmed.starts_with('#');- if !is_indent || is_comment {- in_allow = false; // 遇到顶层键或注释即离开 allowBuilds- continue;- }- // 缩进的 `key: value` 行 → 提取键(冒号前)- if let Some(col) = trimmed.find(':') {- let key = trimmed[..col].trim().trim_matches(['\'', '"']);- if !key.is_empty() {- if !key_indexes.contains_key(key) {- order.push(key.to_string());- }- key_indexes.entry(key.to_string()).or_default().push(idx);- }- }- }- }-- // 每个键只保留最后一个出现行,其余标记删除- let mut keep: std::collections::HashSet<usize> = std::collections::HashSet::new();- for key in &order {- if let Some(idxs) = key_indexes.get(key) {- if let Some(&last) = idxs.last() {- keep.insert(last);- }- }- }- let mut out: Vec<&str> = Vec::with_capacity(lines.len());- for (idx, line) in lines.iter().enumerate() {- if key_indexes.values().any(|v| v.contains(&idx)) && !keep.contains(&idx) {- continue; // 是被去重掉的重复键行- }- out.push(line);- }- // 避免重复键里夹带的空行粘连成异常空行:去掉去重区(allowBuilds 段)的连续空行- out.join("\n")-}--/// 把 `github:owner/repo[#ref]` 一类的 GitHub 简写规范为显式 HTTPS 依赖形式-/// (`git+https://github.com/owner/repo.git[#ref]`)。-///-/// 动机:pnpm 解析 GitHub 简写时,「HTTPS 可达性探测一旦失败就回退 git+ssh」-/// 是已知缺陷(issue #3948 / #7243 / #13276,官方已 accepted 仍未修)。公开仓库-/// 一旦落进 git+ssh,在无 SSH 配置的桌面机上(非交互子进程无法应答 known_hosts-/// 询问)必然硬失败。规范为显式 `git+https:` 后 pnpm 直接走 HTTPS 克隆,绕开该-/// 回退;非 `github:` 形式(如纯 npm 包名)原样返回。-fn normalize_git_spec(spec: &str) -> String {- let Some(rest) = spec.strip_prefix("github:") else {- return spec.to_string();- };- let (path, fragment) = match rest.split_once('#') {- Some((p, f)) => (p.trim_end_matches('/'), Some(f)),- None => (rest.trim_end_matches('/'), None),- };- let mut repo = path.to_string();- if !repo.ends_with(".git") {- repo.push_str(".git");- }- let mut url = format!("git+https://github.com/{repo}");- if let Some(fragment) = fragment {- url.push('#');- url.push_str(fragment);- }- url-}--/// 给含空白字符的依赖 spec 加内嵌双引号,使其在 shell 拼接后仍保持单一 token。-///-/// **仅 Windows 需要引号。** `dsh plugin add` 在 JS 里用-/// `spawnSync("pnpm", args, { shell: process.platform === "win32" })` 启动 pnpm:-/// - Windows:`shell:true` 时 Node 只把参数按空格拼接、不做引号转义(官方文档-/// DEP0190:arguments are not escaped, only concatenated)。内置插件的依赖是-/// `link:<应用安装目录>`,而 Windows 安装目录常含空格(如-/// `G:\Deepseek Harness Desktop\resources\internal-plugins\dsh-tauri`),拼进-/// shell 后会被切碎成多个 spec,pnpm 报 `ERR_PNPM_SPEC_NOT_SUPPORTED` / 装成-/// 错误依赖,导致启动自愈每轮都重装(死循环)。包一层双引号让 cmd 把整条-/// spec 视为一个参数;pnpm 解析后自行剥离引号,落盘 `package.json` 的值仍是-/// 不带引号的规范 `link:<路径>`(与 [`super::preset::bundled_dep_spec`] 的-/// 内核对账一致)。-/// - macOS / Linux:`shell:false`,pnpm 以 argv 数组直接启动、空格天然保留,-/// **加引号反而把字面 `"` 当成包名的一部分传给 pnpm → 非法 spec → exit 1**。-/// 这是 issue #104 的根因:内置插件指向 `/Applications/Deepseek Harness-/// Desktop.app/...`(含空格),每次启动自愈重装都失败、服务永远缺该插件。-///-/// 因此只在 `cfg!(windows)` 且 spec 含空白时才包引号——普通 npm 包名 /-/// `git+https://...` 无空格,原样透传,避免无谓改动。-fn shell_quote_spec(spec: &str) -> String {- #[cfg(windows)]- {- if spec.chars().any(|c| c == ' ' || c == '\t') {- return format!("\"{spec}\"");- }- }- spec.to_string()-}--/// 从 pnpm 失败输出里识别网络错误,返回稳定提示,避免把网络问题误报为 dsh-/// 子进程错误。代理、DNS、连接超时和 TLS 失败都属于此类。-fn network_error_hint(output: &str) -> Option<&'static str> {- const SIGNALS: &[&str] = &[- "eai_again",- "enotfound",- "econnrefused",- "econnreset",- "etimedout",- "network timeout",- "network request failed",- "fetch failed",- "unable to verify the first certificate",- "self signed certificate",- "socket hang up",- "could not resolve host",- "failed to connect",- "connection timed out",- "connection reset",- ];- let lower = output.to_ascii_lowercase();- SIGNALS- .iter()- .any(|signal| lower.contains(signal))- .then_some("网络连接失败,请检查网络或代理设置后重试。")-}--fn git_transport_hint(output: &str) -> Option<&'static str> {- const SIGNALS: &[(&str, &str)] = &[- (- "host key verification failed",- "git fell back to SSH and could not verify GitHub's host key (no known_hosts entry; the process ran non-interactively). Make sure GitHub is reachable over HTTPS.",- ),- (- "permission denied (publickey)",- "git reached GitHub over SSH instead of HTTPS (Permission denied (publickey)) — usually your git config rewrites GitHub HTTPS to SSH (url.<base>.insteadOf) while no SSH key is configured. The desktop app isolates git config to force HTTPS for plugin installs; if you still see this, remove that rewrite (git config --global --unset-all '[email protected]:.insteadOf') or configure an SSH key.",- ),- (- "could not read from remote repository",- "pnpm could not read from the git remote — commonly a git+ssh transport failure. Ensure GitHub is reachable over HTTPS.",- ),- (- "ssh: connect to host",- "pnpm tried to reach GitHub over SSH (port 22) and the connection was refused. Use HTTPS instead.",- ),- ];- let lower = output.to_ascii_lowercase();- SIGNALS- .iter()- .find(|(sig, _)| lower.contains(sig))- .map(|(_, hint)| *hint)-}--/// 决定 Harness 服务进程启动时是否应注入 `DSH_PREFER_BUNDLED_PNPM=1`-/// (轻量缓解,issue #69 系列:让 dsh-market 子进程的 pnpm 走与桌面端插件安装-/// 同一套受控策略,而非落到系统 pnpm 引发 store 不兼容 / 无 TTY / allowBuilds 门禁)。-///-/// 与 [`ensure_pnpm`] 的版本感知保持一致,但**启动阶段绝不触发下载**:捆绑版尚未-/// 安装时返回 false(交由用户 pnpm,shim 默认用户优先)。仅当捆绑版已安装且满足-/// 下列任一条件才强制捆绑版:-/// - 档案 store 主版本已知且 == 捆绑版主版本,且用户 pnpm 主版本 != store-/// (否则用户版会 `ERR_PNPM_UNEXPECTED_STORE`);-/// - store 未知(全新档案)且用户 pnpm 缺失或过旧(< `MIN_TRUSTED_PNPM_MAJOR`)。-pub(crate) fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> bool {- let store_major = profile_store_major(app_handle);- let user_major = user_pnpm_major_version(app_handle);- let bundled_major = bundled_pnpm_major(app_handle);- // 捆绑版未安装 → 无法强制,交还用户 pnpm(shim 默认用户优先)- if !config::get_pnpm_binary_path(app_handle).exists() {- return false;- }- match store_major {- Some(store) => bundled_major == Some(store) && user_major != Some(store),- None => match user_major {- Some(major) if major >= MIN_TRUSTED_PNPM_MAJOR => false,- _ => true,- },- }-}--#[cfg(test)]-mod tests {- #[cfg(unix)]- use super::pnpm_major_version_at;- #[cfg(windows)]- use super::pnpm_major_version_at_with_node;- use super::{- append_command_output, apply_allow_build_keys, collapse_allow_builds_duplicates,- declared_main_entry, dep_path_to_name, deprecated_installed_names, diagnostic_suffix,- extract_allow_line_key,- extract_only_builds_git_name, git_transport_hint, has_github_ssh_rewrite_in_output,- normalize_git_spec, parse_allowlist_keys, parse_store_major_from_modules_yaml,- preset_spec_for_install, probe_output_or_fallback, probe_task_or_fallback, read_probe_pipe,- rewrite_rule_targets_ssh_github, shell_quote_spec, silent_install_failure_detail,- wait_for_probe_cleanup_with, PreinstallPluginInfo,- };- use std::path::PathBuf;-- #[test]- fn pnpm_probe_wait_and_output_failures_fall_back_to_bundled() {- let pnpm = PathBuf::from("broken-pnpm");- let output = probe_output_or_fallback(- &pnpm,- Err(std::io::Error::new(- std::io::ErrorKind::BrokenPipe,- "output pipe closed",- )),- )- .unwrap();-- assert!(output.is_none());- }-- #[test]- fn pnpm_probe_wait_task_join_failure_falls_back_to_bundled() {- let pnpm = PathBuf::from("broken-pnpm");- let task: Option<()> = probe_task_or_fallback(&pnpm, Err("blocking worker dropped"));- assert!(task.is_none());- }-- #[tokio::test]- async fn pnpm_probe_cleanup_monitor_releases_after_process_disappears() {- let polls = std::sync::atomic::AtomicUsize::new(0);- tokio::time::timeout(- std::time::Duration::from_millis(50),- wait_for_probe_cleanup_with(- || polls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,- std::time::Duration::from_millis(1),- ),- )- .await- .expect("cleanup monitor should release after liveness turns false");- assert_eq!(polls.load(std::sync::atomic::Ordering::SeqCst), 3);- }-- #[tokio::test]- async fn pnpm_probe_cleanup_monitor_stays_fail_closed_while_process_lives() {- let pending = tokio::time::timeout(- std::time::Duration::from_millis(5),- wait_for_probe_cleanup_with(|| true, std::time::Duration::from_millis(1)),- )- .await;- assert!(pending.is_err());- }-- struct BrokenPipeReader;-- impl std::io::Read for BrokenPipeReader {- fn read(&mut self, _buffer: &mut [u8]) -> std::io::Result<usize> {- Err(std::io::Error::new(- std::io::ErrorKind::BrokenPipe,- "probe output pipe closed",- ))- }- }-- #[test]- fn pnpm_probe_broken_output_pipe_is_reported_as_fallback_failure() {- let error = read_probe_pipe(Some(BrokenPipeReader)).unwrap_err();- assert_eq!(error.kind(), std::io::ErrorKind::BrokenPipe);- }-- #[cfg(unix)]- #[test]- fn pnpm_major_version_at_probes_the_exact_selected_path() {- use std::os::unix::fs::PermissionsExt;- use std::time::{SystemTime, UNIX_EPOCH};-- let nonce = SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap()- .as_nanos();- let root =- std::env::temp_dir().join(format!("dsh-pnpm-major-{}-{nonce}", std::process::id()));- std::fs::create_dir_all(&root).unwrap();- let selected = root.join("selected-pnpm");- let other = root.join("other-pnpm");- std::fs::write(&selected, "#!/bin/sh\nprintf '11.2.0\\n'\n").unwrap();- std::fs::write(&other, "#!/bin/sh\nprintf '10.9.0\\n'\n").unwrap();- for path in [&selected, &other] {- let mut permissions = std::fs::metadata(path).unwrap().permissions();- permissions.set_mode(0o700);- std::fs::set_permissions(path, permissions).unwrap();- }-- assert_eq!(pnpm_major_version_at(&selected), Some(11));- assert_eq!(pnpm_major_version_at(&other), Some(10));- let _ = std::fs::remove_dir_all(root);- }-- /// 回归 Windows GUI 的陈旧 PATH:pnpm shim 必须解析到桌面端选定的 Node,- /// 即使 shim 同目录存在冲突的 node,且路径包含空格和 shell 元字符。- #[cfg(windows)]- #[test]- fn pnpm_major_version_probe_injects_selected_node_for_cmd_shim() {- use std::time::{SystemTime, UNIX_EPOCH};-- let nonce = SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap()- .as_nanos();- let root =- std::env::temp_dir().join(format!("dsh pnpm cmd major {} {nonce}", std::process::id()));- let pnpm_dir = root.join("pnpm & corepack");- let node_dir = root.join("selected node");- std::fs::create_dir_all(&pnpm_dir).unwrap();- std::fs::create_dir_all(&node_dir).unwrap();- let selected = pnpm_dir.join("pnpm.cmd");- let node = node_dir.join("node.cmd");- std::fs::write(&selected, "@echo off\r\nnode --version\r\n").unwrap();- // shim 目录里的冲突运行时若优先会输出 9;选定 Node 必须抢在它前面。- std::fs::write(pnpm_dir.join("node.cmd"), "@echo off\r\necho 9.0.0\r\n").unwrap();- std::fs::write(&node, "@echo off\r\necho 11.24.0\r\n").unwrap();-- assert_eq!(- pnpm_major_version_at_with_node(&selected, Some(&node)),- Some(11)- );- let _ = std::fs::remove_dir_all(root);- }-- /// 构造预设条目的测试助手(internal 由各用例显式指定)- fn preset(id: &str, spec: &str, internal: bool) -> PreinstallPluginInfo {- PreinstallPluginInfo {- id: id.into(),- spec: spec.into(),- package: None,- name: String::new(),- description: String::new(),- repo_url: String::new(),- recommended: false,- fix: false,- default_checked: false,- win_only: false,- internal,- deprecated: false,- }- }-- #[test]- fn deprecated_installed_only_picks_marked_and_installed() {- // 只把 `dsh-ok` 视为已安装,其余一律未安装(便于区分「标记但未安装」)。- let installed = |name: &str| matches!(name, "dsh-ok" | "@scope/deprecated");-- // 命中:deprecated 且已安装 → 返回实际安装包名(dsh-ok 未声明 package,回落 id)- let mut deprecated = preset("dsh-ok", "dshmarket", false);- deprecated.deprecated = true;- assert_eq!(- deprecated_installed_names(&[deprecated], installed),- vec!["dsh-ok".to_string()]- );-- // scoped 包:返回真实安装包名(与预设 id 不一致)- let mut scoped = preset("dsh-scoped", "github:x/y", false);- scoped.deprecated = true;- scoped.package = Some("@scope/deprecated".into());- assert_eq!(- deprecated_installed_names(&[scoped], installed),- vec!["@scope/deprecated".to_string()]- );-- // 未标记 deprecated:即使已安装也不命中- let plain = preset("dsh-plain", "dsh-plain", false);- assert!(deprecated_installed_names(&[plain], installed).is_empty());-- // 标记了但未安装:不命中- let mut absent = preset("dsh-not-installed", "dshmarket", false);- absent.deprecated = true;- assert!(deprecated_installed_names(&[absent], installed).is_empty());-- // 内部插件即使标记 deprecated 也不命中(内部插件由启动自愈强制安装)- let mut internal = preset("dsh-internal", "[email protected]", true);- internal.deprecated = true;- assert!(- deprecated_installed_names(&[internal], |name| matches!(name, "dsh-internal")).is_empty()- );- }-- #[test]- fn diagnostic_suffix_preserves_non_allowbuilds_failure() {- assert_eq!(diagnostic_suffix(""), "");- assert_eq!(- diagnostic_suffix("ERR_PNPM_LINKING_FAILED: stale symlink"),- ": ERR_PNPM_LINKING_FAILED: stale symlink"- );- }-- #[test]- fn install_spec_passthrough_for_regular_preset() {- // 普通插件:spec 原样返回,与捆绑目录无关- let p = preset("dshmarket", "dshmarket", false);- assert_eq!(preset_spec_for_install(&p, None).unwrap(), "dshmarket");- assert_eq!(- preset_spec_for_install(&p, Some(PathBuf::from("/ignored"))).unwrap(),- "dshmarket"- );- }-- #[test]- fn install_spec_uses_bundled_dir_for_internal_preset() {- // 内置插件:安装依赖为 link:<捆绑目录>(正斜杠规范形;pnpm 对- // `file:D:/...` 的盘符绝对路径会按相对解析,必须用 `link:`)- let p = preset("dsh-tauri", "[email protected]", true);- let dir = PathBuf::from("C:\\Apps\\dsh\\resources\\internal-plugins\\dsh-tauri");- assert_eq!(- preset_spec_for_install(&p, Some(dir)).unwrap(),- "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri"- );- }-- #[test]- fn install_spec_errors_when_internal_bundle_missing() {- // 内置插件捆绑目录缺失:发布缺陷,显式报错而非静默走 npm/git spec- let p = preset("dsh-tauri", "[email protected]", true);- let err = preset_spec_for_install(&p, None).unwrap_err();- assert!(err.starts_with("BUNDLED_PLUGIN_MISSING"));- assert!(err.contains("dsh-tauri"));- }-- /// 验证命令无输出且产物缺失时,会同时报告预期清单路径和可操作提示。- #[test]- fn silent_install_failure_reports_empty_output_and_expected_artifact() {- let missing = vec![(- "dsh-win-terminal-inspector".to_string(),- PathBuf::from(- "C:\\Users\\test\\.dsh\\profiles\\web\\node_modules\\dsh-win-terminal-inspector\\package.json",- ),- )];-- let detail = silent_install_failure_detail(&missing, " \r\n");-- assert!(detail.starts_with("PREINSTALL_SILENT_FAIL:"));- assert!(detail.contains("dsh-win-terminal-inspector"));- assert!(detail.contains("package.json"));- assert!(detail.contains("produced no output"));- assert!(detail.contains("Retry the installation"));- }-- /// 验证已有命令日志时,引导用户查看日志而不会误报为完全无输出。- #[test]- fn silent_install_failure_points_to_existing_command_log() {- let missing = vec![(- "dshmarket".to_string(),- PathBuf::from("/tmp/profile/node_modules/dshmarket/package.json"),- )];-- let detail = silent_install_failure_detail(&missing, "pnpm completed\n");-- assert!(detail.contains("Review the preinstall log above"));- assert!(!detail.contains("produced no output"));- }-- /// 验证最终重试无输出时,早期尝试产生的诊断不会被覆盖丢失。- #[test]- fn command_output_retains_earlier_retry_diagnostics() {- let mut output = String::new();- append_command_output(&mut output, "ERR_PNPM_IGNORED_BUILDS");- append_command_output(&mut output, "");-- assert_eq!(output, "ERR_PNPM_IGNORED_BUILDS");- }-- #[test]- fn store_major_parsed_from_modules_yaml() {- // 真实 pnpm v10 写入的 .modules.yaml:storeDir 指向 store\v10- let content = "\-lockfileVersion: '9.0'-settings:- autoInstallPeers: true- excludeLinksFromLockfile: false-dependencies:- '@deepseek-ai/dsh-base': 0.0.4- '@deepseek-ai/dsh-web-app': 0.0.4-storeDir: C:\\Users\\test\\AppData\\Local\\pnpm\\store\\v10-virtualStoreDir: node_modules/.pnpm-";- assert_eq!(parse_store_major_from_modules_yaml(content), Some(10));- }-- #[test]- fn store_major_supports_unix_and_quoted_paths() {- assert_eq!(- parse_store_major_from_modules_yaml(- "storeDir: /home/test/.local/share/pnpm/store/v11\n"- ),- Some(11)- );- assert_eq!(- parse_store_major_from_modules_yaml("storeDir: \"C:\\\\pnpm store\\\\v3\"\n"),- Some(3)- );- }-- #[test]- fn store_major_missing_when_no_store_dir() {- // 档案尚未装过依赖:无 storeDir 段 → None- assert_eq!(- parse_store_major_from_modules_yaml("lockfileVersion: '9.0'\n"),- None- );- assert_eq!(parse_store_major_from_modules_yaml(""), None);- assert_eq!(- parse_store_major_from_modules_yaml("storeDir: C:\\Users\\x\\pnpm\\store\n"),- None- );- }-- #[test]- fn parse_git_dep_path_key() {- let out = "\-[ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED] Failed to prepare git-hosted package fetched from \"...\"-The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"allowBuilds\" allowlist.-...-allowBuilds:- dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89: true-";- let keys = parse_allowlist_keys(out);- assert!(keys.contains(- &"dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"- .to_string()- ));- assert!(!keys.contains(&"dsh-better-sidebar".to_string()));- }-- #[test]- fn parse_ignored_builds_name() {- let out = "[ERR_PNPM_IGNORED_BUILDS] Ignored build scripts: [email protected]\n";- let keys = parse_allowlist_keys(out);- assert_eq!(keys, vec!["node-pty".to_string()]);- }-- #[test]- fn parse_ignored_builds_scoped_name() {- // 回归(CodeRabbit):scoped 原生依赖 `@scope/name@version` 必须保留完整包名,- // 不能按第一个 `@` 切分(那会得到空串导致该包被跳过、无法放行)。- let out = "[ERR_PNPM_IGNORED_BUILDS] Ignored build scripts: @deepseek-ai/[email protected], [email protected]\n";- let keys = parse_allowlist_keys(out);- assert_eq!(- keys,- vec!["@deepseek-ai/dsh-base".to_string(), "node-pty".to_string()]- );- }-- #[test]- fn parse_empty_when_irrelevant() {- let out = "everything looks fine output\nno allowlist here\n";- assert!(parse_allowlist_keys(out).is_empty());- }-- #[test]- fn parse_pnpm10_only_built_dependencies_list() {- // 回归(issue:预装插件在 pnpm 10 下报 ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED):- // pnpm 10(旧 store 复用的用户版)只输出 onlyBuiltDependencies 列表与报错文本- // 里的包名,不含 allowBuilds 块。此前 parse_allowlist_keys 只认 allowBuilds,- // 导致读不到 dsh-better-sidebar、不写白名单、重试也被跳过,安装必然失败。- let out = "\-[ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED] Failed to prepare git-hosted package fetched from \"https://codeload.github.com/omdsh-dev/DSH-better-sidebar/tar.gz/f9153dfc1ce47cf43445c1b351ee3ae47b4ad9f1\"-The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist.-...-This error happened while installing a direct dependency of C:\\Users\\hairy\\.dsh.dev\\profiles\\web-Add the package to \"onlyBuiltDependencies\" in your project's pnpm-workspace.yaml to allow it to run scripts. For example:-onlyBuiltDependencies:-- \"dsh-better-sidebar\"-";- let keys = parse_allowlist_keys(out);- assert_eq!(keys, vec!["dsh-better-sidebar".to_string()]);- }-- #[test]- fn parse_pnpm10_unindented_list_items() {- // 回归(CodeRabbit):pnpm 10 提示段可能不带缩进(`- "name"` 与顶层键同列)。- // 此前循环会把它误当顶层键提前退出,只靠报错文本回退解析才碰巧通过。- let out = "onlyBuiltDependencies:\n- \"dsh-better-sidebar\"\n";- let keys = parse_allowlist_keys(out);- assert_eq!(keys, vec!["dsh-better-sidebar".to_string()]);- }-- #[test]- fn parse_pnpm10_scoped_package_from_message() {- // 报错文本在列表被截断时也可取回名字;scoped 包名保留 `@scope/` 前缀。- let out = "The git-hosted package \"@deepseek-ai/[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist.\n";- let keys = parse_allowlist_keys(out);- assert_eq!(keys, vec!["@deepseek-ai/dsh-base".to_string()]);- }-- #[test]- fn extract_only_builds_git_name_strips_version_and_handles_scoped() {- // 普通包名:name@version → name- assert_eq!(- extract_only_builds_git_name(- "The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist."- ),- Some("node-pty".to_string())- );- // scoped 包名:@scope/name@version → @scope/name(只剥最末一个 @ 后的版本号)- assert_eq!(- extract_only_builds_git_name(- "The git-hosted package \"@deepseek-ai/[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist."- ),- Some("@deepseek-ai/dsh-base".to_string())- );- // pnpm 11 的 allowBuilds 文本不匹配(交由 allowBuilds 块解析)- assert_eq!(- extract_only_builds_git_name(- "The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"allowBuilds\" allowlist."- ),- None- );- // 非 git 门禁行不匹配- assert_eq!(- extract_only_builds_git_name("allowBuilds:\n x: true"),- None- );- }-- #[test]- fn dep_path_to_name_strips_git_resolution_keeps_plain_names() {- // git depPath(unscoped):剥掉 resolution id,保留纯包名- assert_eq!(- dep_path_to_name(- "dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"- ),- "dsh-better-sidebar"- );- // git depPath(scoped):同样只剥 resolution id,保留 `@scope/name`- assert_eq!(- dep_path_to_name(- "@deepseek-ai/dsh-base@git+https://github.com/deepseek-ai/dsh-base.git#abc123"- ),- "@deepseek-ai/dsh-base"- );- // 普通包名 / 包名@版本选择器:原样返回- assert_eq!(dep_path_to_name("node-pty"), "node-pty");- assert_eq!(dep_path_to_name("[email protected]"), "[email protected]");- assert_eq!(dep_path_to_name("@scope/pkg"), "@scope/pkg");- }-- #[test]- fn allow_line_key_requires_indent() {- let key = extract_allow_line_key(" node-pty: true");- assert_eq!(key.as_deref(), Some("node-pty"));-- // 无缩进(顶层键)不应被当作白名单条目- assert_eq!(extract_allow_line_key("packages:"), None);- assert_eq!(extract_allow_line_key("allowBuilds:"), None);- }-- // ---- 归并写回 pnpm-workspace.yaml(issue #49 回归)------ /// 从渲染结果里解析出单一 `allowBuilds` 映射,便于断言。- fn allow_builds_map(yaml: &str) -> serde_yaml::Mapping {- let doc: serde_yaml::Value = serde_yaml::from_str(yaml).expect("output must be valid YAML");- doc.get("allowBuilds")- .and_then(serde_yaml::Value::as_mapping)- .expect("allowBuilds must be a mapping")- .clone()- }-- #[test]- fn apply_adds_new_key_when_absent() {- let base = "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n";- // 无 allowBuilds 时首次写入- let out = apply_allow_build_keys(base, &["node-pty".to_string()]).unwrap();- let map = allow_builds_map(&out);- assert_eq!(map.get("node-pty"), Some(&serde_yaml::Value::Bool(true)));- // 顶级基础设置被保留- let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();- assert!(doc.get("packages").is_some());- assert!(doc.get("nodeLinker").is_some());- }-- #[test]- fn apply_is_idempotent_and_does_not_duplicate() {- // 已放行的键再次写入:结果不变(幂等、不产生重复键)。输入须同时包含- // allowBuilds 与 onlyBuiltDependencies 两个放行出口(桌面端双写,见- // apply_allow_build_keys),证明两处都幂等。- let base = "packages:\n - .\nnodeLinker: hoisted\nautoInstallPeers: false\nallowBuilds:\n node-pty: true\nonlyBuiltDependencies:\n - node-pty\n";- let out = apply_allow_build_keys(base, &["node-pty".to_string()]).unwrap();- assert_eq!(out, base);- }-- #[test]- fn apply_writes_both_allowbuilds_and_only_built_dependencies() {- // pnpm 11 认 allowBuilds(map),pnpm 10 认 onlyBuiltDependencies(list),- // 两者须同时写回,用户 pnpm 10 / 捆绑版 pnpm 11 都能读到放行项。- let base = "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n";- let out = apply_allow_build_keys(base, &["dsh-better-sidebar".to_string()]).unwrap();- let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();- // pnpm 11:allowBuilds 为 map 形式- assert_eq!(- doc["allowBuilds"]["dsh-better-sidebar"],- serde_yaml::Value::Bool(true)- );- // pnpm 10:onlyBuiltDependencies 为 list 形式- let only = doc- .get("onlyBuiltDependencies")- .and_then(serde_yaml::Value::as_sequence)- .expect("onlyBuiltDependencies must be a sequence");- assert_eq!(- only,- &vec![serde_yaml::Value::String("dsh-better-sidebar".to_string())]- );- // 基础设置被保留- assert!(doc.get("packages").is_some());- assert!(doc.get("nodeLinker").is_some());- }-- #[test]- fn apply_git_dep_path_writes_name_selector_for_pnpm10() {- // 回归(CodeRabbit):git 托管插件的完整 depPath 只写进 pnpm 11 的 allowBuilds- // (按 resolution id 匹配);pnpm 10 的 onlyBuiltDependencies 只按包名匹配,- // 必须剥成纯包名,否则 pnpm 10 读不到放行项、prepare 构建仍会被门禁拦截。- // 两个出口同时写好后,pnpm 10 / 11 之间切换都不会再次触发构建门禁。- let base = "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n";- let dep =- "dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"- .to_string();- let out = apply_allow_build_keys(base, &[dep.clone()]).unwrap();- let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();- // pnpm 11:allowBuilds 保留完整 depPath- assert_eq!(- doc["allowBuilds"][&serde_yaml::Value::String(dep)],- serde_yaml::Value::Bool(true)- );- // pnpm 10:onlyBuiltDependencies 只含纯包名- let only = doc- .get("onlyBuiltDependencies")- .and_then(serde_yaml::Value::as_sequence)- .expect("onlyBuiltDependencies must be a sequence");- assert_eq!(- only,- &vec![serde_yaml::Value::String("dsh-better-sidebar".to_string())]- );- }-- #[test]- fn apply_only_built_dependencies_preserves_existing_entries() {- // onlyBuiltDependencies 已含旧条目时,只追加新键、不清空原有条目。- let base = "packages:\n - .\nallowBuilds:\n esbuild: true\nonlyBuiltDependencies:\n - esbuild\n";- let out = apply_allow_build_keys(base, &["dsh-better-sidebar".to_string()]).unwrap();- let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();- let only = doc- .get("onlyBuiltDependencies")- .and_then(serde_yaml::Value::as_sequence)- .expect("onlyBuiltDependencies must be a sequence");- let names: Vec<&str> = only.iter().filter_map(|v| v.as_str()).collect();- assert_eq!(names, vec!["esbuild", "dsh-better-sidebar"]);- }-- #[test]- fn apply_quotes_git_dep_path_keys() {- let dep =- "dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"- .to_string();- // 空内容也能生成合法配置- let out = apply_allow_build_keys("", &[dep.clone()]).unwrap();- let map = allow_builds_map(&out);- assert_eq!(- map.get(&serde_yaml::Value::String(dep)),- Some(&serde_yaml::Value::Bool(true))- );- // 库负责正确加引号,键原样(含 @ / : / #)可回读- let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();- assert_eq!(- doc["allowBuilds"][&serde_yaml::Value::String(- "dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"- .to_string()- )],- serde_yaml::Value::Bool(true)- );- }-- #[test]- fn apply_overwrites_placeholder_value_without_duplicate() {- // 关键回归:旧版字符串拼接可能留下占位键 `node-pty: set this to true or false`- // 与真实键并存。若解析保留重复键,或解析失败被去重兜底,最终都必须只保留- // 一个 `node-pty: true`(不允许重复映射键)。- let corrupted =- "allowBuilds:\n 'dsh-better-sidebar@https://code...': true\n node-pty: set this to true or false\n 'node-pty': true\n";- let out = apply_allow_build_keys(corrupted, &["node-pty".to_string()]).unwrap();- let map = allow_builds_map(&out);- // 恰好只有一个 node-pty 键,值是 true(覆盖了占位值)- assert_eq!(map.get("node-pty"), Some(&serde_yaml::Value::Bool(true)));- // 序列化后全局不允许再出现“重复键”的等价行(node-pty 只出现一次)- let node_pty_keys = out- .lines()- .filter(|l| {- l.trim_start().starts_with("node-pty") || l.trim_start().starts_with("'node-pty'")- })- .count();- assert_eq!(node_pty_keys, 1);- }-- #[test]- fn collapse_dedupes_allow_builds_keys() {- let corrupted =- "packages:\n - .\nallowBuilds:\n node-pty: set this to true or false\n 'node-pty': true\n keep: true\n";- let normalized = collapse_allow_builds_duplicates(corrupted);- // 重复的 node-pty 只剩最后一个(值 true),同键不再重复- let node_pty = normalized- .lines()- .filter(|l| {- l.trim_start().starts_with("node-pty") || l.trim_start().starts_with("'node-pty'")- })- .count();- assert_eq!(node_pty, 1);- assert!(normalized.contains("keep"));- // 去重结果必须是合法 YAML,且能被后续解析- let out = apply_allow_build_keys(&normalized, &["node-pty".to_string()]).unwrap();- assert_eq!(- allow_builds_map(&out).get("node-pty"),- Some(&serde_yaml::Value::Bool(true))- );- }-- // ---- git GitHub 简写规范化(issue #51 根因绕行)------ #[test]- fn normalize_github_shorthand_to_git_https() {- assert_eq!(- normalize_git_spec("github:baihejiangnan/dsh-session-context-menu"),- "git+https://github.com/baihejiangnan/dsh-session-context-menu.git"- );- }-- #[test]- fn normalize_github_shorthand_preserves_ref_and_dedup_git_suffix() {- assert_eq!(- normalize_git_spec("github:omdsh-dev/DSH-better-sidebar#next"),- "git+https://github.com/omdsh-dev/DSH-better-sidebar.git#next"- );- // 已带 .git 不重复追加- assert_eq!(- normalize_git_spec("github:user/repo.git"),- "git+https://github.com/user/repo.git"- );- // 尾部多余斜杠剥掉- assert_eq!(- normalize_git_spec("github:user/repo/"),- "git+https://github.com/user/repo.git"- );- }-- #[test]- fn normalize_non_github_spec_passes_through() {- assert_eq!(normalize_git_spec("dshmarket"), "dshmarket");- assert_eq!(- normalize_git_spec("git+https://github.com/foo/bar.git"),- "git+https://github.com/foo/bar.git"- );- }-- // ---- spec 引号化(仅 Windows:dsh CLI 只在 win32 用 shell 拼接参数)------ #[cfg(windows)]- #[test]- fn shell_quote_quotes_spec_containing_spaces() {- // 安装目录含空格(如 G:\Deepseek Harness Desktop):整条 spec 加双引号,- // 使 dsh CLI 的 shell:true 拼接后仍被 shell 视为单一 token(DEP0190:- // Node 对 shell:true 只拼接不转义)- assert_eq!(- shell_quote_spec(- "link:G:/Deepseek Harness Desktop/resources/internal-plugins/dsh-tauri"- ),- "\"link:G:/Deepseek Harness Desktop/resources/internal-plugins/dsh-tauri\""- );- // 制表符同样触发- assert_eq!(shell_quote_spec("link:C:/x\ty"), "\"link:C:/x\ty\"");- }-- #[cfg(not(windows))]- #[test]- fn shell_quote_leaves_space_path_untouched_on_non_windows() {- // 回归(issue #104):macOS/Linux 上 dsh CLI 直接 spawnSync(shell:false),- // spec 作为一个 argv 传递、空格天然保留,绝不能加引号——字面 `"` 会成为- // 包名的一部分,pnpm 报非法 spec → exit 1 → 内置插件每次启动重装都失败。- assert_eq!(- shell_quote_spec("link:/Applications/Deepseek Harness Desktop.app/Contents/Resources/resources/internal-plugins/dsh-tauri-ui"),- "link:/Applications/Deepseek Harness Desktop.app/Contents/Resources/resources/internal-plugins/dsh-tauri-ui"- );- assert_eq!(- shell_quote_spec("link:/Users/me/my plugins/dsh-tauri"),- "link:/Users/me/my plugins/dsh-tauri"- );- }-- #[test]- fn shell_quote_leaves_space_free_spec_untouched() {- // 普通 npm 包名 / git HTTPS spec 无空格:原样透传,不引入多余引号- assert_eq!(shell_quote_spec("dshmarket"), "dshmarket");- assert_eq!(- shell_quote_spec("git+https://github.com/omdsh-dev/DSH-better-sidebar.git#next"),- "git+https://github.com/omdsh-dev/DSH-better-sidebar.git#next"- );- // 无空格的内置插件路径同样不被改动(保持与 internal.rs expected 一致)- assert_eq!(- shell_quote_spec("link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri"),- "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri"- );- }-- #[cfg(windows)]- #[test]- fn shell_quote_preserves_link_prefix_semantics() {- // 引号只包 path 部分也不影响 pnpm 解析(落盘值仍为不带引号的 link: 规范形)- let quoted = shell_quote_spec(- "link:G:/Deepseek Harness Desktop/resources/internal-plugins/dsh-tauri",- );- assert!(quoted.starts_with('"'));- assert!(quoted.ends_with('"'));- assert!(quoted.contains("Deepseek Harness Desktop"));- }-- // ---- git 传输层错误识别(区别于 allowBuilds 门禁)------ #[test]- fn git_transport_hint_detects_host_key_failure() {- let out = "git ls-remote \"git+ssh://[email protected]/foo.git\" HEAD\nHost key verification failed.\nfatal: Could not read from remote repository.\n";- assert!(git_transport_hint(out).is_some());- }-- #[test]- fn git_transport_hint_detects_publickey_and_ssh() {- assert!(git_transport_hint("[email protected]: Permission denied (publickey)").is_some());- assert!(- git_transport_hint("ssh: connect to host github.com port 22: Connection refused")- .is_some()- );- }-- #[test]- fn git_transport_hint_none_for_allowbuilds_output() {- // allowBuilds 场景(prepare 构建被拦)不应误判为传输层错误- let out = "[ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED] ...\nallowBuilds:\n node-pty: true\n";- assert!(git_transport_hint(out).is_none());- }-- // ---- 插件声明入口解析(构建产物核验)------ fn tmp_pkg_dir(name: &str) -> PathBuf {- let dir = std::env::temp_dir().join(format!(- "dsh-entry-test-{name}-{}",- std::process::id()- ));- let _ = std::fs::remove_dir_all(&dir);- std::fs::create_dir_all(&dir).unwrap();- dir- }-- #[test]- fn declared_main_prefers_dsh_plugin_manifest() {- let dir = tmp_pkg_dir("manifest");- std::fs::write(- dir.join("dsh.plugin.json"),- r#"{"id":"x","main":"./lib/index.js"}"#,- )- .unwrap();- std::fs::write(- dir.join("package.json"),- r#"{"name":"x","main":"dist/index.js"}"#,- )- .unwrap();- assert_eq!(- declared_main_entry(&dir).unwrap(),- dir.join("lib/index.js")- );- let _ = std::fs::remove_dir_all(&dir);- }-- #[test]- fn declared_main_falls_back_to_package_json() {- let dir = tmp_pkg_dir("pkgjson");- std::fs::write(- dir.join("package.json"),- r#"{"name":"x","main":"lib/index.js"}"#,- )- .unwrap();- assert_eq!(- declared_main_entry(&dir).unwrap(),- dir.join("lib/index.js")- );- let _ = std::fs::remove_dir_all(&dir);- }-- #[test]- fn declared_main_reads_exports_default() {- let dir = tmp_pkg_dir("exports");- std::fs::write(- dir.join("package.json"),- r#"{"name":"x","exports":{".":{"types":"./lib/types.d.ts","default":"./lib/index.js"}}}"#,- )- .unwrap();- assert_eq!(- declared_main_entry(&dir).unwrap(),- dir.join("lib/index.js")- );- let _ = std::fs::remove_dir_all(&dir);- }-- #[test]- fn declared_main_reads_exports_string_shorthand_and_require() {- let dir = tmp_pkg_dir("exports-shorthand");- std::fs::write(- dir.join("package.json"),- r#"{"name":"x","exports":"./dist/main.js"}"#,- )- .unwrap();- assert_eq!(- declared_main_entry(&dir).unwrap(),- dir.join("dist/main.js")- );- let _ = std::fs::remove_dir_all(&dir);-- let dir2 = tmp_pkg_dir("exports-require");- std::fs::write(- dir2.join("package.json"),- r#"{"name":"x","exports":{".":{"require":"./cjs/index.js"}}}"#,- )- .unwrap();- assert_eq!(- declared_main_entry(&dir2).unwrap(),- dir2.join("cjs/index.js")- );- let _ = std::fs::remove_dir_all(&dir2);- }-- #[test]- fn declared_main_rejects_escaping_or_absolute_entries() {- // `../` 逃逸与绝对路径都不应通过核验:防止把检查指向包外文件造成假通过- let dir = tmp_pkg_dir("escape");- std::fs::write(- dir.join("package.json"),- r#"{"name":"x","main":"../outside/index.js"}"#,- )- .unwrap();- assert!(declared_main_entry(&dir).is_none());- let absolute_entry = if cfg!(windows) {- "C:\\\\outside\\\\index.js"- } else {- "/outside/index.js"- };- std::fs::write(- dir.join("package.json"),- format!(r#"{{"name":"x","main":"{}"}}"#, absolute_entry),- )- .unwrap();- assert!(declared_main_entry(&dir).is_none());- let _ = std::fs::remove_dir_all(&dir);- }-- #[test]- fn declared_main_falls_through_broken_plugin_manifest() {- // dsh.plugin.json 存在但损坏/无 main 时,回落 package.json- let dir = tmp_pkg_dir("broken-plugin-manifest");- std::fs::write(dir.join("dsh.plugin.json"), r#"not-json"#).unwrap();- std::fs::write(- dir.join("package.json"),- r#"{"name":"x","main":"lib/index.js"}"#,- )- .unwrap();- assert_eq!(- declared_main_entry(&dir).unwrap(),- dir.join("lib/index.js")- );- let _ = std::fs::remove_dir_all(&dir);- }-- #[test]- fn declared_main_none_without_manifest() {- let dir = tmp_pkg_dir("none");- assert!(declared_main_entry(&dir).is_none());- let _ = std::fs::remove_dir_all(&dir);- }-- #[test]- fn rewrite_rule_targets_ssh_github_detects_common_rewrites() {- // GitHub 官方文档的经典写法:HTTPS -> SSH(scp 风格与 ssh:// 风格)- assert!(rewrite_rule_targets_ssh_github(- "[email protected]:.insteadof https://github.com/"- ));- assert!(rewrite_rule_targets_ssh_github(- "url.ssh://[email protected]/.insteadof https://github.com/"- ));- assert!(rewrite_rule_targets_ssh_github(- "url.git+ssh://[email protected]/.insteadof https://github.com"- ));- // http 同样属于被改写对象;value 无尾斜杠也能命中- assert!(rewrite_rule_targets_ssh_github(- "[email protected]:.insteadof http://github.com"- ));- // subsection 大小写保留、key 小写化后仍可识别- assert!(rewrite_rule_targets_ssh_github(- "[email protected]:.insteadOf https://github.com/"- ));- }-- #[test]- fn rewrite_rule_targets_ssh_github_ignores_harmless_rules() {- // 反向规则(ssh -> https)、非 GitHub 主机、https base 都不隔离- assert!(!rewrite_rule_targets_ssh_github(- "url.https://github.com/.insteadof [email protected]:"- ));- assert!(!rewrite_rule_targets_ssh_github(- "[email protected]:.insteadof https://gitlab.example.com/"- ));- assert!(!rewrite_rule_targets_ssh_github(- "url.ssh://[email protected]/.pushinsteadof https://github.com/"- ));- assert!(!rewrite_rule_targets_ssh_github(- "url.file:///c:/git/.insteadof https://github.com/"- ));- // 非 url 键与空行- assert!(!rewrite_rule_targets_ssh_github("core.autocrlf true"));- assert!(!rewrite_rule_targets_ssh_github(""));- assert!(!rewrite_rule_targets_ssh_github(" "));- }-- #[test]- fn has_github_ssh_rewrite_in_output_checks_all_lines() {- let harmful = "core.autocrlf true\nuser.name=x\[email protected]:.insteadof https://github.com/\n";- assert!(has_github_ssh_rewrite_in_output(harmful));- let clean = "core.autocrlf true\nuser.name=x\nurl.https://github.com/.insteadof [email protected]:\n";- assert!(!has_github_ssh_rewrite_in_output(clean));- assert!(!has_github_ssh_rewrite_in_output(""));- }-}diff --git a/src-tauri/src/service/plugin/install/allowlist.rs b/src-tauri/src/service/plugin/install/allowlist.rsnew file mode 100644index 00000000..f15cf9d5--- /dev/null+++ b/src-tauri/src/service/plugin/install/allowlist.rs@@ -0,0 +1,679 @@+//! pnpm 构建放行白名单(`allowBuilds` / `onlyBuiltDependencies`)解析与写回:+//! 从 pnpm 失败输出解析它建议的允许键,合并写回 profile 的+//! `pnpm-workspace.yaml`(pnpm 10 的 list 与 11 的 map 双写),并自愈旧版+//! 字符串拼接遗留的「重复映射键」损坏文件(issue #49)。++use std::collections::HashMap;+use std::path::PathBuf;+use tauri::AppHandle;++use serde_yaml::{Mapping, Value};++use super::profile_dir;++/// 从 pnpm 失败输出中解析需写入构建放行白名单的包名/键集合。+///+/// 兼容 pnpm 10 与 11 的两套输出形式(两者对 git 托管插件 prepare 门禁的提示不同):+/// - pnpm 11(捆绑版)提示 `allowBuilds:\n <key>: true`(map 形式),原样采纳 `<key>`;+/// - pnpm 10(旧 store 复用用户版)提示 `onlyBuiltDependencies:\n - "<name>"`+/// (list 形式)与报错文本里的包名,二者归并取包名;+/// - 传递原生依赖被忽略构建(`Ignored build scripts:`)时,取其 `name@version` 的包名。+pub(super) fn parse_allowlist_keys(output: &str) -> Vec<String> {+ let mut keys: Vec<String> = Vec::new();+ let lines: Vec<&str> = output.lines().collect();++ // 1) git 托管插件的允许键:跟随 `allowBuilds:` 示例行后的缩进 `<key>: true`。+ // pnpm 11 的报错(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`)建议按此形式放行。+ for (idx, line) in lines.iter().enumerate() {+ if line.trim() == "allowBuilds:" {+ if let Some(next) = lines.get(idx + 1) {+ if let Some(key) = extract_allow_line_key(next) {+ push_unique(&mut keys, key);+ }+ }+ }+ }++ // 2) 传递原生构建包名:`Ignored build scripts: <name>@<ver>, ...`。+ for line in &lines {+ if let Some(sub) = line.split("Ignored build scripts:").nth(1) {+ for token in sub.split([',', ' ']) {+ let token = token.trim();+ if token.is_empty() {+ continue;+ }+ // 版本号在最后一个 `@` 之后:scoped 包名(`@scope/name`)本身含 `@`,+ // 必须从尾部切分才能保留完整包名,否则 `split('@').next()` 会得到空串。+ let name = token+ .rsplit_once('@')+ .map_or(token, |(name, _)| name)+ .trim();+ if !name.is_empty() {+ push_unique(&mut keys, name.to_string());+ }+ }+ }+ }++ // 3) pnpm 10 的 `onlyBuiltDependencies:` 列表(git 托管插件 prepare 门禁):+ // onlyBuiltDependencies:+ // - "dsh-better-sidebar"+ for (idx, line) in lines.iter().enumerate() {+ if line.trim() == "onlyBuiltDependencies:" {+ for next in lines.iter().skip(idx + 1) {+ let trimmed = next.trim_start();+ if let Some(rest) = trimmed.strip_prefix('-') {+ // 列表项:可能带缩进也可能不带(pnpm 提示段两种形式都出现过),+ // 先于「顶层键」判定接受,避免无缩进条目被误当作顶层键提前退出。+ let item = rest.trim().trim_matches(['"', '\'']);+ if !item.is_empty() {+ push_unique(&mut keys, item.to_string());+ }+ } else if !next.starts_with(' ')+ && !next.starts_with('\t')+ && !trimmed.is_empty()+ && !trimmed.starts_with('#')+ {+ break; // 顶层键(无缩进且非列表项),已离开列表+ }+ // 其余(缩进行的非列表项、空行、注释):继续扫描+ }+ }+ }++ // 4) pnpm 10 报错文本里的包名(`The git-hosted package "NAME@VER" ... "onlyBuiltDependencies" allowlist.`),+ // 与第 3 步归并:即便列表被截断也能从消息取回名字。+ for line in &lines {+ if let Some(name) = extract_only_builds_git_name(line) {+ push_unique(&mut keys, name);+ }+ }++ keys+}++/// 若 `line` 形如 ` <key>: true`(有缩进),返回 `<key>`(去缩进与后缀)。+/// pnpm 报出的 depPath 键本身不带引号,这里只做剥离该行格式。+fn extract_allow_line_key(line: &str) -> Option<String> {+ let trimmed = line.trim_start();+ if trimmed.len() == line.len() {+ return None; // 无缩进,不是白名单条目+ }+ let suffix = trimmed.strip_suffix(": true")?;+ let key = suffix.trim_end();+ if key.is_empty() {+ return None;+ }+ Some(key.to_string())+}++/// 去重追加:避免同一键在不同输出块被重复计为待放行项。+fn push_unique(keys: &mut Vec<String>, key: String) {+ if !keys.iter().any(|k| k == &key) {+ keys.push(key);+ }+}++/// 从 pnpm 10 的 git 托管插件 prepare 门禁报错文本提取包名。+///+/// 形如 `The git-hosted package "NAME@VERSION" needs to execute build scripts+/// but is not in the "onlyBuiltDependencies" allowlist.`。+/// 仅匹配 `onlyBuiltDependencies` 形式的文本(pnpm 10);pnpm 11 的 `allowBuilds`+/// 形式仍由 [`extract_allow_line_key`] 解析 `allowBuilds:` 块,二者互不干扰。+fn extract_only_builds_git_name(line: &str) -> Option<String> {+ if !line.contains("\"onlyBuiltDependencies\" allowlist") {+ return None;+ }+ let marker = "The git-hosted package \"";+ let start = line.find(marker)? + marker.len();+ let rest = &line[start..];+ let end = rest.find('"')?;+ let quoted = &rest[..end]; // "name@version"+ // 包名(含 scoped 前缀 `@scope/name`)在最末一个 `@` 之前,版本号在之后。+ let (name, _version) = quoted.rsplit_once('@')?;+ (!name.is_empty()).then(|| name.to_string())+}++/// 从 pnpm 11 的 git depPath 允许键(`name@<pkgResolutionId>`)提取纯包名;+/// 普通包名 / `name@version` 选择器原样返回。+///+/// pnpm 10 的 `onlyBuiltDependencies` 只按包名(或包名@版本)匹配,git depPath 里的+/// resolution id(`git+ssh://…` / `https://…` 等)对它没有意义,必须剥掉,否则该+/// 放行项在 pnpm 10 下不生效、git 插件的 prepare 构建仍会被构建门禁拦截。+fn dep_path_to_name(key: &str) -> String {+ const GIT_RES_ID_MARKERS: &[&str] =+ &["@git+", "@https://", "@http://", "@git://", "@github.com/"];+ for marker in GIT_RES_ID_MARKERS {+ if let Some(pos) = key.find(marker) {+ return key[..pos].to_string();+ }+ }+ key.to_string()+}++/// profile 下的 `pnpm-workspace.yaml` 路径($DSH_HOME/profiles/<当前档案>)。+///+/// 构建放行项必须写进**当前活动档案**的工作区配置:`dsh plugin --profile <档案>`+/// 驱动的 pnpm 只读取该档案目录下的 `pnpm-workspace.yaml`,写错路径(如全局或其它+/// 档案)会让放行项失效,安装/升级仍会被 pnpm 的构建门禁拦截。+fn profile_workspace_path(app_handle: &AppHandle) -> PathBuf {+ profile_dir(app_handle).join("pnpm-workspace.yaml")+}++/// 把新的构建放行键合并写回 profile 的 `pnpm-workspace.yaml`,同时写入+/// `allowBuilds`(map,pnpm 11)与 `onlyBuiltDependencies`(list,pnpm 10)。+///+/// 用 YAML 库(serde_yaml)整体改写而非字符串拼接,避免格式错乱:+/// - 键(git depPath 含 `@`/`/`/`:`/`#`)由库自动按需加引号,不再手工拼;+/// - 已存在的同名键会被就地覆盖,不会残留占位值。+///+/// TODO(v1): 移除对旧版损坏文件(issue #49)的自愈逻辑。v1 起只解析干净配置,+/// `apply_allow_build_keys` 中解析失败后的「同键去重再解析」与+/// `collapse_allow_builds_duplicates` 一并删除。+///+/// 防御性修复:旧版本用字符串拼接可能留下「重复映射键」的损坏文件+/// (最多见的是 `node-pty: set this to true or false` 占位行与真正的+/// `'node-pty': true` 并存,见 issue #49)。此处解析失败时先做一次+/// `allowBuilds` 同键去重再解析,把损坏文件自愈回合法 YAML。+pub(super) fn add_allow_build_keys(app_handle: &AppHandle, keys: &[String]) -> Result<(), String> {+ let path = profile_workspace_path(app_handle);+ let dir = path+ .parent()+ .ok_or("PREINSTALL_BAD_PROFILE_DIR: no profile dir")?;+ std::fs::create_dir_all(dir).map_err(|e| format!("PREINSTALL_MKDIR: {e}"))?;++ let content = if path.exists() {+ std::fs::read_to_string(&path).map_err(|e| format!("PREINSTALL_READ_WORKSPACE: {e}"))?+ } else {+ // 与 dsh `initProfile` 生成的基础模板保持一致(尚无 allowBuilds)。+ "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n".to_string()+ };++ let rendered = apply_allow_build_keys(&content, keys)?;+ if rendered == content {+ return Ok(()); // 无变化(所有键已就位),避免无意义写盘+ }++ log::info!(+ "pnpm-workspace.yaml rewritten with allowBuilds {keys:?} at {}",+ path.display()+ );+ std::fs::write(&path, rendered).map_err(|e| format!("PREINSTALL_WRITE_WORKSPACE: {e}"))+}++/// 把新的构建放行键合并进 `pnpm-workspace.yaml` 文本并返回新文本。+///+/// 用 YAML 库(serde_yaml)整体改写而非字符串拼接,避免格式错乱:+/// - `allowBuilds`(pnpm 11)写为 map:键(git depPath 含 `@`/`/`/`:`/`#`)由库+/// 自动按需加引号,已存在的同名键会被就地覆盖为 `true`,不残留占位值、不产生重复键;+/// - `onlyBuiltDependencies`(pnpm 10)写为 list:追加唯一的包名,不清空已有条目。+///+/// 防御性修复:旧版本用字符串拼接可能留下「重复映射键」的损坏文件+/// (最多见的是 `node-pty: set this to true or false` 占位行与真正的+/// `'node-pty': true` 并存,见 issue #49)。此处先尝试严格解析;解析失败时+/// 做一次 `allowBuilds` 同键去重再解析,把损坏文件自愈回合法 YAML。+fn apply_allow_build_keys(content: &str, keys: &[String]) -> Result<String, String> {+ // 先尝试严格解析。旧的损坏文件(重复映射键)严格解析会失败:+ // 把 `allowBuilds` 内同名键去重(保留最后写入的值)后再解析,自愈损坏状态。+ let mut repaired = false;+ let mut doc: Value = match serde_yaml::from_str(content) {+ Ok(v) => v,+ Err(first_err) => {+ let normalized = collapse_allow_builds_duplicates(content);+ if normalized == content {+ return Err(format!("PREINSTALL_WORKSPACE_INVALID_YAML: {first_err}"));+ }+ repaired = true;+ serde_yaml::from_str(&normalized)+ .map_err(|e| format!("PREINSTALL_WORKSPACE_INVALID_YAML: {e}"))?+ }+ };++ // 空/注释-only 内容解析为 `Value::Null`,视为全新空配置(pnpm-workspace.yaml+ // 可加载的最小映射);其余非映射内容才是真正的损坏。+ if doc.is_null() {+ doc = Value::Mapping(Mapping::new());+ }++ let map = doc.as_mapping_mut().ok_or_else(|| {+ "PREINSTALL_WORKSPACE_NOT_MAP: pnpm-workspace.yaml must be a mapping".to_string()+ })?;++ let allow_key = Value::String("allowBuilds".to_string());+ if !map.contains_key(&allow_key) {+ map.insert(allow_key.clone(), Value::Mapping(Mapping::new()));+ }+ let allow_builds = map+ .get_mut(&allow_key)+ .and_then(Value::as_mapping_mut)+ .ok_or_else(|| {+ "PREINSTALL_WORKSPACE_ALLOWBUILDS_NOT_MAP: allowBuilds must be a mapping".to_string()+ })?;++ let mut dirty = false;+ for key in keys {+ let k = Value::String(key.clone());+ if allow_builds.get(&k) == Some(&Value::Bool(true)) {+ continue; // 已是 true,幂等跳过+ }+ // 直接覆盖旧值(含占位值/旧 false),由库负责按需加引号+ allow_builds.insert(k, Value::Bool(true));+ dirty = true;+ }++ // `allowBuilds` 的借用已在上面循环结束后释放(NLL),此处才能对 `map`+ // 再次取可变引用处理 `onlyBuiltDependencies`。+ //+ // pnpm 10(旧 store 复用的用户版)只认 `onlyBuiltDependencies`(list 形式,+ // 见其报错提示),因此这里一并写回,保证 pnpm 10 / 11 两版都能读到放行项;+ // `allowBuilds`(map 形式)覆盖 pnpm 11(捆绑版),二者共存互不冲突。+ //+ // 注意:pnpm 11 的 git 允许键是 `name@<pkgResolutionId>` 完整 depPath(按+ // resolution id 匹配,只能写进 allowBuilds);pnpm 10 只按包名匹配,因此写入+ // onlyBuiltDependencies 前必须经 [`dep_path_to_name`] 剥成纯包名。+ let only_key = Value::String("onlyBuiltDependencies".to_string());+ let to_add: Vec<Value> = {+ let existing_only = map.get(&only_key).and_then(Value::as_sequence);+ keys.iter()+ .map(|k| dep_path_to_name(k))+ .filter(|name| {+ existing_only.map_or(true, |seq| !seq.contains(&Value::String(name.clone())))+ })+ .map(Value::String)+ .collect()+ };+ if !to_add.is_empty() {+ if !map.contains_key(&only_key) {+ map.insert(only_key.clone(), Value::Sequence(Vec::new()));+ }+ let only_builds = map+ .get_mut(&only_key)+ .and_then(Value::as_sequence_mut)+ .ok_or_else(|| {+ "PREINSTALL_WORKSPACE_ONLYBUILT_NOT_SEQ: onlyBuiltDependencies must be a sequence"+ .to_string()+ })?;+ for v in to_add {+ only_builds.push(v);+ dirty = true;+ }+ }+ if !dirty && !repaired {+ return Ok(content.to_string());+ }+ // 有键新增,或损坏文件已被自愈归一化——两种都要落回解析后的完整文档,+ // 否则会把损坏的原始文本原样返回。++ serde_yaml::to_string(&doc).map_err(|e| format!("PREINSTALL_WORKSPACE_RENDER: {e}"))+}++/// 把损坏的 `allowBuilds` 映射(同一键出现多次)去重为合法 YAML。+///+/// 仅作为旧版字符串拼接遗留损坏(重复映射键,见 issue #49)的兜底归一化:+/// 扫描 `allowBuilds:` 之后、下一个顶层键之前的缩进 `key: value` 行,同一键+/// 只保留最后一次出现的行(与 YAML「后者覆盖前者」语义一致),其余行原样保留。+fn collapse_allow_builds_duplicates(content: &str) -> String {+ let lines: Vec<&str> = content.lines().collect();+ let mut in_allow = false;+ // 记录(键 → 该键所有行的索引),用于去重+ let mut key_indexes: HashMap<String, Vec<usize>> = HashMap::new();+ let mut order: Vec<String> = Vec::new();++ for (idx, line) in lines.iter().enumerate() {+ let trimmed = line.trim_start();+ if trimmed == "allowBuilds:" {+ in_allow = true;+ continue;+ }+ if in_allow {+ let is_indent = line.starts_with(' ') || line.starts_with('\t');+ let is_comment = trimmed.starts_with('#');+ if !is_indent || is_comment {+ in_allow = false; // 遇到顶层键或注释即离开 allowBuilds+ continue;+ }+ // 缩进的 `key: value` 行 → 提取键(冒号前)+ if let Some(col) = trimmed.find(':') {+ let key = trimmed[..col].trim().trim_matches(['\'', '"']);+ if !key.is_empty() {+ if !key_indexes.contains_key(key) {+ order.push(key.to_string());+ }+ key_indexes.entry(key.to_string()).or_default().push(idx);+ }+ }+ }+ }++ // 每个键只保留最后一个出现行,其余标记删除+ let mut keep: std::collections::HashSet<usize> = std::collections::HashSet::new();+ for key in &order {+ if let Some(idxs) = key_indexes.get(key) {+ if let Some(&last) = idxs.last() {+ keep.insert(last);+ }+ }+ }+ let mut out: Vec<&str> = Vec::with_capacity(lines.len());+ for (idx, line) in lines.iter().enumerate() {+ if key_indexes.values().any(|v| v.contains(&idx)) && !keep.contains(&idx) {+ continue; // 是被去重掉的重复键行+ }+ out.push(line);+ }+ // 避免重复键里夹带的空行粘连成异常空行:去掉去重区(allowBuilds 段)的连续空行+ out.join("\n")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parse_git_dep_path_key() {+ let out = "\+[ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED] Failed to prepare git-hosted package fetched from \"...\"+The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"allowBuilds\" allowlist.+...+allowBuilds:+ dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89: true+";+ let keys = parse_allowlist_keys(out);+ assert!(keys.contains(+ &"dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"+ .to_string()+ ));+ assert!(!keys.contains(&"dsh-better-sidebar".to_string()));+ }++ #[test]+ fn parse_ignored_builds_name() {+ let out = "[ERR_PNPM_IGNORED_BUILDS] Ignored build scripts: [email protected]\n";+ let keys = parse_allowlist_keys(out);+ assert_eq!(keys, vec!["node-pty".to_string()]);+ }++ #[test]+ fn parse_ignored_builds_scoped_name() {+ // 回归(CodeRabbit):scoped 原生依赖 `@scope/name@version` 必须保留完整包名,+ // 不能按第一个 `@` 切分(那会得到空串导致该包被跳过、无法放行)。+ let out = "[ERR_PNPM_IGNORED_BUILDS] Ignored build scripts: @deepseek-ai/[email protected], [email protected]\n";+ let keys = parse_allowlist_keys(out);+ assert_eq!(+ keys,+ vec!["@deepseek-ai/dsh-base".to_string(), "node-pty".to_string()]+ );+ }++ #[test]+ fn parse_empty_when_irrelevant() {+ let out = "everything looks fine output\nno allowlist here\n";+ assert!(parse_allowlist_keys(out).is_empty());+ }++ #[test]+ fn parse_pnpm10_only_built_dependencies_list() {+ // 回归(issue:预装插件在 pnpm 10 下报 ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED):+ // pnpm 10(旧 store 复用的用户版)只输出 onlyBuiltDependencies 列表与报错文本+ // 里的包名,不含 allowBuilds 块。此前 parse_allowlist_keys 只认 allowBuilds,+ // 导致读不到 dsh-better-sidebar、不写白名单、重试也被跳过,安装必然失败。+ let out = "\+[ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED] Failed to prepare git-hosted package fetched from \"https://codeload.github.com/omdsh-dev/DSH-better-sidebar/tar.gz/f9153dfc1ce47cf43445c1b351ee3ae47b4ad9f1\"+The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist.+...+This error happened while installing a direct dependency of C:\\Users\\hairy\\.dsh.dev\\profiles\\web+Add the package to \"onlyBuiltDependencies\" in your project's pnpm-workspace.yaml to allow it to run scripts. For example:+onlyBuiltDependencies:+- \"dsh-better-sidebar\"+";+ let keys = parse_allowlist_keys(out);+ assert_eq!(keys, vec!["dsh-better-sidebar".to_string()]);+ }++ #[test]+ fn parse_pnpm10_unindented_list_items() {+ // 回归(CodeRabbit):pnpm 10 提示段可能不带缩进(`- "name"` 与顶层键同列)。+ // 此前循环会把它误当顶层键提前退出,只靠报错文本回退解析才碰巧通过。+ let out = "onlyBuiltDependencies:\n- \"dsh-better-sidebar\"\n";+ let keys = parse_allowlist_keys(out);+ assert_eq!(keys, vec!["dsh-better-sidebar".to_string()]);+ }++ #[test]+ fn parse_pnpm10_scoped_package_from_message() {+ // 报错文本在列表被截断时也可取回名字;scoped 包名保留 `@scope/` 前缀。+ let out = "The git-hosted package \"@deepseek-ai/[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist.\n";+ let keys = parse_allowlist_keys(out);+ assert_eq!(keys, vec!["@deepseek-ai/dsh-base".to_string()]);+ }++ #[test]+ fn extract_only_builds_git_name_strips_version_and_handles_scoped() {+ // 普通包名:name@version → name+ assert_eq!(+ extract_only_builds_git_name(+ "The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist."+ ),+ Some("node-pty".to_string())+ );+ // scoped 包名:@scope/name@version → @scope/name(只剥最末一个 @ 后的版本号)+ assert_eq!(+ extract_only_builds_git_name(+ "The git-hosted package \"@deepseek-ai/[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist."+ ),+ Some("@deepseek-ai/dsh-base".to_string())+ );+ // pnpm 11 的 allowBuilds 文本不匹配(交由 allowBuilds 块解析)+ assert_eq!(+ extract_only_builds_git_name(+ "The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"allowBuilds\" allowlist."+ ),+ None+ );+ // 非 git 门禁行不匹配+ assert_eq!(+ extract_only_builds_git_name("allowBuilds:\n x: true"),+ None+ );+ }++ #[test]+ fn dep_path_to_name_strips_git_resolution_keeps_plain_names() {+ // git depPath(unscoped):剥掉 resolution id,保留纯包名+ assert_eq!(+ dep_path_to_name(+ "dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"+ ),+ "dsh-better-sidebar"+ );+ // git depPath(scoped):同样只剥 resolution id,保留 `@scope/name`+ assert_eq!(+ dep_path_to_name(+ "@deepseek-ai/dsh-base@git+https://github.com/deepseek-ai/dsh-base.git#abc123"+ ),+ "@deepseek-ai/dsh-base"+ );+ // 普通包名 / 包名@版本选择器:原样返回+ assert_eq!(dep_path_to_name("node-pty"), "node-pty");+ assert_eq!(dep_path_to_name("[email protected]"), "[email protected]");+ assert_eq!(dep_path_to_name("@scope/pkg"), "@scope/pkg");+ }++ #[test]+ fn allow_line_key_requires_indent() {+ let key = extract_allow_line_key(" node-pty: true");+ assert_eq!(key.as_deref(), Some("node-pty"));++ // 无缩进(顶层键)不应被当作白名单条目+ assert_eq!(extract_allow_line_key("packages:"), None);+ assert_eq!(extract_allow_line_key("allowBuilds:"), None);+ }++ // ---- 归并写回 pnpm-workspace.yaml(issue #49 回归)----++ /// 从渲染结果里解析出单一 `allowBuilds` 映射,便于断言。+ fn allow_builds_map(yaml: &str) -> serde_yaml::Mapping {+ let doc: serde_yaml::Value = serde_yaml::from_str(yaml).expect("output must be valid YAML");+ doc.get("allowBuilds")+ .and_then(serde_yaml::Value::as_mapping)+ .expect("allowBuilds must be a mapping")+ .clone()+ }++ #[test]+ fn apply_adds_new_key_when_absent() {+ let base = "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n";+ // 无 allowBuilds 时首次写入+ let out = apply_allow_build_keys(base, &["node-pty".to_string()]).unwrap();+ let map = allow_builds_map(&out);+ assert_eq!(map.get("node-pty"), Some(&serde_yaml::Value::Bool(true)));+ // 顶级基础设置被保留+ let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();+ assert!(doc.get("packages").is_some());+ assert!(doc.get("nodeLinker").is_some());+ }++ #[test]+ fn apply_is_idempotent_and_does_not_duplicate() {+ // 已放行的键再次写入:结果不变(幂等、不产生重复键)。输入须同时包含+ // allowBuilds 与 onlyBuiltDependencies 两个放行出口(桌面端双写,见+ // apply_allow_build_keys),证明两处都幂等。+ let base = "packages:\n - .\nnodeLinker: hoisted\nautoInstallPeers: false\nallowBuilds:\n node-pty: true\nonlyBuiltDependencies:\n - node-pty\n";+ let out = apply_allow_build_keys(base, &["node-pty".to_string()]).unwrap();+ assert_eq!(out, base);+ }++ #[test]+ fn apply_writes_both_allowbuilds_and_only_built_dependencies() {+ // pnpm 11 认 allowBuilds(map),pnpm 10 认 onlyBuiltDependencies(list),+ // 两者须同时写回,用户 pnpm 10 / 捆绑版 pnpm 11 都能读到放行项。+ let base = "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n";+ let out = apply_allow_build_keys(base, &["dsh-better-sidebar".to_string()]).unwrap();+ let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();+ // pnpm 11:allowBuilds 为 map 形式+ assert_eq!(+ doc["allowBuilds"]["dsh-better-sidebar"],+ serde_yaml::Value::Bool(true)+ );+ // pnpm 10:onlyBuiltDependencies 为 list 形式+ let only = doc+ .get("onlyBuiltDependencies")+ .and_then(serde_yaml::Value::as_sequence)+ .expect("onlyBuiltDependencies must be a sequence");+ assert_eq!(+ only,+ &vec![serde_yaml::Value::String("dsh-better-sidebar".to_string())]+ );+ // 基础设置被保留+ assert!(doc.get("packages").is_some());+ assert!(doc.get("nodeLinker").is_some());+ }++ #[test]+ fn apply_git_dep_path_writes_name_selector_for_pnpm10() {+ // 回归(CodeRabbit):git 托管插件的完整 depPath 只写进 pnpm 11 的 allowBuilds+ // (按 resolution id 匹配);pnpm 10 的 onlyBuiltDependencies 只按包名匹配,+ // 必须剥成纯包名,否则 pnpm 10 读不到放行项、prepare 构建仍会被门禁拦截。+ // 两个出口同时写好后,pnpm 10 / 11 之间切换都不会再次触发构建门禁。+ let base = "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n";+ let dep =+ "dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"+ .to_string();+ let out = apply_allow_build_keys(base, &[dep.clone()]).unwrap();+ let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();+ // pnpm 11:allowBuilds 保留完整 depPath+ assert_eq!(+ doc["allowBuilds"][&serde_yaml::Value::String(dep)],+ serde_yaml::Value::Bool(true)+ );+ // pnpm 10:onlyBuiltDependencies 只含纯包名+ let only = doc+ .get("onlyBuiltDependencies")+ .and_then(serde_yaml::Value::as_sequence)+ .expect("onlyBuiltDependencies must be a sequence");+ assert_eq!(+ only,+ &vec![serde_yaml::Value::String("dsh-better-sidebar".to_string())]+ );+ }++ #[test]+ fn apply_only_built_dependencies_preserves_existing_entries() {+ // onlyBuiltDependencies 已含旧条目时,只追加新键、不清空原有条目。+ let base = "packages:\n - .\nallowBuilds:\n esbuild: true\nonlyBuiltDependencies:\n - esbuild\n";+ let out = apply_allow_build_keys(base, &["dsh-better-sidebar".to_string()]).unwrap();+ let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();+ let only = doc+ .get("onlyBuiltDependencies")+ .and_then(serde_yaml::Value::as_sequence)+ .expect("onlyBuiltDependencies must be a sequence");+ let names: Vec<&str> = only.iter().filter_map(|v| v.as_str()).collect();+ assert_eq!(names, vec!["esbuild", "dsh-better-sidebar"]);+ }++ #[test]+ fn apply_quotes_git_dep_path_keys() {+ let dep =+ "dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"+ .to_string();+ // 空内容也能生成合法配置+ let out = apply_allow_build_keys("", &[dep.clone()]).unwrap();+ let map = allow_builds_map(&out);+ assert_eq!(+ map.get(&serde_yaml::Value::String(dep)),+ Some(&serde_yaml::Value::Bool(true))+ );+ // 库负责正确加引号,键原样(含 @ / : / #)可回读+ let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();+ assert_eq!(+ doc["allowBuilds"][&serde_yaml::Value::String(+ "dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"+ .to_string()+ )],+ serde_yaml::Value::Bool(true)+ );+ }++ #[test]+ fn apply_overwrites_placeholder_value_without_duplicate() {+ // 关键回归:旧版字符串拼接可能留下占位键 `node-pty: set this to true or false`+ // 与真实键并存。若解析保留重复键,或解析失败被去重兜底,最终都必须只保留+ // 一个 `node-pty: true`(不允许重复映射键)。+ let corrupted =+ "allowBuilds:\n 'dsh-better-sidebar@https://code...': true\n node-pty: set this to true or false\n 'node-pty': true\n";+ let out = apply_allow_build_keys(corrupted, &["node-pty".to_string()]).unwrap();+ let map = allow_builds_map(&out);+ // 恰好只有一个 node-pty 键,值是 true(覆盖了占位值)+ assert_eq!(map.get("node-pty"), Some(&serde_yaml::Value::Bool(true)));+ // 序列化后全局不允许再出现“重复键”的等价行(node-pty 只出现一次)+ let node_pty_keys = out+ .lines()+ .filter(|l| {+ l.trim_start().starts_with("node-pty") || l.trim_start().starts_with("'node-pty'")+ })+ .count();+ assert_eq!(node_pty_keys, 1);+ }++ #[test]+ fn collapse_dedupes_allow_builds_keys() {+ let corrupted =+ "packages:\n - .\nallowBuilds:\n node-pty: set this to true or false\n 'node-pty': true\n keep: true\n";+ let normalized = collapse_allow_builds_duplicates(corrupted);+ // 重复的 node-pty 只剩最后一个(值 true),同键不再重复+ let node_pty = normalized+ .lines()+ .filter(|l| {+ l.trim_start().starts_with("node-pty") || l.trim_start().starts_with("'node-pty'")+ })+ .count();+ assert_eq!(node_pty, 1);+ assert!(normalized.contains("keep"));+ // 去重结果必须是合法 YAML,且能被后续解析+ let out = apply_allow_build_keys(&normalized, &["node-pty".to_string()]).unwrap();+ assert_eq!(+ allow_builds_map(&out).get("node-pty"),+ Some(&serde_yaml::Value::Bool(true))+ );+ }+}diff --git a/src-tauri/src/service/plugin/install/artifact.rs b/src-tauri/src/service/plugin/install/artifact.rsnew file mode 100644index 00000000..9a3f22e0--- /dev/null+++ b/src-tauri/src/service/plugin/install/artifact.rs@@ -0,0 +1,438 @@+//! 安装产物核验与修复:逐插件核验 `node_modules/<安装名>/package.json` 真实落盘+//! (防「假成功」),并就地补构建缺失的声明入口(`ensure_plugin_entry_built`,+//! 见 `dsh.plugin.json` / `package.json` 的 `main`/`exports` 解析)。++use std::collections::HashMap;+use std::ffi::OsString;+use std::path::{Path, PathBuf};+use tauri::{AppHandle, Emitter, WebviewWindow};++use serde_json::Value as JsonValue;++use super::append_command_output;+use super::errors;+use super::installed_name;+use super::load_presets;+use super::profile_dir;+use super::PreinstallPluginInfo;+use super::{new_process_owner, run_plugin_process, PreinstallLogPayload, PREINSTALL_LOG_EVENT};++pub(super) fn verify_installed_products(+ app_handle: &AppHandle,+ ids: &[String],+ preset_map: &HashMap<&str, &PreinstallPluginInfo>,+ command_output: &str,+) -> Result<(), String> {+ let node_modules = profile_dir(app_handle).join("node_modules");+ let mut missing = Vec::new();+ for id in ids {+ let Some(preset) = preset_map.get(id.as_str()) else {+ continue;+ };+ let name = installed_name(preset);+ let manifest = node_modules.join(name).join("package.json");+ if manifest.is_file() {+ if let Err(e) = errors::clear(app_handle, id) {+ log::warn!("failed to clear plugin error for {id}: {e}");+ }+ } else {+ missing.push((id.clone(), manifest));+ }+ }+ if missing.is_empty() {+ return Ok(());+ }+ let detail = silent_install_failure_detail(&missing, command_output);+ log::error!("{detail}");+ for (id, _) in &missing {+ if let Err(e) = errors::record(app_handle, id, "install", &detail) {+ log::warn!("failed to record plugin error for {id}: {e}");+ }+ }+ Err(detail)+}++/// 为 exit 0 但无落盘产物的假成功生成可操作诊断:明确缺失插件、预期清单路径,+/// 并区分「子进程完全无输出」与「有输出但仍未落盘」,方便日志反馈直接定位。+fn silent_install_failure_detail(missing: &[(String, PathBuf)], command_output: &str) -> String {+ let ids = missing+ .iter()+ .map(|(id, _)| id.as_str())+ .collect::<Vec<_>>()+ .join(", ");+ let manifests = missing+ .iter()+ .map(|(_, path)| path.display().to_string())+ .collect::<Vec<_>>()+ .join(", ");+ let output_hint = if command_output.trim().is_empty() {+ "The dsh plugin command produced no output."+ } else {+ "Review the preinstall log above for the command output."+ };+ format!(+ "PREINSTALL_SILENT_FAIL: dsh plugin exited with code 0, but no install artifact was created for [{ids}]. Expected package manifests: [{manifests}]. {output_hint} Retry the installation; if it repeats, include the preinstall log and these paths in the bug report."+ )+}++/// 构建 `dsh plugin` 子进程的环境变量:隔离 $DSH_HOME、关闭遥测与颜色、+/// 注入预检解析出的 node 路径(`DSH_NODE`,shim 优先采用,见 shim.rs)、+/// PATH 前置 shim、node 与桌面端自动配置的 Git 目录;用户 pnpm 过旧时强制+/// 捆绑版(见 ensure_pnpm)。+///+/// 供本模块的安装/升级/卸载与 [`super::verify`] 的完整性修复共用:子进程(dsh++fn declared_main_entry(pkg_dir: &Path) -> Option<PathBuf> {+ /// 拼接声明入口并拒绝越界:绝对路径会被 `join` 整体替换基路径,`../`+ /// 逃逸在 `starts_with` 的词法比较下不会被解析——两者都会让核验目标指向+ /// 包外文件,导致假通过。+ fn join_contained(pkg_dir: &Path, entry: &str) -> Option<PathBuf> {+ let candidate = Path::new(entry);+ if candidate.is_absolute()+ || candidate+ .components()+ .any(|c| matches!(c, std::path::Component::ParentDir))+ {+ return None;+ }+ let joined = pkg_dir.join(candidate);+ joined.starts_with(pkg_dir).then_some(joined)+ }+ let from_main_field = |value: &JsonValue| -> Option<PathBuf> {+ value+ .get("main")+ .and_then(|v| v.as_str())+ .and_then(|main| join_contained(pkg_dir, main))+ };+ let plugin_manifest_text = std::fs::read_to_string(pkg_dir.join("dsh.plugin.json")).ok();+ if let Some(text) = plugin_manifest_text {+ if let Ok(value) = serde_json::from_str::<JsonValue>(&text) {+ if let Some(entry) = from_main_field(&value) {+ return Some(entry);+ }+ }+ }+ let pkg_text = std::fs::read_to_string(pkg_dir.join("package.json")).ok()?;+ let value = serde_json::from_str::<JsonValue>(&pkg_text).ok()?;+ if let Some(entry) = from_main_field(&value) {+ return Some(entry);+ }+ let exports = value.get("exports");+ // 字符串简写:"exports": "./lib/index.js"(`get(".")` 对字符串取值会落空,+ // 必须先试字符串形态)+ if let Some(shorthand) = exports.and_then(|v| v.as_str()) {+ return join_contained(pkg_dir, shorthand);+ }+ let dot = exports.and_then(|v| v.get("."));+ for key in ["default", "import", "require"] {+ if let Some(entry) = dot+ .and_then(|d| d.get(key))+ .and_then(|v| v.as_str())+ .and_then(|s| join_contained(pkg_dir, s))+ {+ return Some(entry);+ }+ }+ None+}++/// 把插件 id 解析为 profile 中实际的 npm 包名:预设表(`package` 覆盖字段)+/// 优先;找不到预设时按 profile 清单 `dependencies` 键的 basename 匹配+/// (覆盖 `@scope/name` 形态,如 `dsh-session-context-menu` →+/// `@baihejiangnan/dsh-session-context-menu`)。+pub(super) fn installed_package_name(app_handle: &AppHandle, id: &str) -> Option<String> {+ if let Some(preset) = load_presets(app_handle).iter().find(|p| p.id == id) {+ return Some(installed_name(preset).to_string());+ }+ let manifest_path = profile_dir(app_handle).join("package.json");+ let text = std::fs::read_to_string(&manifest_path).ok()?;+ let value = serde_json::from_str::<JsonValue>(&text).ok()?;+ value+ .get("dependencies")+ .and_then(|d| d.as_object())+ .and_then(|deps| {+ deps.keys()+ .find(|name| name.rsplit('/').next() == Some(id))+ .cloned()+ })+}++/// 核验已装插件包的声明入口产物,缺失时就地补构建或如实报错。+///+/// 背景:`verify_installed_products` 核验的是「包是否落盘」(`package.json`+/// 存在),但 pnpm 放行 git 托管插件的 `prepare` 后,构建仍可能停在不产出的+/// 坏态:tsdown 在 `node_modules` 内加载其 TS 配置受 Node 版本限制(报错建议+/// `--config-loader` 用 `tsx`/`unrun`),此时 `dsh plugin add` 以 0 退出且+/// `package.json` 已落盘,但 `lib/index.js` 缺失——下一次启动 cordis 加载器+/// `ERR_MODULE_NOT_FOUND` 崩溃(应用内所有 fetch 必挂,表现为「插件目录 /+/// 历史会话全部 Failed to fetch」)。+/// 补构建按成本递增:`run build` → `run prepare` → `exec tsdown --config-loader unrun`+/// (社区已知绕过方式,unrun 已随 tsdown 进插件 devDeps)。全部失败则记录错误并+/// 如实返回,杜绝「装上了却跑不起来」的静默成功。+///+/// `pkg_dir` 由调用方解析(install 用预设的 `installed_name`,update 用+/// `installed_package_name`),本函数不再假设 id 即包名。+pub(super) async fn ensure_plugin_entry_built(+ app_handle: &AppHandle,+ id: &str,+ pkg_dir: &Path,+ envs: &HashMap<String, String>,+ window: &WebviewWindow,+) -> Result<(), String> {+ if !pkg_dir.is_dir() {+ return Err(format!(+ "PLUGIN_ENTRY_MISSING: {id} 未安装({} 不存在),请重新安装",+ pkg_dir.display()+ ));+ }+ let Some(entry) = declared_main_entry(pkg_dir) else {+ // 无声明入口(包本身不暴露可核验产物):不阻塞,仅告警+ log::warn!("plugin {id} declares no verifiable main entry, skipping build verify");+ return Ok(());+ };+ if entry.is_file() {+ return Ok(());+ }++ // 与 verify 修复路径同一套 store 主版本感知 pnpm 选择(捆绑版优先,不匹配+ // 时回落用户 pnpm.exe),不硬编码单一 pnpm,避免「装了用户版却没捆绑版」+ // 或 v10/v11 store 不兼容的假失败。+ let Some((program, pre_args)) = super::super::verify::pnpm_direct(app_handle) else {+ return Err(format!(+ "PNPM_NOT_FOUND: no usable pnpm (bundled or user) to rebuild plugin {id}"+ ));+ };+ log::warn!(+ "plugin {id} declared entry {} is missing; rebuilding in place",+ entry.display()+ );+ let attempts: [(&str, &[&str]); 3] = [+ ("build", &["run", "build"]),+ ("prepare", &["run", "prepare"]),+ (+ "tsdown --config-loader unrun",+ &["exec", "tsdown", "--config-loader", "unrun"],+ ),+ ];+ let mut all_output = String::new();+ for (label, args) in attempts {+ let _ = window.emit(+ PREINSTALL_LOG_EVENT,+ PreinstallLogPayload {+ line: format!(+ "[pnpm] {id} 缺少构建产物({}),正在补构建({label})…",+ entry.display()+ ),+ },+ );+ let mut full_args = pre_args.clone();+ full_args.extend(args.iter().map(|a| OsString::from(*a)));+ // 单次 spawn 失败(pnpm 瞬时不可用等)不致命:记日志后尝试下一策略,+ // 输出跨尝试累计,保证最终报错携带最早一次的有效诊断。+ // main 侧 `run_plugin_process` 要求显式 ProcessOwner(pid 槽位跟踪/取消);+ // 补构建是独立的一次性构建,不隶属 install/update 的操作锁,取新 owner。+ match run_plugin_process(+ &program,+ &full_args,+ pkg_dir,+ envs,+ window,+ new_process_owner(),+ )+ .await+ {+ Ok((code, output)) => {+ append_command_output(&mut all_output, &output);+ // 产物出现即视为成功(目标=「入口存在、加载器不崩」);+ // 退出码非 0 但产物已生成(如 post-build 钩子失败)仅记警告。+ if entry.is_file() {+ if code != 0 {+ log::warn!(+ "plugin {id} build via {label} exited {code} but entry {} exists",+ entry.display()+ );+ }+ log::info!("plugin {id} rebuilt via {label}: {}", entry.display());+ return Ok(());+ }+ log::warn!("plugin {id} build via {label} exited {code}; trying next strategy");+ }+ Err(e) => {+ log::warn!(+ "plugin {id} build via {label} failed to spawn: {e}; trying next strategy"+ );+ }+ }+ }+ let tail = all_output+ .lines()+ .rev()+ .take(8)+ .collect::<Vec<_>>()+ .into_iter()+ .rev()+ .collect::<Vec<_>>()+ .join("\n");+ Err(format!(+ "PLUGIN_ENTRY_MISSING: {id} 声明的入口 {} 构建失败(build/prepare 均未产出),尾部日志:\n{tail}",+ entry.display()+ ))+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::PathBuf;++ #[test]+ fn silent_install_failure_reports_empty_output_and_expected_artifact() {+ let missing = vec![(+ "dsh-win-terminal-inspector".to_string(),+ PathBuf::from(+ "C:\\Users\\test\\.dsh\\profiles\\web\\node_modules\\dsh-win-terminal-inspector\\package.json",+ ),+ )];++ let detail = silent_install_failure_detail(&missing, " \r\n");++ assert!(detail.starts_with("PREINSTALL_SILENT_FAIL:"));+ assert!(detail.contains("dsh-win-terminal-inspector"));+ assert!(detail.contains("package.json"));+ assert!(detail.contains("produced no output"));+ assert!(detail.contains("Retry the installation"));+ }++ /// 验证已有命令日志时,引导用户查看日志而不会误报为完全无输出。+ #[test]+ fn silent_install_failure_points_to_existing_command_log() {+ let missing = vec![(+ "dshmarket".to_string(),+ PathBuf::from("/tmp/profile/node_modules/dshmarket/package.json"),+ )];++ let detail = silent_install_failure_detail(&missing, "pnpm completed\n");++ assert!(detail.contains("Review the preinstall log above"));+ assert!(!detail.contains("produced no output"));+ }++ /// 验证最终重试无输出时,早期尝试产生的诊断不会被覆盖丢失。++ fn tmp_pkg_dir(name: &str) -> PathBuf {+ let dir =+ std::env::temp_dir().join(format!("dsh-entry-test-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ #[test]+ fn declared_main_prefers_dsh_plugin_manifest() {+ let dir = tmp_pkg_dir("manifest");+ std::fs::write(+ dir.join("dsh.plugin.json"),+ r#"{"id":"x","main":"./lib/index.js"}"#,+ )+ .unwrap();+ std::fs::write(+ dir.join("package.json"),+ r#"{"name":"x","main":"dist/index.js"}"#,+ )+ .unwrap();+ assert_eq!(declared_main_entry(&dir).unwrap(), dir.join("lib/index.js"));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn declared_main_falls_back_to_package_json() {+ let dir = tmp_pkg_dir("pkgjson");+ std::fs::write(+ dir.join("package.json"),+ r#"{"name":"x","main":"lib/index.js"}"#,+ )+ .unwrap();+ assert_eq!(declared_main_entry(&dir).unwrap(), dir.join("lib/index.js"));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn declared_main_reads_exports_default() {+ let dir = tmp_pkg_dir("exports");+ std::fs::write(+ dir.join("package.json"),+ r#"{"name":"x","exports":{".":{"types":"./lib/types.d.ts","default":"./lib/index.js"}}}"#,+ )+ .unwrap();+ assert_eq!(declared_main_entry(&dir).unwrap(), dir.join("lib/index.js"));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn declared_main_reads_exports_string_shorthand_and_require() {+ let dir = tmp_pkg_dir("exports-shorthand");+ std::fs::write(+ dir.join("package.json"),+ r#"{"name":"x","exports":"./dist/main.js"}"#,+ )+ .unwrap();+ assert_eq!(declared_main_entry(&dir).unwrap(), dir.join("dist/main.js"));+ let _ = std::fs::remove_dir_all(&dir);++ let dir2 = tmp_pkg_dir("exports-require");+ std::fs::write(+ dir2.join("package.json"),+ r#"{"name":"x","exports":{".":{"require":"./cjs/index.js"}}}"#,+ )+ .unwrap();+ assert_eq!(+ declared_main_entry(&dir2).unwrap(),+ dir2.join("cjs/index.js")+ );+ let _ = std::fs::remove_dir_all(&dir2);+ }++ #[test]+ fn declared_main_rejects_escaping_or_absolute_entries() {+ // `../` 逃逸与绝对路径都不应通过核验:防止把检查指向包外文件造成假通过+ let dir = tmp_pkg_dir("escape");+ std::fs::write(+ dir.join("package.json"),+ r#"{"name":"x","main":"../outside/index.js"}"#,+ )+ .unwrap();+ assert!(declared_main_entry(&dir).is_none());+ let absolute_entry = if cfg!(windows) {+ "C:\\\\outside\\\\index.js"+ } else {+ "/outside/index.js"+ };+ std::fs::write(+ dir.join("package.json"),+ format!(r#"{{"name":"x","main":"{}"}}"#, absolute_entry),+ )+ .unwrap();+ assert!(declared_main_entry(&dir).is_none());+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn declared_main_falls_through_broken_plugin_manifest() {+ // dsh.plugin.json 存在但损坏/无 main 时,回落 package.json+ let dir = tmp_pkg_dir("broken-plugin-manifest");+ std::fs::write(dir.join("dsh.plugin.json"), r#"not-json"#).unwrap();+ std::fs::write(+ dir.join("package.json"),+ r#"{"name":"x","main":"lib/index.js"}"#,+ )+ .unwrap();+ assert_eq!(declared_main_entry(&dir).unwrap(), dir.join("lib/index.js"));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn declared_main_none_without_manifest() {+ let dir = tmp_pkg_dir("none");+ assert!(declared_main_entry(&dir).is_none());+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/src-tauri/src/service/plugin/install/diagnose.rs b/src-tauri/src/service/plugin/install/diagnose.rsnew file mode 100644index 00000000..dbcd6351--- /dev/null+++ b/src-tauri/src/service/plugin/install/diagnose.rs@@ -0,0 +1,158 @@+//! 失败输出解析:识别网络错误(代理/DNS/连接/TLS)、git 传输层失败+//! (HTTPS→SSH 回退提示),并从输出中挑选可展示的错误消息(ANSI 清洗、+//! 命中错误标记的行优先、截断)。++/// 从 dsh/pnpm 失败输出中提取可展示的错误消息:优先 git 传输层提示;+/// 否则挑出命中错误标记的行(最多 8 行),没有则取输出尾部,ANSI 清洗后+/// 截断到 2000 字符。+pub(super) fn diagnostic_suffix(detail: &str) -> String {+ if detail.is_empty() {+ String::new()+ } else {+ format!(": {detail}")+ }+}++pub(super) fn pick_error_message(output: &str, hint: Option<&str>) -> String {+ if let Some(hint) = hint {+ return hint.to_string();+ }+ let cleaned: Vec<String> = output+ .split('\n')+ .filter_map(|line| {+ let trimmed = strip_ansi(line);+ let trimmed = trimmed.trim();+ (!trimmed.is_empty()).then(|| trimmed.to_string())+ })+ .filter(|line| {+ line.contains("ERR_")+ || line.contains("error")+ || line.contains("Error")+ || line.contains("failed")+ || line.contains("✖")+ || line.contains("warning")+ })+ .take(8)+ .collect();+ let base = if cleaned.is_empty() {+ output.trim().to_string()+ } else {+ cleaned.join("\n")+ };+ base.chars().take(2000).collect()+}++/// 去除 ANSI 转义序列(`\x1B[...m`,含颜色/样式码)。+fn strip_ansi(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ let mut chars = s.chars().peekable();+ while let Some(c) = chars.next() {+ if c == '\x1b' && chars.peek() == Some(&'[') {+ chars.next(); // '['+ while let Some(&n) = chars.peek() {+ if n.is_ascii_digit() || n == ';' {+ chars.next();+ } else {+ break;+ }+ }+ if chars.peek() == Some(&'m') {+ chars.next();+ }+ } else {+ out.push(c);+ }+ }+ out+}++/// 从 pnpm 失败输出里识别网络错误,返回稳定提示,避免把网络问题误报为 dsh+/// 子进程错误。代理、DNS、连接超时和 TLS 失败都属于此类。+pub(super) fn network_error_hint(output: &str) -> Option<&'static str> {+ const SIGNALS: &[&str] = &[+ "eai_again",+ "enotfound",+ "econnrefused",+ "econnreset",+ "etimedout",+ "network timeout",+ "network request failed",+ "fetch failed",+ "unable to verify the first certificate",+ "self signed certificate",+ "socket hang up",+ "could not resolve host",+ "failed to connect",+ "connection timed out",+ "connection reset",+ ];+ let lower = output.to_ascii_lowercase();+ SIGNALS+ .iter()+ .any(|signal| lower.contains(signal))+ .then_some("网络连接失败,请检查网络或代理设置后重试。")+}++pub(super) fn git_transport_hint(output: &str) -> Option<&'static str> {+ const SIGNALS: &[(&str, &str)] = &[+ (+ "host key verification failed",+ "git fell back to SSH and could not verify GitHub's host key (no known_hosts entry; the process ran non-interactively). Make sure GitHub is reachable over HTTPS.",+ ),+ (+ "permission denied (publickey)",+ "git reached GitHub over SSH instead of HTTPS (Permission denied (publickey)) — usually your git config rewrites GitHub HTTPS to SSH (url.<base>.insteadOf) while no SSH key is configured. The desktop app isolates git config to force HTTPS for plugin installs; if you still see this, remove that rewrite (git config --global --unset-all '[email protected]:.insteadOf') or configure an SSH key.",+ ),+ (+ "could not read from remote repository",+ "pnpm could not read from the git remote — commonly a git+ssh transport failure. Ensure GitHub is reachable over HTTPS.",+ ),+ (+ "ssh: connect to host",+ "pnpm tried to reach GitHub over SSH (port 22) and the connection was refused. Use HTTPS instead.",+ ),+ ];+ let lower = output.to_ascii_lowercase();+ SIGNALS+ .iter()+ .find(|(sig, _)| lower.contains(sig))+ .map(|(_, hint)| *hint)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn diagnostic_suffix_preserves_non_allowbuilds_failure() {+ assert_eq!(diagnostic_suffix(""), "");+ assert_eq!(+ diagnostic_suffix("ERR_PNPM_LINKING_FAILED: stale symlink"),+ ": ERR_PNPM_LINKING_FAILED: stale symlink"+ );+ }++ // ---- git 传输层错误识别(区别于 allowBuilds 门禁)----++ #[test]+ fn git_transport_hint_detects_host_key_failure() {+ let out = "git ls-remote \"git+ssh://[email protected]/foo.git\" HEAD\nHost key verification failed.\nfatal: Could not read from remote repository.\n";+ assert!(git_transport_hint(out).is_some());+ }++ #[test]+ fn git_transport_hint_detects_publickey_and_ssh() {+ assert!(git_transport_hint("[email protected]: Permission denied (publickey)").is_some());+ assert!(+ git_transport_hint("ssh: connect to host github.com port 22: Connection refused")+ .is_some()+ );+ }++ #[test]+ fn git_transport_hint_none_for_allowbuilds_output() {+ // allowBuilds 场景(prepare 构建被拦)不应误判为传输层错误+ let out = "[ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED] ...\nallowBuilds:\n node-pty: true\n";+ assert!(git_transport_hint(out).is_none());+ }+}diff --git a/src-tauri/src/service/plugin/install/env.rs b/src-tauri/src/service/plugin/install/env.rsnew file mode 100644index 00000000..67368990--- /dev/null+++ b/src-tauri/src/service/plugin/install/env.rs@@ -0,0 +1,279 @@+//! `dsh plugin` 子进程环境构建:隔离 $DSH_HOME、关闭遥测与颜色、PATH 前置+//! shim/node/git 目录;并检测用户 git 配置里「GitHub HTTPS → SSH」改写规则,+//! 按需隔离子进程 git 配置强制 HTTPS(桌面机无 SSH 密钥时 git+ssh 必然失败)。++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use tauri::AppHandle;++use crate::config;+use crate::service::cli;++/// 构建 `dsh plugin` 子进程的环境变量:隔离 $DSH_HOME、关闭遥测与颜色、+/// 注入预检解析出的 node 路径(`DSH_NODE`,shim 优先采用,见 shim.rs)、+/// PATH 前置 shim、node 与桌面端自动配置的 Git 目录;用户 pnpm 过旧时强制+/// 捆绑版(见 ensure_pnpm)。+///+/// 供本模块的安装/升级/卸载与 [`crate::service::plugin::verify`] 的完整性修复共用:+/// 子进程(dsh 或 pnpm)都按同一套桌面端环境策略运行,保证 $DSH_HOME / PATH+/// 布局一致。+pub(crate) fn build_plugin_envs(+ app_handle: &AppHandle,+ prefer_bundled_pnpm: bool,+) -> HashMap<String, String> {+ let node = config::get_node_binary_path(app_handle);+ // 规范化为绝对路径:get_node_binary_path 可能返回相对路径(PATH 上出现+ // 相对条目时,如 `.` 或 `tools\node`),而子进程 CWD 与应用进程不同,+ // 相对路径会被解析到错误位置——shim 经 DSH_NODE / PATH 都找不到 node+ // (issue #121 的 "Node.js runtime not found")。已存在(预检通过)的+ // node 可安全 canonicalize;失败时回退原值。+ let node_abs = dunce::canonicalize(&node).unwrap_or_else(|_| node.clone());+ let bin_dir = cli::get_bin_dir(app_handle);+ let mut envs = HashMap::from([+ (+ "DSH_HOME".to_string(),+ config::get_dsh_data_path(app_handle)+ .to_string_lossy()+ .into_owned(),+ ),+ ("DSH_TELEMETRY_DISABLED".to_string(), "1".to_string()),+ ("NO_COLOR".to_string(), "1".to_string()),+ // 把预检解析出的 node 路径显式交给 pnpm/dsh shim(DSH_NODE 优先):+ // shim 自身经 PATH 解析 node 可能与应用预检不一致(PATH 上的相对条目、+ // junction/符号链接、或子进程 PATH 布局差异),导致 pnpm shim 报+ // "Node.js runtime not found" 而应用预检却通过(issue #121)。+ (+ "DSH_NODE".to_string(),+ node_abs.to_string_lossy().into_owned(),+ ),+ ]);+ // 用户 pnpm 过旧/不可探测时强制 pnpm shim 优先捆绑版,避免 8/9 的+ // autoInstallPeers 语义与 workspace-root gate 破坏插件安装(见 ensure_pnpm)+ if prefer_bundled_pnpm {+ envs.insert("DSH_PREFER_BUNDLED_PNPM".to_string(), "1".to_string());+ } else if let Some(pnpm) = cli::find_user_pnpm(app_handle) {+ // 显式注入绝对路径,避免子进程在不同 PATH/CWD 下重新发现失败。+ // Unix 保留 mise 依赖 argv[0] 的 shim 链接;Windows 仍解析连接点并剥离+ // `\\?\`。同时防御性排除应用自身 shim,避免递归调用。+ if let Some(pnpm_value) = cli::pnpm_env_value(&pnpm, &bin_dir) {+ envs.insert("DSH_PNPM".to_string(), pnpm_value);+ }+ }++ let mut paths = vec![bin_dir];+ if let Some(node_dir) = node_abs.parent() {+ paths.push(node_dir.to_path_buf());+ }+ // pnpm 安装 github:/git+ssh: 插件时会直接调用 git。Windows 空白环境使用+ // 桌面端已校验安装的 MinGit,仅对子进程 PATH 生效,不污染用户系统 PATH。+ if let Some(git_dir) = config::get_git_cmd_dir(app_handle) {+ paths.push(git_dir);+ }+ paths.extend(std::env::split_paths(+ &std::env::var_os("PATH").unwrap_or_default(),+ ));++ if let Ok(joined) = std::env::join_paths(paths) {+ envs.insert("PATH".to_string(), joined.to_string_lossy().into_owned());+ }+ // 用户 git 配置若把 GitHub HTTPS 改写为 SSH(url.<base>.insteadOf),pnpm 的+ // git 传输会落进 SSH 而硬失败;按需隔离子进程 git 配置强制 HTTPS+ // (见 [`git_https_isolation_env`],未命中改写规则时返回空 map,零影响)。+ envs.extend(git_https_isolation_env(app_handle));+ envs+}++/// 检测用户 git 配置中「把 GitHub HTTPS 改写为 SSH」的 `url.<base>.insteadOf`+/// 规则,命中时返回隔离子进程 git 配置所需的环境变量,强制插件安装走 HTTPS。+///+/// 背景:不少用户按 GitHub 官方文档配置过+/// `git config --global url."[email protected]:".insteadOf "https://github.com/"`+/// 让个人 git 操作走 SSH。pnpm 解析 `git+https://github.com/...` 插件时同样调用+/// git,URL 被该规则改写后实际走 SSH;桌面机通常没有 SSH 密钥(非交互子进程也+/// 无法应答 known_hosts 询问),于是 `Permission denied (publickey)` /+/// `Host key verification failed` 硬失败(用户可见提示见+/// [`super::diagnose::git_transport_hint`])。检测到该类规则后,把子进程的 git+/// 配置隔离为空文件(`GIT_CONFIG_GLOBAL`)或关闭系统配置(`GIT_CONFIG_NOSYSTEM`),+/// 让 HTTPS 地址原样生效——公开仓库无需任何凭据即可克隆。+///+/// 未命中时返回空 map:普通用户(含只配代理/凭据助手、无 SSH 改写者)的子进程+/// git 配置原样保留,零影响。探测全部为最佳努力——git 缺失、命令失败或输出异常+/// 都视为「无需隔离」,不阻断安装。+///+/// 仅用于桌面端驱动的 `dsh plugin` 子进程(`build_plugin_envs`):不注入长驻服务+/// 进程的环境——那里会被 agent 子进程继承,隔离 git 配置会让 agent 的 git 操作+/// 丢失 user.name/凭据助手/代理等用户配置。+fn git_https_isolation_env(app_handle: &AppHandle) -> HashMap<String, String> {+ let Some(git) = plugin_git_binary(app_handle) else {+ return HashMap::new();+ };+ let mut envs = HashMap::new();+ if git_scope_has_github_ssh_rewrite(&git, &["--global"]) {+ if let Some(config) = empty_git_config_file() {+ log::info!(+ "git config rewrites GitHub HTTPS to SSH (global); isolating GIT_CONFIG_GLOBAL to force HTTPS"+ );+ envs.insert(+ "GIT_CONFIG_GLOBAL".to_string(),+ config.to_string_lossy().into_owned(),+ );+ }+ }+ if git_scope_has_github_ssh_rewrite(&git, &["--system"]) {+ log::info!(+ "git config rewrites GitHub HTTPS to SSH (system); disabling system git config to force HTTPS"+ );+ envs.insert("GIT_CONFIG_NOSYSTEM".to_string(), "1".to_string());+ }+ envs+}++/// 解析插件子进程将使用的 git 可执行文件:Windows 用桌面端已选 Git(系统 Git 或+/// 捆绑 MinGit,见 [`config::get_git_cmd_dir`],与注入子进程 PATH 的目录一致),+/// Unix 直接用 PATH 上的 `git`。+fn plugin_git_binary(app_handle: &AppHandle) -> Option<PathBuf> {+ #[cfg(windows)]+ {+ config::get_git_cmd_dir(app_handle).map(|dir| dir.join("git.exe"))+ }+ #[cfg(not(windows))]+ {+ Some(PathBuf::from("git"))+ }+}++/// 运行 `git config <scope> --get-regexp '^url\.'`,判断该作用域的配置里是否存在+/// 把 GitHub HTTP(S) 改写为 SSH 的 insteadOf 规则。无匹配(git 返回 1)或命令+/// 失败都视为不存在。+fn git_scope_has_github_ssh_rewrite(git: &Path, scope: &[&str]) -> bool {+ let mut cmd = std::process::Command::new(git);+ cmd.args(scope).args(["--get-regexp", "^url\\."]);+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ // CREATE_NO_WINDOW:GUI 进程下禁止闪现控制台窗口+ cmd.creation_flags(0x0800_0000);+ }+ let Ok(output) = cmd.output() else {+ return false;+ };+ if !output.status.success() {+ return false;+ }+ has_github_ssh_rewrite_in_output(&String::from_utf8_lossy(&output.stdout))+}++/// 从 `git config --get-regexp '^url\.'` 的输出文本中判定是否存在把 GitHub+/// HTTP(S) 改写为 SSH 的规则(纯函数,便于单测)。+fn has_github_ssh_rewrite_in_output(output: &str) -> bool {+ output.lines().any(rewrite_rule_targets_ssh_github)+}++/// 判定单条 `url.<base>.insteadOf <value>` 输出行是否为「把 GitHub HTTP(S) 地址+/// 改写为 SSH」的有害规则。git 会把 section/key 名小写化(实际形如+/// `[email protected]:.insteadof`),subsection 与 value 大小写保留;+/// pushInsteadOf(`.pushinsteadof`)不会命中 `.insteadof` 后缀剥离,天然排除+/// (只影响 push,不影响拉取)。+fn rewrite_rule_targets_ssh_github(line: &str) -> bool {+ let mut parts = line.splitn(2, ' ');+ let (key, value) = match (parts.next(), parts.next()) {+ (Some(k), Some(v)) => (k.to_ascii_lowercase(), v.trim()),+ _ => return false,+ };+ let Some(base) = key+ .strip_prefix("url.")+ .and_then(|k| k.strip_suffix(".insteadof"))+ else {+ return false;+ };+ let ssh_base =+ base.starts_with("git@") || base.starts_with("ssh://") || base.starts_with("git+ssh://");+ ssh_base && github_http_host(value)+}++/// value 是否为 GitHub 的 HTTP(S) URL 前缀(如 `https://github.com/`、+/// `https://github.com`、`http://github.com/`)。+fn github_http_host(value: &str) -> bool {+ let value = value.trim();+ let scheme_end = value.find("://").map(|i| i + 3).unwrap_or(0);+ let host = value[scheme_end..]+ .split('/')+ .next()+ .unwrap_or(&value[scheme_end..]);+ host == "github.com" || host == "www.github.com"+}++/// 在系统临时目录创建一个空配置文件,作为隔离后的 `GIT_CONFIG_GLOBAL`。+/// 文件名带进程号与纳秒时间戳防碰撞(0 字节文件由 OS 临时目录回收,无需主动+/// 清理;GIT_CONFIG_GLOBAL 语义为「仅读取该文件」,空文件即无任何全局配置)。+fn empty_git_config_file() -> Option<PathBuf> {+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ let path = std::env::temp_dir().join(format!(+ "dsh-gitconfig-{}-{nanos:x}.empty",+ std::process::id()+ ));+ std::fs::write(&path, "").ok()?;+ Some(path)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rewrite_rule_targets_ssh_github_detects_common_rewrites() {+ // GitHub 官方文档的经典写法:HTTPS -> SSH(scp 风格与 ssh:// 风格)+ assert!(rewrite_rule_targets_ssh_github(+ "[email protected]:.insteadof https://github.com/"+ ));+ assert!(rewrite_rule_targets_ssh_github(+ "url.ssh://[email protected]/.insteadof https://github.com/"+ ));+ assert!(rewrite_rule_targets_ssh_github(+ "url.git+ssh://[email protected]/.insteadof https://github.com"+ ));+ // http 同样属于被改写对象;value 无尾斜杠也能命中+ assert!(rewrite_rule_targets_ssh_github(+ "[email protected]:.insteadof http://github.com"+ ));+ // subsection 大小写保留、key 小写化后仍可识别+ assert!(rewrite_rule_targets_ssh_github(+ "[email protected]:.insteadOf https://github.com/"+ ));+ }++ #[test]+ fn rewrite_rule_targets_ssh_github_ignores_harmless_rules() {+ // 反向规则(ssh -> https)、非 GitHub 主机、https base 都不隔离+ assert!(!rewrite_rule_targets_ssh_github(+ "url.https://github.com/.insteadof [email protected]:"+ ));+ assert!(!rewrite_rule_targets_ssh_github(+ "[email protected]:.insteadof https://gitlab.example.com/"+ ));+ assert!(!rewrite_rule_targets_ssh_github(+ "url.ssh://[email protected]/.pushinsteadof https://github.com/"+ ));+ assert!(!rewrite_rule_targets_ssh_github(+ "url.file:///c:/git/.insteadof https://github.com/"+ ));+ // 非 url 键与空行+ assert!(!rewrite_rule_targets_ssh_github("core.autocrlf true"));+ assert!(!rewrite_rule_targets_ssh_github(""));+ assert!(!rewrite_rule_targets_ssh_github(" "));+ }++ #[test]+ fn has_github_ssh_rewrite_in_output_checks_all_lines() {+ let harmful =+ "core.autocrlf true\nuser.name=x\[email protected]:.insteadof https://github.com/\n";+ assert!(has_github_ssh_rewrite_in_output(harmful));+ let clean =+ "core.autocrlf true\nuser.name=x\nurl.https://github.com/.insteadof [email protected]:\n";+ assert!(!has_github_ssh_rewrite_in_output(clean));+ assert!(!has_github_ssh_rewrite_in_output(""));+ }+}diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rsnew file mode 100644index 00000000..6d528b84--- /dev/null+++ b/src-tauri/src/service/plugin/install/mod.rs@@ -0,0 +1,401 @@+//! 预装插件安装:校验选中项、准备环境(pnpm/dsh shim、按需补齐捆绑 pnpm、+//! 停止运行中的服务),随后调用 `dsh plugin --profile web add <specs...>`,+//! 成功后执行 Windows 极简模式专项修复。+//!+//! pnpm 对两类构建脚本默认不放行、缺白名单时报硬错误:+//! 1. git 托管插件的 `prepare` 构建(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`)——+//! 其允许键随 pnpm 的克隆方式变化(git+ssh#sha / codeload tar.gz),无法预先确定;+//! 2. 传递依赖的原生构建(如 `node-pty`,`ERR_PNPM_IGNORED_BUILDS`)。+//! 因此从 pnpm 错误输出解析它建议的允许键,写入 profile 的+//! `pnpm-workspace.yaml` 后重试,直至成功或无可解析项。+//!+//! pnpm 10 与 11 对放行项的配置键与输出形式不同(均由各自报错提示决定,只能运行期+//! 读取,见 [`allowlist::parse_allowlist_keys`] 与 [`allowlist::apply_allow_build_keys`]):+//! - pnpm 10(旧 store 复用用户版)只认 `onlyBuiltDependencies`(list 形式);+//! - pnpm 11(捆绑版)认 `allowBuilds`(map 形式)。+//! 应用会把同一批包名同时写入这两个键,保证任一版本 pnpm 都能读到放行项。+//!+//! 关键陷阱:pnpm v11 在 `allowBuilds` 阻断时可能仍以 **exit 0** 退出(假成功),+//! 所以重试逻辑不能只看退出码(见 [`run_plugin_with_allow_build_retry`]),安装成功+//! 后还会核验 `node_modules` 产物是否真实落盘(见 [`artifact::verify_installed_products`]),+//! 并就地补构建缺失的声明入口(见 [`artifact::ensure_plugin_entry_built`])。+//!+//! 模块划分(`install/`):+//! - [`self`]:安装编排入口(install / install_internal)与 allowBuilds 重试循环+//! - [`single`]:单插件升级/卸载(`dsh plugin update/remove`,卸载后核验 + 离线兜底、+//! 弃用插件自动卸载)+//! - [`spec`]:安装 spec 准备(内置插件捆绑目录、GitHub 简写规范化、Windows 引号)+//! - [`env`]:`dsh plugin` 子进程环境($DSH_HOME 隔离、git HTTPS 强制)+//! - [`pnpm`]:pnpm 选版与版本探测(store 主版本感知、捆绑版补齐、有界 probe 监控)+//! - [`allowlist`]:构建放行白名单解析与 pnpm-workspace.yaml 写回+//! - [`diagnose`]:失败输出解析(网络 / git 传输层 / ANSI 清洗与消息挑选)+//! - [`artifact`]:安装产物落盘核验(防「假成功」)+ 声明入口就地补构建++use crate::config;+use crate::service::cli;+use crate::service::core;+use crate::service::profile::active_profile;+use crate::service::workflow;+use std::collections::HashMap;+use std::ffi::OsString;+use std::path::Path;+use tauri::{AppHandle, Emitter, Manager, WebviewWindow};++// plugin 兄弟模块的再导出:子模块经 `super::` 统一从这里取,跨模块边界只在此定义。+pub(crate) use super::ensure_profile_npmrc;+pub(crate) use super::errors;+pub(crate) use super::installed::{installed_name, is_installed, profile_dir};+pub(crate) use super::preset::{+ bundled_dep_spec, bundled_plugin_dir, load_presets, PreinstallPluginInfo,+};+pub(crate) use super::process::{+ acquire_operation_lock, acquire_process_lock, new_process_owner, run_plugin_process, PidGuard,+ PreinstallLogPayload, ProcessOwner, PREINSTALL_LOG_EVENT,+};+pub(crate) use super::recovery::is_actionable_plugin_ref;+pub(crate) use super::uninstall_recovery;++mod allowlist;+mod artifact;+mod diagnose;+mod env;+mod pnpm;+mod single;+mod spec;++// 子模块对外 API:plugin 兄弟模块(verify / internal 等)与安装编排共用+pub(crate) use env::build_plugin_envs;+pub(crate) use pnpm::{+ bundled_pnpm_major, harness_prefer_bundled_pnpm, pnpm_major_version_at, profile_store_major,+};+pub(crate) use single::uninstall_deprecated_plugins;+pub use single::{remove, update};++use allowlist::{add_allow_build_keys, parse_allowlist_keys};+use artifact::{ensure_plugin_entry_built, verify_installed_products};+use diagnose::{diagnostic_suffix, git_transport_hint, network_error_hint, pick_error_message};+use pnpm::ensure_pnpm;+use spec::{bundled_dir_of, normalize_git_spec, preset_spec_for_install, shell_quote_spec};++/// 允许构建重试的上限。每次重试解决 pnpm 报出的一个允许键(git depPath 或+/// 传递构建包名),多个 git 插件 / 多个原生依赖各占一次,上限封顶防死循环。+const MAX_ALLOW_LIST_RETRIES: usize = 8;++pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), String> {+ install_with_cancel(app_handle, ids, None, new_process_owner()).await+}++/// 内置插件启动自愈专用入口:取消信号会阻止被结束的 pnpm/dsh 进程再次进入+/// allowBuilds 重试,确保硬上限之后不会悄悄拉起下一棵进程树。+pub(crate) async fn install_internal(+ app_handle: &AppHandle,+ ids: &[String],+ cancel: tokio::sync::watch::Receiver<bool>,+ owner: ProcessOwner,+) -> Result<(), String> {+ install_with_cancel(app_handle, ids, Some(cancel), owner).await+}++async fn install_with_cancel(+ app_handle: &AppHandle,+ ids: &[String],+ cancel: Option<tokio::sync::watch::Receiver<bool>>,+ owner: ProcessOwner,+) -> Result<(), String> {+ if ids.is_empty() {+ return Err("PREINSTALL_EMPTY: no plugins selected".to_string());+ }++ // 单次读取预设并构建查找表,提升算法效率至 O(N)+ let presets = load_presets(app_handle);+ let preset_map: HashMap<&str, &PreinstallPluginInfo> =+ presets.iter().map(|p| (p.id.as_str(), p)).collect();++ let mut specs = Vec::with_capacity(ids.len());+ for id in ids {+ let preset = preset_map+ .get(id.as_str())+ .ok_or_else(|| format!("PREINSTALL_INVALID_ID: {id}"))?;+ // 内置插件改为从随包分发的捆绑目录安装(`link:` 本地联接依赖,见+ // preset::bundled_dep_spec;不用 `file:`——pnpm 对盘符冒号的绝对路径+ // 会当相对路径解析),其余沿用清单声明的 spec;随后统一把+ // `github:user/repo` 规范为显式 `git+https://...`,绕开 pnpm 对+ // GitHub 简写「HTTPS 探测失败即回退 SSH」的已知缺陷(pnpm issue+ // #3948 / #7243 / #13276):公开仓库一旦落进 git+ssh,在没有 SSH 配置+ // 的桌面机上必然 `Host key verification failed` / `Permission denied (publickey)`。+ //+ // 最后经 shell_quote_spec 给含空格的 spec 加内嵌双引号(**仅 Windows**):+ // dsh CLI 只在 win32 用 `shell:true` 启动 pnpm、把参数按空格拼接(Node+ // 不引号转义,DEP0190),内置插件指向应用安装目录(如+ // `G:\Deepseek Harness Desktop\...`,路径常含空格),拼进 shell 后会被+ // 切碎成多个 spec,pnpm 报 `ERR_PNPM_SPEC_NOT_SUPPORTED`,插件装不上、+ // 启动自愈每次重装(死循环)。引号让 cmd 把整条 spec 视为单一 token;+ // pnpm 解析后自行剥离引号,落盘值仍是不带引号的 `link:<路径>`,与内核+ // 对账的 `expected`(bundled_dep_spec)一致。macOS/Linux 是直接+ // `spawnSync`(无 shell),spec 作为单个 argv 传递、空格天然保留,+ // 引号只会被当作包名字符导致安装失败(见 [`shell_quote_spec`])。+ let raw = normalize_git_spec(&preset_spec_for_install(+ preset,+ bundled_dir_of(app_handle, preset),+ )?);+ specs.push(shell_quote_spec(&raw));+ }++ // 确保 pnpm/dsh shim 存在+ cli::ensure_shims(app_handle)?;++ let node = config::get_node_binary_path(app_handle);+ // 活动核心的 dsh 入口:本地核心存在时用本地 CLI,否则预打包+ let dsh_bin = core::active_dsh_binary(app_handle);+ if !node.exists() {+ return Err("NODE_NOT_FOUND: Node.js runtime missing".to_string());+ }+ if !dsh_bin.exists() {+ return Err("HARNESS_NOT_FOUND: dsh CLI missing".to_string());+ }++ let window = app_handle+ .get_webview_window("main")+ .ok_or("WINDOW_NOT_FOUND: main window missing")?;++ // 选定/补齐安装用的 pnpm:返回是否应强制使用捆绑版(版本感知,见 ensure_pnpm)+ let prefer_bundled_pnpm = ensure_pnpm(app_handle, &window, owner).await?;+ // 首次安装可能早于服务启动;提前写入非交互清理配置,避免 pnpm 在无 TTY+ // 环境以 ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY 中止(issue #130)。+ super::ensure_profile_npmrc(app_handle)?;++ // 安装前停止运行中的服务,避免资源冲突+ if workflow::has_owned_process() {+ // 停服务会让用户感到"重启",先在日志面板讲清缘由(issue #48)+ let _ = window.emit(+ PREINSTALL_LOG_EVENT,+ PreinstallLogPayload {+ line: "[harness] 正在停止运行中的服务(安装插件需要短暂重启)…".to_string(),+ },+ );+ log::info!("Stopping running harness service before installing plugins");+ if let Err(e) = workflow::stop(app_handle.clone()).await {+ log::warn!("failed to stop harness before plugin install: {e}");+ }+ }++ let envs = build_plugin_envs(app_handle, prefer_bundled_pnpm);++ // 拼装命令行参数+ let mut args = vec![+ dsh_bin.as_os_str().to_os_string(),+ OsString::from("plugin"),+ OsString::from("--profile"),+ OsString::from(active_profile(app_handle)),+ OsString::from("add"),+ ];+ args.extend(specs.iter().map(|s| OsString::from(s.as_str())));++ let cwd = config::get_dsh_install_path(app_handle);+ // 日志打印实际传给 dsh 的 spec(此前打印 id 会误导排查:安装用的是 spec)+ log::info!("Running dsh plugin install for {specs:?}");++ // `dsh plugin add` 在 profile 目录里驱动 pnpm。pnpm v11 会拦下 git 托管+ // 插件的 prepare 构建与传递原生依赖(见模块头注),其允许键不可预知,因此+ // 失败时解析输出里印出的 `allowBuilds` 键写回 profile 的 pnpm-workspace.yaml+ // 后重试,直至成功或再无键可加(升级路径同样依赖该重试,见+ // [`run_plugin_with_allow_build_retry`])。+ let (exit_code, last_output) = run_plugin_with_allow_build_retry(+ app_handle,+ &node,+ &args,+ &cwd,+ &envs,+ &window,+ "install",+ cancel.as_ref(),+ owner,+ )+ .await?;++ if exit_code != 0 {+ log::error!("dsh plugin install failed with exit code {exit_code}");+ // 区分 git 传输层失败与 allowBuilds 构建门禁:前者是 pnpm 走了 git+ssh+ // (用户环境无 SSH 配置),后者才是补充白名单可自愈的。传输层错误给出+ // 可读指引,避免用户被 dsh 那条 allowBuilds 提示误导。+ let network_error = network_error_hint(&last_output).is_some()+ || (exit_code == 3 && last_output.trim().is_empty());+ let hint = git_transport_hint(&last_output);+ let network_hint = network_error.then_some(+ "NETWORK_ERROR: plugin registry request failed; check network or proxy settings and retry.",+ );+ let message = if network_error {+ network_hint.unwrap_or_default().to_string()+ } else {+ pick_error_message(&last_output, hint)+ };+ // 批量安装失败时给本次选中的每个插件记一条错误(前端据此展示异常标记,+ // 可针对单个插件重试更新/卸载)+ for id in ids {+ if let Err(e) = errors::record(app_handle, id, "install", &message) {+ log::warn!("failed to record plugin error for {id}: {e}");+ }+ }+ if let Some(network_hint) = network_hint {+ log::warn!("network failure detected during plugin install: {network_hint}");+ let _ = window.emit(+ PREINSTALL_LOG_EVENT,+ PreinstallLogPayload {+ line: format!("[network] {network_hint}"),+ },+ );+ return Err(format!("NETWORK_ERROR: {network_hint}"));+ }+ if let Some(hint) = hint {+ log::warn!("git transport failure detected during plugin install: {hint}");+ let _ = window.emit(+ PREINSTALL_LOG_EVENT,+ PreinstallLogPayload {+ line: format!("[pnpm] {hint}"),+ },+ );+ return Err(format!(+ "PREINSTALL_FAILED: dsh plugin exited with code {exit_code} ({hint})"+ ));+ }+ let detail = pick_error_message(&last_output, None);+ if !detail.is_empty() {+ log::error!("dsh plugin install diagnostic: {detail}");+ }+ return Err(format!(+ "PREINSTALL_FAILED: dsh plugin exited with code {exit_code}{}",+ diagnostic_suffix(&detail)+ ));+ }++ // 真正修复:核验本次安装是否真实落盘。pnpm 可能在 allowBuilds 阻断时仍以+ // exit 0 退出(假成功),若产物缺失则记录错误并返回 Err,让前端如实展示失败、+ // 允许重试,而不是误报「已安装」。已落盘的插件在上一步被核验并清除历史错误。+ verify_installed_products(app_handle, ids, &preset_map, &last_output)?;++ // 产物级核验:包已落盘但声明入口(如 `lib/index.js`)未构建时,本次安装+ // 同样是假成功——cordis 加载器在下一次启动必然 ERR_MODULE_NOT_FOUND 崩溃+ // (见 [`ensure_plugin_entry_built`])。就地补构建或如实报错,不让坏态+ // 静默进入下一次启动;包目录按预设的 `installed_name` 解析(scoped 插件+ // 与 id 不同名),失败跨插件聚合后一次性返回,前端可一并重试。+ let mut entry_errors = Vec::new();+ for id in ids {+ let Some(preset) = preset_map.get(id.as_str()) else {+ continue;+ };+ let pkg_dir = profile_dir(app_handle)+ .join("node_modules")+ .join(installed_name(preset));+ if let Err(e) = ensure_plugin_entry_built(app_handle, id, &pkg_dir, &envs, &window).await {+ if let Err(err) = errors::record(app_handle, id, "install", &e) {+ log::warn!("failed to record plugin error for {id}: {err}");+ }+ entry_errors.push(format!("{id}: {e}"));+ }+ }+ if !entry_errors.is_empty() {+ return Err(format!(+ "PREINSTALL_ENTRY_FAILED:\n{}",+ entry_errors.join("\n")+ ));+ }++ // Windows 极简模式专项修复+ if ids.iter().any(|id| id == "dsh-win-terminal-inspector") {+ if let Err(e) = workflow::win_inspector::apply(app_handle) {+ log::warn!("win inspector apply failed after install: {e}");+ }+ }++ // 告知用户安装阶段结束;随后的服务重启由前端 continueAfterPreinstall 负责+ let _ = window.emit(+ PREINSTALL_LOG_EVENT,+ PreinstallLogPayload {+ line: format!("[harness] 已安装 {} 个插件", ids.len()),+ },+ );++ log::info!("Preinstall plugins installed successfully: {ids:?}");+ Ok(())+}++async fn run_plugin_with_allow_build_retry(+ app_handle: &AppHandle,+ node: &Path,+ args: &[OsString],+ cwd: &Path,+ envs: &HashMap<String, String>,+ window: &WebviewWindow,+ action: &str,+ cancel: Option<&tokio::sync::watch::Receiver<bool>>,+ owner: ProcessOwner,+) -> Result<(i32, String), String> {+ let _operation_guard = acquire_operation_lock().await;+ let mut retries = 0usize;+ let mut all_output = String::new();+ let exit_code = loop {+ if cancel.is_some_and(|signal| *signal.borrow()) {+ return Err("PLUGIN_OPERATION_CANCELLED: plugin operation was cancelled".to_string());+ }+ let (code, captured) = run_plugin_process(node, args, cwd, envs, window, owner).await?;+ if cancel.is_some_and(|signal| *signal.borrow()) {+ return Err("PLUGIN_OPERATION_CANCELLED: plugin operation was cancelled".to_string());+ }+ append_command_output(&mut all_output, &captured);+ let new_keys = parse_allowlist_keys(&captured);+ // 有可补充的 allowBuilds 键且未达上限 → 写入并重试(无论本次退出码是否为 0,+ // 见上方注释:pnpm 可能在阻断时仍以 0 退出)。+ if !new_keys.is_empty() && retries < MAX_ALLOW_LIST_RETRIES {+ retries += 1;+ add_allow_build_keys(app_handle, &new_keys)?;+ log::info!("pnpm allowBuilds updated with {new_keys:?}, retrying {action} ({retries})");+ let _ = window.emit(+ PREINSTALL_LOG_EVENT,+ PreinstallLogPayload {+ line: format!("[pnpm] 已放行插件构建(allowBuilds),重试{action}…"),+ },+ );+ continue;+ }+ // 到达重试上限仍解析到待放行键:pnpm 的 exit 0 在 allowBuilds 场景不可信,+ // 直接视为失败(即便退出码为 0),交由调用方走失败 / 产物核验分支。+ if !new_keys.is_empty() {+ log::error!(+ "dsh plugin {action}: allowBuilds retry limit reached ({retries}), keys {new_keys:?} unresolved"+ );+ break if code == 0 { 1 } else { code };+ }+ if code != 0 {+ log::error!(+ "dsh plugin {action} failed with exit code {code}; no allowBuilds entries to add"+ );+ }+ break code;+ };+ Ok((exit_code, all_output))+}++/// 合并单次命令输出,并在相邻尝试之间补换行,保证后续错误解析不会粘连两段日志。+pub(super) fn append_command_output(all_output: &mut String, captured: &str) {+ if captured.is_empty() {+ return;+ }+ if !all_output.is_empty() && !all_output.ends_with('\n') {+ all_output.push('\n');+ }+ all_output.push_str(captured);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn command_output_retains_earlier_retry_diagnostics() {+ let mut output = String::new();+ append_command_output(&mut output, "ERR_PNPM_IGNORED_BUILDS");+ append_command_output(&mut output, "");++ assert_eq!(output, "ERR_PNPM_IGNORED_BUILDS");+ }+}diff --git a/src-tauri/src/service/plugin/install/pnpm.rs b/src-tauri/src/service/plugin/install/pnpm.rsnew file mode 100644index 00000000..ef89d7ab--- /dev/null+++ b/src-tauri/src/service/plugin/install/pnpm.rs@@ -0,0 +1,832 @@+//! pnpm 选版与版本探测:store 主版本感知(pnpm 10 与 11 的 store 布局互不兼容)、+//! 用户 pnpm 探测(注入桌面端选定 Node 的 PATH,见 issue #182;wait/cleanup 全程+//! 有界监控,见 probe 机制)、捆绑版按需补齐下载,以及服务启动时的+//! `DSH_PREFER_BUNDLED_PNPM` 决策(启动阶段不触发下载)。++use crate::config;+use crate::service::cli;+use crate::service::download;+use crate::service::download::Installable;+use std::ffi::OsString;+use std::io::Read;+use std::path::Path;+#[cfg(test)]+use std::path::PathBuf;+use tauri::{AppHandle, Emitter, WebviewWindow};++use super::acquire_process_lock;+use super::profile_dir;+use super::PidGuard;+use super::PreinstallLogPayload;+use super::ProcessOwner;+use super::PREINSTALL_LOG_EVENT;++const MIN_TRUSTED_PNPM_MAJOR: u32 = 10;+const PNPM_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);+const PNPM_PROBE_CLEANUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);+const PNPM_PROBE_REAP_RETRY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);+const PNPM_PROBE_REAP_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_millis(25);+const PNPM_PROBE_LIVENESS_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);++pub(super) async fn ensure_pnpm(+ app_handle: &AppHandle,+ window: &WebviewWindow,+ owner: ProcessOwner,+) -> Result<bool, String> {+ // 档案的 node_modules 由哪个 pnpm 主版本创建(.modules.yaml 的 storeDir 段)+ let store_major = profile_store_major(app_handle);+ let user_major = user_pnpm_major_version_bounded(app_handle, owner).await?;++ // 1) store 主版本已知 → 优先选与 store 一致的 pnpm(用户版或捆绑版)+ if let Some(store) = store_major {+ if user_major == Some(store) {+ log::info!("Reusing user-installed pnpm (major {store}) matching profile store");+ return Ok(false);+ }+ if bundled_pnpm_major(app_handle) == Some(store) {+ log::info!("Using bundled pnpm (major {store}) matching profile store");+ return Ok(true);+ }+ log::warn!(+ "No pnpm matches profile store major {store} (user {user_major:?}), falling back to user pnpm"+ );+ }++ // 2) store 未知(全新档案/未装过依赖)或无可匹配版本 → 用户 pnpm ≥ 10 优先+ match user_major {+ Some(major) if major >= MIN_TRUSTED_PNPM_MAJOR => {+ log::info!("Reusing user-installed pnpm (major {major}) for plugin install");+ return Ok(false);+ }+ Some(major) => {+ log::warn!(+ "User pnpm major {major} < {MIN_TRUSTED_PNPM_MAJOR} (missing autoInstallPeers/workspace-root semantics), using bundled pnpm"+ );+ }+ None => {+ log::warn!(+ "User pnpm version not detectable (broken/blocked shim?), using bundled pnpm"+ );+ }+ }++ // 捆绑版已存在 → 直接用(零额外下载);否则下载。+ if config::get_pnpm_binary_path(app_handle).exists() {+ return Ok(true);+ }++ let _ = window.emit(+ PREINSTALL_LOG_EVENT,+ PreinstallLogPayload {+ line: "[pnpm] bundled pnpm not found, downloading before plugin install".to_string(),+ },+ );++ let tracker = download::ProgressTracker::new(window, 2);+ let url = download::Pnpm.get_download_url()?;+ let name = url.split('/').next_back().unwrap_or(&url).to_string();+ let buffer = download::download_file(&tracker, url)+ .await+ .map_err(|e| format!("PNPM_DOWNLOAD_FAILED: {e}"))?;+ download::verify_sha256(&buffer, config::PNPM_SHA256)+ .map_err(|e| format!("PNPM_INTEGRITY_FAILED: {e}"))?;+ let dest = download::Pnpm.get_install_path(app_handle);++ download::ensure_extract(&tracker, name, buffer, dest)+ .await+ .map_err(|e| format!("PNPM_EXTRACT_FAILED: {e}"))?;++ let _ = window.emit(+ PREINSTALL_LOG_EVENT,+ PreinstallLogPayload {+ line: "[pnpm] bundled pnpm ready".to_string(),+ },+ );+ Ok(true)+}++async fn user_pnpm_major_version_bounded(+ app_handle: &AppHandle,+ owner: ProcessOwner,+) -> Result<Option<u32>, String> {+ let Some(pnpm) = cli::find_user_pnpm(app_handle) else {+ return Ok(None);+ };+ let node = config::get_node_binary_path(app_handle);+ let mut command = std::process::Command::new(&pnpm);+ command.arg("--version");+ if let Some(path) = pnpm_probe_path(&pnpm, Some(&node)) {+ command.env("PATH", path);+ }+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ command.creation_flags(0x0800_0000);+ }+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt;+ command.process_group(0);+ }++ let process_guard = acquire_process_lock().await?;+ let child = match command+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .spawn()+ {+ Ok(child) => child,+ Err(error) => {+ log::warn!(+ "pnpm version probe failed to spawn {}: {error}",+ pnpm.display()+ );+ return Ok(None);+ }+ };+ let pid = child.id();+ let pid_guard = PidGuard::set(owner, pid);+ let mut waiter = tauri::async_runtime::spawn_blocking(move || {+ let mut child = child;+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ wait_for_probe_output(&mut child)+ }))+ .unwrap_or_else(|_| {+ super::super::cancel::terminate_pid_tree(pid);+ ProbeWaitResult::CleanupPending {+ pid,+ reason: format!(+ "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe pid {pid} panicked before cleanup completed"+ ),+ }+ });+ match result {+ ProbeWaitResult::Finished(result) => ProbeTaskResult::Finished(result),+ ProbeWaitResult::CleanupPending { pid, reason } => {+ ProbeTaskResult::CleanupPending { child, pid, reason }+ }+ }+ });++ let output = match tokio::time::timeout(PNPM_PROBE_TIMEOUT, &mut waiter).await {+ Ok(joined) => {+ let Some(task) = probe_task_or_fallback(&pnpm, joined) else {+ let reason =+ "PNPM_PROBE_WAIT_TASK_FAILED: pnpm version probe wait task failed".to_string();+ monitor_orphaned_probe_pid(owner, pid, reason, process_guard, pid_guard);+ return Ok(None);+ };+ match task {+ ProbeTaskResult::Finished(waited) => {+ match probe_output_or_fallback(&pnpm, waited)? {+ Some(output) => output,+ None => return Ok(None),+ }+ }+ ProbeTaskResult::CleanupPending { child, pid, reason } => {+ let pending = ProbeCleanupPending {+ child,+ pid,+ reason,+ owner,+ _process_guard: process_guard,+ _pid_guard: pid_guard,+ };+ let reason = pending.reason.clone();+ monitor_probe_cleanup(pending);+ return Err(reason);+ }+ }+ }+ Err(_) => {+ let reason = format!(+ "PNPM_PROBE_TIMEOUT: pnpm version probe exceeded {} seconds",+ PNPM_PROBE_TIMEOUT.as_secs()+ );+ log::error!("{reason}");+ super::super::process::mark_process_cleanup_failed(owner, reason.clone());+ super::super::cancel::terminate_owned_install(owner).await;+ let cleanup = match tokio::time::timeout(PNPM_PROBE_CLEANUP_TIMEOUT, &mut waiter).await+ {+ Ok(cleanup) => cleanup,+ Err(_) => {+ let cleanup_reason =+ "PNPM_PROBE_CLEANUP_TIMEOUT: pnpm version probe did not exit after forced termination"+ .to_string();+ monitor_probe_wait_task(+ waiter,+ owner,+ pid,+ cleanup_reason.clone(),+ process_guard,+ pid_guard,+ );+ return Err(cleanup_reason);+ }+ };+ match cleanup {+ Ok(ProbeTaskResult::Finished(_)) => {+ super::super::process::clear_process_cleanup_failed(owner);+ return Err(reason);+ }+ Ok(ProbeTaskResult::CleanupPending { child, pid, reason }) => {+ let pending = ProbeCleanupPending {+ child,+ pid,+ reason,+ owner,+ _process_guard: process_guard,+ _pid_guard: pid_guard,+ };+ let cleanup_reason = pending.reason.clone();+ monitor_probe_cleanup(pending);+ return Err(cleanup_reason);+ }+ Err(error) => {+ monitor_orphaned_probe_pid(+ owner,+ pid,+ format!(+ "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe wait task failed during cleanup: {error}"+ ),+ process_guard,+ pid_guard,+ );+ return Err(format!(+ "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe wait task failed during cleanup: {error}"+ ));+ }+ }+ }+ };+ Ok(parse_pnpm_major_output(&pnpm, &output))+}++enum ProbeWaitResult {+ Finished(std::io::Result<std::process::Output>),+ CleanupPending { pid: u32, reason: String },+}++enum ProbeTaskResult {+ Finished(std::io::Result<std::process::Output>),+ CleanupPending {+ child: std::process::Child,+ pid: u32,+ reason: String,+ },+}++struct ProbeCleanupPending {+ child: std::process::Child,+ pid: u32,+ reason: String,+ owner: ProcessOwner,+ _process_guard: tokio::sync::OwnedMutexGuard<()>,+ _pid_guard: PidGuard,+}++impl ProbeCleanupPending {+ fn release(self) {+ let Self {+ child,+ owner,+ _process_guard,+ _pid_guard,+ ..+ } = self;+ super::super::process::release_process_cleanup(owner, _pid_guard, _process_guard);+ drop(child);+ }+}++fn wait_for_probe_output(child: &mut std::process::Child) -> ProbeWaitResult {+ let pid = child.id();+ let stdout = child.stdout.take();+ let stderr = child.stderr.take();+ let stdout_reader = match std::thread::Builder::new()+ .name("pnpm-probe-stdout".to_string())+ .spawn(move || read_probe_pipe(stdout))+ {+ Ok(reader) => reader,+ Err(error) => return reap_probe_after_wait_failure(child, pid, error),+ };+ let stderr_reader = match std::thread::Builder::new()+ .name("pnpm-probe-stderr".to_string())+ .spawn(move || read_probe_pipe(stderr))+ {+ Ok(reader) => reader,+ Err(error) => return reap_probe_after_wait_failure(child, pid, error),+ };++ let status = match child.wait() {+ Ok(status) => status,+ Err(error) => return reap_probe_after_wait_failure(child, pid, error),+ };+ let stdout = match join_probe_reader(stdout_reader) {+ Ok(stdout) => stdout,+ Err(error) => return ProbeWaitResult::Finished(Err(error)),+ };+ let stderr = match join_probe_reader(stderr_reader) {+ Ok(stderr) => stderr,+ Err(error) => return ProbeWaitResult::Finished(Err(error)),+ };+ ProbeWaitResult::Finished(Ok(std::process::Output {+ status,+ stdout,+ stderr,+ }))+}++fn reap_probe_after_wait_failure(+ child: &mut std::process::Child,+ pid: u32,+ error: std::io::Error,+) -> ProbeWaitResult {+ super::super::cancel::terminate_pid_tree(pid);+ if let Err(kill_error) = child.kill() {+ log::warn!("pnpm version probe kill after wait failure failed: {kill_error}");+ }+ let started = std::time::Instant::now();+ loop {+ match child.try_wait() {+ Ok(Some(_)) => return ProbeWaitResult::Finished(Err(error)),+ Ok(None) => {}+ Err(cleanup_error) => {+ log::warn!("pnpm version probe reap after wait failure failed: {cleanup_error}");+ if super::super::process::plugin_process_has_exited(pid) {+ return ProbeWaitResult::Finished(Err(error));+ }+ }+ }+ if started.elapsed() >= PNPM_PROBE_REAP_RETRY_TIMEOUT {+ return ProbeWaitResult::CleanupPending {+ pid,+ reason: format!(+ "PNPM_PROBE_CLEANUP_FAILED: pnpm version probe pid {pid} could not be reaped after wait failure: {error}"+ ),+ };+ }+ std::thread::sleep(PNPM_PROBE_REAP_RETRY_INTERVAL);+ }+}++fn monitor_probe_cleanup(mut pending: ProbeCleanupPending) {+ super::super::process::mark_process_cleanup_failed(pending.owner, pending.reason.clone());+ tauri::async_runtime::spawn(async move {+ wait_for_probe_cleanup(&mut pending).await;+ pending.release();+ });+}++fn monitor_probe_wait_task(+ waiter: tauri::async_runtime::JoinHandle<ProbeTaskResult>,+ owner: ProcessOwner,+ pid: u32,+ reason: String,+ process_guard: tokio::sync::OwnedMutexGuard<()>,+ pid_guard: PidGuard,+) {+ super::super::process::mark_process_cleanup_failed(owner, reason);+ tauri::async_runtime::spawn(async move {+ match waiter.await {+ Ok(ProbeTaskResult::CleanupPending { child, pid, reason }) => {+ let mut pending = ProbeCleanupPending {+ child,+ pid,+ reason,+ owner,+ _process_guard: process_guard,+ _pid_guard: pid_guard,+ };+ wait_for_probe_cleanup(&mut pending).await;+ pending.release();+ }+ Ok(ProbeTaskResult::Finished(_)) => {+ super::super::process::release_process_cleanup(owner, pid_guard, process_guard);+ }+ Err(error) => {+ log::error!("pnpm version probe cleanup wait task failed: {error}");+ wait_for_probe_cleanup_with(+ || !super::super::process::plugin_process_has_exited(pid),+ PNPM_PROBE_LIVENESS_INTERVAL,+ )+ .await;+ super::super::process::release_process_cleanup(owner, pid_guard, process_guard);+ }+ }+ });+}++fn monitor_orphaned_probe_pid(+ owner: ProcessOwner,+ pid: u32,+ reason: String,+ process_guard: tokio::sync::OwnedMutexGuard<()>,+ pid_guard: PidGuard,+) {+ super::super::process::mark_process_cleanup_failed(owner, reason);+ super::super::cancel::terminate_pid_tree(pid);+ tauri::async_runtime::spawn(async move {+ wait_for_probe_cleanup_with(+ || !super::super::process::plugin_process_has_exited(pid),+ PNPM_PROBE_LIVENESS_INTERVAL,+ )+ .await;+ super::super::process::release_process_cleanup(owner, pid_guard, process_guard);+ });+}++async fn wait_for_probe_cleanup(pending: &mut ProbeCleanupPending) {+ wait_for_probe_cleanup_with(+ || match pending.child.try_wait() {+ Ok(Some(_)) => false,+ Ok(None) => true,+ Err(error) => {+ log::warn!(+ "pnpm version probe cleanup monitor wait failed for pid {}: {error}",+ pending.pid+ );+ !super::super::process::plugin_process_has_exited(pending.pid)+ }+ },+ PNPM_PROBE_LIVENESS_INTERVAL,+ )+ .await;+ log::info!(+ "pnpm version probe cleanup monitor released pid {}",+ pending.pid+ );+}++async fn wait_for_probe_cleanup_with<F>(mut remains_active: F, interval: std::time::Duration)+where+ F: FnMut() -> bool,+{+ while remains_active() {+ tokio::time::sleep(interval).await;+ }+}++fn read_probe_pipe<R: Read>(pipe: Option<R>) -> std::io::Result<Vec<u8>> {+ let mut output = Vec::new();+ if let Some(mut pipe) = pipe {+ pipe.read_to_end(&mut output)?;+ }+ Ok(output)+}++fn join_probe_reader(+ reader: std::thread::JoinHandle<std::io::Result<Vec<u8>>>,+) -> std::io::Result<Vec<u8>> {+ reader+ .join()+ .map_err(|_| std::io::Error::other("pnpm version probe output reader thread panicked"))?+}++fn log_probe_fallback(pnpm: &Path, phase: &str, error: impl std::fmt::Display) {+ log::warn!(+ "pnpm version probe {phase} failed for {}: {error}; falling back to bundled pnpm",+ pnpm.display()+ );+}++fn probe_task_or_fallback<T, E: std::fmt::Display>(pnpm: &Path, result: Result<T, E>) -> Option<T> {+ match result {+ Ok(task) => Some(task),+ Err(error) => {+ log_probe_fallback(pnpm, "wait task", error);+ None+ }+ }+}++fn probe_output_or_fallback(+ pnpm: &Path,+ result: std::io::Result<std::process::Output>,+) -> Result<Option<std::process::Output>, String> {+ match result {+ Ok(output) => Ok(Some(output)),+ Err(error) => {+ log_probe_fallback(pnpm, "output", error);+ Ok(None)+ }+ }+}++/// 用户 pnpm 主版本号(解析 `pnpm --version` 首个点分字段);不存在或不可运行+/// (corepack shim 在 Node 24 上 ERR_INVALID_THIS 崩溃等)返回 None。+///+/// 供 [`ensure_pnpm`] 选版与 [`crate::service::plugin::verify`] 的修复选版共用(store 主版本匹配)。+pub(crate) fn user_pnpm_major_version(app_handle: &AppHandle) -> Option<u32> {+ let pnpm = cli::find_user_pnpm(app_handle)?;+ let node = config::get_node_binary_path(app_handle);+ pnpm_major_version_at_with_node(&pnpm, Some(&node))+}++/// 探测精确 pnpm 可执行路径的主版本,供直接执行路径校验实际将运行的文件。+pub(crate) fn pnpm_major_version_at(pnpm: &Path) -> Option<u32> {+ pnpm_major_version_at_with_node(pnpm, None)+}++/// 在受控 Node 环境中探测 pnpm 主版本。Windows GUI 进程继承的 PATH 可能早于+/// Node/pnpm 安装,而 corepack 的 `pnpm.cmd` 需要通过 PATH 调用 `node`;探测时+/// 必须注入桌面端已经选定的 Node 目录,否则会把健康 pnpm 误判为不可用(issue #182)。+fn pnpm_major_version_at_with_node(pnpm: &Path, node: Option<&Path>) -> Option<u32> {+ let mut cmd = std::process::Command::new(pnpm);+ cmd.arg("--version");+ if let Some(path) = pnpm_probe_path(pnpm, node) {+ cmd.env("PATH", path);+ }+ // 打包版是 GUI 进程(无控制台):版本探测不能弹出可见黑窗。+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW+ }+ let output = match cmd.output() {+ Ok(output) => output,+ Err(error) => {+ log::warn!(+ "pnpm version probe failed to spawn {}: {error}",+ pnpm.display()+ );+ return None;+ }+ };+ parse_pnpm_major_output(pnpm, &output)+}++fn parse_pnpm_major_output(pnpm: &Path, output: &std::process::Output) -> Option<u32> {+ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ log::warn!(+ "pnpm version probe failed for {} with status {}: {}",+ pnpm.display(),+ output.status,+ stderr.trim()+ );+ return None;+ }+ let stdout = String::from_utf8_lossy(&output.stdout);+ stdout.split('.').next()?.trim().parse::<u32>().ok()+}++/// 构建 pnpm 探测专用 PATH:用户 pnpm 所在目录和选定 Node 目录前置,其余环境保留。+fn pnpm_probe_path(pnpm: &Path, node: Option<&Path>) -> Option<OsString> {+ let mut paths = Vec::new();+ // 选定 Node 必须位于 pnpm shim 目录之前:corepack 目录可能残留另一份 node,+ // bare `node` 应与桌面端预检和后续插件命令使用同一运行时。+ if let Some(parent) = node.and_then(Path::parent) {+ paths.push(parent.to_path_buf());+ }+ if let Some(parent) = pnpm.parent() {+ paths.push(parent.to_path_buf());+ }+ paths.extend(std::env::split_paths(+ &std::env::var_os("PATH").unwrap_or_default(),+ ));+ std::env::join_paths(paths).ok()+}++/// 档案 `node_modules` 使用的 pnpm store 主版本(`<profile>/node_modules/.modules.yaml`+/// 的 `storeDir` 路径段,如 `...\store\v10` → 10)。+///+/// pnpm 10 与 11 的 store 布局互不兼容:用与 store 主版本不一致的 pnpm 更新+/// 已装插件会 `ERR_PNPM_UNEXPECTED_STORE` 退出。档案尚未安装过依赖(没有+/// node_modules)时返回 `None`,由调用方走"全新档案"逻辑。+/// 供 [`ensure_pnpm`] 选版与 [`crate::service::plugin::verify`] 的修复选版共用。+pub(crate) fn profile_store_major(app_handle: &AppHandle) -> Option<u32> {+ let modules_yaml = profile_dir(app_handle)+ .join("node_modules")+ .join(".modules.yaml");+ let content = std::fs::read_to_string(modules_yaml).ok()?;+ parse_store_major_from_modules_yaml(&content)+}++/// 从 `.modules.yaml` 文本解析 store 主版本(纯函数,便于单测)。+fn parse_store_major_from_modules_yaml(content: &str) -> Option<u32> {+ let store_dir = content+ .lines()+ .find_map(|line| line.trim().strip_prefix("storeDir:").map(str::trim))?;+ // storeDir 形如 `C:\Users\xx\AppData\Local\pnpm\store\v10`,取末段 `v10` 的数字+ let major = store_dir+ .trim_matches(['"', '\''])+ .rsplit(['\\', '/'])+ .next()?+ .strip_prefix('v')?;+ major.parse().ok()+}++/// 捆绑版 pnpm 的主版本(读 `dependencies/pnpm/package.json` 的 version 字段);+/// 未安装或清单缺失返回 None。+///+/// 供 [`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()?;+ let value: serde_json::Value = serde_json::from_str(&content).ok()?;+ value+ .get("version")?+ .as_str()?+ .split('.')+ .next()?+ .parse()+ .ok()+}++/// 从 pnpm 失败输出中解析需写入构建放行白名单的包名/键集合。+///+/// 兼容 pnpm 10 与 11 的两套输出形式(两者对 git 托管插件 prepare 门禁的提示不同):+/// - pnpm 11(捆绑版)提示 `allowBuilds:\n <key>: true`(map 形式),原样采纳 `<key>`;+/// - pnpm 10(旧 store 复用用户版)提示 `onlyBuiltDependencies:\n - "<name>"`+/// (list 形式)与报错文本里的包名,二者归并取包名;++pub(crate) fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> bool {+ let store_major = profile_store_major(app_handle);+ let user_major = user_pnpm_major_version(app_handle);+ let bundled_major = bundled_pnpm_major(app_handle);+ // 捆绑版未安装 → 无法强制,交还用户 pnpm(shim 默认用户优先)+ if !config::get_pnpm_binary_path(app_handle).exists() {+ return false;+ }+ match store_major {+ Some(store) => bundled_major == Some(store) && user_major != Some(store),+ None => match user_major {+ Some(major) if major >= MIN_TRUSTED_PNPM_MAJOR => false,+ _ => true,+ },+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn pnpm_probe_wait_and_output_failures_fall_back_to_bundled() {+ let pnpm = PathBuf::from("broken-pnpm");+ let output = probe_output_or_fallback(+ &pnpm,+ Err(std::io::Error::new(+ std::io::ErrorKind::BrokenPipe,+ "output pipe closed",+ )),+ )+ .unwrap();++ assert!(output.is_none());+ }++ #[test]+ fn pnpm_probe_wait_task_join_failure_falls_back_to_bundled() {+ let pnpm = PathBuf::from("broken-pnpm");+ let task: Option<()> = probe_task_or_fallback(&pnpm, Err("blocking worker dropped"));+ assert!(task.is_none());+ }++ #[tokio::test]+ async fn pnpm_probe_cleanup_monitor_releases_after_process_disappears() {+ let polls = std::sync::atomic::AtomicUsize::new(0);+ tokio::time::timeout(+ std::time::Duration::from_millis(50),+ wait_for_probe_cleanup_with(+ || polls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,+ std::time::Duration::from_millis(1),+ ),+ )+ .await+ .expect("cleanup monitor should release after liveness turns false");+ assert_eq!(polls.load(std::sync::atomic::Ordering::SeqCst), 3);+ }++ #[tokio::test]+ async fn pnpm_probe_cleanup_monitor_stays_fail_closed_while_process_lives() {+ let pending = tokio::time::timeout(+ std::time::Duration::from_millis(5),+ wait_for_probe_cleanup_with(|| true, std::time::Duration::from_millis(1)),+ )+ .await;+ assert!(pending.is_err());+ }++ struct BrokenPipeReader;++ impl std::io::Read for BrokenPipeReader {+ fn read(&mut self, _buffer: &mut [u8]) -> std::io::Result<usize> {+ Err(std::io::Error::new(+ std::io::ErrorKind::BrokenPipe,+ "probe output pipe closed",+ ))+ }+ }++ #[test]+ fn pnpm_probe_broken_output_pipe_is_reported_as_fallback_failure() {+ let error = read_probe_pipe(Some(BrokenPipeReader)).unwrap_err();+ assert_eq!(error.kind(), std::io::ErrorKind::BrokenPipe);+ }++ #[cfg(unix)]+ #[test]+ fn pnpm_major_version_at_probes_the_exact_selected_path() {+ use std::os::unix::fs::PermissionsExt;+ use std::time::{SystemTime, UNIX_EPOCH};++ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let root =+ std::env::temp_dir().join(format!("dsh-pnpm-major-{}-{nonce}", std::process::id()));+ std::fs::create_dir_all(&root).unwrap();+ let selected = root.join("selected-pnpm");+ let other = root.join("other-pnpm");+ std::fs::write(&selected, "#!/bin/sh\nprintf '11.2.0\\n'\n").unwrap();+ std::fs::write(&other, "#!/bin/sh\nprintf '10.9.0\\n'\n").unwrap();+ for path in [&selected, &other] {+ let mut permissions = std::fs::metadata(path).unwrap().permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(path, permissions).unwrap();+ }++ assert_eq!(pnpm_major_version_at(&selected), Some(11));+ assert_eq!(pnpm_major_version_at(&other), Some(10));+ let _ = std::fs::remove_dir_all(root);+ }++ /// 回归 Windows GUI 的陈旧 PATH:pnpm shim 必须解析到桌面端选定的 Node,+ /// 即使 shim 同目录存在冲突的 node,且路径包含空格和 shell 元字符。+ #[cfg(windows)]+ #[test]+ fn pnpm_major_version_probe_injects_selected_node_for_cmd_shim() {+ use std::time::{SystemTime, UNIX_EPOCH};++ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let root =+ std::env::temp_dir().join(format!("dsh pnpm cmd major {} {nonce}", std::process::id()));+ let pnpm_dir = root.join("pnpm & corepack");+ let node_dir = root.join("selected node");+ std::fs::create_dir_all(&pnpm_dir).unwrap();+ std::fs::create_dir_all(&node_dir).unwrap();+ let selected = pnpm_dir.join("pnpm.cmd");+ let node = node_dir.join("node.cmd");+ std::fs::write(&selected, "@echo off\r\nnode --version\r\n").unwrap();+ // shim 目录里的冲突运行时若优先会输出 9;选定 Node 必须抢在它前面。+ std::fs::write(pnpm_dir.join("node.cmd"), "@echo off\r\necho 9.0.0\r\n").unwrap();+ std::fs::write(&node, "@echo off\r\necho 11.24.0\r\n").unwrap();++ assert_eq!(+ pnpm_major_version_at_with_node(&selected, Some(&node)),+ Some(11)+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn store_major_parsed_from_modules_yaml() {+ // 真实 pnpm v10 写入的 .modules.yaml:storeDir 指向 store\v10+ let content = "\+lockfileVersion: '9.0'+settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false+dependencies:+ '@deepseek-ai/dsh-base': 0.0.4+ '@deepseek-ai/dsh-web-app': 0.0.4+storeDir: C:\\Users\\test\\AppData\\Local\\pnpm\\store\\v10+virtualStoreDir: node_modules/.pnpm+";+ assert_eq!(parse_store_major_from_modules_yaml(content), Some(10));+ }++ #[test]+ fn store_major_supports_unix_and_quoted_paths() {+ assert_eq!(+ parse_store_major_from_modules_yaml(+ "storeDir: /home/test/.local/share/pnpm/store/v11\n"+ ),+ Some(11)+ );+ assert_eq!(+ parse_store_major_from_modules_yaml("storeDir: \"C:\\\\pnpm store\\\\v3\"\n"),+ Some(3)+ );+ }++ #[test]+ fn store_major_missing_when_no_store_dir() {+ // 档案尚未装过依赖:无 storeDir 段 → None+ assert_eq!(+ parse_store_major_from_modules_yaml("lockfileVersion: '9.0'\n"),+ None+ );+ assert_eq!(parse_store_major_from_modules_yaml(""), None);+ assert_eq!(+ parse_store_major_from_modules_yaml("storeDir: C:\\Users\\x\\pnpm\\store\n"),+ None+ );+ }+}diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rsnew file mode 100644index 00000000..22ba1640--- /dev/null+++ b/src-tauri/src/service/plugin/install/single.rs@@ -0,0 +1,303 @@+//! 单插件升级/卸载:`dsh plugin --profile <当前档案> update/remove <id>`。+//! 与安装共用环境准备(shim、pnpm 选版、停止服务)与 allowBuilds 重试;+//! 卸载后核验 profile 清单,插件仍被引用时走离线卸载兜底(受保护包除外)。+//! 另含启动期弃用插件自动卸载(`uninstall_deprecated_plugins`)。++use std::ffi::OsString;+use tauri::{AppHandle, Emitter, Manager};++use crate::config;+use crate::service::cli;+use crate::service::core;+use crate::service::profile::active_profile;+use crate::service::workflow;++use super::artifact::{ensure_plugin_entry_built, installed_package_name};+use super::build_plugin_envs;+use super::diagnose::{git_transport_hint, network_error_hint, pick_error_message};+use super::errors;+use super::installed_name;+use super::is_actionable_plugin_ref;+use super::is_installed;+use super::load_presets;+use super::new_process_owner;+use super::pnpm::ensure_pnpm;+use super::profile_dir;+use super::run_plugin_with_allow_build_retry;+use super::uninstall_recovery;+use super::PreinstallPluginInfo;+use super::{PreinstallLogPayload, PREINSTALL_LOG_EVENT};++pub async fn update(app_handle: &AppHandle, id: &str) -> Result<(), String> {+ run_single_plugin_command(+ app_handle,+ id,+ "update",+ &["update".to_string(), id.to_string()],+ )+ .await+}++/// 卸载单个插件:`dsh plugin --profile <当前档案> remove <id>`+pub async fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {+ let command_result = run_single_plugin_command(+ app_handle,+ id,+ "remove",+ &["remove".to_string(), id.to_string()],+ )+ .await;+ // `dsh plugin remove` 以子进程退出码为准,可能出现「命令成功但插件仍在」的+ // 边界(如 bundle 层残留、pnpm 静默失败);node_modules / lockfile 损坏时+ // (典型:安装只写入了 profile 清单而产物缺失,见 issue #90)pnpm 甚至会+ // 直接失败。两种情形统一核验 profile 清单:只要插件仍被引用就回落离线卸载+ // (直接改清单 + 删目录 + 清 lockfile),确保插件真正移除+ // (参考 dsh-market 的「卸载后核验」约定:确认插件离开 profile 才算成功)。+ if is_installed(app_handle, id) {+ // 第三方可卸载插件才允许离线兜底;核心/官方等受保护包即使残留也不强删+ // (`uninstall_recovery` 对它们会拒绝)。+ if is_actionable_plugin_ref(id) {+ let outcome = match &command_result {+ Ok(()) => "reported success".to_string(),+ Err(e) => format!("failed: {e}"),+ };+ log::warn!(+ "dsh plugin remove {outcome} but {id} is still referenced by profile manifest; forcing offline uninstall"+ );+ uninstall_recovery(app_handle, id)?;+ } else {+ // 受保护包:命令失败则如实上报(不要把失败误报为成功),成功则仅告警。+ command_result?;+ log::warn!(+ "dsh plugin remove reported success but protected package {id} is still referenced by profile manifest; skipping offline uninstall"+ );+ }+ }+ Ok(())+}++/// 计算需要自动卸载的弃用插件已安装包名(纯函数,便于单测)。+///+/// 命中条件:清单中带 `deprecated` 标记、非内部插件(内部插件由启动自愈强制+/// 安装,不适用弃用语义),且当前已安装(以实际 npm 包名 `installed_name` 为准)。+/// 返回实际安装包名——离线卸载(`uninstall_recovery`)以它为键从 profile 清单与+/// `node_modules` 精准移除(scoped 包名与预设 id 不一致时也能正确卸载)。+fn deprecated_installed_names(+ presets: &[PreinstallPluginInfo],+ installed: impl Fn(&str) -> bool,+) -> Vec<String> {+ presets+ .iter()+ .filter(|p| p.deprecated && !p.internal)+ .filter(|p| installed(installed_name(p)))+ .map(|p| installed_name(p).to_string())+ .collect()+}++/// 启动时自动卸载清单中带 `deprecated` 标记的插件。+///+/// 弃用是发布侧决策:某个社区插件下架/被替换后,在 `preset-plugins.json` 里给它+/// 打上 `deprecated` 标记,桌面端每次启动核对「已安装 → 自动卸载」,无需用户手动+/// 处理,也避免残留插件继续在 profile 里加载破坏启动。仅处理社区预设;未被引用+/// 的条目跳过。已卸载/未安装的插件跳过,绝不误伤其它插件。+///+/// 启动阶段走离线精准卸载(`uninstall_recovery`):不依赖 node/pnpm/窗口,即使+/// 插件产物已损坏也能移除,也不会触发服务停止或 pnpm 下载。最佳努力:任何失败+/// 只记告警,不阻断启动(调用方仅打日志)。+pub(crate) async fn uninstall_deprecated_plugins(app_handle: &AppHandle) -> Result<(), String> {+ let presets = load_presets(app_handle);+ let names = deprecated_installed_names(&presets, |name| is_installed(app_handle, name));+ if names.is_empty() {+ return Ok(());+ }+ log::info!("uninstalling deprecated preset plugins: {names:?}");+ let mut failures = Vec::new();+ for name in &names {+ log::info!("DEPRECATED_PLUGIN_UNINSTALL: removing deprecated plugin {name}");+ if let Err(e) = uninstall_recovery(app_handle, name) {+ log::warn!("DEPRECATED_PLUGIN_UNINSTALL_FAILED: {name}: {e}");+ failures.push(format!("{name}: {e}"));+ }+ }+ if failures.is_empty() {+ Ok(())+ } else {+ Err(failures.join("; "))+ }+}++/// 执行单个插件的升级/卸载:准备环境 → 停止服务 → 运行 `dsh plugin` →+/// 失败记录错误、成功清除错误。+async fn run_single_plugin_command(+ app_handle: &AppHandle,+ id: &str,+ action: &str,+ sub_args: &[String],+) -> Result<(), String> {+ if id.is_empty() {+ return Err("PLUGIN_EMPTY_ID: plugin id is empty".to_string());+ }+ let window = app_handle+ .get_webview_window("main")+ .ok_or("WINDOW_NOT_FOUND: main window missing")?;++ cli::ensure_shims(app_handle)?;++ let node = config::get_node_binary_path(app_handle);+ let dsh_bin = core::active_dsh_binary(app_handle);+ if !node.exists() {+ return Err("NODE_NOT_FOUND: Node.js runtime missing".to_string());+ }+ if !dsh_bin.exists() {+ return Err("HARNESS_NOT_FOUND: dsh CLI missing".to_string());+ }++ let owner = new_process_owner();+ let prefer_bundled_pnpm = ensure_pnpm(app_handle, &window, owner).await?;+ // `.npmrc` 可能在服务启动后被删除;升级/卸载同样可能触发 pnpm 非交互清理。+ super::ensure_profile_npmrc(app_handle)?;++ // 插件操作会改写 profile,先停止运行中的服务(与安装一致)+ if workflow::has_owned_process() {+ let _ = window.emit(+ PREINSTALL_LOG_EVENT,+ PreinstallLogPayload {+ line: format!("[harness] 正在停止运行中的服务({action}插件需要短暂重启)…"),+ },+ );+ if let Err(e) = workflow::stop(app_handle.clone()).await {+ log::warn!("failed to stop harness before plugin {action}: {e}");+ }+ }++ let envs = build_plugin_envs(app_handle, prefer_bundled_pnpm);++ let mut args = vec![+ dsh_bin.as_os_str().to_os_string(),+ OsString::from("plugin"),+ OsString::from("--profile"),+ OsString::from(active_profile(app_handle)),+ OsString::from(action),+ ];+ args.extend(sub_args.iter().map(OsString::from));++ let cwd = config::get_dsh_install_path(app_handle);+ log::info!("Running dsh plugin {action} for {id}");+ let (exit_code, output) = run_plugin_with_allow_build_retry(+ app_handle, &node, &args, &cwd, &envs, &window, action, None, owner,+ )+ .await?;++ if exit_code != 0 {+ log::error!("dsh plugin {action} failed for {id} with exit code {exit_code}");+ let network_error =+ network_error_hint(&output).is_some() || (exit_code == 3 && output.trim().is_empty());+ let message = if network_error {+ "NETWORK_ERROR: plugin registry request failed; check network or proxy settings and retry."+ .to_string()+ } else {+ pick_error_message(&output, git_transport_hint(&output))+ };+ if let Err(e) = errors::record(app_handle, id, action, &message) {+ log::warn!("failed to record plugin error for {id}: {e}");+ }+ if network_error {+ return Err("NETWORK_ERROR: plugin registry request failed; check network or proxy settings and retry.".to_string());+ }+ return Err(format!(+ "PLUGIN_{}_FAILED: dsh plugin exited with code {exit_code}",+ action.to_uppercase()+ ));+ }++ // 成功:清除历史错误;卸载 win-terminal-inspector 时顺带清理 patch 挂载+ if let Err(e) = errors::clear(app_handle, id) {+ log::warn!("failed to clear plugin error for {id}: {e}");+ }+ // 升级路径与安装一致地核验构建产物:git 托管插件升级后同样可能停在+ // 「prepare 未构建 → 声明入口缺失」坏态,若不拦截,下一次启动即崩溃+ // (见 [`ensure_plugin_entry_built`])。包名先解析(预设 package 覆盖 /+ // 清单依赖 basename),解析不到时跳过核验(警告即可,不误杀成功更新)。+ if action == "update" {+ let Some(name) = installed_package_name(app_handle, id) else {+ log::warn!("plugin {id} not resolvable to a package name, skipping entry verify");+ return Ok(());+ };+ let pkg_dir = profile_dir(app_handle).join("node_modules").join(name);+ if let Err(e) = ensure_plugin_entry_built(app_handle, id, &pkg_dir, &envs, &window).await {+ if let Err(err) = errors::record(app_handle, id, action, &e) {+ log::warn!("failed to record plugin error for {id}: {err}");+ }+ return Err(e);+ }+ }+ if action == "remove" && id == "dsh-win-terminal-inspector" {+ if let Err(e) = workflow::win_inspector::apply(app_handle) {+ log::warn!("win inspector patch prune failed after remove: {e}");+ }+ }+ log::info!("dsh plugin {action} succeeded for {id}");+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn preset(id: &str, spec: &str, internal: bool) -> PreinstallPluginInfo {+ PreinstallPluginInfo {+ id: id.into(),+ spec: spec.into(),+ package: None,+ name: String::new(),+ description: String::new(),+ repo_url: String::new(),+ recommended: false,+ fix: false,+ default_checked: false,+ win_only: false,+ internal,+ deprecated: false,+ }+ }++ #[test]+ fn deprecated_installed_only_picks_marked_and_installed() {+ // 只把 `dsh-ok` 视为已安装,其余一律未安装(便于区分「标记但未安装」)。+ let installed = |name: &str| matches!(name, "dsh-ok" | "@scope/deprecated");++ // 命中:deprecated 且已安装 → 返回实际安装包名(dsh-ok 未声明 package,回落 id)+ let mut deprecated = preset("dsh-ok", "dshmarket", false);+ deprecated.deprecated = true;+ assert_eq!(+ deprecated_installed_names(&[deprecated], installed),+ vec!["dsh-ok".to_string()]+ );++ // scoped 包:返回真实安装包名(与预设 id 不一致)+ let mut scoped = preset("dsh-scoped", "github:x/y", false);+ scoped.deprecated = true;+ scoped.package = Some("@scope/deprecated".into());+ assert_eq!(+ deprecated_installed_names(&[scoped], installed),+ vec!["@scope/deprecated".to_string()]+ );++ // 未标记 deprecated:即使已安装也不命中+ let plain = preset("dsh-plain", "dsh-plain", false);+ assert!(deprecated_installed_names(&[plain], installed).is_empty());++ // 标记了但未安装:不命中+ let mut absent = preset("dsh-not-installed", "dshmarket", false);+ absent.deprecated = true;+ assert!(deprecated_installed_names(&[absent], installed).is_empty());++ // 内部插件即使标记 deprecated 也不命中(内部插件由启动自愈强制安装)+ let mut internal = preset("dsh-internal", "[email protected]", true);+ internal.deprecated = true;+ assert!(+ deprecated_installed_names(&[internal], |name| matches!(name, "dsh-internal"))+ .is_empty()+ );+ }+}diff --git a/src-tauri/src/service/plugin/install/spec.rs b/src-tauri/src/service/plugin/install/spec.rsnew file mode 100644index 00000000..f53709b7--- /dev/null+++ b/src-tauri/src/service/plugin/install/spec.rs@@ -0,0 +1,254 @@+//! 安装 spec 准备:内置插件捆绑目录解析(`link:` 本地依赖——pnpm 对 `file:` 的+//! 盘符绝对路径会按相对解析)、GitHub 简写规范化(绕开 pnpm 的 HTTPS→SSH 回退+//! 缺陷)与 Windows 下含空格 spec 的引号化(dsh CLI 只在 win32 用 shell 拼接参数)。++use std::path::PathBuf;+use tauri::AppHandle;++use super::bundled_dep_spec;+use super::bundled_plugin_dir;+use super::PreinstallPluginInfo;++/// 内置插件才需要解析捆绑目录(普通插件无此概念),避免无谓的资源探测+pub(super) fn bundled_dir_of(+ app_handle: &AppHandle,+ preset: &PreinstallPluginInfo,+) -> Option<PathBuf> {+ if !preset.internal {+ return None;+ }+ bundled_plugin_dir(app_handle, &preset.id)+}++/// 解析某预设的安装 spec(纯函数,便于单测):内置插件固定为随包捆绑目录的+/// `file:` 本地依赖(路径正确性由 [`crate::service::plugin::internal::ensure`] 启动自愈核对);+/// 普通插件沿用清单声明。+///+/// 捆绑目录缺失时返回错误:内置插件缺失意味着构建期 prebuild 未执行或产物被+/// 删,属发布缺陷而非用户侧的普通安装失败,错误前缀便于区分。+pub(super) fn preset_spec_for_install(+ preset: &PreinstallPluginInfo,+ bundled_dir: Option<PathBuf>,+) -> Result<String, String> {+ if !preset.internal {+ return Ok(preset.spec.clone());+ }+ let dir = bundled_dir.ok_or_else(|| {+ format!(+ "BUNDLED_PLUGIN_MISSING: no bundled dir for internal plugin {} (run scripts/prebuild.ts at build time)",+ preset.id+ )+ })?;+ Ok(bundled_dep_spec(&dir))+}++/// 把 `github:owner/repo[#ref]` 一类的 GitHub 简写规范为显式 HTTPS 依赖形式+/// (`git+https://github.com/owner/repo.git[#ref]`)。+///+/// 动机:pnpm 解析 GitHub 简写时,「HTTPS 可达性探测一旦失败就回退 git+ssh」+/// 是已知缺陷(issue #3948 / #7243 / #13276,官方已 accepted 仍未修)。公开仓库+/// 一旦落进 git+ssh,在无 SSH 配置的桌面机上(非交互子进程无法应答 known_hosts+/// 询问)必然硬失败。规范为显式 `git+https:` 后 pnpm 直接走 HTTPS 克隆,绕开该+/// 回退;非 `github:` 形式(如纯 npm 包名)原样返回。+pub(super) fn normalize_git_spec(spec: &str) -> String {+ let Some(rest) = spec.strip_prefix("github:") else {+ return spec.to_string();+ };+ let (path, fragment) = match rest.split_once('#') {+ Some((p, f)) => (p.trim_end_matches('/'), Some(f)),+ None => (rest.trim_end_matches('/'), None),+ };+ let mut repo = path.to_string();+ if !repo.ends_with(".git") {+ repo.push_str(".git");+ }+ let mut url = format!("git+https://github.com/{repo}");+ if let Some(fragment) = fragment {+ url.push('#');+ url.push_str(fragment);+ }+ url+}++/// 给含空白字符的依赖 spec 加内嵌双引号,使其在 shell 拼接后仍保持单一 token。+///+/// **仅 Windows 需要引号。** `dsh plugin add` 在 JS 里用+/// `spawnSync("pnpm", args, { shell: process.platform === "win32" })` 启动 pnpm:+/// - Windows:`shell:true` 时 Node 只把参数按空格拼接、不做引号转义(官方文档+/// DEP0190:arguments are not escaped, only concatenated)。内置插件的依赖是+/// `link:<应用安装目录>`,而 Windows 安装目录常含空格(如+/// `G:\Deepseek Harness Desktop\resources\internal-plugins\dsh-tauri`),拼进+/// shell 后会被切碎成多个 spec,pnpm 报 `ERR_PNPM_SPEC_NOT_SUPPORTED` / 装成+/// 错误依赖,导致启动自愈每轮都重装(死循环)。包一层双引号让 cmd 把整条+/// spec 视为一个参数;pnpm 解析后自行剥离引号,落盘 `package.json` 的值仍是+/// 不带引号的规范 `link:<路径>`(与 [`bundled_dep_spec`] 的内核对账一致)。+/// - macOS / Linux:`shell:false`,pnpm 以 argv 数组直接启动、空格天然保留,+/// **加引号反而把字面 `"` 当成包名的一部分传给 pnpm → 非法 spec → exit 1**。+/// 这是 issue #104 的根因:内置插件指向 `/Applications/Deepseek Harness+/// Desktop.app/...`(含空格),每次启动自愈重装都失败、服务永远缺该插件。+///+/// 因此只在 `cfg!(windows)` 且 spec 含空白时才包引号——普通 npm 包名 /+/// `git+https://...` 无空格,原样透传,避免无谓改动。+pub(super) fn shell_quote_spec(spec: &str) -> String {+ #[cfg(windows)]+ {+ if spec.chars().any(|c| c == ' ' || c == '\t') {+ return format!("\"{spec}\"");+ }+ }+ spec.to_string()+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::PathBuf;++ /// 构造预设条目的测试助手(internal 由各用例显式指定)+ fn preset(id: &str, spec: &str, internal: bool) -> PreinstallPluginInfo {+ PreinstallPluginInfo {+ id: id.into(),+ spec: spec.into(),+ package: None,+ name: String::new(),+ description: String::new(),+ repo_url: String::new(),+ recommended: false,+ fix: false,+ default_checked: false,+ win_only: false,+ internal,+ deprecated: false,+ }+ }++ #[test]+ fn install_spec_passthrough_for_regular_preset() {+ // 普通插件:spec 原样返回,与捆绑目录无关+ let p = preset("dshmarket", "dshmarket", false);+ assert_eq!(preset_spec_for_install(&p, None).unwrap(), "dshmarket");+ assert_eq!(+ preset_spec_for_install(&p, Some(PathBuf::from("/ignored"))).unwrap(),+ "dshmarket"+ );+ }++ #[test]+ fn install_spec_uses_bundled_dir_for_internal_preset() {+ // 内置插件:安装依赖为 link:<捆绑目录>(正斜杠规范形;pnpm 对+ // `file:D:/...` 的盘符绝对路径会按相对解析,必须用 `link:`)+ let p = preset("dsh-tauri", "[email protected]", true);+ let dir = PathBuf::from("C:\\Apps\\dsh\\resources\\internal-plugins\\dsh-tauri");+ assert_eq!(+ preset_spec_for_install(&p, Some(dir)).unwrap(),+ "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri"+ );+ }++ #[test]+ fn install_spec_errors_when_internal_bundle_missing() {+ // 内置插件捆绑目录缺失:发布缺陷,显式报错而非静默走 npm/git spec+ let p = preset("dsh-tauri", "[email protected]", true);+ let err = preset_spec_for_install(&p, None).unwrap_err();+ assert!(err.starts_with("BUNDLED_PLUGIN_MISSING"));+ assert!(err.contains("dsh-tauri"));+ }++ // ---- git GitHub 简写规范化(issue #51 根因绕行)----++ #[test]+ fn normalize_github_shorthand_to_git_https() {+ assert_eq!(+ normalize_git_spec("github:baihejiangnan/dsh-session-context-menu"),+ "git+https://github.com/baihejiangnan/dsh-session-context-menu.git"+ );+ }++ #[test]+ fn normalize_github_shorthand_preserves_ref_and_dedup_git_suffix() {+ assert_eq!(+ normalize_git_spec("github:omdsh-dev/DSH-better-sidebar#next"),+ "git+https://github.com/omdsh-dev/DSH-better-sidebar.git#next"+ );+ // 已带 .git 不重复追加+ assert_eq!(+ normalize_git_spec("github:user/repo.git"),+ "git+https://github.com/user/repo.git"+ );+ // 尾部多余斜杠剥掉+ assert_eq!(+ normalize_git_spec("github:user/repo/"),+ "git+https://github.com/user/repo.git"+ );+ }++ #[test]+ fn normalize_non_github_spec_passes_through() {+ assert_eq!(normalize_git_spec("dshmarket"), "dshmarket");+ assert_eq!(+ normalize_git_spec("git+https://github.com/foo/bar.git"),+ "git+https://github.com/foo/bar.git"+ );+ }++ // ---- spec 引号化(仅 Windows:dsh CLI 只在 win32 用 shell 拼接参数)----++ #[cfg(windows)]+ #[test]+ fn shell_quote_quotes_spec_containing_spaces() {+ // 安装目录含空格(如 G:\Deepseek Harness Desktop):整条 spec 加双引号,+ // 使 dsh CLI 的 shell:true 拼接后仍被 shell 视为单一 token(DEP0190:+ // Node 对 shell:true 只拼接不转义)+ assert_eq!(+ shell_quote_spec(+ "link:G:/Deepseek Harness Desktop/resources/internal-plugins/dsh-tauri"+ ),+ "\"link:G:/Deepseek Harness Desktop/resources/internal-plugins/dsh-tauri\""+ );+ // 制表符同样触发+ assert_eq!(shell_quote_spec("link:C:/x\ty"), "\"link:C:/x\ty\"");+ }++ #[cfg(not(windows))]+ #[test]+ fn shell_quote_leaves_space_path_untouched_on_non_windows() {+ // 回归(issue #104):macOS/Linux 上 dsh CLI 直接 spawnSync(shell:false),+ // spec 作为一个 argv 传递、空格天然保留,绝不能加引号——字面 `"` 会成为+ // 包名的一部分,pnpm 报非法 spec → exit 1 → 内置插件每次启动重装都失败。+ assert_eq!(+ shell_quote_spec("link:/Applications/Deepseek Harness Desktop.app/Contents/Resources/resources/internal-plugins/dsh-tauri-ui"),+ "link:/Applications/Deepseek Harness Desktop.app/Contents/Resources/resources/internal-plugins/dsh-tauri-ui"+ );+ assert_eq!(+ shell_quote_spec("link:/Users/me/my plugins/dsh-tauri"),+ "link:/Users/me/my plugins/dsh-tauri"+ );+ }++ #[test]+ fn shell_quote_leaves_space_free_spec_untouched() {+ // 普通 npm 包名 / git HTTPS spec 无空格:原样透传,不引入多余引号+ assert_eq!(shell_quote_spec("dshmarket"), "dshmarket");+ assert_eq!(+ shell_quote_spec("git+https://github.com/omdsh-dev/DSH-better-sidebar.git#next"),+ "git+https://github.com/omdsh-dev/DSH-better-sidebar.git#next"+ );+ // 无空格的内置插件路径同样不被改动(保持与 internal.rs expected 一致)+ assert_eq!(+ shell_quote_spec("link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri"),+ "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri"+ );+ }++ #[cfg(windows)]+ #[test]+ fn shell_quote_preserves_link_prefix_semantics() {+ // 引号只包 path 部分也不影响 pnpm 解析(落盘值仍为不带引号的 link: 规范形)+ let quoted = shell_quote_spec(+ "link:G:/Deepseek Harness Desktop/resources/internal-plugins/dsh-tauri",+ );+ assert!(quoted.starts_with('"'));+ assert!(quoted.ends_with('"'));+ assert!(quoted.contains("Deepseek Harness Desktop"));+ }+}diff --git a/src-tauri/src/service/plugin/internal/manifest.rs b/src-tauri/src/service/plugin/internal/manifest.rsnew file mode 100644index 00000000..4d896a2f--- /dev/null+++ b/src-tauri/src/service/plugin/internal/manifest.rs@@ -0,0 +1,352 @@+//! profile 清单与 `node_modules` 入口文件操作:内置插件就绪判定、待重装包声明+//! 的精准移除(保留其它插件)、原子写回清单与失效入口清理。++use std::collections::HashSet;+#[cfg(windows)]+use std::os::windows::fs::FileTypeExt;+use std::path::Path;++/// 读取并解析入口清单,避免仅凭文件存在就把截断或不可读的内置插件视为健康。+pub(super) fn internal_plugin_entry_is_ready(entry: &Path) -> bool {+ let Ok(raw) = std::fs::read(entry.join("package.json")) else {+ return false;+ };+ serde_json::from_slice::<serde_json::Value>(&raw).is_ok_and(|manifest| manifest.is_object())+}++/// 从 profile 清单精准移除待重装 internal 包的依赖与 bundle 引用。+pub(super) fn remove_internal_plugins_from_manifest(+ manifest: &mut serde_json::Value,+ names: &HashSet<&str>,+) -> bool {+ let mut modified = false;+ if let Some(dependencies) = manifest+ .get_mut("dependencies")+ .and_then(serde_json::Value::as_object_mut)+ {+ for name in names {+ modified |= dependencies.remove(*name).is_some();+ }+ }+ if let Some(bundles) = manifest+ .get_mut("dsh")+ .and_then(|dsh| dsh.get_mut("profile"))+ .and_then(|profile| profile.get_mut("bundles"))+ .and_then(serde_json::Value::as_array_mut)+ {+ let before = bundles.len();+ bundles.retain(|bundle| bundle.as_str().is_none_or(|name| !names.contains(name)));+ modified |= bundles.len() != before;+ }+ modified+}++/// 经同目录临时文件原子替换 profile 清单,失败时保留原文件。+pub(super) fn write_profile_manifest(+ path: &Path,+ manifest: &serde_json::Value,+) -> Result<(), String> {+ use std::io::Write;++ let rendered = serde_json::to_string_pretty(manifest)+ .map_err(|e| format!("INTERNAL_PLUGIN_MANIFEST_RENDER_FAILED: {e}"))?;+ let temp = path.with_extension(format!("json.internal.{}.tmp", std::process::id()));+ let result = (|| -> std::io::Result<()> {+ let mut file = std::fs::File::create(&temp)?;+ file.write_all(format!("{rendered}\n").as_bytes())?;+ file.sync_all()?;+ drop(file);+ replace_manifest_file(&temp, path)+ })();+ if let Err(e) = result {+ let _ = std::fs::remove_file(&temp);+ return Err(format!("INTERNAL_PLUGIN_MANIFEST_WRITE_FAILED: {e}"));+ }+ log::info!(+ "Removed stale internal plugin declarations from profile manifest: {}",+ path.display()+ );+ Ok(())+}++#[cfg(not(windows))]+fn replace_manifest_file(temp: &Path, path: &Path) -> std::io::Result<()> {+ std::fs::rename(temp, path)+}++#[cfg(windows)]+fn replace_manifest_file(temp: &Path, path: &Path) -> std::io::Result<()> {+ use std::os::windows::ffi::OsStrExt;+ use windows_sys::Win32::Storage::FileSystem::{+ MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,+ };++ let temp_wide: Vec<u16> = temp.as_os_str().encode_wide().chain(Some(0)).collect();+ let path_wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();+ let moved = unsafe {+ MoveFileExW(+ temp_wide.as_ptr(),+ path_wide.as_ptr(),+ MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,+ )+ };+ if moved == 0 {+ return Err(std::io::Error::last_os_error());+ }+ Ok(())+}++/// 删除失效的插件入口,但绝不跟随符号链接 / junction 删除捆绑资源。+///+/// 正常目录只可能是 pnpm 留下的损坏产物,可以递归清理;Unix 符号链接与 Windows+/// junction 则只删除入口本身。入口不存在(包括已被并发清掉)视为幂等成功。+pub(super) fn remove_stale_plugin_entry(entry: &Path) -> std::io::Result<()> {+ let metadata = match std::fs::symlink_metadata(entry) {+ Ok(metadata) => metadata,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(e) => return Err(e),+ };+ let file_type = metadata.file_type();+ #[cfg(windows)]+ if file_type.is_symlink_dir() {+ return std::fs::remove_dir(entry);+ }+ if file_type.is_symlink() {+ return std::fs::remove_file(entry);+ }+ if file_type.is_dir() {+ return std::fs::remove_dir_all(entry);+ }+ std::fs::remove_file(entry)+}++/// 判断 pnpm 写入 profile 的依赖值与期望的 `link:` 捆绑路径是否一致。+///+/// 容忍:`link:`/`file:` 前缀缺失或两者混写(历史遗留 `file:` 安装值);Windows+/// 下路径大小写不敏感;尾部斜杠差异(pnpm 各版本落盘形式略有出入)。+pub(super) fn dep_matches_spec(actual: &str, expected: &str) -> bool {+ let norm = |spec: &str| {+ let stripped = spec+ .strip_prefix("link:")+ .or_else(|| spec.strip_prefix("file:"))+ .unwrap_or(spec);+ // 统一用 dunce 归一化 Windows 扩展长度路径前缀(`\\?\`):+ // 期望值已经由 bundled_dep_spec 归一化掉前缀;若历史命中的实值仍带+ // `//?/` / `\\?\` 前缀,先归一再比对,保证幂等(避免旧值一次次触发+ // 不必要的重装)。先把手写正斜杠的 verbatim 形式(`//?/`)换算成反斜杠+ // (dunce 依赖 `\\?\` 识别 verbatim),再交给 dunce::simplified,最后+ // 统一回正斜杠,与 bundled_dep_spec 的产出可比。+ let backslash = stripped.replace('/', "\\");+ dunce::simplified(Path::new(&backslash))+ .to_string_lossy()+ .replace('\\', "/")+ .trim_end_matches('/')+ .to_string()+ };+ let actual = norm(actual);+ let expected = norm(expected);+ if cfg!(windows) {+ actual.eq_ignore_ascii_case(&expected)+ } else {+ actual == expected+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn internal_plugin_entry_requires_readable_manifest_object() {+ let root = std::env::temp_dir().join(format!(+ "dsh-internal-entry-readiness-{}",+ std::process::id()+ ));+ let manifest = root.join("package.json");+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(&root).unwrap();++ assert!(!internal_plugin_entry_is_ready(&root));++ std::fs::write(&manifest, br#"{"name":"dsh-tauri"}"#).unwrap();+ assert!(internal_plugin_entry_is_ready(&root));++ std::fs::write(&manifest, br#"{"name":"dsh-tauri""#).unwrap();+ assert!(!internal_plugin_entry_is_ready(&root));++ std::fs::write(&manifest, b"[]").unwrap();+ assert!(!internal_plugin_entry_is_ready(&root));++ std::fs::write(&manifest, [0xff, 0xfe, 0xfd]).unwrap();+ assert!(!internal_plugin_entry_is_ready(&root));++ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn stale_internal_manifest_entries_are_removed_without_touching_other_plugins() {+ let mut manifest = serde_json::json!({+ "private": true,+ "dependencies": {+ "dsh-tauri": "file:/Applications/Deepseek Harness Desktop.app/Contents/Resources/resources/preset-plugins/dsh-tauri",+ "dsh-tauri-ui": "link:/Applications/Deepseek Harness Desktop.app/Contents/Resources/resources/preset-plugins/dsh-tauri-ui",+ "dshmarket": "github:dsh-market/dshmarket"+ },+ "dsh": {+ "profile": {+ "bundles": ["dsh-tauri", "dsh-tauri-ui", "dshmarket"]+ }+ }+ });+ let names = HashSet::from(["dsh-tauri", "dsh-tauri-ui"]);++ assert!(remove_internal_plugins_from_manifest(&mut manifest, &names));+ assert_eq!(+ manifest["dependencies"],+ serde_json::json!({ "dshmarket": "github:dsh-market/dshmarket" })+ );+ assert_eq!(+ manifest["dsh"]["profile"]["bundles"],+ serde_json::json!(["dshmarket"])+ );+ assert!(!remove_internal_plugins_from_manifest(+ &mut manifest,+ &names+ ));+ }++ #[test]+ fn manifest_replacement_preserves_original_when_temp_write_fails() {+ let root = std::env::temp_dir().join(format!(+ "dsh-internal-manifest-write-failure-{}",+ std::process::id()+ ));+ let path = root.join("package.json");+ std::fs::create_dir_all(&path).unwrap();+ std::fs::write(path.join("sentinel"), "original").unwrap();++ let error = write_profile_manifest(&path, &serde_json::json!({ "private": true }))+ .expect_err("directory destination must reject replacement");++ assert!(error.starts_with("INTERNAL_PLUGIN_MANIFEST_WRITE_FAILED:"));+ assert_eq!(+ std::fs::read_to_string(path.join("sentinel")).unwrap(),+ "original"+ );+ assert!(!root+ .join(format!("package.json.internal.{}.tmp", std::process::id()))+ .exists());+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn stale_plain_directory_is_removed() {+ let root = std::env::temp_dir().join(format!(+ "dsh-internal-stale-directory-{}",+ std::process::id()+ ));+ let entry = root.join("node_modules/dsh-tauri-ui");+ std::fs::create_dir_all(&entry).unwrap();+ std::fs::write(entry.join("partial"), "broken").unwrap();++ remove_stale_plugin_entry(&entry).unwrap();++ assert!(!entry.exists());+ let _ = std::fs::remove_dir_all(root);+ }++ #[cfg(unix)]+ #[test]+ fn stale_symlink_is_removed_without_touching_target() {+ let root =+ std::env::temp_dir().join(format!("dsh-internal-stale-symlink-{}", std::process::id()));+ let target = root.join("old-app/dsh-tauri-ui");+ let entry = root.join("profile/node_modules/dsh-tauri-ui");+ std::fs::create_dir_all(&target).unwrap();+ std::fs::write(target.join("package.json"), "{}").unwrap();+ std::fs::create_dir_all(entry.parent().unwrap()).unwrap();+ std::os::unix::fs::symlink(&target, &entry).unwrap();++ remove_stale_plugin_entry(&entry).unwrap();++ assert!(target.join("package.json").is_file());+ assert!(std::fs::symlink_metadata(&entry).is_err());+ let _ = std::fs::remove_dir_all(root);+ }++ #[cfg(unix)]+ #[test]+ fn dangling_symlink_is_removed_idempotently() {+ let root = std::env::temp_dir().join(format!(+ "dsh-internal-dangling-symlink-{}",+ std::process::id()+ ));+ let entry = root.join("profile/node_modules/dsh-tauri-ui");+ std::fs::create_dir_all(entry.parent().unwrap()).unwrap();+ std::os::unix::fs::symlink(root.join("missing-app/dsh-tauri-ui"), &entry).unwrap();++ remove_stale_plugin_entry(&entry).unwrap();+ remove_stale_plugin_entry(&entry).unwrap();++ assert!(std::fs::symlink_metadata(&entry).is_err());+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn dep_spec_matches_itself() {+ let expected = "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri";+ // 与自身一致+ assert!(dep_matches_spec(expected, expected));+ // 无 link:/file: 前缀(pnpm 某些场景直接落路径)+ assert!(dep_matches_spec(+ "C:/Apps/dsh/resources/internal-plugins/dsh-tauri",+ expected+ ));+ // 尾部斜杠差异+ assert!(dep_matches_spec(+ "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri/",+ expected+ ));+ // 反斜杠(Windows 原生形式)+ assert!(dep_matches_spec(+ "link:C:\\Apps\\dsh\\resources\\internal-plugins\\dsh-tauri",+ expected+ ));+ // 历史遗留 file: 形式(协议切换前已安装的值)+ assert!(dep_matches_spec(+ "file:C:/Apps/dsh/resources/internal-plugins/dsh-tauri",+ expected+ ));+ }++ #[test]+ fn dep_spec_rejects_wrong_path_or_source() {+ let expected = "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri";+ // 仍指向 npm 版本(用户手动从 npm 安装,非捆绑 link: 源)+ assert!(!dep_matches_spec("[email protected]", expected));+ // 指向其它位置(旧版本安装目录等)+ assert!(!dep_matches_spec("link:D:/elsewhere/dsh-tauri", expected));+ // 同名不同宿主盘符+ assert!(!dep_matches_spec(+ "link:D:/Apps/dsh/resources/internal-plugins/dsh-tauri",+ expected+ ));+ }++ #[cfg(windows)]+ #[test]+ fn dep_spec_case_insensitive_on_windows() {+ // Windows 文件系统大小写不敏感,路径比较须忽略大小写+ let expected = "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri";+ assert!(dep_matches_spec(+ "link:c:/apps/DSH/resources/internal-plugins/Dsh-Tauri",+ expected+ ));+ // 实值仍带 Windows 扩展长度前缀(`\\?\`,dunce::simplified 归一化)时,+ // 与归一化掉前缀的期望值仍视为同一路径(幂等,避免不必要的重装)+ assert!(dep_matches_spec(+ "link://?/C:/Apps/dsh/resources/internal-plugins/dsh-tauri",+ expected+ ));+ }+}diff --git a/src-tauri/src/service/plugin/internal.rs b/src-tauri/src/service/plugin/internal/mod.rssimilarity index 65%rename from src-tauri/src/service/plugin/internal.rsrename to src-tauri/src/service/plugin/internal/mod.rsindex a365afb6..1bc57b02 100644--- a/src-tauri/src/service/plugin/internal.rs+++ b/src-tauri/src/service/plugin/internal/mod.rs@@ -9,16 +9,26 @@//!//! 为什么放在启动而非安装流程:安装是用户主动行为,内置插件是应用自身的完整性//! 要求——用户怎么卸载、何时卸载都不影响下次启动自动恢复,无需任何用户操作。+//!+//! 模块划分:协调/飞行(本文件)与 profile 清单/入口文件操作([`manifest`])。use std::collections::{HashMap, HashSet};use std::future::Future;-#[cfg(windows)]-use std::os::windows::fs::FileTypeExt;-use std::path::Path;+use std::path::PathBuf;use tauri::{AppHandle, Emitter};+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::process::{new_process_owner, ProcessOwner};++use manifest::{+ dep_matches_spec, internal_plugin_entry_is_ready, remove_internal_plugins_from_manifest,+ remove_stale_plugin_entry, write_profile_manifest,+};++mod manifest;/// 核对并强制安装缺失/路径不正确/被卸载的内置插件,在服务进程启动前调用。///@@ -58,7 +68,7 @@ const ENSURE_OWNER_DRAIN_INTERVAL: std::time::Duration = std::time::Duration::fr#[derive(Clone)]struct EnsureFlight {id: u64,- owner: super::process::ProcessOwner,+ owner: ProcessOwner,state: EnsureFlightState,result: tokio::sync::watch::Receiver<Option<Result<(), String>>>,cancel: tokio::sync::watch::Sender<bool>,@@ -98,7 +108,7 @@ impl EnsureCoordinator {&mut self,) -> (u64,- super::process::ProcessOwner,+ ProcessOwner,tokio::sync::watch::Sender<Option<Result<(), String>>>,tokio::sync::watch::Receiver<Option<Result<(), String>>>,tokio::sync::watch::Sender<bool>,@@ -106,7 +116,7 @@ impl EnsureCoordinator {) {self.next_id = self.next_id.wrapping_add(1);let id = self.next_id;- let owner = super::process::new_process_owner();+ let owner = new_process_owner();let (result_tx, result_rx) = tokio::sync::watch::channel(None);let (cancel_tx, cancel_rx) = tokio::sync::watch::channel(false);self.active = Some(EnsureFlight {@@ -174,6 +184,7 @@ async fn subscribe_or_start(run_ensure_operation(&app_handle, &internal, owner, cancel_tx, cancel_rx).await;// 强杀返回不等于持有句柄的 wait 已完成;必须等精确 owner 的 PID// 守卫随 wait 退出,才能发布结果并允许 Retry 创建下一次 flight。+if !wait_for_owner_release(owner, ENSURE_OWNER_DRAIN_TIMEOUT).await {let reason = format!("INTERNAL_PLUGIN_PROCESS_REAP_TIMEOUT: plugin process owner {owner:?} remained active for {} seconds",@@ -290,7 +301,7 @@ pub(crate) async fn cancel() -> Result<(), String> {async fn run_ensure_operation(app_handle: &AppHandle,internal: &[PreinstallPluginInfo],- owner: super::process::ProcessOwner,+ owner: ProcessOwner,cancel_tx: tokio::sync::watch::Sender<bool>,mut cancel: tokio::sync::watch::Receiver<bool>,) -> Result<(), String> {@@ -327,7 +338,7 @@ async fn run_ensure_operation(let reason = "INTERNAL_PLUGIN_INSTALL_TIMEOUT: plugin install exceeded 600 seconds";log::error!("{reason}");let _ = cancel_tx.send(true);- super::cancel::terminate_owned_install(owner).await;+ terminate_owned_install(owner).await;if tokio::time::timeout(ENSURE_CLEANUP_TIMEOUT, &mut operation).await.is_err() {log::error!("INTERNAL_PLUGIN_CLEANUP_TIMEOUT: plugin process did not exit after forced termination");}@@ -338,7 +349,7 @@ async fn run_ensure_operation(if changed.is_err() || *cancel.borrow() {let reason = "INTERNAL_PLUGIN_INSTALL_CANCELLED: plugin install was cancelled";log::warn!("{reason}");- super::cancel::terminate_owned_install(owner).await;+ terminate_owned_install(owner).await;if tokio::time::timeout(ENSURE_CLEANUP_TIMEOUT, &mut operation).await.is_err() {log::error!("INTERNAL_PLUGIN_CLEANUP_TIMEOUT: plugin process did not exit after forced termination");}@@ -376,7 +387,7 @@ async fn ensure_inner(app_handle: &AppHandle,internal: &[&PreinstallPluginInfo],cancel: tokio::sync::watch::Receiver<bool>,- owner: super::process::ProcessOwner,+ owner: ProcessOwner,) -> Result<(), String> {log::info!("checking {} internal preset plugins for install state",@@ -404,7 +415,7 @@ async fn ensure_inner(None => HashMap::new(),};- let mut need: Vec<(String, String, std::path::PathBuf)> = Vec::new();+ let mut need: Vec<(String, String, PathBuf)> = Vec::new();for preset in internal {let Some(bundled) = bundled_plugin_dir(app_handle, &preset.id) else {// 未找到内置插件目录:release 说明构建期 prebuild 未拉取(发布缺陷,@@ -477,155 +488,12 @@ async fn ensure_inner(}// 复用常规安装编排(环境准备/补齐 pnpm/`dsh plugin add file:<dir>`);// 启动阶段无持有进程,install 内部不会停服务。失败同样交给调用方告警。- if let Err(e) = super::install::install_internal(app_handle, &ids, cancel, owner).await {+ if let Err(e) = install_internal(app_handle, &ids, cancel, owner).await {return Err(format!("INTERNAL_PLUGIN_INSTALL_FAILED: {e}"));}Ok(())}-/// 读取并解析入口清单,避免仅凭文件存在就把截断或不可读的内置插件视为健康。-fn internal_plugin_entry_is_ready(entry: &Path) -> bool {- let Ok(raw) = std::fs::read(entry.join("package.json")) else {- return false;- };- serde_json::from_slice::<serde_json::Value>(&raw).is_ok_and(|manifest| manifest.is_object())-}--/// 从 profile 清单精准移除待重装 internal 包的依赖与 bundle 引用。-fn remove_internal_plugins_from_manifest(- manifest: &mut serde_json::Value,- names: &HashSet<&str>,-) -> bool {- let mut modified = false;- if let Some(dependencies) = manifest- .get_mut("dependencies")- .and_then(serde_json::Value::as_object_mut)- {- for name in names {- modified |= dependencies.remove(*name).is_some();- }- }- if let Some(bundles) = manifest- .get_mut("dsh")- .and_then(|dsh| dsh.get_mut("profile"))- .and_then(|profile| profile.get_mut("bundles"))- .and_then(serde_json::Value::as_array_mut)- {- let before = bundles.len();- bundles.retain(|bundle| bundle.as_str().is_none_or(|name| !names.contains(name)));- modified |= bundles.len() != before;- }- modified-}--/// 经同目录临时文件原子替换 profile 清单,失败时保留原文件。-fn write_profile_manifest(path: &Path, manifest: &serde_json::Value) -> Result<(), String> {- use std::io::Write;-- let rendered = serde_json::to_string_pretty(manifest)- .map_err(|e| format!("INTERNAL_PLUGIN_MANIFEST_RENDER_FAILED: {e}"))?;- let temp = path.with_extension(format!("json.internal.{}.tmp", std::process::id()));- let result = (|| -> std::io::Result<()> {- let mut file = std::fs::File::create(&temp)?;- file.write_all(format!("{rendered}\n").as_bytes())?;- file.sync_all()?;- drop(file);- replace_manifest_file(&temp, path)- })();- if let Err(e) = result {- let _ = std::fs::remove_file(&temp);- return Err(format!("INTERNAL_PLUGIN_MANIFEST_WRITE_FAILED: {e}"));- }- log::info!(- "Removed stale internal plugin declarations from profile manifest: {}",- path.display()- );- Ok(())-}--#[cfg(not(windows))]-fn replace_manifest_file(temp: &Path, path: &Path) -> std::io::Result<()> {- std::fs::rename(temp, path)-}--#[cfg(windows)]-fn replace_manifest_file(temp: &Path, path: &Path) -> std::io::Result<()> {- use std::os::windows::ffi::OsStrExt;- use windows_sys::Win32::Storage::FileSystem::{- MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,- };-- let temp_wide: Vec<u16> = temp.as_os_str().encode_wide().chain(Some(0)).collect();- let path_wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();- let moved = unsafe {- MoveFileExW(- temp_wide.as_ptr(),- path_wide.as_ptr(),- MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,- )- };- if moved == 0 {- return Err(std::io::Error::last_os_error());- }- Ok(())-}--/// 删除失效的插件入口,但绝不跟随符号链接 / junction 删除捆绑资源。-///-/// 正常目录只可能是 pnpm 留下的损坏产物,可以递归清理;Unix 符号链接与 Windows-/// junction 则只删除入口本身。入口不存在(包括已被并发清掉)视为幂等成功。-fn remove_stale_plugin_entry(entry: &Path) -> std::io::Result<()> {- let metadata = match std::fs::symlink_metadata(entry) {- Ok(metadata) => metadata,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),- Err(e) => return Err(e),- };- let file_type = metadata.file_type();- #[cfg(windows)]- if file_type.is_symlink_dir() {- return std::fs::remove_dir(entry);- }- if file_type.is_symlink() {- return std::fs::remove_file(entry);- }- if file_type.is_dir() {- return std::fs::remove_dir_all(entry);- }- std::fs::remove_file(entry)-}--/// 判断 pnpm 写入 profile 的依赖值与期望的 `link:` 捆绑路径是否一致。-///-/// 容忍:`link:`/`file:` 前缀缺失或两者混写(历史遗留 `file:` 安装值);Windows-/// 下路径大小写不敏感;尾部斜杠差异(pnpm 各版本落盘形式略有出入)。-fn dep_matches_spec(actual: &str, expected: &str) -> bool {- let norm = |spec: &str| {- let stripped = spec- .strip_prefix("link:")- .or_else(|| spec.strip_prefix("file:"))- .unwrap_or(spec);- // 统一用 dunce 归一化 Windows 扩展长度路径前缀(`\\?\`):- // 期望值已经由 bundled_dep_spec 归一化掉前缀;若历史命中的实值仍带- // `//?/` / `\\?\` 前缀,先归一再比对,保证幂等(避免旧值一次次触发- // 不必要的重装)。先把手写正斜杠的 verbatim 形式(`//?/`)换算成反斜杠- // (dunce 依赖 `\\?\` 识别 verbatim),再交给 dunce::simplified,最后- // 统一回正斜杠,与 bundled_dep_spec 的产出可比。- let backslash = stripped.replace('/', "\\");- dunce::simplified(Path::new(&backslash))- .to_string_lossy()- .replace('\\', "/")- .trim_end_matches('/')- .to_string()- };- let actual = norm(actual);- let expected = norm(expected);- if cfg!(windows) {- actual.eq_ignore_ascii_case(&expected)- } else {- actual == expected- }-}-#[cfg(test)]mod tests {use super::*;@@ -655,7 +523,7 @@ mod tests {let coordinator =std::sync::Arc::new(tokio::sync::Mutex::new(EnsureCoordinator::default()));let fresh_flight = std::sync::Arc::new(tokio::sync::Mutex::new(- None::<(u64, super::super::process::ProcessOwner, FlightResultSender)>,+ None::<(u64, ProcessOwner, FlightResultSender)>,));let fresh_started = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));let cancelling_subscribers = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));@@ -672,9 +540,7 @@ mod tests {async fn retry(coordinator: std::sync::Arc<tokio::sync::Mutex<EnsureCoordinator>>,fresh_flight: std::sync::Arc<- tokio::sync::Mutex<- Option<(u64, super::super::process::ProcessOwner, FlightResultSender)>,- >,+ tokio::sync::Mutex<Option<(u64, ProcessOwner, FlightResultSender)>>,>,fresh_started: std::sync::Arc<std::sync::atomic::AtomicUsize>,cancelling_subscribers: std::sync::Arc<std::sync::atomic::AtomicUsize>,@@ -775,198 +641,4 @@ mod tests {assert_eq!(outcome, Err(reason));assert_eq!(coordinator.next_id, 1);}-- #[test]- fn internal_plugin_entry_requires_readable_manifest_object() {- let root = std::env::temp_dir().join(format!(- "dsh-internal-entry-readiness-{}",- std::process::id()- ));- let manifest = root.join("package.json");- let _ = std::fs::remove_dir_all(&root);- std::fs::create_dir_all(&root).unwrap();-- assert!(!internal_plugin_entry_is_ready(&root));-- std::fs::write(&manifest, br#"{"name":"dsh-tauri"}"#).unwrap();- assert!(internal_plugin_entry_is_ready(&root));-- std::fs::write(&manifest, br#"{"name":"dsh-tauri""#).unwrap();- assert!(!internal_plugin_entry_is_ready(&root));-- std::fs::write(&manifest, b"[]").unwrap();- assert!(!internal_plugin_entry_is_ready(&root));-- std::fs::write(&manifest, [0xff, 0xfe, 0xfd]).unwrap();- assert!(!internal_plugin_entry_is_ready(&root));-- let _ = std::fs::remove_dir_all(root);- }-- #[test]- fn stale_internal_manifest_entries_are_removed_without_touching_other_plugins() {- let mut manifest = serde_json::json!({- "private": true,- "dependencies": {- "dsh-tauri": "file:/Applications/Deepseek Harness Desktop.app/Contents/Resources/resources/preset-plugins/dsh-tauri",- "dsh-tauri-ui": "link:/Applications/Deepseek Harness Desktop.app/Contents/Resources/resources/preset-plugins/dsh-tauri-ui",- "dshmarket": "github:dsh-market/dshmarket"- },- "dsh": {- "profile": {- "bundles": ["dsh-tauri", "dsh-tauri-ui", "dshmarket"]- }- }- });- let names = HashSet::from(["dsh-tauri", "dsh-tauri-ui"]);-- assert!(remove_internal_plugins_from_manifest(&mut manifest, &names));- assert_eq!(- manifest["dependencies"],- serde_json::json!({ "dshmarket": "github:dsh-market/dshmarket" })- );- assert_eq!(- manifest["dsh"]["profile"]["bundles"],- serde_json::json!(["dshmarket"])- );- assert!(!remove_internal_plugins_from_manifest(- &mut manifest,- &names- ));- }-- #[test]- fn manifest_replacement_preserves_original_when_temp_write_fails() {- let root = std::env::temp_dir().join(format!(- "dsh-internal-manifest-write-failure-{}",- std::process::id()- ));- let path = root.join("package.json");- std::fs::create_dir_all(&path).unwrap();- std::fs::write(path.join("sentinel"), "original").unwrap();-- let error = write_profile_manifest(&path, &serde_json::json!({ "private": true }))- .expect_err("directory destination must reject replacement");-- assert!(error.starts_with("INTERNAL_PLUGIN_MANIFEST_WRITE_FAILED:"));- assert_eq!(- std::fs::read_to_string(path.join("sentinel")).unwrap(),- "original"- );- assert!(!root- .join(format!("package.json.internal.{}.tmp", std::process::id()))- .exists());- let _ = std::fs::remove_dir_all(root);- }-- #[test]- fn stale_plain_directory_is_removed() {- let root = std::env::temp_dir().join(format!(- "dsh-internal-stale-directory-{}",- std::process::id()- ));- let entry = root.join("node_modules/dsh-tauri-ui");- std::fs::create_dir_all(&entry).unwrap();- std::fs::write(entry.join("partial"), "broken").unwrap();-- remove_stale_plugin_entry(&entry).unwrap();-- assert!(!entry.exists());- let _ = std::fs::remove_dir_all(root);- }-- #[cfg(unix)]- #[test]- fn stale_symlink_is_removed_without_touching_target() {- let root =- std::env::temp_dir().join(format!("dsh-internal-stale-symlink-{}", std::process::id()));- let target = root.join("old-app/dsh-tauri-ui");- let entry = root.join("profile/node_modules/dsh-tauri-ui");- std::fs::create_dir_all(&target).unwrap();- std::fs::write(target.join("package.json"), "{}").unwrap();- std::fs::create_dir_all(entry.parent().unwrap()).unwrap();- std::os::unix::fs::symlink(&target, &entry).unwrap();-- remove_stale_plugin_entry(&entry).unwrap();-- assert!(target.join("package.json").is_file());- assert!(std::fs::symlink_metadata(&entry).is_err());- let _ = std::fs::remove_dir_all(root);- }-- #[cfg(unix)]- #[test]- fn dangling_symlink_is_removed_idempotently() {- let root = std::env::temp_dir().join(format!(- "dsh-internal-dangling-symlink-{}",- std::process::id()- ));- let entry = root.join("profile/node_modules/dsh-tauri-ui");- std::fs::create_dir_all(entry.parent().unwrap()).unwrap();- std::os::unix::fs::symlink(root.join("missing-app/dsh-tauri-ui"), &entry).unwrap();-- remove_stale_plugin_entry(&entry).unwrap();- remove_stale_plugin_entry(&entry).unwrap();-- assert!(std::fs::symlink_metadata(&entry).is_err());- let _ = std::fs::remove_dir_all(root);- }-- #[test]- fn dep_spec_matches_itself() {- let expected = "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri";- // 与自身一致- assert!(dep_matches_spec(expected, expected));- // 无 link:/file: 前缀(pnpm 某些场景直接落路径)- assert!(dep_matches_spec(- "C:/Apps/dsh/resources/internal-plugins/dsh-tauri",- expected- ));- // 尾部斜杠差异- assert!(dep_matches_spec(- "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri/",- expected- ));- // 反斜杠(Windows 原生形式)- assert!(dep_matches_spec(- "link:C:\\Apps\\dsh\\resources\\internal-plugins\\dsh-tauri",- expected- ));- // 历史遗留 file: 形式(协议切换前已安装的值)- assert!(dep_matches_spec(- "file:C:/Apps/dsh/resources/internal-plugins/dsh-tauri",- expected- ));- }-- #[test]- fn dep_spec_rejects_wrong_path_or_source() {- let expected = "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri";- // 仍指向 npm 版本(用户手动从 npm 安装,非捆绑 link: 源)- assert!(!dep_matches_spec("[email protected]", expected));- // 指向其它位置(旧版本安装目录等)- assert!(!dep_matches_spec("link:D:/elsewhere/dsh-tauri", expected));- // 同名不同宿主盘符- assert!(!dep_matches_spec(- "link:D:/Apps/dsh/resources/internal-plugins/dsh-tauri",- expected- ));- }-- #[cfg(windows)]- #[test]- fn dep_spec_case_insensitive_on_windows() {- // Windows 文件系统大小写不敏感,路径比较须忽略大小写- let expected = "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri";- assert!(dep_matches_spec(- "link:c:/apps/DSH/resources/internal-plugins/Dsh-Tauri",- expected- ));- // 实值仍带 Windows 扩展长度前缀(`\\?\`,dunce::simplified 归一化)时,- // 与归一化掉前缀的期望值仍视为同一路径(幂等,避免不必要的重装)- assert!(dep_matches_spec(- "link://?/C:/Apps/dsh/resources/internal-plugins/dsh-tauri",- expected- ));- }}diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex 08b74962..3ea443dd 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -19,7 +19,8 @@//! - [`installed`]:profile 内已安装插件检测(解析 package.json 的依赖与 bundles)//! - [`internal`]:内置插件启动自愈(随包分发产物缺失/路径变更时强制重装)//! - [`verify`]:预装插件完整性自检(清单引用但 node_modules 产物缺失时 `pnpm install` 修复)-//! - [`install`]:对外安装/升级/卸载编排(校验、环境准备、调用 dsh 子进程),+//! - [`install`]:对外安装/升级/卸载编排(目录模块 `install/`:编排入口、spec 准备、+//! 子进程环境、pnpm 选版、allowBuilds 白名单、错误诊断与产物核验),//! 以及启动时对清单中带 `deprecated` 标记的社区插件自动卸载//! - [`errors`]:插件错误记录(安装/升级/卸载失败 + 页面运行期上报,持久化)//! - [`process`]:dsh 子进程启动与输出流逐行转发@@ -40,8 +41,8 @@ pub mod watch;pub use cancel::cancel;pub(crate) use install::harness_prefer_bundled_pnpm;-pub use install::{install, remove, update};pub(crate) use install::uninstall_deprecated_plugins;+pub use install::{install, remove, update};pub(crate) use installed::ensure_profile_npmrc;pub use installed::{list, PreinstallPlugin};pub(crate) use internal::cancel as cancel_internal_plugins;diff --git a/src-tauri/src/service/plugin/recovery.rs b/src-tauri/src/service/plugin/recovery.rsdeleted file mode 100644index 2f1d401c..00000000--- a/src-tauri/src/service/plugin/recovery.rs+++ /dev/null@@ -1,930 +0,0 @@-//! 插件异常修复(recovery):启动失败 / 运行期异常时定位问题插件,并提供-//! 「卸除此插件并继续检测」的一键离线修复。-//!-//! 参考 dataelement/dsh-desktop 的插件异常修复模式(PR #94/#96):-//! - **定位**:从启动日志按错误特征提取插件引用(duplicate route / loader entry /-//! cannot resolve bundle / no dsh.bundle / slot conflict / failed to import),再-//! 按 profile `package.json` + `node_modules` 归属回配置的根插件——只有拿到确凿-//! 证据才动手,绝不瞎猜。-//! - **卸载**:直接改 profile 清单(`dependencies` + `dsh.profile.bundles`)、删除-//! `node_modules/<id>`、剥离 `cordis.patch.yml` 中该插件的补丁层、清掉-//! `pnpm-lock.yaml`(best-effort),保留其它插件与配置。与 [`super::install`] 走-//! `dsh plugin` 子进程不同:本模块离线、精准,不需要网络。-//!-//! 卸载成功后由前端 `restart()` 重启并重新检测;若仍有问题,启动失败再次触发-//! 定位,形成「继续检测」循环。--use regex::Regex;-use serde::{Deserialize, Serialize};-use std::collections::HashSet;-use std::fs;-#[cfg(windows)]-use std::os::windows::fs::FileTypeExt;-use std::path::Path;-use tauri::AppHandle;--use super::errors;-use super::installed::profile_dir;-use crate::service::fs_guard;--/// 前端监听的事件名:需要弹出插件异常修复界面时推送。-pub(crate) const RECOVERY_REQUIRED_EVENT: &str = "plugin-recovery-required";--/// 真正不可被「修复卸载」删除的核心 bundle / 官方包。-///-/// `dshmarket`(插件市场)虽然列在预设清单里,但它本身是第三方插件(npm 包-/// `dshmarket`,来源 `dsh-market/dsh-market`),不是核心/官方包,必须允许用户-/// 卸载。若把它列入保护名单,用户从插件面板点「卸载」时,`dsh plugin remove`-/// 因 dshmarket 属于 in-box bundle(`pnpm remove` 不动它)会返回成功但插件仍在,-/// 桌面端又因 protection 跳过离线卸载兜底,最终「提示成功但插件仍在」。-fn is_core_package(name: &str) -> bool {- name == "@deepseek-ai/dsh-base"- || name == "@deepseek-ai/dsh-web-app"- || name.starts_with("@deepseek-ai/")-}--/// 是否为合法的 npm 包名(可带 scope)。用于过滤日志里提取到的候选引用。-fn is_package_name(s: &str) -> bool {- let s = s.trim();- if s.is_empty() || s.contains(':') || s.chars().any(|c| c.is_whitespace()) {- return false;- }-- let (scope, name) = if let Some((scope, name)) = s.split_once('/') {- // scoped 包名必须恰好只有一层 scope/name,不能把多个路径片段带入 join。- if !s.starts_with('@') || name.is_empty() || name.contains('/') {- return false;- }- (Some(scope), name)- } else {- if s.starts_with('@') {- return false;- }- (None, s)- };-- fn valid_component(component: &str, is_scope: bool) -> bool {- let component = if is_scope {- component.strip_prefix('@').unwrap_or(component)- } else {- component- };- !component.is_empty()- && component != "."- && component != ".."- && !component.starts_with('.')- && !component.ends_with('.')- && !component.starts_with("..")- && !component.ends_with("..")- && component- .chars()- .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_')- }-- if scope.is_some_and(|scope| !valid_component(scope, true)) {- return false;- }- valid_component(name, false)-}--/// 是否是可行动的第三方插件引用(排除核心包与 @deepseek-ai 官方包)。-pub(crate) fn is_actionable_plugin_ref(s: &str) -> bool {- is_package_name(s) && !is_core_package(s.trim())-}--/// 启动失败时前端读到的日志行(已清洗 ANSI),序列化给前端(camelCase)。-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "camelCase")]-pub struct PluginRecoveryInfo {- /// 定位到的插件 id(npm 包名),可能为空(未定位到具体插件)- pub plugins: Vec<String>,- /// 失败原因判别键:duplicate_route / duplicate_loader_entry / cannot_resolve_bundle /- /// no_dsh_bundle / slot_conflict / load_failed / runtime / unknown- pub reason: String,- /// 动态详情(如冲突的路由 / 槽位 / 服务组件 id),用于 I18n 插值- pub detail: String,- /// 原始错误信息(技术详情查看)- pub raw_error: String,-}--// ---- 纯提取函数(便于单元测试)------/// 从日志文本中提取插件引用(多个错误特征的正则,去重)。-fn extract_plugin_refs(text: &str) -> Vec<String> {- let mut refs = HashSet::new();- let patterns = [- // failed to apply/import loader entry <name> (<pkg>)- r#"failed to (?:apply|import) loader entry[^\n]*\(([^)]+)\)"#,- // cannot resolve profile bundle "<pkg>"- r#"cannot resolve profile bundle\s+["']?([^"'\n]+)["']?"#,- // profile bundle "<pkg>" declares no dsh.bundle- r#"profile bundle\s+["']?([^"'\n]+)["']?\s+declares no dsh\.bundle"#,- // plugin(s) failed to load: <pkg>- r#"plugins? failed to load:\s*([A-Za-z0-9@/_.\-]+)"#,- ];- for pattern in patterns {- if let Ok(re) = Regex::new(pattern) {- for cap in re.captures_iter(text) {- if let Some(m) = cap.get(1) {- let cand = m.as_str().trim();- if is_actionable_plugin_ref(cand) {- refs.insert(cand.to_string());- }- }- }- }- }- // 「Failed to load plugins」错误卡片:紧随其后的若干行通常是包名。- for m in Regex::new(r"(?m)^Failed to load plugins\s*$")- .expect("literal")- .find_iter(text)- {- let rest = &text[m.end()..];- for line in rest.lines().take(12) {- let cand = line.trim().trim_end_matches(['.', ',', ' ']);- if is_actionable_plugin_ref(cand) {- refs.insert(cand.to_string());- }- }- }- refs.into_iter().collect()-}--/// 抽取「重复 loader entry id」。-fn extract_duplicate_loader_entry(text: &str) -> Option<String> {- let re = Regex::new(r#"duplicate loader entry id:\s*["']?([^"'\s]+)["']?"#).ok()?;- re.captures(text)- .and_then(|c| c.get(1))- .map(|m| m.as_str().trim().to_string())-}--/// 抽取「界面槽位冲突」的槽位名。-fn extract_slot_conflict(text: &str) -> Option<String> {- let re = Regex::new(r#"single slot\s+["']([^"']+)["']\s+already has a registration"#).ok()?;- if let Some(c) = re.captures(text) {- return c.get(1).map(|m| m.as_str().trim().to_string());- }- let re = Regex::new(r#"UI slot\s+["']([^"']+)["']\s+has duplicate registrations"#).ok()?;- re.captures(text)- .and_then(|c| c.get(1))- .map(|m| m.as_str().trim().to_string())-}--/// 对日志文本分类失败原因,返回(判别键, 动态详情)。-fn classify_reason(text: &str) -> (String, String) {- let dup_route = Regex::new(r#"duplicate prefix route\s+["']([^"']+)["']"#).expect("literal");- if let Some(c) = dup_route.captures(text) {- let route = c.get(1).map(|m| m.as_str().to_string()).unwrap_or_default();- return ("duplicate_route".into(), route);- }- if let Some(entry) = extract_duplicate_loader_entry(text) {- return ("duplicate_loader_entry".into(), entry);- }- if let Some(re) = Regex::new(r#"cannot resolve profile bundle\s+["']?([^"'\n]+)["']?"#).ok() {- if let Some(c) = re.captures(text) {- return (- "cannot_resolve_bundle".into(),- c.get(1).map(|m| m.as_str().to_string()).unwrap_or_default(),- );- }- }- if text.contains("declares no dsh.bundle") {- let pkg = extract_plugin_refs(text)- .into_iter()- .next()- .unwrap_or_default();- return ("no_dsh_bundle".into(), pkg);- }- if let Some(slot) = extract_slot_conflict(text) {- return ("slot_conflict".into(), slot);- }- if text.contains("failed to import loader entry")- || text.contains("failed to apply loader entry")- {- return ("load_failed".into(), String::new());- }- ("unknown".into(), String::new())-}--// ---- 归属:把日志里的引用映射回 profile 配置的根插件 ------/// 读取 role 包自身的 package.json,返回一个轻量视图。-#[derive(Default)]-struct PluginMeta {- deps: Vec<String>,- optional_deps: Vec<String>,- patch_path: Option<String>,-}--fn read_plugin_meta(dir: &Path) -> Option<PluginMeta> {- let content = fs::read_to_string(dir.join("package.json")).ok()?;- let v: serde_json::Value = serde_json::from_str(&content).ok()?;- let mut meta = PluginMeta::default();- if let Some(deps) = v.get("dependencies").and_then(|d| d.as_object()) {- meta.deps = deps.keys().cloned().collect();- }- if let Some(deps) = v.get("optionalDependencies").and_then(|d| d.as_object()) {- meta.optional_deps = deps.keys().cloned().collect();- }- meta.patch_path = v- .get("dsh")- .and_then(|d| d.get("bundle"))- .and_then(|b| b.get("patch"))- .and_then(|p| p.as_str())- .map(String::from);- Some(meta)-}--/// 从档案清单提取启动时会加载的第三方根插件。-///-/// 不能要求插件同时存在于 `dependencies`:卸载中断或旧版 CLI 可能只删掉依赖,-/// 却把 bundle 留在清单中;这正会触发 `cannot resolve profile bundle`,也正是恢复-/// 流程需要识别并清理的损坏状态。-fn configured_root_bundles(manifest: &serde_json::Value) -> Vec<String> {- manifest- .get("dsh")- .and_then(|d| d.get("profile"))- .and_then(|p| p.get("bundles"))- .and_then(|b| b.as_array())- .map(|bundles| {- bundles- .iter()- .filter_map(|bundle| bundle.as_str())- .filter(|bundle| is_actionable_plugin_ref(bundle))- .map(String::from)- .collect()- })- .unwrap_or_default()-}--/// 当前档案配置的根插件:以 `dsh.profile.bundles` 为准,因为只有 bundles 会随-/// 启动加载并导致 profile bundle 解析失败。-fn configured_roots(app_handle: &AppHandle) -> Vec<String> {- let dir = profile_dir(app_handle);- let content = match fs::read_to_string(dir.join("package.json")) {- Ok(c) => c,- Err(_) => return Vec::new(),- };- let v: serde_json::Value = match serde_json::from_str(&content) {- Ok(v) => v,- Err(_) => return Vec::new(),- };- configured_root_bundles(&v)-}--/// 判断某个根 bundle 是否「拥有」被报告的子包:其依赖里直接声明了该子包,或其-/// patch 层里引用该包名。-fn bundle_owns_package(profile: &Path, bundle: &str, package: &str) -> bool {- let dir = profile.join("node_modules").join(bundle);- let Some(meta) = read_plugin_meta(&dir) else {- return false;- };- if meta.deps.iter().any(|d| d == package) || meta.optional_deps.iter().any(|d| d == package) {- return true;- }- if let Some(patch) = &meta.patch_path {- if let Ok(content) = fs::read_to_string(dir.join(patch)) {- return content.contains(package);- }- }- false-}--/// 判断某个根插件的运行时代码/依赖是否引用了给定包集合之一(用于「动态创建官方-/// UI 包」的归属)。-fn plugin_references_packages(profile: &Path, plugin: &str, packages: &HashSet<String>) -> bool {- let dir = profile.join("node_modules").join(plugin);- if let Some(meta) = read_plugin_meta(&dir) {- if meta- .deps- .iter()- .chain(meta.optional_deps.iter())- .any(|d| packages.contains(d))- {- return true;- }- }- for file in [- "cordis.patch.yml",- "index.js",- "lib/index.js",- "dist/index.js",- ] {- if let Ok(content) = fs::read_to_string(dir.join(file)) {- if packages.iter().any(|p| content.contains(p)) {- return true;- }- }- }- false-}--/// 判断某个根插件的 patch 层是否声明了重复的 loader entry id。-fn plugin_declares_loader_entry(profile: &Path, plugin: &str, entry_id: &str) -> bool {- let dir = profile.join("node_modules").join(plugin);- let Some(meta) = read_plugin_meta(&dir) else {- return false;- };- let Some(patch) = &meta.patch_path else {- return false;- };- let Ok(content) = fs::read_to_string(dir.join(patch)) else {- return false;- };- let re = Regex::new(&format!(- r#"^\s*-\s+id:\s*["']?{}["']?(?:\s*(?:#.*)?)?$"#,- regex::escape(entry_id)- ))- .ok();- re.map(|re| re.is_match(&content)).unwrap_or(false)-}--/// 判断某个根插件的文件是否包含给定槽位名。-fn plugin_matches_slot(profile: &Path, plugin: &str, slot: &str) -> bool {- let dir = profile.join("node_modules").join(plugin);- for file in [- "cordis.patch.yml",- "client.js",- "lib/client.js",- "dist/client.js",- "package.json",- "index.js",- "lib/index.js",- "dist/index.js",- ] {- if let Ok(content) = fs::read_to_string(dir.join(file)) {- if content.contains(slot) {- return true;- }- }- }- false-}--/// 提供某槽位的官方 UI 客户端包(用于槽位冲突归属)。-fn packages_providing_slot(profile: &Path, slot: &str) -> Vec<String> {- let scope = profile.join("node_modules").join("@deepseek-ai");- let Ok(entries) = fs::read_dir(&scope) else {- return Vec::new();- };- let mut out = Vec::new();- for entry in entries.flatten() {- let name = entry.file_name().to_string_lossy().into_owned();- if !name.starts_with("dsh-client-ui-") {- continue;- }- let package = format!("@deepseek-ai/{name}");- let dir = entry.path();- for file in ["client.js", "lib/client.js", "dist/client.js"] {- if let Ok(content) = fs::read_to_string(dir.join(file)) {- if content.contains(slot) {- out.push(package);- break;- }- }- }- }- out-}--/// 把日志提取到的引用归属回 profile 配置的根插件;只在一对一(证据唯一)时返回,-/// 否则返回空(绝不瞎猜)。-fn resolve_recovery_plugins(- app_handle: &AppHandle,- detected_refs: &[String],- duplicate_entry: Option<&str>,- slot_conflict: Option<&str>,-) -> Vec<String> {- let profile = profile_dir(app_handle);- let roots = configured_roots(app_handle);- if roots.is_empty() {- return Vec::new();- }- let roots_set: HashSet<&String> = roots.iter().collect();-- // 1) 直接命中,或证明某报告子包被唯一根插件拥有。- let mut matched = HashSet::new();- for detected in detected_refs {- if !is_package_name(detected) {- continue;- }- if roots_set.contains(detected) {- matched.insert(detected.clone());- continue;- }- let owners: Vec<&String> = roots- .iter()- .filter(|root| bundle_owns_package(&profile, root, detected))- .collect();- if owners.len() == 1 {- matched.insert(owners[0].clone());- }- }- if matched.len() == 1 {- return matched.into_iter().collect();- }-- // 1b) 兜底:某官方叶包(loader 报错常指这个)被动态创建,归属回引用它的唯一根。- let mut dynamic_owners = HashSet::new();- for detected in detected_refs {- if !is_package_name(detected) || roots_set.contains(detected) {- continue;- }- let packages: HashSet<String> = [detected.to_string()].into();- let owners: Vec<&String> = roots- .iter()- .filter(|root| plugin_references_packages(&profile, root, &packages))- .collect();- if owners.len() == 1 {- dynamic_owners.insert(owners[0].clone());- }- }- if dynamic_owners.len() == 1 {- return dynamic_owners.into_iter().collect();- }-- // 2) 重复 loader entry:命中唯一根插件。- if let Some(entry) = duplicate_entry {- let owners: Vec<&String> = roots- .iter()- .filter(|root| plugin_declares_loader_entry(&profile, root, entry))- .collect();- if owners.len() == 1 {- return owners.into_iter().map(|s| s.clone()).collect();- }- }-- // 3) 槽位冲突:命中唯一根插件;否则找提供槽位的官方包,再由唯一根引用它。- if let Some(slot) = slot_conflict {- let matched: Vec<&String> = roots- .iter()- .filter(|root| plugin_matches_slot(&profile, root, slot))- .collect();- if matched.len() == 1 {- return matched.into_iter().map(|s| s.clone()).collect();- }- let providers: HashSet<String> = packages_providing_slot(&profile, slot)- .into_iter()- .collect();- if !providers.is_empty() {- let owners: Vec<&String> = roots- .iter()- .filter(|root| plugin_references_packages(&profile, root, &providers))- .collect();- if owners.len() == 1 {- return owners.into_iter().map(|s| s.clone()).collect();- }- }- }-- Vec::new()-}--/// 定位启动失败的问题插件:给定日志行,返回恢复信息(未定位到则 plugins 为空)。-pub fn detect(app_handle: &AppHandle, log_lines: &[String]) -> PluginRecoveryInfo {- let text = log_lines.join("\n");- let refs = extract_plugin_refs(&text);- let duplicate_entry = extract_duplicate_loader_entry(&text);- let slot_conflict = extract_slot_conflict(&text);- let (reason, detail) = classify_reason(&text);- let plugins = resolve_recovery_plugins(- app_handle,- &refs,- duplicate_entry.as_deref(),- slot_conflict.as_deref(),- );- let raw_error = refs_text(&text);- PluginRecoveryInfo {- plugins,- reason,- detail,- raw_error,- }-}--/// 原始错误描述:尽量取关键错误行,供「查看技术详情」。-fn refs_text(text: &str) -> String {- // 从日志里搜出带错误标记的行(最多 8 行),没有则取尾部。- let marker_any =- Regex::new(r"(?i)error|duplicate|fatal|panic|throw|failed|exception|✖").expect("literal");- let mut err_lines: Vec<&str> = text- .lines()- .filter(|l| marker_any.is_match(l))- .map(|l| l.trim())- .filter(|l| !l.is_empty())- .collect();- if err_lines.is_empty() {- let tail: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();- let start = tail.len().saturating_sub(8);- err_lines = tail[start..].to_vec();- }- let joined = err_lines.join("\n");- joined.chars().take(2000).collect()-}--// ---- 卸载(直接改 profile 清单)------/// 从 manifest 中移除指定插件(`dependencies` + `dsh.profile.bundles`),返回是否有改动。-fn remove_plugin_from_manifest(manifest: &mut serde_json::Value, id: &str) -> bool {- let mut modified = false;- if let Some(deps) = manifest- .get_mut("dependencies")- .and_then(|d| d.as_object_mut())- {- if deps.remove(id).is_some() {- modified = true;- }- }- if let Some(bundles) = manifest- .get_mut("dsh")- .and_then(|d| d.get_mut("profile"))- .and_then(|p| p.get_mut("bundles"))- .and_then(|b| b.as_array_mut())- {- let before = bundles.len();- bundles.retain(|b| b.as_str() != Some(id));- if bundles.len() != before {- modified = true;- }- }- modified-}--/// 删除插件入口:符号链接或 junction 只删除入口本身,普通目录递归删除。-fn remove_plugin_entry(entry: &Path) -> std::io::Result<()> {- let file_type = fs::symlink_metadata(entry)?.file_type();- #[cfg(windows)]- if file_type.is_symlink_dir() {- return fs::remove_dir(entry);- }- if file_type.is_symlink() {- return fs::remove_file(entry);- }- fs::remove_dir_all(entry)-}--/// 删除 `node_modules/<id>`;scoped 目录删除后若 scope 空则一并清理。-fn remove_plugin_dir(profile: &Path, id: &str) {- let node_modules = profile.join("node_modules");- let Ok(node_modules_root) = fs_guard::ensure_within(&node_modules, profile) else {- log::warn!(- "refusing to remove plugin from node_modules outside profile: {}",- node_modules.display()- );- return;- };- let entry = node_modules.join(id);- let Ok(entry_metadata) = fs::symlink_metadata(&entry) else {- return;- };- let entry_is_dangling_symlink = entry_metadata.file_type().is_symlink() && !entry.exists();- if entry_is_dangling_symlink {- // 悬空链接无法规范化目标,只验证父目录,确保删除的仍是 node_modules 内入口。- let Some(parent) = entry.parent() else {- return;- };- if let Err(e) = fs_guard::ensure_within(parent, &node_modules_root) {- log::warn!(- "refusing to remove dangling plugin symlink outside node_modules: {} ({e})",- entry.display()- );- return;- }- } else if let Err(e) = fs_guard::ensure_within(&entry, &node_modules_root) {- log::warn!(- "refusing to remove plugin outside node_modules: {} ({e})",- entry.display()- );- return;- }- if let Err(e) = remove_plugin_entry(&entry) {- if e.kind() != std::io::ErrorKind::NotFound {- log::warn!("failed to remove plugin dir {}: {e}", entry.display());- }- }- if let Some(scope) = id- .starts_with('@')- .then(|| id.split('/').next().unwrap_or_default())- {- if !scope.is_empty() && scope != id {- let scope_entry = node_modules.join(scope);- if scope_entry.is_dir()- && scope_entry- .read_dir()- .map(|mut d| d.next().is_none())- .unwrap_or(false)- {- if fs_guard::ensure_within(&scope_entry, &node_modules_root).is_ok() {- let _ = remove_plugin_entry(&scope_entry);- }- }- }- }-}--/// 从 `cordis.patch.yml` 中剥离目标插件的 patch 条目(保留其它插件的 patch)。-///-/// 与 dsh-desktop「直接重置为 []」不同:这里只移除与目标插件相关的条目,不破坏-/// 其它插件的配置层,符合「其它插件不会被删除」的承诺。解析失败则原样保留。-fn strip_cordis_patch_for(profile: &Path, id: &str) {- let path = profile.join("cordis.patch.yml");- let Ok(content) = fs::read_to_string(&path) else {- return;- };- let Ok(doc) = serde_yaml::from_str::<serde_yaml::Value>(&content) else {- return;- };- let Some(entries) = doc.as_sequence() else {- return;- };- let kept: Vec<serde_yaml::Value> = entries- .iter()- .filter(|e| !patch_entry_targets(e, id))- .cloned()- .collect();- if kept.len() == entries.len() {- return;- }- if let Ok(rendered) = serde_yaml::to_string(&serde_yaml::Value::Sequence(kept)) {- let _ = fs::write(&path, rendered);- log::info!("Stripped cordis.patch.yml entries for plugin {id}");- }-}--/// 一个 patch 条目是否「针对」目标插件:顶层 id 字段或任意字段值等于该包名。-fn patch_entry_targets(entry: &serde_yaml::Value, id: &str) -> bool {- match entry {- serde_yaml::Value::Mapping(map) => map- .iter()- .any(|(k, v)| k.as_str() == Some(id) || v.as_str() == Some(id)),- serde_yaml::Value::String(s) => s == id,- _ => false,- }-}--/// 修复模式卸载:精准删除指定插件(离线、不破坏其它插件)。-pub fn uninstall(app_handle: &AppHandle, id: &str) -> Result<(), String> {- if !is_actionable_plugin_ref(id) {- return Err(format!(- "PLUGIN_RECOVERY_REFUSED: refusing to remove core/official package {id}"- ));- }- let profile = profile_dir(app_handle);- let manifest_path = profile.join("package.json");- if !manifest_path.exists() {- return Err("PLUGIN_RECOVERY_NO_MANIFEST: profile package.json missing".to_string());- }- let content =- fs::read_to_string(&manifest_path).map_err(|e| format!("PLUGIN_RECOVERY_READ: {e}"))?;- let mut manifest: serde_json::Value =- serde_json::from_str(&content).map_err(|e| format!("PLUGIN_RECOVERY_PARSE: {e}"))?;-- let modified = remove_plugin_from_manifest(&mut manifest, id);- if modified {- let rendered = serde_json::to_string_pretty(&manifest)- .map_err(|e| format!("PLUGIN_RECOVERY_RENDER: {e}"))?;- std::fs::write(&manifest_path, format!("{rendered}\n"))- .map_err(|e| format!("PLUGIN_RECOVERY_WRITE: {e}"))?;- log::info!("Recovery uninstall removed plugin {id} from profile manifest");- }-- remove_plugin_dir(&profile, id);- strip_cordis_patch_for(&profile, id);- // 清掉 lockfile,让 pnpm 重装时重建干净依赖图(best-effort)。- if let Err(e) = fs::remove_file(profile.join("pnpm-lock.yaml")) {- if e.kind() != std::io::ErrorKind::NotFound {- log::warn!("failed to remove pnpm-lock.yaml during recovery: {e}");- }- }- if let Err(e) = errors::clear(app_handle, id) {- log::warn!("failed to clear plugin error for {id} during recovery: {e}");- }- Ok(())-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn package_name_validation() {- assert!(is_package_name("dshmarket"));- assert!(is_package_name("@scope/pkg"));- assert!(is_package_name("dsh-better-sidebar"));- assert!(!is_package_name(""));- assert!(!is_package_name("has space"));- assert!(!is_package_name("with:colon"));- assert!(!is_package_name("@bare"));- assert!(!is_package_name("foo/../../target"));- assert!(!is_package_name("@scope/../../target"));- assert!(!is_package_name("@scope/pkg/extra"));- assert!(!is_package_name(r"foo\..\target"));- assert!(!is_package_name(r"@scope\pkg"));- assert!(!is_package_name("@scope/@pkg"));- assert!(!is_package_name("@scope/.."));- assert!(!is_package_name("@scope/."));- assert!(!is_package_name(".pnpm"));- assert!(!is_package_name(".hidden"));- assert!(!is_package_name("foo."));- assert!(!is_package_name("@.scope/pkg"));- assert!(!is_package_name("@scope/.hidden"));- assert!(!is_package_name("@scope/foo."));- assert!(is_package_name("foo.bar"));- assert!(is_package_name("@scope/pkg.name"));- assert!(!is_actionable_plugin_ref("@deepseek-ai/dsh-base"));- // dshmarket 是第三方市场插件,可卸载(不应被当作核心保护包)- assert!(is_actionable_plugin_ref("dshmarket"));- assert!(is_actionable_plugin_ref("dsh-better-sidebar"));- }-- #[test]- fn remove_plugin_dir_rejects_path_escape() {- let root = std::env::temp_dir().join(format!("dsh-plugin-recovery-{}", std::process::id()));- let profile = root.join("profile");- std::fs::create_dir_all(profile.join("node_modules/foo")).unwrap();- let outside = profile.join("target");- std::fs::create_dir_all(&outside).unwrap();-- remove_plugin_dir(&profile, "foo/../../target");-- assert!(outside.exists(), "path traversal target must remain");- let _ = std::fs::remove_dir_all(root);- }-- #[test]- fn remove_plugin_dir_removes_valid_plugin() {- let root =- std::env::temp_dir().join(format!("dsh-plugin-recovery-valid-{}", std::process::id()));- let profile = root.join("profile");- let plugin = profile.join("node_modules/dsh-example");- std::fs::create_dir_all(&plugin).unwrap();- std::fs::write(plugin.join("index.js"), "module.exports = {};").unwrap();-- remove_plugin_dir(&profile, "dsh-example");-- assert!(!plugin.exists(), "valid plugin directory should be removed");- let _ = std::fs::remove_dir_all(root);- }-- #[cfg(unix)]- #[test]- fn remove_plugin_dir_removes_symlink_without_target() {- let root = std::env::temp_dir().join(format!(- "dsh-plugin-recovery-pnpm-symlink-{}",- std::process::id()- ));- let profile = root.join("profile");- let link = profile.join("node_modules/dsh-example");- let target = profile.join("node_modules/.pnpm/dsh-example@1/node_modules/dsh-example");- std::fs::create_dir_all(&target).unwrap();- std::os::unix::fs::symlink(&target, &link).unwrap();-- remove_plugin_dir(&profile, "dsh-example");-- assert!(target.exists(), "pnpm canonical target must remain");- assert!(- std::fs::symlink_metadata(&link).is_err(),- "only the package symlink entry should be removed"- );- let _ = std::fs::remove_dir_all(root);- }-- #[cfg(unix)]- #[test]- fn remove_plugin_dir_removes_dangling_symlink() {- let root = std::env::temp_dir().join(format!(- "dsh-plugin-recovery-dangling-symlink-{}",- std::process::id()- ));- let profile = root.join("profile");- let link = profile.join("node_modules/dsh-example");- let missing_target = profile.join("node_modules/.pnpm/missing/dsh-example");- std::fs::create_dir_all(link.parent().unwrap()).unwrap();- std::os::unix::fs::symlink(&missing_target, &link).unwrap();-- remove_plugin_dir(&profile, "dsh-example");-- assert!(- std::fs::symlink_metadata(&link).is_err(),- "dangling plugin symlink entry should be removed"- );- let _ = std::fs::remove_dir_all(root);- }-- #[cfg(unix)]- #[test]- fn remove_plugin_dir_rejects_node_modules_symlink_escape() {- let root =- std::env::temp_dir().join(format!("dsh-plugin-recovery-link-{}", std::process::id()));- let profile = root.join("profile");- let outside = root.join("outside-node-modules");- let plugin = outside.join("dsh-example");- std::fs::create_dir_all(&profile).unwrap();- std::fs::create_dir_all(&plugin).unwrap();- std::os::unix::fs::symlink(&outside, profile.join("node_modules")).unwrap();-- remove_plugin_dir(&profile, "dsh-example");-- assert!(plugin.exists(), "plugin outside profile must remain");- let _ = std::fs::remove_dir_all(root);- }-- #[test]- fn extract_refs_from_failure_log() {- let log = r#"-[stderr] failed to apply loader entry dshSidebarApi (@omdsh-dev/dsh-better-sidebar)-[stderr] cannot resolve profile bundle "dsh-web-ui-all"-"#;- let refs = extract_plugin_refs(log);- assert!(refs.contains(&"@omdsh-dev/dsh-better-sidebar".to_string()));- assert!(refs.contains(&"dsh-web-ui-all".to_string()));- }-- #[test]- fn extract_refs_from_boot_card() {- let log = "Failed to load plugins\ndsh-better-sidebar\n@scope/another\nAn unknown error occurred\n";- let refs = extract_plugin_refs(log);- assert!(refs.contains(&"dsh-better-sidebar".to_string()));- assert!(refs.contains(&"@scope/another".to_string()));- // 非包名行不应被当作插件引用- assert!(!refs.iter().any(|r| r.contains("unknown")));- }-- #[test]- fn extract_duplicate_and_slot() {- let route_log = r#"duplicate prefix route "/sidebar/api""#;- assert_eq!(classify_reason(route_log).0, "duplicate_route");- let entry_log = "duplicate loader entry id: \"dshSidebarApi\"";- assert_eq!(- extract_duplicate_loader_entry(entry_log).as_deref(),- Some("dshSidebarApi")- );- let slot_log = r#"single slot "sidebar" already has a registration"#;- assert_eq!(extract_slot_conflict(slot_log).as_deref(), Some("sidebar"));- }-- #[test]- fn remove_plugin_from_manifest_edits_deps_and_bundles() {- let mut manifest = serde_json::json!({- "name": "dsh-profile-web",- "private": true,- "dependencies": { "dshmarker": "1.0.0", "dsh-better-sidebar": "1.0.0" },- "dsh": { "profile": { "bundles": ["@deepseek-ai/dsh-base", "dsh-better-sidebar"] } }- });- let modified = remove_plugin_from_manifest(&mut manifest, "dsh-better-sidebar");- assert!(modified);- assert!(manifest["dependencies"].get("dsh-better-sidebar").is_none());- assert!(manifest["dependencies"].get("dshmarker").is_some());- assert_eq!(- manifest["dsh"]["profile"]["bundles"]- .as_array()- .unwrap()- .len(),- 1- );- }-- #[test]- fn configured_roots_include_bundle_left_after_dependency_removal() {- let manifest = serde_json::json!({- "name": "dsh-profile-web",- "private": true,- "dependencies": {},- "dsh": {- "profile": {- "bundles": [- "@deepseek-ai/dsh-base",- "@deepseek-ai/dsh-web-app",- "@linxin666/dsh-web-ui-all"- ]- }- }- });-- assert_eq!(- configured_root_bundles(&manifest),- vec!["@linxin666/dsh-web-ui-all"]- );- }-- #[test]- fn patch_strip_targets_plugin_only() {- let patch = serde_yaml::to_string(&serde_yaml::Value::Sequence(vec![- serde_yaml::from_str::<serde_yaml::Value>("id: dsh-better-sidebar\nfoo: 1").unwrap(),- serde_yaml::from_str::<serde_yaml::Value>("id: dsh-web-ui-all\nbar: 2").unwrap(),- ]))- .unwrap();- let doc: serde_yaml::Value = serde_yaml::from_str(&patch).unwrap();- let kept: Vec<serde_yaml::Value> = doc- .as_sequence()- .unwrap()- .iter()- .filter(|e| !patch_entry_targets(e, "dsh-better-sidebar"))- .cloned()- .collect();- assert_eq!(kept.len(), 1);- let kept_doc = serde_yaml::to_string(&serde_yaml::Value::Sequence(kept)).unwrap();- assert!(kept_doc.contains("dsh-web-ui-all"));- assert!(!kept_doc.contains("dsh-better-sidebar"));- }-}diff --git a/src-tauri/src/service/plugin/recovery/extract.rs b/src-tauri/src/service/plugin/recovery/extract.rsnew file mode 100644index 00000000..33ebd643--- /dev/null+++ b/src-tauri/src/service/plugin/recovery/extract.rs@@ -0,0 +1,142 @@+//! 纯提取函数:从启动日志按错误特征正则提取插件引用与失败原因判别键。++use regex::Regex;+use std::collections::HashSet;++use super::is_actionable_plugin_ref;++/// 从日志文本中提取插件引用(多个错误特征的正则,去重)。+pub(super) fn extract_plugin_refs(text: &str) -> Vec<String> {+ let mut refs = HashSet::new();+ let patterns = [+ // failed to apply/import loader entry <name> (<pkg>)+ r#"failed to (?:apply|import) loader entry[^\n]*\(([^)]+)\)"#,+ // cannot resolve profile bundle "<pkg>"+ r#"cannot resolve profile bundle\s+["']?([^"'\n]+)["']?"#,+ // profile bundle "<pkg>" declares no dsh.bundle+ r#"profile bundle\s+["']?([^"'\n]+)["']?\s+declares no dsh\.bundle"#,+ // plugin(s) failed to load: <pkg>+ r#"plugins? failed to load:\s*([A-Za-z0-9@/_.\-]+)"#,+ ];+ for pattern in patterns {+ if let Ok(re) = Regex::new(pattern) {+ for cap in re.captures_iter(text) {+ if let Some(m) = cap.get(1) {+ let cand = m.as_str().trim();+ if is_actionable_plugin_ref(cand) {+ refs.insert(cand.to_string());+ }+ }+ }+ }+ }+ // 「Failed to load plugins」错误卡片:紧随其后的若干行通常是包名。+ for m in Regex::new(r"(?m)^Failed to load plugins\s*$")+ .expect("literal")+ .find_iter(text)+ {+ let rest = &text[m.end()..];+ for line in rest.lines().take(12) {+ let cand = line.trim().trim_end_matches(['.', ',', ' ']);+ if is_actionable_plugin_ref(cand) {+ refs.insert(cand.to_string());+ }+ }+ }+ refs.into_iter().collect()+}++/// 抽取「重复 loader entry id」。+pub(super) fn extract_duplicate_loader_entry(text: &str) -> Option<String> {+ let re = Regex::new(r#"duplicate loader entry id:\s*["']?([^"'\s]+)["']?"#).ok()?;+ re.captures(text)+ .and_then(|c| c.get(1))+ .map(|m| m.as_str().trim().to_string())+}++/// 抽取「界面槽位冲突」的槽位名。+pub(super) fn extract_slot_conflict(text: &str) -> Option<String> {+ let re = Regex::new(r#"single slot\s+["']([^"']+)["']\s+already has a registration"#).ok()?;+ if let Some(c) = re.captures(text) {+ return c.get(1).map(|m| m.as_str().trim().to_string());+ }+ let re = Regex::new(r#"UI slot\s+["']([^"']+)["']\s+has duplicate registrations"#).ok()?;+ re.captures(text)+ .and_then(|c| c.get(1))+ .map(|m| m.as_str().trim().to_string())+}++/// 对日志文本分类失败原因,返回(判别键, 动态详情)。+pub(super) fn classify_reason(text: &str) -> (String, String) {+ let dup_route = Regex::new(r#"duplicate prefix route\s+["']([^"']+)["']"#).expect("literal");+ if let Some(c) = dup_route.captures(text) {+ let route = c.get(1).map(|m| m.as_str().to_string()).unwrap_or_default();+ return ("duplicate_route".into(), route);+ }+ if let Some(entry) = extract_duplicate_loader_entry(text) {+ return ("duplicate_loader_entry".into(), entry);+ }+ if let Some(re) = Regex::new(r#"cannot resolve profile bundle\s+["']?([^"'\n]+)["']?"#).ok() {+ if let Some(c) = re.captures(text) {+ return (+ "cannot_resolve_bundle".into(),+ c.get(1).map(|m| m.as_str().to_string()).unwrap_or_default(),+ );+ }+ }+ if text.contains("declares no dsh.bundle") {+ let pkg = extract_plugin_refs(text)+ .into_iter()+ .next()+ .unwrap_or_default();+ return ("no_dsh_bundle".into(), pkg);+ }+ if let Some(slot) = extract_slot_conflict(text) {+ return ("slot_conflict".into(), slot);+ }+ if text.contains("failed to import loader entry")+ || text.contains("failed to apply loader entry")+ {+ return ("load_failed".into(), String::new());+ }+ ("unknown".into(), String::new())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn extract_refs_from_failure_log() {+ let log = r#"+[stderr] failed to apply loader entry dshSidebarApi (@omdsh-dev/dsh-better-sidebar)+[stderr] cannot resolve profile bundle "dsh-web-ui-all"+"#;+ let refs = extract_plugin_refs(log);+ assert!(refs.contains(&"@omdsh-dev/dsh-better-sidebar".to_string()));+ assert!(refs.contains(&"dsh-web-ui-all".to_string()));+ }++ #[test]+ fn extract_refs_from_boot_card() {+ let log = "Failed to load plugins\ndsh-better-sidebar\n@scope/another\nAn unknown error occurred\n";+ let refs = extract_plugin_refs(log);+ assert!(refs.contains(&"dsh-better-sidebar".to_string()));+ assert!(refs.contains(&"@scope/another".to_string()));+ // 非包名行不应被当作插件引用+ assert!(!refs.iter().any(|r| r.contains("unknown")));+ }++ #[test]+ fn extract_duplicate_and_slot() {+ let route_log = r#"duplicate prefix route "/sidebar/api""#;+ assert_eq!(classify_reason(route_log).0, "duplicate_route");+ let entry_log = "duplicate loader entry id: \"dshSidebarApi\"";+ assert_eq!(+ extract_duplicate_loader_entry(entry_log).as_deref(),+ Some("dshSidebarApi")+ );+ let slot_log = r#"single slot "sidebar" already has a registration"#;+ assert_eq!(extract_slot_conflict(slot_log).as_deref(), Some("sidebar"));+ }+}diff --git a/src-tauri/src/service/plugin/recovery/mod.rs b/src-tauri/src/service/plugin/recovery/mod.rsnew file mode 100644index 00000000..e65760a0--- /dev/null+++ b/src-tauri/src/service/plugin/recovery/mod.rs@@ -0,0 +1,232 @@+//! 插件异常修复(recovery):启动失败 / 运行期异常时定位问题插件,并提供+//! 「卸除此插件并继续检测」的一键离线修复。+//!+//! 参考 dataelement/dsh-desktop 的插件异常修复模式(PR #94/#96):+//! - **定位**:从启动日志按错误特征提取插件引用(duplicate route / loader entry /+//! cannot resolve bundle / no dsh.bundle / slot conflict / failed to import),再+//! 按 profile `package.json` + `node_modules` 归属回配置的根插件——只有拿到确凿+//! 证据才动手,绝不瞎猜(提取见 [`extract`],归属见 [`ownership`])。+//! - **卸载**:直接改 profile 清单(`dependencies` + `dsh.profile.bundles`)、删除+//! `node_modules/<id>`、剥离 `cordis.patch.yml` 中该插件的补丁层、清掉+//! `pnpm-lock.yaml`(best-effort),保留其它插件与配置(见 [`uninstall`])。+//! 与 [`super::install`] 走 `dsh plugin` 子进程不同:本模块离线、精准,不需要网络。+//!+//! 卸载成功后由前端 `restart()` 重启并重新检测;若仍有问题,启动失败再次触发+//! 定位,形成「继续检测」循环。++use regex::Regex;+use serde::{Deserialize, Serialize};+use tauri::AppHandle;++use super::errors;++use extract::{+ classify_reason, extract_duplicate_loader_entry, extract_plugin_refs, extract_slot_conflict,+};+use ownership::resolve_recovery_plugins;+use uninstall::{remove_plugin_dir, remove_plugin_from_manifest, strip_cordis_patch_for};++// plugin 兄弟模块的再导出:子模块经 `super::` 统一从这里取。+pub(crate) use super::installed::profile_dir;++mod extract;+mod ownership;+mod uninstall;++/// 前端监听的事件名:需要弹出插件异常修复界面时推送。+pub(crate) const RECOVERY_REQUIRED_EVENT: &str = "plugin-recovery-required";++/// 真正不可被「修复卸载」删除的核心 bundle / 官方包。+///+/// `dshmarket`(插件市场)虽然列在预设清单里,但它本身是第三方插件(npm 包+/// `dshmarket`,来源 `dsh-market/dsh-market`),不是核心/官方包,必须允许用户+/// 卸载。若把它列入保护名单,用户从插件面板点「卸载」时,`dsh plugin remove`+/// 因 dshmarket 属于 in-box bundle(`pnpm remove` 不动它)会返回成功但插件仍在,+/// 桌面端又因 protection 跳过离线卸载兜底,最终「提示成功但插件仍在」。+fn is_core_package(name: &str) -> bool {+ name == "@deepseek-ai/dsh-base"+ || name == "@deepseek-ai/dsh-web-app"+ || name.starts_with("@deepseek-ai/")+}++/// 是否为合法的 npm 包名(可带 scope)。用于过滤日志里提取到的候选引用。+fn is_package_name(s: &str) -> bool {+ let s = s.trim();+ if s.is_empty() || s.contains(':') || s.chars().any(|c| c.is_whitespace()) {+ return false;+ }++ let (scope, name) = if let Some((scope, name)) = s.split_once('/') {+ // scoped 包名必须恰好只有一层 scope/name,不能把多个路径片段带入 join。+ if !s.starts_with('@') || name.is_empty() || name.contains('/') {+ return false;+ }+ (Some(scope), name)+ } else {+ if s.starts_with('@') {+ return false;+ }+ (None, s)+ };++ fn valid_component(component: &str, is_scope: bool) -> bool {+ let component = if is_scope {+ component.strip_prefix('@').unwrap_or(component)+ } else {+ component+ };+ !component.is_empty()+ && component != "."+ && component != ".."+ && !component.starts_with('.')+ && !component.ends_with('.')+ && !component.starts_with("..")+ && !component.ends_with("..")+ && component+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_')+ }++ if scope.is_some_and(|scope| !valid_component(scope, true)) {+ return false;+ }+ valid_component(name, false)+}++/// 是否是可行动的第三方插件引用(排除核心包与 @deepseek-ai 官方包)。+pub(crate) fn is_actionable_plugin_ref(s: &str) -> bool {+ is_package_name(s) && !is_core_package(s.trim())+}++/// 启动失败时前端读到的日志行(已清洗 ANSI),序列化给前端(camelCase)。+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct PluginRecoveryInfo {+ /// 定位到的插件 id(npm 包名),可能为空(未定位到具体插件)+ pub plugins: Vec<String>,+ /// 失败原因判别键:duplicate_route / duplicate_loader_entry / cannot_resolve_bundle /+ /// no_dsh_bundle / slot_conflict / load_failed / runtime / unknown+ pub reason: String,+ /// 动态详情(如冲突的路由 / 槽位 / 服务组件 id),用于 I18n 插值+ pub detail: String,+ /// 原始错误信息(技术详情查看)+ pub raw_error: String,+}++/// 定位启动失败的问题插件:给定日志行,返回恢复信息(未定位到则 plugins 为空)。+pub fn detect(app_handle: &AppHandle, log_lines: &[String]) -> PluginRecoveryInfo {+ let text = log_lines.join("\n");+ let refs = extract_plugin_refs(&text);+ let duplicate_entry = extract_duplicate_loader_entry(&text);+ let slot_conflict = extract_slot_conflict(&text);+ let (reason, detail) = classify_reason(&text);+ let plugins = resolve_recovery_plugins(+ app_handle,+ &refs,+ duplicate_entry.as_deref(),+ slot_conflict.as_deref(),+ );+ let raw_error = refs_text(&text);+ PluginRecoveryInfo {+ plugins,+ reason,+ detail,+ raw_error,+ }+}++/// 原始错误描述:尽量取关键错误行,供「查看技术详情」。+fn refs_text(text: &str) -> String {+ // 从日志里搜出带错误标记的行(最多 8 行),没有则取尾部。+ let marker_any =+ Regex::new(r"(?i)error|duplicate|fatal|panic|throw|failed|exception|✖").expect("literal");+ let mut err_lines: Vec<&str> = text+ .lines()+ .filter(|l| marker_any.is_match(l))+ .map(|l| l.trim())+ .filter(|l| !l.is_empty())+ .collect();+ if err_lines.is_empty() {+ let tail: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();+ let start = tail.len().saturating_sub(8);+ err_lines = tail[start..].to_vec();+ }+ let joined = err_lines.join("\n");+ joined.chars().take(2000).collect()+}++/// 修复模式卸载:精准删除指定插件(离线、不破坏其它插件)。+pub fn uninstall(app_handle: &AppHandle, id: &str) -> Result<(), String> {+ if !is_actionable_plugin_ref(id) {+ return Err(format!(+ "PLUGIN_RECOVERY_REFUSED: refusing to remove core/official package {id}"+ ));+ }+ let profile = profile_dir(app_handle);+ let manifest_path = profile.join("package.json");+ if !manifest_path.exists() {+ return Err("PLUGIN_RECOVERY_NO_MANIFEST: profile package.json missing".to_string());+ }+ let content = std::fs::read_to_string(&manifest_path)+ .map_err(|e| format!("PLUGIN_RECOVERY_READ: {e}"))?;+ let mut manifest: serde_json::Value =+ serde_json::from_str(&content).map_err(|e| format!("PLUGIN_RECOVERY_PARSE: {e}"))?;++ let modified = remove_plugin_from_manifest(&mut manifest, id);+ if modified {+ let rendered = serde_json::to_string_pretty(&manifest)+ .map_err(|e| format!("PLUGIN_RECOVERY_RENDER: {e}"))?;+ std::fs::write(&manifest_path, format!("{rendered}\n"))+ .map_err(|e| format!("PLUGIN_RECOVERY_WRITE: {e}"))?;+ log::info!("Recovery uninstall removed plugin {id} from profile manifest");+ }++ remove_plugin_dir(&profile, id);+ strip_cordis_patch_for(&profile, id);+ // 清掉 lockfile,让 pnpm 重装时重建干净依赖图(best-effort)。+ if let Err(e) = std::fs::remove_file(profile.join("pnpm-lock.yaml")) {+ if e.kind() != std::io::ErrorKind::NotFound {+ log::warn!("failed to remove pnpm-lock.yaml during recovery: {e}");+ }+ }+ if let Err(e) = errors::clear(app_handle, id) {+ log::warn!("failed to clear plugin error for {id} during recovery: {e}");+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn package_name_validation() {+ assert!(is_package_name("dshmarket"));+ assert!(is_package_name("@scope/pkg"));+ assert!(is_package_name("dsh-better-sidebar"));+ assert!(!is_package_name(""));+ assert!(!is_package_name("has space"));+ assert!(!is_package_name("with:colon"));+ assert!(!is_package_name("@bare"));+ assert!(!is_package_name("foo/../../target"));+ assert!(!is_package_name("@scope/../../target"));+ assert!(!is_package_name("@scope/pkg/extra"));+ assert!(!is_package_name(r"foo\..\target"));+ assert!(!is_package_name(r"@scope\pkg"));+ assert!(!is_package_name("@scope/@pkg"));+ assert!(!is_package_name("@scope/.."));+ assert!(!is_package_name("@scope/."));+ assert!(!is_package_name(".pnpm"));+ assert!(!is_package_name(".hidden"));+ assert!(!is_package_name("foo."));+ assert!(!is_package_name("@.scope/pkg"));+ assert!(!is_package_name("@scope/.hidden"));+ assert!(!is_package_name("@scope/foo."));+ assert!(is_package_name("foo.bar"));+ assert!(is_package_name("@scope/pkg.name"));+ assert!(!is_actionable_plugin_ref("@deepseek-ai/dsh-base"));+ // dshmarket 是第三方市场插件,可卸载(不应被当作核心保护包)+ assert!(is_actionable_plugin_ref("dshmarket"));+ assert!(is_actionable_plugin_ref("dsh-better-sidebar"));+ }+}diff --git a/src-tauri/src/service/plugin/recovery/ownership.rs b/src-tauri/src/service/plugin/recovery/ownership.rsnew file mode 100644index 00000000..2dcda94e--- /dev/null+++ b/src-tauri/src/service/plugin/recovery/ownership.rs@@ -0,0 +1,312 @@+//! 归属:把日志里提取到的引用映射回 profile 配置的根插件——只有拿到确凿的+//! 一对一证据才返回,绝不瞎猜。++use regex::Regex;+use std::collections::HashSet;+use std::fs;+use std::path::Path;+use tauri::AppHandle;++use super::is_actionable_plugin_ref;+use super::is_package_name;+use super::profile_dir;++/// 读取 role 包自身的 package.json,返回一个轻量视图。+#[derive(Default)]+struct PluginMeta {+ deps: Vec<String>,+ optional_deps: Vec<String>,+ patch_path: Option<String>,+}++fn read_plugin_meta(dir: &Path) -> Option<PluginMeta> {+ let content = fs::read_to_string(dir.join("package.json")).ok()?;+ let v: serde_json::Value = serde_json::from_str(&content).ok()?;+ let mut meta = PluginMeta::default();+ if let Some(deps) = v.get("dependencies").and_then(|d| d.as_object()) {+ meta.deps = deps.keys().cloned().collect();+ }+ if let Some(deps) = v.get("optionalDependencies").and_then(|d| d.as_object()) {+ meta.optional_deps = deps.keys().cloned().collect();+ }+ meta.patch_path = v+ .get("dsh")+ .and_then(|d| d.get("bundle"))+ .and_then(|b| b.get("patch"))+ .and_then(|p| p.as_str())+ .map(String::from);+ Some(meta)+}++/// 从档案清单提取启动时会加载的第三方根插件。+///+/// 不能要求插件同时存在于 `dependencies`:卸载中断或旧版 CLI 可能只删掉依赖,+/// 却把 bundle 留在清单中;这正会触发 `cannot resolve profile bundle`,也正是恢复+/// 流程需要识别并清理的损坏状态。+fn configured_root_bundles(manifest: &serde_json::Value) -> Vec<String> {+ manifest+ .get("dsh")+ .and_then(|d| d.get("profile"))+ .and_then(|p| p.get("bundles"))+ .and_then(|b| b.as_array())+ .map(|bundles| {+ bundles+ .iter()+ .filter_map(|bundle| bundle.as_str())+ .filter(|bundle| is_actionable_plugin_ref(bundle))+ .map(String::from)+ .collect()+ })+ .unwrap_or_default()+}++/// 当前档案配置的根插件:以 `dsh.profile.bundles` 为准,因为只有 bundles 会随+/// 启动加载并导致 profile bundle 解析失败。+fn configured_roots(app_handle: &AppHandle) -> Vec<String> {+ let dir = profile_dir(app_handle);+ let content = match fs::read_to_string(dir.join("package.json")) {+ Ok(c) => c,+ Err(_) => return Vec::new(),+ };+ let v: serde_json::Value = match serde_json::from_str(&content) {+ Ok(v) => v,+ Err(_) => return Vec::new(),+ };+ configured_root_bundles(&v)+}++/// 判断某个根 bundle 是否「拥有」被报告的子包:其依赖里直接声明了该子包,或其+/// patch 层里引用该包名。+fn bundle_owns_package(profile: &Path, bundle: &str, package: &str) -> bool {+ let dir = profile.join("node_modules").join(bundle);+ let Some(meta) = read_plugin_meta(&dir) else {+ return false;+ };+ if meta.deps.iter().any(|d| d == package) || meta.optional_deps.iter().any(|d| d == package) {+ return true;+ }+ if let Some(patch) = &meta.patch_path {+ if let Ok(content) = fs::read_to_string(dir.join(patch)) {+ return content.contains(package);+ }+ }+ false+}++/// 判断某个根插件的运行时代码/依赖是否引用了给定包集合之一(用于「动态创建官方+/// UI 包」的归属)。+fn plugin_references_packages(profile: &Path, plugin: &str, packages: &HashSet<String>) -> bool {+ let dir = profile.join("node_modules").join(plugin);+ if let Some(meta) = read_plugin_meta(&dir) {+ if meta+ .deps+ .iter()+ .chain(meta.optional_deps.iter())+ .any(|d| packages.contains(d))+ {+ return true;+ }+ }+ for file in [+ "cordis.patch.yml",+ "index.js",+ "lib/index.js",+ "dist/index.js",+ ] {+ if let Ok(content) = fs::read_to_string(dir.join(file)) {+ if packages.iter().any(|p| content.contains(p)) {+ return true;+ }+ }+ }+ false+}++/// 判断某个根插件的 patch 层是否声明了重复的 loader entry id。+fn plugin_declares_loader_entry(profile: &Path, plugin: &str, entry_id: &str) -> bool {+ let dir = profile.join("node_modules").join(plugin);+ let Some(meta) = read_plugin_meta(&dir) else {+ return false;+ };+ let Some(patch) = &meta.patch_path else {+ return false;+ };+ let Ok(content) = fs::read_to_string(dir.join(patch)) else {+ return false;+ };+ let re = Regex::new(&format!(+ r#"^\s*-\s+id:\s*["']?{}["']?(?:\s*(?:#.*)?)?$"#,+ regex::escape(entry_id)+ ))+ .ok();+ re.map(|re| re.is_match(&content)).unwrap_or(false)+}++/// 判断某个根插件的文件是否包含给定槽位名。+fn plugin_matches_slot(profile: &Path, plugin: &str, slot: &str) -> bool {+ let dir = profile.join("node_modules").join(plugin);+ for file in [+ "cordis.patch.yml",+ "client.js",+ "lib/client.js",+ "dist/client.js",+ "package.json",+ "index.js",+ "lib/index.js",+ "dist/index.js",+ ] {+ if let Ok(content) = fs::read_to_string(dir.join(file)) {+ if content.contains(slot) {+ return true;+ }+ }+ }+ false+}++/// 提供某槽位的官方 UI 客户端包(用于槽位冲突归属)。+fn packages_providing_slot(profile: &Path, slot: &str) -> Vec<String> {+ let scope = profile.join("node_modules").join("@deepseek-ai");+ let Ok(entries) = fs::read_dir(&scope) else {+ return Vec::new();+ };+ let mut out = Vec::new();+ for entry in entries.flatten() {+ let name = entry.file_name().to_string_lossy().into_owned();+ if !name.starts_with("dsh-client-ui-") {+ continue;+ }+ let package = format!("@deepseek-ai/{name}");+ let dir = entry.path();+ for file in ["client.js", "lib/client.js", "dist/client.js"] {+ if let Ok(content) = fs::read_to_string(dir.join(file)) {+ if content.contains(slot) {+ out.push(package);+ break;+ }+ }+ }+ }+ out+}++/// 把日志提取到的引用归属回 profile 配置的根插件;只在一对一(证据唯一)时返回,+/// 否则返回空(绝不瞎猜)。+pub(super) fn resolve_recovery_plugins(+ app_handle: &AppHandle,+ detected_refs: &[String],+ duplicate_entry: Option<&str>,+ slot_conflict: Option<&str>,+) -> Vec<String> {+ let profile = profile_dir(app_handle);+ let roots = configured_roots(app_handle);+ if roots.is_empty() {+ return Vec::new();+ }+ let roots_set: HashSet<&String> = roots.iter().collect();++ // 1) 直接命中,或证明某报告子包被唯一根插件拥有。+ let mut matched = HashSet::new();+ for detected in detected_refs {+ if !is_package_name(detected) {+ continue;+ }+ if roots_set.contains(detected) {+ matched.insert(detected.clone());+ continue;+ }+ let owners: Vec<&String> = roots+ .iter()+ .filter(|root| bundle_owns_package(&profile, root, detected))+ .collect();+ if owners.len() == 1 {+ matched.insert(owners[0].clone());+ }+ }+ if matched.len() == 1 {+ return matched.into_iter().collect();+ }++ // 1b) 兜底:某官方叶包(loader 报错常指这个)被动态创建,归属回引用它的唯一根。+ let mut dynamic_owners = HashSet::new();+ for detected in detected_refs {+ if !is_package_name(detected) || roots_set.contains(detected) {+ continue;+ }+ let packages: HashSet<String> = [detected.to_string()].into();+ let owners: Vec<&String> = roots+ .iter()+ .filter(|root| plugin_references_packages(&profile, root, &packages))+ .collect();+ if owners.len() == 1 {+ dynamic_owners.insert(owners[0].clone());+ }+ }+ if dynamic_owners.len() == 1 {+ return dynamic_owners.into_iter().collect();+ }++ // 2) 重复 loader entry:命中唯一根插件。+ if let Some(entry) = duplicate_entry {+ let owners: Vec<&String> = roots+ .iter()+ .filter(|root| plugin_declares_loader_entry(&profile, root, entry))+ .collect();+ if owners.len() == 1 {+ return owners.into_iter().map(|s| s.clone()).collect();+ }+ }++ // 3) 槽位冲突:命中唯一根插件;否则找提供槽位的官方包,再由唯一根引用它。+ if let Some(slot) = slot_conflict {+ let matched: Vec<&String> = roots+ .iter()+ .filter(|root| plugin_matches_slot(&profile, root, slot))+ .collect();+ if matched.len() == 1 {+ return matched.into_iter().map(|s| s.clone()).collect();+ }+ let providers: HashSet<String> = packages_providing_slot(&profile, slot)+ .into_iter()+ .collect();+ if !providers.is_empty() {+ let owners: Vec<&String> = roots+ .iter()+ .filter(|root| plugin_references_packages(&profile, root, &providers))+ .collect();+ if owners.len() == 1 {+ return owners.into_iter().map(|s| s.clone()).collect();+ }+ }+ }++ Vec::new()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn configured_roots_include_bundle_left_after_dependency_removal() {+ let manifest = serde_json::json!({+ "name": "dsh-profile-web",+ "private": true,+ "dependencies": {},+ "dsh": {+ "profile": {+ "bundles": [+ "@deepseek-ai/dsh-base",+ "@deepseek-ai/dsh-web-app",+ "@linxin666/dsh-web-ui-all"+ ]+ }+ }+ });++ assert_eq!(+ configured_root_bundles(&manifest),+ vec!["@linxin666/dsh-web-ui-all"]+ );+ }+}diff --git a/src-tauri/src/service/plugin/recovery/uninstall.rs b/src-tauri/src/service/plugin/recovery/uninstall.rsnew file mode 100644index 00000000..eebdcb1d--- /dev/null+++ b/src-tauri/src/service/plugin/recovery/uninstall.rs@@ -0,0 +1,287 @@+//! 离线卸载(直接改 profile 清单):从 manifest 移除依赖与 bundle 引用、+//! 删除 `node_modules/<id>` 入口(含 scoped 空目录清理与路径逃逸防护)、+//! 剥离 `cordis.patch.yml` 中目标插件的 patch 条目。++use std::fs;+#[cfg(windows)]+use std::os::windows::fs::FileTypeExt;+use std::path::Path;++use crate::service::fs_guard;++/// 从 manifest 中移除指定插件(`dependencies` + `dsh.profile.bundles`),返回是否有改动。+pub(super) fn remove_plugin_from_manifest(manifest: &mut serde_json::Value, id: &str) -> bool {+ let mut modified = false;+ if let Some(deps) = manifest+ .get_mut("dependencies")+ .and_then(|d| d.as_object_mut())+ {+ if deps.remove(id).is_some() {+ modified = true;+ }+ }+ if let Some(bundles) = manifest+ .get_mut("dsh")+ .and_then(|d| d.get_mut("profile"))+ .and_then(|p| p.get_mut("bundles"))+ .and_then(|b| b.as_array_mut())+ {+ let before = bundles.len();+ bundles.retain(|b| b.as_str() != Some(id));+ if bundles.len() != before {+ modified = true;+ }+ }+ modified+}++/// 删除插件入口:符号链接或 junction 只删除入口本身,普通目录递归删除。+fn remove_plugin_entry(entry: &Path) -> std::io::Result<()> {+ let file_type = fs::symlink_metadata(entry)?.file_type();+ #[cfg(windows)]+ if file_type.is_symlink_dir() {+ return fs::remove_dir(entry);+ }+ if file_type.is_symlink() {+ return fs::remove_file(entry);+ }+ fs::remove_dir_all(entry)+}++/// 删除 `node_modules/<id>`;scoped 目录删除后若 scope 空则一并清理。+pub(super) fn remove_plugin_dir(profile: &Path, id: &str) {+ let node_modules = profile.join("node_modules");+ let Ok(node_modules_root) = fs_guard::ensure_within(&node_modules, profile) else {+ log::warn!(+ "refusing to remove plugin from node_modules outside profile: {}",+ node_modules.display()+ );+ return;+ };+ let entry = node_modules.join(id);+ let Ok(entry_metadata) = fs::symlink_metadata(&entry) else {+ return;+ };+ let entry_is_dangling_symlink = entry_metadata.file_type().is_symlink() && !entry.exists();+ if entry_is_dangling_symlink {+ // 悬空链接无法规范化目标,只验证父目录,确保删除的仍是 node_modules 内入口。+ let Some(parent) = entry.parent() else {+ return;+ };+ if let Err(e) = fs_guard::ensure_within(parent, &node_modules_root) {+ log::warn!(+ "refusing to remove dangling plugin symlink outside node_modules: {} ({e})",+ entry.display()+ );+ return;+ }+ } else if let Err(e) = fs_guard::ensure_within(&entry, &node_modules_root) {+ log::warn!(+ "refusing to remove plugin outside node_modules: {} ({e})",+ entry.display()+ );+ return;+ }+ if let Err(e) = remove_plugin_entry(&entry) {+ if e.kind() != std::io::ErrorKind::NotFound {+ log::warn!("failed to remove plugin dir {}: {e}", entry.display());+ }+ }+ if let Some(scope) = id+ .starts_with('@')+ .then(|| id.split('/').next().unwrap_or_default())+ {+ if !scope.is_empty() && scope != id {+ let scope_entry = node_modules.join(scope);+ if scope_entry.is_dir()+ && scope_entry+ .read_dir()+ .map(|mut d| d.next().is_none())+ .unwrap_or(false)+ {+ if fs_guard::ensure_within(&scope_entry, &node_modules_root).is_ok() {+ let _ = remove_plugin_entry(&scope_entry);+ }+ }+ }+ }+}++/// 从 `cordis.patch.yml` 中剥离目标插件的 patch 条目(保留其它插件的 patch)。+///+/// 与 dsh-desktop「直接重置为 []」不同:这里只移除与目标插件相关的条目,不破坏+/// 其它插件的配置层,符合「其它插件不会被删除」的承诺。解析失败则原样保留。+pub(super) fn strip_cordis_patch_for(profile: &Path, id: &str) {+ let path = profile.join("cordis.patch.yml");+ let Ok(content) = fs::read_to_string(&path) else {+ return;+ };+ let Ok(doc) = serde_yaml::from_str::<serde_yaml::Value>(&content) else {+ return;+ };+ let Some(entries) = doc.as_sequence() else {+ return;+ };+ let kept: Vec<serde_yaml::Value> = entries+ .iter()+ .filter(|e| !patch_entry_targets(e, id))+ .cloned()+ .collect();+ if kept.len() == entries.len() {+ return;+ }+ if let Ok(rendered) = serde_yaml::to_string(&serde_yaml::Value::Sequence(kept)) {+ let _ = fs::write(&path, rendered);+ log::info!("Stripped cordis.patch.yml entries for plugin {id}");+ }+}++/// 一个 patch 条目是否「针对」目标插件:顶层 id 字段或任意字段值等于该包名。+fn patch_entry_targets(entry: &serde_yaml::Value, id: &str) -> bool {+ match entry {+ serde_yaml::Value::Mapping(map) => map+ .iter()+ .any(|(k, v)| k.as_str() == Some(id) || v.as_str() == Some(id)),+ serde_yaml::Value::String(s) => s == id,+ _ => false,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn remove_plugin_dir_rejects_path_escape() {+ let root = std::env::temp_dir().join(format!("dsh-plugin-recovery-{}", std::process::id()));+ let profile = root.join("profile");+ std::fs::create_dir_all(profile.join("node_modules/foo")).unwrap();+ let outside = profile.join("target");+ std::fs::create_dir_all(&outside).unwrap();++ remove_plugin_dir(&profile, "foo/../../target");++ assert!(outside.exists(), "path traversal target must remain");+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn remove_plugin_dir_removes_valid_plugin() {+ let root =+ std::env::temp_dir().join(format!("dsh-plugin-recovery-valid-{}", std::process::id()));+ let profile = root.join("profile");+ let plugin = profile.join("node_modules/dsh-example");+ std::fs::create_dir_all(&plugin).unwrap();+ std::fs::write(plugin.join("index.js"), "module.exports = {};").unwrap();++ remove_plugin_dir(&profile, "dsh-example");++ assert!(!plugin.exists(), "valid plugin directory should be removed");+ let _ = std::fs::remove_dir_all(root);+ }++ #[cfg(unix)]+ #[test]+ fn remove_plugin_dir_removes_symlink_without_target() {+ let root = std::env::temp_dir().join(format!(+ "dsh-plugin-recovery-pnpm-symlink-{}",+ std::process::id()+ ));+ let profile = root.join("profile");+ let link = profile.join("node_modules/dsh-example");+ let target = profile.join("node_modules/.pnpm/dsh-example@1/node_modules/dsh-example");+ std::fs::create_dir_all(&target).unwrap();+ std::os::unix::fs::symlink(&target, &link).unwrap();++ remove_plugin_dir(&profile, "dsh-example");++ assert!(target.exists(), "pnpm canonical target must remain");+ assert!(+ std::fs::symlink_metadata(&link).is_err(),+ "only the package symlink entry should be removed"+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[cfg(unix)]+ #[test]+ fn remove_plugin_dir_removes_dangling_symlink() {+ let root = std::env::temp_dir().join(format!(+ "dsh-plugin-recovery-dangling-symlink-{}",+ std::process::id()+ ));+ let profile = root.join("profile");+ let link = profile.join("node_modules/dsh-example");+ let missing_target = profile.join("node_modules/.pnpm/missing/dsh-example");+ std::fs::create_dir_all(link.parent().unwrap()).unwrap();+ std::os::unix::fs::symlink(&missing_target, &link).unwrap();++ remove_plugin_dir(&profile, "dsh-example");++ assert!(+ std::fs::symlink_metadata(&link).is_err(),+ "dangling plugin symlink entry should be removed"+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[cfg(unix)]+ #[test]+ fn remove_plugin_dir_rejects_node_modules_symlink_escape() {+ let root =+ std::env::temp_dir().join(format!("dsh-plugin-recovery-link-{}", std::process::id()));+ let profile = root.join("profile");+ let outside = root.join("outside-node-modules");+ let plugin = outside.join("dsh-example");+ std::fs::create_dir_all(&profile).unwrap();+ std::fs::create_dir_all(&plugin).unwrap();+ std::os::unix::fs::symlink(&outside, profile.join("node_modules")).unwrap();++ remove_plugin_dir(&profile, "dsh-example");++ assert!(plugin.exists(), "plugin outside profile must remain");+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn remove_plugin_from_manifest_edits_deps_and_bundles() {+ let mut manifest = serde_json::json!({+ "name": "dsh-profile-web",+ "private": true,+ "dependencies": { "dshmarker": "1.0.0", "dsh-better-sidebar": "1.0.0" },+ "dsh": { "profile": { "bundles": ["@deepseek-ai/dsh-base", "dsh-better-sidebar"] } }+ });+ let modified = remove_plugin_from_manifest(&mut manifest, "dsh-better-sidebar");+ assert!(modified);+ assert!(manifest["dependencies"].get("dsh-better-sidebar").is_none());+ assert!(manifest["dependencies"].get("dshmarker").is_some());+ assert_eq!(+ manifest["dsh"]["profile"]["bundles"]+ .as_array()+ .unwrap()+ .len(),+ 1+ );+ }++ #[test]+ fn patch_strip_targets_plugin_only() {+ let patch = serde_yaml::to_string(&serde_yaml::Value::Sequence(vec![+ serde_yaml::from_str::<serde_yaml::Value>("id: dsh-better-sidebar\nfoo: 1").unwrap(),+ serde_yaml::from_str::<serde_yaml::Value>("id: dsh-web-ui-all\nbar: 2").unwrap(),+ ]))+ .unwrap();+ let doc: serde_yaml::Value = serde_yaml::from_str(&patch).unwrap();+ let kept: Vec<serde_yaml::Value> = doc+ .as_sequence()+ .unwrap()+ .iter()+ .filter(|e| !patch_entry_targets(e, "dsh-better-sidebar"))+ .cloned()+ .collect();+ assert_eq!(kept.len(), 1);+ let kept_doc = serde_yaml::to_string(&serde_yaml::Value::Sequence(kept)).unwrap();+ assert!(kept_doc.contains("dsh-web-ui-all"));+ assert!(!kept_doc.contains("dsh-better-sidebar"));+ }+}diff --git a/src-tauri/src/service/workflow/health.rs b/src-tauri/src/service/workflow/health.rsnew file mode 100644index 00000000..8839ec57--- /dev/null+++ b/src-tauri/src/service/workflow/health.rs@@ -0,0 +1,96 @@+//! 健康检查(通过 Rust 代理,避免 WebView CORS 问题)。++use std::sync::atomic::Ordering;++use crate::config;++use super::process::{has_owned_process, LAUNCH_GUARD};+use super::utils;++/// 无持有进程时应返回给前端的探测信号。+///+/// `launch` 仍在进行(LAUNCH_GUARD 未释放)时,无持有进程是**临时**状态:`launch`+/// 已抢到守卫、尚未把持有进程登记进槽位(spawn 未完成,典型为 auto_start 与前端+/// boot 并发拉起——前端 `launch_harness` 命中“launch already in progress, skipping”+/// 后立刻来探测,此刻 `wait_for_port_release` 可能仍在等待端口回落)。若把这种+/// 临时状态当作 `HARNESS_NOT_OWNED`,前端会命中快速失败分支(`notOwned` → 立即+/// 放弃重试),表现为“首次启动超时、刷新/重试后恢复”。+///+/// 因此 `launch` 仍在进行时返回可重试的“启动中”(`HARNESS_NOT_READY`),让前端+/// 继续轮询;守卫已释放却仍无持有进程,才是真正崩溃/从未拉起(进程随后退出、槽位+/// 被监视线程清空),返回 `HARNESS_NOT_OWNED` 让前端快速失败,避免把“启动即崩溃”+/// 误判成“启动慢”而白白耗完 8 轮重试。+fn not_owned_probe_signal(launch_in_progress: bool) -> &'static str {+ if launch_in_progress {+ "HARNESS_NOT_READY: Harness service is still starting"+ } else {+ "HARNESS_NOT_OWNED: no Harness process is owned by this app"+ }+}++fn all_client_modules_ready(ready: usize, total: usize) -> bool {+ total > 0 && ready == total+}++/// 健康检查(通过 Rust 代理,避免 WebView CORS 问题)+pub async fn proxy_health_check(port: u16) -> Result<String, String> {+ if !has_owned_process() {+ 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 = utils::health_probe_plugin_urls(port);+ let total = endpoints.len();+ let mut ready = 0usize;+ let mut failures = Vec::with_capacity(total);++ for endpoint in endpoints {+ match client.get(&endpoint).send().await {+ Ok(response) => {+ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ if utils::looks_like_plugin_bundle(status.is_success(), &body) {+ ready += 1;+ continue;+ }+ let failure = format!("{endpoint} returned {status} (not a plugin bundle)");+ log::debug!("Health check failed: {failure}");+ failures.push(failure);+ }+ Err(err) => {+ log::debug!("Health check {endpoint}: {err}");+ failures.push(format!("{endpoint}: {err}"));+ }+ }+ }+ if all_client_modules_ready(ready, total) {+ return Ok(format!("healthy - {ready}/{total} client modules ready"));+ }+ Err(format!(+ "HARNESS_NOT_READY: Harness client modules are not ready ({ready}/{total} ready; {})",+ failures.join("; ")+ ))+}++#[cfg(test)]+mod tests {+ use super::*;++ /// 回归:无持有进程在“launch 仍在进行”(守卫未释放)时应返回可重试的+ /// `HARNESS_NOT_READY`,而不是把临时状态当成崩溃的 `HARNESS_NOT_OWNED` —+ /// 后者会让前端命中快速失败分支,表现为“首次启动超时、刷新/重试后恢复”。+ #[test]+ fn not_owned_is_retryable_during_launch_not_fatal() {+ // launch 仍在进行(守卫未释放):无持有进程是启动中的临时状态,前端继续轮询+ assert!(not_owned_probe_signal(true).starts_with("HARNESS_NOT_READY"));+ // 启动已结束(守卫释放)却仍无持有进程:进程已退出/从未拉起 → 快速失败+ assert!(not_owned_probe_signal(false).starts_with("HARNESS_NOT_OWNED"));+ }++ #[test]+ fn readiness_requires_every_client_module() {+ assert!(!all_client_modules_ready(1, 2));+ assert!(all_client_modules_ready(2, 2));+ assert!(!all_client_modules_ready(0, 0));+ }+}diff --git a/src-tauri/src/service/workflow/install.rs b/src-tauri/src/service/workflow/install.rsnew file mode 100644index 00000000..059e104e--- /dev/null+++ b/src-tauri/src/service/workflow/install.rs@@ -0,0 +1,214 @@+//! 安装环境(Node.js 运行时 + 打包的 Harness 发行版 + pnpm;Windows 缺失+//! 系统 Git 时再自动安装免安装 MinGit)。原 `workflow::install`。++use crate::config;+use crate::service::download;+use tauri::Manager;++use super::process::{has_owned_process, stop, terminate_stale_harness_processes};++/// 安装环境(Node.js 运行时 + 打包的 Harness 发行版 + pnpm;Windows 缺失+/// 系统 Git 时再自动安装免安装 MinGit)。+///+/// 返回是否真正落盘更新了 Harness(dsh 任务实际下载并解压);仅重装+/// Node/pnpm/Git 或全部任务被跳过时返回 false,供调用方决定是否重启页面。+pub async fn install(+ app_handle: &tauri::AppHandle,+ mut dsh_latest: Option<download::LatestDshPkg>,+) -> Result<bool, String> {+ log::info!("Starting installation process");+ // dsh 任务(index==1)实际下载解压时置 true+ let mut dsh_updated = false;++ // 安装前先停止本应用持有的 Harness 服务:运行中的 node 进程会把+ // 原生模块 DLL(如 sharp 的 libvips-42.dll)加载进内存并锁住文件,+ // 不停止的话覆盖解压必然失败(Windows os error 32)。+ // 进程归属以启动时记录的 PID 为准,不根据端口结束未知程序。+ if has_owned_process() {+ log::info!("Stopping running Harness service before installation");+ stop(app_handle.clone()).await?;+ }+ // 只停本应用持有的进程还不够:历史崩溃/强杀残留的孤儿 Harness 实例+ // (不在 .harness.pid 标记中)同样从 dependencies/dsh 启动、占用目录文件+ // 句柄,会导致更新切换目录失败(INSTALL_BACKUP_FAILED, os error 32)。+ // 按命令行路径精确清扫所有本应用 dsh 安装目录启动的进程。+ // 枚举/结束涉及 powershell 枚举与 taskkill(同步阻塞),移出 Tokio 线程。+ {+ let handle = app_handle.clone();+ tauri::async_runtime::spawn_blocking(move || {+ terminate_stale_harness_processes(&handle);+ })+ .await+ .map_err(|e| format!("STOP_FAILED: {e}"))?;+ }++ let window = app_handle+ .get_webview_window("main")+ .ok_or("Failed to get main window")?;+ log::debug!("Main window obtained");+ let mut tasks: Vec<Box<dyn download::Installable>> = vec![+ Box::new(download::Nodejs),+ Box::new(download::Dsh),+ Box::new(download::Pnpm),+ ];+ // Windows Sandbox 等空白环境没有 Git;仅 Windows 加入第 4 项,若系统 Git+ // 可真实执行则 Installable 会跳过,不重复下载也不修改系统 PATH。+ #[cfg(windows)]+ tasks.push(Box::new(download::Git));+ // 每项均有下载/解压两个阶段,按实际平台任务数计算,避免进度提前到 100%。+ let mut tracker = download::ProgressTracker::new(&window, tasks.len() * 2);+ log::info!("Task list created, {} tasks total", tasks.len());++ for (index, task) in tasks.iter().enumerate() {+ log::debug!("Processing task {}/{}", index + 1, tasks.len());+ // 已安装但版本/commit 与最新 release 不一致时强制重新下载。+ // 版本优先(与 resolve_update 的判定完全一致):dsh 的 rc 发布会复用+ // 同一 git commit(record_commit 不变),只比 commit 会把 rc.8 之于+ // rc.7 误判为"已最新"而跳过下载——日志表现为"All installation tasks+ // completed"但实际什么都没下载,重启后仍是旧版,且前端丢掉更新提示。+ let outdated = index == 1+ && dsh_latest.as_ref().is_some_and(|info| {+ let installed_version = config::get_dsh_version(app_handle);+ let latest_version = download::parse_version_from_tag(&info.tag);+ // 版本号可解析且不同 → 必须更新;版本不可解析时退回同一发布判定+ let version_differs =+ match (installed_version.as_deref(), latest_version.as_deref()) {+ (Some(a), Some(b)) => a != b,+ _ => false,+ };+ // 「同一发布」判定与 resolve_update 完全一致:记录 tag 与最新 tag+ // 相同、或记录 commit 与 release 的任一合法标识(完整 SHA / build-id)+ // 一致。限流期安装会把 build-id 写进记录,API 恢复后解析出的完整+ // SHA 与之不等但仍是同一 release,不能据此误判为过期而重下。+ version_differs+ || !download::record_matches_latest_release(+ config::get_dsh_pkg_commit(app_handle).as_deref(),+ config::get_dsh_pkg_tag(app_handle).as_deref(),+ info,+ )+ });+ if task.check_installed(app_handle) && !outdated {+ log::debug!(+ "Task {} already installed and up to date, skipping",+ index + 1+ );+ tracker.skip_phases(2);+ continue;+ }++ log::info!("Task {} not installed, starting installation", index + 1);++ // 1. 下载+ tracker.start_phase(+ "download",+ &format!(+ "{} {}",+ config::i18n::t("install.downloading"),+ task.title()+ ),+ );+ // 下载 URL 对 dsh 也是完全确定可算的(DSH_CORE_URL + 平台文件名),+ // 无需依赖 GitHub API 元数据;api.github.com 限流/被代理拦截时+ // (mac 首次启动常见)仍能拿到真实下载地址,避免整次安装被瞬时失败卡死。+ // dsh 核心默认先走 GitHub 官方直连,失败自动切换 ghfast.top 镜像兜底+ // (下载层会在界面上告知用户);其余任务保持单一官方源。+ let (urls, name) = if index == 1 {+ let urls = config::get_dsh_download_urls()?;+ let name = urls+ .first()+ .and_then(|u| u.rsplit('/').next())+ .unwrap_or("")+ .to_string();+ (urls, name)+ } else {+ let url = task.get_download_url()?;+ let name = url.rsplit('/').next().unwrap_or("").to_string();+ (vec![url], name)+ };+ // 取文件名用于解压类型判定;下载 URL 正常必含 '/',但这里不 panic,+ // 防御性兜底为空串(后续 ensure_extract 会因无法判定类型而报错返回,+ // 不再让进程崩溃)。+ log::debug!("Download URL: {}", urls.join(" -> "));+ log::debug!("File name: {}", name);+ let buffer = download::download_file_from_sources(&tracker, urls).await?;+ log::info!("Download completed, file size: {} bytes", buffer.len());+ let expected_digest = match index {+ 0 => download::fetch_node_sha256(task.get_download_url()?.as_str()).await?,+ 1 => {+ // dsh 的 SHA-256 digest 只能来自 GitHub release asset 元数据+ // (安全设计,见 dsh_INTEGRITY_UNAVAILABLE)。首次安装时该元数据+ // 可能因 api.github.com 限流/网络抖动而缺失(mac 首次启动常见,+ // issue #31),这里带退避重取,避免启动被瞬时失败卡死。+ if dsh_latest.is_none() {+ for attempt in 0..3 {+ match download::fetch_latest_dsh_pkg_info().await {+ Ok(info) => {+ dsh_latest = Some(info);+ break;+ }+ Err(e) if attempt < 2 => {+ log::warn!(+ "Retrying dsh release metadata fetch ({}/3), will retry: {}",+ attempt + 1,+ e+ );+ tokio::time::sleep(std::time::Duration::from_millis(+ 500 * (attempt as u64 + 1),+ ))+ .await;+ }+ Err(e) => {+ return Err(format!(+ "DSH_INTEGRITY_UNAVAILABLE: 无法获取 Harness 发行版的完整性校验信息({}),请检查网络后重试",+ e+ ));+ }+ }+ }+ }+ dsh_latest+ .as_ref()+ .and_then(|info| info.digest.clone())+ .ok_or_else(|| {+ "DSH_INTEGRITY_UNAVAILABLE: trusted release digest is required".to_string()+ })?+ }+ 2 => config::PNPM_SHA256.to_string(),+ #[cfg(windows)]+ 3 => config::get_mingit_sha256()?.to_string(),+ _ => return Err("INSTALL_TASK_INVALID: unknown install task".to_string()),+ };+ download::verify_sha256(&buffer, &expected_digest)?;+ log::info!("Download integrity verified for task {}", index + 1);+ tracker.end_phase();++ // 2. 解压+ tracker.start_phase(+ "extract",+ &format!("{} {}", config::i18n::t("install.extracting"), task.title()),+ );+ let dest = task.get_install_path(app_handle);+ log::debug!("Installation path: {:?}", dest);+ download::ensure_extract(&tracker, name, buffer, dest).await?;+ log::info!("Extraction completed");+ tracker.end_phase();++ // 记录本次安装对应的 release tag 与 commit,供下次启动比对+ if index == 1 {+ dsh_updated = true;+ if let Some(info) = &dsh_latest {+ config::set_dsh_pkg_commit(app_handle, info.commit.clone());+ config::set_dsh_pkg_tag(app_handle, info.tag.clone());+ }+ }+ }++ log::info!("All installation tasks completed");+ tracker.update(+ 100.0,+ config::i18n::t("install.done"),+ "All tasks completed".into(),+ );++ Ok(dsh_updated)+}diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rsnew file mode 100644index 00000000..ce59b9e4--- /dev/null+++ b/src-tauri/src/service/workflow/launch.rs@@ -0,0 +1,635 @@+//! Harness 服务启动编排:`start` / `restart` / `launch`,含端口自愈+//! (避让递增 + 回落、等待释放)、`--no-open` 版本判定、补丁挂点与+//! Windows 隐藏控制台启动。++use crate::config;+use std::collections::HashMap;+#[cfg(windows)]+use std::ffi::OsString;+use std::fs;+#[cfg(not(windows))]+use std::process::{Command, Stdio};+use std::sync::atomic::Ordering;++#[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, on_owned_process_exit, stop, LaunchGuard, LAUNCH_GUARD};+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::{is_port_in_use, rotate_service_log, spawn_output_readers};+use super::win_inspector;++/// 端口释放等待上限:刚结束/清扫过上个会话的残留 dsh 进程后,TCP 端口释放+/// 存在短暂滞后(taskkill 返回 ≠ 端口已可复用)。等待窗口内端口回落为空闲则+/// 复用配置端口;到期仍未释放才按“真占用”逐级递增。+const PORT_RELEASE_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);++/// 轮询等待配置端口释放为空闲(端口本来就空闲则立即返回)。+///+/// async(tokio)实现,避免长时间阻塞启动线程。与 `stop()` 里“给系统一点时间+/// 释放端口”的目的一致,但以“端口确实空闲”为准而不是固定睡 800ms——因此+/// 端口很快释放时几乎不额外耗时,只有真占用才等到超时。+async fn wait_for_port_release(port: u16) {+ let deadline = tokio::time::Instant::now() + PORT_RELEASE_WAIT;+ while tokio::time::Instant::now() < deadline {+ if !is_port_in_use(port) {+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(80)).await;+ }+}++/// 从起始端口向上查找第一个空闲端口,绝不结束未知的端口占用进程。+fn find_available_port(start: u16) -> Result<u16, String> {+ find_available_port_by(start, is_port_in_use)+}++/// 按调用方提供的占用判定查找第一个空闲端口。+///+/// 将扫描决策与真实套接字状态分离,使单测能确定性验证递增与溢出,不在函数+/// 返回后再次探测系统端口;后者存在不可消除的 TOCTOU,任何端口段都可能被+/// 其他进程在两次探测之间占用。+fn find_available_port_by(+ start: u16,+ mut is_in_use: impl FnMut(u16) -> bool,+) -> Result<u16, String> {+ let mut port = start;+ loop {+ if !is_in_use(port) {+ return Ok(port);+ }+ log::warn!("Port {port} is occupied, trying the next port");+ port = port.checked_add(1).ok_or_else(|| {+ "PORT_EXHAUSTED: no available TCP port after the configured port".to_string()+ })?;+ }+}++/// 启动时端口自愈决策(纯函数,便于单测)。+///+/// 自动避让递增(配置端口被占 → 逐级顶高)遗留的非默认端口只在回落目标+/// (用户手动端口或默认端口)空闲时才回落;回落目标被占则维持当前端口,+/// 留给 `find_available_port` 逐级递增。用户手动设置的端口经 `manual_port`+/// 记录,回落目标即用户值;从未手动设置时回落目标是默认端口(3080/3081)。+/// 返回值与 `configured` 相同表示无需自愈。+fn resolve_heal_port(configured: u16, heal_target: u16, heal_target_free: bool) -> u16 {+ if configured != heal_target && heal_target_free {+ heal_target+ } else {+ configured+ }+}++/// dsh 版本是否支持 `--no-open` 标志。+///+/// 0.1.0-rc.8 起 `dsh web` 默认在系统浏览器打开 UI(桌面端内嵌 WebView,+/// 不希望每次启动都弹浏览器),并新增 `--no-open` 关闭该行为。更早的 rc+/// 版本没有这个标志,commander 会把未知选项当作错误、导致 web profile+/// 启动失败,因此追加标志前必须按已装版本判定:0.1.0-rc.8 及以上传标志;+/// 更早不传(保持旧行为)。+///+/// 比较用 `semver` 库按完整语义化版本进行:只比 rc 序号会把基础版本更大的+/// 新版本误判为旧版——`0.1.1-rc.1` 的 rc 号(1)虽小于 8,但晚于+/// 0.1.0-rc.8,同样支持 `--no-open`(该误判是浏览器复弹的回归根因)。+/// 版本号非法(无法解析)时保守处理:不追加标志。+fn version_supports_no_open(version: &str) -> bool {+ // 首个支持 `--no-open` 的 dsh 版本(0.1.0-rc.8)+ const NO_OPEN_MIN_VERSION: &str = "0.1.0-rc.8";+ let Ok(min) = semver::Version::parse(NO_OPEN_MIN_VERSION) else {+ return false;+ };+ semver::Version::parse(version)+ .map(|v| v >= min)+ .unwrap_or(false)+}++/// 按当前活动核心的 dsh 版本决定是否追加 `--no-open`(见 [`version_supports_no_open`])。+///+/// 版本以活动核心为准:本地核心(用户 CLI 安装)与预打包核心各自读自己的+/// 包清单;读不到时保守处理:不追加标志。+fn web_supports_no_open_flag(app_handle: &tauri::AppHandle) -> bool {+ match crate::service::core::active_version(app_handle) {+ Some(version) => version_supports_no_open(&version),+ None => false,+ }+}++/// 检测并启动 Harness 服务+pub async fn start(app_handle: tauri::AppHandle) -> Result<(), String> {+ let setting = config::get_store_dat_setting(&app_handle);+ let node_binary_path = config::get_node_binary_path(&app_handle);+ // 活动核心的入口:本地核心存在时优先本地(需求 3),否则预打包+ let dsh_binary_path = crate::service::core::active_dsh_binary(&app_handle);++ if !setting.installed {+ log::debug!("Harness not installed, skipping startup");+ return Ok(());+ }+ if !node_binary_path.exists() || !dsh_binary_path.exists() {+ // Windows RedirectionGuard(448):安装器继承的强制执行上下文永不自行恢复,+ // 先尝试通过 explorer 逃逸重拉(见 relaunch_via_shell_escape 注释),+ // 成功则本进程退出;未命中(重拉未逃逸/非 448)才走常规缺失处理。+ #[cfg(windows)]+ if dsh_bin_open_error(&app_handle) == Some(448) {+ relaunch_via_shell_escape(&app_handle);+ }+ let mut setting = config::get_store_dat_setting(&app_handle);+ setting.installed = false;+ config::set_store_dat_setting(&app_handle, setting);+ // 状态变更需要 info 级落盘:这是「store 显示未安装」的源头之一+ // (核心文件短暂缺失被复位),自更新后自动重开走进安装分支多由此触发。+ log::info!("Runtime files missing (node/dsh), resetting installed flag");+ return Ok(());+ }++ if has_owned_process() {+ log::info!("Owned Harness process is already running");+ status::set_status(status::Status::Running);+ status::emit_status(&app_handle);+ return Ok(());+ }++ // 清理 RedirectionGuard(448) 逃逸重拉标记:本进程正常走到启动说明处于干净上下文,+ // 移除标记保证下次自更新后仍能触发逃逸重拉。+ #[cfg(windows)]+ let _ = std::fs::remove_file(relaunch_marker_path(&app_handle));++ log::info!("Starting Harness service");+ status::set_status(status::Status::Starting);+ status::emit_status(&app_handle);+ launch(app_handle).await?;+ // 之后由 scheduler/task/tick_check_dsh_process/mod.rs 检测状态++ Ok(())+}++/// 重启 Harness 服务+pub async fn restart(app_handle: tauri::AppHandle) -> Result<(), String> {+ log::info!("Restarting Harness service");++ // 1. 停止现有服务+ stop(app_handle.clone()).await?;++ // 2. 重新启动+ start(app_handle).await?;++ Ok(())+}++/// 启动 Harness 服务进程+pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {+ let mut setting = config::get_store_dat_setting(&app_handle);+ let node_binary_path = config::get_node_binary_path(&app_handle);+ // 活动核心的 dsh 入口(本地核心优先,未检测到走预打包)+ let dsh_binary_path = crate::service::core::active_dsh_binary(&app_handle);++ log::debug!("Checking Node.js path: {:?}", node_binary_path);+ if !node_binary_path.exists() {+ log::error!("Node.js not installed");+ return Err("NODE_NOT_FOUND: Node.js not installed".to_string());+ }+ log::debug!("Checking Harness path: {:?}", dsh_binary_path);+ if !dsh_binary_path.exists() {+ log::error!("Harness not installed");+ return Err("HARNESS_NOT_FOUND: Harness not installed".to_string());+ }++ // 避免重复启动(配合启动守卫,确保并发调用只拉起一个进程)+ if has_owned_process() {+ log::info!("Owned Harness process is already running, skipping launch");+ return Ok(());+ }+ if LAUNCH_GUARD+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)+ .is_err()+ {+ log::info!("Harness launch already in progress, skipping");+ return Ok(());+ }+ let _launch_guard = LaunchGuard;++ // 端口自愈:自动避让递增(配置端口被占 → 逐级顶高)遗留的非默认端口,+ // 在回落目标(用户手动端口 manual_port,否则默认端口)空闲时回落,避免+ // 端口只增不减、一路从 3080 漂到 3084+(issue #91)。先于+ // wait_for_port_release 探测:既然放弃旧端口,就无需等它释放。+ let heal_target = setting.manual_port.unwrap_or(config::default_port());+ let healed_port = resolve_heal_port(setting.port, heal_target, !is_port_in_use(heal_target));+ if healed_port != setting.port {+ log::info!(+ "Harness port healed from {} back to {} (no longer occupied)",+ setting.port,+ healed_port+ );+ setting.port = healed_port;+ config::set_store_dat_setting(&app_handle, setting.clone());+ }++ // 端口冲突时从当前值开始逐个递增,并持久化最终选择供所有调用方复用。+ // 注意:上个会话的残留 dsh 进程刚被我们结束/清扫(sweep_orphan、stop、+ // stop_on_exit),TCP 端口释放存在短暂滞后——此刻立刻探测会把“刚释放的+ // 端口”误判为仍占用,从而把配置端口永久顶高(dev 热更新下 3081→3082→…+ // 一路漂移,表现为“端口持续累加 + 首次启动超时、刷新后恢复”)。先留出+ // 窗口等配置端口回落为空闲,再决定是否真的逐级递增。+ wait_for_port_release(setting.port).await;+ let available_port = find_available_port(setting.port)?;+ if available_port != setting.port {+ log::info!(+ "Harness port changed from {} to {} because the configured port is occupied",+ setting.port,+ available_port+ );+ setting.port = available_port;+ config::set_store_dat_setting(&app_handle, setting.clone());+ }++ // 构造环境变量:隔离的 $DSH_HOME + 隐私默认(关闭遥测)+ let dsh_home = config::get_dsh_data_path(&app_handle);+ fs::create_dir_all(&dsh_home).map_err(|e| format!("create dsh home failed: {e}"))?;++ // Linux 起步前探测 inotify 监视上限:harness 服务(dsh web)用 chokidar 递归+ // 监视 profile 目录,上限过低会在启动一瞬间抛 ENOSPC 直接退出(issue #116)。+ // 进程无法自我调高该参数,这里只做告警(启动日志 + 读取 run logs 中的环境信息),+ // 前端据服务日志的 ENOSPC 特征给出「调高 fs.inotify.max_user_watches」的针对性提示。+ #[cfg(unix)]+ warn_if_inotify_watch_limit_low();++ // Windows 极简模式修复的自愈:插件已装入 profile 时确保 patch 挂载行与+ // minimal-win 用户 preset 落盘(幂等)。最佳努力:失败只告警,不阻断启动。+ if let Err(e) = win_inspector::apply(&app_handle) {+ log::warn!("win32 terminal support apply failed: {e}");+ }+ // renderer 的 SlotOutlet 一行导出补丁(dsh-tauri-ui 设置侧边栏依赖):只补+ // 活动核心的 dsh-client-ui-renderer lib/client.js,已含导出即跳过(幂等;核心+ // 换版本后自动重打,上游官方导出后自动退休)。最佳努力:失败只告警,不阻断+ // 启动——未打补丁时插件侧降级,官方设置 dialog 照常工作,绝不白屏。+ if let Err(e) = crate::service::patch::renderer::apply(&app_handle) {+ log::warn!("renderer SlotOutlet patch failed: {e}");+ }+ // Expose an id-based SessionStore.remove facade so plugins can perform a+ // real in-memory teardown instead of leaving deleted sessions ungrouped.+ if let Err(e) = crate::service::patch::session::apply(&app_handle) {+ log::warn!("SessionStore.remove patch failed: {e}");+ }+ // worktree 会话以隔离 cwd 执行,但产品归属仍是源 Workspace;放宽上游显式+ // attach 的 cwd 相等约束,其他 cwd 有效性校验保持不变。最佳努力且幂等。+ if let Err(e) = crate::service::patch::workspace::apply(&app_handle) {+ log::warn!("workspace worktree membership patch failed: {e}");+ }+ // 当前 DSH client-HMR 会卸载第三方插件却不重新挂载。debug 直接联接本地+ // 插件源码,故将 rebuilt 降级为自动刷新页面;release 保持上游行为。+ if let Err(e) = crate::service::patch::client_hmr::apply(&app_handle) {+ log::warn!("debug client plugin reload fallback patch failed: {e}");+ }+ // 预防性处理:pnpm 在无 TTY 环境(dsh-market 等子进程)下重装/更新插件时,+ // 清理/重建 node_modules 会触发交互确认并因无 TTY 直接中止+ // (ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY),表现为插件更新失败。+ // 启动时确保 profile 的 .npmrc 写入 confirmModulesPurge=false(幂等、保留+ // 已有配置)。最佳努力:失败只告警,不阻断启动。+ if let Err(e) = crate::service::plugin::ensure_profile_npmrc(&app_handle) {+ log::warn!("ensure profile .npmrc failed: {e}");+ }+ // 弃用插件自动卸载:预设清单里带 `deprecated` 标记的社区插件若已安装,启动时+ // 自动移除(避免残留插件继续在 profile 里加载、甚至导致启动失败)。最佳努力:+ // 失败只告警,不阻断启动。+ if let Err(e) = crate::service::plugin::uninstall_deprecated_plugins(&app_handle).await {+ log::warn!("uninstall deprecated plugins failed: {e}");+ }+ // 内置插件自愈:随包分发的内置插件(dsh-tauri 等)必须在服务进程加载插件+ // 前就绪——核对「已安装 + 安装路径指向当前捆绑目录」,未安装、路径不正确+ // 或用户卸载后重启,一律强制重装(见 service::plugin::internal)。最佳+ // 努力:失败只告警,不阻断启动(核心功能缺失是发布缺陷,由 prebuild 报错)。+ if let Err(e) = crate::service::plugin::ensure_internal_plugins(&app_handle).await {+ log::warn!("ensure internal plugins failed: {e}");+ }+ // 预装插件完整性自检:清单引用的预装插件若在 node_modules 缺失产物,服务+ // 启动时 loader 会对每个缺失插件抛 ERR_MODULE_NOT_FOUND 而整体失败(issue+ // #90,日志特征 `Cannot find package`)。用 `pnpm install` 以现有 manifest ++ // lockfile 为准重建依赖图修复;修复失败只告警并给缺失插件记录错误标记+ // (启动失败场景由前端 recovery 对话框兜底,见 service::plugin::recovery)。+ if let Err(e) = crate::service::plugin::ensure_preset_plugins(&app_handle).await {+ log::warn!("ensure preset plugins failed: {e}");+ }+ let mut envs: HashMap<String, String> = HashMap::new();+ envs.insert(+ "DSH_HOME".to_string(),+ dsh_home.to_string_lossy().into_owned(),+ );+ envs.insert("DSH_TELEMETRY_DISABLED".to_string(), "1".to_string());+ envs.insert("NO_COLOR".to_string(), "1".to_string());+ envs.insert("DSH_WEB_PORT".to_string(), setting.port.to_string());+ // 把服务实际使用的 node 路径显式交给子进程(pnpm/dsh shim 的 DSH_NODE+ // 优先):市场(dsh-market)等子进程经 PATH 解析 node 可能与桌面端预检+ // 不一致(相对 PATH 条目 / junction / 子进程 PATH 布局差异),导致 pnpm+ // shim 报 "Node.js runtime not found"(issue #121,与 build_plugin_envs+ // 的注入保持一致)。先规范化为绝对路径:相对路径在子进程 CWD 下会解析+ // 到错误位置;已存在(上面校验过)的 node 可安全 canonicalize。用+ // dunce::canonicalize 而不是 std::fs::canonicalize:后者在 Windows 上会+ // 返回 `\\?\` verbatim 前缀,cmd.exe 无法直接启动这种路径,导致 pnpm/dsh+ // shim 报 "The system cannot find the path specified."。+ let node_abs =+ dunce::canonicalize(&node_binary_path).unwrap_or_else(|_| node_binary_path.clone());+ envs.insert(+ "DSH_NODE".to_string(),+ node_abs.to_string_lossy().into_owned(),+ );++ // 扩展 PATH,让 dsh 及其子进程能找到 node 与桌面端自动配置的 Git;Windows+ // 上再注入 Git Bash 的 bin 目录:persistent bash(--noprofile --norc)不执行+ // profile 脚本、PATH+ // 完全继承服务进程,若不含 Git 的 usr/bin,ls/sed/find 等 coreutils 全会+ // `command not found`(MSYS 运行时在部分环境下不会自动补 /usr/bin)。+ // 前置应用自身的 shim 目录,使市场(dsh-market)及其子进程通过名字解析的+ // `pnpm`/`dsh` 都命中桌面端 shim,从而受桌面端 pnpm 选版策略管辖+ // (轻量缓解,issue #69 系列)。+ if let Some(node_dir) = node_binary_path.parent() {+ if let Some(existing_path) = std::env::var_os("PATH") {+ let git_dirs = win_inspector::git_bash_bin_dirs();+ // 只打印注入的前缀目录,完整 PATH 太长会刷屏+ 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)];+ paths.push(node_dir.to_path_buf());+ if let Some(git_dir) = config::get_git_cmd_dir(&app_handle) {+ log::debug!(+ "harness service Git PATH prepend: {}",+ git_dir.to_string_lossy()+ );+ paths.push(git_dir);+ }+ paths.extend(git_dirs);+ paths.extend(std::env::split_paths(&existing_path));+ if let Ok(new_path) = std::env::join_paths(paths) {+ envs.insert("PATH".to_string(), new_path.to_string_lossy().into_owned());+ }+ }+ }++ // 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) {+ // 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),+ ) {+ envs.insert("DSH_PNPM".to_string(), pnpm_value);+ }+ }++ // 让市场子进程的 pnpm 与桌面端同一套受控策略(store 主版本感知、避免落到系统+ // homebrew pnpm)。与插件安装路径的 ensure_pnpm 版本感知一致,但启动阶段绝不+ // 触发下载;捆绑版未安装或与 store 不匹配时不注入(交由用户 pnpm)。+ // 最佳努力:失败只告警,不阻断启动。+ if crate::service::plugin::harness_prefer_bundled_pnpm(&app_handle) {+ envs.insert("DSH_PREFER_BUNDLED_PNPM".to_string(), "1".to_string());+ }++ // 日志文件(前端日志面板读取)。+ // 每次真实启动前轮转:只保留最近 3 次启动的日志,旧文件后退为+ // `dsh-web.log.1` / `dsh-web.log.2`,避免单文件随多次启动无限增长。+ let log_path = config::get_service_log_path(&app_handle);+ fs::create_dir_all(log_path.parent().unwrap_or(std::path::Path::new(".")))+ .map_err(|e| format!("create log dir failed: {e}"))?;+ rotate_service_log(&log_path, 3);++ // rc.8 起 `dsh web` 默认在系统浏览器打开 UI;桌面端内嵌 WebView,不需要+ // 浏览器,追加 `--no-open` 关闭(老版本无此标志时按版本判定不传)。+ let no_open = web_supports_no_open_flag(&app_handle);++ log::info!("Starting Harness process");++ // Windows 打包版是 GUI 进程(没有控制台)。直接以 CREATE_NO_WINDOW 启动+ // node 会让 dsh 派生的子进程各自新建可见控制台窗口(频繁闪烁 cmd 黑窗),+ // 因此 Windows 上改用“隐藏控制台”方式启动,见 win_spawn 模块。+ let active_profile = crate::service::profile::active_profile(&app_handle);+ let spawn_result = {+ #[cfg(windows)]+ {+ let mut args: Vec<OsString> = vec![+ dsh_binary_path.as_os_str().to_os_string(),+ OsString::from("--profile"),+ OsString::from(active_profile.as_str()),+ OsString::from("--host"),+ OsString::from("127.0.0.1"),+ OsString::from("--port"),+ OsString::from(setting.port.to_string()),+ ];+ if no_open {+ args.push(OsString::from("--no-open"));+ }+ super::win_spawn::spawn_with_hidden_console_owned(+ &node_binary_path,+ &args,+ Some(&config::get_dsh_install_path(&app_handle)),+ &envs,+ )+ .map(|(stdout, stderr, pid, handle)| {+ // PID 与句柄作为整体一次登记,与退出清理(take 一并取出)配对+ let handle_value = handle as usize;+ set_owned_process_with_handle(pid, handle_value);+ std::thread::spawn(move || unsafe {+ use windows_sys::Win32::Foundation::CloseHandle;+ use windows_sys::Win32::System::Threading::{+ GetExitCodeProcess, WaitForSingleObject, INFINITE,+ };+ let process_handle = handle_value as windows_sys::Win32::Foundation::HANDLE;+ WaitForSingleObject(process_handle, INFINITE);+ // 记录退出码:启动即崩溃(插件冲突等)时前端据此快速失败,+ // 退出码也便于诊断问题+ let mut exit_code: u32 = 0;+ if GetExitCodeProcess(process_handle, &mut exit_code) != 0 {+ log::warn!("Owned Harness process {pid} exited with code {exit_code}");+ } else {+ log::warn!("Owned Harness process {pid} exited (exit code unavailable)");+ }+ // 进程确已退出:清空持有 PID 并把 Status 从 Running 回落为+ // Stopped(原有实现只清 PID、状态永远停留在 Running)。+ // 仅当该 PID 仍是当前登记才取出——旧监视线程不会误清新进程。+ // take 返回值里的句柄由本线程负责关闭(不会与+ // terminate_owned_process 重复 close——进程已 exit,+ // 通常是本线程取走)。+ let owned = on_owned_process_exit(pid);+ if let Some(owned) = owned {+ let h = owned.handle as windows_sys::Win32::Foundation::HANDLE;+ CloseHandle(h);+ }+ });+ (Some(stdout), Some(stderr), pid)+ })+ }+ #[cfg(not(windows))]+ {+ use std::os::unix::process::CommandExt;+ let mut cmd = Command::new(&node_binary_path);+ cmd.arg(&dsh_binary_path)+ .arg("--profile")+ .arg(active_profile.as_str())+ .arg("--host")+ .arg("127.0.0.1")+ .arg("--port")+ .arg(&setting.port.to_string());+ if no_open {+ cmd.arg("--no-open");+ }+ cmd.envs(&envs)+ .current_dir(config::get_dsh_install_path(&app_handle))+ // 核心修正:提供一个空的 stdin 防止 setRawMode 报错+ .stdin(Stdio::null())+ // 使用管道捕获输出,以便在子线程中读取+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ // 独立进程组让停止操作只影响 Harness 及其后代。+ .process_group(0);+ cmd.spawn().map(|mut child| {+ let pid = child.id();+ let stdout = child.stdout.take();+ let stderr = child.stderr.take();+ set_owned_process(pid);+ std::thread::spawn(move || {+ let code = child.wait().ok().and_then(|status| status.code());+ // 记录退出码:启动即崩溃(插件冲突等)时前端据此快速失败+ if let Some(code) = code {+ log::warn!("Owned Harness process {pid} exited with code {code}");+ } else {+ log::warn!("Owned Harness process {pid} exited (no exit code)");+ }+ // 进程确已退出:清空持有 PID 并把 Status 从 Running 回落为 Stopped+ // (Unix 无进程句柄可关闭,忽略返回的进程记录)。+ // 仅当该 PID 仍是当前登记才取出——旧监视线程不会误清新进程。+ let _ = on_owned_process_exit(pid);+ });+ (stdout, stderr, pid)+ })+ }+ };++ 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}"))+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::net::TcpListener;++ #[test]+ fn occupied_port_advances_to_a_free_port() {+ let mut checked = Vec::new();+ let selected = find_available_port_by(3080, |port| {+ checked.push(port);+ port < 3082+ })+ .expect("find next free port");++ assert_eq!(selected, 3082);+ assert_eq!(checked, vec![3080, 3081, 3082]);+ }++ #[test]+ fn occupied_port_reports_exhaustion_at_max_port() {+ let error = find_available_port_by(u16::MAX, |_| true).expect_err("port exhaustion");+ assert!(error.starts_with("PORT_EXHAUSTED:"));+ }++ /// 模拟“上个会话残留进程刚被杀、端口仍在释放”的场景:先占用端口,随后在+ /// 另一线程释放。验证 `wait_for_port_release` 在端口回落后立即返回,而不是+ /// 等到完整等待窗口——这正是避免端口永久顶高(dev 热更新下 3081→3082→…)+ /// 的关键行为。+ #[tokio::test]+ async fn wait_for_port_release_returns_shortly_after_port_is_released() {+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind held test port");+ let held = listener.local_addr().expect("read held port").port();++ // 端口此刻确实被占用(模拟残留进程仍在监听)+ assert!(is_port_in_use(held));+ let releaser = std::thread::spawn(move || {+ std::thread::sleep(std::time::Duration::from_millis(150));+ drop(listener);+ });++ let started = std::time::Instant::now();+ wait_for_port_release(held).await;+ // 端口 150ms 后释放 + 80ms 轮询间隔,应远小于 1.5s 等待上限+ assert!(+ started.elapsed() < std::time::Duration::from_millis(800),+ "wait_for_port_release should return shortly after the port is released, not wait the full window"+ );+ releaser.join().expect("port releaser thread");+ }++ #[test]+ fn no_open_supported_on_rc8_and_later() {+ assert!(version_supports_no_open("0.1.0-rc.8"));+ assert!(version_supports_no_open("0.1.0-rc.9"));+ // 基础版本更大的新版本:0.1.1-rc.1 的 rc 号(1)虽小于 8,但晚于+ // 0.1.0-rc.8,同样支持 --no-open(只比 rc 号会把这里误判为旧版)+ assert!(version_supports_no_open("0.1.1-rc.1"));+ assert!(version_supports_no_open("0.1.2-rc.1"));+ // 稳定版必然晚于 rc.8+ assert!(version_supports_no_open("0.1.0"));+ assert!(version_supports_no_open("0.2.0"));+ assert!(version_supports_no_open("1.0.0"));+ }++ #[test]+ fn no_open_absent_before_rc8() {+ assert!(!version_supports_no_open("0.1.0-rc.7"));+ assert!(!version_supports_no_open("0.1.0-rc.0"));+ // 基础版本更早的 rc 系列一律不支持+ assert!(!version_supports_no_open("0.0.1-rc.5"));+ assert!(!version_supports_no_open("0.0.9-rc.99"));+ }++ #[test]+ fn no_open_unknown_version_is_conservative() {+ assert!(!version_supports_no_open(""));+ // rc 号缺失:`0.1.0-rc` 的预发布 [rc] 短于 [rc, 8],判为早于 rc.8+ assert!(!version_supports_no_open("0.1.0-rc"));+ // 不完整/非法版本号(缺 patch、带 v 前缀、无 semver 结构):无法解析+ assert!(!version_supports_no_open("0.1"));+ assert!(!version_supports_no_open("v0.1.0"));+ assert!(!version_supports_no_open("not-a-version"));+ }++ /// 端口自愈(issue #91):自动避让递增遗留的非默认端口,在回落目标空闲时+ /// 回落到目标(默认端口或用户手动端口),回落目标被占时维持当前端口。+ #[test]+ fn heal_port_returns_target_when_free() {+ // 自动递增遗留 3084,默认 3080 空闲 → 回落默认端口+ assert_eq!(resolve_heal_port(3084, 3080, true), 3080);+ // 用户手动 9090 空闲 → 回落用户值+ assert_eq!(resolve_heal_port(9091, 9090, true), 9090);+ }++ #[test]+ fn heal_port_keeps_current_when_target_busy_or_aligned() {+ // 回落目标被占 → 维持当前端口(留给 find_available_port 逐级递增)+ assert_eq!(resolve_heal_port(3084, 3080, false), 3084);+ // 当前端口即回落目标(已是最优)→ 不变+ assert_eq!(resolve_heal_port(3080, 3080, true), 3080);+ assert_eq!(resolve_heal_port(3080, 3080, false), 3080);+ }+}diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rsindex 6de109d2..c10272da 100644--- a/src-tauri/src/service/workflow/mod.rs+++ b/src-tauri/src/service/workflow/mod.rs@@ -1,1626 +1,30 @@+//! Harness 服务进程生命周期编排(workflow)。+//!+//! 模块划分:+//! - [`process`]:本应用持有的 Harness 根进程登记(PID + Windows 句柄成对)、+//! 启动守卫、停止/退出回收、进程树终止与按 dsh 安装路径清扫历史残留+//! - [`launch`]:start / restart / launch 编排(端口自愈、`--no-open` 版本判定、+//! 补丁挂点、Windows 隐藏控制台启动)+//! - [`sweep`]:孤儿 Harness 清扫(`.harness.pid` + 端口/PID 双重确认)与+//! Windows RedirectionGuard(448) 逃逸重拉+//! - [`install`]:安装环境(Node.js 运行时 + Harness 发行版 + pnpm + MinGit)+//! - [`health`]:健康检查(Rust 代理,避免 WebView CORS 问题)+//! - [`status`] / [`utils`] / [`win_inspector`] / [`win_spawn`]:既有子模块+pub mod status;pub mod utils;pub(crate) mod win_inspector;#[cfg(windows)]pub(crate) mod win_spawn;-use crate::config;-use crate::service::download;-use crate::service::workflow::utils::{is_port_in_use, spawn_output_readers};-use std::collections::HashMap;--#[cfg(windows)]-use std::ffi::OsString;-use std::fs;-use std::process::{Command, Stdio};-use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{Mutex, OnceLock};-use tauri::Manager;--/// 启动守卫:并发调用 `launch` 时只允许一个真正拉起 dsh 进程-static LAUNCH_GUARD: AtomicBool = AtomicBool::new(false);--/// 当前进程内由桌面端创建的 Harness 根进程(PID + Windows 句柄)。-///-/// PID 与句柄装在同一把锁的可选值里:`take()` 一次性成对取出,保证-/// 「PID 清空」与「句柄关闭」之间不存在跨原子竞态(WARN-6)。历史上 PID/句柄-/// 分两个 `Atomic*` 存储,`stop` 读 PID 与监视线程清句柄之间有微窗口可能导致-/// 漏杀或重复 close。-#[derive(Clone, Copy)]-struct OwnedProcess {- pid: u32,- /// Windows 进程句柄(原始 HANDLE 转 usize 存储,避免 `*mut c_void` 非 Send)。- /// 只在 Windows 存在;Unix 无句柄概念。- #[cfg(windows)]- handle: usize,-}--fn owned_process_lock() -> &'static Mutex<Option<OwnedProcess>> {- static OWNED_PROCESS: OnceLock<Mutex<Option<OwnedProcess>>> = OnceLock::new();- OWNED_PROCESS.get_or_init(|| Mutex::new(None))-}--/// 记录新持有的 Harness 根进程(Unix,启动成功后调用)。-#[cfg(not(windows))]-fn set_owned_process(pid: u32) {- let mut guard = owned_process_lock()- .lock()- .unwrap_or_else(|e| e.into_inner());- *guard = Some(OwnedProcess { pid });-}--/// 若调用方 owns 该进程(Windows 额外存句柄),记录之。-#[cfg(windows)]-fn set_owned_process_with_handle(pid: u32, handle: usize) {- let mut guard = owned_process_lock()- .lock()- .unwrap_or_else(|e| e.into_inner());- *guard = Some(OwnedProcess { pid, handle });-}--/// 原子取出持有的进程(PID+句柄一起)。Whoever takes it is responsible for-/// closing the Windows handle. 无条件取出(停止/退出路径)。-fn take_owned_process() -> Option<OwnedProcess> {- owned_process_lock()- .lock()- .unwrap_or_else(|e| e.into_inner())- .take()-}--/// 仅当当前持有进程的 PID 与 `pid` 匹配时才取出(成对 PID+句柄)。-///-/// 保留 base 代码 `compare_exchange(pid, 0)` 的防护语义:退出监视线程只能清掉-/// 属于自己那一条登记,绝不误取/误清「刚启动的新进程」的登记——否则会把它-/// 当作已退出而错误回落 Status,并把新进程的句柄误关(WARN-6 合并引入的回退)。-fn take_owned_process_if(pid: u32) -> Option<OwnedProcess> {- let mut guard = owned_process_lock()- .lock()- .unwrap_or_else(|e| e.into_inner());- take_owned_process_if_matching(&mut guard, pid)-}--/// 纯函数部分:便于单测,不触碰全局状态。-fn take_owned_process_if_matching(- owned: &mut Option<OwnedProcess>,- pid: u32,-) -> Option<OwnedProcess> {- if owned.as_ref().map(|p| p.pid) == Some(pid) {- owned.take()- } else {- None- }-}--struct LaunchGuard;--impl Drop for LaunchGuard {- fn drop(&mut self) {- LAUNCH_GUARD.store(false, Ordering::SeqCst);- }-}--/// 端口释放等待上限:刚结束/清扫过上个会话的残留 dsh 进程后,TCP 端口释放-/// 存在短暂滞后(taskkill 返回 ≠ 端口已可复用)。等待窗口内端口回落为空闲则-/// 复用配置端口;到期仍未释放才按“真占用”逐级递增。-const PORT_RELEASE_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);--/// 轮询等待配置端口释放为空闲(端口本来就空闲则立即返回)。-///-/// async(tokio)实现,避免长时间阻塞启动线程。与 `stop()` 里“给系统一点时间-/// 释放端口”的目的一致,但以“端口确实空闲”为准而不是固定睡 800ms——因此-/// 端口很快释放时几乎不额外耗时,只有真占用才等到超时。-async fn wait_for_port_release(port: u16) {- let deadline = tokio::time::Instant::now() + PORT_RELEASE_WAIT;- while tokio::time::Instant::now() < deadline {- if !is_port_in_use(port) {- return;- }- tokio::time::sleep(std::time::Duration::from_millis(80)).await;- }-}--/// 从起始端口向上查找第一个空闲端口,绝不结束未知的端口占用进程。-fn find_available_port(start: u16) -> Result<u16, String> {- find_available_port_by(start, is_port_in_use)-}--/// 按调用方提供的占用判定查找第一个空闲端口。-///-/// 将扫描决策与真实套接字状态分离,使单测能确定性验证递增与溢出,不在函数-/// 返回后再次探测系统端口;后者存在不可消除的 TOCTOU,任何端口段都可能被-/// 其他进程在两次探测之间占用。-fn find_available_port_by(- start: u16,- mut is_in_use: impl FnMut(u16) -> bool,-) -> Result<u16, String> {- let mut port = start;- loop {- if !is_in_use(port) {- return Ok(port);- }- log::warn!("Port {port} is occupied, trying the next port");- port = port.checked_add(1).ok_or_else(|| {- "PORT_EXHAUSTED: no available TCP port after the configured port".to_string()- })?;- }-}--/// 启动时端口自愈决策(纯函数,便于单测)。-///-/// 自动避让递增(配置端口被占 → 逐级顶高)遗留的非默认端口只在回落目标-/// (用户手动端口或默认端口)空闲时才回落;回落目标被占则维持当前端口,-/// 留给 `find_available_port` 逐级递增。用户手动设置的端口经 `manual_port`-/// 记录,回落目标即用户值;从未手动设置时回落目标是默认端口(3080/3081)。-/// 返回值与 `configured` 相同表示无需自愈。-fn resolve_heal_port(configured: u16, heal_target: u16, heal_target_free: bool) -> u16 {- if configured != heal_target && heal_target_free {- heal_target- } else {- configured- }-}--/// dsh 版本是否支持 `--no-open` 标志。-///-/// 0.1.0-rc.8 起 `dsh web` 默认在系统浏览器打开 UI(桌面端内嵌 WebView,-/// 不希望每次启动都弹浏览器),并新增 `--no-open` 关闭该行为。更早的 rc-/// 版本没有这个标志,commander 会把未知选项当作错误、导致 web profile-/// 启动失败,因此追加标志前必须按已装版本判定:0.1.0-rc.8 及以上传标志;-/// 更早不传(保持旧行为)。-///-/// 比较用 `semver` 库按完整语义化版本进行:只比 rc 序号会把基础版本更大的-/// 新版本误判为旧版——`0.1.1-rc.1` 的 rc 号(1)虽小于 8,但晚于-/// 0.1.0-rc.8,同样支持 `--no-open`(该误判是浏览器复弹的回归根因)。-/// 版本号非法(无法解析)时保守处理:不追加标志。-fn version_supports_no_open(version: &str) -> bool {- // 首个支持 `--no-open` 的 dsh 版本(0.1.0-rc.8)- const NO_OPEN_MIN_VERSION: &str = "0.1.0-rc.8";- let Ok(min) = semver::Version::parse(NO_OPEN_MIN_VERSION) else {- return false;- };- semver::Version::parse(version)- .map(|v| v >= min)- .unwrap_or(false)-}--/// 按当前活动核心的 dsh 版本决定是否追加 `--no-open`(见 [`version_supports_no_open`])。-///-/// 版本以活动核心为准:本地核心(用户 CLI 安装)与预打包核心各自读自己的-/// 包清单;读不到时保守处理:不追加标志。-fn web_supports_no_open_flag(app_handle: &tauri::AppHandle) -> bool {- match crate::service::core::active_version(app_handle) {- Some(version) => version_supports_no_open(&version),- None => false,- }-}--/// 只结束本应用当前进程创建并仍持有的 Harness 进程树。-fn terminate_owned_process() {- // 一次性取出 PID+句柄(成对),杜绝「PID 已清空/句柄未清」的漏杀窗口- let Some(owned) = take_owned_process() else {- return;- };-- #[cfg(windows)]- {- use windows_sys::Win32::Foundation::CloseHandle;- use windows_sys::Win32::System::Threading::WaitForSingleObject;- const WAIT_TIMEOUT_CODE: u32 = 0x0000_0102;- let handle = owned.handle as windows_sys::Win32::Foundation::HANDLE;- if handle.is_null() {- return;- }- // 真实句柄已结束说明 PID 可能已复用,此时绝不调用 taskkill。- if unsafe { WaitForSingleObject(handle, 0) } != WAIT_TIMEOUT_CODE {- unsafe { CloseHandle(handle) };- return;- }- kill_pid_tree(owned.pid);- unsafe {- WaitForSingleObject(handle, 5_000);- CloseHandle(handle);- }- }-- #[cfg(unix)]- {- kill_pid_tree(owned.pid);- }-}--/// 结束进程树(Windows `taskkill /PID <pid> /T /F`;Unix 负 PID 进程组,与-/// 启动时 `process_group(0)` 对应)。调用方需先确认 PID 确实指向目标进程。-fn kill_pid_tree(pid: u32) {- #[cfg(windows)]- {- let mut cmd = Command::new("taskkill");- cmd.args(["/PID", &pid.to_string(), "/T", "/F"]);- use std::os::windows::process::CommandExt;- cmd.creation_flags(0x08000000);- cmd.stdout(Stdio::null());- cmd.stderr(Stdio::null());- if let Err(e) = cmd.output() {- log::error!("Failed to stop Harness process tree {pid}: {e}");- }- }-- #[cfg(unix)]- {- // Harness 根进程启动在独立进程组中,负 PID 只作用于该进程树;手动通过- // CLI 拉起的外围 dsh 进程未必有独立进程组(组信号报错),此时回退直接- // 杀 PID——PID 的归属已由调用方确认(路径匹配或 .harness.pid 双重确认),- // 绝不会误杀未知进程。- let group = format!("-{pid}");- let group_term_ok = Command::new("kill")- .args(["-TERM", "--", &group])- .output()- .map(|output| output.status.success())- .unwrap_or(false);- if !group_term_ok {- let _ = Command::new("kill")- .args(["-TERM", "--", &pid.to_string()])- .output();- }- std::thread::sleep(std::time::Duration::from_millis(300));- let group_kill_ok = Command::new("kill")- .args(["-KILL", "--", &group])- .output()- .map(|output| output.status.success())- .unwrap_or(false);- if !group_kill_ok {- let _ = Command::new("kill")- .args(["-KILL", "--", &pid.to_string()])- .output();- }- }-}--/// 解析 `ps -axo pid=,command=` 的一行:返回 `(PID, 命令行)`。-///-/// 输出形如 ` 12345 node /path/to/bin.js --profile web ...`(PID 前可能有-/// 前导空格、行尾有换行)。PID 缺失或不可解析的行返回 None(跳过该行)。-#[cfg_attr(windows, allow(dead_code))] // 仅 Unix 清场分支与测试使用-fn parse_ps_line(line: &str) -> Option<(u32, &str)> {- let trimmed = line.trim_start();- let split = trimmed.find(|c: char| c.is_whitespace())?;- let pid = trimmed[..split].trim().parse::<u32>().ok()?;- Some((pid, trimmed[split..].trim_start()))-}--/// 判断命令行中是否包含一个完整参数。-///-/// `ps` 会把 argv 用空格拼成命令行,但不会给本身含空格的参数补引号,因此不能-/// 用 `split_whitespace` 还原参数。改为在原始命令行中匹配完整字符串,并校验-/// 前后为空白或行边界;这样 macOS 的 `Library/Application Support` 路径也能-/// 正确识别,同时不会把路径前缀相似的其他参数误判为目标。-#[cfg_attr(windows, allow(dead_code))] // 仅 Unix 清场分支与测试使用-fn command_line_has_argument(cmdline: &str, argument: &str) -> bool {- if argument.is_empty() {- return false;- }-- cmdline.match_indices(argument).any(|(start, matched)| {- let before_is_boundary = cmdline[..start]- .chars()- .next_back()- .map_or(true, char::is_whitespace);- let end = start + matched.len();- let after_is_boundary = cmdline[end..]- .chars()- .next()- .map_or(true, char::is_whitespace);- before_is_boundary && after_is_boundary- })-}--/// 判断命令行是否为「从本应用 dsh 安装目录启动的 Harness 服务」。-///-/// 除入口路径外同时核对桌面端服务启动参数,避免清扫时误伤用户并行执行的-/// `dsh plugin` 等短命令。-#[cfg_attr(windows, allow(dead_code))] // 仅 Unix 清场分支与测试使用-fn is_harness_command_line(cmdline: &str, dsh_bin: &str) -> bool {- command_line_has_argument(cmdline, dsh_bin)- && command_line_has_argument(cmdline, "--host")- && command_line_has_argument(cmdline, "127.0.0.1")- && command_line_has_argument(cmdline, "--port")-}--pub fn has_owned_process() -> bool {- owned_process_lock()- .lock()- .map(|g| g.is_some())- .unwrap_or(false)-}--/// 处理「持有的 dsh 进程退出」这一事实(由退出监视线程与健康检查 tick 共用):-///-/// - 仅当退出的 PID 仍是当前登记的那个进程时才清空持有(`take_owned_process_if`-/// 按 pid 匹配),PID/句柄作为整体成对取出——杜绝「读 PID」与「清句柄」-/// 之间的跨原子竞态(WARN-6),也杜绝旧监视线程误清新启动进程的登记;-/// - 若当前状态仍是 Running,回落到 Stopped——否则进程已经没了、状态却永远-/// 显示「运行中」,前端按钮/横幅会长期处于错误语义(WARN-5)。-///-/// 返回被取出的进程记录(含 Windows 句柄),取到者负责 `CloseHandle`——保证-/// 「取走进程」与「关闭句柄」同属一个调用者,杜绝重复 close。幂等:多次调用-/// (tick 与监视线程并发)只会生效一次,后续调用返回 None。-fn on_owned_process_exit(pid: u32) -> Option<OwnedProcess> {- let owned = take_owned_process_if(pid)?;-- log::warn!(- "Owned Harness process {} exited; resetting status to Stopped",- owned.pid- );-- if status::get_status() == status::Status::Running {- status::set_status(status::Status::Stopped);- }- Some(owned)-}--/// 结束所有从本应用 dsh 安装目录启动的 Harness 服务进程(含历史崩溃残留的孤儿实例)。-///-/// 只停本应用当前持有的进程不够:`.harness.pid` 标记只记录最近一次会话的 PID,-/// 应用多次崩溃/强杀(任务管理器结束等)会遗留多个孤儿 dsh 进程、端口一路漂移-/// (3080→3081→…),`sweep_orphan_harness` 每次只能回收最近一个,更早的孤儿-/// 会持续占用 `dependencies/dsh` 目录的文件句柄(node 以该目录为 cwd 且模块-/// DLL 加载在内存),更新切换目录时触发 os error 32(INSTALL_BACKUP_FAILED)。-///-/// 命令行为本应用 dsh 入口路径(`...\dependencies\dsh\node_modules\...\bin.js`)-/// 的 node 进程可判定为本应用的服务实例——路径精确匹配不会误杀用户其它 node-/// 程序,因此可安全地全部结束(taskkill /T /F)。-pub fn terminate_stale_harness_processes(app_handle: &tauri::AppHandle) {- // 开发(debug)构建不做按路径清扫:生产与开发共用同一个 `dependencies/dsh`- // 安装目录(核心共用),按命令行路径匹配会把同时运行的 release 服务进程- // 一并结束——`pnpm tauri dev` 每次后端重编译都会重启应用并触发清扫,导致- // "release 版 DSH 被 dev 版热更新杀掉"。开发构建自身的崩溃残留仍由- // `.harness.pid` 标记(位于独立数据目录 `.dsh.dev`,PID+端口双重确认)- // 精确回收。- if cfg!(debug_assertions) {- return;- }- #[cfg(windows)]- {- use std::os::windows::process::CommandExt;- let dsh_bin_path = config::get_dsh_binary_path(app_handle);- let Some(dsh_bin) = dsh_bin_path.to_str() else {- return;- };- // 进程名过滤保证 PowerShell 自身(其命令行同样包含该路径)不被误杀;- // 路径中的单引号按 PS 字符串字面量规则转义,避免用户目录含 `'` 时语法错误。- let escaped = dsh_bin.replace('\'', "''");- let script = format!(- "Get-CimInstance Win32_Process -Filter \"Name = 'node.exe'\" | Where-Object {{ $_.CommandLine -like '*{escaped}*' }} | Select-Object -ExpandProperty ProcessId"- );- let Ok(output) = Command::new("powershell")- .args(["-NoProfile", "-NonInteractive", "-Command", &script])- .creation_flags(0x08000000)- .output()- else {- log::error!("Failed to enumerate stale Harness service processes");- return;- };- let mut found = 0;- for line in String::from_utf8_lossy(&output.stdout).lines() {- let Ok(pid) = line.trim().parse::<u32>() else {- continue;- };- found += 1;- log::warn!("Terminating stale Harness service process {pid} (from dsh install dir)");- kill_pid_tree(pid);- }- if found > 0 {- // 与 stop() 同理:taskkill 返回后 DLL 句柄的释放还有短暂滞后,- // 让出一点时间避免紧随其后的目录切换撞上残留锁。- std::thread::sleep(std::time::Duration::from_millis(800));- }- }- #[cfg(not(windows))]- {- // Unix 同样需要按路径清扫:打开中的文件允许重命名确实不阻塞更新切换,- // 但崩溃/强杀残留的孤儿 dsh 实例会持续监听端口,下一次启动只能一路- // 漂移端口(3080→3081→…)并被持久化,表现为「更新后端口递增」- // (issue #91)。用 `ps -ww -axo pid=,command=` 枚举完整命令行(`-ww`- // 防止 macOS 按终端宽度截断长路径),按参数边界匹配本应用 dsh 入口与- // 服务参数,不会误杀用户其它 node/dsh 命令,因此可安全地全部结束。- let dsh_bin = config::get_dsh_binary_path(app_handle);- let Some(dsh_bin_str) = dsh_bin.to_str() else {- return;- };- let Ok(output) = Command::new("ps")- .args(["-ww", "-axo", "pid=,command="])- .output()- else {- log::error!("Failed to enumerate stale Harness service processes");- return;- };- let mut found = 0;- for line in String::from_utf8_lossy(&output.stdout).lines() {- let Some((pid, cmdline)) = parse_ps_line(line) else {- continue;- };- if !is_harness_command_line(cmdline, dsh_bin_str) {- continue;- }- found += 1;- log::warn!("Terminating stale Harness service process {pid} (from dsh install dir)");- kill_pid_tree(pid);- }- if found > 0 {- // 与 stop() 同理:信号发完后 PID 回收与端口释放还有短暂滞后,- // 让出一点时间避免紧随其后的启动探测撞上尚未释放的端口。- std::thread::sleep(std::time::Duration::from_millis(800));- }- }-}--#[cfg(unix)]-pub(crate) fn warn_if_inotify_watch_limit_low() {- let Some(limit) = crate::config::linux_inotify_max_user_watches() else {- return;- };- if limit < crate::config::MIN_INOTIFY_MAX_USER_WATCHES {- log::warn!(- "Linux inotify.max_user_watches is {} (below recommended {}); dsh web may crash with ENOSPC (issue #116). To fix, run `sudo sysctl fs.inotify.max_user_watches={}` and write the same value to /etc/sysctl.conf to persist.",- limit,- crate::config::MIN_INOTIFY_MAX_USER_WATCHES,- crate::config::MIN_INOTIFY_MAX_USER_WATCHES,- );- }-}--// ----------------------------------------------------------------------------// 孤儿 Harness 清扫:崩溃/强杀残留实例的识别与回收(issue #34 关联现象)-// -----------------------------------------------------------------------------/// 孤儿清扫用的 PID/端口标记文件路径($DSH_HOME/.harness.pid,两行:PID、端口)。-///-/// 应用被强杀(崩溃、任务管理器结束等)时无法执行退出清理,其 Harness 子进程-/// 会继续占用端口;下一次启动只能一路漂移端口(3080→3081→…)并触发服务端-/// "already running",表现为应用"坏掉"。启动前据此文件识别并清理这类残留。-fn harness_pid_path(app_handle: &tauri::AppHandle) -> std::path::PathBuf {- config::get_dsh_data_path(app_handle).join(".harness.pid")-}--/// 记录本次启动的 Harness PID 与端口,供下次启动清扫孤儿用。-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。端口与 PID 双重确认后才动手:-/// - 标记进程已死 → 仅清理陈旧标记;-/// - 端口占用者正是标记中的 PID → 本应用残留,结束其进程树并清标记;-/// - 其余情况(标记不可解析、端口被其他程序占用、无法探测占用者)一律不动,-/// 绝不凭端口猜进程、绝不杀未知进程。-pub fn sweep_orphan_harness(app_handle: &tauri::AppHandle) {- if has_owned_process() {- return;- }- // 先按命令行路径清扫所有从本应用 dsh 安装目录启动的孤儿 Harness 实例:- // 标记文件只记录最近一次会话的 PID,应用多次崩溃/强杀会遗留更早的孤儿- // (端口一路漂移 3081/3082/…),它们持续占用 dependencies/dsh 目录的文件- // 句柄,导致更新切换目录失败(INSTALL_BACKUP_FAILED, os error 32)。- // 路径精确匹配不会误杀用户其它 node 程序;标记中的进程若在其中会被一并- // 结束,随后的 PID/端口双重确认自然落空,仅清理陈旧标记。- terminate_stale_harness_processes(app_handle);- let pid_file = harness_pid_path(app_handle);- let Ok(text) = fs::read_to_string(&pid_file) else {- return;- };- let mut lines = text.lines();- let (Some(pid), Some(port)) = (- lines.next().and_then(|l| l.trim().parse::<u32>().ok()),- lines.next().and_then(|l| l.trim().parse::<u16>().ok()),- ) else {- // 标记内容不可解析:陈旧垃圾,清掉即可- let _ = fs::remove_file(&pid_file);- return;- };- if !is_port_in_use(port) {- // 端口已释放:残留实例早已自行退出,仅清理标记- let _ = fs::remove_file(&pid_file);- return;- }- if port_owner_pid(port) != Some(pid) {- // 端口占用者不是我们落盘的进程(或探测不到):可能是其他程序,不动- return;- }- log::warn!("Sweeping orphaned Harness process {pid} (port {port}) left by a previous session");- kill_pid_tree(pid);- let _ = fs::remove_file(&pid_file);-}--/// 占用指定端口的进程 PID(LISTENING 状态)。-/// - Windows:`netstat -ano` 解析;-/// - Unix:`lsof -ti tcp:<port>`,不可用时返回 None。-/// 返回 None 视为"无法确认",调用方不会因此杀任何进程。-fn port_owner_pid(port: u16) -> Option<u32> {- #[cfg(windows)]- {- // 打包版是 GUI 进程(无控制台):netstat 是控制台子系统程序,直接运行会- // 新建一个可见的黑色 cmd 窗口(启动时的孤儿清扫会走到这里)。必须- // CREATE_NO_WINDOW,否则每次启动闪一个黑窗。- use std::os::windows::process::CommandExt;- let output = Command::new("netstat")- .arg("-ano")- .creation_flags(0x08000000)- .output()- .ok()?;- let text = String::from_utf8_lossy(&output.stdout);- let needle = format!(":{port} ");- for line in text.lines() {- let fields: Vec<&str> = line.split_whitespace().collect();- if fields.len() < 5 || fields[0] != "TCP" {- continue;- }- // 本地地址列(如 127.0.0.1:3080 / [::1]:3080)以 :<port> 结尾- if !fields[1].ends_with(&needle) {- continue;- }- if fields[3] == "LISTENING" {- return fields[4].parse().ok();- }- }- None- }- #[cfg(not(windows))]- {- // lsof 在 macOS 默认可用、Linux 常缺失;缺失时跳过清扫(返回 None)- let output = Command::new("lsof")- .args(["-ti", &format!("tcp:{port}")])- .output()- .ok()?;- if !output.status.success() {- return None;- }- String::from_utf8_lossy(&output.stdout)- .lines()- .next()- .and_then(|l| l.trim().parse().ok())- }-}--/// Windows RedirectionGuard(错误码 448 = ERROR_UNTRUSTED_MOUNT_POINT)逃逸重拉的标记路径。-fn relaunch_marker_path(app_handle: &tauri::AppHandle) -> std::path::PathBuf {- config::get_base_dir(app_handle).join(".dsh-relaunch-448")-}--/// 探测 dsh 入口在当前进程上下文下的打开错误码(None=可打开)。-///-/// 448 只在「进程继承 RedirectionGuard 强制执行」时出现;干净上下文(父进程为-/// explorer 等普通进程)下 Level-1 符号链接可正常穿越。-fn dsh_bin_open_error(app_handle: &tauri::AppHandle) -> Option<i32> {- std::fs::File::open(config::get_dsh_binary_path(app_handle))- .err()- .and_then(|e| e.raw_os_error())-}--/// 通过 explorer 转交启动请求,脱离 RedirectionGuard 强制执行上下文后退出本进程。-///-/// Windows 11 25H2 的 RedirectionGuard 对「非提权进程创建的符号链接/联接点」盖信任章,-/// 而安装器(msiexec/RestartManager 自动重开)会在自身进程启用强制执行并随进程树继承,-/// 导致新实例跨越 pnpm 符号链接链打开 bin.js 时持续报 448——实测与等待时长无关、-/// 永不自行恢复(issue #35)。应用无法在运行时关闭继承的策略,只能脱离被污染的进程树:-/// 把启动请求转交给 explorer(单实例壳进程,干净上下文),由 explorer 创建新实例,-/// 其父进程即 explorer,不再继承强制执行(实测:explorer.exe <exe> 的子进程父进程为-/// explorer.exe,而非转交发起者)。标记文件用于防死循环:若上次重拉未逃逸-/// (explorer 未运行等),本次回退到常规缺失处理(复位 installed 走安装流程)。-#[cfg(windows)]-fn relaunch_via_shell_escape(app_handle: &tauri::AppHandle) {- let marker = relaunch_marker_path(app_handle);- if marker.exists() {- let _ = std::fs::remove_file(&marker);- log::warn!("RedirectionGuard(448) relaunch did not escape, falling back to normal missing handling");- return;- }- let _ = std::fs::write(&marker, b"1");- let Ok(exe) = std::env::current_exe() else {- log::warn!("RedirectionGuard(448) detected but current_exe unavailable, falling back");- return;- };- match std::process::Command::new("explorer.exe").arg(&exe).spawn() {- Ok(_) => {- log::warn!(- "RedirectionGuard(448) detected, relaunching via explorer to escape enforced context: {}",- exe.display()- );- // 短暂让出后退出,避免与新实例产生单实例冲突- std::thread::sleep(std::time::Duration::from_millis(300));- std::process::exit(0);- }- Err(e) => {- log::warn!(- "RedirectionGuard(448) detected but explorer spawn failed ({e}), falling back"- );- }- }-}--/// 检测并启动 Harness 服务-pub async fn start(app_handle: tauri::AppHandle) -> Result<(), String> {- let setting = config::get_store_dat_setting(&app_handle);- let node_binary_path = config::get_node_binary_path(&app_handle);- // 活动核心的入口:本地核心存在时优先本地(需求 3),否则预打包- let dsh_binary_path = crate::service::core::active_dsh_binary(&app_handle);-- if !setting.installed {- log::debug!("Harness not installed, skipping startup");- return Ok(());- }- if !node_binary_path.exists() || !dsh_binary_path.exists() {- // Windows RedirectionGuard(448):安装器继承的强制执行上下文永不自行恢复,- // 先尝试通过 explorer 逃逸重拉(见 relaunch_via_shell_escape 注释),- // 成功则本进程退出;未命中(重拉未逃逸/非 448)才走常规缺失处理。- #[cfg(windows)]- if dsh_bin_open_error(&app_handle) == Some(448) {- relaunch_via_shell_escape(&app_handle);- }- let mut setting = config::get_store_dat_setting(&app_handle);- setting.installed = false;- config::set_store_dat_setting(&app_handle, setting);- // 状态变更需要 info 级落盘:这是「store 显示未安装」的源头之一- // (核心文件短暂缺失被复位),自更新后自动重开走进安装分支多由此触发。- log::info!("Runtime files missing (node/dsh), resetting installed flag");- return Ok(());- }-- if has_owned_process() {- log::info!("Owned Harness process is already running");- status::set_status(status::Status::Running);- status::emit_status(&app_handle);- return Ok(());- }-- // 清理 RedirectionGuard(448) 逃逸重拉标记:本进程正常走到启动说明处于干净上下文,- // 移除标记保证下次自更新后仍能触发逃逸重拉。- #[cfg(windows)]- let _ = std::fs::remove_file(relaunch_marker_path(&app_handle));-- log::info!("Starting Harness service");- status::set_status(status::Status::Starting);- status::emit_status(&app_handle);- launch(app_handle).await?;- // 之后由 scheduler/task/tick_check_dsh_process/mod.rs 检测状态-- Ok(())-}--/// 重启 Harness 服务-pub async fn restart(app_handle: tauri::AppHandle) -> Result<(), String> {- log::info!("Restarting Harness service");-- // 1. 停止现有服务- stop(app_handle.clone()).await?;-- // 2. 重新启动- start(app_handle).await?;-- Ok(())-}--/// 启动 Harness 服务进程-pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {- let mut setting = config::get_store_dat_setting(&app_handle);- let node_binary_path = config::get_node_binary_path(&app_handle);- // 活动核心的 dsh 入口(本地核心优先,未检测到走预打包)- let dsh_binary_path = crate::service::core::active_dsh_binary(&app_handle);-- log::debug!("Checking Node.js path: {:?}", node_binary_path);- if !node_binary_path.exists() {- log::error!("Node.js not installed");- return Err("NODE_NOT_FOUND: Node.js not installed".to_string());- }- log::debug!("Checking Harness path: {:?}", dsh_binary_path);- if !dsh_binary_path.exists() {- log::error!("Harness not installed");- return Err("HARNESS_NOT_FOUND: Harness not installed".to_string());- }-- // 避免重复启动(配合启动守卫,确保并发调用只拉起一个进程)- if has_owned_process() {- log::info!("Owned Harness process is already running, skipping launch");- return Ok(());- }- if LAUNCH_GUARD- .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)- .is_err()- {- log::info!("Harness launch already in progress, skipping");- return Ok(());- }- let _launch_guard = LaunchGuard;-- // 端口自愈:自动避让递增(配置端口被占 → 逐级顶高)遗留的非默认端口,- // 在回落目标(用户手动端口 manual_port,否则默认端口)空闲时回落,避免- // 端口只增不减、一路从 3080 漂到 3084+(issue #91)。先于- // wait_for_port_release 探测:既然放弃旧端口,就无需等它释放。- let heal_target = setting.manual_port.unwrap_or(config::default_port());- let healed_port = resolve_heal_port(setting.port, heal_target, !is_port_in_use(heal_target));- if healed_port != setting.port {- log::info!(- "Harness port healed from {} back to {} (no longer occupied)",- setting.port,- healed_port- );- setting.port = healed_port;- config::set_store_dat_setting(&app_handle, setting.clone());- }-- // 端口冲突时从当前值开始逐个递增,并持久化最终选择供所有调用方复用。- // 注意:上个会话的残留 dsh 进程刚被我们结束/清扫(sweep_orphan、stop、- // stop_on_exit),TCP 端口释放存在短暂滞后——此刻立刻探测会把“刚释放的- // 端口”误判为仍占用,从而把配置端口永久顶高(dev 热更新下 3081→3082→…- // 一路漂移,表现为“端口持续累加 + 首次启动超时、刷新后恢复”)。先留出- // 窗口等配置端口回落为空闲,再决定是否真的逐级递增。- wait_for_port_release(setting.port).await;- let available_port = find_available_port(setting.port)?;- if available_port != setting.port {- log::info!(- "Harness port changed from {} to {} because the configured port is occupied",- setting.port,- available_port- );- setting.port = available_port;- config::set_store_dat_setting(&app_handle, setting.clone());- }-- // 构造环境变量:隔离的 $DSH_HOME + 隐私默认(关闭遥测)- let dsh_home = config::get_dsh_data_path(&app_handle);- fs::create_dir_all(&dsh_home).map_err(|e| format!("create dsh home failed: {e}"))?;-- // Linux 起步前探测 inotify 监视上限:harness 服务(dsh web)用 chokidar 递归- // 监视 profile 目录,上限过低会在启动一瞬间抛 ENOSPC 直接退出(issue #116)。- // 进程无法自我调高该参数,这里只做告警(启动日志 + 读取 run logs 中的环境信息),- // 前端据服务日志的 ENOSPC 特征给出「调高 fs.inotify.max_user_watches」的针对性提示。- #[cfg(unix)]- warn_if_inotify_watch_limit_low();-- // Windows 极简模式修复的自愈:插件已装入 profile 时确保 patch 挂载行与- // minimal-win 用户 preset 落盘(幂等)。最佳努力:失败只告警,不阻断启动。- if let Err(e) = win_inspector::apply(&app_handle) {- log::warn!("win32 terminal support apply failed: {e}");- }- // renderer 的 SlotOutlet 一行导出补丁(dsh-tauri-ui 设置侧边栏依赖):只补- // 活动核心的 dsh-client-ui-renderer lib/client.js,已含导出即跳过(幂等;核心- // 换版本后自动重打,上游官方导出后自动退休)。最佳努力:失败只告警,不阻断- // 启动——未打补丁时插件侧降级,官方设置 dialog 照常工作,绝不白屏。- if let Err(e) = crate::service::patch::renderer::apply(&app_handle) {- log::warn!("renderer SlotOutlet patch failed: {e}");- }- // Expose an id-based SessionStore.remove facade so plugins can perform a- // real in-memory teardown instead of leaving deleted sessions ungrouped.- if let Err(e) = crate::service::patch::session::apply(&app_handle) {- log::warn!("SessionStore.remove patch failed: {e}");- }- // worktree 会话以隔离 cwd 执行,但产品归属仍是源 Workspace;放宽上游显式- // attach 的 cwd 相等约束,其他 cwd 有效性校验保持不变。最佳努力且幂等。- if let Err(e) = crate::service::patch::workspace::apply(&app_handle) {- log::warn!("workspace worktree membership patch failed: {e}");- }- // 当前 DSH client-HMR 会卸载第三方插件却不重新挂载。debug 直接联接本地- // 插件源码,故将 rebuilt 降级为自动刷新页面;release 保持上游行为。- if let Err(e) = crate::service::patch::client_hmr::apply(&app_handle) {- log::warn!("debug client plugin reload fallback patch failed: {e}");- }- // 预防性处理:pnpm 在无 TTY 环境(dsh-market 等子进程)下重装/更新插件时,- // 清理/重建 node_modules 会触发交互确认并因无 TTY 直接中止- // (ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY),表现为插件更新失败。- // 启动时确保 profile 的 .npmrc 写入 confirmModulesPurge=false(幂等、保留- // 已有配置)。最佳努力:失败只告警,不阻断启动。- if let Err(e) = crate::service::plugin::ensure_profile_npmrc(&app_handle) {- log::warn!("ensure profile .npmrc failed: {e}");- }- // 弃用插件自动卸载:预设清单里带 `deprecated` 标记的社区插件若已安装,启动时- // 自动移除(避免残留插件继续在 profile 里加载、甚至导致启动失败)。最佳努力:- // 失败只告警,不阻断启动。- if let Err(e) = crate::service::plugin::uninstall_deprecated_plugins(&app_handle).await {- log::warn!("uninstall deprecated plugins failed: {e}");- }- // 内置插件自愈:随包分发的内置插件(dsh-tauri 等)必须在服务进程加载插件- // 前就绪——核对「已安装 + 安装路径指向当前捆绑目录」,未安装、路径不正确- // 或用户卸载后重启,一律强制重装(见 service::plugin::internal)。最佳- // 努力:失败只告警,不阻断启动(核心功能缺失是发布缺陷,由 prebuild 报错)。- if let Err(e) = crate::service::plugin::ensure_internal_plugins(&app_handle).await {- log::warn!("ensure internal plugins failed: {e}");- }- // 预装插件完整性自检:清单引用的预装插件若在 node_modules 缺失产物,服务- // 启动时 loader 会对每个缺失插件抛 ERR_MODULE_NOT_FOUND 而整体失败(issue- // #90,日志特征 `Cannot find package`)。用 `pnpm install` 以现有 manifest +- // lockfile 为准重建依赖图修复;修复失败只告警并给缺失插件记录错误标记- // (启动失败场景由前端 recovery 对话框兜底,见 service::plugin::recovery)。- if let Err(e) = crate::service::plugin::ensure_preset_plugins(&app_handle).await {- log::warn!("ensure preset plugins failed: {e}");- }- let mut envs: HashMap<String, String> = HashMap::new();- envs.insert(- "DSH_HOME".to_string(),- dsh_home.to_string_lossy().into_owned(),- );- envs.insert("DSH_TELEMETRY_DISABLED".to_string(), "1".to_string());- envs.insert("NO_COLOR".to_string(), "1".to_string());- envs.insert("DSH_WEB_PORT".to_string(), setting.port.to_string());- // 把服务实际使用的 node 路径显式交给子进程(pnpm/dsh shim 的 DSH_NODE- // 优先):市场(dsh-market)等子进程经 PATH 解析 node 可能与桌面端预检- // 不一致(相对 PATH 条目 / junction / 子进程 PATH 布局差异),导致 pnpm- // shim 报 "Node.js runtime not found"(issue #121,与 build_plugin_envs- // 的注入保持一致)。先规范化为绝对路径:相对路径在子进程 CWD 下会解析- // 到错误位置;已存在(上面校验过)的 node 可安全 canonicalize。用- // dunce::canonicalize 而不是 std::fs::canonicalize:后者在 Windows 上会- // 返回 `\\?\` verbatim 前缀,cmd.exe 无法直接启动这种路径,导致 pnpm/dsh- // shim 报 "The system cannot find the path specified."。- let node_abs =- dunce::canonicalize(&node_binary_path).unwrap_or_else(|_| node_binary_path.clone());- envs.insert(- "DSH_NODE".to_string(),- node_abs.to_string_lossy().into_owned(),- );-- // 扩展 PATH,让 dsh 及其子进程能找到 node 与桌面端自动配置的 Git;Windows- // 上再注入 Git Bash 的 bin 目录:persistent bash(--noprofile --norc)不执行- // profile 脚本、PATH- // 完全继承服务进程,若不含 Git 的 usr/bin,ls/sed/find 等 coreutils 全会- // `command not found`(MSYS 运行时在部分环境下不会自动补 /usr/bin)。- // 前置应用自身的 shim 目录,使市场(dsh-market)及其子进程通过名字解析的- // `pnpm`/`dsh` 都命中桌面端 shim,从而受桌面端 pnpm 选版策略管辖- // (轻量缓解,issue #69 系列)。- if let Some(node_dir) = node_binary_path.parent() {- if let Some(existing_path) = std::env::var_os("PATH") {- let git_dirs = win_inspector::git_bash_bin_dirs();- // 只打印注入的前缀目录,完整 PATH 太长会刷屏- 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)];- paths.push(node_dir.to_path_buf());- if let Some(git_dir) = config::get_git_cmd_dir(&app_handle) {- log::debug!(- "harness service Git PATH prepend: {}",- git_dir.to_string_lossy()- );- paths.push(git_dir);- }- paths.extend(git_dirs);- paths.extend(std::env::split_paths(&existing_path));- if let Ok(new_path) = std::env::join_paths(paths) {- envs.insert("PATH".to_string(), new_path.to_string_lossy().into_owned());- }- }- }-- // 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) {- // 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),- ) {- envs.insert("DSH_PNPM".to_string(), pnpm_value);- }- }-- // 让市场子进程的 pnpm 与桌面端同一套受控策略(store 主版本感知、避免落到系统- // homebrew pnpm)。与插件安装路径的 ensure_pnpm 版本感知一致,但启动阶段绝不- // 触发下载;捆绑版未安装或与 store 不匹配时不注入(交由用户 pnpm)。- // 最佳努力:失败只告警,不阻断启动。- if crate::service::plugin::harness_prefer_bundled_pnpm(&app_handle) {- envs.insert("DSH_PREFER_BUNDLED_PNPM".to_string(), "1".to_string());- }-- // 日志文件(前端日志面板读取)。- // 每次真实启动前轮转:只保留最近 3 次启动的日志,旧文件后退为- // `dsh-web.log.1` / `dsh-web.log.2`,避免单文件随多次启动无限增长。- let log_path = config::get_service_log_path(&app_handle);- fs::create_dir_all(log_path.parent().unwrap_or(std::path::Path::new(".")))- .map_err(|e| format!("create log dir failed: {e}"))?;- utils::rotate_service_log(&log_path, 3);-- // rc.8 起 `dsh web` 默认在系统浏览器打开 UI;桌面端内嵌 WebView,不需要- // 浏览器,追加 `--no-open` 关闭(老版本无此标志时按版本判定不传)。- let no_open = web_supports_no_open_flag(&app_handle);-- log::info!("Starting Harness process");-- // Windows 打包版是 GUI 进程(没有控制台)。直接以 CREATE_NO_WINDOW 启动- // node 会让 dsh 派生的子进程各自新建可见控制台窗口(频繁闪烁 cmd 黑窗),- // 因此 Windows 上改用“隐藏控制台”方式启动,见 win_spawn 模块。- let active_profile = crate::service::profile::active_profile(&app_handle);- let spawn_result = {- #[cfg(windows)]- {- let mut args: Vec<OsString> = vec![- dsh_binary_path.as_os_str().to_os_string(),- OsString::from("--profile"),- OsString::from(active_profile.as_str()),- OsString::from("--host"),- OsString::from("127.0.0.1"),- OsString::from("--port"),- OsString::from(setting.port.to_string()),- ];- if no_open {- args.push(OsString::from("--no-open"));- }- win_spawn::spawn_with_hidden_console_owned(- &node_binary_path,- &args,- Some(&config::get_dsh_install_path(&app_handle)),- &envs,- )- .map(|(stdout, stderr, pid, handle)| {- // PID 与句柄作为整体一次登记,与退出清理(take 一并取出)配对- let handle_value = handle as usize;- set_owned_process_with_handle(pid, handle_value);- std::thread::spawn(move || unsafe {- use windows_sys::Win32::Foundation::CloseHandle;- use windows_sys::Win32::System::Threading::{- GetExitCodeProcess, WaitForSingleObject, INFINITE,- };- let process_handle = handle_value as windows_sys::Win32::Foundation::HANDLE;- WaitForSingleObject(process_handle, INFINITE);- // 记录退出码:启动即崩溃(插件冲突等)时前端据此快速失败,- // 退出码也便于诊断问题- let mut exit_code: u32 = 0;- if GetExitCodeProcess(process_handle, &mut exit_code) != 0 {- log::warn!("Owned Harness process {pid} exited with code {exit_code}");- } else {- log::warn!("Owned Harness process {pid} exited (exit code unavailable)");- }- // 进程确已退出:清空持有 PID 并把 Status 从 Running 回落为- // Stopped(原有实现只清 PID、状态永远停留在 Running)。- // 仅当该 PID 仍是当前登记才取出——旧监视线程不会误清新进程。- // take 返回值里的句柄由本线程负责关闭(不会与- // terminate_owned_process 重复 close——进程已 exit,- // 通常是本线程取走)。- let owned = on_owned_process_exit(pid);- if let Some(owned) = owned {- let h = owned.handle as windows_sys::Win32::Foundation::HANDLE;- CloseHandle(h);- }- });- (Some(stdout), Some(stderr), pid)- })- }- #[cfg(not(windows))]- {- use std::os::unix::process::CommandExt;- let mut cmd = Command::new(&node_binary_path);- cmd.arg(&dsh_binary_path)- .arg("--profile")- .arg(active_profile.as_str())- .arg("--host")- .arg("127.0.0.1")- .arg("--port")- .arg(&setting.port.to_string());- if no_open {- cmd.arg("--no-open");- }- cmd.envs(&envs)- .current_dir(config::get_dsh_install_path(&app_handle))- // 核心修正:提供一个空的 stdin 防止 setRawMode 报错- .stdin(Stdio::null())- // 使用管道捕获输出,以便在子线程中读取- .stdout(Stdio::piped())- .stderr(Stdio::piped())- // 独立进程组让停止操作只影响 Harness 及其后代。- .process_group(0);- cmd.spawn().map(|mut child| {- let pid = child.id();- let stdout = child.stdout.take();- let stderr = child.stderr.take();- set_owned_process(pid);- std::thread::spawn(move || {- let code = child.wait().ok().and_then(|status| status.code());- // 记录退出码:启动即崩溃(插件冲突等)时前端据此快速失败- if let Some(code) = code {- log::warn!("Owned Harness process {pid} exited with code {code}");- } else {- log::warn!("Owned Harness process {pid} exited (no exit code)");- }- // 进程确已退出:清空持有 PID 并把 Status 从 Running 回落为 Stopped- // (Unix 无进程句柄可关闭,忽略返回的进程记录)。- // 仅当该 PID 仍是当前登记才取出——旧监视线程不会误清新进程。- let _ = on_owned_process_exit(pid);- });- (stdout, stderr, pid)- })- }- };-- 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}"))- }- }-}--/// 停止 Harness 服务-pub async fn stop(app_handle: tauri::AppHandle) -> Result<(), String> {- log::info!("Stopping Harness service...");- // 重置启动守卫,确保后续 launch 可以重新拉起;仅结束持有的根进程树。- // 进程终止涉及 WaitForSingleObject(至多 5s)与 taskkill/kill 等同步阻塞- // 调用,移出 Tokio 执行线程避免卡住其他并发任务(WARN-7/P2-#20)。- LAUNCH_GUARD.store(false, Ordering::SeqCst);- tauri::async_runtime::spawn_blocking(terminate_owned_process)- .await- .map_err(|e| format!("STOP_FAILED: {e}"))?;- // 清理孤儿清扫标记:正常停止的实例不应被下次启动当作残留- let _ = fs::remove_file(harness_pid_path(&app_handle));-- // 给系统一点时间释放端口 (重要!)- tokio::time::sleep(std::time::Duration::from_millis(800)).await;-- status::set_status(status::Status::Stopped);- status::emit_status(&app_handle);- Ok(())-}--/// 应用退出时同步回收 Harness 进程。-///-/// 退出路径上不更新状态、不做异步等待,只结束当前应用持有的 Harness 进程树。-pub fn stop_on_exit(app_handle: tauri::AppHandle, _port: u16) {- terminate_owned_process();- // 正常退出路径同样清理清扫标记(崩溃路径才需要下次启动清扫)- let _ = fs::remove_file(harness_pid_path(&app_handle));-}--/// 安装环境(Node.js 运行时 + 打包的 Harness 发行版 + pnpm;Windows 缺失-/// 系统 Git 时再自动安装免安装 MinGit)。-///-/// 返回是否真正落盘更新了 Harness(dsh 任务实际下载并解压);仅重装-/// Node/pnpm/Git 或全部任务被跳过时返回 false,供调用方决定是否重启页面。-pub async fn install(- app_handle: &tauri::AppHandle,- mut dsh_latest: Option<download::LatestDshPkg>,-) -> Result<bool, String> {- log::info!("Starting installation process");- // dsh 任务(index==1)实际下载解压时置 true- let mut dsh_updated = false;-- // 安装前先停止本应用持有的 Harness 服务:运行中的 node 进程会把- // 原生模块 DLL(如 sharp 的 libvips-42.dll)加载进内存并锁住文件,- // 不停止的话覆盖解压必然失败(Windows os error 32)。- // 进程归属以启动时记录的 PID 为准,不根据端口结束未知程序。- if has_owned_process() {- log::info!("Stopping running Harness service before installation");- stop(app_handle.clone()).await?;- }- // 只停本应用持有的进程还不够:历史崩溃/强杀残留的孤儿 Harness 实例- // (不在 .harness.pid 标记中)同样从 dependencies/dsh 启动、占用目录文件- // 句柄,会导致更新切换目录失败(INSTALL_BACKUP_FAILED, os error 32)。- // 按命令行路径精确清扫所有本应用 dsh 安装目录启动的进程。- // 枚举/结束涉及 powershell 枚举与 taskkill(同步阻塞),移出 Tokio 线程。- {- let handle = app_handle.clone();- tauri::async_runtime::spawn_blocking(move || {- terminate_stale_harness_processes(&handle);- })- .await- .map_err(|e| format!("STOP_FAILED: {e}"))?;- }-- let window = app_handle- .get_webview_window("main")- .ok_or("Failed to get main window")?;- log::debug!("Main window obtained");- let mut tasks: Vec<Box<dyn download::Installable>> = vec![- Box::new(download::Nodejs),- Box::new(download::Dsh),- Box::new(download::Pnpm),- ];- // Windows Sandbox 等空白环境没有 Git;仅 Windows 加入第 4 项,若系统 Git- // 可真实执行则 Installable 会跳过,不重复下载也不修改系统 PATH。- #[cfg(windows)]- tasks.push(Box::new(download::Git));- // 每项均有下载/解压两个阶段,按实际平台任务数计算,避免进度提前到 100%。- let mut tracker = download::ProgressTracker::new(&window, tasks.len() * 2);- log::info!("Task list created, {} tasks total", tasks.len());-- for (index, task) in tasks.iter().enumerate() {- log::debug!("Processing task {}/{}", index + 1, tasks.len());- // 已安装但版本/commit 与最新 release 不一致时强制重新下载。- // 版本优先(与 resolve_update 的判定完全一致):dsh 的 rc 发布会复用- // 同一 git commit(record_commit 不变),只比 commit 会把 rc.8 之于- // rc.7 误判为"已最新"而跳过下载——日志表现为"All installation tasks- // completed"但实际什么都没下载,重启后仍是旧版,且前端丢掉更新提示。- let outdated = index == 1- && dsh_latest.as_ref().is_some_and(|info| {- let installed_version = config::get_dsh_version(app_handle);- let latest_version = download::parse_version_from_tag(&info.tag);- // 版本号可解析且不同 → 必须更新;版本不可解析时退回同一发布判定- let version_differs =- match (installed_version.as_deref(), latest_version.as_deref()) {- (Some(a), Some(b)) => a != b,- _ => false,- };- // 「同一发布」判定与 resolve_update 完全一致:记录 tag 与最新 tag- // 相同、或记录 commit 与 release 的任一合法标识(完整 SHA / build-id)- // 一致。限流期安装会把 build-id 写进记录,API 恢复后解析出的完整- // SHA 与之不等但仍是同一 release,不能据此误判为过期而重下。- version_differs- || !download::record_matches_latest_release(- config::get_dsh_pkg_commit(app_handle).as_deref(),- config::get_dsh_pkg_tag(app_handle).as_deref(),- info,- )- });- if task.check_installed(app_handle) && !outdated {- log::debug!(- "Task {} already installed and up to date, skipping",- index + 1- );- tracker.skip_phases(2);- continue;- }-- log::info!("Task {} not installed, starting installation", index + 1);-- // 1. 下载- tracker.start_phase(- "download",- &format!(- "{} {}",- config::i18n::t("install.downloading"),- task.title()- ),- );- // 下载 URL 对 dsh 也是完全确定可算的(DSH_CORE_URL + 平台文件名),- // 无需依赖 GitHub API 元数据;api.github.com 限流/被代理拦截时- // (mac 首次启动常见)仍能拿到真实下载地址,避免整次安装被瞬时失败卡死。- // dsh 核心默认先走 GitHub 官方直连,失败自动切换 ghfast.top 镜像兜底- // (下载层会在界面上告知用户);其余任务保持单一官方源。- let (urls, name) = if index == 1 {- let urls = config::get_dsh_download_urls()?;- let name = urls- .first()- .and_then(|u| u.rsplit('/').next())- .unwrap_or("")- .to_string();- (urls, name)- } else {- let url = task.get_download_url()?;- let name = url.rsplit('/').next().unwrap_or("").to_string();- (vec![url], name)- };- // 取文件名用于解压类型判定;下载 URL 正常必含 '/',但这里不 panic,- // 防御性兜底为空串(后续 ensure_extract 会因无法判定类型而报错返回,- // 不再让进程崩溃)。- log::debug!("Download URL: {}", urls.join(" -> "));- log::debug!("File name: {}", name);- let buffer = download::download_file_from_sources(&tracker, urls).await?;- log::info!("Download completed, file size: {} bytes", buffer.len());- let expected_digest = match index {- 0 => download::fetch_node_sha256(task.get_download_url()?.as_str()).await?,- 1 => {- // dsh 的 SHA-256 digest 只能来自 GitHub release asset 元数据- // (安全设计,见 dsh_INTEGRITY_UNAVAILABLE)。首次安装时该元数据- // 可能因 api.github.com 限流/网络抖动而缺失(mac 首次启动常见,- // issue #31),这里带退避重取,避免启动被瞬时失败卡死。- if dsh_latest.is_none() {- for attempt in 0..3 {- match download::fetch_latest_dsh_pkg_info().await {- Ok(info) => {- dsh_latest = Some(info);- break;- }- Err(e) if attempt < 2 => {- log::warn!(- "Retrying dsh release metadata fetch ({}/3), will retry: {}",- attempt + 1,- e- );- tokio::time::sleep(std::time::Duration::from_millis(- 500 * (attempt as u64 + 1),- ))- .await;- }- Err(e) => {- return Err(format!(- "DSH_INTEGRITY_UNAVAILABLE: 无法获取 Harness 发行版的完整性校验信息({}),请检查网络后重试",- e- ));- }- }- }- }- dsh_latest- .as_ref()- .and_then(|info| info.digest.clone())- .ok_or_else(|| {- "DSH_INTEGRITY_UNAVAILABLE: trusted release digest is required".to_string()- })?- }- 2 => config::PNPM_SHA256.to_string(),- #[cfg(windows)]- 3 => config::get_mingit_sha256()?.to_string(),- _ => return Err("INSTALL_TASK_INVALID: unknown install task".to_string()),- };- download::verify_sha256(&buffer, &expected_digest)?;- log::info!("Download integrity verified for task {}", index + 1);- tracker.end_phase();-- // 2. 解压- tracker.start_phase(- "extract",- &format!("{} {}", config::i18n::t("install.extracting"), task.title()),- );- let dest = task.get_install_path(app_handle);- log::debug!("Installation path: {:?}", dest);- download::ensure_extract(&tracker, name, buffer, dest).await?;- log::info!("Extraction completed");- tracker.end_phase();-- // 记录本次安装对应的 release tag 与 commit,供下次启动比对- if index == 1 {- dsh_updated = true;- if let Some(info) = &dsh_latest {- config::set_dsh_pkg_commit(app_handle, info.commit.clone());- config::set_dsh_pkg_tag(app_handle, info.tag.clone());- }- }- }-- log::info!("All installation tasks completed");- tracker.update(- 100.0,- config::i18n::t("install.done"),- "All tasks completed".into(),- );-- Ok(dsh_updated)-}--/// 无持有进程时应返回给前端的探测信号。-///-/// `launch` 仍在进行(LAUNCH_GUARD 未释放)时,无持有进程是**临时**状态:`launch`-/// 已抢到守卫、尚未把持有进程登记进槽位(spawn 未完成,典型为 auto_start 与前端-/// boot 并发拉起——前端 `launch_harness` 命中“launch already in progress, skipping”-/// 后立刻来探测,此刻 `wait_for_port_release` 可能仍在等待端口回落)。若把这种-/// 临时状态当作 `HARNESS_NOT_OWNED`,前端会命中快速失败分支(`notOwned` → 立即-/// 放弃重试),表现为“首次启动超时、刷新/重试后恢复”。-///-/// 因此 `launch` 仍在进行时返回可重试的“启动中”(`HARNESS_NOT_READY`),让前端-/// 继续轮询;守卫已释放却仍无持有进程,才是真正崩溃/从未拉起(进程随后退出、槽位-/// 被监视线程清空),返回 `HARNESS_NOT_OWNED` 让前端快速失败,避免把“启动即崩溃”-/// 误判成“启动慢”而白白耗完 8 轮重试。-fn not_owned_probe_signal(launch_in_progress: bool) -> &'static str {- if launch_in_progress {- "HARNESS_NOT_READY: Harness service is still starting"- } else {- "HARNESS_NOT_OWNED: no Harness process is owned by this app"- }-}--fn all_client_modules_ready(ready: usize, total: usize) -> bool {- total > 0 && ready == total-}--/// 健康检查(通过 Rust 代理,避免 WebView CORS 问题)-pub async fn proxy_health_check(port: u16) -> Result<String, String> {- if !has_owned_process() {- 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 = utils::health_probe_plugin_urls(port);- let total = endpoints.len();- let mut ready = 0usize;- let mut failures = Vec::with_capacity(total);-- for endpoint in endpoints {- match client.get(&endpoint).send().await {- Ok(response) => {- let status = response.status();- let body = response.text().await.unwrap_or_default();- if utils::looks_like_plugin_bundle(status.is_success(), &body) {- ready += 1;- continue;- }- let failure = format!("{endpoint} returned {status} (not a plugin bundle)");- log::debug!("Health check failed: {failure}");- failures.push(failure);- }- Err(err) => {- log::debug!("Health check {endpoint}: {err}");- failures.push(format!("{endpoint}: {err}"));- }- }- }- if all_client_modules_ready(ready, total) {- return Ok(format!("healthy - {ready}/{total} client modules ready"));- }- Err(format!(- "HARNESS_NOT_READY: Harness client modules are not ready ({ready}/{total} ready; {})",- failures.join("; ")- ))-}--#[cfg(test)]-mod tests {- use super::*;- use std::net::TcpListener;-- #[test]- fn occupied_port_advances_to_a_free_port() {- let mut checked = Vec::new();- let selected = find_available_port_by(3080, |port| {- checked.push(port);- port < 3082- })- .expect("find next free port");-- assert_eq!(selected, 3082);- assert_eq!(checked, vec![3080, 3081, 3082]);- }-- #[test]- fn occupied_port_reports_exhaustion_at_max_port() {- let error = find_available_port_by(u16::MAX, |_| true).expect_err("port exhaustion");- assert!(error.starts_with("PORT_EXHAUSTED:"));- }-- /// 回归:无持有进程在“launch 仍在进行”(守卫未释放)时应返回可重试的- /// `HARNESS_NOT_READY`,而不是把临时状态当成崩溃的 `HARNESS_NOT_OWNED` —- /// 后者会让前端命中快速失败分支,表现为“首次启动超时、刷新/重试后恢复”。- #[test]- fn not_owned_is_retryable_during_launch_not_fatal() {- // launch 仍在进行(守卫未释放):无持有进程是启动中的临时状态,前端继续轮询- assert!(not_owned_probe_signal(true).starts_with("HARNESS_NOT_READY"));- // 启动已结束(守卫释放)却仍无持有进程:进程已退出/从未拉起 → 快速失败- assert!(not_owned_probe_signal(false).starts_with("HARNESS_NOT_OWNED"));- }-- #[test]- fn readiness_requires_every_client_module() {- assert!(!all_client_modules_ready(1, 2));- assert!(all_client_modules_ready(2, 2));- assert!(!all_client_modules_ready(0, 0));- }-- /// 模拟“上个会话残留进程刚被杀、端口仍在释放”的场景:先占用端口,随后在- /// 另一线程释放。验证 `wait_for_port_release` 在端口回落后立即返回,而不是- /// 等到完整等待窗口——这正是避免端口永久顶高(dev 热更新下 3081→3082→…)- /// 的关键行为。- #[tokio::test]- async fn wait_for_port_release_returns_shortly_after_port_is_released() {- let listener = TcpListener::bind("127.0.0.1:0").expect("bind held test port");- let held = listener.local_addr().expect("read held port").port();-- // 端口此刻确实被占用(模拟残留进程仍在监听)- assert!(is_port_in_use(held));- let releaser = std::thread::spawn(move || {- std::thread::sleep(std::time::Duration::from_millis(150));- drop(listener);- });-- let started = std::time::Instant::now();- wait_for_port_release(held).await;- // 端口 150ms 后释放 + 80ms 轮询间隔,应远小于 1.5s 等待上限- assert!(- started.elapsed() < std::time::Duration::from_millis(800),- "wait_for_port_release should return shortly after the port is released, not wait the full window"- );- releaser.join().expect("port releaser thread");- }-- #[test]- fn no_open_supported_on_rc8_and_later() {- assert!(version_supports_no_open("0.1.0-rc.8"));- assert!(version_supports_no_open("0.1.0-rc.9"));- // 基础版本更大的新版本:0.1.1-rc.1 的 rc 号(1)虽小于 8,但晚于- // 0.1.0-rc.8,同样支持 --no-open(只比 rc 号会把这里误判为旧版)- assert!(version_supports_no_open("0.1.1-rc.1"));- assert!(version_supports_no_open("0.1.2-rc.1"));- // 稳定版必然晚于 rc.8- assert!(version_supports_no_open("0.1.0"));- assert!(version_supports_no_open("0.2.0"));- assert!(version_supports_no_open("1.0.0"));- }-- #[test]- fn no_open_absent_before_rc8() {- assert!(!version_supports_no_open("0.1.0-rc.7"));- assert!(!version_supports_no_open("0.1.0-rc.0"));- // 基础版本更早的 rc 系列一律不支持- assert!(!version_supports_no_open("0.0.1-rc.5"));- assert!(!version_supports_no_open("0.0.9-rc.99"));- }-- #[test]- fn no_open_unknown_version_is_conservative() {- assert!(!version_supports_no_open(""));- // rc 号缺失:`0.1.0-rc` 的预发布 [rc] 短于 [rc, 8],判为早于 rc.8- assert!(!version_supports_no_open("0.1.0-rc"));- // 不完整/非法版本号(缺 patch、带 v 前缀、无 semver 结构):无法解析- assert!(!version_supports_no_open("0.1"));- assert!(!version_supports_no_open("v0.1.0"));- assert!(!version_supports_no_open("not-a-version"));- }-- /// 构造一个测试用 `OwnedProcess`(跨平台处理 Windows 句柄字段)。- #[cfg(windows)]- fn test_owned(pid: u32) -> OwnedProcess {- OwnedProcess { pid, handle: 0 }- }- #[cfg(not(windows))]- fn test_owned(pid: u32) -> OwnedProcess {- OwnedProcess { pid }- }-- /// 退出监视线程只能清掉「与自己 PID 匹配」的登记,不许误清刚启动的新进程,- /// 也不许重复取出(幂等)。回归 WARN-6 合并引入的回退。- #[test]- fn owned_process_take_if_only_matches_pid() {- // 匹配的 PID 才可取出,且取走后槽清空- let mut slot = Some(test_owned(42));- let taken = take_owned_process_if_matching(&mut slot, 42);- assert_eq!(taken.map(|p| p.pid), Some(42));- assert!(slot.is_none());-- // PID 不匹配(旧进程 41 退出)时禁止取出/清空新进程(新进程 42)- let mut slot = Some(test_owned(42));- let taken = take_owned_process_if_matching(&mut slot, 41);- assert!(taken.is_none());- assert_eq!(slot.as_ref().map(|p| p.pid), Some(42));-- // 幂等:已清空后再次取出返回 None- let mut slot: Option<OwnedProcess> = None;- assert!(take_owned_process_if_matching(&mut slot, 42).is_none());- }-- /// 端口自愈(issue #91):自动避让递增遗留的非默认端口,在回落目标空闲时- /// 回落到目标(默认端口或用户手动端口),回落目标被占时维持当前端口。- #[test]- fn heal_port_returns_target_when_free() {- // 自动递增遗留 3084,默认 3080 空闲 → 回落默认端口- assert_eq!(resolve_heal_port(3084, 3080, true), 3080);- // 用户手动 9090 空闲 → 回落用户值- assert_eq!(resolve_heal_port(9091, 9090, true), 9090);- }-- #[test]- fn heal_port_keeps_current_when_target_busy_or_aligned() {- // 回落目标被占 → 维持当前端口(留给 find_available_port 逐级递增)- assert_eq!(resolve_heal_port(3084, 3080, false), 3084);- // 当前端口即回落目标(已是最优)→ 不变- assert_eq!(resolve_heal_port(3080, 3080, true), 3080);- assert_eq!(resolve_heal_port(3080, 3080, false), 3080);- }-- /// `ps -axo pid=,command=` 行解析:首列 PID,其余为命令行。- #[test]- fn parse_ps_line_extracts_pid_and_cmdline() {- // `.lines()` 迭代已去掉行尾换行- let (pid, cmdline) =- parse_ps_line(" 12345 node /path/to/bin.js --profile web").expect("parse ps line");- assert_eq!(pid, 12345);- assert_eq!(cmdline, "node /path/to/bin.js --profile web");- // 多列空白(PID 与命令之间多个空格)+ 行首空白- let (pid, cmdline) = parse_ps_line(" 67890 sh -c sleep 1").expect("parse ps line");- assert_eq!(pid, 67890);- assert_eq!(cmdline, "sh -c sleep 1");- }-- #[test]- fn parse_ps_line_skips_invalid_rows() {- // 无空白分隔(纯 PID)→ 无法取命令行,跳过- assert!(parse_ps_line("12345").is_none());- // PID 不可解析(可能是表头残留)→ 跳过- assert!(parse_ps_line("PID COMMAND").is_none());- // 空行 → 跳过- assert!(parse_ps_line("").is_none());- }-- /// 命令行匹配:argv 整词精确等于 dsh 入口路径才算本应用服务实例。- #[test]- fn harness_cmdline_matches_service_arguments() {- let bin = "/home/u/.dsh/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js";- assert!(is_harness_command_line(- &format!("node {bin} --profile web --host 127.0.0.1 --port 3083"),- bin- ));- }-- #[test]- fn harness_cmdline_matches_macos_app_data_path_with_spaces() {- let bin = "/Users/simon/Library/Application Support/io.github.hairyf.deepseek-harness-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js";- let cmdline =- format!("/opt/homebrew/bin/node {bin} --profile web --host 127.0.0.1 --port 3084");- assert!(is_harness_command_line(&cmdline, bin));- }-- #[test]- fn harness_cmdline_rejects_foreign_and_prefix_paths() {- let bin = "/home/u/.dsh/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js";- // 用户其它 node 程序- assert!(!is_harness_command_line(- "node /usr/bin/some-server.js",- bin- ));- // 路径前缀相似但不同(整词匹配,不做子串匹配)- assert!(!is_harness_command_line(- "node /home/u/.dsh/dependencies/dsh-extra/tool.js",- bin- ));- // 完整路径只是另一参数的前缀时不能命中- assert!(!is_harness_command_line(- &format!("node {bin}.backup --profile web --host 127.0.0.1 --port 3083"),- bin- ));- // 同一 dsh 入口执行插件命令时不是 Harness 服务,不能清扫- assert!(!is_harness_command_line(- &format!("node {bin} plugin list"),- bin- ));- // 路径作为另一个参数的后缀时不能命中- assert!(!is_harness_command_line(- &format!("node prefix{bin} --host 127.0.0.1 --port 3083"),- bin- ));- // 空命令行- assert!(!is_harness_command_line("", bin));- }-- /// 回归(issue #91):Unix 上 `kill_pid_tree` 对「无独立进程组」的进程- /// 必须回退到直接杀 PID——否则手动 CLI 拉起的外围 dsh 永远杀不掉,- /// 残留进程持续占用端口导致端口一路递增。- #[cfg(unix)]- #[test]- fn kill_pid_tree_falls_back_to_direct_pid_kill() {- // 子进程不设独立进程组(模拟手动拉起的外围 dsh);2 秒后自然退出,- // 若 kill_pid_tree 未能杀死它,wait 会等到 2 秒后自然退出 → 超时断言失败- let mut child = Command::new("sh")- .arg("-c")- .arg("sleep 2")- .spawn()- .expect("spawn sleep child");- let pid = child.id();- // 给子进程一点时间进入 sleep,确保信号发到的是 sleep 而非刚 fork 的 sh- std::thread::sleep(std::time::Duration::from_millis(200));- let started = std::time::Instant::now();- kill_pid_tree(pid);- let status = child.wait().expect("wait for child");- assert!(- started.elapsed() < std::time::Duration::from_millis(1500),- "child should have been killed by kill_pid_tree, not waited for natural exit"- );- // 被信号杀死:success() 为 false(SIGTERM 143 / SIGKILL 137)- assert!(!status.success());- }-- /// 正常路径:根进程在独立进程组中(与启动时 `process_group(0)` 对应),- /// 负 PID 组信号应能结束整个进程树。- #[cfg(unix)]- #[test]- fn kill_pid_tree_kills_process_group() {- use std::os::unix::process::CommandExt;- let mut child = Command::new("sh")- .arg("-c")- .arg("sleep 2")- .process_group(0)- .spawn()- .expect("spawn group child");- let pid = child.id();- std::thread::sleep(std::time::Duration::from_millis(200));- let started = std::time::Instant::now();- kill_pid_tree(pid);- let status = child.wait().expect("wait for group child");- assert!(started.elapsed() < std::time::Duration::from_millis(1500));- assert!(!status.success());- }-}+mod health;+mod install;+mod launch;+mod process;+mod sweep;++pub use health::proxy_health_check;+pub use install::install;+pub use launch::{launch, restart, start};+pub use process::{has_owned_process, stop, stop_on_exit};+pub use sweep::sweep_orphan_harness;diff --git a/src-tauri/src/service/workflow/process.rs b/src-tauri/src/service/workflow/process.rsnew file mode 100644index 00000000..5ac7f708--- /dev/null+++ b/src-tauri/src/service/workflow/process.rs@@ -0,0 +1,558 @@+//! Harness 进程生命周期:本应用持有的根进程登记(PID + Windows 句柄成对存储)、+//! 启动守卫、进程树终止与退出状态回落,以及按 dsh 安装路径清扫历史残留的+//! 孤儿服务实例(release 构建;debug 由 `.harness.pid` 标记精确回收)。++use crate::config;+use std::fs;+use std::process::Command;+#[cfg(windows)]+use std::process::Stdio;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Mutex, OnceLock};++use super::status;+use super::sweep::harness_pid_path;++/// 启动守卫:并发调用 `launch` 时只允许一个真正拉起 dsh 进程+pub(crate) static LAUNCH_GUARD: AtomicBool = AtomicBool::new(false);++/// 当前进程内由桌面端创建的 Harness 根进程(PID + Windows 句柄)。+///+/// PID 与句柄装在同一把锁的可选值里:`take()` 一次性成对取出,保证+/// 「PID 清空」与「句柄关闭」之间不存在跨原子竞态(WARN-6)。历史上 PID/句柄+/// 分两个 `Atomic*` 存储,`stop` 读 PID 与监视线程清句柄之间有微窗口可能导致+/// 漏杀或重复 close。+#[derive(Clone, Copy)]+pub(super) struct OwnedProcess {+ pub(super) pid: u32,+ /// Windows 进程句柄(原始 HANDLE 转 usize 存储,避免 `*mut c_void` 非 Send)。+ /// 只在 Windows 存在;Unix 无句柄概念。+ #[cfg(windows)]+ pub(super) handle: usize,+}++fn owned_process_lock() -> &'static Mutex<Option<OwnedProcess>> {+ static OWNED_PROCESS: OnceLock<Mutex<Option<OwnedProcess>>> = OnceLock::new();+ OWNED_PROCESS.get_or_init(|| Mutex::new(None))+}++/// 记录新持有的 Harness 根进程(Unix,启动成功后调用)。+#[cfg(not(windows))]+pub(super) fn set_owned_process(pid: u32) {+ let mut guard = owned_process_lock()+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ *guard = Some(OwnedProcess { pid });+}++/// 若调用方 owns 该进程(Windows 额外存句柄),记录之。+#[cfg(windows)]+pub(super) fn set_owned_process_with_handle(pid: u32, handle: usize) {+ let mut guard = owned_process_lock()+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ *guard = Some(OwnedProcess { pid, handle });+}++/// 原子取出持有的进程(PID+句柄一起)。Whoever takes it is responsible for+/// closing the Windows handle. 无条件取出(停止/退出路径)。+fn take_owned_process() -> Option<OwnedProcess> {+ owned_process_lock()+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .take()+}++/// 仅当当前持有进程的 PID 与 `pid` 匹配时才取出(成对 PID+句柄)。+///+/// 保留 base 代码 `compare_exchange(pid, 0)` 的防护语义:退出监视线程只能清掉+/// 属于自己那一条登记,绝不误取/误清「刚启动的新进程」的登记——否则会把它+/// 当作已退出而错误回落 Status,并把新进程的句柄误关(WARN-6 合并引入的回退)。+fn take_owned_process_if(pid: u32) -> Option<OwnedProcess> {+ let mut guard = owned_process_lock()+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ take_owned_process_if_matching(&mut guard, pid)+}++/// 纯函数部分:便于单测,不触碰全局状态。+fn take_owned_process_if_matching(+ owned: &mut Option<OwnedProcess>,+ pid: u32,+) -> Option<OwnedProcess> {+ if owned.as_ref().map(|p| p.pid) == Some(pid) {+ owned.take()+ } else {+ None+ }+}++pub(crate) struct LaunchGuard;++impl Drop for LaunchGuard {+ fn drop(&mut self) {+ LAUNCH_GUARD.store(false, Ordering::SeqCst);+ }+}++pub fn has_owned_process() -> bool {+ owned_process_lock()+ .lock()+ .map(|g| g.is_some())+ .unwrap_or(false)+}++/// 处理「持有的 dsh 进程退出」这一事实(由退出监视线程与健康检查 tick 共用):+///+/// - 仅当退出的 PID 仍是当前登记的那个进程时才清空持有(`take_owned_process_if`+/// 按 pid 匹配),PID/句柄作为整体成对取出——杜绝「读 PID」与「清句柄」+/// 之间的跨原子竞态(WARN-6),也杜绝旧监视线程误清新启动进程的登记;+/// - 若当前状态仍是 Running,回落到 Stopped——否则进程已经没了、状态却永远+/// 显示「运行中」,前端按钮/横幅会长期处于错误语义(WARN-5)。+///+/// 返回被取出的进程记录(含 Windows 句柄),取到者负责 `CloseHandle`——保证+/// 「取走进程」与「关闭句柄」同属一个调用者,杜绝重复 close。幂等:多次调用+/// (tick 与监视线程并发)只会生效一次,后续调用返回 None。+pub(super) fn on_owned_process_exit(pid: u32) -> Option<OwnedProcess> {+ let owned = take_owned_process_if(pid)?;++ log::warn!(+ "Owned Harness process {} exited; resetting status to Stopped",+ owned.pid+ );++ if status::get_status() == status::Status::Running {+ status::set_status(status::Status::Stopped);+ }+ Some(owned)+}++/// 只结束本应用当前进程创建并仍持有的 Harness 进程树。+fn terminate_owned_process() {+ // 一次性取出 PID+句柄(成对),杜绝「PID 已清空/句柄未清」的漏杀窗口+ let Some(owned) = take_owned_process() else {+ return;+ };++ #[cfg(windows)]+ {+ use windows_sys::Win32::Foundation::CloseHandle;+ use windows_sys::Win32::System::Threading::WaitForSingleObject;+ const WAIT_TIMEOUT_CODE: u32 = 0x0000_0102;+ let handle = owned.handle as windows_sys::Win32::Foundation::HANDLE;+ if handle.is_null() {+ return;+ }+ // 真实句柄已结束说明 PID 可能已复用,此时绝不调用 taskkill。+ if unsafe { WaitForSingleObject(handle, 0) } != WAIT_TIMEOUT_CODE {+ unsafe { CloseHandle(handle) };+ return;+ }+ kill_pid_tree(owned.pid);+ unsafe {+ WaitForSingleObject(handle, 5_000);+ CloseHandle(handle);+ }+ }++ #[cfg(unix)]+ {+ kill_pid_tree(owned.pid);+ }+}++/// 结束进程树(Windows `taskkill /PID <pid> /T /F`;Unix 负 PID 进程组,与+/// 启动时 `process_group(0)` 对应)。调用方需先确认 PID 确实指向目标进程。+pub(super) fn kill_pid_tree(pid: u32) {+ #[cfg(windows)]+ {+ let mut cmd = Command::new("taskkill");+ cmd.args(["/PID", &pid.to_string(), "/T", "/F"]);+ use std::os::windows::process::CommandExt;+ cmd.creation_flags(0x08000000);+ cmd.stdout(Stdio::null());+ cmd.stderr(Stdio::null());+ if let Err(e) = cmd.output() {+ log::error!("Failed to stop Harness process tree {pid}: {e}");+ }+ }++ #[cfg(unix)]+ {+ // Harness 根进程启动在独立进程组中,负 PID 只作用于该进程树;手动通过+ // CLI 拉起的外围 dsh 进程未必有独立进程组(组信号报错),此时回退直接+ // 杀 PID——PID 的归属已由调用方确认(路径匹配或 .harness.pid 双重确认),+ // 绝不会误杀未知进程。+ let group = format!("-{pid}");+ let group_term_ok = Command::new("kill")+ .args(["-TERM", "--", &group])+ .output()+ .map(|output| output.status.success())+ .unwrap_or(false);+ if !group_term_ok {+ let _ = Command::new("kill")+ .args(["-TERM", "--", &pid.to_string()])+ .output();+ }+ std::thread::sleep(std::time::Duration::from_millis(300));+ let group_kill_ok = Command::new("kill")+ .args(["-KILL", "--", &group])+ .output()+ .map(|output| output.status.success())+ .unwrap_or(false);+ if !group_kill_ok {+ let _ = Command::new("kill")+ .args(["-KILL", "--", &pid.to_string()])+ .output();+ }+ }+}++/// 解析 `ps -axo pid=,command=` 的一行:返回 `(PID, 命令行)`。+///+/// 输出形如 ` 12345 node /path/to/bin.js --profile web ...`(PID 前可能有+/// 前导空格、行尾有换行)。PID 缺失或不可解析的行返回 None(跳过该行)。+#[cfg_attr(windows, allow(dead_code))] // 仅 Unix 清场分支与测试使用+fn parse_ps_line(line: &str) -> Option<(u32, &str)> {+ let trimmed = line.trim_start();+ let split = trimmed.find(|c: char| c.is_whitespace())?;+ let pid = trimmed[..split].trim().parse::<u32>().ok()?;+ Some((pid, trimmed[split..].trim_start()))+}++/// 判断命令行中是否包含一个完整参数。+///+/// `ps` 会把 argv 用空格拼成命令行,但不会给本身含空格的参数补引号,因此不能+/// 用 `split_whitespace` 还原参数。改为在原始命令行中匹配完整字符串,并校验+/// 前后为空白或行边界;这样 macOS 的 `Library/Application Support` 路径也能+/// 正确识别,同时不会把路径前缀相似的其他参数误判为目标。+#[cfg_attr(windows, allow(dead_code))] // 仅 Unix 清场分支与测试使用+fn command_line_has_argument(cmdline: &str, argument: &str) -> bool {+ if argument.is_empty() {+ return false;+ }++ cmdline.match_indices(argument).any(|(start, matched)| {+ let before_is_boundary = cmdline[..start]+ .chars()+ .next_back()+ .map_or(true, char::is_whitespace);+ let end = start + matched.len();+ let after_is_boundary = cmdline[end..]+ .chars()+ .next()+ .map_or(true, char::is_whitespace);+ before_is_boundary && after_is_boundary+ })+}++/// 判断命令行是否为「从本应用 dsh 安装目录启动的 Harness 服务」。+///+/// 除入口路径外同时核对桌面端服务启动参数,避免清扫时误伤用户并行执行的+/// `dsh plugin` 等短命令。+#[cfg_attr(windows, allow(dead_code))] // 仅 Unix 清场分支与测试使用+fn is_harness_command_line(cmdline: &str, dsh_bin: &str) -> bool {+ command_line_has_argument(cmdline, dsh_bin)+ && command_line_has_argument(cmdline, "--host")+ && command_line_has_argument(cmdline, "127.0.0.1")+ && command_line_has_argument(cmdline, "--port")+}++/// 结束所有从本应用 dsh 安装目录启动的 Harness 服务进程(含历史崩溃残留的孤儿实例)。+///+/// 只停本应用当前持有的进程不够:`.harness.pid` 标记只记录最近一次会话的 PID,+/// 应用多次崩溃/强杀(任务管理器结束等)会遗留多个孤儿 dsh 进程、端口一路漂移+/// (3080→3081→…),`sweep_orphan_harness` 每次只能回收最近一个,更早的孤儿+/// 会持续占用 `dependencies/dsh` 目录的文件句柄(node 以该目录为 cwd 且模块+/// DLL 加载在内存),更新切换目录时触发 os error 32(INSTALL_BACKUP_FAILED)。+///+/// 命令行为本应用 dsh 入口路径(`...\dependencies\dsh\node_modules\...\bin.js`)+/// 的 node 进程可判定为本应用的服务实例——路径精确匹配不会误杀用户其它 node+/// 程序,因此可安全地全部结束(taskkill /T /F)。+pub fn terminate_stale_harness_processes(app_handle: &tauri::AppHandle) {+ // 开发(debug)构建不做按路径清扫:生产与开发共用同一个 `dependencies/dsh`+ // 安装目录(核心共用),按命令行路径匹配会把同时运行的 release 服务进程+ // 一并结束——`pnpm tauri dev` 每次后端重编译都会重启应用并触发清扫,导致+ // "release 版 DSH 被 dev 版热更新杀掉"。开发构建自身的崩溃残留仍由+ // `.harness.pid` 标记(位于独立数据目录 `.dsh.dev`,PID+端口双重确认)+ // 精确回收。+ if cfg!(debug_assertions) {+ return;+ }+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ let dsh_bin_path = config::get_dsh_binary_path(app_handle);+ let Some(dsh_bin) = dsh_bin_path.to_str() else {+ return;+ };+ // 进程名过滤保证 PowerShell 自身(其命令行同样包含该路径)不被误杀;+ // 路径中的单引号按 PS 字符串字面量规则转义,避免用户目录含 `'` 时语法错误。+ let escaped = dsh_bin.replace('\'', "''");+ let script = format!(+ "Get-CimInstance Win32_Process -Filter \"Name = 'node.exe'\" | Where-Object {{ $_.CommandLine -like '*{escaped}*' }} | Select-Object -ExpandProperty ProcessId"+ );+ let Ok(output) = Command::new("powershell")+ .args(["-NoProfile", "-NonInteractive", "-Command", &script])+ .creation_flags(0x08000000)+ .output()+ else {+ log::error!("Failed to enumerate stale Harness service processes");+ return;+ };+ let mut found = 0;+ for line in String::from_utf8_lossy(&output.stdout).lines() {+ let Ok(pid) = line.trim().parse::<u32>() else {+ continue;+ };+ found += 1;+ log::warn!("Terminating stale Harness service process {pid} (from dsh install dir)");+ kill_pid_tree(pid);+ }+ if found > 0 {+ // 与 stop() 同理:taskkill 返回后 DLL 句柄的释放还有短暂滞后,+ // 让出一点时间避免紧随其后的目录切换撞上残留锁。+ std::thread::sleep(std::time::Duration::from_millis(800));+ }+ }+ #[cfg(not(windows))]+ {+ // Unix 同样需要按路径清扫:打开中的文件允许重命名确实不阻塞更新切换,+ // 但崩溃/强杀残留的孤儿 dsh 实例会持续监听端口,下一次启动只能一路+ // 漂移端口(3080→3081→…)并被持久化,表现为「更新后端口递增」+ // (issue #91)。用 `ps -ww -axo pid=,command=` 枚举完整命令行(`-ww`+ // 防止 macOS 按终端宽度截断长路径),按参数边界匹配本应用 dsh 入口与+ // 服务参数,不会误杀用户其它 node/dsh 命令,因此可安全地全部结束。+ let dsh_bin = config::get_dsh_binary_path(app_handle);+ let Some(dsh_bin_str) = dsh_bin.to_str() else {+ return;+ };+ let Ok(output) = Command::new("ps")+ .args(["-ww", "-axo", "pid=,command="])+ .output()+ else {+ log::error!("Failed to enumerate stale Harness service processes");+ return;+ };+ let mut found = 0;+ for line in String::from_utf8_lossy(&output.stdout).lines() {+ let Some((pid, cmdline)) = parse_ps_line(line) else {+ continue;+ };+ if !is_harness_command_line(cmdline, dsh_bin_str) {+ continue;+ }+ found += 1;+ log::warn!("Terminating stale Harness service process {pid} (from dsh install dir)");+ kill_pid_tree(pid);+ }+ if found > 0 {+ // 与 stop() 同理:信号发完后 PID 回收与端口释放还有短暂滞后,+ // 让出一点时间避免紧随其后的启动探测撞上尚未释放的端口。+ std::thread::sleep(std::time::Duration::from_millis(800));+ }+ }+}++#[cfg(unix)]+pub(super) fn warn_if_inotify_watch_limit_low() {+ let Some(limit) = crate::config::linux_inotify_max_user_watches() else {+ return;+ };+ if limit < crate::config::MIN_INOTIFY_MAX_USER_WATCHES {+ log::warn!(+ "Linux inotify.max_user_watches is {} (below recommended {}); dsh web may crash with ENOSPC (issue #116). To fix, run `sudo sysctl fs.inotify.max_user_watches={}` and write the same value to /etc/sysctl.conf to persist.",+ limit,+ crate::config::MIN_INOTIFY_MAX_USER_WATCHES,+ crate::config::MIN_INOTIFY_MAX_USER_WATCHES,+ );+ }+}++/// 停止 Harness 服务+pub async fn stop(app_handle: tauri::AppHandle) -> Result<(), String> {+ log::info!("Stopping Harness service...");+ // 重置启动守卫,确保后续 launch 可以重新拉起;仅结束持有的根进程树。+ // 进程终止涉及 WaitForSingleObject(至多 5s)与 taskkill/kill 等同步阻塞+ // 调用,移出 Tokio 执行线程避免卡住其他并发任务(WARN-7/P2-#20)。+ LAUNCH_GUARD.store(false, Ordering::SeqCst);+ tauri::async_runtime::spawn_blocking(terminate_owned_process)+ .await+ .map_err(|e| format!("STOP_FAILED: {e}"))?;+ // 清理孤儿清扫标记:正常停止的实例不应被下次启动当作残留+ let _ = fs::remove_file(harness_pid_path(&app_handle));++ // 给系统一点时间释放端口 (重要!)+ tokio::time::sleep(std::time::Duration::from_millis(800)).await;++ status::set_status(status::Status::Stopped);+ status::emit_status(&app_handle);+ Ok(())+}++/// 应用退出时同步回收 Harness 进程。+///+/// 退出路径上不更新状态、不做异步等待,只结束当前应用持有的 Harness 进程树。+pub fn stop_on_exit(app_handle: tauri::AppHandle, _port: u16) {+ terminate_owned_process();+ // 正常退出路径同样清理清扫标记(崩溃路径才需要下次启动清扫)+ let _ = fs::remove_file(harness_pid_path(&app_handle));+}++#[cfg(test)]+mod tests {+ use super::*;++ /// 构造一个测试用 `OwnedProcess`(跨平台处理 Windows 句柄字段)。+ #[cfg(windows)]+ fn test_owned(pid: u32) -> OwnedProcess {+ OwnedProcess { pid, handle: 0 }+ }+ #[cfg(not(windows))]+ fn test_owned(pid: u32) -> OwnedProcess {+ OwnedProcess { pid }+ }++ /// 退出监视线程只能清掉「与自己 PID 匹配」的登记,不许误清刚启动的新进程,+ /// 也不许重复取出(幂等)。回归 WARN-6 合并引入的回退。+ #[test]+ fn owned_process_take_if_only_matches_pid() {+ // 匹配的 PID 才可取出,且取走后槽清空+ let mut slot = Some(test_owned(42));+ let taken = take_owned_process_if_matching(&mut slot, 42);+ assert_eq!(taken.map(|p| p.pid), Some(42));+ assert!(slot.is_none());++ // PID 不匹配(旧进程 41 退出)时禁止取出/清空新进程(新进程 42)+ let mut slot = Some(test_owned(42));+ let taken = take_owned_process_if_matching(&mut slot, 41);+ assert!(taken.is_none());+ assert_eq!(slot.as_ref().map(|p| p.pid), Some(42));++ // 幂等:已清空后再次取出返回 None+ let mut slot: Option<OwnedProcess> = None;+ assert!(take_owned_process_if_matching(&mut slot, 42).is_none());+ }++ /// `ps -axo pid=,command=` 行解析:首列 PID,其余为命令行。+ #[test]+ fn parse_ps_line_extracts_pid_and_cmdline() {+ // `.lines()` 迭代已去掉行尾换行+ let (pid, cmdline) =+ parse_ps_line(" 12345 node /path/to/bin.js --profile web").expect("parse ps line");+ assert_eq!(pid, 12345);+ assert_eq!(cmdline, "node /path/to/bin.js --profile web");+ // 多列空白(PID 与命令之间多个空格)+ 行首空白+ let (pid, cmdline) = parse_ps_line(" 67890 sh -c sleep 1").expect("parse ps line");+ assert_eq!(pid, 67890);+ assert_eq!(cmdline, "sh -c sleep 1");+ }++ #[test]+ fn parse_ps_line_skips_invalid_rows() {+ // 无空白分隔(纯 PID)→ 无法取命令行,跳过+ assert!(parse_ps_line("12345").is_none());+ // PID 不可解析(可能是表头残留)→ 跳过+ assert!(parse_ps_line("PID COMMAND").is_none());+ // 空行 → 跳过+ assert!(parse_ps_line("").is_none());+ }++ /// 命令行匹配:argv 整词精确等于 dsh 入口路径才算本应用服务实例。+ #[test]+ fn harness_cmdline_matches_service_arguments() {+ let bin = "/home/u/.dsh/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js";+ assert!(is_harness_command_line(+ &format!("node {bin} --profile web --host 127.0.0.1 --port 3083"),+ bin+ ));+ }++ #[test]+ fn harness_cmdline_matches_macos_app_data_path_with_spaces() {+ let bin = "/Users/simon/Library/Application Support/io.github.hairyf.deepseek-harness-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js";+ let cmdline =+ format!("/opt/homebrew/bin/node {bin} --profile web --host 127.0.0.1 --port 3084");+ assert!(is_harness_command_line(&cmdline, bin));+ }++ #[test]+ fn harness_cmdline_rejects_foreign_and_prefix_paths() {+ let bin = "/home/u/.dsh/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js";+ // 用户其它 node 程序+ assert!(!is_harness_command_line(+ "node /usr/bin/some-server.js",+ bin+ ));+ // 路径前缀相似但不同(整词匹配,不做子串匹配)+ assert!(!is_harness_command_line(+ "node /home/u/.dsh/dependencies/dsh-extra/tool.js",+ bin+ ));+ // 完整路径只是另一参数的前缀时不能命中+ assert!(!is_harness_command_line(+ &format!("node {bin}.backup --profile web --host 127.0.0.1 --port 3083"),+ bin+ ));+ // 同一 dsh 入口执行插件命令时不是 Harness 服务,不能清扫+ assert!(!is_harness_command_line(+ &format!("node {bin} plugin list"),+ bin+ ));+ // 路径作为另一个参数的后缀时不能命中+ assert!(!is_harness_command_line(+ &format!("node prefix{bin} --host 127.0.0.1 --port 3083"),+ bin+ ));+ // 空命令行+ assert!(!is_harness_command_line("", bin));+ }++ /// 回归(issue #91):Unix 上 `kill_pid_tree` 对「无独立进程组」的进程+ /// 必须回退到直接杀 PID——否则手动 CLI 拉起的外围 dsh 永远杀不掉,+ /// 残留进程持续占用端口导致端口一路递增。+ #[cfg(unix)]+ #[test]+ fn kill_pid_tree_falls_back_to_direct_pid_kill() {+ // 子进程不设独立进程组(模拟手动拉起的外围 dsh);2 秒后自然退出,+ // 若 kill_pid_tree 未能杀死它,wait 会等到 2 秒后自然退出 → 超时断言失败+ let mut child = Command::new("sh")+ .arg("-c")+ .arg("sleep 2")+ .spawn()+ .expect("spawn sleep child");+ let pid = child.id();+ // 给子进程一点时间进入 sleep,确保信号发到的是 sleep 而非刚 fork 的 sh+ std::thread::sleep(std::time::Duration::from_millis(200));+ let started = std::time::Instant::now();+ kill_pid_tree(pid);+ let status = child.wait().expect("wait for child");+ assert!(+ started.elapsed() < std::time::Duration::from_millis(1500),+ "child should have been killed by kill_pid_tree, not waited for natural exit"+ );+ // 被信号杀死:success() 为 false(SIGTERM 143 / SIGKILL 137)+ assert!(!status.success());+ }++ /// 正常路径:根进程在独立进程组中(与启动时 `process_group(0)` 对应),+ /// 负 PID 组信号应能结束整个进程树。+ #[cfg(unix)]+ #[test]+ fn kill_pid_tree_kills_process_group() {+ use std::os::unix::process::CommandExt;+ let mut child = Command::new("sh")+ .arg("-c")+ .arg("sleep 2")+ .process_group(0)+ .spawn()+ .expect("spawn group child");+ let pid = child.id();+ std::thread::sleep(std::time::Duration::from_millis(200));+ let started = std::time::Instant::now();+ kill_pid_tree(pid);+ let status = child.wait().expect("wait for group child");+ assert!(started.elapsed() < std::time::Duration::from_millis(1500));+ assert!(!status.success());+ }+}diff --git a/src-tauri/src/service/workflow/sweep.rs b/src-tauri/src/service/workflow/sweep.rsnew file mode 100644index 00000000..3ef40c6c--- /dev/null+++ b/src-tauri/src/service/workflow/sweep.rs@@ -0,0 +1,178 @@+//! 孤儿 Harness 清扫:崩溃/强杀残留实例的识别与回收(issue #34 关联现象),+//! 以及 Windows RedirectionGuard(448) 逃逸重拉。++use crate::config;+use std::fs;+use std::process::Command;++use super::process::{has_owned_process, kill_pid_tree, terminate_stale_harness_processes};+use super::utils::is_port_in_use;++/// 孤儿清扫用的 PID/端口标记文件路径($DSH_HOME/.harness.pid,两行:PID、端口)。+///+/// 应用被强杀(崩溃、任务管理器结束等)时无法执行退出清理,其 Harness 子进程+/// 会继续占用端口;下一次启动只能一路漂移端口(3080→3081→…)并触发服务端+/// "already running",表现为应用"坏掉"。启动前据此文件识别并清理这类残留。+pub(super) fn harness_pid_path(app_handle: &tauri::AppHandle) -> std::path::PathBuf {+ config::get_dsh_data_path(app_handle).join(".harness.pid")+}++/// 记录本次启动的 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。端口与 PID 双重确认后才动手:+/// - 标记进程已死 → 仅清理陈旧标记;+/// - 端口占用者正是标记中的 PID → 本应用残留,结束其进程树并清标记;+/// - 其余情况(标记不可解析、端口被其他程序占用、无法探测占用者)一律不动,+/// 绝不凭端口猜进程、绝不杀未知进程。+pub fn sweep_orphan_harness(app_handle: &tauri::AppHandle) {+ if has_owned_process() {+ return;+ }+ // 先按命令行路径清扫所有从本应用 dsh 安装目录启动的孤儿 Harness 实例:+ // 标记文件只记录最近一次会话的 PID,应用多次崩溃/强杀会遗留更早的孤儿+ // (端口一路漂移 3081/3082/…),它们持续占用 dependencies/dsh 目录的文件+ // 句柄,导致更新切换目录失败(INSTALL_BACKUP_FAILED, os error 32)。+ // 路径精确匹配不会误杀用户其它 node 程序;标记中的进程若在其中会被一并+ // 结束,随后的 PID/端口双重确认自然落空,仅清理陈旧标记。+ terminate_stale_harness_processes(app_handle);+ let pid_file = harness_pid_path(app_handle);+ let Ok(text) = fs::read_to_string(&pid_file) else {+ return;+ };+ let mut lines = text.lines();+ let (Some(pid), Some(port)) = (+ lines.next().and_then(|l| l.trim().parse::<u32>().ok()),+ lines.next().and_then(|l| l.trim().parse::<u16>().ok()),+ ) else {+ // 标记内容不可解析:陈旧垃圾,清掉即可+ let _ = fs::remove_file(&pid_file);+ return;+ };+ if !is_port_in_use(port) {+ // 端口已释放:残留实例早已自行退出,仅清理标记+ let _ = fs::remove_file(&pid_file);+ return;+ }+ if port_owner_pid(port) != Some(pid) {+ // 端口占用者不是我们落盘的进程(或探测不到):可能是其他程序,不动+ return;+ }+ log::warn!("Sweeping orphaned Harness process {pid} (port {port}) left by a previous session");+ kill_pid_tree(pid);+ let _ = fs::remove_file(&pid_file);+}++/// 占用指定端口的进程 PID(LISTENING 状态)。+/// - Windows:`netstat -ano` 解析;+/// - Unix:`lsof -ti tcp:<port>`,不可用时返回 None。+/// 返回 None 视为"无法确认",调用方不会因此杀任何进程。+fn port_owner_pid(port: u16) -> Option<u32> {+ #[cfg(windows)]+ {+ // 打包版是 GUI 进程(无控制台):netstat 是控制台子系统程序,直接运行会+ // 新建一个可见的黑色 cmd 窗口(启动时的孤儿清扫会走到这里)。必须+ // CREATE_NO_WINDOW,否则每次启动闪一个黑窗。+ use std::os::windows::process::CommandExt;+ let output = Command::new("netstat")+ .arg("-ano")+ .creation_flags(0x08000000)+ .output()+ .ok()?;+ let text = String::from_utf8_lossy(&output.stdout);+ let needle = format!(":{port} ");+ for line in text.lines() {+ let fields: Vec<&str> = line.split_whitespace().collect();+ if fields.len() < 5 || fields[0] != "TCP" {+ continue;+ }+ // 本地地址列(如 127.0.0.1:3080 / [::1]:3080)以 :<port> 结尾+ if !fields[1].ends_with(&needle) {+ continue;+ }+ if fields[3] == "LISTENING" {+ return fields[4].parse().ok();+ }+ }+ None+ }+ #[cfg(not(windows))]+ {+ // lsof 在 macOS 默认可用、Linux 常缺失;缺失时跳过清扫(返回 None)+ let output = Command::new("lsof")+ .args(["-ti", &format!("tcp:{port}")])+ .output()+ .ok()?;+ if !output.status.success() {+ return None;+ }+ String::from_utf8_lossy(&output.stdout)+ .lines()+ .next()+ .and_then(|l| l.trim().parse().ok())+ }+}++/// Windows RedirectionGuard(错误码 448 = ERROR_UNTRUSTED_MOUNT_POINT)逃逸重拉的标记路径。+#[cfg(windows)]+pub(super) fn relaunch_marker_path(app_handle: &tauri::AppHandle) -> std::path::PathBuf {+ config::get_base_dir(app_handle).join(".dsh-relaunch-448")+}++/// 探测 dsh 入口在当前进程上下文下的打开错误码(None=可打开)。+///+/// 448 只在「进程继承 RedirectionGuard 强制执行」时出现;干净上下文(父进程为+/// explorer 等普通进程)下 Level-1 符号链接可正常穿越。+#[cfg(windows)]+pub(super) fn dsh_bin_open_error(app_handle: &tauri::AppHandle) -> Option<i32> {+ std::fs::File::open(config::get_dsh_binary_path(app_handle))+ .err()+ .and_then(|e| e.raw_os_error())+}++/// 通过 explorer 转交启动请求,脱离 RedirectionGuard 强制执行上下文后退出本进程。+///+/// Windows 11 25H2 的 RedirectionGuard 对「非提权进程创建的符号链接/联接点」盖信任章,+/// 而安装器(msiexec/RestartManager 自动重开)会在自身进程启用强制执行并随进程树继承,+/// 导致新实例跨越 pnpm 符号链接链打开 bin.js 时持续报 448——实测与等待时长无关、+/// 永不自行恢复(issue #35)。应用无法在运行时关闭继承的策略,只能脱离被污染的进程树:+/// 把启动请求转交给 explorer(单实例壳进程,干净上下文),由 explorer 创建新实例,+/// 其父进程即 explorer,不再继承强制执行(实测:explorer.exe <exe> 的子进程父进程为+/// explorer.exe,而非转交发起者)。标记文件用于防死循环:若上次重拉未逃逸+/// (explorer 未运行等),本次回退到常规缺失处理(复位 installed 走安装流程)。+#[cfg(windows)]+pub(super) fn relaunch_via_shell_escape(app_handle: &tauri::AppHandle) {+ let marker = relaunch_marker_path(app_handle);+ if marker.exists() {+ let _ = std::fs::remove_file(&marker);+ log::warn!("RedirectionGuard(448) relaunch did not escape, falling back to normal missing handling");+ return;+ }+ let _ = std::fs::write(&marker, b"1");+ let Ok(exe) = std::env::current_exe() else {+ log::warn!("RedirectionGuard(448) detected but current_exe unavailable, falling back");+ return;+ };+ match std::process::Command::new("explorer.exe").arg(&exe).spawn() {+ Ok(_) => {+ log::warn!(+ "RedirectionGuard(448) detected, relaunching via explorer to escape enforced context: {}",+ exe.display()+ );+ // 短暂让出后退出,避免与新实例产生单实例冲突+ std::thread::sleep(std::time::Duration::from_millis(300));+ std::process::exit(0);+ }+ Err(e) => {+ log::warn!(+ "RedirectionGuard(448) detected but explorer spawn failed ({e}), falling back"+ );+ }+ }+}diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rsindex 670dfa1b..b54a8445 100644--- a/src-tauri/src/utils/mod.rs+++ b/src-tauri/src/utils/mod.rs@@ -58,9 +58,8 @@ pub fn patch_dsh(log::warn!("dsh patch anchor missing, skip: {}", target.display());}PatchOutcome::Patched(patched) => {- std::fs::write(&target, patched).map_err(|e| {- format!("DSH_PATCH_WRITE: {} failed: {e}", target.display())- })?;+ std::fs::write(&target, patched)+ .map_err(|e| format!("DSH_PATCH_WRITE: {} failed: {e}", target.display()))?;log::info!("dsh patch applied: {}", target.display());}}diff --git a/test/internal-plugin-phase.test.ts b/test/internal-plugin-phase.test.tsindex 24f6a823..a03d7d6f 100644--- a/test/internal-plugin-phase.test.ts+++ b/test/internal-plugin-phase.test.ts@@ -20,7 +20,7 @@ function payload(detail: InternalPluginsPhasePayload['detail']): InternalPluginsdescribe('internal plugin phase contract', () => {it('matches every Rust detail emitted by the startup phase', () => {const rustSource = readFileSync(- new URL('../src-tauri/src/service/plugin/internal.rs', import.meta.url),+ new URL('../src-tauri/src/service/plugin/internal/mod.rs', import.meta.url),'utf8',)const declaration = rustSource.match(