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