grep_tool.rs

   1use crate::{AgentTool, ToolCallEventStream};
   2use agent_client_protocol as acp;
   3use anyhow::{Result, anyhow};
   4use futures::StreamExt;
   5use gpui::{App, Entity, SharedString, Task};
   6use language::{OffsetRangeExt, ParseStatus, Point};
   7use project::{
   8    Project, WorktreeSettings,
   9    search::{SearchQuery, SearchResult},
  10};
  11use schemars::JsonSchema;
  12use serde::{Deserialize, Serialize};
  13use settings::Settings;
  14use std::{cmp, fmt::Write, sync::Arc};
  15use util::RangeExt;
  16use util::markdown::MarkdownInlineCode;
  17use util::paths::PathMatcher;
  18
  19/// Searches the contents of files in the project with a regular expression
  20///
  21/// - Prefer this tool to path search when searching for symbols in the project, because you won't need to guess what path it's in.
  22/// - Supports full regex syntax (eg. "log.*Error", "function\\s+\\w+", etc.)
  23/// - Pass an `include_pattern` if you know how to narrow your search on the files system
  24/// - Never use this tool to search for paths. Only search file contents with this tool.
  25/// - Use this tool when you need to find files containing specific patterns
  26/// - Results are paginated with 20 matches per page. Use the optional 'offset' parameter to request subsequent pages.
  27/// - DO NOT use HTML entities solely to escape characters in the tool parameters.
  28#[derive(Debug, Serialize, Deserialize, JsonSchema)]
  29pub struct GrepToolInput {
  30    /// A regex pattern to search for in the entire project. Note that the regex will be parsed by the Rust `regex` crate.
  31    ///
  32    /// Do NOT specify a path here! This will only be matched against the code **content**.
  33    pub regex: String,
  34    /// A glob pattern for the paths of files to include in the search.
  35    /// Supports standard glob patterns like "**/*.rs" or "src/**/*.ts".
  36    /// If omitted, all files in the project will be searched.
  37    pub include_pattern: Option<String>,
  38    /// Optional starting position for paginated results (0-based).
  39    /// When not provided, starts from the beginning.
  40    #[serde(default)]
  41    pub offset: u32,
  42    /// Whether the regex is case-sensitive. Defaults to false (case-insensitive).
  43    #[serde(default)]
  44    pub case_sensitive: bool,
  45}
  46
  47impl GrepToolInput {
  48    /// Which page of search results this is.
  49    pub fn page(&self) -> u32 {
  50        1 + (self.offset / RESULTS_PER_PAGE)
  51    }
  52}
  53
  54const RESULTS_PER_PAGE: u32 = 20;
  55
  56pub struct GrepTool {
  57    project: Entity<Project>,
  58}
  59
  60impl GrepTool {
  61    pub fn new(project: Entity<Project>) -> Self {
  62        Self { project }
  63    }
  64}
  65
  66impl AgentTool for GrepTool {
  67    type Input = GrepToolInput;
  68    type Output = String;
  69
  70    fn name() -> &'static str {
  71        "grep"
  72    }
  73
  74    fn kind() -> acp::ToolKind {
  75        acp::ToolKind::Search
  76    }
  77
  78    fn initial_title(
  79        &self,
  80        input: Result<Self::Input, serde_json::Value>,
  81        _cx: &mut App,
  82    ) -> SharedString {
  83        match input {
  84            Ok(input) => {
  85                let page = input.page();
  86                let regex_str = MarkdownInlineCode(&input.regex);
  87                let case_info = if input.case_sensitive {
  88                    " (case-sensitive)"
  89                } else {
  90                    ""
  91                };
  92
  93                if page > 1 {
  94                    format!("Get page {page} of search results for regex {regex_str}{case_info}")
  95                } else {
  96                    format!("Search files for regex {regex_str}{case_info}")
  97                }
  98            }
  99            Err(_) => "Search with regex".into(),
 100        }
 101        .into()
 102    }
 103
 104    fn run(
 105        self: Arc<Self>,
 106        input: Self::Input,
 107        _event_stream: ToolCallEventStream,
 108        cx: &mut App,
 109    ) -> Task<Result<Self::Output>> {
 110        const CONTEXT_LINES: u32 = 2;
 111        const MAX_ANCESTOR_LINES: u32 = 10;
 112
 113        let path_style = self.project.read(cx).path_style(cx);
 114
 115        let include_matcher = match PathMatcher::new(
 116            input
 117                .include_pattern
 118                .as_ref()
 119                .into_iter()
 120                .collect::<Vec<_>>(),
 121            path_style,
 122        ) {
 123            Ok(matcher) => matcher,
 124            Err(error) => {
 125                return Task::ready(Err(anyhow!("invalid include glob pattern: {error}")));
 126            }
 127        };
 128
 129        // Exclude global file_scan_exclusions and private_files settings
 130        let exclude_matcher = {
 131            let global_settings = WorktreeSettings::get_global(cx);
 132            let exclude_patterns = global_settings
 133                .file_scan_exclusions
 134                .sources()
 135                .iter()
 136                .chain(global_settings.private_files.sources().iter());
 137
 138            match PathMatcher::new(exclude_patterns, path_style) {
 139                Ok(matcher) => matcher,
 140                Err(error) => {
 141                    return Task::ready(Err(anyhow!("invalid exclude pattern: {error}")));
 142                }
 143            }
 144        };
 145
 146        let query = match SearchQuery::regex(
 147            &input.regex,
 148            false,
 149            input.case_sensitive,
 150            false,
 151            false,
 152            include_matcher,
 153            exclude_matcher,
 154            true, // Always match file include pattern against *full project paths* that start with a project root.
 155            None,
 156        ) {
 157            Ok(query) => query,
 158            Err(error) => return Task::ready(Err(error)),
 159        };
 160
 161        let results = self
 162            .project
 163            .update(cx, |project, cx| project.search(query, cx));
 164
 165        let project = self.project.downgrade();
 166        cx.spawn(async move |cx|  {
 167            futures::pin_mut!(results);
 168
 169            let mut output = String::new();
 170            let mut skips_remaining = input.offset;
 171            let mut matches_found = 0;
 172            let mut has_more_matches = false;
 173
 174            'outer: while let Some(SearchResult::Buffer { buffer, ranges }) = results.next().await {
 175                if ranges.is_empty() {
 176                    continue;
 177                }
 178
 179                let Ok((Some(path), mut parse_status)) = buffer.read_with(cx, |buffer, cx| {
 180                    (buffer.file().map(|file| file.full_path(cx)), buffer.parse_status())
 181                }) else {
 182                    continue;
 183                };
 184
 185                // Check if this file should be excluded based on its worktree settings
 186                if let Ok(Some(project_path)) = project.read_with(cx, |project, cx| {
 187                    project.find_project_path(&path, cx)
 188                })
 189                    && cx.update(|cx| {
 190                        let worktree_settings = WorktreeSettings::get(Some((&project_path).into()), cx);
 191                        worktree_settings.is_path_excluded(&project_path.path)
 192                            || worktree_settings.is_path_private(&project_path.path)
 193                    }).unwrap_or(false) {
 194                        continue;
 195                    }
 196
 197                while *parse_status.borrow() != ParseStatus::Idle {
 198                    parse_status.changed().await?;
 199                }
 200
 201                let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 202
 203                let mut ranges = ranges
 204                    .into_iter()
 205                    .map(|range| {
 206                        let matched = range.to_point(&snapshot);
 207                        let matched_end_line_len = snapshot.line_len(matched.end.row);
 208                        let full_lines = Point::new(matched.start.row, 0)..Point::new(matched.end.row, matched_end_line_len);
 209                        let symbols = snapshot.symbols_containing(matched.start, None);
 210
 211                        if let Some(ancestor_node) = snapshot.syntax_ancestor(full_lines.clone()) {
 212                            let full_ancestor_range = ancestor_node.byte_range().to_point(&snapshot);
 213                            let end_row = full_ancestor_range.end.row.min(full_ancestor_range.start.row + MAX_ANCESTOR_LINES);
 214                            let end_col = snapshot.line_len(end_row);
 215                            let capped_ancestor_range = Point::new(full_ancestor_range.start.row, 0)..Point::new(end_row, end_col);
 216
 217                            if capped_ancestor_range.contains_inclusive(&full_lines) {
 218                                return (capped_ancestor_range, Some(full_ancestor_range), symbols)
 219                            }
 220                        }
 221
 222                        let mut matched = matched;
 223                        matched.start.column = 0;
 224                        matched.start.row =
 225                            matched.start.row.saturating_sub(CONTEXT_LINES);
 226                        matched.end.row = cmp::min(
 227                            snapshot.max_point().row,
 228                            matched.end.row + CONTEXT_LINES,
 229                        );
 230                        matched.end.column = snapshot.line_len(matched.end.row);
 231
 232                        (matched, None, symbols)
 233                    })
 234                    .peekable();
 235
 236                let mut file_header_written = false;
 237
 238                while let Some((mut range, ancestor_range, parent_symbols)) = ranges.next(){
 239                    if skips_remaining > 0 {
 240                        skips_remaining -= 1;
 241                        continue;
 242                    }
 243
 244                    // We'd already found a full page of matches, and we just found one more.
 245                    if matches_found >= RESULTS_PER_PAGE {
 246                        has_more_matches = true;
 247                        break 'outer;
 248                    }
 249
 250                    while let Some((next_range, _, _)) = ranges.peek() {
 251                        if range.end.row >= next_range.start.row {
 252                            range.end = next_range.end;
 253                            ranges.next();
 254                        } else {
 255                            break;
 256                        }
 257                    }
 258
 259                    if !file_header_written {
 260                        writeln!(output, "\n## Matches in {}", path.display())?;
 261                        file_header_written = true;
 262                    }
 263
 264                    let end_row = range.end.row;
 265                    output.push_str("\n### ");
 266
 267                    for symbol in parent_symbols {
 268                        write!(output, "{} › ", symbol.text)?;
 269                    }
 270
 271                    if range.start.row == end_row {
 272                        writeln!(output, "L{}", range.start.row + 1)?;
 273                    } else {
 274                        writeln!(output, "L{}-{}", range.start.row + 1, end_row + 1)?;
 275                    }
 276
 277                    output.push_str("```\n");
 278                    output.extend(snapshot.text_for_range(range));
 279                    output.push_str("\n```\n");
 280
 281                    if let Some(ancestor_range) = ancestor_range
 282                        && end_row < ancestor_range.end.row {
 283                            let remaining_lines = ancestor_range.end.row - end_row;
 284                            writeln!(output, "\n{} lines remaining in ancestor node. Read the file to see all.", remaining_lines)?;
 285                        }
 286
 287                    matches_found += 1;
 288                }
 289            }
 290
 291            if matches_found == 0 {
 292                Ok("No matches found".into())
 293            } else if has_more_matches {
 294                Ok(format!(
 295                    "Showing matches {}-{} (there were more matches found; use offset: {} to see next page):\n{output}",
 296                    input.offset + 1,
 297                    input.offset + matches_found,
 298                    input.offset + RESULTS_PER_PAGE,
 299                ))
 300            } else {
 301                Ok(format!("Found {matches_found} matches:\n{output}"))
 302            }
 303        })
 304    }
 305}
 306
 307#[cfg(test)]
 308mod tests {
 309    use crate::ToolCallEventStream;
 310
 311    use super::*;
 312    use gpui::{TestAppContext, UpdateGlobal};
 313    use language::{Language, LanguageConfig, LanguageMatcher};
 314    use project::{FakeFs, Project};
 315    use serde_json::json;
 316    use settings::SettingsStore;
 317    use unindent::Unindent;
 318    use util::path;
 319
 320    #[gpui::test]
 321    async fn test_grep_tool_with_include_pattern(cx: &mut TestAppContext) {
 322        init_test(cx);
 323        cx.executor().allow_parking();
 324
 325        let fs = FakeFs::new(cx.executor());
 326        fs.insert_tree(
 327            path!("/root"),
 328            serde_json::json!({
 329                "src": {
 330                    "main.rs": "fn main() {\n    println!(\"Hello, world!\");\n}",
 331                    "utils": {
 332                        "helper.rs": "fn helper() {\n    println!(\"I'm a helper!\");\n}",
 333                    },
 334                },
 335                "tests": {
 336                    "test_main.rs": "fn test_main() {\n    assert!(true);\n}",
 337                }
 338            }),
 339        )
 340        .await;
 341
 342        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 343
 344        // Test with include pattern for Rust files inside the root of the project
 345        let input = GrepToolInput {
 346            regex: "println".to_string(),
 347            include_pattern: Some("root/**/*.rs".to_string()),
 348            offset: 0,
 349            case_sensitive: false,
 350        };
 351
 352        let result = run_grep_tool(input, project.clone(), cx).await;
 353        assert!(result.contains("main.rs"), "Should find matches in main.rs");
 354        assert!(
 355            result.contains("helper.rs"),
 356            "Should find matches in helper.rs"
 357        );
 358        assert!(
 359            !result.contains("test_main.rs"),
 360            "Should not include test_main.rs even though it's a .rs file (because it doesn't have the pattern)"
 361        );
 362
 363        // Test with include pattern for src directory only
 364        let input = GrepToolInput {
 365            regex: "fn".to_string(),
 366            include_pattern: Some("root/**/src/**".to_string()),
 367            offset: 0,
 368            case_sensitive: false,
 369        };
 370
 371        let result = run_grep_tool(input, project.clone(), cx).await;
 372        assert!(
 373            result.contains("main.rs"),
 374            "Should find matches in src/main.rs"
 375        );
 376        assert!(
 377            result.contains("helper.rs"),
 378            "Should find matches in src/utils/helper.rs"
 379        );
 380        assert!(
 381            !result.contains("test_main.rs"),
 382            "Should not include test_main.rs as it's not in src directory"
 383        );
 384
 385        // Test with empty include pattern (should default to all files)
 386        let input = GrepToolInput {
 387            regex: "fn".to_string(),
 388            include_pattern: None,
 389            offset: 0,
 390            case_sensitive: false,
 391        };
 392
 393        let result = run_grep_tool(input, project.clone(), cx).await;
 394        assert!(result.contains("main.rs"), "Should find matches in main.rs");
 395        assert!(
 396            result.contains("helper.rs"),
 397            "Should find matches in helper.rs"
 398        );
 399        assert!(
 400            result.contains("test_main.rs"),
 401            "Should include test_main.rs"
 402        );
 403    }
 404
 405    #[gpui::test]
 406    async fn test_grep_tool_with_case_sensitivity(cx: &mut TestAppContext) {
 407        init_test(cx);
 408        cx.executor().allow_parking();
 409
 410        let fs = FakeFs::new(cx.executor());
 411        fs.insert_tree(
 412            path!("/root"),
 413            serde_json::json!({
 414                "case_test.txt": "This file has UPPERCASE and lowercase text.\nUPPERCASE patterns should match only with case_sensitive: true",
 415            }),
 416        )
 417        .await;
 418
 419        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 420
 421        // Test case-insensitive search (default)
 422        let input = GrepToolInput {
 423            regex: "uppercase".to_string(),
 424            include_pattern: Some("**/*.txt".to_string()),
 425            offset: 0,
 426            case_sensitive: false,
 427        };
 428
 429        let result = run_grep_tool(input, project.clone(), cx).await;
 430        assert!(
 431            result.contains("UPPERCASE"),
 432            "Case-insensitive search should match uppercase"
 433        );
 434
 435        // Test case-sensitive search
 436        let input = GrepToolInput {
 437            regex: "uppercase".to_string(),
 438            include_pattern: Some("**/*.txt".to_string()),
 439            offset: 0,
 440            case_sensitive: true,
 441        };
 442
 443        let result = run_grep_tool(input, project.clone(), cx).await;
 444        assert!(
 445            !result.contains("UPPERCASE"),
 446            "Case-sensitive search should not match uppercase"
 447        );
 448
 449        // Test case-sensitive search
 450        let input = GrepToolInput {
 451            regex: "LOWERCASE".to_string(),
 452            include_pattern: Some("**/*.txt".to_string()),
 453            offset: 0,
 454            case_sensitive: true,
 455        };
 456
 457        let result = run_grep_tool(input, project.clone(), cx).await;
 458
 459        assert!(
 460            !result.contains("lowercase"),
 461            "Case-sensitive search should match lowercase"
 462        );
 463
 464        // Test case-sensitive search for lowercase pattern
 465        let input = GrepToolInput {
 466            regex: "lowercase".to_string(),
 467            include_pattern: Some("**/*.txt".to_string()),
 468            offset: 0,
 469            case_sensitive: true,
 470        };
 471
 472        let result = run_grep_tool(input, project.clone(), cx).await;
 473        assert!(
 474            result.contains("lowercase"),
 475            "Case-sensitive search should match lowercase text"
 476        );
 477    }
 478
 479    /// Helper function to set up a syntax test environment
 480    async fn setup_syntax_test(cx: &mut TestAppContext) -> Entity<Project> {
 481        use unindent::Unindent;
 482        init_test(cx);
 483        cx.executor().allow_parking();
 484
 485        let fs = FakeFs::new(cx.executor());
 486
 487        // Create test file with syntax structures
 488        fs.insert_tree(
 489            path!("/root"),
 490            serde_json::json!({
 491                "test_syntax.rs": r#"
 492                    fn top_level_function() {
 493                        println!("This is at the top level");
 494                    }
 495
 496                    mod feature_module {
 497                        pub mod nested_module {
 498                            pub fn nested_function(
 499                                first_arg: String,
 500                                second_arg: i32,
 501                            ) {
 502                                println!("Function in nested module");
 503                                println!("{first_arg}");
 504                                println!("{second_arg}");
 505                            }
 506                        }
 507                    }
 508
 509                    struct MyStruct {
 510                        field1: String,
 511                        field2: i32,
 512                    }
 513
 514                    impl MyStruct {
 515                        fn method_with_block() {
 516                            let condition = true;
 517                            if condition {
 518                                println!("Inside if block");
 519                            }
 520                        }
 521
 522                        fn long_function() {
 523                            println!("Line 1");
 524                            println!("Line 2");
 525                            println!("Line 3");
 526                            println!("Line 4");
 527                            println!("Line 5");
 528                            println!("Line 6");
 529                            println!("Line 7");
 530                            println!("Line 8");
 531                            println!("Line 9");
 532                            println!("Line 10");
 533                            println!("Line 11");
 534                            println!("Line 12");
 535                        }
 536                    }
 537
 538                    trait Processor {
 539                        fn process(&self, input: &str) -> String;
 540                    }
 541
 542                    impl Processor for MyStruct {
 543                        fn process(&self, input: &str) -> String {
 544                            format!("Processed: {}", input)
 545                        }
 546                    }
 547                "#.unindent().trim(),
 548            }),
 549        )
 550        .await;
 551
 552        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 553
 554        project.update(cx, |project, _cx| {
 555            project.languages().add(rust_lang().into())
 556        });
 557
 558        project
 559    }
 560
 561    #[gpui::test]
 562    async fn test_grep_top_level_function(cx: &mut TestAppContext) {
 563        let project = setup_syntax_test(cx).await;
 564
 565        // Test: Line at the top level of the file
 566        let input = GrepToolInput {
 567            regex: "This is at the top level".to_string(),
 568            include_pattern: Some("**/*.rs".to_string()),
 569            offset: 0,
 570            case_sensitive: false,
 571        };
 572
 573        let result = run_grep_tool(input, project.clone(), cx).await;
 574        let expected = r#"
 575            Found 1 matches:
 576
 577            ## Matches in root/test_syntax.rs
 578
 579            ### fn top_level_function › L1-3
 580            ```
 581            fn top_level_function() {
 582                println!("This is at the top level");
 583            }
 584            ```
 585            "#
 586        .unindent();
 587        assert_eq!(result, expected);
 588    }
 589
 590    #[gpui::test]
 591    async fn test_grep_function_body(cx: &mut TestAppContext) {
 592        let project = setup_syntax_test(cx).await;
 593
 594        // Test: Line inside a function body
 595        let input = GrepToolInput {
 596            regex: "Function in nested module".to_string(),
 597            include_pattern: Some("**/*.rs".to_string()),
 598            offset: 0,
 599            case_sensitive: false,
 600        };
 601
 602        let result = run_grep_tool(input, project.clone(), cx).await;
 603        let expected = r#"
 604            Found 1 matches:
 605
 606            ## Matches in root/test_syntax.rs
 607
 608            ### mod feature_module › pub mod nested_module › pub fn nested_function › L10-14
 609            ```
 610                    ) {
 611                        println!("Function in nested module");
 612                        println!("{first_arg}");
 613                        println!("{second_arg}");
 614                    }
 615            ```
 616            "#
 617        .unindent();
 618        assert_eq!(result, expected);
 619    }
 620
 621    #[gpui::test]
 622    async fn test_grep_function_args_and_body(cx: &mut TestAppContext) {
 623        let project = setup_syntax_test(cx).await;
 624
 625        // Test: Line with a function argument
 626        let input = GrepToolInput {
 627            regex: "second_arg".to_string(),
 628            include_pattern: Some("**/*.rs".to_string()),
 629            offset: 0,
 630            case_sensitive: false,
 631        };
 632
 633        let result = run_grep_tool(input, project.clone(), cx).await;
 634        let expected = r#"
 635            Found 1 matches:
 636
 637            ## Matches in root/test_syntax.rs
 638
 639            ### mod feature_module › pub mod nested_module › pub fn nested_function › L7-14
 640            ```
 641                    pub fn nested_function(
 642                        first_arg: String,
 643                        second_arg: i32,
 644                    ) {
 645                        println!("Function in nested module");
 646                        println!("{first_arg}");
 647                        println!("{second_arg}");
 648                    }
 649            ```
 650            "#
 651        .unindent();
 652        assert_eq!(result, expected);
 653    }
 654
 655    #[gpui::test]
 656    async fn test_grep_if_block(cx: &mut TestAppContext) {
 657        use unindent::Unindent;
 658        let project = setup_syntax_test(cx).await;
 659
 660        // Test: Line inside an if block
 661        let input = GrepToolInput {
 662            regex: "Inside if block".to_string(),
 663            include_pattern: Some("**/*.rs".to_string()),
 664            offset: 0,
 665            case_sensitive: false,
 666        };
 667
 668        let result = run_grep_tool(input, project.clone(), cx).await;
 669        let expected = r#"
 670            Found 1 matches:
 671
 672            ## Matches in root/test_syntax.rs
 673
 674            ### impl MyStruct › fn method_with_block › L26-28
 675            ```
 676                    if condition {
 677                        println!("Inside if block");
 678                    }
 679            ```
 680            "#
 681        .unindent();
 682        assert_eq!(result, expected);
 683    }
 684
 685    #[gpui::test]
 686    async fn test_grep_long_function_top(cx: &mut TestAppContext) {
 687        use unindent::Unindent;
 688        let project = setup_syntax_test(cx).await;
 689
 690        // Test: Line in the middle of a long function - should show message about remaining lines
 691        let input = GrepToolInput {
 692            regex: "Line 5".to_string(),
 693            include_pattern: Some("**/*.rs".to_string()),
 694            offset: 0,
 695            case_sensitive: false,
 696        };
 697
 698        let result = run_grep_tool(input, project.clone(), cx).await;
 699        let expected = r#"
 700            Found 1 matches:
 701
 702            ## Matches in root/test_syntax.rs
 703
 704            ### impl MyStruct › fn long_function › L31-41
 705            ```
 706                fn long_function() {
 707                    println!("Line 1");
 708                    println!("Line 2");
 709                    println!("Line 3");
 710                    println!("Line 4");
 711                    println!("Line 5");
 712                    println!("Line 6");
 713                    println!("Line 7");
 714                    println!("Line 8");
 715                    println!("Line 9");
 716                    println!("Line 10");
 717            ```
 718
 719            3 lines remaining in ancestor node. Read the file to see all.
 720            "#
 721        .unindent();
 722        assert_eq!(result, expected);
 723    }
 724
 725    #[gpui::test]
 726    async fn test_grep_long_function_bottom(cx: &mut TestAppContext) {
 727        use unindent::Unindent;
 728        let project = setup_syntax_test(cx).await;
 729
 730        // Test: Line in the long function
 731        let input = GrepToolInput {
 732            regex: "Line 12".to_string(),
 733            include_pattern: Some("**/*.rs".to_string()),
 734            offset: 0,
 735            case_sensitive: false,
 736        };
 737
 738        let result = run_grep_tool(input, project.clone(), cx).await;
 739        let expected = r#"
 740            Found 1 matches:
 741
 742            ## Matches in root/test_syntax.rs
 743
 744            ### impl MyStruct › fn long_function › L41-45
 745            ```
 746                    println!("Line 10");
 747                    println!("Line 11");
 748                    println!("Line 12");
 749                }
 750            }
 751            ```
 752            "#
 753        .unindent();
 754        assert_eq!(result, expected);
 755    }
 756
 757    async fn run_grep_tool(
 758        input: GrepToolInput,
 759        project: Entity<Project>,
 760        cx: &mut TestAppContext,
 761    ) -> String {
 762        let tool = Arc::new(GrepTool { project });
 763        let task = cx.update(|cx| tool.run(input, ToolCallEventStream::test().0, cx));
 764
 765        match task.await {
 766            Ok(result) => {
 767                if cfg!(windows) {
 768                    result.replace("root\\", "root/")
 769                } else {
 770                    result
 771                }
 772            }
 773            Err(e) => panic!("Failed to run grep tool: {}", e),
 774        }
 775    }
 776
 777    fn init_test(cx: &mut TestAppContext) {
 778        cx.update(|cx| {
 779            let settings_store = SettingsStore::test(cx);
 780            cx.set_global(settings_store);
 781        });
 782    }
 783
 784    fn rust_lang() -> Language {
 785        Language::new(
 786            LanguageConfig {
 787                name: "Rust".into(),
 788                matcher: LanguageMatcher {
 789                    path_suffixes: vec!["rs".to_string()],
 790                    ..Default::default()
 791                },
 792                ..Default::default()
 793            },
 794            Some(tree_sitter_rust::LANGUAGE.into()),
 795        )
 796        .with_outline_query(include_str!("../../../languages/src/rust/outline.scm"))
 797        .unwrap()
 798    }
 799
 800    #[gpui::test]
 801    async fn test_grep_security_boundaries(cx: &mut TestAppContext) {
 802        init_test(cx);
 803
 804        let fs = FakeFs::new(cx.executor());
 805
 806        fs.insert_tree(
 807            path!("/"),
 808            json!({
 809                "project_root": {
 810                    "allowed_file.rs": "fn main() { println!(\"This file is in the project\"); }",
 811                    ".mysecrets": "SECRET_KEY=abc123\nfn secret() { /* private */ }",
 812                    ".secretdir": {
 813                        "config": "fn special_configuration() { /* excluded */ }"
 814                    },
 815                    ".mymetadata": "fn custom_metadata() { /* excluded */ }",
 816                    "subdir": {
 817                        "normal_file.rs": "fn normal_file_content() { /* Normal */ }",
 818                        "special.privatekey": "fn private_key_content() { /* private */ }",
 819                        "data.mysensitive": "fn sensitive_data() { /* private */ }"
 820                    }
 821                },
 822                "outside_project": {
 823                    "sensitive_file.rs": "fn outside_function() { /* This file is outside the project */ }"
 824                }
 825            }),
 826        )
 827        .await;
 828
 829        cx.update(|cx| {
 830            use gpui::UpdateGlobal;
 831            use settings::SettingsStore;
 832            SettingsStore::update_global(cx, |store, cx| {
 833                store.update_user_settings(cx, |settings| {
 834                    settings.project.worktree.file_scan_exclusions = Some(vec![
 835                        "**/.secretdir".to_string(),
 836                        "**/.mymetadata".to_string(),
 837                    ]);
 838                    settings.project.worktree.private_files = Some(
 839                        vec![
 840                            "**/.mysecrets".to_string(),
 841                            "**/*.privatekey".to_string(),
 842                            "**/*.mysensitive".to_string(),
 843                        ]
 844                        .into(),
 845                    );
 846                });
 847            });
 848        });
 849
 850        let project = Project::test(fs.clone(), [path!("/project_root").as_ref()], cx).await;
 851
 852        // Searching for files outside the project worktree should return no results
 853        let result = run_grep_tool(
 854            GrepToolInput {
 855                regex: "outside_function".to_string(),
 856                include_pattern: None,
 857                offset: 0,
 858                case_sensitive: false,
 859            },
 860            project.clone(),
 861            cx,
 862        )
 863        .await;
 864        let paths = extract_paths_from_results(&result);
 865        assert!(
 866            paths.is_empty(),
 867            "grep_tool should not find files outside the project worktree"
 868        );
 869
 870        // Searching within the project should succeed
 871        let result = run_grep_tool(
 872            GrepToolInput {
 873                regex: "main".to_string(),
 874                include_pattern: None,
 875                offset: 0,
 876                case_sensitive: false,
 877            },
 878            project.clone(),
 879            cx,
 880        )
 881        .await;
 882        let paths = extract_paths_from_results(&result);
 883        assert!(
 884            paths.iter().any(|p| p.contains("allowed_file.rs")),
 885            "grep_tool should be able to search files inside worktrees"
 886        );
 887
 888        // Searching files that match file_scan_exclusions should return no results
 889        let result = run_grep_tool(
 890            GrepToolInput {
 891                regex: "special_configuration".to_string(),
 892                include_pattern: None,
 893                offset: 0,
 894                case_sensitive: false,
 895            },
 896            project.clone(),
 897            cx,
 898        )
 899        .await;
 900        let paths = extract_paths_from_results(&result);
 901        assert!(
 902            paths.is_empty(),
 903            "grep_tool should not search files in .secretdir (file_scan_exclusions)"
 904        );
 905
 906        let result = run_grep_tool(
 907            GrepToolInput {
 908                regex: "custom_metadata".to_string(),
 909                include_pattern: None,
 910                offset: 0,
 911                case_sensitive: false,
 912            },
 913            project.clone(),
 914            cx,
 915        )
 916        .await;
 917        let paths = extract_paths_from_results(&result);
 918        assert!(
 919            paths.is_empty(),
 920            "grep_tool should not search .mymetadata files (file_scan_exclusions)"
 921        );
 922
 923        // Searching private files should return no results
 924        let result = run_grep_tool(
 925            GrepToolInput {
 926                regex: "SECRET_KEY".to_string(),
 927                include_pattern: None,
 928                offset: 0,
 929                case_sensitive: false,
 930            },
 931            project.clone(),
 932            cx,
 933        )
 934        .await;
 935        let paths = extract_paths_from_results(&result);
 936        assert!(
 937            paths.is_empty(),
 938            "grep_tool should not search .mysecrets (private_files)"
 939        );
 940
 941        let result = run_grep_tool(
 942            GrepToolInput {
 943                regex: "private_key_content".to_string(),
 944                include_pattern: None,
 945                offset: 0,
 946                case_sensitive: false,
 947            },
 948            project.clone(),
 949            cx,
 950        )
 951        .await;
 952        let paths = extract_paths_from_results(&result);
 953
 954        assert!(
 955            paths.is_empty(),
 956            "grep_tool should not search .privatekey files (private_files)"
 957        );
 958
 959        let result = run_grep_tool(
 960            GrepToolInput {
 961                regex: "sensitive_data".to_string(),
 962                include_pattern: None,
 963                offset: 0,
 964                case_sensitive: false,
 965            },
 966            project.clone(),
 967            cx,
 968        )
 969        .await;
 970        let paths = extract_paths_from_results(&result);
 971        assert!(
 972            paths.is_empty(),
 973            "grep_tool should not search .mysensitive files (private_files)"
 974        );
 975
 976        // Searching a normal file should still work, even with private_files configured
 977        let result = run_grep_tool(
 978            GrepToolInput {
 979                regex: "normal_file_content".to_string(),
 980                include_pattern: None,
 981                offset: 0,
 982                case_sensitive: false,
 983            },
 984            project.clone(),
 985            cx,
 986        )
 987        .await;
 988        let paths = extract_paths_from_results(&result);
 989        assert!(
 990            paths.iter().any(|p| p.contains("normal_file.rs")),
 991            "Should be able to search normal files"
 992        );
 993
 994        // Path traversal attempts with .. in include_pattern should not escape project
 995        let result = run_grep_tool(
 996            GrepToolInput {
 997                regex: "outside_function".to_string(),
 998                include_pattern: Some("../outside_project/**/*.rs".to_string()),
 999                offset: 0,
1000                case_sensitive: false,
1001            },
1002            project.clone(),
1003            cx,
1004        )
1005        .await;
1006        let paths = extract_paths_from_results(&result);
1007        assert!(
1008            paths.is_empty(),
1009            "grep_tool should not allow escaping project boundaries with relative paths"
1010        );
1011    }
1012
1013    #[gpui::test]
1014    async fn test_grep_with_multiple_worktree_settings(cx: &mut TestAppContext) {
1015        init_test(cx);
1016
1017        let fs = FakeFs::new(cx.executor());
1018
1019        // Create first worktree with its own private files
1020        fs.insert_tree(
1021            path!("/worktree1"),
1022            json!({
1023                ".zed": {
1024                    "settings.json": r#"{
1025                        "file_scan_exclusions": ["**/fixture.*"],
1026                        "private_files": ["**/secret.rs"]
1027                    }"#
1028                },
1029                "src": {
1030                    "main.rs": "fn main() { let secret_key = \"hidden\"; }",
1031                    "secret.rs": "const API_KEY: &str = \"secret_value\";",
1032                    "utils.rs": "pub fn get_config() -> String { \"config\".to_string() }"
1033                },
1034                "tests": {
1035                    "test.rs": "fn test_secret() { assert!(true); }",
1036                    "fixture.sql": "SELECT * FROM secret_table;"
1037                }
1038            }),
1039        )
1040        .await;
1041
1042        // Create second worktree with different private files
1043        fs.insert_tree(
1044            path!("/worktree2"),
1045            json!({
1046                ".zed": {
1047                    "settings.json": r#"{
1048                        "file_scan_exclusions": ["**/internal.*"],
1049                        "private_files": ["**/private.js", "**/data.json"]
1050                    }"#
1051                },
1052                "lib": {
1053                    "public.js": "export function getSecret() { return 'public'; }",
1054                    "private.js": "const SECRET_KEY = \"private_value\";",
1055                    "data.json": "{\"secret_data\": \"hidden\"}"
1056                },
1057                "docs": {
1058                    "README.md": "# Documentation with secret info",
1059                    "internal.md": "Internal secret documentation"
1060                }
1061            }),
1062        )
1063        .await;
1064
1065        // Set global settings
1066        cx.update(|cx| {
1067            SettingsStore::update_global(cx, |store, cx| {
1068                store.update_user_settings(cx, |settings| {
1069                    settings.project.worktree.file_scan_exclusions =
1070                        Some(vec!["**/.git".to_string(), "**/node_modules".to_string()]);
1071                    settings.project.worktree.private_files =
1072                        Some(vec!["**/.env".to_string()].into());
1073                });
1074            });
1075        });
1076
1077        let project = Project::test(
1078            fs.clone(),
1079            [path!("/worktree1").as_ref(), path!("/worktree2").as_ref()],
1080            cx,
1081        )
1082        .await;
1083
1084        // Wait for worktrees to be fully scanned
1085        cx.executor().run_until_parked();
1086
1087        // Search for "secret" - should exclude files based on worktree-specific settings
1088        let result = run_grep_tool(
1089            GrepToolInput {
1090                regex: "secret".to_string(),
1091                include_pattern: None,
1092                offset: 0,
1093                case_sensitive: false,
1094            },
1095            project.clone(),
1096            cx,
1097        )
1098        .await;
1099        let paths = extract_paths_from_results(&result);
1100
1101        // Should find matches in non-private files
1102        assert!(
1103            paths.iter().any(|p| p.contains("main.rs")),
1104            "Should find 'secret' in worktree1/src/main.rs"
1105        );
1106        assert!(
1107            paths.iter().any(|p| p.contains("test.rs")),
1108            "Should find 'secret' in worktree1/tests/test.rs"
1109        );
1110        assert!(
1111            paths.iter().any(|p| p.contains("public.js")),
1112            "Should find 'secret' in worktree2/lib/public.js"
1113        );
1114        assert!(
1115            paths.iter().any(|p| p.contains("README.md")),
1116            "Should find 'secret' in worktree2/docs/README.md"
1117        );
1118
1119        // Should NOT find matches in private/excluded files based on worktree settings
1120        assert!(
1121            !paths.iter().any(|p| p.contains("secret.rs")),
1122            "Should not search in worktree1/src/secret.rs (local private_files)"
1123        );
1124        assert!(
1125            !paths.iter().any(|p| p.contains("fixture.sql")),
1126            "Should not search in worktree1/tests/fixture.sql (local file_scan_exclusions)"
1127        );
1128        assert!(
1129            !paths.iter().any(|p| p.contains("private.js")),
1130            "Should not search in worktree2/lib/private.js (local private_files)"
1131        );
1132        assert!(
1133            !paths.iter().any(|p| p.contains("data.json")),
1134            "Should not search in worktree2/lib/data.json (local private_files)"
1135        );
1136        assert!(
1137            !paths.iter().any(|p| p.contains("internal.md")),
1138            "Should not search in worktree2/docs/internal.md (local file_scan_exclusions)"
1139        );
1140
1141        // Test with `include_pattern` specific to one worktree
1142        let result = run_grep_tool(
1143            GrepToolInput {
1144                regex: "secret".to_string(),
1145                include_pattern: Some("worktree1/**/*.rs".to_string()),
1146                offset: 0,
1147                case_sensitive: false,
1148            },
1149            project.clone(),
1150            cx,
1151        )
1152        .await;
1153
1154        let paths = extract_paths_from_results(&result);
1155
1156        // Should only find matches in worktree1 *.rs files (excluding private ones)
1157        assert!(
1158            paths.iter().any(|p| p.contains("main.rs")),
1159            "Should find match in worktree1/src/main.rs"
1160        );
1161        assert!(
1162            paths.iter().any(|p| p.contains("test.rs")),
1163            "Should find match in worktree1/tests/test.rs"
1164        );
1165        assert!(
1166            !paths.iter().any(|p| p.contains("secret.rs")),
1167            "Should not find match in excluded worktree1/src/secret.rs"
1168        );
1169        assert!(
1170            paths.iter().all(|p| !p.contains("worktree2")),
1171            "Should not find any matches in worktree2"
1172        );
1173    }
1174
1175    // Helper function to extract file paths from grep results
1176    fn extract_paths_from_results(results: &str) -> Vec<String> {
1177        results
1178            .lines()
1179            .filter(|line| line.starts_with("## Matches in "))
1180            .map(|line| {
1181                line.strip_prefix("## Matches in ")
1182                    .unwrap()
1183                    .trim()
1184                    .to_string()
1185            })
1186            .collect()
1187    }
1188}