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