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(cli): add send-key, events and wait
RoversX231f4c86ec4f
diff --git a/wezterm/src/cli/agent.rs b/wezterm/src/cli/agent.rsindex 28a66498..e0a782fb 100644--- a/wezterm/src/cli/agent.rs+++ b/wezterm/src/cli/agent.rs@@ -37,7 +37,7 @@ impl AgentCommand {}}-fn state_label(state: AgentState) -> &'static str {+pub(crate) fn state_label(state: AgentState) -> &'static str {match state {AgentState::Working => "working",AgentState::Blocked => "blocked",diff --git a/wezterm/src/cli/events.rs b/wezterm/src/cli/events.rsnew file mode 100644index 00000000..0b1a51c1--- /dev/null+++ b/wezterm/src/cli/events.rs@@ -0,0 +1,476 @@+use crate::cli::agent::state_label;+use crate::cli::CliOutputFormatKind;+use anyhow::{bail, Context};+use clap::Parser;+use codec::Pdu;+use mux::pane::PaneId;+use std::io::Write;+use std::time::Duration;+use thinkterm_proto::{TabId, WindowId};+use wezterm_client::client::Client;+use wezterm_term::{Alert, Progress};++/// How many events may wait unprinted before further ones are dropped.+const BACKLOG: usize = 4096;+/// How often a quiet stream checks that the server is still there, and+/// that the connection has not been replaced by a reconnect.+const LIVENESS_INTERVAL: Duration = Duration::from_secs(5);++#[derive(Debug, Parser, Clone)]+pub struct EventsCommand {+ /// Only what happens to this pane; events about tabs and windows are+ /// left out.+ #[arg(long)]+ pane_id: Option<PaneId>,++ /// "table" prints a line per event; "json" prints one JSON object per+ /// line, with a "type" and the event's own fields.+ #[arg(long = "format", default_value = "table")]+ format: CliOutputFormatKind,+}++// One line of `--format json` each: a stable output format. Add events and+// fields; do not remove or retype them.+#[derive(serde::Serialize, Debug, PartialEq)]+#[serde(tag = "type", rename_all = "snake_case")]+enum Event {+ PaneAdded {+ pane_id: PaneId,+ },+ PaneRemoved {+ pane_id: PaneId,+ },+ /// The program the pane started ended.+ ProgramExited {+ pane_id: PaneId,+ exit_code: Option<u32>,+ signal: Option<String>,+ },+ /// The pane's shell reported a command finished (OSC 133).+ CommandFinished {+ pane_id: PaneId,+ exit_code: Option<i32>,+ },+ Bell {+ pane_id: PaneId,+ },+ Notification {+ pane_id: PaneId,+ title: Option<String>,+ body: String,+ },+ TitleChanged {+ pane_id: PaneId,+ title: String,+ },+ CwdChanged {+ pane_id: PaneId,+ },+ Progress {+ pane_id: PaneId,+ state: &'static str,+ percent: Option<u8>,+ },+ UserVar {+ pane_id: PaneId,+ name: String,+ value: String,+ },+ ClipboardWritten {+ pane_id: PaneId,+ },+ AgentStatus {+ pane_id: PaneId,+ agent: Option<String>,+ state: Option<&'static str>,+ },+ ForegroundProgram {+ pane_id: PaneId,+ executable: Option<String>,+ runs: Option<String>,+ },+ PaneFocused {+ pane_id: PaneId,+ },+ TabAdded {+ tab_id: TabId,+ window_id: WindowId,+ },+ TabTitleChanged {+ tab_id: TabId,+ title: String,+ },+ WindowTitleChanged {+ window_id: WindowId,+ title: String,+ },+ WorkspaceChanged {+ window_id: WindowId,+ workspace: String,+ },+ WorkspaceRenamed {+ old_workspace: String,+ new_workspace: String,+ },+}++impl Event {+ /// The event a server push stands for, if it stands for one.+ fn from_pdu(pdu: Pdu) -> Option<Self> {+ Some(match pdu {+ Pdu::PaneAdded(codec::PaneAdded { pane_id }) => Self::PaneAdded { pane_id },+ Pdu::PaneRemoved(codec::PaneRemoved { pane_id }) => Self::PaneRemoved { pane_id },+ Pdu::PaneExited(codec::PaneExited { pane_id, exit }) => Self::ProgramExited {+ pane_id,+ exit_code: exit.code,+ signal: exit.signal,+ },+ Pdu::NotifyAlert(codec::NotifyAlert { pane_id, alert }) => match alert {+ Alert::Bell => Self::Bell { pane_id },+ Alert::ToastNotification { title, body, .. } => Self::Notification {+ pane_id,+ title,+ body,+ },+ Alert::WindowTitleChanged(title) => Self::TitleChanged { pane_id, title },+ Alert::CurrentWorkingDirectoryChanged => Self::CwdChanged { pane_id },+ Alert::Progress(progress) => {+ let (state, percent) = match progress {+ Progress::None => ("none", None),+ Progress::Percentage(p) => ("percentage", Some(p)),+ Progress::Error(p) => ("error", Some(p)),+ Progress::Indeterminate => ("indeterminate", None),+ };+ Self::Progress {+ pane_id,+ state,+ percent,+ }+ }+ Alert::SetUserVar { name, value } => Self::UserVar {+ pane_id,+ name,+ value,+ },+ Alert::CommandFinished { exit_code } => {+ Self::CommandFinished { pane_id, exit_code }+ }+ Alert::IconTitleChanged(_)+ | Alert::TabTitleChanged(_)+ | Alert::PaletteChanged+ | Alert::OutputSinceFocusLost => return None,+ },+ // What was copied is not repeated here.+ Pdu::SetClipboard(codec::SetClipboard { pane_id, .. }) => {+ Self::ClipboardWritten { pane_id }+ }+ Pdu::AgentStatusChanged(codec::AgentStatusChanged { pane_id, status }) => {+ Self::AgentStatus {+ pane_id,+ state: status.as_ref().map(|status| state_label(status.state)),+ agent: status.map(|status| status.agent_id),+ }+ }+ Pdu::ForegroundProgramChanged(codec::ForegroundProgramChanged { pane_id, program }) => {+ Self::ForegroundProgram {+ pane_id,+ runs: program.as_ref().and_then(|program| program.runs.clone()),+ executable: program.map(|program| program.executable),+ }+ }+ Pdu::PaneFocused(codec::PaneFocused { pane_id }) => Self::PaneFocused { pane_id },+ Pdu::TabAddedToWindow(codec::TabAddedToWindow { tab_id, window_id }) => {+ Self::TabAdded { tab_id, window_id }+ }+ Pdu::TabTitleChanged(codec::TabTitleChanged { tab_id, title }) => {+ Self::TabTitleChanged { tab_id, title }+ }+ Pdu::WindowTitleChanged(codec::WindowTitleChanged { window_id, title }) => {+ Self::WindowTitleChanged { window_id, title }+ }+ Pdu::WindowWorkspaceChanged(codec::WindowWorkspaceChanged {+ window_id,+ workspace,+ }) => Self::WorkspaceChanged {+ window_id,+ workspace,+ },+ Pdu::RenameWorkspace(codec::RenameWorkspace {+ old_workspace,+ new_workspace,+ }) => Self::WorkspaceRenamed {+ old_workspace,+ new_workspace,+ },+ _ => return None,+ })+ }++ fn pane_id(&self) -> Option<PaneId> {+ match self {+ Self::PaneAdded { pane_id }+ | Self::PaneRemoved { pane_id }+ | Self::ProgramExited { pane_id, .. }+ | Self::CommandFinished { pane_id, .. }+ | Self::Bell { pane_id }+ | Self::Notification { pane_id, .. }+ | Self::TitleChanged { pane_id, .. }+ | Self::CwdChanged { pane_id }+ | Self::Progress { pane_id, .. }+ | Self::UserVar { pane_id, .. }+ | Self::ClipboardWritten { pane_id }+ | Self::AgentStatus { pane_id, .. }+ | Self::ForegroundProgram { pane_id, .. }+ | Self::PaneFocused { pane_id } => Some(*pane_id),+ Self::TabAdded { .. }+ | Self::TabTitleChanged { .. }+ | Self::WindowTitleChanged { .. }+ | Self::WorkspaceChanged { .. }+ | Self::WorkspaceRenamed { .. } => None,+ }+ }++ /// The `--format table` line, without its time.+ fn describe(&self) -> String {+ let or_none = |value: &Option<String>| value.clone().unwrap_or_else(|| "-".to_string());+ match self {+ Self::PaneAdded { pane_id } => format!("pane_added pane {pane_id}"),+ Self::PaneRemoved { pane_id } => format!("pane_removed pane {pane_id}"),+ Self::ProgramExited {+ pane_id,+ exit_code,+ signal,+ } => match signal {+ Some(signal) => format!("program_exited pane {pane_id} {signal}"),+ None => match exit_code {+ Some(code) => format!("program_exited pane {pane_id} status {code}"),+ None => format!("program_exited pane {pane_id} status unknown"),+ },+ },+ Self::CommandFinished { pane_id, exit_code } => match exit_code {+ Some(code) => format!("command_finished pane {pane_id} status {code}"),+ None => format!("command_finished pane {pane_id}"),+ },+ Self::Bell { pane_id } => format!("bell pane {pane_id}"),+ Self::Notification {+ pane_id,+ title,+ body,+ } => format!(+ "notification pane {pane_id} {}{body}",+ title.as_ref().map(|t| format!("{t}: ")).unwrap_or_default()+ ),+ Self::TitleChanged { pane_id, title } => {+ format!("title_changed pane {pane_id} {title}")+ }+ Self::CwdChanged { pane_id } => format!("cwd_changed pane {pane_id}"),+ Self::Progress {+ pane_id,+ state,+ percent,+ } => match percent {+ Some(p) => format!("progress pane {pane_id} {state} {p}%"),+ None => format!("progress pane {pane_id} {state}"),+ },+ Self::UserVar {+ pane_id,+ name,+ value,+ } => format!("user_var pane {pane_id} {name}={value}"),+ Self::ClipboardWritten { pane_id } => {+ format!("clipboard_written pane {pane_id}")+ }+ Self::AgentStatus {+ pane_id,+ agent,+ state,+ } => format!(+ "agent_status pane {pane_id} {} {}",+ or_none(agent),+ state.unwrap_or("-")+ ),+ Self::ForegroundProgram {+ pane_id,+ executable,+ runs,+ } => match runs {+ Some(runs) => format!(+ "foreground_program pane {pane_id} {} ({runs})",+ or_none(executable)+ ),+ None => format!(+ "foreground_program pane {pane_id} {}",+ or_none(executable)+ ),+ },+ Self::PaneFocused { pane_id } => format!("pane_focused pane {pane_id}"),+ Self::TabAdded { tab_id, window_id } => {+ format!("tab_added tab {tab_id} window {window_id}")+ }+ Self::TabTitleChanged { tab_id, title } => {+ format!("tab_title_changed tab {tab_id} {title}")+ }+ Self::WindowTitleChanged { window_id, title } => {+ format!("window_title_changed window {window_id} {title}")+ }+ Self::WorkspaceChanged {+ window_id,+ workspace,+ } => format!("workspace_changed window {window_id} {workspace}"),+ Self::WorkspaceRenamed {+ old_workspace,+ new_workspace,+ } => format!("workspace_renamed {old_workspace} -> {new_workspace}"),+ }+ }+}++/// Text a program in a pane chose (a title, a user var, a notification),+/// made safe to print to a terminal: control characters are written out+/// rather than sent, so none of them reaches the terminal running this.+fn printable(text: &str) -> String {+ let mut out = String::with_capacity(text.len());+ for c in text.chars() {+ if c.is_control() {+ out.extend(c.escape_default());+ } else {+ out.push(c);+ }+ }+ out+}++impl EventsCommand {+ pub async fn run(self, client: Client) -> anyhow::Result<()> {+ let pushes = wezterm_client::client::tap_unilateral_pdus(BACKLOG);+ client.subscribe_events(codec::SubscribeEvents {}).await?;+ let mut subscribed_on = client.connection_generation();++ let out = std::io::stdout();+ loop {+ // A reconnect is a new connection on the server, which has+ // not been asked for events.+ if client.connection_generation() != subscribed_on {+ subscribed_on = client.connection_generation();+ client.subscribe_events(codec::SubscribeEvents {}).await?;+ }+ let next = smol::future::or(async { Some(pushes.recv().await) }, async {+ smol::Timer::after(LIVENESS_INTERVAL).await;+ None+ })+ .await;+ let pdu = match next {+ Some(Ok(pdu)) => pdu,+ Some(Err(_)) => bail!("the event stream ended"),+ None => {+ client+ .ping()+ .await+ .context("lost the connection to the server")?;+ continue;+ }+ };+ let Some(event) = Event::from_pdu(pdu) else {+ continue;+ };+ if self.pane_id.is_some() && event.pane_id() != self.pane_id {+ continue;+ }+ let line = match self.format {+ CliOutputFormatKind::Json => serde_json::to_string(&event)?,+ CliOutputFormatKind::Table => format!(+ "{} {}",+ chrono::Local::now().format("%H:%M:%S"),+ printable(&event.describe())+ ),+ };+ writeln!(out.lock(), "{line}").map_err(crate::stdout_error)?;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn an_unavailable_program_exit_status_is_explicit() {+ let event = Event::from_pdu(Pdu::PaneExited(codec::PaneExited {+ pane_id: 4,+ exit: thinkterm_proto::PaneExit {+ code: None,+ signal: None,+ },+ }))+ .unwrap();+ assert_eq!(+ serde_json::to_string(&event).unwrap(),+ r#"{"type":"program_exited","pane_id":4,"exit_code":null,"signal":null}"#+ );+ assert!(event.describe().ends_with("status unknown"));+ }++ #[test]+ fn pushes_become_events_and_json_keeps_its_shape() {+ let exited = Event::from_pdu(Pdu::PaneExited(codec::PaneExited {+ pane_id: 4,+ exit: thinkterm_proto::PaneExit {+ code: Some(2),+ signal: None,+ },+ }))+ .unwrap();+ assert_eq!(+ serde_json::to_string(&exited).unwrap(),+ r#"{"type":"program_exited","pane_id":4,"exit_code":2,"signal":null}"#+ );++ let finished = Event::from_pdu(Pdu::NotifyAlert(codec::NotifyAlert {+ pane_id: 4,+ alert: Alert::CommandFinished { exit_code: Some(1) },+ }))+ .unwrap();+ assert_eq!(+ serde_json::to_string(&finished).unwrap(),+ r#"{"type":"command_finished","pane_id":4,"exit_code":1}"#+ );++ let bell = Event::from_pdu(Pdu::NotifyAlert(codec::NotifyAlert {+ pane_id: 9,+ alert: Alert::Bell,+ }))+ .unwrap();+ assert_eq!(bell, Event::Bell { pane_id: 9 });+ assert_eq!(bell.pane_id(), Some(9));+ }++ #[test]+ fn table_lines_carry_no_control_characters() {+ let event = Event::UserVar {+ pane_id: 1,+ name: "x".to_string(),+ value: "\x1b]52;c;cHduZWQ=\x07\u{9b}2J".to_string(),+ };+ let line = printable(&event.describe());+ assert!(!line.chars().any(char::is_control), "{:?}", line);+ assert!(line.contains("\\u{1b}]52;c;cHduZWQ="), "{:?}", line);+ }++ #[test]+ fn noise_and_clipboard_contents_stay_out() {+ assert_eq!(+ Event::from_pdu(Pdu::NotifyAlert(codec::NotifyAlert {+ pane_id: 1,+ alert: Alert::OutputSinceFocusLost,+ })),+ None+ );+ let copied = Event::from_pdu(Pdu::SetClipboard(codec::SetClipboard {+ pane_id: 1,+ clipboard: Some("secret".to_string()),+ selection: wezterm_term::ClipboardSelection::Clipboard,+ }))+ .unwrap();+ assert!(!serde_json::to_string(&copied).unwrap().contains("secret"));+ }+}diff --git a/wezterm/src/cli/mod.rs b/wezterm/src/cli/mod.rsindex a730374d..c33eda75 100644--- a/wezterm/src/cli/mod.rs+++ b/wezterm/src/cli/mod.rs@@ -9,6 +9,7 @@ mod activate_tab;mod adjust_pane_size;mod agent;mod color_schemes;+mod events;mod get_pane_direction;mod get_text;mod kill_pane;@@ -17,6 +18,7 @@ mod list_clients;mod move_pane_to_new_tab;mod proxy;mod rename_workspace;+mod send_key;mod send_text;mod set_tab_title;mod set_window_title;@@ -24,6 +26,7 @@ mod spawn_command;mod split_pane;mod stop_server;mod tls_creds;+mod wait;mod web_server;mod web_token;mod zoom_pane;@@ -133,6 +136,24 @@ Outputs the pane-id for the newly created pane on success"#[command(name = "send-text", rename_all = "kebab")]SendText(send_text::SendText),+ /// Press keys in a pane by name -- `enter`, `ctrl+c`, `up` -- encoded+ /// the way the program there asked for keys, as if typed.+ /// With `--wait`, wait for the command they start in the pane's shell+ /// and exit with its status.+ #[command(name = "send-key", rename_all = "kebab")]+ SendKey(send_key::SendKey),++ /// Wait for a pane's program to end, or with `--command` for the+ /// command running in its shell, and exit with its status+ #[command(name = "wait", rename_all = "kebab")]+ Wait(wait::WaitCommand),++ /// Print what happens as it happens -- panes opening and closing,+ /// programs and commands finishing, bells, notifications, titles,+ /// agent status -- until interrupted+ #[command(name = "events", rename_all = "kebab")]+ Events(events::EventsCommand),+/// Retrieves the textual content of a pane and output it to stdout#[command(name = "get-text", rename_all = "kebab")]GetText(get_text::GetText),@@ -242,6 +263,9 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>CliSubCommand::MovePaneToNewTab(cmd) => cmd.run(client).await,CliSubCommand::SplitPane(cmd) => cmd.run(client).await,CliSubCommand::SendText(cmd) => cmd.run(client).await,+ CliSubCommand::SendKey(cmd) => cmd.run(client).await,+ CliSubCommand::Wait(cmd) => cmd.run(client).await,+ CliSubCommand::Events(cmd) => cmd.run(client).await,CliSubCommand::GetText(cmd) => cmd.run(client).await,CliSubCommand::SpawnCommand(cmd) => cmd.run(client, &crate::init_config(opts)?).await,CliSubCommand::Proxy(cmd) => cmd.run(client, &crate::init_config(opts)?).await,diff --git a/wezterm/src/cli/send_key.rs b/wezterm/src/cli/send_key.rsnew file mode 100644index 00000000..5ebb5b16--- /dev/null+++ b/wezterm/src/cli/send_key.rs@@ -0,0 +1,205 @@+use crate::cli::wait::{exit_with, parse_timeout, shell_commands, wait_for_command, with_deadline};+use anyhow::{anyhow, bail};+use clap::Parser;+use codec::{InputSerial, SendKeyDown};+use mux::pane::PaneId;+use std::time::{Duration, Instant};+use termwiz::input::{KeyCode, KeyEvent, Modifiers};+use wezterm_client::client::Client;++#[derive(Debug, Parser, Clone)]+pub struct SendKey {+ /// Specify the target pane.+ /// The default is to use the current pane based on the+ /// environment variable WEZTERM_PANE.+ #[arg(long)]+ pane_id: Option<PaneId>,++ /// After the keys, wait for the command they start in the pane's shell+ /// to finish, and exit with its status (125 when the shell gave none):+ /// `send-key --wait enter` runs what `send-text` typed. Needs a shell+ /// that reports its commands (the shell integration's OSC 133 marks).+ #[arg(long)]+ wait: bool,++ /// With --wait, give up after this long, exiting with status 124: a+ /// number of seconds, or a number with s, m or h after it.+ #[arg(long, value_parser = parse_timeout, requires = "wait")]+ timeout: Option<Duration>,++ /// The keys to press, one after another, each written as modifiers and+ /// a key joined by `+`: `enter`, `ctrl+c`, `up`, `shift+tab`, `alt+f`,+ /// `f5`. Modifiers are ctrl, alt (or opt), shift and cmd (or super).+ /// Keys are a character, or enter, tab, escape, backspace, delete,+ /// space, up, down, left, right, home, end, pageup, pagedown, insert+ /// and f1 to f24. Each is encoded the way the program in the pane asked+ /// for keys, as if typed.+ #[arg(required = true, num_args = 1..)]+ keys: Vec<String>,+}++impl SendKey {+ pub async fn run(self, client: Client) -> anyhow::Result<()> {+ let deadline = self.timeout.map(|t| Instant::now() + t);+ let events = self+ .keys+ .iter()+ .map(|key| parse_key(key))+ .collect::<anyhow::Result<Vec<_>>>()?;++ if !self.wait {+ let pane_id = client.resolve_pane_id(self.pane_id).await?;+ return send_keys(&client, pane_id, events).await;+ }+ let code = with_deadline(deadline, async {+ // Finding the focused pane asks the server too.+ let pane_id = client.resolve_pane_id(self.pane_id).await?;+ // Counted before the keys go, so a command that finishes at+ // once is not missed.+ let before = shell_commands(&client, pane_id).await?.finished;+ send_keys(&client, pane_id, events).await?;+ wait_for_command(&client, pane_id, before, deadline).await+ })+ .await?;+ exit_with(code)+ }+}++async fn send_keys(client: &Client, pane_id: PaneId, events: Vec<KeyEvent>) -> anyhow::Result<()> {+ for event in events {+ client+ .key_down(SendKeyDown {+ pane_id,+ event,+ input_serial: InputSerial::now(),+ })+ .await?;+ }+ Ok(())+}++/// One key as the command line writes it: modifiers and a key joined by+/// `+`, any case. `ctrl++` is ctrl and plus.+fn parse_key(text: &str) -> anyhow::Result<KeyEvent> {+ let (mods, key) = if text == "+" {+ ("", "+")+ } else if let Some(mods) = text.strip_suffix("++") {+ (mods, "+")+ } else {+ match text.rsplit_once('+') {+ Some((mods, key)) => (mods, key),+ None => ("", text),+ }+ };++ let mut modifiers = Modifiers::NONE;+ for name in mods.split('+').filter(|name| !name.is_empty()) {+ modifiers |= match name.to_ascii_lowercase().as_str() {+ "ctrl" | "control" => Modifiers::CTRL,+ "alt" | "opt" | "option" | "meta" => Modifiers::ALT,+ "shift" => Modifiers::SHIFT,+ "cmd" | "command" | "super" | "win" => Modifiers::SUPER,+ _ => bail!("{text:?}: {name:?} is not a modifier (ctrl, alt, shift or cmd)"),+ };+ }++ let mut chars = key.chars();+ let key = match (chars.next(), chars.next()) {+ (Some(c), None) => KeyCode::Char(c),+ _ => match key.to_ascii_lowercase().as_str() {+ "enter" | "return" => KeyCode::Enter,+ "tab" => KeyCode::Tab,+ "escape" | "esc" => KeyCode::Escape,+ "backspace" => KeyCode::Backspace,+ "delete" | "del" => KeyCode::Delete,+ "space" => KeyCode::Char(' '),+ "up" => KeyCode::UpArrow,+ "down" => KeyCode::DownArrow,+ "left" => KeyCode::LeftArrow,+ "right" => KeyCode::RightArrow,+ "home" => KeyCode::Home,+ "end" => KeyCode::End,+ "pageup" => KeyCode::PageUp,+ "pagedown" => KeyCode::PageDown,+ "insert" => KeyCode::Insert,+ name => match name.strip_prefix('f').and_then(|n| n.parse::<u8>().ok()) {+ Some(n @ 1..=24) => KeyCode::Function(n),+ _ => return Err(anyhow!("{text:?}: {key:?} is not a key")),+ },+ },+ };+ Ok(KeyEvent { key, modifiers })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn key(key: KeyCode, modifiers: Modifiers) -> KeyEvent {+ KeyEvent { key, modifiers }+ }++ #[test]+ fn keys_are_read_the_way_shortcuts_are_written() {+ assert_eq!(+ parse_key("enter").unwrap(),+ key(KeyCode::Enter, Modifiers::NONE)+ );+ assert_eq!(+ parse_key("Return").unwrap(),+ key(KeyCode::Enter, Modifiers::NONE)+ );+ assert_eq!(+ parse_key("ctrl+c").unwrap(),+ key(KeyCode::Char('c'), Modifiers::CTRL)+ );+ assert_eq!(+ parse_key("Shift+Tab").unwrap(),+ key(KeyCode::Tab, Modifiers::SHIFT)+ );+ assert_eq!(+ parse_key("ctrl+alt+delete").unwrap(),+ key(KeyCode::Delete, Modifiers::CTRL | Modifiers::ALT)+ );+ assert_eq!(+ parse_key("up").unwrap(),+ key(KeyCode::UpArrow, Modifiers::NONE)+ );+ assert_eq!(+ parse_key("f12").unwrap(),+ key(KeyCode::Function(12), Modifiers::NONE)+ );+ assert_eq!(+ parse_key("space").unwrap(),+ key(KeyCode::Char(' '), Modifiers::NONE)+ );+ assert_eq!(+ parse_key("q").unwrap(),+ key(KeyCode::Char('q'), Modifiers::NONE)+ );+ assert_eq!(+ parse_key("/").unwrap(),+ key(KeyCode::Char('/'), Modifiers::NONE)+ );+ assert_eq!(+ parse_key("+").unwrap(),+ key(KeyCode::Char('+'), Modifiers::NONE)+ );+ assert_eq!(+ parse_key("ctrl++").unwrap(),+ key(KeyCode::Char('+'), Modifiers::CTRL)+ );+ assert_eq!(+ parse_key("cmd+k").unwrap(),+ key(KeyCode::Char('k'), Modifiers::SUPER)+ );+ }++ #[test]+ fn unknown_keys_and_modifiers_are_refused() {+ assert!(parse_key("ctrl+").is_err());+ assert!(parse_key("hyper+c").is_err());+ assert!(parse_key("f25").is_err());+ assert!(parse_key("enterr").is_err());+ }+}diff --git a/wezterm/src/cli/spawn_command.rs b/wezterm/src/cli/spawn_command.rsindex 3848531e..0ffd40f1 100644--- a/wezterm/src/cli/spawn_command.rs+++ b/wezterm/src/cli/spawn_command.rs@@ -44,6 +44,16 @@ pub struct SpawnCommand {#[arg(long, requires = "new_window")]workspace: Option<String>,+ /// Wait for the program to end, and exit with its status. The pane+ /// id is printed first, as without it.+ #[arg(long)]+ wait: bool,++ /// With --wait, give up after this long, exiting with status 124: a+ /// number of seconds, or a number with s, m or h after it.+ #[arg(long, value_parser = crate::cli::wait::parse_timeout, requires = "wait")]+ timeout: Option<std::time::Duration>,+/// Instead of executing your shell, run PROG./// For example: `thinkterm cli spawn -- bash -l` will spawn bash/// as if it were a login shell.@@ -121,6 +131,12 @@ impl SpawnCommand {log::debug!("{:?}", spawned);println!("{}", spawned.pane_id);+ if self.wait {+ let deadline = self.timeout.map(|t| std::time::Instant::now() + t);+ let code =+ crate::cli::wait::wait_for_program(&client, spawned.pane_id, deadline).await?;+ crate::cli::wait::exit_with(code);+ }Ok(())}}diff --git a/wezterm/src/cli/split_pane.rs b/wezterm/src/cli/split_pane.rsindex 04428ce1..e4255f4e 100644--- a/wezterm/src/cli/split_pane.rs+++ b/wezterm/src/cli/split_pane.rs@@ -61,6 +61,16 @@ pub struct SplitPane {#[arg(long, conflicts_with_all=&["cwd", "prog"])]move_pane_id: Option<PaneId>,+ /// Wait for the program to end, and exit with its status. The pane+ /// id is printed first, as without it.+ #[arg(long, conflicts_with = "move_pane_id")]+ wait: bool,++ /// With --wait, give up after this long, exiting with status 124: a+ /// number of seconds, or a number with s, m or h after it.+ #[arg(long, value_parser = crate::cli::wait::parse_timeout, requires = "wait")]+ timeout: Option<std::time::Duration>,+/// Instead of executing your shell, run PROG./// For example: `thinkterm cli split-pane -- bash -l` will spawn bash/// as if it were a login shell.@@ -111,6 +121,12 @@ impl SplitPane {log::debug!("{:?}", spawned);println!("{}", spawned.pane_id);+ if self.wait {+ let deadline = self.timeout.map(|t| std::time::Instant::now() + t);+ let code =+ crate::cli::wait::wait_for_program(&client, spawned.pane_id, deadline).await?;+ crate::cli::wait::exit_with(code);+ }Ok(())}}diff --git a/wezterm/src/cli/wait.rs b/wezterm/src/cli/wait.rsnew file mode 100644index 00000000..1c911a99--- /dev/null+++ b/wezterm/src/cli/wait.rs@@ -0,0 +1,383 @@+use anyhow::{anyhow, bail};+use clap::Parser;+use codec::GetPaneRunState;+use mux::pane::PaneId;+use std::time::{Duration, Instant};+use thinkterm_proto::{PaneRunState, ProgramState, ShellCommands};+use wezterm_client::client::Client;++/// What `wait` exits with when it gives up.+pub const TIMED_OUT: i32 = 124;+/// What it exits with when a program or command ended without a known status.+pub const NO_STATUS: i32 = 125;++/// How long `wait --command` gives a command just typed to start.+const START_GRACE: Duration = Duration::from_secs(1);++#[derive(Debug, Parser, Clone)]+pub struct WaitCommand {+ /// The pane to wait for.+ /// The default is to use the current pane based on the+ /// environment variable WEZTERM_PANE.+ #[arg(long)]+ pane_id: Option<PaneId>,++ /// Wait for the command running in the pane's shell to finish rather+ /// than for the pane's program to end, and exit with that command's+ /// status (125 when the shell gave none). When no command has started+ /// within a second, exits with the last command's status. To run a+ /// command and wait for it, `send-key --wait enter` is surer. Needs a+ /// shell that reports its commands (the shell integration's OSC 133+ /// marks).+ #[arg(long)]+ command: bool,++ /// Give up after this long, exiting with status 124: a number of+ /// seconds, or a number with s, m or h after it ("90", "10m").+ #[arg(long, value_parser = parse_timeout)]+ timeout: Option<Duration>,+}++impl WaitCommand {+ pub async fn run(self, client: Client) -> anyhow::Result<()> {+ let deadline = self.timeout.map(|t| Instant::now() + t);+ let code = with_deadline(deadline, async {+ let pane_id = client.resolve_pane_id(self.pane_id).await?;+ Ok(if self.command {+ let before = shell_commands(&client, pane_id).await?;+ // A command typed a moment ago may not have reached the shell.+ let (watch_until, cut_short) = start_watch(Instant::now(), deadline);+ let mut shell = before;+ while !shell.running+ && shell.finished == before.finished+ && Instant::now() < watch_until+ {+ let left = watch_until.saturating_duration_since(Instant::now());+ smol::Timer::after(left.min(Duration::from_millis(50))).await;+ shell = run_state(&client, pane_id).await?.shell;+ }+ if shell.running || shell.finished > before.finished {+ wait_for_command(&client, pane_id, before.finished, deadline).await?+ } else if cut_short {+ eprintln!("timed out");+ TIMED_OUT+ } else if shell.finished == 0 {+ 0+ } else {+ command_status(pane_id, shell.last_exit)+ }+ } else {+ wait_for_program(&client, pane_id, deadline).await?+ })+ })+ .await?;+ exit_with(code)+ }+}++/// Until when `wait --command` watches for a command to start, and whether+/// the timeout is what ends the watch: one shorter than the grace gives up+/// before a command could be told from none.+fn start_watch(now: Instant, deadline: Option<Instant>) -> (Instant, bool) {+ let grace_end = now + START_GRACE;+ match deadline {+ Some(deadline) if deadline < grace_end => (deadline, true),+ _ => (grace_end, false),+ }+}++/// Seconds, or a number followed by s, m or h.+pub fn parse_timeout(text: &str) -> anyhow::Result<Duration> {+ let text = text.trim();+ let (number, unit) = match text.find(|c: char| !c.is_ascii_digit() && c != '.') {+ Some(at) => text.split_at(at),+ None => (text, "s"),+ };+ let number: f64 = number+ .parse()+ .map_err(|_| anyhow!("{text:?} is not a duration such as 90, 30s or 10m"))?;+ let seconds = match unit {+ "s" => number,+ "m" => number * 60.0,+ "h" => number * 3600.0,+ _ => bail!("{text:?} is not a duration such as 90, 30s or 10m"),+ };+ Duration::try_from_secs_f64(seconds).map_err(|err| anyhow!("{text:?}: {err}"))+}++/// End the process with `code`, once what was printed has gone out.+pub fn exit_with(code: i32) -> ! {+ use std::io::Write;+ let _ = std::io::stdout().flush();+ std::process::exit(code)+}++async fn run_state(client: &Client, pane_id: PaneId) -> anyhow::Result<PaneRunState> {+ Ok(client+ .get_pane_run_state(GetPaneRunState { pane_id })+ .await?+ .state)+}++/// What the pane's shell has reported about its commands, or an error+/// saying it reports nothing.+pub async fn shell_commands(client: &Client, pane_id: PaneId) -> anyhow::Result<ShellCommands> {+ let shell = run_state(client, pane_id).await?.shell;+ if !shell.reported {+ bail!(+ "pane {pane_id}'s shell does not report when its commands finish; \+ load ThinkTerm's shell integration in it, or wait for a program \+ started with `spawn --wait` instead"+ );+ }+ Ok(shell)+}++/// Enforce the deadline across the whole wait, including in-flight RPCs.+/// Check again after polling: even an immediately ready result can be late.+/// The wait goes on the heap before the timer is wrapped around it: waits+/// nest, and each kept its own copy of the one inside, which outgrew the+/// main thread's stack in a debug build.+pub fn with_deadline<'a>(+ deadline: Option<Instant>,+ wait: impl std::future::Future<Output = anyhow::Result<i32>> + 'a,+) -> impl std::future::Future<Output = anyhow::Result<i32>> + 'a {+ let wait = Box::pin(wait);+ async move {+ let deadline = match deadline {+ Some(deadline) => deadline,+ None => return wait.await,+ };+ let result = smol::future::or(+ async {+ smol::Timer::at(deadline).await;+ None+ },+ async { Some(wait.await) },+ )+ .await;+ if Instant::now() < deadline {+ if let Some(result) = result {+ return result;+ }+ }+ eprintln!("timed out");+ Ok(TIMED_OUT)+ }+}++fn program_status(pane_id: PaneId, exit: &thinkterm_proto::PaneExit) -> i32 {+ exit.code.map(|code| code as i32).unwrap_or_else(|| {+ eprintln!("pane {pane_id}'s program ended without a known exit status");+ NO_STATUS+ })+}++/// Waits between asks: quick at first, for the short commands, and no+/// slower than a few times a second after that.+struct Pacing(Duration);++impl Pacing {+ fn new() -> Self {+ Self(Duration::from_millis(25))+ }++ async fn pause(&mut self) {+ smol::Timer::after(self.0).await;+ self.0 = (self.0 * 2).min(Duration::from_millis(250));+ }+}++/// Wait for the program `pane_id` started to end, and give back the status+/// to exit with.+pub async fn wait_for_program(+ client: &Client,+ pane_id: PaneId,+ deadline: Option<Instant>,+) -> anyhow::Result<i32> {+ with_deadline(deadline, async {+ let mut pacing = Pacing::new();+ let mut seen = false;+ let mut gone_since = None;+ loop {+ match run_state(client, pane_id).await {+ Ok(state) => match state.program {+ ProgramState::Exited(exit) => {+ if let Some(signal) = &exit.signal {+ eprintln!("pane {pane_id}'s program was ended by {signal}");+ }+ return Ok(program_status(pane_id, &exit));+ }+ // A pane that cannot say still closes in the end.+ ProgramState::Running | ProgramState::Unknown => seen = true,+ },+ // Gone. Its status can still be on its way: a pane is also+ // closed by its pty ending, before its program is reaped.+ Err(err) if seen && is_no_such_pane(&err) => {+ let since = *gone_since.get_or_insert_with(Instant::now);+ if since.elapsed() >= LATE_STATUS {+ eprintln!("pane {pane_id} closed without saying how its program ended");+ return Ok(1);+ }+ }+ Err(err) => return Err(err),+ }+ pacing.pause().await;+ }+ })+ .await+}++/// How long a closed pane's status may still take to arrive.+const LATE_STATUS: Duration = Duration::from_secs(1);++/// The server's answer for a pane it has no record of. Any other failure+/// -- a connection dropping, a GUI handing over -- is not the pane ending.+fn is_no_such_pane(err: &anyhow::Error) -> bool {+ format!("{err:#}").contains("no such pane")+}++/// What to exit with for a finished command's reported status.+fn command_status(pane_id: PaneId, status: Option<i32>) -> i32 {+ status.unwrap_or_else(|| {+ eprintln!("pane {pane_id}'s shell did not say how the command ended");+ NO_STATUS+ })+}++/// Wait until the pane's shell has finished more than `finished` commands,+/// and give back the status the last one reported.+pub async fn wait_for_command(+ client: &Client,+ pane_id: PaneId,+ finished: u64,+ deadline: Option<Instant>,+) -> anyhow::Result<i32> {+ with_deadline(deadline, async {+ let mut pacing = Pacing::new();+ loop {+ let state = run_state(client, pane_id).await?;+ if state.shell.finished > finished {+ return Ok(command_status(pane_id, state.shell.last_exit));+ }+ if let ProgramState::Exited(exit) = state.program {+ eprintln!("pane {pane_id}'s shell ended before the command finished");+ return Ok(program_status(pane_id, &exit));+ }+ pacing.pause().await;+ }+ })+ .await+}++#[cfg(test)]+mod tests {+ use super::{parse_timeout, start_watch, START_GRACE};+ use std::time::{Duration, Instant};++ #[test]+ fn a_stalled_rpc_times_out() {+ smol::block_on(async {+ let deadline = Instant::now() + Duration::from_millis(10);+ let code = super::with_deadline(Some(deadline), std::future::pending())+ .await+ .unwrap();+ assert_eq!(code, super::TIMED_OUT);+ });+ }++ #[test]+ fn an_expired_deadline_does_not_poll_the_rpc() {+ smol::block_on(async {+ let code = super::with_deadline(Some(Instant::now()), async {+ panic!("expired wait must not poll the RPC");+ })+ .await+ .unwrap();+ assert_eq!(code, super::TIMED_OUT);+ });+ }++ #[test]+ fn a_result_that_becomes_ready_after_the_deadline_is_not_success() {+ smol::block_on(async {+ let deadline = Instant::now() + Duration::from_millis(10);+ let code = super::with_deadline(Some(deadline), async {+ // Simulate a poll that runs across the deadline before returning.+ std::thread::sleep(Duration::from_millis(20));+ Ok(0)+ })+ .await+ .unwrap();+ assert_eq!(code, super::TIMED_OUT);+ });+ }++ #[test]+ fn a_deadline_keeps_its_wait_on_the_heap() {+ // However large the wait, the future around it is the same size.+ let small = super::with_deadline(None, async { Ok(0) });+ let large = super::with_deadline(None, async {+ let buffer = [0u8; 1 << 16];+ std::future::ready(()).await;+ Ok(i32::from(buffer[0]))+ });+ assert_eq!(std::mem::size_of_val(&small), std::mem::size_of_val(&large));+ }++ #[test]+ fn a_wait_without_a_deadline_preserves_errors_and_statuses() {+ smol::block_on(async {+ assert_eq!(+ super::with_deadline(None, async { Ok(7) }).await.unwrap(),+ 7+ );+ let error = super::with_deadline(None, async { anyhow::bail!("RPC failed") })+ .await+ .unwrap_err();+ assert_eq!(error.to_string(), "RPC failed");+ let deadline = Instant::now() + Duration::from_secs(60);+ assert_eq!(+ super::with_deadline(Some(deadline), async { Ok(0) })+ .await+ .unwrap(),+ 0+ );+ });+ }++ #[test]+ fn an_unknown_program_status_is_not_a_success() {+ let mut exit = thinkterm_proto::PaneExit {+ code: None,+ signal: None,+ };+ assert_eq!(super::program_status(1, &exit), super::NO_STATUS);+ exit.code = Some(0);+ assert_eq!(super::program_status(1, &exit), 0);+ exit.code = Some(7);+ assert_eq!(super::program_status(1, &exit), 7);+ }++ #[test]+ fn a_timeout_inside_the_start_grace_ends_the_watch() {+ let now = Instant::now();+ let short = now + Duration::from_millis(100);+ assert_eq!(start_watch(now, Some(short)), (short, true));+ assert_eq!(start_watch(now, None), (now + START_GRACE, false));+ let long = now + Duration::from_secs(5);+ assert_eq!(start_watch(now, Some(long)), (now + START_GRACE, false));+ }++ #[test]+ fn timeouts_read_seconds_minutes_and_hours() {+ assert_eq!(parse_timeout("90").unwrap(), Duration::from_secs(90));+ assert_eq!(parse_timeout("30s").unwrap(), Duration::from_secs(30));+ assert_eq!(parse_timeout("10m").unwrap(), Duration::from_secs(600));+ assert_eq!(parse_timeout("1.5h").unwrap(), Duration::from_secs(5400));+ assert_eq!(parse_timeout("0.5").unwrap(), Duration::from_millis(500));+ assert!(parse_timeout("soon").is_err());+ assert!(parse_timeout("10d").is_err());+ assert!(parse_timeout("").is_err());+ }+}