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