agent_diff.rs

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