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