DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(06): 插件禁用/启用 — loading-list removal (#246)
CoderStoryb2cee45a1f54
diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rsindex bcdb7fb5..b3d76e5e 100644--- a/src-tauri/src/bridge/plugin.rs+++ b/src-tauri/src/bridge/plugin.rs@@ -176,3 +176,21 @@ pub fn recover_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {plugin::watch::force_emit(&app_handle);Ok(())}++/// 禁用单个已安装插件:从 profile 的 `dsh.profile.bundles` 移除(代码完全不加载),+/// 并写入 profile 的独立禁用清单。与卸载不同,禁用保留 node_modules 内的包体,+/// 启用时无需重新下载。+#[tauri::command]+pub fn disable_dsh_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {+ plugin::disable(&app_handle, &id)?;+ plugin::watch::force_emit(&app_handle);+ Ok(())+}++/// 启用单个已禁用的插件:加回 `dsh.profile.bundles` 并从独立禁用清单移除。+#[tauri::command]+pub fn enable_dsh_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {+ plugin::enable(&app_handle, &id)?;+ plugin::watch::force_emit(&app_handle);+ Ok(())+}diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 5735ded9..bf27d2ba 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -519,6 +519,8 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::refresh_plugin_updates,crate::bridge::update_dsh_plugin,crate::bridge::remove_dsh_plugin,+ crate::bridge::disable_dsh_plugin,+ crate::bridge::enable_dsh_plugin,crate::bridge::report_plugin_error,crate::bridge::detect_plugin_recovery,crate::bridge::recover_plugin,diff --git a/src-tauri/src/service/plugin/disable.rs b/src-tauri/src/service/plugin/disable.rsnew file mode 100644index 00000000..6773e274--- /dev/null+++ b/src-tauri/src/service/plugin/disable.rs@@ -0,0 +1,422 @@+//! 插件禁用/启用:从 profile 的 `dsh.profile.bundles` 移除(代码完全不加载),+//! 并写入 profile 的独立禁用清单。与卸载不同,禁用保留 node_modules 内的包体,+//! 启用时无需重新下载。+//!+//! 机制遵循 ADR-0001:禁用 = 从加载列表移除 + 记入独立禁用清单;启用 = 精确逆操作。++use std::collections::HashMap;+use std::fs;+use std::path::{Path, PathBuf};+use std::time::SystemTime;++use serde::{Deserialize, Serialize};+use tauri::AppHandle;++use crate::service::fs_guard;+use crate::service::plugin::installed::profile_dir;+use crate::service::plugin::{process, watch};++/// 单条禁用记录(序列化为 camelCase 给前端/磁盘)。+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct DisabledEntry {+ /// 禁用时间(unix 秒级时间戳字符串)。+ pub disabled_at: String,+ /// 禁用来源:当前均为 "user"(用户主动操作)。+ pub reason: String,+}++/// 禁用清单在 profile 目录下的路径。+fn disabled_path(profile: &Path) -> PathBuf {+ profile.join("disabled-plugins.json")+}++/// 读取禁用清单(缺失/损坏按空处理)。+pub(crate) fn load_disabled(profile: &Path) -> HashMap<String, DisabledEntry> {+ let Ok(content) = fs::read_to_string(disabled_path(profile)) else {+ return HashMap::new();+ };+ serde_json::from_str(&content).unwrap_or_default()+}++/// 持久化禁用清单(pretty JSON + 尾部换行)。+fn save_disabled(profile: &Path, map: &HashMap<String, DisabledEntry>) -> Result<(), String> {+ let path = disabled_path(profile);+ if let Some(dir) = path.parent() {+ fs::create_dir_all(dir).map_err(|e| format!("DISABLED_DIR_CREATE_FAILED: {e}"))?;+ }+ let json =+ serde_json::to_string_pretty(map).map_err(|e| format!("DISABLED_RENDER_FAILED: {e}"))?;+ fs::write(&path, format!("{json}\n"))+ .map_err(|e| format!("DISABLED_WRITE_FAILED: {e}"))+}++/// 仅从 `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 {+ 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;+ };+ if bundles.iter().any(|b| b.as_str() == Some(id)) {+ return false;+ }+ bundles.push(serde_json::Value::String(id.to_string()));+ 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+ .get("dependencies")+ .and_then(|d| d.as_object())+ .map(|d| d.contains_key(id))+ .unwrap_or(false)+}++fn now_seconds_string() -> String {+ SystemTime::now()+ .duration_since(SystemTime::UNIX_EPOCH)+ .map(|d| d.as_secs().to_string())+ .unwrap_or_default()+}++/// 回滚禁用清单到操作前的状态。+///+/// 当 manifest 写入失败时,把已加入禁用清单的条目移除,使两个持久化文件+/// 恢复一致(插件仍在 bundles 中,禁用清单无记录),避免留下+/// 「已从 bundles 移除但未记入禁用清单」的不可恢复状态。+fn rollback_disable(profile: &Path, id: &str) {+ let mut map = load_disabled(profile);+ map.remove(id);+ // 回滚写入也失败时,只能静默——此时清单多一条目但插件仍在 bundles,+ // 下次禁用会覆盖该条目,不会阻塞用户操作。+ let _ = save_disabled(profile, &map);+}++/// 禁用插件的纯逻辑(不依赖 AppHandle,便于单元测试)。+///+/// 1. `fs_guard::validate_id(id)`(路径穿越防护)+/// 2. 拒绝官方/核心包+/// 3. 读取 profile package.json+/// 4. 校验插件已安装(dependencies 中存在)+/// 5. 先写入禁用清单(加入条目)+/// 6. 仅从 bundles 移除(不动 dependencies)并写回 manifest+///+/// 写入顺序保证:若步骤 6 失败,通过回滚步骤 5 使两文件恢复一致,+/// 避免插件从 bundles 移除却未记入禁用清单(否则启用会返回+/// `ENABLE_NOT_DISABLED`,用户无法通过正常流程恢复)。+pub(crate) fn disable_plugin_at(profile: &Path, id: &str) -> Result<(), String> {+ // 先做官方/核心包语义校验(优先级高于字符集校验):官方包 id 含 `/`,+ // 必须先于 validate_id 拦截,否则会被字符集校验误判为 INVALID_ID。+ if is_core_package(id) {+ return Err(format!(+ "DISABLE_INTERNAL_PLUGIN: refusing to disable internal/official plugin {id}"+ ));+ }+ fs_guard::validate_id(id)?;+ let manifest_path = profile.join("package.json");+ let content = fs::read_to_string(&manifest_path)+ .map_err(|e| format!("DISABLE_READ_MANIFEST: {e}"))?;+ let mut manifest: serde_json::Value = serde_json::from_str(&content)+ .map_err(|e| format!("DISABLE_PARSE_MANIFEST: {e}"))?;+ if !is_in_dependencies(&manifest, id) {+ return Err(format!(+ "DISABLE_NOT_INSTALLED: plugin {id} is not installed"+ ));+ }+ // 先写禁用清单,确保 manifest 写入失败时可回滚该条目。+ let mut map = load_disabled(profile);+ map.insert(+ id.to_string(),+ DisabledEntry {+ disabled_at: now_seconds_string(),+ reason: "user".to_string(),+ },+ );+ save_disabled(profile, &map)?;+ remove_from_bundles(&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")) {+ rollback_disable(profile, id);+ return Err(format!("DISABLE_WRITE_MANIFEST: {e}"));+ }+ Ok(())+}++/// 回滚启用前的禁用清单状态。+///+/// 当 manifest 写入失败时,把已移除的禁用条目加回,使两个持久化文件+/// 恢复一致(插件仍在禁用清单中,bundles 未记录),避免留下+/// 「已加回 bundles 但禁用清单仍缺条目」的不可恢复状态。+fn rollback_enable(profile: &Path, id: &str) {+ let mut map = load_disabled(profile);+ map.entry(id.to_string()).or_insert_with(|| DisabledEntry {+ disabled_at: now_seconds_string(),+ reason: "user".to_string(),+ });+ let _ = save_disabled(profile, &map);+}++/// 启用插件的纯逻辑(不依赖 AppHandle,便于单元测试)。+///+/// 1. `fs_guard::validate_id(id)`+/// 2. 读取 manifest+/// 3. 校验插件仍安装+/// 4. 校验插件在禁用清单中+/// 5. 先从禁用清单移除条目+/// 6. 加回 bundles 并写回 manifest+///+/// 写入顺序保证:若步骤 6 失败,通过回滚步骤 5 使两文件恢复一致,+/// 避免插件加回 bundles 后禁用清单缺条目(否则再次启用会返回+/// `ENABLE_NOT_DISABLED`,用户无法通过正常流程恢复)。+pub(crate) fn enable_plugin_at(profile: &Path, id: &str) -> Result<(), String> {+ fs_guard::validate_id(id)?;+ let manifest_path = profile.join("package.json");+ let content = fs::read_to_string(&manifest_path)+ .map_err(|e| format!("ENABLE_READ_MANIFEST: {e}"))?;+ let mut manifest: serde_json::Value = serde_json::from_str(&content)+ .map_err(|e| format!("ENABLE_PARSE_MANIFEST: {e}"))?;+ if !is_in_dependencies(&manifest, id) {+ return Err(format!(+ "ENABLE_NOT_INSTALLED: plugin {id} is not installed"+ ));+ }+ let mut map = load_disabled(profile);+ if !map.contains_key(id) {+ return Err(format!(+ "ENABLE_NOT_DISABLED: plugin {id} is not in the disabled list"+ ));+ }+ // 先从禁用清单移除,确保 manifest 写入失败时可回滚该条目。+ map.remove(id);+ save_disabled(profile, &map)?;+ add_to_bundles(&mut manifest, id);+ let rendered = serde_json::to_string_pretty(&manifest)+ .map_err(|e| format!("ENABLE_RENDER_MANIFEST: {e}"))?;+ if let Err(e) = fs::write(&manifest_path, format!("{rendered}\n")) {+ rollback_enable(profile, id);+ return Err(format!("ENABLE_WRITE_MANIFEST: {e}"));+ }+ Ok(())+}++/// 禁用插件(AppHandle 入口):获取 profile 目录 → 持有操作锁 → 执行纯逻辑 → 推送变更。+pub fn disable(app_handle: &AppHandle, id: &str) -> Result<(), String> {+ let profile = profile_dir(app_handle);+ let _guard = tauri::async_runtime::block_on(process::acquire_operation_lock());+ let result = disable_plugin_at(&profile, id);+ drop(_guard);+ watch::force_emit(app_handle);+ result+}++/// 启用插件(AppHandle 入口):获取 profile 目录 → 持有操作锁 → 执行纯逻辑 → 推送变更。+pub fn enable(app_handle: &AppHandle, id: &str) -> Result<(), String> {+ let profile = profile_dir(app_handle);+ let _guard = tauri::async_runtime::block_on(process::acquire_operation_lock());+ let result = enable_plugin_at(&profile, id);+ drop(_guard);+ watch::force_emit(app_handle);+ result+}++#[cfg(test)]+mod tests {+ use super::*;++ /// 构造临时 profile 目录并写入 package.json 清单。+ fn build_profile(test_name: &str, id: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "dsh-disable-test-{}-{}-{}",+ test_name,+ std::process::id(),+ id+ ));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();+ let manifest = serde_json::json!({+ "name": "dsh-profile-web",+ "private": true,+ "dependencies": {+ "dsh-better-sidebar": "1.0.0",+ "dshmarket": "2.0.0",+ "@deepseek-ai/dsh-base": "1.0.0"+ },+ "dsh": { "profile": { "bundles": ["dsh-better-sidebar", "dshmarket", "@deepseek-ai/dsh-base"] } }+ });+ fs::write(+ dir.join("package.json"),+ serde_json::to_string_pretty(&manifest).unwrap(),+ )+ .unwrap();+ dir+ }++ fn read_manifest(profile: &Path) -> serde_json::Value {+ let content = fs::read_to_string(profile.join("package.json")).unwrap();+ serde_json::from_str(&content).unwrap()+ }++ #[test]+ fn disable_removes_from_bundles_only() {+ let profile = build_profile("bundles-only", "a");+ disable_plugin_at(&profile, "dsh-better-sidebar").unwrap();++ let manifest = read_manifest(&profile);+ // dependencies 不变+ assert!(manifest["dependencies"]["dsh-better-sidebar"].is_string());+ assert!(manifest["dependencies"]["dshmarket"].is_string());+ // bundles 中已移除+ let bundles = manifest["dsh"]["profile"]["bundles"].as_array().unwrap();+ assert!(!bundles.iter().any(|b| b.as_str() == Some("dsh-better-sidebar")));+ assert!(bundles.iter().any(|b| b.as_str() == Some("dshmarket")));++ let _ = fs::remove_dir_all(&profile);+ }++ #[test]+ fn disable_writes_disabled_json() {+ let profile = build_profile("disabled-json", "b");+ disable_plugin_at(&profile, "dsh-better-sidebar").unwrap();++ let map = load_disabled(&profile);+ let entry = map.get("dsh-better-sidebar").expect("disabled entry exists");+ assert_eq!(entry.reason, "user");+ assert!(!entry.disabled_at.is_empty());+ // 时间戳是纯数字字符串+ assert!(entry.disabled_at.parse::<u64>().is_ok());++ let _ = fs::remove_dir_all(&profile);+ }++ #[test]+ fn enable_restores_to_bundles() {+ let profile = build_profile("enable-restore", "c");+ disable_plugin_at(&profile, "dsh-better-sidebar").unwrap();+ enable_plugin_at(&profile, "dsh-better-sidebar").unwrap();++ let manifest = read_manifest(&profile);+ let bundles = manifest["dsh"]["profile"]["bundles"].as_array().unwrap();+ assert!(bundles.iter().any(|b| b.as_str() == Some("dsh-better-sidebar")));++ let _ = fs::remove_dir_all(&profile);+ }++ #[test]+ fn enable_removes_from_disabled_json() {+ let profile = build_profile("enable-rm-json", "d");+ disable_plugin_at(&profile, "dsh-better-sidebar").unwrap();+ enable_plugin_at(&profile, "dsh-better-sidebar").unwrap();++ let map = load_disabled(&profile);+ assert!(!map.contains_key("dsh-better-sidebar"));++ let _ = fs::remove_dir_all(&profile);+ }++ #[test]+ fn disable_internal_plugin_is_rejected() {+ let profile = build_profile("internal-reject", "e");+ let err = disable_plugin_at(&profile, "@deepseek-ai/dsh-base").unwrap_err();+ assert!(err.contains("DISABLE_INTERNAL_PLUGIN"));++ // manifest 未被修改+ let manifest = read_manifest(&profile);+ let bundles = manifest["dsh"]["profile"]["bundles"].as_array().unwrap();+ assert_eq!(bundles.len(), 3);++ let _ = fs::remove_dir_all(&profile);+ }++ #[test]+ fn disable_not_installed_is_rejected() {+ let profile = build_profile("not-installed", "f");+ let err = disable_plugin_at(&profile, "dsh-not-exist").unwrap_err();+ assert!(err.contains("DISABLE_NOT_INSTALLED"));++ let _ = fs::remove_dir_all(&profile);+ }++ #[test]+ fn enable_not_disabled_is_rejected() {+ let profile = build_profile("not-disabled", "g");+ // 未禁用就启用 → 拒绝+ let err = enable_plugin_at(&profile, "dsh-better-sidebar").unwrap_err();+ assert!(err.contains("ENABLE_NOT_DISABLED"));++ let _ = fs::remove_dir_all(&profile);+ }++ #[test]+ fn round_trip_preserves_other_bundles() {+ let profile = build_profile("round-trip", "h");+ disable_plugin_at(&profile, "dsh-better-sidebar").unwrap();+ enable_plugin_at(&profile, "dsh-better-sidebar").unwrap();++ let manifest = read_manifest(&profile);+ let bundles = manifest["dsh"]["profile"]["bundles"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|b| b.as_str())+ .collect::<Vec<_>>();+ // 恢复原始顺序可能不同,但内容一致+ assert_eq!(bundles.len(), 3);+ assert!(bundles.contains(&"dsh-better-sidebar"));+ assert!(bundles.contains(&"dshmarket"));+ assert!(bundles.contains(&"@deepseek-ai/dsh-base"));+ // dependencies 完全不变+ assert!(manifest["dependencies"]["dsh-better-sidebar"].is_string());+ assert!(manifest["dependencies"]["dshmarket"].is_string());+ assert!(manifest["dependencies"]["@deepseek-ai/dsh-base"].is_string());++ let _ = fs::remove_dir_all(&profile);+ }++ #[test]+ fn disabled_list_persists_to_disk() {+ let profile = build_profile("persist", "i");+ disable_plugin_at(&profile, "dsh-better-sidebar").unwrap();++ // 重新从磁盘读取(不依赖内存)+ let map = load_disabled(&profile);+ assert!(map.contains_key("dsh-better-sidebar"));++ // 文件确实存在且可解析+ let path = disabled_path(&profile);+ assert!(path.exists());+ let content = fs::read_to_string(&path).unwrap();+ assert!(content.contains("dsh-better-sidebar"));+ assert!(content.contains("\"disabledAt\""));+ assert!(content.contains("\"reason\""));++ let _ = fs::remove_dir_all(&profile);+ }+}diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex e8dfe8d3..d36ac3e4 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -28,6 +28,7 @@//! - [`watch`]:已安装插件文件监控(轮询指纹比对 + `dsh-plugins-updated` 事件推送)mod cancel;+pub mod disable;pub mod errors;mod install;mod installed;@@ -50,6 +51,7 @@ pub(crate) use internal::cancel as cancel_internal_plugins;pub(crate) use internal::ensure as ensure_internal_plugins;pub use preset::repo_url_of;pub(crate) use preset::{current_preset_hash, preinstall_pending, remove_legacy_bundled_plugins};+pub use disable::{disable, enable};pub use recovery::{detect as detect_recovery, uninstall as uninstall_recovery, PluginRecoveryInfo,};diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rsindex 4f87f7fa..72b3196a 100644--- a/src-tauri/src/service/plugin/watch.rs+++ b/src-tauri/src/service/plugin/watch.rs@@ -44,6 +44,12 @@ pub struct DshPlugin {pub repo_url: String,/// 是否在 `dsh.profile.bundles` 中(启动时自动加载)pub bundled: bool,+ /// 是否在禁用清单(`disabled-plugins.json`)中。+ ///+ /// 与 `bundled` 独立:已安装但不在 `bundles` 中的插件,仅当同时存在于+ /// 禁用清单时才视为「已禁用」;否则为「未加载」(用户未主动禁用,+ /// 启用操作会返回 `ENABLE_NOT_DISABLED`,前端不应展示启用入口)。+ pub disabled: bool,/// 预设清单中的「推荐」标记(绿色 chip)pub recommended: bool,/// 预设清单中的「修复」标记(黄色 chip)@@ -145,6 +151,10 @@ fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPlu.map(|p| installed_name(p).to_string()).collect();+ // 禁用清单:用于区分「已禁用」(用户主动禁用)与「未加载」(不在 bundles+ // 但也不在禁用清单,启用会返回 ENABLE_NOT_DISABLED)。+ let disabled_map = crate::service::plugin::disable::load_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,6 +192,7 @@ fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPlu.unwrap_or_default(),repo_url,bundled: bundled.contains(id.as_str()),+ disabled: disabled_map.contains_key(id),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()),@@ -470,6 +481,7 @@ mod tests {description: String::new(),repo_url: String::new(),bundled: true,+ disabled: false,recommended: false,fix: false,internal: false,@@ -500,6 +512,7 @@ mod tests {description: String::new(),repo_url: String::new(),bundled: true,+ disabled: false,recommended: false,fix: false,internal: false,@@ -543,4 +556,60 @@ mod tests {assert!(parse_plugins(&dir, &[]).is_empty());std::fs::remove_dir_all(&dir).ok();}++ /// 覆盖 `disabled` 字段的状态组合:+ /// - 在 bundles 且不在禁用清单 → bundled=true, disabled=false(正常加载)+ /// - 不在 bundles 但在禁用清单 → bundled=false, disabled=true(已禁用,可启用)+ /// - 不在 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()+ ));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir.join("node_modules")).unwrap();+ let manifest = serde_json::json!({+ "name": "dsh-profile-web",+ "private": true,+ "dependencies": {+ "dsh-loaded": "1.0.0",+ "dsh-disabled": "1.0.0",+ "dsh-unloaded": "1.0.0"+ },+ "dsh": { "profile": { "bundles": ["dsh-loaded"] } }+ });+ std::fs::write(+ dir.join("package.json"),+ serde_json::to_string_pretty(&manifest).unwrap(),+ )+ .unwrap();+ for id in ["dsh-loaded", "dsh-disabled", "dsh-unloaded"] {+ 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();+ }+ // 仅 dsh-disabled 写入禁用清单。+ let disabled = serde_json::json!({+ "dsh-disabled": { "disabledAt": "1700000000", "reason": "user" }+ });+ std::fs::write(+ dir.join("disabled-plugins.json"),+ serde_json::to_string_pretty(&disabled).unwrap(),+ )+ .unwrap();++ let plugins = parse_plugins(&dir, &[]);+ let loaded = plugins.iter().find(|p| p.id == "dsh-loaded").unwrap();+ assert!(loaded.bundled);+ assert!(!loaded.disabled);+ let disabled_plugin = plugins.iter().find(|p| p.id == "dsh-disabled").unwrap();+ assert!(!disabled_plugin.bundled);+ assert!(disabled_plugin.disabled);+ let unloaded = plugins.iter().find(|p| p.id == "dsh-unloaded").unwrap();+ assert!(!unloaded.bundled);+ assert!(!unloaded.disabled);++ std::fs::remove_dir_all(&dir).ok();+ }}diff --git a/src/components/config-plugin.tsx b/src/components/config-plugin.tsxindex 84ea89ff..80c95c91 100644--- a/src/components/config-plugin.tsx+++ b/src/components/config-plugin.tsx@@ -6,6 +6,7 @@ import { invoke } from '@tauri-apps/api/core'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { If } from 'react-if-lite'+import { tv } from 'tailwind-variants'import { useStore } from 'valtio-define'import { store } from '@/store'import { toast } from '@/utils/toast'@@ -17,6 +18,23 @@ import { Modal } from './modal'import { PanelHeader } from './panel-header'import { PanelState } from './panel-state'+/**+ * 操作 chip 的样式变体:busy 时禁止点击并降低透明度,否则可点击。+ * 统一各操作 chip 的 busy 样式,避免内联三元重复。+ */+const actionChip = tv({+ base: 'rounded-md',+ variants: {+ busy: {+ true: 'cursor-not-allowed opacity-50',+ false: 'cursor-pointer',+ },+ },+ defaultVariants: {+ busy: false,+ },+})+/*** 「插件」面板:展示已安装插件,作为「插件出问题时」的卸载/升级入口。*@@ -31,13 +49,13 @@ import { PanelState } from './panel-state'export function ConfigPlugin() {const { t } = useTranslation()const queryClient = useQueryClient()- const { plugins, loading, error } = useDshPlugins()+ const { plugins, loading, error, disablePlugin, enablePlugin } = useDshPlugins()const { preinstall } = useStore(store.harness)const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })- /** 行内操作进行中状态:id + 操作类型(update/remove),保证单例运行 */- const [busy, setBusy] = useState<{ id: string, action: 'update' | 'remove' } | null>(null)+ /** 行内操作进行中状态:id + 操作类型(update/remove/disable/enable),保证单例运行 */+ const [busy, setBusy] = useState<{ id: string, action: 'update' | 'remove' | 'disable' | 'enable' } | null>(null)const upgrade = useMutation({mutationFn: (id: string) => invoke<void>('update_dsh_plugin', { id }),@@ -68,6 +86,32 @@ export function ConfigPlugin() {toast(t('plugins.remove_failed', { name }), {})},})+ const disable = useMutation({+ mutationFn: (id: string) => disablePlugin(id),+ onSuccess: (_data, id) => {+ const name = plugins.find(p => p.id === id)?.name ?? id+ void queryClient.invalidateQueries({ queryKey: ['plugins'] })+ toast(t('plugins.disable_toast', { name }), {})+ },+ onError: (err, id) => {+ const name = plugins.find(p => p.id === id)?.name ?? id+ console.error('[ConfigPlugin] disable failed:', err)+ toast(t('plugins.disable_failed', { name }), {})+ },+ })+ const enable = useMutation({+ mutationFn: (id: string) => enablePlugin(id),+ onSuccess: (_data, id) => {+ const name = plugins.find(p => p.id === id)?.name ?? id+ void queryClient.invalidateQueries({ queryKey: ['plugins'] })+ toast(t('plugins.enable_toast', { name }), {})+ },+ onError: (err, id) => {+ const name = plugins.find(p => p.id === id)?.name ?? id+ console.error('[ConfigPlugin] enable failed:', err)+ toast(t('plugins.enable_failed', { name }), {})+ },+ })async function onUpgrade(id: string) {if (busy)@@ -119,6 +163,41 @@ export function ConfigPlugin() {}}+ async function onDisable(id: string) {+ if (busy)+ return+ // 禁用是可逆操作(保留包体,启用即可恢复),无需确认对话框。+ setBusy({ id, action: 'disable' })+ try {+ await disable.mutateAsync(id)+ }+ catch {+ // 错误提示已由 mutation 的 onError 处理+ }+ finally {+ setBusy(null)+ // 禁用后统一拉起服务,使新的 bundles 列表生效。+ void store.harness.restart()+ }+ }++ async function onEnable(id: string) {+ if (busy)+ return+ setBusy({ id, action: 'enable' })+ try {+ await enable.mutateAsync(id)+ }+ catch {+ // 错误提示已由 mutation 的 onError 处理+ }+ finally {+ setBusy(null)+ // 启用后统一拉起服务,使新的 bundles 列表生效。+ void store.harness.restart()+ }+ }+return (<div><PanelHeader@@ -199,6 +278,11 @@ export function ConfigPlugin() {{t('plugins.builtin')}</code></If>+ <If cond={plugin.disabled}>+ <Chip size="sm" variant="soft" color="default">+ {t('plugins.disabled_badge')}+ </Chip>+ </If></div><If cond={plugin.description !== ''}><TextEllipsis lineClamp={2} className="text-xs text-muted">@@ -213,7 +297,7 @@ export function ConfigPlugin() {与文档 P1「对 dshmarket 点击升级」一致,且不会常驻——up-to-date 插件不显示升级按钮 */}<If cond={plugin.updateAvailable || plugin.error != null}><Chip- className={`rounded-md${busy ? ' cursor-not-allowed opacity-50' : ' cursor-pointer'}`}+ className={actionChip({ busy: !!busy })}variant="primary"color="accent"size="sm"@@ -230,8 +314,34 @@ export function ConfigPlugin() {</Chip></If><If cond={!plugin.internal}>+ <If cond={plugin.disabled}>+ <Chip+ className={actionChip({ busy: !!busy })}+ variant="primary"+ color="accent"+ size="sm"+ onClick={() => onEnable(plugin.id)}+ >+ <span className="flex items-center gap-1">+ <If cond={busy?.id === plugin.id && busy.action === 'enable'} then={<Spinner size="sm" color="current" />} />+ {t('plugins.enable')}+ </span>+ </Chip>+ </If>+ <If cond={!plugin.disabled}>+ <Chip+ className={actionChip({ busy: !!busy })}+ size="sm"+ onClick={() => onDisable(plugin.id)}+ >+ <span className="flex items-center gap-1">+ <If cond={busy?.id === plugin.id && busy.action === 'disable'} then={<Spinner size="sm" color="current" />} />+ {t('plugins.disable')}+ </span>+ </Chip>+ </If><Chip- className={`rounded-md${busy ? ' cursor-not-allowed opacity-50' : ' cursor-pointer'}`}+ className={actionChip({ busy: !!busy })}variant="primary"color="danger"size="sm"diff --git a/src/components/item.tsx b/src/components/item.tsxindex bd394e9b..6448d58f 100644--- a/src/components/item.tsx+++ b/src/components/item.tsx@@ -27,7 +27,7 @@ export function Item({ left, right, footer, onClick, className }: ItemProps) {onClick={onClick}><Card.Content className="flex flex-col gap-1.5">- <div className="flex flex-row items-center justify-between">+ <div className="flex flex-row items-center justify-between gap-2"><div className="flex min-w-0 items-center gap-1">{left}</div><div className="flex shrink-0 items-center gap-1.5">{right}</div></div>diff --git a/src/hooks/use-dsh-plugins.ts b/src/hooks/use-dsh-plugins.tsindex d9b9a945..6786aca4 100644--- a/src/hooks/use-dsh-plugins.ts+++ b/src/hooks/use-dsh-plugins.ts@@ -28,6 +28,8 @@ export interface DshPlugin {repo_url: string/** 是否在 dsh.profile.bundles 中(启动时自动加载) */bundled: boolean+ /** 是否在禁用清单(disabled-plugins.json)中,独立于 bundled */+ disabled: boolean/** 预设清单中的「推荐」标记 */recommended: boolean/** 预设清单中的「修复」标记 */@@ -48,6 +50,10 @@ export interface UseDshPluginsResult {error: string/** 手动重新拉取(Rust 侧也会在插件文件变化时实时推送) */refresh: () => Promise<void>+ /** 禁用指定插件(从 dsh.profile.bundles 移除,保留包体) */+ disablePlugin: (id: string) => Promise<void>+ /** 启用指定插件(加回 dsh.profile.bundles) */+ enablePlugin: (id: string) => Promise<void>}/**@@ -111,12 +117,23 @@ export function useDshPlugins(): UseDshPluginsResult {}}, [queryClient])+ function disablePlugin(id: string) {+ return invoke<void>('disable_dsh_plugin', { id })+ }+ function enablePlugin(id: string) {+ return invoke<void>('enable_dsh_plugin', { id })+ }++ async function refresh() {+ await refetch()+ }+return {plugins: data ?? [],loading: isLoading,error: error ? String(error) : '',- refresh: async () => {- await refetch()- },+ refresh,+ disablePlugin,+ enablePlugin,}}diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex 91838778..becae124 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -168,6 +168,13 @@"plugins.upgrade_failed": "Failed to upgrade {{name}}","plugins.updated_toast": "Plugin {{name}} updated","plugins.removed_toast": "Plugin {{name}} uninstalled",+ "plugins.disable": "Disable",+ "plugins.enable": "Enable",+ "plugins.disabled_badge": "Disabled",+ "plugins.disable_toast": "Plugin {{name}} disabled",+ "plugins.disable_failed": "Failed to disable {{name}}",+ "plugins.enable_toast": "Plugin {{name}} enabled",+ "plugins.enable_failed": "Failed to enable {{name}}","core.title": "Harness Core","core.refresh": "Refresh","core.refreshed_toast": "Core list refreshed",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex ad02a205..1c26ae9f 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -168,6 +168,13 @@"plugins.upgrade_failed": "升级插件 {{name}} 失败","plugins.updated_toast": "插件 {{name}} 已更新","plugins.removed_toast": "插件 {{name}} 已卸载",+ "plugins.disable": "禁用",+ "plugins.enable": "启用",+ "plugins.disabled_badge": "已禁用",+ "plugins.disable_toast": "插件 {{name}} 已禁用",+ "plugins.disable_failed": "禁用插件 {{name}} 失败",+ "plugins.enable_toast": "插件 {{name}} 已启用",+ "plugins.enable_failed": "启用插件 {{name}} 失败","core.title": "核心引擎","core.refresh": "刷新","core.refreshed_toast": "核心列表已刷新",diff --git a/test/plugin-disable.test.ts b/test/plugin-disable.test.tsnew file mode 100644index 00000000..abfbec1e--- /dev/null+++ b/test/plugin-disable.test.ts@@ -0,0 +1,90 @@+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'++describe('plugin disable/enable frontend contract', () => {+ it('config-plugin.tsx defines onDisable and onEnable handlers', () => {+ const source = readFileSync(new URL('../src/components/config-plugin.tsx', import.meta.url), 'utf8')++ expect(source).toContain('onDisable')+ expect(source).toContain('onEnable')+ })++ it('config-plugin.tsx consumes the disable/enable hook helpers', () => {+ const source = readFileSync(new URL('../src/components/config-plugin.tsx', import.meta.url), 'utf8')++ // 组件通过 hook 暴露的 disablePlugin/enablePlugin 调用(命令名在 hook 文件内),+ // 与 upgrade/remove 直接 invoke 的模式一致地封装到可复用 helper。+ expect(source).toContain('disablePlugin(')+ expect(source).toContain('enablePlugin(')+ })++ it('disable button uses a neutral variant (tertiary), distinct from the danger Uninstall', () => {+ const source = readFileSync(new URL('../src/components/config-plugin.tsx', import.meta.url), 'utf8')++ // 禁用不是破坏性操作:用 tertiary(中性),区别于卸载的 color="danger"。+ // HeroUI Chip 在当前版本不支持 "bordered",故以 tertiary 替代。+ expect(source).toContain('variant="tertiary"')+ expect(source).not.toContain('variant="bordered"')+ })++ it('config-plugin.tsx renders a Disabled badge via plugins.disabled_badge', () => {+ const source = readFileSync(new URL('../src/components/config-plugin.tsx', import.meta.url), 'utf8')++ expect(source).toContain('plugins.disabled_badge')+ })++ it('config-plugin.tsx extends the busy state union with disable + enable', () => {+ const source = readFileSync(new URL('../src/components/config-plugin.tsx', import.meta.url), 'utf8')++ expect(source).toContain('\'update\' | \'remove\' | \'disable\' | \'enable\'')+ })++ it('config-plugin.tsx does NOT open a confirmation dialog for disable (reversible action)', () => {+ const source = readFileSync(new URL('../src/components/config-plugin.tsx', import.meta.url), 'utf8')++ // onDisable must not call openDialog — the disable handler is a direct action,+ // unlike onRemove which confirms via openDialog. We assert the onDisable block+ // contains no openDialog invocation.+ const onDisableMatch = source.match(/async function onDisable[\s\S]*?\n {2}\}/)+ expect(onDisableMatch).not.toBeNull()+ expect(onDisableMatch![0]).not.toContain('openDialog')+ })++ it('use-dsh-plugins.ts exposes disable_dsh_plugin and enable_dsh_plugin invoke calls', () => {+ const source = readFileSync(new URL('../src/hooks/use-dsh-plugins.ts', import.meta.url), 'utf8')++ expect(source).toContain('disable_dsh_plugin')+ expect(source).toContain('enable_dsh_plugin')+ })++ it('en-US.json contains all 7 disable/enable i18n keys', () => {+ const source = readFileSync(new URL('../src/i18n/locales/en-US.json', import.meta.url), 'utf8')++ expect(source).toContain('"plugins.disable"')+ expect(source).toContain('"plugins.enable"')+ expect(source).toContain('"plugins.disabled_badge"')+ expect(source).toContain('"plugins.disable_toast"')+ expect(source).toContain('"plugins.disable_failed"')+ expect(source).toContain('"plugins.enable_toast"')+ expect(source).toContain('"plugins.enable_failed"')+ })++ it('zh-CN.json contains all 7 disable/enable i18n keys', () => {+ const source = readFileSync(new URL('../src/i18n/locales/zh-CN.json', import.meta.url), 'utf8')++ expect(source).toContain('"plugins.disable"')+ expect(source).toContain('"plugins.enable"')+ expect(source).toContain('"plugins.disabled_badge"')+ expect(source).toContain('"plugins.disable_toast"')+ expect(source).toContain('"plugins.disable_failed"')+ expect(source).toContain('"plugins.enable_toast"')+ expect(source).toContain('"plugins.enable_failed"')+ })++ it('config-plugin.tsx stays within shell conventions (no useCallback/useMemo)', () => {+ const source = readFileSync(new URL('../src/components/config-plugin.tsx', import.meta.url), 'utf8')++ expect(source).not.toContain('useCallback')+ expect(source).not.toContain('useMemo')+ })+})