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