Skip to content

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

fix(plugin): 内置插件链接回读恒失败时改用离线自建链接

hairyfbd9d0d174da1
diff --git a/docs/AGENTS.desktop.md b/docs/AGENTS.desktop.md
index ceb5e144..545d073a 100644
--- a/docs/AGENTS.desktop.md
+++ b/docs/AGENTS.desktop.md
@@ -191,6 +191,7 @@ function ConfirmDialog(props: ConfirmDialogProps) {
* **pnpm Store 绑定冲突**:为防止全局 `store-dir` 冲突导致插件安装失败,`build_plugin_envs` 会将档案记录的 `storeDir` 显式注入为 `npm_config_store_dir` 环境变量。
* **YAML 补丁层错误 (Issue #525)**:损坏的 `cordis.patch.yml` 会被隔离为 `<Name>.broken-<Timestamp>`。若隔离/重命名失败,程序将直接中止并返回 `PATCH_LAYER_QUARANTINE_FAILED`,要求用户手动处理。
* **pnpm Workspace 多文档修复 (Issue #526)**:若 `pnpm-workspace.yaml` 被意外包含 `---` 多文档,解析器会自动尝试解析并合并为单文档落盘自愈(日志标记 `PROFILE_WORKSPACE_MULTI_DOCUMENT`)。
+* **pnpm `link:` 回读失败兜底 (Issue #264)**:pnpm 建好内置插件目录链接后回读 `package.json` 可能**恒定**失败(libuv `UV_UNKNOWN` / 退出码 -4094,实时防护 / EDR / 云盘 / 重解析点过滤驱动所致),重试无法越过且会让启动永久卡在 Plugin installation 阶段;此时由桌面端自建链接并补齐清单(`service::plugin::internal::materialize`,日志标记 `INTERNAL_PLUGIN_OFFLINE_LINK_*`),**仅在诊断里的失败路径确属本轮待装入口时**才兜底(同一签名也可能来自用户自己的 `link:` 依赖,路径不可归因时只给排除项提示、绝不吞成成功)。该路径不写 `pnpm-lock.yaml` 的 importers 条目,由下一次 pnpm 操作补齐。
* **旧版 WebKit 缺失 Iterator 补丁 (Issue #539)**:在非 Windows 平台的 WebView 初始化时注入 `compat_iterator.js.inc` 垫片,补齐 ES2025 Iterator Helpers(在 `Object.getPrototypeOf(...)` 上挂载),防止旧 macOS WebKit 崩溃。
* **Windows `.cmd` shim 行尾 (Issue #581)**:`.gitattributes` 把 `.rs` 固定为 LF,生成的 `dsh.cmd`/`pnpm.cmd` 必须在返回前统一转 CRLF(`normalize_cmd_line_endings`),LF-only 会让部分环境下 cmd.exe 解析错位、内置插件安装全部失败。
* **macOS 媒体权限配置 (Issue #214)**:必须同时在 `Info.plist` (声明 Usage Description) 与 `Entitlements.plist` (声明 `com.apple.security.device.*`) 中配置,相对路径基于 tauri bundle 运行时的 CWD 目录。
diff --git a/src-tauri/src/service/core/mod.rs b/src-tauri/src/service/core/mod.rs
index 0a0a6561..c7ceb54a 100644
--- a/src-tauri/src/service/core/mod.rs
+++ b/src-tauri/src/service/core/mod.rs
@@ -31,3 +31,6 @@ pub use local::{local_core_package_dir, update_local_core};
pub use source::{active_dsh_binary, active_source, active_version, CoreSource, HarnessCore};
pub use version::{download_version, has_installed_version, list, remove_version, set_active};
pub(crate) use runtime::prepare_active_runtime;
+// 目录链接实现(Windows 符号链接 → 无特权时的 junction 回退)供插件模块复用:
+// pnpm 建链后回读失败时,桌面端自行落盘内置插件入口(见 plugin::internal::materialize)。
+pub(crate) use runtime::create_directory_link;
diff --git a/src-tauri/src/service/core/runtime.rs b/src-tauri/src/service/core/runtime.rs
index f508d04d..99d3c45d 100644
--- a/src-tauri/src/service/core/runtime.rs
+++ b/src-tauri/src/service/core/runtime.rs
@@ -489,12 +489,12 @@ fn remove_link_only(path: &Path) -> Result<(), String> {
}
#[cfg(unix)]
-fn create_directory_link(source: &Path, destination: &Path) -> std::io::Result<()> {
+pub(crate) fn create_directory_link(source: &Path, destination: &Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(source, destination)
}
#[cfg(windows)]
-fn create_directory_link(source: &Path, destination: &Path) -> std::io::Result<()> {
+pub(crate) fn create_directory_link(source: &Path, destination: &Path) -> std::io::Result<()> {
// 优先创建真正的符号链接:仅在启用 Developer Mode 或具备
// SeCreateSymbolicLinkPrivilege(管理员)时才可用;普通用户(release 版
// 默认非管理员启动)会得到 ERROR_PRIVILEGE_NOT_HELD(os error 1314),
diff --git a/src-tauri/src/service/plugin/internal/materialize.rs b/src-tauri/src/service/plugin/internal/materialize.rs
new file mode 100644
index 00000000..034ed3d1
--- /dev/null
+++ b/src-tauri/src/service/plugin/internal/materialize.rs
@@ -0,0 +1,329 @@
+//! 内置插件入口的离线落盘兜底:pnpm 的 `link:` 安装路径失败时,改由桌面端自己
+//! 建立 `node_modules/<name>` 目录链接并补齐 profile 清单。
+//!
+//! 为什么需要:pnpm 安装 `link:` 依赖的最后一步是「建好目录链接后立刻回读
+//! `package.json`」,该回读在部分 Windows 环境**恒定**失败——libuv 报
+//! `UV_UNKNOWN`(退出码 -4094,输出含 `UNKNOWN: unknown error, open
+//! '<profile>/node_modules/<name>/package.json'`)。issue #264 把它当作瞬时
+//! 态(重解析点落定 / 杀软扫新路径)用重试覆盖,但实时防护、云盘或重解析点
+//! 过滤驱动一旦稳定拦下该回读,重试就永远无法越过:`link:` 依赖不落盘 →
+//! 下次启动又判 `dep_ok=false` 重装 → 应用每次都卡在 Plugin installation 阶段。
+//!
+//! 兜底之所以成立:链接本身由桌面端的目录链接实现建立(无特权 junction 回退,
+//! 与 pnpm 生成的布局一致),**不需要 pnpm 回读**;可读性由本进程核验。清单
+//! 的 `dependencies` 与 `dsh.profile.bundles` 写成与 pnpm 成功安装一致的值,
+//! 保证 loader 能解析并加载插件。唯一不做的是 `pnpm-lock.yaml` 的 importers
+//! 条目,由下一次用户安装插件时 pnpm 自行补齐。
+
+use std::path::{Path, PathBuf};
+
+use super::manifest::{
+ internal_plugin_entry_is_ready, remove_stale_plugin_entry, write_profile_manifest,
+};
+
+/// 一个待自建的内置插件入口(`spec` 为写入清单的 `link:` 依赖值)。
+pub(super) struct OfflineLink {
+ pub id: String,
+ pub name: String,
+ pub spec: String,
+ pub bundled: PathBuf,
+ pub entry: PathBuf,
+}
+
+/// 强制重建全部入口链接并写回清单;任一入口不可读即整体失败。
+///
+/// 强制重建(而不是复用既有入口)是必须的:既有入口可能正是 pnpm 建好后无法
+/// 回读的那一个,保留它等于把同一失败带进下一轮启动。
+pub(super) fn materialize_links(profile: &Path, links: &[OfflineLink]) -> Result<(), String> {
+ let node_modules = profile.join("node_modules");
+ std::fs::create_dir_all(&node_modules).map_err(|e| {
+ format!(
+ "INTERNAL_PLUGIN_OFFLINE_MKDIR_FAILED: {}: {e}",
+ node_modules.display()
+ )
+ })?;
+
+ let manifest_path = profile.join("package.json");
+ let raw = std::fs::read_to_string(&manifest_path).map_err(|e| {
+ format!(
+ "INTERNAL_PLUGIN_OFFLINE_MANIFEST_READ_FAILED: {}: {e}",
+ manifest_path.display()
+ )
+ })?;
+ let mut manifest: serde_json::Value = serde_json::from_str(&raw)
+ .map_err(|e| format!("INTERNAL_PLUGIN_OFFLINE_MANIFEST_PARSE_FAILED: {e}"))?;
+
+ let mut failures = Vec::new();
+ for link in links {
+ if let Err(e) = remove_stale_plugin_entry(&link.entry) {
+ failures.push(format!("{}: 清理旧入口失败 {e}", link.id));
+ continue;
+ }
+ // 预设显式声明 scoped `package`(如 `@scope/name`)时入口位于
+ // `node_modules/@scope/name`:父目录不存在会直接让建链失败,先补齐。
+ if let Some(parent) = link.entry.parent() {
+ if let Err(e) = std::fs::create_dir_all(parent) {
+ failures.push(format!(
+ "{}: 建立入口父目录失败 {}: {e}",
+ link.id,
+ parent.display()
+ ));
+ continue;
+ }
+ }
+ if let Err(e) = crate::service::core::create_directory_link(&link.bundled, &link.entry) {
+ failures.push(format!(
+ "{}: 建立链接失败 {} -> {}: {e}",
+ link.id,
+ link.entry.display(),
+ link.bundled.display()
+ ));
+ continue;
+ }
+ if !internal_plugin_entry_is_ready(&link.entry) {
+ failures.push(format!(
+ "{}: 自建链接后仍不可读 {}",
+ link.id,
+ link.entry.display()
+ ));
+ }
+ }
+ if !failures.is_empty() {
+ return Err(format!(
+ "INTERNAL_PLUGIN_OFFLINE_LINK_FAILED: {}",
+ failures.join("; ")
+ ));
+ }
+
+ upsert_manifest(&mut manifest, links)?;
+ write_profile_manifest(&manifest_path, &manifest)?;
+ log::warn!(
+ "INTERNAL_PLUGIN_OFFLINE_LINK_OK: materialized {} internal plugin links without pnpm",
+ links.len()
+ );
+ Ok(())
+}
+
+/// 把 `dependencies` 与 `dsh.profile.bundles` 写成与 pnpm 成功安装等价的形态,
+/// 只增改本次的包名,绝不触碰用户的其它依赖与 bundle 顺序。
+fn upsert_manifest(manifest: &mut serde_json::Value, links: &[OfflineLink]) -> Result<(), String> {
+ let object = manifest.as_object_mut().ok_or_else(|| {
+ "INTERNAL_PLUGIN_OFFLINE_MANIFEST_INVALID: profile package.json is not an object"
+ .to_string()
+ })?;
+
+ let dependencies = object
+ .entry("dependencies".to_string())
+ .or_insert_with(|| serde_json::json!({}))
+ .as_object_mut()
+ .ok_or_else(|| {
+ "INTERNAL_PLUGIN_OFFLINE_MANIFEST_INVALID: dependencies is not an object".to_string()
+ })?;
+ for link in links {
+ dependencies.insert(
+ link.name.clone(),
+ serde_json::Value::String(link.spec.clone()),
+ );
+ }
+
+ let dsh = object
+ .entry("dsh".to_string())
+ .or_insert_with(|| serde_json::json!({}))
+ .as_object_mut()
+ .ok_or_else(|| {
+ "INTERNAL_PLUGIN_OFFLINE_MANIFEST_INVALID: dsh is not an object".to_string()
+ })?;
+ let profile = dsh
+ .entry("profile".to_string())
+ .or_insert_with(|| serde_json::json!({}))
+ .as_object_mut()
+ .ok_or_else(|| {
+ "INTERNAL_PLUGIN_OFFLINE_MANIFEST_INVALID: dsh.profile is not an object".to_string()
+ })?;
+ let bundles = profile
+ .entry("bundles".to_string())
+ .or_insert_with(|| serde_json::json!([]))
+ .as_array_mut()
+ .ok_or_else(|| {
+ "INTERNAL_PLUGIN_OFFLINE_MANIFEST_INVALID: dsh.profile.bundles is not an array"
+ .to_string()
+ })?;
+ for link in links {
+ if !bundles
+ .iter()
+ .any(|bundle| bundle.as_str() == Some(link.name.as_str()))
+ {
+ bundles.push(serde_json::Value::String(link.name.clone()));
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::service::plugin::preset::bundled_dep_spec;
+
+ fn tmp_root(label: &str) -> PathBuf {
+ let root =
+ std::env::temp_dir().join(format!("dsh-offline-link-{label}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ std::fs::create_dir_all(&root).unwrap();
+ root
+ }
+
+ /// 造一个「捆绑源目录 + profile」的最小现场:源目录含可读 package.json。
+ fn fixture(label: &str, names: &[&str]) -> (PathBuf, PathBuf, Vec<OfflineLink>) {
+ let root = tmp_root(label);
+ let profile = root.join("profile");
+ std::fs::create_dir_all(&profile).unwrap();
+ std::fs::write(
+ profile.join("package.json"),
+ r#"{
+ "name": "dsh-profile-tauri",
+ "private": true,
+ "dependencies": { "dshmarket": "github:dsh-market/dshmarket" },
+ "dsh": { "profile": { "bundles": ["@deepseek-ai/dsh-base", "dshmarket"] } }
+}"#,
+ )
+ .unwrap();
+
+ let mut links = Vec::new();
+ for name in names {
+ let bundled = root.join("resources").join("node_modules").join(name);
+ std::fs::create_dir_all(&bundled).unwrap();
+ std::fs::write(
+ bundled.join("package.json"),
+ format!(r#"{{"name":"{name}"}}"#),
+ )
+ .unwrap();
+ links.push(OfflineLink {
+ id: (*name).to_string(),
+ name: (*name).to_string(),
+ spec: bundled_dep_spec(&bundled),
+ bundled,
+ entry: profile.join("node_modules").join(name),
+ });
+ }
+ (root, profile, links)
+ }
+
+ fn manifest(profile: &Path) -> serde_json::Value {
+ serde_json::from_str(&std::fs::read_to_string(profile.join("package.json")).unwrap())
+ .unwrap()
+ }
+
+ #[test]
+ fn materialize_links_creates_entry_and_manifest_entries() {
+ let (root, profile, links) = fixture("create", &["dsh-tauri", "dsh-tauri-ui"]);
+
+ materialize_links(&profile, &links).unwrap();
+
+ for link in &links {
+ assert!(
+ internal_plugin_entry_is_ready(&link.entry),
+ "{} entry must be readable",
+ link.id
+ );
+ }
+ let manifest = manifest(&profile);
+ assert_eq!(manifest["dependencies"]["dsh-tauri"], links[0].spec);
+ assert_eq!(manifest["dependencies"]["dsh-tauri-ui"], links[1].spec);
+ // 用户既有依赖与 bundle 顺序必须原样保留,新 bundle 追加在末尾
+ assert_eq!(
+ manifest["dependencies"]["dshmarket"],
+ "github:dsh-market/dshmarket"
+ );
+ assert_eq!(
+ manifest["dsh"]["profile"]["bundles"],
+ serde_json::json!([
+ "@deepseek-ai/dsh-base",
+ "dshmarket",
+ "dsh-tauri",
+ "dsh-tauri-ui"
+ ])
+ );
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn materialize_links_replaces_broken_entry_and_is_idempotent() {
+ let (root, profile, links) = fixture("replace", &["dsh-tauri"]);
+ let entry = links[0].entry.clone();
+ std::fs::create_dir_all(&entry).unwrap();
+ std::fs::write(entry.join("partial"), "broken").unwrap();
+
+ materialize_links(&profile, &links).unwrap();
+ materialize_links(&profile, &links).unwrap();
+
+ assert!(internal_plugin_entry_is_ready(&entry));
+ assert!(!entry.join("partial").exists());
+ let manifest = manifest(&profile);
+ assert_eq!(
+ manifest["dsh"]["profile"]["bundles"],
+ serde_json::json!(["@deepseek-ai/dsh-base", "dshmarket", "dsh-tauri"])
+ );
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn materialize_links_creates_scoped_entry_parent() {
+ // 预设可显式声明 scoped 包名(installed_name 以 package 为准,见
+ // installed.rs::installed_name_resolves_package_else_id),入口落在
+ // node_modules/@scope/ 下:兜底必须自己补齐父目录。
+ let scope = "@baihejiangnan/dsh-session-context-menu";
+ let (root, profile, links) = fixture("scoped", &[scope]);
+
+ materialize_links(&profile, &links).unwrap();
+
+ assert!(internal_plugin_entry_is_ready(&links[0].entry));
+ let manifest = manifest(&profile);
+ assert_eq!(manifest["dependencies"][scope], links[0].spec);
+ assert_eq!(
+ manifest["dsh"]["profile"]["bundles"],
+ serde_json::json!([
+ "@deepseek-ai/dsh-base",
+ "dshmarket",
+ "@baihejiangnan/dsh-session-context-menu"
+ ])
+ );
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn materialize_links_reports_unresolvable_source() {
+ let (root, profile, links) = fixture("missing-source", &["dsh-tauri"]);
+ std::fs::remove_dir_all(&links[0].bundled).unwrap();
+
+ let error = materialize_links(&profile, &links).expect_err("missing source must fail");
+
+ assert!(
+ error.starts_with("INTERNAL_PLUGIN_OFFLINE_LINK_FAILED:"),
+ "{error}"
+ );
+ assert!(error.contains("dsh-tauri"), "{error}");
+ // 失败时不得写入清单:半成品清单会让下一次启动少一个 bundle
+ let manifest = manifest(&profile);
+ assert!(manifest["dependencies"].get("dsh-tauri").is_none());
+ let _ = std::fs::remove_dir_all(root);
+ }
+
+ #[test]
+ fn upsert_manifest_rejects_non_object_manifest() {
+ let links = vec![OfflineLink {
+ id: "dsh-tauri".to_string(),
+ name: "dsh-tauri".to_string(),
+ spec: "link:C:/x".to_string(),
+ bundled: PathBuf::from("C:/x"),
+ entry: PathBuf::from("C:/p/node_modules/dsh-tauri"),
+ }];
+ let mut manifest = serde_json::json!([]);
+
+ let error = upsert_manifest(&mut manifest, &links).expect_err("array manifest must fail");
+
+ assert!(
+ error.starts_with("INTERNAL_PLUGIN_OFFLINE_MANIFEST_INVALID:"),
+ "{error}"
+ );
+ }
+}
diff --git a/src-tauri/src/service/plugin/internal/mod.rs b/src-tauri/src/service/plugin/internal/mod.rs
index 44002298..65c5d0c9 100644
--- a/src-tauri/src/service/plugin/internal/mod.rs
+++ b/src-tauri/src/service/plugin/internal/mod.rs
@@ -11,7 +11,8 @@
//! 为什么放在启动而非安装流程:安装是用户主动行为,内置插件是应用自身的完整性
//! 要求——用户怎么卸载、何时卸载都不影响下次启动自动恢复,无需任何用户操作。
//!
-//! 模块划分:协调/飞行(本文件)与 profile 清单/入口文件操作([`manifest`])。
+//! 模块划分:协调/飞行(本文件)、profile 清单/入口文件操作([`manifest`])与
+//! pnpm 失败后的离线自建链接兜底([`materialize`])。
use std::collections::{HashMap, HashSet};
use std::future::Future;
@@ -22,7 +23,7 @@ use super::cancel::terminate_owned_install;
use super::install::install_internal;
use super::installed::{installed_name, profile_dir, ProfilePackageJson};
use super::preset::{bundled_dep_spec, bundled_plugin_dir, load_presets, PreinstallPluginInfo};
-use super::process::{new_process_owner, ProcessOwner};
+use super::process::{new_process_owner, PreinstallLogPayload, ProcessOwner, PREINSTALL_LOG_EVENT};
use crate::config;
use manifest::{
@@ -30,8 +31,10 @@ use manifest::{
internal_plugin_entry_is_ready, is_local_link_dep, remove_duplicate_bundle_entries_from_patch,
remove_internal_plugins_from_manifest, remove_stale_plugin_entry, write_profile_manifest,
};
+use materialize::{materialize_links, OfflineLink};
mod manifest;
+mod materialize;
/// 核对并强制安装缺失/路径不正确/被卸载的内置插件,在服务进程启动前调用。
///
@@ -721,12 +724,158 @@ async fn ensure_inner(
if let Err(e) = install_result {
// 即使 pnpm 失败也清掉旧 fallback,下一次重试必须从干净入口开始。
remove_legacy_profile_module_fallback_best_effort(&profile);
+ // pnpm 的 `link:` 安装路径在「建好目录链接后立刻回读 package.json」这一步
+ // 失败时(libuv UV_UNKNOWN / 退出码 -4094)可能是**环境性的恒定失败**
+ // (实时防护 / 云盘 / 重解析点过滤驱动),重试与重装都无法越过;此时改由
+ // 桌面端自建链接并补齐清单,让内置插件落盘、启动继续,而不是把应用永久
+ // 卡在 Plugin installation 阶段(见 [`materialize`])。
+ if is_link_materialization_failure(&e, &need) {
+ let _ = app_handle.emit(
+ PREINSTALL_LOG_EVENT,
+ PreinstallLogPayload {
+ line: "[harness] pnpm 无法回读新建的插件链接,改由应用直接建立链接…"
+ .to_string(),
+ },
+ );
+ match materialize_internal_links(app_handle, &profile, &need) {
+ Ok(()) => {
+ log::warn!(
+ "INTERNAL_PLUGIN_OFFLINE_LINK_RECOVERED: internal plugin links materialized after pnpm failure: {e}"
+ );
+ return Ok(());
+ }
+ Err(fallback) => {
+ log::error!("INTERNAL_PLUGIN_OFFLINE_LINK_FAILED: {fallback}");
+ return Err(format!(
+ "INTERNAL_PLUGIN_INSTALL_FAILED: {e}(离线自建链接兜底失败:{fallback})\n{}",
+ link_readback_hint(&profile)
+ ));
+ }
+ }
+ }
+ // 同一签名但诊断里读不到失败路径:无法确认失败的是内置插件入口,因此不做
+ // 兜底(免得把用户自己依赖的真实失败吞成成功),只给可操作的排除项提示。
+ if is_untraceable_link_readback_failure(&e) {
+ log::warn!("INTERNAL_PLUGIN_OFFLINE_LINK_UNATTRIBUTED: {e}");
+ return Err(format!(
+ "INTERNAL_PLUGIN_INSTALL_FAILED: {e}\n{}",
+ link_readback_hint(&profile)
+ ));
+ }
return Err(format!("INTERNAL_PLUGIN_INSTALL_FAILED: {e}"));
}
Ok(())
}
+/// 安全软件排除项提示:兜底失败与「同类但无法归因」时都要给,避免用户只看到裸
+/// pnpm 报错而无从下手。
+fn link_readback_hint(profile: &Path) -> String {
+ format!(
+ "提示:若本机安全软件(实时防护 / EDR / 云盘同步)拦截了档案目录的目录链接,\
+ 请把 {} 加入排除项后重试。",
+ profile.join("node_modules").display()
+ )
+}
+
+/// pnpm 诊断是否属于「`link:` 入口建成后回读 / 落盘失败」这一类签名(尚未归因)。
+///
+/// 注意退出码的措辞:`install` 落盘的是 `dsh plugin exited with code -4094`,
+/// 匹配 `code -4094` 而不是 `exit code -4094`。
+fn looks_like_link_readback_failure(error: &str) -> bool {
+ let lower = error.to_ascii_lowercase();
+ lower.contains("preinstall_failed")
+ && lower.contains("node_modules")
+ && (lower.contains("code -4094") || lower.contains("unknown error, open"))
+}
+
+/// 同类签名但诊断里读不到失败路径:无从确认失败的就是内置插件入口。
+fn is_untraceable_link_readback_failure(error: &str) -> bool {
+ failed_open_path(error).is_none() && looks_like_link_readback_failure(error)
+}
+
+/// 判定安装失败是否属于「pnpm 建好 `link:` 入口后无法回读 / 未落盘」且**可归因到
+/// 本轮待装的内置插件**——即离线自建链接能修、且修了不会掩盖别的失败的那一类。
+///
+/// - `PREINSTALL_SILENT_FAIL`:pnpm 以 0 退出却没落盘产物(源码存在时自建链接必然成功);
+/// - `PREINSTALL_FAILED`:诊断含 `node_modules` 与 `unknown error, open
+/// '<profile>/node_modules/...'`(或退出码 `-4094`,libuv `UV_UNKNOWN`),**且**
+/// 诊断里的失败路径确实落在本轮待装入口之下。
+///
+/// 网络 / spec / git 传输层 / 入口构建失败绝不命中:那些不是链接问题。同一签名也
+/// 可能来自用户自己的 `link:` 依赖(`pnpm add` 会一并解析档案依赖),路径不可归因
+/// 时一律不兜底——宁可漏修也不能把真实失败吞成「安装成功」,此时调用方改为给出
+/// 排除项提示(见 [`is_untraceable_link_readback_failure`] 与 [`link_readback_hint`])。
+fn is_link_materialization_failure(error: &str, need: &[(String, String, PathBuf)]) -> bool {
+ if error
+ .to_ascii_lowercase()
+ .contains("preinstall_silent_fail")
+ {
+ return true;
+ }
+ if !looks_like_link_readback_failure(error) {
+ return false;
+ }
+ match failed_open_path(error) {
+ Some(path) => need
+ .iter()
+ .any(|(_, _, entry)| path_lives_under(&path, entry)),
+ None => false,
+ }
+}
+
+/// 取 pnpm 诊断里 `unknown error, open '<path>'` 的路径(统一分隔符、去尾斜杠)。
+fn failed_open_path(error: &str) -> Option<String> {
+ const MARKER: &str = "unknown error, open ";
+ // 大小写折叠只改 ASCII 字节,偏移量在两份字符串上一致,因此仍返回原始大小写。
+ let lower = error.to_ascii_lowercase();
+ let start = lower.find(MARKER)? + MARKER.len();
+ let rest = error.get(start..)?.trim_start();
+ let rest = rest.strip_prefix('\'')?;
+ let end = rest.find('\'')?;
+ Some(normalize_link_path(&rest[..end]))
+}
+
+fn normalize_link_path(path: &str) -> String {
+ path.replace('\\', "/").trim_end_matches('/').to_string()
+}
+
+/// 路径比较统一折叠大小写:Windows 不区分大小写,宁可漏兜底也不误吞其它依赖的失败。
+fn path_lives_under(path: &str, entry: &Path) -> bool {
+ let entry = normalize_link_path(&entry.to_string_lossy()).to_ascii_lowercase();
+ let path = path.to_ascii_lowercase();
+ path == entry || path.starts_with(&format!("{entry}/"))
+}
+
+/// 用桌面端的目录链接实现落盘本轮待修复的内置插件入口(离线、不依赖 node/pnpm)。
+fn materialize_internal_links(
+ app_handle: &AppHandle,
+ profile: &Path,
+ need: &[(String, String, PathBuf)],
+) -> Result<(), String> {
+ let mut links = Vec::with_capacity(need.len());
+ for (id, name, entry) in need {
+ let bundled = bundled_plugin_dir(app_handle, id)
+ .ok_or_else(|| format!("INTERNAL_PLUGIN_BUNDLE_MISSING: {id}"))?;
+ links.push(OfflineLink {
+ id: id.clone(),
+ name: name.clone(),
+ spec: bundled_dep_spec(&bundled),
+ bundled,
+ entry: entry.clone(),
+ });
+ }
+ materialize_links(profile, &links)?;
+ // pnpm 失败路径已为这些 id 记过安装错误;兜底成功后必须清掉,否则插件面板
+ // 会继续显示「安装失败」而实际上插件已就绪(与 verify 的成功路径一致)。
+ for (id, _, _) in need {
+ if let Err(e) = super::errors::clear(app_handle, id) {
+ log::warn!("failed to clear plugin error for {id} after offline link: {e}");
+ }
+ }
+ Ok(())
+}
+
/// best-effort 包装:旧版 profile-local fallback 清理失败只记告警,绝不阻断本轮的
/// 插件核对与重装(issue #466)。返回 `Err` 的原函数保留完整错误细节供日志定位。
fn remove_legacy_profile_module_fallback_best_effort(profile: &Path) {
@@ -810,9 +959,109 @@ fn is_legacy_profile_fallback_target(target: &Path) -> bool {
mod tests {
use super::*;
+ /// 构造本轮待装列表 `(id, 包名, 入口)`:入口与 `ensure_inner` 一致地落在
+ /// `<profile>/node_modules/<包名>`,用报告里的真实 profile 路径。
+ fn need_entries(names: &[&str]) -> Vec<(String, String, PathBuf)> {
+ let profile = Path::new("C:\\Users\\w00012491\\.dsh\\profiles\\tauri");
+ names
+ .iter()
+ .map(|name| {
+ (
+ (*name).to_string(),
+ (*name).to_string(),
+ profile.join("node_modules").join(name),
+ )
+ })
+ .collect()
+ }
+
+ /// issue #264 的**恒定**版本:pnpm 建好 `link:` 目录链接后回读 package.json
+ /// 失败(libuv UV_UNKNOWN / 退出码 -4094),必须命中离线自建链接兜底。
+ #[test]
+ fn link_materialization_failure_detects_uv_unknown_readback() {
+ let error = "PREINSTALL_FAILED: dsh plugin exited with code -4094: UNKNOWN UNKNOWN: \
+ unknown error, open 'C:\\Users\\w00012491\\.dsh\\profiles\\tauri\\node_modules\\\
+ dsh-tauri-panel-scheduler\\package.json'";
+ let need = need_entries(&["dsh-tauri-panel-scheduler"]);
+ assert!(is_link_materialization_failure(error, &need));
+ // pnpm / Node 的措辞随版本变化,判定大小写不敏感
+ assert!(is_link_materialization_failure(
+ &error.to_ascii_lowercase(),
+ &need
+ ));
+ }
+
+ #[test]
+ fn link_materialization_failure_detects_silent_install() {
+ assert!(is_link_materialization_failure(
+ "PREINSTALL_SILENT_FAIL: dsh plugin exited with code 0, but no install artifact was \
+ created for [dsh-tauri]. Expected package manifests: [...]",
+ &need_entries(&["dsh-tauri"])
+ ));
+ }
+
+ /// 同一签名也可能来自用户自己的 `link:` 依赖(`pnpm add` 会一并解析项目依赖):
+ /// 失败路径不属于本轮内置插件时绝不能兜底,否则真实失败被吞成「安装成功」。
+ #[test]
+ fn link_materialization_failure_rejects_foreign_dependency_path() {
+ let error = "PREINSTALL_FAILED: dsh plugin exited with code -4094: UNKNOWN UNKNOWN: \
+ unknown error, open 'C:\\Users\\w00012491\\.dsh\\profiles\\tauri\\node_modules\\\
+ someone-else-plugin\\package.json'";
+ assert!(!is_link_materialization_failure(
+ error,
+ &need_entries(&["dsh-tauri-panel-scheduler"])
+ ));
+ }
+
+ /// 同类签名但诊断里没有可解析的失败路径:不能归因到内置插件入口,因此既不
+ /// 兜底(免得掩盖用户依赖的失败)也不能只丢裸错误,要走「只给排除项提示」。
+ #[test]
+ fn link_materialization_failure_rejects_unattributed_diagnostic() {
+ let error = "PREINSTALL_FAILED: dsh plugin exited with code -4094: UNKNOWN: cannot \
+ materialize node_modules entry";
+ let need = need_entries(&["dsh-tauri-panel-scheduler"]);
+
+ assert!(!is_link_materialization_failure(error, &need));
+ assert!(is_untraceable_link_readback_failure(error));
+ // 能解析出路径后就不再是「无法归因」,只是路径不属于本轮待装入口
+ assert!(!is_untraceable_link_readback_failure(
+ "PREINSTALL_FAILED: dsh plugin exited with code -4094: UNKNOWN: unknown error, open \
+ 'C:\\Users\\w00012491\\.dsh\\profiles\\tauri\\node_modules\\someone-else\\package.json'"
+ ));
+ }
+
+ #[test]
+ fn link_materialization_failure_rejects_unrelated_failures() {
+ let need = need_entries(&["dsh-tauri"]);
+ assert!(!is_link_materialization_failure(
+ "PREINSTALL_FAILED: dsh plugin exited with code 1: ERR_PNPM_SPEC_NOT_SUPPORTED",
+ &need
+ ));
+ assert!(!is_link_materialization_failure(
+ "NETWORK_ERROR: plugin registry request failed; check network or proxy settings and retry.",
+ &need
+ ));
+ assert!(!is_link_materialization_failure(
+ "PREINSTALL_ENTRY_FAILED:\ndsh-tauri: PLUGIN_ENTRY_MISSING",
+ &need
+ ));
+ // 含 -4094 但诊断里没有 profile 链接路径:不是本兜底能解的那一类
+ assert!(!is_link_materialization_failure(
+ "PREINSTALL_FAILED: dsh plugin exited with code -4094: some unrelated output",
+ &need
+ ));
+ assert!(!is_untraceable_link_readback_failure(
+ "PREINSTALL_FAILED: dsh plugin exited with code -4094: some unrelated output"
+ ));
+ }
+
#[test]
fn legacy_fallback_target_detection_is_path_component_aware() {
- let base = Path::new("home").join("test").join(".dsh").join("profiles").join("web");
+ let base = Path::new("home")
+ .join("test")
+ .join(".dsh")
+ .join("profiles")
+ .join("web");
assert!(is_legacy_profile_fallback_target(
&base
.join(".dsh-module-fallback")
@@ -823,9 +1072,7 @@ mod tests {
&base.join("node_modules").join("anymatch"),
));
assert!(!is_legacy_profile_fallback_target(
- &base
- .join(".dsh-module-fallback-old")
- .join("anymatch"),
+ &base.join(".dsh-module-fallback-old").join("anymatch"),
));
}