A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
Add default shell runtime selection
RoversX90fccb63ed0a
diff --git a/mux/src/default_prog.rs b/mux/src/default_prog.rsnew file mode 100644index 00000000..11a50fd8--- /dev/null+++ b/mux/src/default_prog.rs@@ -0,0 +1,129 @@+//! The process-wide "which shell should a new pane run" preference.+//!+//! The GUI owns a native setting for this; the mux is where every local+//! spawn resolves its program, so the choice is installed here as a+//! process-local override rather than plumbed through each spawn site.+//! Only the GUI installs one — a headless mux server has no such setting,+//! so a client's local preference can never decide what a remote server+//! spawns.++use parking_lot::RwLock;+use std::sync::Arc;++type Preference = Arc<dyn Fn() -> Option<Vec<String>> + Send + Sync>;++lazy_static::lazy_static! {+ static ref PREFERENCE: RwLock<Option<Preference>> = RwLock::new(None);+}++/// Install the preference. The closure is consulted on every local spawn+/// that has not been given an explicit program, so it must be cheap; the+/// GUI reads a cached settings handle.+pub fn set_process_preference(+ preference: impl Fn() -> Option<Vec<String>> + Send + Sync + 'static,+) {+ *PREFERENCE.write() = Some(Arc::new(preference));+}++/// The argv the user chose, if any. `None` means "no preference": keep the+/// platform default (`$SHELL` / `%ComSpec%`) or whatever the Lua config+/// asked for.+pub fn preferred_argv() -> Option<Vec<String>> {+ // Cloned out and the guard dropped before the closure runs: it checks+ // that the chosen shell still exists, and a stalled filesystem must+ // not be able to hold this lock -- and every later spawn -- with it.+ let preference = PREFERENCE.read().clone()?;+ let argv = preference()?;+ if argv.is_empty() {+ return None;+ }+ Some(argv)+}++/// How a chosen shell should be applied to a command that is still asking+/// for the default program.+///+/// The two arms exist because the login-shell convention is expressed+/// differently per platform, not as a style choice:+///+/// * On unix a login shell is spawned by prefixing argv0 with `-`, and+/// `CommandBuilder` only does that while the command is still flagged as+/// the default program (`is_default_prog`). Filling in argv would clear+/// that flag and silently downgrade every pane to a non-login shell —+/// no `.zprofile`, a different PATH. Pointing `SHELL` at the choice+/// instead keeps the flag, and `CommandBuilder::get_shell` already+/// prefers `SHELL`, checks it is executable, and falls back when it is+/// not.+/// * On Windows there is no login-shell concept, so the argv is written+/// directly. `ComSpec` is deliberately NOT used to express the choice:+/// it means "the command processor" to everything downstream (batch+/// files, `%ComSpec%` references), and because it lives in the+/// builder's environment it would be serialized to a remote server and+/// change what *that* machine spawns.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ShellApplication {+ /// Set `SHELL` to this program and leave the default-prog flag alone.+ ShellEnv(String),+ /// Write this argv into the command.+ Argv(Vec<String>),+}++/// Decide how to apply `argv`. A bare program on unix travels as `SHELL`;+/// anything the user spelled out with arguments is taken literally,+/// because they asked for exactly that command line.+pub fn shell_application(argv: &[String], windows: bool) -> Option<ShellApplication> {+ let program = argv.first()?;+ if !windows && argv.len() == 1 {+ return Some(ShellApplication::ShellEnv(program.clone()));+ }+ Some(ShellApplication::Argv(argv.to_vec()))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_bare_unix_shell_travels_as_the_shell_env_var() {+ // The login-shell argv0 is only applied while the command is still+ // the default program, so a bare choice must not fill in argv.+ assert_eq!(+ shell_application(&["/bin/bash".to_string()], false),+ Some(ShellApplication::ShellEnv("/bin/bash".to_string()))+ );+ }++ #[test]+ fn a_unix_choice_with_arguments_is_taken_literally() {+ let argv = vec!["/bin/bash".to_string(), "--norc".to_string()];+ assert_eq!(+ shell_application(&argv, false),+ Some(ShellApplication::Argv(argv))+ );+ }++ #[test]+ fn windows_always_writes_argv() {+ // No login shell to preserve, and ComSpec must keep meaning cmd.exe.+ assert_eq!(+ shell_application(&["pwsh.exe".to_string()], true),+ Some(ShellApplication::Argv(vec!["pwsh.exe".to_string()]))+ );+ }++ #[test]+ fn an_empty_choice_is_not_a_choice() {+ assert_eq!(shell_application(&[], false), None);+ assert_eq!(shell_application(&[], true), None);+ }++ #[test]+ fn an_empty_preference_is_treated_as_no_choice() {+ // A preference that answers "nothing" must read the same as never+ // having installed one, which is what every headless mux server is.+ let preference: Preference = Arc::new(|| None);+ assert_eq!(preference(), None);+ let empty: Preference = Arc::new(|| Some(vec![]));+ assert!(empty().is_some_and(|argv| argv.is_empty()));+ }+}diff --git a/mux/src/domain.rs b/mux/src/domain.rsindex 84d59307..e471a9f3 100644--- a/mux/src/domain.rs+++ b/mux/src/domain.rs@@ -206,10 +206,38 @@ pub trait Domain: Downcast + Send + Sync {}impl_downcast!(Domain);+/// Inside a Flatpak sandbox `fixup_command` re-routes the spawn to the+/// host through `flatpak-spawn` and resolves the host's own login shell+/// itself, so a choice made here would not be honored -- and the paths+/// this process can see belong to the sandbox runtime, not to the host+/// that would run them. Cached: the file cannot appear or disappear+/// while the process lives, and this is consulted on every spawn.+fn running_under_flatpak() -> bool {+ static UNDER_FLATPAK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *UNDER_FLATPAK.get_or_init(|| Path::new("/.flatpak-info").exists())+}++/// What a `LocalDomain` actually spawns into.+///+/// Recorded at construction rather than inferred from the config: a+/// `thinkterm serial ...` invocation builds its domain from the command+/// line and never registers it in `serial_ports`, so a config lookup+/// would classify it as an ordinary local domain and apply settings that+/// break it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum LocalDomainKind {+ /// Programs run directly on this machine.+ Plain,+ /// A serial port: the pty ignores the command and accepts only the+ /// default program.+ Serial,+}+pub struct LocalDomain {pty_system: Mutex<Box<dyn PtySystem + Send>>,id: DomainId,name: String,+ kind: LocalDomainKind,}impl LocalDomain {@@ -217,6 +245,11 @@ impl LocalDomain {Ok(Self::with_pty_system(name, native_pty_system()))}+ fn with_kind(mut self, kind: LocalDomainKind) -> Self {+ self.kind = kind;+ self+ }+fn resolve_exec_domain(&self) -> Option<ExecDomain> {config::configuration().exec_domains@@ -225,6 +258,20 @@ impl LocalDomain {.cloned()}+ /// Whether this domain runs programs directly on this machine.+ ///+ /// WSL, exec and serial domains are all `LocalDomain`s that run+ /// somewhere else -- inside a distribution, inside a container, or+ /// not as a process at all -- so a shell chosen for *this* machine is+ /// meaningless to them, and forcing one on them breaks them: a serial+ /// pty rejects any command that is not the default program outright.+ fn is_plain_local_domain(&self, wsl: Option<&WslDomain>) -> bool {+ self.kind == LocalDomainKind::Plain+ && wsl.is_none()+ && self.resolve_exec_domain().is_none()+ && !running_under_flatpak()+ }+fn resolve_wsl_domain(&self) -> Option<WslDomain> {config::configuration().wsl_domains()@@ -239,6 +286,7 @@ impl LocalDomain {pty_system: Mutex::new(pty_system),id,name: name.to_string(),+ kind: LocalDomainKind::Plain,}}@@ -257,7 +305,8 @@ impl LocalDomain {serial.set_baud_rate(baud as u32);}let pty_system = Box::new(serial);- Ok(Self::with_pty_system(&serial_domain.name, pty_system))+ Ok(Self::with_pty_system(&serial_domain.name, pty_system)+ .with_kind(LocalDomainKind::Serial))}#[cfg(unix)]@@ -462,10 +511,37 @@ impl LocalDomain {let config = configuration();let wsl = self.resolve_wsl_domain();- let default_prog = wsl+ // The user's chosen shell occupies the same slot as the Lua+ // `default_prog`, one tier above it. Sitting in that slot is what+ // keeps a WSL pane out of it: the arm below deliberately never+ // consults the global default for a WSL domain, because a program+ // chosen for this machine is meaningless inside the distribution.+ // Only a command that is still asking for the default program can+ // be affected, so an explicit `wezterm cli spawn -- htop` never+ // pays for consulting the preference (which stats the chosen+ // shell to confirm it still exists).+ let wants_default_prog = command.as_ref()- .map(|wsl| wsl.default_prog.as_ref())- .unwrap_or(config.default_prog.as_ref());+ .map(|cmd| cmd.is_default_prog())+ .unwrap_or(true);+ let chosen_shell = (wants_default_prog && self.is_plain_local_domain(wsl.as_ref()))+ .then(crate::default_prog::preferred_argv)+ .flatten();+ let chosen_application = chosen_shell+ .as_deref()+ .and_then(|argv| crate::default_prog::shell_application(argv, cfg!(windows)));+ let chosen_argv = match &chosen_application {+ Some(crate::default_prog::ShellApplication::Argv(argv)) => Some(argv),+ _ => None,+ };++ let default_prog = match (&wsl, &chosen_application) {+ (Some(wsl), _) => wsl.default_prog.as_ref(),+ // The choice wins over the Lua option: a stale `default_prog`+ // must not make the settings dropdown look inert.+ (None, Some(_)) => chosen_argv,+ (None, None) => config.default_prog.as_ref(),+ };let mut cmd = match command {Some(mut cmd) => {@@ -480,6 +556,18 @@ impl LocalDomain {.unwrap_or(config.default_cwd.as_ref()),)?,};+ // Applied after the command exists, and only while it is still+ // asking for the default program, so an explicitly spawned program+ // (`wezterm cli spawn -- htop`) keeps its own argv and its own+ // inherited SHELL.+ if let Some(crate::default_prog::ShellApplication::ShellEnv(shell)) = &chosen_application {+ // A caller that set SHELL for this spawn meant it -- the+ // documented `SpawnCommand { set_environment_variables = {+ // SHELL = ... } }` idiom must outrank a global preference.+ if cmd.is_default_prog() && cmd.get_env("SHELL").is_none() {+ cmd.env("SHELL", shell);+ }+ }if let Some(dir) = command_dir {// Paths entered in the UI (or relayed by a mux client) may use// `~` for the home directory; the spawn cwd is used verbatim bydiff --git a/mux/src/lib.rs b/mux/src/lib.rsindex 754a565d..76825af2 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -41,6 +41,7 @@ pub mod agent_status;pub mod client;pub mod command_spec;pub mod connui;+pub mod default_prog;pub mod domain;pub mod geometrytrace;pub mod localpane;diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 0d7d6c00..19d1d2a0 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -61,6 +61,7 @@ mod secret;mod selection;mod settings_window;mod shapecache;+mod shell_catalog;mod snippets;mod spawn;mod ssh_hosts;@@ -1149,6 +1150,11 @@ fn setup_mux(mux::agent_status::set_process_preference(|| {crate::native_settings::agent_panel_enabled()});+ // The user-facing shell choice reaches every local spawn from here.+ // A headless mux server installs nothing, so this preference can only+ // ever decide what *this* process spawns, never what a remote server+ // runs for us.+ mux::default_prog::set_process_preference(crate::native_settings::default_shell);let client_id = Arc::new(mux::client::generate_client_id());mux.register_client(client_id.clone());mux.replace_identity(Some(client_id));@@ -1221,6 +1227,14 @@ fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) ->let cmd = if need_builder {let prog = opts.prog.iter().map(|s| s.as_os_str()).collect::<Vec<_>>();+ // Deliberately still the Lua option, not the chosen shell: this+ // resolves before any domain exists and the command may be routed+ // to a remote/exec domain that never reaches the local tiers, so+ // suppressing it here would break `default_prog` for those. The+ // consequence is narrow and documented: with BOTH a Lua+ // `default_prog` and a chosen shell, `--cwd` startups follow the+ // Lua one. Every other spawn goes through LocalDomain::build_command+ // where the choice outranks it.let mut builder = config.build_prog(if prog.is_empty() { None } else { Some(prog) },config.default_prog.as_ref(),diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex dd51edce..885394e6 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -207,12 +207,49 @@ pub(crate) struct NativeTerminalSettings {pub(crate) bottom_quote_mode: NativeBottomQuoteMode,pub(crate) bottom_quote_interval_minutes: Option<u32>,pub(crate) bottom_quote_font_size: Option<f64>,+ /// The program a new pane runs, as argv. `None` means the platform+ /// default (`$SHELL` / `%ComSpec%`).+ pub(crate) default_shell: Option<Vec<String>>,}pub(crate) fn remote_pane_resize_mode() -> NativeRemotePaneResizeMode {load().terminal.remote_pane_resize_mode}+/// The shell the user picked, if any. Read on every local spawn, so it+/// goes through the cached handle rather than `load`, which deep-clones+/// the whole settings tree.+///+/// A choice that no longer exists is dropped rather than passed on, so an+/// uninstalled shell degrades to the platform default instead of leaving+/// the user unable to open a terminal at all.+pub(crate) fn default_shell() -> Option<Vec<String>> {+ let argv = load_shared()+ .terminal+ .default_shell+ .as_ref()+ .filter(|argv| !argv.is_empty())+ .cloned()?;+ let Some(resolved) = crate::shell_catalog::resolve_chosen_argv_now(&argv) else {+ // Warned about once per distinct choice: this is consulted once per+ // pane, so restoring a large layout would otherwise repeat the same+ // line dozens of times.+ static WARNED_FOR: OnceLock<Mutex<Option<String>>> = OnceLock::new();+ let warned = WARNED_FOR.get_or_init(|| Mutex::new(None));+ let mut warned = warned.lock();+ if warned.as_deref() != Some(argv[0].as_str()) {+ *warned = Some(argv[0].clone());+ log::warn!(+ "the chosen default shell {:?} is not an executable file; \+ falling back to the system default",+ argv[0]+ );+ }+ return None;+ };+ Some(resolved)+}+#[derive(Debug, Clone, Default, Deserialize, Serialize)]#[serde(default)]pub(crate) struct NativeChromeSettings {diff --git a/wezterm-gui/src/shell_catalog.rs b/wezterm-gui/src/shell_catalog.rsnew file mode 100644index 00000000..039a458b--- /dev/null+++ b/wezterm-gui/src/shell_catalog.rs@@ -0,0 +1,494 @@+//! Which shells this machine actually has, for the default-shell setting.+//!+//! Both platform tables are consulted unconditionally and the module+//! carries no `cfg`: discovery is only "read some environment variables,+//! join some paths, check what exists", and those are cross-platform+//! APIs. A Windows variable is simply absent on a mac, so that table+//! yields nothing there — and the reverse for the unix paths. Keeping it+//! that way is deliberate: the Windows candidates then compile and are+//! unit-tested on the development machine instead of only in CI, which+//! is the same reason `mux::agent_status::windows_select` keeps its core+//! pure.++use std::collections::HashSet;+use std::path::{Path, PathBuf};++/// A shell the user can pick. `argv` is what a pane will run; `label` is+/// what the dropdown shows.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct DiscoveredShell {+ pub label: String,+ pub argv: Vec<String>,+}++impl DiscoveredShell {+ fn new(label: &str, program: &str) -> Self {+ Self {+ label: label.to_string(),+ argv: vec![program.to_string()],+ }+ }+}++/// Windows candidates, most conventional first. PowerShell 7 is looked up+/// by explicit version directory rather than by listing `PowerShell\*`,+/// because probing paths is all this module is allowed to do. A version+/// installed somewhere else is not offered yet -- the planned "Custom"+/// entry is what will reach it; until then, `default_shell` in+/// settings.json.+const WINDOWS_POWERSHELL_VERSIONS: &[&str] = &["7", "8"];++/// Unix candidates, curated rather than taken from `/etc/shells`: that+/// file lists `csh`, `dash`, `ksh` and `tcsh` on a stock mac, which+/// nobody is choosing here, and the dropdown has no room to spare (its+/// menu neither scrolls nor flips upward). The login shell is offered+/// whatever it is, so an omission only bites a shell that is neither in+/// this table nor the user's own; until the "Custom" entry lands, that+/// case means `default_shell` in settings.json.+const UNIX_SHELLS: &[(&str, &str)] = &[+ ("zsh", "zsh"),+ ("bash", "bash"),+ ("fish", "fish"),+ ("nushell", "nu"),+ ("sh", "sh"),+];++/// Where unix shells live, in the order a user would expect to get: a+/// Homebrew fish should win over a system one of the same name.+const UNIX_PREFIXES: &[&str] = &[+ "/opt/homebrew/bin",+ "/usr/local/bin",+ "/usr/bin",+ "/bin",+ "/usr/local/sbin",+];++/// The shells present on this machine.+pub(crate) fn discover() -> Vec<DiscoveredShell> {+ discover_with(&real_env, &is_executable_file)+}++/// `SHELL` is deliberately absent: `env_bootstrap` removes it at startup+/// because it is stale after `chsh`, so reading it here would always come+/// back empty. The login shell is resolved the way the rest of this crate+/// does it -- through the password database, via the same helper the+/// spawn path itself uses.+fn real_env(name: &str) -> Option<String> {+ if name == "SHELL" {+ let shell = portable_pty::CommandBuilder::new_default_prog().get_shell();+ return (!shell.is_empty()).then_some(shell);+ }+ std::env::var(name).ok()+}++/// A candidate has to be a file this process could actually execute.+/// `exists` is not enough: a directory, or a binary left non-executable by+/// an interrupted upgrade, would pass it and then fail at spawn time with+/// the pane never opening.+fn is_executable_file(path: &str) -> bool {+ let Ok(metadata) = Path::new(path).metadata() else {+ return false;+ };+ if !metadata.is_file() {+ return false;+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ metadata.permissions().mode() & 0o111 != 0+ }+ #[cfg(not(unix))]+ true+}++/// The testable core. `env` reads an environment variable, `exists`+/// answers whether a path is present; both are injected so the whole+/// table can be exercised for either platform from any host.+pub(crate) fn discover_with(+ env: &dyn Fn(&str) -> Option<String>,+ exists: &dyn Fn(&str) -> bool,+) -> Vec<DiscoveredShell> {+ let mut found = vec![];+ let mut seen = HashSet::new();++ let push = |shell: DiscoveredShell, seen: &mut HashSet<String>, found: &mut Vec<_>| {+ // Keyed by program, so the same shell reached through two+ // candidate paths is offered once.+ if seen.insert(shell.argv[0].clone()) {+ found.push(shell);+ }+ };++ // The user's current login shell first: it is the one they already+ // chose, and it is routinely absent from any fixed table (a Homebrew+ // fish, a hand-built zsh).+ if let Some(shell) = env("SHELL").filter(|shell| exists(shell)) {+ let label = file_stem(&shell).unwrap_or_else(|| shell.clone());+ push(DiscoveredShell::new(&label, &shell), &mut seen, &mut found);+ }++ for (label, program) in UNIX_SHELLS {+ for prefix in UNIX_PREFIXES {+ let path = PathBuf::from(prefix).join(program);+ let path = path.to_string_lossy().into_owned();+ if exists(&path) {+ push(DiscoveredShell::new(label, &path), &mut seen, &mut found);+ break;+ }+ }+ }++ for shell in windows_candidates(env, exists) {+ push(shell, &mut seen, &mut found);+ }++ found+}++fn windows_candidates(+ env: &dyn Fn(&str) -> Option<String>,+ exists: &dyn Fn(&str) -> bool,+) -> Vec<DiscoveredShell> {+ let mut found = vec![];++ let system_root = env("SystemRoot").unwrap_or_else(|| r"C:\Windows".to_string());++ // ComSpec is the command processor this machine actually uses; the+ // System32 path is the fallback for a stripped environment.+ let cmd = env("ComSpec").filter(|path| exists(path)).or_else(|| {+ let path = join_windows(&system_root, &["System32", "cmd.exe"]);+ exists(&path).then_some(path)+ });+ if let Some(cmd) = cmd {+ found.push(DiscoveredShell::new("Command Prompt", &cmd));+ }++ let powershell = join_windows(+ &system_root,+ &["System32", "WindowsPowerShell", "v1.0", "powershell.exe"],+ );+ if exists(&powershell) {+ found.push(DiscoveredShell::new("Windows PowerShell", &powershell));+ }++ // Newest first, so "PowerShell" means the most capable one installed.+ for program_files in ["ProgramFiles", "ProgramFiles(x86)"] {+ let Some(root) = env(program_files) else {+ continue;+ };+ for version in WINDOWS_POWERSHELL_VERSIONS.iter().rev() {+ let path = join_windows(&root, &["PowerShell", version, "pwsh.exe"]);+ if exists(&path) {+ found.push(DiscoveredShell::new(+ &format!("PowerShell {version}"),+ &path,+ ));+ break;+ }+ }+ }++ // The Store build installs an alias here rather than under Program+ // Files, and it is the only pwsh some machines have.+ if !found+ .iter()+ .any(|shell| shell.label.starts_with("PowerShell "))+ {+ if let Some(local) = env("LOCALAPPDATA") {+ let path = join_windows(&local, &["Microsoft", "WindowsApps", "pwsh.exe"]);+ if exists(&path) {+ found.push(DiscoveredShell::new("PowerShell", &path));+ }+ }+ }++ if let Some(nu) = search_windows_path("nu.exe", env, exists) {+ found.push(DiscoveredShell::new("nushell", &nu));+ }++ found+}++fn search_windows_path(+ program: &str,+ env: &dyn Fn(&str) -> Option<String>,+ exists: &dyn Fn(&str) -> bool,+) -> Option<String> {+ let path = env("PATH")?;+ path.split(';')+ .filter(|entry| !entry.is_empty())+ .map(|entry| join_windows(entry, &[program]))+ .find(|candidate| exists(candidate))+}++/// Joined textually rather than through `PathBuf`, so a Windows path+/// keeps its backslashes when this runs on a unix host under test.+fn join_windows(root: &str, parts: &[&str]) -> String {+ let mut path = root.trim_end_matches('\\').to_string();+ for part in parts {+ path.push('\\');+ path.push_str(part);+ }+ path+}++/// The argv to actually spawn for a stored choice, with its program+/// resolved to something the spawn path can run, or `None` when the+/// choice cannot be run at all.+///+/// A shell uninstalled since it was chosen must fall back to the platform+/// default rather than take the pane down with it: on Windows an+/// unfindable program is handed to the OS verbatim and the spawn simply+/// fails, so the terminal never opens.+///+/// A bare program name is resolved against `PATH` here rather than+/// trusted: on unix the choice travels as `SHELL`, and+/// `CommandBuilder::get_shell` checks it with `access()`, which resolves+/// a bare name against the *working directory*, not `PATH` — so an+/// unresolved `fish` would silently do nothing at all. Everything this+/// module discovers is already absolute; a bare name only reaches here+/// from a hand-edited settings file.+pub(crate) fn resolve_chosen_argv(+ argv: &[String],+ windows: bool,+ path_var: Option<String>,+ usable: &dyn Fn(&str) -> bool,+) -> Option<Vec<String>> {+ let program = argv.first()?;+ let resolved = if program.contains('/') || program.contains('\\') {+ usable(program).then(|| program.clone())?+ } else {+ let separator = if windows { ';' } else { ':' };+ path_var?+ .split(separator)+ .filter(|entry| !entry.is_empty())+ .map(|entry| {+ let mut candidate = entry.trim_end_matches(['/', '\\']).to_string();+ candidate.push(if windows { '\\' } else { '/' });+ candidate.push_str(program);+ candidate+ })+ .find(|candidate| usable(candidate))?+ };+ let mut argv = argv.to_vec();+ argv[0] = resolved;+ Some(argv)+}++/// `resolve_chosen_argv` against this machine.+pub(crate) fn resolve_chosen_argv_now(argv: &[String]) -> Option<Vec<String>> {+ resolve_chosen_argv(+ argv,+ cfg!(windows),+ std::env::var("PATH").ok(),+ &is_executable_file,+ )+}++fn file_stem(path: &str) -> Option<String> {+ Path::new(path)+ .file_stem()+ .map(|stem| stem.to_string_lossy().into_owned())+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::HashMap;++ fn probe(env: &[(&str, &str)], present: &[&str]) -> (HashMap<String, String>, HashSet<String>) {+ (+ env.iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect(),+ present.iter().map(|p| p.to_string()).collect(),+ )+ }++ fn discover_fake(env: &[(&str, &str)], present: &[&str]) -> Vec<DiscoveredShell> {+ let (env, present) = probe(env, present);+ discover_with(&|name| env.get(name).cloned(), &|path| {+ present.contains(path)+ })+ }++ #[test]+ fn a_windows_machine_is_discovered_from_a_unix_host() {+ // The point of the cfg-free table: this is the Windows path set,+ // exercised on whatever machine runs the tests.+ let shells = discover_fake(+ &[+ ("SystemRoot", r"C:\Windows"),+ ("ComSpec", r"C:\Windows\System32\cmd.exe"),+ ("ProgramFiles", r"C:\Program Files"),+ ],+ &[+ r"C:\Windows\System32\cmd.exe",+ r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",+ r"C:\Program Files\PowerShell\7\pwsh.exe",+ ],+ );+ let labels: Vec<&str> = shells.iter().map(|s| s.label.as_str()).collect();+ assert_eq!(+ labels,+ ["Command Prompt", "Windows PowerShell", "PowerShell 7"]+ );+ assert_eq!(+ shells[2].argv,+ vec![r"C:\Program Files\PowerShell\7\pwsh.exe".to_string()]+ );+ }++ #[test]+ fn the_newest_powershell_wins_and_the_store_alias_only_fills_a_gap() {+ let with_both = discover_fake(+ &[+ ("SystemRoot", r"C:\Windows"),+ ("ProgramFiles", r"C:\Program Files"),+ ("LOCALAPPDATA", r"C:\Users\me\AppData\Local"),+ ],+ &[+ r"C:\Program Files\PowerShell\7\pwsh.exe",+ r"C:\Program Files\PowerShell\8\pwsh.exe",+ r"C:\Users\me\AppData\Local\Microsoft\WindowsApps\pwsh.exe",+ ],+ );+ let labels: Vec<&str> = with_both.iter().map(|s| s.label.as_str()).collect();+ assert_eq!(labels, ["PowerShell 8"]);++ let store_only = discover_fake(+ &[("LOCALAPPDATA", r"C:\Users\me\AppData\Local")],+ &[r"C:\Users\me\AppData\Local\Microsoft\WindowsApps\pwsh.exe"],+ );+ let labels: Vec<&str> = store_only.iter().map(|s| s.label.as_str()).collect();+ assert_eq!(labels, ["PowerShell"]);+ }++ #[test]+ fn nushell_is_found_on_the_windows_path() {+ let shells = discover_fake(&[("PATH", r"C:\nope;;C:\tools")], &[r"C:\tools\nu.exe"]);+ assert_eq!(+ shells,+ vec![DiscoveredShell::new("nushell", r"C:\tools\nu.exe")]+ );+ }++ #[test]+ fn a_unix_machine_prefers_homebrew_over_the_system_copy() {+ let shells = discover_fake(+ &[("SHELL", "/bin/zsh")],+ &[+ "/bin/zsh",+ "/bin/bash",+ "/opt/homebrew/bin/fish",+ "/usr/bin/fish",+ ],+ );+ let argv: Vec<&str> = shells.iter().map(|s| s.argv[0].as_str()).collect();+ // $SHELL leads; fish resolves to the Homebrew copy and appears once.+ assert_eq!(argv, ["/bin/zsh", "/bin/bash", "/opt/homebrew/bin/fish"]);+ }++ #[test]+ fn a_login_shell_outside_the_table_is_still_offered() {+ let shells = discover_fake(+ &[("SHELL", "/opt/custom/bin/elvish")],+ &["/opt/custom/bin/elvish"],+ );+ assert_eq!(+ shells,+ vec![DiscoveredShell::new("elvish", "/opt/custom/bin/elvish")]+ );+ }++ #[test]+ fn an_uninstalled_choice_stops_being_usable() {+ let present: HashSet<String> = HashSet::from(["/bin/zsh".to_string()]);+ let usable = |path: &str| present.contains(path);+ let resolve = |argv: &[String]| resolve_chosen_argv(argv, false, None, &usable);++ assert_eq!(+ resolve(&["/bin/zsh".to_string()]),+ Some(vec!["/bin/zsh".to_string()])+ );+ // Uninstalled since it was chosen: the pane must fall back rather+ // than fail to open.+ assert_eq!(+ resolve_chosen_argv(+ &[r"C:\Program Files\PowerShell\7\pwsh.exe".to_string()],+ true,+ None,+ &usable+ ),+ None+ );+ // With arguments, the program is still what gets checked, and the+ // arguments survive resolution.+ assert_eq!(+ resolve(&["/bin/removed".to_string(), "--norc".to_string()]),+ None+ );+ assert_eq!(+ resolve(&["/bin/zsh".to_string(), "--norc".to_string()]),+ Some(vec!["/bin/zsh".to_string(), "--norc".to_string()])+ );+ assert_eq!(resolve(&[]), None);+ }++ #[test]+ fn a_bare_name_is_resolved_against_path_not_left_relative() {+ // `get_shell` checks the chosen program with access(), which+ // resolves a bare name against the working directory rather than+ // PATH -- so an unresolved name would silently do nothing.+ let present: HashSet<String> = HashSet::from([+ "/opt/homebrew/bin/fish".to_string(),+ r"C:\tools\pwsh.exe".to_string(),+ ]);+ let usable = |path: &str| present.contains(path);++ assert_eq!(+ resolve_chosen_argv(+ &["fish".to_string()],+ false,+ Some("/nope:/opt/homebrew/bin".to_string()),+ &usable+ ),+ Some(vec!["/opt/homebrew/bin/fish".to_string()])+ );+ assert_eq!(+ resolve_chosen_argv(+ &["pwsh.exe".to_string()],+ true,+ Some(r"C:\nope;C:\tools\".to_string()),+ &usable+ ),+ Some(vec![r"C:\tools\pwsh.exe".to_string()])+ );+ // Not on PATH at all: fall back rather than pretend.+ assert_eq!(+ resolve_chosen_argv(+ &["nu".to_string()],+ false,+ Some("/opt/homebrew/bin".to_string()),+ &usable+ ),+ None+ );+ }++ #[test]+ fn nothing_that_is_missing_is_ever_offered() {+ // Every candidate names a path that does not exist, including a+ // $SHELL pointing at an uninstalled shell.+ let shells = discover_fake(+ &[+ ("SHELL", "/bin/removed"),+ ("ComSpec", r"C:\Windows\System32\cmd.exe"),+ ("ProgramFiles", r"C:\Program Files"),+ ("PATH", r"C:\tools"),+ ],+ &[],+ );+ assert!(shells.is_empty(), "{shells:?}");+ }+}