agent_diff.rs

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