edit_file_tool.rs

   1use crate::{AgentTool, Thread, ToolCallEventStream};
   2use acp_thread::Diff;
   3use agent_client_protocol::{self as acp, ToolCallLocation, ToolCallUpdateFields};
   4use anyhow::{Context as _, Result, anyhow};
   5use assistant_tools::edit_agent::{EditAgent, EditAgentOutput, EditAgentOutputEvent, EditFormat};
   6use cloud_llm_client::CompletionIntent;
   7use collections::HashSet;
   8use gpui::{App, AppContext, AsyncApp, Entity, Task, WeakEntity};
   9use indoc::formatdoc;
  10use language::language_settings::{self, FormatOnSave};
  11use language::{LanguageRegistry, ToPoint};
  12use language_model::LanguageModelToolResultContent;
  13use paths;
  14use project::lsp_store::{FormatTrigger, LspFormatTarget};
  15use project::{Project, ProjectPath};
  16use schemars::JsonSchema;
  17use serde::{Deserialize, Serialize};
  18use settings::Settings;
  19use smol::stream::StreamExt as _;
  20use std::path::{Path, PathBuf};
  21use std::sync::Arc;
  22use ui::SharedString;
  23use util::ResultExt;
  24
  25const DEFAULT_UI_TEXT: &str = "Editing file";
  26
  27/// This is a tool for creating a new file or editing an existing file. For moving or renaming files, you should generally use the `terminal` tool with the 'mv' command instead.
  28///
  29/// Before using this tool:
  30///
  31/// 1. Use the `read_file` tool to understand the file's contents and context
  32///
  33/// 2. Verify the directory path is correct (only applicable when creating new files):
  34///    - Use the `list_directory` tool to verify the parent directory exists and is the correct location
  35#[derive(Debug, Serialize, Deserialize, JsonSchema)]
  36pub struct EditFileToolInput {
  37    /// A one-line, user-friendly markdown description of the edit. This will be
  38    /// shown in the UI and also passed to another model to perform the edit.
  39    ///
  40    /// Be terse, but also descriptive in what you want to achieve with this
  41    /// edit. Avoid generic instructions.
  42    ///
  43    /// NEVER mention the file path in this description.
  44    ///
  45    /// <example>Fix API endpoint URLs</example>
  46    /// <example>Update copyright year in `page_footer`</example>
  47    ///
  48    /// Make sure to include this field before all the others in the input object
  49    /// so that we can display it immediately.
  50    pub display_description: String,
  51
  52    /// The full path of the file to create or modify in the project.
  53    ///
  54    /// WARNING: When specifying which file path need changing, you MUST
  55    /// start each path with one of the project's root directories.
  56    ///
  57    /// The following examples assume we have two root directories in the project:
  58    /// - /a/b/backend
  59    /// - /c/d/frontend
  60    ///
  61    /// <example>
  62    /// `backend/src/main.rs`
  63    ///
  64    /// Notice how the file path starts with `backend`. Without that, the path
  65    /// would be ambiguous and the call would fail!
  66    /// </example>
  67    ///
  68    /// <example>
  69    /// `frontend/db.js`
  70    /// </example>
  71    pub path: PathBuf,
  72
  73    /// The mode of operation on the file. Possible values:
  74    /// - 'edit': Make granular edits to an existing file.
  75    /// - 'create': Create a new file if it doesn't exist.
  76    /// - 'overwrite': Replace the entire contents of an existing file.
  77    ///
  78    /// When a file already exists or you just created it, prefer editing
  79    /// it as opposed to recreating it from scratch.
  80    pub mode: EditFileMode,
  81}
  82
  83#[derive(Debug, Serialize, Deserialize, JsonSchema)]
  84struct EditFileToolPartialInput {
  85    #[serde(default)]
  86    path: String,
  87    #[serde(default)]
  88    display_description: String,
  89}
  90
  91#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
  92#[serde(rename_all = "lowercase")]
  93pub enum EditFileMode {
  94    Edit,
  95    Create,
  96    Overwrite,
  97}
  98
  99#[derive(Debug, Serialize, Deserialize)]
 100pub struct EditFileToolOutput {
 101    #[serde(alias = "original_path")]
 102    input_path: PathBuf,
 103    new_text: String,
 104    old_text: Arc<String>,
 105    #[serde(default)]
 106    diff: String,
 107    #[serde(alias = "raw_output")]
 108    edit_agent_output: EditAgentOutput,
 109}
 110
 111impl From<EditFileToolOutput> for LanguageModelToolResultContent {
 112    fn from(output: EditFileToolOutput) -> Self {
 113        if output.diff.is_empty() {
 114            "No edits were made.".into()
 115        } else {
 116            format!(
 117                "Edited {}:\n\n```diff\n{}\n```",
 118                output.input_path.display(),
 119                output.diff
 120            )
 121            .into()
 122        }
 123    }
 124}
 125
 126pub struct EditFileTool {
 127    thread: WeakEntity<Thread>,
 128    language_registry: Arc<LanguageRegistry>,
 129}
 130
 131impl EditFileTool {
 132    pub fn new(thread: WeakEntity<Thread>, language_registry: Arc<LanguageRegistry>) -> Self {
 133        Self {
 134            thread,
 135            language_registry,
 136        }
 137    }
 138
 139    fn authorize(
 140        &self,
 141        input: &EditFileToolInput,
 142        event_stream: &ToolCallEventStream,
 143        cx: &mut App,
 144    ) -> Task<Result<()>> {
 145        if agent_settings::AgentSettings::get_global(cx).always_allow_tool_actions {
 146            return Task::ready(Ok(()));
 147        }
 148
 149        // If any path component matches the local settings folder, then this could affect
 150        // the editor in ways beyond the project source, so prompt.
 151        let local_settings_folder = paths::local_settings_folder_relative_path();
 152        let path = Path::new(&input.path);
 153        if path
 154            .components()
 155            .any(|component| component.as_os_str() == local_settings_folder.as_os_str())
 156        {
 157            return event_stream.authorize(
 158                format!("{} (local settings)", input.display_description),
 159                cx,
 160            );
 161        }
 162
 163        // It's also possible that the global config dir is configured to be inside the project,
 164        // so check for that edge case too.
 165        if let Ok(canonical_path) = std::fs::canonicalize(&input.path)
 166            && canonical_path.starts_with(paths::config_dir())
 167        {
 168            return event_stream.authorize(
 169                format!("{} (global settings)", input.display_description),
 170                cx,
 171            );
 172        }
 173
 174        // Check if path is inside the global config directory
 175        // First check if it's already inside project - if not, try to canonicalize
 176        let Ok(project_path) = self.thread.read_with(cx, |thread, cx| {
 177            thread.project().read(cx).find_project_path(&input.path, cx)
 178        }) else {
 179            return Task::ready(Err(anyhow!("thread was dropped")));
 180        };
 181
 182        // If the path is inside the project, and it's not one of the above edge cases,
 183        // then no confirmation is necessary. Otherwise, confirmation is necessary.
 184        if project_path.is_some() {
 185            Task::ready(Ok(()))
 186        } else {
 187            event_stream.authorize(&input.display_description, cx)
 188        }
 189    }
 190}
 191
 192impl AgentTool for EditFileTool {
 193    type Input = EditFileToolInput;
 194    type Output = EditFileToolOutput;
 195
 196    fn name(&self) -> SharedString {
 197        "edit_file".into()
 198    }
 199
 200    fn kind(&self) -> acp::ToolKind {
 201        acp::ToolKind::Edit
 202    }
 203
 204    fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString {
 205        match input {
 206            Ok(input) => input.display_description.into(),
 207            Err(raw_input) => {
 208                if let Some(input) =
 209                    serde_json::from_value::<EditFileToolPartialInput>(raw_input).ok()
 210                {
 211                    let description = input.display_description.trim();
 212                    if !description.is_empty() {
 213                        return description.to_string().into();
 214                    }
 215
 216                    let path = input.path.trim().to_string();
 217                    if !path.is_empty() {
 218                        return path.into();
 219                    }
 220                }
 221
 222                DEFAULT_UI_TEXT.into()
 223            }
 224        }
 225    }
 226
 227    fn run(
 228        self: Arc<Self>,
 229        input: Self::Input,
 230        event_stream: ToolCallEventStream,
 231        cx: &mut App,
 232    ) -> Task<Result<Self::Output>> {
 233        let Ok(project) = self
 234            .thread
 235            .read_with(cx, |thread, _cx| thread.project().clone())
 236        else {
 237            return Task::ready(Err(anyhow!("thread was dropped")));
 238        };
 239        let project_path = match resolve_path(&input, project.clone(), cx) {
 240            Ok(path) => path,
 241            Err(err) => return Task::ready(Err(anyhow!(err))),
 242        };
 243        let abs_path = project.read(cx).absolute_path(&project_path, cx);
 244        if let Some(abs_path) = abs_path.clone() {
 245            event_stream.update_fields(ToolCallUpdateFields {
 246                locations: Some(vec![acp::ToolCallLocation {
 247                    path: abs_path,
 248                    line: None,
 249                }]),
 250                ..Default::default()
 251            });
 252        }
 253
 254        let authorize = self.authorize(&input, &event_stream, cx);
 255        cx.spawn(async move |cx: &mut AsyncApp| {
 256            authorize.await?;
 257
 258            let (request, model, action_log) = self.thread.update(cx, |thread, cx| {
 259                let request = thread.build_completion_request(CompletionIntent::ToolResults, cx);
 260                (request, thread.model().cloned(), thread.action_log().clone())
 261            })?;
 262            let request = request?;
 263            let model = model.context("No language model configured")?;
 264
 265            let edit_format = EditFormat::from_model(model.clone())?;
 266            let edit_agent = EditAgent::new(
 267                model,
 268                project.clone(),
 269                action_log.clone(),
 270                // TODO: move edit agent to this crate so we can use our templates
 271                assistant_tools::templates::Templates::new(),
 272                edit_format,
 273            );
 274
 275            let buffer = project
 276                .update(cx, |project, cx| {
 277                    project.open_buffer(project_path.clone(), cx)
 278                })?
 279                .await?;
 280
 281            let diff = cx.new(|cx| Diff::new(buffer.clone(), cx))?;
 282            event_stream.update_diff(diff.clone());
 283
 284            let old_snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 285            let old_text = cx
 286                .background_spawn({
 287                    let old_snapshot = old_snapshot.clone();
 288                    async move { Arc::new(old_snapshot.text()) }
 289                })
 290                .await;
 291
 292
 293            let (output, mut events) = if matches!(input.mode, EditFileMode::Edit) {
 294                edit_agent.edit(
 295                    buffer.clone(),
 296                    input.display_description.clone(),
 297                    &request,
 298                    cx,
 299                )
 300            } else {
 301                edit_agent.overwrite(
 302                    buffer.clone(),
 303                    input.display_description.clone(),
 304                    &request,
 305                    cx,
 306                )
 307            };
 308
 309            let mut hallucinated_old_text = false;
 310            let mut ambiguous_ranges = Vec::new();
 311            let mut emitted_location = false;
 312            while let Some(event) = events.next().await {
 313                match event {
 314                    EditAgentOutputEvent::Edited(range) => {
 315                        if !emitted_location {
 316                            let line = buffer.update(cx, |buffer, _cx| {
 317                                range.start.to_point(&buffer.snapshot()).row
 318                            }).ok();
 319                            if let Some(abs_path) = abs_path.clone() {
 320                                event_stream.update_fields(ToolCallUpdateFields {
 321                                    locations: Some(vec![ToolCallLocation { path: abs_path, line }]),
 322                                    ..Default::default()
 323                                });
 324                            }
 325                            emitted_location = true;
 326                        }
 327                    },
 328                    EditAgentOutputEvent::UnresolvedEditRange => hallucinated_old_text = true,
 329                    EditAgentOutputEvent::AmbiguousEditRange(ranges) => ambiguous_ranges = ranges,
 330                    EditAgentOutputEvent::ResolvingEditRange(range) => {
 331                        diff.update(cx, |card, cx| card.reveal_range(range.clone(), cx))?;
 332                        // if !emitted_location {
 333                        //     let line = buffer.update(cx, |buffer, _cx| {
 334                        //         range.start.to_point(&buffer.snapshot()).row
 335                        //     }).ok();
 336                        //     if let Some(abs_path) = abs_path.clone() {
 337                        //         event_stream.update_fields(ToolCallUpdateFields {
 338                        //             locations: Some(vec![ToolCallLocation { path: abs_path, line }]),
 339                        //             ..Default::default()
 340                        //         });
 341                        //     }
 342                        // }
 343                    }
 344                }
 345            }
 346
 347            // If format_on_save is enabled, format the buffer
 348            let format_on_save_enabled = buffer
 349                .read_with(cx, |buffer, cx| {
 350                    let settings = language_settings::language_settings(
 351                        buffer.language().map(|l| l.name()),
 352                        buffer.file(),
 353                        cx,
 354                    );
 355                    settings.format_on_save != FormatOnSave::Off
 356                })
 357                .unwrap_or(false);
 358
 359            let edit_agent_output = output.await?;
 360
 361            if format_on_save_enabled {
 362                action_log.update(cx, |log, cx| {
 363                    log.buffer_edited(buffer.clone(), cx);
 364                })?;
 365
 366                let format_task = project.update(cx, |project, cx| {
 367                    project.format(
 368                        HashSet::from_iter([buffer.clone()]),
 369                        LspFormatTarget::Buffers,
 370                        false, // Don't push to history since the tool did it.
 371                        FormatTrigger::Save,
 372                        cx,
 373                    )
 374                })?;
 375                format_task.await.log_err();
 376            }
 377
 378            project
 379                .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))?
 380                .await?;
 381
 382            action_log.update(cx, |log, cx| {
 383                log.buffer_edited(buffer.clone(), cx);
 384            })?;
 385
 386            let new_snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 387            let (new_text, unified_diff) = cx
 388                .background_spawn({
 389                    let new_snapshot = new_snapshot.clone();
 390                    let old_text = old_text.clone();
 391                    async move {
 392                        let new_text = new_snapshot.text();
 393                        let diff = language::unified_diff(&old_text, &new_text);
 394                        (new_text, diff)
 395                    }
 396                })
 397                .await;
 398
 399            diff.update(cx, |diff, cx| diff.finalize(cx)).ok();
 400
 401            let input_path = input.path.display();
 402            if unified_diff.is_empty() {
 403                anyhow::ensure!(
 404                    !hallucinated_old_text,
 405                    formatdoc! {"
 406                        Some edits were produced but none of them could be applied.
 407                        Read the relevant sections of {input_path} again so that
 408                        I can perform the requested edits.
 409                    "}
 410                );
 411                anyhow::ensure!(
 412                    ambiguous_ranges.is_empty(),
 413                    {
 414                        let line_numbers = ambiguous_ranges
 415                            .iter()
 416                            .map(|range| range.start.to_string())
 417                            .collect::<Vec<_>>()
 418                            .join(", ");
 419                        formatdoc! {"
 420                            <old_text> matches more than one position in the file (lines: {line_numbers}). Read the
 421                            relevant sections of {input_path} again and extend <old_text> so
 422                            that I can perform the requested edits.
 423                        "}
 424                    }
 425                );
 426            }
 427
 428            Ok(EditFileToolOutput {
 429                input_path: input.path,
 430                new_text: new_text.clone(),
 431                old_text,
 432                diff: unified_diff,
 433                edit_agent_output,
 434            })
 435        })
 436    }
 437
 438    fn replay(
 439        &self,
 440        _input: Self::Input,
 441        output: Self::Output,
 442        event_stream: ToolCallEventStream,
 443        cx: &mut App,
 444    ) -> Result<()> {
 445        event_stream.update_diff(cx.new(|cx| {
 446            Diff::finalized(
 447                output.input_path,
 448                Some(output.old_text.to_string()),
 449                output.new_text,
 450                self.language_registry.clone(),
 451                cx,
 452            )
 453        }));
 454        Ok(())
 455    }
 456}
 457
 458/// Validate that the file path is valid, meaning:
 459///
 460/// - For `edit` and `overwrite`, the path must point to an existing file.
 461/// - For `create`, the file must not already exist, but it's parent dir must exist.
 462fn resolve_path(
 463    input: &EditFileToolInput,
 464    project: Entity<Project>,
 465    cx: &mut App,
 466) -> Result<ProjectPath> {
 467    let project = project.read(cx);
 468
 469    match input.mode {
 470        EditFileMode::Edit | EditFileMode::Overwrite => {
 471            let path = project
 472                .find_project_path(&input.path, cx)
 473                .context("Can't edit file: path not found")?;
 474
 475            let entry = project
 476                .entry_for_path(&path, cx)
 477                .context("Can't edit file: path not found")?;
 478
 479            anyhow::ensure!(entry.is_file(), "Can't edit file: path is a directory");
 480            Ok(path)
 481        }
 482
 483        EditFileMode::Create => {
 484            if let Some(path) = project.find_project_path(&input.path, cx) {
 485                anyhow::ensure!(
 486                    project.entry_for_path(&path, cx).is_none(),
 487                    "Can't create file: file already exists"
 488                );
 489            }
 490
 491            let parent_path = input
 492                .path
 493                .parent()
 494                .context("Can't create file: incorrect path")?;
 495
 496            let parent_project_path = project.find_project_path(&parent_path, cx);
 497
 498            let parent_entry = parent_project_path
 499                .as_ref()
 500                .and_then(|path| project.entry_for_path(path, cx))
 501                .context("Can't create file: parent directory doesn't exist")?;
 502
 503            anyhow::ensure!(
 504                parent_entry.is_dir(),
 505                "Can't create file: parent is not a directory"
 506            );
 507
 508            let file_name = input
 509                .path
 510                .file_name()
 511                .context("Can't create file: invalid filename")?;
 512
 513            let new_file_path = parent_project_path.map(|parent| ProjectPath {
 514                path: Arc::from(parent.path.join(file_name)),
 515                ..parent
 516            });
 517
 518            new_file_path.context("Can't create file")
 519        }
 520    }
 521}
 522
 523#[cfg(test)]
 524mod tests {
 525    use super::*;
 526    use crate::{ContextServerRegistry, Templates};
 527    use action_log::ActionLog;
 528    use client::TelemetrySettings;
 529    use fs::Fs;
 530    use gpui::{TestAppContext, UpdateGlobal};
 531    use language_model::fake_provider::FakeLanguageModel;
 532    use prompt_store::ProjectContext;
 533    use serde_json::json;
 534    use settings::SettingsStore;
 535    use util::path;
 536
 537    #[gpui::test]
 538    async fn test_edit_nonexistent_file(cx: &mut TestAppContext) {
 539        init_test(cx);
 540
 541        let fs = project::FakeFs::new(cx.executor());
 542        fs.insert_tree("/root", json!({})).await;
 543        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 544        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
 545        let action_log = cx.new(|_| ActionLog::new(project.clone()));
 546        let context_server_registry =
 547            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 548        let model = Arc::new(FakeLanguageModel::default());
 549        let thread = cx.new(|cx| {
 550            Thread::new(
 551                project,
 552                cx.new(|_cx| ProjectContext::default()),
 553                context_server_registry,
 554                action_log,
 555                Templates::new(),
 556                Some(model),
 557                cx,
 558            )
 559        });
 560        let result = cx
 561            .update(|cx| {
 562                let input = EditFileToolInput {
 563                    display_description: "Some edit".into(),
 564                    path: "root/nonexistent_file.txt".into(),
 565                    mode: EditFileMode::Edit,
 566                };
 567                Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
 568                    input,
 569                    ToolCallEventStream::test().0,
 570                    cx,
 571                )
 572            })
 573            .await;
 574        assert_eq!(
 575            result.unwrap_err().to_string(),
 576            "Can't edit file: path not found"
 577        );
 578    }
 579
 580    #[gpui::test]
 581    async fn test_resolve_path_for_creating_file(cx: &mut TestAppContext) {
 582        let mode = &EditFileMode::Create;
 583
 584        let result = test_resolve_path(mode, "root/new.txt", cx);
 585        assert_resolved_path_eq(result.await, "new.txt");
 586
 587        let result = test_resolve_path(mode, "new.txt", cx);
 588        assert_resolved_path_eq(result.await, "new.txt");
 589
 590        let result = test_resolve_path(mode, "dir/new.txt", cx);
 591        assert_resolved_path_eq(result.await, "dir/new.txt");
 592
 593        let result = test_resolve_path(mode, "root/dir/subdir/existing.txt", cx);
 594        assert_eq!(
 595            result.await.unwrap_err().to_string(),
 596            "Can't create file: file already exists"
 597        );
 598
 599        let result = test_resolve_path(mode, "root/dir/nonexistent_dir/new.txt", cx);
 600        assert_eq!(
 601            result.await.unwrap_err().to_string(),
 602            "Can't create file: parent directory doesn't exist"
 603        );
 604    }
 605
 606    #[gpui::test]
 607    async fn test_resolve_path_for_editing_file(cx: &mut TestAppContext) {
 608        let mode = &EditFileMode::Edit;
 609
 610        let path_with_root = "root/dir/subdir/existing.txt";
 611        let path_without_root = "dir/subdir/existing.txt";
 612        let result = test_resolve_path(mode, path_with_root, cx);
 613        assert_resolved_path_eq(result.await, path_without_root);
 614
 615        let result = test_resolve_path(mode, path_without_root, cx);
 616        assert_resolved_path_eq(result.await, path_without_root);
 617
 618        let result = test_resolve_path(mode, "root/nonexistent.txt", cx);
 619        assert_eq!(
 620            result.await.unwrap_err().to_string(),
 621            "Can't edit file: path not found"
 622        );
 623
 624        let result = test_resolve_path(mode, "root/dir", cx);
 625        assert_eq!(
 626            result.await.unwrap_err().to_string(),
 627            "Can't edit file: path is a directory"
 628        );
 629    }
 630
 631    async fn test_resolve_path(
 632        mode: &EditFileMode,
 633        path: &str,
 634        cx: &mut TestAppContext,
 635    ) -> anyhow::Result<ProjectPath> {
 636        init_test(cx);
 637
 638        let fs = project::FakeFs::new(cx.executor());
 639        fs.insert_tree(
 640            "/root",
 641            json!({
 642                "dir": {
 643                    "subdir": {
 644                        "existing.txt": "hello"
 645                    }
 646                }
 647            }),
 648        )
 649        .await;
 650        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 651
 652        let input = EditFileToolInput {
 653            display_description: "Some edit".into(),
 654            path: path.into(),
 655            mode: mode.clone(),
 656        };
 657
 658        cx.update(|cx| resolve_path(&input, project, cx))
 659    }
 660
 661    fn assert_resolved_path_eq(path: anyhow::Result<ProjectPath>, expected: &str) {
 662        let actual = path
 663            .expect("Should return valid path")
 664            .path
 665            .to_str()
 666            .unwrap()
 667            .replace("\\", "/"); // Naive Windows paths normalization
 668        assert_eq!(actual, expected);
 669    }
 670
 671    #[gpui::test]
 672    async fn test_format_on_save(cx: &mut TestAppContext) {
 673        init_test(cx);
 674
 675        let fs = project::FakeFs::new(cx.executor());
 676        fs.insert_tree("/root", json!({"src": {}})).await;
 677
 678        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 679
 680        // Set up a Rust language with LSP formatting support
 681        let rust_language = Arc::new(language::Language::new(
 682            language::LanguageConfig {
 683                name: "Rust".into(),
 684                matcher: language::LanguageMatcher {
 685                    path_suffixes: vec!["rs".to_string()],
 686                    ..Default::default()
 687                },
 688                ..Default::default()
 689            },
 690            None,
 691        ));
 692
 693        // Register the language and fake LSP
 694        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 695        language_registry.add(rust_language);
 696
 697        let mut fake_language_servers = language_registry.register_fake_lsp(
 698            "Rust",
 699            language::FakeLspAdapter {
 700                capabilities: lsp::ServerCapabilities {
 701                    document_formatting_provider: Some(lsp::OneOf::Left(true)),
 702                    ..Default::default()
 703                },
 704                ..Default::default()
 705            },
 706        );
 707
 708        // Create the file
 709        fs.save(
 710            path!("/root/src/main.rs").as_ref(),
 711            &"initial content".into(),
 712            language::LineEnding::Unix,
 713        )
 714        .await
 715        .unwrap();
 716
 717        // Open the buffer to trigger LSP initialization
 718        let buffer = project
 719            .update(cx, |project, cx| {
 720                project.open_local_buffer(path!("/root/src/main.rs"), cx)
 721            })
 722            .await
 723            .unwrap();
 724
 725        // Register the buffer with language servers
 726        let _handle = project.update(cx, |project, cx| {
 727            project.register_buffer_with_language_servers(&buffer, cx)
 728        });
 729
 730        const UNFORMATTED_CONTENT: &str = "fn main() {println!(\"Hello!\");}\n";
 731        const FORMATTED_CONTENT: &str =
 732            "This file was formatted by the fake formatter in the test.\n";
 733
 734        // Get the fake language server and set up formatting handler
 735        let fake_language_server = fake_language_servers.next().await.unwrap();
 736        fake_language_server.set_request_handler::<lsp::request::Formatting, _, _>({
 737            |_, _| async move {
 738                Ok(Some(vec![lsp::TextEdit {
 739                    range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(1, 0)),
 740                    new_text: FORMATTED_CONTENT.to_string(),
 741                }]))
 742            }
 743        });
 744
 745        let action_log = cx.new(|_| ActionLog::new(project.clone()));
 746        let context_server_registry =
 747            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 748        let model = Arc::new(FakeLanguageModel::default());
 749        let thread = cx.new(|cx| {
 750            Thread::new(
 751                project,
 752                cx.new(|_cx| ProjectContext::default()),
 753                context_server_registry,
 754                action_log.clone(),
 755                Templates::new(),
 756                Some(model.clone()),
 757                cx,
 758            )
 759        });
 760
 761        // First, test with format_on_save enabled
 762        cx.update(|cx| {
 763            SettingsStore::update_global(cx, |store, cx| {
 764                store.update_user_settings::<language::language_settings::AllLanguageSettings>(
 765                    cx,
 766                    |settings| {
 767                        settings.defaults.format_on_save = Some(FormatOnSave::On);
 768                        settings.defaults.formatter =
 769                            Some(language::language_settings::SelectedFormatter::Auto);
 770                    },
 771                );
 772            });
 773        });
 774
 775        // Have the model stream unformatted content
 776        let edit_result = {
 777            let edit_task = cx.update(|cx| {
 778                let input = EditFileToolInput {
 779                    display_description: "Create main function".into(),
 780                    path: "root/src/main.rs".into(),
 781                    mode: EditFileMode::Overwrite,
 782                };
 783                Arc::new(EditFileTool::new(
 784                    thread.downgrade(),
 785                    language_registry.clone(),
 786                ))
 787                .run(input, ToolCallEventStream::test().0, cx)
 788            });
 789
 790            // Stream the unformatted content
 791            cx.executor().run_until_parked();
 792            model.send_last_completion_stream_text_chunk(UNFORMATTED_CONTENT.to_string());
 793            model.end_last_completion_stream();
 794
 795            edit_task.await
 796        };
 797        assert!(edit_result.is_ok());
 798
 799        // Wait for any async operations (e.g. formatting) to complete
 800        cx.executor().run_until_parked();
 801
 802        // Read the file to verify it was formatted automatically
 803        let new_content = fs.load(path!("/root/src/main.rs").as_ref()).await.unwrap();
 804        assert_eq!(
 805            // Ignore carriage returns on Windows
 806            new_content.replace("\r\n", "\n"),
 807            FORMATTED_CONTENT,
 808            "Code should be formatted when format_on_save is enabled"
 809        );
 810
 811        let stale_buffer_count = action_log.read_with(cx, |log, cx| log.stale_buffers(cx).count());
 812
 813        assert_eq!(
 814            stale_buffer_count, 0,
 815            "BUG: Buffer is incorrectly marked as stale after format-on-save. Found {} stale buffers. \
 816             This causes the agent to think the file was modified externally when it was just formatted.",
 817            stale_buffer_count
 818        );
 819
 820        // Next, test with format_on_save disabled
 821        cx.update(|cx| {
 822            SettingsStore::update_global(cx, |store, cx| {
 823                store.update_user_settings::<language::language_settings::AllLanguageSettings>(
 824                    cx,
 825                    |settings| {
 826                        settings.defaults.format_on_save = Some(FormatOnSave::Off);
 827                    },
 828                );
 829            });
 830        });
 831
 832        // Stream unformatted edits again
 833        let edit_result = {
 834            let edit_task = cx.update(|cx| {
 835                let input = EditFileToolInput {
 836                    display_description: "Update main function".into(),
 837                    path: "root/src/main.rs".into(),
 838                    mode: EditFileMode::Overwrite,
 839                };
 840                Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
 841                    input,
 842                    ToolCallEventStream::test().0,
 843                    cx,
 844                )
 845            });
 846
 847            // Stream the unformatted content
 848            cx.executor().run_until_parked();
 849            model.send_last_completion_stream_text_chunk(UNFORMATTED_CONTENT.to_string());
 850            model.end_last_completion_stream();
 851
 852            edit_task.await
 853        };
 854        assert!(edit_result.is_ok());
 855
 856        // Wait for any async operations (e.g. formatting) to complete
 857        cx.executor().run_until_parked();
 858
 859        // Verify the file was not formatted
 860        let new_content = fs.load(path!("/root/src/main.rs").as_ref()).await.unwrap();
 861        assert_eq!(
 862            // Ignore carriage returns on Windows
 863            new_content.replace("\r\n", "\n"),
 864            UNFORMATTED_CONTENT,
 865            "Code should not be formatted when format_on_save is disabled"
 866        );
 867    }
 868
 869    #[gpui::test]
 870    async fn test_remove_trailing_whitespace(cx: &mut TestAppContext) {
 871        init_test(cx);
 872
 873        let fs = project::FakeFs::new(cx.executor());
 874        fs.insert_tree("/root", json!({"src": {}})).await;
 875
 876        // Create a simple file with trailing whitespace
 877        fs.save(
 878            path!("/root/src/main.rs").as_ref(),
 879            &"initial content".into(),
 880            language::LineEnding::Unix,
 881        )
 882        .await
 883        .unwrap();
 884
 885        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 886        let context_server_registry =
 887            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 888        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
 889        let action_log = cx.new(|_| ActionLog::new(project.clone()));
 890        let model = Arc::new(FakeLanguageModel::default());
 891        let thread = cx.new(|cx| {
 892            Thread::new(
 893                project,
 894                cx.new(|_cx| ProjectContext::default()),
 895                context_server_registry,
 896                action_log.clone(),
 897                Templates::new(),
 898                Some(model.clone()),
 899                cx,
 900            )
 901        });
 902
 903        // First, test with remove_trailing_whitespace_on_save enabled
 904        cx.update(|cx| {
 905            SettingsStore::update_global(cx, |store, cx| {
 906                store.update_user_settings::<language::language_settings::AllLanguageSettings>(
 907                    cx,
 908                    |settings| {
 909                        settings.defaults.remove_trailing_whitespace_on_save = Some(true);
 910                    },
 911                );
 912            });
 913        });
 914
 915        const CONTENT_WITH_TRAILING_WHITESPACE: &str =
 916            "fn main() {  \n    println!(\"Hello!\");  \n}\n";
 917
 918        // Have the model stream content that contains trailing whitespace
 919        let edit_result = {
 920            let edit_task = cx.update(|cx| {
 921                let input = EditFileToolInput {
 922                    display_description: "Create main function".into(),
 923                    path: "root/src/main.rs".into(),
 924                    mode: EditFileMode::Overwrite,
 925                };
 926                Arc::new(EditFileTool::new(
 927                    thread.downgrade(),
 928                    language_registry.clone(),
 929                ))
 930                .run(input, ToolCallEventStream::test().0, cx)
 931            });
 932
 933            // Stream the content with trailing whitespace
 934            cx.executor().run_until_parked();
 935            model.send_last_completion_stream_text_chunk(
 936                CONTENT_WITH_TRAILING_WHITESPACE.to_string(),
 937            );
 938            model.end_last_completion_stream();
 939
 940            edit_task.await
 941        };
 942        assert!(edit_result.is_ok());
 943
 944        // Wait for any async operations (e.g. formatting) to complete
 945        cx.executor().run_until_parked();
 946
 947        // Read the file to verify trailing whitespace was removed automatically
 948        assert_eq!(
 949            // Ignore carriage returns on Windows
 950            fs.load(path!("/root/src/main.rs").as_ref())
 951                .await
 952                .unwrap()
 953                .replace("\r\n", "\n"),
 954            "fn main() {\n    println!(\"Hello!\");\n}\n",
 955            "Trailing whitespace should be removed when remove_trailing_whitespace_on_save is enabled"
 956        );
 957
 958        // Next, test with remove_trailing_whitespace_on_save disabled
 959        cx.update(|cx| {
 960            SettingsStore::update_global(cx, |store, cx| {
 961                store.update_user_settings::<language::language_settings::AllLanguageSettings>(
 962                    cx,
 963                    |settings| {
 964                        settings.defaults.remove_trailing_whitespace_on_save = Some(false);
 965                    },
 966                );
 967            });
 968        });
 969
 970        // Stream edits again with trailing whitespace
 971        let edit_result = {
 972            let edit_task = cx.update(|cx| {
 973                let input = EditFileToolInput {
 974                    display_description: "Update main function".into(),
 975                    path: "root/src/main.rs".into(),
 976                    mode: EditFileMode::Overwrite,
 977                };
 978                Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
 979                    input,
 980                    ToolCallEventStream::test().0,
 981                    cx,
 982                )
 983            });
 984
 985            // Stream the content with trailing whitespace
 986            cx.executor().run_until_parked();
 987            model.send_last_completion_stream_text_chunk(
 988                CONTENT_WITH_TRAILING_WHITESPACE.to_string(),
 989            );
 990            model.end_last_completion_stream();
 991
 992            edit_task.await
 993        };
 994        assert!(edit_result.is_ok());
 995
 996        // Wait for any async operations (e.g. formatting) to complete
 997        cx.executor().run_until_parked();
 998
 999        // Verify the file still has trailing whitespace
1000        // Read the file again - it should still have trailing whitespace
1001        let final_content = fs.load(path!("/root/src/main.rs").as_ref()).await.unwrap();
1002        assert_eq!(
1003            // Ignore carriage returns on Windows
1004            final_content.replace("\r\n", "\n"),
1005            CONTENT_WITH_TRAILING_WHITESPACE,
1006            "Trailing whitespace should remain when remove_trailing_whitespace_on_save is disabled"
1007        );
1008    }
1009
1010    #[gpui::test]
1011    async fn test_authorize(cx: &mut TestAppContext) {
1012        init_test(cx);
1013        let fs = project::FakeFs::new(cx.executor());
1014        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
1015        let context_server_registry =
1016            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1017        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1018        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1019        let model = Arc::new(FakeLanguageModel::default());
1020        let thread = cx.new(|cx| {
1021            Thread::new(
1022                project,
1023                cx.new(|_cx| ProjectContext::default()),
1024                context_server_registry,
1025                action_log.clone(),
1026                Templates::new(),
1027                Some(model.clone()),
1028                cx,
1029            )
1030        });
1031        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1032        fs.insert_tree("/root", json!({})).await;
1033
1034        // Test 1: Path with .zed component should require confirmation
1035        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1036        let _auth = cx.update(|cx| {
1037            tool.authorize(
1038                &EditFileToolInput {
1039                    display_description: "test 1".into(),
1040                    path: ".zed/settings.json".into(),
1041                    mode: EditFileMode::Edit,
1042                },
1043                &stream_tx,
1044                cx,
1045            )
1046        });
1047
1048        let event = stream_rx.expect_authorization().await;
1049        assert_eq!(
1050            event.tool_call.fields.title,
1051            Some("test 1 (local settings)".into())
1052        );
1053
1054        // Test 2: Path outside project should require confirmation
1055        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1056        let _auth = cx.update(|cx| {
1057            tool.authorize(
1058                &EditFileToolInput {
1059                    display_description: "test 2".into(),
1060                    path: "/etc/hosts".into(),
1061                    mode: EditFileMode::Edit,
1062                },
1063                &stream_tx,
1064                cx,
1065            )
1066        });
1067
1068        let event = stream_rx.expect_authorization().await;
1069        assert_eq!(event.tool_call.fields.title, Some("test 2".into()));
1070
1071        // Test 3: Relative path without .zed should not require confirmation
1072        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1073        cx.update(|cx| {
1074            tool.authorize(
1075                &EditFileToolInput {
1076                    display_description: "test 3".into(),
1077                    path: "root/src/main.rs".into(),
1078                    mode: EditFileMode::Edit,
1079                },
1080                &stream_tx,
1081                cx,
1082            )
1083        })
1084        .await
1085        .unwrap();
1086        assert!(stream_rx.try_next().is_err());
1087
1088        // Test 4: Path with .zed in the middle should require confirmation
1089        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1090        let _auth = cx.update(|cx| {
1091            tool.authorize(
1092                &EditFileToolInput {
1093                    display_description: "test 4".into(),
1094                    path: "root/.zed/tasks.json".into(),
1095                    mode: EditFileMode::Edit,
1096                },
1097                &stream_tx,
1098                cx,
1099            )
1100        });
1101        let event = stream_rx.expect_authorization().await;
1102        assert_eq!(
1103            event.tool_call.fields.title,
1104            Some("test 4 (local settings)".into())
1105        );
1106
1107        // Test 5: When always_allow_tool_actions is enabled, no confirmation needed
1108        cx.update(|cx| {
1109            let mut settings = agent_settings::AgentSettings::get_global(cx).clone();
1110            settings.always_allow_tool_actions = true;
1111            agent_settings::AgentSettings::override_global(settings, cx);
1112        });
1113
1114        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1115        cx.update(|cx| {
1116            tool.authorize(
1117                &EditFileToolInput {
1118                    display_description: "test 5.1".into(),
1119                    path: ".zed/settings.json".into(),
1120                    mode: EditFileMode::Edit,
1121                },
1122                &stream_tx,
1123                cx,
1124            )
1125        })
1126        .await
1127        .unwrap();
1128        assert!(stream_rx.try_next().is_err());
1129
1130        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1131        cx.update(|cx| {
1132            tool.authorize(
1133                &EditFileToolInput {
1134                    display_description: "test 5.2".into(),
1135                    path: "/etc/hosts".into(),
1136                    mode: EditFileMode::Edit,
1137                },
1138                &stream_tx,
1139                cx,
1140            )
1141        })
1142        .await
1143        .unwrap();
1144        assert!(stream_rx.try_next().is_err());
1145    }
1146
1147    #[gpui::test]
1148    async fn test_authorize_global_config(cx: &mut TestAppContext) {
1149        init_test(cx);
1150        let fs = project::FakeFs::new(cx.executor());
1151        fs.insert_tree("/project", json!({})).await;
1152        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1153        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1154        let context_server_registry =
1155            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1156        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1157        let model = Arc::new(FakeLanguageModel::default());
1158        let thread = cx.new(|cx| {
1159            Thread::new(
1160                project,
1161                cx.new(|_cx| ProjectContext::default()),
1162                context_server_registry,
1163                action_log.clone(),
1164                Templates::new(),
1165                Some(model.clone()),
1166                cx,
1167            )
1168        });
1169        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1170
1171        // Test global config paths - these should require confirmation if they exist and are outside the project
1172        let test_cases = vec![
1173            (
1174                "/etc/hosts",
1175                true,
1176                "System file should require confirmation",
1177            ),
1178            (
1179                "/usr/local/bin/script",
1180                true,
1181                "System bin file should require confirmation",
1182            ),
1183            (
1184                "project/normal_file.rs",
1185                false,
1186                "Normal project file should not require confirmation",
1187            ),
1188        ];
1189
1190        for (path, should_confirm, description) in test_cases {
1191            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1192            let auth = cx.update(|cx| {
1193                tool.authorize(
1194                    &EditFileToolInput {
1195                        display_description: "Edit file".into(),
1196                        path: path.into(),
1197                        mode: EditFileMode::Edit,
1198                    },
1199                    &stream_tx,
1200                    cx,
1201                )
1202            });
1203
1204            if should_confirm {
1205                stream_rx.expect_authorization().await;
1206            } else {
1207                auth.await.unwrap();
1208                assert!(
1209                    stream_rx.try_next().is_err(),
1210                    "Failed for case: {} - path: {} - expected no confirmation but got one",
1211                    description,
1212                    path
1213                );
1214            }
1215        }
1216    }
1217
1218    #[gpui::test]
1219    async fn test_needs_confirmation_with_multiple_worktrees(cx: &mut TestAppContext) {
1220        init_test(cx);
1221        let fs = project::FakeFs::new(cx.executor());
1222
1223        // Create multiple worktree directories
1224        fs.insert_tree(
1225            "/workspace/frontend",
1226            json!({
1227                "src": {
1228                    "main.js": "console.log('frontend');"
1229                }
1230            }),
1231        )
1232        .await;
1233        fs.insert_tree(
1234            "/workspace/backend",
1235            json!({
1236                "src": {
1237                    "main.rs": "fn main() {}"
1238                }
1239            }),
1240        )
1241        .await;
1242        fs.insert_tree(
1243            "/workspace/shared",
1244            json!({
1245                ".zed": {
1246                    "settings.json": "{}"
1247                }
1248            }),
1249        )
1250        .await;
1251
1252        // Create project with multiple worktrees
1253        let project = Project::test(
1254            fs.clone(),
1255            [
1256                path!("/workspace/frontend").as_ref(),
1257                path!("/workspace/backend").as_ref(),
1258                path!("/workspace/shared").as_ref(),
1259            ],
1260            cx,
1261        )
1262        .await;
1263        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1264        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1265        let context_server_registry =
1266            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1267        let model = Arc::new(FakeLanguageModel::default());
1268        let thread = cx.new(|cx| {
1269            Thread::new(
1270                project.clone(),
1271                cx.new(|_cx| ProjectContext::default()),
1272                context_server_registry.clone(),
1273                action_log.clone(),
1274                Templates::new(),
1275                Some(model.clone()),
1276                cx,
1277            )
1278        });
1279        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1280
1281        // Test files in different worktrees
1282        let test_cases = vec![
1283            ("frontend/src/main.js", false, "File in first worktree"),
1284            ("backend/src/main.rs", false, "File in second worktree"),
1285            (
1286                "shared/.zed/settings.json",
1287                true,
1288                ".zed file in third worktree",
1289            ),
1290            ("/etc/hosts", true, "Absolute path outside all worktrees"),
1291            (
1292                "../outside/file.txt",
1293                true,
1294                "Relative path outside worktrees",
1295            ),
1296        ];
1297
1298        for (path, should_confirm, description) in test_cases {
1299            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1300            let auth = cx.update(|cx| {
1301                tool.authorize(
1302                    &EditFileToolInput {
1303                        display_description: "Edit file".into(),
1304                        path: path.into(),
1305                        mode: EditFileMode::Edit,
1306                    },
1307                    &stream_tx,
1308                    cx,
1309                )
1310            });
1311
1312            if should_confirm {
1313                stream_rx.expect_authorization().await;
1314            } else {
1315                auth.await.unwrap();
1316                assert!(
1317                    stream_rx.try_next().is_err(),
1318                    "Failed for case: {} - path: {} - expected no confirmation but got one",
1319                    description,
1320                    path
1321                );
1322            }
1323        }
1324    }
1325
1326    #[gpui::test]
1327    async fn test_needs_confirmation_edge_cases(cx: &mut TestAppContext) {
1328        init_test(cx);
1329        let fs = project::FakeFs::new(cx.executor());
1330        fs.insert_tree(
1331            "/project",
1332            json!({
1333                ".zed": {
1334                    "settings.json": "{}"
1335                },
1336                "src": {
1337                    ".zed": {
1338                        "local.json": "{}"
1339                    }
1340                }
1341            }),
1342        )
1343        .await;
1344        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1345        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1346        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1347        let context_server_registry =
1348            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1349        let model = Arc::new(FakeLanguageModel::default());
1350        let thread = cx.new(|cx| {
1351            Thread::new(
1352                project.clone(),
1353                cx.new(|_cx| ProjectContext::default()),
1354                context_server_registry.clone(),
1355                action_log.clone(),
1356                Templates::new(),
1357                Some(model.clone()),
1358                cx,
1359            )
1360        });
1361        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1362
1363        // Test edge cases
1364        let test_cases = vec![
1365            // Empty path - find_project_path returns Some for empty paths
1366            ("", false, "Empty path is treated as project root"),
1367            // Root directory
1368            ("/", true, "Root directory should be outside project"),
1369            // Parent directory references - find_project_path resolves these
1370            (
1371                "project/../other",
1372                false,
1373                "Path with .. is resolved by find_project_path",
1374            ),
1375            (
1376                "project/./src/file.rs",
1377                false,
1378                "Path with . should work normally",
1379            ),
1380            // Windows-style paths (if on Windows)
1381            #[cfg(target_os = "windows")]
1382            ("C:\\Windows\\System32\\hosts", true, "Windows system path"),
1383            #[cfg(target_os = "windows")]
1384            ("project\\src\\main.rs", false, "Windows-style project path"),
1385        ];
1386
1387        for (path, should_confirm, description) in test_cases {
1388            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1389            let auth = cx.update(|cx| {
1390                tool.authorize(
1391                    &EditFileToolInput {
1392                        display_description: "Edit file".into(),
1393                        path: path.into(),
1394                        mode: EditFileMode::Edit,
1395                    },
1396                    &stream_tx,
1397                    cx,
1398                )
1399            });
1400
1401            if should_confirm {
1402                stream_rx.expect_authorization().await;
1403            } else {
1404                auth.await.unwrap();
1405                assert!(
1406                    stream_rx.try_next().is_err(),
1407                    "Failed for case: {} - path: {} - expected no confirmation but got one",
1408                    description,
1409                    path
1410                );
1411            }
1412        }
1413    }
1414
1415    #[gpui::test]
1416    async fn test_needs_confirmation_with_different_modes(cx: &mut TestAppContext) {
1417        init_test(cx);
1418        let fs = project::FakeFs::new(cx.executor());
1419        fs.insert_tree(
1420            "/project",
1421            json!({
1422                "existing.txt": "content",
1423                ".zed": {
1424                    "settings.json": "{}"
1425                }
1426            }),
1427        )
1428        .await;
1429        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1430        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1431        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1432        let context_server_registry =
1433            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1434        let model = Arc::new(FakeLanguageModel::default());
1435        let thread = cx.new(|cx| {
1436            Thread::new(
1437                project.clone(),
1438                cx.new(|_cx| ProjectContext::default()),
1439                context_server_registry.clone(),
1440                action_log.clone(),
1441                Templates::new(),
1442                Some(model.clone()),
1443                cx,
1444            )
1445        });
1446        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1447
1448        // Test different EditFileMode values
1449        let modes = vec![
1450            EditFileMode::Edit,
1451            EditFileMode::Create,
1452            EditFileMode::Overwrite,
1453        ];
1454
1455        for mode in modes {
1456            // Test .zed path with different modes
1457            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1458            let _auth = cx.update(|cx| {
1459                tool.authorize(
1460                    &EditFileToolInput {
1461                        display_description: "Edit settings".into(),
1462                        path: "project/.zed/settings.json".into(),
1463                        mode: mode.clone(),
1464                    },
1465                    &stream_tx,
1466                    cx,
1467                )
1468            });
1469
1470            stream_rx.expect_authorization().await;
1471
1472            // Test outside path with different modes
1473            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1474            let _auth = cx.update(|cx| {
1475                tool.authorize(
1476                    &EditFileToolInput {
1477                        display_description: "Edit file".into(),
1478                        path: "/outside/file.txt".into(),
1479                        mode: mode.clone(),
1480                    },
1481                    &stream_tx,
1482                    cx,
1483                )
1484            });
1485
1486            stream_rx.expect_authorization().await;
1487
1488            // Test normal path with different modes
1489            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1490            cx.update(|cx| {
1491                tool.authorize(
1492                    &EditFileToolInput {
1493                        display_description: "Edit file".into(),
1494                        path: "project/normal.txt".into(),
1495                        mode: mode.clone(),
1496                    },
1497                    &stream_tx,
1498                    cx,
1499                )
1500            })
1501            .await
1502            .unwrap();
1503            assert!(stream_rx.try_next().is_err());
1504        }
1505    }
1506
1507    #[gpui::test]
1508    async fn test_initial_title_with_partial_input(cx: &mut TestAppContext) {
1509        init_test(cx);
1510        let fs = project::FakeFs::new(cx.executor());
1511        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1512        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1513        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1514        let context_server_registry =
1515            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1516        let model = Arc::new(FakeLanguageModel::default());
1517        let thread = cx.new(|cx| {
1518            Thread::new(
1519                project.clone(),
1520                cx.new(|_cx| ProjectContext::default()),
1521                context_server_registry,
1522                action_log.clone(),
1523                Templates::new(),
1524                Some(model.clone()),
1525                cx,
1526            )
1527        });
1528        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1529
1530        assert_eq!(
1531            tool.initial_title(Err(json!({
1532                "path": "src/main.rs",
1533                "display_description": "",
1534                "old_string": "old code",
1535                "new_string": "new code"
1536            }))),
1537            "src/main.rs"
1538        );
1539        assert_eq!(
1540            tool.initial_title(Err(json!({
1541                "path": "",
1542                "display_description": "Fix error handling",
1543                "old_string": "old code",
1544                "new_string": "new code"
1545            }))),
1546            "Fix error handling"
1547        );
1548        assert_eq!(
1549            tool.initial_title(Err(json!({
1550                "path": "src/main.rs",
1551                "display_description": "Fix error handling",
1552                "old_string": "old code",
1553                "new_string": "new code"
1554            }))),
1555            "Fix error handling"
1556        );
1557        assert_eq!(
1558            tool.initial_title(Err(json!({
1559                "path": "",
1560                "display_description": "",
1561                "old_string": "old code",
1562                "new_string": "new code"
1563            }))),
1564            DEFAULT_UI_TEXT
1565        );
1566        assert_eq!(
1567            tool.initial_title(Err(serde_json::Value::Null)),
1568            DEFAULT_UI_TEXT
1569        );
1570    }
1571
1572    fn init_test(cx: &mut TestAppContext) {
1573        cx.update(|cx| {
1574            let settings_store = SettingsStore::test(cx);
1575            cx.set_global(settings_store);
1576            language::init(cx);
1577            TelemetrySettings::register(cx);
1578            agent_settings::AgentSettings::register(cx);
1579            Project::init_settings(cx);
1580        });
1581    }
1582}