Skip to content

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.

Add Mosh support for SSH hosts

RoversX23f370b8c427
diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rs
index 71cbeda4..cc770722 100644
--- a/wezterm-gui/src/ssh_hosts.rs
+++ b/wezterm-gui/src/ssh_hosts.rs
@@ -5,8 +5,10 @@
//! read-only entries. Runtime domains are still registered lazily with the mux
//! via [`mux::Mux::add_domain`].
-use anyhow::{Context, Result};
+use anyhow::{bail, Context, Result};
+use config::keyassignment::{SpawnCommand, SpawnTabDomain};
use config::{SshDomain, SshMultiplexing};
+use filedescriptor::FileDescriptor;
use mux::domain::Domain;
use mux::ssh::RemoteSshDomain;
use mux::Mux;
@@ -14,12 +16,15 @@ use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
-use std::io::Write;
+use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
+use wezterm_ssh::{Session, SessionEvent};
pub type SshHostId = String;
+pub const DEFAULT_MOSH_SERVER_COMMAND: &str = "mosh-server new -s -l LANG=en_US.UTF-8";
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SshHostSpec {
/// Display name shown on the host card / sidebar row.
@@ -56,12 +61,27 @@ pub struct SshHostSpec {
/// `/etc/os-release` `ID` detected after connecting; drives the OS icon.
#[serde(default)]
pub detected_distro: Option<String>,
+ /// When true, connect with Mosh instead of WezTerm's SSH domain. ThinkTerm
+ /// first tries an integrated SSH bootstrap (`mosh-server new ...`) so the
+ /// stored password can be used; if that fails, it falls back to the
+ /// external `mosh` wrapper for manual interaction.
+ #[serde(default)]
+ pub use_mosh: bool,
+ /// Remote command used by an integrated mosh bootstrap path to start
+ /// `mosh-server`. Kept configurable because different servers may need
+ /// environment overrides or a non-default binary path.
+ #[serde(default = "default_mosh_server_command")]
+ pub mosh_server_command: String,
}
fn default_true() -> bool {
true
}
+fn default_mosh_server_command() -> String {
+ DEFAULT_MOSH_SERVER_COMMAND.to_string()
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SshHostSource {
ThinkTerm,
@@ -311,6 +331,177 @@ pub fn host_project_path(spec: &SshHostSpec) -> PathBuf {
PathBuf::from(format!("ssh://{}", endpoint(spec)))
}
+/// Build the fallback command line for connecting to `spec` via the `mosh` wrapper:
+/// `mosh [--ssh="ssh -p <port> -i <identity>"] <user>@<host>`. mosh performs the
+/// SSH bootstrap itself, so port/identity go into its `--ssh` option and the
+/// target is a bare `user@host` (no `:port`). This fallback only carries port +
+/// identity; arbitrary `ssh_options` and stored passwords are not plumbed
+/// through because the wrapper's SSH bootstrap is interactive.
+pub fn build_mosh_args(spec: &SshHostSpec) -> Vec<String> {
+ let mut ssh = String::from("ssh");
+ if let Some(port) = spec.port {
+ if port != 22 {
+ ssh.push_str(&format!(" -p {port}"));
+ }
+ }
+ if let Some(identity) = spec.identity_file.as_deref().filter(|s| !s.is_empty()) {
+ let identity = shlex::try_quote(identity)
+ .unwrap_or_else(|_| identity.into())
+ .into_owned();
+ ssh.push_str(&format!(" -i {identity}"));
+ }
+
+ let mut args = vec!["mosh".to_string()];
+ if ssh != "ssh" {
+ args.push(format!("--ssh={ssh}"));
+ }
+
+ let target = match spec.username.as_deref().filter(|s| !s.is_empty()) {
+ Some(user) => format!("{user}@{}", spec.host),
+ None => spec.host.clone(),
+ };
+ args.push(target);
+ args
+}
+
+pub fn build_mosh_fallback_spawn(spec: &SshHostSpec) -> SpawnCommand {
+ SpawnCommand {
+ label: Some(format!("mosh {}", spec.label)),
+ args: Some(build_mosh_args(spec)),
+ domain: SpawnTabDomain::DomainName("local".to_string()),
+ ..Default::default()
+ }
+}
+
+fn parse_mosh_connect(output: &str) -> Option<(u16, String)> {
+ for line in output.lines() {
+ let mut parts = line.split_whitespace();
+ if parts.next() != Some("MOSH") || parts.next() != Some("CONNECT") {
+ continue;
+ }
+ let Some(port) = parts.next().and_then(|port| port.parse::<u16>().ok()) else {
+ continue;
+ };
+ let Some(key) = parts.next().filter(|key| !key.is_empty()) else {
+ continue;
+ };
+ let key = key.to_string();
+ if !key.is_empty() {
+ return Some((port, key));
+ }
+ }
+ None
+}
+
+fn build_mosh_client_spawn(
+ spec: &SshHostSpec,
+ host: String,
+ port: u16,
+ key: String,
+) -> SpawnCommand {
+ let mut env = HashMap::new();
+ env.insert("MOSH_KEY".to_string(), key);
+ SpawnCommand {
+ label: Some(format!("mosh {}", spec.label)),
+ args: Some(vec!["mosh-client".to_string(), host, port.to_string()]),
+ set_environment_variables: env,
+ domain: SpawnTabDomain::DomainName("local".to_string()),
+ ..Default::default()
+ }
+}
+
+fn read_fd_to_string(mut fd: FileDescriptor) -> std::io::Result<String> {
+ let mut buf = Vec::new();
+ fd.read_to_end(&mut buf)?;
+ Ok(String::from_utf8_lossy(&buf).into_owned())
+}
+
+async fn connect_mosh_bootstrap_session(spec: &SshHostSpec) -> Result<(Session, String)> {
+ let dom = build_ssh_domain(spec);
+ let ssh_config = mux::ssh::ssh_domain_to_ssh_config(&dom).context("build SSH config")?;
+ let mosh_client_host = ssh_config
+ .get("hostname")
+ .cloned()
+ .unwrap_or_else(|| spec.host.clone());
+ let (session, events) = Session::connect(ssh_config).context("connect to SSH server")?;
+ let mut password = spec
+ .password
+ .as_deref()
+ .map(crate::secret::reveal)
+ .filter(|p| !p.is_empty());
+
+ while let Ok(event) = events.recv().await {
+ match event {
+ SessionEvent::Banner(_) => {}
+ SessionEvent::HostVerify(verify) => {
+ bail!(
+ "SSH host verification requires interactive confirmation: {}",
+ verify.message
+ );
+ }
+ SessionEvent::Authenticate(auth) => {
+ let mut answers = vec![];
+ for prompt in &auth.prompts {
+ if prompt.echo {
+ bail!("SSH authentication requires an interactive prompt");
+ }
+ let Some(stored) = password.take() else {
+ bail!("SSH authentication requires a saved password");
+ };
+ answers.push(stored);
+ }
+ auth.answer(answers)
+ .await
+ .context("answer SSH authentication prompt")?;
+ }
+ SessionEvent::HostVerificationFailed(failed) => {
+ bail!("SSH host verification failed: {}", failed);
+ }
+ SessionEvent::Error(err) => bail!("SSH error: {}", err),
+ SessionEvent::Authenticated => return Ok((session, mosh_client_host)),
+ }
+ }
+
+ bail!("SSH authentication did not complete")
+}
+
+pub async fn build_integrated_mosh_spawn(spec: &SshHostSpec) -> Result<SpawnCommand> {
+ let command = spec.mosh_server_command.trim();
+ if command.is_empty() {
+ bail!("Mosh server command is empty");
+ }
+
+ let (session, host) = connect_mosh_bootstrap_session(spec).await?;
+ let exec = session
+ .exec(command, None)
+ .await
+ .context("run mosh-server command")?;
+ let stdout = exec.stdout;
+ let stderr = exec.stderr;
+ let mut child = exec.child;
+ let stdout_reader = std::thread::spawn(move || read_fd_to_string(stdout));
+ let stderr_reader = std::thread::spawn(move || read_fd_to_string(stderr));
+ let status = child.async_wait().await.context("wait for mosh-server")?;
+ let stdout = stdout_reader
+ .join()
+ .map_err(|_| anyhow::anyhow!("mosh-server stdout reader panicked"))?
+ .context("read mosh-server stdout")?;
+ let stderr = stderr_reader
+ .join()
+ .map_err(|_| anyhow::anyhow!("mosh-server stderr reader panicked"))?
+ .context("read mosh-server stderr")?;
+ let output = format!("{stdout}\n{stderr}");
+
+ let Some((port, key)) = parse_mosh_connect(&output) else {
+ if status.success() {
+ bail!("mosh-server output did not include MOSH CONNECT");
+ }
+ bail!("mosh-server exited with status {}", status.exit_code());
+ };
+
+ Ok(build_mosh_client_spawn(spec, host, port, key))
+}
+
/// Deterministic mux domain name for a host. Stable across restarts so that a
/// snapshotted SSH layout (which records the pane's domain name) can be
/// re-materialized after [`register_saved_hosts`] re-registers the domain.
@@ -448,6 +639,8 @@ fn parse_system_ssh_config_str(content: &str) -> Vec<SshHostEntry> {
default_workspace: None,
detect_os: true,
detected_distro: None,
+ use_mosh: false,
+ mosh_server_command: default_mosh_server_command(),
};
out.push(SshHostEntry {
id: system_host_id(&alias),
@@ -593,6 +786,8 @@ Host prod *.internal
default_workspace: None,
detect_os: false,
detected_distro: None,
+ use_mosh: false,
+ mosh_server_command: default_mosh_server_command(),
}
}
@@ -618,4 +813,129 @@ Host prod *.internal
"an explicit connecttimeout override must win over the default"
);
}
+
+ #[test]
+ fn build_mosh_args_plain_host() {
+ let spec = spec_with_options(HashMap::new());
+ // host-only (no user/port/identity): just `mosh host`.
+ assert_eq!(build_mosh_args(&spec), vec!["mosh", "example.com"]);
+ }
+
+ #[test]
+ fn build_mosh_args_includes_user() {
+ let mut spec = spec_with_options(HashMap::new());
+ spec.username = Some("deploy".to_string());
+ assert_eq!(build_mosh_args(&spec), vec!["mosh", "[email protected]"]);
+ }
+
+ #[test]
+ fn build_mosh_args_maps_port_and_identity_into_ssh() {
+ let mut spec = spec_with_options(HashMap::new());
+ spec.username = Some("deploy".to_string());
+ spec.port = Some(2222);
+ spec.identity_file = Some("/home/me/.ssh/prod".to_string());
+ assert_eq!(
+ build_mosh_args(&spec),
+ vec![
+ "mosh",
+ "--ssh=ssh -p 2222 -i /home/me/.ssh/prod",
+ ]
+ );
+ }
+
+ #[test]
+ fn build_mosh_args_quotes_identity_with_spaces() {
+ let mut spec = spec_with_options(HashMap::new());
+ spec.identity_file = Some("/home/me/.ssh/prod key".to_string());
+ assert_eq!(
+ build_mosh_args(&spec),
+ vec![
+ "mosh",
+ "--ssh=ssh -i '/home/me/.ssh/prod key'",
+ "example.com",
+ ]
+ );
+ }
+
+ #[test]
+ fn build_mosh_args_omits_default_port_22() {
+ let mut spec = spec_with_options(HashMap::new());
+ spec.port = Some(22);
+ // Port 22 is the default, so no `--ssh` is needed.
+ assert_eq!(build_mosh_args(&spec), vec!["mosh", "example.com"]);
+ }
+
+ #[test]
+ fn parse_mosh_connect_finds_line_in_noisy_output() {
+ assert_eq!(
+ parse_mosh_connect("banner\nMOSH CONNECT 60001 abc123\nready"),
+ Some((60001, "abc123".to_string()))
+ );
+ }
+
+ #[test]
+ fn parse_mosh_connect_rejects_invalid_output() {
+ assert_eq!(parse_mosh_connect("MOSH CONNECT nope abc123"), None);
+ assert_eq!(parse_mosh_connect("MOSH CONNECT 60001"), None);
+ assert_eq!(parse_mosh_connect("nothing useful"), None);
+ }
+
+ #[test]
+ fn parse_mosh_connect_skips_malformed_connect_lines() {
+ assert_eq!(
+ parse_mosh_connect("MOSH CONNECT nope abc123\nMOSH CONNECT 60001 good-key"),
+ Some((60001, "good-key".to_string()))
+ );
+ assert_eq!(
+ parse_mosh_connect("MOSH CONNECT 60001\nMOSH CONNECT 60002 better-key"),
+ Some((60002, "better-key".to_string()))
+ );
+ }
+
+ #[test]
+ fn build_mosh_client_spawn_puts_key_only_in_environment() {
+ let spec = spec_with_options(HashMap::new());
+ let spawn = build_mosh_client_spawn(
+ &spec,
+ "example.com".to_string(),
+ 60001,
+ "abc123".to_string(),
+ );
+ assert_eq!(
+ spawn.args,
+ Some(vec![
+ "mosh-client".to_string(),
+ "example.com".to_string(),
+ "60001".to_string(),
+ ])
+ );
+ assert_eq!(
+ spawn
+ .set_environment_variables
+ .get("MOSH_KEY")
+ .map(String::as_str),
+ Some("abc123")
+ );
+ assert!(!spawn
+ .args
+ .as_ref()
+ .unwrap()
+ .iter()
+ .any(|arg| arg.contains("abc123")));
+ assert_eq!(
+ spawn.domain,
+ SpawnTabDomain::DomainName("local".to_string())
+ );
+ }
+
+ #[test]
+ fn use_mosh_defaults_false_when_absent() {
+ // Existing saved hosts (serialized before `use_mosh` existed) must load
+ // with mosh off.
+ let spec: SshHostSpec =
+ serde_json::from_str(r#"{"label":"t","host":"example.com"}"#).unwrap();
+ assert!(!spec.use_mosh);
+ assert_eq!(spec.mosh_server_command, DEFAULT_MOSH_SERVER_COMMAND);
+ }
}
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 5d7ea6a7..ef929f8f 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -168,6 +168,15 @@ pub(crate) struct RemoteConnectState {
pub detect_os: Option<(String, String)>,
}
+/// An in-flight Mosh connection started from a `RemoteThreadView`. Mosh does
+/// not expose an SSH domain status to poll, so the background bootstrap task
+/// uses this token to honor cancellation before adopting the workspace.
+pub(crate) struct MoshConnectState {
+ pub generation: u64,
+ pub workspace_name: String,
+ pub canceled: Arc<AtomicBool>,
+}
+
use crate::spawn::SpawnWhere;
use prevcursor::PrevCursorPos;
@@ -935,6 +944,9 @@ pub struct TermWindow {
/// Tracks SSH connections kicked off by `RemoteThreadView`s.
remote_connects: HashMap<ContentViewId, RemoteConnectState>,
next_remote_connect_generation: u64,
+ /// Tracks Mosh bootstraps kicked off by `RemoteThreadView`s.
+ mosh_connects: HashMap<ContentViewId, MoshConnectState>,
+ next_mosh_connect_generation: u64,
space_owner_id: u64,
active_space_id: String,
workspace_layout_structure_fingerprint: Option<u64>,
@@ -995,7 +1007,8 @@ pub struct TermWindow {
// Full-line per-character colours for the horizontal-scroll fast path, keyed
// by (preview generation, line index). Built once per line and reused across
// every horizontal offset so panning never rebuilds the colour list.
- right_sidebar_file_preview_line_color_cache: RefCell<HashMap<(u64, usize), Rc<Vec<LinearRgba>>>>,
+ right_sidebar_file_preview_line_color_cache:
+ RefCell<HashMap<(u64, usize), Rc<Vec<LinearRgba>>>>,
right_sidebar_file_preview_line_color_cache_order: RefCell<VecDeque<(u64, usize)>>,
right_sidebar_file_tree_scroll_offset: f32,
right_sidebar_file_preview_scroll_offset: f32,
@@ -1493,6 +1506,8 @@ impl TermWindow {
registered_content_view_surfaces: HashMap::new(),
remote_connects: HashMap::new(),
next_remote_connect_generation: 1,
+ mosh_connects: HashMap::new(),
+ next_mosh_connect_generation: 1,
space_owner_id,
active_space_id,
workspace_layout_structure_fingerprint,
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 90c559c8..91a0a7b2 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -30,6 +30,7 @@ use mux_lua::MuxPane;
use std::convert::TryInto;
use std::ops::Sub;
use std::rc::Rc;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use termwiz::hyperlink::Hyperlink;
@@ -2891,6 +2892,7 @@ impl super::TermWindow {
};
self.snapshot_active_workspace_thread_layout();
+ let use_mosh = spec.use_mosh;
let thread_id = crate::workspace_threads::create_disconnected_remote_host_thread(
&self.active_space_id,
&host_id,
@@ -2902,9 +2904,249 @@ impl super::TermWindow {
context.invalidate();
return false;
}
+ if use_mosh {
+ let _ = self.begin_open_remote_thread_connection(thread_id, context, None);
+ }
+ true
+ }
+
+ fn mosh_spec_for_project_id(project_id: &str) -> Option<crate::ssh_hosts::SshHostSpec> {
+ let host_id = crate::workspace_threads::remote_host_id_for_project_id(project_id);
+ crate::ssh_hosts::host_spec(host_id).filter(|spec| spec.use_mosh)
+ }
+
+ /// Bootstrap `mosh-server` over ThinkTerm's SSH stack, then launch the local
+ /// `mosh-client`. If the integrated bootstrap can't proceed (missing stored
+ /// password, host verification prompt, command failure, etc.), fall back to
+ /// the external `mosh` wrapper so the user can still interact manually.
+ fn begin_mosh_thread_connection_impl(
+ &mut self,
+ thread_id: String,
+ view_id: Option<ContentViewId>,
+ context: &dyn WindowOps,
+ orphan_candidate_window_id: Option<MuxWindowId>,
+ workspaces_to_kill_after_adopt: Vec<String>,
+ ) -> bool {
+ let mux = Mux::get();
+ let live_workspaces = mux.iter_workspaces();
+ let Some(plan) =
+ crate::workspace_threads::activation_plan_for_thread(&thread_id, &live_workspaces)
+ else {
+ if let Some(view_id) = view_id {
+ self.fail_remote_connect(view_id, "This thread could not be activated.");
+ } else {
+ context.invalidate();
+ }
+ return true;
+ };
+
+ if !plan.needs_materialize {
+ if let Some(view_id) = view_id {
+ self.remote_connects.remove(&view_id);
+ self.close_content_view_by_id(view_id);
+ }
+ self.activate_workspace_thread_impl(
+ thread_id,
+ context,
+ orphan_candidate_window_id,
+ workspaces_to_kill_after_adopt,
+ );
+ return true;
+ }
+
+ let remote_host_id =
+ crate::workspace_threads::remote_host_id_for_project_id(&plan.project_id).to_string();
+ let Some(spec) = crate::ssh_hosts::host_spec(&remote_host_id).filter(|spec| spec.use_mosh)
+ else {
+ return false;
+ };
+
+ self.snapshot_active_workspace_thread_layout();
+ if view_id.is_none() {
+ self.workspace_sidebar_pending_thread_selection = None;
+ self.set_content_view_active(false);
+ }
+ if let Some(view_id) = view_id {
+ if let Some(view) = self.content_view_mut_by_id(view_id) {
+ view.on_remote_connect_phase(
+ crate::termwindow::content_view::RemoteConnectPhase::Connecting,
+ );
+ }
+ }
+
+ let workspace_name = plan.workspace_name.clone();
+ let (mosh_generation, cancel_token) = if let Some(view_id) = view_id {
+ let generation = self.next_mosh_connect_generation;
+ self.next_mosh_connect_generation =
+ self.next_mosh_connect_generation.saturating_add(1).max(1);
+ let token = Arc::new(AtomicBool::new(false));
+ if let Some(previous) = self.mosh_connects.insert(
+ view_id,
+ super::MoshConnectState {
+ generation,
+ workspace_name: workspace_name.clone(),
+ canceled: Arc::clone(&token),
+ },
+ ) {
+ previous.canceled.store(true, Ordering::SeqCst);
+ self.kill_remote_connect_workspace(&previous.workspace_name);
+ }
+ (Some(generation), Some(token))
+ } else {
+ (None, None)
+ };
+ let size = self.config.initial_size(
+ self.dimensions.dpi as u32,
+ crate::cell_pixel_dims(&self.config, self.dimensions.dpi as f64).ok(),
+ );
+ let term_config: Arc<dyn wezterm_term::TerminalConfiguration> =
+ Arc::new(TermConfig::with_config(self.config.clone()));
+ let window = self.window.clone();
+ let thread_id_for_task = thread_id.clone();
+ let label = spec.label.clone();
+ let fallback_spawn = crate::ssh_hosts::build_mosh_fallback_spawn(&spec);
+ let bootstrap_spec = spec.clone();
+ let cancel_token_for_task = cancel_token.clone();
+
+ promise::spawn::spawn(async move {
+ let spawn_result = promise::spawn::spawn_into_new_thread(move || {
+ promise::spawn::block_on(crate::ssh_hosts::build_integrated_mosh_spawn(
+ &bootstrap_spec,
+ ))
+ })
+ .await;
+ let spawn = match spawn_result {
+ Ok(spawn) => spawn,
+ Err(err) => {
+ log::warn!(
+ "integrated mosh bootstrap failed for {:?}: {err:#}; falling back to external mosh",
+ label
+ );
+ fallback_spawn
+ }
+ };
+
+ if cancel_token_for_task
+ .as_ref()
+ .is_some_and(|token| token.load(Ordering::SeqCst))
+ {
+ return;
+ }
+
+ front_end().set_switching_workspaces(true);
+ let materialized = match crate::workspace_threads::materialize_thread_spawn(
+ workspace_name.clone(),
+ spawn,
+ size,
+ term_config,
+ )
+ .await
+ {
+ Ok(()) => true,
+ Err(err) => {
+ log::error!("failed to materialize Mosh thread: {err:#}");
+ false
+ }
+ };
+
+ if let Some(window) = window {
+ window.notify(TermWindowNotif::Apply(Box::new(move |tw| {
+ tw.finish_mosh_thread_connection(
+ thread_id_for_task,
+ workspace_name,
+ view_id,
+ mosh_generation,
+ cancel_token,
+ materialized,
+ orphan_candidate_window_id,
+ workspaces_to_kill_after_adopt,
+ );
+ })));
+ } else {
+ if cancel_token_for_task
+ .as_ref()
+ .is_some_and(|token| token.load(Ordering::SeqCst))
+ && materialized
+ {
+ kill_workspace_windows(&[workspace_name], None);
+ }
+ front_end().set_switching_workspaces(false);
+ reconcile_workspace_layout_after_materialize(None);
+ }
+ })
+ .detach();
+
+ context.invalidate();
true
}
+ fn finish_mosh_thread_connection(
+ &mut self,
+ thread_id: String,
+ workspace_name: String,
+ view_id: Option<ContentViewId>,
+ mosh_generation: Option<u64>,
+ cancel_token: Option<Arc<AtomicBool>>,
+ materialized: bool,
+ orphan_candidate_window_id: Option<MuxWindowId>,
+ workspaces_to_kill_after_adopt: Vec<String>,
+ ) {
+ let token_cancelled = cancel_token
+ .as_ref()
+ .is_some_and(|token| token.load(Ordering::SeqCst));
+ let mut cancelled = token_cancelled;
+ let mut reveal_now = view_id.is_none();
+ let mut close_view_after_success = None;
+
+ if let Some(view_id) = view_id {
+ let state_matches = self.mosh_connects.get(&view_id).is_some_and(|state| {
+ Some(state.generation) == mosh_generation
+ && cancel_token
+ .as_ref()
+ .is_some_and(|token| Arc::ptr_eq(&state.canceled, token))
+ });
+
+ if !state_matches {
+ cancelled = true;
+ }
+
+ if cancelled {
+ if let Some(state) = self.mosh_connects.remove(&view_id) {
+ state.canceled.store(true, Ordering::SeqCst);
+ }
+ } else if materialized {
+ self.mosh_connects.remove(&view_id);
+ reveal_now = self.active_content_view_id == Some(view_id);
+ self.workspace_sidebar_pending_thread_selection = None;
+ close_view_after_success = Some(view_id);
+ } else {
+ self.mosh_connects.remove(&view_id);
+ self.fail_remote_connect(view_id, "Failed to start Mosh.");
+ }
+ }
+
+ if materialized {
+ if cancelled {
+ self.kill_remote_connect_workspace(&workspace_name);
+ } else if reveal_now {
+ let live_workspaces = Mux::get().iter_workspaces();
+ let _ =
+ crate::workspace_threads::activate_thread_record(&thread_id, &live_workspaces);
+ self.adopt_workspace_in_this_window(&workspace_name);
+ cleanup_orphaned_mux_window(orphan_candidate_window_id);
+ kill_workspace_windows(&workspaces_to_kill_after_adopt, Some(&workspace_name));
+ }
+ }
+
+ if let Some(view_id) = close_view_after_success {
+ self.close_content_view_by_id(view_id);
+ }
+
+ front_end().set_switching_workspaces(false);
+ reconcile_workspace_layout_after_materialize(self.window.clone());
+ self.invalidate_window();
+ }
+
pub(crate) fn activate_workspace_thread_for_new_window(
&mut self,
thread_id: String,
@@ -2940,12 +3182,29 @@ impl super::TermWindow {
return;
}
+ let mux = Mux::get();
+ let live_workspaces = mux.iter_workspaces();
+ if let Some(state) =
+ crate::workspace_threads::thread_connection_state(&thread_id, &live_workspaces)
+ {
+ if state.is_remote && !state.is_live {
+ if Self::mosh_spec_for_project_id(&state.project_id).is_some() {
+ let _ = self.begin_mosh_thread_connection_impl(
+ thread_id,
+ None,
+ context,
+ orphan_candidate_window_id,
+ workspaces_to_kill_after_adopt,
+ );
+ return;
+ }
+ }
+ }
+
self.snapshot_active_workspace_thread_layout();
self.workspace_sidebar_pending_thread_selection = None;
self.set_content_view_active(false);
- let mux = Mux::get();
- let live_workspaces = mux.iter_workspaces();
let Some(plan) =
crate::workspace_threads::activate_thread_record(&thread_id, &live_workspaces)
else {
@@ -3223,6 +3482,16 @@ impl super::TermWindow {
self.fail_remote_connect(view_id, "The saved SSH host no longer exists.");
return;
};
+ if spec.use_mosh {
+ let _ = self.begin_mosh_thread_connection_impl(
+ thread_id,
+ Some(view_id),
+ context,
+ orphan_candidate_window_id,
+ Vec::new(),
+ );
+ return;
+ }
let domain_name = match crate::ssh_hosts::ensure_ssh_domain_registered(&spec) {
Ok(name) => name,
Err(err) => {
@@ -3397,12 +3666,17 @@ impl super::TermWindow {
self.invalidate_window();
}
- /// Cancel an in-flight connection started from `view_id` and tear down its
- /// background SSH workspace. The view has already reset itself to Idle.
+ /// Cancel an in-flight connection started from `view_id` and tear down any
+ /// background workspace it already materialized. The view has already reset
+ /// itself to Idle.
pub(crate) fn cancel_remote_thread_connection(&mut self, view_id: ContentViewId) {
if let Some(state) = self.remote_connects.remove(&view_id) {
self.kill_remote_connect_workspace(&state.workspace_name);
}
+ if let Some(state) = self.mosh_connects.remove(&view_id) {
+ state.canceled.store(true, Ordering::SeqCst);
+ self.kill_remote_connect_workspace(&state.workspace_name);
+ }
self.invalidate_window();
}
diff --git a/wezterm-gui/src/termwindow/remote_thread_view.rs b/wezterm-gui/src/termwindow/remote_thread_view.rs
index 0d2e01f6..fddeac26 100644
--- a/wezterm-gui/src/termwindow/remote_thread_view.rs
+++ b/wezterm-gui/src/termwindow/remote_thread_view.rs
@@ -44,6 +44,7 @@ pub(crate) struct RemoteThreadView {
state: ThreadConnectionState,
endpoint: String,
stale_message: Option<String>,
+ uses_mosh: bool,
phase: ViewPhase,
widgets: UiContext<RemoteThreadAction>,
interaction: InteractionState<RemoteThreadAction>,
@@ -53,6 +54,7 @@ struct RemoteThreadSnapshot {
state: ThreadConnectionState,
endpoint: String,
stale_message: Option<String>,
+ uses_mosh: bool,
}
impl RemoteThreadView {
@@ -63,6 +65,7 @@ impl RemoteThreadView {
state: snapshot.state,
endpoint: snapshot.endpoint,
stale_message: snapshot.stale_message,
+ uses_mosh: snapshot.uses_mosh,
phase: ViewPhase::Idle,
widgets: UiContext::default(),
interaction: InteractionState::default(),
@@ -81,6 +84,15 @@ impl RemoteThreadView {
self.state = snapshot.state;
self.endpoint = snapshot.endpoint;
self.stale_message = snapshot.stale_message;
+ self.uses_mosh = snapshot.uses_mosh;
+ }
+
+ fn transport_label(&self) -> &'static str {
+ if self.uses_mosh {
+ "Mosh"
+ } else {
+ "SSH"
+ }
}
fn paint_impl(
@@ -274,17 +286,31 @@ impl RemoteThreadView {
SPINNER_FRAMES[(elapsed.as_millis() / 120) as usize % SPINNER_FRAMES.len()];
(
format!("{frame} Connecting…"),
- format!("Elapsed {}s", elapsed.as_secs()),
+ format!(
+ "Transport: {} · elapsed {}s",
+ self.transport_label(),
+ elapsed.as_secs()
+ ),
)
}
ViewPhase::Failed { .. } => (
"The connection failed.".to_string(),
- "Retry, or cancel to dismiss.".to_string(),
- ),
- ViewPhase::Idle => (
- "Connect opens SSH.".to_string(),
- "Delete removes this thread.".to_string(),
+ format!(
+ "Transport: {} · retry, or cancel to dismiss.",
+ self.transport_label()
+ ),
),
+ ViewPhase::Idle => {
+ let detail = if self.uses_mosh {
+ "Starts mosh-server over SSH, then opens mosh-client."
+ } else {
+ "Opens a ThinkTerm SSH session."
+ };
+ (
+ format!("Transport: {}", self.transport_label()),
+ detail.to_string(),
+ )
+ }
};
ctx.draw_text(
layers,
@@ -628,11 +654,13 @@ fn remote_thread_snapshot(state: ThreadConnectionState) -> RemoteThreadSnapshot
} else {
None
};
+ let uses_mosh = spec.as_ref().is_some_and(|spec| spec.use_mosh);
RemoteThreadSnapshot {
state,
endpoint,
stale_message,
+ uses_mosh,
}
}
diff --git a/wezterm-gui/src/termwindow/ssh_hosts_view.rs b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
index 532921f0..a1cd5bf2 100644
--- a/wezterm-gui/src/termwindow/ssh_hosts_view.rs
+++ b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
@@ -30,8 +30,10 @@ const FIELD_USER: usize = 3;
const FIELD_PASSWORD: usize = 4;
const FIELD_IDENTITY: usize = 5;
const FIELD_WORKSPACE: usize = 6;
-const FIELD_COUNT: usize = 7;
-const FIELD_LABELS: [&str; FIELD_COUNT] = [
+const FIELD_MOSH_SERVER: usize = 7;
+const BASE_FIELD_COUNT: usize = 7;
+const FIELD_COUNT: usize = 8;
+const FIELD_LABELS: [&str; BASE_FIELD_COUNT] = [
"Name",
"Host",
"Port",
@@ -69,6 +71,7 @@ enum SshViewAction {
New,
FocusField(usize),
ToggleDetect,
+ ToggleMosh,
Save,
SaveAndConnect,
Cancel,
@@ -88,6 +91,7 @@ struct HostForm {
original: Option<SshHostSpec>,
fields: [String; FIELD_COUNT],
detect_os: bool,
+ use_mosh: bool,
error: Option<String>,
}
@@ -172,9 +176,18 @@ impl SshHostsView {
// ---- form helpers -----------------------------------------------------
+ fn visible_field_count(form: &HostForm) -> usize {
+ if form.use_mosh {
+ FIELD_COUNT
+ } else {
+ BASE_FIELD_COUNT
+ }
+ }
+
fn open_new_form(&mut self) {
let mut form = HostForm::default();
form.fields[FIELD_PORT] = "22".to_string();
+ form.fields[FIELD_MOSH_SERVER] = ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND.to_string();
form.detect_os = true;
self.form = Some(form);
self.focus = Focus::Field(FIELD_HOST);
@@ -199,12 +212,15 @@ impl SshHostsView {
.unwrap_or_default();
fields[FIELD_IDENTITY] = spec.identity_file.clone().unwrap_or_default();
fields[FIELD_WORKSPACE] = spec.default_workspace.clone().unwrap_or_default();
+ fields[FIELD_MOSH_SERVER] = spec.mosh_server_command.clone();
let detect_os = spec.detect_os;
+ let use_mosh = spec.use_mosh;
self.form = Some(HostForm {
editing: Some(project_id.to_string()),
original: Some(spec),
fields,
detect_os,
+ use_mosh,
error: None,
});
self.focus = Focus::Field(FIELD_HOST);
@@ -252,6 +268,8 @@ impl SshHostsView {
default_workspace: None,
detect_os: true,
detected_distro: None,
+ use_mosh: false,
+ mosh_server_command: ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND.to_string(),
});
spec.label = label;
spec.host = host;
@@ -273,6 +291,17 @@ impl SshHostsView {
spec.identity_file = opt(&form.fields[FIELD_IDENTITY]);
spec.default_workspace = opt(&form.fields[FIELD_WORKSPACE]);
spec.detect_os = form.detect_os;
+ spec.use_mosh = form.use_mosh;
+ let mosh_server_command = form.fields[FIELD_MOSH_SERVER].trim();
+ if spec.use_mosh && mosh_server_command.is_empty() {
+ form.error = Some("Mosh server command is required".to_string());
+ return None;
+ }
+ spec.mosh_server_command = if mosh_server_command.is_empty() {
+ ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND.to_string()
+ } else {
+ mosh_server_command.to_string()
+ };
let project_id = match &form.editing {
Some(id) => match ssh_hosts::try_update_host(id, spec) {
@@ -397,7 +426,12 @@ impl SshHostsView {
ContentViewResponse::Redraw
}
SshViewAction::FocusField(n) => {
- self.focus = Focus::Field(n.min(FIELD_COUNT - 1));
+ let count = self
+ .form
+ .as_ref()
+ .map(Self::visible_field_count)
+ .unwrap_or(BASE_FIELD_COUNT);
+ self.focus = Focus::Field(n.min(count - 1));
ContentViewResponse::Redraw
}
SshViewAction::ToggleDetect => {
@@ -406,6 +440,19 @@ impl SshHostsView {
}
ContentViewResponse::Redraw
}
+ SshViewAction::ToggleMosh => {
+ if let Some(form) = self.form.as_mut() {
+ form.use_mosh = !form.use_mosh;
+ if form.use_mosh && form.fields[FIELD_MOSH_SERVER].trim().is_empty() {
+ form.fields[FIELD_MOSH_SERVER] =
+ ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND.to_string();
+ }
+ if !form.use_mosh && self.focus == Focus::Field(FIELD_MOSH_SERVER) {
+ self.focus = Focus::Field(FIELD_WORKSPACE);
+ }
+ }
+ ContentViewResponse::Redraw
+ }
SshViewAction::Save => {
self.persist_form();
ContentViewResponse::Redraw
@@ -519,7 +566,12 @@ impl SshHostsView {
fn step_field(&mut self, delta: isize) {
self.select_all = false;
if let Focus::Field(n) = self.focus {
- let next = (n as isize + delta).rem_euclid(FIELD_COUNT as isize) as usize;
+ let count = self
+ .form
+ .as_ref()
+ .map(Self::visible_field_count)
+ .unwrap_or(BASE_FIELD_COUNT);
+ let next = (n.min(count - 1) as isize + delta).rem_euclid(count as isize) as usize;
self.focus = Focus::Field(next);
} else {
self.focus = Focus::Field(FIELD_HOST);
@@ -531,6 +583,9 @@ impl SshHostsView {
Focus::Search => f(&mut self.search),
Focus::Field(n) => {
if let Some(form) = self.form.as_mut() {
+ if n >= FIELD_COUNT {
+ return;
+ }
form.error = None;
f(&mut form.fields[n]);
}
@@ -551,6 +606,9 @@ impl SshHostsView {
Focus::Search => std::mem::take(&mut self.search),
Focus::Field(n) => {
let form = self.form.as_mut()?;
+ if n >= FIELD_COUNT {
+ return None;
+ }
form.error = None;
std::mem::take(&mut form.fields[n])
}
@@ -1168,9 +1226,13 @@ impl SshHostsView {
)?;
let subtitle = {
let user = spec.username.as_deref().unwrap_or("");
- let source = match entry.source {
- SshHostSource::ThinkTerm => "ssh",
- SshHostSource::System => "system ssh",
+ let source = if spec.use_mosh {
+ "mosh"
+ } else {
+ match entry.source {
+ SshHostSource::ThinkTerm => "ssh",
+ SshHostSource::System => "system ssh",
+ }
};
if user.is_empty() {
source.to_string()
@@ -1238,6 +1300,7 @@ impl SshHostsView {
let form = self.form.as_ref().unwrap();
let editing = form.editing.is_some();
let detect_os = form.detect_os;
+ let use_mosh = form.use_mosh;
let fields = form.fields.clone();
let error = form.error.clone();
let focus = self.focus;
@@ -1255,7 +1318,7 @@ impl SshHostsView {
let line_h = ctx.metrics.cell_size.height as f32;
let field_w = width.min(560.0);
let mut cur_y = y + line_h + 18.0;
- for i in 0..FIELD_COUNT {
+ for i in 0..BASE_FIELD_COUNT {
ctx.draw_text(
layers,
font,
@@ -1322,6 +1385,51 @@ impl SshHostsView {
)?;
cur_y += toggle_h + 24.0;
+ // Use-Mosh toggle: connect by launching the local `mosh` client instead
+ // of the SSH domain.
+ ctx.draw_text(
+ layers,
+ font,
+ x,
+ cur_y + (toggle_h - line_h) / 2.0,
+ "Connect with Mosh",
+ palette.text,
+ field_w - toggle_w - 12.0,
+ )?;
+ draw_toggle(
+ ctx,
+ layers,
+ &mut self.widgets,
+ palette,
+ rect(x + field_w - toggle_w, cur_y, toggle_w, toggle_h),
+ use_mosh,
+ SshViewAction::ToggleMosh,
+ )?;
+ cur_y += toggle_h + 24.0;
+
+ if use_mosh {
+ draw_text_input(
+ ctx,
+ layers,
+ font,
+ &mut self.widgets,
+ &self.interaction,
+ palette,
+ tokens,
+ 12.0,
+ cursor_on,
+ TextInputSpec {
+ placeholder: ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND,
+ text: &fields[FIELD_MOSH_SERVER],
+ rect: rect(x, cur_y, field_w, INPUT_H),
+ focused: focus == Focus::Field(FIELD_MOSH_SERVER),
+ selected_all: focus == Focus::Field(FIELD_MOSH_SERVER) && self.select_all,
+ action: SshViewAction::FocusField(FIELD_MOSH_SERVER),
+ },
+ )?;
+ cur_y += INPUT_H + 24.0;
+ }
+
if let Some(err) = &error {
ctx.draw_text(
layers,
diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rs
index afae942c..34dac659 100644
--- a/wezterm-gui/src/termwindow/ui/sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@ -45,6 +45,7 @@ const SESSION_STATUS_DOT_SIZE: usize = 10;
const SESSION_STATUS_ICON_SIZE: usize = 20;
const SESSION_STATUS_ACTIVE_ICON_SIZE: usize = 26;
const SESSION_STATUS_DONE_COLOR: LinearRgba = LinearRgba::with_components(0.20, 0.78, 0.36, 1.0);
+const SESSION_STATUS_OPEN_COLOR: LinearRgba = LinearRgba::with_components(0.12, 0.48, 1.0, 1.0);
const SIDEBAR_SECTION_ACTION_SIZE: usize = 48;
const SIDEBAR_SECTION_ACTION_ICON_INSET: usize = 6;
@@ -288,7 +289,7 @@ impl crate::TermWindow {
} else if session.is_pinned {
foreground.mul_alpha(0.68)
} else if session.is_materialized {
- foreground.mul_alpha(0.45)
+ SESSION_STATUS_OPEN_COLOR
} else {
foreground.mul_alpha(0.16)
}
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index fed010da..52a26dd7 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -1,6 +1,6 @@
use anyhow::{ensure, Context, Result};
use chrono::Utc;
-use config::keyassignment::SpawnTabDomain;
+use config::keyassignment::{SpawnCommand, SpawnTabDomain};
use futures::future::LocalBoxFuture;
use mux::domain::SplitSource;
use mux::pane::PaneId;
@@ -8,6 +8,7 @@ use mux::tab::{PaneEntry, PaneNode, PaneStackEntry, SplitDirection, SplitRequest
use mux::window::WindowId as MuxWindowId;
use mux::Mux;
use parking_lot::Mutex;
+use portable_pty::CommandBuilder;
use serde::{Deserialize, Serialize};
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
@@ -979,6 +980,66 @@ pub async fn materialize_thread(
}
}
+pub async fn materialize_thread_spawn(
+ workspace_name: String,
+ spawn: SpawnCommand,
+ size: TerminalSize,
+ term_config: Arc<dyn TerminalConfiguration>,
+) -> Result<()> {
+ let mux = Mux::get();
+ if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {
+ return Ok(());
+ }
+
+ let cwd = if let Some(cwd) = spawn.cwd.as_ref() {
+ Some(
+ cwd.to_str()
+ .map(|s| s.to_string())
+ .with_context(|| format!("convert cwd {:?} to unicode", cwd))?,
+ )
+ } else {
+ None
+ };
+
+ let command = match (
+ spawn.args.as_ref(),
+ spawn.cwd.as_ref(),
+ spawn.set_environment_variables.is_empty(),
+ ) {
+ (None, None, true) => None,
+ _ => {
+ let mut builder = spawn
+ .args
+ .as_ref()
+ .map(|args| CommandBuilder::from_argv(args.iter().map(Into::into).collect()))
+ .unwrap_or_else(CommandBuilder::new_default_prog);
+ for (key, value) in spawn.set_environment_variables.iter() {
+ builder.env(key, value);
+ }
+ if let Some(cwd) = spawn.cwd.as_ref() {
+ builder.cwd(cwd);
+ }
+ Some(builder)
+ }
+ };
+
+ let (_tab, pane, _window_id) = mux
+ .spawn_tab_or_window(
+ None,
+ spawn.domain,
+ command,
+ cwd,
+ size,
+ None,
+ workspace_name,
+ spawn.position,
+ )
+ .await
+ .context("spawn command in thread workspace")?;
+ pane.set_config(term_config);
+ Ok(())
+}
+
pub fn thread_layout(thread_id: &str) -> Option<WorkspaceThreadLayoutSnapshot> {
let store = THREAD_STORE.lock();
store