diff --git a/codex-rs/tui/src/custom_terminal.rs b/codex-rs/tui/src/custom_terminal.rs index 51511e9f50..8184065e07 100644 --- a/codex-rs/tui/src/custom_terminal.rs +++ b/codex-rs/tui/src/custom_terminal.rs @@ -23,6 +23,8 @@ // SOFTWARE. use std::io; use std::io::Write; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use crossterm::cursor::MoveTo; use crossterm::cursor::RestorePosition; @@ -53,6 +55,9 @@ use ratatui::widgets::WidgetRef; mod cursor; +// Panic and handoff cleanup cannot access the Terminal. Only the stdout TUI sets this flag. +pub(crate) static STDOUT_CURSOR_STYLED: AtomicBool = AtomicBool::new(false); + #[cfg(test)] #[path = "custom_terminal_test_support.rs"] pub(crate) mod test_support; @@ -151,6 +156,9 @@ where pub hidden_cursor: bool, /// Last cursor style sent successfully, so ordinary redraws do not repaint its repair anchor. last_cursor_style: Option, + /// Once we set a shape, keep the existing reset behavior even across cache invalidation. + cursor_style_changed: bool, + pub(crate) tracks_stdout_cursor: bool, /// Area of the viewport pub viewport_area: Rect, /// Last known size of the terminal. Used to detect if the internal buffers have to be resized. @@ -172,7 +180,9 @@ where #[allow(clippy::print_stderr)] fn drop(&mut self) { // Attempt to restore the cursor state - if let Err(err) = self.reset_cursor_style() { + if self.cursor_style_changed + && let Err(err) = self.reset_cursor_style() + { eprintln!("Failed to reset the cursor style: {err}"); } @@ -232,6 +242,8 @@ where current: 0, hidden_cursor: false, last_cursor_style: None, + cursor_style_changed: false, + tracks_stdout_cursor: false, viewport_area: Rect::new( /*x*/ 0, cursor_pos.y, @@ -526,7 +538,9 @@ where None if !self.hidden_cursor => self.hide_cursor()?, None => {} Some(position) => { - self.set_cursor_style_with_repair(cursor_style)?; + if self.cursor_style_changed || cursor_style != SetCursorStyle::DefaultUserShape { + self.set_cursor_style_with_repair(cursor_style)?; + } self.set_cursor_position(position)?; self.show_cursor()?; } @@ -555,7 +569,17 @@ where /// Sets the visible terminal cursor style. pub fn set_cursor_style(&mut self, style: SetCursorStyle) -> io::Result<()> { + let first_override = + !self.cursor_style_changed && style != SetCursorStyle::DefaultUserShape; + // Publish the first override under the same stdout lock as panic cleanup. + let _lock = (first_override && self.tracks_stdout_cursor).then(|| io::stdout().lock()); queue!(self.backend, style)?; + if first_override { + self.cursor_style_changed = true; + if self.tracks_stdout_cursor { + STDOUT_CURSOR_STYLED.store(true, Ordering::Relaxed); + } + } self.last_cursor_style = Some(style); Ok(()) } diff --git a/codex-rs/tui/src/custom_terminal/tests/cursor_tests.rs b/codex-rs/tui/src/custom_terminal/tests/cursor_tests.rs index a6fd62b94b..3f8bde03f9 100644 --- a/codex-rs/tui/src/custom_terminal/tests/cursor_tests.rs +++ b/codex-rs/tui/src/custom_terminal/tests/cursor_tests.rs @@ -71,6 +71,7 @@ fn terminal_draw_repaints_the_cursor_anchor_only_when_its_style_needs_restoring( let buffer = frame.buffer_mut(); buffer.set_string(0, 0, "transcript", Style::default()); buffer.set_string(10, 1, marker, Style::default()); + frame.set_cursor_style(SetCursorStyle::SteadyBar); frame.set_cursor_position((4, 1)); }) .expect("draw"); @@ -98,6 +99,9 @@ fn terminal_draw_repairs_styled_anchor_on_cursor_only_frames() { /*x*/ 0, /*y*/ 1, /*width*/ 12, /*height*/ 1, ); terminal.set_viewport_area(area); + terminal + .set_cursor_style(SetCursorStyle::SteadyBar) + .unwrap(); let mut frames = Vec::new(); let mut parser = vt100::Parser::new(/*rows*/ 2, /*cols*/ 12, /*scrollback_len*/ 0); @@ -143,6 +147,9 @@ fn terminal_draw_repairs_owned_wide_hyperlink_after_skipped_glyphs() { /*x*/ 0, /*y*/ 0, /*width*/ 8, /*height*/ 1, ); terminal.set_viewport_area(area); + terminal + .set_cursor_style(SetCursorStyle::SteadyBar) + .unwrap(); let mut frames = Vec::new(); for _ in 0..2 { terminal.backend_mut().output.clear(); @@ -171,6 +178,9 @@ fn terminal_draw_repairs_single_column_without_scrolling() { /*x*/ 0, /*y*/ 0, /*width*/ 1, /*height*/ 1, ); terminal.set_viewport_area(area); + terminal + .set_cursor_style(SetCursorStyle::SteadyBar) + .unwrap(); let mut frames = Vec::new(); let mut parser = vt100::Parser::new(/*rows*/ 1, /*cols*/ 1, /*scrollback_len*/ 1); diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 6bd03f234f..f962b8086c 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -380,11 +380,13 @@ fn restore_common( if let Err(err) = windows_console::restore_input_mode() { first_error.get_or_insert(err); } - if let Err(err) = execute!( - stdout(), - SetCursorStyle::DefaultUserShape, - crossterm::cursor::Show - ) { + let mut out = stdout().lock(); + if custom_terminal::STDOUT_CURSOR_STYLED.load(Ordering::Relaxed) + && let Err(err) = crossterm::queue!(out, SetCursorStyle::DefaultUserShape) + { + first_error.get_or_insert(err); + } + if let Err(err) = execute!(out, crossterm::cursor::Show) { first_error.get_or_insert(err); } match first_error { @@ -509,6 +511,7 @@ pub(crate) fn init() -> Result { if !stdout().is_terminal() { return Err(std::io::Error::other("stdout is not a terminal")); } + custom_terminal::STDOUT_CURSOR_STYLED.store(false, Ordering::Relaxed); let mut restore_guard = TerminalInitializationGuard { active: true }; let tmux_options = set_modes()?; @@ -790,10 +793,11 @@ impl Tui { } pub(crate) fn new( - terminal: Terminal, + mut terminal: Terminal, enhanced_keys_supported: bool, stderr_guard: terminal_stderr::TerminalStderrGuard, ) -> Self { + terminal.tracks_stdout_cursor = true; let (draw_tx, _) = broadcast::channel(1); let frame_requester = FrameRequester::new(draw_tx.clone()); diff --git a/codex-rs/tui/tests/suite/focus_palette.rs b/codex-rs/tui/tests/suite/focus_palette.rs index ae7da9a337..d712b6f8c8 100644 --- a/codex-rs/tui/tests/suite/focus_palette.rs +++ b/codex-rs/tui/tests/suite/focus_palette.rs @@ -285,6 +285,11 @@ fn default_owned_screen_entry_paints_before_sync_ends_and_exit_clears_inline_dra terminal.screen_contents() ); } + terminal.read_output(Duration::ZERO)?; + ensure!( + !contains_bytes(&terminal.output, b"\x1b[0 q"), + "default session reset the host cursor shape" + ); terminal.write_input(b"shell\n")?; let mut shell_input = [0; 6]; terminal.slave.read_exact(&mut shell_input)?; @@ -321,6 +326,10 @@ fn fullscreen_transcript_can_opt_out_to_terminal_scrollback() -> Result<()> { .any(|bytes| bytes == b"\x1b[?1049h"), "fullscreen opt-out entered the alternate screen" ); + ensure!( + !contains_bytes(&terminal.output, b"\x1b[0 q"), + "scrollback composer reset the host cursor shape" + ); Ok(()) }