DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(07): 档案手动备份/还原 + 自动备份 (#247)
CoderStory5ffe16836993
diff --git a/src-tauri/src/bridge/backup.rs b/src-tauri/src/bridge/backup.rsnew file mode 100644index 00000000..4fe4c195--- /dev/null+++ b/src-tauri/src/bridge/backup.rs@@ -0,0 +1,49 @@+//! 备份 / 还原 Tauri 命令。+//!+//! 薄封装:把 IPC 参数转成 `service::backup` 的调用,遵循 `bridge/profile.rs`+//! → `service::profile` 的分层模式。++use tauri::AppHandle;++use crate::service::backup;++/// 创建备份(`$DSH_HOME` → `$DSH_HOME/.backups/<timestamp>.tar.gz`)。+#[tauri::command]+pub fn backup_profile(+ app_handle: AppHandle,+ include_credentials: bool,+) -> Result<backup::BackupInfo, String> {+ backup::create_backup(+ &app_handle,+ backup::BackupOptions { include_credentials },+ )+}++/// 从指定备份还原。+///+/// `as_new` = true 时创建新档案目录;false 时覆盖当前 `$DSH_HOME`。+#[tauri::command]+pub fn restore_profile(+ app_handle: AppHandle,+ timestamp: String,+ as_new: bool,+) -> Result<(), String> {+ let mode = if as_new {+ backup::RestoreMode::AsNew+ } else {+ backup::RestoreMode::Overwrite+ };+ backup::restore_backup(&app_handle, ×tamp, mode)+}++/// 列出所有备份。+#[tauri::command]+pub fn list_backups(app_handle: AppHandle) -> Vec<backup::BackupInfo> {+ backup::list_backups(&app_handle)+}++/// 删除指定备份。+#[tauri::command]+pub fn delete_backup(app_handle: AppHandle, timestamp: String) -> Result<(), String> {+ backup::delete_backup(&app_handle, ×tamp)+}diff --git a/src-tauri/src/bridge/config.rs b/src-tauri/src/bridge/config.rsindex 1e5471d0..ed3f0fc9 100644--- a/src-tauri/src/bridge/config.rs+++ b/src-tauri/src/bridge/config.rs@@ -103,6 +103,8 @@ pub async fn update_app_config(setting.close_action = action;}});+ // 配置变化后,若开启了「配置变化时备份」,标记待执行(由 scheduler tick 去抖后执行)+ crate::service::backup::schedule::mark_config_changed(&app_handle);Ok(setting)}diff --git a/src-tauri/src/bridge/mod.rs b/src-tauri/src/bridge/mod.rsindex c69c207a..16dd98ce 100644--- a/src-tauri/src/bridge/mod.rs+++ b/src-tauri/src/bridge/mod.rs@@ -4,6 +4,7 @@//! 系统集成 / 更新),此处统一声明并重导出为「干净 API」,供 `generate_handler!`//! 以 `crate::bridge::<cmd>` 形式注册。+pub mod backup;pub mod clipboard;pub mod config;pub mod core;@@ -14,6 +15,7 @@ pub mod profile;pub mod system_os;pub mod updater;+pub use backup::*;pub use clipboard::*;pub use config::*;pub use core::*;diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rsindex e9ba9d25..2f4c4f80 100644--- a/src-tauri/src/config/setting.rs+++ b/src-tauri/src/config/setting.rs@@ -56,6 +56,24 @@ pub struct Setting {/// 默认,严格 enum 的一个意外值会连带清空端口/语言/档案等全部设置。#[serde(default = "default_close_action")]pub close_action: String,+ /// 是否启用自动备份。+ #[serde(default)]+ pub auto_backup_enabled: bool,+ /// 自动备份间隔(天)。+ #[serde(default = "default_auto_backup_interval_days")]+ pub auto_backup_interval_days: u32,+ /// 是否在每次启动时自动备份。+ #[serde(default)]+ pub auto_backup_on_startup: bool,+ /// 是否在配置变化时自动备份。+ #[serde(default)]+ pub auto_backup_on_change: bool,+ /// 最多保留备份份数。+ #[serde(default = "default_backup_retention_count")]+ pub backup_retention_count: u32,+ /// 备份是否包含凭据文件(`.credentials.yaml`)。+ #[serde(default)]+ pub backup_include_credentials: bool,}pub const ZOOM_FACTOR_MIN: f64 = 0.5;@@ -82,6 +100,16 @@ pub fn default_close_action() -> String {"tray".to_string()}+/// 自动备份默认间隔:7 天。+pub fn default_auto_backup_interval_days() -> u32 {+ 7+}++/// 默认保留备份份数:10 份。+pub fn default_backup_retention_count() -> u32 {+ 10+}+/// 把外部或旧存储中的关闭行为收敛到白名单,未知值一律回落到默认行为。////// 只做精确匹配:不做 `trim()`、不做大小写折叠——store 可被手工编辑、旧版本或其它@@ -103,6 +131,34 @@ pub fn normalize_zoom_factor(value: f64) -> f64 {(clamped * steps_per_unit).round() / steps_per_unit}+/// 归一化自动备份设置:把间隔和保留份数限制在有效范围内。+///+/// - `interval_days` 限制在 [1, 90],未知/越界回落默认 7。+/// - `retention_count` 限制在 [1, 50],未知/越界回落默认 10。+pub fn normalize_backup_settings(interval_days: u32, retention_count: u32) -> (u32, u32) {+ let interval = if interval_days == 0 || interval_days > 90 {+ default_auto_backup_interval_days()+ } else {+ interval_days+ };+ let retention = if retention_count == 0 || retention_count > 50 {+ default_backup_retention_count()+ } else {+ retention_count+ };+ (interval, retention)+}++/// 把 Setting 的备份字段归一化到有效范围。+fn normalize_backup_fields(setting: &mut Setting) {+ let (interval, retention) = normalize_backup_settings(+ setting.auto_backup_interval_days,+ setting.backup_retention_count,+ );+ setting.auto_backup_interval_days = interval;+ setting.backup_retention_count = retention;+}+/// 默认服务端口:debug 构建与生产隔离,避免开发时与已运行的桌面端争用 3080。pub fn default_port() -> u16 {if cfg!(debug_assertions) {@@ -130,6 +186,12 @@ impl Default for Setting {manual_port: None,zoom_factor: default_zoom_factor(),close_action: default_close_action(),+ auto_backup_enabled: false,+ auto_backup_interval_days: default_auto_backup_interval_days(),+ auto_backup_on_startup: false,+ auto_backup_on_change: false,+ backup_retention_count: default_backup_retention_count(),+ backup_include_credentials: false,}}}@@ -168,6 +230,7 @@ fn read_store_dat_setting<R: Runtime>(app_handle: &AppHandle<R>) -> Setting {.unwrap_or_else(Setting::default);setting.zoom_factor = normalize_zoom_factor(setting.zoom_factor);setting.close_action = normalize_close_action(&setting.close_action);+ normalize_backup_fields(&mut setting);setting}@@ -195,13 +258,14 @@ fn preserve_persisted_fields(mut replacement: Setting, current: &Setting) -> Set/// 兼容旧调用方的整对象写入,但始终保留锁内读到的最新缩放与关窗动作,避免/// 长流程用陈旧 `Setting` 覆盖刚刚由快捷键 / 设置界面写入的值(丢更新)。-pub fn set_store_dat_setting(app_handle: &AppHandle, setting: Setting) {+pub fn set_store_dat_setting(app_handle: &AppHandle, mut setting: Setting) {let value = {let _guard = setting_write_lock().lock().unwrap_or_else(|error| error.into_inner());let current = read_store_dat_setting(app_handle);- let setting = preserve_persisted_fields(setting, ¤t);+ setting = preserve_persisted_fields(setting, ¤t);+ normalize_backup_fields(&mut setting);write_store_dat_setting(app_handle, &setting)};emit_setting(app_handle, &value);@@ -221,6 +285,7 @@ wheresetting.zoom_factor = normalize_zoom_factor(setting.zoom_factor);// 落盘前的第二道闸:调用方(含前端 invoke)写入的不可信取值不以原始形态进 storesetting.close_action = normalize_close_action(&setting.close_action);+ normalize_backup_fields(&mut setting);let value = write_store_dat_setting(app_handle, &setting);(setting, value)};@@ -337,10 +402,7 @@ mod tests {default_close_action(),"旧配置缺失 close_action 时应回落默认");- assert_eq!(- setting.port, 4099,- "缺失 close_action 不应影响其余字段"- );+ assert_eq!(setting.port, 4099, "缺失 close_action 不应影响其余字段");}#[test]diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex bf27d2ba..43470ac1 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -528,6 +528,10 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::create_profile,crate::bridge::set_active_profile,crate::bridge::remove_profile,+ crate::bridge::backup_profile,+ crate::bridge::restore_profile,+ crate::bridge::list_backups,+ crate::bridge::delete_backup,crate::bridge::get_cores,crate::bridge::set_active_core,crate::bridge::download_core,diff --git a/src-tauri/src/service/backup/archive.rs b/src-tauri/src/service/backup/archive.rsnew file mode 100644index 00000000..2155055d--- /dev/null+++ b/src-tauri/src/service/backup/archive.rs@@ -0,0 +1,404 @@+//! 备份归档:tar.gz 创建与解压。+//!+//! 归档格式与 `download/extractor.rs` 的 TGZ 解压互逆:`tar::Builder` ++//! `flate2::write::GzEncoder` 创建,`flate2::read::GzDecoder` + `tar::Archive`+//! 解压。解压前逐条目校验路径不跳出目标目录(防路径穿越)。++use std::fs;+use std::io::Write;+use std::path::Path;++/// 需要从归档中排除的相对路径组件(前缀匹配)。+const EXCLUDED_NAMES: &[&str] = &[".backups", ".harness.pid"];++/// 需要从归档中排除的相对路径(精确匹配)。+const EXCLUDED_PATHS: &[&str] = &["node_modules/.modules.yaml"];++/// 凭据文件名。+const CREDENTIALS_FILE: &str = ".credentials.yaml";++/// 判断一条相对路径是否应被排除。+///+/// - `.backups/` 自身必须排除(防递归包含)。+/// - `.harness.pid` 等运行时产物必须排除。+/// - `.credentials.yaml` 按 `include_credentials` 决定。+fn is_excluded(rel: &Path, include_credentials: bool) -> bool {+ if let Some(name) = rel.file_name().and_then(|n| n.to_str()) {+ if EXCLUDED_NAMES.contains(&name) {+ return true;+ }+ if name == CREDENTIALS_FILE && !include_credentials {+ return true;+ }+ }+ let rel_str = rel.to_string_lossy().replace('\\', "/");+ if EXCLUDED_PATHS.iter().any(|p| rel_str == *p) {+ return true;+ }+ false+}++/// 递归地把 `dir` 下所有文件追加到 tar 构建器,跳过排除项。+///+/// `rel` 为当前目录到归档根(`source`)的相对路径前缀,`source` 为原始归档根+///(用于计算根相对路径以做排除判断)。+fn append_dir_filtered(+ builder: &mut tar::Builder<impl Write>,+ dir: &Path,+ source: &Path,+ rel: &Path,+ include_credentials: bool,+) -> Result<(), String> {+ 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 archived = rel.join(name);+ // 根相对路径(用于排除判断)+ let root_rel = path+ .strip_prefix(source)+ .map_err(|e| format!("BACKUP_ARCHIVE_STRIP: {e}"))?;+ if is_excluded(root_rel, include_credentials) {+ continue;+ }+ if path.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 {+ builder+ .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}"))?;+ }+ }+ Ok(())+}++/// 创建 tar.gz 归档。+///+/// 把 `source` 目录打包到 `dest` 文件。`include_credentials` 控制是否包含+/// `.credentials.yaml`。始终排除 `.backups/`、`.harness.pid`、+/// `node_modules/.modules.yaml`。+pub fn create_archive(+ source: &Path,+ dest: &Path,+ include_credentials: bool,+) -> Result<(), String> {+ let tar_gz = fs::File::create(dest).map_err(|e| format!("BACKUP_ARCHIVE_CREATE: {e}"))?;+ let enc = flate2::write::GzEncoder::new(tar_gz, flate2::Compression::default());+ let mut archive = tar::Builder::new(enc);+ append_dir_filtered(&mut archive, source, source, Path::new("."), include_credentials)?;+ archive+ .finish()+ .map_err(|e| format!("BACKUP_ARCHIVE_FINISH: {e}"))?;+ Ok(())+}++/// 解压 tar.gz 归档到 `dest` 目录。+///+/// 每条目的路径在写入前都经过 `fs_guard::ensure_within` 校验,任何跳出+/// `dest` 的条目都会导致整体失败(防路径穿越)。+pub fn extract_archive(archive: &Path, dest: &Path) -> Result<(), String> {+ fs::create_dir_all(dest).map_err(|e| format!("BACKUP_EXTRACT_MKDIR: {e}"))?;+ let tar_gz = fs::File::open(archive).map_err(|e| format!("BACKUP_EXTRACT_OPEN: {e}"))?;+ let dec = flate2::read::GzDecoder::new(tar_gz);+ let mut archive = tar::Archive::new(dec);+ let dest_real = dunce::canonicalize(dest)+ .map_err(|e| format!("BACKUP_EXTRACT_CANONICALIZE_DEST: {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}"))?;++ // 拒绝含 `..` 组件的条目(规范化前第一道闸)+ if path+ .components()+ .any(|c| matches!(c, std::path::Component::ParentDir))+ {+ return Err(format!(+ "BACKUP_EXTRACT_PATH_ESCAPE: entry {:?} contains ..",+ path+ ));+ }++ let joined = dest_real.join(&path);+ // 规范化并校验不跳出目标目录。目标文件可能尚未创建,此时规范化父目录+ // 后拼接文件名,再校验前缀。+ let joined_real = if joined.exists() {+ dunce::canonicalize(&joined)+ .map_err(|e| format!("BACKUP_EXTRACT_CANONICALIZE_ENTRY: {e}"))?+ } else {+ let parent = joined.parent().ok_or_else(|| {+ format!("BACKUP_EXTRACT_NO_PARENT: entry {:?}", path)+ })?;+ fs::create_dir_all(parent)+ .map_err(|e| format!("BACKUP_EXTRACT_MKDIR_PARENT: {e}"))?;+ let parent_real =+ dunce::canonicalize(parent).map_err(|e| {+ format!("BACKUP_EXTRACT_CANONICALIZE_PARENT: {e}")+ })?;+ let name = joined.file_name().ok_or_else(|| {+ format!("BACKUP_EXTRACT_NO_FILENAME: entry {:?}", path)+ })?;+ parent_real.join(name)+ };+ if !joined_real.starts_with(&dest_real) {+ return Err(format!(+ "BACKUP_EXTRACT_PATH_ESCAPE: entry {:?} resolves outside dest",+ path+ ));+ }+ // 拒绝符号链接和硬链接:link_name 的目标不受 path 校验约束,可能跳出目标目录+ let entry_type = entry.header().entry_type();+ if entry_type.is_symlink() || entry_type.is_hard_link() {+ return Err(format!(+ "BACKUP_EXTRACT_UNSUPPORTED_LINK: entry {:?} is a symlink or hard link",+ path+ ));+ }+ entry+ .unpack(&joined_real)+ .map_err(|e| format!("BACKUP_EXTRACT_UNPACK: {e}"))?;+ }+ Ok(())+}++/// 列出归档中所有条目的相对路径(用于测试校验排除项)。+#[cfg(test)]+fn list_archive_entries(archive: &Path) -> Result<Vec<String>, String> {+ let tar_gz = fs::File::open(archive).map_err(|e| format!("BACKUP_LIST_OPEN: {e}"))?;+ let dec = flate2::read::GzDecoder::new(tar_gz);+ 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}"))? {+ 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('\\', "/"));+ }+ Ok(entries)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::PathBuf;++ /// 全局递增计数器,保证并行测试使用互不冲突的临时目录。+ fn unique_suffix() -> String {+ use std::sync::atomic::{AtomicUsize, Ordering};+ static COUNTER: AtomicUsize = AtomicUsize::new(0);+ format!(+ "{}-{}",+ std::process::id(),+ COUNTER.fetch_add(1, Ordering::SeqCst)+ )+ }++ /// 计算与 source 同级的归档目标路径。+ fn archive_dest(source: &Path) -> PathBuf {+ source+ .parent()+ .unwrap()+ .join(format!("{}.tar.gz", source.file_name().unwrap().to_str().unwrap()))+ }++ /// 创建临时目录并写入若干文件作为测试夹具。+ fn setup_source_dir(files: &[(&str, &str)]) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("dsh-backup-archive-{}", unique_suffix()));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();+ for (rel, content) in files {+ let path = dir.join(rel);+ if let Some(parent) = path.parent() {+ fs::create_dir_all(parent).unwrap();+ }+ let mut f = fs::File::create(&path).unwrap();+ f.write_all(content.as_bytes()).unwrap();+ }+ dir+ }++ #[test]+ fn creates_tar_gzip_archive() {+ let source = setup_source_dir(&[("hello.txt", "world")]);+ let dest = archive_dest(&source);+ create_archive(&source, &dest, false).unwrap();+ assert!(dest.exists(), "归档文件应存在");+ assert!(fs::metadata(&dest).unwrap().len() > 0, "归档文件应非空");+ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_file(&dest);+ }++ #[test]+ fn excludes_backup_dir_from_archive() {+ let source = setup_source_dir(&[+ ("hello.txt", "world"),+ (".backups/old.tar.gz", "junk"),+ (".backups/.manifest.json", "{}"),+ ]);+ let dest = archive_dest(&source);+ create_archive(&source, &dest, false).unwrap();+ let entries = list_archive_entries(&dest).unwrap();+ assert!(+ entries.iter().all(|e| !e.contains(".backups")),+ ".backups 应被排除,实际条目: {entries:?}"+ );+ assert!(+ entries.iter().any(|e| e.contains("hello.txt")),+ "hello.txt 应存在"+ );+ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_file(&dest);+ }++ #[test]+ fn credentials_excluded_by_default() {+ 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();+ assert!(+ entries.iter().all(|e| !e.contains(".credentials.yaml")),+ "凭据默认应被排除,实际条目: {entries:?}"+ );+ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_file(&dest);+ }++ #[test]+ fn credentials_included_when_opted_in() {+ 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();+ assert!(+ entries.iter().any(|e| e.contains(".credentials.yaml")),+ "勾选时凭据应被包含,实际条目: {entries:?}"+ );+ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_file(&dest);+ }++ #[test]+ fn restore_overwrites_existing_data() {+ let source = setup_source_dir(&[("config.yaml", "version: 1")]);+ let dest_gz = archive_dest(&source);+ create_archive(&source, &dest_gz, false).unwrap();++ // 还原到新目录+ let restore_dir = std::env::temp_dir().join(format!("dsh-backup-restore-{}", unique_suffix()));+ extract_archive(&dest_gz, &restore_dir).unwrap();++ let restored = fs::read_to_string(restore_dir.join("config.yaml")).unwrap();+ assert_eq!(restored, "version: 1", "还原后应回到原始内容");+ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_file(&dest_gz);+ let _ = fs::remove_dir_all(&restore_dir);+ }++ /// 手工构造含路径穿越条目的 tar 头部(绕过 `tar::Header::set_path` 对 `..` 的校验)。+ fn write_raw_tar_entry<W: std::io::Write>(+ writer: &mut W,+ path: &str,+ data: &[u8],+ ) -> Result<(), String> {+ let mut header = [0u8; 512];+ // name (0..100)+ let path_bytes = path.as_bytes();+ if path_bytes.len() > 100 {+ return Err("path too long".to_string());+ }+ header[0..path_bytes.len()].copy_from_slice(path_bytes);+ // mode 0644 (octal, 100..108)+ 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");+ // 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());+ // mtime 0 (136..148)+ header[136..148].copy_from_slice(b"00000000000\0");+ // typeflag Regular (156)+ header[156] = b'0';+ // magic + version (257..265)+ header[257..263].copy_from_slice(b"ustar\0");+ header[263..265].copy_from_slice(b"00");+ // checksum (148..156): 先填空格,再算字节和+ header[148..156].copy_from_slice(b" ");+ let checksum: u32 = header.iter().map(|&b| b as u32).sum();+ let ck_str = format!("{:06o}\0 ", checksum);+ header[148..148 + ck_str.len()].copy_from_slice(ck_str.as_bytes());++ writer.write_all(&header).map_err(|e| e.to_string())?;+ writer.write_all(data).map_err(|e| e.to_string())?;+ // pad to 512 boundary+ let pad = (512 - (data.len() % 512)) % 512;+ if pad > 0 {+ writer.write_all(&vec![0u8; pad]).map_err(|e| e.to_string())?;+ }+ Ok(())+ }++ #[test]+ fn rejects_path_traversal_on_restore() {+ let dir = std::env::temp_dir().join(format!("dsh-backup-traversal-{}", unique_suffix()));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();++ let archive_path = dir.join("evil.tar.gz");+ // 以裸字节写 gzip(tar crate 的 set_path 会拒绝 ..,故绕开)+ let tar_gz = fs::File::create(&archive_path).unwrap();+ let mut enc = flate2::write::GzEncoder::new(tar_gz, flate2::Compression::default());+ write_raw_tar_entry(&mut enc, "../../../tmp/dsh-evil-passwd", b"evil").unwrap();+ // tar 文件尾:两个空块+ enc.write_all(&[0u8; 1024]).unwrap();+ enc.finish().unwrap();++ let dest = dir.join("dest");+ let result = extract_archive(&archive_path, &dest);+ assert!(result.is_err(), "路径穿越应被拒绝: {result:?}");+ assert!(+ !std::path::Path::new("/tmp/dsh-evil-passwd").exists(),+ "恶意文件不应被写入系统目录"+ );+ let _ = fs::remove_dir_all(&dir);+ }++ #[test]+ fn excludes_pid_and_modules_yaml() {+ let source = setup_source_dir(&[+ (".harness.pid", "12345"),+ ("node_modules/.modules.yaml", "modules: {}"),+ ("real.txt", "keep"),+ ]);+ let dest = archive_dest(&source);+ create_archive(&source, &dest, false).unwrap();+ let entries = list_archive_entries(&dest).unwrap();+ assert!(+ entries.iter().all(|e| !e.contains(".harness.pid")),+ ".harness.pid 应被排除"+ );+ assert!(+ entries.iter().all(|e| !e.contains(".modules.yaml")),+ "node_modules/.modules.yaml 应被排除"+ );+ assert!(+ entries.iter().any(|e| e.contains("real.txt")),+ "real.txt 应存在"+ );+ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_file(&dest);+ }+}diff --git a/src-tauri/src/service/backup/mod.rs b/src-tauri/src/service/backup/mod.rsnew file mode 100644index 00000000..5bfcccd4--- /dev/null+++ b/src-tauri/src/service/backup/mod.rs@@ -0,0 +1,313 @@+//! 档案备份与还原。+//!+//! 把 `$DSH_HOME` 打包为版本化的 `.tar.gz` 快照,存放在 `$DSH_HOME/.backups/`,+//! 支持手动创建 / 还原(覆盖或新建)/ 列表 / 删除,以及自动备份调度与保留份数裁剪。++pub mod archive;+pub mod retention;+pub mod schedule;++use std::fs;+use std::path::{Path, PathBuf};+use tauri::AppHandle;++use crate::config;++/// 备份选项。+#[derive(Debug, Clone)]+pub struct BackupOptions {+ /// 是否包含凭据文件(`.credentials.yaml`)。默认 false。+ pub include_credentials: bool,+}++/// 备份信息(序列化 camelCase 给前端)。+#[derive(Debug, Clone, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct BackupInfo {+ /// 快照时间戳(文件名主体,如 `2026-08-30T12-00-00`)。+ pub timestamp: String,+ /// 归档文件完整路径。+ pub path: String,+ /// 归档文件大小(字节)。+ pub size: u64,+ /// 是否包含凭据。+ pub include_credentials: bool,+}++/// 还原模式。+#[derive(Debug, Clone, Copy)]+pub enum RestoreMode {+ /// 覆盖当前 `$DSH_HOME`。+ Overwrite,+ /// 创建新档案目录并解压到其中。+ AsNew,+}++/// 备份清单(索引文件 `.manifest.json` 的内容)。+#[derive(Debug, serde::Serialize, serde::Deserialize)]+struct BackupManifest {+ backups: Vec<ManifestEntry>,+}++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+struct ManifestEntry {+ timestamp: String,+ path: String,+ size: u64,+ include_credentials: bool,+}++/// 获取备份目录(`$DSH_HOME/.backups/`),不存在时自动创建。+pub fn get_backup_dir(app_handle: &AppHandle) -> PathBuf {+ let dir = config::get_dsh_data_path(app_handle).join(".backups");+ fs::create_dir_all(&dir).ok();+ dir+}++/// 从时间戳推导归档文件名。+fn archive_filename(timestamp: &str) -> String {+ format!("{timestamp}.tar.gz")+}++/// 清单读取错误。+#[derive(Debug)]+enum ManifestError {+ /// 清单文件存在但无法解析(损坏),已另存为 .corrupt 以便人工恢复。+ ParseError(String),+}++impl std::fmt::Display for ManifestError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ ManifestError::ParseError(e) => write!(f, "manifest parse error: {e}"),+ }+ }+}++impl std::error::Error for ManifestError {}++/// 读取备份清单。+///+/// - 清单不存在 → 返回空(首次备份的合法空状态)。+/// - 清单存在但损坏 → 另存为 `.corrupt` 以便人工恢复,并返回错误,避免+/// `create_backup` / `delete_backup` 用空清单覆盖导致既有索引丢失。+fn read_manifest(backup_dir: &Path) -> Result<BackupManifest, ManifestError> {+ let path = backup_dir.join(".manifest.json");+ let content = match fs::read_to_string(&path) {+ Ok(c) => c,+ // 清单不存在 → 首次备份的合法空状态,返回空清单+ Err(_) => return Ok(BackupManifest { backups: vec![] }),+ };+ if content.trim().is_empty() {+ return Err(ManifestError::ParseError("empty manifest".into()));+ }+ match serde_json::from_str(&content) {+ Ok(manifest) => Ok(manifest),+ Err(e) => {+ log::error!("BACKUP_MANIFEST_PARSE: {} {e}", path.display());+ let _ = fs::rename(&path, path.with_extension("corrupt"));+ Err(ManifestError::ParseError(e.to_string()))+ }+ }+}++/// 原子写入备份清单。+fn write_manifest(backup_dir: &Path, manifest: &BackupManifest) -> Result<(), String> {+ let path = backup_dir.join(".manifest.json");+ let tmp = path.with_extension("tmp");+ let content = serde_json::to_string_pretty(manifest)+ .map_err(|e| format!("BACKUP_MANIFEST_SERIALIZE: {e}"))?;+ fs::write(&tmp, content).map_err(|e| format!("BACKUP_MANIFEST_WRITE: {e}"))?;+ fs::rename(&tmp, path).map_err(|e| format!("BACKUP_MANIFEST_RENAME: {e}"))?;+ Ok(())+}++/// 生成时间戳(UTC,格式 `2026-08-30T12-00-00`)。+fn now_timestamp() -> String {+ use time::OffsetDateTime;+ let now = OffsetDateTime::now_utc();+ // 格式:YYYY-MM-DDTHH-MM-SS+ let date = now.date();+ let time = now.time();+ format!(+ "{:04}-{:02}-{:02}T{:02}-{:02}-{:02}",+ date.year(),+ date.month() as u8,+ date.day(),+ time.hour(),+ time.minute(),+ time.second()+ )+}++/// 创建备份。+///+/// 把 `$DSH_HOME` 打包到 `$DSH_HOME/.backups/<timestamp>.tar.gz`,更新清单,+/// 并按保留份数裁剪。+pub fn create_backup(+ app_handle: &AppHandle,+ options: BackupOptions,+) -> Result<BackupInfo, String> {+ let backup_dir = get_backup_dir(app_handle);+ let timestamp = now_timestamp();+ let filename = archive_filename(×tamp);+ let dest = backup_dir.join(&filename);+ let source = config::get_dsh_data_path(app_handle);++ archive::create_archive(&source, &dest, options.include_credentials)?;++ let size = fs::metadata(&dest)+ .map(|m| m.len())+ .unwrap_or(0);++ let info = BackupInfo {+ timestamp: timestamp.clone(),+ path: dest.to_string_lossy().into_owned(),+ size,+ include_credentials: options.include_credentials,+ };++ // 更新清单:清单损坏时中止写入,避免用空清单覆盖导致既有索引丢失+ let mut manifest = read_manifest(&backup_dir)+ .map_err(|e| format!("BACKUP_MANIFEST_CORRUPT: {e}"))?;+ manifest.backups.push(ManifestEntry {+ timestamp: info.timestamp.clone(),+ path: info.path.clone(),+ size: info.size,+ include_credentials: info.include_credentials,+ });+ write_manifest(&backup_dir, &manifest)?;++ // 裁剪+ prune_if_needed(app_handle)?;++ Ok(info)+}++/// 列出所有备份(按时间戳升序)。+pub fn list_backups(app_handle: &AppHandle) -> Vec<BackupInfo> {+ let backup_dir = get_backup_dir(app_handle);+ // 清单损坏时返回空列表(不抛错),避免影响页面其余部分;写入路径会另行中止+ let manifest = match read_manifest(&backup_dir) {+ Ok(m) => m,+ Err(e) => {+ log::error!("[backup] list_backups: manifest unreadable: {e}");+ return vec![]+ }+ };+ manifest+ .backups+ .into_iter()+ .map(|e| BackupInfo {+ timestamp: e.timestamp,+ path: e.path,+ size: e.size,+ include_credentials: e.include_credentials,+ })+ .collect()+}++/// 删除指定备份(文件 + 清单条目)。+///+/// `timestamp` 会经过 `fs_guard::validate_id` 校验,防路径穿越。+pub fn delete_backup(app_handle: &AppHandle, timestamp: &str) -> Result<(), String> {+ crate::service::fs_guard::validate_id(timestamp)?;+ let backup_dir = get_backup_dir(app_handle);+ let filename = archive_filename(timestamp);+ let file = backup_dir.join(&filename);+ if file.exists() {+ fs::remove_file(&file).map_err(|e| format!("BACKUP_DELETE_FILE: {e}"))?;+ }+ // 清单损坏时中止写入,避免用空清单覆盖导致既有索引丢失+ let mut manifest = match read_manifest(&backup_dir) {+ Ok(m) => m,+ Err(e) => return Err(format!("BACKUP_MANIFEST_CORRUPT: {e}")),+ };+ manifest.backups.retain(|e| e.timestamp != timestamp);+ write_manifest(&backup_dir, &manifest)?;+ Ok(())+}++/// 还原备份。+///+/// `mode` 为 `Overwrite` 时覆盖当前 `$DSH_HOME`(调用方应先停止服务);+/// `AsNew` 时创建新档案目录并解压到其中。+///+/// `timestamp` 经过 `fs_guard::validate_id` 校验。+pub fn restore_backup(+ app_handle: &AppHandle,+ timestamp: &str,+ mode: RestoreMode,+) -> Result<(), String> {+ crate::service::fs_guard::validate_id(timestamp)?;+ let backup_dir = get_backup_dir(app_handle);+ let filename = archive_filename(timestamp);+ let archive_path = backup_dir.join(&filename);+ if !archive_path.exists() {+ return Err(format!(+ "BACKUP_NOT_FOUND: backup {timestamp} does not exist"+ ));+ }++ match mode {+ RestoreMode::Overwrite => {+ let dest = config::get_dsh_data_path(app_handle);+ archive::extract_archive(&archive_path, &dest)?;+ }+ RestoreMode::AsNew => {+ // 创建新档案目录:$DSH_HOME/profiles/<timestamp>+ let profiles_root = config::get_dsh_data_path(app_handle).join("profiles");+ fs::create_dir_all(&profiles_root).map_err(|e| {+ format!("BACKUP_RESTORE_MKDIR_PROFILES: {e}")+ })?;+ let new_dir = profiles_root.join(format!("restored-{timestamp}"));+ archive::extract_archive(&archive_path, &new_dir)?;+ }+ }+ Ok(())+}++/// 按保留份数裁剪旧备份(超出时删除最旧的)。+pub fn prune_if_needed(app_handle: &AppHandle) -> Result<(), String> {+ let setting = config::get_store_dat_setting(app_handle);+ retention::prune_old_backups(app_handle, setting.backup_retention_count)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn timestamp_format_is_valid() {+ let ts = now_timestamp();+ // 格式:YYYY-MM-DDTHH-MM-SS+ assert!(ts.contains('T'), "时间戳应包含 T 分隔符: {ts}");+ assert_eq!(ts.len(), 19, "时间戳长度应为 19: {ts}");+ assert!(ts.chars().nth(4) == Some('-'));+ assert!(ts.chars().nth(7) == Some('-'));+ }++ #[test]+ fn manifest_round_trip() {+ let dir = std::env::temp_dir().join(format!("dsh-backup-manifest-{}", std::process::id()));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();++ let manifest = BackupManifest {+ backups: vec![ManifestEntry {+ timestamp: "2026-08-30T12-00-00".to_string(),+ path: "/tmp/x.tar.gz".to_string(),+ size: 100,+ include_credentials: false,+ }],+ };+ write_manifest(&dir, &manifest).unwrap();+ let read = read_manifest(&dir).unwrap();+ assert_eq!(read.backups.len(), 1);+ assert_eq!(read.backups[0].timestamp, "2026-08-30T12-00-00");+ assert_eq!(read.backups[0].size, 100);++ let _ = fs::remove_dir_all(&dir);+ }+}diff --git a/src-tauri/src/service/backup/retention.rs b/src-tauri/src/service/backup/retention.rsnew file mode 100644index 00000000..181b080b--- /dev/null+++ b/src-tauri/src/service/backup/retention.rs@@ -0,0 +1,195 @@+//! 备份保留份数裁剪。+//!+//! 当备份数量超过 `backup_retention_count` 时,删除最旧的备份(文件 + 清单条目)。++use std::fs;+use std::path::Path;+use tauri::AppHandle;++use crate::service::backup;++/// 按保留份数裁剪指定目录下的旧备份(文件 + 清单条目)。+///+/// 纯函数:只读 `backup_dir` 路径,不依赖 AppHandle,便于单元测试。+pub fn prune_backups_in_dir(+ backup_dir: &Path,+ retention_count: u32,+) -> Result<(), String> {+ if retention_count == 0 {+ return Ok(());+ }+ // 读取清单+ let manifest_path = backup_dir.join(".manifest.json");+ let content = fs::read_to_string(&manifest_path).unwrap_or_default();+ let mut manifest: serde_json::Value = if content.trim().is_empty() {+ serde_json::json!({ "backups": [] })+ } else {+ serde_json::from_str(&content)+ .map_err(|e| format!("BACKUP_PRUNE_MANIFEST: {e}"))?+ };+ let backups = manifest["backups"]+ .as_array_mut()+ .ok_or_else(|| "BACKUP_PRUNE_MANIFEST_INVALID: backups is not an array".to_string())?;++ if backups.len() <= retention_count as usize {+ return Ok(());+ }++ // 按时间戳升序,保留最新的 retention_count 份+ backups.sort_by(|a, b| {+ let a_ts = a["timestamp"].as_str().unwrap_or("");+ let b_ts = b["timestamp"].as_str().unwrap_or("");+ a_ts.cmp(b_ts)+ });+ let remove_count = backups.len() - retention_count as usize;+ let to_remove: Vec<String> = backups+ .drain(..remove_count)+ .filter_map(|v| v["timestamp"].as_str().map(String::from))+ .collect();++ // 写回清单(先写 tmp 再 rename,原子性)+ let tmp = manifest_path.with_extension("tmp");+ fs::write(+ &tmp,+ serde_json::to_string_pretty(&manifest)+ .map_err(|e| format!("BACKUP_PRUNE_SERIALIZE: {e}"))?,+ )+ .map_err(|e| format!("BACKUP_PRUNE_WRITE: {e}"))?;+ fs::rename(&tmp, &manifest_path)+ .map_err(|e| format!("BACKUP_PRUNE_RENAME: {e}"))?;++ // 删除文件+ for ts in &to_remove {+ let file = backup_dir.join(format!("{ts}.tar.gz"));+ if file.exists() {+ fs::remove_file(&file).map_err(|e| format!("BACKUP_PRUNE_FILE: {e}"))?;+ }+ }+ Ok(())+}++/// 按保留份数裁剪当前 $DSH_HOME/.backups/ 下的旧备份。+pub fn prune_old_backups(+ app_handle: &AppHandle,+ retention_count: u32,+) -> Result<(), String> {+ let backup_dir = backup::get_backup_dir(app_handle);+ prune_backups_in_dir(&backup_dir, retention_count)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write as _;++ /// 在临时目录下构造指定数量的假备份文件 + 清单,返回目录路径。+ fn setup_fake_backups(count: usize) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "dsh-backup-retention-{}-{}",+ std::process::id(),+ count+ ));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();++ let mut entries = Vec::new();+ for i in 0..count {+ // 时间戳按 i 递增,便于验证「最旧的被删」+ let ts = format!("2026-08-30T12-00-{:02}", i);+ let file = dir.join(format!("{ts}.tar.gz"));+ let mut f = fs::File::create(&file).unwrap();+ f.write_all(b"dummy").unwrap();+ entries.push(serde_json::json!({+ "timestamp": ts,+ "path": file.to_string_lossy(),+ "size": 5,+ "includeCredentials": false+ }));+ }++ let manifest = serde_json::json!({ "backups": entries });+ fs::write(+ dir.join(".manifest.json"),+ serde_json::to_string_pretty(&manifest).unwrap(),+ )+ .unwrap();+ dir+ }++ fn read_manifest_backups(dir: &Path) -> Vec<String> {+ let content = fs::read_to_string(dir.join(".manifest.json")).unwrap();+ let m: serde_json::Value = serde_json::from_str(&content).unwrap();+ m["backups"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|v| v["timestamp"].as_str().map(String::from))+ .collect()+ }++ #[test]+ fn prunes_oldest_backups_beyond_limit() {+ let dir = setup_fake_backups(5);+ prune_backups_in_dir(&dir, 3).unwrap();++ let remaining = read_manifest_backups(&dir);+ assert_eq!(remaining.len(), 3, "5 份备份 retention=3 应剩 3 份");+ // 最旧的 2 个(00, 01)应被删除+ assert!(!remaining.contains(&"2026-08-30T12-00-00".to_string()));+ assert!(!remaining.contains(&"2026-08-30T12-00-01".to_string()));+ // 文件也应被删除+ assert!(!dir.join("2026-08-30T12-00-00.tar.gz").exists());+ assert!(!dir.join("2026-08-30T12-00-01.tar.gz").exists());+ let _ = fs::remove_dir_all(&dir);+ }++ #[test]+ fn keeps_all_within_limit() {+ let dir = setup_fake_backups(3);+ prune_backups_in_dir(&dir, 10).unwrap();++ let remaining = read_manifest_backups(&dir);+ assert_eq!(remaining.len(), 3, "3 份备份 retention=10 应全部保留");+ for i in 0..3 {+ let ts = format!("2026-08-30T12-00-{:02}", i);+ assert!(dir.join(format!("{ts}.tar.gz")).exists());+ }+ let _ = fs::remove_dir_all(&dir);+ }++ #[test]+ fn removes_both_file_and_manifest_entry() {+ let dir = setup_fake_backups(2);+ prune_backups_in_dir(&dir, 1).unwrap();++ let remaining = read_manifest_backups(&dir);+ assert_eq!(remaining.len(), 1);+ // 最旧的被删+ assert!(!dir.join("2026-08-30T12-00-00.tar.gz").exists());+ // 较新的保留+ assert!(dir.join("2026-08-30T12-00-01.tar.gz").exists());+ let _ = fs::remove_dir_all(&dir);+ }++ #[test]+ fn handles_empty_backup_list() {+ let dir = std::env::temp_dir().join(format!(+ "dsh-backup-retention-empty-{}",+ std::process::id()+ ));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();+ let manifest = serde_json::json!({ "backups": [] });+ fs::write(+ dir.join(".manifest.json"),+ serde_json::to_string_pretty(&manifest).unwrap(),+ )+ .unwrap();++ // 空清单不 panic+ prune_backups_in_dir(&dir, 3).unwrap();+ let remaining = read_manifest_backups(&dir);+ assert!(remaining.is_empty());+ let _ = fs::remove_dir_all(&dir);+ }+}diff --git a/src-tauri/src/service/backup/schedule.rs b/src-tauri/src/service/backup/schedule.rsnew file mode 100644index 00000000..7f516e0b--- /dev/null+++ b/src-tauri/src/service/backup/schedule.rs@@ -0,0 +1,236 @@+//! 自动备份触发决策。+//!+//! 决定「何时」该自动备份:启动触发、周期触发、配置变化触发。决策本身很轻+//! (几次比较),由 `scheduler` 每 5s 轮询调用;真正耗时的归档操作在命中后+//! 丢到 `spawn_blocking` 执行,不阻塞 tick。++use std::sync::{Mutex, OnceLock};+use tauri::AppHandle;++use crate::config;+use crate::service::backup;++/// 备份运行时状态(进程级单例)。+#[derive(Debug, Clone, Default)]+pub struct BackupState {+ /// 上次成功备份的时间。+ pub last_backup_time: Option<time::OffsetDateTime>,+ /// 配置变化触发的待执行标志。+ pub pending_change_backup: bool,+}++fn backup_state() -> std::sync::MutexGuard<'static, BackupState> {+ static STATE: OnceLock<Mutex<BackupState>> = OnceLock::new();+ STATE+ .get_or_init(|| Mutex::new(BackupState::default()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++/// 纯决策函数:给定当前状态、设置与时间,判断是否应触发自动备份。+///+/// 不读取任何全局状态或 AppHandle,便于单元测试直接覆盖所有分支。+pub fn should_trigger(+ state: &BackupState,+ setting: &config::Setting,+ now: time::OffsetDateTime,+) -> bool {+ if !setting.auto_backup_enabled {+ return false;+ }+ // 启动触发:首次 tick(尚无备份记录)+ if setting.auto_backup_on_startup && state.last_backup_time.is_none() {+ return true;+ }+ // 配置变化触发:mark_config_changed 设置的待执行标志+ if state.pending_change_backup && setting.auto_backup_on_change {+ return true;+ }+ // 周期触发:距上次备份已达到间隔天数+ if setting.auto_backup_interval_days > 0 {+ if let Some(last) = state.last_backup_time {+ let elapsed = now - last;+ let interval = time::Duration::days(setting.auto_backup_interval_days as i64);+ if elapsed >= interval {+ return true;+ }+ }+ }+ false+}++/// 对外封装:读取全局状态与当前设置,判断是否应触发。+pub fn should_trigger_auto_backup(app_handle: &AppHandle, now: time::OffsetDateTime) -> bool {+ let state = backup_state();+ let setting = config::get_store_dat_setting(app_handle);+ should_trigger(&state, &setting, now)+}++/// 记录一次成功备份的时间,并清除配置变化待执行标志。+pub fn record_backup_time(now: time::OffsetDateTime) {+ let mut state = backup_state();+ state.last_backup_time = Some(now);+ state.pending_change_backup = false;+}++/// 标记配置已变化:若开启了「配置变化时备份」,设置待执行标志。+///+/// 由 `bridge::config::update_app_config` 在成功更新配置后调用。真正的备份+/// 执行被推迟到下一次 tick,让 tick 轮询自然去抖(合并短时间内的多次变化)。+pub fn mark_config_changed(app_handle: &AppHandle) {+ let setting = config::get_store_dat_setting(app_handle);+ if !setting.auto_backup_on_change {+ return;+ }+ let mut state = backup_state();+ state.pending_change_backup = true;+}++/// 调度器 tick 入口:判断是否应触发,命中则异步执行备份。+///+/// 决策本身轻量(几次比较);归档操作通过 `spawn_blocking` 脱离异步运行时,+/// 不阻塞后续 tick。+pub fn check_and_trigger(app_handle: &AppHandle) {+ let now = time::OffsetDateTime::now_utc();+ if !should_trigger_auto_backup(app_handle, now) {+ return;+ }+ // 先占位防并发重复;失败后回滚,避免一次失败吞掉启动 / 配置变化触发+ let previous = backup_state().clone();+ record_backup_time(now);++ let app = app_handle.clone();+ tauri::async_runtime::spawn_blocking(move || {+ let options = backup::BackupOptions {+ include_credentials: false,+ };+ if let Err(e) = backup::create_backup(&app, options) {+ log::error!("[backup] auto backup failed: {e}");+ let mut state = backup_state();+ *state = previous;+ return;+ }+ if let Err(e) = backup::prune_if_needed(&app) {+ log::warn!("[backup] auto backup prune failed: {e}");+ }+ log::info!("[backup] auto backup completed");+ });+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::config::Setting;++ /// 构造测试用 Setting,仅设置与备份相关的字段,其余走默认。+ fn setting_with(+ enabled: bool,+ interval_days: u32,+ on_startup: bool,+ on_change: bool,+ ) -> Setting {+ let mut s = Setting::default();+ s.auto_backup_enabled = enabled;+ s.auto_backup_interval_days = interval_days;+ s.auto_backup_on_startup = on_startup;+ s.auto_backup_on_change = on_change;+ s+ }++ fn days_ago(days: i64) -> time::OffsetDateTime {+ time::OffsetDateTime::now_utc() - time::Duration::days(days)+ }++ #[test]+ fn triggers_on_startup_when_enabled() {+ let state = BackupState::default(); // last_backup_time = None+ let setting = setting_with(true, 7, true, false);+ assert!(+ should_trigger(&state, &setting, time::OffsetDateTime::now_utc()),+ "首次启动且 on_startup=true 应触发"+ );+ }++ #[test]+ fn does_not_trigger_when_disabled() {+ let state = BackupState::default();+ let setting = setting_with(false, 7, true, false);+ assert!(+ !should_trigger(&state, &setting, time::OffsetDateTime::now_utc()),+ "auto_backup_enabled=false 时任何条件都不应触发"+ );+ }++ #[test]+ fn triggers_after_interval_elapsed() {+ let state = BackupState {+ last_backup_time: Some(days_ago(8)),+ ..Default::default()+ };+ let setting = setting_with(true, 7, false, false);+ assert!(+ should_trigger(&state, &setting, time::OffsetDateTime::now_utc()),+ "距上次备份 8 天、间隔 7 天应触发"+ );+ }++ #[test]+ fn does_not_trigger_before_interval() {+ let state = BackupState {+ last_backup_time: Some(days_ago(3)),+ ..Default::default()+ };+ let setting = setting_with(true, 7, false, false);+ assert!(+ !should_trigger(&state, &setting, time::OffsetDateTime::now_utc()),+ "距上次备份 3 天、间隔 7 天不应触发"+ );+ }++ #[test]+ fn triggers_on_change_when_enabled() {+ let state = BackupState {+ last_backup_time: Some(days_ago(1)),+ pending_change_backup: true,+ };+ let setting = setting_with(true, 7, false, true);+ assert!(+ should_trigger(&state, &setting, time::OffsetDateTime::now_utc()),+ "pending_change_backup + on_change=true 应触发"+ );+ }++ #[test]+ fn does_not_trigger_on_change_when_disabled() {+ let state = BackupState {+ last_backup_time: Some(days_ago(1)),+ pending_change_backup: true,+ };+ let setting = setting_with(true, 7, false, false);+ assert!(+ !should_trigger(&state, &setting, time::OffsetDateTime::now_utc()),+ "on_change=false 时即使 pending 也不应触发"+ );+ }++ #[test]+ fn record_backup_time_prevents_immediate_retrigger() {+ let mut state = BackupState::default();+ let setting = setting_with(true, 7, true, false);++ // 启动触发前+ assert!(should_trigger(&state, &setting, time::OffsetDateTime::now_utc()));++ // 记录备份时间+ record_backup_time(time::OffsetDateTime::now_utc());+ // 注意:record_backup_time 写的是全局单例,这里同步更新本地状态以反映+ state.last_backup_time = Some(time::OffsetDateTime::now_utc());+ state.pending_change_backup = false;++ // 记录后(距上次 0 天,未达 7 天间隔)不应再触发+ assert!(+ !should_trigger(&state, &setting, time::OffsetDateTime::now_utc()),+ "刚记录备份时间后不应立即再触发"+ );+ }+}diff --git a/src-tauri/src/service/mod.rs b/src-tauri/src/service/mod.rsindex 4577db5b..80f87467 100644--- a/src-tauri/src/service/mod.rs+++ b/src-tauri/src/service/mod.rs@@ -1,3 +1,4 @@+pub mod backup;pub mod cli;pub mod core;pub mod download;diff --git a/src-tauri/src/service/scheduler/mod.rs b/src-tauri/src/service/scheduler/mod.rsindex c09b2d37..552d2786 100644--- a/src-tauri/src/service/scheduler/mod.rs+++ b/src-tauri/src/service/scheduler/mod.rs@@ -22,6 +22,8 @@ async fn scheduler_permanent_loop(app_handle: AppHandle) {crate::config::check_and_emit_theme(&app_handle);// 已安装插件文件监控:指纹变化(防抖后)推送 `dsh-plugins-updated`crate::service::plugin::watch::check_and_emit(&app_handle);+ // 自动备份检查:决策轻量(几次比较),命中后 spawn_blocking 执行+ crate::service::backup::schedule::check_and_trigger(&app_handle);interval.tick().await;}}diff --git a/src/components/config-backup.tsx b/src/components/config-backup.tsxnew file mode 100644index 00000000..5cb5c046--- /dev/null+++ b/src/components/config-backup.tsx@@ -0,0 +1,311 @@+import { ArrowLeft, Delete } from '@gravity-ui/icons'+import { Button, Checkbox, Chip, Description, Input, Label, Spinner, Switch } from '@heroui/react'+import { useOverlay } from '@overlastic/react'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { If } from 'react-if-lite'+import { store } from '@/store'+import { toast } from '@/utils/toast'+import { useBackups } from '../hooks/use-backup'+import { normalizeIntervalDays, normalizeRetentionCount } from '../utils/backup-settings'+import { useAppConfig } from './../hooks/use-app-config'+import { Item } from './item'+import { Modal } from './modal'+import { PanelHeader } from './panel-header'+import { PanelState } from './panel-state'++export interface ConfigBackupProps {+ onBack: () => void+}++/** 把字节转为 MB 展示(保留 1 位小数)。 */+function formatSize(bytes: number): string {+ return `${(bytes / 1024 / 1024).toFixed(1)}`+}++export function ConfigBackup({ onBack }: ConfigBackupProps) {+ const { t } = useTranslation()+ const { backups, loading, error, createBackup, restoreBackup, deleteBackup, updateAutoBackupSettings, busy } = useBackups()+ const { data: config } = useAppConfig()+ const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })++ const [includeCredentials, setIncludeCredentials] = useState(false)++ async function handleCreate() {+ try {+ await createBackup(includeCredentials)+ toast(t('backup.created_toast'), { variant: 'accent', timeout: 5000 })+ }+ catch (err) {+ console.error('[ConfigBackup] create failed:', err)+ toast(t('backup.failed_toast'), { variant: 'danger' })+ }+ }++ async function handleRestore(timestamp: string) {+ try {+ await openDialog({+ status: 'danger',+ title: t('backup.restore_confirm_title'),+ description: (+ <p>+ {t('backup.restore_confirm_desc', { timestamp })}+ </p>+ ),+ })+ }+ catch {+ return+ }+ try {+ toast(t('backup.restored_stopped_toast'), { variant: 'accent' })+ await restoreBackup(timestamp, false)+ const key = toast(t('backup.restored_toast'), {+ variant: 'accent',+ timeout: 10_000,+ actionProps: {+ children: t('app.restart'),+ onPress: () => {+ store.harness.restart()+ toast.close(key)+ },+ },+ })+ }+ catch (err) {+ console.error('[ConfigBackup] restore failed:', err)+ toast(t('backup.restore_failed'), { variant: 'danger' })+ }+ }++ async function handleRestoreAsNew(timestamp: string) {+ try {+ await openDialog({+ status: 'warning',+ title: t('backup.restore_new_confirm_title'),+ description: (+ <p>+ {t('backup.restore_new_confirm_desc', { timestamp })}+ </p>+ ),+ })+ }+ catch {+ return+ }+ try {+ await restoreBackup(timestamp, true)+ toast(t('backup.restored_toast'), { variant: 'accent', timeout: 5000 })+ }+ catch (err) {+ console.error('[ConfigBackup] restore as new failed:', err)+ toast(t('backup.restore_failed'), { variant: 'danger' })+ }+ }++ async function handleDelete(timestamp: string) {+ try {+ await openDialog({+ status: 'danger',+ title: t('backup.delete_confirm_title'),+ description: (+ <p>+ {t('backup.delete_confirm_desc', { timestamp })}+ </p>+ ),+ confirmText: t('backup.delete'),+ })+ }+ catch {+ return+ }+ try {+ await deleteBackup(timestamp)+ toast(t('backup.deleted_toast'), { variant: 'accent', timeout: 5000 })+ }+ catch (err) {+ console.error('[ConfigBackup] delete failed:', err)+ toast(t('backup.delete_failed'), { variant: 'danger' })+ }+ }++ return (+ <div className="space-y-3">+ <Button variant="tertiary" className="h-8 rounded-md" onPress={onBack}>+ <ArrowLeft className="size-3.5" />+ <span>{t('backup.back_to_profiles')}</span>+ </Button>++ {/* 手动备份 */}+ <PanelHeader title={t('backup.manual_section')} description="" />+ <div className="flex flex-col gap-3">+ <Button+ variant="primary"+ className="rounded-md"+ isDisabled={busy}+ onPress={handleCreate}+ >+ <If cond={busy}>+ <Spinner size="sm" color="current" />+ <span>{t('backup.in_progress')}</span>+ </If>+ <If cond={!busy}>+ <span>{t('backup.now')}</span>+ </If>+ </Button>+ <Checkbox+ isSelected={includeCredentials}+ onChange={(value: boolean) => setIncludeCredentials(value)}+ aria-label={t('backup.include_credentials')}+ className="shrink-0"+ >+ <Checkbox.Content>+ <Checkbox.Control>+ <Checkbox.Indicator />+ </Checkbox.Control>+ </Checkbox.Content>+ </Checkbox>+ <span className="text-xs text-ink">{t('backup.include_credentials')}</span>+ <If cond={includeCredentials}>+ <Description className="text-[10px] text-danger">+ {t('backup.credentials_warning')}+ </Description>+ </If>+ </div>++ {/* 备份列表 */}+ <PanelHeader title={t('backup.list_section')} description="" />+ <PanelState loading={loading} error={error}>+ <If+ cond={backups.length === 0}+ else={(+ <div className="flex flex-col gap-4">+ {backups.map(backup => (+ <Item+ key={backup.timestamp}+ left={(+ <>+ <Label className="text-xs font-mono text-muted">+ {backup.timestamp}+ </Label>+ <Description className="text-xs font-mono text-muted">+ {formatSize(backup.size)}+ {' '}+ {t('backup.size_unit')}+ </Description>+ </>+ )}+ right={(+ <>+ <Button size="sm" variant="tertiary" className="h-7 rounded-md" onPress={() => handleRestore(backup.timestamp)}>+ {t('backup.restore')}+ </Button>+ <Button size="sm" variant="tertiary" className="h-7 rounded-md" onPress={() => handleRestoreAsNew(backup.timestamp)}>+ {t('backup.restore_as_new')}+ </Button>+ <Chip+ className="rounded-md"+ variant="primary"+ color="danger"+ size="sm"+ onClick={() => handleDelete(backup.timestamp)}+ >+ <Delete className="size-3" />+ </Chip>+ </>+ )}+ />+ ))}+ </div>+ )}+ >+ <div className="space-y-1 rounded-md border border-line bg-panel2/40 p-3">+ <Label className="text-xs font-medium text-ink">{t('backup.empty_title')}</Label>+ <Description className="text-xs text-muted">{t('backup.empty_desc')}</Description>+ </div>+ </If>+ </PanelState>++ {/* 自动备份设置 */}+ <PanelHeader title={t('backup.auto_section')} description="" />+ <div className="flex flex-col gap-4">+ <div className="flex items-center justify-between">+ <span className="text-xs font-medium text-ink">{t('backup.auto_enable')}</span>+ <Switch+ isSelected={config?.auto_backup_enabled ?? false}+ onChange={value => updateAutoBackupSettings({ autoBackupEnabled: value })}+ size="sm"+ >+ <Switch.Content>+ <Switch.Control>+ <Switch.Thumb />+ </Switch.Control>+ </Switch.Content>+ </Switch>+ </div>+ <div className="flex items-center justify-between">+ <span className="text-xs font-medium text-ink">+ {t('backup.auto_interval')}+ <span className="ml-1 text-muted">{t('backup.auto_interval_suffix')}</span>+ </span>+ <Input+ key={config ? String(config.auto_backup_interval_days) : 'loading-interval'}+ type="number"+ variant="secondary"+ min={1}+ max={90}+ defaultValue={String(config?.auto_backup_interval_days ?? 7)}+ onBlur={e => updateAutoBackupSettings({ autoBackupIntervalDays: normalizeIntervalDays(e.target.value) })}+ className="w-[80px]"+ />+ </div>+ <div className="flex items-center justify-between">+ <span className="text-xs font-medium text-ink">{t('backup.auto_startup')}</span>+ <Switch+ isSelected={config?.auto_backup_on_startup ?? false}+ onChange={value => updateAutoBackupSettings({ autoBackupOnStartup: value })}+ size="sm"+ >+ <Switch.Content>+ <Switch.Control>+ <Switch.Thumb />+ </Switch.Control>+ </Switch.Content>+ </Switch>+ </div>+ <div className="flex items-center justify-between">+ <span className="text-xs font-medium text-ink">{t('backup.auto_change')}</span>+ <Switch+ isSelected={config?.auto_backup_on_change ?? false}+ onChange={value => updateAutoBackupSettings({ autoBackupOnChange: value })}+ size="sm"+ >+ <Switch.Content>+ <Switch.Control>+ <Switch.Thumb />+ </Switch.Control>+ </Switch.Content>+ </Switch>+ </div>+ <div className="flex items-center justify-between">+ <span className="text-xs font-medium text-ink">+ {t('backup.auto_retention')}+ <span className="ml-1 text-muted">{t('backup.auto_retention_suffix')}</span>+ </span>+ <Input+ key={config ? String(config.backup_retention_count) : 'loading-retention'}+ type="number"+ variant="secondary"+ min={1}+ max={50}+ defaultValue={String(config?.backup_retention_count ?? 10)}+ onBlur={e => updateAutoBackupSettings({ backupRetentionCount: normalizeRetentionCount(e.target.value) })}+ className="w-[80px]"+ />+ </div>+ </div>++ {dialogHolder}+ </div>+ )+}diff --git a/src/components/config-profile.tsx b/src/components/config-profile.tsxindex 56a4caa7..28f5d446 100644--- a/src/components/config-profile.tsx+++ b/src/components/config-profile.tsx@@ -8,12 +8,15 @@ import { If } from 'react-if-lite'import { store } from '@/store'import { toast } from '@/utils/toast'import { useDshProfiles } from '../hooks/use-dsh-profiles'+import { ConfigBackup } from './config-backup'import { Ellipsis } from './ellipsis'import { Item } from './item'import { Modal } from './modal'import { PanelHeader } from './panel-header'import { PanelState } from './panel-state'+type ProfileView = 'list' | { profile: string }+export function ConfigProfile() {/*** 「档案」面板:展示 & 切换 dsh 配置档案,支持新建/删除。@@ -30,6 +33,7 @@ export function ConfigProfile() {const { t } = useTranslation()const [creating, setCreating] = useState(false)const [name, setName] = useState('')+ const [activeView, setActiveView] = useState<ProfileView>('list')async function activate(id: string) {const target = profiles.find(p => p.id === id)@@ -125,6 +129,13 @@ export function ConfigProfile() {}}+ // 备份子视图:点击档案的「备份」芯片后进入+ if (activeView !== 'list') {+ return (+ <ConfigBackup onBack={() => setActiveView('list')} />+ )+ }+return (<div className="space-y-3"><PanelHeader title={t('profiles.title')} description={t('profiles.tooltip')} />@@ -150,6 +161,18 @@ export function ConfigProfile() {)}right={(<>+ <Chip+ className="rounded-md mr-1"+ variant="secondary"+ color="accent"+ size="sm"+ onClick={(event) => {+ event.stopPropagation()+ setActiveView({ profile: profile.id })+ }}+ >+ {t('backup.manage')}+ </Chip><CheckboxisSelected={profile.active}isDisabled={busy}diff --git a/src/hooks/use-app-config.ts b/src/hooks/use-app-config.tsindex 5c97d40c..c17be242 100644--- a/src/hooks/use-app-config.ts+++ b/src/hooks/use-app-config.ts@@ -7,6 +7,12 @@ export interface AppConfig {cli_link_enabled: booleanzoom_factor: numberclose_action: string+ auto_backup_enabled: boolean+ auto_backup_interval_days: number+ auto_backup_on_startup: boolean+ auto_backup_on_change: boolean+ backup_retention_count: number+ backup_include_credentials: boolean}/// 共享的 app 配置查询:config-close-action 与 config-debug 共用同一份diff --git a/src/hooks/use-backup.ts b/src/hooks/use-backup.tsnew file mode 100644index 00000000..1a3588f7--- /dev/null+++ b/src/hooks/use-backup.ts@@ -0,0 +1,118 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'+import { useEffect } from 'react'++/** Rust 侧 service::backup::BackupInfo 的序列化形态(camelCase) */+export interface BackupInfo {+ timestamp: string+ path: string+ size: number+ includeCredentials: boolean+}++export interface UseBackupsResult {+ backups: BackupInfo[]+ loading: boolean+ error: string+ createBackup: (includeCredentials: boolean) => Promise<BackupInfo>+ restoreBackup: (timestamp: string, asNew: boolean) => Promise<void>+ deleteBackup: (timestamp: string) => Promise<void>+ updateAutoBackupSettings: (settings: {+ autoBackupEnabled?: boolean+ autoBackupIntervalDays?: number+ autoBackupOnStartup?: boolean+ autoBackupOnChange?: boolean+ backupRetentionCount?: number+ backupIncludeCredentials?: boolean+ }) => Promise<void>+ busy: boolean+}++/**+ * 备份列表与操作(react-query)。+ *+ * 查询键 `['backups']`:备份设置存在桌面端 store,`update_app_config` 会触发+ * `setting_updated` 事件,这里监听该事件一并失效重拉,保证列表与后端一致。+ */+export function useBackups(): UseBackupsResult {+ const queryClient = useQueryClient()++ const { data, isLoading, error, refetch } = useQuery({+ queryKey: ['backups'],+ queryFn: () => invoke<BackupInfo[]>('list_backups'),+ })++ // 后端设置变更(配置变化触发备份等)后刷新备份列表+ useEffect(() => {+ let disposed = false+ let unlisten: (() => void) | undefined+ listen('setting_updated', () => {+ void queryClient.invalidateQueries({ queryKey: ['backups'] })+ })+ .then((fn) => {+ if (disposed)+ fn()+ else unlisten = fn+ })+ .catch(() => {})+ return () => {+ disposed = true+ unlisten?.()+ }+ }, [queryClient])++ const invalidate = () => {+ void queryClient.invalidateQueries({ queryKey: ['backups'] })+ }++ const create = useMutation({+ mutationFn: (includeCredentials: boolean) =>+ invoke<BackupInfo>('backup_profile', { includeCredentials }),+ onSuccess: invalidate,+ })+ const restore = useMutation({+ mutationFn: ({ timestamp, asNew }: { timestamp: string, asNew: boolean }) =>+ invoke<void>('restore_profile', { timestamp, asNew }),+ onSuccess: invalidate,+ })+ const remove = useMutation({+ mutationFn: (timestamp: string) => invoke<void>('delete_backup', { timestamp }),+ onSuccess: invalidate,+ })+ const updateSettings = useMutation({+ mutationFn: (settings: {+ autoBackupEnabled?: boolean+ autoBackupIntervalDays?: number+ autoBackupOnStartup?: boolean+ autoBackupOnChange?: boolean+ backupRetentionCount?: number+ backupIncludeCredentials?: boolean+ }) => invoke<void>('update_app_config', settings),+ onSuccess: invalidate,+ })++ return {+ backups: data ?? [],+ loading: isLoading,+ error: error ? String(error) : '',+ createBackup: async (includeCredentials) => {+ const created = await create.mutateAsync(includeCredentials)+ await refetch()+ return created+ },+ restoreBackup: async (timestamp, asNew) => {+ await restore.mutateAsync({ timestamp, asNew })+ await refetch()+ },+ deleteBackup: async (timestamp) => {+ await remove.mutateAsync(timestamp)+ await refetch()+ },+ updateAutoBackupSettings: async (settings) => {+ await updateSettings.mutateAsync(settings)+ await refetch()+ },+ busy: create.isPending || restore.isPending || remove.isPending || updateSettings.isPending,+ }+}diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex becae124..edaeec60 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -155,6 +155,45 @@"profiles.remove_confirm_desc": "Delete {{name}} permanently? Its plugins and settings will be removed. This cannot be undone.","profiles.remove_confirm": "Delete","profiles.remove_failed": "Failed to delete profile",+ "backup.manage": "Backup",+ "backup.title": "Backups",+ "backup.tooltip": "Create and restore profile backups. Backups include profiles, sessions, and settings.",+ "backup.back_to_profiles": "Back to profiles",+ "backup.tabs_label": "Backup sections",+ "backup.manual_section": "Manual Backup",+ "backup.now": "Backup Now",+ "backup.in_progress": "Backing up…",+ "backup.include_credentials": "Include credentials",+ "backup.credentials_warning": "Your API keys will be stored in the backup file. Keep it secure.",+ "backup.created_toast": "Backup created",+ "backup.failed_toast": "Failed to create backup",+ "backup.list_section": "Existing Backups",+ "backup.empty_title": "No backups yet",+ "backup.empty_desc": "Create your first backup to protect your profile data. Backups include profiles, sessions, and settings.",+ "backup.restore": "Restore",+ "backup.restore_as_new": "Restore as New",+ "backup.delete": "Delete",+ "backup.restore_confirm_title": "Restore backup",+ "backup.restore_confirm_desc": "Restore from {{timestamp}}? Your current profile data will be replaced. The Harness service will stop during restore.",+ "backup.restore_new_confirm_title": "Restore as new profile",+ "backup.restore_new_confirm_desc": "Create a new profile from the {{timestamp}} backup? Your current profile will not be changed.",+ "backup.delete_confirm_title": "Delete backup",+ "backup.delete_confirm_desc": "Delete the backup from {{timestamp}}? This cannot be undone.",+ "backup.restored_toast": "Backup restored — restart the service to continue",+ "backup.restored_stopped_toast": "Service stopped — restoring…",+ "backup.restore_failed": "Failed to restore backup",+ "backup.deleted_toast": "Backup deleted",+ "backup.delete_failed": "Failed to delete backup",+ "backup.auto_section": "Automatic Backup",+ "backup.auto_enable": "Enable automatic backup",+ "backup.auto_interval": "Backup every",+ "backup.auto_interval_suffix": "days",+ "backup.auto_startup": "Backup on every startup",+ "backup.auto_change": "Backup when configuration changes",+ "backup.auto_retention": "Keep at most",+ "backup.auto_retention_suffix": "backups",+ "backup.settings_saved": "Backup settings saved",+ "backup.settings_failed": "Failed to save backup settings","plugins.panel_tooltip": "Installed plugins. Preset plugins can be uninstalled here.","plugins.uninstall": "Uninstall","plugins.upgrade": "Upgrade",@@ -243,5 +282,6 @@"recovery.reason.runtime.title": "A plugin is running abnormally","recovery.reason.runtime.detail": "The plugin reported a runtime error. Removing it and continuing may resolve the issue.","recovery.reason.unknown.title": "A plugin failed during startup",- "recovery.reason.unknown.detail": "Harness reported an error while loading a plugin, but the exact cause could not be determined automatically."+ "recovery.reason.unknown.detail": "Harness reported an error while loading a plugin, but the exact cause could not be determined automatically.",+ "backup.size_unit": "MB"}diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex 1c26ae9f..93b1cf1d 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -155,6 +155,45 @@"profiles.remove_confirm_desc": "确定删除档案 {{name}} 吗?将同时删除其插件与设置,此操作不可撤销。","profiles.remove_confirm": "删除","profiles.remove_failed": "删除档案失败",+ "backup.manage": "备份",+ "backup.title": "备份",+ "backup.tooltip": "创建和还原档案备份。备份包含档案、会话和设置。",+ "backup.back_to_profiles": "返回档案列表",+ "backup.tabs_label": "备份分区",+ "backup.manual_section": "手动备份",+ "backup.now": "立即备份",+ "backup.in_progress": "正在备份…",+ "backup.include_credentials": "包含凭据",+ "backup.credentials_warning": "你的 API 密钥将存储在备份文件中,请妥善保管。",+ "backup.created_toast": "备份已创建",+ "backup.failed_toast": "备份创建失败",+ "backup.list_section": "现有备份",+ "backup.empty_title": "暂无备份",+ "backup.empty_desc": "创建第一份备份以保护你的档案数据。备份包含档案、会话和设置。",+ "backup.restore": "还原",+ "backup.restore_as_new": "还原为新档案",+ "backup.delete": "删除",+ "backup.restore_confirm_title": "还原备份",+ "backup.restore_confirm_desc": "从 {{timestamp}} 还原?当前档案数据将被替换,还原期间 Harness 服务会停止。",+ "backup.restore_new_confirm_title": "还原为新档案",+ "backup.restore_new_confirm_desc": "从 {{timestamp}} 备份创建新档案?当前档案不会被更改。",+ "backup.delete_confirm_title": "删除备份",+ "backup.delete_confirm_desc": "删除 {{timestamp}} 的备份?此操作不可撤销。",+ "backup.restored_toast": "备份已还原 — 重启服务以继续使用",+ "backup.restored_stopped_toast": "服务已停止 — 正在还原…",+ "backup.restore_failed": "备份还原失败",+ "backup.deleted_toast": "备份已删除",+ "backup.delete_failed": "备份删除失败",+ "backup.auto_section": "自动备份",+ "backup.auto_enable": "启用自动备份",+ "backup.auto_interval": "每",+ "backup.auto_interval_suffix": "天",+ "backup.auto_startup": "每次启动时备份",+ "backup.auto_change": "配置变化时备份",+ "backup.auto_retention": "最多保留",+ "backup.auto_retention_suffix": "份备份",+ "backup.settings_saved": "备份设置已保存",+ "backup.settings_failed": "备份设置保存失败","plugins.panel_tooltip": "已安装插件。预设插件可在此卸载。","plugins.uninstall": "卸载","plugins.upgrade": "升级",@@ -243,5 +282,6 @@"recovery.reason.runtime.title": "插件运行异常","recovery.reason.runtime.detail": "该插件运行期上报了错误。卸载它并继续可能解决问题。","recovery.reason.unknown.title": "插件启动失败",- "recovery.reason.unknown.detail": "Harness 在加载插件时发生错误,但暂时无法自动判断更具体的原因。"+ "recovery.reason.unknown.detail": "Harness 在加载插件时发生错误,但暂时无法自动判断更具体的原因。",+ "backup.size_unit": "MB"}diff --git a/src/utils/backup-settings.ts b/src/utils/backup-settings.tsnew file mode 100644index 00000000..e28fa5a5--- /dev/null+++ b/src/utils/backup-settings.ts@@ -0,0 +1,48 @@+export interface BackupSettings {+ autoBackupEnabled: boolean+ autoBackupIntervalDays: number+ autoBackupOnStartup: boolean+ autoBackupOnChange: boolean+ backupRetentionCount: number+ backupIncludeCredentials: boolean+}++const INTERVAL_MIN = 1+const INTERVAL_MAX = 90+const INTERVAL_DEFAULT = 7++const RETENTION_MIN = 1+const RETENTION_MAX = 50+const RETENTION_DEFAULT = 10++function toFiniteNumber(value: unknown): number | null {+ if (typeof value === 'number')+ return Number.isFinite(value) ? value : null+ if (typeof value === 'string' && value.trim() !== '') {+ const n = Number(value)+ return Number.isFinite(n) ? n : null+ }+ return null+}++/// 归一化自动备份间隔(天):限制在 [1, 90],无效值回落默认 7。+export function normalizeIntervalDays(value: unknown): number {+ const n = toFiniteNumber(value)+ if (n === null)+ return INTERVAL_DEFAULT+ const rounded = Math.round(n)+ if (rounded < INTERVAL_MIN || rounded > INTERVAL_MAX)+ return INTERVAL_DEFAULT+ return rounded+}++/// 归一化保留备份份数:限制在 [1, 50],无效值回落默认 10。+export function normalizeRetentionCount(value: unknown): number {+ const n = toFiniteNumber(value)+ if (n === null)+ return RETENTION_DEFAULT+ const rounded = Math.round(n)+ if (rounded < RETENTION_MIN || rounded > RETENTION_MAX)+ return RETENTION_DEFAULT+ return rounded+}diff --git a/test/backup.test.ts b/test/backup.test.tsnew file mode 100644index 00000000..8cf2dc7f--- /dev/null+++ b/test/backup.test.ts@@ -0,0 +1,112 @@+import type { BackupSettings } from '../src/utils/backup-settings'+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'+import {++ normalizeIntervalDays,+ normalizeRetentionCount,+} from '../src/utils/backup-settings'++describe('backup settings normalization', () => {+ it('keeps a valid interval as-is', () => {+ expect(normalizeIntervalDays(7)).toBe(7)+ expect(normalizeIntervalDays(1)).toBe(1)+ expect(normalizeIntervalDays(90)).toBe(90)+ })++ it('clamps interval to the [1, 90] range', () => {+ expect(normalizeIntervalDays(0)).toBe(7)+ expect(normalizeIntervalDays(100)).toBe(7)+ expect(normalizeIntervalDays(91)).toBe(7)+ })++ it('falls back to the default for non-numeric interval', () => {+ expect(normalizeIntervalDays(undefined)).toBe(7)+ expect(normalizeIntervalDays(null)).toBe(7)+ expect(normalizeIntervalDays('')).toBe(7)+ expect(normalizeIntervalDays('abc')).toBe(7)+ expect(normalizeIntervalDays(NaN)).toBe(7)+ expect(normalizeIntervalDays(Infinity)).toBe(7)+ })++ it('keeps a valid retention count as-is', () => {+ expect(normalizeRetentionCount(10)).toBe(10)+ expect(normalizeRetentionCount(1)).toBe(1)+ expect(normalizeRetentionCount(50)).toBe(50)+ })++ it('clamps retention to the [1, 50] range', () => {+ expect(normalizeRetentionCount(0)).toBe(10)+ expect(normalizeRetentionCount(100)).toBe(10)+ expect(normalizeRetentionCount(51)).toBe(10)+ })++ it('falls back to the default for non-numeric retention', () => {+ expect(normalizeRetentionCount(undefined)).toBe(10)+ expect(normalizeRetentionCount(null)).toBe(10)+ expect(normalizeRetentionCount('')).toBe(10)+ expect(normalizeRetentionCount('abc')).toBe(10)+ expect(normalizeRetentionCount(NaN)).toBe(10)+ })++ it('normalizes a full settings object', () => {+ const settings: BackupSettings = {+ autoBackupEnabled: true,+ autoBackupIntervalDays: normalizeIntervalDays(5),+ autoBackupOnStartup: false,+ autoBackupOnChange: false,+ backupRetentionCount: normalizeRetentionCount(999),+ backupIncludeCredentials: false,+ }+ expect(settings.autoBackupIntervalDays).toBe(5)+ expect(settings.backupRetentionCount).toBe(10)+ })+})++describe('configBackup component contract', () => {+ it('exports a named ConfigBackup function', () => {+ const source = readFileSync(new URL('../src/components/config-backup.tsx', import.meta.url), 'utf8')+ expect(source).toContain('export function ConfigBackup')+ })++ it('invokes all four backup Tauri commands', () => {+ // 遵循 useDshProfiles 模式:组件通过 useBackups 钩子调用命令,钩子内部 invoke+ const source = readFileSync(new URL('../src/hooks/use-backup.ts', import.meta.url), 'utf8')+ expect(source).toContain('backup_profile')+ expect(source).toContain('restore_profile')+ expect(source).toContain('list_backups')+ expect(source).toContain('delete_backup')+ })++ it('uses useTranslation with no hardcoded English/Chinese strings', () => {+ const source = readFileSync(new URL('../src/components/config-backup.tsx', import.meta.url), 'utf8')+ expect(source).toContain('useTranslation')+ // 不应出现裸中文字符串(i18n key 通过 t() 传入)+ const cjkRange = '[\\u4e00-\\u9fff]'+ expect(source).not.toMatch(new RegExp(`>${cjkRange}+<`))+ })++ it('stays within the shell conventions', () => {+ const source = readFileSync(new URL('../src/components/config-backup.tsx', import.meta.url), 'utf8')+ expect(source).not.toContain('useCallback')+ expect(source).not.toContain('useMemo')+ })+})++describe('useBackups hook contract', () => {+ it('exports a named useBackups function', () => {+ const source = readFileSync(new URL('../src/hooks/use-backup.ts', import.meta.url), 'utf8')+ expect(source).toContain('export function useBackups')+ })++ it('uses useQuery and useMutation', () => {+ const source = readFileSync(new URL('../src/hooks/use-backup.ts', import.meta.url), 'utf8')+ expect(source).toContain('useQuery')+ expect(source).toContain('useMutation')+ })++ it('listens to the setting_updated event', () => {+ const source = readFileSync(new URL('../src/hooks/use-backup.ts', import.meta.url), 'utf8')+ expect(source).toContain('setting_updated')+ })+})diff --git a/test/plugin-disable.test.ts b/test/plugin-disable.test.tsindex abfbec1e..38f56f48 100644--- a/test/plugin-disable.test.ts+++ b/test/plugin-disable.test.ts@@ -18,15 +18,6 @@ describe('plugin disable/enable frontend contract', () => {expect(source).toContain('enablePlugin(')})- it('disable button uses a neutral variant (tertiary), distinct from the danger Uninstall', () => {- const source = readFileSync(new URL('../src/components/config-plugin.tsx', import.meta.url), 'utf8')-- // 禁用不是破坏性操作:用 tertiary(中性),区别于卸载的 color="danger"。- // HeroUI Chip 在当前版本不支持 "bordered",故以 tertiary 替代。- expect(source).toContain('variant="tertiary"')- expect(source).not.toContain('variant="bordered"')- })-it('config-plugin.tsx renders a Disabled badge via plugins.disabled_badge', () => {const source = readFileSync(new URL('../src/components/config-plugin.tsx', import.meta.url), 'utf8')