Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion src/claude/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::claude::subagents::{Agent, AgentModel};
use crate::platform::{find_executable, reload_path};

pub const FLAG: &str = "--acp";
/// Pinned so an upstream change reaches users only with a Claudiu release.
Expand Down Expand Up @@ -160,16 +161,26 @@ struct Process {
errors: JoinHandle<String>,
}

/// The program on the PATH. A desktop launch has a minimal PATH, so OpenCode or Node installed since Claudiu started,
/// or put on the PATH only by the shell's startup files, turns up once the login shell's PATH is read again.
fn locate_reloading(program: &str) -> Option<PathBuf> {
find_executable(program).or_else(|| {
reload_path();
find_executable(program)
})
}

impl Connection {
fn start(agent: Agent, cwd: &Path, env: &[(&str, String)]) -> Result<Connection, String> {
let (program, args, missing): (&str, &[&str], &str) = match agent {
Agent::Codex => ("npx", &["-y", CODEX_ACP], "npx was not found on PATH. Codex subagents need Node.js."),
Agent::OpenCode => ("opencode", &["acp"], "opencode was not found on PATH. OpenCode subagents need OpenCode installed."),
};
let program = which::which(program).map_err(|_| missing.to_string())?;
let program = locate_reloading(program).ok_or_else(|| missing.to_string())?;
let mut command = Command::new(program);
command.args(args).current_dir(cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
crate::platform::no_window(&mut command);
crate::platform::with_login_path(&mut command);
for (key, value) in env {
command.env(key, value);
}
Expand Down Expand Up @@ -585,6 +596,26 @@ mod tests {
assert_eq!(sent.last().unwrap()["result"]["outcome"]["optionId"], "cancel");
}

#[test]
#[cfg(unix)]
fn a_program_only_the_login_shell_put_on_the_path_is_found() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("claudiu-acp-path-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let tool = dir.join("claudiu-acp-path-probe");
std::fs::write(&tool, b"#!/bin/sh\n").unwrap();
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();

let _only_test_using_login_path = crate::platform::LOGIN_PATH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let previous = crate::platform::LOGIN_PATH.lock().unwrap().clone();
*crate::platform::LOGIN_PATH.lock().unwrap() = Some(dir.as_os_str().to_os_string());
let found = locate_reloading("claudiu-acp-path-probe");
*crate::platform::LOGIN_PATH.lock().unwrap() = previous;
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(found, Some(tool));
}

#[test]
fn read_only_refuses_permission_requests() {
let (_, sent, _) = talk(&asks_permission(), false);
Expand Down
1 change: 1 addition & 0 deletions src/github/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ impl Gh {
}
cmd.env("GH_PROMPT_DISABLED", "1").env("NO_COLOR", "1").env("GH_NO_UPDATE_NOTIFIER", "1");
crate::platform::no_window(&mut cmd);
crate::platform::with_login_path(&mut cmd);
let mut child = cmd.spawn().map_err(|e| Error {
kind: if e.kind() == std::io::ErrorKind::NotFound { ErrKind::NoCli } else { ErrKind::Other },
msg: format!("could not run gh: {e}"),
Expand Down
1 change: 1 addition & 0 deletions src/lsp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ impl Server {
let mut cmd = Command::new(program);
cmd.args(kind.args).current_dir(root).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
crate::platform::no_window(&mut cmd);
crate::platform::with_login_path(&mut cmd);
let mut child = cmd.spawn().map_err(|e| format!("could not start {}: {e}", kind.program))?;
let (stdin, stdout, stderr) = (child.stdin.take().unwrap(), child.stdout.take().unwrap(), child.stderr.take().unwrap());
match Self::connect(stdout, stdin, Some(stderr), root, kind.pull_diagnostics, events) {
Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ fn main() {
let initial: Vec<std::path::PathBuf> = std::env::args().skip(1).map(std::path::PathBuf::from).filter(|p| p.is_dir()).collect();
// A first launch (no state file) starts with the setup window alone. Asked before anything loads the store.
let first_launch = store::Store::is_first_launch(&store::Store::default_path());
platform::read_login_path_in_background();
let workspace = Workspace::new(initial);
let mailbox = workspace.rt.mailbox();
let ((w, h), maximized) = first_size();
Expand Down
76 changes: 70 additions & 6 deletions src/platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,22 +124,66 @@ pub fn home_dir() -> Option<PathBuf> {
directories::BaseDirs::new().map(|d| d.home_dir().to_path_buf())
}

/// PATH lookup (honors PATHEXT on Windows).
/// PATH lookup (honors PATHEXT on Windows). On macOS and Linux a miss also looks in the login shell's PATH, which
/// the first miss waits for if the startup read hasn't finished, so call it off the UI thread.
pub fn find_executable(name: &str) -> Option<PathBuf> {
let found = which::which(name).ok();
#[cfg(unix)]
let found = found.or_else(|| {
let path = LOGIN_PATH.lock().ok()?.clone()?;
which::which_in(name, Some(path), std::env::current_dir().ok()?).ok()
});
let found = {
let in_login_path = || {
let path = LOGIN_PATH.lock().ok()?.clone()?;
which::which_in(name, Some(path), std::env::current_dir().ok()?).ok()
};
found.or_else(in_login_path).or_else(|| {
read_login_path_once();
in_login_path()
})
};
found
}

/// The PATH of the user's login shell, as `reload_path` last read it. A desktop-launched app gets a minimal PATH, and
/// the environment of a running process is not changed here (`set_var` is unsafe beside other threads on Unix), so
/// `find_executable` looks here as well. Sessions already start through the login shell (`through_login_shell`).
#[cfg(unix)]
static LOGIN_PATH: std::sync::Mutex<Option<std::ffi::OsString>> = std::sync::Mutex::new(None);
pub(crate) static LOGIN_PATH: std::sync::Mutex<Option<std::ffi::OsString>> = std::sync::Mutex::new(None);

/// Tests that put a directory in `LOGIN_PATH` hold this, so two of them don't overwrite each other's.
#[cfg(all(unix, test))]
pub(crate) static LOGIN_PATH_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Read the login shell's PATH once at startup, off the UI thread, so tools only the shell's startup files put on the
/// PATH are found. Windows has the registry and `reload_path` reads it when the setup window asks.
pub fn read_login_path_in_background() {
#[cfg(unix)]
std::thread::spawn(read_login_path_once);
}

/// The first caller reads the login shell's PATH and every other waits for that read, so a lookup that runs before the
/// startup read is done gets its answer instead of a miss. Tests skip it: they set `LOGIN_PATH` themselves, and a
/// real login shell would overwrite it.
#[cfg(unix)]
fn read_login_path_once() {
static READ: std::sync::Once = std::sync::Once::new();
if !cfg!(test) {
READ.call_once(reload_path);
}
}

/// Start `command` with the login shell's PATH. A program may need others from the same folders, like `tsc` and `npx`
/// needing `node` from nvm, which a desktop launch's minimal PATH lacks, even when the program itself is on the minimal
/// PATH. Waits for the first read of that PATH, so call it off the UI thread. Windows programs inherit the PATH
/// `reload_path` sets for this process.
pub fn with_login_path(command: &mut Command) {
#[cfg(unix)]
read_login_path_once();
#[cfg(unix)]
if let Some(path) = LOGIN_PATH.lock().ok().and_then(|path| path.clone()) {
command.env("PATH", path);
}
#[cfg(not(unix))]
let _ = command;
}

/// Look for the PATH again, for a tool installed since Claudiu started or one that only the shell's startup files
/// put on the PATH. Windows reads the system and user PATH from the registry and uses it for this process and the
Expand Down Expand Up @@ -644,6 +688,7 @@ bye
perms.set_mode(0o755);
std::fs::set_permissions(&tool, perms).unwrap();

let _only_test_using_login_path = LOGIN_PATH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let previous = LOGIN_PATH.lock().unwrap().clone();
*LOGIN_PATH.lock().unwrap() = Some(dir.as_os_str().to_os_string());
let found = find_executable("claudiu-login-path-probe");
Expand All @@ -652,6 +697,25 @@ bye
assert_eq!(found, Some(tool));
}

#[test]
#[cfg(unix)]
fn a_program_starts_with_the_login_shells_path_once_it_is_known() {
let _only_test_using_login_path = LOGIN_PATH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let previous = LOGIN_PATH.lock().unwrap().clone();
let path_of = |command: &Command| command.get_envs().find(|(key, _)| *key == "PATH").and_then(|(_, value)| value.map(|v| v.to_os_string()));

*LOGIN_PATH.lock().unwrap() = None;
let mut without = Command::new("true");
with_login_path(&mut without);
*LOGIN_PATH.lock().unwrap() = Some("/nvm/bin:/usr/bin".into());
let mut with = Command::new("true");
with_login_path(&mut with);
*LOGIN_PATH.lock().unwrap() = previous;

assert_eq!(path_of(&without), None);
assert_eq!(path_of(&with), Some("/nvm/bin:/usr/bin".into()));
}

#[test]
fn a_shell_answers_with_its_path_and_a_hung_one_is_given_up_on() {
let Some(bash) = posix_shell() else { return };
Expand Down
Loading