Skip to content

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

fix(desktop): 显式下发 Harness 堆上限,避免 V8 堆耗尽导致会话整体崩溃 (#699)

hairyffaa152ab09bb
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index bb31589c..02d19546 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -144,6 +144,7 @@ windows-sys = { version = "0.61", features = [
"Win32_System_Pipes",
"Win32_System_Registry",
"Win32_System_SystemServices",
+ "Win32_System_SystemInformation",
"Win32_System_Threading",
"Win32_System_Time",
"Win32_UI_WindowsAndMessaging",
diff --git a/src-tauri/src/bridge/config.rs b/src-tauri/src/bridge/config.rs
index a4b40af3..92d99706 100644
--- a/src-tauri/src/bridge/config.rs
+++ b/src-tauri/src/bridge/config.rs
@@ -36,6 +36,7 @@ pub fn is_dev_build() -> bool {
pub async fn update_app_config(
app_handle: AppHandle,
port: Option<u16>,
+ harness_max_heap_mb: Option<u32>,
auto_start: Option<bool>,
cli_link_enabled: Option<bool>,
close_action: Option<String>,
@@ -63,6 +64,9 @@ pub async fn update_app_config(
// 一路顶高(issue #91,见 workflow::launch 的端口自愈逻辑)
setting.manual_port = Some(port);
}
+ if let Some(mb) = harness_max_heap_mb {
+ setting.harness_max_heap_mb = (mb != 0).then_some(mb);
+ }
if let Some(auto_start) = auto_start {
setting.auto_start = auto_start;
}
diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rs
index 4b65c647..87cb3064 100644
--- a/src-tauri/src/config/setting.rs
+++ b/src-tauri/src/config/setting.rs
@@ -9,6 +9,8 @@ use tauri_plugin_store::StoreExt;
pub struct Setting {
pub installed: bool,
pub port: u16,
+ #[serde(default)]
+ pub harness_max_heap_mb: Option<u32>,
pub auto_start: bool,
pub language: String,
#[serde(default)]
@@ -84,6 +86,12 @@ pub struct Setting {
pub const ZOOM_FACTOR_MIN: f64 = 0.5;
pub const ZOOM_FACTOR_MAX: f64 = 2.0;
pub const ZOOM_FACTOR_STEP: f64 = 0.1;
+pub const HARNESS_HEAP_MIN_MB: u32 = 1024;
+pub const HARNESS_HEAP_MAX_MB: u32 = 32768;
+
+pub fn normalize_harness_max_heap_mb(value: Option<u32>) -> Option<u32> {
+ value.filter(|mb| (HARNESS_HEAP_MIN_MB..=HARNESS_HEAP_MAX_MB).contains(mb))
+}
/// 默认档案:桌面端内置的 web 档案
fn default_active_profile() -> String {
@@ -159,6 +167,7 @@ impl Default for Setting {
Self {
installed: false,
port: default_port(),
+ harness_max_heap_mb: None,
auto_start: true,
language: "zh-CN".to_string(),
dsh_pkg_commit: None,
@@ -255,6 +264,7 @@ fn read_store_dat_setting<R: Runtime>(app_handle: &AppHandle<R>) -> Setting {
.and_then(|v| serde_json::from_value(v).ok())
.unwrap_or_else(Setting::default);
setting.zoom_factor = normalize_zoom_factor(setting.zoom_factor);
+ setting.harness_max_heap_mb = normalize_harness_max_heap_mb(setting.harness_max_heap_mb);
setting.close_action = normalize_close_action(&setting.close_action);
normalize_backup_fields(&mut setting);
setting
@@ -278,6 +288,7 @@ fn emit_setting(app_handle: &AppHandle, value: &serde_json::Value) {
fn preserve_persisted_fields(mut replacement: Setting, current: &Setting) -> Setting {
replacement.zoom_factor = normalize_zoom_factor(current.zoom_factor);
+ replacement.harness_max_heap_mb = normalize_harness_max_heap_mb(current.harness_max_heap_mb);
replacement.close_action = normalize_close_action(&current.close_action);
replacement.pet_enabled = current.pet_enabled;
replacement.active_pet.clone_from(&current.active_pet);
@@ -312,6 +323,7 @@ where
let mut setting = read_store_dat_setting(app_handle);
update(&mut setting);
setting.zoom_factor = normalize_zoom_factor(setting.zoom_factor);
+ setting.harness_max_heap_mb = normalize_harness_max_heap_mb(setting.harness_max_heap_mb);
// 落盘前的第二道闸:调用方(含前端 invoke)写入的不可信取值不以原始形态进 store
setting.close_action = normalize_close_action(&setting.close_action);
normalize_backup_fields(&mut setting);
diff --git a/src-tauri/src/service/workflow/heap.rs b/src-tauri/src/service/workflow/heap.rs
new file mode 100644
index 00000000..845001b5
--- /dev/null
+++ b/src-tauri/src/service/workflow/heap.rs
@@ -0,0 +1,121 @@
+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 {
+ 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.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;
+ }
+ }
+ }
+ false
+}
+
+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
+}
+
+pub(super) fn resolve_heap_limit_mb(
+ configured: Option<u32>,
+ node_options: Option<&str>,
+ total_mb: Option<u64>,
+) -> Option<u32> {
+ if node_options.is_some_and(node_options_heap_limit) {
+ return None;
+ }
+ 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}")))
+}
+
+#[cfg(windows)]
+pub(super) fn physical_memory_mb() -> Option<u64> {
+ use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
+ let mut status: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
+ status.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
+ (unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status.ullTotalPhys / 1024 / 1024)
+}
+
+#[cfg(target_os = "macos")]
+pub(super) fn physical_memory_mb() -> Option<u64> {
+ use objc2_foundation::NSProcessInfo;
+ let bytes = NSProcessInfo::processInfo().physicalMemory();
+ (bytes > 0).then_some(bytes / 1024 / 1024)
+}
+
+#[cfg(target_os = "linux")]
+pub(super) fn physical_memory_mb() -> Option<u64> {
+ let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
+ 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)
+}
+
+#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))]
+pub(super) fn physical_memory_mb() -> Option<u64> {
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn adaptive_limit_clamps_at_half_physical_memory() {
+ assert_eq!(auto_heap_limit_mb(4096), 2048);
+ 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);
+ }
+
+ #[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);
+ }
+
+ #[test]
+ fn inherited_heap_limit_takes_precedence_over_configured_and_adaptive_values() {
+ 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",
+ ] {
+ assert_eq!(resolve_heap_limit_mb(Some(12288), Some(options), Some(32768)), None, "{options}");
+ }
+ }
+
+ #[test]
+ fn unrelated_or_malformed_node_options_do_not_disable_adaptive_limit() {
+ for options in [
+ "--trace-warnings",
+ "--no-max-old-space-size=8192",
+ "--max-old-space-size-extra=8192",
+ "--max-old-space-size=",
+ "--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}");
+ }
+ }
+}
diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rs
index af4cf2be..7b461e6e 100644
--- a/src-tauri/src/service/workflow/launch.rs
+++ b/src-tauri/src/service/workflow/launch.rs
@@ -3,9 +3,9 @@
use crate::config;
use std::collections::HashMap;
-#[cfg(windows)]
use std::ffi::OsString;
use std::fs;
+use std::path::Path;
#[cfg(not(windows))]
use std::io::Read;
#[cfg(not(windows))]
@@ -46,6 +46,20 @@ type SpawnResult = Result<
/// 复用配置端口;到期仍未释放才按“真占用”逐级递增。
const PORT_RELEASE_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);
+fn build_harness_args(dsh_binary: &Path, profile: &str, port: u16, heap_mb: Option<u32>) -> Vec<OsString> {
+ let mut args = Vec::with_capacity(7);
+ args.extend(super::heap::heap_option_arg(heap_mb));
+ args.extend([
+ dsh_binary.as_os_str().to_os_string(),
+ OsString::from("--profile"),
+ OsString::from(profile),
+ OsString::from("--port"),
+ OsString::from(port.to_string()),
+ OsString::from("--no-open"),
+ ]);
+ args
+}
+
/// 轮询等待配置端口释放为空闲(端口本来就空闲则立即返回)。
///
/// async(tokio)实现,避免长时间阻塞启动线程。与 `stop()` 里“给系统一点时间
@@ -556,7 +570,16 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
return Err(e);
}
- log::info!("Starting Harness process");
+ let node_options = std::env::var("NODE_OPTIONS").ok();
+ let heap_mb = super::heap::resolve_heap_limit_mb(
+ setting.harness_max_heap_mb,
+ node_options.as_deref(),
+ 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"),
+ }
// dsh 的 Loader 在插件 dispose 时会把组合后的整棵 entry 树回写进
// `cordis.yml`(dsh-app-boot:plugin self-disposing persists the current
@@ -591,14 +614,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
GetExitCodeProcess, WaitForSingleObject, INFINITE,
};
- let mut args: Vec<OsString> = vec![
- dsh_binary_path.as_os_str().to_os_string(),
- OsString::from("--profile"),
- OsString::from(active_profile.as_str()),
- OsString::from("--port"),
- OsString::from(setting.port.to_string()),
- ];
- args.push(OsString::from("--no-open"));
+ let args = build_harness_args(&dsh_binary_path, active_profile.as_str(), setting.port, heap_mb);
// 只负责 spawn 并返回管道/PID/句柄:探测与重试期间不登记、不挂
// 监视线程——只有最终采用的那个进程才登记,否则旧监视线程会通过
@@ -701,12 +717,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
{
use std::os::unix::process::CommandExt;
let mut cmd = Command::new(&node_binary_path);
- cmd.arg(&dsh_binary_path)
- .arg("--profile")
- .arg(active_profile.as_str())
- .arg("--port")
- .arg(&setting.port.to_string());
- cmd.arg("--no-open");
+ cmd.args(build_harness_args(&dsh_binary_path, active_profile.as_str(), setting.port, heap_mb));
cmd.envs(&envs)
.current_dir(&core_dir)
// 核心修正:提供一个空的 stdin 防止 setRawMode 报错
@@ -742,12 +753,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
);
reset_active_profile_root(&app_handle);
cmd = Command::new(&node_binary_path);
- cmd.arg(&dsh_binary_path)
- .arg("--profile")
- .arg(active_profile.as_str())
- .arg("--port")
- .arg(setting.port.to_string());
- cmd.arg("--no-open");
+ cmd.args(build_harness_args(&dsh_binary_path, active_profile.as_str(), setting.port, heap_mb));
cmd.envs(&envs)
.current_dir(&core_dir)
.stdin(Stdio::null())
diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rs
index f194a2e1..5b69b299 100644
--- a/src-tauri/src/service/workflow/mod.rs
+++ b/src-tauri/src/service/workflow/mod.rs
@@ -18,6 +18,7 @@ pub(crate) mod win_inspector;
pub(crate) mod win_spawn;
mod health;
+mod heap;
mod install;
mod launch;
mod process;
diff --git a/src-tauri/src/service/workflow/process.rs b/src-tauri/src/service/workflow/process.rs
index 1989e8c6..f83313ec 100644
--- a/src-tauri/src/service/workflow/process.rs
+++ b/src-tauri/src/service/workflow/process.rs
@@ -175,6 +175,14 @@ pub(super) fn on_owned_process_exit(
"Owned Harness process {} exited with code {code}; resetting status to Stopped",
owned.pid
);
+ // SIGABRT:V8 堆耗尽(`JavaScript heap out of memory`)是桌面端最常见的成因
+ // (issue #699),补一条可检索的日志,便于在没有前端时定位。
+ if code == 134 {
+ log::warn!(
+ "HARNESS_HEAP_OOM: Harness aborted (code 134 / SIGABRT); an exhausted V8 heap \
+ limit is the common cause — raise the service memory limit in Settings"
+ );
+ }
} else {
log::warn!(
"Owned Harness process {} exited (exit code unavailable); resetting status to Stopped",
diff --git a/src/components/logs.utils.ts b/src/components/logs.utils.ts
index 1f4b9ded..aa922550 100644
--- a/src/components/logs.utils.ts
+++ b/src/components/logs.utils.ts
@@ -39,3 +39,7 @@ export function pickErrorLines(lines: readonly string[]): string[] {
export function containsInotifyLimitError(lines: readonly string[]): boolean {
return lines.some(line => /ENOSPC/i.test(line) && /file watchers/i.test(line))
}
+
+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))
+}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index b3b9bd5b..6ed0d71b 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -98,6 +98,7 @@
"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.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)",
@@ -105,6 +106,8 @@
"errors.patch_quarantine_failed": "Could not quarantine the broken patch file (rename failed): {{detail}}. The file is still in place, so restarting will hit the same parse error. Close whatever is holding the file (editor / sync client / antivirus), or rename it to a `.broken-<timestamp>` backup manually, then retry.",
"ui.service_url": "Service URL",
"ui.port": "Port",
+ "ui.heap_limit": "Service memory limit",
+ "ui.heap_limit_auto": "Auto",
"ui.zoom": "Zoom",
"ui.launch_on_login": "Launch app at login",
"ui.launch_on_login_hint": "Starts the desktop app after you sign in. Harness service startup is configured separately.",
@@ -155,6 +158,10 @@
"messages.cli_link_failed": "Failed to update CLI integration",
"messages.port_invalid": "Port must be an integer between 1 and 65535",
"messages.port_save_failed": "Failed to save port",
+ "messages.heap_changed": "Service memory limit changed",
+ "messages.heap_restart_hint": "It takes effect after the service restarts. Restart now?",
+ "messages.heap_invalid": "Service memory limit must be an integer between 1024 and 32768",
+ "messages.heap_save_failed": "Failed to save service memory limit",
"messages.reveal_dir_failed": "Failed to open the data directory",
"nav.sidebar_expand": "Expand sidebar",
"nav.sidebar_collapse": "Collapse sidebar",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index a8efe6a5..5eabef5d 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -98,6 +98,7 @@
"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.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 里,重装该插件即可)",
@@ -105,6 +106,8 @@
"errors.patch_quarantine_failed": "无法隔离损坏的补丁文件(改名失败):{{detail}}。文件仍在原处,重启会再次报同样的解析错误。请先关闭占用该文件的程序(编辑器 / 同步网盘 / 杀毒软件),或手动把该文件改名为 `.broken-<时间戳>` 备份,然后重试。",
"ui.service_url": "服务地址",
"ui.port": "端口",
+ "ui.heap_limit": "服务内存上限",
+ "ui.heap_limit_auto": "自动",
"ui.zoom": "界面缩放",
"ui.launch_on_login": "开机自启动",
"ui.launch_on_login_hint": "登录系统后启动桌面应用;Harness 服务的自动运行配置与此项相互独立。",
@@ -155,6 +158,10 @@
"messages.cli_link_failed": "更新命令行集成设置失败",
"messages.port_invalid": "端口必须是 1 到 65535 之间的整数",
"messages.port_save_failed": "保存端口失败",
+ "messages.heap_changed": "服务内存上限已更改",
+ "messages.heap_restart_hint": "重启服务后生效,是否立即重启?",
+ "messages.heap_invalid": "服务内存上限必须是 1024 到 32768 之间的整数",
+ "messages.heap_save_failed": "保存服务内存上限失败",
"messages.reveal_dir_failed": "打开数据目录失败",
"nav.sidebar_expand": "展开侧边栏",
"nav.sidebar_collapse": "收起侧边栏",
diff --git a/src/layout/components/setup.tsx b/src/layout/components/setup.tsx
index f5ca2bfb..ea654354 100644
--- a/src/layout/components/setup.tsx
+++ b/src/layout/components/setup.tsx
@@ -54,6 +54,7 @@ export function Setup() {
pluginConflictHint,
inotifyLimitHint,
patchLayerHint,
+ heapOomHint,
} = useStore(store.harness)
const error = status === 'error'
const installing = status === 'installing'
@@ -61,9 +62,7 @@ export function Setup() {
const StatusIcon = STATUS_ICONS[status]
// 安装中展示安装日志;错误态展示启动失败时从 dsh 服务日志读取的真实错误行。
const logs = installing ? installer.logs : (error && errorLogs.length > 0 ? errorLogs : undefined)
- // 错误态的针对性提示:插件路由冲突 / Linux inotify 文件监视上限 / 补丁层问题,
- // 三者互斥(由各自的失败特征识别),优先展示最具体的一条。
- const hint = error ? (patchLayerHint || pluginConflictHint || inotifyLimitHint) : undefined
+ const hint = error ? (patchLayerHint || pluginConflictHint || inotifyLimitHint || heapOomHint) : undefined
// 补丁层问题分两种,恢复动作不同:语法错误整层隔离(改名备份),悬空 insert 只
// 剥离解析不到的条目。两者的提示共用 patchLayerHint,入口按错误特征二选一。
const patchEntriesUnresolved = error && containsPatchEntryUnresolved(errorMsg)
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index a1b3ef9e..6228ad09 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -92,6 +92,7 @@ export const harness = defineStore({
inotifyLimitHint: '',
/** 识别到补丁层 YAML 语法错误时的针对性提示(含文件与行列号,Loadable children 展示) */
patchLayerHint: '',
+ heapOomHint: '',
serviceUrl: 'http://127.0.0.1:3080',
/** 带时间戳的 iframe 地址(boot 时生成一次,避免缓存) */
iframeSrc: '',
@@ -196,7 +197,7 @@ export const harness = defineStore({
this.iframeError = false
this.fail(message)
- const error = await attachStartupDiagnostics(new Error(message))
+ const error = await attachStartupDiagnostics(new Error(message), true)
if (exitToken !== bootToken)
return
await recovery.reviewStartupRecovery(
@@ -212,6 +213,7 @@ export const harness = defineStore({
error.inotifyLimitHint,
undefined,
error.patchLayerHint,
+ error.heapOomHint,
)
},
@@ -381,6 +383,7 @@ export const harness = defineStore({
this.pluginConflictHint = ''
this.inotifyLimitHint = ''
this.patchLayerHint = ''
+ this.heapOomHint = ''
preinstall.error = ''
// 服务(重)启动成功:清空插件异常修复态(若曾进入),并重置已「暂不处理」的插件
recovery.reset()
@@ -410,6 +413,7 @@ export const harness = defineStore({
this.pluginConflictHint = ''
this.inotifyLimitHint = ''
this.patchLayerHint = ''
+ this.heapOomHint = ''
recovery.reset()
this.serviceHealthy = false
this.iframeLoaded = false
@@ -467,7 +471,8 @@ export const harness = defineStore({
}
catch (err) {
// 失败时附上服务日志里的真实错误行,供错误界面展示而不是只显示超时文案
- throw await attachStartupDiagnostics(err)
+ const error = err instanceof Error ? err : new Error(String(err))
+ throw await attachStartupDiagnostics(error, error.message.includes('HARNESS_NOT_OWNED') || error.message.includes('Harness exited early'))
}
},
@@ -491,6 +496,7 @@ export const harness = defineStore({
this.pluginConflictHint = ''
this.inotifyLimitHint = ''
this.patchLayerHint = ''
+ this.heapOomHint = ''
recovery.clear()
this.status = 'ready'
let unlistenInstall: UnlistenFn | null = null
@@ -602,6 +608,7 @@ export const harness = defineStore({
error.inotifyLimitHint,
this.serviceRunning,
error.patchLayerHint,
+ error.heapOomHint,
)
}
finally {
@@ -616,12 +623,13 @@ export const harness = defineStore({
},
/** 进入错误态(供本模块与 harness-updater 模块共用) */
- fail(message: string, logs?: string[], pluginConflictHint?: string, inotifyLimitHint?: string, keepServiceRunning = false, patchLayerHint?: string) {
+ fail(message: string, logs?: string[], pluginConflictHint?: string, inotifyLimitHint?: string, keepServiceRunning = false, patchLayerHint?: string, heapOomHint?: string) {
this.errorMsg = message
this.errorLogs = logs ?? []
this.pluginConflictHint = pluginConflictHint ?? ''
this.inotifyLimitHint = inotifyLimitHint ?? ''
this.patchLayerHint = patchLayerHint ?? ''
+ this.heapOomHint = heapOomHint ?? ''
this.status = 'error'
this.serviceRunning = keepServiceRunning
},
@@ -771,6 +779,7 @@ export const harness = defineStore({
this.pluginConflictHint = ''
this.inotifyLimitHint = ''
this.patchLayerHint = ''
+ this.heapOomHint = ''
recovery.reset()
},
diff --git a/src/store/modules/harness/types.ts b/src/store/modules/harness/types.ts
index f4006d51..f2e70938 100644
--- a/src/store/modules/harness/types.ts
+++ b/src/store/modules/harness/types.ts
@@ -61,6 +61,7 @@ export interface StartupError extends Error {
pluginConflictHint?: string
/** Linux inotify 文件监视上限(ENOSPC)导致服务启动即崩溃时的针对性提示 */
inotifyLimitHint?: string
+ heapOomHint?: string
/** 补丁层 YAML 语法错误(`cordis.patch.yml` 手写错误)时的针对性提示 */
patchLayerHint?: string
phase?: StartupPhase
diff --git a/src/store/modules/harness/utils.ts b/src/store/modules/harness/utils.ts
index 3de5fd68..3e957a19 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 { containsInotifyLimitError, pickErrorLines } from '@/components/logs.utils'
+import { containsHeapOomError, containsInotifyLimitError, pickErrorLines } from '@/components/logs.utils'
import { toast } from '@/utils/toast'
import {
HEALTH_PROBE_INITIAL_INTERVAL,
@@ -190,7 +190,7 @@ export async function readServiceLogTail(): Promise<string[]> {
}
/** 失败时把服务日志的真实错误行与冲突提示挂到错误对象上 */
-export async function attachStartupDiagnostics(err: unknown): Promise<StartupError> {
+export async function attachStartupDiagnostics(err: unknown, processExited = false): Promise<StartupError> {
// Tauri `invoke` 对 `Result<_, String>` 命令的 rejection 是裸字符串,
// 必须先归一化为 Error 对象,否则在其上赋属性(ESM 严格模式)会抛
// `TypeError: Cannot create property ... on string`,反而遮蔽真实错误。
@@ -208,6 +208,9 @@ export async function attachStartupDiagnostics(err: unknown): Promise<StartupErr
if (containsInotifyLimitError(lines)) {
diagnosed.inotifyLimitHint = i18next.t('errors.inotify_limit')
}
+ if (processExited && containsHeapOomError(lines)) {
+ diagnosed.heapOomHint = i18next.t('errors.heap_oom')
+ }
}
// 补丁层 YAML 语法错误(issue #525):真实原因是用户手写的 `cordis.patch.yml`
// 解析不了,但失败阶段是「Plugin installation」,很容易被当成插件损坏。这里挂上
diff --git a/src/store/modules/setting/constants.ts b/src/store/modules/setting/constants.ts
index cd6623d7..036dbdeb 100644
--- a/src/store/modules/setting/constants.ts
+++ b/src/store/modules/setting/constants.ts
@@ -6,3 +6,7 @@ export const ZOOM_FACTOR_STEP = 0.1
export const ZOOM_FACTOR_MIN = 0.5
/** 缩放上限,与 Rust `ZOOM_FACTOR_MAX` 一致 */
export const ZOOM_FACTOR_MAX = 2
+/** 服务内存上限下限(MB),与 Rust `HARNESS_HEAP_MIN_MB` 一致 */
+export const HARNESS_HEAP_MIN_MB = 1024
+/** 服务内存上限上限(MB),与 Rust `HARNESS_HEAP_MAX_MB` 一致 */
+export const HARNESS_HEAP_MAX_MB = 32768
diff --git a/src/store/modules/setting/index.ts b/src/store/modules/setting/index.ts
index 99039d90..5092c51c 100644
--- a/src/store/modules/setting/index.ts
+++ b/src/store/modules/setting/index.ts
@@ -1 +1,2 @@
+export { HARNESS_HEAP_MAX_MB, HARNESS_HEAP_MIN_MB } from './constants'
export { setting } from './store'
diff --git a/src/store/modules/setting/store.ts b/src/store/modules/setting/store.ts
index 4fb026cb..3a09824c 100644
--- a/src/store/modules/setting/store.ts
+++ b/src/store/modules/setting/store.ts
@@ -11,6 +11,7 @@ export const setting = defineStore({
state: () => ({
installed: false,
port: 3080,
+ harness_max_heap_mb: null as number | null,
auto_start: true,
cli_link_enabled: true,
zoom_factor: 1,
diff --git a/src/store/modules/setting/types/index.ts b/src/store/modules/setting/types/index.ts
index a51d97cf..87555a38 100644
--- a/src/store/modules/setting/types/index.ts
+++ b/src/store/modules/setting/types/index.ts
@@ -2,6 +2,7 @@ export interface AppSetting {
/** 依赖是否已安装(boot 流程据此决定是否走安装与更新检查) */
installed: boolean
port: number
+ harness_max_heap_mb: number | null
auto_start: boolean
cli_link_enabled: boolean
zoom_factor: number
@@ -12,6 +13,7 @@ export interface AppSetting {
export interface AppSettingUpdate {
port?: number
+ harnessMaxHeapMb?: number
autoStart?: boolean
cliLinkEnabled?: boolean
closeAction?: string
diff --git a/src/ui/config/debug.tsx b/src/ui/config/debug.tsx
index b84a1cfc..cb343935 100644
--- a/src/ui/config/debug.tsx
+++ b/src/ui/config/debug.tsx
@@ -11,6 +11,7 @@ import { Panel } from '@/components/panel'
import { queryKeys } from '@/config/query-keys'
import { useListen } from '@/hooks/use-listen'
import { store } from '@/store'
+import { HARNESS_HEAP_MAX_MB, HARNESS_HEAP_MIN_MB } from '@/store/modules/setting'
import { ConfigCloseAction } from '@/ui/config/components/close-action'
import { ConfigLaunchOnLogin } from '@/ui/config/components/launch-on-login'
import { useCoreBreakingConfirm } from '@/ui/config/hooks/use-core-breaking-confirm'
@@ -47,6 +48,7 @@ export function ConfigDebug() {
// 端口编辑态:用户尚未输入时为 undefined,展示值始终以 store 中已保存的端口为准。
// 初值不写入 state(避免渲染期副作用),用户一旦输入即以输入值为准。
const [portInput, setPortInput] = useState<number>()
+ const [heapInput, setHeapInput] = useState<string>()
const { data: info, refetch: refreshInfo } = useQuery({
queryKey: queryKeys.info,
@@ -58,8 +60,11 @@ export function ConfigDebug() {
void refreshInfo()
})
- const { port: savedPort, zoom_factor: zoomFactor } = useStore(store.setting)
+ const { port: savedPort, zoom_factor: zoomFactor, harness_max_heap_mb: savedHeapMb } = useStore(store.setting)
const port = portInput ?? savedPort
+ const heapValue = heapInput ?? String(savedHeapMb ?? '')
+ /** 空输入代表自动值(null),其余按数字解析,非法值交给保存前的整数校验拦下 */
+ const parsedHeap = heapValue.trim() === '' ? null : Number(heapValue)
const { data: cliStatus, refetch: refreshCliStatus } = useQuery({
queryKey: queryKeys.cliStatus,
@@ -142,6 +147,37 @@ export function ConfigDebug() {
},
})
+ const { mutate: onSaveHeap } = useMutation({
+ mutationFn: async (mb: number | null) => {
+ // 空输入 = 交回自动值;Rust 侧把 0 归一化为 None(物理内存一半,见 workflow/heap.rs)
+ if (mb !== null && (!Number.isInteger(mb) || mb < HARNESS_HEAP_MIN_MB || mb > HARNESS_HEAP_MAX_MB)) {
+ throw new Error('HEAP_INVALID')
+ }
+ await store.setting.update({ harnessMaxHeapMb: mb ?? 0 })
+ const key = toast(t('messages.heap_changed'), {
+ variant: 'accent',
+ description: t('messages.heap_restart_hint'),
+ timeout: 10_000,
+ actionProps: {
+ children: t('app.restart'),
+ onPress: () => {
+ store.harness.restart()
+ toast.close(key)
+ },
+ },
+ })
+ },
+ onError: (err: unknown) => {
+ console.error('[ConfigDebug] save heap limit failed:', err)
+ if (String(err).includes('HEAP_INVALID')) {
+ toast(t('messages.heap_invalid'), { variant: 'danger' })
+ }
+ else {
+ toast(t('messages.heap_save_failed'), { variant: 'danger' })
+ }
+ },
+ })
+
const { mutate: onRevealDataDir } = useMutation({
mutationFn: () => invoke('reveal_data_dir'),
onError: (err: unknown) => {
@@ -323,6 +359,28 @@ export function ConfigDebug() {
</Button>
</div>
</div>
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium text-ink">{t('ui.heap_limit')}</span>
+ <div className="flex items-center gap-1.5">
+ <Input
+ type="number"
+ variant="secondary"
+ value={heapValue}
+ placeholder={t('ui.heap_limit_auto')}
+ onChange={e => setHeapInput(e.target.value)}
+ className="w-24 h-8 rounded-md [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ aria-label={t('ui.heap_limit')}
+ />
+ <Button
+ size="sm"
+ variant="primary"
+ className="rounded-md h-8"
+ onPress={() => onSaveHeap(parsedHeap)}
+ >
+ {t('buttons.save')}
+ </Button>
+ </div>
+ </div>
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-ink">{t('ui.language')}</span>
<Select
diff --git a/test/harness-heap.test.ts b/test/harness-heap.test.ts
new file mode 100644
index 00000000..99f04c36
--- /dev/null
+++ b/test/harness-heap.test.ts
@@ -0,0 +1,93 @@
+import { readFileSync } from 'node:fs'
+import i18next from 'i18next'
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { resources } from '../src/i18n/index.resource'
+import { attachStartupDiagnostics } from '../src/store/modules/harness/utils'
+
+const invokeMock = vi.hoisted(() => vi.fn())
+
+vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }))
+
+/** 报告者在 issue #699 里贴出的真实 FATAL 行(V8 堆耗尽) */
+const V8_HEAP_OOM_LINE = 'FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory'
+
+const HEAP_KEYS = [
+ 'errors.heap_oom',
+ 'ui.heap_limit',
+ 'ui.heap_limit_auto',
+ 'messages.heap_changed',
+ 'messages.heap_restart_hint',
+ 'messages.heap_invalid',
+ 'messages.heap_save_failed',
+]
+
+function locale(file: 'zh-CN.json' | 'en-US.json'): Record<string, string> {
+ const raw = readFileSync(new URL(`../src/i18n/locales/${file}`, import.meta.url), 'utf8')
+ return JSON.parse(raw) as Record<string, string>
+}
+
+function stubServiceLogTail(raw: string) {
+ invokeMock.mockImplementation(async (command: string) => (command === 'read_service_logs' ? raw : undefined))
+}
+
+beforeAll(async () => {
+ // 与壳层同一份资源初始化默认 i18next 实例:断言的是真实译文,而不是未初始化时的 key 回退
+ await i18next.init({
+ resources,
+ lng: 'zh-CN',
+ keySeparator: false,
+ nsSeparator: false,
+ initAsync: false,
+ })
+})
+
+afterEach(() => {
+ invokeMock.mockReset()
+})
+
+describe('attachStartupDiagnostics heap exhaustion hint', () => {
+ it('attaches the heap hint when the owned process exited and the log tail shows V8 heap exhaustion', async () => {
+ stubServiceLogTail([
+ 'dsh web: http://127.0.0.1:3080/?token=abc',
+ V8_HEAP_OOM_LINE,
+ ].join('\n'))
+
+ const error = await attachStartupDiagnostics(new Error('Harness exited'), true)
+
+ expect(error.heapOomHint).toBe(locale('zh-CN.json')['errors.heap_oom'])
+ })
+
+ it('keeps the hint off when the same log tail predates the current boot', async () => {
+ stubServiceLogTail([
+ 'dsh web: http://127.0.0.1:3080/?token=abc',
+ V8_HEAP_OOM_LINE,
+ ].join('\n'))
+
+ const error = await attachStartupDiagnostics(new Error('Plugin installation failed'), false)
+
+ expect(error.heapOomHint).toBeUndefined()
+ })
+
+ it('keeps the hint off when the process exited without the V8 signature', async () => {
+ stubServiceLogTail([
+ 'Error: EADDRINUSE: address already in use 127.0.0.1:3080',
+ 'Owned Harness process 42 exited with code 134',
+ ].join('\n'))
+
+ const error = await attachStartupDiagnostics(new Error('Harness exited'), true)
+
+ expect(error.heapOomHint).toBeUndefined()
+ })
+})
+
+describe('harness heap i18n contract', () => {
+ it('defines every heap key in both locales', () => {
+ const zh = locale('zh-CN.json')
+ const en = locale('en-US.json')
+
+ for (const key of HEAP_KEYS) {
+ expect(zh[key], `zh-CN.json missing ${key}`).toBeTypeOf('string')
+ expect(en[key], `en-US.json missing ${key}`).toBeTypeOf('string')
+ }
+ })
+})
diff --git a/test/index.test.ts b/test/index.test.ts
index a43c453f..1fb587b0 100644
--- a/test/index.test.ts
+++ b/test/index.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { containsInotifyLimitError, formatLogLine, pickErrorLines } from '../src/components/logs.utils'
+import { containsHeapOomError, containsInotifyLimitError, formatLogLine, pickErrorLines } from '../src/components/logs.utils'
describe('formatLogLine', () => {
it('strips the official GitHub release download prefix', () => {
@@ -42,6 +42,27 @@ describe('pickErrorLines', () => {
})
})
+describe('containsHeapOomError', () => {
+ it('recognizes the V8 heap exhaustion message', () => {
+ expect(containsHeapOomError([
+ 'FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory',
+ ])).toBe(true)
+ })
+
+ it('recognizes the heap exhaustion marker even when split across lines', () => {
+ expect(containsHeapOomError([
+ 'FATAL ERROR: Ineffective mark-compacts near heap limit',
+ 'Allocation failed - JavaScript heap out of memory',
+ ])).toBe(true)
+ })
+
+ it('does not treat a generic abort or unrelated memory error as V8 heap exhaustion', () => {
+ expect(containsHeapOomError(['Owned Harness process 42 exited with code 134; HARNESS_HEAP_OOM suspected'])).toBe(false)
+ expect(containsHeapOomError(['Error: JavaScript memory allocation failed'])).toBe(false)
+ expect(containsHeapOomError([])).toBe(false)
+ })
+})
+
describe('containsInotifyLimitError', () => {
it('detects the Linux inotify ENOSPC signature', () => {
const lines = [