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