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