Render local Markdown images inline in TUI replies (#64254)

## Why

Markdown image references in assistant replies showed only their alt text,
so users had to open the referenced file to see the image.

## What changed

- Show previews in place of alt text in rich transcript views on supported
  terminals, including in side conversations. For example,
  `![Build chart](./chart.png)` can display the chart directly in the reply.
- Confirm that the conversation uses a local workspace before loading
  visible images off the render thread. Keep alt text as the fallback
  when a preview is unavailable, and preserve it for copying and Find.

## Testing

Add a transcript snapshot covering inline placement and fallback text,
plus tests for selection across previews, text-only Find layout, and
terminal image sizing.

GitOrigin-RevId: 6a3473d340b8771066d1f249f3d3363e1ca9f3bd
This commit is contained in:
Felipe Coury
2026-11-27 04:03:51 +00:00
committed by copyberry
parent 0ea76be91e
commit c7005a3d84
16 changed files with 810 additions and 50 deletions
+41
View File
@@ -12,6 +12,7 @@ use super::sidebar::PaneFocus;
use super::sidebar_document::DocumentRenderOptions;
use super::turn_tips::TipSurface;
use super::*;
use crate::app_server_session::fs::AppServerFileSystem;
use crate::bottom_pane::CommandPopupPlacement;
use crate::bottom_pane::ComposerRenderOptions;
use crate::custom_terminal::Frame;
@@ -154,6 +155,25 @@ impl PreparedConversation {
}
impl App {
/// Like Desktop, preview images with the user's file access. Confirm the reply
/// belongs to a workspace on this host before interpreting its paths here.
fn check_local_image_workspace(
&self,
source: ThreadId,
) -> Option<impl Future<Output = bool> + use<>> {
// A queued switch can still paint cells belonging to the outgoing thread.
if self.app_server_target.uses_remote_workspace() || self.pending_thread_switch_resets != 0
{
return None;
}
let request_handle = self
.conversation_backend_id(Some(source))
.filter(|owner| Some(*owner) == self.app_server_backend_id)
.and_then(|owner| self.backend_registry.request_handle(owner))?;
let fs = AppServerFileSystem { request_handle };
Some(async move { fs.preview_workspace(source).await.is_ok() })
}
/// Copy draft selections before key shortcuts, or after mouse layout has been refreshed.
pub(super) fn handle_composer_copy_event(
&mut self,
@@ -458,6 +478,15 @@ impl App {
}
}
painted = self.paint_conversation(frame, &prepared);
if let Some(local_workspace) =
displayed.and_then(|source| self.check_local_image_workspace(source))
{
self.transcript_view.request_visible_images(
&frames,
local_workspace,
/*streaming*/ None,
);
}
let label_style = parent
.and_then(|id| self.backend_registry.owner(id))
.or(self.app_server_backend_id)
@@ -472,6 +501,7 @@ impl App {
let watch_only = self.docked_agent().is_some_and(|(_, id)| {
id == panes.passive_thread && self.agent_navigation.is_parent_owned(id)
});
let local_workspace = self.check_local_image_workspace(panes.passive_thread);
if let Some(companion) = self.side_companions.get_mut(&panes.passive_thread) {
companion.view.bidi_layout = self.transcript_view.bidi_layout;
companion.view.agent_links = self.transcript_view.agent_links;
@@ -483,6 +513,17 @@ impl App {
&frames,
watch_only,
);
if let Some(local_workspace) = local_workspace {
let streaming = companion
.answer
.as_ref()
.and_then(|a| companion.cells.get(a.index));
companion.view.request_visible_images(
&frames,
local_workspace,
streaming,
);
}
}
}
Some(sidebar::SidebarLayout::Panel { sidebar, focus, .. }) => {
+1 -1
View File
@@ -30,7 +30,7 @@ pub(super) struct SideCompanion {
pub(super) struct SideAnswer {
turn_id: String,
item_id: String,
index: usize,
pub(super) index: usize,
pending: String,
}
+8 -1
View File
@@ -19,7 +19,14 @@ const REALTIME_STOP_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 1);
impl App {
pub(super) fn displayed_conversation_backend_id(&self) -> Option<crate::backend_id::BackendId> {
self.current_displayed_thread_id()
self.conversation_backend_id(self.current_displayed_thread_id())
}
pub(super) fn conversation_backend_id(
&self,
thread_id: Option<ThreadId>,
) -> Option<crate::backend_id::BackendId> {
thread_id
.and_then(|thread_id| {
self.thread_event_channels
.get(&thread_id)
+15 -4
View File
@@ -122,6 +122,7 @@ impl Inline {
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct CopyLine {
pub(crate) images: Vec<MarkdownImage>,
pub(crate) block: Option<Arc<block::Block>>,
pub(crate) prefix: String,
pub(crate) continuation: String,
@@ -178,7 +179,20 @@ pub(crate) fn has_visible_markup(
}))
}
/// A local image and its rendered label in this line's byte coordinates.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct MarkdownImage {
pub(crate) path: Arc<std::path::Path>,
pub(crate) label: Range<usize>,
}
impl CopyLine {
pub(crate) fn byte_len(&self) -> usize {
self.runs
.last()
.map_or(/*default*/ 0, |(range, _)| range.end)
}
pub(crate) fn has_list_marker(&self) -> bool {
self.prefix != self.continuation
}
@@ -198,10 +212,7 @@ impl CopyLine {
.collect::<Vec<_>>();
inline.sort();
inline.dedup();
let start = self
.runs
.last()
.map_or(/*default*/ 0, |(range, _)| range.end);
let start = self.byte_len();
// Keep literal spans separate so they never split context-sensitive prose escaping.
if literal {
if let Some(range) = self.literal_ranges.last_mut()
+43 -8
View File
@@ -43,6 +43,7 @@
//! Inline code and local file paths share the active syntax theme's raw-markup foreground.
use crate::line_truncation::span_width;
use crate::markdown_copy::MarkdownImage;
use crate::markdown_text_merge::DecodedTextMerge;
use crate::render::highlight::current_syntax_theme;
use crate::render::highlight::foreground_color_for_scopes;
@@ -547,6 +548,8 @@ struct Writer<'a, 'policy> {
copy_inline: Vec<crate::markdown_copy::Inline>,
blocks: crate::markdown_copy::block::Stack,
copy_line: crate::markdown_copy::CopyLine,
image_depth: usize,
image: Option<MarkdownImage>,
quote_sources: Vec<std::sync::Arc<str>>,
code_sources: Vec<crate::markdown_copy::SourceBlock>,
transformed_code_source: Option<std::sync::Arc<str>>,
@@ -596,6 +599,8 @@ impl<'a, 'policy> Writer<'a, 'policy> {
copy_inline: Vec::new(),
blocks: Default::default(),
copy_line: Default::default(),
image_depth: 0,
image: None,
quote_sources: Vec::new(),
code_sources: Vec::new(),
transformed_code_source: None,
@@ -821,14 +826,33 @@ impl<'a, 'policy> Writer<'a, 'policy> {
Tag::Strong => self.push_inline_style(self.styles.strong),
Tag::Strikethrough => self.push_inline_style(self.styles.strikethrough),
Tag::Link { dest_url, .. } => self.push_link(dest_url.to_string(), range.start),
Tag::Image { dest_url, .. } => {
self.image_depth += 1;
if self.image_depth == 1
&& !self.in_table_cell()
&& self.link.is_none()
&& let Some(path) =
local_links::local_image_path(&dest_url, self.cwd.as_deref())
{
if self.current_line_content.is_none()
|| self.needs_newline
|| self.pending_marker_line
{
self.push_line(Line::default());
self.needs_newline = false;
}
let start = self.copy_line.byte_len();
self.image = Some(MarkdownImage {
path: path.into(),
label: start..start,
});
}
}
Tag::Table(alignments) => self.start_table(alignments),
Tag::TableHead => self.start_table_head(),
Tag::TableRow => self.start_table_row(range),
Tag::TableCell => self.start_table_cell(),
Tag::HtmlBlock
| Tag::FootnoteDefinition(_)
| Tag::Image { .. }
| Tag::MetadataBlock(_) => {}
Tag::HtmlBlock | Tag::FootnoteDefinition(_) | Tag::MetadataBlock(_) => {}
}
}
@@ -873,14 +897,20 @@ impl<'a, 'policy> Writer<'a, 'policy> {
}
TagEnd::Emphasis | TagEnd::Strong | TagEnd::Strikethrough => self.pop_inline_style(),
TagEnd::Link => self.pop_link(),
TagEnd::Image => {
self.image_depth -= 1;
if self.image_depth == 0
&& let Some(mut image) = self.image.take()
{
image.label.end = self.copy_line.byte_len();
self.copy_line.images.push(image);
}
}
TagEnd::Table => self.end_table(),
TagEnd::TableHead => self.end_table_head(),
TagEnd::TableRow => self.end_table_row(),
TagEnd::TableCell => self.end_table_cell(),
TagEnd::HtmlBlock
| TagEnd::FootnoteDefinition
| TagEnd::Image
| TagEnd::MetadataBlock(_) => {}
TagEnd::HtmlBlock | TagEnd::FootnoteDefinition | TagEnd::MetadataBlock(_) => {}
}
}
@@ -2601,6 +2631,11 @@ impl<'a, 'policy> Writer<'a, 'policy> {
if let Some(mut line) = self.current_line_content.take() {
let style = self.current_line_style;
let mut source = crate::terminal_hyperlinks::LogicalLineSource::from_line(&line.line);
if let Some(image) = &mut self.image {
image.label.end = source.text.len();
self.copy_line.images.push(image.clone());
image.label = 0..0;
}
if !self.current_line_in_code_block
&& crate::wrapping::text_contains_url_like(&source.text)
{
@@ -98,6 +98,25 @@ pub(crate) fn is_markdown_file(path: &str) -> bool {
})
}
pub(super) fn local_image_path(
destination: &str,
cwd: Option<&Path>,
) -> Option<std::path::PathBuf> {
let link = sidebar_file_link(destination)?;
let path = Path::new(&link.path);
if link.location.is_some() || is_absolute_local_link_path(&link.path) != path.is_absolute() {
return None;
}
let resolved = cwd.unwrap_or_else(|| Path::new("")).join(path);
#[cfg(windows)]
if !matches!(resolved.components().next(), Some(std::path::Component::Prefix(p))
if matches!(p.kind(), std::path::Prefix::Disk(_) | std::path::Prefix::VerbatimDisk(_)))
{
return None;
}
resolved.is_absolute().then_some(resolved)
}
pub(crate) fn sidebar_file_link(destination: &str) -> Option<FileLink> {
if destination.len() > 8192 || destination.contains('?') {
return None;
+60 -5
View File
@@ -83,6 +83,12 @@ pub(crate) enum PreviewKind {
}
impl TranscriptImage {
pub(crate) fn fits(&self, available_columns: u16, cell_size: Option<(u32, u32)>) -> bool {
self.columns <= available_columns
&& (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<RgbaImage> {
if max_width == 0 || max_height == 0 {
return None;
@@ -118,21 +124,48 @@ impl TranscriptImage {
kind: PreviewKind,
) -> Option<Self> {
let columns = width.saturating_sub(2);
Self::load_for_cells(path, columns, protocol, kind, terminal_cell_size())
}
pub(crate) fn load_for_cells(
path: &Path,
columns: u16,
protocol: ImageProtocol,
kind: PreviewKind,
cell_size: Option<(u32, u32)>,
) -> Option<Self> {
if columns == 0 {
return None;
}
// Sixel paints physical pixels. Guessing could paint outside the reserved rows.
let (cell_width, cell_height) = match protocol {
ImageProtocol::Sixel => terminal_cell_size()?,
ImageProtocol::Sixel => cell_size?,
ImageProtocol::Kitty | ImageProtocol::KittyLocalFile => match kind {
PreviewKind::Inspected => (8, 16),
PreviewKind::Generated => terminal_cell_size().unwrap_or((8, 16)),
PreviewKind::Generated => cell_size.unwrap_or((8, 16)),
},
};
let image = Self::decode(path)?;
// Keep the current Sixel encoding and tmux placeholder budgets.
let (columns, max_width, max_height) = match (protocol, kind) {
(ImageProtocol::Sixel, _) => (columns.min(48), 160, 80.min(6 * cell_height)),
(ImageProtocol::Sixel, PreviewKind::Generated) => {
// 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 = height_at_budget
.clamp(1, 80)
.min(image.height())
.min(6 * cell_height);
let width = (PIXELS / height).min(BAND_COLUMNS / height.div_ceil(6));
(columns.min(48), width, height)
}
(ImageProtocol::Sixel, PreviewKind::Inspected) => {
(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());
@@ -152,9 +185,12 @@ impl TranscriptImage {
}
};
let max_width = (u32::from(columns) * cell_width).min(max_width);
let pixels = image
let mut pixels = image
.thumbnail(max_width.min(image.width()), max_height.min(image.height()))
.to_rgba8();
if kind == PreviewKind::Generated && protocol != ImageProtocol::Sixel {
pixels = pad_to_cells(pixels, cell_width, cell_height);
}
Some(Self {
protocol,
columns: pixels.width().div_ceil(cell_width) as u16,
@@ -224,3 +260,22 @@ impl TranscriptImage {
Ok(file)
}
}
/// Kitty stretches a placement to whole cells. Fill the last partial cells
/// with transparency so the fitted pixels keep their scale even when clipped.
fn pad_to_cells(pixels: RgbaImage, cell_width: u32, cell_height: u32) -> RgbaImage {
let width = pixels.width().next_multiple_of(cell_width);
let height = pixels.height().next_multiple_of(cell_height);
// Bound the allocation even for implausible terminal-reported cell sizes.
if pixels.dimensions() == (width, height) || u64::from(width) * u64::from(height) > 1024 * 1024
{
return pixels;
}
let mut canvas = RgbaImage::new(width, height);
image::imageops::replace(&mut canvas, &pixels, /*x*/ 0, /*y*/ 0);
canvas
}
#[cfg(test)]
#[path = "transcript_image_tests.rs"]
mod tests;
@@ -0,0 +1,53 @@
#![cfg(test)]
//! Pixel-level checks for fitting previews into terminal cells.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn padding_keeps_fitted_pixels_at_their_original_scale() {
let pixel = |x, y| image::Rgba([x as u8, y as u8, 42, 255]);
let toolbar = RgbaImage::from_fn(/*width*/ 299, /*height*/ 37, pixel);
let expected = RgbaImage::from_fn(/*width*/ 300, /*height*/ 52, |x, y| {
*toolbar
.get_pixel_checked(x, y)
.unwrap_or(&image::Rgba([0; 4]))
});
assert_eq!(
pad_to_cells(toolbar, /*cell_width*/ 12, /*cell_height*/ 26),
expected
);
}
#[test]
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,
columns,
ImageProtocol::Sixel,
PreviewKind::Generated,
/*cell_size*/ Some((10, 20)),
)
.unwrap()
};
let source = RgbaImage::from_fn(
/*width*/ 300,
/*height*/ 37,
|x, y| image::Rgba([x as u8, y as u8, 42, 255]),
);
source.save(&path).unwrap();
let image = load(30);
assert_eq!((image.columns, image.rows), (30, 2));
assert_eq!(image.pixels, source);
assert_eq!(load(20).pixels.dimensions(), (200, 25));
for (width, height) in [(600, 74), (900, 42), (720, 320)] {
RgbaImage::new(width, height).save(&path).unwrap();
let (w, h) = load(48).pixels.dimensions();
assert!(w * h <= 160 * 80);
assert!(w * h.div_ceil(6) <= 160 * 14);
}
}
+47 -30
View File
@@ -17,6 +17,7 @@ mod follow_control;
mod footer;
mod input;
mod layout;
mod markdown_images;
mod mutations;
mod prompt_header;
mod search;
@@ -51,6 +52,7 @@ use select_mode::SelectMode;
use selection::Selection;
use snapshot::ViewSnapshot;
pub(crate) use text::TextLayout;
use text::images;
pub(crate) use bookmark::TranscriptBookmark;
pub(crate) use input::JumpTarget;
@@ -465,6 +467,27 @@ impl TranscriptView {
}
}
pub(crate) fn request_visible_images(
&mut self,
frames: &crate::tui::FrameRequester,
local_workspace: impl Future<Output = bool> + Send + 'static,
streaming: Option<&Arc<dyn HistoryCell>>,
) {
if self.image_protocol.is_none() || self.mode != HistoryRenderMode::Rich {
return;
}
let streaming = streaming.map(EntryKey::cell);
let visible = self
.visible
.chunk_by(|a, b| a.index == b.index)
.filter(|rows| Some(rows[0].key) != streaming)
.flat_map(|rows| {
let first = &rows[0];
images::visible_requests(&first.layout, first.row..first.row + rows.len())
});
self.cache.images.request(visible, frames, local_workspace);
}
pub(crate) fn image_placements(&self) -> Vec<crate::transcript_image::ImagePlacement> {
let mut placements = Vec::new();
let mut y = self.area.y;
@@ -472,33 +495,30 @@ impl TranscriptView {
let entry_y = y;
y += rows.len() as u16;
let visible = &rows[0];
let Some(image) = visible.layout.visible_image() else {
continue;
};
let image_start = visible.layout.text_row_count();
let skip = image_start.saturating_sub(visible.row);
if skip >= rows.len() {
continue;
for (start, indent, image) in images::regions(&visible.layout) {
let top = start.max(visible.row);
let bottom = (start + usize::from(image.rows)).min(visible.row + rows.len());
if top >= bottom
|| !image.fits(
self.area.width.saturating_sub(indent),
self.cache.cell_size(),
)
{
continue;
}
placements.push(crate::transcript_image::ImagePlacement {
image: Arc::clone(image),
area: Rect::new(
self.area.x + indent,
entry_y + (top - visible.row) as u16,
image.columns,
(bottom - top) as u16,
),
first_row: top - start,
file: None,
terminal_id: None,
});
}
let image_indent = if visible.layout.image_left_aligned {
// Match the two-column prefix the assistant's Markdown uses.
2
} else {
self.area.width.saturating_sub(image.columns) / 2
};
let area = Rect::new(
self.area.x + image_indent,
entry_y + skip as u16,
image.columns,
(rows.len() - skip) as u16,
);
placements.push(crate::transcript_image::ImagePlacement {
image: Arc::clone(image),
area,
first_row: visible.row.saturating_sub(image_start),
file: None,
terminal_id: None,
});
}
placements
}
@@ -844,10 +864,7 @@ impl TranscriptView {
Position::Reading(anchor) => {
let index = self.resolve(cells, anchor);
let row = self.layout(cells, index).map_or(/*default*/ 0, |layout| {
layout
.row_for_offset(anchor.offset)
.saturating_add_signed(anchor.row_bias.saturating_neg())
.min(layout.row_count().saturating_sub(/*rhs*/ 1))
layout.reading_row(anchor.offset, anchor.row_bias)
});
self.position = Position::Reading(Anchor {
key: self.entry_key(cells, index),
+18 -1
View File
@@ -117,6 +117,7 @@ fn is_rich_user_prompt(cell: &dyn HistoryCell, mode: HistoryRenderMode) -> bool
#[derive(Default)]
pub(super) struct LayoutCache {
pub(super) images: markdown_images::MarkdownImages,
entries: Vec<CachedLayout>,
document_resize_preview: bool,
frame: u64,
@@ -212,6 +213,8 @@ impl TranscriptView {
if let Some(layout) = self
.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)
{
return Some(Arc::clone(layout));
}
@@ -332,6 +335,10 @@ impl TranscriptView {
}
impl LayoutCache {
pub(super) fn cell_size(&self) -> Option<(u32, u32)> {
self.render_state.as_ref().and_then(|state| state.cell_size)
}
pub(super) fn set_document_resize_preview(&mut self, active: bool) {
if self.document_resize_preview && !active {
// Markdown tables and other width-dependent content need an exact final layout.
@@ -363,6 +370,9 @@ 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));
}
}
pub(super) fn get(
@@ -395,7 +405,13 @@ impl LayoutCache {
}
return layout;
}
let layout = render();
let mut layout = render();
if let Some(protocol) = presentation.image_protocol
&& cell.as_any().is::<crate::history_cell::AgentMarkdownCell>()
{
let size = self.cell_size();
images::attach(&mut layout, cell, protocol, size, &self.images);
}
let layout = if presentation.separated {
layout.with_leading_separator()
} else {
@@ -461,6 +477,7 @@ impl LayoutCache {
let retained_bytes = |entry: &CachedLayout| {
entry.layout.text().len()
+ entry.layout.mapping_bytes
+ images::retained_bytes(&entry.layout)
+ entry
.layout
.image
@@ -166,6 +166,112 @@ fn recent_entries_are_reused_and_old_entries_are_evicted() {
);
}
#[tokio::test]
async fn local_markdown_images_appear_at_their_labels_in_compact_replies() {
use crate::history_cell::AgentMarkdownCell;
use crate::pets::ImageProtocol;
use crate::transcript_view::tests::text;
use crate::tui::FrameRequester;
use crossterm::event::KeyModifiers;
use crossterm::event::MouseButton;
use crossterm::event::MouseEvent;
use crossterm::event::MouseEventKind;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("toolbar final.png");
image::RgbaImage::new(/*width*/ 1, /*height*/ 1)
.save(&path)
.unwrap();
std::fs::copy(&path, dir.path().join("trailing.png")).unwrap();
let markdown = format!(
"![Installed toolbar](<{}>)![](trailing.png)\n\n\
Before ![two\nlines][toolbar] after.\n\n\
- ![](toolbar%20final.png) caption\n\n\
![remote](https://example.com/t.png) and ![missing](missing.png).\n\n\
Final ![trailing label](trailing.png)\n\n\
[toolbar]: toolbar%20final.png",
url::Url::from_file_path(&path).unwrap()
);
let cells: Vec<Arc<dyn HistoryCell>> =
vec![Arc::new(AgentMarkdownCell::new(markdown, dir.path()))];
let area = Rect::new(
/*x*/ 3, /*y*/ 4, /*width*/ 48, /*height*/ 32,
);
let mut buf = Buffer::empty(area);
let mut view = TranscriptView {
copy_on_select: true,
..Default::default()
};
let (tx, mut rx) = tokio::sync::broadcast::channel(/*capacity*/ 1);
let frames = FrameRequester::new(tx);
view.render(area, &mut buf, &cells);
let original = view.layout(&cells, /*index*/ 0).unwrap();
assert!(text(&buf).contains("Installed toolbar"));
view.image_protocol = Some(ImageProtocol::Kitty);
view.render(area, &mut buf, &cells);
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 10), async {
while view.image_placements().len() < 5 {
view.request_visible_images(&frames, async { true }, /*streaming*/ None);
rx.recv().await.unwrap();
view.render(area, &mut buf, &cells);
}
})
.await
.unwrap();
for placement in view.image_placements() {
buf[(placement.area.x, placement.area.y)].set_symbol("▣");
}
let displayed = crate::terminal_hyperlinks::strip_osc8(&text(&buf));
let layout = view.layout(&cells, /*index*/ 0).unwrap();
assert_eq!(layout.text(), original.text());
let search = Arc::clone(&layout).for_search();
assert_eq!(search.row_count(), original.row_count());
assert_eq!(images::regions(&search).count(), 0);
assert!(search.has_markdown_images);
assert_eq!(images::regions(&layout.rewrap(/*width*/ 1)).count(), 0);
let preview = view.image_placements().last().unwrap().area;
assert_eq!(preview.height, 1);
let before = (preview.x, preview.y - 1);
for (column, expected) in [
(preview.right() - 1, "Final "),
(preview.right(), "Final trailing label"),
(preview.right() + 2, "Final trailing label"),
] {
let after = (column, preview.y);
for (from, to) in [(before, after), (after, before)] {
for (kind, (column, row)) in [
(MouseEventKind::Down(MouseButton::Left), from),
(MouseEventKind::Drag(MouseButton::Left), to),
] {
view.handle_mouse(
MouseEvent {
kind,
column,
row,
modifiers: KeyModifiers::NONE,
},
&cells,
);
}
let Some(ViewAction::CopyOnSelect(copied)) = view.handle_mouse(
MouseEvent {
kind: MouseEventKind::Up(MouseButton::Left),
column: to.0,
row: to.1,
modifiers: KeyModifiers::NONE,
},
&cells,
) else {
panic!("expected a copy on release for {from:?} → {to:?}");
};
assert_eq!(copied, expected, "{from:?} → {to:?}");
}
}
insta::assert_snapshot!("inline_markdown_images", displayed.trim_end());
}
#[test]
fn fullscreen_image_previews_follow_layout_without_entering_text_surfaces() {
use crate::history_cell::new_image_generation_call;
@@ -0,0 +1,115 @@
//! Load local Markdown images off the draw thread, only for visible replies.
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::PreviewKind;
use crate::transcript_image::TranscriptImage;
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<Arc<TranscriptImage>>;
#[derive(Clone)]
pub(super) struct Request {
pub(super) reply: Weak<dyn HistoryCell>,
pub(super) path: Arc<Path>,
pub(super) columns: u16,
pub(super) protocol: ImageProtocol,
pub(super) cell_size: Option<(u32, u32)>,
}
impl PartialEq for Request {
fn eq(&self, other: &Self) -> bool {
self.reply.ptr_eq(&other.reply)
&& self.path == other.path
&& self.columns == other.columns
&& self.protocol == other.protocol
&& self.cell_size == other.cell_size
}
}
#[derive(Default)]
pub(super) struct MarkdownImages {
cache: Vec<(Request, Pixels)>,
loading: Option<oneshot::Receiver<(Request, Pixels)>>,
}
impl MarkdownImages {
pub(super) 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<Weak<dyn HistoryCell>> {
let result = self.loading.as_mut()?.try_recv();
if matches!(result, Err(oneshot::error::TryRecvError::Empty)) {
return None;
}
self.loading = None;
let (request, pixels) = result.ok()?;
let updated = pixels.as_ref().map(|_| request.reply.clone());
self.cache.push((request, pixels));
updated
}
pub(super) fn request<'a>(
&mut self,
visible: impl Iterator<Item = &'a Request>,
frames: &FrameRequester,
local_workspace: impl Future<Output = bool> + Send + 'static,
) {
if self.loading.is_some() {
return;
}
let visible: Vec<_> = visible.collect();
let Some(&request) = visible.iter().find(|r| self.get(r).is_none()) else {
return;
};
if self.cache.len() >= CACHE_SIZE {
// Never evict another preview on screen just to request it again next frame.
let offscreen = self
.cache
.iter()
.position(|(key, _)| !visible.contains(&key));
let Some(index) = offscreen else { return };
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,
request.columns,
request.protocol,
PreviewKind::Generated,
request.cell_size,
);
if tx.send((request, image.map(Arc::new))).is_ok() {
frames.schedule_frame();
}
});
});
}
}
@@ -116,6 +116,7 @@ impl TranscriptView {
self.search.current = current;
layout?
};
let layout = layout.for_search();
self.search.scanning_layout = Some((anchor.key, Arc::clone(&layout)));
Some(layout)
}
@@ -0,0 +1,18 @@
---
source: tui/src/transcript_view/layout_tests.rs
expression: displayed.trim_end()
---
• ▣
▣
Before
▣
after.
• ▣
caption
remote and missing.
Final
▣
+34
View File
@@ -12,6 +12,8 @@ use std::sync::Arc;
#[path = "text_blocks.rs"]
pub(super) mod blocks;
#[path = "text_images.rs"]
pub(super) mod images;
#[path = "text_logical.rs"]
mod logical;
@@ -54,6 +56,8 @@ pub(crate) struct TextLayout {
blocks: std::sync::OnceLock<blocks::BlockIndex>,
pub(super) image: Option<std::sync::Arc<crate::transcript_image::TranscriptImage>>,
pub(super) image_left_aligned: bool,
pub(super) has_markdown_images: bool,
inline_images: Vec<images::InlineImage>,
logical: Vec<LogicalLine>,
text: String,
rows: Vec<TextRow>,
@@ -225,7 +229,21 @@ impl TextLayout {
/// Reflow the same displayed content revision, retaining styles, links and disclosure label.
pub(super) fn rewrap(&self, width: u16) -> Self {
self.reflow(width, self.inline_images.clone())
}
pub(super) fn for_search(self: Arc<Self>) -> Arc<Self> {
if self.inline_images.is_empty() {
self
} else {
Arc::new(self.reflow(self.width, Vec::new()))
}
}
fn reflow(&self, width: u16, images: Vec<images::InlineImage>) -> Self {
let mut layout = Self::from_logical(self.logical.clone(), width);
layout.has_markdown_images = self.has_markdown_images;
images::place(&mut layout, images);
if let Some(control) = &self.disclosure_control {
layout = layout.with_control(control.label.clone(), control.anchor);
}
@@ -735,6 +753,9 @@ impl TextLayout {
/// Resolve a cell coordinate to a grapheme boundary, clamping padding to the row's text.
pub(super) fn position_at(&self, row: usize, column: u16) -> usize {
if let Some(end) = images::label_end_at(self, row, column) {
return end;
}
let Some(row) = self.rows.get(row) else {
return self.text.len();
};
@@ -866,6 +887,17 @@ impl TextLayout {
.map_or(/*default*/ 0, str::len)
}
pub(super) fn reading_row(&self, offset: usize, bias: isize) -> usize {
let row = self.row_for_offset(offset);
let target = row.saturating_add_signed(bias.saturating_neg());
// A resize may briefly replace several rows at one offset with a single label.
if bias > 0 && !self.inline_images.is_empty() {
let first = self.rows.partition_point(|r| r.source.start < offset);
return target.max(first.min(row));
}
target.min(self.row_count().saturating_sub(/*rhs*/ 1))
}
/// Find the display row containing a source position, including omitted wrapping whitespace.
pub(super) fn row_for_offset(&self, offset: usize) -> usize {
if self.visible_image().is_some() && offset >= self.text.len() {
@@ -1109,6 +1141,8 @@ impl TextLayout {
blocks: Default::default(),
image: None,
image_left_aligned: false,
has_markdown_images: false,
inline_images: Vec::new(),
logical,
text,
mapping_bytes: rows
@@ -0,0 +1,231 @@
//! Substitute previews for labels in the painted rows, retaining logical text for copy and Find.
use super::LogicalLine;
use super::TextLayout;
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::TranscriptImage;
use crate::transcript_view::markdown_images::MarkdownImages;
use crate::transcript_view::markdown_images::Request;
use std::ops::Range;
use std::sync::Arc;
#[derive(Clone)]
pub(super) struct InlineImage {
label: Range<usize>,
request: Request,
image: Option<Arc<TranscriptImage>>,
// First row measured from the end, so prepending a spacer preserves the placement.
region: Option<(usize, u16)>,
}
pub(in crate::transcript_view) fn retained_bytes(layout: &TextLayout) -> usize {
layout
.inline_images
.iter()
.filter_map(|i| i.image.as_ref())
.map(|i| i.pixels.len())
.sum()
}
pub(in crate::transcript_view) fn attach(
layout: &mut TextLayout,
reply: &Arc<dyn HistoryCell>,
protocol: ImageProtocol,
cell_size: Option<(u32, u32)>,
cache: &MarkdownImages,
) {
let mut images: Vec<InlineImage> = Vec::new();
for ((start, source), line) in layout.logical_sources().zip(&layout.logical) {
let Some(copy) = &source.copy else { continue };
for marker in &copy.images {
let offset = |byte: usize| {
start + (byte.clamp(source.range.start, source.range.end) - source.range.start)
};
let label = offset(marker.label.start)..offset(marker.label.end);
// Fragments of the same multiline label share the original allocation.
if let Some(last) = images.last_mut()
&& Arc::ptr_eq(&last.request.path, &marker.path)
{
last.label.end = label.end;
continue;
}
let request = Request {
reply: Arc::downgrade(reply),
path: Arc::clone(&marker.path),
columns: available_width(line, layout.width),
protocol,
cell_size,
};
images.push(InlineImage {
label,
image: cache.get(&request).cloned().flatten(),
request,
region: None,
});
}
}
layout.has_markdown_images = !images.is_empty();
place(layout, images);
}
pub(in crate::transcript_view) fn visible_requests(
layout: &TextLayout,
rows: Range<usize>,
) -> impl Iterator<Item = &Request> {
let visible = layout.rows.get(rows).unwrap_or_default();
let start = visible.first().map_or(usize::MAX, |r| r.source.start);
let end = visible
.last()
.map_or(/*default*/ 0, |r| r.line_end.unwrap_or(r.source.end));
let first = layout
.inline_images
.partition_point(|i| i.label.end < start);
layout.inline_images[first..]
.iter()
.take_while(move |image| image.label.start <= end)
.map(|image| &image.request)
}
pub(in crate::transcript_view) fn regions(
layout: &TextLayout,
) -> impl Iterator<Item = (usize, u16, &Arc<TranscriptImage>)> {
let trailing = layout.visible_image().map(|image| {
let indent = if layout.image_left_aligned {
2
} else {
(layout.width - image.columns) / 2
};
(layout.rows.len(), indent, image)
});
layout
.inline_images
.iter()
.filter_map(|inline| {
let (distance, indent) = inline.region?;
let row = layout.rows.len().checked_sub(distance)?;
Some((row, indent, inline.image.as_ref()?))
})
.chain(trailing)
}
/// Dragging past a preview's first row includes its label, even for a one-row image.
pub(super) fn label_end_at(layout: &TextLayout, row: usize, column: u16) -> Option<usize> {
layout.inline_images.iter().find_map(|inline| {
let (distance, indent) = inline.region?;
let image = inline.image.as_ref()?;
(layout.rows.len().checked_sub(distance) == Some(row)
&& usize::from(column) >= usize::from(indent) + usize::from(image.columns))
.then_some(inline.label.end)
})
}
pub(super) fn place(layout: &mut TextLayout, mut images: Vec<InlineImage>) {
if !images.iter().any(|i| i.image.is_some()) {
layout.inline_images = images;
return;
}
let lines = std::mem::take(&mut layout.logical);
let mut original = std::mem::take(&mut layout.rows).into_iter().peekable();
let mut start = 0;
let mut resume = None;
let mut pending = images.iter_mut().peekable();
for line in &lines {
let end = start + line.origin.range.len();
let first = layout.rows.len();
while let Some(inline) = pending.next_if(|i| i.label.start <= end) {
inline.region = None;
let Some(image) = &inline.image else { continue };
if !image.fits(
available_width(line, layout.width),
inline.request.cell_size,
) || layout.text.get(inline.label.clone()).is_none()
{
continue;
}
append_fragment(layout, line, start, resume, inline.label.start);
let mut prefix = if layout.rows.len() == first
&& resume.is_none()
&& line.initial_indent.width() > 0
{
&line.initial_indent
} else {
&line.subsequent_indent
};
let indent = prefix.width();
inline.region = Some((layout.rows.len(), indent as u16));
let mut offset = inline.label.start;
for _ in 0..image.rows {
layout.insert_presentation_row(layout.rows.len(), offset, indent, prefix.clone());
prefix = &line.subsequent_indent;
offset = inline.label.end;
}
resume = Some(inline.label.end);
}
while let Some(row) = original.next_if(|r| r.source.start <= end) {
if resume.is_none() {
layout.rows.push(row);
}
}
if resume.is_some_and(|offset| offset <= end) {
append_fragment(layout, line, start, resume.take(), end);
if let Some(row) = layout.rows.last_mut() {
row.line_end = Some(end);
}
}
start = end + 1;
}
layout.logical = lines;
for image in &mut images {
if let Some((row, _)) = &mut image.region {
*row = layout.rows.len() - *row;
}
}
layout.inline_images = images;
}
fn append_fragment(
layout: &mut TextLayout,
line: &LogicalLine,
start: usize,
resume: Option<usize>,
end: usize,
) {
let offset = resume.unwrap_or(start);
let Some(text) = layout.text.get(offset..end) else {
return;
};
if text.trim().is_empty() {
return;
}
let mut fragment = line.clone();
let mut left = offset;
if resume.is_some() {
fragment.initial_indent = line.subsequent_indent.clone();
left += text.len() - text.trim_start().len();
}
let right = offset + text.trim_end().len();
fragment.line.line = super::logical::slice_line(&line.line.line, left - start..right - start);
if !fragment.line.hyperlinks.is_empty() {
let column = |x| source_text_width(&layout.text[start..x]);
fragment.line.hyperlinks = project_hyperlink_columns(
&line.line.hyperlinks,
column(left)..column(right),
/*prefix*/ 0,
);
}
fragment.origin.range.start += left - start;
layout
.rows
.extend(super::layout_line(&fragment, left, layout.width));
}
fn available_width(line: &LogicalLine, width: u16) -> u16 {
let indent = line
.initial_indent
.width()
.max(line.subsequent_indent.width());
usize::from(width).saturating_sub(indent) as u16
}