DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(插件管理器): 插件变更统一收口至 Store 与 useDshPluginsManager (#787)
Mao Mr776db6bd2e97
diff --git a/docs/todos/use-plugins-manager.md b/docs/todos/use-plugins-manager.mddeleted file mode 100644index 630f9280..00000000--- a/docs/todos/use-plugins-manager.md+++ /dev/null@@ -1,450 +0,0 @@-根据您提供的规范文档,以下是遵循您的四项核心优化准则(性能优化、结构简化、可读性增强、逻辑等价性保障)后输出的**代码/文档优化方案**。-------## 优化后文档--# 壳插件安装管理器 `use-plugins-manager` 规范--> **状态**:待实现(TODO)-> **需求来源**:用户需求「壳插件安装重构:新增 use-plugins-manager」(接口详见 §三)-> **上游规范**:[devlopment.md](https://www.google.com/search?q=../specs/devlopment.md)(壳层通用)→ [desktop.baisc.md](https://www.google.com/search?q=../specs/desktop.baisc.md)(运行环境)→ [testing.md](https://www.google.com/search?q=../specs/testing.md)(测试质量)-> **冲突裁决**:`plugin.client.md` / `plugin.client.panel.md` / `plugin.host.service.md` 仅约束 `packages/*/src/{client,host}`,**不约束壳层 `src/**`;壳层 Store 允许 async action(既有先例:`preinstall`、`recovery` Store),但必须严格满足 SSOT(单一真实数据源)与「无模块级可变状态」。-------## 一、目标与边界--### 1.1 核心目标--1. **统一收口**:壳层所有改变「已安装插件集合/启用状态」的操作(安装、升级、卸载、禁用、启用、授权),收口至管理器 Store 及唯一 React 门面 `useDshPluginsManager`。-2. **队列与执行语义**:-* **组间**:按独立 API 调用排队,**严格串行**执行。-* **组内**:一次 API 调用为一个「组」。安装/升级/卸载在组内合并为**一次宿主 CLI 调用(单次 pnpm)**;禁用/启用由于宿主无批量语义,组内并发提交并由宿主自行排队。-* **粒度**:每个插件在代码层面独立追踪进程状态、失败归因与授权状态。---3. **提示权收口**:管理器是唯一执行者与提示者(仅当 `toast: true` 时);`toast: false`(如预装引导页)时,管理器仅暴露状态供调用方自行渲染。-4. **就地授权与续传**:DSH 精确版本豁免与 pnpm 发布保护期豁免在管理器内部就地完成;被拒插件不阻塞同组其他插件,授权或拒绝后将其余**剩余集合**重新提交(§五.6)。--### 1.2 边界声明(明确不做)--| 功能模块 | 现有实现落点 | 不并入管理器的理由 |-| --- | --- | --- |-| **快照与恢复** | `src/ui/config/plugin.tsx`, `src/ui/plugin/recovery.tsx` | 属于系统恢复能力,非安装/启用时序 |-| **内置插件自愈** | `src/store/modules/harness/store.ts` → Rust `internal/mod.rs` | 属于后台幂等自愈(`EnsureCoordinator`),无需用户交互队列 |-| **运行期错误上报** | `src/layout/components/iframe.tsx` | 仅涉及只读错误日志上报 |-| **远程机器插件同步** | `packages/dsh-tauri-ssh/src/host/service/plugins-sync.ts` | 走 Node/SSH Wire 传输,不经过 Tauri 命令 |-| **核心市场 UI** | 核心包 `@deepseek-ai/dsh-plugin-manager` | 仅复用其「安装前检查」逻辑,不接管其 UI 组件 |--> **范围补充**:**禁用/启用** 纳入本次重构。其作为插件加载状态迁移,与安装共享同一个队列、进程状态、授权暂停以及「组结算统一重启一次」语义(§八.5)。-------## 二、现状问题与收敛对照--| # | 现状模式 | 存在缺陷 | 优化后机制 |-| --- | --- | --- | --- |-| **1** | `install_preinstall_plugins` 批量安装 | 单插件被拒导致整批失败且无法精细归因 | 保留「整批单次 pnpm」提高效率,失败时精细归因至具体进程,支持重新提交剩余集合 |-| **2** | 授权 UI 重复实现 | `setup-preinstall.tsx` 与 `plugin.tsx` 存在两套交互与文案 | 由管理器统一收口,集中处理 Toast 提示与授权响应 |-| **3** | 授权命令重复调用 | 两处不同模块分别调用后端同一对授权命令 | 收口至 `manager.approve` 统一处理 |-| **4** | Busy 状态分散 | `plugin.tsx` busy、`preinstall` 状态与 `recovery.busy` 互相独立 | 统一收口至管理器单一队列与 `PluginProcessStatus` 状态机 |-| **5** | 插件列表重复查询 | 3 处 UI 组件各自独立维护 `get_dsh_plugins` 逻辑 | 统一通过 `manager.installed` 进行集中数据投影 |-| **6** | 服务重启高频触发 | 各操作独立调用 `store.harness.restart()`,导致多次无谓重启 | 组结算后统一评估并执行**一次**重启 |-| **7** | 工具函数反向依赖 | `parseBlockedRefusal` 挂在预装模块,导致面板反向依赖 | 迁移至 `src/store/modules/plugins/utils.ts` |-| **8** | 引导逻辑重复 | 两处入口分散处理「打开预设引导」 | 统一收口为 `preinstall.open()` |-| **9** | 面板缺乏安装入口 | 无法在面板直接输入 Spec 安装新插件 | 新增标准的插件安装与兼容性检查入口 |-| **10** | 禁用/启用路径孤立 | 禁用/启用操作独立 Reboot、独立 Busy | 并入管理器队列,统一调度与确认流 |-------## 三、对外契约(TypeScript 类型与 API)--类型定义文件位于 `src/store/modules/plugins/types.ts`。--### 3.1 类型定义--```ts-/** 已安装插件视图(由宿主 DshPlugin 投影转化) */-export interface Plugin {- id: string- name: string- version: string- description: string- repoUrl: string- bundled: boolean- disabled: boolean- patchDisabled: boolean- recommended: boolean- fix: boolean- internal: boolean- hasSnapshot: boolean- error: PluginErrorInfo | null- /** 最新可升级版本;无更新探测缓存时为 null */- latest: string | null- updateAvailable: boolean- /** 已装版本对当前核心的兼容性 */- incompatible: boolean- /** 最新版本对当前核心的兼容性 */- latestIncompatible: boolean-}--/** 插件引用表达:纯 Spec 字符串,或结构化对象 */-export type PluginRef = string | { spec: string; version?: string }--export type PluginProcessType = 'install' | 'upgrade' | 'uninstall' | 'disable' | 'enable'--export type PluginProcessStatus = 'pending' | 'running' | 'unauthorized'--export interface PluginProcess {- /** 同组内唯标识:`${groupId}#${index}` */- id: string- groupId: string- type: PluginProcessType- status: PluginProcessStatus- /** 归一化后的提交 Spec */- spec: string- /** 展示名称 */- name: string- /** 显式指定的版本 */- version?: string- /** 被宿主拦截时的原始拒绝载荷 */- refusal?: BlockedRefusal- /** 进度 Toast 句柄 */- progressKey?: string- /** 授权 Toast 句柄 */- approvalKey?: string-}--export interface PluginProcessResult {- process: PluginProcess- ok: boolean- error?: string- code?: string- reason?: 'not-installed' | 'already-absent' | 'update-hold' | 'rejected' | 'cancelled' | 'retry-exhausted'-}--export interface PluginManagerLog {- at: number- level: 'info' | 'error'- message: string- groupId?: string- processId?: string-}--export interface PluginSearchResult {- spec: string- name?: string- version?: string- compatible: boolean | null- peers?: Record<string, string>- problem?: 'invalid-spec' | 'not-found' | 'network' | 'unsupported' | 'unknown'-}--```--### 3.2 API 契约与使用规范--```ts-const manager = useDshPluginsManager({ toast: true, restartOnSettle: true })--```--#### 成员属性与方法列表--| 成员/方法 | 类型/签名 | 说明 |-| --- | --- | --- |-| `installed` | `Plugin[]` | 当前已安装插件的视图列表 |-| `processes` | `PluginProcess[]` | 当前正在运行或排队中的未终结进程 |-| `pendingApprovals` | `PluginProcess[]` | 等待用户授权的进程 (`status === 'unauthorized'`) |-| `logs` | `PluginManagerLog[]` | 全局日志时间线(最多保留 200 条) |-| `install` | `(refs: PluginRef | PluginRef[]) => Promise<PluginProcessResult[]>` | 提交安装组。传入数组时合并为一次 pnpm 命令 |-| `upgrade` | `(refs: PluginRef | PluginRef[]) => Promise<PluginProcessResult[]>` | 提交升级组 |-| `uninstall` | `(refs: PluginRef | PluginRef[]) => Promise<PluginProcessResult[]>` | 提交卸载组 |-| `disable` | `(refs: PluginRef | PluginRef[]) => Promise<PluginProcessResult[]>` | 提交禁用组(组内并发执行) |-| `enable` | `(refs, options?: { clearConfigOverride?: boolean }) => Promise<PluginProcessResult[]>` | 提交启用组 |-| `approve` | `(refs?: PluginRef | PluginRef[]) => Promise<PluginProcessResult[]>` | 授权并重试;若参数为空,则授权当前所有待授权进程 |-| `reject` | `(ref: PluginRef) => Promise<PluginProcessResult[]>` | 拒绝授权(等价于关闭授权弹窗) |-| `cancel` | `() => Promise<void>` | 取消当前活动组的执行 |-| `search` | `(refs: PluginRef | PluginRef[], options?: { dsh?: string }) => Promise<PluginSearchResult[]>` | 查询插件与当前核心的兼容性 |-| `on` | `(event: ManagerEvent, cb: Function) => () => void` | 订阅管理器事件(返回取消订阅回调) |--#### 通用准则--1. **统一返回数组**:写操作方法均返回 `Promise<PluginProcessResult[]>`。除了非法参数输入会直接 throw 外,内部执行失败均通过 `ok: false` 表达,**绝不抛出 Unhandled Rejection**。-2. **Resolve 时机**:返回的 Promise 在**整个任务组结算完成**(组内全部进程达到终态)后 Resolve。-3. **Ref 归一化规范**:-* `'aaa'` $\rightarrow$ `{ spec: 'aaa', name: 'aaa' }`-* `'aaa@^1.2.0'` $\rightarrow$ `{ spec: 'aaa@^1.2.0', name: 'aaa' }`-* `{ spec: 'aaa', version: '1.2.3' }` $\rightarrow$ `{ spec: '[email protected]', name: 'aaa', version: '1.2.3' }`(`version` 覆盖 spec 内既有范围)-* Scoped 包名(如 `'@scope/[email protected]'`):仅按**末尾** `@` 进行切分。---4. **事件总线**:基于 `createEventHook` 暴露 `completed`、`allcompleted`、`error`、`approve` 事件,提供轻量解耦的状态监听能力。-------## 四、内部状态数据结构--核心逻辑位于 `src/store/modules/plugins/` 目录下。--```ts-interface PluginGroup {- id: string- type: PluginProcessType- status: 'pending' | 'active' | 'settled'- processIds: string[]- /** 重试尝试次数,上限 8 次 */- attempt: number- /** 本次实际提交给宿主的 Spec/ID 集合 */- pending: string[]- /** 组结算最终结果 */- results: PluginProcessResult[]- resume?: () => void- done: Promise<PluginProcessResult[]>- resolveDone: (results: PluginProcessResult[]) => void-}--// Store State 接口-interface PluginsState {- groups: PluginGroup[]- processes: PluginProcess[]- logs: PluginManagerLog[]- activeGroupId: string | null- cancelling: boolean- presenterCount: number-}--```-------## 五、队列、并发与状态流转--### 5.1 队列调度机制--```- [API 触发] ──► 归一化 Ref ──► 创建 PluginGroup ──► 入队 groups ──► 触发 drain()- │-┌──────────────────────────────────────────────────────────────────────┘-▼-评估 activeGroupId:- ├─► 若已有活动组 ──► 保持等待 (Pending)- └─► 若无活动组 ──► 标记组为 Active ──► 组内提交宿主 ──► 状态流转 ──► 组结算 ──► 取下一组--```--### 5.2 组内批处理策略--```- ┌───► pnpm 方式: 合并为单次 CLI 命令提交 (install/upgrade/uninstall)-[组内进程集合] ───────┤- └───► 并发方式: Promise.allSettled 并发调用 (disable/enable)--```--* **批处理**:安装/升级/卸载直接将多个 Spec 拼接为一次 `dsh plugin add/update/remove` 调用,利用底层 pnpm 自身并行能力,不通过 `for await` 逐项串行。-* **并发处理**:禁用与启用由于宿主命令仅支持单 ID,前端通过 `Promise.allSettled` 并发分发,由宿主进程锁自动排队。--### 5.3 进程状态流转--```- ┌─────────────────── (提交宿主) ───────────────────┐- │ │- ▼ │- ┌────────────────────────┐ ┌─────────────────┐- │ status: pending │ │ status: running │- └────────────────────────┘ └────────┬────────┘- ▲ │- │ (授权重试) │ (宿主响应)- │ ▼- ┌────────────────────────┐ ┌─────────────────┐- │ status: unauthorized │◄─── (需要用户授权 / 拦截) ────┤ 结果处理/归因 ├─► 成功/其他失败 ─► [终结并移出]- └────────────┬───────────┘ └─────────────────┘- │- └─── (拒绝 / 取消) ───────────────────────────────────────────────────► [终结并移出]--```--1. **提交阶段**:组发起时,组内所有进程同步由 `pending` 切换至 `running`。-2. **拦截归因**:-* 宿主返回授权拦截码(如 `PLUGIN_VERSION_INCOMPATIBLE`)时,通过 `parseBlockedRefusal` 匹配目标进程。-* 匹配成功的进程切换为 `unauthorized` 并挂载 `refusal` 载荷;同组其他未被拦截的进程**重置回 `pending**`。-* 隐藏当前组的加载 Toast,暂停队列推进,等待用户决策。---3. **重新提交剩余集合**:-* 授权(`approve`)或拒绝(`reject`)后,剔除已终结或已授权项,提取**剩余待执行集合**,再次作为单次 CLI 命令重新提交。----### 5.4 组结算与服务重启--当组内全部进程达到终态(成功、失败或拒绝)后:--1. **统一重启**:若组内发生了实际变更(至少 1 项成功)且 `restartOnSettle === true`,触发**一次** `store.harness.restart()`。-2. **事件分发**:触发 `completed` 与 `error`(若存在失败项)事件。-3. **清理与推进**:移除当前 `PluginGroup`,重置 `activeGroupId` 为 `null`,并递归调用 `drain()` 推进下一队列组。若队列为空,触发 `allcompleted`。-------## 六、授权与拒绝处理--### 6.1 授权流程--```-[收到 unauthorized 状态]- │- ├─► 渲染常驻 Toast (timeout: 0, 带有 "授权" 按钮)- │- ▼-[用户点击 "授权"]- │- ├─► 执行 manager.approve(process)- ├─► 调用宿主 allow_* 接口写入豁免配置- ├─► 进程状态恢复为 pending- └─► 重新提交当前组的剩余集合 (attempt + 1)--```--### 6.2 拒绝流程--```-[用户点击关闭 Toast (x)]- │- ├─► 触发 Toast onClose (Reason: 'dismissed')- ├─► 自动触发 manager.reject(process)- ├─► 进程移出队列,标记状态为 ok: false, reason: 'rejected'- └─► 若组内仍有剩余项 ──► 立即将剩余集合重新提交宿主--```-------## 七、Toast UI 状态映射--管理器的 Toast 采用**声明式状态投影**,在 `presenterCount > 0` 时生效:--```- ┌─── n = 1 : 显示 "正在安装 {{name}}..."- │-┌─── 组正在运行 (n 个进程) ────┼─── n >= 2: 显示 "正在安装 {{count}} 个插件..."-│ │-│ └─── 存在 unauthorized: 隐蔽加载 Toast,避免界面干扰-│-├─── 进程授权等待 ─────────────► 为每个待授权项弹出独立的常驻 Toast (timeout: 0)-│-└─── 组结算完成 ───────────────► 依次触发结果 Toast,多项失败时追加汇总 Toast--```--> ** Toast 基础类库扩展要求**:`src/utils/toast.ts` 的 `onClose` 回调必须扩展 `reason` 参数(`'closed'` | `'evicted'` | `'dismissed'`),仅当为 `'dismissed'`(用户主动关闭)时触发 `reject` 逻辑。-------## 八、宿主侧接口改动 (Rust / Tauri Bridge)--### 8.1 接口变更明细表--| 命令 (Command) | 参数类型 | 返回类型 | 修改说明 |-| --- | --- | --- | --- |-| `install_plugin_specs` | `specs: Vec<String>` | `Result<(), String>` | **新增**:支持传入多个 Spec,合并为单次 `dsh plugin add` 执行 |-| `update_dsh_plugins` | `ids: Vec<String>` | `Result<(), String>` | **变更**:替代原 `update_dsh_plugin`,支持批量更新 |-| `remove_dsh_plugins` | `ids: Vec<String>` | `Result<(), String>` | **变更**:替代原 `remove_dsh_plugin`,支持批量移除 |-| `inspect_plugin_specs` | `specs: Vec<String>, dsh: Option<String>` | `Result<Vec<PluginInspect>, String>` | **新增**:只读检查 Spec 兼容性,不改动本地 Profile |-| `cancel_plugin_processes` | 无 | `Result<(), String>` | **重命名**:由 `cancel_preinstall_plugins` 重命名,提升为通用方法 |--### 8.2 核心兼容性模块 (`src-tauri/src/service/plugin/compat.rs`)--新增 Rust 模块,负责解析与校验 DSH 核心 Peer 依赖:--* 提取插件声明中的 `@deepseek-ai/dsh` 相关 peerDependencies。-* 使用 `semver` crate 执行匹配校验。若解析过程发生异常,遵循 **Fail-Open(默认视作兼容)** 原则,避免阻断正常流程。-------## 九、架构落地路径--### 9.1 文件组织结构--```-src/-├── store/-│ └── modules/-│ └── plugins/-│ ├── index.ts # 集中导出桶文件 (Barrel)-│ ├── store.ts # Pinia/Store 逻辑实现-│ ├── types.ts # 类型定义-│ ├── utils.ts # Ref 归一化、解析与辅助纯函数-│ └── events.ts # 基于 createEventHook 的事件定义-└── hooks/- └── use-plugins-manager.ts # React 封装门面 Hook--```--### 9.2 数据流向图--```-宿主事件 / React Query (queryKeys.plugins)- │- ▼- DshPlugin 原生数据列表- │- ▼- enrichInstalled() 数据转换- │- ▼- manager.installed 视图--```-------## 十、实施阶段规划--```-[P0 基座构建] ──► [P1 Store & Hook 实现] ──► [P2 配置面板收口] ──► [P3 新增安装入口] ──► [P4 预装引导页收口] ──► [P5 垃圾清理]--```--1. **P0 基座**:完成 Rust 命令改造、兼容性校验模块编写与 Toast 原因透传扩展。-2. **P1 管理器**:实现 `src/store/modules/plugins/` 状态机与 `useDshPluginsManager`。-3. **P2 面板收口**:重构 `plugin.tsx` 面板,使其全部切至管理器 API。-4. **P3 新增安装入口**:基于 `manager.search` 与 `manager.install` 构建面板安装交互 UI。-5. **P4 引导页收口**:改造预装页,配置 `useDshPluginsManager({ toast: false, restartOnSettle: false })` 模式。-6. **P5 清理**:移除废弃代码与冗余错误码。-------## 十一、自动化测试覆盖要求--### 11.1 前端单元测试 (Vitest)--新建并完善以下测试用例:--1. `test/plugin-manager-queue.test.ts`-* 验证组间串行执行顺序。-* 验证 `install(['a', 'b'])` 是否严格触发**单次**宿主调用。-* 验证禁用/启用操作在组内的**并发**分发。---2. `test/plugin-manager-approve.test.ts`-* 验证捕获拒绝载荷后的归因定位,以及未受影响进程恢复为 `pending`。-* 验证 `approve` 后仅将剩余集合重新提交宿主。-* 验证关闭 Toast 触发 `reject` 后自动从剩余集合中剔除对应项。---3. `test/plugin-manager-settle.test.ts`-* 验证组结算时 `restartOnSettle` 对重启调用的触发逻辑。---4. `test/plugin-manager-api.test.ts`-* 验证 Ref 归一化纯函数的边界输入。-* 验证幂等性判断(如卸载未安装插件返回 `already-absent`)。----### 11.2 后端单元测试 (Cargo Test)--1. `src-tauri/src/service/plugin/compat.rs`-* 覆盖 Workspace 语法解析、预发布版本匹配、非法 Range 兼容性降级及合并 `dependencies` 与 `peerDependencies` 的断言测试。\ No newline at end of filediff --git a/src-tauri/resources/manifest.jsonc b/src-tauri/resources/manifest.jsoncindex 7b492a2c..90c164b8 100644--- a/src-tauri/resources/manifest.jsonc+++ b/src-tauri/resources/manifest.jsonc@@ -176,7 +176,7 @@"version": [{ "version": "^0.19.1", "dsh": "^0.1.5-rc.1" },{ "version": "^0.21.1", "dsh": "^0.1.7-rc.1" },- { "version": "^0.24.1", "dsh": "^0.2.0-rc.1" }+ { "version": "latest", "dsh": "^0.2.0-rc.1" }]},{@@ -190,7 +190,7 @@"version": [{ "version": "^0.12.2", "dsh": "^0.1.5-rc.1" },{ "version": "^0.14.0", "dsh": "^0.1.7-rc.1" },- { "version": "^0.14.0", "dsh": "^0.2.0-rc.1" }+ { "version": "latest", "dsh": "^0.2.0-rc.1" }]},{@@ -218,7 +218,7 @@"version": [{ "version": "^4.25.0", "dsh": "^0.1.5-rc.1" },{ "version": "^4.29.0", "dsh": "^0.1.7-rc.1" },- { "version": "^4.30.0", "dsh": "^0.2.0-rc.1" }+ { "version": "latest", "dsh": "^0.2.0-rc.1" }]},{diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rsindex 8295d586..1ec65a53 100644--- a/src-tauri/src/bridge/plugin.rs+++ b/src-tauri/src/bridge/plugin.rs@@ -43,13 +43,15 @@ pub async fn install_preinstall_plugins(// 先卸载取消勾选的已安装插件(走 dsh plugin remove,与安装对称)// 卸载在前:避免新装插件与待卸载插件冲突;remove 内部会先停服务再执行log::info!("[preinstall] uninstall_ids={uninstall_ids:?}, install_ids={install_ids:?}");- for id in &uninstall_ids {- log::info!("[preinstall] removing plugin {id} via dsh plugin remove");- if let Err(e) = plugin::remove(&app_handle, id).await {- log::error!("[preinstall] failed to remove plugin {id}: {e}");- return Err(e);- }- log::info!("[preinstall] successfully removed plugin {id}");+ if !uninstall_ids.is_empty() {+ log::info!("[preinstall] removing plugins {uninstall_ids:?} via dsh plugin remove");+ plugin::remove_many(&app_handle, &uninstall_ids)+ .await+ .map_err(|e| {+ log::error!("[preinstall] failed to remove plugins {uninstall_ids:?}: {e}");+ e+ })?;+ log::info!("[preinstall] successfully removed plugins {uninstall_ids:?}");}// 再安装新勾选的插件(会走 dsh plugin add)@@ -67,12 +69,35 @@ pub async fn install_preinstall_plugins(Ok(())}-/// 取消正在进行的预装插件安装(网络抖动/限流卡住时用户点“取消”)。+/// 取消正在进行的插件进程(安装/升级/卸载,网络抖动/限流卡住时用户点“取消”)。#[tauri::command]-pub async fn cancel_preinstall_plugins(app_handle: AppHandle) {+pub async fn cancel_plugin_processes(app_handle: AppHandle) {plugin::cancel(&app_handle).await;}+/// 按原始 spec 安装插件(插件市场 / 手动输入 entry):支持一次传入多个 spec,+/// 合并为单次 `dsh plugin add` 执行,输出同样经 `preinstall-log` 事件推送。+///+/// 与 `install_preinstall_plugins` 的区别只在 spec 来源:此处不走预设清单,+/// 因而没有捆绑目录与版本矩阵,spec 原样交给 pnpm 解析。+#[tauri::command]+pub async fn install_plugin_specs(app_handle: AppHandle, specs: Vec<String>) -> Result<(), String> {+ plugin::install_specs(&app_handle, &specs).await?;+ plugin::watch::force_emit(&app_handle);+ Ok(())+}++/// 只读检查一组 spec 的兼容性(registry `latest` 上的 DSH 家族 peer 依赖),+/// 不改动本地 profile;失败项收敛为结果里的 `problem`,不整体报错。+#[tauri::command]+pub async fn inspect_plugin_specs(+ app_handle: AppHandle,+ specs: Vec<String>,+ dsh: Option<String>,+) -> Result<Vec<plugin::compat::PluginInspect>, String> {+ plugin::inspect_specs(&app_handle, &specs, dsh).await+}+/// 授予「插件版本豁免」:为被核心版本兼容性拒绝的精确 `包名@版本` 组合写授权。////// 前端在风险提示中让用户逐项确认后调用(授权项来自 `install_preinstall_plugins`@@ -169,20 +194,25 @@ pub async fn refresh_plugin_updates(plugin::update::refresh(&app_handle).await}-/// 升级单个已安装插件:`dsh plugin --profile <当前档案> update <id>`,-/// 进程输出通过 `preinstall-log` 事件实时推送。+/// 批量升级已安装插件:`dsh plugin --profile <当前档案> update <id...> --latest`,+/// 合并为单次子进程执行,输出通过 `preinstall-log` 事件实时推送;升级前逐项+/// 记录依赖指纹,命令返回后核验是否真实落盘(防 pnpm 假成功)。+///+/// `ids` 的每一项是 `<id>` 或 `<id>@<版本>`(保留参数名以免改动前端载荷键):面板显示着+/// 目标版本,带上它核验与显式安装兜底才有据可依(见 `plugin::update_many`)。#[tauri::command]-pub async fn update_dsh_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {- plugin::update(&app_handle, &id).await?;+pub async fn update_dsh_plugins(app_handle: AppHandle, ids: Vec<String>) -> Result<(), String> {+ plugin::update_many(&app_handle, &ids).await?;plugin::watch::force_emit(&app_handle);Ok(())}-/// 卸载单个已安装插件:`dsh plugin --profile <当前档案> remove <id>`,-/// 进程输出通过 `preinstall-log` 事件实时推送。+/// 批量卸载已安装插件:`dsh plugin --profile <当前档案> remove <ids...>`,+/// 合并为单次子进程执行,输出通过 `preinstall-log` 事件实时推送;命令后逐项核验,+/// 仍残留且可行动的插件回退离线精准卸载(不依赖网络)。#[tauri::command]-pub async fn remove_dsh_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {- plugin::remove(&app_handle, &id).await?;+pub async fn remove_dsh_plugins(app_handle: AppHandle, ids: Vec<String>) -> Result<(), String> {+ plugin::remove_many(&app_handle, &ids).await?;plugin::watch::force_emit(&app_handle);Ok(())}@@ -228,7 +258,7 @@ pub fn detect_plugin_recovery(/// 修复模式卸载单个插件:直接改 profile 清单(离线、精准),成功后推送新插件列表。///-/// 与 `remove_dsh_plugin`(走 `dsh plugin remove`)不同,此命令不依赖网络,专用于+/// 与 `remove_dsh_plugins`(走 `dsh plugin remove`)不同,此命令不依赖网络,专用于/// 「插件异常修复」场景;前端随后 `restart()` 重启并重新检测。#[tauri::command]pub fn recover_plugin(app_handle: AppHandle, id: String) -> Result<(), String> {diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 46fce8b1..b616b1c8 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -1066,7 +1066,9 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::get_preinstall_plugins,crate::bridge::get_preinstall_pending,crate::bridge::install_preinstall_plugins,- crate::bridge::cancel_preinstall_plugins,+ crate::bridge::install_plugin_specs,+ crate::bridge::inspect_plugin_specs,+ crate::bridge::cancel_plugin_processes,crate::bridge::allow_plugin_versions,crate::bridge::allow_plugin_policy_versions,crate::bridge::skip_preinstall_plugins,@@ -1075,8 +1077,8 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::open_preinstall_repo,crate::bridge::get_dsh_plugins,crate::bridge::refresh_plugin_updates,- crate::bridge::update_dsh_plugin,- crate::bridge::remove_dsh_plugin,+ crate::bridge::update_dsh_plugins,+ crate::bridge::remove_dsh_plugins,crate::bridge::disable_dsh_plugin,crate::bridge::enable_dsh_plugin,crate::bridge::snapshot_plugin,diff --git a/src-tauri/src/service/plugin/cancel.rs b/src-tauri/src/service/plugin/cancel.rsindex 753bdb6d..621bded7 100644--- a/src-tauri/src/service/plugin/cancel.rs+++ b/src-tauri/src/service/plugin/cancel.rs@@ -35,7 +35,7 @@ pub(crate) async fn terminate_active_install() -> bool {/// 退出前同步回收所有进行中的插件安装进程树(`RunEvent::Exit` 调用)。////// 安装子进程以独立进程组启动(`process_group(0)`),父进程退出**不会**连带结束-/// 它们;而取消只由前端命令(`cancel_preinstall_plugins` / `cancel_internal_plugins`)+/// 它们;而取消只由前端命令(`cancel_plugin_processes` / `cancel_internal_plugins`)/// 触发。用户在安装看起来毫无进展时关窗,留下的孤儿会继续占着档案与 pnpm store,/// 下一次启动的安装便排在它后面——表现为永久卡在「Loading internal plugins…」且/// 后端日志一行输出都没有。回收必须在退出路径上显式做。diff --git a/src-tauri/src/service/plugin/compat.rs b/src-tauri/src/service/plugin/compat.rsnew file mode 100644index 00000000..3fd20b57--- /dev/null+++ b/src-tauri/src/service/plugin/compat.rs@@ -0,0 +1,266 @@+//! DSH 核心 Peer 依赖兼容性判定:从插件清单提取 `@deepseek-ai/dsh` 家族的+//! 依赖区间,用 semver 校验是否匹配当前运行时核心版本。任何解析异常一律+//! Fail-Open(视作兼容),避免判定失败反过来阻断正常安装。++use semver::{Comparator, Op, Version, VersionReq};+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;++/// DSH 核心包名;`@deepseek-ai/dsh-*` 子包同属一个运行时家族。+pub const DSH_PACKAGE: &str = "@deepseek-ai/dsh";++/// 只读检查结果:与前端 `PluginSearchResult` 同形(camelCase,可选字段省略)。+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PluginInspect {+ pub spec: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub version: Option<String>,+ pub compatible: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub peers: Option<BTreeMap<String, String>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub problem: Option<String>,+}++pub fn is_dsh_package(name: &str) -> bool {+ name == DSH_PACKAGE || name.starts_with("@deepseek-ai/dsh-")+}++/// 剥离声明协议前缀:`workspace:` / `catalog:` 等区间写法不是合法 semver,+/// 空值与 `*`/`^`/`~` 之类的无区间声明一律视为「无从判定」。+fn protocol_value(raw: &str) -> Option<&str> {+ let trimmed = raw.trim();+ if trimmed.is_empty() {+ return None;+ }+ for prefix in ["workspace:", "catalog:", "portal:", "link:", "file:"] {+ if let Some(rest) = trimmed.strip_prefix(prefix) {+ let rest = rest.trim();+ if rest.is_empty() || matches!(rest, "*" | "^" | "~") {+ return None;+ }+ return Some(rest);+ }+ }+ Some(trimmed)+}++/// 合并 `dependencies` 与 `peerDependencies` 中的 DSH 家族依赖;+/// peer 声明后处理,同名时覆盖 dependencies 的写法。+pub fn peers_from_manifest(manifest: &serde_json::Value) -> BTreeMap<String, String> {+ let mut peers = BTreeMap::new();+ for section in ["dependencies", "peerDependencies"] {+ let Some(map) = manifest.get(section).and_then(serde_json::Value::as_object) else {+ continue;+ };+ for (name, raw) in map {+ if !is_dsh_package(name) {+ continue;+ }+ let Some(raw) = raw.as_str() else {+ continue;+ };+ let Some(value) = protocol_value(raw) else {+ continue;+ };+ peers.insert(name.clone(), value.to_string());+ }+ }+ peers+}++/// 区间是否命中给定版本——对齐内核安装校验的 `includePrerelease` 语义。+///+/// `semver` crate 对预发布版本另设门槛:必须存在比较符与本版本 major.minor.patch+/// 相同且自带 pre。`^0.1.7-rc.1` 因此漏掉 `0.1.8-rc.1` 这类同代更高补丁号的+/// 预发布核心,补一个对本版本恒真的精确比较符即可绕开门槛。+fn matches_including_prerelease(req: &VersionReq, version: &Version) -> bool {+ let matched = req.matches(version);+ if matched || version.pre.is_empty() {+ return matched;+ }+ let mut bridged = req.clone();+ bridged.comparators.push(Comparator {+ op: Op::Exact,+ major: version.major,+ minor: Some(version.minor),+ patch: Some(version.patch),+ pre: version.pre.clone(),+ });+ bridged.matches(version)+}++/// 把 npm 习惯的空格分隔比较符(`>=1.2.3 <2.0.0`)归一到 `semver` crate+/// 接受的逗号分隔形式;无法归一或为空时返回 None。+fn normalize_range(raw: &str) -> Option<String> {+ let mut parts: Vec<String> = Vec::new();+ let mut pending: Option<String> = None;+ for token in raw.split_whitespace() {+ let token = token.trim_matches(',').trim();+ if token.is_empty() {+ continue;+ }+ if matches!(token, ">" | ">=" | "<" | "<=" | "=" | "^" | "~") {+ pending = Some(token.to_string());+ continue;+ }+ match pending.take() {+ Some(op) => parts.push(format!("{op}{token}")),+ None => match Version::parse(token.trim_start_matches('v')) {+ Ok(version) => parts.push(format!("={version}")),+ Err(_) => parts.push(token.to_string()),+ },+ }+ }+ if pending.is_some() || parts.is_empty() {+ return None;+ }+ Some(parts.join(","))+}++/// 单个区间声明是否命中运行时版本。+///+/// 返回 `None` 表示无从判定(区间或运行时版本无法解析),调用方按 Fail-Open 处理;+/// `||` 分隔的备选区间任一命中即为兼容。+pub fn range_matches(raw: &str, runtime: &str) -> Option<bool> {+ let range = protocol_value(raw)?;+ let version = Version::parse(runtime.trim()).ok()?;+ let mut parsed_any = false;+ for alternative in range.split("||") {+ let Some(normalized) = normalize_range(alternative) else {+ continue;+ };+ let Ok(req) = VersionReq::parse(&normalized) else {+ continue;+ };+ parsed_any = true;+ if matches_including_prerelease(&req, &version) {+ return Some(true);+ }+ }+ if parsed_any {+ Some(false)+ } else {+ None+ }+}++/// 全量判定:无 DSH 家族依赖时返回 `None`(无从判定),否则任一声明明确不命中+/// 即不兼容;无法解析的声明一律按兼容放行。+pub fn evaluate(peers: &BTreeMap<String, String>, runtime: &str) -> Option<bool> {+ if peers.is_empty() {+ return None;+ }+ for raw in peers.values() {+ if range_matches(raw, runtime) == Some(false) {+ return Some(false);+ }+ }+ Some(true)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn peers(entries: &[(&str, &str)]) -> BTreeMap<String, String> {+ entries+ .iter()+ .map(|(name, raw)| (name.to_string(), raw.to_string()))+ .collect()+ }++ #[test]+ fn workspace_protocol_is_normalized_before_parsing() {+ assert_eq!(range_matches("workspace:^0.2.0", "0.2.1"), Some(true));+ assert_eq!(range_matches("workspace:^0.2.0", "0.3.0"), Some(false));+ assert_eq!(range_matches("catalog:^0.2.0", "0.2.5"), Some(true));+ assert_eq!(+ range_matches("workspace:>=0.1.7-rc.1 <0.1.7-rc.5", "0.1.7-rc.3"),+ Some(true)+ );+ }++ #[test]+ fn prerelease_versions_match_across_patch_bumps() {+ assert_eq!(range_matches("^0.1.7-rc.1", "0.1.7-rc.2"), Some(true));+ assert_eq!(range_matches("^0.1.7-rc.1", "0.1.8-rc.1"), Some(true));+ assert_eq!(range_matches("^0.2.0-rc.1", "0.2.1-rc.1"), Some(true));+ assert_eq!(range_matches("^0.1.7", "0.1.7-rc.1"), Some(false));+ }++ #[test]+ fn bare_versions_are_exact_like_npm() {+ assert_eq!(range_matches("0.2.0", "0.2.0"), Some(true));+ assert_eq!(range_matches("0.2.0", "0.2.5"), Some(false));+ assert_eq!(range_matches("0.2.0", "0.3.0"), Some(false));+ assert_eq!(range_matches("=0.2.0", "0.2.5"), Some(false));+ assert_eq!(range_matches(">=0.2.0 <0.3.0", "0.2.5"), Some(true));+ assert_eq!(range_matches("^0.2.0", "0.2.5"), Some(true));+ }++ #[test]+ fn invalid_range_degrades_to_unknown_and_stays_compatible() {+ assert_eq!(range_matches("not a range", "0.2.0"), None);+ assert_eq!(range_matches(">>>1.0.0", "0.2.0"), None);+ assert_eq!(range_matches("", "0.2.0"), None);+ assert_eq!(range_matches("^1.0.0", "not-a-version"), None);+ assert_eq!(evaluate(&peers(&[("@deepseek-ai/dsh", "garbage")]), "0.2.0"), Some(true));+ }++ #[test]+ fn alternatives_and_space_separated_comparators_are_supported() {+ assert_eq!(range_matches("^1.0.0 || ^0.2.0", "0.2.3"), Some(true));+ assert_eq!(range_matches("^1.0.0 || ^0.3.0", "0.2.3"), Some(false));+ assert_eq!(range_matches(">=0.1.0 <0.3.0", "0.2.0"), Some(true));+ }++ #[test]+ fn manifest_merges_dependencies_and_peer_dependencies_of_the_dsh_family() {+ let manifest = json!({+ "dependencies": {+ "@deepseek-ai/dsh-fs": "^0.1.0",+ "@deepseek-ai/dsh-llm": "^0.1.0",+ "dshmarket": "^1.0.0",+ "@deepseek-ai/other": "^1.0.0"+ },+ "peerDependencies": {+ "@deepseek-ai/dsh-llm": "^0.1.7-rc.1",+ "@deepseek-ai/dsh": "^0.2.0"+ }+ });+ let merged = peers_from_manifest(&manifest);+ assert_eq!(merged.len(), 3);+ assert_eq!(merged.get("@deepseek-ai/dsh-llm").map(String::as_str), Some("^0.1.7-rc.1"));+ assert_eq!(merged.get("@deepseek-ai/dsh-fs").map(String::as_str), Some("^0.1.0"));+ assert_eq!(merged.get("@deepseek-ai/dsh").map(String::as_str), Some("^0.2.0"));+ assert!(!merged.contains_key("dshmarket"));+ assert!(!merged.contains_key("@deepseek-ai/other"));+ assert!(is_dsh_package("@deepseek-ai/dsh"));+ assert!(is_dsh_package("@deepseek-ai/dsh-llm"));+ assert!(!is_dsh_package("@deepseek-ai/dshx"));+ }++ #[test]+ fn evaluate_reports_unknown_without_family_peers() {+ assert_eq!(evaluate(&BTreeMap::new(), "0.2.0"), None);+ assert_eq!(+ evaluate(&peers(&[("@deepseek-ai/dsh", "^0.2.0")]), "0.2.0-rc.1"),+ Some(false)+ );+ assert_eq!(+ evaluate(+ &peers(&[+ ("@deepseek-ai/dsh", "^0.2.0"),+ ("@deepseek-ai/dsh-llm", "^0.2.0-rc.1"),+ ]),+ "0.2.0"+ ),+ Some(true)+ );+ }+}diff --git a/src-tauri/src/service/plugin/install/artifact.rs b/src-tauri/src/service/plugin/install/artifact.rsindex 0b1ffb39..acfc014a 100644--- a/src-tauri/src/service/plugin/install/artifact.rs+++ b/src-tauri/src/service/plugin/install/artifact.rs@@ -14,29 +14,29 @@ use super::errors;use super::installed_name;use super::load_presets;use super::profile_dir;-use super::PreinstallPluginInfo;+use super::InstallTarget;use super::{new_process_owner, run_plugin_process, PreinstallLogPayload, PREINSTALL_LOG_EVENT};pub(super) fn verify_installed_products(app_handle: &AppHandle,- ids: &[String],- preset_map: &HashMap<&str, &PreinstallPluginInfo>,+ targets: &[InstallTarget],command_output: &str,) -> Result<(), String> {let node_modules = profile_dir(app_handle).join("node_modules");let mut missing = Vec::new();- for id in ids {- let Some(preset) = preset_map.get(id.as_str()) else {+ for target in targets {+ // 无法静态得知包名的 spec(git / 任意 URL)跳过核验:把整条 spec 当目录名会+ // 制造必然失败的误报(见 [`super::spec::package_name_of_spec`])。+ let Some(name) = target.name.as_deref() else {continue;};- let name = installed_name(preset);let manifest = node_modules.join(name).join("package.json");if manifest.is_file() {- if let Err(e) = errors::clear(app_handle, id) {- log::warn!("failed to clear plugin error for {id}: {e}");+ if let Err(e) = errors::clear(app_handle, &target.id) {+ log::warn!("failed to clear plugin error for {}: {e}", target.id);}} else {- missing.push((id.clone(), manifest));+ missing.push((target.id.clone(), manifest));}}if missing.is_empty() {diff --git a/src-tauri/src/service/plugin/install/inspect.rs b/src-tauri/src/service/plugin/install/inspect.rsnew file mode 100644index 00000000..c83bfdca--- /dev/null+++ b/src-tauri/src/service/plugin/install/inspect.rs@@ -0,0 +1,122 @@+//! 插件 spec 兼容性只读检查:解析包名与声明的版本 → 读 npm registry 对应清单 →+//! 提取 `@deepseek-ai/dsh` 家族依赖 → 用 [`crate::service::plugin::compat`] 判定+//! 是否匹配运行时核心版本。全程不落盘、不起子进程,供插件市场在安装前提示。++use std::time::Duration;++use semver::Version;+use tauri::AppHandle;++use crate::service::plugin::compat::{self, PluginInspect};+use crate::service::plugin::update::encode_registry_name;++use super::spec;++/// registry 请求超时:与更新探测一致,只读检查不该拖住安装前交互。+const INSPECT_TIMEOUT: Duration = Duration::from_secs(10);++/// 逐条检查 spec;单条检查的任何异常都收敛为该条的 `problem`,不影响其余条目+/// (Fail-Open:判定失败不等于不兼容)。+pub async fn inspect_specs(+ app_handle: &AppHandle,+ specs: &[String],+ dsh: Option<String>,+) -> Result<Vec<PluginInspect>, String> {+ let runtime = dsh+ .map(|value| value.trim().to_string())+ .filter(|value| !value.is_empty())+ .or_else(|| crate::service::core::active_version(app_handle));+ let client = reqwest::Client::builder()+ .timeout(INSPECT_TIMEOUT)+ .build()+ .map_err(|e| format!("INSPECT_CLIENT: {e}"))?;++ let mut results = Vec::with_capacity(specs.len());+ for raw in specs {+ results.push(inspect_one(&client, raw, runtime.as_deref()).await);+ }+ Ok(results)+}++/// 单条 spec:静态解析不出包名(git / 本地路径 / 非法写法)时不做网络请求。+async fn inspect_one(client: &reqwest::Client, spec: &str, runtime: Option<&str>) -> PluginInspect {+ let raw = spec.trim();+ let Some(name) = spec::package_name_of_spec(raw) else {+ return problem_result(raw, None, "invalid-spec");+ };++ let requested = requested_version(raw, &name);+ let exact = requested+ .as_deref()+ .filter(|value| Version::parse(value).is_ok());+ let target = exact.unwrap_or("latest");+ let url = format!(+ "https://registry.npmjs.org/{}/{}",+ encode_registry_name(&name),+ target+ );+ let response = match client+ .get(&url)+ .header("accept", "application/json")+ .header("user-agent", "deepseek-harness-desktop")+ .send()+ .await+ {+ Ok(response) => response,+ Err(_) => return problem_result(raw, Some(name), "network"),+ };+ // 404 是确定性的「包不存在」,其余非 2xx 都按网络问题处理。+ if !response.status().is_success() {+ let problem = if response.status() == reqwest::StatusCode::NOT_FOUND {+ "not-found"+ } else {+ "network"+ };+ return problem_result(raw, Some(name), problem);+ }+ let Ok(manifest) = response.json::<serde_json::Value>().await else {+ return problem_result(raw, Some(name), "network");+ };++ let version = manifest+ .get("version")+ .and_then(serde_json::Value::as_str)+ .map(String::from);+ let peers = compat::peers_from_manifest(&manifest);+ // 区间(`^1.2.0` / `>=1 <2`)暂不做版本解析:此时读的是 latest 清单,+ // 拿它的依赖去判定会误伤「用旧版本规避新版不兼容」的标准做法,故放行。+ let compatible = if requested.is_some() && exact.is_none() {+ None+ } else {+ runtime.and_then(|runtime| compat::evaluate(&peers, runtime))+ };+ PluginInspect {+ spec: raw.to_string(),+ name: Some(name),+ version,+ compatible,+ peers: (!peers.is_empty()).then_some(peers),+ problem: None,+ }+}++/// spec 里在包名之后显式声明的版本片段(`[email protected]` / `@scope/aaa@^1.0.0`)。+fn requested_version(raw: &str, name: &str) -> Option<String> {+ raw.strip_prefix(name)+ .and_then(|rest| rest.strip_prefix('@'))+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(String::from)+}++/// 出错条目:保留已解析到的包名便于前端展示,兼容性留空(Fail-Open)。+fn problem_result(spec: &str, name: Option<String>, problem: &str) -> PluginInspect {+ PluginInspect {+ spec: spec.to_string(),+ name,+ version: None,+ compatible: None,+ peers: None,+ problem: Some(problem.to_string()),+ }+}diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rsindex b767c06e..a37d8d09 100644--- a/src-tauri/src/service/plugin/install/mod.rs+++ b/src-tauri/src/service/plugin/install/mod.rs@@ -21,10 +21,11 @@//! 并就地补构建缺失的声明入口(见 [`artifact::ensure_plugin_entry_built`])。//!//! 模块划分(`install/`):-//! - [`self`]:安装编排入口(install / install_internal)与 allowBuilds 重试循环-//! - [`single`]:单插件升级/卸载(`dsh plugin update/remove`,卸载后核验 + 离线兜底、+//! - [`self`]:安装编排入口(install / install_specs / install_internal)与 allowBuilds 重试循环+//! - [`single`]:批量升级/卸载(`dsh plugin update/remove`,卸载后核验 + 离线兜底、//! 弃用插件自动卸载)-//! - [`spec`]:安装 spec 准备(内置插件捆绑目录、GitHub 简写规范化、Windows 引号)+//! - [`spec`]:安装 spec 准备(内置插件捆绑目录、GitHub 简写规范化、Windows 引号、包名解析)+//! - [`inspect`]:安装前只读兼容性检查(registry `latest` + DSH 家族 peer 判定)//! - [`env`]:`dsh plugin` 子进程环境($DSH_HOME 隔离、git HTTPS 强制)//! - [`pnpm`]:pnpm 选版与版本探测(store 主版本感知、捆绑版补齐、有界 probe 监控)//! - [`allowlist`]:构建放行白名单解析与 pnpm-workspace.yaml 写回@@ -35,7 +36,6 @@ use crate::config;use crate::service::cli;use crate::service::core;use crate::service::profile::{active_profile, allow_profile_release_age};-use crate::service::workflow;use std::collections::HashMap;use std::ffi::OsString;use std::path::Path;@@ -60,6 +60,7 @@ mod allowlist;mod artifact;mod diagnose;mod env;+mod inspect;mod pnpm;mod single;mod spec;@@ -70,7 +71,8 @@ pub(crate) use pnpm::{bundled_pnpm_major, harness_prefer_bundled_pnpm, pnpm_major_version_at, profile_store_major,};pub(crate) use single::uninstall_deprecated_plugins;-pub use single::{remove, update};+pub use inspect::inspect_specs;+pub use single::{remove_many, update_many};// 版本兼容性/发布时长两类拦截的解析结果都要跨到 `bridge`(前端逐项确认后授权),在此定义出口pub use diagnose::{IncompatibleVersion, PolicyBlockedVersion};@@ -128,8 +130,18 @@ fn policy_verification_retry_delay(retry: usize) -> std::time::Duration {std::time::Duration::from_secs(seconds)}+/// 一次安装操作的目标:`id` 是稳定标识(错误记录 / 快照 / bundles 对账),+/// `name` 是 `node_modules` 下的目录名(产物核验与入口补构建用,无法解析时为+/// `None`,此时跳过这两步),`spec` 是最终交给 `dsh plugin add` 的参数。+pub(crate) struct InstallTarget {+ pub id: String,+ pub name: Option<String>,+ pub spec: String,+}+pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), String> {- install_with_cancel(app_handle, ids, None, new_process_owner()).await+ let targets = preset_targets(app_handle, ids)?;+ install_with_cancel(app_handle, &targets, None, new_process_owner()).await}/// 内置插件启动自愈专用入口:取消信号会阻止被结束的 pnpm/dsh 进程再次进入@@ -140,15 +152,39 @@ pub(crate) async fn install_internal(cancel: tokio::sync::watch::Receiver<bool>,owner: ProcessOwner,) -> Result<(), String> {- install_with_cancel(app_handle, ids, Some(cancel), owner).await+ let targets = preset_targets(app_handle, ids)?;+ install_with_cancel(app_handle, &targets, Some(cancel), owner).await}-async fn install_with_cancel(- app_handle: &AppHandle,- ids: &[String],- cancel: Option<tokio::sync::watch::Receiver<bool>>,- owner: ProcessOwner,-) -> Result<(), String> {+/// 按原始 spec 安装(插件市场 / 手动输入):与预装路径共用同一套编排,只是目标+/// 不再来自预设清单,因而没有捆绑目录与版本矩阵——spec 原样交给 pnpm 解析。+pub async fn install_specs(app_handle: &AppHandle, specs: &[String]) -> Result<(), String> {+ let targets = spec_targets(app_handle, specs);+ if targets.is_empty() {+ return Err("PLUGIN_SPECS_EMPTY: no plugin specs provided".to_string());+ }+ install_with_cancel(app_handle, &targets, None, new_process_owner()).await+}++/// 预设 id → 安装目标:解析捆绑目录与清单 spec,规范化为 `git+https://`。+///+/// 内置插件改为从随包分发的捆绑目录安装(`link:` 本地联接依赖,见+/// preset::bundled_dep_spec;不用 `file:`——pnpm 对盘符冒号的绝对路径会当相对+/// 路径解析),其余沿用清单声明的 spec;随后统一把 `github:user/repo` 规范为显式+/// `git+https://...`,绕开 pnpm 对 GitHub 简写「HTTPS 探测失败即回退 SSH」的已知+/// 缺陷(pnpm issue #3948 / #7243 / #13276):公开仓库一旦落进 git+ssh,在没有+/// SSH 配置的桌面机上必然 `Host key verification failed` / `Permission denied+/// (publickey)`。+///+/// 最后按活动核心决定是否为含空格的 spec 加内嵌双引号:0.1.6-alpha.2 起 dsh CLI+/// 改用 execa 以 argv 数组启动 pnpm,参数不再经 shell 拼接,预加引号只会让 pnpm+/// 收到带字面引号的 spec(issue #647);更早的核心在 win32 用 `shell:true` 把参数+/// 拼成命令行(Node 只拼接、不转义,DEP0190),含空格的内置插件路径+/// (`link:<应用安装目录>`)不预加引号就会被切碎成多个 spec,pnpm 报+/// `ERR_PNPM_SPEC_NOT_SUPPORTED`、启动自愈每轮重装(死循环)。两种形态落盘+/// `package.json` 的值都是不带引号的 `link:<路径>`,与内核对账的 `expected`+/// (bundled_dep_spec)一致(见 [`spec_argument`])。+fn preset_targets(app_handle: &AppHandle, ids: &[String]) -> Result<Vec<InstallTarget>, String> {if ids.is_empty() {return Err("PREINSTALL_EMPTY: no plugins selected".to_string());}@@ -157,45 +193,136 @@ async fn install_with_cancel(let presets = load_presets(app_handle);let preset_map: HashMap<&str, &PreinstallPluginInfo> =presets.iter().map(|p| (p.id.as_str(), p)).collect();-- let mut specs = Vec::with_capacity(ids.len());- let mut needs_git = false;- // 是否给含空格的 spec 预加引号取决于活动核心的 `dsh plugin` 实现(见- // [`spec_argument`]):0.1.6-alpha.2 起 pnpm 由 argv 数组启动,预加引号会变成- // spec 的一部分(issue #647)。let core_version = crate::service::core::active_version(app_handle);++ let mut targets = Vec::with_capacity(ids.len());for id in ids {let preset = preset_map.get(id.as_str()).ok_or_else(|| format!("PREINSTALL_INVALID_ID: {id}"))?;- // 内置插件改为从随包分发的捆绑目录安装(`link:` 本地联接依赖,见- // preset::bundled_dep_spec;不用 `file:`——pnpm 对盘符冒号的绝对路径- // 会当相对路径解析),其余沿用清单声明的 spec;随后统一把- // `github:user/repo` 规范为显式 `git+https://...`,绕开 pnpm 对- // GitHub 简写「HTTPS 探测失败即回退 SSH」的已知缺陷(pnpm issue- // #3948 / #7243 / #13276):公开仓库一旦落进 git+ssh,在没有 SSH 配置- // 的桌面机上必然 `Host key verification failed` / `Permission denied (publickey)`。- //- // 最后按活动核心决定是否为含空格的 spec 加内嵌双引号:0.1.6-alpha.2 起- // dsh CLI 改用 execa 以 argv 数组启动 pnpm,参数不再经 shell 拼接,预加引号- // 只会让 pnpm 收到带字面引号的 spec(issue #647);更早的核心在 win32 用- // `shell:true` 把参数拼成命令行(Node 只拼接、不转义,DEP0190),含空格的- // 内置插件路径(`link:<应用安装目录>`)不预加引号就会被切碎成多个 spec,- // pnpm 报 `ERR_PNPM_SPEC_NOT_SUPPORTED`、启动自愈每轮重装(死循环)。两种- // 形态落盘 `package.json` 的值都是不带引号的 `link:<路径>`,与内核- // 对账的 `expected`(bundled_dep_spec)一致(见 [`spec_argument`])。let raw = normalize_git_spec(&preset_spec_for_install(preset,bundled_dir_of(app_handle, preset),core_version.as_deref(),)?);- // 规范化后 `git+...` 前缀即 git 托管依赖:pnpm 安装时需要实际可用的 git- // (见下方预检);npm 包名(如 `dshmarket`)与 `link:` 本地依赖无需 git。- if raw.starts_with("git+") {- needs_git = true;+ targets.push(InstallTarget {+ id: preset.id.clone(),+ name: Some(installed_name(preset).to_string()),+ spec: spec_argument(&raw, core_version.as_deref()),+ });+ }+ Ok(targets)+}++/// 原始 spec → 安装目标:`link:`/`file:` 读目标包名(读不到回落目录名),npm 形态+/// 剥离版本后缀,git / URL 形态无法静态得知包名,回落 spec 本身并放弃产物核验。+///+/// 命中资源清单的 spec 走 [`preset_targets`] 同一套解析:同一条目无论从预装引导页+/// (预设 id)还是从面板 / 市场(原始 spec)进入,都必须解析出相同的安装目标——内置+/// 插件的捆绑 `link:` 目录与清单版本矩阵只能在这一侧得到。解析失败(内置插件缺+/// 捆绑产物,属发布缺陷)时退回裸 spec,让 pnpm 报出真实原因而不是静默跳过该条目。+fn spec_targets(app_handle: &AppHandle, specs: &[String]) -> Vec<InstallTarget> {+ let core_version = crate::service::core::active_version(app_handle);+ let presets = load_presets(app_handle);+ let mut targets = Vec::with_capacity(specs.len());+ for spec in specs {+ let spec = spec.trim();+ if spec.is_empty() {+ continue;+ }+ if let Some(preset) = presets+ .iter()+ .find(|preset| preset.id == spec || preset.spec == spec)+ {+ if let Ok(raw) = preset_spec_for_install(+ preset,+ bundled_dir_of(app_handle, preset),+ core_version.as_deref(),+ ) {+ targets.push(InstallTarget {+ id: preset.id.clone(),+ name: Some(installed_name(preset).to_string()),+ spec: spec_argument(&normalize_git_spec(&raw), core_version.as_deref()),+ });+ continue;+ }}- specs.push(spec_argument(&raw, core_version.as_deref()));+ let raw = normalize_git_spec(spec);+ let name = spec::package_name_of_spec(&raw);+ targets.push(InstallTarget {+ id: name.clone().unwrap_or_else(|| raw.clone()),+ name,+ spec: spec_argument(&raw, core_version.as_deref()),+ });}+ targets+}++/// 被门禁拦下的条目**全部**已在 lock 中时,返回该补写的豁免条目(精确 `包名@版本`)。+fn locked_release_age_exemptions(+ profile: &Path,+ blocked: &[PolicyBlockedVersion],+) -> Option<Vec<String>> {+ if blocked.is_empty() {+ return None;+ }+ let mut entries = Vec::with_capacity(blocked.len());+ for item in blocked {+ if single::locked_package_version(profile, &item.name).as_deref()+ != Some(item.version.as_str())+ {+ return None;+ }+ entries.push(format!("{}@{}", item.name, item.version));+ }+ Some(entries)+}++/// 这次失败是不是「lockfile 里早就有的太新条目又被门禁拦下」:是则补齐豁免并返回 `true`。+///+/// pnpm 的 `minimumReleaseAgeExclude` 只被**解析**阶段采信,lockfile 校验阶段照旧按窗口+/// 判定:一旦 lock 里存在比窗口更新的条目(用户授权后放宽窗口装上的那一次就会写入),+/// 此后**每一次**触发状态变更的插件操作都会失败——升级第二个插件卡在第一个插件的条目上,+/// 启动期的内置插件安装失败还会让应用起不来(`INTERNAL_PLUGIN_INSTALL_FAILED`)。+/// 已在 lock 里的版本说明它早就装到本机,不是本次要审的新版本:补进豁免清单(幂等)并让+/// 调用方放宽窗口重跑一次,把档案带回自洽状态。+///+/// 被拦下的条目里只要有一个不在 lock 中(或 lock 里是别的版本),说明那是本次新解析出来+/// 的版本:保持默认窗口、交前端走「逐项授权」,绝不放宽。+fn heal_locked_release_age(app_handle: &AppHandle, output: &str) -> bool {+ let blocked = policy_blocked_versions(output);+ let Some(entries) = locked_release_age_exemptions(&profile_dir(app_handle), &blocked) else {+ return false;+ };+ match allow_profile_release_age(app_handle, &entries) {+ Ok(()) => {+ log::warn!(+ "pnpm release-age policy blocked {} entries that are already locked; recorded them as exempt and retrying with the window relaxed",+ entries.len()+ );+ true+ }+ Err(error) => {+ log::warn!("failed to record the release-age exemptions for locked entries: {error}");+ false+ }+ }+}++async fn install_with_cancel(+ app_handle: &AppHandle,+ targets: &[InstallTarget],+ cancel: Option<tokio::sync::watch::Receiver<bool>>,+ owner: ProcessOwner,+) -> Result<(), String> {+ if targets.is_empty() {+ return Err("PREINSTALL_EMPTY: no plugins selected".to_string());+ }++ let specs: Vec<&str> = targets.iter().map(|t| t.spec.as_str()).collect();+ // 规范化后 `git+...` 前缀即 git 托管依赖:pnpm 安装时需要实际可用的 git+ // (见下方预检);npm 包名(如 `dshmarket`)与 `link:` 本地依赖无需 git。+ let needs_git = specs.iter().any(|s| s.starts_with("git+"));// git 托管插件安装前预检(issue #369):Linux/macOS 完全依赖系统 git(不在// 空白 Windows 自动配置范围,`config::git_runtime_ready` 非 Windows 恒真),@@ -236,35 +363,13 @@ async fn install_with_cancel(// 旧档案可能由早期版本创建,没有同步 Harness 的最小发布时间例外;补齐// 精确的已审查 zod 版本,避免 registry 元数据瞬时失败阻断插件安装(issue #222)。super::ensure_profile_pnpm_policy(app_handle)?;- // 安装前停止运行中的服务,避免资源冲突。- // 记录停服结果:停服失败意味着服务可能仍在运行、插件目录可能被写入,- // 此时创建快照会捕获不一致状态,因此停服失败时跳过快照(不终止安装)。- let mut stopped = true;- if workflow::has_owned_process() {- // 停服务会让用户感到"重启",先在日志面板讲清缘由(issue #48)- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: "[harness] 正在停止运行中的服务(安装插件需要短暂重启)…".to_string(),- },- );- log::info!("Stopping running harness service before installing plugins");- stopped = match workflow::stop(app_handle.clone()).await {- Ok(()) => true,- Err(e) => {- log::warn!("failed to stop harness before plugin install: {e}");- false- }- };- }- // 安装/升级前自动快照已安装的插件(覆盖式),失败仅告警不阻断安装。- // 仅在服务已确认停止后执行,保证快照一致+ // 安装/升级前自动快照已安装的插件(覆盖式),失败仅告警不阻断安装// (issue #303:自动快照失败不阻塞主流程,避免升级被陈旧快照问题拖垮)。- if stopped {- for id in ids {- if is_installed(app_handle, id) {- super::snapshot::create_best_effort(app_handle, id);- }+ // 这里**不再**为了快照停掉运行中的服务:插件包只会被随后的 pnpm 改写,先停服对+ // 快照一致性没有帮助,却让用户看到一次「服务被重启」;是否重启交给结算后的提示。+ for target in targets {+ if is_installed(app_handle, &target.id) {+ super::snapshot::create_best_effort(app_handle, &target.id);}}@@ -278,7 +383,7 @@ async fn install_with_cancel(OsString::from(active_profile(app_handle)),OsString::from("add"),];- args.extend(specs.iter().map(|s| OsString::from(s.as_str())));+ args.extend(specs.iter().map(OsString::from));let cwd = config::get_dsh_install_path(app_handle);// 日志打印实际传给 dsh 的 spec(此前打印 id 会误导排查:安装用的是 spec)@@ -302,6 +407,29 @@ async fn install_with_cancel().await?;+ // 门禁自愈:lockfile 里早有的太新条目会让**每一次**状态变更都失败+ // (见 [`heal_locked_release_age`])。补齐豁免后放宽窗口重跑一次,仍失败就照原样分类。+ let (exit_code, last_output, last_attempt) = if exit_code != 0+ && heal_locked_release_age(app_handle, &last_attempt)+ {+ let mut retry_args = args.clone();+ retry_args.push(OsString::from(single::RELEASE_AGE_RELAXED_FLAG));+ run_plugin_install_with_transient_retry(+ app_handle,+ &node,+ &retry_args,+ &cwd,+ &envs,+ &window,+ "install",+ cancel.as_ref(),+ owner,+ )+ .await?+ } else {+ (exit_code, last_output, last_attempt)+ };+if exit_code != 0 {log::error!("dsh plugin install failed with exit code {exit_code}");// 先无条件落一行 pnpm 原始诊断:后面的分类文案(网络 / store 指引)会丢掉细节,@@ -359,9 +487,9 @@ async fn install_with_cancel(};// 批量安装失败时给本次选中的每个插件记一条错误(前端据此展示异常标记,// 可针对单个插件重试更新/卸载)- for id in ids {- if let Err(e) = errors::record(app_handle, id, "install", &message) {- log::warn!("failed to record plugin error for {id}: {e}");+ for target in targets {+ if let Err(e) = errors::record(app_handle, &target.id, "install", &message) {+ log::warn!("failed to record plugin error for {}: {e}", target.id);}}if let Some(network_hint) = network_hint {@@ -412,7 +540,7 @@ async fn install_with_cancel(// 真正修复:核验本次安装是否真实落盘。pnpm 可能在 allowBuilds 阻断时仍以// exit 0 退出(假成功),若产物缺失则记录错误并返回 Err,让前端如实展示失败、// 允许重试,而不是误报「已安装」。已落盘的插件在上一步被核验并清除历史错误。- verify_installed_products(app_handle, ids, &preset_map, &last_output)?;+ verify_installed_products(app_handle, targets, &last_output)?;// 产物级核验:包已落盘但声明入口(如 `lib/index.js`)未构建时,本次安装// 同样是假成功——cordis 加载器在下一次启动必然 ERR_MODULE_NOT_FOUND 崩溃@@ -420,18 +548,18 @@ async fn install_with_cancel(// 静默进入下一次启动;包目录按预设的 `installed_name` 解析(scoped 插件// 与 id 不同名),失败跨插件聚合后一次性返回,前端可一并重试。let mut entry_errors = Vec::new();- for id in ids {- let Some(preset) = preset_map.get(id.as_str()) else {+ for target in targets {+ let Some(name) = target.name.as_deref() else {continue;};- let pkg_dir = profile_dir(app_handle)- .join("node_modules")- .join(installed_name(preset));- if let Err(e) = ensure_plugin_entry_built(app_handle, id, &pkg_dir, &envs, &window).await {- if let Err(err) = errors::record(app_handle, id, "install", &e) {- log::warn!("failed to record plugin error for {id}: {err}");+ let pkg_dir = profile_dir(app_handle).join("node_modules").join(name);+ if let Err(e) =+ ensure_plugin_entry_built(app_handle, &target.id, &pkg_dir, &envs, &window).await+ {+ if let Err(err) = errors::record(app_handle, &target.id, "install", &e) {+ log::warn!("failed to record plugin error for {}: {err}", target.id);}- entry_errors.push(format!("{id}: {e}"));+ entry_errors.push(format!("{}: {e}", target.id));}}if !entry_errors.is_empty() {@@ -445,11 +573,14 @@ async fn install_with_cancel(let _ = window.emit(PREINSTALL_LOG_EVENT,PreinstallLogPayload {- line: format!("[harness] 已安装 {} 个插件", ids.len()),+ line: format!("[harness] 已安装 {} 个插件", targets.len()),},);- log::info!("Preinstall plugins installed successfully: {ids:?}");+ log::info!(+ "Preinstall plugins installed successfully: {:?}",+ targets.iter().map(|t| &t.id).collect::<Vec<_>>()+ );Ok(())}@@ -532,7 +663,9 @@ pub async fn allow_version_exemptions(}/// 记录用户明确授权的发布时长策略豁免:把精确 `包名@版本` 写进档案的-/// `minimumReleaseAgeExclude`,pnpm 的解析与 lockfile 校验随后都会放行这些条目。+/// `minimumReleaseAgeExclude`,pnpm 的解析随后会放行这些条目;lockfile 校验阶段+/// 仍按默认窗口拦截,因此升级调用还会附上 `--config.minimumReleaseAge=0`+/// (见 `single::update_many`),否则授权过的版本依旧装不上。////// 与 [`allow_version_exemptions`] 的分工:那个针对 dsh 的**版本兼容性**(写档案的/// `compatibility.json`),这个针对 pnpm 的**发布时长门禁**(写 `pnpm-workspace.yaml`)。@@ -777,6 +910,41 @@ pub(super) fn append_command_output(all_output: &mut String, captured: &str) {mod tests {use super::*;+ #[test]+ fn locked_release_age_exemptions_require_every_blocked_entry_to_be_locked() {+ let dir = std::env::temp_dir().join(format!("dsh-heal-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(+ dir.join("pnpm-lock.yaml"),+ "lockfileVersion: '9.0'\nimporters:\n .:\n dependencies:\n dshmarket:\n specifier: ^2.12.0\n version: 2.12.0\n",+ )+ .unwrap();++ let locked = PolicyBlockedVersion {+ name: "dshmarket".to_string(),+ version: "2.12.0".to_string(),+ };+ let newer = PolicyBlockedVersion {+ name: "dshmarket".to_string(),+ version: "2.13.0".to_string(),+ };+ let absent = PolicyBlockedVersion {+ name: "elsewhere".to_string(),+ version: "1.0.0".to_string(),+ };++ assert_eq!(+ locked_release_age_exemptions(&dir, &[locked.clone()]),+ Some(vec!["[email protected]".to_string()])+ );+ assert_eq!(locked_release_age_exemptions(&dir, &[newer]), None);+ assert_eq!(locked_release_age_exemptions(&dir, &[absent]), None);+ assert_eq!(locked_release_age_exemptions(&dir, &[]), None);++ let _ = std::fs::remove_dir_all(&dir);+ }+#[test]fn command_output_retains_earlier_retry_diagnostics() {let mut output = String::new();diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rsindex ae61fdcc..0ab164ea 100644--- a/src-tauri/src/service/plugin/install/single.rs+++ b/src-tauri/src/service/plugin/install/single.rs@@ -6,7 +6,7 @@use std::collections::HashSet;use std::ffi::OsString;use std::path::Path;-use tauri::{AppHandle, Emitter, Manager};+use tauri::{AppHandle, Manager};use crate::config;use crate::service::cli;@@ -16,6 +16,7 @@ use crate::service::workflow;use super::artifact::{ensure_plugin_entry_built, installed_package_name};use super::build_plugin_envs;+use super::harness_prefer_bundled_pnpm;use super::diagnose::{git_transport_hint, incompatible_versions, network_error_hint, pick_error_message,policy_blocked_versions, policy_verification_network_failure, store_mismatch_hint,@@ -32,15 +33,275 @@ use super::profile_dir;use super::run_plugin_with_allow_build_retry;use super::uninstall_recovery;use super::PreinstallPluginInfo;-use super::{PreinstallLogPayload, PREINSTALL_LOG_EVENT};use crate::service::plugin::update::known_latest;use crate::service::profile::profile_release_age_excluded;-pub async fn update(app_handle: &AppHandle, id: &str) -> Result<(), String> {- run_single_plugin_command(app_handle, id, "update", &update_pnpm_args(id)).await+/// 批量升级:每个条目是 `<id>` 或 `<id>@<版本>`,两者走的路不同。+///+/// - 带版本(面板的升级入口一直显示着目标版本,所以这是常态):直接显式安装那个版本+/// (见 [`install_targets`])——不猜、不从声明范围里挑,于是「来源被钉死」「探测缓存+/// 没命中」都不会再让升级落空;+/// - 不带版本(面板没探测到新版本、修复入口、外部调用):先用宿主自己的探测补齐目标+/// (见 [`resolve_missing_targets`]),补不上才沿用 `dsh plugin update <id> --latest`+/// 让 pnpm 在声明范围内挑最新,再逐项核验是否真的落地(见 [`update_to_latest`])。+///+/// 逐项核验的结果汇总成一条错误消息(见 [`update_failure_payload`])。+pub async fn update_many(app_handle: &AppHandle, specs: &[String]) -> Result<(), String> {+ let mut requested: Vec<(String, Option<String>)> = specs+ .iter()+ .map(|spec| split_upgrade_spec(spec))+ .collect();+ if requested.iter().any(|(_, version)| version.is_none()) {+ resolve_missing_targets(app_handle, &mut requested).await;+ }+ let explicit: Vec<(String, String)> = requested+ .iter()+ .filter_map(|(id, version)| Some((id.clone(), version.clone()?)))+ .collect();+ let implicit: Vec<String> = requested+ .iter()+ .filter(|(_, version)| version.is_none())+ .map(|(id, _)| id.clone())+ .collect();+ let mut failures = Vec::new();+ if !explicit.is_empty() {+ failures.extend(install_targets(app_handle, &explicit).await?);+ }+ if !implicit.is_empty() {+ failures.extend(update_to_latest(app_handle, &implicit).await?);+ }+ match update_failure_payload(failures) {+ Some(message) => Err(message),+ None => Ok(()),+ }}-/// 升级时转发给 pnpm 的参数:`<id> --latest`。+/// 面板没给出目标版本的条目:宿主自己探一次 registry 再决定精确目标。+///+/// 前端只在探测缓存命中时才知道目标版本,缓存没命中(面板没刷新过、探测被限流或+/// 失败)时条目会退化成 `<id>`,而只靠 `--latest` 又要看 pnpm 的发布时长窗口脸色。+/// 宿主这里补一次探测(带 TTL 缓存,命中时零请求),把「确实有更新」的条目升级成+/// 精确目标,让升级结果不再取决于某一次 UI 快照。+async fn resolve_missing_targets(+ app_handle: &AppHandle,+ requested: &mut [(String, Option<String>)],+) {+ if let Err(e) = crate::service::plugin::update::refresh(app_handle).await {+ log::warn!("failed to probe plugin updates before upgrading: {e}");+ return;+ }+ let profile = profile_dir(app_handle);+ for (id, version) in requested.iter_mut() {+ if version.is_some() {+ continue;+ }+ let Some(latest) = known_latest(id) else {+ continue;+ };+ if !is_registry_version(&latest) || installed_package_version(&profile, id).as_deref() == Some(latest.as_str()) {+ continue;+ }+ *version = Some(latest);+ }+}++/// 显式安装一批精确目标(一次 pnpm 调用处理整批),并逐项核验是否真的落地。+///+/// `pnpm add <id>@<version>` 直接请求那个版本,声明里钉死来源(catalog 条目 / git ref /+/// `link:` 本地目录 / 精确版本)也照样被改写到目标版本——这正是「用户授权过那个新版本、+/// 升级却始终停在旧版本」的唯一出路。+///+/// 目标还在发布保护期内时先让 pnpm 如实报错(不加旗标),再用**我们自己请求的目标**合成+/// 拒绝载荷请用户授权(见 [`policy_refusal_from_specs`]);授权会写进档案豁免清单,重跑时+/// 本批目标全部已豁免,带上放宽旗标就是安全的。反过来,没豁免就放宽会把太新的条目写进+/// lock,此后每一次插件操作都会在 lockfile 校验阶段失败(见 §5.3 的自愈说明)。+async fn install_targets(+ app_handle: &AppHandle,+ targets: &[(String, String)],+) -> Result<Vec<String>, String> {+ let profile = profile_dir(app_handle);+ let specs: Vec<String> = targets+ .iter()+ .map(|(id, version)| format!("{id}@{version}"))+ .collect();+ let ids: Vec<String> = targets.iter().map(|(id, _)| id.clone()).collect();+ let before: Vec<Option<String>> = ids+ .iter()+ .map(|id| dependency_fingerprint(&profile, id))+ .collect();+ let mut args = specs.clone();+ if targets.iter().all(|(id, version)| {+ profile_release_age_excluded(app_handle, &format!("{id}@{version}"))+ }) {+ args.push(RELEASE_AGE_RELAXED_FLAG.to_string());+ }+ if let Err(e) = run_plugin_command(app_handle, &ids, "add", &args).await {+ return Err(policy_refusal_from_specs(&specs, &e).unwrap_or(e));+ }+ let mut failures = Vec::new();+ for (index, (id, version)) in targets.iter().enumerate() {+ if let Err(e) =+ verify_update_landed(app_handle, id, before[index].as_deref(), Some(version)).await+ {+ failures.push(e);+ }+ }+ Ok(failures)+}++/// 没有目标版本的条目:`dsh plugin update <id> --latest` 让 pnpm 在声明范围内挑最新,+/// 逐项核验没落地的那些再尝试一次显式安装(见 [`force_upgrade_spec`],只对已授权过的目标+/// 动手;未授权的先由前端走授权流程)。+async fn update_to_latest(app_handle: &AppHandle, ids: &[String]) -> Result<Vec<String>, String> {+ let profile = profile_dir(app_handle);+ let before: Vec<Option<String>> = ids+ .iter()+ .map(|id| dependency_fingerprint(&profile, id))+ .collect();+ let targets: Vec<(bool, bool)> = ids+ .iter()+ .map(|id| release_age_target(app_handle, &profile, id))+ .collect();+ let mut args = update_pnpm_args(ids);+ if relax_release_age(&targets) {+ args.push(RELEASE_AGE_RELAXED_FLAG.to_string());+ }+ run_plugin_command(app_handle, ids, "update", &args).await?;+ let mut failures = Vec::new();+ let mut forced = Vec::new();+ for (index, id) in ids.iter().enumerate() {+ match verify_update_landed(app_handle, id, before[index].as_deref(), None).await {+ Ok(()) => {}+ Err(e) => match force_upgrade_spec(id, &e) {+ Some(spec) => forced.push(spec),+ None => failures.push(e),+ },+ }+ }+ if forced.is_empty() {+ return Ok(failures);+ }+ log::warn!("dsh plugin update was blocked by the declared source, forcing {forced:?}");+ let forced_ids: Vec<String> = forced+ .iter()+ .map(|spec| split_upgrade_spec(spec).0)+ .collect();+ if let Err(e) = run_plugin_command(app_handle, &forced_ids, "add", &forced).await {+ return Err(policy_refusal_from_specs(&forced, &e).unwrap_or(e));+ }+ for (index, id) in ids.iter().enumerate() {+ let target = format!("{id}@");+ if !forced.iter().any(|spec| spec.starts_with(&target)) {+ continue;+ }+ if let Err(e) = verify_update_landed(app_handle, id, before[index].as_deref(), None).await {+ failures.push(e);+ }+ }+ Ok(failures)+}++/// 把面板给的升级条目切成 `(id, 目标版本)`:`[email protected]` 与 `@scope/[email protected]` 都按最后+/// 一个 `@` 切,`@scope/aaa`(无版本)与 `github:owner/repo` 这类非 registry 版本整条当+/// id——它们的「最新」是提交 SHA,装不了、也不该进发布时长豁免清单。+fn split_upgrade_spec(spec: &str) -> (String, Option<String>) {+ let Some((id, version)) = spec.rsplit_once('@') else {+ return (spec.to_string(), None);+ };+ if id.is_empty() {+ return (spec.to_string(), None);+ }+ if !is_registry_version(version) {+ return (id.to_string(), None);+ }+ (id.to_string(), Some(version.to_string()))+}++/// 显式安装被发布时长门禁拦住时,用**我们自己请求的目标**合成拒绝载荷。+///+/// pnpm 在两个阶段报的文本不同(解析形 / lockfile 校验形,见 `super::diagnose`),而+/// 「装不上」这一侧只知道失败。按请求的精确目标如实点名,前端才能照常请用户授权;授权+/// 会写进档案豁免清单,重跑时本批目标全部已授权,于是带上放宽旗标真的装上。+fn policy_refusal_from_specs(specs: &[String], failure: &str) -> Option<String> {+ if !failure.contains("ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION")+ && !failure.contains("minimumReleaseAge")+ {+ return None;+ }+ let blocked: Vec<serde_json::Value> = specs+ .iter()+ .filter_map(|spec| {+ let (id, version) = split_upgrade_spec(spec);+ let version = version?;+ Some(serde_json::json!({ "name": id, "version": version }))+ })+ .collect();+ if blocked.is_empty() {+ return None;+ }+ Some(format!(+ "PLUGIN_POLICY_BLOCKED: {}",+ serde_json::Value::Array(blocked)+ ))+}++/// 升级没落地、且只剩「声明把来源钉死」这一种成因时,显式安装目标版本所需的 spec。+///+/// `--latest` 只让 pnpm 越过声明**范围**里的版本;把来源钉死的声明(git ref、`link:`+/// 本地目录、精确版本、catalog 条目)在更新时会被 pnpm 原样保留——git spec 甚至不会被+/// 退化成 semver 范围——于是「用户已经授权过那个精确版本」仍然停在旧版本上。这种情况+/// 只有 `pnpm add <id>@<version>` 会把声明改写到目标版本,由 [`update_many`] 补这一步。+///+/// 只对**已授权过**的目标动手:`retryable` 为真说明用户还没授权,必须先走授权流程,+/// 否则等于替用户绕过发布时长门禁;`latest` 不是 registry 版本(git 提交 / 本地目录)时+/// 没有可安装的版本,显式安装无从谈起。+fn force_upgrade_spec(id: &str, failure: &str) -> Option<String> {+ let payload = failure.strip_prefix(UPDATE_HOLD_PREFIX)?;+ let payload: serde_json::Value = serde_json::from_str(payload).ok()?;+ if payload.get("retryable").and_then(serde_json::Value::as_bool) != Some(false) {+ return None;+ }+ let latest = payload.get("latest").and_then(serde_json::Value::as_str)?;+ if !is_registry_version(latest) {+ return None;+ }+ Some(format!("{id}@{latest}"))+}++/// 升级没生效的前缀:`PLUGIN_UPDATE_NO_CHANGE: <JSON>`。+const UPDATE_HOLD_PREFIX: &str = "PLUGIN_UPDATE_NO_CHANGE:";++/// 把逐项核验的失败汇成一条错误消息。+///+/// 多个 id 各自没生效时**不能**把每条 `PLUGIN_UPDATE_NO_CHANGE:` 用换行拼起来:前端把前缀+/// 之后的内容整体当成一份载荷,多份 JSON 拼在一起不再合法,解析失败会让整批退化成+/// 「升级插件 X 失败」,把「授权一下就能装的版本」说成损坏(见+/// `src/store/modules/plugins/utils.ts` 的 `parseUpdateHold`)。因此把每个没生效的条目收进+/// 一个 JSON 数组一次性带出去,前端就能逐项归因:能授权的进授权流程,钉死来源的中性提示。+/// 混进真正的失败(入口构建等)时优先如实报那条——它才是用户要处理的问题。+fn update_failure_payload(failures: Vec<String>) -> Option<String> {+ let mut holds = Vec::new();+ let mut others = Vec::new();+ for failure in failures {+ let payload = failure.strip_prefix(UPDATE_HOLD_PREFIX);+ match payload.and_then(|payload| serde_json::from_str::<serde_json::Value>(payload).ok()) {+ Some(value) => holds.push(value),+ None => others.push(failure),+ }+ }+ if !others.is_empty() {+ return Some(others.join("\n"));+ }+ if holds.is_empty() {+ return None;+ }+ Some(format!(+ "{UPDATE_HOLD_PREFIX} {}",+ serde_json::Value::Array(holds)+ ))+}++/// 升级时转发给 pnpm 的参数:每个 id 后各跟一个 `--latest`。////// `update` 动词不写在这里:它由 [`single_plugin_args`] 作为动作统一放在参数最前,/// 重复一次会变成 `pnpm update update <id>`(见该函数的说明)。@@ -52,15 +313,69 @@ pub async fn update(app_handle: &AppHandle, id: &str) -> Result<(), String> {/// 据此报「升级成功」而版本纹丝不动。加 `--latest` 才允许 pnpm 越过声明范围,并由/// pnpm 自己把 catalog 条目改写到新版本;git spec 不受影响(`--latest` 不会把/// `github:owner/repo` 退化成 semver 范围,实测原样保留)。-fn update_pnpm_args(id: &str) -> Vec<String> {- vec![id.to_string(), "--latest".to_string()]+fn update_pnpm_args(ids: &[String]) -> Vec<String> {+ ids.iter()+ .flat_map(|id| [id.clone(), "--latest".to_string()])+ .collect()+}++/// 放宽 pnpm 发布时长门禁的参数:档案的 `minimumReleaseAgeExclude` 会被解析阶段采信,+/// lockfile 校验阶段却照旧按默认窗口拦截,授权过的精确版本因此永远装不上(见+/// [`relax_release_age`])。+pub(super) const RELEASE_AGE_RELAXED_FLAG: &str = "--config.minimumReleaseAge=0";++/// 单个 id 的发布时长门禁事实:`(有可升级的 registry 目标, 该目标已授权)`。+///+/// 目标版本取更新探测缓存([`known_latest`],不新发网络请求);git 托管插件的「最新」是+/// 提交 SHA、`next` 这类 ref 都不是版本,不能进发布时长豁免清单,按形状挡掉。+fn release_age_target(app_handle: &AppHandle, profile: &Path, id: &str) -> (bool, bool) {+ let target = known_latest(id);+ let target = target.as_deref().filter(|latest| is_registry_version(latest));+ let Some(target) = target else {+ return (false, false);+ };+ let upgradable = installed_package_version(profile, id).as_deref() != Some(target);+ let excluded = profile_release_age_excluded(app_handle, &format!("{id}@{target}"));+ (upgradable, excluded)+}++/// 这次 `update` 调用是否要放宽发布时长门禁([`RELEASE_AGE_RELAXED_FLAG`])。+///+/// 实测 bundled pnpm 11.7.0:档案已列出 `[email protected]` 时+/// `pnpm update billion-context --latest` 仍以 1 退出并报+/// `ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION`,同一命令追加+/// `--config.minimumReleaseAge=0` 才装到 0.1.174——「授权过的版本装不上」正是+/// 升级入口报「没有可授权的新版本」的成因。+///+/// 该旗标是**全调用生效**的:一旦放宽,同批里未被授权的包也可能跟着越过默认窗口。+/// 因此只在「本批每个可升级的 registry 目标都已授权」时放宽;混进一个未授权的可+/// 升级目标就保持默认窗口,界面照旧先请用户授权。升级入口按单个插件派发,批里通常+/// 只有一个目标。+fn relax_release_age(targets: &[(bool, bool)]) -> bool {+ let mut authorized = 0;+ for (upgradable, excluded) in targets {+ if !*upgradable {+ continue;+ }+ if !*excluded {+ return false;+ }+ authorized += 1;+ }+ authorized > 0+}++/// registry 版本形状:数字开头且含 `.`。git 托管插件的「最新」是提交 SHA、`next`+/// 这类 ref 都不是版本,不能进发布时长豁免清单。+fn is_registry_version(value: &str) -> bool {+ value.contains('.') && value.starts_with(|c: char| c.is_ascii_digit())}/// 依赖的「解析指纹」:profile `pnpm-lock.yaml` 当前 importer(`importers["."]`)/// 中该直接依赖的 `specifier @ version`;该依赖不在 lock 里时回落到/// `node_modules/<id>/package.json` 的实际版本。///-/// 用途是核验升级是否真的落地(见 [`run_single_plugin_command`]):pnpm 可能以 0+/// 用途是核验升级是否真的落地(见 [`verify_update_landed`]):pnpm 可能以 0/// 退出却什么都没装,而「什么都没装」在两种依赖上表现不同——registry 依赖是版本号/// 不变,git 依赖是版本号本来就可能不变(插件不 bump version)而只有 lock 里的/// codeload 提交变化。因此指纹取 lock 的解析结果,两种依赖都能识别。@@ -78,6 +393,11 @@ fn dependency_fingerprint(profile: &Path, id: &str) -> Option<String> {/// 扫描会把同名传递依赖的解析结果算进来,指纹就会因无关依赖变动而抖动。/// lock 缺失、损坏或结构不是预期形态时返回 `None`(交由调用方跳过核验)。fn lock_dependency_entry(profile: &Path, id: &str) -> Option<String> {+ lock_dependency(profile, id).map(|(specifier, version)| format!("{specifier} @ {version}"))+}++/// importer 中该依赖的 `specifier` 与解析出的精确版本。+fn lock_dependency(profile: &Path, id: &str) -> Option<(String, String)> {let text = std::fs::read_to_string(profile.join("pnpm-lock.yaml")).ok()?;let lockfile: serde_yaml::Value = serde_yaml::from_str(&text).ok()?;let dependency = lockfile@@ -88,12 +408,22 @@ fn lock_dependency_entry(profile: &Path, id: &str) -> Option<String> {let specifier = dependency.get("specifier").and_then(serde_yaml::Value::as_str)- .unwrap_or_default();+ .unwrap_or_default()+ .to_string();let version = dependency.get("version").and_then(serde_yaml::Value::as_str)- .unwrap_or_default();- Some(format!("{specifier} @ {version}"))+ .unwrap_or_default()+ .to_string();+ Some((specifier, version))+}++/// importer 里该依赖已解析的精确版本(不在 lock 中 / 读不出时 `None`)。+///+/// 供发布时长门禁的自愈判定使用(见 `install::heal_locked_release_age`):被 pnpm 拦下+/// 的版本若正是 lock 里早早解析好的那个,说明它早就装到本机了,不是本次新解析的版本。+pub(super) fn locked_package_version(profile: &Path, id: &str) -> Option<String> {+ lock_dependency(profile, id).map(|(_, version)| version)}/// `node_modules/<id>/package.json` 声明的版本(缺失或损坏返回 `None`)。@@ -104,45 +434,63 @@ fn installed_package_version(profile: &Path, id: &str) -> Option<String> {manifest.get("version")?.as_str().map(String::from)}-/// 卸载单个插件:`dsh plugin --profile <当前档案> remove <id>`-pub async fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {- let command_result =- run_single_plugin_command(app_handle, id, "remove", &[id.to_string()]).await;- // `dsh plugin remove` 以子进程退出码为准,可能出现「命令成功但插件仍在」的- // 边界(如 bundle 层残留、pnpm 静默失败);node_modules / lockfile 损坏时- // (典型:安装只写入了 profile 清单而产物缺失,见 issue #90)pnpm 甚至会- // 直接失败。两种情形统一核验 profile 清单:只要插件仍被引用就回落离线卸载- // (直接改清单 + 删目录 + 清 lockfile),确保插件真正移除- // (参考 dsh-market 的「卸载后核验」约定:确认插件离开 profile 才算成功)。- if is_installed(app_handle, id) {- // 第三方可卸载插件才允许离线兜底;核心/官方等受保护包即使残留也不强删- // (`uninstall_recovery` 对它们会拒绝)。- if is_actionable_plugin_ref(id) {- let outcome = match &command_result {- Ok(()) => "reported success".to_string(),- Err(e) => format!("failed: {e}"),- };- log::warn!(- "dsh plugin remove {outcome} but {id} is still referenced by profile manifest; forcing offline uninstall"- );- uninstall_recovery(app_handle, id)?;- // 离线兜底成功:插件已真正从 profile 移除,清除历史错误,避免前端- // 残留异常标记(best-effort)。- if let Err(e) = errors::clear(app_handle, id) {- log::warn!("failed to clear plugin error for {id}: {e}");+/// 批量卸载:单次 `dsh plugin remove <id1> <id2> ...`,随后逐项核验 profile 清单,+/// 仍被引用时走离线卸载兜底(第三方可卸载插件),最后级联清理各自的单插件快照。+pub async fn remove_many(app_handle: &AppHandle, ids: &[String]) -> Result<(), String> {+ let command_result = run_plugin_command(app_handle, ids, "remove", ids).await;+ let mut failures = Vec::new();+ for id in ids {+ // `dsh plugin remove` 以子进程退出码为准,可能出现「命令成功但插件仍在」的+ // 边界(如 bundle 层残留、pnpm 静默失败);node_modules / lockfile 损坏时+ // (典型:安装只写入了 profile 清单而产物缺失,见 issue #90)pnpm 甚至会+ // 直接失败。两种情形统一核验 profile 清单:只要插件仍被引用就回落离线卸载+ // (直接改清单 + 删目录 + 清 lockfile),确保插件真正移除+ // (参考 dsh-market 的「卸载后核验」约定:确认插件离开 profile 才算成功)。+ if is_installed(app_handle, id) {+ // 第三方可卸载插件才允许离线兜底;核心/官方等受保护包即使残留也不强删+ // (`uninstall_recovery` 对它们会拒绝)。+ if is_actionable_plugin_ref(id) {+ let outcome = match &command_result {+ Ok(()) => "reported success".to_string(),+ Err(e) => format!("failed: {e}"),+ };+ log::warn!(+ "dsh plugin remove {outcome} but {id} is still referenced by profile manifest; forcing offline uninstall"+ );+ match uninstall_recovery(app_handle, id) {+ Ok(()) => {+ // 离线兜底成功:插件已真正从 profile 移除,清除历史错误,避免+ // 前端残留异常标记(best-effort)。+ if let Err(e) = errors::clear(app_handle, id) {+ log::warn!("failed to clear plugin error for {id}: {e}");+ }+ }+ Err(e) => failures.push(format!("{id}: {e}")),+ }+ } else {+ // 受保护包:命令失败则如实上报(不要把失败误报为成功),成功则仅告警。+ if let Err(e) = &command_result {+ failures.push(format!("{id}: {e}"));+ }+ log::warn!(+ "dsh plugin remove reported success but protected package {id} is still referenced by profile manifest; skipping offline uninstall"+ );}- } else {- // 受保护包:命令失败则如实上报(不要把失败误报为成功),成功则仅告警。- command_result?;- log::warn!(- "dsh plugin remove reported success but protected package {id} is still referenced by profile manifest; skipping offline uninstall"- );+ }+ // 卸载级联清理单插件快照(best-effort):只有插件确实离开 profile 才删。+ // 离线兜底失败或受保护包残留时插件仍在,快照是用户唯一的回滚手段,必须保留+ // (issue #303:插件已移除则快照随之失效,避免残留孤儿快照占用存储)。+ if !is_installed(app_handle, id) {+ super::super::snapshot::delete_best_effort(app_handle, id);}}- // 卸载级联清理单插件快照(best-effort):插件已移除,快照随之失效- // (issue #303:卸载后删除快照,避免残留孤儿快照占用存储)。- super::super::snapshot::delete_best_effort(app_handle, id);- Ok(())+ // 与单插件卸载的原语义一致:以「条目是否真的离开 profile」为准。命令以非 0+ // 退出但插件已被移走时不报错(卸载已达成),只有仍残留且兜底也失败才算失败。+ if failures.is_empty() {+ Ok(())+ } else {+ Err(failures.join("\n"))+ }}/// 计算需要自动卸载的弃用插件已安装包名(纯函数,便于单测)。@@ -261,15 +609,16 @@ pub(super) fn single_plugin_args(profile: &str, action: &str, sub_args: &[Stringargs}-/// 执行单个插件的升级/卸载:准备环境 → 停止服务 → 运行 `dsh plugin` →-/// 失败记录错误、成功清除错误。-async fn run_single_plugin_command(+/// 批量执行插件的升级/卸载:准备环境 → 停止服务 → 运行**一次** `dsh plugin`+/// (`dsh plugin` 把动词之后的参数原样转发 pnpm,一次调用即可处理多个依赖)→+/// 失败逐项记录错误、成功逐项清除错误。+async fn run_plugin_command(app_handle: &AppHandle,- id: &str,+ ids: &[String],action: &str,sub_args: &[String],) -> Result<(), String> {- if id.is_empty() {+ if ids.is_empty() {return Err("PLUGIN_EMPTY_ID: plugin id is empty".to_string());}let window = app_handle@@ -294,42 +643,18 @@ async fn run_single_plugin_command(// 与批量安装保持一致:旧档案也必须具备精确的 release-age 例外,// 否则升级/卸载触发 pnpm lockfile 校验时同样会被 issue #222 的问题阻断。super::ensure_profile_pnpm_policy(app_handle)?;- // 插件操作会改写 profile,先停止运行中的服务(与安装一致)。- // 记录停服结果:停服失败意味着服务可能仍在运行、插件目录可能被写入,- // 此时创建快照会捕获不一致状态,因此停服失败时跳过快照(不终止升级)。- let mut stopped = true;- if workflow::has_owned_process() {- let _ = window.emit(- PREINSTALL_LOG_EVENT,- PreinstallLogPayload {- line: format!("[harness] 正在停止运行中的服务({action}插件需要短暂重启)…"),- },- );- stopped = match workflow::stop(app_handle.clone()).await {- Ok(()) => true,- Err(e) => {- log::warn!("failed to stop harness before plugin {action}: {e}");- false- }- };- }- // 升级前自动快照当前版本(覆盖式),失败仅告警不阻断升级。- // 仅在服务已确认停止后执行:服务运行期间插件目录可能被写入,先停服保证快照一致+ // 升级前自动快照当前版本(覆盖式),失败仅告警不阻断升级// (issue #303:自动快照失败不阻塞主流程;还原入口在插件面板)。- if action == "update" && stopped {- super::super::snapshot::create_best_effort(app_handle, id);+ // 与批量安装一致,这里**不再**停掉运行中的服务:插件包只会被随后的 pnpm 改写,+ // 先停服对快照一致性没有帮助,反而让用户在升级中途失去服务。+ if action == "update" {+ for id in ids {+ super::super::snapshot::create_best_effort(app_handle, id);+ }}let envs = build_plugin_envs(app_handle, prefer_bundled_pnpm);- // 升级前的依赖解析指纹:升级命令以 0 退出后用它核验是否真的落地- // (见下方 `action == "update"` 分支的假成功核验)。非升级动作不需要。- let before_fingerprint = if action == "update" {- dependency_fingerprint(&profile_dir(app_handle), id)- } else {- None- };-let mut args = vec![dsh_bin.as_os_str().to_os_string()];args.extend(single_plugin_args(&active_profile(app_handle),@@ -338,14 +663,34 @@ async fn run_single_plugin_command());let cwd = config::get_dsh_install_path(app_handle);- log::info!("Running dsh plugin {action} for {id}");+ log::info!("Running dsh plugin {action} for {ids:?}");let (exit_code, output, last_attempt) = run_plugin_with_allow_build_retry(app_handle, &node, &args, &cwd, &envs, &window, action, None, owner,).await?;+ // 门禁自愈:lockfile 里早有的太新条目会让**每一次**状态变更都失败+ // (见 `super::heal_locked_release_age`)。补齐豁免后放宽窗口重跑一次——本批若已经+ // 因全部目标授权而放宽过(参数里已有旗标),就没什么可补的,直接按原样分类。+ let relaxed = args+ .iter()+ .any(|arg| arg.to_str() == Some(RELEASE_AGE_RELAXED_FLAG));+ let (exit_code, output, last_attempt) = if exit_code != 0+ && !relaxed+ && super::heal_locked_release_age(app_handle, &last_attempt)+ {+ let mut retry_args = args.clone();+ retry_args.push(OsString::from(RELEASE_AGE_RELAXED_FLAG));+ run_plugin_with_allow_build_retry(+ app_handle, &node, &retry_args, &cwd, &envs, &window, action, None, owner,+ )+ .await?+ } else {+ (exit_code, output, last_attempt)+ };+if exit_code != 0 {- log::error!("dsh plugin {action} failed for {id} with exit code {exit_code}");+ log::error!("dsh plugin {action} failed for {ids:?} with exit code {exit_code}");// 版本兼容性拒绝:dsh 在 pnpm 之前核对插件声明的 DSH peer 依赖,未授权精确版本// 即拒绝(不下载、不构建),升级同样会撞上(新版本声明了更高的核心 peer 依赖)。// 与批量安装路径一致地解析成精确三元组,交前端「授权后重跑」;不记插件错误——@@ -392,8 +737,10 @@ async fn run_single_plugin_command(} else {pick_error_message(&output, hint)};- if let Err(e) = errors::record(app_handle, id, action, &message) {- log::warn!("failed to record plugin error for {id}: {e}");+ for id in ids {+ if let Err(e) = errors::record(app_handle, id, action, &message) {+ log::warn!("failed to record plugin error for {id}: {e}");+ }}if network_error {return Err("NETWORK_ERROR: plugin registry request failed; check network or proxy settings and retry.".to_string());@@ -412,76 +759,104 @@ async fn run_single_plugin_command());}- // 成功:清除历史错误;卸载 win-terminal-inspector 时顺带清理 patch 挂载- if let Err(e) = errors::clear(app_handle, id) {- log::warn!("failed to clear plugin error for {id}: {e}");+ // 成功:逐项清除历史错误;卸载 win-terminal-inspector 时顺带清理 patch 挂载+ for id in ids {+ if let Err(e) = errors::clear(app_handle, id) {+ log::warn!("failed to clear plugin error for {id}: {e}");+ }}- // 升级路径与安装一致地核验构建产物:git 托管插件升级后同样可能停在- // 「prepare 未构建 → 声明入口缺失」坏态,若不拦截,下一次启动即崩溃- // (见 [`ensure_plugin_entry_built`])。包名先解析(预设 package 覆盖 /- // 清单依赖 basename),解析不到时跳过核验(警告即可,不误杀成功更新)。- if action == "update" {- // 假成功核验:pnpm 以 0 退出、但该依赖的解析结果与升级前完全一致,说明这次- // 升级没有落地。两种已知成因都属于「按当前策略不该动」,而不是插件损坏:- // 1. 档案 spec 把版本钉死(`catalog:` 条目 / git 提交 / `link:` 本地目录),- // `--latest` 也越不过声明范围;- // 2. pnpm 的 release-age 策略:新版本发布不足 `minimumReleaseAge`(pnpm 11- // 默认 1440 分钟 = 24 小时)时解析会回落到仍达标的最新版本,命令照旧以 0- // 退出且**不打印任何说明**——实测 bundled pnpm 11.7.0 在 `^2.10.15` 上- // `update --latest` 静默停在 2.10.15,把 `minimumReleaseAge: 0` 写进档案- // 才取到 2.11.2。因此这条消息不能只归因于 catalog 钉死(会把人引偏)。- // 必须如实报「没升级」——报成功会让用户以为已在新版本上(与 [`remove`] 的- // 「卸载后核验」同理);但**不**记进插件错误:插件没坏,记了会让列表挂上- // 「可能已损坏或与当前环境不兼容」的误导标记(安装/升级真失败各有记录点)。- if let Some(before) = before_fingerprint.as_deref() {- if dependency_fingerprint(&profile_dir(app_handle), id).as_deref() == Some(before) {- let detail = installed_package_version(&profile_dir(app_handle), id)- .unwrap_or_else(|| before.to_string());- // 只有「新版本太新」这一种成因有出路(授权那个精确版本即可过闸),因此把- // 目标版本与「是否已在豁免清单里」一并带出去:已经授权过还是不动,说明成因- // 是档案把来源钉死,界面就别再给按钮——否则用户只会反复点一个没用的动作。- // 目标版本取自更新探测缓存(不新发网络请求);git 托管插件的「最新」是提交- // SHA、不是 registry 版本,不能进发布时长豁免清单,按形状挡掉。- let latest = known_latest(id).filter(|latest| {- latest != &detail- && latest.contains('.')- && latest.starts_with(|c: char| c.is_ascii_digit())- });- let retryable = latest.as_deref().is_some_and(|latest| {- !profile_release_age_excluded(app_handle, &format!("{id}@{latest}"))- });- log::warn!(- "dsh plugin update made no change for {id}, still at {detail}, newest {latest:?}, actionable {retryable}"- );- return Err(format!(- "PLUGIN_UPDATE_NO_CHANGE: {}",- serde_json::json!({- "name": id,- "version": detail,- "latest": latest,- "retryable": retryable,- })- ));- }+ if action == "remove" && ids.iter().any(|id| id == "dsh-win-terminal-inspector") {+ if let Err(e) = workflow::win_inspector::apply(app_handle) {+ log::warn!("win inspector patch prune failed after remove: {e}");}- let Some(name) = installed_package_name(app_handle, id) else {- log::warn!("plugin {id} not resolvable to a package name, skipping entry verify");+ }+ log::info!("dsh plugin {action} succeeded for {ids:?}");+ Ok(())+}++/// 升级后逐项核验:确认升级真的落地,并补构建缺失的声明入口。+///+/// 假成功核验:pnpm 以 0 退出、但该依赖的解析结果与升级前完全一致,说明这次+/// 升级没有落地。两种已知成因都属于「按当前策略不该动」,而不是插件损坏:+/// 1. 档案 spec 把版本钉死(`catalog:` 条目 / git 提交 / `link:` 本地目录),+/// `--latest` 也越不过声明范围——这一种由 [`update_many`] 在授权后用显式安装兜底+/// (见 [`force_upgrade_spec`]),只有兜底也推不动时才把「没升级」报给用户;+/// 2. pnpm 的 release-age 策略:新版本发布不足 `minimumReleaseAge`(pnpm 11+/// 默认 1440 分钟 = 24 小时)时解析会回落到仍达标的最新版本,命令照旧以 0+/// 退出且**不打印任何说明**——实测 bundled pnpm 11.7.0 在 `^2.10.15` 上+/// `update --latest` 静默停在 2.10.15。用户授权该精确版本后,由 [`update_many`]+/// 追加 `--config.minimumReleaseAge=0` 才能真正落地(档案里的豁免只被解析阶段+/// 采信,lockfile 校验阶段照样拦)。因此这条消息不能只归因于 catalog 钉死+/// (会把人引偏)。+/// 必须如实报「没升级」——报成功会让用户以为已在新版本上(与 [`remove_many`] 的+/// 「卸载后核验」同理);但**不**记进插件错误:插件没坏,记了会让列表挂上+/// 「可能已损坏或与当前环境不兼容」的误导标记(安装/升级真失败各有记录点)。+///+/// 入口核验与安装一致:git 托管插件升级后同样可能停在「prepare 未构建 → 声明+/// 入口缺失」坏态,若不拦截,下一次启动即崩溃(见 [`ensure_plugin_entry_built`])。+/// 包名先解析(预设 package 覆盖 / 清单依赖 basename),解析不到时跳过核验+/// (警告即可,不误杀成功更新)。+async fn verify_update_landed(+ app_handle: &AppHandle,+ id: &str,+ before: Option<&str>,+ expected: Option<&str>,+) -> Result<(), String> {+ if let Some(expected) = expected {+ // 已经就是用户要的那个版本:pnpm 没有东西可改,指纹自然不变,但请求的状态已经达成+ // ——显式安装之后这一条必须算成功,否则「装上了」会被报成「没有变化」。+ if installed_package_version(&profile_dir(app_handle), id).as_deref() == Some(expected) {return Ok(());- };- let pkg_dir = profile_dir(app_handle).join("node_modules").join(name);- if let Err(e) = ensure_plugin_entry_built(app_handle, id, &pkg_dir, &envs, &window).await {- if let Err(err) = errors::record(app_handle, id, action, &e) {- log::warn!("failed to record plugin error for {id}: {err}");- }- return Err(e);}}- if action == "remove" && id == "dsh-win-terminal-inspector" {- if let Err(e) = workflow::win_inspector::apply(app_handle) {- log::warn!("win inspector patch prune failed after remove: {e}");+ if let Some(before) = before {+ if dependency_fingerprint(&profile_dir(app_handle), id).as_deref() == Some(before) {+ let detail = installed_package_version(&profile_dir(app_handle), id)+ .unwrap_or_else(|| before.to_string());+ // 只有「新版本太新」这一种成因有出路(授权那个精确版本即可过闸),因此把+ // 目标版本与「是否已在豁免清单里」一并带出去:已经授权过还是不动,说明成因+ // 是档案把来源钉死,界面就别再给按钮——否则用户只会反复点一个没用的动作。+ // 目标版本优先用本次请求带来的版本(面板显示的那个),探测缓存只在没有时才+ // 兜底:缓存没命中会让 `latest` 为空、`retryable` 判成不可授权,用户点升级+ // 就只剩一句「没有变化」。+ let latest = expected+ .filter(|expected| *expected != detail && is_registry_version(expected))+ .map(str::to_string)+ .or_else(|| {+ known_latest(id).filter(|latest| latest != &detail && is_registry_version(latest))+ });+ let retryable = latest.as_deref().is_some_and(|latest| {+ !profile_release_age_excluded(app_handle, &format!("{id}@{latest}"))+ });+ log::warn!(+ "dsh plugin update made no change for {id}, still at {detail}, newest {latest:?}, actionable {retryable}"+ );+ return Err(format!(+ "{UPDATE_HOLD_PREFIX} {}",+ serde_json::json!({+ "name": id,+ "version": detail,+ "latest": latest,+ "retryable": retryable,+ })+ ));+ }+ }+ let Some(name) = installed_package_name(app_handle, id) else {+ log::warn!("plugin {id} not resolvable to a package name, skipping entry verify");+ return Ok(());+ };+ let window = app_handle+ .get_webview_window("main")+ .ok_or("WINDOW_NOT_FOUND: main window missing")?;+ let envs = build_plugin_envs(app_handle, harness_prefer_bundled_pnpm(app_handle));+ let pkg_dir = profile_dir(app_handle).join("node_modules").join(name);+ if let Err(e) = ensure_plugin_entry_built(app_handle, id, &pkg_dir, &envs, &window).await {+ if let Err(err) = errors::record(app_handle, id, "update", &e) {+ log::warn!("failed to record plugin error for {id}: {err}");}+ return Err(e);}- log::info!("dsh plugin {action} succeeded for {id}");Ok(())}@@ -532,6 +907,111 @@ mod tests {.is_empty());}+ /// 一批里两个 id 都没生效时,两条 hold 载荷必须并成**一个** JSON 数组:拼成多行会让+ /// 前端 `parseUpdateHold` 解析失败,把「授权一下就能装」说成「升级失败」。+ #[test]+ fn update_failure_payload_merges_holds_into_one_array() {+ let message = update_failure_payload(vec![+ format!(+ "{UPDATE_HOLD_PREFIX} {}",+ serde_json::json!({"name": "a", "version": "1.0.0", "latest": "2.0.0", "retryable": true})+ ),+ format!(+ "{UPDATE_HOLD_PREFIX} {}",+ serde_json::json!({"name": "b", "version": "1.0.0", "latest": null, "retryable": false})+ ),+ ])+ .expect("message");++ let payload = message.strip_prefix(UPDATE_HOLD_PREFIX).expect("prefix");+ let parsed: serde_json::Value = serde_json::from_str(payload).expect("array payload");+ let items = parsed.as_array().expect("array");+ assert_eq!(items.len(), 2);+ assert_eq!(items[0]["name"], "a");+ assert_eq!(items[1]["retryable"], false);+ }++ /// 真正的失败(入口构建等)不能被 hold 载荷吞掉,否则用户看不到要处理的问题。+ #[test]+ fn update_failure_payload_prefers_real_failures() {+ let message = update_failure_payload(vec![+ "PLUGIN_ENTRY_MISSING: a is broken".to_string(),+ format!(+ "{UPDATE_HOLD_PREFIX} {}",+ serde_json::json!({"name": "a", "latest": "2.0.0", "retryable": true})+ ),+ ])+ .expect("message");++ assert_eq!(message, "PLUGIN_ENTRY_MISSING: a is broken");+ assert!(update_failure_payload(Vec::new()).is_none());+ }++ /// 只有「已授权过的 registry 目标」才补显式安装:未授权时先走授权流程,git / link 目标+ /// 没有可安装的版本号。+ #[test]+ fn pinned_upgrades_are_forced_only_after_authorisation() {+ let hold = |latest: &str, retryable: bool| {+ format!(+ "{UPDATE_HOLD_PREFIX} {}",+ serde_json::json!({"name": "a", "latest": latest, "retryable": retryable})+ )+ };++ assert_eq!(+ force_upgrade_spec("a", &hold("0.1.174", false)),+ Some("[email protected]".to_string())+ );+ assert_eq!(force_upgrade_spec("a", &hold("0.1.174", true)), None);+ assert_eq!(force_upgrade_spec("a", &hold("main", false)), None);+ assert_eq!(force_upgrade_spec("a", &hold("", false)), None);+ assert_eq!(force_upgrade_spec("a", "PLUGIN_ENTRY_MISSING: broken"), None);+ }++ /// 面板给的条目才带版本:`@scope` 包按最后一个 `@` 切,非 registry 版本(git ref、`next`)+ /// 整条当 id——它们进不了 `pnpm add <id>@<version>`,也不该进发布时长豁免清单。+ #[test]+ fn upgrade_specs_split_versions_only_when_they_are_registry_versions() {+ assert_eq!(+ split_upgrade_spec("[email protected]"),+ ("aaa".to_string(), Some("1.2.3".to_string()))+ );+ assert_eq!(+ split_upgrade_spec("@scope/[email protected]"),+ ("@scope/aaa".to_string(), Some("1.2.3".to_string()))+ );+ assert_eq!(+ split_upgrade_spec("@scope/aaa"),+ ("@scope/aaa".to_string(), None)+ );+ assert_eq!(split_upgrade_spec("aaa@next"), ("aaa".to_string(), None));+ assert_eq!(+ split_upgrade_spec("github:owner/repo#main"),+ ("github:owner/repo#main".to_string(), None)+ );+ }++ /// 显式安装被发布时长门禁拦住时,按请求的精确目标合成拒绝载荷——pnpm 两个阶段报的文本+ /// 不同,前端要的是「哪个包、哪个版本」。+ #[test]+ fn policy_refusals_name_the_requested_targets() {+ let specs = vec!["[email protected]".to_string(), "[email protected]".to_string()];+ let failure = "ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION [email protected] was published at ...";++ assert_eq!(+ policy_refusal_from_specs(&specs, failure),+ Some(+ "PLUGIN_POLICY_BLOCKED: [{\"name\":\"aaa\",\"version\":\"1.2.3\"},{\"name\":\"bbb\",\"version\":\"2.0.0\"}]"+ .to_string()+ )+ );+ assert_eq!(policy_refusal_from_specs(&specs, "PLUGIN_ENTRY_MISSING: broken"), None);+ assert_eq!(+ policy_refusal_from_specs(&["aaa@next".to_string()], failure),+ None+ );+ }+fn preset(id: &str, spec: &str, internal: bool) -> PreinstallPluginInfo {PreinstallPluginInfo {id: id.into(),@@ -723,11 +1203,36 @@ mod tests {// `catalog:` 条目上时(catalog `^0.18.1` 之于 0.19.0),升级会退化成// 「退出码 0 但什么都没装」的假成功——正是 sidebar 0.18.1→0.19.0 不生效的根因。assert_eq!(- update_pnpm_args("dsh-better-sidebar"),+ update_pnpm_args(&["dsh-better-sidebar".to_string()]),vec!["dsh-better-sidebar", "--latest"]);}+ /// 回归用户报告:授权过的精确版本此前永远装不上——档案里的发布时长豁免只被+ /// 解析阶段采信,lockfile 校验阶段照旧按默认窗口拦截,`--latest` 于是「退出 0+ /// 但版本没动」。已授权的目标版本必须让那次调用带上门禁放宽参数。+ #[test]+ fn release_age_relaxation_requires_an_authorized_registry_target() {+ assert!(relax_release_age(&[(true, true)]));+ // 没授权过 → 不放宽,界面照旧先请用户授权+ assert!(!relax_release_age(&[(true, false)]));+ // 混进未授权的可升级目标 → 整批保持默认窗口,不能顺带把它放过去+ assert!(!relax_release_age(&[(true, true), (true, false)]));+ // 没有可升级目标的目标不阻碍放宽(同版本 / 没有 registry 目标)+ assert!(relax_release_age(&[(true, true), (false, false)]));+ assert!(!relax_release_age(&[(false, true)]));+ assert!(!relax_release_age(&[]));+ }++ #[test]+ fn registry_versions_are_recognized_by_shape() {+ assert!(is_registry_version("0.1.174"));+ assert!(is_registry_version("1.66.5"));+ assert!(!is_registry_version("next"));+ assert!(!is_registry_version("b3a69187e1bac1bf6162e3d37d005e58bc2ee74e"));+ assert!(!is_registry_version(""));+ }+/// 回归 issue #715:`dsh plugin` 把动作之后的参数原样转发给 pnpm,动作动词因此/// 只能出现一次。升级/卸载曾把动词同时放进 `action` 与 `sub_args`,实际执行/// `pnpm remove remove <id>`、`pnpm update update <id> --latest`。@@ -739,7 +1244,11 @@ mod tests {vec!["plugin", "--profile", "tauri", "remove", "dshmarket"]);- let update = single_plugin_args("tauri", "update", &update_pnpm_args("dsh-better-sidebar"));+ let update = single_plugin_args(+ "tauri",+ "update",+ &update_pnpm_args(&["dsh-better-sidebar".to_string()]),+ );assert_eq!(update,vec![diff --git a/src-tauri/src/service/plugin/install/spec.rs b/src-tauri/src/service/plugin/install/spec.rsindex b5e3e5b3..7dfed702 100644--- a/src-tauri/src/service/plugin/install/spec.rs+++ b/src-tauri/src/service/plugin/install/spec.rs@@ -2,13 +2,67 @@//! 盘符绝对路径会按相对解析)、GitHub 简写规范化(绕开 pnpm 的 HTTPS→SSH 回退//! 缺陷)与 Windows 下含空格 spec 的引号化(dsh CLI 只在 win32 用 shell 拼接参数)。-use std::path::PathBuf;+use std::path::{Path, PathBuf};use tauri::AppHandle;use super::bundled_dep_spec;use super::bundled_plugin_dir;use super::PreinstallPluginInfo;+/// 从安装 spec 解析包名,供「产物核验」与「入口补构建」定位+/// `node_modules/<name>`。+///+/// - `link:` / `file:` 本地依赖:读目标目录的 `package.json` 的 `name`(最准确),+/// 读不到时回落目录名(pnpm 落盘的目录名通常是包名,但 `link:` 目标目录名未必+/// 与包名一致,故以清单为准);+/// - npm 形态(含 scoped):剥离末尾 `@版本/区间`,`@scope/name` 里的 `@` 不算分隔符;+/// - git / URL / 其他含 `:` 或空白的形态:install 后的目录名无法静态得知,返回 `None`+/// ——调用方跳过产物核验而不是把 `node_modules/<整条 spec>` 当成必然缺失。+pub(super) fn package_name_of_spec(spec: &str) -> Option<String> {+ for prefix in ["link:", "file:"] {+ if let Some(path) = spec.strip_prefix(prefix) {+ return local_package_name(Path::new(path.trim()));+ }+ }+ if spec.contains(':') || spec.contains(char::is_whitespace) {+ return None;+ }+ let name = package_name_of_npm_spec(spec);+ if name.is_empty() {+ None+ } else {+ Some(name.to_string())+ }+}++/// `link:` / `file:` 目标目录的包名:优先读其 `package.json`,回落目录名。+fn local_package_name(path: &Path) -> Option<String> {+ if let Ok(content) = std::fs::read_to_string(path.join("package.json")) {+ if let Ok(value) = serde_json::from_str::<serde_json::Value>(&content) {+ if let Some(name) = value.get("name").and_then(|v| v.as_str()) {+ if !name.is_empty() {+ return Some(name.to_string());+ }+ }+ }+ }+ path.file_name().map(|s| s.to_string_lossy().into_owned())+}++/// 剥离 `name@range` 的版本后缀:scoped 包只在 `@scope/` 的斜杠之后寻找 `@`,+/// 否则 `@scope/name` 会被从首个 `@` 切开得到空包名。+fn package_name_of_npm_spec(spec: &str) -> &str {+ let search_from = if spec.starts_with('@') {+ spec.find('/').map_or(spec.len(), |i| i + 1)+ } else {+ 0+ };+ match spec[search_from..].find('@') {+ Some(offset) => spec[..search_from + offset].trim_end_matches('@'),+ None => spec,+ }+}+/// 内置插件才需要解析捆绑目录(普通插件无此概念),避免无谓的资源探测pub(super) fn bundled_dir_of(app_handle: &AppHandle,diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex 5f8dcf9b..2ed19e70 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -33,6 +33,7 @@//! - [`watch`]:已安装插件文件监控(轮询指纹比对 + `dsh-plugins-updated` 事件推送)mod cancel;+pub mod compat;pub mod disable;pub mod errors;mod install;@@ -55,8 +56,8 @@ pub(crate) use cancel::terminate_active_installs_blocking;pub(crate) use install::harness_prefer_bundled_pnpm;pub(crate) use install::uninstall_deprecated_plugins;pub use install::{- allow_policy_versions, allow_version_exemptions, install, remove, update, IncompatibleVersion,- PolicyBlockedVersion,+ 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,diff --git a/src-tauri/src/service/plugin/update.rs b/src-tauri/src/service/plugin/update.rsindex 03cebaa6..7883539b 100644--- a/src-tauri/src/service/plugin/update.rs+++ b/src-tauri/src/service/plugin/update.rs@@ -427,7 +427,10 @@ fn is_upgrade(installed: &str, latest: &str) -> bool {}/// 把 npm 包名编码为 registry 路径(`@scope/name` → `@scope%2Fname`)。-fn encode_registry_name(name: &str) -> String {+///+/// `pub(crate)`:插件 spec 兼容性检查(`install::inspect`)需要读同一个 registry,+/// 复用这里的编码与请求形状,避免两处 URL 拼装漂移。+pub(crate) fn encode_registry_name(name: &str) -> String {name.replace('@', "%40").replace('/', "%2F")}@@ -435,7 +438,8 @@ fn encode_registry_name(name: &str) -> String {// 网络判定// ----------------------------------------------------------------------------async fn fetch_json(client: &reqwest::Client, url: &str) -> Option<Value> {+/// registry/API 的 JSON GET(非 2xx 与网络错误统一返回 `None`)。+pub(crate) async fn fetch_json(client: &reqwest::Client, url: &str) -> Option<Value> {let res = client.get(url).header("accept", "application/json")diff --git a/src-tauri/src/service/profile/mod.rs b/src-tauri/src/service/profile/mod.rsindex 472d5f52..b0269744 100644--- a/src-tauri/src/service/profile/mod.rs+++ b/src-tauri/src/service/profile/mod.rs@@ -186,10 +186,11 @@ pub(crate) fn profile_release_age_excluded(app_handle: &AppHandle, entry: &str)/// 把用户明确授权过的精确 `包名@版本` 追加进档案的 `minimumReleaseAgeExclude`。///-/// pnpm 的发布时长策略(`minimumReleaseAge`,11 默认 24 小时)在解析与 lockfile 校验-/// 两处都会拦下太新的版本;档案一旦声明了这样的版本,**每次**插件操作都会失败。用户-/// 在界面上确认接受这些精确版本后走这里:写的是精确条目,只让列出的版本过闸,其余-/// 解析照旧受窗口约束;已存在的条目不会重复写。+/// pnpm 的发布时长策略(`minimumReleaseAge`,11 默认 24 小时)只被**解析**阶段采信:+/// 写进豁免清单能让 pnpm 解析到这个版本,也能让此后 `pnpm install` 的 lockfile 校验+/// 放行**豁免清单里的精确条目**(实测:无豁免时校验阶段硬失败,补上豁免后通过)。+/// 用户授权与「太新条目早已在 lock 里」的自愈(`install::heal_locked_release_age`)都走+/// 这里:写的是精确条目,只让列出的版本过闸,其余解析照旧受窗口约束;已存在的不重复写。pub(crate) fn allow_profile_release_age(app_handle: &AppHandle,entries: &[String],@@ -377,7 +378,15 @@ pub fn create(app_handle: &AppHandle, name: &str) -> Result<Profile, String> {if dir.is_dir() {return Err(format!("PROFILE_EXISTS: profile {id} already exists"));}- init_profile_dir(&dir, &id)?;+ if let Err(error) = init_profile_dir(&dir, &id) {+ // 初始化中途失败会留下半成品目录,此后同名档案永远撞上 `PROFILE_EXISTS`:用户+ // 反复看到的只有「创建档案失败」,真实原因再也复现不出来。目录是本函数刚刚+ // 创建的(上面已确认不存在),因此整体回滚,让重试与首次尝试完全等价。+ if let Err(cleanup) = fs::remove_dir_all(&dir) {+ log::warn!("failed to roll back the half-initialized profile {id}: {cleanup}");+ }+ return Err(error);+ }Ok(Profile {id,name: trimmed.to_string(),diff --git a/src/hooks/use-plugins-manager.ts b/src/hooks/use-plugins-manager.tsnew file mode 100644index 00000000..d9721bb1--- /dev/null+++ b/src/hooks/use-plugins-manager.ts@@ -0,0 +1,124 @@+import type {+ Plugin,+ PluginManagerLog,+ PluginProcess,+ PluginProcessResult,+ PluginRef,+ PluginSearchResult,+ PluginsManagerRuntime,+} from '@/store/modules/plugins'+import type { PluginsManagerEvent, PluginsManagerEventMap } from '@/store/modules/plugins/events'+import type { DshPlugin } from '@/types'+import { useMount, useWatch } from '@reause/core'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import { invoke } from '@tauri-apps/api/core'+import { useStore } from 'valtio-define'+import { queryKeys } from '@/config/query-keys'+import { useListen } from '@/hooks/use-listen'+import { plugins } from '@/store/modules/plugins'++export interface UseDshPluginsManagerOptions {+ toast?: boolean+ restartOnSettle?: boolean+}++export interface UseDshPluginsManagerResult {+ installed: Plugin[]+ processes: PluginProcess[]+ pendingApprovals: PluginProcess[]+ logs: PluginManagerLog[]+ loading: boolean+ cancelling: boolean+ error: string+ refresh: () => Promise<void>+ setInstalled: (list: DshPlugin[]) => void+ install: (refs: PluginRef | PluginRef[]) => Promise<PluginProcessResult[]>+ upgrade: (refs: PluginRef | PluginRef[]) => Promise<PluginProcessResult[]>+ uninstall: (refs: PluginRef | PluginRef[]) => Promise<PluginProcessResult[]>+ disable: (refs: PluginRef | PluginRef[]) => Promise<PluginProcessResult[]>+ enable: (+ refs: PluginRef | PluginRef[],+ options?: { clearConfigOverride?: boolean },+ ) => Promise<PluginProcessResult[]>+ approve: (refs?: PluginRef | PluginRef[]) => Promise<PluginProcessResult[]>+ reject: (ref: PluginRef) => Promise<PluginProcessResult[]>+ cancel: () => Promise<void>+ search: (refs: PluginRef | PluginRef[], options?: { dsh?: string }) => Promise<PluginSearchResult[]>+ on: (+ event: PluginsManagerEvent,+ handler: (payload: PluginsManagerEventMap[PluginsManagerEvent]) => void,+ ) => () => void+}++export function useDshPluginsManager(options: UseDshPluginsManagerOptions = {}): UseDshPluginsManagerResult {+ const runtime: PluginsManagerRuntime = {+ toast: options.toast ?? true,+ restartOnSettle: options.restartOnSettle ?? true,+ }+ const snapshot = useStore(plugins)+ const queryClient = useQueryClient()+ const { data, isLoading, error } = useQuery({+ queryKey: queryKeys.plugins,+ queryFn: () => invoke<DshPlugin[]>('get_dsh_plugins'),+ })++ async function run(+ type: 'install' | 'upgrade' | 'uninstall' | 'disable' | 'enable',+ refs: PluginRef | PluginRef[],+ enableOptions?: { clearConfigOverride?: boolean },+ ): Promise<PluginProcessResult[]> {+ const results = await plugins.enqueue(type, refs, {+ ...runtime,+ clearConfigOverride: enableOptions?.clearConfigOverride ?? runtime.clearConfigOverride ?? false,+ })+ void queryClient.invalidateQueries({ queryKey: queryKeys.plugins })+ return results+ }++ useWatch(+ [data],+ () => {+ if (data)+ plugins.setInstalled(data)+ },+ { immediate: true },+ )++ useMount(() => {+ void plugins.refresh()+ })+ useListen<{ line: string }>('preinstall-log', (event) => {+ plugins.setProgressDetail(event.payload.line)+ })++ function on<K extends PluginsManagerEvent>(+ event: K,+ handler: (payload: PluginsManagerEventMap[K]) => void,+ ): () => void {+ return plugins.on(event, handler)+ }++ return {+ installed: [...snapshot.installed],+ processes: [...snapshot.processes] as PluginProcess[],+ pendingApprovals: [...snapshot.pendingApprovals] as PluginProcess[],+ logs: [...snapshot.logs],+ loading: isLoading,+ cancelling: snapshot.cancelling,+ error: error ? String(error) : '',+ refresh: async () => {+ await plugins.refresh()+ },+ setInstalled: list => plugins.setInstalled(list),+ install: refs => run('install', refs),+ upgrade: refs => run('upgrade', refs),+ uninstall: refs => run('uninstall', refs),+ disable: refs => run('disable', refs),+ enable: (refs, enableOptions) => run('enable', refs, enableOptions),+ approve: refs => plugins.approve(refs),+ reject: ref => plugins.reject(ref),+ cancel: () => plugins.cancel(),+ search: (refs, searchOptions) => plugins.search(refs, searchOptions),+ on,+ }+}diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex 6c5904c8..1ad67f98 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -43,7 +43,6 @@"preinstall.policy_desc": "pnpm skips releases younger than 24 hours. Authorising the checked ones records the exemption and re-runs the install.","preinstall.load_failed": "Failed to load preinstall plugin list","preinstall.empty": "No preinstalled plugins available.",- "preinstall.settings_title": "Recommended Plugins","preinstall.settings_hint": "Reopen the preset wizard to re-select or install recommended plugins.","preinstall.restarting_hint": "[harness] Restarting the service, please wait…","preinstall.open_preset": "Open Preset",@@ -194,6 +193,11 @@"profiles.activate_restart_hint": "Takes effect after the service restarts. Restart now?","profiles.activate_failed": "Failed to switch to {{name}}","profiles.create_failed": "Failed to create profile",+ "profiles.name_invalid_hint": "Profile names accept letters, digits, \"-\" and \"_\" only — non-Latin characters are dropped, try an English or pinyin name",+ "profiles.error_empty_name": "Enter a profile name first",+ "profiles.error_name_too_long": "The profile name is too long — 64 characters at most",+ "profiles.error_reserved": "That name is reserved by the system, pick another one",+ "profiles.error_not_found": "The profile to clone no longer exists","profiles.remove": "Delete","profiles.remove_confirm_title": "Delete profile","profiles.remove_confirm_desc": "Delete {{name}} permanently? Its plugins and settings will be removed. This cannot be undone.",@@ -263,18 +267,15 @@"plugins.abnormal_desc": "Plugin {{name}} is abnormal and may be corrupted or incompatible with the current environment.","plugins.remove_confirm_title": "Uninstall plugin","plugins.remove_confirm_desc": "Uninstall {{name}}? Its features will no longer be available after removal.",- "plugins.remove_failed": "Failed to uninstall {{name}}",- "plugins.upgrade_failed": "Failed to upgrade {{name}}","plugins.blocked_incompatible_title": "{{name}} is incompatible with the current core","plugins.blocked_incompatible_desc": "Rejected version: {{blocked}} (running it may crash or lose data). Authorising records the exemption and retries.","plugins.blocked_policy_title": "{{name}}'s update is blocked by the release-age window","plugins.blocked_policy_desc": "Blocked version: {{blocked}} (published under 24 hours ago, so pnpm skips it). Authorising records the exemption and retries.","plugins.hold_title": "{{name}} was not upgraded","plugins.hold_desc": "{{blocked}} is still inside the release-age window (pnpm skips it). Authorising records the exemption and retries.",- "plugins.hold_pinned_desc": "No new version to authorise: the profile pins the source (a catalog/git/link or exact spec), so `--latest` cannot move past it. The plugin itself is fine.",+ "plugins.hold_pinned_desc": "Authorised and explicitly reinstalled, but the profile still pins this plugin's source (catalog / git / link or an exact spec), so pnpm keeps the current version. The plugin itself is fine.",+ "plugins.hold_no_target": "No installable target version: the plugin's source is pinned, or npm reports no newer release. Reopen the panel to refresh the version list and try again.","plugins.authorize_failed": "Authorisation failed",- "plugins.updated_toast": "Plugin {{name}} updated",- "plugins.removed_toast": "Plugin {{name}} uninstalled","plugins.disable": "Disable","plugins.enable": "Enable","plugins.disabled_badge": "Disabled",@@ -298,12 +299,55 @@"plugins.restore_confirm_desc": "Restore {{name}} from its snapshot? Its current state will be replaced, and the Harness service will stop during restore.","plugins.restore_failed": "Failed to restore {{name}}","plugins.restore_restart_hint": "Plugin {{name}} restored — restart the service to continue",+ "plugins.queue_summary": "Plugin operations finished",+ "plugins.queue_summary_success": "{{count}} succeeded",+ "plugins.queue_summary_failed": "{{count}} failed",+ "plugins.queue_summary_skipped": "{{count}} unchanged","plugins.delete_snapshot": "Delete snapshot","plugins.snapshot_delete_title": "Delete snapshot","plugins.snapshot_delete_desc": "Delete the snapshot of {{name}}? This cannot be undone.","plugins.snapshot_delete_confirm": "Delete","plugins.snapshot_deleted_toast": "Snapshot of {{name}} deleted","plugins.snapshot_delete_failed": "Failed to delete snapshot of {{name}}",+ "plugins.log_enqueued": "Queued {{count}} plugin tasks",+ "plugins.action_failed": "Plugin task failed",+ "plugins.not_authorized": "{{name}} was not authorised",+ "plugins.retry_exhausted": "Gave up after too many authorisation attempts",+ "plugins.already_absent": "{{name}} is not installed",+ "plugins.not_installed": "{{name}} is not installed",+ "plugins.no_change": "{{name}} needs no change",+ "plugins.rejected": "Cancelled: authorisation was declined",+ "plugins.cancelled": "Cancelled",+ "plugins.progress_many": "Processing {{count}} plugins...",+ "plugins.progress_install_one": "Installing {{name}}...",+ "plugins.progress_install_many": "Installing {{count}} plugins...",+ "plugins.progress_upgrade_one": "Upgrading {{name}}...",+ "plugins.progress_upgrade_many": "Upgrading {{count}} plugins...",+ "plugins.progress_uninstall_one": "Uninstalling {{name}}...",+ "plugins.progress_uninstall_many": "Uninstalling {{count}} plugins...",+ "plugins.progress_disable_one": "Disabling {{name}}...",+ "plugins.progress_disable_many": "Disabling {{count}} plugins...",+ "plugins.progress_enable_one": "Enabling {{name}}...",+ "plugins.progress_enable_many": "Enabling {{count}} plugins...",+ "plugins.result_install_success": "Plugin {{name}} installed",+ "plugins.result_install_failed": "Failed to install {{name}}",+ "plugins.result_upgrade_success": "Plugin {{name}} upgraded",+ "plugins.result_upgrade_failed": "Failed to upgrade {{name}}",+ "plugins.result_uninstall_success": "Plugin {{name}} uninstalled",+ "plugins.result_uninstall_failed": "Failed to uninstall {{name}}",+ "plugins.result_disable_success": "Plugin {{name}} disabled",+ "plugins.result_disable_failed": "Failed to disable {{name}}",+ "plugins.result_enable_success": "Plugin {{name}} enabled",+ "plugins.result_enable_failed": "Failed to enable {{name}}",+ "plugins.install": "Install",+ "plugins.install_placeholder": "Enter a plugin package or spec (comma-separated for multiple)",+ "plugins.search_incompatible": "These plugins are incompatible with the current core: {{names}}",+ "plugins.search_incompatible_badge": "Incompatible",+ "plugins.search_invalid_spec": "Invalid spec",+ "plugins.search_not_found": "Not found in registry",+ "plugins.search_network": "Registry lookup failed",+ "plugins.search_unsupported": "Source not supported yet",+ "plugins.search_unknown": "Check failed","core.title": "Harness Core","core.refresh": "Refresh","core.refreshed_toast": "Core list refreshed",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex f67a7e47..96c6a08b 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -43,7 +43,6 @@"preinstall.policy_desc": "pnpm 默认不解析发布不足 24 小时的新版本。勾选授权后写入豁免并重跑安装。","preinstall.load_failed": "预装插件列表加载失败","preinstall.empty": "暂无可预装的插件。",- "preinstall.settings_title": "预装插件","preinstall.settings_hint": "重新打开预设引导,可重新选择或安装推荐的插件。","preinstall.restarting_hint": "[harness] 正在重启服务,请稍候…","preinstall.open_preset": "打开预设",@@ -194,6 +193,11 @@"profiles.activate_restart_hint": "重启服务后生效,是否立即重启?","profiles.activate_failed": "切换档案 {{name}} 失败","profiles.create_failed": "创建档案失败",+ "profiles.name_invalid_hint": "档案名只能用字母、数字、- 和 _:中文等字符会被丢弃,请改用英文或拼音",+ "profiles.error_empty_name": "请先输入档案名",+ "profiles.error_name_too_long": "档案名太长,最多 64 个字符",+ "profiles.error_reserved": "这个名字被系统保留,请换一个",+ "profiles.error_not_found": "找不到要克隆的档案,它可能已被删除","profiles.remove": "删除","profiles.remove_confirm_title": "删除档案","profiles.remove_confirm_desc": "确定删除档案 {{name}} 吗?将同时删除其插件与设置,此操作不可撤销。",@@ -263,18 +267,15 @@"plugins.abnormal_desc": "插件 {{name}} 运行异常,可能已损坏或与当前环境不兼容。","plugins.remove_confirm_title": "卸载插件","plugins.remove_confirm_desc": "确定卸载插件 {{name}} 吗?卸载后其功能将不可用。",- "plugins.remove_failed": "卸载插件 {{name}} 失败",- "plugins.upgrade_failed": "升级插件 {{name}} 失败","plugins.blocked_incompatible_title": "{{name}} 与当前核心不兼容","plugins.blocked_incompatible_desc": "被拒绝的版本:{{blocked}}(运行可能崩溃或丢数据)。授权后写入豁免并重试。","plugins.blocked_policy_title": "{{name}} 的更新被发布保护期拦下","plugins.blocked_policy_desc": "被挡住的版本:{{blocked}}(发布不足 24 小时,pnpm 默认不解析)。授权后写入豁免并重试。","plugins.hold_title": "{{name}} 的升级没有生效","plugins.hold_desc": "{{blocked}} 还在发布保护期内(pnpm 默认不解析),授权后写入豁免并重试。",- "plugins.hold_pinned_desc": "没有可授权的新版本:档案把来源钉死了(catalog / git / link 或精确版本),`--latest` 越不过声明范围。插件本身没有损坏。",+ "plugins.hold_pinned_desc": "已经授权并显式安装过目标版本,但档案仍把该插件钉在固定来源(catalog / git / link 或精确版本),pnpm 保持不变。插件本身没有损坏。",+ "plugins.hold_no_target": "没有可安装的目标版本:插件来源被钉死,或 npm 上没有更新的版本。重新打开插件面板刷新版本列表后再试。","plugins.authorize_failed": "授权失败",- "plugins.updated_toast": "插件 {{name}} 已更新",- "plugins.removed_toast": "插件 {{name}} 已卸载","plugins.disable": "禁用","plugins.enable": "启用","plugins.disabled_badge": "已禁用",@@ -298,12 +299,55 @@"plugins.restore_confirm_desc": "将插件 {{name}} 还原到快照状态?当前状态将被替换,还原期间 Harness 服务会停止。","plugins.restore_failed": "还原插件 {{name}} 失败","plugins.restore_restart_hint": "插件 {{name}} 已还原 — 重启服务以继续使用",+ "plugins.queue_summary": "插件操作已完成",+ "plugins.queue_summary_success": "{{count}} 个成功",+ "plugins.queue_summary_failed": "{{count}} 个失败",+ "plugins.queue_summary_skipped": "{{count}} 个无需变更","plugins.delete_snapshot": "删除快照","plugins.snapshot_delete_title": "删除快照","plugins.snapshot_delete_desc": "删除插件 {{name}} 的快照?此操作不可撤销。","plugins.snapshot_delete_confirm": "删除","plugins.snapshot_deleted_toast": "插件 {{name}} 的快照已删除","plugins.snapshot_delete_failed": "删除插件 {{name}} 的快照失败",+ "plugins.log_enqueued": "已排队 {{count}} 个插件任务",+ "plugins.action_failed": "插件任务执行失败",+ "plugins.not_authorized": "{{name}} 未获授权",+ "plugins.retry_exhausted": "授权重试次数已达上限",+ "plugins.already_absent": "{{name}} 未安装",+ "plugins.not_installed": "{{name}} 未安装",+ "plugins.no_change": "{{name}} 无需变更",+ "plugins.rejected": "已取消:用户拒绝授权",+ "plugins.cancelled": "已取消",+ "plugins.progress_many": "正在处理 {{count}} 个插件...",+ "plugins.progress_install_one": "正在安装 {{name}}...",+ "plugins.progress_install_many": "正在安装 {{count}} 个插件...",+ "plugins.progress_upgrade_one": "正在升级 {{name}}...",+ "plugins.progress_upgrade_many": "正在升级 {{count}} 个插件...",+ "plugins.progress_uninstall_one": "正在卸载 {{name}}...",+ "plugins.progress_uninstall_many": "正在卸载 {{count}} 个插件...",+ "plugins.progress_disable_one": "正在禁用 {{name}}...",+ "plugins.progress_disable_many": "正在禁用 {{count}} 个插件...",+ "plugins.progress_enable_one": "正在启用 {{name}}...",+ "plugins.progress_enable_many": "正在启用 {{count}} 个插件...",+ "plugins.result_install_success": "插件 {{name}} 安装完成",+ "plugins.result_install_failed": "安装插件 {{name}} 失败",+ "plugins.result_upgrade_success": "插件 {{name}} 升级完成",+ "plugins.result_upgrade_failed": "升级插件 {{name}} 失败",+ "plugins.result_uninstall_success": "插件 {{name}} 已卸载",+ "plugins.result_uninstall_failed": "卸载插件 {{name}} 失败",+ "plugins.result_disable_success": "插件 {{name}} 已禁用",+ "plugins.result_disable_failed": "禁用插件 {{name}} 失败",+ "plugins.result_enable_success": "插件 {{name}} 已启用",+ "plugins.result_enable_failed": "启用插件 {{name}} 失败",+ "plugins.install": "安装",+ "plugins.install_placeholder": "输入插件包名或 spec(可逗号分隔多个)",+ "plugins.search_incompatible": "以下插件与当前核心不兼容:{{names}}",+ "plugins.search_incompatible_badge": "不兼容",+ "plugins.search_invalid_spec": "无效的 spec",+ "plugins.search_not_found": "未在仓库中找到",+ "plugins.search_network": "联网查询失败",+ "plugins.search_unsupported": "暂不支持该来源",+ "plugins.search_unknown": "检查失败","core.title": "核心引擎","core.refresh": "刷新","core.refreshed_toast": "核心列表已刷新",diff --git a/src/layout/components/setup-preinstall.tsx b/src/layout/components/setup-preinstall.tsxindex b067d53e..d66a7646 100644--- a/src/layout/components/setup-preinstall.tsx+++ b/src/layout/components/setup-preinstall.tsx@@ -1,4 +1,5 @@-import type { IncompatibleVersion, PreinstallPlugin } from '@/store/modules/preinstall'+import type { PluginProcess } from '@/store/modules/plugins'+import type { PreinstallPlugin } from '@/store/modules/preinstall'import { ArrowUpRightFromSquare, Copy, PlugConnection, Xmark } from '@gravity-ui/icons'import { Button, Card, Checkbox, Chip, ScrollShadow, Spinner, Switch, Typography } from '@heroui/react'import { useMount } from '@reause/core'@@ -10,12 +11,14 @@ import { useStore } from 'valtio-define'import { Ellipsis } from '@/components/ellipsis'import { Empty } from '@/components/empty'import { Logs } from '@/components/logs'+import { useListen } from '@/hooks/use-listen'+import { useDshPluginsManager } from '@/hooks/use-plugins-manager'import { store } from '@/store'import { writeClipboardText } from '@/utils/clipboard'/*** 预装插件引导页:首次安装(或老版本升级)后展示推荐插件列表,- * 用户确认后调用 `dsh plugin` 安装(日志实时回流到控制台),+ * 用户确认后交由插件管理器执行安装/卸载(日志实时回流到控制台),* 或跳过;两者都会标记完成并继续启动服务。*/@@ -165,25 +168,41 @@ function LogPanel({ logs }: { logs: readonly string[] }) {)}+/** 被拒进程展示的精确版本清单:授权按精确 `包名@版本` 生效,因此原样展示 */+function refusedVersions(process: PluginProcess): string {+ return (process.refusal?.versions ?? []).map(item => `${item.name}@${item.version}`).join('、')+}+export function PreinstallSetup() {const { t } = useTranslation()const preinstall = useStore(store.preinstall)+ // 引导页不自行提示(toast: false)也不自行重启(restartOnSettle: false):+ // 提示权在页面,重启由收尾的 continueStartup 统一做一次+ const manager = useDshPluginsManager({ toast: false, restartOnSettle: false })// 用户手动调整后的选择(一旦交互即接管默认勾选)const [selected, setSelected] = useState<Set<string>>(() => new Set())const [touched, setTouched] = useState(false)- // 版本豁免的勾选集合:默认全不勾——「可能导致崩溃或数据丢失」的风险必须由用户- // 明确接受,不想装这些插件的人有「跳过」可走+ // 授权勾选集合:被拒插件必须由用户明确接受风险,不想装的人可以「跳过」退出const [allowed, setAllowed] = useState<Set<string>>(() => new Set())- // 授权进行中:逐条起 dsh 进程写兼容性豁免,期间禁用按钮并显示加载态+ // 授权进行中:写豁免期间禁用按钮并显示加载态const [granting, setGranting] = useState(false)- const blocked = preinstall.incompatible- const policyBlocked = preinstall.policyBlocked+ // 本轮提交的失败明细(管理器以 ok:false 表达失败,不抛异常)+ const [failures, setFailures] = useState<string[]>([])++ const approvals = manager.pendingApprovals+ const incompatibleApprovals = approvals.filter(process => process.refusal?.kind === 'incompatible')+ const policyApprovals = approvals.filter(process => process.refusal?.kind !== 'incompatible')// 进入引导页时拉取插件列表(仅挂载一次,无需清理)useMount(() => {void store.preinstall.load()})+ // dsh plugin 进程输出经 `preinstall-log` 回流;卸载即注销,不残留监听+ useListen<{ line: string }>('preinstall-log', (event) => {+ store.preinstall.pushLog(event.payload.line)+ })+// 默认勾选:已安装 + 未安装的推荐插件 +「修复」类项 + 无 chip 但标记默认勾选的项(如 dsh-notification)。// 派生计算而非在加载回调里 setState,避免与 store 的加载去重守卫竞争,// 保证插件到位后默认勾选必定生效(用户手动调整后以用户选择为准)。@@ -191,18 +210,6 @@ export function PreinstallSetup() {? initialCheckedSet(preinstall.plugins, preinstall.isFirstTime): selected- /**- * 拦截项在勾选集合里的键:必须带上运行时版本。- *- * 豁免是按「精确包名@版本 + 运行时版本」三元组生效的,解析结果也按三元组去重,因此- * `name@version` 相同、运行时不同的两条是两条不同的授权。只用 `name@version` 当键会让- * 勾选一行连带授权另一行(把别的运行时的豁免也一起写下去,dsh 只会拒绝它)。- * 展示给用户的标签仍是 `name@version`,键只在内部用。- */- function incompatibleKey(item: IncompatibleVersion) {- return JSON.stringify([item.name, item.version, item.runtime_version])- }-function toggle(id: string, checked: boolean) {// 首次交互以「当前默认勾选」为起点:selected 初始为空,若直接在其上增删,// 取消一个会误把其余默认项一并取消。这里先以 initialCheckedSet 播种,@@ -227,7 +234,18 @@ export function PreinstallSetup() {})}- function handleConfirm() {+ /**+ * 汇总一组进程结果里的失败明细,供错误面板展示。+ * `already-absent` 是卸载的「已达成的目标」(插件本就不在 profile),`cancelled` 是用户+ * 自己按下的取消,两者都不是需要用户重试的失败。+ */+ function collectFailures(results: Awaited<ReturnType<typeof manager.install>>): string[] {+ return results+ .filter(result => !result.ok && result.reason !== 'already-absent' && result.reason !== 'cancelled')+ .map(result => `${result.process.name}: ${result.error ?? ''}`)+ }++ async function handleConfirm() {// 基于 plugin.installed 推导操作:选中且未安装 → 安装;已安装且未选中 → 卸载const toInstall = preinstall.plugins.filter(p => effectiveSelected.has(p.id) && !p.installed)@@ -235,46 +253,57 @@ export function PreinstallSetup() {const toUninstall = preinstall.plugins.filter(p => p.installed && !effectiveSelected.has(p.id) && !p.unsupported).map(p => p.id)- void store.preinstall.confirm({ installIds: toInstall, uninstallIds: toUninstall })+ setFailures([])+ const failed: string[] = []+ // 卸载在前:避免新装插件与待卸载插件冲突;两者各自成组,由队列保证先后+ if (toUninstall.length > 0)+ failed.push(...collectFailures(await manager.uninstall(toUninstall)))+ if (toInstall.length > 0)+ failed.push(...collectFailures(await manager.install(toInstall)))+ // 刷新 installed 标记:卸载已生效但安装失败时,重试的 diff 必须基于新状态,+ // 否则已移除的插件会再次被当作待卸载项,重试永远不会成功。+ await store.preinstall.load()+ if (failed.length > 0) {+ setFailures(failed)+ return+ }+ // 未产生任何变更时也要标记完成,否则引导页每轮启动都会再次弹出+ await store.preinstall.finish()}function handleSkip() {void store.preinstall.skip()}- function toggleAllowed(key: string, checked: boolean) {+ function toggleAllowed(id: string, checked: boolean) {setAllowed((prev) => {const next = new Set(prev)if (checked) {- next.add(key)+ next.add(id)}else {- next.delete(key)+ next.delete(id)}return next})}+/**- * 授权勾选的精确版本后重跑安装。+ * 授权勾选的风险项并续传。** 豁免只对「精确的包名@版本(+ 运行时版本)」生效、且不随插件或核心升级继承,因此- * 必须真的重跑一次由 dsh 复核,不能假定授权即放行。- *- * 授权要逐条起进程(dsh 的 allow-version、或写档案豁免清单),期间用 granting 给出- * 按钮反馈:这段等待既没有安装日志也没有列表变化,否则点完像没反应。+ * 必须真的重跑一次由 dsh 复核,不能假定授权即放行——`approve` 内部写豁免后会把+ * 剩余集合重新提交,返回的 Promise 在整组结算后才 Resolve。*/- async function handleGrant<T extends { name: string, version: string }>(- items: readonly T[],- keyOf: (item: T) => string,- grant: (selected: T[]) => Promise<boolean>,- ) {- const versions = items.filter(item => allowed.has(keyOf(item)))- if (granting || versions.length === 0)+ async function handleGrant(targets: PluginProcess[]) {+ const picked = targets.filter(process => allowed.has(process.id))+ if (granting || picked.length === 0)returnsetGranting(true)try {- if (await grant(versions))- handleConfirm()+ const failed = collectFailures(await manager.approve(picked.map(process => process.spec)))+ if (failed.length > 0)+ setFailures(failed)}finally {setGranting(false)@@ -285,7 +314,12 @@ export function PreinstallSetup() {const toInstallCount = preinstall.plugins.filter(p => effectiveSelected.has(p.id) && !p.installed).lengthconst toUninstallCount = preinstall.plugins.filter(p => p.installed && !effectiveSelected.has(p.id) && !p.unsupported).lengthconst hasChanges = toInstallCount > 0 || toUninstallCount > 0- const installing = preinstall.installing+ // 有进程在排队/执行中即视为安装中;但只要有待授权项就必须切到授权视图:整批被拒时+ // 未被点名的进程会回到 pending 等授权,若仍按「存在非 unauthorized 进程」判定,授权+ // 界面永远不会出现,用户只能取消。+ const installing = approvals.length === 0 && manager.processes.length > 0+ const blocked = approvals.length > 0+ const failing = failures.length > 0return (<div className="flex h-full w-full items-center justify-center bg-canvas">@@ -301,7 +335,7 @@ export function PreinstallSetup() {// 被核心版本拦截、被 pnpm 发布时长策略拦截(都可逐项授权)或安装失败时// 不叠加插件列表,只展示原因 + 日志 + 操作<If- cond={blocked.length > 0 || policyBlocked.length > 0 || preinstall.error !== ''}+ cond={blocked || failing}else={(<>{/* 卡片网格限定高度滚动,上下溢出由 ScrollShadow 渐隐提示 */}@@ -356,7 +390,7 @@ export function PreinstallSetup() {</ScrollShadow>{/* 可取消勾选提示:让用户知道预设插件可减选,取消后不会安装 */}- <If cond={preinstall.plugins.length > 0 && !installing && preinstall.error === ''}>+ <If cond={preinstall.plugins.length > 0 && !installing && !failing}><p className="text-center text-xs text-muted">{t('preinstall.can_uncheck_hint')}</p></If>@@ -396,109 +430,50 @@ export function PreinstallSetup() {</>)}>- {/* 安装失败:错误信息 + 日志 + 操作 */}<If- cond={blocked.length > 0}+ cond={blocked}else={(- // 发布时长策略拦截:档案已声明太新的版本,pnpm 的 minimumReleaseAge- // 不放行,不授权则每次插件操作都失败;同样逐项授权后重跑- <If- cond={policyBlocked.length > 0}- else={(- <div className="flex flex-col gap-2.5">- <div className="flex flex-col gap-2 rounded-md border border-danger/30 bg-danger/5 p-3">- <p className="text-xs font-medium text-danger">{t('preinstall.failed')}</p>- <p className="max-h-[120px] overflow-y-auto break-all font-mono text-[11px] leading-relaxed text-muted">- {preinstall.error}- </p>- </div>- <LogPanel logs={preinstall.logs} />- <div className="flex items-center justify-end gap-2">- <Button className="h-8 rounded-md" size="sm" variant="tertiary" onPress={handleSkip} isDisabled={installing}>- {t('preinstall.skip')}- </Button>- <Button- className="h-8 rounded-md"- size="sm"- variant="primary"- onPress={handleConfirm}- isDisabled={installing || !hasChanges}- >- {t('app.retry')}- </Button>- </div>- </div>- )}- >- <div className="flex flex-col gap-2.5">- <div className="flex flex-col gap-2 rounded-md border border-warning/30 bg-warning/5 p-3">- <p className="text-xs font-medium text-warning">{t('preinstall.policy_title')}</p>- <p className="text-[11px] leading-relaxed text-muted">{t('preinstall.policy_desc')}</p>- <div className="mt-0.5 flex flex-col gap-1.5">- {policyBlocked.map((item) => {- const key = `${item.name}@${item.version}`- return (- <label key={key} className="flex cursor-pointer items-center gap-2">- <Checkbox- className="shrink-0"- isSelected={allowed.has(key)}- onChange={(value: boolean) => toggleAllowed(key, value)}- aria-label={key}- >- <Checkbox.Content>- <Checkbox.Control>- <Checkbox.Indicator />- </Checkbox.Control>- </Checkbox.Content>- </Checkbox>- <span className="font-mono text-[11px] text-ink">{key}</span>- </label>- )- })}- </div>- </div>- <LogPanel logs={preinstall.logs} />- <div className="flex items-center justify-end gap-2">- <Button className="h-8 rounded-md" size="sm" variant="tertiary" onPress={handleSkip} isDisabled={installing || granting}>- {t('preinstall.skip')}- </Button>- <Button- className="h-8 rounded-md"- size="sm"- variant="primary"- onPress={() => void handleGrant(policyBlocked, item => `${item.name}@${item.version}`, versions => store.preinstall.allowPolicyVersions(versions))}- isDisabled={installing || granting || allowed.size === 0}- >- <If cond={granting}>- <Spinner size="sm" color="current" />- <span>{t('preinstall.granting')}</span>- </If>- <If cond={!granting}>- <span>{t('preinstall.confirm')}</span>- </If>- </Button>- </div>+ // 安装失败:错误信息 + 日志 + 操作+ <div className="flex flex-col gap-2.5">+ <div className="flex flex-col gap-2 rounded-md border border-danger/30 bg-danger/5 p-3">+ <p className="text-xs font-medium text-danger">{t('preinstall.failed')}</p>+ <p className="max-h-[120px] overflow-y-auto break-all font-mono text-[11px] leading-relaxed text-muted">+ {failures.join('\n')}+ </p></div>- </If>+ <LogPanel logs={preinstall.logs} />+ <div className="flex items-center justify-end gap-2">+ <Button className="h-8 rounded-md" size="sm" variant="tertiary" onPress={handleSkip} isDisabled={installing}>+ {t('preinstall.skip')}+ </Button>+ <Button+ className="h-8 rounded-md"+ size="sm"+ variant="primary"+ onPress={handleConfirm}+ isDisabled={installing || !hasChanges}+ >+ {t('app.retry')}+ </Button>+ </div>+ </div>)}>- {/* 版本兼容性拒绝:核心在 pnpm 之前拦下整批安装,插件与当前核心的- DSH peer 依赖不匹配;逐项授权精确版本(风险由用户明确承担)后重试 */}<div className="flex flex-col gap-2.5">- <div className="flex flex-col gap-2 rounded-md border border-danger/30 bg-danger/5 p-3">- <p className="text-xs font-medium text-danger">{t('preinstall.incompatible_title')}</p>- <p className="text-[11px] leading-relaxed text-muted">{t('preinstall.incompatible_desc')}</p>- <div className="mt-0.5 flex flex-col gap-1.5">- {blocked.map((item) => {- const label = `${item.name}@${item.version}`- const key = incompatibleKey(item)- return (- <label key={key} className="flex cursor-pointer items-center gap-2">+ {/* 版本兼容性拒绝:核心在 pnpm 之前拦下整批安装,插件与当前核心的+ DSH peer 依赖不匹配;逐项授权精确版本(风险由用户明确承担)后重试 */}+ <If cond={incompatibleApprovals.length > 0}>+ <div className="flex flex-col gap-2 rounded-md border border-danger/30 bg-danger/5 p-3">+ <p className="text-xs font-medium text-danger">{t('preinstall.incompatible_title')}</p>+ <p className="text-[11px] leading-relaxed text-muted">{t('preinstall.incompatible_desc')}</p>+ <div className="mt-0.5 flex flex-col gap-1.5">+ {incompatibleApprovals.map(process => (+ <label key={process.id} className="flex cursor-pointer items-center gap-2"><CheckboxclassName="shrink-0"- isSelected={allowed.has(key)}- onChange={(value: boolean) => toggleAllowed(key, value)}- aria-label={label}+ isSelected={allowed.has(process.id)}+ onChange={(value: boolean) => toggleAllowed(process.id, value)}+ aria-label={process.name}><Checkbox.Content><Checkbox.Control>@@ -506,23 +481,52 @@ export function PreinstallSetup() {</Checkbox.Control></Checkbox.Content></Checkbox>- <span className="font-mono text-[11px] text-ink">{label}</span>+ <span className="font-mono text-[11px] text-ink">{refusedVersions(process)}</span></label>- )- })}+ ))}+ </div></div>- </div>+ </If>++ {/* 发布时长策略 / 升级保留拦截:档案已声明太新的版本时每次插件操作都失败,+ 同样逐项授权后重跑 */}+ <If cond={policyApprovals.length > 0}>+ <div className="flex flex-col gap-2 rounded-md border border-warning/30 bg-warning/5 p-3">+ <p className="text-xs font-medium text-warning">{t('preinstall.policy_title')}</p>+ <p className="text-[11px] leading-relaxed text-muted">{t('preinstall.policy_desc')}</p>+ <div className="mt-0.5 flex flex-col gap-1.5">+ {policyApprovals.map(process => (+ <label key={process.id} className="flex cursor-pointer items-center gap-2">+ <Checkbox+ className="shrink-0"+ isSelected={allowed.has(process.id)}+ onChange={(value: boolean) => toggleAllowed(process.id, value)}+ aria-label={process.name}+ >+ <Checkbox.Content>+ <Checkbox.Control>+ <Checkbox.Indicator />+ </Checkbox.Control>+ </Checkbox.Content>+ </Checkbox>+ <span className="font-mono text-[11px] text-ink">{refusedVersions(process) || process.name}</span>+ </label>+ ))}+ </div>+ </div>+ </If>+<LogPanel logs={preinstall.logs} /><div className="flex items-center justify-end gap-2">- <Button className="h-8 rounded-md" size="sm" variant="tertiary" onPress={handleSkip} isDisabled={installing || granting}>+ <Button className="h-8 rounded-md" size="sm" variant="tertiary" onPress={handleSkip} isDisabled={granting}>{t('preinstall.skip')}</Button><ButtonclassName="h-8 rounded-md"size="sm"variant="primary"- onPress={() => void handleGrant(blocked, incompatibleKey, versions => store.preinstall.allowIncompatible(versions))}- isDisabled={installing || granting || allowed.size === 0}+ onPress={() => void handleGrant(approvals)}+ isDisabled={granting || allowed.size === 0}><If cond={granting}><Spinner size="sm" color="current" />@@ -551,11 +555,11 @@ export function PreinstallSetup() {className="h-8 rounded-md"size="sm"variant="tertiary"- onPress={store.preinstall.cancel}- isDisabled={preinstall.cancelling}+ onPress={() => void manager.cancel()}+ isDisabled={manager.cancelling || manager.processes.length === 0}><Xmark className="size-3.5" />- {preinstall.cancelling ? t('preinstall.cancelling') : t('preinstall.cancel')}+ {manager.cancelling ? t('preinstall.cancelling') : t('preinstall.cancel')}</Button></div></div>diff --git a/src/store/index.ts b/src/store/index.tsindex c74b719f..6246f524 100644--- a/src/store/index.ts+++ b/src/store/index.ts@@ -1,6 +1,7 @@import { desktopUpdater } from './modules/desktop-updater'import { harness } from './modules/harness'import { harnessUpdater } from './modules/harness-updater'+import { plugins } from './modules/plugins'import { preinstall } from './modules/preinstall'import { recovery } from './modules/recovery'import { remote } from './modules/remote'@@ -20,6 +21,7 @@ import { setting } from './modules/setting'export const store = {harness,harnessUpdater,+ plugins,preinstall,recovery,setting,diff --git a/src/store/modules/plugins/events.ts b/src/store/modules/plugins/events.tsnew file mode 100644index 00000000..c56d709f--- /dev/null+++ b/src/store/modules/plugins/events.ts@@ -0,0 +1,35 @@+import type { PluginProcess, PluginProcessResult } from './types'+import { createEventHook } from '@reause/core'++export interface PluginsManagerEventMap {+ completed: PluginProcessResult[]+ allcompleted: PluginProcessResult[]+ error: PluginProcessResult[]+ approve: PluginProcess+}++export type PluginsManagerEvent = keyof PluginsManagerEventMap++const hooks = {+ completed: createEventHook<PluginProcessResult[]>(),+ allcompleted: createEventHook<PluginProcessResult[]>(),+ error: createEventHook<PluginProcessResult[]>(),+ approve: createEventHook<PluginProcess>(),+}++type Trigger<K extends PluginsManagerEvent> = (payload: PluginsManagerEventMap[K]) => void+type Subscribe<K extends PluginsManagerEvent> = (handler: (payload: PluginsManagerEventMap[K]) => void) => () => void++export function triggerPluginsManagerEvent<K extends PluginsManagerEvent>(+ event: K,+ payload: PluginsManagerEventMap[K],+): void {+ ;(hooks[event] as unknown as { trigger: Trigger<K> }).trigger(payload)+}++export function onPluginsManagerEvent<K extends PluginsManagerEvent>(+ event: K,+ handler: (payload: PluginsManagerEventMap[K]) => void,+): () => void {+ return (hooks[event] as unknown as { on: Subscribe<K> }).on(handler)+}diff --git a/src/store/modules/plugins/index.ts b/src/store/modules/plugins/index.tsnew file mode 100644index 00000000..e0a9e9f6--- /dev/null+++ b/src/store/modules/plugins/index.ts@@ -0,0 +1,19 @@+export { plugins } from './store'+export type {+ BlockedRefusal,+ Plugin,+ PluginGroup,+ PluginManagerLog,+ PluginProcess,+ PluginProcessReason,+ PluginProcessResult,+ PluginProcessStatus,+ PluginProcessType,+ PluginRef,+ PluginSearchProblem,+ PluginSearchResult,+ PluginsManagerRuntime,+ PluginsState,+} from './types'+export { enrichInstalled, normalizeRef, normalizeRefs, parseBlockedRefusal, refusalNames } from './utils'+export type { NormalizedRef } from './utils'diff --git a/src/store/modules/plugins/store.ts b/src/store/modules/plugins/store.tsnew file mode 100644index 00000000..bb0f19ea--- /dev/null+++ b/src/store/modules/plugins/store.ts@@ -0,0 +1,733 @@+import type { PluginsManagerEvent, PluginsManagerEventMap } from './events'+import type {+ BlockedRefusal,+ Plugin,+ PluginGroup,+ PluginProcess,+ PluginProcessReason,+ PluginProcessResult,+ PluginProcessType,+ PluginRef,+ PluginSearchProblem,+ PluginSearchResult,+ PluginsManagerRuntime,+ PluginsState,+} from './types'+import type { DshPlugin } from '@/types'+import type { ToastCloseReason } from '@/utils/toast'+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, refusalNames } from './utils'++const LOG_LIMIT = 200+const MAX_ATTEMPTS = 8++const COMMANDS: Record<PluginProcessType, string> = {+ install: 'install_plugin_specs',+ upgrade: 'update_dsh_plugins',+ uninstall: 'remove_dsh_plugins',+ disable: 'disable_dsh_plugin',+ enable: 'enable_dsh_plugin',+}++const PROGRESS_ONE: Record<PluginProcessType, string> = {+ install: 'plugins.progress_install_one',+ upgrade: 'plugins.progress_upgrade_one',+ uninstall: 'plugins.progress_uninstall_one',+ disable: 'plugins.progress_disable_one',+ enable: 'plugins.progress_enable_one',+}++const PROGRESS_MANY: Record<PluginProcessType, string> = {+ install: 'plugins.progress_install_many',+ upgrade: 'plugins.progress_upgrade_many',+ uninstall: 'plugins.progress_uninstall_many',+ disable: 'plugins.progress_disable_many',+ enable: 'plugins.progress_enable_many',+}++const RESULT_SUCCESS: Record<PluginProcessType, string> = {+ install: 'plugins.result_install_success',+ upgrade: 'plugins.result_upgrade_success',+ uninstall: 'plugins.result_uninstall_success',+ disable: 'plugins.result_disable_success',+ enable: 'plugins.result_enable_success',+}++const RESULT_FAILED: Record<PluginProcessType, string> = {+ install: 'plugins.result_install_failed',+ upgrade: 'plugins.result_upgrade_failed',+ uninstall: 'plugins.result_uninstall_failed',+ disable: 'plugins.result_disable_failed',+ enable: 'plugins.result_enable_failed',+}++const BLOCK_TITLE: Record<BlockedRefusal['kind'], string> = {+ 'incompatible': 'plugins.blocked_incompatible_title',+ 'policy': 'plugins.blocked_policy_title',+ 'update-hold': 'plugins.hold_title',+}++const BLOCK_DESC: Record<BlockedRefusal['kind'], string> = {+ 'incompatible': 'plugins.blocked_incompatible_desc',+ 'policy': 'plugins.blocked_policy_desc',+ 'update-hold': 'plugins.hold_desc',+}++const NOOP_MESSAGE: Record<PluginProcessType, string> = {+ install: 'plugins.already_absent',+ upgrade: 'plugins.no_change',+ uninstall: 'plugins.already_absent',+ disable: 'plugins.no_change',+ enable: 'plugins.no_change',+}++interface PluginInspectPayload {+ spec: string+ name?: string+ version?: string+ compatible?: boolean | null+ peers?: Record<string, string>+ problem?: PluginSearchProblem+}++function nextGroupId(type: PluginProcessType): string {+ return `${type}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++function errorCode(message: string): string | undefined {+ return /^([A-Z][A-Z0-9_]+):/.exec(message)?.[1]+}++export const plugins = defineStore({+ state: (): PluginsState => ({+ groups: [],+ processes: [],+ logs: [],+ activeGroupId: null,+ cancelling: false,+ installedSource: [],+ installedLoaded: false,+ progressKey: null,+ progressDetail: '',+ queueResults: [],+ }),+ getters: {+ installed(): Plugin[] {+ return enrichInstalled(this.installedSource)+ },+ pendingApprovals(): PluginProcess[] {+ return this.processes.filter(process => process.status === 'unauthorized')+ },+ },+ actions: {+ pushLog(level: 'info' | 'error', message: string, groupId?: string, processId?: string): void {+ this.logs = [...this.logs, { at: Date.now(), level, message, groupId, processId }].slice(-LOG_LIMIT)+ },++ setInstalled(list: DshPlugin[]): void {+ this.installedSource = list+ this.installedLoaded = true+ },++ async refresh(): Promise<DshPlugin[]> {+ const list = await invoke<DshPlugin[]>('refresh_plugin_updates')+ this.setInstalled(list)+ return list+ },++ on<K extends PluginsManagerEvent>(+ event: K,+ handler: (payload: PluginsManagerEventMap[K]) => void,+ ): () => void {+ return onPluginsManagerEvent(event, handler)+ },++ enqueue(+ type: PluginProcessType,+ refs: PluginRef | PluginRef[],+ options: PluginsManagerRuntime,+ ): Promise<PluginProcessResult[]> {+ const normalized = normalizeRefs(refs)+ const groupId = nextGroupId(type)+ const created: PluginProcess[] = normalized.map((ref, index) => ({+ id: `${groupId}#${index}`,+ groupId,+ type,+ status: 'pending',+ spec: ref.spec,+ name: ref.name,+ ...(ref.version === undefined ? {} : { version: ref.version }),+ }))+ let resolveDone: (results: PluginProcessResult[]) => void = () => {}+ const done = new Promise<PluginProcessResult[]>((resolve) => {+ resolveDone = resolve+ })+ const group: PluginGroup = {+ id: groupId,+ type,+ status: 'pending',+ processIds: created.map(process => process.id),+ attempt: 0,+ pending: created.map(process => process.id),+ results: [],+ done,+ resolveDone,+ options,+ }+ this.processes = [...this.processes, ...created]+ this.groups = [...this.groups, group]+ this.pushLog('info', i18next.t('plugins.log_enqueued', { count: created.length }), groupId)+ this.syncProgress()+ void this.drain()+ return done+ },++ async drain(): Promise<void> {+ if (this.activeGroupId !== null)+ return+ const group = this.groups.find(item => item.status === 'pending')+ if (!group)+ return+ this.activeGroupId = group.id+ group.status = 'active'+ try {+ await this.runGroup(group)+ }+ finally {+ this.activeGroupId = null+ void this.drain()+ }+ },++ async runGroup(group: PluginGroup): Promise<void> {+ this.syncProgress()+ while (group.pending.length > 0) {+ const targets = group.pending+ .map(id => this.processes.find(process => process.id === id))+ .filter((process): process is PluginProcess => process !== undefined && process.status === 'pending')+ if (this.cancelling)+ break+ if (targets.length === 0) {+ this.hideProgress()+ await new Promise<void>((resolve) => {+ group.resume = resolve+ })+ group.resume = undefined+ this.syncProgress()+ continue+ }+ if (group.attempt >= MAX_ATTEMPTS) {+ targets.forEach((process) => {+ this.finish(group.id, process, {+ process,+ ok: false,+ error: i18next.t('plugins.retry_exhausted'),+ reason: 'retry-exhausted',+ })+ })+ break+ }+ const runnable: PluginProcess[] = []+ targets.forEach((process) => {+ const reason = this.precheck(process)+ if (reason === null) {+ runnable.push(process)+ return+ }+ this.finish(group.id, process, {+ process,+ ok: false,+ error: i18next.t(reason === 'not-installed' ? 'plugins.not_installed' : NOOP_MESSAGE[process.type], {+ name: process.name,+ }),+ reason,+ })+ })+ if (runnable.length === 0)+ continue+ runnable.forEach((process) => {+ process.status = 'running'+ })+ const blocked = await this.submit(group, runnable)+ if (blocked.length > 0) {+ this.hideProgress()+ await new Promise<void>((resolve) => {+ group.resume = resolve+ })+ group.resume = undefined+ this.syncProgress()+ continue+ }+ runnable.forEach(process => this.detach(process.id))+ }+ this.settle(group)+ },++ precheck(process: PluginProcess): PluginProcessReason | null {+ // 升级永不预跳过:面板既然画出了升级入口,就说明它有版本或异常信息要处理,而本地快照+ // (`installedSource`)可能刚被安装/刷新改过。按快照判「没有更新」会把用户的点击悄悄丢掉——+ // 用户点过的插件必须交给宿主,宿主按面板给的目标版本显式安装,装不上就报真实错误+ // (见 `update_dsh_plugins` → `install_targets`)。+ if (process.type === 'install' || process.type === 'upgrade' || !this.installedLoaded)+ return null+ const installed = this.installedSource.find(item => item.id === process.name || item.name === process.name)+ if (!installed)+ return process.type === 'uninstall' ? 'already-absent' : 'not-installed'+ if (process.type === 'disable' && installed.disabled)+ return 'already-absent'+ if (process.type === 'enable' && !installed.disabled && !installed.patchDisabled)+ return 'already-absent'+ return null+ },++ async submit(group: PluginGroup, targets: PluginProcess[]): Promise<PluginProcess[]> {+ group.attempt += 1+ if (group.type === 'disable' || group.type === 'enable') {+ const settled = await Promise.allSettled(+ targets.map(process =>+ invoke<void>(COMMANDS[group.type], {+ id: process.name,+ ...(group.type === 'enable' ? { clearConfigOverride: group.options.clearConfigOverride ?? false } : {}),+ }),+ ),+ )+ const blocked: PluginProcess[] = []+ settled.forEach((outcome, index) => {+ const process = targets[index]+ if (outcome.status === 'fulfilled') {+ this.finish(group.id, process, { process, ok: true })+ return+ }+ const message = errorMessage(outcome.reason)+ const refusal = parseBlockedRefusal(message)+ if (refusal !== null && refusalNames(refusal).size > 0) {+ this.block(group, process, refusal, group.options.toast)+ blocked.push(process)+ return+ }+ this.finish(group.id, process, { process, ok: false, error: message, code: errorCode(message) })+ })+ return blocked+ }+ try {+ // 升级的载荷项是 `id@版本`(面板显示着目标版本,带上它核验与显式安装兜底才有据+ // 可依,见 `update_dsh_plugins`);宿主的参数名仍叫 `ids`。+ await invoke<void>(COMMANDS[group.type], {+ ...(group.type === 'install'+ ? { specs: targets.map(process => process.spec) }+ : group.type === 'upgrade'+ ? { ids: targets.map(process => process.spec) }+ : { ids: targets.map(process => process.name) }),+ })+ targets.forEach(process => this.finish(group.id, process, { process, ok: true }))+ return []+ }+ catch (error) {+ // 宿主调用返回时这一组可能已经被 cancel() 结算(取消不等在途调用结束):此时+ // group.pending 已空。若照旧按拒绝归结,就会给已经按「已取消」结算的进程重新挂上授权+ // 等待,而 cancel 早已返回、再没人唤醒 resume,整条队列连同后续组会永久卡死。finish 用+ // 同一判据做幂等,这里也让归因只看仍留在组里的进程。+ const message = errorMessage(error)+ const refusal = parseBlockedRefusal(message)+ // 升级:宿主对整批逐项核验过指纹,只有被点名的才没生效。+ // - 没被点名的说明确实装上了,报成功即可,重提一次反而会把它们重新判成「没有变化」;+ // - 还能授权(新版本只是太新,写进档案豁免清单就能过闸)→ 进授权流程,常驻提示带按钮;+ // - 点名的版本已经授权过(写在豁免清单里)却还是没有变化:这是**失败**,不是+ // 「可跳过」。用户点升级就是要装上那个版本,静默跳过会让他以为已经更新(见+ // `plugins.hold_pinned_desc` 的原因说明);+ // - 载荷连目标版本都没有(探测缓存没命中、面板当时也没有版本可带)时无从安装:这同样是+ // 失败,只是原因不同(没有可安装的目标版本)。任何「什么都没发生」的路径都必须留下+ // 一条可见的结果,否则汇总里会出现用户看不见的空桶(「1 个成功」而其它插件下落不明)。+ if (refusal?.kind === 'update-hold') {+ const names = refusalNames(refusal)+ const known = new Set(refusal.versions.map(item => item.name))+ const blocked: PluginProcess[] = []+ targets.forEach((process) => {+ if (!group.pending.includes(process.id))+ return+ if (names.size > 0 && !names.has(process.name)) {+ this.finish(group.id, process, { process, ok: true })+ return+ }+ if (names.size > 0 && refusal.retryableNames.includes(process.name)) {+ this.block(group, process, refusal, group.options.toast)+ blocked.push(process)+ return+ }+ this.finish(group.id, process, {+ process,+ ok: false,+ error: i18next.t(+ known.has(process.name) ? 'plugins.hold_pinned_desc' : 'plugins.hold_no_target',+ ),+ })+ })+ return blocked+ }+ if (refusal !== null && refusalNames(refusal).size > 0) {+ const names = refusalNames(refusal)+ const blocked: PluginProcess[] = []+ targets.forEach((process) => {+ if (!group.pending.includes(process.id))+ return+ if (names.has(process.name)) {+ this.block(group, process, refusal, group.options.toast)+ blocked.push(process)+ return+ }+ process.status = 'pending'+ })+ // 只有当被点名的包确实在本次提交里时才进入授权等待。refusal 常点名传递依赖+ // 等外部包,此时 blocked 为空;若照样返回,runGroup 会因无人调用 resume 永久挂起。+ if (blocked.length > 0)+ return blocked+ }+ targets.forEach(process =>+ this.finish(group.id, process, {+ process,+ ok: false,+ error: message,+ code: errorCode(message),+ }),+ )+ return []+ }+ },++ block(group: PluginGroup, process: PluginProcess, refusal: BlockedRefusal, presenter: boolean): void {+ process.status = 'unauthorized'+ process.refusal = refusal+ this.pushLog('error', i18next.t('plugins.not_authorized', { name: process.name }), group.id, process.id)+ if (!presenter)+ return+ const versions = refusal.versions.map(item => `${item.name}@${item.version}`).join('、')+ process.approvalKey = toast(i18next.t(BLOCK_TITLE[refusal.kind], { name: process.name }), {+ variant: refusal.kind === 'incompatible' ? 'danger' : 'warning',+ timeout: 0,+ // 授权气泡必须一直可点:被新气泡挤掉后没人能再授权它,队列会永远停在等待授权上+ sticky: true,+ description: i18next.t(BLOCK_DESC[refusal.kind], { blocked: versions }),+ actionProps: {+ children: i18next.t('buttons.authorize'),+ onPress: () => {+ void this.approve(process.spec)+ },+ },+ onClose: (reason: ToastCloseReason) => {+ if (reason !== 'dismissed')+ return+ void this.reject(process.spec)+ },+ })+ },++ finish(groupId: string, process: PluginProcess, result: PluginProcessResult): void {+ const group = this.groups.find(item => item.id === groupId)+ // 幂等:cancel 会先给仍在运行的进程结算 'cancelled',被中断的宿主调用随后 reject+ // 回来时不能再次记账,否则结果、提示与事件都会重复。+ if (group === undefined || !group.pending.includes(process.id)) {+ this.detach(process.id)+ return+ }+ group.pending = group.pending.filter(id => id !== process.id)+ group.results = [...group.results, result]+ if (!result.ok) {+ this.pushLog('error', result.error ?? i18next.t('plugins.action_failed'), groupId, process.id)+ }+ this.detach(process.id)+ },++ detach(processId: string): void {+ this.processes = this.processes.filter(process => process.id !== processId)+ },++ settle(group: PluginGroup): void {+ const results = group.results+ const failed = results.filter(result => !result.ok)+ group.status = 'settled'+ this.groups = this.groups.filter(item => item.id !== group.id)+ group.processIds.forEach(id => this.detach(id))+ this.syncProgress()+ group.resolveDone(results)+ triggerPluginsManagerEvent('completed', results)+ if (failed.length > 0)+ triggerPluginsManagerEvent('error', failed)+ this.presentResults(group, results)+ if (this.groups.length === 0)+ triggerPluginsManagerEvent('allcompleted', results)+ },++ /** 全队列共享的加载气泡:标题按待处理进程总数聚合,因此后入队的组会立刻改变计数 */+ progressTargets(): PluginProcess[] {+ return this.processes.filter(process => process.status !== 'unauthorized')+ },++ progressTitle(processes: PluginProcess[]): string {+ const first = processes[0]+ if (processes.length >= 2) {+ const types = new Set(processes.map(process => process.type))+ return types.size === 1+ ? i18next.t(PROGRESS_MANY[first.type], { count: processes.length })+ : i18next.t('plugins.progress_many', { count: processes.length })+ }+ return i18next.t(PROGRESS_ONE[first.type], { name: first.name })+ },++ syncProgress(): void {+ const processes = this.progressTargets()+ // 提示权只由入队时的 toast 选项决定:面板关闭(presenter 卸载)不该让仍在跑的队列+ // 失去进度气泡与授权入口。+ const wanted = processes.length > 0+ && this.groups.some(group => group.options.toast)+ if (!wanted) {+ this.hideProgress()+ return+ }+ const title = this.progressTitle(processes)+ const description = this.progressDetail === '' ? undefined : this.progressDetail+ // 结果 Toast 会把共享气泡挤出可见限额(见 MAX_VISIBLE_TOASTS):被淘汰的 key 其+ // update 静默失效,若继续沿用,后续组就完全没有进度提示,故按「已死」重建。+ const current = this.progressKey+ if (current === null || !toast.isActive(current))+ this.progressKey = toast(title, { timeout: 0, isLoading: true, description })+ else+ toast.update(current, { title, isLoading: true, description })+ const key = this.progressKey+ processes.forEach((process) => {+ process.progressKey = key ?? undefined+ })+ },++ hideProgress(): void {+ if (this.progressKey !== null) {+ toast.close(this.progressKey)+ this.progressKey = null+ }+ this.progressDetail = ''+ this.processes.forEach((process) => {+ process.progressKey = undefined+ })+ },++ /** 安装日志的末行即加载气泡的副标题(HeroUI 默认气泡的 description 直接读条目 content) */+ setProgressDetail(line: string): void {+ const current = this.progressKey+ if (current === null || !toast.isActive(current))+ return+ this.progressDetail = line+ toast.update(current, { description: line })+ },++ /**+ * 结果提示:整条队列(一次入队的多个组)跑完才汇报一次。+ *+ * 每个组各自弹结果会互相盖住——用户只看到最后一条,前面失败的原因全被顶掉。因此把结果+ * 攒到队列排空再统一汇报(见 [`presentQueueResults`](self))。+ */+ presentResults(group: PluginGroup, results: PluginProcessResult[]): void {+ if (!group.options.toast)+ return+ this.queueResults.push(...results)+ if (this.groups.length > 0)+ return+ const pending = this.queueResults+ this.queueResults = []+ this.presentQueueResults(pending, group)+ },++ presentQueueResults(results: PluginProcessResult[], group: PluginGroup): void {+ if (results.length === 0)+ return+ const succeeded = results.filter(result => result.ok).length+ // 汇总不允许有看不见的桶:升级点名的目标版本没装上必定带 `error`,会落进 `failed`;+ // 只有卸载/禁用本来无事可做(already-absent)才算「无需变更」。用户自己取消或拒绝授权+ // 的项(cancelled / rejected)既不算成功也不算失败,也不再追着提示(见 m07292/m07436)。+ const noop = results.filter(result => result.reason === 'already-absent').length+ const failed = results.filter(+ result => !result.ok+ && result.reason !== 'already-absent'+ && 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+ // 用户自己的选择(取消 / 拒绝授权)不再补一条错误提示追问他;其余结果无论成败都要+ // 说出来(失败带 `description: result.error`),否则用户会以为操作没发生。+ if (result.reason === 'cancelled' || result.reason === 'rejected')+ return+ const title = i18next.t(+ result.ok ? RESULT_SUCCESS[result.process.type] : RESULT_FAILED[result.process.type],+ { name: result.process.name },+ )+ restartKey = toast(+ title,+ result.ok+ ? restart+ ? { variant: 'accent', timeout: 0, actionProps: restartAction }+ : { variant: 'default' }+ : { variant: 'danger', description: result.error },+ )+ return+ }+ const parts = [+ succeeded > 0 ? i18next.t('plugins.queue_summary_success', { count: succeeded }) : '',+ failed > 0 ? i18next.t('plugins.queue_summary_failed', { count: failed }) : '',+ noop > 0 ? i18next.t('plugins.queue_summary_skipped', { count: noop }) : '',+ ].filter(part => part !== '')+ restartKey = toast(i18next.t('plugins.queue_summary'), {+ description: parts.join(' · '),+ variant: failed > 0 ? 'danger' : restart ? 'accent' : 'default',+ timeout: restart ? 0 : undefined,+ actionProps: restart ? restartAction : undefined,+ })+ },++ async approve(refs?: PluginRef | PluginRef[]): Promise<PluginProcessResult[]> {+ const group = this.activeGroup()+ if (!group)+ return []+ const targets = this.approvalTargets(group, refs)+ if (targets.length === 0)+ return group.done+ for (const process of targets) {+ const refusal = process.refusal+ if (!refusal)+ continue+ try {+ await invoke<void>(refusal.kind === 'incompatible' ? 'allow_plugin_versions' : 'allow_plugin_policy_versions', {+ versions: refusal.versions,+ })+ }+ catch (error) {+ const message = errorMessage(error)+ this.pushLog('error', message, group.id, process.id)+ if (group.options.toast) {+ toast(i18next.t('plugins.authorize_failed'), {})+ }+ continue+ }+ if (process.approvalKey !== undefined) {+ toast.close(process.approvalKey)+ process.approvalKey = undefined+ }+ process.refusal = undefined+ process.status = 'pending'+ triggerPluginsManagerEvent('approve', process)+ }+ group.resume?.()+ return group.done+ },++ async reject(ref: PluginRef): Promise<PluginProcessResult[]> {+ const normalized = normalizeRef(ref)+ const group = this.activeGroup()+ if (!group)+ return []+ const process = this.approvalTargets(group, normalized.spec).find(+ item => item.name === normalized.name || item.spec === normalized.spec,+ )+ if (!process)+ return group.done+ if (process.approvalKey !== undefined) {+ toast.close(process.approvalKey)+ process.approvalKey = undefined+ }+ this.finish(group.id, process, {+ process,+ ok: false,+ error: i18next.t('plugins.rejected'),+ reason: 'rejected',+ })+ group.resume?.()+ return group.done+ },++ async cancel(): Promise<void> {+ const group = this.activeGroup()+ if (!group || this.cancelling)+ return+ this.cancelling = true+ try {+ await invoke<void>('cancel_plugin_processes')+ }+ catch (error) {+ this.pushLog('error', errorMessage(error), group.id)+ }+ const remaining = group.pending+ .map(id => this.processes.find(process => process.id === id))+ .filter((process): process is PluginProcess => process !== undefined)+ remaining.forEach((process) => {+ if (process.approvalKey !== undefined) {+ toast.close(process.approvalKey)+ process.approvalKey = undefined+ }+ this.finish(group.id, process, {+ process,+ ok: false,+ error: i18next.t('plugins.cancelled'),+ reason: 'cancelled',+ })+ })+ this.cancelling = false+ group.resume?.()+ },++ async search(refs: PluginRef | PluginRef[], options?: { dsh?: string }): Promise<PluginSearchResult[]> {+ const normalized = normalizeRefs(refs)+ const specs = normalized.map(item => item.spec)+ try {+ const inspected = await invoke<PluginInspectPayload[]>('inspect_plugin_specs', {+ specs,+ dsh: options?.dsh ?? null,+ })+ return inspected.map(item => ({+ spec: item.spec,+ name: item.name,+ version: item.version,+ compatible: item.compatible ?? null,+ peers: item.peers,+ problem: item.problem,+ }))+ }+ catch (error) {+ this.pushLog('error', errorMessage(error))+ return specs.map(spec => ({ spec, compatible: null, problem: 'network' as const }))+ }+ },++ activeGroup(): PluginGroup | undefined {+ return this.groups.find(item => item.id === this.activeGroupId)+ },++ approvalTargets(group: PluginGroup, refs?: PluginRef | PluginRef[]): PluginProcess[] {+ const unauthorized = group.pending+ .map(id => this.processes.find(process => process.id === id))+ .filter((process): process is PluginProcess => process !== undefined && process.status === 'unauthorized')+ if (refs === undefined)+ return unauthorized+ const normalized = normalizeRefs(refs)+ const names = new Set(normalized.map(item => item.name))+ return unauthorized.filter(process => names.has(process.name))+ },+ },+})diff --git a/src/store/modules/plugins/types.ts b/src/store/modules/plugins/types.tsnew file mode 100644index 00000000..ee2fdd4d--- /dev/null+++ b/src/store/modules/plugins/types.ts@@ -0,0 +1,120 @@+import type { IncompatibleVersion, PolicyBlockedVersion } from '../preinstall/types'+import type { DshPlugin, PluginErrorInfo } from '@/types'++export type BlockedRefusal+ = | { kind: 'incompatible', versions: IncompatibleVersion[] }+ | { kind: 'policy', versions: PolicyBlockedVersion[] }+ // update-hold 是逐项核验的结果:一次升级可能有的插件装上了、有的没变化、有的只是太新+ // 需要授权。`versions` 只放能写进档案豁免清单的条目(带得出新版本号的),`retryableNames`+ // 是可以就地授权的那几个,`heldNames` 是完全查不到更新版本的(来源被钉死)——它们只能+ // 报「保持原样」,不能进授权流程。+ | { kind: 'update-hold', versions: PolicyBlockedVersion[], retryable: boolean, retryableNames: string[], heldNames: string[] }++export interface Plugin {+ id: string+ name: string+ version: string+ description: string+ repoUrl: string+ bundled: boolean+ disabled: boolean+ patchDisabled: boolean+ recommended: boolean+ fix: boolean+ internal: boolean+ hasSnapshot: boolean+ error: PluginErrorInfo | null+ latest: string | null+ updateAvailable: boolean+ incompatible: boolean+ latestIncompatible: boolean+}++export type PluginRef = string | { spec: string, version?: string }++export type PluginProcessType = 'install' | 'upgrade' | 'uninstall' | 'disable' | 'enable'++export type PluginProcessStatus = 'pending' | 'running' | 'unauthorized'++export type PluginProcessReason+ = | 'not-installed'+ | 'already-absent'+ | 'update-hold'+ | 'rejected'+ | 'cancelled'+ | 'retry-exhausted'++export interface PluginProcess {+ id: string+ groupId: string+ type: PluginProcessType+ status: PluginProcessStatus+ spec: string+ name: string+ version?: string+ refusal?: BlockedRefusal+ progressKey?: string+ approvalKey?: string+}++export interface PluginProcessResult {+ process: PluginProcess+ ok: boolean+ error?: string+ code?: string+ reason?: PluginProcessReason+}++export interface PluginManagerLog {+ at: number+ level: 'info' | 'error'+ message: string+ groupId?: string+ processId?: string+}++export type PluginSearchProblem = 'invalid-spec' | 'not-found' | 'network' | 'unsupported' | 'unknown'++export interface PluginSearchResult {+ spec: string+ name?: string+ version?: string+ compatible: boolean | null+ peers?: Record<string, string>+ problem?: PluginSearchProblem+}++export interface PluginsManagerRuntime {+ toast: boolean+ restartOnSettle: boolean+ clearConfigOverride?: boolean+}++export interface PluginGroup {+ id: string+ type: PluginProcessType+ status: 'pending' | 'active' | 'settled'+ processIds: string[]+ attempt: number+ pending: string[]+ results: PluginProcessResult[]+ resume?: () => void+ done: Promise<PluginProcessResult[]>+ resolveDone: (results: PluginProcessResult[]) => void+ options: PluginsManagerRuntime+}++export interface PluginsState {+ groups: PluginGroup[]+ processes: PluginProcess[]+ logs: PluginManagerLog[]+ activeGroupId: string | null+ cancelling: boolean+ installedSource: DshPlugin[]+ installedLoaded: boolean+ progressKey: string | null+ progressDetail: string+ queueResults: PluginProcessResult[]+}++export type { DshPlugin }diff --git a/src/store/modules/plugins/utils.ts b/src/store/modules/plugins/utils.tsnew file mode 100644index 00000000..aa5c6a64--- /dev/null+++ b/src/store/modules/plugins/utils.ts@@ -0,0 +1,144 @@+import type { IncompatibleVersion, PolicyBlockedVersion } from '../preinstall/types'+import type { BlockedRefusal, Plugin, PluginRef } from './types'+import type { DshPlugin } from '@/types'++export interface NormalizedRef {+ spec: string+ name: string+ version?: string+}++const INCOMPATIBLE_PREFIX = 'PLUGIN_VERSION_INCOMPATIBLE:'+const POLICY_BLOCKED_PREFIX = 'PLUGIN_POLICY_BLOCKED:'+const UPDATE_HOLD_PREFIX = 'PLUGIN_UPDATE_NO_CHANGE:'+const INCOMPATIBLE_MESSAGE = /PLUGIN_VERSION_INCOMPATIBLE:|is incompatible with dsh/i++export function parseVersions<T>(error: string, prefix: string): T[] | null {+ if (!error.startsWith(prefix))+ return null+ try {+ const parsed = JSON.parse(error.slice(prefix.length)) as T[]+ return parsed.length > 0 ? parsed : null+ }+ catch (err) {+ console.error(`[PluginsManager] failed to parse ${prefix} payload:`, err)+ return null+ }+}++interface UpdateHoldEntry {+ name?: unknown+ latest?: unknown+ retryable?: unknown+}++/**+ * 升级没生效的载荷:宿主逐项核验整批插件后合成的结果。+ * 单个 id 时是一份对象,多个 id 时是同样结构的数组 —— 两者都要能解析,否则整批会退化成+ * 「升级插件 X 失败」,把「授权一下就能装上的新版本」说成失败。+ */+export function parseUpdateHold(error: string): BlockedRefusal | null {+ if (!error.startsWith(UPDATE_HOLD_PREFIX))+ return null+ try {+ const parsed = JSON.parse(error.slice(UPDATE_HOLD_PREFIX.length)) as unknown+ const entries: unknown[] = Array.isArray(parsed) ? parsed : [parsed]+ const versions: PolicyBlockedVersion[] = []+ const retryableNames: string[] = []+ const heldNames: string[] = []+ entries.forEach((entry) => {+ const item = (entry ?? {}) as UpdateHoldEntry+ if (typeof item.name !== 'string')+ return+ const latest = typeof item.latest === 'string' && item.latest !== '' ? item.latest : null+ if (latest === null) {+ heldNames.push(item.name)+ return+ }+ versions.push({ name: item.name, version: latest })+ if (item.retryable === true)+ retryableNames.push(item.name)+ })+ if (versions.length === 0 && heldNames.length === 0)+ return null+ return {+ kind: 'update-hold',+ versions,+ retryable: retryableNames.length > 0,+ retryableNames,+ heldNames,+ }+ }+ catch (err) {+ console.error(`[PluginsManager] failed to parse ${UPDATE_HOLD_PREFIX} payload:`, err)+ return null+ }+}++export function parseBlockedRefusal(error: string): BlockedRefusal | null {+ const incompatible = parseVersions<IncompatibleVersion>(error, INCOMPATIBLE_PREFIX)+ if (incompatible)+ return { kind: 'incompatible', versions: incompatible }+ const policy = parseVersions<PolicyBlockedVersion>(error, POLICY_BLOCKED_PREFIX)+ if (policy)+ return { kind: 'policy', versions: policy }+ return parseUpdateHold(error)+}++export function refusalNames(refusal: BlockedRefusal): Set<string> {+ const names = new Set(refusal.versions.map(item => item.name))+ if (refusal.kind === 'update-hold')+ refusal.heldNames.forEach(name => names.add(name))+ return names+}++export function normalizeRef(ref: PluginRef): NormalizedRef {+ const raw = typeof ref === 'string' ? ref : ref?.spec+ if (typeof raw !== 'string' || raw.trim() === '') {+ throw new Error(`PLUGIN_REF_INVALID: ${JSON.stringify(ref)}`)+ }+ const spec = raw.trim()+ const explicit = typeof ref === 'string' ? undefined : ref.version+ const at = spec.lastIndexOf('@')+ const name = at > 0 ? spec.slice(0, at) : spec+ if (name === '')+ throw new Error(`PLUGIN_REF_INVALID: ${JSON.stringify(ref)}`)+ const declared = at > 0 ? spec.slice(at + 1) : undefined+ const version = explicit ?? declared+ if (version === undefined || version === '')+ return { spec: name, name }+ return { spec: `${name}@${version}`, name, version }+}++export function normalizeRefs(refs: PluginRef | PluginRef[]): NormalizedRef[] {+ const list = Array.isArray(refs) ? refs : [refs]+ if (list.length === 0)+ throw new Error('PLUGIN_REFS_EMPTY: no plugin refs provided')+ return list.map(item => normalizeRef(item))+}++export function enrichInstalled(list: DshPlugin[]): Plugin[] {+ return list.map((item) => {+ const error = item.error ?? null+ const incompatible = error !== null && INCOMPATIBLE_MESSAGE.test(error.message)+ return {+ id: item.id,+ name: item.name === '' ? item.id : item.name,+ version: item.version,+ description: item.description,+ repoUrl: item.repo_url,+ bundled: item.bundled,+ disabled: item.disabled,+ patchDisabled: item.patchDisabled,+ recommended: item.recommended,+ fix: item.fix,+ internal: item.internal,+ hasSnapshot: item.hasSnapshot,+ error,+ latest: item.latestVersion ?? null,+ updateAvailable: item.updateAvailable,+ incompatible,+ latestIncompatible: item.updateAvailable && incompatible,+ }+ })+}diff --git a/src/store/modules/preinstall/store.ts b/src/store/modules/preinstall/store.tsindex 3f6b1f0c..57d4dfca 100644--- a/src/store/modules/preinstall/store.ts+++ b/src/store/modules/preinstall/store.ts@@ -7,84 +7,15 @@ import { defineStore } from 'valtio-define'import { hooks } from '@/config/hooks'import { harness } from '../harness'import { harnessUpdater } from '../harness-updater'--/** 预装安装日志在界面上的保留行数 */-const LOG_LIMIT = 200--/**- * 后端「拦截清单」的两套前缀:其后都是清单 JSON。- *- * dsh 的版本兼容性与 pnpm 的发布时长策略(`minimumReleaseAge`)是两套互不相干的拦截,- * 但形状一致:后端把清单挂在错误串上(Tauri 命令的错误通道只有字符串),前端解出来- * 交给用户逐项授权后重跑。- */-const INCOMPATIBLE_PREFIX = 'PLUGIN_VERSION_INCOMPATIBLE:'-const POLICY_BLOCKED_PREFIX = 'PLUGIN_POLICY_BLOCKED:'-const NO_CHANGE_PREFIX = 'PLUGIN_UPDATE_NO_CHANGE:'--/** 被拦下的清单:核心版本兼容性拒绝、pnpm 发布时长策略拒绝,或「升级没落地」。 */-export type BlockedRefusal- = | { kind: 'incompatible', versions: IncompatibleVersion[] }- | { kind: 'policy', versions: PolicyBlockedVersion[] }- | { kind: 'update-hold', versions: PolicyBlockedVersion[], retryable: boolean }+import { parseBlockedRefusal } from '../plugins/utils'/**- * 解析后端拦截清单的错误载荷;识别不出来返回 null。- *- * 引导页与插件面板共用这一处解析:两边的错误通道都一样,规则必须一致。解析失败一律- * 退回普通失败展示——绝不把读不出来的 JSON 当成可授权项(那会变成一次来路不明的授权)。+ * 预装安装日志在界面上的保留行数*/-export function parseBlockedRefusal(error: string): BlockedRefusal | null {- const incompatible = parseVersions<IncompatibleVersion>(error, INCOMPATIBLE_PREFIX)- if (incompatible)- return { kind: 'incompatible', versions: incompatible }- const policy = parseVersions<PolicyBlockedVersion>(error, POLICY_BLOCKED_PREFIX)- if (policy)- return { kind: 'policy', versions: policy }- return parseUpdateHold(error)-}--/**- * 「升级以 0 退出但版本没动」:只有「新版本还在发布保护期内」这一种成因有出路,后端因此- * 连同目标版本(更新探测缓存里的 registry latest)与 `retryable` 一起给出。已经授权过还- * 不动时 `retryable` 为 false——那是档案把来源钉死,界面就不要再给按钮。- */-function parseUpdateHold(error: string): BlockedRefusal | null {- if (!error.startsWith(NO_CHANGE_PREFIX))- return null- try {- const payload = JSON.parse(error.slice(NO_CHANGE_PREFIX.length)) as {- name?: unknown- latest?: unknown- retryable?: unknown- }- if (typeof payload.name !== 'string')- return null- const latest = typeof payload.latest === 'string' && payload.latest !== '' ? payload.latest : null- return {- kind: 'update-hold',- versions: latest ? [{ name: payload.name, version: latest }] : [],- retryable: payload.retryable === true && latest !== null,- }- }- catch (err) {- console.error(`[Harness] failed to parse ${NO_CHANGE_PREFIX} payload:`, err)- return null- }-}+const LOG_LIMIT = 200-function parseVersions<T>(error: string, prefix: string): T[] | null {- if (!error.startsWith(prefix))- return null- try {- const parsed = JSON.parse(error.slice(prefix.length)) as T[]- return parsed.length > 0 ? parsed : null- }- catch (err) {- console.error(`[Harness] failed to parse ${prefix} payload:`, err)- return null- }-}+export { parseBlockedRefusal }+export type { BlockedRefusal } from '../plugins/types'/*** 预装插件引导模块:首次安装、老版本升级或资源清单 plugins 节内容变更后,@@ -142,10 +73,15 @@ export const preinstall = defineStore({return this.plugins},+ /** 追加一行 `dsh plugin` 进程输出(日志上限见 [`LOG_LIMIT`]) */+ pushLog(line: string) {+ this.logs = [...this.logs, line].slice(-LOG_LIMIT)+ },+/** 预装安装日志流:dsh plugin 进程输出逐行追加 */async listenLog(): Promise<UnlistenFn> {return listen<PreinstallLogPayload>('preinstall-log', (e) => {- this.logs = [...this.logs, e.payload.line].slice(-LOG_LIMIT)+ this.pushLog(e.payload.line)})},@@ -262,7 +198,7 @@ export const preinstall = defineStore({this.installing = falsethis.cancelling = false})- await invoke('cancel_preinstall_plugins')+ await invoke('cancel_plugin_processes')}catch (err) {console.error('[Harness] cancel preinstall failed:', err)@@ -277,12 +213,22 @@ export const preinstall = defineStore({async skip() {if (this.installing)return+ await this.finish()+ },++ /**+ * 引导收尾:标记引导完成(记录预设指纹)并继续启动服务。+ *+ * 安装由管理器执行(`install_plugin_specs`),不再经过 `install_preinstall_plugins`,+ * 因此「标记完成」这一步要在这里补上,否则引导页每轮启动都会再次弹出。+ */+ async finish() {try {await invoke('skip_preinstall_plugins')await this.continueStartup()}catch (err) {- console.error('[Harness] skip preinstall failed:', err)+ console.error('[Harness] finish preinstall failed:', err)this.error = String(err)}},diff --git a/src/styles/main.css b/src/styles/main.cssindex c15ef450..ffb4e3f7 100644--- a/src/styles/main.css+++ b/src/styles/main.css@@ -114,6 +114,15 @@ html[data-theme="light"] {animation: load-spin 0.8s linear infinite;}+/* 加载态气泡(HeroUI 默认气泡里带 Spinner 的那种)由 Store 持有整个生命周期,+ 用户关闭只会让共享进度气泡消失、随后又被重建,故不提供关闭入口。HeroUI 的默认+ children 无条件渲染 ToastCloseButton 且 Toast.Provider 不可注入 slots,只能按库+ 自己的 data-slot 标记隐藏。:has() 需 WebView2 105+ / WKWebView 15.4+,旧引擎下+ 选择器失效、按钮照常显示,仅退化不影响功能。 */+[data-slot="toast"]:has([data-slot="spinner"]) [data-slot="toast-close"] {+ display: none;+}+@layer base {html,body,diff --git a/src/ui/config/plugin.tsx b/src/ui/config/plugin.tsxindex d23c8d5d..14b68e6d 100644--- a/src/ui/config/plugin.tsx+++ b/src/ui/config/plugin.tsx@@ -1,32 +1,26 @@-import type { BlockedRefusal } from '@/store/modules/preinstall'-import type { DshPlugin } from '@/types'+import type { Plugin, PluginProcess, PluginSearchProblem, PluginSearchResult } from '@/store/modules/plugins'import { ChevronRight, CircleExclamation } from '@gravity-ui/icons'-import { Button, Chip, Label, Spinner, Switch, Tooltip } from '@heroui/react'+import { Button, Chip, Input, Label, Spinner, Switch, Tooltip } from '@heroui/react'import { useOverlay } from '@overlastic/react'-import { useMount, useToggle } from '@reause/core'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useToggle } from '@reause/core'+import { useMutation, 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 { tv } from 'tailwind-variants'-import { useStore } from 'valtio-define'import { Ellipsis as TextEllipsis } from '@/components/ellipsis'import { Empty } from '@/components/empty'import { Item } from '@/components/item'import { Modal } from '@/components/modal'import { Panel } from '@/components/panel'import { queryKeys } from '@/config/query-keys'-import { useListen } from '@/hooks/use-listen'+import { useDshPluginsManager } from '@/hooks/use-plugins-manager'import { store } from '@/store'-import { parseBlockedRefusal } from '@/store/modules/preinstall'import { silence } from '@/utils/silence'import { toast } from '@/utils/toast'-/**- * 操作 chip 的样式变体:busy 时禁止点击并降低透明度,否则可点击。- * 统一各操作 chip 的 busy 样式,避免内联三元重复。- */+/** 操作 chip 的样式变体:busy 时禁止点击并降低透明度,否则可点击。 */const actionChip = tv({base: 'rounded-md',variants: {@@ -40,200 +34,54 @@ const actionChip = tv({},})+/** 队列里的进程类型 → 面板行内动作名(队列叫 upgrade/uninstall,按钮叫 update/remove) */+const QUEUED_ACTIONS: Record<PluginProcess['type'], string> = {+ install: 'install',+ upgrade: 'update',+ uninstall: 'remove',+ disable: 'disable',+ enable: 'enable',+}++/** 兼容性检查的问题码 → i18n key:管理器把宿主返回的 problem 原样透传给调用方 */+const searchProblemKeys: Record<PluginSearchProblem, string> = {+ 'invalid-spec': 'plugins.search_invalid_spec',+ 'not-found': 'plugins.search_not_found',+ 'network': 'plugins.search_network',+ 'unsupported': 'plugins.search_unsupported',+ 'unknown': 'plugins.search_unknown',+}+/**- * 「插件」面板:展示已安装插件,作为「插件出问题时」的卸载/升级入口。+ * 「插件」面板:已安装插件的安装/升级/卸载/禁用/启用全部经 `useDshPluginsManager` 收口+ * (队列、授权、Toast、组结算重启由管理器统一负责),面板只保留确认对话框与行内 busy。*- * - 列表来自 `get_dsh_plugins` 查询;后端(`service/plugin/watch`)秒级监控 profile- * 插件文件,变化时经 `dsh-plugins-updated` 推送完整列表,由根布局统一写入该查询- * 缓存(面板 / 配置对话框角标 / 导航栏共用同一份缓存,无需重新拉取)。- * - 升级 `update_dsh_plugin` / 卸载 `remove_dsh_plugin` 已接入后端- * (`dsh plugin --profile <当前档案> update|remove <id>`,进程输出经- * `preinstall-log` 事件实时推送)。- * - 「异常」标记:插件带 `error` 字段(安装/升级/卸载失败或页面运行期上报)- * 时显示 danger 图标按钮,Tooltip 展示错误详情,行内可直接升级/卸载修复。+ * 快照(创建/还原/删除)不在管理器范围内+ * 仍由面板直接调用宿主命令;这些操作同样会改写插件状态,因此成功后失效插件列表查询。*/export function ConfigPlugin() {const { t } = useTranslation()const queryClient = useQueryClient()- const preinstall = useStore(store.preinstall)-- const { data: pluginList, isLoading, error: pluginError } = useQuery({- queryKey: queryKeys.plugins,- queryFn: () => invoke<DshPlugin[]>('get_dsh_plugins'),- })-- // 重新探测更新可用性并写回缓存(Rust 侧 30min 缓存;失败静默按「无更新」处理,- // 插件管理器仍可用)。升级入口只在确有更新(或异常修复)时显示,而不是常驻。- function refreshUpdates() {- void invoke<DshPlugin[]>('refresh_plugin_updates')- .then(list => queryClient.setQueryData(queryKeys.plugins, list))- .catch(err => console.error('[ConfigPlugin] refresh_plugin_updates failed:', err))- }-- // 打开面板补齐一次;之后插件文件变化(安装/升级/卸载会改写版本与 spec)重新探测- useMount(refreshUpdates)- useListen<DshPlugin[]>('dsh-plugins-updated', refreshUpdates)+ const manager = useDshPluginsManager()- const loading = isLoading- const error = pluginError ? String(pluginError) : ''+ const plugins = manager.installed+ const internalPlugins = plugins.filter(plugin => plugin.internal)+ const managedPlugins = plugins.filter(plugin => !plugin.internal)/** 「内置插件」分组是否展开:默认折叠,内置插件由启动自愈维护,不作为常规可管理项 */const [showInternal, toggleShowInternal] = useToggle()/** 高级选项:默认关闭,快照(创建/还原/删除)属于低频维护操作,不常驻每行 */const [advanced, toggleAdvanced] = useToggle()- // 内置插件(internal)随包分发、由启动自愈安装与维护,排到列表末尾并收进默认折叠的- // 分组:与可升级/可卸载的插件并列只会让用户把它们当作普通插件。它们仍可升级- // (切换核心版本后内置包可能落后),但不提供卸载/禁用/快照入口。- const plugins = pluginList ?? []- const internalPlugins = plugins.filter(plugin => plugin.internal)- const managedPlugins = plugins.filter(plugin => !plugin.internal)+ /** 行内动作标记 `<id>:<action>`:按行独立,某行的动作不阻塞其他行继续入队 */+ const [busy, setBusy] = useState<string[]>([])+ /** 安装输入的原始文本:支持逗号/空白分隔的多个 spec */+ const [installRef, setInstallRef] = useState('')+ const [installing, setInstalling] = useState(false)+ /** 兼容性预检结果:安装前先经 manager.search 展示解析到的版本与兼容性 */+ const [searchResults, setSearchResults] = useState<PluginSearchResult[] | null>(null)const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })- /**- * 记录被拦下版本的精确授权:核心版本兼容性走 `allow_plugin_versions`(写档案的- * `compatibility.json`),发布时长策略走 `allow_plugin_policy_versions`(写- * `minimumReleaseAgeExclude`)。两套授权互不相干,但都只认精确版本、都由用户在这里确认。- */- const allowBlocked = useMutation({- mutationFn: (refusal: BlockedRefusal) => invoke<void>(- refusal.kind === 'incompatible' ? 'allow_plugin_versions' : 'allow_plugin_policy_versions',- { versions: refusal.versions },- ),- onError: (err) => {- console.error('[ConfigPlugin] authorising blocked versions failed:', err)- toast(t('plugins.authorize_failed'), {})- },- })-- /**- * 插件操作被拦下时的出路:标题 + 说明 + 被拦下的精确版本,动作按钮「授权」点一次补齐- * 所需豁免并重跑原操作(不想要就关掉气泡,不另设取消按钮)。- *- * 三种情况共用这条通道:核心版本不兼容、发布保护期挡下、以及「升级以 0 退出但版本没动」- * (最后一种只是同一种发布保护期的静默形态:`--latest` 盯着最新版本,而最新版本还在窗口- * 内时 pnpm 直接不动、也不打印原因)。标题是**这次操作的插件**,清单是**档案里真正挡住- * 它的条目**——两者可以不同:插件操作要过整份 lockfile 校验,档案里任何一条太新的版本- * 都会拦下别人的升级。- *- * 常驻(`timeout: 0`):这是需要用户决定的岔口,超时消失等于把人晾在原地。授权后重跑- * 原操作——豁免写进档案后仍要由 pnpm 真正改一遍依赖,不能假定写入即生效。- */- function onBlocked(refusal: BlockedRefusal, name: string, retry: () => Promise<void>) {- const core = refusal.kind === 'incompatible'- const hold = refusal.kind === 'update-hold'- // 「升级没落地」只有发布保护期这一种成因有出路;后端判定为档案钉死(或没探测到新版- // 本)时不给按钮,否则用户只会反复点一个没用的动作。- const actionable = !hold || refusal.retryable- const titleKey = core- ? 'plugins.blocked_incompatible_title'- : hold ? 'plugins.hold_title' : 'plugins.blocked_policy_title'- const descKey = core- ? 'plugins.blocked_incompatible_desc'- : hold- ? (actionable ? 'plugins.hold_desc' : 'plugins.hold_pinned_desc')- : 'plugins.blocked_policy_desc'- const blocked = refusal.versions.map(item => `${item.name}@${item.version}`).join('、')- const key = toast(t(titleKey, { name }), {- variant: core ? 'danger' : 'warning',- timeout: 0,- description: t(descKey, { blocked }),- actionProps: actionable- ? {- children: t('buttons.authorize'),- onPress: () => {- toast.close(key)- void authorise(refusal, retry)- },- }- : undefined,- })- }-- async function authorise(refusal: BlockedRefusal, retry: () => Promise<void>) {- try {- await allowBlocked.mutateAsync(refusal)- }- catch (e) {- silence(e, 'plugin blocked: error already shown by mutation onError')- return- }- await retry()- }-- /** 行内操作进行中状态:id + 操作类型(update/remove/disable/enable/snapshot/restore/delete-snapshot),保证单例运行 */- const [busy, setBusy] = useState<{ id: string, action: 'update' | 'remove' | 'disable' | 'enable' | 'snapshot' | 'restore' | 'delete-snapshot' } | null>(null)-- const upgrade = useMutation({- mutationFn: (id: string) => invoke<void>('update_dsh_plugin', { id }),- onSuccess: (_data, id) => {- const name = plugins.find(p => p.id === id)?.name ?? id- // 失效插件列表查询:dsh-plugins-updated 事件在停服务重启场景下可能丢失- // (插件操作会停止运行中的服务),必须显式重拉以确保列表落盘后刷新。- void queryClient.invalidateQueries({ queryKey: queryKeys.plugins })- toast(t('plugins.updated_toast', { name }), {})- },- onError: (err, id) => {- const name = plugins.find(p => p.id === id)?.name ?? id- console.error('[ConfigPlugin] upgrade failed:', err)- // 被拦下不是「升级失败」:要么是核心不兼容、要么是发布保护期,重跑多少次都一样。- // 给出可操作的出路(授权精确版本后重试),而不是一句没有出路的失败。- const refusal = parseBlockedRefusal(String(err))- if (refusal) {- onBlocked(refusal, name, () => onUpgrade(id))- return- }- toast(t('plugins.upgrade_failed', { name }), {})- },- })- const remove = useMutation({- mutationFn: (id: string) => invoke<void>('remove_dsh_plugin', { id }),- onSuccess: (_data, id) => {- const name = plugins.find(p => p.id === id)?.name ?? id- // 同上:卸载成功后显式重拉插件列表,避免事件推送丢失导致列表未更新。- void queryClient.invalidateQueries({ queryKey: queryKeys.plugins })- toast(t('plugins.removed_toast', { name }), {})- },- onError: (err, id) => {- const name = plugins.find(p => p.id === id)?.name ?? id- console.error('[ConfigPlugin] remove failed:', err)- // 卸载同样要重写 lockfile 并复核整份档案,因此同样可能被核心不兼容或发布保护期- // 拦下:一样给出授权后重跑的出路,而不是一句失败。- const refusal = parseBlockedRefusal(String(err))- if (refusal) {- onBlocked(refusal, name, () => runRemove(id))- return- }- toast(t('plugins.remove_failed', { name }), {})- },- })- const disable = useMutation({- mutationFn: (id: string) => invoke<void>('disable_dsh_plugin', { id }),- onSuccess: (_data, id) => {- const name = plugins.find(p => p.id === id)?.name ?? id- void queryClient.invalidateQueries({ queryKey: queryKeys.plugins })- toast(t('plugins.disable_toast', { name }), {})- },- onError: (err, id) => {- const name = plugins.find(p => p.id === id)?.name ?? id- console.error('[ConfigPlugin] disable failed:', err)- toast(t('plugins.disable_failed', { name }), {})- },- })- const enable = useMutation({- mutationFn: (args: { id: string, clearConfigOverride: boolean }) =>- invoke<void>('enable_dsh_plugin', { id: args.id, clearConfigOverride: args.clearConfigOverride }),- onSuccess: (_data, args) => {- const name = plugins.find(p => p.id === args.id)?.name ?? args.id- void queryClient.invalidateQueries({ queryKey: queryKeys.plugins })- toast(t('plugins.enable_toast', { name }), {})- },- onError: (err, args) => {- const name = plugins.find(p => p.id === args.id)?.name ?? args.id- console.error('[ConfigPlugin] enable failed:', err)- toast(t('plugins.enable_failed', { name }), {})- },- })const snapshot = useMutation({mutationFn: (id: string) => invoke<void>('snapshot_plugin', { id }),onSuccess: (_data, id) => {@@ -250,7 +98,6 @@ export function ConfigPlugin() {const restore = useMutation({mutationFn: (id: string) => invoke<void>('restore_plugin', { id }),onSuccess: (_data, _id) => {- // 还原后快照仍在(覆盖式不删快照),插件版本回到快照态:重拉列表。void queryClient.invalidateQueries({ queryKey: queryKeys.plugins })},onError: (err, id) => {@@ -273,26 +120,63 @@ export function ConfigPlugin() {},})- async function onUpgrade(id: string) {- if (busy)+ /** 该插件在管理器队列里的进程类型(不在队列里为 null)。 */+ function queuedType(id: string): PluginProcess['type'] | null {+ return manager.processes.find(process => process.name === id)?.type ?? null+ }++ /**+ * 管理器动作只等待组结算:授权等待期间的横幅与结果 Toast 都由管理器弹出,+ * 面板仅负责行内 busy 与「同一行不重复派发」。不同行的动作互不禁用,+ * 后续点击会作为新组进入管理器队列。+ *+ * 队列里已有该插件的同义动作时也算忙(升级 = 更新、卸载 = 移除):Spinner 跟着队列走,+ * 不必等宿主返回;整行禁点由 [`rowBusy`](self) 负责。+ */+ function busyWith(id: string, action: string): boolean {+ if (busy.includes(`${id}:${action}`))+ return true+ const queued = queuedType(id)+ return queued !== null && QUEUED_ACTIONS[queued] === action+ }++ /** 队列里已有该插件的进程时整行禁点:再点只会把它作为新组塞进同一个队列。 */+ function rowBusy(id: string): boolean {+ return queuedType(id) !== null || busy.some(item => item.startsWith(`${id}:`))+ }++ function markBusy(id: string, action: string): void {+ setBusy(current => [...current, `${id}:${action}`])+ }++ function clearBusy(id: string, action: string): void {+ setBusy(current => current.filter(item => item !== `${id}:${action}`))+ }++ async function runAction(id: string, action: 'update' | 'remove' | 'disable' | 'enable', run: () => Promise<unknown>) {+ if (rowBusy(id))return- setBusy({ id, action: 'update' })+ markBusy(id, action)try {- await upgrade.mutateAsync(id)- // 只有升级成功才拉起服务:失败时档案/依赖仍是待处理状态(不兼容、发布保护期、- // 网络…),此时重启只会再失败一次(重启 > 报错),把真正的失败原因淹没掉。- void store.harness.restart()+ await run()}catch (e) {- silence(e, 'plugin upgrade: error already shown by mutation onError')+ silence(e, 'plugin action: error already reported by the manager')}finally {- setBusy(null)+ clearBusy(id, action)}}+ async function onUpgrade(id: string, latest: string | null) {+ // 面板此刻显示着目标版本,把它一起交给管理器:宿主据此核验「装的到底是不是这个版本」,+ // 并在来源被钉死时用显式安装兜底(见 `update_dsh_plugins`)。+ const ref = latest === null ? id : { spec: id, version: latest }+ await runAction(id, 'update', () => manager.upgrade(ref))+ }+async function onRemove(id: string, name: string) {- if (busy)+ if (rowBusy(id))returntry {await openDialog({@@ -310,50 +194,45 @@ export function ConfigPlugin() {silence(e, 'plugin remove: dialog cancelled')return}- await runRemove(id)+ await runAction(id, 'remove', () => manager.uninstall(id))}- /** 已确认过的卸载(发布时长豁免后重跑时不再追问一次「确认卸载」)。 */- async function runRemove(id: string) {- if (busy)+ /**+ * 新增安装入口:先 `manager.search` 预检兼容性(只读,不改 Profile),+ * 命中明确不兼容的 spec 时中止并提示,其余交给 `manager.install` 走统一队列。+ */+ async function onInstall() {+ const refs = installRef.trim().split(/[\s,]+/).filter(Boolean)+ if (refs.length === 0 || installing)return- setBusy({ id, action: 'remove' })+ setInstalling(true)try {- await remove.mutateAsync(id)- // 同升级:只有成功才拉起服务(失败时档案仍是待处理状态,重启只会报错一次)- void store.harness.restart()+ const results = await manager.search(refs)+ setSearchResults(results)+ const incompatibles = results.filter(item => item.compatible === false)+ if (incompatibles.length > 0) {+ const names = incompatibles.map(item => item.name ?? item.spec).join(', ')+ toast(t('plugins.search_incompatible', { names }), { variant: 'danger' })+ return+ }+ setInstallRef('')+ await manager.install(refs)}catch (e) {- silence(e, 'plugin remove: error already shown by mutation onError')+ silence(e, 'plugin install: error already reported by the manager')}finally {- setBusy(null)+ setInstalling(false)}}async function onDisable(id: string) {- if (busy)- return- // 禁用是可逆操作(保留包体,启用即可恢复),无需确认对话框。- setBusy({ id, action: 'disable' })- try {- await disable.mutateAsync(id)- // 只有成功才拉起服务,使新的 bundles 列表生效(失败时什么都没变,重启没有意义)- void store.harness.restart()- }- catch (e) {- silence(e, 'plugin disable: error already shown by mutation onError')- }- finally {- setBusy(null)- }+ await runAction(id, 'disable', () => manager.disable(id))}async function onEnable(id: string, clearConfigOverride = false) {- if (busy)+ if (rowBusy(id))return- // 配置覆盖禁用:启用会修改用户的 cordis.patch.yml(仅移除该插件的禁用覆盖,- // 其余配置条目保留),属于改写用户配置文件的操作,必须先明确确认。if (clearConfigOverride) {const name = plugins.find(p => p.id === id)?.name ?? idtry {@@ -373,24 +252,12 @@ export function ConfigPlugin() {return}}- setBusy({ id, action: 'enable' })- try {- await enable.mutateAsync({ id, clearConfigOverride })- // 同禁用:只有成功才拉起服务,使新的 bundles 列表生效- void store.harness.restart()- }- catch (e) {- silence(e, 'plugin enable: error already shown by mutation onError')- }- finally {- setBusy(null)- }+ await runAction(id, 'enable', () => manager.enable(id, { clearConfigOverride }))}async function onSnapshot(id: string, name: string, hasSnapshot: boolean) {- if (busy)+ if (rowBusy(id))return- // 已存在快照:覆盖式,先确认再覆盖(快照语义 = 覆盖当前状态)。if (hasSnapshot) {try {await openDialog({@@ -409,7 +276,7 @@ export function ConfigPlugin() {return}}- setBusy({ id, action: 'snapshot' })+ markBusy(id, 'snapshot')try {await snapshot.mutateAsync(id)}@@ -417,12 +284,12 @@ export function ConfigPlugin() {silence(e, 'plugin snapshot: error already shown by mutation onError')}finally {- setBusy(null)+ clearBusy(id, 'snapshot')}}async function onRestore(id: string, name: string) {- if (busy)+ if (rowBusy(id))returntry {await openDialog({@@ -440,7 +307,7 @@ export function ConfigPlugin() {silence(e, 'plugin restore: dialog cancelled')return}- setBusy({ id, action: 'restore' })+ markBusy(id, 'restore')try {await restore.mutateAsync(id)// 还原期间后端已停止服务:复用 ui/config/backup 的「重启服务」toast 交互@@ -460,12 +327,12 @@ export function ConfigPlugin() {silence(e, 'plugin restore: error already shown by mutation onError')}finally {- setBusy(null)+ clearBusy(id, 'restore')}}async function onDeleteSnapshot(id: string, name: string) {- if (busy)+ if (rowBusy(id))returntry {await openDialog({@@ -483,7 +350,7 @@ export function ConfigPlugin() {silence(e, 'plugin delete-snapshot: dialog cancelled')return}- setBusy({ id, action: 'delete-snapshot' })+ markBusy(id, 'delete-snapshot')try {await deleteSnapshot.mutateAsync(id)}@@ -491,12 +358,12 @@ export function ConfigPlugin() {silence(e, 'plugin delete-snapshot: error already shown by mutation onError')}finally {- setBusy(null)+ clearBusy(id, 'delete-snapshot')}}/** 插件行:可管理插件列表与「内置插件」折叠分组共用同一行结构 */- function renderPluginRow(plugin: DshPlugin) {+ function renderPluginRow(plugin: Plugin) {return (<Itemkey={plugin.id}@@ -566,51 +433,50 @@ export function ConfigPlugin() {)}right={(<>- {/* 升级入口仅在确有更新(updateAvailable)或插件异常(error,修复入口)时显示;- 与文档 P1「对 dshmarket 点击升级」一致,且不会常驻——up-to-date 插件不显示升级按钮 */}+ {/* 升级入口仅在确有更新(updateAvailable)或插件异常(error,修复入口)时显示 */}<If cond={plugin.updateAvailable || plugin.error != null}><Chip- className={actionChip({ busy: !!busy })}+ className={actionChip({ busy: rowBusy(plugin.id) })}variant="primary"color="accent"size="sm"- onClick={() => onUpgrade(plugin.id)}+ onClick={() => onUpgrade(plugin.id, plugin.latest)}><span className="flex items-center gap-1">- <If cond={busy?.id === plugin.id && busy.action === 'update'} then={<Spinner size="sm" color="current" />} />+ <If cond={busyWith(plugin.id, 'update')} then={<Spinner size="sm" color="current" />} />{t('plugins.upgrade')}- <If cond={plugin.latestVersion != null && plugin.error == null}>+ <If cond={plugin.latest != null && plugin.error == null}><span className="font-mono text-[10px] opacity-80 max-w-[80px] truncate">- {plugin.latestVersion && plugin.latestVersion.length >= 40 ? `${plugin.latestVersion.slice(0, 8)}…` : plugin.latestVersion}+ {plugin.latest && plugin.latest.length >= 40 ? `${plugin.latest.slice(0, 8)}…` : plugin.latest}</span></If></span></Chip></If>{/* 启用入口:配置覆盖禁用(含内置插件)或桌面禁用清单 → 可启用。- 配置覆盖禁用时点击会先弹确认框,确认后后端才移除该覆盖 */}+ 配置覆盖禁用时点击会先弹确认框,确认后管理器透传 clearConfigOverride */}<If cond={plugin.patchDisabled || (!plugin.internal && plugin.disabled)}><Chip- className={actionChip({ busy: !!busy })}+ className={actionChip({ busy: rowBusy(plugin.id) })}variant="primary"color="accent"size="sm"onClick={() => onEnable(plugin.id, plugin.patchDisabled)}><span className="flex items-center gap-1">- <If cond={busy?.id === plugin.id && busy.action === 'enable'} then={<Spinner size="sm" color="current" />} />+ <If cond={busyWith(plugin.id, 'enable')} then={<Spinner size="sm" color="current" />} />{t('plugins.enable')}</span></Chip></If><If cond={!plugin.internal && !plugin.patchDisabled && !plugin.disabled}><Chip- className={actionChip({ busy: !!busy })}+ className={actionChip({ busy: rowBusy(plugin.id) })}size="sm"onClick={() => onDisable(plugin.id)}><span className="flex items-center gap-1">- <If cond={busy?.id === plugin.id && busy.action === 'disable'} then={<Spinner size="sm" color="current" />} />+ <If cond={busyWith(plugin.id, 'disable')} then={<Spinner size="sm" color="current" />} />{t('plugins.disable')}</span></Chip>@@ -620,51 +486,51 @@ export function ConfigPlugin() {{/* 单插件快照:快照始终可用(已存在时覆盖确认);还原/删除快照仅在存在快照时显示。还原会停服务,还原后 toast 提示重启(issue #303) */}<Chip- className={actionChip({ busy: !!busy })}+ className={actionChip({ busy: rowBusy(plugin.id) })}variant="primary"color="accent"size="sm"onClick={() => onSnapshot(plugin.id, plugin.name, plugin.hasSnapshot)}><span className="flex items-center gap-1">- <If cond={busy?.id === plugin.id && busy.action === 'snapshot'} then={<Spinner size="sm" color="current" />} />+ <If cond={busyWith(plugin.id, 'snapshot')} then={<Spinner size="sm" color="current" />} />{t('plugins.snapshot')}</span></Chip><If cond={plugin.hasSnapshot}><Chip- className={actionChip({ busy: !!busy })}+ className={actionChip({ busy: rowBusy(plugin.id) })}variant="primary"color="accent"size="sm"onClick={() => onRestore(plugin.id, plugin.name)}><span className="flex items-center gap-1">- <If cond={busy?.id === plugin.id && busy.action === 'restore'} then={<Spinner size="sm" color="current" />} />+ <If cond={busyWith(plugin.id, 'restore')} then={<Spinner size="sm" color="current" />} />{t('plugins.restore')}</span></Chip><Chip- className={actionChip({ busy: !!busy })}+ className={actionChip({ busy: rowBusy(plugin.id) })}size="sm"onClick={() => onDeleteSnapshot(plugin.id, plugin.name)}><span className="flex items-center gap-1">- <If cond={busy?.id === plugin.id && busy.action === 'delete-snapshot'} then={<Spinner size="sm" color="current" />} />+ <If cond={busyWith(plugin.id, 'delete-snapshot')} then={<Spinner size="sm" color="current" />} />{t('plugins.delete_snapshot')}</span></Chip></If></If><Chip- className={actionChip({ busy: !!busy })}+ className={actionChip({ busy: rowBusy(plugin.id) })}variant="primary"color="danger"size="sm"onClick={() => onRemove(plugin.id, plugin.name)}><span className="flex items-center gap-1">- <If cond={busy?.id === plugin.id && busy.action === 'remove'} then={<Spinner size="sm" color="current" />} />+ <If cond={busyWith(plugin.id, 'remove')} then={<Spinner size="sm" color="current" />} />{t('plugins.uninstall')}</span></Chip>@@ -702,7 +568,7 @@ export function ConfigPlugin() {variant="primary"className="rounded-md"onPress={store.preinstall.open}- isDisabled={preinstall.installing}+ isDisabled={store.preinstall.installing}>{t('preinstall.open_preset')}</Button>@@ -715,9 +581,62 @@ export function ConfigPlugin() {description={t('plugins.panel_tooltip')}/>- {/* 加载 / 失败 / 空态 */}- <Panel.Loadable loading={loading} error={error}>+ <Panel.Loadable loading={manager.loading} error={manager.error}><div className="flex flex-col gap-4">+ {/* 安装入口:接受 npm spec(可逗号/空白分隔多个),先经管理器只读预检再入队 */}+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2 px-1">+ <Input+ variant="secondary"+ className="h-8 flex-1 rounded-md font-mono text-xs"+ placeholder={t('plugins.install_placeholder')}+ aria-label={t('plugins.install_placeholder')}+ value={installRef}+ onChange={e => setInstallRef(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter')+ void onInstall()+ }}+ />+ <Button+ size="sm"+ variant="tertiary"+ className="h-8 shrink-0 rounded-md"+ isDisabled={installRef.trim() === ''}+ onPress={() => void onInstall()}+ >+ <span className="flex items-center gap-1">+ <If cond={installing} then={<Spinner size="sm" color="current" />} />+ {t('plugins.install')}+ </span>+ </Button>+ </div>+ <If cond={searchResults != null}>+ <div className="flex flex-col gap-1 px-1">+ {(searchResults ?? []).map(result => (+ <div key={result.spec} className="flex items-center gap-2 text-[11px] text-muted">+ <span className="min-w-0 truncate font-mono">{result.spec}</span>+ <If cond={result.version != null}>+ <code className="shrink-0 rounded bg-default px-1.5 py-0.5 font-mono text-[10px]">+ {result.version}+ </code>+ </If>+ <If cond={result.compatible === false}>+ <Chip size="sm" variant="soft" color="danger" className="shrink-0">+ {t('plugins.search_incompatible_badge')}+ </Chip>+ </If>+ <If cond={result.problem != null}>+ <span className="shrink-0 text-danger">+ {t(searchProblemKeys[result.problem ?? 'unknown'])}+ </span>+ </If>+ </div>+ ))}+ </div>+ </If>+ </div>+<If cond={managedPlugins.length > 0} else={<Empty>{t('plugins.empty')}</Empty>}>{managedPlugins.map(plugin => renderPluginRow(plugin))}</If>diff --git a/src/ui/config/profile.tsx b/src/ui/config/profile.tsxindex 2831bd7f..41f94a28 100644--- a/src/ui/config/profile.tsx+++ b/src/ui/config/profile.tsx@@ -18,11 +18,20 @@ import { useInvalidateOnSettingUpdated } from '@/hooks/use-invalidate-on-settingimport { store } from '@/store'import { waitForHarnessStopped } from '@/store/modules/harness'import { ConfigBackup } from '@/ui/config/backup'+import { normalizeProfileId } from '@/utils/profile-id'import { silence } from '@/utils/silence'import { toast } from '@/utils/toast'type ProfileView = 'list' | { profile: string }+/** 宿主档案错误的 `CODE` → 提示 key(错误串是 `CODE: 详情`,详见 `service::profile`) */+const PROFILE_ERROR_KEYS: Record<string, string> = {+ PROFILE_EMPTY_NAME: 'profiles.error_empty_name',+ PROFILE_NAME_TOO_LONG: 'profiles.error_name_too_long',+ PROFILE_RESERVED: 'profiles.error_reserved',+ PROFILE_NOT_FOUND: 'profiles.error_not_found',+}+export function ConfigProfile() {/*** 「档案」面板:展示 & 切换 dsh 配置档案,支持新建/删除。@@ -111,6 +120,37 @@ export function ConfigProfile() {const [cloning, setCloning] = useState<{ sourceId: string, sourceName: string } | null>(null)const [cloneName, setCloneName] = useState('')+ /**+ * 档案名会直接当磁盘目录名与 CLI `--profile` 参数,只能用 ASCII 字母数字(`-`/`_`/空格+ * 分隔,其余字符被丢弃,与后端 `normalize_profile_id` 同一套规则)。归一化后为空说明+ * 整个名字都不可用(例如纯中文):在输入框下面就讲清楚,按钮同时置灰,不让用户提交后+ * 才撞上一个机器错误码。+ */+ function profileNameHint(value: string): string | null {+ if (value.trim() === '' || normalizeProfileId(value) !== '')+ return null+ return t('profiles.name_invalid_hint')+ }++ /**+ * 宿主错误串换成用户能看懂的一句话;未知错误码照原样显示,免得把真实原因吞掉。+ *+ * 「名字不可用」直接用输入框那条提示文案,「已存在」复用已有的 `clone_exists`(带名字),+ * 其余按码查表——同一件事在两个地方各写一份文案就是新的漂移源。+ */+ function profileErrorText(error: unknown, name: string): string {+ const code = String(error).split(':')[0]?.trim() ?? ''+ if (code === 'PROFILE_INVALID_NAME')+ return t('profiles.name_invalid_hint')+ if (code === 'PROFILE_EXISTS')+ return t('profiles.clone_exists', { name })+ const key = PROFILE_ERROR_KEYS[code]+ return key ? t(key) : String(error)+ }++ const createNameHint = profileNameHint(name)+ const cloneNameHint = profileNameHint(cloneName)+/** 推导下一个未占用的自动递增名称(仅作为建议,后端才是权威) */function suggestCloneName(base: string): string {const taken = new Set(profiles.map(p => p.id))@@ -135,6 +175,8 @@ export function ConfigProfile() {toast(t('profiles.clone_empty'), {})return}+ if (cloneNameHint !== null)+ returntry {await cloneProfile(cloning.sourceId, trimmed)setCloning(null)@@ -147,7 +189,7 @@ export function ConfigProfile() {}catch (err) {console.error('[ConfigProfile] clone failed:', err)- toast(t('profiles.clone_failed'), {})+ toast(t('profiles.clone_failed'), { description: profileErrorText(err, trimmed) })}}@@ -205,6 +247,8 @@ export function ConfigProfile() {const trimmed = name.trim()if (!trimmed)return+ if (createNameHint !== null)+ returntry {// 创建成功后列表已刷新出新档案,UI 本身就有变化,不再弹成功 toastawait createProfile(trimmed)@@ -213,7 +257,7 @@ export function ConfigProfile() {}catch (err) {console.error('[ConfigProfile] create failed:', err)- toast(t('profiles.create_failed'), {})+ toast(t('profiles.create_failed'), { description: profileErrorText(err, trimmed) })}}@@ -403,31 +447,39 @@ export function ConfigProfile() {<Ifcond={!creating}else={(- <div className="flex items-center gap-2 px-1">- <Input- autoFocus- variant="secondary"- className="h-8 flex-1 rounded-md"- placeholder={t('profiles.name_placeholder')}- value={name}- onChange={e => setName(e.target.value)}- onKeyDown={(e) => {- if (e.key === 'Enter')- commitCreate()- }}+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-2 px-1">+ <Input+ autoFocus+ variant="secondary"+ className="h-8 flex-1 rounded-md"+ placeholder={t('profiles.name_placeholder')}+ value={name}+ onChange={e => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter')+ commitCreate()+ }}+ />+ <Button size="sm" variant="tertiary" className="h-8 rounded-md" onPress={cancelCreate}>+ {t('profiles.create_cancel')}+ </Button>+ <Button+ size="sm"+ variant="primary"+ className="h-8 rounded-md"+ isDisabled={!name.trim() || createNameHint !== null || busy}+ onPress={commitCreate}+ >+ {t('profiles.create_confirm')}+ </Button>+ </div>+ <If+ cond={createNameHint !== null}+ then={(+ <p className="px-1 text-xs text-muted">{createNameHint}</p>+ )}/>- <Button size="sm" variant="tertiary" className="h-8 rounded-md" onPress={cancelCreate}>- {t('profiles.create_cancel')}- </Button>- <Button- size="sm"- variant="primary"- className="h-8 rounded-md"- isDisabled={!name.trim() || busy}- onPress={commitCreate}- >- {t('profiles.create_confirm')}- </Button></div>)}>@@ -477,6 +529,12 @@ export function ConfigProfile() {commitClone()}}/>+ <If+ cond={cloneNameHint !== null}+ then={(+ <p className="mb-1 text-xs text-muted">{cloneNameHint}</p>+ )}+ />{cloning && (<p className="text-xs text-muted">{t('profiles.clone_default_hint', { name: suggestCloneName(cloning.sourceId) })}@@ -490,7 +548,7 @@ export function ConfigProfile() {<ButtonclassName="rounded-md"variant="primary"- isDisabled={!cloneName.trim() || busy}+ isDisabled={!cloneName.trim() || cloneNameHint !== null || busy}onPress={commitClone}>{busy ? t('profiles.clone_cloning') : t('profiles.clone_confirm')}diff --git a/src/utils/toast.ts b/src/utils/toast.tsindex 696a7e6f..1ac9b62e 100644--- a/src/utils/toast.ts+++ b/src/utils/toast.ts@@ -4,10 +4,22 @@ import type { ReactNode } from 'react'import { ToastQueue } from '@heroui/react'import { hooks } from '@/config/hooks'+/** toast 关闭来源:库侧 close 不携带原因,只能由本模块预记或按超时配置反推 */+export type ToastCloseReason = 'closed' | 'evicted' | 'dismissed'+/** toast() 可选项:库内未暴露的 HeroUIToastOptions(toast-queue 收敛的 content + 超时回调),这里用公开的 ToastContentValue 组合 */-export type ToastOptions = Partial<ToastContentValue & { timeout?: number, onClose?: () => void }> & { placement?: Placement }+export type ToastOptions = Partial<ToastContentValue & { timeout?: number, onClose?: (reason: ToastCloseReason) => void }> & { placement?: Placement, sticky?: boolean }export type ToastUpdateOptions = Partial<ToastContentValue>+/**+ * react-stately 队列的内部形态:`updateVisibleToasts` 是 TS private 但运行时存在,+ * 只重建 visibleToasts 并通知订阅者,不改动条目,因此改 content 后必须自己调它。+ */+interface StatelyQueue {+ queue: Array<{ key: string, content?: ToastContentValue }>+ updateVisibleToasts: (action: string) => void+}+export type Placement = NonNullable<ToastVariants['placement']>export const placements = ['top start',@@ -38,16 +50,31 @@ export const activeQueues = navigator.platform.toLowerCase().includes('linux')const toastContents = new Map<string, ToastContentValue>()const placementsKeys = new Map<string, Placement>()+/**+ * 程序化关闭的原因旁路表。底层 react-stately 的 `close(key)` 对「自动超时 / 用户点+ * 关闭 / 外部 close」走同一条路径且不透传参数,本模块只能在调用 close 前先登记,+ * 回调时取出;未登记(用户点关闭按钮)再按超时配置反推,见 `takeCloseReason`。+ */+const closeReasons = new Map<string, ToastCloseReason>()/*** 每个 placement 的存活 key(按创建顺序,旧→新)。stately queue 对超出* maxVisibleToasts 的条目只做「窗口外排队、等旧条目关闭后复现」,常驻* (timeout: 0)气泡会无限积压并在旧气泡关闭时复现;这里在新 toast 入队后* 直接关闭最旧的条目,保证任何时刻只存在最新的 MAX_VISIBLE_TOASTS 条。+ * `sticky` 的气泡(授权按钮)不入表:它们必须一直可点,被淘汰就等于把用户+ * 堵在「等待授权」上再也点不到(见 config/plugin 的授权流程)。*/const placementOrder = new Map<Placement, string[]>()-function forgetKey(key: string): void {+/**+ * 同步清理一条 toast 的登记。`keepReason` 为真时保留关闭原因,供库侧稍后+ * (rAF 异步)触发的 onClose 读取——`close()` 必须这样调用,否则常驻气泡+ * (`timeout: 0`)的程序化关闭会被误判为用户拒绝。+ */+function forgetKey(key: string, keepReason = false): void {toastContents.delete(key)+ if (!keepReason)+ closeReasons.delete(key)const placement = placementsKeys.get(key)placementsKeys.delete(key)if (placement === undefined)@@ -63,53 +90,91 @@ function forgetKey(key: string): void {}/**- * 统一 toast API:直接调用创建,toast.update/close/clear 通过 key 管理。- * update 触发 `hooks['toast.updated']` 事件(见 config/hooks),由 ToastProvider 消费后- * 原地更新对应 queue 的 content(HeroUI ToastQueue 没有 update 方法)。+ * 关闭原因:优先取本模块登记的程序化原因;未登记说明是用户在气泡上点了关闭+ * (或自动超时),按该条是否配了自动关闭超时反推——配了就是超时自动消失,+ * 没配(`timeout: 0` 常驻)只能是用户点了关闭。+ */+function takeCloseReason(key: string, autoClose: boolean): ToastCloseReason {+ const recorded = closeReasons.get(key)+ if (recorded !== undefined) {+ closeReasons.delete(key)+ return recorded+ }+ return autoClose ? 'closed' : 'dismissed'+}++/**+ * 统一 toast API:直接调用创建,toast.update/close/clear/isActive 通过 key 管理。+ * HeroUI 默认气泡直接读队列条目的 content,而 HeroUI ToastQueue 没有 update 方法:+ * 这里原地改写条目 content 并通知 react-stately 队列重渲染,同时触发+ * `hooks['toast.updated']`(见 config/hooks)供桌宠窗口的自定义气泡消费。*/export const toast = Object.assign((message: string | ReactNode, options?: ToastOptions) => {// 默认右下角;个别调用方需要其他位置时显式传 placement- const { placement = 'bottom end', timeout, onClose, ...rest } = options || {}+ const { placement = 'bottom end', timeout, onClose, sticky = false, ...rest } = options || {}const content = { title: message, ...rest }+ // 未指定 timeout 时 HeroUI 会补默认超时(`constants: DEFAULT_TOAST_TIMEOUT`),+ // 因此「undefined 或正数」都意味着这条会自己消失。+ const autoClose = timeout === undefined || timeout > 0const key = activeQueues[placement].add(content, {timeout,onClose: () => {// 自动超时 / 用户关闭 / 外部 close 都会走到这里;延后业务回调,避免渲染中更新组件。+ const reason = takeCloseReason(key, autoClose)forgetKey(key)- queueMicrotask(() => onClose?.())+ queueMicrotask(() => onClose?.(reason))},})toastContents.set(key, content)placementsKeys.set(key, placement)+ if (sticky)+ return keyconst order = placementOrder.get(placement) ?? []order.push(key)placementOrder.set(placement, order)// 丢弃超出上限的最旧条目(含 rAF 清理延迟期内的死 key),维持「仅最新 N 条」while (order.length > MAX_VISIBLE_TOASTS) {const oldest = order.shift()- if (oldest !== undefined)+ if (oldest !== undefined) {+ closeReasons.set(oldest, 'evicted')activeQueues[placement].close(oldest)+ }}return key},{update(key: string, options: ToastUpdateOptions): void {- if (!placementsKeys.has(key))+ const placement = placementsKeys.get(key)+ if (placement === undefined)returntoastContents.set(key, { ...(toastContents.get(key) ?? {}), ...options })+ const queue = activeQueues[placement].getQueue() as unknown as StatelyQueue+ const entry = queue.queue.find(item => item.key === key)+ if (entry !== undefined) {+ entry.content = { ...entry.content, ...options }+ queue.updateVisibleToasts('update')+ }void hooks['toast.updated'].trigger({ key, options })},+ /** 该 key 是否仍是活着的 toast:被限额淘汰后 update/close 都会静默失效 */+ isActive(key: string): boolean {+ return placementsKeys.has(key)+ },+close(key: string): void {const placement = placementsKeys.get(key)if (placement) {+ closeReasons.set(key, 'closed')activeQueues[placement].close(key)- // onClose 是 rAF 异步回调,这里同步清理登记,紧随其后的 add 不会把死 key 计入限额- forgetKey(key)+ // onClose 是 rAF 异步回调:保留关闭原因到那时再取,但同步清掉其余登记,+ // 紧随其后的 add 不会把死 key 计入限额+ forgetKey(key, true)}else {toastContents.delete(key)+ closeReasons.delete(key)}},@@ -117,6 +182,7 @@ export const toast = Object.assign(toastContents.clear()placementsKeys.clear()placementOrder.clear()+ closeReasons.clear()placements.forEach(p => activeQueues[p].clear())},},diff --git a/test/plugin-disable.test.ts b/test/plugin-disable.test.tsindex d5452cfb..724af158 100644--- a/test/plugin-disable.test.ts+++ b/test/plugin-disable.test.ts@@ -9,12 +9,17 @@ describe('plugin disable/enable frontend contract', () => {expect(source).toContain('onEnable')})- it('config-plugin.tsx invokes the disable/enable commands directly', () => {- const source = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')-- // 面板直接持有 enable/disable mutation(与 upgrade/remove 同一层级)- expect(source).toContain('disable_dsh_plugin')- expect(source).toContain('enable_dsh_plugin')+ it('config-plugin.tsx routes disable/enable through the plugin manager', () => {+ const panel = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')+ const manager = readFileSync(new URL('../src/store/modules/plugins/store.ts', import.meta.url), 'utf8')++ expect(panel).toContain('manager.disable')+ expect(panel).toContain('manager.enable')+ // 宿主命令归管理器统一派发,面板不得再各自持有 mutation+ expect(panel).not.toContain('disable_dsh_plugin')+ expect(panel).not.toContain('enable_dsh_plugin')+ expect(manager).toContain('disable_dsh_plugin')+ expect(manager).toContain('enable_dsh_plugin')})it('config-plugin.tsx renders a Disabled badge via plugins.disabled_badge', () => {@@ -40,12 +45,18 @@ describe('plugin disable/enable frontend contract', () => {expect(onDisableMatch![0]).not.toContain('openDialog')})- it('config-plugin.tsx owns the plugin list query and update probe', () => {- const source = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')-- expect(source).toContain('get_dsh_plugins')- expect(source).toContain('refresh_plugin_updates')- expect(source).toContain('queryKeys.plugins')+ it('the plugin manager owns the single plugin list query and update probe', () => {+ const hook = readFileSync(new URL('../src/hooks/use-plugins-manager.ts', import.meta.url), 'utf8')+ const store = readFileSync(new URL('../src/store/modules/plugins/store.ts', import.meta.url), 'utf8')+ const panel = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')++ expect(hook).toContain('get_dsh_plugins')+ expect(hook).toContain('queryKeys.plugins')+ expect(store).toContain('refresh_plugin_updates')+ // 面板只消费 manager.installed,不再自行查询(消除重复查询)+ expect(panel).not.toContain('get_dsh_plugins')+ expect(panel).not.toContain('refresh_plugin_updates')+ expect(panel).toContain('manager.installed')})it('en-US.json contains all 7 disable/enable i18n keys', () => {diff --git a/test/plugin-manager-api.test.ts b/test/plugin-manager-api.test.tsnew file mode 100644index 00000000..055af40f--- /dev/null+++ b/test/plugin-manager-api.test.ts@@ -0,0 +1,251 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++interface ToastCallOptions {+ timeout?: number+ onClose?: (reason: string) => void+}++const { invoke, restart, toast } = vi.hoisted(() => {+ const toastFn = vi.fn((_message: string, _options?: ToastCallOptions) => 'toast-key')+ return {+ invoke: vi.fn(),+ restart: vi.fn(),+ toast: Object.assign(toastFn, { close: vi.fn(), update: vi.fn(), clear: vi.fn(), isActive: vi.fn(() => true) }),+ }+})++vi.mock('@tauri-apps/api/core', () => ({ invoke }))+vi.mock('../src/store/modules/harness', () => ({ harness: { restart } }))+vi.mock('@/utils/toast', () => ({ toast }))++const { normalizeRef, normalizeRefs, plugins } = await import('../src/store/modules/plugins')++const RUNTIME = { toast: false, restartOnSettle: false }++beforeEach(() => {+ invoke.mockReset()+ toast.mockClear()+ toast.close.mockClear()+ restart.mockClear()+ plugins.groups = []+ plugins.processes = []+ plugins.logs = []+ plugins.activeGroupId = null+ plugins.cancelling = false+ plugins.installedSource = []+ plugins.installedLoaded = false+ plugins.queueResults = []+})++describe('plugins manager ref normalization', () => {+ it('normalizes bare names, declared ranges, explicit versions and scoped packages', () => {+ expect(normalizeRef('aaa')).toEqual({ spec: 'aaa', name: 'aaa' })+ expect(normalizeRef(' aaa ')).toEqual({ spec: 'aaa', name: 'aaa' })+ expect(normalizeRef('aaa@^1.2.0')).toEqual({ spec: 'aaa@^1.2.0', name: 'aaa', version: '^1.2.0' })+ expect(normalizeRef({ spec: 'aaa', version: '1.2.3' })).toEqual({+ spec: '[email protected]',+ name: 'aaa',+ version: '1.2.3',+ })+ expect(normalizeRef({ spec: '[email protected]', version: '2.0.0' })).toEqual({+ spec: '[email protected]',+ name: 'aaa',+ version: '2.0.0',+ })+ expect(normalizeRef('@scope/[email protected]')).toEqual({+ spec: '@scope/[email protected]',+ name: '@scope/pkg',+ version: '1.0.0',+ })+ expect(normalizeRef('@scope/pkg')).toEqual({ spec: '@scope/pkg', name: '@scope/pkg' })+ })++ it('rejects illegal refs synchronously, before any host call', () => {+ expect(() => normalizeRef('')).toThrow('PLUGIN_REF_INVALID')+ expect(() => normalizeRef(' ')).toThrow('PLUGIN_REF_INVALID')+ expect(() => normalizeRefs([])).toThrow('PLUGIN_REFS_EMPTY')+ expect(() => plugins.enqueue('install', [], RUNTIME)).toThrow('PLUGIN_REFS_EMPTY')+ expect(() => plugins.enqueue('install', [' '], RUNTIME)).toThrow('PLUGIN_REF_INVALID')+ expect(invoke).not.toHaveBeenCalled()+ expect(plugins.processes).toEqual([])+ })++ it('collapses a single ref into a one element group', () => {+ expect(normalizeRefs('aaa')).toEqual([{ spec: 'aaa', name: 'aaa' }])+ expect(normalizeRefs(['aaa', '[email protected]'])).toEqual([+ { spec: 'aaa', name: 'aaa' },+ { spec: '[email protected]', name: 'bbb', version: '2.0.0' },+ ])+ })+})++describe('plugins manager idempotency', () => {+ it('reports an uninstall of an absent plugin as already absent without calling the host', async () => {+ plugins.setInstalled([])++ const results = await plugins.enqueue('uninstall', ['ghost'], RUNTIME)++ expect(invoke).not.toHaveBeenCalled()+ expect(results.map(result => [result.process.name, result.ok, result.reason])).toEqual([+ ['ghost', false, 'already-absent'],+ ])+ })++ it('sends an upgrade of an unknown plugin to the host instead of pre-skipping it', async () => {+ plugins.setInstalled([])++ const results = await plugins.enqueue('upgrade', ['ghost'], RUNTIME)++ expect(invoke).toHaveBeenCalledWith('update_dsh_plugins', { ids: ['ghost'] })+ expect(results.map(result => [result.ok, result.reason])).toEqual([[true, undefined]])+ })++ it('routes a broken plugin through the upgrade repair path despite having no update', async () => {+ plugins.setInstalled([+ {+ id: 'aaa',+ name: 'aaa',+ version: '1.0.0',+ description: '',+ repo_url: '',+ bundled: false,+ disabled: false,+ patchDisabled: false,+ recommended: false,+ fix: false,+ internal: false,+ updateAvailable: false,+ hasSnapshot: false,+ error: { message: 'boom', action: 'runtime', at: '1' },+ },+ ])+ invoke.mockResolvedValue(undefined)++ const results = await plugins.enqueue('upgrade', ['aaa'], RUNTIME)++ expect(invoke).toHaveBeenCalledWith('update_dsh_plugins', { ids: ['aaa'] })+ expect(results.map(result => [result.process.name, result.ok])).toEqual([['aaa', true]])+ })++ it('passes the target version the panel is showing to the host', async () => {+ plugins.setInstalled([+ {+ id: 'aaa',+ name: 'aaa',+ version: '1.0.0',+ description: '',+ repo_url: '',+ bundled: false,+ disabled: false,+ patchDisabled: false,+ recommended: false,+ fix: false,+ internal: false,+ updateAvailable: true,+ hasSnapshot: false,+ error: null,+ },+ ])+ invoke.mockResolvedValue(undefined)++ await plugins.enqueue('upgrade', [{ spec: 'aaa', version: '2.0.0' }], RUNTIME)++ expect(invoke).toHaveBeenCalledWith('update_dsh_plugins', { ids: ['[email protected]'] })+ })++ it('hands every clicked upgrade to the host even when the local snapshot says there is no update', async () => {+ // 面板点得动的插件必须交给宿主:本地快照(`installedSource`)可能刚被安装/刷新改过,按它判+ // 「没有更新」会把点击悄悄丢掉——用户只看到「1 个成功」,别的插件毫无动静。+ plugins.setInstalled(+ ['aaa', 'bbb', 'ccc'].map(name => ({+ id: name,+ name,+ version: '1.0.0',+ description: '',+ repo_url: '',+ bundled: false,+ disabled: false,+ patchDisabled: false,+ recommended: false,+ fix: false,+ internal: false,+ updateAvailable: false,+ hasSnapshot: false,+ error: null,+ })),+ )+ invoke.mockResolvedValue(undefined)++ const results = await plugins.enqueue('upgrade', ['aaa', 'bbb', 'ccc'], RUNTIME)++ expect(invoke).toHaveBeenCalledWith('update_dsh_plugins', { ids: ['aaa', 'bbb', 'ccc'] })+ expect(results.map(result => [result.process.name, result.ok])).toEqual([+ ['aaa', true],+ ['bbb', true],+ ['ccc', true],+ ])+ })++ it('reports a disable of an already disabled plugin as already absent', async () => {+ plugins.setInstalled([+ {+ id: 'aaa',+ name: 'aaa',+ version: '1.0.0',+ description: '',+ repo_url: '',+ bundled: false,+ disabled: true,+ patchDisabled: false,+ recommended: false,+ fix: false,+ internal: false,+ updateAvailable: false,+ hasSnapshot: false,+ error: null,+ },+ ])++ const results = await plugins.enqueue('disable', ['aaa'], RUNTIME)++ expect(invoke).not.toHaveBeenCalled()+ expect(results.map(result => [result.ok, result.reason])).toEqual([[false, 'already-absent']])+ })+})++describe('plugins manager search', () => {+ it('degrades to a network problem when the compatibility probe fails', async () => {+ invoke.mockRejectedValue('NETWORK_DOWN: offline')++ const results = await plugins.search(['aaa', { spec: 'bbb', version: '1.0.0' }])++ expect(invoke).toHaveBeenCalledWith('inspect_plugin_specs', {+ specs: ['aaa', '[email protected]'],+ dsh: null,+ })+ expect(results).toEqual([+ { spec: 'aaa', compatible: null, problem: 'network' },+ { spec: '[email protected]', compatible: null, problem: 'network' },+ ])+ })++ it('forwards the runtime version override and normalizes the probe result', async () => {+ invoke.mockResolvedValue([+ { spec: 'aaa', name: 'aaa', version: '1.2.3', compatible: true, peers: { '@deepseek-ai/dsh': '^0.2.0' } },+ ])++ const results = await plugins.search('aaa', { dsh: '0.2.0' })++ expect(invoke).toHaveBeenCalledWith('inspect_plugin_specs', { specs: ['aaa'], dsh: '0.2.0' })+ expect(results).toEqual([+ {+ spec: 'aaa',+ name: 'aaa',+ version: '1.2.3',+ compatible: true,+ peers: { '@deepseek-ai/dsh': '^0.2.0' },+ problem: undefined,+ },+ ])+ })+})diff --git a/test/plugin-manager-approve.test.ts b/test/plugin-manager-approve.test.tsnew file mode 100644index 00000000..c3dbd815--- /dev/null+++ b/test/plugin-manager-approve.test.ts@@ -0,0 +1,236 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++interface ToastCallOptions {+ timeout?: number+ variant?: string+ isLoading?: boolean+ onClose?: (reason: string) => void+}++const { invoke, restart, toast } = vi.hoisted(() => {+ const toastFn = vi.fn((_message: string, _options?: ToastCallOptions) => 'toast-key')+ return {+ invoke: vi.fn(),+ restart: vi.fn(),+ toast: Object.assign(toastFn, { close: vi.fn(), update: vi.fn(), clear: vi.fn(), isActive: vi.fn(() => true) }),+ }+})++vi.mock('@tauri-apps/api/core', () => ({ invoke }))+vi.mock('../src/store/modules/harness', () => ({ harness: { restart } }))+vi.mock('@/utils/toast', () => ({ toast }))++const { plugins } = await import('../src/store/modules/plugins')++const RUNTIME = { toast: false, restartOnSettle: false }++const BLOCKED = [{ name: 'b', version: '0.22.1', runtime_version: '0.2.0-rc.1' }]+const POLICY = [{ name: 'b', version: '2.11.2' }]++function approvalToast() {+ return toast.mock.calls.find(call => call[1]?.onClose !== undefined)+}++beforeEach(() => {+ invoke.mockReset()+ toast.mockClear()+ toast.close.mockClear()+ restart.mockClear()+ plugins.groups = []+ plugins.processes = []+ plugins.logs = []+ plugins.activeGroupId = null+ plugins.cancelling = false+ plugins.installedSource = []+ plugins.installedLoaded = false+ plugins.queueResults = []+})++describe('plugins manager approval', () => {+ it('attributes a refusal to the named process and returns the untouched ones to pending', async () => {+ let installCalls = 0+ invoke.mockImplementation(async (command: string) => {+ if (command !== 'install_plugin_specs')+ return undefined+ installCalls += 1+ if (installCalls === 1)+ throw new Error(`PLUGIN_VERSION_INCOMPATIBLE: ${JSON.stringify(BLOCKED)}`)+ return undefined+ })++ void plugins.enqueue('install', ['a', 'b'], RUNTIME)+ await vi.waitFor(() => expect(plugins.pendingApprovals).toHaveLength(1))++ const blocked = plugins.pendingApprovals[0]+ expect(blocked.name).toBe('b')+ expect(blocked.refusal?.kind).toBe('incompatible')+ expect(plugins.processes.map(process => [process.name, process.status])).toEqual([+ ['a', 'pending'],+ ['b', 'unauthorized'],+ ])++ const results = await plugins.approve('b')++ expect(invoke).toHaveBeenCalledWith('allow_plugin_versions', { versions: BLOCKED })+ expect(invoke.mock.calls.filter(call => call[0] === 'install_plugin_specs')).toHaveLength(2)+ expect(results.map(result => [result.process.name, result.ok])).toEqual([['a', true], ['b', true]])+ })++ it('re-submits only the processes that are still outstanding after a grant', async () => {+ let secondAttempt = 0+ invoke.mockImplementation(async (command: string, args: Record<string, unknown>) => {+ if (command !== 'disable_dsh_plugin')+ return undefined+ if (args.id === 'a')+ return undefined+ secondAttempt += 1+ if (secondAttempt === 1)+ throw new Error(`PLUGIN_POLICY_BLOCKED: ${JSON.stringify(POLICY)}`)+ return undefined+ })++ void plugins.enqueue('disable', ['a', 'b'], RUNTIME)+ await vi.waitFor(() => expect(plugins.pendingApprovals).toHaveLength(1))++ expect(plugins.processes).toHaveLength(1)+ expect(plugins.processes[0].name).toBe('b')+ expect(plugins.processes[0].refusal?.kind).toBe('policy')++ const results = await plugins.approve('b')++ expect(invoke).toHaveBeenCalledWith('allow_plugin_policy_versions', { versions: POLICY })+ expect(invoke.mock.calls+ .filter(call => call[0] === 'disable_dsh_plugin')+ .map(call => (call[1] as { id: string }).id)).toEqual(['a', 'b', 'b'])+ expect(results.map(result => [result.process.name, result.ok])).toEqual([['a', true], ['b', true]])+ })++ it('fails the group instead of hanging when the refusal names a package outside the submission', async () => {+ const outside = [{ name: 'transitive-dep', version: '0.1.0', runtime_version: '0.2.0-rc.1' }]+ invoke.mockImplementation(async (command: string) => {+ if (command === 'install_plugin_specs')+ throw new Error(`PLUGIN_VERSION_INCOMPATIBLE: ${JSON.stringify(outside)}`)+ return undefined+ })++ const done = plugins.enqueue('install', ['aaa'], RUNTIME)+ const guarded = await Promise.race([+ done,+ new Promise(resolve => setTimeout(resolve, 500, 'hung')),+ ])++ expect(guarded).not.toBe('hung')+ const results = await done+ expect(results.map(result => [result.process.name, result.ok])).toEqual([['aaa', false]])+ expect(plugins.pendingApprovals).toHaveLength(0)+ })++ it('records a cancelled process once even when the interrupted host call settles later', async () => {+ const releases: Array<(error: unknown) => void> = []+ invoke.mockImplementation((command: string) => {+ if (command !== 'install_plugin_specs')+ return Promise.resolve(undefined)+ return new Promise((_resolve, reject) => {+ releases.push(reject)+ })+ })++ const done = plugins.enqueue('install', ['aaa'], RUNTIME)+ await vi.waitFor(() => expect(releases).toHaveLength(1))++ void plugins.cancel()+ await vi.waitFor(() => expect(plugins.processes).toHaveLength(0))++ releases[0](new Error('PREINSTALL_FAILED: killed'))+ const results = await done++ expect(results.map(result => [result.process.name, result.ok, result.reason])).toEqual([+ ['aaa', false, 'cancelled'],+ ])+ })++ it('raises a persistent approval toast per blocked process', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command === 'install_plugin_specs')+ throw new Error(`PLUGIN_VERSION_INCOMPATIBLE: ${JSON.stringify(BLOCKED)}`)+ return undefined+ })+ const done = plugins.enqueue('install', ['b'], { toast: true, restartOnSettle: false })+ await vi.waitFor(() => expect(plugins.pendingApprovals).toHaveLength(1))++ const approval = approvalToast()+ expect(approval?.[1]?.timeout).toBe(0)++ await plugins.cancel()+ await done+ expect(plugins.pendingApprovals).toHaveLength(0)+ })++ it('keeps the process unauthorized when the toast is closed for any reason but dismissal', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command === 'install_plugin_specs')+ throw new Error(`PLUGIN_VERSION_INCOMPATIBLE: ${JSON.stringify(BLOCKED)}`)+ return undefined+ })+ const done = plugins.enqueue('install', ['b'], { toast: true, restartOnSettle: false })+ await vi.waitFor(() => expect(plugins.pendingApprovals).toHaveLength(1))++ approvalToast()?.[1]?.onClose?.('closed')+ await Promise.resolve()+ expect(plugins.pendingApprovals).toHaveLength(1)++ await plugins.cancel()+ const results = await done+ expect(results.map(result => [result.ok, result.reason])).toEqual([[false, 'cancelled']])+ })++ it('rejects the process when the approval toast is dismissed by the user', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command === 'install_plugin_specs')+ throw new Error(`PLUGIN_VERSION_INCOMPATIBLE: ${JSON.stringify(BLOCKED)}`)+ return undefined+ })+ const done = plugins.enqueue('install', ['b'], { toast: true, restartOnSettle: false })+ await vi.waitFor(() => expect(plugins.pendingApprovals).toHaveLength(1))++ approvalToast()?.[1]?.onClose?.('dismissed')++ const results = await done+ expect(results.map(result => [result.process.name, result.ok, result.reason])).toEqual([+ ['b', false, 'rejected'],+ ])+ expect(plugins.pendingApprovals).toHaveLength(0)+ expect(toast.close).toHaveBeenCalled()+ // 拒绝是用户自己的选择:不再补一条「失败」提示追问他。+ expect(+ toast.mock.calls.filter(call => call[1]?.variant === 'danger' && call[1]?.onClose === undefined),+ ).toHaveLength(0)+ })++ it('ignores a refusal that arrives after the user cancelled the group', async () => {+ let release: (() => void) | undefined+ const gate = new Promise<void>((resolve) => {+ release = resolve+ })+ invoke.mockImplementation(async (command: string) => {+ if (command !== 'install_plugin_specs')+ return undefined+ await gate+ throw new Error(`PLUGIN_VERSION_INCOMPATIBLE: ${JSON.stringify(BLOCKED)}`)+ })++ const done = plugins.enqueue('install', ['b'], RUNTIME)+ await vi.waitFor(() => expect(invoke.mock.calls.some(call => call[0] === 'install_plugin_specs')).toBe(true))++ await plugins.cancel()+ release?.()++ const results = await done+ expect(results.map(result => [result.process.name, result.ok, result.reason])).toEqual([+ ['b', false, 'cancelled'],+ ])+ // 迟到的拒绝不能给已取消的进程重新挂一个没人点的授权等待,否则整条队列永久卡在 resume 上。+ expect(plugins.pendingApprovals).toHaveLength(0)+ expect(plugins.groups).toHaveLength(0)+ })+})diff --git a/test/plugin-manager-progress.test.ts b/test/plugin-manager-progress.test.tsnew file mode 100644index 00000000..a0a7b3cd--- /dev/null+++ b/test/plugin-manager-progress.test.ts@@ -0,0 +1,180 @@+import i18next from 'i18next'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { resources } from '../src/i18n/index.resource'++interface ToastCallOptions {+ timeout?: number+ isLoading?: boolean+ description?: string+ title?: string+ onClose?: (reason: string) => void+}++const { invoke, restart, toast, update, isActive } = vi.hoisted(() => {+ let index = 0+ const updateFn = vi.fn()+ const isActiveFn = vi.fn(() => true)+ const toastFn = vi.fn((_message: string, _options?: ToastCallOptions): string => `toast-${++index}`)+ return {+ invoke: vi.fn(),+ restart: vi.fn(),+ update: updateFn,+ isActive: isActiveFn,+ toast: Object.assign(toastFn, { close: vi.fn(), update: updateFn, clear: vi.fn(), isActive: isActiveFn }),+ }+})++vi.mock('@tauri-apps/api/core', () => ({ invoke }))+vi.mock('../src/store/modules/harness', () => ({ harness: { restart } }))+vi.mock('@/utils/toast', () => ({ toast }))++// 与 src/i18n/index.ts 相同的扁平 key 约定:标题断言取真实文案而非未初始化的 key+await i18next.init({+ lng: 'en-US',+ fallbackLng: 'en-US',+ resources: resources as unknown as Record<string, { translation: Record<string, string> }>,+ interpolation: { escapeValue: false },+ keySeparator: false,+ nsSeparator: false,+ initAsync: false,+})++const { plugins } = await import('../src/store/modules/plugins')++const RUNTIME = { toast: true, restartOnSettle: false }+const BLOCKED = [{ name: 'b', version: '0.22.1', runtime_version: '0.2.0-rc.1' }]++function progressKey(): string {+ return toast.mock.results[0]?.value as string+}++beforeEach(() => {+ invoke.mockReset()+ invoke.mockResolvedValue(undefined)+ toast.mockClear()+ toast.close.mockClear()+ update.mockClear()+ isActive.mockReset()+ isActive.mockReturnValue(true)+ restart.mockClear()+ plugins.groups = []+ plugins.processes = []+ plugins.logs = []+ plugins.activeGroupId = null+ plugins.cancelling = false+ plugins.installedSource = []+ plugins.installedLoaded = false+ plugins.progressKey = null+ plugins.progressDetail = ''+ plugins.queueResults = []+})++describe('plugins manager progress toast', () => {+ it('opens the shared bubble in the loading state with the single plugin title', async () => {+ invoke.mockImplementation(() => new Promise(() => {}))++ void plugins.enqueue('upgrade', ['aaa'], RUNTIME)++ await vi.waitFor(() => expect(toast).toHaveBeenCalledTimes(1))+ expect(toast.mock.calls[0][0]).toBe('Upgrading aaa...')+ expect(toast.mock.calls[0][1]).toMatchObject({ timeout: 0, isLoading: true })+ })++ it('switches to the aggregate title as soon as another plugin joins the queue', async () => {+ invoke.mockImplementation(() => new Promise(() => {}))++ void plugins.enqueue('upgrade', ['aaa'], RUNTIME)+ await vi.waitFor(() => expect(toast).toHaveBeenCalledTimes(1))++ void plugins.enqueue('upgrade', ['bbb'], RUNTIME)++ await vi.waitFor(() => expect(update).toHaveBeenCalled())+ expect(update).toHaveBeenCalledWith(progressKey(), expect.objectContaining({+ title: 'Upgrading 2 plugins...',+ isLoading: true,+ }))+ })++ it('falls back to the generic title when the queue mixes process types', async () => {+ invoke.mockImplementation(() => new Promise(() => {}))++ void plugins.enqueue('upgrade', ['aaa'], RUNTIME)+ await vi.waitFor(() => expect(toast).toHaveBeenCalledTimes(1))++ void plugins.enqueue('uninstall', ['bbb'], RUNTIME)++ await vi.waitFor(() => expect(update).toHaveBeenCalled())+ expect(update).toHaveBeenLastCalledWith(progressKey(), expect.objectContaining({+ title: 'Processing 2 plugins...',+ }))+ })++ it('renders the newest install log line as the description', async () => {+ invoke.mockImplementation(() => new Promise(() => {}))++ void plugins.enqueue('install', ['aaa'], RUNTIME)+ await vi.waitFor(() => expect(toast).toHaveBeenCalledTimes(1))++ plugins.setProgressDetail('Progress: resolved 1, reused 0')+ plugins.setProgressDetail('added 1 package')++ expect(update).toHaveBeenLastCalledWith(progressKey(), { description: 'added 1 package' })+ })++ it('hides the loading bubble while an approval is pending and restores it after the grant', async () => {+ let installCalls = 0+ invoke.mockImplementation(async (command: string) => {+ if (command !== 'install_plugin_specs')+ return undefined+ installCalls += 1+ if (installCalls === 1)+ throw new Error(`PLUGIN_VERSION_INCOMPATIBLE: ${JSON.stringify(BLOCKED)}`)+ return undefined+ })++ const done = plugins.enqueue('install', ['b'], RUNTIME)+ await vi.waitFor(() => expect(plugins.pendingApprovals).toHaveLength(1))++ expect(toast.close).toHaveBeenCalledWith(progressKey())+ expect(plugins.progressKey).toBeNull()++ await plugins.approve('b')+ const results = await done++ expect(results.map(result => [result.process.name, result.ok])).toEqual([['b', true]])+ expect(plugins.progressKey).toBeNull()+ })++ it('rebuilds the shared bubble once the previous one is no longer active', async () => {+ let submissions = 0+ invoke.mockImplementation(async (command: string) => {+ if (command !== 'update_dsh_plugins')+ return undefined+ submissions += 1+ if (submissions > 1)+ await new Promise(() => {})+ return undefined+ })+ // 第一组结算时把共享气泡标记为已消失(结果提示改到队列排空后才出现,这里模拟授权等其他气泡把它挤掉)+ plugins.on('completed', () => {+ isActive.mockReturnValue(false)+ })++ const first = plugins.enqueue('upgrade', ['aaa'], RUNTIME)+ await vi.waitFor(() => expect(toast).toHaveBeenCalledTimes(1))+ void plugins.enqueue('upgrade', ['bbb'], RUNTIME)+ await first++ await vi.waitFor(() => expect(toast.mock.calls.length).toBeGreaterThanOrEqual(2))++ plugins.setProgressDetail('added 1 package')+ expect(plugins.progressDetail).toBe('')+ expect(update).not.toHaveBeenCalledWith(progressKey(), { description: 'added 1 package' })++ const rebuilt = toast.mock.results.at(-1)?.value as string+ expect(rebuilt).not.toBe(progressKey())+ expect(toast.mock.calls.at(-1)?.[0]).toBe('Upgrading bbb...')+ expect(toast.mock.calls.at(-1)?.[1]).toMatchObject({ timeout: 0, isLoading: true })+ expect(plugins.progressKey).toBe(rebuilt)+ })+})diff --git a/test/plugin-manager-queue.test.ts b/test/plugin-manager-queue.test.tsnew file mode 100644index 00000000..ecce8ed1--- /dev/null+++ b/test/plugin-manager-queue.test.ts@@ -0,0 +1,125 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++interface ToastCallOptions {+ timeout?: number+ onClose?: (reason: string) => void+}++const { invoke, restart, toast } = vi.hoisted(() => {+ const toastFn = vi.fn((_message: string, _options?: ToastCallOptions) => 'toast-key')+ return {+ invoke: vi.fn(),+ restart: vi.fn(),+ toast: Object.assign(toastFn, { close: vi.fn(), update: vi.fn(), clear: vi.fn(), isActive: vi.fn(() => true) }),+ }+})++vi.mock('@tauri-apps/api/core', () => ({ invoke }))+vi.mock('../src/store/modules/harness', () => ({ harness: { restart } }))+vi.mock('@/utils/toast', () => ({ toast }))++const { plugins } = await import('../src/store/modules/plugins')++const RUNTIME = { toast: false, restartOnSettle: false }++function resetStore() {+ invoke.mockReset()+ toast.mockClear()+ toast.close.mockClear()+ restart.mockClear()+ plugins.groups = []+ plugins.processes = []+ plugins.logs = []+ plugins.activeGroupId = null+ plugins.cancelling = false+ plugins.installedSource = []+ plugins.installedLoaded = false+ plugins.queueResults = []+}++beforeEach(resetStore)++describe('plugins manager queue', () => {+ it('submits the next group only after the running group settles', async () => {+ let releaseFirst!: () => void+ const firstGate = new Promise<void>((resolve) => {+ releaseFirst = resolve+ })+ invoke.mockImplementation(async (command: string, args: Record<string, unknown>) => {+ if (command !== 'install_plugin_specs')+ return undefined+ if ((args.specs as string[])[0] === 'a')+ await firstGate+ return undefined+ })++ const firstDone = plugins.enqueue('install', ['a'], RUNTIME)+ const secondDone = plugins.enqueue('install', ['b'], RUNTIME)++ await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(1))+ expect(invoke.mock.calls[0][1]).toEqual({ specs: ['a'] })++ releaseFirst()+ await firstDone+ await secondDone++ expect(invoke.mock.calls.map(call => (call[1] as { specs: string[] }).specs)).toEqual([['a'], ['b']])+ })++ it('merges every install ref of one group into a single host call', async () => {+ invoke.mockResolvedValue(undefined)++ const results = await plugins.enqueue('install', ['a', 'b'], RUNTIME)++ expect(invoke).toHaveBeenCalledTimes(1)+ expect(invoke).toHaveBeenCalledWith('install_plugin_specs', { specs: ['a', 'b'] })+ expect(results).toHaveLength(2)+ expect(results.every(result => result.ok)).toBe(true)+ })++ it('dispatches a disable group concurrently per plugin id', async () => {+ const releases: Array<() => void> = []+ const started: string[] = []+ invoke.mockImplementation((_command: string, args: Record<string, unknown>) => {+ started.push(args.id as string)+ return new Promise<void>((resolve) => {+ releases.push(resolve)+ })+ })++ const done = plugins.enqueue('disable', ['a', 'b'], RUNTIME)++ await vi.waitFor(() => expect(started).toHaveLength(2))+ expect(invoke).toHaveBeenCalledTimes(2)+ expect(invoke.mock.calls.map(call => (call[1] as { id: string }).id)).toEqual(['a', 'b'])++ releases.forEach(release => release())+ const results = await done+ expect(results.every(result => result.ok)).toBe(true)+ })++ it('runs an enable group through the per-plugin command with the override flag', async () => {+ invoke.mockResolvedValue(undefined)++ await plugins.enqueue('enable', ['a'], { ...RUNTIME, clearConfigOverride: true })++ expect(invoke).toHaveBeenCalledTimes(1)+ expect(invoke).toHaveBeenCalledWith('enable_dsh_plugin', { id: 'a', clearConfigOverride: true })+ })++ it('keeps queue order when a later group is enqueued while an earlier one is settling', async () => {+ invoke.mockResolvedValue(undefined)++ const first = plugins.enqueue('install', ['a'], RUNTIME)+ const second = plugins.enqueue('upgrade', ['b'], RUNTIME)+ const third = plugins.enqueue('uninstall', ['c'], RUNTIME)++ await Promise.all([first, second, third])++ expect(invoke.mock.calls.map(call => call[0])).toEqual([+ 'install_plugin_specs',+ 'update_dsh_plugins',+ 'remove_dsh_plugins',+ ])+ })+})diff --git a/test/plugin-manager-settle.test.ts b/test/plugin-manager-settle.test.tsnew file mode 100644index 00000000..0ca20ec4--- /dev/null+++ b/test/plugin-manager-settle.test.ts@@ -0,0 +1,139 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++interface ToastCallOptions {+ timeout?: number+ isLoading?: boolean+ onClose?: (reason: string) => void+ actionProps?: { onPress?: () => void }+}++const { invoke, restart, toast } = vi.hoisted(() => {+ const toastFn = vi.fn((_message: string, _options?: ToastCallOptions) => 'toast-key')+ return {+ invoke: vi.fn(),+ restart: vi.fn(),+ toast: Object.assign(toastFn, { close: vi.fn(), update: vi.fn(), clear: vi.fn(), isActive: vi.fn(() => true) }),+ }+})++vi.mock('@tauri-apps/api/core', () => ({ invoke }))+vi.mock('../src/store/modules/harness', () => ({ harness: { restart } }))+vi.mock('@/utils/toast', () => ({ toast }))++const { plugins } = await import('../src/store/modules/plugins')++const RUNTIME = { toast: false, restartOnSettle: false }++beforeEach(() => {+ invoke.mockReset()+ toast.mockClear()+ toast.close.mockClear()+ restart.mockClear()+ plugins.groups = []+ plugins.processes = []+ plugins.logs = []+ plugins.activeGroupId = null+ plugins.cancelling = false+ plugins.installedSource = []+ plugins.installedLoaded = false+ plugins.queueResults = []+})++describe('plugins manager settle', () => {+ it('asks before restarting instead of restarting a succeeding group on its own', 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)+ })++ it('leaves the harness running when restartOnSettle is disabled', async () => {+ invoke.mockResolvedValue(undefined)++ await plugins.enqueue('install', ['a'], RUNTIME)++ expect(restart).not.toHaveBeenCalled()+ expect(toast.mock.calls.some(call => call[1]?.actionProps !== undefined)).toBe(false)+ })++ it('does not restart when every process of the group failed', async () => {+ invoke.mockRejectedValue('REGISTRY_DOWN: registry unreachable')++ const results = await plugins.enqueue('install', ['a'], { toast: true, restartOnSettle: true })++ expect(results.map(result => [result.ok, result.code, result.reason])).toEqual([+ [false, 'REGISTRY_DOWN', undefined],+ ])+ expect(restart).not.toHaveBeenCalled()+ expect(toast.mock.calls.some(call => call[1]?.actionProps !== undefined)).toBe(false)+ })++ it('does not restart when every process was skipped before reaching the host', async () => {+ invoke.mockResolvedValue(undefined)+ plugins.setInstalled([])++ const results = await plugins.enqueue('uninstall', ['a'], { toast: true, restartOnSettle: true })++ expect(results.map(result => [result.ok, result.reason])).toEqual([[false, 'already-absent']])+ expect(invoke).not.toHaveBeenCalled()+ expect(restart).not.toHaveBeenCalled()+ expect(toast.mock.calls.some(call => call[1]?.actionProps !== undefined)).toBe(false)+ })++ it('emits completed, error and allcompleted around a failing group', async () => {+ invoke.mockRejectedValue('REGISTRY_DOWN: registry unreachable')+ const seen: string[] = []+ const offs = [+ plugins.on('completed', () => seen.push('completed')),+ plugins.on('error', () => seen.push('error')),+ plugins.on('allcompleted', () => seen.push('allcompleted')),+ ]++ try {+ await plugins.enqueue('install', ['a'], RUNTIME)+ }+ finally {+ offs.forEach(off => off())+ }++ expect(seen).toEqual(['completed', 'error', 'allcompleted'])+ })++ it('emits allcompleted only once the queue is drained', async () => {+ invoke.mockResolvedValue(undefined)+ const seen: string[] = []+ const off = plugins.on('allcompleted', payload => seen.push(String(payload.length)))++ try {+ await Promise.all([+ plugins.enqueue('install', ['a'], RUNTIME),+ plugins.enqueue('install', ['b'], RUNTIME),+ ])+ }+ finally {+ off()+ }++ expect(seen).toEqual(['1'])+ })+})diff --git a/test/plugin-manager-summary.test.ts b/test/plugin-manager-summary.test.tsnew file mode 100644index 00000000..77206f30--- /dev/null+++ b/test/plugin-manager-summary.test.ts@@ -0,0 +1,110 @@+import i18next from 'i18next'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { resources } from '../src/i18n/index.resource'++interface ToastCallOptions {+ timeout?: number+ variant?: string+ isLoading?: boolean+ description?: string+ actionProps?: { children?: string, onPress?: () => void }+}++const { invoke, restart, toast } = vi.hoisted(() => {+ let index = 0+ const toastFn = vi.fn((_message: string, _options?: ToastCallOptions): string => `toast-${++index}`)+ return {+ invoke: vi.fn(),+ restart: vi.fn(),+ toast: Object.assign(toastFn, { close: vi.fn(), update: vi.fn(), clear: vi.fn(), isActive: vi.fn(() => true) }),+ }+})++vi.mock('@tauri-apps/api/core', () => ({ invoke }))+vi.mock('../src/store/modules/harness', () => ({ harness: { restart } }))+vi.mock('@/utils/toast', () => ({ toast }))++await i18next.init({+ lng: 'en-US',+ fallbackLng: 'en-US',+ resources: resources as unknown as Record<string, { translation: Record<string, string> }>,+ interpolation: { escapeValue: false },+ keySeparator: false,+ nsSeparator: false,+ initAsync: false,+})++const { plugins } = await import('../src/store/modules/plugins')++const RUNTIME = { toast: true, restartOnSettle: true }++function resultToasts() {+ return toast.mock.calls.filter(call => call[1]?.isLoading !== true)+}++beforeEach(() => {+ invoke.mockReset()+ invoke.mockResolvedValue(undefined)+ toast.mockClear()+ toast.close.mockClear()+ restart.mockClear()+ plugins.groups = []+ plugins.processes = []+ plugins.logs = []+ plugins.activeGroupId = null+ plugins.cancelling = false+ plugins.installedSource = []+ plugins.installedLoaded = false+ plugins.progressKey = null+ plugins.progressDetail = ''+ plugins.queueResults = []+})++describe('plugins manager queue summary', () => {+ it('reports the whole queue with a single toast once it drains', async () => {+ await Promise.all([+ plugins.enqueue('install', ['a'], RUNTIME),+ plugins.enqueue('upgrade', ['b'], RUNTIME),+ plugins.enqueue('uninstall', ['c'], RUNTIME),+ ])++ const toasts = resultToasts()+ 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(plugins.queueResults).toEqual([])+ })++ it('keeps reporting a lone result on its own instead of as a queue summary', async () => {+ await plugins.enqueue('install', ['a'], { toast: true, restartOnSettle: false })++ const toasts = resultToasts()+ expect(toasts).toHaveLength(1)+ expect(toasts[0][0]).toBe('Plugin a installed')+ })++ it('counts successes and failures of the whole queue in the same summary', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command === 'update_dsh_plugins')+ throw new Error('REGISTRY_DOWN: registry unreachable')+ return undefined+ })++ await Promise.all([+ plugins.enqueue('install', ['a'], { toast: true, restartOnSettle: false }),+ plugins.enqueue('upgrade', ['b'], { toast: true, restartOnSettle: false }),+ ])++ const toasts = resultToasts()+ expect(toasts).toHaveLength(1)+ expect(toasts[0][0]).toBe('Plugin operations finished')+ expect(toasts[0][1]?.description).toBe('1 succeeded · 1 failed')+ expect(toasts[0][1]?.variant).toBe('danger')+ expect(toasts[0][1]?.timeout).toBeUndefined()+ expect(toasts[0][1]?.actionProps).toBeUndefined()+ })+})diff --git a/test/plugin-manager-update-hold.test.ts b/test/plugin-manager-update-hold.test.tsnew file mode 100644index 00000000..9c1b1b6d--- /dev/null+++ b/test/plugin-manager-update-hold.test.ts@@ -0,0 +1,206 @@+import i18next from 'i18next'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { resources } from '../src/i18n/index.resource'++interface ToastCallOptions {+ timeout?: number+ variant?: string+ isLoading?: boolean+ description?: string+ actionProps?: { children?: string }+ onClose?: (reason: string) => void+}++const { invoke, restart, toast } = vi.hoisted(() => {+ let index = 0+ const toastFn = vi.fn((_message: string, _options?: ToastCallOptions): string => `toast-${++index}`)+ return {+ invoke: vi.fn(),+ restart: vi.fn(),+ toast: Object.assign(toastFn, { close: vi.fn(), update: vi.fn(), clear: vi.fn(), isActive: vi.fn(() => true) }),+ }+})++vi.mock('@tauri-apps/api/core', () => ({ invoke }))+vi.mock('../src/store/modules/harness', () => ({ harness: { restart } }))+vi.mock('@/utils/toast', () => ({ toast }))++// 与 src/i18n/index.ts 相同的扁平 key 约定:断言的标题/副标题取真实文案+await i18next.init({+ lng: 'en-US',+ fallbackLng: 'en-US',+ resources: resources as unknown as Record<string, { translation: Record<string, string> }>,+ interpolation: { escapeValue: false },+ keySeparator: false,+ nsSeparator: false,+ initAsync: false,+})++const { plugins } = await import('../src/store/modules/plugins')++const RUNTIME = { toast: true, restartOnSettle: false }+const PINNED_DESC = 'Authorised and explicitly reinstalled, but the profile still pins this plugin\'s source (catalog / git / link or an exact spec), so pnpm keeps the current version. The plugin itself is fine.'+const NO_TARGET_DESC = 'No installable target version: the plugin\'s source is pinned, or npm reports no newer release. Reopen the panel to refresh the version list and try again.'++function holdError(payload: unknown): Error {+ return new Error(`PLUGIN_UPDATE_NO_CHANGE: ${JSON.stringify(payload)}`)+}++function approvalToast() {+ return toast.mock.calls.find(call => call[1]?.onClose !== undefined)+}++function resultToasts() {+ return toast.mock.calls.filter(call => call[1]?.isLoading !== true)+}++beforeEach(() => {+ invoke.mockReset()+ invoke.mockResolvedValue(undefined)+ toast.mockClear()+ toast.close.mockClear()+ restart.mockClear()+ plugins.groups = []+ plugins.processes = []+ plugins.logs = []+ plugins.activeGroupId = null+ plugins.cancelling = false+ plugins.installedSource = []+ plugins.installedLoaded = false+ plugins.progressKey = null+ plugins.progressDetail = ''+})++describe('plugins manager update hold', () => {+ it('keeps asking for authorisation while the exact version can still be exempted', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command === 'update_dsh_plugins')+ throw holdError({ name: 'aaa', version: '0.1.0', latest: '0.1.174', retryable: true })+ return undefined+ })++ const done = plugins.enqueue('upgrade', ['aaa'], RUNTIME)+ await vi.waitFor(() => expect(plugins.pendingApprovals).toHaveLength(1))++ expect(plugins.pendingApprovals[0].refusal).toEqual({+ kind: 'update-hold',+ versions: [{ name: 'aaa', version: '0.1.174' }],+ retryable: true,+ retryableNames: ['aaa'],+ heldNames: [],+ })++ const approval = approvalToast()+ expect(approval?.[0]).toBe('aaa was not upgraded')+ expect(approval?.[1]?.timeout).toBe(0)+ expect(approval?.[1]?.actionProps?.children).toBe('Authorise')++ await plugins.cancel()+ await done+ })++ it('reports an authorised target that still did not install as a failure', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command === 'update_dsh_plugins')+ throw holdError({ name: 'aaa', version: '0.1.0', latest: '0.1.174', retryable: false })+ return undefined+ })+ const results = await plugins.enqueue('upgrade', ['aaa'], RUNTIME)++ expect(results.map(result => [result.process.name, result.ok, result.reason])).toEqual([+ ['aaa', false, undefined],+ ])+ expect(plugins.pendingApprovals).toHaveLength(0)+ expect(approvalToast()).toBeUndefined()++ const toasts = resultToasts()+ expect(toasts).toHaveLength(1)+ expect(toasts[0][0]).toBe('Failed to upgrade aaa')+ expect(toasts[0][1]?.description).toBe(PINNED_DESC)+ expect(toasts[0][1]?.variant).toBe('danger')+ })++ it('reports a payload without any target version as a failure', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command === 'update_dsh_plugins')+ throw holdError({ name: 'aaa', version: '0.1.0', latest: null })+ return undefined+ })+ const results = await plugins.enqueue('upgrade', ['aaa'], RUNTIME)++ expect(results.map(result => [result.process.name, result.ok, result.reason])).toEqual([+ ['aaa', false, undefined],+ ])++ const toasts = resultToasts()+ expect(toasts).toHaveLength(1)+ expect(toasts[0][0]).toBe('Failed to upgrade aaa')+ expect(toasts[0][1]?.description).toBe(NO_TARGET_DESC)+ expect(toasts[0][1]?.variant).toBe('danger')+ })++ it('settles every target and counts each one when the payload carries no candidate version', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command === 'update_dsh_plugins') {+ throw holdError([+ { name: 'aaa', version: '0.1.0', latest: null },+ { name: 'bbb', version: '0.2.0', latest: null },+ ])+ }+ return undefined+ })+ const done = plugins.enqueue('upgrade', ['aaa', 'bbb'], RUNTIME)+ const guarded = await Promise.race([+ done,+ new Promise(resolve => setTimeout(resolve, 500, 'hung')),+ ])++ expect(guarded).not.toBe('hung')+ const results = await done+ expect(results.map(result => [result.process.name, result.ok, result.reason])).toEqual([+ ['aaa', false, undefined],+ ['bbb', false, undefined],+ ])+ expect(approvalToast()).toBeUndefined()++ const toasts = resultToasts()+ expect(toasts).toHaveLength(1)+ expect(toasts[0][0]).toBe('Plugin operations finished')+ expect(toasts[0][1]?.description).toBe('2 failed')+ expect(toasts[0][1]?.variant).toBe('danger')+ })++ it('authorises only the named member of a batch and reports the rest as untouched', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command !== 'update_dsh_plugins')+ return undefined+ throw holdError([+ { name: 'aaa', version: '0.1.0', latest: '0.1.174', retryable: true },+ { name: 'bbb', version: '0.2.0', latest: '0.2.1', retryable: false },+ ])+ })+ const done = plugins.enqueue('upgrade', ['aaa', 'bbb'], RUNTIME)+ await vi.waitFor(() => expect(plugins.pendingApprovals).toHaveLength(1))++ expect(plugins.pendingApprovals.map(process => process.name)).toEqual(['aaa'])+ expect(approvalToast()?.[1]?.actionProps?.children).toBe('Authorise')++ await plugins.cancel()+ await done+ })++ it('reports the untouched members of a pinned batch as upgraded and the pinned one as failed', async () => {+ invoke.mockImplementation(async (command: string) => {+ if (command !== 'update_dsh_plugins')+ return undefined+ throw holdError({ name: 'bbb', version: '0.2.0', latest: '0.2.1', retryable: false })+ })+ const results = await plugins.enqueue('upgrade', ['aaa', 'bbb'], RUNTIME)++ expect(invoke.mock.calls.filter(call => call[0] === 'update_dsh_plugins')).toHaveLength(1)+ expect(results.map(result => [result.process.name, result.ok, result.reason])).toEqual([+ ['aaa', true, undefined],+ ['bbb', false, undefined],+ ])+ })+})diff --git a/test/plugin-row-actions.test.ts b/test/plugin-row-actions.test.tsnew file mode 100644index 00000000..7fae307b--- /dev/null+++ b/test/plugin-row-actions.test.ts@@ -0,0 +1,44 @@+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'++function panel(): string {+ return readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')+}++describe('plugin panel per-row actions', () => {+ it('tracks in-flight actions per row instead of one global busy slot', () => {+ const source = panel()++ expect(source).toContain('const [busy, setBusy] = useState<string[]>([])')+ expect(source).toContain('function rowBusy(id: string): boolean')+ expect(source).toContain('function busyWith(id: string, action: string): boolean')+ expect(source).toContain('function markBusy(id: string, action: string): void')+ expect(source).toContain('function clearBusy(id: string, action: string): void')+ // 单槽 busy 会把所有行一起置灰,后续点击无法再入队+ expect(source).not.toContain('setBusy(null)')+ expect(source).not.toContain('setBusy({ id, action')+ })++ it('greys out and spins only the row that owns the action', () => {+ const source = panel()++ expect(source.match(/actionChip\(\{ busy: rowBusy\(plugin\.id\) \}\)/g)).toHaveLength(7)+ expect(source).not.toContain('actionChip({ busy: !!busy })')+ expect(source).toContain('<If cond={busyWith(plugin.id, \'update\')}')+ expect(source).toContain('<If cond={busyWith(plugin.id, \'remove\')}')+ })++ it('keeps the manager action union required by the disable/enable contract', () => {+ expect(panel()).toContain('action: \'update\' | \'remove\' | \'disable\' | \'enable\'')+ })++ it('guards every row handler with rowBusy(id)', () => {+ const source = panel()++ for (const handler of ['onRemove', 'onEnable', 'onSnapshot', 'onRestore', 'onDeleteSnapshot']) {+ const block = source.match(new RegExp(`async function ${handler}\\([\\s\\S]*?\\n {2}\\}`))+ expect(block).not.toBeNull()+ expect(block![0]).toContain('if (rowBusy(id))')+ }+ })+})diff --git a/test/plugin-uninstall.test.ts b/test/plugin-uninstall.test.tsindex 9f14fbf5..ee07fd19 100644--- a/test/plugin-uninstall.test.ts+++ b/test/plugin-uninstall.test.ts@@ -74,16 +74,23 @@ describe('configPlugin preset chip', () => {})})-// ── Suite C — uninstall flow wires to remove_dsh_plugin + restart ────────────+// ── Suite C — uninstall routes through the manager + settles with one restart ──describe('configPlugin uninstall flow', () => {- it('calls remove_dsh_plugin', () => {- const source = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')- expect(source).toContain('remove_dsh_plugin')+ it('routes uninstall through the manager batch command', () => {+ const panel = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')+ const store = readFileSync(new URL('../src/store/modules/plugins/store.ts', import.meta.url), 'utf8')++ expect(panel).toContain('manager.uninstall')+ expect(panel).not.toContain('remove_dsh_plugin')+ expect(store).toContain('remove_dsh_plugins')})- it('restarts the service after uninstall', () => {- const source = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')- expect(source).toContain('store.harness.restart()')+ it('restarts the service once when the group settles', () => {+ 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()')})it('shows a confirm dialog before uninstall', () => {diff --git a/test/preinstall-incompatible.test.ts b/test/preinstall-incompatible.test.tsindex 4b269bf1..5bf4fe9f 100644--- a/test/preinstall-incompatible.test.ts+++ b/test/preinstall-incompatible.test.ts@@ -189,16 +189,32 @@ describe('blocked-refusal parsing', () => {kind: 'update-hold',versions: [{ name: 'dshmarket', version: '1.66.5' }],retryable: true,+ retryableNames: ['dshmarket'],+ heldNames: [],})})it('keeps a pinned-or-unknown hold without an authorizable version', () => {- // 已经授权过还是不动(或没探测到新版本):不能给出可授权项,否则用户只能空点+ // 已经授权过(在豁免清单里)还是不动:版本号在 `versions` 里但不是可授权项,+ // 调用方据此报真实失败而不是让用户空点授权const punished = parseBlockedRefusal(`PLUGIN_UPDATE_NO_CHANGE: ${JSON.stringify({ name: 'dshmarket', version: '1.66.2', latest: '1.66.5', retryable: false })}`)- expect(punished).toEqual({ kind: 'update-hold', versions: [{ name: 'dshmarket', version: '1.66.5' }], retryable: false })+ expect(punished).toEqual({+ kind: 'update-hold',+ versions: [{ name: 'dshmarket', version: '1.66.5' }],+ retryable: false,+ retryableNames: [],+ heldNames: [],+ })+ // 连候选版本都没有:进 `heldNames`,调用方按「没有可安装的目标版本」报失败const unknown = parseBlockedRefusal(`PLUGIN_UPDATE_NO_CHANGE: ${JSON.stringify({ name: 'dshmarket', version: '1.66.2', latest: null, retryable: false })}`)- expect(unknown).toEqual({ kind: 'update-hold', versions: [], retryable: false })+ expect(unknown).toEqual({+ kind: 'update-hold',+ versions: [],+ retryable: false,+ retryableNames: [],+ heldNames: ['dshmarket'],+ })})it('degrades a malformed hold payload to a plain failure', () => {diff --git a/test/toast-provider.test.ts b/test/toast-provider.test.tsindex f76dc6a4..ae96eb4c 100644--- a/test/toast-provider.test.ts+++ b/test/toast-provider.test.ts@@ -3,6 +3,8 @@ import { describe, expect, it } from 'vitest'const PROVIDER = '../src/components/toast-provider.tsx'const HEROUI_TOAST = '../node_modules/@heroui/react/dist/components/toast/toast.js'+const HEROUI_SPINNER = '../node_modules/@heroui/react/dist/components/spinner/spinner.js'+const STYLES = '../src/styles/main.css'function source(path: string): string {return readFileSync(new URL(path, import.meta.url), 'utf8')@@ -21,4 +23,12 @@ describe('toast provider render-slot contract', () => {expect(provider).toContain(': undefined}')expect(provider).not.toContain(': null}')})++ it('hides the close button of loading bubbles through the library data-slot markers', () => {+ // 独立 oracle:HeroUI 的 Spinner 根节点与关闭按钮各自带 data-slot,+ // 默认 children 又无条件渲染关闭按钮 —— 故加载态只能按 DOM 标记隐藏。+ expect(source(HEROUI_SPINNER)).toContain('"data-slot": "spinner"')+ expect(source(HEROUI_TOAST)).toContain('"data-slot": "toast-close"')+ expect(source(STYLES)).toContain('[data-slot="toast"]:has([data-slot="spinner"]) [data-slot="toast-close"]')+ })})diff --git a/test/toast-update.test.ts b/test/toast-update.test.tsnew file mode 100644index 00000000..a6f46583--- /dev/null+++ b/test/toast-update.test.ts@@ -0,0 +1,62 @@+import { afterEach, describe, expect, it } from 'vitest'+import { activeQueues, toast } from '../src/utils/toast'++interface StatelyQueueProbe {+ queue: Array<{ key: string, content?: Record<string, unknown> }>+ visibleToasts: unknown[]+}++function probe(): StatelyQueueProbe {+ return activeQueues['bottom end'].getQueue() as unknown as StatelyQueueProbe+}++function entryOf(key: string) {+ return probe().queue.find(item => item.key === key)+}++afterEach(() => {+ toast.clear()+})++describe('toast.update', () => {+ it('writes the update through to the queue entry so the default bubble re-renders', () => {+ const key = toast('正在升级 aaa...', { timeout: 0 })+ const visibleBefore = probe().visibleToasts++ expect(entryOf(key)?.content).toMatchObject({ title: '正在升级 aaa...' })++ toast.update(key, { title: '正在升级 2 个插件...', isLoading: true, description: 'added 1 package' })++ expect(entryOf(key)?.content).toMatchObject({+ title: '正在升级 2 个插件...',+ isLoading: true,+ description: 'added 1 package',+ })+ expect(probe().visibleToasts).not.toBe(visibleBefore)+ })++ it('ignores keys that were already closed', () => {+ const key = toast('x', { timeout: 0 })+ toast.close(key)++ expect(() => toast.update(key, { description: 'late line' })).not.toThrow()+ expect(entryOf(key)).toBeUndefined()+ })++ it('reports evicted keys as inactive so callers can rebuild the bubble', () => {+ const oldest = toast('1', { timeout: 0 })+ const kept = [toast('2', { timeout: 0 }), toast('3', { timeout: 0 })]+ expect(toast.isActive(oldest)).toBe(true)++ const newest = toast('4', { timeout: 0 })++ expect(toast.isActive(oldest)).toBe(false)+ expect(kept.every(key => toast.isActive(key))).toBe(true)+ expect(toast.isActive(newest)).toBe(true)++ const before = entryOf(oldest)+ toast.update(oldest, { description: 'late line' })+ expect(entryOf(oldest)).toBe(before)+ expect(entryOf(oldest)?.content?.description).toBeUndefined()+ })+})diff --git a/test/toast.test.ts b/test/toast.test.tsindex 9037fd6f..609a55b5 100644--- a/test/toast.test.ts+++ b/test/toast.test.ts@@ -56,4 +56,31 @@ describe('toast lifecycle', () => {expect(queues['bottom end'].visibleToasts.some(item => item.key === otherKey)).toBe(true)expect(onClose).toHaveBeenCalledOnce()})++ it('never discards an actionable notification when the queue overflows', async () => {+ const keys = [1, 2, 3, 4].map(index => toast(`Authorise ${index}`, { timeout: 0, sticky: true }))+ const queue = queues['bottom end']++ // 超出可见上限的那条不能被悄悄销毁:它只是暂时不渲染,旧气泡关闭后必须复现+ // (授权按钮一旦被淘汰,用户再也点不到,队列会永远停在等待授权上)+ await Promise.resolve()+ expect(toast.isActive(keys[0])).toBe(true)++ toast.close(keys[3])+ await Promise.resolve()+ expect(queue.visibleToasts.map(item => item.key)).toEqual([keys[2], keys[1], keys[0]])+ })++ it('still evicts the oldest ordinary notification when the queue overflows', async () => {+ const onClose = vi.fn()+ const first = toast('Result 1', { timeout: 0, onClose })+ toast('Result 2', { timeout: 0 })+ toast('Result 3', { timeout: 0 })+ toast('Result 4', { timeout: 0 })++ await Promise.resolve()+ await Promise.resolve()+ expect(onClose).toHaveBeenCalledWith('evicted')+ expect(toast.isActive(first)).toBe(false)+ })})