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().clone(), thread.action_log().clone())
261 })?;
262
263 let edit_format = EditFormat::from_model(model.clone())?;
264 let edit_agent = EditAgent::new(
265 model,
266 project.clone(),
267 action_log.clone(),
268 // TODO: move edit agent to this crate so we can use our templates
269 assistant_tools::templates::Templates::new(),
270 edit_format,
271 );
272
273 let buffer = project
274 .update(cx, |project, cx| {
275 project.open_buffer(project_path.clone(), cx)
276 })?
277 .await?;
278
279 let diff = cx.new(|cx| Diff::new(buffer.clone(), cx))?;
280 event_stream.update_diff(diff.clone());
281
282 let old_snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
283 let old_text = cx
284 .background_spawn({
285 let old_snapshot = old_snapshot.clone();
286 async move { Arc::new(old_snapshot.text()) }
287 })
288 .await;
289
290
291 let (output, mut events) = if matches!(input.mode, EditFileMode::Edit) {
292 edit_agent.edit(
293 buffer.clone(),
294 input.display_description.clone(),
295 &request,
296 cx,
297 )
298 } else {
299 edit_agent.overwrite(
300 buffer.clone(),
301 input.display_description.clone(),
302 &request,
303 cx,
304 )
305 };
306
307 let mut hallucinated_old_text = false;
308 let mut ambiguous_ranges = Vec::new();
309 let mut emitted_location = false;
310 while let Some(event) = events.next().await {
311 match event {
312 EditAgentOutputEvent::Edited(range) => {
313 if !emitted_location {
314 let line = buffer.update(cx, |buffer, _cx| {
315 range.start.to_point(&buffer.snapshot()).row
316 }).ok();
317 if let Some(abs_path) = abs_path.clone() {
318 event_stream.update_fields(ToolCallUpdateFields {
319 locations: Some(vec![ToolCallLocation { path: abs_path, line }]),
320 ..Default::default()
321 });
322 }
323 emitted_location = true;
324 }
325 },
326 EditAgentOutputEvent::UnresolvedEditRange => hallucinated_old_text = true,
327 EditAgentOutputEvent::AmbiguousEditRange(ranges) => ambiguous_ranges = ranges,
328 EditAgentOutputEvent::ResolvingEditRange(range) => {
329 diff.update(cx, |card, cx| card.reveal_range(range.clone(), cx))?;
330 // if !emitted_location {
331 // let line = buffer.update(cx, |buffer, _cx| {
332 // range.start.to_point(&buffer.snapshot()).row
333 // }).ok();
334 // if let Some(abs_path) = abs_path.clone() {
335 // event_stream.update_fields(ToolCallUpdateFields {
336 // locations: Some(vec![ToolCallLocation { path: abs_path, line }]),
337 // ..Default::default()
338 // });
339 // }
340 // }
341 }
342 }
343 }
344
345 // If format_on_save is enabled, format the buffer
346 let format_on_save_enabled = buffer
347 .read_with(cx, |buffer, cx| {
348 let settings = language_settings::language_settings(
349 buffer.language().map(|l| l.name()),
350 buffer.file(),
351 cx,
352 );
353 settings.format_on_save != FormatOnSave::Off
354 })
355 .unwrap_or(false);
356
357 let edit_agent_output = output.await?;
358
359 if format_on_save_enabled {
360 action_log.update(cx, |log, cx| {
361 log.buffer_edited(buffer.clone(), cx);
362 })?;
363
364 let format_task = project.update(cx, |project, cx| {
365 project.format(
366 HashSet::from_iter([buffer.clone()]),
367 LspFormatTarget::Buffers,
368 false, // Don't push to history since the tool did it.
369 FormatTrigger::Save,
370 cx,
371 )
372 })?;
373 format_task.await.log_err();
374 }
375
376 project
377 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))?
378 .await?;
379
380 action_log.update(cx, |log, cx| {
381 log.buffer_edited(buffer.clone(), cx);
382 })?;
383
384 let new_snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
385 let (new_text, unified_diff) = cx
386 .background_spawn({
387 let new_snapshot = new_snapshot.clone();
388 let old_text = old_text.clone();
389 async move {
390 let new_text = new_snapshot.text();
391 let diff = language::unified_diff(&old_text, &new_text);
392 (new_text, diff)
393 }
394 })
395 .await;
396
397 diff.update(cx, |diff, cx| diff.finalize(cx)).ok();
398
399 let input_path = input.path.display();
400 if unified_diff.is_empty() {
401 anyhow::ensure!(
402 !hallucinated_old_text,
403 formatdoc! {"
404 Some edits were produced but none of them could be applied.
405 Read the relevant sections of {input_path} again so that
406 I can perform the requested edits.
407 "}
408 );
409 anyhow::ensure!(
410 ambiguous_ranges.is_empty(),
411 {
412 let line_numbers = ambiguous_ranges
413 .iter()
414 .map(|range| range.start.to_string())
415 .collect::<Vec<_>>()
416 .join(", ");
417 formatdoc! {"
418 <old_text> matches more than one position in the file (lines: {line_numbers}). Read the
419 relevant sections of {input_path} again and extend <old_text> so
420 that I can perform the requested edits.
421 "}
422 }
423 );
424 }
425
426 Ok(EditFileToolOutput {
427 input_path: input.path,
428 new_text: new_text.clone(),
429 old_text,
430 diff: unified_diff,
431 edit_agent_output,
432 })
433 })
434 }
435
436 fn replay(
437 &self,
438 _input: Self::Input,
439 output: Self::Output,
440 event_stream: ToolCallEventStream,
441 cx: &mut App,
442 ) -> Result<()> {
443 event_stream.update_diff(cx.new(|cx| {
444 Diff::finalized(
445 output.input_path,
446 Some(output.old_text.to_string()),
447 output.new_text,
448 self.language_registry.clone(),
449 cx,
450 )
451 }));
452 Ok(())
453 }
454}
455
456/// Validate that the file path is valid, meaning:
457///
458/// - For `edit` and `overwrite`, the path must point to an existing file.
459/// - For `create`, the file must not already exist, but it's parent dir must exist.
460fn resolve_path(
461 input: &EditFileToolInput,
462 project: Entity<Project>,
463 cx: &mut App,
464) -> Result<ProjectPath> {
465 let project = project.read(cx);
466
467 match input.mode {
468 EditFileMode::Edit | EditFileMode::Overwrite => {
469 let path = project
470 .find_project_path(&input.path, cx)
471 .context("Can't edit file: path not found")?;
472
473 let entry = project
474 .entry_for_path(&path, cx)
475 .context("Can't edit file: path not found")?;
476
477 anyhow::ensure!(entry.is_file(), "Can't edit file: path is a directory");
478 Ok(path)
479 }
480
481 EditFileMode::Create => {
482 if let Some(path) = project.find_project_path(&input.path, cx) {
483 anyhow::ensure!(
484 project.entry_for_path(&path, cx).is_none(),
485 "Can't create file: file already exists"
486 );
487 }
488
489 let parent_path = input
490 .path
491 .parent()
492 .context("Can't create file: incorrect path")?;
493
494 let parent_project_path = project.find_project_path(&parent_path, cx);
495
496 let parent_entry = parent_project_path
497 .as_ref()
498 .and_then(|path| project.entry_for_path(&path, cx))
499 .context("Can't create file: parent directory doesn't exist")?;
500
501 anyhow::ensure!(
502 parent_entry.is_dir(),
503 "Can't create file: parent is not a directory"
504 );
505
506 let file_name = input
507 .path
508 .file_name()
509 .context("Can't create file: invalid filename")?;
510
511 let new_file_path = parent_project_path.map(|parent| ProjectPath {
512 path: Arc::from(parent.path.join(file_name)),
513 ..parent
514 });
515
516 new_file_path.context("Can't create file")
517 }
518 }
519}
520
521#[cfg(test)]
522mod tests {
523 use super::*;
524 use action_log::ActionLog;
525 use client::TelemetrySettings;
526 use fs::Fs;
527 use gpui::{TestAppContext, UpdateGlobal};
528 use language_model::fake_provider::FakeLanguageModel;
529 use serde_json::json;
530 use settings::SettingsStore;
531 use util::path;
532
533 #[gpui::test]
534 async fn test_edit_nonexistent_file(cx: &mut TestAppContext) {
535 init_test(cx);
536
537 let fs = project::FakeFs::new(cx.executor());
538 fs.insert_tree("/root", json!({})).await;
539 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
540 let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
541 let action_log = cx.new(|_| ActionLog::new(project.clone()));
542 let model = Arc::new(FakeLanguageModel::default());
543 let thread = cx.new(|cx| Thread::test(model, project, action_log, cx));
544 let result = cx
545 .update(|cx| {
546 let input = EditFileToolInput {
547 display_description: "Some edit".into(),
548 path: "root/nonexistent_file.txt".into(),
549 mode: EditFileMode::Edit,
550 };
551 Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
552 input,
553 ToolCallEventStream::test().0,
554 cx,
555 )
556 })
557 .await;
558 assert_eq!(
559 result.unwrap_err().to_string(),
560 "Can't edit file: path not found"
561 );
562 }
563
564 #[gpui::test]
565 async fn test_resolve_path_for_creating_file(cx: &mut TestAppContext) {
566 let mode = &EditFileMode::Create;
567
568 let result = test_resolve_path(mode, "root/new.txt", cx);
569 assert_resolved_path_eq(result.await, "new.txt");
570
571 let result = test_resolve_path(mode, "new.txt", cx);
572 assert_resolved_path_eq(result.await, "new.txt");
573
574 let result = test_resolve_path(mode, "dir/new.txt", cx);
575 assert_resolved_path_eq(result.await, "dir/new.txt");
576
577 let result = test_resolve_path(mode, "root/dir/subdir/existing.txt", cx);
578 assert_eq!(
579 result.await.unwrap_err().to_string(),
580 "Can't create file: file already exists"
581 );
582
583 let result = test_resolve_path(mode, "root/dir/nonexistent_dir/new.txt", cx);
584 assert_eq!(
585 result.await.unwrap_err().to_string(),
586 "Can't create file: parent directory doesn't exist"
587 );
588 }
589
590 #[gpui::test]
591 async fn test_resolve_path_for_editing_file(cx: &mut TestAppContext) {
592 let mode = &EditFileMode::Edit;
593
594 let path_with_root = "root/dir/subdir/existing.txt";
595 let path_without_root = "dir/subdir/existing.txt";
596 let result = test_resolve_path(mode, path_with_root, cx);
597 assert_resolved_path_eq(result.await, path_without_root);
598
599 let result = test_resolve_path(mode, path_without_root, cx);
600 assert_resolved_path_eq(result.await, path_without_root);
601
602 let result = test_resolve_path(mode, "root/nonexistent.txt", cx);
603 assert_eq!(
604 result.await.unwrap_err().to_string(),
605 "Can't edit file: path not found"
606 );
607
608 let result = test_resolve_path(mode, "root/dir", cx);
609 assert_eq!(
610 result.await.unwrap_err().to_string(),
611 "Can't edit file: path is a directory"
612 );
613 }
614
615 async fn test_resolve_path(
616 mode: &EditFileMode,
617 path: &str,
618 cx: &mut TestAppContext,
619 ) -> anyhow::Result<ProjectPath> {
620 init_test(cx);
621
622 let fs = project::FakeFs::new(cx.executor());
623 fs.insert_tree(
624 "/root",
625 json!({
626 "dir": {
627 "subdir": {
628 "existing.txt": "hello"
629 }
630 }
631 }),
632 )
633 .await;
634 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
635
636 let input = EditFileToolInput {
637 display_description: "Some edit".into(),
638 path: path.into(),
639 mode: mode.clone(),
640 };
641
642 let result = cx.update(|cx| resolve_path(&input, project, cx));
643 result
644 }
645
646 fn assert_resolved_path_eq(path: anyhow::Result<ProjectPath>, expected: &str) {
647 let actual = path
648 .expect("Should return valid path")
649 .path
650 .to_str()
651 .unwrap()
652 .replace("\\", "/"); // Naive Windows paths normalization
653 assert_eq!(actual, expected);
654 }
655
656 #[gpui::test]
657 async fn test_format_on_save(cx: &mut TestAppContext) {
658 init_test(cx);
659
660 let fs = project::FakeFs::new(cx.executor());
661 fs.insert_tree("/root", json!({"src": {}})).await;
662
663 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
664
665 // Set up a Rust language with LSP formatting support
666 let rust_language = Arc::new(language::Language::new(
667 language::LanguageConfig {
668 name: "Rust".into(),
669 matcher: language::LanguageMatcher {
670 path_suffixes: vec!["rs".to_string()],
671 ..Default::default()
672 },
673 ..Default::default()
674 },
675 None,
676 ));
677
678 // Register the language and fake LSP
679 let language_registry = project.read_with(cx, |project, _| project.languages().clone());
680 language_registry.add(rust_language);
681
682 let mut fake_language_servers = language_registry.register_fake_lsp(
683 "Rust",
684 language::FakeLspAdapter {
685 capabilities: lsp::ServerCapabilities {
686 document_formatting_provider: Some(lsp::OneOf::Left(true)),
687 ..Default::default()
688 },
689 ..Default::default()
690 },
691 );
692
693 // Create the file
694 fs.save(
695 path!("/root/src/main.rs").as_ref(),
696 &"initial content".into(),
697 language::LineEnding::Unix,
698 )
699 .await
700 .unwrap();
701
702 // Open the buffer to trigger LSP initialization
703 let buffer = project
704 .update(cx, |project, cx| {
705 project.open_local_buffer(path!("/root/src/main.rs"), cx)
706 })
707 .await
708 .unwrap();
709
710 // Register the buffer with language servers
711 let _handle = project.update(cx, |project, cx| {
712 project.register_buffer_with_language_servers(&buffer, cx)
713 });
714
715 const UNFORMATTED_CONTENT: &str = "fn main() {println!(\"Hello!\");}\n";
716 const FORMATTED_CONTENT: &str =
717 "This file was formatted by the fake formatter in the test.\n";
718
719 // Get the fake language server and set up formatting handler
720 let fake_language_server = fake_language_servers.next().await.unwrap();
721 fake_language_server.set_request_handler::<lsp::request::Formatting, _, _>({
722 |_, _| async move {
723 Ok(Some(vec![lsp::TextEdit {
724 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(1, 0)),
725 new_text: FORMATTED_CONTENT.to_string(),
726 }]))
727 }
728 });
729
730 let action_log = cx.new(|_| ActionLog::new(project.clone()));
731 let model = Arc::new(FakeLanguageModel::default());
732 let thread = cx.new(|cx| Thread::test(model.clone(), project, action_log.clone(), cx));
733
734 // First, test with format_on_save enabled
735 cx.update(|cx| {
736 SettingsStore::update_global(cx, |store, cx| {
737 store.update_user_settings::<language::language_settings::AllLanguageSettings>(
738 cx,
739 |settings| {
740 settings.defaults.format_on_save = Some(FormatOnSave::On);
741 settings.defaults.formatter =
742 Some(language::language_settings::SelectedFormatter::Auto);
743 },
744 );
745 });
746 });
747
748 // Have the model stream unformatted content
749 let edit_result = {
750 let edit_task = cx.update(|cx| {
751 let input = EditFileToolInput {
752 display_description: "Create main function".into(),
753 path: "root/src/main.rs".into(),
754 mode: EditFileMode::Overwrite,
755 };
756 Arc::new(EditFileTool::new(
757 thread.downgrade(),
758 language_registry.clone(),
759 ))
760 .run(input, ToolCallEventStream::test().0, cx)
761 });
762
763 // Stream the unformatted content
764 cx.executor().run_until_parked();
765 model.send_last_completion_stream_text_chunk(UNFORMATTED_CONTENT.to_string());
766 model.end_last_completion_stream();
767
768 edit_task.await
769 };
770 assert!(edit_result.is_ok());
771
772 // Wait for any async operations (e.g. formatting) to complete
773 cx.executor().run_until_parked();
774
775 // Read the file to verify it was formatted automatically
776 let new_content = fs.load(path!("/root/src/main.rs").as_ref()).await.unwrap();
777 assert_eq!(
778 // Ignore carriage returns on Windows
779 new_content.replace("\r\n", "\n"),
780 FORMATTED_CONTENT,
781 "Code should be formatted when format_on_save is enabled"
782 );
783
784 let stale_buffer_count = action_log.read_with(cx, |log, cx| log.stale_buffers(cx).count());
785
786 assert_eq!(
787 stale_buffer_count, 0,
788 "BUG: Buffer is incorrectly marked as stale after format-on-save. Found {} stale buffers. \
789 This causes the agent to think the file was modified externally when it was just formatted.",
790 stale_buffer_count
791 );
792
793 // Next, test with format_on_save disabled
794 cx.update(|cx| {
795 SettingsStore::update_global(cx, |store, cx| {
796 store.update_user_settings::<language::language_settings::AllLanguageSettings>(
797 cx,
798 |settings| {
799 settings.defaults.format_on_save = Some(FormatOnSave::Off);
800 },
801 );
802 });
803 });
804
805 // Stream unformatted edits again
806 let edit_result = {
807 let edit_task = cx.update(|cx| {
808 let input = EditFileToolInput {
809 display_description: "Update main function".into(),
810 path: "root/src/main.rs".into(),
811 mode: EditFileMode::Overwrite,
812 };
813 Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
814 input,
815 ToolCallEventStream::test().0,
816 cx,
817 )
818 });
819
820 // Stream the unformatted content
821 cx.executor().run_until_parked();
822 model.send_last_completion_stream_text_chunk(UNFORMATTED_CONTENT.to_string());
823 model.end_last_completion_stream();
824
825 edit_task.await
826 };
827 assert!(edit_result.is_ok());
828
829 // Wait for any async operations (e.g. formatting) to complete
830 cx.executor().run_until_parked();
831
832 // Verify the file was not formatted
833 let new_content = fs.load(path!("/root/src/main.rs").as_ref()).await.unwrap();
834 assert_eq!(
835 // Ignore carriage returns on Windows
836 new_content.replace("\r\n", "\n"),
837 UNFORMATTED_CONTENT,
838 "Code should not be formatted when format_on_save is disabled"
839 );
840 }
841
842 #[gpui::test]
843 async fn test_remove_trailing_whitespace(cx: &mut TestAppContext) {
844 init_test(cx);
845
846 let fs = project::FakeFs::new(cx.executor());
847 fs.insert_tree("/root", json!({"src": {}})).await;
848
849 // Create a simple file with trailing whitespace
850 fs.save(
851 path!("/root/src/main.rs").as_ref(),
852 &"initial content".into(),
853 language::LineEnding::Unix,
854 )
855 .await
856 .unwrap();
857
858 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
859 let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
860 let action_log = cx.new(|_| ActionLog::new(project.clone()));
861 let model = Arc::new(FakeLanguageModel::default());
862 let thread = cx.new(|cx| Thread::test(model.clone(), project, action_log, cx));
863
864 // First, test with remove_trailing_whitespace_on_save enabled
865 cx.update(|cx| {
866 SettingsStore::update_global(cx, |store, cx| {
867 store.update_user_settings::<language::language_settings::AllLanguageSettings>(
868 cx,
869 |settings| {
870 settings.defaults.remove_trailing_whitespace_on_save = Some(true);
871 },
872 );
873 });
874 });
875
876 const CONTENT_WITH_TRAILING_WHITESPACE: &str =
877 "fn main() { \n println!(\"Hello!\"); \n}\n";
878
879 // Have the model stream content that contains trailing whitespace
880 let edit_result = {
881 let edit_task = cx.update(|cx| {
882 let input = EditFileToolInput {
883 display_description: "Create main function".into(),
884 path: "root/src/main.rs".into(),
885 mode: EditFileMode::Overwrite,
886 };
887 Arc::new(EditFileTool::new(
888 thread.downgrade(),
889 language_registry.clone(),
890 ))
891 .run(input, ToolCallEventStream::test().0, cx)
892 });
893
894 // Stream the content with trailing whitespace
895 cx.executor().run_until_parked();
896 model.send_last_completion_stream_text_chunk(
897 CONTENT_WITH_TRAILING_WHITESPACE.to_string(),
898 );
899 model.end_last_completion_stream();
900
901 edit_task.await
902 };
903 assert!(edit_result.is_ok());
904
905 // Wait for any async operations (e.g. formatting) to complete
906 cx.executor().run_until_parked();
907
908 // Read the file to verify trailing whitespace was removed automatically
909 assert_eq!(
910 // Ignore carriage returns on Windows
911 fs.load(path!("/root/src/main.rs").as_ref())
912 .await
913 .unwrap()
914 .replace("\r\n", "\n"),
915 "fn main() {\n println!(\"Hello!\");\n}\n",
916 "Trailing whitespace should be removed when remove_trailing_whitespace_on_save is enabled"
917 );
918
919 // Next, test with remove_trailing_whitespace_on_save disabled
920 cx.update(|cx| {
921 SettingsStore::update_global(cx, |store, cx| {
922 store.update_user_settings::<language::language_settings::AllLanguageSettings>(
923 cx,
924 |settings| {
925 settings.defaults.remove_trailing_whitespace_on_save = Some(false);
926 },
927 );
928 });
929 });
930
931 // Stream edits again with trailing whitespace
932 let edit_result = {
933 let edit_task = cx.update(|cx| {
934 let input = EditFileToolInput {
935 display_description: "Update main function".into(),
936 path: "root/src/main.rs".into(),
937 mode: EditFileMode::Overwrite,
938 };
939 Arc::new(EditFileTool::new(thread.downgrade(), language_registry)).run(
940 input,
941 ToolCallEventStream::test().0,
942 cx,
943 )
944 });
945
946 // Stream the content with trailing whitespace
947 cx.executor().run_until_parked();
948 model.send_last_completion_stream_text_chunk(
949 CONTENT_WITH_TRAILING_WHITESPACE.to_string(),
950 );
951 model.end_last_completion_stream();
952
953 edit_task.await
954 };
955 assert!(edit_result.is_ok());
956
957 // Wait for any async operations (e.g. formatting) to complete
958 cx.executor().run_until_parked();
959
960 // Verify the file still has trailing whitespace
961 // Read the file again - it should still have trailing whitespace
962 let final_content = fs.load(path!("/root/src/main.rs").as_ref()).await.unwrap();
963 assert_eq!(
964 // Ignore carriage returns on Windows
965 final_content.replace("\r\n", "\n"),
966 CONTENT_WITH_TRAILING_WHITESPACE,
967 "Trailing whitespace should remain when remove_trailing_whitespace_on_save is disabled"
968 );
969 }
970
971 #[gpui::test]
972 async fn test_authorize(cx: &mut TestAppContext) {
973 init_test(cx);
974 let fs = project::FakeFs::new(cx.executor());
975 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
976 let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
977 let action_log = cx.new(|_| ActionLog::new(project.clone()));
978 let model = Arc::new(FakeLanguageModel::default());
979 let thread = cx.new(|cx| Thread::test(model, project, action_log, cx));
980
981 let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
982 fs.insert_tree("/root", json!({})).await;
983
984 // Test 1: Path with .zed component should require confirmation
985 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
986 let _auth = cx.update(|cx| {
987 tool.authorize(
988 &EditFileToolInput {
989 display_description: "test 1".into(),
990 path: ".zed/settings.json".into(),
991 mode: EditFileMode::Edit,
992 },
993 &stream_tx,
994 cx,
995 )
996 });
997
998 let event = stream_rx.expect_authorization().await;
999 assert_eq!(
1000 event.tool_call.fields.title,
1001 Some("test 1 (local settings)".into())
1002 );
1003
1004 // Test 2: Path outside project should require confirmation
1005 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1006 let _auth = cx.update(|cx| {
1007 tool.authorize(
1008 &EditFileToolInput {
1009 display_description: "test 2".into(),
1010 path: "/etc/hosts".into(),
1011 mode: EditFileMode::Edit,
1012 },
1013 &stream_tx,
1014 cx,
1015 )
1016 });
1017
1018 let event = stream_rx.expect_authorization().await;
1019 assert_eq!(event.tool_call.fields.title, Some("test 2".into()));
1020
1021 // Test 3: Relative path without .zed should not require confirmation
1022 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1023 cx.update(|cx| {
1024 tool.authorize(
1025 &EditFileToolInput {
1026 display_description: "test 3".into(),
1027 path: "root/src/main.rs".into(),
1028 mode: EditFileMode::Edit,
1029 },
1030 &stream_tx,
1031 cx,
1032 )
1033 })
1034 .await
1035 .unwrap();
1036 assert!(stream_rx.try_next().is_err());
1037
1038 // Test 4: Path with .zed in the middle should require confirmation
1039 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1040 let _auth = cx.update(|cx| {
1041 tool.authorize(
1042 &EditFileToolInput {
1043 display_description: "test 4".into(),
1044 path: "root/.zed/tasks.json".into(),
1045 mode: EditFileMode::Edit,
1046 },
1047 &stream_tx,
1048 cx,
1049 )
1050 });
1051 let event = stream_rx.expect_authorization().await;
1052 assert_eq!(
1053 event.tool_call.fields.title,
1054 Some("test 4 (local settings)".into())
1055 );
1056
1057 // Test 5: When always_allow_tool_actions is enabled, no confirmation needed
1058 cx.update(|cx| {
1059 let mut settings = agent_settings::AgentSettings::get_global(cx).clone();
1060 settings.always_allow_tool_actions = true;
1061 agent_settings::AgentSettings::override_global(settings, cx);
1062 });
1063
1064 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1065 cx.update(|cx| {
1066 tool.authorize(
1067 &EditFileToolInput {
1068 display_description: "test 5.1".into(),
1069 path: ".zed/settings.json".into(),
1070 mode: EditFileMode::Edit,
1071 },
1072 &stream_tx,
1073 cx,
1074 )
1075 })
1076 .await
1077 .unwrap();
1078 assert!(stream_rx.try_next().is_err());
1079
1080 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1081 cx.update(|cx| {
1082 tool.authorize(
1083 &EditFileToolInput {
1084 display_description: "test 5.2".into(),
1085 path: "/etc/hosts".into(),
1086 mode: EditFileMode::Edit,
1087 },
1088 &stream_tx,
1089 cx,
1090 )
1091 })
1092 .await
1093 .unwrap();
1094 assert!(stream_rx.try_next().is_err());
1095 }
1096
1097 #[gpui::test]
1098 async fn test_authorize_global_config(cx: &mut TestAppContext) {
1099 init_test(cx);
1100 let fs = project::FakeFs::new(cx.executor());
1101 fs.insert_tree("/project", json!({})).await;
1102 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1103 let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1104 let action_log = cx.new(|_| ActionLog::new(project.clone()));
1105 let model = Arc::new(FakeLanguageModel::default());
1106 let thread = cx.new(|cx| Thread::test(model, project, action_log, cx));
1107
1108 let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1109
1110 // Test global config paths - these should require confirmation if they exist and are outside the project
1111 let test_cases = vec![
1112 (
1113 "/etc/hosts",
1114 true,
1115 "System file should require confirmation",
1116 ),
1117 (
1118 "/usr/local/bin/script",
1119 true,
1120 "System bin file should require confirmation",
1121 ),
1122 (
1123 "project/normal_file.rs",
1124 false,
1125 "Normal project file should not require confirmation",
1126 ),
1127 ];
1128
1129 for (path, should_confirm, description) in test_cases {
1130 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1131 let auth = cx.update(|cx| {
1132 tool.authorize(
1133 &EditFileToolInput {
1134 display_description: "Edit file".into(),
1135 path: path.into(),
1136 mode: EditFileMode::Edit,
1137 },
1138 &stream_tx,
1139 cx,
1140 )
1141 });
1142
1143 if should_confirm {
1144 stream_rx.expect_authorization().await;
1145 } else {
1146 auth.await.unwrap();
1147 assert!(
1148 stream_rx.try_next().is_err(),
1149 "Failed for case: {} - path: {} - expected no confirmation but got one",
1150 description,
1151 path
1152 );
1153 }
1154 }
1155 }
1156
1157 #[gpui::test]
1158 async fn test_needs_confirmation_with_multiple_worktrees(cx: &mut TestAppContext) {
1159 init_test(cx);
1160 let fs = project::FakeFs::new(cx.executor());
1161
1162 // Create multiple worktree directories
1163 fs.insert_tree(
1164 "/workspace/frontend",
1165 json!({
1166 "src": {
1167 "main.js": "console.log('frontend');"
1168 }
1169 }),
1170 )
1171 .await;
1172 fs.insert_tree(
1173 "/workspace/backend",
1174 json!({
1175 "src": {
1176 "main.rs": "fn main() {}"
1177 }
1178 }),
1179 )
1180 .await;
1181 fs.insert_tree(
1182 "/workspace/shared",
1183 json!({
1184 ".zed": {
1185 "settings.json": "{}"
1186 }
1187 }),
1188 )
1189 .await;
1190
1191 // Create project with multiple worktrees
1192 let project = Project::test(
1193 fs.clone(),
1194 [
1195 path!("/workspace/frontend").as_ref(),
1196 path!("/workspace/backend").as_ref(),
1197 path!("/workspace/shared").as_ref(),
1198 ],
1199 cx,
1200 )
1201 .await;
1202 let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1203 let action_log = cx.new(|_| ActionLog::new(project.clone()));
1204 let model = Arc::new(FakeLanguageModel::default());
1205 let thread = cx.new(|cx| Thread::test(model, project, action_log, cx));
1206
1207 let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1208
1209 // Test files in different worktrees
1210 let test_cases = vec![
1211 ("frontend/src/main.js", false, "File in first worktree"),
1212 ("backend/src/main.rs", false, "File in second worktree"),
1213 (
1214 "shared/.zed/settings.json",
1215 true,
1216 ".zed file in third worktree",
1217 ),
1218 ("/etc/hosts", true, "Absolute path outside all worktrees"),
1219 (
1220 "../outside/file.txt",
1221 true,
1222 "Relative path outside worktrees",
1223 ),
1224 ];
1225
1226 for (path, should_confirm, description) in test_cases {
1227 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1228 let auth = cx.update(|cx| {
1229 tool.authorize(
1230 &EditFileToolInput {
1231 display_description: "Edit file".into(),
1232 path: path.into(),
1233 mode: EditFileMode::Edit,
1234 },
1235 &stream_tx,
1236 cx,
1237 )
1238 });
1239
1240 if should_confirm {
1241 stream_rx.expect_authorization().await;
1242 } else {
1243 auth.await.unwrap();
1244 assert!(
1245 stream_rx.try_next().is_err(),
1246 "Failed for case: {} - path: {} - expected no confirmation but got one",
1247 description,
1248 path
1249 );
1250 }
1251 }
1252 }
1253
1254 #[gpui::test]
1255 async fn test_needs_confirmation_edge_cases(cx: &mut TestAppContext) {
1256 init_test(cx);
1257 let fs = project::FakeFs::new(cx.executor());
1258 fs.insert_tree(
1259 "/project",
1260 json!({
1261 ".zed": {
1262 "settings.json": "{}"
1263 },
1264 "src": {
1265 ".zed": {
1266 "local.json": "{}"
1267 }
1268 }
1269 }),
1270 )
1271 .await;
1272 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1273 let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1274 let action_log = cx.new(|_| ActionLog::new(project.clone()));
1275 let model = Arc::new(FakeLanguageModel::default());
1276 let thread = cx.new(|cx| Thread::test(model, project, action_log, cx));
1277
1278 let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1279
1280 // Test edge cases
1281 let test_cases = vec![
1282 // Empty path - find_project_path returns Some for empty paths
1283 ("", false, "Empty path is treated as project root"),
1284 // Root directory
1285 ("/", true, "Root directory should be outside project"),
1286 // Parent directory references - find_project_path resolves these
1287 (
1288 "project/../other",
1289 false,
1290 "Path with .. is resolved by find_project_path",
1291 ),
1292 (
1293 "project/./src/file.rs",
1294 false,
1295 "Path with . should work normally",
1296 ),
1297 // Windows-style paths (if on Windows)
1298 #[cfg(target_os = "windows")]
1299 ("C:\\Windows\\System32\\hosts", true, "Windows system path"),
1300 #[cfg(target_os = "windows")]
1301 ("project\\src\\main.rs", false, "Windows-style project path"),
1302 ];
1303
1304 for (path, should_confirm, description) in test_cases {
1305 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1306 let auth = cx.update(|cx| {
1307 tool.authorize(
1308 &EditFileToolInput {
1309 display_description: "Edit file".into(),
1310 path: path.into(),
1311 mode: EditFileMode::Edit,
1312 },
1313 &stream_tx,
1314 cx,
1315 )
1316 });
1317
1318 if should_confirm {
1319 stream_rx.expect_authorization().await;
1320 } else {
1321 auth.await.unwrap();
1322 assert!(
1323 stream_rx.try_next().is_err(),
1324 "Failed for case: {} - path: {} - expected no confirmation but got one",
1325 description,
1326 path
1327 );
1328 }
1329 }
1330 }
1331
1332 #[gpui::test]
1333 async fn test_needs_confirmation_with_different_modes(cx: &mut TestAppContext) {
1334 init_test(cx);
1335 let fs = project::FakeFs::new(cx.executor());
1336 fs.insert_tree(
1337 "/project",
1338 json!({
1339 "existing.txt": "content",
1340 ".zed": {
1341 "settings.json": "{}"
1342 }
1343 }),
1344 )
1345 .await;
1346 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1347 let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1348 let action_log = cx.new(|_| ActionLog::new(project.clone()));
1349 let model = Arc::new(FakeLanguageModel::default());
1350 let thread = cx.new(|cx| Thread::test(model, project, action_log, cx));
1351
1352 let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1353
1354 // Test different EditFileMode values
1355 let modes = vec![
1356 EditFileMode::Edit,
1357 EditFileMode::Create,
1358 EditFileMode::Overwrite,
1359 ];
1360
1361 for mode in modes {
1362 // Test .zed path with different modes
1363 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1364 let _auth = cx.update(|cx| {
1365 tool.authorize(
1366 &EditFileToolInput {
1367 display_description: "Edit settings".into(),
1368 path: "project/.zed/settings.json".into(),
1369 mode: mode.clone(),
1370 },
1371 &stream_tx,
1372 cx,
1373 )
1374 });
1375
1376 stream_rx.expect_authorization().await;
1377
1378 // Test outside path with different modes
1379 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1380 let _auth = cx.update(|cx| {
1381 tool.authorize(
1382 &EditFileToolInput {
1383 display_description: "Edit file".into(),
1384 path: "/outside/file.txt".into(),
1385 mode: mode.clone(),
1386 },
1387 &stream_tx,
1388 cx,
1389 )
1390 });
1391
1392 stream_rx.expect_authorization().await;
1393
1394 // Test normal path with different modes
1395 let (stream_tx, mut stream_rx) = ToolCallEventStream::test();
1396 cx.update(|cx| {
1397 tool.authorize(
1398 &EditFileToolInput {
1399 display_description: "Edit file".into(),
1400 path: "project/normal.txt".into(),
1401 mode: mode.clone(),
1402 },
1403 &stream_tx,
1404 cx,
1405 )
1406 })
1407 .await
1408 .unwrap();
1409 assert!(stream_rx.try_next().is_err());
1410 }
1411 }
1412
1413 #[gpui::test]
1414 async fn test_initial_title_with_partial_input(cx: &mut TestAppContext) {
1415 init_test(cx);
1416 let fs = project::FakeFs::new(cx.executor());
1417 let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
1418 let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
1419 let action_log = cx.new(|_| ActionLog::new(project.clone()));
1420 let model = Arc::new(FakeLanguageModel::default());
1421 let thread = cx.new(|cx| Thread::test(model, project, action_log, cx));
1422
1423 let tool = Arc::new(EditFileTool::new(thread.downgrade(), language_registry));
1424
1425 assert_eq!(
1426 tool.initial_title(Err(json!({
1427 "path": "src/main.rs",
1428 "display_description": "",
1429 "old_string": "old code",
1430 "new_string": "new code"
1431 }))),
1432 "src/main.rs"
1433 );
1434 assert_eq!(
1435 tool.initial_title(Err(json!({
1436 "path": "",
1437 "display_description": "Fix error handling",
1438 "old_string": "old code",
1439 "new_string": "new code"
1440 }))),
1441 "Fix error handling"
1442 );
1443 assert_eq!(
1444 tool.initial_title(Err(json!({
1445 "path": "src/main.rs",
1446 "display_description": "Fix error handling",
1447 "old_string": "old code",
1448 "new_string": "new code"
1449 }))),
1450 "Fix error handling"
1451 );
1452 assert_eq!(
1453 tool.initial_title(Err(json!({
1454 "path": "",
1455 "display_description": "",
1456 "old_string": "old code",
1457 "new_string": "new code"
1458 }))),
1459 DEFAULT_UI_TEXT
1460 );
1461 assert_eq!(
1462 tool.initial_title(Err(serde_json::Value::Null)),
1463 DEFAULT_UI_TEXT
1464 );
1465 }
1466
1467 fn init_test(cx: &mut TestAppContext) {
1468 cx.update(|cx| {
1469 let settings_store = SettingsStore::test(cx);
1470 cx.set_global(settings_store);
1471 language::init(cx);
1472 TelemetrySettings::register(cx);
1473 agent_settings::AgentSettings::register(cx);
1474 Project::init_settings(cx);
1475 });
1476 }
1477}