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::{Divider, 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::PrimaryRight
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 generating_label = div()
994 .w(rems_from_px(110.)) // Arbitrary size so the label doesn't dance around
995 .child(AnimatedLabel::new("Generating"))
996 .into_any();
997
998 let Some(active_item) = self.active_item.as_ref() else {
999 return Empty.into_any();
1000 };
1001
1002 match active_item {
1003 AgentDiffToolbarItem::Editor { editor, state, .. } => {
1004 let Some(editor) = editor.upgrade() else {
1005 return Empty.into_any();
1006 };
1007
1008 let editor_focus_handle = editor.read(cx).focus_handle(cx);
1009
1010 let content = match state {
1011 EditorState::Idle => return Empty.into_any(),
1012 EditorState::Generating => vec![generating_label],
1013 EditorState::Reviewing => vec![
1014 h_flex()
1015 .child(
1016 IconButton::new("hunk-up", IconName::ArrowUp)
1017 .icon_size(IconSize::Small)
1018 .tooltip(Tooltip::for_action_title_in(
1019 "Previous Hunk",
1020 &GoToPreviousHunk,
1021 &editor_focus_handle,
1022 ))
1023 .on_click({
1024 let editor_focus_handle = editor_focus_handle.clone();
1025 move |_, window, cx| {
1026 editor_focus_handle.dispatch_action(
1027 &GoToPreviousHunk,
1028 window,
1029 cx,
1030 );
1031 }
1032 }),
1033 )
1034 .child(
1035 IconButton::new("hunk-down", IconName::ArrowDown)
1036 .icon_size(IconSize::Small)
1037 .tooltip(Tooltip::for_action_title_in(
1038 "Next Hunk",
1039 &GoToHunk,
1040 &editor_focus_handle,
1041 ))
1042 .on_click({
1043 let editor_focus_handle = editor_focus_handle.clone();
1044 move |_, window, cx| {
1045 editor_focus_handle
1046 .dispatch_action(&GoToHunk, window, cx);
1047 }
1048 }),
1049 )
1050 .into_any(),
1051 Divider::vertical().into_any_element(),
1052 h_flex()
1053 .gap_0p5()
1054 .child(
1055 Button::new("reject-all", "Reject All")
1056 .key_binding({
1057 KeyBinding::for_action_in(
1058 &RejectAll,
1059 &editor_focus_handle,
1060 window,
1061 cx,
1062 )
1063 .map(|kb| kb.size(rems_from_px(12.)))
1064 })
1065 .on_click(cx.listener(|this, _, window, cx| {
1066 this.dispatch_action(&RejectAll, window, cx)
1067 })),
1068 )
1069 .child(
1070 Button::new("keep-all", "Keep All")
1071 .key_binding({
1072 KeyBinding::for_action_in(
1073 &KeepAll,
1074 &editor_focus_handle,
1075 window,
1076 cx,
1077 )
1078 .map(|kb| kb.size(rems_from_px(12.)))
1079 })
1080 .on_click(cx.listener(|this, _, window, cx| {
1081 this.dispatch_action(&KeepAll, window, cx)
1082 })),
1083 )
1084 .into_any(),
1085 Divider::vertical().into_any_element(),
1086 ],
1087 };
1088
1089 h_flex()
1090 .track_focus(&editor_focus_handle)
1091 .size_full()
1092 .child(
1093 h_flex()
1094 .py(DynamicSpacing::Base08.rems(cx))
1095 .px_2()
1096 .gap_1()
1097 .children(content)
1098 .when_some(editor.read(cx).workspace(), |this, _workspace| {
1099 this.child(
1100 IconButton::new("review", IconName::ListCollapse)
1101 .icon_size(IconSize::Small)
1102 .tooltip(Tooltip::for_action_title_in(
1103 "Review All Files",
1104 &OpenAgentDiff,
1105 &editor_focus_handle,
1106 ))
1107 .on_click({
1108 cx.listener(move |this, _, window, cx| {
1109 this.dispatch_action(&OpenAgentDiff, window, cx);
1110 })
1111 }),
1112 )
1113 }),
1114 )
1115 .child(vertical_divider())
1116 .on_action({
1117 let editor = editor.clone();
1118 move |_action: &OpenAgentDiff, window, cx| {
1119 AgentDiff::global(cx).update(cx, |agent_diff, cx| {
1120 agent_diff.deploy_pane_from_editor(&editor, window, cx);
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().px_2().child(generating_label).into_any();
1134 }
1135
1136 let is_empty = agent_diff.read(cx).multibuffer.read(cx).is_empty();
1137 if is_empty {
1138 return Empty.into_any();
1139 }
1140
1141 let focus_handle = agent_diff.focus_handle(cx);
1142
1143 h_group_xl()
1144 .px_2()
1145 .items_center()
1146 .flex_wrap()
1147 .child(
1148 h_group_sm()
1149 .child(
1150 Button::new("reject-all", "Reject All")
1151 .key_binding({
1152 KeyBinding::for_action_in(
1153 &RejectAll,
1154 &focus_handle,
1155 window,
1156 cx,
1157 )
1158 .map(|kb| kb.size(rems_from_px(12.)))
1159 })
1160 .on_click(cx.listener(|this, _, window, cx| {
1161 this.dispatch_action(&RejectAll, window, cx)
1162 })),
1163 )
1164 .child(
1165 Button::new("keep-all", "Keep All")
1166 .key_binding({
1167 KeyBinding::for_action_in(
1168 &KeepAll,
1169 &focus_handle,
1170 window,
1171 cx,
1172 )
1173 .map(|kb| kb.size(rems_from_px(12.)))
1174 })
1175 .on_click(cx.listener(|this, _, window, cx| {
1176 this.dispatch_action(&KeepAll, window, cx)
1177 })),
1178 ),
1179 )
1180 .into_any()
1181 }
1182 }
1183 }
1184}
1185
1186#[derive(Default)]
1187pub struct AgentDiff {
1188 reviewing_editors: HashMap<WeakEntity<Editor>, EditorState>,
1189 workspace_threads: HashMap<WeakEntity<Workspace>, WorkspaceThread>,
1190}
1191
1192#[derive(Clone, Debug, PartialEq, Eq)]
1193pub enum EditorState {
1194 Idle,
1195 Reviewing,
1196 Generating,
1197}
1198
1199struct WorkspaceThread {
1200 thread: WeakEntity<Thread>,
1201 _thread_subscriptions: [Subscription; 2],
1202 singleton_editors: HashMap<WeakEntity<Buffer>, HashMap<WeakEntity<Editor>, Subscription>>,
1203 _settings_subscription: Subscription,
1204 _workspace_subscription: Option<Subscription>,
1205}
1206
1207struct AgentDiffGlobal(Entity<AgentDiff>);
1208
1209impl Global for AgentDiffGlobal {}
1210
1211impl AgentDiff {
1212 fn global(cx: &mut App) -> Entity<Self> {
1213 cx.try_global::<AgentDiffGlobal>()
1214 .map(|global| global.0.clone())
1215 .unwrap_or_else(|| {
1216 let entity = cx.new(|_cx| Self::default());
1217 let global = AgentDiffGlobal(entity.clone());
1218 cx.set_global(global);
1219 entity.clone()
1220 })
1221 }
1222
1223 pub fn set_active_thread(
1224 workspace: &WeakEntity<Workspace>,
1225 thread: &Entity<Thread>,
1226 window: &mut Window,
1227 cx: &mut App,
1228 ) {
1229 Self::global(cx).update(cx, |this, cx| {
1230 this.register_active_thread_impl(workspace, thread, window, cx);
1231 });
1232 }
1233
1234 fn register_active_thread_impl(
1235 &mut self,
1236 workspace: &WeakEntity<Workspace>,
1237 thread: &Entity<Thread>,
1238 window: &mut Window,
1239 cx: &mut Context<Self>,
1240 ) {
1241 let action_log = thread.read(cx).action_log().clone();
1242
1243 let action_log_subscription = cx.observe_in(&action_log, window, {
1244 let workspace = workspace.clone();
1245 move |this, _action_log, window, cx| {
1246 this.update_reviewing_editors(&workspace, window, cx);
1247 }
1248 });
1249
1250 let thread_subscription = cx.subscribe_in(&thread, window, {
1251 let workspace = workspace.clone();
1252 move |this, _thread, event, window, cx| {
1253 this.handle_thread_event(&workspace, event, window, cx)
1254 }
1255 });
1256
1257 if let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) {
1258 // replace thread and action log subscription, but keep editors
1259 workspace_thread.thread = thread.downgrade();
1260 workspace_thread._thread_subscriptions = [action_log_subscription, thread_subscription];
1261 self.update_reviewing_editors(&workspace, window, cx);
1262 return;
1263 }
1264
1265 let settings_subscription = cx.observe_global_in::<SettingsStore>(window, {
1266 let workspace = workspace.clone();
1267 let mut was_active = AssistantSettings::get_global(cx).single_file_review;
1268 move |this, window, cx| {
1269 let is_active = AssistantSettings::get_global(cx).single_file_review;
1270 if was_active != is_active {
1271 was_active = is_active;
1272 this.update_reviewing_editors(&workspace, window, cx);
1273 }
1274 }
1275 });
1276
1277 let workspace_subscription = workspace
1278 .upgrade()
1279 .map(|workspace| cx.subscribe_in(&workspace, window, Self::handle_workspace_event));
1280
1281 self.workspace_threads.insert(
1282 workspace.clone(),
1283 WorkspaceThread {
1284 thread: thread.downgrade(),
1285 _thread_subscriptions: [action_log_subscription, thread_subscription],
1286 singleton_editors: HashMap::default(),
1287 _settings_subscription: settings_subscription,
1288 _workspace_subscription: workspace_subscription,
1289 },
1290 );
1291
1292 let workspace = workspace.clone();
1293 cx.defer_in(window, move |this, window, cx| {
1294 if let Some(workspace) = workspace.upgrade() {
1295 this.register_workspace(workspace, window, cx);
1296 }
1297 });
1298 }
1299
1300 fn register_workspace(
1301 &mut self,
1302 workspace: Entity<Workspace>,
1303 window: &mut Window,
1304 cx: &mut Context<Self>,
1305 ) {
1306 let agent_diff = cx.entity();
1307
1308 let editors = workspace.update(cx, |workspace, cx| {
1309 let agent_diff = agent_diff.clone();
1310
1311 Self::register_review_action::<Keep>(workspace, Self::keep, &agent_diff);
1312 Self::register_review_action::<Reject>(workspace, Self::reject, &agent_diff);
1313 Self::register_review_action::<KeepAll>(workspace, Self::keep_all, &agent_diff);
1314 Self::register_review_action::<RejectAll>(workspace, Self::reject_all, &agent_diff);
1315
1316 workspace.items_of_type(cx).collect::<Vec<_>>()
1317 });
1318
1319 let weak_workspace = workspace.downgrade();
1320
1321 for editor in editors {
1322 if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1323 self.register_editor(weak_workspace.clone(), buffer, editor, window, cx);
1324 };
1325 }
1326
1327 self.update_reviewing_editors(&weak_workspace, window, cx);
1328 }
1329
1330 fn register_review_action<T: Action>(
1331 workspace: &mut Workspace,
1332 review: impl Fn(&Entity<Editor>, &Entity<Thread>, &mut Window, &mut App) -> PostReviewState
1333 + 'static,
1334 this: &Entity<AgentDiff>,
1335 ) {
1336 let this = this.clone();
1337 workspace.register_action(move |workspace, _: &T, window, cx| {
1338 let review = &review;
1339 let task = this.update(cx, |this, cx| {
1340 this.review_in_active_editor(workspace, review, window, cx)
1341 });
1342
1343 if let Some(task) = task {
1344 task.detach_and_log_err(cx);
1345 } else {
1346 cx.propagate();
1347 }
1348 });
1349 }
1350
1351 fn handle_thread_event(
1352 &mut self,
1353 workspace: &WeakEntity<Workspace>,
1354 event: &ThreadEvent,
1355 window: &mut Window,
1356 cx: &mut Context<Self>,
1357 ) {
1358 match event {
1359 ThreadEvent::NewRequest
1360 | ThreadEvent::Stopped(Ok(StopReason::EndTurn))
1361 | ThreadEvent::Stopped(Ok(StopReason::MaxTokens))
1362 | ThreadEvent::Stopped(Err(_))
1363 | ThreadEvent::ShowError(_)
1364 | ThreadEvent::CompletionCanceled => {
1365 self.update_reviewing_editors(workspace, window, cx);
1366 }
1367 // intentionally being exhaustive in case we add a variant we should handle
1368 ThreadEvent::Stopped(Ok(StopReason::ToolUse))
1369 | ThreadEvent::StreamedCompletion
1370 | ThreadEvent::ReceivedTextChunk
1371 | ThreadEvent::StreamedAssistantText(_, _)
1372 | ThreadEvent::StreamedAssistantThinking(_, _)
1373 | ThreadEvent::StreamedToolUse { .. }
1374 | ThreadEvent::InvalidToolInput { .. }
1375 | ThreadEvent::MessageAdded(_)
1376 | ThreadEvent::MessageEdited(_)
1377 | ThreadEvent::MessageDeleted(_)
1378 | ThreadEvent::SummaryGenerated
1379 | ThreadEvent::SummaryChanged
1380 | ThreadEvent::UsePendingTools { .. }
1381 | ThreadEvent::ToolFinished { .. }
1382 | ThreadEvent::CheckpointChanged
1383 | ThreadEvent::ToolConfirmationNeeded
1384 | ThreadEvent::CancelEditing => {}
1385 }
1386 }
1387
1388 fn handle_workspace_event(
1389 &mut self,
1390 workspace: &Entity<Workspace>,
1391 event: &workspace::Event,
1392 window: &mut Window,
1393 cx: &mut Context<Self>,
1394 ) {
1395 match event {
1396 workspace::Event::ItemAdded { item } => {
1397 if let Some(editor) = item.downcast::<Editor>() {
1398 if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1399 self.register_editor(
1400 workspace.downgrade(),
1401 buffer.clone(),
1402 editor,
1403 window,
1404 cx,
1405 );
1406 }
1407 }
1408 }
1409 _ => {}
1410 }
1411 }
1412
1413 fn full_editor_buffer(editor: &Editor, cx: &App) -> Option<WeakEntity<Buffer>> {
1414 if editor.mode().is_full() {
1415 editor
1416 .buffer()
1417 .read(cx)
1418 .as_singleton()
1419 .map(|buffer| buffer.downgrade())
1420 } else {
1421 None
1422 }
1423 }
1424
1425 fn register_editor(
1426 &mut self,
1427 workspace: WeakEntity<Workspace>,
1428 buffer: WeakEntity<Buffer>,
1429 editor: Entity<Editor>,
1430 window: &mut Window,
1431 cx: &mut Context<Self>,
1432 ) {
1433 let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) else {
1434 return;
1435 };
1436
1437 let weak_editor = editor.downgrade();
1438
1439 workspace_thread
1440 .singleton_editors
1441 .entry(buffer.clone())
1442 .or_default()
1443 .entry(weak_editor.clone())
1444 .or_insert_with(|| {
1445 let workspace = workspace.clone();
1446 cx.observe_release(&editor, move |this, _, _cx| {
1447 let Some(active_thread) = this.workspace_threads.get_mut(&workspace) else {
1448 return;
1449 };
1450
1451 if let Entry::Occupied(mut entry) =
1452 active_thread.singleton_editors.entry(buffer)
1453 {
1454 let set = entry.get_mut();
1455 set.remove(&weak_editor);
1456
1457 if set.is_empty() {
1458 entry.remove();
1459 }
1460 }
1461 })
1462 });
1463
1464 self.update_reviewing_editors(&workspace, window, cx);
1465 }
1466
1467 fn update_reviewing_editors(
1468 &mut self,
1469 workspace: &WeakEntity<Workspace>,
1470 window: &mut Window,
1471 cx: &mut Context<Self>,
1472 ) {
1473 if !AssistantSettings::get_global(cx).single_file_review {
1474 for (editor, _) in self.reviewing_editors.drain() {
1475 editor
1476 .update(cx, |editor, cx| editor.end_temporary_diff_override(cx))
1477 .ok();
1478 }
1479 return;
1480 }
1481
1482 let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) else {
1483 return;
1484 };
1485
1486 let Some(thread) = workspace_thread.thread.upgrade() else {
1487 return;
1488 };
1489
1490 let action_log = thread.read(cx).action_log();
1491 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1492
1493 let mut unaffected = self.reviewing_editors.clone();
1494
1495 for (buffer, diff_handle) in changed_buffers {
1496 if buffer.read(cx).file().is_none() {
1497 continue;
1498 }
1499
1500 let Some(buffer_editors) = workspace_thread.singleton_editors.get(&buffer.downgrade())
1501 else {
1502 continue;
1503 };
1504
1505 for (weak_editor, _) in buffer_editors {
1506 let Some(editor) = weak_editor.upgrade() else {
1507 continue;
1508 };
1509
1510 let multibuffer = editor.read(cx).buffer().clone();
1511 multibuffer.update(cx, |multibuffer, cx| {
1512 multibuffer.add_diff(diff_handle.clone(), cx);
1513 });
1514
1515 let new_state = if thread.read(cx).is_generating() {
1516 EditorState::Generating
1517 } else {
1518 EditorState::Reviewing
1519 };
1520
1521 let previous_state = self
1522 .reviewing_editors
1523 .insert(weak_editor.clone(), new_state.clone());
1524
1525 if previous_state.is_none() {
1526 editor.update(cx, |editor, cx| {
1527 editor.start_temporary_diff_override();
1528 editor.set_render_diff_hunk_controls(diff_hunk_controls(&thread), cx);
1529 editor.set_expand_all_diff_hunks(cx);
1530 editor.register_addon(EditorAgentDiffAddon);
1531 });
1532 } else {
1533 unaffected.remove(&weak_editor);
1534 }
1535
1536 if new_state == EditorState::Reviewing && previous_state != Some(new_state) {
1537 // Jump to first hunk when we enter review mode
1538 editor.update(cx, |editor, cx| {
1539 let snapshot = multibuffer.read(cx).snapshot(cx);
1540 if let Some(first_hunk) = snapshot.diff_hunks().next() {
1541 let first_hunk_start = first_hunk.multi_buffer_range().start;
1542
1543 editor.change_selections(
1544 Some(Autoscroll::center()),
1545 window,
1546 cx,
1547 |selections| {
1548 selections.select_ranges([first_hunk_start..first_hunk_start])
1549 },
1550 );
1551 }
1552 });
1553 }
1554 }
1555 }
1556
1557 // Remove editors from this workspace that are no longer under review
1558 for (editor, _) in unaffected {
1559 // Note: We could avoid this check by storing `reviewing_editors` by Workspace,
1560 // but that would add another lookup in `AgentDiff::editor_state`
1561 // which gets called much more frequently.
1562 let in_workspace = editor
1563 .read_with(cx, |editor, _cx| editor.workspace())
1564 .ok()
1565 .flatten()
1566 .map_or(false, |editor_workspace| {
1567 editor_workspace.entity_id() == workspace.entity_id()
1568 });
1569
1570 if in_workspace {
1571 editor
1572 .update(cx, |editor, cx| editor.end_temporary_diff_override(cx))
1573 .ok();
1574 self.reviewing_editors.remove(&editor);
1575 }
1576 }
1577
1578 cx.notify();
1579 }
1580
1581 fn editor_state(&self, editor: &WeakEntity<Editor>) -> EditorState {
1582 self.reviewing_editors
1583 .get(&editor)
1584 .cloned()
1585 .unwrap_or(EditorState::Idle)
1586 }
1587
1588 fn deploy_pane_from_editor(&self, editor: &Entity<Editor>, window: &mut Window, cx: &mut App) {
1589 let Some(workspace) = editor.read(cx).workspace() else {
1590 return;
1591 };
1592
1593 let Some(WorkspaceThread { thread, .. }) =
1594 self.workspace_threads.get(&workspace.downgrade())
1595 else {
1596 return;
1597 };
1598
1599 let Some(thread) = thread.upgrade() else {
1600 return;
1601 };
1602
1603 AgentDiffPane::deploy(thread, workspace.downgrade(), window, cx).log_err();
1604 }
1605
1606 fn keep_all(
1607 editor: &Entity<Editor>,
1608 thread: &Entity<Thread>,
1609 window: &mut Window,
1610 cx: &mut App,
1611 ) -> PostReviewState {
1612 editor.update(cx, |editor, cx| {
1613 let snapshot = editor.buffer().read(cx).snapshot(cx);
1614 keep_edits_in_ranges(
1615 editor,
1616 &snapshot,
1617 thread,
1618 vec![editor::Anchor::min()..editor::Anchor::max()],
1619 window,
1620 cx,
1621 );
1622 });
1623 PostReviewState::AllReviewed
1624 }
1625
1626 fn reject_all(
1627 editor: &Entity<Editor>,
1628 thread: &Entity<Thread>,
1629 window: &mut Window,
1630 cx: &mut App,
1631 ) -> PostReviewState {
1632 editor.update(cx, |editor, cx| {
1633 let snapshot = editor.buffer().read(cx).snapshot(cx);
1634 reject_edits_in_ranges(
1635 editor,
1636 &snapshot,
1637 thread,
1638 vec![editor::Anchor::min()..editor::Anchor::max()],
1639 window,
1640 cx,
1641 );
1642 });
1643 PostReviewState::AllReviewed
1644 }
1645
1646 fn keep(
1647 editor: &Entity<Editor>,
1648 thread: &Entity<Thread>,
1649 window: &mut Window,
1650 cx: &mut App,
1651 ) -> PostReviewState {
1652 editor.update(cx, |editor, cx| {
1653 let snapshot = editor.buffer().read(cx).snapshot(cx);
1654 keep_edits_in_selection(editor, &snapshot, thread, window, cx);
1655 Self::post_review_state(&snapshot)
1656 })
1657 }
1658
1659 fn reject(
1660 editor: &Entity<Editor>,
1661 thread: &Entity<Thread>,
1662 window: &mut Window,
1663 cx: &mut App,
1664 ) -> PostReviewState {
1665 editor.update(cx, |editor, cx| {
1666 let snapshot = editor.buffer().read(cx).snapshot(cx);
1667 reject_edits_in_selection(editor, &snapshot, thread, window, cx);
1668 Self::post_review_state(&snapshot)
1669 })
1670 }
1671
1672 fn post_review_state(snapshot: &MultiBufferSnapshot) -> PostReviewState {
1673 for (i, _) in snapshot.diff_hunks().enumerate() {
1674 if i > 0 {
1675 return PostReviewState::Pending;
1676 }
1677 }
1678 PostReviewState::AllReviewed
1679 }
1680
1681 fn review_in_active_editor(
1682 &mut self,
1683 workspace: &mut Workspace,
1684 review: impl Fn(&Entity<Editor>, &Entity<Thread>, &mut Window, &mut App) -> PostReviewState,
1685 window: &mut Window,
1686 cx: &mut Context<Self>,
1687 ) -> Option<Task<Result<()>>> {
1688 let active_item = workspace.active_item(cx)?;
1689 let editor = active_item.act_as::<Editor>(cx)?;
1690
1691 if !matches!(
1692 self.editor_state(&editor.downgrade()),
1693 EditorState::Reviewing
1694 ) {
1695 return None;
1696 }
1697
1698 let WorkspaceThread { thread, .. } =
1699 self.workspace_threads.get(&workspace.weak_handle())?;
1700
1701 let thread = thread.upgrade()?;
1702
1703 if let PostReviewState::AllReviewed = review(&editor, &thread, window, cx) {
1704 if let Some(curr_buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
1705 let changed_buffers = thread.read(cx).action_log().read(cx).changed_buffers(cx);
1706
1707 let mut keys = changed_buffers.keys().cycle();
1708 keys.find(|k| *k == &curr_buffer);
1709 let next_project_path = keys
1710 .next()
1711 .filter(|k| *k != &curr_buffer)
1712 .and_then(|after| after.read(cx).project_path(cx));
1713
1714 if let Some(path) = next_project_path {
1715 let task = workspace.open_path(path, None, true, window, cx);
1716 let task = cx.spawn(async move |_, _cx| task.await.map(|_| ()));
1717 return Some(task);
1718 }
1719 }
1720 }
1721
1722 return Some(Task::ready(Ok(())));
1723 }
1724}
1725
1726enum PostReviewState {
1727 AllReviewed,
1728 Pending,
1729}
1730
1731pub struct EditorAgentDiffAddon;
1732
1733impl editor::Addon for EditorAgentDiffAddon {
1734 fn to_any(&self) -> &dyn std::any::Any {
1735 self
1736 }
1737
1738 fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
1739 key_context.add("agent_diff");
1740 key_context.add("editor_agent_diff");
1741 }
1742}
1743
1744#[cfg(test)]
1745mod tests {
1746 use super::*;
1747 use crate::{Keep, ThreadStore, thread_store};
1748 use assistant_settings::AssistantSettings;
1749 use assistant_tool::ToolWorkingSet;
1750 use context_server::ContextServerSettings;
1751 use editor::EditorSettings;
1752 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
1753 use project::{FakeFs, Project};
1754 use prompt_store::PromptBuilder;
1755 use serde_json::json;
1756 use settings::{Settings, SettingsStore};
1757 use std::sync::Arc;
1758 use theme::ThemeSettings;
1759 use util::path;
1760
1761 #[gpui::test]
1762 async fn test_multibuffer_agent_diff(cx: &mut TestAppContext) {
1763 cx.update(|cx| {
1764 let settings_store = SettingsStore::test(cx);
1765 cx.set_global(settings_store);
1766 language::init(cx);
1767 Project::init_settings(cx);
1768 AssistantSettings::register(cx);
1769 prompt_store::init(cx);
1770 thread_store::init(cx);
1771 workspace::init_settings(cx);
1772 ThemeSettings::register(cx);
1773 ContextServerSettings::register(cx);
1774 EditorSettings::register(cx);
1775 language_model::init_settings(cx);
1776 });
1777
1778 let fs = FakeFs::new(cx.executor());
1779 fs.insert_tree(
1780 path!("/test"),
1781 json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1782 )
1783 .await;
1784 let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1785 let buffer_path = project
1786 .read_with(cx, |project, cx| {
1787 project.find_project_path("test/file1", cx)
1788 })
1789 .unwrap();
1790
1791 let prompt_store = None;
1792 let thread_store = cx
1793 .update(|cx| {
1794 ThreadStore::load(
1795 project.clone(),
1796 cx.new(|_| ToolWorkingSet::default()),
1797 prompt_store,
1798 Arc::new(PromptBuilder::new(None).unwrap()),
1799 cx,
1800 )
1801 })
1802 .await
1803 .unwrap();
1804 let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
1805 let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
1806
1807 let (workspace, cx) =
1808 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1809 let agent_diff = cx.new_window_entity(|window, cx| {
1810 AgentDiffPane::new(thread.clone(), workspace.downgrade(), window, cx)
1811 });
1812 let editor = agent_diff.read_with(cx, |diff, _cx| diff.editor.clone());
1813
1814 let buffer = project
1815 .update(cx, |project, cx| project.open_buffer(buffer_path, cx))
1816 .await
1817 .unwrap();
1818 cx.update(|_, cx| {
1819 action_log.update(cx, |log, cx| log.buffer_read(buffer.clone(), cx));
1820 buffer.update(cx, |buffer, cx| {
1821 buffer
1822 .edit(
1823 [
1824 (Point::new(1, 1)..Point::new(1, 2), "E"),
1825 (Point::new(3, 2)..Point::new(3, 3), "L"),
1826 (Point::new(5, 0)..Point::new(5, 1), "P"),
1827 (Point::new(7, 1)..Point::new(7, 2), "W"),
1828 ],
1829 None,
1830 cx,
1831 )
1832 .unwrap()
1833 });
1834 action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
1835 });
1836 cx.run_until_parked();
1837
1838 // When opening the assistant diff, the cursor is positioned on the first hunk.
1839 assert_eq!(
1840 editor.read_with(cx, |editor, cx| editor.text(cx)),
1841 "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1842 );
1843 assert_eq!(
1844 editor
1845 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1846 .range(),
1847 Point::new(1, 0)..Point::new(1, 0)
1848 );
1849
1850 // After keeping a hunk, the cursor should be positioned on the second hunk.
1851 agent_diff.update_in(cx, |diff, window, cx| diff.keep(&Keep, window, cx));
1852 cx.run_until_parked();
1853 assert_eq!(
1854 editor.read_with(cx, |editor, cx| editor.text(cx)),
1855 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1856 );
1857 assert_eq!(
1858 editor
1859 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1860 .range(),
1861 Point::new(3, 0)..Point::new(3, 0)
1862 );
1863
1864 // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
1865 editor.update_in(cx, |editor, window, cx| {
1866 editor.change_selections(None, window, cx, |selections| {
1867 selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
1868 });
1869 });
1870 agent_diff.update_in(cx, |diff, window, cx| {
1871 diff.reject(&crate::Reject, window, cx)
1872 });
1873 cx.run_until_parked();
1874 assert_eq!(
1875 editor.read_with(cx, |editor, cx| editor.text(cx)),
1876 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
1877 );
1878 assert_eq!(
1879 editor
1880 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1881 .range(),
1882 Point::new(3, 0)..Point::new(3, 0)
1883 );
1884
1885 // Keeping a range that doesn't intersect the current selection doesn't move it.
1886 agent_diff.update_in(cx, |_diff, window, cx| {
1887 let position = editor
1888 .read(cx)
1889 .buffer()
1890 .read(cx)
1891 .read(cx)
1892 .anchor_before(Point::new(7, 0));
1893 editor.update(cx, |editor, cx| {
1894 let snapshot = editor.buffer().read(cx).snapshot(cx);
1895 keep_edits_in_ranges(
1896 editor,
1897 &snapshot,
1898 &thread,
1899 vec![position..position],
1900 window,
1901 cx,
1902 )
1903 });
1904 });
1905 cx.run_until_parked();
1906 assert_eq!(
1907 editor.read_with(cx, |editor, cx| editor.text(cx)),
1908 "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
1909 );
1910 assert_eq!(
1911 editor
1912 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1913 .range(),
1914 Point::new(3, 0)..Point::new(3, 0)
1915 );
1916 }
1917
1918 #[gpui::test]
1919 async fn test_singleton_agent_diff(cx: &mut TestAppContext) {
1920 cx.update(|cx| {
1921 let settings_store = SettingsStore::test(cx);
1922 cx.set_global(settings_store);
1923 language::init(cx);
1924 Project::init_settings(cx);
1925 AssistantSettings::register(cx);
1926 prompt_store::init(cx);
1927 thread_store::init(cx);
1928 workspace::init_settings(cx);
1929 ThemeSettings::register(cx);
1930 ContextServerSettings::register(cx);
1931 EditorSettings::register(cx);
1932 language_model::init_settings(cx);
1933 workspace::register_project_item::<Editor>(cx);
1934 });
1935
1936 let fs = FakeFs::new(cx.executor());
1937 fs.insert_tree(
1938 path!("/test"),
1939 json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1940 )
1941 .await;
1942 fs.insert_tree(path!("/test"), json!({"file2": "abc\ndef\nghi"}))
1943 .await;
1944
1945 let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1946 let buffer_path1 = project
1947 .read_with(cx, |project, cx| {
1948 project.find_project_path("test/file1", cx)
1949 })
1950 .unwrap();
1951 let buffer_path2 = project
1952 .read_with(cx, |project, cx| {
1953 project.find_project_path("test/file2", cx)
1954 })
1955 .unwrap();
1956
1957 let prompt_store = None;
1958 let thread_store = cx
1959 .update(|cx| {
1960 ThreadStore::load(
1961 project.clone(),
1962 cx.new(|_| ToolWorkingSet::default()),
1963 prompt_store,
1964 Arc::new(PromptBuilder::new(None).unwrap()),
1965 cx,
1966 )
1967 })
1968 .await
1969 .unwrap();
1970 let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
1971 let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
1972
1973 let (workspace, cx) =
1974 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1975
1976 // Add the diff toolbar to the active pane
1977 let diff_toolbar = cx.new_window_entity(|_, cx| AgentDiffToolbar::new(cx));
1978
1979 workspace.update_in(cx, {
1980 let diff_toolbar = diff_toolbar.clone();
1981
1982 move |workspace, window, cx| {
1983 workspace.active_pane().update(cx, |pane, cx| {
1984 pane.toolbar().update(cx, |toolbar, cx| {
1985 toolbar.add_item(diff_toolbar, window, cx);
1986 });
1987 })
1988 }
1989 });
1990
1991 // Set the active thread
1992 cx.update(|window, cx| {
1993 AgentDiff::set_active_thread(&workspace.downgrade(), &thread, window, cx)
1994 });
1995
1996 let buffer1 = project
1997 .update(cx, |project, cx| {
1998 project.open_buffer(buffer_path1.clone(), cx)
1999 })
2000 .await
2001 .unwrap();
2002 let buffer2 = project
2003 .update(cx, |project, cx| {
2004 project.open_buffer(buffer_path2.clone(), cx)
2005 })
2006 .await
2007 .unwrap();
2008
2009 // Open an editor for buffer1
2010 let editor1 = cx.new_window_entity(|window, cx| {
2011 Editor::for_buffer(buffer1.clone(), Some(project.clone()), window, cx)
2012 });
2013
2014 workspace.update_in(cx, |workspace, window, cx| {
2015 workspace.add_item_to_active_pane(Box::new(editor1.clone()), None, true, window, cx);
2016 });
2017 cx.run_until_parked();
2018
2019 // Toolbar knows about the current editor, but it's hidden since there are no changes yet
2020 assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2021 toolbar.active_item,
2022 Some(AgentDiffToolbarItem::Editor {
2023 state: EditorState::Idle,
2024 ..
2025 })
2026 )));
2027 assert_eq!(
2028 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2029 ToolbarItemLocation::Hidden
2030 );
2031
2032 // Make changes
2033 cx.update(|_, cx| {
2034 action_log.update(cx, |log, cx| log.buffer_read(buffer1.clone(), cx));
2035 buffer1.update(cx, |buffer, cx| {
2036 buffer
2037 .edit(
2038 [
2039 (Point::new(1, 1)..Point::new(1, 2), "E"),
2040 (Point::new(3, 2)..Point::new(3, 3), "L"),
2041 (Point::new(5, 0)..Point::new(5, 1), "P"),
2042 (Point::new(7, 1)..Point::new(7, 2), "W"),
2043 ],
2044 None,
2045 cx,
2046 )
2047 .unwrap()
2048 });
2049 action_log.update(cx, |log, cx| log.buffer_edited(buffer1.clone(), cx));
2050
2051 action_log.update(cx, |log, cx| log.buffer_read(buffer2.clone(), cx));
2052 buffer2.update(cx, |buffer, cx| {
2053 buffer
2054 .edit(
2055 [
2056 (Point::new(0, 0)..Point::new(0, 1), "A"),
2057 (Point::new(2, 1)..Point::new(2, 2), "H"),
2058 ],
2059 None,
2060 cx,
2061 )
2062 .unwrap();
2063 });
2064 action_log.update(cx, |log, cx| log.buffer_edited(buffer2.clone(), cx));
2065 });
2066 cx.run_until_parked();
2067
2068 // The already opened editor displays the diff and the cursor is at the first hunk
2069 assert_eq!(
2070 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2071 "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2072 );
2073 assert_eq!(
2074 editor1
2075 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2076 .range(),
2077 Point::new(1, 0)..Point::new(1, 0)
2078 );
2079
2080 // The toolbar is displayed in the right state
2081 assert_eq!(
2082 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2083 ToolbarItemLocation::PrimaryRight
2084 );
2085 assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2086 toolbar.active_item,
2087 Some(AgentDiffToolbarItem::Editor {
2088 state: EditorState::Reviewing,
2089 ..
2090 })
2091 )));
2092
2093 // The toolbar respects its setting
2094 override_toolbar_agent_review_setting(false, cx);
2095 assert_eq!(
2096 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2097 ToolbarItemLocation::Hidden
2098 );
2099 override_toolbar_agent_review_setting(true, cx);
2100 assert_eq!(
2101 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2102 ToolbarItemLocation::PrimaryRight
2103 );
2104
2105 // After keeping a hunk, the cursor should be positioned on the second hunk.
2106 workspace.update(cx, |_, cx| {
2107 cx.dispatch_action(&Keep);
2108 });
2109 cx.run_until_parked();
2110 assert_eq!(
2111 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2112 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2113 );
2114 assert_eq!(
2115 editor1
2116 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2117 .range(),
2118 Point::new(3, 0)..Point::new(3, 0)
2119 );
2120
2121 // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
2122 editor1.update_in(cx, |editor, window, cx| {
2123 editor.change_selections(None, window, cx, |selections| {
2124 selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
2125 });
2126 });
2127 workspace.update(cx, |_, cx| {
2128 cx.dispatch_action(&Reject);
2129 });
2130 cx.run_until_parked();
2131 assert_eq!(
2132 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2133 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
2134 );
2135 assert_eq!(
2136 editor1
2137 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2138 .range(),
2139 Point::new(3, 0)..Point::new(3, 0)
2140 );
2141
2142 // Keeping a range that doesn't intersect the current selection doesn't move it.
2143 editor1.update_in(cx, |editor, window, cx| {
2144 let buffer = editor.buffer().read(cx);
2145 let position = buffer.read(cx).anchor_before(Point::new(7, 0));
2146 let snapshot = buffer.snapshot(cx);
2147 keep_edits_in_ranges(
2148 editor,
2149 &snapshot,
2150 &thread,
2151 vec![position..position],
2152 window,
2153 cx,
2154 )
2155 });
2156 cx.run_until_parked();
2157 assert_eq!(
2158 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2159 "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
2160 );
2161 assert_eq!(
2162 editor1
2163 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2164 .range(),
2165 Point::new(3, 0)..Point::new(3, 0)
2166 );
2167
2168 // Reviewing the last change opens the next changed buffer
2169 workspace
2170 .update_in(cx, |workspace, window, cx| {
2171 AgentDiff::global(cx).update(cx, |agent_diff, cx| {
2172 agent_diff.review_in_active_editor(workspace, AgentDiff::keep, window, cx)
2173 })
2174 })
2175 .unwrap()
2176 .await
2177 .unwrap();
2178
2179 cx.run_until_parked();
2180
2181 let editor2 = workspace.update(cx, |workspace, cx| {
2182 workspace.active_item_as::<Editor>(cx).unwrap()
2183 });
2184
2185 let editor2_path = editor2
2186 .read_with(cx, |editor, cx| editor.project_path(cx))
2187 .unwrap();
2188 assert_eq!(editor2_path, buffer_path2);
2189
2190 assert_eq!(
2191 editor2.read_with(cx, |editor, cx| editor.text(cx)),
2192 "abc\nAbc\ndef\nghi\ngHi"
2193 );
2194 assert_eq!(
2195 editor2
2196 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2197 .range(),
2198 Point::new(0, 0)..Point::new(0, 0)
2199 );
2200
2201 // Editor 1 toolbar is hidden since all changes have been reviewed
2202 workspace.update_in(cx, |workspace, window, cx| {
2203 workspace.activate_item(&editor1, true, true, window, cx)
2204 });
2205
2206 assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2207 toolbar.active_item,
2208 Some(AgentDiffToolbarItem::Editor {
2209 state: EditorState::Idle,
2210 ..
2211 })
2212 )));
2213 assert_eq!(
2214 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2215 ToolbarItemLocation::Hidden
2216 );
2217 }
2218
2219 fn override_toolbar_agent_review_setting(active: bool, cx: &mut VisualTestContext) {
2220 cx.update(|_window, cx| {
2221 SettingsStore::update_global(cx, |store, _cx| {
2222 let mut editor_settings = store.get::<EditorSettings>(None).clone();
2223 editor_settings.toolbar.agent_review = active;
2224 store.override_global(editor_settings);
2225 })
2226 });
2227 cx.run_until_parked();
2228 }
2229}