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
mux-server: never block the main thread on a pane's terminal lock
RoversX900c99ec1a6c
diff --git a/Cargo.lock b/Cargo.lockindex c130c404..42ad42dd 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8143,8 +8143,10 @@ dependencies = ["config","embed-resource","env-bootstrap",+ "hdrhistogram","libc","log",+ "metrics","mlua","mux","openssl",@@ -8175,6 +8177,7 @@ dependencies = ["libc","log","lru",+ "metrics","mux","portable-pty","promise",diff --git a/mux/src/localpane.rs b/mux/src/localpane.rsindex 312a99cd..c5e07007 100644--- a/mux/src/localpane.rs+++ b/mux/src/localpane.rs@@ -361,6 +361,12 @@ impl Pane for LocalPane {self.terminal.lock().current_seqno()}+ fn render_state_is_contended(&self) -> bool {+ // The parser thread holds this for the whole of a batch of output;+ // a probe that fails is the batch still being applied.+ self.terminal.try_lock().is_none()+ }+fn get_changed_since(&self,lines: Range<StableRowIndex>,diff --git a/mux/src/pane.rs b/mux/src/pane.rsindex 267dea6a..ac9a7421 100644--- a/mux/src/pane.rs+++ b/mux/src/pane.rs@@ -286,6 +286,15 @@ pub trait Pane: Downcast + Send + Sync {KeyboardEncoding::Xterm}+ /// Would reading render state (lines, cursor, dimensions) have to wait+ /// for this pane's parser right now? A mux server asks before it reads+ /// on behalf of a client, so its one thread is never stuck behind a+ /// pane digesting a huge frame. A pane with nothing to wait for says+ /// no.+ fn render_state_is_contended(&self) -> bool {+ false+ }+fn copy_user_vars(&self) -> HashMap<String, String> {HashMap::new()}diff --git a/wezterm-mux-server-impl/Cargo.toml b/wezterm-mux-server-impl/Cargo.tomlindex 5f1e3517..4e77c10e 100644--- a/wezterm-mux-server-impl/Cargo.toml+++ b/wezterm-mux-server-impl/Cargo.toml@@ -20,6 +20,7 @@ lazy_static.workspace = truelibc.workspace = truelog.workspace = truelru.workspace = true+metrics.workspace = truemux.workspace = trueportable-pty = { workspace=true, features = ["serde_support"]}promise.workspace = truediff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rsindex 3025a007..a56c0eae 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -17,7 +17,7 @@ use mux::{use promise::spawn::spawn_into_main_thread;use std::collections::HashMap;use std::sync::{Arc, Mutex, OnceLock};-use std::time::Instant;+use std::time::{Duration, Instant};use termwiz::surface::SequenceNo;use url::Url;@@ -81,9 +81,23 @@ pub(crate) struct PerPane {/// Images already sent for this pane, so a fetch can be answered even/// after the cell they were attached to has moved on.sent_images: crate::sent_images::SentImages,+ /// A push task exists for this pane and has not yet read the pane.+ push_scheduled: bool,}impl PerPane {+ /// Claim the one push slot; false when a push is already on its way,+ /// which will carry whatever the caller wanted sent.+ fn claim_push(&mut self) -> bool {+ !std::mem::replace(&mut self.push_scheduled, true)+ }++ /// Give the slot back. Done just before the pane is read, so output+ /// that lands during the read schedules the next push.+ fn release_push(&mut self) {+ self.push_scheduled = false;+ }+fn needs_application_palette(&self, palette: &Option<ColorPalette>) -> bool {self.last_sent_application_palette.as_ref() != Some(palette)}@@ -201,6 +215,49 @@ impl PerPane {}}+/// How long a push waits for a busy pane before looking again: short at+/// first, since a batch of ordinary output is applied in well under a+/// millisecond, backing off so a pane stuck for seconds is not polled at+/// full tilt.+const PUSH_RETRY_MIN: Duration = Duration::from_millis(2);+const PUSH_RETRY_MAX: Duration = Duration::from_millis(50);++/// Push `pane_id`'s changes to this connection once its render state can+/// be read without waiting.+///+/// Every connection's I/O and every push runs on the one main thread,+/// while each pane's parser holds the pane's terminal lock for as long as+/// a batch of output takes to apply. Reading here while a pane was busy+/// with, say, a very large image stalled every other client's handshake,+/// ping and output until that batch was done -- with a runaway pane, for+/// good. So the lock is probed first, and a busy pane's push is put off+/// for as long as it takes: that pane's own output is what waits, nobody+/// else's.+async fn push_pane_changes_when_free(+ pane_id: PaneId,+ sender: PduSender,+ per_pane: Arc<Mutex<PerPane>>,+) -> anyhow::Result<()> {+ let mut delay = PUSH_RETRY_MIN;+ loop {+ let Some(pane) = Mux::get().get_pane(pane_id) else {+ per_pane.lock().unwrap().release_push();+ anyhow::bail!("no such pane {pane_id}");+ };+ if pane.render_state_is_contended() {+ metrics::counter!("mux_server.push.deferred").increment(1);+ smol::Timer::after(delay).await;+ delay = (delay * 2).min(PUSH_RETRY_MAX);+ continue;+ }+ per_pane.lock().unwrap().release_push();+ let started = Instant::now();+ let pushed = maybe_push_pane_changes(&pane, sender, per_pane);+ metrics::histogram!("mux_server.push.latency").record(started.elapsed());+ return pushed;+ }+}+fn maybe_push_pane_changes(pane: &Arc<dyn Pane>,sender: PduSender,@@ -490,15 +547,13 @@ impl SessionHandler {pub fn schedule_pane_push(&mut self, pane_id: PaneId) {let sender = self.to_write_tx.clone();let per_pane = self.per_pane(pane_id);- spawn_into_main_thread(async move {- let mux = Mux::get();- let pane = mux- .get_pane(pane_id)- .ok_or_else(|| anyhow!("no such pane {}", pane_id))?;- maybe_push_pane_changes(&pane, sender, per_pane)?;- Ok::<(), anyhow::Error>(())- })- .detach();+ // One push on its way per pane. A burst of output notifications+ // used to queue a task each, and all but the first found nothing+ // new to send.+ if !per_pane.lock().unwrap().claim_push() {+ return;+ }+ spawn_into_main_thread(push_pane_changes_when_free(pane_id, sender, per_pane)).detach();}pub fn process_one(&mut self, decoded: DecodedPdu) {@@ -2133,6 +2188,21 @@ mod tests {);}+ #[test]+ fn only_one_push_is_scheduled_per_pane_at_a_time() {+ let mut state = PerPane::default();+ assert!(state.claim_push(), "nothing on its way: schedule one");+ assert!(+ !state.claim_push(),+ "already on its way: it will carry this too"+ );+ state.release_push();+ assert!(+ state.claim_push(),+ "released: the next notification schedules again"+ );+ }+#[test]fn application_palette_delivery_distinguishes_unsent_from_reset() {let mut state = PerPane::default();diff --git a/wezterm-mux-server/Cargo.toml b/wezterm-mux-server/Cargo.tomlindex 6b3317e8..2593afee 100644--- a/wezterm-mux-server/Cargo.toml+++ b/wezterm-mux-server/Cargo.toml@@ -22,7 +22,9 @@ clap.workspace = trueconfig.workspace = trueenv-bootstrap.workspace = truelibc.workspace = true+hdrhistogram.workspace = truelog.workspace = true+metrics.workspace = truemux.workspace = truemlua.workspace = trueopenssl.workspace = truediff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rsindex 2dbacda4..fd65c8f5 100644--- a/wezterm-mux-server/src/main.rs+++ b/wezterm-mux-server/src/main.rs@@ -13,6 +13,7 @@ use wezterm_gui_subcommands::*;use wezterm_mux_server_impl::update_mux_domains_for_server;mod daemonize;+mod stats;#[derive(Debug, Parser)]#[command(@@ -236,6 +237,8 @@ fn run() -> anyhow::Result<()> {install_shutdown_signal_handler()?;+ stats::init_from_env()?;+let executor = promise::spawn::SimpleExecutor::new();spawn_listener().map_err(|e| {diff --git a/wezterm-mux-server/src/stats.rs b/wezterm-mux-server/src/stats.rsnew file mode 100644index 00000000..02de7239--- /dev/null+++ b/wezterm-mux-server/src/stats.rs@@ -0,0 +1,155 @@+//! Numbers from inside the server, on request.+//!+//! Set `THINKTERM_MUX_STATS` to a number of seconds and every histogram+//! and counter the server records is logged at that interval: push+//! latency, how often a push found its pane busy, parser throughput.+//! Without it no recorder is installed and the metrics macros cost+//! nothing.++use hdrhistogram::Histogram;+use metrics::{Counter, Gauge, Key, KeyName, Metadata, Recorder, SharedString, Unit};+use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex};+use std::time::Duration;++/// Latencies in nanoseconds; sizes and rates as they come.+struct Hist {+ values: Mutex<Histogram<u64>>,+ scale: f64,+ /// For `.rate` keys: everything recorded since the last report.+ total: AtomicU64,+}++impl metrics::HistogramFn for Hist {+ fn record(&self, value: f64) {+ self.total.fetch_add(value as u64, Ordering::Relaxed);+ self.values+ .lock()+ .unwrap()+ .record((value * self.scale) as u64)+ .ok();+ }+}++struct Count(AtomicU64);++impl metrics::CounterFn for Count {+ fn increment(&self, value: u64) {+ self.0.fetch_add(value, Ordering::Relaxed);+ }++ fn absolute(&self, value: u64) {+ self.0.store(value, Ordering::Relaxed);+ }+}++#[derive(Default)]+struct Registry {+ histograms: HashMap<Key, Arc<Hist>>,+ counters: HashMap<Key, Arc<Count>>,+}++pub struct Stats {+ registry: Arc<Mutex<Registry>>,+}++pub fn init_from_env() -> anyhow::Result<()> {+ let Some(seconds) = std::env::var("THINKTERM_MUX_STATS")+ .ok()+ .and_then(|s| s.trim().parse::<u64>().ok())+ .filter(|s| *s > 0)+ else {+ return Ok(());+ };+ let registry = Arc::new(Mutex::new(Registry::default()));+ let reporter = Arc::clone(®istry);+ std::thread::Builder::new()+ .name("mux-stats".into())+ .spawn(move || loop {+ std::thread::sleep(Duration::from_secs(seconds));+ report(&reporter, seconds);+ })?;+ metrics::set_global_recorder(Stats { registry })+ .map_err(|e| anyhow::anyhow!("installing the metrics recorder: {e}"))+}++fn report(registry: &Mutex<Registry>, interval: u64) {+ let registry = registry.lock().unwrap();+ let mut lines = vec![];+ for (key, hist) in ®istry.histograms {+ let name = key.name();+ if name.ends_with(".rate") {+ let total = hist.total.swap(0, Ordering::Relaxed);+ lines.push(format!("{key}: {}/s", total / interval));+ continue;+ }+ let values = hist.values.lock().unwrap();+ if values.is_empty() {+ continue;+ }+ if name.ends_with(".size") {+ lines.push(format!(+ "{key}: n={} p50={} p95={} max={}",+ values.len(),+ values.value_at_percentile(50.),+ values.value_at_percentile(95.),+ values.max()+ ));+ } else {+ let at = |p| Duration::from_nanos(values.value_at_percentile(p));+ lines.push(format!(+ "{key}: n={} p50={:.2?} p95={:.2?} p99={:.2?} max={:.2?}",+ values.len(),+ at(50.),+ at(95.),+ at(99.),+ Duration::from_nanos(values.max())+ ));+ }+ }+ for (key, count) in ®istry.counters {+ lines.push(format!("{key}: {}", count.0.load(Ordering::Relaxed)));+ }+ lines.sort();+ log::info!("mux stats\n{}", lines.join("\n"));+}++impl Recorder for Stats {+ fn describe_counter(&self, _key: KeyName, _unit: Option<Unit>, _description: SharedString) {}++ fn describe_gauge(&self, _key: KeyName, _unit: Option<Unit>, _description: SharedString) {}++ fn describe_histogram(&self, _key: KeyName, _unit: Option<Unit>, _description: SharedString) {}++ fn register_counter(&self, key: &Key, _metadata: &Metadata) -> Counter {+ let mut registry = self.registry.lock().unwrap();+ let count = registry+ .counters+ .entry(key.clone())+ .or_insert_with(|| Arc::new(Count(AtomicU64::new(0))));+ Counter::from_arc(Arc::clone(count))+ }++ fn register_gauge(&self, _key: &Key, _metadata: &Metadata) -> Gauge {+ Gauge::noop()+ }++ fn register_histogram(&self, key: &Key, _metadata: &Metadata) -> metrics::Histogram {+ let mut registry = self.registry.lock().unwrap();+ let name = key.name();+ let scale = if name.ends_with(".size") || name.ends_with(".rate") {+ 1.0+ } else {+ 1e9+ };+ let hist = registry.histograms.entry(key.clone()).or_insert_with(|| {+ Arc::new(Hist {+ values: Mutex::new(Histogram::new(2).expect("a fresh histogram")),+ scale,+ total: AtomicU64::new(0),+ })+ });+ metrics::Histogram::from_arc(Arc::clone(hist))+ }+}