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