diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index cc2984279d..e94e11d9d1 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3684,6 +3684,7 @@ dependencies = [ "serde_json", "tempfile", "tokio", + "unicode-segmentation", ] [[package]] diff --git a/codex-rs/app-server/src/fuzzy_file_search.rs b/codex-rs/app-server/src/fuzzy_file_search.rs index f8cd61e3ad..1513499947 100644 --- a/codex-rs/app-server/src/fuzzy_file_search.rs +++ b/codex-rs/app-server/src/fuzzy_file_search.rs @@ -45,7 +45,7 @@ pub(crate) async fn run_fuzzy_file_search( file_search::FileSearchOptions { limit, threads, - compute_indices: true, + index_unit: Some(file_search::IndexUnit::Grapheme), ..Default::default() }, Some(cancellation_flag), @@ -147,7 +147,7 @@ pub(crate) fn start_fuzzy_file_search_session( file_search::FileSearchOptions { limit, threads, - compute_indices: true, + index_unit: Some(file_search::IndexUnit::Grapheme), ..Default::default() }, reporter, diff --git a/codex-rs/app-server/tests/suite/fuzzy_file_search.rs b/codex-rs/app-server/tests/suite/fuzzy_file_search.rs index af7233640c..29882940e3 100644 --- a/codex-rs/app-server/tests/suite/fuzzy_file_search.rs +++ b/codex-rs/app-server/tests/suite/fuzzy_file_search.rs @@ -228,7 +228,7 @@ async fn test_fuzzy_file_search_sorts_and_includes_indices() -> Result<()> { std::fs::write(root.path().join("abcde"), "x")?; std::fs::write(root.path().join("abexy"), "x")?; std::fs::write(root.path().join("zzz.txt"), "x")?; - let sub_dir = root.path().join("sub"); + let sub_dir = root.path().join("👩‍💻"); std::fs::create_dir_all(&sub_dir)?; let sub_abce_path = sub_dir.join("abce"); std::fs::write(&sub_abce_path, "x")?; @@ -283,7 +283,7 @@ async fn test_fuzzy_file_search_sorts_and_includes_indices() -> Result<()> { "match_type": "file", "file_name": "abce", "score": filename_bonus + 72, - "indices": [4, 5, 7], + "indices": [2, 3, 5], }, { "root": root_path.clone(), @@ -356,7 +356,7 @@ async fn test_fuzzy_file_search_accepts_cancellation_token() -> Result<()> { async fn test_fuzzy_file_search_session_streams_updates() -> Result<()> { let codex_home = TempDir::new()?; let root = TempDir::new()?; - std::fs::write(root.path().join("alpha.txt"), "contents")?; + std::fs::write(root.path().join("👩‍💻alpha.txt"), "contents")?; let mut mcp = initialized_mcp(&codex_home).await?; let root_path = root.path().to_string_lossy().to_string(); @@ -371,7 +371,8 @@ async fn test_fuzzy_file_search_session_streams_updates() -> Result<()> { wait_for_session_updated(&mut mcp, session_id, "alp", FileExpectation::NonEmpty).await?; assert_eq!(payload.files.len(), 1); assert_eq!(payload.files[0].root, root_path); - assert_eq!(payload.files[0].path, "alpha.txt"); + assert_eq!(payload.files[0].path, "👩‍💻alpha.txt"); + assert_eq!(payload.files[0].indices, Some(vec![1, 2, 3])); let completed = wait_for_session_completed(&mut mcp, session_id).await?; assert_eq!(completed.session_id, session_id); diff --git a/codex-rs/file-search/Cargo.toml b/codex-rs/file-search/Cargo.toml index e235898982..250e7afa9f 100644 --- a/codex-rs/file-search/Cargo.toml +++ b/codex-rs/file-search/Cargo.toml @@ -25,6 +25,7 @@ nucleo = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } tokio = { workspace = true, features = ["full"] } +unicode-segmentation = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } diff --git a/codex-rs/file-search/src/lib.rs b/codex-rs/file-search/src/lib.rs index 908da6fa67..daf5d94427 100644 --- a/codex-rs/file-search/src/lib.rs +++ b/codex-rs/file-search/src/lib.rs @@ -46,12 +46,7 @@ pub use cli::Cli; /// * `path` – Path to the matched entry (file or directory), relative to the /// search directory. /// * `match_type` – Whether this match is a file or directory. -/// * `indices` – Optional list of character indices that matched the query. -/// These are only filled when the caller of [`run`] sets -/// `options.compute_indices` to `true`. The indices vector follows the -/// guidance from `nucleo::pattern::Pattern::indices`: they are -/// unique and sorted in ascending order so that callers can use -/// them directly for highlighting. +/// * `indices` – Sorted, unique offsets into `path` in the requested [`IndexUnit`]. #[derive(Debug, Clone, Serialize, PartialEq, Eq)] pub struct FileMatch { pub score: u32, @@ -114,12 +109,21 @@ pub struct FileSearchSnapshot { pub walk_complete: bool, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IndexUnit { + /// One position per matched grapheme, as used by the app-server protocol. + Grapheme, + /// Every Unicode scalar in each matched grapheme, for terminal highlighting. + Scalar, +} + #[derive(Debug, Clone)] pub struct FileSearchOptions { pub limit: NonZero, pub exclude: Vec, pub threads: NonZero, - pub compute_indices: bool, + /// Omit highlight indices when unset. + pub index_unit: Option, /// Toggle ignore-file processing in the walker. /// /// When enabled, `.gitignore` files are scoped by @@ -138,7 +142,7 @@ impl Default for FileSearchOptions { exclude: Vec::new(), #[expect(clippy::unwrap_used)] threads: NonZero::new(2).unwrap(), - compute_indices: false, + index_unit: None, respect_gitignore: true, } } @@ -183,7 +187,7 @@ pub fn create_session( limit, exclude, threads, - compute_indices, + index_unit, respect_gitignore, } = options; @@ -211,7 +215,7 @@ pub fn create_session( search_directories, limit: limit.get(), threads: threads.get(), - compute_indices, + index_unit, respect_gitignore, cancelled, shutdown: Arc::new(AtomicBool::new(false)), @@ -286,7 +290,7 @@ pub async fn run_main( limit, exclude, threads, - compute_indices, + index_unit: compute_indices.then_some(IndexUnit::Scalar), respect_gitignore: true, }, /*cancel_flag*/ None, @@ -364,7 +368,7 @@ struct SessionInner { search_directories: Vec, limit: usize, threads: usize, - compute_indices: bool, + index_unit: Option, respect_gitignore: bool, cancelled: Arc, shutdown: Arc, diff --git a/codex-rs/file-search/src/lib_tests.rs b/codex-rs/file-search/src/lib_tests.rs index 4893ec24a6..b3792bed6f 100644 --- a/codex-rs/file-search/src/lib_tests.rs +++ b/codex-rs/file-search/src/lib_tests.rs @@ -91,6 +91,35 @@ fn matching_filenames_survive_the_path_result_limit() { ); } +#[test] +fn highlights_use_scalar_offsets_for_basename_and_full_path_matches() { + let root = TempDir::new().unwrap(); + let parent = Path::new("e\u{301}"); + let path = parent.join("👩‍💻target.txt"); + fs::create_dir(root.path().join(parent)).unwrap(); + fs::write(root.path().join(&path), "").unwrap(); + + for (query, expected) in [ + ("target", vec![6, 7, 8, 9, 10, 11]), + ("e👩t", vec![0, 1, 3, 4, 5, 6]), + ] { + let result = run( + query, + vec![root.path().to_path_buf()], + FileSearchOptions { + index_unit: Some(IndexUnit::Scalar), + ..Default::default() + }, + /*cancel_flag*/ None, + ) + .unwrap(); + let [matched] = result.matches.as_slice() else { + panic!("expected one match for {query}"); + }; + assert_eq!((&matched.path, &matched.indices), (&path, &Some(expected))); + } +} + #[test] fn overlapping_roots_share_result_slots_by_path() { let dir = tempfile::tempdir().unwrap(); @@ -276,7 +305,7 @@ fn session_streams_updates_before_walk_complete() { search_directories: vec![dir.path().to_path_buf()], limit: 50, threads: 1, - compute_indices: false, + index_unit: None, respect_gitignore: true, cancelled: Arc::new(AtomicBool::new(false)), shutdown: Arc::new(AtomicBool::new(false)), @@ -447,7 +476,7 @@ fn run_returns_matches_for_query() { limit: NonZero::new(20).unwrap(), exclude: Vec::new(), threads: NonZero::new(2).unwrap(), - compute_indices: false, + index_unit: None, respect_gitignore: true, }; let results = run( @@ -482,7 +511,7 @@ fn run_returns_directory_matches_for_query() { limit: NonZero::new(20).unwrap(), exclude: Vec::new(), threads: NonZero::new(2).unwrap(), - compute_indices: false, + index_unit: None, respect_gitignore: true, }, /*cancel_flag*/ None, @@ -523,7 +552,7 @@ fn cancel_exits_run() { let cancel_flag = Arc::new(AtomicBool::new(true)); let search_dir = dir.path().to_path_buf(); let options = FileSearchOptions { - compute_indices: false, + index_unit: None, ..Default::default() }; let (tx, rx) = std::sync::mpsc::channel(); @@ -572,7 +601,7 @@ fn parent_gitignore_outside_repo_does_not_hide_repo_files() { limit: NonZero::new(20).unwrap(), exclude: Vec::new(), threads: NonZero::new(2).unwrap(), - compute_indices: false, + index_unit: None, respect_gitignore: true, }, /*cancel_flag*/ None, @@ -592,7 +621,7 @@ fn parent_gitignore_outside_repo_does_not_hide_repo_files() { limit: NonZero::new(20).unwrap(), exclude: Vec::new(), threads: NonZero::new(2).unwrap(), - compute_indices: false, + index_unit: None, respect_gitignore: true, }, /*cancel_flag*/ None, @@ -636,7 +665,7 @@ fn git_repo_still_respects_local_gitignore_when_enabled() { limit: NonZero::new(20).unwrap(), exclude: Vec::new(), threads: NonZero::new(2).unwrap(), - compute_indices: false, + index_unit: None, respect_gitignore: true, }, /*cancel_flag*/ None, @@ -656,7 +685,7 @@ fn git_repo_still_respects_local_gitignore_when_enabled() { limit: NonZero::new(20).unwrap(), exclude: Vec::new(), threads: NonZero::new(2).unwrap(), - compute_indices: false, + index_unit: None, respect_gitignore: true, }, /*cancel_flag*/ None, @@ -676,7 +705,7 @@ fn git_repo_still_respects_local_gitignore_when_enabled() { limit: NonZero::new(20).unwrap(), exclude: Vec::new(), threads: NonZero::new(2).unwrap(), - compute_indices: false, + index_unit: None, respect_gitignore: true, }, /*cancel_flag*/ None, diff --git a/codex-rs/file-search/src/matcher_tests.rs b/codex-rs/file-search/src/matcher_tests.rs index c7bb357e0d..e29d63c40f 100644 --- a/codex-rs/file-search/src/matcher_tests.rs +++ b/codex-rs/file-search/src/matcher_tests.rs @@ -33,7 +33,7 @@ fn query_update_does_not_relabel_pending_matches() { search_directories: vec![root.path().to_path_buf()], limit: 50, threads: 1, - compute_indices: true, + index_unit: Some(IndexUnit::Scalar), respect_gitignore: true, cancelled: Arc::new(AtomicBool::new(false)), shutdown: Arc::new(AtomicBool::new(false)), diff --git a/codex-rs/file-search/src/snapshot.rs b/codex-rs/file-search/src/snapshot.rs index a012c0eea7..d0198a0daf 100644 --- a/codex-rs/file-search/src/snapshot.rs +++ b/codex-rs/file-search/src/snapshot.rs @@ -2,6 +2,7 @@ use crate::FileMatch; use crate::FileSearchSnapshot; +use crate::IndexUnit; use crate::IndexedEntry; use crate::MatchType; use crate::SessionInner; @@ -16,6 +17,7 @@ use std::collections::BinaryHeap; use std::path::PathBuf; use std::time::Duration; use std::time::Instant; +use unicode_segmentation::UnicodeSegmentation; // A single Nucleo atom returns a u16. Leave room for its full score within each group. const NAME_BONUS: u32 = u16::MAX as u32 + 1; @@ -174,7 +176,7 @@ fn collect( entry.match_type, ), }; - let indices = if inner.compute_indices { + let indices = inner.index_unit.map(|unit| { let mut indices = Vec::::new(); let path = item.matcher_columns[0].slice(..); let haystack = if matched_name { basename(path) } else { path }; @@ -184,10 +186,24 @@ fn collect( } indices.sort_unstable(); indices.dedup(); - Some(indices) - } else { - None - }; + // Nucleo indexes graphemes. Highlight entire graphemes in the original path. + if unit == IndexUnit::Scalar + && matches!(item.data, IndexedEntry::Unicode(_)) + && path.len() != relative_path.chars().count() + { + let mut matches = indices.into_iter().peekable(); + indices = Vec::new(); + let mut start = 0; + for (i, grapheme) in relative_path.graphemes(/*is_extended*/ true).enumerate() { + let end = start + grapheme.chars().count() as u32; + if matches.next_if_eq(&(i as u32)).is_some() { + indices.extend(start..end); + } + start = end; + } + } + indices + }); Some(FileMatch { score: match_.score, path: PathBuf::from(relative_path), diff --git a/codex-rs/rollout/src/list.rs b/codex-rs/rollout/src/list.rs index 6a0485bfe0..df94d49bd2 100644 --- a/codex-rs/rollout/src/list.rs +++ b/codex-rs/rollout/src/list.rs @@ -1364,7 +1364,6 @@ async fn find_thread_path_by_id_str_in_subdir( let limit = NonZero::new(1).unwrap(); let options = file_search::FileSearchOptions { limit, - compute_indices: false, respect_gitignore: false, ..Default::default() }; diff --git a/codex-rs/tui/src/bottom_pane/file_search_popup.rs b/codex-rs/tui/src/bottom_pane/file_search_popup.rs index d116a32976..9f2a98d8bf 100644 --- a/codex-rs/tui/src/bottom_pane/file_search_popup.rs +++ b/codex-rs/tui/src/bottom_pane/file_search_popup.rs @@ -216,24 +216,26 @@ mod tests { .into_iter() .map(|name| parent.join(name)) .collect(); + let root = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(root.path().join(&parent)).unwrap(); + for path in &paths { + std::fs::write(root.path().join(path), "").unwrap(); + } + let mut matches = codex_file_search::run( + "parser", + vec![root.path().to_path_buf()], + codex_file_search::FileSearchOptions { + index_unit: Some(codex_file_search::IndexUnit::Scalar), + ..Default::default() + }, + /*cancel_flag*/ None, + ) + .unwrap() + .matches; + matches.sort_by(|a, b| a.path.cmp(&b.path)); let mut popup = FileSearchPopup::new(); popup.set_query("parser"); - popup.set_matches( - "parser", - paths - .iter() - .enumerate() - .map(|(index, path)| { - let mut matched = file_match(index); - matched.path = path.clone(); - matched.indices = - fuzzy_match(&path.to_string_lossy(), "parser").map(|(indices, _)| { - indices.into_iter().map(|index| index as u32).collect() - }); - matched - }) - .collect(), - ); + popup.set_matches("parser", matches); for (selected, path) in paths.iter().enumerate() { for width in [28, 40, 80] { let area = Rect::new( @@ -262,18 +264,12 @@ mod tests { ); 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| { - (x..x + 6) - .map(|column| buf[(column, unselected_y)].symbol()) - .eq(["p", "a", "r", "s", "e", "r"]) - }) - .expect("visible filename match"); - assert!( - buf[(parser_x, unselected_y)] - .modifier - .contains(ratatui::style::Modifier::BOLD) - ); + let highlighted: String = (0..width) + .map(|x| &buf[(x, unselected_y)]) + .filter(|cell| cell.modifier.contains(ratatui::style::Modifier::BOLD)) + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert_eq!(highlighted, "parser"); if selected == 0 { snapshots.push(format!("{components:?}, width {width}\n{text}")); } diff --git a/codex-rs/tui/src/bottom_pane/mentions_v2/render.rs b/codex-rs/tui/src/bottom_pane/mentions_v2/render.rs index b1370c9392..91f2c26e3c 100644 --- a/codex-rs/tui/src/bottom_pane/mentions_v2/render.rs +++ b/codex-rs/tui/src/bottom_pane/mentions_v2/render.rs @@ -289,36 +289,21 @@ fn primary_spans(row: &SearchResult, base_style: Style) -> Vec> { MentionType::File | MentionType::Directory => base_style, }; if let Some(indices) = row.match_indices.as_ref() { - highlighted_spans( - &row.display_name, - indices, - name_style, - MatchIndexUnit::Scalar, - ) - .collect() + highlighted_spans(&row.display_name, indices, name_style).collect() } else { vec![row.display_name.clone().set_style(name_style)] } } -enum MatchIndexUnit { - Scalar, - Grapheme, -} - fn highlighted_spans<'a>( text: &'a str, indices: &'a [usize], style: Style, - unit: MatchIndexUnit, ) -> impl Iterator> + 'a { let mut indices = indices.iter().peekable(); let mut index_end = 0; text.graphemes(/*is_extended*/ true).map(move |grapheme| { - index_end += match unit { - MatchIndexUnit::Scalar => grapheme.chars().count(), - MatchIndexUnit::Grapheme => 1, - }; + index_end += grapheme.chars().count(); let mut matched = false; while indices.next_if(|index| **index < index_end).is_some() { matched = true; @@ -368,12 +353,7 @@ fn path_spans(row: &SearchResult, base_style: Style) -> Vec> { .unwrap_or(row.display_name.len()); let path = &row.display_name[..byte_start]; if let Some(indices) = row.match_indices.as_ref() { - spans.extend(highlighted_spans( - path, - indices, - path_style, - MatchIndexUnit::Grapheme, - )); + spans.extend(highlighted_spans(path, indices, path_style)); } else { spans.push(path.to_string().set_style(path_style)); } diff --git a/codex-rs/tui/src/bottom_pane/mentions_v2/render_tests.rs b/codex-rs/tui/src/bottom_pane/mentions_v2/render_tests.rs index 81f92fc0f6..6408d49b42 100644 --- a/codex-rs/tui/src/bottom_pane/mentions_v2/render_tests.rs +++ b/codex-rs/tui/src/bottom_pane/mentions_v2/render_tests.rs @@ -184,7 +184,7 @@ fn fuzzy_matches_preserve_graphemes_when_truncated() { path: path.into(), full_path: path.into(), }, - match_indices: Some(vec![0, 1]), + match_indices: Some(vec![0, 1, 2, 3]), score: 0, }; let mut rendered = Vec::new(); @@ -208,6 +208,34 @@ fn fuzzy_matches_preserve_graphemes_when_truncated() { "); } +#[test] +fn parent_path_highlight_after_joined_emoji() { + let path = "👩‍💻notes/report_beta.rs"; + let row = SearchResult { + display_name: path.to_string(), + description: None, + mention_type: MentionType::File, + label_style: ThreadLabelStyle::Plain, + selection: Selection::File { + path: path.into(), + full_path: path.into(), + }, + match_indices: Some((3..12).collect()), + score: 0, + }; + let mut buffer = Buffer::empty(Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 60, /*height*/ 1, + )); + render_rows(buffer.area, &mut buffer, &[row], &ScrollState::new(), ""); + let bold: String = buffer + .content + .iter() + .filter(|cell| cell.modifier.contains(ratatui::style::Modifier::BOLD)) + .map(ratatui::buffer::Cell::symbol) + .collect(); + insta::assert_snapshot!(bold, @"notes/"); +} + #[test] fn long_mentions_leave_room_for_distinguishing_parent_paths() { let mut rows = rows(); diff --git a/codex-rs/tui/src/file_search.rs b/codex-rs/tui/src/file_search.rs index 70ac98de11..bf1062ae65 100644 --- a/codex-rs/tui/src/file_search.rs +++ b/codex-rs/tui/src/file_search.rs @@ -83,7 +83,7 @@ impl FileSearchManager { let session = file_search::create_session( vec![self.search_dir.clone()], file_search::FileSearchOptions { - compute_indices: true, + index_unit: Some(file_search::IndexUnit::Scalar), ..Default::default() }, reporter,