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.

feat(client): mirror remote panes' foreground programs

RoversX67661bb733e5
diff --git a/thinkterm-session/src/host.rs b/thinkterm-session/src/host.rs
index cfff80a8..9e485861 100644
--- a/thinkterm-session/src/host.rs
+++ b/thinkterm-session/src/host.rs
@@ -119,6 +119,8 @@ pub trait SessionEvents {
fn alert(&self, pane: HostPaneId, alert: Alert);
/// The agent status the server tracks for the pane changed.
fn agent_status_changed(&self, pane: HostPaneId);
+ /// The program the server sees leading the pane's terminal changed.
+ fn foreground_program_changed(&self, pane: HostPaneId);
/// The server removed the pane; its mirror is dead.
fn pane_removed(&self, pane: HostPaneId);
/// The server moved focus to the pane.
diff --git a/thinkterm-session/src/pane.rs b/thinkterm-session/src/pane.rs
index 3aad8a48..4cedc66b 100644
--- a/thinkterm-session/src/pane.rs
+++ b/thinkterm-session/src/pane.rs
@@ -1368,6 +1368,7 @@ mod tests {
}
fn alert(&self, _pane: HostPaneId, _alert: wezterm_term::Alert) {}
fn agent_status_changed(&self, _pane: HostPaneId) {}
+ fn foreground_program_changed(&self, _pane: HostPaneId) {}
fn pane_removed(&self, _pane: HostPaneId) {}
fn pane_focused(&self, _pane: HostPaneId) {}
fn input_recorded(&self) {}
diff --git a/thinkterm-web/src/host.rs b/thinkterm-web/src/host.rs
index e6ca23ce..0c33aa70 100644
--- a/thinkterm-web/src/host.rs
+++ b/thinkterm-web/src/host.rs
@@ -74,6 +74,8 @@ impl SessionEvents for Events {
}
}
fn agent_status_changed(&self, _pane: HostPaneId) {}
+ // The page draws no tab icons yet.
+ fn foreground_program_changed(&self, _pane: HostPaneId) {}
fn pane_removed(&self, pane: HostPaneId) {
self.mark(pane);
}
diff --git a/wasm-probe/src/lib.rs b/wasm-probe/src/lib.rs
index bb397f58..47927592 100644
--- a/wasm-probe/src/lib.rs
+++ b/wasm-probe/src/lib.rs
@@ -222,6 +222,7 @@ mod session_probe {
}
fn alert(&self, _pane: HostPaneId, _alert: wezterm_term::Alert) {}
fn agent_status_changed(&self, _pane: HostPaneId) {}
+ fn foreground_program_changed(&self, _pane: HostPaneId) {}
fn pane_removed(&self, _pane: HostPaneId) {}
fn pane_focused(&self, _pane: HostPaneId) {}
fn input_recorded(&self) {}
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index c870d7b3..3984e435 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -326,12 +326,17 @@ async fn process_unilateral_inner_async(
// never publishes an eviction status (its PaneRemoved handler is
// evict-only), and a retained entry would seed a *reused* remote pane
// id with the dead pane's agent.
+ // Foreground programs are retained the same way, for the same reason.
match &decoded.pdu {
Pdu::AgentStatusChanged(codec::AgentStatusChanged { pane_id, status }) => {
client_domain.record_remote_agent_status(*pane_id, status.clone());
}
+ Pdu::ForegroundProgramChanged(codec::ForegroundProgramChanged { pane_id, program }) => {
+ client_domain.record_remote_foreground_program(*pane_id, program.clone());
+ }
Pdu::PaneRemoved(_) => {
client_domain.record_remote_agent_status(pane_id, None);
+ client_domain.record_remote_foreground_program(pane_id, None);
}
_ => {}
}
@@ -342,12 +347,16 @@ 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, so unmapped
- // is routine and implies no topology change worth a resync.
- // The status was recorded into the snapshot above; the mirror
- // seeds from it whenever it materializes.
- if matches!(decoded.pdu, Pdu::AgentStatusChanged(_)) {
+ // Not for agent status or foreground programs though: the
+ // server publishes those for every pane it owns, other
+ // workspaces included, so unmapped is routine and implies no
+ // topology change worth a resync. The value was recorded into
+ // the snapshot above; the mirror seeds from it whenever it
+ // materializes.
+ if matches!(
+ decoded.pdu,
+ Pdu::AgentStatusChanged(_) | Pdu::ForegroundProgramChanged(_)
+ ) {
return Ok(());
}
log::debug!("got {decoded:?}, pane not found locally, resync");
@@ -2376,6 +2385,11 @@ impl Client {
GetAgentStatuses = (),
GetAgentStatusesResponse
);
+ rpc!(
+ get_foreground_programs,
+ GetForegroundPrograms = (),
+ GetForegroundProgramsResponse
+ );
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.rs
index 331e22ff..c81fce14 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -855,6 +855,8 @@ 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>>,
+ /// The same, for the program leading each remote pane's terminal.
+ remote_foreground_programs: Mutex<HashMap<PaneId, thinkterm_proto::ForegroundProgram>>,
/// 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.
@@ -1142,6 +1144,36 @@ impl ClientInner {
.cloned()
}
+ /// Record one foreground program into the remote-keyed snapshot, on
+ /// the same terms as [`Self::record_remote_agent_status`].
+ pub fn record_remote_foreground_program(
+ &self,
+ remote_pane_id: PaneId,
+ program: Option<thinkterm_proto::ForegroundProgram>,
+ ) {
+ let mut map = self.remote_foreground_programs.lock().unwrap();
+ match program.filter(|program| program.within_budget()) {
+ Some(program) => {
+ map.insert(remote_pane_id, program);
+ }
+ None => {
+ map.remove(&remote_pane_id);
+ }
+ }
+ }
+
+ /// The last foreground program the server reported for a remote pane.
+ pub fn remote_foreground_program(
+ &self,
+ remote_pane_id: PaneId,
+ ) -> Option<thinkterm_proto::ForegroundProgram> {
+ self.remote_foreground_programs
+ .lock()
+ .unwrap()
+ .get(&remote_pane_id)
+ .cloned()
+ }
+
pub fn remote_to_local_pane_id(&self, remote_pane_id: PaneId) -> Option<TabId> {
let mut pane_map = self.remote_to_local_pane.lock().unwrap();
let remote_server_id = self.client.remote_server_id();
@@ -1313,6 +1345,7 @@ impl ClientInner {
self.remote_to_local_stack.lock().unwrap().clear();
self.reported_viewports.lock().unwrap().clear();
self.remote_agent_statuses.lock().unwrap().clear();
+ self.remote_foreground_programs.lock().unwrap().clear();
}
/// Kill every local mirror of this domain: the terminals they showed
@@ -1385,8 +1418,10 @@ impl ClientInner {
// The replacement server allocates pane ids from scratch, so the
// retained statuses describe panes that no longer exist. Left in
// place they would seed the replacement's mirrors (created before
- // the post-replacement fetch) with the dead server's agents.
+ // the post-replacement fetch) with the dead server's agents, and
+ // its programs.
self.remote_agent_statuses.lock().unwrap().clear();
+ self.remote_foreground_programs.lock().unwrap().clear();
mirrors
}
@@ -1672,6 +1707,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()),
+ remote_foreground_programs: Mutex::new(HashMap::new()),
pending_kills: Mutex::new(HashSet::new()),
remote_viewports: Mutex::new(HashMap::new()),
remote_access: Mutex::new(None),
@@ -2469,6 +2505,17 @@ impl ClientDomain {
}
}
+ /// See [`ClientInner::record_remote_foreground_program`].
+ pub fn record_remote_foreground_program(
+ &self,
+ remote_pane_id: PaneId,
+ program: Option<thinkterm_proto::ForegroundProgram>,
+ ) {
+ if let Some(inner) = self.inner() {
+ inner.record_remote_foreground_program(remote_pane_id, program);
+ }
+ }
+
pub fn remote_to_local_window_id(&self, remote_window_id: WindowId) -> Option<WindowId> {
let inner = self.inner()?;
inner.remote_to_local_window(remote_window_id)
@@ -2945,6 +2992,9 @@ impl ClientDomain {
if let Err(err) = client.fetch_agent_statuses().await {
log::warn!("failed to fetch agent statuses on reattach: {err:#}");
}
+ if let Err(err) = client.fetch_foreground_programs().await {
+ log::warn!("failed to fetch foreground programs on reattach: {err:#}");
+ }
if server_replaced && !host_replaced {
let active_remote_tabs = replacement_session
@@ -3275,6 +3325,15 @@ impl ClientDomain {
);
}
}
+ // The same for tab icons, on their own switch.
+ if mux::foreground_program::enabled() {
+ if let Err(err) = self.fetch_foreground_programs().await {
+ log::warn!(
+ "failed to refresh foreground programs from {}: {err:#}",
+ self.config.name()
+ );
+ }
+ }
return Ok(ResyncOutcome::Applied);
}
Ok(ResyncOutcome::NoClient)
@@ -3363,6 +3422,54 @@ impl ClientDomain {
Ok(())
}
+ /// Reconcile the mirrored foreground programs with the server's, on the
+ /// same terms as [`Self::fetch_agent_statuses`]: the snapshot is kept by
+ /// remote pane id for mirrors not yet made, and is authoritative both
+ /// ways for the ones that exist. It converges against live pushes for
+ /// the same reason: every change the server publishes is followed by
+ /// its own ForegroundProgramChanged on the same channel.
+ pub async fn fetch_foreground_programs(&self) -> anyhow::Result<()> {
+ let inner = self
+ .inner()
+ .ok_or_else(|| anyhow!("domain is not attached"))?;
+ let response = inner.client.get_foreground_programs().await?;
+ let remote: std::collections::HashMap<PaneId, thinkterm_proto::ForegroundProgram> =
+ response
+ .programs
+ .into_iter()
+ .map(|entry| (entry.pane_id, entry.program))
+ .collect();
+ *inner.remote_foreground_programs.lock().unwrap() = remote.clone();
+ let mut desired: std::collections::HashMap<PaneId, thinkterm_proto::ForegroundProgram> =
+ remote
+ .into_iter()
+ .filter_map(|(remote_pane, program)| {
+ inner
+ .remote_to_local_pane_id(remote_pane)
+ .map(|local| (local, program))
+ })
+ .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.foreground_program() != target {
+ client_pane.set_foreground_program(target);
+ changed.push(pane.pane_id());
+ }
+ }
+ for pane_id in changed {
+ Mux::notify_from_any_thread(MuxNotification::ForegroundProgramChanged(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<()> {
@@ -5924,6 +6031,12 @@ impl ClientDomain {
self.config.name()
);
}
+ if let Err(err) = self.fetch_foreground_programs().await {
+ log::warn!(
+ "failed to fetch foreground programs 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.rs
index 933b355a..913d11f4 100644
--- a/wezterm-client/src/pane/clientpane.rs
+++ b/wezterm-client/src/pane/clientpane.rs
@@ -78,6 +78,7 @@ pub struct ClientPane {
unseen_output: Mutex<bool>,
progress: Mutex<Progress>,
agent_status: Mutex<Option<thinkterm_proto::AgentStatus>>,
+ foreground_program: Mutex<Option<thinkterm_proto::ForegroundProgram>>,
}
impl ClientPane {
@@ -88,6 +89,11 @@ impl ClientPane {
*self.agent_status.lock() = status.filter(|s| s.within_budget());
}
+ /// The same, for the foreground program.
+ pub fn set_foreground_program(&self, program: Option<thinkterm_proto::ForegroundProgram>) {
+ *self.foreground_program.lock() = program.filter(|program| program.within_budget());
+ }
+
/// 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
@@ -267,6 +273,7 @@ impl ClientPane {
// existed, and nothing re-delivers it until the agent next
// changes state.
agent_status: Mutex::new(client.remote_agent_status(remote_pane_id)),
+ foreground_program: Mutex::new(client.remote_foreground_program(remote_pane_id)),
}
}
@@ -373,6 +380,25 @@ impl ClientPane {
self.host.events().agent_status_changed(self.local_pane_id);
}
}
+ Pdu::ForegroundProgramChanged(codec::ForegroundProgramChanged { program, .. }) => {
+ let program = program.filter(|program| program.within_budget());
+ // Coalesced at send time like the agent status: only a real
+ // change is worth a repaint, or a forward one hop on.
+ let changed = {
+ let mut slot = self.foreground_program.lock();
+ if *slot == program {
+ false
+ } else {
+ *slot = program;
+ true
+ }
+ };
+ if changed {
+ self.host
+ .events()
+ .foreground_program_changed(self.local_pane_id);
+ }
+ }
Pdu::PaneRemoved(PaneRemoved { pane_id }) => {
log::trace!("remote pane {} has been removed", pane_id);
self.session.set_dead(true);
@@ -380,6 +406,7 @@ impl ClientPane {
// the windows lock contended); the dead mirror must not
// keep reporting an agent to the panel meanwhile.
*self.agent_status.lock() = None;
+ *self.foreground_program.lock() = None;
self.host.events().pane_removed(self.local_pane_id);
}
Pdu::PaneFocused(PaneFocused { pane_id }) => {
@@ -714,6 +741,10 @@ impl Pane for ClientPane {
self.agent_status.lock().clone()
}
+ fn foreground_program(&self) -> Option<thinkterm_proto::ForegroundProgram> {
+ self.foreground_program.lock().clone()
+ }
+
fn send_paste(&self, text: &str) -> anyhow::Result<()> {
if self.client.remote_tab_input_is_blocked() {
return Ok(());
diff --git a/wezterm-client/src/pane/events.rs b/wezterm-client/src/pane/events.rs
index 461abd20..d16edcf4 100644
--- a/wezterm-client/src/pane/events.rs
+++ b/wezterm-client/src/pane/events.rs
@@ -185,6 +185,10 @@ impl SessionEvents for MuxEvents {
Mux::get().notify(MuxNotification::AgentStatusChanged(pane));
}
+ fn foreground_program_changed(&self, pane: HostPaneId) {
+ Mux::get().notify(MuxNotification::ForegroundProgramChanged(pane));
+ }
+
fn pane_removed(&self, _pane: HostPaneId) {
let mux = Mux::get();
mux.prune_dead_windows();
diff --git a/wezterm-mux-server-impl/src/dispatch.rs b/wezterm-mux-server-impl/src/dispatch.rs
index f18db2dd..8f181abf 100644
--- a/wezterm-mux-server-impl/src/dispatch.rs
+++ b/wezterm-mux-server-impl/src/dispatch.rs
@@ -638,6 +638,16 @@ fn item_for_notification(n: MuxNotification) -> Option<Item> {
status,
}))
}
+ MuxNotification::ForegroundProgramChanged(pane_id) => {
+ // Read at send time, as the agent status is: a backlog of
+ // queued notifications then all carry the current program.
+ let program = Mux::get()
+ .get_pane(pane_id)
+ .and_then(|p| p.foreground_program());
+ write(Pdu::ForegroundProgramChanged(
+ codec::ForegroundProgramChanged { pane_id, program },
+ ))
+ }
MuxNotification::AssignClipboard {
pane_id,
selection,
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index 26e423d0..17b3bae6 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -1095,6 +1095,7 @@ fn web_peer_may_send(pdu: &Pdu) -> bool {
| Pdu::SetClientView(_)
| Pdu::SetFrontendAccessMode(_)
| Pdu::GetAgentStatuses(_)
+ | Pdu::GetForegroundPrograms(_)
| Pdu::PluginFrame(_)
)
}
@@ -1524,6 +1525,33 @@ impl SessionHandler {
})
.detach();
}
+ Pdu::GetForegroundPrograms(GetForegroundPrograms {}) => {
+ spawn_into_main_thread(async move {
+ catch(
+ move || {
+ // iter_panes rather than the observer's own
+ // registry: a chained mux reports what it
+ // mirrors as well as what it observes itself.
+ let programs = Mux::get()
+ .iter_panes()
+ .into_iter()
+ .filter_map(|pane| {
+ let program = pane.foreground_program()?;
+ Some(ForegroundProgramEntry {
+ pane_id: pane.pane_id(),
+ program,
+ })
+ })
+ .collect();
+ Ok(Pdu::GetForegroundProgramsResponse(
+ GetForegroundProgramsResponse { programs },
+ ))
+ },
+ send_response,
+ )
+ })
+ .detach();
+ }
Pdu::GetClientList(GetClientList) => {
spawn_into_main_thread(async move {
catch(
@@ -2612,6 +2640,8 @@ impl SessionHandler {
Pdu::Pong(_) => {}
Pdu::AgentStatusChanged { .. }
| Pdu::GetAgentStatusesResponse { .. }
+ | Pdu::ForegroundProgramChanged { .. }
+ | Pdu::GetForegroundProgramsResponse { .. }
| Pdu::ListPanesResponse { .. }
| Pdu::SetApplicationPalette { .. }
| Pdu::DefaultPalette { .. }