agent_diff.rs

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