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::{Divider, 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(),
1039 Divider::vertical().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(),
1073 Divider::vertical().into_any_element(),
1074 ],
1075 };
1076
1077 h_flex()
1078 .track_focus(&editor_focus_handle)
1079 .size_full()
1080 .child(
1081 h_flex()
1082 .py(DynamicSpacing::Base08.rems(cx))
1083 .px_2()
1084 .gap_1()
1085 .children(content)
1086 .when_some(editor.read(cx).workspace(), |this, _workspace| {
1087 this.child(
1088 IconButton::new("review", IconName::ListCollapse)
1089 .icon_size(IconSize::Small)
1090 .tooltip(Tooltip::for_action_title_in(
1091 "Review All Files",
1092 &OpenAgentDiff,
1093 &editor_focus_handle,
1094 ))
1095 .on_click({
1096 cx.listener(move |this, _, window, cx| {
1097 this.dispatch_action(&OpenAgentDiff, window, cx);
1098 })
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(generating_label).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 .px_2()
1133 .items_center()
1134 .flex_wrap()
1135 .child(
1136 h_group_sm()
1137 .child(
1138 Button::new("reject-all", "Reject All")
1139 .key_binding({
1140 KeyBinding::for_action_in(
1141 &RejectAll,
1142 &focus_handle,
1143 window,
1144 cx,
1145 )
1146 .map(|kb| kb.size(rems_from_px(12.)))
1147 })
1148 .on_click(cx.listener(|this, _, window, cx| {
1149 this.dispatch_action(&RejectAll, window, cx)
1150 })),
1151 )
1152 .child(
1153 Button::new("keep-all", "Keep All")
1154 .key_binding({
1155 KeyBinding::for_action_in(
1156 &KeepAll,
1157 &focus_handle,
1158 window,
1159 cx,
1160 )
1161 .map(|kb| kb.size(rems_from_px(12.)))
1162 })
1163 .on_click(cx.listener(|this, _, window, cx| {
1164 this.dispatch_action(&KeepAll, window, cx)
1165 })),
1166 ),
1167 )
1168 .into_any()
1169 }
1170 }
1171 }
1172}
1173
1174#[derive(Default)]
1175pub struct AgentDiff {
1176 reviewing_editors: HashMap<WeakEntity<Editor>, EditorState>,
1177 workspace_threads: HashMap<WeakEntity<Workspace>, WorkspaceThread>,
1178}
1179
1180#[derive(Clone, Debug, PartialEq, Eq)]
1181pub enum EditorState {
1182 Idle,
1183 Reviewing,
1184 Generating,
1185}
1186
1187struct WorkspaceThread {
1188 thread: WeakEntity<Thread>,
1189 _thread_subscriptions: [Subscription; 2],
1190 singleton_editors: HashMap<WeakEntity<Buffer>, HashMap<WeakEntity<Editor>, Subscription>>,
1191 _settings_subscription: Subscription,
1192 _workspace_subscription: Option<Subscription>,
1193}
1194
1195struct AgentDiffGlobal(Entity<AgentDiff>);
1196
1197impl Global for AgentDiffGlobal {}
1198
1199impl AgentDiff {
1200 fn global(cx: &mut App) -> Entity<Self> {
1201 cx.try_global::<AgentDiffGlobal>()
1202 .map(|global| global.0.clone())
1203 .unwrap_or_else(|| {
1204 let entity = cx.new(|_cx| Self::default());
1205 let global = AgentDiffGlobal(entity.clone());
1206 cx.set_global(global);
1207 entity.clone()
1208 })
1209 }
1210
1211 pub fn set_active_thread(
1212 workspace: &WeakEntity<Workspace>,
1213 thread: &Entity<Thread>,
1214 window: &mut Window,
1215 cx: &mut App,
1216 ) {
1217 Self::global(cx).update(cx, |this, cx| {
1218 this.register_active_thread_impl(workspace, thread, window, cx);
1219 });
1220 }
1221
1222 fn register_active_thread_impl(
1223 &mut self,
1224 workspace: &WeakEntity<Workspace>,
1225 thread: &Entity<Thread>,
1226 window: &mut Window,
1227 cx: &mut Context<Self>,
1228 ) {
1229 let action_log = thread.read(cx).action_log().clone();
1230
1231 let action_log_subscription = cx.observe_in(&action_log, window, {
1232 let workspace = workspace.clone();
1233 move |this, _action_log, window, cx| {
1234 this.update_reviewing_editors(&workspace, window, cx);
1235 }
1236 });
1237
1238 let thread_subscription = cx.subscribe_in(&thread, window, {
1239 let workspace = workspace.clone();
1240 move |this, _thread, event, window, cx| {
1241 this.handle_thread_event(&workspace, event, window, cx)
1242 }
1243 });
1244
1245 if let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) {
1246 // replace thread and action log subscription, but keep editors
1247 workspace_thread.thread = thread.downgrade();
1248 workspace_thread._thread_subscriptions = [action_log_subscription, thread_subscription];
1249 self.update_reviewing_editors(&workspace, window, cx);
1250 return;
1251 }
1252
1253 let settings_subscription = cx.observe_global_in::<SettingsStore>(window, {
1254 let workspace = workspace.clone();
1255 let mut was_active = AssistantSettings::get_global(cx).single_file_review;
1256 move |this, window, cx| {
1257 let is_active = AssistantSettings::get_global(cx).single_file_review;
1258 if was_active != is_active {
1259 was_active = is_active;
1260 this.update_reviewing_editors(&workspace, window, cx);
1261 }
1262 }
1263 });
1264
1265 let workspace_subscription = workspace
1266 .upgrade()
1267 .map(|workspace| cx.subscribe_in(&workspace, window, Self::handle_workspace_event));
1268
1269 self.workspace_threads.insert(
1270 workspace.clone(),
1271 WorkspaceThread {
1272 thread: thread.downgrade(),
1273 _thread_subscriptions: [action_log_subscription, thread_subscription],
1274 singleton_editors: HashMap::default(),
1275 _settings_subscription: settings_subscription,
1276 _workspace_subscription: workspace_subscription,
1277 },
1278 );
1279
1280 let workspace = workspace.clone();
1281 cx.defer_in(window, move |this, window, cx| {
1282 if let Some(workspace) = workspace.upgrade() {
1283 this.register_workspace(workspace, window, cx);
1284 }
1285 });
1286 }
1287
1288 fn register_workspace(
1289 &mut self,
1290 workspace: Entity<Workspace>,
1291 window: &mut Window,
1292 cx: &mut Context<Self>,
1293 ) {
1294 let agent_diff = cx.entity();
1295
1296 let editors = workspace.update(cx, |workspace, cx| {
1297 let agent_diff = agent_diff.clone();
1298
1299 Self::register_review_action::<Keep>(workspace, Self::keep, &agent_diff);
1300 Self::register_review_action::<Reject>(workspace, Self::reject, &agent_diff);
1301 Self::register_review_action::<KeepAll>(workspace, Self::keep_all, &agent_diff);
1302 Self::register_review_action::<RejectAll>(workspace, Self::reject_all, &agent_diff);
1303
1304 workspace.items_of_type(cx).collect::<Vec<_>>()
1305 });
1306
1307 let weak_workspace = workspace.downgrade();
1308
1309 for editor in editors {
1310 if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1311 self.register_editor(weak_workspace.clone(), buffer, editor, window, cx);
1312 };
1313 }
1314
1315 self.update_reviewing_editors(&weak_workspace, window, cx);
1316 }
1317
1318 fn register_review_action<T: Action>(
1319 workspace: &mut Workspace,
1320 review: impl Fn(&Entity<Editor>, &Entity<Thread>, &mut Window, &mut App) -> PostReviewState
1321 + 'static,
1322 this: &Entity<AgentDiff>,
1323 ) {
1324 let this = this.clone();
1325 workspace.register_action(move |workspace, _: &T, window, cx| {
1326 let review = &review;
1327 let task = this.update(cx, |this, cx| {
1328 this.review_in_active_editor(workspace, review, window, cx)
1329 });
1330
1331 if let Some(task) = task {
1332 task.detach_and_log_err(cx);
1333 } else {
1334 cx.propagate();
1335 }
1336 });
1337 }
1338
1339 fn handle_thread_event(
1340 &mut self,
1341 workspace: &WeakEntity<Workspace>,
1342 event: &ThreadEvent,
1343 window: &mut Window,
1344 cx: &mut Context<Self>,
1345 ) {
1346 match event {
1347 ThreadEvent::NewRequest
1348 | ThreadEvent::Stopped(Ok(StopReason::EndTurn))
1349 | ThreadEvent::Stopped(Ok(StopReason::MaxTokens))
1350 | ThreadEvent::Stopped(Err(_))
1351 | ThreadEvent::ShowError(_)
1352 | ThreadEvent::CompletionCanceled => {
1353 self.update_reviewing_editors(workspace, window, cx);
1354 }
1355 // intentionally being exhaustive in case we add a variant we should handle
1356 ThreadEvent::Stopped(Ok(StopReason::ToolUse))
1357 | ThreadEvent::StreamedCompletion
1358 | ThreadEvent::ReceivedTextChunk
1359 | ThreadEvent::StreamedAssistantText(_, _)
1360 | ThreadEvent::StreamedAssistantThinking(_, _)
1361 | ThreadEvent::StreamedToolUse { .. }
1362 | ThreadEvent::InvalidToolInput { .. }
1363 | ThreadEvent::MissingToolUse { .. }
1364 | ThreadEvent::MessageAdded(_)
1365 | ThreadEvent::MessageEdited(_)
1366 | ThreadEvent::MessageDeleted(_)
1367 | ThreadEvent::SummaryGenerated
1368 | ThreadEvent::SummaryChanged
1369 | ThreadEvent::UsePendingTools { .. }
1370 | ThreadEvent::ToolFinished { .. }
1371 | ThreadEvent::CheckpointChanged
1372 | ThreadEvent::ToolConfirmationNeeded
1373 | ThreadEvent::CancelEditing => {}
1374 }
1375 }
1376
1377 fn handle_workspace_event(
1378 &mut self,
1379 workspace: &Entity<Workspace>,
1380 event: &workspace::Event,
1381 window: &mut Window,
1382 cx: &mut Context<Self>,
1383 ) {
1384 match event {
1385 workspace::Event::ItemAdded { item } => {
1386 if let Some(editor) = item.downcast::<Editor>() {
1387 if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1388 self.register_editor(
1389 workspace.downgrade(),
1390 buffer.clone(),
1391 editor,
1392 window,
1393 cx,
1394 );
1395 }
1396 }
1397 }
1398 _ => {}
1399 }
1400 }
1401
1402 fn full_editor_buffer(editor: &Editor, cx: &App) -> Option<WeakEntity<Buffer>> {
1403 if editor.mode().is_full() {
1404 editor
1405 .buffer()
1406 .read(cx)
1407 .as_singleton()
1408 .map(|buffer| buffer.downgrade())
1409 } else {
1410 None
1411 }
1412 }
1413
1414 fn register_editor(
1415 &mut self,
1416 workspace: WeakEntity<Workspace>,
1417 buffer: WeakEntity<Buffer>,
1418 editor: Entity<Editor>,
1419 window: &mut Window,
1420 cx: &mut Context<Self>,
1421 ) {
1422 let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) else {
1423 return;
1424 };
1425
1426 let weak_editor = editor.downgrade();
1427
1428 workspace_thread
1429 .singleton_editors
1430 .entry(buffer.clone())
1431 .or_default()
1432 .entry(weak_editor.clone())
1433 .or_insert_with(|| {
1434 let workspace = workspace.clone();
1435 cx.observe_release(&editor, move |this, _, _cx| {
1436 let Some(active_thread) = this.workspace_threads.get_mut(&workspace) else {
1437 return;
1438 };
1439
1440 if let Entry::Occupied(mut entry) =
1441 active_thread.singleton_editors.entry(buffer)
1442 {
1443 let set = entry.get_mut();
1444 set.remove(&weak_editor);
1445
1446 if set.is_empty() {
1447 entry.remove();
1448 }
1449 }
1450 })
1451 });
1452
1453 self.update_reviewing_editors(&workspace, window, cx);
1454 }
1455
1456 fn update_reviewing_editors(
1457 &mut self,
1458 workspace: &WeakEntity<Workspace>,
1459 window: &mut Window,
1460 cx: &mut Context<Self>,
1461 ) {
1462 if !AssistantSettings::get_global(cx).single_file_review {
1463 for (editor, _) in self.reviewing_editors.drain() {
1464 editor
1465 .update(cx, |editor, cx| editor.end_temporary_diff_override(cx))
1466 .ok();
1467 }
1468 return;
1469 }
1470
1471 let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) else {
1472 return;
1473 };
1474
1475 let Some(thread) = workspace_thread.thread.upgrade() else {
1476 return;
1477 };
1478
1479 let action_log = thread.read(cx).action_log();
1480 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1481
1482 let mut unaffected = self.reviewing_editors.clone();
1483
1484 for (buffer, diff_handle) in changed_buffers {
1485 if buffer.read(cx).file().is_none() {
1486 continue;
1487 }
1488
1489 let Some(buffer_editors) = workspace_thread.singleton_editors.get(&buffer.downgrade())
1490 else {
1491 continue;
1492 };
1493
1494 for (weak_editor, _) in buffer_editors {
1495 let Some(editor) = weak_editor.upgrade() else {
1496 continue;
1497 };
1498
1499 let multibuffer = editor.read(cx).buffer().clone();
1500 multibuffer.update(cx, |multibuffer, cx| {
1501 multibuffer.add_diff(diff_handle.clone(), cx);
1502 });
1503
1504 let new_state = if thread.read(cx).is_generating() {
1505 EditorState::Generating
1506 } else {
1507 EditorState::Reviewing
1508 };
1509
1510 let previous_state = self
1511 .reviewing_editors
1512 .insert(weak_editor.clone(), new_state.clone());
1513
1514 if previous_state.is_none() {
1515 editor.update(cx, |editor, cx| {
1516 editor.start_temporary_diff_override();
1517 editor.set_render_diff_hunk_controls(diff_hunk_controls(&thread), cx);
1518 editor.set_expand_all_diff_hunks(cx);
1519 editor.register_addon(EditorAgentDiffAddon);
1520 });
1521 } else {
1522 unaffected.remove(&weak_editor);
1523 }
1524
1525 if new_state == EditorState::Reviewing && previous_state != Some(new_state) {
1526 // Jump to first hunk when we enter review mode
1527 editor.update(cx, |editor, cx| {
1528 let snapshot = multibuffer.read(cx).snapshot(cx);
1529 if let Some(first_hunk) = snapshot.diff_hunks().next() {
1530 let first_hunk_start = first_hunk.multi_buffer_range().start;
1531
1532 editor.change_selections(
1533 Some(Autoscroll::center()),
1534 window,
1535 cx,
1536 |selections| {
1537 selections.select_ranges([first_hunk_start..first_hunk_start])
1538 },
1539 );
1540 }
1541 });
1542 }
1543 }
1544 }
1545
1546 // Remove editors from this workspace that are no longer under review
1547 for (editor, _) in unaffected {
1548 // Note: We could avoid this check by storing `reviewing_editors` by Workspace,
1549 // but that would add another lookup in `AgentDiff::editor_state`
1550 // which gets called much more frequently.
1551 let in_workspace = editor
1552 .read_with(cx, |editor, _cx| editor.workspace())
1553 .ok()
1554 .flatten()
1555 .map_or(false, |editor_workspace| {
1556 editor_workspace.entity_id() == workspace.entity_id()
1557 });
1558
1559 if in_workspace {
1560 editor
1561 .update(cx, |editor, cx| editor.end_temporary_diff_override(cx))
1562 .ok();
1563 self.reviewing_editors.remove(&editor);
1564 }
1565 }
1566
1567 cx.notify();
1568 }
1569
1570 fn editor_state(&self, editor: &WeakEntity<Editor>) -> EditorState {
1571 self.reviewing_editors
1572 .get(&editor)
1573 .cloned()
1574 .unwrap_or(EditorState::Idle)
1575 }
1576
1577 fn deploy_pane_from_editor(&self, editor: &Entity<Editor>, window: &mut Window, cx: &mut App) {
1578 let Some(workspace) = editor.read(cx).workspace() else {
1579 return;
1580 };
1581
1582 let Some(WorkspaceThread { thread, .. }) =
1583 self.workspace_threads.get(&workspace.downgrade())
1584 else {
1585 return;
1586 };
1587
1588 let Some(thread) = thread.upgrade() else {
1589 return;
1590 };
1591
1592 AgentDiffPane::deploy(thread, workspace.downgrade(), window, cx).log_err();
1593 }
1594
1595 fn keep_all(
1596 editor: &Entity<Editor>,
1597 thread: &Entity<Thread>,
1598 window: &mut Window,
1599 cx: &mut App,
1600 ) -> PostReviewState {
1601 editor.update(cx, |editor, cx| {
1602 let snapshot = editor.buffer().read(cx).snapshot(cx);
1603 keep_edits_in_ranges(
1604 editor,
1605 &snapshot,
1606 thread,
1607 vec![editor::Anchor::min()..editor::Anchor::max()],
1608 window,
1609 cx,
1610 );
1611 });
1612 PostReviewState::AllReviewed
1613 }
1614
1615 fn reject_all(
1616 editor: &Entity<Editor>,
1617 thread: &Entity<Thread>,
1618 window: &mut Window,
1619 cx: &mut App,
1620 ) -> PostReviewState {
1621 editor.update(cx, |editor, cx| {
1622 let snapshot = editor.buffer().read(cx).snapshot(cx);
1623 reject_edits_in_ranges(
1624 editor,
1625 &snapshot,
1626 thread,
1627 vec![editor::Anchor::min()..editor::Anchor::max()],
1628 window,
1629 cx,
1630 );
1631 });
1632 PostReviewState::AllReviewed
1633 }
1634
1635 fn keep(
1636 editor: &Entity<Editor>,
1637 thread: &Entity<Thread>,
1638 window: &mut Window,
1639 cx: &mut App,
1640 ) -> PostReviewState {
1641 editor.update(cx, |editor, cx| {
1642 let snapshot = editor.buffer().read(cx).snapshot(cx);
1643 keep_edits_in_selection(editor, &snapshot, thread, window, cx);
1644 Self::post_review_state(&snapshot)
1645 })
1646 }
1647
1648 fn reject(
1649 editor: &Entity<Editor>,
1650 thread: &Entity<Thread>,
1651 window: &mut Window,
1652 cx: &mut App,
1653 ) -> PostReviewState {
1654 editor.update(cx, |editor, cx| {
1655 let snapshot = editor.buffer().read(cx).snapshot(cx);
1656 reject_edits_in_selection(editor, &snapshot, thread, window, cx);
1657 Self::post_review_state(&snapshot)
1658 })
1659 }
1660
1661 fn post_review_state(snapshot: &MultiBufferSnapshot) -> PostReviewState {
1662 for (i, _) in snapshot.diff_hunks().enumerate() {
1663 if i > 0 {
1664 return PostReviewState::Pending;
1665 }
1666 }
1667 PostReviewState::AllReviewed
1668 }
1669
1670 fn review_in_active_editor(
1671 &mut self,
1672 workspace: &mut Workspace,
1673 review: impl Fn(&Entity<Editor>, &Entity<Thread>, &mut Window, &mut App) -> PostReviewState,
1674 window: &mut Window,
1675 cx: &mut Context<Self>,
1676 ) -> Option<Task<Result<()>>> {
1677 let active_item = workspace.active_item(cx)?;
1678 let editor = active_item.act_as::<Editor>(cx)?;
1679
1680 if !matches!(
1681 self.editor_state(&editor.downgrade()),
1682 EditorState::Reviewing
1683 ) {
1684 return None;
1685 }
1686
1687 let WorkspaceThread { thread, .. } =
1688 self.workspace_threads.get(&workspace.weak_handle())?;
1689
1690 let thread = thread.upgrade()?;
1691
1692 if let PostReviewState::AllReviewed = review(&editor, &thread, window, cx) {
1693 if let Some(curr_buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
1694 let changed_buffers = thread.read(cx).action_log().read(cx).changed_buffers(cx);
1695
1696 let mut keys = changed_buffers.keys().cycle();
1697 keys.find(|k| *k == &curr_buffer);
1698 let next_project_path = keys
1699 .next()
1700 .filter(|k| *k != &curr_buffer)
1701 .and_then(|after| after.read(cx).project_path(cx));
1702
1703 if let Some(path) = next_project_path {
1704 let task = workspace.open_path(path, None, true, window, cx);
1705 let task = cx.spawn(async move |_, _cx| task.await.map(|_| ()));
1706 return Some(task);
1707 }
1708 }
1709 }
1710
1711 return Some(Task::ready(Ok(())));
1712 }
1713}
1714
1715enum PostReviewState {
1716 AllReviewed,
1717 Pending,
1718}
1719
1720pub struct EditorAgentDiffAddon;
1721
1722impl editor::Addon for EditorAgentDiffAddon {
1723 fn to_any(&self) -> &dyn std::any::Any {
1724 self
1725 }
1726
1727 fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
1728 key_context.add("agent_diff");
1729 key_context.add("editor_agent_diff");
1730 }
1731}
1732
1733#[cfg(test)]
1734mod tests {
1735 use super::*;
1736 use crate::{Keep, ThreadStore, thread_store};
1737 use assistant_settings::AssistantSettings;
1738 use assistant_tool::ToolWorkingSet;
1739 use editor::EditorSettings;
1740 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
1741 use project::{FakeFs, Project};
1742 use prompt_store::PromptBuilder;
1743 use serde_json::json;
1744 use settings::{Settings, SettingsStore};
1745 use std::sync::Arc;
1746 use theme::ThemeSettings;
1747 use util::path;
1748
1749 #[gpui::test]
1750 async fn test_multibuffer_agent_diff(cx: &mut TestAppContext) {
1751 cx.update(|cx| {
1752 let settings_store = SettingsStore::test(cx);
1753 cx.set_global(settings_store);
1754 language::init(cx);
1755 Project::init_settings(cx);
1756 AssistantSettings::register(cx);
1757 prompt_store::init(cx);
1758 thread_store::init(cx);
1759 workspace::init_settings(cx);
1760 ThemeSettings::register(cx);
1761 EditorSettings::register(cx);
1762 language_model::init_settings(cx);
1763 });
1764
1765 let fs = FakeFs::new(cx.executor());
1766 fs.insert_tree(
1767 path!("/test"),
1768 json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1769 )
1770 .await;
1771 let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1772 let buffer_path = project
1773 .read_with(cx, |project, cx| {
1774 project.find_project_path("test/file1", cx)
1775 })
1776 .unwrap();
1777
1778 let prompt_store = None;
1779 let thread_store = cx
1780 .update(|cx| {
1781 ThreadStore::load(
1782 project.clone(),
1783 cx.new(|_| ToolWorkingSet::default()),
1784 prompt_store,
1785 Arc::new(PromptBuilder::new(None).unwrap()),
1786 cx,
1787 )
1788 })
1789 .await
1790 .unwrap();
1791 let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
1792 let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
1793
1794 let (workspace, cx) =
1795 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1796 let agent_diff = cx.new_window_entity(|window, cx| {
1797 AgentDiffPane::new(thread.clone(), workspace.downgrade(), window, cx)
1798 });
1799 let editor = agent_diff.read_with(cx, |diff, _cx| diff.editor.clone());
1800
1801 let buffer = project
1802 .update(cx, |project, cx| project.open_buffer(buffer_path, cx))
1803 .await
1804 .unwrap();
1805 cx.update(|_, cx| {
1806 action_log.update(cx, |log, cx| log.buffer_read(buffer.clone(), cx));
1807 buffer.update(cx, |buffer, cx| {
1808 buffer
1809 .edit(
1810 [
1811 (Point::new(1, 1)..Point::new(1, 2), "E"),
1812 (Point::new(3, 2)..Point::new(3, 3), "L"),
1813 (Point::new(5, 0)..Point::new(5, 1), "P"),
1814 (Point::new(7, 1)..Point::new(7, 2), "W"),
1815 ],
1816 None,
1817 cx,
1818 )
1819 .unwrap()
1820 });
1821 action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
1822 });
1823 cx.run_until_parked();
1824
1825 // When opening the assistant diff, the cursor is positioned on the first hunk.
1826 assert_eq!(
1827 editor.read_with(cx, |editor, cx| editor.text(cx)),
1828 "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1829 );
1830 assert_eq!(
1831 editor
1832 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1833 .range(),
1834 Point::new(1, 0)..Point::new(1, 0)
1835 );
1836
1837 // After keeping a hunk, the cursor should be positioned on the second hunk.
1838 agent_diff.update_in(cx, |diff, window, cx| diff.keep(&Keep, window, cx));
1839 cx.run_until_parked();
1840 assert_eq!(
1841 editor.read_with(cx, |editor, cx| editor.text(cx)),
1842 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1843 );
1844 assert_eq!(
1845 editor
1846 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1847 .range(),
1848 Point::new(3, 0)..Point::new(3, 0)
1849 );
1850
1851 // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
1852 editor.update_in(cx, |editor, window, cx| {
1853 editor.change_selections(None, window, cx, |selections| {
1854 selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
1855 });
1856 });
1857 agent_diff.update_in(cx, |diff, window, cx| {
1858 diff.reject(&crate::Reject, window, cx)
1859 });
1860 cx.run_until_parked();
1861 assert_eq!(
1862 editor.read_with(cx, |editor, cx| editor.text(cx)),
1863 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
1864 );
1865 assert_eq!(
1866 editor
1867 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1868 .range(),
1869 Point::new(3, 0)..Point::new(3, 0)
1870 );
1871
1872 // Keeping a range that doesn't intersect the current selection doesn't move it.
1873 agent_diff.update_in(cx, |_diff, window, cx| {
1874 let position = editor
1875 .read(cx)
1876 .buffer()
1877 .read(cx)
1878 .read(cx)
1879 .anchor_before(Point::new(7, 0));
1880 editor.update(cx, |editor, cx| {
1881 let snapshot = editor.buffer().read(cx).snapshot(cx);
1882 keep_edits_in_ranges(
1883 editor,
1884 &snapshot,
1885 &thread,
1886 vec![position..position],
1887 window,
1888 cx,
1889 )
1890 });
1891 });
1892 cx.run_until_parked();
1893 assert_eq!(
1894 editor.read_with(cx, |editor, cx| editor.text(cx)),
1895 "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
1896 );
1897 assert_eq!(
1898 editor
1899 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1900 .range(),
1901 Point::new(3, 0)..Point::new(3, 0)
1902 );
1903 }
1904
1905 #[gpui::test]
1906 async fn test_singleton_agent_diff(cx: &mut TestAppContext) {
1907 cx.update(|cx| {
1908 let settings_store = SettingsStore::test(cx);
1909 cx.set_global(settings_store);
1910 language::init(cx);
1911 Project::init_settings(cx);
1912 AssistantSettings::register(cx);
1913 prompt_store::init(cx);
1914 thread_store::init(cx);
1915 workspace::init_settings(cx);
1916 ThemeSettings::register(cx);
1917 EditorSettings::register(cx);
1918 language_model::init_settings(cx);
1919 workspace::register_project_item::<Editor>(cx);
1920 });
1921
1922 let fs = FakeFs::new(cx.executor());
1923 fs.insert_tree(
1924 path!("/test"),
1925 json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1926 )
1927 .await;
1928 fs.insert_tree(path!("/test"), json!({"file2": "abc\ndef\nghi"}))
1929 .await;
1930
1931 let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1932 let buffer_path1 = project
1933 .read_with(cx, |project, cx| {
1934 project.find_project_path("test/file1", cx)
1935 })
1936 .unwrap();
1937 let buffer_path2 = project
1938 .read_with(cx, |project, cx| {
1939 project.find_project_path("test/file2", cx)
1940 })
1941 .unwrap();
1942
1943 let prompt_store = None;
1944 let thread_store = cx
1945 .update(|cx| {
1946 ThreadStore::load(
1947 project.clone(),
1948 cx.new(|_| ToolWorkingSet::default()),
1949 prompt_store,
1950 Arc::new(PromptBuilder::new(None).unwrap()),
1951 cx,
1952 )
1953 })
1954 .await
1955 .unwrap();
1956 let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
1957 let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
1958
1959 let (workspace, cx) =
1960 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1961
1962 // Add the diff toolbar to the active pane
1963 let diff_toolbar = cx.new_window_entity(|_, cx| AgentDiffToolbar::new(cx));
1964
1965 workspace.update_in(cx, {
1966 let diff_toolbar = diff_toolbar.clone();
1967
1968 move |workspace, window, cx| {
1969 workspace.active_pane().update(cx, |pane, cx| {
1970 pane.toolbar().update(cx, |toolbar, cx| {
1971 toolbar.add_item(diff_toolbar, window, cx);
1972 });
1973 })
1974 }
1975 });
1976
1977 // Set the active thread
1978 cx.update(|window, cx| {
1979 AgentDiff::set_active_thread(&workspace.downgrade(), &thread, window, cx)
1980 });
1981
1982 let buffer1 = project
1983 .update(cx, |project, cx| {
1984 project.open_buffer(buffer_path1.clone(), cx)
1985 })
1986 .await
1987 .unwrap();
1988 let buffer2 = project
1989 .update(cx, |project, cx| {
1990 project.open_buffer(buffer_path2.clone(), cx)
1991 })
1992 .await
1993 .unwrap();
1994
1995 // Open an editor for buffer1
1996 let editor1 = cx.new_window_entity(|window, cx| {
1997 Editor::for_buffer(buffer1.clone(), Some(project.clone()), window, cx)
1998 });
1999
2000 workspace.update_in(cx, |workspace, window, cx| {
2001 workspace.add_item_to_active_pane(Box::new(editor1.clone()), None, true, window, cx);
2002 });
2003 cx.run_until_parked();
2004
2005 // Toolbar knows about the current editor, but it's hidden since there are no changes yet
2006 assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2007 toolbar.active_item,
2008 Some(AgentDiffToolbarItem::Editor {
2009 state: EditorState::Idle,
2010 ..
2011 })
2012 )));
2013 assert_eq!(
2014 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2015 ToolbarItemLocation::Hidden
2016 );
2017
2018 // Make changes
2019 cx.update(|_, cx| {
2020 action_log.update(cx, |log, cx| log.buffer_read(buffer1.clone(), cx));
2021 buffer1.update(cx, |buffer, cx| {
2022 buffer
2023 .edit(
2024 [
2025 (Point::new(1, 1)..Point::new(1, 2), "E"),
2026 (Point::new(3, 2)..Point::new(3, 3), "L"),
2027 (Point::new(5, 0)..Point::new(5, 1), "P"),
2028 (Point::new(7, 1)..Point::new(7, 2), "W"),
2029 ],
2030 None,
2031 cx,
2032 )
2033 .unwrap()
2034 });
2035 action_log.update(cx, |log, cx| log.buffer_edited(buffer1.clone(), cx));
2036
2037 action_log.update(cx, |log, cx| log.buffer_read(buffer2.clone(), cx));
2038 buffer2.update(cx, |buffer, cx| {
2039 buffer
2040 .edit(
2041 [
2042 (Point::new(0, 0)..Point::new(0, 1), "A"),
2043 (Point::new(2, 1)..Point::new(2, 2), "H"),
2044 ],
2045 None,
2046 cx,
2047 )
2048 .unwrap();
2049 });
2050 action_log.update(cx, |log, cx| log.buffer_edited(buffer2.clone(), cx));
2051 });
2052 cx.run_until_parked();
2053
2054 // The already opened editor displays the diff and the cursor is at the first hunk
2055 assert_eq!(
2056 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2057 "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2058 );
2059 assert_eq!(
2060 editor1
2061 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2062 .range(),
2063 Point::new(1, 0)..Point::new(1, 0)
2064 );
2065
2066 // The toolbar is displayed in the right state
2067 assert_eq!(
2068 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2069 ToolbarItemLocation::PrimaryRight
2070 );
2071 assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2072 toolbar.active_item,
2073 Some(AgentDiffToolbarItem::Editor {
2074 state: EditorState::Reviewing,
2075 ..
2076 })
2077 )));
2078
2079 // The toolbar respects its setting
2080 override_toolbar_agent_review_setting(false, cx);
2081 assert_eq!(
2082 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2083 ToolbarItemLocation::Hidden
2084 );
2085 override_toolbar_agent_review_setting(true, cx);
2086 assert_eq!(
2087 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2088 ToolbarItemLocation::PrimaryRight
2089 );
2090
2091 // After keeping a hunk, the cursor should be positioned on the second hunk.
2092 workspace.update(cx, |_, cx| {
2093 cx.dispatch_action(&Keep);
2094 });
2095 cx.run_until_parked();
2096 assert_eq!(
2097 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2098 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2099 );
2100 assert_eq!(
2101 editor1
2102 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2103 .range(),
2104 Point::new(3, 0)..Point::new(3, 0)
2105 );
2106
2107 // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
2108 editor1.update_in(cx, |editor, window, cx| {
2109 editor.change_selections(None, window, cx, |selections| {
2110 selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
2111 });
2112 });
2113 workspace.update(cx, |_, cx| {
2114 cx.dispatch_action(&Reject);
2115 });
2116 cx.run_until_parked();
2117 assert_eq!(
2118 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2119 "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
2120 );
2121 assert_eq!(
2122 editor1
2123 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2124 .range(),
2125 Point::new(3, 0)..Point::new(3, 0)
2126 );
2127
2128 // Keeping a range that doesn't intersect the current selection doesn't move it.
2129 editor1.update_in(cx, |editor, window, cx| {
2130 let buffer = editor.buffer().read(cx);
2131 let position = buffer.read(cx).anchor_before(Point::new(7, 0));
2132 let snapshot = buffer.snapshot(cx);
2133 keep_edits_in_ranges(
2134 editor,
2135 &snapshot,
2136 &thread,
2137 vec![position..position],
2138 window,
2139 cx,
2140 )
2141 });
2142 cx.run_until_parked();
2143 assert_eq!(
2144 editor1.read_with(cx, |editor, cx| editor.text(cx)),
2145 "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
2146 );
2147 assert_eq!(
2148 editor1
2149 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2150 .range(),
2151 Point::new(3, 0)..Point::new(3, 0)
2152 );
2153
2154 // Reviewing the last change opens the next changed buffer
2155 workspace
2156 .update_in(cx, |workspace, window, cx| {
2157 AgentDiff::global(cx).update(cx, |agent_diff, cx| {
2158 agent_diff.review_in_active_editor(workspace, AgentDiff::keep, window, cx)
2159 })
2160 })
2161 .unwrap()
2162 .await
2163 .unwrap();
2164
2165 cx.run_until_parked();
2166
2167 let editor2 = workspace.update(cx, |workspace, cx| {
2168 workspace.active_item_as::<Editor>(cx).unwrap()
2169 });
2170
2171 let editor2_path = editor2
2172 .read_with(cx, |editor, cx| editor.project_path(cx))
2173 .unwrap();
2174 assert_eq!(editor2_path, buffer_path2);
2175
2176 assert_eq!(
2177 editor2.read_with(cx, |editor, cx| editor.text(cx)),
2178 "abc\nAbc\ndef\nghi\ngHi"
2179 );
2180 assert_eq!(
2181 editor2
2182 .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2183 .range(),
2184 Point::new(0, 0)..Point::new(0, 0)
2185 );
2186
2187 // Editor 1 toolbar is hidden since all changes have been reviewed
2188 workspace.update_in(cx, |workspace, window, cx| {
2189 workspace.activate_item(&editor1, true, true, window, cx)
2190 });
2191
2192 assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2193 toolbar.active_item,
2194 Some(AgentDiffToolbarItem::Editor {
2195 state: EditorState::Idle,
2196 ..
2197 })
2198 )));
2199 assert_eq!(
2200 diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2201 ToolbarItemLocation::Hidden
2202 );
2203 }
2204
2205 fn override_toolbar_agent_review_setting(active: bool, cx: &mut VisualTestContext) {
2206 cx.update(|_window, cx| {
2207 SettingsStore::update_global(cx, |store, _cx| {
2208 let mut editor_settings = store.get::<EditorSettings>(None).clone();
2209 editor_settings.toolbar.agent_review = active;
2210 store.override_global(editor_settings);
2211 })
2212 });
2213 cx.run_until_parked();
2214 }
2215}