Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Recover missed tmux resize notifications in the TUI (#43603)

Felipe Coury7d2c58e6e081
diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs
index 96b3fbcbb9..26e1a97133 100644
--- a/codex-rs/tui/src/tui.rs
+++ b/codex-rs/tui/src/tui.rs
@@ -71,6 +71,7 @@ mod job_control;
mod keyboard_modes;
mod screen_size;
mod scrollback;
+mod size_monitor;
#[cfg(all(test, unix))]
#[path = "tui_startup_tests.rs"]
mod startup_tests;
@@ -637,12 +638,19 @@ impl Tui {
// Cache this to avoid contention with the event reader.
supports_color::on_cached(supports_color::Stream::Stdout);
let _ = crate::terminal_palette::default_colors();
- let scrollback = ScrollbackStrategy::detect(&codex_terminal_detection::terminal_info());
+ let terminal_info = codex_terminal_detection::terminal_info();
+ let scrollback = ScrollbackStrategy::detect(&terminal_info);
+ let mut event_broker = EventBroker::new();
+ event_broker.size_monitor = size_monitor::SizeMonitor::start(
+ &terminal_info,
+ terminal.last_known_screen_size,
+ draw_tx.clone(),
+ );
Self {
frame_requester,
draw_tx,
- event_broker: Arc::new(EventBroker::new()),
+ event_broker: Arc::new(event_broker),
terminal,
pending_history_lines: vec![],
screen_size: ScreenSizePolicy::default(),
diff --git a/codex-rs/tui/src/tui/event_stream.rs b/codex-rs/tui/src/tui/event_stream.rs
index de4ceae632..5f2ce7f5c3 100644
--- a/codex-rs/tui/src/tui/event_stream.rs
+++ b/codex-rs/tui/src/tui/event_stream.rs
@@ -3,7 +3,8 @@
//! - [`EventBroker`] holds the shared crossterm stream so multiple callers reuse the same
//! input source and can drop/recreate it on pause/resume without rebuilding consumers.
//! - [`TuiEventStream`] wraps a draw event subscription plus the shared [`EventBroker`] and maps crossterm
-//! events into [`TuiEvent`].
+//! events into [`TuiEvent`]. The broker also owns the tmux size monitor; its samples
+//! wake the draw subscription and become resize events before rendering.
//! - [`EventSource`] abstracts the underlying event producer; the real implementation is
//! [`CrosstermEventSource`] and tests can swap in [`FakeEventSource`].
//!
@@ -34,6 +35,7 @@ use tokio_stream::wrappers::WatchStream;
use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
use super::TuiEvent;
+use super::size_monitor::SizeMonitor;
/// Result type produced by an event source.
pub type EventResult = std::io::Result<Event>;
@@ -51,6 +53,7 @@ pub trait EventSource: Send + 'static {
pub struct EventBroker<S: EventSource = CrosstermEventSource> {
state: Mutex<EventBrokerState<S>>,
resume_events_tx: watch::Sender<()>,
+ pub(super) size_monitor: Option<SizeMonitor>,
}
/// Tracks state of underlying [`EventSource`].
@@ -83,11 +86,15 @@ impl<S: EventSource + Default> EventBroker<S> {
Self {
state: Mutex::new(EventBrokerState::Start),
resume_events_tx,
+ size_monitor: None,
}
}
/// Drop the underlying event source
pub fn pause_events(&self) {
+ if let Some(monitor) = &self.size_monitor {
+ monitor.set_active(/*active*/ false);
+ }
let mut state = self
.state
.lock()
@@ -97,6 +104,9 @@ impl<S: EventSource + Default> EventBroker<S> {
/// Create a new instance of the underlying event source
pub fn resume_events(&self) {
+ if let Some(monitor) = &self.size_monitor {
+ monitor.set_active(/*active*/ true);
+ }
let mut state = self
.state
.lock()
@@ -238,9 +248,15 @@ impl<S: EventSource + Default + Unpin> TuiEventStream<S> {
/// Poll the draw broadcast stream for the next draw event. Draw events are used to trigger a redraw of the TUI.
pub fn poll_draw_event(&mut self, cx: &mut Context<'_>) -> Poll<Option<TuiEvent>> {
match Pin::new(&mut self.draw_stream).poll_next(cx) {
- Poll::Ready(Some(Ok(()))) => Poll::Ready(Some(TuiEvent::Draw)),
- Poll::Ready(Some(Err(BroadcastStreamRecvError::Lagged(_)))) => {
- Poll::Ready(Some(TuiEvent::Draw))
+ Poll::Ready(Some(Ok(())))
+ | Poll::Ready(Some(Err(BroadcastStreamRecvError::Lagged(_)))) => {
+ let event = self
+ .broker
+ .size_monitor
+ .as_ref()
+ .and_then(SizeMonitor::take_resize)
+ .map_or(TuiEvent::Draw, TuiEvent::Resize);
+ Poll::Ready(Some(event))
}
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
@@ -268,7 +284,11 @@ impl<S: EventSource + Default + Unpin> TuiEventStream<S> {
Some(TuiEvent::Key(key_event))
}
Event::Resize(width, height) => {
- Some(TuiEvent::Resize(ratatui::layout::Size { width, height }))
+ let size = ratatui::layout::Size { width, height };
+ if let Some(monitor) = &self.broker.size_monitor {
+ monitor.observe(size);
+ }
+ Some(TuiEvent::Resize(size))
}
Event::Paste(pasted) => Some(TuiEvent::Paste(pasted)),
Event::FocusGained => {
diff --git a/codex-rs/tui/src/tui/screen_size.rs b/codex-rs/tui/src/tui/screen_size.rs
index c9f657886e..77d5f5c406 100644
--- a/codex-rs/tui/src/tui/screen_size.rs
+++ b/codex-rs/tui/src/tui/screen_size.rs
@@ -49,6 +49,11 @@ impl Tui {
}
TuiEvent::Key(_) | TuiEvent::Paste(_) | TuiEvent::FocusLost => cached,
};
+ if matches!(event, TuiEvent::Resize(_) | TuiEvent::Resume)
+ && let Some(monitor) = &self.event_broker.size_monitor
+ {
+ monitor.observe(size);
+ }
self.screen_size.pending_draw_size = (!matches!(
event,
TuiEvent::Key(_) | TuiEvent::Paste(_) | TuiEvent::FocusLost
@@ -72,6 +77,9 @@ impl Tui {
return Ok(size);
}
let size = self.terminal.size()?;
+ if let Some(monitor) = &self.event_broker.size_monitor {
+ monitor.observe(size);
+ }
self.screen_size.pending_recheck_at = None;
self.screen_size.deferred_size = None;
Ok(size)
diff --git a/codex-rs/tui/src/tui/size_monitor.rs b/codex-rs/tui/src/tui/size_monitor.rs
new file mode 100644
index 0000000000..cf50fd8e3b
--- /dev/null
+++ b/codex-rs/tui/src/tui/size_monitor.rs
@@ -0,0 +1,148 @@
+//! Recovers lost tmux resize notifications without querying geometry on the UI thread.
+//!
+//! One worker belongs to the event broker, including across nested screens. Queries never
+//! hold the shared lock. Pauses and newer geometry invalidate both in-flight and queued
+//! samples. Dropping the monitor wakes the worker without joining a possibly blocked OS call;
+//! that single in-flight call may finish later, but cannot publish or start another query.
+
+use std::io;
+use std::sync::Arc;
+use std::sync::Mutex;
+use std::thread;
+use std::time::Duration;
+
+use codex_terminal_detection::Multiplexer;
+use codex_terminal_detection::TerminalInfo;
+use ratatui::layout::Size;
+use tokio::sync::broadcast;
+
+const CHECK_INTERVAL: Duration = Duration::from_millis(500);
+
+struct State {
+ size: Size,
+ generation: u64,
+ pending: Option<Size>,
+ active: bool,
+ stopped: bool,
+}
+
+pub(super) struct SizeMonitor {
+ state: Arc<Mutex<State>>,
+ worker: thread::JoinHandle<()>,
+}
+
+impl SizeMonitor {
+ pub(super) fn start(
+ terminal_info: &TerminalInfo,
+ size: Size,
+ draw_tx: broadcast::Sender<()>,
+ ) -> Option<Self> {
+ if !cfg!(unix) || !matches!(terminal_info.multiplexer, Some(Multiplexer::Tmux { .. })) {
+ return None;
+ }
+ Self::spawn(size, draw_tx, || {
+ // Unlike terminal::size(), window_size() has no tput subprocess fallback.
+ crossterm::terminal::window_size().map(|size| Size::new(size.columns, size.rows))
+ })
+ .inspect_err(|error| tracing::warn!(%error, "Failed to start terminal size monitor"))
+ .ok()
+ }
+
+ fn spawn(
+ size: Size,
+ draw_tx: broadcast::Sender<()>,
+ mut query: impl FnMut() -> io::Result<Size> + Send + 'static,
+ ) -> io::Result<Self> {
+ let state = Arc::new(Mutex::new(State {
+ size,
+ generation: 0,
+ pending: None,
+ active: true,
+ stopped: false,
+ }));
+ let shared = state.clone();
+ let worker = thread::Builder::new()
+ .name("codex-terminal-size".into())
+ .spawn(move || {
+ loop {
+ thread::park_timeout(CHECK_INTERVAL);
+ let generation = {
+ let state = shared
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if state.stopped {
+ break;
+ }
+ if !state.active {
+ continue;
+ }
+ state.generation
+ };
+ let sampled = query();
+ let mut state = shared
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if state.stopped {
+ break;
+ }
+ if state.generation != generation {
+ continue;
+ }
+ state.pending = sampled
+ .ok()
+ .filter(|size| size.width > 0 && size.height > 0 && *size != state.size);
+ if state.pending.is_some() {
+ drop(state);
+ let _ = draw_tx.send(());
+ }
+ }
+ })?;
+ Ok(Self { state, worker })
+ }
+
+ pub(super) fn observe(&self, size: Size) {
+ let mut state = self
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ state.size = size;
+ state.generation = state.generation.wrapping_add(1);
+ state.pending = None;
+ }
+
+ pub(super) fn set_active(&self, active: bool) {
+ let mut state = self
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ state.active = active;
+ state.generation = state.generation.wrapping_add(1);
+ state.pending = None;
+ }
+
+ pub(super) fn take_resize(&self) -> Option<Size> {
+ let mut state = self
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let size = state.pending.take()?;
+ state.size = size;
+ state.generation = state.generation.wrapping_add(1);
+ tracing::debug!(?size, "Recovered terminal size from background check");
+ Some(size)
+ }
+}
+
+impl Drop for SizeMonitor {
+ fn drop(&mut self) {
+ self.state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .stopped = true;
+ self.worker.thread().unpark();
+ }
+}
+
+#[cfg(test)]
+#[path = "size_monitor_tests.rs"]
+mod tests;
diff --git a/codex-rs/tui/src/tui/size_monitor_tests.rs b/codex-rs/tui/src/tui/size_monitor_tests.rs
new file mode 100644
index 0000000000..f15fe04730
--- /dev/null
+++ b/codex-rs/tui/src/tui/size_monitor_tests.rs
@@ -0,0 +1,263 @@
+use super::*;
+use std::pin::Pin;
+use std::sync::atomic::AtomicBool;
+use std::task::Context;
+use std::task::Poll;
+
+use codex_terminal_detection::TerminalName;
+use crossterm::event::Event;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyModifiers;
+use pretty_assertions::assert_eq;
+use ratatui::layout::Position;
+use ratatui::layout::Rect;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Widget;
+use ratatui::widgets::Wrap;
+use tokio::time::timeout;
+use tokio_stream::StreamExt;
+
+use crate::custom_terminal::Terminal;
+use crate::test_backend::VT100Backend;
+use crate::tui::TuiEvent;
+use crate::tui::event_stream::EventBroker;
+use crate::tui::event_stream::EventResult;
+use crate::tui::event_stream::EventSource;
+use crate::tui::event_stream::TuiEventStream;
+
+#[derive(Default)]
+struct KeySource {
+ sent: bool,
+}
+
+impl EventSource for KeySource {
+ fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<EventResult>> {
+ if self.sent {
+ return Poll::Pending;
+ }
+ self.sent = true;
+ Poll::Ready(Some(Ok(Event::Key(KeyEvent::new(
+ KeyCode::Char('x'),
+ KeyModifiers::NONE,
+ )))))
+ }
+}
+
+struct Harness {
+ broker: Arc<EventBroker<KeySource>>,
+ queries: tokio::sync::mpsc::UnboundedReceiver<()>,
+ replies: std::sync::mpsc::Sender<io::Result<Size>>,
+ draws: broadcast::Receiver<()>,
+}
+
+impl Harness {
+ fn new(size: Size) -> Self {
+ let (draw_tx, draws) = broadcast::channel(/*capacity*/ 1);
+ let (started, queries) = tokio::sync::mpsc::unbounded_channel();
+ let (replies, responses) = std::sync::mpsc::channel();
+ let monitor = SizeMonitor::spawn(size, draw_tx, move || {
+ let _ = started.send(());
+ responses
+ .recv_timeout(Duration::from_secs(5))
+ .unwrap_or_else(|_| Err(io::Error::other("test query was not released")))
+ })
+ .expect("monitor");
+ let mut broker = EventBroker::new();
+ broker.size_monitor = Some(monitor);
+ Self {
+ broker: Arc::new(broker),
+ queries,
+ replies,
+ draws,
+ }
+ }
+
+ fn monitor(&self) -> &SizeMonitor {
+ self.broker.size_monitor.as_ref().unwrap()
+ }
+
+ async fn next_query(&mut self) {
+ self.monitor().worker.thread().unpark();
+ timeout(Duration::from_secs(2), self.queries.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ }
+
+ fn stream(&self) -> TuiEventStream<KeySource> {
+ TuiEventStream::new(
+ self.broker.clone(),
+ self.draws.resubscribe(),
+ Arc::new(AtomicBool::new(/*v*/ false)),
+ #[cfg(unix)]
+ crate::tui::job_control::SuspendContext::new(),
+ #[cfg(unix)]
+ Arc::new(AtomicBool::new(/*v*/ false)),
+ )
+ }
+}
+
+#[tokio::test]
+async fn missed_resize_recovers_and_slow_query_does_not_block_input() {
+ let initial = Size::new(/*width*/ 12, /*height*/ 4);
+ let resized = Size::new(/*width*/ 8, /*height*/ 4);
+ let mut harness = Harness::new(initial);
+ let mut stream = harness.stream();
+ harness.next_query().await;
+ // The worker is blocked waiting for a reply. Input still traverses the real event stream.
+ assert!(matches!(
+ timeout(Duration::from_millis(100), stream.next())
+ .await
+ .unwrap(),
+ Some(TuiEvent::Key(KeyEvent {
+ code: KeyCode::Char('x'),
+ ..
+ }))
+ ));
+ assert!(
+ timeout(
+ CHECK_INTERVAL + Duration::from_millis(50),
+ harness.queries.recv()
+ )
+ .await
+ .is_err()
+ );
+ harness.replies.send(Ok(resized)).unwrap();
+ let event = timeout(Duration::from_secs(2), stream.next())
+ .await
+ .unwrap()
+ .unwrap();
+ let TuiEvent::Resize(size) = event else {
+ panic!("expected recovered resize: {event:?}")
+ };
+ assert_eq!(size, resized);
+
+ let mut terminal = Terminal::with_screen_size_and_cursor_position_for_test(
+ VT100Backend::new(resized.width, resized.height),
+ initial,
+ Position { x: 0, y: 0 },
+ );
+ let area = Rect::new(/*x*/ 0, /*y*/ 0, size.width, size.height);
+ terminal.set_viewport_area(area);
+ terminal
+ .draw_with_size(size, |frame| {
+ Paragraph::new("alpha beta")
+ .wrap(Wrap { trim: false })
+ .render(area, frame.buffer_mut());
+ })
+ .unwrap();
+ assert_eq!(terminal.last_known_screen_size, resized);
+ insta::assert_snapshot!(terminal.backend().vt100().screen().contents(), @"alpha\nbeta");
+}
+
+#[tokio::test]
+async fn newer_resize_invalidates_in_flight_and_queued_samples() {
+ let initial = Size::new(/*width*/ 80, /*height*/ 24);
+ let newer = Size::new(/*width*/ 100, /*height*/ 30);
+ let mut harness = Harness::new(initial);
+ harness.next_query().await;
+ harness.monitor().observe(newer);
+ harness.replies.send(Ok(initial)).unwrap();
+ harness.next_query().await; // The previous result has been processed.
+ assert_eq!(harness.monitor().take_resize(), None);
+ assert_eq!(
+ harness.draws.try_recv(),
+ Err(broadcast::error::TryRecvError::Empty)
+ );
+
+ harness.replies.send(Ok(initial)).unwrap();
+ timeout(Duration::from_secs(2), harness.draws.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ harness.monitor().observe(newer); // Also discard a result already queued for the UI.
+ assert_eq!(harness.monitor().take_resize(), None);
+}
+
+#[tokio::test]
+async fn unchanged_invalid_and_failed_samples_do_not_redraw() {
+ let initial = Size::new(/*width*/ 80, /*height*/ 24);
+ let mut harness = Harness::new(initial);
+ harness.next_query().await;
+ for sample in [
+ Ok(initial),
+ Ok(Size::new(/*width*/ 0, /*height*/ 0)),
+ Err(io::Error::other("query failed")),
+ ] {
+ harness.replies.send(sample).unwrap();
+ harness.next_query().await;
+ assert_eq!(harness.monitor().take_resize(), None);
+ assert_eq!(
+ harness.draws.try_recv(),
+ Err(broadcast::error::TryRecvError::Empty)
+ );
+ }
+}
+
+#[tokio::test]
+async fn terminal_handoff_pauses_queries_and_discards_old_results() {
+ let initial = Size::new(/*width*/ 80, /*height*/ 24);
+ let resized = Size::new(/*width*/ 40, /*height*/ 12);
+ let mut harness = Harness::new(initial);
+ harness.next_query().await;
+ harness.broker.pause_events();
+ harness.replies.send(Ok(resized)).unwrap();
+ harness.monitor().worker.thread().unpark();
+ assert!(
+ timeout(Duration::from_millis(100), harness.queries.recv())
+ .await
+ .is_err()
+ );
+ assert_eq!(harness.monitor().take_resize(), None);
+ harness.broker.resume_events();
+ harness.next_query().await;
+ harness.replies.send(Ok(resized)).unwrap();
+ timeout(Duration::from_secs(2), harness.draws.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(harness.monitor().take_resize(), Some(resized));
+}
+
+#[tokio::test]
+async fn drop_does_not_wait_for_a_blocked_query_or_start_another() {
+ let initial = Size::new(/*width*/ 80, /*height*/ 24);
+ let mut harness = Harness::new(initial);
+ harness.next_query().await;
+ let state = harness.monitor().state.clone();
+ drop(harness.broker);
+ assert!(state.lock().unwrap().stopped);
+ harness
+ .replies
+ .send(Ok(Size::new(/*width*/ 40, /*height*/ 12)))
+ .unwrap();
+ assert_eq!(
+ timeout(Duration::from_secs(2), harness.queries.recv())
+ .await
+ .unwrap(),
+ None
+ );
+ assert_eq!(state.lock().unwrap().pending, None);
+}
+
+#[test]
+fn monitor_requires_tmux_detection() {
+ let (draw_tx, _) = broadcast::channel(/*capacity*/ 1);
+ let mut info = TerminalInfo {
+ name: TerminalName::Ghostty,
+ term_program: None,
+ version: None,
+ term: None,
+ multiplexer: None,
+ };
+ let size = Size::new(/*width*/ 80, /*height*/ 24);
+ assert!(SizeMonitor::start(&info, size, draw_tx.clone()).is_none());
+ info.multiplexer = Some(Multiplexer::Zellij { version: None });
+ assert!(SizeMonitor::start(&info, size, draw_tx.clone()).is_none());
+ info.multiplexer = Some(Multiplexer::Tmux { version: None });
+ assert_eq!(
+ SizeMonitor::start(&info, size, draw_tx).is_some(),
+ cfg!(unix)
+ );
+}