diff --git a/plan2code-app/src-tauri/src/agents.rs b/plan2code-app/src-tauri/src/agents.rs index 052689b..23d7d06 100644 --- a/plan2code-app/src-tauri/src/agents.rs +++ b/plan2code-app/src-tauri/src/agents.rs @@ -1150,6 +1150,34 @@ pub fn custom_agents() -> (Vec, Vec) { .unwrap_or_default() } +/// The command of every built-in and custom agent that the lookup searches +/// PATH for by name, each once, in list order. A command with a folder in it +/// runs from there, whatever PATH holds, so it is left out. The PATH lookup at +/// start (`node_check::login_shell_path`) reads the shell's interactive config +/// when none of these is on the login PATH. +#[cfg(unix)] +pub fn path_agent_commands() -> Vec { + let (custom, _) = custom_agents(); + path_commands( + builtin_entries() + .iter() + .map(|entry| entry.command.as_str()) + .chain(custom.iter().map(|agent| agent.command.as_str())), + ) +} + +/// `path_agent_commands` over the given commands. +#[cfg(unix)] +fn path_commands<'a>(commands: impl Iterator) -> Vec { + let mut seen = HashSet::new(); + commands + .map(clean_command) + .filter(|command| !command.is_empty() && !has_separator(command, false)) + .filter(|command| seen.insert(*command)) + .map(str::to_string) + .collect() +} + fn clean_command(command: &str) -> &str { let command = command.trim(); command @@ -1656,6 +1684,31 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[cfg(unix)] + #[test] + fn the_path_agent_commands_are_the_bare_names_each_once() { + // The baked built-ins, then a custom list with a repeat, a quoted + // name, a command with a folder in it and an empty one. + let builtins = parse_agent_list(BAKED_AGENTS).expect("the baked list parses"); + let custom = [ + "codex", + "\"opencode\"", + "/opt/tools/bin/gemini", + "./agent", + " ", + ]; + assert_eq!( + path_commands( + builtins + .builtins + .iter() + .map(|entry| entry.command.as_str()) + .chain(custom) + ), + ["claude", "devin", "codex", "opencode"] + ); + } + #[test] fn the_baked_list_matches_the_shipped_agents_json() { // include_str! means the baked copy IS src/launcher/agents.json; this diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs index e166131..693061c 100644 --- a/plan2code-app/src-tauri/src/main.rs +++ b/plan2code-app/src-tauri/src/main.rs @@ -162,13 +162,23 @@ fn platform_info() -> serde_json::Value { // What the launch card offers per agent: whether its CLI is on PATH (else how // to install it), and whether it takes its own reasoning effort; plus the -// warnings about agents.json. +// warnings about agents.json. A refresh runs the person's login shell, which +// can take seconds with a slow profile, so the work runs on a blocking thread: +// a sync command would run on the main thread and freeze the window meanwhile. #[tauri::command] -fn agent_availability(refresh: Option) -> serde_json::Value { +async fn agent_availability(refresh: Option) -> Result { + let refresh = refresh == Some(true); + tauri::async_runtime::spawn_blocking(move || agent_list(refresh)) + .await + .map_err(|e| e.to_string()) +} + +// The agent list `agent_availability` answers with. +fn agent_list(refresh: bool) -> serde_json::Value { // "Check again" also works the PATH out again and re-reads the shipped // agent list, so a CLI whose installer added a new folder to PATH, or a // list an update rewrote, is seen without restarting the app. - if refresh == Some(true) { + if refresh { node_check::refresh_path(); agents::refresh_agent_list(); } @@ -2758,7 +2768,7 @@ mod tests { // Every entry carries the shared lookup's state: found (on PATH), // outside (needing setup, not missing) or missing, with `folder` for // where an outside hit lives. - let json = agent_availability(None); + let json = agent_list(false); let entries = json["agents"].as_array().unwrap(); assert!(!entries.is_empty()); let mut builtins = 0; @@ -2777,6 +2787,17 @@ mod tests { assert!(builtins >= 3, "claude, devin and codex are listed"); } + #[test] + fn the_availability_command_is_awaited_not_run_on_the_ui_thread() { + // Check again re-runs the login shell, then the interactive config + // (up to 5 s with slow ones). A sync command runs on the main thread and freezes the + // window that long, so the command is a future that hands the work + // to a blocking thread; awaiting it gives the same list. + let json = tauri::async_runtime::block_on(agent_availability(None)) + .expect("the blocking task finished"); + assert_eq!(json, agent_list(false)); + } + /// A real console, the same way `tests/console_supervisor.rs` sets one /// up (see `console_test_env`). Keep the guard until the test ends: the /// console's variables must not change while its session is in use. diff --git a/plan2code-app/src-tauri/src/node_check.rs b/plan2code-app/src-tauri/src/node_check.rs index b440b3f..0afd016 100644 --- a/plan2code-app/src-tauri/src/node_check.rs +++ b/plan2code-app/src-tauri/src/node_check.rs @@ -8,8 +8,12 @@ //! an agent CLI) should run with, not the bare inherited one; `node_check`, //! `console_supervisor`, `versions` and `agents` all use it. +#[cfg(unix)] +use std::path::Path; use std::process::Command; use std::sync::Mutex; +#[cfg(unix)] +use std::time::{Duration, Instant}; pub const MIN_NODE_MAJOR: u32 = 18; @@ -71,44 +75,319 @@ fn node_override_dir(args: &[String]) -> Option { None } -/// The login shell's own PATH: running it as a login shell sources -/// `.zprofile`, `.bash_profile` or `.profile`, which a GUI launch never does. -/// Windows sets PATH outside any shell's startup files, so this is unix only. +/// The person's shell's own PATH (`$SHELL`, else `/bin/sh`), which a GUI +/// launch never gets. Windows sets PATH outside any shell's startup files, so +/// this is unix only. +/// +/// The rule: ask the login shell first, within `LOGIN_PATH_TIMEOUT` (3 s), +/// since Homebrew and most installers put their PATH lines in its files. Ask +/// again with the interactive config too (`.zshrc`, where nvm, fnm and asdf +/// usually put Node and the agents `npm install -g` adds under it), within +/// `INTERACTIVE_PATH_TIMEOUT` (2 s), only when `node` or every agent command +/// is missing from both the login and the inherited PATH, or on Check again +/// (`refresh_path`). Never after a login timeout, which would hang the same +/// way. So a hung login profile adds at most 3 s to the start, and the slowest +/// case 5 s. The interactive config is left out when it is not needed because +/// its terminal-only lines can start daemons that leave the shell's process +/// group, out of reach of any kill here. Details in `path_from_shell` and +/// `shell_path`. #[cfg(unix)] -fn login_shell_path() -> Option { +fn login_shell_path(args: &[String], inherited: &str, always_interactive: bool) -> Option { let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()); - // `printenv PATH`, not `echo $PATH`: fish expands `$PATH` to a list and - // echoes it space-separated, which is no PATH at all. - let out = Command::new(&shell) - .args(["-lc", "printenv PATH"]) - .output() - .ok()?; - let path = parse_path_output(&String::from_utf8_lossy(&out.stdout)); - (out.status.success() && !path.is_empty()).then_some(path) + let agents = crate::agents::path_agent_commands(); + login_shell_path_for( + Path::new(&shell), + args, + inherited, + &agents, + always_interactive, + ) } -/// A PATH out of a shell's output: the last non-empty line (a login shell's -/// profile may print a banner first), and a space-separated list of absolute -/// folders (what fish's `echo $PATH` prints) turned into a `:` list. A single -/// folder with a space in its name is left alone. -#[cfg_attr(windows, allow(dead_code))] -fn parse_path_output(output: &str) -> String { - let line = output - .lines() - .map(str::trim) - .rfind(|l| !l.is_empty()) - .unwrap_or(""); - let tokens: Vec<&str> = line.split_whitespace().collect(); - let spaced_list = !line.contains(':') - && tokens.len() > 1 - && tokens - .iter() - .all(|t| t.starts_with('/') || t.starts_with('~')); - if spaced_list { - tokens.join(":") - } else { - line.to_string() +/// `login_shell_path` for a given shell and agent commands, so tests need not +/// set `SHELL` or write an agent list. The `--node` folder in `args` counts as +/// already on the inherited PATH. +#[cfg(unix)] +fn login_shell_path_for( + shell: &Path, + args: &[String], + inherited: &str, + agents: &[String], + always_interactive: bool, +) -> Option { + let known = match node_override_dir(args) { + Some(dir) => format!("{dir}:{inherited}"), + None => inherited.to_string(), + }; + path_from_shell(shell, &known, agents, always_interactive) +} + +/// How long the shell may take as a login shell, then with its interactive +/// config when that is asked too (see `login_shell_path`). +#[cfg(unix)] +const LOGIN_PATH_TIMEOUT: Duration = Duration::from_secs(3); +#[cfg(unix)] +const INTERACTIVE_PATH_TIMEOUT: Duration = Duration::from_secs(2); + +/// The most of a shell's output kept while looking for the markers. +#[cfg(unix)] +const SHELL_OUTPUT_LIMIT: usize = 1 << 20; + +#[cfg(unix)] +const SHELL_POLL: Duration = Duration::from_millis(10); + +/// Once the answer is in, how long the shell may take to exit, so a failing +/// exit status still counts; past it the shell is ended and the answer kept. +#[cfg(unix)] +const LINGER_GRACE: Duration = Duration::from_millis(200); + +/// SIGKILL to `child`'s whole process group (it leads one, through +/// `setsid`), then reap it, so nothing a profile started in that group +/// outlives the call. Called once the shell has exited too: while any member +/// is left, the id still names this group; once it is empty the kill finds +/// nothing, barring the id's reuse within that moment. +#[cfg(unix)] +fn kill_process_group(child: &mut std::process::Child) { + if let Ok(pgid) = i32::try_from(child.id()) { + // SAFETY: kill(2) takes plain integers and touches no memory. + unsafe { + libc::kill(-pgid, libc::SIGKILL); + } } + let _ = child.kill(); + let _ = child.wait(); +} + +/// The login shell's PATH, then the interactive config's when it is needed, +/// by the rule `login_shell_path` describes. The interactive answer holds the +/// login PATH as well, so it is used whole; when it fails, the login answer is +/// kept. (bash, asked either way, reads `.bash_profile`, `.bash_login` or +/// `.profile`, not `.bashrc`, as Terminal's login shells do.) `inherited` is +/// the PATH this app has without the shell (with the `--node` folder, when +/// there is one), `agents` the agent commands looked up by name +/// (`agents::path_agent_commands`; an empty list asks for none), and +/// `always_interactive` is Check again. +#[cfg(unix)] +fn path_from_shell( + shell: &Path, + inherited: &str, + agents: &[String], + always_interactive: bool, +) -> Option { + let started = Instant::now(); + let login = shell_path(shell, false, LOGIN_PATH_TIMEOUT); + // `shell_path` returns at its limit only for a shell that never answered; + // one that fails returns well before it. + let timed_out = login.is_none() && started.elapsed() >= LOGIN_PATH_TIMEOUT; + let found = |program: &str| { + login.as_deref().is_some_and(|p| holds_program(p, program)) + || holds_program(inherited, program) + }; + // The app runs an agent, not just Node: one installed with `npm install + // -g` under nvm is on PATH only once `.zshrc` has run, even where another + // node (Homebrew's) is on the login PATH. Any one agent is enough. + let ready = found("node") && (agents.is_empty() || agents.iter().any(|agent| found(agent))); + if is_csh(shell) || timed_out || (ready && !always_interactive) { + if login.is_none() { + eprintln!( + "plan2code: {} gave no PATH from its login config (it {}); using the PATH this app started with", + shell.display(), + if timed_out { + format!("took over {LOGIN_PATH_TIMEOUT:?}") + } else { + "failed".to_string() + } + ); + } + return login; + } + let found = shell_path(shell, true, INTERACTIVE_PATH_TIMEOUT); + if found.is_none() { + eprintln!( + "plan2code: {} gave no PATH with its interactive config (it failed or took over {:?}); using {}", + shell.display(), + INTERACTIVE_PATH_TIMEOUT, + if login.is_some() { + "its login PATH" + } else { + "the PATH this app started with" + } + ); + } + found.or(login) +} + +/// Whether one of `path`'s absolute folders holds an executable regular file +/// named `program` (a symlink to one counts). Nothing is run: this only +/// decides whether the interactive config is worth asking. A relative entry is +/// never searched, since what it names depends on where the app happens to run. +#[cfg(unix)] +fn holds_program(path: &str, program: &str) -> bool { + use std::os::unix::fs::PermissionsExt; + path.split(':') + .filter(|dir| dir.starts_with('/')) + .any(|dir| { + std::fs::metadata(Path::new(dir).join(program)) + .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0) + }) +} + +/// csh and tcsh, which take `-l` only as their one flag. +#[cfg(unix)] +fn is_csh(shell: &Path) -> bool { + shell + .file_name() + .is_some_and(|name| name == "csh" || name == "tcsh") +} + +/// The PATH `shell` ends up with as a login shell (and an interactive one +/// when `interactive`), or `None` when it fails, prints no PATH, or takes +/// longer than `timeout`. The shell has no input and no terminal, and its +/// whole process group is killed when it ends, by itself or at the timeout. A +/// shell that answered but lingers (a slow logout file, an EXIT trap) is ended +/// after `LINGER_GRACE` and its answer kept. csh and tcsh ignore +/// `interactive`: they get `-l` alone and the command on stdin, and their +/// `.cshrc` runs either way. +#[cfg(unix)] +fn shell_path(shell: &Path, interactive: bool, timeout: Duration) -> Option { + use std::io::{Read, Write}; + use std::os::unix::process::CommandExt; + use std::process::Stdio; + use std::sync::Arc; + + // A fresh pair per call, written into the command in halves: a profile + // that echoes or replays commands cannot print a whole marker by accident. + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or_default(); + let tag = format!("__P2C_PATH_{}_{nanos}", std::process::id()); + let (start, end) = (format!("{tag}_START__"), format!("{tag}_END__")); + // fish keeps PATH as a list, so it joins the list with colons itself. + let command = if shell.file_name().is_some_and(|name| name == "fish") { + format!("printf '%s%s%s%s%s' '{tag}' '_START__' (string join : $PATH) '{tag}' '_END__'") + } else { + format!(r#"printf "%s%s%s%s%s" "{tag}" "_START__" "$PATH" "{tag}" "_END__""#) + }; + + let csh = is_csh(shell); + let mut cmd = Command::new(shell); + cmd.arg("-l"); + if csh { + // `-l` must be csh's only flag: the command goes on stdin, followed + // by end of input. + cmd.stdin(Stdio::piped()); + } else { + if interactive { + cmd.arg("-i"); + } + cmd.arg("-c").arg(&command).stdin(Stdio::null()); + } + cmd.stdout(Stdio::piped()).stderr(Stdio::null()); + // SAFETY: setsid(2) is async-signal-safe and touches no memory of this + // process, so it may run between fork and exec. A new session has no + // controlling terminal, so an interactive shell started under the + // launcher's terminal cannot take that terminal and be stopped; it is + // also a new process group, so the timeout's kill reaches every + // descendant. + unsafe { + cmd.pre_exec(|| { + if libc::setsid() == -1 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let mut child = cmd.spawn().ok()?; + if let Some(mut input) = child.stdin.take() { + // One short line, far under a pipe's buffer, so this never blocks. A + // shell that exits before reading it fails below like any other. + let _ = input.write_all(format!("{command}\n").as_bytes()); + } + + // Read on a thread of its own, so a full pipe never blocks the shell. + let sink = Arc::new(Mutex::new(Vec::new())); + let reader = child.stdout.take().map(|mut out| { + let sink = Arc::clone(&sink); + std::thread::spawn(move || { + let mut buf = [0u8; 8192]; + while let Ok(n) = out.read(&mut buf) { + if n == 0 { + break; + } + let mut kept = sink.lock().unwrap_or_else(|e| e.into_inner()); + let room = SHELL_OUTPUT_LIMIT.saturating_sub(kept.len()); + kept.extend_from_slice(&buf[..n.min(room)]); + } + }) + }); + + // The end marker is in: the answer is complete. + let answered = || { + let kept = sink.lock().unwrap_or_else(|e| e.into_inner()); + kept.windows(end.len()).any(|w| w == end.as_bytes()) + }; + + let deadline = Instant::now() + timeout; + let mut answered_at = None; + // `Some` once the shell exited by itself; `None` when it answered but + // lingered and was ended, which keeps the answer. + let exited = loop { + match child.try_wait() { + Ok(Some(status)) => break Some(status), + Ok(None) => { + let now = Instant::now(); + if answered_at.is_none() && answered() { + answered_at = Some(now); + } + match answered_at { + // Answered, then lingering past the grace: a slow logout + // file or an EXIT trap, which would otherwise cost the + // answer (and, at login, the fallback's answer too). + Some(at) if now >= at + LINGER_GRACE => { + kill_process_group(&mut child); + break None; + } + None if now >= deadline => { + kill_process_group(&mut child); + return None; + } + _ => std::thread::sleep(SHELL_POLL), + } + } + Err(_) => { + kill_process_group(&mut child); + return None; + } + } + }; + if let Some(status) = exited { + // A failed shell gives no answer: say so now, not after waiting on + // output a background job may hold open, and end what it left. + if !status.success() { + kill_process_group(&mut child); + return None; + } + // Something the profile started in the background can hold the pipe + // open after the shell exits: stop waiting once the end marker is in, + // and in any case once the timeout is up. Then end that job, as the + // linger and timeout paths do, which also lets the reader finish. + if let Some(reader) = reader { + while !reader.is_finished() && Instant::now() < deadline && !answered() { + std::thread::sleep(SHELL_POLL); + } + } + kill_process_group(&mut child); + } + let kept = sink.lock().unwrap_or_else(|e| e.into_inner()); + let text = String::from_utf8_lossy(&kept); + let from = text.find(&start)? + start.len(); + let path = &text[from..from + text[from..].find(&end)?]; + // A shell that does not expand "$PATH" (nushell, for one) prints it as it + // stands; with no absolute folder at all, the answer is not a PATH. One is + // enough: a real PATH may also carry relative entries such as `.`. + let is_a_path = path.split(':').any(|entry| entry.starts_with('/')); + is_a_path.then(|| path.to_string()) } /// What the PATH lookup is named after in the failure message: the login @@ -148,9 +427,10 @@ pub fn resolved_path() -> String { } /// Work the PATH out again, for "Check again" after an agent CLI was -/// installed: an installer may have added a folder (the login shell's -/// profile on macOS and Linux, the saved user or system PATH on Windows) -/// that this process's own PATH has never had. +/// installed: an installer may have added a folder (the shell's startup +/// files on macOS and Linux, read with the interactive config every time +/// here, or the saved user or system PATH on Windows) that this process's own +/// PATH has never had. pub fn refresh_path() { let fresh = build_path(true); *RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner()) = Some(fresh); @@ -163,8 +443,10 @@ fn build_path(fresh: bool) -> String { if let Some(dir) = node_override_dir(&args) { parts.push(dir); } + // A refresh is Check again, usually right after an install edited the + // shell's interactive config, so it always reads that config too. #[cfg(unix)] - if let Some(login) = login_shell_path() { + if let Some(login) = login_shell_path(&args, &inherited, fresh) { parts.push(login); } // This process's PATH is whatever its parent had, which is stale when @@ -178,8 +460,6 @@ fn build_path(fresh: bool) -> String { if fresh { parts.extend(saved.clone()); } - #[cfg(not(windows))] - let _ = fresh; if !inherited.is_empty() { parts.push(inherited); } @@ -455,52 +735,798 @@ mod tests { assert_eq!(shell_name(""), "sh"); } + /// A fresh, empty folder of this test's own, removed when the test ends, + /// whether it passes or fails. + #[cfg(unix)] + struct Scratch(std::path::PathBuf); + + #[cfg(unix)] + impl std::ops::Deref for Scratch { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } + } + + #[cfg(unix)] + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[cfg(unix)] + fn scratch(name: &str) -> Scratch { + let dir = + std::env::temp_dir().join(format!("plan2code-shellpath-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } + + /// A stand-in for the person's shell: a `/bin/sh` script named `name` + /// that gets `-l [-i] -c `, with `last` set to the command. Each + /// body sets its own PATH, so no test touches this process's environment. + /// + /// It is run once before it is returned: macOS checks a newly written + /// script on its first run, one at a time, which took 230 to 680 ms with + /// five at once (later runs: about 15 ms), longer than a short timeout. + /// + /// On Linux that first run can fail with ETXTBSY ("Text file busy"): + /// another test thread that forks while `write` still holds the file open + /// gives its child a copy of the write descriptor until that child execs + /// (rust-lang/rust#114554). The window is a few microseconds, so the run + /// is retried briefly; once one run has started, no write descriptor is + /// left anywhere and later runs are safe. + #[cfg(unix)] + fn fake_shell(dir: &std::path::Path, name: &str, body: &str) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; + let path = dir.join(name); + std::fs::write( + &path, + format!("#!/bin/sh\n[ -n \"$P2C_WARM\" ] && exit 0\nfor a; do last=$a; done\n{body}\n"), + ) + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + let mut busy = 0; + let warm = loop { + match Command::new(&path).env("P2C_WARM", "1").status() { + Err(e) if e.raw_os_error() == Some(libc::ETXTBSY) && busy < 50 => { + busy += 1; + std::thread::sleep(std::time::Duration::from_millis(10)); + } + result => break result.expect("start the fake shell"), + } + }; + assert!(warm.success(), "the fake shell did not start"); + path + } + + /// Whether `pid` is still a live process (a zombie waiting to be reaped + /// by init counts as gone). + #[cfg(unix)] + fn running(pid: &str) -> bool { + let out = Command::new("ps") + .args(["-o", "stat=", "-p", pid]) + .output() + .unwrap(); + let stat = String::from_utf8_lossy(&out.stdout); + let stat = stat.trim(); + !stat.is_empty() && !stat.starts_with('Z') + } + + #[cfg(unix)] #[test] - fn a_colon_path_is_kept_as_it_is() { - assert_eq!( - parse_path_output( - "/usr/local/bin:/usr/bin:/bin -" - ), - "/usr/local/bin:/usr/bin:/bin" + fn a_scratch_folder_is_removed_even_when_its_test_fails() { + let mut path = std::path::PathBuf::new(); + let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let dir = scratch("unwind"); + path = dir.to_path_buf(); + std::fs::write(dir.join("left"), "x").unwrap(); + panic!("a failing test"); + })); + assert!(failed.is_err()); + assert!( + !path.as_os_str().is_empty() && !path.exists(), + "{path:?} was left behind" ); } + /// For a fake that hangs: the test waits this long, so it stays short. + #[cfg(unix)] + const SHORT: std::time::Duration = std::time::Duration::from_millis(300); + + /// For a fake that answers: it returns as soon as the fake exits, so a + /// generous limit costs nothing and keeps a busy runner from failing it. + #[cfg(unix)] + const ROOMY: std::time::Duration = std::time::Duration::from_secs(5); + + #[cfg(unix)] #[test] - fn fish_s_space_separated_list_becomes_a_colon_list() { + fn shell_path_reads_only_what_sits_between_the_markers() { + let dir = scratch("noise"); + let shell = fake_shell( + &dir, + "zsh", + // `echo "$last"` stands in for a profile that echoes or replays + // commands: the markers sit in the command only in halves, so the + // echoed command text can never pass for the answer. + "echo 'Welcome back'\nprintf 'no newline here'\necho \"$last\"\nPATH=/fake/a:/fake/b\neval \"$last\"\necho\necho 'see you'", + ); assert_eq!( - parse_path_output( - "/home/sam/.nvm/bin /usr/local/bin /usr/bin -" - ), - "/home/sam/.nvm/bin:/usr/local/bin:/usr/bin" + shell_path(&shell, false, ROOMY).as_deref(), + Some("/fake/a:/fake/b") ); } + #[cfg(unix)] #[test] - fn a_banner_before_the_path_and_a_folder_with_a_space_are_handled() { + fn shell_path_always_asks_as_a_login_shell() { + let dir = scratch("login"); + // Answers only when `-l` comes first: the login profile is where + // Homebrew and most installers put their PATH lines. + let shell = fake_shell( + &dir, + "zsh", + "[ \"$1\" = -l ] || exit 1\nPATH=/login/bin\neval \"$last\"", + ); assert_eq!( - parse_path_output( - "Welcome back + shell_path(&shell, true, ROOMY).as_deref(), + Some("/login/bin") + ); + assert_eq!( + shell_path(&shell, false, ROOMY).as_deref(), + Some("/login/bin") + ); + } -/usr/bin:/bin -" + #[cfg(unix)] + #[test] + fn shell_path_gives_the_shell_no_input() { + let dir = scratch("stdin"); + // A profile that prompts or reads must see end of input at once, not + // the app's own stdin (a terminal when started from one). + let shell = fake_shell( + &dir, + "zsh", + "[ /dev/stdin -ef /dev/null ] || exit 1\nPATH=/fake/a\neval \"$last\"", + ); + assert_eq!(shell_path(&shell, true, ROOMY).as_deref(), Some("/fake/a")); + } + + #[cfg(unix)] + #[test] + fn shell_path_gives_up_on_a_hung_shell_and_leaves_nothing_running() { + let dir = scratch("hung"); + let pids = dir.join("pids"); + let shell = fake_shell( + &dir, + "zsh", + &format!("sleep 30 &\necho \"$$ $!\" > '{}'\nwait", pids.display()), + ); + let started = std::time::Instant::now(); + assert_eq!(shell_path(&shell, true, SHORT), None); + // Room for the kill and reap on a busy runner; far short of the 30 s + // sleep, so it still shows the timeout was kept. + assert!( + started.elapsed() < SHORT + std::time::Duration::from_millis(1500), + "took {:?}", + started.elapsed() + ); + let pids = std::fs::read_to_string(&pids).unwrap(); + let pids: Vec<&str> = pids.split_whitespace().collect(); + assert_eq!(pids.len(), 2, "the fake shell and its sleep"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while pids.iter().any(|pid| running(pid)) && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + for pid in &pids { + assert!(!running(pid), "process {pid} outlived the timeout"); + } + } + + #[cfg(unix)] + #[test] + fn shell_path_does_not_wait_on_a_background_job_holding_the_output() { + let dir = scratch("background"); + // The job keeps the shell's stdout open long after the shell exits. + let shell = fake_shell(&dir, "zsh", "sleep 3 &\nPATH=/fake/a\neval \"$last\""); + let started = std::time::Instant::now(); + assert_eq!(shell_path(&shell, false, ROOMY).as_deref(), Some("/fake/a")); + assert!( + started.elapsed() < std::time::Duration::from_secs(2), + "took {:?}", + started.elapsed() + ); + } + + /// Whether the job whose pid `file` holds is gone within two seconds. + #[cfg(unix)] + fn job_ends(file: &std::path::Path) -> bool { + let pid = std::fs::read_to_string(file).unwrap(); + let pid = pid.trim(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while running(pid) { + if std::time::Instant::now() >= deadline { + // Leave nothing behind for the next test, whatever the verdict. + let _ = std::process::Command::new("/bin/kill") + .args(["-9", pid]) + .status(); + return false; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + true + } + + #[cfg(unix)] + #[test] + fn a_job_the_profile_left_running_ends_with_the_shell_that_answered() { + let dir = scratch("job-after-answer"); + let pid = dir.join("pid"); + let shell = fake_shell( + &dir, + "zsh", + &format!( + "/bin/sleep 30 &\necho $! > '{}'\nPATH=/fake/a\neval \"$last\"", + pid.display() ), - "/usr/bin:/bin" + ); + assert_eq!(shell_path(&shell, false, ROOMY).as_deref(), Some("/fake/a")); + assert!(job_ends(&pid), "the profile's job outlived the call"); + } + + #[cfg(unix)] + #[test] + fn a_job_the_profile_left_running_ends_with_a_shell_that_failed() { + let dir = scratch("job-after-failure"); + let pid = dir.join("pid"); + let shell = fake_shell( + &dir, + "zsh", + &format!("/bin/sleep 30 &\necho $! > '{}'\nexit 1", pid.display()), + ); + assert_eq!(shell_path(&shell, false, ROOMY), None); + assert!(job_ends(&pid), "the profile's job outlived the call"); + } + + #[cfg(unix)] + #[test] + fn shell_path_keeps_an_answer_the_shell_lingers_after() { + let dir = scratch("linger"); + let pids = dir.join("pids"); + // Answers, then lingers as a slow `.zlogout` or EXIT trap would + // (`/bin/sleep` by its path: PATH is the fake one by then). + let shell = fake_shell( + &dir, + "zsh", + &format!( + "PATH=/fake/a\neval \"$last\"\n/bin/sleep 30 &\necho \"$$ $!\" > '{}'\nwait", + pids.display() + ), + ); + let started = std::time::Instant::now(); + assert_eq!(shell_path(&shell, true, ROOMY).as_deref(), Some("/fake/a")); + assert!( + started.elapsed() < std::time::Duration::from_secs(2), + "waited out the timeout: {:?}", + started.elapsed() + ); + let pids = std::fs::read_to_string(&pids).unwrap(); + let pids: Vec<&str> = pids.split_whitespace().collect(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while pids.iter().any(|pid| running(pid)) && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + for pid in &pids { + assert!(!running(pid), "process {pid} outlived the answer"); + } + } + + #[cfg(unix)] + #[test] + fn shell_path_gives_up_at_once_when_a_failed_shell_leaves_the_output_open() { + let dir = scratch("failed-background"); + // Fails with no answer while a job it started holds stdout open. + let shell = fake_shell(&dir, "zsh", "sleep 3 &\nexit 1"); + let started = std::time::Instant::now(); + assert_eq!(shell_path(&shell, false, ROOMY), None); + assert!( + started.elapsed() < std::time::Duration::from_secs(2), + "waited on the open output: {:?}", + started.elapsed() + ); + } + + #[cfg(unix)] + #[test] + fn shell_path_is_none_when_the_shell_fails() { + let dir = scratch("fails"); + let shell = fake_shell(&dir, "zsh", "PATH=/fake/a\neval \"$last\"\nexit 1"); + assert_eq!(shell_path(&shell, false, ROOMY), None); + } + + #[cfg(unix)] + #[test] + fn shell_path_reads_the_interactive_config_only_when_asked() { + let dir = scratch("interactive"); + let shell = fake_shell( + &dir, + "zsh", + "PATH=/usr/bin\nfor a; do [ \"$a\" = -i ] && PATH=/nvm/bin:/usr/bin; done\neval \"$last\"", ); assert_eq!( - parse_path_output( - "/Users/Jo Smith/bin -" - ), - "/Users/Jo Smith/bin" + shell_path(&shell, true, ROOMY).as_deref(), + Some("/nvm/bin:/usr/bin") ); assert_eq!( - parse_path_output( - " -" - ), - "" + shell_path(&shell, false, ROOMY).as_deref(), + Some("/usr/bin") ); } + + #[cfg(unix)] + #[test] + fn shell_path_asks_fish_in_its_own_syntax() { + let dir = scratch("fish"); + // Answers only a command that joins fish's PATH list itself. + let body = "case \"$last\" in *'(string join : $PATH)'*) ;; *) exit 1 ;; esac\nlast=$(printf '%s' \"$last\" | sed 's/(string join : \\$PATH)/\"$PATH\"/')\nPATH=/fish/a:/fish/b\neval \"$last\""; + let fish = fake_shell(&dir, "fish", body); + assert_eq!( + shell_path(&fish, true, ROOMY).as_deref(), + Some("/fish/a:/fish/b") + ); + let not_fish = fake_shell(&dir, "bash", body); + assert_eq!(shell_path(¬_fish, true, ROOMY), None); + } + + #[cfg(unix)] + #[test] + fn an_answer_with_no_absolute_folder_is_no_path() { + let dir = scratch("not-a-path"); + // A shell that does not expand "$PATH" (nushell, for one) prints it + // as it stands: joined into the app's PATH it would find nothing. + let literal = fake_shell(&dir, "nu", "PATH='$PATH'\neval \"$last\""); + assert_eq!(shell_path(&literal, true, ROOMY), None); + // A real PATH may carry relative entries too; one absolute folder + // is enough to show it is a PATH, and it is kept as it is. + let mixed = fake_shell(&dir, "zsh", "PATH=.:/usr/bin:bin\neval \"$last\""); + assert_eq!( + shell_path(&mixed, true, ROOMY).as_deref(), + Some(".:/usr/bin:bin") + ); + } + + #[cfg(unix)] + #[test] + fn csh_and_tcsh_get_a_lone_login_flag_and_the_command_on_stdin() { + let dir = scratch("csh"); + // csh and tcsh take `-l` only as their one flag ("Unknown option: + // `-l'" otherwise), so the command has to come on stdin. + let body = "[ \"$#\" = 1 ] && [ \"$1\" = -l ] || exit 1\nread -r last\nPATH=/csh/a:/csh/b\neval \"$last\""; + for name in ["csh", "tcsh"] { + let shell = fake_shell(&dir, name, body); + for interactive in [true, false] { + assert_eq!( + shell_path(&shell, interactive, ROOMY).as_deref(), + Some("/csh/a:/csh/b"), + "{name}, interactive {interactive}" + ); + } + } + } + + #[cfg(unix)] + #[test] + fn a_failing_csh_is_asked_once_since_a_second_run_reads_the_same_files() { + let dir = scratch("csh-once"); + let runs = dir.join("runs"); + // `.cshrc` runs for every csh, so a login-only retry would repeat + // exactly what just failed. + let shell = fake_shell( + &dir, + "tcsh", + &format!("echo run >> '{}'\nexit 1", runs.display()), + ); + assert_eq!(path_from_shell(&shell, "/usr/bin", NO_AGENTS, false), None); + let runs = std::fs::read_to_string(&runs).unwrap_or_default(); + assert_eq!( + runs.lines().count(), + 1, + "asked {} times", + runs.lines().count() + ); + } + + #[cfg(unix)] + #[test] + fn a_csh_with_no_node_is_still_asked_once_even_on_check_again() { + let dir = scratch("csh-once-no-node"); + let runs = dir.join("runs"); + // Its answer has no node, which for another shell would mean asking + // again with the interactive config; csh has no lighter config to + // leave out, so a second run would only repeat the first. + let shell = fake_shell( + &dir, + "csh", + &format!( + "echo run >> '{}'\nread -r last\nPATH=/csh/a\neval \"$last\"", + runs.display() + ), + ); + assert_eq!( + path_from_shell(&shell, "/usr/bin", NO_AGENTS, true).as_deref(), + Some("/csh/a") + ); + let runs = std::fs::read_to_string(&runs).unwrap_or_default(); + assert_eq!( + runs.lines().count(), + 1, + "asked {} times", + runs.lines().count() + ); + } + + /// The real thing where it ships (macOS has `/bin/tcsh`): its answer is + /// the machine's own PATH, so only its shape is checked. + #[cfg(unix)] + #[test] + fn the_real_tcsh_answers_when_it_is_installed() { + let tcsh = std::path::Path::new("/bin/tcsh"); + if !tcsh.exists() { + eprintln!("skipping: no /bin/tcsh"); + return; + } + let path = shell_path(tcsh, true, ROOMY).expect("tcsh gave a PATH"); + assert!(path.starts_with('/'), "{path}"); + } + + #[cfg(unix)] + #[test] + fn a_hung_interactive_config_keeps_the_login_path() { + let dir = scratch("fallback"); + let shell = fake_shell( + &dir, + "zsh", + "for a; do [ \"$a\" = -i ] && exec sleep 30; done\nPATH=/login/bin\neval \"$last\"", + ); + let started = std::time::Instant::now(); + // No node on either PATH, so the interactive config is asked for and + // hangs: the login answer it was asked after is kept. + assert_eq!( + path_from_shell(&shell, "/usr/bin", NO_AGENTS, false).as_deref(), + Some("/login/bin") + ); + // A quick login answer, then the 2 s interactive timeout. Room for a + // busy runner, and far short of the 30 s sleep, so the hung config + // was not waited on. + assert!( + started.elapsed() < INTERACTIVE_PATH_TIMEOUT + std::time::Duration::from_millis(1400), + "took {:?}", + started.elapsed() + ); + } + + /// No agent command to look for: the tests that are about Node alone. + #[cfg(unix)] + const NO_AGENTS: &[String] = &[]; + + /// A folder in `dir` holding an executable file named `node`, as nvm, + /// Homebrew or Volta leave one. `holds_program` never runs it. + #[cfg(unix)] + fn node_in(dir: &std::path::Path, folder: &str) -> String { + programs_in(dir, folder, &["node"]) + } + + /// A folder in `dir` holding an executable file for each of `programs`. + #[cfg(unix)] + fn programs_in(dir: &std::path::Path, folder: &str, programs: &[&str]) -> String { + use std::os::unix::fs::PermissionsExt; + let bin = dir.join(folder); + std::fs::create_dir_all(&bin).unwrap(); + for program in programs { + let file = bin.join(program); + std::fs::write(&file, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + bin.display().to_string() + } + + /// The agent commands the tests below look for. + #[cfg(unix)] + fn agents(names: &[&str]) -> Vec { + names.iter().map(|name| name.to_string()).collect() + } + + /// A fake shell whose PATH is `login` as a login shell and `interactive` + /// when also given `-i`, and which leaves `/ran-interactive` behind + /// when given `-i`, so a test can tell whether the interactive config ran. + #[cfg(unix)] + fn two_config_shell( + dir: &std::path::Path, + login: &str, + interactive: &str, + ) -> (std::path::PathBuf, std::path::PathBuf) { + let ran = dir.join("ran-interactive"); + let shell = fake_shell( + dir, + "zsh", + &format!( + "PATH='{login}'\nfor a; do [ \"$a\" = -i ] && {{ : > '{}'; PATH='{interactive}'; }}; done\neval \"$last\"", + ran.display() + ), + ); + (shell, ran) + } + + #[cfg(unix)] + #[test] + fn holds_program_wants_an_executable_file_in_an_absolute_folder() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("holds-program"); + let real = node_in(&dir, "real"); + assert!(holds_program(&real, "node")); + assert!(holds_program(&format!("/nowhere:{real}:."), "node")); + // A symlink to it, as Homebrew's `bin/node` is. + let linked = dir.join("linked"); + std::fs::create_dir_all(&linked).unwrap(); + std::os::unix::fs::symlink(format!("{real}/node"), linked.join("node")).unwrap(); + assert!(holds_program(&linked.display().to_string(), "node")); + // A folder named node, and a node nobody may run, do not count. + let folder = dir.join("folder"); + std::fs::create_dir_all(folder.join("node")).unwrap(); + assert!(!holds_program(&folder.display().to_string(), "node")); + let plain = dir.join("plain"); + std::fs::create_dir_all(&plain).unwrap(); + std::fs::write(plain.join("node"), "").unwrap(); + std::fs::set_permissions(plain.join("node"), std::fs::Permissions::from_mode(0o644)) + .unwrap(); + assert!(!holds_program(&plain.display().to_string(), "node")); + // A relative entry names a folder that depends on where the app + // happens to run, so it is never searched, even one that reaches a + // real node from here. + assert!(!holds_program("", "node")); + let cwd = std::env::current_dir().unwrap(); + let up = "../".repeat(cwd.components().count() - 1); + let relative = format!("{up}{}", real.trim_start_matches('/')); + assert!( + std::path::Path::new(&relative).join("node").is_file(), + "{relative} does not reach the node" + ); + assert!(!holds_program(&relative, "node")); + } + + #[cfg(unix)] + #[test] + fn node_on_the_login_path_never_runs_the_interactive_config() { + let dir = scratch("login-has-node"); + let login = node_in(&dir, "login-bin"); + let (shell, ran) = two_config_shell(&dir, &login, &format!("/nvm/bin:{login}")); + assert_eq!( + path_from_shell(&shell, "/usr/bin:/bin", NO_AGENTS, false).as_deref(), + Some(login.as_str()) + ); + assert!(!ran.exists(), "the interactive config ran"); + } + + #[cfg(unix)] + #[test] + fn node_on_the_login_path_with_no_agent_there_reads_the_interactive_config() { + // Homebrew's node on the login PATH, and the agent installed with + // `npm install -g` under nvm, which only `.zshrc` puts on PATH. + let dir = scratch("login-node-no-agent"); + let login = node_in(&dir, "brew-bin"); + let interactive = format!( + "{}:{login}", + programs_in(&dir, "nvm-bin", &["node", "claude"]) + ); + let (shell, ran) = two_config_shell(&dir, &login, &interactive); + assert_eq!( + path_from_shell(&shell, "/usr/bin", &agents(&["claude", "codex"]), false).as_deref(), + Some(interactive.as_str()) + ); + assert!(ran.exists(), "the interactive config never ran"); + } + + #[cfg(unix)] + #[test] + fn node_and_one_agent_on_the_login_path_never_run_the_interactive_config() { + let dir = scratch("login-node-and-agent"); + let login = programs_in(&dir, "login-bin", &["node", "codex"]); + let (shell, ran) = two_config_shell(&dir, &login, &format!("/nvm/bin:{login}")); + assert_eq!( + path_from_shell(&shell, "/usr/bin", &agents(&["claude", "codex"]), false).as_deref(), + Some(login.as_str()) + ); + assert!(!ran.exists(), "the interactive config ran"); + } + + #[cfg(unix)] + #[test] + fn an_agent_on_the_inherited_path_counts_as_found() { + let dir = scratch("inherited-agent"); + let login = node_in(&dir, "login-bin"); + let inherited = format!( + "{}:/usr/bin", + programs_in(&dir, "terminal-bin", &["claude"]) + ); + let (shell, ran) = two_config_shell(&dir, &login, &format!("/nvm/bin:{login}")); + assert_eq!( + path_from_shell(&shell, &inherited, &agents(&["claude"]), false).as_deref(), + Some(login.as_str()) + ); + assert!(!ran.exists(), "the interactive config ran"); + } + + #[cfg(unix)] + #[test] + fn node_only_in_the_interactive_config_is_found() { + let dir = scratch("interactive-has-node"); + let interactive = format!("{}:/usr/bin", node_in(&dir, "nvm-bin")); + let (shell, ran) = two_config_shell(&dir, "/usr/bin", &interactive); + assert_eq!( + path_from_shell(&shell, "/usr/bin:/bin", NO_AGENTS, false).as_deref(), + Some(interactive.as_str()) + ); + assert!(ran.exists(), "the interactive config never ran"); + } + + #[cfg(unix)] + #[test] + fn node_on_the_inherited_path_never_runs_the_interactive_config() { + let dir = scratch("inherited-has-node"); + let inherited = format!("{}:/usr/bin", node_in(&dir, "terminal-bin")); + let (shell, ran) = two_config_shell(&dir, "/usr/bin", "/nvm/bin:/usr/bin"); + assert_eq!( + path_from_shell(&shell, &inherited, NO_AGENTS, false).as_deref(), + Some("/usr/bin") + ); + assert!(!ran.exists(), "the interactive config ran"); + } + + #[cfg(unix)] + #[test] + fn a_node_nobody_may_run_does_not_stop_the_interactive_config() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("login-plain-node"); + let plain = dir.join("plain"); + std::fs::create_dir_all(&plain).unwrap(); + std::fs::write(plain.join("node"), "").unwrap(); + std::fs::set_permissions(plain.join("node"), std::fs::Permissions::from_mode(0o644)) + .unwrap(); + let login = plain.display().to_string(); + let (shell, ran) = two_config_shell(&dir, &login, "/nvm/bin"); + assert_eq!( + path_from_shell(&shell, "/usr/bin", NO_AGENTS, false).as_deref(), + Some("/nvm/bin") + ); + assert!(ran.exists(), "the interactive config never ran"); + } + + #[cfg(unix)] + #[test] + fn check_again_reads_the_interactive_config_even_with_node_on_the_login_path() { + let dir = scratch("check-again"); + let login = node_in(&dir, "login-bin"); + let interactive = format!("/new/bin:{login}"); + let (shell, ran) = two_config_shell(&dir, &login, &interactive); + assert_eq!( + path_from_shell(&shell, "/usr/bin", NO_AGENTS, true).as_deref(), + Some(interactive.as_str()) + ); + assert!(ran.exists(), "the interactive config never ran"); + } + + #[cfg(unix)] + #[test] + fn with_node_nowhere_the_interactive_answer_wins_and_a_failed_one_keeps_the_login_path() { + let dir = scratch("no-node"); + // Its answer holds the login PATH and what `.zshrc` adds, so it is + // used whole even when it found no node either. + let (shell, ran) = two_config_shell(&dir, "/usr/bin", "/rc/bin:/usr/bin"); + assert_eq!( + path_from_shell(&shell, "/usr/bin", NO_AGENTS, false).as_deref(), + Some("/rc/bin:/usr/bin") + ); + assert!(ran.exists(), "the interactive config never ran"); + let failing = fake_shell( + &dir, + "bash", + "for a; do [ \"$a\" = -i ] && exit 1; done\nPATH=/login/bin\neval \"$last\"", + ); + assert_eq!( + path_from_shell(&failing, "/usr/bin", NO_AGENTS, false).as_deref(), + Some("/login/bin") + ); + } + + #[cfg(unix)] + #[test] + fn a_hung_login_config_is_not_asked_again_with_the_interactive_one() { + let dir = scratch("login-hangs"); + let pids = dir.join("pids"); + let ran = dir.join("ran-interactive"); + // The interactive config would answer at once, but it reads the same + // login files first, so a real one would hang the same way. + let shell = fake_shell( + &dir, + "zsh", + &format!( + "for a; do [ \"$a\" = -i ] && {{ : > '{}'; PATH=/nvm/bin; eval \"$last\"; exit 0; }}; done\n/bin/sleep 30 &\necho \"$$ $!\" > '{}'\nwait", + ran.display(), + pids.display() + ), + ); + for always_interactive in [false, true] { + let _ = std::fs::remove_file(&pids); + let started = std::time::Instant::now(); + assert_eq!( + path_from_shell(&shell, "/usr/bin", NO_AGENTS, always_interactive), + None + ); + assert!( + started.elapsed() < LOGIN_PATH_TIMEOUT + std::time::Duration::from_millis(1500), + "took {:?}", + started.elapsed() + ); + assert!(!ran.exists(), "the interactive config ran"); + let pids = std::fs::read_to_string(&pids).unwrap(); + let pids: Vec<&str> = pids.split_whitespace().collect(); + assert_eq!(pids.len(), 2, "the fake shell and its sleep"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while pids.iter().any(|pid| running(pid)) && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + for pid in &pids { + assert!(!running(pid), "process {pid} outlived the timeout"); + } + } + } + + #[cfg(unix)] + #[test] + fn fresh_decides_whether_a_found_node_skips_the_interactive_config() { + let dir = scratch("build-path-core"); + let login = node_in(&dir, "login-bin"); + let interactive = format!("/new/bin:{login}"); + let (shell, ran) = two_config_shell(&dir, &login, &interactive); + let args = vec!["plan2code".to_string()]; + // At start, node on the login PATH is enough. + assert_eq!( + login_shell_path_for(&shell, &args, "/usr/bin", NO_AGENTS, false).as_deref(), + Some(login.as_str()) + ); + assert!(!ran.exists(), "the interactive config ran at start"); + // Check again reads it anyway: an install has usually just edited it. + assert_eq!( + login_shell_path_for(&shell, &args, "/usr/bin", NO_AGENTS, true).as_deref(), + Some(interactive.as_str()) + ); + assert!( + ran.exists(), + "Check again never read the interactive config" + ); + } + + #[cfg(unix)] + #[test] + fn the_node_folder_from_the_launcher_skips_the_interactive_config() { + let dir = scratch("node-arg"); + let given = node_in(&dir, "launcher-bin"); + let (shell, ran) = two_config_shell(&dir, "/usr/bin", "/nvm/bin:/usr/bin"); + for args in [ + vec![ + "plan2code".to_string(), + "--node".to_string(), + format!("{given}/node"), + ], + vec!["plan2code".to_string(), format!("--node={given}/node")], + ] { + assert_eq!( + login_shell_path_for(&shell, &args, "/usr/bin", NO_AGENTS, false).as_deref(), + Some("/usr/bin") + ); + assert!(!ran.exists(), "the interactive config ran: {args:?}"); + } + } }