Skip to content

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

feat(data-dir): 数据目录可迁移、可回滚,安装期即可选择 (#871) (#889)

iuuuuuuuu7a5448f414a9
diff --git a/README.en.md b/README.en.md
index b7f4738b..8ef363eb 100644
--- a/README.en.md
+++ b/README.en.md
@@ -42,6 +42,7 @@
- 🔄 **Runtime management** — Install dependencies, select core versions, and access desktop/core updates.
- 🧩 **Plugin management** — 11 built-in plugins, plus community plugin installation, upgrades, removal, and error details.
- 🗂️ **Profile configuration** — Separate plugin/settings configurations; profiles are not an OS security sandbox.
+- 💽 **Data directory** — Pick where data lives during installation (Windows installer); migrate or roll it back later in Settings on Windows, macOS, and Linux.
- ⌨️ **CLI integration** — Managed `dsh` / `pnpm` shims, not a global npm core installation.
- 🐾 **Desktop pets** — Pets / Codex resources, pack imports, and conversation activity; preset media comes from remote hosts.
- 🎨 **Personalization** — 8 palettes, terminal mode, and native transparency, with one-click restore to defaults.
diff --git a/README.es.md b/README.es.md
index 6cdd3c63..4d5f2b18 100644
--- a/README.es.md
+++ b/README.es.md
@@ -42,6 +42,7 @@
- 🔄 **Gestión del runtime** — Instalá dependencias, elegí versiones del núcleo y accedé a actualizaciones del escritorio y del núcleo.
- 🧩 **Gestión de plugins** — 11 plugins integrados, más instalación, actualización, desinstalación y detalles de errores de plugins comunitarios.
- 🗂️ **Configuración por perfiles** — Separá plugins y ajustes; los perfiles no son un sandbox de seguridad del sistema operativo.
+- 💽 **Directorio de datos** — En Windows, elegí dónde se guardan los datos al instalar, y migralo o revertilo después en Ajustes.
- ⌨️ **Integración con la terminal** — Shims administrados de `dsh` / `pnpm`, no una instalación global del núcleo por npm.
- 🐾 **Mascotas de escritorio** — Recursos Pets / Codex, importación de paquetes y actividad de conversaciones; los recursos predefinidos son remotos.
- 🎨 **Personalización** — 8 paletas, modo terminal y transparencia nativa, con restauración de valores predeterminados en un clic.
diff --git a/README.md b/README.md
index e1a3001c..417ffa42 100644
--- a/README.md
+++ b/README.md
@@ -42,6 +42,7 @@
- 🔄 **运行时管理** — 安装依赖、选择内核版本,并提供桌面端与内核更新入口。
- 🧩 **插件管理** — 11 个内置插件;支持社区插件安装、升级、卸载与错误查看。
- 🗂️ **档案配置** — 分别管理插件与设置;档案不是操作系统安全沙箱。
+- 💽 **数据目录** — 安装时(Windows 安装包)可选择数据存放位置;Windows / macOS / Linux 都能在设置里整体迁移与回滚。
- ⌨️ **命令行集成** — 通过托管 shim 提供 `dsh` / `pnpm`,不是全局 npm 内核安装。
- 🐾 **桌宠** — Pets / Codex 资源管理、资源包导入与会话状态展示;预设素材来自远端。
- 🎨 **个性化** — 8 种配色、终端模式与原生透明,可一键恢复默认。
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 6dca5c4e..74c253ab 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -73,6 +73,8 @@ Use `git diff --check` for documentation-only edits. Tests must use isolated dat
- Debug runtime, core, and dependencies live under `<AppData>/dev/`; the log is `<AppData>/dev/logs/dsh-web.dev.log`.
- Debug ignores inherited `DSH_HOME`, uses `~/.dsh.dev`, and does not migrate release data or modify the production CLI PATH.
+- The release data directory is the user-level `DSH_HOME` variable (`~/.dsh` when unset). The Windows installer can set it; on every platform **Settings → Data Directory** copies the data, verifies the copy, renames the old directory aside, and rewrites the variable; rollback restores the previous location from that renamed directory.
+- How that variable is persisted is platform-specific: Windows writes `HKCU\Environment`; macOS writes a `~/Library/LaunchAgents/dsh-tauri.env.plist` LaunchAgent that replays `launchctl setenv` at login (the plist's own `EnvironmentVariables` key would not reach a Finder/Dock-launched app); Linux writes `~/.config/environment.d/dsh-tauri.conf` plus a marked block in `~/.profile`. A GUI app started by launchd or by the display manager inherits no login-shell environment, so the app also reads the variable back from disk at startup.
- Ports are configurable and may fall back when occupied; side-by-side launches need not use those exact values.
- Profiles separate configuration, not OS permissions.
diff --git a/docs/DEVELOPMENT.zh.md b/docs/DEVELOPMENT.zh.md
index 48269281..631f7efc 100644
--- a/docs/DEVELOPMENT.zh.md
+++ b/docs/DEVELOPMENT.zh.md
@@ -73,6 +73,8 @@ cargo test --manifest-path src-tauri/Cargo.toml --all-features --locked
- Debug 的运行时、内核与依赖位于 `<AppData>/dev/`;日志为 `<AppData>/dev/logs/dsh-web.dev.log`。
- Debug 忽略继承的 `DSH_HOME`,固定使用 `~/.dsh.dev`,不迁移正式版数据或修改生产 CLI PATH。
+- 正式版数据目录由**用户级 `DSH_HOME`** 决定(未设置时是 `~/.dsh`)。Windows 安装器可直接设置该变量;三个平台的「设置 → 数据目录」都能复制数据、校验副本、把旧目录改名保底并改写变量;回滚会用该改名目录还原到原位置。
+- 该变量的持久化方式按平台不同:Windows 写 `HKCU\Environment`;macOS 写 `~/Library/LaunchAgents/dsh-tauri.env.plist`,由 LaunchAgent 在登录时重放 `launchctl setenv`(plist 自带的 `EnvironmentVariables` 键到不了 Finder/Dock 启动的应用);Linux 写 `~/.config/environment.d/dsh-tauri.conf` 与 `~/.profile` 里的标记块。由 launchd 或显示管理器启动的 GUI 应用不继承登录 shell 的环境,因此应用启动时还会自己从磁盘回读一次该变量。
- 端口可配置,占用时可能回退;不保证并行启动时始终使用上述值。
- 档案隔离的是配置,不是操作系统权限。
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 96563a31..af40cadd 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -94,8 +94,6 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f3f79755c74fd155000314eb349864caa787c6592eace6c6882dad873d9c39"
dependencies = [
- "async-fs",
- "async-net",
"enumflags2",
"futures-channel",
"futures-util",
@@ -103,6 +101,7 @@ dependencies = [
"raw-window-handle",
"serde",
"serde_repr",
+ "tokio",
"url",
"wayland-backend",
"wayland-client",
@@ -148,17 +147,6 @@ dependencies = [
"slab",
]
-[[package]]
-name = "async-fs"
-version = "2.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5"
-dependencies = [
- "async-lock",
- "blocking",
- "futures-lite",
-]
-
[[package]]
name = "async-io"
version = "2.6.0"
@@ -188,17 +176,6 @@ dependencies = [
"pin-project-lite",
]
-[[package]]
-name = "async-net"
-version = "2.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7"
-dependencies = [
- "async-io",
- "blocking",
- "futures-lite",
-]
-
[[package]]
name = "async-process"
version = "2.5.0"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 8e6735d0..4cdc8559 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -105,6 +105,19 @@ auto-launch = "0.5"
tauri = { version = "2", features = [ "test" ] }
tempfile = "3"
+# 选择数据存放目录(issue #871):Windows 走原生 IFileDialog、macOS 走 NSOpenPanel、
+# Linux 走 xdg-desktop-portal(无 portal 时 rfd 自己回退到 zenity)。
+# 上游的默认特性是 Linux 专用的(xdg-portal + wayland + async-std),因此这里显式列
+# 出特性并关掉默认值:Windows / macOS 只需要 common-controls-v6;Linux 的 ashpd 传输
+# 后端用本仓库已有的 tokio,不为一次选目录再引入 async-std 这整套运行时。
+[target.'cfg(any(windows, target_os = "macos", target_os = "linux"))'.dependencies]
+rfd = { version = "0.16", default-features = false, features = [
+ "common-controls-v6",
+ "xdg-portal",
+ "wayland",
+ "tokio",
+] }
+
[target.'cfg(target_os = "macos")'.dependencies]
objc2-app-kit = { version = "=0.3.2", default-features = false, features = [
"NSWindow",
@@ -165,7 +178,6 @@ tauri-plugin-notifications = { path = "vendor/tauri-plugin-notifications" }
debug = 1
[target.'cfg(windows)'.dependencies]
-rfd = "0.16"
webview2-com = "0.38"
windows-core = "0.61"
winreg = "0.55"
diff --git a/src-tauri/src/bridge/data_dir.rs b/src-tauri/src/bridge/data_dir.rs
new file mode 100644
index 00000000..a99ffef1
--- /dev/null
+++ b/src-tauri/src/bridge/data_dir.rs
@@ -0,0 +1,163 @@
+//! 数据目录(`DSH_HOME`)迁移 / 回滚的 Tauri 命令(issue #871)。
+//!
+//! 薄封装:把 IPC 参数转成 `service::data_dir` 的调用,遵循 `bridge/backup.rs`
+//! 的分层模式。迁移属于长任务(实测约 900 MiB / 25800 个文件),因此:
+//! - 命令先取核心切换锁、停 Harness、持插件操作锁,再进 `spawn_blocking`;
+//! - 进度通过 `data-dir://progress` 事件推送,前端订阅渲染。
+
+use std::path::{Path, PathBuf};
+
+use tauri::AppHandle;
+
+use crate::service::data_dir;
+
+/// 标记文件名(错误信息与 `data_dir::harness_marker` 指向同一个文件)。
+const MARKER_NAME: &str = ".harness.pid";
+
+/// `stop()` 之前:标记读不出来就先拒绝,别给 `stop()` 删标记的机会。
+///
+/// `stop()` 成功后会删掉 `.harness.pid`(`workflow::process::stop`),删掉之后
+/// 「这个目录当时有没有别的 Harness 在写」就再也查不出来了。标记读不出来
+/// (占用、权限、写到一半)恰恰说明有人正动这个文件,此时既拿不到 PID、也就无法
+/// 排除「有个不在 owned 注册表里的 Harness 还在写这个目录」,只能 fail closed。
+///
+/// 标记里写着一个存活 PID 时**不**在这里拒绝:那通常就是本应用自己拉起的 Harness
+/// (`launch.rs` 启动后立刻写下标记),`stop()` 会正常把它停掉;提前拒绝会让
+/// 正常迁移永远走不下去。这类判断留给 `stop()` 之后的 `confirm_harness_stopped`。
+fn reject_unreadable_marker(recorded: data_dir::HarnessMarker) -> Result<(), String> {
+ use data_dir::HarnessMarker;
+ match recorded {
+ HarnessMarker::Invalid => Err(format!(
+ "DATA_DIR_HARNESS_MARKER_INVALID: {} 读不出来,无法确认 Harness 是否已退出,请先退出所有实例再重试",
+ MARKER_NAME
+ )),
+ // 标记里写着一个存活 PID:那通常就是本应用自己拉起的 Harness,放行让
+ // `stop()` 去停它;真正「停不掉」的情况由停服后的复核负责。
+ HarnessMarker::Missing | HarnessMarker::Pid(_) => Ok(()),
+ }
+}
+
+/// `stop()` 之后:确认「记录在案的那个 Harness 真的已经退出」。
+///
+/// `stop()` 只处理本进程持有的那个 Harness。于是「崩溃残留、不在 owned 注册表里
+/// 的 Harness」既拦不住 `stop()`,也会因为标记被删而在 `data_dir::harness_stopped`
+/// 眼里变成「已退出」。所以调用方在停之前先把标记读下来,停完再复核一次它是否真的
+/// 没了——「stop 返回 Ok」与「标记没了」都不是它退出的证据。
+///
+/// 判据刻意只取标记文件里的 PID,不做命令行 / 端口推断:标记路径由数据目录推出,
+/// 天然限定在「同一个数据目录」;而命令行里的 `--profile` 与 `--port` 都不含目录
+/// 信息(用户自己的另一个实例同样是 `--profile tauri --port 3080`),端口还可能被
+/// 无关程序占用。照命令行去清扫会杀掉用户正在用的那个实例,代价远大于让用户
+/// 手动关掉它再重试,因此这里只报告、不动手。
+fn confirm_harness_stopped(recorded: data_dir::HarnessMarker) -> Result<(), String> {
+ use data_dir::HarnessMarker;
+ match recorded {
+ // 正常路径上到不了这里(`reject_unreadable_marker` 已经先拦下),留着是
+ // 为了万一将来有人调换两步顺序时仍然 fail closed。
+ HarnessMarker::Invalid => Err(format!(
+ "DATA_DIR_HARNESS_MARKER_INVALID: {} 读不出来,无法确认 Harness 是否已退出,请先退出所有实例再重试",
+ MARKER_NAME
+ )),
+ // 从未启动过、或上次已正常清理:没有别的实例可担心
+ HarnessMarker::Missing => Ok(()),
+ HarnessMarker::Pid(pid) => {
+ if data_dir::process_alive(pid) {
+ return Err(format!(
+ "DATA_DIR_HARNESS_RUNNING: {pid} 仍在使用数据目录,请先退出那个实例再重试"
+ ));
+ }
+ Ok(())
+ }
+ }
+}
+
+/// 当前数据目录状态(同步命令:只读注册表与目录名,不做遍历)。
+#[tauri::command]
+pub fn get_data_dir_status(app_handle: AppHandle) -> data_dir::DataDirStatus {
+ data_dir::status(&app_handle)
+}
+
+/// 弹出系统选目录对话框,返回用户选中的目录(取消返回 `None`)。
+///
+/// 选目录走 `rfd`:仓库未引入 `tauri-plugin-dialog`,`AsyncFileDialog` 自己起线程
+/// (macOS 后端会把对话框派发到主线程),因此可以直接在异步命令里 `.await`。
+/// Linux 上用 xdg-desktop-portal 后端;没有 portal 的会话(纯 X11、无 DBus)会
+/// 失败,前端据此提示用户手填路径。
+#[tauri::command]
+pub async fn pick_data_dir(app_handle: AppHandle) -> Result<Option<String>, String> {
+ let start = crate::config::get_dsh_data_path(&app_handle);
+ let picked = rfd::AsyncFileDialog::new()
+ .set_title("选择数据存放目录")
+ .set_directory(start.parent().unwrap_or(&start))
+ .pick_folder()
+ .await;
+ Ok(picked.map(|handle| handle.path().to_string_lossy().into_owned()))
+}
+
+/// 数据目录下的顶层条目及占用空间(遍历目录树,脱离异步运行时)。
+#[tauri::command]
+pub async fn list_data_dir_entries(
+ app_handle: AppHandle,
+) -> Result<Vec<data_dir::DataDirEntry>, String> {
+ let app = app_handle.clone();
+ tauri::async_runtime::spawn_blocking(move || data_dir::entries(&app))
+ .await
+ .map_err(|e| format!("DATA_DIR_TASK: {e}"))?
+}
+
+/// 迁移预检:目标合法性、体积、磁盘空间(遍历目录树,脱离异步运行时)。
+#[tauri::command]
+pub async fn preview_data_dir_migration(
+ app_handle: AppHandle,
+ parent: String,
+ leaf: String,
+) -> Result<data_dir::MigrationPlan, String> {
+ let app = app_handle.clone();
+ tauri::async_runtime::spawn_blocking(move || data_dir::preview(&app, Path::new(&parent), &leaf))
+ .await
+ .map_err(|e| format!("DATA_DIR_TASK: {e}"))?
+}
+
+/// 把数据目录迁到 `<parent>\<leaf>`。
+///
+/// 顺序与 `export_recovery_backup` 一致:先停 Harness 再动文件,锁守卫活到
+/// 任务结束,期间任何安装 / 备份 / 核心切换请求都会排队等待。
+#[tauri::command]
+pub async fn migrate_data_dir(
+ app_handle: AppHandle,
+ parent: String,
+ leaf: String,
+) -> Result<data_dir::MigrationOutcome, String> {
+ let transition = crate::service::workflow::acquire_core_transition().await?;
+ let operation = crate::service::plugin::acquire_operation_lock().await;
+ // 标记要在 `stop()` 之前读:停成功时它会顺手删掉标记,删掉之后就再也查不出
+ // 「崩溃残留、不在 owned 注册表里的 Harness」是否还在写这个目录。
+ let recorded = data_dir::harness_marker(&app_handle);
+ reject_unreadable_marker(recorded)?;
+ crate::service::workflow::stop(app_handle.clone()).await?;
+ confirm_harness_stopped(recorded)?;
+ let app = app_handle.clone();
+ let result = data_dir::migrate(app, PathBuf::from(parent), leaf).await;
+ drop(transition);
+ drop(operation);
+ result
+}
+
+/// 回滚到旧目录备份(`backup` 为空时按「会话数优先、时间戳其次」自动挑选)。
+#[tauri::command]
+pub async fn rollback_data_dir(
+ app_handle: AppHandle,
+ backup: Option<String>,
+) -> Result<data_dir::MigrationOutcome, String> {
+ let transition = crate::service::workflow::acquire_core_transition().await?;
+ let operation = crate::service::plugin::acquire_operation_lock().await;
+ let recorded = data_dir::harness_marker(&app_handle);
+ reject_unreadable_marker(recorded)?;
+ crate::service::workflow::stop(app_handle.clone()).await?;
+ confirm_harness_stopped(recorded)?;
+ let app = app_handle.clone();
+ let result = data_dir::rollback(app, backup.map(PathBuf::from)).await;
+ drop(transition);
+ drop(operation);
+ result
+}
diff --git a/src-tauri/src/bridge/mod.rs b/src-tauri/src/bridge/mod.rs
index 73746836..feef65ff 100644
--- a/src-tauri/src/bridge/mod.rs
+++ b/src-tauri/src/bridge/mod.rs
@@ -8,6 +8,7 @@ pub mod backup;
pub mod clipboard;
pub mod config;
pub mod core;
+pub mod data_dir;
pub mod guard;
pub mod lifecycle;
pub mod pet;
@@ -23,6 +24,7 @@ pub use backup::*;
pub use clipboard::*;
pub use config::*;
pub use core::*;
+pub use data_dir::*;
pub use lifecycle::*;
pub use pet::*;
pub use plugin::*;
diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rs
index 6bb47fd1..a8d4c7ba 100644
--- a/src-tauri/src/config/runtime.rs
+++ b/src-tauri/src/config/runtime.rs
@@ -458,7 +458,7 @@ pub fn get_dsh_package_json_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathB
/// 用户主目录(Windows 取 `%USERPROFILE%`,Unix 取 `$HOME`)。
///
/// 不使用 dirs crate(未引入该依赖),与官方 dsh 的 `$HOME/.dsh` 语义保持一致。
-fn user_home_dir() -> Option<PathBuf> {
+pub(crate) fn user_home_dir() -> Option<PathBuf> {
#[cfg(windows)]
let key = "USERPROFILE";
#[cfg(not(windows))]
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 8dff075b..4cbe0172 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -1538,6 +1538,12 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::open_in_browser,
crate::bridge::copy_service_url,
crate::bridge::reveal_data_dir,
+ crate::bridge::get_data_dir_status,
+ crate::bridge::pick_data_dir,
+ crate::bridge::list_data_dir_entries,
+ crate::bridge::preview_data_dir_migration,
+ crate::bridge::migrate_data_dir,
+ crate::bridge::rollback_data_dir,
crate::bridge::reveal_in_folder,
crate::bridge::open_dir,
crate::bridge::read_service_logs,
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 50e6def2..03be7b2e 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -75,6 +75,9 @@ pub fn run() -> Result<(), String> {
}
// 初始化日志系统
logger::init();
+ // Unix:把持久化的 DSH_HOME 补回进程环境(issue #871)。必须在桌面端装配之前,
+ // 否则首次 get_dsh_data_path 会落到默认目录,日志、store 与 shim 全部写错位置。
+ service::data_dir::restore_process_env();
desktop::builder()
.invoke_handler(desktop::handler())
diff --git a/src-tauri/src/service/cli/mod.rs b/src-tauri/src/service/cli/mod.rs
index 46ba2c7c..3ef49c61 100644
--- a/src-tauri/src/service/cli/mod.rs
+++ b/src-tauri/src/service/cli/mod.rs
@@ -26,7 +26,13 @@ mod path;
mod shim;
pub use core::{ensure, ensure_shims, get_status, remove, CliLinkStatus};
+// 数据目录(issue #871)在 Unix 上复用同一套「标记块 + 备份写回」原语,
+// 免得再抄一份 rc 文件读写的实现。
+#[cfg(unix)]
+pub(crate) use path::{strip_rc_block, upsert_rc_block, write_rc_with_backup};
#[cfg(windows)]
pub(crate) use path::find_user_pnpm_executable;
+#[cfg(windows)]
+pub(crate) use path::{delete_user_env, notify_environment_change, read_user_env, write_user_env};
pub use path::{find_user_pnpm, get_bin_dir, pnpm_env_value};
pub use shim::is_generated_shim;
diff --git a/src-tauri/src/service/cli/path/mod.rs b/src-tauri/src/service/cli/path/mod.rs
index 5159e75a..e7e80a64 100644
--- a/src-tauri/src/service/cli/path/mod.rs
+++ b/src-tauri/src/service/cli/path/mod.rs
@@ -22,10 +22,7 @@ use crate::config::CLI_ROOT_DEV_DIR_NAME;
#[cfg(not(windows))]
use rc::{inject_shell_rc, strip_shell_rc, RC_FILES, RC_MARK_START};
#[cfg(windows)]
-use registry::{
- notify_environment_change, path_contains_token, read_user_path, remove_path_token,
- write_user_path,
-};
+use registry::{path_contains_token, read_user_path, remove_path_token, write_user_path};
mod pnpm;
mod rc;
@@ -34,6 +31,14 @@ mod registry;
#[cfg(windows)]
pub(crate) use pnpm::find_user_pnpm_executable;
+#[cfg(windows)]
+pub(crate) use registry::{
+ delete_user_env, notify_environment_change, read_user_env, write_user_env,
+};
+// 数据目录(issue #871)在 Unix 上复用 rc 的「标记块 + 备份写回」原语,
+// 免得再抄一份 rc 文件读写实现。rc 模块本身是私有的,跨模块用要在这里再导出。
+#[cfg(unix)]
+pub(crate) use rc::{strip_rc_block, upsert_rc_block, write_rc_with_backup};
pub use pnpm::{find_user_pnpm, pnpm_env_value};
/// Windows 下 shim 根目录名(`%LOCALAPPDATA%\<此目录>\bin`)
diff --git a/src-tauri/src/service/cli/path/rc.rs b/src-tauri/src/service/cli/path/rc.rs
index 89a34db4..d5df7961 100644
--- a/src-tauri/src/service/cli/path/rc.rs
+++ b/src-tauri/src/service/cli/path/rc.rs
@@ -43,7 +43,7 @@ pub(super) fn inject_shell_rc(app_handle: &AppHandle) -> Result<(), String> {
))
}
};
- let next = upsert_rc_block(&original, &block);
+ let next = upsert_rc_block(&original, &block, RC_MARK_START, RC_MARK_END);
if next == original {
continue;
}
@@ -73,7 +73,7 @@ pub(super) fn strip_shell_rc(app_handle: &AppHandle) -> Result<(), String> {
))
}
};
- let cleaned = strip_rc_block(&original);
+ let cleaned = strip_rc_block(&original, RC_MARK_START, RC_MARK_END);
if cleaned != original {
write_rc_with_backup(&rc_path, &cleaned)?;
log::info!("Removed PATH export from {}", rc_path.display());
@@ -82,11 +82,20 @@ pub(super) fn strip_shell_rc(app_handle: &AppHandle) -> Result<(), String> {
Ok(())
}
-/// 将 PATH 导出块并入 rc 内容:先移除已有标记块,再在文件末尾追加新块,
+/// 将标记块并入 rc 内容:先移除已有标记块,再在文件末尾追加新块,
/// 只更新自身块、保留用户其余配置,且块始终落在文件末尾。
+///
+/// 标记行由调用方给出而不是写死:同一个 rc 文件里会有多份本应用注入的块
+/// (PATH 导出、`DSH_HOME` 导出),每份块必须只认得自己的标记,否则后写的
+/// 块会把前一份删掉。
#[cfg_attr(windows, allow(dead_code))]
-fn upsert_rc_block(content: &str, block: &str) -> String {
- let mut out = strip_rc_block(content);
+pub(crate) fn upsert_rc_block(
+ content: &str,
+ block: &str,
+ mark_start: &str,
+ mark_end: &str,
+) -> String {
+ let mut out = strip_rc_block(content, mark_start, mark_end);
if !out.is_empty() && !out.ends_with('\n') {
out.push('\n');
}
@@ -101,7 +110,10 @@ fn upsert_rc_block(content: &str, block: &str) -> String {
/// 临时文件 + rename 原子替换;写失败时删除临时文件并回滚备份内容,
/// 保证任何异常路径下用户原文件都不会被半写/被清空。
#[cfg_attr(windows, allow(dead_code))]
-fn write_rc_with_backup(rc_path: &std::path::Path, new_content: &str) -> Result<(), String> {
+pub(crate) fn write_rc_with_backup(
+ rc_path: &std::path::Path,
+ new_content: &str,
+) -> Result<(), String> {
let backup_path = rc_path.with_extension("dsh-backup");
let had_original = rc_path.exists();
if had_original {
@@ -141,17 +153,17 @@ fn write_rc_with_backup(rc_path: &std::path::Path, new_content: &str) -> Result<
/// 移除 rc 文件中的标记块(含标记行本身)。
/// 同时被注入(`upsert_rc_block`)与移除路径使用。
#[cfg_attr(windows, allow(dead_code))]
-fn strip_rc_block(content: &str) -> String {
+pub(crate) fn strip_rc_block(content: &str, mark_start: &str, mark_end: &str) -> String {
let lines = content.lines().peekable();
let mut out = String::with_capacity(content.len());
let mut skipping = false;
for line in lines {
- if line.trim() == RC_MARK_START {
+ if line.trim() == mark_start {
skipping = true;
continue;
}
if skipping {
- if line.trim() == RC_MARK_END {
+ if line.trim() == mark_end {
skipping = false;
}
continue;
@@ -174,7 +186,7 @@ mod tests {
#[test]
fn upsert_keeps_user_content_and_appends_block() {
let content = "# oh-my-zsh\nplugins=(git)\nalias ll='ls -alF'\n";
- let next = upsert_rc_block(content, RC_BLOCK);
+ let next = upsert_rc_block(content, RC_BLOCK, RC_MARK_START, RC_MARK_END);
assert!(next.starts_with(content));
assert!(next.ends_with(RC_BLOCK));
assert_eq!(next.matches(RC_MARK_START).count(), 1);
@@ -184,8 +196,8 @@ mod tests {
#[test]
fn upsert_moves_stale_block_to_end() {
let stale = format!("alias ll='ls -alF'\n{RC_BLOCK}export NVM_DIR=\"$HOME/.nvm\"\n");
- let next = upsert_rc_block(&stale, RC_BLOCK);
- let stripped = strip_rc_block(&next);
+ let next = upsert_rc_block(&stale, RC_BLOCK, RC_MARK_START, RC_MARK_END);
+ let stripped = strip_rc_block(&next, RC_MARK_START, RC_MARK_END);
assert_eq!(
stripped,
"alias ll='ls -alF'\nexport NVM_DIR=\"$HOME/.nvm\"\n"
@@ -198,20 +210,20 @@ mod tests {
#[test]
fn upsert_is_idempotent() {
let content = "user content\n";
- let once = upsert_rc_block(content, RC_BLOCK);
- assert_eq!(upsert_rc_block(&once, RC_BLOCK), once);
+ let once = upsert_rc_block(content, RC_BLOCK, RC_MARK_START, RC_MARK_END);
+ assert_eq!(upsert_rc_block(&once, RC_BLOCK, RC_MARK_START, RC_MARK_END), once);
}
/// 空内容(文件不存在时的新建场景)→ 仅注入块,没有多余空行
#[test]
fn upsert_from_missing_file_creates_block_only() {
- assert_eq!(upsert_rc_block("", RC_BLOCK), RC_BLOCK.to_string());
+ assert_eq!(upsert_rc_block("", RC_BLOCK, RC_MARK_START, RC_MARK_END), RC_BLOCK.to_string());
}
/// 无末尾换行的内容 → 补换行后再追加块
#[test]
fn upsert_handles_missing_trailing_newline() {
- let next = upsert_rc_block("no trailing nl", RC_BLOCK);
+ let next = upsert_rc_block("no trailing nl", RC_BLOCK, RC_MARK_START, RC_MARK_END);
assert_eq!(next, "no trailing nl\n".to_string() + RC_BLOCK);
}
@@ -219,9 +231,9 @@ mod tests {
#[test]
fn strip_rc_block_removes_block_and_is_idempotent() {
let content = format!("keep\n{RC_BLOCK}tail\n");
- let cleaned = strip_rc_block(&content);
+ let cleaned = strip_rc_block(&content, RC_MARK_START, RC_MARK_END);
assert_eq!(cleaned, "keep\ntail\n");
- assert_eq!(strip_rc_block(&cleaned), cleaned);
+ assert_eq!(strip_rc_block(&cleaned, RC_MARK_START, RC_MARK_END), cleaned);
}
/// 写回:备份保留原内容、目标被替换为 new_content
@@ -254,4 +266,27 @@ mod tests {
assert!(!rc_path.with_extension("dsh-backup").exists());
let _ = std::fs::remove_dir_all(&dir);
}
+
+ /// 同一个 rc 文件里可以有多份本应用的块(PATH 与 issue #871 的 DSH_HOME):
+ /// 各自只认得自己的标记,后写的一份不能把前一份删掉。
+ #[test]
+ fn two_blocks_coexist_without_clobbering_each_other() {
+ const HOME_START: &str = "# >>> deepseek-harness dsh home >>>";
+ const HOME_END: &str = "# <<< deepseek-harness dsh home <<<";
+ let home_block = format!("{HOME_START}\nexport DSH_HOME=\"/data/dsh\"\n{HOME_END}\n");
+
+ let both = upsert_rc_block(RC_BLOCK, &home_block, HOME_START, HOME_END);
+ assert!(both.contains(RC_MARK_START));
+ assert!(both.contains(HOME_START));
+
+ let again = upsert_rc_block(&both, RC_BLOCK, RC_MARK_START, RC_MARK_END);
+ assert!(again.contains(HOME_START));
+ assert!(again.contains("export DSH_HOME=\"/data/dsh\""));
+ assert_eq!(again.matches(RC_MARK_START).count(), 1);
+ assert_eq!(again.matches(HOME_START).count(), 1);
+ assert_eq!(
+ upsert_rc_block(&again, RC_BLOCK, RC_MARK_START, RC_MARK_END),
+ again
+ );
+ }
}
diff --git a/src-tauri/src/service/cli/path/registry.rs b/src-tauri/src/service/cli/path/registry.rs
index 31be8fdc..601d1b43 100644
--- a/src-tauri/src/service/cli/path/registry.rs
+++ b/src-tauri/src/service/cli/path/registry.rs
@@ -1,5 +1,10 @@
-//! Windows 注册表辅助:`HKCU\Environment\Path` 读写、`WM_SETTINGCHANGE` 广播
-//! 与 PATH token 展开/匹配。仅 Windows 编译(`mod registry` 已在 mod.rs 门控)。
+//! Windows 注册表辅助:HKCU\\Environment 下用户级环境变量的读取、写入与删除、
+//! WM_SETTINGCHANGE 广播,以及 PATH token 的展开与匹配。仅 Windows 编译
+//! (mod registry 已在 mod.rs 门控)。
+//!
+//! 变量名只是同一个注册表入口的参数:read_user_env / write_user_env /
+//! delete_user_env 是唯一实现;read_user_path / write_user_path 是旧 PATH 语义的
+//! 薄封装,保留 Option<String> 返回值以兼容既有调用方。
/// 将 Rust 字符串转为 Win32 API 需要的 NUL 结尾 UTF-16 缓冲
#[inline]
@@ -7,7 +12,22 @@ pub(super) fn to_wide_null(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
}
+/// 读取用户 PATH。既有调用方以 None 表示读取失败、空串表示未设置,因此把
+/// Ok(None) 映射回空串以保持语义不变。
pub(super) fn read_user_path() -> Option<String> {
+ match read_user_env("Path") {
+ Ok(Some(value)) => Some(value),
+ Ok(None) => Some(String::new()),
+ Err(_) => None,
+ }
+}
+
+/// 读取用户环境变量:Ok(None) 表示该变量未设置,Err 表示注册表读取失败。
+///
+/// 失败必须与「未设置/空值」区分:把读取失败当成空值会让上层覆盖用户已有设置,
+/// PATH 注册逻辑正是靠 None 才敢中止写入。值类型不做限制,REG_SZ 与 REG_EXPAND_SZ
+/// 都按字符串返回,其中的 %VAR% 原样保留。
+pub(crate) fn read_user_env(name: &str) -> Result<Option<String>, String> {
use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_MORE_DATA};
use windows_sys::Win32::System::Registry::{
RegCloseKey, RegOpenKeyExW, RegQueryValueExW, HKEY, HKEY_CURRENT_USER, KEY_QUERY_VALUE,
@@ -25,10 +45,12 @@ pub(super) fn read_user_path() -> Option<String> {
);
if ret != 0 {
log::warn!("failed to open HKCU\\Environment (error {ret})");
- return None;
+ return Err(format!(
+ "REG_OPEN_FAILED: failed to open HKCU\\Environment (error {ret})"
+ ));
}
- let value_name = to_wide_null("Path");
+ let value_name = to_wide_null(name);
let mut value_type: u32 = 0;
let mut size: u32 = 0;
let mut ret = RegQueryValueExW(
@@ -42,12 +64,14 @@ pub(super) fn read_user_path() -> Option<String> {
if ret == ERROR_FILE_NOT_FOUND {
RegCloseKey(hkey);
- return Some(String::new());
+ return Ok(None);
}
if ret != ERROR_MORE_DATA && ret != 0 {
RegCloseKey(hkey);
- log::warn!("failed to query HKCU\\Environment\\Path (error {ret})");
- return None;
+ log::warn!("failed to query HKCU\\Environment\\{name} (error {ret})");
+ return Err(format!(
+ "REG_QUERY_FAILED: failed to query HKCU\\Environment\\{name} (error {ret})"
+ ));
}
let mut buf = vec![0u16; (size as usize / 2).max(1) + 1];
@@ -62,15 +86,27 @@ pub(super) fn read_user_path() -> Option<String> {
RegCloseKey(hkey);
if ret != 0 {
- log::warn!("failed to read HKCU\\Environment\\Path (error {ret})");
- return None;
+ log::warn!("failed to read HKCU\\Environment\\{name} (error {ret})");
+ return Err(format!(
+ "REG_QUERY_FAILED: failed to read HKCU\\Environment\\{name} (error {ret})"
+ ));
}
let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
- Some(String::from_utf16_lossy(&buf[..end]))
+ Ok(Some(String::from_utf16_lossy(&buf[..end])))
}
}
+/// 写入用户 PATH
pub(super) fn write_user_path(new_value: &str) -> Result<(), String> {
+ write_user_env("Path", new_value)
+}
+
+/// 写入(或新建)用户环境变量。
+///
+/// 沿用已有值的数据类型(REG_SZ / REG_EXPAND_SZ);值不存在时按 REG_EXPAND_SZ
+/// 创建,与 Windows 自身写用户环境变量的行为一致。写注册表不会通知已运行的
+/// 进程,需要新值对后续进程生效时由调用方广播 notify_environment_change。
+pub(crate) fn write_user_env(name: &str, value: &str) -> Result<(), String> {
use windows_sys::Win32::System::Registry::{
RegCloseKey, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW, HKEY, HKEY_CURRENT_USER,
KEY_QUERY_VALUE, KEY_SET_VALUE, REG_EXPAND_SZ, REG_SZ,
@@ -92,7 +128,7 @@ pub(super) fn write_user_path(new_value: &str) -> Result<(), String> {
));
}
- let value_name = to_wide_null("Path");
+ let value_name = to_wide_null(name);
let mut value_type: u32 = REG_EXPAND_SZ;
let mut size: u32 = 0;
RegQueryValueExW(
@@ -107,7 +143,7 @@ pub(super) fn write_user_path(new_value: &str) -> Result<(), String> {
value_type = REG_EXPAND_SZ;
}
- let wide_value = to_wide_null(new_value);
+ let wide_value = to_wide_null(value);
let bytes = (wide_value.len() * 2) as u32;
let ret = RegSetValueExW(
hkey,
@@ -121,14 +157,51 @@ pub(super) fn write_user_path(new_value: &str) -> Result<(), String> {
if ret != 0 {
return Err(format!(
- "REG_WRITE_FAILED: failed to write HKCU\\Environment\\Path (error {ret})"
+ "REG_WRITE_FAILED: failed to write HKCU\\Environment\\{name} (error {ret})"
+ ));
+ }
+ Ok(())
+ }
+}
+
+/// 删除用户环境变量;变量本就不存在时视为成功(删除是幂等收尾动作)。
+pub(crate) fn delete_user_env(name: &str) -> Result<(), String> {
+ use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND;
+ use windows_sys::Win32::System::Registry::{
+ RegCloseKey, RegDeleteValueW, RegOpenKeyExW, HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE,
+ };
+
+ unsafe {
+ let mut hkey: HKEY = std::ptr::null_mut();
+ let key_name = to_wide_null("Environment");
+ let ret = RegOpenKeyExW(
+ HKEY_CURRENT_USER,
+ key_name.as_ptr(),
+ 0,
+ KEY_SET_VALUE,
+ &mut hkey,
+ );
+ if ret != 0 {
+ return Err(format!(
+ "REG_OPEN_FAILED: failed to open HKCU\\Environment (error {ret})"
+ ));
+ }
+
+ let value_name = to_wide_null(name);
+ let ret = RegDeleteValueW(hkey, value_name.as_ptr());
+ RegCloseKey(hkey);
+
+ if ret != 0 && ret != ERROR_FILE_NOT_FOUND {
+ return Err(format!(
+ "REG_DELETE_FAILED: failed to delete HKCU\\Environment\\{name} (error {ret})"
));
}
Ok(())
}
}
-pub(super) fn notify_environment_change() {
+/// 广播 WM_SETTINGCHANGE,让资源管理器与后续启动的程序重新读取环境变量
+pub(crate) fn notify_environment_change() {
use windows_sys::Win32::Foundation::{LPARAM, WPARAM};
use windows_sys::Win32::UI::WindowsAndMessaging::{
SendMessageTimeoutW, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE,
@@ -147,7 +220,7 @@ pub(super) fn notify_environment_change() {
}
}
-/// 展开字符串中的 `%VAR%`(Windows)
+/// 展开字符串中的 %VAR%(Windows)
fn expand_env(value: &str) -> String {
use windows_sys::Win32::System::Environment::ExpandEnvironmentStringsW;
let wide = to_wide_null(value);
@@ -160,7 +233,7 @@ fn expand_env(value: &str) -> String {
String::from_utf16_lossy(&buf[..end])
}
-/// PATH 值(`;` 分隔)中是否已包含指定目录(大小写不敏感,先展开 %VAR%)
+/// PATH 值(分号分隔)中是否已包含指定目录(大小写不敏感,先展开 %VAR%)
pub(super) fn path_contains_token(path_value: &str, token: &str) -> bool {
let expanded = expand_env(path_value);
let token_lower = token.to_lowercase();
@@ -169,7 +242,7 @@ pub(super) fn path_contains_token(path_value: &str, token: &str) -> bool {
.any(|p| !p.is_empty() && p.trim_end_matches('\\').to_lowercase() == token_lower)
}
-/// 从 PATH 值中移除指定目录 token(同时处理 `%LOCALAPPDATA%` 未展开形式)
+/// 从 PATH 值中移除指定目录 token(同时处理 %LOCALAPPDATA% 未展开形式)
pub(super) fn remove_path_token(path_value: &str, token: &str) -> String {
let token_lower = token.to_lowercase();
let unexpanded_lower = token_lower.replace(
@@ -190,3 +263,37 @@ pub(super) fn remove_path_token(path_value: &str, token: &str) -> String {
.collect();
kept.join(";")
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn to_wide_null_is_nul_terminated_utf16() {
+ let wide = to_wide_null("D:\\DSHHome");
+ assert_eq!(wide.last().copied(), Some(0));
+ assert_eq!(
+ String::from_utf16_lossy(&wide[..wide.len() - 1]),
+ "D:\\DSHHome"
+ );
+ }
+
+ /// 匹配规则是「整段比较 + 大小写归一 + PATH 项尾部反斜杠归一」,不做前缀匹配:
+ /// D:\\Tools 不应命中 D:\\Tools2,否则注册表写入会误判为「已注册」。
+ /// 归一发生在 PATH 项一侧,因此调用方传入的 token 必须本身不带尾部反斜杠
+ /// (get_bin_dir 由 PathBuf::join 拼出,满足该前提)。
+ #[test]
+ fn path_token_match_normalizes_case_and_trailing_separator() {
+ let value = "C:\\Windows;D:\\Tools\\;E:\\Tools2";
+ assert!(path_contains_token(value, "d:\\tools"));
+ assert!(path_contains_token(value, "D:\\Tools"));
+ assert!(!path_contains_token(value, "D:\\Tool"));
+ assert!(!path_contains_token(value, "E:\\Tool"));
+ }
+
+ #[test]
+ fn remove_path_token_drops_empty_segments() {
+ let value = "C:\\Windows;D:\\Tools;;";
+ assert_eq!(remove_path_token(value, "D:\\Tools"), "C:\\Windows");
+ }
+}
diff --git a/src-tauri/src/service/data_dir/env.rs b/src-tauri/src/service/data_dir/env.rs
new file mode 100644
index 00000000..ab8a4c98
--- /dev/null
+++ b/src-tauri/src/service/data_dir/env.rs
@@ -0,0 +1,247 @@
+//! 数据目录环境变量、默认目录、时间戳与磁盘空间。
+//!
+//! 用户级环境变量的读写按平台分流:
+//! - Windows:复用 CLI 集成模块已泛化的 `service::cli::{read_user_env,
+//! write_user_env, delete_user_env}`,注册表 `HKCU\Environment` 全仓库只有一处
+//! 写点,这里不再造第二份 Windows API 调用;
+//! - macOS / Linux:落点是纯文本(`~/.profile` 标记块、macOS LaunchAgent、
+//! Linux `environment.d`),实现集中在 [`super::unix_env`]。
+//!
+//! 本文件只保留「与平台无关的语义」:默认目录、时间戳格式、可用空间预检,
+//! 三个平台的时间戳与空间探测都必须产出同一形状的结果。
+
+use std::path::PathBuf;
+
+use crate::config::{DSH_HOME_DEV_DIR_NAME, DSH_HOME_DIR_NAME};
+
+/// 数据目录环境变量名(官方 dsh、桌面端与 CLI shim 共用同一个值)
+pub(super) const DATA_DIR_ENV: &str = "DSH_HOME";
+
+/// 未设置 `DSH_HOME` 时的默认数据目录(release `~/.dsh`,debug `~/.dsh.dev`)。
+///
+/// 必须与 `config::get_dsh_data_path` 的默认分支逐字一致:回滚时靠它判断
+/// 「原位置就是默认目录」并据此决定是清空环境变量还是写回一个具体路径。
+pub(super) fn default_home() -> PathBuf {
+ let name = if cfg!(debug_assertions) {
+ DSH_HOME_DEV_DIR_NAME
+ } else {
+ DSH_HOME_DIR_NAME
+ };
+ crate::config::user_home_dir()
+ .map(|home| home.join(name))
+ .unwrap_or_else(|| PathBuf::from(name))
+}
+
+/// 读取用户级 `DSH_HOME`(空白值视为未设置:注册表里可能留着空字符串)。
+#[cfg(windows)]
+pub(super) fn read_user_home() -> Result<Option<String>, String> {
+ Ok(normalize(crate::service::cli::read_user_env(DATA_DIR_ENV)?))
+}
+
+/// Unix:值可能来自进程环境、~/.profile 的标记块或平台自己的会话文件
+/// (macOS LaunchAgent / Linux environment.d),三者由 unix_env 统一处理。
+#[cfg(not(windows))]
+pub(super) fn read_user_home() -> Result<Option<String>, String> {
+ Ok(normalize(super::unix_env::read_value()))
+}
+
+/// 写入用户级 `DSH_HOME` 并广播 `WM_SETTINGCHANGE`。
+///
+/// 广播只影响此后新建的进程:已经在跑的终端不会刷新环境变量,所以迁移完成后
+/// 必须重开终端(面板文案里要写明这一点)。
+#[cfg(windows)]
+pub(super) fn write_user_home(value: &str) -> Result<(), String> {
+ crate::service::cli::write_user_env(DATA_DIR_ENV, value)?;
+ crate::service::cli::notify_environment_change();
+ Ok(())
+}
+
+/// Unix:三处落点一起写(~/.profile 标记块、平台会话文件、当前进程环境),
+/// 详见 unix_env。与 Windows 的注册表广播一样,只影响此后新建的进程。
+#[cfg(not(windows))]
+pub(super) fn write_user_home(value: &str) -> Result<(), String> {
+ super::unix_env::write_value(value)
+}
+
+/// 清除用户级 `DSH_HOME`(回滚到默认目录时用)。
+///
+/// 默认目录不该在注册表里留一条冗余记录:`config::get_dsh_data_path` 在未设置时
+/// 本来就会落到默认目录,写一条指向默认目录的值反而会掩盖用户后来的自定义设置。
+#[cfg(windows)]
+pub(super) fn clear_user_home() -> Result<(), String> {
+ crate::service::cli::delete_user_env(DATA_DIR_ENV)?;
+ crate::service::cli::notify_environment_change();
+ Ok(())
+}
+
+#[cfg(not(windows))]
+pub(super) fn clear_user_home() -> Result<(), String> {
+ super::unix_env::clear_value()
+}
+
+/// 本地时间戳 `yyyy-MM-ddTHH-mm-ss`。
+///
+/// 与恢复脚本的 `Get-Date -Format 'yyyy-MM-ddTHH-mm-ss'` 逐字一致:两边留下的
+/// `.moved-*` 目录必须能互相识别(脚本用正则 `[0-9T-]+` 反推原路径,字符集必须一致)。
+#[cfg(windows)]
+pub(super) fn now_stamp() -> String {
+ use windows_sys::Win32::Foundation::SYSTEMTIME;
+ use windows_sys::Win32::System::SystemInformation::GetLocalTime;
+
+ let mut time: SYSTEMTIME = unsafe { std::mem::zeroed() };
+ unsafe { GetLocalTime(&mut time) };
+ format!(
+ "{:04}-{:02}-{:02}T{:02}-{:02}-{:02}",
+ time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond
+ )
+}
+
+/// Unix:本地时间戳,格式与 Windows 分支逐字一致(`yyyy-MM-ddTHH-mm-ss`)。
+///
+/// 用 `localtime_r` 而不是 UTC:`.moved-*` 目录名要能和用户看到的本地时间对上,
+/// 同一天里的两次迁移也才在肉眼上可排序。取不到本地时间(极端情况下 tzdata 缺失)
+/// 时退回 UTC,**绝不返回空串**——空串会让旧目录名退化成 `.moved-`,
+/// `state::moved_stamp` 与 `find_moved_dirs` 的长度判据随之全部失效。
+#[cfg(not(windows))]
+pub(super) fn now_stamp() -> String {
+ let seconds = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|elapsed| elapsed.as_secs() as libc::time_t)
+ .unwrap_or_default();
+ let mut local: libc::tm = unsafe { std::mem::zeroed() };
+ let filled = unsafe {
+ libc::localtime_r(
+ &seconds as *const libc::time_t,
+ &mut local as *mut libc::tm,
+ )
+ };
+ if !filled.is_null() {
+ return format!(
+ "{:04}-{:02}-{:02}T{:02}-{:02}-{:02}",
+ local.tm_year + 1900,
+ local.tm_mon + 1,
+ local.tm_mday,
+ local.tm_hour,
+ local.tm_min,
+ local.tm_sec
+ );
+ }
+ let utc = time::OffsetDateTime::now_utc();
+ format!(
+ "{:04}-{:02}-{:02}T{:02}-{:02}-{:02}",
+ utc.year(),
+ u8::from(utc.month()),
+ utc.day(),
+ utc.hour(),
+ utc.minute(),
+ utc.second()
+ )
+}
+
+/// 目标所在卷的可用字节数。
+///
+/// 目标目录通常还不存在,因此从最近的存在祖先取卷信息;连祖先都探不到
+/// (相对路径、非法字符)时返回 `None`,调用方跳过预检而不是误报空间不足。
+#[cfg(windows)]
+pub(super) fn free_bytes(path: &std::path::Path) -> Option<u64> {
+ use std::os::windows::ffi::OsStrExt;
+ use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
+
+ let mut probe = path.to_path_buf();
+ while !probe.exists() {
+ probe = probe.parent()?.to_path_buf();
+ }
+ let wide: Vec<u16> = probe
+ .as_os_str()
+ .encode_wide()
+ .chain(std::iter::once(0))
+ .collect();
+ let mut free = 0u64;
+ let ok = unsafe {
+ GetDiskFreeSpaceExW(
+ wide.as_ptr(),
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ &mut free,
+ )
+ };
+ (ok != 0).then_some(free)
+}
+
+/// Unix:`statvfs` 取目标所在文件系统的可用字节数(与 Windows 的 `GetDiskFreeSpaceExW`
+/// 同款语义:从最近的存在祖先取卷信息)。
+#[cfg(not(windows))]
+pub(super) fn free_bytes(path: &std::path::Path) -> Option<u64> {
+ use std::ffi::CString;
+ use std::os::unix::ffi::OsStrExt;
+
+ let mut probe = path.to_path_buf();
+ while !probe.exists() {
+ probe = probe.parent()?.to_path_buf();
+ }
+ let c_path = CString::new(probe.as_os_str().as_bytes()).ok()?;
+ let mut stats: libc::statvfs = unsafe { std::mem::zeroed() };
+ if unsafe { libc::statvfs(c_path.as_ptr(), &mut stats) } != 0 {
+ return None;
+ }
+ // f_bavail 是非特权用户可用块数、f_frsize 是块大小;先转 u64 再乘,
+ // 免得在 32 位平台上先乘后溢出。
+ Some((stats.f_bavail as u64).saturating_mul(stats.f_frsize as u64))
+}
+
+/// 空白字符串统一视为「未设置」。
+fn normalize(value: Option<String>) -> Option<String> {
+ value
+ .map(|text| text.trim().to_string())
+ .filter(|text| !text.is_empty())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn normalize_treats_blank_as_unset() {
+ assert_eq!(normalize(Some(" ".to_string())), None);
+ assert_eq!(normalize(Some(String::new())), None);
+ assert_eq!(normalize(None), None);
+ assert_eq!(
+ normalize(Some(" D:\\DSHHome ".to_string())),
+ Some("D:\\DSHHome".to_string())
+ );
+ }
+
+ #[test]
+ fn default_home_matches_the_build_mode() {
+ let home = default_home();
+ let expected = if cfg!(debug_assertions) {
+ DSH_HOME_DEV_DIR_NAME
+ } else {
+ DSH_HOME_DIR_NAME
+ };
+ assert_eq!(home.file_name().unwrap().to_str().unwrap(), expected);
+ }
+
+ #[test]
+ fn stamp_has_the_script_compatible_shape() {
+ let stamp = now_stamp();
+ // yyyy-MM-ddTHH-mm-ss:脚本用 [0-9T-]+ 匹配,字符集必须完全一致,
+ // 且三个平台都要真的产出时间戳(Unix 曾经返回空串,旧目录名会退化成
+ // `.moved-`,`find_moved_dirs` 的长度判据随之失效)。
+ assert_eq!(stamp.len(), 19);
+ assert!(stamp
+ .chars()
+ .all(|c| c.is_ascii_digit() || c == 'T' || c == '-'));
+ assert_eq!(&stamp[10..11], "T");
+ }
+
+ #[test]
+ fn free_bytes_probes_the_nearest_existing_ancestor() {
+ let missing = std::env::temp_dir()
+ .join("dsh-data-dir-not-created")
+ .join("deep");
+ let free = free_bytes(&missing);
+ assert!(free.is_some_and(|bytes| bytes > 0));
+ assert_eq!(free_bytes(std::path::Path::new("relative-only")), None);
+ }
+}
diff --git a/src-tauri/src/service/data_dir/fs_ops.rs b/src-tauri/src/service/data_dir/fs_ops.rs
new file mode 100644
index 00000000..aabeeb28
--- /dev/null
+++ b/src-tauri/src/service/data_dir/fs_ops.rs
@@ -0,0 +1,345 @@
+//! 迁移用文件系统动作:树统计、递归复制、重复解析点重建。
+//!
+//! 全部以 `&Path` 为参数、不接触 `AppHandle`:仓库里没有 `tauri::test`,任何需要
+//! `AppHandle` 的函数都无法单测,而迁移是「一次写错就丢数据」的逻辑,必须能在
+//! 临时目录里被完整驱动(见本模块测试与 `mod.rs` 的用例)。
+
+use rayon::prelude::*;
+use std::fs;
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+/// 迁移时不复制的运行时产物。
+///
+/// `.harness.pid` 记录的是「即将被停止的进程」,复制到新目录只会让下一次启动的
+/// 孤儿清扫读到一条指向旧进程的记录;它由启动流程重新写入。
+pub(super) const SKIP_NAMES: [&str; 1] = [".harness.pid"];
+
+/// 每复制多少个文件回报一次进度:约 900MB / 2.6 万文件的一次迁移,
+/// 逐文件发事件会淹没 IPC。
+const PROGRESS_EVERY_FILES: u64 = 256;
+
+/// 目录树统计。`links` 单列:重复解析点不复制内容,因此不参与「文件数 + 字节数」
+/// 校验,但必须让用户知道有多少条链接需要重建。
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub(super) struct TreeStats {
+ pub files: u64,
+ pub bytes: u64,
+ pub links: u64,
+}
+
+impl TreeStats {
+ /// 复制是否覆盖了源:文件数或字节数任一少于源即视为不完整。
+ ///
+ /// 只用「不少于」而不是「相等」:迁移期间用户可能有程序在往源目录写新文件,
+ /// 目标比源多不算失败;目标比源少才是真丢数据。
+ pub(super) fn covers(&self, source: &TreeStats) -> bool {
+ self.files >= source.files && self.bytes >= source.bytes
+ }
+}
+
+/// 是否为重复解析点(Windows 符号链接、目录联接、挂载点)。
+///
+/// 必须用 `symlink_metadata` + `FILE_ATTRIBUTE_REPARSE_POINT` 判定,不能只看
+/// `FileType::is_symlink()`:目录联接在部分路径上并不报告为 symlink,跟随它递归
+/// 会复制链接目标(pnpm store)的数据,递归删除时更会删掉链接目标里的真实数据
+/// ——这正是 issue #848 的成因。
+#[cfg(windows)]
+fn is_reparse_point(meta: &fs::Metadata) -> bool {
+ use std::os::windows::fs::MetadataExt;
+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
+ meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
+}
+
+#[cfg(not(windows))]
+fn is_reparse_point(meta: &fs::Metadata) -> bool {
+ meta.file_type().is_symlink()
+}
+
+/// 运行时产物判定(文件名非 UTF-8 时不跳过,宁可多复制一个文件也不漏数据)。
+fn is_skipped(name: &str) -> bool {
+ SKIP_NAMES.contains(&name)
+}
+
+/// 递归统计目录树(跳过运行时产物,不跟随重复解析点)。
+pub(super) fn scan_tree(root: &Path, stats: &mut TreeStats) -> Result<(), String> {
+ let read_dir =
+ fs::read_dir(root).map_err(|e| format!("DATA_DIR_SCAN_READ: {}: {e}", root.display()))?;
+ for entry in read_dir {
+ let entry = entry.map_err(|e| format!("DATA_DIR_SCAN_ENTRY: {e}"))?;
+ let name = entry.file_name();
+ if name.to_str().map(is_skipped).unwrap_or(false) {
+ continue;
+ }
+ let path = entry.path();
+ let meta = fs::symlink_metadata(&path)
+ .map_err(|e| format!("DATA_DIR_SCAN_META: {}: {e}", path.display()))?;
+ if is_reparse_point(&meta) {
+ stats.links += 1;
+ } else if meta.is_dir() {
+ scan_tree(&path, stats)?;
+ } else if meta.is_file() {
+ stats.files += 1;
+ stats.bytes += meta.len();
+ }
+ }
+ Ok(())
+}
+
+/// 复制进度:并行分支共享的计数器 + 节流后的回调。
+pub(super) struct CopyProgress<'a> {
+ files: AtomicU64,
+ bytes: AtomicU64,
+ links: AtomicU64,
+ on_tick: &'a (dyn Fn(u64, u64) + Send + Sync),
+}
+
+impl<'a> CopyProgress<'a> {
+ pub(super) fn new(on_tick: &'a (dyn Fn(u64, u64) + Send + Sync)) -> Self {
+ Self {
+ files: AtomicU64::new(0),
+ bytes: AtomicU64::new(0),
+ links: AtomicU64::new(0),
+ on_tick,
+ }
+ }
+
+ /// 已复制的累计量(复制结束后即为目标树的实际内容量)。
+ pub(super) fn stats(&self) -> TreeStats {
+ TreeStats {
+ files: self.files.load(Ordering::Relaxed),
+ bytes: self.bytes.load(Ordering::Relaxed),
+ links: self.links.load(Ordering::Relaxed),
+ }
+ }
+
+ fn record_file(&self, bytes: u64) {
+ let files = self.files.fetch_add(1, Ordering::Relaxed) + 1;
+ let total = self.bytes.fetch_add(bytes, Ordering::Relaxed) + bytes;
+ if files % PROGRESS_EVERY_FILES == 0 {
+ (self.on_tick)(files, total);
+ }
+ }
+
+ fn record_link(&self) {
+ self.links.fetch_add(1, Ordering::Relaxed);
+ }
+}
+
+/// 递归复制目录树到 `dst`(目标必须已存在或可创建,且不得是源的子孙)。
+///
+/// 顶层条目并行处理(同 `service::profile::copy_dir_tree`):pnpm 档案下
+/// `node_modules` 层级深、文件多,串行复制会让 900MB 的迁移明显变慢。
+pub(super) fn copy_tree(src: &Path, dst: &Path, progress: &CopyProgress) -> Result<(), String> {
+ fs::create_dir_all(dst).map_err(|e| format!("DATA_DIR_COPY_MKDIR: {}: {e}", dst.display()))?;
+ let read_dir =
+ fs::read_dir(src).map_err(|e| format!("DATA_DIR_COPY_READ: {}: {e}", src.display()))?;
+ let entries: Vec<fs::DirEntry> = read_dir
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|e| format!("DATA_DIR_COPY_ENTRY: {e}"))?;
+ entries.par_iter().try_for_each(|entry| -> Result<(), String> {
+ let name = entry.file_name();
+ if name.to_str().map(is_skipped).unwrap_or(false) {
+ return Ok(());
+ }
+ let src_path = entry.path();
+ let dst_path = dst.join(&name);
+ let meta = fs::symlink_metadata(&src_path)
+ .map_err(|e| format!("DATA_DIR_COPY_META: {}: {e}", src_path.display()))?;
+ if is_reparse_point(&meta) {
+ copy_link(&src_path, &dst_path);
+ progress.record_link();
+ } else if meta.is_dir() {
+ copy_tree(&src_path, &dst_path, progress)?;
+ } else if meta.is_file() {
+ fs::copy(&src_path, &dst_path)
+ .map_err(|e| format!("DATA_DIR_COPY_FILE: {}: {e}", src_path.display()))?;
+ progress.record_file(meta.len());
+ }
+ Ok(())
+ })
+}
+
+/// 重建一条重复解析点(best-effort)。
+///
+/// 不跟随链接:pnpm 的 `node_modules` 链接指向全局 store,跟随复制既会成倍放大
+/// 数据量,也会让新旧目录共享同一份文件。重建失败(Windows 创建符号链接需要
+/// 权限或开发者模式)只告警、不阻断迁移——链接可以由插件重装流程重建,
+/// 而数据文件不能重来。
+fn copy_link(src: &Path, dst: &Path) {
+ let Ok(target) = fs::read_link(src) else {
+ log::warn!("DATA_DIR_COPY_LINK_READ: {}", src.display());
+ return;
+ };
+ #[cfg(unix)]
+ let created = std::os::unix::fs::symlink(&target, dst);
+ #[cfg(windows)]
+ let created = std::os::windows::fs::symlink_dir(&target, dst)
+ .or_else(|_| std::os::windows::fs::symlink_file(&target, dst));
+ if let Err(error) = created {
+ log::warn!("DATA_DIR_COPY_LINK_CREATE: {}: {error}", dst.display());
+ }
+}
+
+/// 目录不存在或为空 → true。
+///
+/// 读不到目录时返回 false(当成非空):回滚时据此决定「删掉空目录」还是「挪到
+/// 一边」,宁可多留一份,也不冒删数据的风险。
+pub(super) fn is_dir_empty(path: &Path) -> bool {
+ if fs::symlink_metadata(path).is_err() {
+ return true;
+ }
+ match fs::read_dir(path) {
+ Ok(mut entries) => entries.next().is_none(),
+ Err(_) => false,
+ }
+}
+
+/// `<home>/sessions` 下递归匹配 `session-*` 的目录数(与恢复脚本同口径)。
+///
+/// 只枚举目录、不读文件,因此可以在状态查询里对每个候选备份调用。
+pub(super) fn count_sessions(home: &Path) -> u64 {
+ fn walk(dir: &Path, count: &mut u64) {
+ let Ok(read_dir) = fs::read_dir(dir) else {
+ return;
+ };
+ for entry in read_dir.flatten() {
+ let Ok(meta) = fs::symlink_metadata(entry.path()) else {
+ continue;
+ };
+ if is_reparse_point(&meta) || !meta.is_dir() {
+ continue;
+ }
+ if entry
+ .file_name()
+ .to_str()
+ .map(|name| name.starts_with("session-"))
+ .unwrap_or(false)
+ {
+ *count += 1;
+ }
+ walk(&entry.path(), count);
+ }
+ }
+ let mut count = 0;
+ walk(&home.join("sessions"), &mut count);
+ count
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+
+ fn temp_dir(tag: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "dsh-data-dir-{tag}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0)
+ ));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ fn write(path: &Path, text: &str) {
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent).unwrap();
+ }
+ fs::write(path, text).unwrap();
+ }
+
+ #[test]
+ fn scan_tree_counts_files_and_bytes_and_skips_runtime_marker() {
+ let root = temp_dir("scan");
+ write(&root.join("a.txt"), "12345");
+ write(&root.join("nested/b.txt"), "123");
+ write(&root.join(SKIP_NAMES[0]), "99999999");
+
+ let mut stats = TreeStats::default();
+ scan_tree(&root, &mut stats).unwrap();
+
+ assert_eq!(stats.files, 2);
+ assert_eq!(stats.bytes, 8);
+ assert_eq!(stats.links, 0);
+ let _ = fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn copy_tree_reproduces_content_and_reports_totals() {
+ let root = temp_dir("copy");
+ let src = root.join("src");
+ let dst = root.join("dst");
+ write(&src.join("a.txt"), "12345");
+ write(&src.join("nested/b.txt"), "123");
+ write(&src.join(SKIP_NAMES[0]), "99999999");
+
+ let tick = |_files: u64, _bytes: u64| {};
+ let progress = CopyProgress::new(&tick);
+ copy_tree(&src, &dst, &progress).unwrap();
+
+ let stats = progress.stats();
+ assert_eq!(stats.files, 2);
+ assert_eq!(stats.bytes, 8);
+ assert_eq!(fs::read_to_string(dst.join("nested/b.txt")).unwrap(), "123");
+ // 运行时产物不随迁移走:目标目录里不该出现 PID 标记
+ assert!(!dst.join(SKIP_NAMES[0]).exists());
+
+ let mut verified = TreeStats::default();
+ scan_tree(&dst, &mut verified).unwrap();
+ assert!(verified.covers(&stats));
+ let _ = fs::remove_dir_all(&root);
+ }
+
+ /// 目标目录已存在且有内容时也必须完成复制:调用方(迁移)负责先判定「目标必须
+ /// 为空或不存在」,复制本身不做这个判断,避免两处规则不一致。
+ #[test]
+ fn copy_tree_into_existing_empty_directory_succeeds() {
+ let root = temp_dir("copy-existing");
+ let src = root.join("src");
+ let dst = root.join("dst");
+ write(&src.join("a.txt"), "1");
+ fs::create_dir_all(&dst).unwrap();
+
+ let tick = |_files: u64, _bytes: u64| {};
+ let progress = CopyProgress::new(&tick);
+ copy_tree(&src, &dst, &progress).unwrap();
+
+ assert_eq!(fs::read_to_string(dst.join("a.txt")).unwrap(), "1");
+ let _ = fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn is_dir_empty_distinguishes_missing_empty_and_filled() {
+ let root = temp_dir("empty");
+ assert!(is_dir_empty(&root.join("missing")));
+ assert!(is_dir_empty(&root));
+ write(&root.join("a.txt"), "1");
+ assert!(!is_dir_empty(&root));
+ let _ = fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn count_sessions_matches_nested_session_directories() {
+ let root = temp_dir("sessions");
+ write(&root.join("sessions/--C-a--/session-1/x.jsonl"), "{}");
+ write(&root.join("sessions/--C-a--/session-2/x.jsonl"), "{}");
+ write(&root.join("sessions/--C-b--/not-a-session/x.jsonl"), "{}");
+ write(&root.join("other/session-9/x.jsonl"), "{}");
+
+ assert_eq!(count_sessions(&root), 2);
+ let _ = fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn covers_requires_target_not_smaller_than_source() {
+ let source = TreeStats { files: 10, bytes: 100, links: 0 };
+ assert!(TreeStats { files: 10, bytes: 100, links: 0 }.covers(&source));
+ assert!(TreeStats { files: 11, bytes: 100, links: 0 }.covers(&source));
+ assert!(!TreeStats { files: 10, bytes: 99, links: 0 }.covers(&source));
+ assert!(!TreeStats { files: 9, bytes: 100, links: 0 }.covers(&source));
+ }
+}
diff --git a/src-tauri/src/service/data_dir/migrate.rs b/src-tauri/src/service/data_dir/migrate.rs
new file mode 100644
index 00000000..f0dfd90c
--- /dev/null
+++ b/src-tauri/src/service/data_dir/migrate.rs
@@ -0,0 +1,630 @@
+//! 迁移与回滚的编排:校验、复制、改名、改写环境变量。
+//!
+//! 每一步的失败处理都必须能回答「现在数据在哪、用户还能不能找回来」,因此:
+//! - 校验失败:什么都没动;
+//! - 复制/校验失败:目标留着(可能只是磁盘满),源目录原样不动;
+//! - 改名之后失败:把源目录改回来,环境变量与记录文件同步复原。
+
+use std::fs;
+use std::path::{Component, Path, PathBuf};
+use tauri::AppHandle;
+
+use super::env;
+use super::fs_ops::{self, CopyProgress, TreeStats};
+use super::state;
+use super::{
+ harness_stopped, MigrationBackup, MigrationOutcome, MigrationPlan, ProgressPayload,
+ ProgressSink,
+};
+
+/// 预留的磁盘空间余量(百分比):把目标卷填到 0 字节会让系统与其它程序一起失灵。
+const SPACE_MARGIN_PERCENT: u64 = 5;
+
+/// 发现可回滚的旧目录备份。
+///
+/// 搜索三处(issue E):当前数据目录旁边、默认目录旁边、上次迁移记录的原位置旁边。
+/// 跨盘搬家时旧目录留在原盘,既不在当前目录旁边也不在默认目录旁边,只有第三处能找到。
+/// 排序用「会话数优先、时间戳其次」(issue G):会话是用户唯一无法重建的数据,
+/// 一个没有会话的新备份不该盖过旧备份被自动选中。
+pub(super) fn find_backups(app_handle: &AppHandle, current: &Path) -> Vec<MigrationBackup> {
+ let default = env::default_home();
+ let recorded = state::read_last_migration(app_handle).map(PathBuf::from);
+ let mut backups: Vec<MigrationBackup> =
+ collect_backups(&search_places(current, &default, recorded.as_deref()))
+ .into_iter()
+ .map(|path| MigrationBackup {
+ sessions: fs_ops::count_sessions(&path),
+ stamp: stamp_of(&path),
+ path: path.to_string_lossy().into_owned(),
+ })
+ .collect();
+ backups.sort_by(|a, b| {
+ b.sessions
+ .cmp(&a.sessions)
+ .then_with(|| b.stamp.cmp(&a.stamp))
+ });
+ backups
+}
+
+/// 三个搜索位置:当前数据目录、默认目录、上次迁移记录的原位置(去重且保持顺序)。
+fn search_places(current: &Path, default: &Path, recorded: Option<&Path>) -> Vec<PathBuf> {
+ let mut places: Vec<PathBuf> = Vec::new();
+ for path in [Some(current), Some(default), recorded].into_iter().flatten() {
+ if !places.iter().any(|seen| same_path(seen, path)) {
+ places.push(path.to_path_buf());
+ }
+ }
+ places
+}
+
+/// 逐个位置找**该位置自己的**同名备份目录。
+///
+/// 备份名里带的是「被搬走的那个目录」的名字(`~/.dsh` → `~/.dsh.moved-<时间戳>`),
+/// 所以每个位置必须用各自的目录名去匹配。统一用当前位置的名字去找,会把「从默认目录
+/// 搬走」这类最常见的备份全部漏掉——面板上连回滚入口都不会出现(issue E)。
+fn collect_backups(places: &[PathBuf]) -> Vec<PathBuf> {
+ let mut found: Vec<PathBuf> = Vec::new();
+ for place in places {
+ let Some(leaf) = place.file_name().and_then(|name| name.to_str()) else {
+ continue;
+ };
+ let Some(dir) = place.parent() else {
+ continue;
+ };
+ for (candidate, _) in state::find_moved_dirs(dir, leaf) {
+ if !found.contains(&candidate) {
+ found.push(candidate);
+ }
+ }
+ }
+ found
+}
+
+/// 迁移预检:目标合法性、体积与磁盘空间。
+///
+/// 这里**不**检查 Harness 是否已退出:预检是只读的(`preview_data_dir_migration` 不停服),
+/// 而用户点「预检」时 Harness 通常正在运行。停服由迁移命令本身完成,真正的安全网在
+/// [`run`] 开头——那里一定已经停服,且是动手改盘前的最后一道检查。
+pub(super) fn plan(
+ app_handle: &AppHandle,
+ source: &Path,
+ target: &Path,
+) -> Result<MigrationPlan, String> {
+ validate_target(source, target)?;
+ let mut stats = TreeStats::default();
+ fs_ops::scan_tree(source, &mut stats)?;
+ let free = env::free_bytes(target);
+ let needed = stats.bytes + stats.bytes / 100 * SPACE_MARGIN_PERCENT;
+ let remembered = state::read_last_migration(app_handle)
+ .map(PathBuf::from)
+ .is_some_and(|recorded| same_path(&recorded, target));
+ Ok(MigrationPlan {
+ source: source.to_string_lossy().into_owned(),
+ target: target.to_string_lossy().into_owned(),
+ total_files: stats.files,
+ total_bytes: stats.bytes,
+ links: stats.links,
+ target_free_bytes: free.unwrap_or(0),
+ enough_space: free.is_none_or(|available| available >= needed),
+ parent_exists: target.parent().is_some_and(Path::exists),
+ remembered,
+ })
+}
+
+/// 执行迁移:复制 → 校验 → 旧目录改名 → 记录原位置 → 改写用户级 `DSH_HOME`。
+///
+/// 顺序刻意如此:改名与环境变量写在最后,前面任何一步失败都不会让用户失去原目录。
+pub(super) fn run(
+ app_handle: &AppHandle,
+ source: &Path,
+ target: &Path,
+ emit: ProgressSink<'_>,
+) -> Result<MigrationOutcome, String> {
+ // 动手前的最后一道安全网:调用方(`data_dir::migrate`)已经停过服,这里再确认一次,
+ // 避免 Harness 在停服与迁移之间被重新拉起。
+ if !harness_stopped(app_handle) {
+ return Err(format!(
+ "DATA_DIR_HARNESS_RUNNING: {} 仍在使用数据目录",
+ source.display()
+ ));
+ }
+ emit(step("migrate", "scan", 0, 0, 0, 0));
+ let mut expected = TreeStats::default();
+ fs_ops::scan_tree(source, &mut expected)?;
+
+ let tick = |files: u64, bytes: u64| {
+ emit(step("migrate", "copy", files, bytes, expected.files, expected.bytes));
+ };
+ let progress = CopyProgress::new(&tick);
+ fs_ops::copy_tree(source, target, &progress)?;
+ let copied = progress.stats();
+
+ emit(step("migrate", "verify", copied.files, copied.bytes, expected.files, expected.bytes));
+ let mut actual = TreeStats::default();
+ fs_ops::scan_tree(target, &mut actual)?;
+ if !actual.covers(&expected) {
+ // 目标少于源:绝不继续改名,也绝不删目标(可能只是磁盘满,用户能腾出空间重试)
+ return Err(format!(
+ "DATA_DIR_COPY_INCOMPLETE: {} -> {}: {} files/{} bytes, expected {} files/{} bytes",
+ source.display(),
+ target.display(),
+ actual.files,
+ actual.bytes,
+ expected.files,
+ expected.bytes
+ ));
+ }
+
+ emit(step("migrate", "finalize", copied.files, copied.bytes, expected.files, expected.bytes));
+ let stamp = env::now_stamp();
+ let moved = state::with_moved_suffix(source, &stamp)?;
+ // 记录先写:跨盘搬家后旧目录留在原盘,只有这条记录能把它找回来(issue E)
+ state::write_last_migration(app_handle, &source.to_string_lossy())?;
+ fs::rename(source, &moved)
+ .map_err(|e| format!("DATA_DIR_RENAME: {} -> {}: {e}", source.display(), moved.display()))?;
+
+ let text = target.to_string_lossy().into_owned();
+ if let Err(error) = env::write_user_home(&text) {
+ // 环境变量写不进去:把旧目录改回原名,用户至少还能从原来的位置启动
+ if let Err(restore) = fs::rename(&moved, source) {
+ log::error!("DATA_DIR_RENAME_BACK: {}: {restore}", moved.display());
+ }
+ return Err(error);
+ }
+ // 本进程立刻生效:后续 get_dsh_data_path / shim 生成 / 拉起的 Harness 都读新值
+ std::env::set_var(env::DATA_DIR_ENV, &text);
+ refresh_shims(app_handle, target);
+
+ emit(step("migrate", "done", copied.files, copied.bytes, expected.files, expected.bytes));
+ Ok(MigrationOutcome {
+ source: source.to_string_lossy().into_owned(),
+ target: text,
+ moved_to: moved.to_string_lossy().into_owned(),
+ files: copied.files,
+ bytes: copied.bytes,
+ links: copied.links,
+ sessions: fs_ops::count_sessions(target),
+ })
+}
+
+/// 回滚到旧目录备份。
+///
+/// `backup` 为空时按 `find_backups` 的顺序取第一个(会话数优先、时间戳其次,与恢复
+/// 脚本同一规则)。当前数据目录不会被删除——脚本同样只提示、不删除,两份数据同时
+/// 存在才是「一键回滚」敢按下去的前提。
+pub(super) fn rollback(
+ app_handle: &AppHandle,
+ current: &Path,
+ backup: Option<&Path>,
+ emit: ProgressSink<'_>,
+) -> Result<MigrationOutcome, String> {
+ if !harness_stopped(app_handle) {
+ return Err(format!(
+ "DATA_DIR_HARNESS_RUNNING: {} 仍在使用数据目录",
+ current.display()
+ ));
+ }
+ emit(step("rollback", "scan", 0, 0, 0, 0));
+
+ let chosen = match backup {
+ Some(explicit) => explicit.to_path_buf(),
+ None => find_backups(app_handle, current)
+ .first()
+ .map(|item| PathBuf::from(&item.path))
+ .ok_or_else(|| format!("DATA_DIR_NO_BACKUP: {}", current.display()))?,
+ };
+ if !chosen.is_dir() {
+ return Err(format!("DATA_DIR_BACKUP_MISSING: {}", chosen.display()));
+ }
+ let restore_to = state::original_of(&chosen)
+ .ok_or_else(|| format!("DATA_DIR_BACKUP_NAME_INVALID: {}", chosen.display()))?;
+
+ // 目标非空时先挪到一边(issue F):直接覆盖会把用户当前的数据删掉
+ let stamp = env::now_stamp();
+ let aside = if fs_ops::is_dir_empty(&restore_to) {
+ if restore_to.exists() {
+ fs::remove_dir(&restore_to).map_err(|e| {
+ format!("DATA_DIR_ROLLBACK_CLEAR: {}: {e}", restore_to.display())
+ })?;
+ }
+ String::new()
+ } else {
+ let target = state::with_current_suffix(&restore_to, &stamp)?;
+ fs::rename(&restore_to, &target).map_err(|e| {
+ format!("DATA_DIR_ROLLBACK_ASIDE: {}: {e}", restore_to.display())
+ })?;
+ target.to_string_lossy().into_owned()
+ };
+
+ emit(step("rollback", "finalize", 0, 0, 0, 0));
+ if let Some(parent) = restore_to.parent() {
+ fs::create_dir_all(parent).map_err(|e| format!("DATA_DIR_ROLLBACK_MKDIR: {e}"))?;
+ }
+ if let Err(error) = fs::rename(&chosen, &restore_to) {
+ if !aside.is_empty() {
+ let _ = fs::rename(&aside, &restore_to);
+ }
+ return Err(format!(
+ "DATA_DIR_ROLLBACK_MOVE: {} -> {}: {error}",
+ chosen.display(),
+ restore_to.display()
+ ));
+ }
+
+ // 回到默认目录就清掉变量:默认目录不该在注册表里留一条冗余记录
+ let back_to_default = same_path(&restore_to, &env::default_home());
+ let apply = |text: &str| {
+ if back_to_default {
+ let cleared = env::clear_user_home();
+ if cleared.is_ok() {
+ std::env::remove_var(env::DATA_DIR_ENV);
+ }
+ cleared
+ } else {
+ let written = env::write_user_home(text);
+ if written.is_ok() {
+ std::env::set_var(env::DATA_DIR_ENV, text);
+ }
+ written
+ }
+ };
+ rewrite_env_or_undo(&chosen, &restore_to, &aside, apply)?;
+ if let Err(error) = state::write_last_migration(app_handle, "") {
+ log::warn!("DATA_DIR_STATE_CLEAR: {error}");
+ }
+ refresh_shims(app_handle, &restore_to);
+
+ let mut stats = TreeStats::default();
+ if let Err(error) = fs_ops::scan_tree(&restore_to, &mut stats) {
+ log::warn!("DATA_DIR_ROLLBACK_SCAN: {error}");
+ }
+ emit(step("rollback", "done", stats.files, stats.bytes, stats.files, stats.bytes));
+ Ok(MigrationOutcome {
+ source: current.to_string_lossy().into_owned(),
+ target: restore_to.to_string_lossy().into_owned(),
+ moved_to: aside,
+ files: stats.files,
+ bytes: stats.bytes,
+ links: stats.links,
+ sessions: fs_ops::count_sessions(&restore_to),
+ })
+}
+
+/// 回滚最后一步:改写用户级 `DSH_HOME`;写失败就把已经搬动的两个目录放回去再报错。
+///
+/// 这一步是「文件已经搬完」之后唯一还可能失败的动作:直接返回会让 `DSH_HOME` 继续
+/// 指着那个刚被搬空的目录,下次启动就在那儿建一份空数据(用户看到的是「会话全
+/// 没了」)。所以先复原现场再报错。
+///
+/// 真正调注册表 / 广播 `WM_SETTINGCHANGE` 的动作由调用方以 `apply` 传进来:注册表是
+/// 机器级状态,单元测试不能真去改它(会污染跑测试的那台机器、也让断言依赖当前值),
+/// 而「写失败时到底有没有复原」恰恰是必须被真正执行到的那条路径。
+fn rewrite_env_or_undo<F>(
+ chosen: &Path,
+ restore_to: &Path,
+ aside: &str,
+ apply: F,
+) -> Result<(), String>
+where
+ F: FnOnce(&str) -> Result<(), String>,
+{
+ if let Err(error) = apply(&restore_to.to_string_lossy()) {
+ undo_rollback(chosen, restore_to, aside);
+ return Err(error);
+ }
+ Ok(())
+}
+
+/// 回滚中途失败时的复原:把备份放回 `chosen`,再把挪到一边的当前目录放回原位。
+///
+/// 两步的先后不能反:`restore_to` 得先空出来,`aside` 才搬得回去。这一步失败时
+/// 只记日志——此时已经没有任何「更正确」的落点,把现场留在原地比继续搬动更好。
+fn undo_rollback(chosen: &Path, restore_to: &Path, aside: &str) {
+ if let Err(error) = fs::rename(restore_to, chosen) {
+ log::error!("DATA_DIR_ROLLBACK_UNDO: {}: {error}", restore_to.display());
+ return;
+ }
+ if aside.is_empty() {
+ return;
+ }
+ if let Err(error) = fs::rename(Path::new(aside), restore_to) {
+ log::error!("DATA_DIR_ROLLBACK_UNDO_ASIDE: {aside}: {error}");
+ }
+}
+
+/// 目标合法性:不能是源自己、不能互相嵌套、必须为空或不存在。
+///
+/// 嵌套会让「复制 + 校验」在源目录里凭空多出一份自己(递归放大),也让改名后的
+/// 备份目录落在源目录内部——两边都无法收拾。
+fn validate_target(source: &Path, target: &Path) -> Result<(), String> {
+ if !target.is_absolute() {
+ return Err(format!("DATA_DIR_TARGET_NOT_ABSOLUTE: {}", target.display()));
+ }
+ if same_path(source, target) {
+ return Err(format!("DATA_DIR_SAME_AS_SOURCE: {}", target.display()));
+ }
+ if is_within(target, source) {
+ return Err(format!(
+ "DATA_DIR_TARGET_INSIDE_SOURCE: {}",
+ target.display()
+ ));
+ }
+ if is_within(source, target) {
+ return Err(format!("DATA_DIR_SOURCE_INSIDE_TARGET: {}", target.display()));
+ }
+ if target.is_file() {
+ return Err(format!("DATA_DIR_TARGET_NOT_DIR: {}", target.display()));
+ }
+ if !fs_ops::is_dir_empty(target) {
+ return Err(format!("DATA_DIR_TARGET_NOT_EMPTY: {}", target.display()));
+ }
+ Ok(())
+}
+
+/// 重写 CLI shim 与 pnpm 元数据(best-effort)。
+///
+/// shim 内容里烘焙着 `DSH_HOME`,不改写的话终端里的 `dsh` 仍指向旧目录;pnpm 的
+/// `node_modules` 元数据带绝对路径,不修正会在下一次插件安装时被当成损坏的 store。
+/// 两者都只是「改了更好」,失败不能把已经成功的迁移判成失败。
+fn refresh_shims(app_handle: &AppHandle, home: &Path) {
+ if let Err(error) = crate::service::cli::ensure_shims(app_handle) {
+ log::warn!("DATA_DIR_SHIM_REWRITE: {error}");
+ }
+ if let Err(error) = crate::service::migrate::heal_stale_pnpm_metadata(home) {
+ log::warn!("DATA_DIR_PNPM_HEAL: {error}");
+ }
+}
+
+/// 备份目录名里的时间戳部分(名字不合规时返回空串)。
+fn stamp_of(path: &Path) -> String {
+ path.file_name()
+ .and_then(|name| name.to_str())
+ .and_then(state::moved_stamp)
+ .map(str::to_string)
+ .unwrap_or_default()
+}
+
+/// 两个路径是否指向同一处(`\\?\` 前缀与大小写差异不算不同)。
+fn same_path(a: &Path, b: &Path) -> bool {
+ is_within(a, b) && is_within(b, a)
+}
+
+/// `child` 是否位于 `parent` 之内(按路径组件逐段比较)。
+///
+/// 必须逐段比较而不是比字符串前缀:`D:\Data` 与 `D:\Database` 只差一个字符,
+/// 前缀比较会把后者误判成前者的子目录,从而拒绝一个完全合法的目标。
+fn is_within(child: &Path, parent: &Path) -> bool {
+ let parent = dunce::simplified(parent);
+ if parent.as_os_str().is_empty() {
+ return false;
+ }
+ let mut remaining = dunce::simplified(child).components();
+ for part in parent.components() {
+ let Some(found) = remaining.next() else {
+ return false;
+ };
+ if !same_component(&found, &part) {
+ return false;
+ }
+ }
+ true
+}
+
+/// 两个路径组件是否指向同一层。
+///
+/// Windows 的文件名不区分大小写,得用 `eq_ignore_ascii_case`;其它平台按 `PartialEq` 比较。
+/// 这里用 `cfg!` 而不是 `#[cfg]` 门控函数:`cfg!` 只把条件替换成 `true`/`false`,两个分支在
+/// **所有**平台都要参与编译;一旦改成 `#[cfg(windows)]` 门控,非 Windows 平台就会在调用点
+/// 报 `E0425`(`cfg!` 的条件分支永远会被编译,哪怕运行时走不到)。
+fn same_component(a: &Component, b: &Component) -> bool {
+ if cfg!(windows) {
+ a.as_os_str()
+ .to_string_lossy()
+ .eq_ignore_ascii_case(&b.as_os_str().to_string_lossy())
+ } else {
+ a == b
+ }
+}
+
+/// 进度载荷构造。
+fn step(
+ operation: &'static str,
+ phase: &'static str,
+ copied_files: u64,
+ copied_bytes: u64,
+ total_files: u64,
+ total_bytes: u64,
+) -> ProgressPayload {
+ ProgressPayload {
+ operation,
+ phase,
+ copied_files,
+ copied_bytes,
+ total_files,
+ total_bytes,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn temp_dir(tag: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "dsh-data-dir-migrate-{tag}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0)
+ ));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn validate_rejects_same_nested_and_non_empty_targets() {
+ let root = temp_dir("validate");
+ let source = root.join("home");
+ fs::create_dir_all(source.join("sessions")).unwrap();
+ assert!(validate_target(&source, &source).is_err());
+ assert!(validate_target(&source, &source.join("inner")).is_err());
+ assert!(validate_target(&source.join("inner"), &source).is_err());
+ assert!(validate_target(&source, Path::new("relative")).is_err());
+
+ let filled = root.join("filled");
+ fs::create_dir_all(&filled).unwrap();
+ fs::write(filled.join("a.txt"), "1").unwrap();
+ assert!(validate_target(&source, &filled).is_err());
+
+ let empty = root.join("empty");
+ fs::create_dir_all(&empty).unwrap();
+ assert!(validate_target(&source, &empty).is_ok());
+ assert!(validate_target(&source, &root.join("missing")).is_ok());
+ let _ = fs::remove_dir_all(&root);
+ }
+
+ /// 逐段比较路径组件,而不是比字符串前缀。
+ ///
+ /// 断言必须按平台分家:非 Windows 上 `\` 只是普通字符,`Path::new("D:\\Data\\sub")` 是
+ /// **一个**组件,`D:\Database` 与 `D:\Data` 也毫无关系——那套字面量在那边根本测不出
+ /// 「组件比较」这件事,只会全线失败(CI 的 ubuntu / macos job 就是这么红的)。
+ #[test]
+ fn is_within_compares_path_components_not_prefixes() {
+ if cfg!(windows) {
+ let data = Path::new("D:\\Data");
+ assert!(is_within(Path::new("D:\\Data\\sub"), data));
+ assert!(is_within(data, data));
+ assert!(!is_within(Path::new("D:\\Database"), data));
+ assert!(!is_within(Path::new("D:\\Other"), data));
+ } else {
+ let data = Path::new("/data");
+ assert!(is_within(Path::new("/data/sub"), data));
+ assert!(is_within(data, data));
+ assert!(!is_within(Path::new("/database"), data));
+ assert!(!is_within(Path::new("/other"), data));
+ }
+ // 空父路径永远不算「在里面」,与平台无关
+ assert!(!is_within(Path::new("/data"), Path::new("")));
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn is_within_ignores_case_and_the_verbatim_prefix() {
+ assert!(is_within(Path::new("d:\\data\\sub"), Path::new("D:\\Data")));
+ assert!(is_within(Path::new("\\\\?\\D:\\Data\\sub"), Path::new("D:\\Data")));
+ }
+
+ /// 同一个目录的两种写法要判成同一处。
+ ///
+ /// 同样得按平台分家:`D:\Data\` 末尾那个 `\` 在非 Windows 上是普通字符。
+ #[test]
+ fn same_path_matches_only_the_same_directory() {
+ if cfg!(windows) {
+ assert!(same_path(Path::new("D:\\Data"), Path::new("D:\\Data\\")));
+ assert!(!same_path(Path::new("D:\\Data"), Path::new("D:\\Data2")));
+ } else {
+ assert!(same_path(Path::new("/data"), Path::new("/data/")));
+ assert!(!same_path(Path::new("/data"), Path::new("/data2")));
+ }
+ }
+
+ #[test]
+ fn search_places_dedupes_without_losing_order() {
+ let current = Path::new("D:\\Data\\DSHHome");
+ let default = Path::new("C:\\Users\\me\\.dsh");
+ let places = search_places(current, default, Some(Path::new("E:\\Old\\DSHHome")));
+ assert_eq!(places.len(), 3);
+ assert_eq!(places[0], current);
+ assert_eq!(places[1], default);
+ assert_eq!(places[2], Path::new("E:\\Old\\DSHHome"));
+ // 当前目录恰好就是默认目录时只留一个(同一个目录不该被查两遍)
+ assert_eq!(search_places(default, default, None).len(), 1);
+ // 记录为空:只有当前与默认两处
+ assert_eq!(search_places(current, default, None).len(), 2);
+ }
+
+ /// 每个位置必须用**自己的**目录名去匹配备份。
+ ///
+ /// 从默认目录(`~/.dsh`)搬走时备份叫 `.dsh.moved-*`,而当前位置叫 `DSHHome`:
+ /// 统一用当前位置的名字去找会一条都找不到,面板上连回滚入口都不出现。
+ #[test]
+ fn collect_backups_matches_each_place_own_name() {
+ let root = temp_dir("backups");
+ let moved_from = root.join("moved");
+ let moved_to = root.join("moved-to");
+ fs::create_dir_all(&moved_from).unwrap();
+ fs::create_dir_all(&moved_to).unwrap();
+ let from = moved_from.join("DSHHome");
+ let to = moved_to.join(".dsh");
+ fs::create_dir_all(from.join("profiles")).unwrap();
+ fs::create_dir_all(to.join("profiles")).unwrap();
+ let backup_from = moved_from.join("DSHHome.moved-2026-01-01T00-00-00");
+ let backup_to = moved_to.join(".dsh.moved-2026-01-02T00-00-00");
+ fs::create_dir_all(&backup_from).unwrap();
+ fs::create_dir_all(&backup_to).unwrap();
+
+ let found = collect_backups(&[from.clone(), to.clone()]);
+ assert!(found.contains(&backup_from), "当前位置的备份未被找到:{found:?}");
+ assert!(found.contains(&backup_to), "默认位置的备份未被找到:{found:?}");
+ // 反向核对:用当前位置的名字去找默认位置旁边的备份必须一无所获
+ assert!(state::find_moved_dirs(&moved_to, "DSHHome").is_empty());
+ let _ = fs::remove_dir_all(&root);
+ }
+
+ /// 环境变量写失败时必须**真的**复原现场,而不只是「存在 undo_rollback 这个函数」。
+ ///
+ /// 写注册表是机器级动作,单元测试不能真去改它(会污染跑测试的那台机器);
+ /// 所以失败由闭包注入,能一路走到 `rewrite_env_or_undo` 的错误分支:备份要回到
+ /// `chosen`,被挪到一边的当前目录要回到 `restore_to`。
+ #[test]
+ fn env_write_failure_puts_both_directories_back() {
+ let root = temp_dir("undo");
+ let restore_to = root.join("DSHHome");
+ let chosen = root.join("DSHHome.moved-2026-01-01T00-00-00");
+ let aside = root.join("DSHHome.current-2026-01-01T00-00-00");
+ // 回滚走到这一步时的现场:备份已搬回 restore_to,当前目录已挪到 aside
+ fs::create_dir_all(&restore_to).unwrap();
+ fs::write(restore_to.join("sessions.json"), "backup").unwrap();
+ fs::create_dir_all(&aside).unwrap();
+ fs::write(aside.join("sessions.json"), "current").unwrap();
+
+ let error = rewrite_env_or_undo(&chosen, &restore_to, &aside.to_string_lossy(), |_| {
+ Err("DATA_DIR_ENV_WRITE: 注册表写不进去".to_string())
+ })
+ .unwrap_err();
+ assert!(error.contains("DATA_DIR_ENV_WRITE"), "{error}");
+ assert_eq!(
+ fs::read_to_string(chosen.join("sessions.json")).unwrap(),
+ "backup"
+ );
+ assert_eq!(
+ fs::read_to_string(restore_to.join("sessions.json")).unwrap(),
+ "current"
+ );
+ assert!(!aside.exists(), "挪到一边的目录没有被放回去");
+
+ // 目标本来是空的:aside 为空串,只需把备份放回去
+ let plain = root.join("Plain");
+ let plain_backup = root.join("Plain.moved-2026-01-01T00-00-00");
+ fs::create_dir_all(&plain).unwrap();
+ fs::write(plain.join("sessions.json"), "current").unwrap();
+ assert!(rewrite_env_or_undo(&plain_backup, &plain, "", |_| Err("x".to_string())).is_err());
+ assert!(!plain.exists());
+ assert_eq!(
+ fs::read_to_string(plain_backup.join("sessions.json")).unwrap(),
+ "current"
+ );
+
+ // 写成功时一个字节都不该搬动
+ rewrite_env_or_undo(&chosen, &restore_to, "", |text| {
+ assert!(text.ends_with("DSHHome"), "{text}");
+ Ok(())
+ })
+ .unwrap();
+ assert!(chosen.is_dir());
+ assert!(restore_to.is_dir());
+ let _ = fs::remove_dir_all(&root);
+ }
+}
diff --git a/src-tauri/src/service/data_dir/mod.rs b/src-tauri/src/service/data_dir/mod.rs
new file mode 100644
index 00000000..6a7d7c4a
--- /dev/null
+++ b/src-tauri/src/service/data_dir/mod.rs
@@ -0,0 +1,450 @@
+//! Harness 数据目录(`DSH_HOME`)的查看、迁移与回滚(issue #871)。
+//!
+//! 官方 dsh 用用户级环境变量 `DSH_HOME` 决定数据目录,桌面端只是跟随它;因此
+//! 迁移 = 复制数据 + 改写用户级 `DSH_HOME` + 旧目录改名保底,全程不使用目录联接
+//! (issue #848:联接被递归删除会删掉目标里的真实数据)。
+//!
+//! 硬约束(每一条都对应一次真实事故或恢复脚本踩过的坑):
+//! - 迁移前必须确认 Harness 完全退出:改目录时仍有进程在写,复制出来的是一份
+//! 撕裂的数据;
+//! - 复制后按「文件数 + 总字节数」校验,目标少于源即中止且不动源目录;
+//! - 旧目录只改名(`<原目录>.moved-<时间戳>`),永不删除;
+//! - 回滚按「会话数优先、时间戳其次」挑备份,并在目标非空时先把它挪到
+//! `<目标>.current-<时间戳>`。
+//!
+//! 模块划分(参考 `service/backup/`):
+//! - [`env`]:环境变量、默认目录、时间戳、磁盘空间
+//! - [`fs_ops`]:树统计、递归复制、备份发现所需的纯文件系统动作
+//! - [`state`]:上次迁移记录与 `.moved-*` 命名规则
+//! - [`migrate`]:迁移/回滚的编排(校验、复制、改名、改写环境变量)
+
+use std::io::ErrorKind;
+use std::path::{Path, PathBuf};
+use tauri::{AppHandle, Emitter as _};
+
+mod env;
+mod fs_ops;
+mod migrate;
+mod state;
+#[cfg(unix)]
+mod unix_env;
+
+/// 应用启动时把持久化的 `DSH_HOME` 注入本进程(Unix 的实现见 [`unix_env`];
+/// Windows 走注册表,进程启动时已经拿到值,这里是空操作)。
+///
+/// 必须在任何 `config::get_dsh_data_path` 调用之前执行:macOS / Linux 上由
+/// launchd 或显示管理器启动的 GUI 应用拿不到登录 shell 的环境变量,迁移过的
+/// 数据目录只能靠这一步回到进程里,否则会「迁移成功但重启后又读旧目录」。
+pub fn restore_process_env() {
+ #[cfg(unix)]
+ unix_env::restore_process_env();
+}
+
+/// 迁移进度事件(前端进度条订阅;与 `install-progress` 同款「后端推、前端渲染」)。
+pub const PROGRESS_EVENT: &str = "data-dir://progress";
+
+/// 数据目录状态(`supported` 为 false 时前端只展示说明、不展示任何动作)。
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DataDirStatus {
+ pub supported: bool,
+ /// 当前生效的数据目录
+ pub data_dir: String,
+ /// 未设置 `DSH_HOME` 时使用的默认目录(回滚目标可能是它)
+ pub default_dir: String,
+ /// 用户级 `DSH_HOME`(未设置时为空字符串)
+ pub env_override: String,
+ /// 最近一次迁移是否仍可回滚(旧目录还在)
+ pub rollback_available: bool,
+ /// 已发现的旧目录备份,按「会话数优先、时间戳其次」排序
+ pub backups: Vec<MigrationBackup>,
+ /// debug 构建忽略 `DSH_HOME`,面板据此解释「为什么这里改不了」
+ pub debug_build: bool,
+}
+
+/// 一个可回滚的旧目录备份。
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MigrationBackup {
+ pub path: String,
+ pub stamp: String,
+ /// 其中的会话数(备份价值的主要指标,`sessions` 为 0 时面板要给出警告)
+ pub sessions: u64,
+}
+
+/// 数据目录下的一个顶层条目,附占用空间(面板用来展示「要搬走的是什么」)。
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DataDirEntry {
+ pub name: String,
+ pub path: String,
+ pub files: u64,
+ pub bytes: u64,
+}
+
+/// 迁移预检结果(磁盘空间、目标来源、需要重建的链接数)。
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MigrationPlan {
+ pub source: String,
+ pub target: String,
+ pub total_files: u64,
+ pub total_bytes: u64,
+ pub links: u64,
+ pub target_free_bytes: u64,
+ pub enough_space: bool,
+ /// 目标所在目录已存在(父目录已建好,创建可能失败)
+ pub parent_exists: bool,
+ /// 目标取自用户在上次迁移中记录过的位置(提示「回到旧位置」)
+ pub remembered: bool,
+}
+
+/// 迁移/回滚结果。
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MigrationOutcome {
+ pub source: String,
+ pub target: String,
+ /// 旧位置:迁移时是改名后的备份目录,回滚时是「被挪到一边的当前目录」
+ pub moved_to: String,
+ pub files: u64,
+ pub bytes: u64,
+ pub links: u64,
+ pub sessions: u64,
+}
+
+/// 进度回调:迁移在阻塞线程里跑,回调必须能跨线程共享(`CopyProgress` 会在
+/// rayon 工作线程上触发它)。
+pub(super) type ProgressSink<'a> = &'a (dyn Fn(ProgressPayload) + Send + Sync);
+
+/// 进度事件载荷(camelCase 与前端字段一致)。
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ProgressPayload {
+ /// `migrate` / `rollback`
+ pub operation: &'static str,
+ /// `scan` / `copy` / `verify` / `finalize` / `done`
+ pub phase: &'static str,
+ pub copied_files: u64,
+ pub copied_bytes: u64,
+ pub total_files: u64,
+ pub total_bytes: u64,
+}
+
+/// 当前数据目录状态。
+///
+/// 永不返回错误:面板要在任何情况下都能显示「数据目录在哪、能不能改」,
+/// 单个探测失败(读不到注册表、目录不存在)只让对应字段退化为默认值。
+pub fn status(app_handle: &AppHandle) -> DataDirStatus {
+ let data_dir = crate::config::get_dsh_data_path(app_handle);
+ let default_dir = env::default_home();
+ let env_override = env::read_user_home().ok().flatten().unwrap_or_default();
+ let backups: Vec<MigrationBackup> =
+ migrate::find_backups(app_handle, &data_dir).into_iter().collect();
+ let rollback_available = !backups.is_empty();
+ DataDirStatus {
+ supported: !cfg!(debug_assertions),
+ data_dir: data_dir.to_string_lossy().into_owned(),
+ default_dir: default_dir.to_string_lossy().into_owned(),
+ env_override,
+ rollback_available,
+ backups,
+ debug_build: cfg!(debug_assertions),
+ }
+}
+
+/// 当前数据目录下的顶层条目,按占用字节数降序。
+///
+/// 与恢复脚本一致:迁移是整目录搬家,用户只需要知道「这一堆档案一共多大」,
+/// 不需要逐个勾选,因此这里只用于展示与体积汇总。
+pub fn entries(app_handle: &AppHandle) -> Result<Vec<DataDirEntry>, String> {
+ entries_in(&crate::config::get_dsh_data_path(app_handle))
+}
+
+/// [`entries`] 的纯目录版本(不依赖 `AppHandle`,因此可单测)。
+///
+/// 目录不存在时返回空列表而不是错误:迁移刚把旧目录改名搬走、Harness 还没来得及
+/// 重建它,或者安装器把 `DSH_HOME` 指向一个尚未创建的目录时,面板该显示空态
+/// (`data_dir.entries_empty_desc` 就是为这一刻写的),而不是一片红色报错。
+fn entries_in(root: &Path) -> Result<Vec<DataDirEntry>, String> {
+ let read_dir = match std::fs::read_dir(root) {
+ Ok(read_dir) => read_dir,
+ Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
+ Err(error) => return Err(format!("DATA_DIR_READ: {}: {error}", root.display())),
+ };
+ let mut candidates: Vec<DataDirEntry> = Vec::new();
+ for entry in read_dir {
+ let Ok(entry) = entry else { continue };
+ let Ok(meta) = std::fs::symlink_metadata(entry.path()) else {
+ continue;
+ };
+ if !meta.is_dir() {
+ continue;
+ }
+ let mut stats = fs_ops::TreeStats::default();
+ fs_ops::scan_tree(&entry.path(), &mut stats)?;
+ candidates.push(DataDirEntry {
+ name: entry.file_name().to_string_lossy().into_owned(),
+ path: entry.path().to_string_lossy().into_owned(),
+ files: stats.files,
+ bytes: stats.bytes,
+ });
+ }
+ candidates.sort_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.name.cmp(&b.name)));
+ Ok(candidates)
+}
+
+/// 迁移预检:目标合法性、磁盘空间、来源(是否用户上次用过的位置)。
+///
+/// 预检与真正迁移共用 `migrate::plan`,避免「预检说没问题、执行时才拒绝」的错位。
+pub fn preview(
+ app_handle: &AppHandle,
+ parent: &Path,
+ leaf: &str,
+) -> Result<MigrationPlan, String> {
+ let source = crate::config::get_dsh_data_path(app_handle);
+ let target = join_leaf(parent, leaf)?;
+ migrate::plan(app_handle, &source, &target)
+}
+
+/// 把数据目录迁到 `<parent>\<leaf>`。
+///
+/// 调用方(`bridge::data_dir`)必须已经取得核心切换锁、停止 Harness 并持有
+/// 插件操作锁:迁移会改写 `DSH_HOME`,此刻任何仍在运行的 Harness 都会把数据
+/// 写回旧目录,导致两边各有一半。
+pub async fn migrate(
+ app_handle: AppHandle,
+ parent: PathBuf,
+ leaf: String,
+) -> Result<MigrationOutcome, String> {
+ let source = crate::config::get_dsh_data_path(&app_handle);
+ let target = join_leaf(&parent, &leaf)?;
+ migrate::plan(&app_handle, &source, &target)?;
+ let handle = app_handle.clone();
+ let emit = move |payload: ProgressPayload| {
+ let _ = handle.emit(PROGRESS_EVENT, payload);
+ };
+ let app = app_handle.clone();
+ tauri::async_runtime::spawn_blocking(move || migrate::run(&app, &source, &target, &emit))
+ .await
+ .map_err(|e| format!("DATA_DIR_TASK: {e}"))?
+}
+
+/// 回滚到最近的(或指定的)旧目录备份。
+///
+/// `backup` 为 `None` 时按「会话数优先、时间戳其次」自动挑选;选择规则与恢复
+/// 脚本一致,两边挑中的必须是同一个目录。
+pub async fn rollback(
+ app_handle: AppHandle,
+ backup: Option<PathBuf>,
+) -> Result<MigrationOutcome, String> {
+ let current = crate::config::get_dsh_data_path(&app_handle);
+ let handle = app_handle.clone();
+ let emit = move |payload: ProgressPayload| {
+ let _ = handle.emit(PROGRESS_EVENT, payload);
+ };
+ let app = app_handle.clone();
+ tauri::async_runtime::spawn_blocking(move || {
+ migrate::rollback(&app, &current, backup.as_deref(), &emit)
+ })
+ .await
+ .map_err(|e| format!("DATA_DIR_TASK: {e}"))?
+}
+
+/// `.harness.pid` 的读取结果(两行:PID、端口,见 `workflow::sweep::persist_harness_pid`)。
+///
+/// 「文件不在」与「文件在但读不出来 / 解析不出来」必须分开:前者是正常的
+/// 「从未启动过、或上次已正常清理」,后者说明有人正动这个文件(占用、权限、写到
+/// 一半)。区别在于 `workflow::process::stop()` 无论哪种情况都会把标记删掉,于是
+/// 「标记没了」会被误读成「Harness 已退出」——只有把 Invalid 单独标出来,调用方
+/// 才有机会在删标记之前拒绝这次迁移。
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum HarnessMarker {
+ /// 文件不在:从未启动过、或上次已正常清理。
+ Missing,
+ /// 文件在,但读不出来或第一行不是 PID。
+ Invalid,
+ /// 标记里记录的 PID。
+ Pid(u32),
+}
+
+/// 读 `.harness.pid` 并分类。
+///
+/// 只认标记文件,不做端口猜测:端口可能被别的程序占用,也可能因为端口漂移而
+/// 记着上一个端口;标记文件里的 PID 才是「本应用启动的 Harness」的唯一凭据。
+pub(crate) fn harness_marker(app_handle: &AppHandle) -> HarnessMarker {
+ harness_marker_at(&crate::config::get_dsh_data_path(app_handle).join(".harness.pid"))
+}
+
+/// 无 `AppHandle` 版本:路径由调用方给出,便于用临时目录直接测三种分类。
+fn harness_marker_at(marker: &Path) -> HarnessMarker {
+ let text = match std::fs::read_to_string(marker) {
+ Ok(text) => text,
+ Err(error) if error.kind() == ErrorKind::NotFound => return HarnessMarker::Missing,
+ Err(error) => {
+ log::warn!("DATA_DIR_HARNESS_MARKER: {error}");
+ return HarnessMarker::Invalid;
+ }
+ };
+ let Some(pid) = text
+ .lines()
+ .next()
+ .and_then(|line| line.trim().parse::<u32>().ok())
+ else {
+ log::warn!("DATA_DIR_HARNESS_MARKER: 无法解析 {}", marker.display());
+ return HarnessMarker::Invalid;
+ };
+ HarnessMarker::Pid(pid)
+}
+
+/// 是否为「Harness 已经退出」的稳定状态:`.harness.pid` 里的进程不再存活。
+///
+/// 只有「标记不存在」才算已退出——那是从未启动过或上次已正常清理的样子。
+/// 其余一律按「可能还在跑」处理(fail closed):读失败(占用、权限)说明有人正
+/// 动这个文件,内容解析不出来则可能正写到一半,两种情况下接着改数据目录都可能
+/// 复制到一份撕裂的数据。文件被删掉与写坏这两种「假阴性」的代价完全不对等:
+/// 前者只是让用户重试一次,后者会毁掉用户唯一无法重建的会话数据。
+pub(super) fn harness_stopped(app_handle: &AppHandle) -> bool {
+ match harness_marker(app_handle) {
+ HarnessMarker::Missing => true,
+ HarnessMarker::Invalid => false,
+ HarnessMarker::Pid(pid) => !process_alive(pid),
+ }
+}
+
+/// 进程是否存活(只查该 PID,不刷新整张进程表)。
+pub(crate) fn process_alive(pid: u32) -> bool {
+ use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
+
+ let mut system = System::new();
+ let target = [Pid::from_u32(pid)];
+ system.refresh_processes_specifics(
+ ProcessesToUpdate::Some(&target),
+ true,
+ ProcessRefreshKind::nothing(),
+ );
+ system.process(Pid::from_u32(pid)).is_some()
+}
+
+/// 把用户选的「名称」拼到「上级目录」上。
+///
+/// 拒绝含路径分隔符的名字:`Path::join` 遇到绝对路径会整段替换,放任一个
+/// `D:\evil` 之类的名字进来就能把数据目录建到用户没选的地方。
+fn join_leaf(parent: &Path, leaf: &str) -> Result<PathBuf, String> {
+ let trimmed = leaf.trim();
+ if trimmed.is_empty() {
+ return Err(format!("DATA_DIR_NAME_INVALID: {leaf}"));
+ }
+ let allowed = trimmed
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '.' | '_' | '-'));
+ if !allowed {
+ return Err(format!("DATA_DIR_NAME_INVALID: {leaf}"));
+ }
+ if parent.as_os_str().is_empty() {
+ return Err(format!("DATA_DIR_PARENT_MISSING: {leaf}"));
+ }
+ Ok(parent.join(trimmed))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn join_leaf_accepts_plain_names_only() {
+ let parent = Path::new("D:\\");
+ assert_eq!(join_leaf(parent, "DSHHome").unwrap(), parent.join("DSHHome"));
+ assert_eq!(
+ join_leaf(parent, " DSH Home ").unwrap(),
+ parent.join("DSH Home")
+ );
+ // 绝对路径会被 Path::join 整段替换,必须拒绝
+ assert!(join_leaf(parent, "D:\\evil").is_err());
+ assert!(join_leaf(parent, "a/b").is_err());
+ assert!(join_leaf(parent, "a\\b").is_err());
+ assert!(join_leaf(parent, " ").is_err());
+ assert!(join_leaf(Path::new(""), "DSHHome").is_err());
+ }
+
+ #[test]
+ fn process_alive_reports_the_current_process() {
+ assert!(process_alive(std::process::id()));
+ }
+
+ /// 「文件不在」与「文件在但读不出来 / 解析不出来」必须分开:`stop()` 两种
+ /// 情况都会删标记,只有 Invalid 能让调用方在删之前拒绝迁移。
+ #[test]
+ fn harness_marker_tells_missing_from_unreadable() {
+ let root = temp_dir("marker");
+ let marker = root.join(".harness.pid");
+ assert_eq!(harness_marker_at(&marker), HarnessMarker::Missing);
+
+ // 两行(PID、端口):只取第一行
+ std::fs::write(&marker, "4242\n3080\n").unwrap();
+ assert_eq!(harness_marker_at(&marker), HarnessMarker::Pid(4242));
+
+ std::fs::write(&marker, "not-a-pid\n3080\n").unwrap();
+ assert_eq!(harness_marker_at(&marker), HarnessMarker::Invalid);
+ std::fs::write(&marker, "").unwrap();
+ assert_eq!(harness_marker_at(&marker), HarnessMarker::Invalid);
+
+ // 同名目录:`read_to_string` 报的不是 NotFound,属于「有人占着这个名字」
+ std::fs::remove_file(&marker).unwrap();
+ std::fs::create_dir(&marker).unwrap();
+ assert_eq!(harness_marker_at(&marker), HarnessMarker::Invalid);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// 迁移刚把旧目录改名搬走、Harness 还没重建它时,目录会短暂不存在。
+ #[test]
+ fn entries_treat_a_missing_directory_as_empty() {
+ let root = temp_dir("entries-missing");
+ let _ = std::fs::remove_dir_all(&root);
+ assert!(entries_in(&root).unwrap().is_empty());
+ // 真正的读取错误仍要报出来,别把权限问题也当成空目录
+ let file = root.with_extension("txt");
+ std::fs::write(&file, "not a directory").unwrap();
+ assert!(entries_in(&file).unwrap_err().starts_with("DATA_DIR_READ: "));
+ let _ = std::fs::remove_file(&file);
+ }
+
+ #[test]
+ fn entries_lists_directories_largest_first() {
+ let root = temp_dir("entries-order");
+ write(&root.join("small").join("one.bin"), "abc");
+ write(&root.join("big").join("one.bin"), "abcdef");
+ write(&root.join("big").join("two.bin"), "abcdef");
+ // 顶层文件不算「子项占用」,不参与统计
+ write(&root.join("loose.txt"), "x");
+
+ let listed = entries_in(&root).unwrap();
+ let names: Vec<&str> = listed.iter().map(|entry| entry.name.as_str()).collect();
+ assert_eq!(names, vec!["big", "small"]);
+ assert_eq!((listed[0].files, listed[0].bytes), (2, 12));
+ assert_eq!((listed[1].files, listed[1].bytes), (1, 3));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// 临时目录自建:dev-dependencies 里没有 `tempfile`(与 `fs_ops` 同款写法)。
+ fn temp_dir(tag: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "dsh-data-dir-{tag}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0)
+ ));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ fn write(path: &Path, text: &str) {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).unwrap();
+ }
+ std::fs::write(path, text).unwrap();
+ }
+}
diff --git a/src-tauri/src/service/data_dir/state.rs b/src-tauri/src/service/data_dir/state.rs
new file mode 100644
index 00000000..f7bf2357
--- /dev/null
+++ b/src-tauri/src/service/data_dir/state.rs
@@ -0,0 +1,238 @@
+//! 上次迁移记录与 `.moved-*` 备份发现。
+//!
+//! 备份目录名自带原位置(`<原目录>.moved-<时间戳>`),因此回滚目标可以从名字反推,
+//! 不需要额外状态。但跨盘搬家时备份留在旧盘上——既不在当前目录旁边、也不在
+//! `~/.dsh` 旁边,只靠两侧搜索会漏掉,所以搬家时把原位置另记一份(issue E)。
+
+use std::fs;
+use std::path::{Path, PathBuf};
+use tauri::AppHandle;
+
+/// 备份目录名后缀前缀:`D:\DSHHome.moved-2026-10-02T21-33-14`
+const MOVED_INFIX: &str = ".moved-";
+
+/// 回滚前把当前目录挪到一边时用的后缀前缀(与恢复脚本的 `.current-` 一致)
+pub(super) const CURRENT_INFIX: &str = ".current-";
+
+/// 上次迁移记录文件路径:`%LOCALAPPDATA%\deepseek-harness\last-migration.txt`。
+///
+/// 与恢复脚本的 `$StatePath` 逐字一致(脚本也会读这里),因此放在 CLI 集成目录
+/// (`get_bin_dir` 的父目录)而不是应用数据目录:两者必须看到同一份记录。
+/// debug 构建自动落到 `dev-dsh`,与生产互不干扰。
+pub(super) fn state_path(app_handle: &AppHandle) -> PathBuf {
+ crate::service::cli::get_bin_dir(app_handle)
+ .parent()
+ .map(|dir| dir.to_path_buf())
+ .unwrap_or_else(std::env::temp_dir)
+ .join("last-migration.txt")
+}
+
+/// 读取上次搬家的原目录(文件首行;空文件视为无记录)。
+pub(super) fn read_last_migration(app_handle: &AppHandle) -> Option<String> {
+ let text = fs::read_to_string(state_path(app_handle)).ok()?;
+ let first = text.lines().next()?.trim();
+ if first.is_empty() {
+ None
+ } else {
+ Some(first.to_string())
+ }
+}
+
+/// 写入上次搬家的原目录(UTF-8 无 BOM,首行)。
+///
+/// 必须无 BOM:恢复脚本用 `Get-Content` 读首行做路径比较,带 BOM 会让路径前多出
+/// 一个不可见字符从而匹配失败(脚本自己也用 `UTF8Encoding($false)` 写)。
+pub(super) fn write_last_migration(app_handle: &AppHandle, value: &str) -> Result<(), String> {
+ let path = state_path(app_handle);
+ if let Some(dir) = path.parent() {
+ fs::create_dir_all(dir).map_err(|e| format!("DATA_DIR_STATE_MKDIR: {e}"))?;
+ }
+ fs::write(&path, value).map_err(|e| format!("DATA_DIR_STATE_WRITE: {e}"))
+}
+
+/// 目录名是否形如 `<leaf>.moved-<时间戳>`,是则返回时间戳部分。
+///
+/// 时间戳只允许数字、`T` 与 `-`(脚本用 `-replace '\.moved-[0-9T\-]+$'` 反推原路径,
+/// 这里保持同一字符集,两个实现才能互相识别对方留下的备份)。
+pub(super) fn moved_stamp(name: &str) -> Option<&str> {
+ let index = name.rfind(MOVED_INFIX)?;
+ let stamp = &name[index + MOVED_INFIX.len()..];
+ if stamp.is_empty() {
+ return None;
+ }
+ if stamp.chars().all(|c| c.is_ascii_digit() || c == 'T' || c == '-') {
+ Some(stamp)
+ } else {
+ None
+ }
+}
+
+/// 从备份目录名反推它该还原到哪里(`D:\DSHHome.moved-2026-…` → `D:\DSHHome`)。
+pub(super) fn original_of(moved: &Path) -> Option<PathBuf> {
+ let name = moved.file_name()?.to_str()?;
+ let stamp = moved_stamp(name)?;
+ let leaf = &name[..name.len() - MOVED_INFIX.len() - stamp.len()];
+ if leaf.is_empty() {
+ return None;
+ }
+ Some(moved.with_file_name(leaf))
+}
+
+/// 列出 `parent` 下所有 `<leaf>.moved-<时间戳>` 备份(含时间戳)。
+pub(super) fn find_moved_dirs(parent: &Path, leaf: &str) -> Vec<(PathBuf, String)> {
+ let Ok(read_dir) = fs::read_dir(parent) else {
+ return Vec::new();
+ };
+ let mut found = Vec::new();
+ for entry in read_dir.flatten() {
+ let name = entry.file_name();
+ let Some(name) = name.to_str() else {
+ continue;
+ };
+ let Some(stamp) = moved_stamp(name) else {
+ continue;
+ };
+ if name.len() != leaf.len() + MOVED_INFIX.len() + stamp.len() {
+ continue;
+ }
+ if !name.starts_with(leaf) {
+ continue;
+ }
+ found.push((entry.path(), stamp.to_string()));
+ }
+ found
+}
+
+/// 给目录名加上 `.moved-<时间戳>` 后缀(迁移时把旧目录改名保底)。
+///
+/// 同名备份已存在时不覆盖:换个后缀重试到时间戳唯一为止。用户可能在同一秒里
+/// 连续点了两次迁移,直接 `rename` 会把上一次的备份当成目标而失败(Windows 上
+/// 目标目录已存在时 `rename` 报错),这里的自增后缀让两次都留得下来。
+pub(super) fn with_moved_suffix(original: &Path, stamp: &str) -> Result<PathBuf, String> {
+ suffixed(original, MOVED_INFIX, stamp)
+}
+
+/// 给目录名加上 `.current-<时间戳>` 后缀(回滚时把当前目录挪到一边)。
+pub(super) fn with_current_suffix(original: &Path, stamp: &str) -> Result<PathBuf, String> {
+ suffixed(original, CURRENT_INFIX, stamp)
+}
+
+/// 生成 `<原目录><中缀><时间戳>`;已被占用时在时间戳后追加 `-2`、`-3`…。
+///
+/// 追加段仍只用数字与 `-`,因此 `moved_stamp` 与恢复脚本的正则都还能反推原路径。
+fn suffixed(original: &Path, infix: &str, stamp: &str) -> Result<PathBuf, String> {
+ let name = original
+ .file_name()
+ .and_then(|name| name.to_str())
+ .ok_or_else(|| format!("DATA_DIR_NAME_INVALID: {}", original.display()))?;
+ if original.parent().is_none() {
+ return Err(format!("DATA_DIR_NAME_INVALID: {}", original.display()));
+ }
+ let mut candidate = original.with_file_name(format!("{name}{infix}{stamp}"));
+ let mut attempt = 2;
+ while candidate.exists() {
+ candidate = original.with_file_name(format!("{name}{infix}{stamp}-{attempt}"));
+ attempt += 1;
+ }
+ Ok(candidate)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn with_moved_suffix_produces_a_script_compatible_name() {
+ let dir = std::env::temp_dir().join(format!(
+ "dsh-data-dir-suffix-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0)
+ ));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ let original = dir.join("DSHHome");
+ fs::create_dir_all(&original).unwrap();
+
+ let moved = with_moved_suffix(&original, "2026-10-02T21-33-14").unwrap();
+ assert_eq!(
+ moved.file_name().unwrap().to_str().unwrap(),
+ "DSHHome.moved-2026-10-02T21-33-14"
+ );
+ // 脚本的正则必须能反推出原路径
+ assert_eq!(original_of(&moved).unwrap(), original);
+
+ // 同名备份已存在时换后缀,不覆盖已有备份
+ fs::create_dir_all(&moved).unwrap();
+ let second = with_moved_suffix(&original, "2026-10-02T21-33-14").unwrap();
+ assert_ne!(second, moved);
+ assert_eq!(original_of(&second).unwrap(), original);
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ /// 挪到一边的目录名必须还能反推出原路径。
+ ///
+ /// 这里刻意用 `/DSHHome` 这种两平台都认的绝对路径:`D:\DSHHome` 在非 Windows 上
+ /// 只是**一个**组件(`\` 是普通字符),`file_name()` 会把整串吐回来,断言随之失败。
+ /// 生产路径只可能是 Windows 盘符,但这条测试要验的是「拼后缀不改叶子名」,与盘符无关。
+ #[test]
+ fn with_current_suffix_keeps_the_original_path_recoverable() {
+ let original = Path::new("/DSHHome");
+ let aside = with_current_suffix(original, "2026-10-02T21-33-14").unwrap();
+ assert_eq!(
+ aside.file_name().unwrap().to_str().unwrap(),
+ "DSHHome.current-2026-10-02T21-33-14"
+ );
+ // `.current-` 不是迁移备份,发现逻辑不该把它当回滚目标
+ assert_eq!(moved_stamp(aside.file_name().unwrap().to_str().unwrap()), None);
+ }
+
+ #[test]
+ fn moved_stamp_accepts_only_script_compatible_suffixes() {
+ assert_eq!(
+ moved_stamp("DSHHome.moved-2026-10-02T21-33-14"),
+ Some("2026-10-02T21-33-14")
+ );
+ assert_eq!(moved_stamp("DSHHome.moved-"), None);
+ assert_eq!(moved_stamp("DSHHome.moved-2026.10.02"), None);
+ assert_eq!(moved_stamp("DSHHome.current-2026-10-02T21-33-14"), None);
+ assert_eq!(moved_stamp("DSHHome"), None);
+ }
+
+ #[test]
+ fn original_of_strips_the_moved_suffix() {
+ let moved = Path::new("D:\\DSHHome.moved-2026-10-02T21-33-14");
+ assert_eq!(
+ original_of(moved).unwrap(),
+ Path::new("D:\\DSHHome").to_path_buf()
+ );
+ assert_eq!(original_of(Path::new("D:\\DSHHome")), None);
+ }
+
+ #[test]
+ fn find_moved_dirs_matches_only_the_same_leaf() {
+ let root = std::env::temp_dir().join(format!(
+ "dsh-data-dir-state-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0)
+ ));
+ let _ = fs::remove_dir_all(&root);
+ fs::create_dir_all(root.join("DSHHome.moved-2026-10-02T21-33-14")).unwrap();
+ fs::create_dir_all(root.join("DSHHome.moved-2026-10-03T01-02-03")).unwrap();
+ fs::create_dir_all(root.join("Other.moved-2026-10-02T21-33-14")).unwrap();
+ fs::create_dir_all(root.join("DSHHome.current-2026-10-02T21-33-14")).unwrap();
+
+ let mut found: Vec<String> = find_moved_dirs(&root, "DSHHome")
+ .into_iter()
+ .map(|(_, stamp)| stamp)
+ .collect();
+ found.sort();
+ assert_eq!(found, vec!["2026-10-02T21-33-14", "2026-10-03T01-02-03"]);
+ let _ = fs::remove_dir_all(&root);
+ }
+}
diff --git a/src-tauri/src/service/data_dir/unix_env.rs b/src-tauri/src/service/data_dir/unix_env.rs
new file mode 100644
index 00000000..5ffae563
--- /dev/null
+++ b/src-tauri/src/service/data_dir/unix_env.rs
@@ -0,0 +1,551 @@
+//! Unix(macOS / Linux)下 `DSH_HOME` 的持久化机制(issue #871 的跨平台部分)。
+//!
+//! Windows 的落点是注册表 `HKCU\Environment`:一个值就能覆盖所有后续进程。
+//! Unix 没有等价物,必须按「谁启动应用」分别覆盖,这里三个机制同时写、同时清:
+//!
+//! 1. **macOS LaunchAgent**(`~/Library/LaunchAgents/<APP_IDENTIFIER>.env.plist`):
+//! plist 里的 `ProgramArguments` 在 `RunAtLoad` 时执行 `/bin/launchctl setenv`,
+//! 把变量写进用户 launchd 会话,此后 Dock / Finder / Spotlight 启动的 GUI 应用
+//! 都会继承——这是 macOS 上唯一能让「不经过 shell 启动」的应用读到变量的办法
+//! (plist 自带的 `EnvironmentVariables` 键只影响任务自身,GUI 应用读不到);
+//! 2. **Linux `~/.config/environment.d/<APP_IDENTIFIER>.conf`**:systemd 用户会话的
+//! 变量定义,GNOME/KDE 等从显示管理器登录时由 `systemd --user` 读取;
+//! 3. **`~/.profile` 的标记块**:所有走 login shell 的场景(终端启动、SSH,以及
+//! 多数 X11 会话的 `.xinitrc` 链路)。
+//!
+//! 三个机制都只用纯文本 + 系统自带命令,不引入新依赖;Windows 上本模块整块不编译。
+//!
+//! 与 PATH 注入的区别:PATH 块可以「写进 rc 文件、下次开终端生效」,数据目录不行——
+//! 迁移刚结束就要能拉起 Harness,因此除写文件外还要立刻 `std::env::set_var`,
+//! 并在应用启动时从磁盘回读(见 [`restore_process_env`])。
+
+use std::path::PathBuf;
+
+#[cfg(target_os = "macos")]
+use crate::config::APP_IDENTIFIER;
+use crate::service::cli::{strip_rc_block, upsert_rc_block, write_rc_with_backup};
+
+use super::env::DATA_DIR_ENV;
+
+/// 环境变量在 `~/.profile` 里的块标记。
+///
+/// 与 PATH 注入块(`cli::path::rc` 的 `RC_MARK_*`)**必须是不同的标记**:同一个
+/// 文件里两份块各自只认得自己的标记,否则后写的一份会把前一份删掉。
+const PROFILE_MARK_START: &str = "# >>> deepseek-harness dsh home >>>";
+const PROFILE_MARK_END: &str = "# <<< deepseek-harness dsh home <<<";
+
+/// Linux 的 systemd 用户会话变量文件(相对 `$HOME`)。
+#[cfg(target_os = "linux")]
+const ENVIRONMENT_D_FILE: &str = ".config/environment.d/dsh-tauri.conf";
+
+/// macOS LaunchAgent 文件名(相对 `$HOME`)。
+#[cfg(target_os = "macos")]
+fn launch_agent_path(home: &std::path::Path) -> PathBuf {
+ home.join(format!("Library/LaunchAgents/{APP_IDENTIFIER}.env.plist"))
+}
+
+// ---------------------------------------------------------------------------
+// 纯文本助手(与平台无关,因此在 Windows 上也能单测)
+// ---------------------------------------------------------------------------
+
+/// `~/.profile` 的标记块内容。
+///
+/// 值来自 [`quote_sh`]:绝对路径里出现空格、`$`、引号时也要写出合法 shell 语句。
+pub(crate) fn profile_block(value: &str) -> String {
+ format!(
+ "{PROFILE_MARK_START}\nexport {DATA_DIR_ENV}=\"{}\"\n{PROFILE_MARK_END}\n",
+ quote_sh(value)
+ )
+}
+
+/// 从 `~/.profile` 内容里读出标记块中的值(没有块时 `None`)。
+///
+/// 只认自己写的 `export NAME="..."` 形式;用户手写的其它形式不解析,避免误读
+/// 一条与迁移无关的设置。
+pub(crate) fn parse_profile_block(content: &str) -> Option<String> {
+ let mut inside = false;
+ for line in content.lines() {
+ let trimmed = line.trim();
+ if trimmed == PROFILE_MARK_START {
+ inside = true;
+ continue;
+ }
+ if !inside {
+ continue;
+ }
+ if trimmed == PROFILE_MARK_END {
+ break;
+ }
+ let Some(rest) = trimmed.strip_prefix("export ") else {
+ continue;
+ };
+ let Some(rest) = rest.strip_prefix(DATA_DIR_ENV) else {
+ continue;
+ };
+ let Some(raw) = rest.strip_prefix('=') else {
+ continue;
+ };
+ let value = unquote_sh(raw.trim());
+ if !value.is_empty() {
+ return Some(value);
+ }
+ }
+ None
+}
+
+/// 移除 `~/.profile` 里的标记块(保留用户其余内容)。
+pub(crate) fn strip_profile_block(content: &str) -> String {
+ strip_rc_block(content, PROFILE_MARK_START, PROFILE_MARK_END)
+}
+
+/// 把标记块并入 `~/.profile` 内容(幂等,块始终落在文件末尾)。
+pub(crate) fn upsert_profile_block(content: &str, value: &str) -> String {
+ upsert_rc_block(
+ content,
+ &profile_block(value),
+ PROFILE_MARK_START,
+ PROFILE_MARK_END,
+ )
+}
+
+/// 单个 shell 双引号字符串的转义:`\`、`"`、`$` 与反引号需要加反斜杠,
+/// 其余字符(含空格与中文路径)原样保留。
+pub(crate) fn quote_sh(value: &str) -> String {
+ let mut out = String::with_capacity(value.len());
+ for c in value.chars() {
+ if matches!(c, '\\' | '"' | '$' | '`') {
+ out.push('\\');
+ }
+ out.push(c);
+ }
+ out
+}
+
+/// [`quote_sh`] 的逆操作:去掉包裹的双引号并还原反斜杠转义。
+pub(crate) fn unquote_sh(value: &str) -> String {
+ let inner = value
+ .strip_prefix('"')
+ .and_then(|rest| rest.strip_suffix('"'))
+ .unwrap_or(value);
+ let mut out = String::with_capacity(inner.len());
+ let mut escaped = false;
+ for c in inner.chars() {
+ if escaped {
+ out.push(c);
+ escaped = false;
+ continue;
+ }
+ if c == '\\' {
+ escaped = true;
+ continue;
+ }
+ out.push(c);
+ }
+ out
+}
+
+/// 单个 systemd `environment.d` 值的转义。
+///
+/// `environment.d` 只做 `$VAR` 展开与引号剥离(见 systemd 的 `environment.d(5)`),
+/// 反斜杠**不是**转义符,因此不能照搬 shell 的写法:把 `\` 写成 `\\` 会真的得到
+/// 一个双反斜杠。这里只处理真正有语义的字符:`$` 写成 `$$`,`"` 与 `\` 原样保留
+/// (都被双引号包裹,且不参与展开)。
+#[cfg(any(target_os = "linux", test))]
+pub(crate) fn quote_environment_d(value: &str) -> String {
+ let mut out = String::with_capacity(value.len());
+ for c in value.chars() {
+ if c == '$' {
+ out.push_str("$$");
+ } else {
+ out.push(c);
+ }
+ }
+ out
+}
+
+/// `~/.config/environment.d/<APP_IDENTIFIER>.conf` 的内容。
+///
+/// 写绝对路径而不是 `$HOME/...`:systemd 从显示管理器读取该文件时并不保证 `HOME`
+/// 已经存在,展开失败会把数据目录指到一个字面量 `$HOME` 目录上。
+#[cfg(target_os = "linux")]
+pub(crate) fn environment_d_content(value: &str) -> String {
+ format!("{DATA_DIR_ENV}=\"{}\"\n", quote_environment_d(value))
+}
+
+/// 从 `environment.d` 文件内容里读 `DSH_HOME`(只认 `NAME="值"` / `NAME=值`)。
+#[cfg(any(target_os = "linux", test))]
+pub(crate) fn parse_environment_d(content: &str) -> Option<String> {
+ for line in content.lines() {
+ let trimmed = line.trim();
+ if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
+ continue;
+ }
+ let Some(rest) = trimmed.strip_prefix(DATA_DIR_ENV) else {
+ continue;
+ };
+ let Some(raw) = rest.strip_prefix('=') else {
+ continue;
+ };
+ let value = raw.trim().trim_matches('"').replace("$$", "$");
+ if !value.is_empty() {
+ return Some(value);
+ }
+ }
+ None
+}
+
+/// macOS LaunchAgent 的 plist 内容。
+#[cfg(target_os = "macos")]
+pub(crate) fn launch_agent_plist(value: &str) -> String {
+ format!(
+ concat!(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
+ "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n",
+ "<plist version=\"1.0\">\n",
+ "<dict>\n",
+ " <key>Label</key>\n",
+ " <string>{0}.env</string>\n",
+ " <key>ProgramArguments</key>\n",
+ " <array>\n",
+ " <string>/bin/launchctl</string>\n",
+ " <string>setenv</string>\n",
+ " <string>{1}</string>\n",
+ " <string>{2}</string>\n",
+ " </array>\n",
+ " <key>RunAtLoad</key>\n",
+ " <true/>\n",
+ "</dict>\n",
+ "</plist>\n"
+ ),
+ APP_IDENTIFIER,
+ DATA_DIR_ENV,
+ xml_escape(value)
+ )
+}
+
+/// XML 文本转义(plist 里 `<string>` 的值)。
+#[cfg(target_os = "macos")]
+pub(crate) fn xml_escape(value: &str) -> String {
+ let mut out = String::with_capacity(value.len());
+ for c in value.chars() {
+ match c {
+ '&' => out.push_str("&amp;"),
+ '<' => out.push_str("&lt;"),
+ '>' => out.push_str("&gt;"),
+ '"' => out.push_str("&quot;"),
+ _ => out.push(c),
+ }
+ }
+ out
+}
+
+/// 从 LaunchAgent plist 里读回 `DSH_HOME`(`setenv` 的第三个参数)。
+#[cfg(target_os = "macos")]
+pub(crate) fn parse_launch_agent(content: &str) -> Option<String> {
+ let needle = format!("<string>{DATA_DIR_ENV}</string>");
+ let mut lines = content.lines();
+ while let Some(line) = lines.next() {
+ if line.trim() != needle {
+ continue;
+ }
+ let raw = lines.next()?.trim();
+ let value = raw.strip_prefix("<string>")?.strip_suffix("</string>")?;
+ let value = xml_unescape(value);
+ if !value.is_empty() {
+ return Some(value);
+ }
+ }
+ None
+}
+
+/// [`xml_escape`] 的逆操作。
+#[cfg(target_os = "macos")]
+pub(crate) fn xml_unescape(value: &str) -> String {
+ value
+ .replace("&lt;", "<")
+ .replace("&gt;", ">")
+ .replace("&quot;", "\"")
+ .replace("&amp;", "&")
+}
+
+// ---------------------------------------------------------------------------
+// 平台 I/O
+// ---------------------------------------------------------------------------
+
+/// 用户主目录(`$HOME`),复用 `config::user_home_dir` 的平台语义。
+pub(crate) fn home_dir() -> Result<PathBuf, String> {
+ crate::config::user_home_dir()
+ .filter(|path| !path.as_os_str().is_empty())
+ .ok_or_else(|| "DATA_DIR_ENV_HOME: $HOME 未设置".to_string())
+}
+
+/// 读取 `~/.profile`(不存在视为空文件,读失败才报错)。
+pub(crate) fn read_profile() -> Result<String, String> {
+ let path = home_dir()?.join(".profile");
+ match std::fs::read_to_string(&path) {
+ Ok(content) => Ok(content),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
+ Err(error) => Err(format!("DATA_DIR_ENV_READ: {}: {error}", path.display())),
+ }
+}
+
+/// 写入 `~/.profile`(备份 + 原子替换,见 `cli::path::rc::write_rc_with_backup`)。
+pub(crate) fn write_profile(content: &str) -> Result<(), String> {
+ let path = home_dir()?.join(".profile");
+ write_rc_with_backup(&path, content)
+ .map_err(|error| format!("DATA_DIR_ENV_WRITE: {}: {error}", path.display()))
+}
+
+/// 写入 `DSH_HOME`(三处机制一起写)。
+pub(crate) fn write_value(value: &str) -> Result<(), String> {
+ let profile = read_profile()?;
+ write_profile(&upsert_profile_block(&profile, value))?;
+ write_platform_extra(value)?;
+ apply_to_process(Some(value));
+ Ok(())
+}
+
+/// 清除 `DSH_HOME`(三处机制一起清)。
+pub(crate) fn clear_value() -> Result<(), String> {
+ let profile = read_profile()?;
+ let cleaned = strip_profile_block(&profile);
+ if cleaned != profile {
+ write_profile(&cleaned)?;
+ }
+ clear_platform_extra()?;
+ apply_to_process(None);
+ Ok(())
+}
+
+/// 让本进程立刻看到新值:后续 `config::get_dsh_data_path`、shim 生成与拉起的
+/// Harness 都读它,不必等重启。
+fn apply_to_process(value: Option<&str>) {
+ match value {
+ Some(text) => std::env::set_var(DATA_DIR_ENV, text),
+ None => std::env::remove_var(DATA_DIR_ENV),
+ }
+}
+
+/// 从磁盘回读持久化的值(GUI 应用由 launchd / 显示管理器启动,进程环境里可能
+/// 什么都没有)。
+pub(crate) fn read_value() -> Option<String> {
+ if let Some(value) = std::env::var(DATA_DIR_ENV)
+ .ok()
+ .map(|text| text.trim().to_string())
+ .filter(|text| !text.is_empty())
+ {
+ return Some(value);
+ }
+ if let Ok(profile) = read_profile() {
+ if let Some(value) = parse_profile_block(&profile) {
+ return Some(value);
+ }
+ }
+ read_platform_extra()
+}
+
+/// 应用启动时把持久化的值注入本进程。
+///
+/// 必须在任何 `config::get_dsh_data_path` 调用之前执行:macOS / Linux 上 GUI 应用
+/// 拿不到登录 shell 的环境,迁移过的数据目录只能靠这一步回到进程里。
+/// 只补环境、不改文件:`DSH_HOME` 已经设过(终端启动、用户手工 export)时以环境为准。
+pub(crate) fn restore_process_env() {
+ if std::env::var(DATA_DIR_ENV)
+ .map(|text| !text.trim().is_empty())
+ .unwrap_or(false)
+ {
+ return;
+ }
+ let Some(value) = read_value() else {
+ return;
+ };
+ log::info!("restored {DATA_DIR_ENV} from the persisted configuration: {value}");
+ std::env::set_var(DATA_DIR_ENV, value);
+}
+
+/// macOS:`/bin/launchctl setenv` 立刻写入当前用户的 launchd 会话,并写一份
+/// `~/Library/LaunchAgents/*.plist` 让每次登录自动重放(`setenv` 本身只活在
+/// 当前会话里,注销即失效)。
+#[cfg(target_os = "macos")]
+fn write_platform_extra(value: &str) -> Result<(), String> {
+ let plist = launch_agent_path(&home_dir()?);
+ if let Some(parent) = plist.parent() {
+ std::fs::create_dir_all(parent)
+ .map_err(|error| format!("DATA_DIR_ENV_MKDIR: {}: {error}", parent.display()))?;
+ }
+ std::fs::write(&plist, launch_agent_plist(value))
+ .map_err(|error| format!("DATA_DIR_ENV_WRITE: {}: {error}", plist.display()))?;
+ launchctl(&["setenv", DATA_DIR_ENV, value])?;
+ // 旧定义可能还留在 launchd 里:先卸载再加载,否则下次登录会重放旧值。
+ let domain = launch_domain();
+ let text = plist.to_string_lossy().into_owned();
+ let _ = launchctl(&["bootout", &domain, &text]);
+ launchctl(&["bootstrap", &domain, &text])
+}
+
+/// macOS:清掉 `setenv` 与 LaunchAgent。
+#[cfg(target_os = "macos")]
+fn clear_platform_extra() -> Result<(), String> {
+ let plist = launch_agent_path(&home_dir()?);
+ if plist.exists() {
+ let _ = launchctl(&[
+ "bootout",
+ &launch_domain(),
+ &plist.to_string_lossy().into_owned(),
+ ]);
+ std::fs::remove_file(&plist)
+ .map_err(|error| format!("DATA_DIR_ENV_REMOVE: {}: {error}", plist.display()))?;
+ }
+ let _ = launchctl(&["unsetenv", DATA_DIR_ENV]);
+ Ok(())
+}
+
+#[cfg(target_os = "macos")]
+fn read_platform_extra() -> Option<String> {
+ let plist = launch_agent_path(&home_dir().ok()?);
+ parse_launch_agent(&std::fs::read_to_string(plist).ok()?)
+}
+
+#[cfg(target_os = "macos")]
+fn launch_domain() -> String {
+ format!("gui/{}", unsafe { libc::getuid() })
+}
+
+/// 调用 `/bin/launchctl`(不走 shell,参数原样传递)。
+#[cfg(target_os = "macos")]
+fn launchctl(args: &[&str]) -> Result<(), String> {
+ let output = std::process::Command::new("/bin/launchctl")
+ .args(args)
+ .output()
+ .map_err(|error| format!("DATA_DIR_ENV_LAUNCHCTL: launchctl {}: {error}", args[0]))?;
+ if output.status.success() {
+ return Ok(());
+ }
+ let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
+ Err(format!(
+ "DATA_DIR_ENV_LAUNCHCTL: launchctl {} failed: {stderr}",
+ args[0]
+ ))
+}
+
+/// Linux:写 `~/.config/environment.d/<APP_IDENTIFIER>.conf`。
+///
+/// 只写文件、不调 `systemctl --user import-environment`:后者导入的是「当前进程
+/// 环境」,在 GUI 会话之外调用会把它清空,对 GUI 应用也没有意义。
+#[cfg(target_os = "linux")]
+fn write_platform_extra(value: &str) -> Result<(), String> {
+ let path = home_dir()?.join(ENVIRONMENT_D_FILE);
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)
+ .map_err(|error| format!("DATA_DIR_ENV_MKDIR: {}: {error}", parent.display()))?;
+ }
+ std::fs::write(&path, environment_d_content(value))
+ .map_err(|error| format!("DATA_DIR_ENV_WRITE: {}: {error}", path.display()))?;
+ Ok(())
+}
+
+#[cfg(target_os = "linux")]
+fn clear_platform_extra() -> Result<(), String> {
+ let path = home_dir()?.join(ENVIRONMENT_D_FILE);
+ match std::fs::remove_file(&path) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(format!("DATA_DIR_ENV_REMOVE: {}: {error}", path.display())),
+ }
+}
+
+#[cfg(target_os = "linux")]
+fn read_platform_extra() -> Option<String> {
+ let path = home_dir().ok()?.join(ENVIRONMENT_D_FILE);
+ parse_environment_d(&std::fs::read_to_string(path).ok()?)
+}
+
+#[cfg(not(any(target_os = "macos", target_os = "linux")))]
+fn write_platform_extra(_value: &str) -> Result<(), String> {
+ Ok(())
+}
+
+#[cfg(not(any(target_os = "macos", target_os = "linux")))]
+fn clear_platform_extra() -> Result<(), String> {
+ Ok(())
+}
+
+#[cfg(not(any(target_os = "macos", target_os = "linux")))]
+fn read_platform_extra() -> Option<String> {
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn profile_block_round_trips_and_escapes_shell_metacharacters() {
+ let value = "/Volumes/Data/D$SH Home`x`\"q\"";
+ let block = profile_block(value);
+ assert!(block.starts_with(PROFILE_MARK_START));
+ assert!(block.contains("export DSH_HOME=\"/Volumes/Data/D\\$SH Home\\`x\\`\\\"q\\\"\""));
+ assert_eq!(parse_profile_block(&block), Some(value.to_string()));
+ }
+
+ #[test]
+ fn profile_block_upsert_is_idempotent_and_keeps_other_blocks() {
+ const PATH_BLOCK: &str = "# >>> deepseek-harness dsh >>>\nexport PATH=\"$HOME/.local/bin:$PATH\"\n# <<< deepseek-harness dsh <<<\n";
+ let once = upsert_profile_block(PATH_BLOCK, "/data/dsh");
+ assert!(once.contains("export PATH="));
+ assert_eq!(parse_profile_block(&once), Some("/data/dsh".to_string()));
+ assert_eq!(upsert_profile_block(&once, "/data/dsh"), once);
+ assert_eq!(strip_profile_block(&once), PATH_BLOCK);
+ }
+
+ #[test]
+ fn parse_profile_block_ignores_foreign_exports() {
+ let content = format!("{PROFILE_MARK_START}\nexport OTHER=x\n{PROFILE_MARK_END}\n");
+ assert_eq!(parse_profile_block(&content), None);
+ assert_eq!(parse_profile_block("export DSH_HOME=/data/dsh\n"), None);
+ }
+
+ #[test]
+ fn quote_sh_only_escapes_what_a_double_quoted_shell_string_needs() {
+ assert_eq!(quote_sh("/data/dsh"), "/data/dsh");
+ assert_eq!(quote_sh("/data/a b"), "/data/a b");
+ assert_eq!(quote_sh("a\"b"), "a\\\"b");
+ assert_eq!(quote_sh("a$b"), "a\\$b");
+ assert_eq!(quote_sh("a\\b"), "a\\\\b");
+ }
+
+ #[test]
+ fn environment_d_quoting_matches_systemd_rules() {
+ assert_eq!(quote_environment_d("/data/dsh"), "/data/dsh");
+ assert_eq!(quote_environment_d("/data/D$SH"), "/data/D$$SH");
+ assert_eq!(quote_environment_d("C:\\data"), "C:\\data");
+ assert_eq!(parse_environment_d("# c\nDSH_HOME=\"/data/dsh\"\n"), Some("/data/dsh".to_string()));
+ assert_eq!(parse_environment_d("DSH_HOME=\n"), None);
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn launch_agent_plist_is_well_formed_xml_with_escaped_values() {
+ let value = "/Volumes/a&b/<dsh>";
+ let plist = launch_agent_plist(value);
+ assert!(plist.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
+ assert!(plist.contains("<string>/bin/launchctl</string>"));
+ assert!(plist.contains("<string>setenv</string>"));
+ assert!(plist.contains("<string>/Volumes/a&amp;b/&lt;dsh&gt;</string>"));
+ assert!(plist.contains("<key>RunAtLoad</key>"));
+ assert!(plist.ends_with("</plist>\n"));
+ assert_eq!(parse_launch_agent(&plist), Some(value.to_string()));
+ // 有 plutil 的机器上顺带做一次真实语法校验
+ let dir = std::env::temp_dir().join(format!("dsh-launch-agent-{}", std::process::id()));
+ let _ = std::fs::create_dir_all(&dir);
+ let file = dir.join("env.plist");
+ std::fs::write(&file, &plist).unwrap();
+ let lint = std::process::Command::new("/usr/bin/plutil")
+ .args(["-lint", file.to_str().unwrap()])
+ .output();
+ if let Ok(output) = lint {
+ assert!(output.status.success(), "plutil -lint rejected the plist");
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/src-tauri/src/service/mod.rs b/src-tauri/src/service/mod.rs
index dc0db049..f48344ad 100644
--- a/src-tauri/src/service/mod.rs
+++ b/src-tauri/src/service/mod.rs
@@ -1,6 +1,7 @@
pub mod backup;
pub mod cli;
pub mod core;
+pub mod data_dir;
pub mod download;
pub mod fs_guard;
pub mod migrate;
diff --git a/src-tauri/templates/installer.nsi b/src-tauri/templates/installer.nsi
index e524fc45..d3fc68cc 100644
--- a/src-tauri/templates/installer.nsi
+++ b/src-tauri/templates/installer.nsi
@@ -1,4 +1,4 @@
-; This file is forked from Tauri's NSIS installer template, at tauri-bundler v2.9.4:
+; This file is forked from Tauri's NSIS installer template, at tauri-bundler v2.9.4:
; https://github.com/tauri-apps/tauri/blob/tauri-bundler-v2.9.4/crates/tauri-bundler/src/bundle/windows/nsis/installer.nsi
;
; Keep it in sync with upstream tauri-bundler upgrades, but preserve the
@@ -409,8 +409,86 @@ FunctionEnd
; 5. Choose install directory page
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
!insertmacro MUI_PAGE_DIRECTORY
+; 6. Data directory page (Deepseek Harness Desktop)
+;
+; Records where the Harness keeps its data (sessions, profiles, plugins) as
+; the user-level DSH_HOME variable. The in-app "Settings - Data directory"
+; panel migrates an existing installation and can be used again at any time,
+; so this page only has to cover a first install.
+Var DshDataDirNew
+Var DshDataDirOriginal
+Var DshDataDirCtl
+Var DshDataDirChanged
+Page custom DshDataDirPage DshDataDirLeave
+
+Function DshDataDirPage
+ ; Silent and passive installs must not change anything, and a cross-version
+ ; upgrade (/UPDATE) keeps the location the running installation uses.
+ ${If} $PassiveMode = 1
+ ${OrIf} ${Silent}
+ Abort
+ ${EndIf}
+ ${If} $UpdateMode = 1
+ Abort
+ ${EndIf}
+
+ !insertmacro MUI_HEADER_TEXT "$(DshDataDirTitle)" "$(DshDataDirDesc)"
+ nsDialogs::Create 1018
+ Pop $0
+ ${If} $0 == error
+ Abort
+ ${EndIf}
+ ${IfThen} $(^RTL) = 1 ${|} nsDialogs::SetRTL $(^RTL) ${|}
+
+ ${NSD_CreateLabel} 0 0 100% 24u "$(DshDataDirHint)"
+ Pop $1
+
+ ${NSD_CreateDirRequest} 0 30u 76% 13u "$DshDataDirNew"
+ Pop $DshDataDirCtl
+
+ ${NSD_CreateBrowseButton} 78% 30u 22% 13u "$(DshDataDirPick)"
+ Pop $1
+ ${NSD_OnClick} $1 DshDataDirPick
+
+ nsDialogs::Show
+FunctionEnd
+
+Function DshDataDirPick
+ ${NSD_GetText} $DshDataDirCtl $0
+ ${If} $0 == ""
+ StrCpy $0 "$DshDataDirNew"
+ ${EndIf}
+ nsDialogs::SelectFolderDialog "$(DshDataDirPick)" "$0"
+ Pop $1
+ ${If} $1 != error
+ ${NSD_SetText} $DshDataDirCtl "$1"
+ ${EndIf}
+FunctionEnd
+
+Function DshDataDirLeave
+ ${NSD_GetText} $DshDataDirCtl $0
+ ${If} $0 == ""
+ StrCpy $0 "$DshDataDirNew"
+ ${EndIf}
+
+ ; Only an absolute path is usable: a drive-qualified path ("X:...") or a
+ ; UNC path ("\\server\share"). Anything else would silently resolve
+ ; relative to the installer's own working directory.
+ StrCpy $2 $0 1
+ StrCpy $3 $0 1 1
+ ${If} $3 == ":"
+ ${ElseIf} $2 == "\"
+ ${Else}
+ MessageBox MB_ICONEXCLAMATION "$(DshDataDirInvalid)"
+ Abort
+ ${EndIf}
+
+ StrCpy $DshDataDirNew $0
+ StrCpy $DshDataDirChanged 1
+FunctionEnd
+
-; 6. Start menu shortcut page
+; 7. Start menu shortcut page
Var AppStartMenuFolder
!if "${STARTMENUFOLDER}" != ""
!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive
@@ -420,10 +498,10 @@ Var AppStartMenuFolder
!endif
!insertmacro MUI_PAGE_STARTMENU Application $AppStartMenuFolder
-; 7. Installation page
+; 8. Installation page
!insertmacro MUI_PAGE_INSTFILES
-; 8. Finish page
+; 9. Finish page
;
; Don't auto jump to finish page after installation page,
; because the installation page has useful info that can be used debug any issues with the installer.
@@ -496,6 +574,22 @@ FunctionEnd
!include "{{this}}"
{{/each}}
+; Deepseek Harness Desktop: strings for the "Data directory" page.
+; ${LANG_SIMPCHINESE} only exists when SimpChinese is one of the bundled
+; languages, so that block is guarded; English is always present.
+!ifdef LANG_SIMPCHINESE
+LangString DshDataDirTitle ${LANG_SIMPCHINESE} "数据存放目录"
+LangString DshDataDirDesc ${LANG_SIMPCHINESE} "选择 Harness 会话、档案与插件数据的存放位置。安装后可在「设置 - 数据目录」中随时迁移。"
+LangString DshDataDirHint ${LANG_SIMPCHINESE} "默认位置是当前用户主目录下的 .dsh;安装完成后仍可随时修改。"
+LangString DshDataDirPick ${LANG_SIMPCHINESE} "浏览..."
+LangString DshDataDirInvalid ${LANG_SIMPCHINESE} "请填写绝对路径,例如 D:\DSHHome。"
+!endif
+LangString DshDataDirTitle ${LANG_ENGLISH} "Data directory"
+LangString DshDataDirDesc ${LANG_ENGLISH} "Choose where Harness keeps its sessions, profiles and plugins. You can move it later in Settings - Data directory."
+LangString DshDataDirHint ${LANG_ENGLISH} "The default location is .dsh in your user profile; you can change this at any time after installation."
+LangString DshDataDirPick ${LANG_ENGLISH} "Browse..."
+LangString DshDataDirInvalid ${LANG_ENGLISH} "Enter an absolute path, for example D:\DSHHome."
+
Function .onInit
${GetOptions} $CMDLINE "/P" $PassiveMode
${IfNot} ${Errors}
@@ -543,6 +637,23 @@ Function .onInit
!if "${INSTALLMODE}" == "both"
!insertmacro MULTIUSER_INIT
!endif
+
+ ; Deepseek Harness Desktop: pre-fill the data directory page with the
+ ; location this installation would use today - the persisted user-level
+ ; override first, then whatever this process inherited, then the default
+ ; location. The persisted value wins on purpose: the environment this
+ ; installer inherited can be older than the last change, and clicking
+ ; straight through the page would then write that stale path back.
+ ReadRegStr $DshDataDirOriginal HKCU "Environment" "DSH_HOME"
+ ReadEnvStr $DshDataDirNew "DSH_HOME"
+ ${If} $DshDataDirOriginal == ""
+ StrCpy $DshDataDirOriginal "$DshDataDirNew"
+ ${Else}
+ StrCpy $DshDataDirNew "$DshDataDirOriginal"
+ ${EndIf}
+ ${If} $DshDataDirNew == ""
+ StrCpy $DshDataDirNew "$PROFILE\.dsh"
+ ${EndIf}
FunctionEnd
@@ -752,6 +863,28 @@ Section Install
Call CreateOrUpdateDesktopShortcut
${EndIf}
+ ; Deepseek Harness Desktop: persist the data directory picked on the
+ ; "Data directory" page as the user-level DSH_HOME variable. The app and
+ ; the CLI shims resolve their data directory from that variable, so it is
+ ; the single source of truth for where the Harness keeps its data. Silent,
+ ; passive and upgrade installs never reach the page, and therefore always
+ ; leave an existing value untouched.
+ ${If} $DshDataDirChanged = 1
+ ${StrCase} $R0 "$DshDataDirNew" "L"
+ ${StrCase} $R1 "$DshDataDirOriginal" "L"
+ ${If} $R0 != $R1
+ ${StrCase} $R1 "$PROFILE\.dsh" "L"
+ ${If} $R0 == $R1
+ ; The default location needs no variable: the app falls back to it.
+ DeleteRegValue HKCU "Environment" "DSH_HOME"
+ ${Else}
+ WriteRegStr HKCU "Environment" "DSH_HOME" "$DshDataDirNew"
+ ${EndIf}
+ ; Tell running processes (Explorer, open terminals) about the new
+ ; value; without this broadcast only newly launched ones would see it.
+ System::Call 'user32::SendMessageTimeoutW(p 0xFFFF, i ${WM_SETTINGCHANGE}, p 0, w "Environment", i 0x0002, i 5000, p 0)'
+ ${EndIf}
+ ${EndIf}
!ifmacrodef NSIS_HOOK_POSTINSTALL
!insertmacro NSIS_HOOK_POSTINSTALL
!endif
diff --git a/src/config/query-keys.ts b/src/config/query-keys.ts
index bfc7ed08..4fbb76e9 100644
--- a/src/config/query-keys.ts
+++ b/src/config/query-keys.ts
@@ -21,6 +21,10 @@ export const queryKeys = {
profiles: ['profiles'] as const,
/** 当前档案的备份快照列表 */
backups: ['backups'] as const,
+ /** 数据目录状态与旧目录备份(issue #871) */
+ dataDir: ['data_dir'] as const,
+ /** 数据目录下的一级子项体积(issue #871) */
+ dataDirEntries: ['data_dir_entries'] as const,
remoteMachines: ['remote_machines'] as const,
remoteEvents: ['remote_events'] as const,
} as const
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index eb6fcdd4..eefc7355 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -413,6 +413,60 @@
"config.profiles": "Profiles",
"config.plugins": "Plugins",
"config.harness": "Harness",
+ "config.dataDir": "Data Directory",
+ "data_dir.description": "The data directory holds sessions, attachments and plugin caches. It can be moved to another drive, and changed again at any time.",
+ "data_dir.current": "Current location",
+ "data_dir.default_dir": "Default location",
+ "data_dir.env_override": "DSH_HOME environment variable",
+ "data_dir.env_unset": "Not set (using the default location)",
+ "data_dir.reveal": "Open folder",
+ "data_dir.debug_hint": "Development builds always use ~/.dsh.dev and ignore DSH_HOME, so the data directory cannot be migrated here.",
+ "data_dir.unsupported": "This platform does not support migrating the data directory.",
+ "data_dir.migrate_title": "Migrate data directory",
+ "data_dir.migrate_desc": "Copies everything to the new location, verifies the copy, renames the old directory as a fallback and only then rewrites the environment variable. Nothing is ever deleted. Terminals that are already open must be reopened to pick up the new variable.",
+ "data_dir.parent_label": "New location (parent folder)",
+ "data_dir.parent_unset": "Not selected yet",
+ "data_dir.pick": "Choose…",
+ "data_dir.leaf_label": "Folder name",
+ "data_dir.leaf_placeholder": "Keep the current name when empty",
+ "data_dir.leaf_invalid": "Use only letters, digits, spaces and . _ -",
+ "data_dir.preview": "Dry run",
+ "data_dir.migrate_action": "Start migration",
+ "data_dir.plan_source": "From",
+ "data_dir.plan_target": "To",
+ "data_dir.plan_size": "Space needed",
+ "data_dir.plan_files": "Files",
+ "data_dir.plan_free": "Free at target",
+ "data_dir.plan_links": "Links",
+ "data_dir.plan_remembered": "This is where the data lived before the last migration",
+ "data_dir.plan_parent_missing": "The parent folder does not exist yet and will be created",
+ "data_dir.plan_no_space": "Not enough free space on the target drive",
+ "data_dir.usage_title": "Disk usage",
+ "data_dir.usage_desc": "Top-level folders of the current data directory, largest first.",
+ "data_dir.entry_files": "{{count}} files",
+ "data_dir.entries_empty": "Nothing to measure",
+ "data_dir.entries_empty_desc": "The data directory is empty, or it cannot be read right now.",
+ "data_dir.rollback_title": "Roll back to the old location",
+ "data_dir.rollback_desc": "The old directory is still there and can be moved back as it was. The current directory is never deleted, only set aside.",
+ "data_dir.backup_sessions": "{{count}} sessions",
+ "data_dir.rollback_action": "Roll back",
+ "data_dir.backup_no_sessions": "This backup holds no sessions — the session list may be empty after rolling back",
+ "data_dir.migrate_confirm_title": "Migrate data directory",
+ "data_dir.migrate_confirm_desc": "Copy {{source}} to {{target}}. The old directory is kept as .moved-timestamp. DSH will be stopped during the migration.",
+ "data_dir.migrate_done_toast": "Migrated to {{target}}; the old directory is kept at {{movedTo}}",
+ "data_dir.migrate_failed": "Migration failed",
+ "data_dir.rollback_confirm_title": "Roll back data directory",
+ "data_dir.rollback_confirm_desc": "Move {{backup}} back to its original place. If the current directory {{current}} is not empty it is renamed and kept. DSH will be stopped during the rollback.",
+ "data_dir.rollback_done_toast": "Rolled back to {{target}}; the current directory is kept at {{movedTo}}",
+ "data_dir.rollback_done_clean": "Rolled back to {{target}}",
+ "data_dir.rollback_failed": "Rollback failed",
+ "data_dir.pick_failed": "Failed to choose a folder",
+ "data_dir.preview_failed": "Dry run failed",
+ "data_dir.phase_scan": "Counting files…",
+ "data_dir.phase_copy": "Copied {{files}}/{{total}} files ({{bytes}})",
+ "data_dir.phase_verify": "Verifying…",
+ "data_dir.phase_finalize": "Rewriting the environment variable…",
+ "data_dir.phase_done": "Done",
"buttons.cancel": "Cancel",
"buttons.confirm": "Confirm",
"buttons.authorize": "Authorise",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index dd2648fc..e3e8201e 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -413,6 +413,60 @@
"config.profiles": "档案",
"config.plugins": "插件",
"config.harness": "核心",
+ "config.dataDir": "数据",
+ "data_dir.description": "数据目录保存会话、附件与插件缓存;可以整体搬到别的磁盘,之后随时再改。",
+ "data_dir.current": "当前位置",
+ "data_dir.default_dir": "默认位置",
+ "data_dir.env_override": "环境变量 DSH_HOME",
+ "data_dir.env_unset": "未设置(使用默认位置)",
+ "data_dir.reveal": "打开目录",
+ "data_dir.debug_hint": "开发构建固定使用 ~/.dsh.dev,忽略 DSH_HOME,因此这里不能迁移数据目录。",
+ "data_dir.unsupported": "当前平台不支持迁移数据目录。",
+ "data_dir.migrate_title": "迁移数据目录",
+ "data_dir.migrate_desc": "复制到新位置并校验通过后,旧目录改名保底,最后才改写环境变量;不会删除任何数据。已经打开的终端要重开才会读到新变量。",
+ "data_dir.parent_label": "新位置(上级目录)",
+ "data_dir.parent_unset": "尚未选择",
+ "data_dir.pick": "选择…",
+ "data_dir.leaf_label": "目录名",
+ "data_dir.leaf_placeholder": "留空则沿用当前目录名",
+ "data_dir.leaf_invalid": "目录名只能包含字母、数字、空格与 . _ -",
+ "data_dir.preview": "预检",
+ "data_dir.migrate_action": "开始迁移",
+ "data_dir.plan_source": "从",
+ "data_dir.plan_target": "到",
+ "data_dir.plan_size": "需要空间",
+ "data_dir.plan_files": "文件数",
+ "data_dir.plan_free": "目标可用",
+ "data_dir.plan_links": "链接数",
+ "data_dir.plan_remembered": "这是上次迁移之前的位置",
+ "data_dir.plan_parent_missing": "上级目录不存在,迁移时会自动创建",
+ "data_dir.plan_no_space": "目标磁盘剩余空间不足",
+ "data_dir.usage_title": "占用空间",
+ "data_dir.usage_desc": "当前数据目录下一级子项的占用情况(按体积降序)。",
+ "data_dir.entry_files": "{{count}} 个文件",
+ "data_dir.entries_empty": "没有可统计的内容",
+ "data_dir.entries_empty_desc": "数据目录还是空的,或者暂时读取不到。",
+ "data_dir.rollback_title": "回滚到旧位置",
+ "data_dir.rollback_desc": "旧目录还在,可以原样搬回去;当前目录不会被删除,只会挪到一边。",
+ "data_dir.backup_sessions": "{{count}} 个会话",
+ "data_dir.rollback_action": "回滚",
+ "data_dir.backup_no_sessions": "这个备份里没有会话,回滚后会话列表可能是空的",
+ "data_dir.migrate_confirm_title": "迁移数据目录",
+ "data_dir.migrate_confirm_desc": "从 {{source}} 复制到 {{target}},完成后旧目录改名为 .moved-时间戳 保留。迁移期间 DSH 服务会停止。",
+ "data_dir.migrate_done_toast": "已迁移到 {{target}},旧目录保留在 {{movedTo}}",
+ "data_dir.migrate_failed": "迁移失败",
+ "data_dir.rollback_confirm_title": "回滚数据目录",
+ "data_dir.rollback_confirm_desc": "把 {{backup}} 搬回原位;当前目录 {{current}} 若不为空会改名保留。回滚期间 DSH 服务会停止。",
+ "data_dir.rollback_done_toast": "已回滚到 {{target}},当前目录保留在 {{movedTo}}",
+ "data_dir.rollback_done_clean": "已回滚到 {{target}}",
+ "data_dir.rollback_failed": "回滚失败",
+ "data_dir.pick_failed": "选择目录失败",
+ "data_dir.preview_failed": "预检失败",
+ "data_dir.phase_scan": "正在统计文件…",
+ "data_dir.phase_copy": "已复制 {{files}}/{{total}} 个文件({{bytes}})",
+ "data_dir.phase_verify": "正在校验…",
+ "data_dir.phase_finalize": "正在改写环境变量…",
+ "data_dir.phase_done": "完成",
"buttons.cancel": "取消",
"buttons.confirm": "确定",
"buttons.authorize": "授权",
diff --git a/src/layout/components/navbar.tsx b/src/layout/components/navbar.tsx
index 2b7ea579..149458ba 100644
--- a/src/layout/components/navbar.tsx
+++ b/src/layout/components/navbar.tsx
@@ -15,7 +15,7 @@ import { useOverlay } from '@overlastic/react'
import { useQuery } from '@tanstack/react-query'
import { invoke } from '@tauri-apps/api/core'
import { getCurrentWindow } from '@tauri-apps/api/window'
-import { useEffect, useState } from 'react'
+import { Fragment, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { If } from 'react-if-lite'
import { cn } from 'tailwind-variants'
@@ -92,13 +92,14 @@ type FileAction = 'new-window' | 'new-chat' | 'open-folder' | 'close' | 'quit'
type HelpAction = 'task-manager' | 'keyboard-shortcuts' | 'copy-run-logs' | 'check-update' | 'about' | keyof typeof HELP_LINKS
/** 「运行」菜单项:直接打开配置对话框并定位到对应面板。 */
-const CONFIG_TABS: { id: ConfigTab, labelKey: string }[] = [
+const CONFIG_TABS = [
{ id: 'application', labelKey: 'config.application' },
{ id: 'appearance', labelKey: 'config.appearance' },
{ id: 'profiles', labelKey: 'config.profiles' },
{ id: 'plugins', labelKey: 'config.plugins' },
{ id: 'harness', labelKey: 'config.harness' },
-]
+ { id: 'dataDir', labelKey: 'config.dataDir' },
+] as const
/** WKWebView 的 macOS UA 稳定包含 Macintosh,用于切换平台原生窗口 chrome。 */
function detectMacOS() {
@@ -621,41 +622,45 @@ export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSideb
<Dropdown.Popover className="min-w-55" data-testid="dsh-navbar-menu-popover">
<Dropdown.Menu>
{CONFIG_TABS.map(item => (
- <Dropdown.Item
- key={item.id}
- id={item.id}
- data-testid={`dsh-navbar-item-${item.id}`}
- textValue={t(item.labelKey)}
- onAction={() => handleOpenConfig(item.id)}
- >
- <div className="flex w-full items-center justify-between gap-2">
- <Label>{t(item.labelKey)}</Label>
- <If cond={item.id === 'application'}>
- {/* 菜单项整行是 pressable,按钮外包一层专门拦冒泡:React Aria 的
+ <Fragment key={item.id}>
+ <Dropdown.Item
+ id={item.id}
+ data-testid={`dsh-navbar-item-${item.id}`}
+ textValue={t(item.labelKey)}
+ onAction={() => handleOpenConfig(item.id)}
+ >
+ <div className="flex w-full items-center justify-between gap-2">
+ <Label>{t(item.labelKey)}</Label>
+ <If cond={item.id === 'application'}>
+ {/* 菜单项整行是 pressable,按钮外包一层专门拦冒泡:React Aria 的
pressable 只在 pointerdown / click 上收口,pointerup 会冒泡到菜单项,
被菜单项当成「按在别处、松手落在我身上」而自行补一次 click,
顺带把菜单项动作(打开配置面板)也触发了——所以 pointerup 必须在这里拦。 */}
- <span
- className="flex shrink-0 items-center"
- onClick={event => event.stopPropagation()}
- onPointerDown={event => event.stopPropagation()}
- onPointerUp={event => event.stopPropagation()}
- >
- <Button
- className="size-6 hover:bg-background-tertiary"
- isIconOnly
- size="sm"
- variant="ghost"
- aria-label={t('app.restart')}
- data-testid="dsh-navbar-item-application-restart"
- onPress={handleQuickRestart}
+ <span
+ className="flex shrink-0 items-center"
+ onClick={event => event.stopPropagation()}
+ onPointerDown={event => event.stopPropagation()}
+ onPointerUp={event => event.stopPropagation()}
>
- <ArrowRotateRight className="size-3.5" />
- </Button>
- </span>
- </If>
- </div>
- </Dropdown.Item>
+ <Button
+ className="size-6 hover:bg-background-tertiary"
+ isIconOnly
+ size="sm"
+ variant="ghost"
+ aria-label={t('app.restart')}
+ data-testid="dsh-navbar-item-application-restart"
+ onPress={handleQuickRestart}
+ >
+ <ArrowRotateRight className="size-3.5" />
+ </Button>
+ </span>
+ </If>
+ </div>
+ </Dropdown.Item>
+ <If cond={item.id === 'appearance'}>
+ <Separator />
+ </If>
+ </Fragment>
))}
</Dropdown.Menu>
</Dropdown.Popover>
diff --git a/src/types/data-dir.ts b/src/types/data-dir.ts
new file mode 100644
index 00000000..11fa8a0f
--- /dev/null
+++ b/src/types/data-dir.ts
@@ -0,0 +1,77 @@
+/** Rust 侧 service::data_dir 的序列化形态(camelCase)。 */
+
+/** 一个可回滚的旧目录备份:迁移时原目录被改名为 `<原名>.moved-<时间戳>`。 */
+export interface MigrationBackup {
+ path: string
+ /** 目录名里的时间戳(yyyy-MM-ddTHH-mm-ss) */
+ stamp: string
+ /** 其中的会话数(备份价值的主要指标;为 0 时回滚后会话列表可能是空的) */
+ sessions: number
+}
+
+/** 数据目录下的一个顶层子目录,附占用空间。 */
+export interface DataDirEntry {
+ name: string
+ path: string
+ files: number
+ bytes: number
+}
+
+/** 迁移预检结果(目标合法性、体积、磁盘空间)。 */
+export interface MigrationPlan {
+ source: string
+ target: string
+ totalFiles: number
+ totalBytes: number
+ /** 需要重建的符号链接/联接数(复制时按链接重建,不跟随) */
+ links: number
+ /** 目标所在磁盘的可用字节(探测失败时为 0) */
+ targetFreeBytes: number
+ /** 可用空间是否够(含 5% 余量;探测失败按「够」处理) */
+ enoughSpace: boolean
+ /** 目标上级目录已存在 */
+ parentExists: boolean
+ /** 目标与上次迁移记录的位置一致(提示「回到旧位置」) */
+ remembered: boolean
+}
+
+/** 迁移/回滚结果。 */
+export interface MigrationOutcome {
+ source: string
+ target: string
+ /** 旧位置:迁移时是改名后的备份目录,回滚时是「被挪到一边的当前目录」(空串表示无冲突) */
+ movedTo: string
+ files: number
+ bytes: number
+ links: number
+ sessions: number
+}
+
+/** 进度事件 data-dir://progress 的载荷。 */
+export interface DataDirProgress {
+ operation: 'migrate' | 'rollback'
+ /** 回滚只发 scan / finalize / done(不复制,因此没有 copy / verify) */
+ phase: 'scan' | 'copy' | 'verify' | 'finalize' | 'done'
+ copiedFiles: number
+ copiedBytes: number
+ totalFiles: number
+ totalBytes: number
+}
+
+/** 当前数据目录状态;supported 为 false 时面板只展示说明、不展示任何动作。 */
+export interface DataDirStatus {
+ /** 仅 Windows 正式构建可迁移(debug 构建固定用 ~/.dsh.dev,忽略 DSH_HOME) */
+ supported: boolean
+ /** 当前生效的数据目录 */
+ dataDir: string
+ /** 未设置 DSH_HOME 时使用的默认目录(回滚目标可能是它) */
+ defaultDir: string
+ /** 用户级 DSH_HOME(未设置时为空字符串) */
+ envOverride: string
+ /** 最近一次迁移是否仍可回滚(旧目录还在) */
+ rollbackAvailable: boolean
+ /** 已发现的旧目录备份,按「会话数优先、时间戳其次」排序 */
+ backups: MigrationBackup[]
+ /** debug 构建:面板据此解释「为什么这里改不了」 */
+ debugBuild: boolean
+}
diff --git a/src/types/index.ts b/src/types/index.ts
index 04bd702b..9da978ab 100644
--- a/src/types/index.ts
+++ b/src/types/index.ts
@@ -1,4 +1,5 @@
export * from './core'
+export * from './data-dir'
export * from './plugin'
export * from './profile'
export * from './runtime'
diff --git a/src/ui/config/data-dir.test.tsx b/src/ui/config/data-dir.test.tsx
new file mode 100644
index 00000000..a21f3566
--- /dev/null
+++ b/src/ui/config/data-dir.test.tsx
@@ -0,0 +1,247 @@
+// @vitest-environment jsdom
+import type { DataDirEntry, DataDirStatus, MigrationOutcome, MigrationPlan } from '@/types'
+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 { ConfigDataDir } from './data-dir'
+
+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 }) }))
+
+/** 当前数据目录(默认位置,用于断言「原地不动」的分支) */
+const DATA_DIR = 'C:\\DSHHome'
+/** 用户在主目录选择器里挑中的父目录 */
+const PICKED = 'D:\\NewHome'
+/** 迁移目标:父目录 + 目录名 */
+const TARGET = 'D:\\NewHome\\DSHHome'
+/** 迁移后旧目录被改名成的备份 */
+const BACKUP = 'C:\\Users\\me\\.dsh.moved-2026-10-02T21-33-14'
+
+const PLAN: MigrationPlan = {
+ source: DATA_DIR,
+ target: TARGET,
+ totalFiles: 12,
+ totalBytes: 2048,
+ links: 0,
+ targetFreeBytes: 1024 * 1024 * 1024,
+ enoughSpace: true,
+ parentExists: true,
+ remembered: false,
+}
+
+const OUTCOME: MigrationOutcome = {
+ source: DATA_DIR,
+ target: TARGET,
+ movedTo: BACKUP,
+ files: 12,
+ bytes: 2048,
+ links: 0,
+ sessions: 3,
+}
+
+function statusOf(overrides: Partial<DataDirStatus> = {}): DataDirStatus {
+ return {
+ supported: true,
+ dataDir: DATA_DIR,
+ defaultDir: 'C:\\Users\\me\\.dsh',
+ envOverride: DATA_DIR,
+ rollbackAvailable: false,
+ backups: [],
+ debugBuild: false,
+ ...overrides,
+ }
+}
+
+let client: QueryClient
+let backend: { status: DataDirStatus, entries: DataDirEntry[], plan: MigrationPlan, outcome: MigrationOutcome }
+
+beforeEach(() => {
+ backend = { status: statusOf(), entries: [], plan: PLAN, outcome: OUTCOME }
+ mocks.invoke.mockReset().mockImplementation(async (command: string) => {
+ if (command === 'get_data_dir_status')
+ return backend.status
+ if (command === 'list_data_dir_entries')
+ return backend.entries
+ if (command === 'pick_data_dir')
+ return PICKED
+ if (command === 'preview_data_dir_migration')
+ return backend.plan
+ if (command === 'migrate_data_dir' || command === 'rollback_data_dir')
+ return backend.outcome
+ if (command === 'launch_harness' || command === 'reveal_in_folder')
+ return null
+ throw new Error(`Unexpected command: ${command}`)
+ })
+ mocks.dialog.mockReset().mockResolvedValue(undefined)
+ mocks.toast.mockReset().mockReturnValue('toast-key')
+ 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}><ConfigDataDir /></QueryClientProvider>)
+ // data_dir.current 只在 status 查询落地后渲染,用它把首帧的 pending 状态等过去
+ await screen.findByText('data_dir.current')
+}
+
+/** 走完「选父目录 → 预检」两步,返回已可点击的迁移按钮 */
+async function readyToMigrate() {
+ await mount()
+ fireEvent.click(screen.getByRole('button', { name: 'data_dir.pick' }))
+ await screen.findByText(PICKED)
+ fireEvent.click(screen.getByRole('button', { name: 'data_dir.preview' }))
+ await screen.findByText(TARGET)
+ return screen.getByRole('button', { name: 'data_dir.migrate_action' }) as HTMLButtonElement
+}
+
+describe('data directory panel', () => {
+ it('hides every migration control in a debug build and explains why', async () => {
+ backend.status = statusOf({ supported: false, debugBuild: true })
+ await mount()
+ expect(screen.getByTestId('dsh-data-dir-unsupported').textContent).toBe('data_dir.debug_hint')
+ expect(screen.queryByText('data_dir.migrate_title')).toBeNull()
+ expect(screen.queryByText('data_dir.rollback_title')).toBeNull()
+ })
+
+ it('shows the current directory and says so when no DSH_HOME override is set', async () => {
+ backend.status = statusOf({ envOverride: '' })
+ await mount()
+ expect(screen.getByText(DATA_DIR).textContent).toBe(DATA_DIR)
+ expect(screen.getByText('data_dir.env_unset')).toBeTruthy()
+ })
+
+ it('keeps the previous parent when the folder picker is cancelled', async () => {
+ mocks.invoke.mockImplementation(async (command: string) => {
+ if (command === 'get_data_dir_status')
+ return backend.status
+ if (command === 'list_data_dir_entries')
+ return backend.entries
+ if (command === 'pick_data_dir')
+ return null
+ throw new Error(`Unexpected command: ${command}`)
+ })
+ await mount()
+ fireEvent.click(screen.getByRole('button', { name: 'data_dir.pick' }))
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledWith('pick_data_dir'))
+ expect(screen.getByText('data_dir.parent_unset')).toBeTruthy()
+ expect((screen.getByRole('button', { name: 'data_dir.preview' }) as HTMLButtonElement).disabled).toBe(true)
+ })
+
+ it('blocks the preview while the folder name is not a single path segment', async () => {
+ await mount()
+ fireEvent.click(screen.getByRole('button', { name: 'data_dir.pick' }))
+ await screen.findByText(PICKED)
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'nested/leaf' } })
+ expect(screen.getByText('data_dir.leaf_invalid')).toBeTruthy()
+ expect((screen.getByRole('button', { name: 'data_dir.preview' }) as HTMLButtonElement).disabled).toBe(true)
+ expect(mocks.invoke).not.toHaveBeenCalledWith('preview_data_dir_migration', expect.anything())
+ })
+
+ it('offers the migrate action only after a preview that fits the disk', async () => {
+ const migrate = await readyToMigrate()
+ expect(mocks.invoke).toHaveBeenCalledWith('preview_data_dir_migration', { parent: PICKED, leaf: 'DSHHome' })
+ expect(migrate.disabled).toBe(false)
+ expect(screen.getByText('data_dir.plan_source')).toBeTruthy()
+ expect(screen.getByText('2.0 KB')).toBeTruthy()
+ expect(screen.getByText('1.0 GB')).toBeTruthy()
+ expect(screen.getByText('12')).toBeTruthy()
+ })
+
+ it('blocks the migrate action when the target has not enough free space', async () => {
+ backend.plan = { ...PLAN, enoughSpace: false, parentExists: false, remembered: true }
+ const migrate = await readyToMigrate()
+ expect(migrate.disabled).toBe(true)
+ expect(screen.getByText('data_dir.plan_no_space')).toBeTruthy()
+ expect(screen.getByText('data_dir.plan_parent_missing')).toBeTruthy()
+ expect(screen.getByText('data_dir.plan_remembered')).toBeTruthy()
+ })
+
+ it('does not migrate when the confirmation is dismissed', async () => {
+ mocks.dialog.mockRejectedValue(new Error('cancelled'))
+ const migrate = await readyToMigrate()
+ fireEvent.click(migrate)
+ await waitFor(() => expect(mocks.dialog).toHaveBeenCalledTimes(1))
+ expect(mocks.invoke).not.toHaveBeenCalledWith('migrate_data_dir', expect.anything())
+ })
+
+ it('migrates only after confirmation and restarts the harness', async () => {
+ let confirm!: () => void
+ mocks.dialog.mockImplementation(() => new Promise<void>((resolve) => {
+ confirm = resolve
+ }))
+ const migrate = await readyToMigrate()
+ fireEvent.click(migrate)
+ await waitFor(() => expect(mocks.dialog).toHaveBeenCalledWith(expect.objectContaining({ title: 'data_dir.migrate_confirm_title' })))
+ expect(mocks.invoke).not.toHaveBeenCalledWith('migrate_data_dir', expect.anything())
+ await act(async () => {
+ confirm()
+ })
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledWith('migrate_data_dir', { parent: PICKED, leaf: 'DSHHome' }))
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledWith('launch_harness'))
+ expect(mocks.toast).toHaveBeenCalledWith('data_dir.migrate_done_toast', expect.objectContaining({ variant: 'accent' }))
+ })
+
+ it('reports a failed migration without restarting the harness', async () => {
+ mocks.invoke.mockImplementation(async (command: string) => {
+ if (command === 'get_data_dir_status')
+ return backend.status
+ if (command === 'list_data_dir_entries')
+ return backend.entries
+ if (command === 'pick_data_dir')
+ return PICKED
+ if (command === 'preview_data_dir_migration')
+ return backend.plan
+ throw new Error('DATA_DIR_COPY_INCOMPLETE: 12/34')
+ })
+ const migrate = await readyToMigrate()
+ fireEvent.click(migrate)
+ await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith(expect.stringContaining('DATA_DIR_COPY_INCOMPLETE'), { variant: 'danger' }))
+ expect(mocks.invoke).not.toHaveBeenCalledWith('launch_harness')
+ })
+
+ it('warns about a backup that carries no session and rolls back the picked one', async () => {
+ const empty = { path: 'C:\\Users\\me\\.dsh.moved-2026-09-01T10-00-00', stamp: '2026-09-01T10-00-00', sessions: 0 }
+ const full = { path: BACKUP, stamp: '2026-10-02T21-33-14', sessions: 3 }
+ backend.status = statusOf({ rollbackAvailable: true, backups: [empty, full] })
+ backend.outcome = { ...OUTCOME, movedTo: '' }
+ await mount()
+ expect(screen.getByText('data_dir.backup_no_sessions')).toBeTruthy()
+ fireEvent.click(screen.getAllByRole('button', { name: 'data_dir.rollback_action' })[1])
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledWith('rollback_data_dir', { backup: BACKUP }))
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledWith('launch_harness'))
+ expect(mocks.toast).toHaveBeenCalledWith('data_dir.rollback_done_clean', expect.objectContaining({ variant: 'accent' }))
+ })
+
+ it('does not roll back when the confirmation is dismissed', async () => {
+ mocks.dialog.mockRejectedValue(new Error('cancelled'))
+ backend.status = statusOf({ rollbackAvailable: true, backups: [{ path: BACKUP, stamp: '2026-10-02T21-33-14', sessions: 3 }] })
+ await mount()
+ fireEvent.click(screen.getByRole('button', { name: 'data_dir.rollback_action' }))
+ await waitFor(() => expect(mocks.dialog).toHaveBeenCalledTimes(1))
+ expect(mocks.invoke).not.toHaveBeenCalledWith('rollback_data_dir', expect.anything())
+ })
+
+ it('lists what the data directory holds', async () => {
+ backend.entries = [{ name: 'sessions', path: 'C:\\DSHHome\\sessions', files: 900, bytes: 4096 }]
+ await mount()
+ expect(await screen.findByText('sessions')).toBeTruthy()
+ // 体积走 formatBytes;文件数走 t(key, {count}),被 mock 的 t 只回显 key,
+ // 两者被 ' · ' 拼在同一个 <Description> 里,因此用函数匹配器断言整段文本
+ expect(screen.getByText((_, element) => element?.tagName === 'SPAN' && element.textContent === '4.0 KB · data_dir.entry_files')).toBeTruthy()
+ expect(screen.queryByText('data_dir.entries_empty')).toBeNull()
+ })
+
+ it('falls back to the empty state when the data directory has no sub-directory', async () => {
+ await mount()
+ expect(await screen.findByText('data_dir.entries_empty')).toBeTruthy()
+ })
+})
diff --git a/src/ui/config/data-dir.tsx b/src/ui/config/data-dir.tsx
new file mode 100644
index 00000000..d586fb10
--- /dev/null
+++ b/src/ui/config/data-dir.tsx
@@ -0,0 +1,472 @@
+import type { DataDirEntry, DataDirProgress, DataDirStatus, MigrationBackup, MigrationOutcome, MigrationPlan } from '@/types'
+import { Folder } from '@gravity-ui/icons'
+import { Alert, Button, Description, Input, Label, Spinner } from '@heroui/react'
+import { useOverlay } from '@overlastic/react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { invoke } from '@tauri-apps/api/core'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { If } from 'react-if-lite'
+import { Info } from '@/components/info'
+import { Item } from '@/components/item'
+import { Modal } from '@/components/modal'
+import { Panel } from '@/components/panel'
+import { queryKeys } from '@/config/query-keys'
+import { useInvalidateOnSettingUpdated } from '@/hooks/use-invalidate-on-setting-updated'
+import { useListen } from '@/hooks/use-listen'
+import { store } from '@/store'
+import { silence } from '@/utils/silence'
+import { toast } from '@/utils/toast'
+
+/**
+ * 目录名白名单:与 Rust 侧 join_leaf 的校验逐字对应。
+ * 拒绝分隔符与绝对路径,否则用户填一个 \\?\D:\x 就能把数据目录建到没选过的地方。
+ */
+const LEAF_PATTERN = /^[\w .-]+$/
+
+/** 进度面板保留的日志行数(Panel.Progress 只展示最后 5 行)。 */
+const LOG_LIMIT = 8
+
+/**
+ * 预检结果的占位值:planKey 为空串,因此永远不满足「与当前输入一致」,
+ * 这样预检卡片可以用 <If cond={planReady}> 渲染,不必在 JSX 里写三元或做非空断言。
+ */
+const EMPTY_PLAN: MigrationPlan = {
+ source: '',
+ target: '',
+ totalFiles: 0,
+ totalBytes: 0,
+ links: 0,
+ targetFreeBytes: 0,
+ enoughSpace: false,
+ parentExists: false,
+ remembered: false,
+}
+
+/** 把字节转成人类可读体积(保留 1 位小数)。 */
+function formatBytes(bytes: number): string {
+ const kb = 1024
+ if (bytes < kb)
+ return `${bytes} B`
+ if (bytes < kb * kb)
+ return `${(bytes / kb).toFixed(1)} KB`
+ if (bytes < kb * kb * kb)
+ return `${(bytes / kb / kb).toFixed(1)} MB`
+ return `${(bytes / kb / kb / kb).toFixed(1)} GB`
+}
+
+/** 取路径最后一段(跨盘符时 \\ 与 / 都算分隔符)。 */
+function basenameOf(path: string): string {
+ const parts = path.split(/[\\/]/).filter(part => part !== '')
+ return parts.length === 0 ? '' : parts[parts.length - 1]
+}
+
+/**
+ * 数据目录面板(issue #871)。
+ *
+ * 数据目录的唯一真相是**用户级 DSH_HOME 环境变量**:这里既不改 app 配置、
+ * 也不做联接/软链,只做「复制到新位置 → 校验 → 旧目录改名保底 → 改写变量」,
+ * 因此面板只负责收集目标与展示预检,真正的搬家在 Rust 侧阻塞线程里跑。
+ */
+export function ConfigDataDir() {
+ const { t } = useTranslation()
+ const queryClient = useQueryClient()
+ const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })
+
+ const statusQuery = useQuery({
+ queryKey: queryKeys.dataDir,
+ queryFn: () => invoke<DataDirStatus>('get_data_dir_status'),
+ })
+ const entriesQuery = useQuery({
+ queryKey: queryKeys.dataDirEntries,
+ queryFn: () => invoke<DataDirEntry[]>('list_data_dir_entries'),
+ })
+ useInvalidateOnSettingUpdated(queryKeys.dataDir)
+ useInvalidateOnSettingUpdated(queryKeys.dataDirEntries)
+
+ const [parent, setParent] = useState('')
+ const [leaf, setLeaf] = useState('')
+ const [plan, setPlan] = useState<MigrationPlan>(EMPTY_PLAN)
+ const [planKey, setPlanKey] = useState('')
+ const [progress, setProgress] = useState<DataDirProgress | null>(null)
+ const [logs, setLogs] = useState<string[]>([])
+
+ const status = statusQuery.data ?? null
+ const entries = entriesQuery.data ?? []
+ const backups = status === null ? [] : status.backups
+ const entriesError = entriesQuery.error ? String(entriesQuery.error) : ''
+
+ // 目录名留空时沿用当前目录的最后一段,用户改一次即可;不需要 effect 回填。
+ const suggestedLeaf = status === null ? '' : basenameOf(status.dataDir)
+ const effectiveLeaf = leaf === '' ? suggestedLeaf : leaf
+ const leafHint = LEAF_PATTERN.test(effectiveLeaf.trim()) ? '' : t('data_dir.leaf_invalid')
+ const targetKey = `${parent}::${effectiveLeaf}`
+ const planReady = planKey !== '' && planKey === targetKey
+
+ /** 把进度载荷翻成一行日志(回滚不发 copy/verify,只有 scan/finalize/done)。 */
+ function describeProgress(payload: DataDirProgress): string {
+ if (payload.phase === 'scan')
+ return t('data_dir.phase_scan')
+ if (payload.phase === 'copy')
+ return t('data_dir.phase_copy', { files: payload.copiedFiles, total: payload.totalFiles, bytes: formatBytes(payload.copiedBytes) })
+ if (payload.phase === 'verify')
+ return t('data_dir.phase_verify')
+ if (payload.phase === 'finalize')
+ return t('data_dir.phase_finalize')
+ return t('data_dir.phase_done')
+ }
+
+ useListen<DataDirProgress>('data-dir://progress', (event) => {
+ const payload = event.payload
+ setProgress(payload)
+ setLogs(prev => [...prev, describeProgress(payload)].slice(-LOG_LIMIT))
+ })
+
+ function invalidate() {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.dataDir })
+ void queryClient.invalidateQueries({ queryKey: queryKeys.dataDirEntries })
+ // 运行信息里也带 data_dir,迁移后要一起刷新
+ void queryClient.invalidateQueries({ queryKey: queryKeys.info })
+ }
+
+ const preview = useMutation({
+ mutationFn: (vars: { parent: string, leaf: string }) => invoke<MigrationPlan>('preview_data_dir_migration', vars),
+ onSuccess: (value, vars) => {
+ setPlan(value)
+ setPlanKey(`${vars.parent}::${vars.leaf}`)
+ },
+ })
+
+ const migrate = useMutation({
+ mutationFn: (vars: { parent: string, leaf: string }) => invoke<MigrationOutcome>('migrate_data_dir', vars),
+ onSuccess: invalidate,
+ })
+
+ const rollback = useMutation({
+ mutationFn: (backup: string) => invoke<MigrationOutcome>('rollback_data_dir', { backup }),
+ onSuccess: invalidate,
+ })
+
+ const busy = preview.isPending || migrate.isPending || rollback.isPending
+ const progressPercentage = progress !== null && progress.totalBytes > 0
+ ? (progress.copiedBytes / progress.totalBytes) * 100
+ : undefined
+
+ async function handleReveal(path: string) {
+ try {
+ await invoke('reveal_in_folder', { path })
+ }
+ catch (err) {
+ toast(String(err), { variant: 'danger' })
+ }
+ }
+
+ async function handlePick() {
+ try {
+ const picked = await invoke<string | null>('pick_data_dir')
+ if (picked != null) {
+ setParent(picked)
+ setPlanKey('')
+ }
+ }
+ catch (err) {
+ toast(`${t('data_dir.pick_failed')}: ${String(err)}`, { variant: 'danger' })
+ }
+ }
+
+ async function handlePreview() {
+ try {
+ await preview.mutateAsync({ parent, leaf: effectiveLeaf })
+ }
+ catch (err) {
+ toast(`${t('data_dir.preview_failed')}: ${String(err)}`, { variant: 'danger' })
+ }
+ }
+
+ async function handleMigrate() {
+ try {
+ await openDialog({
+ status: 'danger',
+ title: t('data_dir.migrate_confirm_title'),
+ description: (
+ <p>
+ {t('data_dir.migrate_confirm_desc', { source: plan.source, target: plan.target })}
+ </p>
+ ),
+ })
+ }
+ catch (e) {
+ silence(e, 'data-dir: migrate cancelled')
+ return
+ }
+ setProgress(null)
+ setLogs([])
+ try {
+ // 后端命令自己会取迁移锁并停掉 Harness,前端不再重复 shutdown
+ const outcome = await migrate.mutateAsync({ parent, leaf: effectiveLeaf })
+ setPlanKey('')
+ invoke('launch_harness').catch((e) => {
+ console.warn('[ConfigDataDir] launch_harness failed:', e)
+ })
+ const key = toast(t('data_dir.migrate_done_toast', { target: outcome.target, movedTo: outcome.movedTo }), {
+ variant: 'accent',
+ timeout: 10_000,
+ actionProps: {
+ children: t('app.restart'),
+ onPress: () => {
+ store.harness.restart()
+ toast.close(key)
+ },
+ },
+ })
+ }
+ catch (err) {
+ console.error('[ConfigDataDir] migrate failed:', err)
+ toast(`${t('data_dir.migrate_failed')}: ${String(err)}`, { variant: 'danger' })
+ }
+ }
+
+ async function handleRollback(backup: MigrationBackup) {
+ try {
+ await openDialog({
+ status: 'danger',
+ title: t('data_dir.rollback_confirm_title'),
+ description: (
+ <p>
+ {t('data_dir.rollback_confirm_desc', { backup: backup.path, current: status === null ? '' : status.dataDir })}
+ </p>
+ ),
+ })
+ }
+ catch (e) {
+ silence(e, 'data-dir: rollback cancelled')
+ return
+ }
+ setProgress(null)
+ setLogs([])
+ try {
+ const outcome = await rollback.mutateAsync(backup.path)
+ invoke('launch_harness').catch((e) => {
+ console.warn('[ConfigDataDir] launch_harness failed:', e)
+ })
+ const done = outcome.movedTo === ''
+ ? t('data_dir.rollback_done_clean', { target: outcome.target })
+ : t('data_dir.rollback_done_toast', { target: outcome.target, movedTo: outcome.movedTo })
+ const key = toast(done, {
+ variant: 'accent',
+ timeout: 10_000,
+ actionProps: {
+ children: t('app.restart'),
+ onPress: () => {
+ store.harness.restart()
+ toast.close(key)
+ },
+ },
+ })
+ }
+ catch (err) {
+ console.error('[ConfigDataDir] rollback failed:', err)
+ toast(`${t('data_dir.rollback_failed')}: ${String(err)}`, { variant: 'danger' })
+ }
+ }
+
+ return (
+ <div className="space-y-3 pl-4">
+ <Panel.Header
+ title={t('config.dataDir')}
+ description={t('data_dir.description')}
+ testId="dsh-config-panel-title"
+ action={(
+ <Button size="sm" variant="primary" className="h-8" onPress={() => handleReveal(status?.dataDir ?? '')}>
+ <Folder className="size-3.5" />
+ <span>{t('data_dir.reveal')}</span>
+ </Button>
+ )}
+ />
+
+ <If cond={status !== null}>
+ <div className="flex flex-col gap-1">
+ <Info term={t('data_dir.current')}>{status?.dataDir}</Info>
+ <Info term={t('data_dir.default_dir')}>{status?.defaultDir}</Info>
+ <Info term={t('data_dir.env_override')}>
+ <If cond={(status?.envOverride ?? '') === ''} else={status?.envOverride}>
+ {t('data_dir.env_unset')}
+ </If>
+ </Info>
+ </div>
+ </If>
+
+ <If cond={status !== null && !status.supported}>
+ <Alert status="warning" className="gap-2">
+ <Alert.Indicator />
+ <Alert.Content>
+ <Alert.Description data-testid="dsh-data-dir-unsupported">
+ <If cond={status?.debugBuild === true} else={t('data_dir.unsupported')}>
+ {t('data_dir.debug_hint')}
+ </If>
+ </Alert.Description>
+ </Alert.Content>
+ </Alert>
+ </If>
+
+ <If cond={status?.supported === true}>
+ <Panel.Header title={t('data_dir.migrate_title')} description={t('data_dir.migrate_desc')} />
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium text-ink">{t('data_dir.parent_label')}</span>
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className="min-w-0 truncate font-mono text-[11px] text-muted/80">
+ <If cond={parent === ''} else={parent}>
+ {t('data_dir.parent_unset')}
+ </If>
+ </span>
+ <Button size="sm" variant="tertiary" className="h-8" isDisabled={busy} onPress={handlePick}>
+ <span>{t('data_dir.pick')}</span>
+ </Button>
+ </div>
+ </div>
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium text-ink">{t('data_dir.leaf_label')}</span>
+ <Input
+ variant="secondary"
+ className="h-8 w-[220px]"
+ placeholder={t('data_dir.leaf_placeholder')}
+ value={effectiveLeaf}
+ onChange={(e) => {
+ setLeaf(e.target.value)
+ setPlanKey('')
+ }}
+ aria-label={t('data_dir.leaf_label')}
+ />
+ </div>
+ <If cond={leafHint !== ''}>
+ <Description className="text-[10px] text-danger">{leafHint}</Description>
+ </If>
+ <div className="flex items-center gap-2">
+ <Button
+ size="sm"
+ variant="tertiary"
+ className="h-8"
+ isDisabled={busy || parent === '' || leafHint !== ''}
+ onPress={handlePreview}
+ >
+ <If cond={preview.isPending}>
+ <Spinner size="sm" color="current" />
+ </If>
+ <span>{t('data_dir.preview')}</span>
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ className="h-8"
+ isDisabled={busy || !planReady || !plan.enoughSpace}
+ onPress={handleMigrate}
+ >
+ <If cond={migrate.isPending}>
+ <Spinner size="sm" color="current" />
+ </If>
+ <span>{t('data_dir.migrate_action')}</span>
+ </Button>
+ </div>
+ </div>
+ <If cond={planReady}>
+ <div className="flex flex-col gap-1 rounded-md border border-line bg-panel2/40 p-3">
+ <Info term={t('data_dir.plan_source')}>{plan.source}</Info>
+ <Info term={t('data_dir.plan_target')}>{plan.target}</Info>
+ <Info term={t('data_dir.plan_size')}>{formatBytes(plan.totalBytes)}</Info>
+ <Info term={t('data_dir.plan_files')}>{plan.totalFiles}</Info>
+ <Info term={t('data_dir.plan_free')}>{formatBytes(plan.targetFreeBytes)}</Info>
+ <Info term={t('data_dir.plan_links')}>{plan.links}</Info>
+ <If cond={plan.remembered}>
+ <Description className="text-[10px] text-muted">{t('data_dir.plan_remembered')}</Description>
+ </If>
+ <If cond={!plan.parentExists}>
+ <Description className="text-[10px] text-muted">{t('data_dir.plan_parent_missing')}</Description>
+ </If>
+ <If cond={!plan.enoughSpace}>
+ <Description className="text-[10px] text-danger">{t('data_dir.plan_no_space')}</Description>
+ </If>
+ </div>
+ </If>
+ </If>
+
+ <If cond={progress !== null}>
+ <Panel.Progress percentage={progressPercentage} logs={logs} />
+ </If>
+
+ <Panel.Header title={t('data_dir.usage_title')} description={t('data_dir.usage_desc')} />
+ <Panel.Loadable loading={entriesQuery.isLoading} error={entriesError}>
+ <If
+ cond={entries.length === 0}
+ else={(
+ <div className="flex flex-col gap-4">
+ {entries.map(entry => (
+ <Item
+ key={entry.path}
+ left={(
+ <Label className="text-xs font-mono text-muted">{entry.name}</Label>
+ )}
+ right={(
+ <Description className="text-xs font-mono text-muted">
+ {formatBytes(entry.bytes)}
+ {' · '}
+ {t('data_dir.entry_files', { count: entry.files })}
+ </Description>
+ )}
+ />
+ ))}
+ </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('data_dir.entries_empty')}</Label>
+ <Description className="text-xs text-muted">{t('data_dir.entries_empty_desc')}</Description>
+ </div>
+ </If>
+ </Panel.Loadable>
+
+ <If cond={status?.rollbackAvailable === true}>
+ <Panel.Header title={t('data_dir.rollback_title')} description={t('data_dir.rollback_desc')} />
+ <div className="flex flex-col gap-4">
+ {backups.map(backup => (
+ <Item
+ key={backup.path}
+ left={(
+ <>
+ <Label className="text-xs font-mono text-muted">{backup.stamp}</Label>
+ <Description className="text-xs font-mono text-muted">
+ {t('data_dir.backup_sessions', { count: backup.sessions })}
+ </Description>
+ </>
+ )}
+ right={(
+ <Button
+ size="sm"
+ variant="tertiary"
+ className="h-7"
+ isDisabled={busy}
+ onPress={() => handleRollback(backup)}
+ >
+ <If cond={rollback.isPending}>
+ <Spinner size="sm" color="current" />
+ </If>
+ <span>{t('data_dir.rollback_action')}</span>
+ </Button>
+ )}
+ footer={(
+ <div className="flex flex-col gap-1">
+ <Description className="break-all font-mono text-[10px] text-muted">{backup.path}</Description>
+ <If cond={backup.sessions === 0}>
+ <Description className="text-[10px] text-danger">{t('data_dir.backup_no_sessions')}</Description>
+ </If>
+ </div>
+ )}
+ />
+ ))}
+ </div>
+ </If>
+
+ {dialogHolder}
+ </div>
+ )
+}
diff --git a/src/ui/config/debug.tsx b/src/ui/config/debug.tsx
index 47763edc..c3b837ca 100644
--- a/src/ui/config/debug.tsx
+++ b/src/ui/config/debug.tsx
@@ -1,5 +1,5 @@
import type { RuntimeInfo } from '@/types'
-import { ArrowRotateRight, ArrowUpRightFromSquare, ChevronRight, Copy, Folder, Power } from '@gravity-ui/icons'
+import { ArrowRotateRight, ArrowUpRightFromSquare, ChevronRight, Copy, Power } from '@gravity-ui/icons'
import { Button, Chip, Description, Input, Link, ListBox, Select, Spinner, Switch } from '@heroui/react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { invoke } from '@tauri-apps/api/core'
@@ -174,14 +174,6 @@ export function ConfigDebug() {
},
})
- const { mutate: onRevealDataDir } = useMutation({
- mutationFn: () => invoke('reveal_data_dir'),
- onError: (err: unknown) => {
- console.error('[ConfigDebug] reveal data dir failed:', err)
- toast(t('messages.reveal_dir_failed'), { variant: 'danger' })
- },
- })
-
return (
<div className="space-y-3">
<Panel.Header title={t('config.application')} testId="dsh-config-panel-title" />
@@ -274,24 +266,6 @@ export function ConfigDebug() {
<Info term={t('ui.platform')}>
{info ? `${info.platform} / ${info.arch}` : '-'}
</Info>
- <div className="flex items-center justify-between gap-2 text-xs">
- <span className="shrink-0 min-w-[30%] text-muted font-medium">{t('ui.data_dir')}</span>
- <span className="min-w-0 flex items-center gap-1">
- <span className="truncate font-mono text-[11px] text-muted/80" title={info?.data_dir ?? '-'}>
- {info?.data_dir ?? '-'}
- </span>
- <Button
- size="sm"
- variant="ghost"
- isIconOnly
- className="size-6 min-w-6"
- aria-label={t('app.reveal_dir')}
- onPress={() => onRevealDataDir()}
- >
- <Folder className="size-3.5" />
- </Button>
- </span>
- </div>
</div>
</div>
<div className="border-t border-line/30" />
diff --git a/src/ui/dialog/config.tsx b/src/ui/dialog/config.tsx
index be68b6d8..385a2708 100644
--- a/src/ui/dialog/config.tsx
+++ b/src/ui/dialog/config.tsx
@@ -1,6 +1,6 @@
import type { PropsWithOverlays } from '@overlastic/react'
import type { DshPlugin } from '@/types'
-import { Brush, Cpu, LogoWindows, PersonPencil, Puzzle } from '@gravity-ui/icons'
+import { Brush, Cpu, HardDrive, LogoWindows, PersonPencil, Puzzle } from '@gravity-ui/icons'
import { cn, Modal } from '@heroui/react'
import { useDisclosure } from '@overlastic/react'
import { useListener } from '@reause/core'
@@ -13,12 +13,13 @@ import { hooks } from '@/config/hooks'
import { queryKeys } from '@/config/query-keys'
import { ConfigAppearance } from '@/ui/config/appearance'
import { ConfigCore } from '@/ui/config/core'
+import { ConfigDataDir } from '@/ui/config/data-dir'
import { ConfigDebug } from '@/ui/config/debug'
import { ConfigPlugin } from '@/ui/config/plugin'
import { ConfigProfile } from '@/ui/config/profile'
/** 配置面板标识(左侧导航与顶部「配置」菜单共用同一组值) */
-export type ConfigTab = 'appearance' | 'application' | 'profiles' | 'plugins' | 'harness'
+export type ConfigTab = 'appearance' | 'application' | 'profiles' | 'plugins' | 'harness' | 'dataDir'
export interface ConfigDialogProps extends PropsWithOverlays {
/** 打开时定位到的面板;缺省为「应用」 */
@@ -42,6 +43,7 @@ export function ConfigDialog(props: ConfigDialogProps) {
{ label: t('config.profiles'), value: 'profiles', icon: PersonPencil },
{ label: t('config.plugins'), value: 'plugins', icon: Puzzle },
{ label: t('config.harness'), value: 'harness', icon: Cpu },
+ { label: t('config.dataDir'), value: 'dataDir', icon: HardDrive },
]
const [activeTab, setActiveTab] = useState<ConfigTab>(props.tab ?? 'application')
@@ -105,6 +107,9 @@ export function ConfigDialog(props: ConfigDialogProps) {
<Case cond="harness">
<ConfigCore />
</Case>
+ <Case cond="dataDir">
+ <ConfigDataDir />
+ </Case>
</Switch>
</div>
</Modal.Body>
diff --git a/test/data-dir.test.ts b/test/data-dir.test.ts
new file mode 100644
index 00000000..ed17ddba
--- /dev/null
+++ b/test/data-dir.test.ts
@@ -0,0 +1,292 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+import { readLocale, readSource } from './setup/read-source'
+
+/** issue #871:数据目录的安装期选择与运行期迁移。 */
+const PANEL = 'src/ui/config/data-dir.tsx'
+const BRIDGE = 'src-tauri/src/bridge/data_dir.rs'
+const BUILDER = 'src-tauri/src/desktop/builder.rs'
+const MODULE = 'src-tauri/src/service/data_dir/mod.rs'
+const MIGRATE = 'src-tauri/src/service/data_dir/migrate.rs'
+const ENV = 'src-tauri/src/service/data_dir/env.rs'
+const STATE = 'src-tauri/src/service/data_dir/state.rs'
+const INSTALLER = 'src-tauri/templates/installer.nsi'
+
+const COMMANDS = [
+ 'get_data_dir_status',
+ 'pick_data_dir',
+ 'list_data_dir_entries',
+ 'preview_data_dir_migration',
+ 'migrate_data_dir',
+ 'rollback_data_dir',
+]
+
+describe('data directory panel contract', () => {
+ it('exports a named ConfigDataDir function', () => {
+ expect(readSource(PANEL)).toContain('export function ConfigDataDir')
+ })
+
+ it('invokes every data directory command', () => {
+ const source = readSource(PANEL)
+ for (const command of COMMANDS)
+ expect(source).toContain(command)
+ })
+
+ it('renders progress from the data-dir://progress event', () => {
+ expect(readSource(PANEL)).toContain('data-dir://progress')
+ expect(readSource(MODULE)).toContain('pub const PROGRESS_EVENT: &str = "data-dir://progress";')
+ })
+
+ it('uses useTranslation with no hardcoded strings', () => {
+ const source = readSource(PANEL)
+ expect(source).toContain('useTranslation')
+ const cjkRange = '[\\u4e00-\\u9fff]'
+ expect(source).not.toMatch(new RegExp(`>${cjkRange}+<`))
+ expect(source).not.toContain('useCallback')
+ expect(source).not.toContain('useMemo')
+ })
+
+ it('invalidates through the shared setting_updated hook instead of listening directly', () => {
+ const source = readSource(PANEL)
+ expect(source).toContain('useInvalidateOnSettingUpdated(queryKeys.dataDir)')
+ expect(source).toContain('useInvalidateOnSettingUpdated(queryKeys.dataDirEntries)')
+ })
+
+ it('leaves the Harness shutdown to the backend lock', () => {
+ // 前端若自己 shutdown_harness,配置对话框会连带关闭,迁移向导半路消失
+ expect(readSource(PANEL)).not.toContain('shutdown_harness')
+ expect(readSource(BRIDGE)).toContain('acquire_core_transition')
+ expect(readSource(BRIDGE)).toContain('acquire_operation_lock')
+ })
+})
+
+describe('data directory backend contract', () => {
+ it('exposes each command through the bridge', () => {
+ const source = readSource(BRIDGE)
+ for (const command of COMMANDS)
+ expect(source).toMatch(new RegExp(`pub (async )?fn ${command}`))
+ })
+
+ it('registers each command with the Tauri builder exactly once', () => {
+ const builder = readSource(BUILDER)
+ for (const command of COMMANDS) {
+ const hits = builder.split(`crate::bridge::${command}`).length - 1
+ expect(hits).toBe(1)
+ }
+ })
+
+ it('keeps the user-level DSH_HOME as the single source of truth', () => {
+ expect(readSource(ENV)).toContain('pub(super) const DATA_DIR_ENV: &str = "DSH_HOME";')
+ expect(readSource(ENV)).toContain('read_user_env(DATA_DIR_ENV)')
+ expect(readSource(ENV)).toContain('write_user_env(DATA_DIR_ENV, value)')
+ })
+})
+describe('data directory usage contract', () => {
+ it('treats a missing data directory as an empty list instead of an error', () => {
+ // 迁移刚把旧目录改名搬走、Harness 还没重建它,或安装器指向尚未创建的目录时,
+ // 「占用空间」区必须走空态文案,不能弹红色 DATA_DIR_READ。
+ const source = readSource(MODULE)
+ expect(source).toContain('entries_in(&crate::config::get_dsh_data_path(app_handle))')
+ expect(source).toContain('Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()),')
+ expect(source).toContain('DATA_DIR_READ')
+ })
+})
+
+describe('migration safety contract', () => {
+ it('cites the junction accident it must not repeat', () => {
+ const source = readSource(MODULE)
+ expect(source).toContain('issue #871')
+ expect(source).toContain('issue #848')
+ expect(source).toContain('不使用目录联接')
+ })
+
+ it('never links the new home into place', () => {
+ const source = readSource(MIGRATE)
+ expect(source).not.toContain('symlink')
+ expect(source).not.toContain('junction')
+ expect(source).toContain('fs_ops::copy_tree(source, target, &progress)?;')
+ })
+
+ it('verifies the copy by file count and total bytes before touching the source', () => {
+ const source = readSource(MIGRATE)
+ expect(source).toContain('actual.covers(&expected)')
+ expect(source).toContain('DATA_DIR_COPY_INCOMPLETE')
+ expect(source.indexOf('actual.covers(&expected)')).toBeLessThan(source.indexOf('fs::rename(source, &moved)'))
+ })
+
+ it('renames the old directory instead of deleting it', () => {
+ // 只看生产代码:测试模块里的 remove_dir_all 清的是临时目录
+ const source = readSource(MIGRATE).split('#[cfg(test)]')[0]
+ expect(source).toContain('fs::rename(source, &moved)')
+ expect(source).not.toContain('remove_dir_all')
+ expect(readSource(STATE)).toContain(`const MOVED_INFIX: &str = ".moved-";`)
+ expect(readSource(STATE)).toContain(`pub(super) const CURRENT_INFIX: &str = ".current-";`)
+ })
+
+ it('records the original location before renaming so cross-drive rollback stays possible', () => {
+ const source = readSource(MIGRATE)
+ const record = 'state::write_last_migration(app_handle, &source.to_string_lossy())?;'
+ expect(source).toContain(record)
+ expect(source.indexOf(record)).toBeLessThan(source.indexOf('fs::rename(source, &moved)'))
+ })
+
+ it('puts the old directory back when the environment write fails', () => {
+ const source = readSource(MIGRATE)
+ expect(source).toContain('if let Err(error) = env::write_user_home(&text)')
+ expect(source).toContain('if let Err(restore) = fs::rename(&moved, source)')
+ expect(source).toContain('DATA_DIR_RENAME_BACK')
+ })
+
+ it('refuses to migrate while the Harness still holds the data directory', () => {
+ const module = readSource(MODULE)
+ expect(module).toContain('pub(super) fn harness_stopped(app_handle: &AppHandle) -> bool')
+ expect(module).toContain('.harness.pid')
+ const source = readSource(MIGRATE)
+ expect(source).toContain('DATA_DIR_HARNESS_RUNNING')
+ // 预检(preview_data_dir_migration)不停服,用户点「预检」时 Harness 通常正在运行,
+ // 所以停服检查只能落在真正动手的 run() 里;放进 plan() 会让预检永远失败。
+ const guard = 'if !harness_stopped(app_handle) {'
+ const plan = source.slice(source.indexOf('pub(super) fn plan('), source.indexOf('pub(super) fn run('))
+ const run = source.slice(source.indexOf('pub(super) fn run('), source.indexOf('pub(super) fn rollback('))
+ expect(plan).not.toContain('harness_stopped')
+ expect(run).toContain(guard)
+ expect(run.indexOf(guard)).toBeLessThan(run.indexOf('fs_ops::copy_tree'))
+ })
+
+ it('confirms the Harness really stopped before touching the data directory', () => {
+ // `stop()` 成功后会把 `.harness.pid` 删掉:崩溃残留、不在 owned 注册表里的
+ // Harness 会因此看起来「已退出」,所以标记必须在停之前读、停之后再复核。
+ const bridge = readSource(BRIDGE)
+ // 逐个命令切开看顺序,而不是只数「出现了两次」:数量断言在某一处把复核挪到
+ // `stop()` 之前时照样通过,而那种顺序在「崩溃残留、不在 owned 注册表里的
+ // Harness」上会直接放行迁移——正是这道守卫要拦的场景。
+ const bodies = bridge
+ .split('#[tauri::command]')
+ .filter(body => body.includes('workflow::stop'))
+ expect(bodies.length).toBe(2)
+ for (const body of bodies) {
+ const recorded = body.indexOf('let recorded = data_dir::harness_marker(&app_handle);')
+ const reject = body.indexOf('reject_unreadable_marker(recorded)?;')
+ const stop = body.indexOf('crate::service::workflow::stop(app_handle.clone()).await?;')
+ const confirm = body.indexOf('confirm_harness_stopped(recorded)?;')
+ expect(recorded).toBeGreaterThan(-1)
+ expect(reject).toBeGreaterThan(recorded)
+ expect(stop).toBeGreaterThan(reject)
+ expect(confirm).toBeGreaterThan(stop)
+ }
+ // 停之前只拦「标记读不出来」,停之后才复核「标记里那个 PID 是否还在」:
+ // 标记里写着一个存活 PID 通常就是本应用自己刚拉起的 Harness,停之前一并
+ // 拒绝会让正常迁移永远走不下去(`stop()` 才是停它的那一步)。
+ // 停之前那道检查必须放行「存活 PID」分支
+ expect(bridge).toContain('HarnessMarker::Missing | HarnessMarker::Pid(_) => Ok(())')
+ // 停之前那一步必须排在 `stop()` 前面,否则标记已经被删、什么都查不出
+ expect(bridge.indexOf('reject_unreadable_marker(recorded)?;')).toBeLessThan(bridge.indexOf('workflow::stop'))
+ expect(bridge).toContain('DATA_DIR_HARNESS_RUNNING')
+ expect(bridge).toContain('DATA_DIR_HARNESS_MARKER_INVALID')
+ // 标记读不出来与标记不在必须分开:前者要先拒绝,否则 `stop()` 删掉标记后
+ // 就再也查不出「有个不在 owned 注册表里的 Harness 还在写这个目录」。
+ expect(bridge).toContain('HarnessMarker::Invalid')
+ expect(bridge).toContain('HarnessMarker::Missing')
+ const module = readSource(MODULE)
+ expect(module).toContain('pub(crate) enum HarnessMarker {')
+ expect(module).toContain('pub(crate) fn harness_marker(app_handle: &AppHandle) -> HarnessMarker {')
+ // `harness_stopped` 复用同一份分类,不再各写一遍解析逻辑
+ expect(module).toContain('match harness_marker(app_handle) {')
+ })
+
+ it('moves a non-empty rollback target aside instead of overwriting it', () => {
+ const source = readSource(MIGRATE)
+ expect(source).toContain('if fs_ops::is_dir_empty(&restore_to)')
+ expect(source).toContain('state::with_current_suffix(&restore_to, &stamp)?')
+ expect(source).toContain('DATA_DIR_ROLLBACK_ASIDE')
+ expect(source).toContain('DATA_DIR_BACKUP_MISSING')
+ })
+
+ it('puts the backup back when the rollback cannot rewrite the environment', () => {
+ // 回滚的最后一步是改环境变量,此时备份已搬回原位、当前目录已挪到一边;
+ // 直接 `?` 返回会让 DSH_HOME 继续指着刚被搬空的那个目录。
+ const source = readSource(MIGRATE)
+ // 切到定义处而不是调用处:`indexOf` 命中的是 rollback 里那行调用
+ const rollback = source.slice(
+ source.indexOf('pub(super) fn rollback('),
+ source.indexOf('\nfn rewrite_env_or_undo'),
+ )
+ expect(rollback).not.toContain('env::write_user_home(&text)?')
+ expect(rollback).toContain('rewrite_env_or_undo(&chosen, &restore_to, &aside, apply)?;')
+ // 「写失败时到底有没有复原」不看字符串、看行为:Rust 侧
+ // `env_write_failure_puts_both_directories_back` 注入一个必然失败的写入,
+ // 再核对备份回到 chosen、被挪到一边的当前目录回到 restore_to。
+ expect(source).toContain('fn rewrite_env_or_undo<F>(')
+ expect(source).toContain('undo_rollback(chosen, restore_to, aside);')
+ expect(source).toContain('fn undo_rollback(chosen: &Path, restore_to: &Path, aside: &str)')
+ expect(source).toContain('DATA_DIR_ROLLBACK_UNDO')
+ })
+
+ it('ranks backups by session count before timestamp', () => {
+ const source = readSource(MIGRATE)
+ expect(source).toContain('.cmp(&a.sessions)')
+ expect(source).toContain('.then_with')
+ expect(source).toContain('DATA_DIR_NO_BACKUP')
+ })
+})
+
+describe('installer data directory page', () => {
+ it('stays UTF-8 with a BOM so NSIS 3.x can compile the Chinese strings', () => {
+ const bytes = readFileSync(new URL(`../${INSTALLER}`, import.meta.url))
+ expect([...bytes.subarray(0, 3)]).toEqual([0xEF, 0xBB, 0xBF])
+ })
+
+ it('asks for the data directory after the install directory', () => {
+ const source = readSource(INSTALLER)
+ const directoryPage = source.indexOf('!insertmacro MUI_PAGE_DIRECTORY')
+ const dataPage = source.indexOf('Page custom DshDataDirPage DshDataDirLeave')
+ expect(directoryPage).toBeGreaterThan(-1)
+ expect(dataPage).toBeGreaterThan(directoryPage)
+ })
+
+ it('writes the user-level DSH_HOME and broadcasts the change', () => {
+ const source = readSource(INSTALLER)
+ expect(source).toContain('ReadRegStr $DshDataDirOriginal HKCU "Environment" "DSH_HOME"')
+ expect(source).toContain('WriteRegStr HKCU "Environment" "DSH_HOME" "$DshDataDirNew"')
+ expect(source).toContain('DeleteRegValue HKCU "Environment" "DSH_HOME"')
+ expect(source).toContain(`SendMessageTimeoutW(p 0xFFFF, i ${'$'}{WM_SETTINGCHANGE}`)
+ })
+
+ it('prefers the persisted value over the inherited environment when pre-filling', () => {
+ const source = readSource(INSTALLER)
+ const onInit = source.slice(source.indexOf('Function .onInit'), source.indexOf('Section EarlyChecks'))
+ const persistedWins = onInit.indexOf(' StrCpy $DshDataDirNew "$DshDataDirOriginal"')
+ const inheritedWins = onInit.indexOf(' StrCpy $DshDataDirOriginal "$DshDataDirNew"')
+ expect(persistedWins).toBeGreaterThan(-1)
+ expect(inheritedWins).toBeGreaterThan(-1)
+ expect(persistedWins).toBeGreaterThan(inheritedWins)
+ })
+
+ it('does not disturb updates, silent or passive installs', () => {
+ const source = readSource(INSTALLER)
+ const page = source.slice(source.indexOf('Function DshDataDirPage'), source.indexOf('Function DshDataDirPick'))
+ expect(page).toContain('$PassiveMode = 1')
+ expect(page).toContain(`${'$'}{Silent}`)
+ expect(page).toContain('$UpdateMode = 1')
+ expect(page).toContain('Abort')
+ })
+
+ it('ships both bundled languages', () => {
+ const source = readSource(INSTALLER)
+ expect(source).toContain(`LangString DshDataDirTitle ${'$'}{LANG_ENGLISH} "Data directory"`)
+ expect(source).toContain(`LangString DshDataDirTitle ${'$'}{LANG_SIMPCHINESE} "数据存放目录"`)
+ expect(source).toContain('!ifdef LANG_SIMPCHINESE')
+ })
+})
+
+describe('data directory translations', () => {
+ it('keeps both locales in step', () => {
+ const zh = readLocale('zh-CN')
+ const en = readLocale('en-US')
+ const picked = (locale: Record<string, string>) => Object.keys(locale)
+ .filter(key => key === 'config.dataDir' || key.startsWith('data_dir.'))
+ .sort()
+ expect(picked(zh)).toEqual(picked(en))
+ expect(picked(zh).length).toBeGreaterThan(40)
+ })
+})