DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(startup): 使用 fix-path-env 恢复 macOS 登录 PATH (#1217)
Hairyafa9fea85543
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 12a44ece..3ee78cff 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -1040,6 +1040,7 @@ dependencies = ["core-foundation 0.10.1","core-graphics 0.25.0","dunce",+ "fix-path-env","flate2","futures-util","image",@@ -1506,6 +1507,16 @@ version = "0.1.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de"+[[package]]+name = "fix-path-env"+version = "0.0.0"+source = "git+https://github.com/tauri-apps/fix-path-env-rs?rev=c4c45d503ea115a839aae718d02f79e7c7f0f673#c4c45d503ea115a839aae718d02f79e7c7f0f673"+dependencies = [+ "home",+ "strip-ansi-escapes",+ "thiserror 1.0.69",+]+[[package]]name = "fixedbitset"version = "0.5.7"@@ -2145,6 +2156,15 @@ dependencies = ["digest",]+[[package]]+name = "home"+version = "0.5.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"+dependencies = [+ "windows-sys 0.61.2",+]+[[package]]name = "html5ever"version = "0.39.0"@@ -4822,6 +4842,15 @@ dependencies = ["quote",]+[[package]]+name = "strip-ansi-escapes"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a8f8038e7e7969abb3f1b7c2a811225e9296da208539e0f79c5251d6cac0025"+dependencies = [+ "vte",+]+[[package]]name = "strsim"version = "0.11.1"@@ -6252,6 +6281,15 @@ dependencies = ["libc",]+[[package]]+name = "vte"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "231fdcd7ef3037e8330d8e17e61011a2c244126acc0a982f4040ac3f9f0bc077"+dependencies = [+ "memchr",+]+[[package]]name = "walkdir"version = "2.5.0"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex eed83170..689d9c02 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -146,6 +146,7 @@ core-graphics = "0.25"core-foundation = "0.10"[target.'cfg(unix)'.dependencies]+fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs", rev = "c4c45d503ea115a839aae718d02f79e7c7f0f673" }libc = "0.2"# Linux 托盘需要 tray-icon 的 KSNI 后端(背景见 issue #386 / #438):tauri 只开diff --git a/src-tauri/src/desktop/login_path.rs b/src-tauri/src/desktop/login_path.rsnew file mode 100644index 00000000..c22ac79d--- /dev/null+++ b/src-tauri/src/desktop/login_path.rs@@ -0,0 +1,73 @@+use std::ffi::OsString;+use std::io::{Read, Seek, SeekFrom, Write};+use std::os::unix::{ffi::OsStrExt, ffi::OsStringExt, process::CommandExt};+use std::process::{Command, Stdio};+use std::time::{Duration, Instant};++pub fn print() -> Result<(), String> {+ let inherited = std::env::var_os("PATH");+ fix_path_env::fix().map_err(|error| error.to_string())?;+ let restored = std::env::var_os("PATH");+ let mut paths = Vec::new();+ for value in restored.iter().chain(inherited.iter()) {+ for path in std::env::split_paths(value) {+ if !paths.contains(&path) {+ paths.push(path);+ }+ }+ }+ let path = std::env::join_paths(paths).map_err(|error| error.to_string())?;+ std::io::stdout()+ .write_all(path.as_bytes())+ .map_err(|error| error.to_string())+}++pub fn restore(executable: &std::path::Path) -> Result<(), String> {+ let mut output = tempfile::tempfile().map_err(|error| error.to_string())?;+ let mut child = Command::new(executable)+ .arg("--print-login-path")+ .stdin(Stdio::null())+ .stdout(output.try_clone().map_err(|error| error.to_string())?)+ .stderr(Stdio::null())+ .process_group(0)+ .spawn()+ .map_err(|error| error.to_string())?;+ let deadline = Instant::now() + Duration::from_secs(3);+ loop {+ let error = match child.try_wait() {+ Ok(Some(status)) if status.success() => break,+ Ok(Some(status)) => return Err(format!("login PATH helper exited with {status}")),+ Ok(None) if Instant::now() < deadline => {+ std::thread::sleep(Duration::from_millis(20));+ continue;+ }+ Ok(None) => "login PATH helper timed out after 3 seconds".to_owned(),+ Err(error) => format!("login PATH helper wait failed: {error}"),+ };+ let group_killed = unsafe { libc::kill(-(child.id() as libc::pid_t), libc::SIGKILL) };+ let group_error = (group_killed != 0).then(std::io::Error::last_os_error);+ let _ = child.kill();+ child+ .wait()+ .map_err(|cleanup| format!("{error}; reap failed: {cleanup}"))?;+ if let Some(cleanup) = group_error {+ if cleanup.raw_os_error() != Some(libc::ESRCH) {+ return Err(format!("{error}; process group cleanup failed: {cleanup}"));+ }+ }+ return Err(error);+ }+ output+ .seek(SeekFrom::Start(0))+ .map_err(|error| error.to_string())?;+ let mut bytes = Vec::new();+ output+ .take(1_048_577)+ .read_to_end(&mut bytes)+ .map_err(|error| error.to_string())?;+ if bytes.len() > 1_048_576 || bytes.contains(&0) || bytes.is_empty() {+ return Err("invalid login PATH helper output".into());+ }+ std::env::set_var("PATH", OsString::from_vec(bytes));+ Ok(())+}diff --git a/src-tauri/src/desktop/mod.rs b/src-tauri/src/desktop/mod.rsindex f512b97b..b6496cd8 100644--- a/src-tauri/src/desktop/mod.rs+++ b/src-tauri/src/desktop/mod.rs@@ -6,6 +6,8 @@ pub mod compat;pub mod deep_link;pub mod frame_log;pub(crate) mod frontend_preload;+#[cfg(unix)]+pub mod login_path;pub mod notification;pub mod paste;pub mod payload;diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 7e22ffbc..3e48b547 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -17,9 +17,15 @@ pub fn patch_core_dir(core_dir: &std::path::Path) -> Result<(), String> {service::patch::apply_all_at(core_dir)}-/// 应用入口:先做 Wayland 环境兼容,再初始化日志、装配桌面端并进入事件循环。pub fn run() -> Result<(), String> {let started = std::time::Instant::now();+ #[cfg(unix)]+ if let Err(error) = std::env::current_exe()+ .map_err(|error| error.to_string())+ .and_then(|executable| desktop::login_path::restore(&executable))+ {+ eprintln!("STARTUP_PATH_RESTORE_FAILED: {error}");+ }desktop::startup::verify()?;// Wayland EGL workaround:仅 AppImage 需要(见 `should_apply_wayland_egl_workaround`)。if should_apply_wayland_egl_workaround(diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex e62439be..c70290d5 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -20,8 +20,16 @@ fn main() {// 无 GUI 的补丁入口:E2E 的插件 L2 直接起 `dsh web`,需要把 npm 装来的核心// 打成与桌面端装配核心同样的形态。复用 lib 里的补丁集,而不是另抄一份实现。- let args: Vec<String> = std::env::args().collect();- if args.get(1).map(String::as_str) == Some("--patch-core") {+ let args: Vec<_> = std::env::args_os().collect();+ #[cfg(unix)]+ if args.get(1).is_some_and(|arg| arg == "--print-login-path") {+ if let Err(error) = main::desktop::login_path::print() {+ eprintln!("STARTUP_PATH_RESTORE_FAILED: {error}");+ std::process::exit(1);+ }+ return;+ }+ if args.get(1).is_some_and(|arg| arg == "--patch-core") {let Some(dir) = args.get(2) else {eprintln!("usage: deepseek-harness-desktop --patch-core <core-dir>");std::process::exit(2);diff --git a/src-tauri/tests/login_path.rs b/src-tauri/tests/login_path.rsnew file mode 100644index 00000000..d5757aed--- /dev/null+++ b/src-tauri/tests/login_path.rs@@ -0,0 +1,193 @@+#![cfg(unix)]++use std::os::unix::{ffi::OsStrExt, fs::PermissionsExt};+use std::process::{Command, Output, Stdio};+use std::time::{Duration, Instant};++fn execute(command: &mut Command) -> Output {+ let mut child = command+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ let deadline = Instant::now() + Duration::from_secs(8);+ while child.try_wait().unwrap().is_none() {+ if Instant::now() >= deadline {+ child.kill().unwrap();+ child.wait().unwrap();+ panic!("login PATH startup did not return within 8 seconds");+ }+ std::thread::sleep(Duration::from_millis(20));+ }+ child.wait_with_output().unwrap()+}++#[test]+fn startup_login_path_preserves_inherited_directories_and_bounds_shell_wait() {+ let scratch = tempfile::tempdir().unwrap();+ let inherited = scratch.path().join("inherited-bin");+ let login = scratch.path().join("login-bin");+ std::fs::create_dir(&inherited).unwrap();+ std::fs::create_dir(&login).unwrap();+ let tool = login.join("dsh-login-path-probe");+ std::fs::write(&tool, "#!/bin/sh\nprintf 'login-path-tool'\n").unwrap();+ std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o700)).unwrap();+ for (directory, marker) in [(&inherited, "inherited"), (&login, "login")] {+ let tool = directory.join("dsh-login-path-priority");+ std::fs::write(&tool, format!("#!/bin/sh\nprintf '{marker}'\n")).unwrap();+ std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o700)).unwrap();+ }+ let shell = scratch.path().join("login-shell");+ std::fs::write(+ &shell,+ "#!/bin/sh\n[ \"$1\" = '-ilc' ] || exit 91\n[ \"$DISABLE_AUTO_UPDATE\" = true ] || exit 92\n[ \"$DSH_HOME\" = preserve-custom-home ] || exit 93\nprintf 'called' > \"$HOME/called\"\n[ \"$DSH_TEST_PATH_MODE\" != failed ] || exit 17\nif [ \"$DSH_TEST_PATH_MODE\" = hanging ]; then\n /bin/sleep 60 &\n echo \"$!\" > \"$HOME/descendant\"\n wait\nfi\nexport PATH=\"$DSH_TEST_LOGIN_BIN:/usr/bin:/bin:$DSH_TEST_LOGIN_BIN\"\nexec /bin/sh -c \"$2\"\n",+ )+ .unwrap();+ std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o700)).unwrap();+ let original = std::env::join_paths([+ inherited.as_path(),+ std::path::Path::new("/usr/bin"),+ std::path::Path::new("/bin"),+ inherited.as_path(),+ ])+ .unwrap();+ let expected = std::env::join_paths([+ login.as_path(),+ std::path::Path::new("/usr/bin"),+ std::path::Path::new("/bin"),+ inherited.as_path(),+ ])+ .unwrap();+ let configure = |executable: &std::path::Path, mode: &str| {+ let mut command = Command::new(executable);+ command+ .env("DSH_TEST_PATH_MODE", mode)+ .env("DSH_TEST_LOGIN_BIN", &login)+ .env("DSH_TEST_EXPECTED_PATH", &expected)+ .env(+ "SHELL",+ if mode == "missing" {+ scratch.path().join("missing-shell")+ } else {+ shell.clone()+ },+ )+ .env("PATH", &original)+ .env("HOME", scratch.path())+ .env("DSH_HOME", "preserve-custom-home")+ .env("DSH_E2E_HOME", "relative")+ .env("TAURI_WEBDRIVER_PORT", "4445")+ .env_remove("APPDIR");+ command+ };++ let binary = std::path::Path::new(env!("CARGO_BIN_EXE_deepseek-harness-desktop"));+ let non_utf8 = std::ffi::OsStr::from_bytes(b"\xff");+ let helper = execute(+ configure(binary, "restored")+ .arg("--print-login-path")+ .arg(non_utf8),+ );+ assert!(+ helper.status.success(),+ "{}",+ String::from_utf8_lossy(&helper.stderr)+ );+ assert_eq!(helper.stdout, expected.as_bytes());+ let output = Command::new("dsh-login-path-probe")+ .env("PATH", &expected)+ .output()+ .unwrap();+ assert!(output.status.success());+ assert_eq!(output.stdout, b"login-path-tool");+ for mode in ["restored", "failed", "missing", "hanging"] {+ let mut probe = configure(&std::env::current_exe().unwrap(), mode);+ let result = execute(probe.args(["--exact", "restored_path_child", "--nocapture"]));+ assert!(+ result.status.success(),+ "{mode}: {}\n{}",+ String::from_utf8_lossy(&result.stderr),+ String::from_utf8_lossy(&result.stdout)+ );+ if scratch.path().join("called").exists() {+ std::fs::remove_file(scratch.path().join("called")).unwrap();+ }+ let started = Instant::now();+ let output = execute(configure(binary, mode).arg(non_utf8));+ assert_eq!(output.status.code(), Some(1), "{mode}");+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("STARTUP_E2E_HOME_INVALID:"),+ "{mode}: {stderr}"+ );+ assert_eq!(+ stderr.contains("STARTUP_PATH_RESTORE_FAILED:"),+ mode != "restored",+ "{mode}: {stderr}"+ );+ assert_eq!(scratch.path().join("called").exists(), mode != "missing");+ if mode == "hanging" {+ assert!(stderr.contains("timed out after 3 seconds"), "{stderr}");+ assert!(started.elapsed() < Duration::from_secs(6));+ let pid: i32 = std::fs::read_to_string(scratch.path().join("descendant"))+ .unwrap()+ .trim()+ .parse()+ .unwrap();+ let deadline = Instant::now() + Duration::from_secs(2);+ while unsafe { libc::kill(pid, 0) } == 0 {+ let status = Command::new("/bin/ps")+ .args(["-o", "stat=", "-p", &pid.to_string()])+ .output()+ .unwrap();+ if String::from_utf8_lossy(&status.stdout)+ .trim()+ .starts_with('Z')+ {+ break;+ }+ assert!(+ Instant::now() < deadline,+ "login shell descendant {pid} survived timeout"+ );+ std::thread::sleep(Duration::from_millis(20));+ }+ }+ }+ assert!(!scratch.path().join("app-data").exists());+}++#[test]+fn restored_path_child() {+ let Ok(mode) = std::env::var("DSH_TEST_PATH_MODE") else {+ return;+ };+ let original = std::env::var_os("PATH").unwrap();+ let result = main::desktop::login_path::restore(std::path::Path::new(env!(+ "CARGO_BIN_EXE_deepseek-harness-desktop"+ )));+ assert_eq!(result.is_ok(), mode == "restored", "{mode}: {result:?}");+ let expected = if mode == "restored" {+ std::env::var_os("DSH_TEST_EXPECTED_PATH").unwrap()+ } else {+ original+ };+ assert_eq!(std::env::var_os("PATH").unwrap(), expected);+ assert_eq!(std::env::var("DSH_HOME").unwrap(), "preserve-custom-home");+ let tool = Command::new("dsh-login-path-probe").output();+ if mode == "restored" {+ assert_eq!(tool.unwrap().stdout, b"login-path-tool");+ } else {+ assert_eq!(tool.unwrap_err().kind(), std::io::ErrorKind::NotFound);+ }+ let priority = Command::new("dsh-login-path-priority").output().unwrap();+ assert!(priority.status.success());+ assert_eq!(+ priority.stdout,+ if mode == "restored" {+ b"login".as_slice()+ } else {+ b"inherited".as_slice()+ }+ );+}