1use crate::{
2 Templates,
3 edit_agent::{EditAgent, EditAgentOutputEvent},
4 schema::json_schema_for,
5};
6use anyhow::{Result, anyhow};
7use assistant_tool::{
8 ActionLog, AnyToolCard, Tool, ToolCard, ToolResult, ToolResultOutput, ToolUseStatus,
9};
10use buffer_diff::{BufferDiff, BufferDiffSnapshot};
11use editor::{Editor, EditorElement, EditorMode, EditorStyle, MultiBuffer, PathKey};
12use futures::StreamExt;
13use gpui::{
14 Animation, AnimationExt, AnyWindowHandle, App, AppContext, AsyncApp, Entity, EntityId, Task,
15 TextStyle, WeakEntity, pulsating_between,
16};
17use indoc::formatdoc;
18use language::{
19 Anchor, Buffer, Capability, LanguageRegistry, LineEnding, OffsetRangeExt, Rope, TextBuffer,
20 language_settings::SoftWrap,
21};
22use language_model::{LanguageModel, LanguageModelRequestMessage, LanguageModelToolSchemaFormat};
23use project::Project;
24use schemars::JsonSchema;
25use serde::{Deserialize, Serialize};
26use settings::Settings;
27use std::{
28 path::{Path, PathBuf},
29 sync::Arc,
30 time::Duration,
31};
32use theme::ThemeSettings;
33use ui::{Disclosure, Tooltip, prelude::*};
34use util::ResultExt;
35use workspace::Workspace;
36
37pub struct EditFileTool;
38
39#[derive(Debug, Serialize, Deserialize, JsonSchema)]
40pub struct EditFileToolInput {
41 /// A one-line, user-friendly markdown description of the edit. This will be
42 /// shown in the UI and also passed to another model to perform the edit.
43 ///
44 /// Be terse, but also descriptive in what you want to achieve with this
45 /// edit. Avoid generic instructions.
46 ///
47 /// NEVER mention the file path in this description.
48 ///
49 /// <example>Fix API endpoint URLs</example>
50 /// <example>Update copyright year in `page_footer`</example>
51 ///
52 /// Make sure to include this field before all the others in the input object
53 /// so that we can display it immediately.
54 pub display_description: String,
55
56 /// The full path of the file to create or modify in the project.
57 ///
58 /// WARNING: When specifying which file path need changing, you MUST
59 /// start each path with one of the project's root directories.
60 ///
61 /// The following examples assume we have two root directories in the project:
62 /// - backend
63 /// - frontend
64 ///
65 /// <example>
66 /// `backend/src/main.rs`
67 ///
68 /// Notice how the file path starts with root-1. Without that, the path
69 /// would be ambiguous and the call would fail!
70 /// </example>
71 ///
72 /// <example>
73 /// `frontend/db.js`
74 /// </example>
75 pub path: PathBuf,
76
77 /// If true, this tool will recreate the file from scratch.
78 /// If false, this tool will produce granular edits to an existing file.
79 ///
80 /// When a file already exists or you just created it, always prefer editing
81 /// it as opposed to recreating it from scratch.
82 pub create_or_overwrite: bool,
83}
84
85#[derive(Debug, Serialize, Deserialize, JsonSchema)]
86pub struct EditFileToolOutput {
87 pub original_path: PathBuf,
88 pub new_text: String,
89 pub old_text: String,
90}
91
92#[derive(Debug, Serialize, Deserialize, JsonSchema)]
93struct PartialInput {
94 #[serde(default)]
95 path: String,
96 #[serde(default)]
97 display_description: String,
98}
99
100const DEFAULT_UI_TEXT: &str = "Editing file";
101
102impl Tool for EditFileTool {
103 fn name(&self) -> String {
104 "edit_file".into()
105 }
106
107 fn needs_confirmation(&self, _: &serde_json::Value, _: &App) -> bool {
108 false
109 }
110
111 fn description(&self) -> String {
112 include_str!("edit_file_tool/description.md").to_string()
113 }
114
115 fn icon(&self) -> IconName {
116 IconName::Pencil
117 }
118
119 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
120 json_schema_for::<EditFileToolInput>(format)
121 }
122
123 fn ui_text(&self, input: &serde_json::Value) -> String {
124 match serde_json::from_value::<EditFileToolInput>(input.clone()) {
125 Ok(input) => input.display_description,
126 Err(_) => "Editing file".to_string(),
127 }
128 }
129
130 fn still_streaming_ui_text(&self, input: &serde_json::Value) -> String {
131 if let Some(input) = serde_json::from_value::<PartialInput>(input.clone()).ok() {
132 let description = input.display_description.trim();
133 if !description.is_empty() {
134 return description.to_string();
135 }
136
137 let path = input.path.trim();
138 if !path.is_empty() {
139 return path.to_string();
140 }
141 }
142
143 DEFAULT_UI_TEXT.to_string()
144 }
145
146 fn run(
147 self: Arc<Self>,
148 input: serde_json::Value,
149 messages: &[LanguageModelRequestMessage],
150 project: Entity<Project>,
151 action_log: Entity<ActionLog>,
152 model: Arc<dyn LanguageModel>,
153 window: Option<AnyWindowHandle>,
154 cx: &mut App,
155 ) -> ToolResult {
156 let input = match serde_json::from_value::<EditFileToolInput>(input) {
157 Ok(input) => input,
158 Err(err) => return Task::ready(Err(anyhow!(err))).into(),
159 };
160
161 let Some(project_path) = project.read(cx).find_project_path(&input.path, cx) else {
162 return Task::ready(Err(anyhow!(
163 "Path {} not found in project",
164 input.path.display()
165 )))
166 .into();
167 };
168
169 let card = window.and_then(|window| {
170 window
171 .update(cx, |_, window, cx| {
172 cx.new(|cx| {
173 EditFileToolCard::new(input.path.clone(), project.clone(), window, cx)
174 })
175 })
176 .ok()
177 });
178
179 let card_clone = card.clone();
180 let messages = messages.to_vec();
181 let task = cx.spawn(async move |cx: &mut AsyncApp| {
182 let edit_agent = EditAgent::new(model, project.clone(), action_log, Templates::new());
183
184 let buffer = project
185 .update(cx, |project, cx| {
186 project.open_buffer(project_path.clone(), cx)
187 })?
188 .await?;
189
190 let exists = buffer.read_with(cx, |buffer, _| {
191 buffer
192 .file()
193 .as_ref()
194 .map_or(false, |file| file.disk_state().exists())
195 })?;
196 if !input.create_or_overwrite && !exists {
197 return Err(anyhow!("{} not found", input.path.display()));
198 }
199
200 let old_snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
201 let old_text = cx
202 .background_spawn({
203 let old_snapshot = old_snapshot.clone();
204 async move { old_snapshot.text() }
205 })
206 .await;
207
208 let (output, mut events) = if input.create_or_overwrite {
209 edit_agent.overwrite(
210 buffer.clone(),
211 input.display_description.clone(),
212 messages,
213 cx,
214 )
215 } else {
216 edit_agent.edit(
217 buffer.clone(),
218 input.display_description.clone(),
219 messages,
220 cx,
221 )
222 };
223
224 let mut hallucinated_old_text = false;
225 while let Some(event) = events.next().await {
226 match event {
227 EditAgentOutputEvent::Edited => {
228 if let Some(card) = card_clone.as_ref() {
229 let new_snapshot =
230 buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
231 let new_text = cx
232 .background_spawn({
233 let new_snapshot = new_snapshot.clone();
234 async move { new_snapshot.text() }
235 })
236 .await;
237 card.update(cx, |card, cx| {
238 card.set_diff(
239 project_path.path.clone(),
240 old_text.clone(),
241 new_text,
242 cx,
243 );
244 })
245 .log_err();
246 }
247 }
248 EditAgentOutputEvent::OldTextNotFound(_) => hallucinated_old_text = true,
249 }
250 }
251 output.await?;
252
253 project
254 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))?
255 .await?;
256
257 let new_snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
258 let new_text = cx.background_spawn({
259 let new_snapshot = new_snapshot.clone();
260 async move { new_snapshot.text() }
261 });
262 let diff = cx.background_spawn(async move {
263 language::unified_diff(&old_snapshot.text(), &new_snapshot.text())
264 });
265 let (new_text, diff) = futures::join!(new_text, diff);
266
267 let output = EditFileToolOutput {
268 original_path: project_path.path.to_path_buf(),
269 new_text: new_text.clone(),
270 old_text: old_text.clone(),
271 };
272
273 if let Some(card) = card_clone {
274 card.update(cx, |card, cx| {
275 card.set_diff(project_path.path.clone(), old_text, new_text, cx);
276 })
277 .log_err();
278 }
279
280 let input_path = input.path.display();
281 if diff.is_empty() {
282 if hallucinated_old_text {
283 Err(anyhow!(formatdoc! {"
284 Some edits were produced but none of them could be applied.
285 Read the relevant sections of {input_path} again so that
286 I can perform the requested edits.
287 "}))
288 } else {
289 Ok("No edits were made.".to_string().into())
290 }
291 } else {
292 Ok(ToolResultOutput {
293 content: format!("Edited {}:\n\n```diff\n{}\n```", input_path, diff),
294 output: serde_json::to_value(output).ok(),
295 })
296 }
297 });
298
299 ToolResult {
300 output: task,
301 card: card.map(AnyToolCard::from),
302 }
303 }
304
305 fn deserialize_card(
306 self: Arc<Self>,
307 output: serde_json::Value,
308 project: Entity<Project>,
309 window: &mut Window,
310 cx: &mut App,
311 ) -> Option<AnyToolCard> {
312 let output = match serde_json::from_value::<EditFileToolOutput>(output) {
313 Ok(output) => output,
314 Err(_) => return None,
315 };
316
317 let card = cx.new(|cx| {
318 let mut card = EditFileToolCard::new(output.original_path.clone(), project, window, cx);
319 card.set_diff(
320 output.original_path.into(),
321 output.old_text,
322 output.new_text,
323 cx,
324 );
325 card
326 });
327
328 Some(card.into())
329 }
330}
331
332pub struct EditFileToolCard {
333 path: PathBuf,
334 editor: Entity<Editor>,
335 multibuffer: Entity<MultiBuffer>,
336 project: Entity<Project>,
337 diff_task: Option<Task<Result<()>>>,
338 preview_expanded: bool,
339 error_expanded: bool,
340 full_height_expanded: bool,
341 total_lines: Option<u32>,
342 editor_unique_id: EntityId,
343}
344
345impl EditFileToolCard {
346 pub fn new(path: PathBuf, project: Entity<Project>, window: &mut Window, cx: &mut App) -> Self {
347 let multibuffer = cx.new(|_| MultiBuffer::without_headers(Capability::ReadOnly));
348 let editor = cx.new(|cx| {
349 let mut editor = Editor::new(
350 EditorMode::Full {
351 scale_ui_elements_with_buffer_font_size: false,
352 show_active_line_background: false,
353 sized_by_content: true,
354 },
355 multibuffer.clone(),
356 Some(project.clone()),
357 window,
358 cx,
359 );
360 editor.set_show_gutter(false, cx);
361 editor.disable_inline_diagnostics();
362 editor.disable_expand_excerpt_buttons(cx);
363 editor.set_soft_wrap_mode(SoftWrap::None, cx);
364 editor.scroll_manager.set_forbid_vertical_scroll(true);
365 editor.set_show_scrollbars(false, cx);
366 editor.set_show_indent_guides(false, cx);
367 editor.set_read_only(true);
368 editor.set_show_breakpoints(false, cx);
369 editor.set_show_code_actions(false, cx);
370 editor.set_show_git_diff_gutter(false, cx);
371 editor.set_expand_all_diff_hunks(cx);
372 editor
373 });
374 Self {
375 editor_unique_id: editor.entity_id(),
376 path,
377 project,
378 editor,
379 multibuffer,
380 diff_task: None,
381 preview_expanded: true,
382 error_expanded: false,
383 full_height_expanded: false,
384 total_lines: None,
385 }
386 }
387
388 pub fn has_diff(&self) -> bool {
389 self.total_lines.is_some()
390 }
391
392 pub fn set_diff(
393 &mut self,
394 path: Arc<Path>,
395 old_text: String,
396 new_text: String,
397 cx: &mut Context<Self>,
398 ) {
399 let language_registry = self.project.read(cx).languages().clone();
400 self.diff_task = Some(cx.spawn(async move |this, cx| {
401 let buffer = build_buffer(new_text, path.clone(), &language_registry, cx).await?;
402 let buffer_diff = build_buffer_diff(old_text, &buffer, &language_registry, cx).await?;
403
404 this.update(cx, |this, cx| {
405 this.total_lines = this.multibuffer.update(cx, |multibuffer, cx| {
406 let snapshot = buffer.read(cx).snapshot();
407 let diff = buffer_diff.read(cx);
408 let diff_hunk_ranges = diff
409 .hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &snapshot, cx)
410 .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot))
411 .collect::<Vec<_>>();
412 multibuffer.clear(cx);
413 multibuffer.set_excerpts_for_path(
414 PathKey::for_buffer(&buffer, cx),
415 buffer,
416 diff_hunk_ranges,
417 editor::DEFAULT_MULTIBUFFER_CONTEXT,
418 cx,
419 );
420 multibuffer.add_diff(buffer_diff, cx);
421 let end = multibuffer.len(cx);
422 Some(multibuffer.snapshot(cx).offset_to_point(end).row + 1)
423 });
424
425 cx.notify();
426 })
427 }));
428 }
429}
430
431impl ToolCard for EditFileToolCard {
432 fn render(
433 &mut self,
434 status: &ToolUseStatus,
435 window: &mut Window,
436 workspace: WeakEntity<Workspace>,
437 cx: &mut Context<Self>,
438 ) -> impl IntoElement {
439 let (failed, error_message) = match status {
440 ToolUseStatus::Error(err) => (true, Some(err.to_string())),
441 _ => (false, None),
442 };
443
444 let path_label_button = h_flex()
445 .id(("edit-tool-path-label-button", self.editor_unique_id))
446 .w_full()
447 .max_w_full()
448 .px_1()
449 .gap_0p5()
450 .cursor_pointer()
451 .rounded_sm()
452 .opacity(0.8)
453 .hover(|label| {
454 label
455 .opacity(1.)
456 .bg(cx.theme().colors().element_hover.opacity(0.5))
457 })
458 .tooltip(Tooltip::text("Jump to File"))
459 .child(
460 h_flex()
461 .child(
462 Icon::new(IconName::Pencil)
463 .size(IconSize::XSmall)
464 .color(Color::Muted),
465 )
466 .child(
467 div()
468 .text_size(rems(0.8125))
469 .child(self.path.display().to_string())
470 .ml_1p5()
471 .mr_0p5(),
472 )
473 .child(
474 Icon::new(IconName::ArrowUpRight)
475 .size(IconSize::XSmall)
476 .color(Color::Ignored),
477 ),
478 )
479 .on_click({
480 let path = self.path.clone();
481 let workspace = workspace.clone();
482 move |_, window, cx| {
483 workspace
484 .update(cx, {
485 |workspace, cx| {
486 let Some(project_path) =
487 workspace.project().read(cx).find_project_path(&path, cx)
488 else {
489 return;
490 };
491 let open_task =
492 workspace.open_path(project_path, None, true, window, cx);
493 window
494 .spawn(cx, async move |cx| {
495 let item = open_task.await?;
496 if let Some(active_editor) = item.downcast::<Editor>() {
497 active_editor
498 .update_in(cx, |editor, window, cx| {
499 editor.go_to_singleton_buffer_point(
500 language::Point::new(0, 0),
501 window,
502 cx,
503 );
504 })
505 .log_err();
506 }
507 anyhow::Ok(())
508 })
509 .detach_and_log_err(cx);
510 }
511 })
512 .ok();
513 }
514 })
515 .into_any_element();
516
517 let codeblock_header_bg = cx
518 .theme()
519 .colors()
520 .element_background
521 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
522
523 let codeblock_header = h_flex()
524 .flex_none()
525 .p_1()
526 .gap_1()
527 .justify_between()
528 .rounded_t_md()
529 .when(!failed, |header| header.bg(codeblock_header_bg))
530 .child(path_label_button)
531 .when(failed, |header| {
532 header.child(
533 h_flex()
534 .gap_1()
535 .child(
536 Icon::new(IconName::Close)
537 .size(IconSize::Small)
538 .color(Color::Error),
539 )
540 .child(
541 Disclosure::new(
542 ("edit-file-error-disclosure", self.editor_unique_id),
543 self.error_expanded,
544 )
545 .opened_icon(IconName::ChevronUp)
546 .closed_icon(IconName::ChevronDown)
547 .on_click(cx.listener(
548 move |this, _event, _window, _cx| {
549 this.error_expanded = !this.error_expanded;
550 },
551 )),
552 ),
553 )
554 })
555 .when(!failed && self.has_diff(), |header| {
556 header.child(
557 Disclosure::new(
558 ("edit-file-disclosure", self.editor_unique_id),
559 self.preview_expanded,
560 )
561 .opened_icon(IconName::ChevronUp)
562 .closed_icon(IconName::ChevronDown)
563 .on_click(cx.listener(
564 move |this, _event, _window, _cx| {
565 this.preview_expanded = !this.preview_expanded;
566 },
567 )),
568 )
569 });
570
571 let (editor, editor_line_height) = self.editor.update(cx, |editor, cx| {
572 let line_height = editor
573 .style()
574 .map(|style| style.text.line_height_in_pixels(window.rem_size()))
575 .unwrap_or_default();
576
577 let settings = ThemeSettings::get_global(cx);
578 let element = EditorElement::new(
579 &cx.entity(),
580 EditorStyle {
581 background: cx.theme().colors().editor_background,
582 horizontal_padding: rems(0.25).to_pixels(window.rem_size()),
583 local_player: cx.theme().players().local(),
584 text: TextStyle {
585 color: cx.theme().colors().editor_foreground,
586 font_family: settings.buffer_font.family.clone(),
587 font_features: settings.buffer_font.features.clone(),
588 font_fallbacks: settings.buffer_font.fallbacks.clone(),
589 font_size: TextSize::Small
590 .rems(cx)
591 .to_pixels(settings.agent_font_size(cx))
592 .into(),
593 font_weight: settings.buffer_font.weight,
594 line_height: relative(settings.buffer_line_height.value()),
595 ..Default::default()
596 },
597 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
598 syntax: cx.theme().syntax().clone(),
599 status: cx.theme().status().clone(),
600 ..Default::default()
601 },
602 );
603
604 (element.into_any_element(), line_height)
605 });
606
607 let (full_height_icon, full_height_tooltip_label) = if self.full_height_expanded {
608 (IconName::ChevronUp, "Collapse Code Block")
609 } else {
610 (IconName::ChevronDown, "Expand Code Block")
611 };
612
613 let gradient_overlay =
614 div()
615 .absolute()
616 .bottom_0()
617 .left_0()
618 .w_full()
619 .h_2_5()
620 .bg(gpui::linear_gradient(
621 0.,
622 gpui::linear_color_stop(cx.theme().colors().editor_background, 0.),
623 gpui::linear_color_stop(cx.theme().colors().editor_background.opacity(0.), 1.),
624 ));
625
626 let border_color = cx.theme().colors().border.opacity(0.6);
627
628 const DEFAULT_COLLAPSED_LINES: u32 = 10;
629 let is_collapsible = self.total_lines.unwrap_or(0) > DEFAULT_COLLAPSED_LINES;
630
631 let waiting_for_diff = {
632 let styles = [
633 ("w_4_5", (0.1, 0.85), 2000),
634 ("w_1_4", (0.2, 0.75), 2200),
635 ("w_2_4", (0.15, 0.64), 1900),
636 ("w_3_5", (0.25, 0.72), 2300),
637 ("w_2_5", (0.3, 0.56), 1800),
638 ];
639
640 let mut container = v_flex()
641 .p_3()
642 .gap_1()
643 .border_t_1()
644 .rounded_md()
645 .border_color(border_color)
646 .bg(cx.theme().colors().editor_background);
647
648 for (width_method, pulse_range, duration_ms) in styles.iter() {
649 let (min_opacity, max_opacity) = *pulse_range;
650 let placeholder = match *width_method {
651 "w_4_5" => div().w_3_4(),
652 "w_1_4" => div().w_1_4(),
653 "w_2_4" => div().w_2_4(),
654 "w_3_5" => div().w_3_5(),
655 "w_2_5" => div().w_2_5(),
656 _ => div().w_1_2(),
657 }
658 .id("loading_div")
659 .h_1()
660 .rounded_full()
661 .bg(cx.theme().colors().element_active)
662 .with_animation(
663 "loading_pulsate",
664 Animation::new(Duration::from_millis(*duration_ms))
665 .repeat()
666 .with_easing(pulsating_between(min_opacity, max_opacity)),
667 |label, delta| label.opacity(delta),
668 );
669
670 container = container.child(placeholder);
671 }
672
673 container
674 };
675
676 v_flex()
677 .mb_2()
678 .border_1()
679 .when(failed, |card| card.border_dashed())
680 .border_color(border_color)
681 .rounded_md()
682 .overflow_hidden()
683 .child(codeblock_header)
684 .when(failed && self.error_expanded, |card| {
685 card.child(
686 v_flex()
687 .p_2()
688 .gap_1()
689 .border_t_1()
690 .border_dashed()
691 .border_color(border_color)
692 .bg(cx.theme().colors().editor_background)
693 .rounded_b_md()
694 .child(
695 Label::new("Error")
696 .size(LabelSize::XSmall)
697 .color(Color::Error),
698 )
699 .child(
700 div()
701 .rounded_md()
702 .text_ui_sm(cx)
703 .bg(cx.theme().colors().editor_background)
704 .children(
705 error_message
706 .map(|error| div().child(error).into_any_element()),
707 ),
708 ),
709 )
710 })
711 .when(!self.has_diff() && !failed, |card| {
712 card.child(waiting_for_diff)
713 })
714 .when(
715 !failed && self.preview_expanded && self.has_diff(),
716 |card| {
717 card.child(
718 v_flex()
719 .relative()
720 .h_full()
721 .when(!self.full_height_expanded, |editor_container| {
722 editor_container
723 .max_h(DEFAULT_COLLAPSED_LINES as f32 * editor_line_height)
724 })
725 .overflow_hidden()
726 .border_t_1()
727 .border_color(border_color)
728 .bg(cx.theme().colors().editor_background)
729 .child(editor)
730 .when(
731 !self.full_height_expanded && is_collapsible,
732 |editor_container| editor_container.child(gradient_overlay),
733 ),
734 )
735 .when(is_collapsible, |card| {
736 card.child(
737 h_flex()
738 .id(("expand-button", self.editor_unique_id))
739 .flex_none()
740 .cursor_pointer()
741 .h_5()
742 .justify_center()
743 .border_t_1()
744 .rounded_b_md()
745 .border_color(border_color)
746 .bg(cx.theme().colors().editor_background)
747 .hover(|style| {
748 style.bg(cx.theme().colors().element_hover.opacity(0.1))
749 })
750 .child(
751 Icon::new(full_height_icon)
752 .size(IconSize::Small)
753 .color(Color::Muted),
754 )
755 .tooltip(Tooltip::text(full_height_tooltip_label))
756 .on_click(cx.listener(move |this, _event, _window, _cx| {
757 this.full_height_expanded = !this.full_height_expanded;
758 })),
759 )
760 })
761 },
762 )
763 }
764}
765
766async fn build_buffer(
767 mut text: String,
768 path: Arc<Path>,
769 language_registry: &Arc<language::LanguageRegistry>,
770 cx: &mut AsyncApp,
771) -> Result<Entity<Buffer>> {
772 let line_ending = LineEnding::detect(&text);
773 LineEnding::normalize(&mut text);
774 let text = Rope::from(text);
775 let language = cx
776 .update(|_cx| language_registry.language_for_file_path(&path))?
777 .await
778 .ok();
779 let buffer = cx.new(|cx| {
780 let buffer = TextBuffer::new_normalized(
781 0,
782 cx.entity_id().as_non_zero_u64().into(),
783 line_ending,
784 text,
785 );
786 let mut buffer = Buffer::build(buffer, None, Capability::ReadWrite);
787 buffer.set_language(language, cx);
788 buffer
789 })?;
790 Ok(buffer)
791}
792
793async fn build_buffer_diff(
794 mut old_text: String,
795 buffer: &Entity<Buffer>,
796 language_registry: &Arc<LanguageRegistry>,
797 cx: &mut AsyncApp,
798) -> Result<Entity<BufferDiff>> {
799 LineEnding::normalize(&mut old_text);
800
801 let buffer = cx.update(|cx| buffer.read(cx).snapshot())?;
802
803 let base_buffer = cx
804 .update(|cx| {
805 Buffer::build_snapshot(
806 old_text.clone().into(),
807 buffer.language().cloned(),
808 Some(language_registry.clone()),
809 cx,
810 )
811 })?
812 .await;
813
814 let diff_snapshot = cx
815 .update(|cx| {
816 BufferDiffSnapshot::new_with_base_buffer(
817 buffer.text.clone(),
818 Some(old_text.into()),
819 base_buffer,
820 cx,
821 )
822 })?
823 .await;
824
825 let secondary_diff = cx.new(|cx| {
826 let mut diff = BufferDiff::new(&buffer, cx);
827 diff.set_snapshot(diff_snapshot.clone(), &buffer, cx);
828 diff
829 })?;
830
831 cx.new(|cx| {
832 let mut diff = BufferDiff::new(&buffer.text, cx);
833 diff.set_snapshot(diff_snapshot, &buffer, cx);
834 diff.set_secondary_diff(secondary_diff);
835 diff
836 })
837}
838
839#[cfg(test)]
840mod tests {
841 use super::*;
842 use fs::FakeFs;
843 use gpui::TestAppContext;
844 use language_model::fake_provider::FakeLanguageModel;
845 use serde_json::json;
846 use settings::SettingsStore;
847 use util::path;
848
849 #[gpui::test]
850 async fn test_edit_nonexistent_file(cx: &mut TestAppContext) {
851 init_test(cx);
852
853 let fs = FakeFs::new(cx.executor());
854 fs.insert_tree("/root", json!({})).await;
855 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
856 let action_log = cx.new(|_| ActionLog::new(project.clone()));
857 let model = Arc::new(FakeLanguageModel::default());
858 let result = cx
859 .update(|cx| {
860 let input = serde_json::to_value(EditFileToolInput {
861 display_description: "Some edit".into(),
862 path: "root/nonexistent_file.txt".into(),
863 create_or_overwrite: false,
864 })
865 .unwrap();
866 Arc::new(EditFileTool)
867 .run(input, &[], project.clone(), action_log, model, None, cx)
868 .output
869 })
870 .await;
871 assert_eq!(
872 result.unwrap_err().to_string(),
873 "root/nonexistent_file.txt not found"
874 );
875 }
876
877 #[test]
878 fn still_streaming_ui_text_with_path() {
879 let input = json!({
880 "path": "src/main.rs",
881 "display_description": "",
882 "old_string": "old code",
883 "new_string": "new code"
884 });
885
886 assert_eq!(EditFileTool.still_streaming_ui_text(&input), "src/main.rs");
887 }
888
889 #[test]
890 fn still_streaming_ui_text_with_description() {
891 let input = json!({
892 "path": "",
893 "display_description": "Fix error handling",
894 "old_string": "old code",
895 "new_string": "new code"
896 });
897
898 assert_eq!(
899 EditFileTool.still_streaming_ui_text(&input),
900 "Fix error handling",
901 );
902 }
903
904 #[test]
905 fn still_streaming_ui_text_with_path_and_description() {
906 let input = json!({
907 "path": "src/main.rs",
908 "display_description": "Fix error handling",
909 "old_string": "old code",
910 "new_string": "new code"
911 });
912
913 assert_eq!(
914 EditFileTool.still_streaming_ui_text(&input),
915 "Fix error handling",
916 );
917 }
918
919 #[test]
920 fn still_streaming_ui_text_no_path_or_description() {
921 let input = json!({
922 "path": "",
923 "display_description": "",
924 "old_string": "old code",
925 "new_string": "new code"
926 });
927
928 assert_eq!(
929 EditFileTool.still_streaming_ui_text(&input),
930 DEFAULT_UI_TEXT,
931 );
932 }
933
934 #[test]
935 fn still_streaming_ui_text_with_null() {
936 let input = serde_json::Value::Null;
937
938 assert_eq!(
939 EditFileTool.still_streaming_ui_text(&input),
940 DEFAULT_UI_TEXT,
941 );
942 }
943
944 fn init_test(cx: &mut TestAppContext) {
945 cx.update(|cx| {
946 let settings_store = SettingsStore::test(cx);
947 cx.set_global(settings_store);
948 language::init(cx);
949 Project::init_settings(cx);
950 });
951 }
952}