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
feat(mux): keep pane labels on the server
RoversX3d3069699100
diff --git a/codec/src/lib.rs b/codec/src/lib.rsindex e7d80e78..85f00cae 100644--- a/codec/src/lib.rs+++ b/codec/src/lib.rs@@ -824,7 +824,10 @@ macro_rules! pdu {/// 80: How far a pane's programs have got (GetPaneRunState, PaneExited, and/// the CommandFinished alert from OSC 133), and SubscribeEvents for a/// connection that wants events rather than pane contents.-pub const CODEC_VERSION: usize = 80;+/// 81: Pane labels (PaneLabelChanged, ListPanesResponse::pane_labels), the+/// threads behind workspaces (GetWorkspaceNames), and+/// ClientJoined/ClientLeft.+pub const CODEC_VERSION: usize = 81;// Defines the Pdu enum.// Each struct has an explicit identifying number.@@ -939,6 +942,11 @@ pdu! {PaneExited: 114,PaneAdded: 115,SubscribeEvents: 116,+ PaneLabelChanged: 117,+ GetWorkspaceNames: 118,+ GetWorkspaceNamesResponse: 119,+ ClientJoined: 120,+ ClientLeft: 121,}impl Pdu {@@ -1231,6 +1239,9 @@ pub struct ListPanesResponse {pub tabs: Vec<PaneNode>,pub tab_titles: Vec<String>,pub window_titles: HashMap<WindowId, String>,+ /// The labels of the panes that have one.+ #[serde(default)]+ pub pane_labels: HashMap<PaneId, String>,}#[derive(Deserialize, Serialize, PartialEq, Debug)]@@ -1916,10 +1927,51 @@ pub struct PaneAdded {/// This connection wants to hear what happens -- panes appearing and/// closing, programs ending, bells, notifications, titles -- and not what/// the panes show: the server stops pushing their contents to it, and adds-/// `PaneAdded`. For `thinkterm cli events` and anything like it.+/// `PaneAdded`, `ClientJoined` and `ClientLeft`. For `thinkterm cli events`+/// and anything like it.#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]pub struct SubscribeEvents {}+/// Label `pane_id`, or with `None` take its label away: a request that+/// returns `UnitResponse`, and unilateral to every client when a label+/// changes.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct PaneLabelChanged {+ pub pane_id: PaneId,+ pub label: Option<String>,+}++/// Ask which thread each workspace backs, for the names the CLI accepts.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]+pub struct GetWorkspaceNames {}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct WorkspaceName {+ pub workspace: String,+ pub project: String,+ pub thread: String,+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct GetWorkspaceNamesResponse {+ pub names: Vec<WorkspaceName>,+}++/// Unilateral, to a connection that sent `SubscribeEvents`: a client began+/// showing panes -- a window, a browser, a phone. A command that only asks+/// the server something is not one.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct ClientJoined {+ pub client_id: ClientId,+}++/// Unilateral, to a connection that sent `SubscribeEvents`: a client that+/// showed panes went away.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct ClientLeft {+ pub client_id: ClientId,+}+#[derive(Deserialize, Serialize, PartialEq, Debug)]pub struct SetPaneZoomed {pub containing_tab_id: TabId,@@ -2400,6 +2452,7 @@ mod golden {],tab_titles: vec!["main".to_string()],window_titles,+ pane_labels: HashMap::new(),}}@@ -2544,9 +2597,18 @@ mod golden {assert_eq!(back, command_spec());}+ /// LIST_PANES as codec 81 writes it: the pane labels went on the end,+ /// and an empty map is one zero byte after the bytes captured before.+ fn list_panes_with_labels() -> Vec<u8> {+ [LIST_PANES, &[0]].concat()+ }+#[test]fn wire_bytes_are_stable() {- assert_eq!(varbincode_bytes(&list_panes_response()), LIST_PANES);+ assert_eq!(+ varbincode_bytes(&list_panes_response()),+ list_panes_with_labels()+ );assert_eq!(varbincode_bytes(&split_pane()), SPLIT_PANE);assert_eq!(varbincode_bytes(&search_request()), SEARCH);assert_eq!(varbincode_bytes(&client_list_response()), CLIENT_LIST);@@ -2560,7 +2622,10 @@ mod golden {let mut de = varbincode::Deserializer::new(&mut r);serde::Deserialize::deserialize(&mut de).unwrap()}- assert_eq!(back::<ListPanesResponse>(LIST_PANES), list_panes_response());+ assert_eq!(+ back::<ListPanesResponse>(&list_panes_with_labels()),+ list_panes_response()+ );assert_eq!(back::<SplitPane>(SPLIT_PANE), split_pane());assert_eq!(back::<SearchScrollbackRequest>(SEARCH), search_request());assert_eq!(@@ -3100,7 +3165,7 @@ mod test {// tripwire: whoever bumps the codec must come here, confirm the// round-trips still cover the new version, and advance it// deliberately.- assert_eq!(CODEC_VERSION, 80);+ assert_eq!(CODEC_VERSION, 81);use thinkterm_proto::{AgentEvidence, AgentState, AgentStatus, ProgramBlockedKind, ProgramReport,ProgramReportChild, ProgramReportState,@@ -3170,7 +3235,7 @@ mod test {#[test]fn foreground_program_protocol_round_trip_at_version_74() {// Same tripwire as the agent-status test above.- assert_eq!(CODEC_VERSION, 80);+ assert_eq!(CODEC_VERSION, 81);use thinkterm_proto::ForegroundProgram;fn round_trip(pdu: &Pdu) -> Pdu {@@ -3271,13 +3336,21 @@ mod test {#[test]fn run_state_protocol_round_trip_at_version_80() {// Same tripwire as the agent-status test above.- assert_eq!(CODEC_VERSION, 80);+ assert_eq!(CODEC_VERSION, 81);use thinkterm_proto::{PaneExit, PaneRunState, ProgramState, ShellCommands};let exit = PaneExit {code: Some(2),signal: Some("Terminated".to_string()),};+ let client_id = ClientId {+ hostname: "myhost".to_string(),+ username: "user".to_string(),+ pid: 4,+ epoch: 5,+ id: 6,+ ssh_auth_sock: None,+ };for pdu in [Pdu::GetPaneRunState(GetPaneRunState { pane_id: 7 }),Pdu::GetPaneRunStateResponse(GetPaneRunStateResponse {@@ -3313,6 +3386,32 @@ mod test {}),Pdu::PaneAdded(PaneAdded { pane_id: 10 }),Pdu::SubscribeEvents(SubscribeEvents {}),+ Pdu::PaneLabelChanged(PaneLabelChanged {+ pane_id: 10,+ label: Some("reviewer".to_string()),+ }),+ Pdu::PaneLabelChanged(PaneLabelChanged {+ pane_id: 10,+ label: None,+ }),+ Pdu::ListPanesResponse(ListPanesResponse {+ tabs: vec![],+ tab_titles: vec![],+ window_titles: HashMap::new(),+ pane_labels: HashMap::from([(10, "reviewer".to_string())]),+ }),+ Pdu::GetWorkspaceNames(GetWorkspaceNames {}),+ Pdu::GetWorkspaceNamesResponse(GetWorkspaceNamesResponse {+ names: vec![WorkspaceName {+ workspace: "thinkterm:p1:t1".to_string(),+ project: "project".to_string(),+ thread: "fix login".to_string(),+ }],+ }),+ Pdu::ClientJoined(ClientJoined {+ client_id: client_id.clone(),+ }),+ Pdu::ClientLeft(ClientLeft { client_id }),Pdu::NotifyAlert(NotifyAlert {pane_id: 7,alert: Alert::CommandFinished {@@ -3336,7 +3435,7 @@ mod test {fn frame_control_extension_round_trips_without_changing_legacy_version() {// The extension is asked for, so it needed no bump of its own; 74// is the foreground program's, which a server sends unasked.- assert_eq!(CODEC_VERSION, 80);+ assert_eq!(CODEC_VERSION, 81);for pdu in [Pdu::GetKittyImage(GetKittyImage { pane_id: 3, image_id: 7, data_hash: [9; 32], have_frames: 2, image_epoch: Some(4) }),Pdu::GetKittyFrameSelections(GetKittyFrameSelections { pane_id: 3, subscribe: true }),diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex 409c598a..4ece226c 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -111,10 +111,23 @@ pub enum MuxNotification {tab_id: TabId,title: String,},+ /// A pane was labelled, relabelled or had its label taken away.+ PaneLabelChanged {+ pane_id: PaneId,+ label: Option<String>,+ /// Set on a mirror without telling the server that owns the pane:+ /// the label came from it, or is told to it another way.+ from_server: bool,+ },WindowTitleChanged {window_id: WindowId,title: String,},+ /// A client began showing panes: it set a viewport for the first time+ /// since it connected. A command that only asks things never does.+ ClientJoined(Arc<ClientId>),+ /// A client that had shown panes disconnected.+ ClientLeft(Arc<ClientId>),WorkspaceRenamed {old_workspace: String,new_workspace: String,@@ -489,6 +502,27 @@ pub struct Mux {/// removed first, so that `PaneExited` always precedes `PaneRemoved`./// Payloads stay here until announced even if exit history evicts them.unannounced_pane_exits: Mutex<HashMap<PaneId, thinkterm_proto::PaneExit>>,+ /// The labels panes were given, by `cli set-pane-label` or by renaming+ /// a pane tab. One per live pane at most: removing a pane drops its own.+ pane_labels: RwLock<HashMap<PaneId, String>>,+}++/// How many characters a pane label keeps; the rest are cut.+const PANE_LABEL_MAX_CHARS: usize = 128;++/// `text` as a pane label: without control characters, since labels are+/// printed to terminals, trimmed and capped -- and trimmed again after the+/// cut, as `--pane` trims the name it is given. `None` when nothing is+/// left.+pub fn normalized_pane_label(text: &str) -> Option<String> {+ let printable: String = text.chars().filter(|c| !c.is_control()).collect();+ let capped: String = printable+ .trim()+ .chars()+ .take(PANE_LABEL_MAX_CHARS)+ .collect();+ let label = capped.trim_end();+ (!label.is_empty()).then(|| label.to_string())}/// How many ended panes `Mux::recent_pane_exit` remembers, and for how long.@@ -1338,6 +1372,7 @@ impl Mux {palette_advisories: Mutex::new(PaletteAdvisoryState::default()),recent_pane_exits: Mutex::new(std::collections::VecDeque::new()),unannounced_pane_exits: Mutex::new(HashMap::new()),+ pane_labels: RwLock::new(HashMap::new()),identity: RwLock::new(None),num_panes_by_workspace: RwLock::new(HashMap::new()),main_thread_id: std::thread::current().id(),@@ -1612,9 +1647,9 @@ impl Mux {viewport: FrontendViewport,) -> anyhow::Result<FrontendViewportState> {self.validate_frontend_viewport(tab_id, &viewport)?;- let (should_apply, should_publish, access_changed) = {+ let (should_apply, should_publish, access_changed, joined) = {let mut lease = self.frontend_lease.lock();- lease.ever_rendered.insert(client_id.clone());+ let joined = lease.ever_rendered.insert(client_id.clone());let mut access_changed = false;if lease.access_mode == FrontendAccessMode::Handoff&& lease.handoff_owner.is_none()@@ -1659,8 +1694,11 @@ impl Mux {state.view = None;}let should_apply = can_drive && (owner_changed || viewport_changed || access_changed);- (should_apply, should_apply, access_changed)+ (should_apply, should_apply, access_changed, joined)};+ if joined {+ Mux::notify_from_any_thread(MuxNotification::ClientJoined(Arc::new(client_id.clone())));+ }if should_apply {if let Err(err) = self.apply_frontend_viewport(tab_id, &viewport) {return Err(self.fail_closed_frontend_geometry(tab_id, None, err));@@ -1691,8 +1729,27 @@ impl Mux {return Ok(None);}drop(registrations);- self.set_client_viewport(client_id, tab_id, viewport)- .map(Some)+ let state = self.set_client_viewport(client_id, tab_id, viewport);+ self.forget_renderer_if_unregistered(client_id);+ state.map(Some)+ }++ /// A client that unregistered while its report was under way can be+ /// counted as showing panes after `unregister_client` already let it+ /// go: no `ClientLeft` would follow its `ClientJoined`, and the entry+ /// would stay. Unregistering drops the registration before that+ /// entry, so checking after the report catches every interleaving.+ fn forget_renderer_if_unregistered(&self, client_id: &ClientId) {+ if self.drop_unregistered_renderer(client_id) {+ Mux::notify_from_any_thread(MuxNotification::ClientLeft(Arc::new(client_id.clone())));+ }+ }++ /// Whether `client_id` was counted as showing panes though it is no+ /// longer registered. The count is dropped.+ fn drop_unregistered_renderer(&self, client_id: &ClientId) -> bool {+ !self.client_registrations.read().contains_key(client_id)+ && self.frontend_lease.lock().ever_rendered.remove(client_id)}pub fn client_owns_frontend_lease(&self, client_id: &ClientId, tab_id: TabId) -> bool {@@ -1790,6 +1847,7 @@ impl Mux {if let Err(err) = self.claim_frontend_viewport(client_id, tab_id, viewport) {log::error!("failed to apply claimed viewport for tab {tab_id}: {err:#}");}+ self.forget_renderer_if_unregistered(client_id);}true}@@ -1812,8 +1870,9 @@ impl Mux {}drop(registrations);self.client_had_input(client_id);- self.claim_frontend_viewport(client_id, tab_id, viewport)- .map(Some)+ let state = self.claim_frontend_viewport(client_id, tab_id, viewport);+ self.forget_renderer_if_unregistered(client_id);+ state.map(Some)}fn claim_frontend_viewport(@@ -1846,9 +1905,9 @@ impl Mux {.viewport_state(tab_id).ok_or_else(|| anyhow!("viewport state for tab {tab_id} disappeared"));}- let (access_changed, mut affected_tabs) = {+ let (access_changed, mut affected_tabs, joined) = {let mut lease = self.frontend_lease.lock();- lease.ever_rendered.insert(client_id.clone());+ let joined = lease.ever_rendered.insert(client_id.clone());let mode = lease.access_mode;let mut access_changed = false;let mut affected_tabs = vec![tab_id];@@ -1871,8 +1930,11 @@ impl Mux {state.viewports.insert(client_id.clone(), viewport.clone());state.owner = Some(client_id.clone());state.view = None;- (access_changed, affected_tabs)+ (access_changed, affected_tabs, joined)};+ if joined {+ Mux::notify_from_any_thread(MuxNotification::ClientJoined(Arc::new(client_id.clone())));+ }if access_changed {self.publish_frontend_access_state();}@@ -2561,9 +2623,9 @@ impl Mux {self.clients.write().remove(client_id);registrations.remove(client_id);}- let (affected, access_changed) = {+ let (affected, access_changed, left) = {let mut lease = self.frontend_lease.lock();- lease.ever_rendered.remove(client_id);+ let left = lease.ever_rendered.remove(client_id);let mut affected = Vec::new();for (tab_id, state) in &mut lease.tabs {state.viewports.remove(client_id);@@ -2585,9 +2647,13 @@ impl Mux {lease.handoff_ever_owned = true;lease.handoff_last_owner = Some(client_id.clone());}- (affected, access_changed)+ (affected, access_changed, left)};+ if left {+ // A connection is dropped on its own thread.+ Mux::notify_from_any_thread(MuxNotification::ClientLeft(Arc::new(client_id.clone())));+ }if access_changed {self.publish_frontend_access_state();}@@ -2842,6 +2908,55 @@ impl Mux {.map(|(_, exit, _)| exit.clone())}+ /// The label `pane_id` was given, if any.+ pub fn pane_label(&self, pane_id: PaneId) -> Option<String> {+ self.pane_labels.read().get(&pane_id).cloned()+ }++ /// Every label, by pane.+ pub fn pane_labels(&self) -> HashMap<PaneId, String> {+ self.pane_labels.read().clone()+ }++ /// Label `pane_id`, or with `None` or blank text take its label away;+ /// see `normalized_pane_label`. Only a pane the mux has can be+ /// labelled. Says whether anything changed; only a change is+ /// announced, so a client and a server that tell each other about the+ /// same label stop at once.+ pub fn set_pane_label(&self, pane_id: PaneId, label: Option<&str>) -> bool {+ self.change_pane_label(pane_id, label, false)+ }++ /// `set_pane_label` for a mirror, without telling the server that owns+ /// the pane: what it reported, or a label told to it another way.+ pub fn set_pane_label_from_server(&self, pane_id: PaneId, label: Option<&str>) -> bool {+ self.change_pane_label(pane_id, label, true)+ }++ fn change_pane_label(&self, pane_id: PaneId, label: Option<&str>, from_server: bool) -> bool {+ let label = label.and_then(normalized_pane_label);+ let changed = {+ let mut labels = self.pane_labels.write();+ match &label {+ Some(label) => {+ if !self.panes.read().contains_key(&pane_id) {+ return false;+ }+ labels.insert(pane_id, label.clone()).as_ref() != Some(label)+ }+ None => labels.remove(&pane_id).is_some(),+ }+ };+ if changed {+ self.notify(MuxNotification::PaneLabelChanged {+ pane_id,+ label,+ from_server,+ });+ }+ changed+ }+pub fn get_tab(&self, tab_id: TabId) -> Option<Arc<Tab>> {self.tabs.read().get(&tab_id).map(Arc::clone)}@@ -2897,6 +3012,7 @@ impl Mux {// temporary (the panes write guard) would otherwise live across the// notify below, deadlocking any subscriber that touches the pane map.let removed = self.panes.write().remove(&pane_id);+ self.pane_labels.write().remove(&pane_id);if let Some(pane) = removed {log::debug!("killing pane {}", pane_id);pane.kill();@@ -4068,6 +4184,48 @@ mod tests {}}+ #[test]+ fn a_renderer_counted_after_it_unregistered_is_let_go() {+ let mux = Mux::new(None);+ let stays = client_id(1);+ let gone = client_id(2);+ let registration = mux.register_client(Arc::new(stays.clone()));+ {+ let mut lease = mux.frontend_lease.lock();+ lease.ever_rendered.insert(stays.clone());+ lease.ever_rendered.insert(gone.clone());+ }+ assert!(!mux.drop_unregistered_renderer(&stays));+ assert!(mux.drop_unregistered_renderer(&gone));+ assert!(!mux.drop_unregistered_renderer(&gone), "it leaves once");+ let lease = mux.frontend_lease.lock();+ assert!(lease.ever_rendered.contains(&stays));+ assert!(!lease.ever_rendered.contains(&gone));+ drop(lease);+ mux.frontend_lease.lock().ever_rendered.clear();+ mux.unregister_client(&stays, registration);+ }++ #[test]+ fn labels_lose_control_characters_and_blank_is_none() {+ assert_eq!(normalized_pane_label(" build "), Some("build".to_string()));+ assert_eq!(+ normalized_pane_label("\x1b]52;c;aGk=\x07bad\nname"),+ Some("]52;c;aGk=badname".to_string())+ );+ assert_eq!(normalized_pane_label(" \x1b\t "), None);+ assert_eq!(+ normalized_pane_label(&"x".repeat(200)).map(|l| l.len()),+ Some(128)+ );+ let cut_at_a_space = format!("{} suffix", "x".repeat(127));+ assert_eq!(+ normalized_pane_label(&cut_at_a_space),+ Some("x".repeat(127)),+ "no blank is left at the cut"+ );+ }+fn frontend_test_size(cols: usize, rows: usize) -> TerminalSize {TerminalSize {cols,diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rsindex 50371f73..ad3f7041 100644--- a/wezterm-client/src/client.rs+++ b/wezterm-client/src/client.rs@@ -505,16 +505,24 @@ async fn process_unilateral_inner_async(}/// Where a client without a domain of its own -- the CLI -- sends what the-/// server pushes, once it has asked to hear it. See `tap_unilateral_pdus`.-static UNILATERAL_TAP: std::sync::Mutex<Option<Sender<Pdu>>> = std::sync::Mutex::new(None);+/// server pushes, once it has asked to hear it, and which of the pushes it+/// wants. See `tap_unilateral_pdus`.+static UNILATERAL_TAP: std::sync::Mutex<Option<(Sender<Pdu>, fn(&Pdu) -> bool)>> =+ std::sync::Mutex::new(None);/// Hand every PDU the server pushes to a client without a local domain/// (the CLI's own connection) to the returned receiver, rather than drop/// it. At most `capacity` wait unread; the rest are dropped, with a/// warning, so a reader that stops reading cannot grow it without bound.pub fn tap_unilateral_pdus(capacity: usize) -> Receiver<Pdu> {+ tap_unilateral_pdus_where(capacity, |_| true)+}++/// `tap_unilateral_pdus` for only the pushes `wanted` picks: the others,+/// however many, cannot crowd them out.+pub fn tap_unilateral_pdus_where(capacity: usize, wanted: fn(&Pdu) -> bool) -> Receiver<Pdu> {let (tx, rx) = smol::channel::bounded(capacity);- *UNILATERAL_TAP.lock().unwrap() = Some(tx);+ *UNILATERAL_TAP.lock().unwrap() = Some((tx, wanted));rx}@@ -529,8 +537,8 @@ fn process_unilateral(None => {// No panes to update here. A caller that asked for the// server's pushes gets them; anyone else ignores them.- if let Some(tap) = UNILATERAL_TAP.lock().unwrap().as_ref() {- if tap.try_send(decoded.pdu).is_err() {+ if let Some((tap, wanted)) = UNILATERAL_TAP.lock().unwrap().as_ref() {+ if wanted(&decoded.pdu) && tap.try_send(decoded.pdu).is_err() {log::warn!("dropping a server push nobody is reading");}return Ok(());@@ -778,6 +786,34 @@ fn process_unilateral(Pdu::DefaultPalette(_) => {return Ok(());}+ // Only for connections that subscribed to events; a domain never does.+ Pdu::ClientJoined(_) | Pdu::ClientLeft(_) => {+ return Ok(());+ }+ Pdu::PaneLabelChanged(codec::PaneLabelChanged { pane_id, label }) => {+ let pane_id = *pane_id;+ let label = label.clone();+ promise::spawn::spawn_into_main_thread(async move {+ let mux = Mux::try_get().ok_or_else(|| anyhow!("no more mux"))?;+ let client_domain = mux+ .get_domain(local_domain_id)+ .ok_or_else(|| anyhow!("no such domain {}", local_domain_id))?;+ let client_domain =+ client_domain+ .downcast_ref::<ClientDomain>()+ .ok_or_else(|| {+ anyhow!("domain {} is not a ClientDomain instance", local_domain_id)+ })?;+ if client_domain.connection_generation() != Some(connection_generation) {+ return Ok(());+ }++ client_domain.process_remote_pane_label_change(pane_id, label);+ anyhow::Result::<()>::Ok(())+ })+ .detach();+ return Ok(());+ }Pdu::TabResized(_) | Pdu::TabAddedToWindow(_) => {log::trace!("resync due to {:?}", decoded.pdu);promise::spawn::spawn_into_main_thread(async move {@@ -2805,6 +2841,12 @@ impl Client {rpc!(get_image_cell, GetImageCell, GetImageCellResponse);rpc!(set_configured_palette_for_pane, SetPalette, UnitResponse);rpc!(set_tab_title, TabTitleChanged, UnitResponse);+ rpc!(set_pane_label, PaneLabelChanged, UnitResponse);+ rpc!(+ get_workspace_names,+ GetWorkspaceNames = (),+ GetWorkspaceNamesResponse+ );rpc!(set_window_title, WindowTitleChanged, UnitResponse);rpc!(rename_workspace, RenameWorkspace, UnitResponse);rpc!(erase_scrollback, EraseScrollbackRequest, UnitResponse);diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rsindex e5fd6ad7..20312e2b 100644--- a/wezterm-client/src/domain.rs+++ b/wezterm-client/src/domain.rs@@ -2039,6 +2039,44 @@ struct EarlyRemoteState {viewports: Vec<codec::ClientViewportState>,}+/// Numbers for the labels given to mirrors here. Telling the server one+/// that fails keeps it for the next sync only while it is the latest:+/// told after a later one, it would undo that. The mirror cannot say which+/// is the latest, as the server telling back an earlier one may have+/// landed over it.+#[derive(Default)]+struct LabelEdits {+ last: u64,+ /// Each mirror's latest number, until the server takes that label.+ latest: HashMap<PaneId, u64>,+}++impl LabelEdits {+ /// Number the label just given to `pane_id`: the latest now.+ fn number(&mut self, pane_id: PaneId) -> u64 {+ self.last += 1;+ self.latest.insert(pane_id, self.last);+ self.last+ }++ /// Whether the label numbered `number`, after telling the server it,+ /// is to be kept for the next sync: one not `taken`, while still the+ /// latest. One taken lets its number go.+ fn settle(&mut self, pane_id: PaneId, number: u64, taken: bool) -> bool {+ if self.latest.get(&pane_id) != Some(&number) {+ return false;+ }+ if taken {+ self.latest.remove(&pane_id);+ }+ !taken+ }++ fn forget(&mut self, pane_id: PaneId) {+ self.latest.remove(&pane_id);+ }+}+pub struct ClientDomain {config: ClientDomainConfig,label: String,@@ -2055,6 +2093,11 @@ pub struct ClientDomain {/// Serializes topology snapshots. Immediate callers join an active/// generation; background pushes coalesce behind one trailing pass.resync_coordinator: Mutex<ResyncCoordinatorState>,+ /// Labels given to mirrors here that the server has not heard of: given+ /// while detached, or telling it failed. Told on the next sync; one per+ /// mirror at most, dropped with it.+ unsent_labels: Mutex<HashMap<PaneId, Option<String>>>,+ label_edits: Mutex<LabelEdits>,local_domain_id: DomainId,}@@ -2067,6 +2110,67 @@ async fn update_remote_workspace(Ok(())}+/// After telling the server the label numbered `number` for the mirror+/// `pane_id`: one it did not take is kept for the next sync while it is+/// the latest, and shown on the mirror again, where the server telling+/// back an earlier one may have landed over it.+fn settle_label(+ local_domain_id: DomainId,+ pane_id: PaneId,+ label: Option<String>,+ number: u64,+ taken: bool,+) {+ let Some(mux) = Mux::try_get() else {+ return;+ };+ let Some(domain) = mux.get_domain(local_domain_id) else {+ return;+ };+ let Some(domain) = domain.downcast_ref::<ClientDomain>() else {+ return;+ };+ if !domain+ .label_edits+ .lock()+ .unwrap()+ .settle(pane_id, number, taken)+ {+ return;+ }+ domain+ .unsent_labels+ .lock()+ .unwrap()+ .insert(pane_id, label.clone());+ mux.set_pane_label_from_server(pane_id, label.as_deref());+}++/// Tell the server the label numbered `number` given to its pane+/// `remote_pane_id`, mirrored here as `pane_id`.+fn send_label(+ inner: Arc<ClientInner>,+ pane_id: PaneId,+ remote_pane_id: PaneId,+ label: Option<String>,+ number: u64,+) {+ promise::spawn::spawn(async move {+ let sent = inner+ .client+ .set_pane_label(codec::PaneLabelChanged {+ pane_id: remote_pane_id,+ label: label.clone(),+ })+ .await;+ if let Err(err) = &sent {+ log::debug!("pane {pane_id}: the server did not take its label: {err:#}");+ }+ settle_label(inner.local_domain_id, pane_id, label, number, sent.is_ok());+ })+ .detach();+}+fn mux_notify_client_domain(local_domain_id: DomainId, notif: MuxNotification) -> bool {let mux = Mux::get();let domain = match mux.get_domain(local_domain_id) {@@ -2139,6 +2243,44 @@ fn mux_notify_client_domain(local_domain_id: DomainId, notif: MuxNotification) -}).detach();}+ // The server is where a label lives: one it told is not told back,+ // where an old one could undo a rename on its way there.+ MuxNotification::PaneLabelChanged {+ pane_id,+ label,+ from_server: false,+ } => {+ let Some(pane) = mux+ .get_pane(pane_id)+ .filter(|pane| pane.domain_id() == local_domain_id)+ else {+ return true;+ };+ let Some(mirror) = pane.downcast_ref::<ClientPane>() else {+ return true;+ };+ let number = client_domain.label_edits.lock().unwrap().number(pane_id);+ let Some(inner) = client_domain.inner() else {+ client_domain+ .unsent_labels+ .lock()+ .unwrap()+ .insert(pane_id, label);+ return true;+ };+ // This label is the one to tell: one kept from before would+ // follow it on the next sync and undo it.+ client_domain.unsent_labels.lock().unwrap().remove(&pane_id);+ // Not for a mirror left from a server runtime since replaced:+ // its remote id could name another pane now.+ if mirror.belongs_to_remote_server(inner.client.remote_server_id().as_deref()) {+ send_label(inner, pane_id, mirror.remote_pane_id(), label, number);+ }+ }+ MuxNotification::PaneRemoved(pane_id) => {+ client_domain.unsent_labels.lock().unwrap().remove(&pane_id);+ client_domain.label_edits.lock().unwrap().forget(pane_id);+ }MuxNotification::TabTitleChanged { tab_id, title } => {if let Some(remote_tab_id) = client_domain.local_to_remote_tab_id(tab_id) {if let Some(inner) = client_domain.inner() {@@ -2413,6 +2555,8 @@ impl ClientDomain {attaching: std::sync::atomic::AtomicBool::new(false),attach_retries: std::sync::atomic::AtomicUsize::new(0),resync_coordinator: Mutex::new(ResyncCoordinatorState::default()),+ unsent_labels: Mutex::new(HashMap::new()),+ label_edits: Mutex::new(LabelEdits::default()),local_domain_id,}}@@ -3868,6 +4012,14 @@ impl ClientDomain {Ok(state)}+ pub fn process_remote_pane_label_change(&self, remote_pane_id: PaneId, label: Option<String>) {+ if let Some(inner) = self.inner() {+ if let Some(local_pane_id) = inner.remote_to_local_pane_id(remote_pane_id) {+ Mux::get().set_pane_label_from_server(local_pane_id, label.as_deref());+ }+ }+ }+pub fn process_remote_window_title_change(&self, remote_window_id: WindowId, title: String) {if let Some(inner) = self.inner() {if let Some(local_window_id) = inner.remote_to_local_window(remote_window_id) {@@ -4326,6 +4478,61 @@ impl ClientDomain {.retain(|_workspace, window_id| mux.get_window(*window_id).is_some());}+ // Each mirror takes the label the server holds, or loses its own:+ // one taken away while this side could not hear of it would stay+ // for good. Set in this sync, so a push handled after it is not+ // undone by it. A label given here that the server has not heard+ // of is told instead.+ let domain = mux.get_domain(inner.local_domain_id);+ let client_domain = domain+ .as_ref()+ .and_then(|domain| domain.downcast_ref::<ClientDomain>());+ let mut unsent = client_domain+ .map(|domain| std::mem::take(&mut *domain.unsent_labels.lock().unwrap()))+ .unwrap_or_default();+ let server_id = inner.client.remote_server_id();+ for pane in mux.iter_panes() {+ if pane.domain_id() != inner.local_domain_id {+ continue;+ }+ let Some(mirror) = pane.downcast_ref::<ClientPane>() else {+ continue;+ };+ let remote_pane_id = mirror.remote_pane_id();+ if !mirror.belongs_to_remote_server(server_id.as_deref())+ || inner.remote_to_local_pane_id(remote_pane_id) != Some(pane.pane_id())+ {+ continue;+ }+ match (client_domain, unsent.remove(&pane.pane_id())) {+ // Shown again, as the server telling back an earlier one+ // may have landed over it, and told under a new number: a+ // telling of it failing late on the old connection is not+ // to keep it again.+ (Some(client_domain), Some(label)) => {+ mux.set_pane_label_from_server(pane.pane_id(), label.as_deref());+ let number = client_domain+ .label_edits+ .lock()+ .unwrap()+ .number(pane.pane_id());+ send_label(+ Arc::clone(&inner),+ pane.pane_id(),+ remote_pane_id,+ label,+ number,+ );+ }+ _ => {+ mux.set_pane_label_from_server(+ pane.pane_id(),+ panes.pane_labels.get(&remote_pane_id).map(String::as_str),+ );+ }+ }+ }+Ok(())}@@ -4402,7 +4609,7 @@ mod tests {remote_frontend_gate_from_state, remote_move_pane_id, server_runtime_replaced,stale_mirrors_to_reap, thread_id_for_workspace, AttachRetryOutcome, AttachRetryTiming,AutomaticRemotePaneResize, FrontendRecoveryAck, FrontendRecoveryBarrier,- FrontendRecoverySlot, MirrorOrigin, RemoteFrontendGate, ResyncCoordinatorState,+ FrontendRecoverySlot, LabelEdits, MirrorOrigin, RemoteFrontendGate, ResyncCoordinatorState,ResyncDriverAction, ResyncOutcome, ResyncRequestKind, SharedResyncCompletion,ViewportLatencyState,};@@ -5304,6 +5511,29 @@ mod tests {.is_empty());assert!(stale_mirrors_to_reap([(1, mirror("srv-a"))], None, None, 1).is_empty());}++ #[test]+ fn only_the_latest_label_that_failed_is_kept() {+ let mut edits = LabelEdits::default();+ let first = edits.number(1);+ let second = edits.number(1);+ assert!(+ !edits.settle(1, first, false),+ "an earlier one failing late"+ );+ assert!(edits.settle(1, second, false), "the latest failing");+ // Told again on the next sync, under a new number.+ let again = edits.number(1);+ assert!(+ !edits.settle(1, second, false),+ "the old telling failing late"+ );+ assert!(!edits.settle(1, again, true));+ let gone = edits.number(2);+ edits.forget(2);+ assert!(!edits.settle(2, gone, false), "a mirror since removed");+ assert!(edits.latest.is_empty(), "numbers are let go");+ }}#[async_trait(?Send)]diff --git a/wezterm-mux-server-impl/src/dispatch.rs b/wezterm-mux-server-impl/src/dispatch.rsindex 2e930b0e..a5fa3185 100644--- a/wezterm-mux-server-impl/src/dispatch.rs+++ b/wezterm-mux-server-impl/src/dispatch.rs@@ -640,6 +640,20 @@ async fn process_async_with_peer<S: ConnectionStream>(Ok(Item::Notif(MuxNotification::PaneAdded(pane_id))) if handler.events_subscribed => {send_notif_pdu(Pdu::PaneAdded(codec::PaneAdded { pane_id }));}+ Ok(Item::Notif(MuxNotification::ClientJoined(client_id)))+ if handler.events_subscribed =>+ {+ send_notif_pdu(Pdu::ClientJoined(codec::ClientJoined {+ client_id: (*client_id).clone(),+ }));+ }+ Ok(Item::Notif(MuxNotification::ClientLeft(client_id)))+ if handler.events_subscribed =>+ {+ send_notif_pdu(Pdu::ClientLeft(codec::ClientLeft {+ client_id: (*client_id).clone(),+ }));+ }Ok(Item::Notif(other)) => {log::trace!("notification with nothing for the connection to do: {other:?}");}@@ -792,7 +806,9 @@ fn item_for_notification(n: MuxNotification) -> Option<Item> {| MuxNotification::Alert { .. }| MuxNotification::PaneAdded(_)| MuxNotification::PaneExited { .. }- | MuxNotification::PaneRemoved(_) => Some(Item::Notif(n)),+ | MuxNotification::PaneRemoved(_)+ | MuxNotification::ClientJoined(_)+ | MuxNotification::ClientLeft(_) => Some(Item::Notif(n)),MuxNotification::AgentStatusChanged(pane_id) => {// Read the status at send time so the payload is always the// freshest classification, never a queued stale value.@@ -846,6 +862,12 @@ fn item_for_notification(n: MuxNotification) -> Option<Item> {title,}))}+ MuxNotification::PaneLabelChanged { pane_id, label, .. } => {+ write(Pdu::PaneLabelChanged(codec::PaneLabelChanged {+ pane_id,+ label,+ }))+ }MuxNotification::WindowTitleChanged { window_id, title } => {write(Pdu::WindowTitleChanged(codec::WindowTitleChanged {window_id,diff --git a/wezterm-mux-server-impl/src/handoff.rs b/wezterm-mux-server-impl/src/handoff.rsindex 5656a072..e0009db4 100644--- a/wezterm-mux-server-impl/src/handoff.rs+++ b/wezterm-mux-server-impl/src/handoff.rs@@ -226,11 +226,13 @@ const KITTY_NUMBERS_TAG: &[u8] = b"KGPA\x03";const KITTY_PLACEMENTS_TAG: &[u8] = b"KGPA\x04";const KITTY_RELATIVES_TAG: &[u8] = b"KGPA\x05";const SHELL_COMMANDS_TAG: &[u8] = b"TTSH\x01";+const PANE_LABEL_TAG: &[u8] = b"TTLB\x01";fn encode_snapshot(snapshot: &TerminalSnapshot,graphics: &wezterm_term::KittyGraphicsSnapshot,shell: &wezterm_term::ShellCommandsSnapshot,+ label: Option<&str>,) -> anyhow::Result<Vec<u8>> {let mut bytes = Vec::new();snapshot.serialize(&mut varbincode::Serializer::new(&mut bytes))@@ -280,6 +282,13 @@ fn encode_snapshot(shell.serialize(&mut varbincode::Serializer::new(&mut bytes)).context("encoding the shell's command count")?;}+ // The pane's label lives in the mux, not the terminal; it goes last,+ // on the same terms as the shell's count.+ if let Some(label) = label {+ bytes.extend_from_slice(PANE_LABEL_TAG);+ label.serialize(&mut varbincode::Serializer::new(&mut bytes))+ .context("encoding the pane's label")?;+ }zstd::encode_all(&bytes[..], 3).context("compressing a terminal snapshot")}@@ -289,12 +298,16 @@ fn decode_snapshot(TerminalSnapshot,Option<wezterm_term::KittyGraphicsSnapshot>,Option<wezterm_term::ShellCommandsSnapshot>,+ Option<String>,)> {let bytes = zstd::decode_all(bytes).context("decompressing a terminal snapshot")?;let mut reader = &bytes[..];let snapshot = TerminalSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader)).context("decoding a terminal snapshot")?;- let graphics = if reader.is_empty() || reader.starts_with(SHELL_COMMANDS_TAG) {+ let graphics = if reader.is_empty()+ || reader.starts_with(SHELL_COMMANDS_TAG)+ || reader.starts_with(PANE_LABEL_TAG)+ {None} else {let has_relatives = reader.starts_with(KITTY_RELATIVES_TAG);@@ -333,8 +346,13 @@ fn decode_snapshot(Some(wezterm_term::ShellCommandsSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader)).context("decoding the shell's command count")?)} else { None };+ let label = if reader.starts_with(PANE_LABEL_TAG) {+ reader = &reader[PANE_LABEL_TAG.len()..];+ Some(String::deserialize(&mut varbincode::Deserializer::new(&mut reader))+ .context("decoding the pane's label")?)+ } else { None };anyhow::ensure!(reader.is_empty(), "trailing bytes after the terminal snapshot's extensions");- Ok((snapshot, graphics, shell))+ Ok((snapshot, graphics, shell, label))}// ------------------------------------------------------- the old server@@ -569,7 +587,12 @@ fn capture(pid_file: bool) -> anyhow::Result<Capture> {description: parts.description,pid: parts.pid,tty_name: parts.tty_name.map(|name| name.to_string_lossy().into_owned()),- snapshot: encode_snapshot(&snapshot, &graphics, &shell)?,+ snapshot: encode_snapshot(+ &snapshot,+ &graphics,+ &shell,+ mux.pane_label(pane_id).as_deref(),+ )?,},parts.pty_fd,));@@ -759,6 +782,7 @@ struct Received {snapshot: TerminalSnapshot,graphics: Option<wezterm_term::KittyGraphicsSnapshot>,shell: Option<wezterm_term::ShellCommandsSnapshot>,+ label: Option<String>,}/// Receive the panes, the windows and the listening socket; only on@@ -785,9 +809,9 @@ pub fn complete(let pane_id = pane.pane_id;let fd = recv_owned_fd(&stream)?;fail_at("pane")?;- let (snapshot, graphics, shell) = decode_snapshot(&pane.snapshot)+ let (snapshot, graphics, shell, label) = decode_snapshot(&pane.snapshot).with_context(|| format!("pane {pane_id}'s snapshot"))?;- received.push(Received { pane, fd, snapshot, graphics, shell });+ received.push(Received { pane, fd, snapshot, graphics, shell, label });write_message(&mut stream, &HandoffMessage::Ack)?;}HandoffMessage::Topology(list) => {@@ -840,10 +864,15 @@ fn install(committed: false,};let mut by_id: HashMap<PaneId, Arc<dyn Pane>> = HashMap::new();+ let mut labels = Vec::new();for item in received {let pane_id = item.pane.pane_id;+ let label = item.label.clone();let pane = adopt_pane(item, local_domain).with_context(|| format!("adopting pane {pane_id}"))?;+ if let Some(label) = label {+ labels.push((pane.pane_id(), label));+ }staged.panes.push(Arc::clone(&pane));by_id.insert(pane_id, pane);}@@ -855,6 +884,11 @@ fn install(// not drop what was adopted either.register(&staged.panes, built)?;staged.commit();+ // Labelled once the mux has the panes: it labels only its own.+ let mux = Mux::get();+ for (pane_id, label) in labels {+ mux.set_pane_label(pane_id, Some(&label));+ }unsafe { libc::fcntl(listener.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) };let listener = unsafe { wezterm_uds::UnixListener::from_raw_fd(listener.into_raw_fd()) };@@ -878,7 +912,7 @@ fn ensure_blocking(fd: &OwnedFd) -> anyhow::Result<()> {}fn adopt_pane(item: Received, domain_id: DomainId) -> anyhow::Result<Arc<dyn Pane>> {- let Received { pane, fd, snapshot, mut graphics, shell } = item;+ let Received { pane, fd, snapshot, mut graphics, shell, label: _ } = item;ensure_blocking(&fd).context("making an adopted pty blocking")?;let master = portable_pty::unix::master_from_raw_fd(fd, pane.tty_name.map(PathBuf::from))?;let writer = master.take_writer()?;@@ -1136,17 +1170,17 @@ mod tests {let snapshot = term.snapshot();let mut graphics = term.snapshot_kitty_graphics();let shell = term.snapshot_shell_commands();- let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();- assert_eq!(decode_snapshot(&bytes).unwrap(), (snapshot, None, None));+ let bytes = encode_snapshot(&snapshot, &graphics, &shell, None).unwrap();+ assert_eq!(decode_snapshot(&bytes).unwrap(), (snapshot, None, None, None));let snapshot = term.snapshot();graphics.playback.selections.push(wezterm_term::kitty_animation::KittyPlaybackEntry {image_id: 1,data_hash: [7; 32],animation: wezterm_term::kitty_animation::KittyAnimation::new([0, 40], 100),});- let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();+ let bytes = encode_snapshot(&snapshot, &graphics, &shell, None).unwrap();let decoded = decode_snapshot(&bytes).unwrap();- assert_eq!(decoded, (term.snapshot(), Some(graphics.clone()), None));+ assert_eq!(decoded, (term.snapshot(), Some(graphics.clone()), None, None));// Exactly the predecessor's decoder: it consumes the same prefix// and can adopt the terminal without understanding this extension.let raw = zstd::decode_all(&bytes[..]).unwrap();@@ -1169,8 +1203,8 @@ mod tests {for animated in [true, false] {if !animated { graphics.playback.selections.clear(); }graphics.virtual_images = virtuals.clone();- let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();- assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics.clone()), None));+ let bytes = encode_snapshot(&snapshot, &graphics, &shell, None).unwrap();+ assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics.clone()), None, None));let raw = zstd::decode_all(&bytes[..]).unwrap();let mut reader = &raw[..];let old = TerminalSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader)).unwrap();@@ -1183,8 +1217,8 @@ mod tests {for with_virtuals in [true, false] {if !with_virtuals { graphics.virtual_images.clear(); }graphics.image_numbers = vec![(12, 1), (12, 2), (13, 3)];- let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();- assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics.clone()), None));+ let bytes = encode_snapshot(&snapshot, &graphics, &shell, None).unwrap();+ assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics.clone()), None, None));let raw = zstd::decode_all(&bytes[..]).unwrap();let mut reader = &raw[..];let old = TerminalSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader)).unwrap();@@ -1199,8 +1233,8 @@ mod tests {placements: Vec::new(),cell_tags: [Vec::new(), Vec::new()],});- let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();- assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics), None));+ let bytes = encode_snapshot(&snapshot, &graphics, &shell, None).unwrap();+ assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics), None, None));let raw = zstd::decode_all(&bytes[..]).unwrap();let mut reader = &raw[..];let old = TerminalSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader)).unwrap();@@ -1233,10 +1267,10 @@ mod tests {animation: wezterm_term::kitty_animation::KittyAnimation::new([0, 40], 100),});}- let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();+ let bytes = encode_snapshot(&snapshot, &graphics, &shell, None).unwrap();assert_eq!(decode_snapshot(&bytes).unwrap(),- (term.snapshot(), kitty.then(|| graphics.clone()), Some(shell.clone()))+ (term.snapshot(), kitty.then(|| graphics.clone()), Some(shell.clone()), None));let raw = zstd::decode_all(&bytes[..]).unwrap();let mut reader = &raw[..];@@ -1249,6 +1283,37 @@ mod tests {}}+ #[test]+ fn a_pane_label_travels_last() {+ let mut term = wezterm_term::Terminal::new(+ TerminalSize { rows: 4, cols: 10, pixel_width: 80, pixel_height: 64, dpi: 96 },+ Arc::new(config::TermConfig::new()), "ThinkTerm", "test", Box::new(Vec::new()));+ let graphics = term.snapshot_kitty_graphics();+ // Alone, and after the shell's count.+ for reported in [false, true] {+ if reported {+ term.advance_bytes("\x1b]133;A;cl=m;aid=1\x07$ \x1b]133;B\x07true\r\n\x1b]133;C\x07");+ term.advance_bytes("\x1b]133;D;0;aid=1\x07");+ }+ let snapshot = term.snapshot();+ let shell = term.snapshot_shell_commands();+ assert_eq!(shell.reported, reported);+ let bytes = encode_snapshot(&snapshot, &graphics, &shell, Some("reviewer")).unwrap();+ assert_eq!(+ decode_snapshot(&bytes).unwrap(),+ (term.snapshot(), None, reported.then(|| shell.clone()), Some("reviewer".to_string()))+ );+ let raw = zstd::decode_all(&bytes[..]).unwrap();+ let mut reader = &raw[..];+ let old = TerminalSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader)).unwrap();+ assert_eq!(old, snapshot);+ assert!(reader.starts_with(if reported { SHELL_COMMANDS_TAG } else { PANE_LABEL_TAG }));+ assert!(decode_snapshot(&zstd::encode_all(&raw[..raw.len() - 1], 3).unwrap()).is_err());+ let mut trailing = raw; trailing.push(0);+ assert!(decode_snapshot(&zstd::encode_all(&trailing[..], 3).unwrap()).is_err());+ }+ }+#[test]fn relative_handoff_preserves_the_legacy_prefix_and_rebuilds_anonymous_parent_origins() {let make_term = || wezterm_term::Terminal::new(@@ -1265,8 +1330,8 @@ mod tests {let snapshot = terminal.snapshot();let graphics = terminal.snapshot_kitty_graphics();let shell = terminal.snapshot_shell_commands();- let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();- let (decoded, state, _) = decode_snapshot(&bytes).unwrap();+ let bytes = encode_snapshot(&snapshot, &graphics, &shell, None).unwrap();+ let (decoded, state, _, _) = decode_snapshot(&bytes).unwrap();assert_eq!(decoded, snapshot);assert_eq!(state.as_ref(), Some(&graphics));let raw = zstd::decode_all(&bytes[..]).unwrap();diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rsindex 3a91cf4c..0669f7d1 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -1690,6 +1690,7 @@ impl SessionHandler {tabs,tab_titles,window_titles,+ pane_labels: mux.pane_labels(),}))},send_response,@@ -2541,6 +2542,12 @@ impl SessionHandler {let mut lines_and_indices = vec![];for range in lines {+ // One that ends before it starts holds no+ // rows, and the screen's arithmetic would+ // overflow on it.+ if range.start > range.end {+ continue;+ }let (first_row, lines) = pane.get_lines(range);for (idx, mut line) in lines.into_iter().enumerate() {let stable_row = first_row + idx as StableRowIndex;@@ -2876,6 +2883,37 @@ impl SessionHandler {}).detach();}+ Pdu::PaneLabelChanged(PaneLabelChanged { pane_id, label }) => {+ spawn_into_main_thread(async move {+ catch(+ move || {+ let mux = Mux::get();+ mux.get_pane(pane_id)+ .ok_or_else(|| anyhow!("no such pane {pane_id}"))?;+ mux.set_pane_label(pane_id, label.as_deref());+ Ok(Pdu::UnitResponse(UnitResponse {}))+ },+ send_response,+ )+ })+ .detach();+ }+ Pdu::GetWorkspaceNames(GetWorkspaceNames {}) => {+ // The desktop's namer reads its own store, which its main+ // thread keeps.+ spawn_into_main_thread(async move {+ catch(+ move || {+ let workspaces = Mux::get().iter_workspaces();+ Ok(Pdu::GetWorkspaceNamesResponse(GetWorkspaceNamesResponse {+ names: crate::thinkterm_tree::workspace_names(&workspaces),+ }))+ },+ send_response,+ )+ })+ .detach();+ }Pdu::SetPalette(SetPalette { pane_id, palette }) => {spawn_into_main_thread(async move {catch(@@ -2947,6 +2985,9 @@ impl SessionHandler {| Pdu::GetPaneRunStateResponse { .. }| Pdu::PaneExited { .. }| Pdu::PaneAdded { .. }+ | Pdu::GetWorkspaceNamesResponse { .. }+ | Pdu::ClientJoined { .. }+ | Pdu::ClientLeft { .. }| Pdu::GetAgentStatusesResponse { .. }| Pdu::ForegroundProgramChanged { .. }| Pdu::GetForegroundProgramsResponse { .. }diff --git a/wezterm-mux-server-impl/src/thinkterm_layout.rs b/wezterm-mux-server-impl/src/thinkterm_layout.rsindex 5e2c36ca..9ee5e650 100644--- a/wezterm-mux-server-impl/src/thinkterm_layout.rs+++ b/wezterm-mux-server-impl/src/thinkterm_layout.rs@@ -64,6 +64,10 @@ struct StoredTerminalSpec {/// binaries after a downgrade.#[serde(default)]title: String,+ /// The label the pane was given; it is put back on the pane that+ /// replaces it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ label: Option<String>,}#[derive(Debug)]@@ -206,6 +210,7 @@ fn notification_changes_layout(notification: &MuxNotification) -> bool {| MuxNotification::PaneFocused(_)| MuxNotification::TabResized(_)| MuxNotification::WorkspaceRenamed { .. }+ | MuxNotification::PaneLabelChanged { .. }| MuxNotification::Empty)}@@ -417,6 +422,7 @@ fn collect_terminal_spec(cwd: working_dir_from_entry(entry),domain,title: entry.title.clone(),+ label: mux.pane_label(entry.pane_id),});}@@ -588,6 +594,11 @@ async fn restore_decoded_layout(&mut pane_map,).await?;+ for (saved, restored) in &pane_map {+ if let Some(label) = specs.get(saved).and_then(|spec| spec.label.as_deref()) {+ mux.set_pane_label(*restored, Some(label));+ }+ }if let Some(active) = active_pane_entry(node).and_then(|entry| pane_map.get(&entry.pane_id)).and_then(|pane_id| mux.get_pane(*pane_id))@@ -865,6 +876,7 @@ mod tests {cwd: Some("/tmp".to_string()),domain: Some("local".to_string()),title: "shell".to_string(),+ label: None,}],}}@@ -1075,6 +1087,7 @@ mod tests {cwd: None,domain: Some("local".to_string()),title: "shell".to_string(),+ label: None,};let merged = merge_workspace_snapshots("workspace-1",diff --git a/wezterm-mux-server-impl/src/thinkterm_tree.rs b/wezterm-mux-server-impl/src/thinkterm_tree.rsindex 0cabef55..5735dfb2 100644--- a/wezterm-mux-server-impl/src/thinkterm_tree.rs+++ b/wezterm-mux-server-impl/src/thinkterm_tree.rs@@ -112,6 +112,47 @@ pub fn snapshot() -> ThinkTermTree {TREE.lock().unwrap().clone()}+/// How a desktop names the workspaces of its own threads, as a project and+/// a thread. A desktop's threads live in its store, not in this tree, and+/// it serves the CLI from its own mux.+static WORKSPACE_NAMER: std::sync::OnceLock<fn(&str) -> Option<(String, String)>> =+ std::sync::OnceLock::new();++pub fn set_workspace_namer(namer: fn(&str) -> Option<(String, String)>) {+ let _ = WORKSPACE_NAMER.set(namer);+}++/// The project and thread behind each of `workspaces` that a thread+/// backs: the desktop's word for it first, then this tree's.+pub fn workspace_names(workspaces: &[String]) -> Vec<codec::WorkspaceName> {+ let tree = snapshot();+ workspaces+ .iter()+ .filter_map(|workspace| {+ let (project, thread) = WORKSPACE_NAMER+ .get()+ .and_then(|namer| namer(workspace))+ .or_else(|| tree_names_for_workspace(&tree, workspace))?;+ Some(codec::WorkspaceName {+ workspace: workspace.clone(),+ project,+ thread,+ })+ })+ .collect()+}++fn tree_names_for_workspace(tree: &ThinkTermTree, workspace: &str) -> Option<(String, String)> {+ tree.projects.iter().find_map(|project| {+ let thread = project.threads.iter().find(|thread| {+ thread.materialized_workspace_name.as_deref() == Some(workspace)+ || thread.planned_workspace_name.as_deref() == Some(workspace)+ || workspace_name(&project.id, &thread.id) == workspace+ })?;+ Some((project.name.clone(), thread.name.clone()))+ })+}+fn new_id(kind: &str) -> String {format!("{kind}-{}", Uuid::new_v4())}