Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat(backup): 将会话和档案导出到 DSH_HOME 外 (#852)

SkanderBot46f7fbeea1e0
diff --git a/src-tauri/src/bridge/backup.rs b/src-tauri/src/bridge/backup.rs
index 5a0cb3dd..5d917e69 100644
--- a/src-tauri/src/bridge/backup.rs
+++ b/src-tauri/src/bridge/backup.rs
@@ -8,7 +8,26 @@ use tauri::AppHandle;
use crate::service::backup;
-/// 创建备份(`$DSH_HOME` → `$DSH_HOME/.backups/<timestamp>.tar.zst`)。
+#[tauri::command]
+pub async fn export_recovery_backup(
+ app_handle: AppHandle,
+ include_credentials: bool,
+) -> Result<backup::BackupInfo, String> {
+ let transition = crate::service::workflow::acquire_core_transition().await?;
+ let operation = crate::service::plugin::acquire_operation_lock().await;
+ crate::service::workflow::stop(app_handle.clone()).await?;
+ let source = crate::config::get_dsh_data_path(&app_handle);
+ let app_data = crate::config::get_base_dir(&app_handle);
+ tauri::async_runtime::spawn_blocking(move || {
+ let _transition = transition;
+ let _operation = operation;
+ backup::recovery::export(&source, &app_data, include_credentials)
+ })
+ .await
+ .map_err(|e| format!("RECOVERY_TASK: {e}"))?
+}
+
+/// 创建当前 profile 的备份(不包含共享会话与工作区数据)。
///
/// 异步命令:zstd 多线程压缩 + 目录遍历在 `spawn_blocking` 线程池执行。
#[tauri::command]
@@ -34,7 +53,7 @@ pub async fn backup_profile(
/// 从指定备份还原。
///
-/// `as_new` = true 时创建新档案目录;false 时覆盖当前 `$DSH_HOME`。
+/// `as_new` = true 时创建新档案目录;false 时覆盖当前激活的 profile。
/// 异步命令:zstd 解压在 `spawn_blocking` 线程池执行。
#[tauri::command]
pub async fn restore_profile(
diff --git a/src-tauri/src/bridge/guard.rs b/src-tauri/src/bridge/guard.rs
index 02fb7a55..8a674a5b 100644
--- a/src-tauri/src/bridge/guard.rs
+++ b/src-tauri/src/bridge/guard.rs
@@ -25,6 +25,8 @@ pub fn allowed_roots(app_handle: &AppHandle) -> Vec<PathBuf> {
}
let dsh_home = crate::config::get_dsh_data_path(app_handle);
roots.push(dsh_home);
+ // 自定义缓存根下的恢复导出也允许定位,不扩大到该根下的其他文件。
+ roots.push(crate::config::get_base_dir(app_handle).join("recovery-backups"));
// 本地核心(用户通过 CLI 安装)的包目录:由后端检测得到的可信路径,
// 允许「核心」面板的「打开目录」打开它(否则会因不在任何允许根内被拒)。
if let Some(dir) = crate::service::core::local_core_package_dir(app_handle) {
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 52ca8f1c..603e6e8f 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -1280,6 +1280,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::reset_profile,
crate::bridge::clone_profile,
crate::bridge::backup_profile,
+ crate::bridge::export_recovery_backup,
crate::bridge::restore_profile,
crate::bridge::list_backups,
crate::bridge::delete_backup,
diff --git a/src-tauri/src/service/backup/archive.rs b/src-tauri/src/service/backup/archive.rs
index 73e32eda..3893219a 100644
--- a/src-tauri/src/service/backup/archive.rs
+++ b/src-tauri/src/service/backup/archive.rs
@@ -64,6 +64,7 @@ fn append_dir_filtered(
source: &Path,
rel: &Path,
include_credentials: bool,
+ reject_links: 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}"))?;
@@ -82,11 +83,19 @@ fn append_dir_filtered(
let ty = entry
.file_type()
.map_err(|e| format!("BACKUP_ARCHIVE_TYPE: {e}"))?;
+ #[cfg(windows)]
+ if reject_links {
+ use std::os::windows::fs::MetadataExt;
+ let meta = fs::symlink_metadata(&path).map_err(|e| format!("BACKUP_ARCHIVE_TYPE: {e}"))?;
+ if meta.file_attributes() & 0x400 != 0 {
+ return Err(format!("RECOVERY_LINK_UNSUPPORTED: {}", path.display()));
+ }
+ }
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)?;
+ append_dir_filtered(builder, &path, source, &archived, include_credentials, reject_links)?;
} else if ty.is_file() {
builder
.append_file(
@@ -95,6 +104,9 @@ fn append_dir_filtered(
)
.map_err(|e| format!("BACKUP_ARCHIVE_APPEND_FILE: {e}"))?;
} else if ty.is_symlink() {
+ if reject_links {
+ return Err(format!("RECOVERY_LINK_UNSUPPORTED: {}", path.display()));
+ }
// 符号链接:读取 target,tar Symlink 存储(GNU header 限制 100 字节)
let target =
std::fs::read_link(&path).map_err(|e| format!("BACKUP_ARCHIVE_READLINK: {e}"))?;
@@ -130,11 +142,19 @@ fn append_dir_filtered(
/// `node_modules/`。使用 zstd 多线程压缩(级别 0 = 默认 3,
/// 启用 multithread 加速)。
pub fn create_archive(source: &Path, dest: &Path, include_credentials: bool) -> Result<(), String> {
+ create_archive_impl(source, dest, include_credentials, false)
+}
+
+pub(super) fn create_recovery_archive(source: &Path, dest: &Path, include_credentials: bool) -> Result<(), String> {
+ create_archive_impl(source, dest, include_credentials, true)
+}
+
+fn create_archive_impl(source: &Path, dest: &Path, include_credentials: bool, reject_links: 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)
+ .map(|n| if reject_links { n.get().min(2) } else { n.get() } as u32)
.unwrap_or(1);
let mut enc =
zstd::stream::Encoder::new(file, 0).map_err(|e| format!("BACKUP_ARCHIVE_ENCODER: {e}"))?;
@@ -147,6 +167,7 @@ pub fn create_archive(source: &Path, dest: &Path, include_credentials: bool) ->
source,
Path::new("."),
include_credentials,
+ reject_links,
)?;
archive
.finish()
diff --git a/src-tauri/src/service/backup/mod.rs b/src-tauri/src/service/backup/mod.rs
index 85e01229..694e7861 100644
--- a/src-tauri/src/service/backup/mod.rs
+++ b/src-tauri/src/service/backup/mod.rs
@@ -1,9 +1,10 @@
//! 档案备份与还原。
//!
-//! 把 `$DSH_HOME` 打包为版本化的 `.tar.zst` 快照,存放在 `$DSH_HOME/.backups/`,
-//! 支持手动创建 / 还原(覆盖或新建)/ 列表 / 删除,以及自动备份调度与保留份数裁剪。
+//! 档案备份仅打包当前 profile,存放在 `$DSH_HOME/.backups/`,支持还原与保留份数裁剪。
+//! [`recovery`] 另行导出含会话的完整数据到应用数据目录,不参与档案还原或裁剪。
pub mod archive;
+pub mod recovery;
pub mod retention;
use std::fs;
@@ -36,7 +37,7 @@ pub struct BackupInfo {
/// 还原模式。
#[derive(Debug, Clone, Copy)]
pub enum RestoreMode {
- /// 覆盖当前 `$DSH_HOME`。
+ /// 覆盖当前激活的 profile。
Overwrite,
/// 创建新档案目录并解压到其中。
AsNew,
@@ -495,4 +496,3 @@ mod tests {
let _ = fs::remove_dir_all(&dest);
}
}
-
diff --git a/src-tauri/src/service/backup/recovery.rs b/src-tauri/src/service/backup/recovery.rs
new file mode 100644
index 00000000..7685eefa
--- /dev/null
+++ b/src-tauri/src/service/backup/recovery.rs
@@ -0,0 +1,275 @@
+//! issue #848:独立于 DSH_HOME 的恢复导出,包含会话与共享存储,不参与档案还原或自动裁剪。
+
+use std::fs;
+use std::path::{Path, PathBuf};
+
+use super::{archive, BackupInfo};
+
+const RECOVERY_README: &str = "DSH recovery export\n\n\
+data.tar.zst contains DSH_HOME data, including sessions, storages and all profiles.\n\
+Excluded: node_modules, .backups, .plugin-backups and .harness.pid.\n\
+.credentials.yaml is included only when requested. Other files are not redacted\n\
+and may contain secrets. Keep this directory private.\n\n\
+Recovery: stop every desktop, CLI and web client using this DSH_HOME.\n\
+Extract data.tar.zst into a NEW EMPTY directory with a tar.zst-capable tool.\n\
+Inspect the extracted sessions, storages and profiles before copying anything.\n\
+Keep a separate copy of your current DSH_HOME before replacing any files.\n\
+Reinstall profile dependencies using the matching DSH core version.\n\
+Do not use the desktop's profile Restore button for this archive.\n\n\
+This is a manual export, not an automatic backup. It is not automatically pruned.\n\
+Copy it to another device to protect against disk failure.\n";
+
+pub fn export(source: &Path, app_data: &Path, include_credentials: bool) -> Result<BackupInfo, String> {
+ let source = dunce::canonicalize(source).map_err(|e| format!("RECOVERY_SOURCE: {e}"))?;
+ if !source.is_dir() {
+ return Err("RECOVERY_SOURCE: DSH_HOME is not a directory".into());
+ }
+ let app_data = dunce::canonicalize(app_data).map_err(|e| format!("RECOVERY_DESTINATION: {e}"))?;
+ if app_data.starts_with(&source) {
+ return Err("RECOVERY_DESTINATION_INSIDE_SOURCE: application data is inside DSH_HOME".into());
+ }
+ let root = app_data.join("recovery-backups");
+ create_private_dir(&root).or_else(|e| {
+ if e.kind() == std::io::ErrorKind::AlreadyExists { Ok(()) } else { Err(e) }
+ }).map_err(|e| format!("RECOVERY_MKDIR: {e}"))?;
+ let root = dunce::canonicalize(root).map_err(|e| format!("RECOVERY_DESTINATION: {e}"))?;
+ if root.starts_with(&source) || !root.starts_with(&app_data) {
+ return Err("RECOVERY_DESTINATION_UNSAFE: recovery directory resolves outside application data or inside DSH_HOME".into());
+ }
+
+ let timestamp = super::now_timestamp();
+ let directory = reserve_directory(&root, &timestamp)?;
+ let partial = directory.join("data.tar.zst.partial");
+ let path = directory.join("data.tar.zst");
+ let result = (|| {
+ archive::create_recovery_archive(&source, &partial, include_credentials)?;
+ fs::OpenOptions::new().write(true).open(&partial).and_then(|file| file.sync_all())
+ .map_err(|e| format!("RECOVERY_SYNC: {e}"))?;
+ let readme = directory.join("README.txt");
+ fs::write(&readme, RECOVERY_README)
+ .map_err(|e| format!("RECOVERY_README: {e}"))?;
+ fs::OpenOptions::new().write(true).open(&readme).and_then(|file| file.sync_all())
+ .map_err(|e| format!("RECOVERY_SYNC_README: {e}"))?;
+ let size = fs::metadata(&partial).map_err(|e| format!("RECOVERY_METADATA: {e}"))?.len();
+ fs::rename(&partial, &path).map_err(|e| format!("RECOVERY_PUBLISH: {e}"))?;
+ // Unix 还需同步目录项,避免断电后已返回的归档路径或新建目录丢失。
+ #[cfg(unix)]
+ for parent in [&directory, &root, &app_data] {
+ fs::File::open(parent).and_then(|file| file.sync_all())
+ .map_err(|e| format!("RECOVERY_SYNC_DIRECTORY: {e}"))?;
+ }
+ Ok(BackupInfo {
+ timestamp,
+ path: path.to_string_lossy().into_owned(),
+ size,
+ include_credentials,
+ })
+ })();
+ if result.is_err() {
+ // 只删除本次 create_dir 独占创建的导出目录,不触碰既有备份或源数据。
+ if let Err(e) = fs::remove_dir_all(&directory) {
+ log::warn!("RECOVERY_CLEANUP: {}: {e}", directory.display());
+ }
+ }
+ result
+}
+
+fn create_private_dir(path: &Path) -> std::io::Result<()> {
+ let mut builder = fs::DirBuilder::new();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::DirBuilderExt;
+ builder.mode(0o700);
+ }
+ builder.create(path)
+}
+
+fn reserve_directory(root: &Path, timestamp: &str) -> Result<PathBuf, String> {
+ for suffix in 0..1000 {
+ let directory = root.join(format!("{timestamp}-{suffix}"));
+ match create_private_dir(&directory) {
+ Ok(()) => return Ok(directory),
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
+ Err(e) => return Err(format!("RECOVERY_MKDIR: {e}")),
+ }
+ }
+ Err("RECOVERY_COLLISION: too many exports in the same second".into())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct Fixture {
+ root: PathBuf,
+ home: PathBuf,
+ app: PathBuf,
+ }
+
+ impl Fixture {
+ fn new() -> Self {
+ let root = std::env::temp_dir().join(format!(
+ "dsh-recovery-{}-{}",
+ std::process::id(),
+ super::super::timestamp_nanos()
+ ));
+ fs::create_dir(&root).unwrap();
+ let fixture = Self { home: root.join("dsh-home"), app: root.join("app-data"), root };
+ fs::create_dir(&fixture.app).unwrap();
+ for (name, value) in [
+ ("sessions/project/session/session.v4.jsonl.zstd", "saved conversation"),
+ ("storages/workspace.json", "workspace data"),
+ ("profiles/web/cordis.patch.yml", "user patch"),
+ ("profiles/other/package.json", "other profile"),
+ ("dsh-config-manager/snapshots/saved.json", "plugin data"),
+ (".credentials.yaml", "secret"),
+ ("profiles/web/.credentials.yaml", "profile secret"),
+ ("profiles/web/node_modules/plugin/index.js", "dependency"),
+ (".backups/old.tar.zst", "existing backup"),
+ (".plugin-backups/plugin.tgz", "existing snapshot"),
+ (".harness.pid", "123"),
+ ] {
+ let path = fixture.home.join(name);
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(path, value).unwrap();
+ }
+ fixture
+ }
+
+ fn restore(&self, info: &BackupInfo, name: &str) -> PathBuf {
+ let target = self.root.join(name);
+ archive::extract_archive(Path::new(&info.path), &target).unwrap();
+ target
+ }
+ }
+
+ impl Drop for Fixture {
+ fn drop(&mut self) {
+ fs::remove_dir_all(&self.root).unwrap();
+ }
+ }
+
+ #[test]
+ fn export_preserves_sessions_shared_storage_and_every_profile_after_source_loss() {
+ let fixture = Fixture::new();
+ let info = export(&fixture.home, &fixture.app, false).unwrap();
+ assert!(Path::new(&info.path).starts_with(dunce::canonicalize(&fixture.app).unwrap().join("recovery-backups")));
+ assert!(info.size > 0);
+ assert!(!info.include_credentials);
+ assert_eq!(fs::read_to_string(fixture.home.join(".credentials.yaml")).unwrap(), "secret");
+ fs::remove_dir_all(&fixture.home).unwrap();
+ let restored = fixture.restore(&info, "recovered");
+ for (name, expected) in [
+ ("sessions/project/session/session.v4.jsonl.zstd", "saved conversation"),
+ ("storages/workspace.json", "workspace data"),
+ ("profiles/web/cordis.patch.yml", "user patch"),
+ ("profiles/other/package.json", "other profile"),
+ ("dsh-config-manager/snapshots/saved.json", "plugin data"),
+ ] {
+ assert_eq!(fs::read_to_string(restored.join(name)).unwrap(), expected);
+ }
+ for excluded in [".credentials.yaml", "profiles/web/.credentials.yaml", "profiles/web/node_modules", ".backups", ".plugin-backups", ".harness.pid"] {
+ assert!(!restored.join(excluded).exists(), "should exclude {excluded}");
+ }
+ let directory = Path::new(&info.path).parent().unwrap();
+ assert!(fs::read_to_string(directory.join("README.txt")).unwrap().contains("NEW EMPTY directory"));
+ assert!(!directory.join("data.tar.zst.partial").exists());
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(fs::metadata(directory).unwrap().permissions().mode() & 0o777, 0o700);
+ }
+ }
+
+ #[test]
+ fn export_includes_credentials_only_when_requested_and_keeps_previous_exports() {
+ let fixture = Fixture::new();
+ let first = export(&fixture.home, &fixture.app, false).unwrap();
+ let bytes = fs::read(&first.path).unwrap();
+ let second = export(&fixture.home, &fixture.app, true).unwrap();
+ assert_ne!(first.path, second.path);
+ assert_eq!(fs::read(&first.path).unwrap(), bytes);
+ let restored = fixture.restore(&second, "with-credentials");
+ assert!(second.include_credentials);
+ assert_eq!(fs::read_to_string(restored.join(".credentials.yaml")).unwrap(), "secret");
+ assert_eq!(fs::read_to_string(restored.join("profiles/web/.credentials.yaml")).unwrap(), "profile secret");
+ }
+
+ #[test]
+ fn export_rejects_missing_source_without_creating_an_empty_backup() {
+ let fixture = Fixture::new();
+ let error = export(&fixture.root.join("missing"), &fixture.app, false).unwrap_err();
+ assert!(error.starts_with("RECOVERY_SOURCE:"), "{error}");
+ assert!(!fixture.app.join("recovery-backups").exists());
+ }
+
+ #[test]
+ fn export_rejects_app_data_inside_source_before_writing() {
+ let fixture = Fixture::new();
+ let nested = fixture.home.join("app-data");
+ fs::create_dir(&nested).unwrap();
+ for target in [&fixture.home, &nested] {
+ let error = export(&fixture.home, target, false).unwrap_err();
+ assert!(error.starts_with("RECOVERY_DESTINATION_INSIDE_SOURCE:"), "{error}");
+ assert!(!target.join("recovery-backups").exists());
+ }
+ }
+
+ #[test]
+ fn reserve_directory_preserves_existing_files_and_directories() {
+ let fixture = Fixture::new();
+ fs::write(fixture.app.join("stamp-0"), "keep file").unwrap();
+ fs::create_dir(fixture.app.join("stamp-1")).unwrap();
+ let path = reserve_directory(&fixture.app, "stamp").unwrap();
+ assert_eq!(path, fixture.app.join("stamp-2"));
+ assert_eq!(fs::read_to_string(fixture.app.join("stamp-0")).unwrap(), "keep file");
+ assert!(fixture.app.join("stamp-1").is_dir());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn export_rejects_destination_symlinks_into_source_or_outside_app_data() {
+ let fixture = Fixture::new();
+ let link = fixture.app.join("recovery-backups");
+ for target in [&fixture.home, &fixture.root] {
+ std::os::unix::fs::symlink(target, &link).unwrap();
+ let error = export(&fixture.home, &fixture.app, false).unwrap_err();
+ assert!(error.starts_with("RECOVERY_DESTINATION_UNSAFE:"), "{error}");
+ assert_eq!(fs::read_to_string(fixture.home.join(".credentials.yaml")).unwrap(), "secret");
+ fs::remove_file(&link).unwrap();
+ }
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn failed_export_removes_only_its_partial_output_and_preserves_previous_backup() {
+ let fixture = Fixture::new();
+ let saved = export(&fixture.home, &fixture.app, false).unwrap();
+ let bytes = fs::read(&saved.path).unwrap();
+ std::os::unix::fs::symlink("missing", fixture.home.join("linked-data")).unwrap();
+ let error = export(&fixture.home, &fixture.app, false).unwrap_err();
+ assert!(error.starts_with("RECOVERY_LINK_UNSUPPORTED:"), "{error}");
+ assert_eq!(fs::read(&saved.path).unwrap(), bytes);
+ assert_eq!(fs::read_dir(fixture.app.join("recovery-backups")).unwrap().count(), 1);
+ assert_eq!(fs::read_to_string(fixture.home.join(".credentials.yaml")).unwrap(), "secret");
+ assert!(fs::symlink_metadata(fixture.home.join("linked-data")).unwrap().file_type().is_symlink());
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn export_rejects_junctions_without_traversing_them() {
+ use std::os::windows::process::CommandExt;
+ let fixture = Fixture::new();
+ let link = fixture.home.join("linked-data");
+ let status = std::process::Command::new("cmd")
+ .args(["/C", "mklink", "/J"])
+ .arg(&link).arg(&fixture.app)
+ .creation_flags(0x08000000)
+ .status().unwrap();
+ assert!(status.success());
+ let error = export(&fixture.home, &fixture.app, false).unwrap_err();
+ assert!(error.starts_with("RECOVERY_LINK_UNSUPPORTED:"), "{error}");
+ assert_eq!(fs::read_dir(fixture.app.join("recovery-backups")).unwrap().count(), 0);
+ fs::remove_dir(link).unwrap();
+ }
+}
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index 2ed19e70..2c170a11 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -53,6 +53,7 @@ pub mod watch;
pub(crate) use crate::service::profile::ensure_profile_pnpm_policy;
pub use cancel::cancel;
pub(crate) use cancel::terminate_active_installs_blocking;
+pub(crate) use process::acquire_operation_lock;
pub(crate) use install::harness_prefer_bundled_pnpm;
pub(crate) use install::uninstall_deprecated_plugins;
pub use install::{
diff --git a/src/hooks/use-backup.ts b/src/hooks/use-backup.ts
index 917b71bf..d6f2a9ad 100644
--- a/src/hooks/use-backup.ts
+++ b/src/hooks/use-backup.ts
@@ -26,6 +26,9 @@ export interface UseBackupsResult {
restoring: boolean
/** 仅删除进行中 */
deleting: boolean
+ exporting: boolean
+ recoveryBackup: BackupInfo | undefined
+ exportRecoveryBackup: (includeCredentials: boolean) => Promise<BackupInfo>
}
/**
@@ -63,6 +66,10 @@ export function useBackups(): UseBackupsResult {
mutationFn: (timestamp: string) => invoke<void>('delete_backup', { timestamp }),
onSuccess: invalidate,
})
+ const recovery = useMutation({
+ mutationFn: (includeCredentials: boolean) =>
+ invoke<BackupInfo>('export_recovery_backup', { includeCredentials }),
+ })
return {
backups: data ?? [],
loading: isLoading,
@@ -80,9 +87,12 @@ export function useBackups(): UseBackupsResult {
await remove.mutateAsync(timestamp)
await refetch()
},
- busy: create.isPending || restore.isPending || remove.isPending,
+ busy: create.isPending || restore.isPending || remove.isPending || recovery.isPending,
creating: create.isPending,
restoring: restore.isPending,
deleting: remove.isPending,
+ exporting: recovery.isPending,
+ recoveryBackup: recovery.data,
+ exportRecoveryBackup: recovery.mutateAsync,
}
}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 8331788d..cfa5a186 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -250,7 +250,7 @@
"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.empty_desc": "Create a profile backup to protect the active profile configuration. Profile backups do not include conversations; use a recovery export below for conversations and shared data.",
"backup.restore": "Restore",
"backup.restore_as_new": "Restore as New",
"backup.delete": "Delete",
@@ -441,6 +441,15 @@
"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.",
+ "backup.profile_scope": "Profile backups include only the active profile configuration. They do not include conversations or shared workspace data and are stored inside DSH_HOME.",
+ "backup.recovery_section": "Recovery export (including conversations)",
+ "backup.recovery_desc": "Manually export sessions, shared storage and all profiles outside DSH_HOME, under the desktop application data folder. Dependencies and existing backup archives are excluded. Linked files or folders cause the export to fail rather than silently omit their data. Exports are not automatically deleted. Other configuration files may contain secrets even when credentials are excluded.",
+ "backup.export_recovery": "Export recovery archive",
+ "backup.exporting_recovery": "Exporting recovery archive…",
+ "backup.recovery_confirm_title": "Stop the service and export data?",
+ "backup.recovery_confirm_desc": "Finish active work and close other DSH desktop, CLI and web clients first. This desktop’s service will stop and remain stopped after the export. The export includes all profiles and conversations. To recover, extract it into an empty directory and follow README.txt; the profile Restore buttons cannot restore this archive.",
+ "backup.recovery_created": "Recovery archive saved. The service remains stopped; restart it when ready.",
+ "backup.reveal_recovery": "Show recovery archive in folder",
"backup.size_unit": "MB",
"remote.switcher": "Remote machines",
"remote.local": "Local",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 151724a5..5db8ca63 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -250,7 +250,7 @@
"backup.failed_toast": "备份创建失败",
"backup.list_section": "现有备份",
"backup.empty_title": "暂无备份",
- "backup.empty_desc": "创建第一份备份以保护你的档案数据。备份包含档案、会话和设置。",
+ "backup.empty_desc": "创建档案备份以保护当前档案配置。档案备份不包含会话;如需保护会话和共享数据,请使用下方的恢复导出。",
"backup.restore": "还原",
"backup.restore_as_new": "还原为新档案",
"backup.delete": "删除",
@@ -441,6 +441,15 @@
"recovery.reason.runtime.detail": "该插件运行期上报了错误。卸载它并继续可能解决问题。",
"recovery.reason.unknown.title": "插件启动失败",
"recovery.reason.unknown.detail": "Harness 在加载插件时发生错误,但暂时无法自动判断更具体的原因。",
+ "backup.profile_scope": "档案备份仅包含当前档案的配置,不包含会话或共享工作区数据,并存放在 DSH_HOME 内。",
+ "backup.recovery_section": "恢复导出(包含会话)",
+ "backup.recovery_desc": "手动将会话、共享存储及所有档案导出到 DSH_HOME 之外的桌面应用数据目录。依赖和已有备份归档不包含在内。遇到链接文件或目录时会报错,避免静默遗漏其数据。导出不会自动删除。即使不勾选凭据,其他配置文件也可能包含密钥。",
+ "backup.export_recovery": "导出恢复归档",
+ "backup.exporting_recovery": "正在导出恢复归档…",
+ "backup.recovery_confirm_title": "停止服务并导出数据?",
+ "backup.recovery_confirm_desc": "请先完成正在进行的任务,并关闭其他 DSH 桌面端、CLI 和网页客户端。本桌面端服务将停止,导出后保持停止状态。归档包含所有档案及会话。恢复时请解压到空目录并按照 README.txt 操作;档案的还原按钮不适用于此归档。",
+ "backup.recovery_created": "恢复归档已保存。服务保持停止状态,可在准备就绪后重启。",
+ "backup.reveal_recovery": "在文件夹中显示恢复归档",
"backup.size_unit": "MB",
"remote.switcher": "远端机器",
"remote.local": "本地",
diff --git a/src/ui/config/backup.test.tsx b/src/ui/config/backup.test.tsx
new file mode 100644
index 00000000..deafc0d4
--- /dev/null
+++ b/src/ui/config/backup.test.tsx
@@ -0,0 +1,115 @@
+// @vitest-environment jsdom
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import en from '@/i18n/locales/en-US.json'
+import zh from '@/i18n/locales/zh-CN.json'
+import { ConfigBackup } from './backup'
+
+const mocks = vi.hoisted(() => ({ invoke: vi.fn(), dialog: vi.fn(), toast: vi.fn() }))
+vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }))
+vi.mock('@overlastic/react', () => ({ useOverlay: () => [null, mocks.dialog] }))
+vi.mock('@/store', () => ({ store: { harness: { restart: vi.fn() } } }))
+vi.mock('@/utils/toast', () => ({ toast: mocks.toast }))
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))
+
+let client: QueryClient
+const exported = { timestamp: '20261002123000', path: '/scratch/recovery/data.tar.zst', size: 1234, includeCredentials: false }
+
+beforeEach(() => {
+ mocks.invoke.mockReset().mockImplementation(async (command: string) => {
+ if (command === 'list_backups')
+ return []
+ if (command === 'export_recovery_backup')
+ return exported
+ throw new Error(`Unexpected command: ${command}`)
+ })
+ mocks.dialog.mockReset().mockResolvedValue(undefined)
+ mocks.toast.mockReset()
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } } })
+})
+
+afterEach(() => {
+ cleanup()
+ client.clear()
+ vi.restoreAllMocks()
+})
+
+async function mount() {
+ render(<QueryClientProvider client={client}><ConfigBackup onBack={() => {}} /></QueryClientProvider>)
+ await screen.findByText('backup.empty_title')
+}
+
+describe('backup recovery controls', () => {
+ it('describes profile backups without claiming that they include conversations', () => {
+ expect(en['backup.empty_desc']).toContain('do not include conversations')
+ expect(zh['backup.empty_desc']).toContain('不包含会话')
+ })
+
+ it('does not export when the stop-service confirmation is cancelled', async () => {
+ mocks.dialog.mockRejectedValue(new Error('cancelled'))
+ await mount()
+ fireEvent.click(screen.getByRole('button', { name: 'backup.export_recovery' }))
+ await waitFor(() => expect(mocks.dialog).toHaveBeenCalledTimes(1))
+ expect(mocks.invoke).not.toHaveBeenCalledWith('export_recovery_backup', expect.anything())
+ })
+
+ it('exports only after confirmation and displays the saved archive path', async () => {
+ let confirm!: () => void
+ mocks.dialog.mockImplementation(() => new Promise<void>((resolve) => {
+ confirm = resolve
+ }))
+ await mount()
+ fireEvent.click(screen.getByRole('button', { name: 'backup.export_recovery' }))
+ await waitFor(() => expect(mocks.dialog).toHaveBeenCalledWith(expect.objectContaining({ title: 'backup.recovery_confirm_title' })))
+ expect(mocks.invoke).not.toHaveBeenCalledWith('export_recovery_backup', expect.anything())
+ await act(async () => {
+ confirm()
+ })
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledWith('export_recovery_backup', { includeCredentials: false }))
+ expect((await screen.findByText(exported.path)).textContent).toBe(exported.path)
+ expect(mocks.invoke).not.toHaveBeenCalledWith('restore_profile', expect.anything())
+ })
+
+ it('includes credentials only when the user selects the credential option', async () => {
+ await mount()
+ fireEvent.click(screen.getByRole('checkbox', { name: 'backup.include_credentials' }))
+ fireEvent.click(screen.getByRole('button', { name: 'backup.export_recovery' }))
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledWith('export_recovery_backup', { includeCredentials: true }))
+ })
+
+ it('keeps backup actions disabled until the recovery export finishes', async () => {
+ let finish!: (value: typeof exported) => void
+ mocks.invoke.mockImplementation(async (command: string) => {
+ if (command === 'list_backups')
+ return []
+ if (command === 'export_recovery_backup') {
+ return new Promise((resolve) => {
+ finish = resolve
+ })
+ }
+ throw new Error(`Unexpected command: ${command}`)
+ })
+ await mount()
+ fireEvent.click(screen.getByRole('button', { name: 'backup.export_recovery' }))
+ await waitFor(() => expect((screen.getByRole('button', { name: 'backup.now' }) as HTMLButtonElement).disabled).toBe(true))
+ expect((screen.getByRole('button', { name: /backup.exporting_recovery/ }) as HTMLButtonElement).disabled).toBe(true)
+ await act(async () => {
+ finish(exported)
+ })
+ await waitFor(() => expect((screen.getByRole('button', { name: 'backup.now' }) as HTMLButtonElement).disabled).toBe(false))
+ })
+
+ it('reports an export failure without displaying a successful archive', async () => {
+ mocks.invoke.mockImplementation(async (command: string) => {
+ if (command === 'list_backups')
+ return []
+ throw new Error('RECOVERY_ARCHIVE_FAILED: disk full')
+ })
+ await mount()
+ fireEvent.click(screen.getByRole('button', { name: 'backup.export_recovery' }))
+ await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith(expect.stringContaining('disk full'), { variant: 'danger' }))
+ expect(screen.queryByText(exported.path)).toBeNull()
+ expect(mocks.invoke).not.toHaveBeenCalledWith('launch_harness')
+ })
+})
diff --git a/src/ui/config/backup.tsx b/src/ui/config/backup.tsx
index 710993b7..fc157adf 100644
--- a/src/ui/config/backup.tsx
+++ b/src/ui/config/backup.tsx
@@ -25,7 +25,7 @@ function formatSize(bytes: number): string {
export function ConfigBackup({ onBack }: ConfigBackupProps) {
const { t } = useTranslation()
- const { backups, loading, error, createBackup, restoreBackup, deleteBackup, busy, creating, restoring, deleting } = useBackups()
+ const { backups, loading, error, createBackup, restoreBackup, deleteBackup, busy, creating, restoring, deleting, exporting, recoveryBackup, exportRecoveryBackup } = useBackups()
const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })
const [includeCredentials, toggleIncludeCredentials] = useToggle()
@@ -41,6 +41,39 @@ export function ConfigBackup({ onBack }: ConfigBackupProps) {
}
}
+ async function handleExportRecovery() {
+ try {
+ await openDialog({
+ status: 'warning',
+ title: t('backup.recovery_confirm_title'),
+ description: <p>{t('backup.recovery_confirm_desc')}</p>,
+ confirmText: t('backup.export_recovery'),
+ })
+ }
+ catch (e) {
+ silence(e, 'backup: recovery export cancelled')
+ return
+ }
+ try {
+ await exportRecoveryBackup(includeCredentials)
+ toast(t('backup.recovery_created'), { variant: 'accent', timeout: 10000 })
+ }
+ catch (err) {
+ toast(`${t('backup.failed_toast')}: ${String(err)}`, { variant: 'danger' })
+ }
+ }
+
+ async function handleRevealRecovery() {
+ if (!recoveryBackup)
+ return
+ try {
+ await invoke('reveal_in_folder', { path: recoveryBackup.path })
+ }
+ catch (err) {
+ toast(String(err), { variant: 'danger' })
+ }
+ }
+
async function handleRestore(timestamp: string) {
try {
await openDialog({
@@ -152,7 +185,7 @@ export function ConfigBackup({ onBack }: ConfigBackupProps) {
</Button>
{/* 手动备份 */}
- <Panel.Header title={t('backup.manual_section')} description="" />
+ <Panel.Header title={t('backup.manual_section')} description={t('backup.profile_scope')} />
<div className="flex flex-col gap-3">
<Button
variant="primary"
@@ -189,6 +222,23 @@ export function ConfigBackup({ onBack }: ConfigBackupProps) {
</If>
</div>
+ <Panel.Header title={t('backup.recovery_section')} description={t('backup.recovery_desc')} />
+ <Button variant="secondary" isDisabled={busy} onPress={handleExportRecovery}>
+ <If cond={exporting}>
+ <Spinner size="sm" color="current" />
+ <span>{t('backup.exporting_recovery')}</span>
+ </If>
+ <If cond={!exporting}>
+ <span>{t('backup.export_recovery')}</span>
+ </If>
+ </Button>
+ <If cond={Boolean(recoveryBackup)}>
+ <div className="space-y-2">
+ <p className="break-all text-xs text-muted">{recoveryBackup?.path}</p>
+ <Button variant="tertiary" onPress={handleRevealRecovery}>{t('backup.reveal_recovery')}</Button>
+ </div>
+ </If>
+
{/* 备份列表 */}
<Panel.Header title={t('backup.list_section')} description="" />
<Panel.Loadable loading={loading} error={error}>