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