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