Skip to content

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

fix(service): release dsh DLL locks before re-extraction on Windows

hairyf1a40907d4340
diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rs
index 03aaef54..b58827eb 100644
--- a/src-tauri/src/config/runtime.rs
+++ b/src-tauri/src/config/runtime.rs
@@ -9,7 +9,7 @@ use super::format::get_dsh_service_url;
use super::utils::search_node_binary;
/// 获取 App Data 基础目录
-fn get_base_dir<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {
+pub fn get_base_dir<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {
app_handle
.path()
.app_data_dir()
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index ae497939..e1150503 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -141,6 +141,17 @@ pub fn run() {
Ok(())
})
.invoke_handler(handler())
- .run(tauri::generate_context!())
- .expect("error while running tauri application");
+ .build(tauri::generate_context!())
+ .expect("error while building tauri application")
+ .run(|app_handle, event| {
+ // 退出时回收 Harness 进程:不回收的话,node 进程会在应用退出后
+ // 残留并把原生模块 DLL(如 sharp 的 libvips-42.dll)锁在内存,
+ // 下次启动重新解压时会失败(Windows os error 32)
+ if let tauri::RunEvent::Exit = event {
+ let setting = config::get_store_dat_setting(app_handle);
+ if setting.installed {
+ service::workflow::stop_on_exit(app_handle.clone(), setting.port);
+ }
+ }
+ });
}
diff --git a/src-tauri/src/service/download/core.rs b/src-tauri/src/service/download/core.rs
index 73d527e9..c85d2b79 100644
--- a/src-tauri/src/service/download/core.rs
+++ b/src-tauri/src/service/download/core.rs
@@ -1,6 +1,7 @@
use futures_util::StreamExt;
use std::fs;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
+use std::time::Duration;
use crate::service::download::ProgressTracker;
use tauri::Runtime;
@@ -67,6 +68,41 @@ pub async fn download_file<'a, R: Runtime>(
Ok(buffer)
}
+/// 删除目录并等待 Windows 文件锁释放。
+///
+/// 结束 dsh/node 进程后,加载进内存的 DLL 句柄不会立即释放,删除目录可能
+/// 短暂失败(os error 32)。这里轮询等待,最长约 10 秒。
+fn remove_dir_with_retry(dest: &Path) -> bool {
+ const MAX_ATTEMPTS: u32 = 40;
+ const RETRY_DELAY: Duration = Duration::from_millis(250);
+
+ for attempt in 1..=MAX_ATTEMPTS {
+ match fs::remove_dir_all(dest) {
+ Ok(()) => return true,
+ Err(e) => {
+ if attempt < MAX_ATTEMPTS {
+ log::warn!(
+ "Failed to clean {:?} (attempt {}/{}), file may be locked: {}",
+ dest,
+ attempt,
+ MAX_ATTEMPTS,
+ e
+ );
+ std::thread::sleep(RETRY_DELAY);
+ } else {
+ log::error!(
+ "Failed to clean {:?} after {} attempts: {}",
+ dest,
+ MAX_ATTEMPTS,
+ e
+ );
+ }
+ }
+ }
+ }
+ false
+}
+
/// 确保解压文件到指定目录
///
/// # 参数
@@ -115,36 +151,16 @@ pub fn ensure_extract<'a, R: Runtime>(
return Ok(());
}
- // 清理并准备目标目录(Windows 上文件可能被短暂占用,重试等待释放)
+ // 清理并准备目标目录。Windows 上被进程加载的 DLL 在进程退出后释放句柄
+ // 需要时间,轮询等待目录可被删除;仍被占用时直接报错,避免在残留文件
+ // 上继续解压而得到“文件被锁”的误导性错误。
if dest.exists() {
log::debug!("Destination directory exists, cleaning");
- let mut cleaned = false;
- for attempt in 1..=5 {
- match fs::remove_dir_all(&dest) {
- Ok(()) => {
- cleaned = true;
- break;
- }
- Err(e) => {
- if attempt < 5 {
- log::warn!(
- "Failed to clean {:?} (attempt {}/5), file may be locked: {}",
- dest,
- attempt,
- e
- );
- std::thread::sleep(std::time::Duration::from_millis(300));
- } else {
- log::error!("Failed to clean {:?}: {}", dest, e);
- }
- }
- }
- }
- if !cleaned {
- log::error!(
- "Could not fully clean destination {:?}, some files may still be locked",
+ if !remove_dir_with_retry(&dest) {
+ return Err(format!(
+ "Destination directory is still locked, cannot clean: {:?}",
dest
- );
+ ));
}
}
fs::create_dir_all(&dest).map_err(|e| {
diff --git a/src-tauri/src/service/download/extractor.rs b/src-tauri/src/service/download/extractor.rs
index f83651b3..28f26333 100644
--- a/src-tauri/src/service/download/extractor.rs
+++ b/src-tauri/src/service/download/extractor.rs
@@ -12,7 +12,7 @@ use tauri::Runtime;
/// os error 32 = ERROR_SHARING_VIOLATION(文件被占用),os error 5 = 访问被拒绝,
/// 这两类错误通常是瞬时的,等待锁释放后重试即可成功。
fn create_file_with_retry(outpath: &Path) -> Result<fs::File, String> {
- const MAX_ATTEMPTS: u32 = 12;
+ const MAX_ATTEMPTS: u32 = 40;
const RETRY_DELAY: Duration = Duration::from_millis(250);
for attempt in 1..=MAX_ATTEMPTS {
diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rs
index 72f8325b..b43a04d0 100644
--- a/src-tauri/src/service/workflow/mod.rs
+++ b/src-tauri/src/service/workflow/mod.rs
@@ -8,6 +8,7 @@ use crate::service::download;
use crate::service::workflow::utils::{is_dsh_running, is_port_in_use, spawn_output_readers};
use std::collections::HashMap;
use std::fs;
+use std::path::Path;
use std::process::{Command, Stdio};
#[cfg(windows)]
use std::ffi::OsString;
@@ -30,9 +31,11 @@ fn kill_port_holder(port: u16) {
#[cfg(windows)]
{
- // 使用 PowerShell 清理端口占用进程(更稳定)
+ // 使用 PowerShell 找到占用端口的进程,再通过 taskkill /T 结束整个进程树。
+ // dsh 会派生 node worker 子进程,若只杀端口占用者,子进程仍会锁定原生
+ // 模块 DLL(如 sharp 的 libvips-42.dll),导致重新解压失败。
let ps_cmd = format!(
- "Get-NetTCPConnection -LocalPort {} -ErrorAction SilentlyContinue | ForEach-Object {{ Stop-Process -Id $_.OwningProcess -Force }}",
+ "$ids = Get-NetTCPConnection -LocalPort {} -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique; foreach ($id in $ids) {{ taskkill /PID $id /T /F 2>$null }}",
port
);
@@ -61,6 +64,39 @@ fn kill_port_holder(port: u16) {
}
}
+/// 结束本应用(AppData 目录)下由 dsh 拉起的 node 进程。
+///
+/// sharp 等原生模块 DLL 会被 node 及其子进程加载并锁定。服务崩溃或失去响应时
+/// HTTP 探测不到,但这些进程仍持有 DLL;仅杀端口占用者会漏掉不再监听端口的
+/// 子进程。这里通过可执行文件路径或命令行是否位于 AppData 目录来识别。
+#[cfg(windows)]
+fn kill_dsh_processes(base_dir: &Path) {
+ let base = base_dir.to_string_lossy().to_string();
+ let ps_cmd = format!(
+ "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Where-Object {{ ($_.ExecutablePath -like '{base}\\*') -or ($_.CommandLine -like '*{base}\\*') }} | ForEach-Object {{ Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }}"
+ );
+
+ let mut cmd = Command::new("powershell");
+ cmd.args([
+ "-NoProfile",
+ "-NonInteractive",
+ "-WindowStyle",
+ "Hidden",
+ "-Command",
+ &ps_cmd,
+ ]);
+
+ // 隐藏 PowerShell 窗口,避免弹出黑色控制台窗口
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
+ cmd.stdout(Stdio::null());
+ cmd.stderr(Stdio::null());
+
+ if let Err(e) = cmd.output() {
+ log::error!("Failed to kill dsh processes: {}", e);
+ }
+}
+
/// 检测并启动 Harness 服务
pub async fn start(app_handle: tauri::AppHandle) -> Result<(), String> {
let setting = config::get_store_dat_setting(&app_handle);
@@ -270,6 +306,11 @@ pub async fn stop(app_handle: tauri::AppHandle) -> Result<(), String> {
LAUNCH_GUARD.store(false, Ordering::SeqCst);
kill_port_holder(port);
+ // 连带清理 dsh 派生的 node 子进程:它们可能不再监听端口,
+ // 但仍把原生模块 DLL 加载在内存中(Windows 文件锁)
+ #[cfg(windows)]
+ kill_dsh_processes(&config::get_base_dir(&app_handle));
+
// 给系统一点时间释放端口 (重要!)
tokio::time::sleep(std::time::Duration::from_millis(800)).await;
@@ -278,6 +319,17 @@ pub async fn stop(app_handle: tauri::AppHandle) -> Result<(), String> {
Ok(())
}
+/// 应用退出时同步回收 Harness 进程。
+///
+/// 退出路径上不更新状态、不做异步等待,仅强制结束端口占用者及其进程树,
+/// 以及 AppData 目录下的 node 进程,避免残留进程把原生模块 DLL 锁在内存,
+/// 导致下次启动重新解压失败。
+pub fn stop_on_exit(app_handle: tauri::AppHandle, port: u16) {
+ kill_port_holder(port);
+ #[cfg(windows)]
+ kill_dsh_processes(&config::get_base_dir(&app_handle));
+}
+
/// 安装环境(Node.js 运行时 + 打包的 Harness 发行版)
pub async fn install(
app_handle: &tauri::AppHandle,
@@ -287,10 +339,18 @@ pub async fn install(
// 安装前先停止正在运行的 Harness 服务:运行中的 node 进程会把
// 原生模块 DLL(如 sharp 的 libvips-42.dll)加载进内存并锁住文件,
- // 不停止的话覆盖解压必然失败(Windows os error 32)
+ // 不停止的话覆盖解压必然失败(Windows os error 32)。
+ // 注意不能只依赖 HTTP 探测:服务崩溃/失去响应时探测不到,但 node
+ // 进程可能仍存活并持有 DLL,因此探测不到时也要强制清理。
if is_dsh_running().await {
log::info!("Stopping running Harness service before installation");
stop(app_handle.clone()).await?;
+ } else {
+ log::warn!("Harness service not responding, force cleaning dsh processes");
+ kill_port_holder(config::get_store_dat_setting(&app_handle).port);
+ #[cfg(windows)]
+ kill_dsh_processes(&config::get_base_dir(&app_handle));
+ tokio::time::sleep(std::time::Duration::from_millis(800)).await;
}
let window = app_handle