agent_diff.rs

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