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.

wezterm-client: the local session host closes panes, restores layouts and reconnects without the lease gate

RoversX704656f72e4c
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index 3077b9a2..e1e8380d 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -1421,6 +1421,9 @@ impl Reconnectable {
let child = cmd
.spawn()
.with_context(|| format!("while spawning {:?}", cmd))?;
+ if unix_dom.local_session_host {
+ crate::local_update::note_local_session_host_started();
+ }
std::thread::spawn(move || match child.wait_with_output() {
Ok(out) => {
if let Ok(stdout) = std::str::from_utf8(&out.stdout) {
@@ -1921,9 +1924,27 @@ impl Client {
// attempt would only ask again.
suspend = Some("authentication was declined".to_string());
} else if outage_started.elapsed() >= GIVE_UP_AFTER {
- suspend = Some(format!(
- "unable to reconnect for {GIVE_UP_AFTER:?}"
- ));
+ if reconnectable.is_local_session_host() {
+ // The local session host keeps
+ // trying at the capped interval:
+ // its Space is a local one with
+ // no Reconnect row, so a parked
+ // retry could never be resumed.
+ // And a server that kept dying
+ // at once gets started again
+ // after this long; nothing else
+ // would ever try.
+ log::warn!(
+ "the session server has been unreachable for \
+ {GIVE_UP_AFTER:?}; starting it again if nothing answers"
+ );
+ short_sessions = 0;
+ outage_started = std::time::Instant::now();
+ } else {
+ suspend = Some(format!(
+ "unable to reconnect for {GIVE_UP_AFTER:?}"
+ ));
+ }
}
}
}
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index c4d4c74e..3f5341e3 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -855,6 +855,10 @@ pub struct ClientInner {
/// cold-start fetch ran before the panes existed and the push path
/// had nothing to deliver to — each side assumed the other covered it.
remote_agent_statuses: Mutex<HashMap<PaneId, thinkterm_proto::AgentStatus>>,
+ /// Remote panes whose KillPane is on its way. A resync that lands in
+ /// between must not mirror them back: the local mirror is gone already,
+ /// and a fresh one would get a window of its own.
+ pending_kills: Mutex<HashSet<PaneId>>,
/// Authoritative per-remote-tab viewport ownership pushed by the server.
remote_viewports: Mutex<HashMap<TabId, codec::ClientViewportState>>,
/// Connection-wide A/B mode and exclusive handoff owner.
@@ -1448,6 +1452,13 @@ impl ClientInner {
&self,
remote_tab_id: TabId,
) -> anyhow::Result<bool> {
+ // The local session host's terminals are this machine's: the lease
+ // decides who paints, not whether a layout may be restored into it.
+ // Gating here refused the splits of a saved layout while the first
+ // viewport was still being settled, and the thread stayed unbuilt.
+ if self.client.is_local_session_host() {
+ return Ok(true);
+ }
if self.remote_frontend_gate().obscures_terminal() {
return Ok(false);
}
@@ -1456,14 +1467,7 @@ impl ClientInner {
};
match access.mode {
codec::FrontendAccessMode::Handoff => {
- // No owner: the server decides (the first screen, or the
- // one that was driving and came back, is let through and
- // becomes the owner on its first viewport; anyone else is
- // refused there). Refusing here would refuse the splits of
- // a layout restored before anything was painted.
- return Ok(
- access.owner.is_none() || self.remote_owner_is_self(access.owner.as_ref())
- );
+ return Ok(self.remote_owner_is_self(access.owner.as_ref()));
}
codec::FrontendAccessMode::TmuxLatest => {}
}
@@ -1588,6 +1592,7 @@ impl ClientInner {
remote_to_local_tab: Mutex::new(HashMap::new()),
remote_to_local_pane: Mutex::new(HashMap::new()),
remote_agent_statuses: Mutex::new(HashMap::new()),
+ pending_kills: Mutex::new(HashSet::new()),
remote_viewports: Mutex::new(HashMap::new()),
remote_access: Mutex::new(None),
reported_viewports: Mutex::new(HashMap::new()),
@@ -1607,6 +1612,41 @@ impl ClientInner {
}
}
+impl ClientInner {
+ pub(crate) fn note_pending_kill(&self, remote_pane_id: PaneId) {
+ self.pending_kills.lock().unwrap().insert(remote_pane_id);
+ }
+
+ pub(crate) fn forget_pending_kill(&self, remote_pane_id: PaneId) {
+ self.pending_kills.lock().unwrap().remove(&remote_pane_id);
+ }
+
+ /// Whether every pane of this tab is one we asked the server to kill.
+ fn tab_is_being_killed(&self, tabroot: &mux::tab::PaneNode) -> bool {
+ let mut pane_ids = Vec::new();
+ collect_pane_ids(tabroot, &mut pane_ids);
+ if pane_ids.is_empty() {
+ return false;
+ }
+ let pending = self.pending_kills.lock().unwrap();
+ pane_ids.iter().all(|pane_id| pending.contains(pane_id))
+ }
+}
+
+fn collect_pane_ids(node: &mux::tab::PaneNode, out: &mut Vec<PaneId>) {
+ match node {
+ mux::tab::PaneNode::Empty => {}
+ mux::tab::PaneNode::Split { left, right, .. } => {
+ collect_pane_ids(left, out);
+ collect_pane_ids(right, out);
+ }
+ mux::tab::PaneNode::Leaf(entry) => out.push(entry.pane_id),
+ mux::tab::PaneNode::Stack(stack) => {
+ out.extend(stack.panes.iter().map(|entry| entry.pane_id))
+ }
+ }
+}
+
impl ClientInner {
fn begin_structure_mutation(self: &Arc<Self>) -> StructureMutationGuard {
self.mutations_in_flight
@@ -2098,9 +2138,9 @@ impl ClientDomain {
.unwrap_or_else(CommandBuilder::new_default_prog);
match mux::default_prog::shell_application(&argv, cfg!(windows)) {
Some(mux::default_prog::ShellApplication::ShellEnv(shell)) => {
- if cmd.get_env("SHELL").is_none() {
- cmd.env("SHELL", shell);
- }
+ // The builder's base environment already carries the login
+ // SHELL; the choice replaces it.
+ cmd.env("SHELL", shell);
}
Some(mux::default_prog::ShellApplication::Argv(argv)) => {
*cmd.get_argv_mut() = argv.into_iter().map(Into::into).collect();
@@ -3510,6 +3550,13 @@ impl ClientDomain {
};
if let Some((remote_window_id, remote_tab_id)) = tabroot.window_and_tab_ids() {
+ if inner.tab_is_being_killed(&tabroot) {
+ log::debug!(
+ "domain {}: remote tab {remote_tab_id} is being killed; not mirroring it",
+ inner.local_domain_id
+ );
+ continue;
+ }
let tab;
// For a tab we already track, the locally-held size (driven
// by the GUI window geometry) is authoritative; the wire
diff --git a/wezterm-client/src/local_update.rs b/wezterm-client/src/local_update.rs
index 1ff55d19..9045db18 100644
--- a/wezterm-client/src/local_update.rs
+++ b/wezterm-client/src/local_update.rs
@@ -14,6 +14,20 @@ use mux::connui::ConnectionUI;
use std::io::Read;
use std::process::{Command, Stdio};
+/// Whether this process started (or took over) the local session server,
+/// as opposed to finding one already running. The GUI only ever stops a
+/// server it started itself.
+static STARTED_LOCAL_SESSION_HOST: std::sync::atomic::AtomicBool =
+ std::sync::atomic::AtomicBool::new(false);
+
+pub fn note_local_session_host_started() {
+ STARTED_LOCAL_SESSION_HOST.store(true, std::sync::atomic::Ordering::Release);
+}
+
+pub fn local_session_host_started_by_us() -> bool {
+ STARTED_LOCAL_SESSION_HOST.load(std::sync::atomic::Ordering::Acquire)
+}
+
/// Run the server this client ships with as a successor of the one
/// listening on `unix`'s socket. `Ok(true)` when it now serves; `Ok(false)`
/// when the running server refused or the takeover failed (its output was
@@ -80,6 +94,7 @@ pub fn take_over_local_server(unix: &UnixDomain, ui: &ConnectionUI) -> anyhow::R
let _ = thread.join();
}
if status.success() {
+ note_local_session_host_started();
ui.output_str("Handed over; reconnecting.\n");
Ok(true)
} else {
diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rs
index e9438b55..73849e2a 100644
--- a/wezterm-client/src/pane/clientpane.rs
+++ b/wezterm-client/src/pane/clientpane.rs
@@ -1193,7 +1193,13 @@ impl Pane for ClientPane {
*ignore = false;
return;
}
- if self.client.remote_tab_input_is_blocked() {
+ // The local session host's terminals are this machine's: a kill is
+ // not held back by the frontend lease, which is still being settled
+ // for the first moments of every launch. Dropping the kill there
+ // left the pane running in the server while its mirror was gone,
+ // and the next resync mirrored it back as a new window.
+ let host = self.client.client.is_local_session_host();
+ if !host && self.client.remote_tab_input_is_blocked() {
return;
}
let client = Arc::clone(&self.client);
@@ -1219,16 +1225,30 @@ impl Pane for ClientPane {
}
if send_kill {
+ client.note_pending_kill(remote_pane_id);
promise::spawn::spawn(async move {
- if client.prepare_remote_tab_input(remote_tab_id).await? {
- client
- .client
- .kill_pane(KillPane {
- pane_id: remote_pane_id,
- })
- .await?;
+ let result = async {
+ if host || client.prepare_remote_tab_input(remote_tab_id).await? {
+ client
+ .client
+ .kill_pane(KillPane {
+ pane_id: remote_pane_id,
+ })
+ .await?;
+ }
+ Ok::<(), anyhow::Error>(())
}
- Ok::<(), anyhow::Error>(())
+ .await;
+ client.forget_pending_kill(remote_pane_id);
+ if let Err(err) = &result {
+ if host {
+ log::warn!(
+ "the session server refused to close pane {remote_pane_id}: {err:#}; \
+ it stays running and comes back at the next resync"
+ );
+ }
+ }
+ result
})
.detach();
}
@@ -2228,6 +2248,7 @@ mod palette_delivery_tests {
};
queue.push(delta(1, vec![3, 4], vec![]));
queue.push(delta(2, vec![4], vec![10..12]));
+
queue.push(delta(3, vec![7], vec![]));
let (_, carried) = queue.take().unwrap();
let carried = carried.expect("two pushes wait behind the first");
@@ -2240,7 +2261,6 @@ mod palette_delivery_tests {
);
assert!(!carried.contains(12), "ranges are half-open");
}
-
}
#[cfg(test)]