DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(desktop): 升级弹窗改用 InputGroup/Link,版本比对与切换回包不再联网
hairyf18942099a169
diff --git a/src-tauri/src/service/core/version.rs b/src-tauri/src/service/core/version.rsindex 7b4bdc14..3ad35255 100644--- a/src-tauri/src/service/core/version.rs+++ b/src-tauri/src/service/core/version.rs@@ -68,6 +68,54 @@ fn read_manifest_dsh_version(dir: &Path) -> Option<String> {/// tags(无 label,预览标记按 tag 命名兜底),再失败降级为磁盘扫描,只列出/// 本地、激活与已下载的历史版本。pub async fn list(app_handle: &AppHandle) -> Vec<HarnessCore> {+ let (release_metas, remote_catalog_available) = fetch_release_catalog(app_handle).await;+ rows_with_release_catalog(app_handle, release_metas, remote_catalog_available)+}++/// 版本行数据源:GitHub releases → git tags → 空(离线/限流时调用方降级为磁盘扫描)。+async fn fetch_release_catalog(+ app_handle: &AppHandle,+) -> (Vec<download::DshPkgReleaseMeta>, bool) {+ match download::fetch_dsh_pkg_releases().await {+ Ok(metas) => (metas, true),+ Err(e) => {+ log::warn!(+ "Failed to fetch dsh pkg releases ({}), falling back to git tags",+ e+ );+ match download::fetch_dsh_pkg_tags().await {+ Ok(tags) => (+ tags.into_iter()+ .map(|(tag, _)| download::DshPkgReleaseMeta {+ tag,+ prerelease: false,+ })+ .collect(),+ true,+ ),+ Err(e) => {+ log::warn!("Failed to fetch dsh pkg tags: {}", e);+ (Vec::new(), false)+ }+ }+ }+ }+}++/// 只用本地信息(激活记录 + 磁盘槽位)构造核心列表,不联网。+///+/// 核心切换是纯本地操作,回包不该等一轮 GitHub 往返(`fetch_dsh_pkg_releases`+/// 数秒级,离线更久);切换后的「新激活行」与离线列表都走这条路。+fn list_local(app_handle: &AppHandle) -> Vec<HarnessCore> {+ rows_with_release_catalog(app_handle, Vec::new(), false)+}++/// 按给定版本行数据源构造核心列表(`release_metas` 为空即离线/本地视图)。+fn rows_with_release_catalog(+ app_handle: &AppHandle,+ release_metas: Vec<download::DshPkgReleaseMeta>,+ remote_catalog_available: bool,+) -> Vec<HarnessCore> {let source = active_source(app_handle);let local = local_core(app_handle);let local_bin = local@@ -123,30 +171,6 @@ pub async fn list(app_handle: &AppHandle) -> Vec<HarnessCore> {// 版本行:GitHub releases(最新在前,含 Pre-release label)→ 按版本去重,// 同版本只保留最后一个 tag。releases 拉取失败(离线/限流)时回退 git tags,// 预览标记按 tag 命名兜底(见 `download::is_preview_tag`)。- let (release_metas, remote_catalog_available) = match download::fetch_dsh_pkg_releases().await {- Ok(metas) => (metas, true),- Err(e) => {- log::warn!(- "Failed to fetch dsh pkg releases ({}), falling back to git tags",- e- );- match download::fetch_dsh_pkg_tags().await {- Ok(tags) => (- tags.into_iter()- .map(|(tag, _)| download::DshPkgReleaseMeta {- tag,- prerelease: false,- })- .collect(),- true,- ),- Err(e) => {- log::warn!("Failed to fetch dsh pkg tags: {}", e);- (Vec::new(), false)- }- }- }- };let mut version_tags: Vec<(String, String, bool)> = Vec::new(); // (version, tag, preview),保持首次出现顺序for meta in &release_metas {let Some(version) = download::parse_version_from_tag(&meta.tag) else {@@ -379,12 +403,13 @@ pub async fn set_active(app_handle: &AppHandle, id: &str) -> Result<HarnessCore,} else {return Err(format!("CORE_INVALID_ID: {id}"));}- // 查询核心列表可能联网;不要让慢查询继续占用切换锁,重启流程会在- // set_active 返回后通过同一把锁与启动串行化。+ // 先释放切换锁再构造回包:重启流程要拿同一把锁与启动串行化,而回包已是纯本地+ // 构造(`list_local`),不必也不该在锁内多做一步。drop(transition_guard);- list(app_handle)- .await+ // 回包只用本地列表构造,不再调用联网的 `list()`:核心切换是本地操作,为拿一个+ // 返回行等一轮 GitHub 往返会让「切换核心」白等数秒(离线更久)。+ list_local(app_handle).into_iter().find(|c| c.active).ok_or_else(|| "CORE_NOT_FOUND: active core disappeared after switch".to_string())diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex cd537e9b..bb5b7397 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -330,7 +330,7 @@"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": "Upgrading from {{from}} to {{to}} crosses a major/minor version and may break the plugins and settings in the current profile. Switch to a matching profile: confirming creates or switches to that profile, then switches the core and restarts.",+ "core.breaking_desc": "{{from}} → {{to}} has breaking changes that may break this profile's plugins and settings. Switch to a matching profile.","core.breaking_profile_label": "Profile name","core.breaking_ignore": "Switch anyway","core.breaking_profile_failed": "Failed to switch profile — the core was not switched",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex ae847989..77769d23 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -330,7 +330,7 @@"core.local_unsupported_toast": "本地核心版本过低","core.local_unsupported_hint": "内置插件需要 dsh {{version}} 及以上,已自动改用预打包核心。请先更新本地核心,再切换回它。","core.breaking_title": "破坏性更改",- "core.breaking_desc": "从 {{from}} 升级到 {{to}} 跨越了主/次版本,可能破坏当前档案中的插件与设置。请切换到配套档案:确认后将自动创建或切换该档案,再切换核心并重启。",+ "core.breaking_desc": "{{from}} → {{to}} 含破坏性更改,可能破坏当前档案的插件与设置。请切换到配套档案。","core.breaking_profile_label": "档案名称","core.breaking_ignore": "无视风险切换","core.breaking_profile_failed": "切换档案失败,核心未切换",diff --git a/src/layout/index.tsx b/src/layout/index.tsxindex 132761de..94c205f2 100644--- a/src/layout/index.tsx+++ b/src/layout/index.tsx@@ -11,6 +11,7 @@ import { useListen } from '@/hooks/use-listen'import { useThemeAdaptive } from '@/hooks/use-theme-adaptive'import { useWakelockRelease } from '@/hooks/use-wakelock-release'import { useCoreBreakingConfirm } from '@/ui/config/hooks/use-core-breaking-confirm'+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,6 +42,7 @@ export function App() {const { status } = useStore(store.harness)const { updateInfo, updating } = useStore(store.harnessUpdater)const { holder: coreBreakingHolder, confirmCoreBreaking } = useCoreBreakingConfirm()+ const { holder: coreProfileSwitchHolder, guardCoreUpgrade } = useCoreProfileSwitch()// issue #469:本应用没有屏幕常亮的正当需求(常驻播放的 <video> 会让系统无法息屏),// 唤醒锁一旦生效就立刻释放。@@ -132,12 +134,19 @@ export function App() {store.harnessUpdater.showToast(() => handleUpdate())}, { immediate: true })- /** 点击「立即更新」:目标版本高于 rc.2 时先弹破坏性更改确认,取消则中止更新 */+ /**+ * 点击「立即更新」:目标版本高于 rc.2 时先弹破坏性更改确认,取消则中止更新;+ * 目标版本是升级时先落到配套版本档案,更新失败再把档案切回去。+ */async function handleUpdate() {const info = store.harnessUpdater.updateInfoif (!info || !(await confirmCoreBreaking(info.tag)))return- await store.harnessUpdater.handleUpdate()+ const guard = await guardCoreUpgrade(info.tag)+ if (!guard)+ return+ if (!(await store.harnessUpdater.handleUpdate()))+ await guard.rollback?.()}return (@@ -146,6 +155,9 @@ export function App() {<If cond={status === 'ready'}>{coreBreakingHolder}</If>+ <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.tsindex 99781ac2..2ddd278c 100644--- a/src/store/modules/harness-updater/store.ts+++ b/src/store/modules/harness-updater/store.ts@@ -31,10 +31,15 @@ export const harnessUpdater = defineStore({}},- /** 手动更新:重新下载安装新版并重启服务 */- async handleUpdate() {+ /**+ * 手动更新:重新下载安装新版并重启服务。+ *+ * 返回是否真的切到了新版本:false 表示未发生安装(已是最新/无法校验)或安装失败——+ * 调用方据此回滚为本次更新预先切换的版本档案(旧核心不能配新档案)。+ */+ async handleUpdate(): Promise<boolean> {if (this.updating)- return+ return falsethis.updating = truelet unlistenInstall: UnlistenFn | null = nulltry {@@ -59,14 +64,16 @@ export const harnessUpdater = defineStore({if (this.updateInfo) {toast(i18next.t('update.verify_failed'), { variant: 'danger' })}- return+ return false}await harness.launchAndWait()this.updateInfo = null+ return true}catch (err) {console.error('[Harness] update failed:', err)harness.fail(String(err))+ return false}finally {unlistenInstall?.()diff --git a/src/types/index.ts b/src/types/index.tsindex a395d487..04bd702b 100644--- a/src/types/index.ts+++ b/src/types/index.ts@@ -1,3 +1,4 @@export * from './core'export * from './plugin'export * from './profile'+export * from './runtime'diff --git a/src/types/runtime.ts b/src/types/runtime.tsnew file mode 100644index 00000000..f645a6f1--- /dev/null+++ b/src/types/runtime.ts@@ -0,0 +1,12 @@+/** Rust 侧 `config::RuntimeInfo` 的序列化形态(snake_case) */+export interface RuntimeInfo {+ app_version: string+ /** 当前活动核心的版本号(本地读取,界面展示用) */+ dsh_version: string | null+ node_version: string+ service_url: string+ data_dir: string+ log_path: string+ platform: string+ arch: string+}diff --git a/src/ui/config/core.tsx b/src/ui/config/core.tsxindex f54e63ce..308f23a9 100644--- a/src/ui/config/core.tsx+++ b/src/ui/config/core.tsx@@ -1,5 +1,4 @@-import type { HarnessCore, Profile } from '@/types'-import type { CoreUpgradeChoice, CoreUpgradeProfileDialogProps } from '@/ui/dialog/core-upgrade-profile'+import type { HarnessCore } from '@/types'import { ArrowRotateRight, ChevronRight, CircleArrowDown as DownloadIcon, FolderOpen } from '@gravity-ui/icons'import { Button, Checkbox, Chip, Description, Label, Spinner } from '@heroui/react'import { useOverlay } from '@overlastic/react'@@ -17,10 +16,9 @@ import { queryKeys } from '@/config/query-keys'import { useInvalidateOnSettingUpdated } from '@/hooks/use-invalidate-on-setting-updated'import { store } from '@/store'import { useCoreBreakingConfirm } from '@/ui/config/hooks/use-core-breaking-confirm'-import { CoreUpgradeProfileDialog } from '@/ui/dialog/core-upgrade-profile'+import { useCoreProfileSwitch } from '@/ui/config/hooks/use-core-profile-switch'import { DownloadCoreDialog } from '@/ui/dialog/update-core'-import { compareVersions, coreMajorMinor, isCoreMajorMinorUpgrade, isCoreUnsupported, 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'import { silence } from '@/utils/silence'import { toast } from '@/utils/toast'@@ -34,7 +32,7 @@ import { toast } from '@/utils/toast'* 降级为 git tags / 磁盘扫描,仅显示已下载版本)。预览版(Pre-release label* 或 tag 命名)照常列出、可下载安装,但带「预览版」标签、不参与更新提示。* - 切换核心:持久化后**自动重启**服务(需求 5),重启走 harness store 的- * restart 流程(停止 → 重新启动 → 健康检查)。跨主/次版本升级时先弹「破坏性更改」+ * restart 流程(停止 → 重新启动 → 健康检查)。升级到更新的版本时先弹「破坏性更改」* 警告,确认后把当前档案换成与目标版本配套的版本档案(缺失则新建),再切核心并重启。* - 下载版本:拉指定 tag 的发布资产到历史槽位(不激活),随后可切换;* 卸载仅允许非激活的已下载版本。@@ -45,7 +43,7 @@ import { toast } from '@/utils/toast'export function ConfigCore() {const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })const [downloadDialogHolder, openDownloadDialog] = useOverlay(DownloadCoreDialog, { type: 'holder' })- const [upgradeDialogHolder, openUpgradeDialog] = useOverlay<CoreUpgradeProfileDialogProps, CoreUpgradeChoice>(CoreUpgradeProfileDialog, { type: 'holder' })+ const { holder: upgradeDialogHolder, guardCoreUpgrade } = useCoreProfileSwitch()const { holder: coreBreakingHolder, confirmCoreBreaking } = useCoreBreakingConfirm()const { t } = useTranslation()@@ -139,46 +137,6 @@ export function ConfigCore() {}}- /**- * 取(或建)版本档案并切为使用中:同名档案已存在则直接切换,缺失才新建。- *- * 档案名按后端归一化后的 id 匹配(`0.17` → `017`),因此这里先取列表再决定是否新建,- * 不能直接 create——已存在时后端会以 `PROFILE_EXISTS` 拒绝。- *- * 返回 `previousId`(切换前使用中的档案)供核心切换失败时回滚:档案与核心是两次独立的- * 写盘,核心没切成不能把用户留在「旧核心 + 新档案」的组合上。- */- async function activateVersionProfile(name: string): Promise<{ id: string, previousId: string }> {- const profiles = await queryClient.fetchQuery({- queryKey: queryKeys.profiles,- queryFn: () => invoke<Profile[]>('get_profiles'),- })- const previousId = profiles.find(p => p.active)?.id ?? ''- const id = normalizeProfileId(name)- const existing = profiles.find(p => p.id === id)- if (existing) {- if (!existing.active)- await invoke<Profile>('set_active_profile', { id })- return { id, previousId }- }- const created = await invoke<Profile>('create_profile', { name })- await invoke<Profile>('set_active_profile', { id: created.id })- return { id: created.id, previousId }- }-- /** 回滚档案:核心切换失败时切回原档案;回滚失败只记日志,不盖住原始失败提示 */- async function restoreActiveProfile(id: string) {- try {- await invoke<Profile>('set_active_profile', { id })- }- catch (err) {- console.error('[ConfigCore] restore active profile failed:', err)- }- finally {- void queryClient.invalidateQueries({ queryKey: queryKeys.profiles })- }- }-async function onActivate(core: HarnessCore) {if (core.active || busy || !core.present)return@@ -192,32 +150,14 @@ export function ConfigCore() {})return}+ // 升级到更新的 dsh 版本 = 破坏性更改:先把当前档案换成配套档案,档案名默认取目标+ // 版本的 x.x。该弹窗自带「切换」语义,命中时不再叠加一次普通的切换确认。+ // 版本比对只用列表里已加载的在用核心,不为此联网重拉核心列表。const activeCore = cores.find(c => c.active)- const fromVersion = activeCore ? displayVersion(activeCore) : ''- const toVersion = displayVersion(core)- // 跨主/次版本升级 = 破坏性更改:核心与档案配套,先让用户把当前档案换成配套档案。- // 该弹窗本身包含「切换」语义,因此不再叠加一次普通的切换确认。- const breakingUpgrade = isCoreMajorMinorUpgrade(- activeCore ? coreVersionKey(activeCore) : '',- coreVersionKey(core),- )- let profileName = ''- if (breakingUpgrade) {- try {- const choice = await openUpgradeDialog({- fromVersion,- toVersion,- defaultName: coreMajorMinor(coreVersionKey(core)),- })- if (choice.mode === 'profile')- profileName = choice.name- }- catch (e) {- silence(e, 'core switch: breaking upgrade dialog cancelled')- return- }- }- else {+ const guard = await guardCoreUpgrade(coreVersionKey(core), activeCore ? coreVersionKey(activeCore) : '')+ if (!guard)+ return+ if (!guard.handled) {try {const isRiskyVersion = core.recommendedVersion !== null&& (core.aboveRecommended || compareVersions(core.version, core.recommendedVersion) > 0)@@ -240,22 +180,6 @@ export function ConfigCore() {return}}- // 先落档案再切核心:两者都由同一次重启生效,顺序颠倒会让新核心先于配套档案运行。- let previousProfileId = ''- let switchedProfileId = ''- if (profileName) {- try {- const activated = await activateVersionProfile(profileName)- previousProfileId = activated.previousId- switchedProfileId = activated.id- void queryClient.invalidateQueries({ queryKey: queryKeys.profiles })- }- catch (err) {- console.error('[ConfigCore] switch version profile failed:', err)- toast(t('core.breaking_profile_failed'), {})- return- }- }try {// 激活后由 restart 完成时统一失效核心查询;这里不等待联网列表重拉,// 避免 setting 已切换但旧服务仍运行期间人为扩大竞态窗口。@@ -280,8 +204,7 @@ export function ConfigCore() {toast(t('core.switch_failed'), {})// 核心没切成就把档案切回去:否则下次启动会跑在「旧核心 + 新档案」上,// 用户会看到自己的插件与设置「凭空消失」。- if (previousProfileId && previousProfileId !== switchedProfileId)- await restoreActiveProfile(previousProfileId)+ await guard.rollback?.()}}diff --git a/src/ui/config/debug.tsx b/src/ui/config/debug.tsxindex cb343935..5b639a68 100644--- a/src/ui/config/debug.tsx+++ b/src/ui/config/debug.tsx@@ -1,3 +1,4 @@+import type { RuntimeInfo } from '@/types'import { ArrowRotateRight, ArrowUpRightFromSquare, ChevronRight, Copy, Folder, Power } from '@gravity-ui/icons'import { Button, Chip, Description, Input, Link, ListBox, Select, Spinner, Switch } from '@heroui/react'import { useMutation, useQuery } from '@tanstack/react-query'@@ -15,21 +16,11 @@ import { HARNESS_HEAP_MAX_MB, HARNESS_HEAP_MIN_MB } from '@/store/modules/settinimport { ConfigCloseAction } from '@/ui/config/components/close-action'import { ConfigLaunchOnLogin } from '@/ui/config/components/launch-on-login'import { useCoreBreakingConfirm } from '@/ui/config/hooks/use-core-breaking-confirm'+import { useCoreProfileSwitch } from '@/ui/config/hooks/use-core-profile-switch'import { toast } from '@/utils/toast'const ZOOM_OPTIONS = Array.from({ length: 16 }, (_, index) => Number((0.5 + index * 0.1).toFixed(1)))-export interface RuntimeInfo {- app_version: string- dsh_version: string | null- node_version: string- service_url: string- data_dir: string- log_path: string- platform: string- arch: string-}-export interface CliLinkStatus {enabled: booleanshim_exists: boolean@@ -44,6 +35,7 @@ export function ConfigDebug() {const { serviceRunning, busyAction } = useStore(store.harness)const { updateInfo } = useStore(store.harnessUpdater)const { holder: coreBreakingHolder, confirmCoreBreaking } = useCoreBreakingConfirm()+ const { holder: coreProfileSwitchHolder, guardCoreUpgrade } = useCoreProfileSwitch()// 端口编辑态:用户尚未输入时为 undefined,展示值始终以 store 中已保存的端口为准。// 初值不写入 state(避免渲染期副作用),用户一旦输入即以输入值为准。@@ -76,12 +68,19 @@ export function ConfigDebug() {store.harnessUpdater.showToast(() => handleUpdate())}- /** 点击「立即更新」:目标版本高于 rc.2 时先弹破坏性更改确认,取消则中止更新 */+ /**+ * 点击「立即更新」:目标版本高于 rc.2 时先弹破坏性更改确认,取消则中止更新;+ * 目标版本是升级时先落到配套版本档案,更新失败再把档案切回去。+ */async function handleUpdate() {const info = store.harnessUpdater.updateInfoif (!info || !(await confirmCoreBreaking(info.tag)))return- await store.harnessUpdater.handleUpdate()+ const guard = await guardCoreUpgrade(info.tag)+ if (!guard)+ return+ if (!(await store.harnessUpdater.handleUpdate()))+ await guard.rollback?.()}const { mutate: onToggleCliLink } = useMutation({@@ -190,6 +189,7 @@ export function ConfigDebug() {<div className="space-y-3"><Panel.Header title={t('config.application')} testId="dsh-config-panel-title" />{coreBreakingHolder}+ {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.tsxnew file mode 100644index 00000000..6541c54d--- /dev/null+++ b/src/ui/config/hooks/use-core-profile-switch.tsx@@ -0,0 +1,124 @@+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 { coreMajorMinor, 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(桌面外壳)、调试页「存在新版本」。+ *+ * 核心与档案配套:换到更新的 dsh 版本前,先让用户把当前档案换成与目标版本同名的+ * 版本档案(缺失则新建),新版本的插件与设置才不会破坏原档案。+ *+ * 版本比对必须走本地数据:核心面板直接把列表里已加载的「在用核心」版本传进来;+ * 未传时退回只用本地信息的 `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()+ if (!isCoreUpgrade(from, toVersion))+ return { handled: false }++ let choice: CoreUpgradeChoice+ try {+ choice = await openDialog({+ fromVersion: from,+ toVersion,+ defaultName: coreMajorMinor(toVersion),+ })+ }+ catch {+ return null+ }+ 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.tsxindex 6bf2a472..259a5d30 100644--- a/src/ui/dialog/core-upgrade-profile.tsx+++ b/src/ui/dialog/core-upgrade-profile.tsx@@ -1,11 +1,11 @@import type { PropsWithOverlays } from '@overlastic/react'-import { AlertDialog, Button, Input, Label, Link } from '@heroui/react'+import { AlertDialog, Button, InputGroup, Label, Link, 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' }@@ -20,7 +20,8 @@ export interface CoreUpgradeProfileDialogProps extends PropsWithOverlays {}/**- * 「跨主/次版本升级」警告对话框:核心与档案配套,跨版本升级可能破坏当前档案里的插件与设置。+ * 「升级到更新的核心」警告对话框:核心与档案配套,升到任何更新的 dsh 版本都可能破坏+ * 当前档案里的插件与设置。** - 确认:resolve `{ mode: 'profile', name }`,由调用方创建/切换档案后再切核心并重启;* - 「无视风险切换」:resolve `{ mode: 'ignore' }`,跳过档案切换直接切核心;@@ -52,39 +53,38 @@ export function CoreUpgradeProfileDialog(props: CoreUpgradeProfileDialogProps) {<p className="text-xs leading-[1.7] text-muted">{t('core.breaking_desc', { from: props.fromVersion, to: props.toVersion })}</p>- <div className="space-y-1.5">- <Label className="text-xs">{t('core.breaking_profile_label')}</Label>- <Input- autoFocus- variant="secondary"- className="h-8 w-full rounded-md"- value={name}- onChange={e => setName(e.target.value)}- onKeyDown={(e) => {- if (e.key === 'Enter')- confirmProfile()- }}- />- </div>- <Link- className="text-xs text-warning"- onPress={() => disclosure.confirm({ mode: 'ignore' })}- >+ <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">+ <Link className="text-warning" onPress={() => disclosure.confirm({ mode: 'ignore' })}>{t('core.breaking_ignore')}</Link>- </AlertDialog.Body>- <AlertDialog.Footer>- <Button className="rounded-md" variant="tertiary" onPress={disclosure.cancel}>- {t('buttons.cancel')}- </Button>- <Button- className="rounded-md"- variant="primary"- isDisabled={!profileId}- onPress={confirmProfile}- >- {t('buttons.confirm')}- </Button>+ <div className="flex flex-row items-center gap-2">+ <Button className="rounded-md" variant="tertiary" onPress={disclosure.cancel}>+ {t('buttons.cancel')}+ </Button>+ <Button+ className="rounded-md"+ variant="primary"+ isDisabled={!profileId}+ onPress={confirmProfile}+ >+ {t('buttons.confirm')}+ </Button>+ </div></AlertDialog.Footer></AlertDialog.Dialog></AlertDialog.Container>diff --git a/src/utils/core-version.ts b/src/utils/core-version.tsindex 03bd6229..dae9e3e7 100644--- a/src/utils/core-version.ts+++ b/src/utils/core-version.ts@@ -35,19 +35,21 @@ export function coreMajorMinor(version: string): string {}/**- * 目标核心是否相对当前核心跨了主/次版本(patch 升级不算)。+ * 目标核心是否相对在用核心做了升级(任意新版:大版本/小版本/补丁都算)。+ *+ * 核心与档案是配套的:换到任何更新的 dsh 版本都可能破坏当前档案里的插件与设置,切换前+ * 先提示用户换配套档案。判据取「目标 > 在用」而非「跨主/次版本」——dsh 在 0.1.x 上持续推进+ * 破坏性更改(0.1.5 → 0.1.7 就是一次),只跨主/次版本会漏掉这些升级提示。*- * 核心与档案是配套的:跨主/次版本意味着破坏性更改,切换前必须把当前档案换成配套档案。* 不可解析(本地核心版本号缺失、首次切换没有在用核心)一律返回 false——漏提示只是少了* 一次提醒,误判会把正常切换挡在弹窗后面。*/-export function isCoreMajorMinorUpgrade(from: string, to: string): boolean {+export function isCoreUpgrade(from: string, to: string): boolean {const current = semver.parse(stripVersionPrefix(from))const target = semver.parse(stripVersionPrefix(to))if (!current || !target)return falsereturn semver.gt(target, current)- && (target.major !== current.major || target.minor !== current.minor)}/** 判断核心版本(版本串或 release tag)是否高于 rc.2 基准(引入破坏性更改) */diff --git a/test/core-upgrade-profile.test.ts b/test/core-upgrade-profile.test.tsindex a04aa851..577a159a 100644--- a/test/core-upgrade-profile.test.ts+++ b/test/core-upgrade-profile.test.ts@@ -2,13 +2,19 @@ import { readFileSync } from 'node:fs'import { describe, expect, it } from 'vitest'/**- * 「跨主/次版本升级 → 请切换档案」链路的结构契约。+ * 「升级到更新的核心 → 请切换档案」链路的结构契约。** 前端不在单测里挂载组件(与 clone-profile.test.ts 同款跨层守卫),因此读源码断言结构:- * 期望值一律取自需求本身(顺序、命令名、i18n key),不与被测实现同源。+ * 期望值一律取自需求本身(顺序、命令名、i18n key、本地比对),不与被测实现同源。+ *+ * 三个入口共用同一个守卫 hook:核心面板切换、更新提示 toast(桌面外壳)、调试页更新按钮。*/+const guardSource = (): string => readFileSync(new URL('../src/ui/config/hooks/use-core-profile-switch.tsx', import.meta.url), 'utf8')const coreSource = (): string => readFileSync(new URL('../src/ui/config/core.tsx', import.meta.url), 'utf8')const dialogSource = (): string => readFileSync(new URL('../src/ui/dialog/core-upgrade-profile.tsx', import.meta.url), 'utf8')+const layoutSource = (): string => readFileSync(new URL('../src/layout/index.tsx', import.meta.url), 'utf8')+const debugSource = (): string => readFileSync(new URL('../src/ui/config/debug.tsx', import.meta.url), 'utf8')+const updaterSource = (): string => readFileSync(new URL('../src/store/modules/harness-updater/store.ts', import.meta.url), 'utf8')/** 取组件内某个顶层函数的函数体(到该函数自己的 `\n }` 为止,嵌套块缩进更深不会误截) */function bodyOf(source: string, marker: string): string {@@ -19,155 +25,185 @@ function bodyOf(source: string, marker: string): string {return end === -1 ? rest : rest.slice(0, end)}-describe('破坏性升级的判定与警告入口', () => {- it('用「在用核心 → 目标核心」的主/次版本跨度判定,而不是只看目标版本', () => {- const body = bodyOf(coreSource(), 'async function onActivate')+/** 取 `handleUpdate` 的函数体(更新入口在桌面外壳与调试页各有一份) */+function updateBody(source: string): string {+ return bodyOf(source, 'async function handleUpdate')+}- expect(body).toContain('isCoreMajorMinorUpgrade(')- expect(body).toContain('cores.find(c => c.active)')- // 判定两侧都取「版本号缺失时回落 release tag」的版本串- expect(body).toMatch(/coreVersionKey\(activeCore\)/)- expect(body).toMatch(/coreVersionKey\(core\)/)+describe('版本比对一律走本地数据', () => {+ it('守卫不为比对联网重拉核心列表', () => {+ expect(guardSource()).not.toContain('\'get_cores\'')})- it('警告弹窗的默认档案名取目标版本的主/次版本号(x.x)', () => {- const body = bodyOf(coreSource(), 'async function onActivate')+ it('「升级前」版本优先取现成的核心列表缓存,缺失才退回本地命令', () => {+ const body = bodyOf(guardSource(), 'async function localActiveVersion')- expect(body).toMatch(/coreMajorMinor\(coreVersionKey\(core\)\)/)- expect(body).toMatch(/defaultName:/)+ 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('破坏性升级时改弹档案警告,不再叠加普通切换确认', () => {+ it('核心面板直接把列表里已加载的在用核心版本传进守卫', () => {const body = bodyOf(coreSource(), 'async function onActivate')- const upgradeIndex = body.indexOf('openUpgradeDialog')- expect(upgradeIndex).toBeGreaterThan(-1)- // 普通确认(core.switch_confirm_title)只能出现在 breakingUpgrade 之外的 else 分支- const elseIndex = body.indexOf('else {', upgradeIndex)- expect(elseIndex).toBeGreaterThan(upgradeIndex)- expect(body.slice(upgradeIndex, elseIndex)).not.toContain('core.switch_confirm_title')- expect(body.slice(elseIndex)).toContain('core.switch_confirm_title')+ expect(body).toContain('cores.find(c => c.active)')+ expect(body).toMatch(/guardCoreUpgrade\(coreVersionKey\(core\), activeCore \? coreVersionKey\(activeCore\) : ''\)/)+ expect(body).not.toContain('\'get_cores\'')+ })++ it('任何更新的版本都判定为升级,默认档案名取目标版本的主/次版本号(x.x)', () => {+ const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')++ expect(body).toContain('isCoreUpgrade(from, toVersion)')+ expect(body).toContain('coreMajorMinor(toVersion)')+ expect(body).toMatch(/defaultName:/)})+})- it('取消警告即中止本次切换(不落档案、不切核心)', () => {+describe('核心面板:升级弹档案警告,不再叠加普通切换确认', () => {+ it('取消档案警告即中止本次切换(不落档案、不切核心)', () => {const body = bodyOf(coreSource(), 'async function onActivate')- const upgradeIndex = body.indexOf('openUpgradeDialog')- const elseIndex = body.indexOf('else {', upgradeIndex)- const cancelBranch = body.slice(upgradeIndex, elseIndex)+ const guardIndex = body.indexOf('guardCoreUpgrade(')+ const handledIndex = body.indexOf('if (!guard.handled)')- expect(cancelBranch).toContain('silence(')- expect(cancelBranch).toMatch(/return/)- expect(cancelBranch).not.toContain('activate.mutateAsync')+ 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('「无视风险切换」保持档案不变,只切核心', () => {+ it('破坏性升级时改弹档案警告,普通确认只在未命中升级时出现', () => {const body = bodyOf(coreSource(), 'async function onActivate')+ const handledIndex = body.indexOf('if (!guard.handled)')- // 只有选择 profile 才写入 profileName;ignore 分支不赋值 → 跳过档案切换- expect(body).toMatch(/if \(choice\.mode === 'profile'\)\n\s*profileName = choice\.name/)- expect(body).toMatch(/if \(profileName\) \{/)+ expect(handledIndex).toBeGreaterThan(-1)+ expect(body.slice(0, handledIndex)).not.toContain('core.switch_confirm_title')+ expect(body.slice(handledIndex)).toContain('core.switch_confirm_title')})-})-describe('确认后的编排顺序:档案 → 核心 → 重启', () => {it('先落版本档案,再切核心,最后重启', () => {const body = bodyOf(coreSource(), 'async function onActivate')- const profileIndex = body.indexOf('await activateVersionProfile(profileName)')+ const guardIndex = body.indexOf('await guardCoreUpgrade(')const coreIndex = body.indexOf('activate.mutateAsync(core.id)')const restartIndex = body.indexOf('store.harness.restart()')- expect(profileIndex).toBeGreaterThan(-1)- expect(coreIndex).toBeGreaterThan(profileIndex)+ // 档案在守卫内部(弹窗确认后)落定,返回后才切核心;切核心成功才重启+ 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.breaking_profile_failed')- expect(failureIndex).toBeGreaterThan(-1)-- const failureBranch = body.slice(body.lastIndexOf('catch', failureIndex), body.indexOf('try {', failureIndex))- expect(failureBranch).toContain('core.breaking_profile_failed')- expect(failureBranch).toMatch(/return/)- })-it('核心切换失败时回滚到切换前的档案', () => {const body = bodyOf(coreSource(), 'async function onActivate')const failureIndex = body.indexOf('core.switch_failed')expect(failureIndex).toBeGreaterThan(-1)- const failureBranch = body.slice(body.lastIndexOf('catch', failureIndex))- expect(failureBranch).toMatch(/await restoreActiveProfile\(previousProfileId\)/)- // 档案本来就没换(目标档案已使用中)时不做无意义的回滚- expect(failureBranch).toContain('previousProfileId !== switchedProfileId')+ const failureBranch = body.slice(failureIndex)+ expect(failureBranch).toContain('await guard.rollback?.()')})})-describe('activateVersionProfile:缺失才新建,已存在只切换', () => {+describe('守卫:档案缺失才新建,已存在只切换,失败即中止', () => {it('按后端归一化后的 id 匹配在用档案列表', () => {- const body = bodyOf(coreSource(), 'async function activateVersionProfile')+ const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')expect(body).toContain('invoke<Profile[]>(\'get_profiles\')')- expect(body).toContain('normalizeProfileId(name)')+ expect(body).toContain('normalizeProfileId(choice.name)')expect(body).toMatch(/profiles\.find\(p => p\.id === id\)/)})- it('已存在时切到该档案并直接返回,不再新建', () => {- const body = bodyOf(coreSource(), 'async function activateVersionProfile')- const existsIndex = body.indexOf('if (existing)')- const returnIndex = body.indexOf('return { id, previousId }', existsIndex)- const createIndex = body.indexOf('\'create_profile\'')+ it('已存在且在用时不重复切换,缺失时新建并切为使用中', () => {+ const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')- expect(existsIndex).toBeGreaterThan(-1)- expect(returnIndex).toBeGreaterThan(existsIndex)- expect(returnIndex).toBeLessThan(createIndex)- expect(body.slice(existsIndex, returnIndex)).toContain('invoke<Profile>(\'set_active_profile\', { id })')- })-- it('缺失时新建并切为使用中', () => {- const body = bodyOf(coreSource(), 'async function activateVersionProfile')-- expect(body).toContain('invoke<Profile>(\'create_profile\', { name })')+ 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(coreSource(), 'async function activateVersionProfile')+ it('档案切换失败时提示并中止(不切核心)', () => {+ const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')+ const failureIndex = body.indexOf('core.breaking_profile_failed')- expect(body).toContain('profiles.find(p => p.active)?.id')- expect(body).toMatch(/Promise<\{ id: string, previousId: string \}>/)- expect(body).toMatch(/return \{ id: created\.id, previousId \}/)+ expect(failureIndex).toBeGreaterThan(-1)+ expect(body.slice(failureIndex)).toMatch(/return null/)})-})-describe('restoreActiveProfile:回滚不掩盖原始失败', () => {- it('切回原档案,回滚失败只记日志,并始终失效档案查询', () => {- const body = bodyOf(coreSource(), 'async function restoreActiveProfile')+ it('回滚切回原档案,失败只记日志,并始终失效档案查询', () => {+ const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')- expect(body).toContain('invoke<Profile>(\'set_active_profile\', { id })')+ 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')++ 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\')'))+ })+})++describe('更新提示入口(桌面外壳 / 调试页)走同一守卫', () => {+ for (const [name, source] of [['layout', layoutSource], ['debug', debugSource]] as [string, () => string][]) {+ it(`${name}:「立即更新」先确认、再落档案、更新失败回滚`, () => {+ const body = updateBody(source())++ expect(body).toContain('confirmCoreBreaking(info.tag)')+ expect(body).toContain('guardCoreUpgrade(info.tag)')+ expect(body).toMatch(/if \(!guard\)\n\s*return/)+ expect(body).toContain('if (!(await store.harnessUpdater.handleUpdate()))')+ expect(body).toContain('await guard.rollback?.()')+ // 守卫的弹窗必须挂进渲染树,否则 useOverlay 的 holder 无处可渲染+ expect(source()).toContain('{coreProfileSwitchHolder}')+ })+ }++ it('handleUpdate 返回是否真的切到了新版本,供调用方决定是否回滚', () => {+ const source = updaterSource()++ expect(source).toMatch(/async handleUpdate\(\): Promise<boolean>/)+ expect(source).toMatch(/return false/)+ expect(source).toMatch(/return true/)+ })})describe('警告对话框控件', () => {- it('档案名 Input 默认填 x.x 且可编辑', () => {+ it('档案名默认填 x.x、可编辑,并用 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('提供「无视风险切换」Link、取消与确认按钮', () => {+ it('「无视风险切换」用 HeroUI Link,且与取消/确认按钮同处一行的 footer', () => {const source = dialogSource()-- expect(source).toMatch(/core\.breaking_ignore/)- expect(source).toMatch(/disclosure\.confirm\(\{ mode: 'ignore' \}\)/)- expect(source).toMatch(/core\.breaking_profile_label/)- expect(source).toMatch(/buttons\.cancel/)- expect(source).toMatch(/buttons\.confirm/)+ 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 \{[^}]+Link[^}]*\} from '@heroui\/react'/)+ expect(footer).toMatch(/<Link[\s>]/)+ 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 \}\)/)})@@ -178,12 +214,11 @@ describe('警告对话框控件', () => {expect(source).toMatch(/isDisabled=\{!profileId\}/)})- it('警告文案同时给出源版本与目标版本', () => {- expect(dialogSource()).toMatch(/core\.breaking_desc', \{ from: props\.fromVersion, to: props\.toVersion \}/)- })+ it('warning 状态的 AlertDialog,警告文案同时给出源版本与目标版本', () => {+ const source = dialogSource()- it('warning 状态的 AlertDialog', () => {- expect(dialogSource()).toMatch(/status="warning"/)+ expect(source).toMatch(/status="warning"/)+ expect(source).toMatch(/core\.breaking_desc', \{ from: props\.fromVersion, to: props\.toVersion \}/)})})diff --git a/test/core-version.test.ts b/test/core-version.test.tsindex a4d7d23b..c2e6c732 100644--- a/test/core-version.test.ts+++ b/test/core-version.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { coreMajorMinor, isCoreMajorMinorUpgrade, isCoreUnsupported, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-version'+import { coreMajorMinor, isCoreUnsupported, isCoreUpgrade, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-version'/*** issue #596:随包内置插件依赖的平台种子词自 dsh 0.1.5 起才存在,核心低于最低支持@@ -57,30 +57,39 @@ describe('coreMajorMinor', () => {})/**- * 跨主/次版本的升级才触发「破坏性更改 → 请切换档案」,patch 升级与降级一律放行:- * 漏提示只是少一次提醒,误报会把正常切换挡在弹窗后面。+ * 升到任何更新的版本都要提示「破坏性更改 → 请切换档案」:+ * patch 升级同样可能带破坏性更改(用户实测 0.1.5 → 0.1.7 未提示是漏报,见反馈);+ * 降级、平级与不可解析版本一律放行——误报会把正常切换挡在弹窗后面。*/-describe('isCoreMajorMinorUpgrade', () => {- it('跨次版本或主版本的升级为 true', () => {- expect(isCoreMajorMinorUpgrade('0.17.1', '0.18.0')).toBe(true)- expect(isCoreMajorMinorUpgrade('0.17.1', '1.0.0')).toBe(true)- expect(isCoreMajorMinorUpgrade('0.17.1', '1.2.0-rc.1')).toBe(true)+describe('isCoreUpgrade', () => {+ it('任何更新(含 patch、预发布→正式)都算升级', () => {+ expect(isCoreUpgrade('0.1.5', '0.1.7')).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.1.5-rc.1', '0.1.5')).toBe(true)+ expect(isCoreUpgrade('0.1.5-rc.1', '0.1.6-alpha.2')).toBe(true)})- it('同主次版本的 patch 升级不算破坏性升级', () => {- expect(isCoreMajorMinorUpgrade('0.17.1', '0.17.2')).toBe(false)- expect(isCoreMajorMinorUpgrade('0.17.1', '0.17.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)})it('降级不算升级', () => {- expect(isCoreMajorMinorUpgrade('0.18.0', '0.17.1')).toBe(false)- expect(isCoreMajorMinorUpgrade('1.0.0', '0.9.9')).toBe(false)+ expect(isCoreUpgrade('0.1.7', '0.1.5')).toBe(false)+ expect(isCoreUpgrade('0.18.0', '0.17.1')).toBe(false)+ expect(isCoreUpgrade('1.0.0', '0.9.9')).toBe(false)+ expect(isCoreUpgrade('0.1.5', '0.1.5-rc.1')).toBe(false)})it('任一侧版本缺失或不可解析时不误报', () => {- expect(isCoreMajorMinorUpgrade('', '0.18.0')).toBe(false)- expect(isCoreMajorMinorUpgrade('local', '0.18.0')).toBe(false)- expect(isCoreMajorMinorUpgrade('0.17.1', '')).toBe(false)- expect(isCoreMajorMinorUpgrade('0.17.1', 'app')).toBe(false)+ 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)})})