Skip to content

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

feat(plugin): add plugin recovery detection and repair flow

hairyf7aef77b381d2
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 2ef01ef4..c06f317b 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -821,6 +821,7 @@ dependencies = [
"futures-util",
"image",
"log",
+ "regex",
"reqwest 0.12.28",
"rfd",
"semver",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index a45380ee..085b3ce1 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -35,6 +35,7 @@ image = { version = "0.25", default-features = false, features = [ "png" ] }
serde = { version = "1", features = [ "derive" ] }
serde_json = "1"
serde_yaml = "0.9"
+regex = "1"
sha2 = "0.10"
log = "0.4"
tracing = "0.1"
diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rs
index 070e1d05..ab551a1f 100644
--- a/src-tauri/src/bridge/plugin.rs
+++ b/src-tauri/src/bridge/plugin.rs
@@ -95,7 +95,8 @@ pub async fn remove_dsh_plugin(app_handle: AppHandle, id: String) -> Result<(),
Ok(())
}
-/// 上报插件运行期异常(内嵌页面 / dsh-tauri 桥调用),记录后立即推送新列表。
+/// 上报插件运行期异常(内嵌页面 / dsh-tauri 桥调用),记录后立即推送新列表,
+/// 并推送 `plugin-recovery-required` 让前端弹出「卸除此插件并继续检测」修复界面。
#[tauri::command]
pub fn report_plugin_error(
app_handle: AppHandle,
@@ -105,5 +106,36 @@ pub fn report_plugin_error(
) -> Result<(), String> {
plugin::errors::record(&app_handle, &id, action.as_deref().unwrap_or("runtime"), &error)?;
plugin::watch::force_emit(&app_handle);
+ // 运行期异常:直接推送修复界面(应用仍在运行,前端以醒目对话框呈现)。
+ let info = plugin::PluginRecoveryInfo {
+ plugins: vec![id],
+ reason: "runtime".to_string(),
+ detail: String::new(),
+ raw_error: error,
+ };
+ let _ = app_handle.emit(plugin::recovery::RECOVERY_REQUIRED_EVENT, &info);
+ Ok(())
+}
+
+/// 从启动日志定位导致启动失败的问题插件(含归属到配置根插件)。
+///
+/// 前端在启动失败时已读过服务日志(`read_service_logs`),这里直接传入日志行,
+/// 由 Rust 侧按错误特征提取引用并做证据式归属;未定位到具体插件时 `plugins` 为空。
+#[tauri::command]
+pub fn detect_plugin_recovery(
+ app_handle: AppHandle,
+ logs: Vec<String>,
+) -> plugin::PluginRecoveryInfo {
+ plugin::detect_recovery(&app_handle, &logs)
+}
+
+/// 修复模式卸载单个插件:直接改 profile 清单(离线、精准),成功后推送新插件列表。
+///
+/// 与 `remove_dsh_plugin`(走 `dsh plugin remove`)不同,此命令不依赖网络,专用于
+/// 「插件异常修复」场景;前端随后 `restart()` 重启并重新检测。
+#[tauri::command]
+pub fn recover_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {
+ plugin::uninstall_recovery(&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.rs
index 3bb69f93..b611d4b5 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -202,6 +202,8 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::update_dsh_plugin,
crate::bridge::remove_dsh_plugin,
crate::bridge::report_plugin_error,
+ crate::bridge::detect_plugin_recovery,
+ crate::bridge::recover_plugin,
crate::bridge::get_profiles,
crate::bridge::create_profile,
crate::bridge::set_active_profile,
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index b78ad23a..56e71d62 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -29,6 +29,7 @@ mod install;
mod installed;
mod preset;
mod process;
+pub mod recovery;
pub mod watch;
pub use cancel::cancel;
@@ -37,4 +38,5 @@ pub use installed::{list, PreinstallPlugin};
pub(crate) use installed::ensure_profile_npmrc;
pub use preset::repo_url_of;
pub(crate) use preset::{current_preset_hash, preinstall_pending};
+pub use recovery::{detect as detect_recovery, uninstall as uninstall_recovery, PluginRecoveryInfo};
pub use watch::DshPlugin;
\ No newline at end of file
diff --git a/src-tauri/src/service/plugin/recovery.rs b/src-tauri/src/service/plugin/recovery.rs
new file mode 100644
index 00000000..bf8dfc05
--- /dev/null
+++ b/src-tauri/src/service/plugin/recovery.rs
@@ -0,0 +1,681 @@
+//! 插件异常修复(recovery):启动失败 / 运行期异常时定位问题插件,并提供
+//! 「卸除此插件并继续检测」的一键离线修复。
+//!
+//! 参考 dataelement/dsh-desktop 的插件异常修复模式(PR #94/#96):
+//! - **定位**:从启动日志按错误特征提取插件引用(duplicate route / loader entry /
+//! cannot resolve bundle / no dsh.bundle / slot conflict / failed to import),再
+//! 按 profile `package.json` + `node_modules` 归属回配置的根插件——只有拿到确凿
+//! 证据才动手,绝不瞎猜。
+//! - **卸载**:直接改 profile 清单(`dependencies` + `dsh.profile.bundles`)、删除
+//! `node_modules/<id>`、剥离 `cordis.patch.yml` 中该插件的补丁层、清掉
+//! `pnpm-lock.yaml`(best-effort),保留其它插件与配置。与 [`super::install`] 走
+//! `dsh plugin` 子进程不同:本模块离线、精准,不需要网络。
+//!
+//! 卸载成功后由前端 `restart()` 重启并重新检测;若仍有问题,启动失败再次触发
+//! 定位,形成「继续检测」循环。
+
+use regex::Regex;
+use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
+use std::fs;
+use std::path::Path;
+use tauri::AppHandle;
+
+use super::errors;
+use super::installed::profile_dir;
+
+/// 前端监听的事件名:需要弹出插件异常修复界面时推送。
+pub(crate) const RECOVERY_REQUIRED_EVENT: &str = "plugin-recovery-required";
+
+/// 核心 bundle / 官方包:无论如何不可被「修复卸载」删除。
+fn is_core_package(name: &str) -> bool {
+ name == "dshmarket"
+ || name == "@deepseek-ai/dsh-base"
+ || name == "@deepseek-ai/dsh-web-app"
+ || name.starts_with("@deepseek-ai/")
+}
+
+/// 是否为合法的 npm 包名(可带 scope)。用于过滤日志里提取到的候选引用。
+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;
+ }
+ let body = s.strip_prefix('@').unwrap_or(s);
+ // scoped 必须带 `/`(@scope/name)
+ if s.starts_with('@') && !body.contains('/') {
+ return false;
+ }
+ body.chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' || c == '/')
+}
+
+/// 是否是可行动的第三方插件引用(排除核心包与 @deepseek-ai 官方包)。
+fn is_actionable_plugin_ref(s: &str) -> bool {
+ is_package_name(s) && !is_core_package(s.trim())
+}
+
+/// 启动失败时前端读到的日志行(已清洗 ANSI),序列化给前端(camelCase)。
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginRecoveryInfo {
+ /// 定位到的插件 id(npm 包名),可能为空(未定位到具体插件)
+ pub plugins: Vec<String>,
+ /// 失败原因判别键:duplicate_route / duplicate_loader_entry / cannot_resolve_bundle /
+ /// no_dsh_bundle / slot_conflict / load_failed / runtime / unknown
+ pub reason: String,
+ /// 动态详情(如冲突的路由 / 槽位 / 服务组件 id),用于 I18n 插值
+ pub detail: String,
+ /// 原始错误信息(技术详情查看)
+ pub raw_error: String,
+}
+
+// ---- 纯提取函数(便于单元测试)----
+
+/// 从日志文本中提取插件引用(多个错误特征的正则,去重)。
+fn extract_plugin_refs(text: &str) -> Vec<String> {
+ let mut refs = HashSet::new();
+ let patterns = [
+ // failed to apply/import loader entry <name> (<pkg>)
+ r#"failed to (?:apply|import) loader entry[^\n]*\(([^)]+)\)"#,
+ // cannot resolve profile bundle "<pkg>"
+ r#"cannot resolve profile bundle\s+["']?([^"'\n]+)["']?"#,
+ // profile bundle "<pkg>" declares no dsh.bundle
+ r#"profile bundle\s+["']?([^"'\n]+)["']?\s+declares no dsh\.bundle"#,
+ // plugin(s) failed to load: <pkg>
+ r#"plugins? failed to load:\s*([A-Za-z0-9@/_.\-]+)"#,
+ ];
+ for pattern in patterns {
+ if let Ok(re) = Regex::new(pattern) {
+ for cap in re.captures_iter(text) {
+ if let Some(m) = cap.get(1) {
+ let cand = m.as_str().trim();
+ if is_actionable_plugin_ref(cand) {
+ refs.insert(cand.to_string());
+ }
+ }
+ }
+ }
+ }
+ // 「Failed to load plugins」错误卡片:紧随其后的若干行通常是包名。
+ for m in Regex::new(r"(?m)^Failed to load plugins\s*$").expect("literal")
+ .find_iter(text)
+ {
+ let rest = &text[m.end()..];
+ for line in rest.lines().take(12) {
+ let cand = line.trim().trim_end_matches(['.', ',', ' ']);
+ if is_actionable_plugin_ref(cand) {
+ refs.insert(cand.to_string());
+ }
+ }
+ }
+ refs.into_iter().collect()
+}
+
+/// 抽取「重复 loader entry id」。
+fn extract_duplicate_loader_entry(text: &str) -> Option<String> {
+ let re = Regex::new(r#"duplicate loader entry id:\s*["']?([^"'\s]+)["']?"#).ok()?;
+ re.captures(text)
+ .and_then(|c| c.get(1))
+ .map(|m| m.as_str().trim().to_string())
+}
+
+/// 抽取「界面槽位冲突」的槽位名。
+fn extract_slot_conflict(text: &str) -> Option<String> {
+ let re = Regex::new(r#"single slot\s+["']([^"']+)["']\s+already has a registration"#).ok()?;
+ if let Some(c) = re.captures(text) {
+ return c.get(1).map(|m| m.as_str().trim().to_string());
+ }
+ let re = Regex::new(r#"UI slot\s+["']([^"']+)["']\s+has duplicate registrations"#).ok()?;
+ re.captures(text)
+ .and_then(|c| c.get(1))
+ .map(|m| m.as_str().trim().to_string())
+}
+
+/// 对日志文本分类失败原因,返回(判别键, 动态详情)。
+fn classify_reason(text: &str) -> (String, String) {
+ let dup_route =
+ Regex::new(r#"duplicate prefix route\s+["']([^"']+)["']"#).expect("literal");
+ if let Some(c) = dup_route.captures(text) {
+ let route = c.get(1).map(|m| m.as_str().to_string()).unwrap_or_default();
+ return ("duplicate_route".into(), route);
+ }
+ if let Some(entry) = extract_duplicate_loader_entry(text) {
+ return ("duplicate_loader_entry".into(), entry);
+ }
+ if let Some(re) = Regex::new(r#"cannot resolve profile bundle\s+["']?([^"'\n]+)["']?"#)
+ .ok()
+ {
+ if let Some(c) = re.captures(text) {
+ return (
+ "cannot_resolve_bundle".into(),
+ c.get(1).map(|m| m.as_str().to_string()).unwrap_or_default(),
+ );
+ }
+ }
+ if text.contains("declares no dsh.bundle") {
+ let pkg = extract_plugin_refs(text).into_iter().next().unwrap_or_default();
+ return ("no_dsh_bundle".into(), pkg);
+ }
+ if let Some(slot) = extract_slot_conflict(text) {
+ return ("slot_conflict".into(), slot);
+ }
+ if text.contains("failed to import loader entry") || text.contains("failed to apply loader entry") {
+ return ("load_failed".into(), String::new());
+ }
+ ("unknown".into(), String::new())
+}
+
+// ---- 归属:把日志里的引用映射回 profile 配置的根插件 ----
+
+/// 读取 role 包自身的 package.json,返回一个轻量视图。
+#[derive(Default)]
+struct PluginMeta {
+ deps: Vec<String>,
+ optional_deps: Vec<String>,
+ patch_path: Option<String>,
+}
+
+fn read_plugin_meta(dir: &Path) -> Option<PluginMeta> {
+ let content = fs::read_to_string(dir.join("package.json")).ok()?;
+ let v: serde_json::Value = serde_json::from_str(&content).ok()?;
+ let mut meta = PluginMeta::default();
+ if let Some(deps) = v.get("dependencies").and_then(|d| d.as_object()) {
+ meta.deps = deps.keys().cloned().collect();
+ }
+ if let Some(deps) = v.get("optionalDependencies").and_then(|d| d.as_object()) {
+ meta.optional_deps = deps.keys().cloned().collect();
+ }
+ meta.patch_path = v
+ .get("dsh")
+ .and_then(|d| d.get("bundle"))
+ .and_then(|b| b.get("patch"))
+ .and_then(|p| p.as_str())
+ .map(String::from);
+ Some(meta)
+}
+
+/// 当前档案配置的根插件:第三方依赖且在 `dsh.profile.bundles` 中(只有 bundles
+/// 才会随启动加载,才可能引起启动失败)。
+fn configured_roots(app_handle: &AppHandle) -> Vec<String> {
+ let dir = profile_dir(app_handle);
+ let content = match fs::read_to_string(dir.join("package.json")) {
+ Ok(c) => c,
+ Err(_) => return Vec::new(),
+ };
+ let v: serde_json::Value = match serde_json::from_str(&content) {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+ let bundles: HashSet<String> = v
+ .get("dsh")
+ .and_then(|d| d.get("profile"))
+ .and_then(|p| p.get("bundles"))
+ .and_then(|b| b.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|x| x.as_str().map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
+ let deps: Vec<String> = v
+ .get("dependencies")
+ .and_then(|d| d.as_object())
+ .map(|o| o.keys().cloned().collect())
+ .unwrap_or_default();
+ deps.iter()
+ .filter(|d| bundles.contains(*d) && is_actionable_plugin_ref(d))
+ .cloned()
+ .collect()
+}
+
+/// 判断某个根 bundle 是否「拥有」被报告的子包:其依赖里直接声明了该子包,或其
+/// patch 层里引用该包名。
+fn bundle_owns_package(profile: &Path, bundle: &str, package: &str) -> bool {
+ let dir = profile.join("node_modules").join(bundle);
+ let Some(meta) = read_plugin_meta(&dir) else {
+ return false;
+ };
+ if meta.deps.iter().any(|d| d == package)
+ || meta.optional_deps.iter().any(|d| d == package)
+ {
+ return true;
+ }
+ if let Some(patch) = &meta.patch_path {
+ if let Ok(content) = fs::read_to_string(dir.join(patch)) {
+ return content.contains(package);
+ }
+ }
+ false
+}
+
+/// 判断某个根插件的运行时代码/依赖是否引用了给定包集合之一(用于「动态创建官方
+/// UI 包」的归属)。
+fn plugin_references_packages(profile: &Path, plugin: &str, packages: &HashSet<String>) -> bool {
+ let dir = profile.join("node_modules").join(plugin);
+ if let Some(meta) = read_plugin_meta(&dir) {
+ if meta
+ .deps
+ .iter()
+ .chain(meta.optional_deps.iter())
+ .any(|d| packages.contains(d))
+ {
+ return true;
+ }
+ }
+ for file in ["cordis.patch.yml", "index.js", "lib/index.js", "dist/index.js"] {
+ if let Ok(content) = fs::read_to_string(dir.join(file)) {
+ if packages.iter().any(|p| content.contains(p)) {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+/// 判断某个根插件的 patch 层是否声明了重复的 loader entry id。
+fn plugin_declares_loader_entry(profile: &Path, plugin: &str, entry_id: &str) -> bool {
+ let dir = profile.join("node_modules").join(plugin);
+ let Some(meta) = read_plugin_meta(&dir) else {
+ return false;
+ };
+ let Some(patch) = &meta.patch_path else {
+ return false;
+ };
+ let Ok(content) = fs::read_to_string(dir.join(patch)) else {
+ return false;
+ };
+ let re = Regex::new(&format!(r#"^\s*-\s+id:\s*["']?{}["']?(?:\s*(?:#.*)?)?$"#,
+ regex::escape(entry_id))).ok();
+ re.map(|re| re.is_match(&content)).unwrap_or(false)
+}
+
+/// 判断某个根插件的文件是否包含给定槽位名。
+fn plugin_matches_slot(profile: &Path, plugin: &str, slot: &str) -> bool {
+ let dir = profile.join("node_modules").join(plugin);
+ for file in [
+ "cordis.patch.yml",
+ "client.js",
+ "lib/client.js",
+ "dist/client.js",
+ "package.json",
+ "index.js",
+ "lib/index.js",
+ "dist/index.js",
+ ] {
+ if let Ok(content) = fs::read_to_string(dir.join(file)) {
+ if content.contains(slot) {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+/// 提供某槽位的官方 UI 客户端包(用于槽位冲突归属)。
+fn packages_providing_slot(profile: &Path, slot: &str) -> Vec<String> {
+ let scope = profile.join("node_modules").join("@deepseek-ai");
+ let Ok(entries) = fs::read_dir(&scope) else {
+ return Vec::new();
+ };
+ let mut out = Vec::new();
+ for entry in entries.flatten() {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if !name.starts_with("dsh-client-ui-") {
+ continue;
+ }
+ let package = format!("@deepseek-ai/{name}");
+ let dir = entry.path();
+ for file in ["client.js", "lib/client.js", "dist/client.js"] {
+ if let Ok(content) = fs::read_to_string(dir.join(file)) {
+ if content.contains(slot) {
+ out.push(package);
+ break;
+ }
+ }
+ }
+ }
+ out
+}
+
+/// 把日志提取到的引用归属回 profile 配置的根插件;只在一对一(证据唯一)时返回,
+/// 否则返回空(绝不瞎猜)。
+fn resolve_recovery_plugins(
+ app_handle: &AppHandle,
+ detected_refs: &[String],
+ duplicate_entry: Option<&str>,
+ slot_conflict: Option<&str>,
+) -> Vec<String> {
+ let profile = profile_dir(app_handle);
+ let roots = configured_roots(app_handle);
+ if roots.is_empty() {
+ return Vec::new();
+ }
+ let roots_set: HashSet<&String> = roots.iter().collect();
+
+ // 1) 直接命中,或证明某报告子包被唯一根插件拥有。
+ let mut matched = HashSet::new();
+ for detected in detected_refs {
+ if !is_package_name(detected) {
+ continue;
+ }
+ if roots_set.contains(detected) {
+ matched.insert(detected.clone());
+ continue;
+ }
+ let owners: Vec<&String> = roots
+ .iter()
+ .filter(|root| bundle_owns_package(&profile, root, detected))
+ .collect();
+ if owners.len() == 1 {
+ matched.insert(owners[0].clone());
+ }
+ }
+ if matched.len() == 1 {
+ return matched.into_iter().collect();
+ }
+
+ // 1b) 兜底:某官方叶包(loader 报错常指这个)被动态创建,归属回引用它的唯一根。
+ let mut dynamic_owners = HashSet::new();
+ for detected in detected_refs {
+ if !is_package_name(detected) || roots_set.contains(detected) {
+ continue;
+ }
+ let packages: HashSet<String> = [detected.to_string()].into();
+ let owners: Vec<&String> = roots
+ .iter()
+ .filter(|root| plugin_references_packages(&profile, root, &packages))
+ .collect();
+ if owners.len() == 1 {
+ dynamic_owners.insert(owners[0].clone());
+ }
+ }
+ if dynamic_owners.len() == 1 {
+ return dynamic_owners.into_iter().collect();
+ }
+
+ // 2) 重复 loader entry:命中唯一根插件。
+ if let Some(entry) = duplicate_entry {
+ let owners: Vec<&String> = roots
+ .iter()
+ .filter(|root| plugin_declares_loader_entry(&profile, root, entry))
+ .collect();
+ if owners.len() == 1 {
+ return owners.into_iter().map(|s| s.clone()).collect();
+ }
+ }
+
+ // 3) 槽位冲突:命中唯一根插件;否则找提供槽位的官方包,再由唯一根引用它。
+ if let Some(slot) = slot_conflict {
+ let matched: Vec<&String> = roots
+ .iter()
+ .filter(|root| plugin_matches_slot(&profile, root, slot))
+ .collect();
+ if matched.len() == 1 {
+ return matched.into_iter().map(|s| s.clone()).collect();
+ }
+ let providers: HashSet<String> =
+ packages_providing_slot(&profile, slot).into_iter().collect();
+ if !providers.is_empty() {
+ let owners: Vec<&String> = roots
+ .iter()
+ .filter(|root| plugin_references_packages(&profile, root, &providers))
+ .collect();
+ if owners.len() == 1 {
+ return owners.into_iter().map(|s| s.clone()).collect();
+ }
+ }
+ }
+
+ Vec::new()
+}
+
+/// 定位启动失败的问题插件:给定日志行,返回恢复信息(未定位到则 plugins 为空)。
+pub fn detect(app_handle: &AppHandle, log_lines: &[String]) -> PluginRecoveryInfo {
+ let text = log_lines.join("\n");
+ let refs = extract_plugin_refs(&text);
+ let duplicate_entry = extract_duplicate_loader_entry(&text);
+ let slot_conflict = extract_slot_conflict(&text);
+ let (reason, detail) = classify_reason(&text);
+ let plugins = resolve_recovery_plugins(app_handle, &refs, duplicate_entry.as_deref(), slot_conflict.as_deref());
+ let raw_error = refs_text(&text);
+ PluginRecoveryInfo {
+ plugins,
+ reason,
+ detail,
+ raw_error,
+ }
+}
+
+/// 原始错误描述:尽量取关键错误行,供「查看技术详情」。
+fn refs_text(text: &str) -> String {
+ // 从日志里搜出带错误标记的行(最多 8 行),没有则取尾部。
+ let marker_any =
+ Regex::new(r"(?i)error|duplicate|fatal|panic|throw|failed|exception|✖").expect("literal");
+ let mut err_lines: Vec<&str> = text
+ .lines()
+ .filter(|l| marker_any.is_match(l))
+ .map(|l| l.trim())
+ .filter(|l| !l.is_empty())
+ .collect();
+ if err_lines.is_empty() {
+ let tail: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
+ let start = tail.len().saturating_sub(8);
+ err_lines = tail[start..].to_vec();
+ }
+ let joined = err_lines.join("\n");
+ joined.chars().take(2000).collect()
+}
+
+// ---- 卸载(直接改 profile 清单)----
+
+/// 从 manifest 中移除指定插件(`dependencies` + `dsh.profile.bundles`),返回是否有改动。
+fn remove_plugin_from_manifest(manifest: &mut serde_json::Value, id: &str) -> bool {
+ let mut modified = false;
+ if let Some(deps) = manifest.get_mut("dependencies").and_then(|d| d.as_object_mut()) {
+ if deps.remove(id).is_some() {
+ modified = true;
+ }
+ }
+ if 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
+}
+
+/// 删除 `node_modules/<id>`;scoped 目录删除后若 scope 空则一并清理。
+fn remove_plugin_dir(profile: &Path, id: &str) {
+ let node_modules = profile.join("node_modules");
+ let dir = node_modules.join(id);
+ if let Err(e) = fs::remove_dir_all(&dir) {
+ if e.kind() != std::io::ErrorKind::NotFound {
+ log::warn!("failed to remove plugin dir {}: {e}", dir.display());
+ }
+ }
+ if let Some(scope) = id.starts_with('@').then(|| id.split('/').next().unwrap_or_default()) {
+ if !scope.is_empty() && scope != id {
+ let scope_dir = node_modules.join(scope);
+ if scope_dir.is_dir() && scope_dir.read_dir().map(|mut d| d.next().is_none()).unwrap_or(false) {
+ let _ = fs::remove_dir_all(&scope_dir);
+ }
+ }
+ }
+}
+
+/// 从 `cordis.patch.yml` 中剥离目标插件的 patch 条目(保留其它插件的 patch)。
+///
+/// 与 dsh-desktop「直接重置为 []」不同:这里只移除与目标插件相关的条目,不破坏
+/// 其它插件的配置层,符合「其它插件不会被删除」的承诺。解析失败则原样保留。
+fn strip_cordis_patch_for(profile: &Path, id: &str) {
+ let path = profile.join("cordis.patch.yml");
+ let Ok(content) = fs::read_to_string(&path) else {
+ return;
+ };
+ let Ok(doc) = serde_yaml::from_str::<serde_yaml::Value>(&content) else {
+ return;
+ };
+ let Some(entries) = doc.as_sequence() else {
+ return;
+ };
+ let kept: Vec<serde_yaml::Value> = entries
+ .iter()
+ .filter(|e| !patch_entry_targets(e, id))
+ .cloned()
+ .collect();
+ if kept.len() == entries.len() {
+ return;
+ }
+ if let Ok(rendered) = serde_yaml::to_string(&serde_yaml::Value::Sequence(kept)) {
+ let _ = fs::write(&path, rendered);
+ log::info!("Stripped cordis.patch.yml entries for plugin {id}");
+ }
+}
+
+/// 一个 patch 条目是否「针对」目标插件:顶层 id 字段或任意字段值等于该包名。
+fn patch_entry_targets(entry: &serde_yaml::Value, id: &str) -> bool {
+ match entry {
+ serde_yaml::Value::Mapping(map) => map.iter().any(|(k, v)| {
+ k.as_str() == Some(id) || v.as_str() == Some(id)
+ }),
+ serde_yaml::Value::String(s) => s == id,
+ _ => false,
+ }
+}
+
+/// 修复模式卸载:精准删除指定插件(离线、不破坏其它插件)。
+pub fn uninstall(app_handle: &AppHandle, id: &str) -> Result<(), String> {
+ if !is_actionable_plugin_ref(id) {
+ return Err(format!(
+ "PLUGIN_RECOVERY_REFUSED: refusing to remove core/official package {id}"
+ ));
+ }
+ let profile = profile_dir(app_handle);
+ let manifest_path = profile.join("package.json");
+ if !manifest_path.exists() {
+ return Err("PLUGIN_RECOVERY_NO_MANIFEST: profile package.json missing".to_string());
+ }
+ let content = fs::read_to_string(&manifest_path)
+ .map_err(|e| format!("PLUGIN_RECOVERY_READ: {e}"))?;
+ let mut manifest: serde_json::Value = serde_json::from_str(&content)
+ .map_err(|e| format!("PLUGIN_RECOVERY_PARSE: {e}"))?;
+
+ let modified = remove_plugin_from_manifest(&mut manifest, id);
+ if modified {
+ let rendered = serde_json::to_string_pretty(&manifest)
+ .map_err(|e| format!("PLUGIN_RECOVERY_RENDER: {e}"))?;
+ std::fs::write(&manifest_path, format!("{rendered}\n"))
+ .map_err(|e| format!("PLUGIN_RECOVERY_WRITE: {e}"))?;
+ log::info!("Recovery uninstall removed plugin {id} from profile manifest");
+ }
+
+ remove_plugin_dir(&profile, id);
+ strip_cordis_patch_for(&profile, id);
+ // 清掉 lockfile,让 pnpm 重装时重建干净依赖图(best-effort)。
+ if let Err(e) = fs::remove_file(profile.join("pnpm-lock.yaml")) {
+ if e.kind() != std::io::ErrorKind::NotFound {
+ log::warn!("failed to remove pnpm-lock.yaml during recovery: {e}");
+ }
+ }
+ if let Err(e) = errors::clear(app_handle, id) {
+ log::warn!("failed to clear plugin error for {id} during recovery: {e}");
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn package_name_validation() {
+ assert!(is_package_name("dshmarket"));
+ assert!(is_package_name("@scope/pkg"));
+ assert!(is_package_name("dsh-better-sidebar"));
+ assert!(!is_package_name(""));
+ assert!(!is_package_name("has space"));
+ assert!(!is_package_name("with:colon"));
+ assert!(!is_package_name("@bare"));
+ assert!(!is_actionable_plugin_ref("@deepseek-ai/dsh-base"));
+ assert!(!is_actionable_plugin_ref("dshmarket"));
+ assert!(is_actionable_plugin_ref("dsh-better-sidebar"));
+ }
+
+ #[test]
+ fn extract_refs_from_failure_log() {
+ let log = r#"
+[stderr] failed to apply loader entry dshSidebarApi (@omdsh-dev/dsh-better-sidebar)
+[stderr] cannot resolve profile bundle "dsh-web-ui-all"
+"#;
+ let refs = extract_plugin_refs(log);
+ assert!(refs.contains(&"@omdsh-dev/dsh-better-sidebar".to_string()));
+ assert!(refs.contains(&"dsh-web-ui-all".to_string()));
+ }
+
+ #[test]
+ fn extract_refs_from_boot_card() {
+ let log = "Failed to load plugins\ndsh-better-sidebar\n@scope/another\nAn unknown error occurred\n";
+ let refs = extract_plugin_refs(log);
+ assert!(refs.contains(&"dsh-better-sidebar".to_string()));
+ assert!(refs.contains(&"@scope/another".to_string()));
+ // 非包名行不应被当作插件引用
+ assert!(!refs.iter().any(|r| r.contains("unknown")));
+ }
+
+ #[test]
+ fn extract_duplicate_and_slot() {
+ let route_log = r#"duplicate prefix route "/sidebar/api""#;
+ assert_eq!(classify_reason(route_log).0, "duplicate_route");
+ let entry_log = "duplicate loader entry id: \"dshSidebarApi\"";
+ assert_eq!(extract_duplicate_loader_entry(entry_log).as_deref(), Some("dshSidebarApi"));
+ let slot_log = r#"single slot "sidebar" already has a registration"#;
+ assert_eq!(extract_slot_conflict(slot_log).as_deref(), Some("sidebar"));
+ }
+
+ #[test]
+ fn remove_plugin_from_manifest_edits_deps_and_bundles() {
+ let mut manifest = serde_json::json!({
+ "name": "dsh-profile-web",
+ "private": true,
+ "dependencies": { "dshmarker": "1.0.0", "dsh-better-sidebar": "1.0.0" },
+ "dsh": { "profile": { "bundles": ["@deepseek-ai/dsh-base", "dsh-better-sidebar"] } }
+ });
+ let modified = remove_plugin_from_manifest(&mut manifest, "dsh-better-sidebar");
+ assert!(modified);
+ assert!(manifest["dependencies"].get("dsh-better-sidebar").is_none());
+ assert!(manifest["dependencies"].get("dshmarker").is_some());
+ assert_eq!(
+ manifest["dsh"]["profile"]["bundles"].as_array().unwrap().len(),
+ 1
+ );
+ }
+
+ #[test]
+ fn patch_strip_targets_plugin_only() {
+ let patch = serde_yaml::to_string(&serde_yaml::Value::Sequence(vec![
+ serde_yaml::from_str::<serde_yaml::Value>("id: dsh-better-sidebar\nfoo: 1").unwrap(),
+ serde_yaml::from_str::<serde_yaml::Value>("id: dsh-web-ui-all\nbar: 2").unwrap(),
+ ]))
+ .unwrap();
+ let doc: serde_yaml::Value = serde_yaml::from_str(&patch).unwrap();
+ let kept: Vec<serde_yaml::Value> = doc
+ .as_sequence()
+ .unwrap()
+ .iter()
+ .filter(|e| !patch_entry_targets(e, "dsh-better-sidebar"))
+ .cloned()
+ .collect();
+ assert_eq!(kept.len(), 1);
+ let kept_doc = serde_yaml::to_string(&serde_yaml::Value::Sequence(kept)).unwrap();
+ assert!(kept_doc.contains("dsh-web-ui-all"));
+ assert!(!kept_doc.contains("dsh-better-sidebar"));
+ }
+}
diff --git a/src/components/config-dialog.tsx b/src/components/config-dialog.tsx
index 6460081c..c3ba44b7 100644
--- a/src/components/config-dialog.tsx
+++ b/src/components/config-dialog.tsx
@@ -5,7 +5,8 @@ import { cn, Modal } from '@heroui/react'
import { useDisclosure } from '@overlastic/react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { Case, Switch } from 'react-if-lite'
+import { Case, If, Switch } from 'react-if-lite'
+import { useDshPlugins } from '../hooks/use-dsh-plugins'
import { ConfigCore } from './config-core'
import { ConfigDebug } from './config-debug'
import { ConfigPlugin } from './config-plugin'
@@ -16,6 +17,9 @@ export interface ConfigDialogProps extends PropsWithOverlays {}
export function ConfigDialog(props: ConfigDialogProps) {
const disclosure = useDisclosure({ props })
const { t } = useTranslation()
+ // 异常插件数:在「插件」Tab 上给出红点/角标,方便用户直接感知出问题的插件
+ const { plugins } = useDshPlugins()
+ const abnormalCount = plugins.filter(p => p.error != null).length
const navs = [
{ label: t('config.debug'), value: 'debug', icon: Wrench },
@@ -55,6 +59,11 @@ export function ConfigDialog(props: ConfigDialogProps) {
>
<item.icon className="w-5 h-5 mr-2" />
<span>{item.label}</span>
+ <If cond={item.value === 'plugins' && abnormalCount > 0}>
+ <span className="ml-auto flex size-5 items-center justify-center rounded-full bg-danger text-[10px] font-semibold leading-none text-white">
+ {abnormalCount}
+ </span>
+ </If>
</button>
)
})}
diff --git a/src/components/plugin-recovery.tsx b/src/components/plugin-recovery.tsx
new file mode 100644
index 00000000..ee6c0a65
--- /dev/null
+++ b/src/components/plugin-recovery.tsx
@@ -0,0 +1,123 @@
+import { CircleExclamation } from '@gravity-ui/icons'
+import { Button, Chip, Description, Spinner } from '@heroui/react'
+import { useTranslation } from 'react-i18next'
+import { If } from 'react-if-lite'
+import { useStore } from 'valtio-define'
+import { store } from '@/store'
+
+/** 插件异常修复界面最多自动提示的次数(与 store 的 MAX_RECOVERY_ATTEMPTS 一致) */
+const MAX_RECOVERY_ATTEMPTS = 3
+
+/** 失败原因 → i18n 键映射(title / detail,detail 用 {{detail}} 插值) */
+const REASON_KEYS: Record<string, { title: string, detail: string }> = {
+ duplicate_route: { title: 'recovery.reason.duplicate_route.title', detail: 'recovery.reason.duplicate_route.detail' },
+ duplicate_loader_entry: { title: 'recovery.reason.duplicate_loader_entry.title', detail: 'recovery.reason.duplicate_loader_entry.detail' },
+ cannot_resolve_bundle: { title: 'recovery.reason.cannot_resolve_bundle.title', detail: 'recovery.reason.cannot_resolve_bundle.detail' },
+ no_dsh_bundle: { title: 'recovery.reason.no_dsh_bundle.title', detail: 'recovery.reason.no_dsh_bundle.detail' },
+ slot_conflict: { title: 'recovery.reason.slot_conflict.title', detail: 'recovery.reason.slot_conflict.detail' },
+ load_failed: { title: 'recovery.reason.load_failed.title', detail: 'recovery.reason.load_failed.detail' },
+ runtime: { title: 'recovery.reason.runtime.title', detail: 'recovery.reason.runtime.detail' },
+ unknown: { title: 'recovery.reason.unknown.title', detail: 'recovery.reason.unknown.detail' },
+}
+
+/**
+ * 插件异常修复界面。
+ *
+ * - 启动崩溃(`fullScreen`):渲染全屏恢复页(替换 Setup 错误内容),
+ * 主按钮「卸除此插件并继续检测」。
+ * - 运行期异常(应用仍在运行):渲染醒目对话框(不阻断使用),可「暂不处理」。
+ *
+ * 数据全部来自 harness store 的 `recovery` 状态(`plugin-recovery-required`
+ * 事件 / 启动失败检测触发),不在组件内自行拉取。
+ */
+export function PluginRecovery({ fullScreen = false }: { fullScreen?: boolean }) {
+ const { t } = useTranslation()
+ const { recovery } = useStore(store.harness)
+
+ if (!recovery.required || !recovery.info) {
+ return null
+ }
+
+ const info = recovery.info
+ const multiple = info.plugins.length > 1
+ const exhausted = recovery.attempts >= MAX_RECOVERY_ATTEMPTS
+ const reasonKeys = REASON_KEYS[info.reason] ?? REASON_KEYS.unknown
+ const heading = multiple
+ ? t('recovery.heading_many', { count: info.plugins.length })
+ : t('recovery.heading_one')
+ const primaryLabel = multiple
+ ? t('recovery.remove_many', { count: info.plugins.length })
+ : t('recovery.remove_one')
+ const reasonDetail = info.detail
+ ? t(reasonKeys.detail, { detail: info.detail })
+ : t(reasonKeys.detail)
+
+ return (
+ <div
+ className={fullScreen
+ ? 'flex h-full w-full items-center justify-center overflow-auto bg-canvas p-6'
+ : 'fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4'}
+ >
+ <div className={`w-full ${fullScreen ? 'max-w-[640px]' : 'max-w-[560px]'}`}>
+ <div className={`rounded-xl border bg-panel2/40 p-6${fullScreen ? '' : ' shadow-sm'}`}>
+ <div className="mb-4 flex items-center gap-3">
+ <div className="flex size-12 shrink-0 items-center justify-center rounded-full bg-danger/10 text-danger">
+ <CircleExclamation className="size-6" />
+ </div>
+ <div className="min-w-0">
+ <p className="m-0 text-base font-semibold text-ink">{heading}</p>
+ <p className="m-0 text-xs text-muted">{t(reasonKeys.title)}</p>
+ </div>
+ </div>
+
+ <Description className="mb-3 text-sm text-ink">
+ {reasonDetail}
+ </Description>
+
+ <div className="mb-3 space-y-1.5">
+ {info.plugins.map(pkg => (
+ <div key={pkg} className="flex items-center justify-between gap-2 rounded-md bg-black/5 px-3 py-2">
+ <code className="min-w-0 truncate font-mono text-sm text-ink">{pkg}</code>
+ <Chip className="shrink-0 text-xs" variant="primary" color="danger" size="sm">
+ {t('recovery.offender')}
+ </Chip>
+ </div>
+ ))}
+ </div>
+
+ <If cond={exhausted}>
+ <p className="m-0 mb-3 text-xs text-warning">{t('recovery.summary_exhausted')}</p>
+ </If>
+
+ <p className="m-0 mb-4 text-xs text-load-muted">{t('recovery.safety_note')}</p>
+
+ {/* 错误信息默认展示(含原始错误,便于排查) */}
+ <div className="mb-4 max-h-48 overflow-auto rounded-md bg-black/5 p-3">
+ <pre className="m-0 whitespace-pre-wrap break-all font-mono text-[11px] text-muted">
+ {info.raw_error || '—'}
+ </pre>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ className="rounded-md"
+ variant="danger"
+ onPress={() => store.harness.recoverAndRedetect(info.plugins)}
+ >
+ <span className="flex items-center gap-1">
+ <If cond={recovery.busy} then={<Spinner size="sm" color="current" />} />
+ {recovery.busy ? t('recovery.removing') : primaryLabel}
+ </span>
+ </Button>
+ <Button className="rounded-md" variant="tertiary" onPress={() => store.harness.restart()}>
+ {t('recovery.restart')}
+ </Button>
+ <Button className="rounded-md" variant="ghost" onPress={() => store.harness.dismissRecovery()}>
+ {t('recovery.dismiss')}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 02765ac2..db3c6f85 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -206,5 +206,31 @@
"config.plugins": "Plugins",
"config.harness": "Harness",
"buttons.cancel": "Cancel",
- "buttons.confirm": "Confirm"
+ "buttons.confirm": "Confirm",
+ "recovery.heading_one": "A plugin is preventing startup",
+ "recovery.heading_many": "{{count}} plugins are preventing startup",
+ "recovery.remove_one": "Remove this plugin and continue checking",
+ "recovery.remove_many": "Remove these {{count}} plugins and continue checking",
+ "recovery.removing": "Removing and checking again…",
+ "recovery.restart": "Restart Harness",
+ "recovery.dismiss": "Not now",
+ "recovery.safety_note": "Your workspaces, sessions, model settings, and other plugins will not be removed.",
+ "recovery.offender": "Conflicting plugin",
+ "recovery.summary_exhausted": "This issue keeps repeating after attempts. Open the Harness log for the detailed error, or remove the plugin manually from the Plugins panel.",
+ "recovery.reason.duplicate_route.title": "A plugin registered a duplicate service route",
+ "recovery.reason.duplicate_route.detail": "The startup log shows that {{detail}} was registered more than once, so Harness could not continue.",
+ "recovery.reason.duplicate_loader_entry.title": "A plugin registered a duplicate service component",
+ "recovery.reason.duplicate_loader_entry.detail": "The startup log shows that component {{detail}} was registered more than once due to a plugin conflict.",
+ "recovery.reason.cannot_resolve_bundle.title": "The plugin is not fully installed",
+ "recovery.reason.cannot_resolve_bundle.detail": "The profile still references this plugin, but its package cannot be found locally.",
+ "recovery.reason.no_dsh_bundle.title": "The package is not a compatible DSH plugin",
+ "recovery.reason.no_dsh_bundle.detail": "It does not declare the entry point required by Harness.",
+ "recovery.reason.slot_conflict.title": "A plugin has a UI slot conflict",
+ "recovery.reason.slot_conflict.detail": "UI slot {{detail}} has duplicate registrations from conflicting plugins.",
+ "recovery.reason.load_failed.title": "The plugin code could not be loaded",
+ "recovery.reason.load_failed.detail": "Its files may be damaged, missing a dependency, or incompatible with this Harness version.",
+ "recovery.reason.runtime.title": "A plugin is running abnormally",
+ "recovery.reason.runtime.detail": "The plugin reported a runtime error. Removing it and continuing may resolve the issue.",
+ "recovery.reason.unknown.title": "A plugin failed during startup",
+ "recovery.reason.unknown.detail": "Harness reported an error while loading a plugin, but the exact cause could not be determined automatically."
}
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index c4ca2901..9e75c66b 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -206,5 +206,31 @@
"config.plugins": "插件",
"config.harness": "核心",
"buttons.cancel": "取消",
- "buttons.confirm": "确定"
+ "buttons.confirm": "确定",
+ "recovery.heading_one": "发现导致启动失败的插件",
+ "recovery.heading_many": "发现 {{count}} 个导致启动失败的插件",
+ "recovery.remove_one": "卸除此插件并继续检测",
+ "recovery.remove_many": "卸载这 {{count}} 个插件并继续检测",
+ "recovery.removing": "正在处理并重新检测…",
+ "recovery.restart": "重启 Harness",
+ "recovery.dismiss": "暂不处理",
+ "recovery.safety_note": "工作区、会话、模型配置和其他插件不会被删除。",
+ "recovery.offender": "问题插件",
+ "recovery.summary_exhausted": "多次处理后问题仍反复出现。请打开 Harness 日志查看详细错误,或在「插件」面板手动卸载该插件。",
+ "recovery.reason.duplicate_route.title": "插件使用了重复的服务入口",
+ "recovery.reason.duplicate_route.detail": "启动日志显示 {{detail}} 被重复注册,因此 Harness 无法继续启动。",
+ "recovery.reason.duplicate_loader_entry.title": "插件注册了重复的服务组件",
+ "recovery.reason.duplicate_loader_entry.detail": "启动日志显示组件 {{detail}} 被重复定义,插件之间存在加载冲突,因此 Harness 无法继续启动。",
+ "recovery.reason.cannot_resolve_bundle.title": "插件没有完整安装",
+ "recovery.reason.cannot_resolve_bundle.detail": "配置中仍然引用了这个插件,但本地找不到对应的插件包。",
+ "recovery.reason.no_dsh_bundle.title": "安装的包不是兼容的 DSH 插件",
+ "recovery.reason.no_dsh_bundle.detail": "这个包缺少 DSH 插件所需的入口声明,因此 Harness 无法加载。",
+ "recovery.reason.slot_conflict.title": "插件存在界面插槽冲突",
+ "recovery.reason.slot_conflict.detail": "检测到界面插槽 {{detail}} 存在重复注册,多个第三方插件试图占用相同的界面组件,导致前端无法正常渲染。",
+ "recovery.reason.load_failed.title": "插件代码加载失败",
+ "recovery.reason.load_failed.detail": "插件文件可能损坏、缺少依赖,或与当前 Harness 版本不兼容。",
+ "recovery.reason.runtime.title": "插件运行异常",
+ "recovery.reason.runtime.detail": "该插件运行期上报了错误。卸载它并继续可能解决问题。",
+ "recovery.reason.unknown.title": "插件启动失败",
+ "recovery.reason.unknown.detail": "Harness 在加载插件时发生错误,但暂时无法自动判断更具体的原因。"
}
diff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsx
index b45b267e..8d09ff65 100644
--- a/src/layout/components/webview.tsx
+++ b/src/layout/components/webview.tsx
@@ -2,7 +2,9 @@
import { CircleExclamation } from '@gravity-ui/icons'
import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { If } from 'react-if-lite'
import { useStore } from 'valtio-define'
+import { PluginRecovery } from '@/components/plugin-recovery'
import { useIframeShim } from '@/hooks/use-iframe-shim'
import { store } from '@/store'
import { Loadable } from './loadable'
@@ -25,6 +27,7 @@ export function Webview() {
iframeKey,
iframeSrc,
serviceUrl,
+ recovery,
} = useStore(store.harness)
const iframeRef = useRef<HTMLIFrameElement>(null)
@@ -36,7 +39,10 @@ export function Webview() {
<main className="relative flex min-h-0 flex-1 flex-col bg-canvas">
<Navbar />
<div className="min-h-0 flex-1">
- <Setup />
+ {/* 能定位到问题插件时展示全屏恢复页(卸除此插件并继续检测);否则普通错误页 */}
+ <If cond={recovery.required} else={<Setup />}>
+ <PluginRecovery fullScreen />
+ </If>
</div>
</main>
)
diff --git a/src/layout/index.tsx b/src/layout/index.tsx
index dda3f4e4..792c589f 100644
--- a/src/layout/index.tsx
+++ b/src/layout/index.tsx
@@ -1,5 +1,6 @@
import { useEffect } from 'react'
import { useStore } from 'valtio-define'
+import { PluginRecovery } from '../components/plugin-recovery'
import { useDshTheme } from '../hooks/use-dsh-theme'
import { store } from '../store'
import { DesktopUpdater } from './components/desktop-updater'
@@ -11,7 +12,7 @@ import '../i18n'
* 应用根布局:只负责首次启动与整体壳层结构。
* 业务状态与操作方法全部收敛到 valtio-define store,
* 各子组件自行订阅 store,不再通过 props 透传回调与状态。
- * 弹出层(关于 / 检查更新 / 应用配置)统一由 overlastic 命令式打开,
+ * 弹出层(关于 / 检查更新 / 应用配置 / 插件异常修复)统一由 overlastic 命令式打开,
* 仅在需要时挂载,不常驻渲染。
*/
export function App() {
@@ -22,11 +23,46 @@ export function App() {
store.harness.startup()
}, [])
+ // 仅开发模式:快捷键预览「插件异常修复界面」,便于快速看到实际 UI(不影响生产构建)。
+ // Ctrl+Shift+1 → 运行期异常对话框(应用仍在运行)
+ // Ctrl+Shift+2 → 启动崩溃全屏恢复页
+ useEffect(() => {
+ if (!import.meta.env.DEV)
+ return
+ function onKeyDown(e: KeyboardEvent) {
+ if (!e.ctrlKey || !e.shiftKey)
+ return
+ if (e.code === 'Digit1') {
+ e.preventDefault()
+ store.harness.setRuntimeRecovery({
+ plugins: ['dsh-better-sidebar'],
+ reason: 'slot_conflict',
+ detail: 'sidebar',
+ raw_error: 'Preview: dsh-better-sidebar reported a UI slot conflict.',
+ })
+ }
+ else if (e.code === 'Digit2') {
+ e.preventDefault()
+ store.harness.fail('Preview: plugin startup failure')
+ store.harness.setRuntimeRecovery({
+ plugins: ['dsh-better-sidebar'],
+ reason: 'duplicate_loader_entry',
+ detail: 'dshSidebarApi',
+ raw_error: 'Preview: duplicate loader entry id: dshSidebarApi',
+ })
+ }
+ }
+ window.addEventListener('keydown', onKeyDown)
+ return () => window.removeEventListener('keydown', onKeyDown)
+ }, [])
+
return (
<div className="flex h-screen w-screen">
<Webview />
{status === 'ready' && <HarnessUpdater />}
{status === 'ready' && <DownloadToast />}
+ {/* 运行期插件异常:应用仍在运行,弹醒目对话框(启动崩溃走 webview 的全屏恢复页) */}
+ {status === 'ready' && <PluginRecovery />}
<DesktopUpdater />
</div>
)
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index bc42b0f7..d53e8126 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -3,8 +3,10 @@ import type { UnlistenFn } from '@tauri-apps/api/event'
import type {
InstallerState,
InstallProgress,
+ PluginRecoveryInfo,
PreinstallLogPayload,
PreinstallPlugin,
+ RecoveryState,
SetupStatus,
SidebarBusyAction,
} from './types'
@@ -26,6 +28,8 @@ const ERROR_LINE_MARKERS = /error|duplicate|fatal|panic|throw|✖|exception|fail
/** 启动失败错误:附带从 dsh 服务日志中读取的真实错误行与可选的冲突提示 */
interface StartupError extends Error {
logs?: string[]
+ /** 完整清洗后的日志尾(供插件异常定位使用,非仅错误行) */
+ logLines?: string[]
pluginConflictHint?: string
}
@@ -36,6 +40,13 @@ const initialInstaller: InstallerState = {
logs: [],
}
+const initialRecovery: RecoveryState = {
+ required: false,
+ info: null,
+ attempts: 0,
+ busy: false,
+}
+
/** 启动流程令牌:boot 并发/重复调用时只采纳最后一次的结果 */
let bootToken = 0
/** 首次自动启动去重(React StrictMode 会重复挂载 effect) */
@@ -121,6 +132,7 @@ async function attachStartupDiagnostics(err: unknown): Promise<StartupError> {
const startupError = err as StartupError
if (!startupError.logs) {
const lines = await readServiceLogTail()
+ startupError.logLines = lines
startupError.logs = pickErrorLines(lines)
// 识别插件路由冲突(如 `duplicate prefix route "/sidebar/api"`),给出可操作的提示
if (lines.join('\n').includes('duplicate prefix route')) {
@@ -147,6 +159,10 @@ export const harness = defineStore({
errorLogs: [] as string[],
/** 识别到插件路由冲突时的针对性提示(Loadable children 展示) */
pluginConflictHint: '',
+ /** 插件异常修复界面状态(启动崩溃/运行期异常 → 弹出「卸除此插件并继续检测」) */
+ recovery: initialRecovery,
+ /** 用户已「暂不处理」的插件 id(避免同一运行期异常反复弹窗) */
+ dismissedRecoveryIds: [] as string[],
/** 预装插件引导状态:列表/安装进度/日志/错误 */
preinstall: {
plugins: [] as PreinstallPlugin[],
@@ -173,9 +189,25 @@ export const harness = defineStore({
if (bootStarted)
return
bootStarted = true
+ void this.listenPluginRecovery()
void this.boot()
},
+ /**
+ * 订阅后端「插件异常」推送:`report_plugin_error`(运行期异常)会推送
+ * `plugin-recovery-required`,据此弹出「卸除此插件并继续检测」修复界面。
+ */
+ async listenPluginRecovery() {
+ try {
+ await listen<PluginRecoveryInfo>('plugin-recovery-required', (event) => {
+ this.setRuntimeRecovery(event.payload)
+ })
+ }
+ catch (err) {
+ console.error('[Harness] failed to listen plugin-recovery-required:', err)
+ }
+ },
+
/** 刷新 iframe:清除加载态并延迟重新挂载 */
refreshIframe() {
this.iframeLoaded = false
@@ -219,8 +251,11 @@ export const harness = defineStore({
async launchAndWait() {
this.status = 'ready'
this.installer = initialInstaller
+ this.errorMsg = ''
this.errorLogs = []
this.pluginConflictHint = ''
+ this.recovery = initialRecovery
+ this.dismissedRecoveryIds = []
this.serviceHealthy = false
this.iframeLoaded = false
this.iframeError = false
@@ -248,6 +283,9 @@ export const harness = defineStore({
)
}
this.serviceHealthy = true
+ // 服务(重)启动成功:清空插件异常修复态(若曾进入),并重置已「暂不处理」的插件
+ this.recovery = { required: false, info: null, attempts: 0, busy: false }
+ this.dismissedRecoveryIds = []
// 服务(重)启动成功后,dsh 版本/端口/CLI 链接状态等运行时信息可能已变化
// (典型:Harness 更新后旧版本缓存仍在,调试侧边栏需刷新页面才显示新版本)。
// 使侧边栏相关查询缓存失效,重新打开/已挂载时自动拉取最新值。
@@ -329,6 +367,8 @@ export const harness = defineStore({
return
console.error('[Harness] startup failed:', err)
const startupError = await attachStartupDiagnostics(err)
+ // 尝试从日志定位问题插件:能定位则弹出修复界面(全屏恢复页)
+ await this.reviewStartupRecovery(startupError.logLines ?? startupError.logs ?? [])
this.fail(String(startupError), startupError.logs, startupError.pluginConflictHint)
}
finally {
@@ -351,11 +391,82 @@ export const harness = defineStore({
this.serviceRunning = false
},
+ /**
+ * 启动失败时尝试定位问题插件并弹出修复界面。
+ * 能定位到具体插件 → 设置 `recovery`;定位不到则保持普通错误态(无插件可卸载)。
+ */
+ async reviewStartupRecovery(logs: string[]) {
+ if (this.recovery.required || logs.length === 0)
+ return
+ try {
+ const info = await invoke<PluginRecoveryInfo>('detect_plugin_recovery', { logs })
+ if (info.plugins.length > 0) {
+ this.recovery = {
+ required: true,
+ info,
+ attempts: this.recovery.attempts + 1,
+ busy: false,
+ }
+ }
+ }
+ catch (err) {
+ console.error('[Harness] detect_plugin_recovery failed:', err)
+ }
+ },
+
+ /** 运行期插件异常:弹出修复对话框(应用仍在运行)。已「暂不处理」的同插件不再重复弹。 */
+ setRuntimeRecovery(info: PluginRecoveryInfo) {
+ if (info.plugins.length === 0)
+ return
+ if (info.plugins.some(id => this.dismissedRecoveryIds.includes(id)))
+ return
+ this.recovery = {
+ required: true,
+ info,
+ attempts: this.recovery.attempts + 1,
+ busy: false,
+ }
+ },
+
+ /** 「卸除此插件并继续检测」:离线卸载定位到的插件 → 重启并重新检测;仍有问题会再次触发修复界面。 */
+ async recoverAndRedetect(ids: readonly string[]) {
+ if (this.recovery.busy || ids.length === 0)
+ return
+ this.recovery = { ...this.recovery, busy: true }
+ try {
+ for (const id of ids) {
+ await invoke('recover_plugin', { id })
+ }
+ // 卸载成功:清空恢复态回到启动/就绪;若仍失败,boot 的 catch 会再次定位并弹出。
+ // 保留 attempts:连续失败会累加,达到上限后界面提示「查看日志 / 手动卸载」。
+ this.dismissedRecoveryIds = this.dismissedRecoveryIds.filter(x => !ids.includes(x))
+ this.recovery = { required: false, info: null, attempts: this.recovery.attempts, busy: false }
+ await this.restart()
+ }
+ catch (err) {
+ console.error('[Harness] recover_plugin failed:', err)
+ this.recovery = { ...this.recovery, busy: false, attempts: this.recovery.attempts + 1 }
+ }
+ },
+
+ /** 「暂不处理」:关闭修复界面并记住这些插件(运行期场景不阻断使用)。 */
+ dismissRecovery() {
+ if (this.recovery.info) {
+ this.dismissedRecoveryIds = [
+ ...new Set([...this.dismissedRecoveryIds, ...this.recovery.info.plugins]),
+ ]
+ }
+ this.recovery = { required: false, info: null, attempts: 0, busy: false }
+ },
+
/** 重启服务:先强杀再拉起,最终回到就绪/错误态 */
async restart() {
if (this.busyAction)
return
this.busyAction = 'restart'
+ // 手动重启(含修复界面上的「重启 Harness」):先退出恢复态,
+ // 若重启仍失败,boot 的 catch 会重新定位问题插件并再次弹出。
+ this.recovery = { ...this.recovery, required: false, busy: false }
try {
emitter.emit('config:dialog:hidden')
await invoke('shutdown_harness')
@@ -394,6 +505,8 @@ export const harness = defineStore({
this.errorMsg = i18next.t('ui.stopped')
this.errorLogs = []
this.pluginConflictHint = ''
+ this.recovery = initialRecovery
+ this.dismissedRecoveryIds = []
},
/** 服务未运行时点击"重试":重新拉起服务并等待健康检查 */
diff --git a/src/store/modules/harness/types.ts b/src/store/modules/harness/types.ts
index d3673718..707142fb 100644
--- a/src/store/modules/harness/types.ts
+++ b/src/store/modules/harness/types.ts
@@ -40,3 +40,27 @@ export interface InstallProgress {
percentage: number
progress: number
}
+
+/** Rust 侧 service::plugin::recovery::PluginRecoveryInfo 的序列化形态(camelCase) */
+export interface PluginRecoveryInfo {
+ /** 定位到的问题插件(npm 包名);未定位到时为空 */
+ plugins: string[]
+ /** 失败原因判别键:duplicate_route / duplicate_loader_entry / cannot_resolve_bundle / no_dsh_bundle / slot_conflict / load_failed / runtime / unknown */
+ reason: string
+ /** 动态详情(冲突路由 / 槽位 / 服务组件 id),用于 I18n 插值 */
+ detail: string
+ /** 原始错误信息(技术详情查看) */
+ raw_error: string
+}
+
+/** 插件异常修复界面状态 */
+export interface RecoveryState {
+ /** 是否弹出修复界面 */
+ required: boolean
+ /** 定位到的恢复信息 */
+ info: PluginRecoveryInfo | null
+ /** 已触发修复的次数(用于防死循环) */
+ attempts: number
+ /** 修复动作进行中 */
+ busy: boolean
+}