Skip to content

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

feat(plugin): update/remove individual plugins with persisted error registry

hairyf22e5997e449f
diff --git a/src-tauri/src/bridge/cmd.rs b/src-tauri/src/bridge/cmd.rs
index 5d65ed0f..6a33dd8e 100644
--- a/src-tauri/src/bridge/cmd.rs
+++ b/src-tauri/src/bridge/cmd.rs
@@ -308,6 +308,37 @@ pub fn get_dsh_plugins(app_handle: AppHandle) -> Vec<plugin::DshPlugin> {
plugin::watch::list(&app_handle)
}
+/// 升级单个已安装插件:`dsh plugin --profile <当前档案> update <id>`,
+/// 进程输出通过 `preinstall-log` 事件实时推送。
+#[tauri::command]
+pub async fn update_dsh_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {
+ plugin::update(&app_handle, &id).await?;
+ plugin::watch::force_emit(&app_handle);
+ Ok(())
+}
+
+/// 卸载单个已安装插件:`dsh plugin --profile <当前档案> remove <id>`,
+/// 进程输出通过 `preinstall-log` 事件实时推送。
+#[tauri::command]
+pub async fn remove_dsh_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {
+ plugin::remove(&app_handle, &id).await?;
+ plugin::watch::force_emit(&app_handle);
+ Ok(())
+}
+
+/// 上报插件运行期异常(内嵌页面 / dsh-tauri 桥调用),记录后立即推送新列表。
+#[tauri::command]
+pub fn report_plugin_error(
+ app_handle: AppHandle,
+ id: String,
+ error: String,
+ action: Option<String>,
+) -> Result<(), String> {
+ plugin::errors::record(&app_handle, &id, action.as_deref().unwrap_or("runtime"), &error)?;
+ plugin::watch::force_emit(&app_handle);
+ Ok(())
+}
+
/// 档案列表($DSH_HOME/profiles 下的目录,含 active/default 标记)
#[tauri::command]
pub fn get_profiles(app_handle: AppHandle) -> Vec<profile::Profile> {
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index c5cd2413..f6eff7ff 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -199,6 +199,9 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::cmd::skip_preinstall_plugins,
crate::bridge::cmd::open_preinstall_repo,
crate::bridge::cmd::get_dsh_plugins,
+ crate::bridge::cmd::update_dsh_plugin,
+ crate::bridge::cmd::remove_dsh_plugin,
+ crate::bridge::cmd::report_plugin_error,
crate::bridge::cmd::get_profiles,
crate::bridge::cmd::create_profile,
crate::bridge::cmd::set_active_profile,
diff --git a/src-tauri/src/service/plugin/errors.rs b/src-tauri/src/service/plugin/errors.rs
new file mode 100644
index 00000000..1b1572cc
--- /dev/null
+++ b/src-tauri/src/service/plugin/errors.rs
@@ -0,0 +1,103 @@
+//! 插件错误记录(持久化)。
+//!
+//! 记录来源:
+//! - 安装/升级/卸载失败(本应用操作可确定,见 [`super::install`]);
+//! - 页面运行期异常——内嵌 dsh 页面(或 dsh-tauri 桥)经
+//! `report_plugin_error` 命令上报(见 desktop 的 iframe 消息桥)。
+//!
+//! 记录保存在桌面端数据目录 `plugin-errors.json`,与 `$DSH_HOME`(官方数据)
+//! 分离:这是桌面端自己的诊断信息,不属于 dsh profile 数据。
+//! 插件安装/升级/卸载成功时清除对应记录。
+
+use crate::config;
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::path::PathBuf;
+use tauri::AppHandle;
+
+/// 单条插件错误
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PluginError {
+ /// 错误消息(pnpm/运行日志片段,最多保留 2000 字符)
+ pub message: String,
+ /// 记录动作:install / update / remove / runtime
+ pub action: String,
+ /// 记录时间(unix 秒级时间戳字符串)
+ pub at: String,
+}
+
+fn errors_path(app_handle: &AppHandle) -> PathBuf {
+ config::get_base_dir(app_handle).join("plugin-errors.json")
+}
+
+/// 读取全部错误记录(缺失/损坏按空处理)
+pub(crate) fn load(app_handle: &AppHandle) -> HashMap<String, PluginError> {
+ let Ok(content) = std::fs::read_to_string(errors_path(app_handle)) else {
+ return HashMap::new();
+ };
+ serde_json::from_str(&content).unwrap_or_default()
+}
+
+fn save(app_handle: &AppHandle, map: &HashMap<String, PluginError>) -> Result<(), String> {
+ let path = errors_path(app_handle);
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir).map_err(|e| format!("PLUGIN_ERRORS_DIR: {e}"))?;
+ }
+ let json =
+ serde_json::to_string_pretty(map).map_err(|e| format!("PLUGIN_ERRORS_RENDER: {e}"))?;
+ std::fs::write(&path, json).map_err(|e| format!("PLUGIN_ERRORS_WRITE: {e}"))
+}
+
+/// 记录插件错误(同 id 幂等覆盖)
+pub fn record(
+ app_handle: &AppHandle,
+ id: &str,
+ action: &str,
+ message: &str,
+) -> Result<(), String> {
+ let mut map = load(app_handle);
+ map.insert(
+ id.to_string(),
+ PluginError {
+ message: message.trim().to_string(),
+ action: action.to_string(),
+ at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs().to_string())
+ .unwrap_or_default(),
+ },
+ );
+ save(app_handle, &map)
+}
+
+/// 清除插件错误(安装/升级/卸载成功后)
+pub fn clear(app_handle: &AppHandle, id: &str) -> Result<(), String> {
+ let mut map = load(app_handle);
+ if map.remove(id).is_some() {
+ save(app_handle, &map)?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn record_clear_round_trip() {
+ // 不依赖 AppHandle 的纯文件读写用临时目录验证序列化形态
+ let map = HashMap::from([(
+ "dshmarket".to_string(),
+ PluginError {
+ message: "ERR_PNPM_IGNORED_BUILDS".to_string(),
+ action: "install".to_string(),
+ at: "1700000000".to_string(),
+ },
+ )]);
+ let json = serde_json::to_string(&map).unwrap();
+ let back: HashMap<String, PluginError> = serde_json::from_str(&json).unwrap();
+ assert_eq!(back.get("dshmarket").unwrap().action, "install");
+ assert_eq!(back.get("dshmarket").unwrap().message, "ERR_PNPM_IGNORED_BUILDS");
+ }
+}
diff --git a/src-tauri/src/service/plugin/install.rs b/src-tauri/src/service/plugin/install.rs
index 0531525a..1c1fa428 100644
--- a/src-tauri/src/service/plugin/install.rs
+++ b/src-tauri/src/service/plugin/install.rs
@@ -12,8 +12,10 @@
use crate::config;
use crate::service::cli;
+use crate::service::core;
use crate::service::download;
use crate::service::download::Installable;
+use crate::service::profile::active_profile;
use crate::service::workflow;
use std::collections::HashMap;
use std::ffi::OsString;
@@ -21,7 +23,8 @@ use std::path::PathBuf;
use serde_yaml::{Mapping, Value};
use tauri::{AppHandle, Emitter, Manager, WebviewWindow};
-use super::installed::{PREINSTALL_PROFILE, profile_dir};
+use super::errors;
+use super::installed::profile_dir;
use super::preset::load_presets;
use super::process::{run_plugin_process, PreinstallLogPayload, PREINSTALL_LOG_EVENT};
@@ -37,7 +40,7 @@ const MAX_ALLOW_LIST_RETRIES: usize = 8;
/// 自动合成 peer 后 `No matching version found for @deepseek-ai/...` 的假失败。
const MIN_TRUSTED_PNPM_MAJOR: u32 = 10;
-/// 校验并安装选中的预装插件:`dsh plugin --profile web add <ids...>`
+/// 校验并安装选中的预装插件:`dsh plugin --profile <当前档案> add <ids...>`
pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), String> {
if ids.is_empty() {
return Err("PREINSTALL_EMPTY: no plugins selected".to_string());
@@ -66,7 +69,8 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin
cli::ensure_shims(app_handle)?;
let node = config::get_node_binary_path(app_handle);
- let dsh_bin = config::get_dsh_binary_path(app_handle);
+ // 活动核心的 dsh 入口:本地核心存在时用本地 CLI,否则预打包
+ let dsh_bin = core::active_dsh_binary(app_handle);
if !node.exists() {
return Err("NODE_NOT_FOUND: Node.js runtime missing".to_string());
}
@@ -90,51 +94,20 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin
line: "[harness] 正在停止运行中的服务(安装插件需要短暂重启)…".to_string(),
},
);
- log::info!("Stopping running harness service before installing preinstall plugins");
+ log::info!("Stopping running harness service before installing plugins");
if let Err(e) = workflow::stop(app_handle.clone()).await {
- log::warn!("failed to stop harness before preinstall: {e}");
+ log::warn!("failed to stop harness before plugin install: {e}");
}
}
- // 构建环境变量
- let bin_dir = cli::get_bin_dir(app_handle);
- let mut envs = HashMap::from([
- (
- "DSH_HOME".to_string(),
- config::get_dsh_data_path(app_handle)
- .to_string_lossy()
- .into_owned(),
- ),
- ("DSH_TELEMETRY_DISABLED".to_string(), "1".to_string()),
- ("NO_COLOR".to_string(), "1".to_string()),
- ]);
- // 用户 pnpm 过旧/不可探测时强制 pnpm shim 优先捆绑版,避免 8/9 的
- // autoInstallPeers 语义与 workspace-root gate 破坏插件安装(见 ensure_pnpm)
- if prefer_bundled_pnpm {
- envs.insert(
- "DSH_PREFER_BUNDLED_PNPM".to_string(),
- "1".to_string(),
- );
- }
-
- let mut paths = vec![bin_dir];
- if let Some(node_dir) = node.parent() {
- paths.push(node_dir.to_path_buf());
- }
- paths.extend(std::env::split_paths(
- &std::env::var_os("PATH").unwrap_or_default(),
- ));
-
- if let Ok(joined) = std::env::join_paths(paths) {
- envs.insert("PATH".to_string(), joined.to_string_lossy().into_owned());
- }
+ let envs = build_plugin_envs(app_handle, prefer_bundled_pnpm);
// 拼装命令行参数
let mut args = vec![
dsh_bin.as_os_str().to_os_string(),
OsString::from("plugin"),
OsString::from("--profile"),
- OsString::from(PREINSTALL_PROFILE),
+ OsString::from(active_profile(app_handle)),
OsString::from("add"),
];
args.extend(specs.iter().map(|s| OsString::from(s.as_str())));
@@ -182,6 +155,14 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin
// (用户环境无 SSH 配置),后者才是补充白名单可自愈的。传输层错误给出
// 可读指引,避免用户被 dsh 那条 allowBuilds 提示误导。
let hint = git_transport_hint(&last_output);
+ let message = pick_error_message(&last_output, hint);
+ // 批量安装失败时给本次选中的每个插件记一条错误(前端据此展示异常标记,
+ // 可针对单个插件重试更新/卸载)
+ for id in ids {
+ if let Err(e) = errors::record(app_handle, id, "install", &message) {
+ log::warn!("failed to record plugin error for {id}: {e}");
+ }
+ }
if let Some(hint) = hint {
log::warn!("git transport failure detected during plugin install: {hint}");
let _ = window.emit(
@@ -199,6 +180,13 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin
));
}
+ // 安装成功:清除这些插件的历史错误记录
+ for id in ids {
+ if let Err(e) = errors::clear(app_handle, id) {
+ log::warn!("failed to clear plugin error for {id}: {e}");
+ }
+ }
+
// Windows 极简模式专项修复
if ids.iter().any(|id| id == "dsh-win-terminal-inspector") {
if let Err(e) = workflow::win_inspector::apply(app_handle) {
@@ -218,35 +206,249 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin
Ok(())
}
+/// 构建 `dsh plugin` 子进程的环境变量:隔离 $DSH_HOME、关闭遥测与颜色,
+/// PATH 前置 shim 目录与 node 目录;用户 pnpm 过旧时强制捆绑版(见 ensure_pnpm)。
+fn build_plugin_envs(app_handle: &AppHandle, prefer_bundled_pnpm: bool) -> HashMap<String, String> {
+ let node = config::get_node_binary_path(app_handle);
+ let bin_dir = cli::get_bin_dir(app_handle);
+ let mut envs = HashMap::from([
+ (
+ "DSH_HOME".to_string(),
+ config::get_dsh_data_path(app_handle)
+ .to_string_lossy()
+ .into_owned(),
+ ),
+ ("DSH_TELEMETRY_DISABLED".to_string(), "1".to_string()),
+ ("NO_COLOR".to_string(), "1".to_string()),
+ ]);
+ // 用户 pnpm 过旧/不可探测时强制 pnpm shim 优先捆绑版,避免 8/9 的
+ // autoInstallPeers 语义与 workspace-root gate 破坏插件安装(见 ensure_pnpm)
+ if prefer_bundled_pnpm {
+ envs.insert("DSH_PREFER_BUNDLED_PNPM".to_string(), "1".to_string());
+ }
+
+ let mut paths = vec![bin_dir];
+ if let Some(node_dir) = node.parent() {
+ paths.push(node_dir.to_path_buf());
+ }
+ paths.extend(std::env::split_paths(
+ &std::env::var_os("PATH").unwrap_or_default(),
+ ));
+
+ if let Ok(joined) = std::env::join_paths(paths) {
+ envs.insert("PATH".to_string(), joined.to_string_lossy().into_owned());
+ }
+ envs
+}
+
+/// 升级单个插件:`dsh plugin --profile <当前档案> update <id>`
+pub async fn update(app_handle: &AppHandle, id: &str) -> Result<(), String> {
+ run_single_plugin_command(app_handle, id, "update", &["update".to_string(), id.to_string()])
+ .await
+}
+
+/// 卸载单个插件:`dsh plugin --profile <当前档案> remove <id>`
+pub async fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {
+ run_single_plugin_command(app_handle, id, "remove", &["remove".to_string(), id.to_string()])
+ .await
+}
+
+/// 执行单个插件的升级/卸载:准备环境 → 停止服务 → 运行 `dsh plugin` →
+/// 失败记录错误、成功清除错误。
+async fn run_single_plugin_command(
+ app_handle: &AppHandle,
+ id: &str,
+ action: &str,
+ sub_args: &[String],
+) -> Result<(), String> {
+ if id.is_empty() {
+ return Err("PLUGIN_EMPTY_ID: plugin id is empty".to_string());
+ }
+ let window = app_handle
+ .get_webview_window("main")
+ .ok_or("WINDOW_NOT_FOUND: main window missing")?;
+
+ cli::ensure_shims(app_handle)?;
+
+ let node = config::get_node_binary_path(app_handle);
+ let dsh_bin = core::active_dsh_binary(app_handle);
+ if !node.exists() {
+ return Err("NODE_NOT_FOUND: Node.js runtime missing".to_string());
+ }
+ if !dsh_bin.exists() {
+ return Err("HARNESS_NOT_FOUND: dsh CLI missing".to_string());
+ }
+
+ let prefer_bundled_pnpm = ensure_pnpm(app_handle, &window).await?;
+
+ // 插件操作会改写 profile,先停止运行中的服务(与安装一致)
+ if workflow::has_owned_process() {
+ let _ = window.emit(
+ PREINSTALL_LOG_EVENT,
+ PreinstallLogPayload {
+ line: format!("[harness] 正在停止运行中的服务({action}插件需要短暂重启)…"),
+ },
+ );
+ if let Err(e) = workflow::stop(app_handle.clone()).await {
+ log::warn!("failed to stop harness before plugin {action}: {e}");
+ }
+ }
+
+ let envs = build_plugin_envs(app_handle, prefer_bundled_pnpm);
+
+ let mut args = vec![
+ dsh_bin.as_os_str().to_os_string(),
+ OsString::from("plugin"),
+ OsString::from("--profile"),
+ OsString::from(active_profile(app_handle)),
+ OsString::from(action),
+ ];
+ args.extend(sub_args.iter().map(OsString::from));
+
+ let cwd = config::get_dsh_install_path(app_handle);
+ log::info!("Running dsh plugin {action} for {id}");
+ let (exit_code, output) =
+ run_plugin_process(&node, &args, &cwd, &envs, &window).await?;
+
+ if exit_code != 0 {
+ log::error!("dsh plugin {action} failed for {id} with exit code {exit_code}");
+ let message = pick_error_message(&output, git_transport_hint(&output));
+ if let Err(e) = errors::record(app_handle, id, action, &message) {
+ log::warn!("failed to record plugin error for {id}: {e}");
+ }
+ return Err(format!(
+ "PLUGIN_{}_FAILED: dsh plugin exited with code {exit_code}",
+ action.to_uppercase()
+ ));
+ }
+
+ // 成功:清除历史错误;卸载 win-terminal-inspector 时顺带清理 patch 挂载
+ if let Err(e) = errors::clear(app_handle, id) {
+ log::warn!("failed to clear plugin error for {id}: {e}");
+ }
+ if action == "remove" && id == "dsh-win-terminal-inspector" {
+ if let Err(e) = workflow::win_inspector::apply(app_handle) {
+ log::warn!("win inspector patch prune failed after remove: {e}");
+ }
+ }
+ log::info!("dsh plugin {action} succeeded for {id}");
+ Ok(())
+}
+
+/// 从 dsh/pnpm 失败输出中提取可展示的错误消息:优先 git 传输层提示;
+/// 否则挑出命中错误标记的行(最多 8 行),没有则取输出尾部,ANSI 清洗后
+/// 截断到 2000 字符。
+fn pick_error_message(output: &str, hint: Option<&str>) -> String {
+ if let Some(hint) = hint {
+ return hint.to_string();
+ }
+ let cleaned: Vec<String> = output
+ .split('\n')
+ .filter_map(|line| {
+ let trimmed = strip_ansi(line);
+ let trimmed = trimmed.trim();
+ (!trimmed.is_empty()).then(|| trimmed.to_string())
+ })
+ .filter(|line| {
+ line.contains("ERR_")
+ || line.contains("error")
+ || line.contains("Error")
+ || line.contains("failed")
+ || line.contains("✖")
+ || line.contains("warning")
+ })
+ .take(8)
+ .collect();
+ let base = if cleaned.is_empty() {
+ output.trim().to_string()
+ } else {
+ cleaned.join("\n")
+ };
+ base.chars().take(2000).collect()
+}
+
+/// 去除 ANSI 转义序列(`\x1B[...m`,含颜色/样式码)。
+fn strip_ansi(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ let mut chars = s.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == '\x1b' && chars.peek() == Some(&'[') {
+ chars.next(); // '['
+ while let Some(&n) = chars.peek() {
+ if n.is_ascii_digit() || n == ';' {
+ chars.next();
+ } else {
+ break;
+ }
+ }
+ if chars.peek() == Some(&'m') {
+ chars.next();
+ }
+ } else {
+ out.push(c);
+ }
+ }
+ out
+}
+
/// 确保插件安装使用的 pnpm 可用,返回是否应强制使用捆绑版
/// (true 时调用方注入 `DSH_PREFER_BUNDLED_PNPM=1`,pnpm shim 优先捆绑版)。
///
/// 版本感知策略,避免给已装正确 pnpm 的用户增加下载步骤:
-/// - 捆绑版已存在 → 直接用捆绑版(零额外下载,确定性最强);
-/// - 用户 pnpm 主版本 ≥ MIN_TRUSTED_PNPM_MAJOR → 复用用户 pnpm,零额外步骤;
-/// - 用户 pnpm 过旧(8/9:不读 pnpm-workspace.yaml 的 autoInstallPeers、有
-/// workspace-root gate;corepack shim 在 Node 24 上还会 ERR_INVALID_THIS 崩溃)
-/// 或版本不可探测 → 下载捆绑版并强制使用。
+/// - 档案 store 主版本已知 → 只接受与其一致的 pnpm(用户版或捆绑版)。
+/// pnpm 10 与 11 的 store 布局互不兼容(`.../store/v10` vs `v11`),用与
+/// store 主版本不一致的 pnpm 更新已装插件会直接 `ERR_PNPM_UNEXPECTED_STORE`
+/// 退出码 1 失败——升级失败的根因(此前捆绑版 v11 一存在就强制使用,
+/// 对 v10 store 的档案必然失败);
+/// - 用户 pnpm 主版本 == store 主版本 → 复用用户 pnpm,零额外步骤;
+/// - 捆绑版 pnpm 主版本 == store 主版本 → 用捆绑版(不下载);
+/// - store 未知(全新档案/未装过依赖)或无可匹配版本 → 用户 pnpm ≥ 10 优先,
+/// 否则捆绑版已存在则用,再否则下载捆绑版并强制使用。
+///
+/// 用户 pnpm 过旧(8/9:不读 pnpm-workspace.yaml 的 autoInstallPeers、有
+/// workspace-root gate;corepack shim 在 Node 24 上还会 ERR_INVALID_THIS 崩溃)
+/// 或版本不可探测 → 走捆绑版。
async fn ensure_pnpm(app_handle: &AppHandle, window: &WebviewWindow) -> Result<bool, String> {
- if config::get_pnpm_binary_path(app_handle).exists() {
- return Ok(true);
+ // 档案的 node_modules 由哪个 pnpm 主版本创建(.modules.yaml 的 storeDir 段)
+ let store_major = profile_store_major(app_handle);
+ let user_major = user_pnpm_major_version(app_handle);
+
+ // 1) store 主版本已知 → 优先选与 store 一致的 pnpm(用户版或捆绑版)
+ if let Some(store) = store_major {
+ if user_major == Some(store) {
+ log::info!("Reusing user-installed pnpm (major {store}) matching profile store");
+ return Ok(false);
+ }
+ if bundled_pnpm_major(app_handle) == Some(store) {
+ log::info!("Using bundled pnpm (major {store}) matching profile store");
+ return Ok(true);
+ }
+ log::warn!(
+ "No pnpm matches profile store major {store} (user {user_major:?}), falling back to user pnpm"
+ );
}
- match user_pnpm_major_version(app_handle) {
+ // 2) store 未知(全新档案/未装过依赖)或无可匹配版本 → 用户 pnpm ≥ 10 优先
+ match user_major {
Some(major) if major >= MIN_TRUSTED_PNPM_MAJOR => {
log::info!("Reusing user-installed pnpm (major {major}) for plugin install");
return Ok(false);
}
Some(major) => {
log::warn!(
- "User pnpm major {major} < {MIN_TRUSTED_PNPM_MAJOR} (missing autoInstallPeers/workspace-root semantics), downloading bundled pnpm"
+ "User pnpm major {major} < {MIN_TRUSTED_PNPM_MAJOR} (missing autoInstallPeers/workspace-root semantics), using bundled pnpm"
);
}
None => {
- log::warn!("User pnpm version not detectable (broken/blocked shim?), downloading bundled pnpm");
+ log::warn!("User pnpm version not detectable (broken/blocked shim?), using bundled pnpm");
}
}
+ // 捆绑版已存在 → 直接用(零额外下载);否则下载。
+ if config::get_pnpm_binary_path(app_handle).exists() {
+ return Ok(true);
+ }
+
let _ = window.emit(
PREINSTALL_LOG_EVENT,
PreinstallLogPayload {
@@ -292,6 +494,49 @@ fn user_pnpm_major_version(app_handle: &AppHandle) -> Option<u32> {
stdout.split('.').next()?.trim().parse::<u32>().ok()
}
+/// 档案 `node_modules` 使用的 pnpm store 主版本(`<profile>/node_modules/.modules.yaml`
+/// 的 `storeDir` 路径段,如 `...\store\v10` → 10)。
+///
+/// pnpm 10 与 11 的 store 布局互不兼容:用与 store 主版本不一致的 pnpm 更新
+/// 已装插件会 `ERR_PNPM_UNEXPECTED_STORE` 退出。档案尚未安装过依赖(没有
+/// node_modules)时返回 `None`,由调用方走"全新档案"逻辑。
+fn profile_store_major(app_handle: &AppHandle) -> Option<u32> {
+ let modules_yaml = profile_dir(app_handle)
+ .join("node_modules")
+ .join(".modules.yaml");
+ let content = std::fs::read_to_string(modules_yaml).ok()?;
+ parse_store_major_from_modules_yaml(&content)
+}
+
+/// 从 `.modules.yaml` 文本解析 store 主版本(纯函数,便于单测)。
+fn parse_store_major_from_modules_yaml(content: &str) -> Option<u32> {
+ let store_dir = content.lines().find_map(|line| {
+ line.trim().strip_prefix("storeDir:").map(str::trim)
+ })?;
+ // storeDir 形如 `C:\Users\xx\AppData\Local\pnpm\store\v10`,取末段 `v10` 的数字
+ let major = store_dir
+ .trim_matches(['"', '\''])
+ .rsplit(['\\', '/'])
+ .next()?
+ .strip_prefix('v')?;
+ major.parse().ok()
+}
+
+/// 捆绑版 pnpm 的主版本(读 `dependencies/pnpm/package.json` 的 version 字段);
+/// 未安装或清单缺失返回 None。
+fn bundled_pnpm_major(app_handle: &AppHandle) -> Option<u32> {
+ let manifest = config::get_pnpm_install_path(app_handle).join("package.json");
+ let content = std::fs::read_to_string(manifest).ok()?;
+ let value: serde_json::Value = serde_json::from_str(&content).ok()?;
+ value
+ .get("version")?
+ .as_str()?
+ .split('.')
+ .next()?
+ .parse()
+ .ok()
+}
+
/// 从 pnpm 失败输出中解析需写入 `allowBuilds` 的键集合:
/// - git 托管插件 prepare 被拦时,pnpm 会提示 `allowBuilds:\n <depPath>: true`,
/// 原样采纳 depPath(形式随克隆方式变化,只能是运行期报出的值);
@@ -347,7 +592,7 @@ fn extract_allow_line_key(line: &str) -> Option<String> {
Some(key.to_string())
}
-/// profile 下的 `pnpm-workspace.yaml` 路径($DSH_HOME/profiles/web)
+/// profile 下的 `pnpm-workspace.yaml` 路径($DSH_HOME/profiles/<当前档案>)
fn profile_workspace_path(app_handle: &AppHandle) -> PathBuf {
profile_dir(app_handle).join("pnpm-workspace.yaml")
}
@@ -577,7 +822,47 @@ fn git_transport_hint(output: &str) -> Option<&'static str> {
#[cfg(test)]
mod tests {
- use super::{apply_allow_build_keys, collapse_allow_builds_duplicates, extract_allow_line_key, git_transport_hint, normalize_git_spec, parse_allowlist_keys};
+ use super::{apply_allow_build_keys, collapse_allow_builds_duplicates, extract_allow_line_key, git_transport_hint, normalize_git_spec, parse_allowlist_keys, parse_store_major_from_modules_yaml};
+
+ #[test]
+ fn store_major_parsed_from_modules_yaml() {
+ // 真实 pnpm v10 写入的 .modules.yaml:storeDir 指向 store\v10
+ let content = "\
+lockfileVersion: '9.0'
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+dependencies:
+ '@deepseek-ai/dsh-base': 0.0.4
+ '@deepseek-ai/dsh-web-app': 0.0.4
+storeDir: C:\\Users\\test\\AppData\\Local\\pnpm\\store\\v10
+virtualStoreDir: node_modules/.pnpm
+";
+ assert_eq!(parse_store_major_from_modules_yaml(content), Some(10));
+ }
+
+ #[test]
+ fn store_major_supports_unix_and_quoted_paths() {
+ assert_eq!(
+ parse_store_major_from_modules_yaml("storeDir: /home/test/.local/share/pnpm/store/v11\n"),
+ Some(11)
+ );
+ assert_eq!(
+ parse_store_major_from_modules_yaml("storeDir: \"C:\\\\pnpm store\\\\v3\"\n"),
+ Some(3)
+ );
+ }
+
+ #[test]
+ fn store_major_missing_when_no_store_dir() {
+ // 档案尚未装过依赖:无 storeDir 段 → None
+ assert_eq!(parse_store_major_from_modules_yaml("lockfileVersion: '9.0'\n"), None);
+ assert_eq!(parse_store_major_from_modules_yaml(""), None);
+ assert_eq!(
+ parse_store_major_from_modules_yaml("storeDir: C:\\Users\\x\\pnpm\\store\n"),
+ None
+ );
+ }
#[test]
fn parse_git_dep_path_key() {
diff --git a/src-tauri/src/service/plugin/installed.rs b/src-tauri/src/service/plugin/installed.rs
index 6210631f..d435dfd7 100644
--- a/src-tauri/src/service/plugin/installed.rs
+++ b/src-tauri/src/service/plugin/installed.rs
@@ -1,7 +1,6 @@
//! 已安装插件检测:强类型解析 profile 下 package.json 的 `dependencies` 键与
//! `dsh.profile.bundles` 列表,得到已安装插件 id 集合,并组装前端渲染列表。
-use crate::config;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
@@ -9,9 +8,6 @@ use tauri::AppHandle;
use super::preset::{load_presets, PreinstallPluginInfo};
-/// 预装插件安装到的 profile(与 dsh 服务启动的 profile 一致)
-pub(crate) const PREINSTALL_PROFILE: &str = "web";
-
/// 用于强类型解析 profile 下 package.json 的辅助结构
/// (字段 pub(crate):供 watch 模块解析已安装插件清单复用)
#[derive(Deserialize)]
@@ -34,11 +30,15 @@ pub(crate) struct ProfileInner {
pub(crate) bundles: Vec<String>,
}
-/// 预装插件所在的 profile 目录($DSH_HOME/profiles/web)
+/// 插件所在的 profile 目录($DSH_HOME/profiles/<当前档案>)。
+///
+/// 档案由桌面端设置(`active_profile`)决定,不再写死 web;启动服务与插件
+/// 操作都以同一份「当前档案」为准(见 service::profile::active_profile)。
pub(crate) fn profile_dir(app_handle: &AppHandle) -> PathBuf {
- config::get_dsh_data_path(app_handle)
- .join("profiles")
- .join(PREINSTALL_PROFILE)
+ crate::service::profile::profile_dir_of(
+ app_handle,
+ &crate::service::profile::active_profile(app_handle),
+ )
}
/// 已安装的插件 id 集合:通过强类型反序列化读取 package.json 的 `dependencies` 键与 `bundles` 列表
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index c6e33e02..b78ad23a 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -1,9 +1,9 @@
//! 预装插件:首次启动引导安装官方推荐插件(当前为 DSH Market)。
//!
-//! 安装通过 `dsh plugin --profile web add <pkg>` 完成:该子命令是 pnpm 转发器,
-//! 会在 `$DSH_HOME/profiles/web` 初始化 profile 并执行 `pnpm add`,随后把声明了
-//! `dsh.bundle` 的依赖写入 profile 的 bundles 层,使插件在下次启动时加载。
-//! 进程输出逐行通过 `preinstall-log` 事件实时推送给前端日志面板。
+//! 安装通过 `dsh plugin --profile <当前档案> add <pkg>` 完成:该子命令是 pnpm
+//! 转发器,会在 `$DSH_HOME/profiles/<当前档案>` 初始化 profile 并执行 `pnpm add`,
+//! 随后把声明了 `dsh.bundle` 的依赖写入 profile 的 bundles 层,使插件在下次
+//! 启动时加载。进程输出逐行通过 `preinstall-log` 事件实时推送给前端日志面板。
//! 调用 dsh 前会先按需补齐捆绑 pnpm(老版本升级后可能缺失,安装流程内自愈)。
//!
//! 预设清单存放在随安装包分发的 `resources/preset-plugins.json`:社区新增推荐插件
@@ -17,12 +17,14 @@
//! 模块划分(参考 `service/cli/`、`service/download/`):
//! - [`preset`]:预设清单读取与解析(`resources/preset-plugins.json`)
//! - [`installed`]:profile 内已安装插件检测(解析 package.json 的依赖与 bundles)
-//! - [`install`]:对外安装编排(校验选中项、环境准备、调用 dsh 子进程)
+//! - [`install`]:对外安装/升级/卸载编排(校验、环境准备、调用 dsh 子进程)
+//! - [`errors`]:插件错误记录(安装/升级/卸载失败 + 页面运行期上报,持久化)
//! - [`process`]:dsh 子进程启动与输出流逐行转发
//! - [`cancel`]:Windows 下取消正在进行的安装
//! - [`watch`]:已安装插件文件监控(轮询指纹比对 + `dsh-plugins-updated` 事件推送)
mod cancel;
+pub mod errors;
mod install;
mod installed;
mod preset;
@@ -30,7 +32,7 @@ mod process;
pub mod watch;
pub use cancel::cancel;
-pub use install::install;
+pub use install::{install, remove, update};
pub use installed::{list, PreinstallPlugin};
pub(crate) use installed::ensure_profile_npmrc;
pub use preset::repo_url_of;
diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rs
index f49c335f..8d31f6df 100644
--- a/src-tauri/src/service/plugin/watch.rs
+++ b/src-tauri/src/service/plugin/watch.rs
@@ -18,6 +18,7 @@ use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter};
+use super::errors::{self, PluginError};
use super::installed::{profile_dir, ProfilePackageJson};
use super::preset::{load_presets, PreinstallPluginInfo};
@@ -47,6 +48,9 @@ pub struct DshPlugin {
pub recommended: bool,
/// 预设清单中的「修复」标记(黄色 chip)
pub fix: bool,
+ /// 异常信息(安装/升级/卸载失败或页面运行期上报);`None` = 正常
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<PluginError>,
}
/// 用于强类型解析插件自身 package.json 的辅助结构
@@ -163,15 +167,44 @@ fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPlu
bundled: bundled.contains(id.as_str()),
recommended: preset.map(|p| p.recommended).unwrap_or(false),
fix: preset.map(|p| p.fix).unwrap_or(false),
+ error: None,
})
})
.collect()
}
-/// 已安装插件列表(含解析后的元信息),前端首次加载/手动刷新用
+/// 已安装插件列表(含解析后的元信息与错误记录),前端首次加载/手动刷新用
pub fn list(app_handle: &AppHandle) -> Vec<DshPlugin> {
let presets = load_presets(app_handle);
- parse_plugins(&profile_dir(app_handle), &presets)
+ let mut plugins = parse_plugins(&profile_dir(app_handle), &presets);
+ // 合并错误注册表:错误记录变化不反映在文件指纹里,这里每次列表重建时并入
+ let registry = errors::load(app_handle);
+ for plugin in &mut plugins {
+ plugin.error = registry.get(&plugin.id).cloned();
+ }
+ plugins
+}
+
+/// 主动推送一次插件列表(插件安装/升级/卸载/错误记录后调用,不等指纹轮询
+/// 防抖;错误数据变化不改变文件指纹,必须显式推送)。
+///
+/// 同时把监控指纹同步到当前状态,避免紧接着的下一次轮询重复推送同一列表。
+pub fn force_emit(app_handle: &AppHandle) {
+ let fp = fingerprint(app_handle);
+ let mut state = STATE
+ .get_or_init(|| {
+ Mutex::new(WatchState {
+ last_fp: None,
+ last_emit: None,
+ pending_fp: None,
+ })
+ })
+ .lock()
+ .unwrap();
+ state.pending_fp = None;
+ state.last_fp = fp;
+ drop(state);
+ emit(app_handle);
}
/// 变化指纹:profile package.json 与各直接依赖插件 package.json 的内容拼接。
diff --git a/src/components/config-plugin.tsx b/src/components/config-plugin.tsx
index ac4181fc..e7164e39 100644
--- a/src/components/config-plugin.tsx
+++ b/src/components/config-plugin.tsx
@@ -1,43 +1,79 @@
-import { Card, Chip, Label, Spinner, Typography } from '@heroui/react'
+import { CircleExclamation } from '@gravity-ui/icons'
+import { Button, Card, Chip, Label, Spinner, Tooltip, Typography } from '@heroui/react'
import { useOverlay } from '@overlastic/react'
+import { useMutation } from '@tanstack/react-query'
+import { invoke } from '@tauri-apps/api/core'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { If } from 'react-if-lite'
+import { toast } from '@/utils'
import { useDshPlugins } from '../hooks/use-dsh-plugins'
import { Dialog } from './dialog'
import { Ellipsis as TextEllipsis } from './ellipsis'
/**
- * 「插件」面板:只读展示已安装插件,作为「插件出问题时」的卸载/升级入口。
+ * 「插件」面板:展示已安装插件,作为「插件出问题时」的卸载/升级入口。
*
- * 与「档案」面板保持一致:`Card` 行布局 + `Typography` 标题,行尾放交互操作,
- * 卸载用 `Dialog`(`useOverlay` holder)二次确认;异常详情因需「复制日志 +
- * 升级 + 卸载」三个动作,保留为独立 `Modal`。
- *
- * - 数据来自 `useDshPlugins`(`get_dsh_plugins` + `dsh-plugins-updated` 实时事件)。
- * - 卸载 `remove_dsh_plugin`、升级 `upgrade_dsh_plugin` 两个后端命令尚未实现,
- * 目前按需求约定接入「未来命令」(invoke 会失败并 toast 提示,不崩溃)。
- * - 「异常」标记:后端暂未提供插件错误字段,前端暂以「元信息解析失败
- * (version 为空)」粗判为异常并允许查看详情;后端落地后替换为真实 error 字段。
+ * - 数据来自 `useDshPlugins`(`get_dsh_plugins` 查询 + `dsh-plugins-updated`
+ * 实时事件,react-query 缓存同步)。
+ * - 升级 `update_dsh_plugin` / 卸载 `remove_dsh_plugin` 已接入后端
+ * (`dsh plugin --profile <当前档案> update|remove <id>`,进程输出经
+ * `preinstall-log` 事件实时推送)。
+ * - 「异常」标记:插件带 `error` 字段(安装/升级/卸载失败或页面运行期上报)
+ * 时显示 danger 图标按钮,Tooltip 展示错误详情,行内可直接升级/卸载修复。
*/
-
-interface PluginErrorDialogState {
- id: string
- name: string
- log: string
-}
-
export function ConfigPlugin() {
const { t } = useTranslation()
const { plugins, loading, error } = useDshPlugins()
const [dialogHolder, openDialog] = useOverlay(Dialog, { type: 'holder' })
- /** 升级插件(接入尚未实现的后端命令) */
- async function onUpgrade(_id: string, _source?: PluginErrorDialogState) {
+ /** 行内操作进行中状态:id + 操作类型(update/remove),保证单例运行 */
+ const [busy, setBusy] = useState<{ id: string, action: 'update' | 'remove' } | null>(null)
+
+ const upgrade = useMutation({
+ mutationFn: (id: string) => invoke<void>('update_dsh_plugin', { id }),
+ onSuccess: (_data, id) => {
+ const name = plugins.find(p => p.id === id)?.name ?? id
+ toast(t('plugins.updated_toast', { name }), {})
+ },
+ onError: (err, id) => {
+ const name = plugins.find(p => p.id === id)?.name ?? id
+ console.error('[ConfigPlugin] upgrade failed:', err)
+ toast(t('plugins.upgrade_failed', { name }), {})
+ },
+ })
+ const remove = useMutation({
+ mutationFn: (id: string) => invoke<void>('remove_dsh_plugin', { id }),
+ onSuccess: (_data, id) => {
+ const name = plugins.find(p => p.id === id)?.name ?? id
+ toast(t('plugins.removed_toast', { name }), {})
+ },
+ onError: (err, id) => {
+ const name = plugins.find(p => p.id === id)?.name ?? id
+ console.error('[ConfigPlugin] remove failed:', err)
+ toast(t('plugins.remove_failed', { name }), {})
+ },
+ })
+
+ async function onUpgrade(id: string) {
+ if (busy)
+ return
+ setBusy({ id, action: 'update' })
+ try {
+ await upgrade.mutateAsync(id)
+ }
+ catch {
+ // 错误提示已由 mutation 的 onError 处理
+ }
+ finally {
+ setBusy(null)
+ }
}
- /** 卸载插件(接入尚未实现的后端命令) */
async function onRemove(id: string, name: string) {
+ if (busy)
+ return
await openDialog({
status: 'danger',
title: t('plugins.remove_confirm_title'),
@@ -48,7 +84,16 @@ export function ConfigPlugin() {
),
confirmText: t('plugins.uninstall'),
})
- // TODO: 实现卸载逻辑
+ setBusy({ id, action: 'remove' })
+ try {
+ await remove.mutateAsync(id)
+ }
+ catch {
+ // 错误提示已由 mutation 的 onError 处理
+ }
+ finally {
+ setBusy(null)
+ }
}
return (
@@ -96,18 +141,31 @@ export function ConfigPlugin() {
{plugins.map(plugin => (
<Card key={plugin.id} className="rounded-md bg-[#f5f5f5] py-3">
<Card.Content className="flex flex-row items-center justify-between">
- <div>
+ <div className="min-w-0">
<div className="flex min-w-0 items-center gap-1">
- {/* TODO: 检测该插件异常时显示
- <Button
- isIconOnly
- size="sm"
- variant="ghost"
- className="size-6 shrink-0 rounded-md text-danger"
- aria-label={t('plugins.abnormal_tooltip')}
- >
- <CircleExclamation />
- </Button> */}
+ <If cond={plugin.error != null}>
+ <Tooltip delay={0}>
+ <Button
+ isIconOnly
+ size="sm"
+ variant="ghost"
+ className="size-6 shrink-0 rounded-md text-danger"
+ aria-label={t('plugins.abnormal_tooltip')}
+ >
+ <CircleExclamation />
+ </Button>
+ <Tooltip.Content className="max-w-[320px]">
+ <div className="space-y-1">
+ <p className="text-xs font-medium">
+ {t('plugins.abnormal_desc', { name: plugin.name })}
+ </p>
+ <p className="whitespace-pre-wrap break-all font-mono text-[11px] opacity-80">
+ {plugin.error?.message}
+ </p>
+ </div>
+ </Tooltip.Content>
+ </Tooltip>
+ </If>
<Label className="min-w-0 truncate text-sm font-medium text-ink">
{plugin.name}
</Label>
@@ -125,25 +183,36 @@ export function ConfigPlugin() {
</div>
<div className="flex shrink-0 items-center gap-1.5">
- <If cond={true /* isNewUpgrade */}>
+ {/* 更新入口仅在插件异常时显示(需求 2:异常插件的修复入口) */}
+ <If cond={plugin.error != null}>
<Chip
- className="rounded-md cursor-pointer"
+ className={`rounded-md${busy ? ' cursor-not-allowed opacity-50' : ' cursor-pointer'}`}
variant="primary"
color="accent"
- onClick={() => onUpgrade(plugin.id)}
size="sm"
+ onClick={() => onUpgrade(plugin.id)}
>
- 更新
+ <span className="flex items-center gap-1">
+ {busy?.id === plugin.id && busy.action === 'update'
+ ? <Spinner size="sm" color="current" />
+ : null}
+ {t('plugins.upgrade')}
+ </span>
</Chip>
</If>
<Chip
- className="rounded-md cursor-pointer"
+ className={`rounded-md${busy ? ' cursor-not-allowed opacity-50' : ' cursor-pointer'}`}
variant="primary"
color="danger"
size="sm"
onClick={() => onRemove(plugin.id, plugin.name)}
>
- 卸载
+ <span className="flex items-center gap-1">
+ {busy?.id === plugin.id && busy.action === 'remove'
+ ? <Spinner size="sm" color="current" />
+ : null}
+ {t('plugins.uninstall')}
+ </span>
</Chip>
</div>
</Card.Content>
diff --git a/src/hooks/use-dsh-plugins.ts b/src/hooks/use-dsh-plugins.ts
index 5ada633e..33b9b028 100644
--- a/src/hooks/use-dsh-plugins.ts
+++ b/src/hooks/use-dsh-plugins.ts
@@ -1,7 +1,18 @@
import type { UnlistenFn } from '@tauri-apps/api/event'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
import { invoke } from '@tauri-apps/api/core'
import { listen } from '@tauri-apps/api/event'
-import { useEffect, useState } from 'react'
+import { useEffect } from 'react'
+
+/** Rust 侧 service::plugin::watch::DshPlugin 的序列化形态(camelCase) */
+export interface PluginErrorInfo {
+ /** 错误消息(pnpm/运行日志片段) */
+ message: string
+ /** 记录动作:install / update / remove / runtime */
+ action: string
+ /** 记录时间(unix 秒级时间戳字符串) */
+ at: string
+}
/** Rust 侧 service::plugin::watch::DshPlugin 的序列化形态(camelCase) */
export interface DshPlugin {
@@ -20,6 +31,8 @@ export interface DshPlugin {
recommended: boolean
/** 预设清单中的「修复」标记 */
fix: boolean
+ /** 异常信息(安装/升级/卸载失败或页面运行期上报);undefined = 正常 */
+ error?: PluginErrorInfo | null
}
export interface UseDshPluginsResult {
@@ -31,73 +44,56 @@ export interface UseDshPluginsResult {
}
/**
- * 已安装 dsh 插件列表(实时同步)。
+ * 已安装 dsh 插件列表(react-query 实时同步)。
*
* 后端(`service/plugin/watch`)秒级监控 profile 插件文件(package.json +
* node_modules 下各直接依赖清单),解析出插件元信息;首次加载走
- * `get_dsh_plugins` 命令,之后插件安装/卸载/升级时通过
- * `dsh-plugins-updated` 事件增量推送,无需轮询。
+ * `get_dsh_plugins` 查询,之后插件安装/卸载/升级/错误记录时通过
+ * `dsh-plugins-updated` 事件推送完整列表,直接写入查询缓存(无需重新拉取)。
+ *
+ * 查询键 `['plugins']`:插件操作(升级/卸载)成功后会失效重拉,确保与后端
+ * 错误注册表等非文件态数据保持一致。
*/
export function useDshPlugins(): UseDshPluginsResult {
- const [plugins, setPlugins] = useState<DshPlugin[]>([])
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
+ const queryClient = useQueryClient()
+
+ const { data, isLoading, error, refetch } = useQuery({
+ queryKey: ['plugins'],
+ queryFn: () => invoke<DshPlugin[]>('get_dsh_plugins'),
+ })
+ // 订阅后端实时推送:事件载荷即完整列表,直接写入缓存避免多余的往返拉取
useEffect(() => {
let unlisten: UnlistenFn | null = null
let disposed = false
- function apply(list: DshPlugin[]) {
- if (disposed)
- return
- setPlugins(list)
- setLoading(false)
- setError('')
- }
-
- function fail(err: unknown) {
- if (disposed)
- return
- console.error('[useDshPlugins] failed to load plugins:', err)
- setError(String(err))
- setLoading(false)
- }
-
- // 先订阅事件再拉取初始值,避免两者之间的插件变化丢失
listen<DshPlugin[]>('dsh-plugins-updated', (event) => {
- apply(event.payload)
- }).then((fn) => {
if (disposed)
- fn()
- else
- unlisten = fn
- }).catch((err) => {
- console.error('[useDshPlugins] failed to listen dsh-plugins-updated:', err)
+ return
+ queryClient.setQueryData(['plugins'], event.payload)
})
-
- invoke<DshPlugin[]>('get_dsh_plugins').then(apply).catch(fail)
+ .then((fn) => {
+ if (disposed)
+ fn()
+ else
+ unlisten = fn
+ })
+ .catch((err) => {
+ console.error('[useDshPlugins] failed to listen dsh-plugins-updated:', err)
+ })
return () => {
disposed = true
unlisten?.()
}
- }, [])
+ }, [queryClient])
- async function refresh() {
- setLoading(true)
- try {
- const list = await invoke<DshPlugin[]>('get_dsh_plugins')
- setPlugins(list)
- setError('')
- }
- catch (err) {
- console.error('[useDshPlugins] refresh failed:', err)
- setError(String(err))
- }
- finally {
- setLoading(false)
- }
+ return {
+ plugins: data ?? [],
+ loading: isLoading,
+ error: error ? String(error) : '',
+ refresh: async () => {
+ await refetch()
+ },
}
-
- return { plugins, loading, error, refresh }
}
diff --git a/src/hooks/use-iframe-shim.ts b/src/hooks/use-iframe-shim.ts
index 775ca5fb..0c17449d 100644
--- a/src/hooks/use-iframe-shim.ts
+++ b/src/hooks/use-iframe-shim.ts
@@ -4,6 +4,7 @@ import { listen } from '@tauri-apps/api/event'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { useEffect } from 'react'
import { useEvent, useInterval, useMountedState } from 'react-use'
+import { queryClient } from '@/config/client'
import { getIframeOrigin } from '@/utils/iframe-origin'
interface NativeNotificationMessage {
@@ -16,6 +17,18 @@ interface NativeNotificationMessage {
requireInteraction?: boolean
}
+/** iframe 插件异常上报消息(dsh-tauri 桥 / 页面脚本 postMessage 通道) */
+interface PluginErrorMessage {
+ source?: 'dsh-plugin-error-bridge'
+ type?: string
+ /** 插件 id(npm 包名) */
+ id?: string
+ /** 异常消息 */
+ error?: string
+ /** 记录动作:runtime / install / update(默认 runtime) */
+ action?: string
+}
+
export function useIframeShim(iframeRef: RefObject<HTMLIFrameElement | null>) {
const isMounted = useMountedState()
@@ -47,7 +60,39 @@ export function useIframeShim(iframeRef: RefObject<HTMLIFrameElement | null>) {
}).catch(error => console.error('[notification] show_native_notification failed:', error))
}
+ // 接收 iframe 的「插件异常上报」:记录到后端错误注册表并刷新插件列表。
+ // 内嵌页面(或 dsh-tauri 扩展)捕获插件运行期异常后,以
+ // `{ source: 'dsh-plugin-error-bridge', type: 'dsh://plugin-error', id, error }`
+ // postMessage 到宿主,宿主经 `report_plugin_error` 持久化并推送新列表,
+ // 「插件」面板据此展示 danger 图标与更新/卸载入口。
+ function handlePluginError(event: MessageEvent<PluginErrorMessage>) {
+ const data = event.data
+ if (!data || typeof data !== 'object' || data.source !== 'dsh-plugin-error-bridge') {
+ return
+ }
+ if (event.source !== iframeRef.current?.contentWindow) {
+ return
+ }
+ const iframeOrigin = getIframeOrigin(iframeRef)
+ if (!iframeOrigin || event.origin !== iframeOrigin) {
+ return
+ }
+ if (data.type !== 'dsh://plugin-error' || !data.id || !data.error) {
+ return
+ }
+ void invoke('report_plugin_error', {
+ id: data.id,
+ error: data.error,
+ action: data.action ?? 'runtime',
+ })
+ .then(() => {
+ void queryClient.invalidateQueries({ queryKey: ['plugins'] })
+ })
+ .catch(error => console.error('[plugin-error] report_plugin_error failed:', error))
+ }
+
useEvent('message', handleMessage)
+ useEvent('message', handlePluginError)
// 系统通知点击 → 通知 iframe 聚焦对应会话
useEffect(() => {
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 1fa01d1c..30c99072 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -164,8 +164,10 @@
"plugins.error_log": "Error log",
"plugins.remove_confirm_title": "Uninstall plugin",
"plugins.remove_confirm_desc": "Uninstall {{name}}? Its features will no longer be available after removal.",
- "plugins.remove_failed": "Uninstall failed — the backend command is not wired up yet.",
- "plugins.upgrade_failed": "Upgrade failed — the backend command is not wired up yet.",
+ "plugins.remove_failed": "Failed to uninstall {{name}}",
+ "plugins.upgrade_failed": "Failed to upgrade {{name}}",
+ "plugins.updated_toast": "Plugin {{name}} updated",
+ "plugins.removed_toast": "Plugin {{name}} uninstalled",
"plugins.close": "Close",
"plugins.copy_failed": "Failed to copy the error log",
"core.title": "Harness Core",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 5e45cae4..3c4920c6 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -164,8 +164,10 @@
"plugins.error_log": "错误日志",
"plugins.remove_confirm_title": "卸载插件",
"plugins.remove_confirm_desc": "确定卸载插件 {{name}} 吗?卸载后其功能将不可用。",
- "plugins.remove_failed": "卸载失败(后端命令尚未接入)。",
- "plugins.upgrade_failed": "升级失败(后端命令尚未接入)。",
+ "plugins.remove_failed": "卸载插件 {{name}} 失败",
+ "plugins.upgrade_failed": "升级插件 {{name}} 失败",
+ "plugins.updated_toast": "插件 {{name}} 已更新",
+ "plugins.removed_toast": "插件 {{name}} 已卸载",
"plugins.close": "关闭",
"plugins.copy_failed": "复制错误日志失败",
"core.title": "核心引擎",
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index 8dd9f115..bd9f2e8f 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -254,6 +254,7 @@ export const harness = defineStore({
void queryClient.invalidateQueries({ queryKey: ['config'] })
void queryClient.invalidateQueries({ queryKey: ['cli_status'] })
// 档案/核心切换后重启:当前档案的插件列表、核心来源状态一并刷新
+ void queryClient.invalidateQueries({ queryKey: ['plugins'] })
void queryClient.invalidateQueries({ queryKey: ['profiles'] })
void queryClient.invalidateQueries({ queryKey: ['cores'] })
}