Skip to content

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

chore(rust): consolidate compatible plugin service helpers (#821)

Mao Mrd81d8a4a26c0
diff --git a/docs/audit/rust-plugin-service.md b/docs/audit/rust-plugin-service.md
index 62199620..642e4460 100644
--- a/docs/audit/rust-plugin-service.md
+++ b/docs/audit/rust-plugin-service.md
@@ -79,3 +79,14 @@ Over-engineering only。正确性 / 安全 / 性能不在本报告范围。所
- `DisabledEntry.reason` 与 `SnapshotManifest.patches` 的删除不需要数据迁移:serde 默认忽略未知键,旧 JSON / 旧归档照常反序列化。
## net: -508 lines, -0 deps possible.
+
+## 执行复核(2026-10-01)
+
+- **已实施**:共享 `drain_captured`、上限指数退避、core 包保护谓词、补丁条目匹配、manifest bundle 移除、悬空 insert 判定、watch 默认状态、git URL 归一、重复 bundle 正则与 pnpm 退出后释放 guard 的步骤;hex nibble 改用标准库。均复用现有模块,不新增依赖。
+- **进程边界保留**:process 的 ANSI 行解码、EOF 补换行、事件先于捕获和读错日志,与 verify 的整管 UTF-8-lossy 捕获/读错丢弃不同;owner、取消、等待和 Windows 修复宽限也不同。仅共享逐字相同的取回缓冲区操作,不合并 spawn/drain/wait。
+- **配置边界保留**:snapshot upsert 保留已有重复 bundle,materialize 会去重并处理无效节点,不能直接合并;snapshot 原子写支持归档流式生成,manifest/patch 的持久化、临时文件、替换失败与清理策略不同,不改为字节数组层。Windows WRITE_THROUGH 不等同文件 sync_all,保留原替换实现。
+- **迁移与性能保留**:未到 v1 版本边界,allowlist 损坏旧 YAML 修复、legacy 布局回退及删除失败注入保留。ensure receipt 的配置指纹及 30 秒窗口保留,避免重复执行非纯 no-op 的安装/验证/文件副作用。
+- **协议保留**:DisabledEntry.reason 和 SnapshotManifest.patches 是序列化输出字段,不以本仓无读者为理由删除。pnpm 探测错误分类包装仍钉住日志/返回协议;ensure 取消与超时路径的原清理顺序不改。
+- **其他不实施**:watch 的强类型元信息拒绝无效字段,ownership 的 Value 解析容忍无关字段,不能并成一个 schema;时间戳格式及 fallback 不同,time 依赖未启用 macros,不为小幅精简增加 feature 或新中间层。
+- **兼容细节**:disable 剥离仍只接受 mapping,recovery 的 scalar 支持不扩大到 disable;bundle 移除必须先执行,不能被 dependencies 已修改的短路跳过;debug gating、空 repository 优先级、正则分类顺序、移位退避边界、锁中毒时返回空缓冲区及子进程退出前 guard 生命周期保留。
+- **验证**:新增真实隔离目录、子进程及纯函数边界回归;`cargo test --all-features --locked` 全量 772 项通过,plugin 回归五轮独立乱序(4101/4202/4303/4404/4505)各 319 项通过。将退出等待谓词变为立即完成的变异被 live-probe guard 用例捕获(提前释放断言失败),恢复后全量和五轮均通过。全仓 cargo fmt 检出既有范围外格式差异,不格式化无关文件;修改文件 rustfmt 检查通过。未执行本地插件构建或修改用户数据。
diff --git a/src-tauri/src/service/plugin/disable.rs b/src-tauri/src/service/plugin/disable.rs
index 07748642..298a0e49 100644
--- a/src-tauri/src/service/plugin/disable.rs
+++ b/src-tauri/src/service/plugin/disable.rs
@@ -14,6 +14,7 @@ use tauri::AppHandle;
use crate::service::fs_guard;
use crate::service::plugin::installed::profile_dir;
+use crate::service::plugin::recovery::{is_core_package, patch_entry_targets, remove_bundle};
use crate::service::plugin::{process, watch};
/// 单条禁用记录(序列化为 camelCase 给前端/磁盘)。
@@ -162,11 +163,7 @@ pub(crate) fn strip_patch_disable(profile: &Path, id: &str) -> Result<bool, Stri
kept.push(entry);
continue;
};
- let targeted = map.iter().any(|(k, v)| {
- names
- .iter()
- .any(|n| k.as_str() == Some(n.as_str()) || v.as_str() == Some(n.as_str()))
- });
+ let targeted = names.iter().any(|name| patch_entry_targets(&entry, name));
if !targeted || !patch_entry_disabled(&map) {
kept.push(entry);
continue;
@@ -190,22 +187,6 @@ pub(crate) fn strip_patch_disable(profile: &Path, id: &str) -> Result<bool, Stri
Ok(true)
}
-/// 仅从 `dsh.profile.bundles` 移除指定插件(不动 `dependencies`)。
-/// 返回是否实际移除了条目。
-fn remove_from_bundles(manifest: &mut serde_json::Value, id: &str) -> bool {
- let Some(bundles) = manifest
- .get_mut("dsh")
- .and_then(|d| d.get_mut("profile"))
- .and_then(|p| p.get_mut("bundles"))
- .and_then(|b| b.as_array_mut())
- else {
- return false;
- };
- let before = bundles.len();
- bundles.retain(|b| b.as_str() != Some(id));
- bundles.len() != before
-}
-
/// 把插件加回 `dsh.profile.bundles`(若已存在则不重复添加)。
/// 返回是否实际新增了条目。
fn add_to_bundles(manifest: &mut serde_json::Value, id: &str) -> bool {
@@ -224,11 +205,6 @@ fn add_to_bundles(manifest: &mut serde_json::Value, id: &str) -> bool {
true
}
-/// 是否为官方/核心包(`@deepseek-ai/` 前缀)。与 recovery 模块的保护名单一致。
-fn is_core_package(id: &str) -> bool {
- id.starts_with("@deepseek-ai/")
-}
-
/// 检查插件是否已安装(dependencies 中存在)。
fn is_in_dependencies(manifest: &serde_json::Value, id: &str) -> bool {
manifest
@@ -299,7 +275,7 @@ pub(crate) fn disable_plugin_at(profile: &Path, id: &str) -> Result<(), String>
},
);
save_disabled(profile, &map)?;
- remove_from_bundles(&mut manifest, id);
+ remove_bundle(&mut manifest, id);
let rendered = serde_json::to_string_pretty(&manifest)
.map_err(|e| format!("DISABLE_RENDER_MANIFEST: {e}"))?;
if let Err(e) = fs::write(&manifest_path, format!("{rendered}\n")) {
@@ -665,6 +641,27 @@ mod tests {
fs::remove_dir_all(&profile).ok();
}
+ #[test]
+ fn strip_patch_disable_preserves_non_mapping_and_false_or_nested_targets() {
+ let profile = build_profile("patch-boundaries", "p");
+ write_patch(
+ &profile,
+ "- dsh-better-sidebar\n- [dsh-better-sidebar]\n- id: other\n config: {id: dsh-better-sidebar}\n disabled: true\n- id: dsh-better-sidebar\n disabled: false\n- dsh-better-sidebar: alias\n disabled: true\n",
+ );
+ assert!(strip_patch_disable(&profile, "dsh-better-sidebar").unwrap());
+ let patch = profile.join("cordis.patch.yml");
+ let content = fs::read_to_string(&patch).unwrap();
+ let doc: serde_yaml::Value = serde_yaml::from_str(&content).unwrap();
+ let expected: serde_yaml::Value = serde_yaml::from_str(
+ "- dsh-better-sidebar\n- [dsh-better-sidebar]\n- id: other\n config: {id: dsh-better-sidebar}\n disabled: true\n- id: dsh-better-sidebar\n disabled: false\n- dsh-better-sidebar: alias\n",
+ )
+ .unwrap();
+ assert_eq!(doc, expected);
+ assert!(!strip_patch_disable(&profile, "dsh-better-sidebar").unwrap());
+ assert_eq!(fs::read_to_string(&patch).unwrap(), content);
+ fs::remove_dir_all(&profile).unwrap();
+ }
+
/// 带其它配置的禁用条目:只摘 `disabled` 键,其余配置保留(不删除无关配置)。
#[test]
fn strip_patch_disable_keeps_other_config_keys() {
diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rs
index a37d8d09..08c2bc34 100644
--- a/src-tauri/src/service/plugin/install/mod.rs
+++ b/src-tauri/src/service/plugin/install/mod.rs
@@ -67,11 +67,11 @@ mod spec;
// 子模块对外 API:plugin 兄弟模块(verify / internal 等)与安装编排共用
pub(crate) use env::build_plugin_envs;
+pub use inspect::inspect_specs;
pub(crate) use pnpm::{
bundled_pnpm_major, harness_prefer_bundled_pnpm, pnpm_major_version_at, profile_store_major,
};
pub(crate) use single::uninstall_deprecated_plugins;
-pub use inspect::inspect_specs;
pub use single::{remove_many, update_many};
// 版本兼容性/发布时长两类拦截的解析结果都要跨到 `bridge`(前端逐项确认后授权),在此定义出口
pub use diagnose::{IncompatibleVersion, PolicyBlockedVersion};
@@ -103,13 +103,17 @@ const TRANSIENT_FS_RETRIES: usize = 8;
/// 瞬时文件系统错误的首次重试延迟;后续延迟按指数增长,最多 64 秒。
const TRANSIENT_FS_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(1);
+fn capped_backoff(retry: usize, base_secs: u64, cap_secs: u64) -> std::time::Duration {
+ std::time::Duration::from_secs(
+ base_secs
+ .checked_shl(retry.saturating_sub(1) as u32)
+ .unwrap_or(cap_secs)
+ .min(cap_secs),
+ )
+}
+
fn transient_fs_retry_delay(retry: usize) -> std::time::Duration {
- let seconds = TRANSIENT_FS_RETRY_DELAY
- .as_secs()
- .checked_shl(retry.saturating_sub(1) as u32)
- .unwrap_or(64)
- .min(64);
- std::time::Duration::from_secs(seconds)
+ capped_backoff(retry, TRANSIENT_FS_RETRY_DELAY.as_secs(), 64)
}
/// lockfile supply-chain 校验因 registry 元数据拉不到而误判违规时的重试上限
@@ -122,12 +126,7 @@ const POLICY_VERIFICATION_RETRIES: usize = 4;
const POLICY_VERIFICATION_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(5);
fn policy_verification_retry_delay(retry: usize) -> std::time::Duration {
- let seconds = POLICY_VERIFICATION_RETRY_DELAY
- .as_secs()
- .checked_shl(retry.saturating_sub(1) as u32)
- .unwrap_or(30)
- .min(30);
- std::time::Duration::from_secs(seconds)
+ capped_backoff(retry, POLICY_VERIFICATION_RETRY_DELAY.as_secs(), 30)
}
/// 一次安装操作的目标:`id` 是稳定标识(错误记录 / 快照 / bundles 对账),
@@ -409,26 +408,25 @@ async fn install_with_cancel(
// 门禁自愈:lockfile 里早有的太新条目会让**每一次**状态变更都失败
// (见 [`heal_locked_release_age`])。补齐豁免后放宽窗口重跑一次,仍失败就照原样分类。
- let (exit_code, last_output, last_attempt) = if exit_code != 0
- && heal_locked_release_age(app_handle, &last_attempt)
- {
- let mut retry_args = args.clone();
- retry_args.push(OsString::from(single::RELEASE_AGE_RELAXED_FLAG));
- run_plugin_install_with_transient_retry(
- app_handle,
- &node,
- &retry_args,
- &cwd,
- &envs,
- &window,
- "install",
- cancel.as_ref(),
- owner,
- )
- .await?
- } else {
- (exit_code, last_output, last_attempt)
- };
+ let (exit_code, last_output, last_attempt) =
+ if exit_code != 0 && heal_locked_release_age(app_handle, &last_attempt) {
+ let mut retry_args = args.clone();
+ retry_args.push(OsString::from(single::RELEASE_AGE_RELAXED_FLAG));
+ run_plugin_install_with_transient_retry(
+ app_handle,
+ &node,
+ &retry_args,
+ &cwd,
+ &envs,
+ &window,
+ "install",
+ cancel.as_ref(),
+ owner,
+ )
+ .await?
+ } else {
+ (exit_code, last_output, last_attempt)
+ };
if exit_code != 0 {
log::error!("dsh plugin install failed with exit code {exit_code}");
@@ -444,7 +442,9 @@ async fn install_with_cancel(
// 该拒绝几乎没有 pnpm 输出,落到通用分支只会给出一段用户无从下手的纯文本。
let incompatible = incompatible_versions(&last_attempt);
if !incompatible.is_empty() {
- log::warn!("dsh rejected the install for incompatible plugin versions: {incompatible:?}");
+ log::warn!(
+ "dsh rejected the install for incompatible plugin versions: {incompatible:?}"
+ );
let payload = serde_json::to_string(&incompatible)
.map_err(|e| format!("PREINSTALL_SERIALIZE: {e}"))?;
return Err(format!("PLUGIN_VERSION_INCOMPATIBLE: {payload}"));
@@ -976,6 +976,24 @@ mod tests {
));
}
+ #[test]
+ fn capped_backoff_preserves_zero_and_shift_limit_boundaries() {
+ for (retry, base, cap, seconds) in [
+ (0, 1, 64, 1),
+ (0, 5, 30, 5),
+ (3, 5, 30, 20),
+ (63, 1, 64, 64),
+ (65, 1, 64, 64),
+ (65, 5, 30, 30),
+ ] {
+ assert_eq!(
+ capped_backoff(retry, base, cap),
+ std::time::Duration::from_secs(seconds),
+ "retry={retry}, base={base}, cap={cap}"
+ );
+ }
+ }
+
#[test]
fn transient_fs_retry_delay_uses_exponential_backoff() {
assert_eq!(
diff --git a/src-tauri/src/service/plugin/install/pnpm.rs b/src-tauri/src/service/plugin/install/pnpm.rs
index 356460a6..c022a73a 100644
--- a/src-tauri/src/service/plugin/install/pnpm.rs
+++ b/src-tauri/src/service/plugin/install/pnpm.rs
@@ -420,12 +420,7 @@ fn monitor_probe_wait_task(
}
Err(error) => {
log::error!("pnpm version probe cleanup wait task failed: {error}");
- wait_for_probe_cleanup_with(
- || !super::super::process::plugin_process_has_exited(pid),
- PNPM_PROBE_LIVENESS_INTERVAL,
- )
- .await;
- super::super::process::release_process_cleanup(owner, pid_guard, process_guard);
+ await_exit_then_release(owner, pid, pid_guard, process_guard).await;
}
}
});
@@ -440,14 +435,26 @@ fn monitor_orphaned_probe_pid(
) {
super::super::process::mark_process_cleanup_failed(owner, reason);
super::super::cancel::terminate_pid_tree(pid);
- tauri::async_runtime::spawn(async move {
- wait_for_probe_cleanup_with(
- || !super::super::process::plugin_process_has_exited(pid),
- PNPM_PROBE_LIVENESS_INTERVAL,
- )
- .await;
- super::super::process::release_process_cleanup(owner, pid_guard, process_guard);
- });
+ tauri::async_runtime::spawn(await_exit_then_release(
+ owner,
+ pid,
+ pid_guard,
+ process_guard,
+ ));
+}
+
+async fn await_exit_then_release(
+ owner: ProcessOwner,
+ pid: u32,
+ pid_guard: PidGuard,
+ process_guard: tokio::sync::OwnedMutexGuard<()>,
+) {
+ wait_for_probe_cleanup_with(
+ || !super::super::process::plugin_process_has_exited(pid),
+ PNPM_PROBE_LIVENESS_INTERVAL,
+ )
+ .await;
+ super::super::process::release_process_cleanup(owner, pid_guard, process_guard);
}
async fn wait_for_probe_cleanup(pending: &mut ProbeCleanupPending) {
@@ -929,6 +936,89 @@ mod tests {
assert!(pending.is_err());
}
+ #[tokio::test]
+ async fn exited_probe_releases_its_pid_and_process_guard() {
+ #[cfg(windows)]
+ let mut child = {
+ use std::os::windows::process::CommandExt;
+ std::process::Command::new("cmd.exe")
+ .creation_flags(0x08000000)
+ .args(["/D", "/C", "exit 0"])
+ .spawn()
+ .unwrap()
+ };
+ #[cfg(not(windows))]
+ let mut child = std::process::Command::new("sh")
+ .args(["-c", "exit 0"])
+ .spawn()
+ .unwrap();
+ let pid = child.id();
+ assert!(child.wait().unwrap().success());
+ let owner = super::super::super::process::new_process_owner();
+ let pid_guard = PidGuard::set(owner, pid);
+ let lock = std::sync::Arc::new(tokio::sync::Mutex::new(()));
+ let process_guard = lock.clone().lock_owned().await;
+ assert!(lock.try_lock().is_err());
+ tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ await_exit_then_release(owner, pid, pid_guard, process_guard),
+ )
+ .await
+ .unwrap();
+ assert_eq!(super::super::super::process::active_plugin_pid(owner), None);
+ assert!(lock.try_lock().is_ok());
+ }
+
+ #[tokio::test]
+ async fn live_probe_retains_its_pid_and_process_guard_until_exit() {
+ #[cfg(windows)]
+ let mut command = {
+ use std::os::windows::process::CommandExt;
+ let mut command = std::process::Command::new("cmd.exe");
+ command
+ .creation_flags(0x08000000)
+ .args(["/D", "/C", "set /p token="]);
+ command
+ };
+ #[cfg(not(windows))]
+ let mut command = {
+ let mut command = std::process::Command::new("sh");
+ command.args(["-c", "read -r token"]);
+ command
+ };
+ let mut child = command
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .unwrap();
+ let pid = child.id();
+ let owner = super::super::super::process::new_process_owner();
+ let pid_guard = PidGuard::set(owner, pid);
+ let lock = std::sync::Arc::new(tokio::sync::Mutex::new(()));
+ let process_guard = lock.clone().lock_owned().await;
+ let release = await_exit_then_release(owner, pid, pid_guard, process_guard);
+ tokio::pin!(release);
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(50), &mut release)
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ super::super::super::process::active_plugin_pid(owner),
+ Some(pid)
+ );
+ assert!(lock.try_lock().is_err());
+ use std::io::Write;
+ child.stdin.take().unwrap().write_all(b"done\n").unwrap();
+ tokio::time::timeout(std::time::Duration::from_secs(5), &mut release)
+ .await
+ .unwrap();
+ let _ = child.wait();
+ assert_eq!(super::super::super::process::active_plugin_pid(owner), None);
+ assert!(lock.try_lock().is_ok());
+ }
+
struct BrokenPipeReader;
impl std::io::Read for BrokenPipeReader {
diff --git a/src-tauri/src/service/plugin/patch_entries.rs b/src-tauri/src/service/plugin/patch_entries.rs
index e57ebcf6..0301385b 100644
--- a/src-tauri/src/service/plugin/patch_entries.rs
+++ b/src-tauri/src/service/plugin/patch_entries.rs
@@ -119,12 +119,7 @@ pub(crate) fn scan_unresolved_entries_in(
let declared = declared_dependencies(profile_dir);
let mut unresolved = Vec::new();
for layer in patch_layer_paths(profile_dir, dsh_home) {
- unresolved.extend(scan_layer(
- &layer,
- profile_dir,
- install_anchor,
- &declared,
- ));
+ unresolved.extend(scan_layer(&layer, profile_dir, install_anchor, &declared));
}
unresolved
}
@@ -156,12 +151,8 @@ pub(crate) fn strip_unresolved_entries_in(
}
let stamp = now_stamp();
let backup = backup_path(&layer, "bak", &stamp);
- std::fs::copy(&layer, &backup).map_err(|e| {
- format!(
- "PATCH_LAYER_STRIP_BACKUP_FAILED: {}: {e}",
- backup.display()
- )
- })?;
+ std::fs::copy(&layer, &backup)
+ .map_err(|e| format!("PATCH_LAYER_STRIP_BACKUP_FAILED: {}: {e}", backup.display()))?;
let rendered = serde_yaml::to_string(&Value::Sequence(kept))
.map_err(|e| format!("PATCH_LAYER_STRIP_RENDER_FAILED: {e}"))?;
write_patch_layer_atomically(&layer, &rendered, &stamp)?;
@@ -214,16 +205,9 @@ fn scan_layer(
&mut blocking
};
for item in items {
- let Some(name) = item
- .as_mapping()
- .and_then(|item| map_get(item, "name"))
- .and_then(Value::as_str)
- else {
+ let Some(name) = dangling_package(profile_dir, install_anchor, item) else {
continue;
};
- if !is_bare_package_name(name) || package_resolvable(profile_dir, install_anchor, name) {
- continue;
- }
target.push(UnresolvedPatchEntry {
layer: layer.display().to_string(),
line: item_line(&raw, &starts, index, name),
@@ -251,7 +235,19 @@ fn scan_layer(
blocking
}
-/// 剥离条目里悬空的 insert 项,返回(保留下来的顶层条目,移除数量)。
+fn dangling_package<'a>(
+ profile_dir: &Path,
+ install_anchor: Option<&Path>,
+ item: &'a Value,
+) -> Option<&'a str> {
+ item.as_mapping()
+ .and_then(|item| map_get(item, "name"))
+ .and_then(Value::as_str)
+ .filter(|name| {
+ is_bare_package_name(name) && !package_resolvable(profile_dir, install_anchor, name)
+ })
+}
+
fn strip_entries(
entries: &[Value],
profile_dir: &Path,
@@ -274,15 +270,7 @@ fn strip_entries(
};
let mut kept_items = Vec::with_capacity(items.len());
for item in items {
- let dangling = item
- .as_mapping()
- .and_then(|item| map_get(item, "name"))
- .and_then(Value::as_str)
- .is_some_and(|name| {
- is_bare_package_name(name)
- && !package_resolvable(profile_dir, install_anchor, name)
- });
- if dangling {
+ if dangling_package(profile_dir, install_anchor, item).is_some() {
removed += 1;
} else {
kept_items.push(item.clone());
@@ -294,7 +282,11 @@ fn strip_entries(
kept.push(Value::Mapping(stripped));
}
} else {
- kept.push(Value::Mapping(with_key(map, "insert", Value::Sequence(kept_items))));
+ kept.push(Value::Mapping(with_key(
+ map,
+ "insert",
+ Value::Sequence(kept_items),
+ )));
}
}
(kept, removed)
@@ -350,9 +342,12 @@ fn package_resolvable(profile_dir: &Path, install_anchor: Option<&Path>, name: &
/// 与 dsh-app-boot 的 `packageDirFromAnchor` 同一判定(探测目录里的 `package.json`,
/// 不要求包导出 `./package.json`),因此结果与 loader 的 import 一致。
fn resolvable_from(anchor: &Path, name: &str) -> bool {
- anchor
- .ancestors()
- .any(|dir| dir.join("node_modules").join(name).join("package.json").is_file())
+ anchor.ancestors().any(|dir| {
+ dir.join("node_modules")
+ .join(name)
+ .join("package.json")
+ .is_file()
+ })
}
/// 顶层序列项的起始行号(1-based);补丁层是顶层数组,`- ` 必须顶格。
@@ -477,6 +472,36 @@ mod tests {
std::fs::write(dir.join("package.json"), "{}\n").unwrap();
}
+ #[test]
+ fn dangling_package_preserves_item_shape_and_resolution_boundaries() {
+ let profile = tmp_dir("dangling-boundaries");
+ let anchor = tmp_dir("dangling-anchor");
+ install_package(&profile, "local-plugin");
+ install_package(&anchor, "anchor-plugin");
+ for (yaml, expected) in [
+ ("name: missing-plugin", Some("missing-plugin")),
+ ("name: '@scope/missing'", Some("@scope/missing")),
+ ("name: local-plugin", None),
+ ("name: anchor-plugin", None),
+ ("name: ./relative", None),
+ ("name: file:///plugin.js", None),
+ ("name: 7", None),
+ ("id: missing-plugin", None),
+ ("missing-plugin", None),
+ ("[missing-plugin]", None),
+ ("null", None),
+ ] {
+ let item = serde_yaml::from_str(yaml).unwrap();
+ assert_eq!(
+ dangling_package(&profile, Some(&anchor), &item),
+ expected,
+ "{yaml}"
+ );
+ }
+ std::fs::remove_dir_all(profile).unwrap();
+ std::fs::remove_dir_all(anchor).unwrap();
+ }
+
/// 事故形态:包已卸载、手写的 insert 还在补丁层里。
const DANGLING_LAYER: &str = "- insert:\n - id: file-edit\n name: dsh-file-edit\n";
@@ -620,10 +645,7 @@ mod tests {
assert!(scan_unresolved_entries_in(&profile, &home, Some(&bin)).is_empty());
// 没有安装锚点时同一份补丁层会被判定为悬空,证明锚点确实参与了判定。
- assert_eq!(
- scan_unresolved_entries_in(&profile, &home, None).len(),
- 1
- );
+ assert_eq!(scan_unresolved_entries_in(&profile, &home, None).len(), 1);
let _ = std::fs::remove_dir_all(&install);
let _ = std::fs::remove_dir_all(&profile);
let _ = std::fs::remove_dir_all(&home);
@@ -647,7 +669,9 @@ mod tests {
assert_eq!(report.layers[0].removed, 1);
let backup = PathBuf::from(&report.layers[0].backup);
assert!(backup.is_file());
- assert!(std::fs::read_to_string(&backup).unwrap().contains("dsh-gone"));
+ assert!(std::fs::read_to_string(&backup)
+ .unwrap()
+ .contains("dsh-gone"));
let stripped = std::fs::read_to_string(profile.join("cordis.patch.yml")).unwrap();
assert!(stripped.contains("dsh-keep"), "{stripped}");
assert!(stripped.contains("untouched"), "{stripped}");
@@ -724,9 +748,10 @@ mod tests {
let message = unresolved_entries_message(&entries);
assert!(message.starts_with(&format!("{PATCH_ENTRY_UNRESOLVED}: ")));
- let payload: serde_json::Value =
- serde_json::from_str(message.trim_start_matches(&format!("{PATCH_ENTRY_UNRESOLVED}: ")))
- .unwrap();
+ let payload: serde_json::Value = serde_json::from_str(
+ message.trim_start_matches(&format!("{PATCH_ENTRY_UNRESOLVED}: ")),
+ )
+ .unwrap();
assert_eq!(payload["entries"][0]["name"], "dsh-file-edit");
assert_eq!(payload["entries"][0]["line"], 3);
assert_eq!(payload["entries"][0]["declared"], true);
diff --git a/src-tauri/src/service/plugin/preset.rs b/src-tauri/src/service/plugin/preset.rs
index c184e8e3..22f95a00 100644
--- a/src-tauri/src/service/plugin/preset.rs
+++ b/src-tauri/src/service/plugin/preset.rs
@@ -129,21 +129,6 @@ fn dev_plugins_root() -> PathBuf {
.join("packages")
}
-#[cfg(debug_assertions)]
-fn normalize_dev_repo_url(value: &str) -> String {
- let mut url = value.trim().to_string();
- if let Some(rest) = url.strip_prefix("git+") {
- url = rest.to_string();
- }
- if let Some(rest) = url.strip_prefix("git://") {
- url = format!("https://{rest}");
- }
- if let Some(rest) = url.strip_suffix(".git") {
- url = rest.to_string();
- }
- url
-}
-
#[cfg(debug_assertions)]
fn dev_repo_url(manifest: &DevPluginPackageJson) -> String {
let repository = manifest.repository.as_ref().and_then(|repository| {
@@ -153,7 +138,7 @@ fn dev_repo_url(manifest: &DevPluginPackageJson) -> String {
});
repository
.or(manifest.homepage.as_deref())
- .map(normalize_dev_repo_url)
+ .map(super::watch::normalize_repo_url)
.unwrap_or_default()
}
@@ -1037,6 +1022,30 @@ mod tests {
root
}
+ #[cfg(debug_assertions)]
+ #[test]
+ fn dev_repo_url_keeps_repository_precedence_and_homepage_fallback() {
+ for (json, expected) in [
+ (
+ r#"{"repository":" git+git://example/repo.git ","homepage":"https://fallback"}"#,
+ "https://example/repo",
+ ),
+ (
+ r#"{"repository":{"url":"git://example/object.git"}}"#,
+ "https://example/object",
+ ),
+ (
+ r#"{"repository":{"url":42},"homepage":"git+https://example/home.git"}"#,
+ "https://example/home",
+ ),
+ (r#"{"repository":"","homepage":"https://fallback"}"#, ""),
+ (r#"{}"#, ""),
+ ] {
+ let manifest = serde_json::from_str(json).unwrap();
+ assert_eq!(dev_repo_url(&manifest), expected, "{json}");
+ }
+ }
+
#[cfg(debug_assertions)]
#[test]
fn dev_discovery_empty_root_returns_none() {
diff --git a/src-tauri/src/service/plugin/process.rs b/src-tauri/src/service/plugin/process.rs
index 571694ef..e8bbab68 100644
--- a/src-tauri/src/service/plugin/process.rs
+++ b/src-tauri/src/service/plugin/process.rs
@@ -344,7 +344,7 @@ pub(crate) async fn run_plugin_process(
}
/// 取出(并清空)共享缓冲区中的全部捕获输出。
-fn drain_captured(captured: Arc<Mutex<String>>) -> String {
+pub(super) fn drain_captured(captured: Arc<Mutex<String>>) -> String {
captured
.lock()
.map(|mut buf| std::mem::take(&mut *buf))
@@ -403,6 +403,43 @@ fn spawn_line_emitter<R: Read + Send + 'static>(
mod tests {
use super::*;
+ #[test]
+ fn drain_captured_preserves_exact_output_and_clears_shared_buffer() {
+ let captured = Arc::new(Mutex::new(
+ "stdout \r\n\tstderr\0中文\npartial\r".to_string(),
+ ));
+
+ assert_eq!(
+ drain_captured(captured.clone()),
+ "stdout \r\n\tstderr\0中文\npartial\r"
+ );
+ assert_eq!(*captured.lock().unwrap(), "");
+ assert_eq!(drain_captured(captured.clone()), "");
+
+ captured.lock().unwrap().push_str("late stderr");
+ assert_eq!(drain_captured(captured.clone()), "late stderr");
+ assert_eq!(*captured.lock().unwrap(), "");
+ }
+
+ #[test]
+ fn drain_captured_returns_empty_without_recovering_poisoned_buffer() {
+ let captured = Arc::new(Mutex::new("retained output".to_string()));
+ let writer = captured.clone();
+ assert!(std::thread::spawn(move || {
+ let _guard = writer.lock().unwrap();
+ panic!("poison isolated capture buffer");
+ })
+ .join()
+ .is_err());
+
+ assert_eq!(drain_captured(captured.clone()), "");
+ assert!(captured.is_poisoned());
+ assert_eq!(
+ *captured.lock().unwrap_err().into_inner(),
+ "retained output"
+ );
+ }
+
#[test]
fn stale_guard_cannot_clear_a_new_process_for_the_same_owner() {
let owner = new_process_owner();
diff --git a/src-tauri/src/service/plugin/recovery/extract.rs b/src-tauri/src/service/plugin/recovery/extract.rs
index 91299def..7ac345b2 100644
--- a/src-tauri/src/service/plugin/recovery/extract.rs
+++ b/src-tauri/src/service/plugin/recovery/extract.rs
@@ -36,11 +36,6 @@ static RE_FAILED_TO_LOAD_PLUGINS: LazyLock<Regex> =
static RE_DUP_PREFIX_ROUTE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#"duplicate prefix route\s+["']([^"']+)["']"#).expect("literal"));
-/// 无法解析 profile bundle(classify_reason 用)。
-static RE_CANNOT_RESOLVE_BUNDLE: LazyLock<Regex> = LazyLock::new(|| {
- Regex::new(r#"cannot resolve profile bundle\s+["']?([^"'\n]+)["']?"#).expect("literal")
-});
-
/// 从日志文本中提取插件引用(多个错误特征的正则,去重)。
pub(super) fn extract_plugin_refs(text: &str) -> Vec<String> {
let mut refs = HashSet::new();
@@ -96,7 +91,7 @@ pub(super) fn classify_reason(text: &str) -> (String, String) {
if let Some(entry) = extract_duplicate_loader_entry(text) {
return ("duplicate_loader_entry".into(), entry);
}
- if let Some(c) = RE_CANNOT_RESOLVE_BUNDLE.captures(text) {
+ if let Some(c) = PLUGIN_REF_PATTERNS[1].captures(text) {
return (
"cannot_resolve_bundle".into(),
c.get(1).map(|m| m.as_str().to_string()).unwrap_or_default(),
@@ -124,6 +119,44 @@ pub(super) fn classify_reason(text: &str) -> (String, String) {
mod tests {
use super::*;
+ #[test]
+ fn cannot_resolve_bundle_reuses_pattern_without_broadening_refs() {
+ for (text, refs, reason, detail) in [
+ (
+ "cannot resolve profile bundle \"@scope/pkg\"",
+ vec!["@scope/pkg"],
+ "cannot_resolve_bundle",
+ "@scope/pkg",
+ ),
+ (
+ "cannot resolve profile bundle 'dsh-plugin'",
+ vec!["dsh-plugin"],
+ "cannot_resolve_bundle",
+ "dsh-plugin",
+ ),
+ (
+ "cannot resolve profile bundle foo/../../target",
+ vec![],
+ "cannot_resolve_bundle",
+ "foo/../../target",
+ ),
+ ("cannot resolve profile bundle \"\"", vec![], "unknown", ""),
+ (
+ "cannot resolve profile bundle \"dsh-plugin\"\nduplicate loader entry id: alias",
+ vec!["dsh-plugin"],
+ "duplicate_loader_entry",
+ "alias",
+ ),
+ ] {
+ assert_eq!(extract_plugin_refs(text), refs, "{text}");
+ assert_eq!(
+ classify_reason(text),
+ (reason.into(), detail.into()),
+ "{text}"
+ );
+ }
+ }
+
#[test]
fn extract_refs_from_failure_log() {
let log = r#"
diff --git a/src-tauri/src/service/plugin/recovery/mod.rs b/src-tauri/src/service/plugin/recovery/mod.rs
index 95fbeae4..0fe64460 100644
--- a/src-tauri/src/service/plugin/recovery/mod.rs
+++ b/src-tauri/src/service/plugin/recovery/mod.rs
@@ -24,6 +24,7 @@ use extract::{
classify_reason, extract_duplicate_loader_entry, extract_plugin_refs, extract_slot_conflict,
};
use ownership::resolve_recovery_plugins;
+pub(crate) use uninstall::{patch_entry_targets, remove_bundle};
use uninstall::{remove_plugin_dir, remove_plugin_from_manifest, strip_cordis_patch_for};
// plugin 兄弟模块的再导出:子模块经 `super::` 统一从这里取。
@@ -46,7 +47,7 @@ pub(crate) const RECOVERY_REQUIRED_EVENT: &str = "plugin-recovery-required";
///
/// `@deepseek-ai/dsh-base` / `@deepseek-ai/dsh-web-app` 等核心包都被
/// `@deepseek-ai/` 前缀覆盖,无需逐个点名。
-fn is_core_package(name: &str) -> bool {
+pub(crate) fn is_core_package(name: &str) -> bool {
name.starts_with("@deepseek-ai/")
}
@@ -200,6 +201,22 @@ pub fn uninstall(app_handle: &AppHandle, id: &str) -> Result<(), String> {
mod tests {
use super::*;
+ #[test]
+ fn core_package_predicate_preserves_exact_prefix_boundary() {
+ for (name, expected) in [
+ ("@deepseek-ai/pkg", true),
+ ("@deepseek-ai/", true),
+ ("@deepseek-ai", false),
+ ("@deepseek-ai-extra/pkg", false),
+ (" @deepseek-ai/pkg", false),
+ ("@Deepseek-ai/pkg", false),
+ ("dshmarket", false),
+ ("", false),
+ ] {
+ assert_eq!(is_core_package(name), expected, "{name}");
+ }
+ }
+
#[test]
fn package_name_validation() {
assert!(is_package_name("dshmarket"));
diff --git a/src-tauri/src/service/plugin/recovery/uninstall.rs b/src-tauri/src/service/plugin/recovery/uninstall.rs
index 0a080d15..2074a03e 100644
--- a/src-tauri/src/service/plugin/recovery/uninstall.rs
+++ b/src-tauri/src/service/plugin/recovery/uninstall.rs
@@ -20,19 +20,21 @@ pub(super) fn remove_plugin_from_manifest(manifest: &mut serde_json::Value, id:
modified = true;
}
}
- if let Some(bundles) = manifest
+ remove_bundle(manifest, id) || modified
+}
+
+pub(crate) fn remove_bundle(manifest: &mut serde_json::Value, id: &str) -> bool {
+ let Some(bundles) = manifest
.get_mut("dsh")
.and_then(|d| d.get_mut("profile"))
.and_then(|p| p.get_mut("bundles"))
.and_then(|b| b.as_array_mut())
- {
- let before = bundles.len();
- bundles.retain(|b| b.as_str() != Some(id));
- if bundles.len() != before {
- modified = true;
- }
- }
- modified
+ else {
+ return false;
+ };
+ let before = bundles.len();
+ bundles.retain(|b| b.as_str() != Some(id));
+ bundles.len() != before
}
/// 删除插件入口:符号链接或 junction 只删除入口本身;普通目录递归删除,
@@ -150,7 +152,7 @@ pub(super) fn strip_cordis_patch_for(profile: &Path, id: &str) {
}
/// 一个 patch 条目是否「针对」目标插件:顶层 id 字段或任意字段值等于该包名。
-fn patch_entry_targets(entry: &serde_yaml::Value, id: &str) -> bool {
+pub(crate) fn patch_entry_targets(entry: &serde_yaml::Value, id: &str) -> bool {
match entry {
serde_yaml::Value::Mapping(map) => map
.iter()
@@ -164,6 +166,78 @@ fn patch_entry_targets(entry: &serde_yaml::Value, id: &str) -> bool {
mod tests {
use super::*;
+ #[test]
+ fn remove_bundle_preserves_non_targets_and_reports_only_removal() {
+ let mut manifest = serde_json::json!({
+ "dependencies": {"target": "1"},
+ "dsh": {"profile": {"bundles": ["target", 7, null, {"id": "target"}, "target-extra", "target"]}}
+ });
+ assert!(remove_bundle(&mut manifest, "target"));
+ assert_eq!(manifest["dependencies"], serde_json::json!({"target": "1"}));
+ assert_eq!(
+ manifest["dsh"]["profile"]["bundles"],
+ serde_json::json!([7, null, {"id": "target"}, "target-extra"])
+ );
+ assert!(!remove_bundle(&mut manifest, "target"));
+ for mut malformed in [
+ serde_json::json!({}),
+ serde_json::json!({"dsh": null}),
+ serde_json::json!({"dsh": {"profile": {"bundles": "target"}}}),
+ serde_json::json!({"dsh": {"profile": {"bundles": []}}}),
+ ] {
+ let original = malformed.clone();
+ assert!(!remove_bundle(&mut malformed, "target"));
+ assert_eq!(malformed, original);
+ }
+ }
+
+ #[test]
+ fn manifest_removal_reports_dependency_only_and_bundle_only_changes() {
+ for (mut manifest, expected) in [
+ (serde_json::json!({"dependencies": {"target": "1"}}), true),
+ (
+ serde_json::json!({"dependencies": {"target": "1"}, "dsh": {"profile": {"bundles": ["target"]}}}),
+ true,
+ ),
+ (
+ serde_json::json!({"dependencies": null, "dsh": {"profile": {"bundles": ["target"]}}}),
+ true,
+ ),
+ (
+ serde_json::json!({"dsh": {"profile": {"bundles": ["target"]}}}),
+ true,
+ ),
+ (
+ serde_json::json!({"dependencies": {}, "dsh": {"profile": {"bundles": []}}}),
+ false,
+ ),
+ ] {
+ assert_eq!(
+ remove_plugin_from_manifest(&mut manifest, "target"),
+ expected
+ );
+ assert!(!remove_plugin_from_manifest(&mut manifest, "target"));
+ }
+ }
+
+ #[test]
+ fn patch_targets_match_only_exact_top_level_strings() {
+ for (yaml, expected) in [
+ ("target", true),
+ ("id: target", true),
+ ("target: null", true),
+ ("alias: target", true),
+ ("id: target-extra", false),
+ ("config: {id: target}", false),
+ ("- target", false),
+ ("null", false),
+ ("42", false),
+ ] {
+ let entry = serde_yaml::from_str(yaml).unwrap();
+ assert_eq!(patch_entry_targets(&entry, "target"), expected, "{yaml}");
+ }
+ }
+
#[test]
fn remove_plugin_dir_rejects_path_escape() {
let root = std::env::temp_dir().join(format!("dsh-plugin-recovery-{}", std::process::id()));
diff --git a/src-tauri/src/service/plugin/update.rs b/src-tauri/src/service/plugin/update.rs
index 7883539b..c2fe963e 100644
--- a/src-tauri/src/service/plugin/update.rs
+++ b/src-tauri/src/service/plugin/update.rs
@@ -391,15 +391,8 @@ fn percent_decode_once(value: &str) -> Option<String> {
String::from_utf8(decoded).ok()
}
-/// percent decode 只接受十六进制字节;非法 nibble 返回 None,使 selector
-/// 解析 fail closed 而不是生成被截断的 ref。
fn hex_value(value: u8) -> Option<u8> {
- match value {
- b'0'..=b'9' => Some(value - b'0'),
- b'a'..=b'f' => Some(value - b'a' + 10),
- b'A'..=b'F' => Some(value - b'A' + 10),
- _ => None,
- }
+ char::from(value).to_digit(16).map(|digit| digit as u8)
}
/// `owner/repo` 形态校验(owner/repo 各仅允许字母数字 `._-`,避免误吞 URL 首位)。
@@ -641,6 +634,37 @@ pub async fn refresh(app_handle: &AppHandle) -> Result<Vec<DshPlugin>, String> {
mod tests {
use super::*;
+ #[test]
+ fn hex_value_accepts_only_ascii_hex_nibbles() {
+ for byte in 0..=u8::MAX {
+ let expected = b"0123456789abcdef"
+ .iter()
+ .position(|candidate| *candidate == byte.to_ascii_lowercase())
+ .map(|position| position as u8);
+ assert_eq!(hex_value(byte), expected, "byte={byte}");
+ }
+ }
+
+ #[test]
+ fn percent_decode_preserves_single_pass_and_rejects_invalid_escapes() {
+ for (encoded, expected) in [
+ ("branch%2Ffeature", Some("branch/feature")),
+ ("%41%4a%4F", Some("AJO")),
+ ("%252F", Some("%2F")),
+ ("%E4%B8%AD", Some("中")),
+ ("%", None),
+ ("%2", None),
+ ("%2G", None),
+ ("%FF", None),
+ ] {
+ assert_eq!(
+ percent_decode_once(encoded).as_deref(),
+ expected,
+ "{encoded}"
+ );
+ }
+ }
+
fn target(repo: &str, reference: Option<&str>) -> Option<GitHubTarget> {
Some(GitHubTarget {
repo: repo.to_string(),
diff --git a/src-tauri/src/service/plugin/verify.rs b/src-tauri/src/service/plugin/verify.rs
index 9367e15e..6ef09d2f 100644
--- a/src-tauri/src/service/plugin/verify.rs
+++ b/src-tauri/src/service/plugin/verify.rs
@@ -31,6 +31,7 @@ use super::errors;
use super::install::{build_plugin_envs, harness_prefer_bundled_pnpm};
use super::installed::{installed_name, profile_dir, ProfilePackageJson};
use super::preset::{load_presets, PreinstallPluginInfo};
+use super::process::drain_captured;
/// 判定清单引用的预装插件是否缺失产物(纯函数,便于单测)。
///
@@ -312,14 +313,6 @@ fn drain_pipe<R: Read + Send + 'static>(mut reader: R, captured: Arc<Mutex<Strin
});
}
-/// 取出(并清空)共享缓冲区中的全部捕获输出。
-fn drain_captured(captured: Arc<Mutex<String>>) -> String {
- captured
- .lock()
- .map(|mut buf| std::mem::take(&mut *buf))
- .unwrap_or_default()
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rs
index d08e16a2..823a62ff 100644
--- a/src-tauri/src/service/plugin/watch.rs
+++ b/src-tauri/src/service/plugin/watch.rs
@@ -109,7 +109,7 @@ fn plugin_dir(profile: &Path, id: &str) -> PathBuf {
/// 规范化仓库地址,便于系统浏览器直接打开:
/// `git+https://...` / `git://...` → `https://...`,去掉末尾 `.git`
-fn normalize_repo_url(url: &str) -> String {
+pub(crate) fn normalize_repo_url(url: &str) -> String {
let mut normalized = url.trim().to_string();
if let Some(rest) = normalized.strip_prefix("git+") {
normalized = rest.to_string();
@@ -256,16 +256,7 @@ pub fn list(app_handle: &AppHandle) -> Vec<DshPlugin> {
/// 同时把监控指纹同步到当前状态,避免紧接着的下一次轮询重复推送同一列表。
pub fn force_emit(app_handle: &AppHandle) {
let fp = fingerprint(app_handle);
- let mut state = STATE
- .get_or_init(|| {
- Mutex::new(WatchState {
- last_fp: None,
- last_emit: None,
- pending_fp: None,
- })
- })
- .lock()
- .unwrap();
+ let mut state = STATE.get_or_init(Mutex::default).lock().unwrap();
state.pending_fp = None;
state.last_fp = fp;
drop(state);
@@ -303,6 +294,7 @@ fn fingerprint(app_handle: &AppHandle) -> Option<String> {
}
/// 监控状态:指纹 + 防抖窗口(仅 check_and_emit 单线程轮询访问)
+#[derive(Default)]
struct WatchState {
/// 上次已推送的指纹(内容一致则跳过)
last_fp: Option<String>,
@@ -318,16 +310,7 @@ static STATE: OnceLock<Mutex<WatchState>> = OnceLock::new();
/// 重新解析插件列表并推送 `dsh-plugins-updated` 事件。
pub fn check_and_emit(app_handle: &AppHandle) {
let fp = fingerprint(app_handle);
- let mut state = STATE
- .get_or_init(|| {
- Mutex::new(WatchState {
- last_fp: None,
- last_emit: None,
- pending_fp: None,
- })
- })
- .lock()
- .unwrap();
+ let mut state = STATE.get_or_init(Mutex::default).lock().unwrap();
if state.last_fp.as_deref() == fp.as_deref() {
return;
@@ -413,6 +396,38 @@ mod tests {
}]
}
+ #[test]
+ fn watch_state_default_starts_without_fingerprints_or_debounce() {
+ let state = Mutex::<WatchState>::default();
+ let state = state.lock().unwrap();
+ assert_eq!(state.last_fp, None);
+ assert_eq!(state.last_emit, None);
+ assert_eq!(state.pending_fp, None);
+ }
+
+ #[test]
+ fn repo_url_normalization_preserves_existing_boundaries() {
+ for (input, expected) in [
+ (" git+git://example/repo.git ", "https://example/repo"),
+ ("git+https://example/repo.git", "https://example/repo"),
+ ("git://example/repo.git", "https://example/repo"),
+ ("https://example/repo.git/", "https://example/repo.git/"),
+ (
+ "https://example/repo.git?x=1",
+ "https://example/repo.git?x=1",
+ ),
+ ("git+ssh://example/repo.git", "ssh://example/repo"),
+ (
+ "git+git+https://example/repo.git",
+ "git+https://example/repo",
+ ),
+ ("Git://example/repo.git", "Git://example/repo"),
+ (" ", ""),
+ ] {
+ assert_eq!(normalize_repo_url(input), expected, "{input}");
+ }
+ }
+
#[test]
fn parse_plugins_lists_direct_deps_with_meta() {
let dir = build_profile(