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