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.

mux, mux-server: review fixes for the summary, the deferred resize and the input queue

RoversX404c29d864ab
diff --git a/mux/src/lib.rs b/mux/src/lib.rs
index df511be2..b4001ed3 100644
--- a/mux/src/lib.rs
+++ b/mux/src/lib.rs
@@ -561,8 +561,6 @@ pub(crate) fn has_external_kitty_image_data_source(actions: &[Action]) -> bool {
})
}
-/// This function applies parsed actions to the pane and notifies any
-/// mux subscribers about the output event
/// A pane whose parser holds the terminal for a long time, on request:
/// `THINKTERM_WEDGE_PANE=<pane id>` in the server's environment makes that
/// pane's parser take its terminal lock and keep it for
@@ -593,6 +591,8 @@ fn wedge_for_the_test(pane: &Arc<dyn Pane>) {
log::warn!("THINKTERM_WEDGE_PANE: pane {wedged} released");
}
+/// This function applies parsed actions to the pane and notifies any
+/// mux subscribers about the output event
fn send_actions_to_mux(pane: &Weak<dyn Pane>, dead: &Arc<AtomicBool>, mut actions: Vec<Action>) {
let start = Instant::now();
// External kitty payloads (a path or shm name) are read here, on the
diff --git a/mux/src/localpane.rs b/mux/src/localpane.rs
index a1888cba..8167a733 100644
--- a/mux/src/localpane.rs
+++ b/mux/src/localpane.rs
@@ -351,11 +351,8 @@ impl Pane for LocalPane {
}
fn get_cursor_position(&self) -> StableCursorPosition {
- let mut cursor = terminal_get_cursor_position(&mut self.terminal.lock());
- if self.tmux_domain.lock().is_some() {
- cursor.visibility = termwiz::surface::CursorVisibility::Hidden;
- }
- cursor
+ let tmux = self.tmux_domain.lock().is_some();
+ PaneSummary::cursor_position_of(&mut self.terminal.lock(), tmux)
}
fn get_keyboard_encoding(&self) -> KeyboardEncoding {
@@ -382,23 +379,36 @@ impl Pane for LocalPane {
}
fn summary_without_waiting(&self) -> PaneSummary {
+ // The note before the snapshot: read the other way round, a
+ // parser applying the note in between would leave a snapshot
+ // from before the resize with no note to say so.
+ let resize_pending = *self.pending_resize.lock();
let mut summary = match self.terminal.try_lock() {
Some(mut term) => self.store_summary(&mut term),
None => self.last_summary.lock().clone(),
};
- // A size the terminal has yet to take is the size the pane has:
- // the pty has it, and whoever asked for it reads this next.
- if let Some(size) = *self.pending_resize.lock() {
- summary.dimensions.cols = size.cols;
- summary.dimensions.viewport_rows = size.rows;
- summary.dimensions.pixel_width = size.pixel_width;
- summary.dimensions.pixel_height = size.pixel_height;
- summary.dimensions.dpi = size.dpi;
- }
+ // Noted alongside a coherent snapshot, never patched into it:
+ // that gave a screen no terminal ever showed, with a scrollback
+ // offset from before the reflow.
+ summary.resize_pending = resize_pending;
+ summary
+ }
+
+ fn listing_summary(&self) -> PaneSummary {
+ let mut summary = self.summary_without_waiting();
self.spice_summary(&mut summary);
summary
}
+ fn title_without_waiting(&self) -> String {
+ let mut title = match self.terminal.try_lock() {
+ Some(term) => term.get_title().to_string(),
+ None => self.last_summary.lock().title.clone(),
+ };
+ self.spice_title(&mut title);
+ title
+ }
+
fn get_changed_since(
&self,
lines: Range<StableRowIndex>,
@@ -636,9 +646,11 @@ impl Pane for LocalPane {
// A resize that arrived after that last look, while the terminal
// was still held here, found both of its own probes failing and
// left its note; nothing else would read it until the next batch,
- // which a quiet program may never write. Looked at once more with
- // the terminal free, so one side or the other always applies it.
- if self.pending_resize.lock().is_some() {
+ // which a quiet program may never write. Looked at again with the
+ // terminal free, for as long as notes keep arriving: one left
+ // after the last look is applied by the resize's own second
+ // probe, which finds the terminal free.
+ while self.pending_resize.lock().is_some() {
let mut term = self.terminal.lock();
self.apply_pending_resize(&mut term);
self.store_summary(&mut term);
@@ -684,6 +696,7 @@ impl Pane for LocalPane {
Some(mut term) => {
*self.pending_resize.lock() = None;
term.resize(size);
+ self.store_summary(&mut term);
}
None => {
*self.pending_resize.lock() = Some(size);
@@ -692,6 +705,7 @@ impl Pane for LocalPane {
// applies one left after it.
if let Some(mut term) = self.terminal.try_lock() {
self.apply_pending_resize(&mut term);
+ self.store_summary(&mut term);
}
}
}
@@ -720,18 +734,8 @@ impl Pane for LocalPane {
}
fn get_title(&self) -> String {
- let title = self.terminal.lock().get_title().to_string();
- // If the title is the default pane title, then try to spice
- // things up a bit by returning the process basename instead
- if title == "thinkterm" {
- if let Some(proc_name) = self.get_foreground_process_name(CachePolicy::AllowStale) {
- let proc_name = std::path::Path::new(&proc_name);
- if let Some(name) = proc_name.file_name() {
- return name.to_string_lossy().to_string();
- }
- }
- }
-
+ let mut title = self.terminal.lock().get_title().to_string();
+ self.spice_title(&mut title);
title
}
@@ -760,14 +764,12 @@ impl Pane for LocalPane {
}
fn erase_scrollback(&self, erase_mode: ScrollbackEraseMode) {
+ let mut term = self.terminal.lock();
match erase_mode {
- ScrollbackEraseMode::ScrollbackOnly => {
- self.terminal.lock().erase_scrollback();
- }
- ScrollbackEraseMode::ScrollbackAndViewport => {
- self.terminal.lock().erase_scrollback_and_viewport();
- }
+ ScrollbackEraseMode::ScrollbackOnly => term.erase_scrollback(),
+ ScrollbackEraseMode::ScrollbackAndViewport => term.erase_scrollback_and_viewport(),
}
+ self.store_summary(&mut term);
}
fn focus_changed(&self, focused: bool) {
@@ -787,19 +789,13 @@ impl Pane for LocalPane {
}
fn is_alt_screen_active(&self) -> bool {
- if self.tmux_domain.lock().is_some() {
- false
- } else {
- self.terminal.lock().is_alt_screen_active()
- }
+ let tmux = self.tmux_domain.lock().is_some();
+ PaneSummary::alt_screen_of(&self.terminal.lock(), tmux)
}
fn get_current_working_dir(&self, policy: CachePolicy) -> Option<Url> {
- self.terminal
- .lock()
- .get_current_dir()
- .cloned()
- .or_else(|| self.divine_current_working_dir(policy))
+ let reported = self.terminal.lock().get_current_dir().cloned();
+ self.working_dir_or_divined(reported, policy)
}
fn tty_name(&self) -> Option<String> {
@@ -1314,7 +1310,7 @@ impl LocalPane {
tmux_domain: None,
}));
terminal.set_notification_handler(Box::new(LocalPaneNotifHandler { pane_id }));
- let last_summary = Mutex::new(raw_summary(&mut terminal, false));
+ let last_summary = Mutex::new(PaneSummary::from_terminal(&mut terminal, false));
Self {
pane_id,
@@ -1342,29 +1338,38 @@ impl LocalPane {
/// nothing that needs a process lookup. `spice_summary` adds that at
/// read time, so the parser thread never does it.
fn store_summary(&self, term: &mut Terminal) -> PaneSummary {
- let summary = raw_summary(term, self.tmux_domain.lock().is_some());
+ let summary = PaneSummary::from_terminal(term, self.tmux_domain.lock().is_some());
*self.last_summary.lock() = summary.clone();
summary
}
/// What `get_title` and `get_current_working_dir` add beyond the
- /// terminal's own answer: the foreground process name for a pane that
- /// never set a title, and a working directory divined from that
- /// process when the shell reported none. Both come from the cached
- /// process list, never from the terminal.
+ /// terminal's own answer, from the cached process list and never from
+ /// the terminal. `listing_summary` is the summary with these on.
fn spice_summary(&self, summary: &mut PaneSummary) {
- if summary.title == "thinkterm" {
- if let Some(proc_name) = self.get_foreground_process_name(CachePolicy::AllowStale) {
- if let Some(name) = std::path::Path::new(&proc_name).file_name() {
- summary.title = name.to_string_lossy().to_string();
- }
- }
+ self.spice_title(&mut summary.title);
+ summary.working_dir =
+ self.working_dir_or_divined(summary.working_dir.take(), CachePolicy::AllowStale);
+ }
+
+ /// A pane that never set a title is named after its foreground process.
+ fn spice_title(&self, title: &mut String) {
+ if title != "thinkterm" {
+ return;
}
- if summary.working_dir.is_none() {
- summary.working_dir = self.divine_current_working_dir(CachePolicy::AllowStale);
+ if let Some(proc_name) = self.get_foreground_process_name(CachePolicy::AllowStale) {
+ if let Some(name) = std::path::Path::new(&proc_name).file_name() {
+ *title = name.to_string_lossy().to_string();
+ }
}
}
+ /// The directory the shell reported, or the one divined from the
+ /// foreground process when it reported none.
+ fn working_dir_or_divined(&self, reported: Option<Url>, policy: CachePolicy) -> Option<Url> {
+ reported.or_else(|| self.divine_current_working_dir(policy))
+ }
+
/// Give the terminal a size the pty already has. Called with the
/// terminal lock held, before and after a batch of output: before, so
/// output written in answer to the resize is parsed at the new size;
@@ -1503,23 +1508,6 @@ impl Drop for LocalPane {
}
}
-/// The summary straight from the terminal, under the guard the caller
-/// holds. `tmux` hides the cursor and the alternate screen the way the
-/// individual readers do for a pane that fronts a tmux control mode.
-fn raw_summary(term: &mut Terminal, tmux: bool) -> PaneSummary {
- let mut cursor_position = terminal_get_cursor_position(term);
- if tmux {
- cursor_position.visibility = termwiz::surface::CursorVisibility::Hidden;
- }
- PaneSummary {
- title: term.get_title().to_string(),
- dimensions: terminal_get_dimensions(term),
- cursor_position,
- working_dir: term.get_current_dir().cloned(),
- alt_screen: !tmux && term.is_alt_screen_active(),
- }
-}
-
#[cfg(test)]
mod summary_tests {
use super::*;
@@ -1615,6 +1603,13 @@ mod summary_tests {
Arc<StdMutex<Vec<PtySize>>>,
std::sync::mpsc::Sender<()>,
) {
+ // The waiter thread `LocalPane::new` starts hops to the main
+ // thread when the child exits; with no scheduler that is a panic
+ // that poisons promise's scheduler lock for every test after.
+ static SCHEDULER: std::sync::Once = std::sync::Once::new();
+ SCHEDULER.call_once(|| {
+ promise::spawn::SimpleExecutor::new();
+ });
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
let sizes = Arc::new(StdMutex::new(vec![]));
let terminal = Terminal::new(
@@ -1669,11 +1664,17 @@ mod summary_tests {
vec![100, 120],
"the pty took both at once"
);
+ let summary = pane.summary_without_waiting();
+ assert_eq!(
+ summary.resize_pending.map(|s| s.cols),
+ Some(120),
+ "the summary notes the size the pane has"
+ );
assert_eq!(
- pane.summary_without_waiting().dimensions.cols,
- 120,
- "the summary already says the size the pane has"
+ summary.dimensions.cols, 80,
+ "next to a coherent snapshot of what the screen still shows"
);
+ assert_eq!(summary.terminal_size().cols, 120);
assert_eq!(guard.get_size().cols, 80, "the terminal has neither yet");
drop(guard);
// The parser's next batch, empty as it may be.
@@ -1703,10 +1704,36 @@ mod summary_tests {
}
#[test]
- fn a_resize_with_the_terminal_free_lands_at_once() {
+ fn a_resize_with_the_terminal_free_lands_at_once_and_refreshes_the_summary() {
let (pane, _sizes, _exit) = pane();
pane.resize(size(90, 20)).unwrap();
assert_eq!(pane.get_dimensions().cols, 90);
assert!(pane.pending_resize.lock().is_none());
+ let guard = pane.terminal.lock();
+ let summary = pane.summary_without_waiting();
+ assert_eq!(summary.dimensions.cols, 90, "the stored copy moved with it");
+ assert!(summary.resize_pending.is_none());
+ drop(guard);
+ }
+
+ #[test]
+ fn erasing_the_scrollback_refreshes_the_summary() {
+ let (pane, _sizes, _exit) = pane();
+ for _ in 0..40 {
+ pane.perform_actions(vec![
+ termwiz::escape::Action::Print('x'),
+ termwiz::escape::Action::Control(termwiz::escape::ControlCode::LineFeed),
+ ]);
+ }
+ let before = pane.get_dimensions().scrollback_rows;
+ pane.erase_scrollback(ScrollbackEraseMode::ScrollbackAndViewport);
+ let guard = pane.terminal.lock();
+ let summary = pane.summary_without_waiting();
+ assert!(summary.dimensions.scrollback_rows < before);
+ assert_eq!(
+ summary.dimensions.scrollback_rows,
+ guard.screen().physical_rows
+ );
+ drop(guard);
}
}
diff --git a/mux/src/pane.rs b/mux/src/pane.rs
index d0ca0710..732b27a8 100644
--- a/mux/src/pane.rs
+++ b/mux/src/pane.rs
@@ -188,7 +188,8 @@ impl LogicalLine {
/// The facts about a pane that a listing shows: what `Tab` reads for its
/// pane tree and a mux server answers `ListPanes` with. Gathered under one
/// guard where the pane has one, and kept where it can be handed out even
-/// while the pane's parser holds that guard.
+/// while the pane's parser holds that guard. Always one coherent snapshot
+/// of the terminal; a size the terminal has yet to take rides alongside.
#[derive(Debug, Clone)]
pub struct PaneSummary {
pub title: String,
@@ -196,6 +197,53 @@ pub struct PaneSummary {
pub cursor_position: StableCursorPosition,
pub working_dir: Option<Url>,
pub alt_screen: bool,
+ /// A size the pane's pty already has but its terminal does not yet,
+ /// because the parser held the terminal when the resize came. The
+ /// size the pane *has*; `dimensions` is what its screen still shows.
+ pub resize_pending: Option<TerminalSize>,
+}
+
+impl PaneSummary {
+ /// The snapshot straight from a terminal, under the guard the caller
+ /// holds. `tmux` hides the cursor and the alternate screen, as the
+ /// individual readers do for a pane fronting a tmux control mode.
+ pub fn from_terminal(term: &mut wezterm_term::Terminal, tmux: bool) -> Self {
+ Self {
+ title: term.get_title().to_string(),
+ dimensions: terminal_get_dimensions(term),
+ cursor_position: Self::cursor_position_of(term, tmux),
+ working_dir: term.get_current_dir().cloned(),
+ alt_screen: Self::alt_screen_of(term, tmux),
+ resize_pending: None,
+ }
+ }
+
+ pub fn cursor_position_of(
+ term: &mut wezterm_term::Terminal,
+ tmux: bool,
+ ) -> StableCursorPosition {
+ let mut cursor = terminal_get_cursor_position(term);
+ if tmux {
+ cursor.visibility = termwiz::surface::CursorVisibility::Hidden;
+ }
+ cursor
+ }
+
+ pub fn alt_screen_of(term: &wezterm_term::Terminal, tmux: bool) -> bool {
+ !tmux && term.is_alt_screen_active()
+ }
+
+ /// The size the pane has: the pending one when a resize is waiting
+ /// on the parser, otherwise the one its screen shows.
+ pub fn terminal_size(&self) -> TerminalSize {
+ self.resize_pending.unwrap_or(TerminalSize {
+ cols: self.dimensions.cols,
+ rows: self.dimensions.viewport_rows,
+ pixel_width: self.dimensions.pixel_width,
+ pixel_height: self.dimensions.pixel_height,
+ dpi: self.dimensions.dpi,
+ })
+ }
}
/// A Pane represents a view on a terminal
@@ -315,9 +363,10 @@ pub trait Pane: Downcast + Send + Sync {
let _ = hold;
}
- /// What a listing shows of this pane, without waiting for its parser:
- /// the facts as they are if they can be read now, otherwise as they
- /// were last read. A pane with nothing to wait for reads them now.
+ /// The terminal's own facts about this pane, without waiting for its
+ /// parser: as they are if they can be read now, otherwise as they were
+ /// last read. Nothing here consults the process behind the pane. A
+ /// pane with nothing to wait for reads them now.
fn summary_without_waiting(&self) -> PaneSummary {
PaneSummary {
title: self.get_title(),
@@ -325,9 +374,24 @@ pub trait Pane: Downcast + Send + Sync {
cursor_position: self.get_cursor_position(),
working_dir: self.get_current_working_dir(CachePolicy::AllowStale),
alt_screen: self.is_alt_screen_active(),
+ resize_pending: None,
}
}
+ /// `summary_without_waiting` with what a listing wants on top: the
+ /// title and working directory the way `get_title` and
+ /// `get_current_working_dir` would give them, process lookups
+ /// included. Costlier than the summary; not for a per-frame path.
+ fn listing_summary(&self) -> PaneSummary {
+ self.summary_without_waiting()
+ }
+
+ /// `get_title`, without waiting for the parser. For paths that paint
+ /// every frame and want nothing else.
+ fn title_without_waiting(&self) -> String {
+ self.summary_without_waiting().title
+ }
+
fn copy_user_vars(&self) -> HashMap<String, String> {
HashMap::new()
}
diff --git a/mux/src/tab.rs b/mux/src/tab.rs
index a7705d8b..684213ad 100644
--- a/mux/src/tab.rs
+++ b/mux/src/tab.rs
@@ -169,7 +169,7 @@ impl PaneStack {
.enumerate()
.map(|(idx, pane)| PaneStackTab {
pane_id: pane.pane_id(),
- title: pane.summary_without_waiting().title,
+ title: pane.title_without_waiting(),
is_active: idx == active,
})
.collect()
@@ -343,7 +343,7 @@ fn pane_tree(
// One read that does not wait for the pane's parser, in place of
// five that each did: a listing must answer while one pane is
// busy, and it is answered on the thread that serves every pane.
- let summary = pane.summary_without_waiting();
+ let summary = pane.listing_summary();
let dims = summary.dimensions;
PaneEntry {
@@ -776,7 +776,9 @@ fn compute_tree_size_from_panes(node: &mut Tree, tab_cell: &TerminalSize) -> Opt
Tree::Empty => None,
Tree::Leaf(stack) => {
let pane = stack.active_pane()?;
- let dims = pane.summary_without_waiting().dimensions;
+ // The size the pane has, a pending one included: its pty
+ // already has that, and this derives what the tab asked for.
+ let dims = pane.summary_without_waiting().terminal_size();
let cell_width = tab_cell.pixel_width;
let cell_height = tab_cell.pixel_height;
// Fall back to the pane's own counts when it cannot describe
@@ -790,7 +792,7 @@ fn compute_tree_size_from_panes(node: &mut Tree, tab_cell: &TerminalSize) -> Opt
let rows = if cell_height > 0 && dims.pixel_height > 0 {
(dims.pixel_height / cell_height).max(1)
} else {
- dims.viewport_rows
+ dims.rows
};
let size = TerminalSize {
cols,
@@ -3155,14 +3157,7 @@ impl TabInner {
let stack = cursor.leaf_mut().unwrap();
if stack.contains_pane(base_pane_id) {
if let Some(base) = stack.active_pane() {
- let dims = base.summary_without_waiting().dimensions;
- pane.resize(TerminalSize {
- rows: dims.viewport_rows,
- cols: dims.cols,
- pixel_height: dims.pixel_height,
- pixel_width: dims.pixel_width,
- dpi: dims.dpi,
- })?;
+ pane.resize(base.summary_without_waiting().terminal_size())?;
}
stack.push_and_activate(Arc::clone(&pane));
found = true;
@@ -3233,14 +3228,7 @@ impl TabInner {
if has_target {
target_found = true;
if let Some(active) = stack.active_pane() {
- let dims = active.summary_without_waiting().dimensions;
- target_dims = Some(TerminalSize {
- rows: dims.viewport_rows,
- cols: dims.cols,
- pixel_height: dims.pixel_height,
- pixel_width: dims.pixel_width,
- dpi: dims.dpi,
- });
+ target_dims = Some(active.summary_without_waiting().terminal_size());
}
}
if has_src && has_target {
@@ -3292,14 +3280,9 @@ impl TabInner {
if let Some(base) =
stack.active_pane().filter(|_| !removed.is_remote_mirror())
{
- let dims = base.summary_without_waiting().dimensions;
- if let Err(err) = removed.resize(TerminalSize {
- rows: dims.viewport_rows,
- cols: dims.cols,
- pixel_height: dims.pixel_height,
- pixel_width: dims.pixel_width,
- dpi: dims.dpi,
- }) {
+ if let Err(err) =
+ removed.resize(base.summary_without_waiting().terminal_size())
+ {
log::error!(
"move_pane_to_stack: resize after rebalance failed: {err:#}"
);
@@ -3877,6 +3860,7 @@ mod test {
cursor_position: StableCursorPosition::default(),
working_dir: None,
alt_screen: false,
+ resize_pending: None,
}
}
}
diff --git a/mux/src/termwiztermtab.rs b/mux/src/termwiztermtab.rs
index 436bbb73..f3e55890 100644
--- a/mux/src/termwiztermtab.rs
+++ b/mux/src/termwiztermtab.rs
@@ -93,6 +93,9 @@ pub struct TermWizTerminalPane {
dead: Mutex<bool>,
writer: Mutex<Vec<u8>>,
render_rx: FileDescriptor,
+ /// As `LocalPane::last_summary`: the render thread holds the terminal
+ /// for the whole of a batch, and the tab must not wait on it.
+ last_summary: Mutex<crate::pane::PaneSummary>,
}
impl TermWizTerminalPane {
@@ -105,22 +108,27 @@ impl TermWizTerminalPane {
) -> Self {
let pane_id = alloc_pane_id();
- let terminal = Mutex::new(wezterm_term::Terminal::new(
+ let mut terminal = wezterm_term::Terminal::new(
size,
term_config.unwrap_or_else(|| Arc::new(config::TermConfig::new())),
"ThinkTerm",
config::wezterm_version(),
Box::new(Vec::new()), // FIXME: connect to something?
+ );
+ let last_summary = Mutex::new(crate::pane::PaneSummary::from_terminal(
+ &mut terminal,
+ false,
));
Self {
pane_id,
domain_id,
- terminal,
+ terminal: Mutex::new(terminal),
writer: Mutex::new(Vec::new()),
render_rx,
input_tx,
dead: Mutex::new(false),
+ last_summary,
}
}
}
@@ -130,6 +138,17 @@ impl Pane for TermWizTerminalPane {
self.terminal.try_lock().is_none()
}
+ fn summary_without_waiting(&self) -> crate::pane::PaneSummary {
+ match self.terminal.try_lock() {
+ Some(mut term) => {
+ let summary = crate::pane::PaneSummary::from_terminal(&mut term, false);
+ *self.last_summary.lock() = summary.clone();
+ summary
+ }
+ None => self.last_summary.lock().clone(),
+ }
+ }
+
fn pane_id(&self) -> PaneId {
self.pane_id
}
@@ -274,7 +293,9 @@ impl Pane for TermWizTerminalPane {
crate::materialize_kitty_image_data_sources(&mut actions);
}
}
- self.terminal.lock().perform_actions(actions)
+ let mut term = self.terminal.lock();
+ term.perform_actions(actions);
+ *self.last_summary.lock() = crate::pane::PaneSummary::from_terminal(&mut term, false);
}
fn kill(&self) {
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index 30b10ece..16e6f25d 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -120,6 +120,14 @@ enum PaneInput {
EraseScrollback(ScrollbackEraseMode),
}
+impl PaneInput {
+ /// Whether applying this needs the pane's terminal, and so a pane
+ /// that is free. Bytes for the pty do not.
+ fn needs_the_terminal(&self) -> bool {
+ !matches!(self, PaneInput::Write(_))
+ }
+}
+
/// Input waiting in `PerPane::inputs`, with the reply its request is owed.
struct QueuedInput {
input: PaneInput,
@@ -426,7 +434,9 @@ async fn push_pane_changes_when_free(
per_pane: Arc::clone(&per_pane),
released: false,
};
- let Some(pane) = pane_when_free(pane_id, &sender, "this push").await? else {
+ let Some(pane) =
+ pane_when_free(pane_id, &sender, "this push", Some(PUSH_DEFERRAL_LIMIT)).await?
+ else {
// Its next output will try again.
return Ok(());
};
@@ -440,19 +450,22 @@ async fn push_pane_changes_when_free(
}
/// The pane, once its render state can be read without waiting on its
-/// parser; None after `PUSH_DEFERRAL_LIMIT` of nothing but contention,
-/// with a warning naming `what` gave up. Every read of a pane on the main
-/// thread goes through here, so a pane wedged in its parser costs its own
-/// readers a wait and nobody else anything. The probe is a moment's
-/// glance, not a reservation; a pane that takes the lock back right after
-/// it still has to be waited for, once.
+/// parser. With a `limit`, None after that long of nothing but
+/// contention, with a warning naming `what` gave up; without one the wait
+/// is for as long as it takes, and the warning says so once. Every read
+/// of a pane on the main thread goes through here, so a pane wedged in
+/// its parser costs its own readers a wait and nobody else anything. The
+/// probe is a moment's glance, not a reservation; a pane that takes the
+/// lock back right after it still has to be waited for, once.
async fn pane_when_free(
pane_id: PaneId,
sender: &PduSender,
what: &str,
+ limit: Option<Duration>,
) -> anyhow::Result<Option<Arc<dyn Pane>>> {
let mut delay = PUSH_RETRY_MIN;
let started = Instant::now();
+ let mut warned = false;
loop {
if sender.is_closed() {
anyhow::bail!("connection closed while pane {pane_id} was busy");
@@ -463,12 +476,21 @@ async fn pane_when_free(
if !pane.render_state_is_contended() {
return Ok(Some(pane));
}
- if started.elapsed() > PUSH_DEFERRAL_LIMIT {
- log::warn!(
- "pane {pane_id} has been busy for {:?}; giving up on {what}",
- started.elapsed()
- );
- return Ok(None);
+ if started.elapsed() > limit.unwrap_or(PUSH_DEFERRAL_LIMIT) {
+ if limit.is_some() {
+ log::warn!(
+ "pane {pane_id} has been busy for {:?}; giving up on {what}",
+ started.elapsed()
+ );
+ return Ok(None);
+ }
+ if !warned {
+ warned = true;
+ log::warn!(
+ "pane {pane_id} has been busy for {:?}; {what} waits for it",
+ started.elapsed()
+ );
+ }
}
metrics::counter!("mux_server.push.deferred").increment(1);
smol::Timer::after(delay).await;
@@ -488,10 +510,12 @@ async fn pane_when_free(
/// a client's input in the order it sent it, which is what the shared
/// main-thread queue used to guarantee.
///
-/// A pane busy past `PUSH_DEFERRAL_LIMIT` fails the piece in hand and
-/// everything queued behind it -- the client is told, rather than left
-/// with input that lands minutes later -- and the drain ends; the next
-/// input starts a fresh one.
+/// Input is never given up on: a keystroke that lands late is what the
+/// user typed, one that is thrown away is not, and only this pane waits.
+/// Bytes for the pty need no terminal at all -- kitty and win32 keys,
+/// composed text, `SendString`, `cli send-text` all arrive that way --
+/// and go to the pty as soon as they reach the head of the queue, so a
+/// Ctrl-C still reaches a program whose output is what wedged the pane.
async fn drain_pane_inputs(
pane_id: PaneId,
sender: PduSender,
@@ -510,13 +534,17 @@ async fn drain_pane_inputs(
let Some(item) = drain.next() else {
return;
};
- let pane = match pane_when_free(pane_id, &sender, "its input").await {
- Ok(Some(pane)) => pane,
- Ok(None) => {
- drain.why = "the pane stayed busy";
- (item.respond)(Err(anyhow!("pane {pane_id} is busy")));
- return;
- }
+ let pane = if item.input.needs_the_terminal() {
+ pane_when_free(pane_id, &sender, "its input", None)
+ .await
+ .and_then(|pane| pane.ok_or_else(|| anyhow!("pane {pane_id} is busy")))
+ } else {
+ Mux::get()
+ .get_pane(pane_id)
+ .ok_or_else(|| anyhow!("no such pane {pane_id}"))
+ };
+ let pane = match pane {
+ Ok(pane) => pane,
Err(err) => {
drain.why = "the pane or the connection went away";
(item.respond)(Err(err));
@@ -525,6 +553,9 @@ async fn drain_pane_inputs(
};
let result = apply_pane_input(&pane, &sender, &per_pane, &source, item.input);
(item.respond)(result);
+ // A burst typed while the pane was busy is applied a piece per
+ // turn of the main thread, not all in one.
+ smol::future::yield_now().await;
}
}
@@ -588,6 +619,10 @@ fn apply_pane_input(
let mux = Mux::get();
let _identity = mux.with_identity(source.client_id.clone());
if let PaneInput::EraseScrollback(erase_mode) = input {
+ // Checked when the request arrived; checked again now that the
+ // wait for the pane may have been long enough for the terminal
+ // to change hands.
+ require_registered_frontend_access(&mux, source.client_id.as_ref(), source.registration)?;
pane.erase_scrollback(erase_mode);
return Ok(Pdu::UnitResponse(UnitResponse {}));
}
@@ -640,7 +675,17 @@ fn apply_pane_input(
}
PaneInput::Write(data) => {
pane.writer().write_all(&data)?;
- None
+ // The pane may be busy (see `PaneInput::needs_the_terminal`);
+ // its push is read once it is free, like any other.
+ if per_pane.lock().unwrap().claim_push() {
+ spawn_into_main_thread(push_pane_changes_when_free(
+ pane.pane_id(),
+ sender.clone(),
+ Arc::clone(per_pane),
+ ))
+ .detach();
+ }
+ return Ok(Pdu::UnitResponse(UnitResponse {}));
}
PaneInput::EraseScrollback(_) => unreachable!("answered above"),
};
@@ -1352,8 +1397,6 @@ impl SessionHandler {
);
}
Pdu::KillPane(KillPane { pane_id }) => {
- let sender = self.to_write_tx.clone();
- let per_pane = self.per_pane(pane_id);
spawn_into_main_thread(async move {
catch(
move || {
@@ -1362,16 +1405,9 @@ impl SessionHandler {
.get_pane(pane_id)
.ok_or_else(|| anyhow!("no such pane {}", pane_id))?;
pane.kill();
+ // No push for a pane that is gone: PaneRemoved
+ // tells the client everything it needs.
mux.remove_pane(pane_id);
- // Like every push: read once the pane is free,
- // not here. It is gone by then, and the push
- // finds nothing to do.
- if per_pane.lock().unwrap().claim_push() {
- spawn_into_main_thread(push_pane_changes_when_free(
- pane_id, sender, per_pane,
- ))
- .detach();
- }
Ok(Pdu::UnitResponse(UnitResponse {}))
},
send_response,
@@ -1400,8 +1436,13 @@ impl SessionHandler {
) -> anyhow::Result<Pdu> {
// The search holds the terminal for its whole run, on
// the main thread: only once the pane is free.
- let Some(pane) =
- pane_when_free(pane_id, &sender, "a scrollback search").await?
+ let Some(pane) = pane_when_free(
+ pane_id,
+ &sender,
+ "a scrollback search",
+ Some(PUSH_DEFERRAL_LIMIT),
+ )
+ .await?
else {
anyhow::bail!("pane {pane_id} is busy");
};
@@ -1917,7 +1958,14 @@ impl SessionHandler {
// Read once the pane can be read without waiting, like
// a push: the client asks again for rows it does not
// get, and the main thread has everyone else's work.
- let pane = match pane_when_free(pane_id, &sender, "a row fetch").await {
+ let pane = match pane_when_free(
+ pane_id,
+ &sender,
+ "a row fetch",
+ Some(PUSH_DEFERRAL_LIMIT),
+ )
+ .await
+ {
Ok(Some(pane)) => pane,
Ok(None) => {
send_response(Err(anyhow!("pane {pane_id} is busy")));
@@ -1973,7 +2021,14 @@ impl SessionHandler {
// be read without waiting.
let mut data = per_pane.lock().unwrap().sent_images.get(&data_hash);
let pane = if data.is_none() {
- match pane_when_free(pane_id, &sender, "an image fetch").await {
+ match pane_when_free(
+ pane_id,
+ &sender,
+ "an image fetch",
+ Some(PUSH_DEFERRAL_LIMIT),
+ )
+ .await
+ {
Ok(Some(pane)) => Some(pane),
Ok(None) => {
send_response(Err(anyhow!("pane {pane_id} is busy")));
@@ -2688,6 +2743,16 @@ mod tests {
assert!(state.needs_application_palette(&None));
}
+ #[test]
+ fn only_bytes_for_the_pty_skip_the_wait_for_a_free_pane() {
+ assert!(!PaneInput::Write(vec![]).needs_the_terminal());
+ assert!(PaneInput::Paste(String::new()).needs_the_terminal());
+ assert!(PaneInput::EraseScrollback(
+ config::keyassignment::ScrollbackEraseMode::ScrollbackOnly
+ )
+ .needs_the_terminal());
+ }
+
/// Input for a pane waits in its queue in the order it was sent; a
/// drain that ends early answers what it leaves behind and lets the
/// next input start a new one.