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, 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::{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}
 871
 872pub enum AgentDiffToolbarItem {
 873    Pane(WeakEntity<AgentDiffPane>),
 874    Editor {
 875        editor: WeakEntity<Editor>,
 876        _diff_subscription: Subscription,
 877    },
 878}
 879
 880impl AgentDiffToolbar {
 881    pub fn new() -> Self {
 882        Self { active_item: None }
 883    }
 884
 885    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
 886        let Some(active_item) = self.active_item.as_ref() else {
 887            return;
 888        };
 889
 890        match active_item {
 891            AgentDiffToolbarItem::Pane(agent_diff) => {
 892                if let Some(agent_diff) = agent_diff.upgrade() {
 893                    agent_diff.focus_handle(cx).focus(window);
 894                }
 895            }
 896            AgentDiffToolbarItem::Editor { editor, .. } => {
 897                if let Some(editor) = editor.upgrade() {
 898                    editor.read(cx).focus_handle(cx).focus(window);
 899                }
 900            }
 901        }
 902
 903        let action = action.boxed_clone();
 904        cx.defer(move |cx| {
 905            cx.dispatch_action(action.as_ref());
 906        })
 907    }
 908}
 909
 910impl EventEmitter<ToolbarItemEvent> for AgentDiffToolbar {}
 911
 912impl ToolbarItemView for AgentDiffToolbar {
 913    fn set_active_pane_item(
 914        &mut self,
 915        active_pane_item: Option<&dyn ItemHandle>,
 916        _: &mut Window,
 917        cx: &mut Context<Self>,
 918    ) -> ToolbarItemLocation {
 919        if let Some(item) = active_pane_item {
 920            if let Some(pane) = item.act_as::<AgentDiffPane>(cx) {
 921                self.active_item = Some(AgentDiffToolbarItem::Pane(pane.downgrade()));
 922                return ToolbarItemLocation::PrimaryRight;
 923            }
 924
 925            if let Some(editor) = item.act_as::<Editor>(cx) {
 926                if editor.read(cx).mode().is_full() {
 927                    let agent_diff = AgentDiff::global(cx);
 928
 929                    self.active_item = Some(AgentDiffToolbarItem::Editor {
 930                        editor: editor.downgrade(),
 931                        _diff_subscription: cx.observe(&agent_diff, |_, _, cx| {
 932                            cx.notify();
 933                        }),
 934                    });
 935
 936                    return ToolbarItemLocation::PrimaryLeft;
 937                }
 938            }
 939        }
 940
 941        self.active_item = None;
 942        ToolbarItemLocation::Hidden
 943    }
 944
 945    fn pane_focus_update(
 946        &mut self,
 947        _pane_focused: bool,
 948        _window: &mut Window,
 949        _cx: &mut Context<Self>,
 950    ) {
 951    }
 952}
 953
 954impl Render for AgentDiffToolbar {
 955    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 956        let Some(active_item) = self.active_item.as_ref() else {
 957            return Empty.into_any();
 958        };
 959
 960        match active_item {
 961            AgentDiffToolbarItem::Editor { editor, .. } => {
 962                let Some(editor) = editor.upgrade() else {
 963                    return Empty.into_any();
 964                };
 965
 966                let agent_diff = AgentDiff::global(cx);
 967                let editor_focus_handle = editor.read(cx).focus_handle(cx);
 968
 969                let content = match agent_diff.read(cx).editor_state(&editor) {
 970                    EditorState::Idle => return Empty.into_any(),
 971                    EditorState::Generating => vec![
 972                        h_flex()
 973                            .ml_1()
 974                            .gap_1p5()
 975                            .w_32()
 976                            .child(Icon::new(IconName::ZedAssistant))
 977                            .child(
 978                                div()
 979                                    .w(rems(6.5625))
 980                                    .child(AnimatedLabel::new("Generating")),
 981                            )
 982                            .into_any(),
 983                    ],
 984                    EditorState::Reviewing => vec![
 985                        h_flex()
 986                            .child(
 987                                IconButton::new("hunk-up", IconName::ArrowUp)
 988                                    .tooltip(ui::Tooltip::for_action_title_in(
 989                                        "Previous Hunk",
 990                                        &GoToPreviousHunk,
 991                                        &editor_focus_handle,
 992                                    ))
 993                                    .on_click({
 994                                        let editor_focus_handle = editor_focus_handle.clone();
 995                                        move |_, window, cx| {
 996                                            editor_focus_handle.dispatch_action(
 997                                                &GoToPreviousHunk,
 998                                                window,
 999                                                cx,
1000                                            );
1001                                        }
1002                                    }),
1003                            )
1004                            .child(
1005                                IconButton::new("hunk-down", IconName::ArrowDown)
1006                                    .tooltip(ui::Tooltip::for_action_title_in(
1007                                        "Next Hunk",
1008                                        &GoToHunk,
1009                                        &editor_focus_handle,
1010                                    ))
1011                                    .on_click({
1012                                        let editor_focus_handle = editor_focus_handle.clone();
1013                                        move |_, window, cx| {
1014                                            editor_focus_handle
1015                                                .dispatch_action(&GoToHunk, window, cx);
1016                                        }
1017                                    }),
1018                            )
1019                            .into_any(),
1020                        vertical_divider().into_any_element(),
1021                        h_flex()
1022                            .child(
1023                                Button::new("reject-all", "Reject All")
1024                                    .key_binding({
1025                                        KeyBinding::for_action_in(
1026                                            &RejectAll,
1027                                            &editor_focus_handle,
1028                                            window,
1029                                            cx,
1030                                        )
1031                                        .map(|kb| kb.size(rems_from_px(12.)))
1032                                    })
1033                                    .on_click(cx.listener(|this, _, window, cx| {
1034                                        this.dispatch_action(&RejectAll, window, cx)
1035                                    })),
1036                            )
1037                            .child(
1038                                Button::new("keep-all", "Keep All")
1039                                    .key_binding({
1040                                        KeyBinding::for_action_in(
1041                                            &KeepAll,
1042                                            &editor_focus_handle,
1043                                            window,
1044                                            cx,
1045                                        )
1046                                        .map(|kb| kb.size(rems_from_px(12.)))
1047                                    })
1048                                    .on_click(cx.listener(|this, _, window, cx| {
1049                                        this.dispatch_action(&KeepAll, window, cx)
1050                                    })),
1051                            )
1052                            .into_any(),
1053                    ],
1054                };
1055
1056                h_flex()
1057                    .bg(cx.theme().colors().surface_background)
1058                    .rounded_md()
1059                    .p_1()
1060                    .mx_2()
1061                    .gap_1()
1062                    .children(content)
1063                    .child(vertical_divider())
1064                    .track_focus(&editor_focus_handle)
1065                    .on_action({
1066                        let agent_diff = agent_diff.clone();
1067                        let editor = editor.clone();
1068                        move |_action: &OpenAgentDiff, window, cx| {
1069                            agent_diff.update(cx, |agent_diff, cx| {
1070                                agent_diff.deploy_pane_from_editor(&editor, window, cx);
1071                            });
1072                        }
1073                    })
1074                    .when_some(editor.read(cx).workspace(), |this, _workspace| {
1075                        this.child(
1076                            IconButton::new("review", IconName::ListTree)
1077                                .tooltip(ui::Tooltip::for_action_title_in(
1078                                    "Review All Files",
1079                                    &OpenAgentDiff,
1080                                    &editor_focus_handle,
1081                                ))
1082                                .on_click({
1083                                    cx.listener(move |this, _, window, cx| {
1084                                        this.dispatch_action(&OpenAgentDiff, window, cx);
1085                                    })
1086                                }),
1087                        )
1088                    })
1089                    .into_any()
1090            }
1091            AgentDiffToolbarItem::Pane(agent_diff) => {
1092                let Some(agent_diff) = agent_diff.upgrade() else {
1093                    return Empty.into_any();
1094                };
1095
1096                let is_generating = agent_diff.read(cx).thread.read(cx).is_generating();
1097                if is_generating {
1098                    return div()
1099                        .w(rems(6.5625)) // Arbitrary 105px size—so the label doesn't dance around
1100                        .child(AnimatedLabel::new("Generating"))
1101                        .into_any();
1102                }
1103
1104                let is_empty = agent_diff.read(cx).multibuffer.read(cx).is_empty();
1105                if is_empty {
1106                    return Empty.into_any();
1107                }
1108
1109                let focus_handle = agent_diff.focus_handle(cx);
1110
1111                h_group_xl()
1112                    .my_neg_1()
1113                    .items_center()
1114                    .p_1()
1115                    .flex_wrap()
1116                    .justify_between()
1117                    .child(
1118                        h_group_sm()
1119                            .child(
1120                                Button::new("reject-all", "Reject All")
1121                                    .key_binding({
1122                                        KeyBinding::for_action_in(
1123                                            &RejectAll,
1124                                            &focus_handle,
1125                                            window,
1126                                            cx,
1127                                        )
1128                                        .map(|kb| kb.size(rems_from_px(12.)))
1129                                    })
1130                                    .on_click(cx.listener(|this, _, window, cx| {
1131                                        this.dispatch_action(&RejectAll, window, cx)
1132                                    })),
1133                            )
1134                            .child(
1135                                Button::new("keep-all", "Keep All")
1136                                    .key_binding({
1137                                        KeyBinding::for_action_in(
1138                                            &KeepAll,
1139                                            &focus_handle,
1140                                            window,
1141                                            cx,
1142                                        )
1143                                        .map(|kb| kb.size(rems_from_px(12.)))
1144                                    })
1145                                    .on_click(cx.listener(|this, _, window, cx| {
1146                                        this.dispatch_action(&KeepAll, window, cx)
1147                                    })),
1148                            ),
1149                    )
1150                    .into_any()
1151            }
1152        }
1153    }
1154}
1155
1156#[derive(Default)]
1157pub struct AgentDiff {
1158    reviewing_editors: HashMap<WeakEntity<Editor>, EditorState>,
1159    workspace_threads: HashMap<WeakEntity<Workspace>, WorkspaceThread>,
1160}
1161
1162#[derive(Clone, Debug, PartialEq, Eq)]
1163enum EditorState {
1164    Idle,
1165    Reviewing,
1166    Generating,
1167}
1168
1169struct WorkspaceThread {
1170    thread: WeakEntity<Thread>,
1171    _thread_subscriptions: [Subscription; 2],
1172    singleton_editors: HashMap<WeakEntity<Buffer>, HashMap<WeakEntity<Editor>, Subscription>>,
1173    _settings_subscription: Subscription,
1174    _workspace_subscription: Option<Subscription>,
1175}
1176
1177struct AgentDiffGlobal(Entity<AgentDiff>);
1178
1179impl Global for AgentDiffGlobal {}
1180
1181impl AgentDiff {
1182    fn global(cx: &mut App) -> Entity<Self> {
1183        cx.try_global::<AgentDiffGlobal>()
1184            .map(|global| global.0.clone())
1185            .unwrap_or_else(|| {
1186                let entity = cx.new(|_cx| Self::default());
1187                let global = AgentDiffGlobal(entity.clone());
1188                cx.set_global(global);
1189                entity.clone()
1190            })
1191    }
1192
1193    pub fn set_active_thread(
1194        workspace: &WeakEntity<Workspace>,
1195        thread: &Entity<Thread>,
1196        window: &mut Window,
1197        cx: &mut App,
1198    ) {
1199        Self::global(cx).update(cx, |this, cx| {
1200            this.register_active_thread_impl(workspace, thread, window, cx);
1201        });
1202    }
1203
1204    fn register_active_thread_impl(
1205        &mut self,
1206        workspace: &WeakEntity<Workspace>,
1207        thread: &Entity<Thread>,
1208        window: &mut Window,
1209        cx: &mut Context<Self>,
1210    ) {
1211        let action_log = thread.read(cx).action_log().clone();
1212
1213        let action_log_subscription = cx.observe_in(&action_log, window, {
1214            let workspace = workspace.clone();
1215            move |this, _action_log, window, cx| {
1216                this.update_reviewing_editors(&workspace, window, cx);
1217            }
1218        });
1219
1220        let thread_subscription = cx.subscribe_in(&thread, window, {
1221            let workspace = workspace.clone();
1222            move |this, _thread, event, window, cx| {
1223                this.handle_thread_event(&workspace, event, window, cx)
1224            }
1225        });
1226
1227        if let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) {
1228            // replace thread and action log subscription, but keep editors
1229            workspace_thread.thread = thread.downgrade();
1230            workspace_thread._thread_subscriptions = [action_log_subscription, thread_subscription];
1231            self.update_reviewing_editors(&workspace, window, cx);
1232            return;
1233        }
1234
1235        let settings_subscription = cx.observe_global_in::<SettingsStore>(window, {
1236            let workspace = workspace.clone();
1237            let mut was_active = AssistantSettings::get_global(cx).single_file_review;
1238            move |this, window, cx| {
1239                let is_active = AssistantSettings::get_global(cx).single_file_review;
1240                if was_active != is_active {
1241                    was_active = is_active;
1242                    this.update_reviewing_editors(&workspace, window, cx);
1243                }
1244            }
1245        });
1246
1247        let workspace_subscription = workspace
1248            .upgrade()
1249            .map(|workspace| cx.subscribe_in(&workspace, window, Self::handle_workspace_event));
1250
1251        self.workspace_threads.insert(
1252            workspace.clone(),
1253            WorkspaceThread {
1254                thread: thread.downgrade(),
1255                _thread_subscriptions: [action_log_subscription, thread_subscription],
1256                singleton_editors: HashMap::default(),
1257                _settings_subscription: settings_subscription,
1258                _workspace_subscription: workspace_subscription,
1259            },
1260        );
1261
1262        let workspace = workspace.clone();
1263        cx.defer_in(window, move |this, window, cx| {
1264            if let Some(workspace) = workspace.upgrade() {
1265                this.register_workspace(workspace, window, cx);
1266            }
1267        });
1268    }
1269
1270    fn register_workspace(
1271        &mut self,
1272        workspace: Entity<Workspace>,
1273        window: &mut Window,
1274        cx: &mut Context<Self>,
1275    ) {
1276        let agent_diff = cx.entity();
1277
1278        let editors = workspace.update(cx, |workspace, cx| {
1279            let agent_diff = agent_diff.clone();
1280
1281            Self::register_review_action::<Keep>(workspace, Self::keep, &agent_diff);
1282            Self::register_review_action::<Reject>(workspace, Self::reject, &agent_diff);
1283            Self::register_review_action::<KeepAll>(workspace, Self::keep_all, &agent_diff);
1284            Self::register_review_action::<RejectAll>(workspace, Self::reject_all, &agent_diff);
1285
1286            workspace.items_of_type(cx).collect::<Vec<_>>()
1287        });
1288
1289        let weak_workspace = workspace.downgrade();
1290
1291        for editor in editors {
1292            if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1293                self.register_editor(weak_workspace.clone(), buffer, editor, window, cx);
1294            };
1295        }
1296
1297        self.update_reviewing_editors(&weak_workspace, window, cx);
1298    }
1299
1300    fn register_review_action<T: Action>(
1301        workspace: &mut Workspace,
1302        review: impl Fn(&Entity<Editor>, &Entity<Thread>, &mut Window, &mut App) -> PostReviewState
1303        + 'static,
1304        this: &Entity<AgentDiff>,
1305    ) {
1306        let this = this.clone();
1307        workspace.register_action(move |workspace, _: &T, window, cx| {
1308            let review = &review;
1309            let task = this.update(cx, |this, cx| {
1310                this.review_in_active_editor(workspace, review, window, cx)
1311            });
1312
1313            if let Some(task) = task {
1314                task.detach_and_log_err(cx);
1315            } else {
1316                cx.propagate();
1317            }
1318        });
1319    }
1320
1321    fn handle_thread_event(
1322        &mut self,
1323        workspace: &WeakEntity<Workspace>,
1324        event: &ThreadEvent,
1325        window: &mut Window,
1326        cx: &mut Context<Self>,
1327    ) {
1328        match event {
1329            ThreadEvent::NewRequest
1330            | ThreadEvent::Stopped(Ok(StopReason::EndTurn))
1331            | ThreadEvent::Stopped(Ok(StopReason::MaxTokens))
1332            | ThreadEvent::Stopped(Err(_))
1333            | ThreadEvent::ShowError(_)
1334            | ThreadEvent::CompletionCanceled => {
1335                self.update_reviewing_editors(workspace, window, cx);
1336            }
1337            // intentionally being exhaustive in case we add a variant we should handle
1338            ThreadEvent::Stopped(Ok(StopReason::ToolUse))
1339            | ThreadEvent::UsageUpdated(_)
1340            | ThreadEvent::StreamedCompletion
1341            | ThreadEvent::ReceivedTextChunk
1342            | ThreadEvent::StreamedAssistantText(_, _)
1343            | ThreadEvent::StreamedAssistantThinking(_, _)
1344            | ThreadEvent::StreamedToolUse { .. }
1345            | ThreadEvent::InvalidToolInput { .. }
1346            | ThreadEvent::MessageAdded(_)
1347            | ThreadEvent::MessageEdited(_)
1348            | ThreadEvent::MessageDeleted(_)
1349            | ThreadEvent::SummaryGenerated
1350            | ThreadEvent::SummaryChanged
1351            | ThreadEvent::UsePendingTools { .. }
1352            | ThreadEvent::ToolFinished { .. }
1353            | ThreadEvent::CheckpointChanged
1354            | ThreadEvent::ToolConfirmationNeeded
1355            | ThreadEvent::CancelEditing => {}
1356        }
1357    }
1358
1359    fn handle_workspace_event(
1360        &mut self,
1361        workspace: &Entity<Workspace>,
1362        event: &workspace::Event,
1363        window: &mut Window,
1364        cx: &mut Context<Self>,
1365    ) {
1366        match event {
1367            workspace::Event::ItemAdded { item } => {
1368                if let Some(editor) = item.downcast::<Editor>() {
1369                    if let Some(buffer) = Self::full_editor_buffer(editor.read(cx), cx) {
1370                        self.register_editor(
1371                            workspace.downgrade(),
1372                            buffer.clone(),
1373                            editor,
1374                            window,
1375                            cx,
1376                        );
1377                    }
1378                }
1379            }
1380            _ => {}
1381        }
1382    }
1383
1384    fn full_editor_buffer(editor: &Editor, cx: &App) -> Option<WeakEntity<Buffer>> {
1385        if editor.mode().is_full() {
1386            editor
1387                .buffer()
1388                .read(cx)
1389                .as_singleton()
1390                .map(|buffer| buffer.downgrade())
1391        } else {
1392            None
1393        }
1394    }
1395
1396    fn register_editor(
1397        &mut self,
1398        workspace: WeakEntity<Workspace>,
1399        buffer: WeakEntity<Buffer>,
1400        editor: Entity<Editor>,
1401        window: &mut Window,
1402        cx: &mut Context<Self>,
1403    ) {
1404        let Some(workspace_thread) = self.workspace_threads.get_mut(&workspace) else {
1405            return;
1406        };
1407
1408        let weak_editor = editor.downgrade();
1409
1410        workspace_thread
1411            .singleton_editors
1412            .entry(buffer.clone())
1413            .or_default()
1414            .entry(weak_editor.clone())
1415            .or_insert_with(|| {
1416                let workspace = workspace.clone();
1417                cx.observe_release(&editor, move |this, _, _cx| {
1418                    let Some(active_thread) = this.workspace_threads.get_mut(&workspace) else {
1419                        return;
1420                    };
1421
1422                    if let Entry::Occupied(mut entry) =
1423                        active_thread.singleton_editors.entry(buffer)
1424                    {
1425                        let set = entry.get_mut();
1426                        set.remove(&weak_editor);
1427
1428                        if set.is_empty() {
1429                            entry.remove();
1430                        }
1431                    }
1432                })
1433            });
1434
1435        self.update_reviewing_editors(&workspace, window, cx);
1436    }
1437
1438    fn update_reviewing_editors(
1439        &mut self,
1440        workspace: &WeakEntity<Workspace>,
1441        window: &mut Window,
1442        cx: &mut Context<Self>,
1443    ) {
1444        if !AssistantSettings::get_global(cx).single_file_review {
1445            for (editor, _) in self.reviewing_editors.drain() {
1446                editor
1447                    .update(cx, |editor, cx| editor.end_temporary_diff_override(cx))
1448                    .ok();
1449            }
1450            return;
1451        }
1452
1453        let Some(workspace_thread) = self.workspace_threads.get_mut(workspace) else {
1454            return;
1455        };
1456
1457        let Some(thread) = workspace_thread.thread.upgrade() else {
1458            return;
1459        };
1460
1461        let action_log = thread.read(cx).action_log();
1462        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1463
1464        let mut unaffected = self.reviewing_editors.clone();
1465
1466        for (buffer, diff_handle) in changed_buffers {
1467            if buffer.read(cx).file().is_none() {
1468                continue;
1469            }
1470
1471            let Some(buffer_editors) = workspace_thread.singleton_editors.get(&buffer.downgrade())
1472            else {
1473                continue;
1474            };
1475
1476            for (weak_editor, _) in buffer_editors {
1477                let Some(editor) = weak_editor.upgrade() else {
1478                    continue;
1479                };
1480
1481                let multibuffer = editor.read(cx).buffer().clone();
1482                multibuffer.update(cx, |multibuffer, cx| {
1483                    multibuffer.add_diff(diff_handle.clone(), cx);
1484                });
1485
1486                let new_state = if thread.read(cx).is_generating() {
1487                    EditorState::Generating
1488                } else {
1489                    EditorState::Reviewing
1490                };
1491
1492                let previous_state = self
1493                    .reviewing_editors
1494                    .insert(weak_editor.clone(), new_state.clone());
1495
1496                if previous_state.is_none() {
1497                    editor.update(cx, |editor, cx| {
1498                        editor.start_temporary_diff_override();
1499                        editor.set_render_diff_hunk_controls(diff_hunk_controls(&thread), cx);
1500                        editor.set_expand_all_diff_hunks(cx);
1501                        editor.register_addon(EditorAgentDiffAddon);
1502                    });
1503                } else {
1504                    unaffected.remove(&weak_editor);
1505                }
1506
1507                if new_state == EditorState::Reviewing && previous_state != Some(new_state) {
1508                    // Jump to first hunk when we enter review mode
1509                    editor.update(cx, |editor, cx| {
1510                        let snapshot = multibuffer.read(cx).snapshot(cx);
1511                        if let Some(first_hunk) = snapshot.diff_hunks().next() {
1512                            let first_hunk_start = first_hunk.multi_buffer_range().start;
1513
1514                            editor.change_selections(
1515                                Some(Autoscroll::center()),
1516                                window,
1517                                cx,
1518                                |selections| {
1519                                    selections.select_ranges([first_hunk_start..first_hunk_start])
1520                                },
1521                            );
1522                        }
1523                    });
1524                }
1525            }
1526        }
1527
1528        // Remove editors from this workspace that are no longer under review
1529        for (editor, _) in unaffected {
1530            // Note: We could avoid this check by storing `reviewing_editors` by Workspace,
1531            // but that would add another lookup in `AgentDiff::editor_state`
1532            // which gets called much more frequently.
1533            let in_workspace = editor
1534                .read_with(cx, |editor, _cx| editor.workspace())
1535                .ok()
1536                .flatten()
1537                .map_or(false, |editor_workspace| {
1538                    editor_workspace.entity_id() == workspace.entity_id()
1539                });
1540
1541            if in_workspace {
1542                editor
1543                    .update(cx, |editor, cx| editor.end_temporary_diff_override(cx))
1544                    .ok();
1545                self.reviewing_editors.remove(&editor);
1546            }
1547        }
1548
1549        cx.notify();
1550    }
1551
1552    fn editor_state(&self, editor: &Entity<Editor>) -> &EditorState {
1553        self.reviewing_editors
1554            .get(&editor.downgrade())
1555            .unwrap_or(&EditorState::Idle)
1556    }
1557
1558    fn deploy_pane_from_editor(&self, editor: &Entity<Editor>, window: &mut Window, cx: &mut App) {
1559        let Some(workspace) = editor.read(cx).workspace() else {
1560            return;
1561        };
1562
1563        let Some(WorkspaceThread { thread, .. }) =
1564            self.workspace_threads.get(&workspace.downgrade())
1565        else {
1566            return;
1567        };
1568
1569        let Some(thread) = thread.upgrade() else {
1570            return;
1571        };
1572
1573        AgentDiffPane::deploy(thread, workspace.downgrade(), window, cx).log_err();
1574    }
1575
1576    fn keep_all(
1577        editor: &Entity<Editor>,
1578        thread: &Entity<Thread>,
1579        window: &mut Window,
1580        cx: &mut App,
1581    ) -> PostReviewState {
1582        editor.update(cx, |editor, cx| {
1583            let snapshot = editor.buffer().read(cx).snapshot(cx);
1584            keep_edits_in_ranges(
1585                editor,
1586                &snapshot,
1587                thread,
1588                vec![editor::Anchor::min()..editor::Anchor::max()],
1589                window,
1590                cx,
1591            );
1592        });
1593        PostReviewState::AllReviewed
1594    }
1595
1596    fn reject_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            reject_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 keep(
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            keep_edits_in_selection(editor, &snapshot, thread, window, cx);
1625            Self::post_review_state(&snapshot)
1626        })
1627    }
1628
1629    fn reject(
1630        editor: &Entity<Editor>,
1631        thread: &Entity<Thread>,
1632        window: &mut Window,
1633        cx: &mut App,
1634    ) -> PostReviewState {
1635        editor.update(cx, |editor, cx| {
1636            let snapshot = editor.buffer().read(cx).snapshot(cx);
1637            reject_edits_in_selection(editor, &snapshot, thread, window, cx);
1638            Self::post_review_state(&snapshot)
1639        })
1640    }
1641
1642    fn post_review_state(snapshot: &MultiBufferSnapshot) -> PostReviewState {
1643        for (i, _) in snapshot.diff_hunks().enumerate() {
1644            if i > 0 {
1645                return PostReviewState::Pending;
1646            }
1647        }
1648        PostReviewState::AllReviewed
1649    }
1650
1651    fn review_in_active_editor(
1652        &mut self,
1653        workspace: &mut Workspace,
1654        review: impl Fn(&Entity<Editor>, &Entity<Thread>, &mut Window, &mut App) -> PostReviewState,
1655        window: &mut Window,
1656        cx: &mut Context<Self>,
1657    ) -> Option<Task<Result<()>>> {
1658        let active_item = workspace.active_item(cx)?;
1659        let editor = active_item.act_as::<Editor>(cx)?;
1660
1661        if !matches!(self.editor_state(&editor), EditorState::Reviewing) {
1662            return None;
1663        }
1664
1665        let WorkspaceThread { thread, .. } =
1666            self.workspace_threads.get(&workspace.weak_handle())?;
1667
1668        let thread = thread.upgrade()?;
1669
1670        if let PostReviewState::AllReviewed = review(&editor, &thread, window, cx) {
1671            if let Some(curr_buffer) = editor.read(cx).buffer().read(cx).as_singleton() {
1672                let changed_buffers = thread.read(cx).action_log().read(cx).changed_buffers(cx);
1673
1674                let mut keys = changed_buffers.keys().cycle();
1675                keys.find(|k| *k == &curr_buffer);
1676                let next_project_path = keys
1677                    .next()
1678                    .filter(|k| *k != &curr_buffer)
1679                    .and_then(|after| after.read(cx).project_path(cx));
1680
1681                if let Some(path) = next_project_path {
1682                    let task = workspace.open_path(path, None, true, window, cx);
1683                    let task = cx.spawn(async move |_, _cx| task.await.map(|_| ()));
1684                    return Some(task);
1685                }
1686            }
1687        }
1688
1689        return Some(Task::ready(Ok(())));
1690    }
1691}
1692
1693enum PostReviewState {
1694    AllReviewed,
1695    Pending,
1696}
1697
1698pub struct EditorAgentDiffAddon;
1699
1700impl editor::Addon for EditorAgentDiffAddon {
1701    fn to_any(&self) -> &dyn std::any::Any {
1702        self
1703    }
1704
1705    fn extend_key_context(&self, key_context: &mut gpui::KeyContext, _: &App) {
1706        key_context.add("agent_diff");
1707        key_context.add("editor_agent_diff");
1708    }
1709}
1710
1711#[cfg(test)]
1712mod tests {
1713    use super::*;
1714    use crate::{Keep, ThreadStore, thread_store};
1715    use assistant_settings::AssistantSettings;
1716    use assistant_tool::ToolWorkingSet;
1717    use context_server::ContextServerSettings;
1718    use editor::EditorSettings;
1719    use gpui::TestAppContext;
1720    use project::{FakeFs, Project};
1721    use prompt_store::PromptBuilder;
1722    use serde_json::json;
1723    use settings::{Settings, SettingsStore};
1724    use std::sync::Arc;
1725    use theme::ThemeSettings;
1726    use util::path;
1727
1728    #[gpui::test]
1729    async fn test_multibuffer_agent_diff(cx: &mut TestAppContext) {
1730        cx.update(|cx| {
1731            let settings_store = SettingsStore::test(cx);
1732            cx.set_global(settings_store);
1733            language::init(cx);
1734            Project::init_settings(cx);
1735            AssistantSettings::register(cx);
1736            prompt_store::init(cx);
1737            thread_store::init(cx);
1738            workspace::init_settings(cx);
1739            ThemeSettings::register(cx);
1740            ContextServerSettings::register(cx);
1741            EditorSettings::register(cx);
1742            language_model::init_settings(cx);
1743        });
1744
1745        let fs = FakeFs::new(cx.executor());
1746        fs.insert_tree(
1747            path!("/test"),
1748            json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1749        )
1750        .await;
1751        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1752        let buffer_path = project
1753            .read_with(cx, |project, cx| {
1754                project.find_project_path("test/file1", cx)
1755            })
1756            .unwrap();
1757
1758        let prompt_store = None;
1759        let thread_store = cx
1760            .update(|cx| {
1761                ThreadStore::load(
1762                    project.clone(),
1763                    cx.new(|_| ToolWorkingSet::default()),
1764                    prompt_store,
1765                    Arc::new(PromptBuilder::new(None).unwrap()),
1766                    cx,
1767                )
1768            })
1769            .await
1770            .unwrap();
1771        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
1772        let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
1773
1774        let (workspace, cx) =
1775            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1776        let agent_diff = cx.new_window_entity(|window, cx| {
1777            AgentDiffPane::new(thread.clone(), workspace.downgrade(), window, cx)
1778        });
1779        let editor = agent_diff.read_with(cx, |diff, _cx| diff.editor.clone());
1780
1781        let buffer = project
1782            .update(cx, |project, cx| project.open_buffer(buffer_path, cx))
1783            .await
1784            .unwrap();
1785        cx.update(|_, cx| {
1786            action_log.update(cx, |log, cx| log.track_buffer(buffer.clone(), cx));
1787            buffer.update(cx, |buffer, cx| {
1788                buffer
1789                    .edit(
1790                        [
1791                            (Point::new(1, 1)..Point::new(1, 2), "E"),
1792                            (Point::new(3, 2)..Point::new(3, 3), "L"),
1793                            (Point::new(5, 0)..Point::new(5, 1), "P"),
1794                            (Point::new(7, 1)..Point::new(7, 2), "W"),
1795                        ],
1796                        None,
1797                        cx,
1798                    )
1799                    .unwrap()
1800            });
1801            action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
1802        });
1803        cx.run_until_parked();
1804
1805        // When opening the assistant diff, the cursor is positioned on the first hunk.
1806        assert_eq!(
1807            editor.read_with(cx, |editor, cx| editor.text(cx)),
1808            "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1809        );
1810        assert_eq!(
1811            editor
1812                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1813                .range(),
1814            Point::new(1, 0)..Point::new(1, 0)
1815        );
1816
1817        // After keeping a hunk, the cursor should be positioned on the second hunk.
1818        agent_diff.update_in(cx, |diff, window, cx| diff.keep(&Keep, window, cx));
1819        cx.run_until_parked();
1820        assert_eq!(
1821            editor.read_with(cx, |editor, cx| editor.text(cx)),
1822            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
1823        );
1824        assert_eq!(
1825            editor
1826                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
1827                .range(),
1828            Point::new(3, 0)..Point::new(3, 0)
1829        );
1830
1831        // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
1832        editor.update_in(cx, |editor, window, cx| {
1833            editor.change_selections(None, window, cx, |selections| {
1834                selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
1835            });
1836        });
1837        agent_diff.update_in(cx, |diff, window, cx| {
1838            diff.reject(&crate::Reject, window, cx)
1839        });
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\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        // Keeping a range that doesn't intersect the current selection doesn't move it.
1853        agent_diff.update_in(cx, |_diff, window, cx| {
1854            let position = editor
1855                .read(cx)
1856                .buffer()
1857                .read(cx)
1858                .read(cx)
1859                .anchor_before(Point::new(7, 0));
1860            editor.update(cx, |editor, cx| {
1861                let snapshot = editor.buffer().read(cx).snapshot(cx);
1862                keep_edits_in_ranges(
1863                    editor,
1864                    &snapshot,
1865                    &thread,
1866                    vec![position..position],
1867                    window,
1868                    cx,
1869                )
1870            });
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\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
1885    #[gpui::test]
1886    async fn test_singleton_agent_diff(cx: &mut TestAppContext) {
1887        cx.update(|cx| {
1888            let settings_store = SettingsStore::test(cx);
1889            cx.set_global(settings_store);
1890            language::init(cx);
1891            Project::init_settings(cx);
1892            AssistantSettings::register(cx);
1893            prompt_store::init(cx);
1894            thread_store::init(cx);
1895            workspace::init_settings(cx);
1896            ThemeSettings::register(cx);
1897            ContextServerSettings::register(cx);
1898            EditorSettings::register(cx);
1899            language_model::init_settings(cx);
1900            workspace::register_project_item::<Editor>(cx);
1901        });
1902
1903        let fs = FakeFs::new(cx.executor());
1904        fs.insert_tree(
1905            path!("/test"),
1906            json!({"file1": "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz"}),
1907        )
1908        .await;
1909        fs.insert_tree(path!("/test"), json!({"file2": "abc\ndef\nghi"}))
1910            .await;
1911
1912        let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
1913        let buffer_path1 = project
1914            .read_with(cx, |project, cx| {
1915                project.find_project_path("test/file1", cx)
1916            })
1917            .unwrap();
1918        let buffer_path2 = project
1919            .read_with(cx, |project, cx| {
1920                project.find_project_path("test/file2", cx)
1921            })
1922            .unwrap();
1923
1924        let prompt_store = None;
1925        let thread_store = cx
1926            .update(|cx| {
1927                ThreadStore::load(
1928                    project.clone(),
1929                    cx.new(|_| ToolWorkingSet::default()),
1930                    prompt_store,
1931                    Arc::new(PromptBuilder::new(None).unwrap()),
1932                    cx,
1933                )
1934            })
1935            .await
1936            .unwrap();
1937        let thread = thread_store.update(cx, |store, cx| store.create_thread(cx));
1938        let action_log = thread.read_with(cx, |thread, _| thread.action_log().clone());
1939
1940        let (workspace, cx) =
1941            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1942
1943        // Set the active thread
1944        cx.update(|window, cx| {
1945            AgentDiff::set_active_thread(&workspace.downgrade(), &thread, window, cx)
1946        });
1947
1948        let buffer1 = project
1949            .update(cx, |project, cx| {
1950                project.open_buffer(buffer_path1.clone(), cx)
1951            })
1952            .await
1953            .unwrap();
1954        let buffer2 = project
1955            .update(cx, |project, cx| {
1956                project.open_buffer(buffer_path2.clone(), cx)
1957            })
1958            .await
1959            .unwrap();
1960
1961        // Open an editor for buffer1
1962        let editor1 = cx.new_window_entity(|window, cx| {
1963            Editor::for_buffer(buffer1.clone(), Some(project.clone()), window, cx)
1964        });
1965
1966        workspace.update_in(cx, |workspace, window, cx| {
1967            workspace.add_item_to_active_pane(Box::new(editor1.clone()), None, true, window, cx);
1968        });
1969        cx.run_until_parked();
1970
1971        // Make changes
1972        cx.update(|_, cx| {
1973            action_log.update(cx, |log, cx| log.track_buffer(buffer1.clone(), cx));
1974            buffer1.update(cx, |buffer, cx| {
1975                buffer
1976                    .edit(
1977                        [
1978                            (Point::new(1, 1)..Point::new(1, 2), "E"),
1979                            (Point::new(3, 2)..Point::new(3, 3), "L"),
1980                            (Point::new(5, 0)..Point::new(5, 1), "P"),
1981                            (Point::new(7, 1)..Point::new(7, 2), "W"),
1982                        ],
1983                        None,
1984                        cx,
1985                    )
1986                    .unwrap()
1987            });
1988            action_log.update(cx, |log, cx| log.buffer_edited(buffer1.clone(), cx));
1989
1990            action_log.update(cx, |log, cx| log.track_buffer(buffer2.clone(), cx));
1991            buffer2.update(cx, |buffer, cx| {
1992                buffer
1993                    .edit(
1994                        [
1995                            (Point::new(0, 0)..Point::new(0, 1), "A"),
1996                            (Point::new(2, 1)..Point::new(2, 2), "H"),
1997                        ],
1998                        None,
1999                        cx,
2000                    )
2001                    .unwrap();
2002            });
2003            action_log.update(cx, |log, cx| log.buffer_edited(buffer2.clone(), cx));
2004        });
2005        cx.run_until_parked();
2006
2007        // The already opened editor displays the diff and the cursor is at the first hunk
2008        assert_eq!(
2009            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2010            "abc\ndef\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2011        );
2012        assert_eq!(
2013            editor1
2014                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2015                .range(),
2016            Point::new(1, 0)..Point::new(1, 0)
2017        );
2018
2019        // After keeping a hunk, the cursor should be positioned on the second hunk.
2020        workspace.update(cx, |_, cx| {
2021            cx.dispatch_action(&Keep);
2022        });
2023        cx.run_until_parked();
2024        assert_eq!(
2025            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2026            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nvWx\nyz"
2027        );
2028        assert_eq!(
2029            editor1
2030                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2031                .range(),
2032            Point::new(3, 0)..Point::new(3, 0)
2033        );
2034
2035        // Rejecting a hunk also moves the cursor to the next hunk, possibly cycling if it's at the end.
2036        editor1.update_in(cx, |editor, window, cx| {
2037            editor.change_selections(None, window, cx, |selections| {
2038                selections.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
2039            });
2040        });
2041        workspace.update(cx, |_, cx| {
2042            cx.dispatch_action(&Reject);
2043        });
2044        cx.run_until_parked();
2045        assert_eq!(
2046            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2047            "abc\ndEf\nghi\njkl\njkL\nmno\npqr\nPqr\nstu\nvwx\nyz"
2048        );
2049        assert_eq!(
2050            editor1
2051                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2052                .range(),
2053            Point::new(3, 0)..Point::new(3, 0)
2054        );
2055
2056        // Keeping a range that doesn't intersect the current selection doesn't move it.
2057        editor1.update_in(cx, |editor, window, cx| {
2058            let buffer = editor.buffer().read(cx);
2059            let position = buffer.read(cx).anchor_before(Point::new(7, 0));
2060            let snapshot = buffer.snapshot(cx);
2061            keep_edits_in_ranges(
2062                editor,
2063                &snapshot,
2064                &thread,
2065                vec![position..position],
2066                window,
2067                cx,
2068            )
2069        });
2070        cx.run_until_parked();
2071        assert_eq!(
2072            editor1.read_with(cx, |editor, cx| editor.text(cx)),
2073            "abc\ndEf\nghi\njkl\njkL\nmno\nPqr\nstu\nvwx\nyz"
2074        );
2075        assert_eq!(
2076            editor1
2077                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2078                .range(),
2079            Point::new(3, 0)..Point::new(3, 0)
2080        );
2081
2082        // Reviewing the last change opens the next changed buffer
2083        workspace
2084            .update_in(cx, |workspace, window, cx| {
2085                AgentDiff::global(cx).update(cx, |agent_diff, cx| {
2086                    agent_diff.review_in_active_editor(workspace, AgentDiff::keep, window, cx)
2087                })
2088            })
2089            .unwrap()
2090            .await
2091            .unwrap();
2092
2093        cx.run_until_parked();
2094
2095        let editor2 = workspace.update(cx, |workspace, cx| {
2096            workspace.active_item_as::<Editor>(cx).unwrap()
2097        });
2098
2099        let editor2_path = editor2
2100            .read_with(cx, |editor, cx| editor.project_path(cx))
2101            .unwrap();
2102        assert_eq!(editor2_path, buffer_path2);
2103
2104        assert_eq!(
2105            editor2.read_with(cx, |editor, cx| editor.text(cx)),
2106            "abc\nAbc\ndef\nghi\ngHi"
2107        );
2108        assert_eq!(
2109            editor2
2110                .update(cx, |editor, cx| editor.selections.newest::<Point>(cx))
2111                .range(),
2112            Point::new(0, 0)..Point::new(0, 0)
2113        );
2114    }
2115}