Skip to content

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

feat(plugin): self-heal internal plugins at boot and mark built-ins in UI

hairyf3722966c1087
diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rs
index 04e1d365..659173b3 100644
--- a/src-tauri/src/bridge/plugin.rs
+++ b/src-tauri/src/bridge/plugin.rs
@@ -52,6 +52,19 @@ pub async fn skip_preinstall_plugins(app_handle: AppHandle) -> Result<(), String
Ok(())
}
+/// 内置插件启动自愈(供前端 boot 流程调用,独立于预装引导「继续/跳过」)。
+///
+/// 与 service 启动路径(`workflow::launch` 内)共用 `plugin::ensure_internal_plugins`
+/// 同一实现:内部有并发锁、幂等,此后启动/重启路径会再核对但均为 no-op。
+/// 最佳努力:失败只记告警,不阻断启动;前端据此在「Loading internal plugins…」
+/// 与「Loading plugins…」之间切换加载屏文案。
+#[tauri::command]
+pub async fn ensure_internal_plugins(app_handle: AppHandle) {
+ if let Err(e) = plugin::ensure_internal_plugins(&app_handle).await {
+ log::warn!("ensure internal plugins via bridge failed: {e}");
+ }
+}
+
/// 是否有新的预装插件需要引导:预设清单内容与上次记录不一致(或老用户无基线)。
/// 资源文件每次安装都被强制覆盖不可比对,只能比对 app-data 里记录的内容指纹。
#[tauri::command]
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 4f120002..d7623b7b 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -412,6 +412,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::install_preinstall_plugins,
crate::bridge::cancel_preinstall_plugins,
crate::bridge::skip_preinstall_plugins,
+ crate::bridge::ensure_internal_plugins,
crate::bridge::open_preinstall_repo,
crate::bridge::get_dsh_plugins,
crate::bridge::refresh_plugin_updates,
diff --git a/src-tauri/src/service/plugin/internal.rs b/src-tauri/src/service/plugin/internal.rs
index e6db6493..b3581cd5 100644
--- a/src-tauri/src/service/plugin/internal.rs
+++ b/src-tauri/src/service/plugin/internal.rs
@@ -11,15 +11,28 @@
//! 要求——用户怎么卸载、何时卸载都不影响下次启动自动恢复,无需任何用户操作。
use std::collections::HashMap;
-use tauri::AppHandle;
+use tauri::{AppHandle, Emitter};
use super::installed::{installed_name, profile_dir, ProfilePackageJson};
-use super::preset::{bundled_plugin_dir, file_dep_spec, load_presets};
+use super::preset::{bundled_dep_spec, bundled_plugin_dir, load_presets, PreinstallPluginInfo};
/// 核对并强制安装缺失/路径不正确/被卸载的内置插件,在服务进程启动前调用。
///
/// 最佳努力:任何失败只记告警(调用方不阻断启动);捆绑目录缺失(开发环境未跑
/// prebuild)时跳过,交由常规引导流程处理;批量待装列表为空则不触发任何安装。
+/// 内置插件阶段事件载荷:「loading」= 核对/安装进行中(前端加载屏显示
+/// `status.loading_internal`),「done」= 结束(回到常规 `status.loading`)。
+#[derive(serde::Serialize, Clone)]
+struct InternalPluginsPhase {
+ phase: &'static str,
+}
+
+/// 串行化内置插件核对/安装:auto_start(Rust 侧 start→launch)与前端 boot 流程
+/// (新增的 boot 期 ensure 命令)可能并发触发,而安装会启动 `dsh plugin add`
+/// 子进程——两个 pnpm 抢同一档案目录会互相打断。若另一路正在执行,这里等它
+/// 完成后再核对(幂等:上次已装好则本轮全部 no-op)。
+static ENSURE_LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
+
pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {
let presets = load_presets(app_handle);
let internal: Vec<_> = presets.iter().filter(|p| p.internal).collect();
@@ -27,6 +40,28 @@ pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {
return Ok(());
}
+ let _guard = ENSURE_LOCK
+ .get_or_init(|| tokio::sync::Mutex::new(()))
+ .lock()
+ .await;
+ // 前端据此在「Loading internal plugins…」与「Loading plugins…」间切换;
+ // 事件在服务进程启动前发出,于健康轮询期间到达,先于 dsh 自家的 boot 输出。
+ let _ = app_handle.emit("internal-plugins-phase", InternalPluginsPhase { phase: "loading" });
+ let outcome = ensure_inner(app_handle, &internal).await;
+ let _ = app_handle.emit("internal-plugins-phase", InternalPluginsPhase { phase: "done" });
+ outcome
+}
+
+/// 实际的核对与安装:遍历 internal 预设,未安装 / 路径不对 / 被卸载 → 批量重装。
+async fn ensure_inner(
+ app_handle: &AppHandle,
+ internal: &[&PreinstallPluginInfo],
+) -> Result<(), String> {
+ log::info!(
+ "checking {} internal preset plugins for install state",
+ internal.len()
+ );
+
// 一次读取当前档案的依赖声明;档案未初始化(package.json 缺失/损坏)时按
// 「全部缺失」处理,由安装流程自行初始化。
let manifest_path = profile_dir(app_handle).join("package.json");
@@ -40,7 +75,7 @@ pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {
let profile = profile_dir(app_handle);
let mut need: Vec<String> = Vec::new();
- for preset in &internal {
+ for preset in internal {
let Some(bundled) = bundled_plugin_dir(app_handle, &preset.id) else {
// 未找到内置插件目录:release 说明构建期 prebuild 未拉取(发布缺陷,
// 由 prebuild 响亮失败);debug 可用 .env 的 DEV_INTERNAL_PLUGINS_DIR
@@ -52,7 +87,7 @@ pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {
continue;
};
let name = installed_name(preset).to_string();
- let expected = file_dep_spec(&bundled);
+ let expected = bundled_dep_spec(&bundled);
// ① 依赖声明:未声明,或声明的值不再指向当前捆绑目录(路径变更/被改
// 写)→ 重装;② 依赖真实性:node_modules 链接/拷贝须真实存在(用户
// 手动清过 node_modules 时声明可能残留但产物已不在)→ 重装。
@@ -80,13 +115,16 @@ pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {
Ok(())
}
-/// 判断 pnpm 写入 profile 的依赖值与期望的 `file:` 捆绑路径是否一致。
+/// 判断 pnpm 写入 profile 的依赖值与期望的 `link:` 捆绑路径是否一致。
///
-/// 容忍:`file:` 前缀缺失/存在两种写法;Windows 下路径大小写不敏感;尾部斜杠
-/// 差异(pnpm 各版本落盘形式略有出入)。
+/// 容忍:`link:`/`file:` 前缀缺失或两者混写(历史遗留 `file:` 安装值);Windows
+/// 下路径大小写不敏感;尾部斜杠差异(pnpm 各版本落盘形式略有出入)。
fn dep_matches_spec(actual: &str, expected: &str) -> bool {
let norm = |spec: &str| {
- let stripped = spec.strip_prefix("file:").unwrap_or(spec);
+ let stripped = spec
+ .strip_prefix("link:")
+ .or_else(|| spec.strip_prefix("file:"))
+ .unwrap_or(spec);
stripped.replace('\\', "/").trim_end_matches('/').to_string()
};
let actual = norm(actual);
@@ -104,44 +142,49 @@ mod tests {
#[test]
fn dep_spec_matches_itself() {
- let expected = "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri";
+ let expected = "link:C:/Apps/dsh/resources/preset-plugins/dsh-tauri";
// 与自身一致
assert!(dep_matches_spec(expected, expected));
- // 无 file: 前缀(pnpm 某些场景直接落路径)
+ // 无 link:/file: 前缀(pnpm 某些场景直接落路径)
assert!(dep_matches_spec(
"C:/Apps/dsh/resources/preset-plugins/dsh-tauri",
expected
));
// 尾部斜杠差异
assert!(dep_matches_spec(
- "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri/",
+ "link:C:/Apps/dsh/resources/preset-plugins/dsh-tauri/",
expected
));
// 反斜杠(Windows 原生形式)
assert!(dep_matches_spec(
- "file:C:\\Apps\\dsh\\resources\\preset-plugins\\dsh-tauri",
+ "link:C:\\Apps\\dsh\\resources\\preset-plugins\\dsh-tauri",
+ expected
+ ));
+ // 历史遗留 file: 形式(协议切换前已安装的值)
+ assert!(dep_matches_spec(
+ "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri",
expected
));
}
#[test]
fn dep_spec_rejects_wrong_path_or_source() {
- let expected = "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri";
- // 仍指向 npm 版本(用户手动从 npm 安装,非捆绑 file: 源)
+ let expected = "link:C:/Apps/dsh/resources/preset-plugins/dsh-tauri";
+ // 仍指向 npm 版本(用户手动从 npm 安装,非捆绑 link: 源)
assert!(!dep_matches_spec("[email protected]", expected));
// 指向其它位置(旧版本安装目录等)
- assert!(!dep_matches_spec("file:D:/elsewhere/dsh-tauri", expected));
+ assert!(!dep_matches_spec("link:D:/elsewhere/dsh-tauri", expected));
// 同名不同宿主盘符
- assert!(!dep_matches_spec("file:D:/Apps/dsh/resources/preset-plugins/dsh-tauri", expected));
+ assert!(!dep_matches_spec("link:D:/Apps/dsh/resources/preset-plugins/dsh-tauri", expected));
}
#[cfg(windows)]
#[test]
fn dep_spec_case_insensitive_on_windows() {
// Windows 文件系统大小写不敏感,路径比较须忽略大小写
- let expected = "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri";
+ let expected = "link:C:/Apps/dsh/resources/preset-plugins/dsh-tauri";
assert!(dep_matches_spec(
- "file:c:/apps/DSH/resources/preset-plugins/Dsh-Tauri",
+ "link:c:/apps/DSH/resources/preset-plugins/Dsh-Tauri",
expected
));
}
diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rs
index a89720de..de8951c7 100644
--- a/src-tauri/src/service/plugin/watch.rs
+++ b/src-tauri/src/service/plugin/watch.rs
@@ -19,7 +19,7 @@ use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter};
use super::errors::{self, PluginError};
-use super::installed::{profile_dir, ProfilePackageJson};
+use super::installed::{installed_name, profile_dir, ProfilePackageJson};
use super::preset::{load_presets, PreinstallPluginInfo};
/// 前端监听的事件名(插件列表变化时推送)
@@ -48,6 +48,8 @@ pub struct DshPlugin {
pub recommended: bool,
/// 预设清单中的「修复」标记(黄色 chip)
pub fix: bool,
+ /// 预设清单中的「内置」标记(随包分发/本地热更新,前端据此隐藏卸载入口并标注)
+ pub internal: bool,
/// 是否有可用更新(由 `service::plugin::update` 探测;尚未判定时为 false,
/// 前端在挂载后经 `refresh_plugin_updates` 补齐——因此有更新时才显示升级按钮,
/// 不会「常驻」)
@@ -135,6 +137,14 @@ fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPlu
let preset_map: HashMap<&str, &PreinstallPluginInfo> =
presets.iter().map(|p| (p.id.as_str(), p)).collect();
+ // 内置插件按真实依赖键(installed_name:package 优先否则 id)归集,
+ // 与 `internal.rs::ensure` 的安装/自愈口径一致
+ let internal_names: HashSet<String> = presets
+ .iter()
+ .filter(|p| p.internal)
+ .map(|p| installed_name(p).to_string())
+ .collect();
+
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()));
@@ -174,6 +184,7 @@ 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),
+ internal: internal_names.contains(id.as_str()),
update_available: false,
latest_version: None,
error: None,
@@ -407,6 +418,45 @@ mod tests {
std::fs::remove_dir_all(&dir).ok();
}
+ #[test]
+ fn parse_plugins_marks_internal_presets() {
+ let dir = build_profile(
+ "internal",
+ &[
+ (
+ "dsh-tauri",
+ r#"{"name":"dsh-tauri","version":"0.2.0","description":"bridge"}"#,
+ ),
+ (
+ "dshmarket",
+ r#"{"name":"dshmarket","version":"1.13.1"}"#,
+ ),
+ ],
+ );
+ let mut presets = presets_for_test();
+ presets.push(PreinstallPluginInfo {
+ id: "dsh-tauri".into(),
+ spec: "[email protected]".into(),
+ name: "DSH Tauri".into(),
+ description: "Message bridge".into(),
+ repo_url: "https://github.com/dsh-tauri-desk/dsh-tauri".into(),
+ recommended: true,
+ fix: false,
+ default_checked: false,
+ win_only: false,
+ package: None,
+ internal: true,
+ });
+ let plugins = parse_plugins(&dir, &presets);
+ assert_eq!(plugins.len(), 2);
+ let tauri = plugins.iter().find(|p| p.id == "dsh-tauri").unwrap();
+ assert!(tauri.internal);
+ let market = plugins.iter().find(|p| p.id == "dshmarket").unwrap();
+ assert!(!market.internal);
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
#[test]
fn parse_plugins_returns_empty_without_manifest() {
let dir = std::env::temp_dir().join(format!("dsh-watch-empty-{}", std::process::id()));
diff --git a/src/components/config-plugin.tsx b/src/components/config-plugin.tsx
index 983bab7e..a1fc0c1b 100644
--- a/src/components/config-plugin.tsx
+++ b/src/components/config-plugin.tsx
@@ -154,7 +154,7 @@ export function ConfigPlugin() {
)}
>
<div className="space-y-3 flex-wrap gap-2">
- {plugins.map(plugin => (
+ {plugins.sort(a => a.internal ? -1 : 1).map(plugin => (
<Item
key={plugin.id}
left={(
@@ -191,6 +191,11 @@ export function ConfigPlugin() {
{plugin.version}
</code>
</If>
+ <If cond={plugin.internal}>
+ <code className="shrink-0 rounded bg-default px-1.5 py-0.5 font-mono text-[10px] text-muted">
+ {t('plugins.builtin')}
+ </code>
+ </If>
</div>
<If cond={plugin.description !== ''}>
<TextEllipsis lineClamp={2} className="text-xs text-muted">
@@ -220,18 +225,20 @@ export function ConfigPlugin() {
</span>
</Chip>
</If>
- <Chip
- 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">
- <If cond={busy?.id === plugin.id && busy.action === 'remove'} then={<Spinner size="sm" color="current" />} />
- {t('plugins.uninstall')}
- </span>
- </Chip>
+ <If cond={!plugin.internal}>
+ <Chip
+ 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">
+ <If cond={busy?.id === plugin.id && busy.action === 'remove'} then={<Spinner size="sm" color="current" />} />
+ {t('plugins.uninstall')}
+ </span>
+ </Chip>
+ </If>
</>
)}
/>
diff --git a/src/hooks/use-dsh-plugins.ts b/src/hooks/use-dsh-plugins.ts
index 470a54d0..351e5134 100644
--- a/src/hooks/use-dsh-plugins.ts
+++ b/src/hooks/use-dsh-plugins.ts
@@ -31,6 +31,8 @@ export interface DshPlugin {
recommended: boolean
/** 预设清单中的「修复」标记 */
fix: boolean
+ /** 预设清单中的「内置」标记(随包分发/本地热更新):隐藏卸载入口并标注 [内置] */
+ internal: boolean
/** 是否有可用更新(由 `service::plugin::updates` 探测;未判定时为 false) */
updateAvailable: boolean
/** 判定得到的「最新版本」(registry latest / git HEAD SHA);未判定时缺省 */
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 5cd21499..7d60af04 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -12,6 +12,7 @@
"status.error": "Startup failed",
"status.loading": "Loading plugins…",
"status.loading_plugins": "Loading plugins…",
+ "status.loading_internal": "Loading internal plugins…",
"preinstall.title": "Install recommended plugins",
"preinstall.subtitle": "Choose which plugins to install before starting. You can manage them later from Settings → Plugin Market.",
"preinstall.recommend": "Recommended",
@@ -123,6 +124,7 @@
"plugins.panel_tooltip": "Installed plugins, read-only. Plugins normally need no management here — upgrade or uninstall one only when it is causing problems.",
"plugins.uninstall": "Uninstall",
"plugins.upgrade": "Upgrade",
+ "plugins.builtin": "Built-in",
"plugins.abnormal_tooltip": "This plugin is running abnormally. Click to view details.",
"plugins.abnormal_desc": "Plugin {{name}} is abnormal and may be corrupted or incompatible with the current environment.",
"plugins.remove_confirm_title": "Uninstall plugin",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 462839f2..fd880dec 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -12,6 +12,7 @@
"status.error": "启动失败",
"status.loading": "Loading plugins…",
"status.loading_plugins": "Loading plugins…",
+ "status.loading_internal": "正在加载内置插件…",
"preinstall.title": "安装推荐插件",
"preinstall.subtitle": "选择要在启动前安装的插件,之后也可以在设置中的插件市场里管理。",
"preinstall.recommend": "推荐",
@@ -123,6 +124,7 @@
"plugins.panel_tooltip": "该面板只读展示已安装插件。插件通常无需在此管理;仅当某个插件出现问题时,才需要在这里升级或卸载它。",
"plugins.uninstall": "卸载",
"plugins.upgrade": "升级",
+ "plugins.builtin": "内置",
"plugins.abnormal_tooltip": "此插件运行异常,点击查看详情。",
"plugins.abnormal_desc": "插件 {{name}} 运行异常,可能已损坏或与当前环境不兼容。",
"plugins.remove_confirm_title": "卸载插件",
diff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsx
index 182604d7..f538541f 100644
--- a/src/layout/components/webview.tsx
+++ b/src/layout/components/webview.tsx
@@ -23,6 +23,7 @@ export function Webview() {
const {
status,
serviceHealthy,
+ internalLoading,
iframeError,
iframeKey,
iframeSrc,
@@ -79,7 +80,7 @@ export function Webview() {
<div className="relative min-h-0 flex-1">
<If
cond={serviceHealthy}
- else={<Loadable subtitle={t('status.loading')} />}
+ else={<Loadable subtitle={internalLoading ? t('status.loading_internal') : t('status.loading')} />}
>
<iframe
key={iframeKey}
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index f4d976b0..e4e8dc40 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -3,6 +3,7 @@ import type { UnlistenFn } from '@tauri-apps/api/event'
import type {
InstallerState,
InstallProgress,
+ InternalPluginsPhasePayload,
PluginRecoveryInfo,
PreinstallLogPayload,
PreinstallPlugin,
@@ -180,6 +181,8 @@ export const harness = defineStore({
iframeKey: 0,
serviceHealthy: false,
serviceRunning: false,
+ /** 内置插件核对/安装阶段:加载屏在「Loading internal plugins…」与「Loading plugins…」间切换 */
+ internalLoading: false,
busyAction: null as SidebarBusyAction,
}),
actions: {
@@ -189,6 +192,7 @@ export const harness = defineStore({
return
bootStarted = true
void this.listenPluginRecovery()
+ void this.listenInternalPhase()
void this.boot()
},
@@ -207,6 +211,22 @@ export const harness = defineStore({
}
},
+ /**
+ * 订阅后端「内置插件核对阶段」推送:`internal-plugins-phase` 事件
+ * (loading / done),加载屏据此在「Loading internal plugins…」与
+ * 「Loading plugins…」之间切换。事件在服务启动前发出,健康轮询期间到达。
+ */
+ async listenInternalPhase() {
+ try {
+ await listen<InternalPluginsPhasePayload>('internal-plugins-phase', (event) => {
+ this.internalLoading = event.payload.phase === 'loading'
+ })
+ }
+ catch (err) {
+ console.error('[Harness] failed to listen internal-plugins-phase:', err)
+ }
+ },
+
/** 刷新 iframe:清除加载态并延迟重新挂载 */
refreshIframe() {
this.iframeLoaded = false
@@ -357,6 +377,19 @@ export const harness = defineStore({
await invoke('install_dependencies')
}
+ // 内置插件自愈(独立于预装引导):无论是否进入预装页、点不点「继续/跳过」,
+ // 都在启动阶段先把内置插件核对/安装到位——加载屏先显示「Loading internal
+ // plugins…」(此处乐观置位消除文案闪跳,后端 internal-plugins-phase 事件为
+ // 权威信号),确保「下一步先加载内部插件」。后端幂等且不阻断:失败仅告警。
+ this.internalLoading = true
+ try {
+ await invoke('ensure_internal_plugins')
+ }
+ catch (err) {
+ console.error('[Harness] ensure internal plugins failed (best-effort):', err)
+ }
+ this.internalLoading = false
+
// 预装插件引导:首次安装、老版本升级(无指纹基线)或 preset-plugins.json
// 内容变更(社区新增推荐插件)时重新进入预设流程,装完/跳过后才拉起服务。
// preset-plugins.json 随安装包发布、每次安装被强制覆盖,旧文件不可比对,
diff --git a/src/store/modules/harness/types.ts b/src/store/modules/harness/types.ts
index 707142fb..1838cb14 100644
--- a/src/store/modules/harness/types.ts
+++ b/src/store/modules/harness/types.ts
@@ -23,6 +23,11 @@ export interface PreinstallLogPayload {
line: string
}
+/** Rust 侧 internal-plugins-phase 事件载荷(内置插件核对阶段:loading / done) */
+export interface InternalPluginsPhasePayload {
+ phase: 'loading' | 'done'
+}
+
/** 安装器展示状态 */
export interface InstallerState {
title: string