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
agent status: sync statuses between mux server and client
RoversX48bc27d9530d
diff --git a/wezterm-client/Cargo.toml b/wezterm-client/Cargo.tomlindex c0508cd1..c9869523 100644--- a/wezterm-client/Cargo.toml+++ b/wezterm-client/Cargo.toml@@ -31,6 +31,7 @@ ratelim.workspace = truesmol.workspace = truetermwiz.workspace = truetextwrap.workspace = true+thinkterm-proto.workspace = truethiserror.workspace = trueumask.workspace = trueurl.workspace = truediff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rsindex 230ca289..77c1aba2 100644--- a/wezterm-client/src/client.rs+++ b/wezterm-client/src/client.rs@@ -426,6 +426,15 @@ async fn process_unilateral_inner_async(let local_pane_id = match client_domain.remote_to_local_pane_id(pane_id) {Some(p) => p,None => {+ // Not for agent status though: the server publishes those for+ // every pane it owns (other workspaces included), and around a+ // pane's removal the eviction push can land on either side of+ // our own PaneRemoved handling — both orders are harmless.+ // Neither implies a topology change worth a full resync; the+ // cold-start fetch covers late mapping.+ if matches!(decoded.pdu, Pdu::AgentStatusChanged(_)) {+ return Ok(());+ }log::debug!("got {decoded:?}, pane not found locally, resync");client_domain.resync().await?;if client_domain.connection_generation() != Some(connection_generation) {@@ -2177,6 +2186,11 @@ impl Client {rpc!(ping, Ping = (), Pong);rpc!(list_panes, ListPanes = (), ListPanesResponse);+ rpc!(+ get_agent_statuses,+ GetAgentStatuses = (),+ GetAgentStatusesResponse+ );rpc!(spawn_v2, SpawnV2, SpawnResponse);rpc!(split_pane, SplitPane, SpawnResponse);rpc!(spawn_pane_in_stack, SpawnPaneInStack, SpawnResponse);diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rsindex fa1642f4..a829d963 100644--- a/wezterm-client/src/domain.rs+++ b/wezterm-client/src/domain.rs@@ -1973,6 +1973,14 @@ impl ClientDomain {Mux::get().prune_dead_windows();}+ // Before the server-replaced early return below: both reconnect+ // shapes must reconcile agent statuses, or everything that changed+ // while disconnected (agent finished, exited, started) stays wrong+ // until the pane next changes state.+ if let Err(err) = client.fetch_agent_statuses().await {+ log::warn!("failed to fetch agent statuses on reattach: {err:#}");+ }+if server_replaced {let active_remote_tabs = replacement_session.as_ref()@@ -2100,6 +2108,18 @@ impl ClientDomain {return Ok(());}Self::process_pane_list(inner, panes, None, false, None)?;+ // Catch-up only: steady-state updates arrive as pushed+ // AgentStatusChanged PDUs. With detection off on this side+ // there is no consumer for the answer, so skip the RPC --+ // it walks the server's whole pane list on its main thread.+ if mux::agent_status::detection_enabled() {+ if let Err(err) = self.fetch_agent_statuses().await {+ log::warn!(+ "failed to refresh agent statuses from {}: {err:#}",+ self.config.name()+ );+ }+ }}Ok(())}@@ -2125,6 +2145,59 @@ impl ClientDomain {Ok(tree)}+ /// Reconcile the mirrored agent statuses with the server's. Late-+ /// attaching clients would otherwise only learn of *future* status+ /// changes; this closes the cold-start gap on attach, resync and+ /// reconnect. The snapshot is authoritative in both directions: a+ /// mirror the response does not mention is cleared, so an agent that+ /// exited while this client was disconnected does not survive as a+ /// phantom.+ ///+ /// Ordering caveat: this snapshot can interleave with live pushes in+ /// either direction and briefly apply an older value. It converges+ /// because every server-side mutation of a published status enqueues+ /// its own trailing AgentStatusChanged on the same dispatch channel+ /// (the one deliberate exception, the PaneRemoved eviction, is always+ /// followed by the PaneRemoved PDU itself). Any future silent registry+ /// mutation without a paired PDU would make a stale snapshot permanent.+ pub async fn fetch_agent_statuses(&self) -> anyhow::Result<()> {+ let inner = self+ .inner()+ .ok_or_else(|| anyhow!("domain is not attached"))?;+ let response = inner.client.get_agent_statuses().await?;+ let mut desired: std::collections::HashMap<PaneId, thinkterm_proto::AgentStatus> =+ response+ .statuses+ .into_iter()+ .filter_map(|entry| {+ inner+ .remote_to_local_pane_id(entry.pane_id)+ .map(|local| (local, entry.status))+ })+ .collect();+ let mux = Mux::get();+ let mut changed = Vec::new();+ for pane in mux.iter_panes() {+ if pane.domain_id() != self.local_domain_id {+ continue;+ }+ let Some(client_pane) = pane.downcast_ref::<ClientPane>() else {+ continue;+ };+ let target = desired.remove(&pane.pane_id());+ if pane.agent_status() != target {+ client_pane.set_agent_status(target);+ changed.push(pane.pane_id());+ }+ }+ // This runs in an ordinary spawned task, never inside a Mux+ // subscriber callback, so notifying here is safe.+ for pane_id in changed {+ Mux::notify_from_any_thread(MuxNotification::AgentStatusChanged(pane_id));+ }+ Ok(())+ }+/// Pull the server's tree and hand it to the sink. Used on attach and/// whenever a client wants to force a resync of the sidebar structure.pub async fn fetch_thinkterm_tree(&self) -> anyhow::Result<()> {@@ -3977,6 +4050,16 @@ impl ClientDomain {);}+ // Same failure policy: agent statuses are a nicety, not worth+ // failing an attach over; the push path catches us up on the+ // next state change regardless.+ if let Err(err) = self.fetch_agent_statuses().await {+ log::warn!(+ "failed to fetch agent statuses from {}: {err:#}",+ self.config.name()+ );+ }+if let Some(inner) = self.inner() {inner.client.mark_ready();}diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rsindex 929bfed9..2246f0f1 100644--- a/wezterm-client/src/pane/clientpane.rs+++ b/wezterm-client/src/pane/clientpane.rs@@ -216,9 +216,17 @@ pub struct ClientPane {config: Mutex<Option<Arc<dyn TerminalConfiguration>>>,unseen_output: Mutex<bool>,progress: Mutex<Progress>,+ agent_status: Mutex<Option<thinkterm_proto::AgentStatus>>,}impl ClientPane {+ /// Store a status delivered outside the unilateral push path (the+ /// cold-start fetch on attach/resync). Quiet: the caller decides+ /// whether a repaint is warranted.+ pub fn set_agent_status(&self, status: Option<thinkterm_proto::AgentStatus>) {+ *self.agent_status.lock() = status;+ }+/// Ask the (single) sender worker to bring the server to `palette`./// Starts the worker when none is running; a running worker picks the/// new target up by itself. Re-sends of identical palettes are@@ -398,6 +406,7 @@ impl ClientPane {user_vars: Mutex::new(HashMap::new()),config: Mutex::new(None),progress: Mutex::new(Progress::default()),+ agent_status: Mutex::new(None),}}@@ -491,9 +500,35 @@ impl ClientPane {alert,});}+ Pdu::AgentStatusChanged(codec::AgentStatusChanged { status, .. }) => {+ // Read-at-send-time coalescing means a backlog of queued+ // notifications all carry the same current value; only a+ // real change is worth a re-notify (each one repaints and+ // re-scans thread work downstream).+ let changed = {+ let mut slot = self.agent_status.lock();+ if *slot == status {+ false+ } else {+ *slot = status;+ true+ }+ };+ if changed {+ // Re-notify locally: repaints this GUI, and when this+ // process is itself a mux server for further clients,+ // its dispatch forwards the status one hop on (same+ // reason the Progress alert above re-notifies).+ Mux::get().notify(MuxNotification::AgentStatusChanged(self.local_pane_id));+ }+ }Pdu::PaneRemoved(PaneRemoved { pane_id }) => {log::trace!("remote pane {} has been removed", pane_id);self.renderable.lock().inner.borrow_mut().dead = true;+ // The prune below can be deferred (activity in flight, or+ // the windows lock contended); the dead mirror must not+ // keep reporting an agent to the panel meanwhile.+ *self.agent_status.lock() = None;let mux = Mux::get();mux.prune_dead_windows();@@ -834,6 +869,10 @@ impl Pane for ClientPane {self.progress.lock().clone()}+ fn agent_status(&self) -> Option<thinkterm_proto::AgentStatus> {+ self.agent_status.lock().clone()+ }+fn send_paste(&self, text: &str) -> anyhow::Result<()> {if self.client.remote_tab_input_is_blocked() {return Ok(());diff --git a/wezterm-mux-server-impl/src/dispatch.rs b/wezterm-mux-server-impl/src/dispatch.rsindex 59c9b6d4..2899a939 100644--- a/wezterm-mux-server-impl/src/dispatch.rs+++ b/wezterm-mux-server-impl/src/dispatch.rs@@ -112,6 +112,15 @@ wherehandler.schedule_pane_push(pane_id);}Ok(Item::Notif(MuxNotification::PaneAdded(_pane_id))) => {}+ Ok(Item::Notif(MuxNotification::AgentStatusChanged(pane_id))) => {+ // Read the status at send time so the payload is always the+ // freshest classification, never a queued stale value.+ let status = Mux::get().get_pane(pane_id).and_then(|p| p.agent_status());+ Pdu::AgentStatusChanged(codec::AgentStatusChanged { pane_id, status })+ .encode_async(&mut stream, 0)+ .await?;+ stream.flush().await.context("flushing PDU to client")?;+ }Ok(Item::Notif(MuxNotification::PaneRemoved(pane_id))) => {Pdu::PaneRemoved(codec::PaneRemoved { pane_id }).encode_async(&mut stream, 0)diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rsindex f663a131..4f5b26c1 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -649,6 +649,70 @@ impl SessionHandler {}).detach();}+ Pdu::GetAgentStatuses(GetAgentStatuses {}) => {+ spawn_into_main_thread(async move {+ catch(+ move || {+ let mux = Mux::get();+ // The flat pane list first: this query runs on+ // every client resync, and most rounds find no+ // agents at all -- the window/tab walk below+ // exists only to name their workspaces, so it+ // must not run before we know any are needed.+ // iter_panes + agent_status() rather than the+ // detector registry: a chained mux correctly+ // reports what it mirrors as well as what it+ // detected itself.+ let mut agents = vec![];+ for pane in mux.iter_panes() {+ let Some(status) = pane.agent_status() else {+ continue;+ };+ agents.push((pane.pane_id(), status, pane.get_title()));+ }+ if agents.is_empty() {+ return Ok(Pdu::GetAgentStatusesResponse(+ GetAgentStatusesResponse { statuses: vec![] },+ ));+ }+ // One pass over the window/tab topology:+ // resolve_pane_id per agent pane would rescan+ // every tab per entry.+ let mut workspace_by_pane =+ std::collections::HashMap::new();+ for window_id in mux.iter_windows() {+ let Some(window) = mux.get_window(window_id) else {+ continue;+ };+ let workspace = window.get_workspace().to_string();+ for tab in window.iter() {+ for pane in tab.iter_all_panes() {+ workspace_by_pane+ .insert(pane.pane_id(), workspace.clone());+ }+ }+ }+ let statuses = agents+ .into_iter()+ .map(|(pane_id, status, title)| AgentStatusEntry {+ pane_id,+ status,+ title,+ workspace: workspace_by_pane+ .get(&pane_id)+ .cloned()+ .unwrap_or_default(),+ })+ .collect();+ Ok(Pdu::GetAgentStatusesResponse(GetAgentStatusesResponse {+ statuses,+ }))+ },+ send_response,+ )+ })+ .detach();+ }Pdu::GetClientList(GetClientList) => {spawn_into_main_thread(async move {catch(@@ -1588,6 +1652,8 @@ impl SessionHandler {Pdu::Invalid { .. } => send_response(Err(anyhow!("invalid PDU {:?}", decoded.pdu))),Pdu::Pong { .. }+ | Pdu::AgentStatusChanged { .. }+ | Pdu::GetAgentStatusesResponse { .. }| Pdu::ListPanesResponse { .. }| Pdu::SetApplicationPalette { .. }| Pdu::SetClipboard { .. }diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rsindex f16c70cf..2dbacda4 100644--- a/wezterm-mux-server/src/main.rs+++ b/wezterm-mux-server/src/main.rs@@ -270,6 +270,9 @@ async fn async_run(cmd: Option<CommandBuilder>) -> anyhow::Result<()> {let mux = Mux::get();let config = config::configuration();+ // async_run is entered through SimpleExecutor, so promise's schedulers+ // are available before agent detection starts its safety tick.+ mux::agent_status::initialize_mux(&mux);update_mux_domains_for_server(&config)?;let _config_subscription = config::subscribe_to_config_reload(move || {promise::spawn::spawn_into_main_thread(async move {