agent_diff.rs

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