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