| 1 | //! Fuzzy file-picker modal (Ctrl+P). |
| 2 | //! |
| 3 | //! Opens an overlay populated with workspace-relative paths discovered by a |
| 4 | //! single-pass `WalkBuilder` walk (depth from `mention_walk_depth`, default |
| 5 | //! 10, `0` = unlimited; hidden=true, follow_links=false, |
| 6 | //! `.gitignore` honored). The walk keeps at most [`MAX_CANDIDATES`] paths in |
| 7 | //! walk order so opening the picker stays bounded on huge repos. Subsequent |
| 8 | //! keystrokes filter that cached list in memory using a small subsequence + |
| 9 | //! first-letter-bonus scorer — no per-keystroke disk traversal. |
| 10 | //! |
| 11 | //! When the typed query matches nothing in that truncated index, a targeted |
| 12 | //! rescan walks from the query's existing path prefix (or the workspace root) |
| 13 | //! and collects only matching files. Raising `mention_walk_depth` cannot |
| 14 | //! recover files past the 20k cutoff; the rescan can (#2488). |
| 15 | //! |
| 16 | //! Enter emits a [`ViewEvent::FilePickerSelected`] which the UI handler turns |
| 17 | //! into an `@<path>` insertion at the composer cursor. |
| 18 | |
| 19 | use std::cell::{Cell, RefCell}; |
| 20 | use std::collections::HashSet; |
| 21 | use std::path::{Path, PathBuf}; |
| 22 | use std::sync::{Arc, Mutex}; |
| 23 | |
| 24 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; |
| 25 | use ignore::WalkBuilder; |
| 26 | use ratatui::{ |
| 27 | buffer::Buffer, |
| 28 | layout::Rect, |
| 29 | style::Style, |
| 30 | text::{Line, Span}, |
| 31 | widgets::{Paragraph, Widget}, |
| 32 | }; |
| 33 | |
| 34 | use crate::tui::views::rounded::{ |
| 35 | pad_selected_line, render_rounded_footer, render_rounded_surface, |
| 36 | }; |
| 37 | use crate::tui::views::{ |
| 38 | ActionHint, ModalKind, ModalView, ViewAction, ViewEvent, render_panel_scroll_rail, |
| 39 | }; |
| 40 | use codewhale_localization::{Locale, MessageId, tr}; |
| 41 | use codewhale_palette as palette; |
| 42 | use codewhale_runtime::workspace_discovery::{ |
| 43 | DISCOVERY_ALWAYS_DIRS, path_is_excluded_from_discovery, |
| 44 | }; |
| 45 | use codewhale_tui_kit::menu_style; |
| 46 | |
| 47 | /// Maximum number of candidates collected from the initial walk. Keeps memory |
| 48 | /// bounded for very large monorepos; matches the limits codex-rs uses for the |
| 49 | /// equivalent overlay. Files past this cutoff are recovered by a query-targeted |
| 50 | /// rescan rather than by raising the cap or `mention_walk_depth` (#2488). |
| 51 | const MAX_CANDIDATES: usize = 20_000; |
| 52 | |
| 53 | /// Cap on files a miss-rescan may add. The walk itself continues past |
| 54 | /// [`MAX_CANDIDATES`] looking for matches; only this many hits are merged. |
| 55 | const MAX_RESCAN_HITS: usize = 512; |
| 56 | |
| 57 | /// Default walk depth used by the picker's own tests. Production callers pass |
| 58 | /// the configured `mention_walk_depth` (default 10, `0` = unlimited) through |
| 59 | /// [`FilePickerView::new_with_relevance_and_depth`], mirroring the `Workspace` |
| 60 | /// fuzzy index default (`DEFAULT_COMPLETIONS_WALK_DEPTH`). |
| 61 | #[cfg(test)] |
| 62 | const WALK_DEPTH: usize = 10; |
| 63 | |
| 64 | /// Visible candidate rows in the overlay. |
| 65 | const VISIBLE_ROWS: usize = 14; |
| 66 | |
| 67 | const MODIFIED_BOOST: i32 = 360; |
| 68 | const MENTIONED_BOOST: i32 = 240; |
| 69 | const TOOL_BOOST: i32 = 160; |
| 70 | |
| 71 | /// Working-set hints captured when the picker opens. |
| 72 | /// |
| 73 | /// The picker keeps this as plain path strings so filtering stays in-memory and |
| 74 | /// per-keystroke work remains the same shape as the original fuzzy search. |
| 75 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 76 | pub struct FilePickerRelevance { |
| 77 | modified: HashSet<String>, |
| 78 | mentioned: HashSet<String>, |
| 79 | tool: HashSet<String>, |
| 80 | } |
| 81 | |
| 82 | impl FilePickerRelevance { |
| 83 | pub fn mark_modified(&mut self, path: impl Into<String>) { |
| 84 | let path = path.into(); |
| 85 | if !path.is_empty() { |
| 86 | self.modified.insert(path); |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | pub fn mark_mentioned(&mut self, path: impl Into<String>) { |
| 91 | let path = path.into(); |
| 92 | if !path.is_empty() { |
| 93 | self.mentioned.insert(path); |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub fn mark_tool(&mut self, path: impl Into<String>) { |
| 98 | let path = path.into(); |
| 99 | if !path.is_empty() { |
| 100 | self.tool.insert(path); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | fn boost_for(&self, path: &str) -> i32 { |
| 105 | let mut boost = 0; |
| 106 | if self.modified.contains(path) { |
| 107 | boost += MODIFIED_BOOST; |
| 108 | } |
| 109 | if self.mentioned.contains(path) { |
| 110 | boost += MENTIONED_BOOST; |
| 111 | } |
| 112 | if self.tool.contains(path) { |
| 113 | boost += TOOL_BOOST; |
| 114 | } |
| 115 | boost |
| 116 | } |
| 117 | |
| 118 | fn markers_for(&self, path: &str) -> String { |
| 119 | let mut markers = String::with_capacity(3); |
| 120 | markers.push(if self.modified.contains(path) { |
| 121 | 'M' |
| 122 | } else { |
| 123 | ' ' |
| 124 | }); |
| 125 | markers.push(if self.mentioned.contains(path) { |
| 126 | '@' |
| 127 | } else { |
| 128 | ' ' |
| 129 | }); |
| 130 | markers.push(if self.tool.contains(path) { 'T' } else { ' ' }); |
| 131 | markers |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | pub struct FilePickerView { |
| 136 | /// All workspace-relative candidate paths, captured once at construction. |
| 137 | candidates: Vec<String>, |
| 138 | /// Working-set relevance hints, captured once at construction. |
| 139 | relevance: FilePickerRelevance, |
| 140 | /// Filtered indices into `candidates`, sorted by descending score. |
| 141 | filtered: Vec<usize>, |
| 142 | /// User's typed query (lowercased on each refilter). |
| 143 | query: String, |
| 144 | /// Selected row within `filtered`. |
| 145 | selected: usize, |
| 146 | /// Top of the visible window within `filtered`. |
| 147 | scroll: Cell<usize>, |
| 148 | visible_rows: Cell<usize>, |
| 149 | /// Exact visible row targets from the last render for mouse parity. |
| 150 | last_row_hitboxes: RefCell<Vec<(u16, usize)>>, |
| 151 | /// UI locale captured from the app at construction (#4057 wave 2). |
| 152 | locale: Locale, |
| 153 | /// True until the background workspace scan delivers (#3905). The picker |
| 154 | /// paints immediately in this state instead of blocking the event loop on |
| 155 | /// a `git status` subprocess and a 20k-file walk. |
| 156 | is_loading: bool, |
| 157 | /// True while a query-targeted rescan is in flight (#2488). |
| 158 | is_rescanning: bool, |
| 159 | /// Where the background scan drops its result. `None` once drained, or |
| 160 | /// when the scan ran synchronously (no tokio runtime, i.e. unit tests). |
| 161 | loading_cell: Option<Arc<Mutex<Option<PickerScan>>>>, |
| 162 | /// Retained so a query that misses the truncated index can rescan. |
| 163 | workspace_root: PathBuf, |
| 164 | /// Depth used by the initial walk and by a miss-rescan (`None` = unlimited). |
| 165 | max_depth: Option<usize>, |
| 166 | /// True when the initial walk stopped at [`MAX_CANDIDATES`]. |
| 167 | index_truncated: bool, |
| 168 | /// Lowercased query a rescan was last completed for. Prevents repeating |
| 169 | /// a walk that already produced no extra hits. |
| 170 | rescan_query: Option<String>, |
| 171 | } |
| 172 | |
| 173 | /// What the off-thread workspace scan produces: the candidate paths and the |
| 174 | /// git-reported modified paths, which are the only two blocking parts of |
| 175 | /// building this picker. |
| 176 | struct WorkspaceScan { |
| 177 | candidates: Vec<String>, |
| 178 | modified: Vec<String>, |
| 179 | truncated: bool, |
| 180 | } |
| 181 | |
| 182 | /// Either the opening walk or a later query-targeted miss-rescan. |
| 183 | enum PickerScan { |
| 184 | Initial(WorkspaceScan), |
| 185 | Targeted { query: String, hits: Vec<String> }, |
| 186 | } |
| 187 | |
| 188 | struct CandidateWalk { |
| 189 | paths: Vec<String>, |
| 190 | truncated: bool, |
| 191 | } |
| 192 | |
| 193 | impl FilePickerView { |
| 194 | /// Build a picker with working-set relevance hints, using the default |
| 195 | /// walk depth ([`WALK_DEPTH`]). Test-only convenience; production code uses |
| 196 | /// [`FilePickerView::new_with_relevance_and_depth`] with the configured |
| 197 | /// `mention_walk_depth`. |
| 198 | #[cfg(test)] |
| 199 | pub fn new_with_relevance(workspace_root: &Path, relevance: FilePickerRelevance) -> Self { |
| 200 | Self::new_with_relevance_and_depth(workspace_root, relevance, WALK_DEPTH, Locale::En) |
| 201 | } |
| 202 | |
| 203 | /// Build a picker with working-set relevance hints and an explicit walk |
| 204 | /// depth. A depth of `0` disables the depth limit so files in deeply |
| 205 | /// nested workspaces (>= 6 levels) remain discoverable. Files past the |
| 206 | /// [`MAX_CANDIDATES`] walk-order cutoff are recovered by a targeted |
| 207 | /// rescan when the typed query misses the index (#2488). |
| 208 | pub fn new_with_relevance_and_depth( |
| 209 | workspace_root: &Path, |
| 210 | relevance: FilePickerRelevance, |
| 211 | walk_depth: usize, |
| 212 | locale: Locale, |
| 213 | ) -> Self { |
| 214 | let max_depth = if walk_depth == 0 { |
| 215 | None |
| 216 | } else { |
| 217 | Some(walk_depth) |
| 218 | }; |
| 219 | |
| 220 | // Outside a tokio runtime (plain unit tests) do the work inline, so |
| 221 | // tests keep observing a fully-populated picker from the constructor. |
| 222 | if tokio::runtime::Handle::try_current().is_err() { |
| 223 | let walk = collect_candidates_limited(workspace_root, max_depth, MAX_CANDIDATES); |
| 224 | let mut relevance = relevance; |
| 225 | for path in crate::tui::file_picker_relevance::modified_workspace_paths(workspace_root) |
| 226 | { |
| 227 | relevance.mark_modified(path); |
| 228 | } |
| 229 | let mut view = Self { |
| 230 | candidates: walk.paths, |
| 231 | relevance, |
| 232 | filtered: Vec::new(), |
| 233 | query: String::new(), |
| 234 | selected: 0, |
| 235 | scroll: Cell::new(0), |
| 236 | visible_rows: Cell::new(VISIBLE_ROWS), |
| 237 | last_row_hitboxes: RefCell::new(Vec::new()), |
| 238 | locale, |
| 239 | is_loading: false, |
| 240 | is_rescanning: false, |
| 241 | loading_cell: None, |
| 242 | workspace_root: workspace_root.to_path_buf(), |
| 243 | max_depth, |
| 244 | index_truncated: walk.truncated, |
| 245 | rescan_query: None, |
| 246 | }; |
| 247 | view.refilter(); |
| 248 | return view; |
| 249 | } |
| 250 | |
| 251 | // Both halves of the scan are blocking: `git status` is a subprocess, |
| 252 | // and the walk visits up to MAX_CANDIDATES paths. Neither belongs on |
| 253 | // the event loop — Ctrl+P used to freeze the whole TUI until both |
| 254 | // finished (#3905), the same failure #3899/#3900 fixed for the |
| 255 | // adjacent @-mention and file-tree paths. |
| 256 | let loading_cell = Arc::new(Mutex::new(None)); |
| 257 | let cell = loading_cell.clone(); |
| 258 | let root = workspace_root.to_path_buf(); |
| 259 | codewhale_util::utils::spawn_blocking_supervised("file-picker-scan", move || { |
| 260 | let walk = collect_candidates_limited(&root, max_depth, MAX_CANDIDATES); |
| 261 | let scan = PickerScan::Initial(WorkspaceScan { |
| 262 | candidates: walk.paths, |
| 263 | modified: crate::tui::file_picker_relevance::modified_workspace_paths(&root), |
| 264 | truncated: walk.truncated, |
| 265 | }); |
| 266 | if let Ok(mut guard) = cell.lock() { |
| 267 | *guard = Some(scan); |
| 268 | } |
| 269 | }); |
| 270 | |
| 271 | let mut view = Self { |
| 272 | candidates: Vec::new(), |
| 273 | relevance, |
| 274 | filtered: Vec::new(), |
| 275 | query: String::new(), |
| 276 | selected: 0, |
| 277 | scroll: Cell::new(0), |
| 278 | visible_rows: Cell::new(VISIBLE_ROWS), |
| 279 | last_row_hitboxes: RefCell::new(Vec::new()), |
| 280 | locale, |
| 281 | is_loading: true, |
| 282 | is_rescanning: false, |
| 283 | loading_cell: Some(loading_cell), |
| 284 | workspace_root: workspace_root.to_path_buf(), |
| 285 | max_depth, |
| 286 | index_truncated: false, |
| 287 | rescan_query: None, |
| 288 | }; |
| 289 | view.refilter(); |
| 290 | view |
| 291 | } |
| 292 | |
| 293 | /// Test helper: a picker whose in-memory index is already known, including |
| 294 | /// whether that index hit [`MAX_CANDIDATES`]. Used to exercise miss-rescan |
| 295 | /// without creating 20k files. |
| 296 | #[cfg(test)] |
| 297 | fn from_preloaded( |
| 298 | workspace_root: &Path, |
| 299 | candidates: Vec<String>, |
| 300 | truncated: bool, |
| 301 | max_depth: Option<usize>, |
| 302 | ) -> Self { |
| 303 | let mut view = Self { |
| 304 | candidates, |
| 305 | relevance: FilePickerRelevance::default(), |
| 306 | filtered: Vec::new(), |
| 307 | query: String::new(), |
| 308 | selected: 0, |
| 309 | scroll: Cell::new(0), |
| 310 | visible_rows: Cell::new(VISIBLE_ROWS), |
| 311 | last_row_hitboxes: RefCell::new(Vec::new()), |
| 312 | locale: Locale::En, |
| 313 | is_loading: false, |
| 314 | is_rescanning: false, |
| 315 | loading_cell: None, |
| 316 | workspace_root: workspace_root.to_path_buf(), |
| 317 | max_depth, |
| 318 | index_truncated: truncated, |
| 319 | rescan_query: None, |
| 320 | }; |
| 321 | view.refilter(); |
| 322 | view |
| 323 | } |
| 324 | |
| 325 | /// Drain the background scan if it has landed. Called from `tick`, which |
| 326 | /// the view stack runs on the top view every loop iteration. |
| 327 | fn poll_loading(&mut self) { |
| 328 | if !self.is_loading && !self.is_rescanning { |
| 329 | return; |
| 330 | } |
| 331 | // Take the Arc out temporarily to avoid a double-borrow of self. |
| 332 | let Some(cell) = self.loading_cell.take() else { |
| 333 | self.is_loading = false; |
| 334 | self.is_rescanning = false; |
| 335 | return; |
| 336 | }; |
| 337 | let scan = cell.lock().ok().and_then(|mut guard| guard.take()); |
| 338 | match scan { |
| 339 | Some(PickerScan::Initial(scan)) => { |
| 340 | self.candidates = scan.candidates; |
| 341 | self.index_truncated = scan.truncated; |
| 342 | for path in scan.modified { |
| 343 | self.relevance.mark_modified(path); |
| 344 | } |
| 345 | self.is_loading = false; |
| 346 | // The user may already have typed while the scan ran; refilter |
| 347 | // against the query they actually have, not an empty one. |
| 348 | self.refilter(); |
| 349 | } |
| 350 | Some(PickerScan::Targeted { query, hits }) => { |
| 351 | let current = self.query.trim().to_lowercase(); |
| 352 | self.is_rescanning = false; |
| 353 | if current == query { |
| 354 | self.merge_rescan_hits(&query, hits); |
| 355 | } else { |
| 356 | // Query moved on while the walk ran; try again for the |
| 357 | // query the user actually has. |
| 358 | self.maybe_rescan(); |
| 359 | } |
| 360 | } |
| 361 | None => self.loading_cell = Some(cell), |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | fn refilter(&mut self) { |
| 366 | self.refilter_from_index(); |
| 367 | self.maybe_rescan(); |
| 368 | } |
| 369 | |
| 370 | fn refilter_from_index(&mut self) { |
| 371 | let query = self.query.trim().to_lowercase(); |
| 372 | let mut scored: Vec<(usize, i32, i32, i32)> = if query.is_empty() { |
| 373 | self.candidates |
| 374 | .iter() |
| 375 | .enumerate() |
| 376 | .map(|(idx, path)| { |
| 377 | let boost = self.relevance.boost_for(path); |
| 378 | (idx, boost, 0, boost) |
| 379 | }) |
| 380 | .collect() |
| 381 | } else { |
| 382 | self.candidates |
| 383 | .iter() |
| 384 | .enumerate() |
| 385 | .filter_map(|(idx, path)| { |
| 386 | score(&query, path).map(|fuzzy| { |
| 387 | let boost = self.relevance.boost_for(path); |
| 388 | (idx, fuzzy + boost, fuzzy, boost) |
| 389 | }) |
| 390 | }) |
| 391 | .collect() |
| 392 | }; |
| 393 | |
| 394 | // Higher scores first; tie-break by ascending path length, then lex order |
| 395 | // so shorter / more central matches surface above deep nested ones. |
| 396 | scored.sort_by(|a, b| { |
| 397 | b.1.cmp(&a.1) |
| 398 | .then_with(|| b.2.cmp(&a.2)) |
| 399 | .then_with(|| b.3.cmp(&a.3)) |
| 400 | .then_with(|| self.candidates[a.0].len().cmp(&self.candidates[b.0].len())) |
| 401 | .then_with(|| self.candidates[a.0].cmp(&self.candidates[b.0])) |
| 402 | }); |
| 403 | |
| 404 | self.filtered = scored.into_iter().map(|(idx, _, _, _)| idx).collect(); |
| 405 | self.selected = self.selected.min(self.filtered.len().saturating_sub(1)); |
| 406 | self.adjust_scroll(); |
| 407 | } |
| 408 | |
| 409 | /// When the in-memory index is known-incomplete and the typed query |
| 410 | /// matches nothing in it, walk from the query's existing path prefix |
| 411 | /// (or the workspace root) collecting only matching files (#2488). |
| 412 | fn maybe_rescan(&mut self) { |
| 413 | if self.is_loading || self.is_rescanning || !self.index_truncated { |
| 414 | return; |
| 415 | } |
| 416 | if !self.filtered.is_empty() { |
| 417 | return; |
| 418 | } |
| 419 | let query = self.query.trim().to_lowercase(); |
| 420 | if query.is_empty() { |
| 421 | return; |
| 422 | } |
| 423 | // A single letter almost never misses a 20k index; require a bit |
| 424 | // more specificity so a stray miss does not walk a huge tree. |
| 425 | let specific_enough = |
| 426 | query.chars().count() >= 2 || query.contains('/') || query.contains('\\'); |
| 427 | if !specific_enough { |
| 428 | return; |
| 429 | } |
| 430 | if self.rescan_query.as_deref() == Some(query.as_str()) { |
| 431 | return; |
| 432 | } |
| 433 | |
| 434 | if tokio::runtime::Handle::try_current().is_err() { |
| 435 | let hits = collect_query_matches( |
| 436 | &self.workspace_root, |
| 437 | self.max_depth, |
| 438 | &query, |
| 439 | MAX_RESCAN_HITS, |
| 440 | ); |
| 441 | self.merge_rescan_hits(&query, hits); |
| 442 | return; |
| 443 | } |
| 444 | |
| 445 | self.is_rescanning = true; |
| 446 | let loading_cell = Arc::new(Mutex::new(None)); |
| 447 | let cell = loading_cell.clone(); |
| 448 | self.loading_cell = Some(loading_cell); |
| 449 | let root = self.workspace_root.clone(); |
| 450 | let max_depth = self.max_depth; |
| 451 | let query_for_scan = query.clone(); |
| 452 | codewhale_util::utils::spawn_blocking_supervised("file-picker-rescan", move || { |
| 453 | let hits = collect_query_matches(&root, max_depth, &query_for_scan, MAX_RESCAN_HITS); |
| 454 | if let Ok(mut guard) = cell.lock() { |
| 455 | *guard = Some(PickerScan::Targeted { |
| 456 | query: query_for_scan, |
| 457 | hits, |
| 458 | }); |
| 459 | } |
| 460 | }); |
| 461 | } |
| 462 | |
| 463 | fn merge_rescan_hits(&mut self, query: &str, hits: Vec<String>) { |
| 464 | self.rescan_query = Some(query.to_string()); |
| 465 | self.is_rescanning = false; |
| 466 | if !hits.is_empty() { |
| 467 | for hit in hits { |
| 468 | if !self.candidates.iter().any(|existing| existing == &hit) { |
| 469 | self.candidates.push(hit); |
| 470 | } |
| 471 | } |
| 472 | } |
| 473 | self.refilter_from_index(); |
| 474 | } |
| 475 | |
| 476 | fn adjust_scroll(&self) { |
| 477 | let rows = self.visible_rows.get(); |
| 478 | let earliest = self.selected.saturating_sub(rows - 1); |
| 479 | let scroll = self.scroll.get().clamp(earliest, self.selected); |
| 480 | let max_scroll = self.filtered.len().saturating_sub(rows); |
| 481 | self.scroll.set(scroll.min(max_scroll)); |
| 482 | } |
| 483 | |
| 484 | /// Apply one [`list_nav`](codewhale_tui_kit::list_nav) motion (#6290), returning |
| 485 | /// whether it was consumed. This is a typing surface, so only the |
| 486 | /// typing-safe vocabulary applies — no letter alias may eat a query |
| 487 | /// character. `Prev`/`Next` wrap; paging and Home/End clamp. |
| 488 | fn apply_motion(&mut self, motion: codewhale_tui_kit::list_nav::Motion) -> bool { |
| 489 | if self.filtered.is_empty() { |
| 490 | return false; |
| 491 | } |
| 492 | let Some(next) = codewhale_tui_kit::list_nav::apply( |
| 493 | self.selected, |
| 494 | self.filtered.len(), |
| 495 | self.visible_rows.get(), |
| 496 | motion, |
| 497 | ) else { |
| 498 | return false; |
| 499 | }; |
| 500 | self.selected = next; |
| 501 | self.adjust_scroll(); |
| 502 | true |
| 503 | } |
| 504 | |
| 505 | fn selected_path(&self) -> Option<&str> { |
| 506 | let idx = *self.filtered.get(self.selected)?; |
| 507 | self.candidates.get(idx).map(String::as_str) |
| 508 | } |
| 509 | |
| 510 | /// Visible candidate count for tests / diagnostics. |
| 511 | #[cfg(test)] |
| 512 | pub fn visible_count(&self) -> usize { |
| 513 | self.filtered.len() |
| 514 | } |
| 515 | |
| 516 | #[cfg(test)] |
| 517 | pub fn query(&self) -> &str { |
| 518 | &self.query |
| 519 | } |
| 520 | |
| 521 | #[cfg(test)] |
| 522 | pub fn selected_for_test(&self) -> Option<&str> { |
| 523 | self.selected_path() |
| 524 | } |
| 525 | |
| 526 | #[cfg(test)] |
| 527 | pub fn markers_for_test(&self, path: &str) -> String { |
| 528 | self.relevance.markers_for(path) |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | impl ModalView for FilePickerView { |
| 533 | fn kind(&self) -> ModalKind { |
| 534 | ModalKind::FilePicker |
| 535 | } |
| 536 | |
| 537 | fn as_any_mut(&mut self) -> &mut dyn std::any::Any { |
| 538 | self |
| 539 | } |
| 540 | |
| 541 | fn handle_key(&mut self, key: KeyEvent) -> ViewAction { |
| 542 | // Movement keys come from the shared vocabulary (#6290), typing-safe |
| 543 | // set only. This match owns the filter's own keys. |
| 544 | if let Some(motion) = codewhale_tui_kit::list_nav::motion_while_typing(&key) |
| 545 | && self.apply_motion(motion) |
| 546 | { |
| 547 | return ViewAction::None; |
| 548 | } |
| 549 | match key.code { |
| 550 | KeyCode::Esc => ViewAction::Close, |
| 551 | KeyCode::Enter => { |
| 552 | if let Some(path) = self.selected_path() { |
| 553 | let path = path.to_string(); |
| 554 | return ViewAction::EmitAndClose(ViewEvent::FilePickerSelected { path }); |
| 555 | } |
| 556 | ViewAction::Close |
| 557 | } |
| 558 | KeyCode::Backspace => { |
| 559 | self.query.pop(); |
| 560 | self.selected = 0; |
| 561 | self.refilter(); |
| 562 | ViewAction::None |
| 563 | } |
| 564 | KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => { |
| 565 | self.query.clear(); |
| 566 | self.selected = 0; |
| 567 | self.refilter(); |
| 568 | ViewAction::None |
| 569 | } |
| 570 | KeyCode::Char(ch) |
| 571 | if !key.modifiers.contains(KeyModifiers::CONTROL) |
| 572 | && !key.modifiers.contains(KeyModifiers::ALT) |
| 573 | && !ch.is_control() => |
| 574 | { |
| 575 | self.query.push(ch); |
| 576 | self.selected = 0; |
| 577 | self.refilter(); |
| 578 | ViewAction::None |
| 579 | } |
| 580 | _ => ViewAction::None, |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | fn handle_paste(&mut self, text: &str) -> bool { |
| 585 | let sanitized = text |
| 586 | .trim_end_matches(['\r', '\n']) |
| 587 | .replace("\r\n", "\n") |
| 588 | .replace(char::is_control, " "); |
| 589 | self.query.push_str(&sanitized); |
| 590 | self.selected = 0; |
| 591 | self.scroll.set(0); |
| 592 | self.refilter(); |
| 593 | true |
| 594 | } |
| 595 | |
| 596 | fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction { |
| 597 | match mouse.kind { |
| 598 | MouseEventKind::ScrollUp => { |
| 599 | self.apply_motion(codewhale_tui_kit::list_nav::Motion::Prev); |
| 600 | ViewAction::None |
| 601 | } |
| 602 | MouseEventKind::ScrollDown => { |
| 603 | self.apply_motion(codewhale_tui_kit::list_nav::Motion::Next); |
| 604 | ViewAction::None |
| 605 | } |
| 606 | MouseEventKind::Down(MouseButton::Left) => { |
| 607 | let hit = self |
| 608 | .last_row_hitboxes |
| 609 | .borrow() |
| 610 | .iter() |
| 611 | .find_map(|(y, idx)| (*y == mouse.row).then_some(*idx)); |
| 612 | let Some(idx) = hit else { |
| 613 | return ViewAction::None; |
| 614 | }; |
| 615 | if idx == self.selected { |
| 616 | if let Some(path) = self.selected_path() { |
| 617 | return ViewAction::EmitAndClose(ViewEvent::FilePickerSelected { |
| 618 | path: path.to_string(), |
| 619 | }); |
| 620 | } |
| 621 | } else { |
| 622 | self.selected = idx; |
| 623 | self.adjust_scroll(); |
| 624 | } |
| 625 | ViewAction::None |
| 626 | } |
| 627 | _ => ViewAction::None, |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | fn tick(&mut self) -> ViewAction { |
| 632 | self.poll_loading(); |
| 633 | ViewAction::None |
| 634 | } |
| 635 | |
| 636 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 637 | let match_count = self.filtered.len(); |
| 638 | let title = if match_count == 1 { |
| 639 | tr(self.locale, MessageId::FilePickerMatchSingular).into_owned() |
| 640 | } else { |
| 641 | tr(self.locale, MessageId::FilePickerMatchesPlural) |
| 642 | .replace("{count}", &match_count.to_string()) |
| 643 | }; |
| 644 | let meta = if self.is_loading || self.is_rescanning { |
| 645 | Some(tr(self.locale, MessageId::FilePickerScanning).into_owned()) |
| 646 | } else { |
| 647 | Some("@path".to_string()) |
| 648 | }; |
| 649 | let inner = render_rounded_surface(area, buf, title, meta, true); |
| 650 | |
| 651 | let content = render_rounded_footer( |
| 652 | inner, |
| 653 | buf, |
| 654 | &[ |
| 655 | ActionHint::new("↑/↓", "move"), |
| 656 | ActionHint::new("Enter", "insert @path"), |
| 657 | ActionHint::new("Esc", "cancel"), |
| 658 | ], |
| 659 | ); |
| 660 | let visible = VISIBLE_ROWS.min(usize::from(content.height.saturating_sub(2))); |
| 661 | self.visible_rows.set(visible.max(1)); |
| 662 | self.adjust_scroll(); |
| 663 | let scroll = self.scroll.get(); |
| 664 | let content = |
| 665 | render_panel_scroll_rail(content, buf, self.filtered.len(), scroll, visible, true); |
| 666 | |
| 667 | let ascii = crate::tui::color_compat::ascii_safe_enabled(); |
| 668 | let rule = if ascii { "-" } else { "─" }; |
| 669 | let mut lines: Vec<Line<'static>> = Vec::new(); |
| 670 | lines.push(Line::from(vec![ |
| 671 | Span::styled("> ", Style::default().fg(palette::WHALE_ACTION).bold()), |
| 672 | Span::styled( |
| 673 | self.query.clone(), |
| 674 | Style::default().fg(palette::TEXT_PRIMARY), |
| 675 | ), |
| 676 | Span::styled( |
| 677 | " ", |
| 678 | Style::default() |
| 679 | .fg(palette::COMPOSER_BG) |
| 680 | .bg(palette::WHALE_ACTION), |
| 681 | ), |
| 682 | ])); |
| 683 | lines.push(Line::from(Span::styled( |
| 684 | rule.repeat(usize::from(content.width)), |
| 685 | Style::default().fg(palette::BORDER_COLOR), |
| 686 | ))); |
| 687 | |
| 688 | let end = (scroll + visible).min(self.filtered.len()); |
| 689 | self.last_row_hitboxes.borrow_mut().clear(); |
| 690 | if self.is_loading || (self.is_rescanning && self.filtered.is_empty()) { |
| 691 | lines.push(Line::from(Span::styled( |
| 692 | format!(" {}", tr(self.locale, MessageId::FilePickerScanning)), |
| 693 | Style::default().fg(palette::TEXT_MUTED), |
| 694 | ))); |
| 695 | } else if self.filtered.is_empty() { |
| 696 | lines.push(Line::from(Span::styled( |
| 697 | " No matches", |
| 698 | Style::default().fg(palette::TEXT_MUTED), |
| 699 | ))); |
| 700 | } else { |
| 701 | let row_width = usize::from(content.width); |
| 702 | for idx in scroll..end { |
| 703 | let path = &self.candidates[self.filtered[idx]]; |
| 704 | let selected = idx == self.selected; |
| 705 | let prefix = format!("{} ", codewhale_tui_kit::glyphs::selection_marker(selected)); |
| 706 | let marker_field = if content.width >= 18 { |
| 707 | format!("{} ", self.relevance.markers_for(path)) |
| 708 | } else { |
| 709 | String::new() |
| 710 | }; |
| 711 | let reserved = prefix.chars().count() + marker_field.chars().count(); |
| 712 | let display = truncate_path(path, row_width.saturating_sub(reserved)); |
| 713 | let line = if selected { |
| 714 | let sel = menu_style::selected_row_style(); |
| 715 | pad_selected_line( |
| 716 | Line::from(Span::styled( |
| 717 | format!("{prefix}{marker_field}{display}"), |
| 718 | sel, |
| 719 | )), |
| 720 | row_width, |
| 721 | sel, |
| 722 | ) |
| 723 | } else { |
| 724 | let mut spans = vec![Span::styled( |
| 725 | prefix, |
| 726 | Style::default().fg(palette::TEXT_MUTED), |
| 727 | )]; |
| 728 | if !marker_field.is_empty() { |
| 729 | let marker_color = if marker_field.trim().is_empty() { |
| 730 | palette::TEXT_MUTED |
| 731 | } else { |
| 732 | palette::WHALE_LIVE |
| 733 | }; |
| 734 | spans.push(Span::styled( |
| 735 | marker_field, |
| 736 | Style::default().fg(marker_color), |
| 737 | )); |
| 738 | } |
| 739 | if let Some((dir, file)) = display.rsplit_once('/') { |
| 740 | spans.push(Span::styled( |
| 741 | format!("{dir}/"), |
| 742 | Style::default().fg(palette::TEXT_MUTED), |
| 743 | )); |
| 744 | spans.push(Span::styled( |
| 745 | file.to_string(), |
| 746 | Style::default().fg(palette::TEXT_PRIMARY), |
| 747 | )); |
| 748 | } else { |
| 749 | spans.push(Span::styled( |
| 750 | display, |
| 751 | Style::default().fg(palette::TEXT_PRIMARY), |
| 752 | )); |
| 753 | } |
| 754 | Line::from(spans) |
| 755 | }; |
| 756 | let y = content |
| 757 | .y |
| 758 | .saturating_add(u16::try_from(lines.len()).unwrap_or(u16::MAX)); |
| 759 | self.last_row_hitboxes.borrow_mut().push((y, idx)); |
| 760 | lines.push(line); |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | Paragraph::new(lines) |
| 765 | .style(Style::default().fg(palette::TEXT_PRIMARY)) |
| 766 | .render(content, buf); |
| 767 | } |
| 768 | } |
| 769 | |
| 770 | /// Keep the path's tail within `max` display cells, cutting only between |
| 771 | /// grapheme clusters: counting chars overflowed CJK rows and could split a |
| 772 | /// ZWJ or combining sequence (U07-06). ASCII output is unchanged. |
| 773 | fn truncate_path(path: &str, max: usize) -> String { |
| 774 | use unicode_segmentation::UnicodeSegmentation; |
| 775 | if max == 0 { |
| 776 | return String::new(); |
| 777 | } |
| 778 | if codewhale_tui_kit::ui_text::text_display_width(path) <= max { |
| 779 | return path.to_string(); |
| 780 | } |
| 781 | let budget = max.saturating_sub(1); |
| 782 | let mut used = 0usize; |
| 783 | let mut start = path.len(); |
| 784 | for (idx, grapheme) in path.grapheme_indices(true).rev() { |
| 785 | let width = codewhale_tui_kit::ui_text::text_display_width(grapheme); |
| 786 | if used + width > budget { |
| 787 | break; |
| 788 | } |
| 789 | used += width; |
| 790 | start = idx; |
| 791 | } |
| 792 | format!("…{}", &path[start..]) |
| 793 | } |
| 794 | |
| 795 | /// Single-pass walk that collects workspace-relative paths. `max_depth` of |
| 796 | /// `None` walks the whole tree (still bounded by `MAX_CANDIDATES` and |
| 797 | /// `.gitignore`); `Some(n)` caps the recursion at `n` levels. |
| 798 | #[cfg(test)] |
| 799 | fn collect_candidates(root: &Path, max_depth: Option<usize>) -> Vec<String> { |
| 800 | collect_candidates_limited(root, max_depth, MAX_CANDIDATES).paths |
| 801 | } |
| 802 | |
| 803 | fn collect_candidates_limited( |
| 804 | root: &Path, |
| 805 | max_depth: Option<usize>, |
| 806 | limit: usize, |
| 807 | ) -> CandidateWalk { |
| 808 | let mut out: Vec<String> = Vec::new(); |
| 809 | let mut truncated = push_matching_files( |
| 810 | MatchingFileWalk { |
| 811 | walk_root: root, |
| 812 | display_root: root, |
| 813 | max_depth, |
| 814 | honor_gitignore: true, |
| 815 | limit, |
| 816 | matches: &|_| true, |
| 817 | }, |
| 818 | &mut out, |
| 819 | None, |
| 820 | ); |
| 821 | if !truncated { |
| 822 | // Whitelist AI-tool dot-directories so they're discoverable even when |
| 823 | // gitignored. Walk each one separately with gitignore disabled. |
| 824 | for dir in DISCOVERY_ALWAYS_DIRS { |
| 825 | let dot_dir = root.join(dir); |
| 826 | if !dot_dir.is_dir() { |
| 827 | continue; |
| 828 | } |
| 829 | truncated = push_matching_files( |
| 830 | MatchingFileWalk { |
| 831 | walk_root: &dot_dir, |
| 832 | display_root: root, |
| 833 | max_depth: max_depth.map(|d| d.saturating_sub(1)), |
| 834 | honor_gitignore: false, |
| 835 | limit, |
| 836 | matches: &|_| true, |
| 837 | }, |
| 838 | &mut out, |
| 839 | None, |
| 840 | ); |
| 841 | if truncated { |
| 842 | break; |
| 843 | } |
| 844 | } |
| 845 | } |
| 846 | out.sort(); |
| 847 | CandidateWalk { |
| 848 | paths: out, |
| 849 | truncated, |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | /// Walk matching files for a query that missed the truncated index. |
| 854 | /// |
| 855 | /// Starts at the longest existing directory prefix of `query` so a typed path |
| 856 | /// like `packages/app/lib/room_chat_shell` does not re-walk the first 20k |
| 857 | /// files. The walk continues past [`MAX_CANDIDATES`]; only `limit` hits are |
| 858 | /// kept. |
| 859 | fn collect_query_matches( |
| 860 | root: &Path, |
| 861 | max_depth: Option<usize>, |
| 862 | query: &str, |
| 863 | limit: usize, |
| 864 | ) -> Vec<String> { |
| 865 | let query = query.trim(); |
| 866 | if query.is_empty() || limit == 0 { |
| 867 | return Vec::new(); |
| 868 | } |
| 869 | let needle = query.to_lowercase(); |
| 870 | let matches = |path: &str| score(&needle, path).is_some(); |
| 871 | let (start, depth) = targeted_walk_root(root, query, max_depth); |
| 872 | let mut out = Vec::new(); |
| 873 | let mut seen = HashSet::new(); |
| 874 | let under_always = always_dir_prefix(root, &start).is_some(); |
| 875 | let hit_cap = push_matching_files( |
| 876 | MatchingFileWalk { |
| 877 | walk_root: &start, |
| 878 | display_root: root, |
| 879 | max_depth: depth, |
| 880 | honor_gitignore: !under_always, |
| 881 | limit, |
| 882 | matches: &matches, |
| 883 | }, |
| 884 | &mut out, |
| 885 | Some(&mut seen), |
| 886 | ); |
| 887 | if start.as_path() == root && !hit_cap { |
| 888 | for dir in DISCOVERY_ALWAYS_DIRS { |
| 889 | let dot_dir = root.join(dir); |
| 890 | if !dot_dir.is_dir() { |
| 891 | continue; |
| 892 | } |
| 893 | if push_matching_files( |
| 894 | MatchingFileWalk { |
| 895 | walk_root: &dot_dir, |
| 896 | display_root: root, |
| 897 | max_depth: max_depth.map(|d| d.saturating_sub(1)), |
| 898 | honor_gitignore: false, |
| 899 | limit, |
| 900 | matches: &matches, |
| 901 | }, |
| 902 | &mut out, |
| 903 | Some(&mut seen), |
| 904 | ) { |
| 905 | break; |
| 906 | } |
| 907 | } |
| 908 | } |
| 909 | out.sort(); |
| 910 | out |
| 911 | } |
| 912 | |
| 913 | /// Longest existing directory prefix of `query` under `root`. Depth is |
| 914 | /// reduced by the number of consumed components so a targeted walk cannot |
| 915 | /// see farther than the original `mention_walk_depth` cap. |
| 916 | fn targeted_walk_root( |
| 917 | root: &Path, |
| 918 | query: &str, |
| 919 | max_depth: Option<usize>, |
| 920 | ) -> (PathBuf, Option<usize>) { |
| 921 | let normalized = query.replace('\\', "/"); |
| 922 | let mut dir = root.to_path_buf(); |
| 923 | let mut consumed = 0usize; |
| 924 | for component in normalized.split('/') { |
| 925 | if component.is_empty() || component == "." { |
| 926 | continue; |
| 927 | } |
| 928 | if component == ".." { |
| 929 | break; |
| 930 | } |
| 931 | let next = dir.join(component); |
| 932 | if next.is_dir() { |
| 933 | dir = next; |
| 934 | consumed += 1; |
| 935 | } else { |
| 936 | break; |
| 937 | } |
| 938 | } |
| 939 | (dir, max_depth.map(|depth| depth.saturating_sub(consumed))) |
| 940 | } |
| 941 | |
| 942 | fn always_dir_prefix(root: &Path, path: &Path) -> Option<&'static str> { |
| 943 | DISCOVERY_ALWAYS_DIRS.iter().copied().find(|dir| { |
| 944 | let always = root.join(dir); |
| 945 | path == always || path.starts_with(&always) |
| 946 | }) |
| 947 | } |
| 948 | |
| 949 | struct MatchingFileWalk<'a> { |
| 950 | walk_root: &'a Path, |
| 951 | display_root: &'a Path, |
| 952 | max_depth: Option<usize>, |
| 953 | honor_gitignore: bool, |
| 954 | limit: usize, |
| 955 | matches: &'a dyn Fn(&str) -> bool, |
| 956 | } |
| 957 | |
| 958 | fn push_matching_files( |
| 959 | walk: MatchingFileWalk<'_>, |
| 960 | out: &mut Vec<String>, |
| 961 | mut seen: Option<&mut HashSet<String>>, |
| 962 | ) -> bool { |
| 963 | let MatchingFileWalk { |
| 964 | walk_root, |
| 965 | display_root, |
| 966 | max_depth, |
| 967 | honor_gitignore, |
| 968 | limit, |
| 969 | matches, |
| 970 | } = walk; |
| 971 | if limit == 0 || out.len() >= limit { |
| 972 | return true; |
| 973 | } |
| 974 | let mut builder = WalkBuilder::new(walk_root); |
| 975 | builder |
| 976 | .hidden(true) |
| 977 | .follow_links(false) |
| 978 | .max_depth(max_depth); |
| 979 | if honor_gitignore { |
| 980 | builder.git_ignore(true).git_exclude(true).git_global(true); |
| 981 | } else { |
| 982 | builder.git_ignore(false).ignore(false); |
| 983 | } |
| 984 | |
| 985 | for entry in builder.build().flatten() { |
| 986 | if !honor_gitignore && path_is_excluded_from_discovery(display_root, entry.path()) { |
| 987 | continue; |
| 988 | } |
| 989 | if !entry.file_type().is_some_and(|ft| ft.is_file()) { |
| 990 | continue; |
| 991 | } |
| 992 | let path = entry.path(); |
| 993 | let rel = path.strip_prefix(display_root).unwrap_or(path); |
| 994 | // A pick becomes @-mention text that must resolve back to this file. |
| 995 | // A non-UTF-8 name cannot round-trip through text, and its lossy form |
| 996 | // can collide with another file's name, so it is not offered (U07-06). |
| 997 | if rel.as_os_str().is_empty() || rel.to_str().is_none() { |
| 998 | continue; |
| 999 | } |
| 1000 | let display = path_to_workspace_string(rel); |
| 1001 | if display.is_empty() || !matches(&display) { |
| 1002 | continue; |
| 1003 | } |
| 1004 | if let Some(seen) = seen.as_mut() |
| 1005 | && !seen.insert(display.clone()) |
| 1006 | { |
| 1007 | continue; |
| 1008 | } |
| 1009 | out.push(display); |
| 1010 | if out.len() >= limit { |
| 1011 | return true; |
| 1012 | } |
| 1013 | } |
| 1014 | false |
| 1015 | } |
| 1016 | |
| 1017 | fn path_to_workspace_string(path: &Path) -> String { |
| 1018 | // Use forward-slash separators for cross-platform display, matching how |
| 1019 | // @-mentions are spelled in the composer. |
| 1020 | let mut out = String::new(); |
| 1021 | for (idx, comp) in path.components().enumerate() { |
| 1022 | if idx > 0 { |
| 1023 | out.push('/'); |
| 1024 | } |
| 1025 | out.push_str(&comp.as_os_str().to_string_lossy()); |
| 1026 | } |
| 1027 | out |
| 1028 | } |
| 1029 | |
| 1030 | /// Subsequence scorer with first-letter and boundary bonuses. |
| 1031 | /// |
| 1032 | /// Returns `None` if `query` is not a subsequence of `path` (case-insensitive), |
| 1033 | /// otherwise a positive score where higher is better. |
| 1034 | /// |
| 1035 | /// Heuristics (kept deliberately small and predictable): |
| 1036 | /// * +25 for each match that lands at the start of the path or right after a |
| 1037 | /// boundary character (`/`, `_`, `-`, `.`, ` `). |
| 1038 | /// * +10 if the very first character of the query matches the first character |
| 1039 | /// of the path. |
| 1040 | /// * +5 per consecutive match (rewards contiguous runs like typing "main" and |
| 1041 | /// matching `main.rs`). |
| 1042 | /// * Penalty proportional to the gap between consecutive matches keeps tightly |
| 1043 | /// matched candidates above scattered ones. |
| 1044 | pub fn score(query: &str, path: &str) -> Option<i32> { |
| 1045 | if query.is_empty() { |
| 1046 | return Some(0); |
| 1047 | } |
| 1048 | let q: Vec<char> = query.chars().flat_map(char::to_lowercase).collect(); |
| 1049 | let p: Vec<char> = path.chars().flat_map(char::to_lowercase).collect(); |
| 1050 | if q.len() > p.len() { |
| 1051 | return None; |
| 1052 | } |
| 1053 | |
| 1054 | let mut qi = 0usize; |
| 1055 | let mut score: i32 = 0; |
| 1056 | let mut last_match: Option<usize> = None; |
| 1057 | let mut consecutive = 0i32; |
| 1058 | |
| 1059 | for (i, ch) in p.iter().enumerate() { |
| 1060 | if qi >= q.len() { |
| 1061 | break; |
| 1062 | } |
| 1063 | if *ch == q[qi] { |
| 1064 | // Boundary / start bonus. |
| 1065 | if i == 0 { |
| 1066 | score += 25; |
| 1067 | if qi == 0 { |
| 1068 | score += 10; |
| 1069 | } |
| 1070 | } else if matches!(p[i - 1], '/' | '_' | '-' | '.' | ' ') { |
| 1071 | score += 25; |
| 1072 | } else { |
| 1073 | score += 1; |
| 1074 | } |
| 1075 | |
| 1076 | // Consecutive bonus. |
| 1077 | if last_match == Some(i.saturating_sub(1)) { |
| 1078 | consecutive += 1; |
| 1079 | score += 5 * consecutive; |
| 1080 | } else { |
| 1081 | consecutive = 0; |
| 1082 | } |
| 1083 | |
| 1084 | // Gap penalty. |
| 1085 | if let Some(prev) = last_match { |
| 1086 | let gap = i - prev - 1; |
| 1087 | score -= gap as i32; |
| 1088 | } |
| 1089 | |
| 1090 | last_match = Some(i); |
| 1091 | qi += 1; |
| 1092 | } |
| 1093 | } |
| 1094 | |
| 1095 | if qi == q.len() { Some(score) } else { None } |
| 1096 | } |
| 1097 | |
| 1098 | #[cfg(test)] |
| 1099 | mod tests { |
| 1100 | use super::*; |
| 1101 | use std::fs; |
| 1102 | use std::time::Duration; |
| 1103 | use tempfile::TempDir; |
| 1104 | |
| 1105 | #[test] |
| 1106 | fn score_subsequence_match() { |
| 1107 | // Identical query matches start with high bonus. |
| 1108 | let a = score("main", "main.rs").unwrap(); |
| 1109 | let b = score("main", "src/very/deep/main.rs").unwrap(); |
| 1110 | assert!(a > b, "a={a} b={b}"); |
| 1111 | } |
| 1112 | |
| 1113 | #[test] |
| 1114 | fn score_rejects_non_subsequence() { |
| 1115 | assert!(score("zzz", "main.rs").is_none()); |
| 1116 | assert!(score("xyz", "src/lib.rs").is_none()); |
| 1117 | } |
| 1118 | |
| 1119 | #[test] |
| 1120 | fn query_line_carries_explicit_ink_on_the_dark_surface() { |
| 1121 | let dir = TempDir::new().expect("tempdir"); |
| 1122 | let mut picker = |
| 1123 | FilePickerView::new_with_relevance(dir.path(), FilePickerRelevance::default()); |
| 1124 | picker.query = "main".to_string(); |
| 1125 | let area = Rect::new(0, 0, 80, 20); |
| 1126 | let mut buf = Buffer::empty(area); |
| 1127 | picker.render(area, &mut buf); |
| 1128 | let mut checked = 0; |
| 1129 | for y in 0..area.height { |
| 1130 | let mut row = String::new(); |
| 1131 | for x in 0..area.width { |
| 1132 | row.push_str(buf[(x, y)].symbol()); |
| 1133 | } |
| 1134 | if !row.contains("> main") { |
| 1135 | continue; |
| 1136 | } |
| 1137 | for x in 0..area.width { |
| 1138 | let cell = &buf[(x, y)]; |
| 1139 | let symbol = cell.symbol(); |
| 1140 | if symbol.trim().is_empty() || matches!(symbol, ">" | "│" | "|") { |
| 1141 | continue; |
| 1142 | } |
| 1143 | assert_eq!( |
| 1144 | cell.style().fg, |
| 1145 | Some(palette::TEXT_PRIMARY), |
| 1146 | "query cell ({x}, {y}) must carry explicit body ink", |
| 1147 | ); |
| 1148 | checked += 1; |
| 1149 | } |
| 1150 | } |
| 1151 | assert!(checked > 0, "expected a rendered query line"); |
| 1152 | } |
| 1153 | |
| 1154 | #[test] |
| 1155 | fn score_boundary_bonus_beats_substring() { |
| 1156 | // "fp" matches the boundary letters in "file_picker.rs" but only the |
| 1157 | // first letter in "filepicker.rs" — so the boundary candidate should |
| 1158 | // win. |
| 1159 | let boundary = score("fp", "src/file_picker.rs").unwrap(); |
| 1160 | let inline = score("fp", "src/filepicker.rs"); |
| 1161 | // inline doesn't even contain 'p' immediately following 'f'? It does: |
| 1162 | // f-i-l-e-p-i-c-k-e-r — 'p' is preceded by 'e' (no boundary), so it |
| 1163 | // gets only the +1 path score, while boundary gets +25 for the 'p' |
| 1164 | // following the underscore. |
| 1165 | if let Some(inline_score) = inline { |
| 1166 | assert!( |
| 1167 | boundary > inline_score, |
| 1168 | "boundary={boundary} inline={inline_score}" |
| 1169 | ); |
| 1170 | } |
| 1171 | } |
| 1172 | |
| 1173 | #[test] |
| 1174 | fn score_case_insensitive() { |
| 1175 | assert!(score("MAIN", "main.rs").is_some()); |
| 1176 | assert!(score("main", "MAIN.RS").is_some()); |
| 1177 | } |
| 1178 | |
| 1179 | #[test] |
| 1180 | fn score_empty_query_returns_zero() { |
| 1181 | assert_eq!(score("", "anything").unwrap(), 0); |
| 1182 | } |
| 1183 | |
| 1184 | #[test] |
| 1185 | fn picker_typing_narrows_candidates() { |
| 1186 | let dir = TempDir::new().expect("tempdir"); |
| 1187 | let root = dir.path(); |
| 1188 | fs::create_dir_all(root.join("src")).unwrap(); |
| 1189 | fs::write(root.join("src/main.rs"), "").unwrap(); |
| 1190 | fs::write(root.join("src/lib.rs"), "").unwrap(); |
| 1191 | fs::write(root.join("README.md"), "").unwrap(); |
| 1192 | fs::write(root.join("Cargo.toml"), "").unwrap(); |
| 1193 | |
| 1194 | let mut view = FilePickerView::new_with_relevance(root, FilePickerRelevance::default()); |
| 1195 | // Empty query -> all 4 files visible. |
| 1196 | assert_eq!(view.visible_count(), 4, "expected all 4 candidates"); |
| 1197 | |
| 1198 | // Typing "main" should narrow to just src/main.rs. |
| 1199 | for ch in "main".chars() { |
| 1200 | view.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)); |
| 1201 | } |
| 1202 | assert_eq!(view.query(), "main"); |
| 1203 | let visible = view.visible_count(); |
| 1204 | assert_eq!(visible, 1, "expected exactly 1 match for 'main'"); |
| 1205 | let selected = view.selected_for_test().expect("selected path"); |
| 1206 | assert!(selected.ends_with("main.rs"), "selected = {selected}"); |
| 1207 | } |
| 1208 | |
| 1209 | #[test] |
| 1210 | fn picker_empty_query_prioritizes_working_set_files() { |
| 1211 | let dir = TempDir::new().expect("tempdir"); |
| 1212 | let root = dir.path(); |
| 1213 | fs::create_dir_all(root.join("src")).unwrap(); |
| 1214 | fs::write(root.join("src/main.rs"), "").unwrap(); |
| 1215 | fs::write(root.join("src/lib.rs"), "").unwrap(); |
| 1216 | fs::write(root.join("README.md"), "").unwrap(); |
| 1217 | |
| 1218 | let mut relevance = FilePickerRelevance::default(); |
| 1219 | relevance.mark_modified("src/lib.rs"); |
| 1220 | let view = FilePickerView::new_with_relevance(root, relevance); |
| 1221 | |
| 1222 | assert_eq!(view.selected_for_test(), Some("src/lib.rs")); |
| 1223 | assert_eq!(view.markers_for_test("src/lib.rs"), "M "); |
| 1224 | } |
| 1225 | |
| 1226 | #[test] |
| 1227 | fn picker_fuzzy_query_keeps_working_set_boosts() { |
| 1228 | let dir = TempDir::new().expect("tempdir"); |
| 1229 | let root = dir.path(); |
| 1230 | fs::create_dir_all(root.join("src")).unwrap(); |
| 1231 | fs::write(root.join("src/alpha.rs"), "").unwrap(); |
| 1232 | fs::write(root.join("src/zeta.rs"), "").unwrap(); |
| 1233 | |
| 1234 | let mut relevance = FilePickerRelevance::default(); |
| 1235 | relevance.mark_mentioned("src/zeta.rs"); |
| 1236 | relevance.mark_tool("src/zeta.rs"); |
| 1237 | let mut view = FilePickerView::new_with_relevance(root, relevance); |
| 1238 | for ch in "rs".chars() { |
| 1239 | view.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)); |
| 1240 | } |
| 1241 | |
| 1242 | assert_eq!(view.selected_for_test(), Some("src/zeta.rs")); |
| 1243 | assert_eq!(view.markers_for_test("src/zeta.rs"), " @T"); |
| 1244 | } |
| 1245 | |
| 1246 | #[test] |
| 1247 | fn picker_backspace_widens_candidates() { |
| 1248 | let dir = TempDir::new().expect("tempdir"); |
| 1249 | let root = dir.path(); |
| 1250 | fs::write(root.join("a.txt"), "").unwrap(); |
| 1251 | fs::write(root.join("b.txt"), "").unwrap(); |
| 1252 | |
| 1253 | let mut view = FilePickerView::new_with_relevance(root, FilePickerRelevance::default()); |
| 1254 | view.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); |
| 1255 | assert_eq!(view.visible_count(), 1); |
| 1256 | view.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); |
| 1257 | assert_eq!(view.visible_count(), 2); |
| 1258 | } |
| 1259 | |
| 1260 | #[test] |
| 1261 | fn picker_enter_emits_event() { |
| 1262 | let dir = TempDir::new().expect("tempdir"); |
| 1263 | let root = dir.path(); |
| 1264 | fs::write(root.join("only.txt"), "").unwrap(); |
| 1265 | |
| 1266 | let mut view = FilePickerView::new_with_relevance(root, FilePickerRelevance::default()); |
| 1267 | let action = view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); |
| 1268 | match action { |
| 1269 | ViewAction::EmitAndClose(ViewEvent::FilePickerSelected { path }) => { |
| 1270 | assert!(path.ends_with("only.txt")); |
| 1271 | } |
| 1272 | other => panic!("expected EmitAndClose(FilePickerSelected), got {other:?}"), |
| 1273 | } |
| 1274 | } |
| 1275 | |
| 1276 | #[test] |
| 1277 | fn picker_esc_closes_without_emit() { |
| 1278 | let dir = TempDir::new().expect("tempdir"); |
| 1279 | let root = dir.path(); |
| 1280 | fs::write(root.join("only.txt"), "").unwrap(); |
| 1281 | |
| 1282 | let mut view = FilePickerView::new_with_relevance(root, FilePickerRelevance::default()); |
| 1283 | let action = view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); |
| 1284 | assert!(matches!(action, ViewAction::Close)); |
| 1285 | } |
| 1286 | |
| 1287 | #[test] |
| 1288 | fn picker_honors_gitignore() { |
| 1289 | let dir = TempDir::new().expect("tempdir"); |
| 1290 | let root = dir.path(); |
| 1291 | // .gitignore filtering only kicks in inside a git repo or with an |
| 1292 | // explicit `.ignore` file. Use `.ignore` which `WalkBuilder` honors |
| 1293 | // even outside of git. |
| 1294 | fs::write(root.join(".ignore"), "skipme.txt\n").unwrap(); |
| 1295 | fs::write(root.join("keepme.txt"), "").unwrap(); |
| 1296 | fs::write(root.join("skipme.txt"), "").unwrap(); |
| 1297 | |
| 1298 | let view = FilePickerView::new_with_relevance(root, FilePickerRelevance::default()); |
| 1299 | let visible: Vec<_> = view |
| 1300 | .filtered |
| 1301 | .iter() |
| 1302 | .map(|i| view.candidates[*i].as_str()) |
| 1303 | .collect(); |
| 1304 | assert!(visible.iter().any(|p| p.ends_with("keepme.txt"))); |
| 1305 | assert!( |
| 1306 | !visible.iter().any(|p| p.ends_with("skipme.txt")), |
| 1307 | "skipme.txt should be filtered by .ignore: {visible:?}" |
| 1308 | ); |
| 1309 | } |
| 1310 | |
| 1311 | #[test] |
| 1312 | fn picker_finds_deeply_nested_files_within_walk_depth() { |
| 1313 | // #2488: a file inside a 6-level-deep directory sits at component depth |
| 1314 | // 7 and was excluded by the old depth-6 cap. The default depth (10) now |
| 1315 | // reaches it, and `0` (unlimited) reaches arbitrarily deep files. |
| 1316 | let dir = TempDir::new().expect("tempdir"); |
| 1317 | let root = dir.path(); |
| 1318 | let nested = root.join("a/b/c/d/e/f"); |
| 1319 | fs::create_dir_all(&nested).unwrap(); |
| 1320 | fs::write(nested.join("deep.rs"), "deep").unwrap(); |
| 1321 | let deeper = root.join("a/b/c/d/e/f/g/h/i/j/k"); |
| 1322 | fs::create_dir_all(&deeper).unwrap(); |
| 1323 | fs::write(deeper.join("very_deep.rs"), "deeper").unwrap(); |
| 1324 | |
| 1325 | // The old default (6) misses the depth-7 file — the reported bug. |
| 1326 | let shallow = collect_candidates(root, Some(6)); |
| 1327 | assert!( |
| 1328 | !shallow.iter().any(|p| p == "a/b/c/d/e/f/deep.rs"), |
| 1329 | "depth-6 cap should miss the depth-7 file: {shallow:?}" |
| 1330 | ); |
| 1331 | |
| 1332 | // The new default reaches files inside a 6-level-deep directory. |
| 1333 | let default = collect_candidates(root, Some(WALK_DEPTH)); |
| 1334 | assert!( |
| 1335 | default.iter().any(|p| p == "a/b/c/d/e/f/deep.rs"), |
| 1336 | "default walk depth should reach depth-7 files: {default:?}" |
| 1337 | ); |
| 1338 | |
| 1339 | // Unlimited (mention_walk_depth = 0) reaches arbitrarily deep files. |
| 1340 | let unlimited = collect_candidates(root, None); |
| 1341 | assert!( |
| 1342 | unlimited |
| 1343 | .iter() |
| 1344 | .any(|p| p == "a/b/c/d/e/f/g/h/i/j/k/very_deep.rs"), |
| 1345 | "unlimited walk should reach very deep files: {unlimited:?}" |
| 1346 | ); |
| 1347 | } |
| 1348 | |
| 1349 | #[test] |
| 1350 | fn picker_skips_generated_worktree_bulk_inside_unignored_dot_dirs() { |
| 1351 | let dir = TempDir::new().expect("tempdir"); |
| 1352 | let root = dir.path(); |
| 1353 | fs::create_dir_all(root.join("src")).unwrap(); |
| 1354 | fs::write(root.join("src/main.rs"), "fn main() {}").unwrap(); |
| 1355 | |
| 1356 | fs::create_dir_all(root.join(".deepseek/commands")).unwrap(); |
| 1357 | fs::write(root.join(".deepseek/commands/build.md"), "build").unwrap(); |
| 1358 | fs::create_dir_all(root.join(".deepseek/snapshots/deadbeef/.git/objects")).unwrap(); |
| 1359 | fs::write( |
| 1360 | root.join(".deepseek/snapshots/deadbeef/.git/objects/snapshot.pack"), |
| 1361 | "pack", |
| 1362 | ) |
| 1363 | .unwrap(); |
| 1364 | |
| 1365 | fs::create_dir_all(root.join(".claude/commands")).unwrap(); |
| 1366 | fs::write(root.join(".claude/commands/test.md"), "test").unwrap(); |
| 1367 | fs::create_dir_all(root.join(".claude/worktrees/agent/src")).unwrap(); |
| 1368 | fs::write( |
| 1369 | root.join(".claude/worktrees/agent/src/agent-only.md"), |
| 1370 | "agent", |
| 1371 | ) |
| 1372 | .unwrap(); |
| 1373 | |
| 1374 | let candidates = collect_candidates(root, Some(WALK_DEPTH)); |
| 1375 | |
| 1376 | assert!(candidates.iter().any(|path| path == "src/main.rs")); |
| 1377 | assert!( |
| 1378 | candidates |
| 1379 | .iter() |
| 1380 | .any(|path| path == ".deepseek/commands/build.md"), |
| 1381 | "normal .deepseek command files should stay discoverable: {candidates:?}", |
| 1382 | ); |
| 1383 | assert!( |
| 1384 | candidates |
| 1385 | .iter() |
| 1386 | .any(|path| path == ".claude/commands/test.md"), |
| 1387 | "normal .claude command files should stay discoverable: {candidates:?}", |
| 1388 | ); |
| 1389 | assert!( |
| 1390 | candidates |
| 1391 | .iter() |
| 1392 | .all(|path| !path.starts_with(".deepseek/snapshots/")), |
| 1393 | "snapshot side repo files must not enter picker candidates: {candidates:?}", |
| 1394 | ); |
| 1395 | assert!( |
| 1396 | candidates |
| 1397 | .iter() |
| 1398 | .all(|path| !path.starts_with(".claude/worktrees/")), |
| 1399 | ".claude worktree files must not enter picker candidates: {candidates:?}", |
| 1400 | ); |
| 1401 | } |
| 1402 | |
| 1403 | #[test] |
| 1404 | fn collect_candidates_limited_stops_at_the_cap_and_flags_truncation() { |
| 1405 | let dir = TempDir::new().expect("tempdir"); |
| 1406 | let root = dir.path(); |
| 1407 | fs::create_dir_all(root.join("pad")).unwrap(); |
| 1408 | for i in 0..30 { |
| 1409 | fs::write(root.join("pad").join(format!("n{i:02}.txt")), "").unwrap(); |
| 1410 | } |
| 1411 | |
| 1412 | let walk = collect_candidates_limited(root, Some(WALK_DEPTH), 12); |
| 1413 | assert!( |
| 1414 | walk.truncated, |
| 1415 | "hitting the cap must mark the index incomplete" |
| 1416 | ); |
| 1417 | assert_eq!(walk.paths.len(), 12); |
| 1418 | assert!( |
| 1419 | !collect_candidates_limited(root, Some(WALK_DEPTH), 64).truncated, |
| 1420 | "a cap above the file count is a complete index" |
| 1421 | ); |
| 1422 | } |
| 1423 | |
| 1424 | #[test] |
| 1425 | fn targeted_rescan_finds_a_file_the_candidate_cap_dropped() { |
| 1426 | // #2488: the opening walk keeps the first N files in walk order. A |
| 1427 | // later unique file must still be reachable once the user types it. |
| 1428 | let dir = TempDir::new().expect("tempdir"); |
| 1429 | let root = dir.path(); |
| 1430 | fs::create_dir_all(root.join("pad")).unwrap(); |
| 1431 | for i in 0..40 { |
| 1432 | fs::write(root.join("pad").join(format!("n{i:02}.txt")), "").unwrap(); |
| 1433 | } |
| 1434 | fs::create_dir_all(root.join("zzz")).unwrap(); |
| 1435 | fs::write(root.join("zzz/room_chat_shell.dart"), "late").unwrap(); |
| 1436 | |
| 1437 | let walk = collect_candidates_limited(root, Some(WALK_DEPTH), 15); |
| 1438 | assert!(walk.truncated); |
| 1439 | let hits = collect_query_matches(root, Some(WALK_DEPTH), "room_chat_shell", 64); |
| 1440 | assert!( |
| 1441 | hits.iter().any(|path| path == "zzz/room_chat_shell.dart"), |
| 1442 | "targeted rescan must recover the file past the cap: {hits:?}" |
| 1443 | ); |
| 1444 | } |
| 1445 | |
| 1446 | #[test] |
| 1447 | fn targeted_walk_root_descends_into_an_existing_prefix() { |
| 1448 | let dir = TempDir::new().expect("tempdir"); |
| 1449 | let root = dir.path(); |
| 1450 | fs::create_dir_all(root.join("src/nested")).unwrap(); |
| 1451 | fs::write(root.join("src/nested/hit.rs"), "").unwrap(); |
| 1452 | let (start, depth) = targeted_walk_root(root, "src/nested/hit", Some(10)); |
| 1453 | assert_eq!(start, root.join("src/nested")); |
| 1454 | assert_eq!(depth, Some(8)); |
| 1455 | } |
| 1456 | |
| 1457 | #[test] |
| 1458 | fn picker_query_miss_rescans_a_truncated_index() { |
| 1459 | let dir = TempDir::new().expect("tempdir"); |
| 1460 | let root = dir.path(); |
| 1461 | fs::create_dir_all(root.join("zzz")).unwrap(); |
| 1462 | fs::write(root.join("zzz/room_chat_shell.dart"), "late").unwrap(); |
| 1463 | |
| 1464 | let mut view = FilePickerView::from_preloaded( |
| 1465 | root, |
| 1466 | vec!["pad/n00.txt".into(), "pad/n01.txt".into()], |
| 1467 | true, |
| 1468 | Some(WALK_DEPTH), |
| 1469 | ); |
| 1470 | assert_eq!( |
| 1471 | view.visible_count(), |
| 1472 | 2, |
| 1473 | "empty query shows the truncated index" |
| 1474 | ); |
| 1475 | |
| 1476 | for ch in "room_chat_shell".chars() { |
| 1477 | view.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)); |
| 1478 | } |
| 1479 | assert_eq!( |
| 1480 | view.selected_for_test(), |
| 1481 | Some("zzz/room_chat_shell.dart"), |
| 1482 | "a miss against the truncated index must rescan and surface the file" |
| 1483 | ); |
| 1484 | } |
| 1485 | |
| 1486 | #[test] |
| 1487 | fn picker_complete_index_miss_does_not_rescan() { |
| 1488 | let dir = TempDir::new().expect("tempdir"); |
| 1489 | let root = dir.path(); |
| 1490 | fs::write(root.join("keep.txt"), "").unwrap(); |
| 1491 | // A file on disk that is not in the (complete) index must stay |
| 1492 | // invisible — a complete walk already saw the whole tree. |
| 1493 | fs::write(root.join("secret.txt"), "").unwrap(); |
| 1494 | |
| 1495 | let mut view = |
| 1496 | FilePickerView::from_preloaded(root, vec!["keep.txt".into()], false, Some(WALK_DEPTH)); |
| 1497 | for ch in "secret".chars() { |
| 1498 | view.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)); |
| 1499 | } |
| 1500 | assert_eq!(view.visible_count(), 0); |
| 1501 | assert_eq!(view.candidates, vec!["keep.txt".to_string()]); |
| 1502 | } |
| 1503 | |
| 1504 | /// The four terminal sizes the v0.8.66 modal blocker (#3732) requires |
| 1505 | /// every overlay to remain readable and fully operable at. |
| 1506 | const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)]; |
| 1507 | |
| 1508 | #[test] |
| 1509 | fn file_picker_scrolls_and_pages_by_its_rendered_height() { |
| 1510 | let paths = (1..=30) |
| 1511 | .map(|index| format!("file-{index:02}.txt")) |
| 1512 | .collect(); |
| 1513 | let mut picker = FilePickerView::from_preloaded(Path::new("."), paths, false, None); |
| 1514 | let render_rows = |view: &FilePickerView, height| { |
| 1515 | let area = Rect::new(0, 0, 60, height); |
| 1516 | view.render(area, &mut Buffer::empty(area)); |
| 1517 | view.last_row_hitboxes |
| 1518 | .borrow() |
| 1519 | .iter() |
| 1520 | .map(|&(_, index)| index) |
| 1521 | .collect::<Vec<_>>() |
| 1522 | }; |
| 1523 | |
| 1524 | let first_page = render_rows(&picker, 16); |
| 1525 | assert!(!first_page.is_empty() && first_page.len() < VISIBLE_ROWS); |
| 1526 | picker.handle_key(KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE)); |
| 1527 | assert_eq!(picker.selected, first_page.len()); |
| 1528 | assert!(render_rows(&picker, 16).contains(&picker.selected)); |
| 1529 | |
| 1530 | picker.handle_key(KeyEvent::new(KeyCode::End, KeyModifiers::NONE)); |
| 1531 | for height in [16, 12, 32] { |
| 1532 | let rows = render_rows(&picker, height); |
| 1533 | assert_eq!(rows.last(), Some(&29), "viewport at height {height}"); |
| 1534 | if height == 32 { |
| 1535 | assert_eq!(rows.len(), VISIBLE_ROWS); |
| 1536 | } |
| 1537 | } |
| 1538 | assert_eq!(picker.selected_path(), Some("file-30.txt")); |
| 1539 | } |
| 1540 | |
| 1541 | #[test] |
| 1542 | fn file_picker_is_usable_and_opaque_at_blocker_sizes() { |
| 1543 | use crate::tui::views::ViewStack; |
| 1544 | use ratatui::{buffer::Buffer, layout::Rect}; |
| 1545 | use unicode_width::UnicodeWidthStr; |
| 1546 | |
| 1547 | let dir = TempDir::new().expect("tempdir"); |
| 1548 | let root = dir.path(); |
| 1549 | fs::create_dir_all(root.join("src")).unwrap(); |
| 1550 | fs::write(root.join("src/main.rs"), "").unwrap(); |
| 1551 | fs::write(root.join("src/lib.rs"), "").unwrap(); |
| 1552 | fs::write(root.join("README.md"), "").unwrap(); |
| 1553 | |
| 1554 | for (w, h) in BLOCKER_SIZES { |
| 1555 | let area = Rect::new(0, 0, w, h); |
| 1556 | let mut buf = Buffer::empty(area); |
| 1557 | for y in 0..h { |
| 1558 | for x in 0..w { |
| 1559 | buf[(x, y)].set_symbol("X"); |
| 1560 | } |
| 1561 | } |
| 1562 | let mut stack = ViewStack::new(); |
| 1563 | stack.push(FilePickerView::new_with_relevance( |
| 1564 | root, |
| 1565 | FilePickerRelevance::default(), |
| 1566 | )); |
| 1567 | stack.render(area, &mut buf); |
| 1568 | |
| 1569 | let rows: Vec<String> = (0..h) |
| 1570 | .map(|y| { |
| 1571 | (0..w) |
| 1572 | .map(|x| buf[(x, y)].symbol().to_string()) |
| 1573 | .collect::<String>() |
| 1574 | }) |
| 1575 | .collect(); |
| 1576 | let text = rows.join("\n"); |
| 1577 | |
| 1578 | for label in ["move", "insert @path", "cancel"] { |
| 1579 | assert!(text.contains(label), "{w}x{h}: missing footer '{label}'"); |
| 1580 | } |
| 1581 | assert!( |
| 1582 | !text.contains('X'), |
| 1583 | "{w}x{h}: background bleed-through into modal surface" |
| 1584 | ); |
| 1585 | assert_eq!( |
| 1586 | buf[(w / 2, h / 2)].bg, |
| 1587 | palette::COMPOSER_BG, |
| 1588 | "{w}x{h}: modal interior must be opaque" |
| 1589 | ); |
| 1590 | for (y, row) in rows.iter().enumerate() { |
| 1591 | assert!( |
| 1592 | UnicodeWidthStr::width(row.trim_end()) <= w as usize, |
| 1593 | "{w}x{h}: row {y} overflows width: {row:?}" |
| 1594 | ); |
| 1595 | } |
| 1596 | } |
| 1597 | } |
| 1598 | |
| 1599 | /// #3905: opening the picker used to block the event loop on a `git status` |
| 1600 | /// subprocess plus a walk of up to MAX_CANDIDATES paths, freezing the whole |
| 1601 | /// TUI between Ctrl+P and the picker appearing. |
| 1602 | /// |
| 1603 | /// Asserting "fast" by wall clock would be a flaky proxy for the real |
| 1604 | /// contract, so this asserts the structural property instead: inside a |
| 1605 | /// runtime the constructor returns a paintable view that has not yet done |
| 1606 | /// the scan, and the results arrive later through `tick`. |
| 1607 | #[tokio::test] |
| 1608 | async fn opening_the_picker_does_not_block_on_the_workspace_scan() { |
| 1609 | let ws = TempDir::new().unwrap(); |
| 1610 | fs::create_dir_all(ws.path().join("src")).unwrap(); |
| 1611 | for i in 0..200 { |
| 1612 | fs::write(ws.path().join("src").join(format!("f{i}.rs")), "x").unwrap(); |
| 1613 | } |
| 1614 | |
| 1615 | let mut view = FilePickerView::new_with_relevance_and_depth( |
| 1616 | ws.path(), |
| 1617 | FilePickerRelevance::default(), |
| 1618 | WALK_DEPTH, |
| 1619 | Locale::En, |
| 1620 | ); |
| 1621 | |
| 1622 | assert!( |
| 1623 | view.is_loading, |
| 1624 | "the constructor must hand back a paintable view, not a finished scan" |
| 1625 | ); |
| 1626 | assert!( |
| 1627 | view.candidates.is_empty(), |
| 1628 | "no walk may have run on the calling thread" |
| 1629 | ); |
| 1630 | |
| 1631 | // The view is renderable in the loading state — this is the frame the |
| 1632 | // user sees immediately after Ctrl+P. |
| 1633 | let area = Rect::new(0, 0, 60, 20); |
| 1634 | let mut buf = Buffer::empty(area); |
| 1635 | view.render(area, &mut buf); |
| 1636 | |
| 1637 | for _ in 0..500 { |
| 1638 | view.tick(); |
| 1639 | if !view.is_loading { |
| 1640 | break; |
| 1641 | } |
| 1642 | tokio::time::sleep(Duration::from_millis(5)).await; |
| 1643 | } |
| 1644 | |
| 1645 | assert!(!view.is_loading, "the background scan must land via tick"); |
| 1646 | assert_eq!( |
| 1647 | view.candidates.len(), |
| 1648 | 200, |
| 1649 | "every workspace file is discovered once the scan lands" |
| 1650 | ); |
| 1651 | assert_eq!( |
| 1652 | view.filtered.len(), |
| 1653 | 200, |
| 1654 | "results are refiltered after the scan, not left empty" |
| 1655 | ); |
| 1656 | } |
| 1657 | |
| 1658 | /// A query typed while the scan was still running must survive it. |
| 1659 | #[tokio::test] |
| 1660 | async fn a_query_typed_during_the_scan_is_applied_when_results_land() { |
| 1661 | let ws = TempDir::new().unwrap(); |
| 1662 | fs::write(ws.path().join("alpha.rs"), "x").unwrap(); |
| 1663 | fs::write(ws.path().join("beta.rs"), "x").unwrap(); |
| 1664 | |
| 1665 | let mut view = FilePickerView::new_with_relevance_and_depth( |
| 1666 | ws.path(), |
| 1667 | FilePickerRelevance::default(), |
| 1668 | WALK_DEPTH, |
| 1669 | Locale::En, |
| 1670 | ); |
| 1671 | assert!(view.is_loading); |
| 1672 | |
| 1673 | for ch in "alpha".chars() { |
| 1674 | view.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)); |
| 1675 | } |
| 1676 | |
| 1677 | for _ in 0..500 { |
| 1678 | view.tick(); |
| 1679 | if !view.is_loading { |
| 1680 | break; |
| 1681 | } |
| 1682 | tokio::time::sleep(Duration::from_millis(5)).await; |
| 1683 | } |
| 1684 | |
| 1685 | assert!(!view.is_loading); |
| 1686 | assert_eq!(view.query, "alpha"); |
| 1687 | let matched: Vec<&str> = view |
| 1688 | .filtered |
| 1689 | .iter() |
| 1690 | .map(|i| view.candidates[*i].as_str()) |
| 1691 | .collect(); |
| 1692 | assert_eq!( |
| 1693 | matched, |
| 1694 | vec!["alpha.rs"], |
| 1695 | "the scan must refilter against the query the user already typed" |
| 1696 | ); |
| 1697 | } |
| 1698 | |
| 1699 | /// #2488: a miss-rescan on a truncated index must not run on the event |
| 1700 | /// loop. The constructor-style property from #3905 applies here too: |
| 1701 | /// `handle_key` returns a paintable view and the extra file arrives via |
| 1702 | /// `tick`. |
| 1703 | #[tokio::test] |
| 1704 | async fn truncated_index_rescan_does_not_block_handle_key() { |
| 1705 | let ws = TempDir::new().unwrap(); |
| 1706 | fs::write(ws.path().join("late_unique_file.rs"), "x").unwrap(); |
| 1707 | |
| 1708 | let mut view = FilePickerView::from_preloaded( |
| 1709 | ws.path(), |
| 1710 | vec!["unrelated.rs".into()], |
| 1711 | true, |
| 1712 | Some(WALK_DEPTH), |
| 1713 | ); |
| 1714 | for ch in "late_unique_file".chars() { |
| 1715 | view.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)); |
| 1716 | } |
| 1717 | assert!( |
| 1718 | view.is_rescanning |
| 1719 | || view |
| 1720 | .candidates |
| 1721 | .iter() |
| 1722 | .any(|path| path == "late_unique_file.rs"), |
| 1723 | "rescan must start off-thread (or already have merged on a tiny race)" |
| 1724 | ); |
| 1725 | |
| 1726 | for _ in 0..500 { |
| 1727 | view.tick(); |
| 1728 | if view |
| 1729 | .candidates |
| 1730 | .iter() |
| 1731 | .any(|path| path == "late_unique_file.rs") |
| 1732 | { |
| 1733 | break; |
| 1734 | } |
| 1735 | tokio::time::sleep(Duration::from_millis(5)).await; |
| 1736 | } |
| 1737 | assert_eq!(view.selected_for_test(), Some("late_unique_file.rs")); |
| 1738 | } |
| 1739 | |
| 1740 | #[test] |
| 1741 | fn file_picker_handle_paste_sanitizes_and_resets_selection() { |
| 1742 | let ws = TempDir::new().unwrap(); |
| 1743 | let mut view = FilePickerView::from_preloaded( |
| 1744 | ws.path(), |
| 1745 | vec![ |
| 1746 | "src/alpha.rs".into(), |
| 1747 | "src/beta.rs".into(), |
| 1748 | "src/gamma_target.rs".into(), |
| 1749 | ], |
| 1750 | false, |
| 1751 | Some(WALK_DEPTH), |
| 1752 | ); |
| 1753 | view.selected = 2; |
| 1754 | view.scroll.set(1); |
| 1755 | |
| 1756 | assert!(view.handle_paste("gamma\r\n_target\t\n")); |
| 1757 | assert_eq!(view.query(), "gamma _target "); |
| 1758 | assert_eq!(view.selected, 0); |
| 1759 | assert_eq!(view.scroll.get(), 0); |
| 1760 | |
| 1761 | view.query.clear(); |
| 1762 | view.selected = 2; |
| 1763 | view.scroll.set(1); |
| 1764 | assert!(view.handle_paste("gamma_target\r\n")); |
| 1765 | assert_eq!(view.query(), "gamma_target"); |
| 1766 | assert_eq!(view.selected, 0); |
| 1767 | assert_eq!(view.scroll.get(), 0); |
| 1768 | assert_eq!(view.selected_for_test(), Some("src/gamma_target.rs")); |
| 1769 | } |
| 1770 | } |
| 1771 |