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::ToolUseLimitReached
1376 | ThreadEvent::CancelEditing => {}
1377 }
1378 }
1379
1380 fn handle_workspace_event(
1381 &mut self,
1382 workspace: &Entity<Workspace>,
1383 event: &workspace::Event,
1384 window: &mut Window,
1385 cx: &mut Context<Self>,
1386 ) {
1387 match event {
1388 workspace::Event::ItemAdded { item } => {
1389 if let Some(editor) = item.downcast::<Editor>() {
1390 if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1391 self.register_editor(
1392 workspace.downgrade(),
1393 buffer.clone(),
1394 editor,
1395 window,
1396 cx,
1397 );
1398 }
1399 }
1400 }
1401 _ => {}
1402 }
1403 }
1404
1405 fn full_editor_buffer(editor: &Editor, cx: &App) -> Option<WeakEntity<Buffer>> {
1406 if editor.mode().is_full() {
1407 editor
1408 .buffer()
1409 .read(cx)
1410 .as_singleton()
1411 .map(|buffer| buffer.downgrade())
1412 } else {
1413 None
1414 }
1415 }
1416
1417 fn register_editor(
1418 &mut self,
1419 workspace: WeakEntity<Workspace>,
1420 buffer: WeakEntity<Buffer>,
1421 editor: Entity<Editor>,
1422 window: &mut Window,
1423 cx: &mut Context<Self>,
1424 ) {
1425 let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) else {
1426 return;
1427 };
1428
1429 let weak_editor = editor.downgrade();
1430
1431 workspace_thread
1432 .singleton_editors
1433 .entry(buffer.clone())
1434 .or_default()
1435 .entry(weak_editor.clone())
1436 .or_insert_with(|| {
1437 let workspace = workspace.clone();
1438 cx.observe_release(&editor, move |this, _, _cx| {
1439 let Some(active_thread) = this.workspace_threads.get_mut(&workspace) else {
1440 return;
1441 };
1442
1443 if let Entry::Occupied(mut entry) =
1444 active_thread.singleton_editors.entry(buffer)
1445 {
1446 let set = entry.get_mut();
1447 set.remove(&weak_editor);
1448
1449 if set.is_empty() {
1450 entry.remove();
1451 }
1452 }
1453 })
1454 });
1455
1456 self.update_reviewing_editors(&workspace, window, cx);
1457 }
1458
1459 fn update_reviewing_editors(
1460 &mut self,
1461 workspace: &WeakEntity<Workspace>,
1462 window: &mut Window,
1463 cx: &mut Context<Self>,
1464 ) {
1465 if !AgentSettings::get_global(cx).single_file_review {
1466 for (editor, _) in self.reviewing_editors.drain() {
1467 editor
1468 .update(cx, |editor, cx| {
1469 editor.end_temporary_diff_override(cx);
1470 editor.unregister_addon::<EditorAgentDiffAddon>();
1471 })
1472 .ok();
1473 }
1474 return;
1475 }
1476
1477 let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) else {
1478 return;
1479 };
1480
1481 let Some(thread) = workspace_thread.thread.upgrade() else {
1482 return;
1483 };
1484
1485 let action_log = thread.read(cx).action_log();
1486 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1487
1488 let mut unaffected = self.reviewing_editors.clone();
1489
1490 for (buffer, diff_handle) in changed_buffers {
1491 if buffer.read(cx).file().is_none() {
1492 continue;
1493 }
1494
1495 let Some(buffer_editors) = workspace_thread.singleton_editors.get(&buffer.downgrade())
1496 else {
1497 continue;
1498 };
1499
1500 for (weak_editor, _) in buffer_editors {
1501 let Some(editor) = weak_editor.upgrade() else {
1502 continue;
1503 };
1504
1505 let multibuffer = editor.read(cx).buffer().clone();
1506 multibuffer.update(cx, |multibuffer, cx| {
1507 multibuffer.add_diff(diff_handle.clone(), cx);
1508 });
1509
1510 let new_state = if thread.read(cx).is_generating() {
1511 EditorState::Generating
1512 } else {
1513 EditorState::Reviewing
1514 };
1515
1516 let previous_state = self
1517 .reviewing_editors
1518 .insert(weak_editor.clone(), new_state.clone());
1519
1520 if previous_state.is_none() {
1521 editor.update(cx, |editor, cx| {
1522 editor.start_temporary_diff_override();
1523 editor.set_render_diff_hunk_controls(diff_hunk_controls(&thread), cx);
1524 editor.set_expand_all_diff_hunks(cx);
1525 editor.register_addon(EditorAgentDiffAddon);
1526 });
1527 } else {
1528 unaffected.remove(&weak_editor);
1529 }
1530
1531 if new_state == EditorState::Reviewing && previous_state != Some(new_state) {
1532 // Jump to first hunk when we enter review mode
1533 editor.update(cx, |editor, cx| {
1534 let snapshot = multibuffer.read(cx).snapshot(cx);
1535 if let Some(first_hunk) = snapshot.diff_hunks().next() {
1536 let first_hunk_start = first_hunk.multi_buffer_range().start;
1537
1538 editor.change_selections(
1539 Some(Autoscroll::center()),
1540 window,
1541 cx,
1542 |selections| {
1543 selections.select_ranges([first_hunk_start..first_hunk_start])
1544 },
1545 );
1546 }
1547 });
1548 }
1549 }
1550 }
1551
1552 // Remove editors from this workspace that are no longer under review
1553 for (editor, _) in unaffected {
1554 // Note: We could avoid this check by storing `reviewing_editors` by Workspace,
1555 // but that would add another lookup in `AgentDiff::editor_state`
1556 // which gets called much more frequently.
1557 let in_workspace = editor
1558 .read_with(cx, |editor, _cx| editor.workspace())
1559 .ok()
1560 .flatten()
1561 .map_or(false, |editor_workspace| {
1562 editor_workspace.entity_id() == workspace.entity_id()
1563 });
1564
1565 if in_workspace {
1566 editor
1567 .update(cx, |editor, cx| {
1568 editor.end_temporary_diff_override(cx);
1569 editor.unregister_addon::<EditorAgentDiffAddon>();
1570 })
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 agent_settings::AgentSettings;
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 AgentSettings::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 AgentSettings::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}