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