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(proto): drop pane sizes no screen could have, on every client

RoversXc93c60aef2b3
diff --git a/thinkterm-proto/src/layout.rs b/thinkterm-proto/src/layout.rs
index 5ece154d..3000c7a9 100644
--- a/thinkterm-proto/src/layout.rs
+++ b/thinkterm-proto/src/layout.rs
@@ -6,6 +6,40 @@ use wezterm_term::{StableRowIndex, TerminalSize};
use crate::renderable::StableCursorPosition;
+/// The most cells a pane may span either way. Pane sizes come off the wire
+/// and grids, caches, row walks and layouts are built from them; a size past
+/// this is a broken or hostile server, not a screen.
+pub const MAX_PANE_CELLS: usize = 10_000;
+
+/// The most pixels a pane may span either way: a generous cell at the most
+/// cells. Pixel sizes are multiplied and divided in layout, so they are
+/// bounded as well.
+pub const MAX_PANE_PIXELS: usize = MAX_PANE_CELLS * 1024;
+
+/// Whether a size the server sent is one to build or lay out from.
+pub fn terminal_size_is_plausible(size: &TerminalSize) -> bool {
+ size.cols <= MAX_PANE_CELLS
+ && size.rows <= MAX_PANE_CELLS
+ && size.pixel_width <= MAX_PANE_PIXELS
+ && size.pixel_height <= MAX_PANE_PIXELS
+}
+
+/// Blank every tab whose tree describes a pane or split no screen could be.
+/// A tab past the bound is dropped rather than clamped, since a clamped size
+/// would disagree with the pane the server actually has; tabs are blanked in
+/// place so a list kept beside them (tab titles) still lines up. Returns how
+/// many were blanked, for the caller to report.
+pub fn blank_implausible_tabs(tabs: &mut [PaneNode]) -> usize {
+ let mut blanked = 0;
+ for tab in tabs {
+ if !tab.is_plausible() {
+ *tab = PaneNode::Empty;
+ blanked += 1;
+ }
+ }
+ blanked
+}
+
/// This type is used directly by the codec, take care to bump
/// the codec version if you change this
#[derive(Deserialize, Serialize, PartialEq, Debug)]
@@ -38,6 +72,56 @@ impl PaneNode {
}
}
+ /// Every size in the tree within bounds, splits included, and the two
+ /// sides of a split together still a plausible pane. A split's second
+ /// side may be empty (a divider dragged to the far edge leaves it no
+ /// cells), but its first may not: `SplitDirectionAndSize::size` divides
+ /// by it. The whole is checked here without calling `size`, whose
+ /// products can overflow a 32-bit `usize` before any bound applies.
+ pub fn is_plausible(&self) -> bool {
+ match self {
+ PaneNode::Empty => true,
+ PaneNode::Leaf(entry) => entry.is_plausible(),
+ PaneNode::Stack(stack) => stack.panes.iter().all(PaneEntry::is_plausible),
+ PaneNode::Split { left, right, node } => {
+ let (first, second) = (&node.first, &node.second);
+ let sides_ok = terminal_size_is_plausible(first)
+ && terminal_size_is_plausible(second)
+ && first.cols >= 1
+ && first.rows >= 1;
+ // Bounded sides, so neither sum below can overflow.
+ let whole_ok = || {
+ let (cols, rows) = (node.width(), node.height());
+ let cell_width = first.pixel_width / first.cols;
+ let cell_height = first.pixel_height / first.rows;
+ cols <= MAX_PANE_CELLS
+ && rows <= MAX_PANE_CELLS
+ && cell_width
+ .checked_mul(cols)
+ .is_some_and(|total| total <= MAX_PANE_PIXELS)
+ && cell_height
+ .checked_mul(rows)
+ .is_some_and(|total| total <= MAX_PANE_PIXELS)
+ };
+ sides_ok && whole_ok() && left.is_plausible() && right.is_plausible()
+ }
+ }
+ }
+
+ /// Every pane in the tree, left to right, stacked ones included.
+ pub fn entries(&self) -> Vec<&PaneEntry> {
+ match self {
+ PaneNode::Empty => vec![],
+ PaneNode::Leaf(entry) => vec![entry],
+ PaneNode::Stack(stack) => stack.panes.iter().collect(),
+ PaneNode::Split { left, right, .. } => {
+ let mut all = left.entries();
+ all.extend(right.entries());
+ all
+ }
+ }
+ }
+
pub fn root_size(&self) -> Option<TerminalSize> {
match self {
PaneNode::Empty => None,
@@ -113,6 +197,17 @@ pub struct PaneEntry {
pub tty_name: Option<String>,
}
+impl PaneEntry {
+ /// The listed size within bounds, and its rows reachable from its top.
+ pub fn is_plausible(&self) -> bool {
+ terminal_size_is_plausible(&self.size)
+ && self
+ .physical_top
+ .checked_add(self.size.rows as StableRowIndex)
+ .is_some()
+ }
+}
+
#[derive(Deserialize, Clone, Serialize, PartialEq, Debug)]
#[serde(try_from = "String", into = "String")]
pub struct SerdeUrl {
@@ -144,3 +239,107 @@ impl Into<String> for SerdeUrl {
self.url.as_str().into()
}
}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+ use crate::renderable::RenderableDimensions;
+ use crate::split::SplitDirection;
+
+ fn size(cols: usize, rows: usize) -> TerminalSize {
+ TerminalSize {
+ rows,
+ cols,
+ pixel_width: cols * 8,
+ pixel_height: rows * 16,
+ dpi: 72,
+ }
+ }
+
+ fn leaf(size: TerminalSize) -> PaneNode {
+ PaneNode::Leaf(PaneEntry {
+ window_id: 0,
+ tab_id: 0,
+ pane_id: 0,
+ title: String::new(),
+ size,
+ working_dir: None,
+ is_active_pane: true,
+ is_zoomed_pane: false,
+ alt_screen: false,
+ workspace: String::new(),
+ cursor_pos: Default::default(),
+ physical_top: 0,
+ top_row: 0,
+ left_col: 0,
+ tty_name: None,
+ })
+ }
+
+ fn split(first: TerminalSize, second: TerminalSize) -> PaneNode {
+ PaneNode::Split {
+ left: Box::new(leaf(first)),
+ right: Box::new(leaf(second)),
+ node: SplitDirectionAndSize {
+ direction: SplitDirection::Horizontal,
+ first,
+ second,
+ },
+ }
+ }
+
+ #[test]
+ fn ordinary_trees_are_plausible_and_impossible_ones_are_not() {
+ assert!(leaf(size(80, 24)).is_plausible());
+ assert!(split(size(40, 24), size(39, 24)).is_plausible());
+ assert!(!leaf(size(80, MAX_PANE_CELLS + 1)).is_plausible());
+ let mut wide_pixels = size(80, 24);
+ wide_pixels.pixel_width = usize::MAX;
+ assert!(!leaf(wide_pixels).is_plausible());
+ // A zero-width first side would divide by zero in `size()`; an empty
+ // second one is what a divider dragged to the edge leaves.
+ assert!(!split(size(0, 24), size(80, 24)).is_plausible());
+ assert!(split(size(79, 24), size(0, 24)).is_plausible());
+ // Each pixel size in bounds, the whole not (and on a 32-bit target,
+ // not even representable).
+ let mut tall_cells = size(1, 24);
+ tall_cells.pixel_width = MAX_PANE_PIXELS;
+ assert!(!split(tall_cells, size(9_000, 24)).is_plausible());
+ // Each side in bounds, the two together not.
+ assert!(!split(size(6000, 24), size(6000, 24)).is_plausible());
+ let mut tabs = vec![leaf(size(80, 24)), leaf(size(80, 100_000))];
+ assert_eq!(blank_implausible_tabs(&mut tabs), 1);
+ assert!(matches!(tabs[1], PaneNode::Empty));
+ }
+
+ #[test]
+ fn dimensions_with_unreachable_rows_are_not_plausible() {
+ let dims = RenderableDimensions {
+ cols: 80,
+ viewport_rows: 24,
+ scrollback_rows: 100,
+ physical_top: 76,
+ scrollback_top: 0,
+ dpi: 72,
+ pixel_width: 640,
+ pixel_height: 384,
+ reverse_video: false,
+ };
+ assert!(dims.is_plausible());
+ assert!(!RenderableDimensions {
+ scrollback_top: StableRowIndex::MIN,
+ ..dims
+ }
+ .is_plausible());
+ assert!(!RenderableDimensions {
+ physical_top: StableRowIndex::MAX,
+ ..dims
+ }
+ .is_plausible());
+ assert!(!RenderableDimensions {
+ scrollback_top: 100,
+ ..dims
+ }
+ .is_plausible());
+ }
+}
diff --git a/thinkterm-proto/src/renderable.rs b/thinkterm-proto/src/renderable.rs
index 65025a1e..36a5922b 100644
--- a/thinkterm-proto/src/renderable.rs
+++ b/thinkterm-proto/src/renderable.rs
@@ -47,3 +47,21 @@ pub struct RenderableDimensions {
}
#[cfg(feature = "lua")]
impl_lua_conversion_dynamic!(RenderableDimensions);
+
+impl RenderableDimensions {
+ /// Within the bounds a pane may have (`layout::MAX_PANE_CELLS`), with
+ /// every row index sum and difference a client takes over them in range.
+ pub fn is_plausible(&self) -> bool {
+ use crate::layout::{MAX_PANE_CELLS, MAX_PANE_PIXELS};
+ self.cols <= MAX_PANE_CELLS
+ && self.viewport_rows <= MAX_PANE_CELLS
+ && self.pixel_width <= MAX_PANE_PIXELS
+ && self.pixel_height <= MAX_PANE_PIXELS
+ && self.scrollback_top <= self.physical_top
+ && self
+ .physical_top
+ .checked_add(self.viewport_rows as StableRowIndex)
+ .is_some()
+ && self.physical_top.checked_sub(self.scrollback_top).is_some()
+ }
+}
diff --git a/thinkterm-session/src/pane.rs b/thinkterm-session/src/pane.rs
index 8ce180bf..3aad8a48 100644
--- a/thinkterm-session/src/pane.rs
+++ b/thinkterm-session/src/pane.rs
@@ -43,6 +43,29 @@ pub struct PaneSession<H: SessionHost> {
host_pane_id: HostPaneId,
}
+/// The size a session starts from, as the server listed it. Grids and row
+/// caches are built from it before any render delta could be refused, so an
+/// impossible one is brought into bounds here: each client drops such a pane
+/// when it can, and this is the floor under all of them.
+fn plausible_dimensions(dimensions: RenderableDimensions) -> RenderableDimensions {
+ if dimensions.is_plausible() {
+ return dimensions;
+ }
+ log::warn!("a pane was listed with impossible dimensions; starting it from bounded ones");
+ use thinkterm_proto::layout::{MAX_PANE_CELLS, MAX_PANE_PIXELS};
+ let viewport_rows = dimensions.viewport_rows.min(MAX_PANE_CELLS);
+ RenderableDimensions {
+ cols: dimensions.cols.min(MAX_PANE_CELLS),
+ viewport_rows,
+ scrollback_rows: viewport_rows,
+ physical_top: 0,
+ scrollback_top: 0,
+ pixel_width: dimensions.pixel_width.min(MAX_PANE_PIXELS),
+ pixel_height: dimensions.pixel_height.min(MAX_PANE_PIXELS),
+ ..dimensions
+ }
+}
+
impl<H: SessionHost> PaneSession<H> {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -56,6 +79,7 @@ impl<H: SessionHost> PaneSession<H> {
title: &str,
alt_screen: bool,
) -> Arc<Self> {
+ let dimensions = plausible_dimensions(dimensions);
let state = PaneState::new(
config,
dimensions,
@@ -731,10 +755,7 @@ impl<H: SessionHost> PaneSession<H> {
) {
// Reject impossible geometry before it reaches cache seeding or any
// frontend. Clamping only dirty ranges leaves those other walks open.
- if delta.dimensions.viewport_rows > 10_000
- || delta.dimensions.cols > 10_000
- || delta.dimensions.physical_top.checked_add(delta.dimensions.viewport_rows as StableRowIndex).is_none()
- {
+ if !delta.dimensions.is_plausible() {
log::warn!("ignoring render update with invalid pane dimensions");
return;
}
@@ -771,7 +792,7 @@ impl<H: SessionHost> PaneSession<H> {
// only marks cached rows stale, and past as many rows as the cache
// holds that is the same work as marking the whole cache stale, so
// the walk stops there and the one sweep takes over.
- const MAX_VIEWPORT_ROWS: usize = 10_000;
+ const MAX_VIEWPORT_ROWS: usize = thinkterm_proto::layout::MAX_PANE_CELLS;
let physical_top = delta.dimensions.physical_top;
let row_end = physical_top.saturating_add(
delta.dimensions.viewport_rows.min(MAX_VIEWPORT_ROWS) as StableRowIndex,
@@ -1245,6 +1266,39 @@ enum Nearest {
#[cfg(test)]
mod tests {
use super::*;
+
+ #[test]
+ fn an_impossible_listed_size_starts_in_bounds() {
+ use thinkterm_proto::layout::MAX_PANE_CELLS;
+ let wild = RenderableDimensions {
+ cols: usize::MAX,
+ viewport_rows: 100_000,
+ scrollback_rows: 100_000,
+ physical_top: StableRowIndex::MAX,
+ scrollback_top: 0,
+ dpi: 72,
+ pixel_width: usize::MAX,
+ pixel_height: 800,
+ reverse_video: false,
+ };
+ let tamed = plausible_dimensions(wild);
+ assert!(tamed.is_plausible());
+ assert_eq!((tamed.cols, tamed.viewport_rows), (MAX_PANE_CELLS, MAX_PANE_CELLS));
+ assert_eq!(tamed.physical_top, 0);
+ // An ordinary size passes through untouched.
+ let ordinary = RenderableDimensions {
+ cols: 80,
+ viewport_rows: 24,
+ scrollback_rows: 24,
+ physical_top: 0,
+ ..wild
+ };
+ let ordinary = RenderableDimensions {
+ pixel_width: 640,
+ ..ordinary
+ };
+ assert_eq!(plausible_dimensions(ordinary), ordinary);
+ }
use crate::host::{DetachedFuture, HostConfig, LinkError};
use crate::input::{LocalFuture, PaneLink};
use codec::{GetImageCellResponse, GetLinesResponse, UnitResponse};
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
index 54ca2a98..20bff72d 100644
--- a/thinkterm-web/src/app.rs
+++ b/thinkterm-web/src/app.rs
@@ -1079,8 +1079,16 @@ impl<P: Platform, L: Link> App<P, L> {
},
)
.await?;
- let bottom = (cursor.y + 1).min(dims.physical_top + dims.viewport_rows as StableRowIndex);
- let top = (bottom - rows as StableRowIndex).max(dims.scrollback_top);
+ if !dims.is_plausible() {
+ anyhow::bail!("the pane reported impossible dimensions");
+ }
+ let bottom = cursor
+ .y
+ .saturating_add(1)
+ .min(dims.physical_top + dims.viewport_rows as StableRowIndex);
+ let top = bottom
+ .saturating_sub(rows as StableRowIndex)
+ .max(dims.scrollback_top);
let response = thinkterm_session::host::request(
&link,
Pdu::GetLines(codec::GetLines { pane_id, lines: vec![top..bottom] }),
@@ -3233,16 +3241,7 @@ impl<P: Platform, L: Link> App<P, L> {
async fn list_panes(&self) -> Option<codec::ListPanesResponse> {
let link = self.inner.borrow().link.clone();
- match thinkterm_session::host::request(
- &link,
- Pdu::ListPanes(codec::ListPanes {}),
- |pdu| match pdu {
- Pdu::ListPanesResponse(p) => Ok(p),
- other => Err(other),
- },
- )
- .await
- {
+ match crate::attach::list_panes(&link).await {
Ok(list) => Some(list),
Err(err) => {
log::warn!("listing panes: {err:#}");
diff --git a/thinkterm-web/src/attach.rs b/thinkterm-web/src/attach.rs
index 0aa68ade..39af7523 100644
--- a/thinkterm-web/src/attach.rs
+++ b/thinkterm-web/src/attach.rs
@@ -11,6 +11,19 @@ use thinkterm_proto::{ClientId, PaneId, RenderableDimensions, TabId};
use thinkterm_session::host::request;
use wezterm_term::TerminalSize;
+/// The server's pane list, with every tab whose sizes no screen could have
+/// blanked (`PaneNode::is_plausible`). The one way this crate asks for it, so
+/// no caller gets the sizes unchecked.
+pub async fn list_panes<L: Link>(link: &L) -> Result<codec::ListPanesResponse> {
+ let mut panes = request(link, Pdu::ListPanes(codec::ListPanes {}), |pdu| match pdu {
+ Pdu::ListPanesResponse(p) => Ok(p),
+ other => Err(other),
+ })
+ .await?;
+ crate::layout::blank_implausible_tabs(&mut panes);
+ Ok(panes)
+}
+
pub struct Attached {
pub pane_id: PaneId,
pub tab_id: TabId,
@@ -67,11 +80,7 @@ pub async fn attach<L: Link>(
)
.await?;
- let panes = request(link, Pdu::ListPanes(codec::ListPanes {}), |pdu| match pdu {
- Pdu::ListPanesResponse(p) => Ok(p),
- other => Err(other),
- })
- .await?;
+ let panes = list_panes(link).await?;
// The first tab that has a pane, preferring its active one.
let entry = panes
.tabs
@@ -205,11 +214,7 @@ pub async fn reattach<L: Link>(
)
.await?;
- let panes = request(link, Pdu::ListPanes(codec::ListPanes {}), |pdu| match pdu {
- Pdu::ListPanesResponse(p) => Ok(p),
- other => Err(other),
- })
- .await?;
+ let panes = list_panes(link).await?;
let tab = panes
.tabs
.iter()
diff --git a/thinkterm-web/src/layout.rs b/thinkterm-web/src/layout.rs
index 633eff65..24758af1 100644
--- a/thinkterm-web/src/layout.rs
+++ b/thinkterm-web/src/layout.rs
@@ -265,16 +265,17 @@ pub fn scaled(layout: &TabLayout, size: TerminalSize) -> Option<TabLayout> {
/// Every pane in a tab, left to right, top to bottom, stacks included.
pub fn leaves(node: &PaneNode) -> Vec<&PaneEntry> {
- match node {
- PaneNode::Empty => vec![],
- PaneNode::Leaf(entry) => vec![entry],
- PaneNode::Stack(stack) => stack.panes.iter().collect(),
- PaneNode::Split { left, right, .. } => {
- let mut all = leaves(left);
- all.extend(leaves(right));
- all
- }
+ node.entries()
+}
+
+/// Blank every tab whose sizes no screen could have, and say so; see
+/// `thinkterm_proto::layout::blank_implausible_tabs`.
+pub fn blank_implausible_tabs(list: &mut ListPanesResponse) -> usize {
+ let blanked = thinkterm_proto::layout::blank_implausible_tabs(&mut list.tabs);
+ if blanked > 0 {
+ log::warn!("ignoring {blanked} tab(s) with impossible pane sizes");
}
+ blanked
}
/// The tab that holds `pane_id`.
@@ -740,4 +741,29 @@ mod tests {
assert!(matches!(tab_containing(&list, 7), Some(PaneNode::Leaf(e)) if e.pane_id == 7));
assert!(tab_containing(&list, 9).is_none());
}
+
+ #[test]
+ fn tabs_with_impossible_pane_sizes_are_blanked_in_place() {
+ let mut list = ListPanesResponse {
+ tabs: vec![
+ PaneNode::Leaf(pane(1, 80, 24, 0, 0, true)),
+ PaneNode::Leaf(pane(2, 80, 100_000, 0, 0, true)),
+ PaneNode::Leaf(pane(3, 200_000, 24, 0, 0, true)),
+ PaneNode::Leaf(pane(4, 80, 24, 0, 0, true)),
+ ],
+ tab_titles: vec!["a".into(), "b".into(), "c".into(), "d".into()],
+ window_titles: Default::default(),
+ };
+ let mut overflowing = pane(5, 80, 24, 0, 0, true);
+ overflowing.physical_top = StableRowIndex::MAX;
+ list.tabs.push(PaneNode::Leaf(overflowing));
+ assert_eq!(blank_implausible_tabs(&mut list), 3);
+ assert!(matches!(list.tabs[0], PaneNode::Leaf(ref e) if e.pane_id == 1));
+ assert!(matches!(list.tabs[1], PaneNode::Empty));
+ assert!(matches!(list.tabs[2], PaneNode::Empty));
+ assert!(matches!(list.tabs[3], PaneNode::Leaf(ref e) if e.pane_id == 4));
+ assert!(matches!(list.tabs[4], PaneNode::Empty));
+ // Titles still line up with their tabs.
+ assert_eq!(list.tab_titles[3], "d");
+ }
}
diff --git a/thinkterm-web/src/lease.rs b/thinkterm-web/src/lease.rs
index ad3c6107..48ae2902 100644
--- a/thinkterm-web/src/lease.rs
+++ b/thinkterm-web/src/lease.rs
@@ -74,12 +74,26 @@ impl Lease {
}
pub fn apply_viewport(&mut self, state: &codec::ClientViewportState) {
- self.tab_sizes.insert(state.tab_id, state.canonical_size);
+ // The size lays out a whole tab; one no screen could have is not
+ // taken, though who holds the tab still is.
+ let size = thinkterm_proto::layout::terminal_size_is_plausible(&state.canonical_size)
+ .then_some(state.canonical_size);
+ if size.is_none() {
+ log::warn!(
+ "ignoring an impossible canonical size for tab {}",
+ state.tab_id
+ );
+ }
+ if let Some(size) = size {
+ self.tab_sizes.insert(state.tab_id, size);
+ }
if Some(state.tab_id) != self.tab_id {
return;
}
self.tab_owner = state.owner.clone();
- self.canonical_size = Some(state.canonical_size);
+ if size.is_some() {
+ self.canonical_size = size;
+ }
self.apply_access(&state.access);
if self.fit && !self.owns_viewport() {
self.fit = false;
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index 4fb47f68..f024cf9e 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -3693,6 +3693,23 @@ impl ClientDomain {
// window's tabs in its order, and a mirror keeps that order.
let mut placed: HashMap<WindowId, usize> = HashMap::new();
for (mut tabroot, tab_title) in panes.tabs.into_iter().zip(panes.tab_titles.iter()) {
+ // Sizes off the wire build grids and layouts below. A tab listed
+ // with sizes no screen could have is left as it was: not built
+ // from, and not swept either, since it has not gone away.
+ if !tabroot.is_plausible() {
+ log::warn!(
+ "domain {}: ignoring a tab listed with impossible pane sizes",
+ inner.local_domain_id
+ );
+ if let Some((remote_window_id, remote_tab_id)) = tabroot.window_and_tab_ids() {
+ remote_windows_to_forget.remove(&remote_window_id);
+ remote_tabs_to_forget.remove(&remote_tab_id);
+ }
+ for entry in tabroot.entries() {
+ remote_panes_to_forget.remove(&entry.pane_id);
+ }
+ continue;
+ }
// Translate remote stack ids into stable local ids BEFORE the
// tree rebuild, so that GUI state keyed by pane_stack_id
// (collapse layouts, level-2 tab bar scroll) survives resyncs.
@@ -5058,6 +5075,9 @@ impl Domain for ClientDomain {
})
.await?;
+ if !thinkterm_proto::layout::terminal_size_is_plausible(&result.size) {
+ bail!("the server described the new pane with an impossible size");
+ }
let pane: Arc<dyn Pane> = Arc::new(ClientPane::new(
&inner,
result.tab_id,
@@ -5454,6 +5474,9 @@ impl Domain for ClientDomain {
return Ok(moved_pane);
}
+ if !thinkterm_proto::layout::terminal_size_is_plausible(&result.size) {
+ bail!("the server described the new pane with an impossible size");
+ }
let pane: Arc<dyn Pane> = Arc::new(ClientPane::new(
&inner,
result.tab_id,