1use crate::{
2 Keep, KeepAll, OpenAgentDiff, Reject, RejectAll, Thread, ThreadEvent, ui::AnimatedLabel,
3};
4use anyhow::Result;
5use assistant_settings::AssistantSettings;
6use buffer_diff::DiffHunkStatus;
7use collections::{HashMap, HashSet};
8use editor::{
9 Direction, Editor, EditorEvent, EditorSettings, MultiBuffer, MultiBufferSnapshot, ToPoint,
10 actions::{GoToHunk, GoToPreviousHunk},
11 scroll::Autoscroll,
12};
13use gpui::{
14 Action, AnyElement, AnyView, App, AppContext, Empty, Entity, EventEmitter, FocusHandle,
15 Focusable, Global, SharedString, Subscription, Task, WeakEntity, Window, prelude::*,
16};
17
18use language::{Buffer, Capability, DiskState, OffsetRangeExt, Point};
19use language_model::StopReason;
20use multi_buffer::PathKey;
21use project::{Project, ProjectItem, ProjectPath};
22use settings::{Settings, SettingsStore};
23use std::{
24 any::{Any, TypeId},
25 collections::hash_map::Entry,
26 ops::Range,
27 sync::Arc,
28};
29use ui::{IconButtonShape, KeyBinding, Tooltip, prelude::*, vertical_divider};
30use util::ResultExt;
31use workspace::{
32 Item, ItemHandle, ItemNavHistory, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
33 Workspace,
34 item::{BreadcrumbText, ItemEvent, TabContentParams},
35 searchable::SearchableItemHandle,
36};
37use zed_actions::assistant::ToggleFocus;
38
39pub struct AgentDiffPane {
40 multibuffer: Entity<MultiBuffer>,
41 editor: Entity<Editor>,
42 thread: Entity<Thread>,
43 focus_handle: FocusHandle,
44 workspace: WeakEntity<Workspace>,
45 title: SharedString,
46 _subscriptions: Vec<Subscription>,
47}
48
49impl AgentDiffPane {
50 pub fn deploy(
51 thread: Entity<Thread>,
52 workspace: WeakEntity<Workspace>,
53 window: &mut Window,
54 cx: &mut App,
55 ) -> Result<Entity<Self>> {
56 workspace.update(cx, |workspace, cx| {
57 Self::deploy_in_workspace(thread, workspace, window, cx)
58 })
59 }
60
61 pub fn deploy_in_workspace(
62 thread: Entity<Thread>,
63 workspace: &mut Workspace,
64 window: &mut Window,
65 cx: &mut Context<Workspace>,
66 ) -> Entity<Self> {
67 let existing_diff = workspace
68 .items_of_type::<AgentDiffPane>(cx)
69 .find(|diff| diff.read(cx).thread == thread);
70 if let Some(existing_diff) = existing_diff {
71 workspace.activate_item(&existing_diff, true, true, window, cx);
72 existing_diff
73 } else {
74 let agent_diff = cx
75 .new(|cx| AgentDiffPane::new(thread.clone(), workspace.weak_handle(), window, cx));
76 workspace.add_item_to_center(Box::new(agent_diff.clone()), window, cx);
77 agent_diff
78 }
79 }
80
81 pub fn new(
82 thread: Entity<Thread>,
83 workspace: WeakEntity<Workspace>,
84 window: &mut Window,
85 cx: &mut Context<Self>,
86 ) -> Self {
87 let focus_handle = cx.focus_handle();
88 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
89
90 let project = thread.read(cx).project().clone();
91 let editor = cx.new(|cx| {
92 let mut editor =
93 Editor::for_multibuffer(multibuffer.clone(), Some(project.clone()), window, cx);
94 editor.disable_inline_diagnostics();
95 editor.set_expand_all_diff_hunks(cx);
96 editor.set_render_diff_hunk_controls(diff_hunk_controls(&thread), cx);
97 editor.register_addon(AgentDiffAddon);
98 editor
99 });
100
101 let action_log = thread.read(cx).action_log().clone();
102 let mut this = Self {
103 _subscriptions: vec![
104 cx.observe_in(&action_log, window, |this, _action_log, window, cx| {
105 this.update_excerpts(window, cx)
106 }),
107 cx.subscribe(&thread, |this, _thread, event, cx| {
108 this.handle_thread_event(event, cx)
109 }),
110 ],
111 title: SharedString::default(),
112 multibuffer,
113 editor,
114 thread,
115 focus_handle,
116 workspace,
117 };
118 this.update_excerpts(window, cx);
119 this.update_title(cx);
120 this
121 }
122
123 fn update_excerpts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
124 let thread = self.thread.read(cx);
125 let changed_buffers = thread.action_log().read(cx).changed_buffers(cx);
126 let mut paths_to_delete = self.multibuffer.read(cx).paths().collect::<HashSet<_>>();
127
128 for (buffer, diff_handle) in changed_buffers {
129 if buffer.read(cx).file().is_none() {
130 continue;
131 }
132
133 let path_key = PathKey::for_buffer(&buffer, cx);
134 paths_to_delete.remove(&path_key);
135
136 let snapshot = buffer.read(cx).snapshot();
137 let diff = diff_handle.read(cx);
138
139 let diff_hunk_ranges = diff
140 .hunks_intersecting_range(
141 language::Anchor::MIN..language::Anchor::MAX,
142 &snapshot,
143 cx,
144 )
145 .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot))
146 .collect::<Vec<_>>();
147
148 let (was_empty, is_excerpt_newly_added) =
149 self.multibuffer.update(cx, |multibuffer, cx| {
150 let was_empty = multibuffer.is_empty();
151 let (_, is_excerpt_newly_added) = multibuffer.set_excerpts_for_path(
152 path_key.clone(),
153 buffer.clone(),
154 diff_hunk_ranges,
155 editor::DEFAULT_MULTIBUFFER_CONTEXT,
156 cx,
157 );
158 multibuffer.add_diff(diff_handle, cx);
159 (was_empty, is_excerpt_newly_added)
160 });
161
162 self.editor.update(cx, |editor, cx| {
163 if was_empty {
164 let first_hunk = editor
165 .diff_hunks_in_ranges(
166 &[editor::Anchor::min()..editor::Anchor::max()],
167 &self.multibuffer.read(cx).read(cx),
168 )
169 .next();
170
171 if let Some(first_hunk) = first_hunk {
172 let first_hunk_start = first_hunk.multi_buffer_range().start;
173 editor.change_selections(
174 Some(Autoscroll::fit()),
175 window,
176 cx,
177 |selections| {
178 selections
179 .select_anchor_ranges([first_hunk_start..first_hunk_start]);
180 },
181 )
182 }
183 }
184
185 if is_excerpt_newly_added
186 && buffer
187 .read(cx)
188 .file()
189 .map_or(false, |file| file.disk_state() == DiskState::Deleted)
190 {
191 editor.fold_buffer(snapshot.text.remote_id(), cx)
192 }
193 });
194 }
195
196 self.multibuffer.update(cx, |multibuffer, cx| {
197 for path in paths_to_delete {
198 multibuffer.remove_excerpts_for_path(path, cx);
199 }
200 });
201
202 if self.multibuffer.read(cx).is_empty()
203 && self
204 .editor
205 .read(cx)
206 .focus_handle(cx)
207 .contains_focused(window, cx)
208 {
209 self.focus_handle.focus(window);
210 } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
211 self.editor.update(cx, |editor, cx| {
212 editor.focus_handle(cx).focus(window);
213 });
214 }
215 }
216
217 fn update_title(&mut self, cx: &mut Context<Self>) {
218 let new_title = self
219 .thread
220 .read(cx)
221 .summary()
222 .unwrap_or("Assistant Changes".into());
223 if new_title != self.title {
224 self.title = new_title;
225 cx.emit(EditorEvent::TitleChanged);
226 }
227 }
228
229 fn handle_thread_event(&mut self, event: &ThreadEvent, cx: &mut Context<Self>) {
230 match event {
231 ThreadEvent::SummaryGenerated => self.update_title(cx),
232 _ => {}
233 }
234 }
235
236 pub fn move_to_path(&self, path_key: PathKey, window: &mut Window, cx: &mut App) {
237 if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {
238 self.editor.update(cx, |editor, cx| {
239 let first_hunk = editor
240 .diff_hunks_in_ranges(
241 &[position..editor::Anchor::max()],
242 &self.multibuffer.read(cx).read(cx),
243 )
244 .next();
245
246 if let Some(first_hunk) = first_hunk {
247 let first_hunk_start = first_hunk.multi_buffer_range().start;
248 editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
249 selections.select_anchor_ranges([first_hunk_start..first_hunk_start]);
250 })
251 }
252 });
253 }
254 }
255
256 fn keep(&mut self, _: &Keep, window: &mut Window, cx: &mut Context<Self>) {
257 self.editor.update(cx, |editor, cx| {
258 let snapshot = editor.buffer().read(cx).snapshot(cx);
259 keep_edits_in_selection(editor, &snapshot, &self.thread, window, cx);
260 });
261 }
262
263 fn reject(&mut self, _: &Reject, window: &mut Window, cx: &mut Context<Self>) {
264 self.editor.update(cx, |editor, cx| {
265 let snapshot = editor.buffer().read(cx).snapshot(cx);
266 reject_edits_in_selection(editor, &snapshot, &self.thread, window, cx);
267 });
268 }
269
270 fn reject_all(&mut self, _: &RejectAll, window: &mut Window, cx: &mut Context<Self>) {
271 self.editor.update(cx, |editor, cx| {
272 let snapshot = editor.buffer().read(cx).snapshot(cx);
273 reject_edits_in_ranges(
274 editor,
275 &snapshot,
276 &self.thread,
277 vec![editor::Anchor::min()..editor::Anchor::max()],
278 window,
279 cx,
280 );
281 });
282 }
283
284 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
285 self.thread
286 .update(cx, |thread, cx| thread.keep_all_edits(cx));
287 }
288}
289
290fn keep_edits_in_selection(
291 editor: &mut Editor,
292 buffer_snapshot: &MultiBufferSnapshot,
293 thread: &Entity<Thread>,
294 window: &mut Window,
295 cx: &mut Context<Editor>,
296) {
297 let ranges = editor
298 .selections
299 .disjoint_anchor_ranges()
300 .collect::<Vec<_>>();
301
302 keep_edits_in_ranges(editor, buffer_snapshot, &thread, ranges, window, cx)
303}
304
305fn reject_edits_in_selection(
306 editor: &mut Editor,
307 buffer_snapshot: &MultiBufferSnapshot,
308 thread: &Entity<Thread>,
309 window: &mut Window,
310 cx: &mut Context<Editor>,
311) {
312 let ranges = editor
313 .selections
314 .disjoint_anchor_ranges()
315 .collect::<Vec<_>>();
316 reject_edits_in_ranges(editor, buffer_snapshot, &thread, ranges, window, cx)
317}
318
319fn keep_edits_in_ranges(
320 editor: &mut Editor,
321 buffer_snapshot: &MultiBufferSnapshot,
322 thread: &Entity<Thread>,
323 ranges: Vec<Range<editor::Anchor>>,
324 window: &mut Window,
325 cx: &mut Context<Editor>,
326) {
327 if thread.read(cx).is_generating() {
328 return;
329 }
330
331 let diff_hunks_in_ranges = editor
332 .diff_hunks_in_ranges(&ranges, buffer_snapshot)
333 .collect::<Vec<_>>();
334
335 update_editor_selection(editor, buffer_snapshot, &diff_hunks_in_ranges, window, cx);
336
337 let multibuffer = editor.buffer().clone();
338 for hunk in &diff_hunks_in_ranges {
339 let buffer = multibuffer.read(cx).buffer(hunk.buffer_id);
340 if let Some(buffer) = buffer {
341 thread.update(cx, |thread, cx| {
342 thread.keep_edits_in_range(buffer, hunk.buffer_range.clone(), cx)
343 });
344 }
345 }
346}
347
348fn reject_edits_in_ranges(
349 editor: &mut Editor,
350 buffer_snapshot: &MultiBufferSnapshot,
351 thread: &Entity<Thread>,
352 ranges: Vec<Range<editor::Anchor>>,
353 window: &mut Window,
354 cx: &mut Context<Editor>,
355) {
356 if thread.read(cx).is_generating() {
357 return;
358 }
359
360 let diff_hunks_in_ranges = editor
361 .diff_hunks_in_ranges(&ranges, buffer_snapshot)
362 .collect::<Vec<_>>();
363
364 update_editor_selection(editor, buffer_snapshot, &diff_hunks_in_ranges, window, cx);
365
366 let multibuffer = editor.buffer().clone();
367
368 let mut ranges_by_buffer = HashMap::default();
369 for hunk in &diff_hunks_in_ranges {
370 let buffer = multibuffer.read(cx).buffer(hunk.buffer_id);
371 if let Some(buffer) = buffer {
372 ranges_by_buffer
373 .entry(buffer.clone())
374 .or_insert_with(Vec::new)
375 .push(hunk.buffer_range.clone());
376 }
377 }
378
379 for (buffer, ranges) in ranges_by_buffer {
380 thread
381 .update(cx, |thread, cx| {
382 thread.reject_edits_in_ranges(buffer, ranges, cx)
383 })
384 .detach_and_log_err(cx);
385 }
386}
387
388fn update_editor_selection(
389 editor: &mut Editor,
390 buffer_snapshot: &MultiBufferSnapshot,
391 diff_hunks: &[multi_buffer::MultiBufferDiffHunk],
392 window: &mut Window,
393 cx: &mut Context<Editor>,
394) {
395 let newest_cursor = editor.selections.newest::<Point>(cx).head();
396
397 if !diff_hunks.iter().any(|hunk| {
398 hunk.row_range
399 .contains(&multi_buffer::MultiBufferRow(newest_cursor.row))
400 }) {
401 return;
402 }
403
404 let target_hunk = {
405 diff_hunks
406 .last()
407 .and_then(|last_kept_hunk| {
408 let last_kept_hunk_end = last_kept_hunk.multi_buffer_range().end;
409 editor
410 .diff_hunks_in_ranges(
411 &[last_kept_hunk_end..editor::Anchor::max()],
412 buffer_snapshot,
413 )
414 .skip(1)
415 .next()
416 })
417 .or_else(|| {
418 let first_kept_hunk = diff_hunks.first()?;
419 let first_kept_hunk_start = first_kept_hunk.multi_buffer_range().start;
420 editor
421 .diff_hunks_in_ranges(
422 &[editor::Anchor::min()..first_kept_hunk_start],
423 buffer_snapshot,
424 )
425 .next()
426 })
427 };
428
429 if let Some(target_hunk) = target_hunk {
430 editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
431 let next_hunk_start = target_hunk.multi_buffer_range().start;
432 selections.select_anchor_ranges([next_hunk_start..next_hunk_start]);
433 })
434 }
435}
436
437impl EventEmitter<EditorEvent> for AgentDiffPane {}
438
439impl Focusable for AgentDiffPane {
440 fn focus_handle(&self, cx: &App) -> FocusHandle {
441 if self.multibuffer.read(cx).is_empty() {
442 self.focus_handle.clone()
443 } else {
444 self.editor.focus_handle(cx)
445 }
446 }
447}
448
449impl Item for AgentDiffPane {
450 type Event = EditorEvent;
451
452 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
453 Some(Icon::new(IconName::ZedAssistant).color(Color::Muted))
454 }
455
456 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
457 Editor::to_item_events(event, f)
458 }
459
460 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
461 self.editor
462 .update(cx, |editor, cx| editor.deactivated(window, cx));
463 }
464
465 fn navigate(
466 &mut self,
467 data: Box<dyn Any>,
468 window: &mut Window,
469 cx: &mut Context<Self>,
470 ) -> bool {
471 self.editor
472 .update(cx, |editor, cx| editor.navigate(data, window, cx))
473 }
474
475 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
476 Some("Agent Diff".into())
477 }
478
479 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
480 let summary = self
481 .thread
482 .read(cx)
483 .summary()
484 .unwrap_or("Assistant Changes".into());
485 Label::new(format!("Review: {}", summary))
486 .color(if params.selected {
487 Color::Default
488 } else {
489 Color::Muted
490 })
491 .into_any_element()
492 }
493
494 fn telemetry_event_text(&self) -> Option<&'static str> {
495 Some("Assistant Diff Opened")
496 }
497
498 fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
499 Some(Box::new(self.editor.clone()))
500 }
501
502 fn for_each_project_item(
503 &self,
504 cx: &App,
505 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
506 ) {
507 self.editor.for_each_project_item(cx, f)
508 }
509
510 fn is_singleton(&self, _: &App) -> bool {
511 false
512 }
513
514 fn set_nav_history(
515 &mut self,
516 nav_history: ItemNavHistory,
517 _: &mut Window,
518 cx: &mut Context<Self>,
519 ) {
520 self.editor.update(cx, |editor, _| {
521 editor.set_nav_history(Some(nav_history));
522 });
523 }
524
525 fn clone_on_split(
526 &self,
527 _workspace_id: Option<workspace::WorkspaceId>,
528 window: &mut Window,
529 cx: &mut Context<Self>,
530 ) -> Option<Entity<Self>>
531 where
532 Self: Sized,
533 {
534 Some(cx.new(|cx| Self::new(self.thread.clone(), self.workspace.clone(), window, cx)))
535 }
536
537 fn is_dirty(&self, cx: &App) -> bool {
538 self.multibuffer.read(cx).is_dirty(cx)
539 }
540
541 fn has_conflict(&self, cx: &App) -> bool {
542 self.multibuffer.read(cx).has_conflict(cx)
543 }
544
545 fn can_save(&self, _: &App) -> bool {
546 true
547 }
548
549 fn save(
550 &mut self,
551 format: bool,
552 project: Entity<Project>,
553 window: &mut Window,
554 cx: &mut Context<Self>,
555 ) -> Task<Result<()>> {
556 self.editor.save(format, project, window, cx)
557 }
558
559 fn save_as(
560 &mut self,
561 _: Entity<Project>,
562 _: ProjectPath,
563 _window: &mut Window,
564 _: &mut Context<Self>,
565 ) -> Task<Result<()>> {
566 unreachable!()
567 }
568
569 fn reload(
570 &mut self,
571 project: Entity<Project>,
572 window: &mut Window,
573 cx: &mut Context<Self>,
574 ) -> Task<Result<()>> {
575 self.editor.reload(project, window, cx)
576 }
577
578 fn act_as_type<'a>(
579 &'a self,
580 type_id: TypeId,
581 self_handle: &'a Entity<Self>,
582 _: &'a App,
583 ) -> Option<AnyView> {
584 if type_id == TypeId::of::<Self>() {
585 Some(self_handle.to_any())
586 } else if type_id == TypeId::of::<Editor>() {
587 Some(self.editor.to_any())
588 } else {
589 None
590 }
591 }
592
593 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
594 ToolbarItemLocation::PrimaryLeft
595 }
596
597 fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
598 self.editor.breadcrumbs(theme, cx)
599 }
600
601 fn added_to_workspace(
602 &mut self,
603 workspace: &mut Workspace,
604 window: &mut Window,
605 cx: &mut Context<Self>,
606 ) {
607 self.editor.update(cx, |editor, cx| {
608 editor.added_to_workspace(workspace, window, cx)
609 });
610 }
611
612 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
613 "Agent Diff".into()
614 }
615}
616
617impl Render for AgentDiffPane {
618 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
619 let is_empty = self.multibuffer.read(cx).is_empty();
620 let focus_handle = &self.focus_handle;
621
622 div()
623 .track_focus(focus_handle)
624 .key_context(if is_empty { "EmptyPane" } else { "AgentDiff" })
625 .on_action(cx.listener(Self::keep))
626 .on_action(cx.listener(Self::reject))
627 .on_action(cx.listener(Self::reject_all))
628 .on_action(cx.listener(Self::keep_all))
629 .bg(cx.theme().colors().editor_background)
630 .flex()
631 .items_center()
632 .justify_center()
633 .size_full()
634 .when(is_empty, |el| {
635 el.child(
636 v_flex()
637 .items_center()
638 .gap_2()
639 .child("No changes to review")
640 .child(
641 Button::new("continue-iterating", "Continue Iterating")
642 .style(ButtonStyle::Filled)
643 .icon(IconName::ForwardArrow)
644 .icon_position(IconPosition::Start)
645 .icon_size(IconSize::Small)
646 .icon_color(Color::Muted)
647 .full_width()
648 .key_binding(KeyBinding::for_action_in(
649 &ToggleFocus,
650 &focus_handle.clone(),
651 window,
652 cx,
653 ))
654 .on_click(|_event, window, cx| {
655 window.dispatch_action(ToggleFocus.boxed_clone(), cx)
656 }),
657 ),
658 )
659 })
660 .when(!is_empty, |el| el.child(self.editor.clone()))
661 }
662}
663
664fn diff_hunk_controls(thread: &Entity<Thread>) -> editor::RenderDiffHunkControlsFn {
665 let thread = thread.clone();
666
667 Arc::new(
668 move |row,
669 status: &DiffHunkStatus,
670 hunk_range,
671 is_created_file,
672 line_height,
673 editor: &Entity<Editor>,
674 window: &mut Window,
675 cx: &mut App| {
676 {
677 render_diff_hunk_controls(
678 row,
679 status,
680 hunk_range,
681 is_created_file,
682 line_height,
683 &thread,
684 editor,
685 window,
686 cx,
687 )
688 }
689 },
690 )
691}
692
693fn render_diff_hunk_controls(
694 row: u32,
695 _status: &DiffHunkStatus,
696 hunk_range: Range<editor::Anchor>,
697 is_created_file: bool,
698 line_height: Pixels,
699 thread: &Entity<Thread>,
700 editor: &Entity<Editor>,
701 window: &mut Window,
702 cx: &mut App,
703) -> AnyElement {
704 let editor = editor.clone();
705
706 if thread.read(cx).is_generating() {
707 return Empty.into_any();
708 }
709
710 h_flex()
711 .h(line_height)
712 .mr_0p5()
713 .gap_1()
714 .px_0p5()
715 .pb_1()
716 .border_x_1()
717 .border_b_1()
718 .border_color(cx.theme().colors().border)
719 .rounded_b_md()
720 .bg(cx.theme().colors().editor_background)
721 .gap_1()
722 .occlude()
723 .shadow_md()
724 .children(vec![
725 Button::new(("reject", row as u64), "Reject")
726 .disabled(is_created_file)
727 .key_binding(
728 KeyBinding::for_action_in(
729 &Reject,
730 &editor.read(cx).focus_handle(cx),
731 window,
732 cx,
733 )
734 .map(|kb| kb.size(rems_from_px(12.))),
735 )
736 .on_click({
737 let editor = editor.clone();
738 let thread = thread.clone();
739 move |_event, window, cx| {
740 editor.update(cx, |editor, cx| {
741 let snapshot = editor.buffer().read(cx).snapshot(cx);
742 reject_edits_in_ranges(
743 editor,
744 &snapshot,
745 &thread,
746 vec![hunk_range.start..hunk_range.start],
747 window,
748 cx,
749 );
750 })
751 }
752 }),
753 Button::new(("keep", row as u64), "Keep")
754 .key_binding(
755 KeyBinding::for_action_in(&Keep, &editor.read(cx).focus_handle(cx), window, cx)
756 .map(|kb| kb.size(rems_from_px(12.))),
757 )
758 .on_click({
759 let editor = editor.clone();
760 let thread = thread.clone();
761 move |_event, window, cx| {
762 editor.update(cx, |editor, cx| {
763 let snapshot = editor.buffer().read(cx).snapshot(cx);
764 keep_edits_in_ranges(
765 editor,
766 &snapshot,
767 &thread,
768 vec![hunk_range.start..hunk_range.start],
769 window,
770 cx,
771 );
772 });
773 }
774 }),
775 ])
776 .when(
777 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
778 |el| {
779 el.child(
780 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
781 .shape(IconButtonShape::Square)
782 .icon_size(IconSize::Small)
783 // .disabled(!has_multiple_hunks)
784 .tooltip({
785 let focus_handle = editor.focus_handle(cx);
786 move |window, cx| {
787 Tooltip::for_action_in(
788 "Next Hunk",
789 &GoToHunk,
790 &focus_handle,
791 window,
792 cx,
793 )
794 }
795 })
796 .on_click({
797 let editor = editor.clone();
798 move |_event, window, cx| {
799 editor.update(cx, |editor, cx| {
800 let snapshot = editor.snapshot(window, cx);
801 let position =
802 hunk_range.end.to_point(&snapshot.buffer_snapshot);
803 editor.go_to_hunk_before_or_after_position(
804 &snapshot,
805 position,
806 Direction::Next,
807 window,
808 cx,
809 );
810 editor.expand_selected_diff_hunks(cx);
811 });
812 }
813 }),
814 )
815 .child(
816 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
817 .shape(IconButtonShape::Square)
818 .icon_size(IconSize::Small)
819 // .disabled(!has_multiple_hunks)
820 .tooltip({
821 let focus_handle = editor.focus_handle(cx);
822 move |window, cx| {
823 Tooltip::for_action_in(
824 "Previous Hunk",
825 &GoToPreviousHunk,
826 &focus_handle,
827 window,
828 cx,
829 )
830 }
831 })
832 .on_click({
833 let editor = editor.clone();
834 move |_event, window, cx| {
835 editor.update(cx, |editor, cx| {
836 let snapshot = editor.snapshot(window, cx);
837 let point =
838 hunk_range.start.to_point(&snapshot.buffer_snapshot);
839 editor.go_to_hunk_before_or_after_position(
840 &snapshot,
841 point,
842 Direction::Prev,
843 window,
844 cx,
845 );
846 editor.expand_selected_diff_hunks(cx);
847 });
848 }
849 }),
850 )
851 },
852 )
853 .into_any_element()
854}
855
856struct AgentDiffAddon;
857
858impl editor::Addon for AgentDiffAddon {
859 fn to_any(&self) -> &dyn std::any::Any {
860 self
861 }
862
863 fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
864 key_context.add("agent_diff");
865 }
866}
867
868pub struct AgentDiffToolbar {
869 active_item: Option<AgentDiffToolbarItem>,
870 _settings_subscription: Subscription,
871}
872
873pub enum AgentDiffToolbarItem {
874 Pane(WeakEntity<AgentDiffPane>),
875 Editor {
876 editor: WeakEntity<Editor>,
877 state: EditorState,
878 _diff_subscription: Subscription,
879 },
880}
881
882impl AgentDiffToolbar {
883 pub fn new(cx: &mut Context<Self>) -> Self {
884 Self {
885 active_item: None,
886 _settings_subscription: cx.observe_global::<SettingsStore>(Self::update_location),
887 }
888 }
889
890 fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
891 let Some(active_item) = self.active_item.as_ref() else {
892 return;
893 };
894
895 match active_item {
896 AgentDiffToolbarItem::Pane(agent_diff) => {
897 if let Some(agent_diff) = agent_diff.upgrade() {
898 agent_diff.focus_handle(cx).focus(window);
899 }
900 }
901 AgentDiffToolbarItem::Editor { editor, .. } => {
902 if let Some(editor) = editor.upgrade() {
903 editor.read(cx).focus_handle(cx).focus(window);
904 }
905 }
906 }
907
908 let action = action.boxed_clone();
909 cx.defer(move |cx| {
910 cx.dispatch_action(action.as_ref());
911 })
912 }
913
914 fn handle_diff_notify(&mut self, agent_diff: Entity<AgentDiff>, cx: &mut Context<Self>) {
915 let Some(AgentDiffToolbarItem::Editor { editor, state, .. }) = self.active_item.as_mut()
916 else {
917 return;
918 };
919
920 *state = agent_diff.read(cx).editor_state(&editor);
921 self.update_location(cx);
922 cx.notify();
923 }
924
925 fn update_location(&mut self, cx: &mut Context<Self>) {
926 let location = self.location(cx);
927 cx.emit(ToolbarItemEvent::ChangeLocation(location));
928 }
929
930 fn location(&self, cx: &App) -> ToolbarItemLocation {
931 if !EditorSettings::get_global(cx).toolbar.agent_review {
932 return ToolbarItemLocation::Hidden;
933 }
934
935 match &self.active_item {
936 None => ToolbarItemLocation::Hidden,
937 Some(AgentDiffToolbarItem::Pane(_)) => ToolbarItemLocation::PrimaryRight,
938 Some(AgentDiffToolbarItem::Editor { state, .. }) => match state {
939 EditorState::Generating | EditorState::Reviewing => {
940 ToolbarItemLocation::PrimaryLeft
941 }
942 EditorState::Idle => ToolbarItemLocation::Hidden,
943 },
944 }
945 }
946}
947
948impl EventEmitter<ToolbarItemEvent> for AgentDiffToolbar {}
949
950impl ToolbarItemView for AgentDiffToolbar {
951 fn set_active_pane_item(
952 &mut self,
953 active_pane_item: Option<&dyn ItemHandle>,
954 _: &mut Window,
955 cx: &mut Context<Self>,
956 ) -> ToolbarItemLocation {
957 if let Some(item) = active_pane_item {
958 if let Some(pane) = item.act_as::<AgentDiffPane>(cx) {
959 self.active_item = Some(AgentDiffToolbarItem::Pane(pane.downgrade()));
960 return self.location(cx);
961 }
962
963 if let Some(editor) = item.act_as::<Editor>(cx) {
964 if editor.read(cx).mode().is_full() {
965 let agent_diff = AgentDiff::global(cx);
966
967 self.active_item = Some(AgentDiffToolbarItem::Editor {
968 editor: editor.downgrade(),
969 state: agent_diff.read(cx).editor_state(&editor.downgrade()),
970 _diff_subscription: cx.observe(&agent_diff, Self::handle_diff_notify),
971 });
972
973 return self.location(cx);
974 }
975 }
976 }
977
978 self.active_item = None;
979 return self.location(cx);
980 }
981
982 fn pane_focus_update(
983 &mut self,
984 _pane_focused: bool,
985 _window: &mut Window,
986 _cx: &mut Context<Self>,
987 ) {
988 }
989}
990
991impl Render for AgentDiffToolbar {
992 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
993 let Some(active_item) = self.active_item.as_ref() else {
994 return Empty.into_any();
995 };
996
997 match active_item {
998 AgentDiffToolbarItem::Editor { editor, state, .. } => {
999 let Some(editor) = editor.upgrade() else {
1000 return Empty.into_any();
1001 };
1002
1003 let editor_focus_handle = editor.read(cx).focus_handle(cx);
1004
1005 let content = match state {
1006 EditorState::Idle => return Empty.into_any(),
1007 EditorState::Generating => vec![
1008 h_flex()
1009 .ml_1()
1010 .gap_1p5()
1011 .w_32()
1012 .child(Icon::new(IconName::ZedAssistant))
1013 .child(
1014 div()
1015 .w(rems(6.5625))
1016 .child(AnimatedLabel::new("Generating")),
1017 )
1018 .into_any(),
1019 ],
1020 EditorState::Reviewing => vec![
1021 h_flex()
1022 .child(
1023 IconButton::new("hunk-up", IconName::ArrowUp)
1024 .tooltip(ui::Tooltip::for_action_title_in(
1025 "Previous Hunk",
1026 &GoToPreviousHunk,
1027 &editor_focus_handle,
1028 ))
1029 .on_click({
1030 let editor_focus_handle = editor_focus_handle.clone();
1031 move |_, window, cx| {
1032 editor_focus_handle.dispatch_action(
1033 &GoToPreviousHunk,
1034 window,
1035 cx,
1036 );
1037 }
1038 }),
1039 )
1040 .child(
1041 IconButton::new("hunk-down", IconName::ArrowDown)
1042 .tooltip(ui::Tooltip::for_action_title_in(
1043 "Next Hunk",
1044 &GoToHunk,
1045 &editor_focus_handle,
1046 ))
1047 .on_click({
1048 let editor_focus_handle = editor_focus_handle.clone();
1049 move |_, window, cx| {
1050 editor_focus_handle
1051 .dispatch_action(&GoToHunk, window, cx);
1052 }
1053 }),
1054 )
1055 .into_any(),
1056 vertical_divider().into_any_element(),
1057 h_flex()
1058 .child(
1059 Button::new("reject-all", "Reject All")
1060 .key_binding({
1061 KeyBinding::for_action_in(
1062 &RejectAll,
1063 &editor_focus_handle,
1064 window,
1065 cx,
1066 )
1067 .map(|kb| kb.size(rems_from_px(12.)))
1068 })
1069 .on_click(cx.listener(|this, _, window, cx| {
1070 this.dispatch_action(&RejectAll, window, cx)
1071 })),
1072 )
1073 .child(
1074 Button::new("keep-all", "Keep All")
1075 .key_binding({
1076 KeyBinding::for_action_in(
1077 &KeepAll,
1078 &editor_focus_handle,
1079 window,
1080 cx,
1081 )
1082 .map(|kb| kb.size(rems_from_px(12.)))
1083 })
1084 .on_click(cx.listener(|this, _, window, cx| {
1085 this.dispatch_action(&KeepAll, window, cx)
1086 })),
1087 )
1088 .into_any(),
1089 ],
1090 };
1091
1092 h_flex()
1093 .bg(cx.theme().colors().surface_background)
1094 .rounded_md()
1095 .p_1()
1096 .mx_2()
1097 .gap_1()
1098 .children(content)
1099 .child(vertical_divider())
1100 .track_focus(&editor_focus_handle)
1101 .on_action({
1102 let editor = editor.clone();
1103 move |_action: &OpenAgentDiff, window, cx| {
1104 AgentDiff::global(cx).update(cx, |agent_diff, cx| {
1105 agent_diff.deploy_pane_from_editor(&editor, window, cx);
1106 });
1107 }
1108 })
1109 .when_some(editor.read(cx).workspace(), |this, _workspace| {
1110 this.child(
1111 IconButton::new("review", IconName::ListTree)
1112 .tooltip(ui::Tooltip::for_action_title_in(
1113 "Review All Files",
1114 &OpenAgentDiff,
1115 &editor_focus_handle,
1116 ))
1117 .on_click({
1118 cx.listener(move |this, _, window, cx| {
1119 this.dispatch_action(&OpenAgentDiff, window, cx);
1120 })
1121 }),
1122 )
1123 })
1124 .into_any()
1125 }
1126 AgentDiffToolbarItem::Pane(agent_diff) => {
1127 let Some(agent_diff) = agent_diff.upgrade() else {
1128 return Empty.into_any();
1129 };
1130
1131 let is_generating = agent_diff.read(cx).thread.read(cx).is_generating();
1132 if is_generating {
1133 return div()
1134 .w(rems(6.5625)) // Arbitrary 105px size—so the label doesn't dance around
1135 .child(AnimatedLabel::new("Generating"))
1136 .into_any();
1137 }
1138
1139 let is_empty = agent_diff.read(cx).multibuffer.read(cx).is_empty();
1140 if is_empty {
1141 return Empty.into_any();
1142 }
1143
1144 let focus_handle = agent_diff.focus_handle(cx);
1145
1146 h_group_xl()
1147 .my_neg_1()
1148 .items_center()
1149 .p_1()
1150 .flex_wrap()
1151 .justify_between()
1152 .child(
1153 h_group_sm()
1154 .child(
1155 Button::new("reject-all", "Reject All")
1156 .key_binding({
1157 KeyBinding::for_action_in(
1158 &RejectAll,
1159 &focus_handle,
1160 window,
1161 cx,
1162 )
1163 .map(|kb| kb.size(rems_from_px(12.)))
1164 })
1165 .on_click(cx.listener(|this, _, window, cx| {
1166 this.dispatch_action(&RejectAll, window, cx)
1167 })),
1168 )
1169 .child(
1170 Button::new("keep-all", "Keep All")
1171 .key_binding({
1172 KeyBinding::for_action_in(
1173 &KeepAll,
1174 &focus_handle,
1175 window,
1176 cx,
1177 )
1178 .map(|kb| kb.size(rems_from_px(12.)))
1179 })
1180 .on_click(cx.listener(|this, _, window, cx| {
1181 this.dispatch_action(&KeepAll, window, cx)
1182 })),
1183 ),
1184 )
1185 .into_any()
1186 }
1187 }
1188 }
1189}
1190
1191#[derive(Default)]
1192pub struct AgentDiff {
1193 reviewing_editors: HashMap<WeakEntity<Editor>, EditorState>,
1194 workspace_threads: HashMap<WeakEntity<Workspace>, WorkspaceThread>,
1195}
1196
1197#[derive(Clone, Debug, PartialEq, Eq)]
1198pub enum EditorState {
1199 Idle,
1200 Reviewing,
1201 Generating,
1202}
1203
1204struct WorkspaceThread {
1205 thread: WeakEntity<Thread>,
1206 _thread_subscriptions: [Subscription; 2],
1207 singleton_editors: HashMap<WeakEntity<Buffer>, HashMap<WeakEntity<Editor>, Subscription>>,
1208 _settings_subscription: Subscription,
1209 _workspace_subscription: Option<Subscription>,
1210}
1211
1212struct AgentDiffGlobal(Entity<AgentDiff>);
1213
1214impl Global for AgentDiffGlobal {}
1215
1216impl AgentDiff {
1217 fn global(cx: &mut App) -> Entity<Self> {
1218 cx.try_global::<AgentDiffGlobal>()
1219 .map(|global| global.0.clone())
1220 .unwrap_or_else(|| {
1221 let entity = cx.new(|_cx| Self::default());
1222 let global = AgentDiffGlobal(entity.clone());
1223 cx.set_global(global);
1224 entity.clone()
1225 })
1226 }
1227
1228 pub fn set_active_thread(
1229 workspace: &WeakEntity<Workspace>,
1230 thread: &Entity<Thread>,
1231 window: &mut Window,
1232 cx: &mut App,
1233 ) {
1234 Self::global(cx).update(cx, |this, cx| {
1235 this.register_active_thread_impl(workspace, thread, window, cx);
1236 });
1237 }
1238
1239 fn register_active_thread_impl(
1240 &mut self,
1241 workspace: &WeakEntity<Workspace>,
1242 thread: &Entity<Thread>,
1243 window: &mut Window,
1244 cx: &mut Context<Self>,
1245 ) {
1246 let action_log = thread.read(cx).action_log().clone();
1247
1248 let action_log_subscription = cx.observe_in(&action_log, window, {
1249 let workspace = workspace.clone();
1250 move |this, _action_log, window, cx| {
1251 this.update_reviewing_editors(&workspace, window, cx);
1252 }
1253 });
1254
1255 let thread_subscription = cx.subscribe_in(&thread, window, {
1256 let workspace = workspace.clone();
1257 move |this, _thread, event, window, cx| {
1258 this.handle_thread_event(&workspace, event, window, cx)
1259 }
1260 });
1261
1262 if let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) {
1263 // replace thread and action log subscription, but keep editors
1264 workspace_thread.thread = thread.downgrade();
1265 workspace_thread._thread_subscriptions = [action_log_subscription, thread_subscription];
1266 self.update_reviewing_editors(&workspace, window, cx);
1267 return;
1268 }
1269
1270 let settings_subscription = cx.observe_global_in::<SettingsStore>(window, {
1271 let workspace = workspace.clone();
1272 let mut was_active = AssistantSettings::get_global(cx).single_file_review;
1273 move |this, window, cx| {
1274 let is_active = AssistantSettings::get_global(cx).single_file_review;
1275 if was_active != is_active {
1276 was_active = is_active;
1277 this.update_reviewing_editors(&workspace, window, cx);
1278 }
1279 }
1280 });
1281
1282 let workspace_subscription = workspace
1283 .upgrade()
1284 .map(|workspace| cx.subscribe_in(&workspace, window, Self::handle_workspace_event));
1285
1286 self.workspace_threads.insert(
1287 workspace.clone(),
1288 WorkspaceThread {
1289 thread: thread.downgrade(),
1290 _thread_subscriptions: [action_log_subscription, thread_subscription],
1291 singleton_editors: HashMap::default(),
1292 _settings_subscription: settings_subscription,
1293 _workspace_subscription: workspace_subscription,
1294 },
1295 );
1296
1297 let workspace = workspace.clone();
1298 cx.defer_in(window, move |this, window, cx| {
1299 if let Some(workspace) = workspace.upgrade() {
1300 this.register_workspace(workspace, window, cx);
1301 }
1302 });
1303 }
1304
1305 fn register_workspace(
1306 &mut self,
1307 workspace: Entity<Workspace>,
1308 window: &mut Window,
1309 cx: &mut Context<Self>,
1310 ) {
1311 let agent_diff = cx.entity();
1312
1313 let editors = workspace.update(cx, |workspace, cx| {
1314 let agent_diff = agent_diff.clone();
1315
1316 Self::register_review_action::<Keep>(workspace, Self::keep, &agent_diff);
1317 Self::register_review_action::<Reject>(workspace, Self::reject, &agent_diff);
1318 Self::register_review_action::<KeepAll>(workspace, Self::keep_all, &agent_diff);
1319 Self::register_review_action::<RejectAll>(workspace, Self::reject_all, &agent_diff);
1320
1321 workspace.items_of_type(cx).collect::<Vec<_>>()
1322 });
1323
1324 let weak_workspace = workspace.downgrade();
1325
1326 for editor in editors {
1327 if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1328 self.register_editor(weak_workspace.clone(), buffer, editor, window, cx);
1329 };
1330 }
1331
1332 self.update_reviewing_editors(&weak_workspace, window, cx);
1333 }
1334
1335 fn register_review_action<T: Action>(
1336 workspace: &mut Workspace,
1337 review: impl Fn(&Entity<Editor>, &Entity<Thread>, &mut Window, &mut App) -> PostReviewState
1338 + 'static,
1339 this: &Entity<AgentDiff>,
1340 ) {
1341 let this = this.clone();
1342 workspace.register_action(move |workspace, _: &T, window, cx| {
1343 let review = &review;
1344 let task = this.update(cx, |this, cx| {
1345 this.review_in_active_editor(workspace, review, window, cx)
1346 });
1347
1348 if let Some(task) = task {
1349 task.detach_and_log_err(cx);
1350 } else {
1351 cx.propagate();
1352 }
1353 });
1354 }
1355
1356 fn handle_thread_event(
1357 &mut self,
1358 workspace: &WeakEntity<Workspace>,
1359 event: &ThreadEvent,
1360 window: &mut Window,
1361 cx: &mut Context<Self>,
1362 ) {
1363 match event {
1364 ThreadEvent::NewRequest
1365 | ThreadEvent::Stopped(Ok(StopReason::EndTurn))
1366 | ThreadEvent::Stopped(Ok(StopReason::MaxTokens))
1367 | ThreadEvent::Stopped(Err(_))
1368 | ThreadEvent::ShowError(_)
1369 | ThreadEvent::CompletionCanceled => {
1370 self.update_reviewing_editors(workspace, window, cx);
1371 }
1372 // intentionally being exhaustive in case we add a variant we should handle
1373 ThreadEvent::Stopped(Ok(StopReason::ToolUse))
1374 | ThreadEvent::UsageUpdated(_)
1375 | ThreadEvent::StreamedCompletion
1376 | ThreadEvent::ReceivedTextChunk
1377 | ThreadEvent::StreamedAssistantText(_, _)
1378 | ThreadEvent::StreamedAssistantThinking(_, _)
1379 | ThreadEvent::StreamedToolUse { .. }
1380 | ThreadEvent::InvalidToolInput { .. }
1381 | ThreadEvent::MessageAdded(_)
1382 | ThreadEvent::MessageEdited(_)
1383 | ThreadEvent::MessageDeleted(_)
1384 | ThreadEvent::SummaryGenerated
1385 | ThreadEvent::SummaryChanged
1386 | ThreadEvent::UsePendingTools { .. }
1387 | ThreadEvent::ToolFinished { .. }
1388 | ThreadEvent::CheckpointChanged
1389 | ThreadEvent::ToolConfirmationNeeded
1390 | ThreadEvent::CancelEditing => {}
1391 }
1392 }
1393
1394 fn handle_workspace_event(
1395 &mut self,
1396 workspace: &Entity<Workspace>,
1397 event: &workspace::Event,
1398 window: &mut Window,
1399 cx: &mut Context<Self>,
1400 ) {
1401 match event {
1402 workspace::Event::ItemAdded { item } => {
1403 if let Some(editor) = item.downcast::<Editor>() {
1404 if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1405 self.register_editor(
1406 workspace.downgrade(),
1407 buffer.clone(),
1408 editor,
1409 window,
1410 cx,
1411 );
1412 }
1413 }
1414 }
1415 _ => {}
1416 }
1417 }
1418
1419 fn full_editor_buffer(editor: &Editor, cx: &App) -> Option<WeakEntity<Buffer>> {
1420 if editor.mode().is_full() {
1421 editor
1422 .buffer()
1423 .read(cx)
1424 .as_singleton()
1425 .map(|buffer| buffer.downgrade())
1426 } else {
1427 None
1428 }
1429 }
1430
1431 fn register_editor(
1432 &mut self,
1433 workspace: WeakEntity<Workspace>,
1434 buffer: WeakEntity<Buffer>,
1435 editor: Entity<Editor>,
1436 window: &mut Window,
1437 cx: &mut Context<Self>,
1438 ) {
1439 let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) else {
1440 return;
1441 };
1442
1443 let weak_editor = editor.downgrade();
1444
1445 workspace_thread
1446 .singleton_editors
1447 .entry(buffer.clone())
1448 .or_default()
1449 .entry(weak_editor.clone())
1450 .or_insert_with(|| {
1451 let workspace = workspace.clone();
1452 cx.observe_release(&editor, move |this, _, _cx| {
1453 let Some(active_thread) = this.workspace_threads.get_mut(&workspace) else {
1454 return;
1455 };
1456
1457 if let Entry::Occupied(mut entry) =
1458 active_thread.singleton_editors.entry(buffer)
1459 {
1460 let set = entry.get_mut();
1461 set.remove(&weak_editor);
1462
1463 if set.is_empty() {
1464 entry.remove();
1465 }
1466 }
1467 })
1468 });
1469
1470 self.update_reviewing_editors(&workspace, window, cx);
1471 }
1472
1473 fn update_reviewing_editors(
1474 &mut self,
1475 workspace: &WeakEntity<Workspace>,
1476 window: &mut Window,
1477 cx: &mut Context<Self>,
1478 ) {
1479 if !AssistantSettings::get_global(cx).single_file_review {
1480 for (editor, _) in self.reviewing_editors.drain() {
1481 editor
1482 .update(cx, |editor, cx| editor.end_temporary_diff_override(cx))
1483 .ok();
1484 }
1485 return;
1486 }
1487
1488 let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) else {
1489 return;
1490 };
1491
1492 let Some(thread) = workspace_thread.thread.upgrade() else {
1493 return;
1494 };
1495
1496 let action_log = thread.read(cx).action_log();
1497 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1498
1499 let mut unaffected = self.reviewing_editors.clone();
1500
1501 for (buffer, diff_handle) in changed_buffers {
1502 if buffer.read(cx).file().is_none() {
1503 continue;
1504 }
1505
1506 let Some(buffer_editors) = workspace_thread.singleton_editors.get(&buffer.downgrade())
1507 else {
1508 continue;
1509 };
1510
1511 for (weak_editor, _) in buffer_editors {
1512 let Some(editor) = weak_editor.upgrade() else {
1513 continue;
1514 };
1515
1516 let multibuffer = editor.read(cx).buffer().clone();
1517 multibuffer.update(cx, |multibuffer, cx| {
1518 multibuffer.add_diff(diff_handle.clone(), cx);
1519 });
1520
1521 let new_state = if thread.read(cx).is_generating() {
1522 EditorState::Generating
1523 } else {
1524 EditorState::Reviewing
1525 };
1526
1527 let previous_state = self
1528 .reviewing_editors
1529 .insert(weak_editor.clone(), new_state.clone());
1530
1531 if previous_state.is_none() {
1532 editor.update(cx, |editor, cx| {
1533 editor.start_temporary_diff_override();
1534 editor.set_render_diff_hunk_controls(diff_hunk_controls(&thread), cx);
1535 editor.set_expand_all_diff_hunks(cx);
1536 editor.register_addon(EditorAgentDiffAddon);
1537 });
1538 } else {
1539 unaffected.remove(&weak_editor);
1540 }
1541
1542 if new_state == EditorState::Reviewing && previous_state != Some(new_state) {
1543 // Jump to first hunk when we enter review mode
1544 editor.update(cx, |editor, cx| {
1545 let snapshot = multibuffer.read(cx).snapshot(cx);
1546 if let Some(first_hunk) = snapshot.diff_hunks().next() {
1547 let first_hunk_start = first_hunk.multi_buffer_range().start;
1548
1549 editor.change_selections(
1550 Some(Autoscroll::center()),
1551 window,
1552 cx,
1553 |selections| {
1554 selections.select_ranges([first_hunk_start..first_hunk_start])
1555 },
1556 );
1557 }
1558 });
1559 }
1560 }
1561 }
1562
1563 // Remove editors from this workspace that are no longer under review
1564 for (editor, _) in unaffected {
1565 // Note: We could avoid this check by storing `reviewing_editors` by Workspace,
1566 // but that would add another lookup in `AgentDiff::editor_state`
1567 // which gets called much more frequently.
1568 let in_workspace = editor
1569 .read_with(cx, |editor, _cx| editor.workspace())
1570 .ok()
1571 .flatten()
1572 .map_or(false, |editor_workspace| {
1573 editor_workspace.entity_id() == workspace.entity_id()
1574 });
1575
1576 if in_workspace {
1577 editor
1578 .update(cx, |editor, cx| editor.end_temporary_diff_override(cx))
1579 .ok();
1580 self.reviewing_editors.remove(&editor);
1581 }
1582 }
1583
1584 cx.notify();
1585 }
1586
1587 fn editor_state(&self, editor: &WeakEntity<Editor>) -> EditorState {
1588 self.reviewing_editors
1589 .get(&editor)
1590 .cloned()
1591 .unwrap_or(EditorState::Idle)
1592 }
1593
1594 fn deploy_pane_from_editor(&self, editor: &Entity<Editor>, window: &mut Window, cx: &mut App) {
1595 let Some(workspace) = editor.read(cx).workspace() else {
1596 return;
1597 };
1598
1599 let Some(WorkspaceThread { thread, .. }) =
1600 self.workspace_threads.get(&workspace.downgrade())
1601 else {
1602 return;
1603 };
1604
1605 let Some(thread) = thread.upgrade() else {
1606 return;
1607 };
1608
1609 AgentDiffPane::deploy(thread, workspace.downgrade(), window, cx).log_err();
1610 }
1611
1612 fn keep_all(
1613 editor: &Entity<Editor>,
1614 thread: &Entity<Thread>,
1615 window: &mut Window,
1616 cx: &mut App,
1617 ) -> PostReviewState {
1618 editor.update(cx, |editor, cx| {
1619 let snapshot = editor.buffer().read(cx).snapshot(cx);
1620 keep_edits_in_ranges(
1621 editor,
1622 &snapshot,
1623 thread,
1624 vec![editor::Anchor::min()..editor::Anchor::max()],
1625 window,
1626 cx,
1627 );
1628 });
1629 PostReviewState::AllReviewed
1630 }
1631
1632 fn reject_all(
1633 editor: &Entity<Editor>,
1634 thread: &Entity<Thread>,
1635 window: &mut Window,
1636 cx: &mut App,
1637 ) -> PostReviewState {
1638 editor.update(cx, |editor, cx| {
1639 let snapshot = editor.buffer().read(cx).snapshot(cx);
1640 reject_edits_in_ranges(
1641 editor,
1642 &snapshot,
1643 thread,
1644 vec![editor::Anchor::min()..editor::Anchor::max()],
1645 window,
1646 cx,
1647 );
1648 });
1649 PostReviewState::AllReviewed
1650 }
1651
1652 fn keep(
1653 editor: &Entity<Editor>,
1654 thread: &Entity<Thread>,
1655 window: &mut Window,
1656 cx: &mut App,
1657 ) -> PostReviewState {
1658 editor.update(cx, |editor, cx| {
1659 let snapshot = editor.buffer().read(cx).snapshot(cx);
1660 keep_edits_in_selection(editor, &snapshot, thread, window, cx);
1661 Self::post_review_state(&snapshot)
1662 })
1663 }
1664
1665 fn reject(
1666 editor: &Entity<Editor>,
1667 thread: &Entity<Thread>,
1668 window: &mut Window,
1669 cx: &mut App,
1670 ) -> PostReviewState {
1671 editor.update(cx, |editor, cx| {
1672 let snapshot = editor.buffer().read(cx).snapshot(cx);
1673 reject_edits_in_selection(editor, &snapshot, thread, window, cx);
1674 Self::post_review_state(&snapshot)
1675 })
1676 }
1677
1678 fn post_review_state(snapshot: &MultiBufferSnapshot) -> PostReviewState {
1679 for (i, _) in snapshot.diff_hunks().enumerate() {
1680 if i > 0 {
1681 return PostReviewState::Pending;
1682 }
1683 }
1684 PostReviewState::AllReviewed
1685 }
1686
1687 fn review_in_active_editor(
1688 &mut self,
1689 workspace: &mut Workspace,
1690 review: impl Fn(&Entity<Editor>, &Entity<Thread>, &mut Window, &mut App) -> PostReviewState,
1691 window: &mut Window,
1692 cx: &mut Context<Self>,
1693 ) -> Option<Task<Result<()>>> {
1694 let active_item = workspace.active_item(cx)?;
1695 let editor = active_item.act_as::<Editor>(cx)?;
1696
1697 if !matches!(
1698 self.editor_state(&editor.downgrade()),
1699 EditorState::Reviewing
1700 ) {
1701 return None;
1702 }
1703
1704 let WorkspaceThread { thread, .. } =
1705 self.workspace_threads.get(&workspace.weak_handle())?;
1706
1707 let thread = thread.upgrade()?;
1708
1709 if let PostReviewState::AllReviewed = review(&editor, &thread, window, cx) {
1710 if let Some(curr_buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
1711 let changed_buffers = thread.read(cx).action_log().read(cx).changed_buffers(cx);
1712
1713 let mut keys = changed_buffers.keys().cycle();
1714 keys.find(|k| *k == &curr_buffer);
1715 let next_project_path = keys
1716 .next()
1717 .filter(|k| *k != &curr_buffer)
1718 .and_then(|after| after.read(cx).project_path(cx));
1719
1720 if let Some(path) = next_project_path {
1721 let task = workspace.open_path(path, None, true, window, cx);
1722 let task = cx.spawn(async move |_, _cx| task.await.map(|_| ()));
1723 return Some(task);
1724 }
1725 }
1726 }
1727
1728 return Some(Task::ready(Ok(())));
1729 }
1730}
1731
1732enum PostReviewState {
1733 AllReviewed,
1734 Pending,
1735}
1736
1737pub struct EditorAgentDiffAddon;
1738
1739impl editor::Addon for EditorAgentDiffAddon {
1740 fn to_any(&self) -> &dyn std::any::Any {
1741 self
1742 }
1743
1744 fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
1745 key_context.add("agent_diff");
1746 key_context.add("editor_agent_diff");
1747 }
1748}
1749
1750#[cfg(test)]
1751mod tests {
1752 use super::*;
1753 use crate::{Keep, ThreadStore, thread_store};
1754 use assistant_settings::AssistantSettings;
1755 use assistant_tool::ToolWorkingSet;
1756 use context_server::ContextServerSettings;
1757 use editor::EditorSettings;
1758 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
1759 use project::{FakeFs, Project};
1760 use prompt_store::PromptBuilder;
1761 use serde_json::json;
1762 use settings::{Settings, SettingsStore};
1763 use std::sync::Arc;
1764 use theme::ThemeSettings;
1765 use util::path;
1766
1767 #[gpui::test]
1768 async fn test_multibuffer_agent_diff(cx: &mut TestAppContext) {
1769 cx.update(|cx| {
1770 let settings_store = SettingsStore::test(cx);
1771 cx.set_global(settings_store);
1772 language::init(cx);
1773 Project::init_settings(cx);
1774 AssistantSettings::register(cx);
1775 prompt_store::init(cx);
1776 thread_store::init(cx);
1777 workspace::init_settings(cx);
1778 ThemeSettings::register(cx);
1779 ContextServerSettings::register(cx);
1780 EditorSettings::register(cx);
1781 language_model::init_settings(cx);
1782 });
1783
1784 let fs = FakeFs::new(cx.executor());
1785 fs.insert_tree(
1786 path!("/test"),
1787 json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1788 )
1789 .await;
1790 let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1791 let buffer_path = project
1792 .read_with(cx, |project, cx| {
1793 project.find_project_path("test/file1", cx)
1794 })
1795 .unwrap();
1796
1797 let prompt_store = None;
1798 let thread_store = cx
1799 .update(|cx| {
1800 ThreadStore::load(
1801 project.clone(),
1802 cx.new(|_| ToolWorkingSet::default()),
1803 prompt_store,
1804 Arc::new(PromptBuilder::new(None).unwrap()),
1805 cx,
1806 )
1807 })
1808 .await
1809 .unwrap();
1810 let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
1811 let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
1812
1813 let (workspace, cx) =
1814 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1815 let agent_diff = cx.new_window_entity(|window, cx| {
1816 AgentDiffPane::new(thread.clone(), workspace.downgrade(), window, cx)
1817 });
1818 let editor = agent_diff.read_with(cx, |diff, _cx| diff.editor.clone());
1819
1820 let buffer = project
1821 .update(cx, |project, cx| project.open_buffer(buffer_path, cx))
1822 .await
1823 .unwrap();
1824 cx.update(|_, cx| {
1825 action_log.update(cx, |log, cx| log.track_buffer(buffer.clone(), cx));
1826 buffer.update(cx, |buffer, cx| {
1827 buffer
1828 .edit(
1829 [
1830 (Point::new(1, 1)..Point::new(1, 2), "E"),
1831 (Point::new(3, 2)..Point::new(3, 3), "L"),
1832 (Point::new(5, 0)..Point::new(5, 1), "P"),
1833 (Point::new(7, 1)..Point::new(7, 2), "W"),
1834 ],
1835 None,
1836 cx,
1837 )
1838 .unwrap()
1839 });
1840 action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
1841 });
1842 cx.run_until_parked();
1843
1844 // When opening the assistant diff, the cursor is positioned on the first hunk.
1845 assert_eq!(
1846 editor.read_with(cx, |editor, cx| editor.text(cx)),
1847 "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1848 );
1849 assert_eq!(
1850 editor
1851 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1852 .range(),
1853 Point::new(1, 0)..Point::new(1, 0)
1854 );
1855
1856 // After keeping a hunk, the cursor should be positioned on the second hunk.
1857 agent_diff.update_in(cx, |diff, window, cx| diff.keep(&Keep, window, cx));
1858 cx.run_until_parked();
1859 assert_eq!(
1860 editor.read_with(cx, |editor, cx| editor.text(cx)),
1861 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1862 );
1863 assert_eq!(
1864 editor
1865 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1866 .range(),
1867 Point::new(3, 0)..Point::new(3, 0)
1868 );
1869
1870 // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
1871 editor.update_in(cx, |editor, window, cx| {
1872 editor.change_selections(None, window, cx, |selections| {
1873 selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
1874 });
1875 });
1876 agent_diff.update_in(cx, |diff, window, cx| {
1877 diff.reject(&crate::Reject, window, cx)
1878 });
1879 cx.run_until_parked();
1880 assert_eq!(
1881 editor.read_with(cx, |editor, cx| editor.text(cx)),
1882 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
1883 );
1884 assert_eq!(
1885 editor
1886 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1887 .range(),
1888 Point::new(3, 0)..Point::new(3, 0)
1889 );
1890
1891 // Keeping a range that doesn't intersect the current selection doesn't move it.
1892 agent_diff.update_in(cx, |_diff, window, cx| {
1893 let position = editor
1894 .read(cx)
1895 .buffer()
1896 .read(cx)
1897 .read(cx)
1898 .anchor_before(Point::new(7, 0));
1899 editor.update(cx, |editor, cx| {
1900 let snapshot = editor.buffer().read(cx).snapshot(cx);
1901 keep_edits_in_ranges(
1902 editor,
1903 &snapshot,
1904 &thread,
1905 vec![position..position],
1906 window,
1907 cx,
1908 )
1909 });
1910 });
1911 cx.run_until_parked();
1912 assert_eq!(
1913 editor.read_with(cx, |editor, cx| editor.text(cx)),
1914 "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
1915 );
1916 assert_eq!(
1917 editor
1918 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1919 .range(),
1920 Point::new(3, 0)..Point::new(3, 0)
1921 );
1922 }
1923
1924 #[gpui::test]
1925 async fn test_singleton_agent_diff(cx: &mut TestAppContext) {
1926 cx.update(|cx| {
1927 let settings_store = SettingsStore::test(cx);
1928 cx.set_global(settings_store);
1929 language::init(cx);
1930 Project::init_settings(cx);
1931 AssistantSettings::register(cx);
1932 prompt_store::init(cx);
1933 thread_store::init(cx);
1934 workspace::init_settings(cx);
1935 ThemeSettings::register(cx);
1936 ContextServerSettings::register(cx);
1937 EditorSettings::register(cx);
1938 language_model::init_settings(cx);
1939 workspace::register_project_item::<Editor>(cx);
1940 });
1941
1942 let fs = FakeFs::new(cx.executor());
1943 fs.insert_tree(
1944 path!("/test"),
1945 json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1946 )
1947 .await;
1948 fs.insert_tree(path!("/test"), json!({"file2": "abc\ndef\nghi"}))
1949 .await;
1950
1951 let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1952 let buffer_path1 = project
1953 .read_with(cx, |project, cx| {
1954 project.find_project_path("test/file1", cx)
1955 })
1956 .unwrap();
1957 let buffer_path2 = project
1958 .read_with(cx, |project, cx| {
1959 project.find_project_path("test/file2", cx)
1960 })
1961 .unwrap();
1962
1963 let prompt_store = None;
1964 let thread_store = cx
1965 .update(|cx| {
1966 ThreadStore::load(
1967 project.clone(),
1968 cx.new(|_| ToolWorkingSet::default()),
1969 prompt_store,
1970 Arc::new(PromptBuilder::new(None).unwrap()),
1971 cx,
1972 )
1973 })
1974 .await
1975 .unwrap();
1976 let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
1977 let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
1978
1979 let (workspace, cx) =
1980 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1981
1982 // Add the diff toolbar to the active pane
1983 let diff_toolbar = cx.new_window_entity(|_, cx| AgentDiffToolbar::new(cx));
1984
1985 workspace.update_in(cx, {
1986 let diff_toolbar = diff_toolbar.clone();
1987
1988 move |workspace, window, cx| {
1989 workspace.active_pane().update(cx, |pane, cx| {
1990 pane.toolbar().update(cx, |toolbar, cx| {
1991 toolbar.add_item(diff_toolbar, window, cx);
1992 });
1993 })
1994 }
1995 });
1996
1997 // Set the active thread
1998 cx.update(|window, cx| {
1999 AgentDiff::set_active_thread(&workspace.downgrade(), &thread, window, cx)
2000 });
2001
2002 let buffer1 = project
2003 .update(cx, |project, cx| {
2004 project.open_buffer(buffer_path1.clone(), cx)
2005 })
2006 .await
2007 .unwrap();
2008 let buffer2 = project
2009 .update(cx, |project, cx| {
2010 project.open_buffer(buffer_path2.clone(), cx)
2011 })
2012 .await
2013 .unwrap();
2014
2015 // Open an editor for buffer1
2016 let editor1 = cx.new_window_entity(|window, cx| {
2017 Editor::for_buffer(buffer1.clone(), Some(project.clone()), window, cx)
2018 });
2019
2020 workspace.update_in(cx, |workspace, window, cx| {
2021 workspace.add_item_to_active_pane(Box::new(editor1.clone()), None, true, window, cx);
2022 });
2023 cx.run_until_parked();
2024
2025 // Toolbar knows about the current editor, but it's hidden since there are no changes yet
2026 assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2027 toolbar.active_item,
2028 Some(AgentDiffToolbarItem::Editor {
2029 state: EditorState::Idle,
2030 ..
2031 })
2032 )));
2033 assert_eq!(
2034 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2035 ToolbarItemLocation::Hidden
2036 );
2037
2038 // Make changes
2039 cx.update(|_, cx| {
2040 action_log.update(cx, |log, cx| log.track_buffer(buffer1.clone(), cx));
2041 buffer1.update(cx, |buffer, cx| {
2042 buffer
2043 .edit(
2044 [
2045 (Point::new(1, 1)..Point::new(1, 2), "E"),
2046 (Point::new(3, 2)..Point::new(3, 3), "L"),
2047 (Point::new(5, 0)..Point::new(5, 1), "P"),
2048 (Point::new(7, 1)..Point::new(7, 2), "W"),
2049 ],
2050 None,
2051 cx,
2052 )
2053 .unwrap()
2054 });
2055 action_log.update(cx, |log, cx| log.buffer_edited(buffer1.clone(), cx));
2056
2057 action_log.update(cx, |log, cx| log.track_buffer(buffer2.clone(), cx));
2058 buffer2.update(cx, |buffer, cx| {
2059 buffer
2060 .edit(
2061 [
2062 (Point::new(0, 0)..Point::new(0, 1), "A"),
2063 (Point::new(2, 1)..Point::new(2, 2), "H"),
2064 ],
2065 None,
2066 cx,
2067 )
2068 .unwrap();
2069 });
2070 action_log.update(cx, |log, cx| log.buffer_edited(buffer2.clone(), cx));
2071 });
2072 cx.run_until_parked();
2073
2074 // The already opened editor displays the diff and the cursor is at the first hunk
2075 assert_eq!(
2076 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2077 "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2078 );
2079 assert_eq!(
2080 editor1
2081 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2082 .range(),
2083 Point::new(1, 0)..Point::new(1, 0)
2084 );
2085
2086 // The toolbar is displayed in the right state
2087 assert_eq!(
2088 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2089 ToolbarItemLocation::PrimaryLeft
2090 );
2091 assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2092 toolbar.active_item,
2093 Some(AgentDiffToolbarItem::Editor {
2094 state: EditorState::Reviewing,
2095 ..
2096 })
2097 )));
2098
2099 // The toolbar respects its setting
2100 override_toolbar_agent_review_setting(false, cx);
2101 assert_eq!(
2102 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2103 ToolbarItemLocation::Hidden
2104 );
2105 override_toolbar_agent_review_setting(true, cx);
2106 assert_eq!(
2107 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2108 ToolbarItemLocation::PrimaryLeft
2109 );
2110
2111 // After keeping a hunk, the cursor should be positioned on the second hunk.
2112 workspace.update(cx, |_, cx| {
2113 cx.dispatch_action(&Keep);
2114 });
2115 cx.run_until_parked();
2116 assert_eq!(
2117 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2118 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2119 );
2120 assert_eq!(
2121 editor1
2122 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2123 .range(),
2124 Point::new(3, 0)..Point::new(3, 0)
2125 );
2126
2127 // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
2128 editor1.update_in(cx, |editor, window, cx| {
2129 editor.change_selections(None, window, cx, |selections| {
2130 selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
2131 });
2132 });
2133 workspace.update(cx, |_, cx| {
2134 cx.dispatch_action(&Reject);
2135 });
2136 cx.run_until_parked();
2137 assert_eq!(
2138 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2139 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
2140 );
2141 assert_eq!(
2142 editor1
2143 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2144 .range(),
2145 Point::new(3, 0)..Point::new(3, 0)
2146 );
2147
2148 // Keeping a range that doesn't intersect the current selection doesn't move it.
2149 editor1.update_in(cx, |editor, window, cx| {
2150 let buffer = editor.buffer().read(cx);
2151 let position = buffer.read(cx).anchor_before(Point::new(7, 0));
2152 let snapshot = buffer.snapshot(cx);
2153 keep_edits_in_ranges(
2154 editor,
2155 &snapshot,
2156 &thread,
2157 vec![position..position],
2158 window,
2159 cx,
2160 )
2161 });
2162 cx.run_until_parked();
2163 assert_eq!(
2164 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2165 "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
2166 );
2167 assert_eq!(
2168 editor1
2169 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2170 .range(),
2171 Point::new(3, 0)..Point::new(3, 0)
2172 );
2173
2174 // Reviewing the last change opens the next changed buffer
2175 workspace
2176 .update_in(cx, |workspace, window, cx| {
2177 AgentDiff::global(cx).update(cx, |agent_diff, cx| {
2178 agent_diff.review_in_active_editor(workspace, AgentDiff::keep, window, cx)
2179 })
2180 })
2181 .unwrap()
2182 .await
2183 .unwrap();
2184
2185 cx.run_until_parked();
2186
2187 let editor2 = workspace.update(cx, |workspace, cx| {
2188 workspace.active_item_as::<Editor>(cx).unwrap()
2189 });
2190
2191 let editor2_path = editor2
2192 .read_with(cx, |editor, cx| editor.project_path(cx))
2193 .unwrap();
2194 assert_eq!(editor2_path, buffer_path2);
2195
2196 assert_eq!(
2197 editor2.read_with(cx, |editor, cx| editor.text(cx)),
2198 "abc\nAbc\ndef\nghi\ngHi"
2199 );
2200 assert_eq!(
2201 editor2
2202 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2203 .range(),
2204 Point::new(0, 0)..Point::new(0, 0)
2205 );
2206
2207 // Editor 1 toolbar is hidden since all changes have been reviewed
2208 workspace.update_in(cx, |workspace, window, cx| {
2209 workspace.activate_item(&editor1, true, true, window, cx)
2210 });
2211
2212 assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2213 toolbar.active_item,
2214 Some(AgentDiffToolbarItem::Editor {
2215 state: EditorState::Idle,
2216 ..
2217 })
2218 )));
2219 assert_eq!(
2220 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2221 ToolbarItemLocation::Hidden
2222 );
2223 }
2224
2225 fn override_toolbar_agent_review_setting(active: bool, cx: &mut VisualTestContext) {
2226 cx.update(|_window, cx| {
2227 SettingsStore::update_global(cx, |store, _cx| {
2228 let mut editor_settings = store.get::<EditorSettings>(None).clone();
2229 editor_settings.toolbar.agent_review = active;
2230 store.override_global(editor_settings);
2231 })
2232 });
2233 cx.run_until_parked();
2234 }
2235}