Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat(plugin): 被发布保护期拦下时可逐项授权解开

hairyf507434f826b8
diff --git a/src-tauri/src/bridge/plugin.rs b/src-tauri/src/bridge/plugin.rs
index 24d2034a..8295d586 100644
--- a/src-tauri/src/bridge/plugin.rs
+++ b/src-tauri/src/bridge/plugin.rs
@@ -86,6 +86,20 @@ pub async fn allow_plugin_versions(
plugin::allow_version_exemptions(&app_handle, &versions).await
}
+/// 记录发布时长策略豁免:用户确认接受「刚发布、还在 24 小时窗口内」的精确版本后调用。
+///
+/// 授权项来自 `PLUGIN_POLICY_BLOCKED:` 载荷(pnpm 的 `minimumReleaseAge` 门禁——档案
+/// 已声明这样的版本时,每次插件操作都会失败)。写的是精确 `包名@版本`,只让列出的条目
+/// 过闸,其余解析照旧受窗口约束;随后由界面重跑原操作。与 `allow_plugin_versions`
+/// (dsh 的版本兼容性豁免,写 `compatibility.json`)是两套互不相干的授权。
+#[tauri::command]
+pub async fn allow_plugin_policy_versions(
+ app_handle: AppHandle,
+ versions: Vec<plugin::PolicyBlockedVersion>,
+) -> Result<(), String> {
+ plugin::allow_policy_versions(&app_handle, &versions)
+}
+
/// 跳过预装插件引导:记录状态与预设指纹,之后不再弹出(除非清单内容变更)
#[tauri::command]
pub async fn skip_preinstall_plugins(app_handle: AppHandle) -> Result<(), String> {
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index bca3e6f7..9ef20e3e 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -1068,6 +1068,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::install_preinstall_plugins,
crate::bridge::cancel_preinstall_plugins,
crate::bridge::allow_plugin_versions,
+ crate::bridge::allow_plugin_policy_versions,
crate::bridge::skip_preinstall_plugins,
crate::bridge::ensure_internal_plugins,
crate::bridge::cancel_internal_plugins,
diff --git a/src-tauri/src/service/plugin/install/diagnose.rs b/src-tauri/src/service/plugin/install/diagnose.rs
index b8fc68d4..d86e0af3 100644
--- a/src-tauri/src/service/plugin/install/diagnose.rs
+++ b/src-tauri/src/service/plugin/install/diagnose.rs
@@ -84,6 +84,62 @@ fn strip_ansi(s: &str) -> String {
out
}
+/// 真实的发布时长策略违规里的一条记录([`policy_blocked_versions`] 的解析结果)。
+///
+/// 与 [`IncompatibleVersion`] 区分:这里说的是 pnpm 的 `minimumReleaseAge` 门禁,不是
+/// dsh 的版本兼容性。豁免写入档案的 `minimumReleaseAgeExclude`(精确 `包名@版本`),
+/// 因此授权键只需要这两个字段,运行时版本与之无关。
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+pub struct PolicyBlockedVersion {
+ /// `package.json` 的包名(scoped 包含 `@scope/` 前缀)
+ pub name: String,
+ pub version: String,
+}
+
+/// 从失败输出里提取**真实**的发布时长策略违规条目。
+///
+/// pnpm 11 有两种 `ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION`:
+/// - 解析阶段(`<包名>@<版本> was published recently (released …; minimumReleaseAge is …)`)
+/// —— pnpm 自己挑中了太新的版本,回落到旧版本即可,通常不报错;
+/// - lockfile 校验阶段(`<包名>@<版本> was published at <时间>, within the minimumReleaseAge
+/// cutoff (<时间>)`)—— 档案已经声明/装了这个版本,而策略不接受它,于是**每一次**
+/// 插件操作都在这里硬失败(issue #222 的另一面)。
+///
+/// 只认后一种:它带了 pnpm **真的拿到**的发布时间(`was published at <ISO>`),因此能
+/// 确定不是「元数据拉不到被误判」——那种情况见 [`policy_verification_network_failure`],
+/// 属于可重试的网络问题。解析结果用于给用户一条可操作的出路(授权这些精确版本),
+/// 解析失败一律返回空,退回普通失败展示。
+pub(super) fn policy_blocked_versions(output: &str) -> Vec<PolicyBlockedVersion> {
+ let mut found: Vec<PolicyBlockedVersion> = Vec::new();
+ for line in output.split('\n') {
+ let stripped = strip_ansi(line);
+ let Some((key, rest)) = stripped.split_once(" was published at ") else {
+ continue;
+ };
+ // 必须同时是「按发布时间判定的违规」:缺了这句说明不是时间门禁(文案改版也走这里)
+ if !rest.contains("within the minimumReleaseAge cutoff") {
+ continue;
+ }
+ // 版本号自身不含 `@`,按最后一个 `@` 切开包名与版本(scoped 包名以 `@` 开头)
+ let Some((name, version)) = key.trim().rsplit_once('@') else {
+ continue;
+ };
+ let name = name.trim();
+ let version = version.trim();
+ if name.is_empty() || version.is_empty() {
+ continue;
+ }
+ let entry = PolicyBlockedVersion {
+ name: name.to_string(),
+ version: version.to_string(),
+ };
+ if !found.contains(&entry) {
+ found.push(entry);
+ }
+ }
+ found
+}
+
/// dsh 版本兼容性拒绝里的一条记录([[`incompatible_versions`]] 的解析结果)。
///
/// 授权(`dsh plugin allow-version`)只认**精确**的包名 + 版本 + 运行时版本三元组,
@@ -180,10 +236,17 @@ pub(super) fn network_error_hint(output: &str) -> Option<&'static str> {
/// 真·发布时间违规(版本确实太新)不带任何拉取失败信号,绝不命中:那种失败重试无用,
/// 也不该把供应链信号降级成网络问题。
///
+/// 判据收紧到「拿不到真实发布时间」:输出里已经能解析出违规条目与它的发布时间
+/// ([`policy_blocked_versions`])时直接返回 false——那说明 pnpm 拿到了元数据、判定是
+/// 真的,重跑同一条命令只会再失败一次,而且每次都要停服/重启。
+///
/// 传入的必须是**单次尝试**的输出(`run_plugin_with_allow_build_retry` 为此额外返回
/// 最后一次尝试的输出):把历次重试拼接起来判断时,早先一次的网络字样会给最终一次的真·
/// 违规「背书」,正好破坏上面这条边界。
pub(super) fn policy_verification_network_failure(output: &str) -> bool {
+ if !policy_blocked_versions(output).is_empty() {
+ return false;
+ }
let lower = output.to_ascii_lowercase();
if !lower.contains("err_pnpm_minimum_release_age_violation") {
return false;
@@ -483,6 +546,49 @@ mod tests {
assert!(!policy_verification_network_failure(""));
}
+ // ---- 真实的发布时长违规(档案已声明太新的版本 → 每次插件操作都硬失败)----
+
+ /// 用户实测(pnpm 11.7.0,档案 spec 被升到 `^2.11.2`):违规条目带的是 pnpm **真的
+ /// 拿到**的发布时间;后面那些 `UND_ERR_DESTROYED` 拉取失败是进程被 kill 的后果,
+ /// 不是原因。
+ const REAL_POLICY_VIOLATION: &str = "? Verifying lockfile against supply-chain policies (201 entries)...\n✗ Lockfile failed supply-chain policy check (201 entries in 1.5s)\n[ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION] 1 lockfile entries failed verification:\n@wenbin_wb/[email protected] was published at 2026-09-28T14:14:07.937Z, within the minimumReleaseAge cutoff (2026-09-27T15:50:11.385Z)\n\nProgress: resolved 48, reused 0, downloaded 0, added 0\n[WARN] GET https://registry.npmjs.org/axios error (UND_ERR_DESTROYED). Will retry in 10 seconds. 2 retries left.\n";
+
+ #[test]
+ fn policy_blocked_versions_reads_the_real_lockfile_violation() {
+ let blocked = policy_blocked_versions(REAL_POLICY_VIOLATION);
+
+ assert_eq!(blocked.len(), 1);
+ assert_eq!(blocked[0].name, "@wenbin_wb/dsh-bridge");
+ assert_eq!(blocked[0].version, "2.11.2");
+ }
+
+ #[test]
+ fn policy_blocked_versions_dedupes_and_ignores_other_output() {
+ let output = format!(
+ "{REAL_POLICY_VIOLATION}{}\n",
+ "[email protected] was published at 2026-09-28T10:00:00.000Z, within the minimumReleaseAge cutoff (2026-09-27T15:50:11.385Z)"
+ );
+ let blocked = policy_blocked_versions(&output);
+
+ assert_eq!(blocked.len(), 2);
+ assert_eq!(blocked[1].name, "lodash");
+ assert_eq!(blocked[1].version, "4.17.21");
+
+ // 解析阶段那种「pnpm 自己挑中太新版本」的文案:没有精确发布时间,不作为可授权项
+ let resolution_form = "[ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION] [email protected] was published recently (released 5 minutes ago; minimumReleaseAge is 1440)";
+ assert!(policy_blocked_versions(resolution_form).is_empty());
+ // 有时间但没有门禁判据(文案改版)时宁可退回普通失败
+ let no_cutoff = "[email protected] was published at 2026-09-28T10:00:00.000Z";
+ assert!(policy_blocked_versions(no_cutoff).is_empty());
+ }
+
+ #[test]
+ fn genuine_policy_violation_is_not_retried_as_a_network_failure() {
+ // 关键回归:真违规后面跟着的拉取失败(进程被 kill 的后果)不能把它改判成网络问题,
+ // 否则每次插件操作都会白停服重试 4 轮,还给出「registry 元数据拉取失败」的错因。
+ assert!(!policy_verification_network_failure(REAL_POLICY_VIOLATION));
+ }
+
// ---- pnpm store 布局不兼容(ERR_PNPM_UNEXPECTED_STORE 一族)----
/// pnpm 的真实原始输出:档案由 pnpm 10 装好,当前 pnpm 11 解析出另一份 store。
diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rs
index 326565a3..9b0d81dd 100644
--- a/src-tauri/src/service/plugin/install/mod.rs
+++ b/src-tauri/src/service/plugin/install/mod.rs
@@ -34,7 +34,7 @@
use crate::config;
use crate::service::cli;
use crate::service::core;
-use crate::service::profile::active_profile;
+use crate::service::profile::{active_profile, allow_profile_release_age};
use crate::service::workflow;
use std::collections::HashMap;
use std::ffi::OsString;
@@ -71,14 +71,15 @@ pub(crate) use pnpm::{
};
pub(crate) use single::uninstall_deprecated_plugins;
pub use single::{remove, update};
-// 版本兼容性拒绝的解析结果要跨到 `bridge`(前端逐项确认风险后授权),在此定义出口
-pub use diagnose::IncompatibleVersion;
+// 版本兼容性/发布时长两类拦截的解析结果都要跨到 `bridge`(前端逐项确认后授权),在此定义出口
+pub use diagnose::{IncompatibleVersion, PolicyBlockedVersion};
use allowlist::{add_allow_build_keys, parse_allowlist_keys};
use artifact::{ensure_plugin_entry_built, verify_installed_products};
use diagnose::{
diagnostic_suffix, git_transport_hint, incompatible_versions, network_error_hint,
- pick_error_message, policy_verification_network_failure, store_mismatch_hint,
+ pick_error_message, policy_blocked_versions, policy_verification_network_failure,
+ store_mismatch_hint,
};
use pnpm::ensure_pnpm;
use single::single_plugin_args;
@@ -320,6 +321,20 @@ async fn install_with_cancel(
.map_err(|e| format!("PREINSTALL_SERIALIZE: {e}"))?;
return Err(format!("PLUGIN_VERSION_INCOMPATIBLE: {payload}"));
}
+ // 真实的发布时长策略违规:档案已经声明/装了太新的版本,pnpm 的 lockfile 校验
+ // 不放行,于是**每一次**插件操作都会在这里失败。它不是安装故障,也不是网络问题
+ // (发布时间都拿到了),重试毫无意义——解析成精确 `包名@版本` 交给前端,由用户
+ // 明确授权后写进档案的 `minimumReleaseAgeExclude` 再重跑。同样排在网络分类之前。
+ let policy_blocked = policy_blocked_versions(&last_attempt);
+ if !policy_blocked.is_empty() {
+ log::warn!(
+ "pnpm release-age policy rejected {} profile entries: {policy_blocked:?}",
+ policy_blocked.len()
+ );
+ let payload = serde_json::to_string(&policy_blocked)
+ .map_err(|e| format!("PREINSTALL_SERIALIZE: {e}"))?;
+ return Err(format!("PLUGIN_POLICY_BLOCKED: {payload}"));
+ }
// 区分 git 传输层失败与 allowBuilds 构建门禁:前者是 pnpm 走了 git+ssh
// (用户环境无 SSH 配置),后者才是补充白名单可自愈的。传输层错误给出
// 可读指引,避免用户被 dsh 那条 allowBuilds 提示误导。
@@ -516,6 +531,24 @@ pub async fn allow_version_exemptions(
}
}
+/// 记录用户明确授权的发布时长策略豁免:把精确 `包名@版本` 写进档案的
+/// `minimumReleaseAgeExclude`,pnpm 的解析与 lockfile 校验随后都会放行这些条目。
+///
+/// 与 [`allow_version_exemptions`] 的分工:那个针对 dsh 的**版本兼容性**(写档案的
+/// `compatibility.json`),这个针对 pnpm 的**发布时长门禁**(写 `pnpm-workspace.yaml`)。
+/// 两者都只认精确版本、都在用户确认后才调用;这里不起进程、不停服、不碰 `node_modules`,
+/// 写完由界面重跑原操作(重跑会真正改写 lockfile/依赖,必须由 pnpm 自己跑)。
+pub fn allow_policy_versions(
+ app_handle: &AppHandle,
+ versions: &[PolicyBlockedVersion],
+) -> Result<(), String> {
+ let entries: Vec<String> = versions
+ .iter()
+ .map(|entry| format!("{}@{}", entry.name, entry.version))
+ .collect();
+ allow_profile_release_age(app_handle, &entries)
+}
+
/// 返回 `(exit_code, 历次尝试的输出拼接, 最后一次尝试的输出)`。
///
/// 两个字符串用途不同:诊断与用户文案要拼接(早期的 allowBuilds 提示也是线索),而
diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rs
index 094436c8..ad47cdcf 100644
--- a/src-tauri/src/service/plugin/install/single.rs
+++ b/src-tauri/src/service/plugin/install/single.rs
@@ -18,7 +18,7 @@ use super::artifact::{ensure_plugin_entry_built, installed_package_name};
use super::build_plugin_envs;
use super::diagnose::{
git_transport_hint, network_error_hint, pick_error_message,
- policy_verification_network_failure, store_mismatch_hint,
+ policy_blocked_versions, policy_verification_network_failure, store_mismatch_hint,
};
use super::errors;
use super::installed_name;
@@ -344,6 +344,21 @@ async fn run_single_plugin_command(
if exit_code != 0 {
log::error!("dsh plugin {action} failed for {id} with exit code {exit_code}");
+ // 真实的发布时长策略违规优先识别:档案已声明/装了太新的版本,pnpm 的 lockfile
+ // 校验不放行,于是升级/卸载/安装都会在这里失败。不是插件故障、也不是网络问题
+ // (发布时间都拿到了),重试无用——解析成精确 `包名@版本` 交给前端由用户授权,
+ // 写进档案的 `minimumReleaseAgeExclude` 后再重跑。
+ let policy_blocked = policy_blocked_versions(&last_attempt);
+ if !policy_blocked.is_empty() {
+ log::warn!(
+ "pnpm release-age policy rejected {} profile entries during {action}: {policy_blocked:?}",
+ policy_blocked.len()
+ );
+ return Err(format!(
+ "PLUGIN_POLICY_BLOCKED: {}",
+ serde_json::to_string(&policy_blocked).unwrap_or_default()
+ ));
+ }
// lockfile 供应链校验因 registry 元数据拉取失败而误判违规时,对用户而言就是
// 网络问题:给「检查网络后重试」而不是一条看不懂的供应链违规。分类只看最后
// 一次尝试的输出——历次拼接会让早先一次的网络字样给真·违规「背书」;拼接串
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index fe764c1c..baac2f65 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -54,7 +54,10 @@ pub use cancel::cancel;
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_version_exemptions, install, remove, update, IncompatibleVersion};
+pub use install::{
+ allow_policy_versions, allow_version_exemptions, install, remove, update, IncompatibleVersion,
+ PolicyBlockedVersion,
+};
pub(crate) use installed::{ensure_profile_npmrc, installed_name, list_installed, profile_dir};
pub use installed::{list, PreinstallPlugin};
pub(crate) use internal::cancel as cancel_internal_plugins;
diff --git a/src-tauri/src/service/profile/mod.rs b/src-tauri/src/service/profile/mod.rs
index 6e2077aa..32195bd9 100644
--- a/src-tauri/src/service/profile/mod.rs
+++ b/src-tauri/src/service/profile/mod.rs
@@ -151,7 +151,36 @@ pub(crate) fn parse_workspace_document(content: &str) -> Result<(Value, bool), S
}
}
+/// 保证档案具备桌面端预设所需的发布时长策略豁免(见 [`PROFILE_MINIMUM_RELEASE_AGE_EXCLUDES`])。
pub(crate) fn ensure_profile_pnpm_policy(app_handle: &AppHandle) -> Result<(), String> {
+ let entries: Vec<String> = PROFILE_MINIMUM_RELEASE_AGE_EXCLUDES
+ .iter()
+ .map(|package| (*package).to_string())
+ .collect();
+ profile_release_age_excludes(app_handle, &entries)
+}
+
+/// 把用户明确授权过的精确 `包名@版本` 追加进档案的 `minimumReleaseAgeExclude`。
+///
+/// pnpm 的发布时长策略(`minimumReleaseAge`,11 默认 24 小时)在解析与 lockfile 校验
+/// 两处都会拦下太新的版本;档案一旦声明了这样的版本,**每次**插件操作都会失败。用户
+/// 在界面上确认接受这些精确版本后走这里:写的是精确条目,只让列出的版本过闸,其余
+/// 解析照旧受窗口约束;已存在的条目不会重复写。
+pub(crate) fn allow_profile_release_age(
+ app_handle: &AppHandle,
+ entries: &[String],
+) -> Result<(), String> {
+ if entries.is_empty() {
+ return Err("PROFILE_RELEASE_AGE_EMPTY: no release-age exemption to record".to_string());
+ }
+ profile_release_age_excludes(app_handle, entries)
+}
+
+/// 把 `entries` 并入档案 `pnpm-workspace.yaml` 的 `minimumReleaseAgeExclude`(按需落盘)。
+fn profile_release_age_excludes(
+ app_handle: &AppHandle,
+ entries: &[String],
+) -> Result<(), String> {
let path = profile_dir_of(app_handle, &active_profile(app_handle)).join("pnpm-workspace.yaml");
let existing = match fs::read_to_string(&path) {
Ok(content) => content,
@@ -181,8 +210,8 @@ pub(crate) fn ensure_profile_pnpm_policy(app_handle: &AppHandle) -> Result<(), S
})?;
// 归一化(多文档 → 单文档)本身就是需要落盘的改动:不写回的话 pnpm 依然读不了。
let mut changed = normalized;
- for package in PROFILE_MINIMUM_RELEASE_AGE_EXCLUDES {
- let value = Value::String(package.to_string());
+ for package in entries {
+ let value = Value::String(package.clone());
if !sequence.iter().any(|item| item == &value) {
sequence.push(value);
changed = true;
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 279e6e36..a1b98aaa 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -39,6 +39,8 @@
"preinstall.open_repo": "Open repository of {{name}}",
"preinstall.failed": "Installation failed",
"preinstall.network_error": "Network connection failed. Check your network or proxy settings and try again.",
+ "preinstall.policy_title": "These versions are still inside the release-age window",
+ "preinstall.policy_desc": "pnpm does not resolve releases younger than 24 hours, yet the profile already declares them, so plugin operations are blocked. Authorising the checked ones writes their exact versions into the profile's exemption list (exact versions only) 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",
@@ -263,6 +265,10 @@
"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.policy_blocked_title": "Release-age policy is blocking plugin operations",
+ "plugins.policy_blocked_desc": "These versions are younger than 24 hours and pnpm does not resolve them by default, yet the profile already declares them, so every plugin operation fails. Authorising records their exact versions in the profile's exemption list and retries (exact versions only).",
+ "plugins.policy_blocked_confirm": "Authorise and retry",
+ "plugins.policy_allow_failed": "Failed to record the release-age exemption",
"plugins.updated_toast": "Plugin {{name}} updated",
"plugins.removed_toast": "Plugin {{name}} uninstalled",
"plugins.disable": "Disable",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index f9b05bbb..512c1ed2 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -39,6 +39,8 @@
"preinstall.open_repo": "打开 {{name}} 的仓库",
"preinstall.failed": "安装失败",
"preinstall.network_error": "网络连接失败,请检查网络或代理设置后重试。",
+ "preinstall.policy_title": "这些版本还在发布保护期内",
+ "preinstall.policy_desc": "pnpm 默认不解析发布不足 24 小时的新版本,而档案已经声明了它们,因此插件操作会被拦下。勾选后授权会把精确版本写进档案豁免清单(只对这些版本生效)并重跑安装。",
"preinstall.load_failed": "预装插件列表加载失败",
"preinstall.empty": "暂无可预装的插件。",
"preinstall.settings_title": "预装插件",
@@ -263,6 +265,10 @@
"plugins.remove_confirm_desc": "确定卸载插件 {{name}} 吗?卸载后其功能将不可用。",
"plugins.remove_failed": "卸载插件 {{name}} 失败",
"plugins.upgrade_failed": "升级插件 {{name}} 失败",
+ "plugins.policy_blocked_title": "发布保护期挡住了插件操作",
+ "plugins.policy_blocked_desc": "这些版本发布不足 24 小时,pnpm 默认不解析,而档案已经声明了它们,因此每次插件操作都会失败。授权后会把它们的精确版本写进档案豁免清单并重跑(只对这些精确版本生效)。",
+ "plugins.policy_blocked_confirm": "授权并重试",
+ "plugins.policy_allow_failed": "记录发布保护豁免失败",
"plugins.updated_toast": "插件 {{name}} 已更新",
"plugins.removed_toast": "插件 {{name}} 已卸载",
"plugins.disable": "禁用",
diff --git a/src/layout/components/setup-preinstall.tsx b/src/layout/components/setup-preinstall.tsx
index dcddd42c..b067d53e 100644
--- a/src/layout/components/setup-preinstall.tsx
+++ b/src/layout/components/setup-preinstall.tsx
@@ -177,6 +177,7 @@ export function PreinstallSetup() {
// 授权进行中:逐条起 dsh 进程写兼容性豁免,期间禁用按钮并显示加载态
const [granting, setGranting] = useState(false)
const blocked = preinstall.incompatible
+ const policyBlocked = preinstall.policyBlocked
// 进入引导页时拉取插件列表(仅挂载一次,无需清理)
useMount(() => {
@@ -256,19 +257,23 @@ export function PreinstallSetup() {
/**
* 授权勾选的精确版本后重跑安装。
*
- * 豁免只对「精确的包名@版本 + 运行时版本」生效、且不随插件或核心升级继承,因此
+ * 豁免只对「精确的包名@版本(+ 运行时版本)」生效、且不随插件或核心升级继承,因此
* 必须真的重跑一次由 dsh 复核,不能假定授权即放行。
*
- * 授权要逐条起 `dsh plugin allow-version`(每条一次进程启动),期间用 granting
- * 给出按钮反馈:这段等待既没有安装日志也没有列表变化,否则点完像没反应。
+ * 授权要逐条起进程(dsh 的 allow-version、或写档案豁免清单),期间用 granting 给出
+ * 按钮反馈:这段等待既没有安装日志也没有列表变化,否则点完像没反应。
*/
- async function handleAllow() {
- const versions = blocked.filter(item => allowed.has(incompatibleKey(item)))
+ 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)
return
setGranting(true)
try {
- if (await store.preinstall.allowIncompatible(versions))
+ if (await grant(versions))
handleConfirm()
}
finally {
@@ -293,10 +298,10 @@ export function PreinstallSetup() {
<If
cond={installing}
else={(
- // 被核心版本拦截(可逐项授权)或安装失败时不叠加插件列表,
- // 只展示原因 + 日志 + 操作
+ // 被核心版本拦截、被 pnpm 发布时长策略拦截(都可逐项授权)或安装失败时
+ // 不叠加插件列表,只展示原因 + 日志 + 操作
<If
- cond={blocked.length > 0 || preinstall.error !== ''}
+ cond={blocked.length > 0 || policyBlocked.length > 0 || preinstall.error !== ''}
else={(
<>
{/* 卡片网格限定高度滚动,上下溢出由 ScrollShadow 渐隐提示 */}
@@ -395,29 +400,86 @@ export function PreinstallSetup() {
<If
cond={blocked.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>
+ // 发布时长策略拦截:档案已声明太新的版本,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>
- </div>
+ </If>
)}
>
{/* 版本兼容性拒绝:核心在 pnpm 之前拦下整批安装,插件与当前核心的
@@ -459,7 +521,7 @@ export function PreinstallSetup() {
className="h-8 rounded-md"
size="sm"
variant="primary"
- onPress={() => void handleAllow()}
+ onPress={() => void handleGrant(blocked, incompatibleKey, versions => store.preinstall.allowIncompatible(versions))}
isDisabled={installing || granting || allowed.size === 0}
>
<If cond={granting}>
diff --git a/src/store/modules/preinstall/index.ts b/src/store/modules/preinstall/index.ts
index e7648b57..d7eb42d4 100644
--- a/src/store/modules/preinstall/index.ts
+++ b/src/store/modules/preinstall/index.ts
@@ -1,6 +1,7 @@
export { preinstall } from './store'
export type {
IncompatibleVersion,
+ PolicyBlockedVersion,
PreinstallLogPayload,
PreinstallPlugin,
PreinstallSelection,
diff --git a/src/store/modules/preinstall/store.ts b/src/store/modules/preinstall/store.ts
index f9e0664c..c7b8b470 100644
--- a/src/store/modules/preinstall/store.ts
+++ b/src/store/modules/preinstall/store.ts
@@ -1,5 +1,5 @@
import type { UnlistenFn } from '@tauri-apps/api/event'
-import type { IncompatibleVersion, PreinstallLogPayload, PreinstallPlugin, PreinstallSelection } from './types'
+import type { IncompatibleVersion, PolicyBlockedVersion, PreinstallLogPayload, PreinstallPlugin, PreinstallSelection } from './types'
import { invoke } from '@tauri-apps/api/core'
import { listen } from '@tauri-apps/api/event'
import i18next from 'i18next'
@@ -20,6 +20,32 @@ const LOG_LIMIT = 200
*/
const INCOMPATIBLE_PREFIX = 'PLUGIN_VERSION_INCOMPATIBLE:'
+/**
+ * 发布时长策略拦下的载荷前缀(后端 `policy_blocked_versions` 的结果):其后是
+ * `{ name, version }[]` 的 JSON。
+ *
+ * 与 [`INCOMPATIBLE_PREFIX`] 是两套互不相干的拦截(dsh 的版本兼容性 vs pnpm 的
+ * `minimumReleaseAge`),但处理形状一致:都交给界面列出来让用户勾选授权后重跑。
+ */
+const POLICY_BLOCKED_PREFIX = 'PLUGIN_POLICY_BLOCKED:'
+
+/**
+ * 解析后端「发布时长策略拦下」的载荷([`POLICY_BLOCKED_PREFIX`] 之后的
+ * `{ name, version }[]` JSON);识别不出来返回 null,退回普通失败展示。
+ */
+function parsePolicyBlocked(error: string): PolicyBlockedVersion[] | null {
+ if (!error.startsWith(POLICY_BLOCKED_PREFIX))
+ return null
+ try {
+ const parsed = JSON.parse(error.slice(POLICY_BLOCKED_PREFIX.length)) as PolicyBlockedVersion[]
+ return parsed.length > 0 ? parsed : null
+ }
+ catch (err) {
+ console.error('[Harness] failed to parse policy-blocked payload:', err)
+ return null
+ }
+}
+
function parseIncompatible(error: string): IncompatibleVersion[] | null {
if (!error.startsWith(INCOMPATIBLE_PREFIX))
return null
@@ -56,6 +82,12 @@ export const preinstall = defineStore({
* 非空时界面展示风险提示与勾选清单(而非插件列表或错误态)。
*/
incompatible: [] as IncompatibleVersion[],
+ /**
+ * 被 pnpm 发布时长策略拦下的精确版本(`minimumReleaseAge`)。
+ * 非空时同样展示风险提示与勾选清单——档案已声明这些太新的版本,不授权则**每次**
+ * 插件操作都会失败,用户在这里勾选授权后重跑安装即可解开。
+ */
+ policyBlocked: [] as PolicyBlockedVersion[],
/** 拉取预装插件列表失败(区别于空列表;UI 据此展示错误态 + 重试) */
loadError: '',
/** 是否为首次安装引导(决定默认勾选策略):boot 流程进入时为 true,侧边栏手动打开为 false */
@@ -119,10 +151,15 @@ export const preinstall = defineStore({
console.error('[Harness] preinstall failed:', err)
const error = String(err)
const incompatible = parseIncompatible(error)
+ const policyBlocked = parsePolicyBlocked(error)
if (incompatible) {
// 不是故障而是待授权清单:交给界面展示风险与勾选,用户授权后重跑安装
this.incompatible = incompatible
}
+ else if (policyBlocked) {
+ // 同上,但拦下它的是 pnpm 的发布时长策略:清单同样交给界面勾选授权
+ this.policyBlocked = policyBlocked
+ }
else {
this.error = error.startsWith('NETWORK_ERROR:')
? i18next.t('preinstall.network_error')
@@ -158,6 +195,29 @@ export const preinstall = defineStore({
}
},
+ /**
+ * 授予被 pnpm 发布时长策略拦下的精确版本豁免,成功后由界面重跑安装。
+ *
+ * 与 [`allowIncompatible`] 是两套互不相干的授权(一个写档案的 `compatibility.json`、
+ * 一个写 `pnpm-workspace.yaml` 的 `minimumReleaseAgeExclude`),但形状一致:只提交
+ * 用户勾选的精确 `包名@版本`,失败按普通安装失败展示并回到可重试态。
+ */
+ async allowPolicyVersions(versions: PolicyBlockedVersion[]): Promise<boolean> {
+ if (this.installing || versions.length === 0)
+ return false
+ try {
+ await invoke('allow_plugin_policy_versions', { versions })
+ this.policyBlocked = []
+ return true
+ }
+ catch (err) {
+ console.error('[Harness] granting release-age exemption failed:', err)
+ this.policyBlocked = []
+ this.error = String(err)
+ return false
+ }
+ },
+
/**
* 取消正在进行的预装插件安装:网络抖动/拉包限流(429)时可能长时间卡在
* pnpm 重试;调用后端强杀插件安装进程树,回到可重试的选择态。
@@ -218,6 +278,7 @@ export const preinstall = defineStore({
this.error = ''
// 重新打开引导时清掉上次留下的拦截清单,否则会直接落在授权对话框上
this.incompatible = []
+ this.policyBlocked = []
this.logs = []
// 侧边栏手动打开:非首次安装,默认勾选策略为「仅已安装」
this.isFirstTime = false
diff --git a/src/store/modules/preinstall/types.ts b/src/store/modules/preinstall/types.ts
index 43df2d82..3154f8e2 100644
--- a/src/store/modules/preinstall/types.ts
+++ b/src/store/modules/preinstall/types.ts
@@ -36,3 +36,14 @@ export interface IncompatibleVersion {
version: string
runtime_version: string
}
+
+/**
+ * 被 pnpm 发布时长策略拦截的插件版本(与 Rust `service::plugin::PolicyBlockedVersion` 对齐)。
+ *
+ * 豁免写进档案的 `minimumReleaseAgeExclude`,按精确 `包名@版本` 生效,因此只需要这两个
+ * 字段;运行时版本与这条策略无关。
+ */
+export interface PolicyBlockedVersion {
+ name: string
+ version: string
+}
diff --git a/src/ui/config/plugin.tsx b/src/ui/config/plugin.tsx
index 465304cf..bfbcdb00 100644
--- a/src/ui/config/plugin.tsx
+++ b/src/ui/config/plugin.tsx
@@ -21,6 +21,37 @@ import { store } from '@/store'
import { silence } from '@/utils/silence'
import { toast } from '@/utils/toast'
+/**
+ * 被 pnpm 发布时长策略拦下的条目(后端 `PolicyBlockedVersion`)。
+ *
+ * 豁免是按精确 `包名@版本` 写进档案的 `minimumReleaseAgeExclude` 的,所以只需要这两个
+ * 字段;`published_at` 之类的细节由用户自己看时机,不参与授权键。
+ */
+interface PolicyBlockedVersion {
+ name: string
+ version: string
+}
+
+const POLICY_BLOCKED_PREFIX = 'PLUGIN_POLICY_BLOCKED:'
+
+/**
+ * 解析后端「发布时长策略拦下」的载荷;识别不出来返回 null,退回普通失败展示。
+ *
+ * 解析失败绝不能假装可授权——那会把一条读不出来的 JSON 变成用户勾选的豁免。
+ */
+function parsePolicyBlocked(error: string): PolicyBlockedVersion[] | null {
+ if (!error.startsWith(POLICY_BLOCKED_PREFIX))
+ return null
+ try {
+ const parsed = JSON.parse(error.slice(POLICY_BLOCKED_PREFIX.length)) as PolicyBlockedVersion[]
+ return parsed.length > 0 ? parsed : null
+ }
+ catch (err) {
+ console.error('[ConfigPlugin] failed to parse policy-blocked payload:', err)
+ return null
+ }
+}
+
/**
* 操作 chip 的样式变体:busy 时禁止点击并降低透明度,否则可点击。
* 统一各操作 chip 的 busy 样式,避免内联三元重复。
@@ -86,6 +117,59 @@ export function ConfigPlugin() {
const [dialogHolder, openDialog] = useOverlay(Modal, { type: 'holder' })
+ /**
+ * 记录发布时长策略豁免:pnpm 的 `minimumReleaseAge`(11 默认 24 小时)不放行档案里
+ * 已声明的太新版本,于是**每次**插件操作都硬失败(见后端 `PLUGIN_POLICY_BLOCKED`)。
+ * 用户确认接受这些精确版本后写进档案的 `minimumReleaseAgeExclude`,再重跑原操作。
+ */
+ const allowPolicy = useMutation({
+ mutationFn: (versions: PolicyBlockedVersion[]) => invoke<void>('allow_plugin_policy_versions', { versions }),
+ onError: (err) => {
+ console.error('[ConfigPlugin] allow_plugin_policy_versions failed:', err)
+ toast(t('plugins.policy_allow_failed'), {})
+ },
+ })
+
+ /**
+ * 被发布时长策略拦住时的出路:先让用户看清单并明确确认(与版本兼容性豁免一样,
+ * 不放宽默认策略、不替用户决定),确认后写入精确豁免并重跑原操作。
+ */
+ async function onPolicyBlocked(blocked: PolicyBlockedVersion[], retry: () => Promise<void>) {
+ try {
+ await openDialog({
+ status: 'warning',
+ title: t('plugins.policy_blocked_title'),
+ description: (
+ <div className="flex flex-col gap-2">
+ <p>{t('plugins.policy_blocked_desc')}</p>
+ <ul className="flex flex-col gap-1">
+ {blocked.map(item => (
+ <li key={`${item.name}@${item.version}`} className="font-mono text-[11px] text-ink">
+ {item.name}
+ @
+ {item.version}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ),
+ confirmText: t('plugins.policy_blocked_confirm'),
+ })
+ }
+ catch (e) {
+ silence(e, 'plugin policy blocked: dialog cancelled')
+ return
+ }
+ try {
+ await allowPolicy.mutateAsync(blocked)
+ }
+ catch (e) {
+ silence(e, 'plugin policy 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)
@@ -101,6 +185,13 @@ export function ConfigPlugin() {
onError: (err, id) => {
const name = plugins.find(p => p.id === id)?.name ?? id
console.error('[ConfigPlugin] upgrade failed:', err)
+ // 被发布时长策略拦住不是「升级失败」:档案已声明太新的版本,pnpm 不放行,重跑
+ // 多少次都一样。给出可操作的出路(授权精确版本后重试),而不是一句失败。
+ const blocked = parsePolicyBlocked(String(err))
+ if (blocked) {
+ void onPolicyBlocked(blocked, () => onUpgrade(id))
+ return
+ }
toast(t('plugins.upgrade_failed', { name }), {})
},
})
@@ -115,6 +206,13 @@ export function ConfigPlugin() {
onError: (err, id) => {
const name = plugins.find(p => p.id === id)?.name ?? id
console.error('[ConfigPlugin] remove failed:', err)
+ // 卸载同样会重写 lockfile 并复核整份档案,因此同样可能被发布时长策略拦住
+ // (档案里另有太新版本时):一样给出授权后重跑的出路,而不是一句失败。
+ const blocked = parsePolicyBlocked(String(err))
+ if (blocked) {
+ void onPolicyBlocked(blocked, () => runRemove(id))
+ return
+ }
toast(t('plugins.remove_failed', { name }), {})
},
})
@@ -221,6 +319,13 @@ export function ConfigPlugin() {
silence(e, 'plugin remove: dialog cancelled')
return
}
+ await runRemove(id)
+ }
+
+ /** 已确认过的卸载(发布时长豁免后重跑时不再追问一次「确认卸载」)。 */
+ async function runRemove(id: string) {
+ if (busy)
+ return
setBusy({ id, action: 'remove' })
try {
await remove.mutateAsync(id)
diff --git a/test/preinstall-incompatible.test.ts b/test/preinstall-incompatible.test.ts
index 110060bf..609eb782 100644
--- a/test/preinstall-incompatible.test.ts
+++ b/test/preinstall-incompatible.test.ts
@@ -1,5 +1,5 @@
import type { Event } from '@tauri-apps/api/event'
-import type { IncompatibleVersion } from '../src/store/modules/preinstall'
+import type { IncompatibleVersion, PolicyBlockedVersion } from '../src/store/modules/preinstall'
import { beforeEach, describe, expect, it, vi } from 'vitest'
// 版本兼容性拒绝的往返:后端把拒绝清单挂在错误串上(Tauri 命令的错误通道只有字符串),
@@ -11,6 +11,12 @@ const BLOCKED: IncompatibleVersion[] = [
{ name: 'dsh-rewind-plugin', version: '0.14.0', runtime_version: '0.2.0-rc.1' },
]
+// pnpm 发布时长策略拦下的条目:档案已声明太新的版本时每次插件操作都失败,因此这份清单
+// 同样要变成可勾选授权项(而不是一句「去插件面板」),授权后写档案豁免清单再重跑。
+const POLICY_BLOCKED: PolicyBlockedVersion[] = [
+ { name: '@wenbin_wb/dsh-bridge', version: '2.11.2' },
+]
+
const { eventListeners, invoke } = vi.hoisted(() => ({
eventListeners: new Map<string, (event: Event<unknown>) => void>(),
invoke: vi.fn(),
@@ -35,6 +41,7 @@ beforeEach(() => {
invoke.mockReset()
preinstall.error = ''
preinstall.incompatible = []
+ preinstall.policyBlocked = []
preinstall.installing = false
preinstall.logs = []
})
@@ -111,3 +118,65 @@ describe('preinstall version-exemption grant', () => {
expect(preinstall.incompatible).toEqual([])
})
})
+
+describe('preinstall release-age policy refusal', () => {
+ it('exposes the blocked exact versions as authorizable entries instead of a failure', async () => {
+ invoke.mockRejectedValue(`PLUGIN_POLICY_BLOCKED: ${JSON.stringify(POLICY_BLOCKED)}`)
+
+ await preinstall.confirm({ installIds: ['@wenbin_wb/dsh-bridge'] })
+
+ expect(preinstall.policyBlocked).toEqual(POLICY_BLOCKED)
+ expect(preinstall.incompatible).toEqual([])
+ expect(preinstall.error).toBe('')
+ })
+
+ it('keeps a malformed policy payload as a plain install failure', async () => {
+ invoke.mockRejectedValue('PLUGIN_POLICY_BLOCKED: not-json')
+
+ await preinstall.confirm({ installIds: ['@wenbin_wb/dsh-bridge'] })
+
+ expect(preinstall.policyBlocked).toEqual([])
+ expect(preinstall.error).toBe('PLUGIN_POLICY_BLOCKED: not-json')
+ })
+
+ it('grants exactly the checked entries and clears the pending list', async () => {
+ preinstall.policyBlocked = POLICY_BLOCKED
+ invoke.mockResolvedValue(undefined)
+
+ const granted = await preinstall.allowPolicyVersions(POLICY_BLOCKED)
+
+ expect(granted).toBe(true)
+ expect(invoke).toHaveBeenCalledWith('allow_plugin_policy_versions', { versions: POLICY_BLOCKED })
+ expect(preinstall.policyBlocked).toEqual([])
+ })
+
+ it('does not touch the backend when nothing is checked', async () => {
+ preinstall.policyBlocked = POLICY_BLOCKED
+
+ const granted = await preinstall.allowPolicyVersions([])
+
+ expect(granted).toBe(false)
+ expect(invoke).not.toHaveBeenCalled()
+ expect(preinstall.policyBlocked).toEqual(POLICY_BLOCKED)
+ })
+
+ it('reports a failed grant as an install failure with the pending list cleared', async () => {
+ preinstall.policyBlocked = POLICY_BLOCKED
+ invoke.mockRejectedValue('PROFILE_WORKSPACE_WRITE: access denied')
+
+ const granted = await preinstall.allowPolicyVersions(POLICY_BLOCKED)
+
+ expect(granted).toBe(false)
+ expect(preinstall.policyBlocked).toEqual([])
+ expect(preinstall.error).toBe('PROFILE_WORKSPACE_WRITE: access denied')
+ })
+
+ it('drops a stale policy list when the wizard is reopened', async () => {
+ preinstall.policyBlocked = POLICY_BLOCKED
+ invoke.mockResolvedValue([])
+
+ await preinstall.open()
+
+ expect(preinstall.policyBlocked).toEqual([])
+ })
+})