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.

Make remote sessions effectively seamless over unstable links

RoversX38249931da3d
diff --git a/config/src/ssh.rs b/config/src/ssh.rs
index d8f2c00a..ba97032c 100644
--- a/config/src/ssh.rs
+++ b/config/src/ssh.rs
@@ -100,6 +100,13 @@ pub struct SshDomain {
#[dynamic(default)]
pub ssh_option: HashMap<String, String>,
+ /// Optional stored password used to auto-answer the first password
+ /// (non-echo) auth prompt. Populated at runtime when the domain is
+ /// built from a ThinkTerm SSH host entry; not intended for lua config
+ /// (prefer key auth there).
+ #[dynamic(default)]
+ pub stored_password: Option<String>,
+
pub default_prog: Option<Vec<String>>,
#[dynamic(default)]
diff --git a/mux/src/domain.rs b/mux/src/domain.rs
index c7c49439..40f66a2d 100644
--- a/mux/src/domain.rs
+++ b/mux/src/domain.rs
@@ -481,6 +481,17 @@ impl LocalDomain {
)?,
};
if let Some(dir) = command_dir {
+ // Paths entered in the UI (or relayed by a mux client) may use
+ // `~` for the home directory; the spawn cwd is used verbatim by
+ // the OS, so expand it here against this process's home.
+ let dir = if dir == "~" || dir.starts_with("~/") {
+ config::HOME_DIR
+ .join(dir.strip_prefix("~/").unwrap_or(""))
+ .to_string_lossy()
+ .into_owned()
+ } else {
+ dir
+ };
cmd.cwd(dir);
}
if let Ok(sock) = std::env::var("WEZTERM_UNIX_SOCKET") {
diff --git a/mux/src/ssh.rs b/mux/src/ssh.rs
index 07ebd97d..dac00ec1 100644
--- a/mux/src/ssh.rs
+++ b/mux/src/ssh.rs
@@ -60,6 +60,17 @@ impl LineEditorHost for PasswordPromptHost {
pub fn ssh_connect_with_ui(
ssh_config: wezterm_ssh::ConfigMap,
ui: &mut ConnectionUI,
+) -> anyhow::Result<Session> {
+ ssh_connect_with_ui_and_password(ssh_config, ui, None)
+}
+
+/// Like [`ssh_connect_with_ui`], but auto-answers the first password
+/// (non-echo) auth prompt with a stored password, if any. Only once: a
+/// wrong stored password then falls back to interactive entry.
+pub fn ssh_connect_with_ui_and_password(
+ ssh_config: wezterm_ssh::ConfigMap,
+ ui: &mut ConnectionUI,
+ mut password: Option<String>,
) -> anyhow::Result<Session> {
let cloned_ui = ui.clone();
cloned_ui.run_and_log_error(move || {
@@ -104,6 +115,9 @@ pub fn ssh_connect_with_ui(
}
let res = if prompt.echo {
ui.input(editor_prompt)
+ } else if let Some(stored) = password.take() {
+ ui.output_str(&format!("{editor_prompt} (using stored password)\n"));
+ Ok(stored)
} else {
ui.password(editor_prompt)
};
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index e6355867..7e39c4ef 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -11,7 +11,7 @@ use mux::client::ClientId;
use mux::connui::ConnectionUI;
use mux::domain::DomainId;
use mux::pane::PaneId;
-use mux::ssh::ssh_connect_with_ui;
+use mux::ssh::ssh_connect_with_ui_and_password;
use mux::Mux;
use openssl::ssl::{SslConnector, SslFiletype, SslMethod};
use openssl::x509::X509;
@@ -30,6 +30,7 @@ use std::os::unix::process::CommandExt;
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, AsSocket, BorrowedSocket, RawSocket};
use std::path::{Path, PathBuf};
+use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;
use thiserror::Error;
@@ -49,6 +50,9 @@ enum ReaderMessage {
promise: Sender<anyhow::Result<Pdu>>,
},
Readable,
+ /// The connection has been idle for a while: send a keepalive ping,
+ /// or declare the transport dead if the previous ping went unanswered.
+ KeepaliveTick,
}
#[derive(Clone)]
@@ -376,13 +380,24 @@ async fn client_thread_async(
let mut stream = reconnectable.take_stream().unwrap();
+ // Application-level keepalive: a transport that died without an RST
+ // (VPN egress rotation, sleepy NAT) otherwise hangs silently until the
+ // next write. Ping after this much idle time and require the pong to
+ // arrive before the following tick.
+ const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
+ let mut pending_ping: Option<(u64, std::time::Instant)> = None;
+
loop {
let rx_msg = rx.recv();
let wait_for_read = stream
.wait_for_readable()
.map(|_| Ok(ReaderMessage::Readable));
+ let keepalive = async {
+ smol::Timer::after(KEEPALIVE_INTERVAL).await;
+ Ok(ReaderMessage::KeepaliveTick)
+ };
- match smol::future::or(rx_msg, wait_for_read).await {
+ match smol::future::or(smol::future::or(rx_msg, wait_for_read), keepalive).await {
Ok(ReaderMessage::SendPdu { pdu, promise }) => {
let serial = next_serial;
next_serial += 1;
@@ -393,6 +408,25 @@ async fn client_thread_async(
.context("encoding a PDU to send to the server")?;
stream.flush().await.context("flushing PDU to server")?;
}
+ Ok(ReaderMessage::KeepaliveTick) => {
+ if let Some((serial, sent)) = pending_ping.take() {
+ let reason = format!(
+ "keepalive: no response to ping serial {serial} after {:?}; \
+ transport presumed dead",
+ sent.elapsed()
+ );
+ promises.fail_all(&reason);
+ anyhow::bail!("{reason}");
+ }
+ let serial = next_serial;
+ next_serial += 1;
+ pending_ping = Some((serial, std::time::Instant::now()));
+ Pdu::Ping(Ping {})
+ .encode_async(&mut stream, serial)
+ .await
+ .context("encoding keepalive ping")?;
+ stream.flush().await.context("flushing keepalive ping")?;
+ }
Ok(ReaderMessage::Readable) => {
match Pdu::decode_async(&mut stream, Some(next_serial)).await {
Ok(decoded) => {
@@ -401,7 +435,11 @@ async fn client_thread_async(
decoded.serial,
decoded.pdu.pdu_name()
);
- if decoded.serial == 0 {
+ if pending_ping
+ .map_or(false, |(serial, _)| serial == decoded.serial)
+ {
+ pending_ping = None;
+ } else if decoded.serial == 0 {
process_unilateral(local_domain_id, decoded)
.context("processing unilateral PDU from server")
.map_err(|e| {
@@ -636,15 +674,25 @@ impl Reconnectable {
// the set of tabs and we'd have confusing and inconsistent state
ClientDomainConfig::Unix(_) => false,
ClientDomainConfig::Tls(_) => true,
- // It *does* make sense to reconnect with an ssh session, but we
- // need to grow some smarts about whether the disconnect was because
- // we sent CTRL-D to close the last session, or whether it was a network
- // level disconnect, because we will otherwise throw up authentication
- // dialogs that would be annoying
- ClientDomainConfig::Ssh(_) => false,
+ // An ssh transport dies whenever the network path changes
+ // (VPN egress rotation, sleep/wake, flaky wifi); the remote mux
+ // server is typically still alive, so reconnect and reattach.
+ // A user-initiated detach surfaces as ClientWasDestroyed rather
+ // than an IO error, so it never reaches the reconnect loop, and
+ // any auth prompts are handled by the ConnectionUI just like the
+ // initial connect.
+ ClientDomainConfig::Ssh(_) => true,
}
}
+ /// A dropped ssh transport surfaces as a plain EOF on the channel, which
+ /// is indistinguishable from a deliberate server-side close; since the
+ /// common case by far is a network-level drop, we still reconnect. The
+ /// reconnect UI is cancellable for the rare deliberate-shutdown case.
+ fn reconnect_on_eof(&self) -> bool {
+ matches!(&self.config, ClientDomainConfig::Ssh(_))
+ }
+
fn connect(
&mut self,
initial: bool,
@@ -673,7 +721,12 @@ impl Reconnectable {
fn remote_mux_command(path: &Option<String>, args: &str) -> String {
match path {
Some(path) => format!("{path} {args}"),
- None => format!("wezterm {args}"),
+ // The command runs via the remote user's shell: prefer a
+ // thinkterm binary, fall back to a wezterm one.
+ None => format!(
+ "if command -v thinkterm >/dev/null 2>&1; \
+ then exec thinkterm {args}; else exec wezterm {args}; fi"
+ ),
}
}
@@ -685,7 +738,8 @@ impl Reconnectable {
) -> anyhow::Result<()> {
let ssh_config = mux::ssh::ssh_domain_to_ssh_config(&ssh_dom)?;
- let sess = ssh_connect_with_ui(ssh_config, ui)?;
+ let sess =
+ ssh_connect_with_ui_and_password(ssh_config, ui, ssh_dom.stored_password.clone())?;
let cmd = if let Some(cmd) = ssh_dom.override_proxy_command.clone() {
cmd
} else if initial {
@@ -881,7 +935,7 @@ impl Reconnectable {
ssh_config.insert("port".to_string(), port.to_string());
}
- let sess = ssh_connect_with_ui(ssh_config, ui)?;
+ let sess = ssh_connect_with_ui_and_password(ssh_config, ui, None)?;
let creds = ui.run_and_log_error(|| {
// The `tlscreds` command will start the server if needed and then
@@ -1052,7 +1106,7 @@ impl Client {
const MAX_INTERVAL: Duration = Duration::from_secs(10);
let mut backoff = BASE_INTERVAL;
- loop {
+ 'client: loop {
if let Err(e) = client_thread(&mut reconnectable, local_domain_id, &mut receiver) {
if !reconnectable.reconnectable() || local_domain_id.is_none() {
log::debug!("client thread ended: {}", e);
@@ -1063,9 +1117,11 @@ impl Client {
if let Some(ioerr) = e.root_cause().downcast_ref::<std::io::Error>() {
if let std::io::ErrorKind::UnexpectedEof = ioerr.kind() {
- // Don't reconnect for a simple EOF
- log::error!("server closed connection ({})", e);
- break;
+ if !reconnectable.reconnect_on_eof() {
+ // Don't reconnect for a simple EOF
+ log::error!("server closed connection ({})", e);
+ break;
+ }
}
}
@@ -1074,15 +1130,69 @@ impl Client {
break;
}
- let mut ui = ConnectionUI::new();
- ui.title("ThinkTerm: Reconnecting...");
+ // The first couple of attempts run headless: with key
+ // auth or a stored password the reconnect is completely
+ // silent and the user just sees the pane resume. Only
+ // if we still can't get back (interactive auth needed,
+ // or a longer outage) do we escalate to a visible UI
+ // tab hosted in a window of this domain.
+ let mut windowed_ui: Option<ConnectionUI> = None;
+ let mut attempt = 0usize;
loop {
- ui.sleep_with_reason(
- &format!("client disconnected {}; will reconnect", e),
- backoff,
- )
- .ok();
+ attempt += 1;
+ let mut ui = if attempt <= 2 {
+ ConnectionUI::new_headless()
+ } else if let Some(ui) = windowed_ui.clone() {
+ ui
+ } else {
+ // Host the reconnect UI (and any auth prompts)
+ // as a tab inside a window that already shows
+ // this domain's panes; a standalone UI window
+ // would materialize a whole new ThinkTerm
+ // window over the frozen session.
+ let (window_tx, window_rx) = channel();
+ promise::spawn::spawn_into_main_thread(async move {
+ let window_id = Mux::try_get().and_then(|mux| {
+ mux.iter_windows().into_iter().find(|window_id| {
+ mux.get_window(*window_id).map_or(false, |w| {
+ w.iter().any(|tab| {
+ tab.iter_panes_ignoring_zoom().iter().any(|p| {
+ p.pane.domain_id() == local_domain_id
+ })
+ })
+ })
+ })
+ });
+ window_tx.send(window_id).ok();
+ })
+ .detach();
+ let ui_window_id = window_rx
+ .recv_timeout(Duration::from_secs(2))
+ .ok()
+ .flatten();
+
+ let ui = ConnectionUI::with_params(mux::connui::ConnectionUIParams {
+ window_id: ui_window_id,
+ ..Default::default()
+ });
+ ui.title("ThinkTerm: Reconnecting...");
+ windowed_ui = Some(ui.clone());
+ ui
+ };
+
+ if ui
+ .sleep_with_reason(
+ &format!("client disconnected {}; will reconnect", e),
+ backoff,
+ )
+ .is_err()
+ {
+ // The user closed the reconnect window: stop
+ // trying and detach.
+ log::error!("reconnect cancelled by user");
+ break 'client;
+ }
let initial = false;
let no_auto_start = true; // Don't auto-start on a reconnect
match reconnectable.connect(initial, &mut ui, no_auto_start) {
@@ -1412,10 +1522,9 @@ mod tests {
}
#[test]
- fn remote_mux_command_defaults_to_wezterm_without_shell_fallback() {
- assert_eq!(
- Reconnectable::remote_mux_command(&None, "cli --prefer-mux proxy"),
- "wezterm cli --prefer-mux proxy"
- );
+ fn remote_mux_command_defaults_to_thinkterm_with_wezterm_fallback() {
+ let cmd = Reconnectable::remote_mux_command(&None, "cli --prefer-mux proxy");
+ assert!(cmd.contains("thinkterm cli --prefer-mux proxy"), "{cmd}");
+ assert!(cmd.contains("wezterm cli --prefer-mux proxy"), "{cmd}");
}
}
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index d8cb9e0d..a8c79b4f 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -1072,8 +1072,45 @@ impl Domain for ClientDomain {
}
async fn attach(&self, window_id: Option<WindowId>) -> anyhow::Result<()> {
+ let ui = ConnectionUI::with_params(ConnectionUIParams {
+ window_id,
+ ..Default::default()
+ });
+ self.attach_with_ui(window_id, ui).await
+ }
+
+ fn detachable(&self) -> bool {
+ true
+ }
+
+ fn detach(&self) -> anyhow::Result<()> {
+ self.perform_detach();
+ Ok(())
+ }
+
+ fn state(&self) -> DomainState {
+ if self.inner.lock().unwrap().is_some() {
+ DomainState::Attached
+ } else {
+ DomainState::Detached
+ }
+ }
+}
+
+impl ClientDomain {
+ /// The body of Domain::attach, with a caller-supplied ConnectionUI so
+ /// that a retrying caller can funnel every attempt into one UI tab
+ /// instead of leaving a dead tab behind per attempt. On failure the UI
+ /// is left open (the caller either retries into it or lets it linger to
+ /// show the error); on success it is closed.
+ pub async fn attach_with_ui(
+ &self,
+ window_id: Option<WindowId>,
+ ui: ConnectionUI,
+ ) -> anyhow::Result<()> {
if self.state() == DomainState::Attached {
// Already attached
+ ui.close();
return Ok(());
}
@@ -1081,10 +1118,6 @@ impl Domain for ClientDomain {
let config = self.config.clone();
let activity = mux::activity::Activity::new();
- let ui = ConnectionUI::with_params(ConnectionUIParams {
- window_id,
- ..Default::default()
- });
ui.title("ThinkTerm: Connecting...");
ui.async_run_and_log_error({
@@ -1131,21 +1164,4 @@ impl Domain for ClientDomain {
ui.close();
Ok(())
}
-
- fn detachable(&self) -> bool {
- true
- }
-
- fn detach(&self) -> anyhow::Result<()> {
- self.perform_detach();
- Ok(())
- }
-
- fn state(&self) -> DomainState {
- if self.inner.lock().unwrap().is_some() {
- DomainState::Attached
- } else {
- DomainState::Detached
- }
- }
}
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 180f7dae..b02db607 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -27,7 +27,7 @@ use termwiz::cell::CellAttributes;
use termwiz::surface::{Line, SEQ_ZERO};
use unicode_normalization::UnicodeNormalization;
use wezterm_bidi::Direction;
-use wezterm_client::domain::ClientDomain;
+use wezterm_client::domain::{ClientDomain, ClientDomainConfig};
use wezterm_font::shaper::PresentationWidth;
use wezterm_font::FontConfiguration;
use wezterm_gui_subcommands::*;
@@ -372,6 +372,32 @@ async fn spawn_tab_in_domain_if_mux_is_empty(
/// process, focus an existing window instead of duplicating; otherwise create
/// the connect window with an explicit Space claim so the frontend's
/// reconcile/restore can never hijack it away from the in-window ConnectionUI.
+/// `connect <name>` fallback when the name is not a lua-configured domain:
+/// resolve it against the ThinkTerm SSH host store and register a
+/// multiplexing client domain built from that host, including its stored
+/// credentials, so hosts added in the UI are connectable (and reconnect
+/// silently) without a lua ssh_domains entry.
+fn connect_domain_from_ssh_host(name: &str) -> anyhow::Result<Arc<dyn Domain>> {
+ let entry = crate::ssh_hosts::list_all_hosts()
+ .into_iter()
+ .find(|entry| entry.spec.label == name || entry.id == name)
+ .ok_or_else(|| {
+ anyhow!("invalid domain {name}: not in ssh_domains and not a saved SSH host")
+ })?;
+ let mut dom = crate::ssh_hosts::build_ssh_domain(&entry.spec);
+ dom.name = name.to_string();
+ dom.multiplexing = SshMultiplexing::WezTerm;
+ dom.stored_password = entry
+ .spec
+ .password
+ .as_deref()
+ .map(crate::secret::reveal)
+ .filter(|p| !p.is_empty());
+ let domain: Arc<dyn Domain> = Arc::new(ClientDomain::new(ClientDomainConfig::Ssh(dom)));
+ Mux::get().add_domain(&domain);
+ Ok(domain)
+}
+
async fn connect_domain_into_space(
cmd: Option<CommandBuilder>,
domain: Arc<dyn Domain>,
@@ -449,7 +475,38 @@ async fn connect_domain_into_space(
config.update_ulimit()?;
// The ConnectionUI (auth prompts) appears as a tab inside this window.
- domain.attach(Some(window_id)).await?;
+ // Transient network failures (VPN egress rotation, sleepy wifi) are
+ // common on the way to a remote mux; keep retrying with backoff instead
+ // of terminating the process on the first failed attempt. The user can
+ // bail out by closing the window.
+ {
+ let mut backoff = std::time::Duration::from_secs(1);
+ const MAX_BACKOFF: std::time::Duration = std::time::Duration::from_secs(10);
+ // One ConnectionUI tab hosts every attempt; per-attempt UIs would
+ // pile up as dead tabs because the startup Activity token blocks
+ // pruning for as long as we are still retrying.
+ let ui = mux::connui::ConnectionUI::with_params(mux::connui::ConnectionUIParams {
+ window_id: Some(window_id),
+ ..Default::default()
+ });
+ loop {
+ let attempt = match domain.downcast_ref::<ClientDomain>() {
+ Some(client) => client.attach_with_ui(Some(window_id), ui.clone()).await,
+ None => domain.attach(Some(window_id)).await,
+ };
+ match attempt {
+ Ok(()) => break,
+ Err(err) => {
+ log::error!(
+ "attaching {domain_name} failed: {err:#}; retrying in {backoff:?}"
+ );
+ ui.output_str(&format!("Will retry in {backoff:?}...\n"));
+ smol::Timer::after(backoff).await;
+ backoff = (backoff * 2).min(MAX_BACKOFF);
+ }
+ }
+ }
+ }
// Mirror spawn_tab_in_domain_if_mux_is_empty's empty-server handling.
let no_workspace_filter = None;
@@ -588,9 +645,10 @@ async fn async_run_terminal_gui(
let mux = Mux::get();
let domain = if let Some(name) = &opts.domain {
- let domain = mux
- .get_domain_by_name(name)
- .ok_or_else(|| anyhow!("invalid domain {name}"))?;
+ let domain = match mux.get_domain_by_name(name) {
+ Some(domain) => domain,
+ None => connect_domain_from_ssh_host(name)?,
+ };
Some(domain)
} else {
None
@@ -860,12 +918,15 @@ fn setup_mux(
let default_name =
default_domain_name.unwrap_or(config.default_domain.as_deref().unwrap_or("local"));
- let domain = mux.get_domain_by_name(default_name).ok_or_else(|| {
- anyhow::anyhow!(
- "desired default domain '{}' was not found in mux!?",
- default_name
- )
- })?;
+ let domain = match mux.get_domain_by_name(default_name) {
+ Some(domain) => domain,
+ // Not a lua-configured domain: try the ThinkTerm SSH host store
+ // (register_saved_hosts above only registers direct-ssh domains;
+ // this builds a multiplexing client domain for `connect`).
+ None => connect_domain_from_ssh_host(default_name).with_context(|| {
+ format!("desired default domain '{default_name}' was not found in mux")
+ })?,
+ };
mux.set_default_domain(&domain);
Ok(mux)
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index a880797c..13a34480 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -2208,6 +2208,11 @@ impl TermWindow {
tab.resize(self.terminal_size);
}
}
+ // Tabs arriving via a mux resync (switch-back re-fold,
+ // reattach) get their persisted per-pane font scales
+ // re-applied; the adopt-time application ran before
+ // these panes existed.
+ self.apply_workspace_thread_font_scales();
self.persist_workspace_layout_after_mutation("tab added");
}
MuxNotification::PaneOutput(pane_id) => {
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 47be91c2..8cc122d6 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -3368,10 +3368,33 @@ impl super::TermWindow {
d.state() == mux::domain::DomainState::Attached
});
if !attached {
- log::info!(
- "Space is bound to mux domain {domain_name:?} which is not connected; \
- use `wezterm connect {domain_name}` first"
- );
+ // Attach on demand (auth prompts go through the ConnectionUI),
+ // then re-run this activation once the domain is live.
+ let Some(window) = self.window.clone() else {
+ context.invalidate();
+ return;
+ };
+ let domain_name = domain_name.to_string();
+ let mux_window_id = self.mux_window_id;
+ promise::spawn::spawn(async move {
+ let mux = Mux::get();
+ let domain = mux
+ .get_domain_by_name(&domain_name)
+ .ok_or_else(|| anyhow::anyhow!("domain {domain_name} not found"))?;
+ domain.attach(Some(mux_window_id)).await?;
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ if let Some(win) = term_window.window.clone() {
+ term_window.activate_workspace_thread_impl(
+ thread_id,
+ &win,
+ orphan_candidate_window_id,
+ workspaces_to_kill_after_adopt,
+ );
+ }
+ })));
+ anyhow::Ok(())
+ })
+ .detach();
context.invalidate();
return;
}
diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rs
index 8288061e..28a48391 100644
--- a/wezterm-gui/src/termwindow/resize.rs
+++ b/wezterm-gui/src/termwindow/resize.rs
@@ -72,6 +72,7 @@ impl super::TermWindow {
return;
};
+ let mut changed = false;
for tab in mux_window.iter() {
for pos in tab.iter_panes_ignoring_zoom() {
let pane_id = pos.pane.pane_id();
@@ -81,9 +82,15 @@ impl super::TermWindow {
let mut state = self.pane_state(pos.pane.pane_id());
if state.font_scale != font_scale {
state.font_scale = font_scale;
+ changed = true;
}
}
}
+ if !changed {
+ // Called per TabAddedToWindow during resyncs; skip the cache
+ // flush when nothing actually changed.
+ return;
+ }
self.sync_pane_font_sizes();
self.quad_generation += 1;
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index 55afa51f..13cfd739 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -77,6 +77,13 @@ pub struct WorkspaceThread {
pub name: String,
pub project_id: ProjectId,
pub layout: Option<WorkspaceThreadLayoutSnapshot>,
+ /// Per-pane font scales for mux-domain threads, keyed by the REMOTE
+ /// pane id (stable across resyncs for the life of the server). Local
+ /// threads keep font scales inside `layout`; mux threads must never
+ /// persist layout (the server owns it), but font scale is client-side
+ /// presentation state, so it is persisted separately here.
+ #[serde(default, skip_serializing_if = "HashMap::is_empty")]
+ pub remote_font_scales: HashMap<PaneId, f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub planned_workspace_name: Option<String>,
pub materialized_workspace_name: Option<String>,
@@ -992,13 +999,43 @@ pub fn snapshot_active_space_thread_layout_with_font_scales<F>(
return;
}
- // Domain-owned windows (remote mux windows, tmux) must never be
- // snapshotted locally: the remote mux server owns the layout truth,
- // and a local snapshot would fight it on restore.
+ // Domain-owned windows (remote mux windows, tmux) must never have
+ // their LAYOUT snapshotted locally: the remote mux server owns the
+ // layout truth, and a local snapshot would fight it on restore. Font
+ // scale however is client-side presentation state, so persist that
+ // part keyed by the remote pane id: the local pane ids die with the
+ // mirror window on switch-away and are reissued by the resync on
+ // switch-back.
if Mux::get()
.get_window(window_id)
.map_or(false, |w| w.origin_domain().is_some())
{
+ let mut scales: HashMap<PaneId, f64> = HashMap::new();
+ let mut remote_panes = 0usize;
+ if let Some(window) = Mux::get().get_window(window_id) {
+ for tab in window.iter() {
+ for pos in tab.iter_panes_ignoring_zoom() {
+ if let Some(client_pane) =
+ pos.pane.downcast_ref::<wezterm_client::pane::ClientPane>()
+ {
+ remote_panes += 1;
+ if let Some(scale) = pane_font_scale(pos.pane.pane_id()) {
+ scales.insert(client_pane.remote_pane_id, scale);
+ }
+ }
+ }
+ }
+ }
+ if remote_panes == 0 {
+ // The mirror panes may simply not have folded in yet (attach
+ // or resync still in flight); saving now would clobber the
+ // stored scales with an empty map before restore ever ran.
+ return;
+ }
+ let mut store = THREAD_STORE.lock();
+ if store.snapshot_remote_thread_font_scales(space_id, workspace, scales) {
+ persist_locked(&store);
+ }
return;
}
@@ -1167,8 +1204,45 @@ pub fn workspace_pane_font_scales(
workspace: &str,
window_id: MuxWindowId,
) -> Option<HashMap<PaneId, Option<f64>>> {
- let store = THREAD_STORE.lock();
- store.workspace_pane_font_scales(workspace, window_id)
+ let (local, remote) = {
+ let store = THREAD_STORE.lock();
+ (
+ store.workspace_pane_font_scales(workspace, window_id),
+ store.remote_thread_font_scales(workspace),
+ )
+ };
+ log::debug!(
+ "workspace_pane_font_scales: ws={workspace} window={window_id} local={:?} remote={:?}",
+ local,
+ remote
+ );
+ if local.is_some() {
+ return local;
+ }
+ // Mux-domain threads store scales keyed by remote pane id; translate
+ // through the live panes of the window (their local ids are reissued
+ // by every re-fold, the remote ids are stable).
+ let remote = remote?;
+ let mux = Mux::get();
+ let window = mux.get_window(window_id)?;
+ let mut scales: HashMap<PaneId, Option<f64>> = HashMap::new();
+ for tab in window.iter() {
+ for pos in tab.iter_panes_ignoring_zoom() {
+ if let Some(client_pane) =
+ pos.pane.downcast_ref::<wezterm_client::pane::ClientPane>()
+ {
+ scales.insert(
+ pos.pane.pane_id(),
+ remote.get(&client_pane.remote_pane_id).copied(),
+ );
+ }
+ }
+ }
+ if scales.is_empty() {
+ None
+ } else {
+ Some(scales)
+ }
}
pub fn rename_project(project_id: &str, name: String) -> bool {
@@ -2189,6 +2263,65 @@ impl WorkspaceThreadStore {
.and_then(|layout| pane_font_scales_for_window(layout, window_id))
}
+ /// Store remote-pane-id-keyed font scales for the active thread of the
+ /// given mux-domain Space. Counterpart of snapshot_active_space_thread_layout
+ /// for the one piece of state that IS client-owned on remote threads.
+ fn snapshot_remote_thread_font_scales(
+ &mut self,
+ space_id: &str,
+ workspace: &str,
+ scales: HashMap<PaneId, f64>,
+ ) -> bool {
+ let Some(project_id) = self.active_project_id_for_space(space_id) else {
+ return false;
+ };
+ let Some(project) = self
+ .projects
+ .iter_mut()
+ .find(|project| project.space_id == space_id && project.id == project_id)
+ else {
+ return false;
+ };
+ let project_id = project.id.clone();
+ let active_thread_id = project
+ .active_thread_id
+ .clone()
+ .or_else(|| project.threads.first().map(|session| session.id.clone()));
+ let Some(active_thread_id) = active_thread_id else {
+ return false;
+ };
+ let Some(session) = project
+ .threads
+ .iter_mut()
+ .find(|session| session.id == active_thread_id)
+ else {
+ return false;
+ };
+
+ let expected_workspace = session
+ .materialized_workspace_name
+ .clone()
+ .unwrap_or_else(|| workspace_name_for_thread(&project_id, &session.id));
+ if expected_workspace != workspace {
+ return false;
+ }
+
+ if session.remote_font_scales == scales {
+ return false;
+ }
+ session.remote_font_scales = scales;
+ true
+ }
+
+ fn remote_thread_font_scales(&self, workspace: &str) -> Option<HashMap<PaneId, f64>> {
+ self.projects
+ .iter()
+ .flat_map(|project| project.threads.iter())
+ .find(|session| session.materialized_workspace_name.as_deref() == Some(workspace))
+ .map(|session| session.remote_font_scales.clone())
+ .filter(|scales| !scales.is_empty())
+ }
+
fn rename_project(&mut self, project_id: &str, name: String) -> bool {
let name = name.trim();
if name.is_empty() {
@@ -2589,6 +2722,7 @@ impl WorkspaceThread {
name,
project_id,
layout: None,
+ remote_font_scales: HashMap::new(),
planned_workspace_name: None,
materialized_workspace_name: workspace,
last_active_at: now_ts(),
@@ -2610,6 +2744,7 @@ impl WorkspaceThread {
name,
project_id,
layout: None,
+ remote_font_scales: HashMap::new(),
planned_workspace_name: None,
materialized_workspace_name: workspace,
last_active_at: now_ts(),
diff --git a/wezterm/src/bin/thinkterm.rs b/wezterm/src/bin/thinkterm.rs
new file mode 100644
index 00000000..e2553c21
--- /dev/null
+++ b/wezterm/src/bin/thinkterm.rs
@@ -0,0 +1,42 @@
+//! `thinkterm` is the branded name for the ThinkTerm CLI. The full CLI
+//! lives in the `wezterm` binary built from this same crate; exec it so
+//! the two names stay perfectly in sync without compiling the crate twice.
+
+fn main() {
+ let exe_name = if cfg!(windows) {
+ "wezterm.exe"
+ } else {
+ "wezterm"
+ };
+ let exe = match std::env::current_exe()
+ .ok()
+ .and_then(|p| Some(p.parent()?.join(exe_name)))
+ {
+ Some(exe) => exe,
+ None => {
+ eprintln!("thinkterm: unable to locate the {exe_name} binary next to this one");
+ std::process::exit(1);
+ }
+ };
+
+ let mut cmd = std::process::Command::new(exe);
+ cmd.args(std::env::args_os().skip(1));
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ let err = cmd.exec();
+ eprintln!("thinkterm: failed to exec {cmd:?}: {err}");
+ std::process::exit(1);
+ }
+ #[cfg(windows)]
+ {
+ match cmd.status() {
+ Ok(status) => std::process::exit(status.code().unwrap_or(1)),
+ Err(err) => {
+ eprintln!("thinkterm: failed to run {cmd:?}: {err}");
+ std::process::exit(1);
+ }
+ }
+ }
+}