From 21fdf0f834ae45da60d479b2583f02ed278d7de9 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Wed, 25 Nov 2026 00:13:02 +0000 Subject: [PATCH] Centralize TUI image capability checks (#63801) ## What changed Reuse shared terminal session detection and tmux passthrough escaping for image commands. Drive image rendering with explicit checks for fullscreen virtual placement, pixel data retention after placement removal, and whether a protocol's images survive history insertion. ## Testing Extend the automatic pet image protocol test to check that either `TMUX` or `TMUX_PANE` alone requires virtual placement. GitOrigin-RevId: 5d85e09bd9d1dcdfd01588adc8c2f0f4c6019ea1 --- .../src/chatwidget/tests/slash_commands.rs | 4 +- codex-rs/tui/src/custom_terminal.rs | 25 ++++---- codex-rs/tui/src/pets/image_protocol.rs | 43 +++++++------- codex-rs/tui/src/pets/mod.rs | 2 +- codex-rs/tui/src/sidebar_image.rs | 2 +- .../tui/src/terminal_capabilities/images.rs | 58 +++++++++++++------ .../src/terminal_capabilities/images_tests.rs | 11 ++-- codex-rs/tui/src/transcript_image.rs | 2 +- codex-rs/tui/src/tui.rs | 21 ++++--- codex-rs/tui/src/tui/owned_screen_tests.rs | 7 ++- 10 files changed, 96 insertions(+), 79 deletions(-) diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs index 4211c44d20..b52b79603c 100644 --- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs +++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs @@ -12,7 +12,7 @@ fn force_pet_image_support(chat: &mut ChatWidget) { fn force_tmux_pet_image_unsupported(chat: &mut ChatWidget) { chat.set_pet_image_support_for_tests(crate::pets::PetImageSupport::Unsupported( - crate::pets::PetImageUnsupportedReason::Tmux, + crate::pets::PetImageUnsupportedReason::RequiresVirtualPlacement, )); } @@ -24,7 +24,7 @@ fn force_terminal_pet_image_unsupported(chat: &mut ChatWidget) { fn force_old_iterm2_pet_image_unsupported(chat: &mut ChatWidget) { chat.set_pet_image_support_for_tests(crate::pets::PetImageSupport::Unsupported( - crate::pets::PetImageUnsupportedReason::Iterm2TooOld, + crate::pets::PetImageUnsupportedReason::UpgradeRequired, )); } diff --git a/codex-rs/tui/src/custom_terminal.rs b/codex-rs/tui/src/custom_terminal.rs index fd3041a4ac..f75485b37c 100644 --- a/codex-rs/tui/src/custom_terminal.rs +++ b/codex-rs/tui/src/custom_terminal.rs @@ -146,7 +146,7 @@ where { /// The backend used to interface with the terminal backend: B, - pub(crate) tmux_kitty_image_base: Option, + pub(crate) virtual_image_base: Option, /// Holds the results of the current and previous draw calls. The two are compared at the end /// of each draw pass to output the necessary updates to the terminal buffers: [Buffer; 2], @@ -239,7 +239,7 @@ where ) -> Self { Self { backend, - tmux_kitty_image_base: None, + virtual_image_base: None, buffers: [Buffer::empty(Rect::ZERO), Buffer::empty(Rect::ZERO)], current: 0, hidden_cursor: false, @@ -416,16 +416,16 @@ where let cursor_position = frame.cursor_position; let cursor_style = frame.cursor_style; let mut images = std::mem::take(&mut frame.image_placements); - let first_id = if let Some(base) = self.tmux_kitty_image_base { + let first_id = if let Some(base) = self.virtual_image_base { images.truncate(254); // The last two pane IDs belong to the pet and picker. base } else { crate::transcript_image::FIRST_IMAGE_ID }; - let tmux = self.tmux_kitty_image_base.is_some(); - // tmux retains placeholder cells, so keep their existing positional IDs and redraw + let virtual_placements = self.virtual_image_base.is_some(); + // Virtual placements retain placeholder cells, so keep their existing positional IDs and redraw // behavior. Native Kitty can keep the same ID and pixels as other images change. - if !tmux || *retained_images == images { + if !virtual_placements || *retained_images == images { for image in &mut images { if let Some(index) = retained_images.iter().position(|old| old == image) { *image = retained_images.swap_remove(index); @@ -435,12 +435,7 @@ where self.invalidate_viewport(); } let mut moved = Vec::new(); - // iTerm2 can discard the pixel data when a placement is removed. Redraw it - // from the source in that terminal, and keep the fast path for native Kitty. - if !tmux - && codex_terminal_detection::terminal_info().name - != codex_terminal_detection::TerminalName::Iterm2 - { + if !virtual_placements && crate::terminal_capabilities::images::retains_image_data() { for (index, image) in images.iter_mut().enumerate() { if image.terminal_id.is_none() && image.image.protocol != crate::pets::ImageProtocol::Sixel @@ -520,7 +515,7 @@ where let id = placement .terminal_id .ok_or_else(|| io::Error::other("missing terminal ID for placement"))?; - let kitty_placement = if tmux { + let kitty_placement = if virtual_placements { crate::pets::KittyPlacement::Virtual(id) } else { crate::pets::KittyPlacement::Cursor(id) @@ -627,7 +622,7 @@ where // The pet draws after the text frame. Mark its placeholder cells so the next diff // restores the underlying text when the sprite moves or disappears. pub(crate) fn mark_pet_placeholders(&mut self, request: Option<&crate::pets::AmbientPetDraw>) { - if self.tmux_kitty_image_base.is_some() + if self.virtual_image_base.is_some() && let Some(sprite) = request { for pos in sprite.area().intersection(self.viewport_area).positions() { @@ -1050,7 +1045,7 @@ mod tests { ); let mut terminal = Terminal::with_options(CaptureBackend::new(/*width*/ 40, /*height*/ 12)).unwrap(); - terminal.tmux_kitty_image_base = tmux_base; + terminal.virtual_image_base = tmux_base; let size = terminal.last_known_screen_size; terminal.set_viewport_area(Rect::new( /*x*/ 0, diff --git a/codex-rs/tui/src/pets/image_protocol.rs b/codex-rs/tui/src/pets/image_protocol.rs index ff88b4300a..a2974cc50b 100644 --- a/codex-rs/tui/src/pets/image_protocol.rs +++ b/codex-rs/tui/src/pets/image_protocol.rs @@ -1,4 +1,3 @@ -use std::env; use std::fs; use std::io::Write; use std::path::Path; @@ -16,6 +15,7 @@ use image::imageops::FilterType; use ratatui::layout::Rect; use super::sixel; +use crate::terminal_capabilities::images::wrap_graphics_command; const ESC: &str = "\x1b"; const ST: &str = "\x1b\\"; @@ -58,7 +58,7 @@ impl FromStr for ProtocolSelection { } pub fn kitty_delete_image(image_id: u32) -> String { - wrap_for_tmux_if_needed(&format!("{ESC}_Ga=d,d=I,i={image_id},q=2;{ST}")) + wrap_graphics_command(&format!("{ESC}_Ga=d,d=I,i={image_id},q=2;{ST}")) } #[derive(Clone, Copy)] @@ -96,7 +96,7 @@ impl KittyPlacement { pub(crate) fn kitty_move_image(id: u32, area: ratatui::layout::Rect) -> String { let (columns, rows) = (area.width, area.height); // Lowercase i removes placements but keeps the uploaded pixel data. - wrap_for_tmux_if_needed(&format!( + wrap_graphics_command(&format!( "{ESC}_Ga=d,d=i,i={id},q=2;{ST}{ESC}_Ga=p,i={id},c={columns},r={rows},C=1,q=2;{ST}" )) } @@ -129,7 +129,7 @@ pub fn kitty_transmit_png_with_id( } } - Ok(wrap_for_tmux_if_needed(&command)) + Ok(wrap_graphics_command(&command)) } pub fn kitty_transmit_png_file_with_id( @@ -146,7 +146,7 @@ pub fn kitty_transmit_png_file_with_id( let command = format!("{ESC}_Ga=T,t=f,f=100,c={columns},r={rows},q=2{image_id},C=1;{payload}{ST}"); - Ok(wrap_for_tmux_if_needed(&command)) + Ok(wrap_graphics_command(&command)) } fn kitty_image_id_arg(placement: KittyPlacement) -> String { @@ -156,15 +156,6 @@ fn kitty_image_id_arg(placement: KittyPlacement) -> String { } } -fn wrap_for_tmux_if_needed(command: &str) -> String { - if env::var_os("TMUX").is_none() { - return command.to_string(); - } - - let escaped = command.replace(ESC, "\x1b\x1b"); - format!("{ESC}Ptmux;{escaped}{ST}") -} - pub fn sixel_frame(frame_path: &Path, cache_dir: &Path, height_px: u16) -> Result { fs::create_dir_all(cache_dir).with_context(|| format!("create {}", cache_dir.display()))?; @@ -226,7 +217,7 @@ mod tests { fn tmux_passthrough_wraps_and_escapes_control_sequence() { let _guard = EnvVarGuard::new("TMUX", Some("session")); assert_eq!( - wrap_for_tmux_if_needed("\x1b_Gx;\x1b\\"), + wrap_graphics_command("\x1b_Gx;\x1b\\"), "\x1bPtmux;\x1b\x1b_Gx;\x1b\x1b\\\x1b\\" ); } @@ -248,13 +239,25 @@ mod tests { } #[test] - #[serial] - fn auto_protocol_is_disabled_inside_tmux() { - let _guard = EnvVarGuard::new("TMUX", Some("session")); - + fn auto_protocol_requires_virtual_placements_inside_tmux() { + const CHILD: &str = "CODEX_TUI_IMAGE_PLACEMENT_CHILD"; + if std::env::var_os(CHILD).is_none() { + for (key, value) in [("TMUX", "session"), ("TMUX_PANE", "%0")] { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "pets::image_protocol::tests::auto_protocol_requires_virtual_placements_inside_tmux"]) + .env(CHILD, "1") + .env_remove("TMUX") + .env_remove("TMUX_PANE") + .env(key, value) + .status() + .unwrap(); + assert!(status.success(), "{key} placement check failed"); + } + return; + } assert_eq!( ProtocolSelection::Auto.resolve(), - PetImageSupport::Unsupported(PetImageUnsupportedReason::Tmux) + PetImageSupport::Unsupported(PetImageUnsupportedReason::RequiresVirtualPlacement) ); } diff --git a/codex-rs/tui/src/pets/mod.rs b/codex-rs/tui/src/pets/mod.rs index 99e3a7e24f..9087cc7b13 100644 --- a/codex-rs/tui/src/pets/mod.rs +++ b/codex-rs/tui/src/pets/mod.rs @@ -178,7 +178,7 @@ fn render_pet_image( return Ok(()); }; - let pane_base = crate::tui::tmux_fullscreen_image_base(); + let pane_base = crate::tui::fullscreen_virtual_image_base(); let image_id = pane_base.map_or(image_id, |base| base + pane_slot); let placement = if pane_base.is_some() { KittyPlacement::Virtual(image_id) diff --git a/codex-rs/tui/src/sidebar_image.rs b/codex-rs/tui/src/sidebar_image.rs index af0329cb8b..0c40400cc0 100644 --- a/codex-rs/tui/src/sidebar_image.rs +++ b/codex-rs/tui/src/sidebar_image.rs @@ -88,7 +88,7 @@ impl SidebarImage { let available_rows = area.height.saturating_sub(1 + u16::from(area.height > 2)); // tmux uses Kitty's virtual placements. The shared placeholder renderer // currently emits row marks for up to six rows. - let rows = if crate::tui::tmux_fullscreen_image_base().is_some() { + let rows = if crate::tui::fullscreen_virtual_image_base().is_some() { available_rows.min(6) } else { available_rows diff --git a/codex-rs/tui/src/terminal_capabilities/images.rs b/codex-rs/tui/src/terminal_capabilities/images.rs index 71ecdff210..5fe1f40eeb 100644 --- a/codex-rs/tui/src/terminal_capabilities/images.rs +++ b/codex-rs/tui/src/terminal_capabilities/images.rs @@ -1,10 +1,23 @@ //! Detects image protocols and placement support, including fullscreen-only virtual placements. +use crate::tui::fullscreen_virtual_image_base; use codex_terminal_detection::Multiplexer; use codex_terminal_detection::TerminalInfo; use codex_terminal_detection::TerminalName; use codex_terminal_detection::terminal_info; use std::env; +/// Some implementations discard pixel data when the placement is removed. +pub(crate) fn retains_image_data() -> bool { + terminal_info().name != TerminalName::Iterm2 +} + +impl ImageProtocol { + /// File-backed placements and Sixel pixels can scroll with inserted history. + pub(crate) fn survives_history_insertion(self) -> bool { + self == Self::Kitty + } +} + const ITERM2_KITTY_MIN_VERSION: (u64, u64, u64) = (3, 6, 0); #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -24,8 +37,8 @@ impl PetImageSupport { pub(crate) fn protocol(self) -> Option { match self { Self::Supported(protocol) => Some(protocol), - Self::Unsupported(PetImageUnsupportedReason::Tmux) => { - crate::tui::tmux_fullscreen_image_base().map(|_| ImageProtocol::Kitty) + Self::Unsupported(PetImageUnsupportedReason::RequiresVirtualPlacement) => { + fullscreen_virtual_image_base().map(|_| ImageProtocol::Kitty) } Self::Unsupported(_) => None, } @@ -41,22 +54,22 @@ impl PetImageSupport { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum PetImageUnsupportedReason { - Tmux, - Zellij, - Iterm2TooOld, + RequiresVirtualPlacement, + UnsafePanePlacement, + UpgradeRequired, Terminal, } impl PetImageUnsupportedReason { fn message(self) -> &'static str { match self { - Self::Tmux => { + Self::RequiresVirtualPlacement => { "Pets are unavailable in this tmux pane. Use fullscreen Codex with allow-passthrough all, or run Codex outside tmux." } - Self::Zellij => { + Self::UnsafePanePlacement => { "Pets are disabled in Zellij. Terminal images don’t stay reliably pane-local in Zellij. Run Codex outside Zellij to use pets." } - Self::Iterm2TooOld => { + Self::UpgradeRequired => { "Pets require iTerm2 3.6 or newer. Upgrade iTerm2 to use terminal pets." } Self::Terminal => { @@ -67,27 +80,32 @@ impl PetImageUnsupportedReason { } pub(crate) fn detect_pet_image_support() -> PetImageSupport { - if env::var_os("TMUX").is_some() || env::var_os("TMUX_PANE").is_some() { - return PetImageSupport::Unsupported(PetImageUnsupportedReason::Tmux); + if super::is_tmux_session() { + return PetImageSupport::Unsupported(PetImageUnsupportedReason::RequiresVirtualPlacement); } - if env::var_os("ZELLIJ").is_some() - || env::var_os("ZELLIJ_SESSION_NAME").is_some() - || env::var_os("ZELLIJ_VERSION").is_some() - { - return PetImageSupport::Unsupported(PetImageUnsupportedReason::Zellij); + if super::zellij_session() { + return PetImageSupport::Unsupported(PetImageUnsupportedReason::UnsafePanePlacement); } image_support_for_terminal_environment(&terminal_info()) } +pub(crate) fn wrap_graphics_command(command: &str) -> String { + if !super::tmux_transport() { + return command.to_string(); + } + + super::escaped_dcs(command) +} + fn image_support_for_terminal_environment(info: &TerminalInfo) -> PetImageSupport { if info.name == TerminalName::Orca { return if supports_orca_kitty_graphics( info, env::var("ORCA_IMAGE_PROTOCOL").ok().as_deref(), env::var("TERM").ok().as_deref(), - /*sty_present*/ env::var_os("STY").is_some(), + /*sty_present*/ super::screen_active(), ) { PetImageSupport::Supported(ImageProtocol::Kitty) } else { @@ -123,10 +141,12 @@ fn supports_orca_kitty_graphics( fn pet_image_support_for_terminal(info: &TerminalInfo) -> PetImageSupport { match info.multiplexer { Some(Multiplexer::Tmux { .. }) => { - return PetImageSupport::Unsupported(PetImageUnsupportedReason::Tmux); + return PetImageSupport::Unsupported( + PetImageUnsupportedReason::RequiresVirtualPlacement, + ); } Some(Multiplexer::Zellij { .. }) => { - return PetImageSupport::Unsupported(PetImageUnsupportedReason::Zellij); + return PetImageSupport::Unsupported(PetImageUnsupportedReason::UnsafePanePlacement); } None => {} } @@ -136,7 +156,7 @@ fn pet_image_support_for_terminal(info: &TerminalInfo) -> PetImageSupport { } if is_iterm2_terminal(info) { - return PetImageSupport::Unsupported(PetImageUnsupportedReason::Iterm2TooOld); + return PetImageSupport::Unsupported(PetImageUnsupportedReason::UpgradeRequired); } if supports_kitty_graphics(info) { diff --git a/codex-rs/tui/src/terminal_capabilities/images_tests.rs b/codex-rs/tui/src/terminal_capabilities/images_tests.rs index 70a6144d77..b9a11e0cf6 100644 --- a/codex-rs/tui/src/terminal_capabilities/images_tests.rs +++ b/codex-rs/tui/src/terminal_capabilities/images_tests.rs @@ -1,7 +1,6 @@ #![cfg(test)] use super::*; use serial_test::serial; - pub(crate) struct EnvVarGuard { name: &'static str, previous: Option, @@ -36,7 +35,7 @@ fn pet_image_support_prefers_multiplexer_safety() { Some("Ghostty"), /*term*/ None, )), - PetImageSupport::Unsupported(PetImageUnsupportedReason::Tmux) + PetImageSupport::Unsupported(PetImageUnsupportedReason::RequiresVirtualPlacement) ); assert_eq!( pet_image_support_for_terminal(&terminal_info_for_test( @@ -45,7 +44,7 @@ fn pet_image_support_prefers_multiplexer_safety() { Some("kitty"), /*term*/ None, )), - PetImageSupport::Unsupported(PetImageUnsupportedReason::Zellij) + PetImageSupport::Unsupported(PetImageUnsupportedReason::UnsafePanePlacement) ); } @@ -101,15 +100,15 @@ fn pet_image_support_rejects_old_iterm2_versions() { ] { assert_eq!( pet_image_support_for_terminal(&info), - PetImageSupport::Unsupported(PetImageUnsupportedReason::Iterm2TooOld) + PetImageSupport::Unsupported(PetImageUnsupportedReason::UpgradeRequired) ); } } #[test] fn pet_image_support_old_iterm2_message_mentions_upgrade() { - let message = - PetImageSupport::Unsupported(PetImageUnsupportedReason::Iterm2TooOld).unsupported_message(); + let message = PetImageSupport::Unsupported(PetImageUnsupportedReason::UpgradeRequired) + .unsupported_message(); assert_eq!( message, diff --git a/codex-rs/tui/src/transcript_image.rs b/codex-rs/tui/src/transcript_image.rs index 9c42a25058..11733ad825 100644 --- a/codex-rs/tui/src/transcript_image.rs +++ b/codex-rs/tui/src/transcript_image.rs @@ -143,7 +143,7 @@ impl TranscriptImage { } else { 400 }; - let max_height = if crate::tui::tmux_fullscreen_image_base().is_some() { + let max_height = if crate::tui::fullscreen_virtual_image_base().is_some() { 6 * cell_height } else { 400 diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 04489001a4..5e38196615 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -594,7 +594,7 @@ pub(crate) fn init() -> Result { crate::terminal_palette::set_default_colors_from_startup_probe(/*colors*/ None); let mut tui = CustomTerminal::with_options_and_cursor_position(backend, cursor_pos)?; - tui.tmux_kitty_image_base = session.virtual_image_base(); + tui.virtual_image_base = session.virtual_image_base(); let stderr_guard = terminal_stderr::TerminalStderrGuard::install()?; let initialized_terminal = InitializedTerminal { terminal: tui, @@ -701,10 +701,10 @@ impl MouseCapture { } // Zero denotes scrollback mode or a pane without Kitty passthrough. -static TMUX_FULLSCREEN_IMAGE_BASE: AtomicU32 = AtomicU32::new(0); +static FULLSCREEN_VIRTUAL_IMAGE_BASE: AtomicU32 = AtomicU32::new(0); -pub(crate) fn tmux_fullscreen_image_base() -> Option { - std::num::NonZeroU32::new(TMUX_FULLSCREEN_IMAGE_BASE.load(Ordering::Relaxed)) +pub(crate) fn fullscreen_virtual_image_base() -> Option { + std::num::NonZeroU32::new(FULLSCREEN_VIRTUAL_IMAGE_BASE.load(Ordering::Relaxed)) .map(std::num::NonZeroU32::get) } @@ -840,9 +840,9 @@ impl Tui { fn record_owned_screen(&mut self, owned: bool) { self.owned_screen = owned; - TMUX_FULLSCREEN_IMAGE_BASE.store( + FULLSCREEN_VIRTUAL_IMAGE_BASE.store( if owned { - self.terminal.tmux_kitty_image_base.unwrap_or_default() + self.terminal.virtual_image_base.unwrap_or_default() } else { 0 }, @@ -1453,17 +1453,16 @@ impl Tui { let viewport = terminal.viewport_area; // Standard insertion scrolls only above a bottom-aligned viewport when there // are at least two history rows (the minimum for a DEC scroll region). - let preserves_direct_kitty = mode == InsertHistoryMode::Standard + let preserves_viewport = mode == InsertHistoryMode::Standard && viewport.top() > 1 && viewport.bottom() == screen_size.height && screen_size == terminal.last_known_screen_size - && terminal.tmux_kitty_image_base.is_none(); + && terminal.virtual_image_base.is_none(); if retained_images.iter().any(|placement| { - !preserves_direct_kitty - || placement.image.protocol != crate::pets::ImageProtocol::Kitty + !preserves_viewport + || !placement.image.protocol.survives_history_insertion() || placement.area.intersection(viewport) != placement.area }) { - // iTerm2's file-backed images and Sixel pixels can scroll with history. terminal.clear_frame_images(retained_images)?; } diff --git a/codex-rs/tui/src/tui/owned_screen_tests.rs b/codex-rs/tui/src/tui/owned_screen_tests.rs index 381c8b9156..f1bb976429 100644 --- a/codex-rs/tui/src/tui/owned_screen_tests.rs +++ b/codex-rs/tui/src/tui/owned_screen_tests.rs @@ -205,9 +205,10 @@ async fn owned_screen_lifecycle_child() { assert_eq!(tui.terminal.viewport_area, Rect { y: 0, ..inline }); // A fresh fullscreen launch defers terminal entry until its first frame. - tui.terminal.tmux_kitty_image_base = Some(0x80_0100); - let support = - crate::pets::PetImageSupport::Unsupported(crate::pets::PetImageUnsupportedReason::Tmux); + tui.terminal.virtual_image_base = Some(0x80_0100); + let support = crate::pets::PetImageSupport::Unsupported( + crate::pets::PetImageUnsupportedReason::RequiresVirtualPlacement, + ); tui.prepare_owned_screen(/*owned*/ true) .expect("prepare fullscreen"); assert_eq!(support.protocol(), Some(crate::pets::ImageProtocol::Kitty));