Skip to content

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

fix(core): 原生模块 ABI 不匹配时改用捆绑运行时并给出精确诊断

hairyff8fdcfa9aeb6
diff --git a/docs/AGENTS.desktop.md b/docs/AGENTS.desktop.md
index a08d57f1..ba6fa958 100644
--- a/docs/AGENTS.desktop.md
+++ b/docs/AGENTS.desktop.md
@@ -236,6 +236,7 @@ export function FooComponent(props: FooProps) {
- `dsh` CLI is a Node script (`dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js`); CLI integration is **shim + PATH**. pnpm is also JS (`dependencies/pnpm/bin/pnpm.cjs`, npm tarball).
- AppData layout(核心共用):`runtime/node.exe`、`dependencies/dsh/`、`dependencies/pnpm/`、`.store.dat` / `.store.dev.dat`(后者为 debug);服务日志 `logs/dsh-web.log`(debug 为 `logs/dsh-web.dev.log`);`$DSH_HOME` 在用户主目录(release `~/.dsh`,debug `~/.dsh.dev`)。
- Service args: `node bin.js --profile web --host 127.0.0.1 --port <setting.port>`; `cli::ensure` runs after install.
+- 原生模块 ABI(issue #441):预打包核心的原生模块(`fs-ext` 等 node-gyp 包)在 pkg 构建期编译,ABI 只与构建期 Node 大版本一致,而本地 Node 只按 semver 挑选。`service/core/runtime.rs::prepare_active_runtime` 在 spawn 前用 `NATIVE_PROBE_SCRIPT` 探测(require 核心里的原生包,`NODE_MODULE_VERSION` 不匹配即 ABI 失败):先补 sharp/koffi 平台包,再改用与核心对齐的捆绑运行时(`config::set_prefer_bundled_node_runtime`,`get_node_binary_path`/`get_active_node_version`/`Nodejs::check_installed` 均受其影响,`launch.rs` 会在 prepare 后重新解析 node 路径),再 `npm rebuild`(用所选运行时自带的 npm),最后返回 `CORE_NATIVE_ABI_MISMATCH:` 诊断。CLI shim 的 node 选择仍是 semver-only。
## Summary
diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rs
index e4da8a6d..2da3a035 100644
--- a/src-tauri/src/config/runtime.rs
+++ b/src-tauri/src/config/runtime.rs
@@ -2,6 +2,7 @@ use serde::Serialize;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
use tauri::{AppHandle, Manager, Runtime};
use super::constants::*;
@@ -197,15 +198,28 @@ pub fn get_local_node_path() -> Option<PathBuf> {
is_supported_node_version(&version).then_some(node)
}
-/// Node.js 二进制路径
+/// 原生模块 ABI 探测结论:本地 Node 无法加载活动核心的原生模块时,本进程内
+/// 强制改用捆绑运行时。
///
-/// 优先级:本地版本兼容的 Node.js 环境 > 已安装的捆绑运行时
-pub fn get_node_binary_path(app_handle: &tauri::AppHandle) -> PathBuf {
- if let Some(local_node) = get_local_node_path() {
- log::debug!("Using local Node.js: {}", local_node.display());
- return local_node;
- }
+/// 由 `service::core::runtime::prepare_active_runtime` 在拉起 dsh 之前探测并设置:
+/// 原生模块的 ABI 在构建期确定(预打包核心由 pkg 构建期的 Node 决定),而本地 Node
+/// 只按 semver 挑选,可能与其不匹配(issue #441:Node 25 的 ABI 141 加载 ABI 137 的
+/// `fs_ext.node`)。置位后所有 node 解析(服务进程、`DSH_NODE` 注入、运行环境展示)
+/// 统一走捆绑运行时,避免各处各选一个运行时。
+static PREFER_BUNDLED_NODE_RUNTIME: AtomicBool = AtomicBool::new(false);
+
+/// 是否因原生模块 ABI 不匹配而强制使用捆绑运行时
+pub fn prefer_bundled_node_runtime() -> bool {
+ PREFER_BUNDLED_NODE_RUNTIME.load(Ordering::Relaxed)
+}
+
+/// 设置捆绑运行时偏好(仅由启动前的原生模块探测调用)
+pub fn set_prefer_bundled_node_runtime(prefer: bool) {
+ PREFER_BUNDLED_NODE_RUNTIME.store(prefer, Ordering::Relaxed);
+}
+/// 已安装的捆绑运行时 node 二进制(未安装时返回 None)
+pub fn bundled_node_binary(app_handle: &tauri::AppHandle) -> Option<PathBuf> {
let runtime_dir = get_node_install_path(app_handle);
// 使用 cfg 宏在编译时确定文件名
let (rel_path, bin_name) = if cfg!(windows) {
@@ -215,11 +229,45 @@ pub fn get_node_binary_path(app_handle: &tauri::AppHandle) -> PathBuf {
};
let direct_path = runtime_dir.join(rel_path).join(bin_name);
if direct_path.exists() {
- direct_path
+ Some(direct_path)
} else {
// 只有在直接路径不存在时才进行开销较大的递归搜索
- search_node_binary(&runtime_dir, bin_name).unwrap_or(direct_path)
+ search_node_binary(&runtime_dir, bin_name)
+ }
+}
+
+/// Node.js 二进制路径
+///
+/// 优先级:ABI 探测要求捆绑运行时(原生模块不匹配时的兜底)> 本地版本兼容的
+/// Node.js 环境 > 已安装的捆绑运行时
+pub fn get_node_binary_path(app_handle: &tauri::AppHandle) -> PathBuf {
+ let runtime_dir = get_node_install_path(app_handle);
+ let (rel_path, bin_name) = if cfg!(windows) {
+ ("", "node.exe")
+ } else {
+ ("bin", "node")
+ };
+ let bundled = bundled_node_binary(app_handle);
+
+ if prefer_bundled_node_runtime() {
+ if let Some(bundled) = bundled.clone() {
+ log::debug!(
+ "Using bundled Node.js runtime (native ABI override): {}",
+ bundled.display()
+ );
+ return bundled;
+ }
+ log::warn!(
+ "Bundled Node.js runtime is required by the native module ABI check but is not installed"
+ );
+ }
+
+ if let Some(local_node) = get_local_node_path() {
+ log::debug!("Using local Node.js: {}", local_node.display());
+ return local_node;
}
+
+ bundled.unwrap_or_else(|| runtime_dir.join(rel_path).join(bin_name))
}
pub fn get_node_install_path(app_handle: &tauri::AppHandle) -> PathBuf {
@@ -451,14 +499,23 @@ pub fn get_bundled_node_version() -> String {
/// 当前实际使用的 Node.js 版本号(本地 Node 优先,其次捆绑运行时)
pub fn get_active_node_version() -> String {
- if let Some(local_node) = get_local_node_path() {
- if let Some(version) = get_node_version_of(&local_node) {
- return version;
+ // ABI 探测要求捆绑运行时时不能再展示本地 node 版本:界面显示必须与实际
+ // 拉起的服务进程一致(否则用户看到的版本与日志里的运行时对不上)。
+ if !prefer_bundled_node_runtime() {
+ if let Some(local_node) = get_local_node_path() {
+ if let Some(version) = get_node_version_of(&local_node) {
+ return version;
+ }
}
}
get_bundled_node_version()
}
+/// 读取任意 node 二进制的版本号(诊断信息用,例如 "v25.8.2")
+pub fn get_node_version_of_path(node: &Path) -> Option<String> {
+ get_node_version_of(node)
+}
+
fn parse_node_version(output: &str) -> Option<(u64, u64, u64)> {
let version = output.trim().trim_start_matches('v');
let mut parts = version.split('.');
diff --git a/src-tauri/src/service/core/runtime.rs b/src-tauri/src/service/core/runtime.rs
index d70db38d..1a3c26ca 100644
--- a/src-tauri/src/service/core/runtime.rs
+++ b/src-tauri/src/service/core/runtime.rs
@@ -1,15 +1,22 @@
-//! 活动预打包核心的运行时自愈:补齐插件入口并检查原生可选依赖。
+//! 活动预打包核心的运行时自愈:补齐插件入口并检查原生依赖(含 ABI 兼容性)。
//!
//! dsh 的 loader 以核心安装目录作为裸包解析根,而 profile 中的插件实际位于
//! `$DSH_HOME/profiles/<profile>/node_modules`,应用内置插件则位于安装包资源目录。
//! 核心版本切换只移动 `dependencies/dsh`,不会自动重建这些入口,因此每次启动都要
//! 在启动 dsh 前按当前核心重新建立安全的目录链接。用户自行安装的 local 核心不归
//! 桌面端管理,明确跳过本模块。
+//!
+//! 除了入口链接,启动前还要确认核心的原生模块能真正被当前 Node 运行时加载:
+//! 预打包核心的原生模块(`fs-ext` 这类 node-gyp 包)在 pkg 构建期编译,ABI 只与
+//! 构建期 Node 大版本一致;而本地 Node 只按 semver 挑选(`is_supported_node_version`),
+//! 因此 Node 25(ABI 141)会加载 ABI 137 的 `fs_ext.node` 失败,dsh 在插件树加载
+//! 阶段退出、前端只看到 `HARNESS_NOT_OWNED`(issue #441)。这里在 spawn 之前探测,
+//! 先尝试与核心对齐的捆绑运行时,再尝试重建,最后给出可读的 ABI 诊断。
use std::collections::{HashMap, HashSet};
use std::ffi::OsString;
use std::io::Read;
-use std::path::Path;
+use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
@@ -18,8 +25,80 @@ use tauri::AppHandle;
use super::source::CoreSource;
const NATIVE_REPAIR_TIMEOUT: Duration = Duration::from_secs(120);
+/// 原生模块重建(node-gyp 编译)可能远超安装耗时,单独放宽上限
+const NATIVE_REBUILD_TIMEOUT: Duration = Duration::from_secs(300);
+/// 探测脚本的挂起保护:脚本本身只做 require 与目录扫描
+const NATIVE_PROBE_TIMEOUT: Duration = Duration::from_secs(60);
const NODE_PROBE_SCRIPT: &str = "process.stdout.write(process.platform + ':' + process.arch)";
+/// 旧版平台依赖探测:探测脚本结论不可信时的回退检查(sharp/koffi 均为 NAPI 包)
const NATIVE_IMPORT_SCRIPT: &str = "await import('sharp'); await import('koffi')";
+/// 探测脚本的结果标记行前缀(脚本 stdout 里可能混有原生模块自身的输出)
+const NATIVE_PROBE_MARKER: &str = "__DSH_NATIVE_PROBE__";
+/// 原生模块探测脚本:列出无法被当前运行时加载的原生模块。
+///
+/// 1. `sharp` / `koffi`:NAPI 可选依赖,缺目标平台包时动态 import 失败(原有修复路径);
+/// 2. 原生包:带 `binding.gyp` 或自带原生产物目录(`build/Release`、`build/Debug`、
+/// `prebuilds`、`prebuilt`)的包,逐个 require —— 与 dsh 自身的加载方式一致,
+/// 加载失败即为 dsh 启动时同样的失败(fs-ext 这类 node-gyp 包落在 build/Release)。
+/// 崩溃/异常退出时不会有标记行,Rust 侧按"结论未知"处理,不阻断启动。
+const NATIVE_PROBE_SCRIPT: &str = r#"
+const { createRequire } = await import('node:module');
+const { existsSync, readdirSync } = await import('node:fs');
+const { join } = await import('node:path');
+const root = process.cwd();
+const loader = createRequire(join(root, 'dsh-native-probe.cjs'));
+const failures = [];
+const describe = (error) => String((error && error.message) || error);
+const isAbi = (text) => text.includes('NODE_MODULE_VERSION');
+const attempt = (name, target) => {
+ try { loader(target); return null; } catch (error) { return { name, message: describe(error) }; }
+};
+for (const name of ['sharp', 'koffi']) {
+ const failure = attempt(name, name);
+ if (failure) failures.push({ kind: 'import', name, message: failure.message, abi: isAbi(failure.message) });
+}
+try {
+ const nodeModules = join(root, 'node_modules');
+ const outputs = ['build/Release', 'build/Debug', 'prebuilds', 'prebuilt'];
+ const candidates = [];
+ const collect = (dir, name) => {
+ if (existsSync(join(dir, 'binding.gyp')) || outputs.some((relative) => existsSync(join(dir, relative)))) {
+ candidates.push({ dir, name });
+ }
+ };
+ if (existsSync(nodeModules)) {
+ for (const entry of readdirSync(nodeModules, { withFileTypes: true })) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === '.bin' || entry.name === '.pnpm') continue;
+ if (entry.name.startsWith('@')) {
+ const scope = join(nodeModules, entry.name);
+ for (const inner of readdirSync(scope, { withFileTypes: true })) {
+ if (inner.isDirectory()) collect(join(scope, inner.name), entry.name + '/' + inner.name);
+ }
+ continue;
+ }
+ collect(join(nodeModules, entry.name), entry.name);
+ }
+ }
+ for (const pkg of candidates) {
+ let failure = attempt(pkg.name, pkg.name);
+ if (failure) {
+ // 包入口不可 require(纯 ESM / 无 main)时退回直接加载 node-gyp 产物;
+ // 只用来"洗清"失败,绝不覆盖包入口给出的错误信息(后者更完整,且
+ // 直接加载 .node 可能报成"不是有效的 Win32 应用程序"而掩盖 ABI 差异)。
+ const release = join(pkg.dir, 'build', 'Release');
+ if (existsSync(release)) {
+ const addon = readdirSync(release).find((file) => file.endsWith('.node'));
+ if (addon && attempt(pkg.name, join(release, addon)) === null) failure = null;
+ }
+ }
+ if (failure) failures.push({ kind: 'addon', name: pkg.name, message: failure.message, abi: isAbi(failure.message) });
+ }
+} catch (error) {
+ process.stderr.write('native addon scan failed: ' + describe(error) + '\n');
+}
+process.stdout.write('__DSH_NATIVE_PROBE__' + JSON.stringify(failures) + '\n');
+"#;
#[derive(Debug, Clone, PartialEq, Eq)]
struct NodeTarget {
@@ -27,7 +106,72 @@ struct NodeTarget {
arch: String,
}
-/// 在启动预打包核心前修复其插件入口并验证 sharp/koffi 原生依赖。
+/// 单个原生模块的加载失败记录(由探测脚本以 JSON 输出)
+#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
+struct NativeProbeFailure {
+ /// `import`:sharp/koffi 可选依赖;`addon`:带 binding.gyp 的原生包
+ #[serde(default)]
+ kind: String,
+ /// 包名(作用域包为 `@scope/name`)
+ #[serde(default)]
+ name: String,
+ #[serde(default)]
+ message: String,
+ /// 是否为 Node ABI 不匹配(错误文本含 NODE_MODULE_VERSION)
+ #[serde(default)]
+ abi: bool,
+}
+
+impl NativeProbeFailure {
+ fn is_platform_import(&self) -> bool {
+ self.kind == "import"
+ }
+}
+
+/// 原生模块探测结果
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum NativeProbe {
+ /// 全部原生模块均可被当前运行时加载
+ Ready,
+ /// 探测完成,存在加载失败的模块
+ Failed(Vec<NativeProbeFailure>),
+ /// 探测无法得出结论(脚本崩溃/超时/输出不可解析):不阻断启动,交由服务日志兜底
+ Unknown(String),
+}
+
+impl NativeProbe {
+ fn is_ready(&self) -> bool {
+ matches!(self, Self::Ready)
+ }
+
+ fn failures(&self) -> &[NativeProbeFailure] {
+ match self {
+ Self::Failed(failures) => failures,
+ _ => &[],
+ }
+ }
+
+ fn has_abi_mismatch(&self) -> bool {
+ self.failures().iter().any(|failure| failure.abi)
+ }
+
+ fn has_platform_import_failure(&self) -> bool {
+ self.failures().iter().any(NativeProbeFailure::is_platform_import)
+ }
+
+ /// ABI 不匹配的包名(去重,保持探测顺序)
+ fn abi_packages(&self) -> Vec<String> {
+ let mut names: Vec<String> = Vec::new();
+ for failure in self.failures().iter().filter(|failure| failure.abi) {
+ if !names.contains(&failure.name) {
+ names.push(failure.name.clone());
+ }
+ }
+ names
+ }
+}
+
+/// 在启动预打包核心前修复其插件入口并验证原生依赖(含 Node ABI 兼容性)。
///
/// 该函数是幂等的:已有正确链接和可加载的原生模块不会触发写入或联网。原生包
/// 缺失时只按核心清单中的 optionalDependencies 动态构造安装参数,避免把某一台
@@ -57,7 +201,8 @@ struct NodeTarget {
link_required_plugins(app_handle, &core_root)?;
let target = detect_node_target(&node, &core_root).await?;
- if native_imports_ready(&node, &core_root).await {
+ let mut probe = probe_native_modules(&node, &core_root).await;
+ if probe.is_ready() {
log::debug!(
"Bundled core native dependencies are ready for {}:{}",
target.platform,
@@ -65,33 +210,93 @@ struct NodeTarget {
);
return Ok(());
}
+ if let NativeProbe::Unknown(reason) = probe.clone() {
+ // 探测脚本自身不可信(崩溃/超时/输出不可解析)时不能直接放行:先退回原有的
+ // sharp/koffi 探测,仍失败则按平台包缺失处理,避免漏掉平台包修复。
+ log::warn!("CORE_NATIVE_PROBE_UNKNOWN: {reason}");
+ if native_imports_ready(&node, &core_root).await {
+ return Ok(());
+ }
+ probe = NativeProbe::Failed(vec![NativeProbeFailure {
+ kind: "import".into(),
+ name: "sharp/koffi".into(),
+ message: reason,
+ abi: false,
+ }]);
+ }
- let packages = native_package_plan(&core_root, &target);
- if packages.is_empty() {
- return Err(format!(
- "CORE_NATIVE_DEPENDENCY_UNRESOLVED: no optional package version matches {}:{} in {}",
+ // 1) 平台可选依赖(sharp/koffi)缺失:沿用按核心清单安装目标平台包的修复路径。
+ // 先做这一步:它只补平台/架构包、与运行时无关,补齐后再判断 ABI 才有意义。
+ if probe.has_platform_import_failure() {
+ let packages = native_package_plan(&core_root, &target);
+ if packages.is_empty() {
+ return Err(format!(
+ "CORE_NATIVE_DEPENDENCY_UNRESOLVED: no optional package version matches {}:{} in {}",
+ target.platform,
+ target.arch,
+ core_root.display()
+ ));
+ }
+ log::warn!(
+ "CORE_NATIVE_DEPENDENCY_REPAIR: importing sharp/koffi failed for {}:{}, installing {:?}",
target.platform,
target.arch,
- core_root.display()
- ));
+ packages
+ );
+ install_native_packages(&core_root, &target, &packages).await?;
+ let Some(next) = reprobe_after_repair(&node, &core_root).await else {
+ return Ok(());
+ };
+ probe = next;
}
- log::warn!(
- "CORE_NATIVE_DEPENDENCY_REPAIR: importing sharp/koffi failed for {}:{}, installing {:?}",
- target.platform,
- target.arch,
- packages
- );
- install_native_packages(&core_root, &target, &packages).await?;
- if !native_imports_ready(&node, &core_root).await {
- return Err(format!(
- "CORE_NATIVE_DEPENDENCY_REPAIR_FAILED: sharp/koffi still cannot load for {}:{} in {}",
- target.platform,
- target.arch,
+ // 2) ABI 不匹配(issue #441):本地 node 与核心原生模块的构建 ABI 不同。核心由
+ // pkg 在固定 Node 大版本下构建,捆绑运行时与之对齐,因此先验证捆绑运行时;
+ // 探测通过则本进程内固定使用它(config::set_prefer_bundled_node_runtime)。
+ if probe.has_abi_mismatch() && !is_bundled_runtime_node(&node, app_handle) {
+ if let Some(bundled) = crate::config::bundled_node_binary(app_handle) {
+ if probe_native_modules(&bundled, &core_root).await.is_ready() {
+ log::warn!(
+ "CORE_NATIVE_ABI_MISMATCH: {:?} cannot load under {}; switching to the bundled Node.js runtime {}",
+ probe.abi_packages(),
+ node.display(),
+ bundled.display()
+ );
+ crate::config::set_prefer_bundled_node_runtime(true);
+ return Ok(());
+ }
+ }
+ }
+
+ // 3) ABI 不匹配且捆绑运行时也救不了(核心由更高 ABI 的 Node 构建):用所选运行时
+ // 自带的 npm 重建这些包,装了 C++ 工具链的环境可以自愈。
+ let abi_packages = probe.abi_packages();
+ if !abi_packages.is_empty() {
+ log::warn!(
+ "CORE_NATIVE_ABI_MISMATCH: rebuilding {:?} for {} in {}",
+ abi_packages,
+ node.display(),
core_root.display()
- ));
+ );
+ match rebuild_native_packages(&core_root, &node, &abi_packages).await {
+ Ok(()) => {
+ let Some(next) = reprobe_after_repair(&node, &core_root).await else {
+ log::info!(
+ "CORE_NATIVE_REBUILD: rebuilt {:?} for {}",
+ abi_packages,
+ node.display()
+ );
+ return Ok(());
+ };
+ probe = next;
+ }
+ Err(error) => log::warn!("CORE_NATIVE_REBUILD_FAILED: {error}"),
+ }
}
- Ok(())
+
+ // 4) 仍然无法加载:给出精确诊断(模块名 + ABI 差异),而不是让 dsh 在插件树加载
+ // 阶段崩溃、前端只显示 HARNESS_NOT_OWNED。
+ Err(native_failure_diagnostic(probe.failures(), &node, &core_root))
}
/// 从活动 profile 与应用内置清单收集需要在核心根下解析的包,并逐个建立入口。
@@ -498,17 +703,196 @@ async fn detect_node_target(node: &Path, core_root: &Path) -> Result<NodeTarget,
Ok(NodeTarget { platform: platform.to_string(), arch: arch.to_string() })
}
+/// 用指定运行时执行原生模块探测脚本,返回结构化结论。
+async fn probe_native_modules(node: &Path, core_root: &Path) -> NativeProbe {
+ let node = node.to_path_buf();
+ let core_root = core_root.to_path_buf();
+ let result = tokio::task::spawn_blocking(move || {
+ let program = node.as_os_str().to_os_string();
+ let args = vec![
+ OsString::from("--input-type=module"),
+ OsString::from("-e"),
+ OsString::from(NATIVE_PROBE_SCRIPT),
+ ];
+ run_process_with_timeout(&program, &args, &core_root, NATIVE_PROBE_TIMEOUT, "native probe")
+ })
+ .await;
+
+ match result {
+ Ok(Ok(output)) if output.status.success() => {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ match parse_native_probe_failures(&stdout) {
+ Some(failures) if failures.is_empty() => NativeProbe::Ready,
+ Some(failures) => NativeProbe::Failed(failures),
+ None => NativeProbe::Unknown(format!(
+ "probe output is not parseable: {}",
+ command_output_tail(&output)
+ )),
+ }
+ }
+ Ok(Ok(output)) => NativeProbe::Unknown(format!(
+ "probe exited with {}: {}",
+ output.status,
+ command_output_tail(&output)
+ )),
+ Ok(Err(error)) => NativeProbe::Unknown(error),
+ Err(error) => NativeProbe::Unknown(error.to_string()),
+ }
+}
+
+/// 修复后的重新探测:Ready 或结论未知都放行(未知只告警,不因探测自身的问题阻断
+/// 启动)。返回 Some 表示仍有明确的加载失败,需要继续处理。
+async fn reprobe_after_repair(node: &Path, core_root: &Path) -> Option<NativeProbe> {
+ match probe_native_modules(node, core_root).await {
+ NativeProbe::Ready => None,
+ NativeProbe::Unknown(reason) => {
+ log::warn!("CORE_NATIVE_PROBE_UNKNOWN: {reason}");
+ None
+ }
+ probe @ NativeProbe::Failed(_) => Some(probe),
+ }
+}
+
+/// 旧版平台依赖探测(sharp/koffi 动态 import):仅用于探测脚本结论不可信时兜底
async fn native_imports_ready(node: &Path, core_root: &Path) -> bool {
let node = node.to_path_buf();
let core_root = core_root.to_path_buf();
tokio::task::spawn_blocking(move || {
- run_command(&node, &["--input-type=module".into(), "-e".into(), NATIVE_IMPORT_SCRIPT.into()], &core_root)
- .is_ok_and(|output| output.status.success())
+ run_command(
+ &node,
+ &[
+ "--input-type=module".into(),
+ "-e".into(),
+ NATIVE_IMPORT_SCRIPT.into(),
+ ],
+ &core_root,
+ )
+ .is_ok_and(|output| output.status.success())
})
.await
.unwrap_or(false)
}
+/// 解析探测脚本的标记行;缺失或不可解析时返回 None(视为结论未知)
+fn parse_native_probe_failures(stdout: &str) -> Option<Vec<NativeProbeFailure>> {
+ let line = stdout
+ .lines()
+ .rev()
+ .find(|line| line.starts_with(NATIVE_PROBE_MARKER))?;
+ let json = line.trim_start_matches(NATIVE_PROBE_MARKER).trim();
+ serde_json::from_str::<Vec<NativeProbeFailure>>(json).ok()
+}
+
+/// 当前 node 是否就是捆绑运行时(用于避免重复尝试同一个运行时)
+fn is_bundled_runtime_node(node: &Path, app_handle: &AppHandle) -> bool {
+ crate::config::bundled_node_binary(app_handle).is_some_and(|bundled| {
+ bundled == node
+ || bundled
+ .to_string_lossy()
+ .eq_ignore_ascii_case(&node.to_string_lossy())
+ })
+}
+
+/// 生成原生模块加载失败的诊断信息:ABI 不匹配单独给出可读结论,其余按原样列出。
+fn native_failure_diagnostic(failures: &[NativeProbeFailure], node: &Path, core_root: &Path) -> String {
+ if failures.is_empty() {
+ return format!(
+ "CORE_NATIVE_DEPENDENCY_REPAIR_FAILED: native modules could not be verified in {}",
+ core_root.display()
+ );
+ }
+ let abi_failures: Vec<&NativeProbeFailure> =
+ failures.iter().filter(|failure| failure.abi).collect();
+ if !abi_failures.is_empty() {
+ let names = abi_failures
+ .iter()
+ .map(|failure| failure.name.as_str())
+ .collect::<Vec<_>>()
+ .join(", ");
+ let version = crate::config::get_node_version_of_path(node)
+ .unwrap_or_else(|| node.display().to_string());
+ return format!(
+ "CORE_NATIVE_ABI_MISMATCH: {names} cannot load under Node.js {version}: {detail} The Harness core's native modules were built for a different Node.js ABI; install the Node.js version the core was built with, or reinstall/upgrade the Harness core so it matches the bundled Node.js runtime. (core: {core})",
+ names = names,
+ version = version,
+ detail = collapse_whitespace(&abi_failures[0].message),
+ core = core_root.display()
+ );
+ }
+ format!(
+ "CORE_NATIVE_DEPENDENCY_REPAIR_FAILED: native modules still cannot load in {}: {}",
+ core_root.display(),
+ failures
+ .iter()
+ .map(|failure| format!("{}: {}", failure.name, collapse_whitespace(&failure.message)))
+ .collect::<Vec<_>>()
+ .join("; ")
+ )
+}
+
+/// 折叠多行错误文本为单行,便于在界面提示里展示(Node 的 ABI 报错是跨行的)
+fn collapse_whitespace(value: &str) -> String {
+ value.split_whitespace().collect::<Vec<_>>().join(" ")
+}
+
+/// 用所选运行时自带的 npm 重建 ABI 不匹配的原生包。
+///
+/// 必须用与运行时配套的 npm:PATH 里的 npm 可能属于另一个 Node 大版本,用它编译
+/// 只会得到另一个不匹配的 ABI。捆绑运行时目录自带 npm-cli.js,优先直接以该 node
+/// 运行;找不到时退回 PATH 中的 npm(本地 node 安装通常自带)。
+async fn rebuild_native_packages(
+ core_root: &Path,
+ node: &Path,
+ packages: &[String],
+) -> Result<(), String> {
+ let core_root = core_root.to_path_buf();
+ let node = node.to_path_buf();
+ let packages = packages.to_vec();
+ let result = tokio::task::spawn_blocking(move || {
+ let (program, mut args) = npm_command(&node);
+ args.push(OsString::from("rebuild"));
+ args.extend(packages.into_iter().map(OsString::from));
+ run_process_with_timeout(&program, &args, &core_root, NATIVE_REBUILD_TIMEOUT, "npm rebuild")
+ })
+ .await
+ .map_err(|e| format!("CORE_NATIVE_REBUILD_FAILED: {e}"))??;
+ if !result.status.success() {
+ return Err(format!(
+ "CORE_NATIVE_REBUILD_FAILED: npm rebuild exited with {}: {}",
+ result.status,
+ command_output_tail(&result)
+ ));
+ }
+ Ok(())
+}
+
+/// 定位与给定 node 配套的 npm 命令:优先 `<node 目录>/node_modules/npm/bin/npm-cli.js`
+/// (捆绑运行时与官方发行版都在 node 目录下自带 npm),否则退回 PATH 中的 npm。
+fn npm_command(node: &Path) -> (OsString, Vec<OsString>) {
+ if let Some(cli) = npm_cli_path_for(node) {
+ return (node.as_os_str().to_os_string(), vec![cli.into_os_string()]);
+ }
+ let program = if cfg!(windows) {
+ OsString::from("npm.cmd")
+ } else {
+ OsString::from("npm")
+ };
+ (program, Vec::new())
+}
+
+fn npm_cli_path_for(node: &Path) -> Option<PathBuf> {
+ let dir = node.parent()?;
+ // Windows 捆绑运行时:<runtime>/node.exe + <runtime>/node_modules/npm/bin/npm-cli.js
+ // 官方发行版:<node>/bin/node + <node>/lib/node_modules/npm/bin/npm-cli.js
+ // 少数布局把 lib 放在 node 目录之外,再补一个上级 lib 候选。
+ let candidates = [
+ dir.join("node_modules").join("npm").join("bin").join("npm-cli.js"),
+ dir.join("lib").join("node_modules").join("npm").join("bin").join("npm-cli.js"),
+ dir.join("..").join("lib").join("node_modules").join("npm").join("bin").join("npm-cli.js"),
+ ];
+ candidates.into_iter().find(|candidate| candidate.is_file())
+}
+
/// 决定需要补齐的原生依赖安装参数。
///
/// 优先从已安装的根包 `sharp`/`koffi` 的 `optionalDependencies` 取目标平台包的
@@ -585,7 +969,7 @@ async fn install_native_packages(core_root: &Path, target: &NodeTarget, packages
OsString::from(format!("--cpu={}", target.arch)),
];
args.extend(packages.into_iter().map(OsString::from));
- run_process_with_timeout(&program, &args, &core_root, NATIVE_REPAIR_TIMEOUT)
+ run_process_with_timeout(&program, &args, &core_root, NATIVE_REPAIR_TIMEOUT, "npm install")
})
.await
.map_err(|e| format!("CORE_NATIVE_DEPENDENCY_REPAIR_FAILED: {e}"))??;
@@ -615,6 +999,7 @@ fn run_process_with_timeout(
args: &[OsString],
cwd: &Path,
timeout: Duration,
+ label: &str,
) -> Result<std::process::Output, String> {
let mut command = Command::new(program);
command.args(args).current_dir(cwd).stdout(Stdio::piped()).stderr(Stdio::piped());
@@ -652,7 +1037,7 @@ fn run_process_with_timeout(
let _ = stdout_thread.join().unwrap_or_default();
let _ = stderr_thread.join().unwrap_or_default();
return Err(format!(
- "CORE_NATIVE_DEPENDENCY_REPAIR_TIMEOUT: npm exceeded {} seconds (exit {status})",
+ "CORE_NATIVE_DEPENDENCY_REPAIR_TIMEOUT: {label} exceeded {} seconds (exit {status})",
timeout.as_secs()
));
}
@@ -805,4 +1190,216 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+
+ /// 探测脚本必须写出 Rust 侧约定的标记行,并覆盖 ABI 敏感包与 sharp/koffi 两条路径。
+ #[test]
+ fn native_probe_script_matches_marker_and_checks_abi() {
+ assert!(NATIVE_PROBE_SCRIPT.contains(NATIVE_PROBE_MARKER));
+ assert!(NATIVE_PROBE_SCRIPT.contains("NODE_MODULE_VERSION"));
+ assert!(NATIVE_PROBE_SCRIPT.contains("binding.gyp"));
+ assert!(NATIVE_PROBE_SCRIPT.contains("'sharp'"));
+ assert!(NATIVE_PROBE_SCRIPT.contains("'koffi'"));
+ }
+
+ #[test]
+ fn native_probe_failures_parse_from_marker_line_ignoring_noise() {
+ let stdout = concat!(
+ "some addon chatter\n",
+ "__DSH_NATIVE_PROBE__[{\"kind\":\"addon\",\"name\":\"fs-ext\",\"message\":\"The module 'x' was compiled against a different Node.js version using NODE_MODULE_VERSION 137. This version of Node.js requires NODE_MODULE_VERSION 141.\",\"abi\":true},",
+ "{\"kind\":\"import\",\"name\":\"sharp\",\"message\":\"Cannot find module 'sharp'\",\"abi\":false}]\n"
+ );
+ let failures = parse_native_probe_failures(stdout).expect("marker line must parse");
+ assert_eq!(failures.len(), 2);
+ assert_eq!(failures[0].name, "fs-ext");
+ assert!(failures[0].abi);
+ assert!(!failures[0].is_platform_import());
+ assert!(!failures[1].abi);
+ assert!(failures[1].is_platform_import());
+ }
+
+ #[test]
+ fn native_probe_parse_returns_none_without_marker() {
+ assert!(parse_native_probe_failures("no marker here").is_none());
+ assert!(parse_native_probe_failures("__DSH_NATIVE_PROBE__not json").is_none());
+ }
+
+ #[test]
+ fn native_probe_classifies_abi_and_platform_failures() {
+ let probe = NativeProbe::Failed(vec![
+ NativeProbeFailure {
+ kind: "addon".into(),
+ name: "fs-ext".into(),
+ message: "NODE_MODULE_VERSION 137".into(),
+ abi: true,
+ },
+ NativeProbeFailure {
+ kind: "addon".into(),
+ name: "fs-ext".into(),
+ message: "duplicate entry".into(),
+ abi: true,
+ },
+ NativeProbeFailure {
+ kind: "import".into(),
+ name: "koffi".into(),
+ message: "Cannot find module".into(),
+ abi: false,
+ },
+ ]);
+ assert!(!probe.is_ready());
+ assert!(probe.has_abi_mismatch());
+ assert!(probe.has_platform_import_failure());
+ assert_eq!(probe.abi_packages(), vec!["fs-ext".to_string()]);
+ assert!(NativeProbe::Ready.abi_packages().is_empty());
+ assert!(!NativeProbe::Unknown("boom".into()).has_abi_mismatch());
+ }
+
+ /// ABI 诊断必须点名模块、折叠 Node 的跨行报错并给出可操作建议(issue #441)。
+ #[test]
+ fn native_failure_diagnostic_reports_abi_mismatch() {
+ let failures = vec![NativeProbeFailure {
+ kind: "addon".into(),
+ name: "fs-ext".into(),
+ message: "The module 'fs_ext.node'\nwas compiled against a different Node.js version using\nNODE_MODULE_VERSION 137.".into(),
+ abi: true,
+ }];
+ let diagnostic = native_failure_diagnostic(
+ &failures,
+ Path::new("C:\\missing\\node.exe"),
+ Path::new("C:\\core"),
+ );
+ assert!(diagnostic.starts_with("CORE_NATIVE_ABI_MISMATCH:"));
+ assert!(diagnostic.contains("fs-ext"));
+ assert!(diagnostic.contains("NODE_MODULE_VERSION 137"));
+ assert!(!diagnostic.contains('\n'), "diagnostic must be a single line");
+ assert!(diagnostic.contains("install the Node.js version the core was built with"));
+ }
+
+ #[test]
+ fn native_failure_diagnostic_lists_non_abi_failures() {
+ let failures = vec![NativeProbeFailure {
+ kind: "import".into(),
+ name: "sharp".into(),
+ message: "Cannot find module 'sharp'".into(),
+ abi: false,
+ }];
+ let diagnostic = native_failure_diagnostic(&failures, Path::new("node"), Path::new("C:\\core"));
+ assert!(diagnostic.starts_with("CORE_NATIVE_DEPENDENCY_REPAIR_FAILED:"));
+ assert!(diagnostic.contains("sharp: Cannot find module 'sharp'"));
+ }
+
+ #[test]
+ fn collapse_whitespace_folds_multiline_messages() {
+ assert_eq!(collapse_whitespace("a\n b\t c"), "a b c");
+ }
+
+ /// 重建必须使用与所选运行时配套的 npm:捆绑运行时目录自带 npm-cli.js。
+ #[test]
+ fn npm_command_prefers_node_local_npm_cli() {
+ let root = std::env::temp_dir().join(format!("dsh-npm-cli-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ let bin_dir = root.join("node-v22.22.0-win-x64");
+ std::fs::create_dir_all(bin_dir.join("node_modules").join("npm").join("bin")).unwrap();
+ let npm_cli = bin_dir.join("node_modules").join("npm").join("bin").join("npm-cli.js");
+ std::fs::write(&npm_cli, "// npm").unwrap();
+ let node = bin_dir.join("node.exe");
+
+ let (program, args) = npm_command(&node);
+ assert_eq!(program, node.as_os_str().to_os_string());
+ assert_eq!(args, vec![npm_cli.clone().into_os_string()]);
+ assert_eq!(npm_cli_path_for(&node), Some(npm_cli));
+
+ // 找不到配套 npm 时退回 PATH 中的 npm(不硬编码路径)
+ let bare = root.join("bare").join("node.exe");
+ std::fs::create_dir_all(bare.parent().unwrap()).unwrap();
+ let (program, args) = npm_command(&bare);
+ assert!(program == OsString::from("npm.cmd") || program == OsString::from("npm"));
+ assert!(args.is_empty());
+
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// 用真实 Node 跑一遍探测脚本:脚本语法/标记约定出错时这里会失败。
+ /// 本机没有兼容 node 时跳过(受限环境)。
+ #[test]
+ fn native_probe_script_runs_on_real_node() {
+ let Some(node) = crate::config::get_local_node_path() else {
+ return;
+ };
+ let root = std::env::temp_dir().join(format!("dsh-native-probe-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ std::fs::create_dir_all(root.join("node_modules")).unwrap();
+
+ let mut command = Command::new(&node);
+ command
+ .args(["--input-type=module", "-e", NATIVE_PROBE_SCRIPT])
+ .current_dir(&root)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ command.creation_flags(0x08000000);
+ }
+ let output = command.output().expect("node must be runnable");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ output.status.success(),
+ "probe script must exit 0: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ // 空核心目录:sharp/koffi 解析失败但属于非 ABI 失败,必须能结构化解析。
+ let failures = parse_native_probe_failures(&stdout).expect("probe must emit the marker line");
+ assert!(failures.iter().all(|failure| !failure.abi));
+
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// 端到端契约测试:探测脚本 + Rust 解析必须能把"ABI 不匹配的原生包"识别出来
+ /// (issue #441 的 fs-ext 形态:binding.gyp + build/Release/*.node,包入口抛 ABI 错误)。
+ #[test]
+ fn native_probe_detects_abi_mismatch_package() {
+ let Some(node) = crate::config::get_local_node_path() else {
+ return;
+ };
+ let root = std::env::temp_dir().join(format!("dsh-native-abi-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ let pkg = root.join("node_modules").join("fs-ext");
+ std::fs::create_dir_all(pkg.join("build").join("Release")).unwrap();
+ std::fs::write(pkg.join("binding.gyp"), "{}").unwrap();
+ std::fs::write(pkg.join("build").join("Release").join("fs_ext.node"), "stub").unwrap();
+ std::fs::write(
+ pkg.join("package.json"),
+ r#"{"name":"fs-ext","main":"index.js"}"#,
+ )
+ .unwrap();
+ std::fs::write(
+ pkg.join("index.js"),
+ "throw new Error(\"was compiled against a different Node.js version using\\nNODE_MODULE_VERSION 137. This version of Node.js requires\\nNODE_MODULE_VERSION 141.\");",
+ )
+ .unwrap();
+
+ let mut command = Command::new(&node);
+ command
+ .args(["--input-type=module", "-e", NATIVE_PROBE_SCRIPT])
+ .current_dir(&root)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ command.creation_flags(0x08000000);
+ }
+ let output = command.output().expect("node must be runnable");
+ let failures =
+ parse_native_probe_failures(&String::from_utf8_lossy(&output.stdout)).expect("marker line");
+ let probe = NativeProbe::Failed(failures);
+ assert!(probe.has_abi_mismatch(), "fs-ext must be reported as an ABI mismatch");
+ assert_eq!(probe.abi_packages(), vec!["fs-ext".to_string()]);
+ // 诊断必须点名模块,供前端直接展示(而不是让用户只看到 HARNESS_NOT_OWNED)
+ let diagnostic = native_failure_diagnostic(probe.failures(), &node, &root);
+ assert!(diagnostic.starts_with("CORE_NATIVE_ABI_MISMATCH:"));
+ assert!(diagnostic.contains("fs-ext"));
+
+ let _ = std::fs::remove_dir_all(&root);
+ }
}
diff --git a/src-tauri/src/service/download/installable.rs b/src-tauri/src/service/download/installable.rs
index c2be6ee5..f7de048f 100644
--- a/src-tauri/src/service/download/installable.rs
+++ b/src-tauri/src/service/download/installable.rs
@@ -40,6 +40,12 @@ impl Installable for Nodejs {
config::get_node_install_path(app)
}
fn check_installed(&self, app: &AppHandle) -> bool {
+ // 原生模块 ABI 探测已判定本地 node 无法加载核心的原生模块(issue #441):
+ // 此时不能再以"本机有版本兼容的 node"为由跳过捆绑运行时,否则服务进程仍会
+ // 用那个 ABI 不匹配的运行时启动。
+ if config::prefer_bundled_node_runtime() {
+ return config::bundled_node_binary(app).is_some() && config::is_runtime_compatible(app);
+ }
if let Some(local_node) = config::get_local_node_path() {
log::info!(
"Detected compatible local Node.js ({}), skipping bundled runtime",
diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rs
index 7e6adc42..4525647f 100644
--- a/src-tauri/src/service/workflow/launch.rs
+++ b/src-tauri/src/service/workflow/launch.rs
@@ -435,6 +435,17 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
log::error!("prepare active core runtime failed: {e}");
return Err(e);
}
+ // prepare 可能因核心原生模块的 ABI 与本地 node 不匹配而改用捆绑运行时
+ // (issue #441),此时必须重新解析:下面的 DSH_NODE 注入与 PATH 前置都以
+ // 这里的结果为准,否则子进程仍会用那个加载不了原生模块的本地 node。
+ let node_binary_path = config::get_node_binary_path(&app_handle);
+ if !node_binary_path.exists() {
+ log::error!("Node.js runtime resolved for launch is missing");
+ return Err(format!(
+ "NODE_NOT_FOUND: Node.js runtime is missing: {}",
+ node_binary_path.display()
+ ));
+ }
let mut envs: HashMap<String, String> = HashMap::new();
envs.insert(
"DSH_HOME".to_string(),