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