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): report how pane programs and shell commands end
RoversX3b0bbd3e2a8f
diff --git a/codec/src/lib.rs b/codec/src/lib.rsindex 0c2da875..e7d80e78 100644--- a/codec/src/lib.rs+++ b/codec/src/lib.rs@@ -821,7 +821,10 @@ macro_rules! pdu {/// 78: Durable import request identities and reconnectable result queries./// 79: Agent statuses carry programs' own OSC 7501 reports and an error state;/// MarkProgramStatusSeen.-pub const CODEC_VERSION: usize = 79;+/// 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;// Defines the Pdu enum.// Each struct has an explicit identifying number.@@ -931,6 +934,11 @@ pdu! {GetImportSessionStatus: 109,GetImportSessionStatusResponse: 110,MarkProgramStatusSeen: 111,+ GetPaneRunState: 112,+ GetPaneRunStateResponse: 113,+ PaneExited: 114,+ PaneAdded: 115,+ SubscribeEvents: 116,}impl Pdu {@@ -1046,6 +1054,8 @@ impl Pdu {| Pdu::PaneFocused(PaneFocused { pane_id })| Pdu::AgentStatusChanged(AgentStatusChanged { pane_id, .. })| Pdu::ForegroundProgramChanged(ForegroundProgramChanged { pane_id, .. })+ | Pdu::PaneExited(PaneExited { pane_id, .. })+ | Pdu::PaneAdded(PaneAdded { pane_id })| Pdu::PaneRemoved(PaneRemoved { pane_id }) => Some(*pane_id),_ => None,}@@ -1876,6 +1886,40 @@ pub struct MarkProgramStatusSeen {pub pane_id: PaneId,}+/// Ask how far a pane's programs have got. A pane that has already gone is+/// answered from what the mux remembers of how its program ended.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]+pub struct GetPaneRunState {+ pub pane_id: PaneId,+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct GetPaneRunStateResponse {+ pub pane_id: PaneId,+ pub state: thinkterm_proto::PaneRunState,+}++/// Unilateral: the program `pane_id` started has ended. Sent before the+/// pane's `PaneRemoved`, when the pane closes because of it.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct PaneExited {+ pub pane_id: PaneId,+ pub exit: thinkterm_proto::PaneExit,+}++/// Unilateral, to a connection that sent `SubscribeEvents`: a pane appeared.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct PaneAdded {+ pub pane_id: PaneId,+}++/// 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.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]+pub struct SubscribeEvents {}+#[derive(Deserialize, Serialize, PartialEq, Debug)]pub struct SetPaneZoomed {pub containing_tab_id: TabId,@@ -3056,7 +3100,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, 79);+ assert_eq!(CODEC_VERSION, 80);use thinkterm_proto::{AgentEvidence, AgentState, AgentStatus, ProgramBlockedKind, ProgramReport,ProgramReportChild, ProgramReportState,@@ -3126,7 +3170,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, 79);+ assert_eq!(CODEC_VERSION, 80);use thinkterm_proto::ForegroundProgram;fn round_trip(pdu: &Pdu) -> Pdu {@@ -3224,11 +3268,75 @@ mod test {assert_eq!(bytes, [3, 0, 5, 0]);}+ #[test]+ fn run_state_protocol_round_trip_at_version_80() {+ // Same tripwire as the agent-status test above.+ assert_eq!(CODEC_VERSION, 80);+ use thinkterm_proto::{PaneExit, PaneRunState, ProgramState, ShellCommands};++ let exit = PaneExit {+ code: Some(2),+ signal: Some("Terminated".to_string()),+ };+ for pdu in [+ Pdu::GetPaneRunState(GetPaneRunState { pane_id: 7 }),+ Pdu::GetPaneRunStateResponse(GetPaneRunStateResponse {+ pane_id: 7,+ state: PaneRunState {+ program: ProgramState::Running,+ shell: ShellCommands {+ reported: true,+ finished: 12,+ running: true,+ last_exit: Some(1),+ },+ },+ }),+ Pdu::GetPaneRunStateResponse(GetPaneRunStateResponse {+ pane_id: 8,+ state: PaneRunState {+ program: ProgramState::Exited(exit.clone()),+ shell: ShellCommands::default(),+ },+ }),+ Pdu::GetPaneRunStateResponse(GetPaneRunStateResponse {+ pane_id: 9,+ state: PaneRunState::unknown(),+ }),+ Pdu::PaneExited(PaneExited { pane_id: 8, exit }),+ Pdu::PaneExited(PaneExited {+ pane_id: 11,+ exit: PaneExit {+ code: None,+ signal: None,+ },+ }),+ Pdu::PaneAdded(PaneAdded { pane_id: 10 }),+ Pdu::SubscribeEvents(SubscribeEvents {}),+ Pdu::NotifyAlert(NotifyAlert {+ pane_id: 7,+ alert: Alert::CommandFinished {+ exit_code: Some(130),+ },+ }),+ Pdu::NotifyAlert(NotifyAlert {+ pane_id: 7,+ alert: Alert::CommandFinished { exit_code: None },+ }),+ ] {+ let mut encoded = Vec::new();+ pdu.encode(&mut encoded, 0x80).unwrap();+ let decoded = Pdu::decode(encoded.as_slice()).unwrap();+ assert_eq!(decoded.serial, 0x80);+ assert_eq!(decoded.pdu, pdu);+ }+ }+#[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, 79);+ assert_eq!(CODEC_VERSION, 80);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 b942f63e..409c598a 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -70,6 +70,12 @@ pub enum MuxNotification {PaneOutput(PaneId),PaneAdded(PaneId),PaneRemoved(PaneId),+ /// The program the pane started has ended. Raised before the pane is+ /// removed, when it is removed because of it.+ PaneExited {+ pane_id: PaneId,+ exit: thinkterm_proto::PaneExit,+ },/// The mux that owns this pane re-classified its agent status; read/// the fresh value via `Pane::agent_status`.AgentStatusChanged(PaneId),@@ -473,8 +479,22 @@ pub struct Mux {num_panes_by_workspace: RwLock<HashMap<String, usize>>,main_thread_id: std::thread::ThreadId,agent: Option<AgentProxy>,+ /// How the last few panes' programs ended, so a `wait` that arrives+ /// after its pane closed still learns the status. Oldest first, at most+ /// `RECENT_PANE_EXITS` long, and each kept for `RECENT_PANE_EXIT_TTL`.+ recent_pane_exits:+ Mutex<std::collections::VecDeque<(PaneId, thinkterm_proto::PaneExit, Instant)>>,+ /// Panes whose exit is recorded but not yet announced. The announcement+ /// waits for the main thread, and goes out at once if the pane is+ /// 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>>,}+/// How many ended panes `Mux::recent_pane_exit` remembers, and for how long.+const RECENT_PANE_EXITS: usize = 128;+const RECENT_PANE_EXIT_TTL: Duration = Duration::from_secs(10 * 60);+#[derive(Default)]struct TabResizeNotificationState {depth: HashMap<TabId, usize>,@@ -1087,6 +1107,7 @@ fn read_from_pane_pty(};let heartbeat = parse_watchdog::register(pane_id);+ let exit_watch = pane.clone();std::thread::spawn({let dead = Arc::clone(&dead);let control = control.clone();@@ -1187,6 +1208,15 @@ fn read_from_pane_pty(.detach();}ExitBehavior::Close => {+ // The program's end usually closes the pty, and it is reaped a+ // moment after. Give it that moment: then the mux has the+ // status (`cli wait`, `PaneExited`) before it removes the pane.+ if let Some(pane) = exit_watch.upgrade() {+ let deadline = Instant::now() + EXIT_STATUS_GRACE;+ while !pane.is_dead() && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(5));+ }+ }promise::spawn::spawn_into_main_thread(async move {let mux = Mux::get();mux.remove_pane(pane_id);@@ -1198,6 +1228,9 @@ fn read_from_pane_pty(dead.store(true, Ordering::Relaxed);}+/// How long a pane closed by its pty's end waits for its program's status.+const EXIT_STATUS_GRACE: Duration = Duration::from_millis(250);+lazy_static::lazy_static! {static ref MUX: Mutex<Option<Arc<Mux>>> = Mutex::new(None);}@@ -1303,6 +1336,8 @@ impl Mux {#[cfg(test)]frontend_geometry_failures: Mutex::new(std::collections::VecDeque::new()),palette_advisories: Mutex::new(PaletteAdvisoryState::default()),+ recent_pane_exits: Mutex::new(std::collections::VecDeque::new()),+ unannounced_pane_exits: Mutex::new(HashMap::new()),identity: RwLock::new(None),num_panes_by_workspace: RwLock::new(HashMap::new()),main_thread_id: std::thread::current().id(),@@ -2755,6 +2790,58 @@ impl Mux {self.panes.read().get(&pane_id).map(Arc::clone)}+ /// The program `pane_id` started has ended: remember how, for+ /// `recent_pane_exit`, and tell the subscribers. Callable from any+ /// thread, and with any lock held: the news is sent later, from the main+ /// thread, and before the pane's removal if that comes first.+ pub fn record_pane_exit(&self, pane_id: PaneId, exit: thinkterm_proto::PaneExit) {+ {+ let now = Instant::now();+ let mut recent = self.recent_pane_exits.lock();+ recent.retain(|(id, _, at)| {+ *id != pane_id && now.duration_since(*at) < RECENT_PANE_EXIT_TTL+ });+ if recent.len() >= RECENT_PANE_EXITS {+ recent.pop_front();+ }+ recent.push_back((pane_id, exit.clone(), now));+ // Keep pending payloads independently of bounded exit history.+ self.unannounced_pane_exits.lock().insert(pane_id, exit);+ }+ promise::spawn::spawn_into_main_thread(async move {+ if let Some(mux) = Mux::try_get() {+ mux.announce_pane_exit(pane_id, false);+ }+ })+ .detach();+ }++ /// Send the news of a recorded exit, once: from the pane's removal,+ /// just before its `PaneRemoved`, or later from the main thread. Later+ /// is too late for a pane already removed -- every client has dropped+ /// it -- and `recent_pane_exit` still has the status for `cli wait`.+ fn announce_pane_exit(&self, pane_id: PaneId, removing: bool) {+ let exit = match self.unannounced_pane_exits.lock().remove(&pane_id) {+ Some(exit) => exit,+ None => return,+ };+ if !removing && !self.panes.read().contains_key(&pane_id) {+ return;+ }+ self.notify(MuxNotification::PaneExited { pane_id, exit });+ }++ /// How the program of a pane that has ended exited, while it is among+ /// the last `RECENT_PANE_EXITS` to have done so, and recently.+ pub fn recent_pane_exit(&self, pane_id: PaneId) -> Option<thinkterm_proto::PaneExit> {+ self.recent_pane_exits+ .lock()+ .iter()+ .rev()+ .find(|(id, _, at)| *id == pane_id && at.elapsed() < RECENT_PANE_EXIT_TTL)+ .map(|(_, exit, _)| exit.clone())+ }+pub fn get_tab(&self, tab_id: TabId) -> Option<Arc<Tab>> {self.tabs.read().get(&tab_id).map(Arc::clone)}@@ -2813,6 +2900,8 @@ impl Mux {if let Some(pane) = removed {log::debug!("killing pane {}", pane_id);pane.kill();+ // How its program ended goes out first, if that is still to go.+ self.announce_pane_exit(pane_id, true);self.notify(MuxNotification::PaneRemoved(pane_id));changed = true;}@@ -4135,6 +4224,95 @@ mod tests {assert_eq!(quiet.frontend_access_state().generation, before.generation);}+ #[test]+ fn pending_exit_notifications_outlive_history_eviction_and_expiry() {+ let _executor = promise::spawn::SimpleExecutor::new();+ let mux = Mux::new(None);+ let announced = Arc::new(Mutex::new(Vec::new()));+ {+ let announced = Arc::clone(&announced);+ mux.subscribe(move |n| {+ if let MuxNotification::PaneExited { pane_id, exit } = n {+ announced.lock().push((pane_id, exit.code));+ }+ true+ });+ }+ let count = RECENT_PANE_EXITS + 2;+ for pane_id in 0..count {+ mux.record_pane_exit(+ pane_id,+ thinkterm_proto::PaneExit {+ code: Some(pane_id as u32),+ signal: None,+ },+ );+ }+ assert_eq!(mux.recent_pane_exit(0), None);+ // Expiry must not lose the pending payloads either.+ for (_, _, at) in mux.recent_pane_exits.lock().iter_mut() {+ *at = Instant::now() - RECENT_PANE_EXIT_TTL;+ }+ for pane_id in 0..count {+ mux.announce_pane_exit(pane_id, true);+ mux.announce_pane_exit(pane_id, true);+ }+ let expected: Vec<_> = (0..count).map(|id| (id, Some(id as u32))).collect();+ assert_eq!(*announced.lock(), expected);+ assert!(mux.unannounced_pane_exits.lock().is_empty());+ }++ #[test]+ fn recent_pane_exits_are_bounded_and_keep_the_latest() {+ // Announcements are queued for the main thread; a scheduler that+ // merely holds them is enough.+ let _executor = promise::spawn::SimpleExecutor::new();+ let mux = Mux::new(None);+ let announced = Arc::new(Mutex::new(Vec::new()));+ {+ let announced = Arc::clone(&announced);+ mux.subscribe(move |n| {+ if let MuxNotification::PaneExited { pane_id, .. } = n {+ announced.lock().push(pane_id);+ }+ true+ });+ }+ let exit = |code| thinkterm_proto::PaneExit {+ code: Some(code),+ signal: None,+ };+ for pane_id in 0..RECENT_PANE_EXITS + 2 {+ mux.record_pane_exit(pane_id, exit(pane_id as u32));+ }+ assert!(+ announced.lock().is_empty(),+ "never from inside the recording"+ );+ // What removing the pane does: the news goes out then, and only once.+ mux.announce_pane_exit(5, true);+ mux.announce_pane_exit(5, true);+ assert_eq!(*announced.lock(), vec![5]);+ // Too late for a pane that is no longer in the mux.+ mux.announce_pane_exit(6, false);+ assert_eq!(*announced.lock(), vec![5]);+ assert_eq!(+ mux.recent_pane_exit(6),+ Some(exit(6)),+ "still there for `wait`"+ );++ assert_eq!(mux.recent_pane_exits.lock().len(), RECENT_PANE_EXITS);+ // The oldest two made room.+ assert_eq!(mux.recent_pane_exit(0), None);+ assert_eq!(mux.recent_pane_exit(1), None);+ assert_eq!(mux.recent_pane_exit(2), Some(exit(2)));+ // A pane that ends again (a held pane respawned) has one entry.+ mux.record_pane_exit(2, exit(9));+ assert_eq!(mux.recent_pane_exit(2), Some(exit(9)));+ assert_eq!(mux.recent_pane_exits.lock().len(), RECENT_PANE_EXITS);+ }+#[test]fn unclaimed_handoff_lease_belongs_to_the_first_renderer() {let mux = Mux::new(None);diff --git a/mux/src/localpane.rs b/mux/src/localpane.rsindex 69a0c504..ac5d22db 100644--- a/mux/src/localpane.rs+++ b/mux/src/localpane.rs@@ -339,6 +339,11 @@ pub struct LocalPane {/// The progress the terminal last reported, for `get_progress` while/// the parser holds the terminal.last_progress: Mutex<Progress>,+ /// What the shell last reported about its commands, for `run_state`+ /// while the parser holds the terminal.+ last_shell_commands: Mutex<wezterm_term::ShellCommands>,+ /// How the program ended, once `is_dead` has seen it end.+ exit: Mutex<Option<thinkterm_proto::PaneExit>>,}#[async_trait(?Send)]@@ -582,12 +587,8 @@ impl Pane for LocalPane {};if let Some(status) = status {- let success = match status.success() {- true => true,- false => configuration()- .clean_exit_codes- .contains(&status.exit_code()),- };+ *self.exit.lock() = Some(pane_exit(&status));+ let success = exited_cleanly(&status, &configuration().clean_exit_codes);match (self.exit_behavior()@@ -1137,6 +1138,34 @@ impl Pane for LocalPane {term.get_semantic_zones()}+ async fn run_state(&self) -> anyhow::Result<thinkterm_proto::PaneRunState> {+ use thinkterm_proto::{PaneRunState, ProgramState, ShellCommands};+ // Asked over and over by a waiting `cli wait`, on the main thread:+ // never wait for the parser.+ let shell = match self.terminal.try_lock() {+ Some(term) => term.shell_commands(),+ None => *self.last_shell_commands.lock(),+ };+ let program = match &*self.process.lock() {+ ProcessState::Running { .. } => ProgramState::Running,+ ProcessState::DeadPendingClose { .. } | ProcessState::Dead => {+ match self.exit.lock().clone() {+ Some(exit) => ProgramState::Exited(exit),+ None => ProgramState::Unknown,+ }+ }+ };+ Ok(PaneRunState {+ program,+ shell: ShellCommands {+ reported: shell.reported,+ finished: shell.finished,+ running: shell.running,+ last_exit: shell.last_exit,+ },+ })+ }+async fn search(&self,pattern: Pattern,@@ -1449,12 +1478,30 @@ impl AlertHandler for LocalPaneNotifHandler {/// to be blocked in read even after the child process has died./// We need to wake up and notice that the child terminated in order/// for our state to wind down.+fn pane_exit(status: &ExitStatus) -> thinkterm_proto::PaneExit {+ thinkterm_proto::PaneExit {+ code: status.exit_code_if_known(),+ signal: status.signal().map(str::to_string),+ }+}++/// Whether `status` is a clean exit for `exit_behavior`. A pane a handoff+/// adopted ends with no status to judge by, and closes as though it exited+/// cleanly: a plain `exit` there should not read as a failure.+fn exited_cleanly(status: &ExitStatus, clean_exit_codes: &[u32]) -> bool {+ status.success()+ || status+ .exit_code_if_known()+ .map_or(true, |code| clean_exit_codes.contains(&code))+}+/// This block schedules a background thread to wait for the child/// to terminate, and then nudge the muxer to check for dead processes./// Without this, typing `exit` in `cmd.exe` would keep the pane around/// until something else triggered the mux to prune dead processes.fn split_child(mut process: Box<dyn Child>,+ pane_id: PaneId,) -> (Receiver<IoResult<ExitStatus>>,Box<dyn ChildKiller + Sync>,@@ -1467,6 +1514,12 @@ fn split_child(std::thread::spawn(move || {let status = process.wait();+ // Given to the mux as the program is reaped, not when the pane is+ // next asked whether it is dead: a pane removed by then is never+ // asked, and `cli wait` would never learn how it ended.+ if let (Ok(status), Some(mux)) = (&status, Mux::try_get()) {+ mux.record_pane_exit(pane_id, pane_exit(status));+ }tx.try_send(status).ok();promise::spawn::spawn_into_main_thread(async move {let mux = Mux::get();@@ -1532,13 +1585,23 @@ impl LocalPane {/// Everything the terminal remembers. Take it with the reader paused/// (`crate::pause_pane_reader`), or it is a moment behind the pty.- pub fn snapshot_terminal(&self) -> (wezterm_term::TerminalSnapshot, wezterm_term::KittyGraphicsSnapshot) {+ pub fn snapshot_terminal(+ &self,+ ) -> (+ wezterm_term::TerminalSnapshot,+ wezterm_term::KittyGraphicsSnapshot,+ wezterm_term::ShellCommandsSnapshot,+ ) {let mut term = self.terminal.lock();// A resize, configuration or focus noted while the parser held// the terminal is the parser's to apply; with the reader parked it// never will, so apply it here or the snapshot lags the pty.self.apply_pending_and_store(&mut term);- (term.snapshot(), term.snapshot_kitty_graphics())+ (+ term.snapshot(),+ term.snapshot_kitty_graphics(),+ term.snapshot_shell_commands(),+ )}pub fn new(@@ -1550,7 +1613,7 @@ impl LocalPane {domain_id: DomainId,command_description: String,) -> Self {- let (process, signaller, pid) = split_child(process);+ let (process, signaller, pid) = split_child(process, pane_id);terminal.set_device_control_handler(Box::new(LocalPaneDCSHandler {pane_id,@@ -1567,6 +1630,8 @@ impl LocalPane {}let last_summary = Mutex::new(PaneSummary::from_terminal(&mut terminal, false));let config = Mutex::new(terminal.get_config());+ // Not zero for a terminal a handoff restored.+ let last_shell_commands = Mutex::new(terminal.shell_commands());Self {pane_id,@@ -1593,6 +1658,8 @@ impl LocalPane {pending_seen: Mutex::new(false),shell_idle: Mutex::new(None),last_progress: Mutex::new(Progress::default()),+ last_shell_commands,+ exit: Mutex::new(None),}}@@ -1626,6 +1693,7 @@ impl LocalPane {self.apply_pending_focus(term);self.store_summary(term);*self.last_progress.lock() = term.get_progress();+ *self.last_shell_commands.lock() = term.shell_commands();}fn anything_pending(&self) -> bool {@@ -1834,6 +1902,25 @@ mod summary_tests {use portable_pty::PtySize;use std::sync::Mutex as StdMutex;+ #[test]+ fn pane_exit_preserves_unknown_and_known_statuses() {+ assert_eq!(pane_exit(&ExitStatus::unknown()).code, None);+ assert_eq!(pane_exit(&ExitStatus::with_exit_code(0)).code, Some(0));+ assert_eq!(pane_exit(&ExitStatus::with_exit_code(7)).code, Some(7));+ let killed = pane_exit(&ExitStatus::with_signal("Terminated"));+ assert_eq!(killed.code, Some(1));+ assert_eq!(killed.signal.as_deref(), Some("Terminated"));+ }++ #[test]+ fn an_unknown_status_closes_like_a_clean_exit() {+ assert!(exited_cleanly(&ExitStatus::unknown(), &[]));+ assert!(exited_cleanly(&ExitStatus::with_exit_code(0), &[]));+ assert!(!exited_cleanly(&ExitStatus::with_exit_code(3), &[]));+ assert!(exited_cleanly(&ExitStatus::with_exit_code(3), &[3]));+ assert!(!exited_cleanly(&ExitStatus::with_signal("Terminated"), &[]));+ }+/// A child that never exits, so the waiter thread `LocalPane::new`/// spawns sits on it for the life of the test.#[derive(Debug)]diff --git a/mux/src/pane.rs b/mux/src/pane.rsindex 97d3a88c..ba071292 100644--- a/mux/src/pane.rs+++ b/mux/src/pane.rs@@ -508,6 +508,13 @@ pub trait Pane: Downcast + Send + Sync {Ok(vec![])}+ /// How far the pane's programs have got: whether the program it+ /// started is still running, and what its shell has reported about+ /// its commands. A mirror asks the mux that owns the pane.+ async fn run_state(&self) -> anyhow::Result<thinkterm_proto::PaneRunState> {+ Ok(thinkterm_proto::PaneRunState::unknown())+ }+/// Retrieve the set of semantic zonesfn get_semantic_zones(&self) -> anyhow::Result<Vec<SemanticZone>> {Ok(vec![])diff --git a/pty/src/lib.rs b/pty/src/lib.rsindex 27ac4168..9e56c0de 100644--- a/pty/src/lib.rs+++ b/pty/src/lib.rs@@ -168,34 +168,50 @@ pub trait SlavePty {/// Represents the exit status of a child process.#[derive(Debug, Clone)]pub struct ExitStatus {- code: u32,+ code: Option<u32>,signal: Option<String>,}impl ExitStatus {/// Construct an ExitStatus from a process return codepub fn with_exit_code(code: u32) -> Self {- Self { code, signal: None }+ Self {+ code: Some(code),+ signal: None,+ }}/// Construct an ExitStatus from a signal namepub fn with_signal(signal: &str) -> Self {Self {- code: 1,+ code: Some(1),signal: Some(signal.to_string()),}}- /// Returns true if the status indicates successful completion+ /// The process ended, but its actual exit status is unavailable.+ pub fn unknown() -> Self {+ Self {+ code: None,+ signal: None,+ }+ }++ /// Returns true if the status confirms successful completionpub fn success(&self) -> bool {match self.signal {- None => self.code == 0,+ None => self.code == Some(0),Some(_) => false,}}- /// Returns the exit code that this ExitStatus was constructed with+ /// Returns the exit code, or 1 if the actual status is unavailable.pub fn exit_code(&self) -> u32 {+ self.code.unwrap_or(1)+ }++ /// Returns the actual exit code, when it is known.+ pub fn exit_code_if_known(&self) -> Option<u32> {self.code}@@ -221,7 +237,7 @@ impl From<std::process::ExitStatus> for ExitStatus {};return ExitStatus {- code: status.code().map(|c| c as u32).unwrap_or(1),+ code: Some(status.code().map(|c| c as u32).unwrap_or(1)),signal: Some(signal),};}@@ -233,7 +249,10 @@ impl From<std::process::ExitStatus> for ExitStatus {.map(|c| c as u32).unwrap_or_else(|| if status.success() { 0 } else { 1 });- ExitStatus { code, signal: None }+ ExitStatus {+ code: Some(code),+ signal: None,+ }}}@@ -244,7 +263,10 @@ impl std::fmt::Display for ExitStatus {} else {match &self.signal {Some(sig) => write!(fmt, "Terminated by {}", sig),- None => write!(fmt, "Exited with code {}", self.code),+ None => match self.code {+ Some(code) => write!(fmt, "Exited with code {}", code),+ None => write!(fmt, "Exited with unknown status"),+ },}}}@@ -293,9 +315,9 @@ impl Child for std::process::Child {/// A process this process did not spawn: the child of a mux server that/// handed its pane over. Only a parent can wait on a process, so its exit/// is noticed by asking the kernel whether the pid still exists, four-/// times a second; the exit status is not knowable that way and reads as-/// success. (A pid answers as long as it is a zombie, so whoever inherits-/// the process -- init, or a subreaper -- has to reap it.)+/// times a second; the exit status is not knowable that way and is+/// reported as unknown. (A pid answers as long as it is a zombie, so+/// whoever inherits the process -- init, or a subreaper -- has to reap it.)#[cfg(unix)]pub fn adopted_child(pid: u32) -> Box<dyn Child + Send + Sync> {Box::new(AdoptedChild::new(pid))@@ -374,7 +396,7 @@ fn pidfd_open(_pid: u32) -> Option<std::os::fd::OwnedFd> {impl Child for AdoptedChild {fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {Ok(if self.exited(0) {- Some(ExitStatus::with_exit_code(0))+ Some(ExitStatus::unknown())} else {None})@@ -388,7 +410,7 @@ impl Child for AdoptedChild {std::thread::sleep(std::time::Duration::from_millis(250));}}- Ok(ExitStatus::with_exit_code(0))+ Ok(ExitStatus::unknown())}fn process_id(&self) -> Option<u32> {@@ -551,8 +573,15 @@ mod adopted_child_tests {let reaper = std::thread::spawn(move || real.wait());adopted.kill().expect("SIGHUP");let status = adopted.wait().expect("wait");- assert!(status.success(), "the status of an adopted process reads as success");+ assert!(+ !status.success(),+ "an unavailable status must not claim success"+ );+ assert_eq!(status.exit_code_if_known(), None);assert!(reaper.join().unwrap().is_ok());- assert!(adopted.try_wait().unwrap().is_some(), "gone");+ assert_eq!(+ adopted.try_wait().unwrap().unwrap().exit_code_if_known(),+ None+ );}}diff --git a/term/src/terminal.rs b/term/src/terminal.rsindex 6fd1528c..b0dee4df 100644--- a/term/src/terminal.rs+++ b/term/src/terminal.rs@@ -71,6 +71,27 @@ pub enum Alert {OutputSinceFocusLost,/// A change to the progress bar stateProgress(Progress),+ /// The shell reported (OSC 133) that a command finished, with the+ /// status it gave, or `None` when a new prompt ended the command+ /// without one.+ CommandFinished {+ exit_code: Option<i32>,+ },+}++/// How far the shell in a terminal has got, as far as it says with the+/// OSC 133 semantic prompt marks. All zero until the first mark arrives.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]+pub struct ShellCommands {+ /// The shell has sent a mark, so the rest of this means something.+ pub reported: bool,+ /// Commands finished since the first mark. The shell integration also+ /// reports one for a prompt answered with an empty line.+ pub finished: u64,+ /// A command has started (`133;C`) and not yet finished.+ pub running: bool,+ /// The status the last finished command reported.+ pub last_exit: Option<i32>,}pub trait AlertHandler: Send + Sync {diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rsindex 1a7ba817..f467d0e3 100644--- a/term/src/terminalstate/mod.rs+++ b/term/src/terminalstate/mod.rs@@ -323,6 +323,12 @@ pub struct TerminalState {clear_semantic_attribute_on_newline: bool,+ /// What the shell has said with OSC 133 about its commands.+ shell_commands: ShellCommands,+ /// The aid of the shell `shell_commands` follows. See+ /// `counts_shell_mark`.+ shell_aid: Option<String>,+/// If true, writing a character inserts a new cellinsert: bool,@@ -639,6 +645,8 @@ impl TerminalState {left_and_right_margin_mode: false,wrap_next: false,clear_semantic_attribute_on_newline: false,+ shell_commands: ShellCommands::default(),+ shell_aid: None,// We default auto wrap to true even though the default for// a dec terminal is false, because it is more useful this way.dec_auto_wrap: true,@@ -1218,6 +1226,49 @@ impl TerminalState {&self.user_vars}+ /// What the shell has said with OSC 133 about its commands.+ pub fn shell_commands(&self) -> ShellCommands {+ self.shell_commands+ }++ /// Whether a mark from the shell named `aid` counts. The first shell to+ /// name itself is the one followed, so that a shell one of its commands+ /// starts (ssh, docker exec, a subshell) is not taken for it; a+ /// different one at an idle prompt has replaced it. Marks naming no+ /// shell always count.+ fn counts_shell_mark(&mut self, aid: Option<&str>) -> bool {+ self.shell_commands.reported = true;+ let Some(aid) = aid else {+ return true;+ };+ match &self.shell_aid {+ Some(owner) if owner == aid => true,+ Some(_) if self.shell_commands.running => false,+ _ => {+ self.shell_aid = Some(aid.to_string());+ true+ }+ }+ }++ /// A prompt began. A command still marked as running has ended without+ /// the shell reporting its status.+ fn shell_prompt_started(&mut self, aid: Option<&str>) {+ if self.counts_shell_mark(aid) && self.shell_commands.running {+ self.finish_shell_command(None);+ }+ }++ fn finish_shell_command(&mut self, exit_code: Option<i32>) {+ self.shell_commands.reported = true;+ self.shell_commands.running = false;+ self.shell_commands.finished += 1;+ self.shell_commands.last_exit = exit_code;+ if let Some(handler) = self.alert_handler.as_mut() {+ handler.alert(Alert::CommandFinished { exit_code });+ }+ }+fn clear_semantic_attribute_due_to_movement(&mut self) {if self.clear_semantic_attribute_on_newline {self.clear_semantic_attribute_on_newline = false;diff --git a/term/src/terminalstate/performer.rs b/term/src/terminalstate/performer.rsindex 93e71e6d..79f918b8 100644--- a/term/src/terminalstate/performer.rs+++ b/term/src/terminalstate/performer.rs@@ -1057,45 +1057,58 @@ impl<'a> Performer<'a> {self.fresh_line();}OperatingSystemCommand::FinalTermSemanticPrompt(- FinalTermSemanticPrompt::FreshLineAndStartPrompt { .. },+ FinalTermSemanticPrompt::FreshLineAndStartPrompt { aid, .. },) => {self.fresh_line();self.pen.set_semantic_type(SemanticType::Prompt);// A new shell prompt: whatever filed OSC 7501 records has// finished, and only its unseen results remain.self.program_status.end_of_program();+ self.shell_prompt_started(aid.as_deref());}OperatingSystemCommand::FinalTermSemanticPrompt(FinalTermSemanticPrompt::StartPrompt(_),) => {self.pen.set_semantic_type(SemanticType::Prompt);+ // Without an aid it could be a nested shell's; the A or N+ // before it settles that.+ self.shell_commands.reported = true;}OperatingSystemCommand::FinalTermSemanticPrompt(- FinalTermSemanticPrompt::MarkEndOfCommandWithFreshLine { .. },+ FinalTermSemanticPrompt::MarkEndOfCommandWithFreshLine { aid, .. },) => {self.fresh_line();self.pen.set_semantic_type(SemanticType::Prompt);+ self.shell_prompt_started(aid.as_deref());}OperatingSystemCommand::FinalTermSemanticPrompt(FinalTermSemanticPrompt::MarkEndOfPromptAndStartOfInputUntilNextMarker { .. },) => {self.pen.set_semantic_type(SemanticType::Input);+ self.shell_commands.reported = true;}OperatingSystemCommand::FinalTermSemanticPrompt(FinalTermSemanticPrompt::MarkEndOfPromptAndStartOfInputUntilEndOfLine { .. },) => {self.pen.set_semantic_type(SemanticType::Input);self.clear_semantic_attribute_on_newline = true;+ self.shell_commands.reported = true;}OperatingSystemCommand::FinalTermSemanticPrompt(FinalTermSemanticPrompt::MarkEndOfInputAndStartOfOutput { .. },) => {self.pen.set_semantic_type(SemanticType::Output);+ self.shell_commands.reported = true;+ self.shell_commands.running = true;}OperatingSystemCommand::FinalTermSemanticPrompt(- FinalTermSemanticPrompt::CommandStatus { .. },- ) => {}+ FinalTermSemanticPrompt::CommandStatus { status, aid },+ ) => {+ if self.counts_shell_mark(aid.as_deref()) {+ self.finish_shell_command(Some(status));+ }+ }OperatingSystemCommand::SystemNotification(message) => {if let Some(handler) = self.alert_handler.as_mut() {diff --git a/term/src/terminalstate/snapshot.rs b/term/src/terminalstate/snapshot.rsindex 5045b3f7..7e9a5bcc 100644--- a/term/src/terminalstate/snapshot.rs+++ b/term/src/terminalstate/snapshot.rs@@ -179,6 +179,42 @@ pub struct KittySnapshot {pub transmission_in_progress: bool,}+/// How far the shell has got by its OSC 133 marks (see+/// [`crate::ShellCommands`]), and which shell's marks are followed. Kept out+/// of [`TerminalSnapshot`] so that its shape, which every predecessor's+/// decoder expects, stays as it is: a handoff carries this beside it.+#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]+pub struct ShellCommandsSnapshot {+ pub reported: bool,+ pub finished: u64,+ pub running: bool,+ pub last_exit: Option<i32>,+ pub aid: Option<String>,+}++impl TerminalState {+ pub fn snapshot_shell_commands(&self) -> ShellCommandsSnapshot {+ let commands = self.shell_commands;+ ShellCommandsSnapshot {+ reported: commands.reported,+ finished: commands.finished,+ running: commands.running,+ last_exit: commands.last_exit,+ aid: self.shell_aid.clone(),+ }+ }++ pub fn restore_shell_commands(&mut self, snapshot: ShellCommandsSnapshot) {+ self.shell_commands = crate::ShellCommands {+ reported: snapshot.reported,+ finished: snapshot.finished,+ running: snapshot.running,+ last_exit: snapshot.last_exit,+ };+ self.shell_aid = snapshot.aid;+ }+}+/// `termwiz::input::KeyboardEncoding` without serde; the kitty flags travel/// as their bits.#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]diff --git a/term/src/test/mod.rs b/term/src/test/mod.rsindex 1ee57932..8bb80ca4 100644--- a/term/src/test/mod.rs+++ b/term/src/test/mod.rs@@ -333,6 +333,87 @@ fn program_status_reports_are_answered_kept_and_retired() {assert_eq!(term.program_status(usize::MAX), Default::default());}+#[test]+fn shell_commands_follow_the_osc_133_marks() {+ struct Alerts(Arc<Mutex<Vec<Alert>>>);+ impl AlertHandler for Alerts {+ fn alert(&mut self, alert: Alert) {+ self.0.lock().unwrap().push(alert);+ }+ }++ let mut term = TestTerm::new(4, 20, 0);+ let alerts = Arc::new(Mutex::new(vec![]));+ term.set_notification_handler(Box::new(Alerts(Arc::clone(&alerts))));+ assert_eq!(term.shell_commands(), ShellCommands::default());++ // The first prompt: the shell reports, and nothing has finished yet.+ term.print("\x1b]133;A;cl=m;aid=1\x07$ \x1b]133;B\x07");+ assert_eq!(+ term.shell_commands(),+ ShellCommands {+ reported: true,+ ..Default::default()+ }+ );++ // A command runs, and its status comes before the next prompt.+ term.print("make\r\n\x1b]133;C;\x07");+ assert!(term.shell_commands().running);+ term.print("error\r\n\x1b]133;D;2;aid=1\x07\x1b]133;A;cl=m;aid=1\x07");+ assert_eq!(+ term.shell_commands(),+ ShellCommands {+ reported: true,+ finished: 1,+ running: false,+ last_exit: Some(2),+ }+ );++ // A shell that reports no status: the next prompt ends the command.+ term.print("\x1b]133;C;\x07\x1b]133;A\x07");+ assert_eq!(+ term.shell_commands(),+ ShellCommands {+ reported: true,+ finished: 2,+ running: false,+ last_exit: None,+ }+ );++ // A command that starts another shell (ssh, a subshell): its prompts+ // and statuses are not the outer shell's.+ term.print("\x1b]133;A;aid=1\x07\x1b]133;C;\x07");+ term.print("\x1b]133;A;cl=m;aid=2\x07\x1b]133;P;k=i\x07% \x1b]133;B\x07");+ term.print("\x1b]133;C;\x07\x1b]133;D;0;aid=2\x07\x1b]133;A;aid=2\x07");+ assert!(+ term.shell_commands().running,+ "still inside the outer command"+ );+ assert_eq!(term.shell_commands().finished, 2);+ term.print("\x1b]133;D;5;aid=1\x07\x1b]133;A;aid=1\x07");+ assert_eq!(term.shell_commands().finished, 3);+ assert_eq!(term.shell_commands().last_exit, Some(5));++ // Another shell at an idle prompt has taken over (`exec`).+ term.print("\x1b]133;A;aid=3\x07\x1b]133;C;\x07\x1b]133;D;4;aid=3\x07");+ assert_eq!(term.shell_commands().finished, 4);+ assert_eq!(term.shell_commands().last_exit, Some(4));++ let finished: Vec<_> = alerts+ .lock()+ .unwrap()+ .iter()+ .filter_map(|alert| match alert {+ Alert::CommandFinished { exit_code } => Some(*exit_code),+ _ => None,+ })+ .collect();+ assert_eq!(finished, vec![Some(2), None, Some(5), Some(4)]);+}+#[test]fn application_palette_override_tracks_osc_set_query_and_reset() {let mut term = TestTerm::new(4, 8, 0);diff --git a/term/src/test/snapshot.rs b/term/src/test/snapshot.rsindex 200a968c..41edce5e 100644--- a/term/src/test/snapshot.rs+++ b/term/src/test/snapshot.rs@@ -418,3 +418,28 @@ fn restore_applies_agent_budgets_without_changing_other_user_variables() {normal);}++#[test]+fn the_shell_command_count_survives_a_restore() {+ let mut original = terminal(10);+ // One command finished, and a second one -- a shell of its own -- runs.+ original.advance_bytes("\x1b]133;A;cl=m;aid=1\x07$ \x1b]133;B\x07true\r\n\x1b]133;C\x07");+ original.advance_bytes("\x1b]133;D;0;aid=1\x07\x1b]133;A;cl=m;aid=1\x07$ \x1b]133;B\x07");+ original.advance_bytes("bash\r\n\x1b]133;C\x07");+ let shell = original.snapshot_shell_commands();+ assert!(shell.reported && shell.running);+ assert_eq!(shell.finished, 1);++ let mut copy = restored(original.snapshot(), 10);+ copy.restore_shell_commands(shell.clone());+ assert_eq!(copy.shell_commands(), original.shell_commands());+ assert_eq!(copy.snapshot_shell_commands(), shell);++ // The inner shell's marks are still told from the outer one's.+ copy.advance_bytes("\x1b]133;D;0;aid=2\x07\x1b]133;A;cl=m;aid=2\x07");+ assert!(copy.shell_commands().running);+ assert_eq!(copy.shell_commands().finished, 1);+ copy.advance_bytes("\x1b]133;D;9;aid=1\x07");+ assert_eq!(copy.shell_commands().finished, 2);+ assert_eq!(copy.shell_commands().last_exit, Some(9));+}diff --git a/thinkterm-proto/src/lib.rs b/thinkterm-proto/src/lib.rsindex 44f52eb3..9952589e 100644--- a/thinkterm-proto/src/lib.rs+++ b/thinkterm-proto/src/lib.rs@@ -21,6 +21,7 @@ pub mod layout;pub mod pane;pub mod program;pub mod renderable;+pub mod run_state;pub mod split;pub use agent::{@@ -34,6 +35,7 @@ pub use layout::{PaneEntry, PaneNode, PaneStackEntry, SerdeUrl};pub use pane::{Pattern, SearchResult};pub use program::ForegroundProgram;pub use renderable::{RenderableDimensions, StableCursorPosition};+pub use run_state::{PaneExit, PaneRunState, ProgramState, ShellCommands};pub use split::{SplitDirection, SplitDirectionAndSize, SplitRequest, SplitSize};pub type WindowId = usize;diff --git a/thinkterm-proto/src/run_state.rs b/thinkterm-proto/src/run_state.rsnew file mode 100644index 00000000..440e0556--- /dev/null+++ b/thinkterm-proto/src/run_state.rs@@ -0,0 +1,60 @@+//! How far a pane's programs have got.+//!+//! Whether the program the pane started is still running or how it ended,+//! and -- when the pane's shell reports it with OSC 133 -- how many+//! commands it has finished and how the last one ended. `thinkterm cli+//! wait` and `send-key --wait` read it; the mux that owns the pane answers.+//!+//! Varbincode is positional: **field order is the wire contract**. Bump the+//! codec version when changing anything here.++use serde::{Deserialize, Serialize};++/// How the program a pane started ended.+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]+pub struct PaneExit {+ /// The exit code. A program ended by a signal has the code its+ /// platform reports for that (1 on unix). None means the process+ /// ended but its status is unavailable, as after live handoff.+ pub code: Option<u32>,+ /// The signal that ended it, when one did.+ pub signal: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]+pub enum ProgramState {+ Running,+ Exited(PaneExit),+ /// This kind of pane cannot say, or it ended without its status being+ /// seen.+ Unknown,+}++/// What the pane's shell has said with OSC 133 about its commands.+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]+pub struct ShellCommands {+ /// The shell has sent a mark, so the rest of this means something.+ pub reported: bool,+ /// Commands finished since the first mark.+ pub finished: u64,+ /// A command has started and not yet finished.+ pub running: bool,+ /// The status the last finished command reported.+ pub last_exit: Option<i32>,+}++#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]+pub struct PaneRunState {+ pub program: ProgramState,+ pub shell: ShellCommands,+}++impl PaneRunState {+ /// What a pane that knows nothing about its programs reports.+ pub fn unknown() -> Self {+ Self {+ program: ProgramState::Unknown,+ shell: ShellCommands::default(),+ }+ }+}diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rsindex 3d4982b1..50371f73 100644--- a/wezterm-client/src/client.rs+++ b/wezterm-client/src/client.rs@@ -441,10 +441,14 @@ async fn process_unilateral_inner_async(// 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.+ // materializes. Programs ending are told to every client too,+ // and a pane appearing only to event subscribers.if matches!(decoded.pdu,- Pdu::AgentStatusChanged(_) | Pdu::ForegroundProgramChanged(_)+ Pdu::AgentStatusChanged(_)+ | Pdu::ForegroundProgramChanged(_)+ | Pdu::PaneExited(_)+ | Pdu::PaneAdded(_)) {return Ok(());}@@ -463,6 +467,8 @@ async fn process_unilateral_inner_async(let pane = match mux.get_pane(local_pane_id) {Some(p) => p,+ // A program's end can be told after its mirror was dropped.+ None if matches!(decoded.pdu, Pdu::PaneExited(_) | Pdu::PaneAdded(_)) => return Ok(()),None => {log::debug!("got {decoded:?}, but local pane {local_pane_id} no longer exists; resync");client_domain.resync_for_remote_pane(pane_id).await?;@@ -498,6 +504,20 @@ async fn process_unilateral_inner_async(client_pane.process_unilateral(decoded.pdu).await}+/// 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);++/// 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> {+ let (tx, rx) = smol::channel::bounded(capacity);+ *UNILATERAL_TAP.lock().unwrap() = Some(tx);+ rx+}+fn process_unilateral(local_domain_id: Option<DomainId>,connection_generation: u64,@@ -507,9 +527,14 @@ fn process_unilateral(let local_domain_id = match local_domain_id {Some(id) => id,None => {- // FIXME: We currently get a bunch of these; we'll need- // to do something to advise the server when we want them.- // For now, we just ignore them.+ // 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() {+ log::warn!("dropping a server push nobody is reading");+ }+ return Ok(());+ }log::trace!("client doesn't have a real local domain, \so unilateral message cannot be processed by it"@@ -2789,6 +2814,8 @@ impl Client {GetPaneDirectionResponse);rpc!(adjust_pane_size, AdjustPaneSize, UnitResponse);+ rpc!(get_pane_run_state, GetPaneRunState, GetPaneRunStateResponse);+ rpc!(subscribe_events, SubscribeEvents, UnitResponse);}/// The outage clock to carry into the next reconnect round, given how thediff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rsindex 2a8adb8a..c09b82d9 100644--- a/wezterm-client/src/pane/clientpane.rs+++ b/wezterm-client/src/pane/clientpane.rs@@ -414,6 +414,13 @@ impl ClientPane {.foreground_program_changed(self.local_pane_id);}}+ Pdu::PaneExited(PaneExited { exit, .. }) => {+ // Told on, so that whoever asks this mux -- `cli events`+ // or `cli wait` against the GUI -- hears it as well.+ Mux::get().record_pane_exit(self.local_pane_id, exit);+ }+ // Meant for event subscribers; a mirror learns of panes by resync.+ Pdu::PaneAdded(_) => {}Pdu::PaneRemoved(PaneRemoved { pane_id }) => {log::trace!("remote pane {} has been removed", pane_id);self.session.set_dead(true);@@ -997,6 +1004,17 @@ impl Pane for ClientPane {}}+ async fn run_state(&self) -> anyhow::Result<thinkterm_proto::PaneRunState> {+ let response = self+ .client+ .client+ .get_pane_run_state(GetPaneRunState {+ pane_id: self.remote_pane_id,+ })+ .await?;+ Ok(response.state)+ }+fn key_down(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()> {if self.client.remote_tab_input_is_blocked() {return Ok(());diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex b2a18136..e841a9cc 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -327,6 +327,7 @@ impl GuiFrontEnd {MuxNotification::AgentStatusChanged(_) => {}MuxNotification::ForegroundProgramChanged(_) => {}MuxNotification::PaneAdded(_) => {}+ MuxNotification::PaneExited { .. } => {}MuxNotification::Alert {pane_id,alert:@@ -380,7 +381,8 @@ impl GuiFrontEnd {| Alert::WindowTitleChanged(_)| Alert::TabTitleChanged(_)| Alert::IconTitleChanged(_)- | Alert::SetUserVar { .. },+ | Alert::SetUserVar { .. }+ | Alert::CommandFinished { .. },} => {}MuxNotification::Empty => {if config::configuration().quit_when_all_windows_are_closed {diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex cdfc0fa9..82ff63c7 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -5884,6 +5884,11 @@ impl TermWindow {self.refresh_thread_work_for_pane(pane_id);self.update_title();}+ // Filtered out before it gets here; for event subscribers.+ MuxNotification::Alert {+ alert: Alert::CommandFinished { .. },+ pane_id: _,+ } => {}MuxNotification::Alert {alert: Alert::PaletteChanged,pane_id: _,@@ -6076,6 +6081,8 @@ impl TermWindow {self.refresh_thread_work_for_pane(pane_id);self.persist_workspace_layout_after_mutation("pane added");}+ // Filtered out before it gets here; for event subscribers.+ MuxNotification::PaneExited { .. } => {}MuxNotification::PaneRemoved(_) => {self.refresh_all_thread_work();self.persist_workspace_layout_after_mutation("pane removed");@@ -6784,9 +6791,10 @@ impl TermWindow {// contents with (or remove) the opaque handoff surface.}MuxNotification::Alert {- alert: Alert::ToastNotification { .. },+ alert: Alert::ToastNotification { .. } | Alert::CommandFinished { .. },..}+ | MuxNotification::PaneExited { .. }| MuxNotification::AssignClipboard { .. }| MuxNotification::SaveToDownloads { .. }| MuxNotification::WindowCreated(_)diff --git a/wezterm-mux-server-impl/src/dispatch.rs b/wezterm-mux-server-impl/src/dispatch.rsindex d7bf1d70..2e930b0e 100644--- a/wezterm-mux-server-impl/src/dispatch.rs+++ b/wezterm-mux-server-impl/src/dispatch.rs@@ -605,6 +605,17 @@ async fn process_async_with_peer<S: ConnectionStream>(}}}+ // A connection subscribed to events reads no pane contents:+ // output costs it nothing, and an alert goes straight out+ // rather than waiting for the pane's parser.+ Ok(Item::Notif(MuxNotification::PaneOutput(_))) if handler.events_subscribed => {}+ Ok(Item::Notif(MuxNotification::Alert { pane_id, alert }))+ if handler.events_subscribed =>+ {+ if !matches!(alert, wezterm_term::Alert::PaletteChanged) {+ send_notif_pdu(Pdu::NotifyAlert(codec::NotifyAlert { pane_id, alert }));+ }+ }Ok(Item::Notif(MuxNotification::PaneOutput(pane_id))) => {log::trace!("notification: pane output {pane_id}");handler.schedule_pane_push(pane_id);@@ -621,6 +632,14 @@ async fn process_async_with_peer<S: ConnectionStream>(handler.forget_pane(pane_id);send_notif_pdu(Pdu::PaneRemoved(codec::PaneRemoved { pane_id }));}+ // To every client: a GUI mirroring the pane tells its own+ // clients in turn.+ Ok(Item::Notif(MuxNotification::PaneExited { pane_id, exit })) => {+ send_notif_pdu(Pdu::PaneExited(codec::PaneExited { pane_id, exit }));+ }+ Ok(Item::Notif(MuxNotification::PaneAdded(pane_id))) if handler.events_subscribed => {+ send_notif_pdu(Pdu::PaneAdded(codec::PaneAdded { pane_id }));+ }Ok(Item::Notif(other)) => {log::trace!("notification with nothing for the connection to do: {other:?}");}@@ -762,14 +781,17 @@ async fn admission_withdrawn(revoked: &Option<smol::channel::Receiver<()>>) {}/// What the connection loop needs for a mux notification, prepared on the-/// main thread. Pane output, alerts and pane removal need the handler's-/// own state and go through as they are; everything else becomes the PDU-/// it will be sent as, with whatever the mux has to be asked read here.+/// main thread. Pane output, alerts, panes coming and going and programs+/// ending need the handler's own state and go through as they are;+/// everything else becomes the PDU it will be sent as, with whatever the+/// mux has to be asked read here.fn item_for_notification(n: MuxNotification) -> Option<Item> {let write = |pdu: Pdu| Some(Item::WritePdu(DecodedPdu { serial: 0, pdu }));match n {MuxNotification::PaneOutput(_)| MuxNotification::Alert { .. }+ | MuxNotification::PaneAdded(_)+ | MuxNotification::PaneExited { .. }| MuxNotification::PaneRemoved(_) => Some(Item::Notif(n)),MuxNotification::AgentStatusChanged(pane_id) => {// Read the status at send time so the payload is always the@@ -861,8 +883,7 @@ fn item_for_notification(n: MuxNotification) -> Option<Item> {MuxNotification::DefaultPaletteChanged => write(Pdu::DefaultPalette(codec::DefaultPalette {palette: crate::sessionhandler::configured_default_palette(),})),- MuxNotification::PaneAdded(_)- | MuxNotification::SaveToDownloads { .. }+ MuxNotification::SaveToDownloads { .. }| MuxNotification::WindowRemoved(_)| MuxNotification::WindowCreated(_)| MuxNotification::WindowInvalidated(_)diff --git a/wezterm-mux-server-impl/src/handoff.rs b/wezterm-mux-server-impl/src/handoff.rsindex 3dac5190..5656a072 100644--- a/wezterm-mux-server-impl/src/handoff.rs+++ b/wezterm-mux-server-impl/src/handoff.rs@@ -225,8 +225,13 @@ const KITTY_VIRTUAL_TAG: &[u8] = b"KGPA\x02";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";-fn encode_snapshot(snapshot: &TerminalSnapshot, graphics: &wezterm_term::KittyGraphicsSnapshot) -> anyhow::Result<Vec<u8>> {+fn encode_snapshot(+ snapshot: &TerminalSnapshot,+ graphics: &wezterm_term::KittyGraphicsSnapshot,+ shell: &wezterm_term::ShellCommandsSnapshot,+) -> anyhow::Result<Vec<u8>> {let mut bytes = Vec::new();snapshot.serialize(&mut varbincode::Serializer::new(&mut bytes)).context("encoding a terminal snapshot")?;@@ -267,15 +272,29 @@ fn encode_snapshot(snapshot: &TerminalSnapshot, graphics: &wezterm_term::KittyGr.context("encoding Kitty placement identities")?;}}+ // Last, after the Kitty parts. A successor from before those never reads+ // past the prefix; one that knows them refuses this, and with it the+ // handoff, so the old server carries on.+ if shell.reported {+ bytes.extend_from_slice(SHELL_COMMANDS_TAG);+ shell.serialize(&mut varbincode::Serializer::new(&mut bytes))+ .context("encoding the shell's command count")?;+ }zstd::encode_all(&bytes[..], 3).context("compressing a terminal snapshot")}-fn decode_snapshot(bytes: &[u8]) -> anyhow::Result<(TerminalSnapshot, Option<wezterm_term::KittyGraphicsSnapshot>)> {+fn decode_snapshot(+ bytes: &[u8],+) -> anyhow::Result<(+ TerminalSnapshot,+ Option<wezterm_term::KittyGraphicsSnapshot>,+ Option<wezterm_term::ShellCommandsSnapshot>,+)> {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() {+ let graphics = if reader.is_empty() || reader.starts_with(SHELL_COMMANDS_TAG) {None} else {let has_relatives = reader.starts_with(KITTY_RELATIVES_TAG);@@ -307,10 +326,15 @@ fn decode_snapshot(bytes: &[u8]) -> anyhow::Result<(TerminalSnapshot, Option<wezSome(wezterm_term::kitty_relative::RelativeSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader)).context("decoding Kitty relative placements")?)} else { None };- anyhow::ensure!(reader.is_empty(), "trailing bytes after Kitty snapshot extension");Some(wezterm_term::KittyGraphicsSnapshot { playback, virtual_images, image_numbers, placements, relatives })};- Ok((snapshot, graphics))+ let shell = if reader.starts_with(SHELL_COMMANDS_TAG) {+ reader = &reader[SHELL_COMMANDS_TAG.len()..];+ Some(wezterm_term::ShellCommandsSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader))+ .context("decoding the shell's command count")?)+ } else { None };+ anyhow::ensure!(reader.is_empty(), "trailing bytes after the terminal snapshot's extensions");+ Ok((snapshot, graphics, shell))}// ------------------------------------------------------- the old server@@ -537,7 +561,7 @@ fn capture(pid_file: bool) -> anyhow::Result<Capture> {let local = pane.downcast_ref::<LocalPane>().expect("checked above");- let (snapshot, graphics) = local.snapshot_terminal();+ let (snapshot, graphics, shell) = local.snapshot_terminal();paused.push(guard);panes.push((HandoffPane {@@ -545,7 +569,7 @@ 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)?,+ snapshot: encode_snapshot(&snapshot, &graphics, &shell)?,},parts.pty_fd,));@@ -734,6 +758,7 @@ struct Received {fd: OwnedFd,snapshot: TerminalSnapshot,graphics: Option<wezterm_term::KittyGraphicsSnapshot>,+ shell: Option<wezterm_term::ShellCommandsSnapshot>,}/// Receive the panes, the windows and the listening socket; only on@@ -760,9 +785,9 @@ pub fn complete(let pane_id = pane.pane_id;let fd = recv_owned_fd(&stream)?;fail_at("pane")?;- let (snapshot, graphics) = decode_snapshot(&pane.snapshot)+ let (snapshot, graphics, shell) = decode_snapshot(&pane.snapshot).with_context(|| format!("pane {pane_id}'s snapshot"))?;- received.push(Received { pane, fd, snapshot, graphics });+ received.push(Received { pane, fd, snapshot, graphics, shell });write_message(&mut stream, &HandoffMessage::Ack)?;}HandoffMessage::Topology(list) => {@@ -853,7 +878,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 } = item;+ let Received { pane, fd, snapshot, mut graphics, shell } = 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()?;@@ -886,6 +911,11 @@ fn adopt_pane(item: Received, domain_id: DomainId) -> anyhow::Result<Arc<dyn Panlog::warn!("adopting a pane without its {err:#}");}}+ // Without it a shell that reported its commands would read as one that+ // never did, until its next prompt.+ if let Some(shell) = shell {+ terminal.restore_shell_commands(shell);+ }// The old server kept serving between the snapshot and Commit; a// resize in that window reached the pty but not the snapshot.if let Ok(size) = master.get_size() {@@ -1105,17 +1135,18 @@ mod tests {term.advance_bytes("hello");let snapshot = term.snapshot();let mut graphics = term.snapshot_kitty_graphics();- let bytes = encode_snapshot(&snapshot, &graphics).unwrap();- assert_eq!(decode_snapshot(&bytes).unwrap(), (snapshot, None));+ let shell = term.snapshot_shell_commands();+ let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();+ assert_eq!(decode_snapshot(&bytes).unwrap(), (snapshot, 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).unwrap();+ let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();let decoded = decode_snapshot(&bytes).unwrap();- assert_eq!(decoded, (term.snapshot(), Some(graphics.clone())));+ assert_eq!(decoded, (term.snapshot(), Some(graphics.clone()), 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();@@ -1138,8 +1169,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).unwrap();- assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics.clone())));+ let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();+ assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics.clone()), None));let raw = zstd::decode_all(&bytes[..]).unwrap();let mut reader = &raw[..];let old = TerminalSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader)).unwrap();@@ -1152,8 +1183,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).unwrap();- assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics.clone())));+ let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();+ assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics.clone()), None));let raw = zstd::decode_all(&bytes[..]).unwrap();let mut reader = &raw[..];let old = TerminalSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader)).unwrap();@@ -1168,8 +1199,8 @@ mod tests {placements: Vec::new(),cell_tags: [Vec::new(), Vec::new()],});- let bytes = encode_snapshot(&snapshot, &graphics).unwrap();- assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics)));+ let bytes = encode_snapshot(&snapshot, &graphics, &shell).unwrap();+ assert_eq!(decode_snapshot(&bytes).unwrap(), (term.snapshot(), Some(graphics), None));let raw = zstd::decode_all(&bytes[..]).unwrap();let mut reader = &raw[..];let old = TerminalSnapshot::deserialize(&mut varbincode::Deserializer::new(&mut reader)).unwrap();@@ -1180,6 +1211,44 @@ mod tests {assert!(decode_snapshot(&zstd::encode_all(&trailing[..], 3).unwrap()).is_err());}+ #[test]+ fn the_shell_command_count_travels_after_the_snapshot() {+ 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()));+ 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;3;aid=1\x07\x1b]133;A;cl=m;aid=1\x07");+ let snapshot = term.snapshot();+ let mut graphics = term.snapshot_kitty_graphics();+ let shell = term.snapshot_shell_commands();+ assert!(shell.reported);+ assert_eq!(shell.last_exit, Some(3));+ // On its own and after a Kitty part: either way the predecessor's+ // decoder reads the same prefix.+ for kitty in [false, true] {+ if kitty {+ 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();+ assert_eq!(+ decode_snapshot(&bytes).unwrap(),+ (term.snapshot(), kitty.then(|| graphics.clone()), Some(shell.clone()))+ );+ 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 kitty { KITTY_PLAYBACK_TAG } else { SHELL_COMMANDS_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(@@ -1195,8 +1264,9 @@ mod tests {for _ in 0..2 {let snapshot = terminal.snapshot();let graphics = terminal.snapshot_kitty_graphics();- let bytes = encode_snapshot(&snapshot, &graphics).unwrap();- let (decoded, state) = decode_snapshot(&bytes).unwrap();+ let shell = terminal.snapshot_shell_commands();+ let bytes = encode_snapshot(&snapshot, &graphics, &shell).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 ad0b3a13..3a91cf4c 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -121,6 +121,9 @@ pub(crate) struct PerPane {queued_input_bytes: usize,/// A drain task exists for `inputs`.input_draining: bool,+ /// The connection subscribed to events: a push carries the pane's+ /// alerts and nothing of what it shows.+ events_only: bool,}/// What may wait for one pane from one connection before further input is@@ -787,6 +790,14 @@ fn maybe_push_pane_changes(per_pane: Arc<Mutex<PerPane>>,force_with_input_serial: Option<InputSerial>,) -> anyhow::Result<()> {+ {+ // A connection subscribed to events gets the pane's alerts and+ // none of what it shows.+ let mut per_pane = per_pane.lock().unwrap();+ if per_pane.events_only {+ return send_pane_alerts(pane.pane_id(), &sender, &mut per_pane);+ }+ }// Application palette provenance must arrive even when the state is// `None`: that explicit reset prevents a server's configured/advisory// palette from taking over client rendering. Send it before line changes@@ -840,18 +851,24 @@ fn maybe_push_pane_changes(})?;}+ send_pane_alerts(pane.pane_id(), &sender, &mut per_pane)+}++fn send_pane_alerts(+ pane_id: PaneId,+ sender: &PduSender,+ per_pane: &mut PerPane,+) -> anyhow::Result<()> {let notifications: Vec<Alert> = per_pane.notifications.drain(..).collect();for alert in notifications {match alert {// The current application state was sent (and de-duplicated)- // above. Never forward this alert as a configured palette.+ // with the pane's contents. Never forward this alert as a+ // configured palette.Alert::PaletteChanged => {}alert => {sender.send(DecodedPdu {- pdu: Pdu::NotifyAlert(NotifyAlert {- pane_id: pane.pane_id(),- alert,- }),+ pdu: Pdu::NotifyAlert(NotifyAlert { pane_id, alert }),serial: 0,})?;}@@ -1111,6 +1128,8 @@ fn web_peer_may_send(pdu: &Pdu) -> bool {| Pdu::WriteToPane(_)| Pdu::SendKeyDown(_)| Pdu::MarkProgramStatusSeen(_)+ | Pdu::GetPaneRunState(_)+ | Pdu::SubscribeEvents(_)| Pdu::SendMouseEvent(_)| Pdu::SendPaste(_)| Pdu::Resize(_)@@ -1164,6 +1183,9 @@ pub struct SessionHandler {/// `PluginFrame` on; it closes when this does, or when the client/// sends an empty frame.plugin_pipe: Option<crate::plugin_relay::Pipe>,+ /// The client sent `SubscribeEvents`: it hears of panes appearing,+ /// and its pane pushes carry alerts only.+ pub(crate) events_subscribed: bool,}impl Drop for SessionHandler {@@ -1197,6 +1219,7 @@ impl SessionHandler {palette_session_id: None,proxy_client_id: None,plugin_pipe: None,+ events_subscribed: false,}}@@ -1271,11 +1294,21 @@ impl SessionHandler {}pub(crate) fn per_pane(&mut self, pane_id: PaneId) -> Arc<Mutex<PerPane>> {- Arc::clone(- self.per_pane- .entry(pane_id)- .or_insert_with(|| Arc::new(Mutex::new(PerPane::default()))),- )+ let events_only = self.events_subscribed;+ Arc::clone(self.per_pane.entry(pane_id).or_insert_with(|| {+ Arc::new(Mutex::new(PerPane {+ events_only,+ ..PerPane::default()+ }))+ }))+ }++ /// From now on this connection hears what happens, not what panes show.+ fn subscribe_events(&mut self) {+ self.events_subscribed = true;+ for per_pane in self.per_pane.values() {+ per_pane.lock().unwrap().events_only = true;+ }}/// Queue terminal input for `pane_id` and see that a drain is running.@@ -1814,6 +1847,41 @@ impl SessionHandler {.detach();}+ Pdu::GetPaneRunState(GetPaneRunState { pane_id }) => {+ async fn run_state(+ pane_id: PaneId,+ ) -> anyhow::Result<thinkterm_proto::PaneRunState> {+ let mux = Mux::get();+ if let Some(pane) = mux.get_pane(pane_id) {+ return pane.run_state().await;+ }+ // Gone already: what is remembered of how it ended.+ let exit = mux+ .recent_pane_exit(pane_id)+ .ok_or_else(|| anyhow!("no such pane {}", pane_id))?;+ Ok(thinkterm_proto::PaneRunState {+ program: thinkterm_proto::ProgramState::Exited(exit),+ shell: Default::default(),+ })+ }++ spawn_into_main_thread(async move {+ promise::spawn::spawn(async move {+ let result = run_state(pane_id).await.map(|state| {+ Pdu::GetPaneRunStateResponse(GetPaneRunStateResponse { pane_id, state })+ });+ send_response(result);+ })+ .detach();+ })+ .detach();+ }++ Pdu::SubscribeEvents(SubscribeEvents {}) => {+ self.subscribe_events();+ send_response(Ok(Pdu::UnitResponse(UnitResponse {})));+ }+Pdu::MarkProgramStatusSeen(MarkProgramStatusSeen { pane_id }) => {spawn_into_main_thread(async move {catch(@@ -2876,6 +2944,9 @@ impl SessionHandler {// client that had just proved it was alive.Pdu::Pong(_) => {}Pdu::AgentStatusChanged { .. }+ | Pdu::GetPaneRunStateResponse { .. }+ | Pdu::PaneExited { .. }+ | Pdu::PaneAdded { .. }| Pdu::GetAgentStatusesResponse { .. }| Pdu::ForegroundProgramChanged { .. }| Pdu::GetForegroundProgramsResponse { .. }@@ -3505,6 +3576,63 @@ mod tests {);}+ #[test]+ fn subscribing_to_events_turns_pane_pushes_into_alerts() {+ use super::{send_pane_alerts, PduSender, SessionHandler};+ use codec::{DecodedPdu, NotifyAlert, SubscribeEvents};+ use std::sync::Mutex;+ use wezterm_term::Alert;++ let sent: Arc<Mutex<Vec<DecodedPdu>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = Arc::clone(&sent);+ let mut handler = SessionHandler::new(PduSender::new(move |pdu| {+ sink.lock().unwrap().push(pdu);+ Ok(())+ }));+ let before = handler.per_pane(1);+ assert!(!before.lock().unwrap().events_only);++ handler.process_one(DecodedPdu {+ serial: 3,+ pdu: Pdu::SubscribeEvents(SubscribeEvents {}),+ });+ assert!(handler.events_subscribed);+ assert!(+ before.lock().unwrap().events_only,+ "panes seen before as well"+ );+ assert!(handler.per_pane(2).lock().unwrap().events_only);++ let mut state = PerPane::default();+ state.notifications = vec![+ Alert::Bell,+ Alert::PaletteChanged,+ Alert::CommandFinished { exit_code: Some(1) },+ ];+ let sender = handler.to_write_tx.clone();+ send_pane_alerts(5, &sender, &mut state).unwrap();+ assert!(state.notifications.is_empty());++ let sent = sent.lock().unwrap();+ assert_eq!(sent[0].serial, 3);+ assert_eq!(sent[0].pdu.pdu_name(), "UnitResponse");+ let alerts: Vec<&Pdu> = sent[1..].iter().map(|d| &d.pdu).collect();+ assert_eq!(+ alerts,+ vec![+ &Pdu::NotifyAlert(NotifyAlert {+ pane_id: 5,+ alert: Alert::Bell+ }),+ &Pdu::NotifyAlert(NotifyAlert {+ pane_id: 5,+ alert: Alert::CommandFinished { exit_code: Some(1) }+ }),+ ],+ "a palette change is never sent as an alert"+ );+ }+#[test]fn only_one_push_is_scheduled_per_pane_at_a_time() {let mut state = PerPane::default();