DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(plugin): 核心版本不兼容时逐项授权版本豁免
hairyf43894e2fc6fa
diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rsindex 447164a1..24d2034a 100644--- a/src-tauri/src/bridge/plugin.rs+++ b/src-tauri/src/bridge/plugin.rs@@ -73,6 +73,19 @@ pub async fn cancel_preinstall_plugins(app_handle: AppHandle) {plugin::cancel(&app_handle).await;}+/// 授予「插件版本豁免」:为被核心版本兼容性拒绝的精确 `包名@版本` 组合写授权。+///+/// 前端在风险提示中让用户逐项确认后调用(授权项来自 `install_preinstall_plugins`+/// 返回的 `PLUGIN_VERSION_INCOMPATIBLE:` 载荷),随后重跑安装;豁免不随插件或+/// 核心升级继承,且只对列出的精确版本 + 运行时版本生效。+#[tauri::command]+pub async fn allow_plugin_versions(+ app_handle: AppHandle,+ versions: Vec<plugin::IncompatibleVersion>,+) -> Result<(), String> {+ plugin::allow_version_exemptions(&app_handle, &versions).await+}+/// 跳过预装插件引导:记录状态与预设指纹,之后不再弹出(除非清单内容变更)#[tauri::command]pub async fn skip_preinstall_plugins(app_handle: AppHandle) -> Result<(), String> {diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex bfd27d43..bca3e6f7 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -1067,6 +1067,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::get_preinstall_pending,crate::bridge::install_preinstall_plugins,crate::bridge::cancel_preinstall_plugins,+ crate::bridge::allow_plugin_versions,crate::bridge::skip_preinstall_plugins,crate::bridge::ensure_internal_plugins,crate::bridge::cancel_internal_plugins,diff --git a/src-tauri/src/service/plugin/install/diagnose.rs b/src-tauri/src/service/plugin/install/diagnose.rsindex b79ee6fd..b8fc68d4 100644--- a/src-tauri/src/service/plugin/install/diagnose.rs+++ b/src-tauri/src/service/plugin/install/diagnose.rs@@ -1,7 +1,7 @@//! 失败输出解析:识别网络错误(代理/DNS/连接/TLS)、git 传输层失败//! (HTTPS→SSH 回退提示)、pnpm store 布局不兼容(`ERR_PNPM_UNEXPECTED_STORE`-//! 一族),并从输出中挑选可展示的错误消息(ANSI 清洗、命中错误标记的行优先、-//! 截断)。+//! 一族)、dsh 版本兼容性拒绝(逐条精确 `包名@版本` + 运行时版本,供用户授权),+//! 并从输出中挑选可展示的错误消息(ANSI 清洗、命中错误标记的行优先、截断)。/// 给非空诊断文本加 `: ` 前缀,便于直接拼进错误消息(空文本返回空串)。pub(super) fn diagnostic_suffix(detail: &str) -> String {@@ -84,6 +84,65 @@ fn strip_ansi(s: &str) -> String {out}+/// dsh 版本兼容性拒绝里的一条记录([[`incompatible_versions`]] 的解析结果)。+///+/// 授权(`dsh plugin allow-version`)只认**精确**的包名 + 版本 + 运行时版本三元组,+/// 因此三者都必须原样带出,前端据此逐项向用户确认风险后再授权。+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub struct IncompatibleVersion {+ /// `package.json` 的包名(scoped 包含 `@scope/` 前缀)+ pub name: String,+ pub version: String,+ /// 被拒时所处的 dsh 运行时精确版本:授权必须与它完全一致,否则 dsh 拒绝写入+ pub runtime_version: String,+}++/// 从安装失败输出里提取版本兼容性拒绝条目。+///+/// dsh 在 pnpm 之前核对每个待装插件声明的 DSH peer 依赖,未授权精确版本时整批拒绝+/// (不下载、不构建),输出里逐条印出+/// `Plugin <包名>@<版本> is incompatible with dsh <运行时版本>: peerDependencies …`。+/// 这是唯一同时给出三者(可授权键)的地方:`pick_error_message` 的行标记过滤会把它+/// 并进一大段纯文本,用户只能自己从中抄出版本去敲 CLI。解析失败一律返回空——空结果+/// 只是退回原来的「安装失败」展示,绝不误报成可授权项。+pub(super) fn incompatible_versions(output: &str) -> Vec<IncompatibleVersion> {+ let mut found: Vec<IncompatibleVersion> = Vec::new();+ for line in output.split('\n') {+ let stripped = strip_ansi(line);+ // 第一条警告与 `dsh: installation rejected: ` 同处一行(dsh 用同一个模板拼出+ // 整段拒绝说明),因此只能在行内定位而不能要求行首匹配;后续条目各自成行。+ let Some(start) = stripped.find("Plugin ") else {+ continue;+ };+ let Some((key, rest)) = stripped[start + "Plugin ".len()..].split_once(" is incompatible with dsh ")+ else {+ continue;+ };+ // 版本号自身不含 `@`,按最后一个 `@` 切开包名与版本(scoped 包名以 `@` 开头)+ let Some((name, version)) = key.rsplit_once('@') else {+ continue;+ };+ let runtime_version = rest.split(':').next().unwrap_or_default().trim();+ // 运行时版本必须以数字开头:这样即使后续文案改用别的分隔符,也不会把+ // 冒号后的说明文字当成版本号带进授权命令+ if name.is_empty()+ || version.is_empty()+ || !runtime_version.starts_with(|c: char| c.is_ascii_digit())+ {+ continue;+ }+ let entry = IncompatibleVersion {+ name: name.to_string(),+ version: version.to_string(),+ runtime_version: runtime_version.to_string(),+ };+ if !found.contains(&entry) {+ found.push(entry);+ }+ }+ found+}+/// 从 pnpm 失败输出里识别网络错误,返回稳定提示,避免把网络问题误报为 dsh/// 子进程错误。代理、DNS、连接超时和 TLS 失败都属于此类。pub(super) fn network_error_hint(output: &str) -> Option<&'static str> {@@ -257,6 +316,87 @@ mod tests {);}+ // ---- dsh 版本兼容性拒绝:逐条精确版本授权 ----++ /// 用户实测拒绝输出(dsh 0.2.0-rc.1,预装引导一次装两个插件、双双被拒)。+ const INCOMPATIBLE_OUTPUT: &str = "\ndsh: installation rejected: Plugin [email protected] is incompatible with dsh 0.2.0-rc.1: peerDependencies {\"@deepseek-ai/dsh-llm\":\"^0.1.7-rc.1\"}. Running it may cause crashes or data loss. Update the plugin or install a plugin version compatible with this dsh runtime.\ndsh: nothing was installed.\ndsh: to accept the risk, run: dsh plugin --profile core-020 allow-version [email protected] --dsh-version 0.2.0-rc.1 --accept-risk\n";++ #[test]+ fn incompatible_versions_extracts_exact_grantable_triple() {+ assert_eq!(+ incompatible_versions(INCOMPATIBLE_OUTPUT),+ vec![IncompatibleVersion {+ name: "dsh-better-sidebar".to_string(),+ version: "0.22.1".to_string(),+ runtime_version: "0.2.0-rc.1".to_string(),+ }]+ );+ }++ #[test]+ fn incompatible_versions_reads_header_line_and_own_lines_together() {+ // 真实形状:dsh 把第一条警告与 `installation rejected: ` 拼在同一行,其余各自成行+ let out = concat!(+ "\ndsh: installation rejected: Plugin [email protected] is incompatible with dsh 0.2.0-rc.1: peerDependencies {\"@deepseek-ai/dsh-llm\":\"^0.1.7-rc.1\"}. Running it may cause crashes or data loss.\n",+ "Plugin [email protected] is incompatible with dsh 0.2.0-rc.1: peerDependencies {\"@deepseek-ai/dsh-fs\":\"^0.1.7-rc.2\"}. Running it may cause crashes or data loss.\n",+ "dsh: nothing was installed.\n",+ );+ assert_eq!(+ incompatible_versions(out),+ vec![+ IncompatibleVersion {+ name: "dsh-better-sidebar".to_string(),+ version: "0.22.1".to_string(),+ runtime_version: "0.2.0-rc.1".to_string(),+ },+ IncompatibleVersion {+ name: "dsh-rewind-plugin".to_string(),+ version: "0.14.0".to_string(),+ runtime_version: "0.2.0-rc.1".to_string(),+ },+ ]+ );+ }++ #[test]+ fn incompatible_versions_keeps_scoped_package_name() {+ let out = "dsh: installation rejected: Plugin @wenbin_wb/[email protected] is incompatible with dsh 0.2.0-rc.1: peerDependencies {}.\n";+ assert_eq!(+ incompatible_versions(out),+ vec![IncompatibleVersion {+ name: "@wenbin_wb/dsh-bridge".to_string(),+ version: "1.2.3".to_string(),+ runtime_version: "0.2.0-rc.1".to_string(),+ }]+ );+ }++ #[test]+ fn incompatible_versions_dedupes_repeated_refusals() {+ // 重试拼接的整串里同一插件会出现多次:授权列表只应留一条+ let repeated = format!("{INCOMPATIBLE_OUTPUT}{INCOMPATIBLE_OUTPUT}");+ assert_eq!(incompatible_versions(&repeated).len(), 1);+ }++ #[test]+ fn incompatible_versions_ignores_other_failures_and_malformed_lines() {+ assert!(incompatible_versions("ERR_PNPM_FETCH_404 registry error").is_empty());+ assert!(incompatible_versions("").is_empty());+ assert!(incompatible_versions(+ "dsh: plugin command failed; diagnostics: /tmp/pnpm.log\n"+ )+ .is_empty());+ // 运行时版本不是版本号(文案改版)时宁可放弃解析,也不把说明文字当版本带进授权+ assert!(incompatible_versions(+ "Plugin [email protected] is incompatible with dsh unknown-runtime: peerDependencies {}."+ )+ .is_empty());+ assert!(incompatible_versions(+ "Plugin foo is incompatible with dsh 0.2.0-rc.1: peerDependencies {}."+ )+ .is_empty());+ }+// ---- git 传输层错误识别(区别于 allowBuilds 门禁)----/// shim 不可用时 cmd.exe / shim 自己的原话,不含 `error`/`failed`:diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rsindex 21a419d2..326565a3 100644--- a/src-tauri/src/service/plugin/install/mod.rs+++ b/src-tauri/src/service/plugin/install/mod.rs@@ -71,14 +71,17 @@ pub(crate) use pnpm::{};pub(crate) use single::uninstall_deprecated_plugins;pub use single::{remove, update};+// 版本兼容性拒绝的解析结果要跨到 `bridge`(前端逐项确认风险后授权),在此定义出口+pub use diagnose::IncompatibleVersion;use allowlist::{add_allow_build_keys, parse_allowlist_keys};use artifact::{ensure_plugin_entry_built, verify_installed_products};use diagnose::{- diagnostic_suffix, git_transport_hint, network_error_hint, pick_error_message,- policy_verification_network_failure, store_mismatch_hint,+ diagnostic_suffix, git_transport_hint, incompatible_versions, network_error_hint,+ pick_error_message, policy_verification_network_failure, store_mismatch_hint,};use pnpm::ensure_pnpm;+use single::single_plugin_args;use spec::{bundled_dir_of, normalize_git_spec, preset_spec_for_install, spec_argument};/// 允许构建重试的上限。每次重试解决 pnpm 报出的一个允许键(git depPath 或@@ -306,6 +309,17 @@ async fn install_with_cancel(if !detail.is_empty() {log::error!("dsh plugin install diagnostic: {detail}");}+ // 版本兼容性拒绝:dsh 在 pnpm 之前核对声明的 DSH peer 依赖,未授权精确版本+ // 即整批拒绝(不下载、不构建)。这不是安装故障而是待用户授权的清单,解析成+ // 精确三元组交给前端走「勾选授权 → 重试」。必须排在网络/store 分类之前:+ // 该拒绝几乎没有 pnpm 输出,落到通用分支只会给出一段用户无从下手的纯文本。+ let incompatible = incompatible_versions(&last_attempt);+ if !incompatible.is_empty() {+ log::warn!("dsh rejected the install for incompatible plugin versions: {incompatible:?}");+ let payload = serde_json::to_string(&incompatible)+ .map_err(|e| format!("PREINSTALL_SERIALIZE: {e}"))?;+ return Err(format!("PLUGIN_VERSION_INCOMPATIBLE: {payload}"));+ }// 区分 git 传输层失败与 allowBuilds 构建门禁:前者是 pnpm 走了 git+ssh// (用户环境无 SSH 配置),后者才是补充白名单可自愈的。传输层错误给出// 可读指引,避免用户被 dsh 那条 allowBuilds 提示误导。@@ -424,6 +438,84 @@ async fn install_with_cancel(Ok(())}+/// 授予被核心拒绝的插件精确版本豁免:逐条执行 `dsh plugin --profile <档案>+/// allow-version <包名@版本> --dsh-version <运行时> --accept-risk`,写 profile 的+/// `compatibility.json`(不改依赖、bundles 与 patch 层)。+///+/// 授权由用户在风险提示中逐项确认后触发,`--accept-risk` 是这条命令的强制前提;+/// 豁免只对**精确的包名@版本 + 运行时版本**生效,插件或 DSH 升级后都不继承,+/// 因此授权后必须重跑安装由 dsh 自己复核,不能假定一定通过。+///+/// 不走 `ensure_pnpm`/停服:dsh 在 `allow-version` 分支里根本不进入 pnpm,+/// 也不碰 `node_modules`,无需 pnpm 就绪或重启服务。+pub async fn allow_version_exemptions(+ app_handle: &AppHandle,+ versions: &[IncompatibleVersion],+) -> Result<(), String> {+ if versions.is_empty() {+ return Err("PLUGIN_EXEMPTION_EMPTY: no plugin version exemption to grant".to_string());+ }+ let window = app_handle+ .get_webview_window("main")+ .ok_or("WINDOW_NOT_FOUND: main window missing")?;+ 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 envs = build_plugin_envs(app_handle, harness_prefer_bundled_pnpm(app_handle));+ let cwd = config::get_dsh_install_path(app_handle);+ let profile = active_profile(app_handle);+ let owner = new_process_owner();+ let mut failures: Vec<String> = Vec::new();+ for entry in versions {+ let mut args = vec![dsh_bin.as_os_str().to_os_string()];+ args.extend(single_plugin_args(+ &profile,+ "allow-version",+ &[+ format!("{}@{}", entry.name, entry.version),+ "--dsh-version".to_string(),+ entry.runtime_version.clone(),+ "--accept-risk".to_string(),+ ],+ ));+ log::info!(+ "Granting plugin version exemption {}@{} for DSH {}",+ entry.name,+ entry.version,+ entry.runtime_version+ );+ let (exit_code, output) =+ run_plugin_process(&node, &args, &cwd, &envs, &window, owner).await?;+ if exit_code != 0 {+ let detail = pick_error_message(&output, None);+ log::error!(+ "granting plugin version exemption {}@{} failed with exit code {exit_code}: {detail}",+ entry.name,+ entry.version+ );+ failures.push(format!(+ "{}@{}: dsh plugin exited with code {exit_code}{}",+ entry.name,+ entry.version,+ diagnostic_suffix(&detail)+ ));+ }+ }+ // 逐条执行而不是遇错即停:一个条目失败(版本漂移、compatibility.json 损坏)+ // 不该让用户已勾选的其它条目也不被授权;错误跨条目聚合后一次性返回。+ if failures.is_empty() {+ Ok(())+ } else {+ Err(format!("PLUGIN_EXEMPTION_FAILED: {}", failures.join("; ")))+ }+}+/// 返回 `(exit_code, 历次尝试的输出拼接, 最后一次尝试的输出)`。////// 两个字符串用途不同:诊断与用户文案要拼接(早期的 allowBuilds 提示也是线索),而diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rsindex d73f72e9..5b14b254 100644--- a/src-tauri/src/service/plugin/install/single.rs+++ b/src-tauri/src/service/plugin/install/single.rs@@ -245,7 +245,10 @@ pub(crate) async fn uninstall_deprecated_plugins(app_handle: &AppHandle) -> Resu/// pnpm 收到的就是 `pnpm remove remove <id>`(issue #715 日志中的 `pnpm remove/// remove dshmarket`)——`remove` 会去找一个名为 `remove` 的依赖,卸载/升级因此/// 不生效甚至失败。-fn single_plugin_args(profile: &str, action: &str, sub_args: &[String]) -> Vec<OsString> {+///+/// 版本豁免授权(`allow-version`,见 [`super::allow_version_exemptions`])同样走+/// 这个形状:dsh 在转发给 pnpm 之前先拦下该动词,`--profile` 的拼装完全一致。+pub(super) fn single_plugin_args(profile: &str, action: &str, sub_args: &[String]) -> Vec<OsString> {let mut args = vec![OsString::from("plugin"),OsString::from("--profile"),diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex c0e8e19c..fe764c1c 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -54,7 +54,7 @@ pub use cancel::cancel;pub(crate) use cancel::terminate_active_installs_blocking;pub(crate) use install::harness_prefer_bundled_pnpm;pub(crate) use install::uninstall_deprecated_plugins;-pub use install::{install, remove, update};+pub use install::{allow_version_exemptions, install, remove, update, IncompatibleVersion};pub(crate) use installed::{ensure_profile_npmrc, installed_name, list_installed, profile_dir};pub use installed::{list, PreinstallPlugin};pub(crate) use internal::cancel as cancel_internal_plugins;diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex 37429e44..279e6e36 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -46,6 +46,9 @@"preinstall.restarting_hint": "[harness] Restarting the service, please wait…","preinstall.open_preset": "Open Preset","preinstall.can_uncheck_hint": "You can uncheck plugins you don't want. Unchecked plugins won't be installed.",+ "preinstall.incompatible_title": "Installation blocked by the core",+ "preinstall.incompatible_desc": "Running them may cause crashes or data loss. Update the plugin, or install a plugin version compatible with this dsh runtime. To accept this risk explicitly, check and grant the exact version exemptions below (they apply only to the exact versions listed and expire when the plugin or the core is upgraded):",+ "preinstall.granting": "Granting…","plugins.title": "Installed Plugins","plugins.empty": "No plugins installed","plugins.loading": "Loading plugins…",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex bf124182..f9b05bbb 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -46,6 +46,9 @@"preinstall.restarting_hint": "[harness] 正在重启服务,请稍候…","preinstall.open_preset": "打开预设","preinstall.can_uncheck_hint": "你可以取消勾选不需要的插件,取消后不会安装。",+ "preinstall.incompatible_title": "安装被核心拦截",+ "preinstall.incompatible_desc": "运行它们可能会导致崩溃或数据丢失。请更新插件,或安装与此 dsh 运行时兼容的插件版本。要明确接受此风险,请勾选并授予以下确切的版本豁免(仅对列出的精确版本生效,插件或核心升级后失效):",+ "preinstall.granting": "正在授权…","plugins.title": "已安装插件","plugins.empty": "暂无已安装插件","plugins.loading": "正在读取插件…",diff --git a/src/layout/components/setup-preinstall.tsx b/src/layout/components/setup-preinstall.tsxindex affabc9b..4ef90ae1 100644--- a/src/layout/components/setup-preinstall.tsx+++ b/src/layout/components/setup-preinstall.tsx@@ -1,6 +1,6 @@import type { PreinstallPlugin } from '@/store/modules/preinstall'import { ArrowUpRightFromSquare, Copy, PlugConnection, Xmark } from '@gravity-ui/icons'-import { Button, Card, Chip, ScrollShadow, Spinner, Switch, Typography } from '@heroui/react'+import { Button, Card, Checkbox, Chip, ScrollShadow, Spinner, Switch, Typography } from '@heroui/react'import { useMount } from '@reause/core'import { invoke } from '@tauri-apps/api/core'import { useState } from 'react'@@ -171,6 +171,12 @@ export function PreinstallSetup() {// 用户手动调整后的选择(一旦交互即接管默认勾选)const [selected, setSelected] = useState<Set<string>>(() => new Set())const [touched, setTouched] = useState(false)+ // 版本豁免的勾选集合:默认全不勾——「可能导致崩溃或数据丢失」的风险必须由用户+ // 明确接受,不想装这些插件的人有「跳过」可走+ const [allowed, setAllowed] = useState<Set<string>>(() => new Set())+ // 授权进行中:逐条起 dsh 进程写兼容性豁免,期间禁用按钮并显示加载态+ const [granting, setGranting] = useState(false)+ const blocked = preinstall.incompatible// 进入引导页时拉取插件列表(仅挂载一次,无需清理)useMount(() => {@@ -223,6 +229,42 @@ export function PreinstallSetup() {void store.preinstall.skip()}+ function toggleAllowed(key: string, checked: boolean) {+ setAllowed((prev) => {+ const next = new Set(prev)+ if (checked) {+ next.add(key)+ }+ else {+ next.delete(key)+ }+ return next+ })+ }++ /**+ * 授权勾选的精确版本后重跑安装。+ *+ * 豁免只对「精确的包名@版本 + 运行时版本」生效、且不随插件或核心升级继承,因此+ * 必须真的重跑一次由 dsh 复核,不能假定授权即放行。+ *+ * 授权要逐条起 `dsh plugin allow-version`(每条一次进程启动),期间用 granting+ * 给出按钮反馈:这段等待既没有安装日志也没有列表变化,否则点完像没反应。+ */+ async function handleAllow() {+ const versions = blocked.filter(item => allowed.has(`${item.name}@${item.version}`))+ if (granting || versions.length === 0)+ return+ setGranting(true)+ try {+ if (await store.preinstall.allowIncompatible(versions))+ handleConfirm()+ }+ finally {+ setGranting(false)+ }+ }+// 是否有变更:存在需安装或需卸载的插件时启用"确定"const toInstallCount = preinstall.plugins.filter(p => effectiveSelected.has(p.id) && !p.installed).lengthconst toUninstallCount = preinstall.plugins.filter(p => p.installed && !effectiveSelected.has(p.id) && !p.unsupported).length@@ -240,9 +282,10 @@ export function PreinstallSetup() {<Ifcond={installing}else={(- // 安装失败时不叠加插件列表,只展示错误 + 日志 + 重试/跳过+ // 被核心版本拦截(可逐项授权)或安装失败时不叠加插件列表,+ // 只展示原因 + 日志 + 操作<If- cond={preinstall.error !== ''}+ cond={blocked.length > 0 || preinstall.error !== ''}else={(<>{/* 卡片网格限定高度滚动,上下溢出由 ScrollShadow 渐隐提示 */}@@ -338,29 +381,86 @@ export function PreinstallSetup() {)}>{/* 安装失败:错误信息 + 日志 + 操作 */}- <div className="flex flex-col gap-2.5">- <div className="flex flex-col gap-2 rounded-md border border-danger/30 bg-danger/5 p-3">- <p className="text-xs font-medium text-danger">{t('preinstall.failed')}</p>- <p className="max-h-[120px] overflow-y-auto break-all font-mono text-[11px] leading-relaxed text-muted">- {preinstall.error}- </p>- </div>- <LogPanel logs={preinstall.logs} />- <div className="flex items-center justify-end gap-2">- <Button className="h-8 rounded-md" size="sm" variant="tertiary" onPress={handleSkip} isDisabled={installing}>- {t('preinstall.skip')}- </Button>- <Button- className="h-8 rounded-md"- size="sm"- variant="primary"- onPress={handleConfirm}- isDisabled={installing || !hasChanges}- >- {t('app.retry')}- </Button>+ <If+ cond={blocked.length > 0}+ else={(+ <div className="flex flex-col gap-2.5">+ <div className="flex flex-col gap-2 rounded-md border border-danger/30 bg-danger/5 p-3">+ <p className="text-xs font-medium text-danger">{t('preinstall.failed')}</p>+ <p className="max-h-[120px] overflow-y-auto break-all font-mono text-[11px] leading-relaxed text-muted">+ {preinstall.error}+ </p>+ </div>+ <LogPanel logs={preinstall.logs} />+ <div className="flex items-center justify-end gap-2">+ <Button className="h-8 rounded-md" size="sm" variant="tertiary" onPress={handleSkip} isDisabled={installing}>+ {t('preinstall.skip')}+ </Button>+ <Button+ className="h-8 rounded-md"+ size="sm"+ variant="primary"+ onPress={handleConfirm}+ isDisabled={installing || !hasChanges}+ >+ {t('app.retry')}+ </Button>+ </div>+ </div>+ )}+ >+ {/* 版本兼容性拒绝:核心在 pnpm 之前拦下整批安装,插件与当前核心的+ DSH peer 依赖不匹配;逐项授权精确版本(风险由用户明确承担)后重试 */}+ <div className="flex flex-col gap-2.5">+ <div className="flex flex-col gap-2 rounded-md border border-danger/30 bg-danger/5 p-3">+ <p className="text-xs font-medium text-danger">{t('preinstall.incompatible_title')}</p>+ <p className="text-[11px] leading-relaxed text-muted">{t('preinstall.incompatible_desc')}</p>+ <div className="mt-0.5 flex flex-col gap-1.5">+ {blocked.map((item) => {+ const key = `${item.name}@${item.version}`+ return (+ <label key={key} className="flex cursor-pointer items-center gap-2">+ <Checkbox+ className="shrink-0"+ isSelected={allowed.has(key)}+ onChange={(value: boolean) => toggleAllowed(key, value)}+ aria-label={key}+ >+ <Checkbox.Content>+ <Checkbox.Control>+ <Checkbox.Indicator />+ </Checkbox.Control>+ </Checkbox.Content>+ </Checkbox>+ <span className="font-mono text-[11px] text-ink">{key}</span>+ </label>+ )+ })}+ </div>+ </div>+ <LogPanel logs={preinstall.logs} />+ <div className="flex items-center justify-end gap-2">+ <Button className="h-8 rounded-md" size="sm" variant="tertiary" onPress={handleSkip} isDisabled={installing || granting}>+ {t('preinstall.skip')}+ </Button>+ <Button+ className="h-8 rounded-md"+ size="sm"+ variant="primary"+ onPress={() => void handleAllow()}+ isDisabled={installing || granting || allowed.size === 0}+ >+ <If cond={granting}>+ <Spinner size="sm" color="current" />+ <span>{t('preinstall.granting')}</span>+ </If>+ <If cond={!granting}>+ <span>{t('preinstall.confirm')}</span>+ </If>+ </Button>+ </div></div>- </div>+ </If></If>)}>diff --git a/src/store/modules/preinstall/index.ts b/src/store/modules/preinstall/index.tsindex a3086578..e7648b57 100644--- a/src/store/modules/preinstall/index.ts+++ b/src/store/modules/preinstall/index.ts@@ -1,5 +1,6 @@export { preinstall } from './store'export type {+ IncompatibleVersion,PreinstallLogPayload,PreinstallPlugin,PreinstallSelection,diff --git a/src/store/modules/preinstall/store.ts b/src/store/modules/preinstall/store.tsindex 424f0673..b723be15 100644--- a/src/store/modules/preinstall/store.ts+++ b/src/store/modules/preinstall/store.ts@@ -1,5 +1,5 @@import type { UnlistenFn } from '@tauri-apps/api/event'-import type { PreinstallLogPayload, PreinstallPlugin, PreinstallSelection } from './types'+import type { IncompatibleVersion, PreinstallLogPayload, PreinstallPlugin, PreinstallSelection } from './types'import { invoke } from '@tauri-apps/api/core'import { listen } from '@tauri-apps/api/event'import i18next from 'i18next'@@ -11,6 +11,28 @@ import { harnessUpdater } from '../harness-updater'/** 预装安装日志在界面上的保留行数 */const LOG_LIMIT = 200+/**+ * 后端版本兼容性拒绝的前缀:其后是 `IncompatibleVersion[]` 的 JSON。+ *+ * dsh 在 pnpm 之前核对插件声明的 DSH peer 依赖,未授权精确版本即整批拒绝。后端把+ * 拒绝清单挂在错误串上(Tauri 命令的错误通道只有字符串),这里解出来交给界面走+ * 「逐项授权 → 重试」;解析失败返回 null,退回普通的安装失败展示,绝不假装可授权。+ */+const INCOMPATIBLE_PREFIX = 'PLUGIN_VERSION_INCOMPATIBLE:'++function parseIncompatible(error: string): IncompatibleVersion[] | null {+ if (!error.startsWith(INCOMPATIBLE_PREFIX))+ return null+ try {+ const parsed = JSON.parse(error.slice(INCOMPATIBLE_PREFIX.length)) as IncompatibleVersion[]+ return parsed.length > 0 ? parsed : null+ }+ catch (err) {+ console.error('[Harness] failed to parse incompatible plugin payload:', err)+ return null+ }+}+/*** 预装插件引导模块:首次安装、老版本升级或资源清单 plugins 节内容变更后,* 展示推荐插件列表(可增选/减选),确认或跳过后继续启动服务。@@ -29,6 +51,11 @@ export const preinstall = defineStore({logs: [] as string[],/** 安装失败错误(区别于下面列表加载失败) */error: '',+ /**+ * 被核心版本兼容性拦截、等待用户逐项授权的插件版本。+ * 非空时界面展示风险提示与勾选清单(而非插件列表或错误态)。+ */+ incompatible: [] as IncompatibleVersion[],/** 拉取预装插件列表失败(区别于空列表;UI 据此展示错误态 + 重试) */loadError: '',/** 是否为首次安装引导(决定默认勾选策略):boot 流程进入时为 true,侧边栏手动打开为 false */@@ -77,6 +104,7 @@ export const preinstall = defineStore({returnthis.installing = truethis.error = ''+ this.incompatible = []this.logs = []let unlisten: UnlistenFn | null = nulltry {@@ -90,9 +118,16 @@ export const preinstall = defineStore({catch (err) {console.error('[Harness] preinstall failed:', err)const error = String(err)- this.error = error.startsWith('NETWORK_ERROR:')- ? i18next.t('preinstall.network_error')- : error+ const incompatible = parseIncompatible(error)+ if (incompatible) {+ // 不是故障而是待授权清单:交给界面展示风险与勾选,用户授权后重跑安装+ this.incompatible = incompatible+ }+ else {+ this.error = error.startsWith('NETWORK_ERROR:')+ ? i18next.t('preinstall.network_error')+ : error+ }}finally {unlisten?.()@@ -101,6 +136,28 @@ export const preinstall = defineStore({}},+ /**+ * 授予被核心拒绝的插件精确版本豁免,成功后由界面重跑安装。+ *+ * 只提交用户在风险提示中勾选的条目;授权失败按普通安装失败展示(错误态 + 重试),+ * 届时重试会再次触发拒绝、重新给出勾选清单。+ */+ async allowIncompatible(versions: IncompatibleVersion[]): Promise<boolean> {+ if (this.installing || versions.length === 0)+ return false+ try {+ await invoke('allow_plugin_versions', { versions })+ this.incompatible = []+ return true+ }+ catch (err) {+ console.error('[Harness] granting plugin version exemption failed:', err)+ this.incompatible = []+ this.error = String(err)+ return false+ }+ },+/*** 取消正在进行的预装插件安装:网络抖动/拉包限流(429)时可能长时间卡在* pnpm 重试;调用后端强杀插件安装进程树,回到可重试的选择态。diff --git a/src/store/modules/preinstall/types.ts b/src/store/modules/preinstall/types.tsindex a4f7dfe1..43df2d82 100644--- a/src/store/modules/preinstall/types.ts+++ b/src/store/modules/preinstall/types.ts@@ -25,3 +25,14 @@ export interface PreinstallSelection {installIds?: string[]uninstallIds?: string[]}++/**+ * 被核心版本兼容性拦截的插件(与 Rust `service::plugin::IncompatibleVersion` 对齐)。+ *+ * 授权只对**精确的**包名 + 版本 + 运行时版本生效,因此三个字段原样往返后端。+ */+export interface IncompatibleVersion {+ name: string+ version: string+ runtime_version: string+}diff --git a/test/preinstall-incompatible.test.ts b/test/preinstall-incompatible.test.tsnew file mode 100644index 00000000..cf498ccc--- /dev/null+++ b/test/preinstall-incompatible.test.ts@@ -0,0 +1,104 @@+import type { Event } from '@tauri-apps/api/event'+import type { IncompatibleVersion } from '../src/store/modules/preinstall'+import { beforeEach, describe, expect, it, vi } from 'vitest'++// 版本兼容性拒绝的往返:后端把拒绝清单挂在错误串上(Tauri 命令的错误通道只有字符串),+// store 负责解出授权清单、授权后再重跑安装。这里锁定三件事:载荷被解成可授权项而不是+// 安装失败;非该前缀的失败仍是失败;解析不了时宁可报失败也不假装可授权。++const BLOCKED: IncompatibleVersion[] = [+ { name: 'dsh-better-sidebar', version: '0.22.1', runtime_version: '0.2.0-rc.1' },+ { name: 'dsh-rewind-plugin', version: '0.14.0', runtime_version: '0.2.0-rc.1' },+]++const { eventListeners, invoke } = vi.hoisted(() => ({+ eventListeners: new Map<string, (event: Event<unknown>) => void>(),+ invoke: vi.fn(),+}))++vi.mock('@tauri-apps/api/core', () => ({ invoke }))+vi.mock('@tauri-apps/api/event', () => ({+ listen: vi.fn(async (event: string, callback: (payload: Event<unknown>) => void) => {+ eventListeners.set(event, callback)+ return vi.fn()+ }),+}))+vi.mock('@/config/client', () => ({ queryClient: { invalidateQueries: vi.fn() } }))+vi.mock('../src/store/modules/harness-updater', () => ({+ harnessUpdater: { checkForUpdate: vi.fn() },+}))++const { preinstall } = await import('../src/store/modules/preinstall')++beforeEach(() => {+ eventListeners.clear()+ invoke.mockReset()+ preinstall.error = ''+ preinstall.incompatible = []+ preinstall.installing = false+ preinstall.logs = []+})++describe('preinstall version-incompatibility refusal', () => {+ it('exposes the refused exact versions as authorizable entries instead of a failure', async () => {+ invoke.mockRejectedValue(`PLUGIN_VERSION_INCOMPATIBLE: ${JSON.stringify(BLOCKED)}`)++ await preinstall.confirm({ installIds: ['dsh-better-sidebar', 'dsh-rewind-plugin'] })++ expect(preinstall.incompatible).toEqual(BLOCKED)+ expect(preinstall.error).toBe('')+ expect(preinstall.installing).toBe(false)+ })++ it('keeps a malformed refusal payload as a plain install failure', async () => {+ invoke.mockRejectedValue('PLUGIN_VERSION_INCOMPATIBLE: not-json')++ await preinstall.confirm({ installIds: ['dsh-better-sidebar'] })++ expect(preinstall.incompatible).toEqual([])+ expect(preinstall.error).toBe('PLUGIN_VERSION_INCOMPATIBLE: not-json')+ })++ it('keeps an ordinary install failure as a plain install failure', async () => {+ invoke.mockRejectedValue('PREINSTALL_FAILED: dsh plugin exited with code 1')++ await preinstall.confirm({ installIds: ['dsh-better-sidebar'] })++ expect(preinstall.incompatible).toEqual([])+ expect(preinstall.error).toBe('PREINSTALL_FAILED: dsh plugin exited with code 1')+ })+})++describe('preinstall version-exemption grant', () => {+ it('grants exactly the checked entries and clears the pending list', async () => {+ preinstall.incompatible = BLOCKED+ invoke.mockResolvedValue(undefined)++ const granted = await preinstall.allowIncompatible([BLOCKED[0]])++ expect(granted).toBe(true)+ expect(invoke).toHaveBeenCalledWith('allow_plugin_versions', { versions: [BLOCKED[0]] })+ expect(preinstall.incompatible).toEqual([])+ })++ it('does not touch the backend when nothing is checked', async () => {+ preinstall.incompatible = BLOCKED++ const granted = await preinstall.allowIncompatible([])++ expect(granted).toBe(false)+ expect(invoke).not.toHaveBeenCalled()+ expect(preinstall.incompatible).toEqual(BLOCKED)+ })++ it('reports a failed grant as an install failure with the pending list cleared', async () => {+ preinstall.incompatible = BLOCKED+ invoke.mockRejectedValue('PLUGIN_EXEMPTION_FAILED: [email protected]: dsh plugin exited with code 1')++ const granted = await preinstall.allowIncompatible(BLOCKED)++ expect(granted).toBe(false)+ expect(preinstall.incompatible).toEqual([])+ expect(preinstall.error).toBe('PLUGIN_EXEMPTION_FAILED: [email protected]: dsh plugin exited with code 1')+ })+})