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<&AtomicBool>,
205 ) -> Result<(Vec<Value>, bool, usize)> {
206 let matches = run_ripgrep_backend_async(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!("ripgrep 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;
403 let (matches, truncated, total_match_count) = match outcome {
404 Ok(Ok(result)) => result,
405 Ok(Err(worker_err)) => {
406 return Err(worker_err.context("ripgrep search worker failed"));
407 }
408 Err(_elapsed) => {
409 return Err(anyhow::anyhow!(
410 "ripgrep search timed out after {}s; ripgrep was killed",
411 timeout.as_secs()
412 ));
413 }
414 };
415
416 let result = GrepSearchResult {
417 query,
418 matches,
419 truncated,
420 total_matches: if truncated { Some(total_match_count) } else { None },
421 };
422
423 if GrepSearchCache::should_cache(&result) {
428 self.cache.put(&input, result.clone());
429 }
430
431 Ok(result)
432 }
433
434 pub fn enumerate_files_with_pattern(
453 &self,
454 pattern: String,
455 max_results: usize,
456 cancel_flag: Option<Arc<AtomicBool>>,
457 ) -> Result<Vec<String>> {
458 let config = FileSearchConfig::new(pattern, self.search_dir.clone())
459 .with_limit(max_results)
460 .respect_gitignore(true);
461
462 let results = file_search_bridge::search_files(config, cancel_flag)?;
463
464 Ok(file_search_bridge::file_matches_only(results.matches)
465 .into_iter()
466 .map(|m| m.path)
467 .collect())
468 }
469
470 pub fn list_all_files(&self, max_results: usize, exclude_patterns: Vec<String>) -> Result<Vec<String>> {
484 let mut config = FileSearchConfig::new("".to_string(), self.search_dir.clone())
485 .with_limit(max_results)
486 .respect_gitignore(true);
487
488 for pattern in exclude_patterns {
489 config = config.exclude(pattern);
490 }
491
492 let results = file_search_bridge::search_files(config, None)?;
493
494 Ok(file_search_bridge::file_matches_only(results.matches)
495 .into_iter()
496 .map(|m| m.path)
497 .collect())
498 }
499}
500
501#[cfg(test)]
502mod tests {
503 use super::*;
504 use crate::tools::ast_grep_language::AstGrepLanguage;
505 use serde_json::json;
506 use tempfile::TempDir;
507 use tokio::io::BufReader;
508
509 #[tokio::test]
510 async fn perform_search_caches_matches_but_leaves_no_hit_results_uncached() {
511 let workspace = TempDir::new().expect("workspace");
512 std::fs::write(workspace.path().join("hit.rs"), "needle\n").expect("fixture");
513 let manager = GrepSearchManager::new(workspace.path().to_path_buf());
514
515 let miss_input =
521 GrepSearchInput::with_defaults("absent-token".to_string(), workspace.path().to_string_lossy().into_owned());
522 let first_miss = manager.perform_search(miss_input.clone()).await.expect("no-match search");
523 assert!(
524 !first_miss
525 .matches
526 .iter()
527 .any(|entry| entry.get("type").and_then(Value::as_str) == Some("match")),
528 "a no-hit search must carry no match records, got: {:?}",
529 first_miss.matches
530 );
531 let second_miss = manager.perform_search(miss_input).await.expect("repeat no-match search");
532 assert!(
533 !second_miss
534 .matches
535 .iter()
536 .any(|entry| entry.get("type").and_then(Value::as_str) == Some("match"))
537 );
538 assert_eq!(
539 manager.cache.stats().0,
540 0,
541 "no-hit results must never be cached: a stale negative would hide new matches within the TTL window"
542 );
543
544 let hit_input =
546 GrepSearchInput::with_defaults("needle".to_string(), workspace.path().to_string_lossy().into_owned());
547 let hit = manager.perform_search(hit_input).await.expect("matching search");
548 assert!(
549 hit.matches
550 .iter()
551 .any(|entry| entry.get("type").and_then(Value::as_str) == Some("match")),
552 "a hit search must carry at least one match record"
553 );
554 assert_eq!(manager.cache.stats().0, 1, "results with real matches are cached");
555 }
556
557 #[tokio::test]
558 async fn code_search_literal_stream_reaps_at_candidate_cap() {
559 let workspace = TempDir::new().expect("workspace");
560 std::fs::write(workspace.path().join("matches.txt"), "Widget\nWidget\nWidget\n").expect("fixture");
561
562 let outcome = search_literal_bounded("Widget", workspace.path(), &[], 2)
563 .await
564 .expect("bounded literal search");
565
566 assert_eq!(outcome.candidates.len(), 2);
567 assert!(outcome.truncated);
568 }
569
570 #[tokio::test]
571 async fn code_search_literal_candidate_cap_selects_stable_path_prefix() {
572 let workspace = TempDir::new().expect("workspace");
573 for name in ["z.txt", "a.txt", "m.txt"] {
574 std::fs::write(workspace.path().join(name), "Widget\nWidget\n").expect("fixture");
575 }
576
577 let first = search_literal_bounded("Widget", workspace.path(), &[], 2)
578 .await
579 .expect("first bounded search");
580 let second = search_literal_bounded("Widget", workspace.path(), &[], 2)
581 .await
582 .expect("second bounded search");
583
584 assert_eq!(first, second);
585 assert!(first.truncated);
586 assert!(
587 first.candidates.iter().all(|candidate| candidate.path.ends_with("a.txt")),
588 "sorted cap prefix should come from a.txt: {first:?}"
589 );
590 }
591
592 #[tokio::test]
593 async fn code_search_literal_stream_reaps_at_byte_cap() {
594 let workspace = TempDir::new().expect("workspace");
595 std::fs::write(
596 workspace.path().join("large.txt"),
597 format!("Widget{}\n", "x".repeat(CODE_SEARCH_STREAM_BYTE_CAP)),
598 )
599 .expect("fixture");
600
601 let outcome = search_literal_bounded("Widget", workspace.path(), &[], 20)
602 .await
603 .expect("byte-bounded literal search");
604
605 assert!(outcome.candidates.is_empty());
606 assert!(outcome.truncated);
607 }
608
609 #[tokio::test]
610 async fn code_search_bounded_record_distinguishes_exact_eof_from_exhaustion() {
611 let mut exact_reader = BufReader::new(&b"{}\n"[..]);
612 let mut exact_record = Vec::with_capacity(3);
613 let mut exact_bytes_read = 0;
614 assert_eq!(
615 read_bounded_record(&mut exact_reader, &mut exact_record, &mut exact_bytes_read, 3,)
616 .await
617 .expect("exact record"),
618 BoundedRecordRead::Record
619 );
620 exact_record.clear();
621 assert_eq!(
622 read_bounded_record(&mut exact_reader, &mut exact_record, &mut exact_bytes_read, 3,)
623 .await
624 .expect("exact EOF probe"),
625 BoundedRecordRead::Eof
626 );
627
628 let mut oversized_reader = BufReader::new(&b"xxxx"[..]);
629 let mut oversized_record = Vec::with_capacity(3);
630 let mut oversized_bytes_read = 0;
631 assert_eq!(
632 read_bounded_record(&mut oversized_reader, &mut oversized_record, &mut oversized_bytes_read, 3,)
633 .await
634 .expect("oversized record"),
635 BoundedRecordRead::Exhausted
636 );
637 assert_eq!(oversized_record.len(), 3);
638 }
639
640 #[tokio::test]
641 async fn code_search_literal_language_prefilters_are_case_insensitive() {
642 let workspace = TempDir::new().expect("workspace");
643 std::fs::write(workspace.path().join("UPPER.RS"), "Widget\n").expect("Rust fixture");
644 std::fs::write(workspace.path().join("DOCKERFILE"), "Widget\n").expect("Dockerfile fixture");
645
646 let rust = search_literal_bounded("Widget", workspace.path(), &[AstGrepLanguage::Rust], 20)
647 .await
648 .expect("uppercase Rust extension");
649 assert!(rust.candidates.iter().any(|candidate| {
650 candidate.path.ends_with("UPPER.RS")
651 && AstGrepLanguage::from_path(&candidate.path) == Some(AstGrepLanguage::Rust)
652 }));
653
654 let dockerfile = search_literal_bounded("Widget", workspace.path(), &[AstGrepLanguage::Dockerfile], 20)
655 .await
656 .expect("uppercase Dockerfile name");
657 assert!(dockerfile.candidates.iter().any(|candidate| {
658 candidate.path.ends_with("DOCKERFILE")
659 && AstGrepLanguage::from_path(&candidate.path) == Some(AstGrepLanguage::Dockerfile)
660 }));
661 }
662
663 #[tokio::test]
664 async fn code_search_literal_alternation_matches_each_term() {
665 let workspace = TempDir::new().expect("workspace");
669 std::fs::write(workspace.path().join("a.rs"), "tokio\n").expect("fixture a");
670 std::fs::write(workspace.path().join("b.rs"), "async-std\n").expect("fixture b");
671 std::fs::write(workspace.path().join("c.rs"), "runtime\n").expect("fixture c");
672 std::fs::write(workspace.path().join("d.rs"), "unrelated\n").expect("fixture d");
673
674 let outcome = search_literal_bounded("tokio|async-std|runtime", workspace.path(), &[], 20)
675 .await
676 .expect("alternation search");
677
678 let matched_paths: Vec<String> = outcome
679 .candidates
680 .iter()
681 .map(|candidate| {
682 candidate
683 .path
684 .file_name()
685 .map(|name| name.to_string_lossy().into_owned())
686 .unwrap_or_default()
687 })
688 .collect();
689 assert!(matched_paths.contains(&"a.rs".to_string()), "tokio term should match: {matched_paths:?}");
690 assert!(matched_paths.contains(&"b.rs".to_string()), "async-std term should match: {matched_paths:?}");
691 assert!(matched_paths.contains(&"c.rs".to_string()), "runtime term should match: {matched_paths:?}");
692 assert!(
693 !matched_paths.contains(&"d.rs".to_string()),
694 "unrelated fixture should not match: {matched_paths:?}"
695 );
696 assert!(!outcome.truncated);
697 }
698
699 #[tokio::test]
700 async fn code_search_literal_single_term_still_uses_fixed_strings() {
701 let workspace = TempDir::new().expect("workspace");
704 std::fs::write(workspace.path().join("src.rs"), "fn main() {}\n").expect("fixture");
705
706 let outcome = search_literal_bounded("fn main()", workspace.path(), &[], 20)
707 .await
708 .expect("single-term literal search");
709
710 assert_eq!(outcome.candidates.len(), 1);
711 assert!(outcome.candidates[0].path.ends_with("src.rs"));
712 }
713
714 #[test]
715 fn split_alternation_handles_edge_cases() {
716 assert_eq!(split_alternation(""), Vec::<String>::new());
717 assert_eq!(split_alternation(" "), Vec::<String>::new());
718 assert_eq!(split_alternation("Widget"), vec!["Widget".to_string()]);
719 assert_eq!(split_alternation(" Widget "), vec!["Widget".to_string()]);
720 assert_eq!(
721 split_alternation("tokio|async-std|runtime"),
722 vec!["tokio".to_string(), "async-std".to_string(), "runtime".to_string()]
723 );
724 assert_eq!(split_alternation("|foo|"), vec!["foo".to_string()]);
726 assert_eq!(split_alternation("a||b"), vec!["a".to_string(), "b".to_string()]);
727 assert_eq!(split_alternation("||"), Vec::<String>::new());
729 }
730
731 #[test]
732 fn finalize_matches_respects_max_bytes() {
733 let mut input = GrepSearchInput::with_defaults("pat".into(), ".".into());
734 input.max_result_bytes = Some(100);
735 input.max_results = Some(5);
736
737 let matches = vec![json!({"text": "12345"}), json!({"text": "6789"})];
738
739 let (kept, truncated, _total) = GrepSearchManager::finalize_matches(matches, &input);
740 assert!(!truncated);
741 assert_eq!(kept.len(), 2);
742
743 input.max_result_bytes = Some(20);
745 let matches = vec![json!({"text": "12345"}), json!({"text": "6789"})];
746 let (kept, truncated, _total) = GrepSearchManager::finalize_matches(matches, &input);
747 assert!(truncated);
748 assert_eq!(kept.len(), 1); }
750
751 #[test]
752 fn finalize_matches_counts_only_match_type_entries() {
753 let mut input = GrepSearchInput::with_defaults("pat".into(), ".".into());
754 input.max_results = Some(2);
755
756 let matches = vec![
758 json!({"type": "begin", "data": {"path": {"text": "Cargo.lock"}}}),
759 json!({"type": "context", "data": {"line_number": 538, "lines": {"text": "ctx1"}}}),
760 json!({"type": "context", "data": {"line_number": 539, "lines": {"text": "ctx2"}}}),
761 json!({"type": "match", "data": {"line_number": 553, "lines": {"text": "match1"}}}),
762 json!({"type": "context", "data": {"line_number": 554, "lines": {"text": "ctx3"}}}),
763 json!({"type": "context", "data": {"line_number": 555, "lines": {"text": "ctx4"}}}),
764 json!({"type": "context", "data": {"line_number": 560, "lines": {"text": "ctx5"}}}),
765 json!({"type": "match", "data": {"line_number": 563, "lines": {"text": "match2"}}}),
766 json!({"type": "context", "data": {"line_number": 564, "lines": {"text": "ctx6"}}}),
767 json!({"type": "end", "data": {"path": {"text": "Cargo.lock"}}}),
768 ];
769
770 let (kept, truncated, total) = GrepSearchManager::finalize_matches(matches, &input);
771 assert!(!truncated);
774 assert_eq!(kept.len(), 9);
775 assert_eq!(kept[3]["type"], "match");
776 assert_eq!(kept[7]["type"], "match");
777 assert_eq!(total, 2);
778 }
779
780 #[test]
781 fn finalize_matches_truncates_when_more_match_types_than_limit() {
782 let mut input = GrepSearchInput::with_defaults("pat".into(), ".".into());
783 input.max_results = Some(1);
784
785 let matches = vec![
786 json!({"type": "begin", "data": {"path": {"text": "f.txt"}}}),
787 json!({"type": "match", "data": {"line_number": 1, "lines": {"text": "m1"}}}),
788 json!({"type": "context", "data": {"line_number": 2, "lines": {"text": "c1"}}}),
789 json!({"type": "match", "data": {"line_number": 10, "lines": {"text": "m2"}}}),
790 json!({"type": "context", "data": {"line_number": 11, "lines": {"text": "c2"}}}),
791 ];
792
793 let (kept, truncated, total) = GrepSearchManager::finalize_matches(matches, &input);
794 assert!(truncated);
795 assert_eq!(kept.len(), 3);
797 assert_eq!(kept[1]["type"], "match");
798 assert_eq!(kept[2]["type"], "context");
799 assert_eq!(total, 2); }
801
802 #[test]
803 fn test_grep_search_manager_creation() {
804 let manager = GrepSearchManager::new(PathBuf::from("."));
805 assert_eq!(manager.search_dir, PathBuf::from("."));
806 }
807
808 #[test]
809 fn on_user_query_without_runtime_does_not_panic_and_allows_retry() {
810 let manager = GrepSearchManager::new(PathBuf::from("."));
811 manager.on_user_query("first");
812 manager.on_user_query("first");
813 let state = manager.state.lock().expect("state lock");
814 assert!(state.latest_query.is_empty());
815 assert!(!state.is_search_scheduled);
816 }
817
818 #[test]
819 fn test_grep_search_input_new() {
820 let input = GrepSearchInput::new("pattern".to_string(), "/path/to/search".to_string());
821 assert_eq!(input.pattern, "pattern");
822 assert_eq!(input.path, "/path/to/search");
823 assert!(input.case_sensitive.is_none());
824 }
825
826 #[test]
827 fn test_grep_search_input_with_defaults() {
828 let input = GrepSearchInput::with_defaults("pattern".to_string(), "/path".to_string());
829 assert_eq!(input.pattern, "pattern");
830 assert_eq!(input.path, "/path");
831 assert_eq!(input.case_sensitive, Some(true));
832 assert_eq!(input.include_hidden, Some(false));
833 assert_eq!(input.max_results, Some(MAX_SEARCH_RESULTS.get()));
834 }
835}