agent_diff.rs

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