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