1use super::file_search_bridge::{self, FileSearchConfig};
15use super::grep_cache::GrepSearchCache;
16use crate::cache::estimate_json_size;
17use anyhow::Result;
18use serde_json::Value;
19use std::path::PathBuf;
20use std::sync::Arc;
21use std::sync::Mutex;
22use std::sync::atomic::AtomicBool;
23use std::sync::atomic::Ordering;
24use std::thread;
25use std::time::Duration;
26use tracing::warn;
27
28pub(crate) use super::grep_backend::*;
31
32const SEARCH_DEBOUNCE: Duration = Duration::from_millis(150);
35
36const ACTIVE_SEARCH_COMPLETE_POLL_INTERVAL: Duration = Duration::from_millis(20);
38
39pub struct GrepSearchManager {
41 state: Arc<Mutex<SearchState>>,
43
44 search_dir: PathBuf,
45
46 cache: Arc<GrepSearchCache>,
48}
49
50struct SearchState {
51 latest_query: String,
53
54 is_search_scheduled: bool,
56
57 active_search: Option<ActiveSearch>,
59 last_result: Option<GrepSearchResult>,
60}
61
62struct ActiveSearch {
63 query: String,
64 cancellation_token: Arc<AtomicBool>,
65}
66
67impl GrepSearchManager {
68 pub fn new(search_dir: PathBuf) -> Self {
69 Self {
70 state: Arc::new(Mutex::new(SearchState {
71 latest_query: String::new(),
72 is_search_scheduled: false,
73 active_search: None,
74 last_result: None,
75 })),
76 search_dir,
77 cache: Arc::new(GrepSearchCache::new(100)), }
79 }
80
81 fn cached_result(cache: &GrepSearchCache, input: &GrepSearchInput) -> Option<GrepSearchResult> {
82 cache.get(input).map(|cached| GrepSearchResult {
83 query: cached.query.clone(),
84 matches: cached.matches.clone(),
85 truncated: cached.truncated,
86 total_matches: cached.total_matches,
87 })
88 }
89
90 pub fn on_user_query(&self, query: &str) {
92 {
93 let mut st = match self.state.lock() {
94 Ok(state) => state,
95 Err(err) => {
96 warn!("grep search state lock poisoned while handling query update: {err}");
97 return;
98 }
99 };
100 if query != st.latest_query {
101 st.latest_query.clear();
102 st.latest_query.push_str(query);
103 } else {
104 return;
105 }
106
107 if let Some(active_search) = &st.active_search
110 && !query.starts_with(&active_search.query)
111 {
112 active_search.cancellation_token.store(true, Ordering::Relaxed);
113 st.active_search = None;
114 }
115
116 if !st.is_search_scheduled {
118 st.is_search_scheduled = true;
119 } else {
120 return;
121 }
122 }
123
124 let state = self.state.clone();
128 let search_dir = self.search_dir.clone();
129 let cache = self.cache.clone();
130 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
131 warn!("grep search query ignored: no active Tokio runtime");
132 if let Ok(mut st) = self.state.lock() {
133 st.is_search_scheduled = false;
134 st.latest_query.clear();
136 }
137 return;
138 };
139 let search_runtime = runtime.clone();
142 drop(runtime.spawn_blocking(move || {
143 thread::sleep(SEARCH_DEBOUNCE);
146 loop {
147 let active_is_none = match state.lock() {
148 Ok(st) => st.active_search.is_none(),
149 Err(err) => {
150 warn!("grep search state lock poisoned while waiting for active search: {err}");
151 return;
152 }
153 };
154 if active_is_none {
155 break;
156 }
157 thread::sleep(ACTIVE_SEARCH_COMPLETE_POLL_INTERVAL);
158 }
159
160 let cancellation_token = Arc::new(AtomicBool::new(false));
163 let token = cancellation_token.clone();
164 let query = {
165 let mut st = match state.lock() {
166 Ok(state) => state,
167 Err(err) => {
168 warn!("grep search state lock poisoned while preparing debounced search: {err}");
169 return;
170 }
171 };
172 let query = st.latest_query.clone();
173 st.is_search_scheduled = false;
174 st.active_search = Some(ActiveSearch { query: query.clone(), cancellation_token: token });
175 query
176 };
177
178 drop(search_runtime.spawn(GrepSearchManager::spawn_grep_file(
182 query,
183 search_dir,
184 cancellation_token,
185 state,
186 Some(cache),
187 )));
188 }));
189 }
190
191 pub fn last_result(&self) -> Option<GrepSearchResult> {
193 match self.state.lock() {
194 Ok(st) => st.last_result.clone(),
195 Err(err) => {
196 warn!("grep search state lock poisoned while reading last result: {err}");
197 None
198 }
199 }
200 }
201
202 async fn execute_with_backends(
203 input: &GrepSearchInput,
204 cancel_flag: Option<&Arc<AtomicBool>>,
205 ) -> Result<(Vec<Value>, bool, usize)> {
206 let matches = run_search_backend(input, cancel_flag).await?;
207 Ok(Self::finalize_matches(matches, input))
208 }
209
210 fn finalize_matches(mut matches: Vec<Value>, input: &GrepSearchInput) -> (Vec<Value>, bool, usize) {
211 let mut truncated = false;
212 let max_results = input.max_results.unwrap_or(MAX_SEARCH_RESULTS.get());
213
214 if max_results == 0 {
215 return (Vec::new(), !matches.is_empty(), 0);
216 }
217
218 let total_match_count = matches
220 .iter()
221 .filter(|e| e.get("type").and_then(Value::as_str) == Some("match"))
222 .count();
223
224 let mut match_count = 0usize;
227 let mut cut_index = matches.len();
228 for (i, entry) in matches.iter().enumerate() {
229 let is_match = entry.get("type").and_then(Value::as_str).is_some_and(|t| t == "match");
230 if is_match {
231 match_count += 1;
232 if match_count >= max_results {
233 cut_index = i + 1;
236 for rest in matches.iter().skip(i + 1) {
238 let tp = rest.get("type").and_then(Value::as_str);
239 if tp == Some("context") {
240 cut_index += 1;
241 } else {
242 break;
243 }
244 }
245 break;
246 }
247 }
248 }
249 if matches[cut_index..]
251 .iter()
252 .any(|e| e.get("type").and_then(Value::as_str) == Some("match"))
253 {
254 truncated = true;
255 }
256 if cut_index < matches.len() {
257 matches.truncate(cut_index);
258 }
259
260 if let Some(limit) = input.max_result_bytes {
261 let mut total = 0usize;
262 let mut kept_count = 0;
263 for entry in &matches {
264 let entry_bytes = estimate_json_size(entry) as usize;
265 if total + entry_bytes > limit {
266 truncated = true;
267 break;
268 }
269 total += entry_bytes;
270 kept_count += 1;
271 }
272 matches.truncate(kept_count);
273 }
274
275 (matches, truncated, total_match_count)
276 }
277
278 async fn spawn_grep_file(
279 query: String,
280 search_dir: PathBuf,
281 cancellation_token: Arc<AtomicBool>,
282 search_state: Arc<Mutex<SearchState>>,
283 cache: Option<Arc<GrepSearchCache>>,
284 ) {
285 if cancellation_token.load(Ordering::Relaxed) {
287 {
289 let mut st = match search_state.lock() {
290 Ok(state) => state,
291 Err(err) => {
292 warn!("grep search state lock poisoned while cancelling search: {err}");
293 return;
294 }
295 };
296 if let Some(active_search) = &st.active_search
297 && Arc::ptr_eq(&active_search.cancellation_token, &cancellation_token)
298 {
299 st.active_search = None;
300 }
301 }
302 return;
303 }
304
305 let input = GrepSearchInput::with_defaults(query.clone(), search_dir.to_string_lossy().into_owned());
306
307 if let Some(ref cache) = cache
309 && let Some(cached_result) = Self::cached_result(cache, &input)
310 {
311 let mut st = match search_state.lock() {
312 Ok(state) => state,
313 Err(err) => {
314 warn!("grep search state lock poisoned while loading cached result: {err}");
315 return;
316 }
317 };
318 st.last_result = Some(cached_result);
319 return;
320 }
321
322 let timeout = input.timeout.unwrap_or(DEFAULT_SEARCH_TIMEOUT);
326 let search_result = match tokio::time::timeout(
327 timeout,
328 GrepSearchManager::execute_with_backends(&input, Some(&cancellation_token)),
329 )
330 .await
331 {
332 Ok(result) => result,
333 Err(_elapsed) => Err(anyhow::anyhow!("content search timed out after {}s", timeout.as_secs())),
334 };
335
336 let is_cancelled = cancellation_token.load(Ordering::Relaxed);
337 if !is_cancelled
338 && let Ok((matches, truncated, total_match_count)) = search_result
339 && !matches.is_empty()
340 {
341 let result = GrepSearchResult {
342 query,
343 matches,
344 truncated,
345 total_matches: if truncated { Some(total_match_count) } else { None },
346 };
347
348 if let Some(ref cache) = cache
354 && GrepSearchCache::should_cache(&result)
355 {
356 cache.put(&input, result.clone());
357 }
358
359 let mut st = match search_state.lock() {
360 Ok(state) => state,
361 Err(err) => {
362 warn!("grep search state lock poisoned while storing search result: {err}");
363 return;
364 }
365 };
366 st.last_result = Some(result);
367 }
368
369 {
371 let mut st = match search_state.lock() {
372 Ok(state) => state,
373 Err(err) => {
374 warn!("grep search state lock poisoned while clearing active search: {err}");
375 return;
376 }
377 };
378 if let Some(active_search) = &st.active_search
379 && Arc::ptr_eq(&active_search.cancellation_token, &cancellation_token)
380 {
381 st.active_search = None;
382 }
383 }
384 }
385
386 pub async fn perform_search(&self, input: GrepSearchInput) -> Result<GrepSearchResult> {
388 if let Some(cached_result) = Self::cached_result(&self.cache, &input) {
390 return Ok(cached_result);
391 }
392
393 let query = input.pattern.clone();
394 let input_clone = input.clone();
395
396 let timeout = input.timeout.unwrap_or(DEFAULT_SEARCH_TIMEOUT);
397 let outcome = tokio::time::timeout(timeout, Self::execute_with_backends(&input_clone, None)).await;
400 let (matches, truncated, total_match_count) = match outcome {
401 Ok(Ok(result)) => result,
402 Ok(Err(worker_err)) => {
403 return Err(worker_err.context("content search worker failed"));
404 }
405 Err(_elapsed) => {
406 return Err(anyhow::anyhow!(
407 "content search timed out after {}s; the search was cancelled",
408 timeout.as_secs()
409 ));
410 }
411 };
412
413 let result = GrepSearchResult {
414 query,
415 matches,
416 truncated,
417 total_matches: if truncated { Some(total_match_count) } else { None },
418 };
419
420 if GrepSearchCache::should_cache(&result) {
425 self.cache.put(&input, result.clone());
426 }
427
428 Ok(result)
429 }
430
431 pub fn enumerate_files_with_pattern(
450 &self,
451 pattern: String,
452 max_results: usize,
453 cancel_flag: Option<Arc<AtomicBool>>,
454 ) -> Result<Vec<String>> {
455 let config = FileSearchConfig::new(pattern, self.search_dir.clone())
456 .with_limit(max_results)
457 .respect_gitignore(true);
458
459 let results = file_search_bridge::search_files(config, cancel_flag)?;
460
461 Ok(file_search_bridge::file_matches_only(results.matches)
462 .into_iter()
463 .map(|m| m.path)
464 .collect())
465 }
466
467 pub fn list_all_files(&self, max_results: usize, exclude_patterns: Vec<String>) -> Result<Vec<String>> {
481 let mut config = FileSearchConfig::new("".to_string(), self.search_dir.clone())
482 .with_limit(max_results)
483 .respect_gitignore(true);
484
485 for pattern in exclude_patterns {
486 config = config.exclude(pattern);
487 }
488
489 let results = file_search_bridge::search_files(config, None)?;
490
491 Ok(file_search_bridge::file_matches_only(results.matches)
492 .into_iter()
493 .map(|m| m.path)
494 .collect())
495 }
496}
497
498#[cfg(test)]
499mod tests {
500 use super::*;
501 use crate::tools::code_language::CodeLanguage;
502 use serde_json::json;
503 use tempfile::TempDir;
504
505 #[tokio::test]
506 async fn perform_search_caches_matches_but_leaves_no_hit_results_uncached() {
507 let workspace = TempDir::new().expect("workspace");
508 std::fs::write(workspace.path().join("hit.rs"), "needle\n").expect("fixture");
509 let manager = GrepSearchManager::new(workspace.path().to_path_buf());
510
511 let miss_input =
517 GrepSearchInput::with_defaults("absent-token".to_string(), workspace.path().to_string_lossy().into_owned());
518 let first_miss = manager.perform_search(miss_input.clone()).await.expect("no-match search");
519 assert!(
520 !first_miss
521 .matches
522 .iter()
523 .any(|entry| entry.get("type").and_then(Value::as_str) == Some("match")),
524 "a no-hit search must carry no match records, got: {:?}",
525 first_miss.matches
526 );
527 let second_miss = manager.perform_search(miss_input).await.expect("repeat no-match search");
528 assert!(
529 !second_miss
530 .matches
531 .iter()
532 .any(|entry| entry.get("type").and_then(Value::as_str) == Some("match"))
533 );
534 assert_eq!(
535 manager.cache.stats().0,
536 0,
537 "no-hit results must never be cached: a stale negative would hide new matches within the TTL window"
538 );
539
540 let hit_input =
542 GrepSearchInput::with_defaults("needle".to_string(), workspace.path().to_string_lossy().into_owned());
543 let hit = manager.perform_search(hit_input).await.expect("matching search");
544 assert!(
545 hit.matches
546 .iter()
547 .any(|entry| entry.get("type").and_then(Value::as_str) == Some("match")),
548 "a hit search must carry at least one match record"
549 );
550 assert_eq!(manager.cache.stats().0, 1, "results with real matches are cached");
551 }
552
553 #[tokio::test]
554 async fn code_search_literal_stream_reaps_at_candidate_cap() {
555 let workspace = TempDir::new().expect("workspace");
556 std::fs::write(workspace.path().join("matches.txt"), "Widget\nWidget\nWidget\n").expect("fixture");
557
558 let outcome = search_literal_bounded("Widget", workspace.path(), &[], 2)
559 .await
560 .expect("bounded literal search");
561
562 assert_eq!(outcome.candidates.len(), 2);
563 assert!(outcome.truncated);
564 }
565
566 #[tokio::test]
567 async fn code_search_literal_candidate_cap_selects_stable_path_prefix() {
568 let workspace = TempDir::new().expect("workspace");
569 for name in ["z.txt", "a.txt", "m.txt"] {
570 std::fs::write(workspace.path().join(name), "Widget\nWidget\n").expect("fixture");
571 }
572
573 let first = search_literal_bounded("Widget", workspace.path(), &[], 2)
574 .await
575 .expect("first bounded search");
576 let second = search_literal_bounded("Widget", workspace.path(), &[], 2)
577 .await
578 .expect("second bounded search");
579
580 assert_eq!(first.candidates, second.candidates, "the capped prefix must be stable");
581 assert!(first.truncated);
582 assert!(
583 first.candidates.iter().all(|candidate| candidate.path.ends_with("a.txt")),
584 "sorted cap prefix should come from a.txt: {first:?}"
585 );
586 }
587
588 #[tokio::test]
589 async fn code_search_literal_reports_truncation_at_the_cap() {
590 let workspace = TempDir::new().expect("workspace");
591 std::fs::write(workspace.path().join("large.txt"), "Widget\n".repeat(50)).expect("fixture");
592
593 let outcome = search_literal_bounded("Widget", workspace.path(), &[], 20)
594 .await
595 .expect("byte-bounded literal search");
596
597 assert_eq!(outcome.candidates.len(), 20, "the cap bounds the reported matches");
598 assert!(outcome.truncated);
599 }
600
601 #[tokio::test]
602 async fn code_search_literal_language_prefilters_are_case_insensitive() {
603 let workspace = TempDir::new().expect("workspace");
604 std::fs::write(workspace.path().join("UPPER.RS"), "Widget\n").expect("Rust fixture");
605 std::fs::write(workspace.path().join("DOCKERFILE"), "Widget\n").expect("Dockerfile fixture");
606
607 let rust = search_literal_bounded("Widget", workspace.path(), &[CodeLanguage::Rust], 20)
608 .await
609 .expect("uppercase Rust extension");
610 assert!(rust.candidates.iter().any(|candidate| {
611 candidate.path.ends_with("UPPER.RS") && CodeLanguage::from_path(&candidate.path) == Some(CodeLanguage::Rust)
612 }));
613
614 let dockerfile = search_literal_bounded("Widget", workspace.path(), &[CodeLanguage::Dockerfile], 20)
615 .await
616 .expect("uppercase Dockerfile name");
617 assert!(dockerfile.candidates.iter().any(|candidate| {
618 candidate.path.ends_with("DOCKERFILE")
619 && CodeLanguage::from_path(&candidate.path) == Some(CodeLanguage::Dockerfile)
620 }));
621 }
622
623 #[tokio::test]
624 async fn code_search_literal_alternation_matches_each_term() {
625 let workspace = TempDir::new().expect("workspace");
629 std::fs::write(workspace.path().join("a.rs"), "tokio\n").expect("fixture a");
630 std::fs::write(workspace.path().join("b.rs"), "async-std\n").expect("fixture b");
631 std::fs::write(workspace.path().join("c.rs"), "runtime\n").expect("fixture c");
632 std::fs::write(workspace.path().join("d.rs"), "unrelated\n").expect("fixture d");
633
634 let outcome = search_literal_bounded("tokio|async-std|runtime", workspace.path(), &[], 20)
635 .await
636 .expect("alternation search");
637
638 let matched_paths: Vec<String> = outcome
639 .candidates
640 .iter()
641 .map(|candidate| {
642 candidate
643 .path
644 .file_name()
645 .map(|name| name.to_string_lossy().into_owned())
646 .unwrap_or_default()
647 })
648 .collect();
649 assert!(matched_paths.contains(&"a.rs".to_string()), "tokio term should match: {matched_paths:?}");
650 assert!(matched_paths.contains(&"b.rs".to_string()), "async-std term should match: {matched_paths:?}");
651 assert!(matched_paths.contains(&"c.rs".to_string()), "runtime term should match: {matched_paths:?}");
652 assert!(
653 !matched_paths.contains(&"d.rs".to_string()),
654 "unrelated fixture should not match: {matched_paths:?}"
655 );
656 assert!(!outcome.truncated);
657 }
658
659 #[tokio::test]
660 async fn code_search_literal_single_term_still_uses_fixed_strings() {
661 let workspace = TempDir::new().expect("workspace");
664 std::fs::write(workspace.path().join("src.rs"), "fn main() {}\n").expect("fixture");
665
666 let outcome = search_literal_bounded("fn main()", workspace.path(), &[], 20)
667 .await
668 .expect("single-term literal search");
669
670 assert_eq!(outcome.candidates.len(), 1);
671 assert!(outcome.candidates[0].path.ends_with("src.rs"));
672 }
673
674 #[test]
675 fn split_alternation_handles_edge_cases() {
676 assert_eq!(split_alternation(""), Vec::<String>::new());
677 assert_eq!(split_alternation(" "), Vec::<String>::new());
678 assert_eq!(split_alternation("Widget"), vec!["Widget".to_string()]);
679 assert_eq!(split_alternation(" Widget "), vec!["Widget".to_string()]);
680 assert_eq!(
681 split_alternation("tokio|async-std|runtime"),
682 vec!["tokio".to_string(), "async-std".to_string(), "runtime".to_string()]
683 );
684 assert_eq!(split_alternation("|foo|"), vec!["foo".to_string()]);
686 assert_eq!(split_alternation("a||b"), vec!["a".to_string(), "b".to_string()]);
687 assert_eq!(split_alternation("||"), Vec::<String>::new());
689 }
690
691 #[test]
692 fn finalize_matches_respects_max_bytes() {
693 let mut input = GrepSearchInput::with_defaults("pat".into(), ".".into());
694 input.max_result_bytes = Some(100);
695 input.max_results = Some(5);
696
697 let matches = vec![json!({"text": "12345"}), json!({"text": "6789"})];
698
699 let (kept, truncated, _total) = GrepSearchManager::finalize_matches(matches, &input);
700 assert!(!truncated);
701 assert_eq!(kept.len(), 2);
702
703 input.max_result_bytes = Some(20);
705 let matches = vec![json!({"text": "12345"}), json!({"text": "6789"})];
706 let (kept, truncated, _total) = GrepSearchManager::finalize_matches(matches, &input);
707 assert!(truncated);
708 assert_eq!(kept.len(), 1); }
710
711 #[test]
712 fn finalize_matches_counts_only_match_type_entries() {
713 let mut input = GrepSearchInput::with_defaults("pat".into(), ".".into());
714 input.max_results = Some(2);
715
716 let matches = vec![
718 json!({"type": "begin", "data": {"path": {"text": "Cargo.lock"}}}),
719 json!({"type": "context", "data": {"line_number": 538, "lines": {"text": "ctx1"}}}),
720 json!({"type": "context", "data": {"line_number": 539, "lines": {"text": "ctx2"}}}),
721 json!({"type": "match", "data": {"line_number": 553, "lines": {"text": "match1"}}}),
722 json!({"type": "context", "data": {"line_number": 554, "lines": {"text": "ctx3"}}}),
723 json!({"type": "context", "data": {"line_number": 555, "lines": {"text": "ctx4"}}}),
724 json!({"type": "context", "data": {"line_number": 560, "lines": {"text": "ctx5"}}}),
725 json!({"type": "match", "data": {"line_number": 563, "lines": {"text": "match2"}}}),
726 json!({"type": "context", "data": {"line_number": 564, "lines": {"text": "ctx6"}}}),
727 json!({"type": "end", "data": {"path": {"text": "Cargo.lock"}}}),
728 ];
729
730 let (kept, truncated, total) = GrepSearchManager::finalize_matches(matches, &input);
731 assert!(!truncated);
734 assert_eq!(kept.len(), 9);
735 assert_eq!(kept[3]["type"], "match");
736 assert_eq!(kept[7]["type"], "match");
737 assert_eq!(total, 2);
738 }
739
740 #[test]
741 fn finalize_matches_truncates_when_more_match_types_than_limit() {
742 let mut input = GrepSearchInput::with_defaults("pat".into(), ".".into());
743 input.max_results = Some(1);
744
745 let matches = vec![
746 json!({"type": "begin", "data": {"path": {"text": "f.txt"}}}),
747 json!({"type": "match", "data": {"line_number": 1, "lines": {"text": "m1"}}}),
748 json!({"type": "context", "data": {"line_number": 2, "lines": {"text": "c1"}}}),
749 json!({"type": "match", "data": {"line_number": 10, "lines": {"text": "m2"}}}),
750 json!({"type": "context", "data": {"line_number": 11, "lines": {"text": "c2"}}}),
751 ];
752
753 let (kept, truncated, total) = GrepSearchManager::finalize_matches(matches, &input);
754 assert!(truncated);
755 assert_eq!(kept.len(), 3);
757 assert_eq!(kept[1]["type"], "match");
758 assert_eq!(kept[2]["type"], "context");
759 assert_eq!(total, 2); }
761
762 #[test]
763 fn test_grep_search_manager_creation() {
764 let manager = GrepSearchManager::new(PathBuf::from("."));
765 assert_eq!(manager.search_dir, PathBuf::from("."));
766 }
767
768 #[test]
769 fn on_user_query_without_runtime_does_not_panic_and_allows_retry() {
770 let manager = GrepSearchManager::new(PathBuf::from("."));
771 manager.on_user_query("first");
772 manager.on_user_query("first");
773 let state = manager.state.lock().expect("state lock");
774 assert!(state.latest_query.is_empty());
775 assert!(!state.is_search_scheduled);
776 }
777
778 #[test]
779 fn test_grep_search_input_new() {
780 let input = GrepSearchInput::new("pattern".to_string(), "/path/to/search".to_string());
781 assert_eq!(input.pattern, "pattern");
782 assert_eq!(input.path, "/path/to/search");
783 assert!(input.case_sensitive.is_none());
784 }
785
786 #[test]
787 fn test_grep_search_input_with_defaults() {
788 let input = GrepSearchInput::with_defaults("pattern".to_string(), "/path".to_string());
789 assert_eq!(input.pattern, "pattern");
790 assert_eq!(input.path, "/path");
791 assert_eq!(input.case_sensitive, Some(true));
792 assert_eq!(input.include_hidden, Some(false));
793 assert_eq!(input.max_results, Some(MAX_SEARCH_RESULTS.get()));
794 }
795}