Skip to content

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

feat(desktop, migrate): Implement migration of old version data directory to official standard DSH_HOME path

hairyff0937fac4f3d
diff --git a/src-tauri/resources/README.md b/src-tauri/resources/README.md
index 9afe638c..3b5630c6 100644
--- a/src-tauri/resources/README.md
+++ b/src-tauri/resources/README.md
@@ -9,12 +9,29 @@ directory (the Tauri app-data dir for identifier
- `runtime/` — the bundled Node.js runtime (downloaded on first run)
- `dependencies/dsh/` — the packaged DeepSeek Harness distribution (downloaded from the
`hairyf/deepseek-harness-pkg` release feed)
-- `data/dsh/` — the isolated `$DSH_HOME` used by the running `dsh` process
+- `data/dsh/` — **legacy** `$DSH_HOME` location (pre-migration builds only; see below)
- `logs/` — application and `dsh` service logs
- `.store.dat` — desktop settings (port, auto-start, language, etc.)
No manual Node.js or pnpm installation is required.
+## `$DSH_HOME` — shared with the official Node.js install
+
+The user data directory (`$DSH_HOME`) used by the running `dsh` process follows
+the **official dsh convention** (`${DSH_HOME:-$HOME/.dsh}`): the `DSH_HOME`
+environment variable when set, otherwise `~/.dsh`
+(`C:\Users\<you>\.dsh` on Windows). This way the desktop app and a
+`npm i -g @deepseek-ai/dsh` install share the same profiles, sessions, settings
+and credentials — no data switching needed.
+
+On the first launch of a build that introduced this change, the app
+**migrates** any existing legacy data from `%APPDATA%/.../data/dsh` into the
+new `$DSH_HOME` (recursive merge, newer mtime wins; `node_modules` trees are
+skipped — they are regenerated on boot). The legacy directory is removed after
+a successful migration, and the one-shot migration is recorded in `.store.dat`
+(`dsh_home_migrated`). Migration failures are non-fatal: legacy data stays in
+place and the migration retries on the next launch.
+
## Preset plugins — `preset-plugins.json`
The first-run wizard / sidebar preset list is driven by `preset-plugins.json`
diff --git a/src-tauri/src/bridge/cmd.rs b/src-tauri/src/bridge/cmd.rs
index 68dbacc3..d32ed6eb 100644
--- a/src-tauri/src/bridge/cmd.rs
+++ b/src-tauri/src/bridge/cmd.rs
@@ -4,7 +4,7 @@ use crate::service::download::{self, Installable};
use crate::service::plugin;
use crate::service::update;
use crate::service::workflow;
-use tauri::{AppHandle, Manager};
+use tauri::AppHandle;
use tauri_plugin_clipboard_manager::ClipboardExt;
use tauri_plugin_opener::OpenerExt;
@@ -405,27 +405,26 @@ pub fn reveal_in_folder(path: String) -> Result<(), String> {
.map_err(|e| format!("REVEAL_FAILED: {e}"))
}
-/// 在系统文件管理器中打开数据目录
+/// 在系统文件管理器中打开数据目录(官方 $DSH_HOME,即 ~/.dsh)
#[tauri::command]
pub async fn reveal_data_dir(app_handle: AppHandle) -> Result<(), String> {
- let app_data_dir = app_handle
- .path()
- .app_data_dir()
- .map_err(|e| e.to_string())?;
+ let dsh_home = config::get_dsh_data_path(&app_handle);
+ // 目录可能尚未创建(全新安装),先建好再打开,避免资源管理器报路径不存在
+ std::fs::create_dir_all(&dsh_home).map_err(|e| e.to_string())?;
if cfg!(windows) {
std::process::Command::new("explorer")
- .arg(&app_data_dir)
+ .arg(&dsh_home)
.spawn()
.map_err(|e| e.to_string())?;
} else if cfg!(target_os = "macos") {
std::process::Command::new("open")
- .arg(&app_data_dir)
+ .arg(&dsh_home)
.spawn()
.map_err(|e| e.to_string())?;
} else {
std::process::Command::new("xdg-open")
- .arg(&app_data_dir)
+ .arg(&dsh_home)
.spawn()
.map_err(|e| e.to_string())?;
}
diff --git a/src-tauri/src/config/constants.rs b/src-tauri/src/config/constants.rs
index 72faa858..2c54c760 100644
--- a/src-tauri/src/config/constants.rs
+++ b/src-tauri/src/config/constants.rs
@@ -46,7 +46,8 @@ pub const DSH_MANIFEST_RELATIVE: &str = "package.json";
pub const PNPM_CORE_DIR: &str = "pnpm";
pub const PNPM_ENTRY_RELATIVE: &str = "bin/pnpm.cjs";
-/// 数据目录名($DSH_HOME 的相对目录)
+/// 旧版数据目录名:迁移前 $DSH_HOME 位于 `{app_data}/data/dsh`,
+/// 现仅用于 legacy 路径识别(见 service::migrate)。新 $DSH_HOME = 官方 `~/.dsh`。
pub const DSH_DATA_DIR_NAME: &str = "dsh";
/// 简单 Store 持久化
diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rs
index c1b51f1f..75e0671b 100644
--- a/src-tauri/src/config/runtime.rs
+++ b/src-tauri/src/config/runtime.rs
@@ -221,9 +221,33 @@ pub fn get_dsh_package_json_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathB
get_dsh_install_path(app_handle).join(DSH_MANIFEST_RELATIVE)
}
-/// Harness 用户数据目录($DSH_HOME)
-pub fn get_dsh_data_path(app_handle: &tauri::AppHandle) -> PathBuf {
- get_base_dir(app_handle).join("data").join(DSH_DATA_DIR_NAME)
+/// 用户主目录(Windows 取 `%USERPROFILE%`,Unix 取 `$HOME`)。
+///
+/// 不使用 dirs crate(未引入该依赖),与官方 dsh 的 `$HOME/.dsh` 语义保持一致。
+fn user_home_dir() -> Option<PathBuf> {
+ #[cfg(windows)]
+ let key = "USERPROFILE";
+ #[cfg(not(windows))]
+ let key = "HOME";
+ std::env::var_os(key).map(PathBuf::from)
+}
+
+/// Harness 用户数据目录($DSH_HOME)。
+///
+/// 与官方 dsh(`${DSH_HOME:-$HOME/.dsh}`)保持一致:
+/// - 环境变量 `DSH_HOME` 非空时优先使用;
+/// - 否则默认 `~/.dsh`(Windows `%USERPROFILE%\.dsh`,Unix `$HOME/.dsh`)。
+///
+/// 桌面版与官方 node 安装共用同一份数据:两边数据互通、无需切换。
+pub fn get_dsh_data_path<R: Runtime>(_app_handle: &AppHandle<R>) -> PathBuf {
+ if let Some(home) = std::env::var_os("DSH_HOME") {
+ if !home.is_empty() {
+ return PathBuf::from(home);
+ }
+ }
+ user_home_dir()
+ .map(|home| home.join(".dsh"))
+ .unwrap_or_else(|| PathBuf::from(".dsh"))
}
/// dsh 服务日志文件路径
@@ -322,7 +346,8 @@ pub fn runtime_info<R: Runtime>(app: &AppHandle<R>, port: u16) -> RuntimeInfo {
dsh_version: get_dsh_version(app),
node_version: get_active_node_version(),
service_url: get_dsh_service_url(port),
- data_dir: app_data_dir.clone(),
+ // 用户数据所在目录 = 官方 $DSH_HOME(~/.dsh),不再是 AppData
+ data_dir: get_dsh_data_path(app).to_string_lossy().into_owned(),
log_path: PathBuf::from(&app_data_dir)
.join("logs")
.join("dsh-web.log")
diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rs
index 3336fe82..aa5b087e 100644
--- a/src-tauri/src/config/setting.rs
+++ b/src-tauri/src/config/setting.rs
@@ -27,6 +27,10 @@ pub struct Setting {
/// 内容有变更 → 重新进入预设引导。`None` = 老用户升级(无基线)→ 弹一次建立基线。
#[serde(default)]
pub preset_hash: Option<String>,
+ /// 旧版 AppData `data/dsh` → 官方 `$DSH_HOME`(~/.dsh)数据迁移是否已完成。
+ /// 幂等标记:迁移成功并删除旧目录后置位,避免重复合并。
+ #[serde(default)]
+ pub dsh_home_migrated: bool,
}
/// 命令行集成默认开启(开发者工具场景,安装完成即可用)
@@ -55,6 +59,7 @@ impl Default for Setting {
cli_link_enabled: default_cli_link_enabled(),
preinstall_done: false,
preset_hash: None,
+ dsh_home_migrated: false,
}
}
}
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 88301ec3..7dfbe7f0 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -21,6 +21,14 @@ pub fn setup(app_handle: tauri::AppHandle) {
// workflow::sweep_orphan_harness),避免新实例一路漂移端口
crate::service::workflow::sweep_orphan_harness(&app_handle);
+ // 旧版 AppData data/dsh → 官方 $DSH_HOME(~/.dsh)数据迁移。
+ // 必须在 sweep 之后(先杀掉占用文件句柄的残留 dsh 进程)、scheduler/
+ // auto_start 之前(迁移完成前不启动 dsh)。失败仅告警不阻断:旧数据
+ // 原地保留,下次启动重试。
+ if let Err(e) = crate::service::migrate::migrate(&app_handle) {
+ log::warn!("dsh home migration deferred (old data kept): {e}");
+ }
+
// 启动进程监控(tick 检测 dsh 服务状态)
crate::service::scheduler::start(&app_handle);
diff --git a/src-tauri/src/service/cli/shim.rs b/src-tauri/src/service/cli/shim.rs
index dc9e9620..4377b4bd 100644
--- a/src-tauri/src/service/cli/shim.rs
+++ b/src-tauri/src/service/cli/shim.rs
@@ -198,10 +198,10 @@ pub fn escape_path_sh(path: &Path) -> String {
// dsh shim
// ---------------------------------------------------------------------------
-/// Windows `dsh.cmd` 内容。`app_dir` 为应用数据目录(绝对路径,生成时写死)。
-pub fn build_cmd_shim(app_dir: &Path) -> String {
+/// Windows `dsh.cmd` 内容。`app_dir` 为应用数据目录(绝对路径,生成时写死),
+/// `dsh_home` 为官方 `$DSH_HOME`(`~/.dsh`,生成时写死,与桌面端/官方一致)。
+pub fn build_cmd_shim(app_dir: &Path, dsh_home: &Path) -> String {
let dsh_bin = app_dir.join("dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js");
- let dsh_home = app_dir.join("data/dsh");
format!(
r#"@echo off
@@ -236,9 +236,8 @@ exit /b 1
}
/// Windows `dsh.ps1` 内容
-pub fn build_ps1_shim(app_dir: &Path) -> String {
+pub fn build_ps1_shim(app_dir: &Path, dsh_home: &Path) -> String {
let dsh_bin = app_dir.join("dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js");
- let dsh_home = app_dir.join("data/dsh");
format!(
r#"# DeepSeek Harness Desktop - dsh command shim (generated)
@@ -268,9 +267,8 @@ exit $LASTEXITCODE
/// Unix `dsh` shell 脚本内容(POSIX sh)
#[cfg(not(windows))]
-pub fn build_sh_shim(app_dir: &Path) -> String {
+pub fn build_sh_shim(app_dir: &Path, dsh_home: &Path) -> String {
let dsh_bin = app_dir.join("dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js");
- let dsh_home = app_dir.join("data/dsh");
format!(
r#"#!/bin/sh
@@ -502,6 +500,7 @@ pub fn user_dsh_preserved(bin_dir: &Path) -> bool {
/// 同名 `dsh`/`pnpm` 一律保留不动,避免覆盖用户自己的安装与配置。
pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String> {
let app_dir = config::get_base_dir(app_handle);
+ let dsh_home = config::get_dsh_data_path(app_handle);
fs::create_dir_all(bin_dir).map_err(|e| format!("create bin dir failed: {e}"))?;
// 写入单个 shim:若目标已存在且非本应用生成,则跳过不覆盖(保留用户文件)。
@@ -523,14 +522,14 @@ pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String>
#[cfg(windows)]
{
- write_if_ours!(SHIM_CMD_NAME, build_cmd_shim(&app_dir));
- write_if_ours!(SHIM_PS1_NAME, build_ps1_shim(&app_dir));
+ write_if_ours!(SHIM_CMD_NAME, build_cmd_shim(&app_dir, &dsh_home));
+ write_if_ours!(SHIM_PS1_NAME, build_ps1_shim(&app_dir, &dsh_home));
write_if_ours!(PNPM_SHIM_CMD_NAME, build_pnpm_cmd_shim(&app_dir));
write_if_ours!(PNPM_SHIM_PS1_NAME, build_pnpm_ps1_shim(&app_dir));
}
#[cfg(not(windows))]
{
- write_if_ours!(SHIM_SH_NAME, build_sh_shim(&app_dir));
+ write_if_ours!(SHIM_SH_NAME, build_sh_shim(&app_dir, &dsh_home));
write_if_ours!(PNPM_SHIM_SH_NAME, build_pnpm_sh_shim(&app_dir));
// 仅对本应用生成/覆盖过的 shim 设置可执行位;保留的用户文件不动
for name in [SHIM_SH_NAME, PNPM_SHIM_SH_NAME] {
@@ -558,19 +557,29 @@ mod tests {
}
}
+ /// 官方 $DSH_HOME(~/.dsh)
+ fn sample_dsh_home() -> PathBuf {
+ if cfg!(windows) {
+ PathBuf::from(r"C:\Users\test\.dsh")
+ } else {
+ PathBuf::from("/home/test/.dsh")
+ }
+ }
+
#[test]
fn cmd_shim_contains_baked_paths() {
- let content = build_cmd_shim(&sample_app_dir());
+ let content = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());
assert!(content.contains(r"C:\Users\test\AppData\Roaming"));
assert!(content.contains("dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js"));
- assert!(content.contains("data/dsh"));
+ assert!(content.contains(r"C:\Users\test\.dsh"));
+ assert!(!content.contains("data/dsh"));
assert!(content.contains("%*"));
}
#[test]
fn cmd_shim_escapes_percent() {
let dir = PathBuf::from(r"C:\Users\100%test\AppData\Roaming\io.github.hairyf.deepseek-harness-desktop");
- let content = build_cmd_shim(&dir);
+ let content = build_cmd_shim(&dir, &sample_dsh_home());
assert!(content.contains("100%%test"));
assert!(!content.contains(r#"set "APP_DIR=C:\Users\100%test""#));
}
@@ -617,13 +626,15 @@ mod tests {
#[test]
fn ps1_shim_escapes_quotes() {
let dir = PathBuf::from(r"C:\Users\o'brien\AppData\Roaming\io.github.hairyf.deepseek-harness-desktop");
- let content = build_ps1_shim(&dir);
+ let content = build_ps1_shim(&dir, &sample_dsh_home());
assert!(content.contains(r"o''brien"));
+ // dsh_home 同样走 ps1 转义
+ assert!(content.contains(r"C:\Users\test\.dsh"));
}
#[test]
fn cmd_shim_prefers_user_dsh() {
- let content = build_cmd_shim(&sample_app_dir());
+ let content = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());
assert!(content.contains("USER_DSH"));
assert!(content.contains(r#"call "%USER_DSH%" %*"#));
assert!(content.contains("SELF_PREFIX"));
@@ -635,7 +646,7 @@ mod tests {
#[test]
fn ps1_shim_prefers_user_dsh() {
- let content = build_ps1_shim(&sample_app_dir());
+ let content = build_ps1_shim(&sample_app_dir(), &sample_dsh_home());
assert!(content.contains("Get-Command dsh -All"));
assert!(content.contains("$userDsh.Source"));
assert!(content.contains("$PSScriptRoot"));
@@ -649,7 +660,7 @@ mod tests {
fn sh_shim_prefers_user_dsh() {
#[cfg(not(windows))]
{
- let content = build_sh_shim(&sample_app_dir());
+ let content = build_sh_shim(&sample_app_dir(), &sample_dsh_home());
assert!(content.contains(r#"exec "$dir/dsh" "$@""#));
assert!(content.contains("SELF_DIR"));
// 用户 dsh 优先 > 注入 DSH_HOME
@@ -675,9 +686,9 @@ mod tests {
// 本应用生成的 shim -> 不是 foreign,可覆盖
#[cfg(not(windows))]
- let generated = build_sh_shim(&sample_app_dir());
+ let generated = build_sh_shim(&sample_app_dir(), &sample_dsh_home());
#[cfg(windows)]
- let generated = build_cmd_shim(&sample_app_dir());
+ let generated = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());
std::fs::write(&user_dsh, generated).unwrap();
assert!(!is_foreign_file(&user_dsh), "generated shim must not be foreign");
diff --git a/src-tauri/src/service/migrate.rs b/src-tauri/src/service/migrate.rs
new file mode 100644
index 00000000..5b8dfbef
--- /dev/null
+++ b/src-tauri/src/service/migrate.rs
@@ -0,0 +1,312 @@
+//! 用户数据目录迁移:旧版 AppData `data/dsh` → 官方 `$DSH_HOME`(`~/.dsh`)。
+//!
+//! 早期桌面版把 `$DSH_HOME` 隔离在应用数据目录
+//! (`%APPDATA%/io.github.hairyf.deepseek-harness-desktop/data/dsh`),与官方
+//! node 安装(`${DSH_HOME:-$HOME/.dsh}`)不一致,两边数据互不相通。本模块在
+//! 启动早期把旧数据迁移到官方 `$DSH_HOME`,之后桌面版与官方安装共用同一份数据。
+//!
+//! 迁移规则:
+//! - 目标不存在(场景 A)→ 整体搬移(同卷 `rename` 原子移动,跨卷自动退化为复制);
+//! - 目标已存在(场景 B)→ 递归合并,同名文件按 mtime「较新者胜」;
+//! - `node_modules` 目录整体跳过:可再生的安装产物(dsh 启动时会按 profile 的
+//! package.json 重新安装),且 pnpm 的硬链接/junction 直接复制会损坏;
+//! - 迁移成功并删除旧目录后,在 `.store.dat` 置位 `dsh_home_migrated` 幂等标记;
+//! - 任何失败只告警不阻断启动:旧数据原地保留,下次启动重试。
+
+use crate::config;
+use std::fs;
+use std::path::{Path, PathBuf};
+use tauri::AppHandle;
+
+/// 旧版(<0.x 迁移版)$DSH_HOME 位置:AppData 下的 `data/dsh`。
+fn legacy_dsh_home(app_handle: &AppHandle) -> PathBuf {
+ config::get_base_dir(app_handle)
+ .join("data")
+ .join(config::DSH_DATA_DIR_NAME)
+}
+
+/// 启动早期调用:把旧版 AppData 数据目录迁移到官方 `$DSH_HOME`。
+///
+/// 幂等:成功后会删除旧目录并置位 `.store.dat` 标记,重复调用为 no-op。
+/// 失败返回 Err(不删除旧数据),由调用方决定是否阻断——本应用选择仅告警。
+pub fn migrate(app_handle: &AppHandle) -> Result<(), String> {
+ let setting = config::get_store_dat_setting(app_handle);
+ if setting.dsh_home_migrated {
+ log::debug!("dsh home migration already done, skipping");
+ return Ok(());
+ }
+
+ let legacy = legacy_dsh_home(app_handle);
+ let target = config::get_dsh_data_path(app_handle);
+
+ // 旧目录不存在(全新安装 / 官方安装场景)→ 无需迁移
+ if !legacy.exists() {
+ return Ok(());
+ }
+ // 旧路径 == 新路径(用户显式把 DSH_HOME 指向 AppData)→ 跳过
+ if legacy == target {
+ return Ok(());
+ }
+
+ migrate_impl(&legacy, &target)?;
+
+ // 置位幂等标记
+ let mut setting = config::get_store_dat_setting(app_handle);
+ setting.dsh_home_migrated = true;
+ config::set_store_dat_setting(app_handle, setting);
+ log::info!(
+ "dsh home migrated: {} -> {}",
+ legacy.display(),
+ target.display()
+ );
+ Ok(())
+}
+
+/// 迁移实现(纯路径函数,便于单测)。成功时旧目录已被删除。
+fn migrate_impl(legacy: &Path, target: &Path) -> Result<(), String> {
+ if !legacy.exists() {
+ return Ok(());
+ }
+ if let Some(parent) = target.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("create {} failed: {e}", parent.display()))?;
+ }
+ if !target.exists() {
+ // 场景 A:目标不存在 → 整体搬移(rename 同卷原子,node_modules 一并
+ // 无损搬入;跨卷 EXDEV 退化为复制合并,此时 node_modules 跳过)
+ if fs::rename(legacy, target).is_ok() {
+ return Ok(());
+ }
+ log::debug!(
+ "rename {} -> {} failed, falling back to recursive copy",
+ legacy.display(),
+ target.display()
+ );
+ }
+ // 场景 B(或跨卷回退):递归合并,新数据优先
+ merge_tree(legacy, target)?;
+ fs::remove_dir_all(legacy).map_err(|e| {
+ format!(
+ "remove legacy {} after merge failed: {e}",
+ legacy.display()
+ )
+ })
+}
+
+/// 递归把 `src` 目录树合并进 `dst`:
+/// - 目标缺失的条目直接搬入(目录 `rename` 快路径,失败递归复制);
+/// - 两边都有的文件按 mtime 比较,目标不旧于源则保留目标(新数据优先);
+/// - `node_modules` 目录:目标缺失时尝试无损 `rename` 搬入(pnpm 硬链接/
+/// junction 移动无损坏风险,且不丢依赖);目标已有或跨卷 rename 失败时
+/// 跳过(依赖可再生,复制硬链接树会损坏)。
+fn merge_tree(src: &Path, dst: &Path) -> Result<(), String> {
+ fs::create_dir_all(dst).map_err(|e| format!("create {} failed: {e}", dst.display()))?;
+ for entry in fs::read_dir(src)
+ .map_err(|e| format!("read {} failed: {e}", src.display()))?
+ {
+ let entry = entry.map_err(|e| format!("read_dir entry failed: {e}"))?;
+ let name = entry.file_name();
+ let src_path = entry.path();
+ let dst_path = dst.join(&name);
+ if name == "node_modules" {
+ // 依赖树特殊处理:目标已有 → 保留目标;目标缺失 → 无损 rename 搬入
+ if !dst_path.exists() {
+ let _ = fs::rename(&src_path, &dst_path);
+ }
+ continue;
+ }
+ let is_dir = entry
+ .file_type()
+ .map_err(|e| format!("file_type {} failed: {e}", src_path.display()))?
+ .is_dir();
+ if is_dir {
+ if dst_path.exists() && dst_path.is_dir() {
+ merge_tree(&src_path, &dst_path)?;
+ } else if fs::rename(&src_path, &dst_path).is_err() {
+ // 跨卷或目标被文件占用:退化为递归复制
+ merge_tree(&src_path, &dst_path)?;
+ }
+ } else if !dst_path.exists() || src_newer(&src_path, &dst_path) {
+ fs::copy(&src_path, &dst_path).map_err(|e| {
+ format!("copy {} -> {} failed: {e}", src_path.display(), dst_path.display())
+ })?;
+ }
+ }
+ Ok(())
+}
+
+/// `src` 的 mtime 是否严格新于 `dst`(任一 metadata/modified 缺失时按“需要覆盖”处理)。
+fn src_newer(src: &Path, dst: &Path) -> bool {
+ let src_mtime = fs::metadata(src).and_then(|m| m.modified()).ok();
+ let dst_mtime = fs::metadata(dst).and_then(|m| m.modified()).ok();
+ match (src_mtime, dst_mtime) {
+ (Some(s), Some(d)) => s > d,
+ (Some(_), None) => true,
+ _ => false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// 构造一个带内容与 mtime 的临时目录树,返回 (root, 清理守卫)。
+ fn temp_dir(tag: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "dsh-migrate-test-{}-{tag}",
+ std::process::id()
+ ));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ fn write(path: &Path, content: &str) {
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(path, content).unwrap();
+ }
+
+ /// 用标准库 FileTimes 设置 mtime(Rust 1.75+)。
+ /// 注意必须以写权限打开:Windows 上只读句柄调用 set_times 会被拒绝。
+ fn set_mtime(path: &Path, secs_since_epoch: u64) {
+ let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs_since_epoch);
+ let f = fs::OpenOptions::new().write(true).open(path).unwrap();
+ f.set_times(std::fs::FileTimes::new().set_modified(t)).unwrap();
+ }
+
+ // ------------------------------------------------------------------
+ // 场景 A:目标不存在 → 整体搬移
+ // ------------------------------------------------------------------
+
+ #[test]
+ fn scenario_a_moves_whole_tree() {
+ let legacy = temp_dir("a-legacy");
+ let target = temp_dir("a-target-parent").join("dsh");
+ let _ = fs::remove_dir_all(&target);
+
+ write(&legacy.join("settings.yaml"), "theme: dark\n");
+ write(&legacy.join("sessions/s1/data.json"), "{}");
+ write(&legacy.join("profiles/web/package.json"), "{\"name\":\"web\"}");
+ write(&legacy.join("profiles/web/node_modules/x/index.js"), "// x");
+
+ migrate_impl(&legacy, &target).unwrap();
+
+ assert!(!legacy.exists(), "legacy dir must be removed");
+ assert!(target.join("settings.yaml").is_file());
+ assert!(target.join("sessions/s1/data.json").is_file());
+ assert!(target.join("profiles/web/package.json").is_file());
+ // rename 无损搬移:node_modules 一并带入(不丢依赖)
+ assert!(
+ target.join("profiles/web/node_modules/x/index.js").is_file(),
+ "rename must carry node_modules over losslessly"
+ );
+ }
+
+ #[test]
+ fn scenario_a_nonexistent_legacy_is_noop() {
+ let legacy = temp_dir("a-none").join("nope");
+ let target = temp_dir("a-none-target").join("dsh");
+ let _ = fs::remove_dir_all(&target);
+ migrate_impl(&legacy, &target).unwrap();
+ assert!(!target.exists());
+ }
+
+ // ------------------------------------------------------------------
+ // 场景 B:目标已存在 → 合并,新数据优先
+ // ------------------------------------------------------------------
+
+ #[test]
+ fn scenario_b_merges_newer_wins() {
+ let legacy = temp_dir("b-legacy");
+ let target = temp_dir("b-target");
+
+ // 两边都有同名文件:legacy 更新 → 覆盖;target 更新 → 保留
+ write(&legacy.join("shared.txt"), "legacy-new");
+ write(&target.join("shared.txt"), "target-old");
+ set_mtime(&legacy.join("shared.txt"), 200);
+ set_mtime(&target.join("shared.txt"), 100);
+
+ write(&legacy.join("keep-target.txt"), "legacy-old");
+ write(&target.join("keep-target.txt"), "target-new");
+ set_mtime(&legacy.join("keep-target.txt"), 100);
+ set_mtime(&target.join("keep-target.txt"), 200);
+
+ // legacy 独有 → 复制进来
+ write(&legacy.join("only-legacy.txt"), "L");
+ // target 独有 → 保留
+ write(&target.join("only-target.txt"), "T");
+ // node_modules 两边都有 → 保留目标
+ write(&legacy.join("profiles/web/node_modules/p/index.js"), "// legacy p");
+ write(&target.join("profiles/web/node_modules/p/index.js"), "// target p");
+
+ migrate_impl(&legacy, &target).unwrap();
+
+ assert!(!legacy.exists(), "legacy dir must be removed after merge");
+ assert_eq!(
+ fs::read_to_string(target.join("shared.txt")).unwrap(),
+ "legacy-new",
+ "newer source file wins"
+ );
+ assert_eq!(
+ fs::read_to_string(target.join("keep-target.txt")).unwrap(),
+ "target-new",
+ "newer target file is preserved"
+ );
+ assert!(target.join("only-legacy.txt").is_file());
+ assert!(target.join("only-target.txt").is_file());
+ assert_eq!(
+ fs::read_to_string(target.join("profiles/web/node_modules/p/index.js")).unwrap(),
+ "// target p",
+ "existing target node_modules is preserved"
+ );
+ }
+
+ #[test]
+ fn scenario_b_carries_legacy_node_modules_when_target_lacks_it() {
+ let legacy = temp_dir("b-nm-legacy");
+ let target = temp_dir("b-nm-target");
+
+ write(&legacy.join("profiles/web/node_modules/x/index.js"), "// x");
+ write(&legacy.join("profiles/web/package.json"), "{}");
+
+ migrate_impl(&legacy, &target).unwrap();
+ assert!(target.join("profiles/web/package.json").is_file());
+ assert!(
+ target.join("profiles/web/node_modules/x/index.js").is_file(),
+ "legacy node_modules is carried over when target has none"
+ );
+ }
+
+ // ------------------------------------------------------------------
+ // 失败场景:目标被文件占位 → 报错且不删源
+ // ------------------------------------------------------------------
+
+ #[test]
+ fn failure_keeps_legacy_intact() {
+ let legacy = temp_dir("f-legacy");
+ // 目标路径被一个普通文件占位(模拟异常状态)→ merge 应失败且不删源
+ let target = temp_dir("f-target-file").join("occupied");
+ fs::write(&target, "i am a file").unwrap();
+ write(&legacy.join("data.txt"), "precious");
+
+ let err = migrate_impl(&legacy, &target).unwrap_err();
+ assert!(err.contains("failed") || err.contains("create"));
+ assert!(legacy.join("data.txt").is_file(), "source must stay intact");
+ assert!(fs::read_to_string(&target).unwrap() == "i am a file");
+ }
+
+ // ------------------------------------------------------------------
+ // 幂等:migrate() 标记层面(migrate_impl 天然幂等——旧目录已删)
+ // ------------------------------------------------------------------
+
+ #[test]
+ fn merge_tree_is_idempotent() {
+ let legacy = temp_dir("i-legacy");
+ let target = temp_dir("i-target");
+ write(&legacy.join("a.txt"), "1");
+ merge_tree(&legacy, &target).unwrap();
+ // 第二次:legacy 已空,无新增内容
+ merge_tree(&legacy, &target).unwrap();
+ assert_eq!(fs::read_to_string(target.join("a.txt")).unwrap(), "1");
+ }
+}
diff --git a/src-tauri/src/service/mod.rs b/src-tauri/src/service/mod.rs
index b6499439..20940346 100644
--- a/src-tauri/src/service/mod.rs
+++ b/src-tauri/src/service/mod.rs
@@ -1,5 +1,6 @@
pub mod cli;
pub mod download;
+pub mod migrate;
pub mod plugin;
pub mod scheduler;
pub mod update;