DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(plugin): 兼容 pnpm 10 安装预设插件时 onlyBuiltDependencies 放行项 (#123)
Mao Mrec9d5ba41551
diff --git a/src-tauri/src/service/plugin/install.rs b/src-tauri/src/service/plugin/install.rsindex 9335b358..6e6f48fe 100644--- a/src-tauri/src/service/plugin/install.rs+++ b/src-tauri/src/service/plugin/install.rs@@ -2,14 +2,19 @@//! 停止运行中的服务),随后调用 `dsh plugin --profile web add <specs...>`,//! 成功后执行 Windows 极简模式专项修复。//!-//! pnpm v11 对两类构建脚本默认不放行、缺白名单时报硬错误:+//! pnpm 对两类构建脚本默认不放行、缺白名单时报硬错误://! 1. git 托管插件的 `prepare` 构建(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`)——-//! 其允许键(depPath = `name@<pkgResolutionId>`)随 pnpm 的克隆方式变化-//! (git+ssh#sha / codeload tar.gz),无法预先确定;+//! 其允许键随 pnpm 的克隆方式变化(git+ssh#sha / codeload tar.gz),无法预先确定;//! 2. 传递依赖的原生构建(如 `node-pty`,`ERR_PNPM_IGNORED_BUILDS`)。-//! 因此从 pnpm 错误输出解析它建议的 `allowBuilds` 键,写入 profile 的+//! 因此从 pnpm 错误输出解析它建议的允许键,写入 profile 的//! `pnpm-workspace.yaml` 后重试,直至成功或无可解析项。//!+//! pnpm 10 与 11 对放行项的配置键与输出形式不同(均由各自报错提示决定,只能运行期+//! 读取,见 [`parse_allowlist_keys`] 与 [`apply_allow_build_keys`]):+//! - pnpm 10(旧 store 复用用户版)只认 `onlyBuiltDependencies`(list 形式);+//! - pnpm 11(捆绑版)认 `allowBuilds`(map 形式)。+//! 应用会把同一批包名同时写入这两个键,保证任一版本 pnpm 都能读到放行项。+//!//! 关键陷阱:pnpm v11 在 `allowBuilds` 阻断时可能仍以 **exit 0** 退出(假成功),//! 所以重试逻辑不能只看退出码(见 [`run_plugin_with_allow_build_retry`]),安装成功//! 后还会核验 `node_modules` 产物是否真实落盘(见 [`verify_installed_products`])。@@ -782,22 +787,24 @@ pub(crate) fn bundled_pnpm_major(app_handle: &AppHandle) -> Option<u32> {.ok()}-/// 从 pnpm 失败输出中解析需写入 `allowBuilds` 的键集合:-/// - git 托管插件 prepare 被拦时,pnpm 会提示 `allowBuilds:\n <depPath>: true`,-/// 原样采纳 depPath(形式随克隆方式变化,只能是运行期报出的值);+/// 从 pnpm 失败输出中解析需写入构建放行白名单的包名/键集合。+///+/// 兼容 pnpm 10 与 11 的两套输出形式(两者对 git 托管插件 prepare 门禁的提示不同):+/// - pnpm 11(捆绑版)提示 `allowBuilds:\n <key>: true`(map 形式),原样采纳 `<key>`;+/// - pnpm 10(旧 store 复用用户版)提示 `onlyBuiltDependencies:\n - "<name>"`+/// (list 形式)与报错文本里的包名,二者归并取包名;/// - 传递原生依赖被忽略构建(`Ignored build scripts:`)时,取其 `name@version` 的包名。fn parse_allowlist_keys(output: &str) -> Vec<String> {let mut keys: Vec<String> = Vec::new();let lines: Vec<&str> = output.lines().collect();- // 1) git depPath 允许键:跟随 `allowBuilds:` 示例行后的缩进 `<key>: true`。+ // 1) git 托管插件的允许键:跟随 `allowBuilds:` 示例行后的缩进 `<key>: true`。+ // pnpm 11 的报错(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`)建议按此形式放行。for (idx, line) in lines.iter().enumerate() {if line.trim() == "allowBuilds:" {if let Some(next) = lines.get(idx + 1) {if let Some(key) = extract_allow_line_key(next) {- if !keys.iter().any(|k| k == &key) {- keys.push(key);- }+ push_unique(&mut keys, key);}}}@@ -811,14 +818,49 @@ fn parse_allowlist_keys(output: &str) -> Vec<String> {if token.is_empty() {continue;}- let name = token.split('@').next().unwrap_or(token).trim();- if !name.is_empty() && !keys.iter().any(|k| k == name) {- keys.push(name.to_string());+ // 版本号在最后一个 `@` 之后:scoped 包名(`@scope/name`)本身含 `@`,+ // 必须从尾部切分才能保留完整包名,否则 `split('@').next()` 会得到空串。+ let name = token+ .rsplit_once('@')+ .map_or(token, |(name, _)| name)+ .trim();+ if !name.is_empty() {+ push_unique(&mut keys, name.to_string());+ }+ }+ }+ }++ // 3) pnpm 10 的 `onlyBuiltDependencies:` 列表(git 托管插件 prepare 门禁):+ // onlyBuiltDependencies:+ // - "dsh-better-sidebar"+ for (idx, line) in lines.iter().enumerate() {+ if line.trim() == "onlyBuiltDependencies:" {+ for next in lines.iter().skip(idx + 1) {+ let trimmed = next.trim_start();+ if let Some(rest) = trimmed.strip_prefix('-') {+ // 列表项:可能带缩进也可能不带(pnpm 提示段两种形式都出现过),+ // 先于「顶层键」判定接受,避免无缩进条目被误当作顶层键提前退出。+ let item = rest.trim().trim_matches(['"', '\'']);+ if !item.is_empty() {+ push_unique(&mut keys, item.to_string());+ }+ } else if !next.starts_with(' ') && !next.starts_with('\t') && !trimmed.is_empty() && !trimmed.starts_with('#') {+ break; // 顶层键(无缩进且非列表项),已离开列表}+ // 其余(缩进行的非列表项、空行、注释):继续扫描}}}+ // 4) pnpm 10 报错文本里的包名(`The git-hosted package "NAME@VER" ... "onlyBuiltDependencies" allowlist.`),+ // 与第 3 步归并:即便列表被截断也能从消息取回名字。+ for line in &lines {+ if let Some(name) = extract_only_builds_git_name(line) {+ push_unique(&mut keys, name);+ }+ }+keys}@@ -837,12 +879,44 @@ fn extract_allow_line_key(line: &str) -> Option<String> {Some(key.to_string())}-/// profile 下的 `pnpm-workspace.yaml` 路径($DSH_HOME/profiles/<当前档案>)+/// 去重追加:避免同一键在不同输出块被重复计为待放行项。+fn push_unique(keys: &mut Vec<String>, key: String) {+ if !keys.iter().any(|k| k == &key) {+ keys.push(key);+ }+}++/// 从 pnpm 10 的 git 托管插件 prepare 门禁报错文本提取包名。+///+/// 形如 `The git-hosted package "NAME@VERSION" needs to execute build scripts+/// but is not in the "onlyBuiltDependencies" allowlist.`。+/// 仅匹配 `onlyBuiltDependencies` 形式的文本(pnpm 10);pnpm 11 的 `allowBuilds`+/// 形式仍由 [`extract_allow_line_key`] 解析 `allowBuilds:` 块,二者互不干扰。+fn extract_only_builds_git_name(line: &str) -> Option<String> {+ if !line.contains("\"onlyBuiltDependencies\" allowlist") {+ return None;+ }+ let marker = "The git-hosted package \"";+ let start = line.find(marker)? + marker.len();+ let rest = &line[start..];+ let end = rest.find('"')?;+ let quoted = &rest[..end]; // "name@version"+ // 包名(含 scoped 前缀 `@scope/name`)在最末一个 `@` 之前,版本号在之后。+ let (name, _version) = quoted.rsplit_once('@')?;+ (!name.is_empty()).then(|| name.to_string())+}++/// profile 下的 `pnpm-workspace.yaml` 路径($DSH_HOME/profiles/<当前档案>)。+///+/// 构建放行项必须写进**当前活动档案**的工作区配置:`dsh plugin --profile <档案>`+/// 驱动的 pnpm 只读取该档案目录下的 `pnpm-workspace.yaml`,写错路径(如全局或其它+/// 档案)会让放行项失效,安装/升级仍会被 pnpm 的构建门禁拦截。fn profile_workspace_path(app_handle: &AppHandle) -> PathBuf {profile_dir(app_handle).join("pnpm-workspace.yaml")}-/// 把新的 `allowBuilds` 键合并写回 profile 的 `pnpm-workspace.yaml`。+/// 把新的构建放行键合并写回 profile 的 `pnpm-workspace.yaml`,同时写入+/// `allowBuilds`(map,pnpm 11)与 `onlyBuiltDependencies`(list,pnpm 10)。////// 用 YAML 库(serde_yaml)整体改写而非字符串拼接,避免格式错乱:/// - 键(git depPath 含 `@`/`/`/`:`/`#`)由库自动按需加引号,不再手工拼;@@ -880,11 +954,12 @@ fn add_allow_build_keys(app_handle: &AppHandle, keys: &[String]) -> Result<(), Sstd::fs::write(&path, rendered).map_err(|e| format!("PREINSTALL_WRITE_WORKSPACE: {e}"))}-/// 把新的 `allowBuilds` 键合并进 `pnpm-workspace.yaml` 文本并返回新文本。+/// 把新的构建放行键合并进 `pnpm-workspace.yaml` 文本并返回新文本。////// 用 YAML 库(serde_yaml)整体改写而非字符串拼接,避免格式错乱:-/// - 键(git depPath 含 `@`/`/`/`:`/`#`)由库自动按需加引号,不再手工拼;-/// - 已存在的同名键会被就地覆盖为 `true`,不会残留占位值,也不会产生重复键。+/// - `allowBuilds`(pnpm 11)写为 map:键(git depPath 含 `@`/`/`/`:`/`#`)由库+/// 自动按需加引号,已存在的同名键会被就地覆盖为 `true`,不残留占位值、不产生重复键;+/// - `onlyBuiltDependencies`(pnpm 10)写为 list:追加唯一的包名,不清空已有条目。////// 防御性修复:旧版本用字符串拼接可能留下「重复映射键」的损坏文件/// (最多见的是 `node-pty: set this to true or false` 占位行与真正的@@ -941,6 +1016,39 @@ fn apply_allow_build_keys(content: &str, keys: &[String]) -> Result<String, Striallow_builds.insert(k, Value::Bool(true));dirty = true;}++ // `allowBuilds` 的借用已在上面循环结束后释放(NLL),此处才能对 `map`+ // 再次取可变引用处理 `onlyBuiltDependencies`。+ //+ // pnpm 10(旧 store 复用的用户版)只认 `onlyBuiltDependencies`(list 形式,+ // 见其报错提示),因此这里一并写回,保证 pnpm 10 / 11 两版都能读到放行项;+ // `allowBuilds`(map 形式)覆盖 pnpm 11(捆绑版),二者共存互不冲突。+ let only_key = Value::String("onlyBuiltDependencies".to_string());+ let to_add: Vec<Value> = {+ let existing_only = map.get(&only_key).and_then(Value::as_sequence);+ keys.iter()+ .filter(|k| {+ existing_only.map_or(true, |seq| !seq.contains(&Value::String((*k).clone())))+ })+ .map(|k| Value::String(k.clone()))+ .collect()+ };+ if !to_add.is_empty() {+ if !map.contains_key(&only_key) {+ map.insert(only_key.clone(), Value::Sequence(Vec::new()));+ }+ let only_builds = map+ .get_mut(&only_key)+ .and_then(Value::as_sequence_mut)+ .ok_or_else(|| {+ "PREINSTALL_WORKSPACE_ONLYBUILT_NOT_SEQ: onlyBuiltDependencies must be a sequence"+ .to_string()+ })?;+ for v in to_add {+ only_builds.push(v);+ dirty = true;+ }+ }if !dirty && !repaired {return Ok(content.to_string());}@@ -1124,7 +1232,7 @@ pub(crate) fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> bool {#[cfg(test)]mod tests {use std::path::PathBuf;- use super::{append_command_output, apply_allow_build_keys, collapse_allow_builds_duplicates, extract_allow_line_key, git_transport_hint, normalize_git_spec, parse_allowlist_keys, parse_store_major_from_modules_yaml, preset_spec_for_install, shell_quote_spec, silent_install_failure_detail, PreinstallPluginInfo};+ use super::{append_command_output, apply_allow_build_keys, collapse_allow_builds_duplicates, extract_allow_line_key, extract_only_builds_git_name, git_transport_hint, normalize_git_spec, parse_allowlist_keys, parse_store_major_from_modules_yaml, preset_spec_for_install, shell_quote_spec, silent_install_failure_detail, PreinstallPluginInfo};/// 构造预设条目的测试助手(internal 由各用例显式指定)fn preset(id: &str, spec: &str, internal: bool) -> PreinstallPluginInfo {@@ -1282,12 +1390,87 @@ allowBuilds:assert_eq!(keys, vec!["node-pty".to_string()]);}+ #[test]+ fn parse_ignored_builds_scoped_name() {+ // 回归(CodeRabbit):scoped 原生依赖 `@scope/name@version` 必须保留完整包名,+ // 不能按第一个 `@` 切分(那会得到空串导致该包被跳过、无法放行)。+ let out = "[ERR_PNPM_IGNORED_BUILDS] Ignored build scripts: @deepseek-ai/[email protected], [email protected]\n";+ let keys = parse_allowlist_keys(out);+ assert_eq!(+ keys,+ vec!["@deepseek-ai/dsh-base".to_string(), "node-pty".to_string()]+ );+ }+#[test]fn parse_empty_when_irrelevant() {let out = "everything looks fine output\nno allowlist here\n";assert!(parse_allowlist_keys(out).is_empty());}+ #[test]+ fn parse_pnpm10_only_built_dependencies_list() {+ // 回归(issue:预装插件在 pnpm 10 下报 ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED):+ // pnpm 10(旧 store 复用的用户版)只输出 onlyBuiltDependencies 列表与报错文本+ // 里的包名,不含 allowBuilds 块。此前 parse_allowlist_keys 只认 allowBuilds,+ // 导致读不到 dsh-better-sidebar、不写白名单、重试也被跳过,安装必然失败。+ let out = "\+[ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED] Failed to prepare git-hosted package fetched from \"https://codeload.github.com/omdsh-dev/DSH-better-sidebar/tar.gz/f9153dfc1ce47cf43445c1b351ee3ae47b4ad9f1\"+The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist.+...+This error happened while installing a direct dependency of C:\\Users\\hairy\\.dsh.dev\\profiles\\web+Add the package to \"onlyBuiltDependencies\" in your project's pnpm-workspace.yaml to allow it to run scripts. For example:+onlyBuiltDependencies:+- \"dsh-better-sidebar\"+";+ let keys = parse_allowlist_keys(out);+ assert_eq!(keys, vec!["dsh-better-sidebar".to_string()]);+ }++ #[test]+ fn parse_pnpm10_unindented_list_items() {+ // 回归(CodeRabbit):pnpm 10 提示段可能不带缩进(`- "name"` 与顶层键同列)。+ // 此前循环会把它误当顶层键提前退出,只靠报错文本回退解析才碰巧通过。+ let out = "onlyBuiltDependencies:\n- \"dsh-better-sidebar\"\n";+ let keys = parse_allowlist_keys(out);+ assert_eq!(keys, vec!["dsh-better-sidebar".to_string()]);+ }++ #[test]+ fn parse_pnpm10_scoped_package_from_message() {+ // 报错文本在列表被截断时也可取回名字;scoped 包名保留 `@scope/` 前缀。+ let out = "The git-hosted package \"@deepseek-ai/[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist.\n";+ let keys = parse_allowlist_keys(out);+ assert_eq!(keys, vec!["@deepseek-ai/dsh-base".to_string()]);+ }++ #[test]+ fn extract_only_builds_git_name_strips_version_and_handles_scoped() {+ // 普通包名:name@version → name+ assert_eq!(+ extract_only_builds_git_name(+ "The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist."+ ),+ Some("node-pty".to_string())+ );+ // scoped 包名:@scope/name@version → @scope/name(只剥最末一个 @ 后的版本号)+ assert_eq!(+ extract_only_builds_git_name(+ "The git-hosted package \"@deepseek-ai/[email protected]\" needs to execute build scripts but is not in the \"onlyBuiltDependencies\" allowlist."+ ),+ Some("@deepseek-ai/dsh-base".to_string())+ );+ // pnpm 11 的 allowBuilds 文本不匹配(交由 allowBuilds 块解析)+ assert_eq!(+ extract_only_builds_git_name(+ "The git-hosted package \"[email protected]\" needs to execute build scripts but is not in the \"allowBuilds\" allowlist."+ ),+ None+ );+ // 非 git 门禁行不匹配+ assert_eq!(extract_only_builds_git_name("allowBuilds:\n x: true"), None);+ }+#[test]fn allow_line_key_requires_indent() {let key = extract_allow_line_key(" node-pty: true");@@ -1324,12 +1507,57 @@ allowBuilds:#[test]fn apply_is_idempotent_and_does_not_duplicate() {- // 已放行的键再次写入:结果不变(幂等、不产生重复键)- let base = "packages:\n - .\nnodeLinker: hoisted\nautoInstallPeers: false\nallowBuilds:\n node-pty: true\n";+ // 已放行的键再次写入:结果不变(幂等、不产生重复键)。输入须同时包含+ // allowBuilds 与 onlyBuiltDependencies 两个放行出口(桌面端双写,见+ // apply_allow_build_keys),证明两处都幂等。+ let base = "packages:\n - .\nnodeLinker: hoisted\nautoInstallPeers: false\nallowBuilds:\n node-pty: true\nonlyBuiltDependencies:\n - node-pty\n";let out = apply_allow_build_keys(base, &["node-pty".to_string()]).unwrap();assert_eq!(out, base);}+ #[test]+ fn apply_writes_both_allowbuilds_and_only_built_dependencies() {+ // pnpm 11 认 allowBuilds(map),pnpm 10 认 onlyBuiltDependencies(list),+ // 两者须同时写回,用户 pnpm 10 / 捆绑版 pnpm 11 都能读到放行项。+ let base = "packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n";+ let out = apply_allow_build_keys(base, &["dsh-better-sidebar".to_string()]).unwrap();+ let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();+ // pnpm 11:allowBuilds 为 map 形式+ assert_eq!(+ doc["allowBuilds"]["dsh-better-sidebar"],+ serde_yaml::Value::Bool(true)+ );+ // pnpm 10:onlyBuiltDependencies 为 list 形式+ let only = doc+ .get("onlyBuiltDependencies")+ .and_then(serde_yaml::Value::as_sequence)+ .expect("onlyBuiltDependencies must be a sequence");+ assert_eq!(+ only,+ &vec![serde_yaml::Value::String("dsh-better-sidebar".to_string())]+ );+ // 基础设置被保留+ assert!(doc.get("packages").is_some());+ assert!(doc.get("nodeLinker").is_some());+ }++ #[test]+ fn apply_only_built_dependencies_preserves_existing_entries() {+ // onlyBuiltDependencies 已含旧条目时,只追加新键、不清空原有条目。+ let base = "packages:\n - .\nallowBuilds:\n esbuild: true\nonlyBuiltDependencies:\n - esbuild\n";+ let out = apply_allow_build_keys(base, &["dsh-better-sidebar".to_string()]).unwrap();+ let doc: serde_yaml::Value = serde_yaml::from_str(&out).unwrap();+ let only = doc+ .get("onlyBuiltDependencies")+ .and_then(serde_yaml::Value::as_sequence)+ .expect("onlyBuiltDependencies must be a sequence");+ let names: Vec<&str> = only+ .iter()+ .filter_map(|v| v.as_str())+ .collect();+ assert_eq!(names, vec!["esbuild", "dsh-better-sidebar"]);+ }+#[test]fn apply_quotes_git_dep_path_keys() {let dep = "dsh-better-sidebar@git+ssh://[email protected]/omdsh-dev/DSH-better-sidebar.git#6c89".to_string();