Skip to content

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

feat(plugin): 单插件原子快照 snapshot & restore (#303) (#318)

Mao Mr439557861e01
diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rs
index 32522aba..31cd508a 100644
--- a/src-tauri/src/bridge/plugin.rs
+++ b/src-tauri/src/bridge/plugin.rs
@@ -227,3 +227,42 @@ pub fn enable_dsh_plugin(app_handle: AppHandle, id: String) -> Result<(), String
plugin::watch::force_emit(&app_handle);
Ok(())
}
+
+/// 创建单个插件的快照(覆盖式:已存在则整体替换),存档于
+/// `$DSH_HOME/.plugin-backups/<id>.tgz`。
+#[tauri::command]
+pub fn snapshot_plugin(app_handle: AppHandle, id: String) -> Result<plugin::snapshot::SnapshotInfo, String> {
+ plugin::snapshot::create(&app_handle, &id)
+}
+
+/// 批量创建插件快照(升级前置自动快照):单项失败只记录在结果里,不阻断其它项。
+#[tauri::command]
+pub fn snapshot_plugins(
+ app_handle: AppHandle,
+ ids: Vec<String>,
+) -> Result<Vec<plugin::snapshot::SnapshotResult>, String> {
+ Ok(plugin::snapshot::create_many(&app_handle, &ids))
+}
+
+/// 查询单个插件的快照信息(存在性 + 时间 + 大小 + 是否含配置段)。
+#[tauri::command]
+pub fn get_plugin_backup(
+ app_handle: AppHandle,
+ id: String,
+) -> plugin::snapshot::PluginBackupInfo {
+ plugin::snapshot::get(&app_handle, &id)
+}
+
+/// 还原单个插件的快照(覆盖式,内部停服务;仅第三方可行动插件允许)。
+#[tauri::command]
+pub async fn restore_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {
+ plugin::snapshot::restore(&app_handle, &id).await?;
+ plugin::watch::force_emit(&app_handle);
+ Ok(())
+}
+
+/// 删除单个插件的快照(卸载级联清理 / 手动删除):幂等,无快照视为成功。
+#[tauri::command]
+pub fn delete_plugin_backup(app_handle: AppHandle, id: String) -> Result<(), String> {
+ plugin::snapshot::delete(&app_handle, &id)
+}
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index e1a0767b..cb5c33a8 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -526,6 +526,11 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::remove_dsh_plugin,
crate::bridge::disable_dsh_plugin,
crate::bridge::enable_dsh_plugin,
+ crate::bridge::snapshot_plugin,
+ crate::bridge::snapshot_plugins,
+ crate::bridge::get_plugin_backup,
+ crate::bridge::restore_plugin,
+ crate::bridge::delete_plugin_backup,
crate::bridge::report_plugin_error,
crate::bridge::detect_plugin_recovery,
crate::bridge::recover_plugin,
diff --git a/src-tauri/src/service/backup/archive.rs b/src-tauri/src/service/backup/archive.rs
index 5c824e83..611f56f5 100644
--- a/src-tauri/src/service/backup/archive.rs
+++ b/src-tauri/src/service/backup/archive.rs
@@ -24,7 +24,7 @@ fn create_symlink(target: &Path, dst: &Path) -> std::io::Result<()> {
}
/// 需要从归档中排除的相对路径组件(前缀匹配)。
-const EXCLUDED_NAMES: &[&str] = &[".backups", ".harness.pid"];
+const EXCLUDED_NAMES: &[&str] = &[".backups", ".harness.pid", ".plugin-backups"];
/// 需要从归档中排除的相对路径(精确匹配)。
const EXCLUDED_PATHS: &[&str] = &["node_modules/.modules.yaml"];
@@ -335,6 +335,7 @@ mod tests {
("hello.txt", "world"),
(".backups/old.tar.zst", "junk"),
(".backups/.manifest.json", "{}"),
+ (".plugin-backups/dsh-market.tgz", "snapshot"),
]);
let dest = archive_dest(&source);
create_archive(&source, &dest, false).unwrap();
@@ -343,6 +344,10 @@ mod tests {
entries.iter().all(|e| !e.contains(".backups")),
".backups 应被排除,实际条目: {entries:?}"
);
+ assert!(
+ entries.iter().all(|e| !e.contains(".plugin-backups")),
+ ".plugin-backups 应被排除(防单插件快照被整库备份递归包含),实际条目: {entries:?}"
+ );
assert!(
entries.iter().any(|e| e.contains("hello.txt")),
"hello.txt 应存在"
diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rs
index ac1d2e53..cd9eda0c 100644
--- a/src-tauri/src/service/plugin/install/mod.rs
+++ b/src-tauri/src/service/plugin/install/mod.rs
@@ -178,7 +178,10 @@ async fn install_with_cancel(
// 旧档案可能由早期版本创建,没有同步 Harness 的最小发布时间例外;补齐
// 精确的已审查 zod 版本,避免 registry 元数据瞬时失败阻断插件安装(issue #222)。
super::ensure_profile_pnpm_policy(app_handle)?;
- // 安装前停止运行中的服务,避免资源冲突
+ // 安装前停止运行中的服务,避免资源冲突。
+ // 记录停服结果:停服失败意味着服务可能仍在运行、插件目录可能被写入,
+ // 此时创建快照会捕获不一致状态,因此停服失败时跳过快照(不终止安装)。
+ let mut stopped = true;
if workflow::has_owned_process() {
// 停服务会让用户感到"重启",先在日志面板讲清缘由(issue #48)
let _ = window.emit(
@@ -188,8 +191,22 @@ async fn install_with_cancel(
},
);
log::info!("Stopping running harness service before installing plugins");
- if let Err(e) = workflow::stop(app_handle.clone()).await {
- log::warn!("failed to stop harness before plugin install: {e}");
+ stopped = match workflow::stop(app_handle.clone()).await {
+ Ok(()) => true,
+ Err(e) => {
+ log::warn!("failed to stop harness before plugin install: {e}");
+ false
+ }
+ };
+ }
+ // 安装/升级前自动快照已安装的插件(覆盖式),失败仅告警不阻断安装。
+ // 仅在服务已确认停止后执行,保证快照一致
+ // (issue #303:自动快照失败不阻塞主流程,避免升级被陈旧快照问题拖垮)。
+ if stopped {
+ for id in ids {
+ if is_installed(app_handle, id) {
+ super::snapshot::create_best_effort(app_handle, id);
+ }
}
}
diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rs
index 00aa539a..fb7b32dd 100644
--- a/src-tauri/src/service/plugin/install/single.rs
+++ b/src-tauri/src/service/plugin/install/single.rs
@@ -80,6 +80,9 @@ pub async fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {
);
}
}
+ // 卸载级联清理单插件快照(best-effort):插件已移除,快照随之失效
+ // (issue #303:卸载后删除快照,避免残留孤儿快照占用存储)。
+ super::super::snapshot::delete_best_effort(app_handle, id);
Ok(())
}
@@ -174,7 +177,10 @@ async fn run_single_plugin_command(
// 与批量安装保持一致:旧档案也必须具备精确的 release-age 例外,
// 否则升级/卸载触发 pnpm lockfile 校验时同样会被 issue #222 的问题阻断。
super::ensure_profile_pnpm_policy(app_handle)?;
- // 插件操作会改写 profile,先停止运行中的服务(与安装一致)
+ // 插件操作会改写 profile,先停止运行中的服务(与安装一致)。
+ // 记录停服结果:停服失败意味着服务可能仍在运行、插件目录可能被写入,
+ // 此时创建快照会捕获不一致状态,因此停服失败时跳过快照(不终止升级)。
+ let mut stopped = true;
if workflow::has_owned_process() {
let _ = window.emit(
PREINSTALL_LOG_EVENT,
@@ -182,9 +188,19 @@ async fn run_single_plugin_command(
line: format!("[harness] 正在停止运行中的服务({action}插件需要短暂重启)…"),
},
);
- if let Err(e) = workflow::stop(app_handle.clone()).await {
- log::warn!("failed to stop harness before plugin {action}: {e}");
- }
+ stopped = match workflow::stop(app_handle.clone()).await {
+ Ok(()) => true,
+ Err(e) => {
+ log::warn!("failed to stop harness before plugin {action}: {e}");
+ false
+ }
+ };
+ }
+ // 升级前自动快照当前版本(覆盖式),失败仅告警不阻断升级。
+ // 仅在服务已确认停止后执行:服务运行期间插件目录可能被写入,先停服保证快照一致
+ // (issue #303:自动快照失败不阻塞主流程;还原入口在插件面板)。
+ if action == "update" && stopped {
+ super::super::snapshot::create_best_effort(app_handle, id);
}
let envs = build_plugin_envs(app_handle, prefer_bundled_pnpm);
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index d36ac3e4..aedbf738 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -36,6 +36,7 @@ mod internal;
mod preset;
mod process;
pub mod recovery;
+pub mod snapshot;
pub mod update;
pub mod verify;
pub mod watch;
diff --git a/src-tauri/src/service/plugin/snapshot.rs b/src-tauri/src/service/plugin/snapshot.rs
new file mode 100644
index 00000000..1676a70c
--- /dev/null
+++ b/src-tauri/src/service/plugin/snapshot.rs
@@ -0,0 +1,887 @@
+//! 单插件快照:创建 / 读取 / 删除 / 还原插件的原子快照(issue #303)。
+//!
+//! 快照 = `$DSH_HOME/.plugin-backups/<插件id>.tgz`,每插件单份、覆盖式替换
+//! (先写临时文件 + fsync + 同盘 rename,避免半成品归档)。无中央索引:
+//! 列表 = 枚举 `*.tgz` 读取内嵌 `manifest.json`,mtime 即快照时间。
+//!
+//! 归档内嵌 `manifest.json` 自包含元数据(pluginId / created / includeConfig /
+//! spec / patches / entryCount / archiveSize),还原前校验归档完整性
+//! (entryCount / archiveSize 与磁盘比对),防损坏归档被误还原。
+//!
+//! v1 快照 = 包体(`include_config = false`):配置段读写桥是未落地的前置任务,
+//! 按 issue 约定降级为「只还原包 + 提示重启」。归档打包插件的**真实目录**
+//! (pnpm 下 `node_modules/<name>` 是指向 `.pnpm/<name>@<ver>/node_modules/<name>`
+//! 的符号链接,先解析真实目标再归档),跳过符号链接条目,避免把链接本身当内容。
+//!
+//! 还原为三阶段 + 回滚:
+//! 1. 预检:id 校验 + 快照存在 + 归档完整性 + 操作锁 + 停止服务;
+//! 2. 暂存:同盘解压到 `.staging-*` 并校验(package.json 可解析、无逃逸、
+//! 拒绝符号链接——复用 `archive::extract_archive`);
+//! 3. 切换:真实目录 → `.backup-*` rename,暂存包体 → 真实目录 rename,
+//! 校验后清理备份;任一步失败则反转已做步骤(备份还原回原位)。
+//!
+//! 还原范围:仅 `is_actionable_plugin_ref`(第三方插件);`@deepseek-ai/*`
+//! 核心/官方包拒绝还原(快照仍允许创建)。
+
+use std::fs;
+use std::io::{Read, Write};
+use std::path::{Path, PathBuf};
+use tauri::AppHandle;
+
+use crate::config;
+use crate::service::fs_guard;
+
+use super::installed::{is_installed, profile_dir};
+use super::process::acquire_operation_lock;
+use super::recovery::is_actionable_plugin_ref;
+
+/// 快照目录名(`$DSH_HOME/.plugin-backups`)。
+const SNAPSHOT_DIR_NAME: &str = ".plugin-backups";
+/// 归档内嵌清单文件名。
+const MANIFEST_NAME: &str = "manifest.json";
+/// 归档内包体所在前缀目录。
+const PACKAGE_PREFIX: &str = "package";
+
+/// 快照信息(序列化 camelCase 给前端)。
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SnapshotInfo {
+ /// 插件 id(npm 包名)
+ pub id: String,
+ /// 快照时间(UTC,`YYYY-MM-DDTHH-MM-SS`)
+ pub created: String,
+ /// 归档字节数
+ pub size: u64,
+ /// 是否包含配置段(v1 恒为 false)
+ pub include_config: bool,
+}
+
+/// 批量快照的单项结果(单项失败不阻断其它项)。
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SnapshotResult {
+ pub id: String,
+ pub ok: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+}
+
+/// 快照查询信息(`get_plugin_backup` 返回值)。
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginBackupInfo {
+ /// 是否存在快照
+ pub exists: bool,
+ /// 快照时间(UTC),无快照时为 None
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub created: Option<String>,
+ /// 归档字节数,无快照时为 0
+ pub size: u64,
+ /// 是否包含配置段(v1 恒为 false)
+ pub include_config: bool,
+}
+
+/// 归档内嵌清单(自包含元数据,还原前据此校验完整性)。
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct SnapshotManifest {
+ plugin_id: String,
+ created: String,
+ include_config: bool,
+ /// 安装 spec(npm 包名 / git 依赖形式),还原重装时可用
+ spec: String,
+ /// 关联的 cordis 补丁条目(v1 为空)
+ patches: Vec<String>,
+ /// 归档内包体文件条目数
+ entry_count: usize,
+ /// 归档文件字节数
+ archive_size: u64,
+}
+
+/// 快照目录(`$DSH_HOME/.plugin-backups/`),不存在时自动创建。
+fn snapshot_dir(app_handle: &AppHandle) -> PathBuf {
+ let dir = config::get_dsh_data_path(app_handle).join(SNAPSHOT_DIR_NAME);
+ fs::create_dir_all(&dir).ok();
+ dir
+}
+
+/// 生成快照文件名:插件 id 可能含 `/`(scoped 包)与 `@`,`validate_id` 不认可,
+/// 先替换为 `_` 再走字符集白名单校验,杜绝 `..` / 分隔符等穿越形态。
+///
+/// 文件名不参与回读(读取靠内嵌 manifest),同名冲突仅在两个 id 净化后完全相同时
+/// 发生,实际 npm 包名几乎不可能,属可接受的覆盖语义。
+fn snapshot_filename(id: &str) -> Result<String, String> {
+ if id.trim().is_empty() {
+ return Err("SNAPSHOT_INVALID_ID: 插件 id 为空".to_string());
+ }
+ if id.len() > 128 {
+ return Err("SNAPSHOT_INVALID_ID: 插件 id 过长".to_string());
+ }
+ let sanitized: String = id
+ .chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' {
+ c
+ } else {
+ '_'
+ }
+ })
+ .collect();
+ fs_guard::validate_id(&sanitized).map_err(|e| format!("SNAPSHOT_INVALID_ID: {e}"))?;
+ if sanitized.is_empty() {
+ return Err("SNAPSHOT_INVALID_ID: 插件 id 为空".to_string());
+ }
+ Ok(format!("{sanitized}.tgz"))
+}
+
+/// 生成 UTC 时间戳(`YYYY-MM-DDTHH-MM-SS`),与档案备份一致。
+fn now_timestamp() -> String {
+ use time::OffsetDateTime;
+ let now = OffsetDateTime::now_utc();
+ let date = now.date();
+ let time = now.time();
+ format!(
+ "{:04}-{:02}-{:02}T{:02}-{:02}-{:02}",
+ date.year(),
+ date.month() as u8,
+ date.day(),
+ time.hour(),
+ time.minute(),
+ time.second()
+ )
+}
+
+/// 解析插件包在 `node_modules` 下的真实目录:
+/// - pnpm 布局:`node_modules/<id>` 是指向 `.pnpm/<name>@<ver>/node_modules/<name>`
+/// 的符号链接,`dunce::canonicalize` 解析到真实目录;
+/// - 非 pnpm 布局:`node_modules/<id>` 即真实目录。
+///
+/// 快照归档真实目录内容,避免把符号链接本身当内容。
+fn resolve_real_target(node_modules: &Path, id: &str) -> Result<PathBuf, String> {
+ let entry = node_modules.join(id);
+ if !entry.exists() {
+ return Err(format!(
+ "SNAPSHOT_NOT_INSTALLED: {id} 未安装({} 不存在)",
+ entry.display()
+ ));
+ }
+ let real = dunce::canonicalize(&entry)
+ .map_err(|e| format!("SNAPSHOT_RESOLVE_TARGET: {e}"))?;
+ if !real.is_dir() {
+ return Err(format!(
+ "SNAPSHOT_NOT_DIR: {id} 的安装目标 {} 不是目录",
+ real.display()
+ ));
+ }
+ Ok(real)
+}
+
+/// 统计目录下文件条目数与总字节数(跳过符号链接,与归档口径一致)。
+fn count_tree(dir: &Path) -> (usize, u64) {
+ let mut files = 0usize;
+ let mut size = 0u64;
+ let Ok(entries) = fs::read_dir(dir) else {
+ return (files, size);
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ let Ok(meta) = fs::symlink_metadata(&path) else {
+ continue;
+ };
+ if meta.file_type().is_symlink() {
+ continue;
+ }
+ if meta.is_dir() {
+ let (f, s) = count_tree(&path);
+ files += f;
+ size += s;
+ } else {
+ files += 1;
+ size += meta.len();
+ }
+ }
+ (files, size)
+}
+
+/// 递归追加目录内容到 tar 构建器(前缀 `package/`),跳过符号链接条目。
+fn append_package_tree(
+ builder: &mut tar::Builder<impl Write>,
+ dir: &Path,
+ prefix: &Path,
+) -> Result<(), String> {
+ for entry in fs::read_dir(dir).map_err(|e| format!("SNAPSHOT_READDIR: {e}"))? {
+ let entry = entry.map_err(|e| format!("SNAPSHOT_ENTRY: {e}"))?;
+ let path = entry.path();
+ let meta =
+ fs::symlink_metadata(&path).map_err(|e| format!("SNAPSHOT_METADATA: {e}"))?;
+ // 跳过符号链接(含指向目录的链接):不归档链接本身,也不递归进入
+ if meta.file_type().is_symlink() {
+ continue;
+ }
+ let rel = prefix.join(entry.file_name());
+ if meta.is_dir() {
+ let mut header = tar::Header::new_gnu();
+ header.set_entry_type(tar::EntryType::Directory);
+ header.set_mode(0o755);
+ header.set_size(0);
+ header.set_cksum();
+ builder
+ .append_data(&mut header, &rel, std::io::empty())
+ .map_err(|e| format!("SNAPSHOT_APPEND_DIR: {e}"))?;
+ append_package_tree(builder, &path, &rel)?;
+ } else {
+ let file = fs::File::open(&path).map_err(|e| format!("SNAPSHOT_OPEN: {e}"))?;
+ let mut header = tar::Header::new_gnu();
+ header.set_size(meta.len());
+ header.set_mode(0o644);
+ header.set_cksum();
+ builder
+ .append_data(&mut header, &rel, file)
+ .map_err(|e| format!("SNAPSHOT_APPEND_FILE: {e}"))?;
+ }
+ }
+ Ok(())
+}
+
+/// 创建快照归档:写入临时文件 → fsync → rename 到目标(同盘原子替换)。
+fn write_archive_atomic(dest: &Path, write_fn: impl FnOnce(&Path) -> Result<(), String>) -> Result<(), String> {
+ let tmp = dest.with_extension("tmp");
+ let _ = fs::remove_file(&tmp);
+ write_fn(&tmp)?;
+ // fsync 落盘后再 rename,保证归档完整(半成品不会出现在目标名上)。
+ // Windows 上 FlushFileBuffers 需要写访问权限,须以 read+write 打开
+ // (只读句柄 sync_all 会报 ERROR_ACCESS_DENIED os error 5)。
+ let file = fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(&tmp)
+ .map_err(|e| format!("SNAPSHOT_OPEN_TMP: {e}"))?;
+ file.sync_all().map_err(|e| format!("SNAPSHOT_FSYNC: {e}"))?;
+ fs::rename(&tmp, dest).map_err(|e| format!("SNAPSHOT_RENAME: {e}"))?;
+ Ok(())
+}
+
+/// 读取归档内嵌 manifest.json。
+fn read_manifest(path: &Path) -> Result<SnapshotManifest, String> {
+ let file = fs::File::open(path).map_err(|e| format!("SNAPSHOT_OPEN: {e}"))?;
+ let dec = flate2::read::GzDecoder::new(file);
+ let mut archive = tar::Archive::new(dec);
+ for entry in archive
+ .entries()
+ .map_err(|e| format!("SNAPSHOT_LIST: {e}"))?
+ {
+ let mut entry = entry.map_err(|e| format!("SNAPSHOT_ENTRY: {e}"))?;
+ let entry_path = entry
+ .path()
+ .map_err(|e| format!("SNAPSHOT_ENTRY_PATH: {e}"))?;
+ if entry_path == Path::new(MANIFEST_NAME) {
+ let mut buf = Vec::new();
+ entry
+ .read_to_end(&mut buf)
+ .map_err(|e| format!("SNAPSHOT_READ_MANIFEST: {e}"))?;
+ return serde_json::from_slice(&buf)
+ .map_err(|e| format!("SNAPSHOT_MANIFEST_PARSE: {e}"));
+ }
+ }
+ Err("SNAPSHOT_MANIFEST_MISSING: 归档缺少 manifest.json".to_string())
+}
+
+/// 重新统计归档内包体条目与字节数(跳过 manifest.json,与创建口径一致),
+/// 供还原前完整性校验。
+fn count_archive_package(path: &Path) -> Result<(usize, u64), String> {
+ let file = fs::File::open(path).map_err(|e| format!("SNAPSHOT_OPEN: {e}"))?;
+ let dec = flate2::read::GzDecoder::new(file);
+ let mut archive = tar::Archive::new(dec);
+ let mut files = 0usize;
+ let mut size = 0u64;
+ for entry in archive
+ .entries()
+ .map_err(|e| format!("SNAPSHOT_LIST: {e}"))?
+ {
+ let entry = entry.map_err(|e| format!("SNAPSHOT_ENTRY: {e}"))?;
+ let entry_path = entry
+ .path()
+ .map_err(|e| format!("SNAPSHOT_ENTRY_PATH: {e}"))?;
+ if entry_path == Path::new(MANIFEST_NAME) {
+ continue;
+ }
+ if entry.header().entry_type().is_file() {
+ files += 1;
+ size += entry.header().size().unwrap_or(0);
+ }
+ }
+ Ok((files, size))
+}
+
+/// 校验归档完整性:包体条目数与解压后字节数必须与内嵌 manifest 一致(防损坏归档)。
+///
+/// `archive_size` 记录的是包体原始字节数(与 gzip 压缩后文件大小不同,因此不做
+/// 磁盘文件大小比对),配合 `entry_count` 与解压字节数双重校验。
+fn verify_archive_integrity(path: &Path, manifest: &SnapshotManifest) -> Result<(), String> {
+ let (files, size) = count_archive_package(path)?;
+ if files != manifest.entry_count || size != manifest.archive_size {
+ return Err(format!(
+ "SNAPSHOT_INTEGRITY: 归档包体 {files} 项 {size}B 与清单记录 {} 项 {}B 不一致",
+ manifest.entry_count, manifest.archive_size
+ ));
+ }
+ Ok(())
+}
+
+/// 解析安装 spec:预设清单命中用 `spec`,否则回落 profile 清单 `dependencies[id]`,
+/// 再不行回落 id 本身(作为还原重装的依赖形式)。
+fn resolve_spec(app_handle: &AppHandle, id: &str) -> String {
+ if let Some(preset) = super::preset::load_presets(app_handle)
+ .iter()
+ .find(|p| p.id == id)
+ {
+ return preset.spec.clone();
+ }
+ let manifest_path = profile_dir(app_handle).join("package.json");
+ if let Ok(text) = fs::read_to_string(&manifest_path) {
+ if let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) {
+ if let Some(spec) = value
+ .get("dependencies")
+ .and_then(|d| d.get(id))
+ .and_then(|v| v.as_str())
+ {
+ return spec.to_string();
+ }
+ }
+ }
+ id.to_string()
+}
+
+/// 创建单个插件的快照(手动 / 覆盖式:已存在则整体替换)。
+///
+/// 快照对核心/官方包同样允许(只读操作),范围限制只作用于还原。
+pub fn create(app_handle: &AppHandle, id: &str) -> Result<SnapshotInfo, String> {
+ let node_modules = profile_dir(app_handle).join("node_modules");
+ let real = resolve_real_target(&node_modules, id)?;
+
+ let (entry_count, archive_size) = count_tree(&real);
+ let created = now_timestamp();
+ let manifest = SnapshotManifest {
+ plugin_id: id.to_string(),
+ created: created.clone(),
+ include_config: false,
+ spec: resolve_spec(app_handle, id),
+ patches: Vec::new(),
+ entry_count,
+ archive_size,
+ };
+
+ let dir = snapshot_dir(app_handle);
+ let dest = dir.join(snapshot_filename(id)?);
+ write_archive_atomic(&dest, |tmp| {
+ let file = fs::File::create(tmp).map_err(|e| format!("SNAPSHOT_CREATE_FILE: {e}"))?;
+ let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());
+ let mut builder = tar::Builder::new(enc);
+ // 先写 manifest.json(根)
+ let manifest_bytes = serde_json::to_vec(&manifest)
+ .map_err(|e| format!("SNAPSHOT_MANIFEST_SERIALIZE: {e}"))?;
+ let mut header = tar::Header::new_gnu();
+ header.set_size(manifest_bytes.len() as u64);
+ header.set_mode(0o644);
+ header.set_cksum();
+ builder
+ .append_data(&mut header, MANIFEST_NAME, &manifest_bytes[..])
+ .map_err(|e| format!("SNAPSHOT_APPEND_MANIFEST: {e}"))?;
+ // 再写包体(跳过符号链接)
+ append_package_tree(&mut builder, &real, Path::new(PACKAGE_PREFIX))?;
+ builder
+ .finish()
+ .map_err(|e| format!("SNAPSHOT_FINISH: {e}"))?;
+ Ok(())
+ })?;
+
+ Ok(SnapshotInfo {
+ id: id.to_string(),
+ created,
+ size: fs::metadata(&dest).map(|m| m.len()).unwrap_or(0),
+ include_config: false,
+ })
+}
+
+/// 批量创建快照(自动升级前置用):单项失败只记录在结果里,不阻断其它项。
+pub fn create_many(app_handle: &AppHandle, ids: &[String]) -> Vec<SnapshotResult> {
+ ids.iter()
+ .map(|id| match create(app_handle, id) {
+ Ok(_) => SnapshotResult {
+ id: id.clone(),
+ ok: true,
+ error: None,
+ },
+ Err(e) => SnapshotResult {
+ id: id.clone(),
+ ok: false,
+ error: Some(e),
+ },
+ })
+ .collect()
+}
+
+/// 自动快照(安装/升级前置,失败仅告警不阻断操作)。
+pub fn create_best_effort(app_handle: &AppHandle, id: &str) {
+ if let Err(e) = create(app_handle, id) {
+ log::warn!("SNAPSHOT_AUTO_FAILED: {id}: {e}");
+ }
+}
+
+/// 快照是否存在(watch 列表轻量探测,只查文件存在性)。
+pub fn has_snapshot(app_handle: &AppHandle, id: &str) -> bool {
+ let Ok(filename) = snapshot_filename(id) else {
+ return false;
+ };
+ snapshot_dir(app_handle).join(filename).is_file()
+}
+
+/// 查询快照信息(存在性 + 元数据)。
+pub fn get(app_handle: &AppHandle, id: &str) -> PluginBackupInfo {
+ let Ok(filename) = snapshot_filename(id) else {
+ return PluginBackupInfo {
+ exists: false,
+ created: None,
+ size: 0,
+ include_config: false,
+ };
+ };
+ let path = snapshot_dir(app_handle).join(filename);
+ if !path.is_file() {
+ return PluginBackupInfo {
+ exists: false,
+ created: None,
+ size: 0,
+ include_config: false,
+ };
+ }
+ // 只读一次 manifest:`read_manifest` 需解压扫描整个归档,重复调用开销重复。
+ // manifest 不可读时 created 回落当前时间(mtime 语义近似),保持 UI 可展示。
+ let manifest = read_manifest(&path).ok();
+ let created = manifest
+ .as_ref()
+ .map(|m| m.created.clone())
+ .unwrap_or_else(now_timestamp);
+ let size = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
+ let include_config = manifest.is_some_and(|m| m.include_config);
+ PluginBackupInfo {
+ exists: true,
+ created: Some(created),
+ size,
+ include_config,
+ }
+}
+
+/// 删除快照(卸载级联清理 / 手动删除):幂等,文件不存在视为成功。
+pub fn delete(app_handle: &AppHandle, id: &str) -> Result<(), String> {
+ let filename = snapshot_filename(id)?;
+ let path = snapshot_dir(app_handle).join(filename);
+ match fs::remove_file(&path) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(format!("SNAPSHOT_DELETE: {e}")),
+ }
+}
+
+/// 卸载级联清理快照(best-effort,不阻断卸载)。
+pub fn delete_best_effort(app_handle: &AppHandle, id: &str) {
+ if let Err(e) = delete(app_handle, id) {
+ log::warn!("SNAPSHOT_CASCADE_DELETE_FAILED: {id}: {e}");
+ }
+}
+
+/// 解析还原目标:已安装时解析真实目录(有效链接 → `.pnpm/...` 真实目录),
+/// 断裂链接移除后按真实目录重建;未安装时以 `node_modules/<id>` 为落点。
+fn resolve_restore_target(node_modules: &Path, id: &str) -> Result<PathBuf, String> {
+ let entry = node_modules.join(id);
+ if let Ok(meta) = fs::symlink_metadata(&entry) {
+ if meta.file_type().is_symlink() {
+ if let Ok(real) = dunce::canonicalize(&entry) {
+ return Ok(real);
+ }
+ // 断裂链接:目标不可达,移除链接后按真实目录重建(其路径即 node_modules/<id>)
+ fs::remove_file(&entry).map_err(|e| format!("SNAPSHOT_REMOVE_BROKEN_LINK: {e}"))?;
+ return Ok(entry);
+ }
+ return Ok(entry);
+ }
+ Ok(entry)
+}
+
+/// 把插件引用写回 profile 清单(还原被移除的插件时使用):`dependencies[id]` 与
+/// `dsh.profile.bundles` 均补回,使其可被加载。best-effort:失败仅告警不阻断还原。
+///
+/// 拆出纯路径版便于单元测试(不依赖 AppHandle)。
+fn write_back_manifest_refs_at(manifest_path: &Path, id: &str, spec: &str) {
+ let Ok(text) = fs::read_to_string(manifest_path) else {
+ return;
+ };
+ let Ok(mut value) = serde_json::from_str::<serde_json::Value>(&text) else {
+ return;
+ };
+ let version = if spec.is_empty() { "*" } else { spec };
+ let mut modified = false;
+ // dependencies
+ if value.get("dependencies").and_then(|d| d.get(id)).is_none() {
+ if let Some(deps) = value
+ .get_mut("dependencies")
+ .and_then(|d| d.as_object_mut())
+ {
+ deps.insert(id.to_string(), serde_json::Value::String(version.to_string()));
+ modified = true;
+ } else {
+ value["dependencies"] = serde_json::json!({ id: version });
+ modified = true;
+ }
+ }
+ // bundles
+ let bundled = value
+ .get("dsh")
+ .and_then(|d| d.get("profile"))
+ .and_then(|p| p.get("bundles"))
+ .and_then(|b| b.as_array())
+ .is_some_and(|arr| arr.iter().any(|v| v.as_str() == Some(id)));
+ if !bundled {
+ let bundles = value
+ .get_mut("dsh")
+ .and_then(|d| d.get_mut("profile"))
+ .and_then(|p| p.get_mut("bundles"))
+ .and_then(|b| b.as_array_mut());
+ match bundles {
+ Some(arr) => {
+ arr.push(serde_json::Value::String(id.to_string()));
+ modified = true;
+ }
+ None => {
+ if value.get("dsh").is_none() {
+ value["dsh"] = serde_json::json!({});
+ }
+ if value["dsh"].get("profile").is_none() {
+ value["dsh"]["profile"] = serde_json::json!({});
+ }
+ value["dsh"]["profile"]["bundles"] = serde_json::json!([id]);
+ modified = true;
+ }
+ }
+ }
+ if !modified {
+ return;
+ }
+ match serde_json::to_string_pretty(&value) {
+ Ok(rendered) => {
+ if let Err(e) = fs::write(manifest_path, format!("{rendered}\n")) {
+ log::warn!("SNAPSHOT_WRITE_MANIFEST_FAILED: {id}: {e}");
+ }
+ }
+ Err(e) => log::warn!("SNAPSHOT_RENDER_MANIFEST_FAILED: {id}: {e}"),
+ }
+}
+
+/// AppHandle 包装:把引用写回 profile 清单(best-effort)。
+fn write_back_manifest_refs(app_handle: &AppHandle, id: &str, spec: &str) {
+ write_back_manifest_refs_at(&profile_dir(app_handle).join("package.json"), id, spec);
+}
+
+/// 还原单个插件快照(覆盖式,内部停服务 + 三阶段切换 + 回滚)。
+pub async fn restore(app_handle: &AppHandle, id: &str) -> Result<(), String> {
+ // 范围限制:仅第三方可行动插件可还原
+ if !is_actionable_plugin_ref(id) {
+ return Err(format!(
+ "SNAPSHOT_RESTORE_REFUSED: 核心/官方包 {id} 不允许还原"
+ ));
+ }
+ let filename = snapshot_filename(id)?;
+ let archive_path = snapshot_dir(app_handle).join(filename);
+ if !archive_path.is_file() {
+ return Err(format!("SNAPSHOT_NOT_FOUND: {id} 无快照"));
+ }
+ // 归档完整性校验(防损坏归档被误还原)
+ let manifest = read_manifest(&archive_path)?;
+ verify_archive_integrity(&archive_path, &manifest)?;
+
+ // 操作锁 + 停止服务(与安装/卸载一致,还原期间避免资源竞争)
+ let _guard = acquire_operation_lock().await;
+ if crate::service::workflow::has_owned_process() {
+ if let Err(e) = crate::service::workflow::stop(app_handle.clone()).await {
+ log::warn!("failed to stop harness before plugin restore: {e}");
+ }
+ }
+
+ let profile = profile_dir(app_handle);
+ let node_modules = profile.join("node_modules");
+ let dest = resolve_restore_target(&node_modules, id)?;
+ let staging_parent = dest
+ .parent()
+ .ok_or_else(|| "SNAPSHOT_NO_PARENT: 还原目标缺少父目录".to_string())?;
+ fs::create_dir_all(staging_parent)
+ .map_err(|e| format!("SNAPSHOT_MKDIR_STAGING_PARENT: {e}"))?;
+
+ let token = format!("{}-{}", id.replace(['/', '\\'], "_"), std::process::id());
+ let staging = staging_parent.join(format!(".staging-{token}"));
+ let backup = staging_parent.join(format!(".backup-{token}"));
+ let _ = fs::remove_dir_all(&staging);
+ let _ = fs::remove_dir_all(&backup);
+
+ // 阶段 2:暂存解压(复用 archive::extract_archive:拒绝逃逸/符号链接)
+ if let Err(e) = crate::service::backup::archive::extract_archive(&archive_path, &staging) {
+ let _ = fs::remove_dir_all(&staging);
+ return Err(e);
+ }
+ let staged_pkg = staging.join(PACKAGE_PREFIX);
+ let validate = (|| {
+ if !staged_pkg.join("package.json").is_file() {
+ return Err("SNAPSHOT_STAGING_INVALID: 暂存包缺少 package.json".to_string());
+ }
+ let text = fs::read_to_string(staged_pkg.join("package.json"))
+ .map_err(|e| format!("SNAPSHOT_STAGING_READ: {e}"))?;
+ serde_json::from_str::<serde_json::Value>(&text)
+ .map_err(|e| format!("SNAPSHOT_STAGING_PARSE: package.json 无法解析: {e}"))?;
+ Ok(())
+ })();
+ if let Err(e) = validate {
+ let _ = fs::remove_dir_all(&staging);
+ return Err(e);
+ }
+
+ // 阶段 3:切换(dest → backup,staging/package → dest),失败反转已做步骤
+ let dest_existed = fs::symlink_metadata(&dest).is_ok();
+ if dest_existed {
+ if let Err(e) = fs::rename(&dest, &backup) {
+ let _ = fs::remove_dir_all(&staging);
+ return Err(format!("SNAPSHOT_SWITCH_BACKUP: {e}"));
+ }
+ }
+ if let Err(e) = fs::rename(&staged_pkg, &dest) {
+ // 反转:清掉可能的半成品落点,备份还原回原位
+ let _ = fs::remove_dir_all(&dest);
+ if dest_existed {
+ let _ = fs::rename(&backup, &dest);
+ }
+ let _ = fs::remove_dir_all(&staging);
+ return Err(format!("SNAPSHOT_SWITCH_STAGE: {e}"));
+ }
+ // 还原后核验:package.json 必须真实落盘(防假成功)
+ if !dest.join("package.json").is_file() {
+ let _ = fs::remove_dir_all(&dest);
+ if dest_existed {
+ let _ = fs::rename(&backup, &dest);
+ }
+ let _ = fs::remove_dir_all(&staging);
+ return Err("SNAPSHOT_VERIFY_FAILED: 还原后 package.json 缺失".to_string());
+ }
+ // 成功:清理备份与暂存
+ let _ = fs::remove_dir_all(&backup);
+ let _ = fs::remove_dir_all(&staging);
+
+ // 直铺还原的一致性:插件被移除时写回清单引用(使其可加载);
+ // 删除 pnpm-lock.yaml 让 pnpm 重建干净依赖图(best-effort)。
+ if !is_installed(app_handle, id) {
+ write_back_manifest_refs(app_handle, id, &manifest.spec);
+ }
+ if let Err(e) = fs::remove_file(profile.join("pnpm-lock.yaml")) {
+ if e.kind() != std::io::ErrorKind::NotFound {
+ log::warn!("failed to remove pnpm-lock.yaml after plugin restore: {e}");
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// 构造临时 node_modules 下插件包目录(真实目录形态,非 pnpm 链接)。
+ fn setup_package(root: &Path, name: &str) {
+ let pkg = root.join("node_modules").join(name);
+ fs::create_dir_all(&pkg).unwrap();
+ fs::write(
+ pkg.join("package.json"),
+ format!(r#"{{"name":"{name}","version":"1.0.0","main":"lib/index.js"}}"#),
+ )
+ .unwrap();
+ fs::create_dir_all(pkg.join("lib")).unwrap();
+ fs::write(pkg.join("lib").join("index.js"), "module.exports = {};").unwrap();
+ }
+
+ #[test]
+ fn filename_sanitizes_scoped_and_rejects_traversal() {
+ assert_eq!(
+ snapshot_filename("dsh-market").unwrap(),
+ "dsh-market.tgz"
+ );
+ assert_eq!(
+ snapshot_filename("@scope/pkg").unwrap(),
+ "_scope_pkg.tgz"
+ );
+ assert!(snapshot_filename("..").is_err());
+ assert!(snapshot_filename("").is_err());
+ assert!(snapshot_filename("../x").is_err());
+ assert!(snapshot_filename("a/b").is_ok()); // 净化后合法
+ }
+
+ #[test]
+ fn count_tree_skips_symlinks() {
+ let dir = std::env::temp_dir().join(format!("dsh-snap-count-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(dir.join("sub")).unwrap();
+ fs::write(dir.join("a.txt"), "hello").unwrap();
+ fs::write(dir.join("sub").join("b.txt"), "world").unwrap();
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink(dir.join("a.txt"), dir.join("link.txt")).unwrap();
+ }
+ let (files, size) = count_tree(&dir);
+ assert_eq!(files, 2);
+ assert_eq!(size, 10);
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn archive_round_trip_creates_and_reads_manifest() {
+ let dir = std::env::temp_dir().join(format!("dsh-snap-rt-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ setup_package(&dir, "dsh-market");
+ let real = resolve_real_target(&dir.join("node_modules"), "dsh-market").unwrap();
+ let (entry_count, archive_size) = count_tree(&real);
+ let manifest = SnapshotManifest {
+ plugin_id: "dsh-market".to_string(),
+ created: "2026-08-30T12-00-00".to_string(),
+ include_config: false,
+ spec: "dsh-market".to_string(),
+ patches: Vec::new(),
+ entry_count,
+ archive_size,
+ };
+ let archive = dir.join("snap.tgz");
+ write_archive_atomic(&archive, |tmp| {
+ let file = fs::File::create(tmp).unwrap();
+ let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());
+ let mut builder = tar::Builder::new(enc);
+ let bytes = serde_json::to_vec(&manifest).unwrap();
+ let mut header = tar::Header::new_gnu();
+ header.set_size(bytes.len() as u64);
+ header.set_mode(0o644);
+ header.set_cksum();
+ builder.append_data(&mut header, MANIFEST_NAME, &bytes[..]).unwrap();
+ append_package_tree(&mut builder, &real, Path::new(PACKAGE_PREFIX)).unwrap();
+ builder.finish().unwrap();
+ Ok(())
+ })
+ .unwrap();
+
+ let read = read_manifest(&archive).unwrap();
+ assert_eq!(read.plugin_id, "dsh-market");
+ assert_eq!(read.entry_count, entry_count);
+ assert_eq!(read.archive_size, archive_size);
+ verify_archive_integrity(&archive, &read).unwrap();
+
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn archive_round_trip_restores_package_content() {
+ let dir = std::env::temp_dir().join(format!("dsh-snap-ext-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ setup_package(&dir, "dsh-market");
+ let real = resolve_real_target(&dir.join("node_modules"), "dsh-market").unwrap();
+ let (entry_count, archive_size) = count_tree(&real);
+ let manifest = SnapshotManifest {
+ plugin_id: "dsh-market".to_string(),
+ created: "2026-08-30T12-00-00".to_string(),
+ include_config: false,
+ spec: "dsh-market".to_string(),
+ patches: Vec::new(),
+ entry_count,
+ archive_size,
+ };
+ let archive = dir.join("snap.tgz");
+ write_archive_atomic(&archive, |tmp| {
+ let file = fs::File::create(tmp).unwrap();
+ let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());
+ let mut builder = tar::Builder::new(enc);
+ let bytes = serde_json::to_vec(&manifest).unwrap();
+ let mut header = tar::Header::new_gnu();
+ header.set_size(bytes.len() as u64);
+ header.set_mode(0o644);
+ header.set_cksum();
+ builder.append_data(&mut header, MANIFEST_NAME, &bytes[..]).unwrap();
+ append_package_tree(&mut builder, &real, Path::new(PACKAGE_PREFIX)).unwrap();
+ builder.finish().unwrap();
+ Ok(())
+ })
+ .unwrap();
+
+ // 还原到新目录
+ let target = dir.join("restored");
+ crate::service::backup::archive::extract_archive(&archive, &target).unwrap();
+ let pkg = target.join(PACKAGE_PREFIX);
+ assert!(pkg.join("package.json").is_file());
+ assert!(pkg.join("lib").join("index.js").is_file());
+ let text = fs::read_to_string(pkg.join("package.json")).unwrap();
+ assert!(text.contains("dsh-market"));
+
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn resolve_restore_target_handles_real_dir_and_missing() {
+ let dir = std::env::temp_dir().join(format!("dsh-snap-tgt-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(dir.join("node_modules")).unwrap();
+ setup_package(&dir, "pkg-a");
+ // 真实目录
+ let t = resolve_restore_target(&dir.join("node_modules"), "pkg-a").unwrap();
+ assert_eq!(t, dir.join("node_modules").join("pkg-a"));
+ // 未安装:返回目标路径(不报错)
+ let t2 = resolve_restore_target(&dir.join("node_modules"), "pkg-b").unwrap();
+ assert_eq!(t2, dir.join("node_modules").join("pkg-b"));
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn write_back_manifest_refs_restores_deps_and_bundles() {
+ let dir = std::env::temp_dir().join(format!("dsh-snap-wb-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ let manifest_path = dir.join("package.json");
+ fs::write(
+ &manifest_path,
+ r#"{"name":"dsh-profile-web","dependencies":{},"dsh":{"profile":{"bundles":[]}}}"#,
+ )
+ .unwrap();
+
+ // 写回引用:dependencies + bundles 都应补入
+ write_back_manifest_refs_at(&manifest_path, "dsh-market", "dsh-market");
+ let content = fs::read_to_string(&manifest_path).unwrap();
+ let value: serde_json::Value = serde_json::from_str(&content).unwrap();
+ assert_eq!(value["dependencies"]["dsh-market"], "dsh-market");
+ assert_eq!(value["dsh"]["profile"]["bundles"][0], "dsh-market");
+
+ // 幂等:再次写回不重复追加
+ write_back_manifest_refs_at(&manifest_path, "dsh-market", "dsh-market");
+ let content = fs::read_to_string(&manifest_path).unwrap();
+ let value: serde_json::Value = serde_json::from_str(&content).unwrap();
+ assert_eq!(value["dependencies"].as_object().unwrap().len(), 1);
+ assert_eq!(value["dsh"]["profile"]["bundles"].as_array().unwrap().len(), 1);
+
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn write_back_manifest_refs_creates_sections_when_missing() {
+ let dir = std::env::temp_dir().join(format!("dsh-snap-wb2-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ let manifest_path = dir.join("package.json");
+ fs::write(&manifest_path, r#"{"name":"dsh-profile-web"}"#).unwrap();
+
+ // 无 dependencies / dsh 段:应整体创建,spec 为空时版本回落 `*`
+ write_back_manifest_refs_at(&manifest_path, "@scope/pkg", "");
+ let content = fs::read_to_string(&manifest_path).unwrap();
+ let value: serde_json::Value = serde_json::from_str(&content).unwrap();
+ assert_eq!(value["dependencies"]["@scope/pkg"], "*");
+ assert_eq!(value["dsh"]["profile"]["bundles"][0], "@scope/pkg");
+
+ let _ = fs::remove_dir_all(&dir);
+ }
+}
diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rs
index 72b3196a..57a4be71 100644
--- a/src-tauri/src/service/plugin/watch.rs
+++ b/src-tauri/src/service/plugin/watch.rs
@@ -63,6 +63,9 @@ pub struct DshPlugin {
/// 判定得到的「最新版本」(registry latest / git HEAD SHA);未判定或不可判定时缺省
#[serde(skip_serializing_if = "Option::is_none")]
pub latest_version: Option<String>,
+ /// 是否有单插件快照(`$DSH_HOME/.plugin-backups/<id>.tgz`),前端据此展示
+ /// 还原 / 删除快照入口
+ pub has_snapshot: bool,
/// 异常信息(安装/升级/卸载失败或页面运行期上报);`None` = 正常
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<PluginError>,
@@ -198,6 +201,7 @@ fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPlu
internal: internal_names.contains(id.as_str()),
update_available: false,
latest_version: None,
+ has_snapshot: false,
error: None,
})
})
@@ -226,6 +230,10 @@ pub fn list(app_handle: &AppHandle) -> Vec<DshPlugin> {
// 已恢复的安装错误会被过滤,避免持久化历史状态污染当前健康状态。
let registry = errors::load(app_handle);
merge_current_errors(&mut plugins, &registry);
+ // 单插件快照存在性(快照不在 profile 文件指纹里,须单独探测)
+ for plugin in &mut plugins {
+ plugin.has_snapshot = super::snapshot::has_snapshot(app_handle, &plugin.id);
+ }
plugins
}
@@ -487,6 +495,7 @@ mod tests {
internal: false,
update_available: false,
latest_version: None,
+ has_snapshot: false,
error: None,
}];
let registry = HashMap::from([(
@@ -518,6 +527,7 @@ mod tests {
internal: false,
update_available: false,
latest_version: None,
+ has_snapshot: false,
error: None,
};
let install_error = PluginError {
diff --git a/src/components/config-plugin.tsx b/src/components/config-plugin.tsx
index 80c95c91..387c080b 100644
--- a/src/components/config-plugin.tsx
+++ b/src/components/config-plugin.tsx
@@ -54,8 +54,8 @@ export function ConfigPlugin() {
const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })
- /** 行内操作进行中状态:id + 操作类型(update/remove/disable/enable),保证单例运行 */
- const [busy, setBusy] = useState<{ id: string, action: 'update' | 'remove' | 'disable' | 'enable' } | null>(null)
+ /** 行内操作进行中状态:id + 操作类型(update/remove/disable/enable/snapshot/restore/delete-snapshot),保证单例运行 */
+ const [busy, setBusy] = useState<{ id: string, action: 'update' | 'remove' | 'disable' | 'enable' | 'snapshot' | 'restore' | 'delete-snapshot' } | null>(null)
const upgrade = useMutation({
mutationFn: (id: string) => invoke<void>('update_dsh_plugin', { id }),
@@ -112,6 +112,44 @@ export function ConfigPlugin() {
toast(t('plugins.enable_failed', { name }), {})
},
})
+ const snapshot = useMutation({
+ mutationFn: (id: string) => invoke<void>('snapshot_plugin', { id }),
+ onSuccess: (_data, id) => {
+ const name = plugins.find(p => p.id === id)?.name ?? id
+ void queryClient.invalidateQueries({ queryKey: ['plugins'] })
+ toast(t('plugins.snapshot_toast', { name }), {})
+ },
+ onError: (err, id) => {
+ const name = plugins.find(p => p.id === id)?.name ?? id
+ console.error('[ConfigPlugin] snapshot failed:', err)
+ toast(t('plugins.snapshot_failed', { name }), {})
+ },
+ })
+ const restore = useMutation({
+ mutationFn: (id: string) => invoke<void>('restore_plugin', { id }),
+ onSuccess: (_data, _id) => {
+ // 还原后快照仍在(覆盖式不删快照),插件版本回到快照态:重拉列表。
+ void queryClient.invalidateQueries({ queryKey: ['plugins'] })
+ },
+ onError: (err, id) => {
+ const name = plugins.find(p => p.id === id)?.name ?? id
+ console.error('[ConfigPlugin] restore failed:', err)
+ toast(t('plugins.restore_failed', { name }), {})
+ },
+ })
+ const deleteSnapshot = useMutation({
+ mutationFn: (id: string) => invoke<void>('delete_plugin_backup', { id }),
+ onSuccess: (_data, id) => {
+ const name = plugins.find(p => p.id === id)?.name ?? id
+ void queryClient.invalidateQueries({ queryKey: ['plugins'] })
+ toast(t('plugins.snapshot_deleted_toast', { name }), {})
+ },
+ onError: (err, id) => {
+ const name = plugins.find(p => p.id === id)?.name ?? id
+ console.error('[ConfigPlugin] delete snapshot failed:', err)
+ toast(t('plugins.snapshot_delete_failed', { name }), {})
+ },
+ })
async function onUpgrade(id: string) {
if (busy)
@@ -198,6 +236,111 @@ export function ConfigPlugin() {
}
}
+ async function onSnapshot(id: string, name: string, hasSnapshot: boolean) {
+ if (busy)
+ return
+ // 已存在快照:覆盖式,先确认再覆盖(快照语义 = 覆盖当前状态)。
+ if (hasSnapshot) {
+ try {
+ await openDialog({
+ status: 'warning',
+ title: t('plugins.snapshot_overwrite_title'),
+ description: (
+ <p>
+ {t('plugins.snapshot_overwrite_desc', { name })}
+ </p>
+ ),
+ confirmText: t('plugins.snapshot_overwrite_confirm'),
+ })
+ }
+ catch {
+ return
+ }
+ }
+ setBusy({ id, action: 'snapshot' })
+ try {
+ await snapshot.mutateAsync(id)
+ }
+ catch {
+ // 错误提示已由 mutation 的 onError 处理
+ }
+ finally {
+ setBusy(null)
+ }
+ }
+
+ async function onRestore(id: string, name: string) {
+ if (busy)
+ return
+ try {
+ await openDialog({
+ status: 'warning',
+ title: t('plugins.restore_confirm_title'),
+ description: (
+ <p>
+ {t('plugins.restore_confirm_desc', { name })}
+ </p>
+ ),
+ confirmText: t('plugins.restore'),
+ })
+ }
+ catch {
+ return
+ }
+ setBusy({ id, action: 'restore' })
+ try {
+ await restore.mutateAsync(id)
+ // 还原期间后端已停止服务:复用 config-backup 的「重启服务」toast 交互
+ const key = toast(t('plugins.restore_restart_hint', { name }), {
+ variant: 'accent',
+ timeout: 10_000,
+ actionProps: {
+ children: t('app.restart'),
+ onPress: () => {
+ store.harness.restart()
+ toast.close(key)
+ },
+ },
+ })
+ }
+ catch {
+ // 错误提示已由 mutation 的 onError 处理
+ }
+ finally {
+ setBusy(null)
+ }
+ }
+
+ async function onDeleteSnapshot(id: string, name: string) {
+ if (busy)
+ return
+ try {
+ await openDialog({
+ status: 'danger',
+ title: t('plugins.snapshot_delete_title'),
+ description: (
+ <p>
+ {t('plugins.snapshot_delete_desc', { name })}
+ </p>
+ ),
+ confirmText: t('plugins.snapshot_delete_confirm'),
+ })
+ }
+ catch {
+ return
+ }
+ setBusy({ id, action: 'delete-snapshot' })
+ try {
+ await deleteSnapshot.mutateAsync(id)
+ }
+ catch {
+ // 错误提示已由 mutation 的 onError 处理
+ }
+ finally {
+ setBusy(null)
+ }
+ }
+
return (
<div>
<PanelHeader
@@ -340,6 +483,44 @@ export function ConfigPlugin() {
</span>
</Chip>
</If>
+ {/* 单插件快照:快照始终可用(已存在时覆盖确认);还原/删除快照仅在
+ 存在快照时显示。还原会停服务,还原后 toast 提示重启(issue #303) */}
+ <Chip
+ className={actionChip({ busy: !!busy })}
+ variant="primary"
+ color="accent"
+ size="sm"
+ onClick={() => onSnapshot(plugin.id, plugin.name, plugin.hasSnapshot)}
+ >
+ <span className="flex items-center gap-1">
+ <If cond={busy?.id === plugin.id && busy.action === 'snapshot'} then={<Spinner size="sm" color="current" />} />
+ {t('plugins.snapshot')}
+ </span>
+ </Chip>
+ <If cond={plugin.hasSnapshot}>
+ <Chip
+ className={actionChip({ busy: !!busy })}
+ variant="primary"
+ color="accent"
+ size="sm"
+ onClick={() => onRestore(plugin.id, plugin.name)}
+ >
+ <span className="flex items-center gap-1">
+ <If cond={busy?.id === plugin.id && busy.action === 'restore'} then={<Spinner size="sm" color="current" />} />
+ {t('plugins.restore')}
+ </span>
+ </Chip>
+ <Chip
+ className={actionChip({ busy: !!busy })}
+ size="sm"
+ onClick={() => onDeleteSnapshot(plugin.id, plugin.name)}
+ >
+ <span className="flex items-center gap-1">
+ <If cond={busy?.id === plugin.id && busy.action === 'delete-snapshot'} then={<Spinner size="sm" color="current" />} />
+ {t('plugins.delete_snapshot')}
+ </span>
+ </Chip>
+ </If>
<Chip
className={actionChip({ busy: !!busy })}
variant="primary"
diff --git a/src/components/plugin-recovery.tsx b/src/components/plugin-recovery.tsx
index ee6c0a65..c0163085 100644
--- a/src/components/plugin-recovery.tsx
+++ b/src/components/plugin-recovery.tsx
@@ -1,5 +1,7 @@
import { CircleExclamation } from '@gravity-ui/icons'
import { Button, Chip, Description, Spinner } from '@heroui/react'
+import { invoke } from '@tauri-apps/api/core'
+import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { If } from 'react-if-lite'
import { useStore } from 'valtio-define'
@@ -34,6 +36,38 @@ export function PluginRecovery({ fullScreen = false }: { fullScreen?: boolean })
const { t } = useTranslation()
const { recovery } = useStore(store.harness)
+ // 检测问题插件哪些已有单插件快照:仅对「确实有快照」的插件提供「从快照还原」入口
+ // (issue #303)。无快照的插件还原会 SNAPSHOT_NOT_FOUND,故必须按 id 过滤,
+ // 避免多插件场景下整体还原失败。
+ const [restorableIds, setRestorableIds] = useState<string[]>([])
+ useEffect(() => {
+ if (!recovery.required || !recovery.info) {
+ return
+ }
+ let disposed = false
+ Promise.all(recovery.info.plugins.map(async (id) => {
+ try {
+ const r = await invoke<{ exists: boolean }>('get_plugin_backup', { id })
+ return r.exists ? id : null
+ }
+ catch {
+ return null
+ }
+ }))
+ .then((results) => {
+ if (!disposed)
+ setRestorableIds(results.filter((id): id is string => id !== null))
+ })
+ .catch((err) => {
+ console.error('[PluginRecovery] check snapshot failed:', err)
+ if (!disposed)
+ setRestorableIds([])
+ })
+ return () => {
+ disposed = true
+ }
+ }, [recovery.required, recovery.info])
+
if (!recovery.required || !recovery.info) {
return null
}
@@ -48,6 +82,9 @@ export function PluginRecovery({ fullScreen = false }: { fullScreen?: boolean })
const primaryLabel = multiple
? t('recovery.remove_many', { count: info.plugins.length })
: t('recovery.remove_one')
+ const restoreLabel = restorableIds.length > 1
+ ? t('recovery.restore_many', { count: restorableIds.length })
+ : t('recovery.restore_one')
const reasonDetail = info.detail
? t(reasonKeys.detail, { detail: info.detail })
: t(reasonKeys.detail)
@@ -99,6 +136,20 @@ export function PluginRecovery({ fullScreen = false }: { fullScreen?: boolean })
</div>
<div className="flex flex-wrap items-center gap-2">
+ {/* 还原快照:优先级高于卸载——有快照的插件优先用快照还原,避免误删插件;
+ 仅传「确有快照」的 id,无快照的插件保持不动(还原会 SNAPSHOT_NOT_FOUND) */}
+ <If cond={restorableIds.length > 0}>
+ <Button
+ className="rounded-md"
+ variant="primary"
+ onPress={() => store.harness.restoreAndRedetect(restorableIds)}
+ >
+ <span className="flex items-center gap-1">
+ <If cond={recovery.busy} then={<Spinner size="sm" color="current" />} />
+ {recovery.busy ? t('recovery.restoring') : restoreLabel}
+ </span>
+ </Button>
+ </If>
<Button
className="rounded-md"
variant="danger"
diff --git a/src/hooks/use-dsh-plugins.ts b/src/hooks/use-dsh-plugins.ts
index 6786aca4..c143a81b 100644
--- a/src/hooks/use-dsh-plugins.ts
+++ b/src/hooks/use-dsh-plugins.ts
@@ -40,6 +40,8 @@ export interface DshPlugin {
updateAvailable: boolean
/** 判定得到的「最新版本」(registry latest / git HEAD SHA);未判定时缺省 */
latestVersion?: string
+ /** 是否有单插件快照($DSH_HOME/.plugin-backups/<id>.tgz),决定还原/删除快照入口 */
+ hasSnapshot: boolean
/** 异常信息(安装/升级/卸载失败或页面运行期上报);undefined = 正常 */
error?: PluginErrorInfo | null
}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index c94a2eba..d077d7d5 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -222,6 +222,23 @@
"plugins.disable_failed": "Failed to disable {{name}}",
"plugins.enable_toast": "Plugin {{name}} enabled",
"plugins.enable_failed": "Failed to enable {{name}}",
+ "plugins.snapshot": "Snapshot",
+ "plugins.snapshot_toast": "Plugin {{name}} snapshotted",
+ "plugins.snapshot_failed": "Failed to snapshot {{name}}",
+ "plugins.snapshot_overwrite_title": "Overwrite snapshot",
+ "plugins.snapshot_overwrite_desc": "A snapshot of {{name}} already exists. Overwrite it with the current version?",
+ "plugins.snapshot_overwrite_confirm": "Overwrite",
+ "plugins.restore": "Restore",
+ "plugins.restore_confirm_title": "Restore plugin",
+ "plugins.restore_confirm_desc": "Restore {{name}} from its snapshot? Its current state will be replaced, and the Harness service will stop during restore.",
+ "plugins.restore_failed": "Failed to restore {{name}}",
+ "plugins.restore_restart_hint": "Plugin {{name}} restored — restart the service to continue",
+ "plugins.delete_snapshot": "Delete snapshot",
+ "plugins.snapshot_delete_title": "Delete snapshot",
+ "plugins.snapshot_delete_desc": "Delete the snapshot of {{name}}? This cannot be undone.",
+ "plugins.snapshot_delete_confirm": "Delete",
+ "plugins.snapshot_deleted_toast": "Snapshot of {{name}} deleted",
+ "plugins.snapshot_delete_failed": "Failed to delete snapshot of {{name}}",
"core.title": "Harness Core",
"core.refresh": "Refresh",
"core.refreshed_toast": "Core list refreshed",
@@ -269,7 +286,10 @@
"recovery.heading_many": "{{count}} plugins are preventing startup",
"recovery.remove_one": "Remove this plugin and continue checking",
"recovery.remove_many": "Remove these {{count}} plugins and continue checking",
+ "recovery.restore_one": "Restore this plugin from snapshot",
+ "recovery.restore_many": "Restore these {{count}} plugins from snapshot",
"recovery.removing": "Removing and checking again…",
+ "recovery.restoring": "Restoring and checking again…",
"recovery.restart": "Restart Harness",
"recovery.dismiss": "Not now",
"recovery.safety_note": "Your workspaces, sessions, model settings, and other plugins will not be removed.",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index b0531adb..c4d0263f 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -222,6 +222,23 @@
"plugins.disable_failed": "禁用插件 {{name}} 失败",
"plugins.enable_toast": "插件 {{name}} 已启用",
"plugins.enable_failed": "启用插件 {{name}} 失败",
+ "plugins.snapshot": "快照",
+ "plugins.snapshot_toast": "插件 {{name}} 已创建快照",
+ "plugins.snapshot_failed": "创建插件 {{name}} 快照失败",
+ "plugins.snapshot_overwrite_title": "覆盖快照",
+ "plugins.snapshot_overwrite_desc": "插件 {{name}} 已有快照,是否用当前版本覆盖?",
+ "plugins.snapshot_overwrite_confirm": "覆盖",
+ "plugins.restore": "还原",
+ "plugins.restore_confirm_title": "还原插件",
+ "plugins.restore_confirm_desc": "将插件 {{name}} 还原到快照状态?当前状态将被替换,还原期间 Harness 服务会停止。",
+ "plugins.restore_failed": "还原插件 {{name}} 失败",
+ "plugins.restore_restart_hint": "插件 {{name}} 已还原 — 重启服务以继续使用",
+ "plugins.delete_snapshot": "删除快照",
+ "plugins.snapshot_delete_title": "删除快照",
+ "plugins.snapshot_delete_desc": "删除插件 {{name}} 的快照?此操作不可撤销。",
+ "plugins.snapshot_delete_confirm": "删除",
+ "plugins.snapshot_deleted_toast": "插件 {{name}} 的快照已删除",
+ "plugins.snapshot_delete_failed": "删除插件 {{name}} 的快照失败",
"core.title": "核心引擎",
"core.refresh": "刷新",
"core.refreshed_toast": "核心列表已刷新",
@@ -269,7 +286,10 @@
"recovery.heading_many": "发现 {{count}} 个导致启动失败的插件",
"recovery.remove_one": "卸除此插件并继续检测",
"recovery.remove_many": "卸载这 {{count}} 个插件并继续检测",
+ "recovery.restore_one": "从快照还原此插件",
+ "recovery.restore_many": "从快照还原这 {{count}} 个插件",
"recovery.removing": "正在处理并重新检测…",
+ "recovery.restoring": "正在还原并重新检测…",
"recovery.restart": "重启 Harness",
"recovery.dismiss": "暂不处理",
"recovery.safety_note": "工作区、会话、模型配置和其他插件不会被删除。",
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index 36451042..e6cd9393 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -816,6 +816,31 @@ export const harness = defineStore({
}
},
+ /** 从快照还原并继续检测:优先用单插件快照还原问题插件(优先级高于卸载);
+ * 仅对传入的(确有快照的)插件还原,单项失败不阻断其它项。还原成功后重启并重新检测。 */
+ async restoreAndRedetect(ids: readonly string[]) {
+ if (this.recovery.busy || ids.length === 0)
+ return
+ this.recovery = { ...this.recovery, busy: true }
+ try {
+ // 逐项还原,单项失败仅记录告警、不中断整体流程(无快照项由调用方过滤)
+ for (const id of ids) {
+ try {
+ await invoke('restore_plugin', { id })
+ }
+ catch (err) {
+ console.error(`[Harness] restore_plugin failed for ${id}:`, err)
+ }
+ }
+ this.recovery = { required: false, info: null, attempts: this.recovery.attempts, busy: false }
+ await this.restart()
+ }
+ catch (err) {
+ console.error('[Harness] restoreAndRedetect failed:', err)
+ this.recovery = { ...this.recovery, busy: false, attempts: this.recovery.attempts + 1 }
+ }
+ },
+
/** 「暂不处理」:关闭修复界面并记住这些插件(运行期场景不阻断使用)。 */
dismissRecovery() {
if (this.recovery.info) {