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