read_file_tool.rs

  1use action_log::ActionLog;
  2use agent_client_protocol::{self as acp, ToolCallUpdateFields};
  3use anyhow::{Context as _, Result, anyhow};
  4use gpui::{App, Entity, SharedString, Task};
  5use indoc::formatdoc;
  6use language::Point;
  7use language_model::{LanguageModelImage, LanguageModelToolResultContent};
  8use project::{AgentLocation, ImageItem, Project, WorktreeSettings, image_store};
  9use schemars::JsonSchema;
 10use serde::{Deserialize, Serialize};
 11use settings::Settings;
 12use std::sync::Arc;
 13use util::markdown::MarkdownCodeBlock;
 14
 15use crate::{AgentTool, ToolCallEventStream, outline};
 16
 17/// Reads the content of the given file in the project.
 18///
 19/// - Never attempt to read a path that hasn't been previously mentioned.
 20#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 21pub struct ReadFileToolInput {
 22    /// The relative path of the file to read.
 23    ///
 24    /// This path should never be absolute, and the first component of the path should always be a root directory in a project.
 25    ///
 26    /// <example>
 27    /// If the project has the following root directories:
 28    ///
 29    /// - /a/b/directory1
 30    /// - /c/d/directory2
 31    ///
 32    /// If you want to access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.
 33    /// If you want to access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.
 34    /// </example>
 35    pub path: String,
 36    /// Optional line number to start reading on (1-based index)
 37    #[serde(default)]
 38    pub start_line: Option<u32>,
 39    /// Optional line number to end reading on (1-based index, inclusive)
 40    #[serde(default)]
 41    pub end_line: Option<u32>,
 42}
 43
 44pub struct ReadFileTool {
 45    project: Entity<Project>,
 46    action_log: Entity<ActionLog>,
 47}
 48
 49impl ReadFileTool {
 50    pub fn new(project: Entity<Project>, action_log: Entity<ActionLog>) -> Self {
 51        Self {
 52            project,
 53            action_log,
 54        }
 55    }
 56}
 57
 58impl AgentTool for ReadFileTool {
 59    type Input = ReadFileToolInput;
 60    type Output = LanguageModelToolResultContent;
 61
 62    fn name() -> &'static str {
 63        "read_file"
 64    }
 65
 66    fn kind() -> acp::ToolKind {
 67        acp::ToolKind::Read
 68    }
 69
 70    fn initial_title(
 71        &self,
 72        input: Result<Self::Input, serde_json::Value>,
 73        cx: &mut App,
 74    ) -> SharedString {
 75        if let Ok(input) = input
 76            && let Some(project_path) = self.project.read(cx).find_project_path(&input.path, cx)
 77            && let Some(path) = self
 78                .project
 79                .read(cx)
 80                .short_full_path_for_project_path(&project_path, cx)
 81        {
 82            match (input.start_line, input.end_line) {
 83                (Some(start), Some(end)) => {
 84                    format!("Read file `{path}` (lines {}-{})", start, end,)
 85                }
 86                (Some(start), None) => {
 87                    format!("Read file `{path}` (from line {})", start)
 88                }
 89                _ => format!("Read file `{path}`"),
 90            }
 91            .into()
 92        } else {
 93            "Read file".into()
 94        }
 95    }
 96
 97    fn run(
 98        self: Arc<Self>,
 99        input: Self::Input,
100        event_stream: ToolCallEventStream,
101        cx: &mut App,
102    ) -> Task<Result<LanguageModelToolResultContent>> {
103        let Some(project_path) = self.project.read(cx).find_project_path(&input.path, cx) else {
104            return Task::ready(Err(anyhow!("Path {} not found in project", &input.path)));
105        };
106        let Some(abs_path) = self.project.read(cx).absolute_path(&project_path, cx) else {
107            return Task::ready(Err(anyhow!(
108                "Failed to convert {} to absolute path",
109                &input.path
110            )));
111        };
112
113        // Error out if this path is either excluded or private in global settings
114        let global_settings = WorktreeSettings::get_global(cx);
115        if global_settings.is_path_excluded(&project_path.path) {
116            return Task::ready(Err(anyhow!(
117                "Cannot read file because its path matches the global `file_scan_exclusions` setting: {}",
118                &input.path
119            )));
120        }
121
122        if global_settings.is_path_private(&project_path.path) {
123            return Task::ready(Err(anyhow!(
124                "Cannot read file because its path matches the global `private_files` setting: {}",
125                &input.path
126            )));
127        }
128
129        // Error out if this path is either excluded or private in worktree settings
130        let worktree_settings = WorktreeSettings::get(Some((&project_path).into()), cx);
131        if worktree_settings.is_path_excluded(&project_path.path) {
132            return Task::ready(Err(anyhow!(
133                "Cannot read file because its path matches the worktree `file_scan_exclusions` setting: {}",
134                &input.path
135            )));
136        }
137
138        if worktree_settings.is_path_private(&project_path.path) {
139            return Task::ready(Err(anyhow!(
140                "Cannot read file because its path matches the worktree `private_files` setting: {}",
141                &input.path
142            )));
143        }
144
145        let file_path = input.path.clone();
146
147        event_stream.update_fields(ToolCallUpdateFields {
148            locations: Some(vec![acp::ToolCallLocation {
149                path: abs_path.clone(),
150                line: input.start_line.map(|line| line.saturating_sub(1)),
151                meta: None,
152            }]),
153            ..Default::default()
154        });
155
156        if image_store::is_image_file(&self.project, &project_path, cx) {
157            return cx.spawn(async move |cx| {
158                let image_entity: Entity<ImageItem> = cx
159                    .update(|cx| {
160                        self.project.update(cx, |project, cx| {
161                            project.open_image(project_path.clone(), cx)
162                        })
163                    })?
164                    .await?;
165
166                let image =
167                    image_entity.read_with(cx, |image_item, _| Arc::clone(&image_item.image))?;
168
169                let language_model_image = cx
170                    .update(|cx| LanguageModelImage::from_image(image, cx))?
171                    .await
172                    .context("processing image")?;
173
174                Ok(language_model_image.into())
175            });
176        }
177
178        let project = self.project.clone();
179        let action_log = self.action_log.clone();
180
181        cx.spawn(async move |cx| {
182            let buffer = cx
183                .update(|cx| {
184                    project.update(cx, |project, cx| {
185                        project.open_buffer(project_path.clone(), cx)
186                    })
187                })?
188                .await?;
189            if buffer.read_with(cx, |buffer, _| {
190                buffer
191                    .file()
192                    .as_ref()
193                    .is_none_or(|file| !file.disk_state().exists())
194            })? {
195                anyhow::bail!("{file_path} not found");
196            }
197
198            let mut anchor = None;
199
200            // Check if specific line ranges are provided
201            let result = if input.start_line.is_some() || input.end_line.is_some() {
202                let result = buffer.read_with(cx, |buffer, _cx| {
203                    // .max(1) because despite instructions to be 1-indexed, sometimes the model passes 0.
204                    let start = input.start_line.unwrap_or(1).max(1);
205                    let start_row = start - 1;
206                    if start_row <= buffer.max_point().row {
207                        let column = buffer.line_indent_for_row(start_row).raw_len();
208                        anchor = Some(buffer.anchor_before(Point::new(start_row, column)));
209                    }
210
211                    let mut end_row = input.end_line.unwrap_or(u32::MAX);
212                    if end_row <= start_row {
213                        end_row = start_row + 1; // read at least one lines
214                    }
215                    let start = buffer.anchor_before(Point::new(start_row, 0));
216                    let end = buffer.anchor_before(Point::new(end_row, 0));
217                    buffer.text_for_range(start..end).collect::<String>()
218                })?;
219
220                action_log.update(cx, |log, cx| {
221                    log.buffer_read(buffer.clone(), cx);
222                })?;
223
224                Ok(result.into())
225            } else {
226                // No line ranges specified, so check file size to see if it's too big.
227                let buffer_content = outline::get_buffer_content_or_outline(
228                    buffer.clone(),
229                    Some(&abs_path.to_string_lossy()),
230                    cx,
231                )
232                .await?;
233
234                action_log.update(cx, |log, cx| {
235                    log.buffer_read(buffer.clone(), cx);
236                })?;
237
238                if buffer_content.is_outline {
239                    Ok(formatdoc! {"
240                        This file was too big to read all at once.
241
242                        {}
243
244                        Using the line numbers in this outline, you can call this tool again
245                        while specifying the start_line and end_line fields to see the
246                        implementations of symbols in the outline.
247
248                        Alternatively, you can fall back to the `grep` tool (if available)
249                        to search the file for specific content.", buffer_content.text
250                    }
251                    .into())
252                } else {
253                    Ok(buffer_content.text.into())
254                }
255            };
256
257            project.update(cx, |project, cx| {
258                project.set_agent_location(
259                    Some(AgentLocation {
260                        buffer: buffer.downgrade(),
261                        position: anchor.unwrap_or(text::Anchor::MIN),
262                    }),
263                    cx,
264                );
265                if let Ok(LanguageModelToolResultContent::Text(text)) = &result {
266                    let markdown = MarkdownCodeBlock {
267                        tag: &input.path,
268                        text,
269                    }
270                    .to_string();
271                    event_stream.update_fields(ToolCallUpdateFields {
272                        content: Some(vec![acp::ToolCallContent::Content {
273                            content: markdown.into(),
274                        }]),
275                        ..Default::default()
276                    })
277                }
278            })?;
279
280            result
281        })
282    }
283}
284
285#[cfg(test)]
286mod test {
287    use super::*;
288    use gpui::{AppContext, TestAppContext, UpdateGlobal as _};
289    use language::{Language, LanguageConfig, LanguageMatcher, tree_sitter_rust};
290    use project::{FakeFs, Project};
291    use serde_json::json;
292    use settings::SettingsStore;
293    use util::path;
294
295    #[gpui::test]
296    async fn test_read_nonexistent_file(cx: &mut TestAppContext) {
297        init_test(cx);
298
299        let fs = FakeFs::new(cx.executor());
300        fs.insert_tree(path!("/root"), json!({})).await;
301        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
302        let action_log = cx.new(|_| ActionLog::new(project.clone()));
303        let tool = Arc::new(ReadFileTool::new(project, action_log));
304        let (event_stream, _) = ToolCallEventStream::test();
305
306        let result = cx
307            .update(|cx| {
308                let input = ReadFileToolInput {
309                    path: "root/nonexistent_file.txt".to_string(),
310                    start_line: None,
311                    end_line: None,
312                };
313                tool.run(input, event_stream, cx)
314            })
315            .await;
316        assert_eq!(
317            result.unwrap_err().to_string(),
318            "root/nonexistent_file.txt not found"
319        );
320    }
321
322    #[gpui::test]
323    async fn test_read_small_file(cx: &mut TestAppContext) {
324        init_test(cx);
325
326        let fs = FakeFs::new(cx.executor());
327        fs.insert_tree(
328            path!("/root"),
329            json!({
330                "small_file.txt": "This is a small file content"
331            }),
332        )
333        .await;
334        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
335        let action_log = cx.new(|_| ActionLog::new(project.clone()));
336        let tool = Arc::new(ReadFileTool::new(project, action_log));
337        let result = cx
338            .update(|cx| {
339                let input = ReadFileToolInput {
340                    path: "root/small_file.txt".into(),
341                    start_line: None,
342                    end_line: None,
343                };
344                tool.run(input, ToolCallEventStream::test().0, cx)
345            })
346            .await;
347        assert_eq!(result.unwrap(), "This is a small file content".into());
348    }
349
350    #[gpui::test]
351    async fn test_read_large_file(cx: &mut TestAppContext) {
352        init_test(cx);
353
354        let fs = FakeFs::new(cx.executor());
355        fs.insert_tree(
356            path!("/root"),
357            json!({
358                "large_file.rs": (0..1000).map(|i| format!("struct Test{} {{\n    a: u32,\n    b: usize,\n}}", i)).collect::<Vec<_>>().join("\n")
359            }),
360        )
361        .await;
362        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
363        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
364        language_registry.add(Arc::new(rust_lang()));
365        let action_log = cx.new(|_| ActionLog::new(project.clone()));
366        let tool = Arc::new(ReadFileTool::new(project, action_log));
367        let result = cx
368            .update(|cx| {
369                let input = ReadFileToolInput {
370                    path: "root/large_file.rs".into(),
371                    start_line: None,
372                    end_line: None,
373                };
374                tool.clone().run(input, ToolCallEventStream::test().0, cx)
375            })
376            .await
377            .unwrap();
378        let content = result.to_str().unwrap();
379
380        assert_eq!(
381            content.lines().skip(4).take(6).collect::<Vec<_>>(),
382            vec![
383                "struct Test0 [L1-4]",
384                " a [L2]",
385                " b [L3]",
386                "struct Test1 [L5-8]",
387                " a [L6]",
388                " b [L7]",
389            ]
390        );
391
392        let result = cx
393            .update(|cx| {
394                let input = ReadFileToolInput {
395                    path: "root/large_file.rs".into(),
396                    start_line: None,
397                    end_line: None,
398                };
399                tool.run(input, ToolCallEventStream::test().0, cx)
400            })
401            .await
402            .unwrap();
403        let content = result.to_str().unwrap();
404        let expected_content = (0..1000)
405            .flat_map(|i| {
406                vec![
407                    format!("struct Test{} [L{}-{}]", i, i * 4 + 1, i * 4 + 4),
408                    format!(" a [L{}]", i * 4 + 2),
409                    format!(" b [L{}]", i * 4 + 3),
410                ]
411            })
412            .collect::<Vec<_>>();
413        pretty_assertions::assert_eq!(
414            content
415                .lines()
416                .skip(4)
417                .take(expected_content.len())
418                .collect::<Vec<_>>(),
419            expected_content
420        );
421    }
422
423    #[gpui::test]
424    async fn test_read_file_with_line_range(cx: &mut TestAppContext) {
425        init_test(cx);
426
427        let fs = FakeFs::new(cx.executor());
428        fs.insert_tree(
429            path!("/root"),
430            json!({
431                "multiline.txt": "Line 1\nLine 2\nLine 3\nLine 4\nLine 5"
432            }),
433        )
434        .await;
435        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
436
437        let action_log = cx.new(|_| ActionLog::new(project.clone()));
438        let tool = Arc::new(ReadFileTool::new(project, action_log));
439        let result = cx
440            .update(|cx| {
441                let input = ReadFileToolInput {
442                    path: "root/multiline.txt".to_string(),
443                    start_line: Some(2),
444                    end_line: Some(4),
445                };
446                tool.run(input, ToolCallEventStream::test().0, cx)
447            })
448            .await;
449        assert_eq!(result.unwrap(), "Line 2\nLine 3\nLine 4\n".into());
450    }
451
452    #[gpui::test]
453    async fn test_read_file_line_range_edge_cases(cx: &mut TestAppContext) {
454        init_test(cx);
455
456        let fs = FakeFs::new(cx.executor());
457        fs.insert_tree(
458            path!("/root"),
459            json!({
460                "multiline.txt": "Line 1\nLine 2\nLine 3\nLine 4\nLine 5"
461            }),
462        )
463        .await;
464        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
465        let action_log = cx.new(|_| ActionLog::new(project.clone()));
466        let tool = Arc::new(ReadFileTool::new(project, action_log));
467
468        // start_line of 0 should be treated as 1
469        let result = cx
470            .update(|cx| {
471                let input = ReadFileToolInput {
472                    path: "root/multiline.txt".to_string(),
473                    start_line: Some(0),
474                    end_line: Some(2),
475                };
476                tool.clone().run(input, ToolCallEventStream::test().0, cx)
477            })
478            .await;
479        assert_eq!(result.unwrap(), "Line 1\nLine 2\n".into());
480
481        // end_line of 0 should result in at least 1 line
482        let result = cx
483            .update(|cx| {
484                let input = ReadFileToolInput {
485                    path: "root/multiline.txt".to_string(),
486                    start_line: Some(1),
487                    end_line: Some(0),
488                };
489                tool.clone().run(input, ToolCallEventStream::test().0, cx)
490            })
491            .await;
492        assert_eq!(result.unwrap(), "Line 1\n".into());
493
494        // when start_line > end_line, should still return at least 1 line
495        let result = cx
496            .update(|cx| {
497                let input = ReadFileToolInput {
498                    path: "root/multiline.txt".to_string(),
499                    start_line: Some(3),
500                    end_line: Some(2),
501                };
502                tool.clone().run(input, ToolCallEventStream::test().0, cx)
503            })
504            .await;
505        assert_eq!(result.unwrap(), "Line 3\n".into());
506    }
507
508    fn init_test(cx: &mut TestAppContext) {
509        cx.update(|cx| {
510            let settings_store = SettingsStore::test(cx);
511            cx.set_global(settings_store);
512        });
513    }
514
515    fn rust_lang() -> Language {
516        Language::new(
517            LanguageConfig {
518                name: "Rust".into(),
519                matcher: LanguageMatcher {
520                    path_suffixes: vec!["rs".to_string()],
521                    ..Default::default()
522                },
523                ..Default::default()
524            },
525            Some(tree_sitter_rust::LANGUAGE.into()),
526        )
527        .with_outline_query(
528            r#"
529            (line_comment) @annotation
530
531            (struct_item
532                "struct" @context
533                name: (_) @name) @item
534            (enum_item
535                "enum" @context
536                name: (_) @name) @item
537            (enum_variant
538                name: (_) @name) @item
539            (field_declaration
540                name: (_) @name) @item
541            (impl_item
542                "impl" @context
543                trait: (_)? @name
544                "for"? @context
545                type: (_) @name
546                body: (_ "{" (_)* "}")) @item
547            (function_item
548                "fn" @context
549                name: (_) @name) @item
550            (mod_item
551                "mod" @context
552                name: (_) @name) @item
553            "#,
554        )
555        .unwrap()
556    }
557
558    #[gpui::test]
559    async fn test_read_file_security(cx: &mut TestAppContext) {
560        init_test(cx);
561
562        let fs = FakeFs::new(cx.executor());
563
564        fs.insert_tree(
565            path!("/"),
566            json!({
567                "project_root": {
568                    "allowed_file.txt": "This file is in the project",
569                    ".mysecrets": "SECRET_KEY=abc123",
570                    ".secretdir": {
571                        "config": "special configuration"
572                    },
573                    ".mymetadata": "custom metadata",
574                    "subdir": {
575                        "normal_file.txt": "Normal file content",
576                        "special.privatekey": "private key content",
577                        "data.mysensitive": "sensitive data"
578                    }
579                },
580                "outside_project": {
581                    "sensitive_file.txt": "This file is outside the project"
582                }
583            }),
584        )
585        .await;
586
587        cx.update(|cx| {
588            use gpui::UpdateGlobal;
589            use settings::SettingsStore;
590            SettingsStore::update_global(cx, |store, cx| {
591                store.update_user_settings(cx, |settings| {
592                    settings.project.worktree.file_scan_exclusions = Some(vec![
593                        "**/.secretdir".to_string(),
594                        "**/.mymetadata".to_string(),
595                    ]);
596                    settings.project.worktree.private_files = Some(
597                        vec![
598                            "**/.mysecrets".to_string(),
599                            "**/*.privatekey".to_string(),
600                            "**/*.mysensitive".to_string(),
601                        ]
602                        .into(),
603                    );
604                });
605            });
606        });
607
608        let project = Project::test(fs.clone(), [path!("/project_root").as_ref()], cx).await;
609        let action_log = cx.new(|_| ActionLog::new(project.clone()));
610        let tool = Arc::new(ReadFileTool::new(project, action_log));
611
612        // Reading a file outside the project worktree should fail
613        let result = cx
614            .update(|cx| {
615                let input = ReadFileToolInput {
616                    path: "/outside_project/sensitive_file.txt".to_string(),
617                    start_line: None,
618                    end_line: None,
619                };
620                tool.clone().run(input, ToolCallEventStream::test().0, cx)
621            })
622            .await;
623        assert!(
624            result.is_err(),
625            "read_file_tool should error when attempting to read an absolute path outside a worktree"
626        );
627
628        // Reading a file within the project should succeed
629        let result = cx
630            .update(|cx| {
631                let input = ReadFileToolInput {
632                    path: "project_root/allowed_file.txt".to_string(),
633                    start_line: None,
634                    end_line: None,
635                };
636                tool.clone().run(input, ToolCallEventStream::test().0, cx)
637            })
638            .await;
639        assert!(
640            result.is_ok(),
641            "read_file_tool should be able to read files inside worktrees"
642        );
643
644        // Reading files that match file_scan_exclusions should fail
645        let result = cx
646            .update(|cx| {
647                let input = ReadFileToolInput {
648                    path: "project_root/.secretdir/config".to_string(),
649                    start_line: None,
650                    end_line: None,
651                };
652                tool.clone().run(input, ToolCallEventStream::test().0, cx)
653            })
654            .await;
655        assert!(
656            result.is_err(),
657            "read_file_tool should error when attempting to read files in .secretdir (file_scan_exclusions)"
658        );
659
660        let result = cx
661            .update(|cx| {
662                let input = ReadFileToolInput {
663                    path: "project_root/.mymetadata".to_string(),
664                    start_line: None,
665                    end_line: None,
666                };
667                tool.clone().run(input, ToolCallEventStream::test().0, cx)
668            })
669            .await;
670        assert!(
671            result.is_err(),
672            "read_file_tool should error when attempting to read .mymetadata files (file_scan_exclusions)"
673        );
674
675        // Reading private files should fail
676        let result = cx
677            .update(|cx| {
678                let input = ReadFileToolInput {
679                    path: "project_root/.mysecrets".to_string(),
680                    start_line: None,
681                    end_line: None,
682                };
683                tool.clone().run(input, ToolCallEventStream::test().0, cx)
684            })
685            .await;
686        assert!(
687            result.is_err(),
688            "read_file_tool should error when attempting to read .mysecrets (private_files)"
689        );
690
691        let result = cx
692            .update(|cx| {
693                let input = ReadFileToolInput {
694                    path: "project_root/subdir/special.privatekey".to_string(),
695                    start_line: None,
696                    end_line: None,
697                };
698                tool.clone().run(input, ToolCallEventStream::test().0, cx)
699            })
700            .await;
701        assert!(
702            result.is_err(),
703            "read_file_tool should error when attempting to read .privatekey files (private_files)"
704        );
705
706        let result = cx
707            .update(|cx| {
708                let input = ReadFileToolInput {
709                    path: "project_root/subdir/data.mysensitive".to_string(),
710                    start_line: None,
711                    end_line: None,
712                };
713                tool.clone().run(input, ToolCallEventStream::test().0, cx)
714            })
715            .await;
716        assert!(
717            result.is_err(),
718            "read_file_tool should error when attempting to read .mysensitive files (private_files)"
719        );
720
721        // Reading a normal file should still work, even with private_files configured
722        let result = cx
723            .update(|cx| {
724                let input = ReadFileToolInput {
725                    path: "project_root/subdir/normal_file.txt".to_string(),
726                    start_line: None,
727                    end_line: None,
728                };
729                tool.clone().run(input, ToolCallEventStream::test().0, cx)
730            })
731            .await;
732        assert!(result.is_ok(), "Should be able to read normal files");
733        assert_eq!(result.unwrap(), "Normal file content".into());
734
735        // Path traversal attempts with .. should fail
736        let result = cx
737            .update(|cx| {
738                let input = ReadFileToolInput {
739                    path: "project_root/../outside_project/sensitive_file.txt".to_string(),
740                    start_line: None,
741                    end_line: None,
742                };
743                tool.run(input, ToolCallEventStream::test().0, cx)
744            })
745            .await;
746        assert!(
747            result.is_err(),
748            "read_file_tool should error when attempting to read a relative path that resolves to outside a worktree"
749        );
750    }
751
752    #[gpui::test]
753    async fn test_read_file_with_multiple_worktree_settings(cx: &mut TestAppContext) {
754        init_test(cx);
755
756        let fs = FakeFs::new(cx.executor());
757
758        // Create first worktree with its own private_files setting
759        fs.insert_tree(
760            path!("/worktree1"),
761            json!({
762                "src": {
763                    "main.rs": "fn main() { println!(\"Hello from worktree1\"); }",
764                    "secret.rs": "const API_KEY: &str = \"secret_key_1\";",
765                    "config.toml": "[database]\nurl = \"postgres://localhost/db1\""
766                },
767                "tests": {
768                    "test.rs": "mod tests { fn test_it() {} }",
769                    "fixture.sql": "CREATE TABLE users (id INT, name VARCHAR(255));"
770                },
771                ".zed": {
772                    "settings.json": r#"{
773                        "file_scan_exclusions": ["**/fixture.*"],
774                        "private_files": ["**/secret.rs", "**/config.toml"]
775                    }"#
776                }
777            }),
778        )
779        .await;
780
781        // Create second worktree with different private_files setting
782        fs.insert_tree(
783            path!("/worktree2"),
784            json!({
785                "lib": {
786                    "public.js": "export function greet() { return 'Hello from worktree2'; }",
787                    "private.js": "const SECRET_TOKEN = \"private_token_2\";",
788                    "data.json": "{\"api_key\": \"json_secret_key\"}"
789                },
790                "docs": {
791                    "README.md": "# Public Documentation",
792                    "internal.md": "# Internal Secrets and Configuration"
793                },
794                ".zed": {
795                    "settings.json": r#"{
796                        "file_scan_exclusions": ["**/internal.*"],
797                        "private_files": ["**/private.js", "**/data.json"]
798                    }"#
799                }
800            }),
801        )
802        .await;
803
804        // Set global settings
805        cx.update(|cx| {
806            SettingsStore::update_global(cx, |store, cx| {
807                store.update_user_settings(cx, |settings| {
808                    settings.project.worktree.file_scan_exclusions =
809                        Some(vec!["**/.git".to_string(), "**/node_modules".to_string()]);
810                    settings.project.worktree.private_files =
811                        Some(vec!["**/.env".to_string()].into());
812                });
813            });
814        });
815
816        let project = Project::test(
817            fs.clone(),
818            [path!("/worktree1").as_ref(), path!("/worktree2").as_ref()],
819            cx,
820        )
821        .await;
822
823        let action_log = cx.new(|_| ActionLog::new(project.clone()));
824        let tool = Arc::new(ReadFileTool::new(project.clone(), action_log.clone()));
825
826        // Test reading allowed files in worktree1
827        let result = cx
828            .update(|cx| {
829                let input = ReadFileToolInput {
830                    path: "worktree1/src/main.rs".to_string(),
831                    start_line: None,
832                    end_line: None,
833                };
834                tool.clone().run(input, ToolCallEventStream::test().0, cx)
835            })
836            .await
837            .unwrap();
838
839        assert_eq!(
840            result,
841            "fn main() { println!(\"Hello from worktree1\"); }".into()
842        );
843
844        // Test reading private file in worktree1 should fail
845        let result = cx
846            .update(|cx| {
847                let input = ReadFileToolInput {
848                    path: "worktree1/src/secret.rs".to_string(),
849                    start_line: None,
850                    end_line: None,
851                };
852                tool.clone().run(input, ToolCallEventStream::test().0, cx)
853            })
854            .await;
855
856        assert!(result.is_err());
857        assert!(
858            result
859                .unwrap_err()
860                .to_string()
861                .contains("worktree `private_files` setting"),
862            "Error should mention worktree private_files setting"
863        );
864
865        // Test reading excluded file in worktree1 should fail
866        let result = cx
867            .update(|cx| {
868                let input = ReadFileToolInput {
869                    path: "worktree1/tests/fixture.sql".to_string(),
870                    start_line: None,
871                    end_line: None,
872                };
873                tool.clone().run(input, ToolCallEventStream::test().0, cx)
874            })
875            .await;
876
877        assert!(result.is_err());
878        assert!(
879            result
880                .unwrap_err()
881                .to_string()
882                .contains("worktree `file_scan_exclusions` setting"),
883            "Error should mention worktree file_scan_exclusions setting"
884        );
885
886        // Test reading allowed files in worktree2
887        let result = cx
888            .update(|cx| {
889                let input = ReadFileToolInput {
890                    path: "worktree2/lib/public.js".to_string(),
891                    start_line: None,
892                    end_line: None,
893                };
894                tool.clone().run(input, ToolCallEventStream::test().0, cx)
895            })
896            .await
897            .unwrap();
898
899        assert_eq!(
900            result,
901            "export function greet() { return 'Hello from worktree2'; }".into()
902        );
903
904        // Test reading private file in worktree2 should fail
905        let result = cx
906            .update(|cx| {
907                let input = ReadFileToolInput {
908                    path: "worktree2/lib/private.js".to_string(),
909                    start_line: None,
910                    end_line: None,
911                };
912                tool.clone().run(input, ToolCallEventStream::test().0, cx)
913            })
914            .await;
915
916        assert!(result.is_err());
917        assert!(
918            result
919                .unwrap_err()
920                .to_string()
921                .contains("worktree `private_files` setting"),
922            "Error should mention worktree private_files setting"
923        );
924
925        // Test reading excluded file in worktree2 should fail
926        let result = cx
927            .update(|cx| {
928                let input = ReadFileToolInput {
929                    path: "worktree2/docs/internal.md".to_string(),
930                    start_line: None,
931                    end_line: None,
932                };
933                tool.clone().run(input, ToolCallEventStream::test().0, cx)
934            })
935            .await;
936
937        assert!(result.is_err());
938        assert!(
939            result
940                .unwrap_err()
941                .to_string()
942                .contains("worktree `file_scan_exclusions` setting"),
943            "Error should mention worktree file_scan_exclusions setting"
944        );
945
946        // Test that files allowed in one worktree but not in another are handled correctly
947        // (e.g., config.toml is private in worktree1 but doesn't exist in worktree2)
948        let result = cx
949            .update(|cx| {
950                let input = ReadFileToolInput {
951                    path: "worktree1/src/config.toml".to_string(),
952                    start_line: None,
953                    end_line: None,
954                };
955                tool.clone().run(input, ToolCallEventStream::test().0, cx)
956            })
957            .await;
958
959        assert!(result.is_err());
960        assert!(
961            result
962                .unwrap_err()
963                .to_string()
964                .contains("worktree `private_files` setting"),
965            "Config.toml should be blocked by worktree1's private_files setting"
966        );
967    }
968}