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): look up the login-shell PATH once per Runtime start (#2421)

Call Whitebb8a7a16ccbf
diff --git a/desktop/runtime-host/src/bootstrap.rs b/desktop/runtime-host/src/bootstrap.rs
index 00d25a7f3..4dfe9b998 100644
--- a/desktop/runtime-host/src/bootstrap.rs
+++ b/desktop/runtime-host/src/bootstrap.rs
@@ -151,6 +151,10 @@ pub struct RuntimeHost {
launcher: Arc<dyn RuntimeLauncher>,
settings: RuntimeHostSettings,
launched_runtime: Mutex<LaunchState>,
+ /// Reserves one run's prepare-and-launch step, so concurrent runs ask the
+ /// login shell once between them. Only that step takes it: stop and
+ /// removal use the launch-state mutex alone and never wait on a lookup.
+ launch_reservation: tokio::sync::Mutex<()>,
}
/// What the last successful bootstrap run adopted: the monitor's baseline.
@@ -243,6 +247,7 @@ impl RuntimeHost {
launcher,
settings,
launched_runtime: Mutex::new(LaunchState::default()),
+ launch_reservation: tokio::sync::Mutex::new(()),
}
}
@@ -471,11 +476,20 @@ 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;
+ // A run that finds an earlier launch still in flight starts nothing, so
+ // it does not ask the login shell either. The reservation makes a
+ // concurrent run wait here and then find this run's launch in flight.
+ let reservation = self.launch_reservation.lock().await;
+ let prepared = !self.launched_runtime().launch_pending();
+ if prepared {
+ let preparing = launcher.clone();
+ let _ = tokio::task::spawn_blocking(move || preparing.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()) {
+ let launched = self.launch_if_needed(launcher.clone(), trigger.allows_handover(), prepared);
+ drop(reservation);
+ if let Err(error) = launched {
return publish(
sink,
BootstrapStatus::failed(
@@ -714,7 +728,17 @@ impl RuntimeHost {
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
- fn launch_if_needed(&self, launcher: Arc<dyn ResolvedRuntimeLauncher>, hand_over: bool) -> Result<(), LaunchError> {
+ /// Starts the Runtime unless an attempt is still in flight. Only a
+ /// launcher this run `prepared` off the lock may start: launching another
+ /// would run the login-shell lookup under this mutex. An attempt seen in
+ /// flight that has finished since is what such a run waits for, and a
+ /// later run prepares before it launches again.
+ fn launch_if_needed(
+ &self,
+ launcher: Arc<dyn ResolvedRuntimeLauncher>,
+ hand_over: bool,
+ prepared: bool,
+ ) -> Result<(), LaunchError> {
let mut state = self.launched_runtime();
if state.stopping {
return Err(LaunchError::RuntimeStop);
@@ -723,7 +747,7 @@ impl RuntimeHost {
state.retain_completed_attempt_liveness();
state.attempt = None;
}
- if state.attempt.is_none() {
+ if state.attempt.is_none() && prepared {
// Spawning the helper is evidence that a Runtime may exist even
// when the helper later reports failure. Keep that fact separate
// from retry deduplication and stop authority.
@@ -867,7 +891,7 @@ mod tests {
}
assert!(matches!(
- host.launch_if_needed(resolved.clone(), false),
+ host.launch_if_needed(resolved.clone(), false, true),
Err(LaunchError::RuntimeStop)
));
assert_eq!(counting.launches.load(Ordering::SeqCst), 0);
@@ -930,6 +954,131 @@ mod tests {
assert_eq!(status.notice.code, BootstrapNoticeCode::RuntimeSpawnFailed);
}
+ /// A Retry or recovery run that finds an earlier launch still in flight
+ /// starts nothing, so it must not spend the login-shell lookup either.
+ #[tokio::test]
+ async fn a_run_that_finds_a_launch_in_flight_does_not_prepare_another() {
+ 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().attempt = Some(LaunchedRuntime {
+ pid: 1,
+ watch: LaunchWatch::default(),
+ });
+
+ host.bootstrap(&DiscardStatus, BootstrapTrigger::Retry).await;
+
+ assert_eq!(counting.prepares.load(Ordering::SeqCst), 0);
+ assert_eq!(counting.launches.load(Ordering::SeqCst), 0);
+ }
+
+ /// A launcher whose login-shell lookup blocks until the test releases it.
+ struct BlockedLookup {
+ started: std::sync::mpsc::SyncSender<()>,
+ release: Mutex<std::sync::mpsc::Receiver<()>>,
+ }
+
+ struct ResolvesToBlockedLookup(Arc<BlockedLookup>);
+
+ impl RuntimeLauncher for ResolvesToBlockedLookup {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ Ok(Arc::new(self.0.clone()))
+ }
+
+ fn owns_private_files(&self) -> bool {
+ true
+ }
+ }
+
+ impl ResolvedRuntimeLauncher for Arc<BlockedLookup> {
+ fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError> {
+ Ok(LoopbackOrigin::parse(ORIGIN).expect("test origin"))
+ }
+
+ fn prepare_launch(&self) {
+ let _ = self.started.send(());
+ let _ = self.release.lock().expect("release channel").recv();
+ }
+
+ fn launch(&self, _hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
+ Ok(LaunchedRuntime {
+ pid: 1,
+ watch: LaunchWatch::exited(LaunchExit::Started),
+ })
+ }
+ }
+
+ /// The launch reservation covers only preparing and launching: a stop or
+ /// a removal requested while a lookup holds it answers without waiting.
+ #[tokio::test]
+ async fn stop_and_removal_never_wait_on_a_launch_reservation() {
+ let (started_tx, started_rx) = std::sync::mpsc::sync_channel(1);
+ let (release_tx, release_rx) = std::sync::mpsc::channel();
+ let blocked = Arc::new(BlockedLookup {
+ started: started_tx,
+ release: Mutex::new(release_rx),
+ });
+ let host = Arc::new(RuntimeHost::new(
+ Arc::new(AbsentProbe),
+ Arc::new(ResolvesToBlockedLookup(blocked)),
+ RuntimeHostSettings {
+ origin_override: None,
+ ready_timeout: Duration::from_millis(10),
+ poll_interval: Duration::from_millis(1),
+ probe_timeout: Duration::from_millis(10),
+ },
+ ));
+ let running = tokio::spawn({
+ let host = host.clone();
+ async move { host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await }
+ });
+ tokio::task::spawn_blocking(move || started_rx.recv())
+ .await
+ .expect("lookup watcher")
+ .expect("the lookup started and holds the reservation");
+
+ let stop = tokio::time::timeout(Duration::from_secs(5), host.stop_owned_runtime()).await;
+ assert!(stop.is_ok(), "a stop waited on the launch reservation");
+ let removal = tokio::time::timeout(Duration::from_secs(5), host.remove_private_runtime(None)).await;
+ assert!(removal.is_ok(), "a removal waited on the launch reservation");
+
+ release_tx.send(()).expect("release the lookup");
+ running.await.expect("the bootstrap run finishes");
+ }
+
+ /// An attempt seen in flight may finish before the lock is taken. The run
+ /// that saw it did not prepare, so it must not launch: launching would run
+ /// the login-shell lookup under the launch-state mutex.
+ #[test]
+ fn only_a_prepared_run_launches_after_an_in_flight_attempt_finishes() {
+ let counting = Arc::new(CountingLauncher::default());
+ let resolved: Arc<dyn ResolvedRuntimeLauncher> = Arc::new(counting.clone());
+ let host = RuntimeHost::new(Arc::new(AbsentProbe), counting.clone(), RuntimeHostSettings::default());
+ host.launched_runtime().attempt = Some(LaunchedRuntime {
+ pid: 1,
+ watch: LaunchWatch::exited(LaunchExit::Started),
+ });
+
+ host.launch_if_needed(resolved.clone(), false, false)
+ .expect("an unprepared run waits instead");
+ assert_eq!(counting.launches.load(Ordering::SeqCst), 0);
+ assert_eq!(counting.prepares.load(Ordering::SeqCst), 0);
+
+ host.launch_if_needed(resolved, false, true)
+ .expect("a prepared run launches");
+ assert_eq!(counting.launches.load(Ordering::SeqCst), 1);
+ }
+
#[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 bf9a27962..8ff2f2322 100644
--- a/desktop/runtime-host/src/launcher.rs
+++ b/desktop/runtime-host/src/launcher.rs
@@ -362,6 +362,7 @@ impl RuntimeLauncher for InstalledVibeLauncher {
// A development shell drives an install it does not own and has no
// application data directory to write diagnostics into.
log: BootstrapLog::disabled(),
+ login_path: OnceLock::new(),
}))
}
}
@@ -411,6 +412,7 @@ impl RuntimeLauncher for BundledVibeLauncher {
expected_runtime_id: Some(runtime_id),
cleanup: Some((self.bundle.clone(), runtime.root)),
log: self.log.clone(),
+ login_path: OnceLock::new(),
}))
}
@@ -457,6 +459,36 @@ struct ResolvedVibeExecutable {
expected_runtime_id: Option<String>,
cleanup: Option<(PrivateRuntimeBundle, PathBuf)>,
log: BootstrapLog,
+ /// The `PATH` this attempt's Runtime start inherits. See `login_path`.
+ login_path: OnceLock<LoginPath>,
+}
+
+impl ResolvedVibeExecutable {
+ /// The `PATH` the Runtime about to be started inherits, looked up once per
+ /// start attempt.
+ ///
+ /// 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. Held for one attempt so `prepare_launch`
+ /// can run the lookup off the launch-state mutex and `launch` can reuse the
+ /// result. Every bootstrap run resolves a new attempt, so a lookup that
+ /// timed out, or a version manager installed while the app stays open, is
+ /// looked up again on the next start rather than kept until the app exits.
+ fn login_path(&self) -> &LoginPath {
+ self.login_path.get_or_init(|| {
+ let started = Instant::now();
+ let login_path = login_shell_path();
+ self.log.record(
+ "runtime.login_path",
+ &[
+ ("outcome", login_path.outcome().to_owned()),
+ ("ms", started.elapsed().as_millis().to_string()),
+ ],
+ );
+ login_path
+ })
+ }
}
impl ResolvedRuntimeLauncher for ResolvedVibeExecutable {
@@ -465,7 +497,7 @@ impl ResolvedRuntimeLauncher for ResolvedVibeExecutable {
}
fn prepare_launch(&self) {
- let _ = cached_login_path(&self.log);
+ let _ = self.login_path();
}
fn launch(&self, hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
@@ -473,7 +505,7 @@ impl ResolvedRuntimeLauncher for ResolvedVibeExecutable {
// 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 login_path = self.login_path();
let started = Instant::now();
let child = spawn_detached(&self.command, hand_over, login_path).map_err(LaunchError::Spawn)?;
let pid = child.id();
@@ -1042,29 +1074,6 @@ fn is_executable(_metadata: &std::fs::Metadata) -> bool {
true
}
-/// 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,
@@ -1704,9 +1713,39 @@ mod tests {
expected_runtime_id: Some("a".repeat(64)),
cleanup: None,
log: BootstrapLog::disabled(),
+ login_path: OnceLock::new(),
}
}
+ /// A lookup that failed, or a version manager installed while the app
+ /// stays open, must not outlive the start attempt it served: the next
+ /// attempt asks the login shell again, while one attempt asks only once.
+ #[cfg(unix)]
+ #[test]
+ fn each_start_attempt_looks_up_the_login_path_once() {
+ let dir = scratch_dir("login-path-per-attempt");
+ let executable = write_fake_runtime(&dir, "#!/bin/sh\nexit 0\n");
+ let log_path = dir.join("bootstrap.log");
+ let lookups = || {
+ std::fs::read_to_string(&log_path)
+ .unwrap_or_default()
+ .lines()
+ .filter(|line| line.contains(" runtime.login_path "))
+ .count()
+ };
+
+ for attempt in 1..=2 {
+ let resolved = ResolvedVibeExecutable {
+ log: BootstrapLog::at(log_path.clone()),
+ ..identified(executable.clone())
+ };
+ resolved.prepare_launch();
+ resolved.launch(false).expect("the fake runtime starts");
+ assert_eq!(lookups(), attempt, "attempt {attempt}");
+ }
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
/// Asserts the launch contract against what the operating system actually
/// receives, rather than against the constant the code was built from.
#[cfg(unix)]
diff --git a/desktop/runtime-host/src/login_path.rs b/desktop/runtime-host/src/login_path.rs
index 40d5899cb..a0f058d03 100644
--- a/desktop/runtime-host/src/login_path.rs
+++ b/desktop/runtime-host/src/login_path.rs
@@ -79,6 +79,12 @@ impl LoginPath {
/// environment, and an interactive shell attached to the same terminal would
/// compete with it for the foreground.
pub fn login_shell_path() -> LoginPath {
+ // This crate's unit tests never run the developer's own login shell and
+ // its startup files; the lookup itself is covered through `resolve_with`
+ // with test-owned fake shells.
+ if cfg!(test) {
+ return LoginPath::Inherited("test");
+ }
#[cfg(target_os = "macos")]
{
use std::io::IsTerminal;
diff --git a/desktop/runtime-host/tests/bootstrap.rs b/desktop/runtime-host/tests/bootstrap.rs
index 28add65e7..01d0479c8 100644
--- a/desktop/runtime-host/tests/bootstrap.rs
+++ b/desktop/runtime-host/tests/bootstrap.rs
@@ -157,6 +157,7 @@ struct LauncherState {
/// `None` keeps the launch helper running; `Some` has already seen it exit.
exit: Option<LaunchExit>,
resolvable: AtomicBool,
+ prepares: AtomicUsize,
launches: AtomicUsize,
/// Whether each launch asked `vibe start` to hand over a predecessor.
handover_requests: Mutex<Vec<bool>>,
@@ -177,6 +178,7 @@ impl FakeLauncher {
failures,
exit,
resolvable: AtomicBool::new(true),
+ prepares: AtomicUsize::new(0),
launches: AtomicUsize::new(0),
handover_requests: Mutex::new(Vec::new()),
prunes: AtomicUsize::new(0),
@@ -220,6 +222,11 @@ impl FakeLauncher {
self.0.launches.load(Ordering::SeqCst)
}
+ /// How many times a run asked for the login-shell lookup.
+ fn prepares(&self) -> usize {
+ self.0.prepares.load(Ordering::SeqCst)
+ }
+
fn handover_requests(&self) -> Vec<bool> {
self.0.handover_requests.lock().expect("launch recorder").clone()
}
@@ -288,6 +295,10 @@ impl ResolvedRuntimeLauncher for FakeLauncher {
Ok(origin())
}
+ fn prepare_launch(&self) {
+ self.0.prepares.fetch_add(1, Ordering::SeqCst);
+ }
+
fn launch(&self, hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
let call = self.0.launches.fetch_add(1, Ordering::SeqCst) + 1;
self.0
@@ -1410,6 +1421,11 @@ async fn concurrent_bootstraps_start_at_most_one_runtime() {
assert_eq!(first.phase, BootstrapPhase::Ready);
assert_eq!(second.phase, BootstrapPhase::Ready);
assert_eq!(launcher.calls(), 1, "two racing runs must not start two Runtimes");
+ assert_eq!(
+ launcher.prepares(),
+ 1,
+ "two racing runs must not ask the login shell twice"
+ );
}
#[tokio::test(start_paused = true)]