Skip to content

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

fix(desktop): 服务内存上限优先于 NODE_OPTIONS,崩溃提示报出生效值 (#944)

iuuuuuuuub156bd248fe3
diff --git a/src-tauri/src/bridge/config.rs b/src-tauri/src/bridge/config.rs
index 7268c4e3..5220b32b 100644
--- a/src-tauri/src/bridge/config.rs
+++ b/src-tauri/src/bridge/config.rs
@@ -13,6 +13,18 @@ pub async fn get_app_config(app_handle: AppHandle) -> Result<config::Setting, St
Ok(config::get_store_dat_setting(&app_handle))
}
+/// 当前设置下 Harness 进程实际生效的 V8 old-space 上限(MB)。
+///
+/// 与启动链路共用 `workflow::heap` 的同一个判定:用户设置 > 进程环境
+/// `NODE_OPTIONS` 里的上限 > 按物理内存算出的自动值。崩溃提示要用它,避免
+/// 提示里写死一个与真实上限无关的数字。
+#[tauri::command]
+pub fn get_effective_heap_limit_mb(app_handle: AppHandle) -> Option<u32> {
+ crate::service::workflow::effective_heap_limit_mb(
+ config::get_store_dat_setting(&app_handle).harness_max_heap_mb,
+ )
+}
+
/// 当前桌面端是否为 dev 构建(`tauri dev` / `pnpm dev:desktop`)。
///
/// 插件用它决定是否挂载只面向开发的调试入口(例如 dsh-tauri-ui 的「UI 组件」页);
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 4c5c9631..a4ff61dc 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -1582,6 +1582,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::runtime_ready,
crate::bridge::get_app_config,
crate::bridge::update_app_config,
+ crate::bridge::get_effective_heap_limit_mb,
crate::bridge::test_proxy,
crate::bridge::get_launch_on_login,
crate::bridge::set_launch_on_login,
diff --git a/src-tauri/src/service/workflow/heap.rs b/src-tauri/src/service/workflow/heap.rs
index ea9d77c0..084e9b8e 100644
--- a/src-tauri/src/service/workflow/heap.rs
+++ b/src-tauri/src/service/workflow/heap.rs
@@ -1,49 +1,205 @@
use std::ffi::OsString;
const AUTO_HEAP_MIN_MB: u64 = 2048;
-const AUTO_HEAP_MAX_MB: u64 = 8192;
-fn node_options_heap_limit(node_options: &str) -> bool {
+/// 自动值的上限。取物理内存的一半后再按这个上限收敛。
+///
+/// 曾长期是 8192,实测在 63.2GiB 的机器上偏小:单个大会话的日志(Session.log
+/// 常驻内存)加载后就要 2GB 以上,跑起来峰值轻松越过 8GB,进程在 8.2GB 附近
+/// 以 code 134(SIGABRT)终止。抬高到 16384 后同一会话稳定运行。
+const AUTO_HEAP_MAX_MB: u64 = 16384;
+
+/// 「堆上限交给 NODE_OPTIONS」的哨兵值。
+///
+/// `--max-old-space-size=0` 在 V8 里按默认值处理(等价于没传参数),因此 0 可以
+/// 安全地表达「本次不显式下发」,让 NODE_OPTIONS 里的上限继续生效。
+const INHERITED_HEAP_LIMIT_MB: u32 = 0;
+
+/// 显式表达 old-space 上限的 flag(含 V8 接受的下划线变体)。
+const HEAP_LIMIT_FLAGS: [&str; 2] = ["--max-old-space-size", "--max_old_space_size"];
+
+/// 百分比形式的 old-space 上限。它的优先级高于 `--max-old-space-size`(V8 实测:
+/// NODE_OPTIONS 里只写 percentage 时,命令行 `--max-old-space-size=1600` 会被无视,
+/// 实际拿到的是物理内存的百分比),因此既要能识别它,也要在显式下发上限时把它从
+/// 子进程环境里摘掉,否则用户设置看似生效、实际被百分比覆盖。
+const HEAP_PERCENTAGE_FLAGS: [&str; 2] = [
+ "--max-old-space-size-percentage",
+ "--max_old_space_size_percentage",
+];
+
+fn heap_flags() -> impl Iterator<Item = &'static str> {
+ HEAP_LIMIT_FLAGS
+ .iter()
+ .chain(HEAP_PERCENTAGE_FLAGS.iter())
+ .copied()
+}
+
+/// 按出现顺序把 NODE_OPTIONS 里的堆 flag 交给 `visit`(`--flag value` 与 `--flag=value` 都认)。
+///
+/// `visit` 的 `bool` 参数表示取值是否是 V8 会接受的形式(size 要正整数、percentage 要
+/// 正数):解析不出来的取值既改不了上限,也不该把话语权从自动值那里抢走。
+fn for_each_heap_flag(node_options: &str, mut visit: impl FnMut(&'static str, &str, bool)) {
let mut tokens = node_options.split_whitespace();
while let Some(token) = tokens.next() {
let token = token.trim_matches(['"', '\'']);
- for flag in ["--max-old-space-size", "--max_old_space_size"] {
- if token == flag {
- if tokens
- .next()
- .is_some_and(|value| value.trim_matches(['"', '\'']).parse::<u32>().is_ok_and(|mb| mb > 0))
- {
- return true;
- }
- break;
- }
- if token.strip_prefix(flag).and_then(|tail| tail.strip_prefix('='))
- .is_some_and(|value| value.trim_matches(['"', '\'']).parse::<u32>().is_ok_and(|mb| mb > 0))
- {
- return true;
+ for flag in heap_flags() {
+ let attached = token.strip_prefix(flag).and_then(|tail| tail.strip_prefix('='));
+ if token != flag && attached.is_none() {
+ continue;
}
+ let value = match attached {
+ Some(value) => value.trim_matches(['"', '\'']),
+ None => tokens
+ .next()
+ .map(|value| value.trim_matches(['"', '\'']))
+ .unwrap_or_default(),
+ };
+ let is_limit = if HEAP_LIMIT_FLAGS.contains(&flag) {
+ value.parse::<u32>().is_ok_and(|mb| mb > 0)
+ } else {
+ value.parse::<f64>().is_ok_and(|percent| percent > 0.0)
+ };
+ visit(flag, value, is_limit);
+ break;
}
}
- false
+}
+
+/// NODE_OPTIONS 里指定的 old-space 上限(MB)。
+///
+/// 同一个变量里出现多个时以**最后一个**为准——V8 就是这么解析的(实测
+/// `--max-old-space-size=4096 --max-old-space-size=8192` 生效的是 8192),取第一个
+/// 会把实际生效值报小一半。取值解析不出来的条目直接忽略。
+///
+/// 只要出现可解析的 percentage flag 就返回 None:V8 让 percentage 压过 size(实测
+/// `--max-old-space-size=8192 --max-old-space-size-percentage=50` 在 63 GB 机器上得到
+/// 32413 MB,两个 flag 的先后顺序无关),此时报 size 就是谎报生效值。
+fn node_options_heap_limit(node_options: &str) -> Option<u32> {
+ let mut limit = None;
+ let mut has_percentage = false;
+ for_each_heap_flag(node_options, |flag, value, is_limit| {
+ if !is_limit {
+ return;
+ }
+ if !HEAP_LIMIT_FLAGS.contains(&flag) {
+ has_percentage = true;
+ return;
+ }
+ if let Ok(mb) = value.parse::<u32>() {
+ limit = Some(mb);
+ }
+ });
+ if has_percentage {
+ return None;
+ }
+ limit
+}
+
+/// NODE_OPTIONS 是否出现过任何会决定 old-space 上限的 flag(size 或 percentage)。
+///
+/// 解析不出来的取值(`--max-old-space-size=` /`=not-a-number`)不算:V8 会忽略它们,
+/// 让位只会把自动上限白送给一个不生效的 flag。
+pub(super) fn node_options_has_heap_flags(node_options: &str) -> bool {
+ let mut found = false;
+ for_each_heap_flag(node_options, |_, _, is_limit| found |= is_limit);
+ found
+}
+
+/// 摘掉 NODE_OPTIONS 里所有堆 flag,其余选项(`--require` 等)原样保留;全被摘空时返回 None。
+///
+/// 只在桌面端显式下发上限时使用:命令行 `--max-old-space-size` 只压得住 NODE_OPTIONS 里
+/// 的 size,压不住 percentage,留着 percentage 就等于用户设置没生效。
+pub(super) fn node_options_without_heap_flags(node_options: &str) -> Option<String> {
+ let mut kept: Vec<&str> = Vec::new();
+ let mut tokens = node_options.split_whitespace();
+ while let Some(token) = tokens.next() {
+ let bare = token.trim_matches(['"', '\'']);
+ let is_heap_flag = heap_flags().any(|flag| bare == flag || bare.starts_with(&format!("{flag}=")));
+ if !is_heap_flag {
+ kept.push(token);
+ continue;
+ }
+ // `--flag value` 形式:取值是独立 token,必须连它一起丢弃。
+ if !bare.contains('=') {
+ tokens.next();
+ }
+ }
+ (!kept.is_empty()).then(|| kept.join(" "))
+}
+
+/// 进程环境里 NODE_OPTIONS 指定的堆上限(MB)
+pub(super) fn node_options_heap_limit_mb() -> Option<u32> {
+ std::env::var("NODE_OPTIONS")
+ .ok()
+ .as_deref()
+ .and_then(node_options_heap_limit)
+}
+
+/// 当前进程环境里的 NODE_OPTIONS 是否带了任何堆 flag(size 或 percentage)。
+pub(super) fn node_options_has_heap_flags_env() -> bool {
+ std::env::var("NODE_OPTIONS").is_ok_and(|value| node_options_has_heap_flags(&value))
}
pub(super) fn auto_heap_limit_mb(total_mb: u64) -> u32 {
(total_mb / 2).clamp(AUTO_HEAP_MIN_MB, AUTO_HEAP_MAX_MB) as u32
}
+/// 本次启动要给 Node 传的堆上限(MB)。
+///
+/// 优先级:用户设置 > NODE_OPTIONS 里的堆上限 > 按物理内存算出的自动值。
+///
+/// 用户设置排在最前是刻意的:设置页是唯一的显式入口,而 NODE_OPTIONS 可能来自
+/// 系统环境变量或安装脚本,用户既改不动、也看不出它压住了自己的配置(issue 里
+/// 「设置了 8192 还提示 8192」就是这么来的)。命令行 `--max-old-space-size`
+/// 的优先级高于 NODE_OPTIONS(V8 实测),所以只要按用户填的值下发就一定能生效。
+/// 用户没填时才把话语权让回 NODE_OPTIONS,返回哨兵 0 表示「不显式下发」。
+///
+/// `inherited` 只看 NODE_OPTIONS 里**有没有**堆 flag,而不是能不能解析出数值:
+/// 只有 `--max-old-space-size-percentage` 时我们解析不出 MB,但它的优先级高于命令行
+/// `--max-old-space-size`,此时显式下发反而会谎报「用户设置已生效」,所以同样让位。
pub(super) fn resolve_heap_limit_mb(
configured: Option<u32>,
- node_options: Option<&str>,
+ inherited: bool,
total_mb: Option<u64>,
) -> Option<u32> {
- if node_options.is_some_and(node_options_heap_limit) {
- return None;
+ if let Some(configured) = configured {
+ return Some(configured);
+ }
+ if inherited {
+ return Some(INHERITED_HEAP_LIMIT_MB);
+ }
+ total_mb.filter(|total| *total > 0).map(auto_heap_limit_mb)
+}
+
+/// 子进程实际生效的 old-space 上限(MB):显式下发时就是下发的值,交给
+/// NODE_OPTIONS 时取继承值;两者都没有(物理内存未知且未配置)时无从得知。
+pub(super) fn effective_limit_mb(heap_mb: Option<u32>, inherited: Option<u32>) -> Option<u32> {
+ match heap_mb {
+ Some(INHERITED_HEAP_LIMIT_MB) => inherited,
+ other => other,
}
- configured.or_else(|| total_mb.filter(|total| *total > 0).map(auto_heap_limit_mb))
}
pub(super) fn heap_option_arg(heap_mb: Option<u32>) -> Option<OsString> {
- heap_mb.map(|mb| OsString::from(format!("--max-old-space-size={mb}")))
+ heap_mb
+ .filter(|mb| *mb > 0)
+ .map(|mb| OsString::from(format!("--max-old-space-size={mb}")))
+}
+
+/// 按当前设置与进程环境算出「进程真正会拿到」的上限(MB)。
+///
+/// 崩溃提示与启动链路共用这一个判定,避免提示里说的上限与进程实际拿到的
+/// 上限各说各话。
+pub(crate) fn effective_heap_limit_mb(configured: Option<u32>) -> Option<u32> {
+ let inherited = node_options_heap_limit_mb();
+ effective_limit_mb(
+ resolve_heap_limit_mb(
+ configured,
+ node_options_has_heap_flags_env(),
+ physical_memory_mb(),
+ ),
+ inherited,
+ )
}
#[cfg(windows)]
@@ -58,7 +214,7 @@ pub(super) fn physical_memory_mb() -> Option<u64> {
pub(super) fn physical_memory_mb() -> Option<u64> {
use objc2_foundation::NSProcessInfo;
let bytes = NSProcessInfo::processInfo().physicalMemory();
- (bytes > 0).then_some(bytes / 1024 / 1024)
+ (bytes > 0).then(|| bytes / 1024 / 1024)
}
#[cfg(target_os = "linux")]
@@ -67,7 +223,7 @@ pub(super) fn physical_memory_mb() -> Option<u64> {
let total_kb = meminfo.lines()
.find_map(|line| line.strip_prefix("MemTotal:"))?
.split_whitespace().next()?.parse::<u64>().ok()?;
- (total_kb > 0).then_some(total_kb / 1024)
+ (total_kb > 0).then(|| total_kb / 1024)
}
#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))]
@@ -85,27 +241,58 @@ mod tests {
assert_eq!(auto_heap_limit_mb(8192), 4096);
assert_eq!(auto_heap_limit_mb(12288), 6144);
assert_eq!(auto_heap_limit_mb(16384), 8192);
- assert_eq!(auto_heap_limit_mb(32768), 8192);
+ assert_eq!(auto_heap_limit_mb(32768), 16384);
+ // 64GB 机器(用户机器 63.2GiB 的同类量级):一半是 31615MB,必须仍然钳在自动上限内
+ assert_eq!(auto_heap_limit_mb(63231), AUTO_HEAP_MAX_MB as u32);
+ assert_eq!(auto_heap_limit_mb(131072), AUTO_HEAP_MAX_MB as u32);
}
#[test]
fn resolve_preserves_configured_value_and_falls_back_on_unknown_memory() {
- assert_eq!(resolve_heap_limit_mb(Some(12288), None, Some(16384)), Some(12288));
- assert_eq!(resolve_heap_limit_mb(None, None, Some(16384)), Some(8192));
- assert_eq!(resolve_heap_limit_mb(None, None, Some(0)), None);
- assert_eq!(resolve_heap_limit_mb(None, None, None), None);
+ assert_eq!(resolve_heap_limit_mb(Some(12288), false, Some(16384)), Some(12288));
+ assert_eq!(resolve_heap_limit_mb(None, false, Some(16384)), Some(8192));
+ // 大内存机器上自动值不再被 8192 截断(issue 里的 8.2GB 崩溃现场)
+ assert_eq!(resolve_heap_limit_mb(None, false, Some(65536)), Some(AUTO_HEAP_MAX_MB as u32));
+ assert_eq!(resolve_heap_limit_mb(None, false, Some(0)), None);
+ assert_eq!(resolve_heap_limit_mb(None, false, None), None);
}
#[test]
- fn inherited_heap_limit_takes_precedence_over_configured_and_adaptive_values() {
+ fn configured_limit_wins_over_inherited_node_options() {
+ assert_eq!(resolve_heap_limit_mb(Some(1600), true, Some(32768)), Some(1600));
+ assert_eq!(resolve_heap_limit_mb(Some(12288), true, Some(32768)), Some(12288));
+ }
+
+ #[test]
+ fn inherited_heap_limit_is_left_to_node_options() {
for options in [
"--max-old-space-size=8192",
"--trace-warnings --max-old-space-size 8192",
"--max-old-space-size \"8192\"",
"--max_old_space_size=8192",
"--max_old_space_size 8192",
+ "--max-old-space-size-percentage=50",
+ "--max_old_space_size_percentage 50",
] {
- assert_eq!(resolve_heap_limit_mb(Some(12288), Some(options), Some(32768)), None, "{options}");
+ assert!(node_options_has_heap_flags(options), "{options}");
+ assert_eq!(
+ resolve_heap_limit_mb(None, true, Some(32768)),
+ Some(INHERITED_HEAP_LIMIT_MB),
+ "{options}"
+ );
+ }
+ // 只有 size 时才解析得出数值;percentage 拿不到 MB,但仍算「有堆 flag」。
+ for options in [
+ "--max-old-space-size=8192",
+ "--trace-warnings --max-old-space-size 8192",
+ "--max-old-space-size \"8192\"",
+ "--max_old_space_size=8192",
+ "--max_old_space_size 8192",
+ ] {
+ assert_eq!(node_options_heap_limit(options), Some(8192), "{options}");
+ }
+ for options in ["--max-old-space-size-percentage=50", "--max_old_space_size_percentage 50"] {
+ assert_eq!(node_options_heap_limit(options), None, "{options}");
}
}
@@ -119,7 +306,111 @@ mod tests {
"--max-old-space-size=not-a-number",
"--max-old-space-size 0",
] {
- assert_eq!(resolve_heap_limit_mb(None, Some(options), Some(16384)), Some(8192), "{options}");
+ assert_eq!(node_options_heap_limit(options), None, "{options}");
+ assert!(!node_options_has_heap_flags(options), "{options}");
+ assert_eq!(
+ resolve_heap_limit_mb(None, false, Some(16384)),
+ Some(8192),
+ "{options}"
+ );
+ }
+ }
+
+ /// V8 在同一作用域里取**最后一个** `--max-old-space-size`(实测 4096/8192 组合拿到
+ /// 8192),解析器必须跟它一致,否则会把实际生效值报小。
+ #[test]
+ fn the_last_heap_limit_in_node_options_wins() {
+ assert_eq!(
+ node_options_heap_limit("--max-old-space-size=4096 --max-old-space-size=8192"),
+ Some(8192)
+ );
+ assert_eq!(
+ node_options_heap_limit("--max-old-space-size=8192 --max-old-space-size=4096"),
+ Some(4096)
+ );
+ // 解析失败的条目忽略,前一个有效值仍然算数。
+ assert_eq!(
+ node_options_heap_limit("--max-old-space-size=4096 --max-old-space-size=oops"),
+ Some(4096)
+ );
+ }
+
+ #[test]
+ fn strips_every_heap_flag_but_keeps_the_rest_of_node_options() {
+ assert_eq!(
+ node_options_without_heap_flags("--require C:/probe.cjs --max-old-space-size=8192"),
+ Some("--require C:/probe.cjs".to_string())
+ );
+ assert_eq!(
+ node_options_without_heap_flags("--max-old-space-size 8192 --trace-warnings"),
+ Some("--trace-warnings".to_string())
+ );
+ assert_eq!(
+ node_options_without_heap_flags("--max-old-space-size-percentage=50 --require a.cjs"),
+ Some("--require a.cjs".to_string())
+ );
+ // 显式下发上限时真正要摘的组合:size + percentage + 无关选项同时在场,两个堆
+ // flag 都必须消失(留下 percentage 会让命令行上限完全失效)。
+ assert_eq!(
+ node_options_without_heap_flags(
+ "--max-old-space-size=8192 --max-old-space-size-percentage 50 --require C:/probe.cjs"
+ ),
+ Some("--require C:/probe.cjs".to_string())
+ );
+ assert_eq!(
+ node_options_without_heap_flags("--max_old_space_size 8192"),
+ None
+ );
+ assert_eq!(node_options_without_heap_flags("--trace-warnings"), Some("--trace-warnings".to_string()));
+ }
+
+ #[test]
+ fn node_options_heap_limit_reads_the_inherited_value() {
+ assert_eq!(node_options_heap_limit("--max-old-space-size=8192"), Some(8192));
+ assert_eq!(node_options_heap_limit("--max-old-space-size 1600"), Some(1600));
+ assert_eq!(node_options_heap_limit("--max_old_space_size=4096"), Some(4096));
+ }
+
+ /// V8 让 percentage 压过 size(实测 63 GB 机器上 `size=8192 percentage=50` 拿到
+ /// 32413 MB,两个 flag 的先后顺序无关),此时报 size 就是谎报生效值。
+ #[test]
+ fn a_valid_percentage_flag_hides_the_size_flag() {
+ for options in [
+ "--max-old-space-size=8192 --max-old-space-size-percentage=50",
+ "--max-old-space-size-percentage=50 --max-old-space-size=8192",
+ "--max_old_space_size=8192 --max_old_space_size_percentage 50",
+ ] {
+ assert_eq!(node_options_heap_limit(options), None, "{options}");
+ assert!(node_options_has_heap_flags(options), "{options}");
}
+ // 解析不出来的 percentage 不生效,size 仍然算数。
+ assert_eq!(
+ node_options_heap_limit("--max-old-space-size=8192 --max-old-space-size-percentage=abc"),
+ Some(8192)
+ );
+ }
+
+ #[test]
+ fn heap_option_arg_skips_the_inherited_sentinel() {
+ assert_eq!(heap_option_arg(Some(INHERITED_HEAP_LIMIT_MB)), None);
+ assert_eq!(heap_option_arg(None), None);
+ assert_eq!(
+ heap_option_arg(Some(2048)),
+ Some(OsString::from("--max-old-space-size=2048"))
+ );
+ }
+
+ #[test]
+ fn effective_limit_reports_what_the_child_process_gets() {
+ assert_eq!(effective_limit_mb(Some(1600), Some(8192)), Some(1600));
+ assert_eq!(
+ effective_limit_mb(Some(INHERITED_HEAP_LIMIT_MB), Some(8192)),
+ Some(8192)
+ );
+ assert_eq!(
+ effective_limit_mb(Some(INHERITED_HEAP_LIMIT_MB), None),
+ None
+ );
+ assert_eq!(effective_limit_mb(None, Some(8192)), None);
}
}
diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rs
index 4b72e0b0..3cc18811 100644
--- a/src-tauri/src/service/workflow/launch.rs
+++ b/src-tauri/src/service/workflow/launch.rs
@@ -645,15 +645,47 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
}
mark_phase("patch_entry_preflight", &mut phase_started);
- let node_options = std::env::var("NODE_OPTIONS").ok();
+ let inherited_heap_mb = super::heap::node_options_heap_limit_mb();
+ let inherited_heap_flags = super::heap::node_options_has_heap_flags_env();
let heap_mb = super::heap::resolve_heap_limit_mb(
setting.harness_max_heap_mb,
- node_options.as_deref(),
+ inherited_heap_flags,
super::heap::physical_memory_mb(),
);
- match heap_mb {
- Some(mb) => log::info!("Starting Harness process with --max-old-space-size={mb}"),
- None => log::info!("Starting Harness process with Node default or inherited heap options"),
+ // 命令行 `--max-old-space-size` 压得住 NODE_OPTIONS 里的同名 flag,却压不住
+ // `--max-old-space-size-percentage`(V8 实测:只写 percentage 时命令行上限被
+ // 完全无视)。既然这次要显式下发用户设置,就把继承来的堆 flag 从子进程环境里
+ // 摘掉——只删堆相关项,`--require` 等其余选项原样保留;否则「已设置 16384」
+ // 仍可能是一句谎话。
+ if super::heap::heap_option_arg(heap_mb).is_some() {
+ if let Ok(node_options) = std::env::var("NODE_OPTIONS") {
+ if super::heap::node_options_has_heap_flags(&node_options) {
+ let stripped = super::heap::node_options_without_heap_flags(&node_options);
+ log::info!(
+ "Dropped inherited heap flags from NODE_OPTIONS for the Harness process (kept={:?})",
+ stripped
+ );
+ envs.insert("NODE_OPTIONS".to_string(), stripped.unwrap_or_default());
+ }
+ }
+ }
+ // 提示里说的上限必须与进程真正拿到的上限一致,否则用户会看到「已设置 8192
+ // 还提示 8192」这种自相矛盾的诊断(详见 heap.rs 的优先级说明)。
+ match super::heap::effective_limit_mb(heap_mb, inherited_heap_mb) {
+ Some(mb) => log::info!(
+ "Starting Harness process with effective heap limit {mb} MB (configured={:?}, inherited_from_node_options={:?})",
+ setting.harness_max_heap_mb,
+ inherited_heap_mb
+ ),
+ None if inherited_heap_flags => log::info!(
+ "Starting Harness process with the heap limit inherited from NODE_OPTIONS (configured={:?})",
+ setting.harness_max_heap_mb
+ ),
+ None => log::info!(
+ "Starting Harness process with the Node default heap limit (configured={:?}, inherited_from_node_options={:?})",
+ setting.harness_max_heap_mb,
+ inherited_heap_mb
+ ),
}
// dsh 的 Loader 在插件 dispose 时会把组合后的整棵 entry 树回写进
diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rs
index 7123bd82..8d6739f5 100644
--- a/src-tauri/src/service/workflow/mod.rs
+++ b/src-tauri/src/service/workflow/mod.rs
@@ -27,6 +27,7 @@ mod startup;
mod sweep;
pub use health::proxy_health_check;
+pub(crate) use heap::effective_heap_limit_mb;
pub use install::install;
pub use launch::{launch, restart, start};
pub use process::{
diff --git a/src/components/logs.utils.ts b/src/components/logs.utils.ts
index 161dbd38..9fbb1839 100644
--- a/src/components/logs.utils.ts
+++ b/src/components/logs.utils.ts
@@ -47,3 +47,30 @@ export function containsInotifyLimitError(lines: readonly string[]): boolean {
export function containsHeapOomError(lines: readonly string[]): boolean {
return lines.some(line => /JavaScript heap out of memory|Ineffective mark-compacts near heap limit/i.test(line))
}
+
+/** V8 GC 追踪行:`Mark-Compact 8058.3 (8224.0) -> 8051.0 (8234.2) MB`,最后一个括号里是提交的堆总量 */
+const HEAP_COMMITTED_MB = /\(\d+(?:\.\d+)?\)\s*->[^(]*\((\d+(?:\.\d+)?)\)\s*MB/
+
+/**
+ * 从日志尾部取崩溃瞬间实际提交到的堆上限(MB,取整)。
+ *
+ * V8 堆耗尽时会把 GC 追踪行写进日志,括号里的第二个数就是当时的堆总量;
+ * 它通常略高于配置上限(V8 会略微超发),因此比"设置页里现在填了什么"
+ * 更能说明崩溃现场的真实上限。没有 GC 追踪行时返回 undefined。
+ */
+export function heapPeakFromLogs(lines: readonly string[]): number | undefined {
+ let peak: number | undefined
+ for (const line of lines) {
+ const matched = HEAP_COMMITTED_MB.exec(line)
+ if (!matched) {
+ continue
+ }
+ const committed = Number(matched[1])
+ if (!Number.isFinite(committed)) {
+ continue
+ }
+ const mb = Math.floor(committed)
+ peak = peak === undefined ? mb : Math.max(peak, mb)
+ }
+ return peak
+}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index efac79c6..965bab73 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -121,7 +121,9 @@
"errors.client_boot_failed": "The client reported a failure while loading plugins.",
"errors.plugin_route_conflict": "Detected a plugin route conflict: two plugins registered the same route twice. Uninstall the recently added plugin (e.g. dsh-web-ui-all / dsh-better-sidebar) from the Plugins panel, or run dsh plugin --profile <profile> remove <package> for the active profile and retry.",
"errors.inotify_limit": "The Harness service crashed on startup: your system reached the limit for file watchers (inotify ENOSPC). Increase the watcher limit and restart — e.g. run `sudo sysctl fs.inotify.max_user_watches=524288` (and add `fs.inotify.max_user_watches=524288` to `/etc/sysctl.conf` to persist), then restart the app.",
- "errors.heap_oom": "The Harness service was killed after running out of memory (V8 heap limit): with many concurrent sessions or subagents the service grows past the current limit and the whole session crashes. Set a larger value in Settings → Service memory limit (for example 8192), save and restart the service; closing idle sessions or reducing concurrent subagents also helps.",
+ "errors.heap_oom": "The Harness service was killed after running out of memory (V8 heap limit): with many concurrent sessions or subagents the service grows past the current limit and the whole session crashes. The limit in effect was {{limit}} MB. Set a larger value in Settings → Service memory limit (1024–32768), save and restart the service; closing idle sessions or reducing concurrent subagents also helps.",
+ "errors.heap_oom_unknown": "The Harness service was killed after running out of memory (V8 heap limit): with many concurrent sessions or subagents the service grows past the current limit and the whole session crashes. Set a larger value in Settings → Service memory limit (1024–32768), save and restart the service; closing idle sessions or reducing concurrent subagents also helps.",
+ "errors.heap_oom_peak": "The log shows {{peak}} MB of committed heap at the moment of the crash.",
"errors.patch_entry_unresolved": "A patch layer references a plugin package that cannot be resolved, so Harness cannot load the plugin tree: {{detail}}. This usually means a plugin was uninstalled while the hand-written insert entry stayed in cordis.patch.yml. Remove those entries (or reinstall the plugin) and retry, or use \"Remove dangling entries\" to strip only the unresolvable entries (the original file is backed up as `.bak-<timestamp>` first).",
"errors.patch_entry_unresolved_item": "{{layer}} line {{line}}: {{id}} → {{name}}{{note}}",
"errors.patch_entry_unresolved_declared": " (still declared in package.json — reinstalling that plugin is the fix)",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 8a699227..cff73337 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -121,7 +121,9 @@
"errors.client_boot_failed": "客户端加载插件时报告了失败。",
"errors.plugin_route_conflict": "检测到插件路由冲突:两个插件重复注册了同一路由。请在「插件」面板卸载最近安装的插件(如 dsh-web-ui-all / dsh-better-sidebar),或在终端对当前档案执行 dsh plugin --profile <档案名> remove <包名> 后重试。",
"errors.inotify_limit": "Harness 服务启动即崩溃:系统文件监视(inotify)数量达到上限。请调高监视上限后重试——例如执行 `sudo sysctl fs.inotify.max_user_watches=524288`(并将 `fs.inotify.max_user_watches=524288` 写入 `/etc/sysctl.conf` 以持久化),然后重启应用。",
- "errors.heap_oom": "Harness 服务因内存耗尽(V8 堆上限)被强制终止:并发会话/子代理过多时,服务进程的内存会超过当前上限并整体崩溃。可在「设置 → 服务内存上限」填入更大的数值(例如 8192),保存后重启服务;也可以先关闭空闲会话或减少并发子代理。",
+ "errors.heap_oom": "Harness 服务因内存耗尽(V8 堆上限)被强制终止:并发会话/子代理过多时,服务进程的内存会超过当前上限并整体崩溃。当前生效的上限是 {{limit}} MB。可在「设置 → 服务内存上限」填入更大的数值(1024–32768),保存后重启服务;也可以先关闭空闲会话或减少并发子代理。",
+ "errors.heap_oom_unknown": "Harness 服务因内存耗尽(V8 堆上限)被强制终止:并发会话/子代理过多时,服务进程的内存会超过当前上限并整体崩溃。可在「设置 → 服务内存上限」填入更大的数值(1024–32768),保存后重启服务;也可以先关闭空闲会话或减少并发子代理。",
+ "errors.heap_oom_peak": "日志里崩溃瞬间提交的堆总量为 {{peak}} MB。",
"errors.patch_entry_unresolved": "补丁层引用了装不出来的插件包,Harness 无法加载整棵插件树:{{detail}}。通常是插件被卸载后,手写的 insert 条目还留在 cordis.patch.yml 里。请移除这些条目(或重新安装对应插件)后重试;也可以点「移除悬空条目」,由桌面端只剥离解析不到的条目(原文件会先备份为 `.bak-<时间戳>`)。",
"errors.patch_entry_unresolved_item": "{{layer}} 第 {{line}} 行:{{id}} → {{name}}{{note}}",
"errors.patch_entry_unresolved_declared": "(依赖仍在 package.json 里,重装该插件即可)",
diff --git a/src/store/modules/harness/utils.ts b/src/store/modules/harness/utils.ts
index 1cda8b19..5382001c 100644
--- a/src/store/modules/harness/utils.ts
+++ b/src/store/modules/harness/utils.ts
@@ -5,7 +5,7 @@ import type { PatchEntryStripReport, PatchQuarantineReport } from '@/types/plugi
import { promiseTimeout } from '@reause/core'
import { invoke } from '@tauri-apps/api/core'
import i18next from 'i18next'
-import { containsHeapOomError, containsInotifyLimitError, pickErrorLines } from '@/components/logs.utils'
+import { containsHeapOomError, containsInotifyLimitError, heapPeakFromLogs, pickErrorLines } from '@/components/logs.utils'
import { toast } from '@/utils/toast'
import {
HEALTH_PROBE_INITIAL_INTERVAL,
@@ -210,7 +210,14 @@ export async function attachStartupDiagnostics(err: unknown, processExited = fal
diagnosed.inotifyLimitHint = i18next.t('errors.inotify_limit')
}
if (processExited && containsHeapOomError(lines)) {
- diagnosed.heapOomHint = i18next.t('errors.heap_oom')
+ // 提示里报出"崩溃时真正生效的上限":设置页里的值可能被 NODE_OPTIONS 顶掉,
+ // 所以上限以后端启动链路同一份判定(get_effective_heap_limit_mb)为准。
+ const effectiveLimitMb = await invoke<number | null>('get_effective_heap_limit_mb').catch(() => null)
+ const peakMb = heapPeakFromLogs(lines)
+ const hint = effectiveLimitMb
+ ? i18next.t('errors.heap_oom', { limit: effectiveLimitMb })
+ : i18next.t('errors.heap_oom_unknown')
+ diagnosed.heapOomHint = peakMb === undefined ? hint : `${hint} ${i18next.t('errors.heap_oom_peak', { peak: peakMb })}`
}
}
// 补丁层 YAML 语法错误(issue #525):真实原因是用户手写的 `cordis.patch.yml`
diff --git a/test/harness-heap.test.ts b/test/harness-heap.test.ts
index afa326a2..18bf1e3c 100644
--- a/test/harness-heap.test.ts
+++ b/test/harness-heap.test.ts
@@ -14,6 +14,8 @@ const V8_HEAP_OOM_LINE = 'FATAL ERROR: Ineffective mark-compacts near heap limit
const HEAP_KEYS = [
'errors.heap_oom',
+ 'errors.heap_oom_unknown',
+ 'errors.heap_oom_peak',
'ui.heap_limit',
'ui.heap_limit_auto',
'messages.heap_changed',
@@ -27,8 +29,17 @@ function locale(file: 'zh-CN.json' | 'en-US.json'): Record<string, string> {
return JSON.parse(raw) as Record<string, string>
}
-function stubServiceLogTail(raw: string) {
- invokeMock.mockImplementation(async (command: string) => (command === 'read_service_logs' ? raw : undefined))
+/** V8 堆耗尽时的 GC 追踪行,括号里是提交的堆总量(崩溃瞬间已超过配置上限) */
+const V8_HEAP_PEAK_LINE = 'Mark-Compact 8058.3 (8224.0) -> 8051.0 (8234.2) MB'
+
+function stubServiceLogTail(raw: string, effectiveLimitMb: number | null = null) {
+ invokeMock.mockImplementation(async (command: string) => {
+ if (command === 'read_service_logs')
+ return raw
+ if (command === 'get_effective_heap_limit_mb')
+ return effectiveLimitMb
+ return undefined
+ })
}
beforeAll(async () => {
@@ -55,7 +66,29 @@ describe('attachStartupDiagnostics heap exhaustion hint', () => {
const error = await attachStartupDiagnostics(new Error('Harness exited'), true)
- expect(error.heapOomHint).toBe(locale('zh-CN.json')['errors.heap_oom'])
+ expect(error.heapOomHint).toContain(locale('zh-CN.json')['errors.heap_oom_unknown'])
+ })
+
+ it('names the limit that is actually in effect instead of a hard-coded example', async () => {
+ stubServiceLogTail([V8_HEAP_OOM_LINE, V8_HEAP_PEAK_LINE].join('\n'), 1600)
+
+ const error = await attachStartupDiagnostics(new Error('Harness exited'), true)
+
+ expect(error.heapOomHint).toContain('1600 MB')
+ expect(error.heapOomHint).toContain('8234')
+ expect(error.heapOomHint).not.toContain('8192')
+ })
+
+ it('keeps the hint actionable when the effective limit cannot be queried', async () => {
+ invokeMock.mockImplementation(async (command: string) => {
+ if (command === 'read_service_logs')
+ return V8_HEAP_OOM_LINE
+ throw new Error('command not found')
+ })
+
+ const error = await attachStartupDiagnostics(new Error('Harness exited'), true)
+
+ expect(error.heapOomHint).toContain(locale('zh-CN.json')['errors.heap_oom_unknown'])
})
it('keeps the hint off when the same log tail predates the current boot', async () => {
diff --git a/test/index.test.ts b/test/index.test.ts
index 84670f3b..64d8c9c7 100644
--- a/test/index.test.ts
+++ b/test/index.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { containsHeapOomError, containsInotifyLimitError, formatLogLine, pickErrorLines } from '../src/components/logs.utils'
+import { containsHeapOomError, containsInotifyLimitError, formatLogLine, heapPeakFromLogs, pickErrorLines } from '../src/components/logs.utils'
describe('formatLogLine', () => {
it('strips the official GitHub release download prefix', () => {
@@ -91,3 +91,21 @@ describe('containsInotifyLimitError', () => {
expect(containsInotifyLimitError([])).toBe(false)
})
})
+
+describe('heapPeakFromLogs', () => {
+ it('reads the peak heap size from the V8 GC trace line', () => {
+ expect(heapPeakFromLogs(['Mark-Compact 8058.3 (8224.0) -> 8051.0 (8234.2) MB'])).toBe(8234)
+ })
+
+ it('takes the largest peak across the whole tail', () => {
+ expect(heapPeakFromLogs([
+ 'Mark-Compact 4020.1 (4096.0) -> 4010.0 (4102.5) MB',
+ 'Mark-Compact 8058.3 (8224.0) -> 8051.0 (8234.2) MB',
+ ])).toBe(8234)
+ })
+
+ it('returns undefined when the tail carries no GC trace line', () => {
+ expect(heapPeakFromLogs(['FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory'])).toBeUndefined()
+ expect(heapPeakFromLogs([])).toBeUndefined()
+ })
+})