DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
style: format Rust sources
[email protected]168077aca2f6
diff --git a/src-tauri/src/bridge/lifecycle.rs b/src-tauri/src/bridge/lifecycle.rsindex ca8d6f04..416d7a81 100644--- a/src-tauri/src/bridge/lifecycle.rs+++ b/src-tauri/src/bridge/lifecycle.rs@@ -138,8 +138,7 @@ pub async fn install_dependencies(app_handle: AppHandle) -> Result<bool, String>) {// 安装文件已是最新 release,只是记录滞后:修正记录后下次// 启动直接走 commit 快速比对,不再误判、也绝不整包重下- download::UpdateCheck::UpToDate- | download::UpdateCheck::HealUpToDate => {+ download::UpdateCheck::UpToDate | download::UpdateCheck::HealUpToDate => {if record_commit.as_deref() != Some(latest.commit.as_str()) {log::info!("Installed Harness files already at latest release, healing stale record: {} ({})",diff --git a/src-tauri/src/bridge/mod.rs b/src-tauri/src/bridge/mod.rsindex 6e5abeff..c69c207a 100644--- a/src-tauri/src/bridge/mod.rs+++ b/src-tauri/src/bridge/mod.rs@@ -4,8 +4,8 @@//! 系统集成 / 更新),此处统一声明并重导出为「干净 API」,供 `generate_handler!`//! 以 `crate::bridge::<cmd>` 形式注册。-pub mod config;pub mod clipboard;+pub mod config;pub mod core;pub mod guard;pub mod lifecycle;@@ -14,8 +14,8 @@ pub mod profile;pub mod system_os;pub mod updater;-pub use config::*;pub use clipboard::*;+pub use config::*;pub use core::*;pub use lifecycle::*;pub use plugin::*;diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rsindex 659173b3..728fb504 100644--- a/src-tauri/src/bridge/plugin.rs+++ b/src-tauri/src/bridge/plugin.rs@@ -99,7 +99,9 @@ pub fn get_dsh_plugins(app_handle: AppHandle) -> Vec<plugin::DshPlugin> {/// 「无更新」处理)。前端在插件面板挂载后调用一次以补齐 `updateAvailable`,使升级/// 按钮只在确有更新(或异常修复)时出现,而不是常驻。#[tauri::command]-pub async fn refresh_plugin_updates(app_handle: AppHandle) -> Result<Vec<plugin::DshPlugin>, String> {+pub async fn refresh_plugin_updates(+ app_handle: AppHandle,+) -> Result<Vec<plugin::DshPlugin>, String> {plugin::update::refresh(&app_handle).await}@@ -130,7 +132,12 @@ pub fn report_plugin_error(error: String,action: Option<String>,) -> Result<(), String> {- plugin::errors::record(&app_handle, &id, action.as_deref().unwrap_or("runtime"), &error)?;+ plugin::errors::record(+ &app_handle,+ &id,+ action.as_deref().unwrap_or("runtime"),+ &error,+ )?;plugin::watch::force_emit(&app_handle);// 运行期异常:直接推送修复界面(应用仍在运行,前端以醒目对话框呈现)。let info = plugin::PluginRecoveryInfo {diff --git a/src-tauri/src/bridge/profile.rs b/src-tauri/src/bridge/profile.rsindex 08421de9..b2216482 100644--- a/src-tauri/src/bridge/profile.rs+++ b/src-tauri/src/bridge/profile.rs@@ -20,10 +20,7 @@ pub fn create_profile(app_handle: AppHandle, name: String) -> Result<profile::Pr/// 切换当前使用中的档案(持久化;重启服务后生效,由前端触发)#[tauri::command]-pub fn set_active_profile(- app_handle: AppHandle,- id: String,-) -> Result<profile::Profile, String> {+pub fn set_active_profile(app_handle: AppHandle, id: String) -> Result<profile::Profile, String> {profile::set_active(&app_handle, &id)}diff --git a/src-tauri/src/bridge/system_os.rs b/src-tauri/src/bridge/system_os.rsindex 172afc48..b06ca84c 100644--- a/src-tauri/src/bridge/system_os.rs+++ b/src-tauri/src/bridge/system_os.rs@@ -52,8 +52,7 @@ pub fn reveal_in_folder(app_handle: AppHandle, path: String) -> Result<(), Strinif !crate::bridge::guard::is_allowed_path(&app_handle, std::path::Path::new(&path)) {return Err(format!("REVEAL_PATH_REJECTED: {path}"));}- tauri_plugin_opener::reveal_item_in_dir(&path)- .map_err(|e| format!("REVEAL_FAILED: {e}"))+ tauri_plugin_opener::reveal_item_in_dir(&path).map_err(|e| format!("REVEAL_FAILED: {e}"))}/// 在系统文件管理器中打开指定目录(核心版本「打开目录」按钮;目录用 open 而非@@ -64,8 +63,7 @@ pub fn open_dir(app_handle: AppHandle, path: String) -> Result<(), String> {if !crate::bridge::guard::is_allowed_path(&app_handle, std::path::Path::new(&path)) {return Err(format!("OPEN_DIR_REJECTED: {path}"));}- tauri_plugin_opener::open_path(&path, None::<&str>)- .map_err(|e| format!("OPEN_DIR_FAILED: {e}"))+ tauri_plugin_opener::open_path(&path, None::<&str>).map_err(|e| format!("OPEN_DIR_FAILED: {e}"))}/// 在系统文件管理器中打开数据目录(官方 $DSH_HOME,即 ~/.dsh)@@ -252,24 +250,40 @@ mod tests {#[test]fn frontend_line_detected() {// tracing 文件层(desktop.log)与前端独立文件(desktop.frontdesk.log)两种时间戳格式都应命中- assert!(is_frontend_log_line("2024-06-01 12:00:00.123Z INFO frontend: [tag] message"));- assert!(is_frontend_log_line("[2024-06-01 12:00:00.123Z] INFO frontend: message"));- assert!(is_frontend_log_line("2024-06-01 12:00:00.123Z WARN frontend: something"));- assert!(is_frontend_log_line("2024-06-01 12:00:00.123Z ERROR frontend: boom"));+ assert!(is_frontend_log_line(+ "2024-06-01 12:00:00.123Z INFO frontend: [tag] message"+ ));+ assert!(is_frontend_log_line(+ "[2024-06-01 12:00:00.123Z] INFO frontend: message"+ ));+ assert!(is_frontend_log_line(+ "2024-06-01 12:00:00.123Z WARN frontend: something"+ ));+ assert!(is_frontend_log_line(+ "2024-06-01 12:00:00.123Z ERROR frontend: boom"+ ));}#[test]fn backend_line_not_detected() {// 后端(dsh 等 target)不应误判为前端;消息正文里出现 "frontend" 也不应命中- assert!(!is_frontend_log_line("2024-06-01 12:00:00.123Z INFO dsh: starting server"));- assert!(!is_frontend_log_line("[2024-06-01 12:00:00.123Z] INFO dsh: emit to frontend: 3"));- assert!(!is_frontend_log_line("2024-06-01 12:00:00.123Z DEBUG reqwest: GET /ping"));+ assert!(!is_frontend_log_line(+ "2024-06-01 12:00:00.123Z INFO dsh: starting server"+ ));+ assert!(!is_frontend_log_line(+ "[2024-06-01 12:00:00.123Z] INFO dsh: emit to frontend: 3"+ ));+ assert!(!is_frontend_log_line(+ "2024-06-01 12:00:00.123Z DEBUG reqwest: GET /ping"+ ));}#[test]fn frontend_level_padding_and_extra_spaces() {// 级别可能带前导空格(`{:>5}` 或 tracing 层多空格),frontend 目标仍应命中- assert!(is_frontend_log_line("2024-06-01 12:00:00.123Z INFO frontend: padded"));+ assert!(is_frontend_log_line(+ "2024-06-01 12:00:00.123Z INFO frontend: padded"+ ));}#[test]diff --git a/src-tauri/src/config/i18n.rs b/src-tauri/src/config/i18n.rsindex fb721fed..b04e689a 100644--- a/src-tauri/src/config/i18n.rs+++ b/src-tauri/src/config/i18n.rs@@ -14,10 +14,13 @@ pub enum Lang {static CURRENT_LANG: AtomicU8 = AtomicU8::new(0); // 0 = zh, 1 = enpub fn set_language(lang: Lang) {- CURRENT_LANG.store(match lang {- Lang::Zh => 0,- Lang::En => 1,- }, Ordering::SeqCst);+ CURRENT_LANG.store(+ match lang {+ Lang::Zh => 0,+ Lang::En => 1,+ },+ Ordering::SeqCst,+ );}fn lang() -> Lang {@@ -31,17 +34,40 @@ fn lang() -> Lang {/// Look up a translation key. Keys are grouped by domain with `_` separators.pub fn t(key: &str) -> String {let (zh, en): (&str, &str) = match key {- "runtime.unsupported_platform" => ("不支持当前平台/架构", "Unsupported platform/architecture"),+ "runtime.unsupported_platform" => {+ ("不支持当前平台/架构", "Unsupported platform/architecture")+ }"runtime.title" => ("Node.js 运行时", "Node.js runtime"),- "runtime.not_found" => ("Node.js 运行时不存在,请先完成安装", "Node.js runtime not found, run setup first"),- "runtime.incompatible" => ("Node.js 运行时版本过低,需要 v22.15.0+ 或 v23.8.0+", "Node.js runtime is too old, need v22.15.0+ or v23.8.0+"),+ "runtime.not_found" => (+ "Node.js 运行时不存在,请先完成安装",+ "Node.js runtime not found, run setup first",+ ),+ "runtime.incompatible" => (+ "Node.js 运行时版本过低,需要 v22.15.0+ 或 v23.8.0+",+ "Node.js runtime is too old, need v22.15.0+ or v23.8.0+",+ ),"harness.title" => ("DeepSeek Harness 核心", "DeepSeek Harness core"),- "harness.core_not_found" => ("未找到 DeepSeek Harness 核心包,请先完成安装", "DeepSeek Harness core package not found, run setup first"),+ "harness.core_not_found" => (+ "未找到 DeepSeek Harness 核心包,请先完成安装",+ "DeepSeek Harness core package not found, run setup first",+ ),"harness.manifest_invalid" => ("Harness 包清单无效", "Invalid harness package manifest"),- "harness.asset_not_found" => ("发布资源中未找到匹配的平台包", "No matching platform asset found in the release"),- "harness.hash_mismatch" => ("下载文件哈希校验失败", "Downloaded file hash verification failed"),- "harness.start_failed" => ("启动 DeepSeek Harness 服务失败", "Failed to start DeepSeek Harness service"),- "harness.health_unhealthy" => ("DeepSeek Harness 服务未就绪", "DeepSeek Harness service is not ready"),+ "harness.asset_not_found" => (+ "发布资源中未找到匹配的平台包",+ "No matching platform asset found in the release",+ ),+ "harness.hash_mismatch" => (+ "下载文件哈希校验失败",+ "Downloaded file hash verification failed",+ ),+ "harness.start_failed" => (+ "启动 DeepSeek Harness 服务失败",+ "Failed to start DeepSeek Harness service",+ ),+ "harness.health_unhealthy" => (+ "DeepSeek Harness 服务未就绪",+ "DeepSeek Harness service is not ready",+ ),"process.manager_poisoned" => ("进程管理器状态异常", "Process manager state is corrupted"),"config.load_failed" => ("读取配置失败", "Failed to load configuration"),"config.save_failed" => ("保存配置失败", "Failed to save configuration"),diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rsindex c0db6eb6..6d7781dc 100644--- a/src-tauri/src/config/runtime.rs+++ b/src-tauri/src/config/runtime.rs@@ -6,8 +6,8 @@ use tauri::{AppHandle, Manager, Runtime};use super::constants::*;use super::format::get_dsh_service_url;-use super::{detect_region, Region};use super::utils::search_node_binary;+use super::{detect_region, Region};/// 获取 App Data 基础目录pub fn get_base_dir<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {@@ -43,7 +43,12 @@ fn node_pkg_filename(os: &str, arch: &str) -> Result<String, String> {/// Node.js 运行时下载地址pub fn get_node_download_url() -> Result<String, String> {let filename = node_pkg_filename(env::consts::OS, env::consts::ARCH)?;- Ok(format!("{}/{}/{}", node_base_url(detect_region()), NODE_VERSION, filename))+ Ok(format!(+ "{}/{}/{}",+ node_base_url(detect_region()),+ NODE_VERSION,+ filename+ ))}/// 打包的 DeepSeek Harness 发行版下载前缀:恒为 GitHub Release 官方直连,@@ -103,8 +108,10 @@ pub fn mirror_download_url(asset_url: &str) -> String {/// `releases/download/<tag>/`,镜像/直连与平台文件名逻辑与最新版完全一致/// (GitHub 的 tag 下载路径是固定的 release 资产地址,可被确定性推导)。pub fn get_dsh_download_url_for_tag(tag: &str) -> Result<String, String> {- let base = dsh_core_base_url()- .replace("releases/latest/download/", &format!("releases/download/{tag}/"));+ let base = dsh_core_base_url().replace(+ "releases/latest/download/",+ &format!("releases/download/{tag}/"),+ );Ok(format!("{}{}", base, dsh_pkg_asset_filename()?))}@@ -169,7 +176,10 @@ fn node_version_output(node: &Path) -> Option<std::process::Output> {}#[cfg(not(windows))]{- std::process::Command::new(node).arg("--version").output().ok()+ std::process::Command::new(node)+ .arg("--version")+ .output()+ .ok()}}@@ -226,7 +236,9 @@ pub fn get_node_install_path(app_handle: &tauri::AppHandle) -> PathBuf {/// Harness 发行版安装目录pub fn get_dsh_install_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {- get_base_dir(app_handle).join("dependencies").join(DSH_CORE_DIR)+ get_base_dir(app_handle)+ .join("dependencies")+ .join(DSH_CORE_DIR)}/// dsh CLI 入口@@ -236,7 +248,9 @@ pub fn get_dsh_binary_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {/// pnpm 安装目录pub fn get_pnpm_install_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {- get_base_dir(app_handle).join("dependencies").join(PNPM_CORE_DIR)+ get_base_dir(app_handle)+ .join("dependencies")+ .join(PNPM_CORE_DIR)}/// 捆绑 pnpm CLI 入口(纯 JS 发行,用 node 运行)@@ -254,7 +268,11 @@ fn pnpm_base_url(region: Region) -> &'static str {/// pnpm 下载地址(纯 JS 发行,全平台同一 URL)pub fn get_pnpm_download_url() -> String {- format!("{}pnpm-{}.tgz", pnpm_base_url(detect_region()), PNPM_VERSION)+ format!(+ "{}pnpm-{}.tgz",+ pnpm_base_url(detect_region()),+ PNPM_VERSION+ )}/// Windows 免安装 Git 的安装目录。@@ -328,7 +346,10 @@ fn git_binary_works(binary: &Path) -> bool {return false;};let exec_path = String::from_utf8_lossy(&output.stdout).trim().to_string();- !exec_path.is_empty() && PathBuf::from(exec_path).join("git-remote-https.exe").is_file()+ !exec_path.is_empty()+ && PathBuf::from(exec_path)+ .join("git-remote-https.exe")+ .is_file()}/// 返回桌面端应注入子进程 PATH 的已选 Git `cmd` 目录。@@ -479,7 +500,11 @@ pub fn get_dsh_version<R: Runtime>(app_handle: &AppHandle<R>) -> Option<String>.get("dependencies").and_then(|deps| deps.get("@deepseek-ai/dsh")).and_then(|value| value.as_str())- .map(|value| value.trim_start_matches(['^', '~', '=', '>', '<']).to_string())+ .map(|value| {+ value+ .trim_start_matches(['^', '~', '=', '>', '<'])+ .to_string()+ })}/// 侧边栏展示的运行时/版本/诊断信息@@ -525,8 +550,16 @@ mod tests {// 无论哪个地域,首选源都是 GitHub 官方直连;镜像仅作兜底let urls = get_dsh_download_urls().expect("dsh urls");assert_eq!(urls.len(), 2);- assert!(urls[0].starts_with(DSH_CORE_URL), "first source must be official GitHub: {}", urls[0]);- assert!(urls[1].starts_with(DSH_MIRROR_PREFIX), "fallback must be ghfast mirror: {}", urls[1]);+ assert!(+ urls[0].starts_with(DSH_CORE_URL),+ "first source must be official GitHub: {}",+ urls[0]+ );+ assert!(+ urls[1].starts_with(DSH_MIRROR_PREFIX),+ "fallback must be ghfast mirror: {}",+ urls[1]+ );// 两个源的文件名一致(镜像只是换前缀,解压类型判定不受影响)let name = |u: &str| u.rsplit('/').next().unwrap_or("").to_string();assert_eq!(name(&urls[0]), name(&urls[1]));@@ -593,12 +626,36 @@ mod tests {// 与 nodejs.org dist 布局一致(纯函数测试,不受宿主操作系统限制)let cases = [// (os, arch, 期望文件名)- ("linux", "x86_64", format!("node-{}-linux-x64.tar.gz", NODE_VERSION)),- ("linux", "aarch64", format!("node-{}-linux-arm64.tar.gz", NODE_VERSION)),- ("windows", "x86_64", format!("node-{}-win-x64.zip", NODE_VERSION)),- ("windows", "aarch64", format!("node-{}-win-x64.zip", NODE_VERSION)),- ("macos", "aarch64", format!("node-{}-darwin-arm64.tar.gz", NODE_VERSION)),- ("macos", "x86_64", format!("node-{}-darwin-x64.tar.gz", NODE_VERSION)),+ (+ "linux",+ "x86_64",+ format!("node-{}-linux-x64.tar.gz", NODE_VERSION),+ ),+ (+ "linux",+ "aarch64",+ format!("node-{}-linux-arm64.tar.gz", NODE_VERSION),+ ),+ (+ "windows",+ "x86_64",+ format!("node-{}-win-x64.zip", NODE_VERSION),+ ),+ (+ "windows",+ "aarch64",+ format!("node-{}-win-x64.zip", NODE_VERSION),+ ),+ (+ "macos",+ "aarch64",+ format!("node-{}-darwin-arm64.tar.gz", NODE_VERSION),+ ),+ (+ "macos",+ "x86_64",+ format!("node-{}-darwin-x64.tar.gz", NODE_VERSION),+ ),];for (os, arch, expected) in cases {assert_eq!(diff --git a/src-tauri/src/config/theme.rs b/src-tauri/src/config/theme.rsindex 04e8a194..e949c3ff 100644--- a/src-tauri/src/config/theme.rs+++ b/src-tauri/src/config/theme.rs@@ -1,8 +1,8 @@use std::fs;use std::sync::{Mutex, OnceLock};-use tauri::{AppHandle, Emitter};#[cfg(target_os = "macos")]use tauri::Manager;+use tauri::{AppHandle, Emitter};use super::runtime::get_dsh_data_path;diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 21a21140..d5f34448 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -248,7 +248,8 @@ pub fn install_macos_menu(app: &tauri::AppHandle<Wry>) -> tauri::Result<()> {let cut = PredefinedMenuItem::cut(app, Some(&crate::config::i18n::t("menu.cut")))?;let copy = PredefinedMenuItem::copy(app, Some(&crate::config::i18n::t("menu.copy")))?;let paste = PredefinedMenuItem::paste(app, Some(&crate::config::i18n::t("menu.paste")))?;- let select_all = PredefinedMenuItem::select_all(app, Some(&crate::config::i18n::t("menu.select_all")))?;+ let select_all =+ PredefinedMenuItem::select_all(app, Some(&crate::config::i18n::t("menu.select_all")))?;let edit_separator_after_redo = PredefinedMenuItem::separator(app)?;let edit_separator_before_select_all = PredefinedMenuItem::separator(app)?;let edit_menu = Submenu::with_id_and_items(diff --git a/src-tauri/src/desktop/compat.rs b/src-tauri/src/desktop/compat.rsindex 0a3e9d62..cb0f36a7 100644--- a/src-tauri/src/desktop/compat.rs+++ b/src-tauri/src/desktop/compat.rs@@ -73,4 +73,4 @@ pub(crate) const ABORT_SIGNAL_ANY_SHIM_JS: &str = r#"(function () {AbortSignal.any = polyfillAny;} catch (_ignored) { /* 保留原生未定义的现状 */ }}-})();"#;\ No newline at end of file+})();"#;diff --git a/src-tauri/src/desktop/notification.rs b/src-tauri/src/desktop/notification.rsindex c47c9677..cab723a6 100644--- a/src-tauri/src/desktop/notification.rs+++ b/src-tauri/src/desktop/notification.rs@@ -1,7 +1,7 @@#[cfg(windows)]use tauri::Manager;-use crate::{utils::app_icon_temp_path, desktop::payload::NativeNotificationPayload};+use crate::{desktop::payload::NativeNotificationPayload, utils::app_icon_temp_path};/// 如果 DSH 插件仍有兜底走浏览器 Notification,则保持“已授权”假象,/// 并让每次 `new Notification(...)` 转成发给宿主窗口的 postMessage。@@ -217,14 +217,18 @@ pub fn enable_notification_permissions(// 避免 set_permission_state(&hstring) 借用的句柄在回调存活期内失效。let hstring_for_callback = hstring.clone();- log::info!("[notification] resetting persisted notification permission for {origin_str}");+ log::info!(+ "[notification] resetting persisted notification permission for {origin_str}"+ );profile4.SetPermissionState(COREWEBVIEW2_PERMISSION_KIND_NOTIFICATIONS,&hstring,COREWEBVIEW2_PERMISSION_STATE_DEFAULT,&SetPermissionStateCompletedHandler::create(Box::new(move |result| {if let Err(e) = result {- log::warn!("[notification] failed to reset permission for {origin_str}: {e}");+ log::warn!(+ "[notification] failed to reset permission for {origin_str}: {e}"+ );} else {log::info!("[notification] reset permission for {origin_str}");}@@ -346,4 +350,4 @@ pub fn enable_notification_permissions(}Ok(())-}\ No newline at end of file+}diff --git a/src-tauri/src/desktop/window.rs b/src-tauri/src/desktop/window.rsindex 0fe58788..c09dd00b 100644--- a/src-tauri/src/desktop/window.rs+++ b/src-tauri/src/desktop/window.rs@@ -3,13 +3,13 @@ use std::sync::atomic::AtomicBool;#[cfg(windows)]use std::sync::Arc;+#[cfg(windows)]+use tauri::webview::{PageLoadEvent, PageLoadPayload};use tauri::{webview::{DownloadEvent, NewWindowFeatures, NewWindowResponse},Emitter, Runtime, Url, Webview,};#[cfg(windows)]-use tauri::webview::{PageLoadEvent, PageLoadPayload};-#[cfg(windows)]use tauri::{WebviewWindow, Wry};use tauri_plugin_opener::OpenerExt;@@ -74,10 +74,8 @@ pub fn on_page_load(// 需要在页面加载时注册;非 Windows 已在 build_main_window 里通过// initialization_script_for_all_frames 注入,这里不需要再做处理。if payload.event() == PageLoadEvent::Started- && !notification_handlers_registered_for_page.swap(- true,- std::sync::atomic::Ordering::SeqCst,- )+ && !notification_handlers_registered_for_page+ .swap(true, std::sync::atomic::Ordering::SeqCst){log::info!("[notification] top-level page load started; scheduling handler registration");let parent = webview_window.clone();diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex cd97d65c..075ec448 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1,10 +1,10 @@mod bridge;mod config;-mod utils;pub mod desktop;mod logger;mod service;mod task;+mod utils;pub fn run() {// Wayland EGL workaround: AppImage bundles WebKitGTK may fail withdiff --git a/src-tauri/src/logger/mod.rs b/src-tauri/src/logger/mod.rsindex c63d7041..c6885e0f 100644--- a/src-tauri/src/logger/mod.rs+++ b/src-tauri/src/logger/mod.rs@@ -13,8 +13,8 @@ use std::path::PathBuf;use std::sync::{Arc, Mutex, OnceLock};use tracing_appender::non_blocking::{NonBlocking, WorkerGuard};-use tracing_subscriber::fmt::time::OffsetTime;use tracing_subscriber::filter::filter_fn;+use tracing_subscriber::fmt::time::OffsetTime;use tracing_subscriber::layer::{Layer, SubscriberExt};use tracing_subscriber::{fmt, util::SubscriberInitExt, EnvFilter};const APP_IDENTIFIER: &str = "io.github.hairyf.deepseek-harness-desktop";@@ -99,14 +99,21 @@ impl SizeRotatingWriter {if let Some(parent) = self.path.parent() {std::fs::create_dir_all(parent)?;}- let f = OpenOptions::new().create(true).append(true).open(&self.path)?;+ let f = OpenOptions::new()+ .create(true)+ .append(true)+ .open(&self.path)?;*guard = Some(f);Ok(())}fn rotate_if_needed(&self) {let len = {let guard = self.file.lock().unwrap_or_else(|e| e.into_inner());- guard.as_ref().and_then(|f| f.metadata().ok()).map(|m| m.len()).unwrap_or(0)+ guard+ .as_ref()+ .and_then(|f| f.metadata().ok())+ .map(|m| m.len())+ .unwrap_or(0)};if len <= self.max_bytes {return;@@ -159,7 +166,11 @@ impl Write for SizeRotatingWriter {}fn flush(&mut self) -> io::Result<()> {let mut guard = self.file.lock().unwrap_or_else(|e| e.into_inner());- if let Some(f) = guard.as_mut() { f.flush() } else { Ok(()) }+ if let Some(f) = guard.as_mut() {+ f.flush()+ } else {+ Ok(())+ }}}@@ -190,7 +201,11 @@ impl<'a> Write for SizeRotatingWriterGuard<'a> {}fn flush(&mut self) -> io::Result<()> {let mut guard = self.parent.file.lock().unwrap_or_else(|e| e.into_inner());- if let Some(f) = guard.as_mut() { f.flush() } else { Ok(()) }+ if let Some(f) = guard.as_mut() {+ f.flush()+ } else {+ Ok(())+ }}}@@ -222,11 +237,14 @@ impl Write for SharedRotatingWriter {}fn flush(&mut self) -> io::Result<()> {let mut guard = self.0.file.lock().unwrap_or_else(|e| e.into_inner());- if let Some(f) = guard.as_mut() { f.flush() } else { Ok(()) }+ if let Some(f) = guard.as_mut() {+ f.flush()+ } else {+ Ok(())+ }}}-impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for SharedRotatingWriter {type Writer = SizeRotatingWriterGuard<'a>;fn make_writer(&'a self) -> Self::Writer {@@ -257,17 +275,25 @@ pub fn init() {// 前端独立文件:desktop.frontdesk.log(与 dsh 的 `target: "dsh"` 标识对称,`target: "frontend"`)if let Some(path) = frontdesk_log_file_path() {let w = Arc::new(Mutex::new(SizeRotatingWriter::new(- path, MAX_LOG_BYTES, MAX_BACKUPS,+ path,+ MAX_LOG_BYTES,+ MAX_BACKUPS,)));let _ = FRONTDESK_WRITER.set(w);}let timer = OffsetTime::new(time::UtcOffset::UTC,- time::format_description::parse_borrowed::<2>("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]Z").unwrap(),+ time::format_description::parse_borrowed::<2>(+ "[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]Z",+ )+ .unwrap(),);let file_timer = OffsetTime::new(time::UtcOffset::UTC,- time::format_description::parse_borrowed::<2>("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]Z").unwrap(),+ time::format_description::parse_borrowed::<2>(+ "[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]Z",+ )+ .unwrap(),);let stdout_layer = fmt::layer().with_writer(std::io::stdout)@@ -355,11 +381,16 @@ pub fn log_frontend(level: FrontendLevel, target: &str, message: &str) {"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]Z",).unwrap();- let ts = now.format(&fmt).unwrap_or_else(|_| "1970-01-01 00:00:00.000Z".to_string());+ let ts = now+ .format(&fmt)+ .unwrap_or_else(|_| "1970-01-01 00:00:00.000Z".to_string());if is_generic_frontend {format!("[{}] {:>5} frontend: {}\n", ts, level_str, message)} else {- format!("[{}] {:>5} frontend: [{}] {}\n", ts, level_str, target, message)+ format!(+ "[{}] {:>5} frontend: [{}] {}\n",+ ts, level_str, target, message+ )}};let bytes = formatted.as_bytes();@@ -386,8 +417,17 @@ mod tests {}#[test]fn frontend_level_parse() {- assert!(matches!(FrontendLevel::from_str("warn"), FrontendLevel::Warn));- assert!(matches!(FrontendLevel::from_str("WARN"), FrontendLevel::Warn));- assert!(matches!(FrontendLevel::from_str("unknown"), FrontendLevel::Info));+ assert!(matches!(+ FrontendLevel::from_str("warn"),+ FrontendLevel::Warn+ ));+ assert!(matches!(+ FrontendLevel::from_str("WARN"),+ FrontendLevel::Warn+ ));+ assert!(matches!(+ FrontendLevel::from_str("unknown"),+ FrontendLevel::Info+ ));}}diff --git a/src-tauri/src/service/cli/mod.rs b/src-tauri/src/service/cli/mod.rsindex 24ab15ee..46ba2c7c 100644--- a/src-tauri/src/service/cli/mod.rs+++ b/src-tauri/src/service/cli/mod.rs@@ -26,7 +26,7 @@ mod path;mod shim;pub use core::{ensure, ensure_shims, get_status, remove, CliLinkStatus};-pub use path::{find_user_pnpm, get_bin_dir, pnpm_env_value};#[cfg(windows)]pub(crate) use path::find_user_pnpm_executable;+pub use path::{find_user_pnpm, get_bin_dir, pnpm_env_value};pub use shim::is_generated_shim;diff --git a/src-tauri/src/service/cli/path.rs b/src-tauri/src/service/cli/path.rsindex e6da1d13..1e026cc4 100644--- a/src-tauri/src/service/cli/path.rs+++ b/src-tauri/src/service/cli/path.rs@@ -457,7 +457,9 @@ fn write_user_path(new_value: &str) -> Result<(), String> {RegCloseKey(hkey);if ret != 0 {- return Err(format!("failed to write HKCU\\Environment\\Path (error {ret})"));+ return Err(format!(+ "failed to write HKCU\\Environment\\Path (error {ret})"+ ));}Ok(())}@@ -512,7 +514,9 @@ fn path_contains_token(path_value: &str, token: &str) -> bool {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(),+ &std::env::var("LOCALAPPDATA")+ .unwrap_or_default()+ .to_lowercase(),"%localappdata%",);let kept: Vec<&str> = path_value@@ -543,9 +547,7 @@ fn inject_shell_rc(app_handle: &AppHandle) -> Result<(), String> {.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"- );+ 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);@@ -727,10 +729,7 @@ mod tests {Some(pnpm_env_path(&cmd)));assert_eq!(- find_windows_executable_pnpm_in_dirs(- &desktop_bin,- std::slice::from_ref(&user_bin)- ),+ 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);@@ -965,7 +964,10 @@ mod tests {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_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);}diff --git a/src-tauri/src/service/cli/shim.rs b/src-tauri/src/service/cli/shim.rsindex 0bc6875f..4c782d42 100644--- a/src-tauri/src/service/cli/shim.rs+++ b/src-tauri/src/service/cli/shim.rs@@ -598,12 +598,8 @@ fn write_shim_file(target: &Path, content: &str) -> Result<(), String> {"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()- )- })?;+ fs::remove_file(target)+ .map_err(|e| format!("remove dangling symlink {} failed: {e}", target.display()))?;}if target.exists() && is_foreign_file(target) {log::warn!(@@ -708,25 +704,36 @@ mod tests {#[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(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(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("/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")+ 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")}@@ -755,7 +762,9 @@ mod tests {#[test]fn cmd_shim_escapes_percent() {- let dir = PathBuf::from(r"C:\Users\100%test\AppData\Roaming\io.github.hairyf.deepseek-harness-desktop");+ let dir = PathBuf::from(+ r"C:\Users\100%test\AppData\Roaming\io.github.hairyf.deepseek-harness-desktop",+ );let content = build_cmd_shim(&dir, &sample_dsh_home());assert!(content.contains("100%%test"));assert!(!content.contains(r#"set "APP_DIR=C:\Users\100%test""#));@@ -775,7 +784,9 @@ mod tests {assert!(content.contains(r"dependencies\git\cmd\git.exe"));assert!(content.contains(r"dependencies\git\cmd;%PATH%"));let system_probe = content.find("git --exec-path").expect("system Git probe");- let bundled_git = content.find(r"dependencies\git\cmd").expect("bundled Git path");+ let bundled_git = content+ .find(r"dependencies\git\cmd")+ .expect("bundled Git path");assert!(system_probe < bundled_git);}for content in [&dsh_ps1, &pnpm_ps1] {@@ -817,13 +828,22 @@ mod tests {std::fs::create_dir_all(&user_dir).unwrap();let shim = shim_dir.join("pnpm.cmd");std::fs::write(&shim, build_pnpm_cmd_shim(&dir.join("app"))).unwrap();- std::fs::write(user_dir.join("pnpm.cmd"), "@echo off\r\necho REAL_USER_PNPM\r\nexit /b 37\r\n").unwrap();+ std::fs::write(+ user_dir.join("pnpm.cmd"),+ "@echo off\r\necho REAL_USER_PNPM\r\nexit /b 37\r\n",+ )+ .unwrap();let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());let system32 = PathBuf::from(&system_root).join("System32");let path = std::env::join_paths([&shim_dir, &user_dir, &system32]).unwrap();let output = std::process::Command::new(system32.join("cmd.exe"))- .args(["/d", "/c"]).arg(&shim).arg("--version")- .env("PATH", path).env("SystemRoot", system_root).output().unwrap();+ .args(["/d", "/c"])+ .arg(&shim)+ .arg("--version")+ .env("PATH", path)+ .env("SystemRoot", system_root)+ .output()+ .unwrap();assert_eq!(output.status.code(), Some(37));assert!(String::from_utf8_lossy(&output.stdout).contains("REAL_USER_PNPM"));let _ = std::fs::remove_dir_all(dir);@@ -835,7 +855,11 @@ mod tests {fn pnpm_cmd_shim_uses_selected_pnpm_with_restricted_path() {let dir = temp_dir("pnpm-selected");let selected = dir.join("selected pnpm.cmd");- std::fs::write(&selected, "@echo off\r\necho SELECTED_PNPM %*\r\nexit /b 37\r\n").unwrap();+ std::fs::write(+ &selected,+ "@echo off\r\necho SELECTED_PNPM %*\r\nexit /b 37\r\n",+ )+ .unwrap();let selected = dunce::canonicalize(&selected).unwrap();assert!(!selected.to_string_lossy().starts_with(r"\\?\"));let shim = dir.join("pnpm.cmd");@@ -843,10 +867,15 @@ mod tests {let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());let system32 = PathBuf::from(&system_root).join("System32");let output = std::process::Command::new(system32.join("cmd.exe"))- .args(["/d", "/c"]).arg(&shim).arg("probe-121")- .env("PATH", &system32).env("SystemRoot", system_root)+ .args(["/d", "/c"])+ .arg(&shim)+ .arg("probe-121")+ .env("PATH", &system32)+ .env("SystemRoot", system_root).env("DSH_PNPM", &selected)- .env("DSH_PREFER_BUNDLED_PNPM", "1").output().unwrap();+ .env("DSH_PREFER_BUNDLED_PNPM", "1")+ .output()+ .unwrap();assert_eq!(output.status.code(), Some(37));assert!(String::from_utf8_lossy(&output.stdout).contains("SELECTED_PNPM probe-121"));let _ = std::fs::remove_dir_all(dir);@@ -870,10 +899,16 @@ mod tests {let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());let system32 = PathBuf::from(&system_root).join("System32");let output = std::process::Command::new(system32.join("cmd.exe"))- .args(["/d", "/c"]).arg(&shim).arg("both-vars")- .env("PATH", &system32).env("SystemRoot", system_root)- .env("DSH_NODE", &node).env("DSH_PNPM", &selected)- .env("DSH_PREFER_BUNDLED_PNPM", "1").output().unwrap();+ .args(["/d", "/c"])+ .arg(&shim)+ .arg("both-vars")+ .env("PATH", &system32)+ .env("SystemRoot", system_root)+ .env("DSH_NODE", &node)+ .env("DSH_PNPM", &selected)+ .env("DSH_PREFER_BUNDLED_PNPM", "1")+ .output()+ .unwrap();let stdout = String::from_utf8_lossy(&output.stdout);assert!(output.status.success());assert!(stdout.contains("BUNDLED"));@@ -902,16 +937,12 @@ mod tests {fn pnpm_ps1_shim_dispatches_exact_path_with_spaces_args_and_exit_code() {let dir = temp_dir("pnpm-ps1-selected");let selected = dir.join("selected pnpm.cmd");- std::fs::write(- &selected,- "@echo off\r\necho SELECTED:%*\r\nexit /b 37\r\n",- )- .unwrap();+ std::fs::write(&selected, "@echo off\r\necho SELECTED:%*\r\nexit /b 37\r\n").unwrap();let shim = dir.join("pnpm.ps1");std::fs::write(&shim, build_pnpm_ps1_shim(&dir.join("app"))).unwrap();let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());- let powershell = PathBuf::from(&system_root)- .join("System32/WindowsPowerShell/v1.0/powershell.exe");+ let powershell =+ PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");let output = std::process::Command::new(powershell).args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]).arg(&shim)@@ -944,8 +975,8 @@ mod tests {let shim = dir.join("pnpm.ps1");std::fs::write(&shim, build_pnpm_ps1_shim(&app_dir)).unwrap();let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());- let powershell = PathBuf::from(&system_root)- .join("System32/WindowsPowerShell/v1.0/powershell.exe");+ let powershell =+ PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");let output = std::process::Command::new(powershell).args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]).arg(&shim)@@ -956,7 +987,11 @@ mod tests {.output().unwrap();let stdout = String::from_utf8_lossy(&output.stdout);- assert!(output.status.success(), "stderr: {}", String::from_utf8_lossy(&output.stderr));+ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );assert!(stdout.contains("BUNDLED"), "unexpected stdout: {stdout:?}");assert!(!stdout.contains("SELECTED"));let _ = std::fs::remove_dir_all(dir);@@ -985,7 +1020,11 @@ mod tests {let dir = temp_dir("pnpm-sh-selected");let selected = dir.join("selected pnpm");- std::fs::write(&selected, "#!/bin/sh\nprintf 'SELECTED:%s\\n' \"$*\"\nexit 37\n").unwrap();+ std::fs::write(+ &selected,+ "#!/bin/sh\nprintf 'SELECTED:%s\\n' \"$*\"\nexit 37\n",+ )+ .unwrap();let mut permissions = std::fs::metadata(&selected).unwrap().permissions();permissions.set_mode(0o700);std::fs::set_permissions(&selected, permissions).unwrap();@@ -1003,7 +1042,10 @@ mod tests {.output().unwrap();assert_eq!(output.status.code(), Some(37));- assert_eq!(String::from_utf8_lossy(&output.stdout), "SELECTED:alpha beta gamma\n");+ assert_eq!(+ String::from_utf8_lossy(&output.stdout),+ "SELECTED:alpha beta gamma\n"+ );let _ = std::fs::remove_dir_all(dir);}@@ -1098,7 +1140,9 @@ mod tests {#[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");+ let dir = PathBuf::from(+ r"C:\Users\o'brien\AppData\Roaming\io.github.hairyf.deepseek-harness-desktop",+ );let content = build_ps1_shim(&dir, &sample_dsh_home());assert!(content.contains(r"o''brien"));// dsh_home 同样走 ps1 转义@@ -1145,17 +1189,17 @@ mod tests {#[test]fn foreign_file_detection() {- let dir = std::env::temp_dir().join(format!(- "dsh-shim-test-{}",- std::process::id()- ));+ 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");+ assert!(+ is_foreign_file(&user_dsh),+ "user file must be treated as foreign"+ );// 本应用生成的 shim -> 不是 foreign,可覆盖#[cfg(not(windows))]@@ -1163,7 +1207,10 @@ mod tests {#[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");+ assert!(+ !is_foreign_file(&user_dsh),+ "generated shim must not be foreign"+ );let _ = std::fs::remove_dir_all(&dir);}@@ -1256,7 +1303,11 @@ mod tests {).unwrap();- write_shim_file(&target, "#!/bin/sh\n# DeepSeek Harness Desktop - new 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(),diff --git a/src-tauri/src/service/core/local.rs b/src-tauri/src/service/core/local.rsindex ab8efc2c..d24f350d 100644--- a/src-tauri/src/service/core/local.rs+++ b/src-tauri/src/service/core/local.rs@@ -188,13 +188,17 @@ fn local_core_uses_pnpm(app_handle: &AppHandle) -> bool {};let prefixes = prefix_candidates(&bin);// npm 布局命中(node_modules 包存在)→ npm 管理- let npm_layout = prefixes.iter().any(|p| {- probe_package_dir(p).is_some() || probe_package_dir(&p.join("lib")).is_some()- });+ let npm_layout = prefixes+ .iter()+ .any(|p| probe_package_dir(p).is_some() || probe_package_dir(&p.join("lib")).is_some());// pnpm 布局:`<prefix>/global/<n>/node_modules/@deepseek-ai/dsh` 命中 → pnpm 管理let pnpm_layout = prefixes.iter().any(|p| {std::fs::read_dir(p.join("global"))- .map(|entries| entries.flatten().any(|e| probe_package_dir(&e.path()).is_some()))+ .map(|entries| {+ entries+ .flatten()+ .any(|e| probe_package_dir(&e.path()).is_some())+ }).unwrap_or(false)});!npm_layout && pnpm_layout@@ -215,18 +219,30 @@ pub async fn update_local_core(app_handle: AppHandle) -> Result<String, String>let (pm, args): (&str, Vec<String>) = if uses_pnpm {("pnpm",- vec!["add".to_string(), "-g".to_string(), "@deepseek-ai/dsh@latest".to_string()],+ vec![+ "add".to_string(),+ "-g".to_string(),+ "@deepseek-ai/dsh@latest".to_string(),+ ],)} else {("npm",- vec!["install".to_string(), "-g".to_string(), "@deepseek-ai/dsh@latest".to_string()],+ vec![+ "install".to_string(),+ "-g".to_string(),+ "@deepseek-ai/dsh@latest".to_string(),+ ],)};log::info!("Updating local dsh core via `{pm} {args:?}`");// GUI 进程下 npm/pnpm 均以控制台程序方式派生子进程,Windows 上需隐藏窗口- let program = if cfg!(windows) { format!("{pm}.cmd") } else { pm.to_string() };+ let program = if cfg!(windows) {+ format!("{pm}.cmd")+ } else {+ pm.to_string()+ };let (status, stdout, stderr) = tauri::async_runtime::spawn_blocking(move || {let mut cmd = std::process::Command::new(&program);cmd.args(&args);@@ -285,10 +301,7 @@ mod tests {r#"{"name":"@deepseek-ai/dsh","version":"0.1.0-rc.8"}"#,).unwrap();- assert_eq!(- read_package_version(&dir).as_deref(),- Some("0.1.0-rc.8")- );+ assert_eq!(read_package_version(&dir).as_deref(), Some("0.1.0-rc.8"));std::fs::remove_dir_all(&dir).ok();}@@ -318,7 +331,11 @@ mod tests {fn write_our_shim(dir: &std::path::Path) -> std::path::PathBuf {std::fs::create_dir_all(dir).unwrap();let p = dir.join("dsh");- std::fs::write(&p, "# DeepSeek Harness Desktop - dsh command shim (generated)\n").unwrap();+ std::fs::write(+ &p,+ "# DeepSeek Harness Desktop - dsh command shim (generated)\n",+ )+ .unwrap();p}@@ -328,10 +345,7 @@ mod tests {fn scan_dir_finds_foreign_dsh_inside_shim_dir() {let dir = temp_dir("foreign-in-shim");let dsh = write_foreign_dsh(&dir);- assert_eq!(- scan_dirs_for_user_dsh(&[dir.clone()], &["dsh"]),- Some(dsh)- );+ assert_eq!(scan_dirs_for_user_dsh(&[dir.clone()], &["dsh"]), Some(dsh));let _ = std::fs::remove_dir_all(&dir);}@@ -395,7 +409,12 @@ mod tests {// npm 布局命中 `~/.local` 前缀下的 `<prefix>/lib/node_modules/...`assert_eq!(package_dir_from_bin(&bin),- Some(root.join("lib").join("node_modules").join("@deepseek-ai").join("dsh"))+ Some(+ root.join("lib")+ .join("node_modules")+ .join("@deepseek-ai")+ .join("dsh")+ ));let _ = std::fs::remove_dir_all(&root);}diff --git a/src-tauri/src/service/core/version.rs b/src-tauri/src/service/core/version.rsindex 4866aa1f..b01082e5 100644--- a/src-tauri/src/service/core/version.rs+++ b/src-tauri/src/service/core/version.rs@@ -66,7 +66,10 @@ pub async fn list(app_handle: &AppHandle) -> Vec<HarnessCore> {let mut rows: Vec<HarnessCore> = vec![HarnessCore {id: "local".to_string(),source: CoreSource::Local,- version: local.as_ref().map(|c| c.version.clone()).unwrap_or_default(),+ version: local+ .as_ref()+ .map(|c| c.version.clone())+ .unwrap_or_default(),tag: String::new(),path: local_bin.clone().unwrap_or_default(),dir: local@@ -98,7 +101,10 @@ pub async fn list(app_handle: &AppHandle) -> Vec<HarnessCore> {let tags = match download::fetch_dsh_pkg_tags().await {Ok(tags) => tags,Err(e) => {- log::warn!("Failed to fetch dsh pkg tags ({}), showing only on-disk versions", e);+ log::warn!(+ "Failed to fetch dsh pkg tags ({}), showing only on-disk versions",+ e+ );Vec::new()}};@@ -302,13 +308,15 @@ async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), Strbackup_dir.display()));}- download::rename_with_retry(&active_dir, &backup_dir).await.map_err(|e| {- format!(- "CORE_SWITCH_FAILED: {} -> {}: {e}",- active_dir.display(),- backup_dir.display()- )- })?;+ download::rename_with_retry(&active_dir, &backup_dir)+ .await+ .map_err(|e| {+ format!(+ "CORE_SWITCH_FAILED: {} -> {}: {e}",+ active_dir.display(),+ backup_dir.display()+ )+ })?;}// 2. 目标版本进入激活位;失败回滚@@ -372,8 +380,7 @@ pub async fn download_version(app_handle: &AppHandle, tag: &str) -> Result<Harnelet buffer = download::download_file_from_sources(&tracker, urls).await.map_err(|e| format!("CORE_DOWNLOAD_FAILED: {e}"))?;- download::verify_sha256(&buffer, &digest)- .map_err(|e| format!("CORE_INTEGRITY_FAILED: {e}"))?;+ download::verify_sha256(&buffer, &digest).map_err(|e| format!("CORE_INTEGRITY_FAILED: {e}"))?;tracker.end_phase();let name = info.asset_url@@ -401,7 +408,9 @@ pub async fn remove_version(app_handle: &AppHandle, id: &str) -> Result<(), Strifs_guard::validate_id(tag)?;let cur_tag = config::get_dsh_pkg_tag(app_handle);if cur_tag.as_deref() == Some(tag) && active_source(app_handle) == CoreSource::App {- return Err(format!("CORE_ACTIVE_VERSION: cannot remove in-use version {tag}"));+ return Err(format!(+ "CORE_ACTIVE_VERSION: cannot remove in-use version {tag}"+ ));}let dir = existing_slot_dir(app_handle, tag).ok_or_else(|| format!("CORE_VERSION_NOT_FOUND: {tag}"))?;@@ -423,7 +432,10 @@ pub async fn remove_version(app_handle: &AppHandle, id: &str) -> Result<(), Stri/// 解析激活预打包核心的版本号:优先记录 tag(`dsh-<version>-<commit>`),/// 解析不出(无 tag 记录/格式不符)时用安装目录清单版本兜底。-fn active_app_version(active_tag: &Option<String>, manifest_version: Option<String>) -> Option<String> {+fn active_app_version(+ active_tag: &Option<String>,+ manifest_version: Option<String>,+) -> Option<String> {active_tag.as_deref().and_then(download::parse_version_from_tag)diff --git a/src-tauri/src/service/download/core.rs b/src-tauri/src/service/download/core.rsindex 219036dd..717d47ed 100644--- a/src-tauri/src/service/download/core.rs+++ b/src-tauri/src/service/download/core.rs@@ -110,8 +110,15 @@ async fn download_with_retry<'a, R: Runtime>();tokio::time::sleep(delay).await;}- match download_attempt(&client, tracker, url, attempt, MAX_DOWNLOAD_ATTEMPTS, &mut buffer)- .await+ match download_attempt(+ &client,+ tracker,+ url,+ attempt,+ MAX_DOWNLOAD_ATTEMPTS,+ &mut buffer,+ )+ .await{Ok(()) => {log::info!("Download completed, {} bytes total", buffer.len());@@ -230,7 +237,12 @@ async fn download_attempt<'a, R: Runtime>();}- log::info!("Download attempt {}/{} succeeded, {} bytes in buffer", attempt, max_attempts, buffer.len());+ log::info!(+ "Download attempt {}/{} succeeded, {} bytes in buffer",+ attempt,+ max_attempts,+ buffer.len()+ );Ok(())}@@ -573,10 +585,7 @@ fn github_client() -> Result<reqwest::Client, String> {/// 带 GitHub 未认证限流(403)冷却:冷却期内直接返回 Err(由调用方走兜底来源),/// 命中 403 时记录冷却开始。返回的 `reqwest::Response` 已通过 `error_for_status`,/// 403 已被拦截并标记冷却,不会作为普通错误继续向下传输。-async fn github_api_get(- client: &reqwest::Client,- url: &str,-) -> Result<reqwest::Response, String> {+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());}@@ -600,12 +609,13 @@ async fn fetch_releases_latest(client: &reqwest::Client) -> Result<serde_json::V/// 通过 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}"))?;+ 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())@@ -752,9 +762,7 @@ pub async fn fetch_latest_dsh_pkg_info() -> Result<LatestDshPkg, String> {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"- );+ 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",@@ -769,14 +777,15 @@ pub async fn fetch_latest_dsh_pkg_info() -> Result<LatestDshPkg, String> {// 4. 资产 URL 与摘要:仅 API 可达时资产/摘要可信;否则 URL 平台确定性回退、digest=Nonelet (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| {+ 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())@@ -838,22 +847,25 @@ pub async fn fetch_dsh_pkg_asset(tag: &str) -> Result<LatestDshPkg, 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 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| {+ 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())+ 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())@@ -1045,7 +1057,10 @@ mod tests {// 尚未开始且总长未知也不产生 NaNassert_eq!(download_progress_percent(0, 0), -1.0);// 数值绝对不出现非有限值- for pct in [download_progress_percent(50, 0), download_progress_percent(0, 0)] {+ for pct in [+ download_progress_percent(50, 0),+ download_progress_percent(0, 0),+ ] {assert!(pct.is_finite(), "progress must be finite, got {pct}");}}@@ -1070,7 +1085,9 @@ mod tests {assert!(validate_download_url("https://example.com/file.zip").is_err());// 国内镜像源(含 npmmirror 302 后的最终落地域名)assert!(validate_download_url("https://npmmirror.com/mirrors/node/v22/file.zip").is_ok());- assert!(validate_download_url("https://cdn.npmmirror.com/binaries/node/v22/file.zip").is_ok());+ assert!(+ validate_download_url("https://cdn.npmmirror.com/binaries/node/v22/file.zip").is_ok()+ );assert!(validate_download_url("https://registry.npmmirror.com/pnpm/-/pnpm.tgz").is_ok());assert!(validate_download_url("https://ghfast.top/https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/latest/download/deepseek-harness-pkg-windows.zip"@@ -1108,7 +1125,10 @@ mod tests {commit_staged_install(&staging, &dest, &backup).await.expect("recover and commit");- assert_eq!(fs::read_to_string(dest.join("version.txt")).unwrap(), "next");+ assert_eq!(+ fs::read_to_string(dest.join("version.txt")).unwrap(),+ "next"+ );assert!(!backup.exists());fs::remove_dir_all(root).ok();}@@ -1139,8 +1159,7 @@ mod tests {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");+ let got = parse_digest_from_expanded_assets(html, "deepseek-harness-pkg-windows.zip");assert_eq!(got.as_deref(),Some("sha256:4d5416766eb4a66e81b83532abeea64de7e7e2e0bac69a4f0c0508e1d91936c0")@@ -1152,7 +1171,10 @@ mod tests {);// 摘要缺失 → Noneassert_eq!(- parse_digest_from_expanded_assets("<p>no digest here</p>", "deepseek-harness-pkg-windows.zip"),+ parse_digest_from_expanded_assets(+ "<p>no digest here</p>",+ "deepseek-harness-pkg-windows.zip"+ ),None);}diff --git a/src-tauri/src/service/download/mod.rs b/src-tauri/src/service/download/mod.rsindex 3db86a7e..1091eadb 100644--- a/src-tauri/src/service/download/mod.rs+++ b/src-tauri/src/service/download/mod.rs@@ -12,9 +12,9 @@ pub use core::{};// 供核心面板切换版本时使用(跨模块内部接口,不进公共 API)pub(crate) use core::{remove_dir_with_retry, rename_with_retry};-pub use installable::{Dsh, Installable, Nodejs, Pnpm};#[cfg(windows)]pub use installable::Git;+pub use installable::{Dsh, Installable, Nodejs, Pnpm};pub use progress::ProgressTracker;// GitHub API 限流冷却器:任何访问 api.github.com 的服务都应收敛到这一个入口pub use utils::github_api;diff --git a/src-tauri/src/service/download/progress.rs b/src-tauri/src/service/download/progress.rsindex de4aa9ea..5e648307 100644--- a/src-tauri/src/service/download/progress.rs+++ b/src-tauri/src/service/download/progress.rs@@ -56,7 +56,10 @@ impl<'a, R: Runtime> ProgressTracker<'a, R> {let now = Instant::now();// 中毒安全:若 install 过程中已有 panic 污染该锁,后续不应再次 panic// 导致整个桌面进程退出,这里忽略中毒状态继续读取旧值。- let mut last_emit = self.last_emit_time.lock().unwrap_or_else(|e| e.into_inner());+ let mut last_emit = self+ .last_emit_time+ .lock()+ .unwrap_or_else(|e| e.into_inner());// 节流处理:如果距离上次发送不足 50ms,则跳过if let Some(last_time) = *last_emit {diff --git a/src-tauri/src/service/fs_guard.rs b/src-tauri/src/service/fs_guard.rsindex 7cfacc2d..f18bf80a 100644--- a/src-tauri/src/service/fs_guard.rs+++ b/src-tauri/src/service/fs_guard.rs@@ -48,10 +48,8 @@ pub fn validate_id(id: &str) -> Result<(), String> {/// (`/data/foobar` 不作为 `/data/foo` 的子路径)以及 `..`、符号链接改写。/// `root` 不存在时(尚未初始化)直接拒绝——删除操作的前提是父目录存在。pub fn ensure_within(child: &Path, root: &Path) -> Result<PathBuf, String> {- let root_real = dunce::canonicalize(root)- .map_err(|e| format!("ROOT_RESOLVE_FAILED: {e}"))?;- let child_real = dunce::canonicalize(child)- .map_err(|e| format!("PATH_RESOLVE_FAILED: {e}"))?;+ let root_real = dunce::canonicalize(root).map_err(|e| format!("ROOT_RESOLVE_FAILED: {e}"))?;+ let child_real = dunce::canonicalize(child).map_err(|e| format!("PATH_RESOLVE_FAILED: {e}"))?;if !child_real.starts_with(&root_real) {return Err(format!("PATH_ESCAPE_REJECTED: {} is outside {}",@@ -97,7 +95,9 @@ mod tests {#[test]fn validate_id_rejects_traversal() {- for bad in ["..", ".", "../x", "..\\x", "/etc", "\\etc", "a/b", "a b", "a\tb", "a:b"] {+ for bad in [+ "..", ".", "../x", "..\\x", "/etc", "\\etc", "a/b", "a b", "a\tb", "a:b",+ ] {assert!(validate_id(bad).is_err(), "should reject {bad:?}");}for good in ["web", "my-profile", "dsh-1.2.3", "plugin-a_b", "app-7"] {diff --git a/src-tauri/src/service/migrate.rs b/src-tauri/src/service/migrate.rsindex 1895eab7..7b69055e 100644--- a/src-tauri/src/service/migrate.rs+++ b/src-tauri/src/service/migrate.rs@@ -104,12 +104,8 @@ fn migrate_impl(legacy: &Path, target: &Path) -> Result<(), String> {merge_tree(legacy, target)?;// merge 也可能把 node_modules 无损搬入(目标缺失时),同样清除 pnpm 元数据purge_carried_pnpm_metadata(target);- fs::remove_dir_all(legacy).map_err(|e| {- format!(- "remove legacy {} after merge failed: {e}",- legacy.display()- )- })+ fs::remove_dir_all(legacy)+ .map_err(|e| format!("remove legacy {} after merge failed: {e}", legacy.display()))}/// 递归把 `src` 目录树合并进 `dst`:@@ -121,9 +117,7 @@ fn migrate_impl(legacy: &Path, target: &Path) -> Result<(), String> {/// 在合并完成后统一清除其中的 pnpm 元数据(见 `purge_carried_pnpm_metadata`)。fn merge_tree(src: &Path, dst: &Path) -> Result<(), String> {fs::create_dir_all(dst).map_err(|e| format!("create {} failed: {e}", dst.display()))?;- for entry in fs::read_dir(src)- .map_err(|e| format!("read {} failed: {e}", src.display()))?- {+ for entry in fs::read_dir(src).map_err(|e| format!("read {} failed: {e}", src.display()))? {let entry = entry.map_err(|e| format!("read_dir entry failed: {e}"))?;let name = entry.file_name();let src_path = entry.path();@@ -148,7 +142,11 @@ fn merge_tree(src: &Path, dst: &Path) -> Result<(), String> {}} else if !dst_path.exists() || src_newer(&src_path, &dst_path) {fs::copy(&src_path, &dst_path).map_err(|e| {- format!("copy {} -> {} failed: {e}", src_path.display(), dst_path.display())+ format!(+ "copy {} -> {} failed: {e}",+ src_path.display(),+ dst_path.display()+ )})?;}}@@ -272,10 +270,8 @@ mod tests {/// 构造一个带内容与 mtime 的临时目录树,返回 (root, 清理守卫)。fn temp_dir(tag: &str) -> PathBuf {- let dir = std::env::temp_dir().join(format!(- "dsh-migrate-test-{}-{tag}",- std::process::id()- ));+ let dir =+ std::env::temp_dir().join(format!("dsh-migrate-test-{}-{tag}", std::process::id()));let _ = fs::remove_dir_all(&dir);fs::create_dir_all(&dir).unwrap();dir@@ -291,7 +287,8 @@ mod tests {fn set_mtime(path: &Path, secs_since_epoch: u64) {let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs_since_epoch);let f = fs::OpenOptions::new().write(true).open(path).unwrap();- f.set_times(std::fs::FileTimes::new().set_modified(t)).unwrap();+ f.set_times(std::fs::FileTimes::new().set_modified(t))+ .unwrap();}// ------------------------------------------------------------------@@ -306,7 +303,10 @@ mod tests {write(&legacy.join("settings.yaml"), "theme: dark\n");write(&legacy.join("sessions/s1/data.json"), "{}");- write(&legacy.join("profiles/web/package.json"), "{\"name\":\"web\"}");+ write(+ &legacy.join("profiles/web/package.json"),+ "{\"name\":\"web\"}",+ );write(&legacy.join("profiles/web/node_modules/x/index.js"), "// x");// 旧版 pnpm 元数据记录了旧位置的绝对路径 → 迁移后必须清除(issue #103)write(@@ -322,12 +322,16 @@ mod tests {assert!(target.join("profiles/web/package.json").is_file());// rename 无损搬移:node_modules 一并带入(不丢依赖)assert!(- target.join("profiles/web/node_modules/x/index.js").is_file(),+ target+ .join("profiles/web/node_modules/x/index.js")+ .is_file(),"rename must carry node_modules over losslessly");// 但 pnpm 安装元数据必须清除,否则任何 pnpm 操作都会因旧路径抛错assert!(- !target.join("profiles/web/node_modules/.modules.yaml").exists(),+ !target+ .join("profiles/web/node_modules/.modules.yaml")+ .exists(),"carried pnpm .modules.yaml must be purged");}@@ -366,8 +370,14 @@ mod tests {// target 独有 → 保留write(&target.join("only-target.txt"), "T");// node_modules 两边都有 → 保留目标- write(&legacy.join("profiles/web/node_modules/p/index.js"), "// legacy p");- write(&target.join("profiles/web/node_modules/p/index.js"), "// target p");+ write(+ &legacy.join("profiles/web/node_modules/p/index.js"),+ "// legacy p",+ );+ write(+ &target.join("profiles/web/node_modules/p/index.js"),+ "// target p",+ );migrate_impl(&legacy, &target).unwrap();@@ -397,17 +407,24 @@ mod tests {let target = temp_dir("b-nm-target");write(&legacy.join("profiles/web/node_modules/x/index.js"), "// x");- write(&legacy.join("profiles/web/node_modules/.modules.yaml"), "virtualStoreDir: C:\\legacy\\node_modules\\.pnpm\n");+ write(+ &legacy.join("profiles/web/node_modules/.modules.yaml"),+ "virtualStoreDir: C:\\legacy\\node_modules\\.pnpm\n",+ );write(&legacy.join("profiles/web/package.json"), "{}");migrate_impl(&legacy, &target).unwrap();assert!(target.join("profiles/web/package.json").is_file());assert!(- target.join("profiles/web/node_modules/x/index.js").is_file(),+ target+ .join("profiles/web/node_modules/x/index.js")+ .is_file(),"legacy node_modules is carried over when target has none");assert!(- !target.join("profiles/web/node_modules/.modules.yaml").exists(),+ !target+ .join("profiles/web/node_modules/.modules.yaml")+ .exists(),"carried pnpm metadata must be purged after merge too");}@@ -507,7 +524,10 @@ mod tests {fs::create_dir_all(&vsd).unwrap();write(&node_modules.join(".modules.yaml"),- &format!("lockfileVersion: '9.0'\nvirtualStoreDir: {}\n", vsd.display()),+ &format!(+ "lockfileVersion: '9.0'\nvirtualStoreDir: {}\n",+ vsd.display()+ ),);heal_stale_pnpm_metadata(&home).unwrap();diff --git a/src-tauri/src/service/plugin/cancel.rs b/src-tauri/src/service/plugin/cancel.rsindex 129da9d9..6e33d2c3 100644--- a/src-tauri/src/service/plugin/cancel.rs+++ b/src-tauri/src/service/plugin/cancel.rs@@ -94,4 +94,4 @@ pub async fn cancel(app_handle: &AppHandle) {if let Some(window) = app_handle.get_webview_window("main") {let _ = window.emit(PREINSTALL_CANCEL_EVENT, PreinstallCancelPayload {});}-}\ No newline at end of file+}diff --git a/src-tauri/src/service/plugin/errors.rs b/src-tauri/src/service/plugin/errors.rsindex 1b1572cc..5dd66feb 100644--- a/src-tauri/src/service/plugin/errors.rs+++ b/src-tauri/src/service/plugin/errors.rs@@ -50,12 +50,7 @@ fn save(app_handle: &AppHandle, map: &HashMap<String, PluginError>) -> Result<()}/// 记录插件错误(同 id 幂等覆盖)-pub fn record(- app_handle: &AppHandle,- id: &str,- action: &str,- message: &str,-) -> Result<(), String> {+pub fn record(app_handle: &AppHandle, id: &str, action: &str, message: &str) -> Result<(), String> {let mut map = load(app_handle);map.insert(id.to_string(),@@ -98,6 +93,9 @@ mod tests {let json = serde_json::to_string(&map).unwrap();let back: HashMap<String, PluginError> = serde_json::from_str(&json).unwrap();assert_eq!(back.get("dshmarket").unwrap().action, "install");- assert_eq!(back.get("dshmarket").unwrap().message, "ERR_PNPM_IGNORED_BUILDS");+ assert_eq!(+ back.get("dshmarket").unwrap().message,+ "ERR_PNPM_IGNORED_BUILDS"+ );}}diff --git a/src-tauri/src/service/plugin/install.rs b/src-tauri/src/service/plugin/install.rsindex 8a4dcf62..7421e306 100644--- a/src-tauri/src/service/plugin/install.rs+++ b/src-tauri/src/service/plugin/install.rs@@ -26,10 +26,10 @@ 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 std::collections::HashMap;use std::ffi::OsString;use std::path::{Path, PathBuf};-use serde_yaml::{Mapping, Value};use tauri::{AppHandle, Emitter, Manager, WebviewWindow};use super::errors;@@ -59,10 +59,8 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin// 单次读取预设并构建查找表,提升算法效率至 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 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 {@@ -87,7 +85,10 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin// 对账的 `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))?);+ let raw = normalize_git_spec(&preset_spec_for_install(+ preset,+ bundled_dir_of(app_handle, preset),+ )?);specs.push(shell_quote_spec(&raw));}@@ -151,13 +152,7 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin// 后重试,直至成功或再无键可加(升级路径同样依赖该重试,见// [`run_plugin_with_allow_build_retry`])。let (exit_code, last_output) = run_plugin_with_allow_build_retry(- app_handle,- &node,- &args,- &cwd,- &envs,- &window,- "install",+ app_handle, &node, &args, &cwd, &envs, &window, "install",).await?;@@ -338,7 +333,10 @@ fn silent_install_failure_detail(missing: &[(String, PathBuf)], command_output:////// 供本模块的安装/升级/卸载与 [`super::verify`] 的完整性修复共用:子进程(dsh/// 或 pnpm)都按同一套桌面端环境策略运行,保证 $DSH_HOME / PATH 布局一致。-pub(crate) fn build_plugin_envs(app_handle: &AppHandle, prefer_bundled_pnpm: bool) -> HashMap<String, String> {+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 与应用进程不同,@@ -437,9 +435,7 @@ async fn run_plugin_with_allow_build_retry(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})"- );+ log::info!("pnpm allowBuilds updated with {new_keys:?}, retrying {action} ({retries})");let _ = window.emit(PREINSTALL_LOG_EVENT,PreinstallLogPayload {@@ -479,15 +475,24 @@ fn append_command_output(all_output: &mut String, captured: &str) {/// 升级单个插件:`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+ 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;+ 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 甚至会@@ -573,21 +578,14 @@ async fn run_single_plugin_command(let cwd = config::get_dsh_install_path(app_handle);log::info!("Running dsh plugin {action} for {id}");- let (exit_code, output) = run_plugin_with_allow_build_retry(- app_handle,- &node,- &args,- &cwd,- &envs,- &window,- action,- )- .await?;+ let (exit_code, output) =+ run_plugin_with_allow_build_retry(app_handle, &node, &args, &cwd, &envs, &window, action)+ .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 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()@@ -724,7 +722,9 @@ async fn ensure_pnpm(app_handle: &AppHandle, window: &WebviewWindow) -> Result<b);}None => {- log::warn!("User pnpm version not detectable (broken/blocked shim?), using bundled pnpm");+ log::warn!(+ "User pnpm version not detectable (broken/blocked shim?), using bundled pnpm"+ );}}@@ -810,9 +810,9 @@ pub(crate) fn profile_store_major(app_handle: &AppHandle) -> Option<u32> {/// 从 `.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)- })?;+ 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(['"', '\''])@@ -897,7 +897,11 @@ fn parse_allowlist_keys(output: &str) -> Vec<String> {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('#') {+ } else if !next.starts_with(' ')+ && !next.starts_with('\t')+ && !trimmed.is_empty()+ && !trimmed.starts_with('#')+ {break; // 顶层键(无缩进且非列表项),已离开列表}// 其余(缩进行的非列表项、空行、注释):继续扫描@@ -953,7 +957,7 @@ fn extract_only_builds_git_name(line: &str) -> Option<String> {let rest = &line[start..];let end = rest.find('"')?;let quoted = &rest[..end]; // "name@version"- // 包名(含 scoped 前缀 `@scope/name`)在最末一个 `@` 之前,版本号在之后。+ // 包名(含 scoped 前缀 `@scope/name`)在最末一个 `@` 之前,版本号在之后。let (name, _version) = quoted.rsplit_once('@')?;(!name.is_empty()).then(|| name.to_string())}@@ -1007,8 +1011,7 @@ fn add_allow_build_keys(app_handle: &AppHandle, keys: &[String]) -> Result<(), Sstd::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}"))?+ 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()@@ -1019,7 +1022,10 @@ fn add_allow_build_keys(app_handle: &AppHandle, keys: &[String]) -> Result<(), Sreturn Ok(()); // 无变化(所有键已就位),避免无意义写盘}- log::info!("pnpm-workspace.yaml rewritten with allowBuilds {keys:?} at {}", path.display());+ 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}"))}@@ -1043,14 +1049,11 @@ fn apply_allow_build_keys(content: &str, keys: &[String]) -> Result<String, StriErr(first_err) => {let normalized = collapse_allow_builds_duplicates(content);if normalized == content {- return Err(format!(- "PREINSTALL_WORKSPACE_INVALID_YAML: {first_err}"- ));+ 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}")- })?+ serde_yaml::from_str(&normalized)+ .map_err(|e| format!("PREINSTALL_WORKSPACE_INVALID_YAML: {e}"))?}};@@ -1252,16 +1255,27 @@ fn shell_quote_spec(spec: &str) -> String {/// 子进程错误。代理、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",+ "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(- "网络连接失败,请检查网络或代理设置后重试。",- )+ SIGNALS+ .iter()+ .any(|signal| lower.contains(signal))+ .then_some("网络连接失败,请检查网络或代理设置后重试。")}fn git_transport_hint(output: &str) -> Option<&'static str> {@@ -1319,10 +1333,16 @@ pub(crate) fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> bool {#[cfg(test)]mod tests {- use std::path::PathBuf;- use super::{append_command_output, apply_allow_build_keys, collapse_allow_builds_duplicates, dep_path_to_name, extract_allow_line_key, extract_only_builds_git_name, git_transport_hint, normalize_git_spec, parse_allowlist_keys, parse_store_major_from_modules_yaml, preset_spec_for_install, shell_quote_spec, silent_install_failure_detail, PreinstallPluginInfo};#[cfg(unix)]use super::pnpm_major_version_at;+ use super::{+ append_command_output, apply_allow_build_keys, collapse_allow_builds_duplicates,+ dep_path_to_name, extract_allow_line_key, extract_only_builds_git_name, git_transport_hint,+ normalize_git_spec, parse_allowlist_keys, parse_store_major_from_modules_yaml,+ preset_spec_for_install, shell_quote_spec, silent_install_failure_detail,+ PreinstallPluginInfo,+ };+ use std::path::PathBuf;#[cfg(unix)]#[test]@@ -1334,10 +1354,8 @@ mod tests {.duration_since(UNIX_EPOCH).unwrap().as_nanos();- let root = std::env::temp_dir().join(format!(- "dsh-pnpm-major-{}-{nonce}",- std::process::id()- ));+ 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");@@ -1375,10 +1393,7 @@ mod tests {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, None).unwrap(), "dshmarket");assert_eq!(preset_spec_for_install(&p, Some(PathBuf::from("/ignored"))).unwrap(),"dshmarket"@@ -1469,7 +1484,9 @@ virtualStoreDir: node_modules/.pnpm#[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"),+ parse_store_major_from_modules_yaml(+ "storeDir: /home/test/.local/share/pnpm/store/v11\n"+ ),Some(11));assert_eq!(@@ -1481,7 +1498,10 @@ virtualStoreDir: node_modules/.pnpm#[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("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"),@@ -1499,7 +1519,10 @@ 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@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"+ .to_string()+ ));assert!(!keys.contains(&"dsh-better-sidebar".to_string()));}@@ -1588,7 +1611,10 @@ onlyBuiltDependencies:None);// 非 git 门禁行不匹配- assert_eq!(extract_only_builds_git_name("allowBuilds:\n x: true"), None);+ assert_eq!(+ extract_only_builds_git_name("allowBuilds:\n x: true"),+ None+ );}#[test]@@ -1690,8 +1716,9 @@ 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 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@@ -1720,25 +1747,28 @@ onlyBuiltDependencies:.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();+ 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 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)));+ 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()+ "dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89"+ .to_string())],serde_yaml::Value::Bool(true));@@ -1758,7 +1788,9 @@ onlyBuiltDependencies:// 序列化后全局不允许再出现“重复键”的等价行(node-pty 只出现一次)let node_pty_keys = out.lines()- .filter(|l| l.trim_start().starts_with("node-pty") || l.trim_start().starts_with("'node-pty'"))+ .filter(|l| {+ l.trim_start().starts_with("node-pty") || l.trim_start().starts_with("'node-pty'")+ }).count();assert_eq!(node_pty_keys, 1);}@@ -1771,13 +1803,18 @@ onlyBuiltDependencies:// 重复的 node-pty 只剩最后一个(值 true),同键不再重复let node_pty = normalized.lines()- .filter(|l| l.trim_start().starts_with("node-pty") || l.trim_start().starts_with("'node-pty'"))+ .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)));+ assert_eq!(+ allow_builds_map(&out).get("node-pty"),+ Some(&serde_yaml::Value::Bool(true))+ );}// ---- git GitHub 简写规范化(issue #51 根因绕行)----@@ -1843,7 +1880,10 @@ onlyBuiltDependencies:shell_quote_spec("link:/Applications/Deepseek Harness Desktop.app/Contents/Resources/resources/preset-plugins/dsh-tauri-ui"),"link:/Applications/Deepseek Harness Desktop.app/Contents/Resources/resources/preset-plugins/dsh-tauri-ui");- assert_eq!(shell_quote_spec("link:/Users/me/my plugins/dsh-tauri"), "link:/Users/me/my plugins/dsh-tauri");+ assert_eq!(+ shell_quote_spec("link:/Users/me/my plugins/dsh-tauri"),+ "link:/Users/me/my plugins/dsh-tauri"+ );}#[test]@@ -1865,7 +1905,8 @@ onlyBuiltDependencies:#[test]fn shell_quote_preserves_link_prefix_semantics() {// 引号只包 path 部分也不影响 pnpm 解析(落盘值仍为不带引号的 link: 规范形)- let quoted = shell_quote_spec("link:G:/Deepseek Harness Desktop/resources/preset-plugins/dsh-tauri");+ let quoted =+ shell_quote_spec("link:G:/Deepseek Harness Desktop/resources/preset-plugins/dsh-tauri");assert!(quoted.starts_with('"'));assert!(quoted.ends_with('"'));assert!(quoted.contains("Deepseek Harness Desktop"));@@ -1882,7 +1923,10 @@ onlyBuiltDependencies:#[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());+ assert!(+ git_transport_hint("ssh: connect to host github.com port 22: Connection refused")+ .is_some()+ );}#[test]diff --git a/src-tauri/src/service/plugin/installed.rs b/src-tauri/src/service/plugin/installed.rsindex b279d59a..09af5e42 100644--- a/src-tauri/src/service/plugin/installed.rs+++ b/src-tauri/src/service/plugin/installed.rs@@ -272,7 +272,10 @@ mod tests {);// 未声明 package 时回落到 id- let plain = PreinstallPluginInfo { package: None, ..installed };+ let plain = PreinstallPluginInfo {+ package: None,+ ..installed+ };assert_eq!(installed_name(&plain), "dsh-session-context-menu");}-}\ No newline at end of file+}diff --git a/src-tauri/src/service/plugin/internal.rs b/src-tauri/src/service/plugin/internal.rsindex 5a7266c3..f6d62569 100644--- a/src-tauri/src/service/plugin/internal.rs+++ b/src-tauri/src/service/plugin/internal.rs@@ -47,9 +47,15 @@ pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {.await;// 前端据此在「Loading internal plugins…」与「Loading plugins…」间切换;// 事件在服务进程启动前发出,于健康轮询期间到达,先于 dsh 自家的 boot 输出。- let _ = app_handle.emit("internal-plugins-phase", InternalPluginsPhase { phase: "loading" });+ let _ = app_handle.emit(+ "internal-plugins-phase",+ InternalPluginsPhase { phase: "loading" },+ );let outcome = ensure_inner(app_handle, &internal).await;- let _ = app_handle.emit("internal-plugins-phase", InternalPluginsPhase { phase: "done" });+ let _ = app_handle.emit(+ "internal-plugins-phase",+ InternalPluginsPhase { phase: "done" },+ );outcome}@@ -187,7 +193,10 @@ mod tests {// 指向其它位置(旧版本安装目录等)assert!(!dep_matches_spec("link:D:/elsewhere/dsh-tauri", expected));// 同名不同宿主盘符- assert!(!dep_matches_spec("link:D:/Apps/dsh/resources/preset-plugins/dsh-tauri", expected));+ assert!(!dep_matches_spec(+ "link:D:/Apps/dsh/resources/preset-plugins/dsh-tauri",+ expected+ ));}#[cfg(windows)]diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex 6a5cbf9d..77a2ce58 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -38,13 +38,15 @@ pub mod verify;pub mod watch;pub use cancel::cancel;-pub use install::{install, remove, update};pub(crate) use install::harness_prefer_bundled_pnpm;-pub use installed::{list, PreinstallPlugin};+pub use install::{install, remove, update};pub(crate) use installed::ensure_profile_npmrc;+pub use installed::{list, PreinstallPlugin};pub(crate) use internal::ensure as ensure_internal_plugins;pub use preset::repo_url_of;pub(crate) use preset::{current_preset_hash, preinstall_pending};-pub use recovery::{detect as detect_recovery, uninstall as uninstall_recovery, PluginRecoveryInfo};+pub use recovery::{+ detect as detect_recovery, uninstall as uninstall_recovery, PluginRecoveryInfo,+};pub(crate) use verify::ensure_preset_plugins;-pub use watch::DshPlugin;\ No newline at end of file+pub use watch::DshPlugin;diff --git a/src-tauri/src/service/plugin/preset.rs b/src-tauri/src/service/plugin/preset.rsindex 2a427dfe..8b98db2b 100644--- a/src-tauri/src/service/plugin/preset.rs+++ b/src-tauri/src/service/plugin/preset.rs@@ -125,7 +125,9 @@ pub(crate) fn bundled_plugin_dir(app_handle: &AppHandle, id: &str) -> Option<Pat/// `CARGO_MANIFEST_DIR`(即 `src-tauri`)的上层目录得到,只在开发机成立。#[cfg(debug_assertions)]fn dev_internal_plugins_dir() -> Option<PathBuf> {- let env_file = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..").join(".env");+ let env_file = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("..")+ .join(".env");let content = std::fs::read_to_string(env_file).ok()?;parse_dev_internal_dir(&content)}@@ -234,7 +236,10 @@ pub(crate) fn preinstall_pending(app_handle: &AppHandle) -> bool {if !setting.preinstall_done {return true;}- match (setting.preset_hash.as_deref(), current_preset_hash(app_handle)) {+ match (+ setting.preset_hash.as_deref(),+ current_preset_hash(app_handle),+ ) {(None, Some(_)) => true,(Some(prev), Some(cur)) => prev != cur,_ => false,@@ -270,8 +275,7 @@ mod tests {#[test]fn preset_json_ids_are_unique() {let presets = load_presets_for_test();- let ids: std::collections::HashSet<&str> =- presets.iter().map(|p| p.id.as_str()).collect();+ let ids: std::collections::HashSet<&str> = presets.iter().map(|p| p.id.as_str()).collect();assert_eq!(ids.len(), presets.len(), "preset ids must be unique");}@@ -332,11 +336,15 @@ mod tests {fn bundled_dir_discovers_nested_layout() {// 与 preset 文件一致:先探测 {root}/resources/preset-plugins/<id>let dir = std::env::temp_dir().join(format!("dsh-bundled-nested-{}", std::process::id()));- let nested = dir.join("resources").join(BUNDLED_PLUGINS_DIR).join("dsh-tauri");+ let nested = dir+ .join("resources")+ .join(BUNDLED_PLUGINS_DIR)+ .join("dsh-tauri");std::fs::create_dir_all(&nested).expect("create temp nested bundled dir");std::fs::write(nested.join("package.json"), "{}").expect("write bundle manifest");- let found = find_bundled_in_root(&dir, "dsh-tauri").expect("nested bundled dir should be found");+ let found =+ find_bundled_in_root(&dir, "dsh-tauri").expect("nested bundled dir should be found");assert_eq!(found, nested);std::fs::remove_dir_all(&dir).ok();@@ -349,7 +357,8 @@ mod tests {std::fs::create_dir_all(&flat).expect("create temp flat bundled dir");std::fs::write(flat.join("package.json"), "{}").expect("write bundle manifest");- let found = find_bundled_in_root(&dir, "dsh-tauri").expect("flat bundled dir should be found");+ let found =+ find_bundled_in_root(&dir, "dsh-tauri").expect("flat bundled dir should be found");assert_eq!(found, flat);std::fs::remove_dir_all(&dir).ok();@@ -359,7 +368,8 @@ mod tests {fn bundled_dir_requires_package_json() {// 无 package.json 的目录不是有效产物(prebuild 未执行)let dir = std::env::temp_dir().join(format!("dsh-bundled-empty-{}", std::process::id()));- std::fs::create_dir_all(dir.join("preset-plugins").join("dsh-tauri")).expect("create empty dir");+ std::fs::create_dir_all(dir.join("preset-plugins").join("dsh-tauri"))+ .expect("create empty dir");assert!(find_bundled_in_root(&dir, "dsh-tauri").is_none());std::fs::remove_dir_all(&dir).ok();}@@ -367,7 +377,9 @@ mod tests {#[test]fn bundled_dep_spec_normalizes_windows_separators() {assert_eq!(- bundled_dep_spec(std::path::Path::new("C:\\Apps\\dsh\\resources\\preset-plugins\\dsh-tauri")),+ bundled_dep_spec(std::path::Path::new(+ "C:\\Apps\\dsh\\resources\\preset-plugins\\dsh-tauri"+ )),"link:C:/Apps/dsh/resources/preset-plugins/dsh-tauri");// 尾部斜杠去除(Windows 盘符 C:\ 不会出现,路径恒为子目录)@@ -426,7 +438,10 @@ mod tests {fn dev_internal_dir_unset_when_missing_key_or_empty_value() {// 其它键或注释:视为未设置assert_eq!(parse_dev_internal_dir("FOO=bar\n"), None);- assert_eq!(parse_dev_internal_dir("# DEV_INTERNAL_PLUGINS_DIR=C:/x\n"), None);+ assert_eq!(+ parse_dev_internal_dir("# DEV_INTERNAL_PLUGINS_DIR=C:/x\n"),+ None+ );// 显式置空:同样视为未设置(关闭覆盖)assert_eq!(parse_dev_internal_dir("DEV_INTERNAL_PLUGINS_DIR=\n"), None);}@@ -478,4 +493,4 @@ mod tests {_ => false,}}-}\ No newline at end of file+}diff --git a/src-tauri/src/service/plugin/process.rs b/src-tauri/src/service/plugin/process.rsindex 519ad53d..4c3f3df2 100644--- a/src-tauri/src/service/plugin/process.rs+++ b/src-tauri/src/service/plugin/process.rs@@ -197,4 +197,4 @@ fn spawn_line_emitter<R: Read + Send + 'static>(}}});-}\ No newline at end of file+}diff --git a/src-tauri/src/service/plugin/recovery.rs b/src-tauri/src/service/plugin/recovery.rsindex dada8af7..8fb70b1a 100644--- a/src-tauri/src/service/plugin/recovery.rs+++ b/src-tauri/src/service/plugin/recovery.rs@@ -108,7 +108,8 @@ fn extract_plugin_refs(text: &str) -> Vec<String> {}}// 「Failed to load plugins」错误卡片:紧随其后的若干行通常是包名。- for m in Regex::new(r"(?m)^Failed to load plugins\s*$").expect("literal")+ for m in Regex::new(r"(?m)^Failed to load plugins\s*$")+ .expect("literal").find_iter(text){let rest = &text[m.end()..];@@ -144,8 +145,7 @@ fn extract_slot_conflict(text: &str) -> Option<String> {/// 对日志文本分类失败原因,返回(判别键, 动态详情)。fn classify_reason(text: &str) -> (String, String) {- let dup_route =- Regex::new(r#"duplicate prefix route\s+["']([^"']+)["']"#).expect("literal");+ 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);@@ -153,9 +153,7 @@ fn classify_reason(text: &str) -> (String, String) {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(re) = Regex::new(r#"cannot resolve profile bundle\s+["']?([^"'\n]+)["']?"#).ok() {if let Some(c) = re.captures(text) {return ("cannot_resolve_bundle".into(),@@ -164,13 +162,18 @@ fn classify_reason(text: &str) -> (String, String) {}}if text.contains("declares no dsh.bundle") {- let pkg = extract_plugin_refs(text).into_iter().next().unwrap_or_default();+ 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") {+ 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())@@ -249,9 +252,7 @@ fn bundle_owns_package(profile: &Path, bundle: &str, package: &str) -> bool {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)- {+ 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 {@@ -276,7 +277,12 @@ fn plugin_references_packages(profile: &Path, plugin: &str, packages: &HashSet<Sreturn true;}}- for file in ["cordis.patch.yml", "index.js", "lib/index.js", "dist/index.js"] {+ 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;@@ -298,8 +304,11 @@ fn plugin_declares_loader_entry(profile: &Path, plugin: &str, entry_id: &str) ->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();+ 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)}@@ -427,8 +436,9 @@ fn resolve_recovery_plugins(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();+ let providers: HashSet<String> = packages_providing_slot(&profile, slot)+ .into_iter()+ .collect();if !providers.is_empty() {let owners: Vec<&String> = roots.iter()@@ -450,7 +460,12 @@ pub fn detect(app_handle: &AppHandle, log_lines: &[String]) -> PluginRecoveryInflet 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 plugins = resolve_recovery_plugins(+ app_handle,+ &refs,+ duplicate_entry.as_deref(),+ slot_conflict.as_deref(),+ );let raw_error = refs_text(&text);PluginRecoveryInfo {plugins,@@ -485,7 +500,10 @@ fn refs_text(text: &str) -> String {/// 从 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 let Some(deps) = manifest+ .get_mut("dependencies")+ .and_then(|d| d.as_object_mut())+ {if deps.remove(id).is_some() {modified = true;}@@ -514,10 +532,18 @@ fn remove_plugin_dir(profile: &Path, id: &str) {log::warn!("failed to remove plugin dir {}: {e}", dir.display());}}- if let Some(scope) = id.starts_with('@').then(|| id.split('/').next().unwrap_or_default()) {+ if let Some(scope) = id+ .starts_with('@')+ .then(|| id.split('/').next().unwrap_or_default())+ {if !scope.is_empty() && scope != id {let scope_dir = node_modules.join(scope);- if scope_dir.is_dir() && scope_dir.read_dir().map(|mut d| d.next().is_none()).unwrap_or(false) {+ if scope_dir.is_dir()+ && scope_dir+ .read_dir()+ .map(|mut d| d.next().is_none())+ .unwrap_or(false)+ {let _ = fs::remove_dir_all(&scope_dir);}}@@ -556,9 +582,9 @@ fn strip_cordis_patch_for(profile: &Path, id: &str) {/// 一个 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::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,}@@ -576,10 +602,10 @@ pub fn uninstall(app_handle: &AppHandle, id: &str) -> Result<(), String> {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 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 {@@ -649,7 +675,10 @@ mod tests {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"));+ 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"));}@@ -667,7 +696,10 @@ mod tests {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(),+ manifest["dsh"]["profile"]["bundles"]+ .as_array()+ .unwrap()+ .len(),1);}diff --git a/src-tauri/src/service/plugin/update.rs b/src-tauri/src/service/plugin/update.rsindex f4d47036..087339a8 100644--- a/src-tauri/src/service/plugin/update.rs+++ b/src-tauri/src/service/plugin/update.rs@@ -86,8 +86,9 @@ fn read_locked_commits(profile: &Path) -> HashMap<String, String> {let Ok(text) = std::fs::read_to_string(profile.join("pnpm-lock.yaml")) else {return out;};- let re = regex::Regex::new(r"codeload\.github\.com/([^/\s]+)/([^/\s]+)/tar\.gz/([0-9a-fA-F]{7,40})")- .expect("static codeload regex");+ let re =+ regex::Regex::new(r"codeload\.github\.com/([^/\s]+)/([^/\s]+)/tar\.gz/([0-9a-fA-F]{7,40})")+ .expect("static codeload regex");for cap in re.captures_iter(&text) {let repo = format!("{}/{}", &cap[1], &cap[2]).to_lowercase();out.insert(repo, cap[3].to_string());@@ -106,12 +107,22 @@ fn read_locked_commits(profile: &Path) -> HashMap<String, String> {fn extract_github_repo(spec: &str) -> Option<String> {if let Some(rest) = spec.strip_prefix("github:") {let path = rest.split('#').next().unwrap_or(rest).trim_end_matches('/');- let path = path.strip_suffix(".git").unwrap_or(path).trim_end_matches('/');+ let path = path+ .strip_suffix(".git")+ .unwrap_or(path)+ .trim_end_matches('/');return (is_owner_repo(path)).then(|| path.to_string());}let after = spec.split_once("github.com/").map(|(_, r)| r)?;- let path = after.split(['#', '?']).next().unwrap_or(after).trim_end_matches('/');- let path = path.strip_suffix(".git").unwrap_or(path).trim_end_matches('/');+ let path = after+ .split(['#', '?'])+ .next()+ .unwrap_or(after)+ .trim_end_matches('/');+ let path = path+ .strip_suffix(".git")+ .unwrap_or(path)+ .trim_end_matches('/');let mut parts = path.split('/');let owner = parts.next()?;let repo = parts.next()?;@@ -174,7 +185,10 @@ async fn fetch_head_sha(client: &reqwest::Client, repo: &str) -> Option<String>/// npm registry `latest` dist-tag 版本(404/网络错误返回 None)。async fn fetch_npm_latest(client: &reqwest::Client, name: &str) -> Option<String> {- let url = format!("https://registry.npmjs.org/{}/latest", encode_registry_name(name));+ let url = format!(+ "https://registry.npmjs.org/{}/latest",+ encode_registry_name(name)+ );let v = fetch_json(client, &url).await?;v.get("version")?.as_str().map(String::from)}@@ -188,7 +202,10 @@ async fn compute_update(locked: &HashMap<String, String>,) -> UpdateInfo {if spec.starts_with("link:") || spec.starts_with("file:") {- return UpdateInfo { update_available: false, latest: None };+ return UpdateInfo {+ update_available: false,+ latest: None,+ };}if let Some(repo) = extract_github_repo(spec) {@@ -205,7 +222,10 @@ async fn compute_update((Some(i), Some(l)) => is_upgrade(i, l),_ => false,};- UpdateInfo { update_available, latest }+ UpdateInfo {+ update_available,+ latest,+ }}// ---------------------------------------------------------------------------@@ -295,7 +315,13 @@ pub async fn refresh(app_handle: &AppHandle) -> Result<Vec<DshPlugin>, String> {p.update_available = info.update_available;p.latest_version = info.latest.clone();}- cache.insert(key, CacheEntry { info, at: Instant::now() });+ cache.insert(+ key,+ CacheEntry {+ info,+ at: Instant::now(),+ },+ );}Ok(plugins)diff --git a/src-tauri/src/service/plugin/verify.rs b/src-tauri/src/service/plugin/verify.rsindex 41f5d728..06064c2f 100644--- a/src-tauri/src/service/plugin/verify.rs+++ b/src-tauri/src/service/plugin/verify.rs@@ -28,8 +28,8 @@ use crate::config;use crate::service::cli;use super::errors;-use super::installed::{installed_name, profile_dir, ProfilePackageJson};use super::install::{build_plugin_envs, harness_prefer_bundled_pnpm};+use super::installed::{installed_name, profile_dir, ProfilePackageJson};use super::preset::{load_presets, PreinstallPluginInfo};/// 判定清单引用的预装插件是否缺失产物(纯函数,便于单测)。@@ -138,7 +138,10 @@ async fn repair_with_pnpm_install(app_handle: &AppHandle, profile: &Path) -> Resargs.push(OsString::from("install"));let envs = build_plugin_envs(app_handle, harness_prefer_bundled_pnpm(app_handle));- log::info!("repairing profile node_modules via pnpm install in {}", profile.display());+ log::info!(+ "repairing profile node_modules via pnpm install in {}",+ profile.display()+ );let (exit_code, output) = spawn_and_wait(&program, &args, profile, &envs).await?;if exit_code != 0 {// 日志只保留输出尾部,避免刷屏(pnpm 失败信息集中在末尾)。@@ -150,7 +153,9 @@ async fn repair_with_pnpm_install(app_handle: &AppHandle, profile: &Path) -> Res.chars().rev().collect();- return Err(format!("PNPM_INSTALL_FAILED: exit code {exit_code}: {tail}"));+ return Err(format!(+ "PNPM_INSTALL_FAILED: exit code {exit_code}: {tail}"+ ));}Ok(())}@@ -170,14 +175,13 @@ const REPAIR_OUTPUT_LIMIT: usize = 4000;/// Windows 上 `.cmd`/`.bat` 无法被 CreateProcess 直接执行(需 cmd.exe 解析),/// 用户 pnpm 只接受 `.exe`。fn pnpm_direct(app_handle: &AppHandle) -> Option<(PathBuf, Vec<OsString>)> {- use super::install::{- bundled_pnpm_major, pnpm_major_version_at, profile_store_major,- };+ use super::install::{bundled_pnpm_major, pnpm_major_version_at, profile_store_major};let bundled = config::get_pnpm_binary_path(app_handle);let bundled_ready = bundled.exists();let store = profile_store_major(app_handle);- let bundled_matches = bundled_ready && store.is_none_or(|s| bundled_pnpm_major(app_handle) == Some(s));+ let bundled_matches =+ bundled_ready && store.is_none_or(|s| bundled_pnpm_major(app_handle) == Some(s));if bundled_matches {let node = config::get_node_binary_path(app_handle);@@ -234,14 +238,13 @@ async fn spawn_and_wait(GetExitCodeProcess, WaitForSingleObject, INFINITE,};- let (stdout, stderr, handle) =- workflow::win_spawn::spawn_with_hidden_console_tracked(- &program,- &args,- Some(&cwd),- &envs,- )- .map_err(|e| format!("PNPM_REPAIR_SPAWN: {e}"))?;+ let (stdout, stderr, handle) = workflow::win_spawn::spawn_with_hidden_console_tracked(+ &program,+ &args,+ Some(&cwd),+ &envs,+ )+ .map_err(|e| format!("PNPM_REPAIR_SPAWN: {e}"))?;drain_pipe(stdout, captured.clone());drain_pipe(stderr, captured.clone());@@ -339,7 +342,8 @@ mod tests {}fn setup(dir_label: &str, present: &[&str]) -> PathBuf {- let root = std::env::temp_dir().join(format!("dsh-verify-{}-{}", std::process::id(), dir_label));+ let root =+ std::env::temp_dir().join(format!("dsh-verify-{}-{}", std::process::id(), dir_label));let _ = fs::remove_dir_all(&root);let node_modules = root.join("node_modules");for name in present {@@ -355,7 +359,10 @@ mod tests {let presets = vec![preset("dshmarket", None), preset("dsh-notification", None)];let deps = HashMap::from([("dshmarket".to_string(), "1.0.0".to_string()),- ("dsh-notification".to_string(), "github:omdsh-dev/dsh-notification".to_string()),+ (+ "dsh-notification".to_string(),+ "github:omdsh-dev/dsh-notification".to_string(),+ ),]);let bundles = vec!["dshmarket".to_string()];// dshmarket 在(引用且产物在);dsh-notification 被引用但产物缺失@@ -367,7 +374,10 @@ mod tests {#[test]fn missing_ignores_unreferenced_and_present() {- let presets = vec![preset("dshmarket", None), preset("dsh-better-sidebar", None)];+ let presets = vec![+ preset("dshmarket", None),+ preset("dsh-better-sidebar", None),+ ];let deps = HashMap::from([("dshmarket".to_string(), "^1.0.0".to_string())]);let bundles: Vec<String> = Vec::new();// 全部就绪:dshmarket 已装;better-sidebar 未被引用@@ -380,7 +390,10 @@ mod tests {#[test]fn missing_resolves_scoped_package_name() {// scoped 包名(installed_name 走 package 字段)对应 node_modules/@scope/name- let presets = vec![preset("dsh-session-context-menu", Some("@baihejiangnan/dsh-session-context-menu"))];+ let presets = vec![preset(+ "dsh-session-context-menu",+ Some("@baihejiangnan/dsh-session-context-menu"),+ )];let deps = HashMap::from([("@baihejiangnan/dsh-session-context-menu".to_string(),"github:baihejiangnan/dsh-session-context-menu".to_string(),@@ -391,7 +404,12 @@ mod tests {let missing = missing_plugin_ids(&presets, &deps, &bundles, &root.join("node_modules"));assert!(missing.is_empty());// 目录缺失 → 缺失- let missing = missing_plugin_ids(&presets, &deps, &bundles, &root.join("missing-node_modules"));+ let missing = missing_plugin_ids(+ &presets,+ &deps,+ &bundles,+ &root.join("missing-node_modules"),+ );assert_eq!(missing, vec!["dsh-session-context-menu"]);fs::remove_dir_all(&root).ok();}diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rsindex de8951c7..0d698457 100644--- a/src-tauri/src/service/plugin/watch.rs+++ b/src-tauri/src/service/plugin/watch.rs@@ -308,7 +308,8 @@ mod tests {/// 构造临时 profile:package.json + node_modules 下的插件包清单/// (tag 用于区分不同测试的临时目录,避免并行执行时互相清理)fn build_profile(tag: &str, packages: &[(&str, &str)]) -> PathBuf {- let dir = std::env::temp_dir().join(format!("dsh-watch-test-{}-{}", tag, std::process::id()));+ let dir =+ std::env::temp_dir().join(format!("dsh-watch-test-{}-{}", tag, std::process::id()));let _ = std::fs::remove_dir_all(&dir);std::fs::create_dir_all(&dir.join("node_modules")).unwrap();let mut manifest = serde_json::json!({@@ -329,9 +330,8 @@ mod tests {}}manifest["dependencies"] = serde_json::Value::Object(deps);- manifest["dsh"]["profile"]["bundles"] = serde_json::Value::Array(- bundles.into_iter().map(serde_json::Value::String).collect(),- );+ manifest["dsh"]["profile"]["bundles"] =+ serde_json::Value::Array(bundles.into_iter().map(serde_json::Value::String).collect());std::fs::write(dir.join("package.json"),serde_json::to_string_pretty(&manifest).unwrap(),@@ -396,14 +396,8 @@ mod tests {let dir = build_profile("fallback",&[- (- "dsh-at-file",- r#"{"name":"dsh-at-file"}"#,- ),- (- "dshmarket",- r#"{"name":"dshmarket","dsh":{"bundle":{}}}"#,- ),+ ("dsh-at-file", r#"{"name":"dsh-at-file"}"#),+ ("dshmarket", r#"{"name":"dshmarket","dsh":{"bundle":{}}}"#),],);let plugins = parse_plugins(&dir, &presets_for_test());@@ -427,10 +421,7 @@ mod tests {"dsh-tauri",r#"{"name":"dsh-tauri","version":"0.2.0","description":"bridge"}"#,),- (- "dshmarket",- r#"{"name":"dshmarket","version":"1.13.1"}"#,- ),+ ("dshmarket", r#"{"name":"dshmarket","version":"1.13.1"}"#),],);let mut presets = presets_for_test();diff --git a/src-tauri/src/service/profile/mod.rs b/src-tauri/src/service/profile/mod.rsindex f0083a91..3b51f569 100644--- a/src-tauri/src/service/profile/mod.rs+++ b/src-tauri/src/service/profile/mod.rs@@ -28,7 +28,8 @@ const WEB_PROFILE_BUNDLES: [&str; 2] = ["@deepseek-ai/dsh-base", "@deepseek-ai/dconst PROFILE_PATCH_TEMPLATE: &str = "# Your patch layer for this dsh profile, applied after every bundle layer:\n# a top-level YAML array of loader patch entries (id-targeted config\n# overrides, disables, and insert lists; `!!js` expressions allowed).\n[]\n";/// dsh `initProfile` 生成的 pnpm 设置(与官方一致)-const PROFILE_PNPM_WORKSPACE: &str = "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n";+const PROFILE_PNPM_WORKSPACE: &str =+ "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n";/// 档案行(序列化 camelCase 给前端)#[derive(Debug, Clone, Serialize)]@@ -58,7 +59,9 @@ pub fn profile_dir_of(app_handle: &AppHandle, id: &str) -> PathBuf {/// (web 由 dsh 启动/插件操作时按需初始化)。pub fn active_profile(app_handle: &AppHandle) -> String {let stored = config::get_store_dat_setting(app_handle).active_profile;- if !stored.is_empty() && stored != DEFAULT_PROFILE && profile_dir_of(app_handle, &stored).is_dir()+ if !stored.is_empty()+ && stored != DEFAULT_PROFILE+ && profile_dir_of(app_handle, &stored).is_dir(){stored} else {@@ -79,7 +82,11 @@ fn manifest_display_name(dir: &Path, id: &str) -> String {.map(String::from).unwrap_or_else(|| raw);let fallback = id.to_string();- let name = if stripped.is_empty() { fallback } else { stripped };+ let name = if stripped.is_empty() {+ fallback+ } else {+ stripped+ };// 首字母大写,与既有「Web」展示风格一致let mut chars = name.chars();match chars.next() {@@ -197,10 +204,14 @@ pub fn set_active(app_handle: &AppHandle, id: &str) -> Result<Profile, String> {/// 删除档案(默认档案与使用中的档案不可删除)。pub fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {if id == DEFAULT_PROFILE {- return Err("PROFILE_DEFAULT_NOT_REMOVABLE: the default profile cannot be removed".to_string());+ return Err(+ "PROFILE_DEFAULT_NOT_REMOVABLE: the default profile cannot be removed".to_string(),+ );}if id == active_profile(app_handle) {- return Err("PROFILE_ACTIVE_NOT_REMOVABLE: the active profile cannot be removed".to_string());+ return Err(+ "PROFILE_ACTIVE_NOT_REMOVABLE: the active profile cannot be removed".to_string(),+ );}// 路径安全:ID 字符集白名单 + 目标必须位于 profiles 根目录内(防 `..` 穿越)let profiles_root = config::get_dsh_data_path(app_handle).join("profiles");@@ -246,7 +257,10 @@ fn init_profile_dir(dir: &Path, id: &str) -> Result<(), String> {// 与 ensure_profile_npmrc 一致地预写 .npmrc(幂等,绝不覆盖已有配置)。let npmrc_path = dir.join(".npmrc");let npmrc_existing = fs::read_to_string(&npmrc_path).unwrap_or_default();- if !npmrc_existing.lines().any(|l| l.trim() == "confirmModulesPurge=false") {+ if !npmrc_existing+ .lines()+ .any(|l| l.trim() == "confirmModulesPurge=false")+ {let mut content = npmrc_existing;if !content.is_empty() && !content.ends_with('\n') {content.push('\n');diff --git a/src-tauri/src/service/update/install.rs b/src-tauri/src/service/update/install.rsindex 0b3068a3..76c88d95 100644--- a/src-tauri/src/service/update/install.rs+++ b/src-tauri/src/service/update/install.rs@@ -103,7 +103,8 @@ async fn download_from_source(let mut stream = res.bytes_stream();while let Some(chunk) = stream.next().await {let chunk = chunk.map_err(|e| format!("UPDATE_DOWNLOAD: {e}"))?;- file.write_all(&chunk).map_err(|e| format!("UPDATE_FILE: {e}"))?;+ file.write_all(&chunk)+ .map_err(|e| format!("UPDATE_FILE: {e}"))?;downloaded += chunk.len() as u64;let pct = if total > 0 {(downloaded as f64 / total as f64) * 100.0@@ -170,8 +171,8 @@ fn ensure_installer_executable(path: &std::path::Path) -> Result<(), String> {/// 这里按块流式喂给 `Sha256`,完成时仅保留 32 字节摘要。摘要格式接受/// `sha256:<64hex>` 或裸 `<64hex>`(统一转小写比较)。fn verify_installer_sha256(path: &std::path::Path, expected: &str) -> Result<(), String> {- use std::io::Read;use sha2::Digest;+ use std::io::Read;let expected = expected.strip_prefix("sha256:").unwrap_or(expected)@@ -184,7 +185,9 @@ fn verify_installer_sha256(path: &std::path::Path, expected: &str) -> Result<(),let mut hasher = sha2::Sha256::new();let mut buf = [0u8; 64 * 1024];loop {- let n = file.read(&mut buf).map_err(|e| format!("UPDATE_FILE: {e}"))?;+ let n = file+ .read(&mut buf)+ .map_err(|e| format!("UPDATE_FILE: {e}"))?;if n == 0 {break;}@@ -313,15 +316,16 @@ pub async fn open_installer(app_handle: &AppHandle, path: String) -> Result<(),// 用 `dunce::canonicalize`(std `fs::canonicalize`)——它返回的路径不带// Windows `\\?\` verbatim 前缀,`starts_with` 与日志展示更一致。let canonical = dunce::canonicalize(p).map_err(|e| format!("UPDATE_OPEN: {e}"))?;- let updates_real = dunce::canonicalize(&updates_dir)- .map_err(|e| format!("UPDATE_DIR: {e}"))?;+ let updates_real = dunce::canonicalize(&updates_dir).map_err(|e| format!("UPDATE_DIR: {e}"))?;if !canonical.starts_with(&updates_real) {log::error!("Rejecting open_installer outside updates dir: {} (root {})",canonical.display(),updates_real.display());- return Err("UPDATE_PATH_REJECTED: installer path is outside updates directory".to_string());+ return Err(+ "UPDATE_PATH_REJECTED: installer path is outside updates directory".to_string(),+ );}log::info!("Opening desktop installer: {}", p.display());// 更新前先停下本应用持有的 Harness 服务:安装器在安装时会强杀桌面端进程@@ -364,7 +368,11 @@ mod tests {std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();ensure_installer_executable(&file).unwrap();let mode = std::fs::metadata(&file).unwrap().permissions().mode();- assert_eq!(mode & 0o111, 0o111, "应包含所有者/组/其他可执行位,mode={mode:o}");+ assert_eq!(+ mode & 0o111,+ 0o111,+ "应包含所有者/组/其他可执行位,mode={mode:o}"+ );let _ = std::fs::remove_dir_all(&dir);}@@ -391,8 +399,16 @@ mod tests {};let sources = download_sources(&with_digest);assert_eq!(sources.len(), 2);- assert!(sources[1].contains("ghfast.top"), "镜像应为 ghfast.top 前缀: {}", sources[1]);- assert!(sources[1].ends_with("/releases/download/v0.7.4/x.dmg"), "镜像保留完整资产路径: {}", sources[1]);+ assert!(+ sources[1].contains("ghfast.top"),+ "镜像应为 ghfast.top 前缀: {}",+ sources[1]+ );+ assert!(+ sources[1].ends_with("/releases/download/v0.7.4/x.dmg"),+ "镜像保留完整资产路径: {}",+ sources[1]+ );}/// 流式校验:正确的文件通过、错误的摘要拒绝,且不把整个文件读进内存。diff --git a/src-tauri/src/service/update/meta.rs b/src-tauri/src/service/update/meta.rsindex 49a76eb1..b8021fcb 100644--- a/src-tauri/src/service/update/meta.rs+++ b/src-tauri/src/service/update/meta.rs@@ -94,7 +94,10 @@ fn extract_asset_names(html: &str, tag: &str) -> Vec<String> {let mut start = 0;while let Some(pos) = html[start..].find(&needle) {let after = start + pos + needle.len();- let end = html[after..].find('"').map(|e| after + e).unwrap_or(html.len());+ let end = html[after..]+ .find('"')+ .map(|e| after + e)+ .unwrap_or(html.len());names.push(html[after..end].to_string());start = end;}@@ -226,7 +229,10 @@ mod tests {let s = r#"<link rel="alternate" href="https://github.com/x/releases/tag/v0.6.6"/>"#;assert_eq!(find_token(s, "releases/tag/", "\""), Some("v0.6.6"));let s2 = "<updated>2026-08-19T09:27:38Z</updated>";- assert_eq!(find_token(s2, "<updated>", "</updated>"), Some("2026-08-19T09:27:38Z"));+ assert_eq!(+ find_token(s2, "<updated>", "</updated>"),+ Some("2026-08-19T09:27:38Z")+ );assert_eq!(find_token("no marker", "releases/tag/", "\""), None);}@@ -242,7 +248,10 @@ mod tests {assert_eq!(parse_atom_entries(feed),vec![- ("v0.7.14-rc.1".to_string(), "2026-08-20T01:00:00Z".to_string()),+ (+ "v0.7.14-rc.1".to_string(),+ "2026-08-20T01:00:00Z".to_string()+ ),("v0.7.13".to_string(), "2026-08-19T00:00:00Z".to_string()),("test-main-42".to_string(), String::new()),]@@ -282,10 +291,7 @@ mod tests {let bad = r#"<td>app.dmg sha256:zz"#;assert!(parse_digest_from_expanded_assets(bad, "app.dmg").is_none());// 多字节内容前移后仍能解析(切片边界安全)- let unicode = format!(- "中文说明app.dmg{}更多内容",- hex- );+ let unicode = format!("中文说明app.dmg{}更多内容", hex);assert!(parse_digest_from_expanded_assets(&unicode, "app.dmg").is_some());}diff --git a/src-tauri/src/service/update/version.rs b/src-tauri/src/service/update/version.rsindex 660cc079..4836d8fd 100644--- a/src-tauri/src/service/update/version.rs+++ b/src-tauri/src/service/update/version.rs@@ -142,7 +142,10 @@ mod tests {assert_eq!(parse_version("v0.5.2").unwrap().to_string(), "0.5.2");assert_eq!(parse_version("0.5.2").unwrap().to_string(), "0.5.2");// pre-release 也是合法 semver- assert_eq!(parse_version("0.5.2-rc.1").unwrap().to_string(), "0.5.2-rc.1");+ assert_eq!(+ parse_version("0.5.2-rc.1").unwrap().to_string(),+ "0.5.2-rc.1"+ );// 非法 semver(如手动测试 release 的 tag / 只有两段)返回 Noneassert_eq!(parse_version("abc"), None);assert_eq!(parse_version("test-main-123"), None);@@ -213,7 +216,10 @@ mod tests {#[cfg(target_arch = "x86_64")]{assert_eq!(arch_rank("Deepseek.Harness.Desktop_0.6.6_x64.dmg"), 2);- assert_eq!(arch_rank("Deepseek.Harness.Desktop_0.6.6_amd64.AppImage"), 2);+ assert_eq!(+ arch_rank("Deepseek.Harness.Desktop_0.6.6_amd64.AppImage"),+ 2+ );assert_eq!(arch_rank("Deepseek.Harness.Desktop-0.6.6-1.x86_64.rpm"), 2);assert_eq!(arch_rank("Deepseek.Harness.Desktop_0.6.6_aarch64.dmg"), 0);}diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rsindex eee49829..bda69e83 100644--- a/src-tauri/src/service/workflow/mod.rs+++ b/src-tauri/src/service/workflow/mod.rs@@ -1,11 +1,11 @@-pub mod status;-pub mod utils;pub(crate) mod client_hmr_patch;pub(crate) mod renderer_patch;-pub(crate) mod workspace_patch;+pub mod status;+pub mod utils;pub(crate) mod win_inspector;#[cfg(windows)]pub(crate) mod win_spawn;+pub(crate) mod workspace_patch;use crate::config;use crate::service::download;@@ -46,14 +46,18 @@ fn owned_process_lock() -> &'static Mutex<Option<OwnedProcess>> {/// 记录新持有的 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());+ 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());+ let mut guard = owned_process_lock()+ .lock()+ .unwrap_or_else(|e| e.into_inner());*guard = Some(OwnedProcess { pid, handle });}@@ -72,7 +76,9 @@ fn take_owned_process() -> Option<OwnedProcess> {/// 属于自己那一条登记,绝不误取/误清「刚启动的新进程」的登记——否则会把它/// 当作已退出而错误回落 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());+ let mut guard = owned_process_lock()+ .lock()+ .unwrap_or_else(|e| e.into_inner());take_owned_process_if_matching(&mut guard, pid)}@@ -504,7 +510,9 @@ pub fn sweep_orphan_harness(app_handle: &tauri::AppHandle) {// 结束,随后的 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 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()),@@ -627,7 +635,9 @@ fn relaunch_via_shell_escape(app_handle: &tauri::AppHandle) {std::process::exit(0);}Err(e) => {- log::warn!("RedirectionGuard(448) detected but explorer spawn failed ({e}), falling back");+ log::warn!(+ "RedirectionGuard(448) detected but explorer spawn failed ({e}), falling back"+ );}}}@@ -830,8 +840,8 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// shim 报 "Node.js runtime not found"(issue #121,与 build_plugin_envs// 的注入保持一致)。先规范化为绝对路径:相对路径在子进程 CWD 下会解析// 到错误位置;已存在(上面校验过)的 node 可安全 canonicalize。- let node_abs = std::fs::canonicalize(&node_binary_path)- .unwrap_or_else(|_| node_binary_path.clone());+ let node_abs =+ std::fs::canonicalize(&node_binary_path).unwrap_or_else(|_| node_binary_path.clone());envs.insert("DSH_NODE".to_string(),node_abs.to_string_lossy().into_owned(),diff --git a/src-tauri/src/service/workflow/renderer_patch.rs b/src-tauri/src/service/workflow/renderer_patch.rsindex 0518e7d7..c3ee316e 100644--- a/src-tauri/src/service/workflow/renderer_patch.rs+++ b/src-tauri/src/service/workflow/renderer_patch.rs@@ -59,7 +59,10 @@ fn patch_source(source: &str) -> PatchOutcome {return PatchOutcome::AnchorMissing;};let mut patched = source.to_string();- patched.insert_str(line_start, &format!("{indent}exports.SlotOutlet = SlotOutlet;\n"));+ patched.insert_str(+ line_start,+ &format!("{indent}exports.SlotOutlet = SlotOutlet;\n"),+ );PatchOutcome::Patched(patched)}@@ -107,7 +110,10 @@ pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {fs::write(&client_js, patched).map_err(|e| {format!("RENDERER_PATCH_WRITE: {} failed: {e}", client_js.display())})?;- log::info!("renderer SlotOutlet export patched: {}", client_js.display());+ log::info!(+ "renderer SlotOutlet export patched: {}",+ client_js.display()+ );}}Ok(())diff --git a/src-tauri/src/service/workflow/status.rs b/src-tauri/src/service/workflow/status.rsindex c852b733..f5a993fe 100644--- a/src-tauri/src/service/workflow/status.rs+++ b/src-tauri/src/service/workflow/status.rs@@ -29,5 +29,8 @@ pub fn emit_status(app_handle: &AppHandle) {}pub fn get_status() -> Status {- get_status_lock().lock().unwrap_or_else(|e| e.into_inner()).clone()+ get_status_lock()+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .clone()}diff --git a/src-tauri/src/service/workflow/utils.rs b/src-tauri/src/service/workflow/utils.rsindex 5426d70b..0b59663f 100644--- a/src-tauri/src/service/workflow/utils.rs+++ b/src-tauri/src/service/workflow/utils.rs@@ -31,12 +31,8 @@ pub(super) fn loopback_http_client(timeout: Duration) -> Result<reqwest::Client,/// 必须等到真实 JS bundle(而非 HTML fallback)可取,才视为可挂载 iframe。pub(super) fn health_probe_plugin_urls(port: u16) -> Vec<String> {vec![- format!(- "http://127.0.0.1:{port}/plugins/@deepseek-ai/dsh-client-ui-layout/client.js"- ),- format!(- "http://127.0.0.1:{port}/plugins/@deepseek-ai/dsh-client-runtime/client.js"- ),+ format!("http://127.0.0.1:{port}/plugins/@deepseek-ai/dsh-client-ui-layout/client.js"),+ format!("http://127.0.0.1:{port}/plugins/@deepseek-ai/dsh-client-runtime/client.js"),]}@@ -167,7 +163,11 @@ fn append_log(log_path: &PathBuf, line: &str) {if log_path.exists() {let _ = std::fs::rename(log_path, indexed_log_path(log_path, 1));}- let _ = std::fs::OpenOptions::new().create(true).write(true).truncate(true).open(log_path);+ let _ = std::fs::OpenOptions::new()+ .create(true)+ .write(true)+ .truncate(true)+ .open(log_path);}}}@@ -177,10 +177,7 @@ fn indexed_log_path(log_path: &PathBuf, index: usize) -> PathBuf {if index == 0 {return log_path.clone();}- let mut name = log_path- .file_name()- .unwrap_or_default()- .to_os_string();+ let mut name = log_path.file_name().unwrap_or_default().to_os_string();name.push(format!(".{}", index));log_path.with_file_name(name)}@@ -228,10 +225,7 @@ mod tests {/// 且每次启动都会新建当前日志文件。#[test]fn rotate_keeps_only_last_three_starts() {- let dir = std::env::temp_dir().join(format!(- "dsh_rotate_test_{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("dsh_rotate_test_{}", std::process::id()));let log = dir.join("dsh-web.log");let _ = fs::remove_dir_all(&dir);@@ -266,10 +260,9 @@ mod tests {assert!(urls.iter().all(|u| !u.ends_with("3080/") && !u.ends_with("://127.0.0.1:3080")));- assert!(- urls.iter()- .any(|u| u.contains("dsh-client-ui-layout/client.js"))- );+ assert!(urls+ .iter()+ .any(|u| u.contains("dsh-client-ui-layout/client.js")));}#[test]@@ -278,9 +271,15 @@ mod tests {true,"<!doctype html><html lang=\"en\"><body>HARNESS Loading plugins...</body></html>"));- assert!(!looks_like_plugin_bundle(true, "<html><head></head></html>"));+ assert!(!looks_like_plugin_bundle(+ true,+ "<html><head></head></html>"+ ));assert!(!looks_like_plugin_bundle(true, " "));- assert!(!looks_like_plugin_bundle(false, "window.__ModuleLoader__={}"));+ assert!(!looks_like_plugin_bundle(+ false,+ "window.__ModuleLoader__={}"+ ));assert!(looks_like_plugin_bundle(true,"window.__ModuleLoader__.load({id:\"@deepseek-ai/dsh-client-ui-layout\"})"@@ -290,10 +289,7 @@ mod tests {/// keep=0 时把当前日志也删掉。#[test]fn rotate_with_keep_zero_removes_all() {- let dir = std::env::temp_dir().join(format!(- "dsh_rotate_zero_{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("dsh_rotate_zero_{}", std::process::id()));let log = dir.join("dsh-web.log");let _ = fs::remove_dir_all(&dir);write(&log, "x");diff --git a/src-tauri/src/service/workflow/win_inspector.rs b/src-tauri/src/service/workflow/win_inspector.rsindex ec2aabfd..642eb91a 100644--- a/src-tauri/src/service/workflow/win_inspector.rs+++ b/src-tauri/src/service/workflow/win_inspector.rs@@ -94,8 +94,7 @@ mod imp {/// 写入一个文件及其父目录,返回错误信息。fn write_file(path: &Path, content: &str) -> Result<(), String> {if let Some(parent) = path.parent() {- fs::create_dir_all(parent)- .map_err(|e| format!("create parent dir failed: {e}"))?;+ fs::create_dir_all(parent).map_err(|e| format!("create parent dir failed: {e}"))?;}fs::write(path, content).map_err(|e| format!("write {} failed: {e}", path.display()))}@@ -240,8 +239,7 @@ mod imp {seq.push(plugin_insert_entry());}- let out = serde_yaml::to_string(&doc)- .map_err(|e| format!("PATCH_RENDER_FAILED: {e}"))?;+ let out = serde_yaml::to_string(&doc).map_err(|e| format!("PATCH_RENDER_FAILED: {e}"))?;write_file(&patch_path, &out).map_err(|e| format!("PATCH_WRITE_FAILED: {e}"))}@@ -316,8 +314,8 @@ mod imp {if content.trim().is_empty() {return Ok(serde_yaml::Value::Sequence(Vec::new()));}- let doc: serde_yaml::Value = serde_yaml::from_str(content)- .map_err(|e| format!("PATCH_PARSE_FAILED: {e}"))?;+ let doc: serde_yaml::Value =+ serde_yaml::from_str(content).map_err(|e| format!("PATCH_PARSE_FAILED: {e}"))?;match &doc {serde_yaml::Value::Sequence(_) => Ok(doc),serde_yaml::Value::Null => Ok(serde_yaml::Value::Sequence(Vec::new())),@@ -335,16 +333,14 @@ mod imp {/// 挂载块是否仍使用无法被 Node ESM 稳定加载的裸包名或目录旧写法。fn block_uses_legacy_name(el: &serde_yaml::Value) -> bool {serde_yaml::to_string(el)- .map(|s| {- !s.contains("name: ./node_modules/dsh-win-terminal-inspector/index.js")- })+ .map(|s| !s.contains("name: ./node_modules/dsh-win-terminal-inspector/index.js")).unwrap_or(false)}/// 生成本插件的顶层 `- insert:` 挂载元素(解析自 `PATCH_ENTRY` 模板)。fn plugin_insert_entry() -> serde_yaml::Value {- let seq: serde_yaml::Value = serde_yaml::from_str(PATCH_ENTRY)- .expect("PATCH_ENTRY must remain valid YAML");+ let seq: serde_yaml::Value =+ serde_yaml::from_str(PATCH_ENTRY).expect("PATCH_ENTRY must remain valid YAML");match seq {serde_yaml::Value::Sequence(mut s) => s.remove(0),other => other,