Skip to content

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

fix(plugin): 禁用改用 loader entry id 并识别官方包级禁用 (#1136)

Hairy847e27103a0e
diff --git a/src-tauri/src/service/plugin/atomic_write.rs b/src-tauri/src/service/plugin/atomic_write.rs
index f44adab7..fa2ad147 100644
--- a/src-tauri/src/service/plugin/atomic_write.rs
+++ b/src-tauri/src/service/plugin/atomic_write.rs
@@ -2,7 +2,13 @@ use std::fs::File;
use std::io::{self, Write};
use std::path::Path;
+/// 原子替换 patch 层:拒绝覆盖符号链接(patch 会被用户手写,链接等于绕过范围校验)。
pub(super) fn write_patch_layer_atomically(path: &Path, rendered: &str) -> io::Result<()> {
+ write_file_atomically(path, rendered)
+}
+
+/// 经同目录临时文件原子替换 UTF-8 文件;失败时保留原文件。
+pub(super) fn write_file_atomically(path: &Path, rendered: &str) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_symlink() => {
return Err(io::Error::new(
diff --git a/src-tauri/src/service/plugin/disable.rs b/src-tauri/src/service/plugin/disable.rs
index cb370083..8ff68eb7 100644
--- a/src-tauri/src/service/plugin/disable.rs
+++ b/src-tauri/src/service/plugin/disable.rs
@@ -1,18 +1,20 @@
//! 插件禁用/启用:改写 profile 的 `cordis.patch.yml` 顶层覆盖项的 `disabled` 字段。
//!
//! 与官方 Plugins 页 / dshmarket 共用同一处状态(patch 层),桌面壳不再维护第二份
-//! 记录。禁用保留 node_modules 内的包体与 `dsh.profile.bundles` 选择,启用无需重新
-//! 下载,也不动组合包开关。
+//! 记录。禁用只写 patch 覆盖(保留 node_modules 包体与 bundles 选择);启用撤掉覆盖,
+//! 并在插件是被官方包级开关移出 `dsh.profile.bundles` 的 bundle 包时补回 bundles。
+//! 覆盖项必须用 loader 的 entry id(官方 `patchId`),而不是 npm 包名:两者经常
+//! 不同(`dshmarket` → `dsh-market`),按包名写的覆盖命中不了任何条目,禁用看起来
+//! 成功、运行时却照旧加载。
use std::collections::HashSet;
use std::fs;
-use std::path::Path;
+use std::path::{Component, Path, PathBuf};
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};
+use crate::service::plugin::recovery::{is_core_package, is_package_name, patch_entry_targets};
use crate::service::plugin::{process, watch};
/// profile 层的 patch 覆盖文件。
@@ -88,19 +90,115 @@ fn plugin_target_names(profile: &Path, id: &str) -> Vec<String> {
names
}
-/// 插件是否被 profile 的 patch 覆盖禁用。
-pub(crate) fn has_patch_disable(profile: &Path, id: &str) -> bool {
+/// 条目模块名是否属于该插件(同时覆盖 `dsh-ops/shell` 这类子路径导出)。
+fn module_targets(module: &str, names: &[String]) -> bool {
+ names.iter().any(|name| {
+ module == name
+ || module
+ .strip_prefix(name.as_str())
+ .is_some_and(|rest| rest.starts_with('/'))
+ })
+}
+
+/// 插件包声明的 bundle patch 文件(`dsh.bundle.patch`),限定在包目录内。
+fn bundle_patch_file(profile: &Path, id: &str) -> Option<PathBuf> {
+ let package_dir = profile.join("node_modules").join(id);
+ let meta: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(package_dir.join("package.json")).ok()?).ok()?;
+ let relative = Path::new(meta.get("dsh")?.get("bundle")?.get("patch")?.as_str()?);
+ let escapes = relative.is_absolute()
+ || relative.components().any(|part| {
+ matches!(
+ part,
+ Component::ParentDir | Component::RootDir | Component::Prefix(_)
+ )
+ });
+ (!escapes).then(|| package_dir.join(relative))
+}
+
+fn push_entry_id(map: &serde_yaml::Mapping, names: &[String], ids: &mut Vec<String>) {
+ let Some(id) = map.get("id").and_then(|value| value.as_str()) else {
+ return;
+ };
+ let Some(module) = map.get("name").and_then(|value| value.as_str()) else {
+ return;
+ };
+ if module_targets(module, names) && !ids.iter().any(|existing| existing == id) {
+ ids.push(id.to_string());
+ }
+}
+
+/// 从一层补丁文档里收集目标插件的 loader entry id:顶层覆盖项与 `insert` 列表。
+fn collect_entry_ids(doc: &serde_yaml::Value, names: &[String], ids: &mut Vec<String>) {
+ let Some(entries) = doc.as_sequence() else {
+ return;
+ };
+ for entry in entries {
+ let Some(map) = entry.as_mapping() else {
+ continue;
+ };
+ push_entry_id(map, names, ids);
+ let Some(serde_yaml::Value::Sequence(inserted)) = map.get("insert") else {
+ continue;
+ };
+ for item in inserted {
+ if let Some(map) = item.as_mapping() {
+ push_entry_id(map, names, ids);
+ }
+ }
+ }
+}
+
+/// 插件在 loader 组合树里的条目 id(官方 `PluginInfo.patchId`)。
+///
+/// 来源是插件自带的 bundle patch 与 profile patch 里手工插入的同模块条目;只收
+/// `name` 等于包名或以 `包名/` 开头的条目,避免把顺带插入的其它模块算进来
+/// (`dsh-tauri-pet` 还会插入 skill-filesystem)。
+fn plugin_entry_ids(profile: &Path, id: &str) -> Vec<String> {
let names = plugin_target_names(profile, id);
- load_patch_disabled(profile)
+ let mut ids = Vec::new();
+ for path in [
+ bundle_patch_file(profile, id),
+ Some(profile.join(PATCH_FILE)),
+ ]
+ .into_iter()
+ .flatten()
+ {
+ let Some(content) = fs::read_to_string(path).ok() else {
+ continue;
+ };
+ let Ok(doc) = serde_yaml::from_str::<serde_yaml::Value>(&content) else {
+ continue;
+ };
+ collect_entry_ids(&doc, &names, &mut ids);
+ }
+ ids
+}
+
+/// 插件是否被 profile 的 patch 覆盖完全禁用。
+///
+/// 一个包可能对应多个 loader 条目(`dsh-ops/*`):只有全部条目都被禁用才算
+/// 「已禁用」,否则面板会给出启用入口,把仍然在跑的条目误当成整体已关闭。
+pub(crate) fn has_patch_disable(profile: &Path, id: &str) -> bool {
+ let disabled = load_patch_disabled(profile);
+ if disabled.is_empty() {
+ return false;
+ }
+ let entry_ids = plugin_entry_ids(profile, id);
+ if !entry_ids.is_empty() {
+ return entry_ids.iter().all(|entry_id| disabled.contains(entry_id));
+ }
+ plugin_target_names(profile, id)
.iter()
- .any(|target| names.iter().any(|n| n == target))
+ .any(|name| disabled.contains(name))
}
/// 在 patch 里为目标插件写入 `disabled: true`。
///
-/// 与官方插件开关同款语义:命中最后一条匹配条目就改它的 `disabled`(条目里其它配置
-/// 原样保留),没有匹配条目则追加 `{id, disabled: true}`。已是禁用态时返回
-/// `Ok(false)` 且不写盘。
+/// 与官方插件开关同款语义:逐个 loader entry id 命中最后一条覆盖项就改它的
+/// `disabled`(条目里其它配置原样保留),没有覆盖项则追加 `{id, disabled: true}`。
+/// 已知条目 id 时不再按 npm 包名追加:官方 loader 只按 entry id 命中,包名覆盖
+/// 等于空写。已是禁用态时返回 `Ok(false)` 且不写盘。
pub(crate) fn add_patch_disable(profile: &Path, id: &str) -> Result<bool, String> {
let path = profile.join(PATCH_FILE);
let content = match fs::read_to_string(&path) {
@@ -124,34 +222,69 @@ pub(crate) fn add_patch_disable(profile: &Path, id: &str) -> Result<bool, String
},
};
let names = plugin_target_names(profile, id);
- let key = serde_yaml::Value::String(DISABLED_KEY.to_string());
- let mut hit: Option<&mut serde_yaml::Mapping> = None;
- for entry in entries.iter_mut().rev() {
- if !names.iter().any(|name| patch_entry_targets(entry, name)) {
- continue;
- }
- if let serde_yaml::Value::Mapping(map) = entry {
- hit = Some(map);
- break;
+ let disabled_key = || serde_yaml::Value::String(DISABLED_KEY.to_string());
+ let disable_entry = |entry_id: &str| {
+ let mut map = serde_yaml::Mapping::new();
+ map.insert(
+ serde_yaml::Value::String("id".to_string()),
+ serde_yaml::Value::String(entry_id.to_string()),
+ );
+ map.insert(disabled_key(), serde_yaml::Value::Bool(true));
+ serde_yaml::Value::Mapping(map)
+ };
+ let mut changed = false;
+ let entry_ids = plugin_entry_ids(profile, id);
+ if entry_ids.is_empty() {
+ let mut hit: Option<&mut serde_yaml::Mapping> = None;
+ for entry in entries.iter_mut().rev() {
+ if !names.iter().any(|name| patch_entry_targets(entry, name)) {
+ continue;
+ }
+ if let serde_yaml::Value::Mapping(map) = entry {
+ hit = Some(map);
+ break;
+ }
}
- }
- match hit {
- Some(map) => {
- if patch_entry_disabled(map) {
- return Ok(false);
+ match hit {
+ Some(map) => {
+ if !patch_entry_disabled(map) {
+ map.insert(disabled_key(), serde_yaml::Value::Bool(true));
+ changed = true;
+ }
+ }
+ None => {
+ entries.push(disable_entry(id));
+ changed = true;
}
- map.insert(key, serde_yaml::Value::Bool(true));
}
- None => {
- let mut map = serde_yaml::Mapping::new();
- map.insert(
- serde_yaml::Value::String("id".to_string()),
- serde_yaml::Value::String(id.to_string()),
- );
- map.insert(key, serde_yaml::Value::Bool(true));
- entries.push(serde_yaml::Value::Mapping(map));
+ } else {
+ for entry_id in entry_ids {
+ let hit = entries.iter_mut().rev().find_map(|entry| {
+ let map = entry.as_mapping_mut()?;
+ let same_id = map.get("id").and_then(|value| value.as_str()) == Some(&entry_id);
+ let same_module = map
+ .get("name")
+ .and_then(|value| value.as_str())
+ .is_none_or(|name| module_targets(name, &names));
+ (same_id && same_module && !map.contains_key("insert")).then_some(map)
+ });
+ match hit {
+ Some(map) => {
+ if !patch_entry_disabled(map) {
+ map.insert(disabled_key(), serde_yaml::Value::Bool(true));
+ changed = true;
+ }
+ }
+ None => {
+ entries.push(disable_entry(&entry_id));
+ changed = true;
+ }
+ }
}
}
+ if !changed {
+ return Ok(false);
+ }
let rendered = serde_yaml::to_string(&serde_yaml::Value::Sequence(entries))
.map_err(|e| format!("DISABLE_PATCH_RENDER_FAILED: {e}"))?;
super::atomic_write::write_patch_layer_atomically(&path, &rendered)
@@ -163,11 +296,14 @@ pub(crate) fn add_patch_disable(profile: &Path, id: &str) -> Result<bool, String
/// 从 patch 移除目标插件的显式禁用覆盖,其余配置原样保留(issue #399):
/// 纯禁用条目(仅 `id` + `disabled`)整条移除,带其它配置的条目只摘 `disabled` 键。
///
+/// 命中口径同时包含 loader entry id 与包名别名,顺带清掉旧版按包名写下的无效覆盖。
/// 幂等:无 patch 文件 / 无法解析 / 无目标禁用条目时返回 `Ok(false)` 且不写盘。
pub(crate) fn strip_patch_disable(profile: &Path, id: &str) -> Result<bool, String> {
let path = profile.join(PATCH_FILE);
- let Ok(content) = fs::read_to_string(&path) else {
- return Ok(false);
+ let content = match fs::read_to_string(&path) {
+ Ok(content) => content,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(error) => return Err(format!("ENABLE_PATCH_READ_FAILED: {error}")),
};
let mut doc: serde_yaml::Value =
serde_yaml::from_str(&content).map_err(|e| format!("ENABLE_PATCH_PARSE_FAILED: {e}"))?;
@@ -175,6 +311,7 @@ pub(crate) fn strip_patch_disable(profile: &Path, id: &str) -> Result<bool, Stri
return Ok(false);
};
let names = plugin_target_names(profile, id);
+ let entry_ids = plugin_entry_ids(profile, id);
let mut changed = false;
let mut kept: Vec<serde_yaml::Value> = Vec::with_capacity(entries.len());
for entry in entries.drain(..) {
@@ -182,7 +319,10 @@ pub(crate) fn strip_patch_disable(profile: &Path, id: &str) -> Result<bool, Stri
kept.push(entry);
continue;
};
- let targeted = names.iter().any(|name| patch_entry_targets(&entry, name));
+ let targeted = entry_ids
+ .iter()
+ .any(|entry_id| map.get("id").and_then(|value| value.as_str()) == Some(entry_id))
+ || names.iter().any(|name| patch_entry_targets(&entry, name));
if !targeted || !patch_entry_disabled(&map) {
kept.push(entry);
continue;
@@ -221,18 +361,27 @@ fn read_manifest(profile: &Path, prefix: &str) -> Result<serde_json::Value, Stri
serde_json::from_str(&content).map_err(|e| format!("{prefix}_PARSE_MANIFEST: {e}"))
}
+/// 插件 id 校验:允许 scoped 包名(`@scope/pkg`),同时挡住路径分隔符与穿越。
+///
+/// `fs_guard::validate_id` 会拒绝 `/`,scoped 插件(如 `@wenaixi/dsh-ponytail`)
+/// 按它校验会永远无法禁用/启用。
+fn validate_plugin_id(id: &str) -> Result<(), String> {
+ is_package_name(id)
+ .then_some(())
+ .ok_or_else(|| format!("INVALID_ID: plugin id is not a package name: {id}"))
+}
+
/// 禁用插件的纯逻辑(不依赖 AppHandle,便于单元测试)。
///
/// 只写 patch 覆盖:不再改 `dsh.profile.bundles`(组合包开关归官方插件页),也不写任何
/// 桌面侧清单。
pub(crate) fn disable_plugin_at(profile: &Path, id: &str) -> Result<(), String> {
- // 官方/核心包 id 含 `/`,必须先于 validate_id 拦截,否则会被字符集校验误判。
if is_core_package(id) {
return Err(format!(
"DISABLE_INTERNAL_PLUGIN: refusing to disable internal/official plugin {id}"
));
}
- fs_guard::validate_id(id)?;
+ validate_plugin_id(id)?;
let manifest = read_manifest(profile, "DISABLE")?;
if !is_in_dependencies(&manifest, id) {
return Err(format!(
@@ -243,21 +392,81 @@ pub(crate) fn disable_plugin_at(profile: &Path, id: &str) -> Result<(), String>
Ok(())
}
-/// 启用插件的纯逻辑(不依赖 AppHandle,便于单元测试):仅摘除 patch 里的禁用覆盖。
+/// 插件包是否声明了 `dsh.bundle`(只有 bundle 包才会被官方包级开关移出 bundles)。
+fn declares_bundle(profile: &Path, id: &str) -> bool {
+ let Ok(content) =
+ fs::read_to_string(profile.join("node_modules").join(id).join("package.json"))
+ else {
+ return false;
+ };
+ serde_json::from_str::<serde_json::Value>(&content)
+ .ok()
+ .and_then(|meta| meta.get("dsh").and_then(|dsh| dsh.get("bundle")).cloned())
+ .is_some()
+}
+
+/// 把插件补回 profile 的 `dsh.profile.bundles`(官方包级禁用的反向操作)。
+fn add_bundle(profile: &Path, id: &str, manifest: &mut serde_json::Value) -> Result<bool, String> {
+ let Some(bundles) = manifest
+ .pointer_mut("/dsh/profile/bundles")
+ .and_then(serde_json::Value::as_array_mut)
+ else {
+ return Err("ENABLE_BUNDLES_UNSUPPORTED: dsh.profile.bundles is not a list".to_string());
+ };
+ if bundles.iter().any(|bundle| bundle.as_str() == Some(id)) {
+ return Ok(false);
+ }
+ bundles.push(serde_json::Value::String(id.to_string()));
+ let rendered = serde_json::to_string_pretty(&manifest)
+ .map_err(|e| format!("ENABLE_MANIFEST_RENDER_FAILED: {e}"))?;
+ super::atomic_write::write_file_atomically(
+ &profile.join("package.json"),
+ &format!("{rendered}\n"),
+ )
+ .map_err(|e| format!("ENABLE_MANIFEST_WRITE_FAILED: {e}"))?;
+ Ok(true)
+}
+
+/// 插件是否在 `dsh.profile.bundles` 里;bundle 列表缺失/非数组时返回 `None`。
+fn bundles_include(manifest: &serde_json::Value, id: &str) -> Option<bool> {
+ manifest
+ .pointer("/dsh/profile/bundles")
+ .and_then(serde_json::Value::as_array)
+ .map(|bundles| bundles.iter().any(|bundle| bundle.as_str() == Some(id)))
+}
+
+/// 启用插件的纯逻辑(不依赖 AppHandle,便于单元测试):撤掉 patch 禁用覆盖;
+/// 若插件是被官方包级开关移出 `dsh.profile.bundles` 的 bundle 包,补回 bundles。
+///
+/// 清单读-改-写持 `dsh-atomic-write` 的跨进程写锁(官方插件管理器同款),并在锁内
+/// 重新读取,避免把并发切换的结果覆盖回旧快照。先补 bundles 再撤 patch:任一步失败
+/// 都停在「仍禁用」状态,用户可原样重试。
pub(crate) fn enable_plugin_at(profile: &Path, id: &str) -> Result<(), String> {
- fs_guard::validate_id(id)?;
+ validate_plugin_id(id)?;
let manifest = read_manifest(profile, "ENABLE")?;
if !is_in_dependencies(&manifest, id) {
return Err(format!(
"ENABLE_NOT_INSTALLED: plugin {id} is not installed"
));
}
- if !has_patch_disable(profile, id) {
+ let restored = match bundles_include(&manifest, id) {
+ Some(false) if declares_bundle(profile, id) => {
+ let _lock = process::acquire_plugin_writer_lock(profile)?;
+ let mut locked = read_manifest(profile, "ENABLE")?;
+ if is_in_dependencies(&locked, id) && bundles_include(&locked, id) == Some(false) {
+ add_bundle(profile, id, &mut locked)?
+ } else {
+ false
+ }
+ }
+ _ => false,
+ };
+ let stripped = strip_patch_disable(profile, id)?;
+ if !restored && !stripped {
return Err(format!(
"ENABLE_NOT_DISABLED: plugin {id} has no disable override in cordis.patch.yml"
));
}
- strip_patch_disable(profile, id)?;
Ok(())
}
@@ -322,6 +531,55 @@ mod tests {
fs::write(profile.join(PATCH_FILE), content).unwrap();
}
+ /// 构造带真实 bundle patch 的 profile:`(依赖键, 包内 name, bundle patch)`。
+ fn build_bundle_profile(test_name: &str, packages: &[(&str, &str, &str)]) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "dsh-disable-bundle-{}-{}",
+ test_name,
+ std::process::id()
+ ));
+ let _ = fs::remove_dir_all(&dir);
+ let mut dependencies = serde_json::Map::new();
+ let mut bundles = Vec::new();
+ for (id, name, patch) in packages {
+ dependencies.insert((*id).to_string(), serde_json::json!("1.0.0"));
+ bundles.push(serde_json::json!(id));
+ let package_dir = dir.join("node_modules").join(id);
+ fs::create_dir_all(&package_dir).unwrap();
+ fs::write(
+ package_dir.join("package.json"),
+ serde_json::json!({
+ "name": name,
+ "version": "1.0.0",
+ "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
+ })
+ .to_string(),
+ )
+ .unwrap();
+ fs::write(package_dir.join("cordis.patch.yml"), patch).unwrap();
+ }
+ let manifest = serde_json::json!({
+ "name": "dsh-profile-web",
+ "private": true,
+ "dependencies": dependencies,
+ "dsh": { "profile": { "bundles": bundles } }
+ });
+ fs::write(
+ dir.join("package.json"),
+ serde_json::to_string_pretty(&manifest).unwrap(),
+ )
+ .unwrap();
+ dir
+ }
+
+ fn patch_ids(profile: &Path) -> Vec<String> {
+ read_patch(profile)
+ .lines()
+ .filter_map(|line| line.trim().strip_prefix("- id: "))
+ .map(str::to_string)
+ .collect()
+ }
+
#[test]
fn disable_writes_patch_override_and_keeps_bundles() {
let profile = build_profile("write-patch", "a");
@@ -568,4 +826,264 @@ mod tests {
fs::remove_dir_all(&profile).ok();
}
+
+ /// 核心回归:覆盖项必须写 loader entry id(官方 `patchId`);写 npm 包名
+ /// 命中不了任何条目,禁用会「成功」但运行时照旧加载。
+ #[test]
+ fn disable_writes_loader_entry_id_from_bundle_patch() {
+ let profile = build_bundle_profile(
+ "entry-id",
+ &[(
+ "dshmarket",
+ "dshmarket",
+ "- insert:\n - id: dsh-market\n name: dshmarket\n",
+ )],
+ );
+ disable_plugin_at(&profile, "dshmarket").unwrap();
+
+ assert_eq!(patch_ids(&profile), vec!["dsh-market".to_string()]);
+ assert!(has_patch_disable(&profile, "dshmarket"));
+ assert!(!add_patch_disable(&profile, "dshmarket").unwrap());
+
+ enable_plugin_at(&profile, "dshmarket").unwrap();
+ let doc: serde_yaml::Value = serde_yaml::from_str(&read_patch(&profile)).unwrap();
+ assert!(doc.as_sequence().unwrap().is_empty());
+ assert!(!has_patch_disable(&profile, "dshmarket"));
+
+ fs::remove_dir_all(&profile).ok();
+ }
+
+ /// 一个包可能插入多个条目(`dsh-ops/*`):禁用要覆盖全部,且不误伤同包顺带
+ /// 插入的其它模块(`dsh-tauri-pet` 的 skill-filesystem)。
+ #[test]
+ fn disable_covers_every_package_entry_and_ignores_foreign_inserts() {
+ let profile = build_bundle_profile(
+ "entries",
+ &[
+ (
+ "dsh-ops",
+ "dsh-ops",
+ "- insert:\n - id: dsh-ops-shell\n name: dsh-ops/shell\n - id: dsh-ops-file\n name: dsh-ops/file\n",
+ ),
+ (
+ "dsh-tauri-pet",
+ "dsh-tauri-pet",
+ "- insert:\n - id: dsh-tauri-pet-skills\n name: '@deepseek-ai/dsh-skill-filesystem'\n - id: dsh-tauri-pet\n name: dsh-tauri-pet\n",
+ ),
+ ],
+ );
+ disable_plugin_at(&profile, "dsh-ops").unwrap();
+
+ let ids = patch_ids(&profile);
+ assert!(ids.contains(&"dsh-ops-shell".to_string()));
+ assert!(ids.contains(&"dsh-ops-file".to_string()));
+ assert!(has_patch_disable(&profile, "dsh-ops"));
+ assert!(!has_patch_disable(&profile, "dsh-tauri-pet"));
+
+ enable_plugin_at(&profile, "dsh-ops").unwrap();
+ assert!(!read_patch(&profile).contains("dsh-ops-shell"));
+
+ fs::remove_dir_all(&profile).ok();
+ }
+
+ /// 旧版按包名写下的无效覆盖不再算「已禁用」,启用时顺带清掉。
+ #[test]
+ fn has_patch_disable_ignores_legacy_package_name_override() {
+ let profile = build_bundle_profile(
+ "legacy",
+ &[(
+ "dshmarket",
+ "dshmarket",
+ "- insert:\n - id: dsh-market\n name: dshmarket\n",
+ )],
+ );
+ write_patch(&profile, "- id: dshmarket\n disabled: true\n");
+ assert!(!has_patch_disable(&profile, "dshmarket"));
+
+ disable_plugin_at(&profile, "dshmarket").unwrap();
+ assert!(read_patch(&profile).contains("id: dsh-market"));
+ enable_plugin_at(&profile, "dshmarket").unwrap();
+ assert!(patch_ids(&profile).is_empty());
+
+ fs::remove_dir_all(&profile).ok();
+ }
+
+ #[test]
+ fn disable_updates_existing_entry_override_in_place() {
+ let profile = build_bundle_profile(
+ "existing",
+ &[(
+ "dshmarket",
+ "dshmarket",
+ "- insert:\n - id: dsh-market\n name: dshmarket\n",
+ )],
+ );
+ write_patch(&profile, "- id: dsh-market\n config:\n theme: dark\n");
+ disable_plugin_at(&profile, "dshmarket").unwrap();
+
+ let content = read_patch(&profile);
+ assert_eq!(content.matches("id: dsh-market").count(), 1);
+ assert!(content.contains("theme: dark"));
+ assert!(content.contains("disabled: true"));
+
+ fs::remove_dir_all(&profile).ok();
+ }
+
+ /// 手写 insert 的插件(没有 bundle patch)同样按插入条目的 id 禁用。
+ #[test]
+ fn disable_targets_entries_inserted_by_profile_patch() {
+ let profile = build_profile("profile-insert", "r");
+ let pkg_dir = profile.join("node_modules").join("dsh-better-sidebar");
+ fs::create_dir_all(&pkg_dir).unwrap();
+ fs::write(
+ pkg_dir.join("package.json"),
+ r#"{"name":"better-sidebar","version":"1.0.0"}"#,
+ )
+ .unwrap();
+ write_patch(
+ &profile,
+ "- insert:\n - id: sidebar-dev\n name: better-sidebar\n",
+ );
+ disable_plugin_at(&profile, "dsh-better-sidebar").unwrap();
+
+ let content = read_patch(&profile);
+ assert!(content.contains("id: sidebar-dev"));
+ assert!(has_patch_disable(&profile, "dsh-better-sidebar"));
+
+ enable_plugin_at(&profile, "dsh-better-sidebar").unwrap();
+ assert!(read_patch(&profile).contains("sidebar-dev"));
+ assert!(!has_patch_disable(&profile, "dsh-better-sidebar"));
+
+ fs::remove_dir_all(&profile).ok();
+ }
+
+ /// 官方包级开关的禁用是把 bundle 移出 `dsh.profile.bundles`;启用要补回。
+ #[test]
+ fn enable_restores_bundle_deselected_by_official_switch() {
+ let profile = build_bundle_profile(
+ "bundle-restored",
+ &[(
+ "dshmarket",
+ "dshmarket",
+ "- insert:\n - id: dsh-market\n name: dshmarket\n",
+ )],
+ );
+ let manifest_path = profile.join("package.json");
+ let mut manifest: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap()).unwrap();
+ manifest["dsh"]["profile"]["bundles"] = serde_json::json!([]);
+ fs::write(
+ &manifest_path,
+ serde_json::to_string_pretty(&manifest).unwrap(),
+ )
+ .unwrap();
+
+ enable_plugin_at(&profile, "dshmarket").unwrap();
+
+ let manifest: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap()).unwrap();
+ assert_eq!(
+ manifest["dsh"]["profile"]["bundles"],
+ serde_json::json!(["dshmarket"])
+ );
+
+ fs::remove_dir_all(&profile).ok();
+ }
+
+ /// scoped 包名(含 `/`)同样能禁用/启用:`fs_guard::validate_id` 会拒绝 `/`。
+ #[test]
+ fn disable_and_enable_scoped_plugin() {
+ let profile = build_bundle_profile(
+ "scoped",
+ &[(
+ "@wenaixi/dsh-ponytail",
+ "@wenaixi/dsh-ponytail",
+ "- insert:\n - id: ponytail\n name: '@wenaixi/dsh-ponytail'\n",
+ )],
+ );
+ disable_plugin_at(&profile, "@wenaixi/dsh-ponytail").unwrap();
+ assert_eq!(patch_ids(&profile), vec!["ponytail".to_string()]);
+
+ enable_plugin_at(&profile, "@wenaixi/dsh-ponytail").unwrap();
+ assert!(patch_ids(&profile).is_empty());
+
+ fs::remove_dir_all(&profile).ok();
+ }
+
+ /// 多条目包只有部分条目被禁用时,包整体仍算启用。
+ #[test]
+ fn has_patch_disable_requires_every_package_entry() {
+ let profile = build_bundle_profile(
+ "partial",
+ &[(
+ "dsh-ops",
+ "dsh-ops",
+ "- insert:\n - id: dsh-ops-shell\n name: dsh-ops/shell\n - id: dsh-ops-file\n name: dsh-ops/file\n",
+ )],
+ );
+ write_patch(&profile, "- id: dsh-ops-shell\n disabled: true\n");
+ assert!(!has_patch_disable(&profile, "dsh-ops"));
+
+ disable_plugin_at(&profile, "dsh-ops").unwrap();
+ assert!(has_patch_disable(&profile, "dsh-ops"));
+
+ fs::remove_dir_all(&profile).ok();
+ }
+
+ /// 档案没有 `dsh.profile.bundles` 时跳过补 bundle,但 patch 覆盖照常撤除。
+ #[test]
+ fn enable_without_bundles_list_still_strips_patch_disable() {
+ let profile = build_bundle_profile(
+ "no-bundles",
+ &[(
+ "dshmarket",
+ "dshmarket",
+ "- insert:\n - id: dsh-market\n name: dshmarket\n",
+ )],
+ );
+ let manifest_path = profile.join("package.json");
+ let mut manifest: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap()).unwrap();
+ manifest["dsh"] = serde_json::json!({});
+ fs::write(
+ &manifest_path,
+ serde_json::to_string_pretty(&manifest).unwrap(),
+ )
+ .unwrap();
+ write_patch(&profile, "- id: dsh-market\n disabled: true\n");
+
+ enable_plugin_at(&profile, "dshmarket").unwrap();
+ assert!(patch_ids(&profile).is_empty());
+
+ fs::remove_dir_all(&profile).ok();
+ }
+
+ /// patch 不可读时启用必须报错,不能把「补回 bundle」当成功而留下未知禁用态。
+ #[test]
+ fn enable_reports_unreadable_patch_instead_of_success() {
+ let profile = build_bundle_profile(
+ "unreadable-enable",
+ &[(
+ "dshmarket",
+ "dshmarket",
+ "- insert:\n - id: dsh-market\n name: dshmarket\n",
+ )],
+ );
+ let manifest_path = profile.join("package.json");
+ let mut manifest: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(&manifest_path).unwrap()).unwrap();
+ manifest["dsh"]["profile"]["bundles"] = serde_json::json!([]);
+ fs::write(
+ &manifest_path,
+ serde_json::to_string_pretty(&manifest).unwrap(),
+ )
+ .unwrap();
+ fs::write(profile.join(PATCH_FILE), [0xff, 0xfe]).unwrap();
+
+ let error = enable_plugin_at(&profile, "dshmarket").unwrap_err();
+ assert!(error.starts_with("ENABLE_PATCH_READ_FAILED:"), "{error}");
+ assert!(!profile.join("package.json.lock").exists());
+
+ fs::remove_dir_all(&profile).ok();
+ }
}
diff --git a/src-tauri/src/service/plugin/process.rs b/src-tauri/src/service/plugin/process.rs
index f3d703d3..f1fb78c0 100644
--- a/src-tauri/src/service/plugin/process.rs
+++ b/src-tauri/src/service/plugin/process.rs
@@ -12,6 +12,7 @@ use std::io::{BufRead, BufReader, Read};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
use tauri::{Emitter, Manager, WebviewWindow};
use crate::utils::decode_process_line;
@@ -164,6 +165,118 @@ pub(crate) fn clear_orphan_plugin_writer_lock(profile_dir: &Path) -> bool {
true
}
+/// 跨进程写锁守卫:按 `dsh-atomic-write` 的 `<profile>/package.json.lock` 协议
+/// 持有写锁,Drop 时释放。
+pub(crate) struct PluginWriterLock {
+ path: std::path::PathBuf,
+}
+
+impl Drop for PluginWriterLock {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.path);
+ }
+}
+
+/// 获取 profile 清单的跨进程写锁,供桌面壳直接改写 `package.json` 时使用。
+///
+/// 官方插件管理器和 `dsh plugin` 子进程都走 `withFileLock` 的同一把锁;桌面壳
+/// 的读-改-写也必须持锁,否则并发切包时会把官方刚写入的清单覆盖回旧快照。
+pub(crate) fn acquire_plugin_writer_lock(profile_dir: &Path) -> Result<PluginWriterLock, String> {
+ let path = plugin_writer_lock_path(profile_dir);
+ let deadline = Instant::now() + Duration::from_secs(2);
+ let mut delay = Duration::from_millis(20);
+ loop {
+ match std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&path)
+ {
+ Ok(mut file) => {
+ use std::io::Write;
+ let guard = PluginWriterLock { path };
+ let written = file
+ .write_all(format!("{}\n", std::process::id()).as_bytes())
+ .and_then(|()| file.sync_all());
+ drop(file);
+ written.map_err(|e| format!("PLUGIN_WRITER_LOCK_WRITE_FAILED: {e}"))?;
+ return Ok(guard);
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
+ take_over_exited_plugin_writer_lock(&path);
+ }
+ Err(error) => return Err(format!("PLUGIN_WRITER_LOCK_FAILED: {error}")),
+ }
+ if Instant::now() >= deadline {
+ return Err(format!(
+ "PLUGIN_WRITER_LOCK_TIMEOUT: timed out waiting for {}",
+ path.display()
+ ));
+ }
+ std::thread::sleep(delay);
+ delay = (delay * 2).min(Duration::from_millis(200));
+ }
+}
+
+/// 接管已退出进程留下的写锁:认领文件 + 二次核对,避免误删竞争方刚拿到的锁。
+fn take_over_exited_plugin_writer_lock(path: &Path) -> bool {
+ let Ok(record) = std::fs::read_to_string(path) else {
+ return false;
+ };
+ if !orphan_lock_should_clear(&record, plugin_process_has_exited) {
+ return false;
+ }
+ let Some(claim) = claim_takeover(path, &record) else {
+ return false;
+ };
+ let still_stale = std::fs::read_to_string(path).ok().as_deref() == Some(record.as_str())
+ && orphan_lock_should_clear(&record, plugin_process_has_exited);
+ let removed = still_stale && std::fs::remove_file(path).is_ok();
+ let _ = std::fs::remove_file(&claim);
+ removed
+}
+
+/// 认领一次接管:认领文件记录持有者 PID,已退出持有者留下的认领可被回收。
+fn claim_takeover(path: &Path, record: &str) -> Option<std::path::PathBuf> {
+ use std::io::Write;
+
+ let claim = path.with_file_name(format!(
+ "package.json.lock.takeover-{:016x}",
+ lock_record_hash(record)
+ ));
+ for attempt in 0..2 {
+ match std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&claim)
+ {
+ Ok(mut file) => {
+ let _ = file
+ .write_all(format!("{}\n", std::process::id()).as_bytes())
+ .and_then(|()| file.sync_all());
+ return Some(claim);
+ }
+ Err(error) if attempt == 0 && error.kind() == std::io::ErrorKind::AlreadyExists => {
+ let Ok(owner) = std::fs::read_to_string(&claim) else {
+ return None;
+ };
+ if !orphan_lock_should_clear(&owner, plugin_process_has_exited) {
+ return None;
+ }
+ let _ = std::fs::remove_file(&claim);
+ }
+ Err(_) => return None,
+ }
+ }
+ None
+}
+
+fn lock_record_hash(record: &str) -> u64 {
+ use std::hash::{Hash, Hasher};
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
+ record.hash(&mut hasher);
+ hasher.finish()
+}
+
pub(crate) fn process_cleanup_failure(owner: ProcessOwner) -> Option<String> {
cleanup_failure_sender()
.borrow()
@@ -666,4 +779,66 @@ mod tests {
assert!(!clear_orphan_plugin_writer_lock(&dir), "no lock, no-op");
std::fs::remove_dir_all(&dir).unwrap();
}
+
+ fn writer_lock_test_dir(tag: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "dsh-writer-lock-{}-{:?}-{tag}",
+ std::process::id(),
+ std::thread::current().id()
+ ));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn writer_lock_records_holder_and_releases_on_drop() {
+ let dir = writer_lock_test_dir("release");
+ let path = plugin_writer_lock_path(&dir);
+
+ let guard = acquire_plugin_writer_lock(&dir).unwrap();
+ assert_eq!(
+ std::fs::read_to_string(&path).unwrap().trim(),
+ std::process::id().to_string()
+ );
+
+ drop(guard);
+ assert!(!path.exists());
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn writer_lock_takes_over_dead_holder() {
+ let dir = writer_lock_test_dir("takeover");
+ let path = plugin_writer_lock_path(&dir);
+ std::fs::write(&path, "4000000\n").unwrap();
+
+ let guard = acquire_plugin_writer_lock(&dir).unwrap();
+ assert_eq!(
+ std::fs::read_to_string(&path).unwrap().trim(),
+ std::process::id().to_string()
+ );
+
+ drop(guard);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn writer_lock_reclaims_claim_left_by_exited_process() {
+ let dir = writer_lock_test_dir("stale-claim");
+ let path = plugin_writer_lock_path(&dir);
+ let record = "4000000\n".to_string();
+ std::fs::write(&path, &record).unwrap();
+ let claim = path.with_file_name(format!(
+ "package.json.lock.takeover-{:016x}",
+ lock_record_hash(&record)
+ ));
+ std::fs::write(&claim, "3999999\n").unwrap();
+
+ let guard = acquire_plugin_writer_lock(&dir).unwrap();
+ assert!(!claim.exists());
+
+ drop(guard);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
}
diff --git a/src-tauri/src/service/plugin/recovery/mod.rs b/src-tauri/src/service/plugin/recovery/mod.rs
index ac63f997..5e2010e0 100644
--- a/src-tauri/src/service/plugin/recovery/mod.rs
+++ b/src-tauri/src/service/plugin/recovery/mod.rs
@@ -52,7 +52,7 @@ pub(crate) fn is_core_package(name: &str) -> bool {
}
/// 是否为合法的 npm 包名(可带 scope)。用于过滤日志里提取到的候选引用。
-fn is_package_name(s: &str) -> bool {
+pub(crate) fn is_package_name(s: &str) -> bool {
let s = s.trim();
if s.is_empty() || s.contains(':') || s.chars().any(|c| c.is_whitespace()) {
return false;
diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rs
index ea66e9d0..a82c2604 100644
--- a/src-tauri/src/service/plugin/watch.rs
+++ b/src-tauri/src/service/plugin/watch.rs
@@ -45,11 +45,11 @@ pub struct DshPlugin {
pub repo_url: String,
/// 是否在 `dsh.profile.bundles` 中(启动时自动加载)
pub bundled: bool,
- /// 是否在 profile 的 `cordis.patch.yml` 中被禁用(`disabled: true`)。
+ /// 插件开关状态:profile `cordis.patch.yml` 里的 `disabled` 覆盖,或已安装的
+ /// bundle 包被移出 `dsh.profile.bundles`(官方 Plugins 页的包级禁用)。
///
- /// 这是插件开关的唯一状态,与官方 Plugins 页 / dshmarket 共用:`bundled`
- /// 只表示是否在 `dsh.profile.bundles` 中被自动加载,不代表用户开关。
- pub patch_disabled: bool,
+ /// 与官方 Plugins 页 / dshmarket 共用同一处状态,桌面壳不维护第二份记录。
+ pub disabled: bool,
/// 预设清单中的「推荐」标记(绿色 chip)
pub recommended: bool,
/// 预设清单中的「修复」标记(黄色 chip)
@@ -84,6 +84,15 @@ struct PluginPackageJson {
homepage: Option<String>,
#[serde(default)]
repository: Option<RepositoryField>,
+ #[serde(default)]
+ dsh: Option<PluginDshField>,
+}
+
+/// `package.json` 的 `dsh` 段:只关心是否声明了 `bundle`(用于判定官方包级禁用)。
+#[derive(Deserialize, Default)]
+struct PluginDshField {
+ #[serde(default)]
+ bundle: Option<serde_json::Value>,
}
/// repository 字段兼容两种形态:字符串 URL 或 `{ "type": "git", "url": ... }` 对象
@@ -154,10 +163,6 @@ pub(crate) fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) ->
.map(|p| installed_name(p).to_string())
.collect();
- // 插件开关的唯一状态:`cordis.patch.yml` 顶层 `disabled: true` 条目(与官方
- // Plugins 页 / dshmarket 共用)。
- let patch_disabled_set = crate::service::plugin::disable::load_patch_disabled(profile);
-
let mut dep_ids: Vec<&String> = manifest.dependencies.keys().collect();
// 稳定排序:启动加载(bundles)的插件在前,其余按 id 字典序
dep_ids.sort_by_key(|id| (!bundled.contains(id.as_str()), id.as_str()));
@@ -182,7 +187,9 @@ pub(crate) fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) ->
.and_then(|m| m.name.clone())
.or_else(|| preset.map(|p| p.name.clone()))
.unwrap_or_else(|| id.clone());
- let patch_disabled_by_name = patch_disabled_set.contains(name.as_str());
+ let installed_bundle = meta
+ .as_ref()
+ .is_some_and(|m| m.dsh.as_ref().and_then(|dsh| dsh.bundle.as_ref()).is_some());
DshPlugin {
id: id.clone(),
name,
@@ -197,7 +204,8 @@ pub(crate) fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) ->
.unwrap_or_default(),
repo_url,
bundled: bundled.contains(id.as_str()),
- patch_disabled: patch_disabled_set.contains(id.as_str()) || patch_disabled_by_name,
+ disabled: crate::service::plugin::disable::has_patch_disable(profile, id)
+ || (installed_bundle && !bundled.contains(id.as_str())),
recommended: preset.map(|p| p.recommended).unwrap_or(false),
fix: preset.map(|p| p.fix).unwrap_or(false),
internal: internal_names.contains(id.as_str()),
@@ -527,7 +535,7 @@ mod tests {
description: String::new(),
repo_url: String::new(),
bundled: true,
- patch_disabled: false,
+ disabled: false,
recommended: false,
fix: false,
internal: false,
@@ -559,7 +567,7 @@ mod tests {
description: String::new(),
repo_url: String::new(),
bundled: true,
- patch_disabled: false,
+ disabled: false,
recommended: false,
fix: false,
internal: false,
@@ -605,10 +613,10 @@ mod tests {
std::fs::remove_dir_all(&dir).ok();
}
- /// 三种状态由 `bundled`(是否在 `dsh.profile.bundles`)与 patch 禁用共同决定:
- /// - 在 bundles 且未被 patch 禁用 → bundled=true, patch_disabled=false(正常加载)
- /// - 不在 bundles 但被 patch 禁用 → bundled=false, patch_disabled=true(已禁用,可启用)
- /// - 不在 bundles 且未被 patch 禁用 → bundled=false, patch_disabled=false(未加载)
+ /// 安装后的三种状态:
+ /// - 在 bundles 且无禁用覆盖 → bundled=true, disabled=false(正常加载)
+ /// - bundle 包不在 bundles(官方包级开关禁用)→ bundled=false, disabled=true(已禁用)
+ /// - 非 bundle 依赖且不在 bundles → bundled=false, disabled=false(未加载)
#[test]
fn parse_plugins_distinguishes_disabled_from_unloaded() {
let dir = std::env::temp_dir().join(format!("dsh-watch-disabled-{}", std::process::id()));
@@ -629,32 +637,31 @@ mod tests {
serde_json::to_string_pretty(&manifest).unwrap(),
)
.unwrap();
- for id in ["dsh-loaded", "dsh-disabled", "dsh-unloaded"] {
+ for (id, declares_bundle) in [
+ ("dsh-loaded", true),
+ ("dsh-disabled", true),
+ ("dsh-unloaded", false),
+ ] {
let pkg_dir = dir.join("node_modules").join(id);
std::fs::create_dir_all(&pkg_dir).unwrap();
- std::fs::write(
- pkg_dir.join("package.json"),
- format!(r#"{{"name":"{id}"}}"#),
- )
- .unwrap();
+ let meta = if declares_bundle {
+ serde_json::json!({ "name": id, "version": "1.0.0", "dsh": { "bundle": {} } })
+ } else {
+ serde_json::json!({ "name": id, "version": "1.0.0" })
+ };
+ std::fs::write(pkg_dir.join("package.json"), meta.to_string()).unwrap();
}
- // 仅 dsh-disabled 在 patch 里被禁用。
- std::fs::write(
- dir.join("cordis.patch.yml"),
- "- id: dsh-disabled\n disabled: true\n",
- )
- .unwrap();
let plugins = parse_plugins(&dir, &[]);
let loaded = plugins.iter().find(|p| p.id == "dsh-loaded").unwrap();
assert!(loaded.bundled);
- assert!(!loaded.patch_disabled);
+ assert!(!loaded.disabled);
let disabled_plugin = plugins.iter().find(|p| p.id == "dsh-disabled").unwrap();
assert!(!disabled_plugin.bundled);
- assert!(disabled_plugin.patch_disabled);
+ assert!(disabled_plugin.disabled);
let unloaded = plugins.iter().find(|p| p.id == "dsh-unloaded").unwrap();
assert!(!unloaded.bundled);
- assert!(!unloaded.patch_disabled);
+ assert!(!unloaded.disabled);
std::fs::remove_dir_all(&dir).ok();
}
@@ -684,11 +691,11 @@ mod tests {
.unwrap();
let plugins = parse_plugins(&dir, &presets_for_test());
let market = plugins.iter().find(|p| p.id == "dshmarket").unwrap();
- assert!(market.patch_disabled);
+ assert!(market.disabled);
let pet = plugins.iter().find(|p| p.id == "dsh-tauri-pet").unwrap();
- assert!(!pet.patch_disabled);
+ assert!(!pet.disabled);
let other = plugins.iter().find(|p| p.id == "dsh-other").unwrap();
- assert!(!other.patch_disabled);
+ assert!(!other.disabled);
std::fs::remove_dir_all(&dir).ok();
}
@@ -714,7 +721,69 @@ mod tests {
.iter()
.find(|p| p.id == "dsh-better-sidebar")
.unwrap();
- assert!(sidebar.patch_disabled);
+ assert!(sidebar.disabled);
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ /// 官方 Plugins 页的包级禁用 = 把 bundle 包移出 `dsh.profile.bundles`;
+ /// 桌面插件列表必须显示为已禁用(issue 回归)。
+ #[test]
+ fn parse_plugins_marks_bundle_deselected_as_disabled() {
+ let dir = build_profile(
+ "bundle-deselected",
+ &[(
+ "dshmarket",
+ r#"{"name":"dshmarket","version":"1.13.1","dsh":{"bundle":{}}}"#,
+ )],
+ );
+ let manifest_path = dir.join("package.json");
+ let mut manifest: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap();
+ manifest["dsh"]["profile"]["bundles"] = serde_json::json!([]);
+ std::fs::write(
+ &manifest_path,
+ serde_json::to_string_pretty(&manifest).unwrap(),
+ )
+ .unwrap();
+
+ let plugins = parse_plugins(&dir, &[]);
+ let market = plugins.iter().find(|p| p.id == "dshmarket").unwrap();
+ assert!(!market.bundled);
+ assert!(market.disabled);
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ /// 官方行级开关写入的是 loader entry id(`dsh-market`),不是 npm 包名。
+ #[test]
+ fn parse_plugins_marks_entry_id_patch_disable() {
+ let dir = build_profile(
+ "entry-id",
+ &[(
+ "dshmarket",
+ r#"{"name":"dshmarket","version":"1.13.1","dsh":{"bundle":{"patch":"./cordis.patch.yml"}}}"#,
+ )],
+ );
+ std::fs::write(
+ dir.join("node_modules/dshmarket/cordis.patch.yml"),
+ "- insert:\n - id: dsh-market\n name: dshmarket\n",
+ )
+ .unwrap();
+ std::fs::write(
+ dir.join("cordis.patch.yml"),
+ "- id: dsh-market\n disabled: true\n",
+ )
+ .unwrap();
+
+ let plugins = parse_plugins(&dir, &[]);
+ assert!(
+ plugins
+ .iter()
+ .find(|p| p.id == "dshmarket")
+ .unwrap()
+ .disabled
+ );
std::fs::remove_dir_all(&dir).ok();
}
diff --git a/src/store/modules/plugins/store.ts b/src/store/modules/plugins/store.ts
index 3b7ebc76..5db58833 100644
--- a/src/store/modules/plugins/store.ts
+++ b/src/store/modules/plugins/store.ts
@@ -281,9 +281,9 @@ export const plugins = defineStore({
const installed = this.installedSource.find(item => item.id === process.name || item.name === process.name)
if (!installed)
return process.type === 'uninstall' ? 'already-absent' : 'not-installed'
- if (process.type === 'disable' && installed.patchDisabled)
+ if (process.type === 'disable' && installed.disabled)
return 'already-absent'
- if (process.type === 'enable' && !installed.patchDisabled)
+ if (process.type === 'enable' && !installed.disabled)
return 'already-absent'
return null
},
diff --git a/src/store/modules/plugins/types.ts b/src/store/modules/plugins/types.ts
index b7859a45..0e6a756f 100644
--- a/src/store/modules/plugins/types.ts
+++ b/src/store/modules/plugins/types.ts
@@ -17,7 +17,7 @@ export interface Plugin {
description: string
repoUrl: string
bundled: boolean
- patchDisabled: boolean
+ disabled: boolean
recommended: boolean
fix: boolean
internal: boolean
diff --git a/src/store/modules/plugins/utils.ts b/src/store/modules/plugins/utils.ts
index a9822550..c7c040bc 100644
--- a/src/store/modules/plugins/utils.ts
+++ b/src/store/modules/plugins/utils.ts
@@ -174,7 +174,7 @@ export function enrichInstalled(list: DshPlugin[]): Plugin[] {
description: item.description,
repoUrl: item.repo_url,
bundled: item.bundled,
- patchDisabled: item.patchDisabled,
+ disabled: item.disabled,
recommended: item.recommended,
fix: item.fix,
internal: item.internal,
diff --git a/src/types/plugin.ts b/src/types/plugin.ts
index c2ba2a29..896f5c69 100644
--- a/src/types/plugin.ts
+++ b/src/types/plugin.ts
@@ -21,8 +21,8 @@ export interface DshPlugin {
repo_url: string
/** 是否在 dsh.profile.bundles 中(启动时自动加载) */
bundled: boolean
- /** 是否在 profile 的 cordis.patch.yml 中被禁用(disabled: true),插件开关的唯一状态 */
- patchDisabled: boolean
+ /** 插件开关状态:profile patch 的 disabled 覆盖,或 bundle 包被官方包级开关移出 bundles */
+ disabled: boolean
/** 预设清单中的「推荐」标记 */
recommended: boolean
/** 预设清单中的「修复」标记 */
diff --git a/src/ui/config/plugin.test.tsx b/src/ui/config/plugin.test.tsx
index 0747b7dd..7b61d0d3 100644
--- a/src/ui/config/plugin.test.tsx
+++ b/src/ui/config/plugin.test.tsx
@@ -79,7 +79,7 @@ function plugin(overrides: Partial<Plugin> = {}): Plugin {
id: 'dsh-tauri-pet',
name: 'Desktop Pet',
internal: true,
- patchDisabled: false,
+ disabled: false,
version: '1.0.0',
description: '',
repoUrl: '',
@@ -156,7 +156,7 @@ describe('built-in plugin toggles', () => {
})
it('enables a disabled built-in without showing a disable action', async () => {
- manager.installed = [plugin({ patchDisabled: true })]
+ manager.installed = [plugin({ disabled: true })]
showBuiltIn()
expect(screen.queryByRole('button', { name: 'plugins.disable' })).toBeNull()
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'plugins.enable' })))
diff --git a/src/ui/config/plugin.tsx b/src/ui/config/plugin.tsx
index a6cb7930..e4be8eec 100644
--- a/src/ui/config/plugin.tsx
+++ b/src/ui/config/plugin.tsx
@@ -495,9 +495,8 @@ export function ConfigPlugin() {
{t('plugins.preset')}
</Chip>
</If>
- {/* 禁用态:profile 的 cordis.patch.yml 中的 disabled 覆盖(内置插件同样标注,
- issue #399:Scheduler/Pet 行此前只有「内置」) */}
- <If cond={plugin.patchDisabled}>
+ {/* 禁用态:patch 覆盖或 bundle 包被官方包级开关移出 bundles(issue #399) */}
+ <If cond={plugin.disabled}>
<Chip size="sm" variant="soft" color="default">
{t('plugins.disabled_badge')}
</Chip>
@@ -537,7 +536,7 @@ export function ConfigPlugin() {
</span>
</Chip>
</If>
- <If cond={plugin.patchDisabled}>
+ <If cond={plugin.disabled}>
<Chip
className={actionChip({ busy: rowBusy(plugin.id) })}
variant="primary"
@@ -551,7 +550,7 @@ export function ConfigPlugin() {
</span>
</Chip>
</If>
- <If cond={!plugin.patchDisabled}>
+ <If cond={!plugin.disabled}>
<Chip
className={actionChip({ busy: rowBusy(plugin.id) })}
size="sm"
diff --git a/test/plugin-manager-api.test.ts b/test/plugin-manager-api.test.ts
index 66bb330b..46bf546f 100644
--- a/test/plugin-manager-api.test.ts
+++ b/test/plugin-manager-api.test.ts
@@ -109,7 +109,7 @@ describe('plugins manager idempotency', () => {
description: '',
repo_url: '',
bundled: false,
- patchDisabled: false,
+ disabled: false,
recommended: false,
fix: false,
internal: false,
@@ -135,7 +135,7 @@ describe('plugins manager idempotency', () => {
description: '',
repo_url: '',
bundled: false,
- patchDisabled: false,
+ disabled: false,
recommended: false,
fix: false,
internal: false,
@@ -162,7 +162,7 @@ describe('plugins manager idempotency', () => {
description: '',
repo_url: '',
bundled: false,
- patchDisabled: false,
+ disabled: false,
recommended: false,
fix: false,
internal: false,
@@ -192,7 +192,7 @@ describe('plugins manager idempotency', () => {
description: '',
repo_url: '',
bundled: false,
- patchDisabled: true,
+ disabled: true,
recommended: false,
fix: false,
internal: false,
diff --git a/test/plugin-uninstall.test.ts b/test/plugin-uninstall.test.ts
index dac29a13..2591a47d 100644
--- a/test/plugin-uninstall.test.ts
+++ b/test/plugin-uninstall.test.ts
@@ -76,8 +76,8 @@ describe('configPlugin preset chip', () => {
it('allows internal toggles while withholding uninstall/snapshot', () => {
const source = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')
- expect(source, '禁用入口包含内置插件').toContain('cond={!plugin.patchDisabled}')
- expect(source, '启用入口包含内置插件的禁用态').toContain('cond={plugin.patchDisabled}')
+ expect(source, '禁用入口包含内置插件').toContain('cond={!plugin.disabled}')
+ expect(source, '启用入口包含内置插件的禁用态').toContain('cond={plugin.disabled}')
expect(source, '快照入口由 !plugin.internal 守卫').toContain('<If cond={!plugin.internal}>')
})