DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix: repair plugin release-age exemptions and degraded startup (#1078)
Hairyc23f84f1ae60
diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rsindex 8ecdcd2a..34d9e695 100644--- a/src-tauri/src/bridge/plugin.rs+++ b/src-tauri/src/bridge/plugin.rs@@ -145,8 +145,9 @@ pub async fn allow_plugin_versions(pub async fn allow_plugin_policy_versions(app_handle: AppHandle,versions: Vec<plugin::PolicyBlockedVersion>,+ expected_profile: Option<String>,) -> Result<(), String> {- plugin::allow_policy_versions(&app_handle, &versions)+ plugin::allow_policy_versions(&app_handle, &versions, expected_profile.as_deref())}/// 跳过预装插件引导:记录状态与预设指纹,之后不再弹出(除非清单内容变更)diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rsindex b0bbaaf3..d495c51a 100644--- a/src-tauri/src/service/plugin/install/mod.rs+++ b/src-tauri/src/service/plugin/install/mod.rs@@ -35,7 +35,9 @@use crate::config;use crate::service::cli;use crate::service::core;-use crate::service::profile::{active_profile, allow_profile_release_age};+use crate::service::profile::{+ active_profile, allow_profile_release_age, profile_dir_of, release_age_excludes_at,+};use std::collections::HashMap;use std::ffi::OsString;use std::path::Path;@@ -306,38 +308,37 @@ fn locked_release_age_exemptions(if blocked.is_empty() {return None;}+ let content = std::fs::read_to_string(profile.join("pnpm-lock.yaml")).ok()?;+ let lockfile: serde_yaml::Value = serde_yaml::from_str(&content).ok()?;+ let packages = lockfile.get("packages")?.as_mapping()?;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())+ let entry = format!("{}@{}", item.name, item.version);+ if !packages+ .keys()+ .filter_map(serde_yaml::Value::as_str)+ .any(|key| {+ key.strip_prefix(&entry).is_some_and(|suffix| {+ suffix.is_empty() || (suffix.starts_with('(') && suffix.ends_with(')'))+ })+ }){return None;}- entries.push(format!("{}@{}", item.name, item.version));+ entries.push(entry);}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 {+fn heal_locked_release_age(profile: &Path, output: &str) -> bool {let blocked = policy_blocked_versions(output);- let Some(entries) = locked_release_age_exemptions(&profile_dir(app_handle), &blocked) else {+ let Some(entries) = locked_release_age_exemptions(profile, &blocked) else {return false;};- match allow_profile_release_age(app_handle, &entries) {+ match release_age_excludes_at(profile, &entries) {Ok(()) => {log::warn!(- "pnpm release-age policy blocked {} entries that are already locked; recorded them as exempt and retrying with the window relaxed",+ "pnpm release-age policy blocked {} entries that are already locked; recorded exact exemptions and retrying with the default window",entries.len());true@@ -416,11 +417,13 @@ async fn install_with_cancel(let envs = build_plugin_envs(app_handle, prefer_bundled_pnpm);// 拼装命令行参数+ let profile = active_profile(app_handle);+ let profile_path = profile_dir_of(app_handle, &profile);let mut args = vec![dsh_bin.as_os_str().to_os_string(),OsString::from("plugin"),OsString::from("--profile"),- OsString::from(active_profile(app_handle)),+ OsString::from(&profile),OsString::from("add"),];args.extend(specs.iter().map(OsString::from));@@ -447,16 +450,12 @@ 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));+ if exit_code != 0 && heal_locked_release_age(&profile_path, &last_attempt) {run_plugin_install_with_transient_retry(app_handle,&node,- &retry_args,+ &args,&cwd,&envs,&window,@@ -705,24 +704,16 @@ pub async fn allow_version_exemptions(}}-/// 记录用户明确授权的发布时长策略豁免:把精确 `包名@版本` 写进档案的-/// `minimumReleaseAgeExclude`,pnpm 的解析随后会放行这些条目;lockfile 校验阶段-/// 仍按默认窗口拦截,因此升级调用还会附上 `--config.minimumReleaseAge=0`-/// (见 `single::update_many`),否则授权过的版本依旧装不上。-///-/// 与 [`allow_version_exemptions`] 的分工:那个针对 dsh 的**版本兼容性**(写档案的-/// `compatibility.json`),这个针对 pnpm 的**发布时长门禁**(写 `pnpm-workspace.yaml`)。-/// 两者都只认精确版本、都在用户确认后才调用;这里不起进程、不停服、不碰 `node_modules`,-/// 写完由界面重跑原操作(重跑会真正改写 lockfile/依赖,必须由 pnpm 自己跑)。pub fn allow_policy_versions(app_handle: &AppHandle,versions: &[PolicyBlockedVersion],+ expected_profile: Option<&str>,) -> Result<(), String> {let entries: Vec<String> = versions.iter().map(|entry| format!("{}@{}", entry.name, entry.version)).collect();- allow_profile_release_age(app_handle, &entries)+ allow_profile_release_age(app_handle, &entries, expected_profile)}/// 返回 `(exit_code, 历次尝试的输出拼接, 最后一次尝试的输出)`。@@ -1069,7 +1060,7 @@ mod tests {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",+ "lockfileVersion: '9.0'\nimporters:\n .:\n dependencies:\n dshmarket:\n specifier: ^2.12.0\n version: 2.12.0\npackages:\n [email protected]: {}\n [email protected]: {}\n [email protected]: {}\n '@scope/[email protected]([email protected])': {}\n [email protected]: {}\n [email protected]: {}\n",).unwrap();@@ -1090,6 +1081,50 @@ mod tests {locked_release_age_exemptions(&dir, &[locked.clone()]),Some(vec!["[email protected]".to_string()]));+ let transitive = PolicyBlockedVersion {+ name: "transitive".to_string(),+ version: "1.0.0".to_string(),+ };+ let second = PolicyBlockedVersion {+ name: "transitive".to_string(),+ version: "1.1.0".to_string(),+ };+ let scoped = PolicyBlockedVersion {+ name: "@scope/pkg".to_string(),+ version: "2.0.0".to_string(),+ };+ assert_eq!(+ locked_release_age_exemptions(&dir, &[transitive.clone(), second, scoped]),+ Some(vec![+ "[email protected]".to_string(),+ "[email protected]".to_string(),+ "@scope/[email protected]".to_string()+ ])+ );+ assert_eq!(+ locked_release_age_exemptions(&dir, &[transitive.clone(), newer.clone()]),+ None+ );+ assert_eq!(+ locked_release_age_exemptions(&dir, &[transitive, absent.clone()]),+ None+ );+ for (name, version) in [+ ("transitive", "1.2.0"),+ ("missing", "1.0.0"),+ ("@scope/pkg", "2.1.0"),+ ] {+ assert_eq!(+ locked_release_age_exemptions(+ &dir,+ &[PolicyBlockedVersion {+ name: name.to_string(),+ version: version.to_string()+ }]+ ),+ None+ );+ }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);diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rsindex 8c3a25a6..96c13051 100644--- a/src-tauri/src/service/plugin/install/single.rs+++ b/src-tauri/src/service/plugin/install/single.rs@@ -113,10 +113,6 @@ async fn resolve_missing_targets(/// `link:` 本地目录 / 精确版本)也照样被改写到目标版本——这正是「用户授权过那个新版本、/// 升级却始终停在旧版本」的唯一出路。///-/// 目标还在发布保护期内时先让 pnpm 如实报错(不加旗标),再用**我们自己请求的目标**合成-/// 拒绝载荷请用户授权(见 [`policy_refusal_from_specs`]);授权会写进档案豁免清单,重跑时-/// 本批目标全部已豁免,带上放宽旗标就是安全的。反过来,没豁免就放宽会把太新的条目写进-/// lock,此后每一次插件操作都会在 lockfile 校验阶段失败(见 §5.3 的自愈说明)。async fn install_targets(app_handle: &AppHandle,targets: &[(String, String)],@@ -131,13 +127,7 @@ async fn install_targets(.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 {+ if let Err(e) = run_plugin_command(app_handle, &ids, "add", &specs).await {return UpdateFailure::stage(&specs, e);}let mut failures = Vec::new();@@ -160,14 +150,7 @@ async fn update_to_latest(app_handle: &AppHandle, ids: &[String]) -> Vec<UpdateF.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());- }+ let args = update_pnpm_args(ids);if let Err(e) = run_plugin_command(app_handle, ids, "update", &args).await {return UpdateFailure::stage(ids, e);}@@ -444,52 +427,6 @@ fn update_pnpm_args(ids: &[String]) -> Vec<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(app_handle, 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 {@@ -543,14 +480,6 @@ fn lock_dependency(profile: &Path, id: &str) -> Option<(String, 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`)。fn installed_package_version(profile: &Path, id: &str) -> Option<String> {let path = profile.join("node_modules").join(id).join("package.json");@@ -780,12 +709,10 @@ async fn run_plugin_command(let envs = build_plugin_envs(app_handle, prefer_bundled_pnpm);+ let profile = active_profile(app_handle);+ let profile_path = crate::service::profile::profile_dir_of(app_handle, &profile);let mut args = vec![dsh_bin.as_os_str().to_os_string()];- args.extend(single_plugin_args(- &active_profile(app_handle),- action,- sub_args,- ));+ args.extend(single_plugin_args(&profile, action, sub_args));let cwd = crate::service::core::active_core_dir(app_handle);log::info!("Running dsh plugin {action} for {ids:?}");@@ -794,25 +721,15 @@ async fn run_plugin_command().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)- };+ let (exit_code, output, last_attempt) =+ if exit_code != 0 && super::heal_locked_release_age(&profile_path, &last_attempt) {+ run_plugin_with_allow_build_retry(+ app_handle, &node, &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 {ids:?} with exit code {exit_code}");@@ -909,10 +826,8 @@ async fn run_plugin_command(/// 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 钉死-/// (会把人引偏)。+/// `update --latest` 静默停在 2.10.15。用户授权该精确版本后,档案豁免让+/// 解析与 lockfile 校验放行该版本。因此这条消息不能只归因于 catalog 钉死。/// 必须如实报「没升级」——报成功会让用户以为已在新版本上(与 [`remove_many`] 的/// 「卸载后核验」同理);但**不**记进插件错误:插件没坏,记了会让列表挂上/// 「可能已损坏或与当前环境不兼容」的误导标记(安装/升级真失败各有记录点)。@@ -1521,22 +1436,6 @@ mod tests {);}- /// 回归用户报告:授权过的精确版本此前永远装不上——档案里的发布时长豁免只被- /// 解析阶段采信,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"));diff --git a/src-tauri/src/service/profile/mod.rs b/src-tauri/src/service/profile/mod.rsindex 19c773ba..1b1689ad 100644--- a/src-tauri/src/service/profile/mod.rs+++ b/src-tauri/src/service/profile/mod.rs@@ -182,25 +182,74 @@ pub(crate) fn profile_release_age_excluded(app_handle: &AppHandle, entry: &str)else {return false;};- let wanted = Value::String(entry.to_string());- sequence.iter().any(|item| item == &wanted)+ release_age_excluded(sequence, entry)+}++fn release_age_package(entry: &str) -> Option<(&str, &str)> {+ static NAME: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {+ regex::Regex::new(r"^(?:@[a-zA-Z0-9._-]+/)?[a-zA-Z0-9._-]+$").unwrap()+ });+ let (name, versions) = entry.rsplit_once('@')?;+ (NAME.is_match(name) && versions.split("||").all(|part| !part.trim().is_empty()))+ .then_some((name, versions))+}++fn release_age_excluded(sequence: &[Value], entry: &str) -> bool {+ let Some((name, version)) = release_age_package(entry) else {+ return false;+ };+ sequence.iter().filter_map(Value::as_str).any(|item| {+ release_age_package(item).is_some_and(|(package, versions)| {+ package == name && versions.split("||").any(|part| part.trim() == version)+ })+ })+}++fn normalize_release_age_excludes(sequence: &[Value]) -> Vec<Value> {+ let mut result = Vec::with_capacity(sequence.len());+ let mut packages = std::collections::HashMap::<String, usize>::new();+ for item in sequence {+ let Some((name, versions)) = item.as_str().and_then(release_age_package) else {+ if !result.contains(item) {+ result.push(item.clone());+ }+ continue;+ };+ let index = *packages.entry(name.to_string()).or_insert_with(|| {+ result.push(Value::String(format!("{name}@")));+ result.len() - 1+ });+ let value = result[index].as_str().unwrap();+ let mut merged: Vec<&str> = value[name.len() + 1..]+ .split("||")+ .map(str::trim)+ .filter(|part| !part.is_empty())+ .collect();+ for version in versions.split("||").map(str::trim) {+ if !merged.contains(&version) {+ merged.push(version);+ }+ }+ result[index] = Value::String(format!("{name}@{}", merged.join(" || ")));+ }+ result}-/// 把用户明确授权过的精确 `包名@版本` 追加进档案的 `minimumReleaseAgeExclude`。-///-/// 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],+ expected_profile: Option<&str>,) -> Result<(), String> {if entries.is_empty() {return Err("PROFILE_RELEASE_AGE_EMPTY: no release-age exemption to record".to_string());}- release_age_excludes_at(&profile_dir_of(app_handle, &active_profile(app_handle)), entries)+ let profile = active_profile(app_handle);+ if expected_profile.is_some_and(|expected| expected != profile) {+ return Err(+ "PROFILE_RELEASE_AGE_CHANGED: active profile changed before authorization".to_string(),+ );+ }+ release_age_excludes_at(&profile_dir_of(app_handle, &profile), entries)}/// 把 `entries` 并入**指定档案目录** `pnpm-workspace.yaml` 的 `minimumReleaseAgeExclude`@@ -236,15 +285,11 @@ pub(crate) fn release_age_excludes_at(dir: &Path, entries: &[String]) -> Result<let sequence = excludes.as_sequence_mut().ok_or_else(|| {"PROFILE_WORKSPACE_POLICY_INVALID: minimumReleaseAgeExclude must be a sequence".to_string()})?;- // 归一化(多文档 → 单文档)本身就是需要落盘的改动:不写回的话 pnpm 依然读不了。- let mut changed = normalized;- for package in entries {- let value = Value::String(package.clone());- if !sequence.iter().any(|item| item == &value) {- sequence.push(value);- changed = true;- }- }+ let mut combined = sequence.clone();+ combined.extend(entries.iter().cloned().map(Value::String));+ let merged = normalize_release_age_excludes(&combined);+ let changed = normalized || *sequence != merged;+ *sequence = merged;if changed {if let Some(parent) = path.parent() {fs::create_dir_all(parent).map_err(|e| format!("PROFILE_WORKSPACE_MKDIR: {e}"))?;@@ -1205,6 +1250,74 @@ mod tests {assert!(parse_workspace_document(duplicate).is_err());}+ #[test]+ fn release_age_excludes_merge_every_exact_package_without_expanding_ranges() {+ let dir = std::env::temp_dir().join(format!("dsh-policy-merge-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("pnpm-workspace.yaml");+ std::fs::write(&path, "packages:\n - .\nnodeLinker: hoisted\nminimumReleaseAgeExclude:\n - foo@^1.0.0\n - '@scope/[email protected]'\n - [email protected]\n - [email protected] || 1.3.0\n - '@scope/[email protected]'\n - '@scope/*@3.0.0'\n - '@scope/[email protected]'\n - [email protected]\n").unwrap();+ release_age_excludes_at(&dir, &["[email protected]".to_string()]).unwrap();+ let first = std::fs::read_to_string(&path).unwrap();+ let document: Value = serde_yaml::from_str(&first).unwrap();+ let entries: Vec<&str> = document["minimumReleaseAgeExclude"]+ .as_sequence()+ .unwrap()+ .iter()+ .map(|entry| entry.as_str().unwrap())+ .collect();+ assert_eq!(+ entries,+ vec![+ "foo@^1.0.0 || 1.2.3 || 1.3.0",+ "@scope/[email protected] || 2.1.0",+ "@scope/*@3.0.0",+ "@scope/[email protected]",+ ]+ );+ assert_eq!(document["nodeLinker"].as_str(), Some("hoisted"));+ release_age_excludes_at(+ &dir,+ &["[email protected]".to_string(), "@scope/[email protected]".to_string()],+ )+ .unwrap();+ let merged = std::fs::read_to_string(&path).unwrap();+ let document: Value = serde_yaml::from_str(&merged).unwrap();+ assert_eq!(+ document["minimumReleaseAgeExclude"][0].as_str(),+ Some("foo@^1.0.0 || 1.2.3 || 1.3.0 || 1.4.0")+ );+ release_age_excludes_at(&dir, &["[email protected]".to_string(), "[email protected]".to_string()]).unwrap();+ assert_eq!(std::fs::read_to_string(&path).unwrap(), merged);+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn release_age_excluded_reads_exact_or_branches_not_ranges_or_other_packages() {+ let sequence: Value = serde_yaml::from_str(+ "- foo@^1.0.0 || 1.2.3 || 1.3.0\n- '@scope/[email protected] || 2.1.0'\n- '@scope/*@3.0.0'\n",+ )+ .unwrap();+ let sequence = sequence.as_sequence().unwrap();+ for entry in [+ "[email protected]",+ "[email protected]",+ "@scope/[email protected]",+ "@scope/[email protected]",+ ] {+ assert!(release_age_excluded(sequence, entry), "{entry}");+ }+ for entry in [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "@scope/[email protected]",+ "@scope/[email protected]",+ ] {+ assert!(!release_age_excluded(sequence, entry), "{entry}");+ }+ }+#[test]fn display_name_strips_manifest_prefix() {let dir = std::env::temp_dir().join(format!("dsh-profile-name-{}", std::process::id()));diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.tsindex 891d84d3..cc282f09 100644--- a/src/store/modules/harness/store.ts+++ b/src/store/modules/harness/store.ts@@ -1,4 +1,5 @@import type { UnlistenFn } from '@tauri-apps/api/event'+import type { PolicyBlockedVersion } from '../preinstall'import type { StartupPhase } from './readiness'import type {HarnessProcessExitedPayload,@@ -11,14 +12,18 @@ import type {StartupError,} from './types'import type { PatchEntryStripReport, PatchQuarantineReport } from '@/types/plugin'+import type { Profile } from '@/types/profile'import { invoke } from '@tauri-apps/api/core'import { listen } from '@tauri-apps/api/event'import i18next from 'i18next'+import semver from 'semver'import { defineStore } from 'valtio-define'import { queryClient } from '@/config/client'import { hooks } from '@/config/hooks'import { queryKeys } from '@/config/query-keys'+import { toast } from '@/utils/toast'import { harnessUpdater } from '../harness-updater'+import { parseBlockedRefusal } from '../plugins'import { preinstall } from '../preinstall'import { recovery } from '../recovery'import { setting } from '../setting'@@ -79,6 +84,7 @@ let pluginActivityReason = ''const restartFlight = new SingleFlight<void>()const iframeReloadGate = new BoundedReloadGate(IFRAME_RELOAD_MAX_ATTEMPTS)let iframeRefreshTimer: ReturnType<typeof setTimeout> | undefined+let policyApprovalKey: string | undefined/*** 桌面外壳核心业务模块:安装/启动流程、服务生命周期(启动/健康检查/重启/停止)、@@ -543,6 +549,10 @@ export const harness = defineStore({/** 启动流程:检测环境/安装依赖 → 拉起服务 → 已安装时后台检查更新 */async boot() {const token = ++bootToken+ if (policyApprovalKey !== undefined) {+ toast.close(policyApprovalKey)+ policyApprovalKey = undefined+ }iframeReloadGate.reset()if (iframeRefreshTimer !== undefined) {clearTimeout(iframeRefreshTimer)@@ -565,6 +575,7 @@ export const harness = defineStore({recovery.clear()this.status = 'ready'let unlistenInstall: UnlistenFn | null = null+ let policyApproval: { versions: PolicyBlockedVersion[], profile: string } | undefinedtry {// 事件监听失败(例如 IPC 自定义协议被 CSP 拦截、回退 postMessage 也异常)@@ -605,6 +616,7 @@ export const harness = defineStore({this.startupReason = i18next.t('status.loading_internal')pluginActivitySequence++pluginActivityReason = i18next.t('status.internal_waiting')+ const installProfile = (await invoke<Profile[]>('get_profiles')).find(item => item.active)?.idtry {const result = await waitForActivityTask({task: invoke('ensure_internal_plugins'),@@ -637,7 +649,23 @@ export const harness = defineStore({if (err instanceof Error && (err as StartupError).phase) {throw err}- throw startupError('plugin-install', String(err), 'failed')+ if (token !== bootToken)+ return+ const message = err instanceof Error ? err.message : String(err)+ const policyMessage = message.replace(/^INTERNAL_PLUGIN_INSTALL_FAILED: /, '')+ const refusal = policyMessage.startsWith('PLUGIN_POLICY_BLOCKED:') && !policyMessage.includes('\n')+ ? parseBlockedRefusal(policyMessage)+ : null+ if (refusal?.kind !== 'policy' || !Array.isArray(refusal.versions)+ || !refusal.versions.every(item => item && typeof item.name === 'string' && item.name.trim() !== ''+ && typeof item.version === 'string' && semver.valid(item.version))) {+ throw startupError('plugin-install', message, 'failed')+ }+ const profiles = await invoke<Profile[]>('get_profiles')+ const profile = profiles.find(item => item.active)?.id+ if (!installProfile || profile !== installProfile)+ throw startupError('plugin-install', message, 'failed')+ policyApproval = { versions: refusal.versions, profile }}// 预装插件引导:首次安装、老版本升级(无指纹基线)或清单 plugins 节// 内容变更(社区新增推荐插件)时重新进入预设流程,装完/跳过后才拉起服务。@@ -678,6 +706,45 @@ export const harness = defineStore({}finally {unlistenInstall?.()+ if (policyApproval && token === bootToken) {+ const { versions, profile } = policyApproval+ let granting = false+ const key = toast(i18next.t('plugins.blocked_policy_title', { name: versions.map(item => item.name).join('、') }), {+ variant: 'warning',+ timeout: 0,+ sticky: true,+ description: i18next.t('plugins.blocked_policy_desc', { blocked: versions.map(item => `${item.name}@${item.version}`).join('、') }),+ actionProps: {+ children: i18next.t('buttons.authorize'),+ onPress: async () => {+ if (granting || token !== bootToken || this.busyAction || preinstall.installing)+ return+ granting = true+ try {+ const profiles = await invoke<Profile[]>('get_profiles')+ if (token !== bootToken || profiles.find(item => item.active)?.id !== profile) {+ toast.close(key)+ return+ }+ if (!await preinstall.allowPolicyVersions(versions, profile)) {+ toast(i18next.t('plugins.authorize_failed'), { variant: 'danger', description: preinstall.error })+ return+ }+ toast.close(key)+ if (token === bootToken)+ await this.restart()+ }+ catch (error) {+ toast(i18next.t('plugins.authorize_failed'), { variant: 'danger', description: String(error) })+ }+ finally {+ granting = false+ }+ },+ },+ })+ policyApprovalKey = key+ }}},diff --git a/src/store/modules/preinstall/store.ts b/src/store/modules/preinstall/store.tsindex 57d4dfca..d278bd2e 100644--- a/src/store/modules/preinstall/store.ts+++ b/src/store/modules/preinstall/store.ts@@ -164,11 +164,11 @@ export const preinstall = defineStore({* 一个写 `pnpm-workspace.yaml` 的 `minimumReleaseAgeExclude`),但形状一致:只提交* 用户勾选的精确 `包名@版本`,失败按普通安装失败展示并回到可重试态。*/- async allowPolicyVersions(versions: PolicyBlockedVersion[]): Promise<boolean> {+ async allowPolicyVersions(versions: PolicyBlockedVersion[], expectedProfile?: string): Promise<boolean> {if (this.installing || versions.length === 0)return falsetry {- await invoke('allow_plugin_policy_versions', { versions })+ await invoke('allow_plugin_policy_versions', { versions, ...(expectedProfile === undefined ? {} : { expectedProfile }) })this.policyBlocked = []return true}diff --git a/test/harness-boot-policy.test.ts b/test/harness-boot-policy.test.tsnew file mode 100644index 00000000..008375e5--- /dev/null+++ b/test/harness-boot-policy.test.ts@@ -0,0 +1,267 @@+import type { ToastOptions } from '../src/utils/toast'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const { invoke, toast, unlisten } = vi.hoisted(() => ({+ invoke: vi.fn(),+ toast: Object.assign(vi.fn((_title: unknown, _options?: ToastOptions) => 'policy-toast'), {+ close: vi.fn(),+ }),+ unlisten: vi.fn(),+}))++vi.mock('@tauri-apps/api/core', () => ({ invoke }))+vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(async () => unlisten) }))+vi.mock('@/utils/toast', () => ({ toast }))+vi.mock('@/config/client', () => ({ queryClient: { invalidateQueries: vi.fn() } }))+vi.mock('../src/store/modules/harness-updater', () => ({ harnessUpdater: { checkForUpdate: vi.fn() } }))+vi.mock('../src/store/modules/recovery', () => ({+ recovery: { clear: vi.fn(), reset: vi.fn(), hide: vi.fn(), reviewStartupRecovery: vi.fn() },+}))+vi.mock('i18next', () => ({+ default: { t: (key: string, options?: Record<string, unknown>) => `${key} ${Object.values(options ?? {}).join(' ')}` },+}))++const { harness } = await import('../src/store/modules/harness')+const { preinstall } = await import('../src/store/modules/preinstall')+const { PLUGIN_INACTIVITY_TIMEOUT } = await import('../src/store/modules/harness/constants')+const POLICY = [{ name: '@scope/transitive', version: '1.2.3' }]+const REFUSAL = `INTERNAL_PLUGIN_INSTALL_FAILED: PLUGIN_POLICY_BLOCKED: ${JSON.stringify(POLICY)}`+let ensureFailure: unknown+let grantFailure: unknown+let launchFailure: unknown+let activeProfile: string+let preinstallPending: boolean+let ensureTask: Promise<void> | undefined++function approvalOptions(): ToastOptions {+ const call = toast.mock.calls.find(([, options]) => options?.actionProps !== undefined)+ expect(call, 'boot must expose a persistent authorization action').not.toBeUndefined()+ return call![1]!+}++async function authorize(options = approvalOptions()) {+ const onPress = options.actionProps?.onPress+ expect(onPress).toBeTypeOf('function')+ await onPress!({} as never)+}++beforeEach(() => {+ invoke.mockReset()+ toast.mockClear()+ toast.close.mockClear()+ unlisten.mockClear()+ vi.spyOn(console, 'error').mockImplementation(() => {})+ ensureFailure = REFUSAL+ grantFailure = undefined+ launchFailure = undefined+ ensureTask = undefined+ activeProfile = 'web'+ preinstallPending = false+ harness.status = 'ready'+ harness.serviceHealthy = false+ harness.serviceRunning = false+ harness.busyAction = null+ preinstall.error = ''+ preinstall.installing = false+ preinstall.policyBlocked = []+ invoke.mockImplementation(async (command: string) => {+ switch (command) {+ case 'get_runtime_info': return { service_url: 'http://127.0.0.1:3081' }+ case 'get_app_config': return { installed: true }+ case 'runtime_ready': return true+ case 'get_profiles': return [{ id: activeProfile, active: true }]+ case 'ensure_internal_plugins':+ if (ensureTask)+ return ensureTask+ if (ensureFailure !== undefined)+ throw ensureFailure+ return undefined+ case 'get_preinstall_pending': return preinstallPending+ case 'get_preinstall_plugins': return []+ case 'proxy_health_check': return 'healthy'+ case 'read_run_logs': return ''+ case 'allow_plugin_policy_versions':+ if (grantFailure !== undefined)+ throw grantFailure+ ensureFailure = undefined+ return undefined+ case 'launch_harness':+ if (launchFailure !== undefined)+ throw launchFailure+ return undefined+ default: return undefined+ }+ })+})++afterEach(() => {+ harness.serviceHealthy = false+ vi.clearAllTimers()+ vi.useRealTimers()+ vi.restoreAllMocks()+})++describe('harness boot policy refusal recovery', () => {+ it.each([REFUSAL, `PLUGIN_POLICY_BLOCKED: ${JSON.stringify(POLICY)}`])('continues core startup with an exact-version authorization action for %s', async (failure) => {+ ensureFailure = failure+ await harness.boot()++ expect(harness.status).toBe('ready')+ expect(harness.serviceHealthy).toBe(true)+ expect(harness.errorMsg).toBe('')+ expect(invoke).toHaveBeenCalledWith('launch_harness')+ expect(invoke).not.toHaveBeenCalledWith('allow_plugin_policy_versions', expect.anything())+ const options = approvalOptions()+ expect(options).toMatchObject({ timeout: 0, sticky: true, variant: 'warning' })+ expect(options.description).toContain('@scope/[email protected]')+ expect(unlisten).toHaveBeenCalledOnce()+ })++ it('reuses the exact-version authorization IPC before restarting through ensure again', async () => {+ await harness.boot()+ await authorize()++ expect(invoke.mock.calls.filter(([command]) => command === 'allow_plugin_policy_versions')).toEqual([+ ['allow_plugin_policy_versions', { versions: POLICY, expectedProfile: 'web' }],+ ])+ expect(toast.mock.calls.filter(([, options]) => options?.variant === 'danger')).toEqual([])+ expect(invoke.mock.calls.filter(([command]) => command === 'ensure_internal_plugins')).toHaveLength(2)+ expect(invoke).toHaveBeenCalledWith('shutdown_harness')+ expect(invoke).not.toHaveBeenCalledWith('install_plugin_specs', expect.anything())+ expect(harness.serviceHealthy).toBe(true)+ expect(toast.close).toHaveBeenCalledWith('policy-toast')+ })++ it('allows dismissing authorization without granting or preventing core startup', async () => {+ await harness.boot()+ approvalOptions().onClose?.('dismissed')++ expect(harness.serviceHealthy).toBe(true)+ expect(invoke.mock.calls.filter(([command]) => command === 'ensure_internal_plugins')).toHaveLength(1)+ expect(invoke).not.toHaveBeenCalledWith('allow_plugin_policy_versions', expect.anything())+ })++ it('preserves the pending preinstall recovery path after policy refusal', async () => {+ preinstallPending = true+ await harness.boot()++ expect(harness.status).toBe('preinstall')+ expect(invoke).toHaveBeenCalledWith('get_preinstall_plugins')+ expect(invoke).not.toHaveBeenCalledWith('launch_harness')+ expect(approvalOptions().description).toContain('@scope/[email protected]')+ await preinstall.skip()+ expect(harness.serviceHealthy).toBe(true)+ })++ it('keeps failed authorization visible and retryable without restarting', async () => {+ await harness.boot()+ const options = approvalOptions()+ grantFailure = 'POLICY_WRITE_FAILED: disk full'+ await authorize(options)++ expect(toast).toHaveBeenCalledWith(expect.stringContaining('plugins.authorize_failed'), expect.objectContaining({+ variant: 'danger',+ description: 'POLICY_WRITE_FAILED: disk full',+ }))+ expect(invoke).not.toHaveBeenCalledWith('shutdown_harness')+ expect(harness.serviceHealthy).toBe(true)+ grantFailure = undefined+ await authorize(options)+ expect(invoke).toHaveBeenCalledWith('shutdown_harness')+ })++ it('does not authorize an old boot after a newer boot has started', async () => {+ await harness.boot()+ const oldOptions = approvalOptions()+ ensureFailure = undefined+ await harness.boot()+ await authorize(oldOptions)++ expect(invoke).not.toHaveBeenCalledWith('allow_plugin_policy_versions', expect.anything())+ })++ it('does not apply a previous profile refusal to the newly active profile', async () => {+ await harness.boot()+ activeProfile = 'other'+ await authorize()++ expect(invoke).not.toHaveBeenCalledWith('allow_plugin_policy_versions', expect.anything())+ expect(invoke).not.toHaveBeenCalledWith('shutdown_harness')+ })++ it('does not assign an in-flight refusal to a profile activated during ensure', async () => {+ ensureTask = new Promise((_resolve, reject) => {+ ensureFailure = reject+ })+ const boot = harness.boot()+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledWith('ensure_internal_plugins'))+ activeProfile = 'other'+ ;(ensureFailure as (error: string) => void)(REFUSAL)+ await boot++ expect(harness.status).toBe('error')+ expect(toast.mock.calls.filter(([, options]) => options?.actionProps)).toEqual([])+ expect(invoke).not.toHaveBeenCalledWith('allow_plugin_policy_versions', expect.anything())+ })++ it.each([+ 'INTERNAL_PLUGIN_INSTALL_FAILED: PREINSTALL_FAILED: command failed',+ 'INTERNAL_PLUGIN_INSTALL_FAILED: PLUGIN_OPERATION_CANCELLED: cancelled',+ 'INTERNAL_PLUGIN_INSTALL_FAILED: PLUGIN_PROCESS_CLEANUP_FAILED: process still alive',+ `${REFUSAL}\nPLUGIN_PROCESS_CLEANUP_FAILED: process still alive`,+ `INTERNAL_PLUGIN_INSTALL_FAILED: PLUGIN_PROCESS_CLEANUP_FAILED: ${REFUSAL}`,+ 'INTERNAL_PLUGIN_INSTALL_FAILED: PLUGIN_POLICY_BLOCKED: not-json',+ 'INTERNAL_PLUGIN_INSTALL_FAILED: PLUGIN_POLICY_BLOCKED: []',+ 'INTERNAL_PLUGIN_INSTALL_FAILED: PLUGIN_POLICY_BLOCKED: [{"name":"x"}]',+ 'INTERNAL_PLUGIN_INSTALL_FAILED: PLUGIN_POLICY_BLOCKED: [{"name":"x","version":"*"}]',+ ])('preserves the startup failure contract for %s', async (failure) => {+ ensureFailure = failure+ await harness.boot()++ expect(harness.status).toBe('error')+ expect(harness.errorMsg).toContain(failure)+ expect(invoke).not.toHaveBeenCalledWith('launch_harness')+ expect(toast.mock.calls.filter(([, options]) => options?.actionProps)).toEqual([])+ })++ it('does not hide a subsequent core launch failure behind the policy refusal', async () => {+ launchFailure = 'LAUNCH_FAILED: process exited'+ await harness.boot()++ expect(harness.status).toBe('error')+ expect(harness.errorMsg).toContain('LAUNCH_FAILED: process exited')+ expect(harness.serviceHealthy).toBe(false)+ })++ it('preserves inactivity timeout cancellation and failure handling', async () => {+ vi.useFakeTimers()+ ensureTask = new Promise(() => {})+ const boot = harness.boot()+ await vi.advanceTimersByTimeAsync(PLUGIN_INACTIVITY_TIMEOUT)+ await boot++ expect(invoke).toHaveBeenCalledWith('cancel_internal_plugins')+ expect(harness.status).toBe('error')+ expect(harness.errorMsg).toContain('errors.startup_inactivity')+ expect(invoke).not.toHaveBeenCalledWith('launch_harness')+ })++ it('keeps a timed-out installation cleanup failure blocking', async () => {+ vi.useFakeTimers()+ ensureTask = new Promise(() => {})+ const original = invoke.getMockImplementation()!+ invoke.mockImplementation(async (command: string) => {+ if (command === 'cancel_internal_plugins')+ throw new Error(`PLUGIN_PROCESS_CLEANUP_FAILED: ${REFUSAL}`)+ return original(command)+ })+ const boot = harness.boot()+ await vi.advanceTimersByTimeAsync(PLUGIN_INACTIVITY_TIMEOUT)+ await boot++ expect(harness.status).toBe('error')+ expect(harness.errorMsg).toContain('PLUGIN_PROCESS_CLEANUP_FAILED')+ expect(invoke).not.toHaveBeenCalledWith('launch_harness')+ expect(toast.mock.calls.filter(([, options]) => options?.actionProps)).toEqual([])+ })+})