Resolve TUI image attachments relative to the file search root (#64071)

## Why

Selecting an image through `@` completion could fail when the file
search root differed from the process working directory. The composer
used the relative completion path to open the image.

## What changed

Use the full path from the search result to read and attach images in
both mention pickers. Keep relative paths for text insertion and check
that an image candidate is a regular file before opening it, so a named
pipe such as `pipe.png` is inserted as text without blocking the composer.

## Testing

Regression tests cover submitting an image from the search root in both
pickers and inserting an image-named pipe as relative text on Unix.

GitOrigin-RevId: f1d38f58dd431c3fb12b11ed35838f0b7bfa5674
This commit is contained in:
Eric Traut
2026-11-26 04:00:27 +00:00
committed by copyberry
parent 9e51c745e2
commit af71942309
8 changed files with 101 additions and 26 deletions
+31 -13
View File
@@ -2322,11 +2322,12 @@ impl ChatComposer {
};
};
let sel_path = sel.to_string_lossy().to_string();
let full_path = sel.full_path();
let sel_path = sel.path.to_string_lossy().into_owned();
if let Some((token_range, _)) =
self.current_editable_at_token_range_with_options(/*allow_empty*/ false)
{
self.insert_selected_file_path(token_range, &sel_path);
self.insert_selected_file_path(token_range, &sel_path, full_path);
}
self.popups.active = ActivePopup::None;
(InputResult::None, true)
@@ -2524,10 +2525,11 @@ impl ChatComposer {
.map(|(range, _)| range);
if let (Some(selected), Some(token_range)) = (selected, token_range) {
match selected {
MentionV2Selection::File(path) => {
MentionV2Selection::File { path, full_path } => {
self.insert_selected_file_path(
token_range,
path.to_string_lossy().as_ref(),
&path.to_string_lossy(),
full_path,
);
}
MentionV2Selection::Tool { insert_text, path } => {
@@ -2634,18 +2636,22 @@ impl ChatComposer {
}
}
fn insert_selected_file_path(&mut self, token_range: Range<usize>, selected_path: &str) {
fn insert_selected_file_path(
&mut self,
token_range: Range<usize>,
selected_path: &str,
full_path: PathBuf,
) {
let started_edit = self.begin_direct_edit();
let token_range = self.separate_completion_from_adjacent_element(token_range);
if Self::is_image_path(selected_path) {
let path_buf = PathBuf::from(selected_path);
match image::image_dimensions(&path_buf) {
if Self::is_image_path(selected_path) && full_path.is_file() {
match image::image_dimensions(&full_path) {
Ok((width, height)) => {
tracing::debug!("selected image dimensions={}x{}", width, height);
let start_idx = token_range.start;
self.draft.textarea.replace_range(token_range, "");
self.draft.textarea.set_cursor(start_idx);
self.attach_image(path_buf);
self.attach_image(full_path);
self.advance_past_completion_separator();
}
Err(err) => {
@@ -5120,6 +5126,10 @@ mod snapshot_tests;
#[path = "chat_composer/mentions_layout_tests.rs"]
mod mentions_layout_tests;
#[cfg(test)]
#[path = "chat_composer/image_completion_tests.rs"]
mod image_completion_tests;
#[cfg(test)]
#[path = "chat_composer/skill_completion_tests.rs"]
mod skill_completion_tests;
@@ -10492,7 +10502,7 @@ mod tests {
}
}
fn complete_file(
pub(super) fn complete_file(
composer: &mut ChatComposer,
text: &str,
cursor: usize,
@@ -10511,7 +10521,10 @@ mod tests {
query.to_string(),
vec![FileMatch {
score: 1,
path: selected_path,
path: selected_path
.strip_prefix(&root)
.unwrap_or(&selected_path)
.to_path_buf(),
match_type: codex_file_search::MatchType::File,
root,
indices: None,
@@ -10550,7 +10563,11 @@ mod tests {
fn adjacent_file_completion_inserts_leading_separator() {
let (mut composer, _rx) = new_test_composer();
configure_bound_plugin_left_of_unbound_plugin(&mut composer);
composer.insert_selected_file_path("@sample".len().."@sample@other".len(), "src/main.rs");
composer.insert_selected_file_path(
"@sample".len().."@sample@other".len(),
"src/main.rs",
"/tmp/src/main.rs".into(),
);
assert_eq!(composer.current_text(), "@sample src/main.rs ");
}
@@ -10569,7 +10586,8 @@ mod tests {
let before = composer.draft_snapshot();
composer.insert_selected_file_path(
"@sample".len().."@sample@other".len(),
image_path.to_str().expect("UTF-8 path"),
"image.png",
image_path.clone(),
);
assert_eq!(composer.current_text(), "@sample [Image #1] ");
@@ -788,7 +788,7 @@ fn vim_replace_completion_preserves_suffix() {
composer.set_text_content(text.into(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor(cursor);
keys(composer, command);
composer.insert_selected_file_path(0.."@ma".len(), path);
composer.insert_selected_file_path(0.."@ma".len(), path, path.into());
composer.sync_popups();
assert_eq!(
(composer.current_text(), composer.current_cursor()),
@@ -0,0 +1,44 @@
#![cfg(test)]
//! Image attachment and text fallback for file picker selections.
use super::tests::complete_file;
use super::tests::new_test_composer;
use super::*;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
#[test]
fn image_completion_submits_the_file_from_the_search_root() {
let tmp = tempdir().expect("create TempDir");
let path = tmp.path().join("snap4.png");
image::RgbaImage::new(1, 1).save(&path).expect("write PNG");
for mentions_v2 in [false, true] {
let (mut composer, _rx) = new_test_composer();
composer.set_mentions_v2_enabled(mentions_v2);
complete_file(&mut composer, "@snap", "@snap".len(), "snap", path.clone());
insta::allow_duplicates! {
insta::assert_snapshot!(composer.current_text().trim_end(), @"[Image #1]");
}
let (result, _) =
composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(matches!(result, InputResult::Submitted { .. }));
assert_eq!(composer.take_recent_submission_images(), vec![path.clone()]);
}
}
#[cfg(unix)]
#[test]
fn image_completion_keeps_a_named_pipe_as_relative_text() {
let tmp = tempdir().expect("create TempDir");
let path = tmp.path().join("pipe.png");
let status = std::process::Command::new("mkfifo")
.arg(&path)
.status()
.expect("run mkfifo");
assert!(status.success());
let (mut composer, _rx) = new_test_composer();
complete_file(&mut composer, "@pipe", "@pipe".len(), "pipe", path);
insta::assert_snapshot!(composer.current_text().trim_end(), @"pipe.png");
}
@@ -1,8 +1,6 @@
//! Display file completions while preserving the full path used for insertion.
//! Narrow rows retain the filename; fuzzy highlights refer to the displayed text.
use std::path::PathBuf;
use codex_file_search::FileMatch;
use codex_utils_fuzzy_match::fuzzy_match;
use ratatui::buffer::Buffer;
@@ -96,11 +94,10 @@ impl FileSearchPopup {
self.state.ensure_visible(len, len.min(MAX_POPUP_ROWS));
}
pub(crate) fn selected_match(&self) -> Option<&PathBuf> {
pub(crate) fn selected_match(&self) -> Option<&FileMatch> {
self.state
.selected_idx
.and_then(|idx| self.matches.get(idx))
.map(|file_match| &file_match.path)
}
pub(crate) fn calculate_required_height(&self) -> u16 {
@@ -194,6 +191,7 @@ mod tests {
use super::*;
use codex_file_search::MatchType;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
fn file_match(index: usize) -> FileMatch {
FileMatch {
@@ -262,7 +260,7 @@ mod tests {
text.contains("parser_alpha.rs") && text.contains("parser_beta.rs"),
"{text}"
);
assert_eq!(popup.selected_match(), Some(path));
assert_eq!(popup.selected_match().map(|m| &m.path), Some(path));
let unselected_y = if selected == 0 { 2 } else { 1 };
let parser_x = (0..width.saturating_sub(/*rhs*/ 5))
.find(|&x| {
@@ -10,7 +10,10 @@ const TAG_WIDTH: usize = "Plugin".len();
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Selection {
File(PathBuf),
File {
path: PathBuf,
full_path: PathBuf,
},
Tool {
insert_text: String,
path: Option<String>,
@@ -104,7 +104,10 @@ fn file_match_to_row(file_match: &FileMatch) -> SearchResult {
description: None,
mention_type,
label_style: ThreadLabelStyle::Plain,
selection: Selection::File(file_match.path.clone()),
selection: Selection::File {
path: file_match.path.clone(),
full_path: file_match.full_path(),
},
match_indices: file_match
.indices
.as_ref()
@@ -410,12 +410,12 @@ fn file_name(row: &SearchResult) -> Option<&str> {
fn file_name_start(row: &SearchResult) -> usize {
match row.selection {
Selection::File(_) if row.mention_type.is_filesystem() => row
Selection::File { .. } if row.mention_type.is_filesystem() => row
.display_name
.rfind(['/', '\\'])
.map(|idx| row.display_name[..idx + 1].chars().count())
.unwrap_or(0),
Selection::File(_) | Selection::Tool { .. } => usize::MAX,
Selection::File { .. } | Selection::Tool { .. } => usize::MAX,
}
}
@@ -25,7 +25,10 @@ fn rows() -> Vec<SearchResult> {
description: None,
mention_type: MentionType::File,
label_style: ThreadLabelStyle::Plain,
selection: Selection::File(name.into()),
selection: Selection::File {
path: name.into(),
full_path: name.into(),
},
match_indices: None,
score: 0,
});
@@ -177,7 +180,10 @@ fn fuzzy_matches_preserve_graphemes_when_truncated() {
description: None,
mention_type: MentionType::File,
label_style: ThreadLabelStyle::Plain,
selection: Selection::File(path.into()),
selection: Selection::File {
path: path.into(),
full_path: path.into(),
},
match_indices: Some(vec![0, 1]),
score: 0,
};
@@ -216,7 +222,10 @@ fn long_mentions_leave_room_for_distinguishing_parent_paths() {
description: None,
mention_type: MentionType::File,
label_style: ThreadLabelStyle::Plain,
selection: Selection::File(name.into()),
selection: Selection::File {
path: name.into(),
full_path: name.into(),
},
match_indices: None,
score: 0,
});