DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
chore(desktop): 清理 rust clippy 警告(lib+tests 归零)
hairyf48d2cd88ae16
diff --git a/src-tauri/src/bridge/config.rs b/src-tauri/src/bridge/config.rsindex 92d99706..90d3aa6c 100644--- a/src-tauri/src/bridge/config.rs+++ b/src-tauri/src/bridge/config.rs@@ -33,6 +33,7 @@ pub fn is_dev_build() -> bool {/// 备份字段(backup_retention_count / backup_include_credentials)由前端/// 设置页写入,归一化由 `normalize_backup_fields` 统一负责。#[tauri::command]+#[allow(clippy::too_many_arguments)]pub async fn update_app_config(app_handle: AppHandle,port: Option<u16>,diff --git a/src-tauri/src/bridge/pet.rs b/src-tauri/src/bridge/pet.rsindex 7b4eaa9e..e2b571b4 100644--- a/src-tauri/src/bridge/pet.rs+++ b/src-tauri/src/bridge/pet.rs@@ -315,19 +315,17 @@ async fn consume_pet_session_stream(app: &AppHandle, url: &str) -> Result<(), Stlet trimmed = line.trim();if let Some(data) = trimmed.strip_prefix("data:") {pending_data.push(data.trim().to_string());- } else if trimmed.is_empty() {- if !pending_data.is_empty() {- let frame: Value = serde_json::from_str(&pending_data.join("\n"))- .map_err(|error| error.to_string())?;- let action = frame- .get("action")- .and_then(Value::as_str)- .unwrap_or_default()- .to_string();- let payload = frame.get("payload").cloned().unwrap_or(Value::Null);- emit_pet_session(app, &action, &payload);- pending_data.clear();- }+ } else if trimmed.is_empty() && !pending_data.is_empty() {+ let frame: Value = serde_json::from_str(&pending_data.join("\n"))+ .map_err(|error| error.to_string())?;+ let action = frame+ .get("action")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ let payload = frame.get("payload").cloned().unwrap_or(Value::Null);+ emit_pet_session(app, &action, &payload);+ pending_data.clear();}// 其余(':' 开头的注释帧等)忽略。}@@ -690,13 +688,13 @@ struct SpriteGrid {/// 声明与图集比例不符时以图集为准:旧版 8x9 图集沿用缺省 v2 声明(或清单漏写版本)/// 是常见写法,按声明拒绝会让整个宠物无法导入。fn sprite_grid(declared: Option<u8>, width: u32, height: u32) -> Result<SpriteGrid, String> {- if width % u32::from(PET_SPRITE_COLUMNS) != 0 {+ if !width.is_multiple_of(u32::from(PET_SPRITE_COLUMNS)) {return Err(format!("PET_ASSET_DIMENSIONS_INVALID: spritesheet width must be divisible by {PET_SPRITE_COLUMNS} columns"));}- let v1 = height % u32::from(PET_SPRITE_V1_ROWS) == 0;- let v2 = height % u32::from(PET_SPRITE_V2_ROWS) == 0;+ let v1 = height.is_multiple_of(u32::from(PET_SPRITE_V1_ROWS));+ let v2 = height.is_multiple_of(u32::from(PET_SPRITE_V2_ROWS));let version = match (v1, v2) {(false, false) => {return Err(format!(@@ -1029,7 +1027,7 @@ fn copy_archive_entry<R: Read, W: Write>(fn extract_pet_archive(bytes: &[u8], staging: &Path) -> Result<PetManifest, String> {let mut archive = ZipArchive::new(Cursor::new(bytes)).map_err(|error| format!("PET_ARCHIVE_INVALID: failed to open zip: {error}"))?;- if archive.len() == 0 || archive.len() > PET_PACKAGE_MAX_ENTRIES {+ if archive.is_empty() || archive.len() > PET_PACKAGE_MAX_ENTRIES {return Err(format!("PET_ARCHIVE_ENTRY_LIMIT: archive must contain 1..={PET_PACKAGE_MAX_ENTRIES} entries"));diff --git a/src-tauri/src/config/manifest.rs b/src-tauri/src/config/manifest.rsindex 1f00f97c..ad8fa2ae 100644--- a/src-tauri/src/config/manifest.rs+++ b/src-tauri/src/config/manifest.rs@@ -222,19 +222,14 @@ pub struct DependencySpec {}/// 入口路径声明:单一路径字符串或按平台映射-#[derive(Debug, Clone, PartialEq, Eq)]+#[derive(Debug, Clone, PartialEq, Eq, Default)]pub enum EntrySpec {Single(String),Platform(BTreeMap<String, String>),+ #[default]Empty,}-impl Default for EntrySpec {- fn default() -> Self {- EntrySpec::Empty- }-}-impl<'de> Deserialize<'de> for EntrySpec {fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>wherediff --git a/src-tauri/src/config/region.rs b/src-tauri/src/config/region.rsindex d84b0f7b..86dfb5a5 100644--- a/src-tauri/src/config/region.rs+++ b/src-tauri/src/config/region.rs@@ -72,7 +72,7 @@ fn current_locale() -> String {if len <= 0 {return String::new();}- return String::from_utf16_lossy(&buf[..len as usize - 1]);+ String::from_utf16_lossy(&buf[..len as usize - 1])}#[cfg(not(windows))]{@@ -113,7 +113,7 @@ fn is_china_timezone() -> bool {.iter().position(|&c| c == 0).unwrap_or(info.TimeZoneKeyName.len());- return tz_name_is_china(&String::from_utf16_lossy(&info.TimeZoneKeyName[..len]));+ tz_name_is_china(&String::from_utf16_lossy(&info.TimeZoneKeyName[..len]))}#[cfg(not(windows))]{diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rsindex 27e1721e..03555f25 100644--- a/src-tauri/src/config/setting.rs+++ b/src-tauri/src/config/setting.rs@@ -425,19 +425,23 @@ mod tests {#[test]fn legacy_full_setting_write_preserves_latest_fields() {- let mut stale = Setting::default();- stale.zoom_factor = 0.8;- stale.close_action = "quit".to_string();- stale.pet_enabled = false;- stale.active_pet = Some("chat:stale".to_string());- stale.pet_size = Some(80.0);-- let mut current = Setting::default();- current.zoom_factor = 1.6;- current.close_action = "tray".to_string();- current.pet_enabled = true;- current.active_pet = Some("codex:latest".to_string());- current.pet_size = Some(140.0);+ let stale = Setting {+ zoom_factor: 0.8,+ close_action: "quit".to_string(),+ pet_enabled: false,+ active_pet: Some("chat:stale".to_string()),+ pet_size: Some(80.0),+ ..Default::default()+ };++ let current = Setting {+ zoom_factor: 1.6,+ close_action: "tray".to_string(),+ pet_enabled: true,+ active_pet: Some("codex:latest".to_string()),+ pet_size: Some(140.0),+ ..Default::default()+ };let merged = preserve_persisted_fields(stale, ¤t);diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 03b9dc0f..6b1650e8 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -1,15 +1,12 @@-use std::sync::atomic::{AtomicU64, Ordering};#[cfg(windows)]use std::sync::atomic::AtomicBool;+use std::sync::atomic::{AtomicU64, Ordering};#[cfg(windows)]use std::sync::Arc;#[cfg(target_os = "macos")]use std::sync::{Mutex, OnceLock};-use tauri::{- ipc::Invoke,- Emitter, Manager, Runtime, WebviewUrl, WebviewWindowBuilder, Wry,-};+use tauri::{ipc::Invoke, Emitter, Manager, Runtime, WebviewUrl, WebviewWindowBuilder, Wry};// 托盘相关的 tauri 类型只在非 Linux 路径使用:Linux 走 desktop::linux_tray 的// KSNI 托盘(见该文件的背景说明),届时这些导入会变成未使用。@@ -567,7 +564,7 @@ pub fn build_main_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::We// “源码”按钮在桌面端因此无法跳转(浏览器里正常)。// 这里把 http(s) 链接交给系统浏览器打开,其余协议一律拒绝。.on_new_window(move |url, features| on_new_window(app_handle.clone(), url, features))- .on_download(|webview, event| on_download(webview, event));+ .on_download(on_download);#[cfg(windows)]let webview_builder = webview_builder.on_page_load(move |webview_window, payload| {@@ -705,7 +702,7 @@ pub fn build_extra_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::Wlet webview_builder = webview_builder.disable_drag_drop_handler().on_new_window(move |url, features| on_new_window(app_handle.clone(), url, features))- .on_download(|webview, event| on_download(webview, event));+ .on_download(on_download);#[cfg(windows)]let webview_builder = {@@ -1075,7 +1072,7 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {}// get_store_dat_setting 内部已归一化,取值只可能是 tray 或 quitlet close_action =- crate::config::get_store_dat_setting(&window.app_handle()).close_action;+ crate::config::get_store_dat_setting(window.app_handle()).close_action;if close_action == crate::desktop::activation::CLOSE_ACTION_QUIT {// 不 prevent_close、不 hide:直接退出。app.exit(0) 会走// RunEvent::ExitRequested,既有的几何保存逻辑照常触发@@ -1122,7 +1119,7 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {},tauri::WindowEvent::ScaleFactorChanged { .. } => {if window.label() == crate::desktop::pet::PET_WINDOW_LABEL {- crate::desktop::pet::apply_pet_size(&window.app_handle());+ crate::desktop::pet::apply_pet_size(window.app_handle());}}tauri::WindowEvent::Resized(_) => {diff --git a/src-tauri/src/desktop/pet.rs b/src-tauri/src/desktop/pet.rsindex 5db5f5fe..884a7e5e 100644--- a/src-tauri/src/desktop/pet.rs+++ b/src-tauri/src/desktop/pet.rs@@ -160,6 +160,7 @@ pub fn apply_pet_size<R: Runtime>(app: &AppHandle<R>) {}/// 将窗口左上角限制到单个显示器内;窗口大于显示器时贴齐其左上角。+#[allow(clippy::too_many_arguments)]fn clamp_window_position(x: i32,y: i32,diff --git a/src-tauri/src/desktop/pet_mouse.rs b/src-tauri/src/desktop/pet_mouse.rsindex 28ef90ec..9d32904e 100644--- a/src-tauri/src/desktop/pet_mouse.rs+++ b/src-tauri/src/desktop/pet_mouse.rs@@ -208,7 +208,7 @@ pub fn start_pet_mouse_stream(window: WebviewWindow, state: State<'_, PetMouseStloop {// 每约 500ms 跟随当前接收窗口刷新一次缩放系数:桌宠被拖到另一块缩放// 不同的显示器后,命中换算的系数必须同步(issue #523)。- if ticks % SCALE_REFRESH_TICKS == 0 {+ if ticks.is_multiple_of(SCALE_REFRESH_TICKS) {refresh_scale_factor(&emitter, &throttle_scale);}ticks = ticks.wrapping_add(1);diff --git a/src-tauri/src/logger/mod.rs b/src-tauri/src/logger/mod.rsindex 34c38e0e..cfee01c3 100644--- a/src-tauri/src/logger/mod.rs+++ b/src-tauri/src/logger/mod.rs@@ -9,7 +9,7 @@use std::fs::{File, OpenOptions};use std::io::{self, Write};-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex, OnceLock};use tracing_appender::non_blocking::{NonBlocking, WorkerGuard};@@ -89,9 +89,9 @@ fn frontdesk_log_file_path() -> Option<PathBuf> {Some(app_data_dir()?.join("logs").join(FRONTDESK_LOG_FILE_NAME))}-fn backup_path(base: &PathBuf, n: usize) -> PathBuf {+fn backup_path(base: &Path, n: usize) -> PathBuf {if n == 0 {- base.clone()+ base.to_path_buf()} else {PathBuf::from(format!("{}.{}", base.display(), n))}@@ -427,6 +427,7 @@ pub fn log_frontend(level: FrontendLevel, target: &str, message: &str) {mod tests {use super::*;#[test]+ #[allow(clippy::assertions_on_constants)]fn debug_logs_are_separated_from_release() {// dev 与 release 共用 identifier;不隔离会让两个进程写同一个 desktop.log。assert!(cfg!(debug_assertions), "cargo test 构建为 debug");diff --git a/src-tauri/src/service/backup/archive.rs b/src-tauri/src/service/backup/archive.rsindex 973cfdd5..0d4082b2 100644--- a/src-tauri/src/service/backup/archive.rs+++ b/src-tauri/src/service/backup/archive.rs@@ -70,9 +70,9 @@ fn append_dir_filtered(for entry in fs::read_dir(dir).map_err(|e| format!("BACKUP_ARCHIVE_READDIR: {e}"))? {let entry = entry.map_err(|e| format!("BACKUP_ARCHIVE_ENTRY: {e}"))?;let path = entry.path();- let name = path.file_name().ok_or_else(|| {- format!("BACKUP_ARCHIVE_NO_NAME: {}", path.display())- })?;+ let name = path+ .file_name()+ .ok_or_else(|| format!("BACKUP_ARCHIVE_NO_NAME: {}", path.display()))?;let archived = rel.join(name);// 根相对路径(用于排除判断)let root_rel = path@@ -81,28 +81,32 @@ fn append_dir_filtered(if is_excluded(root_rel, include_credentials) {continue;}- let ty = entry.file_type().map_err(|e| format!("BACKUP_ARCHIVE_TYPE: {e}"))?;+ let ty = entry+ .file_type()+ .map_err(|e| format!("BACKUP_ARCHIVE_TYPE: {e}"))?;if ty.is_dir() {builder.append_dir(&archived, &path).map_err(|e| format!("BACKUP_ARCHIVE_APPEND_DIR: {e}"))?;append_dir_filtered(builder, &path, source, &archived, include_credentials)?;- }- else if ty.is_file() {+ } else if ty.is_file() {builder- .append_file(&archived, &mut fs::File::open(&path).map_err(|e| {- format!("BACKUP_ARCHIVE_OPEN: {e}")- })?)+ .append_file(+ &archived,+ &mut fs::File::open(&path).map_err(|e| format!("BACKUP_ARCHIVE_OPEN: {e}"))?,+ ).map_err(|e| format!("BACKUP_ARCHIVE_APPEND_FILE: {e}"))?;- }- else if ty.is_symlink() {+ } else if ty.is_symlink() {// 符号链接:读取 target,tar Symlink 存储(GNU header 限制 100 字节)- let target = std::fs::read_link(&path)- .map_err(|e| format!("BACKUP_ARCHIVE_READLINK: {e}"))?;+ let target =+ std::fs::read_link(&path).map_err(|e| format!("BACKUP_ARCHIVE_READLINK: {e}"))?;if target.as_os_str().len() > 100 {- eprintln!("[backup] 跳过超长符号链接: {} -> {}", path.display(), target.display());- }- else {+ eprintln!(+ "[backup] 跳过超长符号链接: {} -> {}",+ path.display(),+ target.display()+ );+ } else {let mut header = tar::Header::new_gnu();header.set_entry_type(tar::EntryType::Symlink);header.set_size(0);@@ -113,8 +117,7 @@ fn append_dir_filtered(.append_link(&mut header, &archived, &target).map_err(|e| format!("BACKUP_ARCHIVE_APPEND_LINK: {e}"))?;}- }- else {+ } else {// socket/FIFO/设备:runtime 资源,跳过eprintln!("[backup] 跳过特殊文件: {} ({:?})", path.display(), ty);}@@ -128,23 +131,25 @@ fn append_dir_filtered(/// `.credentials.yaml`。始终排除 `.backups/`、`.harness.pid`、/// `node_modules/.modules.yaml`。使用 zstd 多线程压缩(级别 0 = 默认 3,/// 启用 multithread 加速)。-pub fn create_archive(- source: &Path,- dest: &Path,- include_credentials: bool,-) -> Result<(), String> {+pub fn create_archive(source: &Path, dest: &Path, include_credentials: bool) -> Result<(), String> {let file = fs::File::create(dest).map_err(|e| format!("BACKUP_ARCHIVE_CREATE: {e}"))?;// 级别 0 使用 zstd 默认压缩级别(3),在速度与压缩率间取得平衡。// 多线程压缩:利用多核 CPU 并行压缩块,速度比单线程快 3-5 倍。let workers = std::thread::available_parallelism().map(|n| n.get() as u32).unwrap_or(1);- let mut enc = zstd::stream::Encoder::new(file, 0)- .map_err(|e| format!("BACKUP_ARCHIVE_ENCODER: {e}"))?;+ let mut enc =+ zstd::stream::Encoder::new(file, 0).map_err(|e| format!("BACKUP_ARCHIVE_ENCODER: {e}"))?;enc.multithread(workers).map_err(|e| format!("BACKUP_ARCHIVE_MULTITHREAD: {e}"))?;let mut archive = tar::Builder::new(enc);- append_dir_filtered(&mut archive, source, source, Path::new("."), include_credentials)?;+ append_dir_filtered(+ &mut archive,+ source,+ source,+ Path::new("."),+ include_credentials,+ )?;archive.finish().map_err(|e| format!("BACKUP_ARCHIVE_FINISH: {e}"))?;@@ -168,8 +173,8 @@ pub fn extract_archive(archive: &Path, dest: &Path) -> Result<(), String> {fs::create_dir_all(dest).map_err(|e| format!("BACKUP_EXTRACT_MKDIR: {e}"))?;let file = fs::File::open(archive).map_err(|e| format!("BACKUP_EXTRACT_OPEN: {e}"))?;// 注意:zstd 解码不支持多线程(每帧必须顺序解码),保持单线程- let dec = zstd::stream::Decoder::new(file)- .map_err(|e| format!("BACKUP_EXTRACT_DECODER: {e}"))?;+ let dec =+ zstd::stream::Decoder::new(file).map_err(|e| format!("BACKUP_EXTRACT_DECODER: {e}"))?;let mut archive = tar::Archive::new(dec);extract_tar_entries(&mut archive, dest)}@@ -196,9 +201,15 @@ fn extract_tar_entries<R: Read>(archive: &mut tar::Archive<R>, dest: &Path) -> Rarchive.set_preserve_ownerships(false);// 单次遍历:避免重复调用 archive.entries() 导致 decoder 状态错乱- for entry in archive.entries().map_err(|e| format!("BACKUP_EXTRACT_ENTRIES: {e}"))? {+ for entry in archive+ .entries()+ .map_err(|e| format!("BACKUP_EXTRACT_ENTRIES: {e}"))?+ {let mut entry = entry.map_err(|e| format!("BACKUP_EXTRACT_ENTRY: {e}"))?;- let path = entry.path().map_err(|e| format!("BACKUP_EXTRACT_PATH: {e}"))?.into_owned();+ let path = entry+ .path()+ .map_err(|e| format!("BACKUP_EXTRACT_PATH: {e}"))?+ .into_owned();// 拒绝含 `..` 组件的条目(防路径穿越)if path@@ -228,8 +239,7 @@ fn extract_tar_entries<R: Read>(archive: &mut tar::Archive<R>, dest: &Path) -> R// 创建父目录if let Some(parent) = dest_path.parent() {- fs::create_dir_all(parent)- .map_err(|e| format!("BACKUP_EXTRACT_MKDIR_PARENT: {e}"))?;+ fs::create_dir_all(parent).map_err(|e| format!("BACKUP_EXTRACT_MKDIR_PARENT: {e}"))?;}// 根据 entry type 分支处理(替代 entry.unpack 避免 macOS tar bug)@@ -238,8 +248,7 @@ fn extract_tar_entries<R: Read>(archive: &mut tar::Archive<R>, dest: &Path) -> R// 目录:直接创建fs::create_dir_all(&dest_path).map_err(|e| format!("BACKUP_EXTRACT_MKDIR: {e} (path={})", path.display()))?;- }- else if entry_type.is_symlink() {+ } else if entry_type.is_symlink() {// 符号链接:读取 target 并创建链接let target = entry.link_name()@@ -254,12 +263,12 @@ fn extract_tar_entries<R: Read>(archive: &mut tar::Archive<R>, dest: &Path) -> Rif e.kind() != std::io::ErrorKind::AlreadyExists {return Err(format!("BACKUP_EXTRACT_SYMLINK: {e} (target={}, dest={})",- target.display(), dest_path.display()+ target.display(),+ dest_path.display()));}}- }- else {+ } else {// 普通文件:先写临时文件,再原子 rename(macOS 上 unlink + write 会被// 读锁干扰成 0 字节;temp + rename 是原子的,原文件在成功前保持完好)let mut content = Vec::new();@@ -268,7 +277,10 @@ fn extract_tar_entries<R: Read>(archive: &mut tar::Archive<R>, dest: &Path) -> R// 临时文件路径:<dest>.tmp.<pid>.<nanos>let tmp_name = format!("{}.tmp.{}.{}",- dest_path.file_name().and_then(|n| n.to_str()).unwrap_or("restore"),+ dest_path+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("restore"),std::process::id(),std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)@@ -276,11 +288,17 @@ fn extract_tar_entries<R: Read>(archive: &mut tar::Archive<R>, dest: &Path) -> R.as_nanos());let tmp_path = dest_path.with_file_name(tmp_name);- fs::write(&tmp_path, &content)- .map_err(|e| format!("BACKUP_EXTRACT_WRITE_TMP: {e} (tmp={})", tmp_path.display()))?;+ fs::write(&tmp_path, &content).map_err(|e| {+ format!("BACKUP_EXTRACT_WRITE_TMP: {e} (tmp={})", tmp_path.display())+ })?;// 原子 rename 替换目标文件(macOS 上 rename 不要求目标文件关闭)- fs::rename(&tmp_path, &dest_path)- .map_err(|e| format!("BACKUP_EXTRACT_RENAME: {e} (tmp={}, dest={})", tmp_path.display(), dest_path.display()))?;+ fs::rename(&tmp_path, &dest_path).map_err(|e| {+ format!(+ "BACKUP_EXTRACT_RENAME: {e} (tmp={}, dest={})",+ tmp_path.display(),+ dest_path.display()+ )+ })?;}}Ok(())@@ -290,11 +308,13 @@ fn extract_tar_entries<R: Read>(archive: &mut tar::Archive<R>, dest: &Path) -> R#[cfg(test)]fn list_archive_entries(archive: &Path) -> Result<Vec<String>, String> {let file = fs::File::open(archive).map_err(|e| format!("BACKUP_LIST_OPEN: {e}"))?;- let dec = zstd::stream::Decoder::new(file)- .map_err(|e| format!("BACKUP_LIST_DECODER: {e}"))?;+ let dec = zstd::stream::Decoder::new(file).map_err(|e| format!("BACKUP_LIST_DECODER: {e}"))?;let mut archive = tar::Archive::new(dec);let mut entries = Vec::new();- for entry in archive.entries().map_err(|e| format!("BACKUP_LIST_ENTRIES: {e}"))? {+ for entry in archive+ .entries()+ .map_err(|e| format!("BACKUP_LIST_ENTRIES: {e}"))?+ {let entry = entry.map_err(|e| format!("BACKUP_LIST_ENTRY: {e}"))?;let path = entry.path().map_err(|e| format!("BACKUP_LIST_PATH: {e}"))?;entries.push(path.to_string_lossy().replace('\\', "/"));@@ -320,10 +340,10 @@ mod tests {/// 计算与 source 同级的归档目标路径。fn archive_dest(source: &Path) -> PathBuf {- source- .parent()- .unwrap()- .join(format!("{}.tar.zst", source.file_name().unwrap().to_str().unwrap()))+ source.parent().unwrap().join(format!(+ "{}.tar.zst",+ source.file_name().unwrap().to_str().unwrap()+ ))}/// 创建临时目录并写入若干文件作为测试夹具。@@ -382,10 +402,7 @@ mod tests {#[test]fn credentials_excluded_by_default() {- let source = setup_source_dir(&[- (".credentials.yaml", "key: secret"),- ("data.txt", "ok"),- ]);+ let source = setup_source_dir(&[(".credentials.yaml", "key: secret"), ("data.txt", "ok")]);let dest = archive_dest(&source);create_archive(&source, &dest, false).unwrap();let entries = list_archive_entries(&dest).unwrap();@@ -399,10 +416,7 @@ mod tests {#[test]fn credentials_included_when_opted_in() {- let source = setup_source_dir(&[- (".credentials.yaml", "key: secret"),- ("data.txt", "ok"),- ]);+ let source = setup_source_dir(&[(".credentials.yaml", "key: secret"), ("data.txt", "ok")]);let dest = archive_dest(&source);create_archive(&source, &dest, true).unwrap();let entries = list_archive_entries(&dest).unwrap();@@ -421,7 +435,8 @@ mod tests {create_archive(&source, &dest_zst, false).unwrap();// 还原到新目录- let restore_dir = std::env::temp_dir().join(format!("dsh-backup-restore-{}", unique_suffix()));+ let restore_dir =+ std::env::temp_dir().join(format!("dsh-backup-restore-{}", unique_suffix()));extract_archive(&dest_zst, &restore_dir).unwrap();let restored_path = restore_dir.join("config.yaml");@@ -451,7 +466,8 @@ mod tests {let mode = b"0000644\0";header[100..108].copy_from_slice(mode);// uid/gid 0 (108..124)- header[108..124].copy_from_slice(b"0000000\00000000\0");+ header[108..116].copy_from_slice(b"0000000\0");+ header[116..124].copy_from_slice(b"0000000\0");// size (octal, 124..136)let size_str = format!("{:011o}\0", data.len());header[124..124 + size_str.len()].copy_from_slice(size_str.as_bytes());@@ -473,7 +489,9 @@ mod tests {// pad to 512 boundarylet pad = (512 - (data.len() % 512)) % 512;if pad > 0 {- writer.write_all(&vec![0u8; pad]).map_err(|e| e.to_string())?;+ writer+ .write_all(&vec![0u8; pad])+ .map_err(|e| e.to_string())?;}Ok(())}@@ -540,7 +558,10 @@ mod tests {(name, content)}).collect();- let refs: Vec<(&str, &str)> = files.iter().map(|(p, c)| (p.as_str(), c.as_str())).collect();+ let refs: Vec<(&str, &str)> = files+ .iter()+ .map(|(p, c)| (p.as_str(), c.as_str()))+ .collect();let source = setup_source_dir(&refs);let dest = archive_dest(&source);@@ -548,7 +569,8 @@ mod tests {assert!(dest.exists(), "归档文件应存在");// 解压到新目录并验证内容- let restore_dir = std::env::temp_dir().join(format!("dsh-backup-mt-restore-{}", unique_suffix()));+ let restore_dir =+ std::env::temp_dir().join(format!("dsh-backup-mt-restore-{}", unique_suffix()));extract_archive(&dest, &restore_dir).unwrap();for (rel, expected) in &files {@@ -611,16 +633,24 @@ mod tests {// 验证归档中包含 link 条目let entries = list_archive_entries(&dest).unwrap();- assert!(entries.iter().any(|e| e.ends_with("link.txt")), "归档应包含 link.txt");+ assert!(+ entries.iter().any(|e| e.ends_with("link.txt")),+ "归档应包含 link.txt"+ );// 还原并验证符号链接- let restore_dir = std::env::temp_dir().join(format!("dsh-backup-symlink-{}", unique_suffix()));+ let restore_dir =+ std::env::temp_dir().join(format!("dsh-backup-symlink-{}", unique_suffix()));extract_archive(&dest, &restore_dir).unwrap();let link_path = restore_dir.join("link.txt");assert!(link_path.is_symlink(), "link.txt 应为符号链接");let target = std::fs::read_link(&link_path).unwrap();- assert_eq!(target, std::path::PathBuf::from("target.txt"), "链接目标应一致");+ assert_eq!(+ target,+ std::path::PathBuf::from("target.txt"),+ "链接目标应一致"+ );let _ = fs::remove_dir_all(&source);let _ = fs::remove_file(&dest);@@ -657,7 +687,9 @@ mod tests {// 创建 FIFO(named pipe):mkfifo 需要 C stringunsafe {libc::mkfifo(- std::ffi::CString::new(fifo_path.to_str().unwrap()).unwrap().as_ptr(),+ std::ffi::CString::new(fifo_path.to_str().unwrap())+ .unwrap()+ .as_ptr(),0o644,);}@@ -677,10 +709,8 @@ mod tests {#[cfg(unix)]#[test]fn handles_mixed_file_types() {- let source = setup_source_dir(&[- ("normal.txt", "content"),- ("subdir/nested.txt", "nested"),- ]);+ let source =+ setup_source_dir(&[("normal.txt", "content"), ("subdir/nested.txt", "nested")]);// 添加符号链接std::os::unix::fs::symlink("normal.txt", source.join("link_to_normal")).unwrap();// 添加 socket@@ -719,7 +749,8 @@ mod tests {let dest = archive_dest(&source);create_archive(&source, &dest, false).unwrap();- let restore_dir = std::env::temp_dir().join(format!("dsh-backup-nested-{}", unique_suffix()));+ let restore_dir =+ std::env::temp_dir().join(format!("dsh-backup-nested-{}", unique_suffix()));extract_archive(&dest, &restore_dir).unwrap();let link = restore_dir.join("sub").join("up_link");diff --git a/src-tauri/src/service/cli/path/rc.rs b/src-tauri/src/service/cli/path/rc.rsindex 8ff2b09d..89a34db4 100644--- a/src-tauri/src/service/cli/path/rc.rs+++ b/src-tauri/src/service/cli/path/rc.rs@@ -142,10 +142,10 @@ fn write_rc_with_backup(rc_path: &std::path::Path, new_content: &str) -> Result</// 同时被注入(`upsert_rc_block`)与移除路径使用。#[cfg_attr(windows, allow(dead_code))]fn strip_rc_block(content: &str) -> String {- let mut lines = content.lines().peekable();+ let lines = content.lines().peekable();let mut out = String::with_capacity(content.len());let mut skipping = false;- while let Some(line) = lines.next() {+ for line in lines {if line.trim() == RC_MARK_START {skipping = true;continue;diff --git a/src-tauri/src/service/cli/shim/templates.rs b/src-tauri/src/service/cli/shim/templates.rsindex d7c00365..48db06c9 100644--- a/src-tauri/src/service/cli/shim/templates.rs+++ b/src-tauri/src/service/cli/shim/templates.rs@@ -179,8 +179,7 @@ if ($userDsh) {}"#;-#[cfg_attr(windows, allow(dead_code))] // 仅 Unix shim 使用-#[cfg_attr(debug_assertions, allow(dead_code))]+#[cfg_attr(any(windows, debug_assertions), allow(dead_code))] // 仅 Unix shim 使用pub(super) const SH_USER_DSH_PRECEDENCE: &str = r#"# Prefer a user-installed dsh on PATH (skip our own shim dir), fall back to bundled.# This preserves your own dsh binary and its $DSH_HOME config; nothing is overwritten.diff --git a/src-tauri/src/service/core/local.rs b/src-tauri/src/service/core/local.rsindex 4c7d206d..23f446de 100644--- a/src-tauri/src/service/core/local.rs+++ b/src-tauri/src/service/core/local.rs@@ -118,7 +118,9 @@ fn append_windows_dsh_dirs(dirs: &mut Vec<PathBuf>) {append(PathBuf::from(appdata).join("npm"));}if let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") {- let fnm_versions = PathBuf::from(&local_app_data).join("fnm").join("node-versions");+ let fnm_versions = PathBuf::from(&local_app_data)+ .join("fnm")+ .join("node-versions");if let Ok(entries) = std::fs::read_dir(&fnm_versions) {for entry in entries.flatten() {// 版本目录下 `installation` 是 node 实际安装根;npm 全局包位于其@@ -335,7 +337,7 @@ pub async fn update_local_core(app_handle: AppHandle) -> Result<String, String>};if !status {- let output = tail(stdout.into_iter().chain(stderr.into_iter()).collect());+ let output = tail(stdout.into_iter().chain(stderr).collect());return Err(format!("CORE_UPDATE_FAILED: {output}"));}@@ -407,7 +409,10 @@ 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(std::slice::from_ref(&dir), &["dsh"]),+ Some(dsh)+ );let _ = std::fs::remove_dir_all(&dir);}@@ -419,7 +424,10 @@ mod tests {let ours = write_our_shim(&shim_dir);let theirs = write_foreign_dsh(&bin_dir);// 只扫 shim 目录 → 跳过本应用 shim,无命中- assert_eq!(scan_dirs_for_user_dsh(&[shim_dir.clone()], &["dsh"]), None);+ assert_eq!(+ scan_dirs_for_user_dsh(std::slice::from_ref(&shim_dir), &["dsh"]),+ None+ );// 同时扫两个目录 → 命中用户 dsh(不是本应用 shim)assert_eq!(scan_dirs_for_user_dsh(&[shim_dir.clone(), bin_dir.clone()], &["dsh"]),diff --git a/src-tauri/src/service/core/runtime.rs b/src-tauri/src/service/core/runtime.rsindex e0f409af..5e6dda89 100644--- a/src-tauri/src/service/core/runtime.rs+++ b/src-tauri/src/service/core/runtime.rs@@ -40,7 +40,7 @@ const NATIVE_PROBE_MARKER: &str = "__DSH_NATIVE_PROBE__";/// 2. 原生包:带 `binding.gyp` 或自带原生产物目录(`build/Release`、`build/Debug`、/// `prebuilds`、`prebuilt`)的包,逐个 require —— 与 dsh 自身的加载方式一致,/// 加载失败即为 dsh 启动时同样的失败(fs-ext 这类 node-gyp 包落在 build/Release)。-/// 崩溃/异常退出时不会有标记行,Rust 侧按"结论未知"处理,不阻断启动。+/// 崩溃/异常退出时不会有标记行,Rust 侧按"结论未知"处理,不阻断启动。const NATIVE_PROBE_SCRIPT: &str = r#"const { createRequire } = await import('node:module');const { existsSync, readdirSync } = await import('node:fs');@@ -159,7 +159,9 @@ impl NativeProbe {}fn has_platform_import_failure(&self) -> bool {- self.failures().iter().any(NativeProbeFailure::is_platform_import)+ self.failures()+ .iter()+ .any(NativeProbeFailure::is_platform_import)}/// ABI 不匹配的包名(去重,保持探测顺序)@@ -180,7 +182,7 @@ impl NativeProbe {/// 缺失时只按核心清单中的 optionalDependencies 动态构造安装参数,避免把某一台/// 机器的版本、平台或架构写死在桌面端。失败返回诊断错误,调用方不应继续启动/// 一个已知无法加载的 dsh 进程。- pub(crate) async fn prepare_active_runtime(app_handle: &AppHandle) -> Result<(), String> {+pub(crate) async fn prepare_active_runtime(app_handle: &AppHandle) -> Result<(), String> {if crate::service::core::active_source(app_handle) != CoreSource::App {log::debug!("Skipping core runtime repair for user-owned local core");return Ok(());@@ -299,7 +301,11 @@ impl NativeProbe {// 4) 仍然无法加载:给出精确诊断(模块名 + ABI 差异),而不是让 dsh 在插件树加载// 阶段崩溃、前端只显示 HARNESS_NOT_OWNED。- Err(native_failure_diagnostic(probe.failures(), &node, &core_root))+ Err(native_failure_diagnostic(+ probe.failures(),+ &node,+ &core_root,+ ))}/// 从活动 profile 与应用内置清单收集需要在核心根下解析的包,并逐个建立入口。@@ -415,7 +421,11 @@ fn ensure_package_link(name: &str, source: &Path, node_modules: &Path) -> Resultlet existing = match std::fs::symlink_metadata(&destination) {Ok(metadata) => Some(metadata),Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,- Err(e) => return Err(format!("CORE_PLUGIN_DESTINATION_STAT_FAILED: {destination:?}: {e}")),+ Err(e) => {+ return Err(format!(+ "CORE_PLUGIN_DESTINATION_STAT_FAILED: {destination:?}: {e}"+ ))+ }};if let Some(metadata) = existing {if !metadata.file_type().is_symlink() {@@ -460,7 +470,10 @@ fn ensure_package_link(name: &str, source: &Path, node_modules: &Path) -> Result/// 校验并创建 scope 目录;目录本身不能是链接,防止目的地逃逸核心根。fn ensure_non_link_directory(path: &Path, root: &Path) -> Result<(), String> {if !path.starts_with(root) {- return Err(format!("CORE_PLUGIN_DESTINATION_ESCAPE: {}", path.display()));+ return Err(format!(+ "CORE_PLUGIN_DESTINATION_ESCAPE: {}",+ path.display()+ ));}let relative = path.strip_prefix(root).unwrap_or(Path::new("."));let mut current = root.to_path_buf();@@ -474,13 +487,26 @@ fn ensure_non_link_directory(path: &Path, root: &Path) -> Result<(), String> {));}Ok(metadata) if metadata.is_dir() => {}- Ok(_) => return Err(format!("CORE_PLUGIN_DESTINATION_PARENT_INVALID: {}", current.display())),+ Ok(_) => {+ return Err(format!(+ "CORE_PLUGIN_DESTINATION_PARENT_INVALID: {}",+ current.display()+ ))+ }Err(e) if e.kind() == std::io::ErrorKind::NotFound => {std::fs::create_dir(¤t).map_err(|e| {- format!("CORE_PLUGIN_DESTINATION_PARENT_CREATE_FAILED: {}: {e}", current.display())+ format!(+ "CORE_PLUGIN_DESTINATION_PARENT_CREATE_FAILED: {}: {e}",+ current.display()+ )})?;}- Err(e) => return Err(format!("CORE_PLUGIN_DESTINATION_PARENT_STAT_FAILED: {}: {e}", current.display())),+ Err(e) => {+ return Err(format!(+ "CORE_PLUGIN_DESTINATION_PARENT_STAT_FAILED: {}: {e}",+ current.display()+ ))+ }}}Ok(())@@ -541,9 +567,9 @@ fn create_directory_junction(source: &Path, destination: &Path) -> std::io::ResuCreateFileW, FILE_FLAG_BACKUP_SEMANTICS, FILE_SHARE_DELETE, FILE_SHARE_READ,FILE_SHARE_WRITE, OPEN_EXISTING,};- use windows_sys::Win32::System::IO::DeviceIoControl;use windows_sys::Win32::System::Ioctl::FSCTL_SET_REPARSE_POINT;use windows_sys::Win32::System::SystemServices::IO_REPARSE_TAG_MOUNT_POINT;+ use windows_sys::Win32::System::IO::DeviceIoControl;// junction 目标必须是 NT 命名空间内的绝对路径:盘符路径映射为// `\??\G:\...`,UNC 路径映射为 `\??\UNC\server\share\...`。@@ -668,7 +694,10 @@ fn is_safe_package_name(name: &str) -> bool {if parts.len() == 1 {return valid_package_component(parts[0]);}- parts.len() == 2 && parts[0].starts_with('@') && valid_package_component(parts[0]) && valid_package_component(parts[1])+ parts.len() == 2+ && parts[0].starts_with('@')+ && valid_package_component(parts[0])+ && valid_package_component(parts[1])}fn valid_package_component(value: &str) -> bool {@@ -681,19 +710,40 @@ fn valid_package_component(value: &str) -> bool {}fn read_package_name(path: &Path) -> Result<Option<String>, String> {- let raw = std::fs::read_to_string(path)- .map_err(|e| format!("CORE_PLUGIN_PACKAGE_MANIFEST_READ_FAILED: {}: {e}", path.display()))?;- let value = serde_json::from_str::<serde_json::Value>(&raw)- .map_err(|e| format!("CORE_PLUGIN_PACKAGE_MANIFEST_INVALID: {}: {e}", path.display()))?;- Ok(value.get("name").and_then(|value| value.as_str()).map(str::to_owned))+ let raw = std::fs::read_to_string(path).map_err(|e| {+ format!(+ "CORE_PLUGIN_PACKAGE_MANIFEST_READ_FAILED: {}: {e}",+ path.display()+ )+ })?;+ let value = serde_json::from_str::<serde_json::Value>(&raw).map_err(|e| {+ format!(+ "CORE_PLUGIN_PACKAGE_MANIFEST_INVALID: {}: {e}",+ path.display()+ )+ })?;+ Ok(value+ .get("name")+ .and_then(|value| value.as_str())+ .map(str::to_owned))}async fn detect_node_target(node: &Path, core_root: &Path) -> Result<NodeTarget, String> {let node = node.to_path_buf();let core_root = core_root.to_path_buf();- let output = tokio::task::spawn_blocking(move || run_command(&node, &["--input-type=module".into(), "-e".into(), NODE_PROBE_SCRIPT.into()], &core_root))- .await- .map_err(|e| format!("CORE_NODE_PLATFORM_PROBE_FAILED: {e}"))??;+ let output = tokio::task::spawn_blocking(move || {+ run_command(+ &node,+ &[+ "--input-type=module".into(),+ "-e".into(),+ NODE_PROBE_SCRIPT.into(),+ ],+ &core_root,+ )+ })+ .await+ .map_err(|e| format!("CORE_NODE_PLATFORM_PROBE_FAILED: {e}"))??;if !output.status.success() {return Err(format!("CORE_NODE_PLATFORM_PROBE_FAILED: {}",@@ -705,11 +755,17 @@ async fn detect_node_target(node: &Path, core_root: &Path) -> Result<NodeTarget,return Err(format!("CORE_NODE_PLATFORM_UNSUPPORTED: {value}"));};let supported_platform = matches!(platform, "darwin" | "linux" | "win32");- let supported_arch = matches!(arch, "x64" | "arm64" | "ia32" | "arm" | "ppc64" | "riscv64" | "s390x" | "loong64");+ let supported_arch = matches!(+ arch,+ "x64" | "arm64" | "ia32" | "arm" | "ppc64" | "riscv64" | "s390x" | "loong64"+ );if !supported_platform || !supported_arch {return Err(format!("CORE_NODE_PLATFORM_UNSUPPORTED: {value}"));}- Ok(NodeTarget { platform: platform.to_string(), arch: arch.to_string() })+ Ok(NodeTarget {+ platform: platform.to_string(),+ arch: arch.to_string(),+ })}/// 用指定运行时执行原生模块探测脚本,返回结构化结论。@@ -723,7 +779,13 @@ async fn probe_native_modules(node: &Path, core_root: &Path) -> NativeProbe {OsString::from("-e"),OsString::from(NATIVE_PROBE_SCRIPT),];- run_process_with_timeout(&program, &args, &core_root, NATIVE_PROBE_TIMEOUT, "native probe")+ run_process_with_timeout(+ &program,+ &args,+ &core_root,+ NATIVE_PROBE_TIMEOUT,+ "native probe",+ )}).await;@@ -803,7 +865,11 @@ fn is_bundled_runtime_node(node: &Path, app_handle: &AppHandle) -> bool {}/// 生成原生模块加载失败的诊断信息:ABI 不匹配单独给出可读结论,其余按原样列出。-fn native_failure_diagnostic(failures: &[NativeProbeFailure], node: &Path, core_root: &Path) -> String {+fn native_failure_diagnostic(+ failures: &[NativeProbeFailure],+ node: &Path,+ core_root: &Path,+) -> String {if failures.is_empty() {return format!("CORE_NATIVE_DEPENDENCY_REPAIR_FAILED: native modules could not be verified in {}",@@ -833,7 +899,11 @@ fn native_failure_diagnostic(failures: &[NativeProbeFailure], node: &Path, core_core_root.display(),failures.iter()- .map(|failure| format!("{}: {}", failure.name, collapse_whitespace(&failure.message)))+ .map(|failure| format!(+ "{}: {}",+ failure.name,+ collapse_whitespace(&failure.message)+ )).collect::<Vec<_>>().join("; "))@@ -861,7 +931,13 @@ async fn rebuild_native_packages(let (program, mut args) = npm_command(&node);args.push(OsString::from("rebuild"));args.extend(packages.into_iter().map(OsString::from));- run_process_with_timeout(&program, &args, &core_root, NATIVE_REBUILD_TIMEOUT, "npm rebuild")+ run_process_with_timeout(+ &program,+ &args,+ &core_root,+ NATIVE_REBUILD_TIMEOUT,+ "npm rebuild",+ )}).await.map_err(|e| format!("CORE_NATIVE_REBUILD_FAILED: {e}"))??;@@ -895,9 +971,21 @@ fn npm_cli_path_for(node: &Path) -> Option<PathBuf> {// 官方发行版:<node>/bin/node + <node>/lib/node_modules/npm/bin/npm-cli.js// 少数布局把 lib 放在 node 目录之外,再补一个上级 lib 候选。let candidates = [- dir.join("node_modules").join("npm").join("bin").join("npm-cli.js"),- dir.join("lib").join("node_modules").join("npm").join("bin").join("npm-cli.js"),- dir.join("..").join("lib").join("node_modules").join("npm").join("bin").join("npm-cli.js"),+ dir.join("node_modules")+ .join("npm")+ .join("bin")+ .join("npm-cli.js"),+ dir.join("lib")+ .join("node_modules")+ .join("npm")+ .join("bin")+ .join("npm-cli.js"),+ dir.join("..")+ .join("lib")+ .join("node_modules")+ .join("npm")+ .join("bin")+ .join("npm-cli.js"),];candidates.into_iter().find(|candidate| candidate.is_file())}@@ -963,12 +1051,20 @@ fn read_optional_dependencies(path: &Path) -> HashMap<String, String> {.unwrap_or_default()}-async fn install_native_packages(core_root: &Path, target: &NodeTarget, packages: &[String]) -> Result<(), String> {+async fn install_native_packages(+ core_root: &Path,+ target: &NodeTarget,+ packages: &[String],+) -> Result<(), String> {let core_root = core_root.to_path_buf();let target = target.clone();let packages = packages.to_vec();let result = tokio::task::spawn_blocking(move || {- let program = if cfg!(windows) { OsString::from("npm.cmd") } else { OsString::from("npm") };+ let program = if cfg!(windows) {+ OsString::from("npm.cmd")+ } else {+ OsString::from("npm")+ };let mut args = vec![OsString::from("install"),OsString::from("--no-save"),@@ -978,7 +1074,13 @@ async fn install_native_packages(core_root: &Path, target: &NodeTarget, packagesOsString::from(format!("--cpu={}", target.arch)),];args.extend(packages.into_iter().map(OsString::from));- run_process_with_timeout(&program, &args, &core_root, NATIVE_REPAIR_TIMEOUT, "npm install")+ run_process_with_timeout(+ &program,+ &args,+ &core_root,+ NATIVE_REPAIR_TIMEOUT,+ "npm install",+ )}).await.map_err(|e| format!("CORE_NATIVE_DEPENDENCY_REPAIR_FAILED: {e}"))??;@@ -992,15 +1094,25 @@ async fn install_native_packages(core_root: &Path, target: &NodeTarget, packagesOk(())}-fn run_command(program: &Path, args: &[OsString], cwd: &Path) -> Result<std::process::Output, String> {+fn run_command(+ program: &Path,+ args: &[OsString],+ cwd: &Path,+) -> Result<std::process::Output, String> {let mut command = Command::new(program);- command.args(args).current_dir(cwd).stdout(Stdio::piped()).stderr(Stdio::piped());+ command+ .args(args)+ .current_dir(cwd)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());#[cfg(windows)]{use std::os::windows::process::CommandExt;command.creation_flags(0x08000000);}- command.output().map_err(|e| format!("CORE_RUNTIME_COMMAND_FAILED: {}: {e}", program.display()))+ command+ .output()+ .map_err(|e| format!("CORE_RUNTIME_COMMAND_FAILED: {}: {e}", program.display()))}fn run_process_with_timeout(@@ -1011,7 +1123,11 @@ fn run_process_with_timeout(label: &str,) -> Result<std::process::Output, String> {let mut command = Command::new(program);- command.args(args).current_dir(cwd).stdout(Stdio::piped()).stderr(Stdio::piped());+ command+ .args(args)+ .current_dir(cwd)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());#[cfg(windows)]{use std::os::windows::process::CommandExt;@@ -1034,14 +1150,23 @@ fn run_process_with_timeout(});let started = Instant::now();loop {- if let Some(status) = child.try_wait().map_err(|e| format!("CORE_NATIVE_DEPENDENCY_REPAIR_WAIT_FAILED: {e}"))? {+ if let Some(status) = child+ .try_wait()+ .map_err(|e| format!("CORE_NATIVE_DEPENDENCY_REPAIR_WAIT_FAILED: {e}"))?+ {let stdout = stdout_thread.join().unwrap_or_default();let stderr = stderr_thread.join().unwrap_or_default();- return Ok(std::process::Output { status, stdout, stderr });+ return Ok(std::process::Output {+ status,+ stdout,+ stderr,+ });}if started.elapsed() >= timeout {let _ = child.kill();- let status = child.wait().map_err(|e| format!("CORE_NATIVE_DEPENDENCY_REPAIR_KILL_FAILED: {e}"))?;+ let status = child+ .wait()+ .map_err(|e| format!("CORE_NATIVE_DEPENDENCY_REPAIR_KILL_FAILED: {e}"))?;// 排空管道,避免子进程因写满缓冲而挂起;输出在超时路径不作分析。let _ = stdout_thread.join().unwrap_or_default();let _ = stderr_thread.join().unwrap_or_default();@@ -1059,7 +1184,15 @@ fn command_output_tail(output: &std::process::Output) -> String {if value.trim().is_empty() {value = String::from_utf8_lossy(&output.stdout).to_string();}- value.trim().chars().rev().take(2000).collect::<String>().chars().rev().collect()+ value+ .trim()+ .chars()+ .rev()+ .take(2000)+ .collect::<String>()+ .chars()+ .rev()+ .collect()}#[cfg(test)]@@ -1095,13 +1228,19 @@ mod tests {.unwrap();let plan = native_package_plan(&root,- &NodeTarget { platform: "darwin".into(), arch: "arm64".into() },+ &NodeTarget {+ platform: "darwin".into(),+ arch: "arm64".into(),+ },+ );+ assert_eq!(+ plan,+ vec![+ "@img/[email protected]",+ "@img/[email protected]",+ "@koromix/[email protected]",+ ]);- assert_eq!(plan, vec![- "@img/[email protected]",- "@img/[email protected]",- "@koromix/[email protected]",- ]);let _ = std::fs::remove_dir_all(root);}@@ -1123,7 +1262,10 @@ mod tests {.unwrap_or_else(|e| panic!("link must be created without privileges: {e}"));let metadata = std::fs::symlink_metadata(&destination).unwrap();- assert!(metadata.file_type().is_symlink(), "junction must be treated as a link");+ assert!(+ metadata.file_type().is_symlink(),+ "junction must be treated as a link"+ );let resolved = std::fs::read_link(&destination).unwrap();assert_eq!(resolved.canonicalize().unwrap(), canonical_source);@@ -1167,7 +1309,10 @@ mod tests {.unwrap_or_else(|e| panic!("junction must be creatable without privileges: {e}"));let metadata = std::fs::symlink_metadata(&destination).unwrap();- assert!(metadata.file_type().is_symlink(), "junction must be treated as a link");+ assert!(+ metadata.file_type().is_symlink(),+ "junction must be treated as a link"+ );assert_eq!(std::fs::canonicalize(&destination).unwrap(),canonical_source,@@ -1279,7 +1424,10 @@ mod tests {assert!(diagnostic.starts_with("CORE_NATIVE_ABI_MISMATCH:"));assert!(diagnostic.contains("fs-ext"));assert!(diagnostic.contains("NODE_MODULE_VERSION 137"));- assert!(!diagnostic.contains('\n'), "diagnostic must be a single line");+ assert!(+ !diagnostic.contains('\n'),+ "diagnostic must be a single line"+ );assert!(diagnostic.contains("install the Node.js version the core was built with"));}@@ -1291,7 +1439,8 @@ mod tests {message: "Cannot find module 'sharp'".into(),abi: false,}];- let diagnostic = native_failure_diagnostic(&failures, Path::new("node"), Path::new("C:\\core"));+ let diagnostic =+ native_failure_diagnostic(&failures, Path::new("node"), Path::new("C:\\core"));assert!(diagnostic.starts_with("CORE_NATIVE_DEPENDENCY_REPAIR_FAILED:"));assert!(diagnostic.contains("sharp: Cannot find module 'sharp'"));}@@ -1308,7 +1457,11 @@ mod tests {let _ = std::fs::remove_dir_all(&root);let bin_dir = root.join("node-v22.22.0-win-x64");std::fs::create_dir_all(bin_dir.join("node_modules").join("npm").join("bin")).unwrap();- let npm_cli = bin_dir.join("node_modules").join("npm").join("bin").join("npm-cli.js");+ let npm_cli = bin_dir+ .join("node_modules")+ .join("npm")+ .join("bin")+ .join("npm-cli.js");std::fs::write(&npm_cli, "// npm").unwrap();let node = bin_dir.join("node.exe");@@ -1321,7 +1474,7 @@ mod tests {let bare = root.join("bare").join("node.exe");std::fs::create_dir_all(bare.parent().unwrap()).unwrap();let (program, args) = npm_command(&bare);- assert!(program == OsString::from("npm.cmd") || program == OsString::from("npm"));+ assert!(program == "npm.cmd" || program == "npm");assert!(args.is_empty());let _ = std::fs::remove_dir_all(&root);@@ -1357,7 +1510,8 @@ mod tests {String::from_utf8_lossy(&output.stderr));// 空核心目录:sharp/koffi 解析失败但属于非 ABI 失败,必须能结构化解析。- let failures = parse_native_probe_failures(&stdout).expect("probe must emit the marker line");+ let failures =+ parse_native_probe_failures(&stdout).expect("probe must emit the marker line");assert!(failures.iter().all(|failure| !failure.abi));let _ = std::fs::remove_dir_all(&root);@@ -1375,7 +1529,11 @@ mod tests {let pkg = root.join("node_modules").join("fs-ext");std::fs::create_dir_all(pkg.join("build").join("Release")).unwrap();std::fs::write(pkg.join("binding.gyp"), "{}").unwrap();- std::fs::write(pkg.join("build").join("Release").join("fs_ext.node"), "stub").unwrap();+ std::fs::write(+ pkg.join("build").join("Release").join("fs_ext.node"),+ "stub",+ )+ .unwrap();std::fs::write(pkg.join("package.json"),r#"{"name":"fs-ext","main":"index.js"}"#,@@ -1399,10 +1557,13 @@ mod tests {command.creation_flags(0x08000000);}let output = command.output().expect("node must be runnable");- let failures =- parse_native_probe_failures(&String::from_utf8_lossy(&output.stdout)).expect("marker line");+ let failures = parse_native_probe_failures(&String::from_utf8_lossy(&output.stdout))+ .expect("marker line");let probe = NativeProbe::Failed(failures);- assert!(probe.has_abi_mismatch(), "fs-ext must be reported as an ABI mismatch");+ assert!(+ probe.has_abi_mismatch(),+ "fs-ext must be reported as an ABI mismatch"+ );assert_eq!(probe.abi_packages(), vec!["fs-ext".to_string()]);// 诊断必须点名模块,供前端直接展示(而不是让用户只看到 HARNESS_NOT_OWNED)let diagnostic = native_failure_diagnostic(probe.failures(), &node, &root);diff --git a/src-tauri/src/service/core/version.rs b/src-tauri/src/service/core/version.rsindex 91174c7c..7b4bdc14 100644--- a/src-tauri/src/service/core/version.rs+++ b/src-tauri/src/service/core/version.rs@@ -383,11 +383,11 @@ pub async fn set_active(app_handle: &AppHandle, id: &str) -> Result<HarnessCore,// set_active 返回后通过同一把锁与启动串行化。drop(transition_guard);- Ok(list(app_handle)+ list(app_handle).await.into_iter().find(|c| c.active)- .ok_or_else(|| "CORE_NOT_FOUND: active core disappeared after switch".to_string())?)+ .ok_or_else(|| "CORE_NOT_FOUND: active core disappeared after switch".to_string())}/// 切换到指定 tag 的预打包版本(已下载的历史槽位)。@@ -495,18 +495,16 @@ async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), Str));}- if holding.exists() {- if !download::remove_dir_with_retry(&holding).await {+ if holding.exists() && !download::remove_dir_with_retry(&holding).await {+ log::warn!(+ "CORE_SWITCH_WARNING: failed to remove stale backup {} after successful switch",+ holding.display()+ );+ if let Err(e) = download::rename_with_retry(&holding, &stale_backup).await {log::warn!(- "CORE_SWITCH_WARNING: failed to remove stale backup {} after successful switch",- holding.display()+ "CORE_SWITCH_WARNING: failed to rename stale backup to {}: {e}",+ stale_backup.display());- if let Err(e) = download::rename_with_retry(&holding, &stale_backup).await {- log::warn!(- "CORE_SWITCH_WARNING: failed to rename stale backup to {}: {e}",- stale_backup.display()- );- }}}diff --git a/src-tauri/src/service/download/github.rs b/src-tauri/src/service/download/github.rsindex 3dc409b2..174b2225 100644--- a/src-tauri/src/service/download/github.rs+++ b/src-tauri/src/service/download/github.rs@@ -77,7 +77,7 @@ fn parse_release_list_from_html(body: &str) -> Vec<DshPkgReleaseMeta> {let mut cursor = 0;while let Some(relative) = body[cursor..].find(marker) {let start = cursor + relative + marker.len();- let Some(end) = body[start..].find(|c: char| c == '"' || c == '\'' || c == '?') else {+ let Some(end) = body[start..].find(['"', '\'', '?']) else {break;};let tag = &body[start..start + end];@@ -638,21 +638,21 @@ pub fn resolve_update(.filter(|(_, commit)| Some(commit.as_str()) == record_commit).collect();match matches.as_slice() {- // 唯一命中且 tag 与最新 release 同名 → 同一发布(API 限流 commit 兜底- // 造成的 tag 差异,承接 #379 的修复场景)。- [(tag, _)] if tag.as_str() == latest.tag.as_str() => UpdateCheck::UpToDate,- // 唯一命中但 tag 与最新 release 不一致 → 同版本热修或滞后记录。- [(tag, _)] => match parse_version_from_tag(tag) {- Some(record_version) if record_behind_latest(&record_version) => {- UpdateCheck::HealUpToDate- }- // 反查到的版本与最新版本相同(或解析失败)→ 视为同版本热修- _ => UpdateCheck::UpdateAvailable,- },- // 多 tag 共指同一 commit → 模糊,按更新提示以免漏报。- _ if matches.len() > 1 => UpdateCheck::UpdateAvailable,- // 无法考证记录对应的版本 → 以实际安装文件为准,修正记录- _ => UpdateCheck::HealUpToDate,+ // 唯一命中且 tag 与最新 release 同名 → 同一发布(API 限流 commit 兜底+ // 造成的 tag 差异,承接 #379 的修复场景)。+ [(tag, _)] if tag.as_str() == latest.tag.as_str() => UpdateCheck::UpToDate,+ // 唯一命中但 tag 与最新 release 不一致 → 同版本热修或滞后记录。+ [(tag, _)] => match parse_version_from_tag(tag) {+ Some(record_version) if record_behind_latest(&record_version) => {+ UpdateCheck::HealUpToDate+ }+ // 反查到的版本与最新版本相同(或解析失败)→ 视为同版本热修+ _ => UpdateCheck::UpdateAvailable,+ },+ // 多 tag 共指同一 commit → 模糊,按更新提示以免漏报。+ _ if matches.len() > 1 => UpdateCheck::UpdateAvailable,+ // 无法考证记录对应的版本 → 以实际安装文件为准,修正记录+ _ => UpdateCheck::HealUpToDate,}}}@@ -824,9 +824,7 @@ mod tests {fn parses_digest_from_expanded_assets_html() {// 模拟 expanded_assets 片段:资产文件名之后紧跟作者填写的 sha256:<64hex>。// 来自真实 rc.8 页面:windows 资产摘要为 4d541676...- let html = concat!(- "…/deepseek-harness-pkg-windows.zip…<span>sha256:4d5416766eb4a66e81b83532abeea64de7e7e2e0bac69a4f0c0508e1d91936c0</span>",- );+ let html = "…/deepseek-harness-pkg-windows.zip…<span>sha256:4d5416766eb4a66e81b83532abeea64de7e7e2e0bac69a4f0c0508e1d91936c0</span>";let got = parse_digest_from_expanded_assets(html, "deepseek-harness-pkg-windows.zip");assert_eq!(got.as_deref(),@@ -1221,10 +1219,7 @@ mod tests {fn resolve_legacy_tag_older_build_is_still_hotfix_update() {// 反向回归:legacy_tags 反查到的是真正的同版本旧 build(不是 latest),// 必须仍然报告 UpdateAvailable(hotfix),不能让上面的修复误伤这一支。- let latest = latest(- "dsh-0.1.2-rc.1-33729514615",- "33729514615",- );+ let latest = latest("dsh-0.1.2-rc.1-33729514615", "33729514615");let tags = vec![("dsh-0.1.2-rc.1-33600000000".to_string(), // 旧 build,不是 latest"11122233344455556666777788899900aaaabbbb".to_string(),@@ -1242,13 +1237,16 @@ mod tests {fn resolve_legacy_tag_match_not_first_in_list_is_up_to_date() {// 顺序无关:legacy_tags 把匹配项放在末尾,前面的非匹配项不能让 `.find()`// 提前截走、必须仍然识别为同一发布。- let latest = latest(- "dsh-0.1.2-rc.1-33729514615",- "33729514615",- );+ let latest = latest("dsh-0.1.2-rc.1-33729514615", "33729514615");let tags = vec![- ("unrelated/v0.0.1".to_string(), "fff000fff000fff000fff000fff000fff000f0000".to_string()),- ("dsh-0.1.2-rc.1-33729514615".to_string(), "abc123def4567890abcdef1234567890abcdef12".to_string()),+ (+ "unrelated/v0.0.1".to_string(),+ "fff000fff000fff000fff000fff000fff000f0000".to_string(),+ ),+ (+ "dsh-0.1.2-rc.1-33729514615".to_string(),+ "abc123def4567890abcdef1234567890abcdef12".to_string(),+ ),];let decision = resolve_update(Some("abc123def4567890abcdef1234567890abcdef12"),@@ -1264,13 +1262,16 @@ mod tests {fn resolve_legacy_tag_multiple_matches_is_update_available() {// 防御:同一 commit 被多个 tag 指向(stable / latest 别名、不同命名规范的// 同源 tag),反查不唯一 → 模糊场景,按更新提示以免漏报。- let latest = latest(- "dsh-0.1.2-rc.1-33729514615",- "33729514615",- );+ let latest = latest("dsh-0.1.2-rc.1-33729514615", "33729514615");let tags = vec![- ("dsh-0.1.2-rc.1-stable".to_string(), "abc123def4567890abcdef1234567890abcdef12".to_string()),- ("dsh-0.1.2-rc.1-33729514615".to_string(), "abc123def4567890abcdef1234567890abcdef12".to_string()),+ (+ "dsh-0.1.2-rc.1-stable".to_string(),+ "abc123def4567890abcdef1234567890abcdef12".to_string(),+ ),+ (+ "dsh-0.1.2-rc.1-33729514615".to_string(),+ "abc123def4567890abcdef1234567890abcdef12".to_string(),+ ),];let decision = resolve_update(Some("abc123def4567890abcdef1234567890abcdef12"),diff --git a/src-tauri/src/service/fs_guard.rs b/src-tauri/src/service/fs_guard.rsindex f18bf80a..da93da7f 100644--- a/src-tauri/src/service/fs_guard.rs+++ b/src-tauri/src/service/fs_guard.rs@@ -147,7 +147,7 @@ mod tests {let dir = std::env::temp_dir().join(format!("dsh-fsguard2-{}", std::process::id()));let root = dir.join("profiles");fs::create_dir_all(&root).unwrap();- fs::create_dir_all(&root.join("web")).unwrap();+ fs::create_dir_all(root.join("web")).unwrap();let res = safe_remove_target(&root, "web");assert!(res.is_ok());let res = join_safe(&root, "app-1");diff --git a/src-tauri/src/service/migrate.rs b/src-tauri/src/service/migrate.rsindex bde5f59f..5dd2c354 100644--- a/src-tauri/src/service/migrate.rs+++ b/src-tauri/src/service/migrate.rs@@ -328,7 +328,7 @@ fn purge_if_stale_modules_metadata(node_modules: &Path, dsh_home: &Path) {let stale = doc.as_mapping().is_some_and(|mapping| {["virtualStoreDir", "storeDir"].iter().any(|key| {mapping- .get(&serde_yaml::Value::String((*key).into()))+ .get(serde_yaml::Value::String((*key).into())).and_then(serde_yaml::Value::as_str).is_some_and(|value| {let p = Path::new(value);diff --git a/src-tauri/src/service/patch/mod.rs b/src-tauri/src/service/patch/mod.rsindex 8faca1fd..2a5a6d71 100644--- a/src-tauri/src/service/patch/mod.rs+++ b/src-tauri/src/service/patch/mod.rs@@ -29,6 +29,7 @@ use std::path::Path;/// 单个补丁失败不阻断其余:与启动路径一样是「最佳努力」,但这里把错误汇总返回,/// 让编排层能看见哪一条出了问题。pub(crate) fn apply_all_at(core_dir: &Path) -> Result<(), String> {+ #[allow(clippy::type_complexity)]let patches: [(&str, fn(&Path) -> Result<(), String>); 8] = [("renderer", renderer::apply_at),("composer", composer::apply_at),diff --git a/src-tauri/src/service/plugin/disable.rs b/src-tauri/src/service/plugin/disable.rsindex 13c4cde3..07748642 100644--- a/src-tauri/src/service/plugin/disable.rs+++ b/src-tauri/src/service/plugin/disable.rs@@ -47,8 +47,7 @@ fn save_disabled(profile: &Path, map: &HashMap<String, DisabledEntry>) -> Result}let json =serde_json::to_string_pretty(map).map_err(|e| format!("DISABLED_RENDER_FAILED: {e}"))?;- fs::write(&path, format!("{json}\n"))- .map_err(|e| format!("DISABLED_WRITE_FAILED: {e}"))+ fs::write(&path, format!("{json}\n")).map_err(|e| format!("DISABLED_WRITE_FAILED: {e}"))}/// 读取 profile 的 `cordis.patch.yml`,返回「配置层显式禁用」条目的目标集合。@@ -95,7 +94,7 @@ pub(crate) fn load_patch_disabled(profile: &Path) -> HashSet<String> {////// 兼容 YAML 常见真值写法:布尔 `true`、非零数字、字符串 true/1/yes/on。fn patch_entry_disabled(map: &serde_yaml::Mapping) -> bool {- let Some(value) = map.get(&serde_yaml::Value::String("disabled".to_string())) else {+ let Some(value) = map.get(serde_yaml::Value::String("disabled".to_string())) else {return false;};match value {@@ -173,7 +172,7 @@ pub(crate) fn strip_patch_disable(profile: &Path, id: &str) -> Result<bool, Stricontinue;}changed = true;- map.remove(&serde_yaml::Value::String("disabled".to_string()));+ map.remove(serde_yaml::Value::String("disabled".to_string()));// 摘除 disabled 后仅剩 id(或为空)→ 纯禁用条目,整条丢弃;// 还有其它键 → 保留该条目的其余配置。let keeps_other_config = map.iter().any(|(k, _)| k.as_str() != Some("id"));@@ -281,10 +280,10 @@ pub(crate) fn disable_plugin_at(profile: &Path, id: &str) -> Result<(), String>}fs_guard::validate_id(id)?;let manifest_path = profile.join("package.json");- let content = fs::read_to_string(&manifest_path)- .map_err(|e| format!("DISABLE_READ_MANIFEST: {e}"))?;- let mut manifest: serde_json::Value = serde_json::from_str(&content)- .map_err(|e| format!("DISABLE_PARSE_MANIFEST: {e}"))?;+ let content =+ fs::read_to_string(&manifest_path).map_err(|e| format!("DISABLE_READ_MANIFEST: {e}"))?;+ let mut manifest: serde_json::Value =+ serde_json::from_str(&content).map_err(|e| format!("DISABLE_PARSE_MANIFEST: {e}"))?;if !is_in_dependencies(&manifest, id) {return Err(format!("DISABLE_NOT_INSTALLED: plugin {id} is not installed"@@ -346,10 +345,10 @@ pub(crate) fn enable_plugin_at() -> Result<(), String> {fs_guard::validate_id(id)?;let manifest_path = profile.join("package.json");- let content = fs::read_to_string(&manifest_path)- .map_err(|e| format!("ENABLE_READ_MANIFEST: {e}"))?;- let mut manifest: serde_json::Value = serde_json::from_str(&content)- .map_err(|e| format!("ENABLE_PARSE_MANIFEST: {e}"))?;+ let content =+ fs::read_to_string(&manifest_path).map_err(|e| format!("ENABLE_READ_MANIFEST: {e}"))?;+ let mut manifest: serde_json::Value =+ serde_json::from_str(&content).map_err(|e| format!("ENABLE_PARSE_MANIFEST: {e}"))?;if !is_in_dependencies(&manifest, id) {return Err(format!("ENABLE_NOT_INSTALLED: plugin {id} is not installed"@@ -460,7 +459,9 @@ mod tests {assert!(manifest["dependencies"]["dshmarket"].is_string());// bundles 中已移除let bundles = manifest["dsh"]["profile"]["bundles"].as_array().unwrap();- assert!(!bundles.iter().any(|b| b.as_str() == Some("dsh-better-sidebar")));+ assert!(!bundles+ .iter()+ .any(|b| b.as_str() == Some("dsh-better-sidebar")));assert!(bundles.iter().any(|b| b.as_str() == Some("dshmarket")));let _ = fs::remove_dir_all(&profile);@@ -472,7 +473,9 @@ mod tests {disable_plugin_at(&profile, "dsh-better-sidebar").unwrap();let map = load_disabled(&profile);- let entry = map.get("dsh-better-sidebar").expect("disabled entry exists");+ let entry = map+ .get("dsh-better-sidebar")+ .expect("disabled entry exists");assert_eq!(entry.reason, "user");assert!(!entry.disabled_at.is_empty());// 时间戳是纯数字字符串@@ -489,7 +492,9 @@ mod tests {let manifest = read_manifest(&profile);let bundles = manifest["dsh"]["profile"]["bundles"].as_array().unwrap();- assert!(bundles.iter().any(|b| b.as_str() == Some("dsh-better-sidebar")));+ assert!(bundles+ .iter()+ .any(|b| b.as_str() == Some("dsh-better-sidebar")));let _ = fs::remove_dir_all(&profile);}@@ -653,7 +658,9 @@ mod tests {// bundles 已加回let manifest = read_manifest(&profile);let bundles = manifest["dsh"]["profile"]["bundles"].as_array().unwrap();- assert!(bundles.iter().any(|b| b.as_str() == Some("dsh-better-sidebar")));+ assert!(bundles+ .iter()+ .any(|b| b.as_str() == Some("dsh-better-sidebar")));fs::remove_dir_all(&profile).ok();}diff --git a/src-tauri/src/service/plugin/install/allowlist.rs b/src-tauri/src/service/plugin/install/allowlist.rsindex c71a6724..55ee83c5 100644--- a/src-tauri/src/service/plugin/install/allowlist.rs+++ b/src-tauri/src/service/plugin/install/allowlist.rs@@ -280,7 +280,7 @@ fn apply_allow_build_keys(content: &str, keys: &[String]) -> Result<String, Strikeys.iter().map(|k| dep_path_to_name(k)).filter(|name| {- existing_only.map_or(true, |seq| !seq.contains(&Value::String(name.clone())))+ existing_only.is_none_or(|seq| !seq.contains(&Value::String(name.clone())))}).map(Value::String).collect()@@ -582,7 +582,7 @@ onlyBuiltDependencies: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 out = apply_allow_build_keys(base, std::slice::from_ref(&dep)).unwrap();let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();// pnpm 11:allowBuilds 保留完整 depPathassert_eq!(@@ -620,10 +620,10 @@ onlyBuiltDependencies:"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 out = apply_allow_build_keys("", std::slice::from_ref(&dep)).unwrap();let map = allow_builds_map(&out);assert_eq!(- map.get(&serde_yaml::Value::String(dep)),+ map.get(serde_yaml::Value::String(dep)),Some(&serde_yaml::Value::Bool(true)));// 库负责正确加引号,键原样(含 @ / : / #)可回读@@ -693,7 +693,8 @@ onlyBuiltDependencies:assert!(doc.get("packages").is_some());assert!(doc.get("nodeLinker").is_some());assert_eq!(- doc.get("autoInstallPeers").and_then(serde_yaml::Value::as_bool),+ doc.get("autoInstallPeers")+ .and_then(serde_yaml::Value::as_bool),Some(false));assert_eq!(diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rsindex 0a998db8..969b85c7 100644--- a/src-tauri/src/service/plugin/install/mod.rs+++ b/src-tauri/src/service/plugin/install/mod.rs@@ -6,14 +6,14 @@//! 1. git 托管插件的 `prepare` 构建(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`)——//! 其允许键随 pnpm 的克隆方式变化(git+ssh#sha / codeload tar.gz),无法预先确定;//! 2. 传递依赖的原生构建(如 `node-pty`,`ERR_PNPM_IGNORED_BUILDS`)。-//! 因此从 pnpm 错误输出解析它建议的允许键,写入 profile 的-//! `pnpm-workspace.yaml` 后重试,直至成功或无可解析项。+//! 因此从 pnpm 错误输出解析它建议的允许键,写入 profile 的+//! `pnpm-workspace.yaml` 后重试,直至成功或无可解析项。//!//! pnpm 10 与 11 对放行项的配置键与输出形式不同(均由各自报错提示决定,只能运行期//! 读取,见 [`allowlist::parse_allowlist_keys`] 与 [`allowlist::apply_allow_build_keys`])://! - pnpm 10(旧 store 复用用户版)只认 `onlyBuiltDependencies`(list 形式);//! - pnpm 11(捆绑版)认 `allowBuilds`(map 形式)。-//! 应用会把同一批包名同时写入这两个键,保证任一版本 pnpm 都能读到放行项。+//! 应用会把同一批包名同时写入这两个键,保证任一版本 pnpm 都能读到放行项。//!//! 关键陷阱:pnpm v11 在 `allowBuilds` 阻断时可能仍以 **exit 0** 退出(假成功),//! 所以重试逻辑不能只看退出码(见 [`run_plugin_with_allow_build_retry`]),安装成功@@ -397,6 +397,7 @@ async fn install_with_cancel(Ok(())}+#[allow(clippy::too_many_arguments)]async fn run_plugin_with_allow_build_retry(app_handle: &AppHandle,node: &Path,@@ -463,6 +464,7 @@ async fn run_plugin_with_allow_build_retry(////// 识别到瞬时失败后再跑一次完整命令(有界,见 [`TRANSIENT_FS_RETRIES`]),每次重试前/// 短暂休眠等 reparse point 落定 / 杀软扫完;该失败是概率性的,重试即大概率越过。+#[allow(clippy::too_many_arguments)]async fn run_plugin_install_with_transient_retry(app_handle: &AppHandle,node: &Path,@@ -545,7 +547,10 @@ mod tests {#[test]fn transient_fs_failure_detects_uv_unknown_exit_code() {assert!(is_transient_fs_install_failure(-4094, ""));- assert!(is_transient_fs_install_failure(-4094, "some unrelated output"));+ assert!(is_transient_fs_install_failure(+ -4094,+ "some unrelated output"+ ));}#[test]@@ -555,20 +560,38 @@ mod tests {let output = "[UNKNOWN] unknown error, open 'C:\\Users\\x\\.dsh\\profiles\\web\\node_modules\\dsh-tauri\\package.json'";assert!(is_transient_fs_install_failure(1, output));// `[unknown]` / `unknown error` 大小写不敏感- assert!(is_transient_fs_install_failure(1, &output.to_ascii_lowercase()));+ assert!(is_transient_fs_install_failure(+ 1,+ &output.to_ascii_lowercase()+ ));}#[test]fn transient_fs_retry_delay_uses_exponential_backoff() {- assert_eq!(transient_fs_retry_delay(1), std::time::Duration::from_secs(1));- assert_eq!(transient_fs_retry_delay(2), std::time::Duration::from_secs(2));- assert_eq!(transient_fs_retry_delay(8), std::time::Duration::from_secs(64));+ assert_eq!(+ transient_fs_retry_delay(1),+ std::time::Duration::from_secs(1)+ );+ assert_eq!(+ transient_fs_retry_delay(2),+ std::time::Duration::from_secs(2)+ );+ assert_eq!(+ transient_fs_retry_delay(8),+ std::time::Duration::from_secs(64)+ );}#[test]fn transient_fs_failure_rejects_ordinary_failures() {- assert!(!is_transient_fs_install_failure(1, "ERR_PNPM_SPEC_NOT_SUPPORTED"));- assert!(!is_transient_fs_install_failure(254, "ENOENT: no such file"));+ assert!(!is_transient_fs_install_failure(+ 1,+ "ERR_PNPM_SPEC_NOT_SUPPORTED"+ ));+ assert!(!is_transient_fs_install_failure(+ 254,+ "ENOENT: no such file"+ ));assert!(!is_transient_fs_install_failure(3,"ERR_PNPM_FETCH_404 registry error"diff --git a/src-tauri/src/service/plugin/install/pnpm.rs b/src-tauri/src/service/plugin/install/pnpm.rsindex b63b4151..356460a6 100644--- a/src-tauri/src/service/plugin/install/pnpm.rs+++ b/src-tauri/src/service/plugin/install/pnpm.rs@@ -798,10 +798,7 @@ pub(crate) fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> bool {}match store_major {Some(store) => bundled_major == Some(store) && user_major != Some(store),- None => match user_major {- Some(major) if major >= MIN_TRUSTED_PNPM_MAJOR => false,- _ => true,- },+ None => !matches!(user_major, Some(major) if major >= MIN_TRUSTED_PNPM_MAJOR),}}diff --git a/src-tauri/src/service/plugin/internal/mod.rs b/src-tauri/src/service/plugin/internal/mod.rsindex 097fd61d..059d10f8 100644--- a/src-tauri/src/service/plugin/internal/mod.rs+++ b/src-tauri/src/service/plugin/internal/mod.rs@@ -110,6 +110,7 @@ impl EnsureCoordinator {})}+ #[allow(clippy::type_complexity)]fn start(&mut self,) -> (@@ -219,16 +220,13 @@ pub(crate) fn repair_loader_state(app_handle: &AppHandle) -> Result<(), String>// 启动时与新 patch 再合并,必须恢复官方约定的空根配置。let root = profile.join("cordis.yml");const EMPTY_ROOT: &str = "# dsh profile root — an empty entry list. The tree is composed as patches:\n# each bundle in package.json's dsh.profile.bundles, then cordis.patch.yml, then any\n# --patch overlays. Edit cordis.patch.yml, not this file.\n[]\n";- if std::fs::read_to_string(&root).ok().as_deref() != Some(EMPTY_ROOT) {- if profile.is_dir() {- std::fs::write(&root, EMPTY_ROOT).map_err(|e| {- format!("INTERNAL_PLUGIN_ROOT_WRITE_FAILED: {}: {e}", root.display())- })?;- log::warn!(- "INTERNAL_PLUGIN_PROFILE_MIGRATED: reset stale profile root {}",- root.display()- );- }+ if std::fs::read_to_string(&root).ok().as_deref() != Some(EMPTY_ROOT) && profile.is_dir() {+ std::fs::write(&root, EMPTY_ROOT)+ .map_err(|e| format!("INTERNAL_PLUGIN_ROOT_WRITE_FAILED: {}: {e}", root.display()))?;+ log::warn!(+ "INTERNAL_PLUGIN_PROFILE_MIGRATED: reset stale profile root {}",+ root.display()+ );}if changed_manifest {log::warn!(diff --git a/src-tauri/src/service/plugin/patch_guard.rs b/src-tauri/src/service/plugin/patch_guard.rsindex c9fe2ef4..457c4d88 100644--- a/src-tauri/src/service/plugin/patch_guard.rs+++ b/src-tauri/src/service/plugin/patch_guard.rs@@ -250,9 +250,15 @@ mod tests {assert_eq!(record.original, home_patch.display().to_string());// 原文件被移走、备份保留原始内容(绝不删除)。assert!(!home_patch.exists());- assert_eq!(std::fs::read_to_string(&record.backup).unwrap(), BROKEN_UNQUOTED_JS);+ assert_eq!(+ std::fs::read_to_string(&record.backup).unwrap(),+ BROKEN_UNQUOTED_JS+ );// 合法的档案层原样保留,且不产生备份。- assert_eq!(std::fs::read_to_string(&profile_patch).unwrap(), VALID_LAYER);+ assert_eq!(+ std::fs::read_to_string(&profile_patch).unwrap(),+ VALID_LAYER+ );assert_eq!(std::fs::read_dir(&profile).unwrap().count(), 1);let _ = std::fs::remove_dir_all(&profile);let _ = std::fs::remove_dir_all(&home);@@ -264,7 +270,12 @@ mod tests {let home = tmp_dir("idempotent-home");std::fs::write(home.join(PATCH_FILENAME), BROKEN_UNQUOTED_JS).unwrap();- assert_eq!(quarantine_patch_layers_in(&profile, &home).quarantined.len(), 1);+ assert_eq!(+ quarantine_patch_layers_in(&profile, &home)+ .quarantined+ .len(),+ 1+ );// 第二次调用:文件已不在,不再产生任何动作(可反复点「安全模式」)。let second = quarantine_patch_layers_in(&profile, &home);assert!(second.quarantined.is_empty());@@ -281,17 +292,17 @@ mod tests {let first = dir.join(format!("{PATCH_FILENAME}.broken-20260914123456"));std::fs::write(&first, "keep me\n").unwrap();- let report = quarantine_layers(- &[patch.clone()],- "20260914123456",- );+ let report = quarantine_layers(std::slice::from_ref(&patch), "20260914123456");assert_eq!(report.quarantined.len(), 1);let record = &report.quarantined[0];assert!(record.backup.ends_with("-2"), "{}", record.backup);// 既有备份内容不被覆盖。assert_eq!(std::fs::read_to_string(&first).unwrap(), "keep me\n");- assert_eq!(std::fs::read_to_string(&record.backup).unwrap(), BROKEN_UNQUOTED_JS);+ assert_eq!(+ std::fs::read_to_string(&record.backup).unwrap(),+ BROKEN_UNQUOTED_JS+ );let _ = std::fs::remove_dir_all(&dir);}diff --git a/src-tauri/src/service/plugin/recovery/ownership.rs b/src-tauri/src/service/plugin/recovery/ownership.rsindex 4f0b3729..fda03cb6 100644--- a/src-tauri/src/service/plugin/recovery/ownership.rs+++ b/src-tauri/src/service/plugin/recovery/ownership.rs@@ -275,7 +275,7 @@ pub(super) fn resolve_recovery_plugins(.filter(|root| plugin_declares_loader_entry(&profile, root, entry)).collect();if owners.len() == 1 {- return owners.into_iter().map(|s| s.clone()).collect();+ return owners.into_iter().cloned().collect();}}@@ -286,7 +286,7 @@ pub(super) fn resolve_recovery_plugins(.filter(|root| plugin_matches_slot(&profile, root, slot)).collect();if matched.len() == 1 {- return matched.into_iter().map(|s| s.clone()).collect();+ return matched.into_iter().cloned().collect();}let providers: HashSet<String> = packages_providing_slot(&profile, slot).into_iter()@@ -297,7 +297,7 @@ pub(super) fn resolve_recovery_plugins(.filter(|root| plugin_references_packages(&profile, root, &providers)).collect();if owners.len() == 1 {- return owners.into_iter().map(|s| s.clone()).collect();+ return owners.into_iter().cloned().collect();}}}diff --git a/src-tauri/src/service/plugin/recovery/uninstall.rs b/src-tauri/src/service/plugin/recovery/uninstall.rsindex 812bb921..0a080d15 100644--- a/src-tauri/src/service/plugin/recovery/uninstall.rs+++ b/src-tauri/src/service/plugin/recovery/uninstall.rs@@ -112,10 +112,9 @@ pub(super) fn remove_plugin_dir(profile: &Path, id: &str) {.read_dir().map(|mut d| d.next().is_none()).unwrap_or(false)+ && fs_guard::ensure_within(&scope_entry, &node_modules_root).is_ok(){- if fs_guard::ensure_within(&scope_entry, &node_modules_root).is_ok() {- let _ = remove_plugin_entry(&scope_entry);- }+ let _ = remove_plugin_entry(&scope_entry);}}}@@ -244,8 +243,10 @@ mod tests {fn remove_plugin_dir_unlinks_junction_pointing_outside_profile() {// 内置插件以 link: 指向应用资源目录(在 profile 之外,如 dsh-tauri-panel):// junction 的 canonicalize 落在 profile 外,仍必须只解链入口、绝不动目标。- let root =- std::env::temp_dir().join(format!("dsh-plugin-recovery-junction-{}", std::process::id()));+ let root = std::env::temp_dir().join(format!(+ "dsh-plugin-recovery-junction-{}",+ std::process::id()+ ));let profile = root.join("profile");let target = root.join("app-resources/dsh-tauri-panel");let entry = profile.join("node_modules/dsh-tauri-panel");diff --git a/src-tauri/src/service/plugin/snapshot.rs b/src-tauri/src/service/plugin/snapshot.rsindex c55efce7..b4a349d1 100644--- a/src-tauri/src/service/plugin/snapshot.rs+++ b/src-tauri/src/service/plugin/snapshot.rs@@ -16,9 +16,9 @@//! 还原为三阶段 + 回滚://! 1. 预检:id 校验 + 快照存在 + 归档完整性 + 操作锁 + 停止服务;//! 2. 暂存:同盘解压到 `.staging-*` 并校验(package.json 可解析、无逃逸、-//! 拒绝符号链接——复用 `archive::extract_archive_gzip`);+//! 拒绝符号链接——复用 `archive::extract_archive_gzip`);//! 3. 切换:真实目录 → `.backup-*` rename,暂存包体 → 真实目录 rename,-//! 校验后清理备份;任一步失败则反转已做步骤(备份还原回原位)。+//! 校验后清理备份;任一步失败则反转已做步骤(备份还原回原位)。//!//! 还原范围:仅 `is_actionable_plugin_ref`(第三方插件);`@deepseek-ai/*`//! 核心/官方包拒绝还原(快照仍允许创建)。@@ -165,8 +165,7 @@ fn resolve_real_target(node_modules: &Path, id: &str) -> Result<PathBuf, String>entry.display()));}- let real = dunce::canonicalize(&entry)- .map_err(|e| format!("SNAPSHOT_RESOLVE_TARGET: {e}"))?;+ let real = dunce::canonicalize(&entry).map_err(|e| format!("SNAPSHOT_RESOLVE_TARGET: {e}"))?;if !real.is_dir() {return Err(format!("SNAPSHOT_NOT_DIR: {id} 的安装目标 {} 不是目录",@@ -212,8 +211,7 @@ fn append_package_tree(for entry in fs::read_dir(dir).map_err(|e| format!("SNAPSHOT_READDIR: {e}"))? {let entry = entry.map_err(|e| format!("SNAPSHOT_ENTRY: {e}"))?;let path = entry.path();- let meta =- fs::symlink_metadata(&path).map_err(|e| format!("SNAPSHOT_METADATA: {e}"))?;+ let meta = fs::symlink_metadata(&path).map_err(|e| format!("SNAPSHOT_METADATA: {e}"))?;// 跳过符号链接(含指向目录的链接):不归档链接本身,也不递归进入if meta.file_type().is_symlink() {continue;@@ -244,7 +242,10 @@ fn append_package_tree(}/// 创建快照归档:写入临时文件 → fsync → rename 到目标(同盘原子替换)。-fn write_archive_atomic(dest: &Path, write_fn: impl FnOnce(&Path) -> Result<(), String>) -> Result<(), String> {+fn write_archive_atomic(+ dest: &Path,+ write_fn: impl FnOnce(&Path) -> Result<(), String>,+) -> Result<(), String> {let tmp = dest.with_extension("tmp");let _ = fs::remove_file(&tmp);write_fn(&tmp)?;@@ -256,7 +257,8 @@ fn write_archive_atomic(dest: &Path, write_fn: impl FnOnce(&Path) -> Result<(),.write(true).open(&tmp).map_err(|e| format!("SNAPSHOT_OPEN_TMP: {e}"))?;- file.sync_all().map_err(|e| format!("SNAPSHOT_FSYNC: {e}"))?;+ file.sync_all()+ .map_err(|e| format!("SNAPSHOT_FSYNC: {e}"))?;fs::rename(&tmp, dest).map_err(|e| format!("SNAPSHOT_RENAME: {e}"))?;Ok(())}@@ -527,7 +529,10 @@ fn write_back_manifest_refs_at(manifest_path: &Path, id: &str, spec: &str) {.get_mut("dependencies").and_then(|d| d.as_object_mut()){- deps.insert(id.to_string(), serde_json::Value::String(version.to_string()));+ deps.insert(+ id.to_string(),+ serde_json::Value::String(version.to_string()),+ );modified = true;} else {value["dependencies"] = serde_json::json!({ id: version });@@ -706,14 +711,8 @@ mod tests {#[test]fn filename_sanitizes_scoped_and_rejects_traversal() {- assert_eq!(- snapshot_filename("dsh-market").unwrap(),- "dsh-market.tgz"- );- assert_eq!(- snapshot_filename("@scope/pkg").unwrap(),- "_scope_pkg.tgz"- );+ assert_eq!(snapshot_filename("dsh-market").unwrap(), "dsh-market.tgz");+ assert_eq!(snapshot_filename("@scope/pkg").unwrap(), "_scope_pkg.tgz");assert!(snapshot_filename("..").is_err());assert!(snapshot_filename("").is_err());assert!(snapshot_filename("../x").is_err());@@ -763,7 +762,9 @@ mod tests {header.set_size(bytes.len() as u64);header.set_mode(0o644);header.set_cksum();- builder.append_data(&mut header, MANIFEST_NAME, &bytes[..]).unwrap();+ builder+ .append_data(&mut header, MANIFEST_NAME, &bytes[..])+ .unwrap();append_package_tree(&mut builder, &real, Path::new(PACKAGE_PREFIX)).unwrap();builder.finish().unwrap();Ok(())@@ -805,7 +806,9 @@ mod tests {header.set_size(bytes.len() as u64);header.set_mode(0o644);header.set_cksum();- builder.append_data(&mut header, MANIFEST_NAME, &bytes[..]).unwrap();+ builder+ .append_data(&mut header, MANIFEST_NAME, &bytes[..])+ .unwrap();append_package_tree(&mut builder, &real, Path::new(PACKAGE_PREFIX)).unwrap();builder.finish().unwrap();Ok(())@@ -863,7 +866,10 @@ mod tests {let content = fs::read_to_string(&manifest_path).unwrap();let value: serde_json::Value = serde_json::from_str(&content).unwrap();assert_eq!(value["dependencies"].as_object().unwrap().len(), 1);- assert_eq!(value["dsh"]["profile"]["bundles"].as_array().unwrap().len(), 1);+ assert_eq!(+ value["dsh"]["profile"]["bundles"].as_array().unwrap().len(),+ 1+ );let _ = fs::remove_dir_all(&dir);}diff --git a/src-tauri/src/service/plugin/update.rs b/src-tauri/src/service/plugin/update.rsindex 787140bc..c6fc6bfa 100644--- a/src-tauri/src/service/plugin/update.rs+++ b/src-tauri/src/service/plugin/update.rs@@ -8,8 +8,8 @@//! - `link:` / `file:` 本地依赖 → 永不视为有更新;//! - git 类型(`github:` / `git+https://github.com/…` / `https://codeload.github.com/…`)//! → 用 pnpm-lock.yaml 里记录的 codeload 提交 SHA 对比 GitHub 跟踪目标:-//! git spec 显式声明 `#ref` 时跟踪该 tag / branch / SHA,未声明时跟踪 HEAD;-//! 镜像安装写入的 codeload archive URL 记录的是当前安装提交,更新源仍是 HEAD;+//! git spec 显式声明 `#ref` 时跟踪该 tag / branch / SHA,未声明时跟踪 HEAD;+//! 镜像安装写入的 codeload archive URL 记录的是当前安装提交,更新源仍是 HEAD;//! - 其余(registry)→ 用 npm registry 的 `latest` dist-tag 与已装版本做语义化比较,//! `latest > installed` 才视为有更新(避免把 `latest` 指向更旧版本误判为可升级)。//!@@ -672,17 +672,23 @@ mod tests {#[test]fn effective_spec_passes_through_when_it_cannot_resolve() {// 非 catalog spec、条目缺失、文件缺失/损坏 → 一律原样返回,绝不猜测- let dir = workspace_probe("passthrough", "packages:\n - .\ncatalog:\n other: ^1.0.0\n");+ let dir = workspace_probe(+ "passthrough",+ "packages:\n - .\ncatalog:\n other: ^1.0.0\n",+ );assert_eq!(effective_spec(&dir, "dsh-probe", "^2.0.0"), "^2.0.0");- assert_eq!(effective_spec(&dir, "dsh-probe", "github:a/b"), "github:a/b");+ assert_eq!(+ effective_spec(&dir, "dsh-probe", "github:a/b"),+ "github:a/b"+ );assert_eq!(effective_spec(&dir, "dsh-probe", "catalog:"), "catalog:");assert_eq!(effective_spec(&dir, "dsh-probe", "catalog:missing"),"catalog:missing");- let absent = std::env::temp_dir()- .join(format!("dsh-update-cat-{}-absent", std::process::id()));+ let absent =+ std::env::temp_dir().join(format!("dsh-update-cat-{}-absent", std::process::id()));let _ = std::fs::remove_dir_all(&absent);assert_eq!(effective_spec(&absent, "dsh-probe", "catalog:"), "catalog:");diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rsindex a95b0c09..d08e16a2 100644--- a/src-tauri/src/service/plugin/watch.rs+++ b/src-tauri/src/service/plugin/watch.rs@@ -174,7 +174,7 @@ fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPludep_ids.into_iter()- .filter_map(|id| {+ .map(|id| {let preset = preset_map.get(id.as_str());let meta = read_plugin_meta(&plugin_dir(profile, id));let repo_url = meta@@ -193,7 +193,7 @@ fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPlu.or_else(|| preset.map(|p| p.name.clone())).unwrap_or_else(|| id.clone());let patch_disabled_by_name = patch_disabled_set.contains(name.as_str());- Some(DshPlugin {+ DshPlugin {id: id.clone(),name,version: meta@@ -208,8 +208,7 @@ fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPlurepo_url,bundled: bundled.contains(id.as_str()),disabled: disabled_map.contains_key(id),- patch_disabled: patch_disabled_set.contains(id.as_str())- || patch_disabled_by_name,+ patch_disabled: patch_disabled_set.contains(id.as_str()) || patch_disabled_by_name,recommended: preset.map(|p| p.recommended).unwrap_or(false),fix: preset.map(|p| p.fix).unwrap_or(false),internal: internal_names.contains(id.as_str()),@@ -217,7 +216,7 @@ fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPlulatest_version: None,has_snapshot: false,error: None,- })+ }}).collect()}@@ -338,7 +337,7 @@ pub fn check_and_emit(app_handle: &AppHandle) {state.pending_fp = fp;let can_emit = state.last_emit- .map_or(true, |last| last.elapsed() >= DEBOUNCE);+ .is_none_or(|last| last.elapsed() >= DEBOUNCE);if !can_emit {return;}@@ -367,7 +366,7 @@ mod tests {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();+ std::fs::create_dir_all(dir.join("node_modules")).unwrap();let mut manifest = serde_json::json!({"name": "dsh-profile-web","private": true,@@ -603,12 +602,9 @@ mod tests {/// - 不在 bundles 且不在禁用清单 → bundled=false, disabled=false(未加载,启用会失败)#[test]fn parse_plugins_distinguishes_disabled_from_unloaded() {- let dir = std::env::temp_dir().join(format!(- "dsh-watch-disabled-{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("dsh-watch-disabled-{}", std::process::id()));let _ = std::fs::remove_dir_all(&dir);- std::fs::create_dir_all(&dir.join("node_modules")).unwrap();+ std::fs::create_dir_all(dir.join("node_modules")).unwrap();let manifest = serde_json::json!({"name": "dsh-profile-web","private": true,@@ -627,7 +623,11 @@ mod tests {for id in ["dsh-loaded", "dsh-disabled", "dsh-unloaded"] {let pkg_dir = dir.join("node_modules").join(id);std::fs::create_dir_all(&pkg_dir).unwrap();- std::fs::write(pkg_dir.join("package.json"), format!(r#"{{"name":"{id}"}}"#)).unwrap();+ std::fs::write(+ pkg_dir.join("package.json"),+ format!(r#"{{"name":"{id}"}}"#),+ )+ .unwrap();}// 仅 dsh-disabled 写入禁用清单。let disabled = serde_json::json!({@@ -665,7 +665,10 @@ mod tests {"dshmarket",r#"{"name":"dshmarket","version":"1.13.1","dsh":{"bundle":{}}}"#,),- ("dsh-tauri-pet", r#"{"name":"dsh-tauri-pet","version":"0.1.0"}"#),+ (+ "dsh-tauri-pet",+ r#"{"name":"dsh-tauri-pet","version":"0.1.0"}"#,+ ),("dsh-other", r#"{"name":"dsh-other","version":"0.1.0"}"#),],);diff --git a/src-tauri/src/service/profile/mod.rs b/src-tauri/src/service/profile/mod.rsindex ab504e0c..6e2077aa 100644--- a/src-tauri/src/service/profile/mod.rs+++ b/src-tauri/src/service/profile/mod.rs@@ -579,11 +579,17 @@ pub fn reset_with_root(profiles_root: &Path, id: &str) -> Result<(), String> {/// - `name` 为 `None` 时按 source_id 自动递增;`Some` 时规范化并校验冲突;/// - 复制后清除搬入的 pnpm 元数据(`.modules.yaml`),并重写 manifest name 为/// `dsh-profile-<new-id>`。-pub fn clone_with_root(profiles_root: &Path, source_id: &str, name: Option<&str>) -> Result<Profile, String> {+pub fn clone_with_root(+ profiles_root: &Path,+ source_id: &str,+ name: Option<&str>,+) -> Result<Profile, String> {fs_guard::validate_id(source_id)?;let src_dir = fs_guard::join_safe(profiles_root, source_id)?;if !src_dir.is_dir() {- return Err(format!("PROFILE_NOT_FOUND: profile {source_id} does not exist"));+ return Err(format!(+ "PROFILE_NOT_FOUND: profile {source_id} does not exist"+ ));}let new_id = match name {@@ -594,7 +600,9 @@ pub fn clone_with_root(profiles_root: &Path, source_id: &str, name: Option<&str>}let id = normalize_profile_id(trimmed);if id.is_empty() {- return Err("PROFILE_INVALID_NAME: profile name has no usable characters".to_string());+ return Err(+ "PROFILE_INVALID_NAME: profile name has no usable characters".to_string(),+ );}if id.len() > 64 {return Err("PROFILE_NAME_TOO_LONG: profile id exceeds 64 characters".to_string());@@ -649,37 +657,38 @@ fn copy_dir_tree(src: &Path, dst: &Path) -> Result<(), String> {let entries: Vec<_> = read_dir.collect::<Result<Vec<_>, _>>().map_err(|e| format!("COPY_ENTRY: {e}"))?;- entries.par_iter().try_for_each(|entry| -> Result<(), String> {- let name = entry.file_name();- // 仅跳过运行时产物(不随克隆迁移)- if let Some(s) = name.to_str() {- if s == ".harness.pid" || s == ".backups" {- return Ok(());+ entries+ .par_iter()+ .try_for_each(|entry| -> Result<(), String> {+ let name = entry.file_name();+ // 仅跳过运行时产物(不随克隆迁移)+ if let Some(s) = name.to_str() {+ if s == ".harness.pid" || s == ".backups" {+ return Ok(());+ }}- }- let src_path = entry.path();- let dst_path = dst.join(&name);- let ty = entry.file_type().map_err(|e| format!("COPY_TYPE: {e}"))?;- if ty.is_symlink() {- // 保留符号链接原样(如 node_modules/.bin 下的可执行链接)- let target = std::fs::read_link(&src_path)- .map_err(|e| format!("COPY_LINK_READ: {e}"))?;- copy_symlink(&target, &dst_path)?;- } else if ty.is_dir() {- copy_dir_tree(&src_path, &dst_path)?;- } else if ty.is_file() {- fs::copy(&src_path, &dst_path).map_err(|e| format!("COPY_FILE: {e}"))?;- }- Ok(())- })?;+ let src_path = entry.path();+ let dst_path = dst.join(&name);+ let ty = entry.file_type().map_err(|e| format!("COPY_TYPE: {e}"))?;+ if ty.is_symlink() {+ // 保留符号链接原样(如 node_modules/.bin 下的可执行链接)+ let target =+ std::fs::read_link(&src_path).map_err(|e| format!("COPY_LINK_READ: {e}"))?;+ copy_symlink(&target, &dst_path)?;+ } else if ty.is_dir() {+ copy_dir_tree(&src_path, &dst_path)?;+ } else if ty.is_file() {+ fs::copy(&src_path, &dst_path).map_err(|e| format!("COPY_FILE: {e}"))?;+ }+ Ok(())+ })?;Ok(())}/// 在目标位置重建一条符号链接(指向原链接相同的目标)。#[cfg(unix)]fn copy_symlink(target: &std::path::Path, dst: &Path) -> Result<(), String> {- std::os::unix::fs::symlink(target, dst)- .map_err(|e| format!("COPY_LINK_CREATE: {e}"))+ std::os::unix::fs::symlink(target, dst).map_err(|e| format!("COPY_LINK_CREATE: {e}"))}/// 在目标位置重建一条符号链接(Windows 下需要权限,best-effort)。@@ -717,8 +726,8 @@ fn rewrite_manifest_name(dir: &Path, new_id: &str) -> Result<(), String> {/// 同目录临时文件 + rename 原子替换写入档案清单(调用方决定错误码前缀)。fn rewrite_manifest_name_atomic(path: &Path, manifest: &serde_json::Value) -> Result<(), String> {- let content = serde_json::to_string_pretty(manifest)- .map_err(|e| format!("MANIFEST_RENDER: {e}"))?;+ let content =+ serde_json::to_string_pretty(manifest).map_err(|e| format!("MANIFEST_RENDER: {e}"))?;atomic_write(path, &format!("{content}\n"), "MANIFEST_WRITE")}@@ -939,10 +948,10 @@ fn init_profile_dir(dir: &Path, id: &str) -> Result<(), String> {#[cfg(test)]mod clone_tests {use super::*;- use std::path::PathBuf;+ use std::path::{Path, PathBuf};/// 在 profiles 根目录下构造一个最小源档案目录,返回其路径。- fn scaffold_source(root: &PathBuf, id: &str) -> PathBuf {+ fn scaffold_source(root: &Path, id: &str) -> PathBuf {let dir = root.join(id);std::fs::create_dir_all(&dir).unwrap();std::fs::write(@@ -984,7 +993,11 @@ mod clone_tests {let root = tmp.join("profiles");scaffold_source(&root, "web");std::fs::create_dir_all(root.join("web-1")).unwrap();- std::fs::write(root.join("web-1/package.json"), r#"{"name":"dsh-profile-web-1"}"#).unwrap();+ std::fs::write(+ root.join("web-1/package.json"),+ r#"{"name":"dsh-profile-web-1"}"#,+ )+ .unwrap();let profile = clone_with_root(&root, "web", None).unwrap();assert_eq!(profile.id, "web-2");@@ -1002,7 +1015,8 @@ mod clone_tests {let profile = clone_with_root(&root, "web", None).unwrap();let dst = root.join(&profile.id);let manifest: serde_json::Value =- serde_json::from_str(&std::fs::read_to_string(dst.join("package.json")).unwrap()).unwrap();+ serde_json::from_str(&std::fs::read_to_string(dst.join("package.json")).unwrap())+ .unwrap();assert_eq!(manifest["name"], format!("dsh-profile-{}", profile.id));let _ = std::fs::remove_dir_all(&tmp);@@ -1031,7 +1045,10 @@ mod clone_tests {let root = tmp.join("profiles");let err = clone_with_root(&root, "nonexistent", None).unwrap_err();- assert!(err.contains("PROFILE_NOT_FOUND"), "expected PROFILE_NOT_FOUND, got: {err}");+ assert!(+ err.contains("PROFILE_NOT_FOUND"),+ "expected PROFILE_NOT_FOUND, got: {err}"+ );let _ = std::fs::remove_dir_all(&tmp);}@@ -1044,12 +1061,19 @@ mod clone_tests {scaffold_source(&root, "web");let nm = root.join("web/node_modules");std::fs::create_dir_all(&nm).unwrap();- std::fs::write(nm.join(".modules.yaml"), "lockfileVersion: '9.0'\nstoreDir: /old/store\n").unwrap();+ std::fs::write(+ nm.join(".modules.yaml"),+ "lockfileVersion: '9.0'\nstoreDir: /old/store\n",+ )+ .unwrap();let profile = clone_with_root(&root, "web", None).unwrap();let dst_nm = root.join(&profile.id).join("node_modules");assert!(dst_nm.is_dir(), "node_modules should be copied");- assert!(!dst_nm.join(".modules.yaml").exists(), "carried .modules.yaml must be purged");+ assert!(+ !dst_nm.join(".modules.yaml").exists(),+ "carried .modules.yaml must be purged"+ );let _ = std::fs::remove_dir_all(&tmp);}@@ -1089,7 +1113,10 @@ mod tests {let mapping = value.as_mapping().unwrap();assert_eq!(mapping.len(), 3, "{mapping:?}");assert_eq!(- value.get("packages").and_then(Value::as_sequence).map(Vec::len),+ value+ .get("packages")+ .and_then(Value::as_sequence)+ .map(Vec::len),Some(1));assert_eq!(@@ -1104,7 +1131,10 @@ mod tests {let (value, normalized) =parse_workspace_document("nodeLinker: hoisted\n---\nnodeLinker: isolated\n").unwrap();assert!(normalized);- assert_eq!(value.get("nodeLinker").and_then(Value::as_str), Some("isolated"));+ assert_eq!(+ value.get("nodeLinker").and_then(Value::as_str),+ Some("isolated")+ );}/// 非映射文档(序列/标量)无法安全合并,保留原始解析错误。@@ -1341,10 +1371,7 @@ mod tests {let root = tmp.join("profiles");// 旧目录不存在(全新安装 / 已迁移完成)→ 无需改名即视为就绪- assert_eq!(- adopt_tauri_profile_dir(&root),- ProfileDirAdoption::Adopted- );+ assert_eq!(adopt_tauri_profile_dir(&root), ProfileDirAdoption::Adopted);let legacy = root.join(LEGACY_DESKTOP_PROFILE);std::fs::create_dir_all(&legacy).unwrap();@@ -1353,15 +1380,9 @@ mod tests {r#"{"name":"dsh-profile-desktop","private":true}"#,).unwrap();- assert_eq!(- adopt_tauri_profile_dir(&root),- ProfileDirAdoption::Adopted- );+ assert_eq!(adopt_tauri_profile_dir(&root), ProfileDirAdoption::Adopted);// 再跑一次:旧目录已不存在,仍为 Adopted(幂等,不阻断 active_profile 改写)- assert_eq!(- adopt_tauri_profile_dir(&root),- ProfileDirAdoption::Adopted- );+ assert_eq!(adopt_tauri_profile_dir(&root), ProfileDirAdoption::Adopted);let _ = std::fs::remove_dir_all(&tmp);}@@ -1390,7 +1411,10 @@ mod tests {adoption == ProfileDirAdoption::Failed || adoption == ProfileDirAdoption::Blocked,"rename failure must be reported, got {adoption:?}");- assert!(legacy.join("package.json").is_file(), "legacy profile must stay");+ assert!(+ legacy.join("package.json").is_file(),+ "legacy profile must stay"+ );assert_eq!(std::fs::read_to_string(legacy.join("package.json")).unwrap(),r#"{"name":"dsh-profile-desktop","private":true}"#,@@ -1399,10 +1423,7 @@ mod tests {// 放开占位文件后下次启动改名成功(重试路径)std::fs::remove_file(root.join(DESKTOP_PROFILE)).unwrap();- assert_eq!(- adopt_tauri_profile_dir(&root),- ProfileDirAdoption::Adopted- );+ assert_eq!(adopt_tauri_profile_dir(&root), ProfileDirAdoption::Adopted);assert!(!legacy.exists(), "retry must finish the rename");let _ = std::fs::remove_dir_all(&tmp);@@ -1639,7 +1660,10 @@ mod tests {manifest["dsh"]["profile"]["bundles"],serde_json::json!(["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app"]));- assert!(!profiles_root.join("web").join("disabled-plugins.json").exists());+ assert!(!profiles_root+ .join("web")+ .join("disabled-plugins.json")+ .exists());// 会话数据完整保留assert!(sessions.join("_no-cwd").join("s1.json").is_file());@@ -1668,7 +1692,7 @@ mod tests {let root = tmp.join("profiles");std::fs::create_dir_all(&root).unwrap();let res = std::panic::catch_unwind(|| {- std::fs::create_dir_all(&root.join("web")).unwrap();+ std::fs::create_dir_all(root.join("web")).unwrap();let ok = crate::service::fs_guard::safe_remove_target(&root, "web");assert!(ok.is_ok(), "存在的合法目录应通过守卫: {ok:?}");let bad = crate::service::fs_guard::safe_remove_target(&root, "..");diff --git a/src-tauri/src/service/update/install.rs b/src-tauri/src/service/update/install.rsindex 30d7fe5d..990fc795 100644--- a/src-tauri/src/service/update/install.rs+++ b/src-tauri/src/service/update/install.rs@@ -517,7 +517,7 @@ mod tests {let file = dir.join("installer.part");let content = b"deepseek-harness-desktop installer payload";std::fs::write(&file, content).unwrap();- let real = format!("sha256:{}", format!("{:x}", sha2::Sha256::digest(content)));+ let real = format!("sha256:{:x}", sha2::Sha256::digest(content));// 正确摘要通过assert!(verify_installer_sha256(&file, &real).is_ok());// 裸 64hex(无 sha256: 前缀)也接受@@ -539,7 +539,9 @@ mod tests {assert!(ensure_within_updates_dir(&root.join("app-setup.exe"), &root).is_ok());// 目录外的兄弟路径(前缀相同也不能放过:`updates-evil` 不是 `updates` 的子路径)assert!(ensure_within_updates_dir(&root.join("..").join("evil.exe"), &root).is_err());- let sibling = std::path::Path::new("root").join("updates-evil").join("x.exe");+ let sibling = std::path::Path::new("root")+ .join("updates-evil")+ .join("x.exe");assert!(ensure_within_updates_dir(&sibling, &root).is_err());}}diff --git a/src-tauri/src/service/workflow/process.rs b/src-tauri/src/service/workflow/process.rsindex f83313ec..0f1cbe7e 100644--- a/src-tauri/src/service/workflow/process.rs+++ b/src-tauri/src/service/workflow/process.rs@@ -330,12 +330,12 @@ fn command_line_has_argument(cmdline: &str, argument: &str) -> bool {let before_is_boundary = cmdline[..start].chars().next_back()- .map_or(true, char::is_whitespace);+ .is_none_or(char::is_whitespace);let end = start + matched.len();let after_is_boundary = cmdline[end..].chars().next()- .map_or(true, char::is_whitespace);+ .is_none_or(char::is_whitespace);before_is_boundary && after_is_boundary})}@@ -351,7 +351,7 @@ fn command_line_has_argument_after(cmdline: &str, preceding: &str, argument: &stlet end = start + matched.len();let rest = cmdline[end..].trim_start_matches(char::is_whitespace);rest.strip_prefix(argument)- .is_some_and(|tail| tail.chars().next().map_or(true, char::is_whitespace))+ .is_some_and(|tail| tail.chars().next().is_none_or(char::is_whitespace))})}diff --git a/src-tauri/src/service/workflow/sweep.rs b/src-tauri/src/service/workflow/sweep.rsindex 4f360aeb..4465aa8d 100644--- a/src-tauri/src/service/workflow/sweep.rs+++ b/src-tauri/src/service/workflow/sweep.rs@@ -72,7 +72,7 @@ pub fn sweep_orphan_harness(app_handle: &tauri::AppHandle) {/// 占用指定端口的进程 PID(LISTENING 状态)。/// - Windows:`netstat -ano` 解析;/// - Unix:`lsof -ti tcp:<port>`,不可用时返回 None。-/// 返回 None 视为"无法确认",调用方不会因此杀任何进程。+/// 返回 None 视为"无法确认",调用方不会因此杀任何进程。fn port_owner_pid(port: u16) -> Option<u32> {#[cfg(windows)]{diff --git a/src-tauri/src/service/workflow/utils.rs b/src-tauri/src/service/workflow/utils.rsindex 449b0437..7d84c310 100644--- a/src-tauri/src/service/workflow/utils.rs+++ b/src-tauri/src/service/workflow/utils.rs@@ -1,6 +1,6 @@use std::io::{BufRead, BufReader, Read, Write};use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::sync::{Mutex, OnceLock};use std::thread;use std::time::Duration;@@ -278,9 +278,9 @@ fn append_log(log_path: &PathBuf, line: &str) {}/// 轮转日志文件名:`dsh-web.log`(index 0)、`dsh-web.log.1`、`dsh-web.log.2`……-fn indexed_log_path(log_path: &PathBuf, index: usize) -> PathBuf {+fn indexed_log_path(log_path: &Path, index: usize) -> PathBuf {if index == 0 {- return log_path.clone();+ return log_path.to_path_buf();}let mut name = log_path.file_name().unwrap_or_default().to_os_string();name.push(format!(".{}", index));@@ -298,7 +298,7 @@ pub fn rotate_service_log(log_path: &PathBuf, keep: usize) {return;}// 1) 删除超过保留上限的最老文件(它会被顶上来的文件覆盖且无处安放)- let _ = std::fs::remove_file(&indexed_log_path(log_path, keep - 1));+ let _ = std::fs::remove_file(indexed_log_path(log_path, keep - 1));// 2) 从次老到次新依次后移,为本次启动腾出位置for i in (1..keep).rev() {let from = indexed_log_path(log_path, i);@@ -418,10 +418,10 @@ mod tests {// 最后一次循环后:当前为空、.1 = start 4、.2 = start 3assert_eq!(fs::read_to_string(&log).unwrap_or_default(), "");- assert!(fs::read_to_string(&dir.join("dsh-web.log.1"))+ assert!(fs::read_to_string(dir.join("dsh-web.log.1")).unwrap().contains("start 4"));- assert!(fs::read_to_string(&dir.join("dsh-web.log.2"))+ assert!(fs::read_to_string(dir.join("dsh-web.log.2")).unwrap().contains("start 3"));assert!(!dir.join("dsh-web.log.3").exists());@@ -470,12 +470,15 @@ mod tests {let html = r#"<script src="plugins/??@deepseek-ai/dsh-client-modules/client.js&rev=f584d378985b"></script><script>globalThis["__DSH_BOOT__"] = {"rev":"g","entries":[{"id":"@deepseek-ai/dsh-client-ui-layout","url":"plugins/??@deepseek-ai/dsh-client-ui-layout/client.js&rev=f26b875a92b6","rev":"f26b875a92b6"}]}</script>"#;let urls = client_urls_from_boot_html(3081, html).expect("boot graph");assert_eq!(urls.len(), 2);- assert!(urls.iter().all(|url| url- .starts_with("http://127.0.0.1:3081/plugins/")));- assert!(urls.iter().any(|url| url- .contains("dsh-client-modules/client.js&rev=f584d378985b")));- assert!(urls.iter().any(|url| url- .contains("dsh-client-ui-layout/client.js&rev=f26b875a92b6")));+ assert!(urls+ .iter()+ .all(|url| url.starts_with("http://127.0.0.1:3081/plugins/")));+ assert!(urls+ .iter()+ .any(|url| url.contains("dsh-client-modules/client.js&rev=f584d378985b")));+ assert!(urls+ .iter()+ .any(|url| url.contains("dsh-client-ui-layout/client.js&rev=f26b875a92b6")));}#[test]