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