agent_diff.rs

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