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