Skip to content

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

refactor: 移除核心换版警告与预设插件自动卸载 (#1179)

Hairyff096af9ba3d
diff --git a/src-tauri/src/config/manifest.rs b/src-tauri/src/config/manifest.rs
index d0e5fa0e..5ddc666f 100644
--- a/src-tauri/src/config/manifest.rs
+++ b/src-tauri/src/config/manifest.rs
@@ -99,7 +99,7 @@ pub struct VersionPair {
///
/// `semver` crate 对预发布版本另设门槛:必须存在比较符与本版本 major.minor.patch 相同且
/// 自带 pre。于是 `^0.2.0-rc.1` 漏掉 `0.2.1-rc.1` 这类同代更高补丁号的预发布核心(内核
-/// 侧放行),核心一发 rc 就把插件误标成不兼容并触发 `retire_on` 退役。补一个对本版本恒真
+/// 侧放行),核心一发 rc 就把插件误标成不兼容。补一个对本版本恒真
/// 的精确比较符即可绕开门槛,其余比较符的判定不受影响。
fn matches_including_prerelease(req: &semver::VersionReq, version: &semver::Version) -> bool {
let matched = req.matches(version);
@@ -191,69 +191,6 @@ impl PluginVersion {
}
declared
}
-
- /// 已安装版本是否**旧于**核心当前那一代的推荐区间(`None` = 无法判定)。
- ///
- /// 区间是发布侧对「这一代核心该配哪个插件版本」的推荐,不是硬性上界:用户升级到
- /// 比区间更新的版本(声明 `^0.21.1`、实装 `0.22.0`)是允许的,必须与「装了旧版
- /// 本」区分开。判定按区间下界:低于下界 = 过期(核心换代后要重装);达到或超过
- /// 下界但超出上界 = 用户自行升级的新版本,保留。
- pub fn outdated_for_core_generation(
- &self,
- core: Option<&str>,
- installed: Option<&str>,
- ) -> Option<bool> {
- let floor = self.declared_floor_for_core(core)?;
- let installed = semver::Version::parse(installed?).ok()?;
- Some(installed < floor)
- }
-
- /// 某代声明的插件版本区间**下界**(`None` = 没有命中区间 / 区间不可解析 / 区间
- /// 只写了上界,调用方按无法判定处理)。
- ///
- /// 只取**下界**比较符(`^` / `~` / `>=` / `>` / `=`),上界(`<` / `<=`)与
- /// 通配符不参与:`<2.0.0` 这类纯上界声明没有下界语义,若把它当 2.0.0 会让所有
- /// 已装版本都被判成过期而误删。区间是**合取**(需同时满足全部比较符),因此取各
- /// 下界中的最大值——书写顺序与上界位置都不影响结果。
- ///
- /// 预发布标记必须一并保留:`^0.14.0-beta.1` 的下界是 `0.14.0-beta.1`,若截成
- /// `0.14.0` 会把合法实装的 `0.14.0-beta.1` 误判成过期。
- fn declared_floor_for_core(&self, core: Option<&str>) -> Option<semver::Version> {
- let req = parse_req(self.plugin_req_for_core(core)?)?;
- req.comparators
- .iter()
- .filter(|comparator| {
- matches!(
- comparator.op,
- semver::Op::Exact
- | semver::Op::Greater
- | semver::Op::GreaterEq
- | semver::Op::Tilde
- | semver::Op::Caret
- )
- })
- .map(|comparator| semver::Version {
- major: comparator.major,
- minor: comparator.minor.unwrap_or(0),
- patch: comparator.patch.unwrap_or(0),
- pre: comparator.pre.clone(),
- build: semver::BuildMetadata::EMPTY,
- })
- .max()
- }
-
- /// 已安装版本是否落在矩阵声明的任一同代区间内(核心已超出时的清理判定)
- pub fn matches_any_declared(&self, installed: Option<&str>) -> bool {
- let PluginVersion::Matrix(pairs) = self else {
- return false;
- };
- let Some(Ok(installed)) = installed.map(semver::Version::parse) else {
- return false;
- };
- pairs
- .iter()
- .any(|pair| req_matches(&pair.version, &installed))
- }
}
fn deserialize_version<'de, D>(deserializer: D) -> Result<Option<PluginVersion>, D::Error>
@@ -773,10 +710,6 @@ mod tests {
assert!(!matrix.unsupported_on(None));
assert!(!matrix.unsupported_on(Some("not-a-version")));
assert!(matrix.unsupported_on(Some("0.2.1-rc.1")));
- assert!(matrix.matches_any_declared(Some("0.21.3")));
- assert!(matrix.matches_any_declared(Some("0.22.3")));
- assert!(!matrix.matches_any_declared(Some("0.25.0")));
- assert!(!matrix.matches_any_declared(None));
}
#[test]
@@ -822,121 +755,12 @@ mod tests {
}
}
- #[test]
- fn newer_installed_version_is_not_outdated() {
- let matrix = PluginVersion::Matrix(vec![
- VersionPair {
- version: "^0.21.1".to_string(),
- dsh: "^0.1.7-rc.1".to_string(),
- },
- VersionPair {
- version: "^0.24.1".to_string(),
- dsh: "^0.2.0-rc.1".to_string(),
- },
- ]);
- for (core, installed, outdated) in [
- (Some("0.1.7-rc.1"), Some("0.21.1"), Some(false)),
- (Some("0.1.7-rc.1"), Some("0.21.3"), Some(false)),
- (Some("0.1.7-rc.1"), Some("0.22.0"), Some(false)),
- (Some("0.1.7-rc.1"), Some("1.0.0"), Some(false)),
- (Some("0.1.7-rc.1"), Some("0.19.1"), Some(true)),
- (Some("0.1.7-rc.1"), Some("0.20.9"), Some(true)),
- (Some("0.2.1-rc.1"), Some("0.21.3"), Some(true)),
- (Some("0.2.1-rc.1"), Some("0.24.1"), Some(false)),
- (Some("0.2.1-rc.1"), Some("0.25.0"), Some(false)),
- (Some("0.3.0"), Some("0.19.1"), None),
- (Some("0.1.7-rc.1"), None, None),
- (Some("0.1.7-rc.1"), Some("invalid"), None),
- (None, Some("0.19.1"), None),
- ] {
- assert_eq!(
- matrix.outdated_for_core_generation(core, installed),
- outdated,
- "core={core:?} installed={installed:?}"
- );
- }
- }
-
- /// 预发布下界必须整体保留:`^0.14.0-beta.1` 的合法实装版本不能被截成 `0.14.0`
- /// 后误判为过期。
- #[test]
- fn outdated_keeps_prerelease_floor() {
- let matrix = PluginVersion::Matrix(vec![VersionPair {
- version: "^0.14.0-beta.1".to_string(),
- dsh: "^0.1.7-rc.1".to_string(),
- }]);
- assert_eq!(
- matrix.outdated_for_core_generation(Some("0.1.7-rc.1"), Some("0.14.0-beta.1")),
- Some(false)
- );
- assert_eq!(
- matrix.outdated_for_core_generation(Some("0.1.7-rc.1"), Some("0.14.0")),
- Some(false)
- );
- assert_eq!(
- matrix.outdated_for_core_generation(Some("0.1.7-rc.1"), Some("0.13.9")),
- Some(true)
- );
- }
-
- /// 字符串声明不参与过期判定(`latest` 这类标记没有区间语义)。
- #[test]
- fn declared_version_string_is_never_outdated() {
- let declared = PluginVersion::Declared("latest".to_string());
- assert_eq!(
- declared.outdated_for_core_generation(Some("9.9.9"), Some("1.0.0")),
- None
- );
- }
-
- /// 下界只由下界比较符决定,与书写顺序、与是否同时写了上界无关;纯上界声明没有
- /// 下界语义,一律判为无法判定(宁可保留也不误删)。
- #[test]
- fn outdated_floor_reads_lower_bound_comparators_only() {
- let core = Some("0.1.7-rc.1");
- let with = |req: &str| {
- PluginVersion::Matrix(vec![VersionPair {
- version: req.to_string(),
- dsh: "^0.1.7-rc.1".to_string(),
- }])
- };
- // 上界写在前面也不影响下界取值
- assert_eq!(
- with(">=1.2.0 <2.0.0").outdated_for_core_generation(core, Some("1.1.0")),
- Some(true)
- );
- assert_eq!(
- with(">=1.2.0 <2.0.0").outdated_for_core_generation(core, Some("1.5.0")),
- Some(false)
- );
- // 多下界取最大值(区间是合取,必须同时满足)
- assert_eq!(
- with(">=1.4.0 >=1.2.0").outdated_for_core_generation(core, Some("1.3.0")),
- Some(true)
- );
- assert_eq!(
- with(">=1.4.0 >=1.2.0").outdated_for_core_generation(core, Some("1.4.0")),
- Some(false)
- );
- // 纯上界:没有下界可判
- assert_eq!(
- with("<2.0.0").outdated_for_core_generation(core, Some("1.0.0")),
- None
- );
- // 通配符:没有下界可判
- assert_eq!(
- with("*").outdated_for_core_generation(core, Some("1.0.0")),
- None
- );
- }
-
#[test]
fn declared_version_string_is_never_unsupported() {
let declared = PluginVersion::Declared("latest".to_string());
assert!(!declared.unsupported_on(Some("9.9.9")));
// 字符串声明不参与按核心钉版本(`latest` 这类标记不该拼进 spec)
assert_eq!(declared.plugin_req_for_core(Some("9.9.9")), None);
- assert!(!declared.matches_any_declared(Some("9.9.9")));
}
#[test]
diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rs
index 2984ffba..fdaeb430 100644
--- a/src-tauri/src/service/plugin/install/mod.rs
+++ b/src-tauri/src/service/plugin/install/mod.rs
@@ -22,8 +22,7 @@
//!
//! 模块划分(`install/`):
//! - [`self`]:安装编排入口(install / install_specs / install_internal)与 allowBuilds 重试循环
-//! - [`single`]:批量升级/卸载(`dsh plugin update/remove`,卸载后核验 + 离线兜底、
-//! 弃用插件自动卸载)
+//! - [`single`]:批量升级/卸载(`dsh plugin update/remove`,卸载后核验 + 离线兜底)
//! - [`spec`]:安装 spec 准备(内置插件捆绑目录、GitHub 简写规范化、Windows 引号、包名解析)
//! - [`inspect`]:安装前只读兼容性检查(registry `latest` + DSH 家族 peer 判定)
//! - [`env`]:`dsh plugin` 子进程环境($DSH_HOME 隔离、git HTTPS 强制)
@@ -48,7 +47,7 @@ pub(crate) use super::ensure_profile_npmrc;
pub(crate) use super::errors;
pub(crate) use super::installed::{installed_name, is_installed, profile_dir};
pub(crate) use super::preset::{
- bundled_dep_spec, bundled_plugin_dir, load_deprecated_ids, load_presets, PreinstallPluginInfo,
+ bundled_dep_spec, bundled_plugin_dir, load_presets, PreinstallPluginInfo,
};
pub(crate) use super::process::{
acquire_operation_lock, acquire_process_lock, new_process_owner, run_plugin_process, PidGuard,
@@ -75,7 +74,6 @@ pub(crate) use pnpm::{
bundled_pnpm_major, harness_prefer_bundled_pnpm, harness_prefer_bundled_pnpm_from,
pnpm_major_version_at_bounded, profile_store_major,
};
-pub(crate) use single::uninstall_deprecated_plugins;
pub use single::{remove_many, update_many};
// 版本兼容性/发布时长两类拦截的解析结果都要跨到 `bridge`(前端逐项确认后授权),在此定义出口
pub use diagnose::{IncompatibleVersion, PolicyBlockedVersion};
diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rs
index 95e1bb97..a59fc17e 100644
--- a/src-tauri/src/service/plugin/install/single.rs
+++ b/src-tauri/src/service/plugin/install/single.rs
@@ -1,10 +1,7 @@
//! 单插件升级/卸载:`dsh plugin --profile <当前档案> update/remove <id>`。
//! 与安装共用环境准备(shim、pnpm 选版、停止服务)与 allowBuilds 重试;
//! 卸载后核验 profile 清单,插件仍被引用时走离线卸载兜底(受保护包除外)。
-//! 另含启动期弃用插件自动卸载(`uninstall_deprecated_plugins`)。
-#[cfg(test)]
-use std::collections::HashSet;
use std::ffi::OsString;
use std::path::Path;
use tauri::AppHandle;
@@ -26,15 +23,11 @@ use super::errors;
use super::harness_prefer_bundled_pnpm;
use super::is_actionable_plugin_ref;
use super::is_installed;
-use super::load_deprecated_ids;
-use super::load_presets;
use super::new_process_owner;
use super::pnpm::ensure_pnpm;
use super::profile_dir;
use super::run_plugin_with_allow_build_retry;
use super::uninstall_recovery;
-#[cfg(test)]
-use super::PreinstallPluginInfo;
use crate::service::plugin::update::known_latest;
use crate::service::profile::profile_release_age_excluded;
@@ -553,54 +546,6 @@ pub async fn remove_many(app_handle: &AppHandle, ids: &[String]) -> Result<(), S
}
}
-#[cfg(test)]
-use super::super::installed::deprecated_installed_names;
-
-pub(crate) async fn uninstall_deprecated_plugins(app_handle: &AppHandle) -> Result<(), String> {
- let presets = load_presets(app_handle);
- let core_version = core::active_version(app_handle);
- let deprecated_ids = load_deprecated_ids(app_handle);
- let profile = profile_dir(app_handle);
- let manifest = match std::fs::read_to_string(profile.join("package.json")) {
- Ok(raw) => serde_json::from_str::<super::super::installed::ProfilePackageJson>(&raw)
- .map_err(|error| format!("DEPRECATED_PLUGIN_MANIFEST_PARSE_FAILED: {error}"))?,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
- super::super::installed::ProfilePackageJson {
- dependencies: Default::default(),
- dsh: None,
- }
- }
- Err(error) => return Err(format!("DEPRECATED_PLUGIN_MANIFEST_READ_FAILED: {error}")),
- };
- let (names, _) = super::super::installed::deprecated_plugins_at(
- &profile,
- &manifest,
- &presets,
- &deprecated_ids,
- core_version.as_deref(),
- )?;
- if names.is_empty() {
- return Ok(());
- }
- log::info!("uninstalling deprecated preset plugins: {names:?}");
- let mut failures = Vec::new();
- for name in &names {
- log::info!("DEPRECATED_PLUGIN_UNINSTALL: removing deprecated plugin {name}");
- if let Err(e) = uninstall_recovery(app_handle, name) {
- log::warn!("DEPRECATED_PLUGIN_UNINSTALL_FAILED: {name}: {e}");
- failures.push(format!("{name}: {e}"));
- }
- }
- if failures.is_empty() {
- Ok(())
- } else {
- Err(format!(
- "DEPRECATED_PLUGIN_UNINSTALL_FAILED: {}",
- failures.join("; ")
- ))
- }
-}
-
/// `dsh plugin` 的参数:`plugin --profile <档案> <action> <sub_args...>`。
///
/// `dsh plugin` 把 `--profile` 之后的参数**原样**转发给 pnpm(`dsh plugin --profile
@@ -911,49 +856,6 @@ enum UpdateVerifyStep {
#[cfg(test)]
mod tests {
use super::*;
- use crate::config::manifest::{PluginVersion, VersionPair};
-
- /// 测试入口:只关心弃用清单时补一个「未知核心版本 + 未知已安装版本」。
- fn deprecated_names(
- presets: &[PreinstallPluginInfo],
- ids: &HashSet<String>,
- installed: impl Fn(&str) -> bool,
- ) -> Vec<String> {
- deprecated_installed_names(presets, ids, None, installed, |_| None)
- }
-
- /// 内置插件被核心吸收后同样退役:只靠清单声明的版本矩阵(`retire_on`)判定,
- /// 弃用清单不参与。
- #[test]
- fn unsupported_internal_entry_is_uninstalled() {
- let mut entry = preset("dsh-internal", "[email protected]", true);
- entry.version = Some(PluginVersion::Matrix(vec![VersionPair {
- version: "^1.2.3".into(),
- dsh: "^0.1.5-rc.1".into(),
- }]));
-
- // 核心已超出声明区间,且已安装版本仍落在同代区间内 → 退役
- assert_eq!(
- deprecated_installed_names(
- &[entry.clone()],
- &HashSet::new(),
- Some("0.2.0"),
- |name| name == "dsh-internal",
- |_| Some("1.2.3".into()),
- ),
- vec!["dsh-internal".to_string()]
- );
-
- // 已安装版本比清单声明的更新 → 保留,不误删用户手上的修复版
- assert!(deprecated_installed_names(
- &[entry],
- &HashSet::new(),
- Some("0.2.0"),
- |name| name == "dsh-internal",
- |_| Some("2.0.0".into()),
- )
- .is_empty());
- }
/// 一条 hold 载荷:与 `verify_update_landed` 合成的形状一致。
fn hold(name: &str, latest: serde_json::Value, retryable: bool) -> String {
@@ -1211,189 +1113,6 @@ mod tests {
assert_eq!(entries.as_array().expect("array").len(), 1);
}
- fn preset(id: &str, spec: &str, internal: bool) -> PreinstallPluginInfo {
- PreinstallPluginInfo {
- id: id.into(),
- spec: spec.into(),
- package: None,
- name: String::new(),
- description: String::new(),
- repo_url: String::new(),
- recommended: false,
- fix: false,
- default_checked: false,
- default_unchecked: false,
- version: None,
- win_only: false,
- internal,
- }
- }
-
- #[test]
- fn unsupported_cleanup_respects_declared_version_ranges() {
- let declared = vec![
- VersionPair {
- version: "^1.2.0".into(),
- dsh: "^0.1.5-rc.1".into(),
- },
- VersionPair {
- version: "^1.4.0".into(),
- dsh: "^0.1.7-rc.1".into(),
- },
- ];
- for (core, actual, remove) in [
- (Some("0.1.5-rc.3"), Some("1.2.0"), false),
- (Some("0.1.6"), Some("1.2.5"), false),
- (Some("0.1.6"), Some("1.4.0"), false),
- (Some("0.1.7-rc.2"), Some("1.4.0"), false),
- (Some("0.1.7-rc.2"), Some("1.2.0"), true),
- // 回归:核心仍在声明区间内、已装版本**新于**该代区间 → 保留(用户自升级)
- (Some("0.1.7-rc.2"), Some("1.5.0"), false),
- (Some("0.1.7-rc.2"), Some("2.0.0"), false),
- (Some("0.1.5-rc.3"), Some("1.3.0"), false),
- (Some("0.1.5-rc.3"), Some("9.9.9"), false),
- (Some("0.2.0"), Some("1.4.0"), true),
- (Some("0.2.0"), Some("2.0.0"), false),
- (Some("0.2.0"), Some("1.0.0"), false),
- (Some("0.2.0"), None, false),
- (Some("0.2.0"), Some("invalid"), false),
- (None, Some("1.2.0"), false),
- (Some("invalid"), Some("1.2.0"), false),
- ] {
- let mut entry = preset("probe", "@scope/probe", false);
- entry.package = Some("@scope/probe".into());
- entry.version = Some(PluginVersion::Matrix(declared.clone()));
- let names = deprecated_installed_names(
- &[entry.clone()],
- &HashSet::new(),
- core,
- |name| name == "@scope/probe",
- |name| {
- assert_eq!(name, "@scope/probe");
- actual.map(String::from)
- },
- );
- let expected = if remove {
- vec!["@scope/probe".to_string()]
- } else {
- Vec::new()
- };
- assert_eq!(names, expected, "core={core:?}, actual={actual:?}");
- }
- }
-
- #[test]
- fn explicit_deprecation_removes_regardless_of_installed_version() {
- // 显式弃用是发布侧决策:与已安装版本、与核心版本都无关,一律卸载
- let mut entry = preset("probe", "probe", false);
- entry.version = Some(PluginVersion::Declared("1.2.0".into()));
- let ids = HashSet::from(["probe".to_string()]);
- assert_eq!(
- deprecated_installed_names(&[entry], &ids, None, |_| true, |_| Some("2.0.0".into()),),
- vec!["probe".to_string()]
- );
- }
-
- #[test]
- fn unsupported_cleanup_reads_actual_scoped_package_version() {
- let dir = probe_profile("cleanup-version", LOCK_CATALOG, Some("0.18.1"));
- let package = dir.join("node_modules/@scope/probe");
- std::fs::create_dir_all(&package).unwrap();
- std::fs::write(
- package.join("package.json"),
- r#"{"name":"@scope/probe","version":"2.0.0"}"#,
- )
- .unwrap();
- let mut entry = preset("probe", "@scope/probe", false);
- entry.package = Some("@scope/probe".into());
- entry.version = Some(PluginVersion::Matrix(vec![VersionPair {
- version: "^0.18.0".into(),
- dsh: "^0.1.5-rc.1".into(),
- }]));
- let names = deprecated_installed_names(
- &[entry],
- &HashSet::new(),
- Some("0.2.0"),
- |_| true,
- |name| installed_package_version(&dir, name),
- );
- std::fs::remove_dir_all(&dir).unwrap();
- assert!(
- names.is_empty(),
- "newer installed scoped package must be preserved"
- );
- }
-
- #[test]
- fn deprecated_installed_only_picks_marked_and_installed() {
- // 三个弃用条目都在预设清单里声明(预设驱动的常规路径),逐个区分命中。
- let deprecated: HashSet<String> = ["dsh-ok", "dsh-scoped", "dsh-not-installed"]
- .into_iter()
- .map(String::from)
- .collect();
- let mut scoped = preset("dsh-scoped", "github:x/y", false);
- scoped.package = Some("@scope/deprecated".into());
- let declared = vec![
- preset("dsh-ok", "dshmarket", false),
- scoped,
- preset("dsh-not-installed", "dshmarket", false),
- ];
-
- // 命中:登记且已安装 → 返回实际安装包名(dsh-ok 未声明 package,回落 id)
- let only_ok = |name: &str| name == "dsh-ok";
- assert_eq!(
- deprecated_names(&declared, &deprecated, only_ok),
- vec!["dsh-ok".to_string()]
- );
-
- // scoped 包:返回真实安装包名(与预设 id 不一致)
- let only_scoped = |name: &str| name == "@scope/deprecated";
- assert_eq!(
- deprecated_names(&declared, &deprecated, only_scoped),
- vec!["@scope/deprecated".to_string()]
- );
-
- // 登记了但未安装:不命中
- assert!(deprecated_names(&declared, &deprecated, |_| false).is_empty());
-
- // 未登记弃用:即使已安装也不命中
- let plain = preset("dsh-plain", "dsh-plain", false);
- assert!(deprecated_names(&[plain], &deprecated, |name| name == "dsh-plain").is_empty());
-
- // 内部插件即使登记弃用也不命中(内部插件由启动自愈强制安装)
- let internal = preset("dsh-internal", "[email protected]", true);
- assert!(deprecated_names(&[internal], &deprecated, |name| matches!(
- name,
- "dsh-internal"
- ))
- .is_empty());
- }
-
- #[test]
- fn deprecated_installed_falls_back_when_preset_entry_removed() {
- // 弃用条目已从预设清单整体删除(dsh-tauri-panel 并入核心后从
- // plugins.built-in 移除):预设驱动的循环命中不到,兜底按 id 卸载。
- let removed: HashSet<String> = ["dsh-tauri-panel"].into_iter().map(String::from).collect();
-
- assert_eq!(
- deprecated_names(&[], &removed, |name| name == "dsh-tauri-panel"),
- vec!["dsh-tauri-panel".to_string()]
- );
-
- // 清单里根本没有弃用条目:即使同名包已安装也不命中
- assert!(
- deprecated_names(&[], &HashSet::new(), |name| name == "dsh-tauri-panel").is_empty()
- );
-
- // 仍被预设声明(内部插件由自愈强制安装):不走兜底,避免与自愈互相拉扯
- assert!(deprecated_names(
- &[preset("dsh-tauri-panel", "[email protected]", true)],
- &removed,
- |name| name == "dsh-tauri-panel"
- )
- .is_empty());
- }
-
// ---- 升级参数与「假成功」核验 ----
#[test]
diff --git a/src-tauri/src/service/plugin/installed.rs b/src-tauri/src/service/plugin/installed.rs
index 6ad751b0..8ca7cf8f 100644
--- a/src-tauri/src/service/plugin/installed.rs
+++ b/src-tauri/src/service/plugin/installed.rs
@@ -3,7 +3,7 @@
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
use tauri::AppHandle;
use super::preset::{load_deprecated_ids, load_presets, PreinstallPluginInfo};
@@ -103,103 +103,10 @@ pub(crate) fn installed_name(p: &PreinstallPluginInfo) -> &str {
p.package.as_deref().unwrap_or(p.id.as_str())
}
-pub(super) fn deprecated_installed_names(
- presets: &[PreinstallPluginInfo],
- deprecated_ids: &HashSet<String>,
- core_version: Option<&str>,
- mut installed: impl FnMut(&str) -> bool,
- mut installed_version: impl FnMut(&str) -> Option<String>,
-) -> Vec<String> {
- let mut names: Vec<String> = presets
- .iter()
- .filter(|p| {
- let name = installed_name(p);
- if !installed(name) {
- return false;
- }
- if !p.internal && deprecated_ids.contains(&p.id) {
- return true;
- }
- matches!(
- p.version,
- Some(crate::config::manifest::PluginVersion::Matrix(_))
- ) && p.retire_on(core_version, installed_version(name).as_deref())
- })
- .map(|p| installed_name(p).to_string())
- .collect();
- for id in deprecated_ids {
- if !presets.iter().any(|p| p.id == *id) && installed(id) {
- names.push(id.clone());
- }
- }
- names.sort();
- names.dedup();
- names
-}
-
-pub(super) fn deprecated_plugins_at(
- profile: &Path,
- manifest: &ProfilePackageJson,
- presets: &[PreinstallPluginInfo],
- deprecated_ids: &HashSet<String>,
- core_version: Option<&str>,
-) -> Result<(Vec<String>, bool), String> {
- let bundles = manifest.dsh.as_ref().and_then(|dsh| dsh.profile.as_ref());
- let mut failure = None;
- let mut known = true;
- let names = deprecated_installed_names(
- presets,
- deprecated_ids,
- core_version,
- |name| {
- if manifest.dependencies.contains_key(name)
- || bundles.is_some_and(|profile| profile.bundles.iter().any(|id| id == name))
- {
- return true;
- }
- match std::fs::symlink_metadata(profile.join("node_modules").join(name)) {
- Ok(_) => true,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,
- Err(error) => {
- failure = Some(format!(
- "DEPRECATED_PLUGIN_ENTRY_READ_FAILED: {name}: {error}"
- ));
- false
- }
- }
- },
- |name| {
- let version = std::fs::read_to_string(
- profile.join("node_modules").join(name).join("package.json"),
- )
- .ok()
- .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
- .and_then(|manifest| manifest.get("version")?.as_str().map(String::from));
- known &= presets
- .iter()
- .filter(|preset| installed_name(preset) == name)
- .all(|preset| {
- preset.version.as_ref().is_some_and(|range| {
- range
- .outdated_for_core_generation(core_version, version.as_deref())
- .is_some()
- })
- });
- version
- },
- );
- match failure {
- Some(error) => Err(error),
- None => Ok((names, known)),
- }
-}
-
/// 预装插件列表(含 installed 状态),前端渲染用
pub fn list(app_handle: &AppHandle) -> Vec<PreinstallPlugin> {
let installed = list_installed(app_handle);
let is_windows = cfg!(windows);
- // 弃用插件(清单 `plugins.depercated` 登记)不再提供安装入口,启动时自动卸载,
- // 不进入首次引导清单。
let deprecated_ids = load_deprecated_ids(app_handle);
// 当前活动核心版本:按预设声明的(插件版本 ↔ 核心版本)矩阵判定兼容性。
let core_version = crate::service::core::active_version(app_handle);
@@ -210,7 +117,6 @@ pub fn list(app_handle: &AppHandle) -> Vec<PreinstallPlugin> {
// 内置插件(internal:true)由启动自愈强制安装,不进入首次引导清单:
// 对用户而言它们“必装”,给出可取消的勾选框反而造成歧义。
.filter(|p| !p.internal)
- // 弃用插件不再提供安装入口,启动时自动卸载,不进入清单。
.filter(|p| !deprecated_ids.contains(&p.id))
.map(|p| {
// 已安装检测以实际 npm 包名为准:预设可显式声明 package(scoped 包
diff --git a/src-tauri/src/service/plugin/internal/mod.rs b/src-tauri/src/service/plugin/internal/mod.rs
index caf21226..95f59f36 100644
--- a/src-tauri/src/service/plugin/internal/mod.rs
+++ b/src-tauri/src/service/plugin/internal/mod.rs
@@ -21,7 +21,7 @@ use tauri::AppHandle;
use super::cancel::terminate_owned_install;
use super::install::install_internal;
-use super::installed::{deprecated_plugins_at, installed_name, profile_dir, ProfilePackageJson};
+use super::installed::{installed_name, profile_dir, ProfilePackageJson};
use super::preset::{
bundled_dep_spec, bundled_plugin_dir, bundled_plugin_dir_from, load_presets,
presets_from_manifest, PreinstallPluginInfo,
@@ -356,8 +356,6 @@ async fn ensure_scoped(app_handle: &AppHandle) -> Result<(), String> {
crate::service::workflow::early::wait_preparation().await?;
let lock = ensure_lock(&crate::service::profile::active_profile(app_handle));
let presets = load_presets(app_handle);
- // 被核心吸收的内置插件(当前核心已超出其声明的全部核心版本区间)自愈不再装回,
- // 与 `uninstall_deprecated_plugins` 的退役判定同源,避免两边互相拉扯。
let core_version = crate::service::core::active_version(app_handle);
let internal: Vec<_> = presets
.into_iter()
@@ -815,22 +813,15 @@ pub(crate) fn prepare_early_plugins(
return Ok(EarlyPluginState::Defer);
};
let presets = presets_from_manifest(manifest, resources);
- let deprecated = manifest.plugins.deprecated.iter().cloned().collect();
- prepare_early_plugins_from(
- profile,
- dsh_home,
- &presets,
- &deprecated,
- core_version,
- |id| bundled_plugin_dir_from(resources, id),
- )
+ prepare_early_plugins_from(profile, dsh_home, &presets, core_version, |id| {
+ bundled_plugin_dir_from(resources, id)
+ })
}
fn prepare_early_plugins_from(
profile: &Path,
dsh_home: &Path,
presets: &[PreinstallPluginInfo],
- deprecated: &HashSet<String>,
core_version: Option<&str>,
resolve_bundle: impl Fn(&str) -> Option<PathBuf>,
) -> Result<EarlyPluginState, String> {
@@ -885,12 +876,7 @@ fn prepare_early_plugins_from(
{
return Ok(EarlyPluginState::Defer);
}
- let (names, known) = deprecated_plugins_at(profile, parsed, presets, deprecated, core_version)?;
- Ok(if known && names.is_empty() {
- EarlyPluginState::Ready
- } else {
- EarlyPluginState::Defer
- })
+ Ok(EarlyPluginState::Ready)
}
async fn ensure_inner(
@@ -913,9 +899,6 @@ async fn ensure_inner(
true,
|id| bundled_plugin_dir(app_handle, id),
)?;
- // 卸载孤儿内置插件:best-effort、离线精准,不依赖 node/pnpm(其源目录已
- // 不存在,走 `dsh plugin remove` 也没有可安装的本地链接可删)。与弃用插件
- // 自动卸载同一模式:任何失败只记告警,绝不阻断本轮其余重装或整体启动。
if !orphans.is_empty() {
log::info!("Uninstalling orphaned internal preset plugins: {orphans:?}");
for name in &orphans {
@@ -1451,7 +1434,6 @@ mod tests {
win_only: false,
};
let presets = vec![preset("builtin", true), preset("community", false)];
- let deprecated = HashSet::from(["old-plugin".to_string()]);
let path = profile.join("package.json");
let healthy = serde_json::json!({
"dependencies": {"builtin": bundled_dep_spec(&source)},
@@ -1459,7 +1441,7 @@ mod tests {
});
let check = |manifest: &serde_json::Value| {
std::fs::write(&path, manifest.to_string()).unwrap();
- prepare_early_plugins_from(&profile, root.path(), &presets, &deprecated, None, |_| {
+ prepare_early_plugins_from(&profile, root.path(), &presets, None, |_| {
Some(source.clone())
})
};
@@ -1479,7 +1461,7 @@ mod tests {
.unwrap()
.contains("user-plugin"));
assert_eq!(
- prepare_early_plugins_from(&profile, root.path(), &presets, &deprecated, None, |_| {
+ prepare_early_plugins_from(&profile, root.path(), &presets, None, |_| {
Some(source.clone())
})
.unwrap(),
@@ -1534,10 +1516,7 @@ mod tests {
assert_eq!(std::fs::read_to_string(&path).unwrap(), healthy.to_string());
assert_eq!(check(&healthy).unwrap(), EarlyPluginState::Ready);
assert_eq!(
- prepare_early_plugins_from(&profile, root.path(), &presets, &deprecated, None, |_| {
- None
- })
- .unwrap(),
+ prepare_early_plugins_from(&profile, root.path(), &presets, None, |_| None).unwrap(),
EarlyPluginState::Defer
);
std::fs::remove_file(source.join("package.json")).unwrap();
@@ -1559,24 +1538,29 @@ mod tests {
let mut dangling = healthy.clone();
dangling["dependencies"]["removed"] = serde_json::json!("link:missing-source");
assert_eq!(check(&dangling).unwrap(), EarlyPluginState::Defer);
- std::fs::create_dir_all(profile.join("node_modules/old-plugin")).unwrap();
- assert_eq!(check(&healthy).unwrap(), EarlyPluginState::Defer);
- assert!(profile.join("node_modules/old-plugin").is_dir());
- std::fs::remove_dir(profile.join("node_modules/old-plugin")).unwrap();
+ let old_plugin = profile.join("node_modules/old-plugin");
+ std::fs::create_dir_all(&old_plugin).unwrap();
+ std::fs::write(old_plugin.join("data.json"), "user data").unwrap();
+ let mut with_old_plugin = migrated.clone();
+ with_old_plugin["dependencies"]["old-plugin"] = serde_json::json!("1.0.0");
+ with_old_plugin["dsh"]["profile"]["bundles"] = serde_json::json!(["builtin", "old-plugin"]);
+ assert_eq!(check(&with_old_plugin).unwrap(), EarlyPluginState::Ready);
+ let preserved: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
+ assert_eq!(preserved, with_old_plugin);
+ assert_eq!(
+ std::fs::read_to_string(old_plugin.join("data.json")).unwrap(),
+ "user data"
+ );
std::fs::remove_file(entry.join("package.json")).unwrap();
assert_eq!(check(&healthy).unwrap(), EarlyPluginState::Defer);
assert!(!entry.join("package.json").exists());
std::fs::write(&path, "{").unwrap();
- assert!(prepare_early_plugins_from(
- &profile,
- root.path(),
- &presets,
- &deprecated,
- None,
- |_| None
- )
- .unwrap_err()
- .starts_with("INTERNAL_PLUGIN_MANIFEST_PARSE_FAILED:"));
+ assert!(
+ prepare_early_plugins_from(&profile, root.path(), &presets, None, |_| None)
+ .unwrap_err()
+ .starts_with("INTERNAL_PLUGIN_MANIFEST_PARSE_FAILED:")
+ );
assert_eq!(std::fs::read_to_string(&path).unwrap(), "{");
assert_eq!(
prepare_early_plugins(&profile, root.path(), None, None, None).unwrap(),
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index 72c15a95..0411a6d2 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -21,8 +21,7 @@
//! - [`internal`]:内置插件启动自愈(随包分发产物缺失/路径变更时强制重装)
//! - [`verify`]:预装插件完整性自检(清单引用但 node_modules 产物缺失时 `pnpm install` 修复)
//! - [`install`]:对外安装/升级/卸载编排(目录模块 `install/`:编排入口、spec 准备、
-//! 子进程环境、pnpm 选版、allowBuilds 白名单、错误诊断与产物核验),
-//! 以及启动时对 `plugins.depercated` 登记的社区插件自动卸载
+//! 子进程环境、pnpm 选版、allowBuilds 白名单、错误诊断与产物核验)
//! - [`errors`]:插件错误记录(安装/升级/卸载失败 + 页面运行期上报,持久化)
//! - [`process`]:dsh 子进程启动与输出流逐行转发
//! - [`recovery`]:插件异常定位与一键离线卸载
@@ -64,7 +63,6 @@ pub(crate) use hmr::{status as local_plugin_hmr_status, sync_layer as local_plug
pub(crate) use install::harness_prefer_bundled_pnpm_from;
pub(crate) use install::local_spec_from_path;
pub(crate) use install::packument;
-pub(crate) use install::uninstall_deprecated_plugins;
pub use install::{
allow_policy_versions, allow_version_exemptions, inspect_specs, install, install_specs,
remove_many, update_many, IncompatibleVersion, PolicyBlockedVersion,
diff --git a/src-tauri/src/service/plugin/preset.rs b/src-tauri/src/service/plugin/preset.rs
index 92b6579f..8cefc89b 100644
--- a/src-tauri/src/service/plugin/preset.rs
+++ b/src-tauri/src/service/plugin/preset.rs
@@ -52,28 +52,6 @@ impl PreinstallPluginInfo {
.as_ref()
.is_some_and(|version| version.unsupported_on(core_version))
}
-
- /// 核心驱动的退役判定(弃用 / 被核心吸收后自动卸载)。
- ///
- /// - 核心命中某代区间:已装版本**旧于**该代声明的插件区间 → 退役(安装流程会按该代
- /// 区间钉版本重装,见 `preset_spec_for_install`);已装版本达到或超过区间下界
- /// (含超出区间上界的自升级版本,如声明 `^0.21.1` 实装 `0.22.0`)→ 保留,
- /// 区间是发布侧推荐而非硬上界,不能把用户的升级版本卸载掉;
- /// - 核心超出全部区间:已装版本仍落在任一同代区间内(旧版本)→ 退役;
- /// - 未声明区间 / 版本不可解析 / 已装版本无法解析 → 不退役(宁可保留也不误删)。
- pub(crate) fn retire_on(
- &self,
- core_version: Option<&str>,
- installed_version: Option<&str>,
- ) -> bool {
- let Some(version) = self.version.as_ref() else {
- return false;
- };
- if version.unsupported_on(core_version) {
- return version.matches_any_declared(installed_version);
- }
- version.outdated_for_core_generation(core_version, installed_version) == Some(true)
- }
}
/// 清单条目 → 统一插件信息:`checked` 是唯一真值,按前端预选语义派生出
@@ -478,13 +456,6 @@ pub(crate) fn presets_from_manifest(
/// 读取弃用插件名单(`resources/manifest.jsonc` 的 `plugins.depercated`),返回
/// 已登记的预设插件 id 集合。
-///
-/// 弃用是发布侧决策:某社区插件下架/被替换后,把它的 id 追加进清单,桌面端每次
-/// 启动核对「已安装 → 自动卸载」(见
-/// [`super::install::uninstall_deprecated_plugins`])。与 `plugins.preset` 分开
-/// 维护:预设清单只描述「可安装项」,弃用名单只描述「不再提供安装入口的预设 id」,
-/// 调整弃用名单不会让既有用户重新进入首次引导。清单缺失/损坏时回落为空集合,
-/// 不阻断启动(与其它清单同一降级策略)。
pub(crate) fn load_deprecated_ids(app_handle: &AppHandle) -> HashSet<String> {
config::manifest::read(app_handle)
.map(|manifest| manifest.plugins.deprecated.into_iter().collect())
@@ -635,42 +606,6 @@ mod tests {
}
}
- /// 核心驱动的退役判定:核心命中某代区间 → 已装版本不属于该代才退役(旧版插件在
- /// 核心换代后要卸掉,由安装流程按该代区间钉版本重装);核心超出全部区间 → 已安装
- /// 版本仍落在任一同代区间内才退役(新版本宁可保留)。
- #[test]
- fn retire_decision_matrix_follows_declared_ranges() {
- let declared = matrix(&[("^1.2.0", "^0.1.5-rc.1"), ("^1.4.0", "^0.1.7-rc.1")]);
- for (core, installed, retire) in [
- (Some("0.1.5-rc.3"), Some("1.2.0"), false),
- (Some("0.1.6"), Some("1.2.5"), false),
- (Some("0.1.6"), Some("1.4.0"), false),
- (Some("0.1.7-rc.2"), Some("1.4.0"), false),
- (Some("0.1.7-rc.2"), Some("1.2.0"), true),
- (Some("0.2.0"), Some("1.4.0"), true),
- (Some("0.2.0"), Some("1.2.0"), true),
- (Some("0.2.0"), Some("2.0.0"), false),
- (Some("0.2.0"), Some("1.0.0"), false),
- (Some("0.1.6"), None, false),
- (Some("0.1.6"), Some("invalid"), false),
- (None, Some("1.2.0"), false),
- (Some("invalid"), Some("1.2.0"), false),
- ] {
- let mut entry = load_presets_for_test()
- .into_iter()
- .find(|p| p.id == "dshmarket")
- .expect("dshmarket");
- entry.version = Some(declared.clone());
- assert_eq!(
- entry.retire_on(core, installed),
- retire,
- "core={core:?} installed={installed:?}"
- );
- }
- }
-
- /// 回归:同代内的预发布核心(如 `0.2.1-rc.1`)不得把插件判成不兼容,进而不该触发
- /// 退役;上一代遗留版本仍要退役重装。
#[test]
fn prerelease_core_in_same_generation_keeps_plugins() {
let mut entry = load_presets_for_test()
@@ -680,8 +615,6 @@ mod tests {
entry.version = Some(matrix(&[("^0.24.1", "^0.2.0-rc.1")]));
for core in ["0.2.0-rc.1", "0.2.0-rc.2", "0.2.0", "0.2.1-rc.1"] {
assert!(!entry.unsupported_on(Some(core)), "core={core}");
- assert!(!entry.retire_on(Some(core), Some("0.24.5")), "core={core}");
- assert!(entry.retire_on(Some(core), Some("0.23.0")), "core={core}");
}
}
@@ -827,40 +760,26 @@ mod tests {
#[test]
fn deprecated_manifest_lists_absorbed_panel() {
- // 0.15.0 把 dsh-tauri-panel 并入核心,并从内置清单移除了条目,
- // 升级用户只能靠弃用名单兜底卸载(残留 bundle 会导致无法进入软件页面)。
assert!(shipped_deprecated_ids().contains("dsh-tauri-panel"));
}
#[test]
fn deprecated_manifest_lists_absorbed_connection() {
- // dsh-tauri-connection 的载体鉴权适配已并入 dsh-tauri 核心插件,并从内置
- // 清单移除了条目:升级用户的 link: 依赖与 bundle 引用只能靠弃用名单兜底
- // 卸载(残留 bundle 会导致无法进入软件页面)。
assert!(shipped_deprecated_ids().contains("dsh-tauri-connection"));
}
#[test]
fn deprecated_manifest_lists_the_renamed_bridge() {
- // dsh-tauri-bridge 改名为 dsh-tauri-kernel(该功能已整体退役):老档案里的
- // link: 依赖与 bundle 引用只能靠弃用名单兜底卸载(残留 bundle 会导致无法进入
- // 软件页面)。
assert!(shipped_deprecated_ids().contains("dsh-tauri-bridge"));
}
#[test]
fn deprecated_manifest_lists_the_retired_kernel() {
- // dsh-tauri-kernel 因原生内核不稳定退役,并从内置清单移除了条目:升级用户的
- // link: 依赖与 bundle 引用只能靠弃用名单兜底卸载(残留 bundle 会导致无法进入
- // 软件页面)。
assert!(shipped_deprecated_ids().contains("dsh-tauri-kernel"));
}
#[test]
fn deprecated_manifest_lists_absorbed_running_changes() {
- // dsh-tauri-running-changes 已并入 dsh-tauri-experimental,并从内置清单移除
- // 条目:升级用户的残留副本仍从 dsh-tauri 导入 1.0.0 已移出的符号,启动即
- // import 失败,只能靠弃用名单兜底卸载。
assert!(shipped_deprecated_ids().contains("dsh-tauri-running-changes"));
}
@@ -1248,8 +1167,6 @@ mod tests {
std::fs::remove_dir_all(&root).ok();
}
- /// dev 候选覆盖静态条目时必须沿用清单声明的版本矩阵:退役判定读的是发布侧的
- /// 核心计划,与当前 checkout 是否存在该包源码无关。
#[cfg(debug_assertions)]
#[test]
fn dev_merge_carries_static_version_declaration() {
@@ -1285,9 +1202,6 @@ mod tests {
assert_eq!(renamed.description, "desc");
assert!(!renamed.unsupported_on(Some("0.1.7-alpha.0")));
assert!(renamed.unsupported_on(Some("0.2.0")));
- assert!(!renamed.retire_on(Some("0.1.7-alpha.0"), Some("1.2.3")));
- assert!(renamed.retire_on(Some("0.2.0"), Some("1.2.3")));
- assert!(!renamed.retire_on(Some("0.2.0"), Some("2.0.0")));
// dev 覆盖语义不变:条目仍来自仓库源码
assert!(renamed.internal);
std::fs::remove_dir_all(&root).ok();
diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rs
index 9ad0c445..35918694 100644
--- a/src-tauri/src/service/workflow/launch.rs
+++ b/src-tauri/src/service/workflow/launch.rs
@@ -768,13 +768,6 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
if let Err(e) = crate::service::plugin::ensure_profile_npmrc(&app_handle) {
log::warn!("ensure profile .npmrc failed: {e}");
}
- // 弃用插件自动卸载:`manifest.jsonc` 的 `plugins.depercated` 登记的社区插件若已安装,启动时
- // 自动移除(避免残留插件继续在 profile 里加载、甚至导致启动失败)。最佳努力:
- // 失败只告警,不阻断启动。
- if let Err(e) = crate::service::plugin::uninstall_deprecated_plugins(&app_handle).await {
- log::warn!("uninstall deprecated plugins failed: {e}");
- }
- mark_phase("deprecated_plugins", &mut phase_started);
// 内置插件自愈:随包分发的内置插件(dsh-tauri 等)必须在服务进程加载插件
// 前就绪——核对「已安装 + 安装路径指向当前捆绑目录」,未安装、路径不正确
// 或用户卸载后重启,一律强制重装(见 service::plugin::internal)。普通
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index c1c9c226..5dae8db8 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -435,9 +435,9 @@
"core.incompatible_title": "Incompatible versions ({{count}})",
"core.update_local": "Update Local Core",
"core.update_local_requires_app": "Switch to a managed core before updating",
- "core.update_local_requires_app_hint": "The package manager chooses the target version. Switch to a downloaded managed core first, update, then switch back manually and choose a matching profile.",
+ "core.update_local_requires_app_hint": "The package manager chooses the target version. Switch to a downloaded managed core first, update, then switch back manually.",
"core.updated_toast": "Local core updated: {{version}}",
- "core.updated_switch_back_hint": "The desktop will keep using the current managed core. Switch back to the local core manually and choose a matching profile when prompted.",
+ "core.updated_switch_back_hint": "The desktop will keep using the current managed core. Switch back to the local core manually.",
"core.update_failed": "Failed to update the local core",
"core.switch_restart_hint": "Core switched — restarting the service…",
"core.switch_failed": "Failed to switch the core",
@@ -454,11 +454,6 @@
"core.local_unsupported": "Unsupported",
"core.local_unsupported_toast": "Local core is too old",
"core.local_unsupported_hint": "Built-in plugins need dsh {{version}} or newer, so the bundled core is used instead. Update the local core before switching back to it.",
- "core.breaking_title": "Breaking changes",
- "core.breaking_desc": "{{from}} → {{to}} switches core versions (upgrade or downgrade). Mixing them is incompatible: a newer profile on an older core can fail startup when core bundles are unavailable, and an older profile on a newer core leaves packages that break plugins and settings. Switch to a matching profile.",
- "core.breaking_profile_label": "Profile name",
- "core.breaking_ignore": "Keep old profile",
- "core.breaking_profile_failed": "Failed to switch profile — the core was not switched",
"app.dev_env": "Development",
"app.config": "Running",
"config.application": "Application",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 2b61549e..1ea568b8 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -435,9 +435,9 @@
"core.incompatible_title": "不兼容版本({{count}})",
"core.update_local": "更新本地核心",
"core.update_local_requires_app": "请先切换到受管核心再更新",
- "core.update_local_requires_app_hint": "包管理器决定实际更新版本。请先切换到已下载的受管核心,更新后手动切回本地核心并选择配套档案。",
+ "core.update_local_requires_app_hint": "包管理器决定实际更新版本。请先切换到已下载的受管核心,更新后手动切回本地核心。",
"core.updated_toast": "本地核心已更新:{{version}}",
- "core.updated_switch_back_hint": "桌面端将继续使用当前受管核心。请手动切回本地核心,并在提示时选择配套档案。",
+ "core.updated_switch_back_hint": "桌面端将继续使用当前受管核心。请手动切回本地核心。",
"core.update_failed": "本地核心更新失败",
"core.switch_restart_hint": "核心已切换,正在自动重启服务…",
"core.switch_failed": "切换核心失败",
@@ -454,11 +454,6 @@
"core.local_unsupported": "不兼容",
"core.local_unsupported_toast": "本地核心版本过低",
"core.local_unsupported_hint": "内置插件需要 dsh {{version}} 及以上,已自动改用预打包核心。请先更新本地核心,再切换回它。",
- "core.breaking_title": "破坏性更改",
- "core.breaking_desc": "{{from}} → {{to}} 会切换核心版本(升级或降级),两者档案不兼容:较新档案配较旧核心时,核心包不可用会导致启动失败;较旧档案配较新核心会留下不配套的包,破坏插件与设置。请切换到配套档案。",
- "core.breaking_profile_label": "档案名称",
- "core.breaking_ignore": "仍沿用旧档案",
- "core.breaking_profile_failed": "切换档案失败,核心未切换",
"app.dev_env": "开发环境",
"app.config": "运行配置",
"config.application": "应用",
diff --git a/src/layout/index.tsx b/src/layout/index.tsx
index 537c2764..3f88f155 100644
--- a/src/layout/index.tsx
+++ b/src/layout/index.tsx
@@ -10,7 +10,6 @@ import { queryKeys } from '@/config/query-keys'
import { useListen } from '@/hooks/use-listen'
import { useThemeAdaptive } from '@/hooks/use-theme-adaptive'
import { useWakelockRelease } from '@/hooks/use-wakelock-release'
-import { useCoreProfileSwitch } from '@/ui/config/hooks/use-core-profile-switch'
import { toast } from '@/utils/toast'
import { store } from '../store'
import { Recovery } from '../ui/plugin/recovery'
@@ -41,7 +40,6 @@ export function App() {
const { status } = useStore(store.harness)
const { hydrated: settingReady, auto_update: autoUpdate } = useStore(store.setting)
const { updateInfo, updating } = useStore(store.harnessUpdater)
- const { holder: coreProfileSwitchHolder, guardCoreUpgrade } = useCoreProfileSwitch()
// issue #469:本应用没有屏幕常亮的正当需求(常驻播放的 <video> 会让系统无法息屏),
// 唤醒锁一旦生效就立刻释放。
@@ -133,26 +131,12 @@ export function App() {
useWatch([updateInfo, updating], () => {
if (!updateInfo || updating)
return
- store.harnessUpdater.showToast(() => handleUpdate())
+ store.harnessUpdater.showToast(() => store.harnessUpdater.handleUpdate())
}, { immediate: true })
- async function handleUpdate() {
- const info = store.harnessUpdater.updateInfo
- if (!info)
- return
- const guard = await guardCoreUpgrade(info.tag)
- if (!guard)
- return
- if (!(await store.harnessUpdater.handleUpdate()))
- await guard.rollback?.()
- }
-
return (
<div className="flex h-screen w-screen" data-testid="dsh-shell-root">
<Webview />
- <If cond={status === 'ready'}>
- {coreProfileSwitchHolder}
- </If>
{/* 运行期插件异常:应用仍在运行,弹醒目对话框(启动崩溃走 webview 的全屏恢复页) */}
<If cond={status === 'ready'}>
<Recovery />
diff --git a/src/store/modules/harness-updater/store.ts b/src/store/modules/harness-updater/store.ts
index 5840c906..8f6ea422 100644
--- a/src/store/modules/harness-updater/store.ts
+++ b/src/store/modules/harness-updater/store.ts
@@ -31,14 +31,7 @@ export const harnessUpdater = defineStore({
}
},
- /**
- * 手动更新:重新下载安装新版并重启服务。
- *
- * 返回是否真的发生了安装(新版本已落盘):false 表示未发生安装(已是最新/无法校验)
- * 或安装前就失败——调用方据此回滚为本次更新预先切换的版本档案(旧核心不能配新档案)。
- * 安装已落盘但随后的启动失败仍返回 true:核心已经是新版,把档案切回旧版本只会造出
- * 反向的不配套(新核心配旧档案),启动失败另有 `harness.fail` 的失败态呈现。
- */
+ /** 手动更新并重启服务,返回新版本是否已落盘。 */
async handleUpdate(): Promise<boolean> {
if (this.updating)
return false
@@ -77,8 +70,6 @@ export const harnessUpdater = defineStore({
catch (err) {
console.error('[Harness] update failed:', err)
harness.fail(String(err))
- // 已落盘的安装不能报成「没切换」:调用方会据此把档案切回旧版本,反而造出
- // 「新核心 + 旧档案」的不配套状态。
return installed
}
finally {
diff --git a/src/ui/config/core.test.tsx b/src/ui/config/core.test.tsx
index 12d183a2..bae695b1 100644
--- a/src/ui/config/core.test.tsx
+++ b/src/ui/config/core.test.tsx
@@ -80,7 +80,7 @@ function expectNoCoreOrProfileSwitch() {
function expectManagedWarning() {
expect(mocks.toast).toHaveBeenCalledWith('Switch to a managed core before updating', {
variant: 'warning',
- description: 'The package manager chooses the target version. Switch to a downloaded managed core first, update, then switch back manually and choose a matching profile.',
+ description: 'The package manager chooses the target version. Switch to a downloaded managed core first, update, then switch back manually.',
timeout: 10_000,
})
}
@@ -141,7 +141,7 @@ describe('本地核心更新档案安全', () => {
await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith('Local core updated: 0.2.2-rc.1', {
variant: 'success',
- description: 'The desktop will keep using the current managed core. Switch back to the local core manually and choose a matching profile when prompted.',
+ description: 'The desktop will keep using the current managed core. Switch back to the local core manually.',
timeout: 10_000,
}))
expect(mocks.invoke).toHaveBeenCalledWith('update_local_core')
@@ -159,7 +159,7 @@ describe('本地核心更新档案安全', () => {
await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith('Local core updated: 0.2.2-rc.1', {
variant: 'success',
- description: 'The desktop will keep using the current managed core. Switch back to the local core manually and choose a matching profile when prompted.',
+ description: 'The desktop will keep using the current managed core. Switch back to the local core manually.',
timeout: 10_000,
}))
expect(mocks.invoke).toHaveBeenCalledWith('update_local_core')
@@ -207,14 +207,15 @@ describe('本地核心更新档案安全', () => {
expect((screen.getByRole('button', { name: 'Update Local Core' }) as HTMLButtonElement).disabled).toBe(false)
})
- it('更新后手动切回本地新版本仍先询问配套档案,取消不切核心', async () => {
+ it('更新后手动切回只显示普通确认,取消不切核心', async () => {
renderCore()
fireEvent.click(await screen.findByRole('button', { name: 'Update Local Core' }))
const updatedLocal = await screen.findByRole('checkbox', { name: '0.2.2-rc.1' })
fireEvent.click(updatedLocal)
const dialog = await screen.findByRole('alertdialog')
- expect((within(dialog).getByRole('textbox', { name: 'Profile name' }) as HTMLInputElement).value).toBe('Core-0.2.2')
+ expect(within(dialog).queryByRole('textbox')).toBeNull()
+ expect(within(dialog).getByRole('heading').textContent).toBe('Warning')
expectNoCoreOrProfileSwitch()
fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))
diff --git a/src/ui/config/core.tsx b/src/ui/config/core.tsx
index b208d9b0..7b98b224 100644
--- a/src/ui/config/core.tsx
+++ b/src/ui/config/core.tsx
@@ -15,7 +15,6 @@ import { Panel } from '@/components/panel'
import { queryKeys } from '@/config/query-keys'
import { useInvalidateOnSettingUpdated } from '@/hooks/use-invalidate-on-setting-updated'
import { store } from '@/store'
-import { useCoreProfileSwitch } from '@/ui/config/hooks/use-core-profile-switch'
import { DownloadCoreDialog } from '@/ui/dialog/update-core'
import { compareVersions, isCoreUnsupported, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-version'
import { silence } from '@/utils/silence'
@@ -24,7 +23,6 @@ import { toast } from '@/utils/toast'
export function ConfigCore() {
const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })
const [downloadDialogHolder, openDownloadDialog] = useOverlay(DownloadCoreDialog, { type: 'holder' })
- const { holder: upgradeDialogHolder, guardCoreUpgrade } = useCoreProfileSwitch()
const { t } = useTranslation()
@@ -132,32 +130,26 @@ export function ConfigCore() {
})
return
}
- const activeCore = cores.find(c => c.active)
- const guard = await guardCoreUpgrade(coreVersionKey(core), activeCore ? coreVersionKey(activeCore) : '')
- if (!guard)
+ try {
+ const isRiskyVersion = core.recommendedVersion !== null
+ && (core.aboveRecommended || compareVersions(core.version, core.recommendedVersion) > 0)
+ await openDialog({
+ status: isRiskyVersion ? 'danger' : 'warning',
+ title: isRiskyVersion ? t('core.recommended_warning_title') : t('core.switch_confirm_title'),
+ description: (
+ <p>
+ <If
+ cond={isRiskyVersion}
+ then={t('core.recommended_warning_desc', { version: core.recommendedVersion ?? '' })}
+ else={t('core.switch_confirm_desc', { version: displayVersion(core) })}
+ />
+ </p>
+ ),
+ })
+ }
+ catch (e) {
+ silence(e, 'core switch: dialog cancelled')
return
- if (!guard.handled) {
- try {
- const isRiskyVersion = core.recommendedVersion !== null
- && (core.aboveRecommended || compareVersions(core.version, core.recommendedVersion) > 0)
- await openDialog({
- status: isRiskyVersion ? 'danger' : 'warning',
- title: isRiskyVersion ? t('core.recommended_warning_title') : t('core.switch_confirm_title'),
- description: (
- <p>
- <If
- cond={isRiskyVersion}
- then={t('core.recommended_warning_desc', { version: core.recommendedVersion ?? '' })}
- else={t('core.switch_confirm_desc', { version: displayVersion(core) })}
- />
- </p>
- ),
- })
- }
- catch (e) {
- silence(e, 'core switch: dialog cancelled')
- return
- }
}
try {
// 激活后由 restart 完成时统一失效核心查询;这里不等待联网列表重拉,
@@ -181,9 +173,6 @@ export function ConfigCore() {
catch (err) {
console.error('[ConfigCore] switch failed:', err)
toast(t('core.switch_failed'), {})
- // 核心没切成就把档案切回去:否则下次启动会跑在「旧核心 + 新档案」上,
- // 用户会看到自己的插件与设置「凭空消失」。
- await guard.rollback?.()
}
}
@@ -487,7 +476,6 @@ export function ConfigCore() {
{dialogHolder}
{downloadDialogHolder}
- {upgradeDialogHolder}
</div>
)
}
@@ -497,11 +485,6 @@ function displayVersion(version: HarnessCore): string {
return version.version || (version.source === 'local' ? 'local' : 'app')
}
-/** 版本判定用的版本串:版本号缺失时回落到 release tag(列表排序同款兜底) */
-function coreVersionKey(core: HarnessCore): string {
- return core.version || core.tag
-}
-
function isUnsupportedLocal(core: HarnessCore): boolean {
return core.source === 'local' && core.present && isUnsupportedCore(core)
}
diff --git a/src/ui/config/debug.test.tsx b/src/ui/config/debug.test.tsx
index 83fb29e5..6a6ec735 100644
--- a/src/ui/config/debug.test.tsx
+++ b/src/ui/config/debug.test.tsx
@@ -25,9 +25,6 @@ vi.mock('@/hooks/use-listen', () => ({ useListen: () => {} }))
vi.mock('@/ui/config/components/close-action', () => ({ ConfigCloseAction: () => null }))
vi.mock('@/ui/config/components/auto-update', () => ({ ConfigAutoUpdate: () => null }))
vi.mock('@/ui/config/components/launch-on-login', () => ({ ConfigLaunchOnLogin: () => null }))
-vi.mock('@/ui/config/hooks/use-core-profile-switch', () => ({
- useCoreProfileSwitch: () => ({ holder: null, guardCoreUpgrade: vi.fn() }),
-}))
vi.mock('valtio-define', () => {
const store = (state: unknown) => ({
$state: state,
diff --git a/src/ui/config/debug.tsx b/src/ui/config/debug.tsx
index 22c219c6..71e3952b 100644
--- a/src/ui/config/debug.tsx
+++ b/src/ui/config/debug.tsx
@@ -16,7 +16,6 @@ import { HARNESS_HEAP_MAX_MB, HARNESS_HEAP_MIN_MB } from '@/store/modules/settin
import { ConfigAutoUpdate } from '@/ui/config/components/auto-update'
import { ConfigCloseAction } from '@/ui/config/components/close-action'
import { ConfigLaunchOnLogin } from '@/ui/config/components/launch-on-login'
-import { useCoreProfileSwitch } from '@/ui/config/hooks/use-core-profile-switch'
import { writeClipboardText } from '@/utils/clipboard'
import { toast } from '@/utils/toast'
@@ -46,7 +45,6 @@ export function ConfigDebug() {
const { t, i18n } = useTranslation()
const { serviceRunning, busyAction } = useStore(store.harness)
const { updateInfo } = useStore(store.harnessUpdater)
- const { holder: coreProfileSwitchHolder, guardCoreUpgrade } = useCoreProfileSwitch()
// 端口编辑态:用户尚未输入时为 undefined,展示值始终以 store 中已保存的端口为准。
// 初值不写入 state(避免渲染期副作用),用户一旦输入即以输入值为准。
@@ -77,18 +75,7 @@ export function ConfigDebug() {
})
function handleShowNewVersion() {
- store.harnessUpdater.showToast(() => handleUpdate())
- }
-
- async function handleUpdate() {
- const info = store.harnessUpdater.updateInfo
- if (!info)
- return
- const guard = await guardCoreUpgrade(info.tag)
- if (!guard)
- return
- if (!(await store.harnessUpdater.handleUpdate()))
- await guard.rollback?.()
+ store.harnessUpdater.showToast(() => store.harnessUpdater.handleUpdate())
}
const { mutate: onToggleCliLink } = useMutation({
@@ -257,7 +244,6 @@ export function ConfigDebug() {
</Button>
)}
/>
- {coreProfileSwitchHolder}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-xs font-semibold uppercase tracking-wider text-muted">
diff --git a/src/ui/config/hooks/use-core-profile-switch.tsx b/src/ui/config/hooks/use-core-profile-switch.tsx
deleted file mode 100644
index 2bc269a0..00000000
--- a/src/ui/config/hooks/use-core-profile-switch.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import type { HarnessCore, Profile, RuntimeInfo } from '@/types'
-import type { CoreUpgradeChoice, CoreUpgradeProfileDialogProps } from '@/ui/dialog/core-upgrade-profile'
-import { useOverlay } from '@overlastic/react'
-import { useQueryClient } from '@tanstack/react-query'
-import { invoke } from '@tauri-apps/api/core'
-import { useTranslation } from 'react-i18next'
-import { queryKeys } from '@/config/query-keys'
-import { CoreUpgradeProfileDialog } from '@/ui/dialog/core-upgrade-profile'
-import { coreProfileName, isCoreUpgrade } from '@/utils/core-version'
-import { normalizeProfileId } from '@/utils/profile-id'
-import { toast } from '@/utils/toast'
-
-/** 核心换版前的档案确认结果 */
-export interface CoreUpgradeGuard {
- /** 警告弹窗是否已处理切换确认(true 时调用方不必再弹普通切换确认) */
- handled: boolean
- /** 回滚到切换前的档案;未切换过时为 undefined */
- rollback?: () => Promise<void>
-}
-
-/**
- * 切换/更新核心前的「版本不配套 → 请切换档案」守卫,三个入口共用:
- * 核心面板切换、更新提示 toast(桌面外壳)、调试页「存在新版本」。
- *
- * 核心与档案配套:主/次/修订号变化(升级或降级,issue #748)前,先让用户换成与目标版本同名的
- * 版本档案(缺失则新建)。降级沿用较新档案时,旧核心找不到档案里的包,Harness 无法启动;
- * 升级沿用旧档案则会把不配套的包留在原档案里。同一 x.y.z 的预发布互换不弹窗。
- *
- * 版本比对必须走本地数据:核心面板直接把列表里已加载的「在用核心」版本传进来;
- * 未传时退回只用本地信息的 `get_runtime_info`——绝不能为比对去拉 `get_cores`
- * (它要联网取 GitHub releases,用户点一下要白等数秒)。
- */
-export function useCoreProfileSwitch() {
- const [holder, openDialog] = useOverlay<CoreUpgradeProfileDialogProps, CoreUpgradeChoice>(CoreUpgradeProfileDialog, { type: 'holder' })
- const queryClient = useQueryClient()
- const { t } = useTranslation()
-
- /**
- * 在用核心的版本串(本地读取,不做联网比对):优先现成的核心列表缓存,
- * 缺失时退回 `get_runtime_info`(本地读 store/清单)。
- */
- async function localActiveVersion(): Promise<string> {
- const cached = queryClient.getQueryData<HarnessCore[]>(queryKeys.cores)
- const cachedActive = cached?.find(c => c.active)
- if (cachedActive)
- return cachedActive.version || cachedActive.tag
- const info = await queryClient.fetchQuery({
- queryKey: queryKeys.info,
- queryFn: () => invoke<RuntimeInfo>('get_runtime_info'),
- })
- return info.dsh_version ?? ''
- }
-
- /**
- * 目标版本与在用核心的主/次/修订号不同(升级或降级)时弹警告并按用户选择处理档案。
- *
- * `fromVersion` 由调用方从本地已有数据传入(核心面板传列表里的在用核心版本);
- * 省略时退回本地读取。
- *
- * 返回 null = 中止本次切换(用户取消,或档案切换失败——失败提示由本 hook 发出)。
- */
- async function guardCoreUpgrade(toVersion: string, fromVersion?: string): Promise<CoreUpgradeGuard | null> {
- const from = fromVersion ?? await localActiveVersion()
- // isCoreUpgrade 仍只表示「目标更高」。两个方向一起看,降级才会同样隔离档案。
- if (!isCoreUpgrade(from, toVersion) && !isCoreUpgrade(toVersion, from))
- return { handled: false }
-
- let choice: CoreUpgradeChoice
- try {
- choice = await openDialog({
- fromVersion: from,
- toVersion,
- defaultName: coreProfileName(toVersion),
- })
- }
- catch {
- return null
- }
- // 明确无视风险时不改档案。沿用当前档案仍可能与目标核心不兼容(issue #748)。
- if (choice.mode === 'ignore')
- return { handled: true }
-
- try {
- const profiles = await queryClient.fetchQuery({
- queryKey: queryKeys.profiles,
- queryFn: () => invoke<Profile[]>('get_profiles'),
- })
- const previousId = profiles.find(p => p.active)?.id ?? ''
- const id = normalizeProfileId(choice.name)
- const existing = profiles.find(p => p.id === id)
- let switchedId = id
- if (existing) {
- if (!existing.active)
- await invoke<Profile>('set_active_profile', { id })
- }
- else {
- const created = await invoke<Profile>('create_profile', { name: choice.name })
- switchedId = created.id
- await invoke<Profile>('set_active_profile', { id: created.id })
- }
- void queryClient.invalidateQueries({ queryKey: queryKeys.profiles })
- return {
- handled: true,
- rollback: async () => {
- if (!previousId || previousId === switchedId)
- return
- try {
- await invoke<Profile>('set_active_profile', { id: previousId })
- }
- catch (err) {
- console.error('[CoreProfileSwitch] restore active profile failed:', err)
- }
- finally {
- void queryClient.invalidateQueries({ queryKey: queryKeys.profiles })
- }
- },
- }
- }
- catch (err) {
- console.error('[CoreProfileSwitch] switch version profile failed:', err)
- toast(t('core.breaking_profile_failed'), {})
- return null
- }
- }
-
- return { holder, guardCoreUpgrade }
-}
diff --git a/src/ui/dialog/core-upgrade-profile.tsx b/src/ui/dialog/core-upgrade-profile.tsx
deleted file mode 100644
index 2e751c38..00000000
--- a/src/ui/dialog/core-upgrade-profile.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import type { PropsWithOverlays } from '@overlastic/react'
-import { TriangleExclamationFill } from '@gravity-ui/icons'
-import { AlertDialog, Button, Chip, InputGroup, Label, TextField } from '@heroui/react'
-import { useDisclosure } from '@overlastic/react'
-import { useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { normalizeProfileId } from '@/utils/profile-id'
-
-/** 核心升级时的选择:切到配套档案,或无视风险直接切核心 */
-export type CoreUpgradeChoice
- = | { mode: 'profile', name: string }
- | { mode: 'ignore' }
-
-export interface CoreUpgradeProfileDialogProps extends PropsWithOverlays {
- /** 当前使用中的核心版本(展示用) */
- fromVersion: string
- /** 目标核心版本(展示用) */
- toVersion: string
- /** 档案名默认值:目标版本号(含 patch,如 `Core-0.1.7`;同一 patch 的 rc 共用档案) */
- defaultName: string
-}
-
-/**
- * 「升级到更新的核心」警告对话框:核心与档案配套,升到任何更新的 dsh 版本都可能破坏
- * 当前档案里的插件与设置。
- *
- * - 确认:resolve `{ mode: 'profile', name }`,由调用方创建/切换档案后再切核心并重启;
- * - 「无视风险切换」:resolve `{ mode: 'ignore' }`,跳过档案切换直接切核心;
- * - 取消/关闭:reject,调用方中止本次切换。
- */
-export function CoreUpgradeProfileDialog(props: CoreUpgradeProfileDialogProps) {
- const disclosure = useDisclosure({ props })
- const { t } = useTranslation()
- const [name, setName] = useState(props.defaultName)
- const profileId = normalizeProfileId(name)
-
- function confirmProfile() {
- if (!profileId)
- return
- disclosure.confirm({ mode: 'profile', name })
- }
-
- return (
- <AlertDialog onOpenChange={disclosure.cancel} isOpen={disclosure.visible}>
- <AlertDialog.Backdrop>
- <AlertDialog.Container>
- <AlertDialog.Dialog className="sm:max-w-[420px]">
- <AlertDialog.CloseTrigger />
- <AlertDialog.Header>
- <AlertDialog.Icon status="danger" />
- <AlertDialog.Heading>{t('core.breaking_title')}</AlertDialog.Heading>
- </AlertDialog.Header>
- <AlertDialog.Body className="space-y-3">
- <p className="text-xs leading-[1.7] text-muted">
- {t('core.breaking_desc', { from: props.fromVersion, to: props.toVersion })}
- </p>
- <TextField className="w-full" name="profile">
- <Label>{t('core.breaking_profile_label')}</Label>
- <InputGroup fullWidth variant="secondary">
- <InputGroup.Input
- autoFocus
- value={name}
- onChange={e => setName(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter')
- confirmProfile()
- }}
- />
- </InputGroup>
- </TextField>
- </AlertDialog.Body>
- <AlertDialog.Footer className="justify-end">
- <Chip className="cursor-pointer" color="warning" variant="soft" onClick={() => disclosure.confirm({ mode: 'ignore' })}>
- <TriangleExclamationFill width={12} />
- {t('core.breaking_ignore')}
- </Chip>
- <div className="flex flex-row items-center gap-2">
- <Button variant="tertiary" onPress={disclosure.cancel}>
- {t('buttons.cancel')}
- </Button>
- <Button
- variant="primary"
- isDisabled={!profileId}
- onPress={confirmProfile}
- >
- {t('buttons.confirm')}
- </Button>
- </div>
- </AlertDialog.Footer>
- </AlertDialog.Dialog>
- </AlertDialog.Container>
- </AlertDialog.Backdrop>
- </AlertDialog>
- )
-}
diff --git a/src/utils/core-version.ts b/src/utils/core-version.ts
index 02e0bcba..b22d62e4 100644
--- a/src/utils/core-version.ts
+++ b/src/utils/core-version.ts
@@ -20,25 +20,6 @@ export function compareVersions(a: string, b: string): number {
return semver.compare(pa, pb)
}
-export function coreProfileName(version: string): string {
- const parsed = semver.parse(normalizeVersion(version))
- return parsed ? `Core-${parsed.major}.${parsed.minor}.${parsed.patch}` : ''
-}
-
-export function isCoreUpgrade(from: string, to: string): boolean {
- const current = semver.parse(normalizeVersion(from))
- const target = semver.parse(normalizeVersion(to))
- if (!current || !target)
- return false
- const currentCore = [current.major, current.minor, current.patch]
- const targetCore = [target.major, target.minor, target.patch]
- for (let index = 0; index < currentCore.length; index += 1) {
- if (targetCore[index]! !== currentCore[index]!)
- return targetCore[index]! > currentCore[index]!
- }
- return false
-}
-
export function isCoreUnsupported(version: string): boolean {
return compareVersions(version, MIN_SUPPORTED_CORE_VERSION) < 0
}
diff --git a/test/core-upgrade-profile.test.ts b/test/core-upgrade-profile.test.ts
index 0bd6078f..e909a806 100644
--- a/test/core-upgrade-profile.test.ts
+++ b/test/core-upgrade-profile.test.ts
@@ -1,260 +1,36 @@
import { describe, expect, it } from 'vitest'
import { readLocale, readSource } from './setup/read-source'
-/**
- * 「版本号变化(升级或降级)→ 请切换档案」链路的结构契约。
- *
- * 前端不在单测里挂载组件(与 clone-profile.test.ts 同款跨层守卫),因此读源码断言结构:
- * 期望值一律取自需求本身(顺序、命令名、i18n key、双向本地比对),不与被测实现同源。
- *
- * 三个入口共用同一个守卫 hook:核心面板切换、更新提示 toast(桌面外壳)、调试页更新按钮。
- */
-const guardSource = readSource('src/ui/config/hooks/use-core-profile-switch.tsx')
const coreSource = readSource('src/ui/config/core.tsx')
-const dialogSource = readSource('src/ui/dialog/core-upgrade-profile.tsx')
const layoutSource = readSource('src/layout/index.tsx')
const debugSource = readSource('src/ui/config/debug.tsx')
-const updaterSource = readSource('src/store/modules/harness-updater/store.ts')
-/** 取组件内某个顶层函数的函数体(到该函数自己的 `\n }` 为止,嵌套块缩进更深不会误截) */
-function bodyOf(source: string, marker: string): string {
- const start = source.indexOf(marker)
- expect(start, marker).toBeGreaterThan(-1)
- const rest = source.slice(start)
- const end = rest.indexOf('\n }')
- return end === -1 ? rest : rest.slice(0, end)
-}
-
-/** 取 `handleUpdate` 的函数体(更新入口在桌面外壳与调试页各有一份) */
-function updateBody(source: string): string {
- return bodyOf(source, 'async function handleUpdate')
-}
-
-describe('版本比对一律走本地数据', () => {
- it('守卫不为比对联网重拉核心列表', () => {
- expect(guardSource).not.toContain('\'get_cores\'')
- })
-
- it('「升级前」版本优先取现成的核心列表缓存,缺失才退回本地命令', () => {
- const body = bodyOf(guardSource, 'async function localActiveVersion')
-
- expect(body).toContain('queryClient.getQueryData<HarnessCore[]>(queryKeys.cores)')
- expect(body).toMatch(/cachedActive = cached\?\.find\(c => c\.active\)/)
- expect(body).toContain('invoke<RuntimeInfo>(\'get_runtime_info\')')
- })
-
- it('核心面板直接把列表里已加载的在用核心版本传进守卫', () => {
- const body = bodyOf(coreSource, 'async function onActivate')
-
- expect(body).toContain('cores.find(c => c.active)')
- expect(body).toMatch(/guardCoreUpgrade\(coreVersionKey\(core\), activeCore \? coreVersionKey\(activeCore\) : ''\)/)
- expect(body).not.toContain('\'get_cores\'')
- })
-
- it('核心号任一方向变化都要换档案,默认档案名取目标版本号(含 patch,Core-x.y.z)', () => {
- const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
- const bypass = body.indexOf('return { handled: false }')
-
- expect(body).toContain('isCoreUpgrade(from, toVersion)')
- expect(body).toContain('isCoreUpgrade(toVersion, from)')
- expect(body.indexOf('isCoreUpgrade(from, toVersion)')).toBeLessThan(bypass)
- expect(body.indexOf('isCoreUpgrade(toVersion, from)')).toBeLessThan(bypass)
- expect(body).toContain('coreProfileName(toVersion)')
- expect(body).toMatch(/defaultName:/)
- })
-})
-
-describe('核心面板:升级弹档案警告,不再叠加普通切换确认', () => {
- it('取消档案警告即中止本次切换(不落档案、不切核心)', () => {
- const body = bodyOf(coreSource, 'async function onActivate')
- const guardIndex = body.indexOf('guardCoreUpgrade(')
- const handledIndex = body.indexOf('if (!guard.handled)')
-
- expect(guardIndex).toBeGreaterThan(-1)
- expect(handledIndex).toBeGreaterThan(guardIndex)
- // 守卫返回 null = 用户取消或档案切换失败:直接结束,绝不走到激活
- const beforeHandled = body.slice(guardIndex, handledIndex)
- expect(beforeHandled).toMatch(/if \(!guard\)\n\s*return/)
- expect(beforeHandled).not.toContain('activate.mutateAsync')
- })
-
- it('破坏性升级时改弹档案警告,普通确认只在未命中升级时出现', () => {
- const body = bodyOf(coreSource, 'async function onActivate')
- const handledIndex = body.indexOf('if (!guard.handled)')
-
- expect(handledIndex).toBeGreaterThan(-1)
- expect(body.slice(0, handledIndex)).not.toContain('core.switch_confirm_title')
- expect(body.slice(handledIndex)).toContain('core.switch_confirm_title')
- })
-
- it('先落版本档案,再切核心,最后重启', () => {
- const body = bodyOf(coreSource, 'async function onActivate')
- const guardIndex = body.indexOf('await guardCoreUpgrade(')
- const coreIndex = body.indexOf('activate.mutateAsync(core.id)')
- const restartIndex = body.indexOf('store.harness.restart()')
-
- // 档案在守卫内部(弹窗确认后)落定,返回后才切核心;切核心成功才重启
- expect(guardIndex).toBeGreaterThan(-1)
- expect(coreIndex).toBeGreaterThan(guardIndex)
- expect(restartIndex).toBeGreaterThan(coreIndex)
- })
-
- it('核心切换失败时回滚到切换前的档案', () => {
- const body = bodyOf(coreSource, 'async function onActivate')
- const failureIndex = body.indexOf('core.switch_failed')
- expect(failureIndex).toBeGreaterThan(-1)
-
- const failureBranch = body.slice(failureIndex)
- expect(failureBranch).toContain('await guard.rollback?.()')
- })
-})
-
-describe('守卫:档案缺失才新建,已存在只切换,失败即中止', () => {
- it('按后端归一化后的 id 匹配在用档案列表', () => {
- const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
-
- expect(body).toContain('invoke<Profile[]>(\'get_profiles\')')
- expect(body).toContain('normalizeProfileId(choice.name)')
- expect(body).toMatch(/profiles\.find\(p => p\.id === id\)/)
- })
-
- it('已存在且在用时不重复切换,缺失时新建并切为使用中', () => {
- const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
-
- expect(body).toMatch(/if \(!existing\.active\)\n\s*await invoke<Profile>\('set_active_profile', \{ id \}\)/)
- expect(body).toContain('invoke<Profile>(\'create_profile\', { name: choice.name })')
- expect(body).toContain('invoke<Profile>(\'set_active_profile\', { id: created.id })')
- })
-
- it('档案切换失败时提示并中止(不切核心)', () => {
- const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
- const failureIndex = body.indexOf('core.breaking_profile_failed')
-
- expect(failureIndex).toBeGreaterThan(-1)
- expect(body.slice(failureIndex)).toMatch(/return null/)
- })
-
- it('回滚切回原档案,失败只记日志,并始终失效档案查询', () => {
- const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
-
- expect(body).toContain('previousId === switchedId')
- expect(body).toContain('invoke<Profile>(\'set_active_profile\', { id: previousId })')
- expect(body).toMatch(/console\.error/)
- expect(body).toMatch(/finally \{/)
- expect(body).toContain('queryKeys.profiles')
- })
-
- it('「无视风险切换」保持档案不变,只切核心', () => {
- const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
+describe('核心换版沿用当前档案', () => {
+ for (const [name, source] of [['core', coreSource], ['layout', layoutSource], ['debug', debugSource]] as const) {
+ it(`${name} 不再拦截换版或自动切换档案`, () => {
+ expect(source).not.toContain('useCoreProfileSwitch')
+ expect(source).not.toContain('guardCoreUpgrade')
+ expect(source).not.toContain('create_profile')
+ expect(source).not.toContain('set_active_profile')
+ })
+ }
- expect(body).toMatch(/if \(choice\.mode === 'ignore'\)\n\s*return \{ handled: true \}/)
- // ignore 分支必须在读档案列表之前返回,避免无谓的档案请求
- expect(body.indexOf('choice.mode === \'ignore\'')).toBeLessThan(body.indexOf('invoke<Profile[]>(\'get_profiles\')'))
+ it('手动切换保留普通确认,激活成功后仍重启服务', () => {
+ expect(coreSource).toContain('core.switch_confirm_title')
+ const activate = coreSource.indexOf('await runBusy(core.id, () => activate.mutateAsync(core.id))')
+ expect(activate).toBeGreaterThan(-1)
+ expect(coreSource.indexOf('await store.harness.restart()', activate)).toBeGreaterThan(activate)
})
-})
-describe('更新提示入口(桌面外壳 / 调试页)走同一守卫', () => {
for (const [name, source] of [['layout', layoutSource], ['debug', debugSource]] as const) {
- it(`${name}:「立即更新」只走档案守卫,落档案后更新、失败回滚`, () => {
- const body = updateBody(source)
- const guardIndex = body.indexOf('await guardCoreUpgrade(info.tag)')
- const updateIndex = body.indexOf('if (!(await store.harnessUpdater.handleUpdate()))')
- const rollbackIndex = body.indexOf('await guard.rollback?.()')
-
- expect(source, '不得再次叠加已废弃的版本确认').not.toContain('confirmCoreBreaking')
- expect(guardIndex, '更新前必须调用档案守卫').toBeGreaterThan(-1)
- expect(updateIndex, '必须先落定档案,再更新核心').toBeGreaterThan(guardIndex)
- expect(body.slice(guardIndex, updateIndex), '取消或档案切换失败必须阻断更新').toMatch(/if \(!guard\)\n\s*return/)
- expect(rollbackIndex, '核心更新失败后必须回滚档案').toBeGreaterThan(updateIndex)
- expect(body.slice(updateIndex, rollbackIndex), '档案回滚只能发生在更新未切换的分支').not.toContain('}')
- expect(source, '档案守卫对话框必须挂进渲染树').toContain('{coreProfileSwitchHolder}')
+ it(`${name} 更新入口直接执行核心更新`, () => {
+ expect(source).toContain('store.harnessUpdater.showToast(() => store.harnessUpdater.handleUpdate())')
})
}
- it('handleUpdate 返回是否真的切到了新版本,供调用方决定是否回滚', () => {
- const source = updaterSource
-
- expect(source).toMatch(/async handleUpdate\(\): Promise<boolean>/)
- expect(source).toMatch(/return false/)
- expect(source).toMatch(/return true/)
- })
-
- it('已落盘的新版本即使随后启动失败也不报「没切换」(否则会回滚出旧档案配新核心)', () => {
- const source = updaterSource
-
- // 安装结果记在 try 之外,catch 里回传它而不是一律 false
- expect(source).toMatch(/let installed = false/)
- expect(source).toMatch(/installed = changed/)
- expect(source).toMatch(/catch \(err\) \{[\s\S]*?return installed/)
- })
-})
-
-describe('警告对话框控件', () => {
- it('档案名默认填目标版本号(含 patch)、可编辑,并用 InputGroup 组合而非自绘 Label + Input', () => {
- const source = dialogSource
-
- expect(source).toMatch(/useState\(props\.defaultName\)/)
- expect(source).toMatch(/value=\{name\}/)
- expect(source).toMatch(/onChange=\{e => setName\(e\.target\.value\)\}/)
- expect(source).toMatch(/import \{[^}]+InputGroup[^}]+Label[^}]+TextField[^}]*\} from '@heroui\/react'/)
- expect(source).toMatch(/<TextField[\s>]/)
- expect(source).toMatch(/<Label>/)
- expect(source).toMatch(/<InputGroup[\s>]/)
- expect(source).toMatch(/<InputGroup\.Input/)
- expect(source).not.toMatch(/<Input[\s>]/)
- })
-
- it('「无视风险切换」是 warning Chip,与取消/确认按钮同处一行的 footer', () => {
- const source = dialogSource
- const footerStart = source.indexOf('<AlertDialog.Footer')
- const footerEnd = source.indexOf('</AlertDialog.Footer>')
-
- expect(footerStart).toBeGreaterThan(-1)
- expect(footerEnd).toBeGreaterThan(footerStart)
-
- const footer = source.slice(footerStart, footerEnd)
- expect(source).toMatch(/import \{[^}]+Chip[^}]*\} from '@heroui\/react'/)
- expect(footer).toMatch(/<Chip[\s>]/)
- expect(footer).toMatch(/color="warning"/)
- expect(footer).toContain('core.breaking_ignore')
- expect(footer).toMatch(/disclosure\.confirm\(\{ mode: 'ignore' \}\)/)
- expect(footer).toContain('buttons.cancel')
- expect(footer).toContain('buttons.confirm')
- expect(footer).toContain('disclosure.cancel')
- expect(source).toMatch(/disclosure\.confirm\(\{ mode: 'profile', name \}\)/)
- })
-
- it('归一化后为空的档案名禁止确认', () => {
- const source = dialogSource
-
- expect(source).toMatch(/const profileId = normalizeProfileId\(name\)/)
- expect(source).toMatch(/isDisabled=\{!profileId\}/)
- })
-
- it('danger 状态的 AlertDialog,警告文案同时给出源版本与目标版本', () => {
- const source = dialogSource
-
- expect(source).toMatch(/status="danger"/)
- expect(source).toMatch(/core\.breaking_desc', \{ from: props\.fromVersion, to: props\.toVersion \}/)
- })
-})
-
-describe('i18n parity', () => {
- const keys = [
- 'core.breaking_title',
- 'core.breaking_desc',
- 'core.breaking_profile_label',
- 'core.breaking_ignore',
- 'core.breaking_profile_failed',
- ]
-
for (const locale of ['zh-CN', 'en-US']) {
- it(`includes all core.breaking* keys in ${locale}`, () => {
- const messages = readLocale(locale)
- for (const key of keys) {
- expect(typeof messages[key], key).toBe('string')
- expect(messages[key].length, key).toBeGreaterThan(0)
- }
+ it(`${locale} 移除过时的破坏性更改文案`, () => {
+ expect(Object.keys(readLocale(locale)).filter(key => key.startsWith('core.breaking'))).toEqual([])
})
}
})
diff --git a/test/core-version.test.ts b/test/core-version.test.ts
index adc4eeec..8050d18a 100644
--- a/test/core-version.test.ts
+++ b/test/core-version.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { compareVersions, coreProfileName, isCoreUnsupported, isCoreUpgrade, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-version'
-import { normalizeProfileId } from '@/utils/profile-id'
+import { compareVersions, isCoreUnsupported, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-version'
describe('compareVersions', () => {
it.each([
@@ -77,83 +76,3 @@ describe('isCoreUnsupported', () => {
expect(isCoreUnsupported(version)).toBe(false)
})
})
-
-describe('coreProfileName', () => {
- it('取主/次/补丁版本号并加 Core- 前缀,丢掉预发布标识', () => {
- expect(coreProfileName('0.1.7-rc.2')).toBe('Core-0.1.7')
- expect(coreProfileName('0.2.1-rc.1')).toBe('Core-0.2.1')
- expect(coreProfileName('0.17.1')).toBe('Core-0.17.1')
- expect(coreProfileName('0.18.0-rc.1')).toBe('Core-0.18.0')
- expect(coreProfileName('1.2.3')).toBe('Core-1.2.3')
- })
-
- it.each(['0.1.7-alpha.1', '0.1.7-rc.1', '0.1.7-rc.2', '0.1.7'])('%s 共用 Core-0.1.7 档案名', (version) => {
- expect(coreProfileName(version)).toBe('Core-0.1.7')
- })
-
- it('剥掉 dsh-/src- 前缀后再取名,包括旧安装的 tag', () => {
- expect(coreProfileName('dsh-0.1.0-rc.8-32331963388')).toBe('Core-0.1.0')
- expect(coreProfileName('dsh-src-0.2.1-rc.1-39009013600')).toBe('Core-0.2.1')
- expect(coreProfileName('src-2.0.0')).toBe('Core-2.0.0')
- })
-
- it.each(['', 'local', 'app-0.1.0-rc.8'])('版本 %s 缺失或不可解析时为空串', (version) => {
- expect(coreProfileName(version)).toBe('')
- })
-
- it('patch 不同的两个核心归一化后仍有各自可读的档案 id', () => {
- expect(normalizeProfileId(coreProfileName('0.1.5-rc.2'))).toBe('core-015')
- expect(normalizeProfileId(coreProfileName('0.1.7-rc.2'))).toBe('core-017')
- expect(normalizeProfileId(coreProfileName('0.2.1-rc.1'))).toBe('core-021')
- })
-})
-
-describe('isCoreUpgrade', () => {
- it('核心号变大(含 patch)都算升级,包括旧安装迁移', () => {
- expect(isCoreUpgrade('0.1.5', '0.1.7')).toBe(true)
- expect(isCoreUpgrade('0.1.7-rc.1', '0.2.1-rc.1')).toBe(true)
- expect(isCoreUpgrade('0.2.0-rc.2', '0.2.1-rc.1')).toBe(true)
- expect(isCoreUpgrade('0.17.1', '0.18.0')).toBe(true)
- expect(isCoreUpgrade('0.17.1', '1.0.0')).toBe(true)
- expect(isCoreUpgrade('0.17.1', '2.0.0')).toBe(true)
- expect(isCoreUpgrade('0.1.5-rc.1', '0.1.6-alpha.2')).toBe(true)
- })
-
- it('同一核心号的预发布标识互换不算升级', () => {
- expect(isCoreUpgrade('0.1.7-rc.1', '0.1.7-rc.2')).toBe(false)
- expect(isCoreUpgrade('0.1.7-rc.2', '0.1.7-rc.1')).toBe(false)
- expect(isCoreUpgrade('0.1.7-rc.2', '0.1.7-alpha.1')).toBe(false)
- expect(isCoreUpgrade('0.1.5-rc.1', '0.1.5')).toBe(false)
- expect(isCoreUpgrade('0.1.5', '0.1.5-rc.1')).toBe(false)
- expect(isCoreUpgrade('0.2.1-alpha.1', '0.2.1-rc.1')).toBe(false)
- expect(isCoreUpgrade('0.2.1-rc.1', '0.2.1')).toBe(false)
- })
-
- it('平级不算升级', () => {
- expect(isCoreUpgrade('0.1.5', '0.1.5')).toBe(false)
- expect(isCoreUpgrade('0.1.5-rc.1', '0.1.5-rc.1')).toBe(false)
- expect(isCoreUpgrade('0.2.1-rc.1', '0.2.1-rc.1')).toBe(false)
- })
-
- it('降级不算升级', () => {
- expect(isCoreUpgrade('0.2.1-rc.1', '0.1.7-rc.1')).toBe(false)
- expect(isCoreUpgrade('0.2.1-rc.1', '0.2.0-rc.2')).toBe(false)
- expect(isCoreUpgrade('0.1.7', '0.1.5')).toBe(false)
- expect(isCoreUpgrade('0.1.7-rc.2', '0.1.5-rc.1')).toBe(false)
- expect(isCoreUpgrade('0.18.0', '0.17.1')).toBe(false)
- expect(isCoreUpgrade('1.0.0', '0.9.9')).toBe(false)
- })
-
- it('任一侧版本缺失或不可解析时不误报', () => {
- expect(isCoreUpgrade('', '0.18.0')).toBe(false)
- expect(isCoreUpgrade('local', '0.18.0')).toBe(false)
- expect(isCoreUpgrade('0.17.1', '')).toBe(false)
- expect(isCoreUpgrade('0.17.1', 'app')).toBe(false)
- })
-
- it('带 dsh-/src- 前缀的 release tag 按同一版本判定', () => {
- expect(isCoreUpgrade('dsh-0.1.5-rc.8-1', 'src-0.1.7')).toBe(true)
- expect(isCoreUpgrade('dsh-0.1.7-rc.1-1', 'src-0.1.7-rc.2-2')).toBe(false)
- expect(isCoreUpgrade('dsh-src-0.2.0-rc.2-38900000000', 'src-0.2.1-rc.1-39009013600')).toBe(true)
- })
-})