edit_file_tool.rs

  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, EditorMode, MultiBuffer, PathKey};
 12use futures::StreamExt;
 13use gpui::{
 14    Animation, AnimationExt, AnyWindowHandle, App, AppContext, AsyncApp, Entity, EntityId, Task,
 15    TextStyleRefinement, 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            editor.set_text_style_refinement(TextStyleRefinement {
578                font_size: Some(
579                    TextSize::Small
580                        .rems(cx)
581                        .to_pixels(ThemeSettings::get_global(cx).agent_font_size(cx))
582                        .into(),
583                ),
584                ..TextStyleRefinement::default()
585            });
586            let element = editor.render(window, cx);
587            (element.into_any_element(), line_height)
588        });
589
590        let (full_height_icon, full_height_tooltip_label) = if self.full_height_expanded {
591            (IconName::ChevronUp, "Collapse Code Block")
592        } else {
593            (IconName::ChevronDown, "Expand Code Block")
594        };
595
596        let gradient_overlay =
597            div()
598                .absolute()
599                .bottom_0()
600                .left_0()
601                .w_full()
602                .h_2_5()
603                .bg(gpui::linear_gradient(
604                    0.,
605                    gpui::linear_color_stop(cx.theme().colors().editor_background, 0.),
606                    gpui::linear_color_stop(cx.theme().colors().editor_background.opacity(0.), 1.),
607                ));
608
609        let border_color = cx.theme().colors().border.opacity(0.6);
610
611        const DEFAULT_COLLAPSED_LINES: u32 = 10;
612        let is_collapsible = self.total_lines.unwrap_or(0) > DEFAULT_COLLAPSED_LINES;
613
614        let waiting_for_diff = {
615            let styles = [
616                ("w_4_5", (0.1, 0.85), 2000),
617                ("w_1_4", (0.2, 0.75), 2200),
618                ("w_2_4", (0.15, 0.64), 1900),
619                ("w_3_5", (0.25, 0.72), 2300),
620                ("w_2_5", (0.3, 0.56), 1800),
621            ];
622
623            let mut container = v_flex()
624                .p_3()
625                .gap_1()
626                .border_t_1()
627                .rounded_md()
628                .border_color(border_color)
629                .bg(cx.theme().colors().editor_background);
630
631            for (width_method, pulse_range, duration_ms) in styles.iter() {
632                let (min_opacity, max_opacity) = *pulse_range;
633                let placeholder = match *width_method {
634                    "w_4_5" => div().w_3_4(),
635                    "w_1_4" => div().w_1_4(),
636                    "w_2_4" => div().w_2_4(),
637                    "w_3_5" => div().w_3_5(),
638                    "w_2_5" => div().w_2_5(),
639                    _ => div().w_1_2(),
640                }
641                .id("loading_div")
642                .h_1()
643                .rounded_full()
644                .bg(cx.theme().colors().element_active)
645                .with_animation(
646                    "loading_pulsate",
647                    Animation::new(Duration::from_millis(*duration_ms))
648                        .repeat()
649                        .with_easing(pulsating_between(min_opacity, max_opacity)),
650                    |label, delta| label.opacity(delta),
651                );
652
653                container = container.child(placeholder);
654            }
655
656            container
657        };
658
659        v_flex()
660            .mb_2()
661            .border_1()
662            .when(failed, |card| card.border_dashed())
663            .border_color(border_color)
664            .rounded_md()
665            .overflow_hidden()
666            .child(codeblock_header)
667            .when(failed && self.error_expanded, |card| {
668                card.child(
669                    v_flex()
670                        .p_2()
671                        .gap_1()
672                        .border_t_1()
673                        .border_dashed()
674                        .border_color(border_color)
675                        .bg(cx.theme().colors().editor_background)
676                        .rounded_b_md()
677                        .child(
678                            Label::new("Error")
679                                .size(LabelSize::XSmall)
680                                .color(Color::Error),
681                        )
682                        .child(
683                            div()
684                                .rounded_md()
685                                .text_ui_sm(cx)
686                                .bg(cx.theme().colors().editor_background)
687                                .children(
688                                    error_message
689                                        .map(|error| div().child(error).into_any_element()),
690                                ),
691                        ),
692                )
693            })
694            .when(!self.has_diff() && !failed, |card| {
695                card.child(waiting_for_diff)
696            })
697            .when(
698                !failed && self.preview_expanded && self.has_diff(),
699                |card| {
700                    card.child(
701                        v_flex()
702                            .relative()
703                            .h_full()
704                            .when(!self.full_height_expanded, |editor_container| {
705                                editor_container
706                                    .max_h(DEFAULT_COLLAPSED_LINES as f32 * editor_line_height)
707                            })
708                            .overflow_hidden()
709                            .border_t_1()
710                            .border_color(border_color)
711                            .bg(cx.theme().colors().editor_background)
712                            .child(editor)
713                            .when(
714                                !self.full_height_expanded && is_collapsible,
715                                |editor_container| editor_container.child(gradient_overlay),
716                            ),
717                    )
718                    .when(is_collapsible, |card| {
719                        card.child(
720                            h_flex()
721                                .id(("expand-button", self.editor_unique_id))
722                                .flex_none()
723                                .cursor_pointer()
724                                .h_5()
725                                .justify_center()
726                                .border_t_1()
727                                .rounded_b_md()
728                                .border_color(border_color)
729                                .bg(cx.theme().colors().editor_background)
730                                .hover(|style| {
731                                    style.bg(cx.theme().colors().element_hover.opacity(0.1))
732                                })
733                                .child(
734                                    Icon::new(full_height_icon)
735                                        .size(IconSize::Small)
736                                        .color(Color::Muted),
737                                )
738                                .tooltip(Tooltip::text(full_height_tooltip_label))
739                                .on_click(cx.listener(move |this, _event, _window, _cx| {
740                                    this.full_height_expanded = !this.full_height_expanded;
741                                })),
742                        )
743                    })
744                },
745            )
746    }
747}
748
749async fn build_buffer(
750    mut text: String,
751    path: Arc<Path>,
752    language_registry: &Arc<language::LanguageRegistry>,
753    cx: &mut AsyncApp,
754) -> Result<Entity<Buffer>> {
755    let line_ending = LineEnding::detect(&text);
756    LineEnding::normalize(&mut text);
757    let text = Rope::from(text);
758    let language = cx
759        .update(|_cx| language_registry.language_for_file_path(&path))?
760        .await
761        .ok();
762    let buffer = cx.new(|cx| {
763        let buffer = TextBuffer::new_normalized(
764            0,
765            cx.entity_id().as_non_zero_u64().into(),
766            line_ending,
767            text,
768        );
769        let mut buffer = Buffer::build(buffer, None, Capability::ReadWrite);
770        buffer.set_language(language, cx);
771        buffer
772    })?;
773    Ok(buffer)
774}
775
776async fn build_buffer_diff(
777    mut old_text: String,
778    buffer: &Entity<Buffer>,
779    language_registry: &Arc<LanguageRegistry>,
780    cx: &mut AsyncApp,
781) -> Result<Entity<BufferDiff>> {
782    LineEnding::normalize(&mut old_text);
783
784    let buffer = cx.update(|cx| buffer.read(cx).snapshot())?;
785
786    let base_buffer = cx
787        .update(|cx| {
788            Buffer::build_snapshot(
789                old_text.clone().into(),
790                buffer.language().cloned(),
791                Some(language_registry.clone()),
792                cx,
793            )
794        })?
795        .await;
796
797    let diff_snapshot = cx
798        .update(|cx| {
799            BufferDiffSnapshot::new_with_base_buffer(
800                buffer.text.clone(),
801                Some(old_text.into()),
802                base_buffer,
803                cx,
804            )
805        })?
806        .await;
807
808    let secondary_diff = cx.new(|cx| {
809        let mut diff = BufferDiff::new(&buffer, cx);
810        diff.set_snapshot(diff_snapshot.clone(), &buffer, cx);
811        diff
812    })?;
813
814    cx.new(|cx| {
815        let mut diff = BufferDiff::new(&buffer.text, cx);
816        diff.set_snapshot(diff_snapshot, &buffer, cx);
817        diff.set_secondary_diff(secondary_diff);
818        diff
819    })
820}
821
822#[cfg(test)]
823mod tests {
824    use super::*;
825    use fs::FakeFs;
826    use gpui::TestAppContext;
827    use language_model::fake_provider::FakeLanguageModel;
828    use serde_json::json;
829    use settings::SettingsStore;
830    use util::path;
831
832    #[gpui::test]
833    async fn test_edit_nonexistent_file(cx: &mut TestAppContext) {
834        init_test(cx);
835
836        let fs = FakeFs::new(cx.executor());
837        fs.insert_tree("/root", json!({})).await;
838        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
839        let action_log = cx.new(|_| ActionLog::new(project.clone()));
840        let model = Arc::new(FakeLanguageModel::default());
841        let result = cx
842            .update(|cx| {
843                let input = serde_json::to_value(EditFileToolInput {
844                    display_description: "Some edit".into(),
845                    path: "root/nonexistent_file.txt".into(),
846                    create_or_overwrite: false,
847                })
848                .unwrap();
849                Arc::new(EditFileTool)
850                    .run(input, &[], project.clone(), action_log, model, None, cx)
851                    .output
852            })
853            .await;
854        assert_eq!(
855            result.unwrap_err().to_string(),
856            "root/nonexistent_file.txt not found"
857        );
858    }
859
860    #[test]
861    fn still_streaming_ui_text_with_path() {
862        let input = json!({
863            "path": "src/main.rs",
864            "display_description": "",
865            "old_string": "old code",
866            "new_string": "new code"
867        });
868
869        assert_eq!(EditFileTool.still_streaming_ui_text(&input), "src/main.rs");
870    }
871
872    #[test]
873    fn still_streaming_ui_text_with_description() {
874        let input = json!({
875            "path": "",
876            "display_description": "Fix error handling",
877            "old_string": "old code",
878            "new_string": "new code"
879        });
880
881        assert_eq!(
882            EditFileTool.still_streaming_ui_text(&input),
883            "Fix error handling",
884        );
885    }
886
887    #[test]
888    fn still_streaming_ui_text_with_path_and_description() {
889        let input = json!({
890            "path": "src/main.rs",
891            "display_description": "Fix error handling",
892            "old_string": "old code",
893            "new_string": "new code"
894        });
895
896        assert_eq!(
897            EditFileTool.still_streaming_ui_text(&input),
898            "Fix error handling",
899        );
900    }
901
902    #[test]
903    fn still_streaming_ui_text_no_path_or_description() {
904        let input = json!({
905            "path": "",
906            "display_description": "",
907            "old_string": "old code",
908            "new_string": "new code"
909        });
910
911        assert_eq!(
912            EditFileTool.still_streaming_ui_text(&input),
913            DEFAULT_UI_TEXT,
914        );
915    }
916
917    #[test]
918    fn still_streaming_ui_text_with_null() {
919        let input = serde_json::Value::Null;
920
921        assert_eq!(
922            EditFileTool.still_streaming_ui_text(&input),
923            DEFAULT_UI_TEXT,
924        );
925    }
926
927    fn init_test(cx: &mut TestAppContext) {
928        cx.update(|cx| {
929            let settings_store = SettingsStore::test(cx);
930            cx.set_global(settings_store);
931            language::init(cx);
932            Project::init_settings(cx);
933        });
934    }
935}