Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(desktop): start the Runtime with the login shell PATH on macOS (#2379)

Maxfa003991f35e
diff --git a/desktop/README.md b/desktop/README.md
index b285d588e..a4bfcf4e2 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -26,6 +26,18 @@ product logic.
window onto the Workbench; plain `vibe start` honours
`config.ui.open_browser` and would leave the user with a second,
browser-hosted view of the same Runtime.
+
+ On macOS that start inherits the `PATH` of the user's login shell rather than
+ launchd's minimal application `PATH`, so tools installed through nvm, npm, or
+ Homebrew resolve exactly as they do in a terminal. The shell runs `$SHELL -l
+ -i -c` once per start, reads only `PATH`, and keeps its own `PATH` when that
+ shell fails or takes longer than 10 seconds. A private Runtime still puts its
+ own `bin` and Node directories first. Discovery and the lifecycle verbs do
+ not consult the login shell, so adopting a running Runtime never waits on it.
+ The lookup runs on a blocking thread before the launch-state lock is taken, so
+ a concurrent Stop is not held for that budget. A successful lookup lets the
+ shell finish its logout hooks within the remaining time; only a fallback
+ (or a logout that itself hangs) ends the process group.
5. Polls until the Runtime is ready or the bound expires, then navigates. The
window never leaves the bootstrap page before combined readiness succeeds.
If the launcher it started exits non-zero, it gives up immediately instead of
diff --git a/desktop/runtime-host/src/bootstrap.rs b/desktop/runtime-host/src/bootstrap.rs
index 2fd097ee1..00d25a7f3 100644
--- a/desktop/runtime-host/src/bootstrap.rs
+++ b/desktop/runtime-host/src/bootstrap.rs
@@ -468,6 +468,11 @@ impl RuntimeHost {
);
};
+ // The login-shell PATH lookup can wait 10 s on a hanging startup file.
+ // It runs here, on a blocking thread, before the launch-state mutex is
+ // taken, so a concurrent recovery or stop is not held for that budget.
+ let prepared = launcher.clone();
+ let _ = tokio::task::spawn_blocking(move || prepared.prepare_launch()).await;
// The lock makes the decision and launch atomic, so concurrent runs
// cannot both start the Runtime.
if let Err(error) = self.launch_if_needed(launcher.clone(), trigger.allows_handover()) {
@@ -782,6 +787,7 @@ fn publish(sink: &dyn StatusSink, status: BootstrapStatus) -> BootstrapStatus {
mod tests {
use super::*;
use crate::launcher::LaunchWatch;
+ use crate::status::BootstrapPhase;
use std::sync::atomic::{AtomicUsize, Ordering};
const ORIGIN: &str = "http://127.0.0.1:5123";
@@ -789,6 +795,9 @@ mod tests {
/// This app's Runtime, ready.
struct MineProbe;
+ /// Nothing serving the origin: bootstrap will try to start one.
+ struct AbsentProbe;
+
#[async_trait::async_trait]
impl HealthProbe for MineProbe {
async fn presence(&self, _origin: &LoopbackOrigin, _expected: Option<&str>) -> Presence {
@@ -796,10 +805,18 @@ mod tests {
}
}
+ #[async_trait::async_trait]
+ impl HealthProbe for AbsentProbe {
+ async fn presence(&self, _origin: &LoopbackOrigin, _expected: Option<&str>) -> Presence {
+ Presence::Absent
+ }
+ }
+
#[derive(Default)]
struct CountingLauncher {
launches: AtomicUsize,
stops: AtomicUsize,
+ prepares: AtomicUsize,
}
impl RuntimeLauncher for CountingLauncher {
@@ -813,6 +830,10 @@ mod tests {
Ok(LoopbackOrigin::parse(ORIGIN).expect("test origin"))
}
+ fn prepare_launch(&self) {
+ self.prepares.fetch_add(1, Ordering::SeqCst);
+ }
+
fn launch(&self, _hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
self.launches.fetch_add(1, Ordering::SeqCst);
Ok(LaunchedRuntime {
@@ -869,6 +890,46 @@ mod tests {
assert!(!host.launched_runtime().runtime_may_be_running);
}
+ /// Resolves to itself so a bootstrap run can reach `prepare_launch`.
+ struct PreparingLauncher {
+ inner: Arc<CountingLauncher>,
+ }
+
+ impl RuntimeLauncher for PreparingLauncher {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ Ok(Arc::new(self.inner.clone()))
+ }
+ }
+
+ /// The login-shell PATH lookup lives in `prepare_launch`, which bootstrap
+ /// runs on a blocking thread before taking the launch-state mutex. A Stop
+ /// that already holds that mutex therefore still lets the lookup finish,
+ /// and still fences the spawn itself.
+ #[tokio::test]
+ async fn prepare_launch_runs_before_the_launch_state_mutex_is_taken() {
+ let counting = Arc::new(CountingLauncher::default());
+ let host = RuntimeHost::new(
+ Arc::new(AbsentProbe),
+ Arc::new(PreparingLauncher {
+ inner: counting.clone(),
+ }),
+ RuntimeHostSettings {
+ origin_override: None,
+ ready_timeout: Duration::from_millis(10),
+ poll_interval: Duration::from_millis(1),
+ probe_timeout: Duration::from_millis(10),
+ },
+ );
+ host.launched_runtime().stopping = true;
+
+ let status = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+
+ assert_eq!(counting.prepares.load(Ordering::SeqCst), 1);
+ assert_eq!(counting.launches.load(Ordering::SeqCst), 0);
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::RuntimeSpawnFailed);
+ }
+
#[test]
fn production_discovers_the_origin_from_the_installed_runtime() {
let settings = RuntimeHostSettings::default();
diff --git a/desktop/runtime-host/src/launcher.rs b/desktop/runtime-host/src/launcher.rs
index b05bbc96b..e075063d8 100644
--- a/desktop/runtime-host/src/launcher.rs
+++ b/desktop/runtime-host/src/launcher.rs
@@ -21,6 +21,7 @@ use std::time::{Duration, Instant};
use serde::Deserialize;
use crate::bootstrap_log::BootstrapLog;
+use crate::login_path::{login_shell_path, LoginPath};
use crate::origin::LoopbackOrigin;
use crate::private_runtime::{InstalledPrivateRuntime, PrivateRuntimeBundle, PrivateRuntimeError};
use crate::status::BootstrapNoticeCode;
@@ -194,6 +195,11 @@ pub trait RuntimeLauncher: Send + Sync {
/// spawned; readiness is decided by the presence probe.
pub trait ResolvedRuntimeLauncher: Send + Sync {
fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError>;
+ /// Work that must happen before `launch` and that must not hold the
+ /// launch-state mutex: the login-shell `PATH` lookup, which can wait 10 s
+ /// on a hanging startup file. The default is a no-op so a test launcher
+ /// that never starts a Runtime does not wait on the user's shell.
+ fn prepare_launch(&self) {}
/// `hand_over` lets the start replace another desktop Runtime serving this
/// home. The start owns that act and reports it in its exit.
fn launch(&self, hand_over: bool) -> Result<LaunchedRuntime, LaunchError>;
@@ -385,7 +391,6 @@ impl RuntimeLauncher for BundledVibeLauncher {
runtime.npm_cli,
self.backend_root.clone(),
&runtime_id,
- env::var_os("PATH").as_deref(),
),
expected_runtime_id: Some(runtime_id),
cleanup: Some((self.bundle.clone(), runtime.root)),
@@ -443,13 +448,18 @@ impl ResolvedRuntimeLauncher for ResolvedVibeExecutable {
query_endpoint(&self.command, &self.log)
}
+ fn prepare_launch(&self) {
+ let _ = cached_login_path(&self.log);
+ }
+
fn launch(&self, hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
// Only this shell's own Runtime is started by a CLI of its version,
// which knows the flag and exits by the handover contract.
let identified = self.expected_runtime_id.is_some();
let hand_over = hand_over && identified;
+ let login_path = cached_login_path(&self.log);
let started = Instant::now();
- let child = spawn_detached(&self.command, hand_over).map_err(LaunchError::Spawn)?;
+ let child = spawn_detached(&self.command, hand_over, login_path).map_err(LaunchError::Spawn)?;
let pid = child.id();
let watch = LaunchWatch::default();
@@ -511,6 +521,9 @@ struct RuntimeCommand {
executable: PathBuf,
prefix_args: Vec<OsString>,
environment: Vec<(OsString, OsString)>,
+ /// Directories that lead `PATH`, ahead of whatever `PATH` the command
+ /// inherits. Empty for an installed Runtime.
+ path_prefix: Vec<PathBuf>,
/// Whether the shell's own `PYTHON*` variables are withheld from the child.
///
/// Only the private Runtime sets this. `-I` protects just the interpreter
@@ -529,6 +542,7 @@ impl RuntimeCommand {
executable,
prefix_args: Vec::new(),
environment: Vec::new(),
+ path_prefix: Vec::new(),
withholds_inherited_python: false,
}
}
@@ -540,17 +554,11 @@ impl RuntimeCommand {
npm_cli: PathBuf,
backends_root: PathBuf,
runtime_id: &str,
- inherited_path: Option<&OsStr>,
) -> Self {
- let tools_dir = node.parent().expect("validated private Node has a parent");
+ let tools_dir = node.parent().expect("validated private Node has a parent").to_owned();
// The builder includes a relocatable vibe entry point in bin. Expose
// only that directory, never python/bin (which would shadow user tools).
let cli_dir = runtime_root.join("bin");
- let mut path_entries = vec![cli_dir.clone(), tools_dir.to_owned()];
- if let Some(path) = inherited_path {
- path_entries.extend(env::split_paths(path).filter(|entry| !entry.as_os_str().is_empty()));
- }
- let private_path = env::join_paths(path_entries).unwrap_or_else(|_| cli_dir.into_os_string());
Self {
executable: python,
// Isolated mode excludes the user site and PYTHONPATH. The Avibe
@@ -570,7 +578,6 @@ impl RuntimeCommand {
OsString::from("vibe"),
],
environment: vec![
- (OsString::from("PATH"), private_path),
(OsString::from("VIBE_SHOW_RUNTIME_NODE_BIN"), node.into_os_string()),
(OsString::from(DESKTOP_NPM_CLI_ENV), npm_cli.into_os_string()),
(
@@ -585,13 +592,48 @@ impl RuntimeCommand {
// what covers this process itself.
(OsString::from("PYTHONDONTWRITEBYTECODE"), OsString::from("1")),
],
+ path_prefix: vec![cli_dir, tools_dir],
withholds_inherited_python: true,
}
}
- fn apply(&self, command: &mut Command) {
+ /// Applies this command's arguments and environment. `inherited_path` is
+ /// the `PATH` the command would otherwise inherit; `None` means this
+ /// process's own.
+ fn apply(&self, command: &mut Command, inherited_path: Option<&OsStr>) {
command.args(&self.prefix_args);
self.apply_environment(command, env::vars_os());
+ if self.path_prefix.is_empty() {
+ // Nothing to put in front: the command gets the PATH it was given,
+ // or keeps this process's own, byte for byte.
+ if let Some(path) = inherited_path {
+ command.env("PATH", path);
+ }
+ return;
+ }
+ let inherited_path = inherited_path.map(OsStr::to_owned).or_else(|| env::var_os("PATH"));
+ if let Some(path) = self.path(inherited_path.as_deref()) {
+ command.env("PATH", path);
+ }
+ }
+
+ /// `path_prefix` ahead of `inherited`, or `None` when there is neither.
+ ///
+ /// Only a private Runtime has a prefix. Empty entries, which name the
+ /// current directory, are dropped as they always were for it.
+ fn path(&self, inherited: Option<&OsStr>) -> Option<OsString> {
+ let mut entries = self.path_prefix.clone();
+ if let Some(inherited) = inherited {
+ entries.extend(env::split_paths(inherited).filter(|entry| !entry.as_os_str().is_empty()));
+ }
+ if entries.is_empty() {
+ return None;
+ }
+ // An entry that cannot be joined (one containing the separator) is a
+ // PATH the user cannot have been running with; keep only the prefix.
+ env::join_paths(&entries)
+ .or_else(|_| env::join_paths(&self.path_prefix))
+ .ok()
}
/// The environment half of `apply`, over an explicit inherited set.
@@ -679,7 +721,7 @@ fn endpoint_descriptor(
stderr_slot: &mut Option<mpsc::Receiver<Vec<u8>>>,
) -> Result<LoopbackOrigin, LaunchError> {
let mut command = Command::new(&runtime.executable);
- runtime.apply(&mut command);
+ runtime.apply(&mut command, None);
command
.args(ENDPOINT_ARGS)
.stdin(Stdio::null())
@@ -965,8 +1007,39 @@ fn is_executable(_metadata: &std::fs::Metadata) -> bool {
true
}
-fn spawn_detached(runtime: &RuntimeCommand, hand_over: bool) -> std::io::Result<std::process::Child> {
- let mut command = lifecycle_command(runtime, &START_ARGS);
+/// The `PATH` the Runtime about to be started inherits, recorded once.
+///
+/// Only the start needs it: it is the one command whose process outlives this
+/// call and runs the user's agents. Discovery and the lifecycle verbs keep the
+/// shell's own `PATH`, so adopting a running Runtime never waits on the user's
+/// shell startup files. Cached so `prepare_launch` can run the lookup off the
+/// launch-state mutex and `launch` can reuse the result without asking again.
+fn cached_login_path(log: &BootstrapLog) -> &'static LoginPath {
+ static LOGIN_PATH: OnceLock<LoginPath> = OnceLock::new();
+ LOGIN_PATH.get_or_init(|| {
+ let started = Instant::now();
+ let login_path = login_shell_path();
+ log.record(
+ "runtime.login_path",
+ &[
+ ("outcome", login_path.outcome().to_owned()),
+ ("ms", started.elapsed().as_millis().to_string()),
+ ],
+ );
+ login_path
+ })
+}
+
+fn spawn_detached(
+ runtime: &RuntimeCommand,
+ hand_over: bool,
+ login_path: &LoginPath,
+) -> std::io::Result<std::process::Child> {
+ let inherited_path = match login_path {
+ LoginPath::Resolved(path) => Some(path.as_os_str()),
+ LoginPath::Inherited(_) => None,
+ };
+ let mut command = lifecycle_command(runtime, &START_ARGS, inherited_path);
if hand_over {
command.arg(HAND_OVER_ARG);
}
@@ -986,7 +1059,7 @@ fn stop_arguments(runtime_id: &str) -> [&str; 3] {
/// caller would then act against services that are still alive.
fn run_lifecycle_verb(runtime: &RuntimeCommand, args: &[&str], log: &BootstrapLog, event: &str) -> CliOutcome {
let started = Instant::now();
- let mut command = lifecycle_command(runtime, args);
+ let mut command = lifecycle_command(runtime, args, None);
// The verdict is on stderr. It stays in this process and the log.
command.stderr(Stdio::piped());
let mut child = match command.spawn() {
@@ -1049,9 +1122,9 @@ fn last_json_string(stderr: &[u8], field: &str) -> String {
.unwrap_or_else(|| "unknown".to_owned())
}
-fn lifecycle_command(runtime: &RuntimeCommand, args: &[&str]) -> Command {
+fn lifecycle_command(runtime: &RuntimeCommand, args: &[&str], inherited_path: Option<&OsStr>) -> Command {
let mut command = Command::new(&runtime.executable);
- runtime.apply(&mut command);
+ runtime.apply(&mut command, inherited_path);
command
.args(args)
// Nothing the Runtime prints may reach the shell, and therefore the WebView.
@@ -1162,10 +1235,11 @@ mod tests {
executable: PathBuf::from("/test-owned/Runtime Root/python"),
prefix_args: vec![OsString::from("-m"), OsString::from("vibe")],
environment: vec![(OsString::from("AVIBE_DESKTOP_MANAGED_RUNTIME"), OsString::from("1"))],
+ path_prefix: Vec::new(),
withholds_inherited_python: true,
};
let runtime_id = "b".repeat(64);
- let command = lifecycle_command(&runtime, &stop_arguments(&runtime_id));
+ let command = lifecycle_command(&runtime, &stop_arguments(&runtime_id), None);
assert_eq!(command.get_program(), runtime.executable.as_os_str());
assert_eq!(
command.get_args().collect::<Vec<_>>(),
@@ -1772,7 +1846,6 @@ mod tests {
tree.join("tools/npm/bin/npm-cli.js"),
dir.join("backends"),
&"a".repeat(64),
- env::var_os("PATH").as_deref(),
);
let mut process = Command::new(&command.executable);
for (name, value) in &command.environment {
@@ -1829,7 +1902,6 @@ mod tests {
tree.join("tools/npm/bin/npm-cli.js"),
dir.join("backends"),
&"a".repeat(64),
- env::var_os("PATH").as_deref(),
);
let inherited = [
(
@@ -2145,7 +2217,15 @@ mod tests {
npm_cli,
backends_root,
&"a".repeat(64),
- Some(&inherited),
+ );
+ let path_entries: Vec<_> = env::split_paths(&command.path(Some(&inherited)).expect("private PATH")).collect();
+ assert_eq!(
+ path_entries,
+ [
+ runtime_root.join("bin"),
+ node.parent().unwrap().to_owned(),
+ PathBuf::from("/usr/bin")
+ ]
);
assert_eq!(command.executable, python);
@@ -2159,15 +2239,9 @@ mod tests {
]
);
let environment: std::collections::HashMap<_, _> = command.environment.into_iter().collect();
- let path_entries: Vec<_> =
- env::split_paths(environment.get(OsStr::new("PATH")).expect("private PATH")).collect();
- assert_eq!(
- path_entries,
- [
- runtime_root.join("bin"),
- node.parent().unwrap().to_owned(),
- PathBuf::from("/usr/bin")
- ]
+ assert!(
+ !environment.contains_key(OsStr::new("PATH")),
+ "PATH is composed per command, from the PATH that command inherits"
);
assert_eq!(
environment.get(OsStr::new("VIBE_SHOW_RUNTIME_NODE_BIN")),
@@ -2198,4 +2272,82 @@ mod tests {
Some(&OsString::from("1"))
);
}
+ /// The Runtime a desktop launch starts must see the PATH the user's login
+ /// shell has, not the one launchd gave the application: an npm-installed
+ /// backend is a `#!/usr/bin/env node` script, and nvm's `node` is only on
+ /// the former (#2378).
+ #[cfg(unix)]
+ #[test]
+ fn the_runtime_start_inherits_the_login_shell_path() {
+ let dir = scratch_dir("login-path");
+ let recording = dir.join("path");
+ let executable = write_fake_runtime(
+ &dir,
+ &format!("#!/bin/sh\nprintf '%s' \"$PATH\" > \"{}\"\n", recording.display()),
+ );
+ let runtime = RuntimeCommand::installed(executable);
+ let login_path = env::join_paths(["/login/nvm/bin", "/usr/bin", "/bin"]).expect("PATH");
+
+ let mut child = spawn_detached(&runtime, false, &LoginPath::Resolved(login_path.clone())).expect("start");
+ child.wait().expect("fake start exits");
+
+ assert_eq!(wait_for_file(&recording), login_path.to_string_lossy());
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn a_private_runtime_keeps_its_own_tools_ahead_of_the_login_shell_path() {
+ let runtime = RuntimeCommand::private(
+ PathBuf::from("/private/runtime"),
+ PathBuf::from("/private/runtime/python/bin/python3"),
+ PathBuf::from("/private/runtime/tools/bin/node"),
+ PathBuf::from("/private/runtime/tools/npm/bin/npm-cli.js"),
+ PathBuf::from("/private/backends"),
+ &"a".repeat(64),
+ );
+ let login_path = env::join_paths(["/login/nvm/bin", "/usr/bin"]).expect("PATH");
+
+ let command = lifecycle_command(&runtime, &START_ARGS, Some(&login_path));
+
+ let path = command
+ .get_envs()
+ .find_map(|(name, value)| (name == "PATH").then_some(value))
+ .flatten()
+ .expect("the start sets PATH");
+ assert_eq!(
+ env::split_paths(path).collect::<Vec<_>>(),
+ [
+ PathBuf::from("/private/runtime/bin"),
+ PathBuf::from("/private/runtime/tools/bin"),
+ PathBuf::from("/login/nvm/bin"),
+ PathBuf::from("/usr/bin"),
+ ]
+ );
+ }
+
+ #[test]
+ fn an_installed_runtime_inherits_path_verbatim() {
+ let runtime = RuntimeCommand::installed(PathBuf::from("/test-owned/vibe"));
+ let path_override = |command: &Command| {
+ command
+ .get_envs()
+ .find_map(|(name, value)| (name == "PATH").then(|| value.map(OsStr::to_owned)))
+ };
+
+ // Discovery, the lifecycle verbs, and a start whose login PATH could
+ // not be read leave this process's PATH untouched.
+ assert_eq!(path_override(&lifecycle_command(&runtime, &START_ARGS, None)), None);
+ assert_eq!(
+ path_override(&lifecycle_command(&runtime, &stop_arguments(&"b".repeat(64)), None)),
+ None
+ );
+
+ // A login PATH is passed on as the shell printed it, empty entries
+ // (the current directory) included.
+ let login_path = OsString::from(":/login/bin::/usr/bin:");
+ assert_eq!(
+ path_override(&lifecycle_command(&runtime, &START_ARGS, Some(&login_path))),
+ Some(Some(login_path))
+ );
+ }
}
diff --git a/desktop/runtime-host/src/lib.rs b/desktop/runtime-host/src/lib.rs
index dab8568fc..983e417ad 100644
--- a/desktop/runtime-host/src/lib.rs
+++ b/desktop/runtime-host/src/lib.rs
@@ -26,6 +26,7 @@ pub mod deep_link;
pub mod download;
pub mod health;
pub mod launcher;
+pub mod login_path;
pub mod notifications;
pub mod origin;
pub mod private_runtime;
diff --git a/desktop/runtime-host/src/login_path.rs b/desktop/runtime-host/src/login_path.rs
new file mode 100644
index 000000000..40d5899cb
--- /dev/null
+++ b/desktop/runtime-host/src/login_path.rs
@@ -0,0 +1,396 @@
+//! The `PATH` the user's terminal would give the Runtime.
+//!
+//! macOS starts an application from Finder, the Dock, or Launchpad with
+//! launchd's minimal `PATH` (`/usr/bin:/bin:/usr/sbin:/sbin`). Version managers
+//! such as nvm extend `PATH` only in shell startup files, so a Runtime started
+//! with the application's own `PATH` cannot run any `#!/usr/bin/env node`
+//! launcher: an npm-installed Codex or Claude Code fails on every run, while the
+//! same Runtime started from a terminal works.
+//!
+//! The shell therefore asks the user's login shell, once per Runtime start, what
+//! `PATH` it ends up with, the same way editors that start language servers do.
+//! Nothing here is required for the Runtime to start: every failure leaves the
+//! application's own `PATH` in place, which is exactly the behaviour before this
+//! lookup existed.
+
+use std::ffi::OsString;
+#[cfg(target_os = "macos")]
+use std::{
+ io::Read,
+ path::Path,
+ process::{Command, Stdio},
+ sync::mpsc,
+ time::{Duration, Instant},
+};
+
+/// How long the login shell may take to print its `PATH`.
+///
+/// Startup files that load nvm, conda, or a prompt framework commonly take one
+/// or two seconds. The budget is only spent in full when a startup file waits
+/// for input or hangs, and the cost of that is the old `PATH`, not a failed
+/// start.
+#[cfg(target_os = "macos")]
+pub const LOGIN_PATH_TIMEOUT: Duration = Duration::from_secs(10);
+
+/// The shell macOS gives a new account, used when `SHELL` is not usable.
+#[cfg(target_os = "macos")]
+const DEFAULT_SHELL: &str = "/bin/zsh";
+
+#[cfg(target_os = "macos")]
+const START_MARKER: &[u8] = b"__AVIBE_LOGIN_PATH_START__";
+#[cfg(target_os = "macos")]
+const END_MARKER: &[u8] = b"__AVIBE_LOGIN_PATH_END__";
+
+/// Startup files may print banners, so the value is fenced by markers. The
+/// commands are absolute and the arguments need no quoting, so sh, bash, zsh,
+/// fish, and nushell all run it as written.
+#[cfg(target_os = "macos")]
+const PRINT_PATH_SCRIPT: &str = "/usr/bin/printf %s __AVIBE_LOGIN_PATH_START__; /usr/bin/printenv PATH; \
+ /usr/bin/printf %s __AVIBE_LOGIN_PATH_END__";
+
+/// Startup output is not read past this; a `PATH` is far smaller.
+#[cfg(target_os = "macos")]
+const MAX_OUTPUT_BYTES: usize = 256 * 1024;
+
+/// What the Runtime start will use as its inherited `PATH`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum LoginPath {
+ /// The `PATH` the user's login shell ends up with.
+ Resolved(OsString),
+ /// Keep the application's own `PATH`, for the stated reason.
+ Inherited(&'static str),
+}
+
+impl LoginPath {
+ /// The stable code the bootstrap log records for this outcome.
+ pub fn outcome(&self) -> &'static str {
+ match self {
+ Self::Resolved(_) => "resolved",
+ Self::Inherited(reason) => reason,
+ }
+ }
+}
+
+/// The `PATH` a Runtime started now should inherit.
+///
+/// Only macOS gives applications a `PATH` that differs from the terminal's;
+/// Windows applications receive the user's registry `PATH`. An application
+/// started from a terminal (a development run) already carries that terminal's
+/// environment, and an interactive shell attached to the same terminal would
+/// compete with it for the foreground.
+pub fn login_shell_path() -> LoginPath {
+ #[cfg(target_os = "macos")]
+ {
+ use std::io::IsTerminal;
+ if std::io::stdin().is_terminal() {
+ return LoginPath::Inherited("terminal");
+ }
+ let shell = std::env::var_os("SHELL")
+ .map(std::path::PathBuf::from)
+ .filter(|shell| shell.is_absolute())
+ .unwrap_or_else(|| std::path::PathBuf::from(DEFAULT_SHELL));
+ resolve_with(&shell, LOGIN_PATH_TIMEOUT)
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ LoginPath::Inherited("unsupported")
+ }
+}
+
+/// Runs `shell` as an interactive login shell and reads the `PATH` it prints.
+///
+/// Interactive as well as login: nvm's installer writes to `.zshrc` and
+/// `.bashrc`, which only interactive shells read.
+#[cfg(target_os = "macos")]
+pub(crate) fn resolve_with(shell: &Path, timeout: Duration) -> LoginPath {
+ use std::os::unix::process::CommandExt;
+
+ let mut command = Command::new(shell);
+ command
+ .args(["-l", "-i", "-c", PRINT_PATH_SCRIPT])
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ // Out of the shell's own process group, so nothing a startup file does
+ // with job control or signals reaches the desktop shell.
+ .process_group(0);
+ let Ok(mut child) = command.spawn() else {
+ return LoginPath::Inherited("spawn_failed");
+ };
+ let Some(mut stdout) = child.stdout.take() else {
+ let _ = child.kill();
+ let _ = child.wait();
+ return LoginPath::Inherited("spawn_failed");
+ };
+
+ // A process a startup file leaves behind can hold stdout open after the
+ // shell is gone, so the reader is never joined: the value is taken as soon
+ // as both markers have arrived.
+ let (sender, receiver) = mpsc::channel::<Vec<u8>>();
+ std::thread::spawn(move || {
+ let mut chunk = [0_u8; 4096];
+ loop {
+ match stdout.read(&mut chunk) {
+ Ok(0) | Err(_) => break,
+ Ok(read) => {
+ if sender.send(chunk[..read].to_vec()).is_err() {
+ break;
+ }
+ }
+ }
+ }
+ });
+
+ let deadline = Instant::now() + timeout;
+ let mut output = Vec::new();
+ let outcome = loop {
+ if let Some(path) = parse_marked_path(&output) {
+ break path;
+ }
+ if output.len() > MAX_OUTPUT_BYTES {
+ break LoginPath::Inherited("output_too_large");
+ }
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ match receiver.recv_timeout(remaining) {
+ Ok(chunk) => output.extend_from_slice(&chunk),
+ Err(mpsc::RecvTimeoutError::Timeout) => break LoginPath::Inherited("timeout"),
+ Err(mpsc::RecvTimeoutError::Disconnected) => break LoginPath::Inherited("no_path"),
+ }
+ };
+ // A successful lookup has already printed PATH; let the shell finish its
+ // logout hooks (zsh `.zlogout`) within the remaining budget. Only a
+ // fallback, or a logout that itself hangs, takes the group with it.
+ if matches!(outcome, LoginPath::Resolved(_)) {
+ wait_then_end(&mut child, deadline.saturating_duration_since(Instant::now()));
+ } else {
+ end_process_group(&mut child);
+ }
+ outcome
+}
+
+/// Lets a successful shell finish, then ends anything still running.
+///
+/// `try_wait` is non-blocking; a logout hook that finishes promptly is the
+/// common case. The remaining lookup budget is the cap, so a hanging `.zlogout`
+/// cannot stall the Runtime start past the original 10 s.
+#[cfg(target_os = "macos")]
+fn wait_then_end(child: &mut std::process::Child, budget: Duration) {
+ let deadline = Instant::now() + budget;
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => return,
+ Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(20)),
+ _ => {
+ end_process_group(child);
+ return;
+ }
+ }
+ }
+}
+
+/// Ends the login shell and everything its startup files started.
+///
+/// A startup file that blocks in a subprocess (`sleep`, a prompt that waits for
+/// input) would otherwise outlive the shell and hold stdout, and with it the
+/// reader thread, open. The group is signalled before the shell is reaped: until
+/// then its leader's pid, and so the group id, cannot be reused by an unrelated
+/// process. The crate forbids `unsafe`, so the signal goes through `kill(1)`.
+#[cfg(target_os = "macos")]
+fn end_process_group(child: &mut std::process::Child) {
+ let _ = Command::new("/bin/kill")
+ .args(["-KILL", "--", &format!("-{}", child.id())])
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status();
+ let _ = child.kill();
+ let _ = child.wait();
+}
+
+/// The value between the markers, or `None` until the end marker has arrived.
+#[cfg(target_os = "macos")]
+fn parse_marked_path(output: &[u8]) -> Option<LoginPath> {
+ use std::os::unix::ffi::OsStringExt;
+
+ let start = find(output, START_MARKER)? + START_MARKER.len();
+ let length = find(&output[start..], END_MARKER)?;
+ let mut value = &output[start..start + length];
+ while let Some(rest) = value.strip_suffix(b"\n").or_else(|| value.strip_suffix(b"\r")) {
+ value = rest;
+ }
+ if value.is_empty() || value.contains(&0) {
+ return Some(LoginPath::Inherited("no_path"));
+ }
+ Some(LoginPath::Resolved(OsString::from_vec(value.to_vec())))
+}
+
+#[cfg(target_os = "macos")]
+fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ haystack.windows(needle.len()).position(|window| window == needle)
+}
+
+#[cfg(all(test, target_os = "macos"))]
+mod tests {
+ use std::os::unix::fs::PermissionsExt;
+ use std::path::PathBuf;
+
+ use super::*;
+
+ fn scratch_dir(label: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "avibe-login-path-{label}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .expect("clock")
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&dir).expect("scratch dir");
+ dir
+ }
+
+ /// A stand-in login shell: `body` runs first, then the script the shell
+ /// was given, the way a startup file runs before `-c`. `after` runs last,
+ /// the way a logout hook would.
+ fn fake_shell_with_after(dir: &Path, body: &str, after: &str) -> PathBuf {
+ let shell = dir.join("shell");
+ std::fs::write(&shell, format!("#!/bin/sh\n{body}\nshift 3\neval \"$1\"\n{after}\n")).expect("fake shell");
+ std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o755)).expect("chmod");
+ shell
+ }
+
+ fn fake_shell(dir: &Path, body: &str) -> PathBuf {
+ fake_shell_with_after(dir, body, "")
+ }
+
+ #[test]
+ fn the_path_a_startup_file_exports_is_returned_without_its_banner() {
+ let dir = scratch_dir("resolved");
+ let shell = fake_shell(
+ &dir,
+ "echo 'Welcome back'\nPATH=\"/home/user/.nvm/versions/node/v22/bin:$PATH\"; export PATH",
+ );
+
+ let resolved = resolve_with(&shell, Duration::from_secs(10));
+
+ let LoginPath::Resolved(path) = resolved else {
+ panic!("expected a resolved PATH, got {resolved:?}");
+ };
+ let path = path.into_string().expect("utf-8 PATH");
+ assert!(path.starts_with("/home/user/.nvm/versions/node/v22/bin:"), "{path}");
+ assert!(!path.contains('\n'));
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn the_shell_is_started_as_an_interactive_login_shell() {
+ let dir = scratch_dir("flags");
+ let recording = dir.join("argv");
+ let shell = fake_shell(
+ &dir,
+ &format!("printf '%s\\n' \"$1\" \"$2\" \"$3\" > '{}'", recording.display()),
+ );
+
+ assert!(matches!(
+ resolve_with(&shell, Duration::from_secs(10)),
+ LoginPath::Resolved(_)
+ ));
+ assert_eq!(
+ std::fs::read_to_string(&recording).expect("recorded argv"),
+ "-l\n-i\n-c\n"
+ );
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn a_startup_file_that_never_finishes_falls_back_after_the_timeout() {
+ let dir = scratch_dir("timeout");
+ let shell = fake_shell(&dir, "exec sleep 30");
+
+ let started = Instant::now();
+ let resolved = resolve_with(&shell, Duration::from_millis(300));
+
+ assert_eq!(resolved, LoginPath::Inherited("timeout"));
+ assert!(started.elapsed() < Duration::from_secs(5));
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ /// `.zshrc` running `sleep 30` without `exec` blocks in a subprocess, not
+ /// in the shell; the fallback must not leave that subprocess behind.
+ #[test]
+ fn a_fallback_ends_what_the_startup_files_started() {
+ let dir = scratch_dir("group");
+ let pid_file = dir.join("pid");
+ let shell = fake_shell(&dir, &format!("sleep 30 &\necho $! > '{}'\nwait", pid_file.display()));
+
+ // Long enough for the fake shell to start and record its child while
+ // the rest of the suite is spawning processes too.
+ assert_eq!(
+ resolve_with(&shell, Duration::from_secs(3)),
+ LoginPath::Inherited("timeout")
+ );
+
+ let pid = std::fs::read_to_string(&pid_file).expect("startup file ran");
+ let alive = || {
+ Command::new("/bin/kill")
+ .args(["-0", pid.trim()])
+ .stderr(Stdio::null())
+ .status()
+ .is_ok_and(|status| status.success())
+ };
+ let deadline = Instant::now() + Duration::from_secs(5);
+ while alive() && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ assert!(!alive(), "the startup file's subprocess outlived the fallback");
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ /// zsh runs `.zlogout` after `-c` returns. A successful lookup must let
+ /// that hook finish rather than SIGKILL it the moment PATH is printed.
+ #[test]
+ fn a_successful_lookup_lets_the_logout_hook_finish() {
+ let dir = scratch_dir("logout");
+ let done = dir.join("done");
+ let shell = fake_shell_with_after(&dir, "", &format!("sleep 0.2\necho done > '{}'", done.display()));
+
+ assert!(matches!(
+ resolve_with(&shell, Duration::from_secs(10)),
+ LoginPath::Resolved(_)
+ ));
+ assert_eq!(
+ std::fs::read_to_string(&done).expect("logout hook ran to completion"),
+ "done\n"
+ );
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn a_shell_that_exits_without_printing_falls_back() {
+ let dir = scratch_dir("exit");
+ let shell = fake_shell(&dir, "exit 1");
+
+ assert_eq!(
+ resolve_with(&shell, Duration::from_secs(10)),
+ LoginPath::Inherited("no_path")
+ );
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn a_missing_shell_falls_back() {
+ assert_eq!(
+ resolve_with(Path::new("/nonexistent/avibe-test-shell"), Duration::from_secs(1)),
+ LoginPath::Inherited("spawn_failed")
+ );
+ }
+
+ #[test]
+ fn an_empty_value_between_the_markers_is_not_a_path() {
+ assert_eq!(
+ parse_marked_path(b"__AVIBE_LOGIN_PATH_START__\n__AVIBE_LOGIN_PATH_END__"),
+ Some(LoginPath::Inherited("no_path"))
+ );
+ assert_eq!(parse_marked_path(b"__AVIBE_LOGIN_PATH_START__/usr/bin"), None);
+ }
+}