Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

fix(cli): end quietly when stdout's reader goes away

RoversX2eac0d9bfd9a
diff --git a/wezterm/src/cli/agent.rs b/wezterm/src/cli/agent.rs
index e944e7e6..c77f785b 100644
--- a/wezterm/src/cli/agent.rs
+++ b/wezterm/src/cli/agent.rs
@@ -88,7 +88,7 @@ impl AgentListCommand {
title: entry.title,
});
let mut writer = serde_json::Serializer::pretty(out.lock());
- writer.collect_seq(items)?;
+ writer.collect_seq(items).map_err(crate::stdout_error)?;
}
CliOutputFormatKind::Table => {
let now = SystemTime::now()
@@ -144,7 +144,7 @@ impl AgentListCommand {
]
})
.collect::<Vec<_>>();
- tabulate_output(&cols, &data, &mut out.lock())?;
+ tabulate_output(&cols, &data, &mut out.lock()).map_err(crate::stdout_error)?;
}
}
Ok(())
diff --git a/wezterm/src/cli/color_schemes.rs b/wezterm/src/cli/color_schemes.rs
index d2c3ca92..9be7e955 100644
--- a/wezterm/src/cli/color_schemes.rs
+++ b/wezterm/src/cli/color_schemes.rs
@@ -8,6 +8,7 @@
use clap::Parser;
use config::ColorSchemeFile;
use serde::Serialize;
+use std::io::Write;
use wezterm_term::color::ColorPalette;
#[derive(Debug, Parser, Clone)]
@@ -60,13 +61,20 @@ impl ColorSchemesCommand {
Err(err) => log::warn!("color scheme {name:?} did not parse: {err:#}"),
}
}
+ self.print(&schemes).map_err(crate::stdout_error)
+ }
+
+ fn print(&self, schemes: &[Scheme]) -> std::io::Result<()> {
+ // Buffered: the plain list is a thousand short lines.
+ let mut out = std::io::BufWriter::new(std::io::stdout().lock());
if self.json {
- println!("{}", serde_json::to_string(&schemes)?);
+ serde_json::to_writer(&mut out, schemes)?;
+ writeln!(out)?;
} else {
- for scheme in &schemes {
- println!("{}", scheme.name);
+ for scheme in schemes {
+ writeln!(out, "{}", scheme.name)?;
}
}
- Ok(())
+ out.flush()
}
}
diff --git a/wezterm/src/cli/get_text.rs b/wezterm/src/cli/get_text.rs
index a73f012c..9f811485 100644
--- a/wezterm/src/cli/get_text.rs
+++ b/wezterm/src/cli/get_text.rs
@@ -1,5 +1,6 @@
use clap::Parser;
use mux::pane::PaneId;
+use std::io::Write;
use termwiz_funcs::lines_to_escapes;
use wezterm_client::client::Client;
use wezterm_term::{ScrollbackOrVisibleRowIndex, StableRowIndex};
@@ -83,11 +84,14 @@ impl GetText {
.map(|(_idx, line)| line)
.collect();
- if self.escapes {
- println!("{}", lines_to_escapes(lines)?);
+ let mut out = std::io::stdout().lock();
+ let written = if self.escapes {
+ writeln!(out, "{}", lines_to_escapes(lines)?)
} else {
- lines.iter().for_each(|line| println!("{}", line.as_str()));
- }
- Ok(())
+ lines
+ .iter()
+ .try_for_each(|line| writeln!(out, "{}", line.as_str()))
+ };
+ written.map_err(crate::stdout_error)
}
}
diff --git a/wezterm/src/cli/list.rs b/wezterm/src/cli/list.rs
index 4438c442..a291f777 100644
--- a/wezterm/src/cli/list.rs
+++ b/wezterm/src/cli/list.rs
@@ -47,7 +47,9 @@ impl ListCommand {
match self.format {
CliOutputFormatKind::Json => {
let mut writer = serde_json::Serializer::pretty(out.lock());
- writer.collect_seq(output_items.iter())?;
+ writer
+ .collect_seq(output_items.iter())
+ .map_err(crate::stdout_error)?;
}
CliOutputFormatKind::Table => {
let cols = vec![
@@ -94,7 +96,8 @@ impl ListCommand {
]
})
.collect::<Vec<_>>();
- tabulate_output(&cols, &data, &mut std::io::stdout().lock())?;
+ tabulate_output(&cols, &data, &mut std::io::stdout().lock())
+ .map_err(crate::stdout_error)?;
}
}
Ok(())
diff --git a/wezterm/src/cli/list_clients.rs b/wezterm/src/cli/list_clients.rs
index 5697d07f..d995e63c 100644
--- a/wezterm/src/cli/list_clients.rs
+++ b/wezterm/src/cli/list_clients.rs
@@ -25,7 +25,7 @@ impl ListClientsCommand {
.cloned()
.map(CliListClientsResultItem::from);
let mut writer = serde_json::Serializer::pretty(out.lock());
- writer.collect_seq(clients)?;
+ writer.collect_seq(clients).map_err(crate::stdout_error)?;
}
CliOutputFormatKind::Table => {
let cols = vec![
@@ -107,7 +107,7 @@ impl ListClientsCommand {
]);
}
- tabulate_output(&cols, &data, &mut out.lock())?;
+ tabulate_output(&cols, &data, &mut out.lock()).map_err(crate::stdout_error)?;
}
}
Ok(())
diff --git a/wezterm/src/cli/web_token.rs b/wezterm/src/cli/web_token.rs
index 5a641604..7469d067 100644
--- a/wezterm/src/cli/web_token.rs
+++ b/wezterm/src/cli/web_token.rs
@@ -4,6 +4,7 @@
use crate::cli::CliOutputFormatKind;
use anyhow::{anyhow, bail};
use clap::Parser;
+use std::io::Write;
use tabout::{tabulate_output, Alignment, Column};
use wezterm_client::client::Client;
@@ -207,8 +208,8 @@ impl ListCommand {
live_connections: t.live_connections,
})
.collect();
- serde_json::to_writer_pretty(out.lock(), &items)?;
- println!();
+ serde_json::to_writer_pretty(out.lock(), &items).map_err(crate::stdout_error)?;
+ writeln!(out.lock()).map_err(crate::stdout_error)?;
}
CliOutputFormatKind::Table => {
let columns = [
@@ -235,7 +236,7 @@ impl ListCommand {
]
})
.collect();
- tabulate_output(&columns, &rows, &mut out.lock())?;
+ tabulate_output(&columns, &rows, &mut out.lock()).map_err(crate::stdout_error)?;
}
}
Ok(())
diff --git a/wezterm/src/main.rs b/wezterm/src/main.rs
index 8526c880..dacdaae1 100644
--- a/wezterm/src/main.rs
+++ b/wezterm/src/main.rs
@@ -1004,6 +1004,7 @@ impl ListFilesCommand {
deadline,
&mut out,
)
+ .map_err(stdout_error)
.with_context(|| format!("listing {}", self.root.display()))
}
}
@@ -1099,10 +1100,74 @@ fn terminate_with_error_message(err: &str) -> ! {
std::process::exit(1);
}
+/// A write to stdout found its reader gone: `| head` has the lines it
+/// wanted. Only the command's own output is marked this way, so a broken
+/// pipe anywhere else -- the installer an update feeds, say -- still fails.
+#[derive(Debug)]
+struct StdoutClosed;
+
+impl std::fmt::Display for StdoutClosed {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("stdout was closed")
+ }
+}
+
+impl std::error::Error for StdoutClosed {}
+
+/// For the `?` on a write to stdout.
+fn stdout_error(err: impl Into<std::io::Error>) -> anyhow::Error {
+ let err = err.into();
+ if err.kind() == std::io::ErrorKind::BrokenPipe {
+ StdoutClosed.into()
+ } else {
+ err.into()
+ }
+}
+
+fn reader_closed(err: &anyhow::Error) -> bool {
+ err.chain().any(|cause| cause.is::<StdoutClosed>())
+}
+
fn terminate_with_error(err: anyhow::Error) -> ! {
+ // The reader being done is not this command failing.
+ if reader_closed(&err) {
+ std::process::exit(0);
+ }
terminate_with_error_message(&format!("{:#}", err));
}
+#[cfg(test)]
+mod stdout_closed_tests {
+ use super::*;
+ use std::io::{Error, ErrorKind};
+
+ struct ClosedPipe;
+
+ impl Write for ClosedPipe {
+ fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
+ Err(ErrorKind::BrokenPipe.into())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+
+ #[test]
+ fn only_a_closed_stdout_ends_quietly() {
+ let closed = stdout_error(Error::from(ErrorKind::BrokenPipe));
+ assert!(reader_closed(&closed));
+ assert!(reader_closed(&closed.context("listing /home/user")));
+ // The same error from anywhere else -- an installer that quit before
+ // reading its script -- is still a failure.
+ assert!(!reader_closed(&Error::from(ErrorKind::BrokenPipe).into()));
+ let denied = Error::from(ErrorKind::PermissionDenied);
+ assert!(!reader_closed(&stdout_error(denied)));
+ // serde_json hands the io error back.
+ let json = serde_json::to_writer(ClosedPipe, &[1, 2, 3]).unwrap_err();
+ assert!(reader_closed(&stdout_error(json)));
+ }
+}
+
fn main() {
config::designate_this_as_the_main_thread();
config::assign_error_callback(mux::connui::show_configuration_error_message);
@@ -1167,7 +1232,9 @@ fn run() -> anyhow::Result<()> {
),
SubCommand::ShellCompletion { shell } => {
let rendered = render_shell_completion(shell)?;
- std::io::stdout().write_all(rendered.as_bytes())?;
+ std::io::stdout()
+ .write_all(rendered.as_bytes())
+ .map_err(stdout_error)?;
Ok(())
}
}
diff --git a/wezterm/src/plugin.rs b/wezterm/src/plugin.rs
index de1b3f7d..a8288367 100644
--- a/wezterm/src/plugin.rs
+++ b/wezterm/src/plugin.rs
@@ -51,7 +51,7 @@ impl PluginCommand {
Sub::List => {
let listed = manage(&session, api::Request::List { locale: locale() })?;
let listed: Vec<Info> = serde_json::from_value(listed)?;
- print_list(&listed);
+ print_list(&listed).map_err(crate::stdout_error)?;
}
Sub::Enable { id } | Sub::Disable { id } => {
let enabled = matches!(self.sub, Sub::Enable { .. });
@@ -131,14 +131,20 @@ fn state_label(info: &Info) -> &'static str {
}
}
-fn print_list(listed: &[Info]) {
+fn print_list(listed: &[Info]) -> std::io::Result<()> {
+ use std::io::Write;
+ let mut out = std::io::stdout().lock();
let id_width = listed
.iter()
.map(|info| info.id.chars().count())
.max()
.unwrap_or(0)
.max(2);
- println!("{:id_width$} {:11} {:10} NAME", "ID", "STATE", "VERSION");
+ writeln!(
+ out,
+ "{:id_width$} {:11} {:10} NAME",
+ "ID", "STATE", "VERSION"
+ )?;
for info in listed {
let version = if info.builtin {
"built in"
@@ -147,17 +153,19 @@ fn print_list(listed: &[Info]) {
} else {
&info.version
};
- println!(
+ writeln!(
+ out,
"{:id_width$} {:11} {:10} {}",
info.id,
state_label(info),
version,
info.name
- );
+ )?;
if let Some(reason) = info.state.reason() {
- println!("{:id_width$} {reason}", "");
+ writeln!(out, "{:id_width$} {reason}", "")?;
}
}
+ Ok(())
}
#[cfg(test)]