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, 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                        .icon_size(IconSize::Small)
 829                        // .disabled(!has_multiple_hunks)
 830                        .tooltip({
 831                            let focus_handle = editor.focus_handle(cx);
 832                            move |window, cx| {
 833                                Tooltip::for_action_in(
 834                                    "Next Hunk",
 835                                    &GoToHunk,
 836                                    &focus_handle,
 837                                    window,
 838                                    cx,
 839                                )
 840                            }
 841                        })
 842                        .on_click({
 843                            let editor = editor.clone();
 844                            move |_event, window, cx| {
 845                                editor.update(cx, |editor, cx| {
 846                                    let snapshot = editor.snapshot(window, cx);
 847                                    let position =
 848                                        hunk_range.end.to_point(&snapshot.buffer_snapshot());
 849                                    editor.go_to_hunk_before_or_after_position(
 850                                        &snapshot,
 851                                        position,
 852                                        Direction::Next,
 853                                        window,
 854                                        cx,
 855                                    );
 856                                    editor.expand_selected_diff_hunks(cx);
 857                                });
 858                            }
 859                        }),
 860                )
 861                .child(
 862                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
 863                        .icon_size(IconSize::Small)
 864                        // .disabled(!has_multiple_hunks)
 865                        .tooltip({
 866                            let focus_handle = editor.focus_handle(cx);
 867                            move |window, cx| {
 868                                Tooltip::for_action_in(
 869                                    "Previous Hunk",
 870                                    &GoToPreviousHunk,
 871                                    &focus_handle,
 872                                    window,
 873                                    cx,
 874                                )
 875                            }
 876                        })
 877                        .on_click({
 878                            let editor = editor.clone();
 879                            move |_event, window, cx| {
 880                                editor.update(cx, |editor, cx| {
 881                                    let snapshot = editor.snapshot(window, cx);
 882                                    let point =
 883                                        hunk_range.start.to_point(&snapshot.buffer_snapshot());
 884                                    editor.go_to_hunk_before_or_after_position(
 885                                        &snapshot,
 886                                        point,
 887                                        Direction::Prev,
 888                                        window,
 889                                        cx,
 890                                    );
 891                                    editor.expand_selected_diff_hunks(cx);
 892                                });
 893                            }
 894                        }),
 895                )
 896            },
 897        )
 898        .into_any_element()
 899}
 900
 901struct AgentDiffAddon;
 902
 903impl editor::Addon for AgentDiffAddon {
 904    fn to_any(&self) -> &dyn std::any::Any {
 905        self
 906    }
 907
 908    fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
 909        key_context.add("agent_diff");
 910    }
 911}
 912
 913pub struct AgentDiffToolbar {
 914    active_item: Option<AgentDiffToolbarItem>,
 915    _settings_subscription: Subscription,
 916}
 917
 918pub enum AgentDiffToolbarItem {
 919    Pane(WeakEntity<AgentDiffPane>),
 920    Editor {
 921        editor: WeakEntity<Editor>,
 922        state: EditorState,
 923        _diff_subscription: Subscription,
 924    },
 925}
 926
 927impl AgentDiffToolbar {
 928    pub fn new(cx: &mut Context<Self>) -> Self {
 929        Self {
 930            active_item: None,
 931            _settings_subscription: cx.observe_global::<SettingsStore>(Self::update_location),
 932        }
 933    }
 934
 935    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
 936        let Some(active_item) = self.active_item.as_ref() else {
 937            return;
 938        };
 939
 940        match active_item {
 941            AgentDiffToolbarItem::Pane(agent_diff) => {
 942                if let Some(agent_diff) = agent_diff.upgrade() {
 943                    agent_diff.focus_handle(cx).focus(window);
 944                }
 945            }
 946            AgentDiffToolbarItem::Editor { editor, .. } => {
 947                if let Some(editor) = editor.upgrade() {
 948                    editor.read(cx).focus_handle(cx).focus(window);
 949                }
 950            }
 951        }
 952
 953        let action = action.boxed_clone();
 954        cx.defer(move |cx| {
 955            cx.dispatch_action(action.as_ref());
 956        })
 957    }
 958
 959    fn handle_diff_notify(&mut self, agent_diff: Entity<AgentDiff>, cx: &mut Context<Self>) {
 960        let Some(AgentDiffToolbarItem::Editor { editor, state, .. }) = self.active_item.as_mut()
 961        else {
 962            return;
 963        };
 964
 965        *state = agent_diff.read(cx).editor_state(editor);
 966        self.update_location(cx);
 967        cx.notify();
 968    }
 969
 970    fn update_location(&mut self, cx: &mut Context<Self>) {
 971        let location = self.location(cx);
 972        cx.emit(ToolbarItemEvent::ChangeLocation(location));
 973    }
 974
 975    fn location(&self, cx: &App) -> ToolbarItemLocation {
 976        if !EditorSettings::get_global(cx).toolbar.agent_review {
 977            return ToolbarItemLocation::Hidden;
 978        }
 979
 980        match &self.active_item {
 981            None => ToolbarItemLocation::Hidden,
 982            Some(AgentDiffToolbarItem::Pane(_)) => ToolbarItemLocation::PrimaryRight,
 983            Some(AgentDiffToolbarItem::Editor { state, .. }) => match state {
 984                EditorState::Generating | EditorState::Reviewing => {
 985                    ToolbarItemLocation::PrimaryRight
 986                }
 987                EditorState::Idle => ToolbarItemLocation::Hidden,
 988            },
 989        }
 990    }
 991}
 992
 993impl EventEmitter<ToolbarItemEvent> for AgentDiffToolbar {}
 994
 995impl ToolbarItemView for AgentDiffToolbar {
 996    fn set_active_pane_item(
 997        &mut self,
 998        active_pane_item: Option<&dyn ItemHandle>,
 999        _: &mut Window,
1000        cx: &mut Context<Self>,
1001    ) -> ToolbarItemLocation {
1002        if let Some(item) = active_pane_item {
1003            if let Some(pane) = item.act_as::<AgentDiffPane>(cx) {
1004                self.active_item = Some(AgentDiffToolbarItem::Pane(pane.downgrade()));
1005                return self.location(cx);
1006            }
1007
1008            if let Some(editor) = item.act_as::<Editor>(cx)
1009                && editor.read(cx).mode().is_full()
1010            {
1011                let agent_diff = AgentDiff::global(cx);
1012
1013                self.active_item = Some(AgentDiffToolbarItem::Editor {
1014                    editor: editor.downgrade(),
1015                    state: agent_diff.read(cx).editor_state(&editor.downgrade()),
1016                    _diff_subscription: cx.observe(&agent_diff, Self::handle_diff_notify),
1017                });
1018
1019                return self.location(cx);
1020            }
1021        }
1022
1023        self.active_item = None;
1024        self.location(cx)
1025    }
1026
1027    fn pane_focus_update(
1028        &mut self,
1029        _pane_focused: bool,
1030        _window: &mut Window,
1031        _cx: &mut Context<Self>,
1032    ) {
1033    }
1034}
1035
1036impl Render for AgentDiffToolbar {
1037    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1038        let spinner_icon = div()
1039            .px_0p5()
1040            .id("generating")
1041            .tooltip(Tooltip::text("Generating Changes…"))
1042            .child(
1043                Icon::new(IconName::LoadCircle)
1044                    .size(IconSize::Small)
1045                    .color(Color::Accent)
1046                    .with_rotate_animation(3),
1047            )
1048            .into_any();
1049
1050        let Some(active_item) = self.active_item.as_ref() else {
1051            return Empty.into_any();
1052        };
1053
1054        match active_item {
1055            AgentDiffToolbarItem::Editor { editor, state, .. } => {
1056                let Some(editor) = editor.upgrade() else {
1057                    return Empty.into_any();
1058                };
1059
1060                let editor_focus_handle = editor.read(cx).focus_handle(cx);
1061
1062                let content = match state {
1063                    EditorState::Idle => return Empty.into_any(),
1064                    EditorState::Generating => vec![spinner_icon],
1065                    EditorState::Reviewing => vec![
1066                        h_flex()
1067                            .child(
1068                                IconButton::new("hunk-up", IconName::ArrowUp)
1069                                    .icon_size(IconSize::Small)
1070                                    .tooltip(Tooltip::for_action_title_in(
1071                                        "Previous Hunk",
1072                                        &GoToPreviousHunk,
1073                                        &editor_focus_handle,
1074                                    ))
1075                                    .on_click({
1076                                        let editor_focus_handle = editor_focus_handle.clone();
1077                                        move |_, window, cx| {
1078                                            editor_focus_handle.dispatch_action(
1079                                                &GoToPreviousHunk,
1080                                                window,
1081                                                cx,
1082                                            );
1083                                        }
1084                                    }),
1085                            )
1086                            .child(
1087                                IconButton::new("hunk-down", IconName::ArrowDown)
1088                                    .icon_size(IconSize::Small)
1089                                    .tooltip(Tooltip::for_action_title_in(
1090                                        "Next Hunk",
1091                                        &GoToHunk,
1092                                        &editor_focus_handle,
1093                                    ))
1094                                    .on_click({
1095                                        let editor_focus_handle = editor_focus_handle.clone();
1096                                        move |_, window, cx| {
1097                                            editor_focus_handle
1098                                                .dispatch_action(&GoToHunk, window, cx);
1099                                        }
1100                                    }),
1101                            )
1102                            .into_any_element(),
1103                        vertical_divider().into_any_element(),
1104                        h_flex()
1105                            .gap_0p5()
1106                            .child(
1107                                Button::new("reject-all", "Reject All")
1108                                    .key_binding({
1109                                        KeyBinding::for_action_in(
1110                                            &RejectAll,
1111                                            &editor_focus_handle,
1112                                            window,
1113                                            cx,
1114                                        )
1115                                        .map(|kb| kb.size(rems_from_px(12.)))
1116                                    })
1117                                    .on_click(cx.listener(|this, _, window, cx| {
1118                                        this.dispatch_action(&RejectAll, window, cx)
1119                                    })),
1120                            )
1121                            .child(
1122                                Button::new("keep-all", "Keep All")
1123                                    .key_binding({
1124                                        KeyBinding::for_action_in(
1125                                            &KeepAll,
1126                                            &editor_focus_handle,
1127                                            window,
1128                                            cx,
1129                                        )
1130                                        .map(|kb| kb.size(rems_from_px(12.)))
1131                                    })
1132                                    .on_click(cx.listener(|this, _, window, cx| {
1133                                        this.dispatch_action(&KeepAll, window, cx)
1134                                    })),
1135                            )
1136                            .into_any_element(),
1137                    ],
1138                };
1139
1140                h_flex()
1141                    .track_focus(&editor_focus_handle)
1142                    .size_full()
1143                    .px_1()
1144                    .mr_1()
1145                    .gap_1()
1146                    .children(content)
1147                    .child(vertical_divider())
1148                    .when_some(editor.read(cx).workspace(), |this, _workspace| {
1149                        this.child(
1150                            IconButton::new("review", IconName::ListTodo)
1151                                .icon_size(IconSize::Small)
1152                                .tooltip(Tooltip::for_action_title_in(
1153                                    "Review All Files",
1154                                    &OpenAgentDiff,
1155                                    &editor_focus_handle,
1156                                ))
1157                                .on_click({
1158                                    cx.listener(move |this, _, window, cx| {
1159                                        this.dispatch_action(&OpenAgentDiff, window, cx);
1160                                    })
1161                                }),
1162                        )
1163                    })
1164                    .child(vertical_divider())
1165                    .on_action({
1166                        let editor = editor.clone();
1167                        move |_action: &OpenAgentDiff, window, cx| {
1168                            AgentDiff::global(cx).update(cx, |agent_diff, cx| {
1169                                agent_diff.deploy_pane_from_editor(&editor, window, cx);
1170                            });
1171                        }
1172                    })
1173                    .into_any()
1174            }
1175            AgentDiffToolbarItem::Pane(agent_diff) => {
1176                let Some(agent_diff) = agent_diff.upgrade() else {
1177                    return Empty.into_any();
1178                };
1179
1180                let has_pending_edit_tool_use =
1181                    agent_diff.read(cx).thread.has_pending_edit_tool_uses(cx);
1182
1183                if has_pending_edit_tool_use {
1184                    return div().px_2().child(spinner_icon).into_any();
1185                }
1186
1187                let is_empty = agent_diff.read(cx).multibuffer.read(cx).is_empty();
1188                if is_empty {
1189                    return Empty.into_any();
1190                }
1191
1192                let focus_handle = agent_diff.focus_handle(cx);
1193
1194                h_group_xl()
1195                    .my_neg_1()
1196                    .py_1()
1197                    .items_center()
1198                    .flex_wrap()
1199                    .child(
1200                        h_group_sm()
1201                            .child(
1202                                Button::new("reject-all", "Reject All")
1203                                    .key_binding({
1204                                        KeyBinding::for_action_in(
1205                                            &RejectAll,
1206                                            &focus_handle,
1207                                            window,
1208                                            cx,
1209                                        )
1210                                        .map(|kb| kb.size(rems_from_px(12.)))
1211                                    })
1212                                    .on_click(cx.listener(|this, _, window, cx| {
1213                                        this.dispatch_action(&RejectAll, window, cx)
1214                                    })),
1215                            )
1216                            .child(
1217                                Button::new("keep-all", "Keep All")
1218                                    .key_binding({
1219                                        KeyBinding::for_action_in(
1220                                            &KeepAll,
1221                                            &focus_handle,
1222                                            window,
1223                                            cx,
1224                                        )
1225                                        .map(|kb| kb.size(rems_from_px(12.)))
1226                                    })
1227                                    .on_click(cx.listener(|this, _, window, cx| {
1228                                        this.dispatch_action(&KeepAll, window, cx)
1229                                    })),
1230                            ),
1231                    )
1232                    .into_any()
1233            }
1234        }
1235    }
1236}
1237
1238#[derive(Default)]
1239pub struct AgentDiff {
1240    reviewing_editors: HashMap<WeakEntity<Editor>, EditorState>,
1241    workspace_threads: HashMap<WeakEntity<Workspace>, WorkspaceThread>,
1242}
1243
1244#[derive(Clone, Debug, PartialEq, Eq)]
1245pub enum EditorState {
1246    Idle,
1247    Reviewing,
1248    Generating,
1249}
1250
1251struct WorkspaceThread {
1252    thread: WeakAgentDiffThread,
1253    _thread_subscriptions: (Subscription, Subscription),
1254    singleton_editors: HashMap<WeakEntity<Buffer>, HashMap<WeakEntity<Editor>, Subscription>>,
1255    _settings_subscription: Subscription,
1256    _workspace_subscription: Option<Subscription>,
1257}
1258
1259struct AgentDiffGlobal(Entity<AgentDiff>);
1260
1261impl Global for AgentDiffGlobal {}
1262
1263impl AgentDiff {
1264    fn global(cx: &mut App) -> Entity<Self> {
1265        cx.try_global::<AgentDiffGlobal>()
1266            .map(|global| global.0.clone())
1267            .unwrap_or_else(|| {
1268                let entity = cx.new(|_cx| Self::default());
1269                let global = AgentDiffGlobal(entity.clone());
1270                cx.set_global(global);
1271                entity
1272            })
1273    }
1274
1275    pub fn set_active_thread(
1276        workspace: &WeakEntity<Workspace>,
1277        thread: impl Into<AgentDiffThread>,
1278        window: &mut Window,
1279        cx: &mut App,
1280    ) {
1281        Self::global(cx).update(cx, |this, cx| {
1282            this.register_active_thread_impl(workspace, thread.into(), window, cx);
1283        });
1284    }
1285
1286    fn register_active_thread_impl(
1287        &mut self,
1288        workspace: &WeakEntity<Workspace>,
1289        thread: AgentDiffThread,
1290        window: &mut Window,
1291        cx: &mut Context<Self>,
1292    ) {
1293        let action_log = thread.action_log(cx);
1294
1295        let action_log_subscription = cx.observe_in(&action_log, window, {
1296            let workspace = workspace.clone();
1297            move |this, _action_log, window, cx| {
1298                this.update_reviewing_editors(&workspace, window, cx);
1299            }
1300        });
1301
1302        let thread_subscription = match &thread {
1303            AgentDiffThread::AcpThread(thread) => cx.subscribe_in(thread, window, {
1304                let workspace = workspace.clone();
1305                move |this, thread, event, window, cx| {
1306                    this.handle_acp_thread_event(&workspace, thread, event, window, cx)
1307                }
1308            }),
1309        };
1310
1311        if let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) {
1312            // replace thread and action log subscription, but keep editors
1313            workspace_thread.thread = thread.downgrade();
1314            workspace_thread._thread_subscriptions = (action_log_subscription, thread_subscription);
1315            self.update_reviewing_editors(workspace, window, cx);
1316            return;
1317        }
1318
1319        let settings_subscription = cx.observe_global_in::<SettingsStore>(window, {
1320            let workspace = workspace.clone();
1321            let mut was_active = AgentSettings::get_global(cx).single_file_review;
1322            move |this, window, cx| {
1323                let is_active = AgentSettings::get_global(cx).single_file_review;
1324                if was_active != is_active {
1325                    was_active = is_active;
1326                    this.update_reviewing_editors(&workspace, window, cx);
1327                }
1328            }
1329        });
1330
1331        let workspace_subscription = workspace
1332            .upgrade()
1333            .map(|workspace| cx.subscribe_in(&workspace, window, Self::handle_workspace_event));
1334
1335        self.workspace_threads.insert(
1336            workspace.clone(),
1337            WorkspaceThread {
1338                thread: thread.downgrade(),
1339                _thread_subscriptions: (action_log_subscription, thread_subscription),
1340                singleton_editors: HashMap::default(),
1341                _settings_subscription: settings_subscription,
1342                _workspace_subscription: workspace_subscription,
1343            },
1344        );
1345
1346        let workspace = workspace.clone();
1347        cx.defer_in(window, move |this, window, cx| {
1348            if let Some(workspace) = workspace.upgrade() {
1349                this.register_workspace(workspace, window, cx);
1350            }
1351        });
1352    }
1353
1354    fn register_workspace(
1355        &mut self,
1356        workspace: Entity<Workspace>,
1357        window: &mut Window,
1358        cx: &mut Context<Self>,
1359    ) {
1360        let agent_diff = cx.entity();
1361
1362        let editors = workspace.update(cx, |workspace, cx| {
1363            let agent_diff = agent_diff.clone();
1364
1365            Self::register_review_action::<Keep>(workspace, Self::keep, &agent_diff);
1366            Self::register_review_action::<Reject>(workspace, Self::reject, &agent_diff);
1367            Self::register_review_action::<KeepAll>(workspace, Self::keep_all, &agent_diff);
1368            Self::register_review_action::<RejectAll>(workspace, Self::reject_all, &agent_diff);
1369
1370            workspace.items_of_type(cx).collect::<Vec<_>>()
1371        });
1372
1373        let weak_workspace = workspace.downgrade();
1374
1375        for editor in editors {
1376            if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1377                self.register_editor(weak_workspace.clone(), buffer, editor, window, cx);
1378            };
1379        }
1380
1381        self.update_reviewing_editors(&weak_workspace, window, cx);
1382    }
1383
1384    fn register_review_action<T: Action>(
1385        workspace: &mut Workspace,
1386        review: impl Fn(&Entity<Editor>, &AgentDiffThread, &mut Window, &mut App) -> PostReviewState
1387        + 'static,
1388        this: &Entity<AgentDiff>,
1389    ) {
1390        let this = this.clone();
1391        workspace.register_action(move |workspace, _: &T, window, cx| {
1392            let review = &review;
1393            let task = this.update(cx, |this, cx| {
1394                this.review_in_active_editor(workspace, review, window, cx)
1395            });
1396
1397            if let Some(task) = task {
1398                task.detach_and_log_err(cx);
1399            } else {
1400                cx.propagate();
1401            }
1402        });
1403    }
1404
1405    fn handle_acp_thread_event(
1406        &mut self,
1407        workspace: &WeakEntity<Workspace>,
1408        thread: &Entity<AcpThread>,
1409        event: &AcpThreadEvent,
1410        window: &mut Window,
1411        cx: &mut Context<Self>,
1412    ) {
1413        match event {
1414            AcpThreadEvent::NewEntry => {
1415                if thread
1416                    .read(cx)
1417                    .entries()
1418                    .last()
1419                    .is_some_and(|entry| entry.diffs().next().is_some())
1420                {
1421                    self.update_reviewing_editors(workspace, window, cx);
1422                }
1423            }
1424            AcpThreadEvent::EntryUpdated(ix) => {
1425                if thread
1426                    .read(cx)
1427                    .entries()
1428                    .get(*ix)
1429                    .is_some_and(|entry| entry.diffs().next().is_some())
1430                {
1431                    self.update_reviewing_editors(workspace, window, cx);
1432                }
1433            }
1434            AcpThreadEvent::Stopped
1435            | AcpThreadEvent::Error
1436            | AcpThreadEvent::LoadError(_)
1437            | AcpThreadEvent::Refusal => {
1438                self.update_reviewing_editors(workspace, window, cx);
1439            }
1440            AcpThreadEvent::TitleUpdated
1441            | AcpThreadEvent::TokenUsageUpdated
1442            | AcpThreadEvent::EntriesRemoved(_)
1443            | AcpThreadEvent::ToolAuthorizationRequired
1444            | AcpThreadEvent::PromptCapabilitiesUpdated
1445            | AcpThreadEvent::AvailableCommandsUpdated(_)
1446            | AcpThreadEvent::Retry(_)
1447            | AcpThreadEvent::ModeUpdated(_) => {}
1448        }
1449    }
1450
1451    fn handle_workspace_event(
1452        &mut self,
1453        workspace: &Entity<Workspace>,
1454        event: &workspace::Event,
1455        window: &mut Window,
1456        cx: &mut Context<Self>,
1457    ) {
1458        if let workspace::Event::ItemAdded { item } = event
1459            && let Some(editor) = item.downcast::<Editor>()
1460            && let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx)
1461        {
1462            self.register_editor(workspace.downgrade(), buffer, editor, window, cx);
1463        }
1464    }
1465
1466    fn full_editor_buffer(editor: &Editor, cx: &App) -> Option<WeakEntity<Buffer>> {
1467        if editor.mode().is_full() {
1468            editor
1469                .buffer()
1470                .read(cx)
1471                .as_singleton()
1472                .map(|buffer| buffer.downgrade())
1473        } else {
1474            None
1475        }
1476    }
1477
1478    fn register_editor(
1479        &mut self,
1480        workspace: WeakEntity<Workspace>,
1481        buffer: WeakEntity<Buffer>,
1482        editor: Entity<Editor>,
1483        window: &mut Window,
1484        cx: &mut Context<Self>,
1485    ) {
1486        let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) else {
1487            return;
1488        };
1489
1490        let weak_editor = editor.downgrade();
1491
1492        workspace_thread
1493            .singleton_editors
1494            .entry(buffer.clone())
1495            .or_default()
1496            .entry(weak_editor.clone())
1497            .or_insert_with(|| {
1498                let workspace = workspace.clone();
1499                cx.observe_release(&editor, move |this, _, _cx| {
1500                    let Some(active_thread) = this.workspace_threads.get_mut(&workspace) else {
1501                        return;
1502                    };
1503
1504                    if let Entry::Occupied(mut entry) =
1505                        active_thread.singleton_editors.entry(buffer)
1506                    {
1507                        let set = entry.get_mut();
1508                        set.remove(&weak_editor);
1509
1510                        if set.is_empty() {
1511                            entry.remove();
1512                        }
1513                    }
1514                })
1515            });
1516
1517        self.update_reviewing_editors(&workspace, window, cx);
1518    }
1519
1520    fn update_reviewing_editors(
1521        &mut self,
1522        workspace: &WeakEntity<Workspace>,
1523        window: &mut Window,
1524        cx: &mut Context<Self>,
1525    ) {
1526        if !AgentSettings::get_global(cx).single_file_review {
1527            for (editor, _) in self.reviewing_editors.drain() {
1528                editor
1529                    .update(cx, |editor, cx| {
1530                        editor.end_temporary_diff_override(cx);
1531                        editor.unregister_addon::<EditorAgentDiffAddon>();
1532                    })
1533                    .ok();
1534            }
1535            return;
1536        }
1537
1538        let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) else {
1539            return;
1540        };
1541
1542        let Some(thread) = workspace_thread.thread.upgrade() else {
1543            return;
1544        };
1545
1546        let action_log = thread.action_log(cx);
1547        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1548
1549        let mut unaffected = self.reviewing_editors.clone();
1550
1551        for (buffer, diff_handle) in changed_buffers {
1552            if buffer.read(cx).file().is_none() {
1553                continue;
1554            }
1555
1556            let Some(buffer_editors) = workspace_thread.singleton_editors.get(&buffer.downgrade())
1557            else {
1558                continue;
1559            };
1560
1561            for weak_editor in buffer_editors.keys() {
1562                let Some(editor) = weak_editor.upgrade() else {
1563                    continue;
1564                };
1565
1566                let multibuffer = editor.read(cx).buffer().clone();
1567                multibuffer.update(cx, |multibuffer, cx| {
1568                    multibuffer.add_diff(diff_handle.clone(), cx);
1569                });
1570
1571                let new_state = if thread.is_generating(cx) {
1572                    EditorState::Generating
1573                } else {
1574                    EditorState::Reviewing
1575                };
1576
1577                let previous_state = self
1578                    .reviewing_editors
1579                    .insert(weak_editor.clone(), new_state.clone());
1580
1581                if previous_state.is_none() {
1582                    editor.update(cx, |editor, cx| {
1583                        editor.start_temporary_diff_override();
1584                        editor.set_render_diff_hunk_controls(diff_hunk_controls(&thread), cx);
1585                        editor.set_expand_all_diff_hunks(cx);
1586                        editor.register_addon(EditorAgentDiffAddon);
1587                    });
1588                } else {
1589                    unaffected.remove(weak_editor);
1590                }
1591
1592                if new_state == EditorState::Reviewing && previous_state != Some(new_state) {
1593                    // Jump to first hunk when we enter review mode
1594                    editor.update(cx, |editor, cx| {
1595                        let snapshot = multibuffer.read(cx).snapshot(cx);
1596                        if let Some(first_hunk) = snapshot.diff_hunks().next() {
1597                            let first_hunk_start = first_hunk.multi_buffer_range().start;
1598
1599                            editor.change_selections(
1600                                SelectionEffects::scroll(Autoscroll::center()),
1601                                window,
1602                                cx,
1603                                |selections| {
1604                                    selections.select_ranges([first_hunk_start..first_hunk_start])
1605                                },
1606                            );
1607                        }
1608                    });
1609                }
1610            }
1611        }
1612
1613        // Remove editors from this workspace that are no longer under review
1614        for (editor, _) in unaffected {
1615            // Note: We could avoid this check by storing `reviewing_editors` by Workspace,
1616            // but that would add another lookup in `AgentDiff::editor_state`
1617            // which gets called much more frequently.
1618            let in_workspace = editor
1619                .read_with(cx, |editor, _cx| editor.workspace())
1620                .ok()
1621                .flatten()
1622                .is_some_and(|editor_workspace| {
1623                    editor_workspace.entity_id() == workspace.entity_id()
1624                });
1625
1626            if in_workspace {
1627                editor
1628                    .update(cx, |editor, cx| {
1629                        editor.end_temporary_diff_override(cx);
1630                        editor.unregister_addon::<EditorAgentDiffAddon>();
1631                    })
1632                    .ok();
1633                self.reviewing_editors.remove(&editor);
1634            }
1635        }
1636
1637        cx.notify();
1638    }
1639
1640    fn editor_state(&self, editor: &WeakEntity<Editor>) -> EditorState {
1641        self.reviewing_editors
1642            .get(editor)
1643            .cloned()
1644            .unwrap_or(EditorState::Idle)
1645    }
1646
1647    fn deploy_pane_from_editor(&self, editor: &Entity<Editor>, window: &mut Window, cx: &mut App) {
1648        let Some(workspace) = editor.read(cx).workspace() else {
1649            return;
1650        };
1651
1652        let Some(WorkspaceThread { thread, .. }) =
1653            self.workspace_threads.get(&workspace.downgrade())
1654        else {
1655            return;
1656        };
1657
1658        let Some(thread) = thread.upgrade() else {
1659            return;
1660        };
1661
1662        AgentDiffPane::deploy(thread, workspace.downgrade(), window, cx).log_err();
1663    }
1664
1665    fn keep_all(
1666        editor: &Entity<Editor>,
1667        thread: &AgentDiffThread,
1668        window: &mut Window,
1669        cx: &mut App,
1670    ) -> PostReviewState {
1671        editor.update(cx, |editor, cx| {
1672            let snapshot = editor.buffer().read(cx).snapshot(cx);
1673            keep_edits_in_ranges(
1674                editor,
1675                &snapshot,
1676                thread,
1677                vec![editor::Anchor::min()..editor::Anchor::max()],
1678                window,
1679                cx,
1680            );
1681        });
1682        PostReviewState::AllReviewed
1683    }
1684
1685    fn reject_all(
1686        editor: &Entity<Editor>,
1687        thread: &AgentDiffThread,
1688        window: &mut Window,
1689        cx: &mut App,
1690    ) -> PostReviewState {
1691        editor.update(cx, |editor, cx| {
1692            let snapshot = editor.buffer().read(cx).snapshot(cx);
1693            reject_edits_in_ranges(
1694                editor,
1695                &snapshot,
1696                thread,
1697                vec![editor::Anchor::min()..editor::Anchor::max()],
1698                window,
1699                cx,
1700            );
1701        });
1702        PostReviewState::AllReviewed
1703    }
1704
1705    fn keep(
1706        editor: &Entity<Editor>,
1707        thread: &AgentDiffThread,
1708        window: &mut Window,
1709        cx: &mut App,
1710    ) -> PostReviewState {
1711        editor.update(cx, |editor, cx| {
1712            let snapshot = editor.buffer().read(cx).snapshot(cx);
1713            keep_edits_in_selection(editor, &snapshot, thread, window, cx);
1714            Self::post_review_state(&snapshot)
1715        })
1716    }
1717
1718    fn reject(
1719        editor: &Entity<Editor>,
1720        thread: &AgentDiffThread,
1721        window: &mut Window,
1722        cx: &mut App,
1723    ) -> PostReviewState {
1724        editor.update(cx, |editor, cx| {
1725            let snapshot = editor.buffer().read(cx).snapshot(cx);
1726            reject_edits_in_selection(editor, &snapshot, thread, window, cx);
1727            Self::post_review_state(&snapshot)
1728        })
1729    }
1730
1731    fn post_review_state(snapshot: &MultiBufferSnapshot) -> PostReviewState {
1732        for (i, _) in snapshot.diff_hunks().enumerate() {
1733            if i > 0 {
1734                return PostReviewState::Pending;
1735            }
1736        }
1737        PostReviewState::AllReviewed
1738    }
1739
1740    fn review_in_active_editor(
1741        &mut self,
1742        workspace: &mut Workspace,
1743        review: impl Fn(&Entity<Editor>, &AgentDiffThread, &mut Window, &mut App) -> PostReviewState,
1744        window: &mut Window,
1745        cx: &mut Context<Self>,
1746    ) -> Option<Task<Result<()>>> {
1747        let active_item = workspace.active_item(cx)?;
1748        let editor = active_item.act_as::<Editor>(cx)?;
1749
1750        if !matches!(
1751            self.editor_state(&editor.downgrade()),
1752            EditorState::Reviewing
1753        ) {
1754            return None;
1755        }
1756
1757        let WorkspaceThread { thread, .. } =
1758            self.workspace_threads.get(&workspace.weak_handle())?;
1759
1760        let thread = thread.upgrade()?;
1761
1762        if let PostReviewState::AllReviewed = review(&editor, &thread, window, cx)
1763            && let Some(curr_buffer) = editor.read(cx).buffer().read(cx).as_singleton()
1764        {
1765            let changed_buffers = thread.action_log(cx).read(cx).changed_buffers(cx);
1766
1767            let mut keys = changed_buffers.keys().cycle();
1768            keys.find(|k| *k == &curr_buffer);
1769            let next_project_path = keys
1770                .next()
1771                .filter(|k| *k != &curr_buffer)
1772                .and_then(|after| after.read(cx).project_path(cx));
1773
1774            if let Some(path) = next_project_path {
1775                let task = workspace.open_path(path, None, true, window, cx);
1776                let task = cx.spawn(async move |_, _cx| task.await.map(|_| ()));
1777                return Some(task);
1778            }
1779        }
1780
1781        Some(Task::ready(Ok(())))
1782    }
1783}
1784
1785enum PostReviewState {
1786    AllReviewed,
1787    Pending,
1788}
1789
1790pub struct EditorAgentDiffAddon;
1791
1792impl editor::Addon for EditorAgentDiffAddon {
1793    fn to_any(&self) -> &dyn std::any::Any {
1794        self
1795    }
1796
1797    fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
1798        key_context.add("agent_diff");
1799        key_context.add("editor_agent_diff");
1800    }
1801}
1802
1803#[cfg(test)]
1804mod tests {
1805    use super::*;
1806    use crate::Keep;
1807    use acp_thread::AgentConnection as _;
1808    use agent_settings::AgentSettings;
1809    use editor::EditorSettings;
1810    use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
1811    use project::{FakeFs, Project};
1812    use serde_json::json;
1813    use settings::{Settings, SettingsStore};
1814    use std::{path::Path, rc::Rc};
1815    use util::path;
1816
1817    #[gpui::test]
1818    async fn test_multibuffer_agent_diff(cx: &mut TestAppContext) {
1819        cx.update(|cx| {
1820            let settings_store = SettingsStore::test(cx);
1821            cx.set_global(settings_store);
1822            language::init(cx);
1823            Project::init_settings(cx);
1824            AgentSettings::register(cx);
1825            prompt_store::init(cx);
1826            workspace::init_settings(cx);
1827            theme::init(theme::LoadThemes::JustBase, cx);
1828            EditorSettings::register(cx);
1829            language_model::init_settings(cx);
1830        });
1831
1832        let fs = FakeFs::new(cx.executor());
1833        fs.insert_tree(
1834            path!("/test"),
1835            json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1836        )
1837        .await;
1838        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1839        let buffer_path = project
1840            .read_with(cx, |project, cx| {
1841                project.find_project_path("test/file1", cx)
1842            })
1843            .unwrap();
1844
1845        let connection = Rc::new(acp_thread::StubAgentConnection::new());
1846        let thread = cx
1847            .update(|cx| {
1848                connection
1849                    .clone()
1850                    .new_thread(project.clone(), Path::new(path!("/test")), cx)
1851            })
1852            .await
1853            .unwrap();
1854
1855        let thread = AgentDiffThread::AcpThread(thread);
1856        let action_log = cx.read(|cx| thread.action_log(cx));
1857
1858        let (workspace, cx) =
1859            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1860        let agent_diff = cx.new_window_entity(|window, cx| {
1861            AgentDiffPane::new(thread.clone(), workspace.downgrade(), window, cx)
1862        });
1863        let editor = agent_diff.read_with(cx, |diff, _cx| diff.editor.clone());
1864
1865        let buffer = project
1866            .update(cx, |project, cx| project.open_buffer(buffer_path, cx))
1867            .await
1868            .unwrap();
1869        cx.update(|_, cx| {
1870            action_log.update(cx, |log, cx| log.buffer_read(buffer.clone(), cx));
1871            buffer.update(cx, |buffer, cx| {
1872                buffer
1873                    .edit(
1874                        [
1875                            (Point::new(1, 1)..Point::new(1, 2), "E"),
1876                            (Point::new(3, 2)..Point::new(3, 3), "L"),
1877                            (Point::new(5, 0)..Point::new(5, 1), "P"),
1878                            (Point::new(7, 1)..Point::new(7, 2), "W"),
1879                        ],
1880                        None,
1881                        cx,
1882                    )
1883                    .unwrap()
1884            });
1885            action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
1886        });
1887        cx.run_until_parked();
1888
1889        // When opening the assistant diff, the cursor is positioned on the first hunk.
1890        assert_eq!(
1891            editor.read_with(cx, |editor, cx| editor.text(cx)),
1892            "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1893        );
1894        assert_eq!(
1895            editor
1896                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1897                .range(),
1898            Point::new(1, 0)..Point::new(1, 0)
1899        );
1900
1901        // After keeping a hunk, the cursor should be positioned on the second hunk.
1902        agent_diff.update_in(cx, |diff, window, cx| diff.keep(&Keep, window, cx));
1903        cx.run_until_parked();
1904        assert_eq!(
1905            editor.read_with(cx, |editor, cx| editor.text(cx)),
1906            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1907        );
1908        assert_eq!(
1909            editor
1910                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1911                .range(),
1912            Point::new(3, 0)..Point::new(3, 0)
1913        );
1914
1915        // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
1916        editor.update_in(cx, |editor, window, cx| {
1917            editor.change_selections(SelectionEffects::no_scroll(), window, cx, |selections| {
1918                selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
1919            });
1920        });
1921        agent_diff.update_in(cx, |diff, window, cx| {
1922            diff.reject(&crate::Reject, window, cx)
1923        });
1924        cx.run_until_parked();
1925        assert_eq!(
1926            editor.read_with(cx, |editor, cx| editor.text(cx)),
1927            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
1928        );
1929        assert_eq!(
1930            editor
1931                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1932                .range(),
1933            Point::new(3, 0)..Point::new(3, 0)
1934        );
1935
1936        // Keeping a range that doesn't intersect the current selection doesn't move it.
1937        agent_diff.update_in(cx, |_diff, window, cx| {
1938            let position = editor
1939                .read(cx)
1940                .buffer()
1941                .read(cx)
1942                .read(cx)
1943                .anchor_before(Point::new(7, 0));
1944            editor.update(cx, |editor, cx| {
1945                let snapshot = editor.buffer().read(cx).snapshot(cx);
1946                keep_edits_in_ranges(
1947                    editor,
1948                    &snapshot,
1949                    &thread,
1950                    vec![position..position],
1951                    window,
1952                    cx,
1953                )
1954            });
1955        });
1956        cx.run_until_parked();
1957        assert_eq!(
1958            editor.read_with(cx, |editor, cx| editor.text(cx)),
1959            "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
1960        );
1961        assert_eq!(
1962            editor
1963                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1964                .range(),
1965            Point::new(3, 0)..Point::new(3, 0)
1966        );
1967    }
1968
1969    #[gpui::test]
1970    async fn test_singleton_agent_diff(cx: &mut TestAppContext) {
1971        cx.update(|cx| {
1972            let settings_store = SettingsStore::test(cx);
1973            cx.set_global(settings_store);
1974            language::init(cx);
1975            Project::init_settings(cx);
1976            AgentSettings::register(cx);
1977            prompt_store::init(cx);
1978            workspace::init_settings(cx);
1979            theme::init(theme::LoadThemes::JustBase, cx);
1980            EditorSettings::register(cx);
1981            language_model::init_settings(cx);
1982            workspace::register_project_item::<Editor>(cx);
1983        });
1984
1985        let fs = FakeFs::new(cx.executor());
1986        fs.insert_tree(
1987            path!("/test"),
1988            json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1989        )
1990        .await;
1991        fs.insert_tree(path!("/test"), json!({"file2": "abc\ndef\nghi"}))
1992            .await;
1993
1994        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1995        let buffer_path1 = project
1996            .read_with(cx, |project, cx| {
1997                project.find_project_path("test/file1", cx)
1998            })
1999            .unwrap();
2000        let buffer_path2 = project
2001            .read_with(cx, |project, cx| {
2002                project.find_project_path("test/file2", cx)
2003            })
2004            .unwrap();
2005
2006        let (workspace, cx) =
2007            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2008
2009        // Add the diff toolbar to the active pane
2010        let diff_toolbar = cx.new_window_entity(|_, cx| AgentDiffToolbar::new(cx));
2011
2012        workspace.update_in(cx, {
2013            let diff_toolbar = diff_toolbar.clone();
2014
2015            move |workspace, window, cx| {
2016                workspace.active_pane().update(cx, |pane, cx| {
2017                    pane.toolbar().update(cx, |toolbar, cx| {
2018                        toolbar.add_item(diff_toolbar, window, cx);
2019                    });
2020                })
2021            }
2022        });
2023
2024        let connection = Rc::new(acp_thread::StubAgentConnection::new());
2025        let thread = cx
2026            .update(|_, cx| {
2027                connection
2028                    .clone()
2029                    .new_thread(project.clone(), Path::new(path!("/test")), cx)
2030            })
2031            .await
2032            .unwrap();
2033        let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
2034
2035        // Set the active thread
2036        let thread = AgentDiffThread::AcpThread(thread);
2037        cx.update(|window, cx| {
2038            AgentDiff::set_active_thread(&workspace.downgrade(), thread.clone(), window, cx)
2039        });
2040
2041        let buffer1 = project
2042            .update(cx, |project, cx| {
2043                project.open_buffer(buffer_path1.clone(), cx)
2044            })
2045            .await
2046            .unwrap();
2047        let buffer2 = project
2048            .update(cx, |project, cx| {
2049                project.open_buffer(buffer_path2.clone(), cx)
2050            })
2051            .await
2052            .unwrap();
2053
2054        // Open an editor for buffer1
2055        let editor1 = cx.new_window_entity(|window, cx| {
2056            Editor::for_buffer(buffer1.clone(), Some(project.clone()), window, cx)
2057        });
2058
2059        workspace.update_in(cx, |workspace, window, cx| {
2060            workspace.add_item_to_active_pane(Box::new(editor1.clone()), None, true, window, cx);
2061        });
2062        cx.run_until_parked();
2063
2064        // Toolbar knows about the current editor, but it's hidden since there are no changes yet
2065        assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2066            toolbar.active_item,
2067            Some(AgentDiffToolbarItem::Editor {
2068                state: EditorState::Idle,
2069                ..
2070            })
2071        )));
2072        assert_eq!(
2073            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2074            ToolbarItemLocation::Hidden
2075        );
2076
2077        // Make changes
2078        cx.update(|_, cx| {
2079            action_log.update(cx, |log, cx| log.buffer_read(buffer1.clone(), cx));
2080            buffer1.update(cx, |buffer, cx| {
2081                buffer
2082                    .edit(
2083                        [
2084                            (Point::new(1, 1)..Point::new(1, 2), "E"),
2085                            (Point::new(3, 2)..Point::new(3, 3), "L"),
2086                            (Point::new(5, 0)..Point::new(5, 1), "P"),
2087                            (Point::new(7, 1)..Point::new(7, 2), "W"),
2088                        ],
2089                        None,
2090                        cx,
2091                    )
2092                    .unwrap()
2093            });
2094            action_log.update(cx, |log, cx| log.buffer_edited(buffer1.clone(), cx));
2095
2096            action_log.update(cx, |log, cx| log.buffer_read(buffer2.clone(), cx));
2097            buffer2.update(cx, |buffer, cx| {
2098                buffer
2099                    .edit(
2100                        [
2101                            (Point::new(0, 0)..Point::new(0, 1), "A"),
2102                            (Point::new(2, 1)..Point::new(2, 2), "H"),
2103                        ],
2104                        None,
2105                        cx,
2106                    )
2107                    .unwrap();
2108            });
2109            action_log.update(cx, |log, cx| log.buffer_edited(buffer2.clone(), cx));
2110        });
2111        cx.run_until_parked();
2112
2113        // The already opened editor displays the diff and the cursor is at the first hunk
2114        assert_eq!(
2115            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2116            "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2117        );
2118        assert_eq!(
2119            editor1
2120                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2121                .range(),
2122            Point::new(1, 0)..Point::new(1, 0)
2123        );
2124
2125        // The toolbar is displayed in the right state
2126        assert_eq!(
2127            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2128            ToolbarItemLocation::PrimaryRight
2129        );
2130        assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2131            toolbar.active_item,
2132            Some(AgentDiffToolbarItem::Editor {
2133                state: EditorState::Reviewing,
2134                ..
2135            })
2136        )));
2137
2138        // The toolbar respects its setting
2139        override_toolbar_agent_review_setting(false, cx);
2140        assert_eq!(
2141            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2142            ToolbarItemLocation::Hidden
2143        );
2144        override_toolbar_agent_review_setting(true, cx);
2145        assert_eq!(
2146            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2147            ToolbarItemLocation::PrimaryRight
2148        );
2149
2150        // After keeping a hunk, the cursor should be positioned on the second hunk.
2151        workspace.update(cx, |_, cx| {
2152            cx.dispatch_action(&Keep);
2153        });
2154        cx.run_until_parked();
2155        assert_eq!(
2156            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2157            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2158        );
2159        assert_eq!(
2160            editor1
2161                .update(cx, |editor, cx| editor.selections.newest::<Point>(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.selections.newest::<Point>(cx))
2183                .range(),
2184            Point::new(3, 0)..Point::new(3, 0)
2185        );
2186
2187        // Keeping a range that doesn't intersect the current selection doesn't move it.
2188        editor1.update_in(cx, |editor, window, cx| {
2189            let buffer = editor.buffer().read(cx);
2190            let position = buffer.read(cx).anchor_before(Point::new(7, 0));
2191            let snapshot = buffer.snapshot(cx);
2192            keep_edits_in_ranges(
2193                editor,
2194                &snapshot,
2195                &thread,
2196                vec![position..position],
2197                window,
2198                cx,
2199            )
2200        });
2201        cx.run_until_parked();
2202        assert_eq!(
2203            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2204            "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
2205        );
2206        assert_eq!(
2207            editor1
2208                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2209                .range(),
2210            Point::new(3, 0)..Point::new(3, 0)
2211        );
2212
2213        // Reviewing the last change opens the next changed buffer
2214        workspace
2215            .update_in(cx, |workspace, window, cx| {
2216                AgentDiff::global(cx).update(cx, |agent_diff, cx| {
2217                    agent_diff.review_in_active_editor(workspace, AgentDiff::keep, window, cx)
2218                })
2219            })
2220            .unwrap()
2221            .await
2222            .unwrap();
2223
2224        cx.run_until_parked();
2225
2226        let editor2 = workspace.update(cx, |workspace, cx| {
2227            workspace.active_item_as::<Editor>(cx).unwrap()
2228        });
2229
2230        let editor2_path = editor2
2231            .read_with(cx, |editor, cx| editor.project_path(cx))
2232            .unwrap();
2233        assert_eq!(editor2_path, buffer_path2);
2234
2235        assert_eq!(
2236            editor2.read_with(cx, |editor, cx| editor.text(cx)),
2237            "abc\nAbc\ndef\nghi\ngHi"
2238        );
2239        assert_eq!(
2240            editor2
2241                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2242                .range(),
2243            Point::new(0, 0)..Point::new(0, 0)
2244        );
2245
2246        // Editor 1 toolbar is hidden since all changes have been reviewed
2247        workspace.update_in(cx, |workspace, window, cx| {
2248            workspace.activate_item(&editor1, true, true, window, cx)
2249        });
2250
2251        assert!(diff_toolbar.read_with(cx, |toolbar, _cx| matches!(
2252            toolbar.active_item,
2253            Some(AgentDiffToolbarItem::Editor {
2254                state: EditorState::Idle,
2255                ..
2256            })
2257        )));
2258        assert_eq!(
2259            diff_toolbar.read_with(cx, |toolbar, cx| toolbar.location(cx)),
2260            ToolbarItemLocation::Hidden
2261        );
2262    }
2263
2264    fn override_toolbar_agent_review_setting(active: bool, cx: &mut VisualTestContext) {
2265        cx.update(|_window, cx| {
2266            SettingsStore::update_global(cx, |store, _cx| {
2267                let mut editor_settings = store.get::<EditorSettings>(None).clone();
2268                editor_settings.toolbar.agent_review = active;
2269                store.override_global(editor_settings);
2270            })
2271        });
2272        cx.run_until_parked();
2273    }
2274}