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        let result = cx.update(|cx| resolve_path(&input, project, cx));
 659        result
 660    }
 661
 662    fn assert_resolved_path_eq(path: anyhow::Result<ProjectPath>, expected: &str) {
 663        let actual = path
 664            .expect("Should return valid path")
 665            .path
 666            .to_str()
 667            .unwrap()
 668            .replace("\\", "/"); // Naive Windows paths normalization
 669        assert_eq!(actual, expected);
 670    }
 671
 672    #[gpui::test]
 673    async fn test_format_on_save(cx: &mut TestAppContext) {
 674        init_test(cx);
 675
 676        let fs = project::FakeFs::new(cx.executor());
 677        fs.insert_tree("/root", json!({"src": {}})).await;
 678
 679        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 680
 681        // Set up a Rust language with LSP formatting support
 682        let rust_language = Arc::new(language::Language::new(
 683            language::LanguageConfig {
 684                name: "Rust".into(),
 685                matcher: language::LanguageMatcher {
 686                    path_suffixes: vec!["rs".to_string()],
 687                    ..Default::default()
 688                },
 689                ..Default::default()
 690            },
 691            None,
 692        ));
 693
 694        // Register the language and fake LSP
 695        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 696        language_registry.add(rust_language);
 697
 698        let mut fake_language_servers = language_registry.register_fake_lsp(
 699            "Rust",
 700            language::FakeLspAdapter {
 701                capabilities: lsp::ServerCapabilities {
 702                    document_formatting_provider: Some(lsp::OneOf::Left(true)),
 703                    ..Default::default()
 704                },
 705                ..Default::default()
 706            },
 707        );
 708
 709        // Create the file
 710        fs.save(
 711            path!("/root/src/main.rs").as_ref(),
 712            &"initial content".into(),
 713            language::LineEnding::Unix,
 714        )
 715        .await
 716        .unwrap();
 717
 718        // Open the buffer to trigger LSP initialization
 719        let buffer = project
 720            .update(cx, |project, cx| {
 721                project.open_local_buffer(path!("/root/src/main.rs"), cx)
 722            })
 723            .await
 724            .unwrap();
 725
 726        // Register the buffer with language servers
 727        let _handle = project.update(cx, |project, cx| {
 728            project.register_buffer_with_language_servers(&buffer, cx)
 729        });
 730
 731        const UNFORMATTED_CONTENT: &str = "fn main() {println!(\"Hello!\");}\n";
 732        const FORMATTED_CONTENT: &str =
 733            "This file was formatted by the fake formatter in the test.\n";
 734
 735        // Get the fake language server and set up formatting handler
 736        let fake_language_server = fake_language_servers.next().await.unwrap();
 737        fake_language_server.set_request_handler::<lsp::request::Formatting, _, _>({
 738            |_, _| async move {
 739                Ok(Some(vec![lsp::TextEdit {
 740                    range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(1, 0)),
 741                    new_text: FORMATTED_CONTENT.to_string(),
 742                }]))
 743            }
 744        });
 745
 746        let action_log = cx.new(|_| ActionLog::new(project.clone()));
 747        let context_server_registry =
 748            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 749        let model = Arc::new(FakeLanguageModel::default());
 750        let thread = cx.new(|cx| {
 751            Thread::new(
 752                project,
 753                cx.new(|_cx| ProjectContext::default()),
 754                context_server_registry,
 755                action_log.clone(),
 756                Templates::new(),
 757                Some(model.clone()),
 758                cx,
 759            )
 760        });
 761
 762        // First, test with format_on_save enabled
 763        cx.update(|cx| {
 764            SettingsStore::update_global(cx, |store, cx| {
 765                store.update_user_settings::<language::language_settings::AllLanguageSettings>(
 766                    cx,
 767                    |settings| {
 768                        settings.defaults.format_on_save = Some(FormatOnSave::On);
 769                        settings.defaults.formatter =
 770                            Some(language::language_settings::SelectedFormatter::Auto);
 771                    },
 772                );
 773            });
 774        });
 775
 776        // Have the model stream unformatted content
 777        let edit_result = {
 778            let edit_task = cx.update(|cx| {
 779                let input = EditFileToolInput {
 780                    display_description: "Create main function".into(),
 781                    path: "root/src/main.rs".into(),
 782                    mode: EditFileMode::Overwrite,
 783                };
 784                Arc::new(EditFileTool::new(
 785                    thread.downgrade(),
 786                    language_registry.clone(),
 787                ))
 788                .run(input, ToolCallEventStream::test().0, cx)
 789            });
 790
 791            // Stream the unformatted content
 792            cx.executor().run_until_parked();
 793            model.send_last_completion_stream_text_chunk(UNFORMATTED_CONTENT.to_string());
 794            model.end_last_completion_stream();
 795
 796            edit_task.await
 797        };
 798        assert!(edit_result.is_ok());
 799
 800        // Wait for any async operations (e.g. formatting) to complete
 801        cx.executor().run_until_parked();
 802
 803        // Read the file to verify it was formatted automatically
 804        let new_content = fs.load(path!("/root/src/main.rs").as_ref()).await.unwrap();
 805        assert_eq!(
 806            // Ignore carriage returns on Windows
 807            new_content.replace("\r\n", "\n"),
 808            FORMATTED_CONTENT,
 809            "Code should be formatted when format_on_save is enabled"
 810        );
 811
 812        let stale_buffer_count = action_log.read_with(cx, |log, cx| log.stale_buffers(cx).count());
 813
 814        assert_eq!(
 815            stale_buffer_count, 0,
 816            "BUG: Buffer is incorrectly marked as stale after format-on-save. Found {} stale buffers. \
 817             This causes the agent to think the file was modified externally when it was just formatted.",
 818            stale_buffer_count
 819        );
 820
 821        // Next, test with format_on_save disabled
 822        cx.update(|cx| {
 823            SettingsStore::update_global(cx, |store, cx| {
 824                store.update_user_settings::<language::language_settings::AllLanguageSettings>(
 825                    cx,
 826                    |settings| {
 827                        settings.defaults.format_on_save = Some(FormatOnSave::Off);
 828                    },
 829                );
 830            });
 831        });
 832
 833        // Stream unformatted edits again
 834        let edit_result = {
 835            let edit_task = cx.update(|cx| {
 836                let input = EditFileToolInput {
 837                    display_description: "Update main function".into(),
 838                    path: "root/src/main.rs".into(),
 839                    mode: EditFileMode::Overwrite,
 840                };
 841                Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
 842                    input,
 843                    ToolCallEventStream::test().0,
 844                    cx,
 845                )
 846            });
 847
 848            // Stream the unformatted content
 849            cx.executor().run_until_parked();
 850            model.send_last_completion_stream_text_chunk(UNFORMATTED_CONTENT.to_string());
 851            model.end_last_completion_stream();
 852
 853            edit_task.await
 854        };
 855        assert!(edit_result.is_ok());
 856
 857        // Wait for any async operations (e.g. formatting) to complete
 858        cx.executor().run_until_parked();
 859
 860        // Verify the file was not formatted
 861        let new_content = fs.load(path!("/root/src/main.rs").as_ref()).await.unwrap();
 862        assert_eq!(
 863            // Ignore carriage returns on Windows
 864            new_content.replace("\r\n", "\n"),
 865            UNFORMATTED_CONTENT,
 866            "Code should not be formatted when format_on_save is disabled"
 867        );
 868    }
 869
 870    #[gpui::test]
 871    async fn test_remove_trailing_whitespace(cx: &mut TestAppContext) {
 872        init_test(cx);
 873
 874        let fs = project::FakeFs::new(cx.executor());
 875        fs.insert_tree("/root", json!({"src": {}})).await;
 876
 877        // Create a simple file with trailing whitespace
 878        fs.save(
 879            path!("/root/src/main.rs").as_ref(),
 880            &"initial content".into(),
 881            language::LineEnding::Unix,
 882        )
 883        .await
 884        .unwrap();
 885
 886        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
 887        let context_server_registry =
 888            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 889        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
 890        let action_log = cx.new(|_| ActionLog::new(project.clone()));
 891        let model = Arc::new(FakeLanguageModel::default());
 892        let thread = cx.new(|cx| {
 893            Thread::new(
 894                project,
 895                cx.new(|_cx| ProjectContext::default()),
 896                context_server_registry,
 897                action_log.clone(),
 898                Templates::new(),
 899                Some(model.clone()),
 900                cx,
 901            )
 902        });
 903
 904        // First, test with remove_trailing_whitespace_on_save enabled
 905        cx.update(|cx| {
 906            SettingsStore::update_global(cx, |store, cx| {
 907                store.update_user_settings::<language::language_settings::AllLanguageSettings>(
 908                    cx,
 909                    |settings| {
 910                        settings.defaults.remove_trailing_whitespace_on_save = Some(true);
 911                    },
 912                );
 913            });
 914        });
 915
 916        const CONTENT_WITH_TRAILING_WHITESPACE: &str =
 917            "fn main() {  \n    println!(\"Hello!\");  \n}\n";
 918
 919        // Have the model stream content that contains trailing whitespace
 920        let edit_result = {
 921            let edit_task = cx.update(|cx| {
 922                let input = EditFileToolInput {
 923                    display_description: "Create main function".into(),
 924                    path: "root/src/main.rs".into(),
 925                    mode: EditFileMode::Overwrite,
 926                };
 927                Arc::new(EditFileTool::new(
 928                    thread.downgrade(),
 929                    language_registry.clone(),
 930                ))
 931                .run(input, ToolCallEventStream::test().0, cx)
 932            });
 933
 934            // Stream the content with trailing whitespace
 935            cx.executor().run_until_parked();
 936            model.send_last_completion_stream_text_chunk(
 937                CONTENT_WITH_TRAILING_WHITESPACE.to_string(),
 938            );
 939            model.end_last_completion_stream();
 940
 941            edit_task.await
 942        };
 943        assert!(edit_result.is_ok());
 944
 945        // Wait for any async operations (e.g. formatting) to complete
 946        cx.executor().run_until_parked();
 947
 948        // Read the file to verify trailing whitespace was removed automatically
 949        assert_eq!(
 950            // Ignore carriage returns on Windows
 951            fs.load(path!("/root/src/main.rs").as_ref())
 952                .await
 953                .unwrap()
 954                .replace("\r\n", "\n"),
 955            "fn main() {\n    println!(\"Hello!\");\n}\n",
 956            "Trailing whitespace should be removed when remove_trailing_whitespace_on_save is enabled"
 957        );
 958
 959        // Next, test with remove_trailing_whitespace_on_save disabled
 960        cx.update(|cx| {
 961            SettingsStore::update_global(cx, |store, cx| {
 962                store.update_user_settings::<language::language_settings::AllLanguageSettings>(
 963                    cx,
 964                    |settings| {
 965                        settings.defaults.remove_trailing_whitespace_on_save = Some(false);
 966                    },
 967                );
 968            });
 969        });
 970
 971        // Stream edits again with trailing whitespace
 972        let edit_result = {
 973            let edit_task = cx.update(|cx| {
 974                let input = EditFileToolInput {
 975                    display_description: "Update main function".into(),
 976                    path: "root/src/main.rs".into(),
 977                    mode: EditFileMode::Overwrite,
 978                };
 979                Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
 980                    input,
 981                    ToolCallEventStream::test().0,
 982                    cx,
 983                )
 984            });
 985
 986            // Stream the content with trailing whitespace
 987            cx.executor().run_until_parked();
 988            model.send_last_completion_stream_text_chunk(
 989                CONTENT_WITH_TRAILING_WHITESPACE.to_string(),
 990            );
 991            model.end_last_completion_stream();
 992
 993            edit_task.await
 994        };
 995        assert!(edit_result.is_ok());
 996
 997        // Wait for any async operations (e.g. formatting) to complete
 998        cx.executor().run_until_parked();
 999
1000        // Verify the file still has trailing whitespace
1001        // Read the file again - it should still have trailing whitespace
1002        let final_content = fs.load(path!("/root/src/main.rs").as_ref()).await.unwrap();
1003        assert_eq!(
1004            // Ignore carriage returns on Windows
1005            final_content.replace("\r\n", "\n"),
1006            CONTENT_WITH_TRAILING_WHITESPACE,
1007            "Trailing whitespace should remain when remove_trailing_whitespace_on_save is disabled"
1008        );
1009    }
1010
1011    #[gpui::test]
1012    async fn test_authorize(cx: &mut TestAppContext) {
1013        init_test(cx);
1014        let fs = project::FakeFs::new(cx.executor());
1015        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
1016        let context_server_registry =
1017            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1018        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1019        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1020        let model = Arc::new(FakeLanguageModel::default());
1021        let thread = cx.new(|cx| {
1022            Thread::new(
1023                project,
1024                cx.new(|_cx| ProjectContext::default()),
1025                context_server_registry,
1026                action_log.clone(),
1027                Templates::new(),
1028                Some(model.clone()),
1029                cx,
1030            )
1031        });
1032        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1033        fs.insert_tree("/root", json!({})).await;
1034
1035        // Test 1: Path with .zed component should require confirmation
1036        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1037        let _auth = cx.update(|cx| {
1038            tool.authorize(
1039                &EditFileToolInput {
1040                    display_description: "test 1".into(),
1041                    path: ".zed/settings.json".into(),
1042                    mode: EditFileMode::Edit,
1043                },
1044                &stream_tx,
1045                cx,
1046            )
1047        });
1048
1049        let event = stream_rx.expect_authorization().await;
1050        assert_eq!(
1051            event.tool_call.fields.title,
1052            Some("test 1 (local settings)".into())
1053        );
1054
1055        // Test 2: Path outside project should require confirmation
1056        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1057        let _auth = cx.update(|cx| {
1058            tool.authorize(
1059                &EditFileToolInput {
1060                    display_description: "test 2".into(),
1061                    path: "/etc/hosts".into(),
1062                    mode: EditFileMode::Edit,
1063                },
1064                &stream_tx,
1065                cx,
1066            )
1067        });
1068
1069        let event = stream_rx.expect_authorization().await;
1070        assert_eq!(event.tool_call.fields.title, Some("test 2".into()));
1071
1072        // Test 3: Relative path without .zed should not require confirmation
1073        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1074        cx.update(|cx| {
1075            tool.authorize(
1076                &EditFileToolInput {
1077                    display_description: "test 3".into(),
1078                    path: "root/src/main.rs".into(),
1079                    mode: EditFileMode::Edit,
1080                },
1081                &stream_tx,
1082                cx,
1083            )
1084        })
1085        .await
1086        .unwrap();
1087        assert!(stream_rx.try_next().is_err());
1088
1089        // Test 4: Path with .zed in the middle should require confirmation
1090        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1091        let _auth = cx.update(|cx| {
1092            tool.authorize(
1093                &EditFileToolInput {
1094                    display_description: "test 4".into(),
1095                    path: "root/.zed/tasks.json".into(),
1096                    mode: EditFileMode::Edit,
1097                },
1098                &stream_tx,
1099                cx,
1100            )
1101        });
1102        let event = stream_rx.expect_authorization().await;
1103        assert_eq!(
1104            event.tool_call.fields.title,
1105            Some("test 4 (local settings)".into())
1106        );
1107
1108        // Test 5: When always_allow_tool_actions is enabled, no confirmation needed
1109        cx.update(|cx| {
1110            let mut settings = agent_settings::AgentSettings::get_global(cx).clone();
1111            settings.always_allow_tool_actions = true;
1112            agent_settings::AgentSettings::override_global(settings, cx);
1113        });
1114
1115        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1116        cx.update(|cx| {
1117            tool.authorize(
1118                &EditFileToolInput {
1119                    display_description: "test 5.1".into(),
1120                    path: ".zed/settings.json".into(),
1121                    mode: EditFileMode::Edit,
1122                },
1123                &stream_tx,
1124                cx,
1125            )
1126        })
1127        .await
1128        .unwrap();
1129        assert!(stream_rx.try_next().is_err());
1130
1131        let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1132        cx.update(|cx| {
1133            tool.authorize(
1134                &EditFileToolInput {
1135                    display_description: "test 5.2".into(),
1136                    path: "/etc/hosts".into(),
1137                    mode: EditFileMode::Edit,
1138                },
1139                &stream_tx,
1140                cx,
1141            )
1142        })
1143        .await
1144        .unwrap();
1145        assert!(stream_rx.try_next().is_err());
1146    }
1147
1148    #[gpui::test]
1149    async fn test_authorize_global_config(cx: &mut TestAppContext) {
1150        init_test(cx);
1151        let fs = project::FakeFs::new(cx.executor());
1152        fs.insert_tree("/project", json!({})).await;
1153        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1154        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1155        let context_server_registry =
1156            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1157        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1158        let model = Arc::new(FakeLanguageModel::default());
1159        let thread = cx.new(|cx| {
1160            Thread::new(
1161                project,
1162                cx.new(|_cx| ProjectContext::default()),
1163                context_server_registry,
1164                action_log.clone(),
1165                Templates::new(),
1166                Some(model.clone()),
1167                cx,
1168            )
1169        });
1170        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1171
1172        // Test global config paths - these should require confirmation if they exist and are outside the project
1173        let test_cases = vec![
1174            (
1175                "/etc/hosts",
1176                true,
1177                "System file should require confirmation",
1178            ),
1179            (
1180                "/usr/local/bin/script",
1181                true,
1182                "System bin file should require confirmation",
1183            ),
1184            (
1185                "project/normal_file.rs",
1186                false,
1187                "Normal project file should not require confirmation",
1188            ),
1189        ];
1190
1191        for (path, should_confirm, description) in test_cases {
1192            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1193            let auth = cx.update(|cx| {
1194                tool.authorize(
1195                    &EditFileToolInput {
1196                        display_description: "Edit file".into(),
1197                        path: path.into(),
1198                        mode: EditFileMode::Edit,
1199                    },
1200                    &stream_tx,
1201                    cx,
1202                )
1203            });
1204
1205            if should_confirm {
1206                stream_rx.expect_authorization().await;
1207            } else {
1208                auth.await.unwrap();
1209                assert!(
1210                    stream_rx.try_next().is_err(),
1211                    "Failed for case: {} - path: {} - expected no confirmation but got one",
1212                    description,
1213                    path
1214                );
1215            }
1216        }
1217    }
1218
1219    #[gpui::test]
1220    async fn test_needs_confirmation_with_multiple_worktrees(cx: &mut TestAppContext) {
1221        init_test(cx);
1222        let fs = project::FakeFs::new(cx.executor());
1223
1224        // Create multiple worktree directories
1225        fs.insert_tree(
1226            "/workspace/frontend",
1227            json!({
1228                "src": {
1229                    "main.js": "console.log('frontend');"
1230                }
1231            }),
1232        )
1233        .await;
1234        fs.insert_tree(
1235            "/workspace/backend",
1236            json!({
1237                "src": {
1238                    "main.rs": "fn main() {}"
1239                }
1240            }),
1241        )
1242        .await;
1243        fs.insert_tree(
1244            "/workspace/shared",
1245            json!({
1246                ".zed": {
1247                    "settings.json": "{}"
1248                }
1249            }),
1250        )
1251        .await;
1252
1253        // Create project with multiple worktrees
1254        let project = Project::test(
1255            fs.clone(),
1256            [
1257                path!("/workspace/frontend").as_ref(),
1258                path!("/workspace/backend").as_ref(),
1259                path!("/workspace/shared").as_ref(),
1260            ],
1261            cx,
1262        )
1263        .await;
1264        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1265        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1266        let context_server_registry =
1267            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1268        let model = Arc::new(FakeLanguageModel::default());
1269        let thread = cx.new(|cx| {
1270            Thread::new(
1271                project.clone(),
1272                cx.new(|_cx| ProjectContext::default()),
1273                context_server_registry.clone(),
1274                action_log.clone(),
1275                Templates::new(),
1276                Some(model.clone()),
1277                cx,
1278            )
1279        });
1280        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1281
1282        // Test files in different worktrees
1283        let test_cases = vec![
1284            ("frontend/src/main.js", false, "File in first worktree"),
1285            ("backend/src/main.rs", false, "File in second worktree"),
1286            (
1287                "shared/.zed/settings.json",
1288                true,
1289                ".zed file in third worktree",
1290            ),
1291            ("/etc/hosts", true, "Absolute path outside all worktrees"),
1292            (
1293                "../outside/file.txt",
1294                true,
1295                "Relative path outside worktrees",
1296            ),
1297        ];
1298
1299        for (path, should_confirm, description) in test_cases {
1300            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1301            let auth = cx.update(|cx| {
1302                tool.authorize(
1303                    &EditFileToolInput {
1304                        display_description: "Edit file".into(),
1305                        path: path.into(),
1306                        mode: EditFileMode::Edit,
1307                    },
1308                    &stream_tx,
1309                    cx,
1310                )
1311            });
1312
1313            if should_confirm {
1314                stream_rx.expect_authorization().await;
1315            } else {
1316                auth.await.unwrap();
1317                assert!(
1318                    stream_rx.try_next().is_err(),
1319                    "Failed for case: {} - path: {} - expected no confirmation but got one",
1320                    description,
1321                    path
1322                );
1323            }
1324        }
1325    }
1326
1327    #[gpui::test]
1328    async fn test_needs_confirmation_edge_cases(cx: &mut TestAppContext) {
1329        init_test(cx);
1330        let fs = project::FakeFs::new(cx.executor());
1331        fs.insert_tree(
1332            "/project",
1333            json!({
1334                ".zed": {
1335                    "settings.json": "{}"
1336                },
1337                "src": {
1338                    ".zed": {
1339                        "local.json": "{}"
1340                    }
1341                }
1342            }),
1343        )
1344        .await;
1345        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1346        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1347        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1348        let context_server_registry =
1349            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1350        let model = Arc::new(FakeLanguageModel::default());
1351        let thread = cx.new(|cx| {
1352            Thread::new(
1353                project.clone(),
1354                cx.new(|_cx| ProjectContext::default()),
1355                context_server_registry.clone(),
1356                action_log.clone(),
1357                Templates::new(),
1358                Some(model.clone()),
1359                cx,
1360            )
1361        });
1362        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1363
1364        // Test edge cases
1365        let test_cases = vec![
1366            // Empty path - find_project_path returns Some for empty paths
1367            ("", false, "Empty path is treated as project root"),
1368            // Root directory
1369            ("/", true, "Root directory should be outside project"),
1370            // Parent directory references - find_project_path resolves these
1371            (
1372                "project/../other",
1373                false,
1374                "Path with .. is resolved by find_project_path",
1375            ),
1376            (
1377                "project/./src/file.rs",
1378                false,
1379                "Path with . should work normally",
1380            ),
1381            // Windows-style paths (if on Windows)
1382            #[cfg(target_os = "windows")]
1383            ("C:\\Windows\\System32\\hosts", true, "Windows system path"),
1384            #[cfg(target_os = "windows")]
1385            ("project\\src\\main.rs", false, "Windows-style project path"),
1386        ];
1387
1388        for (path, should_confirm, description) in test_cases {
1389            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1390            let auth = cx.update(|cx| {
1391                tool.authorize(
1392                    &EditFileToolInput {
1393                        display_description: "Edit file".into(),
1394                        path: path.into(),
1395                        mode: EditFileMode::Edit,
1396                    },
1397                    &stream_tx,
1398                    cx,
1399                )
1400            });
1401
1402            if should_confirm {
1403                stream_rx.expect_authorization().await;
1404            } else {
1405                auth.await.unwrap();
1406                assert!(
1407                    stream_rx.try_next().is_err(),
1408                    "Failed for case: {} - path: {} - expected no confirmation but got one",
1409                    description,
1410                    path
1411                );
1412            }
1413        }
1414    }
1415
1416    #[gpui::test]
1417    async fn test_needs_confirmation_with_different_modes(cx: &mut TestAppContext) {
1418        init_test(cx);
1419        let fs = project::FakeFs::new(cx.executor());
1420        fs.insert_tree(
1421            "/project",
1422            json!({
1423                "existing.txt": "content",
1424                ".zed": {
1425                    "settings.json": "{}"
1426                }
1427            }),
1428        )
1429        .await;
1430        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1431        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1432        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1433        let context_server_registry =
1434            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1435        let model = Arc::new(FakeLanguageModel::default());
1436        let thread = cx.new(|cx| {
1437            Thread::new(
1438                project.clone(),
1439                cx.new(|_cx| ProjectContext::default()),
1440                context_server_registry.clone(),
1441                action_log.clone(),
1442                Templates::new(),
1443                Some(model.clone()),
1444                cx,
1445            )
1446        });
1447        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1448
1449        // Test different EditFileMode values
1450        let modes = vec![
1451            EditFileMode::Edit,
1452            EditFileMode::Create,
1453            EditFileMode::Overwrite,
1454        ];
1455
1456        for mode in modes {
1457            // Test .zed path with different modes
1458            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1459            let _auth = cx.update(|cx| {
1460                tool.authorize(
1461                    &EditFileToolInput {
1462                        display_description: "Edit settings".into(),
1463                        path: "project/.zed/settings.json".into(),
1464                        mode: mode.clone(),
1465                    },
1466                    &stream_tx,
1467                    cx,
1468                )
1469            });
1470
1471            stream_rx.expect_authorization().await;
1472
1473            // Test outside path with different modes
1474            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1475            let _auth = cx.update(|cx| {
1476                tool.authorize(
1477                    &EditFileToolInput {
1478                        display_description: "Edit file".into(),
1479                        path: "/outside/file.txt".into(),
1480                        mode: mode.clone(),
1481                    },
1482                    &stream_tx,
1483                    cx,
1484                )
1485            });
1486
1487            stream_rx.expect_authorization().await;
1488
1489            // Test normal path with different modes
1490            let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1491            cx.update(|cx| {
1492                tool.authorize(
1493                    &EditFileToolInput {
1494                        display_description: "Edit file".into(),
1495                        path: "project/normal.txt".into(),
1496                        mode: mode.clone(),
1497                    },
1498                    &stream_tx,
1499                    cx,
1500                )
1501            })
1502            .await
1503            .unwrap();
1504            assert!(stream_rx.try_next().is_err());
1505        }
1506    }
1507
1508    #[gpui::test]
1509    async fn test_initial_title_with_partial_input(cx: &mut TestAppContext) {
1510        init_test(cx);
1511        let fs = project::FakeFs::new(cx.executor());
1512        let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1513        let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1514        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1515        let context_server_registry =
1516            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
1517        let model = Arc::new(FakeLanguageModel::default());
1518        let thread = cx.new(|cx| {
1519            Thread::new(
1520                project.clone(),
1521                cx.new(|_cx| ProjectContext::default()),
1522                context_server_registry,
1523                action_log.clone(),
1524                Templates::new(),
1525                Some(model.clone()),
1526                cx,
1527            )
1528        });
1529        let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1530
1531        assert_eq!(
1532            tool.initial_title(Err(json!({
1533                "path": "src/main.rs",
1534                "display_description": "",
1535                "old_string": "old code",
1536                "new_string": "new code"
1537            }))),
1538            "src/main.rs"
1539        );
1540        assert_eq!(
1541            tool.initial_title(Err(json!({
1542                "path": "",
1543                "display_description": "Fix error handling",
1544                "old_string": "old code",
1545                "new_string": "new code"
1546            }))),
1547            "Fix error handling"
1548        );
1549        assert_eq!(
1550            tool.initial_title(Err(json!({
1551                "path": "src/main.rs",
1552                "display_description": "Fix error handling",
1553                "old_string": "old code",
1554                "new_string": "new code"
1555            }))),
1556            "Fix error handling"
1557        );
1558        assert_eq!(
1559            tool.initial_title(Err(json!({
1560                "path": "",
1561                "display_description": "",
1562                "old_string": "old code",
1563                "new_string": "new code"
1564            }))),
1565            DEFAULT_UI_TEXT
1566        );
1567        assert_eq!(
1568            tool.initial_title(Err(serde_json::Value::Null)),
1569            DEFAULT_UI_TEXT
1570        );
1571    }
1572
1573    fn init_test(cx: &mut TestAppContext) {
1574        cx.update(|cx| {
1575            let settings_store = SettingsStore::test(cx);
1576            cx.set_global(settings_store);
1577            language::init(cx);
1578            TelemetrySettings::register(cx);
1579            agent_settings::AgentSettings::register(cx);
1580            Project::init_settings(cx);
1581        });
1582    }
1583}