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