From eb79af452e3e831d7ffbbcb9acb98e139a338e61 Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Tue, 1 Dec 2026 19:12:40 +0000 Subject: [PATCH] Load TUI image previews in the background and downscale large JPEGs (#65079) ## Why Composer thumbnails and transcript tool previews read and decoded files during rendering. A JPEG whose decoded pixels exceeded the 32 MiB allocation budget could lose its preview even when the encoded file fit within the file size limit. ## What changed - Load visible composer thumbnails and transcript previews on background workers and request a redraw when the result is ready. Reuse prepared tool previews when the viewport changes size. - Share the sidebar's scaled JPEG fallback with composer and transcript previews. Preserve the oriented source aspect ratio and enforce the encoded file size limit separately from the decode budget. - Check that the owning thread has a local workspace before reading an inspected image. Generated artifacts can still load from the daemon host. ## Testing Cover large JPEG previews in the composer and transcript, thumbnail refresh after an attachment is replaced, text fallback for oversized PNGs, and an inspected path shared by local and remote workspaces. GitOrigin-RevId: f2c8948a9abaa2527932423224b6ebeda3e122ae --- codex-rs/tui/src/app.rs | 3 +- .../tui/src/app/owned_transcript_tests.rs | 59 +++++++-- codex-rs/tui/src/app/tests.rs | 8 ++ .../chat_composer/status_surface_tests.rs | 1 + codex-rs/tui/src/chatwidget/rendering.rs | 7 +- codex-rs/tui/src/custom_terminal.rs | 18 +-- codex-rs/tui/src/image_decode.rs | 56 +++++++++ .../{sidebar_image => image_decode}/jpeg.rs | 12 +- .../jpeg/entropy.rs | 0 codex-rs/tui/src/sidebar_image.rs | 33 ++--- codex-rs/tui/src/sidebar_image_tests.rs | 2 +- codex-rs/tui/src/transcript_image.rs | 114 ++++++++++-------- .../tui/src/transcript_image/background.rs | 73 +++++++++++ codex-rs/tui/src/transcript_image/composer.rs | 100 +++++++++------ codex-rs/tui/src/transcript_image/local.rs | 57 +++++++++ codex-rs/tui/src/transcript_image_tests.rs | 5 +- codex-rs/tui/src/transcript_view.rs | 2 +- .../{markdown_images.rs => image_requests.rs} | 95 ++++++++------- codex-rs/tui/src/transcript_view/layout.rs | 64 ++++++---- .../tui/src/transcript_view/layout_tests.rs | 57 ++++++++- codex-rs/tui/src/transcript_view/text.rs | 3 + .../tui/src/transcript_view/text_images.rs | 14 ++- 22 files changed, 560 insertions(+), 223 deletions(-) rename codex-rs/tui/src/{sidebar_image => image_decode}/jpeg.rs (98%) rename codex-rs/tui/src/{sidebar_image => image_decode}/jpeg/entropy.rs (100%) create mode 100644 codex-rs/tui/src/transcript_image/background.rs create mode 100644 codex-rs/tui/src/transcript_image/local.rs rename codex-rs/tui/src/transcript_view/{markdown_images.rs => image_requests.rs} (51%) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 7f3925170c..64d4c9a11b 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1586,7 +1586,8 @@ impl App { !self.app_server_target.uses_remote_workspace() && crate::projectless::has_only_local_environments(&self.environment_manager) }); - self.chat_widget.prepare_composer_images(protocol); + self.chat_widget + .prepare_composer_images(protocol, &tui.frame_requester()); protocol } diff --git a/codex-rs/tui/src/app/owned_transcript_tests.rs b/codex-rs/tui/src/app/owned_transcript_tests.rs index 68394ba95d..e24c60e9c4 100644 --- a/codex-rs/tui/src/app/owned_transcript_tests.rs +++ b/codex-rs/tui/src/app/owned_transcript_tests.rs @@ -651,15 +651,15 @@ async fn owned_details_keep_the_composer_cursor_and_screen() -> Result<()> { let path = dir.path().join("preview.png"); image::RgbaImage::from_pixel(8, 16, image::Rgba([80, 30, 20, 255])).save(&path)?; let protocol = crate::pets::ImageProtocol::KittyLocalFile; - let image = Arc::new( - crate::transcript_image::TranscriptImage::load( - &path, - area.width, - protocol, - crate::transcript_image::PreviewKind::Inspected, - ) - .unwrap(), - ); + let image = crate::transcript_image::PreparedImage::load_for_cells( + &crate::transcript_image::local::ImageFile::at(&path).unwrap(), + area.width.saturating_sub(2), + protocol, + crate::transcript_image::PreviewKind::Inspected, + /*cell_size*/ None, + ) + .unwrap() + .image; let neighbor = Rect::new(/*x*/ 4, /*y*/ 9, image.columns, image.rows); let presented = |tui: &tui::Tui| { tui.retained_images @@ -779,8 +779,17 @@ async fn owned_details_keep_the_composer_cursor_and_screen() -> Result<()> { Some("Preview".to_string()), Some(AbsolutePathBuf::try_from(path)?), ))); - app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw) - .await?; + app.app_server_backend_id = Some(server.backend_id()); + app.backend_registry.connect(&server); + let mut requests = crate::tui::test_support::record_frame_requests(&mut tui); + loop { + app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw) + .await?; + if tui.retained_images.len() > 1 { + break; + } + requests.recv().await.unwrap(); + } let images = presented(&tui); assert_eq!(images.len(), 2); assert_eq!(images[0], neighbor); @@ -2294,6 +2303,9 @@ async fn composer_thumbnails_follow_draft_deletion_and_resize() -> Result<()> { let portrait = dir.path().join("portrait.png"); let red = image::Rgba([255, 0, 0, 255]); image::RgbaImage::from_pixel(/*width*/ 400, /*height*/ 1, red).save(&banner)?; + // The replacement JPEG needs 36 MiB of RGB pixels at full resolution. + let replacement = dir.path().join("photo.jpg"); + image::RgbImage::from_pixel(4096, 3072, image::Rgb([64; 3])).save(&replacement)?; for owned in [false, true] { image::RgbaImage::new(/*width*/ 4, /*height*/ 400).save(&portrait)?; @@ -2312,7 +2324,12 @@ async fn composer_thumbnails_follow_draft_deletion_and_resize() -> Result<()> { .attach_image(banner.clone(), ClipboardPasteContext::Composer); let narrow = Size::new(/*width*/ 20, /*height*/ 24); + let mut frames = crate::tui::test_support::record_frame_requests(&mut tui); app.render_chat_widget_frame(&mut tui, narrow)?; + while tui.retained_images.len() < 2 { + frames.recv().await.unwrap(); + app.render_chat_widget_frame(&mut tui, narrow)?; + } let placements = &tui.retained_images; assert_eq!(placements.len(), 2); let pixels = &placements[0].image.pixels; @@ -2361,10 +2378,26 @@ async fn composer_thumbnails_follow_draft_deletion_and_resize() -> Result<()> { assert_eq!(tui.retained_images.len(), 2); assert_eq!(tui.retained_images[0].image.pixels, portrait_image.pixels); // A draft submits the current file, even if it was replaced since attachment. - image::RgbaImage::from_pixel(/*width*/ 2, /*height*/ 2, red).save(&portrait)?; + std::fs::copy(&replacement, &portrait)?; app.render_chat_widget_frame(&mut tui, wide)?; + assert_eq!(tui.retained_images.len(), 1); + while tui.retained_images.len() < 2 { + frames.recv().await.unwrap(); + app.render_chat_widget_frame(&mut tui, wide)?; + } let updated = &tui.retained_images[0].image.pixels; - assert!(updated.pixels().any(|pixel| *pixel == red)); + assert_eq!( + *updated.get_pixel(updated.width() / 2, updated.height() / 2), + image::Rgba([64, 64, 64, 255]) + ); + // A cached tile still observes the independent encoded-file limit. + std::fs::File::options() + .write(true) + .open(&portrait)? + .set_len(32 * 1024 * 1024 + 1)?; + assert!(crate::transcript_image::local::ImageFile::at(&portrait).is_none()); + app.render_chat_widget_frame(&mut tui, wide)?; + assert_eq!(tui.retained_images.len(), 1); // Both insufficient height and an unsupported terminal leave the references editable. for (height, support) in [ (5, PetImageSupport::Supported(ImageProtocol::Kitty)), diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 84c5b7f32f..d67f0078dd 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -4850,6 +4850,14 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<() Some(image_path), ))); app.transcript_view.jump_to_latest(); + app.app_server_backend_id = Some(app_server.backend_id()); + app.backend_registry.connect(&app_server); + let mut requests = crate::tui::test_support::record_frame_requests(&mut tui); + side_frame(&mut app, &mut tui, wide)?; + while tui.retained_images.is_empty() { + requests.recv().await.unwrap(); + side_frame(&mut app, &mut tui, wide)?; + } } side_frame(&mut app, &mut tui, wide)?; let divider = divider_at(&tui, 0); diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/status_surface_tests.rs b/codex-rs/tui/src/bottom_pane/chat_composer/status_surface_tests.rs index 0466015f8d..c57edf30f5 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/status_surface_tests.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/status_surface_tests.rs @@ -353,6 +353,7 @@ fn thumbnails_fit_after_basic_footer_rows_and_before_extra_status() { let previews = crate::transcript_image::composer::ComposerImages::for_terminal( crate::pets::ImageProtocol::Kitty, /*previous*/ None, + &crate::tui::FrameRequester::test_dummy(), ) .unwrap(); let mut frames = Vec::new(); diff --git a/codex-rs/tui/src/chatwidget/rendering.rs b/codex-rs/tui/src/chatwidget/rendering.rs index b2fd4c2df1..33f0832627 100644 --- a/codex-rs/tui/src/chatwidget/rendering.rs +++ b/codex-rs/tui/src/chatwidget/rendering.rs @@ -219,7 +219,11 @@ impl BlockedThreadNotice<'_> { } impl ChatWidget { - pub(crate) fn prepare_composer_images(&mut self, protocol: Option) { + pub(crate) fn prepare_composer_images( + &mut self, + protocol: Option, + frames: &crate::tui::FrameRequester, + ) { self.composer_images = protocol .filter(|_| { !self.bottom_pane.composer_local_images().is_empty() @@ -229,6 +233,7 @@ impl ChatWidget { crate::transcript_image::composer::ComposerImages::for_terminal( protocol, self.composer_images.take(), + frames, ) }); } diff --git a/codex-rs/tui/src/custom_terminal.rs b/codex-rs/tui/src/custom_terminal.rs index d2d4d689fc..f59393d902 100644 --- a/codex-rs/tui/src/custom_terminal.rs +++ b/codex-rs/tui/src/custom_terminal.rs @@ -1040,15 +1040,15 @@ mod tests { (crate::pets::ImageProtocol::KittyLocalFile, None), (crate::pets::ImageProtocol::Kitty, Some(0x80_0100)), ] { - let image = std::sync::Arc::new( - crate::transcript_image::TranscriptImage::load( - &path, - /*width*/ 40, - protocol, - crate::transcript_image::PreviewKind::Inspected, - ) - .unwrap(), - ); + let image = crate::transcript_image::PreparedImage::load_for_cells( + &crate::transcript_image::local::ImageFile::at(&path).unwrap(), + /*columns*/ 38, + protocol, + crate::transcript_image::PreviewKind::Inspected, + /*cell_size*/ None, + ) + .unwrap() + .image; let mut terminal = Terminal::with_options(CaptureBackend::new(/*width*/ 40, /*height*/ 12)).unwrap(); terminal.virtual_image_base = tmux_base; diff --git a/codex-rs/tui/src/image_decode.rs b/codex-rs/tui/src/image_decode.rs index 48fd044359..d25630ecff 100644 --- a/codex-rs/tui/src/image_decode.rs +++ b/codex-rs/tui/src/image_decode.rs @@ -1,13 +1,69 @@ //! Decode image pixels in their display orientation within the caller's allocation limits. +mod jpeg; + +#[cfg(test)] +pub(crate) use jpeg::decode_scaled as scaled_jpeg; + use image::DynamicImage; use image::ImageDecoder; +use image::ImageError; +use image::ImageFormat; use image::ImageReader; use image::ImageResult; use image::Limits; +use image::error::LimitErrorKind; use std::io::BufRead; +use std::io::Cursor; use std::io::Seek; +// The thumbnail can be smaller than the oriented source used for labels and layout. +pub(crate) struct Preview { + pub(crate) image: DynamicImage, + pub(crate) size: (u32, u32), +} + +pub(crate) const MAX_PREVIEW_EDGE: u32 = 768; + +impl Preview { + /// Fit against the original aspect ratio, including when the decoder rounded + /// each axis up to a whole JPEG block. + pub(crate) fn thumbnail(&self, max_width: u32, max_height: u32) -> DynamicImage { + let (width, height) = self.size; + if self.size == (self.image.width(), self.image.height()) { + return self + .image + .thumbnail(max_width.min(width), max_height.min(height)); + } + // Bound interpolation even if the terminal reports very large cells. + let scale = (f64::from(max_width.min(MAX_PREVIEW_EDGE)) / f64::from(width)) + .min(f64::from(max_height.min(MAX_PREVIEW_EDGE)) / f64::from(height)) + .min(1.0); + let fit = |axis: u32| (f64::from(axis) * scale).round().max(1.0) as u32; + self.image.thumbnail_exact(fit(width), fit(height)) + } +} + +/// Retry oversized JPEGs at one sample per block using the same encoded bytes. +pub(crate) fn decode_preview(bytes: &[u8], format: ImageFormat) -> ImageResult { + let mut limits = Limits::default(); + limits.max_alloc = Some(32 * 1024 * 1024); + let reader = ImageReader::with_format(Cursor::new(bytes), format); + match decode_oriented(reader, limits.clone()) { + Ok(image) => { + let size = (image.width(), image.height()); + Ok(Preview { image, size }) + } + Err(ImageError::Limits(error)) + if format == ImageFormat::Jpeg + && error.kind() == LimitErrorKind::InsufficientMemory => + { + jpeg::decode_scaled(bytes, limits).ok_or(ImageError::Limits(error)) + } + Err(error) => Err(error), + } +} + pub(crate) fn decode_oriented( mut reader: ImageReader, mut limits: Limits, diff --git a/codex-rs/tui/src/sidebar_image/jpeg.rs b/codex-rs/tui/src/image_decode/jpeg.rs similarity index 98% rename from codex-rs/tui/src/sidebar_image/jpeg.rs rename to codex-rs/tui/src/image_decode/jpeg.rs index e4da203714..5367941f72 100644 --- a/codex-rs/tui/src/sidebar_image/jpeg.rs +++ b/codex-rs/tui/src/image_decode/jpeg.rs @@ -1,7 +1,7 @@ -//! One-eighth-scale fallback for sidebar JPEGs above the pixel budget. +//! One-eighth-scale fallback for JPEGs above the pixel budget. //! Each DC coefficient gives the average of an 8×8 block (T.81 F.2). //! Keep only these coefficients, including progressive refinements, -//! and let the image crate resize their color samples to fit the sidebar. +//! and let the image crate resize their color samples to fit the preview. mod entropy; @@ -15,16 +15,14 @@ use image::Rgb; use image::metadata::Orientation; use super::MAX_PREVIEW_EDGE; +use super::Preview; fn word(bytes: &mut &[u8]) -> Option { Some(u16::from_be_bytes(bytes.split_off(..2)?.try_into().ok()?)) } /// Return None to retain the original allocation error when a preview is unavailable. -pub(super) fn decode_scaled( - mut bytes: &[u8], - mut limits: Limits, -) -> Option<(DynamicImage, (u32, u32))> { +pub(crate) fn decode_scaled(mut bytes: &[u8], mut limits: Limits) -> Option { bytes = bytes.strip_prefix(&[0xff, 0xd8])?; let mut decoder = Decoder::default(); let mut orientation = None; @@ -95,7 +93,7 @@ pub(super) fn decode_scaled( if orientation.to_exif() >= 5 { size = (size.1, size.0); } - Some((image, size)) + Some(Preview { image, size }) } #[derive(Default)] diff --git a/codex-rs/tui/src/sidebar_image/jpeg/entropy.rs b/codex-rs/tui/src/image_decode/jpeg/entropy.rs similarity index 100% rename from codex-rs/tui/src/sidebar_image/jpeg/entropy.rs rename to codex-rs/tui/src/image_decode/jpeg/entropy.rs diff --git a/codex-rs/tui/src/sidebar_image.rs b/codex-rs/tui/src/sidebar_image.rs index 4fa83fc615..47670e7387 100644 --- a/codex-rs/tui/src/sidebar_image.rs +++ b/codex-rs/tui/src/sidebar_image.rs @@ -1,33 +1,28 @@ //! Decode a workspace image once and reuse the transcript's terminal image lifecycle. -use std::io::Cursor; use std::sync::Arc; use color_eyre::eyre::OptionExt; use color_eyre::eyre::Result; use image::DynamicImage; -use image::ImageError; use image::ImageFormat; -use image::error::LimitErrorKind; use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::style::Stylize; use ratatui::text::Line; use ratatui::widgets::Widget; +use crate::image_decode; +use crate::image_decode::MAX_PREVIEW_EDGE; use crate::pets::ImageProtocol; use crate::transcript_image::ImagePlacement; use crate::transcript_image::TranscriptImage; use crate::transcript_image::terminal_cell_size; -mod jpeg; - #[cfg(test)] #[path = "sidebar_image_tests.rs"] mod tests; -const MAX_PREVIEW_EDGE: u32 = 768; - #[derive(Debug)] pub(crate) enum DocumentContent { Text(String), @@ -64,27 +59,13 @@ fn supported_format(format: ImageFormat) -> bool { impl SidebarImage { pub(crate) fn decode(bytes: &[u8]) -> Result { - let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format()?; - let format = reader - .format() + let format = image::guess_format(bytes) + .ok() .filter(|format| supported_format(*format)) .ok_or_eyre("Unsupported image format")?; - let mut limits = image::Limits::default(); - limits.max_alloc = Some(32 * 1024 * 1024); - let (image, (width, height)) = - match crate::image_decode::decode_oriented(reader, limits.clone()) { - Ok(image) => { - let size = (image.width(), image.height()); - (image, size) - } - Err(ImageError::Limits(error)) - if format == ImageFormat::Jpeg - && error.kind() == LimitErrorKind::InsufficientMemory => - { - jpeg::decode_scaled(bytes, limits).ok_or(ImageError::Limits(error))? - } - Err(error) => return Err(error.into()), - }; + let preview = image_decode::decode_preview(bytes, format)?; + let (width, height) = preview.size; + let image = preview.image; Ok(Self { label: format!( "{} · {width} × {height}", diff --git a/codex-rs/tui/src/sidebar_image_tests.rs b/codex-rs/tui/src/sidebar_image_tests.rs index 15c38964cc..8501e9c960 100644 --- a/codex-rs/tui/src/sidebar_image_tests.rs +++ b/codex-rs/tui/src/sidebar_image_tests.rs @@ -32,7 +32,7 @@ fn split_progressive_preview_requires_intact_scans_and_enough_memory() { let decode = |input: &[u8], budget| { let mut limits = image::Limits::default(); limits.max_alloc = Some(budget); - super::jpeg::decode_scaled(input, limits) + crate::image_decode::scaled_jpeg(input, limits).map(|preview| (preview.image, preview.size)) }; let required = 3 * 4 * 6 * 2 + 5 * 7 * 3; // padded 4:2:0 DC blocks + RGB pixels assert!(decode(&bytes, required - 1).is_none()); diff --git a/codex-rs/tui/src/transcript_image.rs b/codex-rs/tui/src/transcript_image.rs index 470f8319e0..e1555bca3a 100644 --- a/codex-rs/tui/src/transcript_image.rs +++ b/codex-rs/tui/src/transcript_image.rs @@ -4,10 +4,11 @@ //! their reserved rows belong to layout. The terminal retains visible placements and any local //! transport files until those placements change. +pub(crate) mod background; pub(crate) mod composer; +pub(crate) mod local; use std::io::Write; -use std::path::Path; use std::sync::Arc; use anyhow::Result; @@ -19,6 +20,7 @@ use image::ImageFormat; use image::RgbaImage; use ratatui::layout::Rect; +use crate::image_decode::Preview; use crate::pets::ImageProtocol; use crate::pets::KittyPlacement; @@ -80,6 +82,7 @@ pub(crate) fn terminal_cell_size() -> Option<(u32, u32)> { pub(crate) enum PreviewKind { Inspected, Generated, + Inline, } impl TranscriptImage { @@ -88,47 +91,33 @@ impl TranscriptImage { && (self.protocol != ImageProtocol::Sixel || cell_size == Some((self.cell_width, self.cell_height))) } +} - fn load_pixels(path: &Path, max_width: u32, max_height: u32) -> Option { - if max_width == 0 || max_height == 0 { - return None; - } - let image = Self::decode(path)?; - Some( - image - .thumbnail(max_width.min(image.width()), max_height.min(image.height())) - .to_rgba8(), - ) - } +/// Cache the largest useful terminal rendition of a tool result. On a narrow +/// resize, refit its content without the terminal padding or another file read. +pub(crate) struct PreparedImage { + pub(crate) image: Arc, + source_size: (u32, u32), + content_size: (u32, u32), +} - fn decode(path: &Path) -> Option { - let metadata = path.metadata().ok()?; - if !metadata.is_file() || metadata.len() > 32 * 1024 * 1024 { - return None; - } - let reader = image::ImageReader::open(path) - .ok()? - .with_guessed_format() - .ok()?; - // The reader checks the decoded size before allocating the raster. Keep normal - // screenshots usable, but never allocate hundreds of MB for an optional thumbnail. - let mut limits = image::Limits::default(); - limits.max_alloc = Some(32 * 1024 * 1024); - crate::image_decode::decode_oriented(reader, limits).ok() - } - - pub(crate) fn load( - path: &Path, - width: u16, +impl PreparedImage { + pub(crate) fn load_for_cells( + file: &local::ImageFile, + columns: u16, protocol: ImageProtocol, kind: PreviewKind, + cell_size: Option<(u32, u32)>, ) -> Option { - let columns = width.saturating_sub(2); - Self::load_for_cells(path, columns, protocol, kind, terminal_cell_size()) + if columns == 0 || (protocol == ImageProtocol::Sixel && cell_size.is_none()) { + return None; + } + let source = file.read()?; + Self::fit_for_cells(&source, columns, protocol, kind, cell_size) } - pub(crate) fn load_for_cells( - path: &Path, + fn fit_for_cells( + preview: &Preview, columns: u16, protocol: ImageProtocol, kind: PreviewKind, @@ -142,23 +131,22 @@ impl TranscriptImage { ImageProtocol::Sixel => cell_size?, ImageProtocol::Kitty | ImageProtocol::KittyLocalFile => match kind { PreviewKind::Inspected => (8, 16), - PreviewKind::Generated => cell_size.unwrap_or((8, 16)), + PreviewKind::Generated | PreviewKind::Inline => cell_size.unwrap_or((8, 16)), }, }; - let image = Self::decode(path)?; + let (width, height) = preview.size; let (columns, max_width, max_height) = match (protocol, kind) { - (ImageProtocol::Sixel, PreviewKind::Generated) => { + (ImageProtocol::Sixel, PreviewKind::Generated | PreviewKind::Inline) => { // Fit the original 160 x 80 pixel budget to the source aspect ratio. // The encoder scans each six-row band once per active color, so // also bound width times band count (including a partial last band). const PIXELS: u32 = 160 * 80; const BAND_COLUMNS: u32 = 160 * 80_u32.div_ceil(6); - let height_at_budget = (u64::from(PIXELS) * u64::from(image.height()) - / u64::from(image.width())) - .isqrt() as u32; + let height_at_budget = + (u64::from(PIXELS) * u64::from(height) / u64::from(width)).isqrt() as u32; let height = height_at_budget .clamp(1, 80) - .min(image.height()) + .min(height) .min(6 * cell_height); let width = (PIXELS / height).min(BAND_COLUMNS / height.div_ceil(6)); (columns.min(48), width, height) @@ -167,8 +155,8 @@ impl TranscriptImage { (columns.min(48), 160, 80.min(6 * cell_height)) } (_, PreviewKind::Inspected) => (columns.min(48), 384, 6 * cell_height), - (_, PreviewKind::Generated) => { - let ratio = f64::from(image.width()) / f64::from(image.height()); + (_, PreviewKind::Generated | PreviewKind::Inline) => { + let ratio = f64::from(width) / f64::from(height); let max_width = if ratio >= 2.0 { 768 } else if ratio >= 1.01 { @@ -184,23 +172,49 @@ impl TranscriptImage { (columns, max_width, max_height) } }; - let max_width = (u32::from(columns) * cell_width).min(max_width); - let mut pixels = image - .thumbnail(max_width.min(image.width()), max_height.min(image.height())) - .to_rgba8(); - if kind == PreviewKind::Generated && protocol != ImageProtocol::Sixel { + let max_width = u32::from(columns).saturating_mul(cell_width).min(max_width); + let max_height = max_height.min(crate::image_decode::MAX_PREVIEW_EDGE); + let mut pixels = preview.thumbnail(max_width, max_height).into_rgba8(); + let content_size = pixels.dimensions(); + if kind != PreviewKind::Inspected && protocol != ImageProtocol::Sixel { pixels = pad_to_cells(pixels, cell_width, cell_height); } - Some(Self { + let image = Arc::new(TranscriptImage { protocol, columns: pixels.width().div_ceil(cell_width) as u16, rows: pixels.height().div_ceil(cell_height) as u16, pixels, cell_width, cell_height, + }); + Some(Self { + image, + content_size, + source_size: preview.size, }) } + pub(crate) fn for_columns( + &self, + columns: u16, + kind: PreviewKind, + ) -> Option> { + let image = &self.image; + if columns >= image.columns { + return Some(Arc::clone(image)); + } + let (width, height) = self.content_size; + let pixels = image::imageops::crop_imm(&image.pixels, 0, 0, width, height).to_image(); + let preview = Preview { + image: DynamicImage::ImageRgba8(pixels), + size: self.source_size, + }; + let cells = Some((image.cell_width, image.cell_height)); + Self::fit_for_cells(&preview, columns, image.protocol, kind, cells).map(|p| p.image) + } +} + +impl TranscriptImage { /// Draw only the visible vertical slice, never covering the prompt header or composer. pub(crate) fn draw( &self, diff --git a/codex-rs/tui/src/transcript_image/background.rs b/codex-rs/tui/src/transcript_image/background.rs new file mode 100644 index 0000000000..c32c57f362 --- /dev/null +++ b/codex-rs/tui/src/transcript_image/background.rs @@ -0,0 +1,73 @@ +//! One in-flight file read per view. Publish its result before requesting a redraw. + +use std::time::Duration; +use std::time::Instant; +use tokio::sync::oneshot; + +use crate::tui::FrameRequester; + +pub(crate) struct ImageLoader { + pending: Option>>, + denied_at: Option, +} + +impl Default for ImageLoader { + fn default() -> Self { + Self { + pending: None, + denied_at: None, + } + } +} + +impl ImageLoader { + pub(crate) fn is_loading(&self) -> bool { + self.pending.is_some() + } + + /// Avoid rechecking a refused workspace on every keystroke. + pub(crate) fn recently_denied(&self) -> bool { + self.denied_at + .is_some_and(|t| t.elapsed() < Duration::from_secs(/*secs*/ 5)) + } + + pub(crate) fn poll(&mut self) -> Option { + let result = self.pending.as_mut()?.try_recv(); + if matches!(result, Err(oneshot::error::TryRecvError::Empty)) { + return None; + } + self.pending = None; + let image = result.ok()?; + if image.is_none() { + self.denied_at = Some(Instant::now()); + } + image + } + + pub(crate) fn start( + &mut self, + frames: &FrameRequester, + allowed: impl Future + Send + 'static, + load: impl FnOnce() -> T + Send + 'static, + ) { + if self.pending.is_some() { + return; + } + let (tx, rx) = oneshot::channel(); + self.pending = Some(rx); + let frames = frames.clone(); + tokio::spawn(async move { + if !allowed.await { + if tx.send(None).is_ok() { + frames.schedule_frame(); + } + return; + } + tokio::task::spawn_blocking(move || { + if !tx.is_closed() && tx.send(Some(load())).is_ok() { + frames.schedule_frame(); + } + }); + }); + } +} diff --git a/codex-rs/tui/src/transcript_image/composer.rs b/codex-rs/tui/src/transcript_image/composer.rs index c0a010d8c0..cddee1363f 100644 --- a/codex-rs/tui/src/transcript_image/composer.rs +++ b/codex-rs/tui/src/transcript_image/composer.rs @@ -3,8 +3,6 @@ use std::cell::RefCell; use std::collections::HashMap; -use std::path::Path; -use std::path::PathBuf; use std::sync::Arc; use image::Rgba; @@ -17,46 +15,60 @@ use ratatui::widgets::Wrap; use super::ImagePlacement; use super::TranscriptImage; +use super::background::ImageLoader; +use super::local::ImageFile; use super::terminal_cell_size; use crate::bottom_pane::LocalImageAttachment; use crate::bottom_pane::TextArea; +use crate::image_decode::Preview; use crate::pets::ImageProtocol; +use crate::tui::FrameRequester; // Six columns by three rows is square with typical 8 × 16 pixel cells. const WIDTH: u16 = 6; const HEIGHT: u16 = 3; -#[derive(Hash, PartialEq, Eq)] -struct TileKey { - path: PathBuf, - version: Option<(u64, std::time::SystemTime)>, -} - -pub(crate) struct ComposerImages { +#[derive(Clone, Copy, PartialEq)] +struct TileStyle { protocol: ImageProtocol, cell_size: (u32, u32), background: (u8, u8, u8), - cache: RefCell>>>, +} + +type Tile = Option>; + +pub(crate) struct ComposerImages { + style: TileStyle, + frames: FrameRequester, + loading: RefCell>, + cache: RefCell>, pub(crate) placements: RefCell>, } impl ComposerImages { - pub(crate) fn for_terminal(protocol: ImageProtocol, previous: Option) -> Option { + pub(crate) fn for_terminal( + protocol: ImageProtocol, + previous: Option, + frames: &FrameRequester, + ) -> Option { // Kitty can scale a nominal raster into its cell placement. Sixel needs physical pixels. let cell_size = terminal_cell_size() .or_else(|| (protocol != ImageProtocol::Sixel).then_some((8, 16)))?; let background = crate::terminal_palette::default_bg() .map(crate::style::user_message_bg_rgb) .unwrap_or((48, 48, 48)); - if previous.as_ref().is_some_and(|old| { - (old.protocol, old.cell_size, old.background) == (protocol, cell_size, background) - }) { - return previous; - } - Some(Self { + let style = TileStyle { protocol, cell_size, background, + }; + if previous.as_ref().is_some_and(|old| old.style == style) { + return previous; + } + Some(Self { + style, + frames: frames.clone(), + loading: previous.map(|old| old.loading).unwrap_or_default(), cache: RefCell::default(), placements: RefCell::default(), }) @@ -84,6 +96,12 @@ impl ComposerImages { let (visible, hidden) = visible_thumbnails(area.width, attachments.len()); let mut cache = self.cache.borrow_mut(); let mut previous = std::mem::take(&mut *cache); + let mut loading = self.loading.borrow_mut(); + if let Some((file, style, tile)) = loading.poll() + && style == self.style + { + previous.insert(file, tile); + } let mut placements = self.placements.borrow_mut(); placements.clear(); let style = crate::style::secondary_text_style(); @@ -104,24 +122,29 @@ impl ComposerImages { .unwrap_or(usize::MAX) }); } + let size = self.style.tile_size(); for attachment in ordered.into_iter().take(visible) { - let path = &attachment.path; - let key = TileKey { - path: path.clone(), - version: path - .metadata() - .ok() - .and_then(|m| Some((m.len(), m.modified().ok()?))), - }; - let image = cache.entry(key).or_insert_with_key(|key| { - previous - .remove(key) - .unwrap_or_else(|| self.load_tile(path).map(Arc::new)) + let image = ImageFile::at(&attachment.path).and_then(|file| { + if let Some(tile) = previous.remove(&file) { + cache.insert(file.clone(), tile); + } + if let Some(tile) = cache.get(&file) { + return tile.clone(); + } + let size = size?; + let style = self.style; + loading.start(&self.frames, async { true }, move || { + let tile = file + .read() + .map(|preview| Arc::new(style.make_tile(&preview, size))); + (file, style, tile) + }); + None }); let tile = Rect::new(x, area.y, WIDTH, HEIGHT); if let Some(image) = image { placements.push(ImagePlacement { - image: image.clone(), + image, area: tile, first_row: 0, file: None, @@ -139,8 +162,10 @@ impl ComposerImages { buf.set_string(x, area.y, format!("+{hidden}"), style); } } +} - fn load_tile(&self, path: &Path) -> Option { +impl TileStyle { + fn tile_size(&self) -> Option<(u32, u32)> { let (cell_width, cell_height) = self.cell_size; let width = u32::from(WIDTH) * cell_width; let height = u32::from(HEIGHT) * cell_height; @@ -149,9 +174,12 @@ impl ComposerImages { if scale > 1 && self.protocol == ImageProtocol::Sixel { return None; } - let width = (width / scale).max(3); - let height = (height / scale).max(3); - let pixels = TranscriptImage::load_pixels(path, width - 2, height - 2)?; + Some(((width / scale).max(3), (height / scale).max(3))) + } + + fn make_tile(&self, preview: &Preview, (width, height): (u32, u32)) -> TranscriptImage { + let (cell_width, cell_height) = self.cell_size; + let pixels = preview.thumbnail(width - 2, height - 2).into_rgba8(); let (r, g, b) = self.background; let contrast = if crate::color::is_light(self.background) { 0 @@ -177,14 +205,14 @@ impl ComposerImages { i64::from((width - pixels.width()) / 2), i64::from((height - pixels.height()) / 2), ); - Some(TranscriptImage { + TranscriptImage { protocol: self.protocol, columns: WIDTH, rows: HEIGHT, pixels: tile, cell_width, cell_height, - }) + } } } diff --git a/codex-rs/tui/src/transcript_image/local.rs b/codex-rs/tui/src/transcript_image/local.rs new file mode 100644 index 0000000000..108aaf1919 --- /dev/null +++ b/codex-rs/tui/src/transcript_image/local.rs @@ -0,0 +1,57 @@ +//! Read one bounded revision of a local file for both preview decode attempts. + +use std::fs::File; +use std::fs::Metadata; +use std::io::Read; +use std::path::Path; +use std::path::PathBuf; +use std::time::SystemTime; + +use crate::image_decode; +use crate::image_decode::Preview; + +#[derive(Clone, PartialEq, Eq, Hash)] +pub(crate) struct ImageFile { + path: PathBuf, + len: u64, + modified: Option, +} + +impl ImageFile { + pub(crate) fn at(path: &Path) -> Option { + let metadata = path.metadata().ok()?; + (metadata.is_file() && metadata.len() <= 32 * 1024 * 1024).then(|| Self { + path: path.to_owned(), + len: metadata.len(), + modified: metadata.modified().ok(), + }) + } + + fn matches(&self, metadata: &Metadata) -> bool { + metadata.is_file() + && metadata.len() == self.len + && metadata.modified().ok() == self.modified + } + + pub(super) fn read(&self) -> Option { + let mut options = File::options(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + // A queued photo can be replaced by a FIFO before the worker opens it. + options.custom_flags(libc::O_NONBLOCK); + } + let mut file = options.open(&self.path).ok()?; + if !self.matches(&file.metadata().ok()?) { + return None; + } + // Bound the read even if the file grows after checking the open handle. + let mut bytes = vec![0; self.len as usize]; + file.read_exact(&mut bytes).ok()?; + let format = image::guess_format(&bytes) + .or_else(|_| image::ImageFormat::from_path(&self.path)) + .ok()?; + image_decode::decode_preview(&bytes, format).ok() + } +} diff --git a/codex-rs/tui/src/transcript_image_tests.rs b/codex-rs/tui/src/transcript_image_tests.rs index 023d9ee02b..f218d991b6 100644 --- a/codex-rs/tui/src/transcript_image_tests.rs +++ b/codex-rs/tui/src/transcript_image_tests.rs @@ -24,14 +24,15 @@ fn sixel_output_fits_wide_images_within_the_original_encoding_budget() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("image.png"); let load = |columns| { - TranscriptImage::load_for_cells( - &path, + PreparedImage::load_for_cells( + &local::ImageFile::at(&path).unwrap(), columns, ImageProtocol::Sixel, PreviewKind::Generated, /*cell_size*/ Some((10, 20)), ) .unwrap() + .image }; let source = RgbaImage::from_fn( /*width*/ 300, diff --git a/codex-rs/tui/src/transcript_view.rs b/codex-rs/tui/src/transcript_view.rs index fb65a76fff..98f2d22e8b 100644 --- a/codex-rs/tui/src/transcript_view.rs +++ b/codex-rs/tui/src/transcript_view.rs @@ -15,9 +15,9 @@ pub(crate) use document::DocumentPosition; pub(crate) use document::DocumentTarget; mod follow_control; mod footer; +mod image_requests; mod input; mod layout; -mod markdown_images; mod mutations; mod prompt_header; mod search; diff --git a/codex-rs/tui/src/transcript_view/markdown_images.rs b/codex-rs/tui/src/transcript_view/image_requests.rs similarity index 51% rename from codex-rs/tui/src/transcript_view/markdown_images.rs rename to codex-rs/tui/src/transcript_view/image_requests.rs index 737111535c..e493029926 100644 --- a/codex-rs/tui/src/transcript_view/markdown_images.rs +++ b/codex-rs/tui/src/transcript_view/image_requests.rs @@ -1,27 +1,28 @@ -//! Load local Markdown images off the draw thread, only for visible replies. +//! Load local images off the draw thread, only for visible replies and tool cells. use std::path::Path; use std::sync::Arc; use std::sync::Weak; -use std::time::Duration; -use tokio::sync::oneshot; use crate::history_cell::HistoryCell; use crate::pets::ImageProtocol; +use crate::transcript_image::PreparedImage; use crate::transcript_image::PreviewKind; use crate::transcript_image::TranscriptImage; +use crate::transcript_image::background::ImageLoader; +use crate::transcript_image::local::ImageFile; use crate::tui::FrameRequester; // One bounded decoder in flight per view. Keep misses too, so an unavailable // preview never causes a redraw loop. A new reply can reuse the same filename. const CACHE_SIZE: usize = 32; -type Pixels = Option>; #[derive(Clone)] pub(super) struct Request { pub(super) reply: Weak, pub(super) path: Arc, pub(super) columns: u16, + pub(super) kind: PreviewKind, pub(super) protocol: ImageProtocol, pub(super) cell_size: Option<(u32, u32)>, } @@ -31,32 +32,47 @@ impl PartialEq for Request { self.reply.ptr_eq(&other.reply) && self.path == other.path && self.columns == other.columns + && self.kind == other.kind && self.protocol == other.protocol && self.cell_size == other.cell_size } } -#[derive(Default)] -pub(super) struct MarkdownImages { - cache: Vec<(Request, Pixels)>, - loading: Option>, +struct Pixels { + file: Option, + preview: Option, } -impl MarkdownImages { - pub(super) fn get(&self, request: &Request) -> Option<&Pixels> { +#[derive(Default)] +pub(super) struct TranscriptImages { + cache: Vec<(Request, Pixels)>, + loading: ImageLoader<(Request, Pixels)>, +} + +impl TranscriptImages { + fn get(&self, request: &Request) -> Option<&Pixels> { let (_, image) = self.cache.iter().find(|(key, _)| key == request)?; Some(image) } - /// Return the cell whose cached text layout can now include a preview. - pub(super) fn poll(&mut self) -> Option> { - let result = self.loading.as_mut()?.try_recv(); - if matches!(result, Err(oneshot::error::TryRecvError::Empty)) { + pub(super) fn fitted( + &mut self, + request: &Request, + columns: u16, + ) -> Option> { + let pixels = self.get(request)?; + // Check for edits on relayout only after the owning cell has authorized a read. + if request.kind != PreviewKind::Inline && pixels.file != ImageFile::at(&request.path) { + self.cache.retain(|(key, _)| key != request); return None; } - self.loading = None; - let (request, pixels) = result.ok()?; - let updated = pixels.as_ref().map(|_| request.reply.clone()); + pixels.preview.as_ref()?.for_columns(columns, request.kind) + } + + /// Return the cell whose cached text layout can now include a preview. + pub(super) fn poll(&mut self) -> Option> { + let (request, pixels) = self.loading.poll()?; + let updated = pixels.preview.as_ref().map(|_| request.reply.clone()); self.cache.push((request, pixels)); updated } @@ -67,11 +83,17 @@ impl MarkdownImages { frames: &FrameRequester, local_workspace: impl Future + Send + 'static, ) { - if self.loading.is_some() { + if self.loading.is_loading() { return; } + // Generated artifacts live on the daemon host. The other paths belong + // to the executor and need a check of this thread’s workspace. + let denied = self.loading.recently_denied(); let visible: Vec<_> = visible.collect(); - let Some(&request) = visible.iter().find(|r| self.get(r).is_none()) else { + let Some(&request) = visible + .iter() + .find(|r| (!denied || r.kind == PreviewKind::Generated) && self.get(r).is_none()) + else { return; }; if self.cache.len() >= CACHE_SIZE { @@ -84,32 +106,23 @@ impl MarkdownImages { self.cache.remove(index); } let request = request.clone(); - let (tx, rx) = oneshot::channel(); - self.loading = Some(rx); - let frames = frames.clone(); - tokio::spawn(async move { - if !local_workspace.await { - // Retry on a later draw if the workspace or connection changes. - tokio::time::sleep(Duration::from_secs(/*secs*/ 5)).await; - return; - } - tokio::task::spawn_blocking(move || { - if tx.is_closed() || request.reply.strong_count() == 0 { - drop(tx); - frames.schedule_frame(); - return; - } - let image = TranscriptImage::load_for_cells( - &request.path, + let generated = request.kind == PreviewKind::Generated; + let allowed = async move { generated || local_workspace.await }; + self.loading.start(frames, allowed, move || { + let file = request + .reply + .upgrade() + .and_then(|_| ImageFile::at(&request.path)); + let preview = file.as_ref().and_then(|file| { + PreparedImage::load_for_cells( + file, request.columns, request.protocol, - PreviewKind::Generated, + request.kind, request.cell_size, - ); - if tx.send((request, image.map(Arc::new))).is_ok() { - frames.schedule_frame(); - } + ) }); + (request, Pixels { file, preview }) }); } } diff --git a/codex-rs/tui/src/transcript_view/layout.rs b/codex-rs/tui/src/transcript_view/layout.rs index 51ef0b2096..80eb759dfa 100644 --- a/codex-rs/tui/src/transcript_view/layout.rs +++ b/codex-rs/tui/src/transcript_view/layout.rs @@ -68,7 +68,7 @@ fn cell_content_layout( presentation: CellPresentation, shortcut: Option, ) -> TextLayout { - let mut layout = if presentation.disclosure { + if presentation.disclosure { activity_layout( ActivityTranscriptLines { activity: if presentation.expanded { @@ -92,25 +92,7 @@ fn cell_content_layout( mode, ); TextLayout::new(bidi::session_lines(lines, presentation.bidi_layout), width) - }; - if let Some(protocol) = presentation.image_protocol - && let Some(path) = cell.image_path() - { - use crate::transcript_image::PreviewKind; - let kind = if cell - .as_any() - .is::() - { - PreviewKind::Generated - } else { - PreviewKind::Inspected - }; - layout.image = - crate::transcript_image::TranscriptImage::load(path.as_path(), width, protocol, kind) - .map(Arc::new); - layout.image_left_aligned = kind == PreviewKind::Generated; } - layout } fn is_rich_user_prompt(cell: &dyn HistoryCell, mode: HistoryRenderMode) -> bool { @@ -119,7 +101,7 @@ fn is_rich_user_prompt(cell: &dyn HistoryCell, mode: HistoryRenderMode) -> bool #[derive(Default)] pub(super) struct LayoutCache { - pub(super) images: markdown_images::MarkdownImages, + pub(super) images: image_requests::TranscriptImages, entries: Vec, viewport_height: u16, document_resize_preview: bool, @@ -200,6 +182,9 @@ impl TranscriptView { } let key = self.entry_key(cells, index); if let Some(layout) = self.search.match_layout(key) { + if self.selection.is_none() && layout.tool_image.is_some() && layout.image.is_none() { + return self.entry_layout(cells, index, /*full_content*/ true); + } return Some(layout); } self.base_layout(cells, index) @@ -217,7 +202,10 @@ impl TranscriptView { .snapshot() .and_then(|snapshot| snapshot.pinned.get(&key)) // Refresh previews after selection releases the pinned text layout. - .filter(|layout| self.selection.is_some() || !layout.has_markdown_images) + .filter(|layout| { + self.selection.is_some() + || (!layout.has_markdown_images && layout.tool_image.is_none()) + }) { return Some(Arc::clone(layout)); } @@ -375,8 +363,8 @@ impl LayoutCache { self.entries.clear(); self.render_state = Some(state); } - if let Some(reply) = self.images.poll() { - self.entries.retain(|entry| !entry.source.ptr_eq(&reply)); + if let Some(source) = self.images.poll() { + self.entries.retain(|entry| !entry.source.ptr_eq(&source)); } } @@ -416,11 +404,39 @@ impl LayoutCache { return layout; } let mut layout = render(); + if !presentation.summarized + && let Some(protocol) = presentation.image_protocol + && width > 2 + && (protocol != crate::pets::ImageProtocol::Sixel || self.cell_size().is_some()) + && let Some(path) = cell.image_path() + { + use crate::transcript_image::PreviewKind; + let kind = if cell + .as_any() + .is::() + { + PreviewKind::Generated + } else { + PreviewKind::Inspected + }; + let request = image_requests::Request { + reply: source.clone(), + path: path.as_path().into(), + // Refit the widest useful tool preview across viewport changes. + columns: u16::MAX, + kind, + protocol, + cell_size: self.cell_size(), + }; + layout.image = self.images.fitted(&request, width - 2); + layout.tool_image = Some(Box::new(request)); + layout.image_left_aligned = kind == PreviewKind::Generated; + } if let Some(protocol) = presentation.image_protocol && cell.as_any().is::() { let size = self.cell_size(); - images::attach(&mut layout, cell, protocol, size, &self.images); + images::attach(&mut layout, cell, protocol, size, &mut self.images); } let layout = if presentation.separated { layout.with_leading_separator() diff --git a/codex-rs/tui/src/transcript_view/layout_tests.rs b/codex-rs/tui/src/transcript_view/layout_tests.rs index 655009d84f..6cc7d5caca 100644 --- a/codex-rs/tui/src/transcript_view/layout_tests.rs +++ b/codex-rs/tui/src/transcript_view/layout_tests.rs @@ -273,8 +273,40 @@ async fn local_markdown_images_appear_at_their_labels_in_compact_replies() { insta::assert_snapshot!("inline_markdown_images", displayed.trim_end()); } -#[test] -fn fullscreen_image_previews_follow_layout_without_entering_text_surfaces() { +#[tokio::test] +async fn inspected_photo_requires_its_own_local_workspace_even_with_a_cached_namesake() { + use crate::history_cell::new_view_image_tool_call; + use crate::pets::ImageProtocol; + use codex_utils_path_uri::LegacyAppPathString; + + let dir = tempfile::tempdir().unwrap(); + let photo = dir.path().join("photo.jpg"); + image::RgbImage::new(16, 16).save(&photo).unwrap(); + let (frames, mut rx) = crate::tui::FrameRequester::test_channel(); + let area = Rect::new(0, 0, 48, 12); + let mut buf = Buffer::empty(area); + let mut view = TranscriptView { + detailed: true, + image_protocol: Some(ImageProtocol::Kitty), + ..Default::default() + }; + // Two threads on the same daemon inspect the same path on different executors. + for (local, expected) in [(true, 1), (false, 0)] { + let cells: [Arc; 1] = [Arc::new(new_view_image_tool_call( + "view-call".into(), + LegacyAppPathString::from_string(photo.to_string_lossy().into_owned()), + ))]; + view.render(area, &mut buf, &cells); + assert!(view.image_placements().is_empty()); + view.request_visible_images(&frames, async move { local }, /*streaming*/ None); + rx.recv().await.unwrap(); + view.render(area, &mut buf, &cells); + assert_eq!(view.image_placements().len(), expected); + } +} + +#[tokio::test] +async fn fullscreen_image_previews_follow_layout_without_entering_text_surfaces() { use crate::history_cell::new_image_generation_call; use crate::history_cell::new_view_image_tool_call; use crate::pets::ImageProtocol; @@ -286,8 +318,9 @@ fn fullscreen_image_previews_follow_layout_without_entering_text_surfaces() { image::RgbaImage::from_pixel(480, 160, image::Rgba([255, 0, 0, 255])) .save(&path) .unwrap(); - let square_path = dir.path().join("generated.png"); - image::RgbImage::new(768, 768).save(&square_path).unwrap(); + // The square needs 36 MiB at full resolution, above the preview budget. + let square_path = dir.path().join("generated.jpg"); + image::RgbImage::new(3584, 3584).save(&square_path).unwrap(); let cells: Vec> = vec![ Arc::new(new_view_image_tool_call( "view-call".to_string(), @@ -330,6 +363,10 @@ fn fullscreen_image_previews_follow_layout_without_entering_text_surfaces() { view.render(area, &mut buf, &cells); view.sync_turn_details(&cells, /*enabled*/ true, /*active*/ None); view.render(area, &mut buf, &cells); + let (frames, mut rx) = crate::tui::FrameRequester::test_channel(); + view.request_visible_images(&frames, async { true }, /*streaming*/ None); + rx.recv().await.unwrap(); + view.render(area, &mut buf, &cells); let collapsed = frame(&buf); let collapsed_areas: Vec<_> = view.image_placements().iter().map(|p| p.area).collect(); assert_eq!(collapsed_areas.len(), 1); @@ -357,6 +394,9 @@ fn fullscreen_image_previews_follow_layout_without_entering_text_surfaces() { .collect(); view.image_protocol = Some(ImageProtocol::Kitty); view.render(area, &mut buf, &cells); + view.request_visible_images(&frames, async { true }, /*streaming*/ None); + rx.recv().await.unwrap(); + view.render(area, &mut buf, &cells); let expanded_areas: Vec<_> = view.image_placements().iter().map(|p| p.area).collect(); insta::assert_snapshot!( "fullscreen_image_artifact_rows", @@ -418,12 +458,17 @@ fn fullscreen_image_previews_follow_layout_without_entering_text_surfaces() { assert_eq!(buf, text_only); assert!(view.image_placements().is_empty()); - // A tiny compressed file with a large decoded raster must also fall back to text. - image::RgbImage::new(4000, 3000).save(&path).unwrap(); + // Only JPEG gets the scaled fallback. An oversized PNG keeps the text label. + image::RgbImage::new(4000, 3000) + .save_with_format(&square_path, image::ImageFormat::Png) + .unwrap(); view.image_protocol = None; view.render(area, &mut buf, &cells); view.image_protocol = Some(ImageProtocol::Kitty); view.render(area, &mut buf, &cells); + view.request_visible_images(&frames, async { true }, /*streaming*/ None); + rx.recv().await.unwrap(); + view.render(area, &mut buf, &cells); assert_eq!(buf, text_only); assert!(view.image_placements().is_empty()); } diff --git a/codex-rs/tui/src/transcript_view/text.rs b/codex-rs/tui/src/transcript_view/text.rs index 8b66ebe2b8..0b7d2010e7 100644 --- a/codex-rs/tui/src/transcript_view/text.rs +++ b/codex-rs/tui/src/transcript_view/text.rs @@ -55,6 +55,7 @@ use ratatui::text::Line; pub(crate) struct TextLayout { blocks: std::sync::OnceLock, pub(super) image: Option>, + pub(super) tool_image: Option>, pub(super) image_left_aligned: bool, pub(super) has_markdown_images: bool, inline_images: Vec, @@ -248,6 +249,7 @@ impl TextLayout { layout = layout.with_control(control.label.clone(), control.anchor); } layout.image = self.image.clone(); + layout.tool_image = self.tool_image.clone(); layout.image_left_aligned = self.image_left_aligned; if self.leading_blank_hidden { layout = layout.without_leading_blank_row(); @@ -1140,6 +1142,7 @@ impl TextLayout { Self { blocks: Default::default(), image: None, + tool_image: None, image_left_aligned: false, has_markdown_images: false, inline_images: Vec::new(), diff --git a/codex-rs/tui/src/transcript_view/text_images.rs b/codex-rs/tui/src/transcript_view/text_images.rs index 9947cf2dc4..82472303ac 100644 --- a/codex-rs/tui/src/transcript_view/text_images.rs +++ b/codex-rs/tui/src/transcript_view/text_images.rs @@ -6,9 +6,10 @@ use crate::history_cell::HistoryCell; use crate::pets::ImageProtocol; use crate::terminal_hyperlinks::project_hyperlink_columns; use crate::terminal_hyperlinks::source_text_width; +use crate::transcript_image::PreviewKind; use crate::transcript_image::TranscriptImage; -use crate::transcript_view::markdown_images::MarkdownImages; -use crate::transcript_view::markdown_images::Request; +use crate::transcript_view::image_requests::Request; +use crate::transcript_view::image_requests::TranscriptImages; use std::ops::Range; use std::sync::Arc; @@ -35,7 +36,7 @@ pub(in crate::transcript_view) fn attach( reply: &Arc, protocol: ImageProtocol, cell_size: Option<(u32, u32)>, - cache: &MarkdownImages, + cache: &mut TranscriptImages, ) { let mut images: Vec = Vec::new(); for ((start, source), line) in layout.logical_sources().zip(&layout.logical) { @@ -52,16 +53,18 @@ pub(in crate::transcript_view) fn attach( last.label.end = label.end; continue; } + let columns = available_width(line, layout.width); let request = Request { reply: Arc::downgrade(reply), path: Arc::clone(&marker.path), - columns: available_width(line, layout.width), + columns, + kind: PreviewKind::Inline, protocol, cell_size, }; images.push(InlineImage { label, - image: cache.get(&request).cloned().flatten(), + image: cache.fitted(&request, columns), request, region: None, }); @@ -87,6 +90,7 @@ pub(in crate::transcript_view) fn visible_requests( .iter() .take_while(move |image| image.label.start <= end) .map(|image| &image.request) + .chain(layout.tool_image.as_deref()) } pub(in crate::transcript_view) fn regions(