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.

mux-server: never mint a landing Space under a desktop; poll in accept

RoversXf2e6c444ffc7
diff --git a/wezterm-mux-server-impl/src/thinkterm_tree.rs b/wezterm-mux-server-impl/src/thinkterm_tree.rs
index 74529210..0cabef55 100644
--- a/wezterm-mux-server-impl/src/thinkterm_tree.rs
+++ b/wezterm-mux-server-impl/src/thinkterm_tree.rs
@@ -17,6 +17,7 @@ use codec::{
use mux::{Mux, MuxNotification};
use std::io::Write;
use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use uuid::Uuid;
@@ -119,14 +120,32 @@ fn workspace_name(project_id: &str, thread_id: &str) -> String {
format!("thinkterm:{project_id}:{thread_id}")
}
+/// Whether a desktop on this machine owns the tree. Set from the launch
+/// (`--no-initial-pane`, which only the desktop passes): its Spaces are
+/// published to this server, so an empty tree means the desktop has not
+/// spoken yet, not that there is nothing -- and minting a landing here
+/// would leave a second "Default" beside the desktop's for good.
+static HOSTED_BY_DESKTOP: AtomicBool = AtomicBool::new(false);
+
+pub fn set_hosted_by_desktop(hosted: bool) {
+ HOSTED_BY_DESKTOP.store(hosted, Ordering::SeqCst);
+}
+
+pub fn hosted_by_desktop() -> bool {
+ HOSTED_BY_DESKTOP.load(Ordering::SeqCst)
+}
+
/// Resolve a landing Thread against the authoritative tree. Missing
-/// Default/Home/main rows are created here, never reconstructed from a client
-/// cache. The operation is idempotent: once a usable Thread exists, repeated
-/// calls only return it.
+/// Default/Home/main rows are created here when `may_mint`, never
+/// reconstructed from a client cache; a server whose tree a desktop owns
+/// refuses instead, since the rows are the desktop's to publish. The
+/// operation is idempotent: once a usable Thread exists, repeated calls
+/// only return it.
fn ensure_landing_in_tree(
tree: &mut ThinkTermTree,
preferred_thread_id: Option<&str>,
-) -> (LandingRecord, bool) {
+ may_mint: bool,
+) -> Result<(LandingRecord, bool)> {
let mut changed = false;
// Archived projects never serve as a landing target: a fresh attach
// must not silently resurrect a project the user put away. When every
@@ -157,6 +176,9 @@ fn ensure_landing_in_tree(
let (project_index, thread_index) = match selected {
Some(selected) => selected,
+ None if !may_mint => anyhow::bail!(
+ "no thread to open: the desktop on this machine has not published its workspaces yet"
+ ),
None => {
if tree.spaces.is_empty() {
tree.spaces.push(TtSpace {
@@ -220,14 +242,14 @@ fn ensure_landing_in_tree(
changed = true;
}
- (
+ Ok((
LandingRecord {
thread_id: thread.id.clone(),
workspace,
project_path: project.path.clone(),
},
changed,
- )
+ ))
}
/// Ensure a server-owned landing Thread and persist it before any terminal is
@@ -238,7 +260,8 @@ pub fn ensure_landing(preferred_thread_id: Option<&str>) -> Result<LandingRecord
let (landing, changed) = {
let mut guard = TREE.lock().unwrap();
let mut candidate = guard.clone();
- let (landing, changed) = ensure_landing_in_tree(&mut candidate, preferred_thread_id);
+ let (landing, changed) =
+ ensure_landing_in_tree(&mut candidate, preferred_thread_id, !hosted_by_desktop())?;
if changed {
ensure_unique_thread_names(&mut candidate);
candidate.revision = candidate.revision.saturating_add(1);
@@ -466,7 +489,7 @@ mod test {
#[test]
fn landing_bootstraps_default_home_main_once() {
let mut tree = ThinkTermTree::default();
- let (first, changed) = ensure_landing_in_tree(&mut tree, None);
+ let (first, changed) = ensure_landing_in_tree(&mut tree, None, true).unwrap();
assert!(changed);
assert_eq!(tree.spaces.len(), 1);
assert_eq!(tree.spaces[0].name, "Default");
@@ -477,7 +500,7 @@ mod test {
assert_eq!(tree.projects[0].threads[0].name, "main");
assert_eq!(first.thread_id, tree.projects[0].threads[0].id);
- let (second, changed) = ensure_landing_in_tree(&mut tree, None);
+ let (second, changed) = ensure_landing_in_tree(&mut tree, None, true).unwrap();
assert!(!changed);
assert_eq!(second, first);
assert_eq!(tree.spaces.len(), 1);
@@ -485,10 +508,25 @@ mod test {
assert_eq!(tree.projects[0].threads.len(), 1);
}
+ /// A server the desktop hosts never invents rows: the desktop's are
+ /// coming, and a second "Default" beside them would stay for good.
+ #[test]
+ fn a_desktop_hosted_server_does_not_mint_a_landing() {
+ let mut tree = ThinkTermTree::default();
+ let err = ensure_landing_in_tree(&mut tree, None, false).unwrap_err();
+ assert!(err.to_string().contains("not published"));
+ assert!(tree.spaces.is_empty() && tree.projects.is_empty());
+ // With rows published, it lands in them as ever.
+ let mut tree = sample();
+ let (landing, changed) = ensure_landing_in_tree(&mut tree, None, false).unwrap();
+ assert!(!changed);
+ assert_eq!(landing.thread_id, "t1");
+ }
+
#[test]
fn landing_honors_an_existing_preferred_thread() {
let mut tree = sample();
- let (landing, changed) = ensure_landing_in_tree(&mut tree, Some("t1"));
+ let (landing, changed) = ensure_landing_in_tree(&mut tree, Some("t1"), true).unwrap();
assert!(!changed);
assert_eq!(landing.thread_id, "t1");
assert_eq!(landing.workspace, "thinkterm:p1:t1");
@@ -501,7 +539,7 @@ mod test {
revision: 9,
..ThinkTermTree::default()
};
- let (landing, changed) = ensure_landing_in_tree(&mut tree, Some("stale-thread"));
+ let (landing, changed) = ensure_landing_in_tree(&mut tree, Some("stale-thread"), true).unwrap();
assert!(changed);
assert_ne!(landing.thread_id, "stale-thread");
assert!(landing.thread_id.starts_with("thread-"));
@@ -541,7 +579,7 @@ mod test {
}
));
- let (landing, changed) = ensure_landing_in_tree(&mut tree, Some("t1"));
+ let (landing, changed) = ensure_landing_in_tree(&mut tree, Some("t1"), true).unwrap();
assert!(!changed);
assert_eq!(
landing.thread_id, "t2",
@@ -557,7 +595,7 @@ mod test {
.find(|project| project.id == "p2")
.unwrap()
.archived_at = Some(101);
- let (landing, changed) = ensure_landing_in_tree(&mut tree, None);
+ let (landing, changed) = ensure_landing_in_tree(&mut tree, None, true).unwrap();
assert!(changed);
let host = tree
.projects
diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rs
index 73428dfa..33f3b38d 100644
--- a/wezterm-mux-server/src/main.rs
+++ b/wezterm-mux-server/src/main.rs
@@ -279,6 +279,9 @@ fn run() -> anyhow::Result<()> {
))?;
let no_initial_pane = opts.no_initial_pane;
+ // Only the desktop launches the server this way; its tree is then the
+ // desktop's to seed, never this server's.
+ wezterm_mux_server_impl::thinkterm_tree::set_hosted_by_desktop(no_initial_pane);
let need_builder = !opts.prog.is_empty() || opts.cwd.is_some();
let cmd = if need_builder {
@@ -530,6 +533,9 @@ async fn async_run(
if let Err(err) = update_mux_domains_for_server(&config::configuration()) {
log::error!("Error updating mux domains: {:#}", err);
}
+ // The reloaded config may name a different color_scheme; every
+ // connection is told, so browsers repaint with it.
+ Mux::get().notify(mux::MuxNotification::DefaultPaletteChanged);
})
.detach();
true
diff --git a/wezterm-mux-server/src/web.rs b/wezterm-mux-server/src/web.rs
index d065a4f4..0dd75c0a 100644
--- a/wezterm-mux-server/src/web.rs
+++ b/wezterm-mux-server/src/web.rs
@@ -37,6 +37,8 @@ struct Listening {
/// The address `accept()` actually returned, not the configured
/// string: an unspecified bind has to be woken through a real address.
local: SocketAddr,
+ /// Set by the loop as it returns: the port is free from then on.
+ done: Option<Arc<AtomicBool>>,
}
/// The bind addresses currently accepting, in configuration order.
@@ -85,10 +87,18 @@ pub fn stop_web_listener(bind_address: &str) -> bool {
return false;
};
entry.stop.store(true, Ordering::SeqCst);
- // The knock is refused by the loop, which is the point: it is only
- // there to return from `accept`. A failure here means nobody was
- // blocked on it any more, which is equally fine.
+ // The loop waits in `poll` with a timeout and looks at the flag
+ // between waits (a `shutdown` on a listening socket is ENOTCONN on
+ // macOS and does not wake `accept`); the knock only shortens the wait
+ // where it lands on this listener rather than a more specific one.
let _ = TcpStream::connect_timeout(&wake_address(entry.local), Duration::from_secs(1));
+ if let Some(done) = entry.done.as_ref() {
+ // Bounded: the port is free once the loop has returned.
+ let waited = std::time::Instant::now();
+ while !done.load(Ordering::SeqCst) && waited.elapsed() < Duration::from_secs(2) {
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ }
log::error!("stopped listening for web clients on {bind_address}");
true
}
@@ -239,6 +249,7 @@ pub fn spawn_web_listener(server: &WebServer) -> anyhow::Result<()> {
);
let stop = Arc::new(AtomicBool::new(false));
+ let done = Arc::new(AtomicBool::new(false));
// Registered before the thread starts, so a stop that arrives in the
// same breath as the start still finds it.
LISTENERS.lock().map_or_else(|e| e.into_inner(), |g| g).insert(
@@ -247,12 +258,13 @@ pub fn spawn_web_listener(server: &WebServer) -> anyhow::Result<()> {
effective: effective.clone(),
stop: Arc::clone(&stop),
local,
+ done: Some(Arc::clone(&done)),
},
);
let bind_address = server.bind_address.clone();
match std::thread::Builder::new()
.name(format!("web-accept-{}", server.bind_address))
- .spawn(move || accept_loop(listener, acceptor, site, stop))
+ .spawn(move || accept_loop(listener, acceptor, site, stop, done))
{
Ok(_) => {
// The other half of `disconnect_all`, which stops admissions
@@ -279,22 +291,61 @@ pub fn spawn_web_listener(server: &WebServer) -> anyhow::Result<()> {
/// peer costs nothing; an exhausted descriptor table would otherwise spin.
const ACCEPT_RETRY: Duration = Duration::from_millis(100);
+/// How long the loop waits for a connection before it looks at the stop
+/// flag again: a stop is seen within this, knock or no knock.
+const ACCEPT_WAIT: Duration = Duration::from_millis(250);
+
+/// Wait for a connection to be ready, `ACCEPT_WAIT` at most. Blocking
+/// `accept` cannot be woken from another thread on every platform (a
+/// `shutdown` of a listening socket is ENOTCONN on macOS), so the wait
+/// is a `poll` and the accept never blocks.
+fn connection_ready(listener: &TcpListener) -> bool {
+ #[cfg(unix)]
+ {
+ use std::os::unix::io::AsRawFd;
+ let mut fds = [libc::pollfd { fd: listener.as_raw_fd(), events: libc::POLLIN, revents: 0 }];
+ let n = unsafe { libc::poll(fds.as_mut_ptr(), 1, ACCEPT_WAIT.as_millis() as libc::c_int) };
+ n > 0
+ }
+ #[cfg(not(unix))]
+ {
+ std::thread::sleep(Duration::from_millis(20));
+ true
+ }
+}
+
fn accept_loop(
listener: TcpListener,
acceptor: Option<SslAcceptor>,
site: Arc<WebSite>,
stop: Arc<AtomicBool>,
+ done: Arc<AtomicBool>,
) {
- for stream in listener.incoming() {
+ let _ = listener.set_nonblocking(true);
+ loop {
// Checked before the connection is looked at, so the knock that
// woke us is dropped rather than served.
if stop.load(Ordering::SeqCst) {
log::info!("web accept loop for {} is done", site.describe);
+ done.store(true, Ordering::SeqCst);
return;
}
- let stream = match stream {
- Ok(stream) => stream,
+ if !connection_ready(&listener) {
+ continue;
+ }
+ let stream = match listener.accept() {
+ // Blocking again for the handshake; `Async::new` sets its own.
+ Ok((stream, _)) => {
+ let _ = stream.set_nonblocking(false);
+ stream
+ }
+ Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => continue,
Err(err) => {
+ if stop.load(Ordering::SeqCst) {
+ log::info!("web accept loop for {} is done", site.describe);
+ done.store(true, Ordering::SeqCst);
+ return;
+ }
// One bad client (or a moment without descriptors) is one
// refused connection, not the end of the listener.
log::error!("web accept failed on {}: {err}", site.describe);