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