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(remote): offer to install ThinkTerm on a server that has none
RoversXfe3d48b76753
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rsindex 2b6c1cf8..78ee0341 100644--- a/wezterm-client/src/client.rs+++ b/wezterm-client/src/client.rs@@ -314,6 +314,72 @@ pub struct IncompatibleVersionError {pub codec_vers: usize,}+/// The host a ThinkTerm Connect domain reaches over ssh has neither+/// ThinkTerm nor WezTerm to run the mux proxy with. The attach offers to+/// install ThinkTerm there (`remote_update::offer_remote_install`).+#[derive(Error, Debug, Clone, PartialEq, Eq)]+#[error("ThinkTerm is not installed on {host}")]+pub struct RemoteMuxMissing {+ pub host: String,+}++/// The person chose not to install ThinkTerm on a host that has none. A+/// click on the host's card then reaches it with plain ssh, this once; the+/// other ways in stop here.+#[derive(Error, Debug, Clone, PartialEq, Eq)]+#[error("ThinkTerm was not installed on {host}")]+pub struct RemoteInstallDeclined {+ pub host: String,+}++/// Asks a host whether the default proxy command has a binary to run: the+/// same three places `Reconnectable::remote_mux_command` tries, in a shell+/// that prints which way it went.+const REMOTE_MUX_PROBE: &str = "if [ -x \"$HOME/.local/bin/thinkterm\" ] \+ || command -v thinkterm >/dev/null 2>&1 \+ || command -v wezterm >/dev/null 2>&1; \+ then echo present; else echo missing; fi";++/// Whether the probe's output says there is nothing to run. Anything but a+/// plain "missing" -- a login banner, an error, no answer -- is not taken+/// for one: the proxy then runs and fails the way it always has.+fn probe_says_missing(output: &str) -> bool {+ output.trim() == "missing"+}++/// How long a host gets to answer the probe. One that does not is taken to+/// have a binary: the proxy then runs, and its handshake has its own limit.+const REMOTE_MUX_PROBE_TIMEOUT: Duration = Duration::from_secs(15);++/// `fd` read until the other end closes it, or `None` once `limit` has+/// passed first, or the output grows past anything the probe prints.+fn read_until_closed_within(fd: &mut FileDescriptor, limit: Duration) -> Option<String> {+ use filedescriptor::{poll, pollfd, AsRawSocketDescriptor, POLLIN};+ const MAX_OUTPUT: usize = 16 * 1024;+ let deadline = std::time::Instant::now() + limit;+ let mut output = Vec::new();+ let mut buf = [0u8; 1024];+ loop {+ let left = deadline.checked_duration_since(std::time::Instant::now())?;+ let mut pfd = [pollfd {+ fd: fd.as_socket_descriptor(),+ events: POLLIN,+ revents: 0,+ }];+ match poll(&mut pfd, Some(left)) {+ Ok(0) => return None,+ Ok(_) => match fd.read(&mut buf) {+ Ok(0) => return Some(String::from_utf8_lossy(&output).into_owned()),+ Ok(len) if output.len() + len > MAX_OUTPUT => return None,+ Ok(len) => output.extend_from_slice(&buf[..len]),+ Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {}+ Err(_) => return None,+ },+ Err(_) => return None,+ }+ }+}+/// The server answered an RPC with a refusal. The transport carried the/// request and the reply; only this request was rejected. Callers that/// keep going after a refusal downcast to this so that a transport@@ -1613,6 +1679,36 @@ impl Reconnectable {}}+ /// Whether `sess`'s host has no binary for the default proxy command.+ /// A probe that cannot be run answers no.+ fn remote_mux_missing(sess: &wezterm_ssh::Session) -> bool {+ // Its input from /dev/null: closing our end of stdin early closes+ // the whole channel, losing the answer.+ let probe = format!("{{ {REMOTE_MUX_PROBE}; }} </dev/null");+ let exec = match smol::block_on(sess.exec(&probe, None)) {+ Ok(exec) => exec,+ Err(err) => {+ log::warn!("could not ask the host for its mux binary: {err:#}");+ return false;+ }+ };+ let stdin = exec.stdin;+ let mut stdout = exec.stdout;+ let mut stderr = exec.stderr;+ let mut child = exec.child;+ let drain = thread::spawn(move || std::io::copy(&mut stderr, &mut std::io::sink()));+ let Some(output) = read_until_closed_within(&mut stdout, REMOTE_MUX_PROBE_TIMEOUT) else {+ // Closing our end of the channel ends it, and with it the+ // drain; waiting on either here could last forever.+ log::warn!("the host did not say in time whether it has a mux binary");+ return false;+ };+ let _ = drain.join();+ let _ = child.wait();+ drop(stdin);+ probe_says_missing(&output)+ }+fn ssh_connect(&mut self,ssh_dom: SshDomain,@@ -1624,6 +1720,21 @@ impl Reconnectable {let sess =ssh_connect_with_ui_and_password(ssh_config, ui, ssh_dom.stored_password.clone())?;+ // A host with no mux binary would answer the proxy only with+ // "command not found" and a closed stream. Asked first, that case is+ // told apart, and the attach can offer to install ThinkTerm. Only the+ // default command is probed: a configured path or proxy command is+ // the person's own, and a reconnect has already been through this.+ if initial+ && ssh_dom.override_proxy_command.is_none()+ && ssh_dom.remote_wezterm_path.is_none()+ && Self::remote_mux_missing(&sess)+ {+ return Err(RemoteMuxMissing {+ host: ssh_dom.remote_address.clone(),+ }+ .into());+ }let cmd = if let Some(cmd) = ssh_dom.override_proxy_command.clone() {cmd} else if initial || !no_auto_start {@@ -3026,6 +3137,80 @@ mod tests {);}+ #[test]+ fn only_a_plain_missing_counts_as_no_mux_binary() {+ assert!(super::probe_says_missing("missing\n"));+ assert!(!super::probe_says_missing("present\n"));+ assert!(!super::probe_says_missing(""));+ assert!(!super::probe_says_missing("Welcome to devbox\nmissing\n"));+ }++ /// The probe, run in a shell, says "missing" exactly when the default+ /// proxy command finds nothing to run.+ #[cfg(unix)]+ #[test]+ fn the_probe_finds_a_binary_exactly_where_the_proxy_command_would() {+ use std::os::unix::fs::PermissionsExt;+ use std::path::Path;++ fn place(dir: &Path, name: &str) {+ std::fs::create_dir_all(dir).unwrap();+ let file = dir.join(name);+ std::fs::write(&file, "#!/bin/sh\necho ran\n").unwrap();+ std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ fn run(home: &Path, bin: &Path, script: &str) -> String {+ let out = std::process::Command::new("/bin/sh")+ .arg("-c")+ .arg(script)+ .env_clear()+ .env("HOME", home)+ .env("PATH", bin)+ .output()+ .unwrap();+ String::from_utf8_lossy(&out.stdout).into_owned()+ }++ for (case, missing) in [+ ("~/.local/bin/thinkterm", false),+ ("thinkterm on PATH", false),+ ("wezterm on PATH", false),+ ("nothing", true),+ ] {+ let dir = tempfile::tempdir().unwrap();+ let home = dir.path().join("home");+ let bin = dir.path().join("bin");+ std::fs::create_dir_all(&home).unwrap();+ std::fs::create_dir_all(&bin).unwrap();+ match case {+ "~/.local/bin/thinkterm" => place(&home.join(".local/bin"), "thinkterm"),+ "thinkterm on PATH" => place(&bin, "thinkterm"),+ "wezterm on PATH" => place(&bin, "wezterm"),+ _ => {}+ }+ let probe = run(&home, &bin, super::REMOTE_MUX_PROBE);+ let proxy = run(&home, &bin, &Reconnectable::remote_mux_command(&None, "proxy"));+ assert_eq!(super::probe_says_missing(&probe), missing, "{case}: {probe:?}");+ assert_eq!(proxy.trim() == "ran", !missing, "{case}: {proxy:?}");+ }+ }++ #[cfg(unix)]+ #[test]+ fn a_probe_that_never_answers_is_given_up_on() {+ let (mut ours, _theirs) = filedescriptor::socketpair().unwrap();+ let started = Instant::now();+ let read = super::read_until_closed_within(&mut ours, Duration::from_millis(100));+ assert_eq!(read, None);+ assert!(started.elapsed() < Duration::from_secs(5));++ let (mut ours, mut theirs) = filedescriptor::socketpair().unwrap();+ std::io::Write::write_all(&mut theirs, b"missing\n").unwrap();+ drop(theirs);+ let read = super::read_until_closed_within(&mut ours, Duration::from_secs(5));+ assert_eq!(read.as_deref(), Some("missing\n"));+ }+#[test]fn remote_mux_command_defaults_to_thinkterm_with_wezterm_fallback() {let cmd = Reconnectable::remote_mux_command(&None, "cli --prefer-mux proxy");diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rsindex 20312e2b..cedbf662 100644--- a/wezterm-client/src/domain.rs+++ b/wezterm-client/src/domain.rs@@ -338,6 +338,14 @@ pub fn is_fatal_attach_error(err: &anyhow::Error) -> bool {|| cause.downcast_ref::<wezterm_ssh::HostVerificationFailed>().is_some()+ // A host with no ThinkTerm stays without one until somebody+ // installs it; trying again would only ask again.+ || cause+ .downcast_ref::<crate::client::RemoteMuxMissing>()+ .is_some()+ || cause+ .downcast_ref::<crate::client::RemoteInstallDeclined>()+ .is_some()})}@@ -5018,6 +5026,13 @@ mod tests {file: None,}).context("host verification"),+ anyhow::Error::new(crate::client::RemoteMuxMissing {+ host: "server-a:22".to_string(),+ })+ .context("Installing ThinkTerm failed: cancelled"),+ anyhow::Error::new(crate::client::RemoteInstallDeclined {+ host: "server-a:22".to_string(),+ }),];for err in fatal_errors {assert!(is_fatal_attach_error(&err), "{}", format!("{err:#}"));@@ -6192,7 +6207,49 @@ impl ClientDomain {}})};- let mut client = connect(config.clone(), ui.clone()).await?;+ let mut client = match connect(config.clone(), ui.clone()).await {+ Ok(client) => client,+ Err(err) => {+ // A host with no ThinkTerm at all is the other+ // connect failure this side can repair: asked, it+ // gets this client's version over the same hop.+ let (ClientDomainConfig::Ssh(ssh), Some(missing)) =+ (&config, err.downcast_ref::<crate::client::RemoteMuxMissing>())+ else {+ return Err(err);+ };+ let host = missing.host.clone();+ let outcome = {+ let ssh = ssh.clone();+ let ui = ui.clone();+ spawn_into_new_thread(move || {+ crate::remote_update::offer_remote_install(&ssh, &ui)+ })+ .await+ };+ match outcome {+ Ok(crate::remote_update::RemoteInstallOutcome::Installed) => {+ connect(config.clone(), ui.clone()).await?+ }+ Ok(crate::remote_update::RemoteInstallOutcome::Declined) => {+ return Err(crate::client::RemoteInstallDeclined { host }.into());+ }+ // Why it could not be installed is on screen;+ // the host is still without ThinkTerm.+ Ok(crate::remote_update::RemoteInstallOutcome::Unavailable) => {+ return Err(err);+ }+ // The host is still without ThinkTerm, which+ // ends this attach; the reason it failed (a+ // cancelled password among them) goes with it.+ Err(install_err) => {+ return Err(err.context(format!(+ "Installing ThinkTerm failed: {install_err:#}"+ )));+ }+ }+ }+ };ui.output_str("Checking server version\n");let verified = client.verify_version_compat(&ui).await;diff --git a/wezterm-client/src/remote_update.rs b/wezterm-client/src/remote_update.rsindex 8c5d60e6..959c532a 100644--- a/wezterm-client/src/remote_update.rs+++ b/wezterm-client/src/remote_update.rs@@ -271,6 +271,114 @@ pub fn offer_remote_update(Ok(RemoteUpdateOutcome::Updated { restarted: true })}+/// What became of the offer to install ThinkTerm on a host that had none.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RemoteInstallOutcome {+ /// The person said no.+ Declined,+ /// Nothing could be installed: there is no way to ask here, the client+ /// is not a release build, its release is not on GitHub, or the host+ /// cannot run it. The UI already says which.+ Unavailable,+ Installed,+}++/// Offer to install this client's ThinkTerm on `ssh_dom`'s host, which has+/// none, so that ThinkTerm Connect can run there. Asked once, before+/// anything is looked up or installed.+pub fn offer_remote_install(+ ssh_dom: &SshDomain,+ ui: &ConnectionUI,+) -> anyhow::Result<RemoteInstallOutcome> {+ let local = thinkterm_update::running_release_version();+ let host = ssh_dom.remote_address.clone();+ let command = thinkterm_update::install_command("server", &local);++ ui.output_str(&format!(+ "\nThinkTerm is not installed on {host}. ThinkTerm Connect runs there, so \+ that its terminals keep running when you disconnect.\n"+ ));+ if !thinkterm_update::is_release_version(&local) {+ ui.output_str(&format!(+ "This client is a development build ({local}), so there is no release to \+ install on {host} that matches it. Build and install a matching \+ thinkterm-mux-server there by hand, or switch the host to SSH.\n"+ ));+ return Ok(RemoteInstallOutcome::Unavailable);+ }+ // Uncommitted changes can include a newer protocol than the release+ // that carries this version label.+ let caveat = if config::wezterm_version().ends_with("-dirty") {+ format!(+ "This client was built with unreleased source changes (codec {}), so the \+ released {local} may still not match it.\n",+ codec::CODEC_VERSION+ )+ } else {+ String::new()+ };+ let answer = ui.input(&format!(+ "ThinkTerm can install {local} there now (downloaded from GitHub, as the ssh \+ user, under ~/.local, with no root):\n \+ {command}\n\+ {caveat}Install it? [y/N] "+ ));+ let answer = match answer {+ Ok(answer) => answer,+ Err(err) => {+ log::info!("remote install not offered: {err:#}");+ ui.output_str(&format!(+ "To install it yourself, run this on {host}:\n {command}\n"+ ));+ return Ok(RemoteInstallOutcome::Unavailable);+ }+ };+ if !is_yes(&answer) {+ ui.output_str(&format!(+ "Not installing. To do it yourself, run this on {host}:\n {command}\n"+ ));+ return Ok(RemoteInstallOutcome::Declined);+ }+ if let Err(lookup) = thinkterm_update::get_release_by_tag(&local) {+ if is_not_published(&lookup) {+ ui.output_str(&format!(+ "GitHub has no release {local} yet. Install a matching \+ thinkterm-mux-server on {host} by hand, or switch the host to SSH.\n"+ ));+ } else {+ ui.output_str(&format!("Could not look up {local} on GitHub: {lookup:#}\n"));+ }+ return Ok(RemoteInstallOutcome::Unavailable);+ }++ let ssh_config = mux::ssh::ssh_domain_to_ssh_config(ssh_dom)?;+ let mut ui_for_auth = ui.clone();+ let session = mux::ssh::ssh_connect_with_ui_and_password(+ ssh_config,+ &mut ui_for_auth,+ ssh_dom.stored_password.clone(),+ )+ .with_context(|| format!("opening an ssh session to {host} for the install"))?;+ if let Some(reason) = host_cannot_take_a_release(&session) {+ ui.output_str(&format!(+ "{reason}, so the release build of {local} cannot be installed on {host}.\n{}\n",+ thinkterm_update::build_from_source_instructions(&local)+ ));+ return Ok(RemoteInstallOutcome::Unavailable);+ }++ ui.output_str(&format!("\nInstalling ThinkTerm {local} on {host}...\n"));+ if !run_and_relay(&session, ui, &command)? {+ ui.output_str(&format!(+ "\nThe installer on {host} failed; its output is above.\n{}\n",+ thinkterm_update::build_from_source_instructions(&local)+ ));+ anyhow::bail!("the installer on {host} failed");+ }+ ui.output_str("Installed; connecting.\n");+ Ok(RemoteInstallOutcome::Installed)+}+/// What a person types to stop the server themselves.const STOP_HINT: &str = "pkill -f thinkterm-mux-server";diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 9a72c520..e9d8191c 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -774,6 +774,19 @@ pub(crate) async fn connect_domain_into_space(}Err(err) => {log::error!("attaching {domain_name} failed: {err:#}");+ // The host has no ThinkTerm and the person chose not to+ // install it: nothing is left to show in this window, and+ // the caller that can reach the host with plain ssh needs+ // to know why this stopped.+ let declined = err.chain().any(|cause| {+ cause+ .downcast_ref::<wezterm_client::client::RemoteInstallDeclined>()+ .is_some()+ });+ if declined {+ ui.close();+ return Err(err);+ }return Ok(());}}diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 8ae38f4e..ac6ba007 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -6754,6 +6754,7 @@ impl super::TermWindow {// this just reads what it said.let detect = spec.detect_os && spec.detected_distro.is_none();let detect_host_id = host_id.clone();+ let fallback_host_id = host_id.clone();let detect_window = self.window.as_ref().cloned();promise::spawn::spawn(async move {let domain = match Mux::get().get_domain_by_name(&name) {@@ -6768,7 +6769,33 @@ impl super::TermWindow {};let attached = Arc::clone(&domain);if let Err(err) = crate::connect_domain_into_space(None, domain).await {- log::error!("connect {name}: {err:#}");+ // The host has no ThinkTerm and the person chose not to+ // install it: reach it with plain ssh this time. The host+ // stays a Connect host for the next connect.+ let declined = err.chain().any(|cause| {+ cause+ .downcast_ref::<wezterm_client::client::RemoteInstallDeclined>()+ .is_some()+ });+ match (declined, detect_window.as_ref()) {+ (true, Some(window)) => {+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ let Some(spec) = crate::ssh_hosts::host_spec(&fallback_host_id)+ else {+ return;+ };+ if let Some(window) = term_window.window.clone() {+ term_window.open_direct_ssh_host_thread(+ fallback_host_id,+ &spec,+ &window,+ true,+ );+ }+ })));+ }+ _ => log::error!("connect {name}: {err:#}"),+ }return;}if detect {@@ -6789,6 +6816,21 @@ impl super::TermWindow {return true;}+ self.open_direct_ssh_host_thread(host_id, &spec, context, false)+ }++ /// A thread on `host_id` over a direct ssh (or Mosh) connection, in the+ /// active Space: how a plain host opens, and how a Connect host opens+ /// when its server could not run ThinkTerm. A Mosh thread, and one asked+ /// to `connect_now` (the person already chose to connect), starts+ /// connecting at once.+ pub(crate) fn open_direct_ssh_host_thread(+ &mut self,+ host_id: String,+ spec: &crate::ssh_hosts::SshHostSpec,+ context: &dyn WindowOps,+ connect_now: bool,+ ) -> bool {self.snapshot_active_workspace_thread_layout();let use_mosh = spec.use_mosh;// Any Space can own projects now (a migrated collection simply@@ -6804,7 +6846,7 @@ impl super::TermWindow {context.invalidate();return false;}- if use_mosh {+ if use_mosh || connect_now {let _ = self.begin_open_remote_thread_connection(thread_id, context, None);}true