DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(profile): 档案支持从其他档案迁移插件与档案数据 (#938)
Mao Mrf1401c9a25d5
diff --git a/AGENTS.md b/AGENTS.mdindex 9d93671d..5f9dd9fc 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -9,6 +9,7 @@| **基础通用** | 所有代码修改 | `docs/specs/devlopment.md` || **测试标准** | 通用 Unit Test、E2E 集成测试断言与结构 | `docs/specs/testing.md` || **桌面端 - 基础架构** | 桌面端主进程、Shell 基础、GUI 渲染核心 | `docs/specs/desktop.baisc.md` |+| **桌面端 - UI 组件** | 设置面板 / 对话框等前端组件的内部分区、派生数据与提交动作组织 | `docs/specs/desktop.ui.md` || **桌面端 - 测试验证** | 桌面端 E2E 测试、UI 单元测试、桌面功能测试 | `docs/specs/desktop.test.md` || **插件 - 基础架构** | 插件常量归属、跨侧共享约定与退级策略 | `docs/specs/plugin.baisc.md` || **插件 - 客户端核心** | 插件 Client 通信、状态管理与客户端逻辑 | `docs/specs/plugin.client.md` |diff --git a/docs/specs/desktop.ui.md b/docs/specs/desktop.ui.mdnew file mode 100644index 00000000..9e17d33b--- /dev/null+++ b/docs/specs/desktop.ui.md@@ -0,0 +1,103 @@+# 桌面端 UI 组件规范 (Desktop UI Component Protocol)++> **适用范围**:`src/ui/**` 与 `src/components/**` 下的 React 组件(设置面板、对话框、独立视图)。+> 本规范是 [devlopment.md](./devlopment.md) 与 [desktop.baisc.md](./desktop.baisc.md)(§3 前端编码规范)在**组件实现粒度**上的补充:结构性规则看那两份,**组件内部怎么组织**看这份。++---++## 一、 组件内分区与编号注释++组件函数体按**固定顺序**分区,每区以 `// N. 中文标题 (English hint)` 起头:++| 序号 | 分区 | 放什么 |+| :--- | :--- | :--- |+| 1 | `数据查询 (Queries)` | `useQuery` / store 读取等**不依赖本地选择**的数据源 |+| 2 | `本地用户选择状态` | `useState` / `useToggle` 等交互状态 |+| 3 | `<业务>数据 Query` | 依赖上面状态的查询(配 `enabled: Boolean(key)` 开关) |+| 4 | `派生数据提取与 Map 索引构造` | 兜底(`?? []`)、派生布尔、Map 索引表 |+| 5 | `使用 useMutation 封装<动作>流程` | 提交动作 |++```tsx+export function ProfileMigrateDialog(props: PropsWithOverlays) {+ // 1. 数据查询 (Queries)+ const { data: cores } = useQuery({ /* … */ })++ // 2. 本地用户选择状态+ const [pickedSourceId, setPickedSourceId] = useState('')++ // 3. 档案迁移分析数据 Query+ const { data: analysis, isLoading, error } = useQuery({ /* …, enabled: Boolean(pickedSourceId) */ })++ // 4. 派生数据提取与 Map 索引构造 (常数级别 O(1) 查找)+ const installedMap = new Map(manager.installed.map(p => [p.id, p.version]))++ // 5. 使用 useMutation 封装迁移提交流程+ const { mutate: handleMigrate, isPending: busy } = useMutation({ /* … */ })+}+```++* **顺序不可打乱**:查询 → 本地状态 → 依赖查询 → 派生 → 提交。新增逻辑按职责插进对应分区,不另起序号。+* **派生值集中在一处**:`?? []`、`filter`、`find` 只在第 4 区出现;JSX 里写的是"怎么渲染",不是"怎么算"。+* 分区外只允许两类注释:区块 `{/* … */}`(见 §四)与 `// 阶段 A:` 之类的多阶段标记。++---++## 二、 Map 索引代替线性查找++渲染循环里要按 id / kind 反查时,**先在派生区构造一次 Map**,渲染时 O(1) 取值:++```tsx+const installedMap = new Map(manager.installed.map(p => [p.id, p.version]))+const dataItemMap = new Map(dataItems.map(item => [item.kind, item]))+```++* 禁止在 `map()` / `filter()` 回调里 `list.find(...)`(渲染 N 项就是 O(n²))。+* 禁止为"只查一次"再抽工具函数或多写一层 hook——索引表就在第 4 区,谁用谁读。++---++## 三、 提交动作一律用 `useMutation` 收敛++```tsx+const { mutate: handleMigrate, isPending: busy } = useMutation({+ mutationFn: async () => {+ // 阶段 A: 迁移档案数据+ // 阶段 B: 安装插件+ return { totalCount, failedCount }+ },+ onSuccess: ({ totalCount, failedCount }) => {+ void queryClient.invalidateQueries({ queryKey: queryKeys.plugins })+ // toast 汇总 + 关闭弹窗(disclosure.confirm())+ },+ onError: (err) => {+ console.error('[ProfileMigrateDialog] migrate failed:', err)+ toast(t('profiles.migrate_failed'), { variant: 'danger', description: String(err) })+ },+})+```++* **busy 直接取 `isPending`**,不得再手写 `useState(false)` + `try / catch / finally`。+* `mutationFn` 只负责副作用与**返回汇总结果**(给 `onSuccess` 用),不弹提示、不动缓存。+* 多阶段副作用逐段标注 `// 阶段 A: …` / `// 阶段 B: …`。+* 提示遵守"**谁执行,谁提示**":toast 只在 `onSuccess` / `onError` 里发一次,上层不重复。+* 提交按钮:`onPress={() => handleMigrate()}`,禁用条件由派生值算一次(`canSubmit`)。++---++## 四、 注释与文档粒度++* **组件 JSDoc 只留一行定位**:`/** 「迁移档案数据」对话框组件 */`。交互流程、取舍、边界写进 PR 描述,不复制进源码。+* **常量表只留一行用途**:`/** 判定结果 → Chip 颜色与文案 key */`、`/** 数据项的列出顺序:凭据固定最后 */`;不逐字复述字面量。+* **JSX 区块用单行注释**:`{/* 源档案与目标档案选择 */}`、`{/* 插件列表面板 */}`;块内不再加注释。+* 除上述三类与 `// 阶段 X:` / `ponytail:` 外,**不新增注释**(与 `AGENTS.md` 的 0 注释原则一致)。++---++## 五、 自检清单++* [ ] **分区**:五个分区是否齐全、顺序是否固定?+* [ ] **派生**:渲染循环里是否还有 `Array.find`?索引表是否在第 4 区一次构造?+* [ ] **提交**:是否走 `useMutation`?busy 是否直接用 `isPending`?toast 是否只发一次?+* [ ] **注释**:JSDoc 是否只有一行?JSX 区块是否单行注释、块内无冗余注释?+* [ ] **主题**:HeroUI 组件上是否没有再叠 `rounded*` 工具类?(圆角由主题负责,`test/shell-heroui-theme.test.ts` 会拦)+* [ ] **工程校验**:`eslint` 零 error、`tsc -p tsconfig.typecheck.json` 零错误、相关 `vitest run --project unit` 通过。diff --git a/src-tauri/src/bridge/profile.rs b/src-tauri/src/bridge/profile.rsindex 0920627b..9144fe33 100644--- a/src-tauri/src/bridge/profile.rs+++ b/src-tauri/src/bridge/profile.rs@@ -6,6 +6,7 @@use crate::config;use crate::service::profile;+use crate::service::profile::migrate::{MigrationAnalysis, MigrationDataKind, MigrateReport};use tauri::AppHandle;/// 档案列表($DSH_HOME/profiles 下的目录,含 active/default 标记)@@ -56,3 +57,27 @@ pub async fn clone_profile(.await.map_err(|e| format!("PROFILE_CLONE_TASK: {e}"))?}++/// 分析源档案的可迁移插件与档案级数据(只读,判定基准 = 当前核心版本)+#[tauri::command]+pub async fn analyze_profile_migration(+ app_handle: AppHandle,+ source_id: String,+) -> Result<MigrationAnalysis, String> {+ profile::migrate::analyze(&app_handle, &source_id).await+}++/// 把源档案选中的数据并入当前档案(逐项独立,结果里逐项报告)+#[tauri::command]+pub async fn migrate_profile_data(+ app_handle: AppHandle,+ source_id: String,+ items: Vec<MigrationDataKind>,+) -> Result<MigrateReport, String> {+ let handle = app_handle.clone();+ tauri::async_runtime::spawn_blocking(move || {+ profile::migrate::apply(&handle, &source_id, &items)+ })+ .await+ .map_err(|e| format!("PROFILE_MIGRATION_TASK: {e}"))?+}diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 694c67b3..12253f57 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -1565,6 +1565,8 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::remove_profile,crate::bridge::reset_profile,crate::bridge::clone_profile,+ crate::bridge::analyze_profile_migration,+ crate::bridge::migrate_profile_data,crate::bridge::backup_profile,crate::bridge::export_recovery_backup,crate::bridge::restore_profile,diff --git a/src-tauri/src/service/plugin/disable.rs b/src-tauri/src/service/plugin/disable.rsindex 7a582d2f..f7da93e6 100644--- a/src-tauri/src/service/plugin/disable.rs+++ b/src-tauri/src/service/plugin/disable.rs@@ -41,7 +41,10 @@ pub(crate) fn load_disabled(profile: &Path) -> HashMap<String, DisabledEntry> {}/// 持久化禁用清单(pretty JSON + 尾部换行)。-fn save_disabled(profile: &Path, map: &HashMap<String, DisabledEntry>) -> Result<(), String> {+pub(crate) fn save_disabled(+ profile: &Path,+ map: &HashMap<String, DisabledEntry>,+) -> Result<(), String> {let path = disabled_path(profile);if let Some(dir) = path.parent() {fs::create_dir_all(dir).map_err(|e| format!("DISABLED_DIR_CREATE_FAILED: {e}"))?;diff --git a/src-tauri/src/service/plugin/install/inspect.rs b/src-tauri/src/service/plugin/install/inspect.rsindex 3318d587..00133379 100644--- a/src-tauri/src/service/plugin/install/inspect.rs+++ b/src-tauri/src/service/plugin/install/inspect.rs@@ -44,6 +44,30 @@ pub async fn inspect_specs(Ok(results)}+/// 拉取包的完整版本清单(缩写 packument:`versions` 映射里带每个版本的依赖声明)。+///+/// 与 [`inspect_one`] 读的单版本清单不同:判定「哪个历史版本与该核心兼容」必须+/// 遍历全部版本,只有不带版本号的 packument 才有。任何失败返回 `None`(Fail-Open)。+pub(crate) async fn packument(app_handle: &AppHandle, name: &str) -> Option<serde_json::Value> {+ let client = crate::config::proxy::http_client_builder(app_handle)+ .ok()?+ .timeout(INSPECT_TIMEOUT)+ .build()+ .ok()?;+ let url = format!("https://registry.npmjs.org/{}", encode_registry_name(name));+ let response = client+ .get(&url)+ .header("accept", "application/vnd.npm.install-v1+json")+ .header("user-agent", "deepseek-harness-desktop")+ .send()+ .await+ .ok()?;+ if !response.status().is_success() {+ return None;+ }+ response.json::<serde_json::Value>().await.ok()+}+/// 单条 spec:本地目录离线读清单;静态解析不出 registry 包名的来源(`github:`/// 简写、git / tarball URL)不做网络请求。async fn inspect_one(diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rsindex bc8cdea0..7fd2825f 100644--- a/src-tauri/src/service/plugin/install/mod.rs+++ b/src-tauri/src/service/plugin/install/mod.rs@@ -68,6 +68,7 @@ mod spec;// 子模块对外 API:plugin 兄弟模块(verify / internal 等)与安装编排共用pub(crate) use env::build_plugin_envs;pub use inspect::inspect_specs;+pub(crate) use inspect::packument;pub(crate) use pnpm::{bundled_pnpm_major, harness_prefer_bundled_pnpm, pnpm_major_version_at, profile_store_major,};diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex f366f16c..8462ddb4 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -60,12 +60,14 @@ pub(crate) use process::acquire_operation_lock;pub(crate) use install::harness_prefer_bundled_pnpm;pub(crate) use install::local_spec_from_path;pub(crate) use install::uninstall_deprecated_plugins;+pub(crate) use install::packument;pub use install::{allow_policy_versions, allow_version_exemptions, inspect_specs, install, install_specs,remove_many, update_many, IncompatibleVersion, PolicyBlockedVersion,};pub(crate) use installed::{declared_packages, ensure_profile_npmrc, installed_name, list_installed, profile_dir,+ ProfilePackageJson,};pub use installed::{list, PreinstallPlugin};pub(crate) use hmr::{status as local_plugin_hmr_status, sync_layer as local_plugin_hmr_sync};diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rsindex 823a62ff..6a5dda4d 100644--- a/src-tauri/src/service/plugin/watch.rs+++ b/src-tauri/src/service/plugin/watch.rs@@ -133,7 +133,7 @@ fn read_plugin_meta(dir: &Path) -> Option<PluginPackageJson> {////// 只列出 profile package.json `dependencies` 中的直接依赖——node_modules 里/// 还有大量传递依赖(clsx/zod 等),它们不是用户安装的 dsh 插件,不应展示。-fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPlugin> {+pub(crate) fn parse_plugins(profile: &Path, presets: &[PreinstallPluginInfo]) -> Vec<DshPlugin> {let manifest_content = match std::fs::read_to_string(profile.join("package.json")) {Ok(content) => content,Err(_) => return Vec::new(),diff --git a/src-tauri/src/service/profile/migrate.rs b/src-tauri/src/service/profile/migrate.rsnew file mode 100644index 00000000..1d2dfc9c--- /dev/null+++ b/src-tauri/src/service/profile/migrate.rs@@ -0,0 +1,747 @@+//! 档案数据迁移:把一个非当前档案(源)的 registry 插件与档案级数据搬进当前+//! 档案(目标)。+//!+//! 兼容性以**当前运行核心版本**为基准判定:不兼容的插件给出可用的升级/降级版本,+//! 判定不出来的一律标为「未知兼容」,由安装链路既有的授权流程兜底——迁移本身+//! 绝不因为兼容性拒绝任何条目。+//!+//! 数据合并一律纯增量、冲突时目标优先(不覆盖目标已有内容),因此不需要备份+//! 与回滚;凭据一项更严格:目标已有 `.credentials.yaml` 时整项跳过。++use std::collections::{BTreeMap, HashSet};+use std::fs;+use std::path::Path;++use semver::Version;+use serde::{Deserialize, Serialize};+use serde_yaml::Value;+use tauri::AppHandle;++use crate::config;+use crate::service::fs_guard;+use crate::service::plugin::compat::{self, PluginInspect};+use crate::service::plugin::{+ disable, inspect_specs, load_presets, packument, watch, ProfilePackageJson,+};++/// 发布时长策略豁免键(与 `profile::profile_release_age_excludes` 同源)。+const POLICY_KEY: &str = "minimumReleaseAgeExclude";++/// 档案级数据的落盘文件名。+const CREDENTIALS_FILE: &str = ".credentials.yaml";+const PATCH_FILE: &str = "cordis.patch.yml";+const DISABLED_FILE: &str = "disabled-plugins.json";+const POLICY_FILE: &str = "pnpm-workspace.yaml";++/// 迁移条目的兼容性判定结果(判定基准 = 当前核心版本)。+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub enum MigrationVerdict {+ Compatible,+ Upgrade,+ Downgrade,+ Unknown,+}++/// 单条可迁移插件。+#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MigrationEntry {+ /// 依赖键(npm 包名)+ pub id: String,+ /// 源档案已安装的版本+ pub version: String,+ /// 实际用于安装的 spec(不兼容时带目标版本)+ pub spec: String,+ pub verdict: MigrationVerdict,+ /// 升级/降级的建议版本;其余判定缺省+ #[serde(skip_serializing_if = "Option::is_none")]+ pub target_version: Option<String>,+}++/// 档案级数据类别。+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum MigrationDataKind {+ /// 补丁层 `cordis.patch.yml`+ Patch,+ /// 桌面禁用清单 `disabled-plugins.json`+ Disabled,+ /// 发布时长策略豁免 `pnpm-workspace.yaml`+ Policy,+ /// 凭据 `.credentials.yaml`+ Credentials,+}++/// 档案级数据项:`covered` = 目标档案已完全包含(迁移无意义,界面据此禁用勾选)。+#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MigrationDataItem {+ pub kind: MigrationDataKind,+ /// 条目数;凭据等无「条数」概念的一项缺省+ #[serde(skip_serializing_if = "Option::is_none")]+ pub count: Option<usize>,+ pub covered: bool,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MigrationAnalysis {+ pub plugins: Vec<MigrationEntry>,+ pub data: Vec<MigrationDataItem>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MigrationFailure {+ pub kind: MigrationDataKind,+ pub message: String,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MigrateReport {+ pub applied: Vec<MigrationDataKind>,+ /// 目标已有、按「目标优先」未改动的项+ pub skipped: Vec<MigrationDataKind>,+ pub failures: Vec<MigrationFailure>,+}++/// 依赖值是否指向 registry 上可发布的版本。+///+/// `link:` / `file:` / `portal:` / `workspace:` / `catalog:` 是随包分发的桌面内置+/// 插件(目标档案本来就有),`github:` 简写与 git/tarball URL 也不是「版本」,+/// 都不属于可迁移条目。+fn is_registry_range(raw: &str) -> bool {+ matches!(+ raw.trim().as_bytes().first(),+ Some(b'0'..=b'9' | b'^' | b'~' | b'>' | b'<' | b'=' | b'v' | b'*')+ )+}++/// 在一份 packument 里挑出与该运行时核心兼容的最高版本。+///+/// 只认 [`crate::service::plugin::compat::evaluate`] 明确返回 `true` 的版本:+/// 声明里没有 DSH 家族依赖的版本返回 `None`(无从判定),不算兼容候选——否则+/// 会把「判不出来」当成「可用」推荐给用户。+pub(crate) fn pick_nearest(packument: &serde_json::Value, runtime: &str) -> Option<String> {+ let mut best: Option<Version> = None;+ for (raw, manifest) in packument.get("versions")?.as_object()? {+ if compat::evaluate(&compat::peers_from_manifest(manifest), runtime) != Some(true) {+ continue;+ }+ let Ok(version) = Version::parse(raw) else {+ continue;+ };+ if best.as_ref().map(|current| version > *current).unwrap_or(true) {+ best = Some(version);+ }+ }+ best.map(|version| version.to_string())+}++/// 已装版本与建议版本的升降关系;相等或解析不出时判为无从判定。+fn compare_versions(installed: &str, nearest: &str) -> (MigrationVerdict, Option<String>) {+ let (Ok(current), Ok(target)) = (Version::parse(installed), Version::parse(nearest)) else {+ return (MigrationVerdict::Unknown, None);+ };+ if target > current {+ (MigrationVerdict::Upgrade, Some(nearest.to_string()))+ } else if target < current {+ (MigrationVerdict::Downgrade, Some(nearest.to_string()))+ } else {+ (MigrationVerdict::Unknown, None)+ }+}++/// 档案清单里指向 registry 的依赖,与已安装版本配对(未装出产物的条目跳过)。+///+/// 结果按 id 排序:`dependencies` 是 HashMap,迭代顺序每次调用都不同,+/// 直接产出会让迁移列表在每次打开时抖动。+fn candidates(app_handle: &AppHandle, dir: &Path) -> Vec<(String, String)> {+ let content = match fs::read_to_string(dir.join("package.json")) {+ Ok(content) => content,+ Err(_) => return Vec::new(),+ };+ let manifest: ProfilePackageJson = match serde_json::from_str(&content) {+ Ok(manifest) => manifest,+ Err(_) => return Vec::new(),+ };+ let installed: BTreeMap<String, String> = watch::parse_plugins(dir, &load_presets(app_handle))+ .into_iter()+ .filter(|plugin| !plugin.version.is_empty())+ .map(|plugin| (plugin.id, plugin.version))+ .collect();+ let mut entries: Vec<(String, String)> = manifest+ .dependencies+ .into_iter()+ .filter(|(id, raw)| is_registry_range(raw) && installed.contains_key(id))+ .map(|(id, _)| {+ let version = installed[&id].clone();+ (id, version)+ })+ .collect();+ entries.sort_by(|left, right| left.0.cmp(&right.0));+ entries+}++/// 建议版本:取该包与当前核心兼容的最高版本。+async fn nearest(app_handle: &AppHandle, id: &str, runtime: Option<&str>) -> Option<String> {+ let packument = packument(app_handle, id).await?;+ pick_nearest(&packument, runtime?)+}++/// 分析源档案:列出可迁移的 registry 插件与源档案里实际存在的档案级数据。+pub async fn analyze(+ app_handle: &AppHandle,+ source_id: &str,+) -> Result<MigrationAnalysis, String> {+ let root = config::get_dsh_data_path(app_handle).join("profiles");+ let dir = fs_guard::join_safe(&root, source_id)?;+ if !dir.is_dir() {+ return Err("PROFILE_MIGRATION_SOURCE_MISSING: source profile does not exist".to_string());+ }+ let entries = candidates(app_handle, &dir);+ let target = fs_guard::join_safe(&root, &super::active_profile(app_handle))?;+ let specs: Vec<String> = entries+ .iter()+ .map(|(id, version)| format!("{id}@{version}"))+ .collect();+ // 探测整体失败(registry 不可达)不阻断迁移:全部条目降级为「未知兼容」,+ // 由安装链路既有的授权流程兜底。+ let inspected: Vec<PluginInspect> = inspect_specs(app_handle, &specs, None)+ .await+ .unwrap_or_default();+ let runtime = crate::service::core::active_version(app_handle);+ let mut plugins = Vec::with_capacity(entries.len());+ for (index, (id, version)) in entries.into_iter().enumerate() {+ let (verdict, target_version) = match inspected.get(index).and_then(|item| item.compatible) {+ Some(true) => (MigrationVerdict::Compatible, None),+ Some(false) => match nearest(app_handle, &id, runtime.as_deref()).await {+ Some(nearest) => compare_versions(&version, &nearest),+ None => (MigrationVerdict::Unknown, None),+ },+ None => (MigrationVerdict::Unknown, None),+ };+ let spec = match &target_version {+ Some(target) => format!("{id}@{target}"),+ None => format!("{id}@{version}"),+ };+ plugins.push(MigrationEntry {+ id,+ version,+ spec,+ verdict,+ target_version,+ });+ }+ Ok(MigrationAnalysis {+ plugins,+ data: data_items(&dir, &target),+ })+}++/// 把源档案选中的数据并入目标档案(当前档案)。+///+/// 逐项独立执行:一项失败不影响其余项,结果里逐项报告。+pub fn apply(+ app_handle: &AppHandle,+ source_id: &str,+ kinds: &[MigrationDataKind],+) -> Result<MigrateReport, String> {+ let root = config::get_dsh_data_path(app_handle).join("profiles");+ let source = fs_guard::join_safe(&root, source_id)?;+ if !source.is_dir() {+ return Err("PROFILE_MIGRATION_SOURCE_MISSING: source profile does not exist".to_string());+ }+ let active = super::active_profile(app_handle);+ if active == source_id {+ return Err("PROFILE_MIGRATION_SAME_PROFILE: source is the active profile".to_string());+ }+ let target = fs_guard::join_safe(&root, &active)?;+ let mut report = MigrateReport {+ applied: Vec::new(),+ skipped: Vec::new(),+ failures: Vec::new(),+ };+ for kind in kinds {+ match merge(*kind, &source, &target) {+ Ok(true) => report.applied.push(*kind),+ Ok(false) => report.skipped.push(*kind),+ Err(message) => report.failures.push(MigrationFailure {+ kind: *kind,+ message,+ }),+ }+ }+ Ok(report)+}++/// 源档案里实际存在的档案级数据(空项不列,前端据列表决定渲染哪些开关)。+///+/// `covered` 逐类与目标档案对比:目标已完全包含源的内容时迁移是空操作,界面应当+/// 直接禁用勾选(与「目标已装同名插件」同一套语义)。+fn data_items(source: &Path, target: &Path) -> Vec<MigrationDataItem> {+ let mut items = Vec::new();+ let patch = patch_layer_entries(&source.join(PATCH_FILE)).unwrap_or_default();+ if !patch.is_empty() {+ items.push(MigrationDataItem {+ kind: MigrationDataKind::Patch,+ count: Some(patch.len()),+ covered: patch_covered(&patch, target),+ });+ }+ let disabled = disable::load_disabled(source);+ if !disabled.is_empty() {+ let existing = disable::load_disabled(target);+ items.push(MigrationDataItem {+ kind: MigrationDataKind::Disabled,+ count: Some(disabled.len()),+ covered: disabled.keys().all(|id| existing.contains_key(id)),+ });+ }+ let policy = release_age_excludes(source);+ if !policy.is_empty() {+ let existing = release_age_excludes(target);+ items.push(MigrationDataItem {+ kind: MigrationDataKind::Policy,+ count: Some(policy.len()),+ covered: policy.iter().all(|entry| existing.contains(entry)),+ });+ }+ if source.join(CREDENTIALS_FILE).is_file() {+ items.push(MigrationDataItem {+ kind: MigrationDataKind::Credentials,+ count: None,+ covered: target.join(CREDENTIALS_FILE).exists(),+ });+ }+ items+}++/// 目标档案的补丁层是否已包含源档案的全部条目;无 `id` 的条目一律算未覆盖+/// (它们没有身份键,无法判定是否重复)。+fn patch_covered(source: &[Value], target: &Path) -> bool {+ let existing = patch_layer_entries(&target.join(PATCH_FILE)).unwrap_or_default();+ let ids: HashSet<&str> = existing.iter().filter_map(patch_entry_id).collect();+ source.iter().all(|entry| match patch_entry_id(entry) {+ Some(id) => ids.contains(id),+ None => false,+ })+}++/// 补丁层文件的顶层数组;文件缺失、读不出或不是数组时返回 `None`。+fn patch_layer_entries(path: &Path) -> Option<Vec<Value>> {+ let content = fs::read_to_string(path).ok()?;+ let document: Value = serde_yaml::from_str(&content).ok()?;+ Some(document.as_sequence()?.clone())+}++/// 补丁层条目的身份键;缺失 `id` 的条目无身份,调用方按「永远追加」处理。+fn patch_entry_id(entry: &Value) -> Option<&str> {+ entry.get("id").and_then(Value::as_str)+}++/// 档案的 `minimumReleaseAgeExclude` 列表。+fn release_age_excludes(dir: &Path) -> Vec<String> {+ let Ok(content) = fs::read_to_string(dir.join(POLICY_FILE)) else {+ return Vec::new();+ };+ let Ok((document, _)) = super::parse_workspace_document(&content) else {+ return Vec::new();+ };+ document+ .as_mapping()+ .and_then(|mapping| mapping.get(Value::String(POLICY_KEY.to_string())))+ .and_then(Value::as_sequence)+ .map(|sequence| {+ sequence+ .iter()+ .filter_map(|item| item.as_str().map(String::from))+ .collect()+ })+ .unwrap_or_default()+}++/// 单项合并;`Ok(true)` = 已写入,`Ok(false)` = 目标已有或源里没有内容。+fn merge(kind: MigrationDataKind, source: &Path, target: &Path) -> Result<bool, String> {+ match kind {+ MigrationDataKind::Patch => merge_patch(source, target),+ MigrationDataKind::Disabled => merge_disabled(source, target),+ MigrationDataKind::Policy => merge_policy(source, target),+ MigrationDataKind::Credentials => merge_credentials(source, target),+ }+}++/// 补丁层按条目 `id` 求并集:目标已有的 `id` 一律不动(目标优先)。+fn merge_patch(source: &Path, target: &Path) -> Result<bool, String> {+ let Some(incoming) = patch_layer_entries(&source.join(PATCH_FILE)) else {+ return Ok(false);+ };+ let mut entries = patch_layer_entries(&target.join(PATCH_FILE)).unwrap_or_default();+ let mut existing: HashSet<String> = entries+ .iter()+ .filter_map(patch_entry_id)+ .map(String::from)+ .collect();+ let mut added = false;+ for entry in incoming {+ if let Some(id) = patch_entry_id(&entry) {+ if !existing.insert(id.to_string()) {+ continue;+ }+ }+ entries.push(entry);+ added = true;+ }+ if !added {+ return Ok(false);+ }+ let rendered = serde_yaml::to_string(&Value::Sequence(entries))+ .map_err(|e| format!("PROFILE_MIGRATION_PATCH_RENDER: {e}"))?;+ fs::write(target.join(PATCH_FILE), rendered)+ .map_err(|e| format!("PROFILE_MIGRATION_PATCH_WRITE: {e}"))?;+ Ok(true)+}++/// 禁用清单按插件 id 求并集:目标已有的 id 保留目标记录(含禁用时间)。+fn merge_disabled(source: &Path, target: &Path) -> Result<bool, String> {+ if !source.join(DISABLED_FILE).is_file() {+ return Ok(false);+ }+ let incoming = disable::load_disabled(source);+ if incoming.is_empty() {+ return Ok(false);+ }+ let mut merged = disable::load_disabled(target);+ let before = merged.len();+ for (id, entry) in incoming {+ merged.entry(id).or_insert(entry);+ }+ if merged.len() == before {+ return Ok(false);+ }+ disable::save_disabled(target, &merged)?;+ Ok(true)+}++/// 发布时长豁免并进目标档案(复用既有的档案级写入,含去重与落盘格式)。+///+/// 按 `target` 路径写:调用开始时捕获的目标档案不能在半途被「当前档案」改道。+fn merge_policy(source: &Path, target: &Path) -> Result<bool, String> {+ let existing = release_age_excludes(target);+ let missing: Vec<String> = release_age_excludes(source)+ .into_iter()+ .filter(|entry| !existing.contains(entry))+ .collect();+ if missing.is_empty() {+ return Ok(false);+ }+ super::release_age_excludes_at(target, &missing)?;+ Ok(true)+}++/// 凭据绝不覆盖:目标已有 `.credentials.yaml` 时整项跳过。+fn merge_credentials(source: &Path, target: &Path) -> Result<bool, String> {+ let from = source.join(CREDENTIALS_FILE);+ if !from.is_file() {+ return Ok(false);+ }+ let to = target.join(CREDENTIALS_FILE);+ if to.exists() {+ return Ok(false);+ }+ fs::create_dir_all(target).map_err(|e| format!("PROFILE_MIGRATION_CREDENTIALS_DIR: {e}"))?;+ fs::copy(&from, &to).map_err(|e| format!("PROFILE_MIGRATION_CREDENTIALS_COPY: {e}"))?;+ Ok(true)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn workspace(name: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!("dsh-migrate-{name}-{}", std::process::id()));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();+ dir+ }++ #[test]+ fn registry_ranges_exclude_local_and_git_sources() {+ for raw in ["1.2.3", "^0.24.1", "~1.0.0", ">=1 <2", "v1.2.3", "*"] {+ assert!(is_registry_range(raw), "{raw} 应视为 registry 版本");+ }+ for raw in [+ "link:D:/software/plugin",+ "file:../plugin",+ "workspace:^1.0.0",+ "catalog:^1.0.0",+ "portal:./plugin",+ "github:owner/repo",+ "git+https://example.com/a.git",+ "npm:[email protected]",+ ] {+ assert!(!is_registry_range(raw), "{raw} 不应进入迁移列表");+ }+ }++ #[test]+ fn pick_nearest_returns_highest_compatible_version() {+ let packument = json!({+ "versions": {+ "0.24.1": { "peerDependencies": { "@deepseek-ai/dsh-llm": "^0.2.0" } },+ "0.23.0": { "peerDependencies": { "@deepseek-ai/dsh-llm": "^0.1.5" } },+ "0.22.0": { "peerDependencies": { "@deepseek-ai/dsh-llm": "^0.1.5" } },+ "0.25.0": { "peerDependencies": { "@deepseek-ai/dsh-llm": "^0.3.0" } }+ }+ });++ assert_eq!(+ pick_nearest(&packument, "0.1.7").as_deref(),+ Some("0.23.0"),+ "最高兼容版本必须是 0.23.0,而不是 latest 或最旧"+ );+ }++ /// 没有 DSH 家族依赖的版本是「无从判定」(`None`),不能当兼容候选。+ #[test]+ fn pick_nearest_ignores_versions_without_dsh_peers() {+ let packument = json!({+ "versions": {+ "1.0.0": { "dependencies": { "zod": "^4.0.0" } },+ "0.9.0": { "peerDependencies": { "@deepseek-ai/dsh": "^0.1.0" } }+ }+ });++ assert_eq!(pick_nearest(&packument, "0.1.7").as_deref(), Some("0.9.0"));+ }++ #[test]+ fn pick_nearest_returns_none_when_nothing_is_proven_compatible() {+ let packument = json!({+ "versions": { "2.0.0": { "peerDependencies": { "@deepseek-ai/dsh": "^0.3.0" } } }+ });++ assert_eq!(pick_nearest(&packument, "0.1.7"), None);+ assert_eq!(pick_nearest(&json!({}), "0.1.7"), None);+ }++ #[test]+ fn compare_versions_maps_incompatible_install_to_upgrade_or_downgrade() {+ assert_eq!(+ compare_versions("0.22.0", "0.24.0"),+ (MigrationVerdict::Upgrade, Some("0.24.0".to_string()))+ );+ assert_eq!(+ compare_versions("0.24.0", "0.22.0"),+ (MigrationVerdict::Downgrade, Some("0.22.0".to_string()))+ );+ assert_eq!(+ compare_versions("0.24.0", "0.24.0"),+ (MigrationVerdict::Unknown, None)+ );+ assert_eq!(+ compare_versions("nightly", "0.24.0"),+ (MigrationVerdict::Unknown, None)+ );+ }++ #[test]+ fn merge_patch_appends_only_missing_ids() {+ let source = workspace("patch-source");+ let target = workspace("patch-target");+ fs::write(+ source.join(PATCH_FILE),+ "- id: shared\n name: '@scope/shared'\n- id: new\n name: '@scope/new'\n",+ )+ .unwrap();+ fs::write(+ target.join(PATCH_FILE),+ "- id: shared\n name: '@scope/local'\n",+ )+ .unwrap();++ assert!(merge_patch(&source, &target).unwrap());++ let merged = patch_layer_entries(&target.join(PATCH_FILE)).unwrap();+ assert_eq!(merged.len(), 2, "{merged:?}");+ assert_eq!(+ merged[0].get("name").and_then(Value::as_str),+ Some("@scope/local"),+ "目标已有的 id 必须保留目标条目"+ );+ assert_eq!(merged[1].get("id").and_then(Value::as_str), Some("new"));+ assert!(+ !merge_patch(&source, &target).unwrap(),+ "无新增时必须报告未改动,避免无意义的写盘"+ );++ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_dir_all(&target);+ }++ #[test]+ fn merge_disabled_keeps_target_entries() {+ let source = workspace("disabled-source");+ let target = workspace("disabled-target");+ fs::write(+ source.join(DISABLED_FILE),+ r#"{"a":{"disabledAt":"1","reason":"user"},"b":{"disabledAt":"2","reason":"user"}}"#,+ )+ .unwrap();+ fs::write(+ target.join(DISABLED_FILE),+ r#"{"a":{"disabledAt":"9","reason":"user"}}"#,+ )+ .unwrap();++ assert!(merge_disabled(&source, &target).unwrap());++ let merged = disable::load_disabled(&target);+ assert_eq!(merged.len(), 2);+ assert_eq!(merged["a"].disabled_at, "9", "目标记录必须保留");+ assert_eq!(merged["b"].disabled_at, "2");++ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_dir_all(&target);+ }++ #[test]+ fn merge_credentials_never_overwrites_existing_target() {+ let source = workspace("credentials-source");+ let target = workspace("credentials-target");+ fs::write(source.join(CREDENTIALS_FILE), "token: source\n").unwrap();++ assert!(merge_credentials(&source, &target).unwrap());+ assert_eq!(+ fs::read_to_string(target.join(CREDENTIALS_FILE)).unwrap(),+ "token: source\n"+ );++ assert!(+ !merge_credentials(&source, &target).unwrap(),+ "目标已有凭据时必须跳过"+ );+ fs::write(source.join(CREDENTIALS_FILE), "token: changed\n").unwrap();+ assert!(!merge_credentials(&source, &target).unwrap());+ assert_eq!(+ fs::read_to_string(target.join(CREDENTIALS_FILE)).unwrap(),+ "token: source\n",+ "目标凭据不可被源覆盖"+ );++ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_dir_all(&target);+ }++ #[test]+ fn release_age_excludes_reads_only_the_policy_key() {+ let dir = workspace("policy");+ fs::write(+ dir.join(POLICY_FILE),+ "packages:\n - .\nminimumReleaseAgeExclude:\n - [email protected]\n - '@scope/[email protected]'\n",+ )+ .unwrap();++ assert_eq!(+ release_age_excludes(&dir),+ vec!["[email protected]".to_string(), "@scope/[email protected]".to_string()]+ );++ let _ = fs::remove_dir_all(&dir);+ }++ /// 豁免写进 `target` 那份文件:调用方捕获的目标档案不能被「当前档案」改道。+ #[test]+ fn merge_policy_writes_into_the_captured_target_dir() {+ let source = workspace("policy-source");+ let target = workspace("policy-target");+ fs::write(+ source.join(POLICY_FILE),+ "minimumReleaseAgeExclude:\n - [email protected]\n",+ )+ .unwrap();+ fs::write(target.join(POLICY_FILE), "packages:\n - .\n").unwrap();++ assert!(merge_policy(&source, &target).unwrap());+ assert_eq!(release_age_excludes(&target), vec!["[email protected]".to_string()]);+ // 幂等:第二次没有可加条目+ assert!(!merge_policy(&source, &target).unwrap());++ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_dir_all(&target);+ }++ #[test]+ fn data_items_lists_only_what_the_source_profile_has() {+ let dir = workspace("items");+ let target = workspace("items-target");+ assert!(data_items(&dir, &target).is_empty(), "空档案不应列出任何数据项");++ fs::write(dir.join(PATCH_FILE), "- id: only-patch\n").unwrap();+ fs::write(dir.join(CREDENTIALS_FILE), "token: x\n").unwrap();++ let items = data_items(&dir, &target);+ assert_eq!(+ items.iter().map(|item| item.kind).collect::<Vec<_>>(),+ vec![MigrationDataKind::Patch, MigrationDataKind::Credentials]+ );+ assert_eq!(items[0].count, Some(1));+ assert_eq!(items[0].covered, false, "目标档案没有这些条目,必须可迁移");+ assert_eq!(items[1].count, None);+ assert_eq!(items[1].covered, false);++ let _ = fs::remove_dir_all(&dir);+ let _ = fs::remove_dir_all(&target);+ }++ /// 目标档案已完全包含源的内容时迁移是空操作,界面据此禁用勾选。+ #[test]+ fn data_items_marks_fully_contained_entries_as_covered() {+ let source = workspace("covered-source");+ let target = workspace("covered-target");+ fs::write(+ source.join(PATCH_FILE),+ "- id: shared\n- id: extra\n",+ )+ .unwrap();+ fs::write(target.join(PATCH_FILE), "- id: shared\n").unwrap();+ fs::write(+ source.join(POLICY_FILE),+ "minimumReleaseAgeExclude:\n - [email protected]\n - '@scope/[email protected]'\n",+ )+ .unwrap();+ fs::write(+ target.join(POLICY_FILE),+ "minimumReleaseAgeExclude:\n - [email protected]\n - '@scope/[email protected]'\n",+ )+ .unwrap();+ fs::write(source.join(CREDENTIALS_FILE), "token: x\n").unwrap();+ fs::write(target.join(CREDENTIALS_FILE), "token: y\n").unwrap();++ let items = data_items(&source, &target);+ let covered: Vec<(MigrationDataKind, bool)> =+ items.iter().map(|item| (item.kind, item.covered)).collect();+ assert_eq!(+ covered,+ vec![+ (MigrationDataKind::Patch, false),+ (MigrationDataKind::Policy, true),+ (MigrationDataKind::Credentials, true),+ ],+ "只有目标已完整包含的类目才算 covered"+ );++ fs::write(target.join(PATCH_FILE), "- id: shared\n- id: extra\n").unwrap();+ let items = data_items(&source, &target);+ assert!(+ items.iter().all(|item| item.covered),+ "目标补齐后全部类目都应视为已包含:{items:?}"+ );++ let _ = fs::remove_dir_all(&source);+ let _ = fs::remove_dir_all(&target);+ }+}diff --git a/src-tauri/src/service/profile/mod.rs b/src-tauri/src/service/profile/mod.rsindex b0269744..20765f99 100644--- a/src-tauri/src/service/profile/mod.rs+++ b/src-tauri/src/service/profile/mod.rs@@ -38,6 +38,8 @@ use std::fs;use std::path::{Path, PathBuf};use tauri::AppHandle;+pub mod migrate;+/// 桌面端默认档案(内置,不可删除)pub const DEFAULT_PROFILE: &str = "web";@@ -157,7 +159,7 @@ pub(crate) fn ensure_profile_pnpm_policy(app_handle: &AppHandle) -> Result<(), S.iter().map(|package| (*package).to_string()).collect();- profile_release_age_excludes(app_handle, &entries)+ release_age_excludes_at(&profile_dir_of(app_handle, &active_profile(app_handle)), &entries)}/// 档案的 `minimumReleaseAgeExclude` 里是否已经有这个精确 `包名@版本`。@@ -198,15 +200,16 @@ pub(crate) fn allow_profile_release_age(if entries.is_empty() {return Err("PROFILE_RELEASE_AGE_EMPTY: no release-age exemption to record".to_string());}- profile_release_age_excludes(app_handle, entries)+ release_age_excludes_at(&profile_dir_of(app_handle, &active_profile(app_handle)), entries)}-/// 把 `entries` 并入档案 `pnpm-workspace.yaml` 的 `minimumReleaseAgeExclude`(按需落盘)。-fn profile_release_age_excludes(- app_handle: &AppHandle,- entries: &[String],-) -> Result<(), String> {- let path = profile_dir_of(app_handle, &active_profile(app_handle)).join("pnpm-workspace.yaml");+/// 把 `entries` 并入**指定档案目录** `pnpm-workspace.yaml` 的 `minimumReleaseAgeExclude`+/// (按需落盘)。+///+/// 收目录而不是 `AppHandle`:调用方可能持有「操作开始时捕获」的档案路径,半途用户切了+/// 当前档案时,写入不能被改道到新档案(档案迁移即如此)。+pub(crate) fn release_age_excludes_at(dir: &Path, entries: &[String]) -> Result<(), String> {+ let path = dir.join("pnpm-workspace.yaml");let existing = match fs::read_to_string(&path) {Ok(content) => content,Err(error) if error.kind() == std::io::ErrorKind::NotFound => {diff --git a/src/config/query-keys.ts b/src/config/query-keys.tsindex 321982d8..421a604c 100644--- a/src/config/query-keys.ts+++ b/src/config/query-keys.ts@@ -21,6 +21,8 @@ export const queryKeys = {localPluginHmr: ['local_plugin_hmr'] as const,/** dsh 档案列表 */profiles: ['profiles'] as const,+ /** 某一档案的可迁移插件与数据(迁移对话框,按源档案 id 区分) */+ profileMigration: (sourceId: string) => ['profile_migration', sourceId] as const,/** 当前档案的备份快照列表 */backups: ['backups'] as const,/** 数据目录状态与旧目录备份(issue #871) */diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex deb0b282..efac79c6 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -243,6 +243,38 @@"profiles.clone_exists": "A profile named \"{{name}}\" already exists.","profiles.clone_empty": "Please enter a profile name","profiles.clone_invalid": "Profile name contains invalid characters",+ "profiles.migrate": "Migrate profile data",+ "profiles.migrate_title": "Migrate Profile Data",+ "profiles.migrate_desc": "Merge the plugins and profile data of the source profile into the active profile. The source profile is left untouched, and on conflicts the active profile always wins.",+ "profiles.migrate_target_active": "Active",+ "profiles.migrate_core": "Core {{version}}",+ "profiles.migrate_source": "Source profile",+ "profiles.migrate_no_source": "No other profile to migrate from",+ "profiles.migrate_pick_source": "Choose a source profile first",+ "profiles.migrate_tab_plugins": "Plugins ({{count}})",+ "profiles.migrate_tab_data": "Profile data",+ "profiles.migrate_plugins_empty": "This profile has no plugins to migrate",+ "profiles.migrate_nothing": "The active profile already contains everything from the source profile",+ "profiles.migrate_installed": "Installed {{version}}",+ "profiles.migrate_verdict_compatible": "Compatible",+ "profiles.migrate_verdict_upgrade": "↑Upgrade → {{version}}",+ "profiles.migrate_verdict_downgrade": "↓Downgrade → {{version}}",+ "profiles.migrate_verdict_unknown": "Compatibility unknown",+ "profiles.migrate_data_patch": "Patch layer · {{count}}",+ "profiles.migrate_data_disabled": "Disabled list · {{count}}",+ "profiles.migrate_data_policy": "minimumReleaseAgeExclude · {{count}}",+ "profiles.migrate_data_credentials": "Credentials",+ "profiles.migrate_data_absent": "Not in the source profile",+ "profiles.migrate_data_covered": "Already in the active profile",+ "profiles.migrate_credentials_badge": "Sensitive",+ "profiles.migrate_analyzing": "Analyzing…",+ "profiles.migrate_analyze_failed": "Failed to read the source profile — nothing to migrate",+ "profiles.migrate_confirm": "Start migration",+ "profiles.migrate_busy": "Migrating…",+ "profiles.migrate_partial": "Some profile data was not migrated",+ "profiles.migrate_plugin_failed": "{{count}} plugin(s) failed to migrate",+ "profiles.migrate_success": "Migrated {{count}} item(s)",+ "profiles.migrate_failed": "Migration failed","backup.manage": "Backup","backup.back_to_profiles": "Back to profiles","backup.manual_section": "Manual Backup",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex 4186941a..8a699227 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -243,6 +243,38 @@"profiles.clone_exists": "档案名称「{{name}}」已存在","profiles.clone_empty": "请输入档案名称","profiles.clone_invalid": "档案名称包含无效字符",+ "profiles.migrate": "档案数据迁移",+ "profiles.migrate_title": "迁移档案数据",+ "profiles.migrate_desc": "把来源档案的插件与档案数据并入当前档案,源档案保持原样。",+ "profiles.migrate_target_active": "使用中",+ "profiles.migrate_core": "核心 {{version}}",+ "profiles.migrate_source": "来源档案",+ "profiles.migrate_no_source": "没有其他档案可迁移",+ "profiles.migrate_pick_source": "请先选择来源档案",+ "profiles.migrate_tab_plugins": "插件({{count}})",+ "profiles.migrate_tab_data": "档案数据",+ "profiles.migrate_plugins_empty": "这个档案没有可迁移的插件",+ "profiles.migrate_nothing": "当前档案已包含源档案的全部内容,没有可迁移的项目",+ "profiles.migrate_installed": "已装 {{version}}",+ "profiles.migrate_verdict_compatible": "兼容",+ "profiles.migrate_verdict_upgrade": "↑升级 → {{version}}",+ "profiles.migrate_verdict_downgrade": "↓降级 → {{version}}",+ "profiles.migrate_verdict_unknown": "未知兼容",+ "profiles.migrate_data_patch": "补丁层 · {{count}} 项",+ "profiles.migrate_data_disabled": "禁用清单 · {{count}} 项",+ "profiles.migrate_data_policy": "时间限制豁免 · {{count}} 项",+ "profiles.migrate_data_credentials": "凭据",+ "profiles.migrate_data_absent": "源档案没有此项",+ "profiles.migrate_data_covered": "当前档案已包含",+ "profiles.migrate_credentials_badge": "敏感",+ "profiles.migrate_analyzing": "正在分析…",+ "profiles.migrate_analyze_failed": "读取源档案失败,无法迁移",+ "profiles.migrate_confirm": "开始迁移",+ "profiles.migrate_busy": "迁移中…",+ "profiles.migrate_partial": "部分档案数据未迁移",+ "profiles.migrate_plugin_failed": "{{count}} 个插件迁移失败",+ "profiles.migrate_success": "已迁移 {{count}} 项",+ "profiles.migrate_failed": "迁移失败","backup.manage": "备份","backup.back_to_profiles": "返回档案列表","backup.manual_section": "手动备份",diff --git a/src/store/modules/plugins/store.ts b/src/store/modules/plugins/store.tsindex 17fe5e22..4f15b40d 100644--- a/src/store/modules/plugins/store.ts+++ b/src/store/modules/plugins/store.ts@@ -19,7 +19,6 @@ import { invoke } from '@tauri-apps/api/core'import i18next from 'i18next'import { defineStore } from 'valtio-define'import { toast } from '@/utils/toast'-import { harness } from '../harness'import { onPluginsManagerEvent, triggerPluginsManagerEvent } from './events'import { enrichInstalled, normalizeRef, normalizeRefs, parseBlockedRefusal, parseUpdateFailures, refusalNames } from './utils'@@ -568,10 +567,10 @@ export const plugins = defineStore({returnconst pending = this.queueResultsthis.queueResults = []- this.presentQueueResults(pending, group)+ this.presentQueueResults(pending)},- presentQueueResults(results: PluginProcessResult[], group: PluginGroup): void {+ presentQueueResults(results: PluginProcessResult[]): void {if (results.length === 0)returnconst succeeded = results.filter(result => result.ok).length@@ -585,17 +584,6 @@ export const plugins = defineStore({&& result.reason !== 'cancelled'&& result.reason !== 'rejected',).length- const restart = group.options.restartOnSettle && succeeded > 0- // 需要重启时把「重启」按钮挂在结果气泡上:一次操作只留一条。单独再弹一条常驻的重启提示- // 会和结果提示同时出现,用户看到的就是「两个 toast 说同一件事」。- let restartKey = ''- const restartAction = {- children: i18next.t('app.restart'),- onPress: () => {- toast.close(restartKey)- void harness.restart()- },- }if (results.length === 1) {const [result] = results// 用户自己的选择(取消 / 拒绝授权)不再补一条错误提示追问他;其余结果无论成败都要@@ -606,13 +594,9 @@ export const plugins = defineStore({result.ok ? RESULT_SUCCESS[result.process.type] : RESULT_FAILED[result.process.type],{ name: result.process.name },)- restartKey = toast(+ toast(title,- result.ok- ? restart- ? { variant: 'accent', timeout: 0, actionProps: restartAction }- : { variant: 'default' }- : { variant: 'danger', description: result.error },+ result.ok ? { variant: 'default' } : { variant: 'danger', description: result.error },)return}@@ -624,11 +608,9 @@ export const plugins = defineStore({// 每一项都是用户自己的选择时没有任何收支可报,别弹一条空汇总气泡追问他。if (parts.length === 0)return- restartKey = toast(i18next.t('plugins.queue_summary'), {+ toast(i18next.t('plugins.queue_summary'), {description: parts.join(' · '),- variant: failed > 0 ? 'danger' : restart ? 'accent' : 'default',- timeout: restart ? 0 : undefined,- actionProps: restart ? restartAction : undefined,+ variant: failed > 0 ? 'danger' : 'default',})},diff --git a/src/types/plugin.ts b/src/types/plugin.tsindex bf9c91e4..9cc76962 100644--- a/src/types/plugin.ts+++ b/src/types/plugin.ts@@ -80,3 +80,53 @@ export interface PatchEntryStripReport {/** 被清理过的补丁层(没有悬空条目时为空) */layers: StrippedPatchLayer[]}++/** 迁移条目的兼容性判定结果(判定基准 = 当前核心版本) */+export type MigrationVerdict = 'compatible' | 'upgrade' | 'downgrade' | 'unknown'++/** Rust 侧 service::profile::migrate::MigrationEntry 的序列化形态 */+export interface MigrationEntry {+ /** 依赖键(npm 包名) */+ id: string+ /** 源档案已安装的版本 */+ version: string+ /** 实际用于安装的 spec(不兼容时带目标版本) */+ spec: string+ verdict: MigrationVerdict+ /** 升级/降级的建议版本;其余判定缺省 */+ targetVersion?: string+}++/** 档案级数据类别(Rust 侧 MigrationDataKind) */+export type MigrationDataKind = 'patch' | 'disabled' | 'policy' | 'credentials'++/** Rust 侧 service::profile::migrate::MigrationDataItem 的序列化形态 */+export interface MigrationDataItem {+ kind: MigrationDataKind+ /** 条目数;凭据等无「条数」概念的一项缺省 */+ count?: number+ /** 目标档案已完全包含:迁移是空操作,界面禁用勾选 */+ covered: boolean+}++/** Rust 侧 service::profile::migrate::MigrationAnalysis 的序列化形态 */+export interface MigrationAnalysis {+ plugins: MigrationEntry[]+ /** 只有源档案里实际存在的数据项才会出现 */+ data: MigrationDataItem[]+}++/** Rust 侧 service::profile::migrate::MigrationFailure 的序列化形态 */+export interface MigrationFailure {+ kind: MigrationDataKind+ /** 失败原因(Rust 侧错误码,含大写前缀) */+ message: string+}++/** Rust 侧 service::profile::migrate::MigrateReport 的序列化形态 */+export interface MigrateReport {+ applied: MigrationDataKind[]+ /** 目标已有、按「目标优先」未改动的项 */+ skipped: MigrationDataKind[]+ failures: MigrationFailure[]+}diff --git a/src/ui/config/profile.tsx b/src/ui/config/profile.tsxindex 2cdda045..fb26bb85 100644--- a/src/ui/config/profile.tsx+++ b/src/ui/config/profile.tsx@@ -1,5 +1,5 @@import type { Profile } from '@/types'-import { Plus } from '@gravity-ui/icons'+import { CopyArrowRight, Plus } from '@gravity-ui/icons'import { AlertDialog, Button, Checkbox, Chip, Description, Input, Label } from '@heroui/react'import { useOverlay } from '@overlastic/react'import { useToggle } from '@reause/core'@@ -18,6 +18,7 @@ import { useInvalidateOnSettingUpdated } from '@/hooks/use-invalidate-on-settingimport { store } from '@/store'import { waitForHarnessStopped } from '@/store/modules/harness'import { ConfigBackup } from '@/ui/config/backup'+import { ProfileMigrateDialog } from '@/ui/dialog/profile-migrate'import { normalizeProfileId } from '@/utils/profile-id'import { silence } from '@/utils/silence'import { toast } from '@/utils/toast'@@ -106,9 +107,14 @@ export function ConfigProfile() {const profiles = profileList ?? []const loading = isLoadingconst error = profileError ? String(profileError) : ''+ /** 当前使用中的档案,即迁移的目标(不可更改) */+ const activeProfile = profiles.find(profile => profile.active)/** 操作进行中标记(新建/切换/删除/重置/克隆任一) */const busy = create.isPending || activate.isPending || remove.isPending || reset.isPending || clone.isPending+ /** 迁移入口的禁用条件:操作进行中、没有当前档案、或没有第二个档案可作来源 */+ const migrateBlocked = busy || !activeProfile || profiles.length < 2+const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })const { t } = useTranslation()@@ -120,6 +126,9 @@ export function ConfigProfile() {const [cloning, setCloning] = useState<{ sourceId: string, sourceName: string } | null>(null)const [cloneName, setCloneName] = useState('')+ // 迁移档案数据:来源档案在对话框内选择,目标恒为当前使用中的档案+ const [migrateDialogHolder, openMigrateDialog] = useOverlay(ProfileMigrateDialog, { type: 'holder' })+/*** 档案名会直接当磁盘目录名与 CLI `--profile` 参数,只能用 ASCII 字母数字(`-`/`_`/空格* 分隔,其余字符被丢弃,与后端 `normalize_profile_id` 同一套规则)。归一化后为空说明@@ -363,7 +372,22 @@ export function ConfigProfile() {return (<div className="space-y-3">- <Panel.Header title={t('profiles.title')} description={t('profiles.tooltip')} testId="dsh-config-panel-title" />+ <Panel.Header+ title={t('profiles.title')}+ description={t('profiles.tooltip')}+ testId="dsh-config-panel-title"+ action={(+ <Button+ size="sm"+ variant="primary"+ isDisabled={migrateBlocked}+ onPress={() => void openMigrateDialog()}+ >+ <CopyArrowRight className="size-3.5" />+ {t('profiles.migrate')}+ </Button>+ )}+ />{/* 加载 / 失败 / 列表 */}<Panel.Loadable loading={loading} error={error}>@@ -495,6 +519,7 @@ export function ConfigProfile() {</div></Panel.Loadable>{dialogHolder}+ {migrateDialogHolder}{/* 克隆档案:命名对话框(创建型,accent;可编辑建议名称) */}<AlertDialogdiff --git a/src/ui/dialog/profile-migrate.test.tsx b/src/ui/dialog/profile-migrate.test.tsxnew file mode 100644index 00000000..b3677fb4--- /dev/null+++ b/src/ui/dialog/profile-migrate.test.tsx@@ -0,0 +1,180 @@+// @vitest-environment jsdom+import { OverlaysProvider, useOverlay } from '@overlastic/react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { mockIPC } from '@tauri-apps/api/mocks'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { StrictMode } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { ProfileMigrateDialog } from './profile-migrate'++const { install, toast } = vi.hoisted(() => ({+ install: vi.fn(async (refs: string[]) => refs.map(spec => ({ ok: true, spec }))),+ toast: vi.fn(),+}))++vi.mock('@/hooks/use-plugins-manager', () => ({+ useDshPluginsManager: () => ({+ installed: [{ id: '@scope/installed', version: '0.1.0' }],+ install,+ }),+}))+vi.mock('@/utils/toast', () => ({ toast }))+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))++vi.stubGlobal('ResizeObserver', class {+ observe() {}+ unobserve() {}+ disconnect() {}+})++if (typeof CSS === 'undefined')+ vi.stubGlobal('CSS', { escape: (value: string) => value })++Element.prototype.getAnimations = function () {+ return []+}++function fixtures() {+ return {+ plugins: [+ { id: '@scope/installed', version: '0.1.0', spec: '@scope/[email protected]', verdict: 'compatible' },+ { id: '@scope/fresh', version: '2.1.0', spec: '@scope/[email protected]', verdict: 'downgrade', targetVersion: '2.0.0' },+ ],+ data: [+ { kind: 'patch', count: 2, covered: false },+ { kind: 'policy', count: 1, covered: false },+ { kind: 'credentials', covered: false },+ ],+ }+}++let analysis: ReturnType<typeof fixtures>+let client: QueryClient+let calls: Record<string, unknown[]>++function Launcher() {+ const open = useOverlay(ProfileMigrateDialog)+ function handleOpen() {+ void open().catch(() => {})+ }+ return <button onClick={handleOpen}>Open migrate</button>+}++async function openDialog() {+ render(+ <StrictMode>+ <QueryClientProvider client={client}>+ <OverlaysProvider>+ <Launcher />+ </OverlaysProvider>+ </QueryClientProvider>+ </StrictMode>,+ )+ fireEvent.click(screen.getByText('Open migrate'))+ fireEvent.click(await screen.findByRole('button', { name: /profiles\.migrate_source/ }))+ fireEvent.click(await screen.findByRole('option', { name: 'core-021' }))+ await screen.findByRole('checkbox', { name: '@scope/installed' })+}++async function submit() {+ fireEvent.click(screen.getByText('profiles.migrate_confirm'))+ await waitFor(() => expect(calls.migrate).toBeDefined())+}++beforeEach(() => {+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } } })+ analysis = fixtures()+ calls = {}+ install.mockClear()+ install.mockImplementation(async (refs: string[]) => {+ calls.install = refs+ return refs.map(spec => ({ ok: true, spec }))+ })+ toast.mockReset()+ mockIPC((command, args) => {+ if (command === 'get_cores')+ return [{ id: 'app', source: 'app', version: '0.1.7', tag: 'dsh-0.1.7', active: true }]+ if (command === 'get_profiles') {+ return [+ { id: 'core-021', name: 'core-021' },+ { id: 'core-020', name: 'core-020' },+ { id: 'web', name: 'web', active: true },+ ]+ }+ if (command === 'get_dsh_plugins')+ return []+ if (command === 'analyze_profile_migration') {+ calls.analyze = [args]+ return analysis+ }+ if (command === 'migrate_profile_data') {+ calls.migrate = [args]+ return { applied: (args as { items: string[] }).items, skipped: [], failures: [] }+ }+ throw new Error(`Unexpected command: ${command}`)+ })+})++afterEach(() => {+ cleanup()+ client.clear()+})++describe('profileMigrateDialog', () => {+ it('已装的插件默认不勾选,未装的默认勾选', async () => {+ await openDialog()+ expect((screen.getByRole('checkbox', { name: '@scope/installed' }) as HTMLInputElement).disabled).toBe(true)++ await submit()++ expect(calls.migrate).toEqual([{ sourceId: 'core-021', items: ['patch', 'policy'] }])+ expect(calls.install).toEqual(['@scope/[email protected]'])+ })++ it('取消勾选未装插件后只迁移档案数据', async () => {+ await openDialog()+ fireEvent.click(screen.getByRole('checkbox', { name: '@scope/fresh' }))+ await submit()++ expect(calls.install).toBeUndefined()+ })++ it('当前档案已完全包含的数据项不可勾选也不参与迁移', async () => {+ analysis.data = [+ { kind: 'patch', count: 2, covered: true },+ { kind: 'policy', count: 1, covered: false },+ { kind: 'credentials', covered: false },+ ]+ await openDialog()+ fireEvent.click(screen.getByText('profiles.migrate_tab_data'))++ expect((await screen.findByRole('checkbox', { name: 'patch' }) as HTMLInputElement).disabled).toBe(true)+ await submit()++ expect(calls.migrate).toEqual([{ sourceId: 'core-021', items: ['policy'] }])+ })++ it('换来源档案后上一个来源的勾选作废', async () => {+ await openDialog()+ fireEvent.click(screen.getByText('profiles.migrate_tab_data'))+ fireEvent.click(await screen.findByRole('checkbox', { name: 'credentials' }))++ fireEvent.click(screen.getByRole('button', { name: /core-021/ }))+ fireEvent.click(await screen.findByRole('option', { name: 'core-020' }))+ await screen.findByRole('checkbox', { name: '@scope/installed' })++ await submit()++ // 换源后凭据必须为新来源重新显式勾选,不能被上一个来源的选择带过去+ expect(calls.migrate).toEqual([{ sourceId: 'core-020', items: ['patch', 'policy'] }])+ })++ it('凭据必须显式勾选才会迁移', async () => {+ await openDialog()+ fireEvent.click(screen.getByText('profiles.migrate_tab_data'))+ fireEvent.click(await screen.findByRole('checkbox', { name: 'credentials' }))+ await submit()++ expect(calls.migrate).toEqual([{ sourceId: 'core-021', items: ['patch', 'policy', 'credentials'] }])+ })+})diff --git a/src/ui/dialog/profile-migrate.tsx b/src/ui/dialog/profile-migrate.tsxnew file mode 100644index 00000000..5757fba5--- /dev/null+++ b/src/ui/dialog/profile-migrate.tsx@@ -0,0 +1,390 @@+import type { PropsWithOverlays } from '@overlastic/react'+import type { HarnessCore, MigrateReport, MigrationAnalysis, MigrationDataKind, MigrationEntry, MigrationVerdict, Profile } from '@/types'+import { ArrowDown, ArrowRight, ArrowUp } from '@gravity-ui/icons'+import { AlertDialog, Button, Checkbox, Chip, InputGroup, ListBox, Select, Spinner, Tabs } from '@heroui/react'+import { useDisclosure } from '@overlastic/react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { invoke } from '@tauri-apps/api/core'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { If } from 'react-if-lite'+import { queryKeys } from '@/config/query-keys'+import { useDshPluginsManager } from '@/hooks/use-plugins-manager'+import { toast } from '@/utils/toast'++/** 判定结果 → Chip 颜色与文案 key */+const VERDICT_CHIPS: Record<MigrationVerdict, { key: string, color: 'default' | 'accent' | 'success' | 'warning' | 'danger' }> = {+ compatible: { key: 'profiles.migrate_verdict_compatible', color: 'default' },+ upgrade: { key: 'profiles.migrate_verdict_upgrade', color: 'success' },+ downgrade: { key: 'profiles.migrate_verdict_downgrade', color: 'warning' },+ unknown: { key: 'profiles.migrate_verdict_unknown', color: 'warning' },+}++/** 档案级数据类别 → 源档案里的文件名 */+const DATA_FILES: Record<MigrationDataKind, string> = {+ patch: 'cordis.patch.yml',+ disabled: 'disabled-plugins.json',+ policy: 'pnpm-workspace.yaml',+ credentials: '.credentials.yaml',+}++/** 数据项的列出顺序:凭据固定最后 */+const DATA_ORDER: MigrationDataKind[] = ['patch', 'disabled', 'policy', 'credentials']++/** 档案级数据类别 → 说明文案 key */+const DATA_LABEL_KEYS: Record<MigrationDataKind, string> = {+ patch: 'profiles.migrate_data_patch',+ disabled: 'profiles.migrate_data_disabled',+ policy: 'profiles.migrate_data_policy',+ credentials: 'profiles.migrate_data_credentials',+}++/**+ * 「迁移档案数据」对话框组件+ */+export function ProfileMigrateDialog(props: PropsWithOverlays) {+ const disclosure = useDisclosure({ props })+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const manager = useDshPluginsManager()++ // 1. 数据查询 (Queries)+ const { data: cores } = useQuery({+ queryKey: queryKeys.cores,+ queryFn: () => invoke<HarnessCore[]>('get_cores'),+ })+ const { data: profileList } = useQuery({+ queryKey: queryKeys.profiles,+ queryFn: () => invoke<Profile[]>('get_profiles'),+ })++ // 2. 本地用户选择状态+ const [pickedSourceId, setPickedSourceId] = useState('')+ const [pluginOverrides, setPluginOverrides] = useState<Record<string, boolean>>({})+ const [dataOverrides, setDataOverrides] = useState<Record<string, boolean>>({})++ // 3. 档案迁移分析数据 Query+ const { data: analysis, isLoading, isFetching, error } = useQuery({+ queryKey: queryKeys.profileMigration(pickedSourceId),+ queryFn: () => invoke<MigrationAnalysis>('analyze_profile_migration', { sourceId: pickedSourceId }),+ enabled: Boolean(pickedSourceId),+ })++ // 4. 派生数据提取与 Map 索引构造 (常数级别 O(1) 查找)+ const profiles = profileList ?? []+ const target = profiles.find(profile => profile.active)+ const sources = profiles.filter(profile => !profile.active)++ const activeCore = cores?.find(core => core.active)+ const coreVersion = activeCore ? activeCore.version || activeCore.tag : ''+ const plugins = analysis?.plugins ?? []+ const dataItems = analysis?.data ?? []++ const installedMap = new Map(manager.installed.map(p => [p.id, p.version]))+ const dataItemMap = new Map(dataItems.map(item => [item.kind, item]))+ // 已装列表没到位时不能渲染勾选:`installedMap` 为空会让每个插件都像「未装」而默认勾上+ const analyzing = isLoading || manager.loading+ // 提交还要求分析结果确实到手:后台刷新 / 刷新失败时缓存里的旧选择不能拿来对新来源提交+ const analysisReady = analysis !== undefined && error === null && !isFetching++ /** 有迁移价值:同名插件未装、档案数据未被当前档案完全包含 */+ function pluginMigratable(entry: MigrationEntry): boolean {+ return !installedMap.has(entry.id)+ }++ function dataMigratable(kind: MigrationDataKind): boolean {+ const item = dataItemMap.get(kind)+ return item !== undefined && !item.covered+ }++ /** 勾选状态:不可迁移的一律不选;用户显式切换过的一律以用户为准 */+ function pluginPicked(entry: MigrationEntry): boolean {+ return pluginMigratable(entry) && (pluginOverrides[entry.id] ?? true)+ }++ /** 凭据可能含敏感信息,默认不勾选 */+ function dataPicked(kind: MigrationDataKind): boolean {+ return dataMigratable(kind) && (dataOverrides[kind] ?? kind !== 'credentials')+ }++ const pickedPlugins = plugins.filter(pluginPicked)+ const pickedData = DATA_ORDER.filter(dataPicked)+ const hasCandidate = plugins.some(pluginMigratable) || DATA_ORDER.some(dataMigratable)++ // 5. 使用 useMutation 封装迁移提交流程+ const { mutate: handleMigrate, isPending: busy } = useMutation({+ mutationFn: async () => {+ const specs = pickedPlugins.map(entry => entry.spec)+ const kinds = pickedData++ // 阶段 A: 迁移档案数据+ let appliedCount = 0+ let failedKinds: MigrationDataKind[] = []+ if (kinds.length > 0) {+ const report = await invoke<MigrateReport>('migrate_profile_data', {+ sourceId: pickedSourceId,+ items: kinds,+ })+ appliedCount = report.applied.length+ failedKinds = report.failures.map(failure => failure.kind)+ }++ // 阶段 B: 安装插件+ let failed = 0+ if (specs.length > 0) {+ const results = await manager.install(specs)+ failed = results.filter(result => !result.ok).length+ }++ return { appliedCount, failedKinds, specCount: specs.length, failedCount: failed }+ },+ onSuccess: ({ appliedCount, failedKinds, specCount, failedCount }) => {+ void queryClient.invalidateQueries({ queryKey: queryKeys.plugins })++ if (failedKinds.length > 0) {+ const detail = failedKinds+ .map(kind => t(DATA_LABEL_KEYS[kind], { count: dataItemMap.get(kind)?.count ?? '0' }))+ .join('、')+ toast(t('profiles.migrate_partial'), { variant: 'danger', description: detail })+ }+ if (failedCount > 0) {+ toast(t('profiles.migrate_plugin_failed', { count: failedCount }), { variant: 'danger' })+ }+ // 装了插件的那一半由插件管理器的结果气泡负责提示,这里只在纯数据迁移时补一条+ else if (specCount === 0 && appliedCount > 0) {+ toast(t('profiles.migrate_success', { count: appliedCount }), { variant: 'accent' })+ }+ disclosure.confirm()+ },+ onError: (err) => {+ console.error('[ProfileMigrateDialog] migrate failed:', err)+ toast(t('profiles.migrate_failed'), { variant: 'danger', description: String(err) })+ },+ })++ const canSubmit = !busy && !analyzing && analysisReady && Boolean(pickedSourceId) && (pickedPlugins.length > 0 || pickedData.length > 0)++ return (+ <AlertDialog onOpenChange={disclosure.cancel} isOpen={disclosure.visible}>+ <AlertDialog.Backdrop>+ <AlertDialog.Container>+ <AlertDialog.Dialog className="sm:max-w-[560px]">+ <AlertDialog.CloseTrigger />+ <AlertDialog.Header>+ <AlertDialog.Icon status="accent" />+ <AlertDialog.Heading>{t('profiles.migrate_title')}</AlertDialog.Heading>+ </AlertDialog.Header>+ <AlertDialog.Body className="space-y-4">+ <p className="text-xs leading-[1.7] text-muted">{t('profiles.migrate_desc')}</p>++ {/* 源档案与目标档案选择 */}+ <div className="flex justify-between items-center gap-3">+ <Select+ variant="secondary"+ className="flex-1"+ selectedKey={pickedSourceId}+ onSelectionChange={(key) => {+ // 勾选按插件 id / 数据类目记账,两个来源可以同名:换来源必须清空,+ // 否则上一个来源里勾过的凭据会直接套用到新来源。+ setPickedSourceId(String(key))+ setPluginOverrides({})+ setDataOverrides({})+ }}+ isDisabled={busy}+ aria-label={t('profiles.migrate_source')}+ placeholder={t('profiles.migrate_source')}+ >+ <Select.Trigger>+ <Select.Value />+ <Select.Indicator />+ </Select.Trigger>+ <Select.Popover>+ <ListBox>+ {sources.map(profile => (+ <ListBox.Item id={profile.id} key={profile.id} textValue={profile.name}>+ {profile.name}+ </ListBox.Item>+ ))}+ </ListBox>+ </Select.Popover>+ </Select>++ <ArrowRight className="size-4 shrink-0 text-muted" />++ <div className="flex-1">+ <InputGroup fullWidth variant="secondary" className="relative">+ <InputGroup.Input disabled className="min-w-0" value={target?.name ?? ''} />+ <InputGroup.Suffix className="absolute right-0">+ <Chip color="success" variant="soft">{coreVersion}</Chip>+ </InputGroup.Suffix>+ </InputGroup>+ </div>+ </div>++ {/* 迁移分析结果 */}+ <If+ cond={pickedSourceId}+ else={(+ <p className="py-4 text-sm text-muted">+ {sources.length > 0 ? t('profiles.migrate_pick_source') : t('profiles.migrate_no_source')}+ </p>+ )}+ >+ <If cond={analyzing}>+ <div className="flex justify-center p-6">+ <Spinner aria-label={t('profiles.migrate_analyzing')} />+ </div>+ </If>+ <If cond={!analyzing && error !== null}>+ <p className="p-4 text-sm text-danger">{t('profiles.migrate_analyze_failed')}</p>+ </If>+ <If cond={!analyzing && error === null && !hasCandidate}>+ <p className="py-4 text-sm text-muted">{t('profiles.migrate_nothing')}</p>+ </If>+ <If cond={!analyzing && error === null && hasCandidate}>+ <Tabs defaultSelectedKey="plugins" variant="primary">+ <Tabs.ListContainer>+ <Tabs.List aria-label={t('profiles.migrate_title')}>+ <Tabs.Tab id="plugins" className="h-7 px-3 text-xs">+ {t('profiles.migrate_tab_plugins', { count: plugins.length })}+ <Tabs.Indicator />+ </Tabs.Tab>+ <Tabs.Tab id="data" className="h-7 px-3 text-xs">+ {t('profiles.migrate_tab_data')}+ <Tabs.Indicator />+ </Tabs.Tab>+ </Tabs.List>+ </Tabs.ListContainer>++ {/* 插件列表面板 */}+ <Tabs.Panel id="plugins">+ <If+ cond={plugins.length === 0}+ then={<p className="py-4 text-sm text-muted">{t('profiles.migrate_plugins_empty')}</p>}+ else={plugins.map((entry) => {+ const currentVersion = installedMap.get(entry.id)+ const installed = !pluginMigratable(entry)+ const chip = VERDICT_CHIPS[entry.verdict]+ const chipText = entry.targetVersion ? t(chip.key, { version: entry.targetVersion }) : t(chip.key)++ return (+ <div key={entry.id} className="flex justify-between items-center py-1.5">+ <Checkbox+ isSelected={pluginPicked(entry)}+ isDisabled={busy || installed}+ onChange={(value: boolean) => setPluginOverrides(prev => ({ ...prev, [entry.id]: value }))}+ aria-label={entry.id}+ className="shrink-0"+ >+ <Checkbox.Content>+ <Checkbox.Control>+ <Checkbox.Indicator />+ </Checkbox.Control>+ <span className="min-w-0 flex-1 truncate font-mono text-[12.5px] text-ink">+ {entry.id}+ @+ {entry.version}+ </span>+ </Checkbox.Content>+ </Checkbox>++ <div className="flex items-center gap-2">+ <If cond={installed}>+ <Chip size="sm" variant="soft">+ {t('profiles.migrate_installed', { version: currentVersion ?? '' })}+ </Chip>+ </If>++ <If cond={!installed}>+ <If+ cond={entry.targetVersion !== undefined}+ then={(+ <Chip size="sm" color={chip.color} variant="soft" aria-label={chipText}>+ <If+ cond={entry.verdict === 'upgrade'}+ then={<ArrowUp className="size-2.5" />}+ else={<ArrowDown className="size-2.5" />}+ />+ {entry.targetVersion}+ </Chip>+ )}+ else={(+ <Chip size="sm" color={chip.color} variant="soft">+ {chipText}+ </Chip>+ )}+ />+ </If>+ </div>+ </div>+ )+ })}+ />+ </Tabs.Panel>++ {/* 档案数据面板 */}+ <Tabs.Panel id="data">+ {DATA_ORDER.map((kind) => {+ const item = dataItemMap.get(kind)+ const hasItem = item !== undefined+ const covered = item?.covered ?? false+ const labelText = t(DATA_LABEL_KEYS[kind], { count: item?.count ?? '0' })++ return (+ <div key={kind} className="flex items-center justify-between py-1.5">+ <Checkbox+ isSelected={dataPicked(kind)}+ isDisabled={busy || !dataMigratable(kind)}+ onChange={(value: boolean) => setDataOverrides(prev => ({ ...prev, [kind]: value }))}+ aria-label={kind}+ >+ <Checkbox.Content>+ <Checkbox.Control>+ <Checkbox.Indicator />+ </Checkbox.Control>+ <span className="text-[12.5px]">+ {DATA_FILES[kind]}+ </span>+ <If cond={!hasItem}>+ <span className="text-xs text-muted">{t('profiles.migrate_data_absent')}</span>+ </If>+ </Checkbox.Content>+ </Checkbox>++ <div className="flex items-center gap-2">+ <span className="text-xs text-muted">{labelText}</span>+ <If cond={covered}>+ <span className="text-xs text-muted">{t('profiles.migrate_data_covered')}</span>+ </If>+ <If cond={kind === 'credentials'}>+ <Chip size="sm" color="danger" variant="soft">+ {t('profiles.migrate_credentials_badge')}+ </Chip>+ </If>+ </div>+ </div>+ )+ })}+ </Tabs.Panel>+ </Tabs>+ </If>+ </If>+ </AlertDialog.Body>++ <AlertDialog.Footer className="justify-end">+ <div className="flex flex-row items-center gap-2">+ <Button variant="tertiary" isDisabled={busy} onPress={disclosure.cancel}>+ {t('buttons.cancel')}+ </Button>+ <Button variant="primary" isDisabled={!canSubmit} onPress={() => handleMigrate()}>+ <If cond={busy} then={<Spinner size="sm" color="current" />} />+ <If cond={busy} then={<span>{t('profiles.migrate_busy')}</span>} else={<span>{t('profiles.migrate_confirm')}</span>} />+ </Button>+ </div>+ </AlertDialog.Footer>+ </AlertDialog.Dialog>+ </AlertDialog.Container>+ </AlertDialog.Backdrop>+ </AlertDialog>+ )+}diff --git a/test/plugin-manager-settle.test.ts b/test/plugin-manager-settle.test.tsindex 0ca20ec4..e2f1784d 100644--- a/test/plugin-manager-settle.test.ts+++ b/test/plugin-manager-settle.test.ts@@ -40,31 +40,19 @@ beforeEach(() => {})describe('plugins manager settle', () => {- it('asks before restarting instead of restarting a succeeding group on its own', async () => {+ it('settles without offering a restart: the host hot-reloads plugins itself', async () => {invoke.mockResolvedValue(undefined)const results = await plugins.enqueue('install', ['a', 'b'], { toast: true, restartOnSettle: true })expect(results.every(result => result.ok)).toBe(true)expect(restart).not.toHaveBeenCalled()- const prompt = toast.mock.calls.find(call => call[1]?.actionProps !== undefined)- expect(prompt?.[1]?.timeout).toBe(0)- prompt?.[1]?.actionProps?.onPress?.()- expect(toast.close).toHaveBeenCalled()- expect(restart).toHaveBeenCalledTimes(1)- })-- it('folds the restart button into the single result toast instead of adding a second one', async () => {- invoke.mockResolvedValue(undefined)-- await plugins.enqueue('install', ['a'], { toast: true, restartOnSettle: true })-- const toasts = toast.mock.calls.filter(call => call[1]?.isLoading !== true)- expect(toasts).toHaveLength(1)- expect(toasts[0][1]?.timeout).toBe(0)- toasts[0][1]?.actionProps?.onPress?.()- expect(toast.close).toHaveBeenCalled()- expect(restart).toHaveBeenCalledTimes(1)+ // 队列自己热更新插件,结果气泡里不能再挂「重启」按钮,也不能常驻(timeout: 0);+ // 进度气泡(isLoading)本来就是常驻的,只检查结果气泡。+ const resultToasts = toast.mock.calls.filter(call => call[1]?.isLoading !== true)+ expect(resultToasts.length).toBeGreaterThan(0)+ expect(resultToasts.every(call => call[1]?.actionProps === undefined)).toBe(true)+ expect(resultToasts.every(call => call[1]?.timeout !== 0)).toBe(true)})it('leaves the harness running when restartOnSettle is disabled', async () => {diff --git a/test/plugin-manager-summary.test.ts b/test/plugin-manager-summary.test.tsindex 20bf852f..34a0d929 100644--- a/test/plugin-manager-summary.test.ts+++ b/test/plugin-manager-summary.test.ts@@ -73,10 +73,10 @@ describe('plugins manager queue summary', () => {expect(toasts).toHaveLength(1)expect(toasts[0][0]).toBe('Plugin operations finished')expect(toasts[0][1]?.description).toBe('3 succeeded')- expect(toasts[0][1]?.timeout).toBe(0)- toasts[0][1]?.actionProps?.onPress?.()- expect(toast.close).toHaveBeenCalled()- expect(restart).toHaveBeenCalledTimes(1)+ // 队列自己热更新插件:汇总气泡不再常驻、也不再挂「重启」按钮+ expect(toasts[0][1]?.timeout).toBeUndefined()+ expect(toasts[0][1]?.actionProps).toBeUndefined()+ expect(restart).not.toHaveBeenCalled()expect(plugins.queueResults).toEqual([])})diff --git a/test/plugin-manager-upgrade-attribution.test.ts b/test/plugin-manager-upgrade-attribution.test.tsindex 88f52063..c9478a31 100644--- a/test/plugin-manager-upgrade-attribution.test.ts+++ b/test/plugin-manager-upgrade-attribution.test.ts@@ -130,7 +130,7 @@ describe('plugins manager upgrade attribution', () => {])})- it('keeps the restart entry for the target that landed despite the general error', async () => {+ it('reports the landed target without a restart entry despite the general error', async () => {invoke.mockImplementation(async (command: string) => {if (command === 'update_dsh_plugins')throw failureError([{ name: 'bbb', message: NETWORK_MESSAGE }])@@ -145,10 +145,9 @@ describe('plugins manager upgrade attribution', () => {])const toasts = resultToasts()expect(toasts).toHaveLength(1)- expect(toasts[0][1]?.timeout).toBe(0)- expect(toasts[0][1]?.actionProps?.children).toBe('Restart')- toasts[0][1]?.actionProps?.onPress?.()- expect(restart).toHaveBeenCalledTimes(1)+ expect(toasts[0][1]?.timeout).toBeUndefined()+ expect(toasts[0][1]?.actionProps).toBeUndefined()+ expect(restart).not.toHaveBeenCalled()})it('attributes a failure inside a batch that also holds an authorised target', async () => {diff --git a/test/plugin-uninstall.test.ts b/test/plugin-uninstall.test.tsindex adce842f..056da2f4 100644--- a/test/plugin-uninstall.test.ts+++ b/test/plugin-uninstall.test.ts@@ -89,7 +89,7 @@ describe('configPlugin preset chip', () => {})})-// ── Suite C — uninstall routes through the manager + settles with one restart ──+// ── Suite C — uninstall routes through the manager + settles without a restart prompt ──describe('configPlugin uninstall flow', () => {it('routes uninstall through the manager batch command', () => {const panel = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')@@ -100,12 +100,12 @@ describe('configPlugin uninstall flow', () => {expect(store).toContain('remove_dsh_plugins')})- it('restarts the service once when the group settles', () => {+ it('settles results without offering a restart', () => {const store = readFileSync(new URL('../src/store/modules/plugins/store.ts', import.meta.url), 'utf8')- // 重启权收口到组结算:面板不再为卸载单独重启- expect(store).toContain('group.options.restartOnSettle')- expect(store).toContain('harness.restart()')+ // 队列自己热更新插件:结果气泡不挂「重启」按钮,也不再让气泡常驻+ expect(store).not.toContain('restartAction')+ expect(store).not.toContain('actionProps: restart')})it('shows a confirm dialog before uninstall', () => {