From 96acb8a74e14897faa36d66cd50768c0b0978e59 Mon Sep 17 00:00:00 2001 From: dedrisian-oai Date: Wed, 8 Oct 2025 11:42:09 -0700 Subject: [PATCH 01/32] Fix transcript mode rendering issue when showing tab chars (#4911) There's a weird rendering issue with transcript mode: Tab chars bleed through when scrolling up/down. e.g. `nl -ba ...` adds tab chars to each line, which make scrolling look glitchy in transcript mode. Before: https://github.com/user-attachments/assets/631ee7fc-6083-4d35-aaf0-a0b08e734470 After: https://github.com/user-attachments/assets/bbba6111-4bfc-4862-8357-0f51aa2a21ac --- codex-rs/ansi-escape/src/lib.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/codex-rs/ansi-escape/src/lib.rs b/codex-rs/ansi-escape/src/lib.rs index 68ea5e9aa9..b47cf14f8e 100644 --- a/codex-rs/ansi-escape/src/lib.rs +++ b/codex-rs/ansi-escape/src/lib.rs @@ -3,11 +3,30 @@ use ansi_to_tui::IntoText; use ratatui::text::Line; use ratatui::text::Text; +// Expand tabs in a best-effort way for transcript rendering. +// Tabs can interact poorly with left-gutter prefixes in our TUI and CLI +// transcript views (e.g., `nl` separates line numbers from content with a tab). +// Replacing tabs with spaces avoids odd visual artifacts without changing +// semantics for our use cases. +fn expand_tabs(s: &str) -> std::borrow::Cow<'_, str> { + if s.contains('\t') { + // Keep it simple: replace each tab with 4 spaces. + // We do not try to align to tab stops since most usages (like `nl`) + // look acceptable with a fixed substitution and this avoids stateful math + // across spans. + std::borrow::Cow::Owned(s.replace('\t', " ")) + } else { + std::borrow::Cow::Borrowed(s) + } +} + /// This function should be used when the contents of `s` are expected to match /// a single line. If multiple lines are found, a warning is logged and only the /// first line is returned. pub fn ansi_escape_line(s: &str) -> Line<'static> { - let text = ansi_escape(s); + // Normalize tabs to spaces to avoid odd gutter collisions in transcript mode. + let s = expand_tabs(s); + let text = ansi_escape(&s); match text.lines.as_slice() { [] => "".into(), [only] => only.clone(), From e896db1180cc1e893f6d3d878bafe909c518c24e Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Wed, 8 Oct 2025 13:23:13 -0700 Subject: [PATCH 02/32] tui: hardcode xterm palette, shimmer blends between fg and bg (#4957) Instead of querying all 256 terminal colors on startup, which was slow in some terminals, hardcode the default xterm palette. Additionally, tweak the shimmer so that it blends between default_fg and default_bg, instead of "dark gray" (according to the terminal) and pure white (regardless of terminal theme). --- codex-rs/tui/src/shimmer.rs | 15 +- codex-rs/tui/src/style.rs | 25 +- codex-rs/tui/src/terminal_palette.rs | 527 +++++++++++++++------------ codex-rs/tui/src/tui.rs | 1 - 4 files changed, 300 insertions(+), 268 deletions(-) diff --git a/codex-rs/tui/src/shimmer.rs b/codex-rs/tui/src/shimmer.rs index a6a16f2ce6..ba081e7c49 100644 --- a/codex-rs/tui/src/shimmer.rs +++ b/codex-rs/tui/src/shimmer.rs @@ -8,10 +8,8 @@ use ratatui::style::Style; use ratatui::text::Span; use crate::color::blend; +use crate::terminal_palette::default_bg; use crate::terminal_palette::default_fg; -use crate::terminal_palette::terminal_palette; - -const FALLBACK_DARK_GRAY: (u8, u8, u8) = (103, 103, 103); static PROCESS_START: OnceLock = OnceLock::new(); @@ -35,11 +33,11 @@ pub(crate) fn shimmer_spans(text: &str) -> Vec> { let has_true_color = supports_color::on_cached(supports_color::Stream::Stdout) .map(|level| level.has_16m) .unwrap_or(false); - let band_half_width = 3.0; + let band_half_width = 5.0; let mut spans: Vec> = Vec::with_capacity(chars.len()); - let default_fg = default_fg(); - let palette_dark_gray = terminal_palette().map(|palette| palette[8]); + let base_color = default_fg().unwrap_or((128, 128, 128)); + let highlight_color = default_bg().unwrap_or((255, 255, 255)); for (i, ch) in chars.iter().enumerate() { let i_pos = i as isize + padding as isize; let pos = pos as isize; @@ -52,11 +50,8 @@ pub(crate) fn shimmer_spans(text: &str) -> Vec> { 0.0 }; let style = if has_true_color { - let base = palette_dark_gray - .or(default_fg) - .unwrap_or(FALLBACK_DARK_GRAY); let highlight = t.clamp(0.0, 1.0); - let (r, g, b) = blend((255, 255, 255), base, highlight); + let (r, g, b) = blend(highlight_color, base_color, highlight * 0.9); // Allow custom RGB colors, as the implementation is thoughtfully // adjusting the level of the default foreground color. #[allow(clippy::disallowed_methods)] diff --git a/codex-rs/tui/src/style.rs b/codex-rs/tui/src/style.rs index 01861e1e15..e50d59791e 100644 --- a/codex-rs/tui/src/style.rs +++ b/codex-rs/tui/src/style.rs @@ -1,8 +1,7 @@ use crate::color::blend; use crate::color::is_light; -use crate::color::perceptual_distance; +use crate::terminal_palette::best_color; use crate::terminal_palette::default_bg; -use crate::terminal_palette::terminal_palette; use ratatui::style::Color; use ratatui::style::Style; @@ -25,25 +24,5 @@ pub fn user_message_bg(terminal_bg: (u8, u8, u8)) -> Color { } else { (255, 255, 255) }; - let bottom = terminal_bg; - let Some(color_level) = supports_color::on_cached(supports_color::Stream::Stdout) else { - return Color::default(); - }; - - let target = blend(top, bottom, 0.1); - if color_level.has_16m { - let (r, g, b) = target; - Color::Rgb(r, g, b) - } else if color_level.has_256 - && let Some(palette) = terminal_palette() - && let Some((i, _)) = palette.into_iter().enumerate().min_by(|(_, a), (_, b)| { - perceptual_distance(*a, target) - .partial_cmp(&perceptual_distance(*b, target)) - .unwrap_or(std::cmp::Ordering::Equal) - }) - { - Color::Indexed(i as u8) - } else { - Color::default() - } + best_color(blend(top, terminal_bg, 0.1)) } diff --git a/codex-rs/tui/src/terminal_palette.rs b/codex-rs/tui/src/terminal_palette.rs index c35b2cfff4..3f2748eb8e 100644 --- a/codex-rs/tui/src/terminal_palette.rs +++ b/codex-rs/tui/src/terminal_palette.rs @@ -1,5 +1,28 @@ -pub fn terminal_palette() -> Option<[(u8, u8, u8); 256]> { - imp::terminal_palette() +use crate::color::perceptual_distance; +use ratatui::style::Color; + +/// Returns the closest color to the target color that the terminal can display. +pub fn best_color(target: (u8, u8, u8)) -> Color { + let Some(color_level) = supports_color::on_cached(supports_color::Stream::Stdout) else { + return Color::default(); + }; + if color_level.has_16m { + let (r, g, b) = target; + #[allow(clippy::disallowed_methods)] + Color::Rgb(r, g, b) + } else if color_level.has_256 + && let Some((i, _)) = xterm_fixed_colors().enumerate().min_by(|(_, a), (_, b)| { + perceptual_distance(*a, target) + .partial_cmp(&perceptual_distance(*b, target)) + .unwrap_or(std::cmp::Ordering::Equal) + }) + { + #[allow(clippy::disallowed_methods)] + Color::Indexed(i as u8) + } else { + #[allow(clippy::disallowed_methods)] + Color::default() + } } pub fn requery_default_colors() { @@ -8,7 +31,6 @@ pub fn requery_default_colors() { #[derive(Clone, Copy)] pub struct DefaultColors { - #[allow(dead_code)] fg: (u8, u8, u8), bg: (u8, u8, u8), } @@ -17,7 +39,6 @@ pub fn default_colors() -> Option { imp::default_colors() } -#[allow(dead_code)] pub fn default_fg() -> Option<(u8, u8, u8)> { default_colors().map(|c| c.fg) } @@ -29,8 +50,6 @@ pub fn default_bg() -> Option<(u8, u8, u8)> { #[cfg(all(unix, not(test)))] mod imp { use super::DefaultColors; - use std::mem::MaybeUninit; - use std::os::fd::RawFd; use std::sync::Mutex; use std::sync::OnceLock; @@ -69,14 +88,6 @@ mod imp { CACHE.get_or_init(|| Mutex::new(Cache::default())) } - pub(super) fn terminal_palette() -> Option<[(u8, u8, u8); 256]> { - static CACHE: OnceLock> = OnceLock::new(); - *CACHE.get_or_init(|| match query_terminal_palette() { - Ok(Some(palette)) => Some(palette), - _ => None, - }) - } - pub(super) fn default_colors() -> Option { let cache = default_colors_cache(); let mut cache = cache.lock().ok()?; @@ -89,84 +100,6 @@ mod imp { } } - #[allow(dead_code)] - fn query_terminal_palette() -> std::io::Result> { - use std::fs::OpenOptions; - use std::io::ErrorKind; - use std::io::IsTerminal; - use std::io::Read; - use std::io::Write; - use std::os::fd::AsRawFd; - use std::time::Duration; - use std::time::Instant; - - if !std::io::stdout().is_terminal() { - return Ok(None); - } - - let mut tty = match OpenOptions::new().read(true).write(true).open("/dev/tty") { - Ok(file) => file, - Err(_) => return Ok(None), - }; - - for index in 0..256 { - write!(tty, "\x1b]4;{index};?\x07")?; - } - tty.flush()?; - - let fd = tty.as_raw_fd(); - let _termios_guard = unsafe { suppress_echo(fd) }; - unsafe { - let flags = libc::fcntl(fd, libc::F_GETFL); - if flags >= 0 { - libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK); - } - } - - let mut palette: [Option<(u8, u8, u8)>; 256] = [None; 256]; - let mut buffer = Vec::new(); - let mut remaining = palette.len(); - let read_deadline = Instant::now() + Duration::from_millis(1500); - - while remaining > 0 && Instant::now() < read_deadline { - let mut chunk = [0u8; 512]; - match tty.read(&mut chunk) { - Ok(0) => break, - Ok(read) => { - buffer.extend_from_slice(&chunk[..read]); - let newly = apply_palette_responses(&mut buffer, &mut palette); - if newly > 0 { - remaining = remaining.saturating_sub(newly); - } - } - Err(err) if err.kind() == ErrorKind::WouldBlock => { - std::thread::sleep(Duration::from_millis(5)); - } - Err(err) if err.kind() == ErrorKind::Interrupted => continue, - Err(_) => return Ok(None), - } - } - - remaining = remaining.saturating_sub(apply_palette_responses(&mut buffer, &mut palette)); - remaining = remaining.saturating_sub(drain_remaining(&mut tty, &mut buffer, &mut palette)); - - if remaining > 0 { - return Ok(None); - } - - let mut colors = [(0, 0, 0); 256]; - for (slot, value) in colors.iter_mut().zip(palette.into_iter()) { - if let Some(rgb) = value { - *slot = rgb; - } else { - return Ok(None); - } - } - - Ok(Some(colors)) - } - - #[allow(dead_code)] fn query_default_colors() -> std::io::Result> { use std::fs::OpenOptions; use std::io::ErrorKind; @@ -236,144 +169,6 @@ mod imp { Ok(fg.zip(bg).map(|(fg, bg)| DefaultColors { fg, bg })) } - fn drain_remaining( - tty: &mut std::fs::File, - buffer: &mut Vec, - palette: &mut [Option<(u8, u8, u8)>; 256], - ) -> usize { - use std::io::ErrorKind; - use std::io::Read; - use std::time::Duration; - use std::time::Instant; - - let mut chunk = [0u8; 512]; - let mut idle_deadline = Instant::now() + Duration::from_millis(50); - let mut newly_filled = 0usize; - - loop { - match tty.read(&mut chunk) { - Ok(0) => break, - Ok(read) => { - buffer.extend_from_slice(&chunk[..read]); - newly_filled += apply_palette_responses(buffer, palette); - idle_deadline = Instant::now() + Duration::from_millis(50); - } - Err(err) if err.kind() == ErrorKind::WouldBlock => { - if Instant::now() >= idle_deadline { - break; - } - std::thread::sleep(Duration::from_millis(5)); - } - Err(err) if err.kind() == ErrorKind::Interrupted => continue, - Err(_) => break, - } - } - - buffer.clear(); - newly_filled - } - - struct TermiosGuard { - fd: RawFd, - original: libc::termios, - } - - impl Drop for TermiosGuard { - fn drop(&mut self) { - unsafe { - libc::tcsetattr(self.fd, libc::TCSANOW, &self.original); - } - } - } - - unsafe fn suppress_echo(fd: RawFd) -> Option { - let mut termios = MaybeUninit::::uninit(); - if unsafe { libc::tcgetattr(fd, termios.as_mut_ptr()) } != 0 { - return None; - } - let termios = unsafe { termios.assume_init() }; - let mut modified = termios; - modified.c_lflag &= !(libc::ECHO | libc::ECHONL); - if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &modified) } != 0 { - return None; - } - Some(TermiosGuard { - fd, - original: termios, - }) - } - - fn apply_palette_responses( - buffer: &mut Vec, - palette: &mut [Option<(u8, u8, u8)>; 256], - ) -> usize { - let mut newly_filled = 0; - - while let Some(start) = buffer.windows(2).position(|window| window == [0x1b, b']']) { - if start > 0 { - buffer.drain(..start); - continue; - } - - let mut index = 2; // skip ESC ] - let mut terminator_len = None; - while index < buffer.len() { - match buffer[index] { - 0x07 => { - terminator_len = Some(1); - break; - } - 0x1b if index + 1 < buffer.len() && buffer[index + 1] == b'\\' => { - terminator_len = Some(2); - break; - } - _ => index += 1, - } - } - - let Some(terminator_len) = terminator_len else { - break; - }; - - let end = index; - let parsed = std::str::from_utf8(&buffer[2..end]) - .ok() - .and_then(parse_palette_message); - let processed = end + terminator_len; - buffer.drain(..processed); - - if let Some((slot, color)) = parsed - && palette[slot].is_none() - { - palette[slot] = Some(color); - newly_filled += 1; - } - } - - newly_filled - } - - fn parse_palette_message(message: &str) -> Option<(usize, (u8, u8, u8))> { - let mut parts = message.splitn(3, ';'); - if parts.next()? != "4" { - return None; - } - let index: usize = parts.next()?.trim().parse().ok()?; - if index >= 256 { - return None; - } - let payload = parts.next()?; - let (model, values) = payload.split_once(':')?; - if model != "rgb" && model != "rgba" { - return None; - } - let mut components = values.split('/'); - let r = parse_component(components.next()?)?; - let g = parse_component(components.next()?)?; - let b = parse_component(components.next()?)?; - Some((index, (r, g, b))) - } - fn parse_component(component: &str) -> Option { let trimmed = component.trim(); if trimmed.is_empty() { @@ -433,13 +228,277 @@ mod imp { mod imp { use super::DefaultColors; - pub(super) fn terminal_palette() -> Option<[(u8, u8, u8); 256]> { - None - } - pub(super) fn default_colors() -> Option { None } pub(super) fn requery_default_colors() {} } + +/// The subset of Xterm colors that are usually consistent across terminals. +pub fn xterm_fixed_colors() -> impl Iterator { + XTERM_COLORS.into_iter().skip(16) +} + +// Xterm colors; derived from https://ss64.com/bash/syntax-colors.html +pub const XTERM_COLORS: [(u8, u8, u8); 256] = [ + // The first 16 colors vary based on terminal theme, so these are likely not the actual colors + // that are displayed when using these indices. + (0, 0, 0), // 0 Black (SYSTEM) + (128, 0, 0), // 1 Maroon (SYSTEM) + (0, 128, 0), // 2 Green (SYSTEM) + (128, 128, 0), // 3 Olive (SYSTEM) + (0, 0, 128), // 4 Navy (SYSTEM) + (128, 0, 128), // 5 Purple (SYSTEM) + (0, 128, 128), // 6 Teal (SYSTEM) + (192, 192, 192), // 7 Silver (SYSTEM) + (128, 128, 128), // 8 Grey (SYSTEM) + (255, 0, 0), // 9 Red (SYSTEM) + (0, 255, 0), // 10 Lime (SYSTEM) + (255, 255, 0), // 11 Yellow (SYSTEM) + (0, 0, 255), // 12 Blue (SYSTEM) + (255, 0, 255), // 13 Fuchsia (SYSTEM) + (0, 255, 255), // 14 Aqua (SYSTEM) + (255, 255, 255), // 15 White (SYSTEM) + // The rest of the colors are consistent in most terminals. + (0, 0, 0), // 16 Grey0 + (0, 0, 95), // 17 NavyBlue + (0, 0, 135), // 18 DarkBlue + (0, 0, 175), // 19 Blue3 + (0, 0, 215), // 20 Blue3 + (0, 0, 255), // 21 Blue1 + (0, 95, 0), // 22 DarkGreen + (0, 95, 95), // 23 DeepSkyBlue4 + (0, 95, 135), // 24 DeepSkyBlue4 + (0, 95, 175), // 25 DeepSkyBlue4 + (0, 95, 215), // 26 DodgerBlue3 + (0, 95, 255), // 27 DodgerBlue2 + (0, 135, 0), // 28 Green4 + (0, 135, 95), // 29 SpringGreen4 + (0, 135, 135), // 30 Turquoise4 + (0, 135, 175), // 31 DeepSkyBlue3 + (0, 135, 215), // 32 DeepSkyBlue3 + (0, 135, 255), // 33 DodgerBlue1 + (0, 175, 0), // 34 Green3 + (0, 175, 95), // 35 SpringGreen3 + (0, 175, 135), // 36 DarkCyan + (0, 175, 175), // 37 LightSeaGreen + (0, 175, 215), // 38 DeepSkyBlue2 + (0, 175, 255), // 39 DeepSkyBlue1 + (0, 215, 0), // 40 Green3 + (0, 215, 95), // 41 SpringGreen3 + (0, 215, 135), // 42 SpringGreen2 + (0, 215, 175), // 43 Cyan3 + (0, 215, 215), // 44 DarkTurquoise + (0, 215, 255), // 45 Turquoise2 + (0, 255, 0), // 46 Green1 + (0, 255, 95), // 47 SpringGreen2 + (0, 255, 135), // 48 SpringGreen1 + (0, 255, 175), // 49 MediumSpringGreen + (0, 255, 215), // 50 Cyan2 + (0, 255, 255), // 51 Cyan1 + (95, 0, 0), // 52 DarkRed + (95, 0, 95), // 53 DeepPink4 + (95, 0, 135), // 54 Purple4 + (95, 0, 175), // 55 Purple4 + (95, 0, 215), // 56 Purple3 + (95, 0, 255), // 57 BlueViolet + (95, 95, 0), // 58 Orange4 + (95, 95, 95), // 59 Grey37 + (95, 95, 135), // 60 MediumPurple4 + (95, 95, 175), // 61 SlateBlue3 + (95, 95, 215), // 62 SlateBlue3 + (95, 95, 255), // 63 RoyalBlue1 + (95, 135, 0), // 64 Chartreuse4 + (95, 135, 95), // 65 DarkSeaGreen4 + (95, 135, 135), // 66 PaleTurquoise4 + (95, 135, 175), // 67 SteelBlue + (95, 135, 215), // 68 SteelBlue3 + (95, 135, 255), // 69 CornflowerBlue + (95, 175, 0), // 70 Chartreuse3 + (95, 175, 95), // 71 DarkSeaGreen4 + (95, 175, 135), // 72 CadetBlue + (95, 175, 175), // 73 CadetBlue + (95, 175, 215), // 74 SkyBlue3 + (95, 175, 255), // 75 SteelBlue1 + (95, 215, 0), // 76 Chartreuse3 + (95, 215, 95), // 77 PaleGreen3 + (95, 215, 135), // 78 SeaGreen3 + (95, 215, 175), // 79 Aquamarine3 + (95, 215, 215), // 80 MediumTurquoise + (95, 215, 255), // 81 SteelBlue1 + (95, 255, 0), // 82 Chartreuse2 + (95, 255, 95), // 83 SeaGreen2 + (95, 255, 135), // 84 SeaGreen1 + (95, 255, 175), // 85 SeaGreen1 + (95, 255, 215), // 86 Aquamarine1 + (95, 255, 255), // 87 DarkSlateGray2 + (135, 0, 0), // 88 DarkRed + (135, 0, 95), // 89 DeepPink4 + (135, 0, 135), // 90 DarkMagenta + (135, 0, 175), // 91 DarkMagenta + (135, 0, 215), // 92 DarkViolet + (135, 0, 255), // 93 Purple + (135, 95, 0), // 94 Orange4 + (135, 95, 95), // 95 LightPink4 + (135, 95, 135), // 96 Plum4 + (135, 95, 175), // 97 MediumPurple3 + (135, 95, 215), // 98 MediumPurple3 + (135, 95, 255), // 99 SlateBlue1 + (135, 135, 0), // 100 Yellow4 + (135, 135, 95), // 101 Wheat4 + (135, 135, 135), // 102 Grey53 + (135, 135, 175), // 103 LightSlateGrey + (135, 135, 215), // 104 MediumPurple + (135, 135, 255), // 105 LightSlateBlue + (135, 175, 0), // 106 Yellow4 + (135, 175, 95), // 107 DarkOliveGreen3 + (135, 175, 135), // 108 DarkSeaGreen + (135, 175, 175), // 109 LightSkyBlue3 + (135, 175, 215), // 110 LightSkyBlue3 + (135, 175, 255), // 111 SkyBlue2 + (135, 215, 0), // 112 Chartreuse2 + (135, 215, 95), // 113 DarkOliveGreen3 + (135, 215, 135), // 114 PaleGreen3 + (135, 215, 175), // 115 DarkSeaGreen3 + (135, 215, 215), // 116 DarkSlateGray3 + (135, 215, 255), // 117 SkyBlue1 + (135, 255, 0), // 118 Chartreuse1 + (135, 255, 95), // 119 LightGreen + (135, 255, 135), // 120 LightGreen + (135, 255, 175), // 121 PaleGreen1 + (135, 255, 215), // 122 Aquamarine1 + (135, 255, 255), // 123 DarkSlateGray1 + (175, 0, 0), // 124 Red3 + (175, 0, 95), // 125 DeepPink4 + (175, 0, 135), // 126 MediumVioletRed + (175, 0, 175), // 127 Magenta3 + (175, 0, 215), // 128 DarkViolet + (175, 0, 255), // 129 Purple + (175, 95, 0), // 130 DarkOrange3 + (175, 95, 95), // 131 IndianRed + (175, 95, 135), // 132 HotPink3 + (175, 95, 175), // 133 MediumOrchid3 + (175, 95, 215), // 134 MediumOrchid + (175, 95, 255), // 135 MediumPurple2 + (175, 135, 0), // 136 DarkGoldenrod + (175, 135, 95), // 137 LightSalmon3 + (175, 135, 135), // 138 RosyBrown + (175, 135, 175), // 139 Grey63 + (175, 135, 215), // 140 MediumPurple2 + (175, 135, 255), // 141 MediumPurple1 + (175, 175, 0), // 142 Gold3 + (175, 175, 95), // 143 DarkKhaki + (175, 175, 135), // 144 NavajoWhite3 + (175, 175, 175), // 145 Grey69 + (175, 175, 215), // 146 LightSteelBlue3 + (175, 175, 255), // 147 LightSteelBlue + (175, 215, 0), // 148 Yellow3 + (175, 215, 95), // 149 DarkOliveGreen3 + (175, 215, 135), // 150 DarkSeaGreen3 + (175, 215, 175), // 151 DarkSeaGreen2 + (175, 215, 215), // 152 LightCyan3 + (175, 215, 255), // 153 LightSkyBlue1 + (175, 255, 0), // 154 GreenYellow + (175, 255, 95), // 155 DarkOliveGreen2 + (175, 255, 135), // 156 PaleGreen1 + (175, 255, 175), // 157 DarkSeaGreen2 + (175, 255, 215), // 158 DarkSeaGreen1 + (175, 255, 255), // 159 PaleTurquoise1 + (215, 0, 0), // 160 Red3 + (215, 0, 95), // 161 DeepPink3 + (215, 0, 135), // 162 DeepPink3 + (215, 0, 175), // 163 Magenta3 + (215, 0, 215), // 164 Magenta3 + (215, 0, 255), // 165 Magenta2 + (215, 95, 0), // 166 DarkOrange3 + (215, 95, 95), // 167 IndianRed + (215, 95, 135), // 168 HotPink3 + (215, 95, 175), // 169 HotPink2 + (215, 95, 215), // 170 Orchid + (215, 95, 255), // 171 MediumOrchid1 + (215, 135, 0), // 172 Orange3 + (215, 135, 95), // 173 LightSalmon3 + (215, 135, 135), // 174 LightPink3 + (215, 135, 175), // 175 Pink3 + (215, 135, 215), // 176 Plum3 + (215, 135, 255), // 177 Violet + (215, 175, 0), // 178 Gold3 + (215, 175, 95), // 179 LightGoldenrod3 + (215, 175, 135), // 180 Tan + (215, 175, 175), // 181 MistyRose3 + (215, 175, 215), // 182 Thistle3 + (215, 175, 255), // 183 Plum2 + (215, 215, 0), // 184 Yellow3 + (215, 215, 95), // 185 Khaki3 + (215, 215, 135), // 186 LightGoldenrod2 + (215, 215, 175), // 187 LightYellow3 + (215, 215, 215), // 188 Grey84 + (215, 215, 255), // 189 LightSteelBlue1 + (215, 255, 0), // 190 Yellow2 + (215, 255, 95), // 191 DarkOliveGreen1 + (215, 255, 135), // 192 DarkOliveGreen1 + (215, 255, 175), // 193 DarkSeaGreen1 + (215, 255, 215), // 194 Honeydew2 + (215, 255, 255), // 195 LightCyan1 + (255, 0, 0), // 196 Red1 + (255, 0, 95), // 197 DeepPink2 + (255, 0, 135), // 198 DeepPink1 + (255, 0, 175), // 199 DeepPink1 + (255, 0, 215), // 200 Magenta2 + (255, 0, 255), // 201 Magenta1 + (255, 95, 0), // 202 OrangeRed1 + (255, 95, 95), // 203 IndianRed1 + (255, 95, 135), // 204 IndianRed1 + (255, 95, 175), // 205 HotPink + (255, 95, 215), // 206 HotPink + (255, 95, 255), // 207 MediumOrchid1 + (255, 135, 0), // 208 DarkOrange + (255, 135, 95), // 209 Salmon1 + (255, 135, 135), // 210 LightCoral + (255, 135, 175), // 211 PaleVioletRed1 + (255, 135, 215), // 212 Orchid2 + (255, 135, 255), // 213 Orchid1 + (255, 175, 0), // 214 Orange1 + (255, 175, 95), // 215 SandyBrown + (255, 175, 135), // 216 LightSalmon1 + (255, 175, 175), // 217 LightPink1 + (255, 175, 215), // 218 Pink1 + (255, 175, 255), // 219 Plum1 + (255, 215, 0), // 220 Gold1 + (255, 215, 95), // 221 LightGoldenrod2 + (255, 215, 135), // 222 LightGoldenrod2 + (255, 215, 175), // 223 NavajoWhite1 + (255, 215, 215), // 224 MistyRose1 + (255, 215, 255), // 225 Thistle1 + (255, 255, 0), // 226 Yellow1 + (255, 255, 95), // 227 LightGoldenrod1 + (255, 255, 135), // 228 Khaki1 + (255, 255, 175), // 229 Wheat1 + (255, 255, 215), // 230 Cornsilk1 + (255, 255, 255), // 231 Grey100 + (8, 8, 8), // 232 Grey3 + (18, 18, 18), // 233 Grey7 + (28, 28, 28), // 234 Grey11 + (38, 38, 38), // 235 Grey15 + (48, 48, 48), // 236 Grey19 + (58, 58, 58), // 237 Grey23 + (68, 68, 68), // 238 Grey27 + (78, 78, 78), // 239 Grey30 + (88, 88, 88), // 240 Grey35 + (98, 98, 98), // 241 Grey39 + (108, 108, 108), // 242 Grey42 + (118, 118, 118), // 243 Grey46 + (128, 128, 128), // 244 Grey50 + (138, 138, 138), // 245 Grey54 + (148, 148, 148), // 246 Grey58 + (158, 158, 158), // 247 Grey62 + (168, 168, 168), // 248 Grey66 + (178, 178, 178), // 249 Grey70 + (188, 188, 188), // 250 Grey74 + (198, 198, 198), // 251 Grey78 + (208, 208, 208), // 252 Grey82 + (218, 218, 218), // 253 Grey85 + (228, 228, 228), // 254 Grey89 + (238, 238, 238), // 255 Grey93 +]; diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 743a9fe2f7..f6e1c2c5d5 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -277,7 +277,6 @@ impl Tui { let enhanced_keys_supported = supports_keyboard_enhancement().unwrap_or(false); // Cache this to avoid contention with the event reader. supports_color::on_cached(supports_color::Stream::Stdout); - let _ = crate::terminal_palette::terminal_palette(); let _ = crate::terminal_palette::default_colors(); Self { From d3820f4782ddb59dffac96100f8ef1e248901fae Mon Sep 17 00:00:00 2001 From: Gabriel Peal Date: Wed, 8 Oct 2025 13:24:51 -0700 Subject: [PATCH 03/32] [MCP] Add an `enabled` config field (#4917) This lets users more easily toggle MCP servers. --- codex-rs/cli/src/mcp_cmd.rs | 58 +++++++++++++++++---- codex-rs/cli/tests/mcp_add_remove.rs | 4 ++ codex-rs/cli/tests/mcp_list.rs | 7 ++- codex-rs/core/src/config.rs | 43 +++++++++++++++ codex-rs/core/src/config_types.rs | 29 +++++++++++ codex-rs/core/src/mcp_connection_manager.rs | 4 ++ codex-rs/core/tests/suite/rmcp_client.rs | 3 ++ codex-rs/tui/src/history_cell.rs | 10 +++- docs/config.md | 11 ++-- 9 files changed, 155 insertions(+), 14 deletions(-) diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 0cf3c0e228..964b69480c 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -234,6 +234,7 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re let new_entry = McpServerConfig { transport, + enabled: true, startup_timeout_sec: None, tool_timeout_sec: None, }; @@ -365,6 +366,7 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> serde_json::json!({ "name": name, + "enabled": cfg.enabled, "transport": transport, "startup_timeout_sec": cfg .startup_timeout_sec @@ -385,8 +387,8 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> return Ok(()); } - let mut stdio_rows: Vec<[String; 4]> = Vec::new(); - let mut http_rows: Vec<[String; 3]> = Vec::new(); + let mut stdio_rows: Vec<[String; 5]> = Vec::new(); + let mut http_rows: Vec<[String; 4]> = Vec::new(); for (name, cfg) in entries { match &cfg.transport { @@ -409,23 +411,46 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> .join(", ") } }; - stdio_rows.push([name.clone(), command.clone(), args_display, env_display]); + let status = if cfg.enabled { + "enabled".to_string() + } else { + "disabled".to_string() + }; + stdio_rows.push([ + name.clone(), + command.clone(), + args_display, + env_display, + status, + ]); } McpServerTransportConfig::StreamableHttp { url, bearer_token_env_var, } => { + let status = if cfg.enabled { + "enabled".to_string() + } else { + "disabled".to_string() + }; http_rows.push([ name.clone(), url.clone(), bearer_token_env_var.clone().unwrap_or("-".to_string()), + status, ]); } } } if !stdio_rows.is_empty() { - let mut widths = ["Name".len(), "Command".len(), "Args".len(), "Env".len()]; + let mut widths = [ + "Name".len(), + "Command".len(), + "Args".len(), + "Env".len(), + "Status".len(), + ]; for row in &stdio_rows { for (i, cell) in row.iter().enumerate() { widths[i] = widths[i].max(cell.len()); @@ -433,28 +458,32 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> } println!( - "{: } if !http_rows.is_empty() { - let mut widths = ["Name".len(), "Url".len(), "Bearer Token Env Var".len()]; + let mut widths = [ + "Name".len(), + "Url".len(), + "Bearer Token Env Var".len(), + "Status".len(), + ]; for row in &http_rows { for (i, cell) in row.iter().enumerate() { widths[i] = widths[i].max(cell.len()); @@ -472,24 +506,28 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> } println!( - "{: Re }; let output = serde_json::to_string_pretty(&serde_json::json!({ "name": get_args.name, + "enabled": server.enabled, "transport": transport, "startup_timeout_sec": server .startup_timeout_sec @@ -539,6 +578,7 @@ async fn run_get(config_overrides: &CliConfigOverrides, get_args: GetArgs) -> Re } println!("{}", get_args.name); + println!(" enabled: {}", server.enabled); match &server.transport { McpServerTransportConfig::Stdio { command, args, env } => { println!(" transport: stdio"); diff --git a/codex-rs/cli/tests/mcp_add_remove.rs b/codex-rs/cli/tests/mcp_add_remove.rs index 9ccb9f73d0..705509abf5 100644 --- a/codex-rs/cli/tests/mcp_add_remove.rs +++ b/codex-rs/cli/tests/mcp_add_remove.rs @@ -35,6 +35,7 @@ async fn add_and_remove_server_updates_global_config() -> Result<()> { } other => panic!("unexpected transport: {other:?}"), } + assert!(docs.enabled); let mut remove_cmd = codex_command(codex_home.path())?; remove_cmd @@ -90,6 +91,7 @@ async fn add_with_env_preserves_key_order_and_values() -> Result<()> { assert_eq!(env.len(), 2); assert_eq!(env.get("FOO"), Some(&"bar".to_string())); assert_eq!(env.get("ALPHA"), Some(&"beta".to_string())); + assert!(envy.enabled); Ok(()) } @@ -116,6 +118,7 @@ async fn add_streamable_http_without_manual_token() -> Result<()> { } other => panic!("unexpected transport: {other:?}"), } + assert!(github.enabled); assert!(!codex_home.path().join(".credentials.json").exists()); assert!(!codex_home.path().join(".env").exists()); @@ -153,6 +156,7 @@ async fn add_streamable_http_with_custom_env_var() -> Result<()> { } other => panic!("unexpected transport: {other:?}"), } + assert!(issues.enabled); Ok(()) } diff --git a/codex-rs/cli/tests/mcp_list.rs b/codex-rs/cli/tests/mcp_list.rs index 6c83de19fa..0a80dd0cbf 100644 --- a/codex-rs/cli/tests/mcp_list.rs +++ b/codex-rs/cli/tests/mcp_list.rs @@ -1,6 +1,7 @@ use std::path::Path; use anyhow::Result; +use predicates::prelude::PredicateBooleanExt; use predicates::str::contains; use pretty_assertions::assert_eq; use serde_json::Value as JsonValue; @@ -53,6 +54,8 @@ fn list_and_get_render_expected_output() -> Result<()> { assert!(stdout.contains("docs")); assert!(stdout.contains("docs-server")); assert!(stdout.contains("TOKEN=secret")); + assert!(stdout.contains("Status")); + assert!(stdout.contains("enabled")); let mut list_json_cmd = codex_command(codex_home.path())?; let json_output = list_json_cmd.args(["mcp", "list", "--json"]).output()?; @@ -64,6 +67,7 @@ fn list_and_get_render_expected_output() -> Result<()> { json!([ { "name": "docs", + "enabled": true, "transport": { "type": "stdio", "command": "docs-server", @@ -91,6 +95,7 @@ fn list_and_get_render_expected_output() -> Result<()> { assert!(stdout.contains("command: docs-server")); assert!(stdout.contains("args: --port 4000")); assert!(stdout.contains("env: TOKEN=secret")); + assert!(stdout.contains("enabled: true")); assert!(stdout.contains("remove: codex mcp remove docs")); let mut get_json_cmd = codex_command(codex_home.path())?; @@ -98,7 +103,7 @@ fn list_and_get_render_expected_output() -> Result<()> { .args(["mcp", "get", "docs", "--json"]) .assert() .success() - .stdout(contains("\"name\": \"docs\"")); + .stdout(contains("\"name\": \"docs\"").and(contains("\"enabled\": true"))); Ok(()) } diff --git a/codex-rs/core/src/config.rs b/codex-rs/core/src/config.rs index d0437163fc..c715651851 100644 --- a/codex-rs/core/src/config.rs +++ b/codex-rs/core/src/config.rs @@ -401,6 +401,10 @@ pub fn write_global_mcp_servers( } } + if !config.enabled { + entry["enabled"] = toml_edit::value(false); + } + if let Some(timeout) = config.startup_timeout_sec { entry["startup_timeout_sec"] = toml_edit::value(timeout.as_secs_f64()); } @@ -1515,6 +1519,7 @@ exclude_slash_tmp = true args: vec!["hello".to_string()], env: None, }, + enabled: true, startup_timeout_sec: Some(Duration::from_secs(3)), tool_timeout_sec: Some(Duration::from_secs(5)), }, @@ -1535,6 +1540,7 @@ exclude_slash_tmp = true } assert_eq!(docs.startup_timeout_sec, Some(Duration::from_secs(3))); assert_eq!(docs.tool_timeout_sec, Some(Duration::from_secs(5))); + assert!(docs.enabled); let empty = BTreeMap::new(); write_global_mcp_servers(codex_home.path(), &empty)?; @@ -1639,6 +1645,7 @@ bearer_token = "secret" ("ALPHA_VAR".to_string(), "1".to_string()), ])), }, + enabled: true, startup_timeout_sec: None, tool_timeout_sec: None, }, @@ -1689,6 +1696,7 @@ ZIG_VAR = "3" url: "https://example.com/mcp".to_string(), bearer_token_env_var: Some("MCP_TOKEN".to_string()), }, + enabled: true, startup_timeout_sec: Some(Duration::from_secs(2)), tool_timeout_sec: None, }, @@ -1728,6 +1736,7 @@ startup_timeout_sec = 2.0 url: "https://example.com/mcp".to_string(), bearer_token_env_var: None, }, + enabled: true, startup_timeout_sec: None, tool_timeout_sec: None, }, @@ -1758,6 +1767,40 @@ url = "https://example.com/mcp" Ok(()) } + #[tokio::test] + async fn write_global_mcp_servers_serializes_disabled_flag() -> anyhow::Result<()> { + let codex_home = TempDir::new()?; + + let servers = BTreeMap::from([( + "docs".to_string(), + McpServerConfig { + transport: McpServerTransportConfig::Stdio { + command: "docs-server".to_string(), + args: Vec::new(), + env: None, + }, + enabled: false, + startup_timeout_sec: None, + tool_timeout_sec: None, + }, + )]); + + write_global_mcp_servers(codex_home.path(), &servers)?; + + let config_path = codex_home.path().join(CONFIG_TOML_FILE); + let serialized = std::fs::read_to_string(&config_path)?; + assert!( + serialized.contains("enabled = false"), + "serialized config missing disabled flag:\n{serialized}" + ); + + let loaded = load_global_mcp_servers(codex_home.path()).await?; + let docs = loaded.get("docs").expect("docs entry"); + assert!(!docs.enabled); + + Ok(()) + } + #[tokio::test] async fn persist_model_selection_updates_defaults() -> anyhow::Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/core/src/config_types.rs b/codex-rs/core/src/config_types.rs index 8940ac5c08..0ef9248511 100644 --- a/codex-rs/core/src/config_types.rs +++ b/codex-rs/core/src/config_types.rs @@ -20,6 +20,10 @@ pub struct McpServerConfig { #[serde(flatten)] pub transport: McpServerTransportConfig, + /// When `false`, Codex skips initializing this MCP server. + #[serde(default = "default_enabled")] + pub enabled: bool, + /// Startup timeout in seconds for initializing MCP server & initially listing tools. #[serde( default, @@ -56,6 +60,8 @@ impl<'de> Deserialize<'de> for McpServerConfig { startup_timeout_ms: Option, #[serde(default, with = "option_duration_secs")] tool_timeout_sec: Option, + #[serde(default)] + enabled: Option, } let raw = RawMcpServerConfig::deserialize(deserializer)?; @@ -127,10 +133,15 @@ impl<'de> Deserialize<'de> for McpServerConfig { transport, startup_timeout_sec, tool_timeout_sec: raw.tool_timeout_sec, + enabled: raw.enabled.unwrap_or_else(default_enabled), }) } } +const fn default_enabled() -> bool { + true +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(untagged, deny_unknown_fields, rename_all = "snake_case")] pub enum McpServerTransportConfig { @@ -460,6 +471,7 @@ mod tests { env: None } ); + assert!(cfg.enabled); } #[test] @@ -480,6 +492,7 @@ mod tests { env: None } ); + assert!(cfg.enabled); } #[test] @@ -501,6 +514,20 @@ mod tests { env: Some(HashMap::from([("FOO".to_string(), "BAR".to_string())])) } ); + assert!(cfg.enabled); + } + + #[test] + fn deserialize_disabled_server_config() { + let cfg: McpServerConfig = toml::from_str( + r#" + command = "echo" + enabled = false + "#, + ) + .expect("should deserialize disabled server config"); + + assert!(!cfg.enabled); } #[test] @@ -519,6 +546,7 @@ mod tests { bearer_token_env_var: None } ); + assert!(cfg.enabled); } #[test] @@ -538,6 +566,7 @@ mod tests { bearer_token_env_var: Some("GITHUB_TOKEN".to_string()) } ); + assert!(cfg.enabled); } #[test] diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index 0c2fdc6301..768c6b01a6 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -207,6 +207,10 @@ impl McpConnectionManager { continue; } + if !cfg.enabled { + continue; + } + let startup_timeout = cfg.startup_timeout_sec.unwrap_or(DEFAULT_STARTUP_TIMEOUT); let tool_timeout = cfg.tool_timeout_sec.unwrap_or(DEFAULT_TOOL_TIMEOUT); diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index a8a5d3afbf..e111cebcb7 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -86,6 +86,7 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> { expected_env_value.to_string(), )])), }, + enabled: true, startup_timeout_sec: Some(Duration::from_secs(10)), tool_timeout_sec: None, }, @@ -234,6 +235,7 @@ async fn streamable_http_tool_call_round_trip() -> anyhow::Result<()> { url: server_url, bearer_token_env_var: None, }, + enabled: true, startup_timeout_sec: Some(Duration::from_secs(10)), tool_timeout_sec: None, }, @@ -414,6 +416,7 @@ async fn streamable_http_with_oauth_round_trip() -> anyhow::Result<()> { url: server_url, bearer_token_env_var: None, }, + enabled: true, startup_timeout_sec: Some(Duration::from_secs(10)), tool_timeout_sec: None, }, diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 7c4d18e1a3..dbd4a72846 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -874,6 +874,12 @@ pub(crate) fn new_mcp_tools_output( names.sort(); lines.push(vec![" • Server: ".into(), server.clone().into()].into()); + let status_line = if cfg.enabled { + vec![" • Status: ".into(), "enabled".green()].into() + } else { + vec![" • Status: ".into(), "disabled".red()].into() + }; + lines.push(status_line); match &cfg.transport { McpServerTransportConfig::Stdio { command, args, env } => { @@ -899,7 +905,9 @@ pub(crate) fn new_mcp_tools_output( } } - if names.is_empty() { + if !cfg.enabled { + lines.push(vec![" • Tools: ".into(), "(disabled)".red()].into()); + } else if names.is_empty() { lines.push(" • Tools: (none)".into()); } else { lines.push(vec![" • Tools: ".into(), names.join(", ").into()].into()); diff --git a/docs/config.md b/docs/config.md index aa45acc8dd..fba8a3a21d 100644 --- a/docs/config.md +++ b/docs/config.md @@ -384,6 +384,8 @@ For oauth login, you must enable `experimental_use_rmcp_client = true` and then startup_timeout_sec = 20 # Optional: override the default 60s per-tool timeout tool_timeout_sec = 30 +# Optional: disable a server without removing it +enabled = false ``` ### Experimental RMCP client @@ -787,9 +789,12 @@ notifications = [ "agent-turn-complete", "approval-requested" ] | `disable_response_storage` | boolean | Required for ZDR orgs. | | `notify` | array | External program for notifications. | | `instructions` | string | Currently ignored; use `experimental_instructions_file` or `AGENTS.md`. | -| `mcp_servers..command` | string | MCP server launcher command. | -| `mcp_servers..args` | array | MCP server args. | -| `mcp_servers..env` | map | MCP server env vars. | +| `mcp_servers..command` | string | MCP server launcher command (stdio servers only). | +| `mcp_servers..args` | array | MCP server args (stdio servers only). | +| `mcp_servers..env` | map | MCP server env vars (stdio servers only). | +| `mcp_servers..url` | string | MCP server url (streamable http servers only). | +| `mcp_servers..bearer_token_env_var` | string | environment variable containing a bearer token to use for auth (streamable http servers only). | +| `mcp_servers..enabled` | boolean | When false, Codex skips starting the server (default: true). | | `mcp_servers..startup_timeout_sec` | number | Startup timeout in seconds (default: 10). Timeout is applied both for initializing MCP server and initially listing tools. | | `mcp_servers..tool_timeout_sec` | number | Per-tool timeout in seconds (default: 60). Accepts fractional values; omit to use the default. | | `model_providers..name` | string | Display name. | From c89229db97ae06c06deb463f0012ce6fc6b126dd Mon Sep 17 00:00:00 2001 From: dedrisian-oai Date: Wed, 8 Oct 2025 14:32:54 -0700 Subject: [PATCH 04/32] Make context line permanent (#4699) https://github.com/user-attachments/assets/f72c64de-8d6a-45b6-93df-f3a68038067f --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 14 +++--- codex-rs/tui/src/bottom_pane/footer.rs | 49 ++++++++----------- ...mposer__tests__backspace_after_pastes.snap | 2 +- ...tom_pane__chat_composer__tests__empty.snap | 3 +- ...__tests__footer_mode_ctrl_c_interrupt.snap | 1 - ...poser__tests__footer_mode_ctrl_c_quit.snap | 1 - ...sts__footer_mode_ctrl_c_then_esc_hint.snap | 1 - ...tests__footer_mode_esc_hint_backtrack.snap | 1 - ...ts__footer_mode_esc_hint_from_overlay.snap | 1 - ...ests__footer_mode_hidden_while_typing.snap | 1 + ...r_mode_overlay_then_external_esc_hint.snap | 1 - ...tom_pane__chat_composer__tests__large.snap | 2 +- ...chat_composer__tests__multiple_pastes.snap | 2 +- ...tom_pane__chat_composer__tests__small.snap | 2 +- ...ooter__tests__footer_ctrl_c_quit_idle.snap | 1 - ...er__tests__footer_ctrl_c_quit_running.snap | 1 - ...__footer__tests__footer_esc_hint_idle.snap | 1 - ...footer__tests__footer_esc_hint_primed.snap | 1 - ...sts__footer_shortcuts_context_running.snap | 2 +- ...oter__tests__footer_shortcuts_default.snap | 3 +- ...er_fill_height_without_bottom_padding.snap | 2 +- ...exec_and_status_layout_vt100_snapshot.snap | 1 + ...atwidget__tests__status_widget_active.snap | 2 +- 23 files changed, 39 insertions(+), 56 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 2574ded461..7aa6e66958 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -149,7 +149,7 @@ impl ChatComposer { paste_burst: PasteBurst::default(), disable_paste_burst: false, custom_prompts: Vec::new(), - footer_mode: FooterMode::ShortcutPrompt, + footer_mode: FooterMode::ShortcutSummary, footer_hint_override: None, context_window_percent: None, }; @@ -1345,8 +1345,8 @@ impl ChatComposer { FooterMode::EscHint => FooterMode::EscHint, FooterMode::ShortcutOverlay => FooterMode::ShortcutOverlay, FooterMode::CtrlCReminder => FooterMode::CtrlCReminder, - FooterMode::ShortcutPrompt if self.ctrl_c_quit_hint => FooterMode::CtrlCReminder, - FooterMode::ShortcutPrompt if !self.is_empty() => FooterMode::Empty, + FooterMode::ShortcutSummary if self.ctrl_c_quit_hint => FooterMode::CtrlCReminder, + FooterMode::ShortcutSummary if !self.is_empty() => FooterMode::ContextOnly, other => other, } } @@ -1779,11 +1779,11 @@ mod tests { // Toggle back to prompt mode so subsequent typing captures characters. let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE)); - assert_eq!(composer.footer_mode, FooterMode::ShortcutPrompt); + assert_eq!(composer.footer_mode, FooterMode::ShortcutSummary); type_chars_humanlike(&mut composer, &['h']); assert_eq!(composer.textarea.text(), "h"); - assert_eq!(composer.footer_mode(), FooterMode::Empty); + assert_eq!(composer.footer_mode(), FooterMode::ContextOnly); let (result, needs_redraw) = composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE)); @@ -1792,8 +1792,8 @@ mod tests { std::thread::sleep(ChatComposer::recommended_paste_flush_delay()); let _ = composer.flush_paste_burst_if_due(); assert_eq!(composer.textarea.text(), "h?"); - assert_eq!(composer.footer_mode, FooterMode::ShortcutPrompt); - assert_eq!(composer.footer_mode(), FooterMode::Empty); + assert_eq!(composer.footer_mode, FooterMode::ShortcutSummary); + assert_eq!(composer.footer_mode(), FooterMode::ContextOnly); } #[test] diff --git a/codex-rs/tui/src/bottom_pane/footer.rs b/codex-rs/tui/src/bottom_pane/footer.rs index b4c5617ddf..6e92a0ce68 100644 --- a/codex-rs/tui/src/bottom_pane/footer.rs +++ b/codex-rs/tui/src/bottom_pane/footer.rs @@ -23,10 +23,10 @@ pub(crate) struct FooterProps { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum FooterMode { CtrlCReminder, - ShortcutPrompt, + ShortcutSummary, ShortcutOverlay, EscHint, - Empty, + ContextOnly, } pub(crate) fn toggle_shortcut_mode(current: FooterMode, ctrl_c_hint: bool) -> FooterMode { @@ -35,7 +35,7 @@ pub(crate) fn toggle_shortcut_mode(current: FooterMode, ctrl_c_hint: bool) -> Fo } match current { - FooterMode::ShortcutOverlay | FooterMode::CtrlCReminder => FooterMode::ShortcutPrompt, + FooterMode::ShortcutOverlay | FooterMode::CtrlCReminder => FooterMode::ShortcutSummary, _ => FooterMode::ShortcutOverlay, } } @@ -53,7 +53,7 @@ pub(crate) fn reset_mode_after_activity(current: FooterMode) -> FooterMode { FooterMode::EscHint | FooterMode::ShortcutOverlay | FooterMode::CtrlCReminder - | FooterMode::Empty => FooterMode::ShortcutPrompt, + | FooterMode::ContextOnly => FooterMode::ShortcutSummary, other => other, } } @@ -72,26 +72,29 @@ pub(crate) fn render_footer(area: Rect, buf: &mut Buffer, props: FooterProps) { } fn footer_lines(props: FooterProps) -> Vec> { + // Show the context indicator on the left, appended after the primary hint + // (e.g., "? for shortcuts"). Keep it visible even when typing (i.e., when + // the shortcut hint is hidden). Hide it only for the multi-line + // ShortcutOverlay. match props.mode { FooterMode::CtrlCReminder => vec![ctrl_c_reminder_line(CtrlCReminderState { is_task_running: props.is_task_running, })], - FooterMode::ShortcutPrompt => { - if props.is_task_running { - vec![context_window_line(props.context_window_percent)] - } else { - vec![Line::from(vec![ - key_hint::plain(KeyCode::Char('?')).into(), - " for shortcuts".dim(), - ])] - } + FooterMode::ShortcutSummary => { + let mut line = context_window_line(props.context_window_percent); + line.push_span(" · ".dim()); + line.extend(vec![ + key_hint::plain(KeyCode::Char('?')).into(), + " for shortcuts".dim(), + ]); + vec![line] } FooterMode::ShortcutOverlay => shortcut_overlay_lines(ShortcutsState { use_shift_enter_hint: props.use_shift_enter_hint, esc_backtrack_hint: props.esc_backtrack_hint, }), FooterMode::EscHint => vec![esc_hint_line(props.esc_backtrack_hint)], - FooterMode::Empty => Vec::new(), + FooterMode::ContextOnly => vec![context_window_line(props.context_window_percent)], } } @@ -219,18 +222,8 @@ fn build_columns(entries: Vec>) -> Vec> { } fn context_window_line(percent: Option) -> Line<'static> { - let mut spans: Vec> = Vec::new(); - match percent { - Some(percent) => { - spans.push(format!("{percent}%").dim()); - spans.push(" context left".dim()); - } - None => { - spans.push(key_hint::plain(KeyCode::Char('?')).into()); - spans.push(" for shortcuts".dim()); - } - } - Line::from(spans) + let percent = percent.unwrap_or(100); + Line::from(vec![Span::from(format!("{percent}% context left")).dim()]) } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -402,7 +395,7 @@ mod tests { snapshot_footer( "footer_shortcuts_default", FooterProps { - mode: FooterMode::ShortcutPrompt, + mode: FooterMode::ShortcutSummary, esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: false, @@ -468,7 +461,7 @@ mod tests { snapshot_footer( "footer_shortcuts_context_running", FooterProps { - mode: FooterMode::ShortcutPrompt, + mode: FooterMode::ShortcutSummary, esc_backtrack_hint: false, use_shift_enter_hint: false, is_task_running: true, diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap index adb764b6c4..e4cc9ffefd 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap @@ -11,4 +11,4 @@ expression: terminal.backend() " " " " " " -" " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap index db92427864..53e0aee4cf 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 1938 expression: terminal.backend() --- " " @@ -12,4 +11,4 @@ expression: terminal.backend() " " " " " " -" ? for shortcuts " +" 100% context left · ? for shortcuts " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_interrupt.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_interrupt.snap index a805fbf9f4..49ffb0d4c8 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_interrupt.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_interrupt.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 1497 expression: terminal.backend() --- " " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_quit.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_quit.snap index 750ba10192..7ecc5bba71 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_quit.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_quit.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 1497 expression: terminal.backend() --- " " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_then_esc_hint.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_then_esc_hint.snap index 8c2d2bfd39..9cad17b864 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_then_esc_hint.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_then_esc_hint.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 1497 expression: terminal.backend() --- " " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_backtrack.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_backtrack.snap index 5ddf39e315..2fce42cc26 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_backtrack.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_backtrack.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 1497 expression: terminal.backend() --- " " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_from_overlay.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_from_overlay.snap index 8c2d2bfd39..9cad17b864 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_from_overlay.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_from_overlay.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 1497 expression: terminal.backend() --- " " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap index dfeb98d619..67e616e917 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap @@ -10,3 +10,4 @@ expression: terminal.backend() " " " " " " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_overlay_then_external_esc_hint.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_overlay_then_external_esc_hint.snap index 5ddf39e315..2fce42cc26 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_overlay_then_external_esc_hint.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_overlay_then_external_esc_hint.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/chat_composer.rs -assertion_line: 1497 expression: terminal.backend() --- " " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap index 4237a17ae0..6b018021ec 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap @@ -11,4 +11,4 @@ expression: terminal.backend() " " " " " " -" " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap index 3edfc2ce22..40098faee0 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap @@ -11,4 +11,4 @@ expression: terminal.backend() " " " " " " -" " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap index 402740b8fa..498ed76936 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap @@ -11,4 +11,4 @@ expression: terminal.backend() " " " " " " -" " +" 100% context left " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_idle.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_idle.snap index 817adb66d9..31a1b743b8 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_idle.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_idle.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/footer.rs -assertion_line: 389 expression: terminal.backend() --- " ctrl + c again to quit " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_running.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_running.snap index 50bf9b622d..9979372a1b 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_running.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_running.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/footer.rs -assertion_line: 389 expression: terminal.backend() --- " ctrl + c again to interrupt " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_idle.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_idle.snap index 172432a38e..b2333b025f 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_idle.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_idle.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/footer.rs -assertion_line: 389 expression: terminal.backend() --- " esc esc to edit previous message " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_primed.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_primed.snap index 69d79d5327..20f9b178b4 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_primed.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_primed.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/footer.rs -assertion_line: 389 expression: terminal.backend() --- " esc again to edit previous message " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap index 77b3796c20..d05ac90a91 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap @@ -2,4 +2,4 @@ source: tui/src/bottom_pane/footer.rs expression: terminal.backend() --- -" 72% context left " +" 72% context left · ? for shortcuts " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap index b2de215488..c95a5dc0b3 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap @@ -1,6 +1,5 @@ --- source: tui/src/bottom_pane/footer.rs -assertion_line: 389 expression: terminal.backend() --- -" ? for shortcuts " +" 100% context left · ? for shortcuts " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap index ae96888f56..ecf9258330 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap @@ -8,4 +8,4 @@ expression: "render_snapshot(&pane, area)" › Ask Codex to do anything - ? for shortcuts + 100% context left · ? for sh diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap index b83bf8a91a..f913ce0898 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap @@ -13,3 +13,4 @@ expression: term.backend().vt100().screen().contents() › Summarize recent commits + 100% context left diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap index e288807b00..9fbebfb500 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap @@ -9,4 +9,4 @@ expression: terminal.backend() " " "› Ask Codex to do anything " " " -" ? for shortcuts " +" 100% context left · ? for shortcuts " From 3c5e12e2a438d12e38333eaf2d2da6e68af86a89 Mon Sep 17 00:00:00 2001 From: Gabriel Peal Date: Wed, 8 Oct 2025 14:37:57 -0700 Subject: [PATCH 05/32] [MCP] Add auth status to MCP servers (#4918) This adds a queryable auth status for MCP servers which is useful: 1. To determine whether a streamable HTTP server supports auth or not based on whether or not it supports RFC 8414-3.2 2. Allow us to build a better user experience on top of MCP status --- codex-rs/Cargo.lock | 1 + codex-rs/cli/src/mcp_cmd.rs | 82 +++++++++++----- codex-rs/cli/tests/mcp_list.rs | 5 +- codex-rs/core/src/codex.rs | 11 ++- codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/mcp/auth.rs | 58 +++++++++++ codex-rs/core/src/mcp/mod.rs | 1 + codex-rs/protocol/src/protocol.rs | 24 +++++ codex-rs/rmcp-client/Cargo.toml | 1 + codex-rs/rmcp-client/src/auth_status.rs | 125 ++++++++++++++++++++++++ codex-rs/rmcp-client/src/lib.rs | 3 + codex-rs/rmcp-client/src/oauth.rs | 8 ++ codex-rs/tui/src/chatwidget.rs | 6 +- codex-rs/tui/src/history_cell.rs | 9 +- 14 files changed, 307 insertions(+), 28 deletions(-) create mode 100644 codex-rs/core/src/mcp/auth.rs create mode 100644 codex-rs/core/src/mcp/mod.rs create mode 100644 codex-rs/rmcp-client/src/auth_status.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 8c992a6f8e..0c12880c94 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1352,6 +1352,7 @@ version = "0.0.0" dependencies = [ "anyhow", "axum", + "codex-protocol", "dirs", "futures", "keyring", diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 964b69480c..0a5be0dc23 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -13,6 +13,8 @@ use codex_core::config::load_global_mcp_servers; use codex_core::config::write_global_mcp_servers; use codex_core::config_types::McpServerConfig; use codex_core::config_types::McpServerTransportConfig; +use codex_core::mcp::auth::compute_auth_statuses; +use codex_core::protocol::McpAuthStatus; use codex_rmcp_client::delete_oauth_tokens; use codex_rmcp_client::perform_oauth_login; @@ -340,11 +342,20 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> let mut entries: Vec<_> = config.mcp_servers.iter().collect(); entries.sort_by(|(a, _), (b, _)| a.cmp(b)); + let auth_statuses = compute_auth_statuses( + config.mcp_servers.iter(), + config.mcp_oauth_credentials_store_mode, + ) + .await; if list_args.json { let json_entries: Vec<_> = entries .into_iter() .map(|(name, cfg)| { + let auth_status = auth_statuses + .get(name.as_str()) + .copied() + .unwrap_or(McpAuthStatus::Unsupported); let transport = match &cfg.transport { McpServerTransportConfig::Stdio { command, args, env } => serde_json::json!({ "type": "stdio", @@ -374,6 +385,7 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> "tool_timeout_sec": cfg .tool_timeout_sec .map(|timeout| timeout.as_secs_f64()), + "auth_status": auth_status, }) }) .collect(); @@ -387,8 +399,8 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> return Ok(()); } - let mut stdio_rows: Vec<[String; 5]> = Vec::new(); - let mut http_rows: Vec<[String; 4]> = Vec::new(); + let mut stdio_rows: Vec<[String; 6]> = Vec::new(); + let mut http_rows: Vec<[String; 5]> = Vec::new(); for (name, cfg) in entries { match &cfg.transport { @@ -416,12 +428,18 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> } else { "disabled".to_string() }; + let auth_status = auth_statuses + .get(name.as_str()) + .copied() + .unwrap_or(McpAuthStatus::Unsupported) + .to_string(); stdio_rows.push([ name.clone(), command.clone(), args_display, env_display, status, + auth_status, ]); } McpServerTransportConfig::StreamableHttp { @@ -433,11 +451,17 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> } else { "disabled".to_string() }; + let auth_status = auth_statuses + .get(name.as_str()) + .copied() + .unwrap_or(McpAuthStatus::Unsupported) + .to_string(); http_rows.push([ name.clone(), url.clone(), bearer_token_env_var.clone().unwrap_or("-".to_string()), status, + auth_status, ]); } } @@ -450,6 +474,7 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> "Args".len(), "Env".len(), "Status".len(), + "Auth".len(), ]; for row in &stdio_rows { for (i, cell) in row.iter().enumerate() { @@ -458,32 +483,36 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> } println!( - "{: "Url".len(), "Bearer Token Env Var".len(), "Status".len(), + "Auth".len(), ]; for row in &http_rows { for (i, cell) in row.iter().enumerate() { @@ -506,28 +536,32 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> } println!( - "{: Result<()> { assert!(stdout.contains("docs-server")); assert!(stdout.contains("TOKEN=secret")); assert!(stdout.contains("Status")); + assert!(stdout.contains("Auth")); assert!(stdout.contains("enabled")); + assert!(stdout.contains("Unsupported")); let mut list_json_cmd = codex_command(codex_home.path())?; let json_output = list_json_cmd.args(["mcp", "list", "--json"]).output()?; @@ -80,7 +82,8 @@ fn list_and_get_render_expected_output() -> Result<()> { } }, "startup_timeout_sec": null, - "tool_timeout_sec": null + "tool_timeout_sec": null, + "auth_status": "unsupported" } ] ) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 356e25ed3a..cae47cb322 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -57,6 +57,7 @@ use crate::exec_command::WriteStdinParams; use crate::executor::Executor; use crate::executor::ExecutorConfig; use crate::executor::normalize_exec_result; +use crate::mcp::auth::compute_auth_statuses; use crate::mcp_connection_manager::McpConnectionManager; use crate::model_family::find_family_for_model; use crate::openai_model_info::get_model_info; @@ -1403,10 +1404,18 @@ async fn submission_loop( // This is a cheap lookup from the connection manager's cache. let tools = sess.services.mcp_connection_manager.list_all_tools(); + let auth_statuses = compute_auth_statuses( + config.mcp_servers.iter(), + config.mcp_oauth_credentials_store_mode, + ) + .await; let event = Event { id: sub_id, msg: EventMsg::McpListToolsResponse( - crate::protocol::McpListToolsResponseEvent { tools }, + crate::protocol::McpListToolsResponseEvent { + tools, + auth_statuses, + }, ), }; sess.send_event(event).await; diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 08baa2bdc6..201d8feb4d 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -32,6 +32,7 @@ pub mod executor; mod flags; pub mod git_info; pub mod landlock; +pub mod mcp; mod mcp_connection_manager; mod mcp_tool_call; mod message_history; diff --git a/codex-rs/core/src/mcp/auth.rs b/codex-rs/core/src/mcp/auth.rs new file mode 100644 index 0000000000..dbb9db804f --- /dev/null +++ b/codex-rs/core/src/mcp/auth.rs @@ -0,0 +1,58 @@ +use std::collections::HashMap; + +use anyhow::Result; +use codex_protocol::protocol::McpAuthStatus; +use codex_rmcp_client::OAuthCredentialsStoreMode; +use codex_rmcp_client::determine_streamable_http_auth_status; +use futures::future::join_all; +use tracing::warn; + +use crate::config_types::McpServerConfig; +use crate::config_types::McpServerTransportConfig; + +pub async fn compute_auth_statuses<'a, I>( + servers: I, + store_mode: OAuthCredentialsStoreMode, +) -> HashMap +where + I: IntoIterator, +{ + let futures = servers.into_iter().map(|(name, config)| { + let name = name.clone(); + let config = config.clone(); + async move { + let status = match compute_auth_status(&name, &config, store_mode).await { + Ok(status) => status, + Err(error) => { + warn!("failed to determine auth status for MCP server `{name}`: {error:?}"); + McpAuthStatus::Unsupported + } + }; + (name, status) + } + }); + + join_all(futures).await.into_iter().collect() +} + +async fn compute_auth_status( + server_name: &str, + config: &McpServerConfig, + store_mode: OAuthCredentialsStoreMode, +) -> Result { + match &config.transport { + McpServerTransportConfig::Stdio { .. } => Ok(McpAuthStatus::Unsupported), + McpServerTransportConfig::StreamableHttp { + url, + bearer_token_env_var, + } => { + determine_streamable_http_auth_status( + server_name, + url, + bearer_token_env_var.as_deref(), + store_mode, + ) + .await + } + } +} diff --git a/codex-rs/core/src/mcp/mod.rs b/codex-rs/core/src/mcp/mod.rs new file mode 100644 index 0000000000..0e4a05d597 --- /dev/null +++ b/codex-rs/core/src/mcp/mod.rs @@ -0,0 +1 @@ +pub mod auth; diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 3b6520be67..1ae32e5122 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -1243,6 +1243,30 @@ pub struct GetHistoryEntryResponseEvent { pub struct McpListToolsResponseEvent { /// Fully qualified tool name -> tool definition. pub tools: std::collections::HashMap, + /// Authentication status for each configured MCP server. + pub auth_statuses: std::collections::HashMap, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(rename_all = "snake_case")] +#[ts(rename_all = "snake_case")] +pub enum McpAuthStatus { + Unsupported, + NotLoggedIn, + BearerToken, + OAuth, +} + +impl fmt::Display for McpAuthStatus { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let text = match self { + McpAuthStatus::Unsupported => "Unsupported", + McpAuthStatus::NotLoggedIn => "Not logged in", + McpAuthStatus::BearerToken => "Bearer token", + McpAuthStatus::OAuth => "OAuth", + }; + f.write_str(text) + } } /// Response payload for `Op::ListCustomPrompts`. diff --git a/codex-rs/rmcp-client/Cargo.toml b/codex-rs/rmcp-client/Cargo.toml index ddbc70563e..99a609b339 100644 --- a/codex-rs/rmcp-client/Cargo.toml +++ b/codex-rs/rmcp-client/Cargo.toml @@ -12,6 +12,7 @@ axum = { workspace = true, default-features = false, features = [ "http1", "tokio", ] } +codex-protocol = { workspace = true } keyring = { workspace = true, features = [ "apple-native", "crypto-rust", diff --git a/codex-rs/rmcp-client/src/auth_status.rs b/codex-rs/rmcp-client/src/auth_status.rs new file mode 100644 index 0000000000..0281c0ffe8 --- /dev/null +++ b/codex-rs/rmcp-client/src/auth_status.rs @@ -0,0 +1,125 @@ +use std::time::Duration; + +use anyhow::Error; +use anyhow::Result; +use codex_protocol::protocol::McpAuthStatus; +use reqwest::Client; +use reqwest::StatusCode; +use reqwest::Url; +use serde::Deserialize; +use tracing::debug; + +use crate::OAuthCredentialsStoreMode; +use crate::oauth::has_oauth_tokens; + +const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(5); +const OAUTH_DISCOVERY_HEADER: &str = "MCP-Protocol-Version"; +const OAUTH_DISCOVERY_VERSION: &str = "2024-11-05"; + +/// Determine the authentication status for a streamable HTTP MCP server. +pub async fn determine_streamable_http_auth_status( + server_name: &str, + url: &str, + bearer_token_env_var: Option<&str>, + store_mode: OAuthCredentialsStoreMode, +) -> Result { + if bearer_token_env_var.is_some() { + return Ok(McpAuthStatus::BearerToken); + } + + if has_oauth_tokens(server_name, url, store_mode)? { + return Ok(McpAuthStatus::OAuth); + } + + match supports_oauth_login(url).await { + Ok(true) => Ok(McpAuthStatus::NotLoggedIn), + Ok(false) => Ok(McpAuthStatus::Unsupported), + Err(error) => { + debug!( + "failed to detect OAuth support for MCP server `{server_name}` at {url}: {error:?}" + ); + Ok(McpAuthStatus::Unsupported) + } + } +} + +/// Attempt to determine whether a streamable HTTP MCP server advertises OAuth login. +async fn supports_oauth_login(url: &str) -> Result { + let base_url = Url::parse(url)?; + let client = Client::builder().timeout(DISCOVERY_TIMEOUT).build()?; + + let mut last_error: Option = None; + for candidate_path in discovery_paths(base_url.path()) { + let mut discovery_url = base_url.clone(); + discovery_url.set_path(&candidate_path); + + let response = match client + .get(discovery_url.clone()) + .header(OAUTH_DISCOVERY_HEADER, OAUTH_DISCOVERY_VERSION) + .send() + .await + { + Ok(response) => response, + Err(err) => { + last_error = Some(err.into()); + continue; + } + }; + + if response.status() != StatusCode::OK { + continue; + } + + let metadata = match response.json::().await { + Ok(metadata) => metadata, + Err(err) => { + last_error = Some(err.into()); + continue; + } + }; + + if metadata.authorization_endpoint.is_some() && metadata.token_endpoint.is_some() { + return Ok(true); + } + } + + if let Some(err) = last_error { + debug!("OAuth discovery requests failed for {url}: {err:?}"); + } + + Ok(false) +} + +#[derive(Debug, Deserialize)] +struct OAuthDiscoveryMetadata { + #[serde(default)] + authorization_endpoint: Option, + #[serde(default)] + token_endpoint: Option, +} + +/// Implements RFC 8414 section 3.1 for discovering well-known oauth endpoints. +/// This is a requirement for MCP servers to support OAuth. +/// https://datatracker.ietf.org/doc/html/rfc8414#section-3.1 +/// https://github.com/modelcontextprotocol/rust-sdk/blob/main/crates/rmcp/src/transport/auth.rs#L182 +fn discovery_paths(base_path: &str) -> Vec { + let trimmed = base_path.trim_start_matches('/').trim_end_matches('/'); + let canonical = "/.well-known/oauth-authorization-server".to_string(); + + if trimmed.is_empty() { + return vec![canonical]; + } + + let mut candidates = Vec::new(); + let mut push_unique = |candidate: String| { + if !candidates.contains(&candidate) { + candidates.push(candidate); + } + }; + + push_unique(format!("{canonical}/{trimmed}")); + push_unique(format!("/{trimmed}/.well-known/oauth-authorization-server")); + push_unique(canonical); + + candidates +} diff --git a/codex-rs/rmcp-client/src/lib.rs b/codex-rs/rmcp-client/src/lib.rs index 0d15584f0f..05412da184 100644 --- a/codex-rs/rmcp-client/src/lib.rs +++ b/codex-rs/rmcp-client/src/lib.rs @@ -1,3 +1,4 @@ +mod auth_status; mod find_codex_home; mod logging_client_handler; mod oauth; @@ -5,6 +6,8 @@ mod perform_oauth_login; mod rmcp_client; mod utils; +pub use auth_status::determine_streamable_http_auth_status; +pub use codex_protocol::protocol::McpAuthStatus; pub use oauth::OAuthCredentialsStoreMode; pub use oauth::StoredOAuthTokens; pub use oauth::WrappedOAuthTokenResponse; diff --git a/codex-rs/rmcp-client/src/oauth.rs b/codex-rs/rmcp-client/src/oauth.rs index 0534847651..afa0e907b1 100644 --- a/codex-rs/rmcp-client/src/oauth.rs +++ b/codex-rs/rmcp-client/src/oauth.rs @@ -162,6 +162,14 @@ pub(crate) fn load_oauth_tokens( } } +pub(crate) fn has_oauth_tokens( + server_name: &str, + url: &str, + store_mode: OAuthCredentialsStoreMode, +) -> Result { + Ok(load_oauth_tokens(server_name, url, store_mode)?.is_some()) +} + fn load_oauth_tokens_from_keyring_with_fallback_to_file( keyring_store: &K, server_name: &str, diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 2237c678c7..973b0e3ba2 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1906,7 +1906,11 @@ impl ChatWidget { } fn on_list_mcp_tools(&mut self, ev: McpListToolsResponseEvent) { - self.add_to_history(history_cell::new_mcp_tools_output(&self.config, ev.tools)); + self.add_to_history(history_cell::new_mcp_tools_output( + &self.config, + ev.tools, + &ev.auth_statuses, + )); } fn on_list_custom_prompts(&mut self, ev: ListCustomPromptsResponseEvent) { diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index dbd4a72846..151712b6b0 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -21,6 +21,7 @@ use codex_core::config::Config; use codex_core::config_types::McpServerTransportConfig; use codex_core::config_types::ReasoningSummaryFormat; use codex_core::protocol::FileChange; +use codex_core::protocol::McpAuthStatus; use codex_core::protocol::McpInvocation; use codex_core::protocol::SessionConfiguredEvent; use codex_core::protocol_config_types::ReasoningEffort as ReasoningEffortConfig; @@ -849,7 +850,8 @@ pub(crate) fn empty_mcp_output() -> PlainHistoryCell { /// Render MCP tools grouped by connection using the fully-qualified tool names. pub(crate) fn new_mcp_tools_output( config: &Config, - tools: std::collections::HashMap, + tools: HashMap, + auth_statuses: &HashMap, ) -> PlainHistoryCell { let mut lines: Vec> = vec![ "/mcp".magenta().into(), @@ -873,6 +875,10 @@ pub(crate) fn new_mcp_tools_output( .collect(); names.sort(); + let status = auth_statuses + .get(server.as_str()) + .copied() + .unwrap_or(McpAuthStatus::Unsupported); lines.push(vec![" • Server: ".into(), server.clone().into()].into()); let status_line = if cfg.enabled { vec![" • Status: ".into(), "enabled".green()].into() @@ -880,6 +886,7 @@ pub(crate) fn new_mcp_tools_output( vec![" • Status: ".into(), "disabled".red()].into() }; lines.push(status_line); + lines.push(vec![" • Auth: ".into(), status.to_string().into()].into()); match &cfg.transport { McpServerTransportConfig::Stdio { command, args, env } => { From f4bc03d7c049aaec020d431498949dfb6523f32e Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Wed, 8 Oct 2025 14:57:32 -0700 Subject: [PATCH 06/32] tui: fix off-by-16 in terminal_palette (#4967) caught by a bad refactor in #4957 --- codex-rs/tui/src/terminal_palette.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/codex-rs/tui/src/terminal_palette.rs b/codex-rs/tui/src/terminal_palette.rs index 3f2748eb8e..05d842d5f1 100644 --- a/codex-rs/tui/src/terminal_palette.rs +++ b/codex-rs/tui/src/terminal_palette.rs @@ -11,7 +11,7 @@ pub fn best_color(target: (u8, u8, u8)) -> Color { #[allow(clippy::disallowed_methods)] Color::Rgb(r, g, b) } else if color_level.has_256 - && let Some((i, _)) = xterm_fixed_colors().enumerate().min_by(|(_, a), (_, b)| { + && let Some((i, _)) = xterm_fixed_colors().min_by(|(_, a), (_, b)| { perceptual_distance(*a, target) .partial_cmp(&perceptual_distance(*b, target)) .unwrap_or(std::cmp::Ordering::Equal) @@ -236,8 +236,8 @@ mod imp { } /// The subset of Xterm colors that are usually consistent across terminals. -pub fn xterm_fixed_colors() -> impl Iterator { - XTERM_COLORS.into_iter().skip(16) +fn xterm_fixed_colors() -> impl Iterator { + XTERM_COLORS.into_iter().enumerate().skip(16) } // Xterm colors; derived from https://ss64.com/bash/syntax-colors.html From b6165aee0c01badaf4dfd80bb409e85eb76cae52 Mon Sep 17 00:00:00 2001 From: rakesh-oai Date: Wed, 8 Oct 2025 15:29:20 -0700 Subject: [PATCH 07/32] Create alias (#4971) # External (non-OpenAI) Pull Request Requirements Before opening this Pull Request, please read the dedicated "Contributing" markdown file or your PR may be closed: https://github.com/openai/codex/blob/main/docs/contributing.md If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. --- codex-rs/cli/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index d889823298..cd43041ab0 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -157,7 +157,7 @@ struct LoginCommand { )] api_key: Option, - #[arg(long = "use-device-code")] + #[arg(long = "device-auth")] use_device_code: bool, /// EXPERIMENTAL: Use custom OAuth issuer base URL (advanced) From ec238a2c39cc2813be349f882d2d48ed46d87e0a Mon Sep 17 00:00:00 2001 From: dedrisian-oai Date: Wed, 8 Oct 2025 16:35:35 -0700 Subject: [PATCH 08/32] feat: Set chat name (#4974) Set chat name with `/name` so they appear in the codex resume page: https://github.com/user-attachments/assets/c0252bba-3a53-44c7-a740-f4690a3ad405 --- codex-rs/core/src/codex.rs | 11 ++++ codex-rs/core/src/rollout/list.rs | 64 +++++++++++++------ codex-rs/core/src/rollout/policy.rs | 1 + codex-rs/core/src/rollout/tests.rs | 12 ++++ .../src/event_processor_with_human_output.rs | 1 + codex-rs/mcp-server/src/codex_tool_runner.rs | 1 + codex-rs/protocol/src/protocol.rs | 13 ++++ codex-rs/tui/src/app.rs | 3 + codex-rs/tui/src/app_event.rs | 3 + codex-rs/tui/src/bottom_pane/mod.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 58 +++++++++++++++++ codex-rs/tui/src/resume_picker.rs | 16 ++++- codex-rs/tui/src/slash_command.rs | 4 ++ 13 files changed, 167 insertions(+), 22 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index cae47cb322..fe875b2c2f 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -88,6 +88,7 @@ use crate::protocol::ReviewDecision; use crate::protocol::ReviewOutputEvent; use crate::protocol::SandboxPolicy; use crate::protocol::SessionConfiguredEvent; +use crate::protocol::SessionRenamedEvent; use crate::protocol::StreamErrorEvent; use crate::protocol::Submission; use crate::protocol::TokenCountEvent; @@ -1507,6 +1508,16 @@ async fn submission_loop( }; sess.send_event(event).await; } + Op::SetSessionName { name } => { + // Persist a rename event and notify the client. We rely on the + // recorder's filtering to include this in the rollout. + let sub_id = sub.id.clone(); + let event = Event { + id: sub_id, + msg: EventMsg::SessionRenamed(SessionRenamedEvent { name }), + }; + sess.send_event(event).await; + } Op::Review { review_request } => { spawn_review_thread( sess.clone(), diff --git a/codex-rs/core/src/rollout/list.rs b/codex-rs/core/src/rollout/list.rs index b27b3382e3..0276a91aca 100644 --- a/codex-rs/core/src/rollout/list.rs +++ b/codex-rs/core/src/rollout/list.rs @@ -17,6 +17,7 @@ use super::SESSIONS_SUBDIR; use crate::protocol::EventMsg; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; +use codex_protocol::protocol::SessionRenamedEvent; use codex_protocol::protocol::SessionSource; /// Returned page of conversation summaries. @@ -41,6 +42,8 @@ pub struct ConversationItem { pub head: Vec, /// Last up to `TAIL_RECORD_LIMIT` JSONL response records parsed as JSON. pub tail: Vec, + /// Latest human-friendly session name, if any. + pub name: Option, /// RFC3339 timestamp string for when the session was created, if available. pub created_at: Option, /// RFC3339 timestamp string for the most recent response in the tail, if available. @@ -56,6 +59,7 @@ struct HeadTailSummary { source: Option, created_at: Option, updated_at: Option, + name: Option, } /// Hard cap to bound worst‑case work per request. @@ -222,6 +226,7 @@ async fn traverse_directories_for_paths( path, head, tail, + name: summary.name, created_at, updated_at, }); @@ -382,14 +387,21 @@ async fn read_head_and_tail( if matches!(ev, EventMsg::UserMessage(_)) { summary.saw_user_event = true; } + if let EventMsg::SessionRenamed(SessionRenamedEvent { name }) = ev { + summary.name = Some(name); + } } } } if tail_limit != 0 { - let (tail, updated_at) = read_tail_records(path, tail_limit).await?; + let (tail, updated_at, latest_name) = read_tail_records(path, tail_limit).await?; summary.tail = tail; summary.updated_at = updated_at; + // Prefer the most recent rename event discovered from the tail scan; fallback to any name seen in head. + if latest_name.is_some() { + summary.name = latest_name; + } } Ok(summary) } @@ -397,13 +409,13 @@ async fn read_head_and_tail( async fn read_tail_records( path: &Path, max_records: usize, -) -> io::Result<(Vec, Option)> { +) -> io::Result<(Vec, Option, Option)> { use std::io::SeekFrom; use tokio::io::AsyncReadExt; use tokio::io::AsyncSeekExt; if max_records == 0 { - return Ok((Vec::new(), None)); + return Ok((Vec::new(), None, None)); } const CHUNK_SIZE: usize = 8192; @@ -411,28 +423,33 @@ async fn read_tail_records( let mut file = tokio::fs::File::open(path).await?; let mut pos = file.seek(SeekFrom::End(0)).await?; if pos == 0 { - return Ok((Vec::new(), None)); + return Ok((Vec::new(), None, None)); } let mut buffer: Vec = Vec::new(); let mut latest_timestamp: Option = None; + let mut latest_name: Option = None; loop { let slice_start = match (pos > 0, buffer.iter().position(|&b| b == b'\n')) { (true, Some(idx)) => idx + 1, _ => 0, }; - let (tail, newest_ts) = collect_last_response_values(&buffer[slice_start..], max_records); + let (tail, newest_ts, name_opt) = + collect_last_response_values(&buffer[slice_start..], max_records); if latest_timestamp.is_none() { latest_timestamp = newest_ts.clone(); } + if latest_name.is_none() { + latest_name = name_opt.clone(); + } if tail.len() >= max_records || pos == 0 { - return Ok((tail, latest_timestamp.or(newest_ts))); + return Ok((tail, latest_timestamp.or(newest_ts), latest_name)); } let read_size = CHUNK_SIZE.min(pos as usize); if read_size == 0 { - return Ok((tail, latest_timestamp.or(newest_ts))); + return Ok((tail, latest_timestamp.or(newest_ts), latest_name)); } pos -= read_size as u64; file.seek(SeekFrom::Start(pos)).await?; @@ -446,16 +463,17 @@ async fn read_tail_records( fn collect_last_response_values( buffer: &[u8], max_records: usize, -) -> (Vec, Option) { +) -> (Vec, Option, Option) { use std::borrow::Cow; if buffer.is_empty() || max_records == 0 { - return (Vec::new(), None); + return (Vec::new(), None, None); } let text: Cow<'_, str> = String::from_utf8_lossy(buffer); let mut collected_rev: Vec = Vec::new(); let mut latest_timestamp: Option = None; + let mut latest_name: Option = None; for line in text.lines().rev() { let trimmed = line.trim(); if trimmed.is_empty() { @@ -464,20 +482,30 @@ fn collect_last_response_values( let parsed: serde_json::Result = serde_json::from_str(trimmed); let Ok(rollout_line) = parsed else { continue }; let RolloutLine { timestamp, item } = rollout_line; - if let RolloutItem::ResponseItem(item) = item - && let Ok(val) = serde_json::to_value(&item) - { - if latest_timestamp.is_none() { - latest_timestamp = Some(timestamp.clone()); + match item { + RolloutItem::ResponseItem(item) => { + if let Ok(val) = serde_json::to_value(&item) { + if latest_timestamp.is_none() { + latest_timestamp = Some(timestamp.clone()); + } + collected_rev.push(val); + if collected_rev.len() == max_records { + break; + } + } } - collected_rev.push(val); - if collected_rev.len() == max_records { - break; + RolloutItem::EventMsg(ev) => { + if latest_name.is_none() + && let EventMsg::SessionRenamed(SessionRenamedEvent { name }) = ev + { + latest_name = Some(name); + } } + _ => {} } } collected_rev.reverse(); - (collected_rev, latest_timestamp) + (collected_rev, latest_timestamp, latest_name) } /// Locate a recorded conversation rollout file by its UUID string using the existing diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index 8fc39e79f5..3ff25e59a8 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -39,6 +39,7 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::AgentMessage(_) | EventMsg::AgentReasoning(_) | EventMsg::AgentReasoningRawContent(_) + | EventMsg::SessionRenamed(_) | EventMsg::TokenCount(_) | EventMsg::EnteredReviewMode(_) | EventMsg::ExitedReviewMode(_) diff --git a/codex-rs/core/src/rollout/tests.rs b/codex-rs/core/src/rollout/tests.rs index b1f34e3a9c..f3e2c82fea 100644 --- a/codex-rs/core/src/rollout/tests.rs +++ b/codex-rs/core/src/rollout/tests.rs @@ -196,6 +196,7 @@ async fn test_list_conversations_latest_first() { path: p1, head: head_3, tail: Vec::new(), + name: None, created_at: Some("2025-01-03T12-00-00".into()), updated_at: Some("2025-01-03T12-00-00".into()), }, @@ -203,6 +204,7 @@ async fn test_list_conversations_latest_first() { path: p2, head: head_2, tail: Vec::new(), + name: None, created_at: Some("2025-01-02T12-00-00".into()), updated_at: Some("2025-01-02T12-00-00".into()), }, @@ -210,6 +212,7 @@ async fn test_list_conversations_latest_first() { path: p3, head: head_1, tail: Vec::new(), + name: None, created_at: Some("2025-01-01T12-00-00".into()), updated_at: Some("2025-01-01T12-00-00".into()), }, @@ -317,6 +320,7 @@ async fn test_pagination_cursor() { path: p5, head: head_5, tail: Vec::new(), + name: None, created_at: Some("2025-03-05T09-00-00".into()), updated_at: Some("2025-03-05T09-00-00".into()), }, @@ -324,6 +328,7 @@ async fn test_pagination_cursor() { path: p4, head: head_4, tail: Vec::new(), + name: None, created_at: Some("2025-03-04T09-00-00".into()), updated_at: Some("2025-03-04T09-00-00".into()), }, @@ -380,6 +385,7 @@ async fn test_pagination_cursor() { path: p3, head: head_3, tail: Vec::new(), + name: None, created_at: Some("2025-03-03T09-00-00".into()), updated_at: Some("2025-03-03T09-00-00".into()), }, @@ -387,6 +393,7 @@ async fn test_pagination_cursor() { path: p2, head: head_2, tail: Vec::new(), + name: None, created_at: Some("2025-03-02T09-00-00".into()), updated_at: Some("2025-03-02T09-00-00".into()), }, @@ -427,6 +434,7 @@ async fn test_pagination_cursor() { path: p1, head: head_1, tail: Vec::new(), + name: None, created_at: Some("2025-03-01T09-00-00".into()), updated_at: Some("2025-03-01T09-00-00".into()), }], @@ -475,6 +483,7 @@ async fn test_get_conversation_contents() { path: expected_path, head: expected_head, tail: Vec::new(), + name: None, created_at: Some(ts.into()), updated_at: Some(ts.into()), }], @@ -823,6 +832,7 @@ async fn test_stable_ordering_same_second_pagination() { path: p3, head: head(u3), tail: Vec::new(), + name: None, created_at: Some(ts.to_string()), updated_at: Some(ts.to_string()), }, @@ -830,6 +840,7 @@ async fn test_stable_ordering_same_second_pagination() { path: p2, head: head(u2), tail: Vec::new(), + name: None, created_at: Some(ts.to_string()), updated_at: Some(ts.to_string()), }, @@ -860,6 +871,7 @@ async fn test_stable_ordering_same_second_pagination() { path: p1, head: head(u1), tail: Vec::new(), + name: None, created_at: Some(ts.to_string()), updated_at: Some(ts.to_string()), }], diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index f9aa3f8598..465be95c96 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -511,6 +511,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { }, EventMsg::ShutdownComplete => return CodexStatus::Shutdown, EventMsg::ConversationPath(_) => {} + EventMsg::SessionRenamed(_) => {} EventMsg::UserMessage(_) => {} EventMsg::EnteredReviewMode(_) => {} EventMsg::ExitedReviewMode(_) => {} diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index f09dc98cbc..a5a3f4f7f6 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -279,6 +279,7 @@ async fn run_codex_tool_session_inner( | EventMsg::TurnAborted(_) | EventMsg::ConversationPath(_) | EventMsg::UserMessage(_) + | EventMsg::SessionRenamed(_) | EventMsg::ShutdownComplete | EventMsg::ViewImageToolCall(_) | EventMsg::EnteredReviewMode(_) diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 1ae32e5122..100de2c7cb 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -171,6 +171,11 @@ pub enum Op { /// to generate a summary which will be returned as an AgentMessage event. Compact, + /// Set a human-friendly name for the current session. + /// The agent will persist this to the rollout as an event so that UIs can + /// surface it when listing sessions. + SetSessionName { name: String }, + /// Request a code review from the agent. Review { review_request: ReviewRequest }, @@ -458,6 +463,9 @@ pub enum EventMsg { /// Signaled when the model begins a new reasoning summary section (e.g., a new titled block). AgentReasoningSectionBreak(AgentReasoningSectionBreakEvent), + /// Session was given a human-friendly name by the user. + SessionRenamed(SessionRenamedEvent), + /// Ack the client's configure message. SessionConfigured(SessionConfiguredEvent), @@ -895,6 +903,11 @@ pub struct WebSearchEndEvent { pub query: String, } +#[derive(Debug, Clone, Deserialize, Serialize, TS)] +pub struct SessionRenamedEvent { + pub name: String, +} + /// Response payload for `Op::GetHistory` containing the current session's /// in-memory transcript. #[derive(Debug, Clone, Deserialize, Serialize, TS)] diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index cb3dea5e60..8ff57e6aa1 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -381,6 +381,9 @@ impl App { AppEvent::OpenReviewCustomPrompt => { self.chat_widget.show_review_custom_prompt(); } + AppEvent::SetSessionName(name) => { + self.chat_widget.begin_set_session_name(name); + } AppEvent::FullScreenApprovalRequest(request) => match request { ApprovalRequest::ApplyPatch { cwd, changes, .. } => { let _ = tui.enter_alt_screen(); diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 9d79c8ae13..e0bdd03948 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -85,6 +85,9 @@ pub(crate) enum AppEvent { /// Open the custom prompt option from the review popup. OpenReviewCustomPrompt, + /// Begin setting a human-readable name for the current session. + SetSessionName(String), + /// Open the approval popup. FullScreenApprovalRequest(ApprovalRequest), } diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index db13a041cd..4eca199b32 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -25,7 +25,7 @@ pub mod custom_prompt_view; mod file_search_popup; mod footer; mod list_selection_view; -mod prompt_args; +pub mod prompt_args; pub(crate) use list_selection_view::SelectionViewParams; mod paste_burst; pub mod popup_consts; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 973b0e3ba2..8da2ca635a 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1104,6 +1104,7 @@ impl ChatWidget { return; } match cmd { + SlashCommand::Name => self.open_name_popup(), SlashCommand::New => { self.app_event_tx.send(AppEvent::NewSession); } @@ -1251,6 +1252,29 @@ impl ChatWidget { return; } + // Intercept '/name ' as a local rename command (no images allowed). + if image_paths.is_empty() + && let Some((cmd, rest)) = crate::bottom_pane::prompt_args::parse_slash_name(&text) + && cmd == "name" + { + let name = rest.trim(); + if name.is_empty() { + // Provide a brief usage hint. + self.add_to_history(history_cell::new_info_event( + "Usage: /name ".to_string(), + None, + )); + self.request_redraw(); + } else { + // Send the rename op; persistence and ack come as an event. + let name_str = name.to_string(); + self.codex_op_tx + .send(Op::SetSessionName { name: name_str }) + .unwrap_or_else(|e| tracing::error!("failed to send SetSessionName op: {e}")); + } + return; + } + self.capture_ghost_snapshot(); let mut items: Vec = Vec::new(); @@ -1443,6 +1467,13 @@ impl ChatWidget { self.app_event_tx .send(crate::app_event::AppEvent::ConversationHistory(ev)); } + EventMsg::SessionRenamed(ev) => { + self.add_to_history(history_cell::new_info_event( + format!("Named this chat: {}", ev.name), + None, + )); + self.request_redraw(); + } EventMsg::EnteredReviewMode(review_request) => { self.on_entered_review_mode(review_request) } @@ -2081,6 +2112,33 @@ impl ChatWidget { self.bottom_pane.show_view(Box::new(view)); } + pub(crate) fn open_name_popup(&mut self) { + let tx = self.app_event_tx.clone(); + let view = CustomPromptView::new( + "Name this chat".to_string(), + "Type a name and press Enter".to_string(), + None, + Box::new(move |name: String| { + let trimmed = name.trim().to_string(); + if trimmed.is_empty() { + return; + } + tx.send(AppEvent::SetSessionName(trimmed)); + }), + ); + self.bottom_pane.show_view(Box::new(view)); + } + + pub(crate) fn begin_set_session_name(&mut self, name: String) { + let trimmed = name.trim().to_string(); + if trimmed.is_empty() { + return; + } + self.codex_op_tx + .send(Op::SetSessionName { name: trimmed }) + .unwrap_or_else(|e| tracing::error!("failed to send SetSessionName op: {e}")); + } + /// Programmatically submit a user text message as if typed in the /// composer. The text will be added to conversation history and sent to /// the agent. diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index eb2a9cd4ea..1ef580ad18 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -167,6 +167,7 @@ struct PickerState { next_search_token: usize, page_loader: PageLoader, view_rows: Option, + // No additional per-path state; names are embedded in rollouts. } struct PaginationState { @@ -586,9 +587,14 @@ fn head_to_row(item: &ConversationItem) -> Row { .and_then(parse_timestamp_str) .or(created_at); - let preview = preview_from_head(&item.head) - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) + let preview = item + .name + .clone() + .or_else(|| { + preview_from_head(&item.head) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + }) .unwrap_or_else(|| String::from("(no message yet)")); Row { @@ -958,6 +964,7 @@ mod tests { path: PathBuf::from(path), head: head_with_ts_and_user_text(ts, &[preview]), tail: Vec::new(), + name: None, created_at: Some(ts.to_string()), updated_at: Some(ts.to_string()), } @@ -1020,6 +1027,7 @@ mod tests { path: PathBuf::from("/tmp/a.jsonl"), head: head_with_ts_and_user_text("2025-01-01T00:00:00Z", &["A"]), tail: Vec::new(), + name: None, created_at: Some("2025-01-01T00:00:00Z".into()), updated_at: Some("2025-01-01T00:00:00Z".into()), }; @@ -1027,6 +1035,7 @@ mod tests { path: PathBuf::from("/tmp/b.jsonl"), head: head_with_ts_and_user_text("2025-01-02T00:00:00Z", &["B"]), tail: Vec::new(), + name: None, created_at: Some("2025-01-02T00:00:00Z".into()), updated_at: Some("2025-01-02T00:00:00Z".into()), }; @@ -1055,6 +1064,7 @@ mod tests { path: PathBuf::from("/tmp/a.jsonl"), head, tail, + name: None, created_at: Some("2025-01-01T00:00:00Z".into()), updated_at: Some("2025-01-01T01:00:00Z".into()), }; diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 14604a736d..92afe24748 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -15,6 +15,7 @@ pub enum SlashCommand { Model, Approvals, Review, + Name, New, Init, Compact, @@ -33,6 +34,7 @@ impl SlashCommand { /// User-visible description shown in the popup. pub fn description(self) -> &'static str { match self { + SlashCommand::Name => "set a name for this chat", SlashCommand::New => "start a new chat during a conversation", SlashCommand::Init => "create an AGENTS.md file with instructions for Codex", SlashCommand::Compact => "summarize conversation to prevent hitting the context limit", @@ -60,6 +62,8 @@ impl SlashCommand { /// Whether this command can be run while a task is in progress. pub fn available_during_task(self) -> bool { match self { + // Naming is a local UI action; allow during tasks. + SlashCommand::Name => true, SlashCommand::New | SlashCommand::Init | SlashCommand::Compact From 43002366814cdab3c1e93cdb83e5b06ef72b4181 Mon Sep 17 00:00:00 2001 From: dedrisian-oai Date: Wed, 8 Oct 2025 17:13:49 -0700 Subject: [PATCH 09/32] revert /name for now (#4978) There was a regression where we'd read entire rollout contents if there was no /name present. --- codex-rs/core/src/codex.rs | 11 ---- codex-rs/core/src/rollout/list.rs | 64 ++++++------------- codex-rs/core/src/rollout/policy.rs | 1 - codex-rs/core/src/rollout/tests.rs | 12 ---- .../src/event_processor_with_human_output.rs | 1 - codex-rs/mcp-server/src/codex_tool_runner.rs | 1 - codex-rs/protocol/src/protocol.rs | 13 ---- codex-rs/tui/src/app.rs | 3 - codex-rs/tui/src/app_event.rs | 3 - codex-rs/tui/src/bottom_pane/mod.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 58 ----------------- codex-rs/tui/src/resume_picker.rs | 16 +---- codex-rs/tui/src/slash_command.rs | 4 -- 13 files changed, 22 insertions(+), 167 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index fe875b2c2f..cae47cb322 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -88,7 +88,6 @@ use crate::protocol::ReviewDecision; use crate::protocol::ReviewOutputEvent; use crate::protocol::SandboxPolicy; use crate::protocol::SessionConfiguredEvent; -use crate::protocol::SessionRenamedEvent; use crate::protocol::StreamErrorEvent; use crate::protocol::Submission; use crate::protocol::TokenCountEvent; @@ -1508,16 +1507,6 @@ async fn submission_loop( }; sess.send_event(event).await; } - Op::SetSessionName { name } => { - // Persist a rename event and notify the client. We rely on the - // recorder's filtering to include this in the rollout. - let sub_id = sub.id.clone(); - let event = Event { - id: sub_id, - msg: EventMsg::SessionRenamed(SessionRenamedEvent { name }), - }; - sess.send_event(event).await; - } Op::Review { review_request } => { spawn_review_thread( sess.clone(), diff --git a/codex-rs/core/src/rollout/list.rs b/codex-rs/core/src/rollout/list.rs index 0276a91aca..b27b3382e3 100644 --- a/codex-rs/core/src/rollout/list.rs +++ b/codex-rs/core/src/rollout/list.rs @@ -17,7 +17,6 @@ use super::SESSIONS_SUBDIR; use crate::protocol::EventMsg; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::RolloutLine; -use codex_protocol::protocol::SessionRenamedEvent; use codex_protocol::protocol::SessionSource; /// Returned page of conversation summaries. @@ -42,8 +41,6 @@ pub struct ConversationItem { pub head: Vec, /// Last up to `TAIL_RECORD_LIMIT` JSONL response records parsed as JSON. pub tail: Vec, - /// Latest human-friendly session name, if any. - pub name: Option, /// RFC3339 timestamp string for when the session was created, if available. pub created_at: Option, /// RFC3339 timestamp string for the most recent response in the tail, if available. @@ -59,7 +56,6 @@ struct HeadTailSummary { source: Option, created_at: Option, updated_at: Option, - name: Option, } /// Hard cap to bound worst‑case work per request. @@ -226,7 +222,6 @@ async fn traverse_directories_for_paths( path, head, tail, - name: summary.name, created_at, updated_at, }); @@ -387,21 +382,14 @@ async fn read_head_and_tail( if matches!(ev, EventMsg::UserMessage(_)) { summary.saw_user_event = true; } - if let EventMsg::SessionRenamed(SessionRenamedEvent { name }) = ev { - summary.name = Some(name); - } } } } if tail_limit != 0 { - let (tail, updated_at, latest_name) = read_tail_records(path, tail_limit).await?; + let (tail, updated_at) = read_tail_records(path, tail_limit).await?; summary.tail = tail; summary.updated_at = updated_at; - // Prefer the most recent rename event discovered from the tail scan; fallback to any name seen in head. - if latest_name.is_some() { - summary.name = latest_name; - } } Ok(summary) } @@ -409,13 +397,13 @@ async fn read_head_and_tail( async fn read_tail_records( path: &Path, max_records: usize, -) -> io::Result<(Vec, Option, Option)> { +) -> io::Result<(Vec, Option)> { use std::io::SeekFrom; use tokio::io::AsyncReadExt; use tokio::io::AsyncSeekExt; if max_records == 0 { - return Ok((Vec::new(), None, None)); + return Ok((Vec::new(), None)); } const CHUNK_SIZE: usize = 8192; @@ -423,33 +411,28 @@ async fn read_tail_records( let mut file = tokio::fs::File::open(path).await?; let mut pos = file.seek(SeekFrom::End(0)).await?; if pos == 0 { - return Ok((Vec::new(), None, None)); + return Ok((Vec::new(), None)); } let mut buffer: Vec = Vec::new(); let mut latest_timestamp: Option = None; - let mut latest_name: Option = None; loop { let slice_start = match (pos > 0, buffer.iter().position(|&b| b == b'\n')) { (true, Some(idx)) => idx + 1, _ => 0, }; - let (tail, newest_ts, name_opt) = - collect_last_response_values(&buffer[slice_start..], max_records); + let (tail, newest_ts) = collect_last_response_values(&buffer[slice_start..], max_records); if latest_timestamp.is_none() { latest_timestamp = newest_ts.clone(); } - if latest_name.is_none() { - latest_name = name_opt.clone(); - } if tail.len() >= max_records || pos == 0 { - return Ok((tail, latest_timestamp.or(newest_ts), latest_name)); + return Ok((tail, latest_timestamp.or(newest_ts))); } let read_size = CHUNK_SIZE.min(pos as usize); if read_size == 0 { - return Ok((tail, latest_timestamp.or(newest_ts), latest_name)); + return Ok((tail, latest_timestamp.or(newest_ts))); } pos -= read_size as u64; file.seek(SeekFrom::Start(pos)).await?; @@ -463,17 +446,16 @@ async fn read_tail_records( fn collect_last_response_values( buffer: &[u8], max_records: usize, -) -> (Vec, Option, Option) { +) -> (Vec, Option) { use std::borrow::Cow; if buffer.is_empty() || max_records == 0 { - return (Vec::new(), None, None); + return (Vec::new(), None); } let text: Cow<'_, str> = String::from_utf8_lossy(buffer); let mut collected_rev: Vec = Vec::new(); let mut latest_timestamp: Option = None; - let mut latest_name: Option = None; for line in text.lines().rev() { let trimmed = line.trim(); if trimmed.is_empty() { @@ -482,30 +464,20 @@ fn collect_last_response_values( let parsed: serde_json::Result = serde_json::from_str(trimmed); let Ok(rollout_line) = parsed else { continue }; let RolloutLine { timestamp, item } = rollout_line; - match item { - RolloutItem::ResponseItem(item) => { - if let Ok(val) = serde_json::to_value(&item) { - if latest_timestamp.is_none() { - latest_timestamp = Some(timestamp.clone()); - } - collected_rev.push(val); - if collected_rev.len() == max_records { - break; - } - } + if let RolloutItem::ResponseItem(item) = item + && let Ok(val) = serde_json::to_value(&item) + { + if latest_timestamp.is_none() { + latest_timestamp = Some(timestamp.clone()); } - RolloutItem::EventMsg(ev) => { - if latest_name.is_none() - && let EventMsg::SessionRenamed(SessionRenamedEvent { name }) = ev - { - latest_name = Some(name); - } + collected_rev.push(val); + if collected_rev.len() == max_records { + break; } - _ => {} } } collected_rev.reverse(); - (collected_rev, latest_timestamp, latest_name) + (collected_rev, latest_timestamp) } /// Locate a recorded conversation rollout file by its UUID string using the existing diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index 3ff25e59a8..8fc39e79f5 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -39,7 +39,6 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::AgentMessage(_) | EventMsg::AgentReasoning(_) | EventMsg::AgentReasoningRawContent(_) - | EventMsg::SessionRenamed(_) | EventMsg::TokenCount(_) | EventMsg::EnteredReviewMode(_) | EventMsg::ExitedReviewMode(_) diff --git a/codex-rs/core/src/rollout/tests.rs b/codex-rs/core/src/rollout/tests.rs index f3e2c82fea..b1f34e3a9c 100644 --- a/codex-rs/core/src/rollout/tests.rs +++ b/codex-rs/core/src/rollout/tests.rs @@ -196,7 +196,6 @@ async fn test_list_conversations_latest_first() { path: p1, head: head_3, tail: Vec::new(), - name: None, created_at: Some("2025-01-03T12-00-00".into()), updated_at: Some("2025-01-03T12-00-00".into()), }, @@ -204,7 +203,6 @@ async fn test_list_conversations_latest_first() { path: p2, head: head_2, tail: Vec::new(), - name: None, created_at: Some("2025-01-02T12-00-00".into()), updated_at: Some("2025-01-02T12-00-00".into()), }, @@ -212,7 +210,6 @@ async fn test_list_conversations_latest_first() { path: p3, head: head_1, tail: Vec::new(), - name: None, created_at: Some("2025-01-01T12-00-00".into()), updated_at: Some("2025-01-01T12-00-00".into()), }, @@ -320,7 +317,6 @@ async fn test_pagination_cursor() { path: p5, head: head_5, tail: Vec::new(), - name: None, created_at: Some("2025-03-05T09-00-00".into()), updated_at: Some("2025-03-05T09-00-00".into()), }, @@ -328,7 +324,6 @@ async fn test_pagination_cursor() { path: p4, head: head_4, tail: Vec::new(), - name: None, created_at: Some("2025-03-04T09-00-00".into()), updated_at: Some("2025-03-04T09-00-00".into()), }, @@ -385,7 +380,6 @@ async fn test_pagination_cursor() { path: p3, head: head_3, tail: Vec::new(), - name: None, created_at: Some("2025-03-03T09-00-00".into()), updated_at: Some("2025-03-03T09-00-00".into()), }, @@ -393,7 +387,6 @@ async fn test_pagination_cursor() { path: p2, head: head_2, tail: Vec::new(), - name: None, created_at: Some("2025-03-02T09-00-00".into()), updated_at: Some("2025-03-02T09-00-00".into()), }, @@ -434,7 +427,6 @@ async fn test_pagination_cursor() { path: p1, head: head_1, tail: Vec::new(), - name: None, created_at: Some("2025-03-01T09-00-00".into()), updated_at: Some("2025-03-01T09-00-00".into()), }], @@ -483,7 +475,6 @@ async fn test_get_conversation_contents() { path: expected_path, head: expected_head, tail: Vec::new(), - name: None, created_at: Some(ts.into()), updated_at: Some(ts.into()), }], @@ -832,7 +823,6 @@ async fn test_stable_ordering_same_second_pagination() { path: p3, head: head(u3), tail: Vec::new(), - name: None, created_at: Some(ts.to_string()), updated_at: Some(ts.to_string()), }, @@ -840,7 +830,6 @@ async fn test_stable_ordering_same_second_pagination() { path: p2, head: head(u2), tail: Vec::new(), - name: None, created_at: Some(ts.to_string()), updated_at: Some(ts.to_string()), }, @@ -871,7 +860,6 @@ async fn test_stable_ordering_same_second_pagination() { path: p1, head: head(u1), tail: Vec::new(), - name: None, created_at: Some(ts.to_string()), updated_at: Some(ts.to_string()), }], diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index 465be95c96..f9aa3f8598 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -511,7 +511,6 @@ impl EventProcessor for EventProcessorWithHumanOutput { }, EventMsg::ShutdownComplete => return CodexStatus::Shutdown, EventMsg::ConversationPath(_) => {} - EventMsg::SessionRenamed(_) => {} EventMsg::UserMessage(_) => {} EventMsg::EnteredReviewMode(_) => {} EventMsg::ExitedReviewMode(_) => {} diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index a5a3f4f7f6..f09dc98cbc 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -279,7 +279,6 @@ async fn run_codex_tool_session_inner( | EventMsg::TurnAborted(_) | EventMsg::ConversationPath(_) | EventMsg::UserMessage(_) - | EventMsg::SessionRenamed(_) | EventMsg::ShutdownComplete | EventMsg::ViewImageToolCall(_) | EventMsg::EnteredReviewMode(_) diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 100de2c7cb..1ae32e5122 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -171,11 +171,6 @@ pub enum Op { /// to generate a summary which will be returned as an AgentMessage event. Compact, - /// Set a human-friendly name for the current session. - /// The agent will persist this to the rollout as an event so that UIs can - /// surface it when listing sessions. - SetSessionName { name: String }, - /// Request a code review from the agent. Review { review_request: ReviewRequest }, @@ -463,9 +458,6 @@ pub enum EventMsg { /// Signaled when the model begins a new reasoning summary section (e.g., a new titled block). AgentReasoningSectionBreak(AgentReasoningSectionBreakEvent), - /// Session was given a human-friendly name by the user. - SessionRenamed(SessionRenamedEvent), - /// Ack the client's configure message. SessionConfigured(SessionConfiguredEvent), @@ -903,11 +895,6 @@ pub struct WebSearchEndEvent { pub query: String, } -#[derive(Debug, Clone, Deserialize, Serialize, TS)] -pub struct SessionRenamedEvent { - pub name: String, -} - /// Response payload for `Op::GetHistory` containing the current session's /// in-memory transcript. #[derive(Debug, Clone, Deserialize, Serialize, TS)] diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 8ff57e6aa1..cb3dea5e60 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -381,9 +381,6 @@ impl App { AppEvent::OpenReviewCustomPrompt => { self.chat_widget.show_review_custom_prompt(); } - AppEvent::SetSessionName(name) => { - self.chat_widget.begin_set_session_name(name); - } AppEvent::FullScreenApprovalRequest(request) => match request { ApprovalRequest::ApplyPatch { cwd, changes, .. } => { let _ = tui.enter_alt_screen(); diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index e0bdd03948..9d79c8ae13 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -85,9 +85,6 @@ pub(crate) enum AppEvent { /// Open the custom prompt option from the review popup. OpenReviewCustomPrompt, - /// Begin setting a human-readable name for the current session. - SetSessionName(String), - /// Open the approval popup. FullScreenApprovalRequest(ApprovalRequest), } diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 4eca199b32..db13a041cd 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -25,7 +25,7 @@ pub mod custom_prompt_view; mod file_search_popup; mod footer; mod list_selection_view; -pub mod prompt_args; +mod prompt_args; pub(crate) use list_selection_view::SelectionViewParams; mod paste_burst; pub mod popup_consts; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 8da2ca635a..973b0e3ba2 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1104,7 +1104,6 @@ impl ChatWidget { return; } match cmd { - SlashCommand::Name => self.open_name_popup(), SlashCommand::New => { self.app_event_tx.send(AppEvent::NewSession); } @@ -1252,29 +1251,6 @@ impl ChatWidget { return; } - // Intercept '/name ' as a local rename command (no images allowed). - if image_paths.is_empty() - && let Some((cmd, rest)) = crate::bottom_pane::prompt_args::parse_slash_name(&text) - && cmd == "name" - { - let name = rest.trim(); - if name.is_empty() { - // Provide a brief usage hint. - self.add_to_history(history_cell::new_info_event( - "Usage: /name ".to_string(), - None, - )); - self.request_redraw(); - } else { - // Send the rename op; persistence and ack come as an event. - let name_str = name.to_string(); - self.codex_op_tx - .send(Op::SetSessionName { name: name_str }) - .unwrap_or_else(|e| tracing::error!("failed to send SetSessionName op: {e}")); - } - return; - } - self.capture_ghost_snapshot(); let mut items: Vec = Vec::new(); @@ -1467,13 +1443,6 @@ impl ChatWidget { self.app_event_tx .send(crate::app_event::AppEvent::ConversationHistory(ev)); } - EventMsg::SessionRenamed(ev) => { - self.add_to_history(history_cell::new_info_event( - format!("Named this chat: {}", ev.name), - None, - )); - self.request_redraw(); - } EventMsg::EnteredReviewMode(review_request) => { self.on_entered_review_mode(review_request) } @@ -2112,33 +2081,6 @@ impl ChatWidget { self.bottom_pane.show_view(Box::new(view)); } - pub(crate) fn open_name_popup(&mut self) { - let tx = self.app_event_tx.clone(); - let view = CustomPromptView::new( - "Name this chat".to_string(), - "Type a name and press Enter".to_string(), - None, - Box::new(move |name: String| { - let trimmed = name.trim().to_string(); - if trimmed.is_empty() { - return; - } - tx.send(AppEvent::SetSessionName(trimmed)); - }), - ); - self.bottom_pane.show_view(Box::new(view)); - } - - pub(crate) fn begin_set_session_name(&mut self, name: String) { - let trimmed = name.trim().to_string(); - if trimmed.is_empty() { - return; - } - self.codex_op_tx - .send(Op::SetSessionName { name: trimmed }) - .unwrap_or_else(|e| tracing::error!("failed to send SetSessionName op: {e}")); - } - /// Programmatically submit a user text message as if typed in the /// composer. The text will be added to conversation history and sent to /// the agent. diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 1ef580ad18..eb2a9cd4ea 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -167,7 +167,6 @@ struct PickerState { next_search_token: usize, page_loader: PageLoader, view_rows: Option, - // No additional per-path state; names are embedded in rollouts. } struct PaginationState { @@ -587,14 +586,9 @@ fn head_to_row(item: &ConversationItem) -> Row { .and_then(parse_timestamp_str) .or(created_at); - let preview = item - .name - .clone() - .or_else(|| { - preview_from_head(&item.head) - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) - }) + let preview = preview_from_head(&item.head) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) .unwrap_or_else(|| String::from("(no message yet)")); Row { @@ -964,7 +958,6 @@ mod tests { path: PathBuf::from(path), head: head_with_ts_and_user_text(ts, &[preview]), tail: Vec::new(), - name: None, created_at: Some(ts.to_string()), updated_at: Some(ts.to_string()), } @@ -1027,7 +1020,6 @@ mod tests { path: PathBuf::from("/tmp/a.jsonl"), head: head_with_ts_and_user_text("2025-01-01T00:00:00Z", &["A"]), tail: Vec::new(), - name: None, created_at: Some("2025-01-01T00:00:00Z".into()), updated_at: Some("2025-01-01T00:00:00Z".into()), }; @@ -1035,7 +1027,6 @@ mod tests { path: PathBuf::from("/tmp/b.jsonl"), head: head_with_ts_and_user_text("2025-01-02T00:00:00Z", &["B"]), tail: Vec::new(), - name: None, created_at: Some("2025-01-02T00:00:00Z".into()), updated_at: Some("2025-01-02T00:00:00Z".into()), }; @@ -1064,7 +1055,6 @@ mod tests { path: PathBuf::from("/tmp/a.jsonl"), head, tail, - name: None, created_at: Some("2025-01-01T00:00:00Z".into()), updated_at: Some("2025-01-01T01:00:00Z".into()), }; diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 92afe24748..14604a736d 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -15,7 +15,6 @@ pub enum SlashCommand { Model, Approvals, Review, - Name, New, Init, Compact, @@ -34,7 +33,6 @@ impl SlashCommand { /// User-visible description shown in the popup. pub fn description(self) -> &'static str { match self { - SlashCommand::Name => "set a name for this chat", SlashCommand::New => "start a new chat during a conversation", SlashCommand::Init => "create an AGENTS.md file with instructions for Codex", SlashCommand::Compact => "summarize conversation to prevent hitting the context limit", @@ -62,8 +60,6 @@ impl SlashCommand { /// Whether this command can be run while a task is in progress. pub fn available_during_task(self) -> bool { match self { - // Naming is a local UI action; allow during tasks. - SlashCommand::Name => true, SlashCommand::New | SlashCommand::Init | SlashCommand::Compact From 0026b12615e546cbdb8d63dd85f303de33bc730c Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 9 Oct 2025 16:55:02 +0100 Subject: [PATCH 10/32] feat: indentation mode for read_file (#4887) Add a read file that select the region of the file based on the indentation level --- codex-rs/core/src/tools/handlers/read_file.rs | 928 ++++++++++++++++-- codex-rs/core/src/tools/spec.rs | 63 +- 2 files changed, 899 insertions(+), 92 deletions(-) diff --git a/codex-rs/core/src/tools/handlers/read_file.rs b/codex-rs/core/src/tools/handlers/read_file.rs index 38b76f28ad..f9b6ae4dab 100644 --- a/codex-rs/core/src/tools/handlers/read_file.rs +++ b/codex-rs/core/src/tools/handlers/read_file.rs @@ -1,12 +1,9 @@ -use std::path::Path; +use std::collections::VecDeque; use std::path::PathBuf; use async_trait::async_trait; use codex_utils_string::take_bytes_at_char_boundary; use serde::Deserialize; -use tokio::fs::File; -use tokio::io::AsyncBufReadExt; -use tokio::io::BufReader; use crate::function_tool::FunctionCallError; use crate::tools::context::ToolInvocation; @@ -18,22 +15,78 @@ use crate::tools::registry::ToolKind; pub struct ReadFileHandler; const MAX_LINE_LENGTH: usize = 500; +const TAB_WIDTH: usize = 4; -fn default_offset() -> usize { - 1 -} +// TODO(jif) add support for block comments +const COMMENT_PREFIXES: &[&str] = &["#", "//", "--"]; -fn default_limit() -> usize { - 2000 +/// JSON arguments accepted by the `read_file` tool handler. +#[derive(Deserialize)] +struct ReadFileArgs { + /// Absolute path to the file that will be read. + file_path: String, + /// 1-indexed line number to start reading from; defaults to 1. + #[serde(default = "defaults::offset")] + offset: usize, + /// Maximum number of lines to return; defaults to 2000. + #[serde(default = "defaults::limit")] + limit: usize, + /// Determines whether the handler reads a simple slice or indentation-aware block. + #[serde(default)] + mode: ReadMode, + /// Optional indentation configuration used when `mode` is `Indentation`. + #[serde(default)] + indentation: Option, } #[derive(Deserialize)] -struct ReadFileArgs { - file_path: String, - #[serde(default = "default_offset")] - offset: usize, - #[serde(default = "default_limit")] - limit: usize, +#[serde(rename_all = "snake_case")] +enum ReadMode { + Slice, + Indentation, +} +/// Additional configuration for indentation-aware reads. +#[derive(Deserialize, Clone)] +struct IndentationArgs { + /// Optional explicit anchor line; defaults to `offset` when omitted. + #[serde(default)] + anchor_line: Option, + /// Maximum indentation depth to collect; `0` means unlimited. + #[serde(default = "defaults::max_levels")] + max_levels: usize, + /// Whether to include sibling blocks at the same indentation level. + #[serde(default = "defaults::include_siblings")] + include_siblings: bool, + /// Whether to include header lines above the anchor block. This made on a best effort basis. + #[serde(default = "defaults::include_header")] + include_header: bool, + /// Optional hard cap on returned lines; defaults to the global `limit`. + #[serde(default)] + max_lines: Option, +} + +#[derive(Clone, Debug)] +struct LineRecord { + number: usize, + raw: String, + display: String, + indent: usize, +} + +impl LineRecord { + fn trimmed(&self) -> &str { + self.raw.trim_start() + } + + fn is_blank(&self) -> bool { + self.trimmed().is_empty() + } + + fn is_comment(&self) -> bool { + COMMENT_PREFIXES + .iter() + .any(|prefix| self.raw.trim().starts_with(prefix)) + } } #[async_trait] @@ -64,6 +117,8 @@ impl ToolHandler for ReadFileHandler { file_path, offset, limit, + mode, + indentation, } = args; if offset == 0 { @@ -85,7 +140,13 @@ impl ToolHandler for ReadFileHandler { )); } - let collected = read_file_slice(&path, offset, limit).await?; + let collected = match mode { + ReadMode::Slice => slice::read(&path, offset, limit).await?, + ReadMode::Indentation => { + let indentation = indentation.unwrap_or_default(); + indentation::read_block(&path, offset, limit, indentation).await? + } + }; Ok(ToolOutput::Function { content: collected.join("\n"), success: Some(true), @@ -93,62 +154,280 @@ impl ToolHandler for ReadFileHandler { } } -async fn read_file_slice( - path: &Path, - offset: usize, - limit: usize, -) -> Result, FunctionCallError> { - let file = File::open(path) - .await - .map_err(|err| FunctionCallError::RespondToModel(format!("failed to read file: {err}")))?; +mod slice { + use crate::function_tool::FunctionCallError; + use crate::tools::handlers::read_file::format_line; + use std::path::Path; + use tokio::fs::File; + use tokio::io::AsyncBufReadExt; + use tokio::io::BufReader; - let mut reader = BufReader::new(file); - let mut collected = Vec::new(); - let mut seen = 0usize; - let mut buffer = Vec::new(); - - loop { - buffer.clear(); - let bytes_read = reader.read_until(b'\n', &mut buffer).await.map_err(|err| { + pub async fn read( + path: &Path, + offset: usize, + limit: usize, + ) -> Result, FunctionCallError> { + let file = File::open(path).await.map_err(|err| { FunctionCallError::RespondToModel(format!("failed to read file: {err}")) })?; - if bytes_read == 0 { - break; - } + let mut reader = BufReader::new(file); + let mut collected = Vec::new(); + let mut seen = 0usize; + let mut buffer = Vec::new(); - if buffer.last() == Some(&b'\n') { - buffer.pop(); - if buffer.last() == Some(&b'\r') { + loop { + buffer.clear(); + let bytes_read = reader.read_until(b'\n', &mut buffer).await.map_err(|err| { + FunctionCallError::RespondToModel(format!("failed to read file: {err}")) + })?; + + if bytes_read == 0 { + break; + } + + if buffer.last() == Some(&b'\n') { buffer.pop(); + if buffer.last() == Some(&b'\r') { + buffer.pop(); + } + } + + seen += 1; + + if seen < offset { + continue; + } + + if collected.len() == limit { + break; + } + + let formatted = format_line(&buffer); + collected.push(format!("L{seen}: {formatted}")); + + if collected.len() == limit { + break; } } - seen += 1; - if seen < offset { - continue; + return Err(FunctionCallError::RespondToModel( + "offset exceeds file length".to_string(), + )); } - if collected.len() == limit { - break; + Ok(collected) + } +} + +mod indentation { + use crate::function_tool::FunctionCallError; + use crate::tools::handlers::read_file::IndentationArgs; + use crate::tools::handlers::read_file::LineRecord; + use crate::tools::handlers::read_file::TAB_WIDTH; + use crate::tools::handlers::read_file::format_line; + use crate::tools::handlers::read_file::trim_empty_lines; + use std::collections::VecDeque; + use std::path::Path; + use tokio::fs::File; + use tokio::io::AsyncBufReadExt; + use tokio::io::BufReader; + + pub async fn read_block( + path: &Path, + offset: usize, + limit: usize, + options: IndentationArgs, + ) -> Result, FunctionCallError> { + let anchor_line = options.anchor_line.unwrap_or(offset); + if anchor_line == 0 { + return Err(FunctionCallError::RespondToModel( + "anchor_line must be a 1-indexed line number".to_string(), + )); } - let formatted = format_line(&buffer); - collected.push(format!("L{seen}: {formatted}")); - - if collected.len() == limit { - break; + let guard_limit = options.max_lines.unwrap_or(limit); + if guard_limit == 0 { + return Err(FunctionCallError::RespondToModel( + "max_lines must be greater than zero".to_string(), + )); } + + let collected = collect_file_lines(path).await?; + if collected.is_empty() || anchor_line > collected.len() { + return Err(FunctionCallError::RespondToModel( + "anchor_line exceeds file length".to_string(), + )); + } + + let anchor_index = anchor_line - 1; + let effective_indents = compute_effective_indents(&collected); + let anchor_indent = effective_indents[anchor_index]; + + // Compute the min indent + let min_indent = if options.max_levels == 0 { + 0 + } else { + anchor_indent.saturating_sub(options.max_levels * TAB_WIDTH) + }; + + // Cap requested lines by guard_limit and file length + let final_limit = limit.min(guard_limit).min(collected.len()); + + if final_limit == 1 { + return Ok(vec![format!( + "L{}: {}", + collected[anchor_index].number, collected[anchor_index].display + )]); + } + + // Cursors + let mut i: isize = anchor_index as isize - 1; // up (inclusive) + let mut j: usize = anchor_index + 1; // down (inclusive) + let mut i_counter_min_indent = 0; + let mut j_counter_min_indent = 0; + + let mut out = VecDeque::with_capacity(limit); + out.push_back(&collected[anchor_index]); + + while out.len() < final_limit { + let mut progressed = 0; + + // Up. + if i >= 0 { + let iu = i as usize; + if effective_indents[iu] >= min_indent { + out.push_front(&collected[iu]); + progressed += 1; + i -= 1; + + // We do not include the siblings (not applied to comments). + if effective_indents[iu] == min_indent && !options.include_siblings { + let allow_header_comment = + options.include_header && collected[iu].is_comment(); + let can_take_line = allow_header_comment || i_counter_min_indent == 0; + + if can_take_line { + i_counter_min_indent += 1; + } else { + // This line shouldn't have been taken. + out.pop_front(); + progressed -= 1; + i = -1; // consider using Option or a control flag instead of a sentinel + } + } + + // Short-cut. + if out.len() >= final_limit { + break; + } + } else { + // Stop moving up. + i = -1; + } + } + + // Down. + if j < collected.len() { + let ju = j; + if effective_indents[ju] >= min_indent { + out.push_back(&collected[ju]); + progressed += 1; + j += 1; + + // We do not include the siblings (applied to comments). + if effective_indents[ju] == min_indent && !options.include_siblings { + if j_counter_min_indent > 0 { + // This line shouldn't have been taken. + out.pop_back(); + progressed -= 1; + j = collected.len(); + } + j_counter_min_indent += 1; + } + } else { + // Stop moving down. + j = collected.len(); + } + } + + if progressed == 0 { + break; + } + } + + // Trim empty lines + trim_empty_lines(&mut out); + + Ok(out + .into_iter() + .map(|record| format!("L{}: {}", record.number, record.display)) + .collect()) } - if seen < offset { - return Err(FunctionCallError::RespondToModel( - "offset exceeds file length".to_string(), - )); + async fn collect_file_lines(path: &Path) -> Result, FunctionCallError> { + let file = File::open(path).await.map_err(|err| { + FunctionCallError::RespondToModel(format!("failed to read file: {err}")) + })?; + + let mut reader = BufReader::new(file); + let mut buffer = Vec::new(); + let mut lines = Vec::new(); + let mut number = 0usize; + + loop { + buffer.clear(); + let bytes_read = reader.read_until(b'\n', &mut buffer).await.map_err(|err| { + FunctionCallError::RespondToModel(format!("failed to read file: {err}")) + })?; + + if bytes_read == 0 { + break; + } + + if buffer.last() == Some(&b'\n') { + buffer.pop(); + if buffer.last() == Some(&b'\r') { + buffer.pop(); + } + } + + number += 1; + let raw = String::from_utf8_lossy(&buffer).into_owned(); + let indent = measure_indent(&raw); + let display = format_line(&buffer); + lines.push(LineRecord { + number, + raw, + display, + indent, + }); + } + + Ok(lines) } - Ok(collected) + fn compute_effective_indents(records: &[LineRecord]) -> Vec { + let mut effective = Vec::with_capacity(records.len()); + let mut previous_indent = 0usize; + for record in records { + if record.is_blank() { + effective.push(previous_indent); + } else { + previous_indent = record.indent; + effective.push(previous_indent); + } + } + effective + } + + fn measure_indent(line: &str) -> usize { + line.chars() + .take_while(|c| matches!(c, ' ' | '\t')) + .map(|c| if c == '\t' { TAB_WIDTH } else { 1 }) + .sum() + } } fn format_line(bytes: &[u8]) -> String { @@ -160,93 +439,560 @@ fn format_line(bytes: &[u8]) -> String { } } +fn trim_empty_lines(out: &mut VecDeque<&LineRecord>) { + while matches!(out.front(), Some(line) if line.raw.trim().is_empty()) { + out.pop_front(); + } + while matches!(out.back(), Some(line) if line.raw.trim().is_empty()) { + out.pop_back(); + } +} + +mod defaults { + use super::*; + + impl Default for IndentationArgs { + fn default() -> Self { + Self { + anchor_line: None, + max_levels: max_levels(), + include_siblings: include_siblings(), + include_header: include_header(), + max_lines: None, + } + } + } + + impl Default for ReadMode { + fn default() -> Self { + Self::Slice + } + } + + pub fn offset() -> usize { + 1 + } + + pub fn limit() -> usize { + 2000 + } + + pub fn max_levels() -> usize { + 0 + } + + pub fn include_siblings() -> bool { + false + } + + pub fn include_header() -> bool { + true + } +} + #[cfg(test)] mod tests { + use super::indentation::read_block; + use super::slice::read; use super::*; + use pretty_assertions::assert_eq; use tempfile::NamedTempFile; #[tokio::test] - async fn reads_requested_range() { - let mut temp = NamedTempFile::new().expect("create temp file"); + async fn reads_requested_range() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; use std::io::Write as _; - writeln!(temp, "alpha").unwrap(); - writeln!(temp, "beta").unwrap(); - writeln!(temp, "gamma").unwrap(); + write!( + temp, + "alpha +beta +gamma +" + )?; - let lines = read_file_slice(temp.path(), 2, 2) - .await - .expect("read slice"); + let lines = read(temp.path(), 2, 2).await?; assert_eq!(lines, vec!["L2: beta".to_string(), "L3: gamma".to_string()]); + Ok(()) } #[tokio::test] - async fn errors_when_offset_exceeds_length() { - let mut temp = NamedTempFile::new().expect("create temp file"); + async fn errors_when_offset_exceeds_length() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; use std::io::Write as _; - writeln!(temp, "only").unwrap(); + writeln!(temp, "only")?; - let err = read_file_slice(temp.path(), 3, 1) + let err = read(temp.path(), 3, 1) .await .expect_err("offset exceeds length"); assert_eq!( err, FunctionCallError::RespondToModel("offset exceeds file length".to_string()) ); + Ok(()) } #[tokio::test] - async fn reads_non_utf8_lines() { - let mut temp = NamedTempFile::new().expect("create temp file"); + async fn reads_non_utf8_lines() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; use std::io::Write as _; - temp.as_file_mut().write_all(b"\xff\xfe\nplain\n").unwrap(); + temp.as_file_mut().write_all(b"\xff\xfe\nplain\n")?; - let lines = read_file_slice(temp.path(), 1, 2) - .await - .expect("read slice"); + let lines = read(temp.path(), 1, 2).await?; let expected_first = format!("L1: {}{}", '\u{FFFD}', '\u{FFFD}'); assert_eq!(lines, vec![expected_first, "L2: plain".to_string()]); + Ok(()) } #[tokio::test] - async fn trims_crlf_endings() { - let mut temp = NamedTempFile::new().expect("create temp file"); + async fn trims_crlf_endings() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; use std::io::Write as _; - write!(temp, "one\r\ntwo\r\n").unwrap(); + write!(temp, "one\r\ntwo\r\n")?; - let lines = read_file_slice(temp.path(), 1, 2) - .await - .expect("read slice"); + let lines = read(temp.path(), 1, 2).await?; assert_eq!(lines, vec!["L1: one".to_string(), "L2: two".to_string()]); + Ok(()) } #[tokio::test] - async fn respects_limit_even_with_more_lines() { - let mut temp = NamedTempFile::new().expect("create temp file"); + async fn respects_limit_even_with_more_lines() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; use std::io::Write as _; - writeln!(temp, "first").unwrap(); - writeln!(temp, "second").unwrap(); - writeln!(temp, "third").unwrap(); + write!( + temp, + "first +second +third +" + )?; - let lines = read_file_slice(temp.path(), 1, 2) - .await - .expect("read slice"); + let lines = read(temp.path(), 1, 2).await?; assert_eq!( lines, vec!["L1: first".to_string(), "L2: second".to_string()] ); + Ok(()) } #[tokio::test] - async fn truncates_lines_longer_than_max_length() { - let mut temp = NamedTempFile::new().expect("create temp file"); + async fn truncates_lines_longer_than_max_length() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; use std::io::Write as _; let long_line = "x".repeat(MAX_LINE_LENGTH + 50); - writeln!(temp, "{long_line}").unwrap(); + writeln!(temp, "{long_line}")?; - let lines = read_file_slice(temp.path(), 1, 1) - .await - .expect("read slice"); + let lines = read(temp.path(), 1, 1).await?; let expected = "x".repeat(MAX_LINE_LENGTH); assert_eq!(lines, vec![format!("L1: {expected}")]); + Ok(()) + } + + #[tokio::test] + async fn indentation_mode_captures_block() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; + use std::io::Write as _; + write!( + temp, + "fn outer() {{ + if cond {{ + inner(); + }} + tail(); +}} +" + )?; + + let options = IndentationArgs { + anchor_line: Some(3), + include_siblings: false, + max_levels: 1, + ..Default::default() + }; + + let lines = read_block(temp.path(), 3, 10, options).await?; + + assert_eq!( + lines, + vec![ + "L2: if cond {".to_string(), + "L3: inner();".to_string(), + "L4: }".to_string() + ] + ); + Ok(()) + } + + #[tokio::test] + async fn indentation_mode_expands_parents() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; + use std::io::Write as _; + write!( + temp, + "mod root {{ + fn outer() {{ + if cond {{ + inner(); + }} + }} +}} +" + )?; + + let mut options = IndentationArgs { + anchor_line: Some(4), + max_levels: 2, + ..Default::default() + }; + + let lines = read_block(temp.path(), 4, 50, options.clone()).await?; + assert_eq!( + lines, + vec![ + "L2: fn outer() {".to_string(), + "L3: if cond {".to_string(), + "L4: inner();".to_string(), + "L5: }".to_string(), + "L6: }".to_string(), + ] + ); + + options.max_levels = 3; + let expanded = read_block(temp.path(), 4, 50, options).await?; + assert_eq!( + expanded, + vec![ + "L1: mod root {".to_string(), + "L2: fn outer() {".to_string(), + "L3: if cond {".to_string(), + "L4: inner();".to_string(), + "L5: }".to_string(), + "L6: }".to_string(), + "L7: }".to_string(), + ] + ); + Ok(()) + } + + #[tokio::test] + async fn indentation_mode_respects_sibling_flag() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; + use std::io::Write as _; + write!( + temp, + "fn wrapper() {{ + if first {{ + do_first(); + }} + if second {{ + do_second(); + }} +}} +" + )?; + + let mut options = IndentationArgs { + anchor_line: Some(3), + include_siblings: false, + max_levels: 1, + ..Default::default() + }; + + let lines = read_block(temp.path(), 3, 50, options.clone()).await?; + assert_eq!( + lines, + vec![ + "L2: if first {".to_string(), + "L3: do_first();".to_string(), + "L4: }".to_string(), + ] + ); + + options.include_siblings = true; + let with_siblings = read_block(temp.path(), 3, 50, options).await?; + assert_eq!( + with_siblings, + vec![ + "L2: if first {".to_string(), + "L3: do_first();".to_string(), + "L4: }".to_string(), + "L5: if second {".to_string(), + "L6: do_second();".to_string(), + "L7: }".to_string(), + ] + ); + Ok(()) + } + + #[tokio::test] + async fn indentation_mode_handles_python_sample() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; + use std::io::Write as _; + write!( + temp, + "class Foo: + def __init__(self, size): + self.size = size + def double(self, value): + if value is None: + return 0 + result = value * self.size + return result +class Bar: + def compute(self): + helper = Foo(2) + return helper.double(5) +" + )?; + + let options = IndentationArgs { + anchor_line: Some(7), + include_siblings: true, + max_levels: 1, + ..Default::default() + }; + + let lines = read_block(temp.path(), 1, 200, options).await?; + assert_eq!( + lines, + vec![ + "L2: def __init__(self, size):".to_string(), + "L3: self.size = size".to_string(), + "L4: def double(self, value):".to_string(), + "L5: if value is None:".to_string(), + "L6: return 0".to_string(), + "L7: result = value * self.size".to_string(), + "L8: return result".to_string(), + ] + ); + Ok(()) + } + + #[tokio::test] + #[ignore] + async fn indentation_mode_handles_javascript_sample() -> anyhow::Result<()> { + let mut temp = NamedTempFile::new()?; + use std::io::Write as _; + write!( + temp, + "export function makeThing() {{ + const cache = new Map(); + function ensure(key) {{ + if (!cache.has(key)) {{ + cache.set(key, []); + }} + return cache.get(key); + }} + const handlers = {{ + init() {{ + console.log(\"init\"); + }}, + run() {{ + if (Math.random() > 0.5) {{ + return \"heads\"; + }} + return \"tails\"; + }}, + }}; + return {{ cache, handlers }}; +}} +export function other() {{ + return makeThing(); +}} +" + )?; + + let options = IndentationArgs { + anchor_line: Some(15), + max_levels: 1, + ..Default::default() + }; + + let lines = read_block(temp.path(), 15, 200, options).await?; + assert_eq!( + lines, + vec![ + "L10: init() {".to_string(), + "L11: console.log(\"init\");".to_string(), + "L12: },".to_string(), + "L13: run() {".to_string(), + "L14: if (Math.random() > 0.5) {".to_string(), + "L15: return \"heads\";".to_string(), + "L16: }".to_string(), + "L17: return \"tails\";".to_string(), + "L18: },".to_string(), + ] + ); + Ok(()) + } + + fn write_cpp_sample() -> anyhow::Result { + let mut temp = NamedTempFile::new()?; + use std::io::Write as _; + write!( + temp, + "#include +#include + +namespace sample {{ +class Runner {{ +public: + void setup() {{ + if (enabled_) {{ + init(); + }} + }} + + // Run the code + int run() const {{ + switch (mode_) {{ + case Mode::Fast: + return fast(); + case Mode::Slow: + return slow(); + default: + return fallback(); + }} + }} + +private: + bool enabled_ = false; + Mode mode_ = Mode::Fast; + + int fast() const {{ + return 1; + }} +}}; +}} // namespace sample +" + )?; + Ok(temp) + } + + #[tokio::test] + async fn indentation_mode_handles_cpp_sample_shallow() -> anyhow::Result<()> { + let temp = write_cpp_sample()?; + + let options = IndentationArgs { + include_siblings: false, + anchor_line: Some(18), + max_levels: 1, + ..Default::default() + }; + + let lines = read_block(temp.path(), 18, 200, options).await?; + assert_eq!( + lines, + vec![ + "L15: switch (mode_) {".to_string(), + "L16: case Mode::Fast:".to_string(), + "L17: return fast();".to_string(), + "L18: case Mode::Slow:".to_string(), + "L19: return slow();".to_string(), + "L20: default:".to_string(), + "L21: return fallback();".to_string(), + "L22: }".to_string(), + ] + ); + Ok(()) + } + + #[tokio::test] + async fn indentation_mode_handles_cpp_sample() -> anyhow::Result<()> { + let temp = write_cpp_sample()?; + + let options = IndentationArgs { + include_siblings: false, + anchor_line: Some(18), + max_levels: 2, + ..Default::default() + }; + + let lines = read_block(temp.path(), 18, 200, options).await?; + assert_eq!( + lines, + vec![ + "L13: // Run the code".to_string(), + "L14: int run() const {".to_string(), + "L15: switch (mode_) {".to_string(), + "L16: case Mode::Fast:".to_string(), + "L17: return fast();".to_string(), + "L18: case Mode::Slow:".to_string(), + "L19: return slow();".to_string(), + "L20: default:".to_string(), + "L21: return fallback();".to_string(), + "L22: }".to_string(), + "L23: }".to_string(), + ] + ); + Ok(()) + } + + #[tokio::test] + async fn indentation_mode_handles_cpp_sample_no_headers() -> anyhow::Result<()> { + let temp = write_cpp_sample()?; + + let options = IndentationArgs { + include_siblings: false, + include_header: false, + anchor_line: Some(18), + max_levels: 2, + ..Default::default() + }; + + let lines = read_block(temp.path(), 18, 200, options).await?; + assert_eq!( + lines, + vec![ + "L14: int run() const {".to_string(), + "L15: switch (mode_) {".to_string(), + "L16: case Mode::Fast:".to_string(), + "L17: return fast();".to_string(), + "L18: case Mode::Slow:".to_string(), + "L19: return slow();".to_string(), + "L20: default:".to_string(), + "L21: return fallback();".to_string(), + "L22: }".to_string(), + "L23: }".to_string(), + ] + ); + Ok(()) + } + + #[tokio::test] + async fn indentation_mode_handles_cpp_sample_siblings() -> anyhow::Result<()> { + let temp = write_cpp_sample()?; + + let options = IndentationArgs { + include_siblings: true, + include_header: false, + anchor_line: Some(18), + max_levels: 2, + ..Default::default() + }; + + let lines = read_block(temp.path(), 18, 200, options).await?; + assert_eq!( + lines, + vec![ + "L7: void setup() {".to_string(), + "L8: if (enabled_) {".to_string(), + "L9: init();".to_string(), + "L10: }".to_string(), + "L11: }".to_string(), + "L12: ".to_string(), + "L13: // Run the code".to_string(), + "L14: int run() const {".to_string(), + "L15: switch (mode_) {".to_string(), + "L16: case Mode::Fast:".to_string(), + "L17: return fast();".to_string(), + "L18: case Mode::Slow:".to_string(), + "L19: return slow();".to_string(), + "L20: default:".to_string(), + "L21: return fallback();".to_string(), + "L22: }".to_string(), + "L23: }".to_string(), + ] + ); + Ok(()) } } diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index e38095ecc9..c10f8e22f9 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -392,11 +392,72 @@ fn create_read_file_tool() -> ToolSpec { description: Some("The maximum number of lines to return.".to_string()), }, ); + properties.insert( + "mode".to_string(), + JsonSchema::String { + description: Some( + "Optional mode selector: \"slice\" for simple ranges (default) or \"indentation\" \ + to expand around an anchor line." + .to_string(), + ), + }, + ); + + let mut indentation_properties = BTreeMap::new(); + indentation_properties.insert( + "anchor_line".to_string(), + JsonSchema::Number { + description: Some( + "Anchor line to center the indentation lookup on (defaults to offset).".to_string(), + ), + }, + ); + indentation_properties.insert( + "max_levels".to_string(), + JsonSchema::Number { + description: Some( + "How many parent indentation levels (smaller indents) to include.".to_string(), + ), + }, + ); + indentation_properties.insert( + "include_siblings".to_string(), + JsonSchema::Boolean { + description: Some( + "When true, include additional blocks that share the anchor indentation." + .to_string(), + ), + }, + ); + indentation_properties.insert( + "include_header".to_string(), + JsonSchema::Boolean { + description: Some( + "Include doc comments or attributes directly above the selected block.".to_string(), + ), + }, + ); + indentation_properties.insert( + "max_lines".to_string(), + JsonSchema::Number { + description: Some( + "Hard cap on the number of lines returned when using indentation mode.".to_string(), + ), + }, + ); + properties.insert( + "indentation".to_string(), + JsonSchema::Object { + properties: indentation_properties, + required: None, + additional_properties: Some(false.into()), + }, + ); ToolSpec::Function(ResponsesApiTool { name: "read_file".to_string(), description: - "Reads a local file with 1-indexed line numbers and returns up to the requested number of lines." + "Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes." .to_string(), strict: false, parameters: JsonSchema::Object { From ca6a0358def87487a4a1186cae5a94591e7bd842 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 9 Oct 2025 17:01:01 +0100 Subject: [PATCH 11/32] bug: sandbox denied error logs (#4874) Check on STDOUT / STDERR or aggregated output for some logs when sanbox is denied --- codex-rs/core/src/error.rs | 108 ++++++++++++++++++++-- codex-rs/core/src/exec.rs | 128 +++++++++++++++++++++++++-- codex-rs/core/src/executor/runner.rs | 17 ++++ codex-rs/core/tests/suite/tools.rs | 73 --------------- 4 files changed, 237 insertions(+), 89 deletions(-) diff --git a/codex-rs/core/src/error.rs b/codex-rs/core/src/error.rs index 6fad448b44..786e20523a 100644 --- a/codex-rs/core/src/error.rs +++ b/codex-rs/core/src/error.rs @@ -1,6 +1,7 @@ use crate::exec::ExecToolCallOutput; use crate::token_data::KnownPlan; use crate::token_data::PlanType; +use crate::truncate::truncate_middle; use codex_protocol::ConversationId; use codex_protocol::protocol::RateLimitSnapshot; use reqwest::StatusCode; @@ -12,6 +13,9 @@ use tokio::task::JoinError; pub type Result = std::result::Result; +/// Limit UI error messages to a reasonable size while keeping useful context. +const ERROR_MESSAGE_UI_MAX_BYTES: usize = 2 * 1024; // 4 KiB + #[derive(Error, Debug)] pub enum SandboxErr { /// Error from sandbox execution @@ -304,21 +308,44 @@ impl CodexErr { } pub fn get_error_message_ui(e: &CodexErr) -> String { - match e { - CodexErr::Sandbox(SandboxErr::Denied { output }) => output.stderr.text.clone(), + let message = match e { + CodexErr::Sandbox(SandboxErr::Denied { output }) => { + let aggregated = output.aggregated_output.text.trim(); + if !aggregated.is_empty() { + output.aggregated_output.text.clone() + } else { + let stderr = output.stderr.text.trim(); + let stdout = output.stdout.text.trim(); + match (stderr.is_empty(), stdout.is_empty()) { + (false, false) => format!("{stderr}\n{stdout}"), + (false, true) => output.stderr.text.clone(), + (true, false) => output.stdout.text.clone(), + (true, true) => format!( + "command failed inside sandbox with exit code {}", + output.exit_code + ), + } + } + } // Timeouts are not sandbox errors from a UX perspective; present them plainly - CodexErr::Sandbox(SandboxErr::Timeout { output }) => format!( - "error: command timed out after {} ms", - output.duration.as_millis() - ), + CodexErr::Sandbox(SandboxErr::Timeout { output }) => { + format!( + "error: command timed out after {} ms", + output.duration.as_millis() + ) + } _ => e.to_string(), - } + }; + + truncate_middle(&message, ERROR_MESSAGE_UI_MAX_BYTES).0 } #[cfg(test)] mod tests { use super::*; + use crate::exec::StreamOutput; use codex_protocol::protocol::RateLimitWindow; + use pretty_assertions::assert_eq; fn rate_limit_snapshot() -> RateLimitSnapshot { RateLimitSnapshot { @@ -348,6 +375,73 @@ mod tests { ); } + #[test] + fn sandbox_denied_uses_aggregated_output_when_stderr_empty() { + let output = ExecToolCallOutput { + exit_code: 77, + stdout: StreamOutput::new(String::new()), + stderr: StreamOutput::new(String::new()), + aggregated_output: StreamOutput::new("aggregate detail".to_string()), + duration: Duration::from_millis(10), + timed_out: false, + }; + let err = CodexErr::Sandbox(SandboxErr::Denied { + output: Box::new(output), + }); + assert_eq!(get_error_message_ui(&err), "aggregate detail"); + } + + #[test] + fn sandbox_denied_reports_both_streams_when_available() { + let output = ExecToolCallOutput { + exit_code: 9, + stdout: StreamOutput::new("stdout detail".to_string()), + stderr: StreamOutput::new("stderr detail".to_string()), + aggregated_output: StreamOutput::new(String::new()), + duration: Duration::from_millis(10), + timed_out: false, + }; + let err = CodexErr::Sandbox(SandboxErr::Denied { + output: Box::new(output), + }); + assert_eq!(get_error_message_ui(&err), "stderr detail\nstdout detail"); + } + + #[test] + fn sandbox_denied_reports_stdout_when_no_stderr() { + let output = ExecToolCallOutput { + exit_code: 11, + stdout: StreamOutput::new("stdout only".to_string()), + stderr: StreamOutput::new(String::new()), + aggregated_output: StreamOutput::new(String::new()), + duration: Duration::from_millis(8), + timed_out: false, + }; + let err = CodexErr::Sandbox(SandboxErr::Denied { + output: Box::new(output), + }); + assert_eq!(get_error_message_ui(&err), "stdout only"); + } + + #[test] + fn sandbox_denied_reports_exit_code_when_no_output_available() { + let output = ExecToolCallOutput { + exit_code: 13, + stdout: StreamOutput::new(String::new()), + stderr: StreamOutput::new(String::new()), + aggregated_output: StreamOutput::new(String::new()), + duration: Duration::from_millis(5), + timed_out: false, + }; + let err = CodexErr::Sandbox(SandboxErr::Denied { + output: Box::new(output), + }); + assert_eq!( + get_error_message_ui(&err), + "command failed inside sandbox with exit code 13" + ); + } + #[test] fn usage_limit_reached_error_formats_free_plan() { let err = UsageLimitReachedError { diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index d84bbc9fcb..22d1deeb1c 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -177,7 +177,7 @@ pub async fn process_exec_tool_call( })); } - if exit_code != 0 && is_likely_sandbox_denied(sandbox_type, exit_code) { + if is_likely_sandbox_denied(sandbox_type, &exec_output) { return Err(CodexErr::Sandbox(SandboxErr::Denied { output: Box::new(exec_output), })); @@ -195,21 +195,57 @@ pub async fn process_exec_tool_call( /// We don't have a fully deterministic way to tell if our command failed /// because of the sandbox - a command in the user's zshrc file might hit an /// error, but the command itself might fail or succeed for other reasons. -/// For now, we conservatively check for 'command not found' (exit code 127), -/// and can add additional cases as necessary. -fn is_likely_sandbox_denied(sandbox_type: SandboxType, exit_code: i32) -> bool { - if sandbox_type == SandboxType::None { +/// For now, we conservatively check for well known command failure exit codes and +/// also look for common sandbox denial keywords in the command output. +fn is_likely_sandbox_denied(sandbox_type: SandboxType, exec_output: &ExecToolCallOutput) -> bool { + if sandbox_type == SandboxType::None || exec_output.exit_code == 0 { return false; } // Quick rejects: well-known non-sandbox shell exit codes - // 127: command not found, 2: misuse of shell builtins - if exit_code == 127 { + // 2: misuse of shell builtins + // 126: permission denied + // 127: command not found + const QUICK_REJECT_EXIT_CODES: [i32; 3] = [2, 126, 127]; + if QUICK_REJECT_EXIT_CODES.contains(&exec_output.exit_code) { return false; } - // For all other cases, we assume the sandbox is the cause - true + const SANDBOX_DENIED_KEYWORDS: [&str; 6] = [ + "operation not permitted", + "permission denied", + "read-only file system", + "seccomp", + "sandbox", + "landlock", + ]; + + if [ + &exec_output.stderr.text, + &exec_output.stdout.text, + &exec_output.aggregated_output.text, + ] + .into_iter() + .any(|section| { + let lower = section.to_lowercase(); + SANDBOX_DENIED_KEYWORDS + .iter() + .any(|needle| lower.contains(needle)) + }) { + return true; + } + + #[cfg(unix)] + { + const SIGSYS_CODE: i32 = libc::SIGSYS; + if sandbox_type == SandboxType::LinuxSeccomp + && exec_output.exit_code == EXIT_CODE_SIGNAL_BASE + SIGSYS_CODE + { + return true; + } + } + + false } #[derive(Debug)] @@ -436,3 +472,77 @@ fn synthetic_exit_status(code: i32) -> ExitStatus { #[expect(clippy::unwrap_used)] std::process::ExitStatus::from_raw(code.try_into().unwrap()) } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + fn make_exec_output( + exit_code: i32, + stdout: &str, + stderr: &str, + aggregated: &str, + ) -> ExecToolCallOutput { + ExecToolCallOutput { + exit_code, + stdout: StreamOutput::new(stdout.to_string()), + stderr: StreamOutput::new(stderr.to_string()), + aggregated_output: StreamOutput::new(aggregated.to_string()), + duration: Duration::from_millis(1), + timed_out: false, + } + } + + #[test] + fn sandbox_detection_requires_keywords() { + let output = make_exec_output(1, "", "", ""); + assert!(!is_likely_sandbox_denied( + SandboxType::LinuxSeccomp, + &output + )); + } + + #[test] + fn sandbox_detection_identifies_keyword_in_stderr() { + let output = make_exec_output(1, "", "Operation not permitted", ""); + assert!(is_likely_sandbox_denied(SandboxType::LinuxSeccomp, &output)); + } + + #[test] + fn sandbox_detection_respects_quick_reject_exit_codes() { + let output = make_exec_output(127, "", "command not found", ""); + assert!(!is_likely_sandbox_denied( + SandboxType::LinuxSeccomp, + &output + )); + } + + #[test] + fn sandbox_detection_ignores_non_sandbox_mode() { + let output = make_exec_output(1, "", "Operation not permitted", ""); + assert!(!is_likely_sandbox_denied(SandboxType::None, &output)); + } + + #[test] + fn sandbox_detection_uses_aggregated_output() { + let output = make_exec_output( + 101, + "", + "", + "cargo failed: Read-only file system when writing target", + ); + assert!(is_likely_sandbox_denied( + SandboxType::MacosSeatbelt, + &output + )); + } + + #[cfg(unix)] + #[test] + fn sandbox_detection_flags_sigsys_exit_code() { + let exit_code = EXIT_CODE_SIGNAL_BASE + libc::SIGSYS; + let output = make_exec_output(exit_code, "", "", ""); + assert!(is_likely_sandbox_denied(SandboxType::LinuxSeccomp, &output)); + } +} diff --git a/codex-rs/core/src/executor/runner.rs b/codex-rs/core/src/executor/runner.rs index f475aad67e..9a1956f66f 100644 --- a/codex-rs/core/src/executor/runner.rs +++ b/codex-rs/core/src/executor/runner.rs @@ -380,6 +380,23 @@ mod tests { assert_eq!(message, "failed in sandbox: sandbox stderr"); } + #[test] + fn sandbox_failure_message_falls_back_to_aggregated_output() { + let output = ExecToolCallOutput { + exit_code: 101, + stdout: StreamOutput::new(String::new()), + stderr: StreamOutput::new(String::new()), + aggregated_output: StreamOutput::new("aggregate text".to_string()), + duration: Duration::from_millis(10), + timed_out: false, + }; + let err = SandboxErr::Denied { + output: Box::new(output), + }; + let message = sandbox_failure_message(err); + assert_eq!(message, "failed in sandbox: aggregate text"); + } + #[test] fn normalize_function_error_synthesizes_payload() { let err = FunctionCallError::RespondToModel("boom".to_string()); diff --git a/codex-rs/core/tests/suite/tools.rs b/codex-rs/core/tests/suite/tools.rs index 99c70dbd61..ba87cb333d 100644 --- a/codex-rs/core/tests/suite/tools.rs +++ b/codex-rs/core/tests/suite/tools.rs @@ -403,79 +403,6 @@ async fn shell_timeout_includes_timeout_prefix_and_metadata() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn shell_sandbox_denied_truncates_error_output() -> Result<()> { - skip_if_no_network!(Ok(())); - - let server = start_mock_server().await; - let mut builder = test_codex(); - let test = builder.build(&server).await?; - - let call_id = "shell-denied"; - let long_line = "this is a long stderr line that should trigger truncation 0123456789abcdefghijklmnopqrstuvwxyz"; - let script = format!( - "for i in $(seq 1 500); do >&2 echo '{long_line}'; done; cat <<'EOF' > denied.txt\ncontent\nEOF", - ); - let args = json!({ - "command": ["/bin/sh", "-c", script], - "timeout_ms": 1_000, - }); - - mount_sse_once( - &server, - sse(vec![ - ev_response_created("resp-1"), - ev_function_call(call_id, "shell", &serde_json::to_string(&args)?), - ev_completed("resp-1"), - ]), - ) - .await; - let second_mock = mount_sse_once( - &server, - sse(vec![ - ev_assistant_message("msg-1", "done"), - ev_completed("resp-2"), - ]), - ) - .await; - - submit_turn( - &test, - "attempt to write in read-only sandbox", - AskForApproval::Never, - SandboxPolicy::ReadOnly, - ) - .await?; - - let denied_item = second_mock.single_request().function_call_output(call_id); - - let output = denied_item - .get("output") - .and_then(Value::as_str) - .expect("denied output string"); - - let sandbox_pattern = r#"(?s)^Exit code: -?\d+ -Wall time: [0-9]+(?:\.[0-9]+)? seconds -Total output lines: \d+ -Output: - -failed in sandbox: .*?(?:Operation not permitted|Permission denied|Read-only file system).*? -\[\.{3} omitted \d+ of \d+ lines \.{3}\] -.*this is a long stderr line that should trigger truncation 0123456789abcdefghijklmnopqrstuvwxyz.* -\n?$"#; - let sandbox_regex = Regex::new(sandbox_pattern)?; - if !sandbox_regex.is_match(output) { - let fallback_pattern = r#"(?s)^Total output lines: \d+ - -failed in sandbox: this is a long stderr line that should trigger truncation 0123456789abcdefghijklmnopqrstuvwxyz -.*this is a long stderr line that should trigger truncation 0123456789abcdefghijklmnopqrstuvwxyz.* -.*(?:Operation not permitted|Permission denied|Read-only file system).*$"#; - assert_regex_match(fallback_pattern, output); - } - - Ok(()) -} - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn shell_spawn_failure_truncates_exec_error() -> Result<()> { skip_if_no_network!(Ok(())); From 3ddd4d47d07425da48ba5373d8bac14cca45f625 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 9 Oct 2025 17:06:07 +0100 Subject: [PATCH 12/32] fix: lagged output in unified_exec buffer (#4992) Handle `Lagged` error when the broadcast buffer of the unified_exec is full --- codex-rs/core/src/unified_exec/mod.rs | 21 +++- codex-rs/core/tests/suite/unified_exec.rs | 125 ++++++++++++++++++++++ 2 files changed, 141 insertions(+), 5 deletions(-) diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index 48b82e3e8c..a8f754c92e 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -110,11 +110,22 @@ impl ManagedUnifiedExecSession { let buffer_clone = Arc::clone(&output_buffer); let notify_clone = Arc::clone(&output_notify); let output_task = tokio::spawn(async move { - while let Ok(chunk) = receiver.recv().await { - let mut guard = buffer_clone.lock().await; - guard.push_chunk(chunk); - drop(guard); - notify_clone.notify_waiters(); + loop { + match receiver.recv().await { + Ok(chunk) => { + let mut guard = buffer_clone.lock().await; + guard.push_chunk(chunk); + drop(guard); + notify_clone.notify_waiters(); + } + // If we lag behind the broadcast buffer, skip missed + // messages but keep the task alive to continue streaming. + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { + continue; + } + // When the sender closes, exit the task. + Err(tokio::sync::broadcast::error::RecvError::Closed) => break, + } } }); diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index 5afcc9f5fa..b8c0fadbbe 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -167,6 +167,131 @@ async fn unified_exec_reuses_session_via_stdin() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn unified_exec_streams_after_lagged_output() -> Result<()> { + skip_if_no_network!(Ok(())); + skip_if_sandbox!(Ok(())); + + let server = start_mock_server().await; + + let mut builder = test_codex().with_config(|config| { + config.use_experimental_unified_exec_tool = true; + }); + let TestCodex { + codex, + cwd, + session_configured, + .. + } = builder.build(&server).await?; + + let script = r#"python3 - <<'PY' +import sys +import time + +chunk = b'x' * (1 << 20) +for _ in range(4): + sys.stdout.buffer.write(chunk) + sys.stdout.flush() + +time.sleep(0.2) +for _ in range(5): + sys.stdout.write("TAIL-MARKER\n") + sys.stdout.flush() + time.sleep(0.05) + +time.sleep(0.2) +PY +"#; + + let first_call_id = "uexec-lag-start"; + let first_args = serde_json::json!({ + "input": ["/bin/sh", "-c", script], + "timeout_ms": 25, + }); + + let second_call_id = "uexec-lag-poll"; + let second_args = serde_json::json!({ + "input": Vec::::new(), + "session_id": "0", + "timeout_ms": 800, + }); + + let responses = vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_function_call( + first_call_id, + "unified_exec", + &serde_json::to_string(&first_args)?, + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_function_call( + second_call_id, + "unified_exec", + &serde_json::to_string(&second_args)?, + ), + ev_completed("resp-2"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "lag handled"), + ev_completed("resp-3"), + ]), + ]; + mount_sse_sequence(&server, responses).await; + + let session_model = session_configured.model.clone(); + + codex + .submit(Op::UserTurn { + items: vec![InputItem::Text { + text: "exercise lag handling".into(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model: session_model, + effort: None, + summary: ReasoningSummary::Auto, + }) + .await?; + + wait_for_event(&codex, |event| matches!(event, EventMsg::TaskComplete(_))).await; + + let requests = server.received_requests().await.expect("recorded requests"); + assert!(!requests.is_empty(), "expected at least one POST request"); + + let bodies = requests + .iter() + .map(|req| req.body_json::().expect("request json")) + .collect::>(); + + let outputs = collect_tool_outputs(&bodies)?; + + let start_output = outputs + .get(first_call_id) + .expect("missing initial unified_exec output"); + let session_id = start_output["session_id"].as_str().unwrap_or_default(); + assert!( + !session_id.is_empty(), + "expected session id from initial unified_exec response" + ); + + let poll_output = outputs + .get(second_call_id) + .expect("missing poll unified_exec output"); + let poll_text = poll_output["output"].as_str().unwrap_or_default(); + assert!( + poll_text.contains("TAIL-MARKER"), + "expected poll output to contain tail marker, got {poll_text:?}" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn unified_exec_timeout_and_followup_poll() -> Result<()> { skip_if_no_network!(Ok(())); From 7b4a4c2219e234b39266ffadb096fb0aad62bae9 Mon Sep 17 00:00:00 2001 From: Shijie Rao Date: Thu, 9 Oct 2025 09:42:24 -0700 Subject: [PATCH 13/32] Shijie/codesign binary (#4899) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Summary * Added code signing for MacOS. ### Before - UNSIGNED codex-aarch64 Screenshot 2025-10-08 at 11 53 28 AM ### After - SIGNED codex-aarch64 Screenshot 2025-10-08 at 11 52 20 AM --- .github/workflows/rust-release.yml | 134 ++++++++++++++++++++++++++++- 1 file changed, 132 insertions(+), 2 deletions(-) diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index aebdef5948..be04615699 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -47,7 +47,7 @@ jobs: build: needs: tag-check - name: ${{ matrix.runner }} - ${{ matrix.target }} + name: Build - ${{ matrix.runner }} - ${{ matrix.target }} runs-on: ${{ matrix.runner }} timeout-minutes: 30 defaults: @@ -94,11 +94,118 @@ jobs: - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} name: Install musl build tools run: | - sudo apt install -y musl-tools pkg-config + sudo apt-get update + sudo apt-get install -y musl-tools pkg-config - name: Cargo build run: cargo build --target ${{ matrix.target }} --release --bin codex --bin codex-responses-api-proxy + - if: ${{ matrix.runner == 'macos-14' }} + name: Configure Apple code signing + shell: bash + env: + KEYCHAIN_PASSWORD: actions + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE_P12 }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + run: | + set -euo pipefail + + if [[ -z "${APPLE_CERTIFICATE:-}" ]]; then + echo "APPLE_CERTIFICATE is required for macOS signing" + exit 1 + fi + + if [[ -z "${APPLE_CERTIFICATE_PASSWORD:-}" ]]; then + echo "APPLE_CERTIFICATE_PASSWORD is required for macOS signing" + exit 1 + fi + + cert_path="${RUNNER_TEMP}/apple_signing_certificate.p12" + echo "$APPLE_CERTIFICATE" | base64 -d > "$cert_path" + + keychain_path="${RUNNER_TEMP}/codex-signing.keychain-db" + security create-keychain -p "$KEYCHAIN_PASSWORD" "$keychain_path" + security set-keychain-settings -lut 21600 "$keychain_path" + security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$keychain_path" + + keychain_args=() + cleanup_keychain() { + if ((${#keychain_args[@]} > 0)); then + security list-keychains -s "${keychain_args[@]}" || true + security default-keychain -s "${keychain_args[0]}" || true + else + security list-keychains -s || true + fi + if [[ -f "$keychain_path" ]]; then + security delete-keychain "$keychain_path" || true + fi + } + + while IFS= read -r keychain; do + [[ -n "$keychain" ]] && keychain_args+=("$keychain") + done < <(security list-keychains | sed 's/^[[:space:]]*//;s/[[:space:]]*$//;s/"//g') + + if ((${#keychain_args[@]} > 0)); then + security list-keychains -s "$keychain_path" "${keychain_args[@]}" + else + security list-keychains -s "$keychain_path" + fi + + security default-keychain -s "$keychain_path" + security import "$cert_path" -k "$keychain_path" -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign -T /usr/bin/security + security set-key-partition-list -S apple-tool:,apple: -s -k "$KEYCHAIN_PASSWORD" "$keychain_path" > /dev/null + + codesign_hashes=() + while IFS= read -r hash; do + [[ -n "$hash" ]] && codesign_hashes+=("$hash") + done < <(security find-identity -v -p codesigning "$keychain_path" \ + | sed -n 's/.*\([0-9A-F]\{40\}\).*/\1/p' \ + | sort -u) + + if ((${#codesign_hashes[@]} == 0)); then + echo "No signing identities found in $keychain_path" + cleanup_keychain + rm -f "$cert_path" + exit 1 + fi + + if ((${#codesign_hashes[@]} > 1)); then + echo "Multiple signing identities found in $keychain_path:" + printf ' %s\n' "${codesign_hashes[@]}" + cleanup_keychain + rm -f "$cert_path" + exit 1 + fi + + APPLE_CODESIGN_IDENTITY="${codesign_hashes[0]}" + + rm -f "$cert_path" + + echo "APPLE_CODESIGN_IDENTITY=$APPLE_CODESIGN_IDENTITY" >> "$GITHUB_ENV" + echo "APPLE_CODESIGN_KEYCHAIN=$keychain_path" >> "$GITHUB_ENV" + echo "::add-mask::$APPLE_CODESIGN_IDENTITY" + + - if: ${{ matrix.runner == 'macos-14' }} + name: Sign macOS binaries + shell: bash + run: | + set -euo pipefail + + if [[ -z "${APPLE_CODESIGN_IDENTITY:-}" ]]; then + echo "APPLE_CODESIGN_IDENTITY is required for macOS signing" + exit 1 + fi + + keychain_args=() + if [[ -n "${APPLE_CODESIGN_KEYCHAIN:-}" && -f "${APPLE_CODESIGN_KEYCHAIN}" ]]; then + keychain_args+=(--keychain "${APPLE_CODESIGN_KEYCHAIN}") + fi + + for binary in codex codex-responses-api-proxy; do + path="target/${{ matrix.target }}/release/${binary}" + codesign --force --options runtime --timestamp --sign "$APPLE_CODESIGN_IDENTITY" "${keychain_args[@]}" "$path" + done + - name: Stage artifacts shell: bash run: | @@ -157,6 +264,29 @@ jobs: zstd -T0 -19 --rm "$dest/$base" done + - name: Remove signing keychain + if: ${{ always() && matrix.runner == 'macos-14' }} + shell: bash + env: + APPLE_CODESIGN_KEYCHAIN: ${{ env.APPLE_CODESIGN_KEYCHAIN }} + run: | + set -euo pipefail + if [[ -n "${APPLE_CODESIGN_KEYCHAIN:-}" ]]; then + keychain_args=() + while IFS= read -r keychain; do + [[ "$keychain" == "$APPLE_CODESIGN_KEYCHAIN" ]] && continue + [[ -n "$keychain" ]] && keychain_args+=("$keychain") + done < <(security list-keychains | sed 's/^[[:space:]]*//;s/[[:space:]]*$//;s/"//g') + if ((${#keychain_args[@]} > 0)); then + security list-keychains -s "${keychain_args[@]}" + security default-keychain -s "${keychain_args[0]}" + fi + + if [[ -f "$APPLE_CODESIGN_KEYCHAIN" ]]; then + security delete-keychain "$APPLE_CODESIGN_KEYCHAIN" + fi + fi + - uses: actions/upload-artifact@v4 with: name: ${{ matrix.target }} From 0308febc2324a3759215dbf92fb61c81db608243 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 9 Oct 2025 10:29:22 -0700 Subject: [PATCH 14/32] Remove unused type (#5003) It was never exported --- sdk/typescript/src/items.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/sdk/typescript/src/items.ts b/sdk/typescript/src/items.ts index 37563f9af9..fa2e0326bf 100644 --- a/sdk/typescript/src/items.ts +++ b/sdk/typescript/src/items.ts @@ -102,11 +102,6 @@ export type TodoListItem = { items: TodoItem[]; }; -export type SessionItem = { - id: string; - type: "session"; - session_id: string; -}; /** Canonical union of thread items and their type-specific payloads. */ export type ThreadItem = From bf82353f451dd71a1a9696fc595444fca04cc6d6 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 9 Oct 2025 10:37:13 -0700 Subject: [PATCH 15/32] tui: fix wrapping in user approval decisions (#5008) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit before: Screenshot 2025-10-09 at 10 20 57 AM after: Screenshot 2025-10-09 at 10 20 35 AM --- .../tui/src/bottom_pane/approval_overlay.rs | 118 ++++---------- ...pproval_history_decision_aborted_long.snap | 4 +- codex-rs/tui/src/history_cell.rs | 150 +++++++++++++++++- codex-rs/tui/src/pager_overlay.rs | 8 +- 4 files changed, 184 insertions(+), 96 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index 6585124c52..d6e96cf78d 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -16,7 +16,6 @@ use crate::key_hint::KeyBinding; use crate::render::highlight::highlight_bash_to_lines; use crate::render::renderable::ColumnRenderable; use crate::render::renderable::Renderable; -use crate::text_formatting::truncate_text; use codex_core::protocol::FileChange; use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; @@ -160,11 +159,8 @@ impl ApprovalOverlay { } fn handle_exec_decision(&self, id: &str, command: &[String], decision: ReviewDecision) { - if let Some(lines) = build_exec_history_lines(command.to_vec(), decision) { - self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new( - history_cell::new_user_approval_decision(lines), - ))); - } + let cell = history_cell::new_approval_decision_cell(command.to_vec(), decision); + self.app_event_tx.send(AppEvent::InsertHistoryCell(cell)); self.app_event_tx.send(AppEvent::CodexOp(Op::ExecApproval { id: id.to_string(), decision, @@ -396,91 +392,11 @@ fn patch_options() -> Vec { ] } -fn build_exec_history_lines( - command: Vec, - decision: ReviewDecision, -) -> Option>> { - use ReviewDecision::*; - - let (symbol, summary): (Span<'static>, Vec>) = match decision { - Approved => { - let snippet = Span::from(exec_snippet(&command)).dim(); - ( - "✔ ".green(), - vec![ - "You ".into(), - "approved".bold(), - " codex to run ".into(), - snippet, - " this time".bold(), - ], - ) - } - ApprovedForSession => { - let snippet = Span::from(exec_snippet(&command)).dim(); - ( - "✔ ".green(), - vec![ - "You ".into(), - "approved".bold(), - " codex to run ".into(), - snippet, - " every time this session".bold(), - ], - ) - } - Denied => { - let snippet = Span::from(exec_snippet(&command)).dim(); - ( - "✗ ".red(), - vec![ - "You ".into(), - "did not approve".bold(), - " codex to run ".into(), - snippet, - ], - ) - } - Abort => { - let snippet = Span::from(exec_snippet(&command)).dim(); - ( - "✗ ".red(), - vec![ - "You ".into(), - "canceled".bold(), - " the request to run ".into(), - snippet, - ], - ) - } - }; - - let mut lines = Vec::new(); - let mut spans = Vec::new(); - spans.push(symbol); - spans.extend(summary); - lines.push(Line::from(spans)); - Some(lines) -} - -fn truncate_exec_snippet(full_cmd: &str) -> String { - let mut snippet = match full_cmd.split_once('\n') { - Some((first, _)) => format!("{first} ..."), - None => full_cmd.to_string(), - }; - snippet = truncate_text(&snippet, 80); - snippet -} - -fn exec_snippet(command: &[String]) -> String { - let full_cmd = strip_bash_lc_and_escape(command); - truncate_exec_snippet(&full_cmd) -} - #[cfg(test)] mod tests { use super::*; use crate::app_event::AppEvent; + use pretty_assertions::assert_eq; use tokio::sync::mpsc::unbounded_channel; fn make_exec_request() -> ApprovalRequest { @@ -550,6 +466,34 @@ mod tests { ); } + #[test] + fn exec_history_cell_wraps_with_two_space_indent() { + let command = vec![ + "/bin/zsh".into(), + "-lc".into(), + "git add tui/src/render/mod.rs tui/src/render/renderable.rs".into(), + ]; + let cell = history_cell::new_approval_decision_cell(command, ReviewDecision::Approved); + let lines = cell.display_lines(28); + let rendered: Vec = lines + .iter() + .map(|line| { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + }) + .collect(); + let expected = vec![ + "✔ You approved codex to".to_string(), + " run /bin/zsh -lc 'git add".to_string(), + " tui/src/render/mod.rs tui/".to_string(), + " src/render/renderable.rs'".to_string(), + " this time".to_string(), + ]; + assert_eq!(rendered, expected); + } + #[test] fn enter_sets_last_selected_index_without_dismissing() { let (tx_raw, mut rx) = unbounded_channel::(); diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_aborted_long.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_aborted_long.snap index 524e096824..f04e1f078a 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_aborted_long.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_aborted_long.snap @@ -1,5 +1,7 @@ --- source: tui/src/chatwidget/tests.rs +assertion_line: 495 expression: lines_to_single_string(&aborted_long) --- -✗ You canceled the request to run echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... +✗ You canceled the request to run echo + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 151712b6b0..18a6c72d24 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -6,12 +6,15 @@ use crate::exec_cell::TOOL_CALL_MAX_LINES; use crate::exec_cell::output_lines; use crate::exec_cell::spinner; use crate::exec_command::relativize_to_home; +use crate::exec_command::strip_bash_lc_and_escape; use crate::markdown::MarkdownCitationContext; use crate::markdown::append_markdown; use crate::render::line_utils::line_to_static; use crate::render::line_utils::prefix_lines; +use crate::render::line_utils::push_owned_lines; use crate::style::user_message_style; use crate::text_formatting::format_and_truncate_tool_result; +use crate::text_formatting::truncate_text; use crate::ui_consts::LIVE_PREFIX_COLS; use crate::wrapping::RtOptions; use crate::wrapping::word_wrap_line; @@ -262,6 +265,126 @@ impl HistoryCell for PlainHistoryCell { } } +#[derive(Debug)] +pub(crate) struct PrefixedWrappedHistoryCell { + text: Text<'static>, + initial_prefix: Line<'static>, + subsequent_prefix: Line<'static>, +} + +impl PrefixedWrappedHistoryCell { + pub(crate) fn new( + text: impl Into>, + initial_prefix: impl Into>, + subsequent_prefix: impl Into>, + ) -> Self { + Self { + text: text.into(), + initial_prefix: initial_prefix.into(), + subsequent_prefix: subsequent_prefix.into(), + } + } +} + +impl HistoryCell for PrefixedWrappedHistoryCell { + fn display_lines(&self, width: u16) -> Vec> { + if width == 0 { + return Vec::new(); + } + let opts = RtOptions::new(width.max(1) as usize) + .initial_indent(self.initial_prefix.clone()) + .subsequent_indent(self.subsequent_prefix.clone()); + let wrapped = word_wrap_lines(&self.text, opts); + let mut out = Vec::new(); + push_owned_lines(&wrapped, &mut out); + out + } + + fn desired_height(&self, width: u16) -> u16 { + self.display_lines(width).len() as u16 + } +} + +fn truncate_exec_snippet(full_cmd: &str) -> String { + let mut snippet = match full_cmd.split_once('\n') { + Some((first, _)) => format!("{first} ..."), + None => full_cmd.to_string(), + }; + snippet = truncate_text(&snippet, 80); + snippet +} + +fn exec_snippet(command: &[String]) -> String { + let full_cmd = strip_bash_lc_and_escape(command); + truncate_exec_snippet(&full_cmd) +} + +pub fn new_approval_decision_cell( + command: Vec, + decision: codex_core::protocol::ReviewDecision, +) -> Box { + use codex_core::protocol::ReviewDecision::*; + + let (symbol, summary): (Span<'static>, Vec>) = match decision { + Approved => { + let snippet = Span::from(exec_snippet(&command)).dim(); + ( + "✔ ".green(), + vec![ + "You ".into(), + "approved".bold(), + " codex to run ".into(), + snippet, + " this time".bold(), + ], + ) + } + ApprovedForSession => { + let snippet = Span::from(exec_snippet(&command)).dim(); + ( + "✔ ".green(), + vec![ + "You ".into(), + "approved".bold(), + " codex to run ".into(), + snippet, + " every time this session".bold(), + ], + ) + } + Denied => { + let snippet = Span::from(exec_snippet(&command)).dim(); + ( + "✗ ".red(), + vec![ + "You ".into(), + "did not approve".bold(), + " codex to run ".into(), + snippet, + ], + ) + } + Abort => { + let snippet = Span::from(exec_snippet(&command)).dim(); + ( + "✗ ".red(), + vec![ + "You ".into(), + "canceled".bold(), + " the request to run ".into(), + snippet, + ], + ) + } + }; + + Box::new(PrefixedWrappedHistoryCell::new( + Line::from(summary), + symbol, + " ", + )) +} + /// Cyan history cell line showing the current review status. pub(crate) fn new_review_status_line(message: String) -> PlainHistoryCell { PlainHistoryCell { @@ -447,10 +570,6 @@ pub(crate) fn new_user_prompt(message: String) -> UserHistoryCell { UserHistoryCell { message } } -pub(crate) fn new_user_approval_decision(lines: Vec>) -> PlainHistoryCell { - PlainHistoryCell { lines } -} - #[derive(Debug)] struct SessionHeaderHistoryCell { version: &'static str, @@ -1203,6 +1322,29 @@ mod tests { assert_eq!(cell.desired_transcript_height(80), 1); } + #[test] + fn prefixed_wrapped_history_cell_indents_wrapped_lines() { + let summary = Line::from(vec![ + "You ".into(), + "approved".bold(), + " codex to run ".into(), + "echo something really long to ensure wrapping happens".dim(), + " this time".bold(), + ]); + let cell = PrefixedWrappedHistoryCell::new(summary, "✔ ".green(), " "); + let rendered = render_lines(&cell.display_lines(24)); + assert_eq!( + rendered, + vec![ + "✔ You approved codex".to_string(), + " to run echo something".to_string(), + " really long to ensure".to_string(), + " wrapping happens this".to_string(), + " time".to_string(), + ] + ); + } + #[test] fn active_mcp_tool_call_snapshot() { let invocation = McpInvocation { diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index 46c6c19a18..9395fb71dd 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -582,6 +582,7 @@ fn render_offset_content( #[cfg(test)] mod tests { use super::*; + use codex_core::protocol::ReviewDecision; use insta::assert_snapshot; use std::collections::HashMap; use std::path::PathBuf; @@ -589,6 +590,7 @@ mod tests { use std::time::Duration; use crate::exec_cell::CommandOutput; + use crate::history_cell; use crate::history_cell::HistoryCell; use crate::history_cell::new_patch_event; use codex_core::protocol::FileChange; @@ -712,10 +714,8 @@ mod tests { cells.push(apply_begin_cell); let apply_end_cell: Arc = - Arc::new(crate::history_cell::new_user_approval_decision(vec![ - "✓ Patch applied".green().bold().into(), - "src/foo.txt".dim().into(), - ])); + history_cell::new_approval_decision_cell(vec!["ls".into()], ReviewDecision::Approved) + .into(); cells.push(apply_end_cell); let mut exec_cell = crate::exec_cell::new_active_exec_command( From 95b41dd7f18b85a696758e3efe242c8880e9755a Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 9 Oct 2025 10:39:45 -0700 Subject: [PATCH 16/32] tui: fix wrapping in trust_directory (#5007) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refactor trust_directory to use ColumnRenderable & friends, thus correcting wrapping behavior at small widths. Also introduce RowRenderable with fixed-width rows. - fixed wrapping in trust_directory - changed selector cursor to match other list item selections - allow y/n to work as well as 1/2 - fixed key_hint to be standard before: Screenshot 2025-10-09 at 9 50 36 AM after: Screenshot 2025-10-09 at 9 51 31 AM --- .../tui/src/bottom_pane/approval_overlay.rs | 8 +- .../src/bottom_pane/list_selection_view.rs | 2 +- ...exec_and_status_layout_vt100_snapshot.snap | 1 + codex-rs/tui/src/diff_render.rs | 2 +- ..._tests__renders_snapshot_for_git_repo.snap | 14 ++ .../tui/src/onboarding/trust_directory.rs | 171 ++++++++++++------ codex-rs/tui/src/render/mod.rs | 8 +- codex-rs/tui/src/render/renderable.rs | 78 +++++++- codex-rs/tui/src/test_backend.rs | 3 +- codex-rs/tui/src/wrapping.rs | 1 + 10 files changed, 220 insertions(+), 68 deletions(-) create mode 100644 codex-rs/tui/src/onboarding/snapshots/codex_tui__onboarding__trust_directory__tests__renders_snapshot_for_git_repo.snap diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index d6e96cf78d..ce0e3c9c95 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -104,9 +104,9 @@ impl ApprovalOverlay { ), }; - let header = Box::new(ColumnRenderable::new([ - Box::new(Line::from(title.bold())), - Box::new(Line::from("")), + let header = Box::new(ColumnRenderable::with([ + Line::from(title.bold()).into(), + Line::from("").into(), header, ])); @@ -323,7 +323,7 @@ impl From for ApprovalRequestState { header.push(DiffSummary::new(changes, cwd).into()); Self { variant: ApprovalVariant::ApplyPatch { id }, - header: Box::new(ColumnRenderable::new(header)), + header: Box::new(ColumnRenderable::with(header)), } } } diff --git a/codex-rs/tui/src/bottom_pane/list_selection_view.rs b/codex-rs/tui/src/bottom_pane/list_selection_view.rs index 238f74d6e4..1e8d1983b0 100644 --- a/codex-rs/tui/src/bottom_pane/list_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/list_selection_view.rs @@ -87,7 +87,7 @@ impl ListSelectionView { if params.title.is_some() || params.subtitle.is_some() { let title = params.title.map(|title| Line::from(title.bold())); let subtitle = params.subtitle.map(|subtitle| Line::from(subtitle.dim())); - header = Box::new(ColumnRenderable::new([ + header = Box::new(ColumnRenderable::with([ header, Box::new(title), Box::new(subtitle), diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap index f913ce0898..c3bdf60bd2 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap @@ -13,4 +13,5 @@ expression: term.backend().vt100().screen().contents() › Summarize recent commits + 100% context left diff --git a/codex-rs/tui/src/diff_render.rs b/codex-rs/tui/src/diff_render.rs index a4b7c87f73..665fad15f7 100644 --- a/codex-rs/tui/src/diff_render.rs +++ b/codex-rs/tui/src/diff_render.rs @@ -72,7 +72,7 @@ impl From for Box { ))); } - Box::new(ColumnRenderable::new(rows)) + Box::new(ColumnRenderable::with(rows)) } } diff --git a/codex-rs/tui/src/onboarding/snapshots/codex_tui__onboarding__trust_directory__tests__renders_snapshot_for_git_repo.snap b/codex-rs/tui/src/onboarding/snapshots/codex_tui__onboarding__trust_directory__tests__renders_snapshot_for_git_repo.snap new file mode 100644 index 0000000000..71cbc3d6ea --- /dev/null +++ b/codex-rs/tui/src/onboarding/snapshots/codex_tui__onboarding__trust_directory__tests__renders_snapshot_for_git_repo.snap @@ -0,0 +1,14 @@ +--- +source: tui/src/onboarding/trust_directory.rs +expression: terminal.backend() +--- +> You are running Codex in /workspace/project + + Since this folder is version controlled, you may wish to allow Codex + to work in this folder without asking for approval. + +› 1. Yes, allow Codex to work in this folder without asking for + approval + 2. No, ask me to approve edits and commands + + Press enter to continue diff --git a/codex-rs/tui/src/onboarding/trust_directory.rs b/codex-rs/tui/src/onboarding/trust_directory.rs index 1058208bee..3324c3d866 100644 --- a/codex-rs/tui/src/onboarding/trust_directory.rs +++ b/codex-rs/tui/src/onboarding/trust_directory.rs @@ -7,19 +7,25 @@ use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; use ratatui::buffer::Buffer; use ratatui::layout::Rect; -use ratatui::prelude::Widget; -use ratatui::style::Color; -use ratatui::style::Modifier; +use ratatui::style::Style; +use ratatui::style::Styled as _; use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::widgets::Paragraph; use ratatui::widgets::WidgetRef; use ratatui::widgets::Wrap; +use crate::key_hint; use crate::onboarding::onboarding_screen::KeyboardHandler; use crate::onboarding::onboarding_screen::StepStateProvider; +use crate::render::Insets; +use crate::render::renderable::ColumnRenderable; +use crate::render::renderable::Renderable; +use crate::render::renderable::RenderableExt as _; +use crate::render::renderable::RowRenderable; use super::onboarding_screen::StepState; +use unicode_width::UnicodeWidthStr; pub(crate) struct TrustDirectoryWidget { pub codex_home: PathBuf, @@ -38,76 +44,106 @@ pub enum TrustDirectorySelection { impl WidgetRef for &TrustDirectoryWidget { fn render_ref(&self, area: Rect, buf: &mut Buffer) { - let mut lines: Vec = vec![ - Line::from(vec![ - "> ".into(), - "You are running Codex in ".bold(), - self.cwd.to_string_lossy().to_string().into(), - ]), - "".into(), - ]; + let mut column = ColumnRenderable::new(); - if self.is_git_repo { - lines.push( - " Since this folder is version controlled, you may wish to allow Codex".into(), - ); - lines.push(" to work in this folder without asking for approval.".into()); + column.push(Line::from(vec![ + "> ".into(), + "You are running Codex in ".bold(), + self.cwd.to_string_lossy().to_string().into(), + ])); + column.push(""); + + let guidance = if self.is_git_repo { + "Since this folder is version controlled, you may wish to allow Codex to work in this folder without asking for approval." } else { - lines.push( - " Since this folder is not version controlled, we recommend requiring".into(), - ); - lines.push(" approval of all edits and commands.".into()); - } - lines.push("".into()); + "Since this folder is not version controlled, we recommend requiring approval of all edits and commands." + }; - let create_option = - |idx: usize, option: TrustDirectorySelection, text: &str| -> Line<'static> { - let is_selected = self.highlighted == option; - if is_selected { - Line::from(format!("> {}. {text}", idx + 1)).cyan() - } else { - Line::from(format!(" {}. {}", idx + 1, text)) - } - }; + column.push( + Paragraph::new(guidance.to_string()) + .wrap(Wrap { trim: true }) + .inset(Insets::tlbr(0, 2, 0, 0)), + ); + column.push(""); + let mut options: Vec<(&str, TrustDirectorySelection)> = Vec::new(); if self.is_git_repo { - lines.push(create_option( - 0, - TrustDirectorySelection::Trust, + options.push(( "Yes, allow Codex to work in this folder without asking for approval", + TrustDirectorySelection::Trust, )); - lines.push(create_option( - 1, - TrustDirectorySelection::DontTrust, + options.push(( "No, ask me to approve edits and commands", + TrustDirectorySelection::DontTrust, )); } else { - lines.push(create_option( - 0, - TrustDirectorySelection::Trust, + options.push(( "Allow Codex to work in this folder without asking for approval", + TrustDirectorySelection::Trust, )); - lines.push(create_option( - 1, - TrustDirectorySelection::DontTrust, + options.push(( "Require approval of edits and commands", + TrustDirectorySelection::DontTrust, )); } - lines.push("".into()); - if let Some(error) = &self.error { - lines.push(Line::from(format!(" {error}")).fg(Color::Red)); - lines.push("".into()); - } - // AE: Following styles.md, this should probably be Cyan because it's a user input tip. - // But leaving this for a future cleanup. - lines.push(Line::from(" Press Enter to continue").add_modifier(Modifier::DIM)); - Paragraph::new(lines) - .wrap(Wrap { trim: false }) - .render(area, buf); + for (idx, (text, selection)) in options.iter().enumerate() { + column.push(new_option_row( + idx, + text.to_string(), + self.highlighted == *selection, + )); + } + + column.push(""); + + if let Some(error) = &self.error { + column.push( + Paragraph::new(error.to_string()) + .red() + .wrap(Wrap { trim: true }) + .inset(Insets::tlbr(0, 2, 0, 0)), + ); + column.push(""); + } + + column.push( + Line::from(vec![ + "Press ".dim(), + key_hint::plain(KeyCode::Enter).into(), + " to continue".dim(), + ]) + .inset(Insets::tlbr(0, 2, 0, 0)), + ); + + column.render(area, buf); } } +fn new_option_row(index: usize, label: String, is_selected: bool) -> Box { + let prefix = if is_selected { + format!("› {}. ", index + 1) + } else { + format!(" {}. ", index + 1) + }; + + let mut style = Style::default(); + if is_selected { + style = style.cyan(); + } + + let mut row = RowRenderable::new(); + row.push(prefix.width() as u16, prefix.set_style(style)); + row.push( + u16::MAX, + Paragraph::new(label) + .style(style) + .wrap(Wrap { trim: false }), + ); + + row.into() +} + impl KeyboardHandler for TrustDirectoryWidget { fn handle_key_event(&mut self, key_event: KeyEvent) { if key_event.kind == KeyEventKind::Release { @@ -121,8 +157,8 @@ impl KeyboardHandler for TrustDirectoryWidget { KeyCode::Down | KeyCode::Char('j') => { self.highlighted = TrustDirectorySelection::DontTrust; } - KeyCode::Char('1') => self.handle_trust(), - KeyCode::Char('2') => self.handle_dont_trust(), + KeyCode::Char('1') | KeyCode::Char('y') => self.handle_trust(), + KeyCode::Char('2') | KeyCode::Char('n') => self.handle_dont_trust(), KeyCode::Enter => match self.highlighted { TrustDirectorySelection::Trust => self.handle_trust(), TrustDirectorySelection::DontTrust => self.handle_dont_trust(), @@ -161,12 +197,16 @@ impl TrustDirectoryWidget { #[cfg(test)] mod tests { + use crate::test_backend::VT100Backend; + use super::*; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; use crossterm::event::KeyModifiers; use pretty_assertions::assert_eq; + use ratatui::Terminal; + use std::path::PathBuf; #[test] @@ -191,4 +231,23 @@ mod tests { widget.handle_key_event(press); assert_eq!(widget.selection, Some(TrustDirectorySelection::DontTrust)); } + + #[test] + fn renders_snapshot_for_git_repo() { + let widget = TrustDirectoryWidget { + codex_home: PathBuf::from("."), + cwd: PathBuf::from("/workspace/project"), + is_git_repo: true, + selection: None, + highlighted: TrustDirectorySelection::Trust, + error: None, + }; + + let mut terminal = Terminal::new(VT100Backend::new(70, 14)).expect("terminal"); + terminal + .draw(|f| (&widget).render_ref(f.area(), f.buffer_mut())) + .expect("draw"); + + insta::assert_snapshot!(terminal.backend()); + } } diff --git a/codex-rs/tui/src/render/mod.rs b/codex-rs/tui/src/render/mod.rs index bf4fb553c5..a2e4920586 100644 --- a/codex-rs/tui/src/render/mod.rs +++ b/codex-rs/tui/src/render/mod.rs @@ -6,10 +6,10 @@ pub mod renderable; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Insets { - pub left: u16, - pub top: u16, - pub right: u16, - pub bottom: u16, + left: u16, + top: u16, + right: u16, + bottom: u16, } impl Insets { diff --git a/codex-rs/tui/src/render/renderable.rs b/codex-rs/tui/src/render/renderable.rs index 62c2720685..df06449555 100644 --- a/codex-rs/tui/src/render/renderable.rs +++ b/codex-rs/tui/src/render/renderable.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::text::Line; +use ratatui::text::Span; use ratatui::widgets::Paragraph; use ratatui::widgets::WidgetRef; @@ -45,6 +46,15 @@ impl Renderable for String { } } +impl<'a> Renderable for Span<'a> { + fn render(&self, area: Rect, buf: &mut Buffer) { + self.render_ref(area, buf); + } + fn desired_height(&self, _width: u16) -> u16 { + 1 + } +} + impl<'a> Renderable for Line<'a> { fn render(&self, area: Rect, buf: &mut Buffer) { WidgetRef::render_ref(self, area, buf); @@ -114,11 +124,64 @@ impl Renderable for ColumnRenderable { } impl ColumnRenderable { - pub fn new(children: impl IntoIterator>) -> Self { + pub fn new() -> Self { + Self::with(vec![]) + } + + pub fn with(children: impl IntoIterator>) -> Self { Self { children: children.into_iter().collect(), } } + + pub fn push(&mut self, child: impl Into>) { + self.children.push(child.into()); + } +} + +pub struct RowRenderable { + children: Vec<(u16, Box)>, +} + +impl Renderable for RowRenderable { + fn render(&self, area: Rect, buf: &mut Buffer) { + let mut x = area.x; + for (width, child) in &self.children { + let available_width = area.width.saturating_sub(x - area.x); + let child_area = Rect::new(x, area.y, (*width).min(available_width), area.height); + if child_area.is_empty() { + break; + } + child.render(child_area, buf); + x = x.saturating_add(*width); + } + } + fn desired_height(&self, width: u16) -> u16 { + let mut max_height = 0; + let mut width_remaining = width; + for (child_width, child) in &self.children { + let w = (*child_width).min(width_remaining); + if w == 0 { + break; + } + let height = child.desired_height(w); + if height > max_height { + max_height = height; + } + width_remaining = width_remaining.saturating_sub(w); + } + max_height + } +} + +impl RowRenderable { + pub fn new() -> Self { + Self { children: vec![] } + } + + pub fn push(&mut self, width: u16, child: impl Into>) { + self.children.push((width, child.into())); + } } pub struct InsetRenderable { @@ -146,3 +209,16 @@ impl InsetRenderable { } } } + +pub trait RenderableExt { + fn inset(self, insets: Insets) -> Box; +} + +impl>> RenderableExt for R { + fn inset(self, insets: Insets) -> Box { + Box::new(InsetRenderable { + child: self.into(), + insets, + }) + } +} diff --git a/codex-rs/tui/src/test_backend.rs b/codex-rs/tui/src/test_backend.rs index 52e7254711..a5460af2e0 100644 --- a/codex-rs/tui/src/test_backend.rs +++ b/codex-rs/tui/src/test_backend.rs @@ -91,7 +91,8 @@ impl Backend for VT100Backend { } fn size(&self) -> io::Result { - Ok(self.vt100().screen().size().into()) + let (rows, cols) = self.vt100().screen().size(); + Ok(Size::new(cols, rows)) } fn window_size(&mut self) -> io::Result { diff --git a/codex-rs/tui/src/wrapping.rs b/codex-rs/tui/src/wrapping.rs index 70ca2e46ca..3c3b775eb6 100644 --- a/codex-rs/tui/src/wrapping.rs +++ b/codex-rs/tui/src/wrapping.rs @@ -154,6 +154,7 @@ impl<'a> RtOptions<'a> { } } +#[must_use] pub(crate) fn word_wrap_line<'a, O>(line: &'a Line<'a>, width_or_options: O) -> Vec> where O: Into>, From 56296cad8275b96da0713ee63cda034763a9d42d Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 9 Oct 2025 14:01:45 -0700 Subject: [PATCH 17/32] tui: /diff mode wraps long lines (#4891) fixes a regression that stopped long lines from being wrapped when viewing `/diff`. --- codex-rs/tui/src/pager_overlay.rs | 33 ++++++++++++------- ...ests__static_overlay_wraps_long_lines.snap | 13 ++++++++ 2 files changed, 34 insertions(+), 12 deletions(-) create mode 100644 codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_wraps_long_lines.snap diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index 9395fb71dd..84c325b6cb 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -26,6 +26,7 @@ use ratatui::widgets::Clear; use ratatui::widgets::Paragraph; use ratatui::widgets::Widget; use ratatui::widgets::WidgetRef; +use ratatui::widgets::Wrap; pub(crate) enum Overlay { Transcript(TranscriptOverlay), @@ -329,9 +330,9 @@ struct CachedRenderable { } impl CachedRenderable { - fn new(renderable: Box) -> Self { + fn new(renderable: impl Into>) -> Self { Self { - renderable, + renderable: renderable.into(), height: std::cell::Cell::new(None), last_width: std::cell::Cell::new(None), } @@ -400,19 +401,19 @@ impl TranscriptOverlay { .flat_map(|(i, c)| { let mut v: Vec> = Vec::new(); let mut cell_renderable = if c.as_any().is::() { - Box::new(CachedRenderable::new(Box::new(CellRenderable { + Box::new(CachedRenderable::new(CellRenderable { cell: c.clone(), style: if highlight_cell == Some(i) { user_message_style().reversed() } else { user_message_style() }, - }))) as Box + })) as Box } else { - Box::new(CachedRenderable::new(Box::new(CellRenderable { + Box::new(CachedRenderable::new(CellRenderable { cell: c.clone(), style: Style::default(), - }))) as Box + })) as Box }; if !c.is_stream_continuation() && i > 0 { cell_renderable = Box::new(InsetRenderable::new( @@ -496,12 +497,8 @@ pub(crate) struct StaticOverlay { impl StaticOverlay { pub(crate) fn with_title(lines: Vec>, title: String) -> Self { - Self::with_renderables( - vec![Box::new(CachedRenderable::new(Box::new(Paragraph::new( - Text::from(lines), - ))))], - title, - ) + let paragraph = Paragraph::new(Text::from(lines)).wrap(Wrap { trim: false }); + Self::with_renderables(vec![Box::new(CachedRenderable::new(paragraph))], title) } pub(crate) fn with_renderables(renderables: Vec>, title: String) -> Self { @@ -812,6 +809,18 @@ mod tests { assert_snapshot!(term.backend()); } + #[test] + fn static_overlay_wraps_long_lines() { + let mut overlay = StaticOverlay::with_title( + vec!["a very long line that should wrap when rendered within a narrow pager overlay width".into()], + "S T A T I C".to_string(), + ); + let mut term = Terminal::new(TestBackend::new(24, 8)).expect("term"); + term.draw(|f| overlay.render(f.area(), f.buffer_mut())) + .expect("draw"); + assert_snapshot!(term.backend()); + } + #[test] fn pager_view_content_height_counts_renderables() { let pv = PagerView::new( diff --git a/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_wraps_long_lines.snap b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_wraps_long_lines.snap new file mode 100644 index 0000000000..2dfab2aa7d --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_wraps_long_lines.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/pager_overlay.rs +assertion_line: 798 +expression: term.backend() +--- +"/ S T A T I C / / / / / " +"a very long line that " +"should wrap when " +"rendered within a narrow" +"─────────────────── 0% ─" +" ↑/↓ to scroll pgup/pg" +" q to quit " +" " From ddcaf3dccd7a817b6307bff61a4604c4dff27621 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 9 Oct 2025 15:07:04 -0700 Subject: [PATCH 18/32] tui: fix crash when alt+bksp past unicode nbsp (#5016) notably, screenshot filenames on macOS by default contain U+202F right before the "AM/PM" part of the filename. --- codex-rs/tui/src/bottom_pane/textarea.rs | 35 +++++++++++++++++------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/textarea.rs b/codex-rs/tui/src/bottom_pane/textarea.rs index 269fa345e0..6687793979 100644 --- a/codex-rs/tui/src/bottom_pane/textarea.rs +++ b/codex-rs/tui/src/bottom_pane/textarea.rs @@ -799,16 +799,22 @@ impl TextArea { } pub(crate) fn beginning_of_previous_word(&self) -> usize { - if let Some(first_non_ws) = self.text[..self.cursor_pos].rfind(|c: char| !c.is_whitespace()) - { - let candidate = self.text[..first_non_ws] - .rfind(|c: char| c.is_whitespace()) - .map(|i| i + 1) - .unwrap_or(0); - self.adjust_pos_out_of_elements(candidate, true) - } else { - 0 - } + let prefix = &self.text[..self.cursor_pos]; + let Some((first_non_ws_idx, _)) = prefix + .char_indices() + .rev() + .find(|&(_, ch)| !ch.is_whitespace()) + else { + return 0; + }; + let before = &prefix[..first_non_ws_idx]; + let candidate = before + .char_indices() + .rev() + .find(|&(_, ch)| ch.is_whitespace()) + .map(|(idx, ch)| idx + ch.len_utf8()) + .unwrap_or(0); + self.adjust_pos_out_of_elements(candidate, true) } pub(crate) fn end_of_next_word(&self) -> usize { @@ -1262,6 +1268,15 @@ mod tests { assert_eq!(t.cursor(), 6); } + #[test] + fn delete_backward_word_handles_narrow_no_break_space() { + let mut t = ta_with("32\u{202F}AM"); + t.set_cursor(t.text().len()); + t.input(KeyEvent::new(KeyCode::Backspace, KeyModifiers::ALT)); + pretty_assertions::assert_eq!(t.text(), "32\u{202F}"); + pretty_assertions::assert_eq!(t.cursor(), t.text().len()); + } + #[test] fn delete_forward_word_with_without_alt_modifier() { let mut t = ta_with("hello world"); From f98fa85b448d4cb0d6e0b5cb04e7fec2876ff2bf Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 10 Oct 2025 10:07:14 +0100 Subject: [PATCH 19/32] feat: message when stream get correctly resumed (#4988) Screenshot 2025-10-09 at 17 44 16 --- codex-rs/core/src/codex.rs | 4 +-- codex-rs/core/src/codex/compact.rs | 4 +-- codex-rs/protocol/src/protocol.rs | 5 ++++ codex-rs/tui/src/chatwidget.rs | 27 ++++++++++++++++++--- codex-rs/tui/src/chatwidget/tests.rs | 21 ++++++++++------ codex-rs/tui/src/history_cell.rs | 5 ---- codex-rs/tui/src/status_indicator_widget.rs | 5 ++++ 7 files changed, 49 insertions(+), 22 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index cae47cb322..fe352f0103 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -2008,9 +2008,7 @@ async fn run_turn( // at a seemingly frozen screen. sess.notify_stream_error( &sub_id, - format!( - "stream error: {e}; retrying {retries}/{max_retries} in {delay:?}…" - ), + format!("Re-connecting... {retries}/{max_retries}"), ) .await; diff --git a/codex-rs/core/src/codex/compact.rs b/codex-rs/core/src/codex/compact.rs index d35df99c8d..d43e3abcbb 100644 --- a/codex-rs/core/src/codex/compact.rs +++ b/codex-rs/core/src/codex/compact.rs @@ -136,9 +136,7 @@ async fn run_compact_task_inner( let delay = backoff(retries); sess.notify_stream_error( &sub_id, - format!( - "stream error: {e}; retrying {retries}/{max_retries} in {delay:?}…" - ), + format!("Re-connecting... {retries}/{max_retries}"), ) .await; tokio::time::sleep(delay).await; diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 1ae32e5122..b73909473d 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -1203,6 +1203,11 @@ pub struct StreamErrorEvent { pub message: String, } +#[derive(Debug, Clone, Deserialize, Serialize, TS)] +pub struct StreamInfoEvent { + pub message: String, +} + #[derive(Debug, Clone, Deserialize, Serialize, TS)] pub struct PatchApplyBeginEvent { /// Identifier so this can be paired with the PatchApplyEnd event. diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 973b0e3ba2..aeaf239f32 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -240,6 +240,10 @@ pub(crate) struct ChatWidget { reasoning_buffer: String, // Accumulates full reasoning content for transcript-only recording full_reasoning_buffer: String, + // Current status header shown in the status indicator. + current_status_header: String, + // Previous status header to restore after a transient stream retry. + retry_status_header: Option, conversation_id: Option, frame_requester: FrameRequester, // Whether to include the initial welcome banner on session configured @@ -303,6 +307,14 @@ impl ChatWidget { } } + fn set_status_header(&mut self, header: String) { + if self.current_status_header == header { + return; + } + self.current_status_header = header.clone(); + self.bottom_pane.update_status_header(header); + } + // --- Small event handlers --- fn on_session_configured(&mut self, event: codex_core::protocol::SessionConfiguredEvent) { self.bottom_pane @@ -352,7 +364,7 @@ impl ChatWidget { if let Some(header) = extract_first_bold(&self.reasoning_buffer) { // Update the shimmer header to the extracted reasoning chunk header. - self.bottom_pane.update_status_header(header); + self.set_status_header(header); } else { // Fallback while we don't yet have a bold header: leave existing header as-is. } @@ -386,6 +398,8 @@ impl ChatWidget { fn on_task_started(&mut self) { self.bottom_pane.clear_ctrl_c_quit_hint(); self.bottom_pane.set_task_running(true); + self.retry_status_header = None; + self.set_status_header(String::from("Working")); self.full_reasoning_buffer.clear(); self.reasoning_buffer.clear(); self.request_redraw(); @@ -621,9 +635,10 @@ impl ChatWidget { } fn on_stream_error(&mut self, message: String) { - // Show stream errors in the transcript so users see retry/backoff info. - self.add_to_history(history_cell::new_stream_error_event(message)); - self.request_redraw(); + if self.retry_status_header.is_none() { + self.retry_status_header = Some(self.current_status_header.clone()); + } + self.set_status_header(message); } /// Periodic tick to commit at most one queued line to history with a small delay, @@ -928,6 +943,8 @@ impl ChatWidget { interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), + current_status_header: String::from("Working"), + retry_status_header: None, conversation_id: None, queued_user_messages: VecDeque::new(), show_welcome_banner: true, @@ -991,6 +1008,8 @@ impl ChatWidget { interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), + current_status_header: String::from("Working"), + retry_status_header: None, conversation_id: None, queued_user_messages: VecDeque::new(), show_welcome_banner: true, diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 2055445059..d4cf4c7b20 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -276,6 +276,8 @@ fn make_chatwidget_manual() -> ( interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), + current_status_header: String::from("Working"), + retry_status_header: None, conversation_id: None, frame_requester: FrameRequester::test_dummy(), show_welcome_banner: true, @@ -2044,9 +2046,10 @@ fn plan_update_renders_history_cell() { } #[test] -fn stream_error_is_rendered_to_history() { +fn stream_error_updates_status_indicator() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); - let msg = "stream error: stream disconnected before completion: idle timeout waiting for SSE; retrying 1/5 in 211ms…"; + chat.bottom_pane.set_task_running(true); + let msg = "Re-connecting... 2/5"; chat.handle_codex_event(Event { id: "sub-1".into(), msg: EventMsg::StreamError(StreamErrorEvent { @@ -2055,11 +2058,15 @@ fn stream_error_is_rendered_to_history() { }); let cells = drain_insert_history(&mut rx); - assert!(!cells.is_empty(), "expected a history cell for StreamError"); - let blob = lines_to_single_string(cells.last().unwrap()); - assert!(blob.contains('⚠')); - assert!(blob.contains("stream error:")); - assert!(blob.contains("idle timeout waiting for SSE")); + assert!( + cells.is_empty(), + "expected no history cell for StreamError event" + ); + let status = chat + .bottom_pane + .status_widget() + .expect("status indicator should be visible"); + assert_eq!(status.header(), msg); } #[test] diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 18a6c72d24..aa0ae35d92 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -1062,11 +1062,6 @@ pub(crate) fn new_error_event(message: String) -> PlainHistoryCell { PlainHistoryCell { lines } } -pub(crate) fn new_stream_error_event(message: String) -> PlainHistoryCell { - let lines: Vec> = vec![vec![padded_emoji("⚠️").into(), message.dim()].into()]; - PlainHistoryCell { lines } -} - /// Render a user‑friendly plan update styled like a checkbox todo list. pub(crate) fn new_plan_update(update: UpdatePlanArgs) -> PlanUpdateCell { let UpdatePlanArgs { explanation, plan } = update; diff --git a/codex-rs/tui/src/status_indicator_widget.rs b/codex-rs/tui/src/status_indicator_widget.rs index ce4f6eabd8..4bcc5cf267 100644 --- a/codex-rs/tui/src/status_indicator_widget.rs +++ b/codex-rs/tui/src/status_indicator_widget.rs @@ -103,6 +103,11 @@ impl StatusIndicatorWidget { } } + #[cfg(test)] + pub(crate) fn header(&self) -> &str { + &self.header + } + /// Replace the queued messages displayed beneath the header. pub(crate) fn set_queued_messages(&mut self, queued: Vec) { self.queued_messages = queued; From 85e735797366b7272cd36cd81b7fd5aff8418d86 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 10 Oct 2025 14:57:47 +0100 Subject: [PATCH 20/32] fix: workflow cache (#5050) Decouple cache saving to fix the `verify` steps never being run due to a cache saving issue --- .github/workflows/rust-ci.yml | 42 +++++++++++++++++++++-- codex-rs/core/tests/suite/unified_exec.rs | 2 +- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index 846408f3a8..cbf62f72f0 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -148,15 +148,26 @@ jobs: targets: ${{ matrix.target }} components: clippy - - uses: actions/cache@v4 + # Explicit cache restore: split cargo home vs target, so we can + # avoid caching the large target dir on the gnu-dev job. + - name: Restore cargo home cache + id: cache_cargo_home_restore + uses: actions/cache/restore@v4 with: path: | ~/.cargo/bin/ ~/.cargo/registry/index/ ~/.cargo/registry/cache/ ~/.cargo/git/db/ - ${{ github.workspace }}/codex-rs/target/ - key: cargo-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}-${{ hashFiles('**/Cargo.lock') }} + key: cargo-home-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}-${{ hashFiles('**/Cargo.lock') }} + + - name: Restore target cache (except gnu-dev) + id: cache_target_restore + if: ${{ !(matrix.target == 'x86_64-unknown-linux-gnu' && matrix.profile != 'release') }} + uses: actions/cache/restore@v4 + with: + path: ${{ github.workspace }}/codex-rs/target/ + key: cargo-target-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}-${{ hashFiles('**/Cargo.lock') }} - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} name: Install musl build tools @@ -194,6 +205,31 @@ jobs: env: RUST_BACKTRACE: 1 + # Save caches explicitly; make non-fatal so cache packaging + # never fails the overall job. Only save when key wasn't hit. + - name: Save cargo home cache + if: always() && !cancelled() && steps.cache_cargo_home_restore.outputs.cache-hit != 'true' + continue-on-error: true + uses: actions/cache/save@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + key: cargo-home-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}-${{ hashFiles('**/Cargo.lock') }} + + - name: Save target cache (except gnu-dev) + if: >- + always() && !cancelled() && + (steps.cache_target_restore.outputs.cache-hit != 'true') && + !(matrix.target == 'x86_64-unknown-linux-gnu' && matrix.profile != 'release') + continue-on-error: true + uses: actions/cache/save@v4 + with: + path: ${{ github.workspace }}/codex-rs/target/ + key: cargo-target-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}-${{ hashFiles('**/Cargo.lock') }} + # Fail the job if any of the previous steps failed. - name: verify all steps passed if: | diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index b8c0fadbbe..cfa96dd75c 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -213,7 +213,7 @@ PY let second_args = serde_json::json!({ "input": Vec::::new(), "session_id": "0", - "timeout_ms": 800, + "timeout_ms": 2_000, }); let responses = vec![ From 961ed31901b00e60241e54c0b2f1646048473043 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 10 Oct 2025 15:35:28 +0100 Subject: [PATCH 21/32] feat: make shortcut works even with capslock (#5049) Shortcut where not working in caps-lock. Fixing this --- codex-rs/core/tests/suite/shell_serialization.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 12 ++++++------ codex-rs/tui/src/chatwidget/tests.rs | 12 ++++++++++++ 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/codex-rs/core/tests/suite/shell_serialization.rs b/codex-rs/core/tests/suite/shell_serialization.rs index 67fc2786ca..fd9c26d882 100644 --- a/codex-rs/core/tests/suite/shell_serialization.rs +++ b/codex-rs/core/tests/suite/shell_serialization.rs @@ -213,7 +213,7 @@ async fn shell_output_reserializes_truncated_content() -> Result<()> { let call_id = "shell-truncated"; let args = json!({ "command": ["/bin/sh", "-c", "seq 1 400"], - "timeout_ms": 1_000, + "timeout_ms": 5_000, }); let responses = vec![ sse(vec![ diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index aeaf239f32..787e098093 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1034,20 +1034,20 @@ impl ChatWidget { pub(crate) fn handle_key_event(&mut self, key_event: KeyEvent) { match key_event { KeyEvent { - code: KeyCode::Char('c'), - modifiers: crossterm::event::KeyModifiers::CONTROL, + code: KeyCode::Char(c), + modifiers, kind: KeyEventKind::Press, .. - } => { + } if modifiers.contains(KeyModifiers::CONTROL) && c.eq_ignore_ascii_case(&'c') => { self.on_ctrl_c(); return; } KeyEvent { - code: KeyCode::Char('v'), - modifiers: KeyModifiers::CONTROL, + code: KeyCode::Char(c), + modifiers, kind: KeyEventKind::Press, .. - } => { + } if modifiers.contains(KeyModifiers::CONTROL) && c.eq_ignore_ascii_case(&'v') => { if let Ok((path, info)) = paste_image_to_temp_png() { self.attach_image(path, info.width, info.height, info.encoded_format.label()); } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index d4cf4c7b20..3bfdf243bc 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -676,6 +676,18 @@ fn streaming_final_answer_keeps_task_running_state() { assert!(chat.bottom_pane.ctrl_c_quit_hint_visible()); } +#[test] +fn ctrl_c_shutdown_ignores_caps_lock() { + let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(); + + chat.handle_key_event(KeyEvent::new(KeyCode::Char('C'), KeyModifiers::CONTROL)); + + match op_rx.try_recv() { + Ok(Op::Shutdown) => {} + other => panic!("expected Op::Shutdown, got {other:?}"), + } +} + #[test] fn exec_history_cell_shows_working_then_completed() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); From 90af046c5c08da705cf7a99adc7b7b4ffd7e8daf Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Fri, 10 Oct 2025 09:56:18 -0700 Subject: [PATCH 22/32] tui: include the image name in the textarea placeholder (#5056) Fixes #5013 --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 46 ++++++++++++++----- 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 7aa6e66958..3cd38e8de9 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -319,8 +319,12 @@ impl ChatComposer { } /// Attempt to start a burst by retro-capturing recent chars before the cursor. - pub fn attach_image(&mut self, path: PathBuf, width: u32, height: u32, format_label: &str) { - let placeholder = format!("[image {width}x{height} {format_label}]"); + pub fn attach_image(&mut self, path: PathBuf, width: u32, height: u32, _format_label: &str) { + let file_label = path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| "image".to_string()); + let placeholder = format!("[{file_label} {width}x{height}]"); // Insert as an element to match large paste placeholder behavior: // styled distinctly and treated atomically for cursor/mutations. self.textarea.insert_element(&placeholder); @@ -2581,7 +2585,7 @@ mod tests { let (result, _) = composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); match result { - InputResult::Submitted(text) => assert_eq!(text, "[image 32x16 PNG] hi"), + InputResult::Submitted(text) => assert_eq!(text, "[image1.png 32x16] hi"), _ => panic!("expected Submitted"), } let imgs = composer.take_recent_submission_images(); @@ -2604,7 +2608,7 @@ mod tests { let (result, _) = composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); match result { - InputResult::Submitted(text) => assert_eq!(text, "[image 10x5 PNG]"), + InputResult::Submitted(text) => assert_eq!(text, "[image2.png 10x5]"), _ => panic!("expected Submitted"), } let imgs = composer.take_recent_submission_images(); @@ -2677,7 +2681,12 @@ mod tests { composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); assert_eq!(composer.attached_images.len(), 1); - assert!(composer.textarea.text().starts_with("[image 10x5 PNG]")); + assert!( + composer + .textarea + .text() + .starts_with("[image_multibyte.png 10x5]") + ); } #[test] @@ -2700,21 +2709,31 @@ mod tests { composer.handle_paste(" ".into()); composer.attach_image(path2.clone(), 10, 5, "PNG"); - let ph = composer.attached_images[0].placeholder.clone(); + let placeholder1 = composer.attached_images[0].placeholder.clone(); + let placeholder2 = composer.attached_images[1].placeholder.clone(); let text = composer.textarea.text().to_string(); - let start1 = text.find(&ph).expect("first placeholder present"); - let end1 = start1 + ph.len(); + let start1 = text.find(&placeholder1).expect("first placeholder present"); + let end1 = start1 + placeholder1.len(); composer.textarea.set_cursor(end1); // Backspace should delete the first placeholder and its mapping. composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); let new_text = composer.textarea.text().to_string(); - assert_eq!(1, new_text.matches(&ph).count(), "one placeholder remains"); + assert_eq!( + 0, + new_text.matches(&placeholder1).count(), + "first placeholder removed" + ); + assert_eq!( + 1, + new_text.matches(&placeholder2).count(), + "second placeholder remains" + ); assert_eq!( vec![AttachedImage { path: path2, - placeholder: "[image 10x5 PNG]".to_string() + placeholder: "[image_dup2.png 10x5]".to_string() }], composer.attached_images, "one image mapping remains" @@ -2741,7 +2760,12 @@ mod tests { let needs_redraw = composer.handle_paste(tmp_path.to_string_lossy().to_string()); assert!(needs_redraw); - assert!(composer.textarea.text().starts_with("[image 3x2 PNG] ")); + assert!( + composer + .textarea + .text() + .starts_with("[codex_tui_test_paste_image.png 3x2] ") + ); let imgs = composer.take_recent_submission_images(); assert_eq!(imgs, vec![tmp_path]); From 26f7c46856060f440615645bdf2faf9e62c74e72 Mon Sep 17 00:00:00 2001 From: Shijie Rao Date: Fri, 10 Oct 2025 17:23:41 -0700 Subject: [PATCH 23/32] fixes #5011: update mcp server doc (#5014) --- docs/config.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/config.md b/docs/config.md index fba8a3a21d..2ac7aba6b7 100644 --- a/docs/config.md +++ b/docs/config.md @@ -370,9 +370,8 @@ API_KEY = "value" experimental_use_rmcp_client = true [mcp_servers.figma] url = "https://mcp.linear.app/mcp" -# Optional bearer token to be passed into an `Authorization: Bearer ` header -# Use this with caution because the token is in plaintext and can be read by Codex itself. -bearer_token = "" +# Optional environment variable containing a bearer token to use for auth +bearer_token_env_var = "" ``` For oauth login, you must enable `experimental_use_rmcp_client = true` and then run `codex mcp login server_name` From 5346cc422dd053717c6f22ab20ffbd0aa5c6594b Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 14 Oct 2025 09:47:20 +0100 Subject: [PATCH 24/32] feat: discard prompt starting with a slash (#5048) This is does not consider lines starting with a space or containing multiple `/` as commands Screenshot 2025-10-13 at 10 00 08 --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 3cd38e8de9..5b63a410bb 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -962,6 +962,7 @@ impl ChatComposer { } let mut text = self.textarea.text().to_string(); let original_input = text.clone(); + let input_starts_with_space = original_input.starts_with(' '); self.textarea.set_text(""); // Replace all pending pastes in the text @@ -975,6 +976,35 @@ impl ChatComposer { // If there is neither text nor attachments, suppress submission entirely. let has_attachments = !self.attached_images.is_empty(); text = text.trim().to_string(); + if let Some((name, _rest)) = parse_slash_name(&text) { + let treat_as_plain_text = input_starts_with_space || name.contains('/'); + if !treat_as_plain_text { + let is_builtin = built_in_slash_commands() + .into_iter() + .any(|(command_name, _)| command_name == name); + let prompt_prefix = format!("{PROMPTS_CMD_PREFIX}:"); + let is_known_prompt = name + .strip_prefix(&prompt_prefix) + .map(|prompt_name| { + self.custom_prompts + .iter() + .any(|prompt| prompt.name == prompt_name) + }) + .unwrap_or(false); + if !is_builtin && !is_known_prompt { + let message = format!( + r#"Unrecognized command '/{name}'. Type "/" for a list of supported commands."# + ); + self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new( + history_cell::new_info_event(message, None), + ))); + self.textarea.set_text(&original_input); + self.textarea.set_cursor(original_input.len()); + return (InputResult::None, true); + } + } + } + let expanded_prompt = match expand_custom_prompt(&text, &self.custom_prompts) { Ok(expanded) => expanded, Err(err) => { @@ -2877,6 +2907,76 @@ mod tests { assert!(composer.textarea.is_empty()); } + #[test] + fn slash_path_input_submits_without_command_error() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + + let (tx, mut rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + + composer + .textarea + .set_text("/Users/example/project/src/main.rs"); + + let (result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + if let InputResult::Submitted(text) = result { + assert_eq!(text, "/Users/example/project/src/main.rs"); + } else { + panic!("expected Submitted"); + } + assert!(composer.textarea.is_empty()); + match rx.try_recv() { + Ok(event) => panic!("unexpected event: {event:?}"), + Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {} + Err(err) => panic!("unexpected channel state: {err:?}"), + } + } + + #[test] + fn slash_with_leading_space_submits_as_text() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + + let (tx, mut rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + + composer.textarea.set_text(" /this-looks-like-a-command"); + + let (result, _needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + if let InputResult::Submitted(text) = result { + assert_eq!(text, "/this-looks-like-a-command"); + } else { + panic!("expected Submitted"); + } + assert!(composer.textarea.is_empty()); + match rx.try_recv() { + Ok(event) => panic!("unexpected event: {event:?}"), + Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {} + Err(err) => panic!("unexpected channel state: {err:?}"), + } + } + #[test] fn custom_prompt_invalid_args_reports_error() { let (tx, mut rx) = unbounded_channel::(); From 268a10f917ac43b3e66c03ee0aa1f179f754ec9a Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 14 Oct 2025 16:17:00 +0100 Subject: [PATCH 25/32] feat: add header for task kind (#5142) Add a header in the responses API request for the task kind (compact, review, ...) for observability purpose The header name is `codex-task-type` --- codex-rs/core/src/client.rs | 21 ++++- codex-rs/core/src/codex.rs | 12 ++- codex-rs/core/src/codex/compact.rs | 7 +- codex-rs/core/src/state/turn.rs | 22 +++++ codex-rs/core/src/tasks/regular.rs | 2 +- codex-rs/core/src/tasks/review.rs | 2 +- codex-rs/core/tests/responses_headers.rs | 102 +++++++++++++++++++++++ 7 files changed, 161 insertions(+), 7 deletions(-) create mode 100644 codex-rs/core/tests/responses_headers.rs diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 3ea2ca79b5..a8dcb7259a 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -47,6 +47,7 @@ use crate::openai_tools::create_tools_json_for_responses_api; use crate::protocol::RateLimitSnapshot; use crate::protocol::RateLimitWindow; use crate::protocol::TokenUsage; +use crate::state::TaskKind; use crate::token_data::PlanType; use crate::util::backoff; use codex_otel::otel_event_manager::OtelEventManager; @@ -123,8 +124,16 @@ impl ModelClient { /// the provider config. Public callers always invoke `stream()` – the /// specialised helpers are private to avoid accidental misuse. pub async fn stream(&self, prompt: &Prompt) -> Result { + self.stream_with_task_kind(prompt, TaskKind::Regular).await + } + + pub(crate) async fn stream_with_task_kind( + &self, + prompt: &Prompt, + task_kind: TaskKind, + ) -> Result { match self.provider.wire_api { - WireApi::Responses => self.stream_responses(prompt).await, + WireApi::Responses => self.stream_responses(prompt, task_kind).await, WireApi::Chat => { // Create the raw streaming connection first. let response_stream = stream_chat_completions( @@ -165,7 +174,11 @@ impl ModelClient { } /// Implementation for the OpenAI *Responses* experimental API. - async fn stream_responses(&self, prompt: &Prompt) -> Result { + async fn stream_responses( + &self, + prompt: &Prompt, + task_kind: TaskKind, + ) -> Result { if let Some(path) = &*CODEX_RS_SSE_FIXTURE { // short circuit for tests warn!(path, "Streaming from fixture"); @@ -244,7 +257,7 @@ impl ModelClient { let max_attempts = self.provider.request_max_retries(); for attempt in 0..=max_attempts { match self - .attempt_stream_responses(attempt, &payload_json, &auth_manager) + .attempt_stream_responses(attempt, &payload_json, &auth_manager, task_kind) .await { Ok(stream) => { @@ -272,6 +285,7 @@ impl ModelClient { attempt: u64, payload_json: &Value, auth_manager: &Option>, + task_kind: TaskKind, ) -> std::result::Result { // Always fetch the latest auth in case a prior attempt refreshed the token. let auth = auth_manager.as_ref().and_then(|m| m.auth()); @@ -294,6 +308,7 @@ impl ModelClient { .header("conversation_id", self.conversation_id.to_string()) .header("session_id", self.conversation_id.to_string()) .header(reqwest::header::ACCEPT, "text/event-stream") + .header("Codex-Task-Type", task_kind.header_value()) .json(payload_json); if let Some(auth) = auth.as_ref() diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index fe352f0103..22b34b1cd0 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -99,6 +99,7 @@ use crate::rollout::RolloutRecorderParams; use crate::shell; use crate::state::ActiveTurn; use crate::state::SessionServices; +use crate::state::TaskKind; use crate::tasks::CompactTask; use crate::tasks::RegularTask; use crate::tasks::ReviewTask; @@ -1634,6 +1635,7 @@ pub(crate) async fn run_task( turn_context: Arc, sub_id: String, input: Vec, + task_kind: TaskKind, ) -> Option { if input.is_empty() { return None; @@ -1717,6 +1719,7 @@ pub(crate) async fn run_task( Arc::clone(&turn_diff_tracker), sub_id.clone(), turn_input, + task_kind, ) .await { @@ -1942,6 +1945,7 @@ async fn run_turn( turn_diff_tracker: SharedTurnDiffTracker, sub_id: String, input: Vec, + task_kind: TaskKind, ) -> CodexResult { let mcp_tools = sess.services.mcp_connection_manager.list_all_tools(); let router = Arc::new(ToolRouter::from_config( @@ -1971,6 +1975,7 @@ async fn run_turn( Arc::clone(&turn_diff_tracker), &sub_id, &prompt, + task_kind, ) .await { @@ -2044,6 +2049,7 @@ async fn try_run_turn( turn_diff_tracker: SharedTurnDiffTracker, sub_id: &str, prompt: &Prompt, + task_kind: TaskKind, ) -> CodexResult { // call_ids that are part of this response. let completed_call_ids = prompt @@ -2109,7 +2115,11 @@ async fn try_run_turn( summary: turn_context.client.get_reasoning_summary(), }); sess.persist_rollout_items(&[rollout_item]).await; - let mut stream = turn_context.client.clone().stream(&prompt).await?; + let mut stream = turn_context + .client + .clone() + .stream_with_task_kind(prompt.as_ref(), task_kind) + .await?; let tool_runtime = ToolCallRuntime::new( Arc::clone(&router), diff --git a/codex-rs/core/src/codex/compact.rs b/codex-rs/core/src/codex/compact.rs index d43e3abcbb..93bbfa79c6 100644 --- a/codex-rs/core/src/codex/compact.rs +++ b/codex-rs/core/src/codex/compact.rs @@ -16,6 +16,7 @@ use crate::protocol::InputItem; use crate::protocol::InputMessageKind; use crate::protocol::TaskStartedEvent; use crate::protocol::TurnContextItem; +use crate::state::TaskKind; use crate::truncate::truncate_middle; use crate::util::backoff; use askama::Template; @@ -258,7 +259,11 @@ async fn drain_to_completed( sub_id: &str, prompt: &Prompt, ) -> CodexResult<()> { - let mut stream = turn_context.client.clone().stream(prompt).await?; + let mut stream = turn_context + .client + .clone() + .stream_with_task_kind(prompt, TaskKind::Compact) + .await?; loop { let maybe_event = stream.next().await; let Some(event) = maybe_event else { diff --git a/codex-rs/core/src/state/turn.rs b/codex-rs/core/src/state/turn.rs index f715d5481e..89af13a1a5 100644 --- a/codex-rs/core/src/state/turn.rs +++ b/codex-rs/core/src/state/turn.rs @@ -34,6 +34,16 @@ pub(crate) enum TaskKind { Compact, } +impl TaskKind { + pub(crate) fn header_value(self) -> &'static str { + match self { + TaskKind::Regular => "standard", + TaskKind::Review => "review", + TaskKind::Compact => "compact", + } + } +} + #[derive(Clone)] pub(crate) struct RunningTask { pub(crate) handle: AbortHandle, @@ -113,3 +123,15 @@ impl ActiveTurn { } } } + +#[cfg(test)] +mod tests { + use super::TaskKind; + + #[test] + fn header_value_matches_expected_labels() { + assert_eq!(TaskKind::Regular.header_value(), "standard"); + assert_eq!(TaskKind::Review.header_value(), "review"); + assert_eq!(TaskKind::Compact.header_value(), "compact"); + } +} diff --git a/codex-rs/core/src/tasks/regular.rs b/codex-rs/core/src/tasks/regular.rs index 9d24099746..b3758d5fc6 100644 --- a/codex-rs/core/src/tasks/regular.rs +++ b/codex-rs/core/src/tasks/regular.rs @@ -27,6 +27,6 @@ impl SessionTask for RegularTask { input: Vec, ) -> Option { let sess = session.clone_session(); - run_task(sess, ctx, sub_id, input).await + run_task(sess, ctx, sub_id, input, TaskKind::Regular).await } } diff --git a/codex-rs/core/src/tasks/review.rs b/codex-rs/core/src/tasks/review.rs index 047a2f40e2..cec9243234 100644 --- a/codex-rs/core/src/tasks/review.rs +++ b/codex-rs/core/src/tasks/review.rs @@ -28,7 +28,7 @@ impl SessionTask for ReviewTask { input: Vec, ) -> Option { let sess = session.clone_session(); - run_task(sess, ctx, sub_id, input).await + run_task(sess, ctx, sub_id, input, TaskKind::Review).await } async fn abort(&self, session: Arc, sub_id: &str) { diff --git a/codex-rs/core/tests/responses_headers.rs b/codex-rs/core/tests/responses_headers.rs new file mode 100644 index 0000000000..19967b06ea --- /dev/null +++ b/codex-rs/core/tests/responses_headers.rs @@ -0,0 +1,102 @@ +use std::sync::Arc; + +use codex_app_server_protocol::AuthMode; +use codex_core::ContentItem; +use codex_core::ModelClient; +use codex_core::ModelProviderInfo; +use codex_core::Prompt; +use codex_core::ResponseEvent; +use codex_core::ResponseItem; +use codex_core::WireApi; +use codex_otel::otel_event_manager::OtelEventManager; +use codex_protocol::ConversationId; +use core_test_support::load_default_config_for_test; +use core_test_support::responses; +use futures::StreamExt; +use tempfile::TempDir; +use wiremock::matchers::header; + +#[tokio::test] +async fn responses_stream_includes_task_type_header() { + core_test_support::skip_if_no_network!(); + + let server = responses::start_mock_server().await; + let response_body = responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_completed("resp-1"), + ]); + + let request_recorder = responses::mount_sse_once_match( + &server, + header("Codex-Task-Type", "standard"), + response_body, + ) + .await; + + let provider = ModelProviderInfo { + name: "mock".into(), + base_url: Some(format!("{}/v1", server.uri())), + env_key: None, + env_key_instructions: None, + wire_api: WireApi::Responses, + query_params: None, + http_headers: None, + env_http_headers: None, + request_max_retries: Some(0), + stream_max_retries: Some(0), + stream_idle_timeout_ms: Some(5_000), + requires_openai_auth: false, + }; + + let codex_home = TempDir::new().expect("failed to create TempDir"); + let mut config = load_default_config_for_test(&codex_home); + config.model_provider_id = provider.name.clone(); + config.model_provider = provider.clone(); + let effort = config.model_reasoning_effort; + let summary = config.model_reasoning_summary; + let config = Arc::new(config); + + let conversation_id = ConversationId::new(); + + let otel_event_manager = OtelEventManager::new( + conversation_id, + config.model.as_str(), + config.model_family.slug.as_str(), + None, + Some(AuthMode::ChatGPT), + false, + "test".to_string(), + ); + + let client = ModelClient::new( + Arc::clone(&config), + None, + otel_event_manager, + provider, + effort, + summary, + conversation_id, + ); + + let mut prompt = Prompt::default(); + prompt.input = vec![ResponseItem::Message { + id: None, + role: "user".into(), + content: vec![ContentItem::InputText { + text: "hello".into(), + }], + }]; + + let mut stream = client.stream(&prompt).await.expect("stream failed"); + while let Some(event) = stream.next().await { + if matches!(event, Ok(ResponseEvent::Completed { .. })) { + break; + } + } + + let request = request_recorder.single_request(); + assert_eq!( + request.header("Codex-Task-Type").as_deref(), + Some("standard") + ); +} From 57584d6f341ead766242a59186e168c7ab299587 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 14 Oct 2025 18:15:47 +0100 Subject: [PATCH 26/32] fix: the 7 omitted lines issue (#5141) Before, the CLI was always showing `... +7 lines` (with the 7 constant) due to a double truncation Screenshot 2025-10-13 at 10 28 11 --- ...et__tests__binary_size_ideal_response.snap | 3 +- codex-rs/tui/src/exec_cell/render.rs | 71 +++++++++++++++---- codex-rs/tui/src/history_cell.rs | 5 +- 3 files changed, 62 insertions(+), 17 deletions(-) diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap index e3121774f4..77738439a1 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap @@ -1,6 +1,5 @@ --- source: tui/src/chatwidget/tests.rs -assertion_line: 1152 expression: "lines[start_idx..].join(\"\\n\")" --- • I need to check the codex-rs repository to explain why the project's binaries @@ -33,7 +32,7 @@ expression: "lines[start_idx..].join(\"\\n\")" │ … +1 lines └ --- ansi-escape/Cargo.toml [package] - … +7 lines + … +243 lines ] } tracing = { version diff --git a/codex-rs/tui/src/exec_cell/render.rs b/codex-rs/tui/src/exec_cell/render.rs index a3cc8cacae..98d9d07256 100644 --- a/codex-rs/tui/src/exec_cell/render.rs +++ b/codex-rs/tui/src/exec_cell/render.rs @@ -48,10 +48,16 @@ pub(crate) fn new_active_exec_command( }) } +#[derive(Clone)] +pub(crate) struct OutputLines { + pub(crate) lines: Vec>, + pub(crate) omitted: Option, +} + pub(crate) fn output_lines( output: Option<&CommandOutput>, params: OutputLinesParams, -) -> Vec> { +) -> OutputLines { let OutputLinesParams { only_err, include_angle_pipe, @@ -63,9 +69,19 @@ pub(crate) fn output_lines( stderr, .. } = match output { - Some(output) if only_err && output.exit_code == 0 => return vec![], + Some(output) if only_err && output.exit_code == 0 => { + return OutputLines { + lines: Vec::new(), + omitted: None, + }; + } Some(output) => output, - None => return vec![], + None => { + return OutputLines { + lines: Vec::new(), + omitted: None, + }; + } }; let src = if *exit_code == 0 { stdout } else { stderr }; @@ -73,7 +89,7 @@ pub(crate) fn output_lines( let total = lines.len(); let limit = TOOL_CALL_MAX_LINES; - let mut out = Vec::new(); + let mut out: Vec> = Vec::new(); let head_end = total.min(limit); for (i, raw) in lines[..head_end].iter().enumerate() { @@ -93,6 +109,11 @@ pub(crate) fn output_lines( } let show_ellipsis = total > 2 * limit; + let omitted = if show_ellipsis { + Some(total - 2 * limit) + } else { + None + }; if show_ellipsis { let omitted = total - 2 * limit; out.push(format!("… +{omitted} lines").into()); @@ -114,7 +135,10 @@ pub(crate) fn output_lines( out.push(line); } - out + OutputLines { + lines: out, + omitted, + } } pub(crate) fn spinner(start_time: Option) -> Span<'static> { @@ -371,7 +395,7 @@ impl ExecCell { } if let Some(output) = call.output.as_ref() { - let raw_output_lines = output_lines( + let raw_output = output_lines( Some(output), OutputLinesParams { only_err: false, @@ -380,15 +404,18 @@ impl ExecCell { }, ); - if raw_output_lines.is_empty() { + if raw_output.lines.is_empty() { lines.extend(prefix_lines( vec![Line::from("(no output)".dim())], Span::from(layout.output_block.initial_prefix).dim(), Span::from(layout.output_block.subsequent_prefix), )); } else { - let trimmed_output = - Self::truncate_lines_middle(&raw_output_lines, layout.output_max_lines); + let trimmed_output = Self::truncate_lines_middle( + &raw_output.lines, + layout.output_max_lines, + raw_output.omitted, + ); let mut wrapped_output: Vec> = Vec::new(); let output_wrap_width = layout.output_block.wrap_width(width); @@ -427,7 +454,11 @@ impl ExecCell { out } - fn truncate_lines_middle(lines: &[Line<'static>], max: usize) -> Vec> { + fn truncate_lines_middle( + lines: &[Line<'static>], + max: usize, + omitted_hint: Option, + ) -> Vec> { if max == 0 { return Vec::new(); } @@ -435,7 +466,17 @@ impl ExecCell { return lines.to_vec(); } if max == 1 { - return vec![Self::ellipsis_line(lines.len())]; + // Carry forward any previously omitted count and add any + // additionally hidden content lines from this truncation. + let base = omitted_hint.unwrap_or(0); + // When an existing ellipsis is present, `lines` already includes + // that single representation line; exclude it from the count of + // additionally omitted content lines. + let extra = lines + .len() + .saturating_sub(usize::from(omitted_hint.is_some())); + let omitted = base + extra; + return vec![Self::ellipsis_line(omitted)]; } let head = (max - 1) / 2; @@ -446,8 +487,12 @@ impl ExecCell { out.extend(lines[..head].iter().cloned()); } - let omitted = lines.len().saturating_sub(head + tail); - out.push(Self::ellipsis_line(omitted)); + let base = omitted_hint.unwrap_or(0); + let additional = lines + .len() + .saturating_sub(head + tail) + .saturating_sub(usize::from(omitted_hint.is_some())); + out.push(Self::ellipsis_line(base + additional)); if tail > 0 { out.extend(lines[lines.len() - tail..].iter().cloned()); diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index aa0ae35d92..2cc0c3fd9e 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -1148,7 +1148,7 @@ pub(crate) fn new_patch_apply_failure(stderr: String) -> PlainHistoryCell { lines.push(Line::from("✘ Failed to apply patch".magenta().bold())); if !stderr.trim().is_empty() { - lines.extend(output_lines( + let output = output_lines( Some(&CommandOutput { exit_code: 1, stdout: String::new(), @@ -1160,7 +1160,8 @@ pub(crate) fn new_patch_apply_failure(stderr: String) -> PlainHistoryCell { include_angle_pipe: true, include_prefix: true, }, - )); + ); + lines.extend(output.lines); } PlainHistoryCell { lines } From 8662162f4515c8fdfbba8dccd2e53543993152f4 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Tue, 14 Oct 2025 10:49:17 -0700 Subject: [PATCH 27/32] cloud: codex cloud exec (#5060) By analogy to `codex exec`, this kicks off a task in codex cloud noninteractively. --- codex-rs/cloud-tasks/src/cli.rs | 40 +++++ codex-rs/cloud-tasks/src/lib.rs | 248 ++++++++++++++++++++++--------- codex-rs/cloud-tasks/src/util.rs | 15 ++ 3 files changed, 236 insertions(+), 67 deletions(-) diff --git a/codex-rs/cloud-tasks/src/cli.rs b/codex-rs/cloud-tasks/src/cli.rs index 81125aeb1c..4122aeff68 100644 --- a/codex-rs/cloud-tasks/src/cli.rs +++ b/codex-rs/cloud-tasks/src/cli.rs @@ -1,3 +1,4 @@ +use clap::Args; use clap::Parser; use codex_common::CliConfigOverrides; @@ -6,4 +7,43 @@ use codex_common::CliConfigOverrides; pub struct Cli { #[clap(skip)] pub config_overrides: CliConfigOverrides, + + #[command(subcommand)] + pub command: Option, +} + +#[derive(Debug, clap::Subcommand)] +pub enum Command { + /// Submit a new Codex Cloud task without launching the TUI. + Exec(ExecCommand), +} + +#[derive(Debug, Args)] +pub struct ExecCommand { + /// Task prompt to run in Codex Cloud. + #[arg(value_name = "QUERY")] + pub query: Option, + + /// Target environment identifier (see `codex cloud` to browse). + #[arg(long = "env", value_name = "ENV_ID")] + pub environment: String, + + /// Number of assistant attempts (best-of-N). + #[arg( + long = "attempts", + default_value_t = 1usize, + value_parser = parse_attempts + )] + pub attempts: usize, +} + +fn parse_attempts(input: &str) -> Result { + let value: usize = input + .parse() + .map_err(|_| "attempts must be an integer between 1 and 4".to_string())?; + if (1..=4).contains(&value) { + Ok(value) + } else { + Err("attempts must be between 1 and 4".to_string()) + } } diff --git a/codex-rs/cloud-tasks/src/lib.rs b/codex-rs/cloud-tasks/src/lib.rs index 69490e1c9a..6087cbea5b 100644 --- a/codex-rs/cloud-tasks/src/lib.rs +++ b/codex-rs/cloud-tasks/src/lib.rs @@ -7,7 +7,9 @@ mod ui; pub mod util; pub use cli::Cli; +use anyhow::anyhow; use std::io::IsTerminal; +use std::io::Read; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -23,6 +25,175 @@ struct ApplyJob { diff_override: Option, } +struct BackendContext { + backend: Arc, + base_url: String, +} + +async fn init_backend(user_agent_suffix: &str) -> anyhow::Result { + let use_mock = matches!( + std::env::var("CODEX_CLOUD_TASKS_MODE").ok().as_deref(), + Some("mock") | Some("MOCK") + ); + let base_url = std::env::var("CODEX_CLOUD_TASKS_BASE_URL") + .unwrap_or_else(|_| "https://chatgpt.com/backend-api".to_string()); + + set_user_agent_suffix(user_agent_suffix); + + if use_mock { + return Ok(BackendContext { + backend: Arc::new(codex_cloud_tasks_client::MockClient), + base_url, + }); + } + + let ua = codex_core::default_client::get_codex_user_agent(); + let mut http = codex_cloud_tasks_client::HttpClient::new(base_url.clone())?.with_user_agent(ua); + let style = if base_url.contains("/backend-api") { + "wham" + } else { + "codex-api" + }; + append_error_log(format!("startup: base_url={base_url} path_style={style}")); + + let auth = match codex_core::config::find_codex_home() + .ok() + .map(|home| codex_login::AuthManager::new(home, false)) + .and_then(|am| am.auth()) + { + Some(auth) => auth, + None => { + eprintln!( + "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." + ); + std::process::exit(1); + } + }; + + if let Some(acc) = auth.get_account_id() { + append_error_log(format!("auth: mode=ChatGPT account_id={acc}")); + } + + let token = match auth.get_token().await { + Ok(t) if !t.is_empty() => t, + _ => { + eprintln!( + "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." + ); + std::process::exit(1); + } + }; + + http = http.with_bearer_token(token.clone()); + if let Some(acc) = auth + .get_account_id() + .or_else(|| util::extract_chatgpt_account_id(&token)) + { + append_error_log(format!("auth: set ChatGPT-Account-Id header: {acc}")); + http = http.with_chatgpt_account_id(acc); + } + + Ok(BackendContext { + backend: Arc::new(http), + base_url, + }) +} + +async fn run_exec_command(args: crate::cli::ExecCommand) -> anyhow::Result<()> { + let crate::cli::ExecCommand { + query, + environment, + attempts, + } = args; + let ctx = init_backend("codex_cloud_tasks_exec").await?; + let prompt = resolve_query_input(query)?; + let env_id = resolve_environment_id(&ctx, &environment).await?; + let created = codex_cloud_tasks_client::CloudBackend::create_task( + &*ctx.backend, + &env_id, + &prompt, + "main", + false, + attempts, + ) + .await?; + let url = util::task_url(&ctx.base_url, &created.id.0); + println!("{url}"); + Ok(()) +} + +async fn resolve_environment_id(ctx: &BackendContext, requested: &str) -> anyhow::Result { + let trimmed = requested.trim(); + if trimmed.is_empty() { + return Err(anyhow!("environment id must not be empty")); + } + let normalized = util::normalize_base_url(&ctx.base_url); + let headers = util::build_chatgpt_headers().await; + let environments = crate::env_detect::list_environments(&normalized, &headers).await?; + if environments.is_empty() { + return Err(anyhow!( + "no cloud environments are available for this workspace" + )); + } + + if let Some(row) = environments.iter().find(|row| row.id == trimmed) { + return Ok(row.id.clone()); + } + + let label_matches = environments + .iter() + .filter(|row| { + row.label + .as_deref() + .map(|label| label.eq_ignore_ascii_case(trimmed)) + .unwrap_or(false) + }) + .collect::>(); + match label_matches.as_slice() { + [] => Err(anyhow!( + "environment '{trimmed}' not found; run `codex cloud` to list available environments" + )), + [single] => Ok(single.id.clone()), + [first, rest @ ..] => { + let first_id = &first.id; + if rest.iter().all(|row| row.id == *first_id) { + Ok(first_id.clone()) + } else { + Err(anyhow!( + "environment label '{trimmed}' is ambiguous; run `codex cloud` to pick the desired environment id" + )) + } + } + } +} + +fn resolve_query_input(query_arg: Option) -> anyhow::Result { + match query_arg { + Some(q) if q != "-" => Ok(q), + maybe_dash => { + let force_stdin = matches!(maybe_dash.as_deref(), Some("-")); + if std::io::stdin().is_terminal() && !force_stdin { + return Err(anyhow!( + "no query provided. Pass one as an argument or pipe it via stdin." + )); + } + if !force_stdin { + eprintln!("Reading query from stdin..."); + } + let mut buffer = String::new(); + std::io::stdin() + .read_to_string(&mut buffer) + .map_err(|e| anyhow!("failed to read query from stdin: {e}"))?; + if buffer.trim().is_empty() { + return Err(anyhow!( + "no query provided via stdin (received empty input)." + )); + } + Ok(buffer) + } + } +} + fn level_from_status(status: codex_cloud_tasks_client::ApplyStatus) -> app::ApplyResultLevel { match status { codex_cloud_tasks_client::ApplyStatus::Success => app::ApplyResultLevel::Success, @@ -148,7 +319,14 @@ fn spawn_apply( // (no standalone patch summarizer needed – UI displays raw diffs) /// Entry point for the `codex cloud` subcommand. -pub async fn run_main(_cli: Cli, _codex_linux_sandbox_exe: Option) -> anyhow::Result<()> { +pub async fn run_main(cli: Cli, _codex_linux_sandbox_exe: Option) -> anyhow::Result<()> { + if let Some(command) = cli.command { + return match command { + crate::cli::Command::Exec(args) => run_exec_command(args).await, + }; + } + let Cli { .. } = cli; + // Very minimal logging setup; mirrors other crates' pattern. let default_level = "error"; let _ = tracing_subscriber::fmt() @@ -162,72 +340,8 @@ pub async fn run_main(_cli: Cli, _codex_linux_sandbox_exe: Option) -> a .try_init(); info!("Launching Cloud Tasks list UI"); - set_user_agent_suffix("codex_cloud_tasks_tui"); - - // Default to online unless explicitly configured to use mock. - let use_mock = matches!( - std::env::var("CODEX_CLOUD_TASKS_MODE").ok().as_deref(), - Some("mock") | Some("MOCK") - ); - - let backend: Arc = if use_mock { - Arc::new(codex_cloud_tasks_client::MockClient) - } else { - // Build an HTTP client against the configured (or default) base URL. - let base_url = std::env::var("CODEX_CLOUD_TASKS_BASE_URL") - .unwrap_or_else(|_| "https://chatgpt.com/backend-api".to_string()); - let ua = codex_core::default_client::get_codex_user_agent(); - let mut http = - codex_cloud_tasks_client::HttpClient::new(base_url.clone())?.with_user_agent(ua); - // Log which base URL and path style we're going to use. - let style = if base_url.contains("/backend-api") { - "wham" - } else { - "codex-api" - }; - append_error_log(format!("startup: base_url={base_url} path_style={style}")); - - // Require ChatGPT login (SWIC). Exit with a clear message if missing. - let _token = match codex_core::config::find_codex_home() - .ok() - .map(|home| codex_login::AuthManager::new(home, false)) - .and_then(|am| am.auth()) - { - Some(auth) => { - // Log account context for debugging workspace selection. - if let Some(acc) = auth.get_account_id() { - append_error_log(format!("auth: mode=ChatGPT account_id={acc}")); - } - match auth.get_token().await { - Ok(t) if !t.is_empty() => { - // Attach token and ChatGPT-Account-Id header if available - http = http.with_bearer_token(t.clone()); - if let Some(acc) = auth - .get_account_id() - .or_else(|| util::extract_chatgpt_account_id(&t)) - { - append_error_log(format!("auth: set ChatGPT-Account-Id header: {acc}")); - http = http.with_chatgpt_account_id(acc); - } - t - } - _ => { - eprintln!( - "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." - ); - std::process::exit(1); - } - } - } - None => { - eprintln!( - "Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'." - ); - std::process::exit(1); - } - }; - Arc::new(http) - }; + let BackendContext { backend, .. } = init_backend("codex_cloud_tasks_tui").await?; + let backend = backend; // Terminal setup use crossterm::ExecutableCommand; diff --git a/codex-rs/cloud-tasks/src/util.rs b/codex-rs/cloud-tasks/src/util.rs index 8003a02f1e..5d160e54fa 100644 --- a/codex-rs/cloud-tasks/src/util.rs +++ b/codex-rs/cloud-tasks/src/util.rs @@ -91,3 +91,18 @@ pub async fn build_chatgpt_headers() -> HeaderMap { } headers } + +/// Construct a browser-friendly task URL for the given backend base URL. +pub fn task_url(base_url: &str, task_id: &str) -> String { + let normalized = normalize_base_url(base_url); + if let Some(root) = normalized.strip_suffix("/backend-api") { + return format!("{root}/codex/tasks/{task_id}"); + } + if let Some(root) = normalized.strip_suffix("/api/codex") { + return format!("{root}/codex/tasks/{task_id}"); + } + if normalized.ends_with("/codex") { + return format!("{normalized}/tasks/{task_id}"); + } + format!("{normalized}/codex/tasks/{task_id}") +} From d6c5df9a0a8228b2b9a94cdae5e5747e8d98108a Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Tue, 14 Oct 2025 10:49:44 -0700 Subject: [PATCH 28/32] detect Bun installs in CLI update banner (#5074) ## Summary - detect Bun-managed installs in the JavaScript launcher and set a dedicated environment flag - show a Bun-specific upgrade command in the update banner when that flag is present Fixes #5012 ------ https://chatgpt.com/codex/tasks/task_i_68e95c439494832c835bdf34b3b1774e --------- Co-authored-by: Michael Bolin --- codex-cli/bin/codex.js | 35 ++++++++++++++++++++++++++++++++++- codex-rs/tui/src/lib.rs | 10 +++++++++- 2 files changed, 43 insertions(+), 2 deletions(-) mode change 100755 => 100644 codex-cli/bin/codex.js diff --git a/codex-cli/bin/codex.js b/codex-cli/bin/codex.js old mode 100755 new mode 100644 index 17dd98a8e8..805be85af8 --- a/codex-cli/bin/codex.js +++ b/codex-cli/bin/codex.js @@ -80,6 +80,32 @@ function getUpdatedPath(newDirs) { return updatedPath; } +/** + * Use heuristics to detect the package manager that was used to install Codex + * in order to give the user a hint about how to update it. + */ +function detectPackageManager() { + const userAgent = process.env.npm_config_user_agent || ""; + if (/\bbun\//.test(userAgent)) { + return "bun"; + } + + const execPath = process.env.npm_execpath || ""; + if (execPath.includes("bun")) { + return "bun"; + } + + if ( + process.env.BUN_INSTALL || + process.env.BUN_INSTALL_GLOBAL_DIR || + process.env.BUN_INSTALL_BIN_DIR + ) { + return "bun"; + } + + return userAgent ? "npm" : null; +} + const additionalDirs = []; const pathDir = path.join(archRoot, "path"); if (existsSync(pathDir)) { @@ -87,9 +113,16 @@ if (existsSync(pathDir)) { } const updatedPath = getUpdatedPath(additionalDirs); +const env = { ...process.env, PATH: updatedPath }; +const packageManagerEnvVar = + detectPackageManager() === "bun" + ? "CODEX_MANAGED_BY_BUN" + : "CODEX_MANAGED_BY_NPM"; +env[packageManagerEnvVar] = "1"; + const child = spawn(binaryPath, process.argv.slice(2), { stdio: "inherit", - env: { ...process.env, PATH: updatedPath, CODEX_MANAGED_BY_NPM: "1" }, + env, }); child.on("error", (err) => { diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 5d7188c036..7d7412e0a4 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -310,6 +310,7 @@ async fn run_ratatui_app( let current_version = env!("CARGO_PKG_VERSION"); let exe = std::env::current_exe()?; + let managed_by_bun = std::env::var_os("CODEX_MANAGED_BY_BUN").is_some(); let managed_by_npm = std::env::var_os("CODEX_MANAGED_BY_NPM").is_some(); let mut content_lines: Vec> = vec![ @@ -330,7 +331,14 @@ async fn run_ratatui_app( Line::from(""), ]; - if managed_by_npm { + if managed_by_bun { + let bun_cmd = "bun install -g @openai/codex@latest"; + content_lines.push(Line::from(vec![ + "Run ".into(), + bun_cmd.cyan(), + " to update.".into(), + ])); + } else if managed_by_npm { let npm_cmd = "npm install -g @openai/codex@latest"; content_lines.push(Line::from(vec![ "Run ".into(), From f7b4e296093b0f6f9ff749fbe75ecd5e278f2c9b Mon Sep 17 00:00:00 2001 From: jif-oai Date: Tue, 14 Oct 2025 18:50:00 +0100 Subject: [PATCH 29/32] feat: feature flag (#4948) Add proper feature flag instead of having custom flags for everything. This is just for experimental/wip part of the code It can be used through CLI: ```bash codex --enable unified_exec --disable view_image_tool ``` Or in the `config.toml` ```toml # Global toggles applied to every profile unless overridden. [features] apply_patch_freeform = true view_image_tool = false ``` Follow-up: In a following PR, the goal is to have a default have `bundles` of features that we can associate to a model --- codex-rs/cli/src/main.rs | 88 +++++- codex-rs/cli/src/mcp_cmd.rs | 3 +- codex-rs/core/src/codex.rs | 54 ++-- codex-rs/core/src/config.rs | 166 +++++++++--- codex-rs/core/src/config_profile.rs | 12 + codex-rs/core/src/features.rs | 250 ++++++++++++++++++ codex-rs/core/src/features/legacy.rs | 158 +++++++++++ codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/tools/spec.rs | 146 +++++----- codex-rs/core/tests/suite/model_tools.rs | 13 +- codex-rs/core/tests/suite/prompt_caching.rs | 5 +- codex-rs/core/tests/suite/rmcp_client.rs | 7 +- .../core/tests/suite/shell_serialization.rs | 5 +- codex-rs/core/tests/suite/tool_harness.rs | 9 +- codex-rs/core/tests/suite/tools.rs | 7 +- codex-rs/core/tests/suite/unified_exec.rs | 14 +- 16 files changed, 762 insertions(+), 176 deletions(-) create mode 100644 codex-rs/core/src/features.rs create mode 100644 codex-rs/core/src/features/legacy.rs diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index cd43041ab0..81b795b0a1 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -26,6 +26,8 @@ use supports_color::Stream; mod mcp_cmd; use crate::mcp_cmd::McpCli; +use codex_core::config::Config; +use codex_core::config::ConfigOverrides; /// Codex CLI /// @@ -45,6 +47,9 @@ struct MultitoolCli { #[clap(flatten)] pub config_overrides: CliConfigOverrides, + #[clap(flatten)] + pub feature_toggles: FeatureToggles, + #[clap(flatten)] interactive: TuiCli, @@ -97,6 +102,9 @@ enum Subcommand { /// Internal: run the responses API proxy. #[clap(hide = true)] ResponsesApiProxy(ResponsesApiProxyArgs), + + /// Inspect feature flags. + Features(FeaturesCli), } #[derive(Debug, Parser)] @@ -231,6 +239,53 @@ fn print_exit_messages(exit_info: AppExitInfo) { } } +#[derive(Debug, Default, Parser, Clone)] +struct FeatureToggles { + /// Enable a feature (repeatable). Equivalent to `-c features.=true`. + #[arg(long = "enable", value_name = "FEATURE", action = clap::ArgAction::Append, global = true)] + enable: Vec, + + /// Disable a feature (repeatable). Equivalent to `-c features.=false`. + #[arg(long = "disable", value_name = "FEATURE", action = clap::ArgAction::Append, global = true)] + disable: Vec, +} + +impl FeatureToggles { + fn to_overrides(&self) -> Vec { + let mut v = Vec::new(); + for k in &self.enable { + v.push(format!("features.{k}=true")); + } + for k in &self.disable { + v.push(format!("features.{k}=false")); + } + v + } +} + +#[derive(Debug, Parser)] +struct FeaturesCli { + #[command(subcommand)] + sub: FeaturesSubcommand, +} + +#[derive(Debug, Parser)] +enum FeaturesSubcommand { + /// List known features with their stage and effective state. + List, +} + +fn stage_str(stage: codex_core::features::Stage) -> &'static str { + use codex_core::features::Stage; + match stage { + Stage::Experimental => "experimental", + Stage::Beta => "beta", + Stage::Stable => "stable", + Stage::Deprecated => "deprecated", + Stage::Removed => "removed", + } +} + /// As early as possible in the process lifecycle, apply hardening measures. We /// skip this in debug builds to avoid interfering with debugging. #[ctor::ctor] @@ -248,11 +303,17 @@ fn main() -> anyhow::Result<()> { async fn cli_main(codex_linux_sandbox_exe: Option) -> anyhow::Result<()> { let MultitoolCli { - config_overrides: root_config_overrides, + config_overrides: mut root_config_overrides, + feature_toggles, mut interactive, subcommand, } = MultitoolCli::parse(); + // Fold --enable/--disable into config overrides so they flow to all subcommands. + root_config_overrides + .raw_overrides + .extend(feature_toggles.to_overrides()); + match subcommand { None => { prepend_config_flags( @@ -381,6 +442,30 @@ async fn cli_main(codex_linux_sandbox_exe: Option) -> anyhow::Result<() Some(Subcommand::GenerateTs(gen_cli)) => { codex_protocol_ts::generate_ts(&gen_cli.out_dir, gen_cli.prettier.as_deref())?; } + Some(Subcommand::Features(FeaturesCli { sub })) => match sub { + FeaturesSubcommand::List => { + // Respect root-level `-c` overrides plus top-level flags like `--profile`. + let cli_kv_overrides = root_config_overrides + .parse_overrides() + .map_err(|e| anyhow::anyhow!(e))?; + + // Thread through relevant top-level flags (at minimum, `--profile`). + // Also honor `--search` since it maps to a feature toggle. + let overrides = ConfigOverrides { + config_profile: interactive.config_profile.clone(), + tools_web_search_request: interactive.web_search.then_some(true), + ..Default::default() + }; + + let config = Config::load_with_cli_overrides(cli_kv_overrides, overrides).await?; + for def in codex_core::features::FEATURES.iter() { + let name = def.key; + let stage = stage_str(def.stage); + let enabled = config.features.enabled(def.id); + println!("{name}\t{stage}\t{enabled}"); + } + } + }, } Ok(()) @@ -484,6 +569,7 @@ mod tests { interactive, config_overrides: root_overrides, subcommand, + feature_toggles: _, } = cli; let Subcommand::Resume(ResumeCommand { diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 0a5be0dc23..d1b0ffc835 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -13,6 +13,7 @@ use codex_core::config::load_global_mcp_servers; use codex_core::config::write_global_mcp_servers; use codex_core::config_types::McpServerConfig; use codex_core::config_types::McpServerTransportConfig; +use codex_core::features::Feature; use codex_core::mcp::auth::compute_auth_statuses; use codex_core::protocol::McpAuthStatus; use codex_rmcp_client::delete_oauth_tokens; @@ -285,7 +286,7 @@ async fn run_login(config_overrides: &CliConfigOverrides, login_args: LoginArgs) .await .context("failed to load configuration")?; - if !config.use_experimental_use_rmcp_client { + if !config.features.enabled(Feature::RmcpClient) { bail!( "OAuth login is only supported when experimental_use_rmcp_client is true in config.toml." ); diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 22b34b1cd0..495af42c65 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -365,7 +365,9 @@ impl Session { let mcp_fut = McpConnectionManager::new( config.mcp_servers.clone(), - config.use_experimental_use_rmcp_client, + config + .features + .enabled(crate::features::Feature::RmcpClient), config.mcp_oauth_credentials_store_mode, ); let default_shell_fut = shell::default_user_shell(); @@ -447,12 +449,7 @@ impl Session { client, tools_config: ToolsConfig::new(&ToolsConfigParams { model_family: &config.model_family, - include_plan_tool: config.include_plan_tool, - include_apply_patch_tool: config.include_apply_patch_tool, - include_web_search_request: config.tools_web_search_request, - use_streamable_shell_tool: config.use_experimental_streamable_shell_tool, - include_view_image_tool: config.include_view_image_tool, - experimental_unified_exec_tool: config.use_experimental_unified_exec_tool, + features: &config.features, }), user_instructions, base_instructions, @@ -1196,12 +1193,7 @@ async fn submission_loop( let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &effective_family, - include_plan_tool: config.include_plan_tool, - include_apply_patch_tool: config.include_apply_patch_tool, - include_web_search_request: config.tools_web_search_request, - use_streamable_shell_tool: config.use_experimental_streamable_shell_tool, - include_view_image_tool: config.include_view_image_tool, - experimental_unified_exec_tool: config.use_experimental_unified_exec_tool, + features: &config.features, }); let new_turn_context = TurnContext { @@ -1298,14 +1290,7 @@ async fn submission_loop( client, tools_config: ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: config.include_plan_tool, - include_apply_patch_tool: config.include_apply_patch_tool, - include_web_search_request: config.tools_web_search_request, - use_streamable_shell_tool: config - .use_experimental_streamable_shell_tool, - include_view_image_tool: config.include_view_image_tool, - experimental_unified_exec_tool: config - .use_experimental_unified_exec_tool, + features: &config.features, }), user_instructions: turn_context.user_instructions.clone(), base_instructions: turn_context.base_instructions.clone(), @@ -1537,14 +1522,15 @@ async fn spawn_review_thread( let model = config.review_model.clone(); let review_model_family = find_family_for_model(&model) .unwrap_or_else(|| parent_turn_context.client.get_model_family()); + // For reviews, disable plan, web_search, view_image regardless of global settings. + let mut review_features = config.features.clone(); + review_features.disable(crate::features::Feature::PlanTool); + review_features.disable(crate::features::Feature::WebSearchRequest); + review_features.disable(crate::features::Feature::ViewImageTool); + review_features.disable(crate::features::Feature::StreamableShell); let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &review_model_family, - include_plan_tool: false, - include_apply_patch_tool: config.include_apply_patch_tool, - include_web_search_request: false, - use_streamable_shell_tool: false, - include_view_image_tool: false, - experimental_unified_exec_tool: config.use_experimental_unified_exec_tool, + features: &review_features, }); let base_instructions = REVIEW_PROMPT.to_string(); @@ -2758,12 +2744,7 @@ mod tests { ); let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &config.model_family, - include_plan_tool: config.include_plan_tool, - include_apply_patch_tool: config.include_apply_patch_tool, - include_web_search_request: config.tools_web_search_request, - use_streamable_shell_tool: config.use_experimental_streamable_shell_tool, - include_view_image_tool: config.include_view_image_tool, - experimental_unified_exec_tool: config.use_experimental_unified_exec_tool, + features: &config.features, }); let turn_context = TurnContext { client, @@ -2831,12 +2812,7 @@ mod tests { ); let tools_config = ToolsConfig::new(&ToolsConfigParams { model_family: &config.model_family, - include_plan_tool: config.include_plan_tool, - include_apply_patch_tool: config.include_apply_patch_tool, - include_web_search_request: config.tools_web_search_request, - use_streamable_shell_tool: config.use_experimental_streamable_shell_tool, - include_view_image_tool: config.include_view_image_tool, - experimental_unified_exec_tool: config.use_experimental_unified_exec_tool, + features: &config.features, }); let turn_context = Arc::new(TurnContext { client, diff --git a/codex-rs/core/src/config.rs b/codex-rs/core/src/config.rs index c715651851..47db1a88bf 100644 --- a/codex-rs/core/src/config.rs +++ b/codex-rs/core/src/config.rs @@ -17,6 +17,10 @@ use crate::config_types::ShellEnvironmentPolicy; use crate::config_types::ShellEnvironmentPolicyToml; use crate::config_types::Tui; use crate::config_types::UriBasedFileOpener; +use crate::features::Feature; +use crate::features::FeatureOverrides; +use crate::features::Features; +use crate::features::FeaturesToml; use crate::git_info::resolve_root_git_project_for_trust; use crate::model_family::ModelFamily; use crate::model_family::derive_default_model_family; @@ -218,6 +222,9 @@ pub struct Config { /// Include the `view_image` tool that lets the agent attach a local image path to context. pub include_view_image_tool: bool, + /// Centralized feature flags; source of truth for feature gating. + pub features: Features, + /// The active profile name used to derive this `Config` (if any). pub active_profile: Option, @@ -794,19 +801,15 @@ pub struct ConfigToml { /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). pub chatgpt_base_url: Option, - /// Experimental path to a file whose contents replace the built-in BASE_INSTRUCTIONS. - pub experimental_instructions_file: Option, - - pub experimental_use_exec_command_tool: Option, - pub experimental_use_unified_exec_tool: Option, - pub experimental_use_rmcp_client: Option, - pub experimental_use_freeform_apply_patch: Option, - pub projects: Option>, /// Nested tools section for feature toggles pub tools: Option, + /// Centralized feature flags (new). Prefer this over individual toggles. + #[serde(default)] + pub features: Option, + /// When true, disables burst-paste detection for typed input entirely. /// All characters are inserted as they are received, and no buffering /// or placeholder replacement will occur for fast keypress bursts. @@ -817,6 +820,13 @@ pub struct ConfigToml { /// Tracks whether the Windows onboarding screen has been acknowledged. pub windows_wsl_setup_acknowledged: Option, + + /// Legacy, now use features + pub experimental_instructions_file: Option, + pub experimental_use_exec_command_tool: Option, + pub experimental_use_unified_exec_tool: Option, + pub experimental_use_rmcp_client: Option, + pub experimental_use_freeform_apply_patch: Option, } impl From for UserSavedConfig { @@ -980,9 +990,9 @@ impl Config { config_profile: config_profile_key, codex_linux_sandbox_exe, base_instructions, - include_plan_tool, - include_apply_patch_tool, - include_view_image_tool, + include_plan_tool: include_plan_tool_override, + include_apply_patch_tool: include_apply_patch_tool_override, + include_view_image_tool: include_view_image_tool_override, show_raw_agent_reasoning, tools_web_search_request: override_tools_web_search_request, } = overrides; @@ -1005,6 +1015,15 @@ impl Config { None => ConfigProfile::default(), }; + let feature_overrides = FeatureOverrides { + include_plan_tool: include_plan_tool_override, + include_apply_patch_tool: include_apply_patch_tool_override, + include_view_image_tool: include_view_image_tool_override, + web_search_request: override_tools_web_search_request, + }; + + let features = Features::from_config(&cfg, &config_profile, feature_overrides); + let sandbox_policy = cfg.derive_sandbox_policy(sandbox_mode); let mut model_providers = built_in_model_providers(); @@ -1050,13 +1069,13 @@ impl Config { let history = cfg.history.unwrap_or_default(); - let tools_web_search_request = override_tools_web_search_request - .or(cfg.tools.as_ref().and_then(|t| t.web_search)) - .unwrap_or(false); - - let include_view_image_tool = include_view_image_tool - .or(cfg.tools.as_ref().and_then(|t| t.view_image)) - .unwrap_or(true); + let include_plan_tool_flag = features.enabled(Feature::PlanTool); + let include_apply_patch_tool_flag = features.enabled(Feature::ApplyPatchFreeform); + let include_view_image_tool_flag = features.enabled(Feature::ViewImageTool); + let tools_web_search_request = features.enabled(Feature::WebSearchRequest); + let use_experimental_streamable_shell_tool = features.enabled(Feature::StreamableShell); + let use_experimental_unified_exec_tool = features.enabled(Feature::UnifiedExec); + let use_experimental_use_rmcp_client = features.enabled(Feature::RmcpClient); let model = model .or(config_profile.model) @@ -1164,19 +1183,14 @@ impl Config { .chatgpt_base_url .or(cfg.chatgpt_base_url) .unwrap_or("https://chatgpt.com/backend-api/".to_string()), - include_plan_tool: include_plan_tool.unwrap_or(false), - include_apply_patch_tool: include_apply_patch_tool - .or(cfg.experimental_use_freeform_apply_patch) - .unwrap_or(false), + include_plan_tool: include_plan_tool_flag, + include_apply_patch_tool: include_apply_patch_tool_flag, tools_web_search_request, - use_experimental_streamable_shell_tool: cfg - .experimental_use_exec_command_tool - .unwrap_or(false), - use_experimental_unified_exec_tool: cfg - .experimental_use_unified_exec_tool - .unwrap_or(false), - use_experimental_use_rmcp_client: cfg.experimental_use_rmcp_client.unwrap_or(false), - include_view_image_tool, + use_experimental_streamable_shell_tool, + use_experimental_unified_exec_tool, + use_experimental_use_rmcp_client, + include_view_image_tool: include_view_image_tool_flag, + features, active_profile: active_profile_name, windows_wsl_setup_acknowledged: cfg.windows_wsl_setup_acknowledged.unwrap_or(false), disable_paste_burst: cfg.disable_paste_burst.unwrap_or(false), @@ -1309,6 +1323,7 @@ pub fn log_dir(cfg: &Config) -> std::io::Result { mod tests { use crate::config_types::HistoryPersistence; use crate::config_types::Notifications; + use crate::features::Feature; use super::*; use pretty_assertions::assert_eq; @@ -1436,6 +1451,93 @@ exclude_slash_tmp = true Ok(()) } + #[test] + fn profile_legacy_toggles_override_base() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let mut profiles = HashMap::new(); + profiles.insert( + "work".to_string(), + ConfigProfile { + include_plan_tool: Some(true), + include_view_image_tool: Some(false), + ..Default::default() + }, + ); + let cfg = ConfigToml { + profiles, + profile: Some("work".to_string()), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert!(config.features.enabled(Feature::PlanTool)); + assert!(!config.features.enabled(Feature::ViewImageTool)); + assert!(config.include_plan_tool); + assert!(!config.include_view_image_tool); + + Ok(()) + } + + #[test] + fn feature_table_overrides_legacy_flags() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let mut entries = BTreeMap::new(); + entries.insert("plan_tool".to_string(), false); + entries.insert("apply_patch_freeform".to_string(), false); + let cfg = ConfigToml { + features: Some(crate::features::FeaturesToml { entries }), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert!(!config.features.enabled(Feature::PlanTool)); + assert!(!config.features.enabled(Feature::ApplyPatchFreeform)); + assert!(!config.include_plan_tool); + assert!(!config.include_apply_patch_tool); + + Ok(()) + } + + #[test] + fn legacy_toggles_map_to_features() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let cfg = ConfigToml { + experimental_use_exec_command_tool: Some(true), + experimental_use_unified_exec_tool: Some(true), + experimental_use_rmcp_client: Some(true), + experimental_use_freeform_apply_patch: Some(true), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert!(config.features.enabled(Feature::ApplyPatchFreeform)); + assert!(config.features.enabled(Feature::StreamableShell)); + assert!(config.features.enabled(Feature::UnifiedExec)); + assert!(config.features.enabled(Feature::RmcpClient)); + + assert!(config.include_apply_patch_tool); + assert!(config.use_experimental_streamable_shell_tool); + assert!(config.use_experimental_unified_exec_tool); + assert!(config.use_experimental_use_rmcp_client); + + Ok(()) + } + #[test] fn config_honors_explicit_file_oauth_store_mode() -> std::io::Result<()> { let codex_home = TempDir::new()?; @@ -2120,6 +2222,7 @@ model_verbosity = "high" use_experimental_unified_exec_tool: false, use_experimental_use_rmcp_client: false, include_view_image_tool: true, + features: Features::with_defaults(), active_profile: Some("o3".to_string()), windows_wsl_setup_acknowledged: false, disable_paste_burst: false, @@ -2183,6 +2286,7 @@ model_verbosity = "high" use_experimental_unified_exec_tool: false, use_experimental_use_rmcp_client: false, include_view_image_tool: true, + features: Features::with_defaults(), active_profile: Some("gpt3".to_string()), windows_wsl_setup_acknowledged: false, disable_paste_burst: false, @@ -2261,6 +2365,7 @@ model_verbosity = "high" use_experimental_unified_exec_tool: false, use_experimental_use_rmcp_client: false, include_view_image_tool: true, + features: Features::with_defaults(), active_profile: Some("zdr".to_string()), windows_wsl_setup_acknowledged: false, disable_paste_burst: false, @@ -2325,6 +2430,7 @@ model_verbosity = "high" use_experimental_unified_exec_tool: false, use_experimental_use_rmcp_client: false, include_view_image_tool: true, + features: Features::with_defaults(), active_profile: Some("gpt5".to_string()), windows_wsl_setup_acknowledged: false, disable_paste_burst: false, diff --git a/codex-rs/core/src/config_profile.rs b/codex-rs/core/src/config_profile.rs index da52176068..ba2201ed9c 100644 --- a/codex-rs/core/src/config_profile.rs +++ b/codex-rs/core/src/config_profile.rs @@ -20,6 +20,18 @@ pub struct ConfigProfile { pub model_verbosity: Option, pub chatgpt_base_url: Option, pub experimental_instructions_file: Option, + pub include_plan_tool: Option, + pub include_apply_patch_tool: Option, + pub include_view_image_tool: Option, + pub experimental_use_unified_exec_tool: Option, + pub experimental_use_exec_command_tool: Option, + pub experimental_use_rmcp_client: Option, + pub experimental_use_freeform_apply_patch: Option, + pub tools_web_search: Option, + pub tools_view_image: Option, + /// Optional feature toggles scoped to this profile. + #[serde(default)] + pub features: Option, } impl From for codex_app_server_protocol::Profile { diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs new file mode 100644 index 0000000000..b8314b0c14 --- /dev/null +++ b/codex-rs/core/src/features.rs @@ -0,0 +1,250 @@ +//! Centralized feature flags and metadata. +//! +//! This module defines a small set of toggles that gate experimental and +//! optional behavior across the codebase. Instead of wiring individual +//! booleans through multiple types, call sites consult a single `Features` +//! container attached to `Config`. + +use crate::config::ConfigToml; +use crate::config_profile::ConfigProfile; +use serde::Deserialize; +use std::collections::BTreeMap; +use std::collections::BTreeSet; + +mod legacy; +pub(crate) use legacy::LegacyFeatureToggles; + +/// High-level lifecycle stage for a feature. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Stage { + Experimental, + Beta, + Stable, + Deprecated, + Removed, +} + +/// Unique features toggled via configuration. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Feature { + /// Use the single unified PTY-backed exec tool. + UnifiedExec, + /// Use the streamable exec-command/write-stdin tool pair. + StreamableShell, + /// Use the official Rust MCP client (rmcp). + RmcpClient, + /// Include the plan tool. + PlanTool, + /// Include the freeform apply_patch tool. + ApplyPatchFreeform, + /// Include the view_image tool. + ViewImageTool, + /// Allow the model to request web searches. + WebSearchRequest, +} + +impl Feature { + pub fn key(self) -> &'static str { + self.info().key + } + + pub fn stage(self) -> Stage { + self.info().stage + } + + pub fn default_enabled(self) -> bool { + self.info().default_enabled + } + + fn info(self) -> &'static FeatureSpec { + FEATURES + .iter() + .find(|spec| spec.id == self) + .unwrap_or_else(|| unreachable!("missing FeatureSpec for {:?}", self)) + } +} + +/// Holds the effective set of enabled features. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Features { + enabled: BTreeSet, +} + +#[derive(Debug, Clone, Default)] +pub struct FeatureOverrides { + pub include_plan_tool: Option, + pub include_apply_patch_tool: Option, + pub include_view_image_tool: Option, + pub web_search_request: Option, +} + +impl FeatureOverrides { + fn apply(self, features: &mut Features) { + LegacyFeatureToggles { + include_plan_tool: self.include_plan_tool, + include_apply_patch_tool: self.include_apply_patch_tool, + include_view_image_tool: self.include_view_image_tool, + tools_web_search: self.web_search_request, + ..Default::default() + } + .apply(features); + } +} + +impl Features { + /// Starts with built-in defaults. + pub fn with_defaults() -> Self { + let mut set = BTreeSet::new(); + for spec in FEATURES { + if spec.default_enabled { + set.insert(spec.id); + } + } + Self { enabled: set } + } + + pub fn enabled(&self, f: Feature) -> bool { + self.enabled.contains(&f) + } + + pub fn enable(&mut self, f: Feature) { + self.enabled.insert(f); + } + + pub fn disable(&mut self, f: Feature) { + self.enabled.remove(&f); + } + + /// Apply a table of key -> bool toggles (e.g. from TOML). + pub fn apply_map(&mut self, m: &BTreeMap) { + for (k, v) in m { + match feature_for_key(k) { + Some(feat) => { + if *v { + self.enable(feat); + } else { + self.disable(feat); + } + } + None => { + tracing::warn!("unknown feature key in config: {k}"); + } + } + } + } + + pub fn from_config( + cfg: &ConfigToml, + config_profile: &ConfigProfile, + overrides: FeatureOverrides, + ) -> Self { + let mut features = Features::with_defaults(); + + let base_legacy = LegacyFeatureToggles { + experimental_use_freeform_apply_patch: cfg.experimental_use_freeform_apply_patch, + experimental_use_exec_command_tool: cfg.experimental_use_exec_command_tool, + experimental_use_unified_exec_tool: cfg.experimental_use_unified_exec_tool, + experimental_use_rmcp_client: cfg.experimental_use_rmcp_client, + tools_web_search: cfg.tools.as_ref().and_then(|t| t.web_search), + tools_view_image: cfg.tools.as_ref().and_then(|t| t.view_image), + ..Default::default() + }; + base_legacy.apply(&mut features); + + if let Some(base_features) = cfg.features.as_ref() { + features.apply_map(&base_features.entries); + } + + let profile_legacy = LegacyFeatureToggles { + include_plan_tool: config_profile.include_plan_tool, + include_apply_patch_tool: config_profile.include_apply_patch_tool, + include_view_image_tool: config_profile.include_view_image_tool, + experimental_use_freeform_apply_patch: config_profile + .experimental_use_freeform_apply_patch, + experimental_use_exec_command_tool: config_profile.experimental_use_exec_command_tool, + experimental_use_unified_exec_tool: config_profile.experimental_use_unified_exec_tool, + experimental_use_rmcp_client: config_profile.experimental_use_rmcp_client, + tools_web_search: config_profile.tools_web_search, + tools_view_image: config_profile.tools_view_image, + }; + profile_legacy.apply(&mut features); + if let Some(profile_features) = config_profile.features.as_ref() { + features.apply_map(&profile_features.entries); + } + + overrides.apply(&mut features); + + features + } +} + +/// Keys accepted in `[features]` tables. +fn feature_for_key(key: &str) -> Option { + for spec in FEATURES { + if spec.key == key { + return Some(spec.id); + } + } + legacy::feature_for_key(key) +} + +/// Deserializable features table for TOML. +#[derive(Deserialize, Debug, Clone, Default, PartialEq)] +pub struct FeaturesToml { + #[serde(flatten)] + pub entries: BTreeMap, +} + +/// Single, easy-to-read registry of all feature definitions. +#[derive(Debug, Clone, Copy)] +pub struct FeatureSpec { + pub id: Feature, + pub key: &'static str, + pub stage: Stage, + pub default_enabled: bool, +} + +pub const FEATURES: &[FeatureSpec] = &[ + FeatureSpec { + id: Feature::UnifiedExec, + key: "unified_exec", + stage: Stage::Experimental, + default_enabled: false, + }, + FeatureSpec { + id: Feature::StreamableShell, + key: "streamable_shell", + stage: Stage::Experimental, + default_enabled: false, + }, + FeatureSpec { + id: Feature::RmcpClient, + key: "rmcp_client", + stage: Stage::Experimental, + default_enabled: false, + }, + FeatureSpec { + id: Feature::PlanTool, + key: "plan_tool", + stage: Stage::Stable, + default_enabled: false, + }, + FeatureSpec { + id: Feature::ApplyPatchFreeform, + key: "apply_patch_freeform", + stage: Stage::Beta, + default_enabled: false, + }, + FeatureSpec { + id: Feature::ViewImageTool, + key: "view_image_tool", + stage: Stage::Stable, + default_enabled: true, + }, + FeatureSpec { + id: Feature::WebSearchRequest, + key: "web_search_request", + stage: Stage::Stable, + default_enabled: false, + }, +]; diff --git a/codex-rs/core/src/features/legacy.rs b/codex-rs/core/src/features/legacy.rs new file mode 100644 index 0000000000..3becb07e7c --- /dev/null +++ b/codex-rs/core/src/features/legacy.rs @@ -0,0 +1,158 @@ +use super::Feature; +use super::Features; +use tracing::info; + +#[derive(Clone, Copy)] +struct Alias { + legacy_key: &'static str, + feature: Feature, +} + +const ALIASES: &[Alias] = &[ + Alias { + legacy_key: "experimental_use_unified_exec_tool", + feature: Feature::UnifiedExec, + }, + Alias { + legacy_key: "experimental_use_exec_command_tool", + feature: Feature::StreamableShell, + }, + Alias { + legacy_key: "experimental_use_rmcp_client", + feature: Feature::RmcpClient, + }, + Alias { + legacy_key: "experimental_use_freeform_apply_patch", + feature: Feature::ApplyPatchFreeform, + }, + Alias { + legacy_key: "include_apply_patch_tool", + feature: Feature::ApplyPatchFreeform, + }, + Alias { + legacy_key: "include_plan_tool", + feature: Feature::PlanTool, + }, + Alias { + legacy_key: "include_view_image_tool", + feature: Feature::ViewImageTool, + }, + Alias { + legacy_key: "web_search", + feature: Feature::WebSearchRequest, + }, +]; + +pub(crate) fn feature_for_key(key: &str) -> Option { + ALIASES + .iter() + .find(|alias| alias.legacy_key == key) + .map(|alias| { + log_alias(alias.legacy_key, alias.feature); + alias.feature + }) +} + +#[derive(Debug, Default)] +pub struct LegacyFeatureToggles { + pub include_plan_tool: Option, + pub include_apply_patch_tool: Option, + pub include_view_image_tool: Option, + pub experimental_use_freeform_apply_patch: Option, + pub experimental_use_exec_command_tool: Option, + pub experimental_use_unified_exec_tool: Option, + pub experimental_use_rmcp_client: Option, + pub tools_web_search: Option, + pub tools_view_image: Option, +} + +impl LegacyFeatureToggles { + pub fn apply(self, features: &mut Features) { + set_if_some( + features, + Feature::PlanTool, + self.include_plan_tool, + "include_plan_tool", + ); + set_if_some( + features, + Feature::ApplyPatchFreeform, + self.include_apply_patch_tool, + "include_apply_patch_tool", + ); + set_if_some( + features, + Feature::ApplyPatchFreeform, + self.experimental_use_freeform_apply_patch, + "experimental_use_freeform_apply_patch", + ); + set_if_some( + features, + Feature::StreamableShell, + self.experimental_use_exec_command_tool, + "experimental_use_exec_command_tool", + ); + set_if_some( + features, + Feature::UnifiedExec, + self.experimental_use_unified_exec_tool, + "experimental_use_unified_exec_tool", + ); + set_if_some( + features, + Feature::RmcpClient, + self.experimental_use_rmcp_client, + "experimental_use_rmcp_client", + ); + set_if_some( + features, + Feature::WebSearchRequest, + self.tools_web_search, + "tools.web_search", + ); + set_if_some( + features, + Feature::ViewImageTool, + self.include_view_image_tool, + "include_view_image_tool", + ); + set_if_some( + features, + Feature::ViewImageTool, + self.tools_view_image, + "tools.view_image", + ); + } +} + +fn set_if_some( + features: &mut Features, + feature: Feature, + maybe_value: Option, + alias_key: &'static str, +) { + if let Some(enabled) = maybe_value { + set_feature(features, feature, enabled); + log_alias(alias_key, feature); + } +} + +fn set_feature(features: &mut Features, feature: Feature, enabled: bool) { + if enabled { + features.enable(feature); + } else { + features.disable(feature); + } +} + +fn log_alias(alias: &str, feature: Feature) { + let canonical = feature.key(); + if alias == canonical { + return; + } + info!( + %alias, + canonical, + "legacy feature toggle detected; prefer `[features].{canonical}`" + ); +} diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 201d8feb4d..22e1d4cdf0 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -29,6 +29,7 @@ pub mod exec; mod exec_command; pub mod exec_env; pub mod executor; +pub mod features; mod flags; pub mod git_info; pub mod landlock; diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index c10f8e22f9..bb1df187c2 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -1,5 +1,7 @@ use crate::client_common::tools::ResponsesApiTool; use crate::client_common::tools::ToolSpec; +use crate::features::Feature; +use crate::features::Features; use crate::model_family::ModelFamily; use crate::tools::handlers::PLAN_TOOL; use crate::tools::handlers::apply_patch::ApplyPatchToolType; @@ -33,26 +35,23 @@ pub(crate) struct ToolsConfig { pub(crate) struct ToolsConfigParams<'a> { pub(crate) model_family: &'a ModelFamily, - pub(crate) include_plan_tool: bool, - pub(crate) include_apply_patch_tool: bool, - pub(crate) include_web_search_request: bool, - pub(crate) use_streamable_shell_tool: bool, - pub(crate) include_view_image_tool: bool, - pub(crate) experimental_unified_exec_tool: bool, + pub(crate) features: &'a Features, } impl ToolsConfig { pub fn new(params: &ToolsConfigParams) -> Self { let ToolsConfigParams { model_family, - include_plan_tool, - include_apply_patch_tool, - include_web_search_request, - use_streamable_shell_tool, - include_view_image_tool, - experimental_unified_exec_tool, + features, } = params; - let shell_type = if *use_streamable_shell_tool { + let use_streamable_shell_tool = features.enabled(Feature::StreamableShell); + let experimental_unified_exec_tool = features.enabled(Feature::UnifiedExec); + let include_plan_tool = features.enabled(Feature::PlanTool); + let include_apply_patch_tool = features.enabled(Feature::ApplyPatchFreeform); + let include_web_search_request = features.enabled(Feature::WebSearchRequest); + let include_view_image_tool = features.enabled(Feature::ViewImageTool); + + let shell_type = if use_streamable_shell_tool { ConfigShellToolType::Streamable } else if model_family.uses_local_shell_tool { ConfigShellToolType::Local @@ -64,7 +63,7 @@ impl ToolsConfig { Some(ApplyPatchToolType::Freeform) => Some(ApplyPatchToolType::Freeform), Some(ApplyPatchToolType::Function) => Some(ApplyPatchToolType::Function), None => { - if *include_apply_patch_tool { + if include_apply_patch_tool { Some(ApplyPatchToolType::Freeform) } else { None @@ -74,11 +73,11 @@ impl ToolsConfig { Self { shell_type, - plan_tool: *include_plan_tool, + plan_tool: include_plan_tool, apply_patch_tool_type, - web_search_request: *include_web_search_request, - include_view_image_tool: *include_view_image_tool, - experimental_unified_exec_tool: *experimental_unified_exec_tool, + web_search_request: include_web_search_request, + include_view_image_tool, + experimental_unified_exec_tool, experimental_supported_tools: model_family.experimental_supported_tools.clone(), } } @@ -906,14 +905,13 @@ mod tests { fn test_build_specs() { let model_family = find_family_for_model("codex-mini-latest") .expect("codex-mini-latest should be a valid model family"); + let mut features = Features::with_defaults(); + features.enable(Feature::PlanTool); + features.enable(Feature::WebSearchRequest); + features.enable(Feature::UnifiedExec); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: true, - include_apply_patch_tool: false, - include_web_search_request: true, - use_streamable_shell_tool: false, - include_view_image_tool: true, - experimental_unified_exec_tool: true, + features: &features, }); let (tools, _) = build_specs(&config, Some(HashMap::new())).build(); @@ -926,14 +924,13 @@ mod tests { #[test] fn test_build_specs_default_shell() { let model_family = find_family_for_model("o3").expect("o3 should be a valid model family"); + let mut features = Features::with_defaults(); + features.enable(Feature::PlanTool); + features.enable(Feature::WebSearchRequest); + features.enable(Feature::UnifiedExec); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: true, - include_apply_patch_tool: false, - include_web_search_request: true, - use_streamable_shell_tool: false, - include_view_image_tool: true, - experimental_unified_exec_tool: true, + features: &features, }); let (tools, _) = build_specs(&config, Some(HashMap::new())).build(); @@ -948,14 +945,12 @@ mod tests { fn test_parallel_support_flags() { let model_family = find_family_for_model("gpt-5-codex") .expect("codex-mini-latest should be a valid model family"); + let mut features = Features::with_defaults(); + features.disable(Feature::ViewImageTool); + features.enable(Feature::UnifiedExec); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: false, - include_apply_patch_tool: false, - include_web_search_request: false, - use_streamable_shell_tool: false, - include_view_image_tool: false, - experimental_unified_exec_tool: true, + features: &features, }); let (tools, _) = build_specs(&config, None).build(); @@ -969,14 +964,11 @@ mod tests { fn test_test_model_family_includes_sync_tool() { let model_family = find_family_for_model("test-gpt-5-codex") .expect("test-gpt-5-codex should be a valid model family"); + let mut features = Features::with_defaults(); + features.disable(Feature::ViewImageTool); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: false, - include_apply_patch_tool: false, - include_web_search_request: false, - use_streamable_shell_tool: false, - include_view_image_tool: false, - experimental_unified_exec_tool: false, + features: &features, }); let (tools, _) = build_specs(&config, None).build(); @@ -1001,14 +993,12 @@ mod tests { #[test] fn test_build_specs_mcp_tools() { let model_family = find_family_for_model("o3").expect("o3 should be a valid model family"); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); + features.enable(Feature::WebSearchRequest); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: false, - include_apply_patch_tool: false, - include_web_search_request: true, - use_streamable_shell_tool: false, - include_view_image_tool: true, - experimental_unified_exec_tool: true, + features: &features, }); let (tools, _) = build_specs( &config, @@ -1106,14 +1096,11 @@ mod tests { #[test] fn test_build_specs_mcp_tools_sorted_by_name() { let model_family = find_family_for_model("o3").expect("o3 should be a valid model family"); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: false, - include_apply_patch_tool: false, - include_web_search_request: false, - use_streamable_shell_tool: false, - include_view_image_tool: true, - experimental_unified_exec_tool: true, + features: &features, }); // Intentionally construct a map with keys that would sort alphabetically. @@ -1183,14 +1170,12 @@ mod tests { fn test_mcp_tool_property_missing_type_defaults_to_string() { let model_family = find_family_for_model("gpt-5-codex") .expect("gpt-5-codex should be a valid model family"); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); + features.enable(Feature::WebSearchRequest); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: false, - include_apply_patch_tool: false, - include_web_search_request: true, - use_streamable_shell_tool: false, - include_view_image_tool: true, - experimental_unified_exec_tool: true, + features: &features, }); let (tools, _) = build_specs( @@ -1252,14 +1237,12 @@ mod tests { fn test_mcp_tool_integer_normalized_to_number() { let model_family = find_family_for_model("gpt-5-codex") .expect("gpt-5-codex should be a valid model family"); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); + features.enable(Feature::WebSearchRequest); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: false, - include_apply_patch_tool: false, - include_web_search_request: true, - use_streamable_shell_tool: false, - include_view_image_tool: true, - experimental_unified_exec_tool: true, + features: &features, }); let (tools, _) = build_specs( @@ -1316,14 +1299,13 @@ mod tests { fn test_mcp_tool_array_without_items_gets_default_string_items() { let model_family = find_family_for_model("gpt-5-codex") .expect("gpt-5-codex should be a valid model family"); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); + features.enable(Feature::WebSearchRequest); + features.enable(Feature::ApplyPatchFreeform); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: false, - include_apply_patch_tool: true, - include_web_search_request: true, - use_streamable_shell_tool: false, - include_view_image_tool: true, - experimental_unified_exec_tool: true, + features: &features, }); let (tools, _) = build_specs( @@ -1383,14 +1365,12 @@ mod tests { fn test_mcp_tool_anyof_defaults_to_string() { let model_family = find_family_for_model("gpt-5-codex") .expect("gpt-5-codex should be a valid model family"); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); + features.enable(Feature::WebSearchRequest); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: false, - include_apply_patch_tool: false, - include_web_search_request: true, - use_streamable_shell_tool: false, - include_view_image_tool: true, - experimental_unified_exec_tool: true, + features: &features, }); let (tools, _) = build_specs( @@ -1462,14 +1442,12 @@ mod tests { fn test_get_openai_tools_mcp_tools_with_additional_properties_schema() { let model_family = find_family_for_model("gpt-5-codex") .expect("gpt-5-codex should be a valid model family"); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); + features.enable(Feature::WebSearchRequest); let config = ToolsConfig::new(&ToolsConfigParams { model_family: &model_family, - include_plan_tool: false, - include_apply_patch_tool: false, - include_web_search_request: true, - use_streamable_shell_tool: false, - include_view_image_tool: true, - experimental_unified_exec_tool: true, + features: &features, }); let (tools, _) = build_specs( &config, diff --git a/codex-rs/core/tests/suite/model_tools.rs b/codex-rs/core/tests/suite/model_tools.rs index ee7b44d4b0..f26cfcf67c 100644 --- a/codex-rs/core/tests/suite/model_tools.rs +++ b/codex-rs/core/tests/suite/model_tools.rs @@ -4,6 +4,7 @@ use codex_core::CodexAuth; use codex_core::ConversationManager; use codex_core::ModelProviderInfo; use codex_core::built_in_model_providers; +use codex_core::features::Feature; use codex_core::model_family::find_family_for_model; use codex_core::protocol::EventMsg; use codex_core::protocol::InputItem; @@ -56,12 +57,12 @@ async fn collect_tool_identifiers_for_model(model: &str) -> Vec { config.model = model.to_string(); config.model_family = find_family_for_model(model).unwrap_or_else(|| panic!("unknown model family for {model}")); - config.include_plan_tool = false; - config.include_apply_patch_tool = false; - config.include_view_image_tool = false; - config.tools_web_search_request = false; - config.use_experimental_streamable_shell_tool = false; - config.use_experimental_unified_exec_tool = false; + config.features.disable(Feature::PlanTool); + config.features.disable(Feature::ApplyPatchFreeform); + config.features.disable(Feature::ViewImageTool); + config.features.disable(Feature::WebSearchRequest); + config.features.disable(Feature::StreamableShell); + config.features.disable(Feature::UnifiedExec); let conversation_manager = ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index 9ca0cc9369..dc000af449 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -5,6 +5,7 @@ use codex_core::ConversationManager; use codex_core::ModelProviderInfo; use codex_core::built_in_model_providers; use codex_core::config::OPENAI_DEFAULT_MODEL; +use codex_core::features::Feature; use codex_core::model_family::find_family_for_model; use codex_core::protocol::AskForApproval; use codex_core::protocol::EventMsg; @@ -99,10 +100,10 @@ async fn codex_mini_latest_tools() { config.cwd = cwd.path().to_path_buf(); config.model_provider = model_provider; config.user_instructions = Some("be consistent and helpful".to_string()); + config.features.disable(Feature::ApplyPatchFreeform); let conversation_manager = ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); - config.include_apply_patch_tool = false; config.model = "codex-mini-latest".to_string(); config.model_family = find_family_for_model("codex-mini-latest").unwrap(); @@ -185,7 +186,7 @@ async fn prompt_tools_are_consistent_across_requests() { config.cwd = cwd.path().to_path_buf(); config.model_provider = model_provider; config.user_instructions = Some("be consistent and helpful".to_string()); - config.include_plan_tool = true; + config.features.enable(Feature::PlanTool); let conversation_manager = ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index e111cebcb7..9dd921b91f 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -9,6 +9,7 @@ use std::time::UNIX_EPOCH; use codex_core::config_types::McpServerConfig; use codex_core::config_types::McpServerTransportConfig; +use codex_core::features::Feature; use codex_core::protocol::AskForApproval; use codex_core::protocol::EventMsg; @@ -74,7 +75,7 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> { let fixture = test_codex() .with_config(move |config| { - config.use_experimental_use_rmcp_client = true; + config.features.enable(Feature::RmcpClient); config.mcp_servers.insert( server_name.to_string(), McpServerConfig { @@ -227,7 +228,7 @@ async fn streamable_http_tool_call_round_trip() -> anyhow::Result<()> { let fixture = test_codex() .with_config(move |config| { - config.use_experimental_use_rmcp_client = true; + config.features.enable(Feature::RmcpClient); config.mcp_servers.insert( server_name.to_string(), McpServerConfig { @@ -408,7 +409,7 @@ async fn streamable_http_with_oauth_round_trip() -> anyhow::Result<()> { let fixture = test_codex() .with_config(move |config| { - config.use_experimental_use_rmcp_client = true; + config.features.enable(Feature::RmcpClient); config.mcp_servers.insert( server_name.to_string(), McpServerConfig { diff --git a/codex-rs/core/tests/suite/shell_serialization.rs b/codex-rs/core/tests/suite/shell_serialization.rs index fd9c26d882..ba509e2825 100644 --- a/codex-rs/core/tests/suite/shell_serialization.rs +++ b/codex-rs/core/tests/suite/shell_serialization.rs @@ -1,6 +1,7 @@ #![cfg(not(target_os = "windows"))] use anyhow::Result; +use codex_core::features::Feature; use codex_core::model_family::find_family_for_model; use codex_core::protocol::AskForApproval; use codex_core::protocol::EventMsg; @@ -77,7 +78,7 @@ async fn shell_output_stays_json_without_freeform_apply_patch() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.include_apply_patch_tool = false; + config.features.disable(Feature::ApplyPatchFreeform); config.model = "gpt-5".to_string(); config.model_family = find_family_for_model("gpt-5").expect("gpt-5 is a model family"); }); @@ -143,7 +144,7 @@ async fn shell_output_is_structured_with_freeform_apply_patch() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.include_apply_patch_tool = true; + config.features.enable(Feature::ApplyPatchFreeform); }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/tool_harness.rs b/codex-rs/core/tests/suite/tool_harness.rs index eaefe7d9dc..a89317b7ba 100644 --- a/codex-rs/core/tests/suite/tool_harness.rs +++ b/codex-rs/core/tests/suite/tool_harness.rs @@ -1,6 +1,7 @@ #![cfg(not(target_os = "windows"))] use assert_matches::assert_matches; +use codex_core::features::Feature; use codex_core::model_family::find_family_for_model; use codex_core::protocol::AskForApproval; use codex_core::protocol::EventMsg; @@ -104,7 +105,7 @@ async fn update_plan_tool_emits_plan_update_event() -> anyhow::Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.include_plan_tool = true; + config.features.enable(Feature::PlanTool); }); let TestCodex { codex, @@ -191,7 +192,7 @@ async fn update_plan_tool_rejects_malformed_payload() -> anyhow::Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.include_plan_tool = true; + config.features.enable(Feature::PlanTool); }); let TestCodex { codex, @@ -285,7 +286,7 @@ async fn apply_patch_tool_executes_and_emits_patch_events() -> anyhow::Result<() let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.include_apply_patch_tool = true; + config.features.enable(Feature::ApplyPatchFreeform); }); let TestCodex { codex, @@ -403,7 +404,7 @@ async fn apply_patch_reports_parse_diagnostics() -> anyhow::Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.include_apply_patch_tool = true; + config.features.enable(Feature::ApplyPatchFreeform); }); let TestCodex { codex, diff --git a/codex-rs/core/tests/suite/tools.rs b/codex-rs/core/tests/suite/tools.rs index ba87cb333d..ec07b0cdbd 100644 --- a/codex-rs/core/tests/suite/tools.rs +++ b/codex-rs/core/tests/suite/tools.rs @@ -2,6 +2,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used)] use anyhow::Result; +use codex_core::features::Feature; use codex_core::model_family::find_family_for_model; use codex_core::protocol::AskForApproval; use codex_core::protocol::EventMsg; @@ -293,7 +294,11 @@ async fn collect_tools(use_unified_exec: bool) -> Result> { let mock = mount_sse_sequence(&server, responses).await; let mut builder = test_codex().with_config(move |config| { - config.use_experimental_unified_exec_tool = use_unified_exec; + if use_unified_exec { + config.features.enable(Feature::UnifiedExec); + } else { + config.features.disable(Feature::UnifiedExec); + } }); let test = builder.build(&server).await?; diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index cfa96dd75c..6298ab06de 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -3,6 +3,7 @@ use std::collections::HashMap; use anyhow::Result; +use codex_core::features::Feature; use codex_core::protocol::AskForApproval; use codex_core::protocol::EventMsg; use codex_core::protocol::InputItem; @@ -42,7 +43,13 @@ fn collect_tool_outputs(bodies: &[Value]) -> Result> { if let Some(call_id) = item.get("call_id").and_then(Value::as_str) { let content = extract_output_text(item) .ok_or_else(|| anyhow::anyhow!("missing tool output content"))?; - let parsed: Value = serde_json::from_str(content)?; + let trimmed = content.trim(); + if trimmed.is_empty() { + continue; + } + let parsed: Value = serde_json::from_str(trimmed).map_err(|err| { + anyhow::anyhow!("failed to parse tool output content {trimmed:?}: {err}") + })?; outputs.insert(call_id.to_string(), parsed); } } @@ -59,7 +66,7 @@ async fn unified_exec_reuses_session_via_stdin() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.use_experimental_unified_exec_tool = true; + config.features.enable(Feature::UnifiedExec); }); let TestCodex { codex, @@ -176,6 +183,7 @@ async fn unified_exec_streams_after_lagged_output() -> Result<()> { let mut builder = test_codex().with_config(|config| { config.use_experimental_unified_exec_tool = true; + config.features.enable(Feature::UnifiedExec); }); let TestCodex { codex, @@ -300,7 +308,7 @@ async fn unified_exec_timeout_and_followup_poll() -> Result<()> { let server = start_mock_server().await; let mut builder = test_codex().with_config(|config| { - config.use_experimental_unified_exec_tool = true; + config.features.enable(Feature::UnifiedExec); }); let TestCodex { codex, From 9be704a934fb51e7cf3e38614c0bf7e0033e0aa7 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Tue, 14 Oct 2025 11:02:11 -0700 Subject: [PATCH 30/32] tui: reserve 1 cell right margin for composer and user history (#5026) keep a 1 cell margin at the right edge of the screen in the composer (and in the user message in history). this lets us print clear-to-EOL 1 char before the end of the line in history, so that resizing the terminal will keep the background color (at least in iterm/terminal.app). it also stops the cursor in the textarea from floating off the right edge. --------- Co-authored-by: joshka-oai --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 7 +++++-- ...ts__status_hidden_when_height_too_small_height_1.snap | 2 +- ...ts__status_hidden_when_height_too_small_height_2.snap | 2 +- codex-rs/tui/src/history_cell.rs | 9 +++++++-- ...story_cell_wraps_and_prefixes_each_line_snapshot.snap | 6 +++--- 5 files changed, 17 insertions(+), 9 deletions(-) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 5b63a410bb..0d1395d51d 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -165,8 +165,9 @@ impl ChatComposer { .unwrap_or_else(|| footer_height(footer_props)); let footer_spacing = Self::footer_spacing(footer_hint_height); let footer_total_height = footer_hint_height + footer_spacing; + const COLS_WITH_MARGIN: u16 = LIVE_PREFIX_COLS + 1; self.textarea - .desired_height(width.saturating_sub(LIVE_PREFIX_COLS)) + .desired_height(width.saturating_sub(COLS_WITH_MARGIN)) + 2 + match &self.active_popup { ActivePopup::None => footer_total_height, @@ -197,7 +198,9 @@ impl ChatComposer { let [composer_rect, popup_rect] = Layout::vertical([Constraint::Min(1), popup_constraint]).areas(area); let mut textarea_rect = composer_rect; - textarea_rect.width = textarea_rect.width.saturating_sub(LIVE_PREFIX_COLS); + textarea_rect.width = textarea_rect.width.saturating_sub( + LIVE_PREFIX_COLS + 1, /* keep a one-column right margin for wrapping */ + ); textarea_rect.x = textarea_rect.x.saturating_add(LIVE_PREFIX_COLS); [composer_rect, textarea_rect, popup_rect] } diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_1.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_1.snap index 310c32b40c..52f96e8557 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_1.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_1.snap @@ -2,4 +2,4 @@ source: tui/src/bottom_pane/mod.rs expression: "render_snapshot(&pane, area1)" --- -› Ask Codex to do an +› Ask Codex to do a diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_2.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_2.snap index ea0beeedf3..964bf7ed87 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_2.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_2.snap @@ -3,4 +3,4 @@ source: tui/src/bottom_pane/mod.rs expression: "render_snapshot(&pane, area2)" --- -› Ask Codex to do an +› Ask Codex to do a diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 2cc0c3fd9e..fe37d5fa09 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -114,7 +114,11 @@ impl HistoryCell for UserHistoryCell { fn display_lines(&self, width: u16) -> Vec> { let mut lines: Vec> = Vec::new(); - let wrap_width = width.saturating_sub(LIVE_PREFIX_COLS); + let wrap_width = width + .saturating_sub( + LIVE_PREFIX_COLS + 1, /* keep a one-column right margin for wrapping */ + ) + .max(1); let style = user_message_style(); @@ -125,7 +129,8 @@ impl HistoryCell for UserHistoryCell { .map(|l| Line::from(l).style(style)) .collect::>(), // Wrap algorithm matches textarea.rs. - RtOptions::new(wrap_width as usize).wrap_algorithm(textwrap::WrapAlgorithm::FirstFit), + RtOptions::new(usize::from(wrap_width)) + .wrap_algorithm(textwrap::WrapAlgorithm::FirstFit), ); lines.push(Line::from("").style(style)); diff --git a/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__user_history_cell_wraps_and_prefixes_each_line_snapshot.snap b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__user_history_cell_wraps_and_prefixes_each_line_snapshot.snap index 3fd59095ce..9870dddb06 100644 --- a/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__user_history_cell_wraps_and_prefixes_each_line_snapshot.snap +++ b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__user_history_cell_wraps_and_prefixes_each_line_snapshot.snap @@ -3,6 +3,6 @@ source: tui/src/history_cell.rs expression: rendered --- › one two - three four - five six - seven + three + four five + six seven From 13035561cd5fa33078354afc95a3184eed68c7fe Mon Sep 17 00:00:00 2001 From: Javi <666807+JaviSoto@users.noreply.github.com> Date: Tue, 14 Oct 2025 11:55:10 -0700 Subject: [PATCH 31/32] feat: pass codex thread ID in notifier metadata (#4582) --- codex-rs/core/src/codex.rs | 1 + codex-rs/core/src/user_notification.rs | 4 +++- docs/config.md | 7 ++++++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 495af42c65..88f42c0f6c 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -1858,6 +1858,7 @@ pub(crate) async fn run_task( ); sess.notifier() .notify(&UserNotification::AgentTurnComplete { + thread_id: sess.conversation_id.to_string(), turn_id: sub_id.clone(), input_messages: turn_input_messages, last_assistant_message: last_agent_message.clone(), diff --git a/codex-rs/core/src/user_notification.rs b/codex-rs/core/src/user_notification.rs index 5eb9e98058..be96d56270 100644 --- a/codex-rs/core/src/user_notification.rs +++ b/codex-rs/core/src/user_notification.rs @@ -49,6 +49,7 @@ impl UserNotifier { pub(crate) enum UserNotification { #[serde(rename_all = "kebab-case")] AgentTurnComplete { + thread_id: String, turn_id: String, /// Messages that the user sent to the agent to initiate the turn. @@ -67,6 +68,7 @@ mod tests { #[test] fn test_user_notification() -> Result<()> { let notification = UserNotification::AgentTurnComplete { + thread_id: "b5f6c1c2-1111-2222-3333-444455556666".to_string(), turn_id: "12345".to_string(), input_messages: vec!["Rename `foo` to `bar` and update the callsites.".to_string()], last_assistant_message: Some( @@ -76,7 +78,7 @@ mod tests { let serialized = serde_json::to_string(¬ification)?; assert_eq!( serialized, - r#"{"type":"agent-turn-complete","turn-id":"12345","input-messages":["Rename `foo` to `bar` and update the callsites."],"last-assistant-message":"Rename complete and verified `cargo build` succeeds."}"# + r#"{"type":"agent-turn-complete","thread-id":"b5f6c1c2-1111-2222-3333-444455556666","turn-id":"12345","input-messages":["Rename `foo` to `bar` and update the callsites."],"last-assistant-message":"Rename complete and verified `cargo build` succeeds."}"# ); Ok(()) } diff --git a/docs/config.md b/docs/config.md index 2ac7aba6b7..c1d305f35a 100644 --- a/docs/config.md +++ b/docs/config.md @@ -602,6 +602,7 @@ Specify a program that will be executed to get notified about events generated b ```json { "type": "agent-turn-complete", + "thread-id": "b5f6c1c2-1111-2222-3333-444455556666", "turn-id": "12345", "input-messages": ["Rename `foo` to `bar` and update the callsites."], "last-assistant-message": "Rename complete and verified `cargo build` succeeds." @@ -610,6 +611,8 @@ Specify a program that will be executed to get notified about events generated b The `"type"` property will always be set. Currently, `"agent-turn-complete"` is the only notification type that is supported. +`"thread-id"` contains a string that identifies the Codex session that produced the notification; you can use it to correlate multiple turns that belong to the same task. + As an example, here is a Python script that parses the JSON and decides whether to show a desktop push notification using [terminal-notifier](https://github.com/julienXX/terminal-notifier) on macOS: ```python @@ -644,6 +647,8 @@ def main() -> int: print(f"not sending a push notification for: {notification_type}") return 0 + thread_id = notification.get("thread-id", "") + subprocess.check_output( [ "terminal-notifier", @@ -652,7 +657,7 @@ def main() -> int: "-message", message, "-group", - "codex", + "codex-" + thread_id, "-ignoreDnD", "-activate", "com.googlecode.iterm2", From 0a0a10d8b3aff709a4c07bfe468376202b0b5e16 Mon Sep 17 00:00:00 2001 From: Dylan Date: Tue, 14 Oct 2025 13:00:49 -0700 Subject: [PATCH 32/32] fix: apply_patch shell_serialization tests (#4786) ## Summary Adds additional shell_serialization tests specifically for apply_patch and other cases. ## Test Plan - [x] These are all tests --- codex-rs/core/src/executor/backends.rs | 24 +- codex-rs/core/src/executor/runner.rs | 26 +- codex-rs/core/tests/common/test_codex.rs | 7 + .../core/tests/suite/shell_serialization.rs | 548 +++++++++++++++++- codex-rs/core/tests/suite/tool_harness.rs | 60 +- 5 files changed, 608 insertions(+), 57 deletions(-) diff --git a/codex-rs/core/src/executor/backends.rs b/codex-rs/core/src/executor/backends.rs index 95cdb3cacb..9c65745c4f 100644 --- a/codex-rs/core/src/executor/backends.rs +++ b/codex-rs/core/src/executor/backends.rs @@ -6,6 +6,7 @@ use async_trait::async_trait; use crate::CODEX_APPLY_PATCH_ARG1; use crate::apply_patch::ApplyPatchExec; use crate::exec::ExecParams; +use crate::executor::ExecutorConfig; use crate::function_tool::FunctionCallError; pub(crate) enum ExecutionMode { @@ -22,6 +23,7 @@ pub(crate) trait ExecutionBackend: Send + Sync { params: ExecParams, // Required for downcasting the apply_patch. mode: &ExecutionMode, + config: &ExecutorConfig, ) -> Result; fn stream_stdout(&self, _mode: &ExecutionMode) -> bool { @@ -47,6 +49,7 @@ impl ExecutionBackend for ShellBackend { &self, params: ExecParams, mode: &ExecutionMode, + _config: &ExecutorConfig, ) -> Result { match mode { ExecutionMode::Shell => Ok(params), @@ -65,17 +68,22 @@ impl ExecutionBackend for ApplyPatchBackend { &self, params: ExecParams, mode: &ExecutionMode, + config: &ExecutorConfig, ) -> Result { match mode { ExecutionMode::ApplyPatch(exec) => { - let path_to_codex = env::current_exe() - .ok() - .map(|p| p.to_string_lossy().to_string()) - .ok_or_else(|| { - FunctionCallError::RespondToModel( - "failed to determine path to codex executable".to_string(), - ) - })?; + let path_to_codex = if let Some(exe_path) = &config.codex_exe { + exe_path.to_string_lossy().to_string() + } else { + env::current_exe() + .ok() + .map(|p| p.to_string_lossy().to_string()) + .ok_or_else(|| { + FunctionCallError::RespondToModel( + "failed to determine path to codex executable".to_string(), + ) + })? + }; let patch = exec.action.patch.clone(); Ok(ExecParams { diff --git a/codex-rs/core/src/executor/runner.rs b/codex-rs/core/src/executor/runner.rs index 9a1956f66f..e13016e37f 100644 --- a/codex-rs/core/src/executor/runner.rs +++ b/codex-rs/core/src/executor/runner.rs @@ -30,19 +30,19 @@ use codex_otel::otel_event_manager::ToolDecisionSource; pub(crate) struct ExecutorConfig { pub(crate) sandbox_policy: SandboxPolicy, pub(crate) sandbox_cwd: PathBuf, - codex_linux_sandbox_exe: Option, + pub(crate) codex_exe: Option, } impl ExecutorConfig { pub(crate) fn new( sandbox_policy: SandboxPolicy, sandbox_cwd: PathBuf, - codex_linux_sandbox_exe: Option, + codex_exe: Option, ) -> Self { Self { sandbox_policy, sandbox_cwd, - codex_linux_sandbox_exe, + codex_exe, } } } @@ -86,7 +86,14 @@ impl Executor { maybe_translate_shell_command(request.params, session, request.use_shell_profile); } - // Step 1: Normalise parameters via the selected backend. + // Step 1: Snapshot sandbox configuration so it stays stable for this run. + let config = self + .config + .read() + .map_err(|_| ExecError::rejection("executor config poisoned"))? + .clone(); + + // Step 2: Normalise parameters via the selected backend. let backend = backend_for_mode(&request.mode); let stdout_stream = if backend.stream_stdout(&request.mode) { request.stdout_stream.clone() @@ -94,16 +101,9 @@ impl Executor { None }; request.params = backend - .prepare(request.params, &request.mode) + .prepare(request.params, &request.mode, &config) .map_err(ExecError::from)?; - // Step 2: Snapshot sandbox configuration so it stays stable for this run. - let config = self - .config - .read() - .map_err(|_| ExecError::rejection("executor config poisoned"))? - .clone(); - // Step 3: Decide sandbox placement, prompting for approval when needed. let sandbox_decision = select_sandbox( &request, @@ -227,7 +227,7 @@ impl Executor { sandbox, &config.sandbox_policy, &config.sandbox_cwd, - &config.codex_linux_sandbox_exe, + &config.codex_exe, stdout_stream, ) .await diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 3957b05248..0e07d82228 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -1,4 +1,5 @@ use std::mem::swap; +use std::path::PathBuf; use std::sync::Arc; use codex_core::CodexAuth; @@ -39,6 +40,12 @@ impl TestCodexBuilder { let mut config = load_default_config_for_test(&home); config.cwd = cwd.path().to_path_buf(); config.model_provider = model_provider; + config.codex_linux_sandbox_exe = Some(PathBuf::from( + assert_cmd::Command::cargo_bin("codex")? + .get_program() + .to_os_string(), + )); + let mut mutators = vec![]; swap(&mut self.config_mutators, &mut mutators); diff --git a/codex-rs/core/tests/suite/shell_serialization.rs b/codex-rs/core/tests/suite/shell_serialization.rs index ba509e2825..b671f17fcb 100644 --- a/codex-rs/core/tests/suite/shell_serialization.rs +++ b/codex-rs/core/tests/suite/shell_serialization.rs @@ -10,9 +10,12 @@ use codex_core::protocol::Op; use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use core_test_support::assert_regex_match; +use core_test_support::responses::ev_apply_patch_function_call; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_custom_tool_call; use core_test_support::responses::ev_function_call; +use core_test_support::responses::ev_local_shell_call; use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; @@ -21,8 +24,11 @@ use core_test_support::skip_if_no_network; use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; +use pretty_assertions::assert_eq; +use regex_lite::Regex; use serde_json::Value; use serde_json::json; +use std::fs; async fn submit_turn(test: &TestCodex, prompt: &str, sandbox_policy: SandboxPolicy) -> Result<()> { let session_model = test.session_configured.model.clone(); @@ -72,6 +78,21 @@ fn find_function_call_output<'a>(bodies: &'a [Value], call_id: &str) -> Option<& None } +fn find_custom_tool_call_output<'a>(bodies: &'a [Value], call_id: &str) -> Option<&'a Value> { + for body in bodies { + if let Some(items) = body.get("input").and_then(Value::as_array) { + for item in items { + if item.get("type").and_then(Value::as_str) == Some("custom_tool_call_output") + && item.get("call_id").and_then(Value::as_str) == Some(call_id) + { + return Some(item); + } + } + } + } + None +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn shell_output_stays_json_without_freeform_apply_patch() -> Result<()> { skip_if_no_network!(Ok(())); @@ -120,7 +141,12 @@ async fn shell_output_stays_json_without_freeform_apply_patch() -> Result<()> { .and_then(Value::as_str) .expect("shell output string"); - let parsed: Value = serde_json::from_str(output)?; + let mut parsed: Value = serde_json::from_str(output)?; + if let Some(metadata) = parsed.get_mut("metadata").and_then(Value::as_object_mut) { + // duration_seconds is non-deterministic; remove it for deep equality + let _ = metadata.remove("duration_seconds"); + } + assert_eq!( parsed .get("metadata") @@ -199,6 +225,83 @@ freeform shell Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shell_output_for_freeform_tool_records_duration() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex().with_config(|config| { + config.include_apply_patch_tool = true; + }); + let test = builder.build(&server).await?; + + #[cfg(target_os = "linux")] + let sleep_cmd = vec!["/bin/bash", "-c", "sleep 1"]; + + #[cfg(target_os = "macos")] + let sleep_cmd = vec!["/bin/bash", "-c", "sleep 1"]; + + #[cfg(windows)] + let sleep_cmd = "timeout 1"; + + let call_id = "shell-structured"; + let args = json!({ + "command": sleep_cmd, + "timeout_ms": 2_000, + }); + let responses = vec![ + sse(vec![ + json!({"type": "response.created", "response": {"id": "resp-1"}}), + ev_function_call(call_id, "shell", &serde_json::to_string(&args)?), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ]; + mount_sse_sequence(&server, responses).await; + + submit_turn( + &test, + "run the structured shell command", + SandboxPolicy::DangerFullAccess, + ) + .await?; + + let requests = server + .received_requests() + .await + .expect("recorded requests present"); + let bodies = request_bodies(&requests)?; + let output_item = + find_function_call_output(&bodies, call_id).expect("structured output present"); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("structured output string"); + + let expected_pattern = r#"(?s)^Exit code: 0 +Wall time: [0-9]+(?:\.[0-9]+)? seconds +Output: +$"#; + assert_regex_match(expected_pattern, output); + + let wall_time_regex = Regex::new(r"(?m)^Wall (?:time|Clock): ([0-9]+(?:\.[0-9]+)?) seconds$") + .expect("compile wall time regex"); + let wall_time_seconds = wall_time_regex + .captures(output) + .and_then(|caps| caps.get(1)) + .and_then(|value| value.as_str().parse::().ok()) + .expect("expected structured shell output to contain wall time seconds"); + assert!( + wall_time_seconds > 0.5, + "expected wall time to be greater than zero seconds, got {wall_time_seconds}" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn shell_output_reserializes_truncated_content() -> Result<()> { skip_if_no_network!(Ok(())); @@ -276,3 +379,446 @@ $"#; Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_custom_tool_output_is_structured() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex().with_config(|config| { + config.include_apply_patch_tool = true; + }); + let test = builder.build(&server).await?; + + let call_id = "apply-patch-structured"; + let file_name = "structured.txt"; + let patch = format!( + r#"*** Begin Patch +*** Add File: {file_name} ++from custom tool +*** End Patch +"# + ); + let responses = vec![ + sse(vec![ + json!({"type": "response.created", "response": {"id": "resp-1"}}), + ev_custom_tool_call(call_id, "apply_patch", &patch), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ]; + mount_sse_sequence(&server, responses).await; + + submit_turn( + &test, + "apply the patch via custom tool", + SandboxPolicy::DangerFullAccess, + ) + .await?; + + let requests = server + .received_requests() + .await + .expect("recorded requests present"); + let bodies = request_bodies(&requests)?; + let output_item = + find_custom_tool_call_output(&bodies, call_id).expect("apply_patch output present"); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("apply_patch output string"); + + let expected_pattern = format!( + r"(?s)^Exit code: 0 +Wall time: [0-9]+(?:\.[0-9]+)? seconds +Output: +Success. Updated the following files: +A {file_name} +?$" + ); + assert_regex_match(&expected_pattern, output); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_custom_tool_call_creates_file() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex().with_config(|config| { + config.include_apply_patch_tool = true; + }); + let test = builder.build(&server).await?; + + let call_id = "apply-patch-add-file"; + let file_name = "custom_tool_apply_patch.txt"; + let patch = format!( + "*** Begin Patch\n*** Add File: {file_name}\n+custom tool content\n*** End Patch\n" + ); + let responses = vec![ + sse(vec![ + json!({"type": "response.created", "response": {"id": "resp-1"}}), + ev_custom_tool_call(call_id, "apply_patch", &patch), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "apply_patch done"), + ev_completed("resp-2"), + ]), + ]; + mount_sse_sequence(&server, responses).await; + + submit_turn( + &test, + "apply the patch via custom tool to create a file", + SandboxPolicy::DangerFullAccess, + ) + .await?; + + let requests = server + .received_requests() + .await + .expect("recorded requests present"); + let bodies = request_bodies(&requests)?; + let output_item = + find_custom_tool_call_output(&bodies, call_id).expect("apply_patch output present"); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("apply_patch output string"); + + let expected_pattern = format!( + r"(?s)^Exit code: 0 +Wall time: [0-9]+(?:\.[0-9]+)? seconds +Output: +Success. Updated the following files: +A {file_name} +?$" + ); + assert_regex_match(&expected_pattern, output); + + let new_file_path = test.cwd.path().join(file_name); + let created_contents = fs::read_to_string(&new_file_path)?; + assert_eq!( + created_contents, "custom tool content\n", + "expected file contents for {file_name}" + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_custom_tool_call_updates_existing_file() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex().with_config(|config| { + config.include_apply_patch_tool = true; + }); + let test = builder.build(&server).await?; + + let call_id = "apply-patch-update-file"; + let file_name = "custom_tool_apply_patch_existing.txt"; + let file_path = test.cwd.path().join(file_name); + fs::write(&file_path, "before\n")?; + let patch = format!( + "*** Begin Patch\n*** Update File: {file_name}\n@@\n-before\n+after\n*** End Patch\n" + ); + let responses = vec![ + sse(vec![ + json!({"type": "response.created", "response": {"id": "resp-1"}}), + ev_custom_tool_call(call_id, "apply_patch", &patch), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "apply_patch update done"), + ev_completed("resp-2"), + ]), + ]; + mount_sse_sequence(&server, responses).await; + + submit_turn( + &test, + "apply the patch via custom tool to update a file", + SandboxPolicy::DangerFullAccess, + ) + .await?; + + let requests = server + .received_requests() + .await + .expect("recorded requests present"); + let bodies = request_bodies(&requests)?; + let output_item = + find_custom_tool_call_output(&bodies, call_id).expect("apply_patch output present"); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("apply_patch output string"); + + let expected_pattern = format!( + r"(?s)^Exit code: 0 +Wall time: [0-9]+(?:\.[0-9]+)? seconds +Output: +Success. Updated the following files: +M {file_name} +?$" + ); + assert_regex_match(&expected_pattern, output); + + let updated_contents = fs::read_to_string(file_path)?; + assert_eq!(updated_contents, "after\n", "expected updated file content"); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_custom_tool_call_reports_failure_output() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex().with_config(|config| { + config.include_apply_patch_tool = true; + }); + let test = builder.build(&server).await?; + + let call_id = "apply-patch-failure"; + let missing_file = "missing_custom_tool_apply_patch.txt"; + let patch = format!( + "*** Begin Patch\n*** Update File: {missing_file}\n@@\n-before\n+after\n*** End Patch\n" + ); + let responses = vec![ + sse(vec![ + json!({"type": "response.created", "response": {"id": "resp-1"}}), + ev_custom_tool_call(call_id, "apply_patch", &patch), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "apply_patch failure done"), + ev_completed("resp-2"), + ]), + ]; + mount_sse_sequence(&server, responses).await; + + submit_turn( + &test, + "attempt a failing apply_patch via custom tool", + SandboxPolicy::DangerFullAccess, + ) + .await?; + + let requests = server + .received_requests() + .await + .expect("recorded requests present"); + let bodies = request_bodies(&requests)?; + let output_item = + find_custom_tool_call_output(&bodies, call_id).expect("apply_patch output present"); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("apply_patch output string"); + + let expected_output = format!( + "apply_patch verification failed: Failed to read file to update {}/{missing_file}: No such file or directory (os error 2)", + test.cwd.path().to_string_lossy() + ); + assert_eq!(output, expected_output); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apply_patch_function_call_output_is_structured() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex().with_config(|config| { + config.include_apply_patch_tool = true; + }); + let test = builder.build(&server).await?; + + let call_id = "apply-patch-function"; + let file_name = "function_apply_patch.txt"; + let patch = + format!("*** Begin Patch\n*** Add File: {file_name}\n+via function call\n*** End Patch\n"); + let responses = vec![ + sse(vec![ + json!({"type": "response.created", "response": {"id": "resp-1"}}), + ev_apply_patch_function_call(call_id, &patch), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "apply_patch function done"), + ev_completed("resp-2"), + ]), + ]; + mount_sse_sequence(&server, responses).await; + + submit_turn( + &test, + "apply the patch via function-call apply_patch", + SandboxPolicy::DangerFullAccess, + ) + .await?; + + let requests = server + .received_requests() + .await + .expect("recorded requests present"); + let bodies = request_bodies(&requests)?; + let output_item = + find_function_call_output(&bodies, call_id).expect("apply_patch function output present"); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("apply_patch output string"); + + let expected_pattern = format!( + r"(?s)^Exit code: 0 +Wall time: [0-9]+(?:\.[0-9]+)? seconds +Output: +Success. Updated the following files: +A {file_name} +?$" + ); + assert_regex_match(&expected_pattern, output); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn shell_output_is_structured_for_nonzero_exit() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex().with_config(|config| { + config.model = "gpt-5-codex".to_string(); + config.model_family = + find_family_for_model("gpt-5-codex").expect("gpt-5-codex is a model family"); + config.include_apply_patch_tool = true; + }); + let test = builder.build(&server).await?; + + let call_id = "shell-nonzero-exit"; + let args = json!({ + "command": ["/bin/sh", "-c", "exit 42"], + "timeout_ms": 1_000, + }); + let responses = vec![ + sse(vec![ + json!({"type": "response.created", "response": {"id": "resp-1"}}), + ev_function_call(call_id, "shell", &serde_json::to_string(&args)?), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "shell failure handled"), + ev_completed("resp-2"), + ]), + ]; + mount_sse_sequence(&server, responses).await; + + submit_turn( + &test, + "run the failing shell command", + SandboxPolicy::DangerFullAccess, + ) + .await?; + + let requests = server + .received_requests() + .await + .expect("recorded requests present"); + let bodies = request_bodies(&requests)?; + let output_item = find_function_call_output(&bodies, call_id).expect("shell output present"); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("shell output string"); + + let expected_output = r"Exit code: 42 +Wall time: 0 seconds +Output: +"; + assert_eq!(output, expected_output); + assert!( + serde_json::from_str::(output).is_err(), + "expected structured shell output to be plain text", + ); + assert!( + output.starts_with("Exit code: 42\n"), + "expected non-zero exit code prefix, got {output:?}", + ); + assert!( + output.contains("\nOutput:\n"), + "expected Output section, got {output:?}", + ); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn local_shell_call_output_is_structured() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut builder = test_codex().with_config(|config| { + config.model = "gpt-5-codex".to_string(); + config.model_family = + find_family_for_model("gpt-5-codex").expect("gpt-5-codex is a model family"); + config.include_apply_patch_tool = true; + }); + let test = builder.build(&server).await?; + + let call_id = "local-shell-call"; + let responses = vec![ + sse(vec![ + json!({"type": "response.created", "response": {"id": "resp-1"}}), + ev_local_shell_call(call_id, "completed", vec!["/bin/echo", "local shell"]), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_assistant_message("msg-1", "local shell done"), + ev_completed("resp-2"), + ]), + ]; + mount_sse_sequence(&server, responses).await; + + submit_turn( + &test, + "run the local shell command", + SandboxPolicy::DangerFullAccess, + ) + .await?; + + let requests = server + .received_requests() + .await + .expect("recorded requests present"); + let bodies = request_bodies(&requests)?; + let output_item = + find_function_call_output(&bodies, call_id).expect("local shell output present"); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("local shell output string"); + + assert!( + serde_json::from_str::(output).is_err(), + "expected structured local shell output to be plain text", + ); + assert!( + output.starts_with("Exit code: 0\n"), + "expected zero exit code prefix, got {output:?}", + ); + assert!( + output.contains("local shell"), + "expected command stdout to be present, got {output:?}", + ); + + Ok(()) +} diff --git a/codex-rs/core/tests/suite/tool_harness.rs b/codex-rs/core/tests/suite/tool_harness.rs index a89317b7ba..68bd76bd8e 100644 --- a/codex-rs/core/tests/suite/tool_harness.rs +++ b/codex-rs/core/tests/suite/tool_harness.rs @@ -1,5 +1,7 @@ #![cfg(not(target_os = "windows"))] +use std::fs; + use assert_matches::assert_matches; use codex_core::features::Feature; use codex_core::model_family::find_family_for_model; @@ -295,15 +297,19 @@ async fn apply_patch_tool_executes_and_emits_patch_events() -> anyhow::Result<() .. } = builder.build(&server).await?; + let file_name = "notes.txt"; + let file_path = cwd.path().join(file_name); let call_id = "apply-patch-call"; - let patch_content = r#"*** Begin Patch -*** Add File: notes.txt + let patch_content = format!( + r#"*** Begin Patch +*** Add File: {file_name} +Tool harness apply patch -*** End Patch"#; +*** End Patch"# + ); let first_response = sse(vec![ ev_response_created("resp-1"), - ev_apply_patch_function_call(call_id, patch_content), + ev_apply_patch_function_call(call_id, &patch_content), ev_completed("resp-1"), ]); responses::mount_sse_once_match(&server, any(), first_response).await; @@ -352,6 +358,7 @@ async fn apply_patch_tool_executes_and_emits_patch_events() -> anyhow::Result<() assert!(saw_patch_begin, "expected PatchApplyBegin event"); let patch_end_success = patch_end_success.expect("expected PatchApplyEnd event to capture success flag"); + assert!(patch_end_success); let req = second_mock.single_request(); let output_item = req.function_call_output(call_id); @@ -361,38 +368,21 @@ async fn apply_patch_tool_executes_and_emits_patch_events() -> anyhow::Result<() ); let output_text = extract_output_text(&output_item).expect("output text present"); - if let Ok(exec_output) = serde_json::from_str::(output_text) { - let exit_code = exec_output["metadata"]["exit_code"] - .as_i64() - .expect("exit_code present"); - let summary = exec_output["output"].as_str().expect("output field"); - assert_eq!( - exit_code, 0, - "expected apply_patch exit_code=0, got {exit_code}, summary: {summary:?}" - ); - assert!( - patch_end_success, - "expected PatchApplyEnd success flag, summary: {summary:?}" - ); - assert!( - summary.contains("Success."), - "expected apply_patch summary to note success, got {summary:?}" - ); + let expected_pattern = format!( + r"(?s)^Exit code: 0 +Wall time: [0-9]+(?:\.[0-9]+)? seconds +Output: +Success. Updated the following files: +A {file_name} +?$" + ); + assert_regex_match(&expected_pattern, output_text); - let patched_path = cwd.path().join("notes.txt"); - let contents = std::fs::read_to_string(&patched_path) - .unwrap_or_else(|e| panic!("failed reading {}: {e}", patched_path.display())); - assert_eq!(contents, "Tool harness apply patch\n"); - } else { - assert!( - output_text.contains("codex-run-as-apply-patch"), - "expected apply_patch failure message to mention codex-run-as-apply-patch, got {output_text:?}" - ); - assert!( - !patch_end_success, - "expected PatchApplyEnd to report success=false when apply_patch invocation fails" - ); - } + let updated_contents = fs::read_to_string(file_path)?; + assert_eq!( + updated_contents, "Tool harness apply patch\n", + "expected updated file content" + ); Ok(()) }