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
feat(ssh): install shell integration on hosts from their settings
RoversX2521e87cc278
diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex c94f76e9..a71b9d08 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -51,6 +51,7 @@ pub mod pane;mod parse_watchdog;pub mod renderable;pub mod session_server;+pub mod shell_integration;pub mod ssh;pub mod ssh_agent;pub mod tab;diff --git a/mux/src/shell_integration.rs b/mux/src/shell_integration.rsnew file mode 100644index 00000000..e071bc1b--- /dev/null+++ b/mux/src/shell_integration.rs@@ -0,0 +1,694 @@+//! Shell integration on an ssh host, installed and removed from ThinkTerm's+//! host settings.+//!+//! Over plain ssh ThinkTerm sees no process on the far side, so a tab cannot+//! say what runs there -- unless the host's shell reports it. The shell+//! integration does: before each command it sets the `WEZTERM_PROG` user var+//! to the command line, and empties it at the prompt (see+//! `crate::foreground_program`). Setting it up puts two files in+//! `~/.config/thinkterm` over SFTP, and a helper run once adds -- or removes+//! -- the line that loads the script in the startup files the login shell+//! reads. Nothing else on the host is touched.++use anyhow::{bail, Context};+use std::io::Read;+use wezterm_ssh::Session;++const DIR: &str = ".config/thinkterm";+const SCRIPT_PATH: &str = ".config/thinkterm/shell-integration.sh";+const SETUP_PATH: &str = ".config/thinkterm/shell-integration-setup.sh";++/// The integration as installed, behind a guard: bash reads `.bashrc` and a+/// login file, and may be told to load it from both.+const SCRIPT: &str = concat!(+ "# ThinkTerm shell integration: tells the terminal which command runs.\n",+ "# Installed and removed from ThinkTerm's host settings.\n",+ "[ -n \"${__thinkterm_shell_integration-}\" ] && return 0\n",+ "__thinkterm_shell_integration=1\n",+ include_str!("../../assets/shell-integration/wezterm.sh"),+);++/// Adds or removes the loading line, marked so it can be found again, and+/// deletes itself. POSIX sh, run as `sh <path> install|remove` so the login+/// shell's own syntax never matters. It says what it did on its last line,+/// and only once every file is done -- or names the file it could not write.+const SETUP: &str = r##"# Adds or removes the line that loads ThinkTerm's shell integration in the+# startup files the login shell reads; ThinkTerm runs it over ssh from its+# host settings. It says what it did on its last line once every file is+# done. Otherwise it exits non-zero, naming a file it could not write when+# that is why, and an install leaves none of its files with the line.+script=.config/thinkterm/shell-integration.sh+marker='# thinkterm-shell-integration'+line='[ -f "$HOME/.config/thinkterm/shell-integration.sh" ] && . "$HOME/.config/thinkterm/shell-integration.sh" # thinkterm-shell-integration'+# Gone however this ends: the shell reads on from the file it has open.+rm -f "$0"+cd "$HOME" || exit 1++# Ends in failure over a file the host would not let it write, named for+# ThinkTerm on the last line: from the home as ~/..., when it is in there.+unwritable() {+ case "$1" in+ "$HOME"/*) echo "unwritable ~${1#"$HOME"}" ;;+ /*) echo "unwritable $1" ;;+ *) echo "unwritable ~/$1" ;;+ esac+ exit 1+}++shell=$(basename "${SHELL:-sh}")+if [ "$shell" = zsh ]; then+ zsh=$SHELL+else+ zsh=$(command -v zsh 2>/dev/null)+fi++# Where zsh reads .zshrc: a .zshenv may move it with ZDOTDIR. Asked of zsh+# itself, started afresh; whatever .zshenv prints comes before the answer.+zdir=+if [ -n "$zsh" ]; then+ zdir=$( (unset ZDOTDIR; exec "$zsh" -c 'printf "\n%s\n" "${ZDOTDIR:-$HOME}"') </dev/null 2>/dev/null | tail -n 1)+fi+if [ -z "$zdir" ] || [ ! -d "$zdir" ]; then+ zdir=$HOME+fi++has_line() {+ [ -f "$1" ] && grep -qF "$marker" "$1"+}++# Whether the file can be written, or made where it is missing.+writable() {+ if [ -e "$1" ]; then+ [ -w "$1" ]+ else+ [ -w "$(dirname "$1")" ]+ fi+}++add() {+ has_line "$1" && return 0+ # A file that does not end its last line would run it into ours.+ if [ -s "$1" ] && [ -n "$(tail -c 1 "$1")" ]; then+ printf '\n' >> "$1" || return 1+ fi+ printf '%s\n' "$line" >> "$1"+}++strip() {+ has_line "$1" || return 0+ kept=.config/thinkterm/kept-$$+ rm -f "$kept"+ grep -vF "$marker" "$1" > "$kept"+ copied=$?+ # 1 is "every line matched": the file held only our line. Without a whole+ # copy the file stays as it is -- written from nothing it would be empty.+ if [ ! -f "$kept" ]; then+ broken=.config/thinkterm+ return 1+ fi+ if [ "$copied" -gt 1 ]; then+ rm -f "$kept"+ broken=$1+ return 1+ fi+ # Rewritten in place, so a symlinked dotfile stays a symlink.+ broken=$1+ cat "$kept" > "$1"+ rewritten=$?+ rm -f "$kept"+ return "$rewritten"+}++# Whether a startup file still loads the script.+referenced() {+ for file in .zshrc "$zdir/.zshrc" .bashrc .bash_profile .bash_login .profile; do+ has_line "$file" && return 0+ done+ return 1+}++# Ends an install that could not write a file. The script goes too, unless+# a line from before still loads it.+give_up() {+ referenced || rm -f "$script"+ unwritable "$1"+}++case "$1" in+ install)+ case "$shell" in+ zsh)+ set -- "$zdir/.zshrc"+ ;;+ bash)+ # An interactive shell reads .bashrc; a login shell -- what+ # ThinkTerm starts over ssh -- the first of these that exists.+ login=.profile+ for candidate in .bash_profile .bash_login .profile; do+ if [ -f "$candidate" ]; then+ login=$candidate+ break+ fi+ done+ set -- .bashrc "$login"+ ;;+ *)+ rm -f "$script"+ echo "unsupported $shell"+ exit 0+ ;;+ esac+ # Nothing is touched unless every file can take the line.+ for file in "$@"; do+ writable "$file" || give_up "$file"+ done+ for file in "$@"; do+ add "$file" && continue+ # Half done: none of these files keeps the line.+ for added in "$@"; do+ strip "$added"+ done+ give_up "$file"+ done+ echo "installed $shell"+ ;;+ remove)+ left=+ for file in .zshrc "$zdir/.zshrc" .bashrc .bash_profile .bash_login .profile; do+ strip "$file" || left=${left:-$broken}+ done+ # A line that could not be taken out loads nothing without the script.+ rm -f "$script"+ [ -z "$left" ] || unwritable "$left"+ echo removed+ ;;+ *)+ echo "usage: sh $0 install|remove" >&2+ exit 1+ ;;+esac+"##;++/// What setting up a host came to.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ShellIntegrationOutcome {+ /// Loaded from now on by this login shell, from its next start.+ Installed(String),+ Removed,+ /// A login shell the integration has no hooks for (fish, say); nothing+ /// was left on the host.+ Unsupported(String),+}++/// A startup file the host would not let the setup write, from the home as+/// `~/...` when it is in there. What fails a setup most often, and what the+/// user can do something about, so it is told apart from other errors.+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+#[error("cannot write {0} on the host")]+pub struct UnwritableStartupFile(pub String);++/// The session to the host never came up, so the setup never ran. Not a+/// failure of the setup: the change waits for a connection that does come+/// up, and the terminal already says why this one did not.+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+#[error("not connected: {0}")]+pub struct NotConnected(pub String);++/// Install (`true`) or remove the integration on the host `session` is+/// connected to.+pub async fn set_up(session: &Session, install: bool) -> anyhow::Result<ShellIntegrationOutcome> {+ let sftp = session.sftp();+ for dir in [".config", DIR] {+ // There already, as often as not; a real failure shows at the write.+ let _ = sftp.create_dir(dir.to_string(), 0o755).await;+ }+ if install {+ upload(&sftp, SCRIPT_PATH, SCRIPT).await?;+ }+ upload(&sftp, SETUP_PATH, SETUP).await?;+ drop(sftp);++ let action = if install { "install" } else { "remove" };+ // Its stdin stays open below, so nothing in it may wait on input.+ let exec = session+ .exec(&format!("sh {SETUP_PATH} {action} </dev/null"), None)+ .await+ .context("running the setup")?;+ // Every stream stays open until both outputs are read: dropping stdin+ // closes the whole channel.+ let wezterm_ssh::ExecResult {+ stdin,+ mut stdout,+ mut stderr,+ mut child,+ } = exec;+ let (output, errors) = smol::unblock(move || {+ let mut output = String::new();+ let mut errors = String::new();+ let _ = stdout.read_to_string(&mut output);+ let _ = stderr.read_to_string(&mut errors);+ (output, errors)+ })+ .await;+ let status = child.async_wait().await.context("waiting for the setup")?;+ drop(stdin);+ match parse_report(&output) {+ // A connection lost on the way reads as a failed exit too.+ Some(Report::Done(outcome)) if status.success() => Ok(outcome),+ Some(Report::Unwritable(path)) => Err(UnwritableStartupFile(path).into()),+ _ => {+ let errors = errors.split_whitespace().collect::<Vec<_>>().join(" ");+ if errors.is_empty() {+ bail!("the setup on the host failed: {status}");+ }+ bail!("the setup on the host failed: {status}: {errors}");+ }+ }+}++async fn upload(sftp: &wezterm_ssh::Sftp, path: &str, content: &str) -> anyhow::Result<()> {+ use smol::io::AsyncWriteExt;+ let mut file = sftp+ .create(path.to_string())+ .await+ .with_context(|| format!("creating ~/{path}"))?;+ file.write_all(content.as_bytes())+ .await+ .with_context(|| format!("writing ~/{path}"))?;+ file.flush()+ .await+ .with_context(|| format!("writing ~/{path}"))?;+ Ok(())+}++/// What the helper says on its last line.+#[derive(Debug, PartialEq, Eq)]+enum Report {+ Done(ShellIntegrationOutcome),+ Unwritable(String),+}++fn parse_report(output: &str) -> Option<Report> {+ // The last line: the login shell that runs the helper may print first,+ // from a .zshenv say.+ let line = output+ .lines()+ .rev()+ .find(|line| !line.trim().is_empty())?+ .trim();+ if line == "removed" {+ return Some(Report::Done(ShellIntegrationOutcome::Removed));+ }+ let (word, rest) = line.split_once(' ')?;+ let rest = rest.trim().to_string();+ match word {+ "installed" => Some(Report::Done(ShellIntegrationOutcome::Installed(rest))),+ "unsupported" => Some(Report::Done(ShellIntegrationOutcome::Unsupported(rest))),+ "unwritable" => Some(Report::Unwritable(rest)),+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reports_are_read_from_the_last_line() {+ let done = |outcome| Some(Report::Done(outcome));+ assert_eq!(+ parse_report("installed bash\n"),+ done(ShellIntegrationOutcome::Installed("bash".to_string()))+ );+ assert_eq!(+ parse_report("removed\n"),+ done(ShellIntegrationOutcome::Removed)+ );+ assert_eq!(+ parse_report("unsupported fish\n"),+ done(ShellIntegrationOutcome::Unsupported("fish".to_string()))+ );+ assert_eq!(+ parse_report("unwritable ~/.config/zsh/.zshrc\n"),+ Some(Report::Unwritable("~/.config/zsh/.zshrc".to_string()))+ );+ // Whatever the login shell printed before the helper ran.+ assert_eq!(+ parse_report("welcome back\ninstalled zsh\n\n"),+ done(ShellIntegrationOutcome::Installed("zsh".to_string()))+ );+ assert_eq!(parse_report("sh: not found\n"), None);+ assert_eq!(parse_report("installed\n"), None);+ assert_eq!(parse_report(""), None);+ }++ /// An empty home of its own for one test, removed when dropped.+ #[cfg(unix)]+ struct ScratchHome(std::path::PathBuf);++ #[cfg(unix)]+ impl ScratchHome {+ fn new(name: &str) -> Self {+ let path = std::env::temp_dir().join(format!(+ "thinkterm-shell-integration-{}-{name}",+ std::process::id()+ ));+ let _ = std::fs::remove_dir_all(&path);+ std::fs::create_dir_all(&path).unwrap();+ Self(path)+ }+ }++ #[cfg(unix)]+ impl Drop for ScratchHome {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ /// The shells a host may run the helper with as `sh`: bash goes by that+ /// name on some systems and dash on others, and a failed redirection+ /// ends with a different status in each. Those installed here.+ #[cfg(unix)]+ fn posix_shells() -> Vec<&'static str> {+ ["/bin/sh", "/bin/dash"]+ .iter()+ .copied()+ .filter(|path| std::path::Path::new(path).exists())+ .collect()+ }++ /// Puts the helper in a scratch home and runs it there with `sh`, as the+ /// host would.+ #[cfg(unix)]+ fn run_setup(sh: &str, home: &std::path::Path, shell: &str, action: &str) -> (bool, String) {+ std::fs::create_dir_all(home.join(DIR)).unwrap();+ std::fs::write(home.join(SETUP_PATH), SETUP).unwrap();+ run_placed_setup(sh, home, shell, action)+ }++ /// Runs the helper already in place: whether it ended well, and its+ /// stdout.+ #[cfg(unix)]+ fn run_placed_setup(+ sh: &str,+ home: &std::path::Path,+ shell: &str,+ action: &str,+ ) -> (bool, String) {+ let output = std::process::Command::new(sh)+ .arg(SETUP_PATH)+ .arg(action)+ .current_dir(home)+ .env("HOME", home)+ .env("SHELL", shell)+ .env_remove("ZDOTDIR")+ .output()+ .unwrap();+ (+ output.status.success(),+ String::from_utf8(output.stdout).unwrap().trim().to_string(),+ )+ }++ /// The last line a shell prints when started as a login over ssh starts+ /// it, in a scratch home, and asked to run `command`.+ #[cfg(unix)]+ fn started_shell_says(home: &std::path::Path, shell: &str, command: &str) -> String {+ let output = std::process::Command::new(shell)+ .args(["-l", "-i", "-c", command])+ .current_dir(home)+ .env("HOME", home)+ .env("TERM", "xterm-256color")+ .env_remove("ZDOTDIR")+ .env_remove("BASH_ENV")+ .env_remove("ENV")+ .env_remove("TERM_PROGRAM")+ .stdin(std::process::Stdio::null())+ .output()+ .unwrap();+ String::from_utf8_lossy(&output.stdout)+ .lines()+ .last()+ .unwrap_or_default()+ .to_string()+ }++ #[cfg(unix)]+ fn set_mode(path: &std::path::Path, mode: u32) {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();+ }++ /// Whether permissions stop this process from writing `path`. They do+ /// not stop root, and a test of a file that cannot be written means+ /// nothing there.+ #[cfg(unix)]+ fn held_back_by(path: &std::path::Path) -> bool {+ if path.is_dir() {+ let probe = path.join("probe");+ let made = std::fs::write(&probe, "").is_ok();+ let _ = std::fs::remove_file(&probe);+ !made+ } else {+ std::fs::OpenOptions::new().append(true).open(path).is_err()+ }+ }++ #[cfg(unix)]+ fn marked_lines(path: &std::path::Path) -> usize {+ std::fs::read_to_string(path)+ .unwrap_or_default()+ .lines()+ .filter(|line| line.contains("# thinkterm-shell-integration"))+ .count()+ }++ #[cfg(unix)]+ #[test]+ fn bash_gets_its_rc_and_login_file_once_and_loses_them_again() {+ for (n, sh) in posix_shells().into_iter().enumerate() {+ let scratch = ScratchHome::new(&format!("bash-{n}"));+ let home = scratch.0.as_path();+ // A login file with no final newline, which must stay intact.+ std::fs::write(home.join(".bash_profile"), "export EDITOR=vi").unwrap();++ let installed = (true, "installed bash".to_string());+ assert_eq!(+ run_setup(sh, home, "/bin/bash", "install"),+ installed,+ "{sh}"+ );+ // Again: nothing doubles.+ assert_eq!(+ run_setup(sh, home, "/bin/bash", "install"),+ installed,+ "{sh}"+ );+ assert_eq!(marked_lines(&home.join(".bashrc")), 1, "{sh}");+ assert_eq!(marked_lines(&home.join(".bash_profile")), 1, "{sh}");+ let login = std::fs::read_to_string(home.join(".bash_profile")).unwrap();+ assert!(login.starts_with("export EDITOR=vi\n"), "{}", sh);+ // .bash_profile shadows .profile, which is left alone.+ assert!(!home.join(".profile").exists(), "{}", sh);+ // The helper deletes itself.+ assert!(!home.join(SETUP_PATH).exists(), "{}", sh);++ let removed = (true, "removed".to_string());+ assert_eq!(run_setup(sh, home, "/bin/bash", "remove"), removed, "{sh}");+ assert_eq!(marked_lines(&home.join(".bashrc")), 0, "{sh}");+ assert_eq!(+ std::fs::read_to_string(home.join(".bash_profile")).unwrap(),+ "export EDITOR=vi\n",+ "{sh}"+ );+ assert!(!home.join(SETUP_PATH).exists(), "{}", sh);+ }+ }++ #[cfg(unix)]+ #[test]+ fn zsh_gets_zshrc_and_other_shells_are_left_alone() {+ for (n, sh) in posix_shells().into_iter().enumerate() {+ let scratch = ScratchHome::new(&format!("zsh-{n}"));+ let home = scratch.0.as_path();+ let installed = (true, "installed zsh".to_string());+ assert_eq!(+ run_setup(sh, home, "/usr/bin/zsh", "install"),+ installed,+ "{sh}"+ );+ assert_eq!(marked_lines(&home.join(".zshrc")), 1, "{sh}");+ assert!(!home.join(".bashrc").exists(), "{}", sh);+ let removed = (true, "removed".to_string());+ assert_eq!(+ run_setup(sh, home, "/usr/bin/zsh", "remove"),+ removed,+ "{sh}"+ );+ assert_eq!(marked_lines(&home.join(".zshrc")), 0, "{sh}");++ std::fs::write(home.join(SCRIPT_PATH), "x").unwrap();+ let unsupported = (true, "unsupported fish".to_string());+ assert_eq!(+ run_setup(sh, home, "/usr/bin/fish", "install"),+ unsupported,+ "{sh}"+ );+ assert!(!home.join(".config/fish").exists(), "{}", sh);+ assert!(!home.join(SCRIPT_PATH).exists(), "{}", sh);+ }+ }++ #[cfg(unix)]+ #[test]+ fn a_file_that_cannot_be_written_fails_the_install_and_touches_nothing() {+ for (n, sh) in posix_shells().into_iter().enumerate() {+ let scratch = ScratchHome::new(&format!("read-only-{n}"));+ let home = scratch.0.as_path();+ let login = home.join(".bash_profile");+ std::fs::write(&login, "export EDITOR=vi\n").unwrap();+ set_mode(&login, 0o444);+ if !held_back_by(&login) {+ return;+ }+ std::fs::create_dir_all(home.join(DIR)).unwrap();+ std::fs::write(home.join(SCRIPT_PATH), SCRIPT).unwrap();++ // It names the file, and not even .bashrc, which could be+ // written, takes the line.+ assert_eq!(+ run_setup(sh, home, "/bin/bash", "install"),+ (false, "unwritable ~/.bash_profile".to_string()),+ "{sh}"+ );+ assert!(!home.join(".bashrc").exists(), "{}", sh);+ assert_eq!(+ std::fs::read_to_string(&login).unwrap(),+ "export EDITOR=vi\n",+ "{sh}"+ );+ assert!(!home.join(SCRIPT_PATH).exists(), "{}", sh);+ assert!(!home.join(SETUP_PATH).exists(), "{}", sh);+ }+ }++ #[cfg(unix)]+ #[test]+ fn a_file_is_never_emptied_when_it_cannot_be_copied() {+ for (n, sh) in posix_shells().into_iter().enumerate() {+ let scratch = ScratchHome::new(&format!("no-copy-{n}"));+ let home = scratch.0.as_path();+ std::fs::write(home.join(".bashrc"), "export KEEP=me\n").unwrap();+ assert!(run_setup(sh, home, "/bin/bash", "install").0, "{}", sh);+ let before = std::fs::read_to_string(home.join(".bashrc")).unwrap();++ // The copy is made beside the helper, in a folder that now takes+ // no new file.+ std::fs::write(home.join(SETUP_PATH), SETUP).unwrap();+ let dir = home.join(DIR);+ set_mode(&dir, 0o555);+ if !held_back_by(&dir) {+ set_mode(&dir, 0o755);+ return;+ }+ let said = run_placed_setup(sh, home, "/bin/bash", "remove");+ set_mode(&dir, 0o755);+ assert_eq!(+ said,+ (false, "unwritable ~/.config/thinkterm".to_string()),+ "{sh}"+ );+ assert_eq!(+ std::fs::read_to_string(home.join(".bashrc")).unwrap(),+ before,+ "{sh}"+ );+ }+ }++ #[cfg(unix)]+ #[test]+ fn zsh_takes_the_line_where_its_zdotdir_points() {+ let Some(zsh) = ["/bin/zsh", "/usr/bin/zsh"]+ .iter()+ .copied()+ .find(|path| std::path::Path::new(path).exists())+ else {+ return;+ };+ for (n, sh) in posix_shells().into_iter().enumerate() {+ let scratch = ScratchHome::new(&format!("zdotdir-{n}"));+ let home = scratch.0.as_path();+ std::fs::create_dir_all(home.join(".config/zsh")).unwrap();+ // Not exported, as it is often written, and with a greeting on+ // stdout.+ std::fs::write(+ home.join(".zshenv"),+ "ZDOTDIR=\"$HOME/.config/zsh\"\necho welcome\n",+ )+ .unwrap();++ let installed = (true, "installed zsh".to_string());+ assert_eq!(run_setup(sh, home, zsh, "install"), installed, "{sh}");+ assert_eq!(marked_lines(&home.join(".config/zsh/.zshrc")), 1, "{sh}");+ assert!(!home.join(".zshrc").exists(), "{}", sh);++ std::fs::write(home.join(SCRIPT_PATH), SCRIPT).unwrap();+ let said = started_shell_says(+ home,+ zsh,+ "print -r -- \"${__thinkterm_shell_integration-}:${(j:,:)precmd_functions}\"",+ );+ assert!(+ said.starts_with("1:") && said.contains("__wezterm_user_vars_precmd"),+ "{}: {}",+ sh,+ said+ );++ let removed = (true, "removed".to_string());+ assert_eq!(run_setup(sh, home, zsh, "remove"), removed, "{sh}");+ assert_eq!(marked_lines(&home.join(".config/zsh/.zshrc")), 0, "{sh}");++ // A file there it cannot write is named from the home.+ let rc = home.join(".config/zsh/.zshrc");+ set_mode(&rc, 0o444);+ if held_back_by(&rc) {+ let unwritable = (false, "unwritable ~/.config/zsh/.zshrc".to_string());+ assert_eq!(run_setup(sh, home, zsh, "install"), unwritable, "{sh}");+ }+ set_mode(&rc, 0o644);+ }+ }++ #[cfg(unix)]+ #[test]+ fn a_bash_login_shell_loads_the_line() {+ if !std::path::Path::new("/bin/bash").exists() {+ return;+ }+ let scratch = ScratchHome::new("bash-login");+ let home = scratch.0.as_path();+ std::fs::write(home.join(".bash_profile"), "export EDITOR=vi\n").unwrap();+ assert!(run_setup("/bin/sh", home, "/bin/bash", "install").0);++ std::fs::write(home.join(SCRIPT_PATH), SCRIPT).unwrap();+ let said = started_shell_says(+ home,+ "/bin/bash",+ "echo \"${__thinkterm_shell_integration-}:${precmd_functions[*]}\"",+ );+ assert!(+ said.starts_with("1:") && said.contains("__wezterm_user_vars_precmd"),+ "{}",+ said+ );+ }++ #[test]+ fn the_integration_loads_once_per_shell() {+ assert!(SCRIPT.contains("[ -n \"${__thinkterm_shell_integration-}\" ] && return 0"));+ assert!(SCRIPT.contains("WEZTERM_PROG"));+ }+}diff --git a/mux/src/ssh.rs b/mux/src/ssh.rsindex 1e9abbed..0ca87217 100644--- a/mux/src/ssh.rs+++ b/mux/src/ssh.rs@@ -349,6 +349,36 @@ impl RemoteSshDomain {parse_os_release_id(&text)}+ /// Install (`true`) or remove the shell integration that lets a tab show+ /// what runs on this host (`crate::shell_integration`). Waits while the+ /// session is still connecting: a password or a host key may be waiting+ /// on the user.+ pub async fn set_up_shell_integration(+ &self,+ install: bool,+ ) -> anyhow::Result<crate::shell_integration::ShellIntegrationOutcome> {+ let deadline = Instant::now() + Duration::from_secs(300);+ let session = loop {+ match self.connection_status() {+ SshConnectionStatus::Connected => {+ if let Some(session) = self.session.lock().unwrap().as_ref().cloned() {+ break session;+ }+ }+ SshConnectionStatus::Failed(message) => {+ return Err(crate::shell_integration::NotConnected(message).into());+ }+ SshConnectionStatus::Connecting | SshConnectionStatus::Authenticating => {}+ }+ if Instant::now() >= deadline {+ let waited = "still connecting after five minutes".to_string();+ return Err(crate::shell_integration::NotConnected(waited).into());+ }+ smol::Timer::after(Duration::from_millis(500)).await;+ };+ crate::shell_integration::set_up(&session, install).await+ }+pub fn ssh_config(&self) -> anyhow::Result<ConfigMap> {ssh_domain_to_ssh_config(&self.dom)}diff --git a/thinkterm-core/src/ssh_hosts.rs b/thinkterm-core/src/ssh_hosts.rsindex 72039119..3acecaa6 100644--- a/thinkterm-core/src/ssh_hosts.rs+++ b/thinkterm-core/src/ssh_hosts.rs@@ -36,6 +36,35 @@ pub struct SshHostSpec {pub use_mosh: bool,#[serde(default = "default_mosh_server_command")]pub mosh_server_command: String,+ /// Whether the host's shell should report each command it runs, so a tab+ /// can show it over plain ssh: ThinkTerm installs its shell integration+ /// there (`mux::shell_integration`).+ #[serde(default)]+ pub shell_integration: bool,+ /// The `shell_integration` setting as last carried out on the host: a+ /// change is made at the next connection and only recorded here once it+ /// has been.+ #[serde(default)]+ pub shell_integration_applied: bool,+ /// The login shell that setup found the integration has no hooks for, in+ /// which case it left nothing on the host.+ #[serde(default)]+ pub shell_integration_unsupported: Option<String>,+ /// Why the last connection could not carry `shell_integration` out, kept+ /// until one does; the next connection tries again.+ #[serde(default)]+ pub shell_integration_failure: Option<ShellIntegrationFailure>,+}++/// Why setting a host's shell integration up failed.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum ShellIntegrationFailure {+ /// A startup file the host would not let it write, from the home as+ /// `~/...` when it is in there.+ Unwritable(String),+ /// Anything else, as the error put it.+ Other(String),}pub fn default_true() -> bool {@@ -157,6 +186,10 @@ pub fn parse_system_ssh_config(content: &str) -> Vec<SshHostEntry> {detected_distro: None,use_mosh: false,mosh_server_command: default_mosh_server_command(),+ shell_integration: false,+ shell_integration_applied: false,+ shell_integration_unsupported: None,+ shell_integration_failure: None,},});}@@ -324,6 +357,10 @@ mod tests {detected_distro: None,use_mosh: false,mosh_server_command: default_mosh_server_command(),+ shell_integration: false,+ shell_integration_applied: false,+ shell_integration_unsupported: None,+ shell_integration_failure: None,};assert_eq!(ssh_domain_name(&spec), "ssh:[email protected]");assert_eq!(build_ssh_domain(&spec).remote_address, "example.test:22");diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex 1b9f6ba3..a6beee62 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -480,6 +480,15 @@ ssh-group-session = Sitzungssh-detect-os = Betriebssystem erkennenssh-use-mosh = Mit Mosh verbindenssh-use-mux = ThinkTerm Connect+ssh-shell-integration = Entfernte Programme erkennen+ssh-shell-integration-note = Wirkt bei SSH: Das Tab-Symbol zeigt, was auf diesem Server läuft.+ssh-shell-integration-install = Eingeschaltet fügt die nächste Verbindung den bash- oder zsh-Startdateien des Servers eine Zeile hinzu.+ssh-shell-integration-installed = Auf dem Server eingerichtet; ab jetzt geöffnete Shells melden es.+ssh-shell-integration-remove = Ausgeschaltet: Die Zeile wird bei der nächsten Verbindung entfernt.+ssh-shell-integration-unsupported = Die Login-Shell dieses Servers ist { $shell }; unterstützt werden nur bash und zsh.+ssh-shell-integration-failed-install = Die letzte Verbindung konnte sie nicht einrichten; die nächste versucht es erneut: { $reason }+ssh-shell-integration-failed-remove = Die letzte Verbindung konnte sie nicht entfernen; die nächste versucht es erneut: { $reason }+ssh-shell-integration-unwritable = { $path } auf dem Server ist nicht beschreibbarssh-advanced = Erweitertssh-add-option = + Option hinzufügenssh-save-open = Speichern und öffnendiff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex 1b71244c..968c909c 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -480,6 +480,15 @@ ssh-group-session = Sessionssh-detect-os = Detect OSssh-use-mosh = Connect with Moshssh-use-mux = ThinkTerm Connect+ssh-shell-integration = Detect remote programs+ssh-shell-integration-note = Works over SSH: tab icons show what runs on this server.+ssh-shell-integration-install = When on, the next connection adds one line to the server's bash or zsh startup files.+ssh-shell-integration-installed = Set up on the server; shells opened from now on report what they run.+ssh-shell-integration-remove = Turned off: the line is removed at the next connection.+ssh-shell-integration-unsupported = This server's login shell is { $shell }; only bash and zsh are supported.+ssh-shell-integration-failed-install = The last connection could not set it up; the next one tries again: { $reason }+ssh-shell-integration-failed-remove = The last connection could not remove it; the next one tries again: { $reason }+ssh-shell-integration-unwritable = { $path } on the server cannot be writtenssh-advanced = Advancedssh-add-option = + Add optionssh-save-open = Save & Opendiff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex dc978232..17070726 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -480,6 +480,15 @@ ssh-group-session = Sessionssh-detect-os = Détecter le systèmessh-use-mosh = Se connecter avec Moshssh-use-mux = ThinkTerm Connect+ssh-shell-integration = Détecter les programmes distants+ssh-shell-integration-note = Fonctionne en SSH : l’icône de l’onglet montre ce qui tourne sur ce serveur.+ssh-shell-integration-install = Une fois activé, la prochaine connexion ajoute une ligne aux fichiers de démarrage bash ou zsh du serveur.+ssh-shell-integration-installed = Installé sur le serveur ; les shells ouverts désormais le signalent.+ssh-shell-integration-remove = Désactivé : la ligne est retirée à la prochaine connexion.+ssh-shell-integration-unsupported = Le shell de connexion de ce serveur est { $shell } ; seuls bash et zsh sont pris en charge.+ssh-shell-integration-failed-install = La dernière connexion n’a pas pu l’installer ; la prochaine réessaiera : { $reason }+ssh-shell-integration-failed-remove = La dernière connexion n’a pas pu la retirer ; la prochaine réessaiera : { $reason }+ssh-shell-integration-unwritable = { $path } n’est pas modifiable sur le serveurssh-advanced = Avancéssh-add-option = + Ajouter une optionssh-save-open = Enregistrer et ouvrirdiff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex 8f82af2e..dca8124c 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -471,6 +471,15 @@ ssh-group-session = セッションssh-detect-os = OS を検出ssh-use-mosh = Mosh で接続ssh-use-mux = ThinkTerm Connect+ssh-shell-integration = リモートのプログラムを識別+ssh-shell-integration-note = SSH 接続で有効:タブのアイコンがこのサーバーで動いているプログラムを表示します。+ssh-shell-integration-install = オンにすると、次回の接続時にサーバーの bash / zsh の起動ファイルへ 1 行追加します。+ssh-shell-integration-installed = サーバーに設定済みです。これから開くシェルで有効になります。+ssh-shell-integration-remove = オフ:次回の接続時にその 1 行を削除します。+ssh-shell-integration-unsupported = このサーバーのログインシェルは { $shell } です。対応しているのは bash と zsh だけです。+ssh-shell-integration-failed-install = 前回の接続では設定できませんでした。次回の接続で再試行します:{ $reason }+ssh-shell-integration-failed-remove = 前回の接続では削除できませんでした。次回の接続で再試行します:{ $reason }+ssh-shell-integration-unwritable = サーバーの { $path } に書き込めませんssh-advanced = 詳細設定ssh-add-option = + オプションを追加ssh-save-open = 保存して開くdiff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex d2b7d416..eff43e1e 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -471,6 +471,15 @@ ssh-group-session = 会话ssh-detect-os = 检测操作系统ssh-use-mosh = 使用 Mosh 连接ssh-use-mux = ThinkTerm Connect+ssh-shell-integration = 识别远端程序+ssh-shell-integration-note = SSH 连接时起作用:tab 图标显示这台服务器上正在运行的程序。+ssh-shell-integration-install = 开启后,下次连接时会在服务器的 bash / zsh 启动文件里加一行。+ssh-shell-integration-installed = 已在服务器上装好,之后新开的 shell 都会生效。+ssh-shell-integration-remove = 已关闭:下次连接时从服务器上删掉那一行。+ssh-shell-integration-unsupported = 这台服务器的登录 shell 是 { $shell },只支持 bash 和 zsh。+ssh-shell-integration-failed-install = 上次连接时没装上,下次连接会再试:{ $reason }+ssh-shell-integration-failed-remove = 上次连接时没删掉,下次连接会再试:{ $reason }+ssh-shell-integration-unwritable = 服务器上的 { $path } 写不进去ssh-advanced = 高级ssh-add-option = + 添加选项ssh-save-open = 保存并打开diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rsindex 9abf3e07..c3f7b778 100644--- a/wezterm-gui/src/ssh_hosts.rs+++ b/wezterm-gui/src/ssh_hosts.rs@@ -10,6 +10,7 @@ use config::keyassignment::{SpawnCommand, SpawnTabDomain};use config::SshDomain;use filedescriptor::FileDescriptor;use mux::domain::Domain;+use mux::shell_integration::{NotConnected, ShellIntegrationOutcome, UnwritableStartupFile};use mux::ssh::RemoteSshDomain;use mux::Mux;use parking_lot::Mutex;@@ -22,8 +23,8 @@ use std::sync::Arc;use wezterm_ssh::{Session, SessionEvent};pub use thinkterm_core::ssh_hosts::{- default_mosh_server_command, SshHostEntry, SshHostId, SshHostSource, SshHostSpec,- DEFAULT_MOSH_SERVER_COMMAND,+ default_mosh_server_command, ShellIntegrationFailure, SshHostEntry, SshHostId, SshHostSource,+ SshHostSpec, DEFAULT_MOSH_SERVER_COMMAND,};#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]@@ -219,7 +220,7 @@ fn upsert_host(spec: SshHostSpec) -> Result<(SshHostId, SshHostSpec)> {/// the host to a different `user@host:port` has to re-key the record or it/// stops matching its own spec. `None` means there was no such editable/// record.-pub fn try_update_host(host_id: &str, spec: SshHostSpec) -> Result<Option<SshHostId>> {+pub fn try_update_host(host_id: &str, mut spec: SshHostSpec) -> Result<Option<SshHostId>> {if is_system_host_id(host_id) {return Ok(None);}@@ -235,6 +236,18 @@ pub fn try_update_host(host_id: &str, spec: SshHostSpec) -> Result<Option<SshHoslet Some(record) = store.hosts.iter_mut().find(|record| record.id == host_id) else {return Ok(None);};+ // What connections found on the host is the record's to keep, not the+ // copy the form took when it opened -- unless the host moved to another+ // endpoint, which ThinkTerm has set nothing up on yet.+ if new_id == host_id {+ spec.shell_integration_applied = record.spec.shell_integration_applied;+ spec.shell_integration_unsupported = record.spec.shell_integration_unsupported.clone();+ spec.shell_integration_failure = record.spec.shell_integration_failure.clone();+ } else {+ spec.shell_integration_applied = false;+ spec.shell_integration_unsupported = None;+ spec.shell_integration_failure = None;+ }record.id = new_id.clone();record.spec = spec;save_ssh_host_store(&store)?;@@ -286,6 +299,129 @@ pub fn set_host_distro(host_id: &str, distro_id: &str) -> bool {true}+/// The shell integration change a host's settings still wait on: `Some`+/// with whether to install it, when the setting and what was last carried+/// out differ. Only a direct ssh connection can carry it out; ThinkTerm+/// Connect sees the host's processes itself, and Mosh has no session for it.+pub fn pending_shell_integration(spec: &SshHostSpec) -> Option<bool> {+ (!spec.use_mosh+ && !spec.multiplexing+ && spec.shell_integration != spec.shell_integration_applied)+ .then_some(spec.shell_integration)+}++/// Record what setting up the host's shell integration came to, so the next+/// connection does not carry it out again. Returns whether the record+/// changed.+pub fn record_shell_integration(host_id: &str, outcome: &ShellIntegrationOutcome) -> bool {+ if is_system_host_id(host_id) {+ return false;+ }+ let Ok(mut store) = host_store() else {+ return false;+ };+ let Some(record) = store.hosts.iter_mut().find(|record| record.id == host_id) else {+ return false;+ };+ // A shell without hooks counts as carried out too: nothing was left on+ // the host, and the next connection would only find the same shell.+ let (applied, unsupported) = match outcome {+ ShellIntegrationOutcome::Installed(_) => (true, None),+ ShellIntegrationOutcome::Removed => (false, None),+ ShellIntegrationOutcome::Unsupported(shell) => (true, Some(shell.clone())),+ };+ if record.spec.shell_integration_applied == applied+ && record.spec.shell_integration_unsupported == unsupported+ && record.spec.shell_integration_failure.is_none()+ {+ return false;+ }+ record.spec.shell_integration_applied = applied;+ record.spec.shell_integration_unsupported = unsupported;+ record.spec.shell_integration_failure = None;+ if let Err(err) = save_ssh_host_store(&store) {+ log::warn!("failed to persist SSH host shell integration for {host_id}: {err:#}");+ }+ true+}++/// Record why carrying out the host's shell integration setting failed, for+/// its settings to show until a connection gets it done. Returns whether the+/// record changed.+pub fn record_shell_integration_failure(host_id: &str, err: &anyhow::Error) -> bool {+ if is_system_host_id(host_id) {+ return false;+ }+ let Some(failure) = shell_integration_failure(err) else {+ return false;+ };+ let Ok(mut store) = host_store() else {+ return false;+ };+ let Some(record) = store.hosts.iter_mut().find(|record| record.id == host_id) else {+ return false;+ };+ if record.spec.shell_integration_failure.as_ref() == Some(&failure) {+ return false;+ }+ record.spec.shell_integration_failure = Some(failure);+ if let Err(err) = save_ssh_host_store(&store) {+ log::warn!("failed to persist SSH host shell integration for {host_id}: {err:#}");+ }+ true+}++/// How a failed setup is kept: a file the host would not let it write as+/// such, anything else in one line short enough for a few lines of the form.+/// Nothing when it never ran -- a host that never connected has nothing to+/// show for it.+fn shell_integration_failure(err: &anyhow::Error) -> Option<ShellIntegrationFailure> {+ if err.downcast_ref::<NotConnected>().is_some() {+ return None;+ }+ if let Some(file) = err.downcast_ref::<UnwritableStartupFile>() {+ return Some(ShellIntegrationFailure::Unwritable(file.0.clone()));+ }+ let message = format!("{err:#}")+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ");+ let mut short: String = message.chars().take(240).collect();+ if short.len() < message.len() {+ short.push('…');+ }+ Some(ShellIntegrationFailure::Other(short))+}++/// What connections have found about a host's shell integration so far, as+/// `record_shell_integration` and `record_shell_integration_failure` keep it.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct ShellIntegrationRecord {+ /// The setting as last carried out.+ pub applied: bool,+ /// The login shell the integration has no hooks for.+ pub unsupported: Option<String>,+ /// Why the last connection could not carry the setting out.+ pub failure: Option<ShellIntegrationFailure>,+}++/// What setting up the host's shell integration has come to so far.+pub fn shell_integration_record(host_id: &str) -> ShellIntegrationRecord {+ let Ok(store) = host_store() else {+ return ShellIntegrationRecord::default();+ };+ store+ .hosts+ .iter()+ .find(|record| record.id == host_id)+ .map(|record| ShellIntegrationRecord {+ applied: record.spec.shell_integration_applied,+ unsupported: record.spec.shell_integration_unsupported.clone(),+ failure: record.spec.shell_integration_failure.clone(),+ })+ .unwrap_or_default()+}+pub fn is_system_host_id(host_id: &str) -> bool {host_id.starts_with("system-ssh-")}@@ -651,6 +787,10 @@ fn parse_system_ssh_config_str(content: &str) -> Vec<SshHostEntry> {detected_distro: None,use_mosh: false,mosh_server_command: default_mosh_server_command(),+ shell_integration: false,+ shell_integration_applied: false,+ shell_integration_unsupported: None,+ shell_integration_failure: None,};out.push(SshHostEntry {id: system_host_id(&alias),@@ -838,6 +978,63 @@ Host prod *.internal);}+ #[test]+ fn a_connection_that_never_came_up_is_no_failure_of_the_setup() {+ let refused = anyhow::Error::new(NotConnected("connection refused".to_string()));+ assert_eq!(shell_integration_failure(&refused), None);+ }++ #[test]+ fn a_failed_setup_is_kept_as_the_file_or_in_one_short_line() {+ let unwritable = anyhow::Error::new(UnwritableStartupFile("~/.zshrc".to_string()));+ assert_eq!(+ shell_integration_failure(&unwritable),+ Some(ShellIntegrationFailure::Unwritable("~/.zshrc".to_string()))+ );+ // Still the file under a context.+ let wrapped = unwritable.context("setting up example");+ assert_eq!(+ shell_integration_failure(&wrapped),+ Some(ShellIntegrationFailure::Unwritable("~/.zshrc".to_string()))+ );++ let lost = anyhow::anyhow!("the setup on the host failed:\n Exited with code 2");+ assert_eq!(+ shell_integration_failure(&lost),+ Some(ShellIntegrationFailure::Other(+ "the setup on the host failed: Exited with code 2".to_string()+ ))+ );+ let long = anyhow::anyhow!("{}", "x".repeat(300));+ match shell_integration_failure(&long) {+ Some(ShellIntegrationFailure::Other(text)) => {+ assert_eq!(text.chars().count(), 241);+ assert!(text.ends_with('…'));+ }+ other => panic!("{:?}", other),+ }+ }++ #[test]+ fn only_a_changed_setting_on_plain_ssh_waits_on_a_connection() {+ let mut spec = spec_with_options(HashMap::new());+ assert_eq!(pending_shell_integration(&spec), None);+ spec.shell_integration = true;+ assert_eq!(pending_shell_integration(&spec), Some(true));+ spec.shell_integration_applied = true;+ assert_eq!(pending_shell_integration(&spec), None);+ spec.shell_integration = false;+ assert_eq!(pending_shell_integration(&spec), Some(false));++ // Connect sees the host's processes itself, and Mosh has no session+ // to carry the change out on.+ spec.multiplexing = true;+ assert_eq!(pending_shell_integration(&spec), None);+ spec.multiplexing = false;+ spec.use_mosh = true;+ assert_eq!(pending_shell_integration(&spec), None);+ }+fn spec_with_options(ssh_options: HashMap<String, String>) -> SshHostSpec {SshHostSpec {label: "t".to_string(),@@ -853,6 +1050,10 @@ Host prod *.internaldetected_distro: None,use_mosh: false,mosh_server_command: default_mosh_server_command(),+ shell_integration: false,+ shell_integration_applied: false,+ shell_integration_unsupported: None,+ shell_integration_failure: None,}}diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 90e3f3d0..3d1993f5 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -238,6 +238,9 @@ pub(crate) struct RemoteConnectState {pub orphan_candidate_window_id: Option<MuxWindowId>,/// `(domain_name, host_id)` to run OS detection on once connected.pub detect_os: Option<(String, String)>,+ /// `(domain_name, host_id, install)` when the host's shell integration+ /// setting waits on this connection (`ssh_hosts::pending_shell_integration`).+ pub shell_integration: Option<(String, String, bool)>,}/// An in-flight Mosh connection started from a `RemoteThreadView`. Mosh doesdiff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex c4a255b9..1ff799fa 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -7134,9 +7134,12 @@ impl super::TermWindow {return;}let mut detect_remote_os = None;+ let mut shell_integration = None;let (initial_cwd, default_domain) = if let Some(spec) = remote_spec.as_ref() {match crate::ssh_hosts::ensure_ssh_domain_registered(spec) {Ok(domain_name) => {+ shell_integration = crate::ssh_hosts::pending_shell_integration(spec)+ .map(|install| (domain_name.clone(), remote_host_id.clone(), install));if spec.detect_os {detect_remote_os = Some((domain_name.clone(), remote_host_id));}@@ -7228,6 +7231,7 @@ impl super::TermWindow {orphan_candidate_window_id,cleanup_workspaces,detect_remote_os,+ shell_integration,);})));}@@ -7329,6 +7333,7 @@ impl super::TermWindow {orphan_candidate_window_id: Option<MuxWindowId>,workspaces_to_kill_after_adopt: Vec<String>,detect_remote_os: Option<(String, String)>,+ shell_integration: Option<(String, String, bool)>,) {let is_current = self.local_thread_activation.as_ref().is_some_and(|state| {local_thread_activation_matches(@@ -7411,6 +7416,9 @@ impl super::TermWindow {reconcile_workspace_layout_after_materialize(self.window.clone());self.invalidate_window();+ if let Some((domain_name, host_id, install)) = shell_integration {+ set_up_remote_shell_integration(domain_name, host_id, install, self.window.clone());+ }if let Some((detect_domain, detect_project)) = detect_remote_os {let detect_window = self.window.clone();promise::spawn::spawn(async move {@@ -7622,6 +7630,8 @@ impl super::TermWindow {domain_name: domain_name.clone(),started: Instant::now(),orphan_candidate_window_id,+ shell_integration: crate::ssh_hosts::pending_shell_integration(&spec)+ .map(|install| (domain_name.clone(), remote_host_id.clone(), install)),detect_os: spec.detect_os.then(|| (domain_name.clone(), remote_host_id)),@@ -7744,6 +7754,9 @@ impl super::TermWindow {let detect = state.detect_os;let orphan_candidate_window_id = state.orphan_candidate_window_id;let window = self.window.as_ref().cloned();+ if let Some((domain_name, host_id, install)) = state.shell_integration {+ set_up_remote_shell_integration(domain_name, host_id, install, window.clone());+ }let reveal_now = self.active_content_view_id == Some(view_id);self.close_content_view_by_id(view_id);if reveal_now {@@ -9229,6 +9242,42 @@ mod blocked_pointer_tests {}}+/// Carry out a change of a host's shell integration setting on the+/// connection just made to it (`mux::shell_integration`), and record it so+/// the next connection does not repeat it -- or why it failed, for the host's+/// settings to show.+fn set_up_remote_shell_integration(+ domain_name: String,+ host_id: String,+ install: bool,+ window: Option<::window::Window>,+) {+ promise::spawn::spawn(async move {+ let Some(domain) = Mux::get().get_domain_by_name(&domain_name) else {+ return;+ };+ let Some(ssh) = domain.as_ref().downcast_ref::<RemoteSshDomain>() else {+ return;+ };+ let changed = match ssh.set_up_shell_integration(install).await {+ Ok(outcome) => {+ log::info!("shell integration on {domain_name}: {outcome:?}");+ crate::ssh_hosts::record_shell_integration(&host_id, &outcome)+ }+ Err(err) => {+ log::warn!("shell integration on {domain_name}: {err:#}");+ crate::ssh_hosts::record_shell_integration_failure(&host_id, &err)+ }+ };+ if changed {+ if let Some(window) = window {+ window.invalidate();+ }+ }+ })+ .detach();+}+/// After a thread has finished materializing its saved layout, the materialize/// guard suppressed any layout saves (so we never persist a half-built tree)./// That means a structural change the user made *during* materialization (e.g.diff --git a/wezterm-gui/src/termwindow/ssh_hosts_view.rs b/wezterm-gui/src/termwindow/ssh_hosts_view.rsindex 3c133754..2b2516f7 100644--- a/wezterm-gui/src/termwindow/ssh_hosts_view.rs+++ b/wezterm-gui/src/termwindow/ssh_hosts_view.rs@@ -7,9 +7,10 @@//! [`SshViewOutcome`] so `TermWindow` integration stays minimal.use crate::quad::{HeapQuadAllocator, QuadClipRect, TripleLayerQuadAllocator};-use crate::ssh_hosts::{self, SshHostEntry, SshHostSource, SshHostSpec};+use crate::ssh_hosts::{self, ShellIntegrationFailure, SshHostEntry, SshHostSource, SshHostSpec};use crate::termwindow::content_view::{ContentView, ContentViewResponse, RemoteHostCommand};use crate::termwindow::ui::icons::{distro_to_icon, SvgIcon};+use crate::termwindow::ui::right_sidebar::wrap_snippet_text_for_width;use crate::termwindow::TermWindow;use crate::ui::anim::Easing;use crate::ui::{@@ -149,6 +150,7 @@ enum SshViewAction {ToggleDetect,ToggleMosh,ToggleMux,+ ToggleShellIntegration,RevealPassword,Save,SaveAndConnect,@@ -184,6 +186,7 @@ struct HostForm {detect_os: bool,use_mosh: bool,multiplexing: bool,+ shell_integration: bool,error: Option<String>,}@@ -353,6 +356,7 @@ impl SshHostsView {let detect_os = spec.detect_os;let use_mosh = spec.use_mosh;let multiplexing = spec.multiplexing;+ let shell_integration = spec.shell_integration;// Sorted so the rows keep a stable order between opens.let mut option_pairs: Vec<(String, String)> = spec.ssh_options@@ -374,6 +378,7 @@ impl SshHostsView {detect_os,use_mosh,multiplexing,+ shell_integration,error: None,});self.focus = Focus::Field(FIELD_HOST);@@ -435,6 +440,10 @@ impl SshHostsView {detected_distro: None,use_mosh: false,mosh_server_command: ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND.to_string(),+ shell_integration: false,+ shell_integration_applied: false,+ shell_integration_unsupported: None,+ shell_integration_failure: None,});spec.label = label;spec.host = host;@@ -461,6 +470,7 @@ impl SshHostsView {spec.detect_os = form.detect_os;spec.use_mosh = form.use_mosh;spec.multiplexing = form.multiplexing;+ spec.shell_integration = form.shell_integration;let mosh_server_command = form.fields[FIELD_MOSH_SERVER].text().trim();if spec.use_mosh && mosh_server_command.is_empty() {form.error = Some(crate::i18n::tr("ssh-error-mosh-command"));@@ -718,6 +728,12 @@ impl SshHostsView {}ContentViewResponse::Redraw}+ SshViewAction::ToggleShellIntegration => {+ if let Some(form) = self.form.as_mut() {+ form.shell_integration = !form.shell_integration;+ }+ ContentViewResponse::Redraw+ }SshViewAction::Save => {self.persist_form();ContentViewResponse::Redraw@@ -853,6 +869,7 @@ impl SshHostsView {form.detect_os = spec.detect_os;form.use_mosh = spec.use_mosh;form.multiplexing = spec.multiplexing;+ form.shell_integration = spec.shell_integration;form.options = spec.ssh_options.iter()@@ -2061,6 +2078,81 @@ impl SshHostsView {Ok(y + height)}+ /// The lines under the shell integration toggle: where it works, then+ /// what the next connection will do about it, what the last one found,+ /// or why it failed.+ fn shell_integration_note(+ ctx: &DrawContext,+ font: &Rc<LoadedFont>,+ editing: Option<&str>,+ on: bool,+ width: f32,+ ) -> Vec<String> {+ if width <= 0.0 {+ return Vec::new();+ }+ let record = editing+ .map(ssh_hosts::shell_integration_record)+ .unwrap_or_default();+ [+ crate::i18n::tr("ssh-shell-integration-note"),+ Self::shell_integration_status(on, record),+ ]+ .iter()+ .flat_map(|text| {+ wrap_snippet_text_for_width(text, 5, false, |segment| {+ ctx.measure_text_width(font, segment) / width+ })+ })+ .collect()+ }++ /// The line under the note: what the next connection will do about the+ /// setting, what the last one found, or why it failed.+ fn shell_integration_status(on: bool, record: ssh_hosts::ShellIntegrationRecord) -> String {+ // A failure counts only while the change still waits on a+ // connection: turned back, nothing is left to fail.+ if on != record.applied {+ if let Some(failure) = &record.failure {+ return Self::shell_integration_failure_text(failure, on);+ }+ }+ match (on, record.applied, record.unsupported) {+ (true, true, Some(shell)) => {+ let mut args = FluentArgs::new();+ args.set("shell", shell);+ crate::i18n::tr_args("ssh-shell-integration-unsupported", &args)+ }+ (true, true, None) => crate::i18n::tr("ssh-shell-integration-installed"),+ (false, true, None) => crate::i18n::tr("ssh-shell-integration-remove"),+ _ => crate::i18n::tr("ssh-shell-integration-install"),+ }+ }++ /// Why the last connection could not carry the setting out, and that the+ /// next one tries again.+ fn shell_integration_failure_text(+ failure: &ShellIntegrationFailure,+ installing: bool,+ ) -> String {+ let reason = match failure {+ ShellIntegrationFailure::Unwritable(path) => {+ let mut args = FluentArgs::new();+ args.set("path", path.clone());+ crate::i18n::tr_args("ssh-shell-integration-unwritable", &args)+ }+ ShellIntegrationFailure::Other(message) => message.clone(),+ };+ let mut args = FluentArgs::new();+ args.set("reason", reason);+ let id = if installing {+ "ssh-shell-integration-failed-install"+ } else {+ "ssh-shell-integration-failed-remove"+ };+ crate::i18n::tr_args(id, &args)+ }+#[allow(clippy::too_many_arguments)]fn paint_inspector(&mut self,@@ -2083,6 +2175,7 @@ impl SshHostsView {let detect_os = form.detect_os;let use_mosh = form.use_mosh;let multiplexing = form.multiplexing;+ let shell_integration = form.shell_integration;let advanced_open = form.advanced_open;let error = form.error.clone();let fields = form.fields.clone();@@ -2302,10 +2395,26 @@ impl SshHostsView {y += auth_h + card_gap;// ---- Session+ // Only plain ssh needs the shell to report what runs: Connect+ // sees the host's processes itself, and Mosh does not pass the+ // reports on.+ let integration_note = (!use_mosh && !multiplexing).then(|| {+ Self::shell_integration_note(+ ctx,+ font,+ editing.as_deref(),+ shell_integration,+ inner,+ )+ });let mut session_rows = vec![field_h, toggle_h, toggle_h, toggle_h];if use_mosh {session_rows.push(field_h);}+ if let Some(lines) = &integration_note {+ // The toggle and the note under it are one row.+ session_rows.push(toggle_h + lines.len() as f32 * line_h);+ }let session_h = Self::inspector_card_height(ctx, section_h, &session_rows);let mut fy = Self::paint_inspector_card(ctx,@@ -2367,6 +2476,33 @@ impl SshHostsView {fy,inner,)? + gap;+ if let Some(lines) = &integration_note {+ fy = self.paint_toggle_row(+ ctx,+ &mut body_layers,+ font,+ palette,+ &crate::i18n::tr("ssh-shell-integration"),+ shell_integration,+ SshViewAction::ToggleShellIntegration,+ x + pad,+ fy,+ inner,+ )?;+ for line in lines {+ ctx.draw_text(+ &mut body_layers,+ font,+ x + pad,+ fy,+ line,+ palette.muted_text,+ inner,+ )?;+ fy += line_h;+ }+ fy += gap;+ }if use_mosh {let mosh = fields[FIELD_MOSH_SERVER].text().to_string();let text_pad = ctx.px(12.0);@@ -2801,9 +2937,35 @@ mod tests {detected_distro: None,use_mosh: false,mosh_server_command: super::ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND.to_string(),+ shell_integration: false,+ shell_integration_applied: false,+ shell_integration_unsupported: None,+ shell_integration_failure: None,}}+ #[test]+ fn a_failure_shows_only_while_the_change_still_waits() {+ use crate::ssh_hosts::{ShellIntegrationFailure, ShellIntegrationRecord};+ let failed = |failure| ShellIntegrationRecord {+ applied: false,+ unsupported: None,+ failure: Some(failure),+ };+ let unwritable = || ShellIntegrationFailure::Unwritable("~/.zshrc".to_string());++ // Turned on, and the last connection could not write the file.+ let text = SshHostsView::shell_integration_status(true, failed(unwritable()));+ assert!(text.contains("~/.zshrc"), "{}", text);+ let other = ShellIntegrationFailure::Other("Exited with code 2".to_string());+ let text = SshHostsView::shell_integration_status(true, failed(other));+ assert!(text.contains("Exited with code 2"), "{}", text);++ // Turned back off: nothing waits, so nothing has failed.+ let text = SshHostsView::shell_integration_status(false, failed(unwritable()));+ assert!(!text.contains("~/.zshrc"), "{}", text);+ }+#[test]fn duplicate_opens_a_prefilled_new_host_form() {let mut view = SshHostsView::new();