diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 8a1dbf0c0b..b8f4566df2 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -905,6 +905,10 @@ impl App { app_server: &mut AppServerSession, mut event: TuiEvent, ) -> Result { + #[cfg(unix)] + if let Some(message) = tui.event_broker.take_suspend_timeout_message() { + self.chat_widget.add_error_message(message.into()); + } if let TuiEvent::Key(key) = &mut event { *key = self.resolve_key_layout(tui, *key); } diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index be0de0209e..8b81601b64 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -807,6 +807,10 @@ async fn run_session_picker_event_loop( loop { tokio::select! { Some(ev) = tui_events.next() => { + #[cfg(unix)] + if let Some(message) = alt.tui.event_broker.take_suspend_timeout_message() { + state.inline_error = Some(message.into()); + } alt.tui.clipboard.poll(); let screen_size = alt.tui.screen_size_for_event(&ev)?; if alt.tui.dismiss_shortcut_on_input(&ev, &mut state.chord_matcher) { continue; } @@ -5350,6 +5354,16 @@ mod tests { let snapshot = terminal.backend().to_string(); assert_snapshot!("resume_picker_search_error", snapshot); + + #[cfg(unix)] + { + state.inline_error = Some(crate::tui::EventBroker::SUSPEND_TIMEOUT_MESSAGE.into()); + let mut frame = terminal.get_frame(); + let line = search_line(&state, frame.area().width); + frame.render_widget_ref(&line, frame.area()); + terminal.flush().expect("flush"); + assert_snapshot!(terminal.backend().to_string(), @"Press Ctrl+Z to retry. Timed out waiting for terminal color reports."); + } } #[test] diff --git a/codex-rs/tui/src/startup_orchestration.rs b/codex-rs/tui/src/startup_orchestration.rs index db32726fdc..d26de2ded2 100644 --- a/codex-rs/tui/src/startup_orchestration.rs +++ b/codex-rs/tui/src/startup_orchestration.rs @@ -748,8 +748,9 @@ pub(super) async fn run_main_inner( { eprintln!("Could not create otel exporter: {e}"); } + Ok::<(), std::io::Error>(()) }) - .await; + .await?; None } Err(_) => { diff --git a/codex-rs/tui/src/style.rs b/codex-rs/tui/src/style.rs index d2a9af5934..718812b696 100644 --- a/codex-rs/tui/src/style.rs +++ b/codex-rs/tui/src/style.rs @@ -466,7 +466,7 @@ mod tests { _ => unreachable!(), }; assert_eq!(effective_stdout_color_level(), expected_level); - crate::terminal_palette::set_default_colors_from_startup_probe(/*colors*/ None); + crate::terminal_palette::set_default_colors(/*colors*/ None); // Preserve configured theme accents when the terminal can represent their palette. assert_eq!( accent_style(), diff --git a/codex-rs/tui/src/terminal_capabilities.rs b/codex-rs/tui/src/terminal_capabilities.rs index 74e70d0f70..d6c6feaa92 100644 --- a/codex-rs/tui/src/terminal_capabilities.rs +++ b/codex-rs/tui/src/terminal_capabilities.rs @@ -8,6 +8,9 @@ mod resize_reflow_cap; #[cfg(unix)] mod terminal_identity; pub(crate) mod terminal_probe; +#[cfg(all(test, unix))] +#[path = "terminal_capabilities_tests.rs"] +mod tests; mod tmux; mod tmux_clipboard; @@ -107,6 +110,25 @@ fn direct_terminal_name() -> Option { .then_some(terminal.name) } +#[cfg(unix)] +pub(crate) fn supports_live_palette() -> bool { + direct_stdout() + && live_palette_supported( + &terminal_info(), + std::env::var("TERM").ok().as_deref(), + is_ssh_session(), + ) +} + +#[cfg(unix)] +fn live_palette_supported(terminal: &TerminalInfo, term: Option<&str>, ssh: bool) -> bool { + !ssh && is_direct_terminal(terminal, term) + && matches!( + terminal.name, + TerminalName::Kitty | TerminalName::Ghostty | TerminalName::Rex + ) +} + /// A terminal's explicit bidi mode overrides assumptions about its renderer. /// Silence or an unrecognized mode alone cannot rule out native or partial RTL. pub(crate) fn needs_bidi_layout(implicit_bidi: Option) -> bool { diff --git a/codex-rs/tui/src/terminal_capabilities/images_tests.rs b/codex-rs/tui/src/terminal_capabilities/images_tests.rs index b9a11e0cf6..64ca906040 100644 --- a/codex-rs/tui/src/terminal_capabilities/images_tests.rs +++ b/codex-rs/tui/src/terminal_capabilities/images_tests.rs @@ -280,7 +280,7 @@ fn pet_image_support_rejects_unknown_terminals() { ); } -fn terminal_info_for_test( +pub(in crate::terminal_capabilities) fn terminal_info_for_test( name: TerminalName, multiplexer: Option, term_program: Option<&str>, diff --git a/codex-rs/tui/src/terminal_capabilities/terminal_probe.rs b/codex-rs/tui/src/terminal_capabilities/terminal_probe.rs index e9bc29ce67..d0831a75ac 100644 --- a/codex-rs/tui/src/terminal_capabilities/terminal_probe.rs +++ b/codex-rs/tui/src/terminal_capabilities/terminal_probe.rs @@ -70,6 +70,10 @@ mod imp { static DA1_SUPPORTED: AtomicBool = AtomicBool::new(false); + pub(crate) fn da1_supported() -> bool { + DA1_SUPPORTED.load(Ordering::Relaxed) + } + /// Results from the TUI's one-shot startup terminal probe. #[derive(Debug, Default, Clone, Copy, Eq, PartialEq)] pub(crate) struct StartupProbe { @@ -267,7 +271,7 @@ mod imp { /// Wait for both replies, retaining a lone background when the probe ends. pub(crate) fn default_colors(timeout: Duration) -> io::Result> { let mut tty = Tty::open()?; - tty.write_all(b"\x1B]10;?\x1B\\\x1B]11;?\x1B\\")?; + tty.write_all(crate::terminal_palette::DEFAULT_COLOR_QUERY)?; let mut colors = None; read_until(&mut tty, timeout, |buffer| { colors = parse_default_colors(buffer); @@ -289,7 +293,7 @@ mod imp { /// A DA1 reply follows reports the terminal generated before we disabled reporting. pub(crate) fn wait_for_exit_reports() -> io::Result<()> { - if !DA1_SUPPORTED.load(Ordering::Relaxed) { + if !da1_supported() { return Ok(()); } let mut tty = Tty::open()?; @@ -333,7 +337,8 @@ mod imp { query.extend_from_slice(b"\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\"); } // DA1 finishes keyboard detection and establishes whether we can use it at exit. - query.extend_from_slice(b"\x1B[c\x1B[6n\x1B]10;?\x1B\\\x1B]11;?\x1B\\"); + query.extend_from_slice(b"\x1B[c\x1B[6n"); + query.extend_from_slice(crate::terminal_palette::DEFAULT_COLOR_QUERY); if query_identity { query.extend_from_slice(b"\x1B[>c"); } @@ -922,9 +927,13 @@ fn parse_osc_color(buffer: &[u8], slot: u8) -> Option<(u8, u8, u8)> { #[cfg(any(unix, test))] fn parse_default_colors(buffer: &[u8]) -> Option { - let bg = parse_osc_color(buffer, /*slot*/ 11)?; - let fg = parse_osc_color(buffer, /*slot*/ 10); - Some(crate::terminal_palette::DefaultColors { fg, bg }) + let mut replies = crate::terminal_palette::ColorReplies::default(); + for slot in [10, 11] { + if let Some(rgb) = parse_osc_color(buffer, slot) { + replies.record(slot, rgb); + } + } + replies.colors() } #[cfg(any(unix, windows, test))] @@ -942,30 +951,10 @@ fn osc_payload_end(buffer: &[u8]) -> Option<(usize, usize)> { #[cfg(any(unix, windows, test))] fn parse_osc_rgb(payload: &str) -> Option<(u8, u8, u8)> { - let (prefix, values) = payload.trim().split_once(':')?; - if !prefix.eq_ignore_ascii_case("rgb") && !prefix.eq_ignore_ascii_case("rgba") { - return None; + match crossterm::style::Color::from_osc_rgb(payload)? { + crossterm::style::Color::Rgb { r, g, b } => Some((r, g, b)), + _ => None, } - - let mut parts = values.split('/'); - let r = parse_osc_component(parts.next()?)?; - let g = parse_osc_component(parts.next()?)?; - let b = parse_osc_component(parts.next()?)?; - if prefix.eq_ignore_ascii_case("rgba") { - parse_osc_component(parts.next()?)?; - } - parts.next().is_none().then_some((r, g, b)) -} - -#[cfg(any(unix, windows, test))] -fn parse_osc_component(component: &str) -> Option { - if !(1..=4).contains(&component.len()) { - return None; - } - - let value = u32::from(u16::from_str_radix(component, /*radix*/ 16).ok()?); - let maximum = (1_u32 << (component.len() * 4)) - 1; - Some((value * u32::from(u8::MAX) / maximum) as u8) } #[cfg(any(unix, windows, test))] diff --git a/codex-rs/tui/src/terminal_capabilities_tests.rs b/codex-rs/tui/src/terminal_capabilities_tests.rs new file mode 100644 index 0000000000..7f5406692d --- /dev/null +++ b/codex-rs/tui/src/terminal_capabilities_tests.rs @@ -0,0 +1,35 @@ +#![cfg(test)] + +use super::images::tests::terminal_info_for_test; +use super::live_palette_supported; +use codex_terminal_detection::Multiplexer; +use codex_terminal_detection::TerminalName; +use pretty_assertions::assert_eq; + +#[test] +fn live_palette_requires_a_supported_direct_local_terminal() { + let term = "xterm-256color"; + let tmux = Some(Multiplexer::Tmux { version: None }); + let zellij = Some(Multiplexer::Zellij { version: None }); + for (name, multiplexer, term, ssh, expected) in [ + (TerminalName::Ghostty, None, term, false, true), + (TerminalName::Rex, None, term, false, true), + (TerminalName::Kitty, None, term, false, true), + (TerminalName::Iterm2, None, term, false, false), + (TerminalName::Unknown, None, term, false, false), + (TerminalName::Ghostty, None, term, true, false), + (TerminalName::Ghostty, tmux, term, false, false), + (TerminalName::Ghostty, zellij, term, false, false), + (TerminalName::Ghostty, None, "screen-256color", false, false), + (TerminalName::Ghostty, None, "tmux-256color", false, false), + (TerminalName::Ghostty, None, "dumb", false, false), + ] { + let terminal = + terminal_info_for_test(name, multiplexer, /*term_program*/ None, Some(term)); + assert_eq!( + live_palette_supported(&terminal, Some(term), ssh), + expected, + "{terminal:?}, ssh={ssh}" + ); + } +} diff --git a/codex-rs/tui/src/terminal_palette.rs b/codex-rs/tui/src/terminal_palette.rs index c2c01e0850..6e740510e4 100644 --- a/codex-rs/tui/src/terminal_palette.rs +++ b/codex-rs/tui/src/terminal_palette.rs @@ -53,6 +53,35 @@ pub struct DefaultColors { pub(crate) bg: (u8, u8, u8), } +#[cfg(unix)] +pub(crate) const DEFAULT_COLOR_QUERY: &[u8] = b"\x1b]10;?\x1b\\\x1b]11;?\x1b\\"; + +/// One query's replies. A usable background is sufficient for the composer tint. +#[cfg(any(unix, test))] +#[derive(Default)] +pub(crate) struct ColorReplies { + fg: Option<(u8, u8, u8)>, + bg: Option<(u8, u8, u8)>, +} + +#[cfg(any(unix, test))] +impl ColorReplies { + pub(crate) fn record(&mut self, slot: u8, rgb: (u8, u8, u8)) { + match slot { + 10 => self.fg = Some(rgb), + 11 => self.bg = Some(rgb), + _ => {} + } + } + + pub(crate) fn colors(self) -> Option { + Some(DefaultColors { + fg: self.fg, + bg: self.bg?, + }) + } +} + #[cfg(any(windows, test))] impl From for DefaultColors { fn from(colors: crate::terminal_probe::DefaultColors) -> Self { @@ -107,8 +136,8 @@ pub fn default_bg() -> Option<(u8, u8, u8)> { } #[cfg(any(unix, windows))] -pub(crate) fn set_default_colors_from_startup_probe(colors: Option) { - imp::set_default_colors_from_startup_probe(colors); +pub(crate) fn set_default_colors(colors: Option) -> bool { + imp::set_default_colors(colors) } #[cfg(any(all(unix, not(test)), windows))] @@ -152,11 +181,12 @@ mod imp { cache.get_or_init_with(query_default_colors) } - pub(super) fn set_default_colors_from_startup_probe(colors: Option) { - if let Ok(mut cache) = default_colors_cache().lock() { - cache.value = colors; - cache.attempted = true; - } + pub(super) fn set_default_colors(colors: Option) -> bool { + let Ok(mut cache) = default_colors_cache().lock() else { + return false; + }; + cache.attempted = true; + std::mem::replace(&mut cache.value, colors) != colors } /// Queries terminal default colors through the bounded startup probe path. @@ -180,7 +210,9 @@ mod imp { } #[cfg(any(unix, windows))] - pub(super) fn set_default_colors_from_startup_probe(_colors: Option) {} + pub(super) fn set_default_colors(_colors: Option) -> bool { + false + } } /// The subset of Xterm colors that are usually consistent across terminals. diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index ec1d81246e..cb043d9918 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -71,6 +71,8 @@ mod input_boundary; #[cfg(unix)] mod job_control; mod link_pointer; +#[cfg(unix)] +mod palette_source; #[cfg(all(test, windows))] #[path = "tui/windows_console_tests.rs"] mod windows_console_tests; @@ -318,9 +320,9 @@ impl Command for DisableAlternateScroll { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum RawModeRestore { - DrainAndDisable, +#[derive(Clone, Copy)] +enum RawModeRestore<'a> { + DrainAndDisable(&'a EventBroker), Disable, Keep, } @@ -338,7 +340,7 @@ pub(crate) enum TerminalHandoff { } fn restore_common( - raw_mode_restore: RawModeRestore, + raw_mode_restore: RawModeRestore<'_>, keyboard_restore: KeyboardRestore, handoff: TerminalHandoff, ) -> Result<()> { @@ -362,14 +364,14 @@ fn restore_common( first_error.get_or_insert(err); } let _ = execute!(stdout(), DisableFocusChange); - if raw_mode_restore == RawModeRestore::DrainAndDisable { + if let RawModeRestore::DrainAndDisable(_events) = raw_mode_restore { #[cfg(unix)] - if let Err(err) = crate::terminal_probe::wait_for_exit_reports() { + if let Err(err) = _events.wait_for_exit_reports() { tracing::debug!(%err, "failed to drain outstanding terminal reports"); } flush_terminal_input_buffer(); } - if raw_mode_restore != RawModeRestore::Keep + if !matches!(raw_mode_restore, RawModeRestore::Keep) && let Err(err) = disable_raw_mode() { first_error.get_or_insert(err); @@ -434,7 +436,7 @@ pub(super) fn restore_after_exit_with_events(events: Option<&EventBroker>) -> Re } Some(events) => { events.pause_events(); - RawModeRestore::DrainAndDisable + RawModeRestore::DrainAndDisable(events) } None => RawModeRestore::Disable, }; @@ -565,7 +567,7 @@ pub(crate) fn init() -> Result { ); #[cfg(unix)] - crate::terminal_palette::set_default_colors_from_startup_probe(startup_probe.default_colors); + crate::terminal_palette::set_default_colors(startup_probe.default_colors); #[cfg(unix)] let cursor_pos = match startup_probe.cursor_position { @@ -593,7 +595,7 @@ pub(crate) fn init() -> Result { #[cfg(windows)] // OSC replies can arrive after their deadline. Do not issue terminal queries before directory // trust and other protected startup screens have finished accepting their security decisions. - crate::terminal_palette::set_default_colors_from_startup_probe(/*colors*/ None); + crate::terminal_palette::set_default_colors(/*colors*/ None); let mut tui = CustomTerminal::with_options_and_cursor_position(backend, cursor_pos)?; #[cfg(unix)] @@ -640,14 +642,14 @@ fn probe_windows_default_colors() { default_colors = colors.is_some(), "terminal default color probe completed" ); - crate::terminal_palette::set_default_colors_from_startup_probe(colors); + crate::terminal_palette::set_default_colors(colors); } Err(err) => { tracing::warn!( duration_ms = %started_at.elapsed().as_millis(), "terminal default color probe failed: {err}" ); - crate::terminal_palette::set_default_colors_from_startup_probe(/*colors*/ None); + crate::terminal_palette::set_default_colors(/*colors*/ None); } } } @@ -1067,13 +1069,22 @@ impl Tui { /// This pauses crossterm's stdin polling by dropping the underlying event stream, restores /// terminal modes and stderr while keeping raw mode enabled, then re-applies Codex TUI modes /// and stderr suppression before resuming events. - pub(crate) async fn with_restored(&mut self, handoff: TerminalHandoff, f: F) -> R + pub(crate) async fn with_restored( + &mut self, + handoff: TerminalHandoff, + f: F, + ) -> std::result::Result where + E: From, F: FnOnce() -> Fut, - Fut: Future, + Fut: Future>, { // Pause crossterm events to avoid stdin conflicts with external program `f`. - self.pause_events(); + self.link_hover.mouse = None; + if let Err(err) = self.event_broker.pause_for_handoff() { + self.resume_events(); + return Err(err.into()); + } // Restore both screens' input modes before giving the terminal to an editor. Repaint the // last frame on the alternate screen so separate-window editors leave Codex visible. @@ -1157,6 +1168,16 @@ impl Tui { } crate::terminal_program_status::invalidate_terminal_program_status(); + // A legacy Escape key can look like the start of a delayed OSC reply. + #[cfg(unix)] + if matches!(handoff, TerminalHandoff::KeepScreen) + && self.enhanced_keys_supported + && crate::terminal_probe::da1_supported() + && terminal_capabilities::supports_live_palette() + { + self.event_broker + .enable_palette_source(self.frame_requester()); + } self.resume_events(); self.schedule_screen_size_recheck(Duration::ZERO); output diff --git a/codex-rs/tui/src/tui/event_stream.rs b/codex-rs/tui/src/tui/event_stream.rs index 430a4341ac..01004e1a2b 100644 --- a/codex-rs/tui/src/tui/event_stream.rs +++ b/codex-rs/tui/src/tui/event_stream.rs @@ -36,6 +36,8 @@ use tokio_stream::wrappers::WatchStream; use tokio_stream::wrappers::errors::BroadcastStreamRecvError; use super::TuiEvent; +#[cfg(unix)] +use super::palette_source::PaletteSource; use super::size_monitor::SizeMonitor; /// Result type produced by an event source. @@ -54,19 +56,47 @@ pub trait EventSource: Send + 'static { pub struct EventBroker { state: Mutex>, resume_events_tx: watch::Sender<()>, + #[cfg(unix)] + suspend_handoff_timed_out: AtomicBool, pub(super) size_monitor: Option, } struct BrokerInput { source: EventBrokerState, + #[cfg(unix)] + palette: Option, // The first non-drag report (or end of input) belongs to the next poll, even // if a different stream takes over the shared terminal. - lookahead: Poll>, + lookahead: Lookahead, // Deliver focus changes captured during a thread transition before newer input. pending_focus: VecDeque, drain_failed: bool, } +type Lookahead = Poll>; + +impl BrokerInput { + fn discard_lookahead(&mut self) { + if let Poll::Ready(Some(Ok(event @ (Event::FocusGained | Event::FocusLost)))) = + std::mem::replace(&mut self.lookahead, Poll::Pending) + { + self.pending_focus.push_back(event); + } + } +} + +impl BrokerInput { + fn active(&mut self) -> Option<(&mut (dyn EventSource + Unpin), &mut Lookahead)> { + #[cfg(unix)] + if !matches!(self.source, EventBrokerState::Paused) + && let Some(palette) = &mut self.palette + { + return Some((palette, &mut self.lookahead)); + } + Some((self.source.active_event_source_mut()?, &mut self.lookahead)) + } +} + /// Tracks state of underlying [`EventSource`]. enum EventBrokerState { Paused, // Underlying event source (i.e., crossterm EventStream) dropped @@ -97,17 +127,25 @@ impl EventBroker { Self { state: Mutex::new(BrokerInput { source: EventBrokerState::Start, + #[cfg(unix)] + palette: None, pending_focus: VecDeque::new(), lookahead: Poll::Pending, drain_failed: false, }), resume_events_tx, + #[cfg(unix)] + suspend_handoff_timed_out: AtomicBool::new(false), size_monitor: None, } } /// Drop the underlying event source pub fn pause_events(&self) { + self.pause().discard_lookahead(); + } + + fn pause(&self) -> std::sync::MutexGuard<'_, BrokerInput> { if let Some(monitor) = &self.size_monitor { monitor.set_active(/*active*/ false); } @@ -116,12 +154,25 @@ impl EventBroker { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); state.source = EventBrokerState::Paused; - // Only focus reports survive an input boundary. - if let Poll::Ready(Some(Ok(event @ (Event::FocusGained | Event::FocusLost)))) = - std::mem::replace(&mut state.lookahead, Poll::Pending) - { - state.pending_focus.push_back(event); + #[cfg(unix)] + if let Some(palette) = &mut state.palette { + palette.pause(); } + state + } + + pub(super) fn pause_for_handoff(&self) -> std::io::Result<()> { + let mut state = self.pause(); + #[cfg(unix)] + if let Some(palette) = &mut state.palette { + palette.handoff(crate::terminal_probe::DEFAULT_TIMEOUT)?; + // A key decoded while waiting for the marker belongs to the old + // screen. In particular, Enter must never submit the edited draft. + // On timeout the caller resumes with those keys still available. + crossterm::event::discard_buffered_input()?; + } + state.discard_lookahead(); + Ok(()) } /// Called with the event source paused. A terminal error must not expose stale keys. @@ -159,6 +210,45 @@ impl EventBroker { } } +#[cfg(unix)] +impl EventBroker { + pub(crate) const SUSPEND_TIMEOUT_MESSAGE: &'static str = + "Press Ctrl+Z to retry. Timed out waiting for terminal color reports."; + + pub(crate) fn take_suspend_timeout_message(&self) -> Option<&'static str> { + self.suspend_handoff_timed_out + .swap(false, Ordering::Relaxed) + .then_some(Self::SUSPEND_TIMEOUT_MESSAGE) + } + + pub(super) fn wait_for_exit_reports(&self) -> std::io::Result<()> { + let palette = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .palette + .take(); + match palette { + // Reuse the numbered marker after an earlier handoff timed out. + Some(mut palette) => palette.handoff(std::time::Duration::from_secs(/*secs*/ 2)), + None => crate::terminal_probe::wait_for_exit_reports(), + } + } + + pub(super) fn enable_palette_source(&self, frames: super::FrameRequester) { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if state.palette.is_none() { + if matches!(state.source, EventBrokerState::Running(_)) { + state.source = EventBrokerState::Start; + } + state.palette = Some(PaletteSource::new(frames)); + } + } +} + /// Real crossterm-backed event source. pub struct CrosstermEventSource { #[cfg(not(windows))] @@ -275,10 +365,7 @@ impl TuiEventStream { return Poll::Ready(self.map_crossterm_event(event)); } } - let BrokerInput { - source, lookahead, .. - } = &mut *state; - let events = match source.active_event_source_mut() { + let (events, lookahead) = match state.active() { Some(events) => events, None => { drop(state); @@ -359,10 +446,17 @@ impl TuiEventStream { Event::Key(key_event) => { #[cfg(unix)] if crate::tui::job_control::SUSPEND_KEY.is_press(key_event) { - self.broker.pause_events(); - let suspend_result = self - .suspend_context - .suspend(&self.alt_screen_active, &mut self.dialog_status); + let handoff = self.broker.pause_for_handoff(); + self.broker.suspend_handoff_timed_out.store( + handoff + .as_ref() + .is_err_and(|err| err.kind() == std::io::ErrorKind::TimedOut), + Ordering::Relaxed, + ); + let suspend_result = handoff.and_then(|()| { + self.suspend_context + .suspend(&self.alt_screen_active, &mut self.dialog_status) + }); self.broker.resume_events(); if let Err(err) = suspend_result { tracing::warn!( diff --git a/codex-rs/tui/src/tui/palette_source.rs b/codex-rs/tui/src/tui/palette_source.rs new file mode 100644 index 0000000000..aa6a673fad --- /dev/null +++ b/codex-rs/tui/src/tui/palette_source.rs @@ -0,0 +1,137 @@ +//! Refresh default colors on editor return through the broker's sole input reader. +//! On supported terminals, a mode status reply ends the preceding batch of OSC replies. + +use super::FrameRequester; +use super::event_stream::EventSource; +use crate::terminal_palette::ColorReplies; +use crate::terminal_palette::DEFAULT_COLOR_QUERY; +use crate::terminal_palette::set_default_colors; +use crossterm::event::ColorReportHandoff; +use crossterm::event::Event; +use crossterm::event::TerminalEvent; +use crossterm::event::TerminalEventStream; +use crossterm::style::Color; +use std::io; +use std::io::Write; +use std::pin::Pin; +use std::task::Context; +use std::task::Poll; +use std::time::Duration; +use tokio_stream::Stream; + +fn send_query() -> io::Result<()> { + let mut out = io::stdout().lock(); + out.write_all(DEFAULT_COLOR_QUERY)?; + out.write_all(b"\x1b[?2031$p")?; + out.flush() +} + +pub(super) struct PaletteSource { + events: Option, + frames: FrameRequester, + phase: Phase, + replies: ColorReplies, + handoff: ColorReportHandoff, +} + +#[derive(Clone, Copy)] +enum Phase { + Refresh, + Listening, + Idle, +} + +impl PaletteSource { + pub(super) fn new(frames: FrameRequester) -> Self { + Self { + events: None, + frames, + phase: Phase::Refresh, + replies: ColorReplies::default(), + handoff: ColorReportHandoff::default(), + } + } + + pub(super) fn pause(&mut self) { + self.events = None; + // A screen transition can discard a reply. Query again when input resumes. + self.phase = match self.phase { + Phase::Listening => Phase::Refresh, + phase => phase, + }; + } + + pub(super) fn handoff(&mut self, timeout: Duration) -> io::Result<()> { + self.phase = Phase::Idle; + // Even a paused reader may have a reply in flight from the previous screen. + if !self.handoff.drain(timeout)? { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "Timed out waiting for terminal color reports. Please try again.", + )); + } + self.phase = Phase::Refresh; + Ok(()) + } + + // Wait until the input reader has finished any partial paste or queued reports. + fn query(&mut self) { + if matches!(self.phase, Phase::Refresh) + && self + .events + .get_or_insert_with(TerminalEventStream::default) + .prepare_color_query() + { + self.replies = ColorReplies::default(); + self.phase = Phase::Listening; + if let Err(err) = send_query() { + tracing::debug!(%err, "failed to query terminal colors"); + self.phase = Phase::Idle; + } + } + } + + fn report(&mut self, event: TerminalEvent) { + match (self.phase, event) { + ( + Phase::Listening, + TerminalEvent::Color { + slot, + color: Some(Color::Rgb { r, g, b }), + }, + ) => { + self.replies.record(slot, (r, g, b)); + } + (Phase::Listening, TerminalEvent::ColorSchemeReporting(status)) => { + self.phase = Phase::Idle; + if status == 2 + && let Some(colors) = std::mem::take(&mut self.replies).colors() + && set_default_colors(Some(colors)) + { + self.frames.schedule_frame(); + } + } + _ => {} + } + } +} + +impl EventSource for PaletteSource { + fn poll_next( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll>> { + for _ in 0..32 { + self.query(); + let events = self.events.get_or_insert_with(TerminalEventStream::default); + match std::task::ready!(Pin::new(events).poll_next(cx)) { + Some(Ok(TerminalEvent::Input(event))) => return Poll::Ready(Some(Ok(event))), + Some(Ok(report)) => self.report(report), + Some(Err(err)) => return Poll::Ready(Some(Err(err))), + None => return Poll::Ready(None), + } + } + cx.waker().wake_by_ref(); + Poll::Pending + } +} diff --git a/codex-rs/tui/tests/suite/external_editor_tests.rs b/codex-rs/tui/tests/suite/external_editor_tests.rs index 2279f6b56d..c14aaf82b6 100644 --- a/codex-rs/tui/tests/suite/external_editor_tests.rs +++ b/codex-rs/tui/tests/suite/external_editor_tests.rs @@ -55,6 +55,7 @@ fn external_editors_keep_the_screen_and_return_the_draft() -> Result<()> { .or_else(|_| codex_utils_cargo_bin::cargo_bin("codex"))?; let mut terminal = PtyCodex::start_binary(&codex, &repo_root, home, &args, Some(&editor))?; terminal.wait_for_startup()?; + terminal.answer_handoff_queries = true; terminal.wait_for_screen("GPT-5.6-Terra")?; terminal.write_input(b"initial draft")?; terminal.wait_for_screen("initial draft")?; diff --git a/codex-rs/tui/tests/suite/focus_palette.rs b/codex-rs/tui/tests/suite/focus_palette.rs index 004ce13976..f385c48985 100644 --- a/codex-rs/tui/tests/suite/focus_palette.rs +++ b/codex-rs/tui/tests/suite/focus_palette.rs @@ -28,6 +28,8 @@ mod external_editor; mod gov_cloud_guidance; #[path = "job_control_tests.rs"] mod job_control; +#[path = "live_palette_tests.rs"] +mod live_palette; #[path = "startup_color_replay_tests.rs"] mod startup_color_replay; #[path = "startup_idle_escape_tests.rs"] @@ -402,6 +404,7 @@ pub(super) struct PtyCodex { cursor_answered: bool, palette_answered: bool, keyboard_answered: bool, + answer_handoff_queries: bool, _codex_home: TempDir, } @@ -472,6 +475,7 @@ impl PtyCodex { let mut command = Command::new(codex); if let Some(editor) = editor { command.env("VISUAL", editor); + command.env("CODEX_TUI_DISABLE_KEYBOARD_ENHANCEMENT", "0"); } let child = command .args(extra_args) @@ -482,6 +486,13 @@ impl PtyCodex { .env_remove("TMUX") .env_remove("TMUX_PANE") .env_remove("STY") + .env_remove("SSH_TTY") + .env_remove("SSH_CONNECTION") + .env_remove("ZELLIJ") + .env_remove("ZELLIJ_SESSION_NAME") + .env_remove("ZELLIJ_VERSION") + .env_remove("NO_COLOR") + .env("COLORTERM", "truecolor") .env_remove("VTE_VERSION") .env("TERM_PROGRAM", "kitty") .env_remove("TERM_PROGRAM_VERSION") @@ -507,6 +518,7 @@ impl PtyCodex { cursor_answered: false, palette_answered: false, keyboard_answered: false, + answer_handoff_queries: false, _codex_home: codex_home, }) } @@ -613,8 +625,12 @@ impl PtyCodex { let mut chunk = [0_u8; 8192]; let count = self.master.read(&mut chunk)?; + let start = self.output.len().saturating_sub(2); self.output.extend_from_slice(&chunk[..count]); self.parser.process(&chunk[..count]); + if self.answer_handoff_queries && contains_bytes(&self.output[start..], b"\x1b[c") { + self.write_input(b"\x1b[?1;2c")?; + } Ok(()) } diff --git a/codex-rs/tui/tests/suite/live_palette_tests.rs b/codex-rs/tui/tests/suite/live_palette_tests.rs new file mode 100644 index 0000000000..f8fced474a --- /dev/null +++ b/codex-rs/tui/tests/suite/live_palette_tests.rs @@ -0,0 +1,137 @@ +#![cfg(test)] +//! Check the composer color and draft across an external editor handoff. + +use super::*; + +const RESET: &[u8] = b"\x1b[?2031;2$y"; +const QUERY: &[u8] = b"\x1b]11;?\x1b\\\x1b[?2031$p"; +const WHITE: &[u8] = b"\x1b]11;rgb:ffff/ffff/ffff\x07"; + +fn start() -> Result { + let repo = codex_utils_cargo_bin::repo_root()?; + let home = tempfile::tempdir()?; + write_test_config_with_bundled_models(home.path(), &repo)?; + let editor = home.path().join("editor"); + codex_utils_cargo_bin::write_executable(&editor, "#!/bin/sh\nprintf 'λ edited' > \"$1\"\n")?; + let codex = codex_utils_cargo_bin::cargo_bin("codex-tui") + .or_else(|_| codex_utils_cargo_bin::cargo_bin("codex"))?; + let mut terminal = + PtyCodex::start_binary(&codex, &repo, home, &["--no-daemon"], Some(&editor))?; + terminal.wait_for_startup()?; + terminal.wait_for_screen("GPT-5.6-Terra")?; + Ok(terminal) +} + +impl PtyCodex { + fn wait_for_palette(&mut self, ready: impl Fn(&Self) -> bool) -> Result<()> { + let deadline = Instant::now() + FOCUS_INPUT_TIMEOUT; + while !ready(self) { + self.ensure_running()?; + ensure!( + Instant::now() < deadline, + "palette test timed out:\n{}", + self.screen_contents() + ); + self.read_output(Duration::from_millis(/*millis*/ 10))?; + } + Ok(()) + } + + fn draft_color(&self) -> Option { + let screen = self.parser.screen(); + let (rows, columns) = screen.size(); + (0..rows) + .flat_map(|row| (0..columns).map(move |column| (row, column))) + .filter_map(|(row, column)| screen.cell(row, column)) + .find(|cell| cell.contents() == "λ") + .map(vt100::Cell::bgcolor) + } +} + +fn first_editor_return() -> Result<(PtyCodex, vt100::Color)> { + let mut terminal = start()?; + terminal.write_input("λ draft".as_bytes())?; + terminal.wait_for_screen("λ draft")?; + let dark = terminal.draft_color().context("missing draft")?; + terminal.write_input(b"\x07")?; + terminal.wait_for_palette(|t| contains_bytes(&t.output, QUERY))?; + terminal.write_input(&[WHITE, RESET].concat())?; + terminal.wait_for_screen("λ edited")?; + terminal.wait_for_palette(|t| t.draft_color().is_some_and(|color| color != dark))?; + Ok((terminal, dark)) +} + +#[test] +fn editor_return_uses_fresh_colors() -> Result<()> { + let (mut terminal, dark) = first_editor_return()?; + let returned = terminal.draft_color().context("missing edited draft")?; + insta::assert_snapshot!( + format!("Draft {dark:?} → editor return {returned:?}"), + @"Draft Rgb(30, 30, 30) → editor return Rgb(244, 244, 244)" + ); + + // An Enter decoded before the editor starts must never submit its result. + terminal.output.clear(); + terminal.write_input(b"\x07")?; + terminal.wait_for_palette(|t| contains_bytes(&t.output, b"\x1b[c"))?; + terminal.write_input(b"\r\x1b[?1;2c")?; + terminal.wait_for_palette(|t| contains_bytes(&t.output, QUERY))?; + terminal.write_input(&[WHITE, RESET, b"-kept"].concat())?; + terminal.wait_for_screen("λ edited-kept")?; + Ok(()) +} + +#[test] +fn suspend_timeout_preserves_the_draft_and_retries_the_marker_on_exit() -> Result<()> { + verify_timeout_and_exit(b"\x1b[122;5u", "Press Ctrl+Z to retry") +} + +#[test] +fn editor_timeout_preserves_the_draft_and_retries_the_marker_on_exit() -> Result<()> { + verify_timeout_and_exit(b"\x07", "Timed out waiting for terminal color reports") +} + +fn verify_timeout_and_exit(shortcut: &[u8], message: &str) -> Result<()> { + let (mut terminal, _) = first_editor_return()?; + terminal.output.clear(); + terminal.write_input(shortcut)?; + terminal.wait_for_palette(|t| contains_bytes(&t.output, b"\x1b[c"))?; + terminal.write_input(b"!")?; + terminal.wait_for_screen(message)?; + terminal.wait_for_screen("λ edited!")?; + if shortcut == b"\x1b[122;5u" { + let screen = terminal.screen_contents(); + let line = screen + .lines() + .find(|line| line.contains(message)) + .context("missing suspend feedback")?; + insta::assert_snapshot!(line.trim(), @"■ Press Ctrl+Z to retry. Timed out waiting for terminal color reports."); + } + + terminal.output.clear(); + terminal.write_input(b"\x15\x1b[99;5u")?; + terminal.wait_for_palette(|t| contains_bytes(&t.output, b"\x1b[?30000$p"))?; + assert!(!contains_bytes(&terminal.output, b"\x1b[c")); + // Exit must consume the matching reply before its two-second fallback. + let deadline = Instant::now() + Duration::from_millis(/*millis*/ 1500); + terminal.write_input(b"\x1b[?1;2c")?; + std::thread::sleep(Duration::from_millis(/*millis*/ 50)); + terminal.ensure_running()?; + terminal.write_input(b"\x1b[?30000;0$y")?; + loop { + terminal.read_output(Duration::from_millis(/*millis*/ 10))?; + ensure!( + Instant::now() < deadline, + "numbered reply did not release exit" + ); + if let Some(status) = terminal.child.try_wait()? { + ensure!(status.success(), "exit failed: {status}"); + break; + } + } + terminal.write_input(b"shell\n")?; + let mut input = [0; 6]; + terminal.slave.read_exact(&mut input)?; + pretty_assertions::assert_eq!(&input, b"shell\n"); + Ok(()) +} diff --git a/codex-rs/tui/tests/suite/startup_color_replay_tests.rs b/codex-rs/tui/tests/suite/startup_color_replay_tests.rs index 1f77aafec0..65dbb9dd17 100644 --- a/codex-rs/tui/tests/suite/startup_color_replay_tests.rs +++ b/codex-rs/tui/tests/suite/startup_color_replay_tests.rs @@ -32,6 +32,49 @@ fn startup_color_reply_started_after_probe_preserves_input() -> Result<()> { #[test] fn startup_color_reply_consumed_inside_paste_does_not_delay_escape() -> Result<()> { + let mut attempt = 0; + let (mut terminal, query_observed_at) = loop { + attempt += 1; + let (mut terminal, query_observed_at) = prepare_consumed_color_paste()?; + terminal.ensure_running()?; + // A stale preparation must not hide a reply that has already leaked into the draft. + ensure!(!terminal.screen_contains(";rgb:"), "color reply leaked"); + let query_age = query_observed_at.elapsed(); + if query_age < Duration::from_millis(/*millis*/ 1500) { + break (terminal, query_observed_at); + } + eprintln!( + "consumed-paste preparation {attempt}/3 reached search at {query_age:?}; no Escape sent" + ); + ensure!( + attempt < 3, + "could not prepare consumed-paste Escape inside the startup reply budget" + ); + }; + ensure!( + query_observed_at.elapsed() < Duration::from_millis(/*millis*/ 1500), + "search setup missed the startup color grace window" + ); + terminal.write_input(b"\x1b")?; + let escape_deadline = Instant::now() + Duration::from_millis(/*millis*/ 250); + while terminal.screen_contains("reverse-i-search:") { + terminal.ensure_running()?; + terminal.read_output(Duration::from_millis(/*millis*/ 5))?; + ensure!( + Instant::now() < escape_deadline, + "consumed color replies delayed Escape: {}", + terminal.screen_contents(), + ); + } + ensure!( + terminal.screen_contains("paste-kept"), + "paste draft was lost" + ); + ensure!(!terminal.screen_contains(";rgb:"), "color reply leaked"); + Ok(()) +} + +fn prepare_consumed_color_paste() -> Result<(PtyCodex, Instant)> { let repo_root = codex_utils_cargo_bin::repo_root()?; let codex = codex_utils_cargo_bin::cargo_bin("codex-tui") .or_else(|_| codex_utils_cargo_bin::cargo_bin("codex"))?; @@ -72,27 +115,7 @@ fn startup_color_reply_consumed_inside_paste_does_not_delay_escape() -> Result<( terminal.wait_for_screen("GPT-5.6-Terra")?; terminal.write_input(b"\x12")?; terminal.wait_for_screen("reverse-i-search:")?; - ensure!( - query_observed_at.elapsed() < Duration::from_millis(/*millis*/ 1500), - "search setup missed the startup color grace window" - ); - terminal.write_input(b"\x1b")?; - let escape_deadline = Instant::now() + Duration::from_millis(/*millis*/ 250); - while terminal.screen_contains("reverse-i-search:") { - terminal.ensure_running()?; - terminal.read_output(Duration::from_millis(/*millis*/ 5))?; - ensure!( - Instant::now() < escape_deadline, - "consumed color replies delayed Escape: {}", - terminal.screen_contents(), - ); - } - ensure!( - terminal.screen_contains("paste-kept"), - "paste draft was lost" - ); - ensure!(!terminal.screen_contains(";rgb:"), "color reply leaked"); - Ok(()) + Ok((terminal, query_observed_at)) } fn check_split_color_reply(continuation: Continuation) -> Result<()> {