DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(desktop): 核心跨主次版本升级时提示切换版本档案
hairyf35a7b2678b72
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex dd84faab..cd537e9b 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -329,6 +329,11 @@"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": "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_profile_label": "Profile name",+ "core.breaking_ignore": "Switch anyway",+ "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.jsonindex 284bfb94..ae847989 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -329,6 +329,11 @@"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/ui/config/core.tsx b/src/ui/config/core.tsxindex 37f34912..37a6dfe0 100644--- a/src/ui/config/core.tsx+++ b/src/ui/config/core.tsx@@ -1,4 +1,5 @@-import type { HarnessCore } from '@/types'+import type { HarnessCore, Profile } from '@/types'+import type { CoreUpgradeChoice, CoreUpgradeProfileDialogProps } from '@/ui/dialog/core-upgrade-profile'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'@@ -16,8 +17,10 @@ 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 { DownloadCoreDialog } from '@/ui/dialog/update-core'-import { compareVersions, isCoreUnsupported, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-version'+import { compareVersions, coreMajorMinor, isCoreMajorMinorUpgrade, isCoreUnsupported, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-version'+import { normalizeProfileId } from '@/utils/profile-id'import { silence } from '@/utils/silence'import { toast } from '@/utils/toast'@@ -31,7 +34,8 @@ import { toast } from '@/utils/toast'* 降级为 git tags / 磁盘扫描,仅显示已下载版本)。预览版(Pre-release label* 或 tag 命名)照常列出、可下载安装,但带「预览版」标签、不参与更新提示。* - 切换核心:持久化后**自动重启**服务(需求 5),重启走 harness store 的- * restart 流程(停止 → 重新启动 → 健康检查)。+ * restart 流程(停止 → 重新启动 → 健康检查)。跨主/次版本升级时先弹「破坏性更改」+ * 警告,确认后把当前档案换成与目标版本配套的版本档案(缺失则新建),再切核心并重启。* - 下载版本:拉指定 tag 的发布资产到历史槽位(不激活),随后可切换;* 卸载仅允许非激活的已下载版本。* - 本地核心更新:通过用户包管理器 CLI(npm install -g @latest / pnpm add -g @latest)。@@ -41,6 +45,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: coreBreakingHolder, confirmCoreBreaking } = useCoreBreakingConfirm()const { t } = useTranslation()@@ -134,6 +139,29 @@ export function ConfigCore() {}}+ /**+ * 取(或建)版本档案并切为使用中:同名档案已存在则直接切换,缺失才新建。+ *+ * 档案名按后端归一化后的 id 匹配(`0.17` → `017`),因此这里先取列表再决定是否新建,+ * 不能直接 create——已存在时后端会以 `PROFILE_EXISTS` 拒绝。+ */+ async function activateVersionProfile(name: string): Promise<string> {+ const profiles = await queryClient.fetchQuery({+ queryKey: queryKeys.profiles,+ queryFn: () => invoke<Profile[]>('get_profiles'),+ })+ 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+ }+ const created = await invoke<Profile>('create_profile', { name })+ await invoke<Profile>('set_active_profile', { id: created.id })+ return created.id+ }+async function onActivate(core: HarnessCore) {if (core.active || busy || !core.present)return@@ -147,26 +175,65 @@ export function ConfigCore() {})return}- 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>- ),- })+ 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+ }}- catch (e) {- silence(e, 'core switch: dialog cancelled')- return+ else {+ 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 (profileName) {+ try {+ await activateVersionProfile(profileName)+ 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 完成时统一失效核心查询;这里不等待联网列表重拉,@@ -476,6 +543,7 @@ export function ConfigCore() {{dialogHolder}{downloadDialogHolder}+ {upgradeDialogHolder}{coreBreakingHolder}</div>)@@ -486,6 +554,11 @@ 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+}+/*** 本地核心是否低于最低支持基线。判据与「不兼容版本」分组完全一致(同一基线,* `isUnsupportedCore`),低于基线时随包内置插件无法加载(issue #596),桌面端自动diff --git a/src/ui/dialog/core-upgrade-profile.tsx b/src/ui/dialog/core-upgrade-profile.tsxnew file mode 100644index 00000000..6bf2a472--- /dev/null+++ b/src/ui/dialog/core-upgrade-profile.tsx@@ -0,0 +1,94 @@+import type { PropsWithOverlays } from '@overlastic/react'+import { AlertDialog, Button, Input, Label, Link } 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+ /** 档案名默认值:目标版本的主/次版本号(`x.x`) */+ defaultName: string+}++/**+ * 「跨主/次版本升级」警告对话框:核心与档案配套,跨版本升级可能破坏当前档案里的插件与设置。+ *+ * - 确认: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="warning" />+ <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>+ <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' })}+ >+ {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>+ </AlertDialog.Footer>+ </AlertDialog.Dialog>+ </AlertDialog.Container>+ </AlertDialog.Backdrop>+ </AlertDialog>+ )+}diff --git a/src/utils/core-version.ts b/src/utils/core-version.tsindex 38ac9caf..03bd6229 100644--- a/src/utils/core-version.ts+++ b/src/utils/core-version.ts@@ -6,6 +6,14 @@ import semver from 'semver'*/export const CORE_BREAKING_BASELINE = '0.1.2-rc.1'+/** 剥掉 release tag 的 `dsh-`/`src-` 前缀(含重复的 `dsh-src-` 链)后再交给 semver */+function stripVersionPrefix(version: string): string {+ let value = version+ while (value.startsWith('dsh-') || value.startsWith('src-'))+ value = value.replace(/^(?:src|dsh)-/, '')+ return value+}+/*** Semver comparison using the `semver` package.* Handles `dsh-`/`src-` prefixes (including repeated `dsh-src-` chains) by@@ -13,19 +21,35 @@ export const CORE_BREAKING_BASELINE = '0.1.2-rc.1'* Returns: negative if a < b, 0 if equal, positive if a > b.*/export function compareVersions(a: string, b: string): number {- const clean = (v: string) => {- let s = v- while (s.startsWith('dsh-') || s.startsWith('src-'))- s = s.replace(/^(?:src|dsh)-/, '')- return s- }- const pa = semver.parse(clean(a))- const pb = semver.parse(clean(b))+ const pa = semver.parse(stripVersionPrefix(a))+ const pb = semver.parse(stripVersionPrefix(b))if (!pa || !pb)return 0return semver.compare(pa, pb)}+/** 主/次版本号(`x.x`,不含 patch 与预发布标识);缺失或不可解析时为空串 */+export function coreMajorMinor(version: string): string {+ const parsed = semver.parse(stripVersionPrefix(version))+ return parsed ? `${parsed.major}.${parsed.minor}` : ''+}++/**+ * 目标核心是否相对当前核心跨了主/次版本(patch 升级不算)。+ *+ * 核心与档案是配套的:跨主/次版本意味着破坏性更改,切换前必须把当前档案换成配套档案。+ * 不可解析(本地核心版本号缺失、首次切换没有在用核心)一律返回 false——漏提示只是少了+ * 一次提醒,误判会把正常切换挡在弹窗后面。+ */+export function isCoreMajorMinorUpgrade(from: string, to: string): boolean {+ const current = semver.parse(stripVersionPrefix(from))+ const target = semver.parse(stripVersionPrefix(to))+ if (!current || !target)+ return false+ return semver.gt(target, current)+ && (target.major !== current.major || target.minor !== current.minor)+}+/** 判断核心版本(版本串或 release tag)是否高于 rc.2 基准(引入破坏性更改) */export function isCoreBreakingVersion(version: string): boolean {return !!version && compareVersions(version, CORE_BREAKING_BASELINE) > 0diff --git a/src/utils/profile-id.ts b/src/utils/profile-id.tsnew file mode 100644index 00000000..da950a5d--- /dev/null+++ b/src/utils/profile-id.ts@@ -0,0 +1,23 @@+/**+ * 档案展示名 → 档案 id 的归一化,与 Rust `service::profile::normalize_profile_id` 一一对应:+ * 小写、仅保留 ASCII 字母数字,`-`/`_`/空格作分隔符(连续分隔符合并),其余字符丢弃,去首尾 `-`。+ *+ * 前端必须与后端用同一套归一化,否则「档案是否已存在」会判错:`0.17` 这类带点的名字在+ * 后端落成 `017`,只按原名匹配会误判为不存在,进而重复调用 create_profile 撞 `PROFILE_EXISTS`。+ */+export function normalizeProfileId(name: string): string {+ let out = ''+ let pendingSeparator = false+ for (const char of name.toLowerCase()) {+ if (/[a-z0-9]/.test(char)) {+ if (pendingSeparator && out)+ out += '-'+ pendingSeparator = false+ out += char+ }+ else if (char === ' ' || char === '-' || char === '_') {+ pendingSeparator = true+ }+ }+ return out.replace(/^-+|-+$/g, '')+}diff --git a/test/core-upgrade-profile.test.ts b/test/core-upgrade-profile.test.tsnew file mode 100644index 00000000..0789a873--- /dev/null+++ b/test/core-upgrade-profile.test.ts@@ -0,0 +1,178 @@+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'++/**+ * 「跨主/次版本升级 → 请切换档案」链路的结构契约。+ *+ * 前端不在单测里挂载组件(与 clone-profile.test.ts 同款跨层守卫),因此读源码断言结构:+ * 期望值一律取自需求本身(顺序、命令名、i18n key),不与被测实现同源。+ */+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')++/** 取组件内某个顶层函数的函数体(到该函数自己的 `\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)+}++describe('破坏性升级的判定与警告入口', () => {+ it('用「在用核心 → 目标核心」的主/次版本跨度判定,而不是只看目标版本', () => {+ const body = bodyOf(coreSource(), 'async function onActivate')++ expect(body).toContain('isCoreMajorMinorUpgrade(')+ expect(body).toContain('cores.find(c => c.active)')+ // 判定两侧都取「版本号缺失时回落 release tag」的版本串+ expect(body).toMatch(/coreVersionKey\(activeCore\)/)+ expect(body).toMatch(/coreVersionKey\(core\)/)+ })++ it('警告弹窗的默认档案名取目标版本的主/次版本号(x.x)', () => {+ const body = bodyOf(coreSource(), 'async function onActivate')++ expect(body).toMatch(/coreMajorMinor\(coreVersionKey\(core\)\)/)+ expect(body).toMatch(/defaultName:/)+ })++ 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')+ })++ 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)++ expect(cancelBranch).toContain('silence(')+ expect(cancelBranch).toMatch(/return/)+ expect(cancelBranch).not.toContain('activate.mutateAsync')+ })++ it('「无视风险切换」保持档案不变,只切核心', () => {+ const body = bodyOf(coreSource(), 'async function onActivate')++ // 只有选择 profile 才写入 profileName;ignore 分支不赋值 → 跳过档案切换+ expect(body).toMatch(/if \(choice\.mode === 'profile'\)\n\s*profileName = choice\.name/)+ expect(body).toMatch(/if \(profileName\) \{/)+ })+})++describe('确认后的编排顺序:档案 → 核心 → 重启', () => {+ it('先落版本档案,再切核心,最后重启', () => {+ const body = bodyOf(coreSource(), 'async function onActivate')+ const profileIndex = body.indexOf('await activateVersionProfile(profileName)')+ const coreIndex = body.indexOf('activate.mutateAsync(core.id)')+ const restartIndex = body.indexOf('store.harness.restart()')++ expect(profileIndex).toBeGreaterThan(-1)+ expect(coreIndex).toBeGreaterThan(profileIndex)+ 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/)+ })+})++describe('activateVersionProfile:缺失才新建,已存在只切换', () => {+ it('按后端归一化后的 id 匹配在用档案列表', () => {+ const body = bodyOf(coreSource(), 'async function activateVersionProfile')++ expect(body).toContain('invoke<Profile[]>(\'get_profiles\')')+ expect(body).toContain('normalizeProfileId(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', existsIndex)+ const createIndex = body.indexOf('\'create_profile\'')++ 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).toContain('invoke<Profile>(\'set_active_profile\', { id: created.id })')+ })+})++describe('警告对话框控件', () => {+ it('档案名 Input 默认填 x.x 且可编辑', () => {+ const source = dialogSource()++ expect(source).toMatch(/useState\(props\.defaultName\)/)+ expect(source).toMatch(/value=\{name\}/)+ expect(source).toMatch(/onChange=\{e => setName\(e\.target\.value\)\}/)+ })++ it('提供「无视风险切换」Link、取消与确认按钮', () => {+ 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/)+ 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('警告文案同时给出源版本与目标版本', () => {+ expect(dialogSource()).toMatch(/core\.breaking_desc', \{ from: props\.fromVersion, to: props\.toVersion \}/)+ })++ it('warning 状态的 AlertDialog', () => {+ expect(dialogSource()).toMatch(/status="warning"/)+ })+})++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 = JSON.parse(readFileSync(new URL(`../src/i18n/locales/${locale}.json`, import.meta.url), 'utf8')) as Record<string, unknown>+ for (const key of keys) {+ expect(typeof messages[key], key).toBe('string')+ expect((messages[key] as string).length, key).toBeGreaterThan(0)+ }+ })+ }+})diff --git a/test/core-version.test.ts b/test/core-version.test.tsindex 0029b371..a4d7d23b 100644--- a/test/core-version.test.ts+++ b/test/core-version.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { isCoreUnsupported, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-version'+import { coreMajorMinor, isCoreMajorMinorUpgrade, isCoreUnsupported, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-version'/*** issue #596:随包内置插件依赖的平台种子词自 dsh 0.1.5 起才存在,核心低于最低支持@@ -36,3 +36,51 @@ describe('isCoreUnsupported', () => {expect(isCoreUnsupported('src-0.1.5-rc.1')).toBe(false)})})++describe('coreMajorMinor', () => {+ it('只取主/次版本号,丢掉 patch 与预发布标识', () => {+ expect(coreMajorMinor('0.17.1')).toBe('0.17')+ expect(coreMajorMinor('0.18.0-rc.1')).toBe('0.18')+ expect(coreMajorMinor('1.2.3')).toBe('1.2')+ })++ it('剥掉 dsh-/src- 前缀后再取主/次版本号', () => {+ expect(coreMajorMinor('dsh-0.1.0-rc.8-32331963388')).toBe('0.1')+ expect(coreMajorMinor('src-2.0.0')).toBe('2.0')+ })++ it('版本缺失或不可解析时为空串', () => {+ expect(coreMajorMinor('')).toBe('')+ expect(coreMajorMinor('local')).toBe('')+ expect(coreMajorMinor('app-0.1.0-rc.8')).toBe('')+ })+})++/**+ * 跨主/次版本的升级才触发「破坏性更改 → 请切换档案」,patch 升级与降级一律放行:+ * 漏提示只是少一次提醒,误报会把正常切换挡在弹窗后面。+ */+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)+ })++ it('同主次版本的 patch 升级不算破坏性升级', () => {+ expect(isCoreMajorMinorUpgrade('0.17.1', '0.17.2')).toBe(false)+ expect(isCoreMajorMinorUpgrade('0.17.1', '0.17.1')).toBe(false)+ })++ it('降级不算升级', () => {+ expect(isCoreMajorMinorUpgrade('0.18.0', '0.17.1')).toBe(false)+ expect(isCoreMajorMinorUpgrade('1.0.0', '0.9.9')).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)+ })+})diff --git a/test/profile-id.test.ts b/test/profile-id.test.tsnew file mode 100644index 00000000..779a57eb--- /dev/null+++ b/test/profile-id.test.ts@@ -0,0 +1,50 @@+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'+import { normalizeProfileId } from '@/utils/profile-id'++const PROFILE_RS = new URL('../src-tauri/src/service/profile/mod.rs', import.meta.url)++/**+ * 从 Rust 侧 `normalize_id_lowercases_and_joins` 里抽出全部+ * `assert_eq!(normalize_profile_id("X"), "Y");` 断言对。+ *+ * 归一化是前后端共享契约:前端要用它判断「版本档案是否已存在」,判错就会重复创建+ * (撞 `PROFILE_EXISTS`)或切错档案。因此这里不写死期望值,而是直接以 Rust 单测为+ * 权威来源,TS 实现必须与后端逐条一致。+ */+function rustCases(): Array<{ input: string, expected: string }> {+ const source = readFileSync(PROFILE_RS, 'utf8')+ const matches = source.matchAll(/assert_eq!\(\s*normalize_profile_id\("([^"]*)"\),\s*"([^"]*)"\s*\);/g)+ return [...matches].map(m => ({ input: m[1], expected: m[2] }))+}++describe('normalizeProfileId 与 Rust normalize_profile_id 一致', () => {+ it('保留至少 4 条 Rust 侧归一化断言(契约未被删除)', () => {+ expect(rustCases().length).toBeGreaterThanOrEqual(4)+ })++ it('逐条通过 Rust 单测的输入与期望', () => {+ for (const { input, expected } of rustCases())+ expect(normalizeProfileId(input), input).toBe(expected)+ })++ /** 版本档案名带点:后端把 `.` 丢弃(`0.17` → `017`),前端匹配 id 必须同款 */+ it('把版本号形式的档案名归一化为纯数字 id', () => {+ expect(normalizeProfileId('0.17')).toBe('017')+ expect(normalizeProfileId('0.18')).toBe('018')+ expect(normalizeProfileId(' 1.0 ')).toBe('10')+ })++ it('空名与纯符号名归一化为空串', () => {+ expect(normalizeProfileId('')).toBe('')+ expect(normalizeProfileId(' ')).toBe('')+ expect(normalizeProfileId('...')).toBe('')+ expect(normalizeProfileId('-_-')).toBe('')+ })++ it('连续分隔符合并、首尾分隔符去除', () => {+ expect(normalizeProfileId('-dev--stage-')).toBe('dev-stage')+ expect(normalizeProfileId('a___b')).toBe('a-b')+ expect(normalizeProfileId('A B')).toBe('a-b')+ })+})