Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T01:49:30.691Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

agent_diff.rs

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