From 4df48e7b7f3235ece1f7d9c859ff5ace03a4bbd7 Mon Sep 17 00:00:00 2001 From: Xiao Deshi Date: Sat, 21 Nov 2026 17:32:24 +0800 Subject: [PATCH 1/5] fix(desktop): discover nvm-managed Node in the App tool search MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Finder and launchd never load a user's interactive shell profile, so the desktop App resolves its tools from a bounded search path. That search covered Homebrew and `$HOME/.local/bin` but not nvm, which activates Node by prepending `$NVM_BIN` to the interactive PATH. On a host whose only supported Node is nvm-managed, the private installer therefore ran `loopx doctor --deep --installation-only` without a Node on PATH, the TypeScript runtime check failed, and the installer exited 1 — surfaced as "安装程序退出(1);App 的启动环境未找到 Node.js" with `node_found: false`. Resolve the same bounded nvm locations the Lark CLI resolver already uses, without running nvm or sourcing any startup file: an `NVM_BIN` activated in the App's own environment, then the recorded `default` alias chain (`default` -> `lts/*` -> `lts/krypton` -> `v24.22.1`), then the installed versions newest-first behind the supported Homebrew runtimes. The alias read stays inside `$NVM_DIR/alias`, is depth-bounded and rejects non-normal path components, so a missing, cyclic or malformed chain simply falls through to installed-version discovery. The installer and the App-owned services share this one search path, so the same fix also covers the services the App starts afterwards. Signed-off-by: Xiao Deshi --- apps/desktop/loopx-control-plane/README.md | 8 +- .../src-tauri/src/services.rs | 128 +++++++++++++++- .../src-tauri/src/services_tests.rs | 137 ++++++++++++++++++ 3 files changed, 270 insertions(+), 3 deletions(-) diff --git a/apps/desktop/loopx-control-plane/README.md b/apps/desktop/loopx-control-plane/README.md index deac5411c4..6f9498de7a 100644 --- a/apps/desktop/loopx-control-plane/README.md +++ b/apps/desktop/loopx-control-plane/README.md @@ -315,8 +315,12 @@ shell, and a shell update does not certify Goal acceptance or provider readiness The release workflow packages both layers from one Git revision. The installer and App-owned services use the same bounded tool search, -including standard Homebrew locations on macOS, without loading interactive -shell profiles. Finder launches therefore do not depend on terminal PATH setup. +including standard Homebrew locations on macOS and nvm-managed Node +directories on Unix, without loading interactive shell profiles. Finder +launches therefore do not depend on terminal PATH setup. nvm resolution is +read-only and never runs nvm or sources a startup file: an `NVM_BIN` activated +in the App's own environment wins, then the `default` alias chain, then the +installed versions newest-first behind the supported Homebrew runtimes. When preparing the first App-owned snapshot, an already selected managed CLI's recorded Python is reused if the App has no interpreter record of its own. This leaves that CLI's launcher and installation owner unchanged. diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs index 633fd66171..9d9997691a 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs @@ -1088,14 +1088,136 @@ fn configure_codex_chat_home( } } +// Alias files chain (`default` -> `lts/*` -> `lts/krypton` -> `v24.22.1`). +// Read a bounded chain instead of running nvm, so a missing, cyclic or +// malformed chain just falls through to installed-version discovery. +#[cfg(unix)] +const NVM_ALIAS_DEPTH_LIMIT: usize = 8; + +// `v24.22.1`, `24.22.1` and the alias targets that name them are the only +// accepted forms; anything else is a non-version alias name to follow. +#[cfg(unix)] +fn nvm_version(name: &str) -> Option<(u64, u64, u64)> { + let trimmed = name.trim().strip_prefix('v').unwrap_or(name.trim()); + let mut fields = trimmed.split('.'); + let major = fields.next()?.parse().ok()?; + let minor = fields.next()?.parse().ok()?; + let patch = fields.next()?.parse().ok()?; + fields.next().is_none().then_some((major, minor, patch)) +} + +// Alias names are file names under `$NVM_DIR/alias`; keep the read inside that +// directory instead of letting a crafted alias escape it. +#[cfg(unix)] +fn is_bounded_nvm_alias(name: &str) -> bool { + !name.is_empty() + && !name.contains('\0') + && Path::new(name) + .components() + .all(|component| matches!(component, std::path::Component::Normal(_))) +} + +#[cfg(unix)] +fn resolve_nvm_alias(root: &Path, alias: &str, depth: usize) -> Option { + if depth >= NVM_ALIAS_DEPTH_LIMIT { + return None; + } + let name = alias.trim(); + if !is_bounded_nvm_alias(name) { + return None; + } + if let Some((major, minor, patch)) = nvm_version(name) { + // nvm names its version directories with the `v` prefix, whatever + // form the alias chain used to reach them. + return Some(format!("v{major}.{minor}.{patch}")); + } + let target = fs::read_to_string(root.join("alias").join(name)).ok()?; + resolve_nvm_alias(root, &target, depth + 1) +} + +#[cfg(unix)] +fn installed_nvm_versions(root: &Path) -> Vec { + let Ok(entries) = fs::read_dir(root.join("versions/node")) else { + return Vec::new(); + }; + let mut versions: Vec<_> = entries + .flatten() + .filter_map(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + nvm_version(&name).map(|version| (version, name)) + }) + .collect(); + versions.sort_by_key(|(version, _)| std::cmp::Reverse(*version)); + versions.into_iter().map(|(_, name)| name).collect() +} + +// nvm activates a Node by prepending `$NVM_BIN` to the interactive shell PATH. +// Finder/launchd never load that activation, so a host whose only Node is +// nvm-managed looks Node-less to the private installer and the owned services. +// Resolve the same bounded locations the Lark CLI resolver uses, without +// executing nvm or sourcing any startup file: the version activated in this +// App's environment, then the recorded `default` alias. +#[cfg(unix)] +fn activated_nvm_directories(nvm_root: &Path, nvm_bin: Option<&std::ffi::OsStr>) -> Vec { + let mut directories = Vec::new(); + if let Some(active) = nvm_bin.filter(|value| !value.is_empty()) { + push_tool_directory(&mut directories, PathBuf::from(active)); + } + if let Some(version) = resolve_nvm_alias(nvm_root, "default", 0) { + push_tool_directory( + &mut directories, + nvm_root.join("versions/node").join(version).join("bin"), + ); + } + directories +} + +// A host can have nvm-managed versions without a usable `default` alias. Keep +// them discoverable newest-first, behind the activated selection and the +// supported Homebrew LTS runtimes, so an outdated default cannot hide them. +#[cfg(unix)] +fn installed_nvm_directories(nvm_root: &Path) -> Vec { + let mut directories = Vec::new(); + for version in installed_nvm_versions(nvm_root) { + push_tool_directory( + &mut directories, + nvm_root.join("versions/node").join(version).join("bin"), + ); + } + directories +} + +#[cfg(unix)] +fn push_tool_directory(directories: &mut Vec, candidate: PathBuf) { + if candidate.is_dir() && !directories.contains(&candidate) { + directories.push(candidate); + } +} + +#[cfg(unix)] +fn nvm_root(home: Option<&std::ffi::OsStr>) -> Option { + if let Some(configured) = env::var_os("NVM_DIR").filter(|value| !value.is_empty()) { + return Some(PathBuf::from(configured)); + } + home.map(|home| PathBuf::from(home).join(".nvm")) +} + fn runtime_search_path( home: Option, inherited: Option, ) -> std::ffi::OsString { let mut paths = Vec::new(); - if let Some(home) = home { + if let Some(ref home) = home { paths.push(PathBuf::from(home).join(".local/bin")); } + #[cfg(unix)] + let nvm_root = nvm_root(home.as_deref()); + #[cfg(unix)] + let nvm_bin = env::var_os("NVM_BIN").filter(|value| !value.is_empty()); + #[cfg(unix)] + if let Some(nvm_root) = &nvm_root { + paths.extend(activated_nvm_directories(nvm_root, nvm_bin.as_deref())); + } if cfg!(target_os = "macos") { paths.extend([ PathBuf::from("/opt/homebrew/bin"), @@ -1110,6 +1232,10 @@ fn runtime_search_path( PathBuf::from("/usr/local/opt/node@22/bin"), ]); } + #[cfg(unix)] + if let Some(nvm_root) = &nvm_root { + paths.extend(installed_nvm_directories(nvm_root)); + } for path in inherited .as_deref() .map(env::split_paths) diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs index ecb7547f7b..45f51c8d4c 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs @@ -107,6 +107,12 @@ fn status_readiness_is_explicit_and_fails_closed() { #[test] #[cfg(target_os = "macos")] fn finder_runtime_path_includes_tools_without_loading_shell_profiles() { + // An nvm-activated test shell would prepend its own NVM_BIN to this + // fixture home's search path, so the fixed-position assertions below only + // hold for a process started without that activation. + if env::var_os("NVM_BIN").is_some() { + return; + } let path = runtime_search_path( Some("/fixture/user".into()), Some("/usr/bin:/bin:/usr/sbin:/sbin".into()), @@ -134,6 +140,137 @@ fn finder_runtime_path_includes_tools_without_loading_shell_profiles() { assert_eq!(again, path, "tool search must be idempotent"); } +#[cfg(unix)] +fn nvm_fixture(root: &Path) -> PathBuf { + let versions = root.join("versions/node"); + for version in ["v24.22.1", "v22.14.0", "v18.20.8"] { + fs::create_dir_all(versions.join(version).join("bin")).expect("nvm version bin"); + } + let alias = root.join("alias"); + fs::create_dir_all(alias.join("lts")).expect("nvm alias directory"); + fs::write(alias.join("default"), "lts/*\n").expect("default alias"); + fs::write(alias.join("lts/*"), "lts/krypton\n").expect("lts alias"); + fs::write(alias.join("lts/krypton"), "v24.22.1\n").expect("lts codename alias"); + root.to_path_buf() +} + +#[test] +#[cfg(unix)] +fn finder_runtime_path_finds_nvm_managed_node() { + // A test process started inside an nvm-activated shell would otherwise + // resolve this fixture home against the developer's own NVM_DIR/NVM_BIN. + if env::var_os("NVM_DIR").is_some() || env::var_os("NVM_BIN").is_some() { + return; + } + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm")); + let path = runtime_search_path( + Some(home.path().to_path_buf().into()), + Some("/usr/bin:/bin:/usr/sbin:/sbin".into()), + ); + let paths: Vec<_> = env::split_paths(&path).collect(); + let default_bin = nvm_root.join("versions/node/v24.22.1/bin"); + let position = |candidate: &Path| { + paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + assert_eq!(paths[0], home.path().join(".local/bin")); + assert_eq!( + position(&default_bin), + 1, + "the nvm default alias is the Node the user's shell activates" + ); + assert!( + position(&default_bin) < position(Path::new("/opt/homebrew/bin")), + "an explicitly selected nvm runtime outranks Homebrew" + ); + assert_eq!( + position(&nvm_root.join("versions/node/v22.14.0/bin")), + position(Path::new("/usr/local/opt/node@22/bin")) + 1, + "installed-but-not-selected nvm versions stay behind supported Homebrew runtimes" + ); + assert!( + position(&nvm_root.join("versions/node/v18.20.8/bin")) + > position(&nvm_root.join("versions/node/v22.14.0/bin")), + "installed nvm versions are discovered newest-first" + ); + let again = runtime_search_path(Some(home.path().to_path_buf().into()), Some(path.clone())); + assert_eq!(again, path, "tool search must be idempotent"); +} + +#[test] +#[cfg(unix)] +fn activated_nvm_bin_outranks_the_recorded_default_alias() { + let root = tempfile::tempdir().expect("nvm fixture"); + let nvm_root = nvm_fixture(root.path()); + let activated = nvm_root.join("versions/node/v18.20.8/bin"); + let directories = activated_nvm_directories(&nvm_root, Some(activated.as_os_str())); + assert_eq!( + directories, + vec![ + activated.clone(), + nvm_root.join("versions/node/v24.22.1/bin"), + ] + ); + assert_eq!( + activated_nvm_directories(&nvm_root, None), + vec![nvm_root.join("versions/node/v24.22.1/bin")], + "without an activation only the default alias resolves" + ); + assert_eq!( + activated_nvm_directories(&nvm_root, Some(std::ffi::OsStr::new("/absent/bin"))), + vec![nvm_root.join("versions/node/v24.22.1/bin")], + "a stale NVM_BIN must not shadow the recorded default" + ); +} + +#[test] +#[cfg(unix)] +fn nvm_alias_chain_resolves_versions_and_rejects_escapes() { + let root = tempfile::tempdir().expect("nvm fixture"); + let nvm_root = nvm_fixture(root.path()); + assert_eq!( + resolve_nvm_alias(&nvm_root, "default", 0).as_deref(), + Some("v24.22.1") + ); + assert_eq!( + resolve_nvm_alias(&nvm_root, "22.14.0", 0).as_deref(), + Some("v22.14.0"), + "a version without the v prefix still names nvm's directory" + ); + for alias in ["", "missing", "../outside", "/etc/passwd", "lts/../default"] { + assert_eq!( + resolve_nvm_alias(&nvm_root, alias, 0), + None, + "alias {alias:?} must not resolve" + ); + } + fs::write(nvm_root.join("alias/cycle"), "cycle").expect("cyclic alias"); + assert_eq!(resolve_nvm_alias(&nvm_root, "cycle", 0), None); + assert!(installed_nvm_versions(&nvm_root) + .iter() + .zip(["v24.22.1", "v22.14.0", "v18.20.8"]) + .all(|(found, expected)| found == expected)); + assert_eq!(nvm_version("v24.22.1"), Some((24, 22, 1))); + assert_eq!(nvm_version("not-a-version"), None); + assert_eq!(nvm_version("v24.22"), None); +} + +#[test] +#[cfg(unix)] +fn nvm_root_follows_configured_directory_and_conventional_home() { + match env::var_os("NVM_DIR").filter(|value| !value.is_empty()) { + Some(configured) => assert_eq!(nvm_root(None), Some(PathBuf::from(configured))), + None => assert_eq!( + nvm_root(Some(std::ffi::OsStr::new("/fixture/user"))), + Some(PathBuf::from("/fixture/user/.nvm")), + "an unset NVM_DIR keeps the conventional location" + ), + } +} + #[cfg(not(windows))] fn spawn_listener_fixture( executable: &Path, From dd43091f06804c666d5b2f038323064d6b0c0a30 Mon Sep 17 00:00:00 2001 From: Xiao Deshi Date: Sat, 21 Nov 2026 20:49:13 +0800 Subject: [PATCH 2/5] fix(desktop): keep inferred nvm discovery behind existing Node candidates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of the first head found a regression: an inferred nvm `default` alias was placed ahead of the Homebrew runtimes, so a Finder launch on a host with a stale nvm default (Node 20) plus a qualified Homebrew Node moved from `doctor` exit 0 to exit 1 — the App preferred the stale inferred candidate over a Node the host already provided. Split the two kinds of nvm location: - an `NVM_BIN` the launching shell exported stays first, which only preserves the precedence the inherited PATH already gave a terminal-launched App, and - everything this App discovers on disk — the recorded `default` alias, then the installed versions newest-first — is appended last, behind Homebrew and the inherited PATH, so automatic discovery extends the search for a host that has no other Node and never displaces one that does. Deduplicate the whole search path, so a directory discovered twice (an activated version that is also the recorded default, or an inherited entry this App also adds) appears once, and keep the search idempotent. Tests pin the nvm inputs through `runtime_search_path_from` instead of mutating the process environment that parallel tests read, and add the reviewer's scenario as a real qualification oracle: a stale inferred default beside a supported Node resolves to the supported one, while the same stale default stays discoverable when nothing else provides a Node. Differential against the installed App's private release, same doctor command and search path: | scenario | base | head | | --- | --- | --- | | qualified Node + stale nvm default | exit 0, node 24.22.1 | exit 0, node 24.22.1 | | nvm-only, stale default v20 | exit 1, node unavailable | exit 1, node 20.18.0 reported | | nvm-only, supported default v24 | exit 1, node unavailable | exit 0, node 24.22.1 | Signed-off-by: Xiao Deshi --- apps/desktop/loopx-control-plane/README.md | 10 +- .../src-tauri/src/services.rs | 133 ++++++++---- .../src-tauri/src/services_tests.rs | 200 ++++++++++++++---- 3 files changed, 249 insertions(+), 94 deletions(-) diff --git a/apps/desktop/loopx-control-plane/README.md b/apps/desktop/loopx-control-plane/README.md index 6f9498de7a..5de0d21742 100644 --- a/apps/desktop/loopx-control-plane/README.md +++ b/apps/desktop/loopx-control-plane/README.md @@ -318,9 +318,13 @@ The installer and App-owned services use the same bounded tool search, including standard Homebrew locations on macOS and nvm-managed Node directories on Unix, without loading interactive shell profiles. Finder launches therefore do not depend on terminal PATH setup. nvm resolution is -read-only and never runs nvm or sources a startup file: an `NVM_BIN` activated -in the App's own environment wins, then the `default` alias chain, then the -installed versions newest-first behind the supported Homebrew runtimes. +read-only and never runs nvm or sources a startup file. An `NVM_BIN` the +launching shell exported stays first, keeping the precedence the inherited +PATH already had. nvm locations this App discovers on disk — the recorded +`default` alias, then the installed versions newest-first — are appended last, +behind Homebrew and the inherited PATH, so an inferred stale default cannot +displace a Node the host already provides, while a host whose only Node is +nvm-managed still gets one. Each directory appears once in the search. When preparing the first App-owned snapshot, an already selected managed CLI's recorded Python is reused if the App has no interpreter record of its own. This leaves that CLI's launcher and installation owner unchanged. diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs index 9d9997691a..2bcdc0f10f 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs @@ -1151,33 +1151,38 @@ fn installed_nvm_versions(root: &Path) -> Vec { versions.into_iter().map(|(_, name)| name).collect() } -// nvm activates a Node by prepending `$NVM_BIN` to the interactive shell PATH. -// Finder/launchd never load that activation, so a host whose only Node is -// nvm-managed looks Node-less to the private installer and the owned services. -// Resolve the same bounded locations the Lark CLI resolver uses, without -// executing nvm or sourcing any startup file: the version activated in this -// App's environment, then the recorded `default` alias. +// nvm activates a Node by prepending `$NVM_BIN` to the interactive shell +// PATH. Finder/launchd never load that activation, so a host whose only Node +// is nvm-managed looks Node-less to the private installer and the owned +// services. Resolve the same bounded locations the Lark CLI resolver uses, +// without executing nvm or sourcing any startup file. +// +// Only an activation inherited from the launching shell (`nvm use`, or a +// terminal-launched App) is explicit intent, and it keeps the precedence the +// inherited PATH already had. Everything this App infers from disk is a +// fallback and must never shadow a candidate the host already provides. #[cfg(unix)] -fn activated_nvm_directories(nvm_root: &Path, nvm_bin: Option<&std::ffi::OsStr>) -> Vec { +fn explicit_nvm_directories(nvm_bin: Option<&std::ffi::OsStr>) -> Vec { let mut directories = Vec::new(); if let Some(active) = nvm_bin.filter(|value| !value.is_empty()) { push_tool_directory(&mut directories, PathBuf::from(active)); } + directories +} + +// Discovered, never activated: the recorded `default` alias first, then the +// installed versions newest-first. Appended behind the known runtimes and the +// inherited PATH, so a stale default cannot hide a supported Homebrew or +// inherited Node, and a host without any other Node still finds nvm. +#[cfg(unix)] +fn discovered_nvm_directories(nvm_root: &Path) -> Vec { + let mut directories = Vec::new(); if let Some(version) = resolve_nvm_alias(nvm_root, "default", 0) { push_tool_directory( &mut directories, nvm_root.join("versions/node").join(version).join("bin"), ); } - directories -} - -// A host can have nvm-managed versions without a usable `default` alias. Keep -// them discoverable newest-first, behind the activated selection and the -// supported Homebrew LTS runtimes, so an outdated default cannot hide them. -#[cfg(unix)] -fn installed_nvm_directories(nvm_root: &Path) -> Vec { - let mut directories = Vec::new(); for version in installed_nvm_versions(nvm_root) { push_tool_directory( &mut directories, @@ -1194,6 +1199,17 @@ fn push_tool_directory(directories: &mut Vec, candidate: PathBuf) { } } +// One tool search, one copy of each directory: a candidate discovered twice +// (an activated version that is also the recorded default, or an inherited +// entry this App also adds) must not appear twice in the search path. +fn extend_unique(paths: &mut Vec, candidates: impl IntoIterator) { + for candidate in candidates { + if !paths.contains(&candidate) { + paths.push(candidate); + } + } +} + #[cfg(unix)] fn nvm_root(home: Option<&std::ffi::OsStr>) -> Option { if let Some(configured) = env::var_os("NVM_DIR").filter(|value| !value.is_empty()) { @@ -1206,46 +1222,69 @@ fn runtime_search_path( home: Option, inherited: Option, ) -> std::ffi::OsString { - let mut paths = Vec::new(); - if let Some(ref home) = home { - paths.push(PathBuf::from(home).join(".local/bin")); - } #[cfg(unix)] let nvm_root = nvm_root(home.as_deref()); #[cfg(unix)] let nvm_bin = env::var_os("NVM_BIN").filter(|value| !value.is_empty()); + runtime_search_path_from( + home, + inherited, + #[cfg(unix)] + nvm_root.as_deref(), + #[cfg(unix)] + nvm_bin.as_deref(), + ) +} + +// The nvm inputs are parameters so a test can pin them without mutating the +// process environment that parallel tests read. +fn runtime_search_path_from( + home: Option, + inherited: Option, + #[cfg(unix)] nvm_root: Option<&Path>, + #[cfg(unix)] nvm_bin: Option<&std::ffi::OsStr>, +) -> std::ffi::OsString { + let mut paths = Vec::new(); + if let Some(ref home) = home { + paths.push(PathBuf::from(home).join(".local/bin")); + } + // An activation the launching shell exported keeps the precedence the + // inherited PATH already gave it. #[cfg(unix)] - if let Some(nvm_root) = &nvm_root { - paths.extend(activated_nvm_directories(nvm_root, nvm_bin.as_deref())); + if let Some(nvm_bin) = nvm_bin { + extend_unique(&mut paths, explicit_nvm_directories(Some(nvm_bin))); } if cfg!(target_os = "macos") { - paths.extend([ - PathBuf::from("/opt/homebrew/bin"), - PathBuf::from("/usr/local/bin"), - // Homebrew's supported LTS Node formulae are keg-only. Finder - // does not inherit the shell PATH that activates those runtimes. - // Use the same bounded search for the private installer and the - // services it starts; Core still qualifies the actual version. - PathBuf::from("/opt/homebrew/opt/node@24/bin"), - PathBuf::from("/usr/local/opt/node@24/bin"), - PathBuf::from("/opt/homebrew/opt/node@22/bin"), - PathBuf::from("/usr/local/opt/node@22/bin"), - ]); + extend_unique( + &mut paths, + [ + PathBuf::from("/opt/homebrew/bin"), + PathBuf::from("/usr/local/bin"), + // Homebrew's supported LTS Node formulae are keg-only. Finder + // does not inherit the shell PATH that activates those runtimes. + // Use the same bounded search for the private installer and the + // services it starts; Core still qualifies the actual version. + PathBuf::from("/opt/homebrew/opt/node@24/bin"), + PathBuf::from("/usr/local/opt/node@24/bin"), + PathBuf::from("/opt/homebrew/opt/node@22/bin"), + PathBuf::from("/usr/local/opt/node@22/bin"), + ], + ); } #[cfg(unix)] - if let Some(nvm_root) = &nvm_root { - paths.extend(installed_nvm_directories(nvm_root)); - } - for path in inherited - .as_deref() - .map(env::split_paths) - .into_iter() - .flatten() - { - if !paths.contains(&path) { - paths.push(path); - } - } + let discovered = nvm_root.map(discovered_nvm_directories).unwrap_or_default(); + extend_unique( + &mut paths, + inherited + .as_deref() + .map(env::split_paths) + .into_iter() + .flatten(), + ); + // Inferred nvm locations are the last resort: they extend the search for a + // host that has no other Node, and never displace one that already exists. + #[cfg(unix)] + extend_unique(&mut paths, discovered); env::join_paths(paths).unwrap_or_else(|_| inherited.unwrap_or_default()) } diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs index 45f51c8d4c..a39a3a4b95 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs @@ -110,7 +110,7 @@ fn finder_runtime_path_includes_tools_without_loading_shell_profiles() { // An nvm-activated test shell would prepend its own NVM_BIN to this // fixture home's search path, so the fixed-position assertions below only // hold for a process started without that activation. - if env::var_os("NVM_BIN").is_some() { + if ambient_nvm_activation() { return; } let path = runtime_search_path( @@ -141,32 +141,50 @@ fn finder_runtime_path_includes_tools_without_loading_shell_profiles() { } #[cfg(unix)] -fn nvm_fixture(root: &Path) -> PathBuf { +fn nvm_fixture(root: &Path, default: &str) -> PathBuf { let versions = root.join("versions/node"); - for version in ["v24.22.1", "v22.14.0", "v18.20.8"] { + for version in ["v24.22.1", "v22.14.0", "v20.18.0"] { fs::create_dir_all(versions.join(version).join("bin")).expect("nvm version bin"); } let alias = root.join("alias"); fs::create_dir_all(alias.join("lts")).expect("nvm alias directory"); - fs::write(alias.join("default"), "lts/*\n").expect("default alias"); + fs::write(alias.join("default"), format!("{default}\n")).expect("default alias"); fs::write(alias.join("lts/*"), "lts/krypton\n").expect("lts alias"); fs::write(alias.join("lts/krypton"), "v24.22.1\n").expect("lts codename alias"); root.to_path_buf() } +// A real Node stand-in so a resolution assertion doubles as a version +// qualification: the search order decides which executable Core would probe. +#[cfg(unix)] +fn node_fixture(bin: &Path, version: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + fs::create_dir_all(bin).expect("node fixture bin"); + let executable = bin.join("node"); + fs::write(&executable, format!("#!/bin/sh\nprintf 'v{version}\\n'\n")) + .expect("node fixture executable"); + fs::set_permissions(&executable, fs::Permissions::from_mode(0o755)).expect("node fixture mode"); + executable +} + +// An nvm-activated test shell would resolve this fixture home against the +// developer's own NVM_DIR/NVM_BIN, so the fixed-position assertions below only +// hold for a process started without that activation. +#[cfg(unix)] +fn ambient_nvm_activation() -> bool { + env::var_os("NVM_DIR").is_some() || env::var_os("NVM_BIN").is_some() +} + #[test] #[cfg(unix)] fn finder_runtime_path_finds_nvm_managed_node() { - // A test process started inside an nvm-activated shell would otherwise - // resolve this fixture home against the developer's own NVM_DIR/NVM_BIN. - if env::var_os("NVM_DIR").is_some() || env::var_os("NVM_BIN").is_some() { - return; - } let home = tempfile::tempdir().expect("home fixture"); - let nvm_root = nvm_fixture(&home.path().join(".nvm")); - let path = runtime_search_path( + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v24.22.1"); + let path = runtime_search_path_from( Some(home.path().to_path_buf().into()), Some("/usr/bin:/bin:/usr/sbin:/sbin".into()), + Some(&nvm_root), + None, ); let paths: Vec<_> = env::split_paths(&path).collect(); let default_bin = nvm_root.join("versions/node/v24.22.1/bin"); @@ -177,52 +195,145 @@ fn finder_runtime_path_finds_nvm_managed_node() { .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) }; assert_eq!(paths[0], home.path().join(".local/bin")); - assert_eq!( - position(&default_bin), - 1, - "the nvm default alias is the Node the user's shell activates" - ); + // A host whose only Node is nvm-managed must still be found from Finder. + assert!(paths.contains(&default_bin)); + // Inferred nvm is the last resort: behind every candidate the host already + // provides, and behind the inherited PATH a terminal launch contributes. + for existing in [ + Path::new("/opt/homebrew/bin"), + Path::new("/usr/local/bin"), + Path::new("/opt/homebrew/opt/node@24/bin"), + Path::new("/usr/local/opt/node@24/bin"), + Path::new("/opt/homebrew/opt/node@22/bin"), + Path::new("/usr/local/opt/node@22/bin"), + Path::new("/usr/bin"), + Path::new("/bin"), + ] { + assert!( + position(existing) < position(&default_bin), + "inferred nvm must stay behind the existing candidate {}", + existing.display() + ); + } assert!( - position(&default_bin) < position(Path::new("/opt/homebrew/bin")), - "an explicitly selected nvm runtime outranks Homebrew" - ); - assert_eq!( - position(&nvm_root.join("versions/node/v22.14.0/bin")), - position(Path::new("/usr/local/opt/node@22/bin")) + 1, - "installed-but-not-selected nvm versions stay behind supported Homebrew runtimes" + position(&nvm_root.join("versions/node/v22.14.0/bin")) > position(&default_bin), + "the recorded default alias leads the discovered versions" ); assert!( - position(&nvm_root.join("versions/node/v18.20.8/bin")) + position(&nvm_root.join("versions/node/v20.18.0/bin")) > position(&nvm_root.join("versions/node/v22.14.0/bin")), "installed nvm versions are discovered newest-first" ); - let again = runtime_search_path(Some(home.path().to_path_buf().into()), Some(path.clone())); + let mut unique = paths.clone(); + unique.sort(); + unique.dedup(); + assert_eq!( + unique.len(), + paths.len(), + "one tool search must not repeat a directory: {paths:?}" + ); + assert_eq!( + paths.iter().filter(|p| *p == &default_bin).count(), + 1, + "the recorded default alias is also an installed version and must appear once" + ); + let again = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(path.clone()), + Some(&nvm_root), + None, + ); assert_eq!(again, path, "tool search must be idempotent"); } #[test] #[cfg(unix)] -fn activated_nvm_bin_outranks_the_recorded_default_alias() { - let root = tempfile::tempdir().expect("nvm fixture"); - let nvm_root = nvm_fixture(root.path()); - let activated = nvm_root.join("versions/node/v18.20.8/bin"); - let directories = activated_nvm_directories(&nvm_root, Some(activated.as_os_str())); +fn explicit_nvm_activation_keeps_terminal_launch_precedence() { + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v24.22.1"); + let activated = nvm_root.join("versions/node/v20.18.0/bin"); assert_eq!( - directories, - vec![ - activated.clone(), - nvm_root.join("versions/node/v24.22.1/bin"), - ] + explicit_nvm_directories(Some(activated.as_os_str())), + vec![activated.clone()], + "an activation exported by the launching shell is explicit intent" + ); + assert!( + explicit_nvm_directories(None).is_empty(), + "without an activation nothing is explicit" + ); + assert!( + explicit_nvm_directories(Some(std::ffi::OsStr::new("/absent/bin"))).is_empty(), + "a stale NVM_BIN contributes nothing" + ); + let path = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some("/usr/bin:/bin".into()), + Some(&nvm_root), + Some(activated.as_os_str()), ); + let paths: Vec<_> = env::split_paths(&path).collect(); + let position = |candidate: &Path| { + paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; assert_eq!( - activated_nvm_directories(&nvm_root, None), - vec![nvm_root.join("versions/node/v24.22.1/bin")], - "without an activation only the default alias resolves" + position(&activated), + 1, + "an exported activation keeps the precedence the inherited PATH already had" + ); + assert!(position(&activated) < position(Path::new("/opt/homebrew/bin"))); + // The same activation is also an installed version, so it must not repeat. + assert_eq!(paths.iter().filter(|p| *p == &activated).count(), 1); +} + +// The reviewer's regression: a Finder launch with no NVM_BIN, an nvm `default` +// that predates the supported minimum, and a qualified Node the host already +// provides. The inferred default must be discovered, never preferred. +#[test] +#[cfg(unix)] +fn inferred_nvm_default_cannot_shadow_an_existing_qualified_node() { + let home = tempfile::tempdir().expect("home fixture"); + let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v20.18.0"); + let stale_default = nvm_root.join("versions/node/v20.18.0/bin"); + node_fixture(&stale_default, "20.18.0"); + // A supported Node the host already provides, the way Homebrew or an + // inherited terminal PATH would. + let qualified = node_fixture(&home.path().join("qualified/node/bin"), "24.22.1"); + let qualified_bin = qualified.parent().expect("qualified bin").to_path_buf(); + let path = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(qualified_bin.to_string_lossy().into_owned().into()), + Some(&nvm_root), + None, + ); + let resolved = resolve_executable_path("node", Some(path.as_os_str())) + .expect("the search must find the qualified Node"); + assert_eq!( + resolved, qualified, + "an inferred stale nvm default must not displace a supported Node" + ); + let version = Command::new(&resolved) + .arg("--version") + .output() + .expect("run resolved node"); + assert_eq!(String::from_utf8_lossy(&version.stdout).trim(), "v24.22.1"); + + // Without any other Node on the host, the same stale default is still the + // only candidate, so nvm remains discoverable rather than invisible. + let isolated = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some("/usr/bin:/bin".into()), + Some(&nvm_root), + None, ); + let paths: Vec<_> = env::split_paths(&isolated).collect(); + assert!(paths.contains(&stale_default)); assert_eq!( - activated_nvm_directories(&nvm_root, Some(std::ffi::OsStr::new("/absent/bin"))), - vec![nvm_root.join("versions/node/v24.22.1/bin")], - "a stale NVM_BIN must not shadow the recorded default" + resolve_executable_path("node", Some(isolated.as_os_str())), + Some(stale_default.join("node")), + "nvm-managed Node stays discoverable when nothing else provides one" ); } @@ -230,10 +341,11 @@ fn activated_nvm_bin_outranks_the_recorded_default_alias() { #[cfg(unix)] fn nvm_alias_chain_resolves_versions_and_rejects_escapes() { let root = tempfile::tempdir().expect("nvm fixture"); - let nvm_root = nvm_fixture(root.path()); + let nvm_root = nvm_fixture(root.path(), "lts/*"); assert_eq!( resolve_nvm_alias(&nvm_root, "default", 0).as_deref(), - Some("v24.22.1") + Some("v24.22.1"), + "the default alias chain resolves to the recorded version" ); assert_eq!( resolve_nvm_alias(&nvm_root, "22.14.0", 0).as_deref(), @@ -251,7 +363,7 @@ fn nvm_alias_chain_resolves_versions_and_rejects_escapes() { assert_eq!(resolve_nvm_alias(&nvm_root, "cycle", 0), None); assert!(installed_nvm_versions(&nvm_root) .iter() - .zip(["v24.22.1", "v22.14.0", "v18.20.8"]) + .zip(["v24.22.1", "v22.14.0", "v20.18.0"]) .all(|(found, expected)| found == expected)); assert_eq!(nvm_version("v24.22.1"), Some((24, 22, 1))); assert_eq!(nvm_version("not-a-version"), None); From 4bd3bf8719cd7bbb0e397f83021eb177ae117c46 Mon Sep 17 00:00:00 2001 From: Xiao Deshi Date: Sat, 21 Nov 2026 21:08:55 +0800 Subject: [PATCH 3/5] test(desktop): make the nvm precedence oracle host-independent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CI macOS runner ships a real Node at /opt/homebrew/bin, so the regression test's assumption that the fixture provides the only qualified candidate was wrong there: resolution legitimately picked the runner's Homebrew Node and the test failed. Assert the rule instead of a specific winner. For a given search path, resolve `node` and check whether any non-nvm candidate exists on this host: when one does, the resolved executable must not be the inferred stale default and must not come from the nvm tree; when none does, the inferred default is the only candidate and must still resolve. The ordering guarantee behind that resolution is asserted directly, so every non-nvm entry — including the Homebrew entries this App adds — precedes the inferred one. Verified locally both with and without a simulated /opt/homebrew/bin/node, which is the environment the runner provides. Signed-off-by: Xiao Deshi --- .../src-tauri/src/services_tests.rs | 88 ++++++++++++++----- 1 file changed, 68 insertions(+), 20 deletions(-) diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs index a39a3a4b95..a98edbfae9 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs @@ -288,9 +288,42 @@ fn explicit_nvm_activation_keeps_terminal_launch_precedence() { assert_eq!(paths.iter().filter(|p| *p == &activated).count(), 1); } +// An inferred nvm candidate may only be selected when no other candidate +// exists on the host. That rule must hold on any machine, with or without a +// Homebrew Node, so the oracle checks the host instead of assuming one. +#[cfg(unix)] +fn assert_inferred_nvm_never_displaces_existing( + nvm_root: &Path, + stale_default_bin: &Path, + search: &std::ffi::OsStr, +) { + let resolved = + resolve_executable_path("node", Some(search)).expect("the search must resolve a Node"); + let host_has_other_node = env::split_paths(search) + .any(|directory| !directory.starts_with(nvm_root) && directory.join("node").is_file()); + if host_has_other_node { + assert_ne!( + resolved, + stale_default_bin.join("node"), + "an inferred stale nvm default must not displace a candidate the host already provides" + ); + assert!( + !resolved.starts_with(nvm_root), + "resolution must come from an existing candidate, not the inferred default: {}", + resolved.display() + ); + } else { + assert_eq!( + resolved, + stale_default_bin.join("node"), + "nvm-managed Node stays discoverable when nothing else provides one" + ); + } +} + // The reviewer's regression: a Finder launch with no NVM_BIN, an nvm `default` -// that predates the supported minimum, and a qualified Node the host already -// provides. The inferred default must be discovered, never preferred. +// that predates the supported minimum, and a Node the host already provides. +// The inferred default must be discovered, never preferred. #[test] #[cfg(unix)] fn inferred_nvm_default_cannot_shadow_an_existing_qualified_node() { @@ -302,23 +335,43 @@ fn inferred_nvm_default_cannot_shadow_an_existing_qualified_node() { // inherited terminal PATH would. let qualified = node_fixture(&home.path().join("qualified/node/bin"), "24.22.1"); let qualified_bin = qualified.parent().expect("qualified bin").to_path_buf(); - let path = runtime_search_path_from( + let with_candidate = runtime_search_path_from( Some(home.path().to_path_buf().into()), Some(qualified_bin.to_string_lossy().into_owned().into()), Some(&nvm_root), None, ); - let resolved = resolve_executable_path("node", Some(path.as_os_str())) - .expect("the search must find the qualified Node"); - assert_eq!( - resolved, qualified, - "an inferred stale nvm default must not displace a supported Node" + assert_inferred_nvm_never_displaces_existing( + &nvm_root, + &stale_default, + with_candidate.as_os_str(), ); - let version = Command::new(&resolved) - .arg("--version") - .output() - .expect("run resolved node"); - assert_eq!(String::from_utf8_lossy(&version.stdout).trim(), "v24.22.1"); + + // The ordering guarantee behind that resolution: every non-nvm candidate, + // including the Homebrew entries this App adds, precedes the inferred one. + let paths: Vec<_> = env::split_paths(&with_candidate).collect(); + let position = |candidate: &Path| { + paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + for existing in [ + home.path().join(".local/bin").as_path(), + Path::new("/opt/homebrew/bin"), + Path::new("/usr/local/bin"), + Path::new("/opt/homebrew/opt/node@24/bin"), + Path::new("/usr/local/opt/node@24/bin"), + Path::new("/opt/homebrew/opt/node@22/bin"), + Path::new("/usr/local/opt/node@22/bin"), + qualified_bin.as_path(), + ] { + assert!( + position(existing) < position(&stale_default), + "inferred nvm must stay behind the existing candidate {}", + existing.display() + ); + } // Without any other Node on the host, the same stale default is still the // only candidate, so nvm remains discoverable rather than invisible. @@ -328,13 +381,8 @@ fn inferred_nvm_default_cannot_shadow_an_existing_qualified_node() { Some(&nvm_root), None, ); - let paths: Vec<_> = env::split_paths(&isolated).collect(); - assert!(paths.contains(&stale_default)); - assert_eq!( - resolve_executable_path("node", Some(isolated.as_os_str())), - Some(stale_default.join("node")), - "nvm-managed Node stays discoverable when nothing else provides one" - ); + assert!(env::split_paths(&isolated).any(|directory| directory == stale_default)); + assert_inferred_nvm_never_displaces_existing(&nvm_root, &stale_default, isolated.as_os_str()); } #[test] From c11b466564c881678459c255ee55cf82453530e6 Mon Sep 17 00:00:00 2001 From: Xiao Deshi Date: Sat, 21 Nov 2026 23:07:29 +0800 Subject: [PATCH 4/5] fix(desktop): demote a stale NVM_BIN behind the Node the shell selected MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of the second head found a second precedence regression: an `NVM_BIN` the launching shell exported was always promoted ahead of the inherited PATH, so a terminal that had put a supported Node first after `nvm use` still resolved the stale Node 20 directory and moved `doctor` from exit 0 to exit 1. An exported activation is now authoritative only while it still agrees with the Node the inherited PATH selects: no Node there, or the same executable nvm activated. Otherwise the shell moved on and left the variable behind, so the directory drops to the last resort — behind the discovered `default` alias and the installed versions, which also keeps a newer install ahead of it. Also gate the macOS-only Homebrew entries in the Unix tests behind `cfg(target_os = "macos")`: those six directories are only added by the macOS branch of the search, so asserting them on every Unix platform failed on non-macOS sources. The generic inherited-PATH versus nvm ordering assertions stay for all Unix. Differential against the installed App's private release, same doctor command and search path: | scenario | base | previous head | this head | | --- | --- | --- | --- | | stale NVM_BIN v20, PATH selects v24 | exit 0, node 24.22.1 | exit 1, node 20.18.0 | exit 0, node 24.22.1 | | activation still matches PATH | exit 0, node 24.22.1 | exit 0 | exit 0, node 24.22.1 | | stale default alias + qualified Node | exit 0, node 24.22.1 | exit 0 | exit 0, node 24.22.1 | | nvm-only, supported Node | exit 1, unavailable | exit 0 | exit 0, node 24.22.1 | Disclosed residual case: a host whose only Node is nvm-managed and whose `default` alias predates the supported minimum while a newer version is installed resolves the recorded default first. That is the user's own recorded choice and Core still qualifies the version, so the App reports the real version instead of a missing Node; `nvm alias default` moves it. Signed-off-by: Xiao Deshi --- apps/desktop/loopx-control-plane/README.md | 14 ++- .../src-tauri/src/services.rs | 72 ++++++++--- .../src-tauri/src/services_tests.rs | 118 +++++++++++++----- 3 files changed, 152 insertions(+), 52 deletions(-) diff --git a/apps/desktop/loopx-control-plane/README.md b/apps/desktop/loopx-control-plane/README.md index 5de0d21742..050ca96ee9 100644 --- a/apps/desktop/loopx-control-plane/README.md +++ b/apps/desktop/loopx-control-plane/README.md @@ -319,12 +319,14 @@ including standard Homebrew locations on macOS and nvm-managed Node directories on Unix, without loading interactive shell profiles. Finder launches therefore do not depend on terminal PATH setup. nvm resolution is read-only and never runs nvm or sources a startup file. An `NVM_BIN` the -launching shell exported stays first, keeping the precedence the inherited -PATH already had. nvm locations this App discovers on disk — the recorded -`default` alias, then the installed versions newest-first — are appended last, -behind Homebrew and the inherited PATH, so an inferred stale default cannot -displace a Node the host already provides, while a host whose only Node is -nvm-managed still gets one. Each directory appears once in the search. +launching shell exported stays first while it still matches the Node that PATH +selects; once the shell selects a different Node, the variable is stale and its +directory drops to the last resort, behind every discovered nvm location. nvm +locations this App discovers on disk — the recorded `default` alias, then the +installed versions newest-first — are appended behind Homebrew and the +inherited PATH, so an inferred stale default cannot displace a Node the host +already provides, while a host whose only Node is nvm-managed still gets one. +Each directory appears once in the search. When preparing the first App-owned snapshot, an already selected managed CLI's recorded Python is reused if the App has no interpreter record of its own. This leaves that CLI's launcher and installation owner unchanged. diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs index 2bcdc0f10f..138eec8bb1 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services.rs @@ -1157,25 +1157,51 @@ fn installed_nvm_versions(root: &Path) -> Vec { // services. Resolve the same bounded locations the Lark CLI resolver uses, // without executing nvm or sourcing any startup file. // -// Only an activation inherited from the launching shell (`nvm use`, or a -// terminal-launched App) is explicit intent, and it keeps the precedence the -// inherited PATH already had. Everything this App infers from disk is a -// fallback and must never shadow a candidate the host already provides. +// An activation inherited from the launching shell (`nvm use`, or a +// terminal-launched App) is explicit intent, but only while it still matches +// the Node that PATH selects. A shell can keep a stale `NVM_BIN` after putting +// another Node first, and preferring the stale directory there would replace a +// working Node with an unsupported one. Without that agreement the directory is +// only a fallback, ranked behind every discovered nvm location. #[cfg(unix)] -fn explicit_nvm_directories(nvm_bin: Option<&std::ffi::OsStr>) -> Vec { - let mut directories = Vec::new(); - if let Some(active) = nvm_bin.filter(|value| !value.is_empty()) { - push_tool_directory(&mut directories, PathBuf::from(active)); +fn explicit_nvm_directories( + nvm_bin: Option<&std::ffi::OsStr>, + inherited: Option<&std::ffi::OsStr>, +) -> Vec { + let Some(active) = nvm_bin.filter(|value| !value.is_empty()) else { + return Vec::new(); + }; + let directory = PathBuf::from(active); + if !nvm_bin_agrees_with_inherited_node(&directory, inherited) { + return Vec::new(); } + let mut directories = Vec::new(); + push_tool_directory(&mut directories, directory); directories } +// `NVM_BIN` agrees when the inherited PATH has no Node of its own, or when the +// Node it resolves to is the same executable nvm activated. Anything else means +// the shell moved on and left the variable behind. +#[cfg(unix)] +fn nvm_bin_agrees_with_inherited_node(nvm_bin: &Path, inherited: Option<&std::ffi::OsStr>) -> bool { + match resolve_executable_path("node", inherited) { + Some(inherited_node) => paths_refer_to_same_file( + &inherited_node.to_string_lossy(), + &nvm_bin.join("node").to_string_lossy(), + ), + None => true, + } +} + // Discovered, never activated: the recorded `default` alias first, then the // installed versions newest-first. Appended behind the known runtimes and the // inherited PATH, so a stale default cannot hide a supported Homebrew or -// inherited Node, and a host without any other Node still finds nvm. +// inherited Node, and a host without any other Node still finds nvm. A +// demoted `NVM_BIN` ranks last: it is an explicit location the host no longer +// selects, so a newer installed version must win before it. #[cfg(unix)] -fn discovered_nvm_directories(nvm_root: &Path) -> Vec { +fn discovered_nvm_directories(nvm_root: &Path, demoted_nvm_bin: Option<&Path>) -> Vec { let mut directories = Vec::new(); if let Some(version) = resolve_nvm_alias(nvm_root, "default", 0) { push_tool_directory( @@ -1189,6 +1215,9 @@ fn discovered_nvm_directories(nvm_root: &Path) -> Vec { nvm_root.join("versions/node").join(version).join("bin"), ); } + if let Some(demoted) = demoted_nvm_bin { + push_tool_directory(&mut directories, demoted.to_path_buf()); + } directories } @@ -1249,10 +1278,17 @@ fn runtime_search_path_from( paths.push(PathBuf::from(home).join(".local/bin")); } // An activation the launching shell exported keeps the precedence the - // inherited PATH already gave it. + // inherited PATH already gave it, but only while it still agrees with the + // Node that PATH selects. #[cfg(unix)] - if let Some(nvm_bin) = nvm_bin { - extend_unique(&mut paths, explicit_nvm_directories(Some(nvm_bin))); + let explicit_nvm_bin = nvm_bin.and_then(|nvm_bin| { + explicit_nvm_directories(Some(nvm_bin), inherited.as_deref()) + .into_iter() + .next() + }); + #[cfg(unix)] + if let Some(nvm_bin) = explicit_nvm_bin.as_deref() { + extend_unique(&mut paths, [nvm_bin.to_path_buf()]); } if cfg!(target_os = "macos") { extend_unique( @@ -1271,8 +1307,16 @@ fn runtime_search_path_from( ], ); } + // A `NVM_BIN` the host no longer selects is demoted to the last resort, + // behind the discovered versions so a newer install still wins over it. + #[cfg(unix)] + let demoted_nvm_bin = nvm_bin + .filter(|nvm_bin| explicit_nvm_bin.as_deref() != Some(Path::new(nvm_bin))) + .map(PathBuf::from); #[cfg(unix)] - let discovered = nvm_root.map(discovered_nvm_directories).unwrap_or_default(); + let discovered = nvm_root + .map(|nvm_root| discovered_nvm_directories(nvm_root, demoted_nvm_bin.as_deref())) + .unwrap_or_default(); extend_unique( &mut paths, inherited diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs index a98edbfae9..0c77b5e718 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs @@ -199,16 +199,18 @@ fn finder_runtime_path_finds_nvm_managed_node() { assert!(paths.contains(&default_bin)); // Inferred nvm is the last resort: behind every candidate the host already // provides, and behind the inherited PATH a terminal launch contributes. - for existing in [ + // The Homebrew entries are only added on macOS, so they are asserted there. + let mut existing: Vec<&Path> = vec![Path::new("/usr/bin"), Path::new("/bin")]; + #[cfg(target_os = "macos")] + existing.extend([ Path::new("/opt/homebrew/bin"), Path::new("/usr/local/bin"), Path::new("/opt/homebrew/opt/node@24/bin"), Path::new("/usr/local/opt/node@24/bin"), Path::new("/opt/homebrew/opt/node@22/bin"), Path::new("/usr/local/opt/node@22/bin"), - Path::new("/usr/bin"), - Path::new("/bin"), - ] { + ]); + for existing in existing { assert!( position(existing) < position(&default_bin), "inferred nvm must stay behind the existing candidate {}", @@ -246,46 +248,95 @@ fn finder_runtime_path_finds_nvm_managed_node() { assert_eq!(again, path, "tool search must be idempotent"); } +// A terminal activation is authoritative only while it still matches the Node +// the inherited PATH selects. A shell that put another Node first after `nvm +// use` leaves a stale `NVM_BIN` behind, and preferring it would replace a +// working Node with an unsupported one. #[test] #[cfg(unix)] -fn explicit_nvm_activation_keeps_terminal_launch_precedence() { +fn stale_nvm_bin_yields_to_the_node_the_shell_selected() { let home = tempfile::tempdir().expect("home fixture"); let nvm_root = nvm_fixture(&home.path().join(".nvm"), "v24.22.1"); - let activated = nvm_root.join("versions/node/v20.18.0/bin"); - assert_eq!( - explicit_nvm_directories(Some(activated.as_os_str())), - vec![activated.clone()], - "an activation exported by the launching shell is explicit intent" + let stale = nvm_root.join("versions/node/v20.18.0/bin"); + node_fixture(&stale, "20.18.0"); + let selected = node_fixture(&home.path().join("selected/node/bin"), "24.22.1"); + let selected_bin = selected.parent().expect("selected bin").to_path_buf(); + + // Still the selected Node: the activation keeps terminal-launch precedence. + let agreed = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some(selected_bin.to_string_lossy().into_owned().into()), + Some(&nvm_root), + Some(selected_bin.as_os_str()), ); - assert!( - explicit_nvm_directories(None).is_empty(), - "without an activation nothing is explicit" + let agreed_paths: Vec<_> = env::split_paths(&agreed).collect(); + let position = |candidate: &Path| { + agreed_paths + .iter() + .position(|p| p == candidate) + .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) + }; + assert_eq!( + position(selected_bin.as_path()), + 1, + "an activation that still matches the selected Node keeps its precedence" ); - assert!( - explicit_nvm_directories(Some(std::ffi::OsStr::new("/absent/bin"))).is_empty(), - "a stale NVM_BIN contributes nothing" + assert_eq!( + resolve_executable_path("node", Some(agreed.as_os_str())), + Some(selected.clone()), + "the selected Node still wins" ); - let path = runtime_search_path_from( + + // No longer the selected Node: the stale directory becomes a last resort. + let stale_nvm_bin = stale.as_os_str(); + let demoted = runtime_search_path_from( Some(home.path().to_path_buf().into()), - Some("/usr/bin:/bin".into()), + Some(selected_bin.to_string_lossy().into_owned().into()), Some(&nvm_root), - Some(activated.as_os_str()), + Some(stale_nvm_bin), ); - let paths: Vec<_> = env::split_paths(&path).collect(); - let position = |candidate: &Path| { - paths + let demoted_paths: Vec<_> = env::split_paths(&demoted).collect(); + let demoted_position = |candidate: &Path| { + demoted_paths .iter() .position(|p| p == candidate) .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) }; + assert!( + demoted_position(selected_bin.as_path()) < demoted_position(&stale), + "a stale NVM_BIN must not precede the Node the shell selected" + ); + assert!( + demoted_position(&nvm_root.join("versions/node/v24.22.1/bin")) < demoted_position(&stale), + "a newer installed version outranks a demoted NVM_BIN" + ); assert_eq!( - position(&activated), - 1, - "an exported activation keeps the precedence the inherited PATH already had" + resolve_executable_path("node", Some(demoted.as_os_str())), + Some(selected.clone()), + "the stale NVM_BIN must not displace the selected Node" + ); + + // Nothing else on the PATH: the activation is the only candidate, so it + // stays authoritative and nvm-only hosts keep working. + let only_nvm = runtime_search_path_from( + Some(home.path().to_path_buf().into()), + Some("/usr/bin:/bin".into()), + Some(&nvm_root), + Some(stale_nvm_bin), + ); + let only_nvm_paths: Vec<_> = env::split_paths(&only_nvm).collect(); + assert!( + only_nvm_paths.contains(&stale), + "an activation with no competing Node stays in the search" + ); + let mut unique = only_nvm_paths.clone(); + unique.sort(); + unique.dedup(); + assert_eq!( + unique.len(), + only_nvm_paths.len(), + "no duplicate directories" ); - assert!(position(&activated) < position(Path::new("/opt/homebrew/bin"))); - // The same activation is also an installed version, so it must not repeat. - assert_eq!(paths.iter().filter(|p| *p == &activated).count(), 1); } // An inferred nvm candidate may only be selected when no other candidate @@ -356,16 +407,19 @@ fn inferred_nvm_default_cannot_shadow_an_existing_qualified_node() { .position(|p| p == candidate) .unwrap_or_else(|| panic!("{} missing from tool search", candidate.display())) }; - for existing in [ - home.path().join(".local/bin").as_path(), + // The Homebrew entries only exist on macOS, so they are asserted there. + let local_bin = home.path().join(".local/bin"); + let mut existing: Vec<&Path> = vec![local_bin.as_path(), qualified_bin.as_path()]; + #[cfg(target_os = "macos")] + existing.extend([ Path::new("/opt/homebrew/bin"), Path::new("/usr/local/bin"), Path::new("/opt/homebrew/opt/node@24/bin"), Path::new("/usr/local/opt/node@24/bin"), Path::new("/opt/homebrew/opt/node@22/bin"), Path::new("/usr/local/opt/node@22/bin"), - qualified_bin.as_path(), - ] { + ]); + for existing in existing { assert!( position(existing) < position(&stale_default), "inferred nvm must stay behind the existing candidate {}", From f3ad36a0c0e7a8a0ad1a7e0fc35be000768d5abe Mon Sep 17 00:00:00 2001 From: Xiao Deshi Date: Sat, 21 Nov 2026 23:23:59 +0800 Subject: [PATCH 5/5] test(desktop): keep the stale NVM_BIN oracle host-independent The CI macOS runner ships a real Node at /opt/homebrew/bin, which the search ranks ahead of the inherited PATH. The new test therefore resolved that Node instead of the fixture's selected one and failed on the runner while passing locally. Assert the rule, not a specific winner: with a host candidate present the resolved Node must be that candidate, and only when none exists may a demoted `NVM_BIN` be selected at all. The PATH-order guarantees (an agreeing activation at position 1, a demoted one behind the selected Node and behind the newer installed version) stay host-independent. Verified locally with and without a simulated /opt/homebrew/bin/node. Signed-off-by: Xiao Deshi --- .../src-tauri/src/services_tests.rs | 39 ++++++++++++++----- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs index 0c77b5e718..55fee497a3 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/services_tests.rs @@ -281,11 +281,7 @@ fn stale_nvm_bin_yields_to_the_node_the_shell_selected() { 1, "an activation that still matches the selected Node keeps its precedence" ); - assert_eq!( - resolve_executable_path("node", Some(agreed.as_os_str())), - Some(selected.clone()), - "the selected Node still wins" - ); + assert_demoted_nvm_bin_is_last_resort(&nvm_root, &stale, agreed.as_os_str()); // No longer the selected Node: the stale directory becomes a last resort. let stale_nvm_bin = stale.as_os_str(); @@ -310,11 +306,7 @@ fn stale_nvm_bin_yields_to_the_node_the_shell_selected() { demoted_position(&nvm_root.join("versions/node/v24.22.1/bin")) < demoted_position(&stale), "a newer installed version outranks a demoted NVM_BIN" ); - assert_eq!( - resolve_executable_path("node", Some(demoted.as_os_str())), - Some(selected.clone()), - "the stale NVM_BIN must not displace the selected Node" - ); + assert_demoted_nvm_bin_is_last_resort(&nvm_root, &stale, demoted.as_os_str()); // Nothing else on the PATH: the activation is the only candidate, so it // stays authoritative and nvm-only hosts keep working. @@ -372,6 +364,33 @@ fn assert_inferred_nvm_never_displaces_existing( } } +// A demoted `NVM_BIN` may only be selected when nothing else can be: a Node +// the host provides, or a newer nvm install, must win first. The oracle reads +// the host instead of assuming which candidate that is. +#[cfg(unix)] +fn assert_demoted_nvm_bin_is_last_resort( + nvm_root: &Path, + stale_bin: &Path, + search: &std::ffi::OsStr, +) { + let resolved = + resolve_executable_path("node", Some(search)).expect("the search must resolve a Node"); + let host_candidate = env::split_paths(search) + .find(|directory| !directory.starts_with(nvm_root) && directory.join("node").is_file()); + match host_candidate { + Some(directory) => assert_eq!( + resolved, + directory.join("node"), + "a demoted NVM_BIN must yield to the Node the host provides" + ), + None => assert_ne!( + resolved, + stale_bin.join("node"), + "a demoted NVM_BIN may only be selected when nothing else can be" + ), + } +} + // The reviewer's regression: a Finder launch with no NVM_BIN, an nvm `default` // that predates the supported minimum, and a Node the host already provides. // The inferred default must be discovered, never preferred.