agent_diff.rs

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