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(client): put back a pane size the server kept, without blanking

RoversX26d9102a061f
diff --git a/thinkterm-session/src/decide.rs b/thinkterm-session/src/decide.rs
index 992b4980..83707832 100644
--- a/thinkterm-session/src/decide.rs
+++ b/thinkterm-session/src/decide.rs
@@ -1,6 +1,8 @@
//! Pure decisions a pane makes about resizing, palettes and its watchdog,
//! off the network so the ordering rules are unit-testable. Moved from the
//! desktop client's `clientpane.rs`; every client makes these the same way.
+use crate::clock::Timestamp;
+use std::time::Duration;
use thinkterm_proto::RenderableDimensions;
use wezterm_term::color::ColorPalette;
use wezterm_term::TerminalSize;
@@ -198,6 +200,82 @@ pub fn finish_preview_request(
}
}
+/// How long the server may keep a pane at another size than the one its
+/// frontend settled on before the frontend says it again: long enough for a
+/// viewport report still on its way (debounced, then a round trip) to land.
+pub const GEOMETRY_REPAIR_GRACE: Duration = Duration::from_millis(500);
+/// How long a resent size gets to land before it is sent again.
+pub const GEOMETRY_REPAIR_RETRY: Duration = Duration::from_secs(2);
+/// How often one size is resent before the frontend stops insisting on it.
+pub const GEOMETRY_REPAIR_ATTEMPTS: u32 = 3;
+
+/// A pane whose size on the server disagrees with the one its frontend
+/// settled on.
+///
+/// Viewport reports carry the frontend's sizes, and the server skips a
+/// report identical to the last one. A size the server changed on its own
+/// since (a zoomed pane stack switching pages gives the new page the whole
+/// tab, before the pane's font scale and nav bar) was therefore never put
+/// back: the frontend reshaped only its own copy on every paint, every push
+/// restored the server's, and for a different width that blanked the whole
+/// pane each time.
+#[derive(Debug, Default)]
+pub struct GeometryRepair {
+ target: Option<TerminalSize>,
+ since: Timestamp,
+ sent_at: Option<Timestamp>,
+ attempts: u32,
+}
+
+impl GeometryRepair {
+ /// Whether to resend `target` now, given the dimensions the server last
+ /// reported. The disagreement has to outlast `GEOMETRY_REPAIR_GRACE` for
+ /// the same target; a new target starts the wait over, so a window that
+ /// is still being dragged sends nothing until it holds still.
+ pub fn should_resend(
+ &mut self,
+ server: RenderableDimensions,
+ target: TerminalSize,
+ now: Timestamp,
+ ) -> bool {
+ if render_dimensions_match_size(server, target) {
+ *self = Self::default();
+ return false;
+ }
+ if self.target != Some(target) {
+ *self = Self {
+ target: Some(target),
+ since: now,
+ ..Self::default()
+ };
+ return false;
+ }
+ let due = self.due().is_some_and(|due| now >= due);
+ if due {
+ self.sent_at = Some(now);
+ self.attempts += 1;
+ }
+ due
+ }
+
+ /// How long until `should_resend` could say yes. A pane that stopped
+ /// drawing may not paint again by itself, so the caller has to look
+ /// again then. None when nothing is pending.
+ pub fn next_check_in(&self, now: Timestamp) -> Option<Duration> {
+ self.due().map(|due| due.saturating_duration_since(now))
+ }
+
+ fn due(&self) -> Option<Timestamp> {
+ if self.target.is_none() || self.attempts >= GEOMETRY_REPAIR_ATTEMPTS {
+ return None;
+ }
+ Some(match self.sent_at {
+ None => self.since + GEOMETRY_REPAIR_GRACE,
+ Some(sent_at) => sent_at + GEOMETRY_REPAIR_RETRY,
+ })
+ }
+}
+
#[cfg(test)]
mod test {
use super::*;
@@ -392,6 +470,105 @@ mod test {
assert!(render_watchdog_should_run(false));
assert!(!render_watchdog_should_run(true));
}
+
+ fn at(ms: u64) -> Timestamp {
+ Timestamp::from_micros(ms * 1000)
+ }
+
+ #[test]
+ fn a_server_left_at_another_size_is_told_again_after_the_grace() {
+ let target = size(97, 26, 144);
+ let server = dimensions(size(118, 34, 144));
+ let mut repair = GeometryRepair::default();
+
+ assert!(!repair.should_resend(server, target, at(0)));
+ assert!(
+ !repair.should_resend(server, target, at(400)),
+ "a report still on its way gets the grace to land"
+ );
+ assert!(repair.should_resend(server, target, at(500)));
+ assert!(
+ !repair.should_resend(server, target, at(600)),
+ "one resend at a time"
+ );
+ }
+
+ #[test]
+ fn a_server_that_agrees_is_left_alone_and_clears_the_repair() {
+ let target = size(97, 26, 144);
+ let mut repair = GeometryRepair::default();
+
+ assert!(!repair.should_resend(dimensions(target), target, at(0)));
+ assert!(!repair.should_resend(dimensions(size(118, 34, 144)), target, at(1000)));
+ assert!(!repair.should_resend(dimensions(target), target, at(1400)));
+ assert!(
+ !repair.should_resend(dimensions(size(118, 34, 144)), target, at(1600)),
+ "agreement in between starts the grace over"
+ );
+ assert!(repair.should_resend(dimensions(size(118, 34, 144)), target, at(2100)));
+ }
+
+ #[test]
+ fn a_target_that_keeps_moving_is_not_resent() {
+ let server = dimensions(size(118, 34, 144));
+ let mut repair = GeometryRepair::default();
+
+ for step in 0..10 {
+ assert!(
+ !repair.should_resend(server, size(80 + step, 26, 144), at(step as u64 * 300)),
+ "a window being dragged is not chased"
+ );
+ }
+ }
+
+ #[test]
+ fn resends_are_spaced_and_end_after_a_few_attempts() {
+ let target = size(97, 26, 144);
+ let server = dimensions(size(118, 34, 144));
+ let mut repair = GeometryRepair::default();
+
+ assert!(!repair.should_resend(server, target, at(0)));
+ assert!(repair.should_resend(server, target, at(500)));
+ assert!(!repair.should_resend(server, target, at(2000)));
+ assert!(repair.should_resend(server, target, at(2500)));
+ assert!(repair.should_resend(server, target, at(4500)));
+ assert!(
+ !repair.should_resend(server, target, at(60_000)),
+ "a server that never takes the size is not asked forever"
+ );
+ assert!(!repair.should_resend(server, size(98, 26, 144), at(60_000)));
+ assert!(
+ repair.should_resend(server, size(98, 26, 144), at(60_500)),
+ "a new target is worth trying again"
+ );
+ }
+
+ #[test]
+ fn a_pending_repair_says_when_to_look_again() {
+ let target = size(97, 26, 144);
+ let server = dimensions(size(118, 34, 144));
+ let mut repair = GeometryRepair::default();
+ assert_eq!(repair.next_check_in(at(0)), None, "nothing pending");
+
+ repair.should_resend(server, target, at(0));
+ assert_eq!(
+ repair.next_check_in(at(100)),
+ Some(Duration::from_millis(400)),
+ "an idle pane is looked at again when the grace ends"
+ );
+ assert!(repair.should_resend(server, target, at(500)));
+ assert_eq!(
+ repair.next_check_in(at(500)),
+ Some(GEOMETRY_REPAIR_RETRY),
+ "and again when a resend that did not land may be retried"
+ );
+ assert!(repair.should_resend(server, target, at(2500)));
+ assert!(repair.should_resend(server, target, at(4500)));
+ assert_eq!(repair.next_check_in(at(4500)), None, "given up");
+
+ repair.should_resend(dimensions(target), target, at(5000));
+ assert_eq!(repair.next_check_in(at(5000)), None, "settled");
+ }
}
#[cfg(test)]
diff --git a/thinkterm-session/src/pane.rs b/thinkterm-session/src/pane.rs
index 25ae7d7a..1cda8c4c 100644
--- a/thinkterm-session/src/pane.rs
+++ b/thinkterm-session/src/pane.rs
@@ -366,6 +366,18 @@ impl<H: SessionHost> PaneSession<H> {
self.state().server_geometry_matches(size)
}
+ /// Whether the server has kept this pane at another size than `target`
+ /// for long enough that the frontend should send `target` again, and
+ /// how long until it should look again while that is pending; see
+ /// `GeometryRepair`.
+ pub fn server_geometry_repair(&self, target: TerminalSize) -> (bool, Option<Duration>) {
+ let now = self.now();
+ let mut st = self.state();
+ let server = st.server_dimensions;
+ let resend = st.geometry_repair.should_resend(server, target, now);
+ (resend, st.geometry_repair.next_check_in(now))
+ }
+
/// Which fields or render rows block a takeover from settling on `size`.
pub fn frontend_geometry_mismatch(&self, size: TerminalSize) -> Option<String> {
let mut st = self.state();
@@ -928,10 +940,15 @@ impl<H: SessionHost> PaneSession<H> {
st.frontend_preview.is_some(),
);
st.dimensions = visible_dimensions;
- if let Some(preserve_lines) = invalidate {
+ match invalidate {
// During a preview, retain old rows while marking them stale. This
// prevents a blank flash as a full-screen application redraws.
- st.invalidate_line_cache(preserve_lines);
+ Some(true) => st.invalidate_line_cache(true),
+ // A width this surface did not have keeps them too: clearing them
+ // blanked the whole pane until the refetch landed, on every push
+ // while the server and the frontend disagreed about the width.
+ Some(false) => st.invalidate_line_cache_for_width(visible_dimensions.cols),
+ None => {}
}
// Retaining rows is not enough when the resize rewrapped the
// scrollback: the viewport's stable range moved and the retained
@@ -2244,6 +2261,39 @@ mod tests {
);
}
+ /// A push carrying a width this surface did not have keeps the cached
+ /// rows drawable: clearing them blanked the whole pane on every push
+ /// while the server and the frontend disagreed about the width.
+ #[test]
+ fn a_push_with_another_width_keeps_the_rows_drawable() {
+ let (host, session) = session(&[(0, "kept")]);
+ session.queue_render_delta(delta(1, false, false));
+ host.spawner.run_all();
+ let _ = session.get_lines(0..1);
+ host.spawner.run_all();
+ session.apply_local_resize(TerminalSize {
+ cols: 60,
+ pixel_width: 600,
+ ..size()
+ });
+
+ session.queue_render_delta(delta(2, false, false));
+ host.spawner.run_all();
+
+ let st = session.state();
+ assert_eq!(st.dimensions.cols, 80, "the server's width is shown");
+ match st.lines.peek(&0) {
+ Some(LineEntry::Stale(line)) => {
+ assert_eq!(line.as_str().trim_end(), "kept");
+ assert_eq!(line.len(), 80, "normalized to the new width");
+ }
+ other => panic!(
+ "row 0 must stay drawable, found {:?}",
+ other.map(|entry| entry.kind())
+ ),
+ }
+ }
+
fn rows_requested(host: &TestHost) -> usize {
host.link.rows_asked.get()
}
diff --git a/thinkterm-session/src/pane_state.rs b/thinkterm-session/src/pane_state.rs
index a6895acc..b97a9446 100644
--- a/thinkterm-session/src/pane_state.rs
+++ b/thinkterm-session/src/pane_state.rs
@@ -4,6 +4,7 @@
//! and predictive echo. Pure over the host's `Timestamp`; the session in
//! `pane.rs` does the talking.
use crate::clock::{RateLimiter, Timestamp};
+use crate::decide::GeometryRepair;
use crate::lines::*;
use crate::SessionConfig;
use codec::InputSerial;
@@ -52,6 +53,9 @@ pub struct PaneState {
/// line contents, but cannot bounce the visible surface back to an older
/// grid between mouse-move frames.
pub(crate) frontend_preview: Option<FrontendPreviewGeometry>,
+ /// A server size that disagrees with the one the frontend settled on,
+ /// and when the frontend last said its own again.
+ pub(crate) geometry_repair: GeometryRepair,
pub(crate) lines: LruCache<StableRowIndex, LineEntry>,
pub(crate) line_cache_epoch: u64,
@@ -110,6 +114,7 @@ impl PaneState {
keyboard_encoding: KeyboardEncoding::Xterm,
server_dimensions: dimensions,
frontend_preview: None,
+ geometry_repair: GeometryRepair::default(),
lines: LruCache::new(NonZeroUsize::new(config.scrollback_lines.max(128)).unwrap()),
line_cache_epoch: 0,
warmed_epoch: None,
@@ -340,6 +345,14 @@ impl PaneState {
invalidate_line_entries(&mut self.lines, preserve_lines);
}
+ /// Like `apply_local_resize`, for a width the server reported: keep the
+ /// cached rows drawable, normalized to `cols` and stale, until the
+ /// refetch replaces them.
+ pub(crate) fn invalidate_line_cache_for_width(&mut self, cols: usize) {
+ self.line_cache_epoch = self.line_cache_epoch.wrapping_add(1);
+ resize_stale_line_entries(&mut self.lines, cols);
+ }
+
/// Converge the locally rendered surface to the geometry requested by the
/// GUI. This is deliberately separate from deciding whether a Resize RPC
/// is needed: a delayed server update can temporarily restore old
diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rs
index 746c487f..232dcf57 100644
--- a/wezterm-client/src/pane/clientpane.rs
+++ b/wezterm-client/src/pane/clientpane.rs
@@ -576,6 +576,50 @@ impl ClientPane {
changed
}
+ /// Send `size` again, as a plain per-pane Resize, once the server has
+ /// kept this pane at another size for a while. Returns how long until
+ /// the caller should check again while that is pending: a pane that
+ /// stopped drawing may not paint by itself.
+ ///
+ /// Adoption only reshapes the local surface and leaves the server to the
+ /// viewport report, which the server skips when it repeats the last one.
+ /// A size the server changed on its own since was then never put back,
+ /// and each push and paint flipped the surface between the two sizes.
+ pub fn resend_frontend_geometry_if_ignored(
+ &self,
+ size: TerminalSize,
+ ) -> Option<std::time::Duration> {
+ let (resend, recheck_in) = self.session.server_geometry_repair(size);
+ if !resend {
+ return recheck_in;
+ }
+ let client = Arc::clone(&self.client);
+ let remote_pane_id = self.remote_pane_id;
+ let remote_tab_id = self.remote_tab_id();
+ log::info!(
+ "the server kept pane {} at another size than {}x{}; sending it again",
+ self.local_pane_id,
+ size.cols,
+ size.rows
+ );
+ promise::spawn::spawn(async move {
+ if let Err(err) = client
+ .client
+ .resize(Resize {
+ containing_tab_id: remote_tab_id,
+ pane_id: remote_pane_id,
+ size,
+ })
+ .await
+ {
+ log::warn!("resending the size of remote pane {remote_pane_id}: {err:#}");
+ }
+ Ok::<(), anyhow::Error>(())
+ })
+ .detach();
+ recheck_in
+ }
+
/// Pin the local render surface to a divider preview epoch. Unlike a
/// normal adoption this deliberately preserves cached rows and ignores
/// older server dimensions until the final full viewport is confirmed.
diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rs
index c6a8307e..bd973dae 100644
--- a/wezterm-gui/src/termwindow/resize.rs
+++ b/wezterm-gui/src/termwindow/resize.rs
@@ -2505,7 +2505,11 @@ impl super::TermWindow {
}
}
- fn sync_positioned_pane_font_size(&self, pos: &PositionedPane) -> anyhow::Result<()> {
+ fn sync_positioned_pane_font_size(
+ &self,
+ pos: &PositionedPane,
+ settled: bool,
+ ) -> anyhow::Result<()> {
let pane_id = pos.pane.pane_id();
let font_scale = self.pane_font_scale(pane_id);
let render_metrics = if font_scale.to_bits() == self.fonts.get_font_scale().to_bits() {
@@ -2558,6 +2562,17 @@ impl super::TermWindow {
}
}
+ // Adoption above is local only. A size the server changed on its own
+ // (a zoomed stack switching pages) is otherwise never put back. The
+ // pane may have stopped drawing, so a pending check owes a frame.
+ if settled {
+ if let Some(client) = pos.pane.downcast_ref::<ClientPane>() {
+ if let Some(recheck_in) = client.resend_frontend_geometry_if_ignored(target_size) {
+ self.update_next_frame_time(Some(Instant::now() + recheck_in));
+ }
+ }
+ }
+
Ok(())
}
@@ -2573,12 +2588,15 @@ impl super::TermWindow {
let Some(tab) = Mux::get().get_active_tab_for_window(self.mux_window_id) else {
return;
};
+ // A geometry epoch or a divider preview is still taking the server
+ // to these sizes; only a settled tab is checked for one it kept.
+ let settled = !self.frontend_geometry_phases.contains_key(&tab.tab_id());
for positioned in self.get_panes_to_render() {
let Some(members) = self.positioned_panes_for_stack(&tab, &positioned) else {
continue;
};
for pos in members {
- if let Err(err) = self.sync_positioned_pane_font_size(&pos) {
+ if let Err(err) = self.sync_positioned_pane_font_size(&pos, settled) {
log::error!(
"failed to sync font-scaled pane size for pane {}: {:#}",
pos.pane.pane_id(),