1use crate::{Keep, Reject, Thread, ThreadEvent};
2use anyhow::Result;
3use buffer_diff::DiffHunkStatus;
4use collections::HashSet;
5use editor::{
6 Direction, Editor, EditorEvent, MultiBuffer, ToPoint,
7 actions::{GoToHunk, GoToPreviousHunk},
8 scroll::Autoscroll,
9};
10use gpui::{
11 Action, AnyElement, AnyView, App, Entity, EventEmitter, FocusHandle, Focusable, SharedString,
12 Subscription, Task, WeakEntity, Window, prelude::*,
13};
14use language::{Capability, DiskState, OffsetRangeExt, Point};
15use multi_buffer::PathKey;
16use project::{Project, ProjectPath};
17use std::{
18 any::{Any, TypeId},
19 ops::Range,
20 sync::Arc,
21};
22use ui::{IconButtonShape, KeyBinding, Tooltip, prelude::*};
23use workspace::{
24 Item, ItemHandle, ItemNavHistory, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
25 Workspace,
26 item::{BreadcrumbText, ItemEvent, TabContentParams},
27 searchable::SearchableItemHandle,
28};
29use zed_actions::assistant::ToggleFocus;
30
31pub struct AgentDiff {
32 multibuffer: Entity<MultiBuffer>,
33 editor: Entity<Editor>,
34 thread: Entity<Thread>,
35 focus_handle: FocusHandle,
36 workspace: WeakEntity<Workspace>,
37 title: SharedString,
38 _subscriptions: Vec<Subscription>,
39}
40
41impl AgentDiff {
42 pub fn deploy(
43 thread: Entity<Thread>,
44 workspace: WeakEntity<Workspace>,
45 window: &mut Window,
46 cx: &mut App,
47 ) -> Result<Entity<Self>> {
48 let existing_diff = workspace.update(cx, |workspace, cx| {
49 workspace
50 .items_of_type::<AgentDiff>(cx)
51 .find(|diff| diff.read(cx).thread == thread)
52 })?;
53 if let Some(existing_diff) = existing_diff {
54 workspace.update(cx, |workspace, cx| {
55 workspace.activate_item(&existing_diff, true, true, window, cx);
56 })?;
57 Ok(existing_diff)
58 } else {
59 let agent_diff =
60 cx.new(|cx| AgentDiff::new(thread.clone(), workspace.clone(), window, cx));
61 workspace.update(cx, |workspace, cx| {
62 workspace.add_item_to_center(Box::new(agent_diff.clone()), window, cx);
63 })?;
64 Ok(agent_diff)
65 }
66 }
67
68 pub fn new(
69 thread: Entity<Thread>,
70 workspace: WeakEntity<Workspace>,
71 window: &mut Window,
72 cx: &mut Context<Self>,
73 ) -> Self {
74 let focus_handle = cx.focus_handle();
75 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
76
77 let project = thread.read(cx).project().clone();
78 let render_diff_hunk_controls = Arc::new({
79 let agent_diff = cx.entity();
80 move |row,
81 status: &DiffHunkStatus,
82 hunk_range,
83 is_created_file,
84 line_height,
85 editor: &Entity<Editor>,
86 window: &mut Window,
87 cx: &mut App| {
88 render_diff_hunk_controls(
89 row,
90 status,
91 hunk_range,
92 is_created_file,
93 line_height,
94 &agent_diff,
95 editor,
96 window,
97 cx,
98 )
99 }
100 });
101 let editor = cx.new(|cx| {
102 let mut editor =
103 Editor::for_multibuffer(multibuffer.clone(), Some(project.clone()), window, cx);
104 editor.disable_inline_diagnostics();
105 editor.set_expand_all_diff_hunks(cx);
106 editor.set_render_diff_hunk_controls(render_diff_hunk_controls, cx);
107 editor.register_addon(AgentDiffAddon);
108 editor
109 });
110
111 let action_log = thread.read(cx).action_log().clone();
112 let mut this = Self {
113 _subscriptions: vec![
114 cx.observe_in(&action_log, window, |this, _action_log, window, cx| {
115 this.update_excerpts(window, cx)
116 }),
117 cx.subscribe(&thread, |this, _thread, event, cx| {
118 this.handle_thread_event(event, cx)
119 }),
120 ],
121 title: SharedString::default(),
122 multibuffer,
123 editor,
124 thread,
125 focus_handle,
126 workspace,
127 };
128 this.update_excerpts(window, cx);
129 this.update_title(cx);
130 this
131 }
132
133 fn update_excerpts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
134 let thread = self.thread.read(cx);
135 let changed_buffers = thread.action_log().read(cx).changed_buffers(cx);
136 let mut paths_to_delete = self.multibuffer.read(cx).paths().collect::<HashSet<_>>();
137
138 for (buffer, diff_handle) in changed_buffers {
139 if buffer.read(cx).file().is_none() {
140 continue;
141 }
142
143 let path_key = PathKey::for_buffer(&buffer, cx);
144 paths_to_delete.remove(&path_key);
145
146 let snapshot = buffer.read(cx).snapshot();
147 let diff = diff_handle.read(cx);
148
149 let diff_hunk_ranges = diff
150 .hunks_intersecting_range(
151 language::Anchor::MIN..language::Anchor::MAX,
152 &snapshot,
153 cx,
154 )
155 .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot))
156 .collect::<Vec<_>>();
157
158 let (was_empty, is_excerpt_newly_added) =
159 self.multibuffer.update(cx, |multibuffer, cx| {
160 let was_empty = multibuffer.is_empty();
161 let (_, is_excerpt_newly_added) = multibuffer.set_excerpts_for_path(
162 path_key.clone(),
163 buffer.clone(),
164 diff_hunk_ranges,
165 editor::DEFAULT_MULTIBUFFER_CONTEXT,
166 cx,
167 );
168 multibuffer.add_diff(diff_handle, cx);
169 (was_empty, is_excerpt_newly_added)
170 });
171
172 self.editor.update(cx, |editor, cx| {
173 if was_empty {
174 let first_hunk = editor
175 .diff_hunks_in_ranges(
176 &[editor::Anchor::min()..editor::Anchor::max()],
177 &self.multibuffer.read(cx).read(cx),
178 )
179 .next();
180
181 if let Some(first_hunk) = first_hunk {
182 let first_hunk_start = first_hunk.multi_buffer_range().start;
183 editor.change_selections(
184 Some(Autoscroll::fit()),
185 window,
186 cx,
187 |selections| {
188 selections
189 .select_anchor_ranges([first_hunk_start..first_hunk_start]);
190 },
191 )
192 }
193 }
194
195 if is_excerpt_newly_added
196 && buffer
197 .read(cx)
198 .file()
199 .map_or(false, |file| file.disk_state() == DiskState::Deleted)
200 {
201 editor.fold_buffer(snapshot.text.remote_id(), cx)
202 }
203 });
204 }
205
206 self.multibuffer.update(cx, |multibuffer, cx| {
207 for path in paths_to_delete {
208 multibuffer.remove_excerpts_for_path(path, cx);
209 }
210 });
211
212 if self.multibuffer.read(cx).is_empty()
213 && self
214 .editor
215 .read(cx)
216 .focus_handle(cx)
217 .contains_focused(window, cx)
218 {
219 self.focus_handle.focus(window);
220 } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
221 self.editor.update(cx, |editor, cx| {
222 editor.focus_handle(cx).focus(window);
223 });
224 }
225 }
226
227 fn update_title(&mut self, cx: &mut Context<Self>) {
228 let new_title = self
229 .thread
230 .read(cx)
231 .summary()
232 .unwrap_or("Assistant Changes".into());
233 if new_title != self.title {
234 self.title = new_title;
235 cx.emit(EditorEvent::TitleChanged);
236 }
237 }
238
239 fn handle_thread_event(&mut self, event: &ThreadEvent, cx: &mut Context<Self>) {
240 match event {
241 ThreadEvent::SummaryGenerated => self.update_title(cx),
242 _ => {}
243 }
244 }
245
246 pub fn move_to_path(&mut self, path_key: PathKey, window: &mut Window, cx: &mut Context<Self>) {
247 if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {
248 self.editor.update(cx, |editor, cx| {
249 let first_hunk = editor
250 .diff_hunks_in_ranges(
251 &[position..editor::Anchor::max()],
252 &self.multibuffer.read(cx).read(cx),
253 )
254 .next();
255
256 if let Some(first_hunk) = first_hunk {
257 let first_hunk_start = first_hunk.multi_buffer_range().start;
258 editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
259 selections.select_anchor_ranges([first_hunk_start..first_hunk_start]);
260 })
261 }
262 });
263 }
264 }
265
266 fn keep(&mut self, _: &crate::Keep, window: &mut Window, cx: &mut Context<Self>) {
267 let ranges = self
268 .editor
269 .read(cx)
270 .selections
271 .disjoint_anchor_ranges()
272 .collect::<Vec<_>>();
273 self.keep_edits_in_ranges(ranges, window, cx);
274 }
275
276 fn reject(&mut self, _: &crate::Reject, window: &mut Window, cx: &mut Context<Self>) {
277 let ranges = self
278 .editor
279 .read(cx)
280 .selections
281 .disjoint_anchor_ranges()
282 .collect::<Vec<_>>();
283 self.reject_edits_in_ranges(ranges, window, cx);
284 }
285
286 fn reject_all(&mut self, _: &crate::RejectAll, window: &mut Window, cx: &mut Context<Self>) {
287 self.reject_edits_in_ranges(
288 vec![editor::Anchor::min()..editor::Anchor::max()],
289 window,
290 cx,
291 );
292 }
293
294 fn keep_all(&mut self, _: &crate::KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
295 self.thread
296 .update(cx, |thread, cx| thread.keep_all_edits(cx));
297 }
298
299 fn keep_edits_in_ranges(
300 &mut self,
301 ranges: Vec<Range<editor::Anchor>>,
302 window: &mut Window,
303 cx: &mut Context<Self>,
304 ) {
305 let snapshot = self.multibuffer.read(cx).snapshot(cx);
306 let diff_hunks_in_ranges = self
307 .editor
308 .read(cx)
309 .diff_hunks_in_ranges(&ranges, &snapshot)
310 .collect::<Vec<_>>();
311 let newest_cursor = self.editor.update(cx, |editor, cx| {
312 editor.selections.newest::<Point>(cx).head()
313 });
314 if diff_hunks_in_ranges.iter().any(|hunk| {
315 hunk.row_range
316 .contains(&multi_buffer::MultiBufferRow(newest_cursor.row))
317 }) {
318 self.update_selection(&diff_hunks_in_ranges, window, cx);
319 }
320
321 for hunk in &diff_hunks_in_ranges {
322 let buffer = self.multibuffer.read(cx).buffer(hunk.buffer_id);
323 if let Some(buffer) = buffer {
324 self.thread.update(cx, |thread, cx| {
325 thread.keep_edits_in_range(buffer, hunk.buffer_range.clone(), cx)
326 });
327 }
328 }
329 }
330
331 fn reject_edits_in_ranges(
332 &mut self,
333 ranges: Vec<Range<editor::Anchor>>,
334 window: &mut Window,
335 cx: &mut Context<Self>,
336 ) {
337 let snapshot = self.multibuffer.read(cx).snapshot(cx);
338 let diff_hunks_in_ranges = self
339 .editor
340 .read(cx)
341 .diff_hunks_in_ranges(&ranges, &snapshot)
342 .collect::<Vec<_>>();
343 let newest_cursor = self.editor.update(cx, |editor, cx| {
344 editor.selections.newest::<Point>(cx).head()
345 });
346 if diff_hunks_in_ranges.iter().any(|hunk| {
347 hunk.row_range
348 .contains(&multi_buffer::MultiBufferRow(newest_cursor.row))
349 }) {
350 self.update_selection(&diff_hunks_in_ranges, window, cx);
351 }
352
353 for hunk in &diff_hunks_in_ranges {
354 let buffer = self.multibuffer.read(cx).buffer(hunk.buffer_id);
355 if let Some(buffer) = buffer {
356 self.thread
357 .update(cx, |thread, cx| {
358 thread.reject_edits_in_range(buffer, hunk.buffer_range.clone(), cx)
359 })
360 .detach_and_log_err(cx);
361 }
362 }
363 }
364
365 fn update_selection(
366 &mut self,
367 diff_hunks: &[multi_buffer::MultiBufferDiffHunk],
368 window: &mut Window,
369 cx: &mut Context<Self>,
370 ) {
371 let snapshot = self.multibuffer.read(cx).snapshot(cx);
372 let target_hunk = diff_hunks
373 .last()
374 .and_then(|last_kept_hunk| {
375 let last_kept_hunk_end = last_kept_hunk.multi_buffer_range().end;
376 self.editor
377 .read(cx)
378 .diff_hunks_in_ranges(&[last_kept_hunk_end..editor::Anchor::max()], &snapshot)
379 .skip(1)
380 .next()
381 })
382 .or_else(|| {
383 let first_kept_hunk = diff_hunks.first()?;
384 let first_kept_hunk_start = first_kept_hunk.multi_buffer_range().start;
385 self.editor
386 .read(cx)
387 .diff_hunks_in_ranges(
388 &[editor::Anchor::min()..first_kept_hunk_start],
389 &snapshot,
390 )
391 .next()
392 });
393
394 if let Some(target_hunk) = target_hunk {
395 self.editor.update(cx, |editor, cx| {
396 editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
397 let next_hunk_start = target_hunk.multi_buffer_range().start;
398 selections.select_anchor_ranges([next_hunk_start..next_hunk_start]);
399 })
400 });
401 }
402 }
403}
404
405impl EventEmitter<EditorEvent> for AgentDiff {}
406
407impl Focusable for AgentDiff {
408 fn focus_handle(&self, cx: &App) -> FocusHandle {
409 if self.multibuffer.read(cx).is_empty() {
410 self.focus_handle.clone()
411 } else {
412 self.editor.focus_handle(cx)
413 }
414 }
415}
416
417impl Item for AgentDiff {
418 type Event = EditorEvent;
419
420 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
421 Some(Icon::new(IconName::ZedAssistant).color(Color::Muted))
422 }
423
424 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
425 Editor::to_item_events(event, f)
426 }
427
428 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
429 self.editor
430 .update(cx, |editor, cx| editor.deactivated(window, cx));
431 }
432
433 fn navigate(
434 &mut self,
435 data: Box<dyn Any>,
436 window: &mut Window,
437 cx: &mut Context<Self>,
438 ) -> bool {
439 self.editor
440 .update(cx, |editor, cx| editor.navigate(data, window, cx))
441 }
442
443 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
444 Some("Agent Diff".into())
445 }
446
447 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
448 let summary = self
449 .thread
450 .read(cx)
451 .summary()
452 .unwrap_or("Assistant Changes".into());
453 Label::new(format!("Review: {}", summary))
454 .color(if params.selected {
455 Color::Default
456 } else {
457 Color::Muted
458 })
459 .into_any_element()
460 }
461
462 fn telemetry_event_text(&self) -> Option<&'static str> {
463 Some("Assistant Diff Opened")
464 }
465
466 fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
467 Some(Box::new(self.editor.clone()))
468 }
469
470 fn for_each_project_item(
471 &self,
472 cx: &App,
473 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
474 ) {
475 self.editor.for_each_project_item(cx, f)
476 }
477
478 fn is_singleton(&self, _: &App) -> bool {
479 false
480 }
481
482 fn set_nav_history(
483 &mut self,
484 nav_history: ItemNavHistory,
485 _: &mut Window,
486 cx: &mut Context<Self>,
487 ) {
488 self.editor.update(cx, |editor, _| {
489 editor.set_nav_history(Some(nav_history));
490 });
491 }
492
493 fn clone_on_split(
494 &self,
495 _workspace_id: Option<workspace::WorkspaceId>,
496 window: &mut Window,
497 cx: &mut Context<Self>,
498 ) -> Option<Entity<Self>>
499 where
500 Self: Sized,
501 {
502 Some(cx.new(|cx| Self::new(self.thread.clone(), self.workspace.clone(), window, cx)))
503 }
504
505 fn is_dirty(&self, cx: &App) -> bool {
506 self.multibuffer.read(cx).is_dirty(cx)
507 }
508
509 fn has_conflict(&self, cx: &App) -> bool {
510 self.multibuffer.read(cx).has_conflict(cx)
511 }
512
513 fn can_save(&self, _: &App) -> bool {
514 true
515 }
516
517 fn save(
518 &mut self,
519 format: bool,
520 project: Entity<Project>,
521 window: &mut Window,
522 cx: &mut Context<Self>,
523 ) -> Task<Result<()>> {
524 self.editor.save(format, project, window, cx)
525 }
526
527 fn save_as(
528 &mut self,
529 _: Entity<Project>,
530 _: ProjectPath,
531 _window: &mut Window,
532 _: &mut Context<Self>,
533 ) -> Task<Result<()>> {
534 unreachable!()
535 }
536
537 fn reload(
538 &mut self,
539 project: Entity<Project>,
540 window: &mut Window,
541 cx: &mut Context<Self>,
542 ) -> Task<Result<()>> {
543 self.editor.reload(project, window, cx)
544 }
545
546 fn act_as_type<'a>(
547 &'a self,
548 type_id: TypeId,
549 self_handle: &'a Entity<Self>,
550 _: &'a App,
551 ) -> Option<AnyView> {
552 if type_id == TypeId::of::<Self>() {
553 Some(self_handle.to_any())
554 } else if type_id == TypeId::of::<Editor>() {
555 Some(self.editor.to_any())
556 } else {
557 None
558 }
559 }
560
561 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
562 ToolbarItemLocation::PrimaryLeft
563 }
564
565 fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
566 self.editor.breadcrumbs(theme, cx)
567 }
568
569 fn added_to_workspace(
570 &mut self,
571 workspace: &mut Workspace,
572 window: &mut Window,
573 cx: &mut Context<Self>,
574 ) {
575 self.editor.update(cx, |editor, cx| {
576 editor.added_to_workspace(workspace, window, cx)
577 });
578 }
579}
580
581impl Render for AgentDiff {
582 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
583 let is_empty = self.multibuffer.read(cx).is_empty();
584 let focus_handle = &self.focus_handle;
585
586 div()
587 .track_focus(focus_handle)
588 .key_context(if is_empty { "EmptyPane" } else { "AgentDiff" })
589 .on_action(cx.listener(Self::keep))
590 .on_action(cx.listener(Self::reject))
591 .on_action(cx.listener(Self::reject_all))
592 .on_action(cx.listener(Self::keep_all))
593 .bg(cx.theme().colors().editor_background)
594 .flex()
595 .items_center()
596 .justify_center()
597 .size_full()
598 .when(is_empty, |el| {
599 el.child(
600 v_flex()
601 .items_center()
602 .gap_2()
603 .child("No changes to review")
604 .child(
605 Button::new("continue-iterating", "Continue Iterating")
606 .style(ButtonStyle::Filled)
607 .icon(IconName::ForwardArrow)
608 .icon_position(IconPosition::Start)
609 .icon_size(IconSize::Small)
610 .icon_color(Color::Muted)
611 .full_width()
612 .key_binding(KeyBinding::for_action_in(
613 &ToggleFocus,
614 &focus_handle.clone(),
615 window,
616 cx,
617 ))
618 .on_click(|_event, window, cx| {
619 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
620 }),
621 ),
622 )
623 })
624 .when(!is_empty, |el| el.child(self.editor.clone()))
625 }
626}
627
628fn render_diff_hunk_controls(
629 row: u32,
630 _status: &DiffHunkStatus,
631 hunk_range: Range<editor::Anchor>,
632 is_created_file: bool,
633 line_height: Pixels,
634 agent_diff: &Entity<AgentDiff>,
635 editor: &Entity<Editor>,
636 window: &mut Window,
637 cx: &mut App,
638) -> AnyElement {
639 let editor = editor.clone();
640 h_flex()
641 .h(line_height)
642 .mr_0p5()
643 .gap_1()
644 .px_0p5()
645 .pb_1()
646 .border_x_1()
647 .border_b_1()
648 .border_color(cx.theme().colors().border)
649 .rounded_b_md()
650 .bg(cx.theme().colors().editor_background)
651 .gap_1()
652 .occlude()
653 .shadow_md()
654 .children(vec![
655 Button::new(("reject", row as u64), "Reject")
656 .disabled(is_created_file)
657 .key_binding(
658 KeyBinding::for_action_in(
659 &Reject,
660 &editor.read(cx).focus_handle(cx),
661 window,
662 cx,
663 )
664 .map(|kb| kb.size(rems_from_px(12.))),
665 )
666 .on_click({
667 let agent_diff = agent_diff.clone();
668 move |_event, window, cx| {
669 agent_diff.update(cx, |diff, cx| {
670 diff.reject_edits_in_ranges(
671 vec![hunk_range.start..hunk_range.start],
672 window,
673 cx,
674 );
675 });
676 }
677 }),
678 Button::new(("keep", row as u64), "Keep")
679 .key_binding(
680 KeyBinding::for_action_in(&Keep, &editor.read(cx).focus_handle(cx), window, cx)
681 .map(|kb| kb.size(rems_from_px(12.))),
682 )
683 .on_click({
684 let agent_diff = agent_diff.clone();
685 move |_event, window, cx| {
686 agent_diff.update(cx, |diff, cx| {
687 diff.keep_edits_in_ranges(
688 vec![hunk_range.start..hunk_range.start],
689 window,
690 cx,
691 );
692 });
693 }
694 }),
695 ])
696 .when(
697 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
698 |el| {
699 el.child(
700 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
701 .shape(IconButtonShape::Square)
702 .icon_size(IconSize::Small)
703 // .disabled(!has_multiple_hunks)
704 .tooltip({
705 let focus_handle = editor.focus_handle(cx);
706 move |window, cx| {
707 Tooltip::for_action_in(
708 "Next Hunk",
709 &GoToHunk,
710 &focus_handle,
711 window,
712 cx,
713 )
714 }
715 })
716 .on_click({
717 let editor = editor.clone();
718 move |_event, window, cx| {
719 editor.update(cx, |editor, cx| {
720 let snapshot = editor.snapshot(window, cx);
721 let position =
722 hunk_range.end.to_point(&snapshot.buffer_snapshot);
723 editor.go_to_hunk_before_or_after_position(
724 &snapshot,
725 position,
726 Direction::Next,
727 window,
728 cx,
729 );
730 editor.expand_selected_diff_hunks(cx);
731 });
732 }
733 }),
734 )
735 .child(
736 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
737 .shape(IconButtonShape::Square)
738 .icon_size(IconSize::Small)
739 // .disabled(!has_multiple_hunks)
740 .tooltip({
741 let focus_handle = editor.focus_handle(cx);
742 move |window, cx| {
743 Tooltip::for_action_in(
744 "Previous Hunk",
745 &GoToPreviousHunk,
746 &focus_handle,
747 window,
748 cx,
749 )
750 }
751 })
752 .on_click({
753 let editor = editor.clone();
754 move |_event, window, cx| {
755 editor.update(cx, |editor, cx| {
756 let snapshot = editor.snapshot(window, cx);
757 let point =
758 hunk_range.start.to_point(&snapshot.buffer_snapshot);
759 editor.go_to_hunk_before_or_after_position(
760 &snapshot,
761 point,
762 Direction::Prev,
763 window,
764 cx,
765 );
766 editor.expand_selected_diff_hunks(cx);
767 });
768 }
769 }),
770 )
771 },
772 )
773 .into_any_element()
774}
775
776struct AgentDiffAddon;
777
778impl editor::Addon for AgentDiffAddon {
779 fn to_any(&self) -> &dyn std::any::Any {
780 self
781 }
782
783 fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
784 key_context.add("agent_diff");
785 }
786}
787
788pub struct AgentDiffToolbar {
789 agent_diff: Option<WeakEntity<AgentDiff>>,
790 _workspace: WeakEntity<Workspace>,
791}
792
793impl AgentDiffToolbar {
794 pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
795 Self {
796 agent_diff: None,
797 _workspace: workspace.weak_handle(),
798 }
799 }
800
801 fn agent_diff(&self, _: &App) -> Option<Entity<AgentDiff>> {
802 self.agent_diff.as_ref()?.upgrade()
803 }
804
805 fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
806 if let Some(agent_diff) = self.agent_diff(cx) {
807 agent_diff.focus_handle(cx).focus(window);
808 }
809 let action = action.boxed_clone();
810 cx.defer(move |cx| {
811 cx.dispatch_action(action.as_ref());
812 })
813 }
814}
815
816impl EventEmitter<ToolbarItemEvent> for AgentDiffToolbar {}
817
818impl ToolbarItemView for AgentDiffToolbar {
819 fn set_active_pane_item(
820 &mut self,
821 active_pane_item: Option<&dyn ItemHandle>,
822 _: &mut Window,
823 cx: &mut Context<Self>,
824 ) -> ToolbarItemLocation {
825 self.agent_diff = active_pane_item
826 .and_then(|item| item.act_as::<AgentDiff>(cx))
827 .map(|entity| entity.downgrade());
828 if self.agent_diff.is_some() {
829 ToolbarItemLocation::PrimaryRight
830 } else {
831 ToolbarItemLocation::Hidden
832 }
833 }
834
835 fn pane_focus_update(
836 &mut self,
837 _pane_focused: bool,
838 _window: &mut Window,
839 _cx: &mut Context<Self>,
840 ) {
841 }
842}
843
844impl Render for AgentDiffToolbar {
845 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
846 let agent_diff = match self.agent_diff(cx) {
847 Some(ad) => ad,
848 None => return div(),
849 };
850
851 let is_empty = agent_diff.read(cx).multibuffer.read(cx).is_empty();
852
853 if is_empty {
854 return div();
855 }
856
857 h_group_xl()
858 .my_neg_1()
859 .items_center()
860 .p_1()
861 .flex_wrap()
862 .justify_between()
863 .child(
864 h_group_sm()
865 .child(
866 Button::new("reject-all", "Reject All").on_click(cx.listener(
867 |this, _, window, cx| {
868 this.dispatch_action(&crate::RejectAll, window, cx)
869 },
870 )),
871 )
872 .child(Button::new("keep-all", "Keep All").on_click(cx.listener(
873 |this, _, window, cx| this.dispatch_action(&crate::KeepAll, window, cx),
874 ))),
875 )
876 }
877}
878
879#[cfg(test)]
880mod tests {
881 use super::*;
882 use crate::{ThreadStore, thread_store};
883 use assistant_settings::AssistantSettings;
884 use context_server::ContextServerSettings;
885 use editor::EditorSettings;
886 use gpui::TestAppContext;
887 use project::{FakeFs, Project};
888 use prompt_store::PromptBuilder;
889 use serde_json::json;
890 use settings::{Settings, SettingsStore};
891 use std::sync::Arc;
892 use theme::ThemeSettings;
893 use util::path;
894
895 #[gpui::test]
896 async fn test_agent_diff(cx: &mut TestAppContext) {
897 cx.update(|cx| {
898 let settings_store = SettingsStore::test(cx);
899 cx.set_global(settings_store);
900 language::init(cx);
901 Project::init_settings(cx);
902 AssistantSettings::register(cx);
903 thread_store::init(cx);
904 workspace::init_settings(cx);
905 ThemeSettings::register(cx);
906 ContextServerSettings::register(cx);
907 EditorSettings::register(cx);
908 });
909
910 let fs = FakeFs::new(cx.executor());
911 fs.insert_tree(
912 path!("/test"),
913 json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
914 )
915 .await;
916 let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
917 let buffer_path = project
918 .read_with(cx, |project, cx| {
919 project.find_project_path("test/file1", cx)
920 })
921 .unwrap();
922
923 let thread_store = cx.update(|cx| {
924 ThreadStore::new(
925 project.clone(),
926 Arc::default(),
927 Arc::new(PromptBuilder::new(None).unwrap()),
928 cx,
929 )
930 .unwrap()
931 });
932 let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
933 let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
934
935 let (workspace, cx) =
936 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
937 let agent_diff = cx.new_window_entity(|window, cx| {
938 AgentDiff::new(thread.clone(), workspace.downgrade(), window, cx)
939 });
940 let editor = agent_diff.read_with(cx, |diff, _cx| diff.editor.clone());
941
942 let buffer = project
943 .update(cx, |project, cx| project.open_buffer(buffer_path, cx))
944 .await
945 .unwrap();
946 cx.update(|_, cx| {
947 action_log.update(cx, |log, cx| log.buffer_read(buffer.clone(), cx));
948 buffer.update(cx, |buffer, cx| {
949 buffer
950 .edit(
951 [
952 (Point::new(1, 1)..Point::new(1, 2), "E"),
953 (Point::new(3, 2)..Point::new(3, 3), "L"),
954 (Point::new(5, 0)..Point::new(5, 1), "P"),
955 (Point::new(7, 1)..Point::new(7, 2), "W"),
956 ],
957 None,
958 cx,
959 )
960 .unwrap()
961 });
962 action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
963 });
964 cx.run_until_parked();
965
966 // When opening the assistant diff, the cursor is positioned on the first hunk.
967 assert_eq!(
968 editor.read_with(cx, |editor, cx| editor.text(cx)),
969 "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
970 );
971 assert_eq!(
972 editor
973 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
974 .range(),
975 Point::new(1, 0)..Point::new(1, 0)
976 );
977
978 // After keeping a hunk, the cursor should be positioned on the second hunk.
979 agent_diff.update_in(cx, |diff, window, cx| diff.keep(&crate::Keep, window, cx));
980 cx.run_until_parked();
981 assert_eq!(
982 editor.read_with(cx, |editor, cx| editor.text(cx)),
983 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
984 );
985 assert_eq!(
986 editor
987 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
988 .range(),
989 Point::new(3, 0)..Point::new(3, 0)
990 );
991
992 // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
993 editor.update_in(cx, |editor, window, cx| {
994 editor.change_selections(None, window, cx, |selections| {
995 selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
996 });
997 });
998 agent_diff.update_in(cx, |diff, window, cx| {
999 diff.reject(&crate::Reject, window, cx)
1000 });
1001 cx.run_until_parked();
1002 assert_eq!(
1003 editor.read_with(cx, |editor, cx| editor.text(cx)),
1004 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
1005 );
1006 assert_eq!(
1007 editor
1008 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1009 .range(),
1010 Point::new(3, 0)..Point::new(3, 0)
1011 );
1012
1013 // Keeping a range that doesn't intersect the current selection doesn't move it.
1014 agent_diff.update_in(cx, |diff, window, cx| {
1015 let position = editor
1016 .read(cx)
1017 .buffer()
1018 .read(cx)
1019 .read(cx)
1020 .anchor_before(Point::new(7, 0));
1021 diff.keep_edits_in_ranges(vec![position..position], window, cx)
1022 });
1023 cx.run_until_parked();
1024 assert_eq!(
1025 editor.read_with(cx, |editor, cx| editor.text(cx)),
1026 "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
1027 );
1028 assert_eq!(
1029 editor
1030 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1031 .range(),
1032 Point::new(3, 0)..Point::new(3, 0)
1033 );
1034 }
1035}